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
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
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
30 #include <linux/module.h>
31 #include <linux/nmi.h>
32 #include <linux/init.h>
33 #include <linux/uaccess.h>
34 #include <linux/highmem.h>
35 #include <linux/smp_lock.h>
36 #include <asm/mmu_context.h>
37 #include <linux/interrupt.h>
38 #include <linux/capability.h>
39 #include <linux/completion.h>
40 #include <linux/kernel_stat.h>
41 #include <linux/debug_locks.h>
42 #include <linux/perf_event.h>
43 #include <linux/security.h>
44 #include <linux/notifier.h>
45 #include <linux/profile.h>
46 #include <linux/freezer.h>
47 #include <linux/vmalloc.h>
48 #include <linux/blkdev.h>
49 #include <linux/delay.h>
50 #include <linux/pid_namespace.h>
51 #include <linux/smp.h>
52 #include <linux/threads.h>
53 #include <linux/timer.h>
54 #include <linux/rcupdate.h>
55 #include <linux/cpu.h>
56 #include <linux/cpuset.h>
57 #include <linux/percpu.h>
58 #include <linux/proc_fs.h>
59 #include <linux/seq_file.h>
60 #include <linux/stop_machine.h>
61 #include <linux/sysctl.h>
62 #include <linux/syscalls.h>
63 #include <linux/times.h>
64 #include <linux/tsacct_kern.h>
65 #include <linux/kprobes.h>
66 #include <linux/delayacct.h>
67 #include <linux/unistd.h>
68 #include <linux/pagemap.h>
69 #include <linux/hrtimer.h>
70 #include <linux/tick.h>
71 #include <linux/debugfs.h>
72 #include <linux/ctype.h>
73 #include <linux/ftrace.h>
74 #include <linux/slab.h>
77 #include <asm/irq_regs.h>
79 #include "sched_cpupri.h"
80 #include "workqueue_sched.h"
82 #define CREATE_TRACE_POINTS
83 #include <trace/events/sched.h>
86 * Convert user-nice values [ -20 ... 0 ... 19 ]
87 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
90 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
91 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
92 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
95 * 'User priority' is the nice value converted to something we
96 * can work with better when scaling various scheduler parameters,
97 * it's a [ 0 ... 39 ] range.
99 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
100 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
101 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
104 * Helpers for converting nanosecond timing to jiffy resolution
106 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
108 #define NICE_0_LOAD SCHED_LOAD_SCALE
109 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
112 * These are the 'tuning knobs' of the scheduler:
114 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
115 * Timeslices get refilled after they expire.
117 #define DEF_TIMESLICE (100 * HZ / 1000)
120 * single value that denotes runtime == period, ie unlimited time.
122 #define RUNTIME_INF ((u64)~0ULL)
124 static inline int rt_policy(int policy)
126 if (unlikely(policy == SCHED_FIFO || policy == SCHED_RR))
131 static inline int task_has_rt_policy(struct task_struct *p)
133 return rt_policy(p->policy);
137 * This is the priority-queue data structure of the RT scheduling class:
139 struct rt_prio_array {
140 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
141 struct list_head queue[MAX_RT_PRIO];
144 struct rt_bandwidth {
145 /* nests inside the rq lock: */
146 raw_spinlock_t rt_runtime_lock;
149 struct hrtimer rt_period_timer;
152 static struct rt_bandwidth def_rt_bandwidth;
154 static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
156 static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
158 struct rt_bandwidth *rt_b =
159 container_of(timer, struct rt_bandwidth, rt_period_timer);
165 now = hrtimer_cb_get_time(timer);
166 overrun = hrtimer_forward(timer, now, rt_b->rt_period);
171 idle = do_sched_rt_period_timer(rt_b, overrun);
174 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
178 void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
180 rt_b->rt_period = ns_to_ktime(period);
181 rt_b->rt_runtime = runtime;
183 raw_spin_lock_init(&rt_b->rt_runtime_lock);
185 hrtimer_init(&rt_b->rt_period_timer,
186 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
187 rt_b->rt_period_timer.function = sched_rt_period_timer;
190 static inline int rt_bandwidth_enabled(void)
192 return sysctl_sched_rt_runtime >= 0;
195 static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
199 if (!rt_bandwidth_enabled() || rt_b->rt_runtime == RUNTIME_INF)
202 if (hrtimer_active(&rt_b->rt_period_timer))
205 raw_spin_lock(&rt_b->rt_runtime_lock);
210 if (hrtimer_active(&rt_b->rt_period_timer))
213 now = hrtimer_cb_get_time(&rt_b->rt_period_timer);
214 hrtimer_forward(&rt_b->rt_period_timer, now, rt_b->rt_period);
216 soft = hrtimer_get_softexpires(&rt_b->rt_period_timer);
217 hard = hrtimer_get_expires(&rt_b->rt_period_timer);
218 delta = ktime_to_ns(ktime_sub(hard, soft));
219 __hrtimer_start_range_ns(&rt_b->rt_period_timer, soft, delta,
220 HRTIMER_MODE_ABS_PINNED, 0);
222 raw_spin_unlock(&rt_b->rt_runtime_lock);
225 #ifdef CONFIG_RT_GROUP_SCHED
226 static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
228 hrtimer_cancel(&rt_b->rt_period_timer);
233 * sched_domains_mutex serializes calls to arch_init_sched_domains,
234 * detach_destroy_domains and partition_sched_domains.
236 static DEFINE_MUTEX(sched_domains_mutex);
238 #ifdef CONFIG_CGROUP_SCHED
240 #include <linux/cgroup.h>
244 static LIST_HEAD(task_groups);
246 /* task group related information */
248 struct cgroup_subsys_state css;
250 #ifdef CONFIG_FAIR_GROUP_SCHED
251 /* schedulable entities of this group on each cpu */
252 struct sched_entity **se;
253 /* runqueue "owned" by this group on each cpu */
254 struct cfs_rq **cfs_rq;
255 unsigned long shares;
257 atomic_t load_weight;
260 #ifdef CONFIG_RT_GROUP_SCHED
261 struct sched_rt_entity **rt_se;
262 struct rt_rq **rt_rq;
264 struct rt_bandwidth rt_bandwidth;
268 struct list_head list;
270 struct task_group *parent;
271 struct list_head siblings;
272 struct list_head children;
275 #define root_task_group init_task_group
277 /* task_group_lock serializes the addition/removal of task groups */
278 static DEFINE_SPINLOCK(task_group_lock);
280 #ifdef CONFIG_FAIR_GROUP_SCHED
282 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
285 * A weight of 0 or 1 can cause arithmetics problems.
286 * A weight of a cfs_rq is the sum of weights of which entities
287 * are queued on this cfs_rq, so a weight of a entity should not be
288 * too large, so as the shares value of a task group.
289 * (The default weight is 1024 - so there's no practical
290 * limitation from this.)
293 #define MAX_SHARES (1UL << 18)
295 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
298 /* Default task group.
299 * Every task in system belong to this group at bootup.
301 struct task_group init_task_group;
303 #endif /* CONFIG_CGROUP_SCHED */
305 /* CFS-related fields in a runqueue */
307 struct load_weight load;
308 unsigned long nr_running;
313 struct rb_root tasks_timeline;
314 struct rb_node *rb_leftmost;
316 struct list_head tasks;
317 struct list_head *balance_iterator;
320 * 'curr' points to currently running entity on this cfs_rq.
321 * It is set to NULL otherwise (i.e when none are currently running).
323 struct sched_entity *curr, *next, *last;
325 unsigned int nr_spread_over;
327 #ifdef CONFIG_FAIR_GROUP_SCHED
328 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
331 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
332 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
333 * (like users, containers etc.)
335 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
336 * list is used during load balance.
339 struct list_head leaf_cfs_rq_list;
340 struct task_group *tg; /* group that "owns" this runqueue */
344 * the part of load.weight contributed by tasks
346 unsigned long task_weight;
349 * h_load = weight * f(tg)
351 * Where f(tg) is the recursive weight fraction assigned to
354 unsigned long h_load;
357 * Maintaining per-cpu shares distribution for group scheduling
359 * load_stamp is the last time we updated the load average
360 * load_last is the last time we updated the load average and saw load
361 * load_unacc_exec_time is currently unaccounted execution time
365 u64 load_stamp, load_last, load_unacc_exec_time;
367 unsigned long load_contribution;
372 /* Real-Time classes' related field in a runqueue: */
374 struct rt_prio_array active;
375 unsigned long rt_nr_running;
376 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
378 int curr; /* highest queued rt task prio */
380 int next; /* next highest */
385 unsigned long rt_nr_migratory;
386 unsigned long rt_nr_total;
388 struct plist_head pushable_tasks;
393 /* Nests inside the rq lock: */
394 raw_spinlock_t rt_runtime_lock;
396 #ifdef CONFIG_RT_GROUP_SCHED
397 unsigned long rt_nr_boosted;
400 struct list_head leaf_rt_rq_list;
401 struct task_group *tg;
408 * We add the notion of a root-domain which will be used to define per-domain
409 * variables. Each exclusive cpuset essentially defines an island domain by
410 * fully partitioning the member cpus from any other cpuset. Whenever a new
411 * exclusive cpuset is created, we also create and attach a new root-domain
418 cpumask_var_t online;
421 * The "RT overload" flag: it gets set if a CPU has more than
422 * one runnable RT task.
424 cpumask_var_t rto_mask;
426 struct cpupri cpupri;
430 * By default the system creates a single root-domain with all cpus as
431 * members (mimicking the global state we have today).
433 static struct root_domain def_root_domain;
435 #endif /* CONFIG_SMP */
438 * This is the main, per-CPU runqueue data structure.
440 * Locking rule: those places that want to lock multiple runqueues
441 * (such as the load balancing or the thread migration code), lock
442 * acquire operations must be ordered by ascending &runqueue.
449 * nr_running and cpu_load should be in the same cacheline because
450 * remote CPUs use both these fields when doing load calculation.
452 unsigned long nr_running;
453 #define CPU_LOAD_IDX_MAX 5
454 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
455 unsigned long last_load_update_tick;
458 unsigned char nohz_balance_kick;
460 unsigned int skip_clock_update;
462 /* capture load from *all* tasks on this cpu: */
463 struct load_weight load;
464 unsigned long nr_load_updates;
470 #ifdef CONFIG_FAIR_GROUP_SCHED
471 /* list of leaf cfs_rq on this cpu: */
472 struct list_head leaf_cfs_rq_list;
474 #ifdef CONFIG_RT_GROUP_SCHED
475 struct list_head leaf_rt_rq_list;
479 * This is part of a global counter where only the total sum
480 * over all CPUs matters. A task can increase this counter on
481 * one CPU and if it got migrated afterwards it may decrease
482 * it on another CPU. Always updated under the runqueue lock:
484 unsigned long nr_uninterruptible;
486 struct task_struct *curr, *idle, *stop;
487 unsigned long next_balance;
488 struct mm_struct *prev_mm;
496 struct root_domain *rd;
497 struct sched_domain *sd;
499 unsigned long cpu_power;
501 unsigned char idle_at_tick;
502 /* For active balancing */
506 struct cpu_stop_work active_balance_work;
507 /* cpu of this runqueue: */
511 unsigned long avg_load_per_task;
519 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
523 /* calc_load related fields */
524 unsigned long calc_load_update;
525 long calc_load_active;
527 #ifdef CONFIG_SCHED_HRTICK
529 int hrtick_csd_pending;
530 struct call_single_data hrtick_csd;
532 struct hrtimer hrtick_timer;
535 #ifdef CONFIG_SCHEDSTATS
537 struct sched_info rq_sched_info;
538 unsigned long long rq_cpu_time;
539 /* could above be rq->cfs_rq.exec_clock + rq->rt_rq.rt_runtime ? */
541 /* sys_sched_yield() stats */
542 unsigned int yld_count;
544 /* schedule() stats */
545 unsigned int sched_switch;
546 unsigned int sched_count;
547 unsigned int sched_goidle;
549 /* try_to_wake_up() stats */
550 unsigned int ttwu_count;
551 unsigned int ttwu_local;
554 unsigned int bkl_count;
558 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
561 static void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags);
563 static inline int cpu_of(struct rq *rq)
572 #define rcu_dereference_check_sched_domain(p) \
573 rcu_dereference_check((p), \
574 rcu_read_lock_sched_held() || \
575 lockdep_is_held(&sched_domains_mutex))
578 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
579 * See detach_destroy_domains: synchronize_sched for details.
581 * The domain tree of any CPU may only be accessed from within
582 * preempt-disabled sections.
584 #define for_each_domain(cpu, __sd) \
585 for (__sd = rcu_dereference_check_sched_domain(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
587 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
588 #define this_rq() (&__get_cpu_var(runqueues))
589 #define task_rq(p) cpu_rq(task_cpu(p))
590 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
591 #define raw_rq() (&__raw_get_cpu_var(runqueues))
593 #ifdef CONFIG_CGROUP_SCHED
596 * Return the group to which this tasks belongs.
598 * We use task_subsys_state_check() and extend the RCU verification
599 * with lockdep_is_held(&task_rq(p)->lock) because cpu_cgroup_attach()
600 * holds that lock for each task it moves into the cgroup. Therefore
601 * by holding that lock, we pin the task to the current cgroup.
603 static inline struct task_group *task_group(struct task_struct *p)
605 struct cgroup_subsys_state *css;
607 css = task_subsys_state_check(p, cpu_cgroup_subsys_id,
608 lockdep_is_held(&task_rq(p)->lock));
609 return container_of(css, struct task_group, css);
612 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
613 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
615 #ifdef CONFIG_FAIR_GROUP_SCHED
616 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
617 p->se.parent = task_group(p)->se[cpu];
620 #ifdef CONFIG_RT_GROUP_SCHED
621 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
622 p->rt.parent = task_group(p)->rt_se[cpu];
626 #else /* CONFIG_CGROUP_SCHED */
628 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
629 static inline struct task_group *task_group(struct task_struct *p)
634 #endif /* CONFIG_CGROUP_SCHED */
636 static u64 irq_time_cpu(int cpu);
637 static void sched_irq_time_avg_update(struct rq *rq, u64 irq_time);
639 inline void update_rq_clock(struct rq *rq)
641 if (!rq->skip_clock_update) {
642 int cpu = cpu_of(rq);
645 rq->clock = sched_clock_cpu(cpu);
646 irq_time = irq_time_cpu(cpu);
647 if (rq->clock - irq_time > rq->clock_task)
648 rq->clock_task = rq->clock - irq_time;
650 sched_irq_time_avg_update(rq, irq_time);
655 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
657 #ifdef CONFIG_SCHED_DEBUG
658 # define const_debug __read_mostly
660 # define const_debug static const
665 * @cpu: the processor in question.
667 * Returns true if the current cpu runqueue is locked.
668 * This interface allows printk to be called with the runqueue lock
669 * held and know whether or not it is OK to wake up the klogd.
671 int runqueue_is_locked(int cpu)
673 return raw_spin_is_locked(&cpu_rq(cpu)->lock);
677 * Debugging: various feature bits
680 #define SCHED_FEAT(name, enabled) \
681 __SCHED_FEAT_##name ,
684 #include "sched_features.h"
689 #define SCHED_FEAT(name, enabled) \
690 (1UL << __SCHED_FEAT_##name) * enabled |
692 const_debug unsigned int sysctl_sched_features =
693 #include "sched_features.h"
698 #ifdef CONFIG_SCHED_DEBUG
699 #define SCHED_FEAT(name, enabled) \
702 static __read_mostly char *sched_feat_names[] = {
703 #include "sched_features.h"
709 static int sched_feat_show(struct seq_file *m, void *v)
713 for (i = 0; sched_feat_names[i]; i++) {
714 if (!(sysctl_sched_features & (1UL << i)))
716 seq_printf(m, "%s ", sched_feat_names[i]);
724 sched_feat_write(struct file *filp, const char __user *ubuf,
725 size_t cnt, loff_t *ppos)
735 if (copy_from_user(&buf, ubuf, cnt))
741 if (strncmp(buf, "NO_", 3) == 0) {
746 for (i = 0; sched_feat_names[i]; i++) {
747 if (strcmp(cmp, sched_feat_names[i]) == 0) {
749 sysctl_sched_features &= ~(1UL << i);
751 sysctl_sched_features |= (1UL << i);
756 if (!sched_feat_names[i])
764 static int sched_feat_open(struct inode *inode, struct file *filp)
766 return single_open(filp, sched_feat_show, NULL);
769 static const struct file_operations sched_feat_fops = {
770 .open = sched_feat_open,
771 .write = sched_feat_write,
774 .release = single_release,
777 static __init int sched_init_debug(void)
779 debugfs_create_file("sched_features", 0644, NULL, NULL,
784 late_initcall(sched_init_debug);
788 #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
791 * Number of tasks to iterate in a single balance run.
792 * Limited because this is done with IRQs disabled.
794 const_debug unsigned int sysctl_sched_nr_migrate = 32;
797 * period over which we average the RT time consumption, measured
802 const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
805 * period over which we measure -rt task cpu usage in us.
808 unsigned int sysctl_sched_rt_period = 1000000;
810 static __read_mostly int scheduler_running;
813 * part of the period that we allow rt tasks to run in us.
816 int sysctl_sched_rt_runtime = 950000;
818 static inline u64 global_rt_period(void)
820 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
823 static inline u64 global_rt_runtime(void)
825 if (sysctl_sched_rt_runtime < 0)
828 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
831 #ifndef prepare_arch_switch
832 # define prepare_arch_switch(next) do { } while (0)
834 #ifndef finish_arch_switch
835 # define finish_arch_switch(prev) do { } while (0)
838 static inline int task_current(struct rq *rq, struct task_struct *p)
840 return rq->curr == p;
843 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
844 static inline int task_running(struct rq *rq, struct task_struct *p)
846 return task_current(rq, p);
849 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
853 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
855 #ifdef CONFIG_DEBUG_SPINLOCK
856 /* this is a valid case when another task releases the spinlock */
857 rq->lock.owner = current;
860 * If we are tracking spinlock dependencies then we have to
861 * fix up the runqueue lock - which gets 'carried over' from
864 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
866 raw_spin_unlock_irq(&rq->lock);
869 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
870 static inline int task_running(struct rq *rq, struct task_struct *p)
875 return task_current(rq, p);
879 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
883 * We can optimise this out completely for !SMP, because the
884 * SMP rebalancing from interrupt is the only thing that cares
889 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
890 raw_spin_unlock_irq(&rq->lock);
892 raw_spin_unlock(&rq->lock);
896 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
900 * After ->oncpu is cleared, the task can be moved to a different CPU.
901 * We must ensure this doesn't happen until the switch is completely
907 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
911 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
914 * Check whether the task is waking, we use this to synchronize ->cpus_allowed
917 static inline int task_is_waking(struct task_struct *p)
919 return unlikely(p->state == TASK_WAKING);
923 * __task_rq_lock - lock the runqueue a given task resides on.
924 * Must be called interrupts disabled.
926 static inline struct rq *__task_rq_lock(struct task_struct *p)
933 raw_spin_lock(&rq->lock);
934 if (likely(rq == task_rq(p)))
936 raw_spin_unlock(&rq->lock);
941 * task_rq_lock - lock the runqueue a given task resides on and disable
942 * interrupts. Note the ordering: we can safely lookup the task_rq without
943 * explicitly disabling preemption.
945 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
951 local_irq_save(*flags);
953 raw_spin_lock(&rq->lock);
954 if (likely(rq == task_rq(p)))
956 raw_spin_unlock_irqrestore(&rq->lock, *flags);
960 static void __task_rq_unlock(struct rq *rq)
963 raw_spin_unlock(&rq->lock);
966 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
969 raw_spin_unlock_irqrestore(&rq->lock, *flags);
973 * this_rq_lock - lock this runqueue and disable interrupts.
975 static struct rq *this_rq_lock(void)
982 raw_spin_lock(&rq->lock);
987 #ifdef CONFIG_SCHED_HRTICK
989 * Use HR-timers to deliver accurate preemption points.
991 * Its all a bit involved since we cannot program an hrt while holding the
992 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
995 * When we get rescheduled we reprogram the hrtick_timer outside of the
1001 * - enabled by features
1002 * - hrtimer is actually high res
1004 static inline int hrtick_enabled(struct rq *rq)
1006 if (!sched_feat(HRTICK))
1008 if (!cpu_active(cpu_of(rq)))
1010 return hrtimer_is_hres_active(&rq->hrtick_timer);
1013 static void hrtick_clear(struct rq *rq)
1015 if (hrtimer_active(&rq->hrtick_timer))
1016 hrtimer_cancel(&rq->hrtick_timer);
1020 * High-resolution timer tick.
1021 * Runs from hardirq context with interrupts disabled.
1023 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1025 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1027 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1029 raw_spin_lock(&rq->lock);
1030 update_rq_clock(rq);
1031 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1032 raw_spin_unlock(&rq->lock);
1034 return HRTIMER_NORESTART;
1039 * called from hardirq (IPI) context
1041 static void __hrtick_start(void *arg)
1043 struct rq *rq = arg;
1045 raw_spin_lock(&rq->lock);
1046 hrtimer_restart(&rq->hrtick_timer);
1047 rq->hrtick_csd_pending = 0;
1048 raw_spin_unlock(&rq->lock);
1052 * Called to set the hrtick timer state.
1054 * called with rq->lock held and irqs disabled
1056 static void hrtick_start(struct rq *rq, u64 delay)
1058 struct hrtimer *timer = &rq->hrtick_timer;
1059 ktime_t time = ktime_add_ns(timer->base->get_time(), delay);
1061 hrtimer_set_expires(timer, time);
1063 if (rq == this_rq()) {
1064 hrtimer_restart(timer);
1065 } else if (!rq->hrtick_csd_pending) {
1066 __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0);
1067 rq->hrtick_csd_pending = 1;
1072 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
1074 int cpu = (int)(long)hcpu;
1077 case CPU_UP_CANCELED:
1078 case CPU_UP_CANCELED_FROZEN:
1079 case CPU_DOWN_PREPARE:
1080 case CPU_DOWN_PREPARE_FROZEN:
1082 case CPU_DEAD_FROZEN:
1083 hrtick_clear(cpu_rq(cpu));
1090 static __init void init_hrtick(void)
1092 hotcpu_notifier(hotplug_hrtick, 0);
1096 * Called to set the hrtick timer state.
1098 * called with rq->lock held and irqs disabled
1100 static void hrtick_start(struct rq *rq, u64 delay)
1102 __hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0,
1103 HRTIMER_MODE_REL_PINNED, 0);
1106 static inline void init_hrtick(void)
1109 #endif /* CONFIG_SMP */
1111 static void init_rq_hrtick(struct rq *rq)
1114 rq->hrtick_csd_pending = 0;
1116 rq->hrtick_csd.flags = 0;
1117 rq->hrtick_csd.func = __hrtick_start;
1118 rq->hrtick_csd.info = rq;
1121 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1122 rq->hrtick_timer.function = hrtick;
1124 #else /* CONFIG_SCHED_HRTICK */
1125 static inline void hrtick_clear(struct rq *rq)
1129 static inline void init_rq_hrtick(struct rq *rq)
1133 static inline void init_hrtick(void)
1136 #endif /* CONFIG_SCHED_HRTICK */
1139 * resched_task - mark a task 'to be rescheduled now'.
1141 * On UP this means the setting of the need_resched flag, on SMP it
1142 * might also involve a cross-CPU call to trigger the scheduler on
1147 #ifndef tsk_is_polling
1148 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1151 static void resched_task(struct task_struct *p)
1155 assert_raw_spin_locked(&task_rq(p)->lock);
1157 if (test_tsk_need_resched(p))
1160 set_tsk_need_resched(p);
1163 if (cpu == smp_processor_id())
1166 /* NEED_RESCHED must be visible before we test polling */
1168 if (!tsk_is_polling(p))
1169 smp_send_reschedule(cpu);
1172 static void resched_cpu(int cpu)
1174 struct rq *rq = cpu_rq(cpu);
1175 unsigned long flags;
1177 if (!raw_spin_trylock_irqsave(&rq->lock, flags))
1179 resched_task(cpu_curr(cpu));
1180 raw_spin_unlock_irqrestore(&rq->lock, flags);
1185 * In the semi idle case, use the nearest busy cpu for migrating timers
1186 * from an idle cpu. This is good for power-savings.
1188 * We don't do similar optimization for completely idle system, as
1189 * selecting an idle cpu will add more delays to the timers than intended
1190 * (as that cpu's timer base may not be uptodate wrt jiffies etc).
1192 int get_nohz_timer_target(void)
1194 int cpu = smp_processor_id();
1196 struct sched_domain *sd;
1198 for_each_domain(cpu, sd) {
1199 for_each_cpu(i, sched_domain_span(sd))
1206 * When add_timer_on() enqueues a timer into the timer wheel of an
1207 * idle CPU then this timer might expire before the next timer event
1208 * which is scheduled to wake up that CPU. In case of a completely
1209 * idle system the next event might even be infinite time into the
1210 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1211 * leaves the inner idle loop so the newly added timer is taken into
1212 * account when the CPU goes back to idle and evaluates the timer
1213 * wheel for the next timer event.
1215 void wake_up_idle_cpu(int cpu)
1217 struct rq *rq = cpu_rq(cpu);
1219 if (cpu == smp_processor_id())
1223 * This is safe, as this function is called with the timer
1224 * wheel base lock of (cpu) held. When the CPU is on the way
1225 * to idle and has not yet set rq->curr to idle then it will
1226 * be serialized on the timer wheel base lock and take the new
1227 * timer into account automatically.
1229 if (rq->curr != rq->idle)
1233 * We can set TIF_RESCHED on the idle task of the other CPU
1234 * lockless. The worst case is that the other CPU runs the
1235 * idle task through an additional NOOP schedule()
1237 set_tsk_need_resched(rq->idle);
1239 /* NEED_RESCHED must be visible before we test polling */
1241 if (!tsk_is_polling(rq->idle))
1242 smp_send_reschedule(cpu);
1245 #endif /* CONFIG_NO_HZ */
1247 static u64 sched_avg_period(void)
1249 return (u64)sysctl_sched_time_avg * NSEC_PER_MSEC / 2;
1252 static void sched_avg_update(struct rq *rq)
1254 s64 period = sched_avg_period();
1256 while ((s64)(rq->clock - rq->age_stamp) > period) {
1258 * Inline assembly required to prevent the compiler
1259 * optimising this loop into a divmod call.
1260 * See __iter_div_u64_rem() for another example of this.
1262 asm("" : "+rm" (rq->age_stamp));
1263 rq->age_stamp += period;
1268 static void sched_rt_avg_update(struct rq *rq, u64 rt_delta)
1270 rq->rt_avg += rt_delta;
1271 sched_avg_update(rq);
1274 #else /* !CONFIG_SMP */
1275 static void resched_task(struct task_struct *p)
1277 assert_raw_spin_locked(&task_rq(p)->lock);
1278 set_tsk_need_resched(p);
1281 static void sched_rt_avg_update(struct rq *rq, u64 rt_delta)
1285 static void sched_avg_update(struct rq *rq)
1288 #endif /* CONFIG_SMP */
1290 #if BITS_PER_LONG == 32
1291 # define WMULT_CONST (~0UL)
1293 # define WMULT_CONST (1UL << 32)
1296 #define WMULT_SHIFT 32
1299 * Shift right and round:
1301 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1304 * delta *= weight / lw
1306 static unsigned long
1307 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1308 struct load_weight *lw)
1312 if (!lw->inv_weight) {
1313 if (BITS_PER_LONG > 32 && unlikely(lw->weight >= WMULT_CONST))
1316 lw->inv_weight = 1 + (WMULT_CONST-lw->weight/2)
1320 tmp = (u64)delta_exec * weight;
1322 * Check whether we'd overflow the 64-bit multiplication:
1324 if (unlikely(tmp > WMULT_CONST))
1325 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1328 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1330 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1333 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1339 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1345 static inline void update_load_set(struct load_weight *lw, unsigned long w)
1352 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1353 * of tasks with abnormal "nice" values across CPUs the contribution that
1354 * each task makes to its run queue's load is weighted according to its
1355 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1356 * scaled version of the new time slice allocation that they receive on time
1360 #define WEIGHT_IDLEPRIO 3
1361 #define WMULT_IDLEPRIO 1431655765
1364 * Nice levels are multiplicative, with a gentle 10% change for every
1365 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1366 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1367 * that remained on nice 0.
1369 * The "10% effect" is relative and cumulative: from _any_ nice level,
1370 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1371 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1372 * If a task goes up by ~10% and another task goes down by ~10% then
1373 * the relative distance between them is ~25%.)
1375 static const int prio_to_weight[40] = {
1376 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1377 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1378 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1379 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1380 /* 0 */ 1024, 820, 655, 526, 423,
1381 /* 5 */ 335, 272, 215, 172, 137,
1382 /* 10 */ 110, 87, 70, 56, 45,
1383 /* 15 */ 36, 29, 23, 18, 15,
1387 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1389 * In cases where the weight does not change often, we can use the
1390 * precalculated inverse to speed up arithmetics by turning divisions
1391 * into multiplications:
1393 static const u32 prio_to_wmult[40] = {
1394 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1395 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1396 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1397 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1398 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1399 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1400 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1401 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1404 /* Time spent by the tasks of the cpu accounting group executing in ... */
1405 enum cpuacct_stat_index {
1406 CPUACCT_STAT_USER, /* ... user mode */
1407 CPUACCT_STAT_SYSTEM, /* ... kernel mode */
1409 CPUACCT_STAT_NSTATS,
1412 #ifdef CONFIG_CGROUP_CPUACCT
1413 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1414 static void cpuacct_update_stats(struct task_struct *tsk,
1415 enum cpuacct_stat_index idx, cputime_t val);
1417 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1418 static inline void cpuacct_update_stats(struct task_struct *tsk,
1419 enum cpuacct_stat_index idx, cputime_t val) {}
1422 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1424 update_load_add(&rq->load, load);
1427 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1429 update_load_sub(&rq->load, load);
1432 #if (defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)) || defined(CONFIG_RT_GROUP_SCHED)
1433 typedef int (*tg_visitor)(struct task_group *, void *);
1436 * Iterate the full tree, calling @down when first entering a node and @up when
1437 * leaving it for the final time.
1439 static int walk_tg_tree(tg_visitor down, tg_visitor up, void *data)
1441 struct task_group *parent, *child;
1445 parent = &root_task_group;
1447 ret = (*down)(parent, data);
1450 list_for_each_entry_rcu(child, &parent->children, siblings) {
1457 ret = (*up)(parent, data);
1462 parent = parent->parent;
1471 static int tg_nop(struct task_group *tg, void *data)
1478 /* Used instead of source_load when we know the type == 0 */
1479 static unsigned long weighted_cpuload(const int cpu)
1481 return cpu_rq(cpu)->load.weight;
1485 * Return a low guess at the load of a migration-source cpu weighted
1486 * according to the scheduling class and "nice" value.
1488 * We want to under-estimate the load of migration sources, to
1489 * balance conservatively.
1491 static unsigned long source_load(int cpu, int type)
1493 struct rq *rq = cpu_rq(cpu);
1494 unsigned long total = weighted_cpuload(cpu);
1496 if (type == 0 || !sched_feat(LB_BIAS))
1499 return min(rq->cpu_load[type-1], total);
1503 * Return a high guess at the load of a migration-target cpu weighted
1504 * according to the scheduling class and "nice" value.
1506 static unsigned long target_load(int cpu, int type)
1508 struct rq *rq = cpu_rq(cpu);
1509 unsigned long total = weighted_cpuload(cpu);
1511 if (type == 0 || !sched_feat(LB_BIAS))
1514 return max(rq->cpu_load[type-1], total);
1517 static unsigned long power_of(int cpu)
1519 return cpu_rq(cpu)->cpu_power;
1522 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1524 static unsigned long cpu_avg_load_per_task(int cpu)
1526 struct rq *rq = cpu_rq(cpu);
1527 unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
1530 rq->avg_load_per_task = rq->load.weight / nr_running;
1532 rq->avg_load_per_task = 0;
1534 return rq->avg_load_per_task;
1537 #ifdef CONFIG_FAIR_GROUP_SCHED
1540 * Compute the cpu's hierarchical load factor for each task group.
1541 * This needs to be done in a top-down fashion because the load of a child
1542 * group is a fraction of its parents load.
1544 static int tg_load_down(struct task_group *tg, void *data)
1547 long cpu = (long)data;
1550 load = cpu_rq(cpu)->load.weight;
1552 load = tg->parent->cfs_rq[cpu]->h_load;
1553 load *= tg->se[cpu]->load.weight;
1554 load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
1557 tg->cfs_rq[cpu]->h_load = load;
1562 static void update_h_load(long cpu)
1564 walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
1569 #ifdef CONFIG_PREEMPT
1571 static void double_rq_lock(struct rq *rq1, struct rq *rq2);
1574 * fair double_lock_balance: Safely acquires both rq->locks in a fair
1575 * way at the expense of forcing extra atomic operations in all
1576 * invocations. This assures that the double_lock is acquired using the
1577 * same underlying policy as the spinlock_t on this architecture, which
1578 * reduces latency compared to the unfair variant below. However, it
1579 * also adds more overhead and therefore may reduce throughput.
1581 static inline int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1582 __releases(this_rq->lock)
1583 __acquires(busiest->lock)
1584 __acquires(this_rq->lock)
1586 raw_spin_unlock(&this_rq->lock);
1587 double_rq_lock(this_rq, busiest);
1594 * Unfair double_lock_balance: Optimizes throughput at the expense of
1595 * latency by eliminating extra atomic operations when the locks are
1596 * already in proper order on entry. This favors lower cpu-ids and will
1597 * grant the double lock to lower cpus over higher ids under contention,
1598 * regardless of entry order into the function.
1600 static int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1601 __releases(this_rq->lock)
1602 __acquires(busiest->lock)
1603 __acquires(this_rq->lock)
1607 if (unlikely(!raw_spin_trylock(&busiest->lock))) {
1608 if (busiest < this_rq) {
1609 raw_spin_unlock(&this_rq->lock);
1610 raw_spin_lock(&busiest->lock);
1611 raw_spin_lock_nested(&this_rq->lock,
1612 SINGLE_DEPTH_NESTING);
1615 raw_spin_lock_nested(&busiest->lock,
1616 SINGLE_DEPTH_NESTING);
1621 #endif /* CONFIG_PREEMPT */
1624 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1626 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
1628 if (unlikely(!irqs_disabled())) {
1629 /* printk() doesn't work good under rq->lock */
1630 raw_spin_unlock(&this_rq->lock);
1634 return _double_lock_balance(this_rq, busiest);
1637 static inline void double_unlock_balance(struct rq *this_rq, struct rq *busiest)
1638 __releases(busiest->lock)
1640 raw_spin_unlock(&busiest->lock);
1641 lock_set_subclass(&this_rq->lock.dep_map, 0, _RET_IP_);
1645 * double_rq_lock - safely lock two runqueues
1647 * Note this does not disable interrupts like task_rq_lock,
1648 * you need to do so manually before calling.
1650 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
1651 __acquires(rq1->lock)
1652 __acquires(rq2->lock)
1654 BUG_ON(!irqs_disabled());
1656 raw_spin_lock(&rq1->lock);
1657 __acquire(rq2->lock); /* Fake it out ;) */
1660 raw_spin_lock(&rq1->lock);
1661 raw_spin_lock_nested(&rq2->lock, SINGLE_DEPTH_NESTING);
1663 raw_spin_lock(&rq2->lock);
1664 raw_spin_lock_nested(&rq1->lock, SINGLE_DEPTH_NESTING);
1670 * double_rq_unlock - safely unlock two runqueues
1672 * Note this does not restore interrupts like task_rq_unlock,
1673 * you need to do so manually after calling.
1675 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
1676 __releases(rq1->lock)
1677 __releases(rq2->lock)
1679 raw_spin_unlock(&rq1->lock);
1681 raw_spin_unlock(&rq2->lock);
1683 __release(rq2->lock);
1688 static void calc_load_account_idle(struct rq *this_rq);
1689 static void update_sysctl(void);
1690 static int get_update_sysctl_factor(void);
1691 static void update_cpu_load(struct rq *this_rq);
1693 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1695 set_task_rq(p, cpu);
1698 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1699 * successfuly executed on another CPU. We must ensure that updates of
1700 * per-task data have been completed by this moment.
1703 task_thread_info(p)->cpu = cpu;
1707 static const struct sched_class rt_sched_class;
1709 #define sched_class_highest (&stop_sched_class)
1710 #define for_each_class(class) \
1711 for (class = sched_class_highest; class; class = class->next)
1713 #include "sched_stats.h"
1715 static void inc_nr_running(struct rq *rq)
1720 static void dec_nr_running(struct rq *rq)
1725 static void set_load_weight(struct task_struct *p)
1728 * SCHED_IDLE tasks get minimal weight:
1730 if (p->policy == SCHED_IDLE) {
1731 p->se.load.weight = WEIGHT_IDLEPRIO;
1732 p->se.load.inv_weight = WMULT_IDLEPRIO;
1736 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1737 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1740 static void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
1742 update_rq_clock(rq);
1743 sched_info_queued(p);
1744 p->sched_class->enqueue_task(rq, p, flags);
1748 static void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
1750 update_rq_clock(rq);
1751 sched_info_dequeued(p);
1752 p->sched_class->dequeue_task(rq, p, flags);
1757 * activate_task - move a task to the runqueue.
1759 static void activate_task(struct rq *rq, struct task_struct *p, int flags)
1761 if (task_contributes_to_load(p))
1762 rq->nr_uninterruptible--;
1764 enqueue_task(rq, p, flags);
1769 * deactivate_task - remove a task from the runqueue.
1771 static void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
1773 if (task_contributes_to_load(p))
1774 rq->nr_uninterruptible++;
1776 dequeue_task(rq, p, flags);
1780 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
1783 * There are no locks covering percpu hardirq/softirq time.
1784 * They are only modified in account_system_vtime, on corresponding CPU
1785 * with interrupts disabled. So, writes are safe.
1786 * They are read and saved off onto struct rq in update_rq_clock().
1787 * This may result in other CPU reading this CPU's irq time and can
1788 * race with irq/account_system_vtime on this CPU. We would either get old
1789 * or new value (or semi updated value on 32 bit) with a side effect of
1790 * accounting a slice of irq time to wrong task when irq is in progress
1791 * while we read rq->clock. That is a worthy compromise in place of having
1792 * locks on each irq in account_system_time.
1794 static DEFINE_PER_CPU(u64, cpu_hardirq_time);
1795 static DEFINE_PER_CPU(u64, cpu_softirq_time);
1797 static DEFINE_PER_CPU(u64, irq_start_time);
1798 static int sched_clock_irqtime;
1800 void enable_sched_clock_irqtime(void)
1802 sched_clock_irqtime = 1;
1805 void disable_sched_clock_irqtime(void)
1807 sched_clock_irqtime = 0;
1810 static u64 irq_time_cpu(int cpu)
1812 if (!sched_clock_irqtime)
1815 return per_cpu(cpu_softirq_time, cpu) + per_cpu(cpu_hardirq_time, cpu);
1818 void account_system_vtime(struct task_struct *curr)
1820 unsigned long flags;
1824 if (!sched_clock_irqtime)
1827 local_irq_save(flags);
1829 cpu = smp_processor_id();
1830 now = sched_clock_cpu(cpu);
1831 delta = now - per_cpu(irq_start_time, cpu);
1832 per_cpu(irq_start_time, cpu) = now;
1834 * We do not account for softirq time from ksoftirqd here.
1835 * We want to continue accounting softirq time to ksoftirqd thread
1836 * in that case, so as not to confuse scheduler with a special task
1837 * that do not consume any time, but still wants to run.
1839 if (hardirq_count())
1840 per_cpu(cpu_hardirq_time, cpu) += delta;
1841 else if (in_serving_softirq() && !(curr->flags & PF_KSOFTIRQD))
1842 per_cpu(cpu_softirq_time, cpu) += delta;
1844 local_irq_restore(flags);
1846 EXPORT_SYMBOL_GPL(account_system_vtime);
1848 static void sched_irq_time_avg_update(struct rq *rq, u64 curr_irq_time)
1850 if (sched_clock_irqtime && sched_feat(NONIRQ_POWER)) {
1851 u64 delta_irq = curr_irq_time - rq->prev_irq_time;
1852 rq->prev_irq_time = curr_irq_time;
1853 sched_rt_avg_update(rq, delta_irq);
1859 static u64 irq_time_cpu(int cpu)
1864 static void sched_irq_time_avg_update(struct rq *rq, u64 curr_irq_time) { }
1868 #include "sched_idletask.c"
1869 #include "sched_fair.c"
1870 #include "sched_rt.c"
1871 #include "sched_stoptask.c"
1872 #ifdef CONFIG_SCHED_DEBUG
1873 # include "sched_debug.c"
1876 void sched_set_stop_task(int cpu, struct task_struct *stop)
1878 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
1879 struct task_struct *old_stop = cpu_rq(cpu)->stop;
1883 * Make it appear like a SCHED_FIFO task, its something
1884 * userspace knows about and won't get confused about.
1886 * Also, it will make PI more or less work without too
1887 * much confusion -- but then, stop work should not
1888 * rely on PI working anyway.
1890 sched_setscheduler_nocheck(stop, SCHED_FIFO, ¶m);
1892 stop->sched_class = &stop_sched_class;
1895 cpu_rq(cpu)->stop = stop;
1899 * Reset it back to a normal scheduling class so that
1900 * it can die in pieces.
1902 old_stop->sched_class = &rt_sched_class;
1907 * __normal_prio - return the priority that is based on the static prio
1909 static inline int __normal_prio(struct task_struct *p)
1911 return p->static_prio;
1915 * Calculate the expected normal priority: i.e. priority
1916 * without taking RT-inheritance into account. Might be
1917 * boosted by interactivity modifiers. Changes upon fork,
1918 * setprio syscalls, and whenever the interactivity
1919 * estimator recalculates.
1921 static inline int normal_prio(struct task_struct *p)
1925 if (task_has_rt_policy(p))
1926 prio = MAX_RT_PRIO-1 - p->rt_priority;
1928 prio = __normal_prio(p);
1933 * Calculate the current priority, i.e. the priority
1934 * taken into account by the scheduler. This value might
1935 * be boosted by RT tasks, or might be boosted by
1936 * interactivity modifiers. Will be RT if the task got
1937 * RT-boosted. If not then it returns p->normal_prio.
1939 static int effective_prio(struct task_struct *p)
1941 p->normal_prio = normal_prio(p);
1943 * If we are RT tasks or we were boosted to RT priority,
1944 * keep the priority unchanged. Otherwise, update priority
1945 * to the normal priority:
1947 if (!rt_prio(p->prio))
1948 return p->normal_prio;
1953 * task_curr - is this task currently executing on a CPU?
1954 * @p: the task in question.
1956 inline int task_curr(const struct task_struct *p)
1958 return cpu_curr(task_cpu(p)) == p;
1961 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1962 const struct sched_class *prev_class,
1963 int oldprio, int running)
1965 if (prev_class != p->sched_class) {
1966 if (prev_class->switched_from)
1967 prev_class->switched_from(rq, p, running);
1968 p->sched_class->switched_to(rq, p, running);
1970 p->sched_class->prio_changed(rq, p, oldprio, running);
1973 static void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
1975 const struct sched_class *class;
1977 if (p->sched_class == rq->curr->sched_class) {
1978 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
1980 for_each_class(class) {
1981 if (class == rq->curr->sched_class)
1983 if (class == p->sched_class) {
1984 resched_task(rq->curr);
1991 * A queue event has occurred, and we're going to schedule. In
1992 * this case, we can save a useless back to back clock update.
1994 if (test_tsk_need_resched(rq->curr))
1995 rq->skip_clock_update = 1;
2000 * Is this task likely cache-hot:
2003 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
2007 if (p->sched_class != &fair_sched_class)
2010 if (unlikely(p->policy == SCHED_IDLE))
2014 * Buddy candidates are cache hot:
2016 if (sched_feat(CACHE_HOT_BUDDY) && this_rq()->nr_running &&
2017 (&p->se == cfs_rq_of(&p->se)->next ||
2018 &p->se == cfs_rq_of(&p->se)->last))
2021 if (sysctl_sched_migration_cost == -1)
2023 if (sysctl_sched_migration_cost == 0)
2026 delta = now - p->se.exec_start;
2028 return delta < (s64)sysctl_sched_migration_cost;
2031 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
2033 #ifdef CONFIG_SCHED_DEBUG
2035 * We should never call set_task_cpu() on a blocked task,
2036 * ttwu() will sort out the placement.
2038 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
2039 !(task_thread_info(p)->preempt_count & PREEMPT_ACTIVE));
2042 trace_sched_migrate_task(p, new_cpu);
2044 if (task_cpu(p) != new_cpu) {
2045 p->se.nr_migrations++;
2046 perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, 1, NULL, 0);
2049 __set_task_cpu(p, new_cpu);
2052 struct migration_arg {
2053 struct task_struct *task;
2057 static int migration_cpu_stop(void *data);
2060 * The task's runqueue lock must be held.
2061 * Returns true if you have to wait for migration thread.
2063 static bool migrate_task(struct task_struct *p, int dest_cpu)
2065 struct rq *rq = task_rq(p);
2068 * If the task is not on a runqueue (and not running), then
2069 * the next wake-up will properly place the task.
2071 return p->se.on_rq || task_running(rq, p);
2075 * wait_task_inactive - wait for a thread to unschedule.
2077 * If @match_state is nonzero, it's the @p->state value just checked and
2078 * not expected to change. If it changes, i.e. @p might have woken up,
2079 * then return zero. When we succeed in waiting for @p to be off its CPU,
2080 * we return a positive number (its total switch count). If a second call
2081 * a short while later returns the same number, the caller can be sure that
2082 * @p has remained unscheduled the whole time.
2084 * The caller must ensure that the task *will* unschedule sometime soon,
2085 * else this function might spin for a *long* time. This function can't
2086 * be called with interrupts off, or it may introduce deadlock with
2087 * smp_call_function() if an IPI is sent by the same process we are
2088 * waiting to become inactive.
2090 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
2092 unsigned long flags;
2099 * We do the initial early heuristics without holding
2100 * any task-queue locks at all. We'll only try to get
2101 * the runqueue lock when things look like they will
2107 * If the task is actively running on another CPU
2108 * still, just relax and busy-wait without holding
2111 * NOTE! Since we don't hold any locks, it's not
2112 * even sure that "rq" stays as the right runqueue!
2113 * But we don't care, since "task_running()" will
2114 * return false if the runqueue has changed and p
2115 * is actually now running somewhere else!
2117 while (task_running(rq, p)) {
2118 if (match_state && unlikely(p->state != match_state))
2124 * Ok, time to look more closely! We need the rq
2125 * lock now, to be *sure*. If we're wrong, we'll
2126 * just go back and repeat.
2128 rq = task_rq_lock(p, &flags);
2129 trace_sched_wait_task(p);
2130 running = task_running(rq, p);
2131 on_rq = p->se.on_rq;
2133 if (!match_state || p->state == match_state)
2134 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
2135 task_rq_unlock(rq, &flags);
2138 * If it changed from the expected state, bail out now.
2140 if (unlikely(!ncsw))
2144 * Was it really running after all now that we
2145 * checked with the proper locks actually held?
2147 * Oops. Go back and try again..
2149 if (unlikely(running)) {
2155 * It's not enough that it's not actively running,
2156 * it must be off the runqueue _entirely_, and not
2159 * So if it was still runnable (but just not actively
2160 * running right now), it's preempted, and we should
2161 * yield - it could be a while.
2163 if (unlikely(on_rq)) {
2164 schedule_timeout_uninterruptible(1);
2169 * Ahh, all good. It wasn't running, and it wasn't
2170 * runnable, which means that it will never become
2171 * running in the future either. We're all done!
2180 * kick_process - kick a running thread to enter/exit the kernel
2181 * @p: the to-be-kicked thread
2183 * Cause a process which is running on another CPU to enter
2184 * kernel-mode, without any delay. (to get signals handled.)
2186 * NOTE: this function doesnt have to take the runqueue lock,
2187 * because all it wants to ensure is that the remote task enters
2188 * the kernel. If the IPI races and the task has been migrated
2189 * to another CPU then no harm is done and the purpose has been
2192 void kick_process(struct task_struct *p)
2198 if ((cpu != smp_processor_id()) && task_curr(p))
2199 smp_send_reschedule(cpu);
2202 EXPORT_SYMBOL_GPL(kick_process);
2203 #endif /* CONFIG_SMP */
2206 * task_oncpu_function_call - call a function on the cpu on which a task runs
2207 * @p: the task to evaluate
2208 * @func: the function to be called
2209 * @info: the function call argument
2211 * Calls the function @func when the task is currently running. This might
2212 * be on the current CPU, which just calls the function directly
2214 void task_oncpu_function_call(struct task_struct *p,
2215 void (*func) (void *info), void *info)
2222 smp_call_function_single(cpu, func, info, 1);
2228 * ->cpus_allowed is protected by either TASK_WAKING or rq->lock held.
2230 static int select_fallback_rq(int cpu, struct task_struct *p)
2233 const struct cpumask *nodemask = cpumask_of_node(cpu_to_node(cpu));
2235 /* Look for allowed, online CPU in same node. */
2236 for_each_cpu_and(dest_cpu, nodemask, cpu_active_mask)
2237 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
2240 /* Any allowed, online CPU? */
2241 dest_cpu = cpumask_any_and(&p->cpus_allowed, cpu_active_mask);
2242 if (dest_cpu < nr_cpu_ids)
2245 /* No more Mr. Nice Guy. */
2246 dest_cpu = cpuset_cpus_allowed_fallback(p);
2248 * Don't tell them about moving exiting tasks or
2249 * kernel threads (both mm NULL), since they never
2252 if (p->mm && printk_ratelimit()) {
2253 printk(KERN_INFO "process %d (%s) no longer affine to cpu%d\n",
2254 task_pid_nr(p), p->comm, cpu);
2261 * The caller (fork, wakeup) owns TASK_WAKING, ->cpus_allowed is stable.
2264 int select_task_rq(struct rq *rq, struct task_struct *p, int sd_flags, int wake_flags)
2266 int cpu = p->sched_class->select_task_rq(rq, p, sd_flags, wake_flags);
2269 * In order not to call set_task_cpu() on a blocking task we need
2270 * to rely on ttwu() to place the task on a valid ->cpus_allowed
2273 * Since this is common to all placement strategies, this lives here.
2275 * [ this allows ->select_task() to simply return task_cpu(p) and
2276 * not worry about this generic constraint ]
2278 if (unlikely(!cpumask_test_cpu(cpu, &p->cpus_allowed) ||
2280 cpu = select_fallback_rq(task_cpu(p), p);
2285 static void update_avg(u64 *avg, u64 sample)
2287 s64 diff = sample - *avg;
2292 static inline void ttwu_activate(struct task_struct *p, struct rq *rq,
2293 bool is_sync, bool is_migrate, bool is_local,
2294 unsigned long en_flags)
2296 schedstat_inc(p, se.statistics.nr_wakeups);
2298 schedstat_inc(p, se.statistics.nr_wakeups_sync);
2300 schedstat_inc(p, se.statistics.nr_wakeups_migrate);
2302 schedstat_inc(p, se.statistics.nr_wakeups_local);
2304 schedstat_inc(p, se.statistics.nr_wakeups_remote);
2306 activate_task(rq, p, en_flags);
2309 static inline void ttwu_post_activation(struct task_struct *p, struct rq *rq,
2310 int wake_flags, bool success)
2312 trace_sched_wakeup(p, success);
2313 check_preempt_curr(rq, p, wake_flags);
2315 p->state = TASK_RUNNING;
2317 if (p->sched_class->task_woken)
2318 p->sched_class->task_woken(rq, p);
2320 if (unlikely(rq->idle_stamp)) {
2321 u64 delta = rq->clock - rq->idle_stamp;
2322 u64 max = 2*sysctl_sched_migration_cost;
2327 update_avg(&rq->avg_idle, delta);
2331 /* if a worker is waking up, notify workqueue */
2332 if ((p->flags & PF_WQ_WORKER) && success)
2333 wq_worker_waking_up(p, cpu_of(rq));
2337 * try_to_wake_up - wake up a thread
2338 * @p: the thread to be awakened
2339 * @state: the mask of task states that can be woken
2340 * @wake_flags: wake modifier flags (WF_*)
2342 * Put it on the run-queue if it's not already there. The "current"
2343 * thread is always on the run-queue (except when the actual
2344 * re-schedule is in progress), and as such you're allowed to do
2345 * the simpler "current->state = TASK_RUNNING" to mark yourself
2346 * runnable without the overhead of this.
2348 * Returns %true if @p was woken up, %false if it was already running
2349 * or @state didn't match @p's state.
2351 static int try_to_wake_up(struct task_struct *p, unsigned int state,
2354 int cpu, orig_cpu, this_cpu, success = 0;
2355 unsigned long flags;
2356 unsigned long en_flags = ENQUEUE_WAKEUP;
2359 this_cpu = get_cpu();
2362 rq = task_rq_lock(p, &flags);
2363 if (!(p->state & state))
2373 if (unlikely(task_running(rq, p)))
2377 * In order to handle concurrent wakeups and release the rq->lock
2378 * we put the task in TASK_WAKING state.
2380 * First fix up the nr_uninterruptible count:
2382 if (task_contributes_to_load(p)) {
2383 if (likely(cpu_online(orig_cpu)))
2384 rq->nr_uninterruptible--;
2386 this_rq()->nr_uninterruptible--;
2388 p->state = TASK_WAKING;
2390 if (p->sched_class->task_waking) {
2391 p->sched_class->task_waking(rq, p);
2392 en_flags |= ENQUEUE_WAKING;
2395 cpu = select_task_rq(rq, p, SD_BALANCE_WAKE, wake_flags);
2396 if (cpu != orig_cpu)
2397 set_task_cpu(p, cpu);
2398 __task_rq_unlock(rq);
2401 raw_spin_lock(&rq->lock);
2404 * We migrated the task without holding either rq->lock, however
2405 * since the task is not on the task list itself, nobody else
2406 * will try and migrate the task, hence the rq should match the
2407 * cpu we just moved it to.
2409 WARN_ON(task_cpu(p) != cpu);
2410 WARN_ON(p->state != TASK_WAKING);
2412 #ifdef CONFIG_SCHEDSTATS
2413 schedstat_inc(rq, ttwu_count);
2414 if (cpu == this_cpu)
2415 schedstat_inc(rq, ttwu_local);
2417 struct sched_domain *sd;
2418 for_each_domain(this_cpu, sd) {
2419 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2420 schedstat_inc(sd, ttwu_wake_remote);
2425 #endif /* CONFIG_SCHEDSTATS */
2428 #endif /* CONFIG_SMP */
2429 ttwu_activate(p, rq, wake_flags & WF_SYNC, orig_cpu != cpu,
2430 cpu == this_cpu, en_flags);
2433 ttwu_post_activation(p, rq, wake_flags, success);
2435 task_rq_unlock(rq, &flags);
2442 * try_to_wake_up_local - try to wake up a local task with rq lock held
2443 * @p: the thread to be awakened
2445 * Put @p on the run-queue if it's not alredy there. The caller must
2446 * ensure that this_rq() is locked, @p is bound to this_rq() and not
2447 * the current task. this_rq() stays locked over invocation.
2449 static void try_to_wake_up_local(struct task_struct *p)
2451 struct rq *rq = task_rq(p);
2452 bool success = false;
2454 BUG_ON(rq != this_rq());
2455 BUG_ON(p == current);
2456 lockdep_assert_held(&rq->lock);
2458 if (!(p->state & TASK_NORMAL))
2462 if (likely(!task_running(rq, p))) {
2463 schedstat_inc(rq, ttwu_count);
2464 schedstat_inc(rq, ttwu_local);
2466 ttwu_activate(p, rq, false, false, true, ENQUEUE_WAKEUP);
2469 ttwu_post_activation(p, rq, 0, success);
2473 * wake_up_process - Wake up a specific process
2474 * @p: The process to be woken up.
2476 * Attempt to wake up the nominated process and move it to the set of runnable
2477 * processes. Returns 1 if the process was woken up, 0 if it was already
2480 * It may be assumed that this function implies a write memory barrier before
2481 * changing the task state if and only if any tasks are woken up.
2483 int wake_up_process(struct task_struct *p)
2485 return try_to_wake_up(p, TASK_ALL, 0);
2487 EXPORT_SYMBOL(wake_up_process);
2489 int wake_up_state(struct task_struct *p, unsigned int state)
2491 return try_to_wake_up(p, state, 0);
2495 * Perform scheduler related setup for a newly forked process p.
2496 * p is forked by current.
2498 * __sched_fork() is basic setup used by init_idle() too:
2500 static void __sched_fork(struct task_struct *p)
2502 p->se.exec_start = 0;
2503 p->se.sum_exec_runtime = 0;
2504 p->se.prev_sum_exec_runtime = 0;
2505 p->se.nr_migrations = 0;
2507 #ifdef CONFIG_SCHEDSTATS
2508 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
2511 INIT_LIST_HEAD(&p->rt.run_list);
2513 INIT_LIST_HEAD(&p->se.group_node);
2515 #ifdef CONFIG_PREEMPT_NOTIFIERS
2516 INIT_HLIST_HEAD(&p->preempt_notifiers);
2521 * fork()/clone()-time setup:
2523 void sched_fork(struct task_struct *p, int clone_flags)
2525 int cpu = get_cpu();
2529 * We mark the process as running here. This guarantees that
2530 * nobody will actually run it, and a signal or other external
2531 * event cannot wake it up and insert it on the runqueue either.
2533 p->state = TASK_RUNNING;
2536 * Revert to default priority/policy on fork if requested.
2538 if (unlikely(p->sched_reset_on_fork)) {
2539 if (p->policy == SCHED_FIFO || p->policy == SCHED_RR) {
2540 p->policy = SCHED_NORMAL;
2541 p->normal_prio = p->static_prio;
2544 if (PRIO_TO_NICE(p->static_prio) < 0) {
2545 p->static_prio = NICE_TO_PRIO(0);
2546 p->normal_prio = p->static_prio;
2551 * We don't need the reset flag anymore after the fork. It has
2552 * fulfilled its duty:
2554 p->sched_reset_on_fork = 0;
2558 * Make sure we do not leak PI boosting priority to the child.
2560 p->prio = current->normal_prio;
2562 if (!rt_prio(p->prio))
2563 p->sched_class = &fair_sched_class;
2565 if (p->sched_class->task_fork)
2566 p->sched_class->task_fork(p);
2569 * The child is not yet in the pid-hash so no cgroup attach races,
2570 * and the cgroup is pinned to this child due to cgroup_fork()
2571 * is ran before sched_fork().
2573 * Silence PROVE_RCU.
2576 set_task_cpu(p, cpu);
2579 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2580 if (likely(sched_info_on()))
2581 memset(&p->sched_info, 0, sizeof(p->sched_info));
2583 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2586 #ifdef CONFIG_PREEMPT
2587 /* Want to start with kernel preemption disabled. */
2588 task_thread_info(p)->preempt_count = 1;
2590 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2596 * wake_up_new_task - wake up a newly created task for the first time.
2598 * This function will do some initial scheduler statistics housekeeping
2599 * that must be done for every newly created context, then puts the task
2600 * on the runqueue and wakes it.
2602 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2604 unsigned long flags;
2606 int cpu __maybe_unused = get_cpu();
2609 rq = task_rq_lock(p, &flags);
2610 p->state = TASK_WAKING;
2613 * Fork balancing, do it here and not earlier because:
2614 * - cpus_allowed can change in the fork path
2615 * - any previously selected cpu might disappear through hotplug
2617 * We set TASK_WAKING so that select_task_rq() can drop rq->lock
2618 * without people poking at ->cpus_allowed.
2620 cpu = select_task_rq(rq, p, SD_BALANCE_FORK, 0);
2621 set_task_cpu(p, cpu);
2623 p->state = TASK_RUNNING;
2624 task_rq_unlock(rq, &flags);
2627 rq = task_rq_lock(p, &flags);
2628 activate_task(rq, p, 0);
2629 trace_sched_wakeup_new(p, 1);
2630 check_preempt_curr(rq, p, WF_FORK);
2632 if (p->sched_class->task_woken)
2633 p->sched_class->task_woken(rq, p);
2635 task_rq_unlock(rq, &flags);
2639 #ifdef CONFIG_PREEMPT_NOTIFIERS
2642 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2643 * @notifier: notifier struct to register
2645 void preempt_notifier_register(struct preempt_notifier *notifier)
2647 hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
2649 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2652 * preempt_notifier_unregister - no longer interested in preemption notifications
2653 * @notifier: notifier struct to unregister
2655 * This is safe to call from within a preemption notifier.
2657 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2659 hlist_del(¬ifier->link);
2661 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2663 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2665 struct preempt_notifier *notifier;
2666 struct hlist_node *node;
2668 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2669 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2673 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2674 struct task_struct *next)
2676 struct preempt_notifier *notifier;
2677 struct hlist_node *node;
2679 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2680 notifier->ops->sched_out(notifier, next);
2683 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2685 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2690 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2691 struct task_struct *next)
2695 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2698 * prepare_task_switch - prepare to switch tasks
2699 * @rq: the runqueue preparing to switch
2700 * @prev: the current task that is being switched out
2701 * @next: the task we are going to switch to.
2703 * This is called with the rq lock held and interrupts off. It must
2704 * be paired with a subsequent finish_task_switch after the context
2707 * prepare_task_switch sets up locking and calls architecture specific
2711 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2712 struct task_struct *next)
2714 fire_sched_out_preempt_notifiers(prev, next);
2715 prepare_lock_switch(rq, next);
2716 prepare_arch_switch(next);
2720 * finish_task_switch - clean up after a task-switch
2721 * @rq: runqueue associated with task-switch
2722 * @prev: the thread we just switched away from.
2724 * finish_task_switch must be called after the context switch, paired
2725 * with a prepare_task_switch call before the context switch.
2726 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2727 * and do any other architecture-specific cleanup actions.
2729 * Note that we may have delayed dropping an mm in context_switch(). If
2730 * so, we finish that here outside of the runqueue lock. (Doing it
2731 * with the lock held can cause deadlocks; see schedule() for
2734 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2735 __releases(rq->lock)
2737 struct mm_struct *mm = rq->prev_mm;
2743 * A task struct has one reference for the use as "current".
2744 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2745 * schedule one last time. The schedule call will never return, and
2746 * the scheduled task must drop that reference.
2747 * The test for TASK_DEAD must occur while the runqueue locks are
2748 * still held, otherwise prev could be scheduled on another cpu, die
2749 * there before we look at prev->state, and then the reference would
2751 * Manfred Spraul <manfred@colorfullife.com>
2753 prev_state = prev->state;
2754 finish_arch_switch(prev);
2755 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
2756 local_irq_disable();
2757 #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */
2758 perf_event_task_sched_in(current);
2759 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
2761 #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */
2762 finish_lock_switch(rq, prev);
2764 fire_sched_in_preempt_notifiers(current);
2767 if (unlikely(prev_state == TASK_DEAD)) {
2769 * Remove function-return probe instances associated with this
2770 * task and put them back on the free list.
2772 kprobe_flush_task(prev);
2773 put_task_struct(prev);
2779 /* assumes rq->lock is held */
2780 static inline void pre_schedule(struct rq *rq, struct task_struct *prev)
2782 if (prev->sched_class->pre_schedule)
2783 prev->sched_class->pre_schedule(rq, prev);
2786 /* rq->lock is NOT held, but preemption is disabled */
2787 static inline void post_schedule(struct rq *rq)
2789 if (rq->post_schedule) {
2790 unsigned long flags;
2792 raw_spin_lock_irqsave(&rq->lock, flags);
2793 if (rq->curr->sched_class->post_schedule)
2794 rq->curr->sched_class->post_schedule(rq);
2795 raw_spin_unlock_irqrestore(&rq->lock, flags);
2797 rq->post_schedule = 0;
2803 static inline void pre_schedule(struct rq *rq, struct task_struct *p)
2807 static inline void post_schedule(struct rq *rq)
2814 * schedule_tail - first thing a freshly forked thread must call.
2815 * @prev: the thread we just switched away from.
2817 asmlinkage void schedule_tail(struct task_struct *prev)
2818 __releases(rq->lock)
2820 struct rq *rq = this_rq();
2822 finish_task_switch(rq, prev);
2825 * FIXME: do we need to worry about rq being invalidated by the
2830 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2831 /* In this case, finish_task_switch does not reenable preemption */
2834 if (current->set_child_tid)
2835 put_user(task_pid_vnr(current), current->set_child_tid);
2839 * context_switch - switch to the new MM and the new
2840 * thread's register state.
2843 context_switch(struct rq *rq, struct task_struct *prev,
2844 struct task_struct *next)
2846 struct mm_struct *mm, *oldmm;
2848 prepare_task_switch(rq, prev, next);
2849 trace_sched_switch(prev, next);
2851 oldmm = prev->active_mm;
2853 * For paravirt, this is coupled with an exit in switch_to to
2854 * combine the page table reload and the switch backend into
2857 arch_start_context_switch(prev);
2860 next->active_mm = oldmm;
2861 atomic_inc(&oldmm->mm_count);
2862 enter_lazy_tlb(oldmm, next);
2864 switch_mm(oldmm, mm, next);
2867 prev->active_mm = NULL;
2868 rq->prev_mm = oldmm;
2871 * Since the runqueue lock will be released by the next
2872 * task (which is an invalid locking op but in the case
2873 * of the scheduler it's an obvious special-case), so we
2874 * do an early lockdep release here:
2876 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2877 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2880 /* Here we just switch the register state and the stack. */
2881 switch_to(prev, next, prev);
2885 * this_rq must be evaluated again because prev may have moved
2886 * CPUs since it called schedule(), thus the 'rq' on its stack
2887 * frame will be invalid.
2889 finish_task_switch(this_rq(), prev);
2893 * nr_running, nr_uninterruptible and nr_context_switches:
2895 * externally visible scheduler statistics: current number of runnable
2896 * threads, current number of uninterruptible-sleeping threads, total
2897 * number of context switches performed since bootup.
2899 unsigned long nr_running(void)
2901 unsigned long i, sum = 0;
2903 for_each_online_cpu(i)
2904 sum += cpu_rq(i)->nr_running;
2909 unsigned long nr_uninterruptible(void)
2911 unsigned long i, sum = 0;
2913 for_each_possible_cpu(i)
2914 sum += cpu_rq(i)->nr_uninterruptible;
2917 * Since we read the counters lockless, it might be slightly
2918 * inaccurate. Do not allow it to go below zero though:
2920 if (unlikely((long)sum < 0))
2926 unsigned long long nr_context_switches(void)
2929 unsigned long long sum = 0;
2931 for_each_possible_cpu(i)
2932 sum += cpu_rq(i)->nr_switches;
2937 unsigned long nr_iowait(void)
2939 unsigned long i, sum = 0;
2941 for_each_possible_cpu(i)
2942 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2947 unsigned long nr_iowait_cpu(int cpu)
2949 struct rq *this = cpu_rq(cpu);
2950 return atomic_read(&this->nr_iowait);
2953 unsigned long this_cpu_load(void)
2955 struct rq *this = this_rq();
2956 return this->cpu_load[0];
2960 /* Variables and functions for calc_load */
2961 static atomic_long_t calc_load_tasks;
2962 static unsigned long calc_load_update;
2963 unsigned long avenrun[3];
2964 EXPORT_SYMBOL(avenrun);
2966 static long calc_load_fold_active(struct rq *this_rq)
2968 long nr_active, delta = 0;
2970 nr_active = this_rq->nr_running;
2971 nr_active += (long) this_rq->nr_uninterruptible;
2973 if (nr_active != this_rq->calc_load_active) {
2974 delta = nr_active - this_rq->calc_load_active;
2975 this_rq->calc_load_active = nr_active;
2983 * For NO_HZ we delay the active fold to the next LOAD_FREQ update.
2985 * When making the ILB scale, we should try to pull this in as well.
2987 static atomic_long_t calc_load_tasks_idle;
2989 static void calc_load_account_idle(struct rq *this_rq)
2993 delta = calc_load_fold_active(this_rq);
2995 atomic_long_add(delta, &calc_load_tasks_idle);
2998 static long calc_load_fold_idle(void)
3003 * Its got a race, we don't care...
3005 if (atomic_long_read(&calc_load_tasks_idle))
3006 delta = atomic_long_xchg(&calc_load_tasks_idle, 0);
3011 static void calc_load_account_idle(struct rq *this_rq)
3015 static inline long calc_load_fold_idle(void)
3022 * get_avenrun - get the load average array
3023 * @loads: pointer to dest load array
3024 * @offset: offset to add
3025 * @shift: shift count to shift the result left
3027 * These values are estimates at best, so no need for locking.
3029 void get_avenrun(unsigned long *loads, unsigned long offset, int shift)
3031 loads[0] = (avenrun[0] + offset) << shift;
3032 loads[1] = (avenrun[1] + offset) << shift;
3033 loads[2] = (avenrun[2] + offset) << shift;
3036 static unsigned long
3037 calc_load(unsigned long load, unsigned long exp, unsigned long active)
3040 load += active * (FIXED_1 - exp);
3041 return load >> FSHIFT;
3045 * calc_load - update the avenrun load estimates 10 ticks after the
3046 * CPUs have updated calc_load_tasks.
3048 void calc_global_load(void)
3050 unsigned long upd = calc_load_update + 10;
3053 if (time_before(jiffies, upd))
3056 active = atomic_long_read(&calc_load_tasks);
3057 active = active > 0 ? active * FIXED_1 : 0;
3059 avenrun[0] = calc_load(avenrun[0], EXP_1, active);
3060 avenrun[1] = calc_load(avenrun[1], EXP_5, active);
3061 avenrun[2] = calc_load(avenrun[2], EXP_15, active);
3063 calc_load_update += LOAD_FREQ;
3067 * Called from update_cpu_load() to periodically update this CPU's
3070 static void calc_load_account_active(struct rq *this_rq)
3074 if (time_before(jiffies, this_rq->calc_load_update))
3077 delta = calc_load_fold_active(this_rq);
3078 delta += calc_load_fold_idle();
3080 atomic_long_add(delta, &calc_load_tasks);
3082 this_rq->calc_load_update += LOAD_FREQ;
3086 * The exact cpuload at various idx values, calculated at every tick would be
3087 * load = (2^idx - 1) / 2^idx * load + 1 / 2^idx * cur_load
3089 * If a cpu misses updates for n-1 ticks (as it was idle) and update gets called
3090 * on nth tick when cpu may be busy, then we have:
3091 * load = ((2^idx - 1) / 2^idx)^(n-1) * load
3092 * load = (2^idx - 1) / 2^idx) * load + 1 / 2^idx * cur_load
3094 * decay_load_missed() below does efficient calculation of
3095 * load = ((2^idx - 1) / 2^idx)^(n-1) * load
3096 * avoiding 0..n-1 loop doing load = ((2^idx - 1) / 2^idx) * load
3098 * The calculation is approximated on a 128 point scale.
3099 * degrade_zero_ticks is the number of ticks after which load at any
3100 * particular idx is approximated to be zero.
3101 * degrade_factor is a precomputed table, a row for each load idx.
3102 * Each column corresponds to degradation factor for a power of two ticks,
3103 * based on 128 point scale.
3105 * row 2, col 3 (=12) says that the degradation at load idx 2 after
3106 * 8 ticks is 12/128 (which is an approximation of exact factor 3^8/4^8).
3108 * With this power of 2 load factors, we can degrade the load n times
3109 * by looking at 1 bits in n and doing as many mult/shift instead of
3110 * n mult/shifts needed by the exact degradation.
3112 #define DEGRADE_SHIFT 7
3113 static const unsigned char
3114 degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128};
3115 static const unsigned char
3116 degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = {
3117 {0, 0, 0, 0, 0, 0, 0, 0},
3118 {64, 32, 8, 0, 0, 0, 0, 0},
3119 {96, 72, 40, 12, 1, 0, 0},
3120 {112, 98, 75, 43, 15, 1, 0},
3121 {120, 112, 98, 76, 45, 16, 2} };
3124 * Update cpu_load for any missed ticks, due to tickless idle. The backlog
3125 * would be when CPU is idle and so we just decay the old load without
3126 * adding any new load.
3128 static unsigned long
3129 decay_load_missed(unsigned long load, unsigned long missed_updates, int idx)
3133 if (!missed_updates)
3136 if (missed_updates >= degrade_zero_ticks[idx])
3140 return load >> missed_updates;
3142 while (missed_updates) {
3143 if (missed_updates % 2)
3144 load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT;
3146 missed_updates >>= 1;
3153 * Update rq->cpu_load[] statistics. This function is usually called every
3154 * scheduler tick (TICK_NSEC). With tickless idle this will not be called
3155 * every tick. We fix it up based on jiffies.
3157 static void update_cpu_load(struct rq *this_rq)
3159 unsigned long this_load = this_rq->load.weight;
3160 unsigned long curr_jiffies = jiffies;
3161 unsigned long pending_updates;
3164 this_rq->nr_load_updates++;
3166 /* Avoid repeated calls on same jiffy, when moving in and out of idle */
3167 if (curr_jiffies == this_rq->last_load_update_tick)
3170 pending_updates = curr_jiffies - this_rq->last_load_update_tick;
3171 this_rq->last_load_update_tick = curr_jiffies;
3173 /* Update our load: */
3174 this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */
3175 for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
3176 unsigned long old_load, new_load;
3178 /* scale is effectively 1 << i now, and >> i divides by scale */
3180 old_load = this_rq->cpu_load[i];
3181 old_load = decay_load_missed(old_load, pending_updates - 1, i);
3182 new_load = this_load;
3184 * Round up the averaging division if load is increasing. This
3185 * prevents us from getting stuck on 9 if the load is 10, for
3188 if (new_load > old_load)
3189 new_load += scale - 1;
3191 this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i;
3194 sched_avg_update(this_rq);
3197 static void update_cpu_load_active(struct rq *this_rq)
3199 update_cpu_load(this_rq);
3201 calc_load_account_active(this_rq);
3207 * sched_exec - execve() is a valuable balancing opportunity, because at
3208 * this point the task has the smallest effective memory and cache footprint.
3210 void sched_exec(void)
3212 struct task_struct *p = current;
3213 unsigned long flags;
3217 rq = task_rq_lock(p, &flags);
3218 dest_cpu = p->sched_class->select_task_rq(rq, p, SD_BALANCE_EXEC, 0);
3219 if (dest_cpu == smp_processor_id())
3223 * select_task_rq() can race against ->cpus_allowed
3225 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed) &&
3226 likely(cpu_active(dest_cpu)) && migrate_task(p, dest_cpu)) {
3227 struct migration_arg arg = { p, dest_cpu };
3229 task_rq_unlock(rq, &flags);
3230 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
3234 task_rq_unlock(rq, &flags);
3239 DEFINE_PER_CPU(struct kernel_stat, kstat);
3241 EXPORT_PER_CPU_SYMBOL(kstat);
3244 * Return any ns on the sched_clock that have not yet been accounted in
3245 * @p in case that task is currently running.
3247 * Called with task_rq_lock() held on @rq.
3249 static u64 do_task_delta_exec(struct task_struct *p, struct rq *rq)
3253 if (task_current(rq, p)) {
3254 update_rq_clock(rq);
3255 ns = rq->clock_task - p->se.exec_start;
3263 unsigned long long task_delta_exec(struct task_struct *p)
3265 unsigned long flags;
3269 rq = task_rq_lock(p, &flags);
3270 ns = do_task_delta_exec(p, rq);
3271 task_rq_unlock(rq, &flags);
3277 * Return accounted runtime for the task.
3278 * In case the task is currently running, return the runtime plus current's
3279 * pending runtime that have not been accounted yet.
3281 unsigned long long task_sched_runtime(struct task_struct *p)
3283 unsigned long flags;
3287 rq = task_rq_lock(p, &flags);
3288 ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq);
3289 task_rq_unlock(rq, &flags);
3295 * Return sum_exec_runtime for the thread group.
3296 * In case the task is currently running, return the sum plus current's
3297 * pending runtime that have not been accounted yet.
3299 * Note that the thread group might have other running tasks as well,
3300 * so the return value not includes other pending runtime that other
3301 * running tasks might have.
3303 unsigned long long thread_group_sched_runtime(struct task_struct *p)
3305 struct task_cputime totals;
3306 unsigned long flags;
3310 rq = task_rq_lock(p, &flags);
3311 thread_group_cputime(p, &totals);
3312 ns = totals.sum_exec_runtime + do_task_delta_exec(p, rq);
3313 task_rq_unlock(rq, &flags);
3319 * Account user cpu time to a process.
3320 * @p: the process that the cpu time gets accounted to
3321 * @cputime: the cpu time spent in user space since the last update
3322 * @cputime_scaled: cputime scaled by cpu frequency
3324 void account_user_time(struct task_struct *p, cputime_t cputime,
3325 cputime_t cputime_scaled)
3327 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3330 /* Add user time to process. */
3331 p->utime = cputime_add(p->utime, cputime);
3332 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
3333 account_group_user_time(p, cputime);
3335 /* Add user time to cpustat. */
3336 tmp = cputime_to_cputime64(cputime);
3337 if (TASK_NICE(p) > 0)
3338 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3340 cpustat->user = cputime64_add(cpustat->user, tmp);
3342 cpuacct_update_stats(p, CPUACCT_STAT_USER, cputime);
3343 /* Account for user time used */
3344 acct_update_integrals(p);
3348 * Account guest cpu time to a process.
3349 * @p: the process that the cpu time gets accounted to
3350 * @cputime: the cpu time spent in virtual machine since the last update
3351 * @cputime_scaled: cputime scaled by cpu frequency
3353 static void account_guest_time(struct task_struct *p, cputime_t cputime,
3354 cputime_t cputime_scaled)
3357 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3359 tmp = cputime_to_cputime64(cputime);
3361 /* Add guest time to process. */
3362 p->utime = cputime_add(p->utime, cputime);
3363 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
3364 account_group_user_time(p, cputime);
3365 p->gtime = cputime_add(p->gtime, cputime);
3367 /* Add guest time to cpustat. */
3368 if (TASK_NICE(p) > 0) {
3369 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3370 cpustat->guest_nice = cputime64_add(cpustat->guest_nice, tmp);
3372 cpustat->user = cputime64_add(cpustat->user, tmp);
3373 cpustat->guest = cputime64_add(cpustat->guest, tmp);
3378 * Account system cpu time to a process.
3379 * @p: the process that the cpu time gets accounted to
3380 * @hardirq_offset: the offset to subtract from hardirq_count()
3381 * @cputime: the cpu time spent in kernel space since the last update
3382 * @cputime_scaled: cputime scaled by cpu frequency
3384 void account_system_time(struct task_struct *p, int hardirq_offset,
3385 cputime_t cputime, cputime_t cputime_scaled)
3387 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3390 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
3391 account_guest_time(p, cputime, cputime_scaled);
3395 /* Add system time to process. */
3396 p->stime = cputime_add(p->stime, cputime);
3397 p->stimescaled = cputime_add(p->stimescaled, cputime_scaled);
3398 account_group_system_time(p, cputime);
3400 /* Add system time to cpustat. */
3401 tmp = cputime_to_cputime64(cputime);
3402 if (hardirq_count() - hardirq_offset)
3403 cpustat->irq = cputime64_add(cpustat->irq, tmp);
3404 else if (in_serving_softirq())
3405 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
3407 cpustat->system = cputime64_add(cpustat->system, tmp);
3409 cpuacct_update_stats(p, CPUACCT_STAT_SYSTEM, cputime);
3411 /* Account for system time used */
3412 acct_update_integrals(p);
3416 * Account for involuntary wait time.
3417 * @steal: the cpu time spent in involuntary wait
3419 void account_steal_time(cputime_t cputime)
3421 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3422 cputime64_t cputime64 = cputime_to_cputime64(cputime);
3424 cpustat->steal = cputime64_add(cpustat->steal, cputime64);
3428 * Account for idle time.
3429 * @cputime: the cpu time spent in idle wait
3431 void account_idle_time(cputime_t cputime)
3433 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3434 cputime64_t cputime64 = cputime_to_cputime64(cputime);
3435 struct rq *rq = this_rq();
3437 if (atomic_read(&rq->nr_iowait) > 0)
3438 cpustat->iowait = cputime64_add(cpustat->iowait, cputime64);
3440 cpustat->idle = cputime64_add(cpustat->idle, cputime64);
3443 #ifndef CONFIG_VIRT_CPU_ACCOUNTING
3446 * Account a single tick of cpu time.
3447 * @p: the process that the cpu time gets accounted to
3448 * @user_tick: indicates if the tick is a user or a system tick
3450 void account_process_tick(struct task_struct *p, int user_tick)
3452 cputime_t one_jiffy_scaled = cputime_to_scaled(cputime_one_jiffy);
3453 struct rq *rq = this_rq();
3456 account_user_time(p, cputime_one_jiffy, one_jiffy_scaled);
3457 else if ((p != rq->idle) || (irq_count() != HARDIRQ_OFFSET))
3458 account_system_time(p, HARDIRQ_OFFSET, cputime_one_jiffy,
3461 account_idle_time(cputime_one_jiffy);
3465 * Account multiple ticks of steal time.
3466 * @p: the process from which the cpu time has been stolen
3467 * @ticks: number of stolen ticks
3469 void account_steal_ticks(unsigned long ticks)
3471 account_steal_time(jiffies_to_cputime(ticks));
3475 * Account multiple ticks of idle time.
3476 * @ticks: number of stolen ticks
3478 void account_idle_ticks(unsigned long ticks)
3480 account_idle_time(jiffies_to_cputime(ticks));
3486 * Use precise platform statistics if available:
3488 #ifdef CONFIG_VIRT_CPU_ACCOUNTING
3489 void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
3495 void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
3497 struct task_cputime cputime;
3499 thread_group_cputime(p, &cputime);
3501 *ut = cputime.utime;
3502 *st = cputime.stime;
3506 #ifndef nsecs_to_cputime
3507 # define nsecs_to_cputime(__nsecs) nsecs_to_jiffies(__nsecs)
3510 void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
3512 cputime_t rtime, utime = p->utime, total = cputime_add(utime, p->stime);
3515 * Use CFS's precise accounting:
3517 rtime = nsecs_to_cputime(p->se.sum_exec_runtime);
3523 do_div(temp, total);
3524 utime = (cputime_t)temp;
3529 * Compare with previous values, to keep monotonicity:
3531 p->prev_utime = max(p->prev_utime, utime);
3532 p->prev_stime = max(p->prev_stime, cputime_sub(rtime, p->prev_utime));
3534 *ut = p->prev_utime;
3535 *st = p->prev_stime;
3539 * Must be called with siglock held.
3541 void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
3543 struct signal_struct *sig = p->signal;
3544 struct task_cputime cputime;
3545 cputime_t rtime, utime, total;
3547 thread_group_cputime(p, &cputime);
3549 total = cputime_add(cputime.utime, cputime.stime);
3550 rtime = nsecs_to_cputime(cputime.sum_exec_runtime);
3555 temp *= cputime.utime;
3556 do_div(temp, total);
3557 utime = (cputime_t)temp;
3561 sig->prev_utime = max(sig->prev_utime, utime);
3562 sig->prev_stime = max(sig->prev_stime,
3563 cputime_sub(rtime, sig->prev_utime));
3565 *ut = sig->prev_utime;
3566 *st = sig->prev_stime;
3571 * This function gets called by the timer code, with HZ frequency.
3572 * We call it with interrupts disabled.
3574 * It also gets called by the fork code, when changing the parent's
3577 void scheduler_tick(void)
3579 int cpu = smp_processor_id();
3580 struct rq *rq = cpu_rq(cpu);
3581 struct task_struct *curr = rq->curr;
3585 raw_spin_lock(&rq->lock);
3586 update_rq_clock(rq);
3587 update_cpu_load_active(rq);
3588 curr->sched_class->task_tick(rq, curr, 0);
3589 raw_spin_unlock(&rq->lock);
3591 perf_event_task_tick();
3594 rq->idle_at_tick = idle_cpu(cpu);
3595 trigger_load_balance(rq, cpu);
3599 notrace unsigned long get_parent_ip(unsigned long addr)
3601 if (in_lock_functions(addr)) {
3602 addr = CALLER_ADDR2;
3603 if (in_lock_functions(addr))
3604 addr = CALLER_ADDR3;
3609 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
3610 defined(CONFIG_PREEMPT_TRACER))
3612 void __kprobes add_preempt_count(int val)
3614 #ifdef CONFIG_DEBUG_PREEMPT
3618 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3621 preempt_count() += val;
3622 #ifdef CONFIG_DEBUG_PREEMPT
3624 * Spinlock count overflowing soon?
3626 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3629 if (preempt_count() == val)
3630 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
3632 EXPORT_SYMBOL(add_preempt_count);
3634 void __kprobes sub_preempt_count(int val)
3636 #ifdef CONFIG_DEBUG_PREEMPT
3640 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3643 * Is the spinlock portion underflowing?
3645 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3646 !(preempt_count() & PREEMPT_MASK)))
3650 if (preempt_count() == val)
3651 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
3652 preempt_count() -= val;
3654 EXPORT_SYMBOL(sub_preempt_count);
3659 * Print scheduling while atomic bug:
3661 static noinline void __schedule_bug(struct task_struct *prev)
3663 struct pt_regs *regs = get_irq_regs();
3665 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3666 prev->comm, prev->pid, preempt_count());
3668 debug_show_held_locks(prev);
3670 if (irqs_disabled())
3671 print_irqtrace_events(prev);
3680 * Various schedule()-time debugging checks and statistics:
3682 static inline void schedule_debug(struct task_struct *prev)
3685 * Test if we are atomic. Since do_exit() needs to call into
3686 * schedule() atomically, we ignore that path for now.
3687 * Otherwise, whine if we are scheduling when we should not be.
3689 if (unlikely(in_atomic_preempt_off() && !prev->exit_state))
3690 __schedule_bug(prev);
3692 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3694 schedstat_inc(this_rq(), sched_count);
3695 #ifdef CONFIG_SCHEDSTATS
3696 if (unlikely(prev->lock_depth >= 0)) {
3697 schedstat_inc(this_rq(), bkl_count);
3698 schedstat_inc(prev, sched_info.bkl_count);
3703 static void put_prev_task(struct rq *rq, struct task_struct *prev)
3706 update_rq_clock(rq);
3707 rq->skip_clock_update = 0;
3708 prev->sched_class->put_prev_task(rq, prev);
3712 * Pick up the highest-prio task:
3714 static inline struct task_struct *
3715 pick_next_task(struct rq *rq)
3717 const struct sched_class *class;
3718 struct task_struct *p;
3721 * Optimization: we know that if all tasks are in
3722 * the fair class we can call that function directly:
3724 if (likely(rq->nr_running == rq->cfs.nr_running)) {
3725 p = fair_sched_class.pick_next_task(rq);
3730 for_each_class(class) {
3731 p = class->pick_next_task(rq);
3736 BUG(); /* the idle class will always have a runnable task */
3740 * schedule() is the main scheduler function.
3742 asmlinkage void __sched schedule(void)
3744 struct task_struct *prev, *next;
3745 unsigned long *switch_count;
3751 cpu = smp_processor_id();
3753 rcu_note_context_switch(cpu);
3756 release_kernel_lock(prev);
3757 need_resched_nonpreemptible:
3759 schedule_debug(prev);
3761 if (sched_feat(HRTICK))
3764 raw_spin_lock_irq(&rq->lock);
3765 clear_tsk_need_resched(prev);
3767 switch_count = &prev->nivcsw;
3768 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3769 if (unlikely(signal_pending_state(prev->state, prev))) {
3770 prev->state = TASK_RUNNING;
3773 * If a worker is going to sleep, notify and
3774 * ask workqueue whether it wants to wake up a
3775 * task to maintain concurrency. If so, wake
3778 if (prev->flags & PF_WQ_WORKER) {
3779 struct task_struct *to_wakeup;
3781 to_wakeup = wq_worker_sleeping(prev, cpu);
3783 try_to_wake_up_local(to_wakeup);
3785 deactivate_task(rq, prev, DEQUEUE_SLEEP);
3787 switch_count = &prev->nvcsw;
3790 pre_schedule(rq, prev);
3792 if (unlikely(!rq->nr_running))
3793 idle_balance(cpu, rq);
3795 put_prev_task(rq, prev);
3796 next = pick_next_task(rq);
3798 if (likely(prev != next)) {
3799 sched_info_switch(prev, next);
3800 perf_event_task_sched_out(prev, next);
3806 context_switch(rq, prev, next); /* unlocks the rq */
3808 * The context switch have flipped the stack from under us
3809 * and restored the local variables which were saved when
3810 * this task called schedule() in the past. prev == current
3811 * is still correct, but it can be moved to another cpu/rq.
3813 cpu = smp_processor_id();
3816 raw_spin_unlock_irq(&rq->lock);
3820 if (unlikely(reacquire_kernel_lock(prev)))
3821 goto need_resched_nonpreemptible;
3823 preempt_enable_no_resched();
3827 EXPORT_SYMBOL(schedule);
3829 #ifdef CONFIG_MUTEX_SPIN_ON_OWNER
3831 * Look out! "owner" is an entirely speculative pointer
3832 * access and not reliable.
3834 int mutex_spin_on_owner(struct mutex *lock, struct thread_info *owner)
3839 if (!sched_feat(OWNER_SPIN))
3842 #ifdef CONFIG_DEBUG_PAGEALLOC
3844 * Need to access the cpu field knowing that
3845 * DEBUG_PAGEALLOC could have unmapped it if
3846 * the mutex owner just released it and exited.
3848 if (probe_kernel_address(&owner->cpu, cpu))
3855 * Even if the access succeeded (likely case),
3856 * the cpu field may no longer be valid.
3858 if (cpu >= nr_cpumask_bits)
3862 * We need to validate that we can do a
3863 * get_cpu() and that we have the percpu area.
3865 if (!cpu_online(cpu))
3872 * Owner changed, break to re-assess state.
3874 if (lock->owner != owner) {
3876 * If the lock has switched to a different owner,
3877 * we likely have heavy contention. Return 0 to quit
3878 * optimistic spinning and not contend further:
3886 * Is that owner really running on that cpu?
3888 if (task_thread_info(rq->curr) != owner || need_resched())
3898 #ifdef CONFIG_PREEMPT
3900 * this is the entry point to schedule() from in-kernel preemption
3901 * off of preempt_enable. Kernel preemptions off return from interrupt
3902 * occur there and call schedule directly.
3904 asmlinkage void __sched notrace preempt_schedule(void)
3906 struct thread_info *ti = current_thread_info();
3909 * If there is a non-zero preempt_count or interrupts are disabled,
3910 * we do not want to preempt the current task. Just return..
3912 if (likely(ti->preempt_count || irqs_disabled()))
3916 add_preempt_count_notrace(PREEMPT_ACTIVE);
3918 sub_preempt_count_notrace(PREEMPT_ACTIVE);
3921 * Check again in case we missed a preemption opportunity
3922 * between schedule and now.
3925 } while (need_resched());
3927 EXPORT_SYMBOL(preempt_schedule);
3930 * this is the entry point to schedule() from kernel preemption
3931 * off of irq context.
3932 * Note, that this is called and return with irqs disabled. This will
3933 * protect us against recursive calling from irq.
3935 asmlinkage void __sched preempt_schedule_irq(void)
3937 struct thread_info *ti = current_thread_info();
3939 /* Catch callers which need to be fixed */
3940 BUG_ON(ti->preempt_count || !irqs_disabled());
3943 add_preempt_count(PREEMPT_ACTIVE);
3946 local_irq_disable();
3947 sub_preempt_count(PREEMPT_ACTIVE);
3950 * Check again in case we missed a preemption opportunity
3951 * between schedule and now.
3954 } while (need_resched());
3957 #endif /* CONFIG_PREEMPT */
3959 int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
3962 return try_to_wake_up(curr->private, mode, wake_flags);
3964 EXPORT_SYMBOL(default_wake_function);
3967 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3968 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3969 * number) then we wake all the non-exclusive tasks and one exclusive task.
3971 * There are circumstances in which we can try to wake a task which has already
3972 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3973 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3975 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3976 int nr_exclusive, int wake_flags, void *key)
3978 wait_queue_t *curr, *next;
3980 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
3981 unsigned flags = curr->flags;
3983 if (curr->func(curr, mode, wake_flags, key) &&
3984 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
3990 * __wake_up - wake up threads blocked on a waitqueue.
3992 * @mode: which threads
3993 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3994 * @key: is directly passed to the wakeup function
3996 * It may be assumed that this function implies a write memory barrier before
3997 * changing the task state if and only if any tasks are woken up.
3999 void __wake_up(wait_queue_head_t *q, unsigned int mode,
4000 int nr_exclusive, void *key)
4002 unsigned long flags;
4004 spin_lock_irqsave(&q->lock, flags);
4005 __wake_up_common(q, mode, nr_exclusive, 0, key);
4006 spin_unlock_irqrestore(&q->lock, flags);
4008 EXPORT_SYMBOL(__wake_up);
4011 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4013 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4015 __wake_up_common(q, mode, 1, 0, NULL);
4017 EXPORT_SYMBOL_GPL(__wake_up_locked);
4019 void __wake_up_locked_key(wait_queue_head_t *q, unsigned int mode, void *key)
4021 __wake_up_common(q, mode, 1, 0, key);
4025 * __wake_up_sync_key - wake up threads blocked on a waitqueue.
4027 * @mode: which threads
4028 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4029 * @key: opaque value to be passed to wakeup targets
4031 * The sync wakeup differs that the waker knows that it will schedule
4032 * away soon, so while the target thread will be woken up, it will not
4033 * be migrated to another CPU - ie. the two threads are 'synchronized'
4034 * with each other. This can prevent needless bouncing between CPUs.
4036 * On UP it can prevent extra preemption.
4038 * It may be assumed that this function implies a write memory barrier before
4039 * changing the task state if and only if any tasks are woken up.
4041 void __wake_up_sync_key(wait_queue_head_t *q, unsigned int mode,
4042 int nr_exclusive, void *key)
4044 unsigned long flags;
4045 int wake_flags = WF_SYNC;
4050 if (unlikely(!nr_exclusive))
4053 spin_lock_irqsave(&q->lock, flags);
4054 __wake_up_common(q, mode, nr_exclusive, wake_flags, key);
4055 spin_unlock_irqrestore(&q->lock, flags);
4057 EXPORT_SYMBOL_GPL(__wake_up_sync_key);
4060 * __wake_up_sync - see __wake_up_sync_key()
4062 void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4064 __wake_up_sync_key(q, mode, nr_exclusive, NULL);
4066 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
4069 * complete: - signals a single thread waiting on this completion
4070 * @x: holds the state of this particular completion
4072 * This will wake up a single thread waiting on this completion. Threads will be
4073 * awakened in the same order in which they were queued.
4075 * See also complete_all(), wait_for_completion() and related routines.
4077 * It may be assumed that this function implies a write memory barrier before
4078 * changing the task state if and only if any tasks are woken up.
4080 void complete(struct completion *x)
4082 unsigned long flags;
4084 spin_lock_irqsave(&x->wait.lock, flags);
4086 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4087 spin_unlock_irqrestore(&x->wait.lock, flags);
4089 EXPORT_SYMBOL(complete);
4092 * complete_all: - signals all threads waiting on this completion
4093 * @x: holds the state of this particular completion
4095 * This will wake up all threads waiting on this particular completion event.
4097 * It may be assumed that this function implies a write memory barrier before
4098 * changing the task state if and only if any tasks are woken up.
4100 void complete_all(struct completion *x)
4102 unsigned long flags;
4104 spin_lock_irqsave(&x->wait.lock, flags);
4105 x->done += UINT_MAX/2;
4106 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4107 spin_unlock_irqrestore(&x->wait.lock, flags);
4109 EXPORT_SYMBOL(complete_all);
4111 static inline long __sched
4112 do_wait_for_common(struct completion *x, long timeout, int state)
4115 DECLARE_WAITQUEUE(wait, current);
4117 __add_wait_queue_tail_exclusive(&x->wait, &wait);
4119 if (signal_pending_state(state, current)) {
4120 timeout = -ERESTARTSYS;
4123 __set_current_state(state);
4124 spin_unlock_irq(&x->wait.lock);
4125 timeout = schedule_timeout(timeout);
4126 spin_lock_irq(&x->wait.lock);
4127 } while (!x->done && timeout);
4128 __remove_wait_queue(&x->wait, &wait);
4133 return timeout ?: 1;
4137 wait_for_common(struct completion *x, long timeout, int state)
4141 spin_lock_irq(&x->wait.lock);
4142 timeout = do_wait_for_common(x, timeout, state);
4143 spin_unlock_irq(&x->wait.lock);
4148 * wait_for_completion: - waits for completion of a task
4149 * @x: holds the state of this particular completion
4151 * This waits to be signaled for completion of a specific task. It is NOT
4152 * interruptible and there is no timeout.
4154 * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
4155 * and interrupt capability. Also see complete().
4157 void __sched wait_for_completion(struct completion *x)
4159 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4161 EXPORT_SYMBOL(wait_for_completion);
4164 * wait_for_completion_timeout: - waits for completion of a task (w/timeout)
4165 * @x: holds the state of this particular completion
4166 * @timeout: timeout value in jiffies
4168 * This waits for either a completion of a specific task to be signaled or for a
4169 * specified timeout to expire. The timeout is in jiffies. It is not
4172 unsigned long __sched
4173 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4175 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4177 EXPORT_SYMBOL(wait_for_completion_timeout);
4180 * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
4181 * @x: holds the state of this particular completion
4183 * This waits for completion of a specific task to be signaled. It is
4186 int __sched wait_for_completion_interruptible(struct completion *x)
4188 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4189 if (t == -ERESTARTSYS)
4193 EXPORT_SYMBOL(wait_for_completion_interruptible);
4196 * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
4197 * @x: holds the state of this particular completion
4198 * @timeout: timeout value in jiffies
4200 * This waits for either a completion of a specific task to be signaled or for a
4201 * specified timeout to expire. It is interruptible. The timeout is in jiffies.
4203 unsigned long __sched
4204 wait_for_completion_interruptible_timeout(struct completion *x,
4205 unsigned long timeout)
4207 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4209 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4212 * wait_for_completion_killable: - waits for completion of a task (killable)
4213 * @x: holds the state of this particular completion
4215 * This waits to be signaled for completion of a specific task. It can be
4216 * interrupted by a kill signal.
4218 int __sched wait_for_completion_killable(struct completion *x)
4220 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4221 if (t == -ERESTARTSYS)
4225 EXPORT_SYMBOL(wait_for_completion_killable);
4228 * wait_for_completion_killable_timeout: - waits for completion of a task (w/(to,killable))
4229 * @x: holds the state of this particular completion
4230 * @timeout: timeout value in jiffies
4232 * This waits for either a completion of a specific task to be
4233 * signaled or for a specified timeout to expire. It can be
4234 * interrupted by a kill signal. The timeout is in jiffies.
4236 unsigned long __sched
4237 wait_for_completion_killable_timeout(struct completion *x,
4238 unsigned long timeout)
4240 return wait_for_common(x, timeout, TASK_KILLABLE);
4242 EXPORT_SYMBOL(wait_for_completion_killable_timeout);
4245 * try_wait_for_completion - try to decrement a completion without blocking
4246 * @x: completion structure
4248 * Returns: 0 if a decrement cannot be done without blocking
4249 * 1 if a decrement succeeded.
4251 * If a completion is being used as a counting completion,
4252 * attempt to decrement the counter without blocking. This
4253 * enables us to avoid waiting if the resource the completion
4254 * is protecting is not available.
4256 bool try_wait_for_completion(struct completion *x)
4258 unsigned long flags;
4261 spin_lock_irqsave(&x->wait.lock, flags);
4266 spin_unlock_irqrestore(&x->wait.lock, flags);
4269 EXPORT_SYMBOL(try_wait_for_completion);
4272 * completion_done - Test to see if a completion has any waiters
4273 * @x: completion structure
4275 * Returns: 0 if there are waiters (wait_for_completion() in progress)
4276 * 1 if there are no waiters.
4279 bool completion_done(struct completion *x)
4281 unsigned long flags;
4284 spin_lock_irqsave(&x->wait.lock, flags);
4287 spin_unlock_irqrestore(&x->wait.lock, flags);
4290 EXPORT_SYMBOL(completion_done);
4293 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4295 unsigned long flags;
4298 init_waitqueue_entry(&wait, current);
4300 __set_current_state(state);
4302 spin_lock_irqsave(&q->lock, flags);
4303 __add_wait_queue(q, &wait);
4304 spin_unlock(&q->lock);
4305 timeout = schedule_timeout(timeout);
4306 spin_lock_irq(&q->lock);
4307 __remove_wait_queue(q, &wait);
4308 spin_unlock_irqrestore(&q->lock, flags);
4313 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4315 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4317 EXPORT_SYMBOL(interruptible_sleep_on);
4320 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4322 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4324 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4326 void __sched sleep_on(wait_queue_head_t *q)
4328 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4330 EXPORT_SYMBOL(sleep_on);
4332 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4334 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
4336 EXPORT_SYMBOL(sleep_on_timeout);
4338 #ifdef CONFIG_RT_MUTEXES
4341 * rt_mutex_setprio - set the current priority of a task
4343 * @prio: prio value (kernel-internal form)
4345 * This function changes the 'effective' priority of a task. It does
4346 * not touch ->normal_prio like __setscheduler().
4348 * Used by the rt_mutex code to implement priority inheritance logic.
4350 void rt_mutex_setprio(struct task_struct *p, int prio)
4352 unsigned long flags;
4353 int oldprio, on_rq, running;
4355 const struct sched_class *prev_class;
4357 BUG_ON(prio < 0 || prio > MAX_PRIO);
4359 rq = task_rq_lock(p, &flags);
4361 trace_sched_pi_setprio(p, prio);
4363 prev_class = p->sched_class;
4364 on_rq = p->se.on_rq;
4365 running = task_current(rq, p);
4367 dequeue_task(rq, p, 0);
4369 p->sched_class->put_prev_task(rq, p);
4372 p->sched_class = &rt_sched_class;
4374 p->sched_class = &fair_sched_class;
4379 p->sched_class->set_curr_task(rq);
4381 enqueue_task(rq, p, oldprio < prio ? ENQUEUE_HEAD : 0);
4383 check_class_changed(rq, p, prev_class, oldprio, running);
4385 task_rq_unlock(rq, &flags);
4390 void set_user_nice(struct task_struct *p, long nice)
4392 int old_prio, delta, on_rq;
4393 unsigned long flags;
4396 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4399 * We have to be careful, if called from sys_setpriority(),
4400 * the task might be in the middle of scheduling on another CPU.
4402 rq = task_rq_lock(p, &flags);
4404 * The RT priorities are set via sched_setscheduler(), but we still
4405 * allow the 'normal' nice value to be set - but as expected
4406 * it wont have any effect on scheduling until the task is
4407 * SCHED_FIFO/SCHED_RR:
4409 if (task_has_rt_policy(p)) {
4410 p->static_prio = NICE_TO_PRIO(nice);
4413 on_rq = p->se.on_rq;
4415 dequeue_task(rq, p, 0);
4417 p->static_prio = NICE_TO_PRIO(nice);
4420 p->prio = effective_prio(p);
4421 delta = p->prio - old_prio;
4424 enqueue_task(rq, p, 0);
4426 * If the task increased its priority or is running and
4427 * lowered its priority, then reschedule its CPU:
4429 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4430 resched_task(rq->curr);
4433 task_rq_unlock(rq, &flags);
4435 EXPORT_SYMBOL(set_user_nice);
4438 * can_nice - check if a task can reduce its nice value
4442 int can_nice(const struct task_struct *p, const int nice)
4444 /* convert nice value [19,-20] to rlimit style value [1,40] */
4445 int nice_rlim = 20 - nice;
4447 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
4448 capable(CAP_SYS_NICE));
4451 #ifdef __ARCH_WANT_SYS_NICE
4454 * sys_nice - change the priority of the current process.
4455 * @increment: priority increment
4457 * sys_setpriority is a more generic, but much slower function that
4458 * does similar things.
4460 SYSCALL_DEFINE1(nice, int, increment)
4465 * Setpriority might change our priority at the same moment.
4466 * We don't have to worry. Conceptually one call occurs first
4467 * and we have a single winner.
4469 if (increment < -40)
4474 nice = TASK_NICE(current) + increment;
4480 if (increment < 0 && !can_nice(current, nice))
4483 retval = security_task_setnice(current, nice);
4487 set_user_nice(current, nice);
4494 * task_prio - return the priority value of a given task.
4495 * @p: the task in question.
4497 * This is the priority value as seen by users in /proc.
4498 * RT tasks are offset by -200. Normal tasks are centered
4499 * around 0, value goes from -16 to +15.
4501 int task_prio(const struct task_struct *p)
4503 return p->prio - MAX_RT_PRIO;
4507 * task_nice - return the nice value of a given task.
4508 * @p: the task in question.
4510 int task_nice(const struct task_struct *p)
4512 return TASK_NICE(p);
4514 EXPORT_SYMBOL(task_nice);
4517 * idle_cpu - is a given cpu idle currently?
4518 * @cpu: the processor in question.
4520 int idle_cpu(int cpu)
4522 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
4526 * idle_task - return the idle task for a given cpu.
4527 * @cpu: the processor in question.
4529 struct task_struct *idle_task(int cpu)
4531 return cpu_rq(cpu)->idle;
4535 * find_process_by_pid - find a process with a matching PID value.
4536 * @pid: the pid in question.
4538 static struct task_struct *find_process_by_pid(pid_t pid)
4540 return pid ? find_task_by_vpid(pid) : current;
4543 /* Actually do priority change: must hold rq lock. */
4545 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
4547 BUG_ON(p->se.on_rq);
4550 p->rt_priority = prio;
4551 p->normal_prio = normal_prio(p);
4552 /* we are holding p->pi_lock already */
4553 p->prio = rt_mutex_getprio(p);
4554 if (rt_prio(p->prio))
4555 p->sched_class = &rt_sched_class;
4557 p->sched_class = &fair_sched_class;
4562 * check the target process has a UID that matches the current process's
4564 static bool check_same_owner(struct task_struct *p)
4566 const struct cred *cred = current_cred(), *pcred;
4570 pcred = __task_cred(p);
4571 match = (cred->euid == pcred->euid ||
4572 cred->euid == pcred->uid);
4577 static int __sched_setscheduler(struct task_struct *p, int policy,
4578 const struct sched_param *param, bool user)
4580 int retval, oldprio, oldpolicy = -1, on_rq, running;
4581 unsigned long flags;
4582 const struct sched_class *prev_class;
4586 /* may grab non-irq protected spin_locks */
4587 BUG_ON(in_interrupt());
4589 /* double check policy once rq lock held */
4591 reset_on_fork = p->sched_reset_on_fork;
4592 policy = oldpolicy = p->policy;
4594 reset_on_fork = !!(policy & SCHED_RESET_ON_FORK);
4595 policy &= ~SCHED_RESET_ON_FORK;
4597 if (policy != SCHED_FIFO && policy != SCHED_RR &&
4598 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
4599 policy != SCHED_IDLE)
4604 * Valid priorities for SCHED_FIFO and SCHED_RR are
4605 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4606 * SCHED_BATCH and SCHED_IDLE is 0.
4608 if (param->sched_priority < 0 ||
4609 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
4610 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
4612 if (rt_policy(policy) != (param->sched_priority != 0))
4616 * Allow unprivileged RT tasks to decrease priority:
4618 if (user && !capable(CAP_SYS_NICE)) {
4619 if (rt_policy(policy)) {
4620 unsigned long rlim_rtprio =
4621 task_rlimit(p, RLIMIT_RTPRIO);
4623 /* can't set/change the rt policy */
4624 if (policy != p->policy && !rlim_rtprio)
4627 /* can't increase priority */
4628 if (param->sched_priority > p->rt_priority &&
4629 param->sched_priority > rlim_rtprio)
4633 * Like positive nice levels, dont allow tasks to
4634 * move out of SCHED_IDLE either:
4636 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
4639 /* can't change other user's priorities */
4640 if (!check_same_owner(p))
4643 /* Normal users shall not reset the sched_reset_on_fork flag */
4644 if (p->sched_reset_on_fork && !reset_on_fork)
4649 retval = security_task_setscheduler(p);
4655 * make sure no PI-waiters arrive (or leave) while we are
4656 * changing the priority of the task:
4658 raw_spin_lock_irqsave(&p->pi_lock, flags);
4660 * To be able to change p->policy safely, the apropriate
4661 * runqueue lock must be held.
4663 rq = __task_rq_lock(p);
4666 * Changing the policy of the stop threads its a very bad idea
4668 if (p == rq->stop) {
4669 __task_rq_unlock(rq);
4670 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4674 #ifdef CONFIG_RT_GROUP_SCHED
4677 * Do not allow realtime tasks into groups that have no runtime
4680 if (rt_bandwidth_enabled() && rt_policy(policy) &&
4681 task_group(p)->rt_bandwidth.rt_runtime == 0) {
4682 __task_rq_unlock(rq);
4683 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4689 /* recheck policy now with rq lock held */
4690 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4691 policy = oldpolicy = -1;
4692 __task_rq_unlock(rq);
4693 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4696 on_rq = p->se.on_rq;
4697 running = task_current(rq, p);
4699 deactivate_task(rq, p, 0);
4701 p->sched_class->put_prev_task(rq, p);
4703 p->sched_reset_on_fork = reset_on_fork;
4706 prev_class = p->sched_class;
4707 __setscheduler(rq, p, policy, param->sched_priority);
4710 p->sched_class->set_curr_task(rq);
4712 activate_task(rq, p, 0);
4714 check_class_changed(rq, p, prev_class, oldprio, running);
4716 __task_rq_unlock(rq);
4717 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4719 rt_mutex_adjust_pi(p);
4725 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4726 * @p: the task in question.
4727 * @policy: new policy.
4728 * @param: structure containing the new RT priority.
4730 * NOTE that the task may be already dead.
4732 int sched_setscheduler(struct task_struct *p, int policy,
4733 const struct sched_param *param)
4735 return __sched_setscheduler(p, policy, param, true);
4737 EXPORT_SYMBOL_GPL(sched_setscheduler);
4740 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4741 * @p: the task in question.
4742 * @policy: new policy.
4743 * @param: structure containing the new RT priority.
4745 * Just like sched_setscheduler, only don't bother checking if the
4746 * current context has permission. For example, this is needed in
4747 * stop_machine(): we create temporary high priority worker threads,
4748 * but our caller might not have that capability.
4750 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
4751 const struct sched_param *param)
4753 return __sched_setscheduler(p, policy, param, false);
4757 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4759 struct sched_param lparam;
4760 struct task_struct *p;
4763 if (!param || pid < 0)
4765 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4770 p = find_process_by_pid(pid);
4772 retval = sched_setscheduler(p, policy, &lparam);
4779 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4780 * @pid: the pid in question.
4781 * @policy: new policy.
4782 * @param: structure containing the new RT priority.
4784 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
4785 struct sched_param __user *, param)
4787 /* negative values for policy are not valid */
4791 return do_sched_setscheduler(pid, policy, param);
4795 * sys_sched_setparam - set/change the RT priority of a thread
4796 * @pid: the pid in question.
4797 * @param: structure containing the new RT priority.
4799 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
4801 return do_sched_setscheduler(pid, -1, param);
4805 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4806 * @pid: the pid in question.
4808 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
4810 struct task_struct *p;
4818 p = find_process_by_pid(pid);
4820 retval = security_task_getscheduler(p);
4823 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
4830 * sys_sched_getparam - get the RT priority of a thread
4831 * @pid: the pid in question.
4832 * @param: structure containing the RT priority.
4834 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
4836 struct sched_param lp;
4837 struct task_struct *p;
4840 if (!param || pid < 0)
4844 p = find_process_by_pid(pid);
4849 retval = security_task_getscheduler(p);
4853 lp.sched_priority = p->rt_priority;
4857 * This one might sleep, we cannot do it with a spinlock held ...
4859 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4868 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
4870 cpumask_var_t cpus_allowed, new_mask;
4871 struct task_struct *p;
4877 p = find_process_by_pid(pid);
4884 /* Prevent p going away */
4888 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4892 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4894 goto out_free_cpus_allowed;
4897 if (!check_same_owner(p) && !capable(CAP_SYS_NICE))
4900 retval = security_task_setscheduler(p);
4904 cpuset_cpus_allowed(p, cpus_allowed);
4905 cpumask_and(new_mask, in_mask, cpus_allowed);
4907 retval = set_cpus_allowed_ptr(p, new_mask);
4910 cpuset_cpus_allowed(p, cpus_allowed);
4911 if (!cpumask_subset(new_mask, cpus_allowed)) {
4913 * We must have raced with a concurrent cpuset
4914 * update. Just reset the cpus_allowed to the
4915 * cpuset's cpus_allowed
4917 cpumask_copy(new_mask, cpus_allowed);
4922 free_cpumask_var(new_mask);
4923 out_free_cpus_allowed:
4924 free_cpumask_var(cpus_allowed);
4931 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4932 struct cpumask *new_mask)
4934 if (len < cpumask_size())
4935 cpumask_clear(new_mask);
4936 else if (len > cpumask_size())
4937 len = cpumask_size();
4939 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4943 * sys_sched_setaffinity - set the cpu affinity of a process
4944 * @pid: pid of the process
4945 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4946 * @user_mask_ptr: user-space pointer to the new cpu mask
4948 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4949 unsigned long __user *, user_mask_ptr)
4951 cpumask_var_t new_mask;
4954 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4957 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4959 retval = sched_setaffinity(pid, new_mask);
4960 free_cpumask_var(new_mask);
4964 long sched_getaffinity(pid_t pid, struct cpumask *mask)
4966 struct task_struct *p;
4967 unsigned long flags;
4975 p = find_process_by_pid(pid);
4979 retval = security_task_getscheduler(p);
4983 rq = task_rq_lock(p, &flags);
4984 cpumask_and(mask, &p->cpus_allowed, cpu_online_mask);
4985 task_rq_unlock(rq, &flags);
4995 * sys_sched_getaffinity - get the cpu affinity of a process
4996 * @pid: pid of the process
4997 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4998 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5000 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
5001 unsigned long __user *, user_mask_ptr)
5006 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
5008 if (len & (sizeof(unsigned long)-1))
5011 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
5014 ret = sched_getaffinity(pid, mask);
5016 size_t retlen = min_t(size_t, len, cpumask_size());
5018 if (copy_to_user(user_mask_ptr, mask, retlen))
5023 free_cpumask_var(mask);
5029 * sys_sched_yield - yield the current processor to other threads.
5031 * This function yields the current CPU to other tasks. If there are no
5032 * other threads running on this CPU then this function will return.
5034 SYSCALL_DEFINE0(sched_yield)
5036 struct rq *rq = this_rq_lock();
5038 schedstat_inc(rq, yld_count);
5039 current->sched_class->yield_task(rq);
5042 * Since we are going to call schedule() anyway, there's
5043 * no need to preempt or enable interrupts:
5045 __release(rq->lock);
5046 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5047 do_raw_spin_unlock(&rq->lock);
5048 preempt_enable_no_resched();
5055 static inline int should_resched(void)
5057 return need_resched() && !(preempt_count() & PREEMPT_ACTIVE);
5060 static void __cond_resched(void)
5062 add_preempt_count(PREEMPT_ACTIVE);
5064 sub_preempt_count(PREEMPT_ACTIVE);
5067 int __sched _cond_resched(void)
5069 if (should_resched()) {
5075 EXPORT_SYMBOL(_cond_resched);
5078 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
5079 * call schedule, and on return reacquire the lock.
5081 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5082 * operations here to prevent schedule() from being called twice (once via
5083 * spin_unlock(), once by hand).
5085 int __cond_resched_lock(spinlock_t *lock)
5087 int resched = should_resched();
5090 lockdep_assert_held(lock);
5092 if (spin_needbreak(lock) || resched) {
5103 EXPORT_SYMBOL(__cond_resched_lock);
5105 int __sched __cond_resched_softirq(void)
5107 BUG_ON(!in_softirq());
5109 if (should_resched()) {
5117 EXPORT_SYMBOL(__cond_resched_softirq);
5120 * yield - yield the current processor to other threads.
5122 * This is a shortcut for kernel-space yielding - it marks the
5123 * thread runnable and calls sys_sched_yield().
5125 void __sched yield(void)
5127 set_current_state(TASK_RUNNING);
5130 EXPORT_SYMBOL(yield);
5133 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5134 * that process accounting knows that this is a task in IO wait state.
5136 void __sched io_schedule(void)
5138 struct rq *rq = raw_rq();
5140 delayacct_blkio_start();
5141 atomic_inc(&rq->nr_iowait);
5142 current->in_iowait = 1;
5144 current->in_iowait = 0;
5145 atomic_dec(&rq->nr_iowait);
5146 delayacct_blkio_end();
5148 EXPORT_SYMBOL(io_schedule);
5150 long __sched io_schedule_timeout(long timeout)
5152 struct rq *rq = raw_rq();
5155 delayacct_blkio_start();
5156 atomic_inc(&rq->nr_iowait);
5157 current->in_iowait = 1;
5158 ret = schedule_timeout(timeout);
5159 current->in_iowait = 0;
5160 atomic_dec(&rq->nr_iowait);
5161 delayacct_blkio_end();
5166 * sys_sched_get_priority_max - return maximum RT priority.
5167 * @policy: scheduling class.
5169 * this syscall returns the maximum rt_priority that can be used
5170 * by a given scheduling class.
5172 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
5179 ret = MAX_USER_RT_PRIO-1;
5191 * sys_sched_get_priority_min - return minimum RT priority.
5192 * @policy: scheduling class.
5194 * this syscall returns the minimum rt_priority that can be used
5195 * by a given scheduling class.
5197 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
5215 * sys_sched_rr_get_interval - return the default timeslice of a process.
5216 * @pid: pid of the process.
5217 * @interval: userspace pointer to the timeslice value.
5219 * this syscall writes the default timeslice value of a given process
5220 * into the user-space timespec buffer. A value of '0' means infinity.
5222 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
5223 struct timespec __user *, interval)
5225 struct task_struct *p;
5226 unsigned int time_slice;
5227 unsigned long flags;
5237 p = find_process_by_pid(pid);
5241 retval = security_task_getscheduler(p);
5245 rq = task_rq_lock(p, &flags);
5246 time_slice = p->sched_class->get_rr_interval(rq, p);
5247 task_rq_unlock(rq, &flags);
5250 jiffies_to_timespec(time_slice, &t);
5251 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5259 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
5261 void sched_show_task(struct task_struct *p)
5263 unsigned long free = 0;
5266 state = p->state ? __ffs(p->state) + 1 : 0;
5267 printk(KERN_INFO "%-15.15s %c", p->comm,
5268 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5269 #if BITS_PER_LONG == 32
5270 if (state == TASK_RUNNING)
5271 printk(KERN_CONT " running ");
5273 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5275 if (state == TASK_RUNNING)
5276 printk(KERN_CONT " running task ");
5278 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5280 #ifdef CONFIG_DEBUG_STACK_USAGE
5281 free = stack_not_used(p);
5283 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
5284 task_pid_nr(p), task_pid_nr(p->real_parent),
5285 (unsigned long)task_thread_info(p)->flags);
5287 show_stack(p, NULL);
5290 void show_state_filter(unsigned long state_filter)
5292 struct task_struct *g, *p;
5294 #if BITS_PER_LONG == 32
5296 " task PC stack pid father\n");
5299 " task PC stack pid father\n");
5301 read_lock(&tasklist_lock);
5302 do_each_thread(g, p) {
5304 * reset the NMI-timeout, listing all files on a slow
5305 * console might take alot of time:
5307 touch_nmi_watchdog();
5308 if (!state_filter || (p->state & state_filter))
5310 } while_each_thread(g, p);
5312 touch_all_softlockup_watchdogs();
5314 #ifdef CONFIG_SCHED_DEBUG
5315 sysrq_sched_debug_show();
5317 read_unlock(&tasklist_lock);
5319 * Only show locks if all tasks are dumped:
5322 debug_show_all_locks();
5325 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5327 idle->sched_class = &idle_sched_class;
5331 * init_idle - set up an idle thread for a given CPU
5332 * @idle: task in question
5333 * @cpu: cpu the idle task belongs to
5335 * NOTE: this function does not set the idle thread's NEED_RESCHED
5336 * flag, to make booting more robust.
5338 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5340 struct rq *rq = cpu_rq(cpu);
5341 unsigned long flags;
5343 raw_spin_lock_irqsave(&rq->lock, flags);
5346 idle->state = TASK_RUNNING;
5347 idle->se.exec_start = sched_clock();
5349 cpumask_copy(&idle->cpus_allowed, cpumask_of(cpu));
5351 * We're having a chicken and egg problem, even though we are
5352 * holding rq->lock, the cpu isn't yet set to this cpu so the
5353 * lockdep check in task_group() will fail.
5355 * Similar case to sched_fork(). / Alternatively we could
5356 * use task_rq_lock() here and obtain the other rq->lock.
5361 __set_task_cpu(idle, cpu);
5364 rq->curr = rq->idle = idle;
5365 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5368 raw_spin_unlock_irqrestore(&rq->lock, flags);
5370 /* Set the preempt count _outside_ the spinlocks! */
5371 #if defined(CONFIG_PREEMPT)
5372 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
5374 task_thread_info(idle)->preempt_count = 0;
5377 * The idle tasks have their own, simple scheduling class:
5379 idle->sched_class = &idle_sched_class;
5380 ftrace_graph_init_task(idle);
5384 * In a system that switches off the HZ timer nohz_cpu_mask
5385 * indicates which cpus entered this state. This is used
5386 * in the rcu update to wait only for active cpus. For system
5387 * which do not switch off the HZ timer nohz_cpu_mask should
5388 * always be CPU_BITS_NONE.
5390 cpumask_var_t nohz_cpu_mask;
5393 * Increase the granularity value when there are more CPUs,
5394 * because with more CPUs the 'effective latency' as visible
5395 * to users decreases. But the relationship is not linear,
5396 * so pick a second-best guess by going with the log2 of the
5399 * This idea comes from the SD scheduler of Con Kolivas:
5401 static int get_update_sysctl_factor(void)
5403 unsigned int cpus = min_t(int, num_online_cpus(), 8);
5404 unsigned int factor;
5406 switch (sysctl_sched_tunable_scaling) {
5407 case SCHED_TUNABLESCALING_NONE:
5410 case SCHED_TUNABLESCALING_LINEAR:
5413 case SCHED_TUNABLESCALING_LOG:
5415 factor = 1 + ilog2(cpus);
5422 static void update_sysctl(void)
5424 unsigned int factor = get_update_sysctl_factor();
5426 #define SET_SYSCTL(name) \
5427 (sysctl_##name = (factor) * normalized_sysctl_##name)
5428 SET_SYSCTL(sched_min_granularity);
5429 SET_SYSCTL(sched_latency);
5430 SET_SYSCTL(sched_wakeup_granularity);
5434 static inline void sched_init_granularity(void)
5441 * This is how migration works:
5443 * 1) we invoke migration_cpu_stop() on the target CPU using
5445 * 2) stopper starts to run (implicitly forcing the migrated thread
5447 * 3) it checks whether the migrated task is still in the wrong runqueue.
5448 * 4) if it's in the wrong runqueue then the migration thread removes
5449 * it and puts it into the right queue.
5450 * 5) stopper completes and stop_one_cpu() returns and the migration
5455 * Change a given task's CPU affinity. Migrate the thread to a
5456 * proper CPU and schedule it away if the CPU it's executing on
5457 * is removed from the allowed bitmask.
5459 * NOTE: the caller must have a valid reference to the task, the
5460 * task must not exit() & deallocate itself prematurely. The
5461 * call is not atomic; no spinlocks may be held.
5463 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
5465 unsigned long flags;
5467 unsigned int dest_cpu;
5471 * Serialize against TASK_WAKING so that ttwu() and wunt() can
5472 * drop the rq->lock and still rely on ->cpus_allowed.
5475 while (task_is_waking(p))
5477 rq = task_rq_lock(p, &flags);
5478 if (task_is_waking(p)) {
5479 task_rq_unlock(rq, &flags);
5483 if (!cpumask_intersects(new_mask, cpu_active_mask)) {
5488 if (unlikely((p->flags & PF_THREAD_BOUND) && p != current &&
5489 !cpumask_equal(&p->cpus_allowed, new_mask))) {
5494 if (p->sched_class->set_cpus_allowed)
5495 p->sched_class->set_cpus_allowed(p, new_mask);
5497 cpumask_copy(&p->cpus_allowed, new_mask);
5498 p->rt.nr_cpus_allowed = cpumask_weight(new_mask);
5501 /* Can the task run on the task's current CPU? If so, we're done */
5502 if (cpumask_test_cpu(task_cpu(p), new_mask))
5505 dest_cpu = cpumask_any_and(cpu_active_mask, new_mask);
5506 if (migrate_task(p, dest_cpu)) {
5507 struct migration_arg arg = { p, dest_cpu };
5508 /* Need help from migration thread: drop lock and wait. */
5509 task_rq_unlock(rq, &flags);
5510 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
5511 tlb_migrate_finish(p->mm);
5515 task_rq_unlock(rq, &flags);
5519 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
5522 * Move (not current) task off this cpu, onto dest cpu. We're doing
5523 * this because either it can't run here any more (set_cpus_allowed()
5524 * away from this CPU, or CPU going down), or because we're
5525 * attempting to rebalance this task on exec (sched_exec).
5527 * So we race with normal scheduler movements, but that's OK, as long
5528 * as the task is no longer on this CPU.
5530 * Returns non-zero if task was successfully migrated.
5532 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
5534 struct rq *rq_dest, *rq_src;
5537 if (unlikely(!cpu_active(dest_cpu)))
5540 rq_src = cpu_rq(src_cpu);
5541 rq_dest = cpu_rq(dest_cpu);
5543 double_rq_lock(rq_src, rq_dest);
5544 /* Already moved. */
5545 if (task_cpu(p) != src_cpu)
5547 /* Affinity changed (again). */
5548 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
5552 * If we're not on a rq, the next wake-up will ensure we're
5556 deactivate_task(rq_src, p, 0);
5557 set_task_cpu(p, dest_cpu);
5558 activate_task(rq_dest, p, 0);
5559 check_preempt_curr(rq_dest, p, 0);
5564 double_rq_unlock(rq_src, rq_dest);
5569 * migration_cpu_stop - this will be executed by a highprio stopper thread
5570 * and performs thread migration by bumping thread off CPU then
5571 * 'pushing' onto another runqueue.
5573 static int migration_cpu_stop(void *data)
5575 struct migration_arg *arg = data;
5578 * The original target cpu might have gone down and we might
5579 * be on another cpu but it doesn't matter.
5581 local_irq_disable();
5582 __migrate_task(arg->task, raw_smp_processor_id(), arg->dest_cpu);
5587 #ifdef CONFIG_HOTPLUG_CPU
5590 * Ensures that the idle task is using init_mm right before its cpu goes
5593 void idle_task_exit(void)
5595 struct mm_struct *mm = current->active_mm;
5597 BUG_ON(cpu_online(smp_processor_id()));
5600 switch_mm(mm, &init_mm, current);
5605 * While a dead CPU has no uninterruptible tasks queued at this point,
5606 * it might still have a nonzero ->nr_uninterruptible counter, because
5607 * for performance reasons the counter is not stricly tracking tasks to
5608 * their home CPUs. So we just add the counter to another CPU's counter,
5609 * to keep the global sum constant after CPU-down:
5611 static void migrate_nr_uninterruptible(struct rq *rq_src)
5613 struct rq *rq_dest = cpu_rq(cpumask_any(cpu_active_mask));
5615 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5616 rq_src->nr_uninterruptible = 0;
5620 * remove the tasks which were accounted by rq from calc_load_tasks.
5622 static void calc_global_load_remove(struct rq *rq)
5624 atomic_long_sub(rq->calc_load_active, &calc_load_tasks);
5625 rq->calc_load_active = 0;
5629 * Migrate all tasks from the rq, sleeping tasks will be migrated by
5630 * try_to_wake_up()->select_task_rq().
5632 * Called with rq->lock held even though we'er in stop_machine() and
5633 * there's no concurrency possible, we hold the required locks anyway
5634 * because of lock validation efforts.
5636 static void migrate_tasks(unsigned int dead_cpu)
5638 struct rq *rq = cpu_rq(dead_cpu);
5639 struct task_struct *next, *stop = rq->stop;
5643 * Fudge the rq selection such that the below task selection loop
5644 * doesn't get stuck on the currently eligible stop task.
5646 * We're currently inside stop_machine() and the rq is either stuck
5647 * in the stop_machine_cpu_stop() loop, or we're executing this code,
5648 * either way we should never end up calling schedule() until we're
5655 * There's this thread running, bail when that's the only
5658 if (rq->nr_running == 1)
5661 next = pick_next_task(rq);
5663 next->sched_class->put_prev_task(rq, next);
5665 /* Find suitable destination for @next, with force if needed. */
5666 dest_cpu = select_fallback_rq(dead_cpu, next);
5667 raw_spin_unlock(&rq->lock);
5669 __migrate_task(next, dead_cpu, dest_cpu);
5671 raw_spin_lock(&rq->lock);
5677 #endif /* CONFIG_HOTPLUG_CPU */
5679 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5681 static struct ctl_table sd_ctl_dir[] = {
5683 .procname = "sched_domain",
5689 static struct ctl_table sd_ctl_root[] = {
5691 .procname = "kernel",
5693 .child = sd_ctl_dir,
5698 static struct ctl_table *sd_alloc_ctl_entry(int n)
5700 struct ctl_table *entry =
5701 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
5706 static void sd_free_ctl_entry(struct ctl_table **tablep)
5708 struct ctl_table *entry;
5711 * In the intermediate directories, both the child directory and
5712 * procname are dynamically allocated and could fail but the mode
5713 * will always be set. In the lowest directory the names are
5714 * static strings and all have proc handlers.
5716 for (entry = *tablep; entry->mode; entry++) {
5718 sd_free_ctl_entry(&entry->child);
5719 if (entry->proc_handler == NULL)
5720 kfree(entry->procname);
5728 set_table_entry(struct ctl_table *entry,
5729 const char *procname, void *data, int maxlen,
5730 mode_t mode, proc_handler *proc_handler)
5732 entry->procname = procname;
5734 entry->maxlen = maxlen;
5736 entry->proc_handler = proc_handler;
5739 static struct ctl_table *
5740 sd_alloc_ctl_domain_table(struct sched_domain *sd)
5742 struct ctl_table *table = sd_alloc_ctl_entry(13);
5747 set_table_entry(&table[0], "min_interval", &sd->min_interval,
5748 sizeof(long), 0644, proc_doulongvec_minmax);
5749 set_table_entry(&table[1], "max_interval", &sd->max_interval,
5750 sizeof(long), 0644, proc_doulongvec_minmax);
5751 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
5752 sizeof(int), 0644, proc_dointvec_minmax);
5753 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
5754 sizeof(int), 0644, proc_dointvec_minmax);
5755 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
5756 sizeof(int), 0644, proc_dointvec_minmax);
5757 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
5758 sizeof(int), 0644, proc_dointvec_minmax);
5759 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
5760 sizeof(int), 0644, proc_dointvec_minmax);
5761 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
5762 sizeof(int), 0644, proc_dointvec_minmax);
5763 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
5764 sizeof(int), 0644, proc_dointvec_minmax);
5765 set_table_entry(&table[9], "cache_nice_tries",
5766 &sd->cache_nice_tries,
5767 sizeof(int), 0644, proc_dointvec_minmax);
5768 set_table_entry(&table[10], "flags", &sd->flags,
5769 sizeof(int), 0644, proc_dointvec_minmax);
5770 set_table_entry(&table[11], "name", sd->name,
5771 CORENAME_MAX_SIZE, 0444, proc_dostring);
5772 /* &table[12] is terminator */
5777 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
5779 struct ctl_table *entry, *table;
5780 struct sched_domain *sd;
5781 int domain_num = 0, i;
5784 for_each_domain(cpu, sd)
5786 entry = table = sd_alloc_ctl_entry(domain_num + 1);
5791 for_each_domain(cpu, sd) {
5792 snprintf(buf, 32, "domain%d", i);
5793 entry->procname = kstrdup(buf, GFP_KERNEL);
5795 entry->child = sd_alloc_ctl_domain_table(sd);
5802 static struct ctl_table_header *sd_sysctl_header;
5803 static void register_sched_domain_sysctl(void)
5805 int i, cpu_num = num_possible_cpus();
5806 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5809 WARN_ON(sd_ctl_dir[0].child);
5810 sd_ctl_dir[0].child = entry;
5815 for_each_possible_cpu(i) {
5816 snprintf(buf, 32, "cpu%d", i);
5817 entry->procname = kstrdup(buf, GFP_KERNEL);
5819 entry->child = sd_alloc_ctl_cpu_table(i);
5823 WARN_ON(sd_sysctl_header);
5824 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
5827 /* may be called multiple times per register */
5828 static void unregister_sched_domain_sysctl(void)
5830 if (sd_sysctl_header)
5831 unregister_sysctl_table(sd_sysctl_header);
5832 sd_sysctl_header = NULL;
5833 if (sd_ctl_dir[0].child)
5834 sd_free_ctl_entry(&sd_ctl_dir[0].child);
5837 static void register_sched_domain_sysctl(void)
5840 static void unregister_sched_domain_sysctl(void)
5845 static void set_rq_online(struct rq *rq)
5848 const struct sched_class *class;
5850 cpumask_set_cpu(rq->cpu, rq->rd->online);
5853 for_each_class(class) {
5854 if (class->rq_online)
5855 class->rq_online(rq);
5860 static void set_rq_offline(struct rq *rq)
5863 const struct sched_class *class;
5865 for_each_class(class) {
5866 if (class->rq_offline)
5867 class->rq_offline(rq);
5870 cpumask_clear_cpu(rq->cpu, rq->rd->online);
5876 * migration_call - callback that gets triggered when a CPU is added.
5877 * Here we can start up the necessary migration thread for the new CPU.
5879 static int __cpuinit
5880 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
5882 int cpu = (long)hcpu;
5883 unsigned long flags;
5884 struct rq *rq = cpu_rq(cpu);
5886 switch (action & ~CPU_TASKS_FROZEN) {
5888 case CPU_UP_PREPARE:
5889 rq->calc_load_update = calc_load_update;
5893 /* Update our root-domain */
5894 raw_spin_lock_irqsave(&rq->lock, flags);
5896 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5900 raw_spin_unlock_irqrestore(&rq->lock, flags);
5903 #ifdef CONFIG_HOTPLUG_CPU
5905 /* Update our root-domain */
5906 raw_spin_lock_irqsave(&rq->lock, flags);
5908 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5912 BUG_ON(rq->nr_running != 1); /* the migration thread */
5913 raw_spin_unlock_irqrestore(&rq->lock, flags);
5915 migrate_nr_uninterruptible(rq);
5916 calc_global_load_remove(rq);
5924 * Register at high priority so that task migration (migrate_all_tasks)
5925 * happens before everything else. This has to be lower priority than
5926 * the notifier in the perf_event subsystem, though.
5928 static struct notifier_block __cpuinitdata migration_notifier = {
5929 .notifier_call = migration_call,
5930 .priority = CPU_PRI_MIGRATION,
5933 static int __cpuinit sched_cpu_active(struct notifier_block *nfb,
5934 unsigned long action, void *hcpu)
5936 switch (action & ~CPU_TASKS_FROZEN) {
5938 case CPU_DOWN_FAILED:
5939 set_cpu_active((long)hcpu, true);
5946 static int __cpuinit sched_cpu_inactive(struct notifier_block *nfb,
5947 unsigned long action, void *hcpu)
5949 switch (action & ~CPU_TASKS_FROZEN) {
5950 case CPU_DOWN_PREPARE:
5951 set_cpu_active((long)hcpu, false);
5958 static int __init migration_init(void)
5960 void *cpu = (void *)(long)smp_processor_id();
5963 /* Initialize migration for the boot CPU */
5964 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5965 BUG_ON(err == NOTIFY_BAD);
5966 migration_call(&migration_notifier, CPU_ONLINE, cpu);
5967 register_cpu_notifier(&migration_notifier);
5969 /* Register cpu active notifiers */
5970 cpu_notifier(sched_cpu_active, CPU_PRI_SCHED_ACTIVE);
5971 cpu_notifier(sched_cpu_inactive, CPU_PRI_SCHED_INACTIVE);
5975 early_initcall(migration_init);
5980 #ifdef CONFIG_SCHED_DEBUG
5982 static __read_mostly int sched_domain_debug_enabled;
5984 static int __init sched_domain_debug_setup(char *str)
5986 sched_domain_debug_enabled = 1;
5990 early_param("sched_debug", sched_domain_debug_setup);
5992 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
5993 struct cpumask *groupmask)
5995 struct sched_group *group = sd->groups;
5998 cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
5999 cpumask_clear(groupmask);
6001 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6003 if (!(sd->flags & SD_LOAD_BALANCE)) {
6004 printk("does not load-balance\n");
6006 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6011 printk(KERN_CONT "span %s level %s\n", str, sd->name);
6013 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
6014 printk(KERN_ERR "ERROR: domain->span does not contain "
6017 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
6018 printk(KERN_ERR "ERROR: domain->groups does not contain"
6022 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6026 printk(KERN_ERR "ERROR: group is NULL\n");
6030 if (!group->cpu_power) {
6031 printk(KERN_CONT "\n");
6032 printk(KERN_ERR "ERROR: domain->cpu_power not "
6037 if (!cpumask_weight(sched_group_cpus(group))) {
6038 printk(KERN_CONT "\n");
6039 printk(KERN_ERR "ERROR: empty group\n");
6043 if (cpumask_intersects(groupmask, sched_group_cpus(group))) {
6044 printk(KERN_CONT "\n");
6045 printk(KERN_ERR "ERROR: repeated CPUs\n");
6049 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
6051 cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
6053 printk(KERN_CONT " %s", str);
6054 if (group->cpu_power != SCHED_LOAD_SCALE) {
6055 printk(KERN_CONT " (cpu_power = %d)",
6059 group = group->next;
6060 } while (group != sd->groups);
6061 printk(KERN_CONT "\n");
6063 if (!cpumask_equal(sched_domain_span(sd), groupmask))
6064 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6067 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
6068 printk(KERN_ERR "ERROR: parent span is not a superset "
6069 "of domain->span\n");
6073 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6075 cpumask_var_t groupmask;
6078 if (!sched_domain_debug_enabled)
6082 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6086 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6088 if (!alloc_cpumask_var(&groupmask, GFP_KERNEL)) {
6089 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
6094 if (sched_domain_debug_one(sd, cpu, level, groupmask))
6101 free_cpumask_var(groupmask);
6103 #else /* !CONFIG_SCHED_DEBUG */
6104 # define sched_domain_debug(sd, cpu) do { } while (0)
6105 #endif /* CONFIG_SCHED_DEBUG */
6107 static int sd_degenerate(struct sched_domain *sd)
6109 if (cpumask_weight(sched_domain_span(sd)) == 1)
6112 /* Following flags need at least 2 groups */
6113 if (sd->flags & (SD_LOAD_BALANCE |
6114 SD_BALANCE_NEWIDLE |
6118 SD_SHARE_PKG_RESOURCES)) {
6119 if (sd->groups != sd->groups->next)
6123 /* Following flags don't use groups */
6124 if (sd->flags & (SD_WAKE_AFFINE))
6131 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6133 unsigned long cflags = sd->flags, pflags = parent->flags;
6135 if (sd_degenerate(parent))
6138 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
6141 /* Flags needing groups don't count if only 1 group in parent */
6142 if (parent->groups == parent->groups->next) {
6143 pflags &= ~(SD_LOAD_BALANCE |
6144 SD_BALANCE_NEWIDLE |
6148 SD_SHARE_PKG_RESOURCES);
6149 if (nr_node_ids == 1)
6150 pflags &= ~SD_SERIALIZE;
6152 if (~cflags & pflags)
6158 static void free_rootdomain(struct root_domain *rd)
6160 synchronize_sched();
6162 cpupri_cleanup(&rd->cpupri);
6164 free_cpumask_var(rd->rto_mask);
6165 free_cpumask_var(rd->online);
6166 free_cpumask_var(rd->span);
6170 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6172 struct root_domain *old_rd = NULL;
6173 unsigned long flags;
6175 raw_spin_lock_irqsave(&rq->lock, flags);
6180 if (cpumask_test_cpu(rq->cpu, old_rd->online))
6183 cpumask_clear_cpu(rq->cpu, old_rd->span);
6186 * If we dont want to free the old_rt yet then
6187 * set old_rd to NULL to skip the freeing later
6190 if (!atomic_dec_and_test(&old_rd->refcount))
6194 atomic_inc(&rd->refcount);
6197 cpumask_set_cpu(rq->cpu, rd->span);
6198 if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
6201 raw_spin_unlock_irqrestore(&rq->lock, flags);
6204 free_rootdomain(old_rd);
6207 static int init_rootdomain(struct root_domain *rd)
6209 memset(rd, 0, sizeof(*rd));
6211 if (!alloc_cpumask_var(&rd->span, GFP_KERNEL))
6213 if (!alloc_cpumask_var(&rd->online, GFP_KERNEL))
6215 if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
6218 if (cpupri_init(&rd->cpupri) != 0)
6223 free_cpumask_var(rd->rto_mask);
6225 free_cpumask_var(rd->online);
6227 free_cpumask_var(rd->span);
6232 static void init_defrootdomain(void)
6234 init_rootdomain(&def_root_domain);
6236 atomic_set(&def_root_domain.refcount, 1);
6239 static struct root_domain *alloc_rootdomain(void)
6241 struct root_domain *rd;
6243 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6247 if (init_rootdomain(rd) != 0) {
6256 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6257 * hold the hotplug lock.
6260 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6262 struct rq *rq = cpu_rq(cpu);
6263 struct sched_domain *tmp;
6265 for (tmp = sd; tmp; tmp = tmp->parent)
6266 tmp->span_weight = cpumask_weight(sched_domain_span(tmp));
6268 /* Remove the sched domains which do not contribute to scheduling. */
6269 for (tmp = sd; tmp; ) {
6270 struct sched_domain *parent = tmp->parent;
6274 if (sd_parent_degenerate(tmp, parent)) {
6275 tmp->parent = parent->parent;
6277 parent->parent->child = tmp;
6282 if (sd && sd_degenerate(sd)) {
6288 sched_domain_debug(sd, cpu);
6290 rq_attach_root(rq, rd);
6291 rcu_assign_pointer(rq->sd, sd);
6294 /* cpus with isolated domains */
6295 static cpumask_var_t cpu_isolated_map;
6297 /* Setup the mask of cpus configured for isolated domains */
6298 static int __init isolated_cpu_setup(char *str)
6300 alloc_bootmem_cpumask_var(&cpu_isolated_map);
6301 cpulist_parse(str, cpu_isolated_map);
6305 __setup("isolcpus=", isolated_cpu_setup);
6308 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6309 * to a function which identifies what group(along with sched group) a CPU
6310 * belongs to. The return value of group_fn must be a >= 0 and < nr_cpu_ids
6311 * (due to the fact that we keep track of groups covered with a struct cpumask).
6313 * init_sched_build_groups will build a circular linked list of the groups
6314 * covered by the given span, and will set each group's ->cpumask correctly,
6315 * and ->cpu_power to 0.
6318 init_sched_build_groups(const struct cpumask *span,
6319 const struct cpumask *cpu_map,
6320 int (*group_fn)(int cpu, const struct cpumask *cpu_map,
6321 struct sched_group **sg,
6322 struct cpumask *tmpmask),
6323 struct cpumask *covered, struct cpumask *tmpmask)
6325 struct sched_group *first = NULL, *last = NULL;
6328 cpumask_clear(covered);
6330 for_each_cpu(i, span) {
6331 struct sched_group *sg;
6332 int group = group_fn(i, cpu_map, &sg, tmpmask);
6335 if (cpumask_test_cpu(i, covered))
6338 cpumask_clear(sched_group_cpus(sg));
6341 for_each_cpu(j, span) {
6342 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
6345 cpumask_set_cpu(j, covered);
6346 cpumask_set_cpu(j, sched_group_cpus(sg));
6357 #define SD_NODES_PER_DOMAIN 16
6362 * find_next_best_node - find the next node to include in a sched_domain
6363 * @node: node whose sched_domain we're building
6364 * @used_nodes: nodes already in the sched_domain
6366 * Find the next node to include in a given scheduling domain. Simply
6367 * finds the closest node not already in the @used_nodes map.
6369 * Should use nodemask_t.
6371 static int find_next_best_node(int node, nodemask_t *used_nodes)
6373 int i, n, val, min_val, best_node = 0;
6377 for (i = 0; i < nr_node_ids; i++) {
6378 /* Start at @node */
6379 n = (node + i) % nr_node_ids;
6381 if (!nr_cpus_node(n))
6384 /* Skip already used nodes */
6385 if (node_isset(n, *used_nodes))
6388 /* Simple min distance search */
6389 val = node_distance(node, n);
6391 if (val < min_val) {
6397 node_set(best_node, *used_nodes);
6402 * sched_domain_node_span - get a cpumask for a node's sched_domain
6403 * @node: node whose cpumask we're constructing
6404 * @span: resulting cpumask
6406 * Given a node, construct a good cpumask for its sched_domain to span. It
6407 * should be one that prevents unnecessary balancing, but also spreads tasks
6410 static void sched_domain_node_span(int node, struct cpumask *span)
6412 nodemask_t used_nodes;
6415 cpumask_clear(span);
6416 nodes_clear(used_nodes);
6418 cpumask_or(span, span, cpumask_of_node(node));
6419 node_set(node, used_nodes);
6421 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
6422 int next_node = find_next_best_node(node, &used_nodes);
6424 cpumask_or(span, span, cpumask_of_node(next_node));
6427 #endif /* CONFIG_NUMA */
6429 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6432 * The cpus mask in sched_group and sched_domain hangs off the end.
6434 * ( See the the comments in include/linux/sched.h:struct sched_group
6435 * and struct sched_domain. )
6437 struct static_sched_group {
6438 struct sched_group sg;
6439 DECLARE_BITMAP(cpus, CONFIG_NR_CPUS);
6442 struct static_sched_domain {
6443 struct sched_domain sd;
6444 DECLARE_BITMAP(span, CONFIG_NR_CPUS);
6450 cpumask_var_t domainspan;
6451 cpumask_var_t covered;
6452 cpumask_var_t notcovered;
6454 cpumask_var_t nodemask;
6455 cpumask_var_t this_sibling_map;
6456 cpumask_var_t this_core_map;
6457 cpumask_var_t this_book_map;
6458 cpumask_var_t send_covered;
6459 cpumask_var_t tmpmask;
6460 struct sched_group **sched_group_nodes;
6461 struct root_domain *rd;
6465 sa_sched_groups = 0,
6471 sa_this_sibling_map,
6473 sa_sched_group_nodes,
6483 * SMT sched-domains:
6485 #ifdef CONFIG_SCHED_SMT
6486 static DEFINE_PER_CPU(struct static_sched_domain, cpu_domains);
6487 static DEFINE_PER_CPU(struct static_sched_group, sched_groups);
6490 cpu_to_cpu_group(int cpu, const struct cpumask *cpu_map,
6491 struct sched_group **sg, struct cpumask *unused)
6494 *sg = &per_cpu(sched_groups, cpu).sg;
6497 #endif /* CONFIG_SCHED_SMT */
6500 * multi-core sched-domains:
6502 #ifdef CONFIG_SCHED_MC
6503 static DEFINE_PER_CPU(struct static_sched_domain, core_domains);
6504 static DEFINE_PER_CPU(struct static_sched_group, sched_group_core);
6507 cpu_to_core_group(int cpu, const struct cpumask *cpu_map,
6508 struct sched_group **sg, struct cpumask *mask)
6511 #ifdef CONFIG_SCHED_SMT
6512 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
6513 group = cpumask_first(mask);
6518 *sg = &per_cpu(sched_group_core, group).sg;
6521 #endif /* CONFIG_SCHED_MC */
6524 * book sched-domains:
6526 #ifdef CONFIG_SCHED_BOOK
6527 static DEFINE_PER_CPU(struct static_sched_domain, book_domains);
6528 static DEFINE_PER_CPU(struct static_sched_group, sched_group_book);
6531 cpu_to_book_group(int cpu, const struct cpumask *cpu_map,
6532 struct sched_group **sg, struct cpumask *mask)
6535 #ifdef CONFIG_SCHED_MC
6536 cpumask_and(mask, cpu_coregroup_mask(cpu), cpu_map);
6537 group = cpumask_first(mask);
6538 #elif defined(CONFIG_SCHED_SMT)
6539 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
6540 group = cpumask_first(mask);
6543 *sg = &per_cpu(sched_group_book, group).sg;
6546 #endif /* CONFIG_SCHED_BOOK */
6548 static DEFINE_PER_CPU(struct static_sched_domain, phys_domains);
6549 static DEFINE_PER_CPU(struct static_sched_group, sched_group_phys);
6552 cpu_to_phys_group(int cpu, const struct cpumask *cpu_map,
6553 struct sched_group **sg, struct cpumask *mask)
6556 #ifdef CONFIG_SCHED_BOOK
6557 cpumask_and(mask, cpu_book_mask(cpu), cpu_map);
6558 group = cpumask_first(mask);
6559 #elif defined(CONFIG_SCHED_MC)
6560 cpumask_and(mask, cpu_coregroup_mask(cpu), cpu_map);
6561 group = cpumask_first(mask);
6562 #elif defined(CONFIG_SCHED_SMT)
6563 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
6564 group = cpumask_first(mask);
6569 *sg = &per_cpu(sched_group_phys, group).sg;
6575 * The init_sched_build_groups can't handle what we want to do with node
6576 * groups, so roll our own. Now each node has its own list of groups which
6577 * gets dynamically allocated.
6579 static DEFINE_PER_CPU(struct static_sched_domain, node_domains);
6580 static struct sched_group ***sched_group_nodes_bycpu;
6582 static DEFINE_PER_CPU(struct static_sched_domain, allnodes_domains);
6583 static DEFINE_PER_CPU(struct static_sched_group, sched_group_allnodes);
6585 static int cpu_to_allnodes_group(int cpu, const struct cpumask *cpu_map,
6586 struct sched_group **sg,
6587 struct cpumask *nodemask)
6591 cpumask_and(nodemask, cpumask_of_node(cpu_to_node(cpu)), cpu_map);
6592 group = cpumask_first(nodemask);
6595 *sg = &per_cpu(sched_group_allnodes, group).sg;
6599 static void init_numa_sched_groups_power(struct sched_group *group_head)
6601 struct sched_group *sg = group_head;
6607 for_each_cpu(j, sched_group_cpus(sg)) {
6608 struct sched_domain *sd;
6610 sd = &per_cpu(phys_domains, j).sd;
6611 if (j != group_first_cpu(sd->groups)) {
6613 * Only add "power" once for each
6619 sg->cpu_power += sd->groups->cpu_power;
6622 } while (sg != group_head);
6625 static int build_numa_sched_groups(struct s_data *d,
6626 const struct cpumask *cpu_map, int num)
6628 struct sched_domain *sd;
6629 struct sched_group *sg, *prev;
6632 cpumask_clear(d->covered);
6633 cpumask_and(d->nodemask, cpumask_of_node(num), cpu_map);
6634 if (cpumask_empty(d->nodemask)) {
6635 d->sched_group_nodes[num] = NULL;
6639 sched_domain_node_span(num, d->domainspan);
6640 cpumask_and(d->domainspan, d->domainspan, cpu_map);
6642 sg = kmalloc_node(sizeof(struct sched_group) + cpumask_size(),
6645 printk(KERN_WARNING "Can not alloc domain group for node %d\n",
6649 d->sched_group_nodes[num] = sg;
6651 for_each_cpu(j, d->nodemask) {
6652 sd = &per_cpu(node_domains, j).sd;
6657 cpumask_copy(sched_group_cpus(sg), d->nodemask);
6659 cpumask_or(d->covered, d->covered, d->nodemask);
6662 for (j = 0; j < nr_node_ids; j++) {
6663 n = (num + j) % nr_node_ids;
6664 cpumask_complement(d->notcovered, d->covered);
6665 cpumask_and(d->tmpmask, d->notcovered, cpu_map);
6666 cpumask_and(d->tmpmask, d->tmpmask, d->domainspan);
6667 if (cpumask_empty(d->tmpmask))
6669 cpumask_and(d->tmpmask, d->tmpmask, cpumask_of_node(n));
6670 if (cpumask_empty(d->tmpmask))
6672 sg = kmalloc_node(sizeof(struct sched_group) + cpumask_size(),
6676 "Can not alloc domain group for node %d\n", j);
6680 cpumask_copy(sched_group_cpus(sg), d->tmpmask);
6681 sg->next = prev->next;
6682 cpumask_or(d->covered, d->covered, d->tmpmask);
6689 #endif /* CONFIG_NUMA */
6692 /* Free memory allocated for various sched_group structures */
6693 static void free_sched_groups(const struct cpumask *cpu_map,
6694 struct cpumask *nodemask)
6698 for_each_cpu(cpu, cpu_map) {
6699 struct sched_group **sched_group_nodes
6700 = sched_group_nodes_bycpu[cpu];
6702 if (!sched_group_nodes)
6705 for (i = 0; i < nr_node_ids; i++) {
6706 struct sched_group *oldsg, *sg = sched_group_nodes[i];
6708 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
6709 if (cpumask_empty(nodemask))
6719 if (oldsg != sched_group_nodes[i])
6722 kfree(sched_group_nodes);
6723 sched_group_nodes_bycpu[cpu] = NULL;
6726 #else /* !CONFIG_NUMA */
6727 static void free_sched_groups(const struct cpumask *cpu_map,
6728 struct cpumask *nodemask)
6731 #endif /* CONFIG_NUMA */
6734 * Initialize sched groups cpu_power.
6736 * cpu_power indicates the capacity of sched group, which is used while
6737 * distributing the load between different sched groups in a sched domain.
6738 * Typically cpu_power for all the groups in a sched domain will be same unless
6739 * there are asymmetries in the topology. If there are asymmetries, group
6740 * having more cpu_power will pickup more load compared to the group having
6743 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
6745 struct sched_domain *child;
6746 struct sched_group *group;
6750 WARN_ON(!sd || !sd->groups);
6752 if (cpu != group_first_cpu(sd->groups))
6755 sd->groups->group_weight = cpumask_weight(sched_group_cpus(sd->groups));
6759 sd->groups->cpu_power = 0;
6762 power = SCHED_LOAD_SCALE;
6763 weight = cpumask_weight(sched_domain_span(sd));
6765 * SMT siblings share the power of a single core.
6766 * Usually multiple threads get a better yield out of
6767 * that one core than a single thread would have,
6768 * reflect that in sd->smt_gain.
6770 if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
6771 power *= sd->smt_gain;
6773 power >>= SCHED_LOAD_SHIFT;
6775 sd->groups->cpu_power += power;
6780 * Add cpu_power of each child group to this groups cpu_power.
6782 group = child->groups;
6784 sd->groups->cpu_power += group->cpu_power;
6785 group = group->next;
6786 } while (group != child->groups);
6790 * Initializers for schedule domains
6791 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
6794 #ifdef CONFIG_SCHED_DEBUG
6795 # define SD_INIT_NAME(sd, type) sd->name = #type
6797 # define SD_INIT_NAME(sd, type) do { } while (0)
6800 #define SD_INIT(sd, type) sd_init_##type(sd)
6802 #define SD_INIT_FUNC(type) \
6803 static noinline void sd_init_##type(struct sched_domain *sd) \
6805 memset(sd, 0, sizeof(*sd)); \
6806 *sd = SD_##type##_INIT; \
6807 sd->level = SD_LV_##type; \
6808 SD_INIT_NAME(sd, type); \
6813 SD_INIT_FUNC(ALLNODES)
6816 #ifdef CONFIG_SCHED_SMT
6817 SD_INIT_FUNC(SIBLING)
6819 #ifdef CONFIG_SCHED_MC
6822 #ifdef CONFIG_SCHED_BOOK
6826 static int default_relax_domain_level = -1;
6828 static int __init setup_relax_domain_level(char *str)
6832 val = simple_strtoul(str, NULL, 0);
6833 if (val < SD_LV_MAX)
6834 default_relax_domain_level = val;
6838 __setup("relax_domain_level=", setup_relax_domain_level);
6840 static void set_domain_attribute(struct sched_domain *sd,
6841 struct sched_domain_attr *attr)
6845 if (!attr || attr->relax_domain_level < 0) {
6846 if (default_relax_domain_level < 0)
6849 request = default_relax_domain_level;
6851 request = attr->relax_domain_level;
6852 if (request < sd->level) {
6853 /* turn off idle balance on this domain */
6854 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6856 /* turn on idle balance on this domain */
6857 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6861 static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
6862 const struct cpumask *cpu_map)
6865 case sa_sched_groups:
6866 free_sched_groups(cpu_map, d->tmpmask); /* fall through */
6867 d->sched_group_nodes = NULL;
6869 free_rootdomain(d->rd); /* fall through */
6871 free_cpumask_var(d->tmpmask); /* fall through */
6872 case sa_send_covered:
6873 free_cpumask_var(d->send_covered); /* fall through */
6874 case sa_this_book_map:
6875 free_cpumask_var(d->this_book_map); /* fall through */
6876 case sa_this_core_map:
6877 free_cpumask_var(d->this_core_map); /* fall through */
6878 case sa_this_sibling_map:
6879 free_cpumask_var(d->this_sibling_map); /* fall through */
6881 free_cpumask_var(d->nodemask); /* fall through */
6882 case sa_sched_group_nodes:
6884 kfree(d->sched_group_nodes); /* fall through */
6886 free_cpumask_var(d->notcovered); /* fall through */
6888 free_cpumask_var(d->covered); /* fall through */
6890 free_cpumask_var(d->domainspan); /* fall through */
6897 static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
6898 const struct cpumask *cpu_map)
6901 if (!alloc_cpumask_var(&d->domainspan, GFP_KERNEL))
6903 if (!alloc_cpumask_var(&d->covered, GFP_KERNEL))
6904 return sa_domainspan;
6905 if (!alloc_cpumask_var(&d->notcovered, GFP_KERNEL))
6907 /* Allocate the per-node list of sched groups */
6908 d->sched_group_nodes = kcalloc(nr_node_ids,
6909 sizeof(struct sched_group *), GFP_KERNEL);
6910 if (!d->sched_group_nodes) {
6911 printk(KERN_WARNING "Can not alloc sched group node list\n");
6912 return sa_notcovered;
6914 sched_group_nodes_bycpu[cpumask_first(cpu_map)] = d->sched_group_nodes;
6916 if (!alloc_cpumask_var(&d->nodemask, GFP_KERNEL))
6917 return sa_sched_group_nodes;
6918 if (!alloc_cpumask_var(&d->this_sibling_map, GFP_KERNEL))
6920 if (!alloc_cpumask_var(&d->this_core_map, GFP_KERNEL))
6921 return sa_this_sibling_map;
6922 if (!alloc_cpumask_var(&d->this_book_map, GFP_KERNEL))
6923 return sa_this_core_map;
6924 if (!alloc_cpumask_var(&d->send_covered, GFP_KERNEL))
6925 return sa_this_book_map;
6926 if (!alloc_cpumask_var(&d->tmpmask, GFP_KERNEL))
6927 return sa_send_covered;
6928 d->rd = alloc_rootdomain();
6930 printk(KERN_WARNING "Cannot alloc root domain\n");
6933 return sa_rootdomain;
6936 static struct sched_domain *__build_numa_sched_domains(struct s_data *d,
6937 const struct cpumask *cpu_map, struct sched_domain_attr *attr, int i)
6939 struct sched_domain *sd = NULL;
6941 struct sched_domain *parent;
6944 if (cpumask_weight(cpu_map) >
6945 SD_NODES_PER_DOMAIN * cpumask_weight(d->nodemask)) {
6946 sd = &per_cpu(allnodes_domains, i).sd;
6947 SD_INIT(sd, ALLNODES);
6948 set_domain_attribute(sd, attr);
6949 cpumask_copy(sched_domain_span(sd), cpu_map);
6950 cpu_to_allnodes_group(i, cpu_map, &sd->groups, d->tmpmask);
6955 sd = &per_cpu(node_domains, i).sd;
6957 set_domain_attribute(sd, attr);
6958 sched_domain_node_span(cpu_to_node(i), sched_domain_span(sd));
6959 sd->parent = parent;
6962 cpumask_and(sched_domain_span(sd), sched_domain_span(sd), cpu_map);
6967 static struct sched_domain *__build_cpu_sched_domain(struct s_data *d,
6968 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
6969 struct sched_domain *parent, int i)
6971 struct sched_domain *sd;
6972 sd = &per_cpu(phys_domains, i).sd;
6974 set_domain_attribute(sd, attr);
6975 cpumask_copy(sched_domain_span(sd), d->nodemask);
6976 sd->parent = parent;
6979 cpu_to_phys_group(i, cpu_map, &sd->groups, d->tmpmask);
6983 static struct sched_domain *__build_book_sched_domain(struct s_data *d,
6984 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
6985 struct sched_domain *parent, int i)
6987 struct sched_domain *sd = parent;
6988 #ifdef CONFIG_SCHED_BOOK
6989 sd = &per_cpu(book_domains, i).sd;
6991 set_domain_attribute(sd, attr);
6992 cpumask_and(sched_domain_span(sd), cpu_map, cpu_book_mask(i));
6993 sd->parent = parent;
6995 cpu_to_book_group(i, cpu_map, &sd->groups, d->tmpmask);
7000 static struct sched_domain *__build_mc_sched_domain(struct s_data *d,
7001 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
7002 struct sched_domain *parent, int i)
7004 struct sched_domain *sd = parent;
7005 #ifdef CONFIG_SCHED_MC
7006 sd = &per_cpu(core_domains, i).sd;
7008 set_domain_attribute(sd, attr);
7009 cpumask_and(sched_domain_span(sd), cpu_map, cpu_coregroup_mask(i));
7010 sd->parent = parent;
7012 cpu_to_core_group(i, cpu_map, &sd->groups, d->tmpmask);
7017 static struct sched_domain *__build_smt_sched_domain(struct s_data *d,
7018 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
7019 struct sched_domain *parent, int i)
7021 struct sched_domain *sd = parent;
7022 #ifdef CONFIG_SCHED_SMT
7023 sd = &per_cpu(cpu_domains, i).sd;
7024 SD_INIT(sd, SIBLING);
7025 set_domain_attribute(sd, attr);
7026 cpumask_and(sched_domain_span(sd), cpu_map, topology_thread_cpumask(i));
7027 sd->parent = parent;
7029 cpu_to_cpu_group(i, cpu_map, &sd->groups, d->tmpmask);
7034 static void build_sched_groups(struct s_data *d, enum sched_domain_level l,
7035 const struct cpumask *cpu_map, int cpu)
7038 #ifdef CONFIG_SCHED_SMT
7039 case SD_LV_SIBLING: /* set up CPU (sibling) groups */
7040 cpumask_and(d->this_sibling_map, cpu_map,
7041 topology_thread_cpumask(cpu));
7042 if (cpu == cpumask_first(d->this_sibling_map))
7043 init_sched_build_groups(d->this_sibling_map, cpu_map,
7045 d->send_covered, d->tmpmask);
7048 #ifdef CONFIG_SCHED_MC
7049 case SD_LV_MC: /* set up multi-core groups */
7050 cpumask_and(d->this_core_map, cpu_map, cpu_coregroup_mask(cpu));
7051 if (cpu == cpumask_first(d->this_core_map))
7052 init_sched_build_groups(d->this_core_map, cpu_map,
7054 d->send_covered, d->tmpmask);
7057 #ifdef CONFIG_SCHED_BOOK
7058 case SD_LV_BOOK: /* set up book groups */
7059 cpumask_and(d->this_book_map, cpu_map, cpu_book_mask(cpu));
7060 if (cpu == cpumask_first(d->this_book_map))
7061 init_sched_build_groups(d->this_book_map, cpu_map,
7063 d->send_covered, d->tmpmask);
7066 case SD_LV_CPU: /* set up physical groups */
7067 cpumask_and(d->nodemask, cpumask_of_node(cpu), cpu_map);
7068 if (!cpumask_empty(d->nodemask))
7069 init_sched_build_groups(d->nodemask, cpu_map,
7071 d->send_covered, d->tmpmask);
7074 case SD_LV_ALLNODES:
7075 init_sched_build_groups(cpu_map, cpu_map, &cpu_to_allnodes_group,
7076 d->send_covered, d->tmpmask);
7085 * Build sched domains for a given set of cpus and attach the sched domains
7086 * to the individual cpus
7088 static int __build_sched_domains(const struct cpumask *cpu_map,
7089 struct sched_domain_attr *attr)
7091 enum s_alloc alloc_state = sa_none;
7093 struct sched_domain *sd;
7099 alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
7100 if (alloc_state != sa_rootdomain)
7102 alloc_state = sa_sched_groups;
7105 * Set up domains for cpus specified by the cpu_map.
7107 for_each_cpu(i, cpu_map) {
7108 cpumask_and(d.nodemask, cpumask_of_node(cpu_to_node(i)),
7111 sd = __build_numa_sched_domains(&d, cpu_map, attr, i);
7112 sd = __build_cpu_sched_domain(&d, cpu_map, attr, sd, i);
7113 sd = __build_book_sched_domain(&d, cpu_map, attr, sd, i);
7114 sd = __build_mc_sched_domain(&d, cpu_map, attr, sd, i);
7115 sd = __build_smt_sched_domain(&d, cpu_map, attr, sd, i);
7118 for_each_cpu(i, cpu_map) {
7119 build_sched_groups(&d, SD_LV_SIBLING, cpu_map, i);
7120 build_sched_groups(&d, SD_LV_BOOK, cpu_map, i);
7121 build_sched_groups(&d, SD_LV_MC, cpu_map, i);
7124 /* Set up physical groups */
7125 for (i = 0; i < nr_node_ids; i++)
7126 build_sched_groups(&d, SD_LV_CPU, cpu_map, i);
7129 /* Set up node groups */
7131 build_sched_groups(&d, SD_LV_ALLNODES, cpu_map, 0);
7133 for (i = 0; i < nr_node_ids; i++)
7134 if (build_numa_sched_groups(&d, cpu_map, i))
7138 /* Calculate CPU power for physical packages and nodes */
7139 #ifdef CONFIG_SCHED_SMT
7140 for_each_cpu(i, cpu_map) {
7141 sd = &per_cpu(cpu_domains, i).sd;
7142 init_sched_groups_power(i, sd);
7145 #ifdef CONFIG_SCHED_MC
7146 for_each_cpu(i, cpu_map) {
7147 sd = &per_cpu(core_domains, i).sd;
7148 init_sched_groups_power(i, sd);
7151 #ifdef CONFIG_SCHED_BOOK
7152 for_each_cpu(i, cpu_map) {
7153 sd = &per_cpu(book_domains, i).sd;
7154 init_sched_groups_power(i, sd);
7158 for_each_cpu(i, cpu_map) {
7159 sd = &per_cpu(phys_domains, i).sd;
7160 init_sched_groups_power(i, sd);
7164 for (i = 0; i < nr_node_ids; i++)
7165 init_numa_sched_groups_power(d.sched_group_nodes[i]);
7167 if (d.sd_allnodes) {
7168 struct sched_group *sg;
7170 cpu_to_allnodes_group(cpumask_first(cpu_map), cpu_map, &sg,
7172 init_numa_sched_groups_power(sg);
7176 /* Attach the domains */
7177 for_each_cpu(i, cpu_map) {
7178 #ifdef CONFIG_SCHED_SMT
7179 sd = &per_cpu(cpu_domains, i).sd;
7180 #elif defined(CONFIG_SCHED_MC)
7181 sd = &per_cpu(core_domains, i).sd;
7182 #elif defined(CONFIG_SCHED_BOOK)
7183 sd = &per_cpu(book_domains, i).sd;
7185 sd = &per_cpu(phys_domains, i).sd;
7187 cpu_attach_domain(sd, d.rd, i);
7190 d.sched_group_nodes = NULL; /* don't free this we still need it */
7191 __free_domain_allocs(&d, sa_tmpmask, cpu_map);
7195 __free_domain_allocs(&d, alloc_state, cpu_map);
7199 static int build_sched_domains(const struct cpumask *cpu_map)
7201 return __build_sched_domains(cpu_map, NULL);
7204 static cpumask_var_t *doms_cur; /* current sched domains */
7205 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7206 static struct sched_domain_attr *dattr_cur;
7207 /* attribues of custom domains in 'doms_cur' */
7210 * Special case: If a kmalloc of a doms_cur partition (array of
7211 * cpumask) fails, then fallback to a single sched domain,
7212 * as determined by the single cpumask fallback_doms.
7214 static cpumask_var_t fallback_doms;
7217 * arch_update_cpu_topology lets virtualized architectures update the
7218 * cpu core maps. It is supposed to return 1 if the topology changed
7219 * or 0 if it stayed the same.
7221 int __attribute__((weak)) arch_update_cpu_topology(void)
7226 cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
7229 cpumask_var_t *doms;
7231 doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
7234 for (i = 0; i < ndoms; i++) {
7235 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
7236 free_sched_domains(doms, i);
7243 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
7246 for (i = 0; i < ndoms; i++)
7247 free_cpumask_var(doms[i]);
7252 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7253 * For now this just excludes isolated cpus, but could be used to
7254 * exclude other special cases in the future.
7256 static int arch_init_sched_domains(const struct cpumask *cpu_map)
7260 arch_update_cpu_topology();
7262 doms_cur = alloc_sched_domains(ndoms_cur);
7264 doms_cur = &fallback_doms;
7265 cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
7267 err = build_sched_domains(doms_cur[0]);
7268 register_sched_domain_sysctl();
7273 static void arch_destroy_sched_domains(const struct cpumask *cpu_map,
7274 struct cpumask *tmpmask)
7276 free_sched_groups(cpu_map, tmpmask);
7280 * Detach sched domains from a group of cpus specified in cpu_map
7281 * These cpus will now be attached to the NULL domain
7283 static void detach_destroy_domains(const struct cpumask *cpu_map)
7285 /* Save because hotplug lock held. */
7286 static DECLARE_BITMAP(tmpmask, CONFIG_NR_CPUS);
7289 for_each_cpu(i, cpu_map)
7290 cpu_attach_domain(NULL, &def_root_domain, i);
7291 synchronize_sched();
7292 arch_destroy_sched_domains(cpu_map, to_cpumask(tmpmask));
7295 /* handle null as "default" */
7296 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7297 struct sched_domain_attr *new, int idx_new)
7299 struct sched_domain_attr tmp;
7306 return !memcmp(cur ? (cur + idx_cur) : &tmp,
7307 new ? (new + idx_new) : &tmp,
7308 sizeof(struct sched_domain_attr));
7312 * Partition sched domains as specified by the 'ndoms_new'
7313 * cpumasks in the array doms_new[] of cpumasks. This compares
7314 * doms_new[] to the current sched domain partitioning, doms_cur[].
7315 * It destroys each deleted domain and builds each new domain.
7317 * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
7318 * The masks don't intersect (don't overlap.) We should setup one
7319 * sched domain for each mask. CPUs not in any of the cpumasks will
7320 * not be load balanced. If the same cpumask appears both in the
7321 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7324 * The passed in 'doms_new' should be allocated using
7325 * alloc_sched_domains. This routine takes ownership of it and will
7326 * free_sched_domains it when done with it. If the caller failed the
7327 * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
7328 * and partition_sched_domains() will fallback to the single partition
7329 * 'fallback_doms', it also forces the domains to be rebuilt.
7331 * If doms_new == NULL it will be replaced with cpu_online_mask.
7332 * ndoms_new == 0 is a special case for destroying existing domains,
7333 * and it will not create the default domain.
7335 * Call with hotplug lock held
7337 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
7338 struct sched_domain_attr *dattr_new)
7343 mutex_lock(&sched_domains_mutex);
7345 /* always unregister in case we don't destroy any domains */
7346 unregister_sched_domain_sysctl();
7348 /* Let architecture update cpu core mappings. */
7349 new_topology = arch_update_cpu_topology();
7351 n = doms_new ? ndoms_new : 0;
7353 /* Destroy deleted domains */
7354 for (i = 0; i < ndoms_cur; i++) {
7355 for (j = 0; j < n && !new_topology; j++) {
7356 if (cpumask_equal(doms_cur[i], doms_new[j])
7357 && dattrs_equal(dattr_cur, i, dattr_new, j))
7360 /* no match - a current sched domain not in new doms_new[] */
7361 detach_destroy_domains(doms_cur[i]);
7366 if (doms_new == NULL) {
7368 doms_new = &fallback_doms;
7369 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
7370 WARN_ON_ONCE(dattr_new);
7373 /* Build new domains */
7374 for (i = 0; i < ndoms_new; i++) {
7375 for (j = 0; j < ndoms_cur && !new_topology; j++) {
7376 if (cpumask_equal(doms_new[i], doms_cur[j])
7377 && dattrs_equal(dattr_new, i, dattr_cur, j))
7380 /* no match - add a new doms_new */
7381 __build_sched_domains(doms_new[i],
7382 dattr_new ? dattr_new + i : NULL);
7387 /* Remember the new sched domains */
7388 if (doms_cur != &fallback_doms)
7389 free_sched_domains(doms_cur, ndoms_cur);
7390 kfree(dattr_cur); /* kfree(NULL) is safe */
7391 doms_cur = doms_new;
7392 dattr_cur = dattr_new;
7393 ndoms_cur = ndoms_new;
7395 register_sched_domain_sysctl();
7397 mutex_unlock(&sched_domains_mutex);
7400 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7401 static void arch_reinit_sched_domains(void)
7405 /* Destroy domains first to force the rebuild */
7406 partition_sched_domains(0, NULL, NULL);
7408 rebuild_sched_domains();
7412 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7414 unsigned int level = 0;
7416 if (sscanf(buf, "%u", &level) != 1)
7420 * level is always be positive so don't check for
7421 * level < POWERSAVINGS_BALANCE_NONE which is 0
7422 * What happens on 0 or 1 byte write,
7423 * need to check for count as well?
7426 if (level >= MAX_POWERSAVINGS_BALANCE_LEVELS)
7430 sched_smt_power_savings = level;
7432 sched_mc_power_savings = level;
7434 arch_reinit_sched_domains();
7439 #ifdef CONFIG_SCHED_MC
7440 static ssize_t sched_mc_power_savings_show(struct sysdev_class *class,
7441 struct sysdev_class_attribute *attr,
7444 return sprintf(page, "%u\n", sched_mc_power_savings);
7446 static ssize_t sched_mc_power_savings_store(struct sysdev_class *class,
7447 struct sysdev_class_attribute *attr,
7448 const char *buf, size_t count)
7450 return sched_power_savings_store(buf, count, 0);
7452 static SYSDEV_CLASS_ATTR(sched_mc_power_savings, 0644,
7453 sched_mc_power_savings_show,
7454 sched_mc_power_savings_store);
7457 #ifdef CONFIG_SCHED_SMT
7458 static ssize_t sched_smt_power_savings_show(struct sysdev_class *dev,
7459 struct sysdev_class_attribute *attr,
7462 return sprintf(page, "%u\n", sched_smt_power_savings);
7464 static ssize_t sched_smt_power_savings_store(struct sysdev_class *dev,
7465 struct sysdev_class_attribute *attr,
7466 const char *buf, size_t count)
7468 return sched_power_savings_store(buf, count, 1);
7470 static SYSDEV_CLASS_ATTR(sched_smt_power_savings, 0644,
7471 sched_smt_power_savings_show,
7472 sched_smt_power_savings_store);
7475 int __init sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7479 #ifdef CONFIG_SCHED_SMT
7481 err = sysfs_create_file(&cls->kset.kobj,
7482 &attr_sched_smt_power_savings.attr);
7484 #ifdef CONFIG_SCHED_MC
7485 if (!err && mc_capable())
7486 err = sysfs_create_file(&cls->kset.kobj,
7487 &attr_sched_mc_power_savings.attr);
7491 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
7494 * Update cpusets according to cpu_active mask. If cpusets are
7495 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
7496 * around partition_sched_domains().
7498 static int cpuset_cpu_active(struct notifier_block *nfb, unsigned long action,
7501 switch (action & ~CPU_TASKS_FROZEN) {
7503 case CPU_DOWN_FAILED:
7504 cpuset_update_active_cpus();
7511 static int cpuset_cpu_inactive(struct notifier_block *nfb, unsigned long action,
7514 switch (action & ~CPU_TASKS_FROZEN) {
7515 case CPU_DOWN_PREPARE:
7516 cpuset_update_active_cpus();
7523 static int update_runtime(struct notifier_block *nfb,
7524 unsigned long action, void *hcpu)
7526 int cpu = (int)(long)hcpu;
7529 case CPU_DOWN_PREPARE:
7530 case CPU_DOWN_PREPARE_FROZEN:
7531 disable_runtime(cpu_rq(cpu));
7534 case CPU_DOWN_FAILED:
7535 case CPU_DOWN_FAILED_FROZEN:
7537 case CPU_ONLINE_FROZEN:
7538 enable_runtime(cpu_rq(cpu));
7546 void __init sched_init_smp(void)
7548 cpumask_var_t non_isolated_cpus;
7550 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
7551 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
7553 #if defined(CONFIG_NUMA)
7554 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
7556 BUG_ON(sched_group_nodes_bycpu == NULL);
7559 mutex_lock(&sched_domains_mutex);
7560 arch_init_sched_domains(cpu_active_mask);
7561 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
7562 if (cpumask_empty(non_isolated_cpus))
7563 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
7564 mutex_unlock(&sched_domains_mutex);
7567 hotcpu_notifier(cpuset_cpu_active, CPU_PRI_CPUSET_ACTIVE);
7568 hotcpu_notifier(cpuset_cpu_inactive, CPU_PRI_CPUSET_INACTIVE);
7570 /* RT runtime code needs to handle some hotplug events */
7571 hotcpu_notifier(update_runtime, 0);
7575 /* Move init over to a non-isolated CPU */
7576 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
7578 sched_init_granularity();
7579 free_cpumask_var(non_isolated_cpus);
7581 init_sched_rt_class();
7584 void __init sched_init_smp(void)
7586 sched_init_granularity();
7588 #endif /* CONFIG_SMP */
7590 const_debug unsigned int sysctl_timer_migration = 1;
7592 int in_sched_functions(unsigned long addr)
7594 return in_lock_functions(addr) ||
7595 (addr >= (unsigned long)__sched_text_start
7596 && addr < (unsigned long)__sched_text_end);
7599 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
7601 cfs_rq->tasks_timeline = RB_ROOT;
7602 INIT_LIST_HEAD(&cfs_rq->tasks);
7603 #ifdef CONFIG_FAIR_GROUP_SCHED
7606 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7609 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
7611 struct rt_prio_array *array;
7614 array = &rt_rq->active;
7615 for (i = 0; i < MAX_RT_PRIO; i++) {
7616 INIT_LIST_HEAD(array->queue + i);
7617 __clear_bit(i, array->bitmap);
7619 /* delimiter for bitsearch: */
7620 __set_bit(MAX_RT_PRIO, array->bitmap);
7622 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
7623 rt_rq->highest_prio.curr = MAX_RT_PRIO;
7625 rt_rq->highest_prio.next = MAX_RT_PRIO;
7629 rt_rq->rt_nr_migratory = 0;
7630 rt_rq->overloaded = 0;
7631 plist_head_init_raw(&rt_rq->pushable_tasks, &rq->lock);
7635 rt_rq->rt_throttled = 0;
7636 rt_rq->rt_runtime = 0;
7637 raw_spin_lock_init(&rt_rq->rt_runtime_lock);
7639 #ifdef CONFIG_RT_GROUP_SCHED
7640 rt_rq->rt_nr_boosted = 0;
7645 #ifdef CONFIG_FAIR_GROUP_SCHED
7646 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
7647 struct sched_entity *se, int cpu,
7648 struct sched_entity *parent)
7650 struct rq *rq = cpu_rq(cpu);
7651 tg->cfs_rq[cpu] = cfs_rq;
7652 init_cfs_rq(cfs_rq, rq);
7656 /* se could be NULL for init_task_group */
7661 se->cfs_rq = &rq->cfs;
7663 se->cfs_rq = parent->my_q;
7666 update_load_set(&se->load, 0);
7667 se->parent = parent;
7671 #ifdef CONFIG_RT_GROUP_SCHED
7672 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
7673 struct sched_rt_entity *rt_se, int cpu,
7674 struct sched_rt_entity *parent)
7676 struct rq *rq = cpu_rq(cpu);
7678 tg->rt_rq[cpu] = rt_rq;
7679 init_rt_rq(rt_rq, rq);
7681 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
7683 tg->rt_se[cpu] = rt_se;
7688 rt_se->rt_rq = &rq->rt;
7690 rt_se->rt_rq = parent->my_q;
7692 rt_se->my_q = rt_rq;
7693 rt_se->parent = parent;
7694 INIT_LIST_HEAD(&rt_se->run_list);
7698 void __init sched_init(void)
7701 unsigned long alloc_size = 0, ptr;
7703 #ifdef CONFIG_FAIR_GROUP_SCHED
7704 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7706 #ifdef CONFIG_RT_GROUP_SCHED
7707 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7709 #ifdef CONFIG_CPUMASK_OFFSTACK
7710 alloc_size += num_possible_cpus() * cpumask_size();
7713 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
7715 #ifdef CONFIG_FAIR_GROUP_SCHED
7716 init_task_group.se = (struct sched_entity **)ptr;
7717 ptr += nr_cpu_ids * sizeof(void **);
7719 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
7720 ptr += nr_cpu_ids * sizeof(void **);
7722 #endif /* CONFIG_FAIR_GROUP_SCHED */
7723 #ifdef CONFIG_RT_GROUP_SCHED
7724 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
7725 ptr += nr_cpu_ids * sizeof(void **);
7727 init_task_group.rt_rq = (struct rt_rq **)ptr;
7728 ptr += nr_cpu_ids * sizeof(void **);
7730 #endif /* CONFIG_RT_GROUP_SCHED */
7731 #ifdef CONFIG_CPUMASK_OFFSTACK
7732 for_each_possible_cpu(i) {
7733 per_cpu(load_balance_tmpmask, i) = (void *)ptr;
7734 ptr += cpumask_size();
7736 #endif /* CONFIG_CPUMASK_OFFSTACK */
7740 init_defrootdomain();
7743 init_rt_bandwidth(&def_rt_bandwidth,
7744 global_rt_period(), global_rt_runtime());
7746 #ifdef CONFIG_RT_GROUP_SCHED
7747 init_rt_bandwidth(&init_task_group.rt_bandwidth,
7748 global_rt_period(), global_rt_runtime());
7749 #endif /* CONFIG_RT_GROUP_SCHED */
7751 #ifdef CONFIG_CGROUP_SCHED
7752 list_add(&init_task_group.list, &task_groups);
7753 INIT_LIST_HEAD(&init_task_group.children);
7755 #endif /* CONFIG_CGROUP_SCHED */
7757 for_each_possible_cpu(i) {
7761 raw_spin_lock_init(&rq->lock);
7763 rq->calc_load_active = 0;
7764 rq->calc_load_update = jiffies + LOAD_FREQ;
7765 init_cfs_rq(&rq->cfs, rq);
7766 init_rt_rq(&rq->rt, rq);
7767 #ifdef CONFIG_FAIR_GROUP_SCHED
7768 init_task_group.shares = init_task_group_load;
7769 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7770 #ifdef CONFIG_CGROUP_SCHED
7772 * How much cpu bandwidth does init_task_group get?
7774 * In case of task-groups formed thr' the cgroup filesystem, it
7775 * gets 100% of the cpu resources in the system. This overall
7776 * system cpu resource is divided among the tasks of
7777 * init_task_group and its child task-groups in a fair manner,
7778 * based on each entity's (task or task-group's) weight
7779 * (se->load.weight).
7781 * In other words, if init_task_group has 10 tasks of weight
7782 * 1024) and two child groups A0 and A1 (of weight 1024 each),
7783 * then A0's share of the cpu resource is:
7785 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
7787 * We achieve this by letting init_task_group's tasks sit
7788 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
7790 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, NULL);
7792 #endif /* CONFIG_FAIR_GROUP_SCHED */
7794 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
7795 #ifdef CONFIG_RT_GROUP_SCHED
7796 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
7797 #ifdef CONFIG_CGROUP_SCHED
7798 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, NULL);
7802 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7803 rq->cpu_load[j] = 0;
7805 rq->last_load_update_tick = jiffies;
7810 rq->cpu_power = SCHED_LOAD_SCALE;
7811 rq->post_schedule = 0;
7812 rq->active_balance = 0;
7813 rq->next_balance = jiffies;
7818 rq->avg_idle = 2*sysctl_sched_migration_cost;
7819 rq_attach_root(rq, &def_root_domain);
7821 rq->nohz_balance_kick = 0;
7822 init_sched_softirq_csd(&per_cpu(remote_sched_softirq_cb, i));
7826 atomic_set(&rq->nr_iowait, 0);
7829 set_load_weight(&init_task);
7831 #ifdef CONFIG_PREEMPT_NOTIFIERS
7832 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
7836 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
7839 #ifdef CONFIG_RT_MUTEXES
7840 plist_head_init_raw(&init_task.pi_waiters, &init_task.pi_lock);
7844 * The boot idle thread does lazy MMU switching as well:
7846 atomic_inc(&init_mm.mm_count);
7847 enter_lazy_tlb(&init_mm, current);
7850 * Make us the idle thread. Technically, schedule() should not be
7851 * called from this thread, however somewhere below it might be,
7852 * but because we are the idle thread, we just pick up running again
7853 * when this runqueue becomes "idle".
7855 init_idle(current, smp_processor_id());
7857 calc_load_update = jiffies + LOAD_FREQ;
7860 * During early bootup we pretend to be a normal task:
7862 current->sched_class = &fair_sched_class;
7864 /* Allocate the nohz_cpu_mask if CONFIG_CPUMASK_OFFSTACK */
7865 zalloc_cpumask_var(&nohz_cpu_mask, GFP_NOWAIT);
7868 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
7869 alloc_cpumask_var(&nohz.grp_idle_mask, GFP_NOWAIT);
7870 atomic_set(&nohz.load_balancer, nr_cpu_ids);
7871 atomic_set(&nohz.first_pick_cpu, nr_cpu_ids);
7872 atomic_set(&nohz.second_pick_cpu, nr_cpu_ids);
7874 /* May be allocated at isolcpus cmdline parse time */
7875 if (cpu_isolated_map == NULL)
7876 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
7881 scheduler_running = 1;
7884 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
7885 static inline int preempt_count_equals(int preempt_offset)
7887 int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth();
7889 return (nested == PREEMPT_INATOMIC_BASE + preempt_offset);
7892 void __might_sleep(const char *file, int line, int preempt_offset)
7895 static unsigned long prev_jiffy; /* ratelimiting */
7897 if ((preempt_count_equals(preempt_offset) && !irqs_disabled()) ||
7898 system_state != SYSTEM_RUNNING || oops_in_progress)
7900 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7902 prev_jiffy = jiffies;
7905 "BUG: sleeping function called from invalid context at %s:%d\n",
7908 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
7909 in_atomic(), irqs_disabled(),
7910 current->pid, current->comm);
7912 debug_show_held_locks(current);
7913 if (irqs_disabled())
7914 print_irqtrace_events(current);
7918 EXPORT_SYMBOL(__might_sleep);
7921 #ifdef CONFIG_MAGIC_SYSRQ
7922 static void normalize_task(struct rq *rq, struct task_struct *p)
7926 on_rq = p->se.on_rq;
7928 deactivate_task(rq, p, 0);
7929 __setscheduler(rq, p, SCHED_NORMAL, 0);
7931 activate_task(rq, p, 0);
7932 resched_task(rq->curr);
7936 void normalize_rt_tasks(void)
7938 struct task_struct *g, *p;
7939 unsigned long flags;
7942 read_lock_irqsave(&tasklist_lock, flags);
7943 do_each_thread(g, p) {
7945 * Only normalize user tasks:
7950 p->se.exec_start = 0;
7951 #ifdef CONFIG_SCHEDSTATS
7952 p->se.statistics.wait_start = 0;
7953 p->se.statistics.sleep_start = 0;
7954 p->se.statistics.block_start = 0;
7959 * Renice negative nice level userspace
7962 if (TASK_NICE(p) < 0 && p->mm)
7963 set_user_nice(p, 0);
7967 raw_spin_lock(&p->pi_lock);
7968 rq = __task_rq_lock(p);
7970 normalize_task(rq, p);
7972 __task_rq_unlock(rq);
7973 raw_spin_unlock(&p->pi_lock);
7974 } while_each_thread(g, p);
7976 read_unlock_irqrestore(&tasklist_lock, flags);
7979 #endif /* CONFIG_MAGIC_SYSRQ */
7981 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
7983 * These functions are only useful for the IA64 MCA handling, or kdb.
7985 * They can only be called when the whole system has been
7986 * stopped - every CPU needs to be quiescent, and no scheduling
7987 * activity can take place. Using them for anything else would
7988 * be a serious bug, and as a result, they aren't even visible
7989 * under any other configuration.
7993 * curr_task - return the current task for a given cpu.
7994 * @cpu: the processor in question.
7996 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7998 struct task_struct *curr_task(int cpu)
8000 return cpu_curr(cpu);
8003 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
8007 * set_curr_task - set the current task for a given cpu.
8008 * @cpu: the processor in question.
8009 * @p: the task pointer to set.
8011 * Description: This function must only be used when non-maskable interrupts
8012 * are serviced on a separate stack. It allows the architecture to switch the
8013 * notion of the current task on a cpu in a non-blocking manner. This function
8014 * must be called with all CPU's synchronized, and interrupts disabled, the
8015 * and caller must save the original value of the current task (see
8016 * curr_task() above) and restore that value before reenabling interrupts and
8017 * re-starting the system.
8019 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8021 void set_curr_task(int cpu, struct task_struct *p)
8028 #ifdef CONFIG_FAIR_GROUP_SCHED
8029 static void free_fair_sched_group(struct task_group *tg)
8033 for_each_possible_cpu(i) {
8035 kfree(tg->cfs_rq[i]);
8045 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8047 struct cfs_rq *cfs_rq;
8048 struct sched_entity *se;
8052 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
8055 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
8059 tg->shares = NICE_0_LOAD;
8061 for_each_possible_cpu(i) {
8064 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
8065 GFP_KERNEL, cpu_to_node(i));
8069 se = kzalloc_node(sizeof(struct sched_entity),
8070 GFP_KERNEL, cpu_to_node(i));
8074 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
8085 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8087 struct rq *rq = cpu_rq(cpu);
8088 unsigned long flags;
8092 * Only empty task groups can be destroyed; so we can speculatively
8093 * check on_list without danger of it being re-added.
8095 if (!tg->cfs_rq[cpu]->on_list)
8098 raw_spin_lock_irqsave(&rq->lock, flags);
8099 list_del_leaf_cfs_rq(tg->cfs_rq[i]);
8100 raw_spin_unlock_irqrestore(&rq->lock, flags);
8102 #else /* !CONFG_FAIR_GROUP_SCHED */
8103 static inline void free_fair_sched_group(struct task_group *tg)
8108 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8113 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8116 #endif /* CONFIG_FAIR_GROUP_SCHED */
8118 #ifdef CONFIG_RT_GROUP_SCHED
8119 static void free_rt_sched_group(struct task_group *tg)
8123 destroy_rt_bandwidth(&tg->rt_bandwidth);
8125 for_each_possible_cpu(i) {
8127 kfree(tg->rt_rq[i]);
8129 kfree(tg->rt_se[i]);
8137 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8139 struct rt_rq *rt_rq;
8140 struct sched_rt_entity *rt_se;
8144 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
8147 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
8151 init_rt_bandwidth(&tg->rt_bandwidth,
8152 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
8154 for_each_possible_cpu(i) {
8157 rt_rq = kzalloc_node(sizeof(struct rt_rq),
8158 GFP_KERNEL, cpu_to_node(i));
8162 rt_se = kzalloc_node(sizeof(struct sched_rt_entity),
8163 GFP_KERNEL, cpu_to_node(i));
8167 init_tg_rt_entry(tg, rt_rq, rt_se, i, parent->rt_se[i]);
8177 #else /* !CONFIG_RT_GROUP_SCHED */
8178 static inline void free_rt_sched_group(struct task_group *tg)
8183 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8187 #endif /* CONFIG_RT_GROUP_SCHED */
8189 #ifdef CONFIG_CGROUP_SCHED
8190 static void free_sched_group(struct task_group *tg)
8192 free_fair_sched_group(tg);
8193 free_rt_sched_group(tg);
8197 /* allocate runqueue etc for a new task group */
8198 struct task_group *sched_create_group(struct task_group *parent)
8200 struct task_group *tg;
8201 unsigned long flags;
8203 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
8205 return ERR_PTR(-ENOMEM);
8207 if (!alloc_fair_sched_group(tg, parent))
8210 if (!alloc_rt_sched_group(tg, parent))
8213 spin_lock_irqsave(&task_group_lock, flags);
8214 list_add_rcu(&tg->list, &task_groups);
8216 WARN_ON(!parent); /* root should already exist */
8218 tg->parent = parent;
8219 INIT_LIST_HEAD(&tg->children);
8220 list_add_rcu(&tg->siblings, &parent->children);
8221 spin_unlock_irqrestore(&task_group_lock, flags);
8226 free_sched_group(tg);
8227 return ERR_PTR(-ENOMEM);
8230 /* rcu callback to free various structures associated with a task group */
8231 static void free_sched_group_rcu(struct rcu_head *rhp)
8233 /* now it should be safe to free those cfs_rqs */
8234 free_sched_group(container_of(rhp, struct task_group, rcu));
8237 /* Destroy runqueue etc associated with a task group */
8238 void sched_destroy_group(struct task_group *tg)
8240 unsigned long flags;
8243 /* end participation in shares distribution */
8244 for_each_possible_cpu(i)
8245 unregister_fair_sched_group(tg, i);
8247 spin_lock_irqsave(&task_group_lock, flags);
8248 list_del_rcu(&tg->list);
8249 list_del_rcu(&tg->siblings);
8250 spin_unlock_irqrestore(&task_group_lock, flags);
8252 /* wait for possible concurrent references to cfs_rqs complete */
8253 call_rcu(&tg->rcu, free_sched_group_rcu);
8256 /* change task's runqueue when it moves between groups.
8257 * The caller of this function should have put the task in its new group
8258 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8259 * reflect its new group.
8261 void sched_move_task(struct task_struct *tsk)
8264 unsigned long flags;
8267 rq = task_rq_lock(tsk, &flags);
8269 running = task_current(rq, tsk);
8270 on_rq = tsk->se.on_rq;
8273 dequeue_task(rq, tsk, 0);
8274 if (unlikely(running))
8275 tsk->sched_class->put_prev_task(rq, tsk);
8277 #ifdef CONFIG_FAIR_GROUP_SCHED
8278 if (tsk->sched_class->task_move_group)
8279 tsk->sched_class->task_move_group(tsk, on_rq);
8282 set_task_rq(tsk, task_cpu(tsk));
8284 if (unlikely(running))
8285 tsk->sched_class->set_curr_task(rq);
8287 enqueue_task(rq, tsk, 0);
8289 task_rq_unlock(rq, &flags);
8291 #endif /* CONFIG_CGROUP_SCHED */
8293 #ifdef CONFIG_FAIR_GROUP_SCHED
8294 static DEFINE_MUTEX(shares_mutex);
8296 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8299 unsigned long flags;
8302 * We can't change the weight of the root cgroup.
8307 if (shares < MIN_SHARES)
8308 shares = MIN_SHARES;
8309 else if (shares > MAX_SHARES)
8310 shares = MAX_SHARES;
8312 mutex_lock(&shares_mutex);
8313 if (tg->shares == shares)
8316 tg->shares = shares;
8317 for_each_possible_cpu(i) {
8318 struct rq *rq = cpu_rq(i);
8319 struct sched_entity *se;
8322 /* Propagate contribution to hierarchy */
8323 raw_spin_lock_irqsave(&rq->lock, flags);
8324 for_each_sched_entity(se)
8325 update_cfs_shares(group_cfs_rq(se), 0);
8326 raw_spin_unlock_irqrestore(&rq->lock, flags);
8330 mutex_unlock(&shares_mutex);
8334 unsigned long sched_group_shares(struct task_group *tg)
8340 #ifdef CONFIG_RT_GROUP_SCHED
8342 * Ensure that the real time constraints are schedulable.
8344 static DEFINE_MUTEX(rt_constraints_mutex);
8346 static unsigned long to_ratio(u64 period, u64 runtime)
8348 if (runtime == RUNTIME_INF)
8351 return div64_u64(runtime << 20, period);
8354 /* Must be called with tasklist_lock held */
8355 static inline int tg_has_rt_tasks(struct task_group *tg)
8357 struct task_struct *g, *p;
8359 do_each_thread(g, p) {
8360 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
8362 } while_each_thread(g, p);
8367 struct rt_schedulable_data {
8368 struct task_group *tg;
8373 static int tg_schedulable(struct task_group *tg, void *data)
8375 struct rt_schedulable_data *d = data;
8376 struct task_group *child;
8377 unsigned long total, sum = 0;
8378 u64 period, runtime;
8380 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8381 runtime = tg->rt_bandwidth.rt_runtime;
8384 period = d->rt_period;
8385 runtime = d->rt_runtime;
8389 * Cannot have more runtime than the period.
8391 if (runtime > period && runtime != RUNTIME_INF)
8395 * Ensure we don't starve existing RT tasks.
8397 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
8400 total = to_ratio(period, runtime);
8403 * Nobody can have more than the global setting allows.
8405 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
8409 * The sum of our children's runtime should not exceed our own.
8411 list_for_each_entry_rcu(child, &tg->children, siblings) {
8412 period = ktime_to_ns(child->rt_bandwidth.rt_period);
8413 runtime = child->rt_bandwidth.rt_runtime;
8415 if (child == d->tg) {
8416 period = d->rt_period;
8417 runtime = d->rt_runtime;
8420 sum += to_ratio(period, runtime);
8429 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8431 struct rt_schedulable_data data = {
8433 .rt_period = period,
8434 .rt_runtime = runtime,
8437 return walk_tg_tree(tg_schedulable, tg_nop, &data);
8440 static int tg_set_bandwidth(struct task_group *tg,
8441 u64 rt_period, u64 rt_runtime)
8445 mutex_lock(&rt_constraints_mutex);
8446 read_lock(&tasklist_lock);
8447 err = __rt_schedulable(tg, rt_period, rt_runtime);
8451 raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8452 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8453 tg->rt_bandwidth.rt_runtime = rt_runtime;
8455 for_each_possible_cpu(i) {
8456 struct rt_rq *rt_rq = tg->rt_rq[i];
8458 raw_spin_lock(&rt_rq->rt_runtime_lock);
8459 rt_rq->rt_runtime = rt_runtime;
8460 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8462 raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8464 read_unlock(&tasklist_lock);
8465 mutex_unlock(&rt_constraints_mutex);
8470 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8472 u64 rt_runtime, rt_period;
8474 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8475 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8476 if (rt_runtime_us < 0)
8477 rt_runtime = RUNTIME_INF;
8479 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8482 long sched_group_rt_runtime(struct task_group *tg)
8486 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8489 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8490 do_div(rt_runtime_us, NSEC_PER_USEC);
8491 return rt_runtime_us;
8494 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
8496 u64 rt_runtime, rt_period;
8498 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
8499 rt_runtime = tg->rt_bandwidth.rt_runtime;
8504 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8507 long sched_group_rt_period(struct task_group *tg)
8511 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8512 do_div(rt_period_us, NSEC_PER_USEC);
8513 return rt_period_us;
8516 static int sched_rt_global_constraints(void)
8518 u64 runtime, period;
8521 if (sysctl_sched_rt_period <= 0)
8524 runtime = global_rt_runtime();
8525 period = global_rt_period();
8528 * Sanity check on the sysctl variables.
8530 if (runtime > period && runtime != RUNTIME_INF)
8533 mutex_lock(&rt_constraints_mutex);
8534 read_lock(&tasklist_lock);
8535 ret = __rt_schedulable(NULL, 0, 0);
8536 read_unlock(&tasklist_lock);
8537 mutex_unlock(&rt_constraints_mutex);
8542 int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
8544 /* Don't accept realtime tasks when there is no way for them to run */
8545 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
8551 #else /* !CONFIG_RT_GROUP_SCHED */
8552 static int sched_rt_global_constraints(void)
8554 unsigned long flags;
8557 if (sysctl_sched_rt_period <= 0)
8561 * There's always some RT tasks in the root group
8562 * -- migration, kstopmachine etc..
8564 if (sysctl_sched_rt_runtime == 0)
8567 raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
8568 for_each_possible_cpu(i) {
8569 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
8571 raw_spin_lock(&rt_rq->rt_runtime_lock);
8572 rt_rq->rt_runtime = global_rt_runtime();
8573 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8575 raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
8579 #endif /* CONFIG_RT_GROUP_SCHED */
8581 int sched_rt_handler(struct ctl_table *table, int write,
8582 void __user *buffer, size_t *lenp,
8586 int old_period, old_runtime;
8587 static DEFINE_MUTEX(mutex);
8590 old_period = sysctl_sched_rt_period;
8591 old_runtime = sysctl_sched_rt_runtime;
8593 ret = proc_dointvec(table, write, buffer, lenp, ppos);
8595 if (!ret && write) {
8596 ret = sched_rt_global_constraints();
8598 sysctl_sched_rt_period = old_period;
8599 sysctl_sched_rt_runtime = old_runtime;
8601 def_rt_bandwidth.rt_runtime = global_rt_runtime();
8602 def_rt_bandwidth.rt_period =
8603 ns_to_ktime(global_rt_period());
8606 mutex_unlock(&mutex);
8611 #ifdef CONFIG_CGROUP_SCHED
8613 /* return corresponding task_group object of a cgroup */
8614 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
8616 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
8617 struct task_group, css);
8620 static struct cgroup_subsys_state *
8621 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
8623 struct task_group *tg, *parent;
8625 if (!cgrp->parent) {
8626 /* This is early initialization for the top cgroup */
8627 return &init_task_group.css;
8630 parent = cgroup_tg(cgrp->parent);
8631 tg = sched_create_group(parent);
8633 return ERR_PTR(-ENOMEM);
8639 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
8641 struct task_group *tg = cgroup_tg(cgrp);
8643 sched_destroy_group(tg);
8647 cpu_cgroup_can_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
8649 #ifdef CONFIG_RT_GROUP_SCHED
8650 if (!sched_rt_can_attach(cgroup_tg(cgrp), tsk))
8653 /* We don't support RT-tasks being in separate groups */
8654 if (tsk->sched_class != &fair_sched_class)
8661 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8662 struct task_struct *tsk, bool threadgroup)
8664 int retval = cpu_cgroup_can_attach_task(cgrp, tsk);
8668 struct task_struct *c;
8670 list_for_each_entry_rcu(c, &tsk->thread_group, thread_group) {
8671 retval = cpu_cgroup_can_attach_task(cgrp, c);
8683 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8684 struct cgroup *old_cont, struct task_struct *tsk,
8687 sched_move_task(tsk);
8689 struct task_struct *c;
8691 list_for_each_entry_rcu(c, &tsk->thread_group, thread_group) {
8698 #ifdef CONFIG_FAIR_GROUP_SCHED
8699 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
8702 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
8705 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
8707 struct task_group *tg = cgroup_tg(cgrp);
8709 return (u64) tg->shares;
8711 #endif /* CONFIG_FAIR_GROUP_SCHED */
8713 #ifdef CONFIG_RT_GROUP_SCHED
8714 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
8717 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
8720 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
8722 return sched_group_rt_runtime(cgroup_tg(cgrp));
8725 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
8728 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
8731 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
8733 return sched_group_rt_period(cgroup_tg(cgrp));
8735 #endif /* CONFIG_RT_GROUP_SCHED */
8737 static struct cftype cpu_files[] = {
8738 #ifdef CONFIG_FAIR_GROUP_SCHED
8741 .read_u64 = cpu_shares_read_u64,
8742 .write_u64 = cpu_shares_write_u64,
8745 #ifdef CONFIG_RT_GROUP_SCHED
8747 .name = "rt_runtime_us",
8748 .read_s64 = cpu_rt_runtime_read,
8749 .write_s64 = cpu_rt_runtime_write,
8752 .name = "rt_period_us",
8753 .read_u64 = cpu_rt_period_read_uint,
8754 .write_u64 = cpu_rt_period_write_uint,
8759 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
8761 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
8764 struct cgroup_subsys cpu_cgroup_subsys = {
8766 .create = cpu_cgroup_create,
8767 .destroy = cpu_cgroup_destroy,
8768 .can_attach = cpu_cgroup_can_attach,
8769 .attach = cpu_cgroup_attach,
8770 .populate = cpu_cgroup_populate,
8771 .subsys_id = cpu_cgroup_subsys_id,
8775 #endif /* CONFIG_CGROUP_SCHED */
8777 #ifdef CONFIG_CGROUP_CPUACCT
8780 * CPU accounting code for task groups.
8782 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
8783 * (balbir@in.ibm.com).
8786 /* track cpu usage of a group of tasks and its child groups */
8788 struct cgroup_subsys_state css;
8789 /* cpuusage holds pointer to a u64-type object on every cpu */
8790 u64 __percpu *cpuusage;
8791 struct percpu_counter cpustat[CPUACCT_STAT_NSTATS];
8792 struct cpuacct *parent;
8795 struct cgroup_subsys cpuacct_subsys;
8797 /* return cpu accounting group corresponding to this container */
8798 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
8800 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
8801 struct cpuacct, css);
8804 /* return cpu accounting group to which this task belongs */
8805 static inline struct cpuacct *task_ca(struct task_struct *tsk)
8807 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
8808 struct cpuacct, css);
8811 /* create a new cpu accounting group */
8812 static struct cgroup_subsys_state *cpuacct_create(
8813 struct cgroup_subsys *ss, struct cgroup *cgrp)
8815 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
8821 ca->cpuusage = alloc_percpu(u64);
8825 for (i = 0; i < CPUACCT_STAT_NSTATS; i++)
8826 if (percpu_counter_init(&ca->cpustat[i], 0))
8827 goto out_free_counters;
8830 ca->parent = cgroup_ca(cgrp->parent);
8836 percpu_counter_destroy(&ca->cpustat[i]);
8837 free_percpu(ca->cpuusage);
8841 return ERR_PTR(-ENOMEM);
8844 /* destroy an existing cpu accounting group */
8846 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
8848 struct cpuacct *ca = cgroup_ca(cgrp);
8851 for (i = 0; i < CPUACCT_STAT_NSTATS; i++)
8852 percpu_counter_destroy(&ca->cpustat[i]);
8853 free_percpu(ca->cpuusage);
8857 static u64 cpuacct_cpuusage_read(struct cpuacct *ca, int cpu)
8859 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
8862 #ifndef CONFIG_64BIT
8864 * Take rq->lock to make 64-bit read safe on 32-bit platforms.
8866 raw_spin_lock_irq(&cpu_rq(cpu)->lock);
8868 raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
8876 static void cpuacct_cpuusage_write(struct cpuacct *ca, int cpu, u64 val)
8878 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
8880 #ifndef CONFIG_64BIT
8882 * Take rq->lock to make 64-bit write safe on 32-bit platforms.
8884 raw_spin_lock_irq(&cpu_rq(cpu)->lock);
8886 raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
8892 /* return total cpu usage (in nanoseconds) of a group */
8893 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
8895 struct cpuacct *ca = cgroup_ca(cgrp);
8896 u64 totalcpuusage = 0;
8899 for_each_present_cpu(i)
8900 totalcpuusage += cpuacct_cpuusage_read(ca, i);
8902 return totalcpuusage;
8905 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
8908 struct cpuacct *ca = cgroup_ca(cgrp);
8917 for_each_present_cpu(i)
8918 cpuacct_cpuusage_write(ca, i, 0);
8924 static int cpuacct_percpu_seq_read(struct cgroup *cgroup, struct cftype *cft,
8927 struct cpuacct *ca = cgroup_ca(cgroup);
8931 for_each_present_cpu(i) {
8932 percpu = cpuacct_cpuusage_read(ca, i);
8933 seq_printf(m, "%llu ", (unsigned long long) percpu);
8935 seq_printf(m, "\n");
8939 static const char *cpuacct_stat_desc[] = {
8940 [CPUACCT_STAT_USER] = "user",
8941 [CPUACCT_STAT_SYSTEM] = "system",
8944 static int cpuacct_stats_show(struct cgroup *cgrp, struct cftype *cft,
8945 struct cgroup_map_cb *cb)
8947 struct cpuacct *ca = cgroup_ca(cgrp);
8950 for (i = 0; i < CPUACCT_STAT_NSTATS; i++) {
8951 s64 val = percpu_counter_read(&ca->cpustat[i]);
8952 val = cputime64_to_clock_t(val);
8953 cb->fill(cb, cpuacct_stat_desc[i], val);
8958 static struct cftype files[] = {
8961 .read_u64 = cpuusage_read,
8962 .write_u64 = cpuusage_write,
8965 .name = "usage_percpu",
8966 .read_seq_string = cpuacct_percpu_seq_read,
8970 .read_map = cpuacct_stats_show,
8974 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
8976 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
8980 * charge this task's execution time to its accounting group.
8982 * called with rq->lock held.
8984 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
8989 if (unlikely(!cpuacct_subsys.active))
8992 cpu = task_cpu(tsk);
8998 for (; ca; ca = ca->parent) {
8999 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
9000 *cpuusage += cputime;
9007 * When CONFIG_VIRT_CPU_ACCOUNTING is enabled one jiffy can be very large
9008 * in cputime_t units. As a result, cpuacct_update_stats calls
9009 * percpu_counter_add with values large enough to always overflow the
9010 * per cpu batch limit causing bad SMP scalability.
9012 * To fix this we scale percpu_counter_batch by cputime_one_jiffy so we
9013 * batch the same amount of time with CONFIG_VIRT_CPU_ACCOUNTING disabled
9014 * and enabled. We cap it at INT_MAX which is the largest allowed batch value.
9017 #define CPUACCT_BATCH \
9018 min_t(long, percpu_counter_batch * cputime_one_jiffy, INT_MAX)
9020 #define CPUACCT_BATCH 0
9024 * Charge the system/user time to the task's accounting group.
9026 static void cpuacct_update_stats(struct task_struct *tsk,
9027 enum cpuacct_stat_index idx, cputime_t val)
9030 int batch = CPUACCT_BATCH;
9032 if (unlikely(!cpuacct_subsys.active))
9039 __percpu_counter_add(&ca->cpustat[idx], val, batch);
9045 struct cgroup_subsys cpuacct_subsys = {
9047 .create = cpuacct_create,
9048 .destroy = cpuacct_destroy,
9049 .populate = cpuacct_populate,
9050 .subsys_id = cpuacct_subsys_id,
9052 #endif /* CONFIG_CGROUP_CPUACCT */
9056 void synchronize_sched_expedited(void)
9060 EXPORT_SYMBOL_GPL(synchronize_sched_expedited);
9062 #else /* #ifndef CONFIG_SMP */
9064 static atomic_t synchronize_sched_expedited_count = ATOMIC_INIT(0);
9066 static int synchronize_sched_expedited_cpu_stop(void *data)
9069 * There must be a full memory barrier on each affected CPU
9070 * between the time that try_stop_cpus() is called and the
9071 * time that it returns.
9073 * In the current initial implementation of cpu_stop, the
9074 * above condition is already met when the control reaches
9075 * this point and the following smp_mb() is not strictly
9076 * necessary. Do smp_mb() anyway for documentation and
9077 * robustness against future implementation changes.
9079 smp_mb(); /* See above comment block. */
9084 * Wait for an rcu-sched grace period to elapse, but use "big hammer"
9085 * approach to force grace period to end quickly. This consumes
9086 * significant time on all CPUs, and is thus not recommended for
9087 * any sort of common-case code.
9089 * Note that it is illegal to call this function while holding any
9090 * lock that is acquired by a CPU-hotplug notifier. Failing to
9091 * observe this restriction will result in deadlock.
9093 void synchronize_sched_expedited(void)
9095 int snap, trycount = 0;
9097 smp_mb(); /* ensure prior mod happens before capturing snap. */
9098 snap = atomic_read(&synchronize_sched_expedited_count) + 1;
9100 while (try_stop_cpus(cpu_online_mask,
9101 synchronize_sched_expedited_cpu_stop,
9104 if (trycount++ < 10)
9105 udelay(trycount * num_online_cpus());
9107 synchronize_sched();
9110 if (atomic_read(&synchronize_sched_expedited_count) - snap > 0) {
9111 smp_mb(); /* ensure test happens before caller kfree */
9116 atomic_inc(&synchronize_sched_expedited_count);
9117 smp_mb__after_atomic_inc(); /* ensure post-GP actions seen after GP. */
9120 EXPORT_SYMBOL_GPL(synchronize_sched_expedited);
9122 #endif /* #else #ifndef CONFIG_SMP */