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>
78 #include <asm/mutex.h>
80 #include "sched_cpupri.h"
81 #include "workqueue_sched.h"
83 #define CREATE_TRACE_POINTS
84 #include <trace/events/sched.h>
87 * Convert user-nice values [ -20 ... 0 ... 19 ]
88 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
91 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
92 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
93 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
96 * 'User priority' is the nice value converted to something we
97 * can work with better when scaling various scheduler parameters,
98 * it's a [ 0 ... 39 ] range.
100 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
101 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
102 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
105 * Helpers for converting nanosecond timing to jiffy resolution
107 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
109 #define NICE_0_LOAD SCHED_LOAD_SCALE
110 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
113 * These are the 'tuning knobs' of the scheduler:
115 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
116 * Timeslices get refilled after they expire.
118 #define DEF_TIMESLICE (100 * HZ / 1000)
121 * single value that denotes runtime == period, ie unlimited time.
123 #define RUNTIME_INF ((u64)~0ULL)
125 static inline int rt_policy(int policy)
127 if (unlikely(policy == SCHED_FIFO || policy == SCHED_RR))
132 static inline int task_has_rt_policy(struct task_struct *p)
134 return rt_policy(p->policy);
138 * This is the priority-queue data structure of the RT scheduling class:
140 struct rt_prio_array {
141 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
142 struct list_head queue[MAX_RT_PRIO];
145 struct rt_bandwidth {
146 /* nests inside the rq lock: */
147 raw_spinlock_t rt_runtime_lock;
150 struct hrtimer rt_period_timer;
153 static struct rt_bandwidth def_rt_bandwidth;
155 static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
157 static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
159 struct rt_bandwidth *rt_b =
160 container_of(timer, struct rt_bandwidth, rt_period_timer);
166 now = hrtimer_cb_get_time(timer);
167 overrun = hrtimer_forward(timer, now, rt_b->rt_period);
172 idle = do_sched_rt_period_timer(rt_b, overrun);
175 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
179 void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
181 rt_b->rt_period = ns_to_ktime(period);
182 rt_b->rt_runtime = runtime;
184 raw_spin_lock_init(&rt_b->rt_runtime_lock);
186 hrtimer_init(&rt_b->rt_period_timer,
187 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
188 rt_b->rt_period_timer.function = sched_rt_period_timer;
191 static inline int rt_bandwidth_enabled(void)
193 return sysctl_sched_rt_runtime >= 0;
196 static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
200 if (!rt_bandwidth_enabled() || rt_b->rt_runtime == RUNTIME_INF)
203 if (hrtimer_active(&rt_b->rt_period_timer))
206 raw_spin_lock(&rt_b->rt_runtime_lock);
211 if (hrtimer_active(&rt_b->rt_period_timer))
214 now = hrtimer_cb_get_time(&rt_b->rt_period_timer);
215 hrtimer_forward(&rt_b->rt_period_timer, now, rt_b->rt_period);
217 soft = hrtimer_get_softexpires(&rt_b->rt_period_timer);
218 hard = hrtimer_get_expires(&rt_b->rt_period_timer);
219 delta = ktime_to_ns(ktime_sub(hard, soft));
220 __hrtimer_start_range_ns(&rt_b->rt_period_timer, soft, delta,
221 HRTIMER_MODE_ABS_PINNED, 0);
223 raw_spin_unlock(&rt_b->rt_runtime_lock);
226 #ifdef CONFIG_RT_GROUP_SCHED
227 static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
229 hrtimer_cancel(&rt_b->rt_period_timer);
234 * sched_domains_mutex serializes calls to arch_init_sched_domains,
235 * detach_destroy_domains and partition_sched_domains.
237 static DEFINE_MUTEX(sched_domains_mutex);
239 #ifdef CONFIG_CGROUP_SCHED
241 #include <linux/cgroup.h>
245 static LIST_HEAD(task_groups);
247 /* task group related information */
249 struct cgroup_subsys_state css;
251 #ifdef CONFIG_FAIR_GROUP_SCHED
252 /* schedulable entities of this group on each cpu */
253 struct sched_entity **se;
254 /* runqueue "owned" by this group on each cpu */
255 struct cfs_rq **cfs_rq;
256 unsigned long shares;
258 atomic_t load_weight;
261 #ifdef CONFIG_RT_GROUP_SCHED
262 struct sched_rt_entity **rt_se;
263 struct rt_rq **rt_rq;
265 struct rt_bandwidth rt_bandwidth;
269 struct list_head list;
271 struct task_group *parent;
272 struct list_head siblings;
273 struct list_head children;
276 #define root_task_group init_task_group
278 /* task_group_lock serializes the addition/removal of task groups */
279 static DEFINE_SPINLOCK(task_group_lock);
281 #ifdef CONFIG_FAIR_GROUP_SCHED
283 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
286 * A weight of 0 or 1 can cause arithmetics problems.
287 * A weight of a cfs_rq is the sum of weights of which entities
288 * are queued on this cfs_rq, so a weight of a entity should not be
289 * too large, so as the shares value of a task group.
290 * (The default weight is 1024 - so there's no practical
291 * limitation from this.)
294 #define MAX_SHARES (1UL << 18)
296 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
299 /* Default task group.
300 * Every task in system belong to this group at bootup.
302 struct task_group init_task_group;
304 #endif /* CONFIG_CGROUP_SCHED */
306 /* CFS-related fields in a runqueue */
308 struct load_weight load;
309 unsigned long nr_running;
314 struct rb_root tasks_timeline;
315 struct rb_node *rb_leftmost;
317 struct list_head tasks;
318 struct list_head *balance_iterator;
321 * 'curr' points to currently running entity on this cfs_rq.
322 * It is set to NULL otherwise (i.e when none are currently running).
324 struct sched_entity *curr, *next, *last;
326 unsigned int nr_spread_over;
328 #ifdef CONFIG_FAIR_GROUP_SCHED
329 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
332 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
333 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
334 * (like users, containers etc.)
336 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
337 * list is used during load balance.
340 struct list_head leaf_cfs_rq_list;
341 struct task_group *tg; /* group that "owns" this runqueue */
345 * the part of load.weight contributed by tasks
347 unsigned long task_weight;
350 * h_load = weight * f(tg)
352 * Where f(tg) is the recursive weight fraction assigned to
355 unsigned long h_load;
358 * Maintaining per-cpu shares distribution for group scheduling
360 * load_stamp is the last time we updated the load average
361 * load_last is the last time we updated the load average and saw load
362 * load_unacc_exec_time is currently unaccounted execution time
366 u64 load_stamp, load_last, load_unacc_exec_time;
368 unsigned long load_contribution;
373 /* Real-Time classes' related field in a runqueue: */
375 struct rt_prio_array active;
376 unsigned long rt_nr_running;
377 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
379 int curr; /* highest queued rt task prio */
381 int next; /* next highest */
386 unsigned long rt_nr_migratory;
387 unsigned long rt_nr_total;
389 struct plist_head pushable_tasks;
394 /* Nests inside the rq lock: */
395 raw_spinlock_t rt_runtime_lock;
397 #ifdef CONFIG_RT_GROUP_SCHED
398 unsigned long rt_nr_boosted;
401 struct list_head leaf_rt_rq_list;
402 struct task_group *tg;
409 * We add the notion of a root-domain which will be used to define per-domain
410 * variables. Each exclusive cpuset essentially defines an island domain by
411 * fully partitioning the member cpus from any other cpuset. Whenever a new
412 * exclusive cpuset is created, we also create and attach a new root-domain
419 cpumask_var_t online;
422 * The "RT overload" flag: it gets set if a CPU has more than
423 * one runnable RT task.
425 cpumask_var_t rto_mask;
427 struct cpupri cpupri;
431 * By default the system creates a single root-domain with all cpus as
432 * members (mimicking the global state we have today).
434 static struct root_domain def_root_domain;
436 #endif /* CONFIG_SMP */
439 * This is the main, per-CPU runqueue data structure.
441 * Locking rule: those places that want to lock multiple runqueues
442 * (such as the load balancing or the thread migration code), lock
443 * acquire operations must be ordered by ascending &runqueue.
450 * nr_running and cpu_load should be in the same cacheline because
451 * remote CPUs use both these fields when doing load calculation.
453 unsigned long nr_running;
454 #define CPU_LOAD_IDX_MAX 5
455 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
456 unsigned long last_load_update_tick;
459 unsigned char nohz_balance_kick;
461 unsigned int skip_clock_update;
463 /* capture load from *all* tasks on this cpu: */
464 struct load_weight load;
465 unsigned long nr_load_updates;
471 #ifdef CONFIG_FAIR_GROUP_SCHED
472 /* list of leaf cfs_rq on this cpu: */
473 struct list_head leaf_cfs_rq_list;
475 #ifdef CONFIG_RT_GROUP_SCHED
476 struct list_head leaf_rt_rq_list;
480 * This is part of a global counter where only the total sum
481 * over all CPUs matters. A task can increase this counter on
482 * one CPU and if it got migrated afterwards it may decrease
483 * it on another CPU. Always updated under the runqueue lock:
485 unsigned long nr_uninterruptible;
487 struct task_struct *curr, *idle, *stop;
488 unsigned long next_balance;
489 struct mm_struct *prev_mm;
497 struct root_domain *rd;
498 struct sched_domain *sd;
500 unsigned long cpu_power;
502 unsigned char idle_at_tick;
503 /* For active balancing */
507 struct cpu_stop_work active_balance_work;
508 /* cpu of this runqueue: */
512 unsigned long avg_load_per_task;
520 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
524 /* calc_load related fields */
525 unsigned long calc_load_update;
526 long calc_load_active;
528 #ifdef CONFIG_SCHED_HRTICK
530 int hrtick_csd_pending;
531 struct call_single_data hrtick_csd;
533 struct hrtimer hrtick_timer;
536 #ifdef CONFIG_SCHEDSTATS
538 struct sched_info rq_sched_info;
539 unsigned long long rq_cpu_time;
540 /* could above be rq->cfs_rq.exec_clock + rq->rt_rq.rt_runtime ? */
542 /* sys_sched_yield() stats */
543 unsigned int yld_count;
545 /* schedule() stats */
546 unsigned int sched_switch;
547 unsigned int sched_count;
548 unsigned int sched_goidle;
550 /* try_to_wake_up() stats */
551 unsigned int ttwu_count;
552 unsigned int ttwu_local;
555 unsigned int bkl_count;
559 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
562 static void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags);
564 static inline int cpu_of(struct rq *rq)
573 #define rcu_dereference_check_sched_domain(p) \
574 rcu_dereference_check((p), \
575 rcu_read_lock_sched_held() || \
576 lockdep_is_held(&sched_domains_mutex))
579 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
580 * See detach_destroy_domains: synchronize_sched for details.
582 * The domain tree of any CPU may only be accessed from within
583 * preempt-disabled sections.
585 #define for_each_domain(cpu, __sd) \
586 for (__sd = rcu_dereference_check_sched_domain(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
588 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
589 #define this_rq() (&__get_cpu_var(runqueues))
590 #define task_rq(p) cpu_rq(task_cpu(p))
591 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
592 #define raw_rq() (&__raw_get_cpu_var(runqueues))
594 #ifdef CONFIG_CGROUP_SCHED
597 * Return the group to which this tasks belongs.
599 * We use task_subsys_state_check() and extend the RCU verification
600 * with lockdep_is_held(&task_rq(p)->lock) because cpu_cgroup_attach()
601 * holds that lock for each task it moves into the cgroup. Therefore
602 * by holding that lock, we pin the task to the current cgroup.
604 static inline struct task_group *task_group(struct task_struct *p)
606 struct cgroup_subsys_state *css;
608 css = task_subsys_state_check(p, cpu_cgroup_subsys_id,
609 lockdep_is_held(&task_rq(p)->lock));
610 return container_of(css, struct task_group, css);
613 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
614 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
616 #ifdef CONFIG_FAIR_GROUP_SCHED
617 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
618 p->se.parent = task_group(p)->se[cpu];
621 #ifdef CONFIG_RT_GROUP_SCHED
622 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
623 p->rt.parent = task_group(p)->rt_se[cpu];
627 #else /* CONFIG_CGROUP_SCHED */
629 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
630 static inline struct task_group *task_group(struct task_struct *p)
635 #endif /* CONFIG_CGROUP_SCHED */
637 static u64 irq_time_cpu(int cpu);
638 static void sched_irq_time_avg_update(struct rq *rq, u64 irq_time);
640 inline void update_rq_clock(struct rq *rq)
642 if (!rq->skip_clock_update) {
643 int cpu = cpu_of(rq);
646 rq->clock = sched_clock_cpu(cpu);
647 irq_time = irq_time_cpu(cpu);
648 if (rq->clock - irq_time > rq->clock_task)
649 rq->clock_task = rq->clock - irq_time;
651 sched_irq_time_avg_update(rq, irq_time);
656 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
658 #ifdef CONFIG_SCHED_DEBUG
659 # define const_debug __read_mostly
661 # define const_debug static const
666 * @cpu: the processor in question.
668 * Returns true if the current cpu runqueue is locked.
669 * This interface allows printk to be called with the runqueue lock
670 * held and know whether or not it is OK to wake up the klogd.
672 int runqueue_is_locked(int cpu)
674 return raw_spin_is_locked(&cpu_rq(cpu)->lock);
678 * Debugging: various feature bits
681 #define SCHED_FEAT(name, enabled) \
682 __SCHED_FEAT_##name ,
685 #include "sched_features.h"
690 #define SCHED_FEAT(name, enabled) \
691 (1UL << __SCHED_FEAT_##name) * enabled |
693 const_debug unsigned int sysctl_sched_features =
694 #include "sched_features.h"
699 #ifdef CONFIG_SCHED_DEBUG
700 #define SCHED_FEAT(name, enabled) \
703 static __read_mostly char *sched_feat_names[] = {
704 #include "sched_features.h"
710 static int sched_feat_show(struct seq_file *m, void *v)
714 for (i = 0; sched_feat_names[i]; i++) {
715 if (!(sysctl_sched_features & (1UL << i)))
717 seq_printf(m, "%s ", sched_feat_names[i]);
725 sched_feat_write(struct file *filp, const char __user *ubuf,
726 size_t cnt, loff_t *ppos)
736 if (copy_from_user(&buf, ubuf, cnt))
742 if (strncmp(buf, "NO_", 3) == 0) {
747 for (i = 0; sched_feat_names[i]; i++) {
748 if (strcmp(cmp, sched_feat_names[i]) == 0) {
750 sysctl_sched_features &= ~(1UL << i);
752 sysctl_sched_features |= (1UL << i);
757 if (!sched_feat_names[i])
765 static int sched_feat_open(struct inode *inode, struct file *filp)
767 return single_open(filp, sched_feat_show, NULL);
770 static const struct file_operations sched_feat_fops = {
771 .open = sched_feat_open,
772 .write = sched_feat_write,
775 .release = single_release,
778 static __init int sched_init_debug(void)
780 debugfs_create_file("sched_features", 0644, NULL, NULL,
785 late_initcall(sched_init_debug);
789 #define sched_feat(x) (sysctl_sched_features & (1UL << __SCHED_FEAT_##x))
792 * Number of tasks to iterate in a single balance run.
793 * Limited because this is done with IRQs disabled.
795 const_debug unsigned int sysctl_sched_nr_migrate = 32;
798 * period over which we average the RT time consumption, measured
803 const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
806 * period over which we measure -rt task cpu usage in us.
809 unsigned int sysctl_sched_rt_period = 1000000;
811 static __read_mostly int scheduler_running;
814 * part of the period that we allow rt tasks to run in us.
817 int sysctl_sched_rt_runtime = 950000;
819 static inline u64 global_rt_period(void)
821 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
824 static inline u64 global_rt_runtime(void)
826 if (sysctl_sched_rt_runtime < 0)
829 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
832 #ifndef prepare_arch_switch
833 # define prepare_arch_switch(next) do { } while (0)
835 #ifndef finish_arch_switch
836 # define finish_arch_switch(prev) do { } while (0)
839 static inline int task_current(struct rq *rq, struct task_struct *p)
841 return rq->curr == p;
844 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
845 static inline int task_running(struct rq *rq, struct task_struct *p)
847 return task_current(rq, p);
850 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
854 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
856 #ifdef CONFIG_DEBUG_SPINLOCK
857 /* this is a valid case when another task releases the spinlock */
858 rq->lock.owner = current;
861 * If we are tracking spinlock dependencies then we have to
862 * fix up the runqueue lock - which gets 'carried over' from
865 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
867 raw_spin_unlock_irq(&rq->lock);
870 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
871 static inline int task_running(struct rq *rq, struct task_struct *p)
876 return task_current(rq, p);
880 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
884 * We can optimise this out completely for !SMP, because the
885 * SMP rebalancing from interrupt is the only thing that cares
890 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
891 raw_spin_unlock_irq(&rq->lock);
893 raw_spin_unlock(&rq->lock);
897 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
901 * After ->oncpu is cleared, the task can be moved to a different CPU.
902 * We must ensure this doesn't happen until the switch is completely
908 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
912 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
915 * Check whether the task is waking, we use this to synchronize ->cpus_allowed
918 static inline int task_is_waking(struct task_struct *p)
920 return unlikely(p->state == TASK_WAKING);
924 * __task_rq_lock - lock the runqueue a given task resides on.
925 * Must be called interrupts disabled.
927 static inline struct rq *__task_rq_lock(struct task_struct *p)
934 raw_spin_lock(&rq->lock);
935 if (likely(rq == task_rq(p)))
937 raw_spin_unlock(&rq->lock);
942 * task_rq_lock - lock the runqueue a given task resides on and disable
943 * interrupts. Note the ordering: we can safely lookup the task_rq without
944 * explicitly disabling preemption.
946 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
952 local_irq_save(*flags);
954 raw_spin_lock(&rq->lock);
955 if (likely(rq == task_rq(p)))
957 raw_spin_unlock_irqrestore(&rq->lock, *flags);
961 static void __task_rq_unlock(struct rq *rq)
964 raw_spin_unlock(&rq->lock);
967 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
970 raw_spin_unlock_irqrestore(&rq->lock, *flags);
974 * this_rq_lock - lock this runqueue and disable interrupts.
976 static struct rq *this_rq_lock(void)
983 raw_spin_lock(&rq->lock);
988 #ifdef CONFIG_SCHED_HRTICK
990 * Use HR-timers to deliver accurate preemption points.
992 * Its all a bit involved since we cannot program an hrt while holding the
993 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
996 * When we get rescheduled we reprogram the hrtick_timer outside of the
1002 * - enabled by features
1003 * - hrtimer is actually high res
1005 static inline int hrtick_enabled(struct rq *rq)
1007 if (!sched_feat(HRTICK))
1009 if (!cpu_active(cpu_of(rq)))
1011 return hrtimer_is_hres_active(&rq->hrtick_timer);
1014 static void hrtick_clear(struct rq *rq)
1016 if (hrtimer_active(&rq->hrtick_timer))
1017 hrtimer_cancel(&rq->hrtick_timer);
1021 * High-resolution timer tick.
1022 * Runs from hardirq context with interrupts disabled.
1024 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1026 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1028 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1030 raw_spin_lock(&rq->lock);
1031 update_rq_clock(rq);
1032 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1033 raw_spin_unlock(&rq->lock);
1035 return HRTIMER_NORESTART;
1040 * called from hardirq (IPI) context
1042 static void __hrtick_start(void *arg)
1044 struct rq *rq = arg;
1046 raw_spin_lock(&rq->lock);
1047 hrtimer_restart(&rq->hrtick_timer);
1048 rq->hrtick_csd_pending = 0;
1049 raw_spin_unlock(&rq->lock);
1053 * Called to set the hrtick timer state.
1055 * called with rq->lock held and irqs disabled
1057 static void hrtick_start(struct rq *rq, u64 delay)
1059 struct hrtimer *timer = &rq->hrtick_timer;
1060 ktime_t time = ktime_add_ns(timer->base->get_time(), delay);
1062 hrtimer_set_expires(timer, time);
1064 if (rq == this_rq()) {
1065 hrtimer_restart(timer);
1066 } else if (!rq->hrtick_csd_pending) {
1067 __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0);
1068 rq->hrtick_csd_pending = 1;
1073 hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu)
1075 int cpu = (int)(long)hcpu;
1078 case CPU_UP_CANCELED:
1079 case CPU_UP_CANCELED_FROZEN:
1080 case CPU_DOWN_PREPARE:
1081 case CPU_DOWN_PREPARE_FROZEN:
1083 case CPU_DEAD_FROZEN:
1084 hrtick_clear(cpu_rq(cpu));
1091 static __init void init_hrtick(void)
1093 hotcpu_notifier(hotplug_hrtick, 0);
1097 * Called to set the hrtick timer state.
1099 * called with rq->lock held and irqs disabled
1101 static void hrtick_start(struct rq *rq, u64 delay)
1103 __hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0,
1104 HRTIMER_MODE_REL_PINNED, 0);
1107 static inline void init_hrtick(void)
1110 #endif /* CONFIG_SMP */
1112 static void init_rq_hrtick(struct rq *rq)
1115 rq->hrtick_csd_pending = 0;
1117 rq->hrtick_csd.flags = 0;
1118 rq->hrtick_csd.func = __hrtick_start;
1119 rq->hrtick_csd.info = rq;
1122 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1123 rq->hrtick_timer.function = hrtick;
1125 #else /* CONFIG_SCHED_HRTICK */
1126 static inline void hrtick_clear(struct rq *rq)
1130 static inline void init_rq_hrtick(struct rq *rq)
1134 static inline void init_hrtick(void)
1137 #endif /* CONFIG_SCHED_HRTICK */
1140 * resched_task - mark a task 'to be rescheduled now'.
1142 * On UP this means the setting of the need_resched flag, on SMP it
1143 * might also involve a cross-CPU call to trigger the scheduler on
1148 #ifndef tsk_is_polling
1149 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1152 static void resched_task(struct task_struct *p)
1156 assert_raw_spin_locked(&task_rq(p)->lock);
1158 if (test_tsk_need_resched(p))
1161 set_tsk_need_resched(p);
1164 if (cpu == smp_processor_id())
1167 /* NEED_RESCHED must be visible before we test polling */
1169 if (!tsk_is_polling(p))
1170 smp_send_reschedule(cpu);
1173 static void resched_cpu(int cpu)
1175 struct rq *rq = cpu_rq(cpu);
1176 unsigned long flags;
1178 if (!raw_spin_trylock_irqsave(&rq->lock, flags))
1180 resched_task(cpu_curr(cpu));
1181 raw_spin_unlock_irqrestore(&rq->lock, flags);
1186 * In the semi idle case, use the nearest busy cpu for migrating timers
1187 * from an idle cpu. This is good for power-savings.
1189 * We don't do similar optimization for completely idle system, as
1190 * selecting an idle cpu will add more delays to the timers than intended
1191 * (as that cpu's timer base may not be uptodate wrt jiffies etc).
1193 int get_nohz_timer_target(void)
1195 int cpu = smp_processor_id();
1197 struct sched_domain *sd;
1199 for_each_domain(cpu, sd) {
1200 for_each_cpu(i, sched_domain_span(sd))
1207 * When add_timer_on() enqueues a timer into the timer wheel of an
1208 * idle CPU then this timer might expire before the next timer event
1209 * which is scheduled to wake up that CPU. In case of a completely
1210 * idle system the next event might even be infinite time into the
1211 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1212 * leaves the inner idle loop so the newly added timer is taken into
1213 * account when the CPU goes back to idle and evaluates the timer
1214 * wheel for the next timer event.
1216 void wake_up_idle_cpu(int cpu)
1218 struct rq *rq = cpu_rq(cpu);
1220 if (cpu == smp_processor_id())
1224 * This is safe, as this function is called with the timer
1225 * wheel base lock of (cpu) held. When the CPU is on the way
1226 * to idle and has not yet set rq->curr to idle then it will
1227 * be serialized on the timer wheel base lock and take the new
1228 * timer into account automatically.
1230 if (rq->curr != rq->idle)
1234 * We can set TIF_RESCHED on the idle task of the other CPU
1235 * lockless. The worst case is that the other CPU runs the
1236 * idle task through an additional NOOP schedule()
1238 set_tsk_need_resched(rq->idle);
1240 /* NEED_RESCHED must be visible before we test polling */
1242 if (!tsk_is_polling(rq->idle))
1243 smp_send_reschedule(cpu);
1246 #endif /* CONFIG_NO_HZ */
1248 static u64 sched_avg_period(void)
1250 return (u64)sysctl_sched_time_avg * NSEC_PER_MSEC / 2;
1253 static void sched_avg_update(struct rq *rq)
1255 s64 period = sched_avg_period();
1257 while ((s64)(rq->clock - rq->age_stamp) > period) {
1259 * Inline assembly required to prevent the compiler
1260 * optimising this loop into a divmod call.
1261 * See __iter_div_u64_rem() for another example of this.
1263 asm("" : "+rm" (rq->age_stamp));
1264 rq->age_stamp += period;
1269 static void sched_rt_avg_update(struct rq *rq, u64 rt_delta)
1271 rq->rt_avg += rt_delta;
1272 sched_avg_update(rq);
1275 #else /* !CONFIG_SMP */
1276 static void resched_task(struct task_struct *p)
1278 assert_raw_spin_locked(&task_rq(p)->lock);
1279 set_tsk_need_resched(p);
1282 static void sched_rt_avg_update(struct rq *rq, u64 rt_delta)
1286 static void sched_avg_update(struct rq *rq)
1289 #endif /* CONFIG_SMP */
1291 #if BITS_PER_LONG == 32
1292 # define WMULT_CONST (~0UL)
1294 # define WMULT_CONST (1UL << 32)
1297 #define WMULT_SHIFT 32
1300 * Shift right and round:
1302 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1305 * delta *= weight / lw
1307 static unsigned long
1308 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1309 struct load_weight *lw)
1313 if (!lw->inv_weight) {
1314 if (BITS_PER_LONG > 32 && unlikely(lw->weight >= WMULT_CONST))
1317 lw->inv_weight = 1 + (WMULT_CONST-lw->weight/2)
1321 tmp = (u64)delta_exec * weight;
1323 * Check whether we'd overflow the 64-bit multiplication:
1325 if (unlikely(tmp > WMULT_CONST))
1326 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1329 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1331 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1334 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1340 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1346 static inline void update_load_set(struct load_weight *lw, unsigned long w)
1353 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1354 * of tasks with abnormal "nice" values across CPUs the contribution that
1355 * each task makes to its run queue's load is weighted according to its
1356 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1357 * scaled version of the new time slice allocation that they receive on time
1361 #define WEIGHT_IDLEPRIO 3
1362 #define WMULT_IDLEPRIO 1431655765
1365 * Nice levels are multiplicative, with a gentle 10% change for every
1366 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1367 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1368 * that remained on nice 0.
1370 * The "10% effect" is relative and cumulative: from _any_ nice level,
1371 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1372 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1373 * If a task goes up by ~10% and another task goes down by ~10% then
1374 * the relative distance between them is ~25%.)
1376 static const int prio_to_weight[40] = {
1377 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1378 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1379 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1380 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1381 /* 0 */ 1024, 820, 655, 526, 423,
1382 /* 5 */ 335, 272, 215, 172, 137,
1383 /* 10 */ 110, 87, 70, 56, 45,
1384 /* 15 */ 36, 29, 23, 18, 15,
1388 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1390 * In cases where the weight does not change often, we can use the
1391 * precalculated inverse to speed up arithmetics by turning divisions
1392 * into multiplications:
1394 static const u32 prio_to_wmult[40] = {
1395 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1396 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1397 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1398 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1399 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1400 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1401 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1402 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1405 /* Time spent by the tasks of the cpu accounting group executing in ... */
1406 enum cpuacct_stat_index {
1407 CPUACCT_STAT_USER, /* ... user mode */
1408 CPUACCT_STAT_SYSTEM, /* ... kernel mode */
1410 CPUACCT_STAT_NSTATS,
1413 #ifdef CONFIG_CGROUP_CPUACCT
1414 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1415 static void cpuacct_update_stats(struct task_struct *tsk,
1416 enum cpuacct_stat_index idx, cputime_t val);
1418 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1419 static inline void cpuacct_update_stats(struct task_struct *tsk,
1420 enum cpuacct_stat_index idx, cputime_t val) {}
1423 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1425 update_load_add(&rq->load, load);
1428 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1430 update_load_sub(&rq->load, load);
1433 #if (defined(CONFIG_SMP) && defined(CONFIG_FAIR_GROUP_SCHED)) || defined(CONFIG_RT_GROUP_SCHED)
1434 typedef int (*tg_visitor)(struct task_group *, void *);
1437 * Iterate the full tree, calling @down when first entering a node and @up when
1438 * leaving it for the final time.
1440 static int walk_tg_tree(tg_visitor down, tg_visitor up, void *data)
1442 struct task_group *parent, *child;
1446 parent = &root_task_group;
1448 ret = (*down)(parent, data);
1451 list_for_each_entry_rcu(child, &parent->children, siblings) {
1458 ret = (*up)(parent, data);
1463 parent = parent->parent;
1472 static int tg_nop(struct task_group *tg, void *data)
1479 /* Used instead of source_load when we know the type == 0 */
1480 static unsigned long weighted_cpuload(const int cpu)
1482 return cpu_rq(cpu)->load.weight;
1486 * Return a low guess at the load of a migration-source cpu weighted
1487 * according to the scheduling class and "nice" value.
1489 * We want to under-estimate the load of migration sources, to
1490 * balance conservatively.
1492 static unsigned long source_load(int cpu, int type)
1494 struct rq *rq = cpu_rq(cpu);
1495 unsigned long total = weighted_cpuload(cpu);
1497 if (type == 0 || !sched_feat(LB_BIAS))
1500 return min(rq->cpu_load[type-1], total);
1504 * Return a high guess at the load of a migration-target cpu weighted
1505 * according to the scheduling class and "nice" value.
1507 static unsigned long target_load(int cpu, int type)
1509 struct rq *rq = cpu_rq(cpu);
1510 unsigned long total = weighted_cpuload(cpu);
1512 if (type == 0 || !sched_feat(LB_BIAS))
1515 return max(rq->cpu_load[type-1], total);
1518 static unsigned long power_of(int cpu)
1520 return cpu_rq(cpu)->cpu_power;
1523 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1525 static unsigned long cpu_avg_load_per_task(int cpu)
1527 struct rq *rq = cpu_rq(cpu);
1528 unsigned long nr_running = ACCESS_ONCE(rq->nr_running);
1531 rq->avg_load_per_task = rq->load.weight / nr_running;
1533 rq->avg_load_per_task = 0;
1535 return rq->avg_load_per_task;
1538 #ifdef CONFIG_FAIR_GROUP_SCHED
1541 * Compute the cpu's hierarchical load factor for each task group.
1542 * This needs to be done in a top-down fashion because the load of a child
1543 * group is a fraction of its parents load.
1545 static int tg_load_down(struct task_group *tg, void *data)
1548 long cpu = (long)data;
1551 load = cpu_rq(cpu)->load.weight;
1553 load = tg->parent->cfs_rq[cpu]->h_load;
1554 load *= tg->se[cpu]->load.weight;
1555 load /= tg->parent->cfs_rq[cpu]->load.weight + 1;
1558 tg->cfs_rq[cpu]->h_load = load;
1563 static void update_h_load(long cpu)
1565 walk_tg_tree(tg_load_down, tg_nop, (void *)cpu);
1570 #ifdef CONFIG_PREEMPT
1572 static void double_rq_lock(struct rq *rq1, struct rq *rq2);
1575 * fair double_lock_balance: Safely acquires both rq->locks in a fair
1576 * way at the expense of forcing extra atomic operations in all
1577 * invocations. This assures that the double_lock is acquired using the
1578 * same underlying policy as the spinlock_t on this architecture, which
1579 * reduces latency compared to the unfair variant below. However, it
1580 * also adds more overhead and therefore may reduce throughput.
1582 static inline int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1583 __releases(this_rq->lock)
1584 __acquires(busiest->lock)
1585 __acquires(this_rq->lock)
1587 raw_spin_unlock(&this_rq->lock);
1588 double_rq_lock(this_rq, busiest);
1595 * Unfair double_lock_balance: Optimizes throughput at the expense of
1596 * latency by eliminating extra atomic operations when the locks are
1597 * already in proper order on entry. This favors lower cpu-ids and will
1598 * grant the double lock to lower cpus over higher ids under contention,
1599 * regardless of entry order into the function.
1601 static int _double_lock_balance(struct rq *this_rq, struct rq *busiest)
1602 __releases(this_rq->lock)
1603 __acquires(busiest->lock)
1604 __acquires(this_rq->lock)
1608 if (unlikely(!raw_spin_trylock(&busiest->lock))) {
1609 if (busiest < this_rq) {
1610 raw_spin_unlock(&this_rq->lock);
1611 raw_spin_lock(&busiest->lock);
1612 raw_spin_lock_nested(&this_rq->lock,
1613 SINGLE_DEPTH_NESTING);
1616 raw_spin_lock_nested(&busiest->lock,
1617 SINGLE_DEPTH_NESTING);
1622 #endif /* CONFIG_PREEMPT */
1625 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1627 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
1629 if (unlikely(!irqs_disabled())) {
1630 /* printk() doesn't work good under rq->lock */
1631 raw_spin_unlock(&this_rq->lock);
1635 return _double_lock_balance(this_rq, busiest);
1638 static inline void double_unlock_balance(struct rq *this_rq, struct rq *busiest)
1639 __releases(busiest->lock)
1641 raw_spin_unlock(&busiest->lock);
1642 lock_set_subclass(&this_rq->lock.dep_map, 0, _RET_IP_);
1646 * double_rq_lock - safely lock two runqueues
1648 * Note this does not disable interrupts like task_rq_lock,
1649 * you need to do so manually before calling.
1651 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
1652 __acquires(rq1->lock)
1653 __acquires(rq2->lock)
1655 BUG_ON(!irqs_disabled());
1657 raw_spin_lock(&rq1->lock);
1658 __acquire(rq2->lock); /* Fake it out ;) */
1661 raw_spin_lock(&rq1->lock);
1662 raw_spin_lock_nested(&rq2->lock, SINGLE_DEPTH_NESTING);
1664 raw_spin_lock(&rq2->lock);
1665 raw_spin_lock_nested(&rq1->lock, SINGLE_DEPTH_NESTING);
1671 * double_rq_unlock - safely unlock two runqueues
1673 * Note this does not restore interrupts like task_rq_unlock,
1674 * you need to do so manually after calling.
1676 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
1677 __releases(rq1->lock)
1678 __releases(rq2->lock)
1680 raw_spin_unlock(&rq1->lock);
1682 raw_spin_unlock(&rq2->lock);
1684 __release(rq2->lock);
1689 static void calc_load_account_idle(struct rq *this_rq);
1690 static void update_sysctl(void);
1691 static int get_update_sysctl_factor(void);
1692 static void update_cpu_load(struct rq *this_rq);
1694 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1696 set_task_rq(p, cpu);
1699 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1700 * successfuly executed on another CPU. We must ensure that updates of
1701 * per-task data have been completed by this moment.
1704 task_thread_info(p)->cpu = cpu;
1708 static const struct sched_class rt_sched_class;
1710 #define sched_class_highest (&stop_sched_class)
1711 #define for_each_class(class) \
1712 for (class = sched_class_highest; class; class = class->next)
1714 #include "sched_stats.h"
1716 static void inc_nr_running(struct rq *rq)
1721 static void dec_nr_running(struct rq *rq)
1726 static void set_load_weight(struct task_struct *p)
1729 * SCHED_IDLE tasks get minimal weight:
1731 if (p->policy == SCHED_IDLE) {
1732 p->se.load.weight = WEIGHT_IDLEPRIO;
1733 p->se.load.inv_weight = WMULT_IDLEPRIO;
1737 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1738 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1741 static void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
1743 update_rq_clock(rq);
1744 sched_info_queued(p);
1745 p->sched_class->enqueue_task(rq, p, flags);
1749 static void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
1751 update_rq_clock(rq);
1752 sched_info_dequeued(p);
1753 p->sched_class->dequeue_task(rq, p, flags);
1758 * activate_task - move a task to the runqueue.
1760 static void activate_task(struct rq *rq, struct task_struct *p, int flags)
1762 if (task_contributes_to_load(p))
1763 rq->nr_uninterruptible--;
1765 enqueue_task(rq, p, flags);
1770 * deactivate_task - remove a task from the runqueue.
1772 static void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
1774 if (task_contributes_to_load(p))
1775 rq->nr_uninterruptible++;
1777 dequeue_task(rq, p, flags);
1781 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
1784 * There are no locks covering percpu hardirq/softirq time.
1785 * They are only modified in account_system_vtime, on corresponding CPU
1786 * with interrupts disabled. So, writes are safe.
1787 * They are read and saved off onto struct rq in update_rq_clock().
1788 * This may result in other CPU reading this CPU's irq time and can
1789 * race with irq/account_system_vtime on this CPU. We would either get old
1790 * or new value (or semi updated value on 32 bit) with a side effect of
1791 * accounting a slice of irq time to wrong task when irq is in progress
1792 * while we read rq->clock. That is a worthy compromise in place of having
1793 * locks on each irq in account_system_time.
1795 static DEFINE_PER_CPU(u64, cpu_hardirq_time);
1796 static DEFINE_PER_CPU(u64, cpu_softirq_time);
1798 static DEFINE_PER_CPU(u64, irq_start_time);
1799 static int sched_clock_irqtime;
1801 void enable_sched_clock_irqtime(void)
1803 sched_clock_irqtime = 1;
1806 void disable_sched_clock_irqtime(void)
1808 sched_clock_irqtime = 0;
1811 static u64 irq_time_cpu(int cpu)
1813 if (!sched_clock_irqtime)
1816 return per_cpu(cpu_softirq_time, cpu) + per_cpu(cpu_hardirq_time, cpu);
1819 void account_system_vtime(struct task_struct *curr)
1821 unsigned long flags;
1825 if (!sched_clock_irqtime)
1828 local_irq_save(flags);
1830 cpu = smp_processor_id();
1831 now = sched_clock_cpu(cpu);
1832 delta = now - per_cpu(irq_start_time, cpu);
1833 per_cpu(irq_start_time, cpu) = now;
1835 * We do not account for softirq time from ksoftirqd here.
1836 * We want to continue accounting softirq time to ksoftirqd thread
1837 * in that case, so as not to confuse scheduler with a special task
1838 * that do not consume any time, but still wants to run.
1840 if (hardirq_count())
1841 per_cpu(cpu_hardirq_time, cpu) += delta;
1842 else if (in_serving_softirq() && !(curr->flags & PF_KSOFTIRQD))
1843 per_cpu(cpu_softirq_time, cpu) += delta;
1845 local_irq_restore(flags);
1847 EXPORT_SYMBOL_GPL(account_system_vtime);
1849 static void sched_irq_time_avg_update(struct rq *rq, u64 curr_irq_time)
1851 if (sched_clock_irqtime && sched_feat(NONIRQ_POWER)) {
1852 u64 delta_irq = curr_irq_time - rq->prev_irq_time;
1853 rq->prev_irq_time = curr_irq_time;
1854 sched_rt_avg_update(rq, delta_irq);
1860 static u64 irq_time_cpu(int cpu)
1865 static void sched_irq_time_avg_update(struct rq *rq, u64 curr_irq_time) { }
1869 #include "sched_idletask.c"
1870 #include "sched_fair.c"
1871 #include "sched_rt.c"
1872 #include "sched_stoptask.c"
1873 #ifdef CONFIG_SCHED_DEBUG
1874 # include "sched_debug.c"
1877 void sched_set_stop_task(int cpu, struct task_struct *stop)
1879 struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
1880 struct task_struct *old_stop = cpu_rq(cpu)->stop;
1884 * Make it appear like a SCHED_FIFO task, its something
1885 * userspace knows about and won't get confused about.
1887 * Also, it will make PI more or less work without too
1888 * much confusion -- but then, stop work should not
1889 * rely on PI working anyway.
1891 sched_setscheduler_nocheck(stop, SCHED_FIFO, ¶m);
1893 stop->sched_class = &stop_sched_class;
1896 cpu_rq(cpu)->stop = stop;
1900 * Reset it back to a normal scheduling class so that
1901 * it can die in pieces.
1903 old_stop->sched_class = &rt_sched_class;
1908 * __normal_prio - return the priority that is based on the static prio
1910 static inline int __normal_prio(struct task_struct *p)
1912 return p->static_prio;
1916 * Calculate the expected normal priority: i.e. priority
1917 * without taking RT-inheritance into account. Might be
1918 * boosted by interactivity modifiers. Changes upon fork,
1919 * setprio syscalls, and whenever the interactivity
1920 * estimator recalculates.
1922 static inline int normal_prio(struct task_struct *p)
1926 if (task_has_rt_policy(p))
1927 prio = MAX_RT_PRIO-1 - p->rt_priority;
1929 prio = __normal_prio(p);
1934 * Calculate the current priority, i.e. the priority
1935 * taken into account by the scheduler. This value might
1936 * be boosted by RT tasks, or might be boosted by
1937 * interactivity modifiers. Will be RT if the task got
1938 * RT-boosted. If not then it returns p->normal_prio.
1940 static int effective_prio(struct task_struct *p)
1942 p->normal_prio = normal_prio(p);
1944 * If we are RT tasks or we were boosted to RT priority,
1945 * keep the priority unchanged. Otherwise, update priority
1946 * to the normal priority:
1948 if (!rt_prio(p->prio))
1949 return p->normal_prio;
1954 * task_curr - is this task currently executing on a CPU?
1955 * @p: the task in question.
1957 inline int task_curr(const struct task_struct *p)
1959 return cpu_curr(task_cpu(p)) == p;
1962 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1963 const struct sched_class *prev_class,
1964 int oldprio, int running)
1966 if (prev_class != p->sched_class) {
1967 if (prev_class->switched_from)
1968 prev_class->switched_from(rq, p, running);
1969 p->sched_class->switched_to(rq, p, running);
1971 p->sched_class->prio_changed(rq, p, oldprio, running);
1974 static void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
1976 const struct sched_class *class;
1978 if (p->sched_class == rq->curr->sched_class) {
1979 rq->curr->sched_class->check_preempt_curr(rq, p, flags);
1981 for_each_class(class) {
1982 if (class == rq->curr->sched_class)
1984 if (class == p->sched_class) {
1985 resched_task(rq->curr);
1992 * A queue event has occurred, and we're going to schedule. In
1993 * this case, we can save a useless back to back clock update.
1995 if (test_tsk_need_resched(rq->curr))
1996 rq->skip_clock_update = 1;
2001 * Is this task likely cache-hot:
2004 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
2008 if (p->sched_class != &fair_sched_class)
2011 if (unlikely(p->policy == SCHED_IDLE))
2015 * Buddy candidates are cache hot:
2017 if (sched_feat(CACHE_HOT_BUDDY) && this_rq()->nr_running &&
2018 (&p->se == cfs_rq_of(&p->se)->next ||
2019 &p->se == cfs_rq_of(&p->se)->last))
2022 if (sysctl_sched_migration_cost == -1)
2024 if (sysctl_sched_migration_cost == 0)
2027 delta = now - p->se.exec_start;
2029 return delta < (s64)sysctl_sched_migration_cost;
2032 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
2034 #ifdef CONFIG_SCHED_DEBUG
2036 * We should never call set_task_cpu() on a blocked task,
2037 * ttwu() will sort out the placement.
2039 WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
2040 !(task_thread_info(p)->preempt_count & PREEMPT_ACTIVE));
2043 trace_sched_migrate_task(p, new_cpu);
2045 if (task_cpu(p) != new_cpu) {
2046 p->se.nr_migrations++;
2047 perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, 1, NULL, 0);
2050 __set_task_cpu(p, new_cpu);
2053 struct migration_arg {
2054 struct task_struct *task;
2058 static int migration_cpu_stop(void *data);
2061 * The task's runqueue lock must be held.
2062 * Returns true if you have to wait for migration thread.
2064 static bool migrate_task(struct task_struct *p, int dest_cpu)
2066 struct rq *rq = task_rq(p);
2069 * If the task is not on a runqueue (and not running), then
2070 * the next wake-up will properly place the task.
2072 return p->se.on_rq || task_running(rq, p);
2076 * wait_task_inactive - wait for a thread to unschedule.
2078 * If @match_state is nonzero, it's the @p->state value just checked and
2079 * not expected to change. If it changes, i.e. @p might have woken up,
2080 * then return zero. When we succeed in waiting for @p to be off its CPU,
2081 * we return a positive number (its total switch count). If a second call
2082 * a short while later returns the same number, the caller can be sure that
2083 * @p has remained unscheduled the whole time.
2085 * The caller must ensure that the task *will* unschedule sometime soon,
2086 * else this function might spin for a *long* time. This function can't
2087 * be called with interrupts off, or it may introduce deadlock with
2088 * smp_call_function() if an IPI is sent by the same process we are
2089 * waiting to become inactive.
2091 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
2093 unsigned long flags;
2100 * We do the initial early heuristics without holding
2101 * any task-queue locks at all. We'll only try to get
2102 * the runqueue lock when things look like they will
2108 * If the task is actively running on another CPU
2109 * still, just relax and busy-wait without holding
2112 * NOTE! Since we don't hold any locks, it's not
2113 * even sure that "rq" stays as the right runqueue!
2114 * But we don't care, since "task_running()" will
2115 * return false if the runqueue has changed and p
2116 * is actually now running somewhere else!
2118 while (task_running(rq, p)) {
2119 if (match_state && unlikely(p->state != match_state))
2125 * Ok, time to look more closely! We need the rq
2126 * lock now, to be *sure*. If we're wrong, we'll
2127 * just go back and repeat.
2129 rq = task_rq_lock(p, &flags);
2130 trace_sched_wait_task(p);
2131 running = task_running(rq, p);
2132 on_rq = p->se.on_rq;
2134 if (!match_state || p->state == match_state)
2135 ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
2136 task_rq_unlock(rq, &flags);
2139 * If it changed from the expected state, bail out now.
2141 if (unlikely(!ncsw))
2145 * Was it really running after all now that we
2146 * checked with the proper locks actually held?
2148 * Oops. Go back and try again..
2150 if (unlikely(running)) {
2156 * It's not enough that it's not actively running,
2157 * it must be off the runqueue _entirely_, and not
2160 * So if it was still runnable (but just not actively
2161 * running right now), it's preempted, and we should
2162 * yield - it could be a while.
2164 if (unlikely(on_rq)) {
2165 schedule_timeout_uninterruptible(1);
2170 * Ahh, all good. It wasn't running, and it wasn't
2171 * runnable, which means that it will never become
2172 * running in the future either. We're all done!
2181 * kick_process - kick a running thread to enter/exit the kernel
2182 * @p: the to-be-kicked thread
2184 * Cause a process which is running on another CPU to enter
2185 * kernel-mode, without any delay. (to get signals handled.)
2187 * NOTE: this function doesnt have to take the runqueue lock,
2188 * because all it wants to ensure is that the remote task enters
2189 * the kernel. If the IPI races and the task has been migrated
2190 * to another CPU then no harm is done and the purpose has been
2193 void kick_process(struct task_struct *p)
2199 if ((cpu != smp_processor_id()) && task_curr(p))
2200 smp_send_reschedule(cpu);
2203 EXPORT_SYMBOL_GPL(kick_process);
2204 #endif /* CONFIG_SMP */
2207 * task_oncpu_function_call - call a function on the cpu on which a task runs
2208 * @p: the task to evaluate
2209 * @func: the function to be called
2210 * @info: the function call argument
2212 * Calls the function @func when the task is currently running. This might
2213 * be on the current CPU, which just calls the function directly
2215 void task_oncpu_function_call(struct task_struct *p,
2216 void (*func) (void *info), void *info)
2223 smp_call_function_single(cpu, func, info, 1);
2229 * ->cpus_allowed is protected by either TASK_WAKING or rq->lock held.
2231 static int select_fallback_rq(int cpu, struct task_struct *p)
2234 const struct cpumask *nodemask = cpumask_of_node(cpu_to_node(cpu));
2236 /* Look for allowed, online CPU in same node. */
2237 for_each_cpu_and(dest_cpu, nodemask, cpu_active_mask)
2238 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
2241 /* Any allowed, online CPU? */
2242 dest_cpu = cpumask_any_and(&p->cpus_allowed, cpu_active_mask);
2243 if (dest_cpu < nr_cpu_ids)
2246 /* No more Mr. Nice Guy. */
2247 dest_cpu = cpuset_cpus_allowed_fallback(p);
2249 * Don't tell them about moving exiting tasks or
2250 * kernel threads (both mm NULL), since they never
2253 if (p->mm && printk_ratelimit()) {
2254 printk(KERN_INFO "process %d (%s) no longer affine to cpu%d\n",
2255 task_pid_nr(p), p->comm, cpu);
2262 * The caller (fork, wakeup) owns TASK_WAKING, ->cpus_allowed is stable.
2265 int select_task_rq(struct rq *rq, struct task_struct *p, int sd_flags, int wake_flags)
2267 int cpu = p->sched_class->select_task_rq(rq, p, sd_flags, wake_flags);
2270 * In order not to call set_task_cpu() on a blocking task we need
2271 * to rely on ttwu() to place the task on a valid ->cpus_allowed
2274 * Since this is common to all placement strategies, this lives here.
2276 * [ this allows ->select_task() to simply return task_cpu(p) and
2277 * not worry about this generic constraint ]
2279 if (unlikely(!cpumask_test_cpu(cpu, &p->cpus_allowed) ||
2281 cpu = select_fallback_rq(task_cpu(p), p);
2286 static void update_avg(u64 *avg, u64 sample)
2288 s64 diff = sample - *avg;
2293 static inline void ttwu_activate(struct task_struct *p, struct rq *rq,
2294 bool is_sync, bool is_migrate, bool is_local,
2295 unsigned long en_flags)
2297 schedstat_inc(p, se.statistics.nr_wakeups);
2299 schedstat_inc(p, se.statistics.nr_wakeups_sync);
2301 schedstat_inc(p, se.statistics.nr_wakeups_migrate);
2303 schedstat_inc(p, se.statistics.nr_wakeups_local);
2305 schedstat_inc(p, se.statistics.nr_wakeups_remote);
2307 activate_task(rq, p, en_flags);
2310 static inline void ttwu_post_activation(struct task_struct *p, struct rq *rq,
2311 int wake_flags, bool success)
2313 trace_sched_wakeup(p, success);
2314 check_preempt_curr(rq, p, wake_flags);
2316 p->state = TASK_RUNNING;
2318 if (p->sched_class->task_woken)
2319 p->sched_class->task_woken(rq, p);
2321 if (unlikely(rq->idle_stamp)) {
2322 u64 delta = rq->clock - rq->idle_stamp;
2323 u64 max = 2*sysctl_sched_migration_cost;
2328 update_avg(&rq->avg_idle, delta);
2332 /* if a worker is waking up, notify workqueue */
2333 if ((p->flags & PF_WQ_WORKER) && success)
2334 wq_worker_waking_up(p, cpu_of(rq));
2338 * try_to_wake_up - wake up a thread
2339 * @p: the thread to be awakened
2340 * @state: the mask of task states that can be woken
2341 * @wake_flags: wake modifier flags (WF_*)
2343 * Put it on the run-queue if it's not already there. The "current"
2344 * thread is always on the run-queue (except when the actual
2345 * re-schedule is in progress), and as such you're allowed to do
2346 * the simpler "current->state = TASK_RUNNING" to mark yourself
2347 * runnable without the overhead of this.
2349 * Returns %true if @p was woken up, %false if it was already running
2350 * or @state didn't match @p's state.
2352 static int try_to_wake_up(struct task_struct *p, unsigned int state,
2355 int cpu, orig_cpu, this_cpu, success = 0;
2356 unsigned long flags;
2357 unsigned long en_flags = ENQUEUE_WAKEUP;
2360 this_cpu = get_cpu();
2363 rq = task_rq_lock(p, &flags);
2364 if (!(p->state & state))
2374 if (unlikely(task_running(rq, p)))
2378 * In order to handle concurrent wakeups and release the rq->lock
2379 * we put the task in TASK_WAKING state.
2381 * First fix up the nr_uninterruptible count:
2383 if (task_contributes_to_load(p)) {
2384 if (likely(cpu_online(orig_cpu)))
2385 rq->nr_uninterruptible--;
2387 this_rq()->nr_uninterruptible--;
2389 p->state = TASK_WAKING;
2391 if (p->sched_class->task_waking) {
2392 p->sched_class->task_waking(rq, p);
2393 en_flags |= ENQUEUE_WAKING;
2396 cpu = select_task_rq(rq, p, SD_BALANCE_WAKE, wake_flags);
2397 if (cpu != orig_cpu)
2398 set_task_cpu(p, cpu);
2399 __task_rq_unlock(rq);
2402 raw_spin_lock(&rq->lock);
2405 * We migrated the task without holding either rq->lock, however
2406 * since the task is not on the task list itself, nobody else
2407 * will try and migrate the task, hence the rq should match the
2408 * cpu we just moved it to.
2410 WARN_ON(task_cpu(p) != cpu);
2411 WARN_ON(p->state != TASK_WAKING);
2413 #ifdef CONFIG_SCHEDSTATS
2414 schedstat_inc(rq, ttwu_count);
2415 if (cpu == this_cpu)
2416 schedstat_inc(rq, ttwu_local);
2418 struct sched_domain *sd;
2419 for_each_domain(this_cpu, sd) {
2420 if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2421 schedstat_inc(sd, ttwu_wake_remote);
2426 #endif /* CONFIG_SCHEDSTATS */
2429 #endif /* CONFIG_SMP */
2430 ttwu_activate(p, rq, wake_flags & WF_SYNC, orig_cpu != cpu,
2431 cpu == this_cpu, en_flags);
2434 ttwu_post_activation(p, rq, wake_flags, success);
2436 task_rq_unlock(rq, &flags);
2443 * try_to_wake_up_local - try to wake up a local task with rq lock held
2444 * @p: the thread to be awakened
2446 * Put @p on the run-queue if it's not alredy there. The caller must
2447 * ensure that this_rq() is locked, @p is bound to this_rq() and not
2448 * the current task. this_rq() stays locked over invocation.
2450 static void try_to_wake_up_local(struct task_struct *p)
2452 struct rq *rq = task_rq(p);
2453 bool success = false;
2455 BUG_ON(rq != this_rq());
2456 BUG_ON(p == current);
2457 lockdep_assert_held(&rq->lock);
2459 if (!(p->state & TASK_NORMAL))
2463 if (likely(!task_running(rq, p))) {
2464 schedstat_inc(rq, ttwu_count);
2465 schedstat_inc(rq, ttwu_local);
2467 ttwu_activate(p, rq, false, false, true, ENQUEUE_WAKEUP);
2470 ttwu_post_activation(p, rq, 0, success);
2474 * wake_up_process - Wake up a specific process
2475 * @p: The process to be woken up.
2477 * Attempt to wake up the nominated process and move it to the set of runnable
2478 * processes. Returns 1 if the process was woken up, 0 if it was already
2481 * It may be assumed that this function implies a write memory barrier before
2482 * changing the task state if and only if any tasks are woken up.
2484 int wake_up_process(struct task_struct *p)
2486 return try_to_wake_up(p, TASK_ALL, 0);
2488 EXPORT_SYMBOL(wake_up_process);
2490 int wake_up_state(struct task_struct *p, unsigned int state)
2492 return try_to_wake_up(p, state, 0);
2496 * Perform scheduler related setup for a newly forked process p.
2497 * p is forked by current.
2499 * __sched_fork() is basic setup used by init_idle() too:
2501 static void __sched_fork(struct task_struct *p)
2503 p->se.exec_start = 0;
2504 p->se.sum_exec_runtime = 0;
2505 p->se.prev_sum_exec_runtime = 0;
2506 p->se.nr_migrations = 0;
2508 #ifdef CONFIG_SCHEDSTATS
2509 memset(&p->se.statistics, 0, sizeof(p->se.statistics));
2512 INIT_LIST_HEAD(&p->rt.run_list);
2514 INIT_LIST_HEAD(&p->se.group_node);
2516 #ifdef CONFIG_PREEMPT_NOTIFIERS
2517 INIT_HLIST_HEAD(&p->preempt_notifiers);
2522 * fork()/clone()-time setup:
2524 void sched_fork(struct task_struct *p, int clone_flags)
2526 int cpu = get_cpu();
2530 * We mark the process as running here. This guarantees that
2531 * nobody will actually run it, and a signal or other external
2532 * event cannot wake it up and insert it on the runqueue either.
2534 p->state = TASK_RUNNING;
2537 * Revert to default priority/policy on fork if requested.
2539 if (unlikely(p->sched_reset_on_fork)) {
2540 if (p->policy == SCHED_FIFO || p->policy == SCHED_RR) {
2541 p->policy = SCHED_NORMAL;
2542 p->normal_prio = p->static_prio;
2545 if (PRIO_TO_NICE(p->static_prio) < 0) {
2546 p->static_prio = NICE_TO_PRIO(0);
2547 p->normal_prio = p->static_prio;
2552 * We don't need the reset flag anymore after the fork. It has
2553 * fulfilled its duty:
2555 p->sched_reset_on_fork = 0;
2559 * Make sure we do not leak PI boosting priority to the child.
2561 p->prio = current->normal_prio;
2563 if (!rt_prio(p->prio))
2564 p->sched_class = &fair_sched_class;
2566 if (p->sched_class->task_fork)
2567 p->sched_class->task_fork(p);
2570 * The child is not yet in the pid-hash so no cgroup attach races,
2571 * and the cgroup is pinned to this child due to cgroup_fork()
2572 * is ran before sched_fork().
2574 * Silence PROVE_RCU.
2577 set_task_cpu(p, cpu);
2580 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2581 if (likely(sched_info_on()))
2582 memset(&p->sched_info, 0, sizeof(p->sched_info));
2584 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2587 #ifdef CONFIG_PREEMPT
2588 /* Want to start with kernel preemption disabled. */
2589 task_thread_info(p)->preempt_count = 1;
2591 plist_node_init(&p->pushable_tasks, MAX_PRIO);
2597 * wake_up_new_task - wake up a newly created task for the first time.
2599 * This function will do some initial scheduler statistics housekeeping
2600 * that must be done for every newly created context, then puts the task
2601 * on the runqueue and wakes it.
2603 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2605 unsigned long flags;
2607 int cpu __maybe_unused = get_cpu();
2610 rq = task_rq_lock(p, &flags);
2611 p->state = TASK_WAKING;
2614 * Fork balancing, do it here and not earlier because:
2615 * - cpus_allowed can change in the fork path
2616 * - any previously selected cpu might disappear through hotplug
2618 * We set TASK_WAKING so that select_task_rq() can drop rq->lock
2619 * without people poking at ->cpus_allowed.
2621 cpu = select_task_rq(rq, p, SD_BALANCE_FORK, 0);
2622 set_task_cpu(p, cpu);
2624 p->state = TASK_RUNNING;
2625 task_rq_unlock(rq, &flags);
2628 rq = task_rq_lock(p, &flags);
2629 activate_task(rq, p, 0);
2630 trace_sched_wakeup_new(p, 1);
2631 check_preempt_curr(rq, p, WF_FORK);
2633 if (p->sched_class->task_woken)
2634 p->sched_class->task_woken(rq, p);
2636 task_rq_unlock(rq, &flags);
2640 #ifdef CONFIG_PREEMPT_NOTIFIERS
2643 * preempt_notifier_register - tell me when current is being preempted & rescheduled
2644 * @notifier: notifier struct to register
2646 void preempt_notifier_register(struct preempt_notifier *notifier)
2648 hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
2650 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2653 * preempt_notifier_unregister - no longer interested in preemption notifications
2654 * @notifier: notifier struct to unregister
2656 * This is safe to call from within a preemption notifier.
2658 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2660 hlist_del(¬ifier->link);
2662 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2664 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2666 struct preempt_notifier *notifier;
2667 struct hlist_node *node;
2669 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2670 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2674 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2675 struct task_struct *next)
2677 struct preempt_notifier *notifier;
2678 struct hlist_node *node;
2680 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2681 notifier->ops->sched_out(notifier, next);
2684 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2686 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2691 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2692 struct task_struct *next)
2696 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2699 * prepare_task_switch - prepare to switch tasks
2700 * @rq: the runqueue preparing to switch
2701 * @prev: the current task that is being switched out
2702 * @next: the task we are going to switch to.
2704 * This is called with the rq lock held and interrupts off. It must
2705 * be paired with a subsequent finish_task_switch after the context
2708 * prepare_task_switch sets up locking and calls architecture specific
2712 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2713 struct task_struct *next)
2715 fire_sched_out_preempt_notifiers(prev, next);
2716 prepare_lock_switch(rq, next);
2717 prepare_arch_switch(next);
2721 * finish_task_switch - clean up after a task-switch
2722 * @rq: runqueue associated with task-switch
2723 * @prev: the thread we just switched away from.
2725 * finish_task_switch must be called after the context switch, paired
2726 * with a prepare_task_switch call before the context switch.
2727 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2728 * and do any other architecture-specific cleanup actions.
2730 * Note that we may have delayed dropping an mm in context_switch(). If
2731 * so, we finish that here outside of the runqueue lock. (Doing it
2732 * with the lock held can cause deadlocks; see schedule() for
2735 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2736 __releases(rq->lock)
2738 struct mm_struct *mm = rq->prev_mm;
2744 * A task struct has one reference for the use as "current".
2745 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2746 * schedule one last time. The schedule call will never return, and
2747 * the scheduled task must drop that reference.
2748 * The test for TASK_DEAD must occur while the runqueue locks are
2749 * still held, otherwise prev could be scheduled on another cpu, die
2750 * there before we look at prev->state, and then the reference would
2752 * Manfred Spraul <manfred@colorfullife.com>
2754 prev_state = prev->state;
2755 finish_arch_switch(prev);
2756 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
2757 local_irq_disable();
2758 #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */
2759 perf_event_task_sched_in(current);
2760 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
2762 #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */
2763 finish_lock_switch(rq, prev);
2765 fire_sched_in_preempt_notifiers(current);
2768 if (unlikely(prev_state == TASK_DEAD)) {
2770 * Remove function-return probe instances associated with this
2771 * task and put them back on the free list.
2773 kprobe_flush_task(prev);
2774 put_task_struct(prev);
2780 /* assumes rq->lock is held */
2781 static inline void pre_schedule(struct rq *rq, struct task_struct *prev)
2783 if (prev->sched_class->pre_schedule)
2784 prev->sched_class->pre_schedule(rq, prev);
2787 /* rq->lock is NOT held, but preemption is disabled */
2788 static inline void post_schedule(struct rq *rq)
2790 if (rq->post_schedule) {
2791 unsigned long flags;
2793 raw_spin_lock_irqsave(&rq->lock, flags);
2794 if (rq->curr->sched_class->post_schedule)
2795 rq->curr->sched_class->post_schedule(rq);
2796 raw_spin_unlock_irqrestore(&rq->lock, flags);
2798 rq->post_schedule = 0;
2804 static inline void pre_schedule(struct rq *rq, struct task_struct *p)
2808 static inline void post_schedule(struct rq *rq)
2815 * schedule_tail - first thing a freshly forked thread must call.
2816 * @prev: the thread we just switched away from.
2818 asmlinkage void schedule_tail(struct task_struct *prev)
2819 __releases(rq->lock)
2821 struct rq *rq = this_rq();
2823 finish_task_switch(rq, prev);
2826 * FIXME: do we need to worry about rq being invalidated by the
2831 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2832 /* In this case, finish_task_switch does not reenable preemption */
2835 if (current->set_child_tid)
2836 put_user(task_pid_vnr(current), current->set_child_tid);
2840 * context_switch - switch to the new MM and the new
2841 * thread's register state.
2844 context_switch(struct rq *rq, struct task_struct *prev,
2845 struct task_struct *next)
2847 struct mm_struct *mm, *oldmm;
2849 prepare_task_switch(rq, prev, next);
2850 trace_sched_switch(prev, next);
2852 oldmm = prev->active_mm;
2854 * For paravirt, this is coupled with an exit in switch_to to
2855 * combine the page table reload and the switch backend into
2858 arch_start_context_switch(prev);
2861 next->active_mm = oldmm;
2862 atomic_inc(&oldmm->mm_count);
2863 enter_lazy_tlb(oldmm, next);
2865 switch_mm(oldmm, mm, next);
2868 prev->active_mm = NULL;
2869 rq->prev_mm = oldmm;
2872 * Since the runqueue lock will be released by the next
2873 * task (which is an invalid locking op but in the case
2874 * of the scheduler it's an obvious special-case), so we
2875 * do an early lockdep release here:
2877 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2878 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2881 /* Here we just switch the register state and the stack. */
2882 switch_to(prev, next, prev);
2886 * this_rq must be evaluated again because prev may have moved
2887 * CPUs since it called schedule(), thus the 'rq' on its stack
2888 * frame will be invalid.
2890 finish_task_switch(this_rq(), prev);
2894 * nr_running, nr_uninterruptible and nr_context_switches:
2896 * externally visible scheduler statistics: current number of runnable
2897 * threads, current number of uninterruptible-sleeping threads, total
2898 * number of context switches performed since bootup.
2900 unsigned long nr_running(void)
2902 unsigned long i, sum = 0;
2904 for_each_online_cpu(i)
2905 sum += cpu_rq(i)->nr_running;
2910 unsigned long nr_uninterruptible(void)
2912 unsigned long i, sum = 0;
2914 for_each_possible_cpu(i)
2915 sum += cpu_rq(i)->nr_uninterruptible;
2918 * Since we read the counters lockless, it might be slightly
2919 * inaccurate. Do not allow it to go below zero though:
2921 if (unlikely((long)sum < 0))
2927 unsigned long long nr_context_switches(void)
2930 unsigned long long sum = 0;
2932 for_each_possible_cpu(i)
2933 sum += cpu_rq(i)->nr_switches;
2938 unsigned long nr_iowait(void)
2940 unsigned long i, sum = 0;
2942 for_each_possible_cpu(i)
2943 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2948 unsigned long nr_iowait_cpu(int cpu)
2950 struct rq *this = cpu_rq(cpu);
2951 return atomic_read(&this->nr_iowait);
2954 unsigned long this_cpu_load(void)
2956 struct rq *this = this_rq();
2957 return this->cpu_load[0];
2961 /* Variables and functions for calc_load */
2962 static atomic_long_t calc_load_tasks;
2963 static unsigned long calc_load_update;
2964 unsigned long avenrun[3];
2965 EXPORT_SYMBOL(avenrun);
2967 static long calc_load_fold_active(struct rq *this_rq)
2969 long nr_active, delta = 0;
2971 nr_active = this_rq->nr_running;
2972 nr_active += (long) this_rq->nr_uninterruptible;
2974 if (nr_active != this_rq->calc_load_active) {
2975 delta = nr_active - this_rq->calc_load_active;
2976 this_rq->calc_load_active = nr_active;
2984 * For NO_HZ we delay the active fold to the next LOAD_FREQ update.
2986 * When making the ILB scale, we should try to pull this in as well.
2988 static atomic_long_t calc_load_tasks_idle;
2990 static void calc_load_account_idle(struct rq *this_rq)
2994 delta = calc_load_fold_active(this_rq);
2996 atomic_long_add(delta, &calc_load_tasks_idle);
2999 static long calc_load_fold_idle(void)
3004 * Its got a race, we don't care...
3006 if (atomic_long_read(&calc_load_tasks_idle))
3007 delta = atomic_long_xchg(&calc_load_tasks_idle, 0);
3012 static void calc_load_account_idle(struct rq *this_rq)
3016 static inline long calc_load_fold_idle(void)
3023 * get_avenrun - get the load average array
3024 * @loads: pointer to dest load array
3025 * @offset: offset to add
3026 * @shift: shift count to shift the result left
3028 * These values are estimates at best, so no need for locking.
3030 void get_avenrun(unsigned long *loads, unsigned long offset, int shift)
3032 loads[0] = (avenrun[0] + offset) << shift;
3033 loads[1] = (avenrun[1] + offset) << shift;
3034 loads[2] = (avenrun[2] + offset) << shift;
3037 static unsigned long
3038 calc_load(unsigned long load, unsigned long exp, unsigned long active)
3041 load += active * (FIXED_1 - exp);
3042 return load >> FSHIFT;
3046 * calc_load - update the avenrun load estimates 10 ticks after the
3047 * CPUs have updated calc_load_tasks.
3049 void calc_global_load(void)
3051 unsigned long upd = calc_load_update + 10;
3054 if (time_before(jiffies, upd))
3057 active = atomic_long_read(&calc_load_tasks);
3058 active = active > 0 ? active * FIXED_1 : 0;
3060 avenrun[0] = calc_load(avenrun[0], EXP_1, active);
3061 avenrun[1] = calc_load(avenrun[1], EXP_5, active);
3062 avenrun[2] = calc_load(avenrun[2], EXP_15, active);
3064 calc_load_update += LOAD_FREQ;
3068 * Called from update_cpu_load() to periodically update this CPU's
3071 static void calc_load_account_active(struct rq *this_rq)
3075 if (time_before(jiffies, this_rq->calc_load_update))
3078 delta = calc_load_fold_active(this_rq);
3079 delta += calc_load_fold_idle();
3081 atomic_long_add(delta, &calc_load_tasks);
3083 this_rq->calc_load_update += LOAD_FREQ;
3087 * The exact cpuload at various idx values, calculated at every tick would be
3088 * load = (2^idx - 1) / 2^idx * load + 1 / 2^idx * cur_load
3090 * If a cpu misses updates for n-1 ticks (as it was idle) and update gets called
3091 * on nth tick when cpu may be busy, then we have:
3092 * load = ((2^idx - 1) / 2^idx)^(n-1) * load
3093 * load = (2^idx - 1) / 2^idx) * load + 1 / 2^idx * cur_load
3095 * decay_load_missed() below does efficient calculation of
3096 * load = ((2^idx - 1) / 2^idx)^(n-1) * load
3097 * avoiding 0..n-1 loop doing load = ((2^idx - 1) / 2^idx) * load
3099 * The calculation is approximated on a 128 point scale.
3100 * degrade_zero_ticks is the number of ticks after which load at any
3101 * particular idx is approximated to be zero.
3102 * degrade_factor is a precomputed table, a row for each load idx.
3103 * Each column corresponds to degradation factor for a power of two ticks,
3104 * based on 128 point scale.
3106 * row 2, col 3 (=12) says that the degradation at load idx 2 after
3107 * 8 ticks is 12/128 (which is an approximation of exact factor 3^8/4^8).
3109 * With this power of 2 load factors, we can degrade the load n times
3110 * by looking at 1 bits in n and doing as many mult/shift instead of
3111 * n mult/shifts needed by the exact degradation.
3113 #define DEGRADE_SHIFT 7
3114 static const unsigned char
3115 degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128};
3116 static const unsigned char
3117 degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = {
3118 {0, 0, 0, 0, 0, 0, 0, 0},
3119 {64, 32, 8, 0, 0, 0, 0, 0},
3120 {96, 72, 40, 12, 1, 0, 0},
3121 {112, 98, 75, 43, 15, 1, 0},
3122 {120, 112, 98, 76, 45, 16, 2} };
3125 * Update cpu_load for any missed ticks, due to tickless idle. The backlog
3126 * would be when CPU is idle and so we just decay the old load without
3127 * adding any new load.
3129 static unsigned long
3130 decay_load_missed(unsigned long load, unsigned long missed_updates, int idx)
3134 if (!missed_updates)
3137 if (missed_updates >= degrade_zero_ticks[idx])
3141 return load >> missed_updates;
3143 while (missed_updates) {
3144 if (missed_updates % 2)
3145 load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT;
3147 missed_updates >>= 1;
3154 * Update rq->cpu_load[] statistics. This function is usually called every
3155 * scheduler tick (TICK_NSEC). With tickless idle this will not be called
3156 * every tick. We fix it up based on jiffies.
3158 static void update_cpu_load(struct rq *this_rq)
3160 unsigned long this_load = this_rq->load.weight;
3161 unsigned long curr_jiffies = jiffies;
3162 unsigned long pending_updates;
3165 this_rq->nr_load_updates++;
3167 /* Avoid repeated calls on same jiffy, when moving in and out of idle */
3168 if (curr_jiffies == this_rq->last_load_update_tick)
3171 pending_updates = curr_jiffies - this_rq->last_load_update_tick;
3172 this_rq->last_load_update_tick = curr_jiffies;
3174 /* Update our load: */
3175 this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */
3176 for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
3177 unsigned long old_load, new_load;
3179 /* scale is effectively 1 << i now, and >> i divides by scale */
3181 old_load = this_rq->cpu_load[i];
3182 old_load = decay_load_missed(old_load, pending_updates - 1, i);
3183 new_load = this_load;
3185 * Round up the averaging division if load is increasing. This
3186 * prevents us from getting stuck on 9 if the load is 10, for
3189 if (new_load > old_load)
3190 new_load += scale - 1;
3192 this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i;
3195 sched_avg_update(this_rq);
3198 static void update_cpu_load_active(struct rq *this_rq)
3200 update_cpu_load(this_rq);
3202 calc_load_account_active(this_rq);
3208 * sched_exec - execve() is a valuable balancing opportunity, because at
3209 * this point the task has the smallest effective memory and cache footprint.
3211 void sched_exec(void)
3213 struct task_struct *p = current;
3214 unsigned long flags;
3218 rq = task_rq_lock(p, &flags);
3219 dest_cpu = p->sched_class->select_task_rq(rq, p, SD_BALANCE_EXEC, 0);
3220 if (dest_cpu == smp_processor_id())
3224 * select_task_rq() can race against ->cpus_allowed
3226 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed) &&
3227 likely(cpu_active(dest_cpu)) && migrate_task(p, dest_cpu)) {
3228 struct migration_arg arg = { p, dest_cpu };
3230 task_rq_unlock(rq, &flags);
3231 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
3235 task_rq_unlock(rq, &flags);
3240 DEFINE_PER_CPU(struct kernel_stat, kstat);
3242 EXPORT_PER_CPU_SYMBOL(kstat);
3245 * Return any ns on the sched_clock that have not yet been accounted in
3246 * @p in case that task is currently running.
3248 * Called with task_rq_lock() held on @rq.
3250 static u64 do_task_delta_exec(struct task_struct *p, struct rq *rq)
3254 if (task_current(rq, p)) {
3255 update_rq_clock(rq);
3256 ns = rq->clock_task - p->se.exec_start;
3264 unsigned long long task_delta_exec(struct task_struct *p)
3266 unsigned long flags;
3270 rq = task_rq_lock(p, &flags);
3271 ns = do_task_delta_exec(p, rq);
3272 task_rq_unlock(rq, &flags);
3278 * Return accounted runtime for the task.
3279 * In case the task is currently running, return the runtime plus current's
3280 * pending runtime that have not been accounted yet.
3282 unsigned long long task_sched_runtime(struct task_struct *p)
3284 unsigned long flags;
3288 rq = task_rq_lock(p, &flags);
3289 ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq);
3290 task_rq_unlock(rq, &flags);
3296 * Return sum_exec_runtime for the thread group.
3297 * In case the task is currently running, return the sum plus current's
3298 * pending runtime that have not been accounted yet.
3300 * Note that the thread group might have other running tasks as well,
3301 * so the return value not includes other pending runtime that other
3302 * running tasks might have.
3304 unsigned long long thread_group_sched_runtime(struct task_struct *p)
3306 struct task_cputime totals;
3307 unsigned long flags;
3311 rq = task_rq_lock(p, &flags);
3312 thread_group_cputime(p, &totals);
3313 ns = totals.sum_exec_runtime + do_task_delta_exec(p, rq);
3314 task_rq_unlock(rq, &flags);
3320 * Account user cpu time to a process.
3321 * @p: the process that the cpu time gets accounted to
3322 * @cputime: the cpu time spent in user space since the last update
3323 * @cputime_scaled: cputime scaled by cpu frequency
3325 void account_user_time(struct task_struct *p, cputime_t cputime,
3326 cputime_t cputime_scaled)
3328 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3331 /* Add user time to process. */
3332 p->utime = cputime_add(p->utime, cputime);
3333 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
3334 account_group_user_time(p, cputime);
3336 /* Add user time to cpustat. */
3337 tmp = cputime_to_cputime64(cputime);
3338 if (TASK_NICE(p) > 0)
3339 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3341 cpustat->user = cputime64_add(cpustat->user, tmp);
3343 cpuacct_update_stats(p, CPUACCT_STAT_USER, cputime);
3344 /* Account for user time used */
3345 acct_update_integrals(p);
3349 * Account guest cpu time to a process.
3350 * @p: the process that the cpu time gets accounted to
3351 * @cputime: the cpu time spent in virtual machine since the last update
3352 * @cputime_scaled: cputime scaled by cpu frequency
3354 static void account_guest_time(struct task_struct *p, cputime_t cputime,
3355 cputime_t cputime_scaled)
3358 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3360 tmp = cputime_to_cputime64(cputime);
3362 /* Add guest time to process. */
3363 p->utime = cputime_add(p->utime, cputime);
3364 p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
3365 account_group_user_time(p, cputime);
3366 p->gtime = cputime_add(p->gtime, cputime);
3368 /* Add guest time to cpustat. */
3369 if (TASK_NICE(p) > 0) {
3370 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3371 cpustat->guest_nice = cputime64_add(cpustat->guest_nice, tmp);
3373 cpustat->user = cputime64_add(cpustat->user, tmp);
3374 cpustat->guest = cputime64_add(cpustat->guest, tmp);
3379 * Account system cpu time to a process.
3380 * @p: the process that the cpu time gets accounted to
3381 * @hardirq_offset: the offset to subtract from hardirq_count()
3382 * @cputime: the cpu time spent in kernel space since the last update
3383 * @cputime_scaled: cputime scaled by cpu frequency
3385 void account_system_time(struct task_struct *p, int hardirq_offset,
3386 cputime_t cputime, cputime_t cputime_scaled)
3388 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3391 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
3392 account_guest_time(p, cputime, cputime_scaled);
3396 /* Add system time to process. */
3397 p->stime = cputime_add(p->stime, cputime);
3398 p->stimescaled = cputime_add(p->stimescaled, cputime_scaled);
3399 account_group_system_time(p, cputime);
3401 /* Add system time to cpustat. */
3402 tmp = cputime_to_cputime64(cputime);
3403 if (hardirq_count() - hardirq_offset)
3404 cpustat->irq = cputime64_add(cpustat->irq, tmp);
3405 else if (in_serving_softirq())
3406 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
3408 cpustat->system = cputime64_add(cpustat->system, tmp);
3410 cpuacct_update_stats(p, CPUACCT_STAT_SYSTEM, cputime);
3412 /* Account for system time used */
3413 acct_update_integrals(p);
3417 * Account for involuntary wait time.
3418 * @steal: the cpu time spent in involuntary wait
3420 void account_steal_time(cputime_t cputime)
3422 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3423 cputime64_t cputime64 = cputime_to_cputime64(cputime);
3425 cpustat->steal = cputime64_add(cpustat->steal, cputime64);
3429 * Account for idle time.
3430 * @cputime: the cpu time spent in idle wait
3432 void account_idle_time(cputime_t cputime)
3434 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3435 cputime64_t cputime64 = cputime_to_cputime64(cputime);
3436 struct rq *rq = this_rq();
3438 if (atomic_read(&rq->nr_iowait) > 0)
3439 cpustat->iowait = cputime64_add(cpustat->iowait, cputime64);
3441 cpustat->idle = cputime64_add(cpustat->idle, cputime64);
3444 #ifndef CONFIG_VIRT_CPU_ACCOUNTING
3447 * Account a single tick of cpu time.
3448 * @p: the process that the cpu time gets accounted to
3449 * @user_tick: indicates if the tick is a user or a system tick
3451 void account_process_tick(struct task_struct *p, int user_tick)
3453 cputime_t one_jiffy_scaled = cputime_to_scaled(cputime_one_jiffy);
3454 struct rq *rq = this_rq();
3457 account_user_time(p, cputime_one_jiffy, one_jiffy_scaled);
3458 else if ((p != rq->idle) || (irq_count() != HARDIRQ_OFFSET))
3459 account_system_time(p, HARDIRQ_OFFSET, cputime_one_jiffy,
3462 account_idle_time(cputime_one_jiffy);
3466 * Account multiple ticks of steal time.
3467 * @p: the process from which the cpu time has been stolen
3468 * @ticks: number of stolen ticks
3470 void account_steal_ticks(unsigned long ticks)
3472 account_steal_time(jiffies_to_cputime(ticks));
3476 * Account multiple ticks of idle time.
3477 * @ticks: number of stolen ticks
3479 void account_idle_ticks(unsigned long ticks)
3481 account_idle_time(jiffies_to_cputime(ticks));
3487 * Use precise platform statistics if available:
3489 #ifdef CONFIG_VIRT_CPU_ACCOUNTING
3490 void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
3496 void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
3498 struct task_cputime cputime;
3500 thread_group_cputime(p, &cputime);
3502 *ut = cputime.utime;
3503 *st = cputime.stime;
3507 #ifndef nsecs_to_cputime
3508 # define nsecs_to_cputime(__nsecs) nsecs_to_jiffies(__nsecs)
3511 void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
3513 cputime_t rtime, utime = p->utime, total = cputime_add(utime, p->stime);
3516 * Use CFS's precise accounting:
3518 rtime = nsecs_to_cputime(p->se.sum_exec_runtime);
3524 do_div(temp, total);
3525 utime = (cputime_t)temp;
3530 * Compare with previous values, to keep monotonicity:
3532 p->prev_utime = max(p->prev_utime, utime);
3533 p->prev_stime = max(p->prev_stime, cputime_sub(rtime, p->prev_utime));
3535 *ut = p->prev_utime;
3536 *st = p->prev_stime;
3540 * Must be called with siglock held.
3542 void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
3544 struct signal_struct *sig = p->signal;
3545 struct task_cputime cputime;
3546 cputime_t rtime, utime, total;
3548 thread_group_cputime(p, &cputime);
3550 total = cputime_add(cputime.utime, cputime.stime);
3551 rtime = nsecs_to_cputime(cputime.sum_exec_runtime);
3556 temp *= cputime.utime;
3557 do_div(temp, total);
3558 utime = (cputime_t)temp;
3562 sig->prev_utime = max(sig->prev_utime, utime);
3563 sig->prev_stime = max(sig->prev_stime,
3564 cputime_sub(rtime, sig->prev_utime));
3566 *ut = sig->prev_utime;
3567 *st = sig->prev_stime;
3572 * This function gets called by the timer code, with HZ frequency.
3573 * We call it with interrupts disabled.
3575 * It also gets called by the fork code, when changing the parent's
3578 void scheduler_tick(void)
3580 int cpu = smp_processor_id();
3581 struct rq *rq = cpu_rq(cpu);
3582 struct task_struct *curr = rq->curr;
3586 raw_spin_lock(&rq->lock);
3587 update_rq_clock(rq);
3588 update_cpu_load_active(rq);
3589 curr->sched_class->task_tick(rq, curr, 0);
3590 raw_spin_unlock(&rq->lock);
3592 perf_event_task_tick();
3595 rq->idle_at_tick = idle_cpu(cpu);
3596 trigger_load_balance(rq, cpu);
3600 notrace unsigned long get_parent_ip(unsigned long addr)
3602 if (in_lock_functions(addr)) {
3603 addr = CALLER_ADDR2;
3604 if (in_lock_functions(addr))
3605 addr = CALLER_ADDR3;
3610 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
3611 defined(CONFIG_PREEMPT_TRACER))
3613 void __kprobes add_preempt_count(int val)
3615 #ifdef CONFIG_DEBUG_PREEMPT
3619 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3622 preempt_count() += val;
3623 #ifdef CONFIG_DEBUG_PREEMPT
3625 * Spinlock count overflowing soon?
3627 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3630 if (preempt_count() == val)
3631 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
3633 EXPORT_SYMBOL(add_preempt_count);
3635 void __kprobes sub_preempt_count(int val)
3637 #ifdef CONFIG_DEBUG_PREEMPT
3641 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3644 * Is the spinlock portion underflowing?
3646 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3647 !(preempt_count() & PREEMPT_MASK)))
3651 if (preempt_count() == val)
3652 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
3653 preempt_count() -= val;
3655 EXPORT_SYMBOL(sub_preempt_count);
3660 * Print scheduling while atomic bug:
3662 static noinline void __schedule_bug(struct task_struct *prev)
3664 struct pt_regs *regs = get_irq_regs();
3666 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3667 prev->comm, prev->pid, preempt_count());
3669 debug_show_held_locks(prev);
3671 if (irqs_disabled())
3672 print_irqtrace_events(prev);
3681 * Various schedule()-time debugging checks and statistics:
3683 static inline void schedule_debug(struct task_struct *prev)
3686 * Test if we are atomic. Since do_exit() needs to call into
3687 * schedule() atomically, we ignore that path for now.
3688 * Otherwise, whine if we are scheduling when we should not be.
3690 if (unlikely(in_atomic_preempt_off() && !prev->exit_state))
3691 __schedule_bug(prev);
3693 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3695 schedstat_inc(this_rq(), sched_count);
3696 #ifdef CONFIG_SCHEDSTATS
3697 if (unlikely(prev->lock_depth >= 0)) {
3698 schedstat_inc(this_rq(), bkl_count);
3699 schedstat_inc(prev, sched_info.bkl_count);
3704 static void put_prev_task(struct rq *rq, struct task_struct *prev)
3707 update_rq_clock(rq);
3708 rq->skip_clock_update = 0;
3709 prev->sched_class->put_prev_task(rq, prev);
3713 * Pick up the highest-prio task:
3715 static inline struct task_struct *
3716 pick_next_task(struct rq *rq)
3718 const struct sched_class *class;
3719 struct task_struct *p;
3722 * Optimization: we know that if all tasks are in
3723 * the fair class we can call that function directly:
3725 if (likely(rq->nr_running == rq->cfs.nr_running)) {
3726 p = fair_sched_class.pick_next_task(rq);
3731 for_each_class(class) {
3732 p = class->pick_next_task(rq);
3737 BUG(); /* the idle class will always have a runnable task */
3741 * schedule() is the main scheduler function.
3743 asmlinkage void __sched schedule(void)
3745 struct task_struct *prev, *next;
3746 unsigned long *switch_count;
3752 cpu = smp_processor_id();
3754 rcu_note_context_switch(cpu);
3757 release_kernel_lock(prev);
3758 need_resched_nonpreemptible:
3760 schedule_debug(prev);
3762 if (sched_feat(HRTICK))
3765 raw_spin_lock_irq(&rq->lock);
3766 clear_tsk_need_resched(prev);
3768 switch_count = &prev->nivcsw;
3769 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3770 if (unlikely(signal_pending_state(prev->state, prev))) {
3771 prev->state = TASK_RUNNING;
3774 * If a worker is going to sleep, notify and
3775 * ask workqueue whether it wants to wake up a
3776 * task to maintain concurrency. If so, wake
3779 if (prev->flags & PF_WQ_WORKER) {
3780 struct task_struct *to_wakeup;
3782 to_wakeup = wq_worker_sleeping(prev, cpu);
3784 try_to_wake_up_local(to_wakeup);
3786 deactivate_task(rq, prev, DEQUEUE_SLEEP);
3788 switch_count = &prev->nvcsw;
3791 pre_schedule(rq, prev);
3793 if (unlikely(!rq->nr_running))
3794 idle_balance(cpu, rq);
3796 put_prev_task(rq, prev);
3797 next = pick_next_task(rq);
3799 if (likely(prev != next)) {
3800 sched_info_switch(prev, next);
3801 perf_event_task_sched_out(prev, next);
3807 context_switch(rq, prev, next); /* unlocks the rq */
3809 * The context switch have flipped the stack from under us
3810 * and restored the local variables which were saved when
3811 * this task called schedule() in the past. prev == current
3812 * is still correct, but it can be moved to another cpu/rq.
3814 cpu = smp_processor_id();
3817 raw_spin_unlock_irq(&rq->lock);
3821 if (unlikely(reacquire_kernel_lock(prev)))
3822 goto need_resched_nonpreemptible;
3824 preempt_enable_no_resched();
3828 EXPORT_SYMBOL(schedule);
3830 #ifdef CONFIG_MUTEX_SPIN_ON_OWNER
3832 * Look out! "owner" is an entirely speculative pointer
3833 * access and not reliable.
3835 int mutex_spin_on_owner(struct mutex *lock, struct thread_info *owner)
3840 if (!sched_feat(OWNER_SPIN))
3843 #ifdef CONFIG_DEBUG_PAGEALLOC
3845 * Need to access the cpu field knowing that
3846 * DEBUG_PAGEALLOC could have unmapped it if
3847 * the mutex owner just released it and exited.
3849 if (probe_kernel_address(&owner->cpu, cpu))
3856 * Even if the access succeeded (likely case),
3857 * the cpu field may no longer be valid.
3859 if (cpu >= nr_cpumask_bits)
3863 * We need to validate that we can do a
3864 * get_cpu() and that we have the percpu area.
3866 if (!cpu_online(cpu))
3873 * Owner changed, break to re-assess state.
3875 if (lock->owner != owner) {
3877 * If the lock has switched to a different owner,
3878 * we likely have heavy contention. Return 0 to quit
3879 * optimistic spinning and not contend further:
3887 * Is that owner really running on that cpu?
3889 if (task_thread_info(rq->curr) != owner || need_resched())
3892 arch_mutex_cpu_relax();
3899 #ifdef CONFIG_PREEMPT
3901 * this is the entry point to schedule() from in-kernel preemption
3902 * off of preempt_enable. Kernel preemptions off return from interrupt
3903 * occur there and call schedule directly.
3905 asmlinkage void __sched notrace preempt_schedule(void)
3907 struct thread_info *ti = current_thread_info();
3910 * If there is a non-zero preempt_count or interrupts are disabled,
3911 * we do not want to preempt the current task. Just return..
3913 if (likely(ti->preempt_count || irqs_disabled()))
3917 add_preempt_count_notrace(PREEMPT_ACTIVE);
3919 sub_preempt_count_notrace(PREEMPT_ACTIVE);
3922 * Check again in case we missed a preemption opportunity
3923 * between schedule and now.
3926 } while (need_resched());
3928 EXPORT_SYMBOL(preempt_schedule);
3931 * this is the entry point to schedule() from kernel preemption
3932 * off of irq context.
3933 * Note, that this is called and return with irqs disabled. This will
3934 * protect us against recursive calling from irq.
3936 asmlinkage void __sched preempt_schedule_irq(void)
3938 struct thread_info *ti = current_thread_info();
3940 /* Catch callers which need to be fixed */
3941 BUG_ON(ti->preempt_count || !irqs_disabled());
3944 add_preempt_count(PREEMPT_ACTIVE);
3947 local_irq_disable();
3948 sub_preempt_count(PREEMPT_ACTIVE);
3951 * Check again in case we missed a preemption opportunity
3952 * between schedule and now.
3955 } while (need_resched());
3958 #endif /* CONFIG_PREEMPT */
3960 int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
3963 return try_to_wake_up(curr->private, mode, wake_flags);
3965 EXPORT_SYMBOL(default_wake_function);
3968 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3969 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3970 * number) then we wake all the non-exclusive tasks and one exclusive task.
3972 * There are circumstances in which we can try to wake a task which has already
3973 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3974 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3976 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3977 int nr_exclusive, int wake_flags, void *key)
3979 wait_queue_t *curr, *next;
3981 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
3982 unsigned flags = curr->flags;
3984 if (curr->func(curr, mode, wake_flags, key) &&
3985 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
3991 * __wake_up - wake up threads blocked on a waitqueue.
3993 * @mode: which threads
3994 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3995 * @key: is directly passed to the wakeup function
3997 * It may be assumed that this function implies a write memory barrier before
3998 * changing the task state if and only if any tasks are woken up.
4000 void __wake_up(wait_queue_head_t *q, unsigned int mode,
4001 int nr_exclusive, void *key)
4003 unsigned long flags;
4005 spin_lock_irqsave(&q->lock, flags);
4006 __wake_up_common(q, mode, nr_exclusive, 0, key);
4007 spin_unlock_irqrestore(&q->lock, flags);
4009 EXPORT_SYMBOL(__wake_up);
4012 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4014 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4016 __wake_up_common(q, mode, 1, 0, NULL);
4018 EXPORT_SYMBOL_GPL(__wake_up_locked);
4020 void __wake_up_locked_key(wait_queue_head_t *q, unsigned int mode, void *key)
4022 __wake_up_common(q, mode, 1, 0, key);
4026 * __wake_up_sync_key - wake up threads blocked on a waitqueue.
4028 * @mode: which threads
4029 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4030 * @key: opaque value to be passed to wakeup targets
4032 * The sync wakeup differs that the waker knows that it will schedule
4033 * away soon, so while the target thread will be woken up, it will not
4034 * be migrated to another CPU - ie. the two threads are 'synchronized'
4035 * with each other. This can prevent needless bouncing between CPUs.
4037 * On UP it can prevent extra preemption.
4039 * It may be assumed that this function implies a write memory barrier before
4040 * changing the task state if and only if any tasks are woken up.
4042 void __wake_up_sync_key(wait_queue_head_t *q, unsigned int mode,
4043 int nr_exclusive, void *key)
4045 unsigned long flags;
4046 int wake_flags = WF_SYNC;
4051 if (unlikely(!nr_exclusive))
4054 spin_lock_irqsave(&q->lock, flags);
4055 __wake_up_common(q, mode, nr_exclusive, wake_flags, key);
4056 spin_unlock_irqrestore(&q->lock, flags);
4058 EXPORT_SYMBOL_GPL(__wake_up_sync_key);
4061 * __wake_up_sync - see __wake_up_sync_key()
4063 void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4065 __wake_up_sync_key(q, mode, nr_exclusive, NULL);
4067 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
4070 * complete: - signals a single thread waiting on this completion
4071 * @x: holds the state of this particular completion
4073 * This will wake up a single thread waiting on this completion. Threads will be
4074 * awakened in the same order in which they were queued.
4076 * See also complete_all(), wait_for_completion() and related routines.
4078 * It may be assumed that this function implies a write memory barrier before
4079 * changing the task state if and only if any tasks are woken up.
4081 void complete(struct completion *x)
4083 unsigned long flags;
4085 spin_lock_irqsave(&x->wait.lock, flags);
4087 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4088 spin_unlock_irqrestore(&x->wait.lock, flags);
4090 EXPORT_SYMBOL(complete);
4093 * complete_all: - signals all threads waiting on this completion
4094 * @x: holds the state of this particular completion
4096 * This will wake up all threads waiting on this particular completion event.
4098 * It may be assumed that this function implies a write memory barrier before
4099 * changing the task state if and only if any tasks are woken up.
4101 void complete_all(struct completion *x)
4103 unsigned long flags;
4105 spin_lock_irqsave(&x->wait.lock, flags);
4106 x->done += UINT_MAX/2;
4107 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4108 spin_unlock_irqrestore(&x->wait.lock, flags);
4110 EXPORT_SYMBOL(complete_all);
4112 static inline long __sched
4113 do_wait_for_common(struct completion *x, long timeout, int state)
4116 DECLARE_WAITQUEUE(wait, current);
4118 __add_wait_queue_tail_exclusive(&x->wait, &wait);
4120 if (signal_pending_state(state, current)) {
4121 timeout = -ERESTARTSYS;
4124 __set_current_state(state);
4125 spin_unlock_irq(&x->wait.lock);
4126 timeout = schedule_timeout(timeout);
4127 spin_lock_irq(&x->wait.lock);
4128 } while (!x->done && timeout);
4129 __remove_wait_queue(&x->wait, &wait);
4134 return timeout ?: 1;
4138 wait_for_common(struct completion *x, long timeout, int state)
4142 spin_lock_irq(&x->wait.lock);
4143 timeout = do_wait_for_common(x, timeout, state);
4144 spin_unlock_irq(&x->wait.lock);
4149 * wait_for_completion: - waits for completion of a task
4150 * @x: holds the state of this particular completion
4152 * This waits to be signaled for completion of a specific task. It is NOT
4153 * interruptible and there is no timeout.
4155 * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
4156 * and interrupt capability. Also see complete().
4158 void __sched wait_for_completion(struct completion *x)
4160 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4162 EXPORT_SYMBOL(wait_for_completion);
4165 * wait_for_completion_timeout: - waits for completion of a task (w/timeout)
4166 * @x: holds the state of this particular completion
4167 * @timeout: timeout value in jiffies
4169 * This waits for either a completion of a specific task to be signaled or for a
4170 * specified timeout to expire. The timeout is in jiffies. It is not
4173 unsigned long __sched
4174 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4176 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4178 EXPORT_SYMBOL(wait_for_completion_timeout);
4181 * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
4182 * @x: holds the state of this particular completion
4184 * This waits for completion of a specific task to be signaled. It is
4187 int __sched wait_for_completion_interruptible(struct completion *x)
4189 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4190 if (t == -ERESTARTSYS)
4194 EXPORT_SYMBOL(wait_for_completion_interruptible);
4197 * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
4198 * @x: holds the state of this particular completion
4199 * @timeout: timeout value in jiffies
4201 * This waits for either a completion of a specific task to be signaled or for a
4202 * specified timeout to expire. It is interruptible. The timeout is in jiffies.
4204 unsigned long __sched
4205 wait_for_completion_interruptible_timeout(struct completion *x,
4206 unsigned long timeout)
4208 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4210 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4213 * wait_for_completion_killable: - waits for completion of a task (killable)
4214 * @x: holds the state of this particular completion
4216 * This waits to be signaled for completion of a specific task. It can be
4217 * interrupted by a kill signal.
4219 int __sched wait_for_completion_killable(struct completion *x)
4221 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4222 if (t == -ERESTARTSYS)
4226 EXPORT_SYMBOL(wait_for_completion_killable);
4229 * wait_for_completion_killable_timeout: - waits for completion of a task (w/(to,killable))
4230 * @x: holds the state of this particular completion
4231 * @timeout: timeout value in jiffies
4233 * This waits for either a completion of a specific task to be
4234 * signaled or for a specified timeout to expire. It can be
4235 * interrupted by a kill signal. The timeout is in jiffies.
4237 unsigned long __sched
4238 wait_for_completion_killable_timeout(struct completion *x,
4239 unsigned long timeout)
4241 return wait_for_common(x, timeout, TASK_KILLABLE);
4243 EXPORT_SYMBOL(wait_for_completion_killable_timeout);
4246 * try_wait_for_completion - try to decrement a completion without blocking
4247 * @x: completion structure
4249 * Returns: 0 if a decrement cannot be done without blocking
4250 * 1 if a decrement succeeded.
4252 * If a completion is being used as a counting completion,
4253 * attempt to decrement the counter without blocking. This
4254 * enables us to avoid waiting if the resource the completion
4255 * is protecting is not available.
4257 bool try_wait_for_completion(struct completion *x)
4259 unsigned long flags;
4262 spin_lock_irqsave(&x->wait.lock, flags);
4267 spin_unlock_irqrestore(&x->wait.lock, flags);
4270 EXPORT_SYMBOL(try_wait_for_completion);
4273 * completion_done - Test to see if a completion has any waiters
4274 * @x: completion structure
4276 * Returns: 0 if there are waiters (wait_for_completion() in progress)
4277 * 1 if there are no waiters.
4280 bool completion_done(struct completion *x)
4282 unsigned long flags;
4285 spin_lock_irqsave(&x->wait.lock, flags);
4288 spin_unlock_irqrestore(&x->wait.lock, flags);
4291 EXPORT_SYMBOL(completion_done);
4294 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4296 unsigned long flags;
4299 init_waitqueue_entry(&wait, current);
4301 __set_current_state(state);
4303 spin_lock_irqsave(&q->lock, flags);
4304 __add_wait_queue(q, &wait);
4305 spin_unlock(&q->lock);
4306 timeout = schedule_timeout(timeout);
4307 spin_lock_irq(&q->lock);
4308 __remove_wait_queue(q, &wait);
4309 spin_unlock_irqrestore(&q->lock, flags);
4314 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4316 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4318 EXPORT_SYMBOL(interruptible_sleep_on);
4321 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4323 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4325 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4327 void __sched sleep_on(wait_queue_head_t *q)
4329 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4331 EXPORT_SYMBOL(sleep_on);
4333 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4335 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
4337 EXPORT_SYMBOL(sleep_on_timeout);
4339 #ifdef CONFIG_RT_MUTEXES
4342 * rt_mutex_setprio - set the current priority of a task
4344 * @prio: prio value (kernel-internal form)
4346 * This function changes the 'effective' priority of a task. It does
4347 * not touch ->normal_prio like __setscheduler().
4349 * Used by the rt_mutex code to implement priority inheritance logic.
4351 void rt_mutex_setprio(struct task_struct *p, int prio)
4353 unsigned long flags;
4354 int oldprio, on_rq, running;
4356 const struct sched_class *prev_class;
4358 BUG_ON(prio < 0 || prio > MAX_PRIO);
4360 rq = task_rq_lock(p, &flags);
4362 trace_sched_pi_setprio(p, prio);
4364 prev_class = p->sched_class;
4365 on_rq = p->se.on_rq;
4366 running = task_current(rq, p);
4368 dequeue_task(rq, p, 0);
4370 p->sched_class->put_prev_task(rq, p);
4373 p->sched_class = &rt_sched_class;
4375 p->sched_class = &fair_sched_class;
4380 p->sched_class->set_curr_task(rq);
4382 enqueue_task(rq, p, oldprio < prio ? ENQUEUE_HEAD : 0);
4384 check_class_changed(rq, p, prev_class, oldprio, running);
4386 task_rq_unlock(rq, &flags);
4391 void set_user_nice(struct task_struct *p, long nice)
4393 int old_prio, delta, on_rq;
4394 unsigned long flags;
4397 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4400 * We have to be careful, if called from sys_setpriority(),
4401 * the task might be in the middle of scheduling on another CPU.
4403 rq = task_rq_lock(p, &flags);
4405 * The RT priorities are set via sched_setscheduler(), but we still
4406 * allow the 'normal' nice value to be set - but as expected
4407 * it wont have any effect on scheduling until the task is
4408 * SCHED_FIFO/SCHED_RR:
4410 if (task_has_rt_policy(p)) {
4411 p->static_prio = NICE_TO_PRIO(nice);
4414 on_rq = p->se.on_rq;
4416 dequeue_task(rq, p, 0);
4418 p->static_prio = NICE_TO_PRIO(nice);
4421 p->prio = effective_prio(p);
4422 delta = p->prio - old_prio;
4425 enqueue_task(rq, p, 0);
4427 * If the task increased its priority or is running and
4428 * lowered its priority, then reschedule its CPU:
4430 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4431 resched_task(rq->curr);
4434 task_rq_unlock(rq, &flags);
4436 EXPORT_SYMBOL(set_user_nice);
4439 * can_nice - check if a task can reduce its nice value
4443 int can_nice(const struct task_struct *p, const int nice)
4445 /* convert nice value [19,-20] to rlimit style value [1,40] */
4446 int nice_rlim = 20 - nice;
4448 return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
4449 capable(CAP_SYS_NICE));
4452 #ifdef __ARCH_WANT_SYS_NICE
4455 * sys_nice - change the priority of the current process.
4456 * @increment: priority increment
4458 * sys_setpriority is a more generic, but much slower function that
4459 * does similar things.
4461 SYSCALL_DEFINE1(nice, int, increment)
4466 * Setpriority might change our priority at the same moment.
4467 * We don't have to worry. Conceptually one call occurs first
4468 * and we have a single winner.
4470 if (increment < -40)
4475 nice = TASK_NICE(current) + increment;
4481 if (increment < 0 && !can_nice(current, nice))
4484 retval = security_task_setnice(current, nice);
4488 set_user_nice(current, nice);
4495 * task_prio - return the priority value of a given task.
4496 * @p: the task in question.
4498 * This is the priority value as seen by users in /proc.
4499 * RT tasks are offset by -200. Normal tasks are centered
4500 * around 0, value goes from -16 to +15.
4502 int task_prio(const struct task_struct *p)
4504 return p->prio - MAX_RT_PRIO;
4508 * task_nice - return the nice value of a given task.
4509 * @p: the task in question.
4511 int task_nice(const struct task_struct *p)
4513 return TASK_NICE(p);
4515 EXPORT_SYMBOL(task_nice);
4518 * idle_cpu - is a given cpu idle currently?
4519 * @cpu: the processor in question.
4521 int idle_cpu(int cpu)
4523 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
4527 * idle_task - return the idle task for a given cpu.
4528 * @cpu: the processor in question.
4530 struct task_struct *idle_task(int cpu)
4532 return cpu_rq(cpu)->idle;
4536 * find_process_by_pid - find a process with a matching PID value.
4537 * @pid: the pid in question.
4539 static struct task_struct *find_process_by_pid(pid_t pid)
4541 return pid ? find_task_by_vpid(pid) : current;
4544 /* Actually do priority change: must hold rq lock. */
4546 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
4548 BUG_ON(p->se.on_rq);
4551 p->rt_priority = prio;
4552 p->normal_prio = normal_prio(p);
4553 /* we are holding p->pi_lock already */
4554 p->prio = rt_mutex_getprio(p);
4555 if (rt_prio(p->prio))
4556 p->sched_class = &rt_sched_class;
4558 p->sched_class = &fair_sched_class;
4563 * check the target process has a UID that matches the current process's
4565 static bool check_same_owner(struct task_struct *p)
4567 const struct cred *cred = current_cred(), *pcred;
4571 pcred = __task_cred(p);
4572 match = (cred->euid == pcred->euid ||
4573 cred->euid == pcred->uid);
4578 static int __sched_setscheduler(struct task_struct *p, int policy,
4579 const struct sched_param *param, bool user)
4581 int retval, oldprio, oldpolicy = -1, on_rq, running;
4582 unsigned long flags;
4583 const struct sched_class *prev_class;
4587 /* may grab non-irq protected spin_locks */
4588 BUG_ON(in_interrupt());
4590 /* double check policy once rq lock held */
4592 reset_on_fork = p->sched_reset_on_fork;
4593 policy = oldpolicy = p->policy;
4595 reset_on_fork = !!(policy & SCHED_RESET_ON_FORK);
4596 policy &= ~SCHED_RESET_ON_FORK;
4598 if (policy != SCHED_FIFO && policy != SCHED_RR &&
4599 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
4600 policy != SCHED_IDLE)
4605 * Valid priorities for SCHED_FIFO and SCHED_RR are
4606 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4607 * SCHED_BATCH and SCHED_IDLE is 0.
4609 if (param->sched_priority < 0 ||
4610 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
4611 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
4613 if (rt_policy(policy) != (param->sched_priority != 0))
4617 * Allow unprivileged RT tasks to decrease priority:
4619 if (user && !capable(CAP_SYS_NICE)) {
4620 if (rt_policy(policy)) {
4621 unsigned long rlim_rtprio =
4622 task_rlimit(p, RLIMIT_RTPRIO);
4624 /* can't set/change the rt policy */
4625 if (policy != p->policy && !rlim_rtprio)
4628 /* can't increase priority */
4629 if (param->sched_priority > p->rt_priority &&
4630 param->sched_priority > rlim_rtprio)
4634 * Like positive nice levels, dont allow tasks to
4635 * move out of SCHED_IDLE either:
4637 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
4640 /* can't change other user's priorities */
4641 if (!check_same_owner(p))
4644 /* Normal users shall not reset the sched_reset_on_fork flag */
4645 if (p->sched_reset_on_fork && !reset_on_fork)
4650 retval = security_task_setscheduler(p);
4656 * make sure no PI-waiters arrive (or leave) while we are
4657 * changing the priority of the task:
4659 raw_spin_lock_irqsave(&p->pi_lock, flags);
4661 * To be able to change p->policy safely, the apropriate
4662 * runqueue lock must be held.
4664 rq = __task_rq_lock(p);
4667 * Changing the policy of the stop threads its a very bad idea
4669 if (p == rq->stop) {
4670 __task_rq_unlock(rq);
4671 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4675 #ifdef CONFIG_RT_GROUP_SCHED
4678 * Do not allow realtime tasks into groups that have no runtime
4681 if (rt_bandwidth_enabled() && rt_policy(policy) &&
4682 task_group(p)->rt_bandwidth.rt_runtime == 0) {
4683 __task_rq_unlock(rq);
4684 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4690 /* recheck policy now with rq lock held */
4691 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4692 policy = oldpolicy = -1;
4693 __task_rq_unlock(rq);
4694 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4697 on_rq = p->se.on_rq;
4698 running = task_current(rq, p);
4700 deactivate_task(rq, p, 0);
4702 p->sched_class->put_prev_task(rq, p);
4704 p->sched_reset_on_fork = reset_on_fork;
4707 prev_class = p->sched_class;
4708 __setscheduler(rq, p, policy, param->sched_priority);
4711 p->sched_class->set_curr_task(rq);
4713 activate_task(rq, p, 0);
4715 check_class_changed(rq, p, prev_class, oldprio, running);
4717 __task_rq_unlock(rq);
4718 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4720 rt_mutex_adjust_pi(p);
4726 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4727 * @p: the task in question.
4728 * @policy: new policy.
4729 * @param: structure containing the new RT priority.
4731 * NOTE that the task may be already dead.
4733 int sched_setscheduler(struct task_struct *p, int policy,
4734 const struct sched_param *param)
4736 return __sched_setscheduler(p, policy, param, true);
4738 EXPORT_SYMBOL_GPL(sched_setscheduler);
4741 * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4742 * @p: the task in question.
4743 * @policy: new policy.
4744 * @param: structure containing the new RT priority.
4746 * Just like sched_setscheduler, only don't bother checking if the
4747 * current context has permission. For example, this is needed in
4748 * stop_machine(): we create temporary high priority worker threads,
4749 * but our caller might not have that capability.
4751 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
4752 const struct sched_param *param)
4754 return __sched_setscheduler(p, policy, param, false);
4758 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4760 struct sched_param lparam;
4761 struct task_struct *p;
4764 if (!param || pid < 0)
4766 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4771 p = find_process_by_pid(pid);
4773 retval = sched_setscheduler(p, policy, &lparam);
4780 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4781 * @pid: the pid in question.
4782 * @policy: new policy.
4783 * @param: structure containing the new RT priority.
4785 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
4786 struct sched_param __user *, param)
4788 /* negative values for policy are not valid */
4792 return do_sched_setscheduler(pid, policy, param);
4796 * sys_sched_setparam - set/change the RT priority of a thread
4797 * @pid: the pid in question.
4798 * @param: structure containing the new RT priority.
4800 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
4802 return do_sched_setscheduler(pid, -1, param);
4806 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4807 * @pid: the pid in question.
4809 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
4811 struct task_struct *p;
4819 p = find_process_by_pid(pid);
4821 retval = security_task_getscheduler(p);
4824 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
4831 * sys_sched_getparam - get the RT priority of a thread
4832 * @pid: the pid in question.
4833 * @param: structure containing the RT priority.
4835 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
4837 struct sched_param lp;
4838 struct task_struct *p;
4841 if (!param || pid < 0)
4845 p = find_process_by_pid(pid);
4850 retval = security_task_getscheduler(p);
4854 lp.sched_priority = p->rt_priority;
4858 * This one might sleep, we cannot do it with a spinlock held ...
4860 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4869 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
4871 cpumask_var_t cpus_allowed, new_mask;
4872 struct task_struct *p;
4878 p = find_process_by_pid(pid);
4885 /* Prevent p going away */
4889 if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4893 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4895 goto out_free_cpus_allowed;
4898 if (!check_same_owner(p) && !capable(CAP_SYS_NICE))
4901 retval = security_task_setscheduler(p);
4905 cpuset_cpus_allowed(p, cpus_allowed);
4906 cpumask_and(new_mask, in_mask, cpus_allowed);
4908 retval = set_cpus_allowed_ptr(p, new_mask);
4911 cpuset_cpus_allowed(p, cpus_allowed);
4912 if (!cpumask_subset(new_mask, cpus_allowed)) {
4914 * We must have raced with a concurrent cpuset
4915 * update. Just reset the cpus_allowed to the
4916 * cpuset's cpus_allowed
4918 cpumask_copy(new_mask, cpus_allowed);
4923 free_cpumask_var(new_mask);
4924 out_free_cpus_allowed:
4925 free_cpumask_var(cpus_allowed);
4932 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4933 struct cpumask *new_mask)
4935 if (len < cpumask_size())
4936 cpumask_clear(new_mask);
4937 else if (len > cpumask_size())
4938 len = cpumask_size();
4940 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4944 * sys_sched_setaffinity - set the cpu affinity of a process
4945 * @pid: pid of the process
4946 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4947 * @user_mask_ptr: user-space pointer to the new cpu mask
4949 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4950 unsigned long __user *, user_mask_ptr)
4952 cpumask_var_t new_mask;
4955 if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4958 retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4960 retval = sched_setaffinity(pid, new_mask);
4961 free_cpumask_var(new_mask);
4965 long sched_getaffinity(pid_t pid, struct cpumask *mask)
4967 struct task_struct *p;
4968 unsigned long flags;
4976 p = find_process_by_pid(pid);
4980 retval = security_task_getscheduler(p);
4984 rq = task_rq_lock(p, &flags);
4985 cpumask_and(mask, &p->cpus_allowed, cpu_online_mask);
4986 task_rq_unlock(rq, &flags);
4996 * sys_sched_getaffinity - get the cpu affinity of a process
4997 * @pid: pid of the process
4998 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4999 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5001 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
5002 unsigned long __user *, user_mask_ptr)
5007 if ((len * BITS_PER_BYTE) < nr_cpu_ids)
5009 if (len & (sizeof(unsigned long)-1))
5012 if (!alloc_cpumask_var(&mask, GFP_KERNEL))
5015 ret = sched_getaffinity(pid, mask);
5017 size_t retlen = min_t(size_t, len, cpumask_size());
5019 if (copy_to_user(user_mask_ptr, mask, retlen))
5024 free_cpumask_var(mask);
5030 * sys_sched_yield - yield the current processor to other threads.
5032 * This function yields the current CPU to other tasks. If there are no
5033 * other threads running on this CPU then this function will return.
5035 SYSCALL_DEFINE0(sched_yield)
5037 struct rq *rq = this_rq_lock();
5039 schedstat_inc(rq, yld_count);
5040 current->sched_class->yield_task(rq);
5043 * Since we are going to call schedule() anyway, there's
5044 * no need to preempt or enable interrupts:
5046 __release(rq->lock);
5047 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5048 do_raw_spin_unlock(&rq->lock);
5049 preempt_enable_no_resched();
5056 static inline int should_resched(void)
5058 return need_resched() && !(preempt_count() & PREEMPT_ACTIVE);
5061 static void __cond_resched(void)
5063 add_preempt_count(PREEMPT_ACTIVE);
5065 sub_preempt_count(PREEMPT_ACTIVE);
5068 int __sched _cond_resched(void)
5070 if (should_resched()) {
5076 EXPORT_SYMBOL(_cond_resched);
5079 * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
5080 * call schedule, and on return reacquire the lock.
5082 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5083 * operations here to prevent schedule() from being called twice (once via
5084 * spin_unlock(), once by hand).
5086 int __cond_resched_lock(spinlock_t *lock)
5088 int resched = should_resched();
5091 lockdep_assert_held(lock);
5093 if (spin_needbreak(lock) || resched) {
5104 EXPORT_SYMBOL(__cond_resched_lock);
5106 int __sched __cond_resched_softirq(void)
5108 BUG_ON(!in_softirq());
5110 if (should_resched()) {
5118 EXPORT_SYMBOL(__cond_resched_softirq);
5121 * yield - yield the current processor to other threads.
5123 * This is a shortcut for kernel-space yielding - it marks the
5124 * thread runnable and calls sys_sched_yield().
5126 void __sched yield(void)
5128 set_current_state(TASK_RUNNING);
5131 EXPORT_SYMBOL(yield);
5134 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5135 * that process accounting knows that this is a task in IO wait state.
5137 void __sched io_schedule(void)
5139 struct rq *rq = raw_rq();
5141 delayacct_blkio_start();
5142 atomic_inc(&rq->nr_iowait);
5143 current->in_iowait = 1;
5145 current->in_iowait = 0;
5146 atomic_dec(&rq->nr_iowait);
5147 delayacct_blkio_end();
5149 EXPORT_SYMBOL(io_schedule);
5151 long __sched io_schedule_timeout(long timeout)
5153 struct rq *rq = raw_rq();
5156 delayacct_blkio_start();
5157 atomic_inc(&rq->nr_iowait);
5158 current->in_iowait = 1;
5159 ret = schedule_timeout(timeout);
5160 current->in_iowait = 0;
5161 atomic_dec(&rq->nr_iowait);
5162 delayacct_blkio_end();
5167 * sys_sched_get_priority_max - return maximum RT priority.
5168 * @policy: scheduling class.
5170 * this syscall returns the maximum rt_priority that can be used
5171 * by a given scheduling class.
5173 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
5180 ret = MAX_USER_RT_PRIO-1;
5192 * sys_sched_get_priority_min - return minimum RT priority.
5193 * @policy: scheduling class.
5195 * this syscall returns the minimum rt_priority that can be used
5196 * by a given scheduling class.
5198 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
5216 * sys_sched_rr_get_interval - return the default timeslice of a process.
5217 * @pid: pid of the process.
5218 * @interval: userspace pointer to the timeslice value.
5220 * this syscall writes the default timeslice value of a given process
5221 * into the user-space timespec buffer. A value of '0' means infinity.
5223 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
5224 struct timespec __user *, interval)
5226 struct task_struct *p;
5227 unsigned int time_slice;
5228 unsigned long flags;
5238 p = find_process_by_pid(pid);
5242 retval = security_task_getscheduler(p);
5246 rq = task_rq_lock(p, &flags);
5247 time_slice = p->sched_class->get_rr_interval(rq, p);
5248 task_rq_unlock(rq, &flags);
5251 jiffies_to_timespec(time_slice, &t);
5252 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5260 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
5262 void sched_show_task(struct task_struct *p)
5264 unsigned long free = 0;
5267 state = p->state ? __ffs(p->state) + 1 : 0;
5268 printk(KERN_INFO "%-15.15s %c", p->comm,
5269 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5270 #if BITS_PER_LONG == 32
5271 if (state == TASK_RUNNING)
5272 printk(KERN_CONT " running ");
5274 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5276 if (state == TASK_RUNNING)
5277 printk(KERN_CONT " running task ");
5279 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5281 #ifdef CONFIG_DEBUG_STACK_USAGE
5282 free = stack_not_used(p);
5284 printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
5285 task_pid_nr(p), task_pid_nr(p->real_parent),
5286 (unsigned long)task_thread_info(p)->flags);
5288 show_stack(p, NULL);
5291 void show_state_filter(unsigned long state_filter)
5293 struct task_struct *g, *p;
5295 #if BITS_PER_LONG == 32
5297 " task PC stack pid father\n");
5300 " task PC stack pid father\n");
5302 read_lock(&tasklist_lock);
5303 do_each_thread(g, p) {
5305 * reset the NMI-timeout, listing all files on a slow
5306 * console might take alot of time:
5308 touch_nmi_watchdog();
5309 if (!state_filter || (p->state & state_filter))
5311 } while_each_thread(g, p);
5313 touch_all_softlockup_watchdogs();
5315 #ifdef CONFIG_SCHED_DEBUG
5316 sysrq_sched_debug_show();
5318 read_unlock(&tasklist_lock);
5320 * Only show locks if all tasks are dumped:
5323 debug_show_all_locks();
5326 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5328 idle->sched_class = &idle_sched_class;
5332 * init_idle - set up an idle thread for a given CPU
5333 * @idle: task in question
5334 * @cpu: cpu the idle task belongs to
5336 * NOTE: this function does not set the idle thread's NEED_RESCHED
5337 * flag, to make booting more robust.
5339 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5341 struct rq *rq = cpu_rq(cpu);
5342 unsigned long flags;
5344 raw_spin_lock_irqsave(&rq->lock, flags);
5347 idle->state = TASK_RUNNING;
5348 idle->se.exec_start = sched_clock();
5350 cpumask_copy(&idle->cpus_allowed, cpumask_of(cpu));
5352 * We're having a chicken and egg problem, even though we are
5353 * holding rq->lock, the cpu isn't yet set to this cpu so the
5354 * lockdep check in task_group() will fail.
5356 * Similar case to sched_fork(). / Alternatively we could
5357 * use task_rq_lock() here and obtain the other rq->lock.
5362 __set_task_cpu(idle, cpu);
5365 rq->curr = rq->idle = idle;
5366 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5369 raw_spin_unlock_irqrestore(&rq->lock, flags);
5371 /* Set the preempt count _outside_ the spinlocks! */
5372 #if defined(CONFIG_PREEMPT)
5373 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
5375 task_thread_info(idle)->preempt_count = 0;
5378 * The idle tasks have their own, simple scheduling class:
5380 idle->sched_class = &idle_sched_class;
5381 ftrace_graph_init_task(idle);
5385 * In a system that switches off the HZ timer nohz_cpu_mask
5386 * indicates which cpus entered this state. This is used
5387 * in the rcu update to wait only for active cpus. For system
5388 * which do not switch off the HZ timer nohz_cpu_mask should
5389 * always be CPU_BITS_NONE.
5391 cpumask_var_t nohz_cpu_mask;
5394 * Increase the granularity value when there are more CPUs,
5395 * because with more CPUs the 'effective latency' as visible
5396 * to users decreases. But the relationship is not linear,
5397 * so pick a second-best guess by going with the log2 of the
5400 * This idea comes from the SD scheduler of Con Kolivas:
5402 static int get_update_sysctl_factor(void)
5404 unsigned int cpus = min_t(int, num_online_cpus(), 8);
5405 unsigned int factor;
5407 switch (sysctl_sched_tunable_scaling) {
5408 case SCHED_TUNABLESCALING_NONE:
5411 case SCHED_TUNABLESCALING_LINEAR:
5414 case SCHED_TUNABLESCALING_LOG:
5416 factor = 1 + ilog2(cpus);
5423 static void update_sysctl(void)
5425 unsigned int factor = get_update_sysctl_factor();
5427 #define SET_SYSCTL(name) \
5428 (sysctl_##name = (factor) * normalized_sysctl_##name)
5429 SET_SYSCTL(sched_min_granularity);
5430 SET_SYSCTL(sched_latency);
5431 SET_SYSCTL(sched_wakeup_granularity);
5435 static inline void sched_init_granularity(void)
5442 * This is how migration works:
5444 * 1) we invoke migration_cpu_stop() on the target CPU using
5446 * 2) stopper starts to run (implicitly forcing the migrated thread
5448 * 3) it checks whether the migrated task is still in the wrong runqueue.
5449 * 4) if it's in the wrong runqueue then the migration thread removes
5450 * it and puts it into the right queue.
5451 * 5) stopper completes and stop_one_cpu() returns and the migration
5456 * Change a given task's CPU affinity. Migrate the thread to a
5457 * proper CPU and schedule it away if the CPU it's executing on
5458 * is removed from the allowed bitmask.
5460 * NOTE: the caller must have a valid reference to the task, the
5461 * task must not exit() & deallocate itself prematurely. The
5462 * call is not atomic; no spinlocks may be held.
5464 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
5466 unsigned long flags;
5468 unsigned int dest_cpu;
5472 * Serialize against TASK_WAKING so that ttwu() and wunt() can
5473 * drop the rq->lock and still rely on ->cpus_allowed.
5476 while (task_is_waking(p))
5478 rq = task_rq_lock(p, &flags);
5479 if (task_is_waking(p)) {
5480 task_rq_unlock(rq, &flags);
5484 if (!cpumask_intersects(new_mask, cpu_active_mask)) {
5489 if (unlikely((p->flags & PF_THREAD_BOUND) && p != current &&
5490 !cpumask_equal(&p->cpus_allowed, new_mask))) {
5495 if (p->sched_class->set_cpus_allowed)
5496 p->sched_class->set_cpus_allowed(p, new_mask);
5498 cpumask_copy(&p->cpus_allowed, new_mask);
5499 p->rt.nr_cpus_allowed = cpumask_weight(new_mask);
5502 /* Can the task run on the task's current CPU? If so, we're done */
5503 if (cpumask_test_cpu(task_cpu(p), new_mask))
5506 dest_cpu = cpumask_any_and(cpu_active_mask, new_mask);
5507 if (migrate_task(p, dest_cpu)) {
5508 struct migration_arg arg = { p, dest_cpu };
5509 /* Need help from migration thread: drop lock and wait. */
5510 task_rq_unlock(rq, &flags);
5511 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
5512 tlb_migrate_finish(p->mm);
5516 task_rq_unlock(rq, &flags);
5520 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
5523 * Move (not current) task off this cpu, onto dest cpu. We're doing
5524 * this because either it can't run here any more (set_cpus_allowed()
5525 * away from this CPU, or CPU going down), or because we're
5526 * attempting to rebalance this task on exec (sched_exec).
5528 * So we race with normal scheduler movements, but that's OK, as long
5529 * as the task is no longer on this CPU.
5531 * Returns non-zero if task was successfully migrated.
5533 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
5535 struct rq *rq_dest, *rq_src;
5538 if (unlikely(!cpu_active(dest_cpu)))
5541 rq_src = cpu_rq(src_cpu);
5542 rq_dest = cpu_rq(dest_cpu);
5544 double_rq_lock(rq_src, rq_dest);
5545 /* Already moved. */
5546 if (task_cpu(p) != src_cpu)
5548 /* Affinity changed (again). */
5549 if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
5553 * If we're not on a rq, the next wake-up will ensure we're
5557 deactivate_task(rq_src, p, 0);
5558 set_task_cpu(p, dest_cpu);
5559 activate_task(rq_dest, p, 0);
5560 check_preempt_curr(rq_dest, p, 0);
5565 double_rq_unlock(rq_src, rq_dest);
5570 * migration_cpu_stop - this will be executed by a highprio stopper thread
5571 * and performs thread migration by bumping thread off CPU then
5572 * 'pushing' onto another runqueue.
5574 static int migration_cpu_stop(void *data)
5576 struct migration_arg *arg = data;
5579 * The original target cpu might have gone down and we might
5580 * be on another cpu but it doesn't matter.
5582 local_irq_disable();
5583 __migrate_task(arg->task, raw_smp_processor_id(), arg->dest_cpu);
5588 #ifdef CONFIG_HOTPLUG_CPU
5591 * Ensures that the idle task is using init_mm right before its cpu goes
5594 void idle_task_exit(void)
5596 struct mm_struct *mm = current->active_mm;
5598 BUG_ON(cpu_online(smp_processor_id()));
5601 switch_mm(mm, &init_mm, current);
5606 * While a dead CPU has no uninterruptible tasks queued at this point,
5607 * it might still have a nonzero ->nr_uninterruptible counter, because
5608 * for performance reasons the counter is not stricly tracking tasks to
5609 * their home CPUs. So we just add the counter to another CPU's counter,
5610 * to keep the global sum constant after CPU-down:
5612 static void migrate_nr_uninterruptible(struct rq *rq_src)
5614 struct rq *rq_dest = cpu_rq(cpumask_any(cpu_active_mask));
5616 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5617 rq_src->nr_uninterruptible = 0;
5621 * remove the tasks which were accounted by rq from calc_load_tasks.
5623 static void calc_global_load_remove(struct rq *rq)
5625 atomic_long_sub(rq->calc_load_active, &calc_load_tasks);
5626 rq->calc_load_active = 0;
5630 * Migrate all tasks from the rq, sleeping tasks will be migrated by
5631 * try_to_wake_up()->select_task_rq().
5633 * Called with rq->lock held even though we'er in stop_machine() and
5634 * there's no concurrency possible, we hold the required locks anyway
5635 * because of lock validation efforts.
5637 static void migrate_tasks(unsigned int dead_cpu)
5639 struct rq *rq = cpu_rq(dead_cpu);
5640 struct task_struct *next, *stop = rq->stop;
5644 * Fudge the rq selection such that the below task selection loop
5645 * doesn't get stuck on the currently eligible stop task.
5647 * We're currently inside stop_machine() and the rq is either stuck
5648 * in the stop_machine_cpu_stop() loop, or we're executing this code,
5649 * either way we should never end up calling schedule() until we're
5656 * There's this thread running, bail when that's the only
5659 if (rq->nr_running == 1)
5662 next = pick_next_task(rq);
5664 next->sched_class->put_prev_task(rq, next);
5666 /* Find suitable destination for @next, with force if needed. */
5667 dest_cpu = select_fallback_rq(dead_cpu, next);
5668 raw_spin_unlock(&rq->lock);
5670 __migrate_task(next, dead_cpu, dest_cpu);
5672 raw_spin_lock(&rq->lock);
5678 #endif /* CONFIG_HOTPLUG_CPU */
5680 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5682 static struct ctl_table sd_ctl_dir[] = {
5684 .procname = "sched_domain",
5690 static struct ctl_table sd_ctl_root[] = {
5692 .procname = "kernel",
5694 .child = sd_ctl_dir,
5699 static struct ctl_table *sd_alloc_ctl_entry(int n)
5701 struct ctl_table *entry =
5702 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
5707 static void sd_free_ctl_entry(struct ctl_table **tablep)
5709 struct ctl_table *entry;
5712 * In the intermediate directories, both the child directory and
5713 * procname are dynamically allocated and could fail but the mode
5714 * will always be set. In the lowest directory the names are
5715 * static strings and all have proc handlers.
5717 for (entry = *tablep; entry->mode; entry++) {
5719 sd_free_ctl_entry(&entry->child);
5720 if (entry->proc_handler == NULL)
5721 kfree(entry->procname);
5729 set_table_entry(struct ctl_table *entry,
5730 const char *procname, void *data, int maxlen,
5731 mode_t mode, proc_handler *proc_handler)
5733 entry->procname = procname;
5735 entry->maxlen = maxlen;
5737 entry->proc_handler = proc_handler;
5740 static struct ctl_table *
5741 sd_alloc_ctl_domain_table(struct sched_domain *sd)
5743 struct ctl_table *table = sd_alloc_ctl_entry(13);
5748 set_table_entry(&table[0], "min_interval", &sd->min_interval,
5749 sizeof(long), 0644, proc_doulongvec_minmax);
5750 set_table_entry(&table[1], "max_interval", &sd->max_interval,
5751 sizeof(long), 0644, proc_doulongvec_minmax);
5752 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
5753 sizeof(int), 0644, proc_dointvec_minmax);
5754 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
5755 sizeof(int), 0644, proc_dointvec_minmax);
5756 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
5757 sizeof(int), 0644, proc_dointvec_minmax);
5758 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
5759 sizeof(int), 0644, proc_dointvec_minmax);
5760 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
5761 sizeof(int), 0644, proc_dointvec_minmax);
5762 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
5763 sizeof(int), 0644, proc_dointvec_minmax);
5764 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
5765 sizeof(int), 0644, proc_dointvec_minmax);
5766 set_table_entry(&table[9], "cache_nice_tries",
5767 &sd->cache_nice_tries,
5768 sizeof(int), 0644, proc_dointvec_minmax);
5769 set_table_entry(&table[10], "flags", &sd->flags,
5770 sizeof(int), 0644, proc_dointvec_minmax);
5771 set_table_entry(&table[11], "name", sd->name,
5772 CORENAME_MAX_SIZE, 0444, proc_dostring);
5773 /* &table[12] is terminator */
5778 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
5780 struct ctl_table *entry, *table;
5781 struct sched_domain *sd;
5782 int domain_num = 0, i;
5785 for_each_domain(cpu, sd)
5787 entry = table = sd_alloc_ctl_entry(domain_num + 1);
5792 for_each_domain(cpu, sd) {
5793 snprintf(buf, 32, "domain%d", i);
5794 entry->procname = kstrdup(buf, GFP_KERNEL);
5796 entry->child = sd_alloc_ctl_domain_table(sd);
5803 static struct ctl_table_header *sd_sysctl_header;
5804 static void register_sched_domain_sysctl(void)
5806 int i, cpu_num = num_possible_cpus();
5807 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5810 WARN_ON(sd_ctl_dir[0].child);
5811 sd_ctl_dir[0].child = entry;
5816 for_each_possible_cpu(i) {
5817 snprintf(buf, 32, "cpu%d", i);
5818 entry->procname = kstrdup(buf, GFP_KERNEL);
5820 entry->child = sd_alloc_ctl_cpu_table(i);
5824 WARN_ON(sd_sysctl_header);
5825 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
5828 /* may be called multiple times per register */
5829 static void unregister_sched_domain_sysctl(void)
5831 if (sd_sysctl_header)
5832 unregister_sysctl_table(sd_sysctl_header);
5833 sd_sysctl_header = NULL;
5834 if (sd_ctl_dir[0].child)
5835 sd_free_ctl_entry(&sd_ctl_dir[0].child);
5838 static void register_sched_domain_sysctl(void)
5841 static void unregister_sched_domain_sysctl(void)
5846 static void set_rq_online(struct rq *rq)
5849 const struct sched_class *class;
5851 cpumask_set_cpu(rq->cpu, rq->rd->online);
5854 for_each_class(class) {
5855 if (class->rq_online)
5856 class->rq_online(rq);
5861 static void set_rq_offline(struct rq *rq)
5864 const struct sched_class *class;
5866 for_each_class(class) {
5867 if (class->rq_offline)
5868 class->rq_offline(rq);
5871 cpumask_clear_cpu(rq->cpu, rq->rd->online);
5877 * migration_call - callback that gets triggered when a CPU is added.
5878 * Here we can start up the necessary migration thread for the new CPU.
5880 static int __cpuinit
5881 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
5883 int cpu = (long)hcpu;
5884 unsigned long flags;
5885 struct rq *rq = cpu_rq(cpu);
5887 switch (action & ~CPU_TASKS_FROZEN) {
5889 case CPU_UP_PREPARE:
5890 rq->calc_load_update = calc_load_update;
5894 /* Update our root-domain */
5895 raw_spin_lock_irqsave(&rq->lock, flags);
5897 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5901 raw_spin_unlock_irqrestore(&rq->lock, flags);
5904 #ifdef CONFIG_HOTPLUG_CPU
5906 /* Update our root-domain */
5907 raw_spin_lock_irqsave(&rq->lock, flags);
5909 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5913 BUG_ON(rq->nr_running != 1); /* the migration thread */
5914 raw_spin_unlock_irqrestore(&rq->lock, flags);
5916 migrate_nr_uninterruptible(rq);
5917 calc_global_load_remove(rq);
5925 * Register at high priority so that task migration (migrate_all_tasks)
5926 * happens before everything else. This has to be lower priority than
5927 * the notifier in the perf_event subsystem, though.
5929 static struct notifier_block __cpuinitdata migration_notifier = {
5930 .notifier_call = migration_call,
5931 .priority = CPU_PRI_MIGRATION,
5934 static int __cpuinit sched_cpu_active(struct notifier_block *nfb,
5935 unsigned long action, void *hcpu)
5937 switch (action & ~CPU_TASKS_FROZEN) {
5939 case CPU_DOWN_FAILED:
5940 set_cpu_active((long)hcpu, true);
5947 static int __cpuinit sched_cpu_inactive(struct notifier_block *nfb,
5948 unsigned long action, void *hcpu)
5950 switch (action & ~CPU_TASKS_FROZEN) {
5951 case CPU_DOWN_PREPARE:
5952 set_cpu_active((long)hcpu, false);
5959 static int __init migration_init(void)
5961 void *cpu = (void *)(long)smp_processor_id();
5964 /* Initialize migration for the boot CPU */
5965 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5966 BUG_ON(err == NOTIFY_BAD);
5967 migration_call(&migration_notifier, CPU_ONLINE, cpu);
5968 register_cpu_notifier(&migration_notifier);
5970 /* Register cpu active notifiers */
5971 cpu_notifier(sched_cpu_active, CPU_PRI_SCHED_ACTIVE);
5972 cpu_notifier(sched_cpu_inactive, CPU_PRI_SCHED_INACTIVE);
5976 early_initcall(migration_init);
5981 #ifdef CONFIG_SCHED_DEBUG
5983 static __read_mostly int sched_domain_debug_enabled;
5985 static int __init sched_domain_debug_setup(char *str)
5987 sched_domain_debug_enabled = 1;
5991 early_param("sched_debug", sched_domain_debug_setup);
5993 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
5994 struct cpumask *groupmask)
5996 struct sched_group *group = sd->groups;
5999 cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
6000 cpumask_clear(groupmask);
6002 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6004 if (!(sd->flags & SD_LOAD_BALANCE)) {
6005 printk("does not load-balance\n");
6007 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6012 printk(KERN_CONT "span %s level %s\n", str, sd->name);
6014 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
6015 printk(KERN_ERR "ERROR: domain->span does not contain "
6018 if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
6019 printk(KERN_ERR "ERROR: domain->groups does not contain"
6023 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6027 printk(KERN_ERR "ERROR: group is NULL\n");
6031 if (!group->cpu_power) {
6032 printk(KERN_CONT "\n");
6033 printk(KERN_ERR "ERROR: domain->cpu_power not "
6038 if (!cpumask_weight(sched_group_cpus(group))) {
6039 printk(KERN_CONT "\n");
6040 printk(KERN_ERR "ERROR: empty group\n");
6044 if (cpumask_intersects(groupmask, sched_group_cpus(group))) {
6045 printk(KERN_CONT "\n");
6046 printk(KERN_ERR "ERROR: repeated CPUs\n");
6050 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
6052 cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
6054 printk(KERN_CONT " %s", str);
6055 if (group->cpu_power != SCHED_LOAD_SCALE) {
6056 printk(KERN_CONT " (cpu_power = %d)",
6060 group = group->next;
6061 } while (group != sd->groups);
6062 printk(KERN_CONT "\n");
6064 if (!cpumask_equal(sched_domain_span(sd), groupmask))
6065 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6068 !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
6069 printk(KERN_ERR "ERROR: parent span is not a superset "
6070 "of domain->span\n");
6074 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6076 cpumask_var_t groupmask;
6079 if (!sched_domain_debug_enabled)
6083 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6087 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6089 if (!alloc_cpumask_var(&groupmask, GFP_KERNEL)) {
6090 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
6095 if (sched_domain_debug_one(sd, cpu, level, groupmask))
6102 free_cpumask_var(groupmask);
6104 #else /* !CONFIG_SCHED_DEBUG */
6105 # define sched_domain_debug(sd, cpu) do { } while (0)
6106 #endif /* CONFIG_SCHED_DEBUG */
6108 static int sd_degenerate(struct sched_domain *sd)
6110 if (cpumask_weight(sched_domain_span(sd)) == 1)
6113 /* Following flags need at least 2 groups */
6114 if (sd->flags & (SD_LOAD_BALANCE |
6115 SD_BALANCE_NEWIDLE |
6119 SD_SHARE_PKG_RESOURCES)) {
6120 if (sd->groups != sd->groups->next)
6124 /* Following flags don't use groups */
6125 if (sd->flags & (SD_WAKE_AFFINE))
6132 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6134 unsigned long cflags = sd->flags, pflags = parent->flags;
6136 if (sd_degenerate(parent))
6139 if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
6142 /* Flags needing groups don't count if only 1 group in parent */
6143 if (parent->groups == parent->groups->next) {
6144 pflags &= ~(SD_LOAD_BALANCE |
6145 SD_BALANCE_NEWIDLE |
6149 SD_SHARE_PKG_RESOURCES);
6150 if (nr_node_ids == 1)
6151 pflags &= ~SD_SERIALIZE;
6153 if (~cflags & pflags)
6159 static void free_rootdomain(struct root_domain *rd)
6161 synchronize_sched();
6163 cpupri_cleanup(&rd->cpupri);
6165 free_cpumask_var(rd->rto_mask);
6166 free_cpumask_var(rd->online);
6167 free_cpumask_var(rd->span);
6171 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6173 struct root_domain *old_rd = NULL;
6174 unsigned long flags;
6176 raw_spin_lock_irqsave(&rq->lock, flags);
6181 if (cpumask_test_cpu(rq->cpu, old_rd->online))
6184 cpumask_clear_cpu(rq->cpu, old_rd->span);
6187 * If we dont want to free the old_rt yet then
6188 * set old_rd to NULL to skip the freeing later
6191 if (!atomic_dec_and_test(&old_rd->refcount))
6195 atomic_inc(&rd->refcount);
6198 cpumask_set_cpu(rq->cpu, rd->span);
6199 if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
6202 raw_spin_unlock_irqrestore(&rq->lock, flags);
6205 free_rootdomain(old_rd);
6208 static int init_rootdomain(struct root_domain *rd)
6210 memset(rd, 0, sizeof(*rd));
6212 if (!alloc_cpumask_var(&rd->span, GFP_KERNEL))
6214 if (!alloc_cpumask_var(&rd->online, GFP_KERNEL))
6216 if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
6219 if (cpupri_init(&rd->cpupri) != 0)
6224 free_cpumask_var(rd->rto_mask);
6226 free_cpumask_var(rd->online);
6228 free_cpumask_var(rd->span);
6233 static void init_defrootdomain(void)
6235 init_rootdomain(&def_root_domain);
6237 atomic_set(&def_root_domain.refcount, 1);
6240 static struct root_domain *alloc_rootdomain(void)
6242 struct root_domain *rd;
6244 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6248 if (init_rootdomain(rd) != 0) {
6257 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6258 * hold the hotplug lock.
6261 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6263 struct rq *rq = cpu_rq(cpu);
6264 struct sched_domain *tmp;
6266 for (tmp = sd; tmp; tmp = tmp->parent)
6267 tmp->span_weight = cpumask_weight(sched_domain_span(tmp));
6269 /* Remove the sched domains which do not contribute to scheduling. */
6270 for (tmp = sd; tmp; ) {
6271 struct sched_domain *parent = tmp->parent;
6275 if (sd_parent_degenerate(tmp, parent)) {
6276 tmp->parent = parent->parent;
6278 parent->parent->child = tmp;
6283 if (sd && sd_degenerate(sd)) {
6289 sched_domain_debug(sd, cpu);
6291 rq_attach_root(rq, rd);
6292 rcu_assign_pointer(rq->sd, sd);
6295 /* cpus with isolated domains */
6296 static cpumask_var_t cpu_isolated_map;
6298 /* Setup the mask of cpus configured for isolated domains */
6299 static int __init isolated_cpu_setup(char *str)
6301 alloc_bootmem_cpumask_var(&cpu_isolated_map);
6302 cpulist_parse(str, cpu_isolated_map);
6306 __setup("isolcpus=", isolated_cpu_setup);
6309 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6310 * to a function which identifies what group(along with sched group) a CPU
6311 * belongs to. The return value of group_fn must be a >= 0 and < nr_cpu_ids
6312 * (due to the fact that we keep track of groups covered with a struct cpumask).
6314 * init_sched_build_groups will build a circular linked list of the groups
6315 * covered by the given span, and will set each group's ->cpumask correctly,
6316 * and ->cpu_power to 0.
6319 init_sched_build_groups(const struct cpumask *span,
6320 const struct cpumask *cpu_map,
6321 int (*group_fn)(int cpu, const struct cpumask *cpu_map,
6322 struct sched_group **sg,
6323 struct cpumask *tmpmask),
6324 struct cpumask *covered, struct cpumask *tmpmask)
6326 struct sched_group *first = NULL, *last = NULL;
6329 cpumask_clear(covered);
6331 for_each_cpu(i, span) {
6332 struct sched_group *sg;
6333 int group = group_fn(i, cpu_map, &sg, tmpmask);
6336 if (cpumask_test_cpu(i, covered))
6339 cpumask_clear(sched_group_cpus(sg));
6342 for_each_cpu(j, span) {
6343 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
6346 cpumask_set_cpu(j, covered);
6347 cpumask_set_cpu(j, sched_group_cpus(sg));
6358 #define SD_NODES_PER_DOMAIN 16
6363 * find_next_best_node - find the next node to include in a sched_domain
6364 * @node: node whose sched_domain we're building
6365 * @used_nodes: nodes already in the sched_domain
6367 * Find the next node to include in a given scheduling domain. Simply
6368 * finds the closest node not already in the @used_nodes map.
6370 * Should use nodemask_t.
6372 static int find_next_best_node(int node, nodemask_t *used_nodes)
6374 int i, n, val, min_val, best_node = 0;
6378 for (i = 0; i < nr_node_ids; i++) {
6379 /* Start at @node */
6380 n = (node + i) % nr_node_ids;
6382 if (!nr_cpus_node(n))
6385 /* Skip already used nodes */
6386 if (node_isset(n, *used_nodes))
6389 /* Simple min distance search */
6390 val = node_distance(node, n);
6392 if (val < min_val) {
6398 node_set(best_node, *used_nodes);
6403 * sched_domain_node_span - get a cpumask for a node's sched_domain
6404 * @node: node whose cpumask we're constructing
6405 * @span: resulting cpumask
6407 * Given a node, construct a good cpumask for its sched_domain to span. It
6408 * should be one that prevents unnecessary balancing, but also spreads tasks
6411 static void sched_domain_node_span(int node, struct cpumask *span)
6413 nodemask_t used_nodes;
6416 cpumask_clear(span);
6417 nodes_clear(used_nodes);
6419 cpumask_or(span, span, cpumask_of_node(node));
6420 node_set(node, used_nodes);
6422 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
6423 int next_node = find_next_best_node(node, &used_nodes);
6425 cpumask_or(span, span, cpumask_of_node(next_node));
6428 #endif /* CONFIG_NUMA */
6430 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6433 * The cpus mask in sched_group and sched_domain hangs off the end.
6435 * ( See the the comments in include/linux/sched.h:struct sched_group
6436 * and struct sched_domain. )
6438 struct static_sched_group {
6439 struct sched_group sg;
6440 DECLARE_BITMAP(cpus, CONFIG_NR_CPUS);
6443 struct static_sched_domain {
6444 struct sched_domain sd;
6445 DECLARE_BITMAP(span, CONFIG_NR_CPUS);
6451 cpumask_var_t domainspan;
6452 cpumask_var_t covered;
6453 cpumask_var_t notcovered;
6455 cpumask_var_t nodemask;
6456 cpumask_var_t this_sibling_map;
6457 cpumask_var_t this_core_map;
6458 cpumask_var_t this_book_map;
6459 cpumask_var_t send_covered;
6460 cpumask_var_t tmpmask;
6461 struct sched_group **sched_group_nodes;
6462 struct root_domain *rd;
6466 sa_sched_groups = 0,
6472 sa_this_sibling_map,
6474 sa_sched_group_nodes,
6484 * SMT sched-domains:
6486 #ifdef CONFIG_SCHED_SMT
6487 static DEFINE_PER_CPU(struct static_sched_domain, cpu_domains);
6488 static DEFINE_PER_CPU(struct static_sched_group, sched_groups);
6491 cpu_to_cpu_group(int cpu, const struct cpumask *cpu_map,
6492 struct sched_group **sg, struct cpumask *unused)
6495 *sg = &per_cpu(sched_groups, cpu).sg;
6498 #endif /* CONFIG_SCHED_SMT */
6501 * multi-core sched-domains:
6503 #ifdef CONFIG_SCHED_MC
6504 static DEFINE_PER_CPU(struct static_sched_domain, core_domains);
6505 static DEFINE_PER_CPU(struct static_sched_group, sched_group_core);
6508 cpu_to_core_group(int cpu, const struct cpumask *cpu_map,
6509 struct sched_group **sg, struct cpumask *mask)
6512 #ifdef CONFIG_SCHED_SMT
6513 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
6514 group = cpumask_first(mask);
6519 *sg = &per_cpu(sched_group_core, group).sg;
6522 #endif /* CONFIG_SCHED_MC */
6525 * book sched-domains:
6527 #ifdef CONFIG_SCHED_BOOK
6528 static DEFINE_PER_CPU(struct static_sched_domain, book_domains);
6529 static DEFINE_PER_CPU(struct static_sched_group, sched_group_book);
6532 cpu_to_book_group(int cpu, const struct cpumask *cpu_map,
6533 struct sched_group **sg, struct cpumask *mask)
6536 #ifdef CONFIG_SCHED_MC
6537 cpumask_and(mask, cpu_coregroup_mask(cpu), cpu_map);
6538 group = cpumask_first(mask);
6539 #elif defined(CONFIG_SCHED_SMT)
6540 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
6541 group = cpumask_first(mask);
6544 *sg = &per_cpu(sched_group_book, group).sg;
6547 #endif /* CONFIG_SCHED_BOOK */
6549 static DEFINE_PER_CPU(struct static_sched_domain, phys_domains);
6550 static DEFINE_PER_CPU(struct static_sched_group, sched_group_phys);
6553 cpu_to_phys_group(int cpu, const struct cpumask *cpu_map,
6554 struct sched_group **sg, struct cpumask *mask)
6557 #ifdef CONFIG_SCHED_BOOK
6558 cpumask_and(mask, cpu_book_mask(cpu), cpu_map);
6559 group = cpumask_first(mask);
6560 #elif defined(CONFIG_SCHED_MC)
6561 cpumask_and(mask, cpu_coregroup_mask(cpu), cpu_map);
6562 group = cpumask_first(mask);
6563 #elif defined(CONFIG_SCHED_SMT)
6564 cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
6565 group = cpumask_first(mask);
6570 *sg = &per_cpu(sched_group_phys, group).sg;
6576 * The init_sched_build_groups can't handle what we want to do with node
6577 * groups, so roll our own. Now each node has its own list of groups which
6578 * gets dynamically allocated.
6580 static DEFINE_PER_CPU(struct static_sched_domain, node_domains);
6581 static struct sched_group ***sched_group_nodes_bycpu;
6583 static DEFINE_PER_CPU(struct static_sched_domain, allnodes_domains);
6584 static DEFINE_PER_CPU(struct static_sched_group, sched_group_allnodes);
6586 static int cpu_to_allnodes_group(int cpu, const struct cpumask *cpu_map,
6587 struct sched_group **sg,
6588 struct cpumask *nodemask)
6592 cpumask_and(nodemask, cpumask_of_node(cpu_to_node(cpu)), cpu_map);
6593 group = cpumask_first(nodemask);
6596 *sg = &per_cpu(sched_group_allnodes, group).sg;
6600 static void init_numa_sched_groups_power(struct sched_group *group_head)
6602 struct sched_group *sg = group_head;
6608 for_each_cpu(j, sched_group_cpus(sg)) {
6609 struct sched_domain *sd;
6611 sd = &per_cpu(phys_domains, j).sd;
6612 if (j != group_first_cpu(sd->groups)) {
6614 * Only add "power" once for each
6620 sg->cpu_power += sd->groups->cpu_power;
6623 } while (sg != group_head);
6626 static int build_numa_sched_groups(struct s_data *d,
6627 const struct cpumask *cpu_map, int num)
6629 struct sched_domain *sd;
6630 struct sched_group *sg, *prev;
6633 cpumask_clear(d->covered);
6634 cpumask_and(d->nodemask, cpumask_of_node(num), cpu_map);
6635 if (cpumask_empty(d->nodemask)) {
6636 d->sched_group_nodes[num] = NULL;
6640 sched_domain_node_span(num, d->domainspan);
6641 cpumask_and(d->domainspan, d->domainspan, cpu_map);
6643 sg = kmalloc_node(sizeof(struct sched_group) + cpumask_size(),
6646 printk(KERN_WARNING "Can not alloc domain group for node %d\n",
6650 d->sched_group_nodes[num] = sg;
6652 for_each_cpu(j, d->nodemask) {
6653 sd = &per_cpu(node_domains, j).sd;
6658 cpumask_copy(sched_group_cpus(sg), d->nodemask);
6660 cpumask_or(d->covered, d->covered, d->nodemask);
6663 for (j = 0; j < nr_node_ids; j++) {
6664 n = (num + j) % nr_node_ids;
6665 cpumask_complement(d->notcovered, d->covered);
6666 cpumask_and(d->tmpmask, d->notcovered, cpu_map);
6667 cpumask_and(d->tmpmask, d->tmpmask, d->domainspan);
6668 if (cpumask_empty(d->tmpmask))
6670 cpumask_and(d->tmpmask, d->tmpmask, cpumask_of_node(n));
6671 if (cpumask_empty(d->tmpmask))
6673 sg = kmalloc_node(sizeof(struct sched_group) + cpumask_size(),
6677 "Can not alloc domain group for node %d\n", j);
6681 cpumask_copy(sched_group_cpus(sg), d->tmpmask);
6682 sg->next = prev->next;
6683 cpumask_or(d->covered, d->covered, d->tmpmask);
6690 #endif /* CONFIG_NUMA */
6693 /* Free memory allocated for various sched_group structures */
6694 static void free_sched_groups(const struct cpumask *cpu_map,
6695 struct cpumask *nodemask)
6699 for_each_cpu(cpu, cpu_map) {
6700 struct sched_group **sched_group_nodes
6701 = sched_group_nodes_bycpu[cpu];
6703 if (!sched_group_nodes)
6706 for (i = 0; i < nr_node_ids; i++) {
6707 struct sched_group *oldsg, *sg = sched_group_nodes[i];
6709 cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
6710 if (cpumask_empty(nodemask))
6720 if (oldsg != sched_group_nodes[i])
6723 kfree(sched_group_nodes);
6724 sched_group_nodes_bycpu[cpu] = NULL;
6727 #else /* !CONFIG_NUMA */
6728 static void free_sched_groups(const struct cpumask *cpu_map,
6729 struct cpumask *nodemask)
6732 #endif /* CONFIG_NUMA */
6735 * Initialize sched groups cpu_power.
6737 * cpu_power indicates the capacity of sched group, which is used while
6738 * distributing the load between different sched groups in a sched domain.
6739 * Typically cpu_power for all the groups in a sched domain will be same unless
6740 * there are asymmetries in the topology. If there are asymmetries, group
6741 * having more cpu_power will pickup more load compared to the group having
6744 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
6746 struct sched_domain *child;
6747 struct sched_group *group;
6751 WARN_ON(!sd || !sd->groups);
6753 if (cpu != group_first_cpu(sd->groups))
6756 sd->groups->group_weight = cpumask_weight(sched_group_cpus(sd->groups));
6760 sd->groups->cpu_power = 0;
6763 power = SCHED_LOAD_SCALE;
6764 weight = cpumask_weight(sched_domain_span(sd));
6766 * SMT siblings share the power of a single core.
6767 * Usually multiple threads get a better yield out of
6768 * that one core than a single thread would have,
6769 * reflect that in sd->smt_gain.
6771 if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
6772 power *= sd->smt_gain;
6774 power >>= SCHED_LOAD_SHIFT;
6776 sd->groups->cpu_power += power;
6781 * Add cpu_power of each child group to this groups cpu_power.
6783 group = child->groups;
6785 sd->groups->cpu_power += group->cpu_power;
6786 group = group->next;
6787 } while (group != child->groups);
6791 * Initializers for schedule domains
6792 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
6795 #ifdef CONFIG_SCHED_DEBUG
6796 # define SD_INIT_NAME(sd, type) sd->name = #type
6798 # define SD_INIT_NAME(sd, type) do { } while (0)
6801 #define SD_INIT(sd, type) sd_init_##type(sd)
6803 #define SD_INIT_FUNC(type) \
6804 static noinline void sd_init_##type(struct sched_domain *sd) \
6806 memset(sd, 0, sizeof(*sd)); \
6807 *sd = SD_##type##_INIT; \
6808 sd->level = SD_LV_##type; \
6809 SD_INIT_NAME(sd, type); \
6814 SD_INIT_FUNC(ALLNODES)
6817 #ifdef CONFIG_SCHED_SMT
6818 SD_INIT_FUNC(SIBLING)
6820 #ifdef CONFIG_SCHED_MC
6823 #ifdef CONFIG_SCHED_BOOK
6827 static int default_relax_domain_level = -1;
6829 static int __init setup_relax_domain_level(char *str)
6833 val = simple_strtoul(str, NULL, 0);
6834 if (val < SD_LV_MAX)
6835 default_relax_domain_level = val;
6839 __setup("relax_domain_level=", setup_relax_domain_level);
6841 static void set_domain_attribute(struct sched_domain *sd,
6842 struct sched_domain_attr *attr)
6846 if (!attr || attr->relax_domain_level < 0) {
6847 if (default_relax_domain_level < 0)
6850 request = default_relax_domain_level;
6852 request = attr->relax_domain_level;
6853 if (request < sd->level) {
6854 /* turn off idle balance on this domain */
6855 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6857 /* turn on idle balance on this domain */
6858 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6862 static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
6863 const struct cpumask *cpu_map)
6866 case sa_sched_groups:
6867 free_sched_groups(cpu_map, d->tmpmask); /* fall through */
6868 d->sched_group_nodes = NULL;
6870 free_rootdomain(d->rd); /* fall through */
6872 free_cpumask_var(d->tmpmask); /* fall through */
6873 case sa_send_covered:
6874 free_cpumask_var(d->send_covered); /* fall through */
6875 case sa_this_book_map:
6876 free_cpumask_var(d->this_book_map); /* fall through */
6877 case sa_this_core_map:
6878 free_cpumask_var(d->this_core_map); /* fall through */
6879 case sa_this_sibling_map:
6880 free_cpumask_var(d->this_sibling_map); /* fall through */
6882 free_cpumask_var(d->nodemask); /* fall through */
6883 case sa_sched_group_nodes:
6885 kfree(d->sched_group_nodes); /* fall through */
6887 free_cpumask_var(d->notcovered); /* fall through */
6889 free_cpumask_var(d->covered); /* fall through */
6891 free_cpumask_var(d->domainspan); /* fall through */
6898 static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
6899 const struct cpumask *cpu_map)
6902 if (!alloc_cpumask_var(&d->domainspan, GFP_KERNEL))
6904 if (!alloc_cpumask_var(&d->covered, GFP_KERNEL))
6905 return sa_domainspan;
6906 if (!alloc_cpumask_var(&d->notcovered, GFP_KERNEL))
6908 /* Allocate the per-node list of sched groups */
6909 d->sched_group_nodes = kcalloc(nr_node_ids,
6910 sizeof(struct sched_group *), GFP_KERNEL);
6911 if (!d->sched_group_nodes) {
6912 printk(KERN_WARNING "Can not alloc sched group node list\n");
6913 return sa_notcovered;
6915 sched_group_nodes_bycpu[cpumask_first(cpu_map)] = d->sched_group_nodes;
6917 if (!alloc_cpumask_var(&d->nodemask, GFP_KERNEL))
6918 return sa_sched_group_nodes;
6919 if (!alloc_cpumask_var(&d->this_sibling_map, GFP_KERNEL))
6921 if (!alloc_cpumask_var(&d->this_core_map, GFP_KERNEL))
6922 return sa_this_sibling_map;
6923 if (!alloc_cpumask_var(&d->this_book_map, GFP_KERNEL))
6924 return sa_this_core_map;
6925 if (!alloc_cpumask_var(&d->send_covered, GFP_KERNEL))
6926 return sa_this_book_map;
6927 if (!alloc_cpumask_var(&d->tmpmask, GFP_KERNEL))
6928 return sa_send_covered;
6929 d->rd = alloc_rootdomain();
6931 printk(KERN_WARNING "Cannot alloc root domain\n");
6934 return sa_rootdomain;
6937 static struct sched_domain *__build_numa_sched_domains(struct s_data *d,
6938 const struct cpumask *cpu_map, struct sched_domain_attr *attr, int i)
6940 struct sched_domain *sd = NULL;
6942 struct sched_domain *parent;
6945 if (cpumask_weight(cpu_map) >
6946 SD_NODES_PER_DOMAIN * cpumask_weight(d->nodemask)) {
6947 sd = &per_cpu(allnodes_domains, i).sd;
6948 SD_INIT(sd, ALLNODES);
6949 set_domain_attribute(sd, attr);
6950 cpumask_copy(sched_domain_span(sd), cpu_map);
6951 cpu_to_allnodes_group(i, cpu_map, &sd->groups, d->tmpmask);
6956 sd = &per_cpu(node_domains, i).sd;
6958 set_domain_attribute(sd, attr);
6959 sched_domain_node_span(cpu_to_node(i), sched_domain_span(sd));
6960 sd->parent = parent;
6963 cpumask_and(sched_domain_span(sd), sched_domain_span(sd), cpu_map);
6968 static struct sched_domain *__build_cpu_sched_domain(struct s_data *d,
6969 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
6970 struct sched_domain *parent, int i)
6972 struct sched_domain *sd;
6973 sd = &per_cpu(phys_domains, i).sd;
6975 set_domain_attribute(sd, attr);
6976 cpumask_copy(sched_domain_span(sd), d->nodemask);
6977 sd->parent = parent;
6980 cpu_to_phys_group(i, cpu_map, &sd->groups, d->tmpmask);
6984 static struct sched_domain *__build_book_sched_domain(struct s_data *d,
6985 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
6986 struct sched_domain *parent, int i)
6988 struct sched_domain *sd = parent;
6989 #ifdef CONFIG_SCHED_BOOK
6990 sd = &per_cpu(book_domains, i).sd;
6992 set_domain_attribute(sd, attr);
6993 cpumask_and(sched_domain_span(sd), cpu_map, cpu_book_mask(i));
6994 sd->parent = parent;
6996 cpu_to_book_group(i, cpu_map, &sd->groups, d->tmpmask);
7001 static struct sched_domain *__build_mc_sched_domain(struct s_data *d,
7002 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
7003 struct sched_domain *parent, int i)
7005 struct sched_domain *sd = parent;
7006 #ifdef CONFIG_SCHED_MC
7007 sd = &per_cpu(core_domains, i).sd;
7009 set_domain_attribute(sd, attr);
7010 cpumask_and(sched_domain_span(sd), cpu_map, cpu_coregroup_mask(i));
7011 sd->parent = parent;
7013 cpu_to_core_group(i, cpu_map, &sd->groups, d->tmpmask);
7018 static struct sched_domain *__build_smt_sched_domain(struct s_data *d,
7019 const struct cpumask *cpu_map, struct sched_domain_attr *attr,
7020 struct sched_domain *parent, int i)
7022 struct sched_domain *sd = parent;
7023 #ifdef CONFIG_SCHED_SMT
7024 sd = &per_cpu(cpu_domains, i).sd;
7025 SD_INIT(sd, SIBLING);
7026 set_domain_attribute(sd, attr);
7027 cpumask_and(sched_domain_span(sd), cpu_map, topology_thread_cpumask(i));
7028 sd->parent = parent;
7030 cpu_to_cpu_group(i, cpu_map, &sd->groups, d->tmpmask);
7035 static void build_sched_groups(struct s_data *d, enum sched_domain_level l,
7036 const struct cpumask *cpu_map, int cpu)
7039 #ifdef CONFIG_SCHED_SMT
7040 case SD_LV_SIBLING: /* set up CPU (sibling) groups */
7041 cpumask_and(d->this_sibling_map, cpu_map,
7042 topology_thread_cpumask(cpu));
7043 if (cpu == cpumask_first(d->this_sibling_map))
7044 init_sched_build_groups(d->this_sibling_map, cpu_map,
7046 d->send_covered, d->tmpmask);
7049 #ifdef CONFIG_SCHED_MC
7050 case SD_LV_MC: /* set up multi-core groups */
7051 cpumask_and(d->this_core_map, cpu_map, cpu_coregroup_mask(cpu));
7052 if (cpu == cpumask_first(d->this_core_map))
7053 init_sched_build_groups(d->this_core_map, cpu_map,
7055 d->send_covered, d->tmpmask);
7058 #ifdef CONFIG_SCHED_BOOK
7059 case SD_LV_BOOK: /* set up book groups */
7060 cpumask_and(d->this_book_map, cpu_map, cpu_book_mask(cpu));
7061 if (cpu == cpumask_first(d->this_book_map))
7062 init_sched_build_groups(d->this_book_map, cpu_map,
7064 d->send_covered, d->tmpmask);
7067 case SD_LV_CPU: /* set up physical groups */
7068 cpumask_and(d->nodemask, cpumask_of_node(cpu), cpu_map);
7069 if (!cpumask_empty(d->nodemask))
7070 init_sched_build_groups(d->nodemask, cpu_map,
7072 d->send_covered, d->tmpmask);
7075 case SD_LV_ALLNODES:
7076 init_sched_build_groups(cpu_map, cpu_map, &cpu_to_allnodes_group,
7077 d->send_covered, d->tmpmask);
7086 * Build sched domains for a given set of cpus and attach the sched domains
7087 * to the individual cpus
7089 static int __build_sched_domains(const struct cpumask *cpu_map,
7090 struct sched_domain_attr *attr)
7092 enum s_alloc alloc_state = sa_none;
7094 struct sched_domain *sd;
7100 alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
7101 if (alloc_state != sa_rootdomain)
7103 alloc_state = sa_sched_groups;
7106 * Set up domains for cpus specified by the cpu_map.
7108 for_each_cpu(i, cpu_map) {
7109 cpumask_and(d.nodemask, cpumask_of_node(cpu_to_node(i)),
7112 sd = __build_numa_sched_domains(&d, cpu_map, attr, i);
7113 sd = __build_cpu_sched_domain(&d, cpu_map, attr, sd, i);
7114 sd = __build_book_sched_domain(&d, cpu_map, attr, sd, i);
7115 sd = __build_mc_sched_domain(&d, cpu_map, attr, sd, i);
7116 sd = __build_smt_sched_domain(&d, cpu_map, attr, sd, i);
7119 for_each_cpu(i, cpu_map) {
7120 build_sched_groups(&d, SD_LV_SIBLING, cpu_map, i);
7121 build_sched_groups(&d, SD_LV_BOOK, cpu_map, i);
7122 build_sched_groups(&d, SD_LV_MC, cpu_map, i);
7125 /* Set up physical groups */
7126 for (i = 0; i < nr_node_ids; i++)
7127 build_sched_groups(&d, SD_LV_CPU, cpu_map, i);
7130 /* Set up node groups */
7132 build_sched_groups(&d, SD_LV_ALLNODES, cpu_map, 0);
7134 for (i = 0; i < nr_node_ids; i++)
7135 if (build_numa_sched_groups(&d, cpu_map, i))
7139 /* Calculate CPU power for physical packages and nodes */
7140 #ifdef CONFIG_SCHED_SMT
7141 for_each_cpu(i, cpu_map) {
7142 sd = &per_cpu(cpu_domains, i).sd;
7143 init_sched_groups_power(i, sd);
7146 #ifdef CONFIG_SCHED_MC
7147 for_each_cpu(i, cpu_map) {
7148 sd = &per_cpu(core_domains, i).sd;
7149 init_sched_groups_power(i, sd);
7152 #ifdef CONFIG_SCHED_BOOK
7153 for_each_cpu(i, cpu_map) {
7154 sd = &per_cpu(book_domains, i).sd;
7155 init_sched_groups_power(i, sd);
7159 for_each_cpu(i, cpu_map) {
7160 sd = &per_cpu(phys_domains, i).sd;
7161 init_sched_groups_power(i, sd);
7165 for (i = 0; i < nr_node_ids; i++)
7166 init_numa_sched_groups_power(d.sched_group_nodes[i]);
7168 if (d.sd_allnodes) {
7169 struct sched_group *sg;
7171 cpu_to_allnodes_group(cpumask_first(cpu_map), cpu_map, &sg,
7173 init_numa_sched_groups_power(sg);
7177 /* Attach the domains */
7178 for_each_cpu(i, cpu_map) {
7179 #ifdef CONFIG_SCHED_SMT
7180 sd = &per_cpu(cpu_domains, i).sd;
7181 #elif defined(CONFIG_SCHED_MC)
7182 sd = &per_cpu(core_domains, i).sd;
7183 #elif defined(CONFIG_SCHED_BOOK)
7184 sd = &per_cpu(book_domains, i).sd;
7186 sd = &per_cpu(phys_domains, i).sd;
7188 cpu_attach_domain(sd, d.rd, i);
7191 d.sched_group_nodes = NULL; /* don't free this we still need it */
7192 __free_domain_allocs(&d, sa_tmpmask, cpu_map);
7196 __free_domain_allocs(&d, alloc_state, cpu_map);
7200 static int build_sched_domains(const struct cpumask *cpu_map)
7202 return __build_sched_domains(cpu_map, NULL);
7205 static cpumask_var_t *doms_cur; /* current sched domains */
7206 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7207 static struct sched_domain_attr *dattr_cur;
7208 /* attribues of custom domains in 'doms_cur' */
7211 * Special case: If a kmalloc of a doms_cur partition (array of
7212 * cpumask) fails, then fallback to a single sched domain,
7213 * as determined by the single cpumask fallback_doms.
7215 static cpumask_var_t fallback_doms;
7218 * arch_update_cpu_topology lets virtualized architectures update the
7219 * cpu core maps. It is supposed to return 1 if the topology changed
7220 * or 0 if it stayed the same.
7222 int __attribute__((weak)) arch_update_cpu_topology(void)
7227 cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
7230 cpumask_var_t *doms;
7232 doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
7235 for (i = 0; i < ndoms; i++) {
7236 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
7237 free_sched_domains(doms, i);
7244 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
7247 for (i = 0; i < ndoms; i++)
7248 free_cpumask_var(doms[i]);
7253 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7254 * For now this just excludes isolated cpus, but could be used to
7255 * exclude other special cases in the future.
7257 static int arch_init_sched_domains(const struct cpumask *cpu_map)
7261 arch_update_cpu_topology();
7263 doms_cur = alloc_sched_domains(ndoms_cur);
7265 doms_cur = &fallback_doms;
7266 cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
7268 err = build_sched_domains(doms_cur[0]);
7269 register_sched_domain_sysctl();
7274 static void arch_destroy_sched_domains(const struct cpumask *cpu_map,
7275 struct cpumask *tmpmask)
7277 free_sched_groups(cpu_map, tmpmask);
7281 * Detach sched domains from a group of cpus specified in cpu_map
7282 * These cpus will now be attached to the NULL domain
7284 static void detach_destroy_domains(const struct cpumask *cpu_map)
7286 /* Save because hotplug lock held. */
7287 static DECLARE_BITMAP(tmpmask, CONFIG_NR_CPUS);
7290 for_each_cpu(i, cpu_map)
7291 cpu_attach_domain(NULL, &def_root_domain, i);
7292 synchronize_sched();
7293 arch_destroy_sched_domains(cpu_map, to_cpumask(tmpmask));
7296 /* handle null as "default" */
7297 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7298 struct sched_domain_attr *new, int idx_new)
7300 struct sched_domain_attr tmp;
7307 return !memcmp(cur ? (cur + idx_cur) : &tmp,
7308 new ? (new + idx_new) : &tmp,
7309 sizeof(struct sched_domain_attr));
7313 * Partition sched domains as specified by the 'ndoms_new'
7314 * cpumasks in the array doms_new[] of cpumasks. This compares
7315 * doms_new[] to the current sched domain partitioning, doms_cur[].
7316 * It destroys each deleted domain and builds each new domain.
7318 * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
7319 * The masks don't intersect (don't overlap.) We should setup one
7320 * sched domain for each mask. CPUs not in any of the cpumasks will
7321 * not be load balanced. If the same cpumask appears both in the
7322 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7325 * The passed in 'doms_new' should be allocated using
7326 * alloc_sched_domains. This routine takes ownership of it and will
7327 * free_sched_domains it when done with it. If the caller failed the
7328 * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
7329 * and partition_sched_domains() will fallback to the single partition
7330 * 'fallback_doms', it also forces the domains to be rebuilt.
7332 * If doms_new == NULL it will be replaced with cpu_online_mask.
7333 * ndoms_new == 0 is a special case for destroying existing domains,
7334 * and it will not create the default domain.
7336 * Call with hotplug lock held
7338 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
7339 struct sched_domain_attr *dattr_new)
7344 mutex_lock(&sched_domains_mutex);
7346 /* always unregister in case we don't destroy any domains */
7347 unregister_sched_domain_sysctl();
7349 /* Let architecture update cpu core mappings. */
7350 new_topology = arch_update_cpu_topology();
7352 n = doms_new ? ndoms_new : 0;
7354 /* Destroy deleted domains */
7355 for (i = 0; i < ndoms_cur; i++) {
7356 for (j = 0; j < n && !new_topology; j++) {
7357 if (cpumask_equal(doms_cur[i], doms_new[j])
7358 && dattrs_equal(dattr_cur, i, dattr_new, j))
7361 /* no match - a current sched domain not in new doms_new[] */
7362 detach_destroy_domains(doms_cur[i]);
7367 if (doms_new == NULL) {
7369 doms_new = &fallback_doms;
7370 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
7371 WARN_ON_ONCE(dattr_new);
7374 /* Build new domains */
7375 for (i = 0; i < ndoms_new; i++) {
7376 for (j = 0; j < ndoms_cur && !new_topology; j++) {
7377 if (cpumask_equal(doms_new[i], doms_cur[j])
7378 && dattrs_equal(dattr_new, i, dattr_cur, j))
7381 /* no match - add a new doms_new */
7382 __build_sched_domains(doms_new[i],
7383 dattr_new ? dattr_new + i : NULL);
7388 /* Remember the new sched domains */
7389 if (doms_cur != &fallback_doms)
7390 free_sched_domains(doms_cur, ndoms_cur);
7391 kfree(dattr_cur); /* kfree(NULL) is safe */
7392 doms_cur = doms_new;
7393 dattr_cur = dattr_new;
7394 ndoms_cur = ndoms_new;
7396 register_sched_domain_sysctl();
7398 mutex_unlock(&sched_domains_mutex);
7401 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7402 static void arch_reinit_sched_domains(void)
7406 /* Destroy domains first to force the rebuild */
7407 partition_sched_domains(0, NULL, NULL);
7409 rebuild_sched_domains();
7413 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7415 unsigned int level = 0;
7417 if (sscanf(buf, "%u", &level) != 1)
7421 * level is always be positive so don't check for
7422 * level < POWERSAVINGS_BALANCE_NONE which is 0
7423 * What happens on 0 or 1 byte write,
7424 * need to check for count as well?
7427 if (level >= MAX_POWERSAVINGS_BALANCE_LEVELS)
7431 sched_smt_power_savings = level;
7433 sched_mc_power_savings = level;
7435 arch_reinit_sched_domains();
7440 #ifdef CONFIG_SCHED_MC
7441 static ssize_t sched_mc_power_savings_show(struct sysdev_class *class,
7442 struct sysdev_class_attribute *attr,
7445 return sprintf(page, "%u\n", sched_mc_power_savings);
7447 static ssize_t sched_mc_power_savings_store(struct sysdev_class *class,
7448 struct sysdev_class_attribute *attr,
7449 const char *buf, size_t count)
7451 return sched_power_savings_store(buf, count, 0);
7453 static SYSDEV_CLASS_ATTR(sched_mc_power_savings, 0644,
7454 sched_mc_power_savings_show,
7455 sched_mc_power_savings_store);
7458 #ifdef CONFIG_SCHED_SMT
7459 static ssize_t sched_smt_power_savings_show(struct sysdev_class *dev,
7460 struct sysdev_class_attribute *attr,
7463 return sprintf(page, "%u\n", sched_smt_power_savings);
7465 static ssize_t sched_smt_power_savings_store(struct sysdev_class *dev,
7466 struct sysdev_class_attribute *attr,
7467 const char *buf, size_t count)
7469 return sched_power_savings_store(buf, count, 1);
7471 static SYSDEV_CLASS_ATTR(sched_smt_power_savings, 0644,
7472 sched_smt_power_savings_show,
7473 sched_smt_power_savings_store);
7476 int __init sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7480 #ifdef CONFIG_SCHED_SMT
7482 err = sysfs_create_file(&cls->kset.kobj,
7483 &attr_sched_smt_power_savings.attr);
7485 #ifdef CONFIG_SCHED_MC
7486 if (!err && mc_capable())
7487 err = sysfs_create_file(&cls->kset.kobj,
7488 &attr_sched_mc_power_savings.attr);
7492 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
7495 * Update cpusets according to cpu_active mask. If cpusets are
7496 * disabled, cpuset_update_active_cpus() becomes a simple wrapper
7497 * around partition_sched_domains().
7499 static int cpuset_cpu_active(struct notifier_block *nfb, unsigned long action,
7502 switch (action & ~CPU_TASKS_FROZEN) {
7504 case CPU_DOWN_FAILED:
7505 cpuset_update_active_cpus();
7512 static int cpuset_cpu_inactive(struct notifier_block *nfb, unsigned long action,
7515 switch (action & ~CPU_TASKS_FROZEN) {
7516 case CPU_DOWN_PREPARE:
7517 cpuset_update_active_cpus();
7524 static int update_runtime(struct notifier_block *nfb,
7525 unsigned long action, void *hcpu)
7527 int cpu = (int)(long)hcpu;
7530 case CPU_DOWN_PREPARE:
7531 case CPU_DOWN_PREPARE_FROZEN:
7532 disable_runtime(cpu_rq(cpu));
7535 case CPU_DOWN_FAILED:
7536 case CPU_DOWN_FAILED_FROZEN:
7538 case CPU_ONLINE_FROZEN:
7539 enable_runtime(cpu_rq(cpu));
7547 void __init sched_init_smp(void)
7549 cpumask_var_t non_isolated_cpus;
7551 alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
7552 alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
7554 #if defined(CONFIG_NUMA)
7555 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
7557 BUG_ON(sched_group_nodes_bycpu == NULL);
7560 mutex_lock(&sched_domains_mutex);
7561 arch_init_sched_domains(cpu_active_mask);
7562 cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
7563 if (cpumask_empty(non_isolated_cpus))
7564 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
7565 mutex_unlock(&sched_domains_mutex);
7568 hotcpu_notifier(cpuset_cpu_active, CPU_PRI_CPUSET_ACTIVE);
7569 hotcpu_notifier(cpuset_cpu_inactive, CPU_PRI_CPUSET_INACTIVE);
7571 /* RT runtime code needs to handle some hotplug events */
7572 hotcpu_notifier(update_runtime, 0);
7576 /* Move init over to a non-isolated CPU */
7577 if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
7579 sched_init_granularity();
7580 free_cpumask_var(non_isolated_cpus);
7582 init_sched_rt_class();
7585 void __init sched_init_smp(void)
7587 sched_init_granularity();
7589 #endif /* CONFIG_SMP */
7591 const_debug unsigned int sysctl_timer_migration = 1;
7593 int in_sched_functions(unsigned long addr)
7595 return in_lock_functions(addr) ||
7596 (addr >= (unsigned long)__sched_text_start
7597 && addr < (unsigned long)__sched_text_end);
7600 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
7602 cfs_rq->tasks_timeline = RB_ROOT;
7603 INIT_LIST_HEAD(&cfs_rq->tasks);
7604 #ifdef CONFIG_FAIR_GROUP_SCHED
7607 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7610 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
7612 struct rt_prio_array *array;
7615 array = &rt_rq->active;
7616 for (i = 0; i < MAX_RT_PRIO; i++) {
7617 INIT_LIST_HEAD(array->queue + i);
7618 __clear_bit(i, array->bitmap);
7620 /* delimiter for bitsearch: */
7621 __set_bit(MAX_RT_PRIO, array->bitmap);
7623 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
7624 rt_rq->highest_prio.curr = MAX_RT_PRIO;
7626 rt_rq->highest_prio.next = MAX_RT_PRIO;
7630 rt_rq->rt_nr_migratory = 0;
7631 rt_rq->overloaded = 0;
7632 plist_head_init_raw(&rt_rq->pushable_tasks, &rq->lock);
7636 rt_rq->rt_throttled = 0;
7637 rt_rq->rt_runtime = 0;
7638 raw_spin_lock_init(&rt_rq->rt_runtime_lock);
7640 #ifdef CONFIG_RT_GROUP_SCHED
7641 rt_rq->rt_nr_boosted = 0;
7646 #ifdef CONFIG_FAIR_GROUP_SCHED
7647 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
7648 struct sched_entity *se, int cpu,
7649 struct sched_entity *parent)
7651 struct rq *rq = cpu_rq(cpu);
7652 tg->cfs_rq[cpu] = cfs_rq;
7653 init_cfs_rq(cfs_rq, rq);
7657 /* se could be NULL for init_task_group */
7662 se->cfs_rq = &rq->cfs;
7664 se->cfs_rq = parent->my_q;
7667 update_load_set(&se->load, 0);
7668 se->parent = parent;
7672 #ifdef CONFIG_RT_GROUP_SCHED
7673 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
7674 struct sched_rt_entity *rt_se, int cpu,
7675 struct sched_rt_entity *parent)
7677 struct rq *rq = cpu_rq(cpu);
7679 tg->rt_rq[cpu] = rt_rq;
7680 init_rt_rq(rt_rq, rq);
7682 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
7684 tg->rt_se[cpu] = rt_se;
7689 rt_se->rt_rq = &rq->rt;
7691 rt_se->rt_rq = parent->my_q;
7693 rt_se->my_q = rt_rq;
7694 rt_se->parent = parent;
7695 INIT_LIST_HEAD(&rt_se->run_list);
7699 void __init sched_init(void)
7702 unsigned long alloc_size = 0, ptr;
7704 #ifdef CONFIG_FAIR_GROUP_SCHED
7705 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7707 #ifdef CONFIG_RT_GROUP_SCHED
7708 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7710 #ifdef CONFIG_CPUMASK_OFFSTACK
7711 alloc_size += num_possible_cpus() * cpumask_size();
7714 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
7716 #ifdef CONFIG_FAIR_GROUP_SCHED
7717 init_task_group.se = (struct sched_entity **)ptr;
7718 ptr += nr_cpu_ids * sizeof(void **);
7720 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
7721 ptr += nr_cpu_ids * sizeof(void **);
7723 #endif /* CONFIG_FAIR_GROUP_SCHED */
7724 #ifdef CONFIG_RT_GROUP_SCHED
7725 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
7726 ptr += nr_cpu_ids * sizeof(void **);
7728 init_task_group.rt_rq = (struct rt_rq **)ptr;
7729 ptr += nr_cpu_ids * sizeof(void **);
7731 #endif /* CONFIG_RT_GROUP_SCHED */
7732 #ifdef CONFIG_CPUMASK_OFFSTACK
7733 for_each_possible_cpu(i) {
7734 per_cpu(load_balance_tmpmask, i) = (void *)ptr;
7735 ptr += cpumask_size();
7737 #endif /* CONFIG_CPUMASK_OFFSTACK */
7741 init_defrootdomain();
7744 init_rt_bandwidth(&def_rt_bandwidth,
7745 global_rt_period(), global_rt_runtime());
7747 #ifdef CONFIG_RT_GROUP_SCHED
7748 init_rt_bandwidth(&init_task_group.rt_bandwidth,
7749 global_rt_period(), global_rt_runtime());
7750 #endif /* CONFIG_RT_GROUP_SCHED */
7752 #ifdef CONFIG_CGROUP_SCHED
7753 list_add(&init_task_group.list, &task_groups);
7754 INIT_LIST_HEAD(&init_task_group.children);
7756 #endif /* CONFIG_CGROUP_SCHED */
7758 for_each_possible_cpu(i) {
7762 raw_spin_lock_init(&rq->lock);
7764 rq->calc_load_active = 0;
7765 rq->calc_load_update = jiffies + LOAD_FREQ;
7766 init_cfs_rq(&rq->cfs, rq);
7767 init_rt_rq(&rq->rt, rq);
7768 #ifdef CONFIG_FAIR_GROUP_SCHED
7769 init_task_group.shares = init_task_group_load;
7770 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7771 #ifdef CONFIG_CGROUP_SCHED
7773 * How much cpu bandwidth does init_task_group get?
7775 * In case of task-groups formed thr' the cgroup filesystem, it
7776 * gets 100% of the cpu resources in the system. This overall
7777 * system cpu resource is divided among the tasks of
7778 * init_task_group and its child task-groups in a fair manner,
7779 * based on each entity's (task or task-group's) weight
7780 * (se->load.weight).
7782 * In other words, if init_task_group has 10 tasks of weight
7783 * 1024) and two child groups A0 and A1 (of weight 1024 each),
7784 * then A0's share of the cpu resource is:
7786 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
7788 * We achieve this by letting init_task_group's tasks sit
7789 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
7791 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, NULL);
7793 #endif /* CONFIG_FAIR_GROUP_SCHED */
7795 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
7796 #ifdef CONFIG_RT_GROUP_SCHED
7797 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
7798 #ifdef CONFIG_CGROUP_SCHED
7799 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, NULL);
7803 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7804 rq->cpu_load[j] = 0;
7806 rq->last_load_update_tick = jiffies;
7811 rq->cpu_power = SCHED_LOAD_SCALE;
7812 rq->post_schedule = 0;
7813 rq->active_balance = 0;
7814 rq->next_balance = jiffies;
7819 rq->avg_idle = 2*sysctl_sched_migration_cost;
7820 rq_attach_root(rq, &def_root_domain);
7822 rq->nohz_balance_kick = 0;
7823 init_sched_softirq_csd(&per_cpu(remote_sched_softirq_cb, i));
7827 atomic_set(&rq->nr_iowait, 0);
7830 set_load_weight(&init_task);
7832 #ifdef CONFIG_PREEMPT_NOTIFIERS
7833 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
7837 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
7840 #ifdef CONFIG_RT_MUTEXES
7841 plist_head_init_raw(&init_task.pi_waiters, &init_task.pi_lock);
7845 * The boot idle thread does lazy MMU switching as well:
7847 atomic_inc(&init_mm.mm_count);
7848 enter_lazy_tlb(&init_mm, current);
7851 * Make us the idle thread. Technically, schedule() should not be
7852 * called from this thread, however somewhere below it might be,
7853 * but because we are the idle thread, we just pick up running again
7854 * when this runqueue becomes "idle".
7856 init_idle(current, smp_processor_id());
7858 calc_load_update = jiffies + LOAD_FREQ;
7861 * During early bootup we pretend to be a normal task:
7863 current->sched_class = &fair_sched_class;
7865 /* Allocate the nohz_cpu_mask if CONFIG_CPUMASK_OFFSTACK */
7866 zalloc_cpumask_var(&nohz_cpu_mask, GFP_NOWAIT);
7869 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
7870 alloc_cpumask_var(&nohz.grp_idle_mask, GFP_NOWAIT);
7871 atomic_set(&nohz.load_balancer, nr_cpu_ids);
7872 atomic_set(&nohz.first_pick_cpu, nr_cpu_ids);
7873 atomic_set(&nohz.second_pick_cpu, nr_cpu_ids);
7875 /* May be allocated at isolcpus cmdline parse time */
7876 if (cpu_isolated_map == NULL)
7877 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
7882 scheduler_running = 1;
7885 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
7886 static inline int preempt_count_equals(int preempt_offset)
7888 int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth();
7890 return (nested == PREEMPT_INATOMIC_BASE + preempt_offset);
7893 void __might_sleep(const char *file, int line, int preempt_offset)
7896 static unsigned long prev_jiffy; /* ratelimiting */
7898 if ((preempt_count_equals(preempt_offset) && !irqs_disabled()) ||
7899 system_state != SYSTEM_RUNNING || oops_in_progress)
7901 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7903 prev_jiffy = jiffies;
7906 "BUG: sleeping function called from invalid context at %s:%d\n",
7909 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
7910 in_atomic(), irqs_disabled(),
7911 current->pid, current->comm);
7913 debug_show_held_locks(current);
7914 if (irqs_disabled())
7915 print_irqtrace_events(current);
7919 EXPORT_SYMBOL(__might_sleep);
7922 #ifdef CONFIG_MAGIC_SYSRQ
7923 static void normalize_task(struct rq *rq, struct task_struct *p)
7927 on_rq = p->se.on_rq;
7929 deactivate_task(rq, p, 0);
7930 __setscheduler(rq, p, SCHED_NORMAL, 0);
7932 activate_task(rq, p, 0);
7933 resched_task(rq->curr);
7937 void normalize_rt_tasks(void)
7939 struct task_struct *g, *p;
7940 unsigned long flags;
7943 read_lock_irqsave(&tasklist_lock, flags);
7944 do_each_thread(g, p) {
7946 * Only normalize user tasks:
7951 p->se.exec_start = 0;
7952 #ifdef CONFIG_SCHEDSTATS
7953 p->se.statistics.wait_start = 0;
7954 p->se.statistics.sleep_start = 0;
7955 p->se.statistics.block_start = 0;
7960 * Renice negative nice level userspace
7963 if (TASK_NICE(p) < 0 && p->mm)
7964 set_user_nice(p, 0);
7968 raw_spin_lock(&p->pi_lock);
7969 rq = __task_rq_lock(p);
7971 normalize_task(rq, p);
7973 __task_rq_unlock(rq);
7974 raw_spin_unlock(&p->pi_lock);
7975 } while_each_thread(g, p);
7977 read_unlock_irqrestore(&tasklist_lock, flags);
7980 #endif /* CONFIG_MAGIC_SYSRQ */
7982 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
7984 * These functions are only useful for the IA64 MCA handling, or kdb.
7986 * They can only be called when the whole system has been
7987 * stopped - every CPU needs to be quiescent, and no scheduling
7988 * activity can take place. Using them for anything else would
7989 * be a serious bug, and as a result, they aren't even visible
7990 * under any other configuration.
7994 * curr_task - return the current task for a given cpu.
7995 * @cpu: the processor in question.
7997 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7999 struct task_struct *curr_task(int cpu)
8001 return cpu_curr(cpu);
8004 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
8008 * set_curr_task - set the current task for a given cpu.
8009 * @cpu: the processor in question.
8010 * @p: the task pointer to set.
8012 * Description: This function must only be used when non-maskable interrupts
8013 * are serviced on a separate stack. It allows the architecture to switch the
8014 * notion of the current task on a cpu in a non-blocking manner. This function
8015 * must be called with all CPU's synchronized, and interrupts disabled, the
8016 * and caller must save the original value of the current task (see
8017 * curr_task() above) and restore that value before reenabling interrupts and
8018 * re-starting the system.
8020 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8022 void set_curr_task(int cpu, struct task_struct *p)
8029 #ifdef CONFIG_FAIR_GROUP_SCHED
8030 static void free_fair_sched_group(struct task_group *tg)
8034 for_each_possible_cpu(i) {
8036 kfree(tg->cfs_rq[i]);
8046 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8048 struct cfs_rq *cfs_rq;
8049 struct sched_entity *se;
8053 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
8056 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
8060 tg->shares = NICE_0_LOAD;
8062 for_each_possible_cpu(i) {
8065 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
8066 GFP_KERNEL, cpu_to_node(i));
8070 se = kzalloc_node(sizeof(struct sched_entity),
8071 GFP_KERNEL, cpu_to_node(i));
8075 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
8086 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8088 struct rq *rq = cpu_rq(cpu);
8089 unsigned long flags;
8093 * Only empty task groups can be destroyed; so we can speculatively
8094 * check on_list without danger of it being re-added.
8096 if (!tg->cfs_rq[cpu]->on_list)
8099 raw_spin_lock_irqsave(&rq->lock, flags);
8100 list_del_leaf_cfs_rq(tg->cfs_rq[i]);
8101 raw_spin_unlock_irqrestore(&rq->lock, flags);
8103 #else /* !CONFG_FAIR_GROUP_SCHED */
8104 static inline void free_fair_sched_group(struct task_group *tg)
8109 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8114 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8117 #endif /* CONFIG_FAIR_GROUP_SCHED */
8119 #ifdef CONFIG_RT_GROUP_SCHED
8120 static void free_rt_sched_group(struct task_group *tg)
8124 destroy_rt_bandwidth(&tg->rt_bandwidth);
8126 for_each_possible_cpu(i) {
8128 kfree(tg->rt_rq[i]);
8130 kfree(tg->rt_se[i]);
8138 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8140 struct rt_rq *rt_rq;
8141 struct sched_rt_entity *rt_se;
8145 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
8148 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
8152 init_rt_bandwidth(&tg->rt_bandwidth,
8153 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
8155 for_each_possible_cpu(i) {
8158 rt_rq = kzalloc_node(sizeof(struct rt_rq),
8159 GFP_KERNEL, cpu_to_node(i));
8163 rt_se = kzalloc_node(sizeof(struct sched_rt_entity),
8164 GFP_KERNEL, cpu_to_node(i));
8168 init_tg_rt_entry(tg, rt_rq, rt_se, i, parent->rt_se[i]);
8178 #else /* !CONFIG_RT_GROUP_SCHED */
8179 static inline void free_rt_sched_group(struct task_group *tg)
8184 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8188 #endif /* CONFIG_RT_GROUP_SCHED */
8190 #ifdef CONFIG_CGROUP_SCHED
8191 static void free_sched_group(struct task_group *tg)
8193 free_fair_sched_group(tg);
8194 free_rt_sched_group(tg);
8198 /* allocate runqueue etc for a new task group */
8199 struct task_group *sched_create_group(struct task_group *parent)
8201 struct task_group *tg;
8202 unsigned long flags;
8204 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
8206 return ERR_PTR(-ENOMEM);
8208 if (!alloc_fair_sched_group(tg, parent))
8211 if (!alloc_rt_sched_group(tg, parent))
8214 spin_lock_irqsave(&task_group_lock, flags);
8215 list_add_rcu(&tg->list, &task_groups);
8217 WARN_ON(!parent); /* root should already exist */
8219 tg->parent = parent;
8220 INIT_LIST_HEAD(&tg->children);
8221 list_add_rcu(&tg->siblings, &parent->children);
8222 spin_unlock_irqrestore(&task_group_lock, flags);
8227 free_sched_group(tg);
8228 return ERR_PTR(-ENOMEM);
8231 /* rcu callback to free various structures associated with a task group */
8232 static void free_sched_group_rcu(struct rcu_head *rhp)
8234 /* now it should be safe to free those cfs_rqs */
8235 free_sched_group(container_of(rhp, struct task_group, rcu));
8238 /* Destroy runqueue etc associated with a task group */
8239 void sched_destroy_group(struct task_group *tg)
8241 unsigned long flags;
8244 /* end participation in shares distribution */
8245 for_each_possible_cpu(i)
8246 unregister_fair_sched_group(tg, i);
8248 spin_lock_irqsave(&task_group_lock, flags);
8249 list_del_rcu(&tg->list);
8250 list_del_rcu(&tg->siblings);
8251 spin_unlock_irqrestore(&task_group_lock, flags);
8253 /* wait for possible concurrent references to cfs_rqs complete */
8254 call_rcu(&tg->rcu, free_sched_group_rcu);
8257 /* change task's runqueue when it moves between groups.
8258 * The caller of this function should have put the task in its new group
8259 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8260 * reflect its new group.
8262 void sched_move_task(struct task_struct *tsk)
8265 unsigned long flags;
8268 rq = task_rq_lock(tsk, &flags);
8270 running = task_current(rq, tsk);
8271 on_rq = tsk->se.on_rq;
8274 dequeue_task(rq, tsk, 0);
8275 if (unlikely(running))
8276 tsk->sched_class->put_prev_task(rq, tsk);
8278 #ifdef CONFIG_FAIR_GROUP_SCHED
8279 if (tsk->sched_class->task_move_group)
8280 tsk->sched_class->task_move_group(tsk, on_rq);
8283 set_task_rq(tsk, task_cpu(tsk));
8285 if (unlikely(running))
8286 tsk->sched_class->set_curr_task(rq);
8288 enqueue_task(rq, tsk, 0);
8290 task_rq_unlock(rq, &flags);
8292 #endif /* CONFIG_CGROUP_SCHED */
8294 #ifdef CONFIG_FAIR_GROUP_SCHED
8295 static DEFINE_MUTEX(shares_mutex);
8297 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8300 unsigned long flags;
8303 * We can't change the weight of the root cgroup.
8308 if (shares < MIN_SHARES)
8309 shares = MIN_SHARES;
8310 else if (shares > MAX_SHARES)
8311 shares = MAX_SHARES;
8313 mutex_lock(&shares_mutex);
8314 if (tg->shares == shares)
8317 tg->shares = shares;
8318 for_each_possible_cpu(i) {
8319 struct rq *rq = cpu_rq(i);
8320 struct sched_entity *se;
8323 /* Propagate contribution to hierarchy */
8324 raw_spin_lock_irqsave(&rq->lock, flags);
8325 for_each_sched_entity(se)
8326 update_cfs_shares(group_cfs_rq(se), 0);
8327 raw_spin_unlock_irqrestore(&rq->lock, flags);
8331 mutex_unlock(&shares_mutex);
8335 unsigned long sched_group_shares(struct task_group *tg)
8341 #ifdef CONFIG_RT_GROUP_SCHED
8343 * Ensure that the real time constraints are schedulable.
8345 static DEFINE_MUTEX(rt_constraints_mutex);
8347 static unsigned long to_ratio(u64 period, u64 runtime)
8349 if (runtime == RUNTIME_INF)
8352 return div64_u64(runtime << 20, period);
8355 /* Must be called with tasklist_lock held */
8356 static inline int tg_has_rt_tasks(struct task_group *tg)
8358 struct task_struct *g, *p;
8360 do_each_thread(g, p) {
8361 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
8363 } while_each_thread(g, p);
8368 struct rt_schedulable_data {
8369 struct task_group *tg;
8374 static int tg_schedulable(struct task_group *tg, void *data)
8376 struct rt_schedulable_data *d = data;
8377 struct task_group *child;
8378 unsigned long total, sum = 0;
8379 u64 period, runtime;
8381 period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8382 runtime = tg->rt_bandwidth.rt_runtime;
8385 period = d->rt_period;
8386 runtime = d->rt_runtime;
8390 * Cannot have more runtime than the period.
8392 if (runtime > period && runtime != RUNTIME_INF)
8396 * Ensure we don't starve existing RT tasks.
8398 if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
8401 total = to_ratio(period, runtime);
8404 * Nobody can have more than the global setting allows.
8406 if (total > to_ratio(global_rt_period(), global_rt_runtime()))
8410 * The sum of our children's runtime should not exceed our own.
8412 list_for_each_entry_rcu(child, &tg->children, siblings) {
8413 period = ktime_to_ns(child->rt_bandwidth.rt_period);
8414 runtime = child->rt_bandwidth.rt_runtime;
8416 if (child == d->tg) {
8417 period = d->rt_period;
8418 runtime = d->rt_runtime;
8421 sum += to_ratio(period, runtime);
8430 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8432 struct rt_schedulable_data data = {
8434 .rt_period = period,
8435 .rt_runtime = runtime,
8438 return walk_tg_tree(tg_schedulable, tg_nop, &data);
8441 static int tg_set_bandwidth(struct task_group *tg,
8442 u64 rt_period, u64 rt_runtime)
8446 mutex_lock(&rt_constraints_mutex);
8447 read_lock(&tasklist_lock);
8448 err = __rt_schedulable(tg, rt_period, rt_runtime);
8452 raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8453 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8454 tg->rt_bandwidth.rt_runtime = rt_runtime;
8456 for_each_possible_cpu(i) {
8457 struct rt_rq *rt_rq = tg->rt_rq[i];
8459 raw_spin_lock(&rt_rq->rt_runtime_lock);
8460 rt_rq->rt_runtime = rt_runtime;
8461 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8463 raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8465 read_unlock(&tasklist_lock);
8466 mutex_unlock(&rt_constraints_mutex);
8471 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8473 u64 rt_runtime, rt_period;
8475 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8476 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8477 if (rt_runtime_us < 0)
8478 rt_runtime = RUNTIME_INF;
8480 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8483 long sched_group_rt_runtime(struct task_group *tg)
8487 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8490 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8491 do_div(rt_runtime_us, NSEC_PER_USEC);
8492 return rt_runtime_us;
8495 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
8497 u64 rt_runtime, rt_period;
8499 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
8500 rt_runtime = tg->rt_bandwidth.rt_runtime;
8505 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8508 long sched_group_rt_period(struct task_group *tg)
8512 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8513 do_div(rt_period_us, NSEC_PER_USEC);
8514 return rt_period_us;
8517 static int sched_rt_global_constraints(void)
8519 u64 runtime, period;
8522 if (sysctl_sched_rt_period <= 0)
8525 runtime = global_rt_runtime();
8526 period = global_rt_period();
8529 * Sanity check on the sysctl variables.
8531 if (runtime > period && runtime != RUNTIME_INF)
8534 mutex_lock(&rt_constraints_mutex);
8535 read_lock(&tasklist_lock);
8536 ret = __rt_schedulable(NULL, 0, 0);
8537 read_unlock(&tasklist_lock);
8538 mutex_unlock(&rt_constraints_mutex);
8543 int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
8545 /* Don't accept realtime tasks when there is no way for them to run */
8546 if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
8552 #else /* !CONFIG_RT_GROUP_SCHED */
8553 static int sched_rt_global_constraints(void)
8555 unsigned long flags;
8558 if (sysctl_sched_rt_period <= 0)
8562 * There's always some RT tasks in the root group
8563 * -- migration, kstopmachine etc..
8565 if (sysctl_sched_rt_runtime == 0)
8568 raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
8569 for_each_possible_cpu(i) {
8570 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
8572 raw_spin_lock(&rt_rq->rt_runtime_lock);
8573 rt_rq->rt_runtime = global_rt_runtime();
8574 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8576 raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
8580 #endif /* CONFIG_RT_GROUP_SCHED */
8582 int sched_rt_handler(struct ctl_table *table, int write,
8583 void __user *buffer, size_t *lenp,
8587 int old_period, old_runtime;
8588 static DEFINE_MUTEX(mutex);
8591 old_period = sysctl_sched_rt_period;
8592 old_runtime = sysctl_sched_rt_runtime;
8594 ret = proc_dointvec(table, write, buffer, lenp, ppos);
8596 if (!ret && write) {
8597 ret = sched_rt_global_constraints();
8599 sysctl_sched_rt_period = old_period;
8600 sysctl_sched_rt_runtime = old_runtime;
8602 def_rt_bandwidth.rt_runtime = global_rt_runtime();
8603 def_rt_bandwidth.rt_period =
8604 ns_to_ktime(global_rt_period());
8607 mutex_unlock(&mutex);
8612 #ifdef CONFIG_CGROUP_SCHED
8614 /* return corresponding task_group object of a cgroup */
8615 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
8617 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
8618 struct task_group, css);
8621 static struct cgroup_subsys_state *
8622 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
8624 struct task_group *tg, *parent;
8626 if (!cgrp->parent) {
8627 /* This is early initialization for the top cgroup */
8628 return &init_task_group.css;
8631 parent = cgroup_tg(cgrp->parent);
8632 tg = sched_create_group(parent);
8634 return ERR_PTR(-ENOMEM);
8640 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
8642 struct task_group *tg = cgroup_tg(cgrp);
8644 sched_destroy_group(tg);
8648 cpu_cgroup_can_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
8650 #ifdef CONFIG_RT_GROUP_SCHED
8651 if (!sched_rt_can_attach(cgroup_tg(cgrp), tsk))
8654 /* We don't support RT-tasks being in separate groups */
8655 if (tsk->sched_class != &fair_sched_class)
8662 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8663 struct task_struct *tsk, bool threadgroup)
8665 int retval = cpu_cgroup_can_attach_task(cgrp, tsk);
8669 struct task_struct *c;
8671 list_for_each_entry_rcu(c, &tsk->thread_group, thread_group) {
8672 retval = cpu_cgroup_can_attach_task(cgrp, c);
8684 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8685 struct cgroup *old_cont, struct task_struct *tsk,
8688 sched_move_task(tsk);
8690 struct task_struct *c;
8692 list_for_each_entry_rcu(c, &tsk->thread_group, thread_group) {
8699 #ifdef CONFIG_FAIR_GROUP_SCHED
8700 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
8703 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
8706 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
8708 struct task_group *tg = cgroup_tg(cgrp);
8710 return (u64) tg->shares;
8712 #endif /* CONFIG_FAIR_GROUP_SCHED */
8714 #ifdef CONFIG_RT_GROUP_SCHED
8715 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
8718 return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
8721 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
8723 return sched_group_rt_runtime(cgroup_tg(cgrp));
8726 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
8729 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
8732 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
8734 return sched_group_rt_period(cgroup_tg(cgrp));
8736 #endif /* CONFIG_RT_GROUP_SCHED */
8738 static struct cftype cpu_files[] = {
8739 #ifdef CONFIG_FAIR_GROUP_SCHED
8742 .read_u64 = cpu_shares_read_u64,
8743 .write_u64 = cpu_shares_write_u64,
8746 #ifdef CONFIG_RT_GROUP_SCHED
8748 .name = "rt_runtime_us",
8749 .read_s64 = cpu_rt_runtime_read,
8750 .write_s64 = cpu_rt_runtime_write,
8753 .name = "rt_period_us",
8754 .read_u64 = cpu_rt_period_read_uint,
8755 .write_u64 = cpu_rt_period_write_uint,
8760 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
8762 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
8765 struct cgroup_subsys cpu_cgroup_subsys = {
8767 .create = cpu_cgroup_create,
8768 .destroy = cpu_cgroup_destroy,
8769 .can_attach = cpu_cgroup_can_attach,
8770 .attach = cpu_cgroup_attach,
8771 .populate = cpu_cgroup_populate,
8772 .subsys_id = cpu_cgroup_subsys_id,
8776 #endif /* CONFIG_CGROUP_SCHED */
8778 #ifdef CONFIG_CGROUP_CPUACCT
8781 * CPU accounting code for task groups.
8783 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
8784 * (balbir@in.ibm.com).
8787 /* track cpu usage of a group of tasks and its child groups */
8789 struct cgroup_subsys_state css;
8790 /* cpuusage holds pointer to a u64-type object on every cpu */
8791 u64 __percpu *cpuusage;
8792 struct percpu_counter cpustat[CPUACCT_STAT_NSTATS];
8793 struct cpuacct *parent;
8796 struct cgroup_subsys cpuacct_subsys;
8798 /* return cpu accounting group corresponding to this container */
8799 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
8801 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
8802 struct cpuacct, css);
8805 /* return cpu accounting group to which this task belongs */
8806 static inline struct cpuacct *task_ca(struct task_struct *tsk)
8808 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
8809 struct cpuacct, css);
8812 /* create a new cpu accounting group */
8813 static struct cgroup_subsys_state *cpuacct_create(
8814 struct cgroup_subsys *ss, struct cgroup *cgrp)
8816 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
8822 ca->cpuusage = alloc_percpu(u64);
8826 for (i = 0; i < CPUACCT_STAT_NSTATS; i++)
8827 if (percpu_counter_init(&ca->cpustat[i], 0))
8828 goto out_free_counters;
8831 ca->parent = cgroup_ca(cgrp->parent);
8837 percpu_counter_destroy(&ca->cpustat[i]);
8838 free_percpu(ca->cpuusage);
8842 return ERR_PTR(-ENOMEM);
8845 /* destroy an existing cpu accounting group */
8847 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
8849 struct cpuacct *ca = cgroup_ca(cgrp);
8852 for (i = 0; i < CPUACCT_STAT_NSTATS; i++)
8853 percpu_counter_destroy(&ca->cpustat[i]);
8854 free_percpu(ca->cpuusage);
8858 static u64 cpuacct_cpuusage_read(struct cpuacct *ca, int cpu)
8860 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
8863 #ifndef CONFIG_64BIT
8865 * Take rq->lock to make 64-bit read safe on 32-bit platforms.
8867 raw_spin_lock_irq(&cpu_rq(cpu)->lock);
8869 raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
8877 static void cpuacct_cpuusage_write(struct cpuacct *ca, int cpu, u64 val)
8879 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
8881 #ifndef CONFIG_64BIT
8883 * Take rq->lock to make 64-bit write safe on 32-bit platforms.
8885 raw_spin_lock_irq(&cpu_rq(cpu)->lock);
8887 raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
8893 /* return total cpu usage (in nanoseconds) of a group */
8894 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
8896 struct cpuacct *ca = cgroup_ca(cgrp);
8897 u64 totalcpuusage = 0;
8900 for_each_present_cpu(i)
8901 totalcpuusage += cpuacct_cpuusage_read(ca, i);
8903 return totalcpuusage;
8906 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
8909 struct cpuacct *ca = cgroup_ca(cgrp);
8918 for_each_present_cpu(i)
8919 cpuacct_cpuusage_write(ca, i, 0);
8925 static int cpuacct_percpu_seq_read(struct cgroup *cgroup, struct cftype *cft,
8928 struct cpuacct *ca = cgroup_ca(cgroup);
8932 for_each_present_cpu(i) {
8933 percpu = cpuacct_cpuusage_read(ca, i);
8934 seq_printf(m, "%llu ", (unsigned long long) percpu);
8936 seq_printf(m, "\n");
8940 static const char *cpuacct_stat_desc[] = {
8941 [CPUACCT_STAT_USER] = "user",
8942 [CPUACCT_STAT_SYSTEM] = "system",
8945 static int cpuacct_stats_show(struct cgroup *cgrp, struct cftype *cft,
8946 struct cgroup_map_cb *cb)
8948 struct cpuacct *ca = cgroup_ca(cgrp);
8951 for (i = 0; i < CPUACCT_STAT_NSTATS; i++) {
8952 s64 val = percpu_counter_read(&ca->cpustat[i]);
8953 val = cputime64_to_clock_t(val);
8954 cb->fill(cb, cpuacct_stat_desc[i], val);
8959 static struct cftype files[] = {
8962 .read_u64 = cpuusage_read,
8963 .write_u64 = cpuusage_write,
8966 .name = "usage_percpu",
8967 .read_seq_string = cpuacct_percpu_seq_read,
8971 .read_map = cpuacct_stats_show,
8975 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
8977 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
8981 * charge this task's execution time to its accounting group.
8983 * called with rq->lock held.
8985 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
8990 if (unlikely(!cpuacct_subsys.active))
8993 cpu = task_cpu(tsk);
8999 for (; ca; ca = ca->parent) {
9000 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
9001 *cpuusage += cputime;
9008 * When CONFIG_VIRT_CPU_ACCOUNTING is enabled one jiffy can be very large
9009 * in cputime_t units. As a result, cpuacct_update_stats calls
9010 * percpu_counter_add with values large enough to always overflow the
9011 * per cpu batch limit causing bad SMP scalability.
9013 * To fix this we scale percpu_counter_batch by cputime_one_jiffy so we
9014 * batch the same amount of time with CONFIG_VIRT_CPU_ACCOUNTING disabled
9015 * and enabled. We cap it at INT_MAX which is the largest allowed batch value.
9018 #define CPUACCT_BATCH \
9019 min_t(long, percpu_counter_batch * cputime_one_jiffy, INT_MAX)
9021 #define CPUACCT_BATCH 0
9025 * Charge the system/user time to the task's accounting group.
9027 static void cpuacct_update_stats(struct task_struct *tsk,
9028 enum cpuacct_stat_index idx, cputime_t val)
9031 int batch = CPUACCT_BATCH;
9033 if (unlikely(!cpuacct_subsys.active))
9040 __percpu_counter_add(&ca->cpustat[idx], val, batch);
9046 struct cgroup_subsys cpuacct_subsys = {
9048 .create = cpuacct_create,
9049 .destroy = cpuacct_destroy,
9050 .populate = cpuacct_populate,
9051 .subsys_id = cpuacct_subsys_id,
9053 #endif /* CONFIG_CGROUP_CPUACCT */
9057 void synchronize_sched_expedited(void)
9061 EXPORT_SYMBOL_GPL(synchronize_sched_expedited);
9063 #else /* #ifndef CONFIG_SMP */
9065 static atomic_t synchronize_sched_expedited_count = ATOMIC_INIT(0);
9067 static int synchronize_sched_expedited_cpu_stop(void *data)
9070 * There must be a full memory barrier on each affected CPU
9071 * between the time that try_stop_cpus() is called and the
9072 * time that it returns.
9074 * In the current initial implementation of cpu_stop, the
9075 * above condition is already met when the control reaches
9076 * this point and the following smp_mb() is not strictly
9077 * necessary. Do smp_mb() anyway for documentation and
9078 * robustness against future implementation changes.
9080 smp_mb(); /* See above comment block. */
9085 * Wait for an rcu-sched grace period to elapse, but use "big hammer"
9086 * approach to force grace period to end quickly. This consumes
9087 * significant time on all CPUs, and is thus not recommended for
9088 * any sort of common-case code.
9090 * Note that it is illegal to call this function while holding any
9091 * lock that is acquired by a CPU-hotplug notifier. Failing to
9092 * observe this restriction will result in deadlock.
9094 void synchronize_sched_expedited(void)
9096 int snap, trycount = 0;
9098 smp_mb(); /* ensure prior mod happens before capturing snap. */
9099 snap = atomic_read(&synchronize_sched_expedited_count) + 1;
9101 while (try_stop_cpus(cpu_online_mask,
9102 synchronize_sched_expedited_cpu_stop,
9105 if (trycount++ < 10)
9106 udelay(trycount * num_online_cpus());
9108 synchronize_sched();
9111 if (atomic_read(&synchronize_sched_expedited_count) - snap > 0) {
9112 smp_mb(); /* ensure test happens before caller kfree */
9117 atomic_inc(&synchronize_sched_expedited_count);
9118 smp_mb__after_atomic_inc(); /* ensure post-GP actions seen after GP. */
9121 EXPORT_SYMBOL_GPL(synchronize_sched_expedited);
9123 #endif /* #else #ifndef CONFIG_SMP */