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/security.h>
43 #include <linux/notifier.h>
44 #include <linux/profile.h>
45 #include <linux/freezer.h>
46 #include <linux/vmalloc.h>
47 #include <linux/blkdev.h>
48 #include <linux/delay.h>
49 #include <linux/pid_namespace.h>
50 #include <linux/smp.h>
51 #include <linux/threads.h>
52 #include <linux/timer.h>
53 #include <linux/rcupdate.h>
54 #include <linux/cpu.h>
55 #include <linux/cpuset.h>
56 #include <linux/percpu.h>
57 #include <linux/kthread.h>
58 #include <linux/seq_file.h>
59 #include <linux/sysctl.h>
60 #include <linux/syscalls.h>
61 #include <linux/times.h>
62 #include <linux/tsacct_kern.h>
63 #include <linux/kprobes.h>
64 #include <linux/delayacct.h>
65 #include <linux/reciprocal_div.h>
66 #include <linux/unistd.h>
67 #include <linux/pagemap.h>
68 #include <linux/hrtimer.h>
69 #include <linux/tick.h>
70 #include <linux/bootmem.h>
73 #include <asm/irq_regs.h>
76 * Scheduler clock - returns current time in nanosec units.
77 * This is default implementation.
78 * Architectures and sub-architectures can override this.
80 unsigned long long __attribute__((weak)) sched_clock(void)
82 return (unsigned long long)jiffies * (NSEC_PER_SEC / HZ);
86 * Convert user-nice values [ -20 ... 0 ... 19 ]
87 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
90 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
91 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
92 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
95 * 'User priority' is the nice value converted to something we
96 * can work with better when scaling various scheduler parameters,
97 * it's a [ 0 ... 39 ] range.
99 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
100 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
101 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
104 * Helpers for converting nanosecond timing to jiffy resolution
106 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
108 #define NICE_0_LOAD SCHED_LOAD_SCALE
109 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
112 * These are the 'tuning knobs' of the scheduler:
114 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
115 * Timeslices get refilled after they expire.
117 #define DEF_TIMESLICE (100 * HZ / 1000)
120 * single value that denotes runtime == period, ie unlimited time.
122 #define RUNTIME_INF ((u64)~0ULL)
126 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
127 * Since cpu_power is a 'constant', we can use a reciprocal divide.
129 static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
131 return reciprocal_divide(load, sg->reciprocal_cpu_power);
135 * Each time a sched group cpu_power is changed,
136 * we must compute its reciprocal value
138 static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
140 sg->__cpu_power += val;
141 sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
145 static inline int rt_policy(int policy)
147 if (unlikely(policy == SCHED_FIFO) || unlikely(policy == SCHED_RR))
152 static inline int task_has_rt_policy(struct task_struct *p)
154 return rt_policy(p->policy);
158 * This is the priority-queue data structure of the RT scheduling class:
160 struct rt_prio_array {
161 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
162 struct list_head queue[MAX_RT_PRIO];
165 struct rt_bandwidth {
166 /* nests inside the rq lock: */
167 spinlock_t rt_runtime_lock;
170 struct hrtimer rt_period_timer;
173 static struct rt_bandwidth def_rt_bandwidth;
175 static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
177 static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
179 struct rt_bandwidth *rt_b =
180 container_of(timer, struct rt_bandwidth, rt_period_timer);
186 now = hrtimer_cb_get_time(timer);
187 overrun = hrtimer_forward(timer, now, rt_b->rt_period);
192 idle = do_sched_rt_period_timer(rt_b, overrun);
195 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
199 void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
201 rt_b->rt_period = ns_to_ktime(period);
202 rt_b->rt_runtime = runtime;
204 spin_lock_init(&rt_b->rt_runtime_lock);
206 hrtimer_init(&rt_b->rt_period_timer,
207 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
208 rt_b->rt_period_timer.function = sched_rt_period_timer;
209 rt_b->rt_period_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
212 static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
216 if (rt_b->rt_runtime == RUNTIME_INF)
219 if (hrtimer_active(&rt_b->rt_period_timer))
222 spin_lock(&rt_b->rt_runtime_lock);
224 if (hrtimer_active(&rt_b->rt_period_timer))
227 now = hrtimer_cb_get_time(&rt_b->rt_period_timer);
228 hrtimer_forward(&rt_b->rt_period_timer, now, rt_b->rt_period);
229 hrtimer_start(&rt_b->rt_period_timer,
230 rt_b->rt_period_timer.expires,
233 spin_unlock(&rt_b->rt_runtime_lock);
236 #ifdef CONFIG_RT_GROUP_SCHED
237 static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
239 hrtimer_cancel(&rt_b->rt_period_timer);
243 #ifdef CONFIG_GROUP_SCHED
245 #include <linux/cgroup.h>
249 static LIST_HEAD(task_groups);
251 /* task group related information */
253 #ifdef CONFIG_CGROUP_SCHED
254 struct cgroup_subsys_state css;
257 #ifdef CONFIG_FAIR_GROUP_SCHED
258 /* schedulable entities of this group on each cpu */
259 struct sched_entity **se;
260 /* runqueue "owned" by this group on each cpu */
261 struct cfs_rq **cfs_rq;
262 unsigned long shares;
265 #ifdef CONFIG_RT_GROUP_SCHED
266 struct sched_rt_entity **rt_se;
267 struct rt_rq **rt_rq;
269 struct rt_bandwidth rt_bandwidth;
273 struct list_head list;
275 struct task_group *parent;
276 struct list_head siblings;
277 struct list_head children;
280 #ifdef CONFIG_USER_SCHED
284 * Every UID task group (including init_task_group aka UID-0) will
285 * be a child to this group.
287 struct task_group root_task_group;
289 #ifdef CONFIG_FAIR_GROUP_SCHED
290 /* Default task group's sched entity on each cpu */
291 static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
292 /* Default task group's cfs_rq on each cpu */
293 static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;
296 #ifdef CONFIG_RT_GROUP_SCHED
297 static DEFINE_PER_CPU(struct sched_rt_entity, init_sched_rt_entity);
298 static DEFINE_PER_CPU(struct rt_rq, init_rt_rq) ____cacheline_aligned_in_smp;
301 #define root_task_group init_task_group
304 /* task_group_lock serializes add/remove of task groups and also changes to
305 * a task group's cpu shares.
307 static DEFINE_SPINLOCK(task_group_lock);
309 /* doms_cur_mutex serializes access to doms_cur[] array */
310 static DEFINE_MUTEX(doms_cur_mutex);
312 #ifdef CONFIG_FAIR_GROUP_SCHED
313 #ifdef CONFIG_USER_SCHED
314 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
316 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
321 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
324 /* Default task group.
325 * Every task in system belong to this group at bootup.
327 struct task_group init_task_group;
329 /* return group to which a task belongs */
330 static inline struct task_group *task_group(struct task_struct *p)
332 struct task_group *tg;
334 #ifdef CONFIG_USER_SCHED
336 #elif defined(CONFIG_CGROUP_SCHED)
337 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
338 struct task_group, css);
340 tg = &init_task_group;
345 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
346 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
348 #ifdef CONFIG_FAIR_GROUP_SCHED
349 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
350 p->se.parent = task_group(p)->se[cpu];
353 #ifdef CONFIG_RT_GROUP_SCHED
354 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
355 p->rt.parent = task_group(p)->rt_se[cpu];
359 static inline void lock_doms_cur(void)
361 mutex_lock(&doms_cur_mutex);
364 static inline void unlock_doms_cur(void)
366 mutex_unlock(&doms_cur_mutex);
371 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
372 static inline void lock_doms_cur(void) { }
373 static inline void unlock_doms_cur(void) { }
375 #endif /* CONFIG_GROUP_SCHED */
377 /* CFS-related fields in a runqueue */
379 struct load_weight load;
380 unsigned long nr_running;
385 struct rb_root tasks_timeline;
386 struct rb_node *rb_leftmost;
388 struct list_head tasks;
389 struct list_head *balance_iterator;
392 * 'curr' points to currently running entity on this cfs_rq.
393 * It is set to NULL otherwise (i.e when none are currently running).
395 struct sched_entity *curr, *next;
397 unsigned long nr_spread_over;
399 #ifdef CONFIG_FAIR_GROUP_SCHED
400 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
403 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
404 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
405 * (like users, containers etc.)
407 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
408 * list is used during load balance.
410 struct list_head leaf_cfs_rq_list;
411 struct task_group *tg; /* group that "owns" this runqueue */
414 unsigned long task_weight;
415 unsigned long shares;
417 * We need space to build a sched_domain wide view of the full task
418 * group tree, in order to avoid depending on dynamic memory allocation
419 * during the load balancing we place this in the per cpu task group
420 * hierarchy. This limits the load balancing to one instance per cpu,
421 * but more should not be needed anyway.
423 struct aggregate_struct {
425 * load = weight(cpus) * f(tg)
427 * Where f(tg) is the recursive weight fraction assigned to
433 * part of the group weight distributed to this span.
435 unsigned long shares;
438 * The sum of all runqueue weights within this span.
440 unsigned long rq_weight;
443 * Weight contributed by tasks; this is the part we can
444 * influence by moving tasks around.
446 unsigned long task_weight;
452 /* Real-Time classes' related field in a runqueue: */
454 struct rt_prio_array active;
455 unsigned long rt_nr_running;
456 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
457 int highest_prio; /* highest queued rt task prio */
460 unsigned long rt_nr_migratory;
466 /* Nests inside the rq lock: */
467 spinlock_t rt_runtime_lock;
469 #ifdef CONFIG_RT_GROUP_SCHED
470 unsigned long rt_nr_boosted;
473 struct list_head leaf_rt_rq_list;
474 struct task_group *tg;
475 struct sched_rt_entity *rt_se;
482 * We add the notion of a root-domain which will be used to define per-domain
483 * variables. Each exclusive cpuset essentially defines an island domain by
484 * fully partitioning the member cpus from any other cpuset. Whenever a new
485 * exclusive cpuset is created, we also create and attach a new root-domain
495 * The "RT overload" flag: it gets set if a CPU has more than
496 * one runnable RT task.
503 * By default the system creates a single root-domain with all cpus as
504 * members (mimicking the global state we have today).
506 static struct root_domain def_root_domain;
511 * This is the main, per-CPU runqueue data structure.
513 * Locking rule: those places that want to lock multiple runqueues
514 * (such as the load balancing or the thread migration code), lock
515 * acquire operations must be ordered by ascending &runqueue.
522 * nr_running and cpu_load should be in the same cacheline because
523 * remote CPUs use both these fields when doing load calculation.
525 unsigned long nr_running;
526 #define CPU_LOAD_IDX_MAX 5
527 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
528 unsigned char idle_at_tick;
530 unsigned long last_tick_seen;
531 unsigned char in_nohz_recently;
533 /* capture load from *all* tasks on this cpu: */
534 struct load_weight load;
535 unsigned long nr_load_updates;
541 #ifdef CONFIG_FAIR_GROUP_SCHED
542 /* list of leaf cfs_rq on this cpu: */
543 struct list_head leaf_cfs_rq_list;
545 #ifdef CONFIG_RT_GROUP_SCHED
546 struct list_head leaf_rt_rq_list;
550 * This is part of a global counter where only the total sum
551 * over all CPUs matters. A task can increase this counter on
552 * one CPU and if it got migrated afterwards it may decrease
553 * it on another CPU. Always updated under the runqueue lock:
555 unsigned long nr_uninterruptible;
557 struct task_struct *curr, *idle;
558 unsigned long next_balance;
559 struct mm_struct *prev_mm;
561 u64 clock, prev_clock_raw;
564 unsigned int clock_warps, clock_overflows, clock_underflows;
566 unsigned int clock_deep_idle_events;
572 struct root_domain *rd;
573 struct sched_domain *sd;
575 /* For active balancing */
578 /* cpu of this runqueue: */
581 struct task_struct *migration_thread;
582 struct list_head migration_queue;
585 #ifdef CONFIG_SCHED_HRTICK
586 unsigned long hrtick_flags;
587 ktime_t hrtick_expire;
588 struct hrtimer hrtick_timer;
591 #ifdef CONFIG_SCHEDSTATS
593 struct sched_info rq_sched_info;
595 /* sys_sched_yield() stats */
596 unsigned int yld_exp_empty;
597 unsigned int yld_act_empty;
598 unsigned int yld_both_empty;
599 unsigned int yld_count;
601 /* schedule() stats */
602 unsigned int sched_switch;
603 unsigned int sched_count;
604 unsigned int sched_goidle;
606 /* try_to_wake_up() stats */
607 unsigned int ttwu_count;
608 unsigned int ttwu_local;
611 unsigned int bkl_count;
613 struct lock_class_key rq_lock_key;
616 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
618 static inline void check_preempt_curr(struct rq *rq, struct task_struct *p)
620 rq->curr->sched_class->check_preempt_curr(rq, p);
623 static inline int cpu_of(struct rq *rq)
633 static inline bool nohz_on(int cpu)
635 return tick_get_tick_sched(cpu)->nohz_mode != NOHZ_MODE_INACTIVE;
638 static inline u64 max_skipped_ticks(struct rq *rq)
640 return nohz_on(cpu_of(rq)) ? jiffies - rq->last_tick_seen + 2 : 1;
643 static inline void update_last_tick_seen(struct rq *rq)
645 rq->last_tick_seen = jiffies;
648 static inline u64 max_skipped_ticks(struct rq *rq)
653 static inline void update_last_tick_seen(struct rq *rq)
659 * Update the per-runqueue clock, as finegrained as the platform can give
660 * us, but without assuming monotonicity, etc.:
662 static void __update_rq_clock(struct rq *rq)
664 u64 prev_raw = rq->prev_clock_raw;
665 u64 now = sched_clock();
666 s64 delta = now - prev_raw;
667 u64 clock = rq->clock;
669 #ifdef CONFIG_SCHED_DEBUG
670 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
673 * Protect against sched_clock() occasionally going backwards:
675 if (unlikely(delta < 0)) {
680 * Catch too large forward jumps too:
682 u64 max_jump = max_skipped_ticks(rq) * TICK_NSEC;
683 u64 max_time = rq->tick_timestamp + max_jump;
685 if (unlikely(clock + delta > max_time)) {
686 if (clock < max_time)
690 rq->clock_overflows++;
692 if (unlikely(delta > rq->clock_max_delta))
693 rq->clock_max_delta = delta;
698 rq->prev_clock_raw = now;
702 static void update_rq_clock(struct rq *rq)
704 if (likely(smp_processor_id() == cpu_of(rq)))
705 __update_rq_clock(rq);
709 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
710 * See detach_destroy_domains: synchronize_sched for details.
712 * The domain tree of any CPU may only be accessed from within
713 * preempt-disabled sections.
715 #define for_each_domain(cpu, __sd) \
716 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
718 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
719 #define this_rq() (&__get_cpu_var(runqueues))
720 #define task_rq(p) cpu_rq(task_cpu(p))
721 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
724 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
726 #ifdef CONFIG_SCHED_DEBUG
727 # define const_debug __read_mostly
729 # define const_debug static const
733 * Debugging: various feature bits
736 SCHED_FEAT_NEW_FAIR_SLEEPERS = 1,
737 SCHED_FEAT_WAKEUP_PREEMPT = 2,
738 SCHED_FEAT_START_DEBIT = 4,
739 SCHED_FEAT_AFFINE_WAKEUPS = 8,
740 SCHED_FEAT_CACHE_HOT_BUDDY = 16,
741 SCHED_FEAT_SYNC_WAKEUPS = 32,
742 SCHED_FEAT_HRTICK = 64,
743 SCHED_FEAT_DOUBLE_TICK = 128,
744 SCHED_FEAT_NORMALIZED_SLEEPER = 256,
745 SCHED_FEAT_DEADLINE = 512,
748 const_debug unsigned int sysctl_sched_features =
749 SCHED_FEAT_NEW_FAIR_SLEEPERS * 1 |
750 SCHED_FEAT_WAKEUP_PREEMPT * 1 |
751 SCHED_FEAT_START_DEBIT * 1 |
752 SCHED_FEAT_AFFINE_WAKEUPS * 1 |
753 SCHED_FEAT_CACHE_HOT_BUDDY * 1 |
754 SCHED_FEAT_SYNC_WAKEUPS * 1 |
755 SCHED_FEAT_HRTICK * 1 |
756 SCHED_FEAT_DOUBLE_TICK * 0 |
757 SCHED_FEAT_NORMALIZED_SLEEPER * 1 |
758 SCHED_FEAT_DEADLINE * 1;
760 #define sched_feat(x) (sysctl_sched_features & SCHED_FEAT_##x)
763 * Number of tasks to iterate in a single balance run.
764 * Limited because this is done with IRQs disabled.
766 const_debug unsigned int sysctl_sched_nr_migrate = 32;
769 * period over which we measure -rt task cpu usage in us.
772 unsigned int sysctl_sched_rt_period = 1000000;
774 static __read_mostly int scheduler_running;
777 * part of the period that we allow rt tasks to run in us.
780 int sysctl_sched_rt_runtime = 950000;
782 static inline u64 global_rt_period(void)
784 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
787 static inline u64 global_rt_runtime(void)
789 if (sysctl_sched_rt_period < 0)
792 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
795 static const unsigned long long time_sync_thresh = 100000;
797 static DEFINE_PER_CPU(unsigned long long, time_offset);
798 static DEFINE_PER_CPU(unsigned long long, prev_cpu_time);
801 * Global lock which we take every now and then to synchronize
802 * the CPUs time. This method is not warp-safe, but it's good
803 * enough to synchronize slowly diverging time sources and thus
804 * it's good enough for tracing:
806 static DEFINE_SPINLOCK(time_sync_lock);
807 static unsigned long long prev_global_time;
809 static unsigned long long __sync_cpu_clock(cycles_t time, int cpu)
813 spin_lock_irqsave(&time_sync_lock, flags);
815 if (time < prev_global_time) {
816 per_cpu(time_offset, cpu) += prev_global_time - time;
817 time = prev_global_time;
819 prev_global_time = time;
822 spin_unlock_irqrestore(&time_sync_lock, flags);
827 static unsigned long long __cpu_clock(int cpu)
829 unsigned long long now;
834 * Only call sched_clock() if the scheduler has already been
835 * initialized (some code might call cpu_clock() very early):
837 if (unlikely(!scheduler_running))
840 local_irq_save(flags);
844 local_irq_restore(flags);
850 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
851 * clock constructed from sched_clock():
853 unsigned long long cpu_clock(int cpu)
855 unsigned long long prev_cpu_time, time, delta_time;
857 prev_cpu_time = per_cpu(prev_cpu_time, cpu);
858 time = __cpu_clock(cpu) + per_cpu(time_offset, cpu);
859 delta_time = time-prev_cpu_time;
861 if (unlikely(delta_time > time_sync_thresh))
862 time = __sync_cpu_clock(time, cpu);
866 EXPORT_SYMBOL_GPL(cpu_clock);
868 #ifndef prepare_arch_switch
869 # define prepare_arch_switch(next) do { } while (0)
871 #ifndef finish_arch_switch
872 # define finish_arch_switch(prev) do { } while (0)
875 static inline int task_current(struct rq *rq, struct task_struct *p)
877 return rq->curr == p;
880 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
881 static inline int task_running(struct rq *rq, struct task_struct *p)
883 return task_current(rq, p);
886 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
890 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
892 #ifdef CONFIG_DEBUG_SPINLOCK
893 /* this is a valid case when another task releases the spinlock */
894 rq->lock.owner = current;
897 * If we are tracking spinlock dependencies then we have to
898 * fix up the runqueue lock - which gets 'carried over' from
901 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
903 spin_unlock_irq(&rq->lock);
906 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
907 static inline int task_running(struct rq *rq, struct task_struct *p)
912 return task_current(rq, p);
916 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
920 * We can optimise this out completely for !SMP, because the
921 * SMP rebalancing from interrupt is the only thing that cares
926 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
927 spin_unlock_irq(&rq->lock);
929 spin_unlock(&rq->lock);
933 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
937 * After ->oncpu is cleared, the task can be moved to a different CPU.
938 * We must ensure this doesn't happen until the switch is completely
944 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
948 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
951 * __task_rq_lock - lock the runqueue a given task resides on.
952 * Must be called interrupts disabled.
954 static inline struct rq *__task_rq_lock(struct task_struct *p)
958 struct rq *rq = task_rq(p);
959 spin_lock(&rq->lock);
960 if (likely(rq == task_rq(p)))
962 spin_unlock(&rq->lock);
967 * task_rq_lock - lock the runqueue a given task resides on and disable
968 * interrupts. Note the ordering: we can safely lookup the task_rq without
969 * explicitly disabling preemption.
971 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
977 local_irq_save(*flags);
979 spin_lock(&rq->lock);
980 if (likely(rq == task_rq(p)))
982 spin_unlock_irqrestore(&rq->lock, *flags);
986 static void __task_rq_unlock(struct rq *rq)
989 spin_unlock(&rq->lock);
992 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
995 spin_unlock_irqrestore(&rq->lock, *flags);
999 * this_rq_lock - lock this runqueue and disable interrupts.
1001 static struct rq *this_rq_lock(void)
1002 __acquires(rq->lock)
1006 local_irq_disable();
1008 spin_lock(&rq->lock);
1014 * We are going deep-idle (irqs are disabled):
1016 void sched_clock_idle_sleep_event(void)
1018 struct rq *rq = cpu_rq(smp_processor_id());
1020 spin_lock(&rq->lock);
1021 __update_rq_clock(rq);
1022 spin_unlock(&rq->lock);
1023 rq->clock_deep_idle_events++;
1025 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
1028 * We just idled delta nanoseconds (called with irqs disabled):
1030 void sched_clock_idle_wakeup_event(u64 delta_ns)
1032 struct rq *rq = cpu_rq(smp_processor_id());
1033 u64 now = sched_clock();
1035 rq->idle_clock += delta_ns;
1037 * Override the previous timestamp and ignore all
1038 * sched_clock() deltas that occured while we idled,
1039 * and use the PM-provided delta_ns to advance the
1042 spin_lock(&rq->lock);
1043 rq->prev_clock_raw = now;
1044 rq->clock += delta_ns;
1045 spin_unlock(&rq->lock);
1046 touch_softlockup_watchdog();
1048 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
1050 static void __resched_task(struct task_struct *p, int tif_bit);
1052 static inline void resched_task(struct task_struct *p)
1054 __resched_task(p, TIF_NEED_RESCHED);
1057 #ifdef CONFIG_SCHED_HRTICK
1059 * Use HR-timers to deliver accurate preemption points.
1061 * Its all a bit involved since we cannot program an hrt while holding the
1062 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1065 * When we get rescheduled we reprogram the hrtick_timer outside of the
1068 static inline void resched_hrt(struct task_struct *p)
1070 __resched_task(p, TIF_HRTICK_RESCHED);
1073 static inline void resched_rq(struct rq *rq)
1075 unsigned long flags;
1077 spin_lock_irqsave(&rq->lock, flags);
1078 resched_task(rq->curr);
1079 spin_unlock_irqrestore(&rq->lock, flags);
1083 HRTICK_SET, /* re-programm hrtick_timer */
1084 HRTICK_RESET, /* not a new slice */
1089 * - enabled by features
1090 * - hrtimer is actually high res
1092 static inline int hrtick_enabled(struct rq *rq)
1094 if (!sched_feat(HRTICK))
1096 return hrtimer_is_hres_active(&rq->hrtick_timer);
1100 * Called to set the hrtick timer state.
1102 * called with rq->lock held and irqs disabled
1104 static void hrtick_start(struct rq *rq, u64 delay, int reset)
1106 assert_spin_locked(&rq->lock);
1109 * preempt at: now + delay
1112 ktime_add_ns(rq->hrtick_timer.base->get_time(), delay);
1114 * indicate we need to program the timer
1116 __set_bit(HRTICK_SET, &rq->hrtick_flags);
1118 __set_bit(HRTICK_RESET, &rq->hrtick_flags);
1121 * New slices are called from the schedule path and don't need a
1122 * forced reschedule.
1125 resched_hrt(rq->curr);
1128 static void hrtick_clear(struct rq *rq)
1130 if (hrtimer_active(&rq->hrtick_timer))
1131 hrtimer_cancel(&rq->hrtick_timer);
1135 * Update the timer from the possible pending state.
1137 static void hrtick_set(struct rq *rq)
1141 unsigned long flags;
1143 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1145 spin_lock_irqsave(&rq->lock, flags);
1146 set = __test_and_clear_bit(HRTICK_SET, &rq->hrtick_flags);
1147 reset = __test_and_clear_bit(HRTICK_RESET, &rq->hrtick_flags);
1148 time = rq->hrtick_expire;
1149 clear_thread_flag(TIF_HRTICK_RESCHED);
1150 spin_unlock_irqrestore(&rq->lock, flags);
1153 hrtimer_start(&rq->hrtick_timer, time, HRTIMER_MODE_ABS);
1154 if (reset && !hrtimer_active(&rq->hrtick_timer))
1161 * High-resolution timer tick.
1162 * Runs from hardirq context with interrupts disabled.
1164 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1166 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1168 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1170 spin_lock(&rq->lock);
1171 __update_rq_clock(rq);
1172 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1173 spin_unlock(&rq->lock);
1175 return HRTIMER_NORESTART;
1178 static inline void init_rq_hrtick(struct rq *rq)
1180 rq->hrtick_flags = 0;
1181 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1182 rq->hrtick_timer.function = hrtick;
1183 rq->hrtick_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
1186 void hrtick_resched(void)
1189 unsigned long flags;
1191 if (!test_thread_flag(TIF_HRTICK_RESCHED))
1194 local_irq_save(flags);
1195 rq = cpu_rq(smp_processor_id());
1197 local_irq_restore(flags);
1200 static inline void hrtick_clear(struct rq *rq)
1204 static inline void hrtick_set(struct rq *rq)
1208 static inline void init_rq_hrtick(struct rq *rq)
1212 void hrtick_resched(void)
1218 * resched_task - mark a task 'to be rescheduled now'.
1220 * On UP this means the setting of the need_resched flag, on SMP it
1221 * might also involve a cross-CPU call to trigger the scheduler on
1226 #ifndef tsk_is_polling
1227 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1230 static void __resched_task(struct task_struct *p, int tif_bit)
1234 assert_spin_locked(&task_rq(p)->lock);
1236 if (unlikely(test_tsk_thread_flag(p, tif_bit)))
1239 set_tsk_thread_flag(p, tif_bit);
1242 if (cpu == smp_processor_id())
1245 /* NEED_RESCHED must be visible before we test polling */
1247 if (!tsk_is_polling(p))
1248 smp_send_reschedule(cpu);
1251 static void resched_cpu(int cpu)
1253 struct rq *rq = cpu_rq(cpu);
1254 unsigned long flags;
1256 if (!spin_trylock_irqsave(&rq->lock, flags))
1258 resched_task(cpu_curr(cpu));
1259 spin_unlock_irqrestore(&rq->lock, flags);
1264 * When add_timer_on() enqueues a timer into the timer wheel of an
1265 * idle CPU then this timer might expire before the next timer event
1266 * which is scheduled to wake up that CPU. In case of a completely
1267 * idle system the next event might even be infinite time into the
1268 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1269 * leaves the inner idle loop so the newly added timer is taken into
1270 * account when the CPU goes back to idle and evaluates the timer
1271 * wheel for the next timer event.
1273 void wake_up_idle_cpu(int cpu)
1275 struct rq *rq = cpu_rq(cpu);
1277 if (cpu == smp_processor_id())
1281 * This is safe, as this function is called with the timer
1282 * wheel base lock of (cpu) held. When the CPU is on the way
1283 * to idle and has not yet set rq->curr to idle then it will
1284 * be serialized on the timer wheel base lock and take the new
1285 * timer into account automatically.
1287 if (rq->curr != rq->idle)
1291 * We can set TIF_RESCHED on the idle task of the other CPU
1292 * lockless. The worst case is that the other CPU runs the
1293 * idle task through an additional NOOP schedule()
1295 set_tsk_thread_flag(rq->idle, TIF_NEED_RESCHED);
1297 /* NEED_RESCHED must be visible before we test polling */
1299 if (!tsk_is_polling(rq->idle))
1300 smp_send_reschedule(cpu);
1305 static void __resched_task(struct task_struct *p, int tif_bit)
1307 assert_spin_locked(&task_rq(p)->lock);
1308 set_tsk_thread_flag(p, tif_bit);
1312 #if BITS_PER_LONG == 32
1313 # define WMULT_CONST (~0UL)
1315 # define WMULT_CONST (1UL << 32)
1318 #define WMULT_SHIFT 32
1321 * Shift right and round:
1323 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1326 * delta *= weight / lw
1328 static unsigned long
1329 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1330 struct load_weight *lw)
1334 if (unlikely(!lw->inv_weight))
1335 lw->inv_weight = (WMULT_CONST-lw->weight/2) / (lw->weight+1);
1337 tmp = (u64)delta_exec * weight;
1339 * Check whether we'd overflow the 64-bit multiplication:
1341 if (unlikely(tmp > WMULT_CONST))
1342 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1345 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1347 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1350 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1356 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1363 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1364 * of tasks with abnormal "nice" values across CPUs the contribution that
1365 * each task makes to its run queue's load is weighted according to its
1366 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1367 * scaled version of the new time slice allocation that they receive on time
1371 #define WEIGHT_IDLEPRIO 2
1372 #define WMULT_IDLEPRIO (1 << 31)
1375 * Nice levels are multiplicative, with a gentle 10% change for every
1376 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1377 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1378 * that remained on nice 0.
1380 * The "10% effect" is relative and cumulative: from _any_ nice level,
1381 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1382 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1383 * If a task goes up by ~10% and another task goes down by ~10% then
1384 * the relative distance between them is ~25%.)
1386 static const int prio_to_weight[40] = {
1387 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1388 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1389 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1390 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1391 /* 0 */ 1024, 820, 655, 526, 423,
1392 /* 5 */ 335, 272, 215, 172, 137,
1393 /* 10 */ 110, 87, 70, 56, 45,
1394 /* 15 */ 36, 29, 23, 18, 15,
1398 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1400 * In cases where the weight does not change often, we can use the
1401 * precalculated inverse to speed up arithmetics by turning divisions
1402 * into multiplications:
1404 static const u32 prio_to_wmult[40] = {
1405 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1406 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1407 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1408 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1409 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1410 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1411 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1412 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1415 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1418 * runqueue iterator, to support SMP load-balancing between different
1419 * scheduling classes, without having to expose their internal data
1420 * structures to the load-balancing proper:
1422 struct rq_iterator {
1424 struct task_struct *(*start)(void *);
1425 struct task_struct *(*next)(void *);
1429 static unsigned long
1430 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1431 unsigned long max_load_move, struct sched_domain *sd,
1432 enum cpu_idle_type idle, int *all_pinned,
1433 int *this_best_prio, struct rq_iterator *iterator);
1436 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1437 struct sched_domain *sd, enum cpu_idle_type idle,
1438 struct rq_iterator *iterator);
1441 #ifdef CONFIG_CGROUP_CPUACCT
1442 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1444 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1447 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1449 update_load_add(&rq->load, load);
1452 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1454 update_load_sub(&rq->load, load);
1458 static unsigned long source_load(int cpu, int type);
1459 static unsigned long target_load(int cpu, int type);
1460 static unsigned long cpu_avg_load_per_task(int cpu);
1461 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1463 #ifdef CONFIG_FAIR_GROUP_SCHED
1466 * Group load balancing.
1468 * We calculate a few balance domain wide aggregate numbers; load and weight.
1469 * Given the pictures below, and assuming each item has equal weight:
1480 * A and B get 1/3-rd of the total load. C and D get 1/3-rd of A's 1/3-rd,
1481 * which equals 1/9-th of the total load.
1484 * The weight of this group on the selected cpus.
1487 * Direct sum of all the cpu's their rq weight, e.g. A would get 3 while
1491 * Part of the rq_weight contributed by tasks; all groups except B would
1495 static inline struct aggregate_struct *
1496 aggregate(struct task_group *tg, struct sched_domain *sd)
1498 return &tg->cfs_rq[sd->first_cpu]->aggregate;
1501 typedef void (*aggregate_func)(struct task_group *, struct sched_domain *);
1504 * Iterate the full tree, calling @down when first entering a node and @up when
1505 * leaving it for the final time.
1508 void aggregate_walk_tree(aggregate_func down, aggregate_func up,
1509 struct sched_domain *sd)
1511 struct task_group *parent, *child;
1514 parent = &root_task_group;
1516 (*down)(parent, sd);
1517 list_for_each_entry_rcu(child, &parent->children, siblings) {
1527 parent = parent->parent;
1534 * Calculate the aggregate runqueue weight.
1537 void aggregate_group_weight(struct task_group *tg, struct sched_domain *sd)
1539 unsigned long rq_weight = 0;
1540 unsigned long task_weight = 0;
1543 for_each_cpu_mask(i, sd->span) {
1544 rq_weight += tg->cfs_rq[i]->load.weight;
1545 task_weight += tg->cfs_rq[i]->task_weight;
1548 aggregate(tg, sd)->rq_weight = rq_weight;
1549 aggregate(tg, sd)->task_weight = task_weight;
1553 * Redistribute tg->shares amongst all tg->cfs_rq[]s.
1555 static void __aggregate_redistribute_shares(struct task_group *tg)
1557 int i, max_cpu = smp_processor_id();
1558 unsigned long rq_weight = 0;
1559 unsigned long shares, max_shares = 0, shares_rem = tg->shares;
1561 for_each_possible_cpu(i)
1562 rq_weight += tg->cfs_rq[i]->load.weight;
1564 for_each_possible_cpu(i) {
1566 * divide shares proportional to the rq_weights.
1568 shares = tg->shares * tg->cfs_rq[i]->load.weight;
1569 shares /= rq_weight + 1;
1571 tg->cfs_rq[i]->shares = shares;
1573 if (shares > max_shares) {
1574 max_shares = shares;
1577 shares_rem -= shares;
1581 * Ensure it all adds up to tg->shares; we can loose a few
1582 * due to rounding down when computing the per-cpu shares.
1585 tg->cfs_rq[max_cpu]->shares += shares_rem;
1589 * Compute the weight of this group on the given cpus.
1592 void aggregate_group_shares(struct task_group *tg, struct sched_domain *sd)
1594 unsigned long shares = 0;
1598 for_each_cpu_mask(i, sd->span)
1599 shares += tg->cfs_rq[i]->shares;
1602 * When the span doesn't have any shares assigned, but does have
1603 * tasks to run do a machine wide rebalance (should be rare).
1605 if (unlikely(!shares && aggregate(tg, sd)->rq_weight)) {
1606 __aggregate_redistribute_shares(tg);
1610 aggregate(tg, sd)->shares = shares;
1614 * Compute the load fraction assigned to this group, relies on the aggregate
1615 * weight and this group's parent's load, i.e. top-down.
1618 void aggregate_group_load(struct task_group *tg, struct sched_domain *sd)
1626 for_each_cpu_mask(i, sd->span)
1627 load += cpu_rq(i)->load.weight;
1630 load = aggregate(tg->parent, sd)->load;
1633 * shares is our weight in the parent's rq so
1634 * shares/parent->rq_weight gives our fraction of the load
1636 load *= aggregate(tg, sd)->shares;
1637 load /= aggregate(tg->parent, sd)->rq_weight + 1;
1640 aggregate(tg, sd)->load = load;
1643 static void __set_se_shares(struct sched_entity *se, unsigned long shares);
1646 * Calculate and set the cpu's group shares.
1649 __update_group_shares_cpu(struct task_group *tg, struct sched_domain *sd,
1653 unsigned long shares;
1654 unsigned long rq_weight;
1659 rq_weight = tg->cfs_rq[tcpu]->load.weight;
1662 * If there are currently no tasks on the cpu pretend there is one of
1663 * average load so that when a new task gets to run here it will not
1664 * get delayed by group starvation.
1668 rq_weight = NICE_0_LOAD;
1672 * \Sum shares * rq_weight
1673 * shares = -----------------------
1677 shares = aggregate(tg, sd)->shares * rq_weight;
1678 shares /= aggregate(tg, sd)->rq_weight + 1;
1681 * record the actual number of shares, not the boosted amount.
1683 tg->cfs_rq[tcpu]->shares = boost ? 0 : shares;
1685 if (shares < MIN_SHARES)
1686 shares = MIN_SHARES;
1688 __set_se_shares(tg->se[tcpu], shares);
1692 * Re-adjust the weights on the cpu the task came from and on the cpu the
1696 __move_group_shares(struct task_group *tg, struct sched_domain *sd,
1699 unsigned long shares;
1701 shares = tg->cfs_rq[scpu]->shares + tg->cfs_rq[dcpu]->shares;
1703 __update_group_shares_cpu(tg, sd, scpu);
1704 __update_group_shares_cpu(tg, sd, dcpu);
1707 * ensure we never loose shares due to rounding errors in the
1708 * above redistribution.
1710 shares -= tg->cfs_rq[scpu]->shares + tg->cfs_rq[dcpu]->shares;
1712 tg->cfs_rq[dcpu]->shares += shares;
1716 * Because changing a group's shares changes the weight of the super-group
1717 * we need to walk up the tree and change all shares until we hit the root.
1720 move_group_shares(struct task_group *tg, struct sched_domain *sd,
1724 __move_group_shares(tg, sd, scpu, dcpu);
1730 void aggregate_group_set_shares(struct task_group *tg, struct sched_domain *sd)
1732 unsigned long shares = aggregate(tg, sd)->shares;
1735 for_each_cpu_mask(i, sd->span) {
1736 struct rq *rq = cpu_rq(i);
1737 unsigned long flags;
1739 spin_lock_irqsave(&rq->lock, flags);
1740 __update_group_shares_cpu(tg, sd, i);
1741 spin_unlock_irqrestore(&rq->lock, flags);
1744 aggregate_group_shares(tg, sd);
1747 * ensure we never loose shares due to rounding errors in the
1748 * above redistribution.
1750 shares -= aggregate(tg, sd)->shares;
1752 tg->cfs_rq[sd->first_cpu]->shares += shares;
1753 aggregate(tg, sd)->shares += shares;
1758 * Calculate the accumulative weight and recursive load of each task group
1759 * while walking down the tree.
1762 void aggregate_get_down(struct task_group *tg, struct sched_domain *sd)
1764 aggregate_group_weight(tg, sd);
1765 aggregate_group_shares(tg, sd);
1766 aggregate_group_load(tg, sd);
1770 * Rebalance the cpu shares while walking back up the tree.
1773 void aggregate_get_up(struct task_group *tg, struct sched_domain *sd)
1775 aggregate_group_set_shares(tg, sd);
1778 static DEFINE_PER_CPU(spinlock_t, aggregate_lock);
1780 static void __init init_aggregate(void)
1784 for_each_possible_cpu(i)
1785 spin_lock_init(&per_cpu(aggregate_lock, i));
1788 static int get_aggregate(struct sched_domain *sd)
1790 if (!spin_trylock(&per_cpu(aggregate_lock, sd->first_cpu)))
1793 aggregate_walk_tree(aggregate_get_down, aggregate_get_up, sd);
1797 static void put_aggregate(struct sched_domain *sd)
1799 spin_unlock(&per_cpu(aggregate_lock, sd->first_cpu));
1802 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1804 cfs_rq->shares = shares;
1809 static inline void init_aggregate(void)
1813 static inline int get_aggregate(struct sched_domain *sd)
1818 static inline void put_aggregate(struct sched_domain *sd)
1823 #else /* CONFIG_SMP */
1825 #ifdef CONFIG_FAIR_GROUP_SCHED
1826 static void cfs_rq_set_shares(struct cfs_rq *cfs_rq, unsigned long shares)
1831 #endif /* CONFIG_SMP */
1833 #include "sched_stats.h"
1834 #include "sched_idletask.c"
1835 #include "sched_fair.c"
1836 #include "sched_rt.c"
1837 #ifdef CONFIG_SCHED_DEBUG
1838 # include "sched_debug.c"
1841 #define sched_class_highest (&rt_sched_class)
1843 static void inc_nr_running(struct rq *rq)
1848 static void dec_nr_running(struct rq *rq)
1853 static void set_load_weight(struct task_struct *p)
1855 if (task_has_rt_policy(p)) {
1856 p->se.load.weight = prio_to_weight[0] * 2;
1857 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1862 * SCHED_IDLE tasks get minimal weight:
1864 if (p->policy == SCHED_IDLE) {
1865 p->se.load.weight = WEIGHT_IDLEPRIO;
1866 p->se.load.inv_weight = WMULT_IDLEPRIO;
1870 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1871 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1874 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1876 sched_info_queued(p);
1877 p->sched_class->enqueue_task(rq, p, wakeup);
1881 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1883 p->sched_class->dequeue_task(rq, p, sleep);
1888 * __normal_prio - return the priority that is based on the static prio
1890 static inline int __normal_prio(struct task_struct *p)
1892 return p->static_prio;
1896 * Calculate the expected normal priority: i.e. priority
1897 * without taking RT-inheritance into account. Might be
1898 * boosted by interactivity modifiers. Changes upon fork,
1899 * setprio syscalls, and whenever the interactivity
1900 * estimator recalculates.
1902 static inline int normal_prio(struct task_struct *p)
1906 if (task_has_rt_policy(p))
1907 prio = MAX_RT_PRIO-1 - p->rt_priority;
1909 prio = __normal_prio(p);
1914 * Calculate the current priority, i.e. the priority
1915 * taken into account by the scheduler. This value might
1916 * be boosted by RT tasks, or might be boosted by
1917 * interactivity modifiers. Will be RT if the task got
1918 * RT-boosted. If not then it returns p->normal_prio.
1920 static int effective_prio(struct task_struct *p)
1922 p->normal_prio = normal_prio(p);
1924 * If we are RT tasks or we were boosted to RT priority,
1925 * keep the priority unchanged. Otherwise, update priority
1926 * to the normal priority:
1928 if (!rt_prio(p->prio))
1929 return p->normal_prio;
1934 * activate_task - move a task to the runqueue.
1936 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1938 if (task_contributes_to_load(p))
1939 rq->nr_uninterruptible--;
1941 enqueue_task(rq, p, wakeup);
1946 * deactivate_task - remove a task from the runqueue.
1948 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1950 if (task_contributes_to_load(p))
1951 rq->nr_uninterruptible++;
1953 dequeue_task(rq, p, sleep);
1958 * task_curr - is this task currently executing on a CPU?
1959 * @p: the task in question.
1961 inline int task_curr(const struct task_struct *p)
1963 return cpu_curr(task_cpu(p)) == p;
1966 /* Used instead of source_load when we know the type == 0 */
1967 unsigned long weighted_cpuload(const int cpu)
1969 return cpu_rq(cpu)->load.weight;
1972 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1974 set_task_rq(p, cpu);
1977 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1978 * successfuly executed on another CPU. We must ensure that updates of
1979 * per-task data have been completed by this moment.
1982 task_thread_info(p)->cpu = cpu;
1986 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1987 const struct sched_class *prev_class,
1988 int oldprio, int running)
1990 if (prev_class != p->sched_class) {
1991 if (prev_class->switched_from)
1992 prev_class->switched_from(rq, p, running);
1993 p->sched_class->switched_to(rq, p, running);
1995 p->sched_class->prio_changed(rq, p, oldprio, running);
2001 * Is this task likely cache-hot:
2004 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
2009 * Buddy candidates are cache hot:
2011 if (sched_feat(CACHE_HOT_BUDDY) && (&p->se == cfs_rq_of(&p->se)->next))
2014 if (p->sched_class != &fair_sched_class)
2017 if (sysctl_sched_migration_cost == -1)
2019 if (sysctl_sched_migration_cost == 0)
2022 delta = now - p->se.exec_start;
2024 return delta < (s64)sysctl_sched_migration_cost;
2028 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
2030 int old_cpu = task_cpu(p);
2031 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
2032 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
2033 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
2036 clock_offset = old_rq->clock - new_rq->clock;
2038 #ifdef CONFIG_SCHEDSTATS
2039 if (p->se.wait_start)
2040 p->se.wait_start -= clock_offset;
2041 if (p->se.sleep_start)
2042 p->se.sleep_start -= clock_offset;
2043 if (p->se.block_start)
2044 p->se.block_start -= clock_offset;
2045 if (old_cpu != new_cpu) {
2046 schedstat_inc(p, se.nr_migrations);
2047 if (task_hot(p, old_rq->clock, NULL))
2048 schedstat_inc(p, se.nr_forced2_migrations);
2051 p->se.vruntime -= old_cfsrq->min_vruntime -
2052 new_cfsrq->min_vruntime;
2054 __set_task_cpu(p, new_cpu);
2057 struct migration_req {
2058 struct list_head list;
2060 struct task_struct *task;
2063 struct completion done;
2067 * The task's runqueue lock must be held.
2068 * Returns true if you have to wait for migration thread.
2071 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
2073 struct rq *rq = task_rq(p);
2076 * If the task is not on a runqueue (and not running), then
2077 * it is sufficient to simply update the task's cpu field.
2079 if (!p->se.on_rq && !task_running(rq, p)) {
2080 set_task_cpu(p, dest_cpu);
2084 init_completion(&req->done);
2086 req->dest_cpu = dest_cpu;
2087 list_add(&req->list, &rq->migration_queue);
2093 * wait_task_inactive - wait for a thread to unschedule.
2095 * The caller must ensure that the task *will* unschedule sometime soon,
2096 * else this function might spin for a *long* time. This function can't
2097 * be called with interrupts off, or it may introduce deadlock with
2098 * smp_call_function() if an IPI is sent by the same process we are
2099 * waiting to become inactive.
2101 void wait_task_inactive(struct task_struct *p)
2103 unsigned long flags;
2109 * We do the initial early heuristics without holding
2110 * any task-queue locks at all. We'll only try to get
2111 * the runqueue lock when things look like they will
2117 * If the task is actively running on another CPU
2118 * still, just relax and busy-wait without holding
2121 * NOTE! Since we don't hold any locks, it's not
2122 * even sure that "rq" stays as the right runqueue!
2123 * But we don't care, since "task_running()" will
2124 * return false if the runqueue has changed and p
2125 * is actually now running somewhere else!
2127 while (task_running(rq, p))
2131 * Ok, time to look more closely! We need the rq
2132 * lock now, to be *sure*. If we're wrong, we'll
2133 * just go back and repeat.
2135 rq = task_rq_lock(p, &flags);
2136 running = task_running(rq, p);
2137 on_rq = p->se.on_rq;
2138 task_rq_unlock(rq, &flags);
2141 * Was it really running after all now that we
2142 * checked with the proper locks actually held?
2144 * Oops. Go back and try again..
2146 if (unlikely(running)) {
2152 * It's not enough that it's not actively running,
2153 * it must be off the runqueue _entirely_, and not
2156 * So if it wa still runnable (but just not actively
2157 * running right now), it's preempted, and we should
2158 * yield - it could be a while.
2160 if (unlikely(on_rq)) {
2161 schedule_timeout_uninterruptible(1);
2166 * Ahh, all good. It wasn't running, and it wasn't
2167 * runnable, which means that it will never become
2168 * running in the future either. We're all done!
2175 * kick_process - kick a running thread to enter/exit the kernel
2176 * @p: the to-be-kicked thread
2178 * Cause a process which is running on another CPU to enter
2179 * kernel-mode, without any delay. (to get signals handled.)
2181 * NOTE: this function doesnt have to take the runqueue lock,
2182 * because all it wants to ensure is that the remote task enters
2183 * the kernel. If the IPI races and the task has been migrated
2184 * to another CPU then no harm is done and the purpose has been
2187 void kick_process(struct task_struct *p)
2193 if ((cpu != smp_processor_id()) && task_curr(p))
2194 smp_send_reschedule(cpu);
2199 * Return a low guess at the load of a migration-source cpu weighted
2200 * according to the scheduling class and "nice" value.
2202 * We want to under-estimate the load of migration sources, to
2203 * balance conservatively.
2205 static unsigned long source_load(int cpu, int type)
2207 struct rq *rq = cpu_rq(cpu);
2208 unsigned long total = weighted_cpuload(cpu);
2213 return min(rq->cpu_load[type-1], total);
2217 * Return a high guess at the load of a migration-target cpu weighted
2218 * according to the scheduling class and "nice" value.
2220 static unsigned long target_load(int cpu, int type)
2222 struct rq *rq = cpu_rq(cpu);
2223 unsigned long total = weighted_cpuload(cpu);
2228 return max(rq->cpu_load[type-1], total);
2232 * Return the average load per task on the cpu's run queue
2234 static unsigned long cpu_avg_load_per_task(int cpu)
2236 struct rq *rq = cpu_rq(cpu);
2237 unsigned long total = weighted_cpuload(cpu);
2238 unsigned long n = rq->nr_running;
2240 return n ? total / n : SCHED_LOAD_SCALE;
2244 * find_idlest_group finds and returns the least busy CPU group within the
2247 static struct sched_group *
2248 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
2250 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
2251 unsigned long min_load = ULONG_MAX, this_load = 0;
2252 int load_idx = sd->forkexec_idx;
2253 int imbalance = 100 + (sd->imbalance_pct-100)/2;
2256 unsigned long load, avg_load;
2260 /* Skip over this group if it has no CPUs allowed */
2261 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
2264 local_group = cpu_isset(this_cpu, group->cpumask);
2266 /* Tally up the load of all CPUs in the group */
2269 for_each_cpu_mask(i, group->cpumask) {
2270 /* Bias balancing toward cpus of our domain */
2272 load = source_load(i, load_idx);
2274 load = target_load(i, load_idx);
2279 /* Adjust by relative CPU power of the group */
2280 avg_load = sg_div_cpu_power(group,
2281 avg_load * SCHED_LOAD_SCALE);
2284 this_load = avg_load;
2286 } else if (avg_load < min_load) {
2287 min_load = avg_load;
2290 } while (group = group->next, group != sd->groups);
2292 if (!idlest || 100*this_load < imbalance*min_load)
2298 * find_idlest_cpu - find the idlest cpu among the cpus in group.
2301 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu,
2304 unsigned long load, min_load = ULONG_MAX;
2308 /* Traverse only the allowed CPUs */
2309 cpus_and(*tmp, group->cpumask, p->cpus_allowed);
2311 for_each_cpu_mask(i, *tmp) {
2312 load = weighted_cpuload(i);
2314 if (load < min_load || (load == min_load && i == this_cpu)) {
2324 * sched_balance_self: balance the current task (running on cpu) in domains
2325 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
2328 * Balance, ie. select the least loaded group.
2330 * Returns the target CPU number, or the same CPU if no balancing is needed.
2332 * preempt must be disabled.
2334 static int sched_balance_self(int cpu, int flag)
2336 struct task_struct *t = current;
2337 struct sched_domain *tmp, *sd = NULL;
2339 for_each_domain(cpu, tmp) {
2341 * If power savings logic is enabled for a domain, stop there.
2343 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
2345 if (tmp->flags & flag)
2350 cpumask_t span, tmpmask;
2351 struct sched_group *group;
2352 int new_cpu, weight;
2354 if (!(sd->flags & flag)) {
2360 group = find_idlest_group(sd, t, cpu);
2366 new_cpu = find_idlest_cpu(group, t, cpu, &tmpmask);
2367 if (new_cpu == -1 || new_cpu == cpu) {
2368 /* Now try balancing at a lower domain level of cpu */
2373 /* Now try balancing at a lower domain level of new_cpu */
2376 weight = cpus_weight(span);
2377 for_each_domain(cpu, tmp) {
2378 if (weight <= cpus_weight(tmp->span))
2380 if (tmp->flags & flag)
2383 /* while loop will break here if sd == NULL */
2389 #endif /* CONFIG_SMP */
2392 * try_to_wake_up - wake up a thread
2393 * @p: the to-be-woken-up thread
2394 * @state: the mask of task states that can be woken
2395 * @sync: do a synchronous wakeup?
2397 * Put it on the run-queue if it's not already there. The "current"
2398 * thread is always on the run-queue (except when the actual
2399 * re-schedule is in progress), and as such you're allowed to do
2400 * the simpler "current->state = TASK_RUNNING" to mark yourself
2401 * runnable without the overhead of this.
2403 * returns failure only if the task is already active.
2405 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
2407 int cpu, orig_cpu, this_cpu, success = 0;
2408 unsigned long flags;
2412 if (!sched_feat(SYNC_WAKEUPS))
2416 rq = task_rq_lock(p, &flags);
2417 old_state = p->state;
2418 if (!(old_state & state))
2426 this_cpu = smp_processor_id();
2429 if (unlikely(task_running(rq, p)))
2432 cpu = p->sched_class->select_task_rq(p, sync);
2433 if (cpu != orig_cpu) {
2434 set_task_cpu(p, cpu);
2435 task_rq_unlock(rq, &flags);
2436 /* might preempt at this point */
2437 rq = task_rq_lock(p, &flags);
2438 old_state = p->state;
2439 if (!(old_state & state))
2444 this_cpu = smp_processor_id();
2448 #ifdef CONFIG_SCHEDSTATS
2449 schedstat_inc(rq, ttwu_count);
2450 if (cpu == this_cpu)
2451 schedstat_inc(rq, ttwu_local);
2453 struct sched_domain *sd;
2454 for_each_domain(this_cpu, sd) {
2455 if (cpu_isset(cpu, sd->span)) {
2456 schedstat_inc(sd, ttwu_wake_remote);
2464 #endif /* CONFIG_SMP */
2465 schedstat_inc(p, se.nr_wakeups);
2467 schedstat_inc(p, se.nr_wakeups_sync);
2468 if (orig_cpu != cpu)
2469 schedstat_inc(p, se.nr_wakeups_migrate);
2470 if (cpu == this_cpu)
2471 schedstat_inc(p, se.nr_wakeups_local);
2473 schedstat_inc(p, se.nr_wakeups_remote);
2474 update_rq_clock(rq);
2475 activate_task(rq, p, 1);
2479 check_preempt_curr(rq, p);
2481 p->state = TASK_RUNNING;
2483 if (p->sched_class->task_wake_up)
2484 p->sched_class->task_wake_up(rq, p);
2487 task_rq_unlock(rq, &flags);
2492 int wake_up_process(struct task_struct *p)
2494 return try_to_wake_up(p, TASK_ALL, 0);
2496 EXPORT_SYMBOL(wake_up_process);
2498 int wake_up_state(struct task_struct *p, unsigned int state)
2500 return try_to_wake_up(p, state, 0);
2504 * Perform scheduler related setup for a newly forked process p.
2505 * p is forked by current.
2507 * __sched_fork() is basic setup used by init_idle() too:
2509 static void __sched_fork(struct task_struct *p)
2511 p->se.exec_start = 0;
2512 p->se.sum_exec_runtime = 0;
2513 p->se.prev_sum_exec_runtime = 0;
2514 p->se.last_wakeup = 0;
2515 p->se.avg_overlap = 0;
2517 #ifdef CONFIG_SCHEDSTATS
2518 p->se.wait_start = 0;
2519 p->se.sum_sleep_runtime = 0;
2520 p->se.sleep_start = 0;
2521 p->se.block_start = 0;
2522 p->se.sleep_max = 0;
2523 p->se.block_max = 0;
2525 p->se.slice_max = 0;
2529 INIT_LIST_HEAD(&p->rt.run_list);
2531 INIT_LIST_HEAD(&p->se.group_node);
2533 #ifdef CONFIG_PREEMPT_NOTIFIERS
2534 INIT_HLIST_HEAD(&p->preempt_notifiers);
2538 * We mark the process as running here, but have not actually
2539 * inserted it onto the runqueue yet. This guarantees that
2540 * nobody will actually run it, and a signal or other external
2541 * event cannot wake it up and insert it on the runqueue either.
2543 p->state = TASK_RUNNING;
2547 * fork()/clone()-time setup:
2549 void sched_fork(struct task_struct *p, int clone_flags)
2551 int cpu = get_cpu();
2556 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
2558 set_task_cpu(p, cpu);
2561 * Make sure we do not leak PI boosting priority to the child:
2563 p->prio = current->normal_prio;
2564 if (!rt_prio(p->prio))
2565 p->sched_class = &fair_sched_class;
2567 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2568 if (likely(sched_info_on()))
2569 memset(&p->sched_info, 0, sizeof(p->sched_info));
2571 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2574 #ifdef CONFIG_PREEMPT
2575 /* Want to start with kernel preemption disabled. */
2576 task_thread_info(p)->preempt_count = 1;
2582 * wake_up_new_task - wake up a newly created task for the first time.
2584 * This function will do some initial scheduler statistics housekeeping
2585 * that must be done for every newly created context, then puts the task
2586 * on the runqueue and wakes it.
2588 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2590 unsigned long flags;
2593 rq = task_rq_lock(p, &flags);
2594 BUG_ON(p->state != TASK_RUNNING);
2595 update_rq_clock(rq);
2597 p->prio = effective_prio(p);
2599 if (!p->sched_class->task_new || !current->se.on_rq) {
2600 activate_task(rq, p, 0);
2603 * Let the scheduling class do new task startup
2604 * management (if any):
2606 p->sched_class->task_new(rq, p);
2609 check_preempt_curr(rq, p);
2611 if (p->sched_class->task_wake_up)
2612 p->sched_class->task_wake_up(rq, p);
2614 task_rq_unlock(rq, &flags);
2617 #ifdef CONFIG_PREEMPT_NOTIFIERS
2620 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2621 * @notifier: notifier struct to register
2623 void preempt_notifier_register(struct preempt_notifier *notifier)
2625 hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
2627 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2630 * preempt_notifier_unregister - no longer interested in preemption notifications
2631 * @notifier: notifier struct to unregister
2633 * This is safe to call from within a preemption notifier.
2635 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2637 hlist_del(¬ifier->link);
2639 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2641 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2643 struct preempt_notifier *notifier;
2644 struct hlist_node *node;
2646 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2647 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2651 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2652 struct task_struct *next)
2654 struct preempt_notifier *notifier;
2655 struct hlist_node *node;
2657 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2658 notifier->ops->sched_out(notifier, next);
2663 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2668 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2669 struct task_struct *next)
2676 * prepare_task_switch - prepare to switch tasks
2677 * @rq: the runqueue preparing to switch
2678 * @prev: the current task that is being switched out
2679 * @next: the task we are going to switch to.
2681 * This is called with the rq lock held and interrupts off. It must
2682 * be paired with a subsequent finish_task_switch after the context
2685 * prepare_task_switch sets up locking and calls architecture specific
2689 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2690 struct task_struct *next)
2692 fire_sched_out_preempt_notifiers(prev, next);
2693 prepare_lock_switch(rq, next);
2694 prepare_arch_switch(next);
2698 * finish_task_switch - clean up after a task-switch
2699 * @rq: runqueue associated with task-switch
2700 * @prev: the thread we just switched away from.
2702 * finish_task_switch must be called after the context switch, paired
2703 * with a prepare_task_switch call before the context switch.
2704 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2705 * and do any other architecture-specific cleanup actions.
2707 * Note that we may have delayed dropping an mm in context_switch(). If
2708 * so, we finish that here outside of the runqueue lock. (Doing it
2709 * with the lock held can cause deadlocks; see schedule() for
2712 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2713 __releases(rq->lock)
2715 struct mm_struct *mm = rq->prev_mm;
2721 * A task struct has one reference for the use as "current".
2722 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2723 * schedule one last time. The schedule call will never return, and
2724 * the scheduled task must drop that reference.
2725 * The test for TASK_DEAD must occur while the runqueue locks are
2726 * still held, otherwise prev could be scheduled on another cpu, die
2727 * there before we look at prev->state, and then the reference would
2729 * Manfred Spraul <manfred@colorfullife.com>
2731 prev_state = prev->state;
2732 finish_arch_switch(prev);
2733 finish_lock_switch(rq, prev);
2735 if (current->sched_class->post_schedule)
2736 current->sched_class->post_schedule(rq);
2739 fire_sched_in_preempt_notifiers(current);
2742 if (unlikely(prev_state == TASK_DEAD)) {
2744 * Remove function-return probe instances associated with this
2745 * task and put them back on the free list.
2747 kprobe_flush_task(prev);
2748 put_task_struct(prev);
2753 * schedule_tail - first thing a freshly forked thread must call.
2754 * @prev: the thread we just switched away from.
2756 asmlinkage void schedule_tail(struct task_struct *prev)
2757 __releases(rq->lock)
2759 struct rq *rq = this_rq();
2761 finish_task_switch(rq, prev);
2762 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2763 /* In this case, finish_task_switch does not reenable preemption */
2766 if (current->set_child_tid)
2767 put_user(task_pid_vnr(current), current->set_child_tid);
2771 * context_switch - switch to the new MM and the new
2772 * thread's register state.
2775 context_switch(struct rq *rq, struct task_struct *prev,
2776 struct task_struct *next)
2778 struct mm_struct *mm, *oldmm;
2780 prepare_task_switch(rq, prev, next);
2782 oldmm = prev->active_mm;
2784 * For paravirt, this is coupled with an exit in switch_to to
2785 * combine the page table reload and the switch backend into
2788 arch_enter_lazy_cpu_mode();
2790 if (unlikely(!mm)) {
2791 next->active_mm = oldmm;
2792 atomic_inc(&oldmm->mm_count);
2793 enter_lazy_tlb(oldmm, next);
2795 switch_mm(oldmm, mm, next);
2797 if (unlikely(!prev->mm)) {
2798 prev->active_mm = NULL;
2799 rq->prev_mm = oldmm;
2802 * Since the runqueue lock will be released by the next
2803 * task (which is an invalid locking op but in the case
2804 * of the scheduler it's an obvious special-case), so we
2805 * do an early lockdep release here:
2807 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2808 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2811 /* Here we just switch the register state and the stack. */
2812 switch_to(prev, next, prev);
2816 * this_rq must be evaluated again because prev may have moved
2817 * CPUs since it called schedule(), thus the 'rq' on its stack
2818 * frame will be invalid.
2820 finish_task_switch(this_rq(), prev);
2824 * nr_running, nr_uninterruptible and nr_context_switches:
2826 * externally visible scheduler statistics: current number of runnable
2827 * threads, current number of uninterruptible-sleeping threads, total
2828 * number of context switches performed since bootup.
2830 unsigned long nr_running(void)
2832 unsigned long i, sum = 0;
2834 for_each_online_cpu(i)
2835 sum += cpu_rq(i)->nr_running;
2840 unsigned long nr_uninterruptible(void)
2842 unsigned long i, sum = 0;
2844 for_each_possible_cpu(i)
2845 sum += cpu_rq(i)->nr_uninterruptible;
2848 * Since we read the counters lockless, it might be slightly
2849 * inaccurate. Do not allow it to go below zero though:
2851 if (unlikely((long)sum < 0))
2857 unsigned long long nr_context_switches(void)
2860 unsigned long long sum = 0;
2862 for_each_possible_cpu(i)
2863 sum += cpu_rq(i)->nr_switches;
2868 unsigned long nr_iowait(void)
2870 unsigned long i, sum = 0;
2872 for_each_possible_cpu(i)
2873 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2878 unsigned long nr_active(void)
2880 unsigned long i, running = 0, uninterruptible = 0;
2882 for_each_online_cpu(i) {
2883 running += cpu_rq(i)->nr_running;
2884 uninterruptible += cpu_rq(i)->nr_uninterruptible;
2887 if (unlikely((long)uninterruptible < 0))
2888 uninterruptible = 0;
2890 return running + uninterruptible;
2894 * Update rq->cpu_load[] statistics. This function is usually called every
2895 * scheduler tick (TICK_NSEC).
2897 static void update_cpu_load(struct rq *this_rq)
2899 unsigned long this_load = this_rq->load.weight;
2902 this_rq->nr_load_updates++;
2904 /* Update our load: */
2905 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
2906 unsigned long old_load, new_load;
2908 /* scale is effectively 1 << i now, and >> i divides by scale */
2910 old_load = this_rq->cpu_load[i];
2911 new_load = this_load;
2913 * Round up the averaging division if load is increasing. This
2914 * prevents us from getting stuck on 9 if the load is 10, for
2917 if (new_load > old_load)
2918 new_load += scale-1;
2919 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
2926 * double_rq_lock - safely lock two runqueues
2928 * Note this does not disable interrupts like task_rq_lock,
2929 * you need to do so manually before calling.
2931 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
2932 __acquires(rq1->lock)
2933 __acquires(rq2->lock)
2935 BUG_ON(!irqs_disabled());
2937 spin_lock(&rq1->lock);
2938 __acquire(rq2->lock); /* Fake it out ;) */
2941 spin_lock(&rq1->lock);
2942 spin_lock(&rq2->lock);
2944 spin_lock(&rq2->lock);
2945 spin_lock(&rq1->lock);
2948 update_rq_clock(rq1);
2949 update_rq_clock(rq2);
2953 * double_rq_unlock - safely unlock two runqueues
2955 * Note this does not restore interrupts like task_rq_unlock,
2956 * you need to do so manually after calling.
2958 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
2959 __releases(rq1->lock)
2960 __releases(rq2->lock)
2962 spin_unlock(&rq1->lock);
2964 spin_unlock(&rq2->lock);
2966 __release(rq2->lock);
2970 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2972 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
2973 __releases(this_rq->lock)
2974 __acquires(busiest->lock)
2975 __acquires(this_rq->lock)
2979 if (unlikely(!irqs_disabled())) {
2980 /* printk() doesn't work good under rq->lock */
2981 spin_unlock(&this_rq->lock);
2984 if (unlikely(!spin_trylock(&busiest->lock))) {
2985 if (busiest < this_rq) {
2986 spin_unlock(&this_rq->lock);
2987 spin_lock(&busiest->lock);
2988 spin_lock(&this_rq->lock);
2991 spin_lock(&busiest->lock);
2997 * If dest_cpu is allowed for this process, migrate the task to it.
2998 * This is accomplished by forcing the cpu_allowed mask to only
2999 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
3000 * the cpu_allowed mask is restored.
3002 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
3004 struct migration_req req;
3005 unsigned long flags;
3008 rq = task_rq_lock(p, &flags);
3009 if (!cpu_isset(dest_cpu, p->cpus_allowed)
3010 || unlikely(cpu_is_offline(dest_cpu)))
3013 /* force the process onto the specified CPU */
3014 if (migrate_task(p, dest_cpu, &req)) {
3015 /* Need to wait for migration thread (might exit: take ref). */
3016 struct task_struct *mt = rq->migration_thread;
3018 get_task_struct(mt);
3019 task_rq_unlock(rq, &flags);
3020 wake_up_process(mt);
3021 put_task_struct(mt);
3022 wait_for_completion(&req.done);
3027 task_rq_unlock(rq, &flags);
3031 * sched_exec - execve() is a valuable balancing opportunity, because at
3032 * this point the task has the smallest effective memory and cache footprint.
3034 void sched_exec(void)
3036 int new_cpu, this_cpu = get_cpu();
3037 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
3039 if (new_cpu != this_cpu)
3040 sched_migrate_task(current, new_cpu);
3044 * pull_task - move a task from a remote runqueue to the local runqueue.
3045 * Both runqueues must be locked.
3047 static void pull_task(struct rq *src_rq, struct task_struct *p,
3048 struct rq *this_rq, int this_cpu)
3050 deactivate_task(src_rq, p, 0);
3051 set_task_cpu(p, this_cpu);
3052 activate_task(this_rq, p, 0);
3054 * Note that idle threads have a prio of MAX_PRIO, for this test
3055 * to be always true for them.
3057 check_preempt_curr(this_rq, p);
3061 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
3064 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
3065 struct sched_domain *sd, enum cpu_idle_type idle,
3069 * We do not migrate tasks that are:
3070 * 1) running (obviously), or
3071 * 2) cannot be migrated to this CPU due to cpus_allowed, or
3072 * 3) are cache-hot on their current CPU.
3074 if (!cpu_isset(this_cpu, p->cpus_allowed)) {
3075 schedstat_inc(p, se.nr_failed_migrations_affine);
3080 if (task_running(rq, p)) {
3081 schedstat_inc(p, se.nr_failed_migrations_running);
3086 * Aggressive migration if:
3087 * 1) task is cache cold, or
3088 * 2) too many balance attempts have failed.
3091 if (!task_hot(p, rq->clock, sd) ||
3092 sd->nr_balance_failed > sd->cache_nice_tries) {
3093 #ifdef CONFIG_SCHEDSTATS
3094 if (task_hot(p, rq->clock, sd)) {
3095 schedstat_inc(sd, lb_hot_gained[idle]);
3096 schedstat_inc(p, se.nr_forced_migrations);
3102 if (task_hot(p, rq->clock, sd)) {
3103 schedstat_inc(p, se.nr_failed_migrations_hot);
3109 static unsigned long
3110 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3111 unsigned long max_load_move, struct sched_domain *sd,
3112 enum cpu_idle_type idle, int *all_pinned,
3113 int *this_best_prio, struct rq_iterator *iterator)
3115 int loops = 0, pulled = 0, pinned = 0, skip_for_load;
3116 struct task_struct *p;
3117 long rem_load_move = max_load_move;
3119 if (max_load_move == 0)
3125 * Start the load-balancing iterator:
3127 p = iterator->start(iterator->arg);
3129 if (!p || loops++ > sysctl_sched_nr_migrate)
3132 * To help distribute high priority tasks across CPUs we don't
3133 * skip a task if it will be the highest priority task (i.e. smallest
3134 * prio value) on its new queue regardless of its load weight
3136 skip_for_load = (p->se.load.weight >> 1) > rem_load_move +
3137 SCHED_LOAD_SCALE_FUZZ;
3138 if ((skip_for_load && p->prio >= *this_best_prio) ||
3139 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3140 p = iterator->next(iterator->arg);
3144 pull_task(busiest, p, this_rq, this_cpu);
3146 rem_load_move -= p->se.load.weight;
3149 * We only want to steal up to the prescribed amount of weighted load.
3151 if (rem_load_move > 0) {
3152 if (p->prio < *this_best_prio)
3153 *this_best_prio = p->prio;
3154 p = iterator->next(iterator->arg);
3159 * Right now, this is one of only two places pull_task() is called,
3160 * so we can safely collect pull_task() stats here rather than
3161 * inside pull_task().
3163 schedstat_add(sd, lb_gained[idle], pulled);
3166 *all_pinned = pinned;
3168 return max_load_move - rem_load_move;
3172 * move_tasks tries to move up to max_load_move weighted load from busiest to
3173 * this_rq, as part of a balancing operation within domain "sd".
3174 * Returns 1 if successful and 0 otherwise.
3176 * Called with both runqueues locked.
3178 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3179 unsigned long max_load_move,
3180 struct sched_domain *sd, enum cpu_idle_type idle,
3183 const struct sched_class *class = sched_class_highest;
3184 unsigned long total_load_moved = 0;
3185 int this_best_prio = this_rq->curr->prio;
3189 class->load_balance(this_rq, this_cpu, busiest,
3190 max_load_move - total_load_moved,
3191 sd, idle, all_pinned, &this_best_prio);
3192 class = class->next;
3193 } while (class && max_load_move > total_load_moved);
3195 return total_load_moved > 0;
3199 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3200 struct sched_domain *sd, enum cpu_idle_type idle,
3201 struct rq_iterator *iterator)
3203 struct task_struct *p = iterator->start(iterator->arg);
3207 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
3208 pull_task(busiest, p, this_rq, this_cpu);
3210 * Right now, this is only the second place pull_task()
3211 * is called, so we can safely collect pull_task()
3212 * stats here rather than inside pull_task().
3214 schedstat_inc(sd, lb_gained[idle]);
3218 p = iterator->next(iterator->arg);
3225 * move_one_task tries to move exactly one task from busiest to this_rq, as
3226 * part of active balancing operations within "domain".
3227 * Returns 1 if successful and 0 otherwise.
3229 * Called with both runqueues locked.
3231 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
3232 struct sched_domain *sd, enum cpu_idle_type idle)
3234 const struct sched_class *class;
3236 for (class = sched_class_highest; class; class = class->next)
3237 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
3244 * find_busiest_group finds and returns the busiest CPU group within the
3245 * domain. It calculates and returns the amount of weighted load which
3246 * should be moved to restore balance via the imbalance parameter.
3248 static struct sched_group *
3249 find_busiest_group(struct sched_domain *sd, int this_cpu,
3250 unsigned long *imbalance, enum cpu_idle_type idle,
3251 int *sd_idle, const cpumask_t *cpus, int *balance)
3253 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
3254 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
3255 unsigned long max_pull;
3256 unsigned long busiest_load_per_task, busiest_nr_running;
3257 unsigned long this_load_per_task, this_nr_running;
3258 int load_idx, group_imb = 0;
3259 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3260 int power_savings_balance = 1;
3261 unsigned long leader_nr_running = 0, min_load_per_task = 0;
3262 unsigned long min_nr_running = ULONG_MAX;
3263 struct sched_group *group_min = NULL, *group_leader = NULL;
3266 max_load = this_load = total_load = total_pwr = 0;
3267 busiest_load_per_task = busiest_nr_running = 0;
3268 this_load_per_task = this_nr_running = 0;
3269 if (idle == CPU_NOT_IDLE)
3270 load_idx = sd->busy_idx;
3271 else if (idle == CPU_NEWLY_IDLE)
3272 load_idx = sd->newidle_idx;
3274 load_idx = sd->idle_idx;
3277 unsigned long load, group_capacity, max_cpu_load, min_cpu_load;
3280 int __group_imb = 0;
3281 unsigned int balance_cpu = -1, first_idle_cpu = 0;
3282 unsigned long sum_nr_running, sum_weighted_load;
3284 local_group = cpu_isset(this_cpu, group->cpumask);
3287 balance_cpu = first_cpu(group->cpumask);
3289 /* Tally up the load of all CPUs in the group */
3290 sum_weighted_load = sum_nr_running = avg_load = 0;
3292 min_cpu_load = ~0UL;
3294 for_each_cpu_mask(i, group->cpumask) {
3297 if (!cpu_isset(i, *cpus))
3302 if (*sd_idle && rq->nr_running)
3305 /* Bias balancing toward cpus of our domain */
3307 if (idle_cpu(i) && !first_idle_cpu) {
3312 load = target_load(i, load_idx);
3314 load = source_load(i, load_idx);
3315 if (load > max_cpu_load)
3316 max_cpu_load = load;
3317 if (min_cpu_load > load)
3318 min_cpu_load = load;
3322 sum_nr_running += rq->nr_running;
3323 sum_weighted_load += weighted_cpuload(i);
3327 * First idle cpu or the first cpu(busiest) in this sched group
3328 * is eligible for doing load balancing at this and above
3329 * domains. In the newly idle case, we will allow all the cpu's
3330 * to do the newly idle load balance.
3332 if (idle != CPU_NEWLY_IDLE && local_group &&
3333 balance_cpu != this_cpu && balance) {
3338 total_load += avg_load;
3339 total_pwr += group->__cpu_power;
3341 /* Adjust by relative CPU power of the group */
3342 avg_load = sg_div_cpu_power(group,
3343 avg_load * SCHED_LOAD_SCALE);
3345 if ((max_cpu_load - min_cpu_load) > SCHED_LOAD_SCALE)
3348 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
3351 this_load = avg_load;
3353 this_nr_running = sum_nr_running;
3354 this_load_per_task = sum_weighted_load;
3355 } else if (avg_load > max_load &&
3356 (sum_nr_running > group_capacity || __group_imb)) {
3357 max_load = avg_load;
3359 busiest_nr_running = sum_nr_running;
3360 busiest_load_per_task = sum_weighted_load;
3361 group_imb = __group_imb;
3364 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3366 * Busy processors will not participate in power savings
3369 if (idle == CPU_NOT_IDLE ||
3370 !(sd->flags & SD_POWERSAVINGS_BALANCE))
3374 * If the local group is idle or completely loaded
3375 * no need to do power savings balance at this domain
3377 if (local_group && (this_nr_running >= group_capacity ||
3379 power_savings_balance = 0;
3382 * If a group is already running at full capacity or idle,
3383 * don't include that group in power savings calculations
3385 if (!power_savings_balance || sum_nr_running >= group_capacity
3390 * Calculate the group which has the least non-idle load.
3391 * This is the group from where we need to pick up the load
3394 if ((sum_nr_running < min_nr_running) ||
3395 (sum_nr_running == min_nr_running &&
3396 first_cpu(group->cpumask) <
3397 first_cpu(group_min->cpumask))) {
3399 min_nr_running = sum_nr_running;
3400 min_load_per_task = sum_weighted_load /
3405 * Calculate the group which is almost near its
3406 * capacity but still has some space to pick up some load
3407 * from other group and save more power
3409 if (sum_nr_running <= group_capacity - 1) {
3410 if (sum_nr_running > leader_nr_running ||
3411 (sum_nr_running == leader_nr_running &&
3412 first_cpu(group->cpumask) >
3413 first_cpu(group_leader->cpumask))) {
3414 group_leader = group;
3415 leader_nr_running = sum_nr_running;
3420 group = group->next;
3421 } while (group != sd->groups);
3423 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
3426 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
3428 if (this_load >= avg_load ||
3429 100*max_load <= sd->imbalance_pct*this_load)
3432 busiest_load_per_task /= busiest_nr_running;
3434 busiest_load_per_task = min(busiest_load_per_task, avg_load);
3437 * We're trying to get all the cpus to the average_load, so we don't
3438 * want to push ourselves above the average load, nor do we wish to
3439 * reduce the max loaded cpu below the average load, as either of these
3440 * actions would just result in more rebalancing later, and ping-pong
3441 * tasks around. Thus we look for the minimum possible imbalance.
3442 * Negative imbalances (*we* are more loaded than anyone else) will
3443 * be counted as no imbalance for these purposes -- we can't fix that
3444 * by pulling tasks to us. Be careful of negative numbers as they'll
3445 * appear as very large values with unsigned longs.
3447 if (max_load <= busiest_load_per_task)
3451 * In the presence of smp nice balancing, certain scenarios can have
3452 * max load less than avg load(as we skip the groups at or below
3453 * its cpu_power, while calculating max_load..)
3455 if (max_load < avg_load) {
3457 goto small_imbalance;
3460 /* Don't want to pull so many tasks that a group would go idle */
3461 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
3463 /* How much load to actually move to equalise the imbalance */
3464 *imbalance = min(max_pull * busiest->__cpu_power,
3465 (avg_load - this_load) * this->__cpu_power)
3469 * if *imbalance is less than the average load per runnable task
3470 * there is no gaurantee that any tasks will be moved so we'll have
3471 * a think about bumping its value to force at least one task to be
3474 if (*imbalance < busiest_load_per_task) {
3475 unsigned long tmp, pwr_now, pwr_move;
3479 pwr_move = pwr_now = 0;
3481 if (this_nr_running) {
3482 this_load_per_task /= this_nr_running;
3483 if (busiest_load_per_task > this_load_per_task)
3486 this_load_per_task = SCHED_LOAD_SCALE;
3488 if (max_load - this_load + SCHED_LOAD_SCALE_FUZZ >=
3489 busiest_load_per_task * imbn) {
3490 *imbalance = busiest_load_per_task;
3495 * OK, we don't have enough imbalance to justify moving tasks,
3496 * however we may be able to increase total CPU power used by
3500 pwr_now += busiest->__cpu_power *
3501 min(busiest_load_per_task, max_load);
3502 pwr_now += this->__cpu_power *
3503 min(this_load_per_task, this_load);
3504 pwr_now /= SCHED_LOAD_SCALE;
3506 /* Amount of load we'd subtract */
3507 tmp = sg_div_cpu_power(busiest,
3508 busiest_load_per_task * SCHED_LOAD_SCALE);
3510 pwr_move += busiest->__cpu_power *
3511 min(busiest_load_per_task, max_load - tmp);
3513 /* Amount of load we'd add */
3514 if (max_load * busiest->__cpu_power <
3515 busiest_load_per_task * SCHED_LOAD_SCALE)
3516 tmp = sg_div_cpu_power(this,
3517 max_load * busiest->__cpu_power);
3519 tmp = sg_div_cpu_power(this,
3520 busiest_load_per_task * SCHED_LOAD_SCALE);
3521 pwr_move += this->__cpu_power *
3522 min(this_load_per_task, this_load + tmp);
3523 pwr_move /= SCHED_LOAD_SCALE;
3525 /* Move if we gain throughput */
3526 if (pwr_move > pwr_now)
3527 *imbalance = busiest_load_per_task;
3533 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3534 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3537 if (this == group_leader && group_leader != group_min) {
3538 *imbalance = min_load_per_task;
3548 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3551 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
3552 unsigned long imbalance, const cpumask_t *cpus)
3554 struct rq *busiest = NULL, *rq;
3555 unsigned long max_load = 0;
3558 for_each_cpu_mask(i, group->cpumask) {
3561 if (!cpu_isset(i, *cpus))
3565 wl = weighted_cpuload(i);
3567 if (rq->nr_running == 1 && wl > imbalance)
3570 if (wl > max_load) {
3580 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3581 * so long as it is large enough.
3583 #define MAX_PINNED_INTERVAL 512
3586 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3587 * tasks if there is an imbalance.
3589 static int load_balance(int this_cpu, struct rq *this_rq,
3590 struct sched_domain *sd, enum cpu_idle_type idle,
3591 int *balance, cpumask_t *cpus)
3593 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
3594 struct sched_group *group;
3595 unsigned long imbalance;
3597 unsigned long flags;
3598 int unlock_aggregate;
3602 unlock_aggregate = get_aggregate(sd);
3605 * When power savings policy is enabled for the parent domain, idle
3606 * sibling can pick up load irrespective of busy siblings. In this case,
3607 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3608 * portraying it as CPU_NOT_IDLE.
3610 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
3611 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3614 schedstat_inc(sd, lb_count[idle]);
3617 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
3624 schedstat_inc(sd, lb_nobusyg[idle]);
3628 busiest = find_busiest_queue(group, idle, imbalance, cpus);
3630 schedstat_inc(sd, lb_nobusyq[idle]);
3634 BUG_ON(busiest == this_rq);
3636 schedstat_add(sd, lb_imbalance[idle], imbalance);
3639 if (busiest->nr_running > 1) {
3641 * Attempt to move tasks. If find_busiest_group has found
3642 * an imbalance but busiest->nr_running <= 1, the group is
3643 * still unbalanced. ld_moved simply stays zero, so it is
3644 * correctly treated as an imbalance.
3646 local_irq_save(flags);
3647 double_rq_lock(this_rq, busiest);
3648 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3649 imbalance, sd, idle, &all_pinned);
3650 double_rq_unlock(this_rq, busiest);
3651 local_irq_restore(flags);
3654 * some other cpu did the load balance for us.
3656 if (ld_moved && this_cpu != smp_processor_id())
3657 resched_cpu(this_cpu);
3659 /* All tasks on this runqueue were pinned by CPU affinity */
3660 if (unlikely(all_pinned)) {
3661 cpu_clear(cpu_of(busiest), *cpus);
3662 if (!cpus_empty(*cpus))
3669 schedstat_inc(sd, lb_failed[idle]);
3670 sd->nr_balance_failed++;
3672 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
3674 spin_lock_irqsave(&busiest->lock, flags);
3676 /* don't kick the migration_thread, if the curr
3677 * task on busiest cpu can't be moved to this_cpu
3679 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
3680 spin_unlock_irqrestore(&busiest->lock, flags);
3682 goto out_one_pinned;
3685 if (!busiest->active_balance) {
3686 busiest->active_balance = 1;
3687 busiest->push_cpu = this_cpu;
3690 spin_unlock_irqrestore(&busiest->lock, flags);
3692 wake_up_process(busiest->migration_thread);
3695 * We've kicked active balancing, reset the failure
3698 sd->nr_balance_failed = sd->cache_nice_tries+1;
3701 sd->nr_balance_failed = 0;
3703 if (likely(!active_balance)) {
3704 /* We were unbalanced, so reset the balancing interval */
3705 sd->balance_interval = sd->min_interval;
3708 * If we've begun active balancing, start to back off. This
3709 * case may not be covered by the all_pinned logic if there
3710 * is only 1 task on the busy runqueue (because we don't call
3713 if (sd->balance_interval < sd->max_interval)
3714 sd->balance_interval *= 2;
3717 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3718 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3724 schedstat_inc(sd, lb_balanced[idle]);
3726 sd->nr_balance_failed = 0;
3729 /* tune up the balancing interval */
3730 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
3731 (sd->balance_interval < sd->max_interval))
3732 sd->balance_interval *= 2;
3734 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3735 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3740 if (unlock_aggregate)
3746 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3747 * tasks if there is an imbalance.
3749 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3750 * this_rq is locked.
3753 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd,
3756 struct sched_group *group;
3757 struct rq *busiest = NULL;
3758 unsigned long imbalance;
3766 * When power savings policy is enabled for the parent domain, idle
3767 * sibling can pick up load irrespective of busy siblings. In this case,
3768 * let the state of idle sibling percolate up as IDLE, instead of
3769 * portraying it as CPU_NOT_IDLE.
3771 if (sd->flags & SD_SHARE_CPUPOWER &&
3772 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3775 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
3777 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
3778 &sd_idle, cpus, NULL);
3780 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
3784 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance, cpus);
3786 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
3790 BUG_ON(busiest == this_rq);
3792 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
3795 if (busiest->nr_running > 1) {
3796 /* Attempt to move tasks */
3797 double_lock_balance(this_rq, busiest);
3798 /* this_rq->clock is already updated */
3799 update_rq_clock(busiest);
3800 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3801 imbalance, sd, CPU_NEWLY_IDLE,
3803 spin_unlock(&busiest->lock);
3805 if (unlikely(all_pinned)) {
3806 cpu_clear(cpu_of(busiest), *cpus);
3807 if (!cpus_empty(*cpus))
3813 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
3814 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3815 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3818 sd->nr_balance_failed = 0;
3823 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
3824 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3825 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3827 sd->nr_balance_failed = 0;
3833 * idle_balance is called by schedule() if this_cpu is about to become
3834 * idle. Attempts to pull tasks from other CPUs.
3836 static void idle_balance(int this_cpu, struct rq *this_rq)
3838 struct sched_domain *sd;
3839 int pulled_task = -1;
3840 unsigned long next_balance = jiffies + HZ;
3843 for_each_domain(this_cpu, sd) {
3844 unsigned long interval;
3846 if (!(sd->flags & SD_LOAD_BALANCE))
3849 if (sd->flags & SD_BALANCE_NEWIDLE)
3850 /* If we've pulled tasks over stop searching: */
3851 pulled_task = load_balance_newidle(this_cpu, this_rq,
3854 interval = msecs_to_jiffies(sd->balance_interval);
3855 if (time_after(next_balance, sd->last_balance + interval))
3856 next_balance = sd->last_balance + interval;
3860 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
3862 * We are going idle. next_balance may be set based on
3863 * a busy processor. So reset next_balance.
3865 this_rq->next_balance = next_balance;
3870 * active_load_balance is run by migration threads. It pushes running tasks
3871 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3872 * running on each physical CPU where possible, and avoids physical /
3873 * logical imbalances.
3875 * Called with busiest_rq locked.
3877 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
3879 int target_cpu = busiest_rq->push_cpu;
3880 struct sched_domain *sd;
3881 struct rq *target_rq;
3883 /* Is there any task to move? */
3884 if (busiest_rq->nr_running <= 1)
3887 target_rq = cpu_rq(target_cpu);
3890 * This condition is "impossible", if it occurs
3891 * we need to fix it. Originally reported by
3892 * Bjorn Helgaas on a 128-cpu setup.
3894 BUG_ON(busiest_rq == target_rq);
3896 /* move a task from busiest_rq to target_rq */
3897 double_lock_balance(busiest_rq, target_rq);
3898 update_rq_clock(busiest_rq);
3899 update_rq_clock(target_rq);
3901 /* Search for an sd spanning us and the target CPU. */
3902 for_each_domain(target_cpu, sd) {
3903 if ((sd->flags & SD_LOAD_BALANCE) &&
3904 cpu_isset(busiest_cpu, sd->span))
3909 schedstat_inc(sd, alb_count);
3911 if (move_one_task(target_rq, target_cpu, busiest_rq,
3913 schedstat_inc(sd, alb_pushed);
3915 schedstat_inc(sd, alb_failed);
3917 spin_unlock(&target_rq->lock);
3922 atomic_t load_balancer;
3924 } nohz ____cacheline_aligned = {
3925 .load_balancer = ATOMIC_INIT(-1),
3926 .cpu_mask = CPU_MASK_NONE,
3930 * This routine will try to nominate the ilb (idle load balancing)
3931 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3932 * load balancing on behalf of all those cpus. If all the cpus in the system
3933 * go into this tickless mode, then there will be no ilb owner (as there is
3934 * no need for one) and all the cpus will sleep till the next wakeup event
3937 * For the ilb owner, tick is not stopped. And this tick will be used
3938 * for idle load balancing. ilb owner will still be part of
3941 * While stopping the tick, this cpu will become the ilb owner if there
3942 * is no other owner. And will be the owner till that cpu becomes busy
3943 * or if all cpus in the system stop their ticks at which point
3944 * there is no need for ilb owner.
3946 * When the ilb owner becomes busy, it nominates another owner, during the
3947 * next busy scheduler_tick()
3949 int select_nohz_load_balancer(int stop_tick)
3951 int cpu = smp_processor_id();
3954 cpu_set(cpu, nohz.cpu_mask);
3955 cpu_rq(cpu)->in_nohz_recently = 1;
3958 * If we are going offline and still the leader, give up!
3960 if (cpu_is_offline(cpu) &&
3961 atomic_read(&nohz.load_balancer) == cpu) {
3962 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3967 /* time for ilb owner also to sleep */
3968 if (cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3969 if (atomic_read(&nohz.load_balancer) == cpu)
3970 atomic_set(&nohz.load_balancer, -1);
3974 if (atomic_read(&nohz.load_balancer) == -1) {
3975 /* make me the ilb owner */
3976 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
3978 } else if (atomic_read(&nohz.load_balancer) == cpu)
3981 if (!cpu_isset(cpu, nohz.cpu_mask))
3984 cpu_clear(cpu, nohz.cpu_mask);
3986 if (atomic_read(&nohz.load_balancer) == cpu)
3987 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3994 static DEFINE_SPINLOCK(balancing);
3997 * It checks each scheduling domain to see if it is due to be balanced,
3998 * and initiates a balancing operation if so.
4000 * Balancing parameters are set up in arch_init_sched_domains.
4002 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
4005 struct rq *rq = cpu_rq(cpu);
4006 unsigned long interval;
4007 struct sched_domain *sd;
4008 /* Earliest time when we have to do rebalance again */
4009 unsigned long next_balance = jiffies + 60*HZ;
4010 int update_next_balance = 0;
4013 for_each_domain(cpu, sd) {
4014 if (!(sd->flags & SD_LOAD_BALANCE))
4017 interval = sd->balance_interval;
4018 if (idle != CPU_IDLE)
4019 interval *= sd->busy_factor;
4021 /* scale ms to jiffies */
4022 interval = msecs_to_jiffies(interval);
4023 if (unlikely(!interval))
4025 if (interval > HZ*NR_CPUS/10)
4026 interval = HZ*NR_CPUS/10;
4029 if (sd->flags & SD_SERIALIZE) {
4030 if (!spin_trylock(&balancing))
4034 if (time_after_eq(jiffies, sd->last_balance + interval)) {
4035 if (load_balance(cpu, rq, sd, idle, &balance, &tmp)) {
4037 * We've pulled tasks over so either we're no
4038 * longer idle, or one of our SMT siblings is
4041 idle = CPU_NOT_IDLE;
4043 sd->last_balance = jiffies;
4045 if (sd->flags & SD_SERIALIZE)
4046 spin_unlock(&balancing);
4048 if (time_after(next_balance, sd->last_balance + interval)) {
4049 next_balance = sd->last_balance + interval;
4050 update_next_balance = 1;
4054 * Stop the load balance at this level. There is another
4055 * CPU in our sched group which is doing load balancing more
4063 * next_balance will be updated only when there is a need.
4064 * When the cpu is attached to null domain for ex, it will not be
4067 if (likely(update_next_balance))
4068 rq->next_balance = next_balance;
4072 * run_rebalance_domains is triggered when needed from the scheduler tick.
4073 * In CONFIG_NO_HZ case, the idle load balance owner will do the
4074 * rebalancing for all the cpus for whom scheduler ticks are stopped.
4076 static void run_rebalance_domains(struct softirq_action *h)
4078 int this_cpu = smp_processor_id();
4079 struct rq *this_rq = cpu_rq(this_cpu);
4080 enum cpu_idle_type idle = this_rq->idle_at_tick ?
4081 CPU_IDLE : CPU_NOT_IDLE;
4083 rebalance_domains(this_cpu, idle);
4087 * If this cpu is the owner for idle load balancing, then do the
4088 * balancing on behalf of the other idle cpus whose ticks are
4091 if (this_rq->idle_at_tick &&
4092 atomic_read(&nohz.load_balancer) == this_cpu) {
4093 cpumask_t cpus = nohz.cpu_mask;
4097 cpu_clear(this_cpu, cpus);
4098 for_each_cpu_mask(balance_cpu, cpus) {
4100 * If this cpu gets work to do, stop the load balancing
4101 * work being done for other cpus. Next load
4102 * balancing owner will pick it up.
4107 rebalance_domains(balance_cpu, CPU_IDLE);
4109 rq = cpu_rq(balance_cpu);
4110 if (time_after(this_rq->next_balance, rq->next_balance))
4111 this_rq->next_balance = rq->next_balance;
4118 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
4120 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
4121 * idle load balancing owner or decide to stop the periodic load balancing,
4122 * if the whole system is idle.
4124 static inline void trigger_load_balance(struct rq *rq, int cpu)
4128 * If we were in the nohz mode recently and busy at the current
4129 * scheduler tick, then check if we need to nominate new idle
4132 if (rq->in_nohz_recently && !rq->idle_at_tick) {
4133 rq->in_nohz_recently = 0;
4135 if (atomic_read(&nohz.load_balancer) == cpu) {
4136 cpu_clear(cpu, nohz.cpu_mask);
4137 atomic_set(&nohz.load_balancer, -1);
4140 if (atomic_read(&nohz.load_balancer) == -1) {
4142 * simple selection for now: Nominate the
4143 * first cpu in the nohz list to be the next
4146 * TBD: Traverse the sched domains and nominate
4147 * the nearest cpu in the nohz.cpu_mask.
4149 int ilb = first_cpu(nohz.cpu_mask);
4151 if (ilb < nr_cpu_ids)
4157 * If this cpu is idle and doing idle load balancing for all the
4158 * cpus with ticks stopped, is it time for that to stop?
4160 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
4161 cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
4167 * If this cpu is idle and the idle load balancing is done by
4168 * someone else, then no need raise the SCHED_SOFTIRQ
4170 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
4171 cpu_isset(cpu, nohz.cpu_mask))
4174 if (time_after_eq(jiffies, rq->next_balance))
4175 raise_softirq(SCHED_SOFTIRQ);
4178 #else /* CONFIG_SMP */
4181 * on UP we do not need to balance between CPUs:
4183 static inline void idle_balance(int cpu, struct rq *rq)
4189 DEFINE_PER_CPU(struct kernel_stat, kstat);
4191 EXPORT_PER_CPU_SYMBOL(kstat);
4194 * Return p->sum_exec_runtime plus any more ns on the sched_clock
4195 * that have not yet been banked in case the task is currently running.
4197 unsigned long long task_sched_runtime(struct task_struct *p)
4199 unsigned long flags;
4203 rq = task_rq_lock(p, &flags);
4204 ns = p->se.sum_exec_runtime;
4205 if (task_current(rq, p)) {
4206 update_rq_clock(rq);
4207 delta_exec = rq->clock - p->se.exec_start;
4208 if ((s64)delta_exec > 0)
4211 task_rq_unlock(rq, &flags);
4217 * Account user cpu time to a process.
4218 * @p: the process that the cpu time gets accounted to
4219 * @cputime: the cpu time spent in user space since the last update
4221 void account_user_time(struct task_struct *p, cputime_t cputime)
4223 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4226 p->utime = cputime_add(p->utime, cputime);
4228 /* Add user time to cpustat. */
4229 tmp = cputime_to_cputime64(cputime);
4230 if (TASK_NICE(p) > 0)
4231 cpustat->nice = cputime64_add(cpustat->nice, tmp);
4233 cpustat->user = cputime64_add(cpustat->user, tmp);
4237 * Account guest cpu time to a process.
4238 * @p: the process that the cpu time gets accounted to
4239 * @cputime: the cpu time spent in virtual machine since the last update
4241 static void account_guest_time(struct task_struct *p, cputime_t cputime)
4244 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4246 tmp = cputime_to_cputime64(cputime);
4248 p->utime = cputime_add(p->utime, cputime);
4249 p->gtime = cputime_add(p->gtime, cputime);
4251 cpustat->user = cputime64_add(cpustat->user, tmp);
4252 cpustat->guest = cputime64_add(cpustat->guest, tmp);
4256 * Account scaled user cpu time to a process.
4257 * @p: the process that the cpu time gets accounted to
4258 * @cputime: the cpu time spent in user space since the last update
4260 void account_user_time_scaled(struct task_struct *p, cputime_t cputime)
4262 p->utimescaled = cputime_add(p->utimescaled, cputime);
4266 * Account system cpu time to a process.
4267 * @p: the process that the cpu time gets accounted to
4268 * @hardirq_offset: the offset to subtract from hardirq_count()
4269 * @cputime: the cpu time spent in kernel space since the last update
4271 void account_system_time(struct task_struct *p, int hardirq_offset,
4274 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4275 struct rq *rq = this_rq();
4278 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0))
4279 return account_guest_time(p, cputime);
4281 p->stime = cputime_add(p->stime, cputime);
4283 /* Add system time to cpustat. */
4284 tmp = cputime_to_cputime64(cputime);
4285 if (hardirq_count() - hardirq_offset)
4286 cpustat->irq = cputime64_add(cpustat->irq, tmp);
4287 else if (softirq_count())
4288 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
4289 else if (p != rq->idle)
4290 cpustat->system = cputime64_add(cpustat->system, tmp);
4291 else if (atomic_read(&rq->nr_iowait) > 0)
4292 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
4294 cpustat->idle = cputime64_add(cpustat->idle, tmp);
4295 /* Account for system time used */
4296 acct_update_integrals(p);
4300 * Account scaled system cpu time to a process.
4301 * @p: the process that the cpu time gets accounted to
4302 * @hardirq_offset: the offset to subtract from hardirq_count()
4303 * @cputime: the cpu time spent in kernel space since the last update
4305 void account_system_time_scaled(struct task_struct *p, cputime_t cputime)
4307 p->stimescaled = cputime_add(p->stimescaled, cputime);
4311 * Account for involuntary wait time.
4312 * @p: the process from which the cpu time has been stolen
4313 * @steal: the cpu time spent in involuntary wait
4315 void account_steal_time(struct task_struct *p, cputime_t steal)
4317 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
4318 cputime64_t tmp = cputime_to_cputime64(steal);
4319 struct rq *rq = this_rq();
4321 if (p == rq->idle) {
4322 p->stime = cputime_add(p->stime, steal);
4323 if (atomic_read(&rq->nr_iowait) > 0)
4324 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
4326 cpustat->idle = cputime64_add(cpustat->idle, tmp);
4328 cpustat->steal = cputime64_add(cpustat->steal, tmp);
4332 * This function gets called by the timer code, with HZ frequency.
4333 * We call it with interrupts disabled.
4335 * It also gets called by the fork code, when changing the parent's
4338 void scheduler_tick(void)
4340 int cpu = smp_processor_id();
4341 struct rq *rq = cpu_rq(cpu);
4342 struct task_struct *curr = rq->curr;
4343 u64 next_tick = rq->tick_timestamp + TICK_NSEC;
4345 spin_lock(&rq->lock);
4346 __update_rq_clock(rq);
4348 * Let rq->clock advance by at least TICK_NSEC:
4350 if (unlikely(rq->clock < next_tick)) {
4351 rq->clock = next_tick;
4352 rq->clock_underflows++;
4354 rq->tick_timestamp = rq->clock;
4355 update_last_tick_seen(rq);
4356 update_cpu_load(rq);
4357 curr->sched_class->task_tick(rq, curr, 0);
4358 spin_unlock(&rq->lock);
4361 rq->idle_at_tick = idle_cpu(cpu);
4362 trigger_load_balance(rq, cpu);
4366 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
4368 void __kprobes add_preempt_count(int val)
4373 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
4375 preempt_count() += val;
4377 * Spinlock count overflowing soon?
4379 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
4382 EXPORT_SYMBOL(add_preempt_count);
4384 void __kprobes sub_preempt_count(int val)
4389 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
4392 * Is the spinlock portion underflowing?
4394 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
4395 !(preempt_count() & PREEMPT_MASK)))
4398 preempt_count() -= val;
4400 EXPORT_SYMBOL(sub_preempt_count);
4405 * Print scheduling while atomic bug:
4407 static noinline void __schedule_bug(struct task_struct *prev)
4409 struct pt_regs *regs = get_irq_regs();
4411 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
4412 prev->comm, prev->pid, preempt_count());
4414 debug_show_held_locks(prev);
4415 if (irqs_disabled())
4416 print_irqtrace_events(prev);
4425 * Various schedule()-time debugging checks and statistics:
4427 static inline void schedule_debug(struct task_struct *prev)
4430 * Test if we are atomic. Since do_exit() needs to call into
4431 * schedule() atomically, we ignore that path for now.
4432 * Otherwise, whine if we are scheduling when we should not be.
4434 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev->exit_state))
4435 __schedule_bug(prev);
4437 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
4439 schedstat_inc(this_rq(), sched_count);
4440 #ifdef CONFIG_SCHEDSTATS
4441 if (unlikely(prev->lock_depth >= 0)) {
4442 schedstat_inc(this_rq(), bkl_count);
4443 schedstat_inc(prev, sched_info.bkl_count);
4449 * Pick up the highest-prio task:
4451 static inline struct task_struct *
4452 pick_next_task(struct rq *rq, struct task_struct *prev)
4454 const struct sched_class *class;
4455 struct task_struct *p;
4458 * Optimization: we know that if all tasks are in
4459 * the fair class we can call that function directly:
4461 if (likely(rq->nr_running == rq->cfs.nr_running)) {
4462 p = fair_sched_class.pick_next_task(rq);
4467 class = sched_class_highest;
4469 p = class->pick_next_task(rq);
4473 * Will never be NULL as the idle class always
4474 * returns a non-NULL p:
4476 class = class->next;
4481 * schedule() is the main scheduler function.
4483 asmlinkage void __sched schedule(void)
4485 struct task_struct *prev, *next;
4486 unsigned long *switch_count;
4492 cpu = smp_processor_id();
4496 switch_count = &prev->nivcsw;
4498 release_kernel_lock(prev);
4499 need_resched_nonpreemptible:
4501 schedule_debug(prev);
4506 * Do the rq-clock update outside the rq lock:
4508 local_irq_disable();
4509 __update_rq_clock(rq);
4510 spin_lock(&rq->lock);
4511 clear_tsk_need_resched(prev);
4513 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
4514 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
4515 signal_pending(prev))) {
4516 prev->state = TASK_RUNNING;
4518 deactivate_task(rq, prev, 1);
4520 switch_count = &prev->nvcsw;
4524 if (prev->sched_class->pre_schedule)
4525 prev->sched_class->pre_schedule(rq, prev);
4528 if (unlikely(!rq->nr_running))
4529 idle_balance(cpu, rq);
4531 prev->sched_class->put_prev_task(rq, prev);
4532 next = pick_next_task(rq, prev);
4534 sched_info_switch(prev, next);
4536 if (likely(prev != next)) {
4541 context_switch(rq, prev, next); /* unlocks the rq */
4543 * the context switch might have flipped the stack from under
4544 * us, hence refresh the local variables.
4546 cpu = smp_processor_id();
4549 spin_unlock_irq(&rq->lock);
4553 if (unlikely(reacquire_kernel_lock(current) < 0))
4554 goto need_resched_nonpreemptible;
4556 preempt_enable_no_resched();
4557 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
4560 EXPORT_SYMBOL(schedule);
4562 #ifdef CONFIG_PREEMPT
4564 * this is the entry point to schedule() from in-kernel preemption
4565 * off of preempt_enable. Kernel preemptions off return from interrupt
4566 * occur there and call schedule directly.
4568 asmlinkage void __sched preempt_schedule(void)
4570 struct thread_info *ti = current_thread_info();
4571 struct task_struct *task = current;
4572 int saved_lock_depth;
4575 * If there is a non-zero preempt_count or interrupts are disabled,
4576 * we do not want to preempt the current task. Just return..
4578 if (likely(ti->preempt_count || irqs_disabled()))
4582 add_preempt_count(PREEMPT_ACTIVE);
4585 * We keep the big kernel semaphore locked, but we
4586 * clear ->lock_depth so that schedule() doesnt
4587 * auto-release the semaphore:
4589 saved_lock_depth = task->lock_depth;
4590 task->lock_depth = -1;
4592 task->lock_depth = saved_lock_depth;
4593 sub_preempt_count(PREEMPT_ACTIVE);
4596 * Check again in case we missed a preemption opportunity
4597 * between schedule and now.
4600 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4602 EXPORT_SYMBOL(preempt_schedule);
4605 * this is the entry point to schedule() from kernel preemption
4606 * off of irq context.
4607 * Note, that this is called and return with irqs disabled. This will
4608 * protect us against recursive calling from irq.
4610 asmlinkage void __sched preempt_schedule_irq(void)
4612 struct thread_info *ti = current_thread_info();
4613 struct task_struct *task = current;
4614 int saved_lock_depth;
4616 /* Catch callers which need to be fixed */
4617 BUG_ON(ti->preempt_count || !irqs_disabled());
4620 add_preempt_count(PREEMPT_ACTIVE);
4623 * We keep the big kernel semaphore locked, but we
4624 * clear ->lock_depth so that schedule() doesnt
4625 * auto-release the semaphore:
4627 saved_lock_depth = task->lock_depth;
4628 task->lock_depth = -1;
4631 local_irq_disable();
4632 task->lock_depth = saved_lock_depth;
4633 sub_preempt_count(PREEMPT_ACTIVE);
4636 * Check again in case we missed a preemption opportunity
4637 * between schedule and now.
4640 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4643 #endif /* CONFIG_PREEMPT */
4645 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
4648 return try_to_wake_up(curr->private, mode, sync);
4650 EXPORT_SYMBOL(default_wake_function);
4653 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4654 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4655 * number) then we wake all the non-exclusive tasks and one exclusive task.
4657 * There are circumstances in which we can try to wake a task which has already
4658 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4659 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4661 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
4662 int nr_exclusive, int sync, void *key)
4664 wait_queue_t *curr, *next;
4666 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
4667 unsigned flags = curr->flags;
4669 if (curr->func(curr, mode, sync, key) &&
4670 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
4676 * __wake_up - wake up threads blocked on a waitqueue.
4678 * @mode: which threads
4679 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4680 * @key: is directly passed to the wakeup function
4682 void __wake_up(wait_queue_head_t *q, unsigned int mode,
4683 int nr_exclusive, void *key)
4685 unsigned long flags;
4687 spin_lock_irqsave(&q->lock, flags);
4688 __wake_up_common(q, mode, nr_exclusive, 0, key);
4689 spin_unlock_irqrestore(&q->lock, flags);
4691 EXPORT_SYMBOL(__wake_up);
4694 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4696 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4698 __wake_up_common(q, mode, 1, 0, NULL);
4702 * __wake_up_sync - wake up threads blocked on a waitqueue.
4704 * @mode: which threads
4705 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4707 * The sync wakeup differs that the waker knows that it will schedule
4708 * away soon, so while the target thread will be woken up, it will not
4709 * be migrated to another CPU - ie. the two threads are 'synchronized'
4710 * with each other. This can prevent needless bouncing between CPUs.
4712 * On UP it can prevent extra preemption.
4715 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4717 unsigned long flags;
4723 if (unlikely(!nr_exclusive))
4726 spin_lock_irqsave(&q->lock, flags);
4727 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
4728 spin_unlock_irqrestore(&q->lock, flags);
4730 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
4732 void complete(struct completion *x)
4734 unsigned long flags;
4736 spin_lock_irqsave(&x->wait.lock, flags);
4738 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4739 spin_unlock_irqrestore(&x->wait.lock, flags);
4741 EXPORT_SYMBOL(complete);
4743 void complete_all(struct completion *x)
4745 unsigned long flags;
4747 spin_lock_irqsave(&x->wait.lock, flags);
4748 x->done += UINT_MAX/2;
4749 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4750 spin_unlock_irqrestore(&x->wait.lock, flags);
4752 EXPORT_SYMBOL(complete_all);
4754 static inline long __sched
4755 do_wait_for_common(struct completion *x, long timeout, int state)
4758 DECLARE_WAITQUEUE(wait, current);
4760 wait.flags |= WQ_FLAG_EXCLUSIVE;
4761 __add_wait_queue_tail(&x->wait, &wait);
4763 if ((state == TASK_INTERRUPTIBLE &&
4764 signal_pending(current)) ||
4765 (state == TASK_KILLABLE &&
4766 fatal_signal_pending(current))) {
4767 __remove_wait_queue(&x->wait, &wait);
4768 return -ERESTARTSYS;
4770 __set_current_state(state);
4771 spin_unlock_irq(&x->wait.lock);
4772 timeout = schedule_timeout(timeout);
4773 spin_lock_irq(&x->wait.lock);
4775 __remove_wait_queue(&x->wait, &wait);
4779 __remove_wait_queue(&x->wait, &wait);
4786 wait_for_common(struct completion *x, long timeout, int state)
4790 spin_lock_irq(&x->wait.lock);
4791 timeout = do_wait_for_common(x, timeout, state);
4792 spin_unlock_irq(&x->wait.lock);
4796 void __sched wait_for_completion(struct completion *x)
4798 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4800 EXPORT_SYMBOL(wait_for_completion);
4802 unsigned long __sched
4803 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4805 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4807 EXPORT_SYMBOL(wait_for_completion_timeout);
4809 int __sched wait_for_completion_interruptible(struct completion *x)
4811 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4812 if (t == -ERESTARTSYS)
4816 EXPORT_SYMBOL(wait_for_completion_interruptible);
4818 unsigned long __sched
4819 wait_for_completion_interruptible_timeout(struct completion *x,
4820 unsigned long timeout)
4822 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4824 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4826 int __sched wait_for_completion_killable(struct completion *x)
4828 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4829 if (t == -ERESTARTSYS)
4833 EXPORT_SYMBOL(wait_for_completion_killable);
4836 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4838 unsigned long flags;
4841 init_waitqueue_entry(&wait, current);
4843 __set_current_state(state);
4845 spin_lock_irqsave(&q->lock, flags);
4846 __add_wait_queue(q, &wait);
4847 spin_unlock(&q->lock);
4848 timeout = schedule_timeout(timeout);
4849 spin_lock_irq(&q->lock);
4850 __remove_wait_queue(q, &wait);
4851 spin_unlock_irqrestore(&q->lock, flags);
4856 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4858 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4860 EXPORT_SYMBOL(interruptible_sleep_on);
4863 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4865 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4867 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4869 void __sched sleep_on(wait_queue_head_t *q)
4871 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4873 EXPORT_SYMBOL(sleep_on);
4875 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4877 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
4879 EXPORT_SYMBOL(sleep_on_timeout);
4881 #ifdef CONFIG_RT_MUTEXES
4884 * rt_mutex_setprio - set the current priority of a task
4886 * @prio: prio value (kernel-internal form)
4888 * This function changes the 'effective' priority of a task. It does
4889 * not touch ->normal_prio like __setscheduler().
4891 * Used by the rt_mutex code to implement priority inheritance logic.
4893 void rt_mutex_setprio(struct task_struct *p, int prio)
4895 unsigned long flags;
4896 int oldprio, on_rq, running;
4898 const struct sched_class *prev_class = p->sched_class;
4900 BUG_ON(prio < 0 || prio > MAX_PRIO);
4902 rq = task_rq_lock(p, &flags);
4903 update_rq_clock(rq);
4906 on_rq = p->se.on_rq;
4907 running = task_current(rq, p);
4909 dequeue_task(rq, p, 0);
4911 p->sched_class->put_prev_task(rq, p);
4914 p->sched_class = &rt_sched_class;
4916 p->sched_class = &fair_sched_class;
4921 p->sched_class->set_curr_task(rq);
4923 enqueue_task(rq, p, 0);
4925 check_class_changed(rq, p, prev_class, oldprio, running);
4927 task_rq_unlock(rq, &flags);
4932 void set_user_nice(struct task_struct *p, long nice)
4934 int old_prio, delta, on_rq;
4935 unsigned long flags;
4938 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4941 * We have to be careful, if called from sys_setpriority(),
4942 * the task might be in the middle of scheduling on another CPU.
4944 rq = task_rq_lock(p, &flags);
4945 update_rq_clock(rq);
4947 * The RT priorities are set via sched_setscheduler(), but we still
4948 * allow the 'normal' nice value to be set - but as expected
4949 * it wont have any effect on scheduling until the task is
4950 * SCHED_FIFO/SCHED_RR:
4952 if (task_has_rt_policy(p)) {
4953 p->static_prio = NICE_TO_PRIO(nice);
4956 on_rq = p->se.on_rq;
4958 dequeue_task(rq, p, 0);
4960 p->static_prio = NICE_TO_PRIO(nice);
4963 p->prio = effective_prio(p);
4964 delta = p->prio - old_prio;
4967 enqueue_task(rq, p, 0);
4969 * If the task increased its priority or is running and
4970 * lowered its priority, then reschedule its CPU:
4972 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4973 resched_task(rq->curr);
4976 task_rq_unlock(rq, &flags);
4978 EXPORT_SYMBOL(set_user_nice);
4981 * can_nice - check if a task can reduce its nice value
4985 int can_nice(const struct task_struct *p, const int nice)
4987 /* convert nice value [19,-20] to rlimit style value [1,40] */
4988 int nice_rlim = 20 - nice;
4990 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
4991 capable(CAP_SYS_NICE));
4994 #ifdef __ARCH_WANT_SYS_NICE
4997 * sys_nice - change the priority of the current process.
4998 * @increment: priority increment
5000 * sys_setpriority is a more generic, but much slower function that
5001 * does similar things.
5003 asmlinkage long sys_nice(int increment)
5008 * Setpriority might change our priority at the same moment.
5009 * We don't have to worry. Conceptually one call occurs first
5010 * and we have a single winner.
5012 if (increment < -40)
5017 nice = PRIO_TO_NICE(current->static_prio) + increment;
5023 if (increment < 0 && !can_nice(current, nice))
5026 retval = security_task_setnice(current, nice);
5030 set_user_nice(current, nice);
5037 * task_prio - return the priority value of a given task.
5038 * @p: the task in question.
5040 * This is the priority value as seen by users in /proc.
5041 * RT tasks are offset by -200. Normal tasks are centered
5042 * around 0, value goes from -16 to +15.
5044 int task_prio(const struct task_struct *p)
5046 return p->prio - MAX_RT_PRIO;
5050 * task_nice - return the nice value of a given task.
5051 * @p: the task in question.
5053 int task_nice(const struct task_struct *p)
5055 return TASK_NICE(p);
5057 EXPORT_SYMBOL(task_nice);
5060 * idle_cpu - is a given cpu idle currently?
5061 * @cpu: the processor in question.
5063 int idle_cpu(int cpu)
5065 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
5069 * idle_task - return the idle task for a given cpu.
5070 * @cpu: the processor in question.
5072 struct task_struct *idle_task(int cpu)
5074 return cpu_rq(cpu)->idle;
5078 * find_process_by_pid - find a process with a matching PID value.
5079 * @pid: the pid in question.
5081 static struct task_struct *find_process_by_pid(pid_t pid)
5083 return pid ? find_task_by_vpid(pid) : current;
5086 /* Actually do priority change: must hold rq lock. */
5088 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
5090 BUG_ON(p->se.on_rq);
5093 switch (p->policy) {
5097 p->sched_class = &fair_sched_class;
5101 p->sched_class = &rt_sched_class;
5105 p->rt_priority = prio;
5106 p->normal_prio = normal_prio(p);
5107 /* we are holding p->pi_lock already */
5108 p->prio = rt_mutex_getprio(p);
5113 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
5114 * @p: the task in question.
5115 * @policy: new policy.
5116 * @param: structure containing the new RT priority.
5118 * NOTE that the task may be already dead.
5120 int sched_setscheduler(struct task_struct *p, int policy,
5121 struct sched_param *param)
5123 int retval, oldprio, oldpolicy = -1, on_rq, running;
5124 unsigned long flags;
5125 const struct sched_class *prev_class = p->sched_class;
5128 /* may grab non-irq protected spin_locks */
5129 BUG_ON(in_interrupt());
5131 /* double check policy once rq lock held */
5133 policy = oldpolicy = p->policy;
5134 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
5135 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
5136 policy != SCHED_IDLE)
5139 * Valid priorities for SCHED_FIFO and SCHED_RR are
5140 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
5141 * SCHED_BATCH and SCHED_IDLE is 0.
5143 if (param->sched_priority < 0 ||
5144 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
5145 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
5147 if (rt_policy(policy) != (param->sched_priority != 0))
5151 * Allow unprivileged RT tasks to decrease priority:
5153 if (!capable(CAP_SYS_NICE)) {
5154 if (rt_policy(policy)) {
5155 unsigned long rlim_rtprio;
5157 if (!lock_task_sighand(p, &flags))
5159 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
5160 unlock_task_sighand(p, &flags);
5162 /* can't set/change the rt policy */
5163 if (policy != p->policy && !rlim_rtprio)
5166 /* can't increase priority */
5167 if (param->sched_priority > p->rt_priority &&
5168 param->sched_priority > rlim_rtprio)
5172 * Like positive nice levels, dont allow tasks to
5173 * move out of SCHED_IDLE either:
5175 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
5178 /* can't change other user's priorities */
5179 if ((current->euid != p->euid) &&
5180 (current->euid != p->uid))
5184 #ifdef CONFIG_RT_GROUP_SCHED
5186 * Do not allow realtime tasks into groups that have no runtime
5189 if (rt_policy(policy) && task_group(p)->rt_bandwidth.rt_runtime == 0)
5193 retval = security_task_setscheduler(p, policy, param);
5197 * make sure no PI-waiters arrive (or leave) while we are
5198 * changing the priority of the task:
5200 spin_lock_irqsave(&p->pi_lock, flags);
5202 * To be able to change p->policy safely, the apropriate
5203 * runqueue lock must be held.
5205 rq = __task_rq_lock(p);
5206 /* recheck policy now with rq lock held */
5207 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
5208 policy = oldpolicy = -1;
5209 __task_rq_unlock(rq);
5210 spin_unlock_irqrestore(&p->pi_lock, flags);
5213 update_rq_clock(rq);
5214 on_rq = p->se.on_rq;
5215 running = task_current(rq, p);
5217 deactivate_task(rq, p, 0);
5219 p->sched_class->put_prev_task(rq, p);
5222 __setscheduler(rq, p, policy, param->sched_priority);
5225 p->sched_class->set_curr_task(rq);
5227 activate_task(rq, p, 0);
5229 check_class_changed(rq, p, prev_class, oldprio, running);
5231 __task_rq_unlock(rq);
5232 spin_unlock_irqrestore(&p->pi_lock, flags);
5234 rt_mutex_adjust_pi(p);
5238 EXPORT_SYMBOL_GPL(sched_setscheduler);
5241 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5243 struct sched_param lparam;
5244 struct task_struct *p;
5247 if (!param || pid < 0)
5249 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
5254 p = find_process_by_pid(pid);
5256 retval = sched_setscheduler(p, policy, &lparam);
5263 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
5264 * @pid: the pid in question.
5265 * @policy: new policy.
5266 * @param: structure containing the new RT priority.
5269 sys_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5271 /* negative values for policy are not valid */
5275 return do_sched_setscheduler(pid, policy, param);
5279 * sys_sched_setparam - set/change the RT priority of a thread
5280 * @pid: the pid in question.
5281 * @param: structure containing the new RT priority.
5283 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
5285 return do_sched_setscheduler(pid, -1, param);
5289 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
5290 * @pid: the pid in question.
5292 asmlinkage long sys_sched_getscheduler(pid_t pid)
5294 struct task_struct *p;
5301 read_lock(&tasklist_lock);
5302 p = find_process_by_pid(pid);
5304 retval = security_task_getscheduler(p);
5308 read_unlock(&tasklist_lock);
5313 * sys_sched_getscheduler - get the RT priority of a thread
5314 * @pid: the pid in question.
5315 * @param: structure containing the RT priority.
5317 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
5319 struct sched_param lp;
5320 struct task_struct *p;
5323 if (!param || pid < 0)
5326 read_lock(&tasklist_lock);
5327 p = find_process_by_pid(pid);
5332 retval = security_task_getscheduler(p);
5336 lp.sched_priority = p->rt_priority;
5337 read_unlock(&tasklist_lock);
5340 * This one might sleep, we cannot do it with a spinlock held ...
5342 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
5347 read_unlock(&tasklist_lock);
5351 long sched_setaffinity(pid_t pid, const cpumask_t *in_mask)
5353 cpumask_t cpus_allowed;
5354 cpumask_t new_mask = *in_mask;
5355 struct task_struct *p;
5359 read_lock(&tasklist_lock);
5361 p = find_process_by_pid(pid);
5363 read_unlock(&tasklist_lock);
5369 * It is not safe to call set_cpus_allowed with the
5370 * tasklist_lock held. We will bump the task_struct's
5371 * usage count and then drop tasklist_lock.
5374 read_unlock(&tasklist_lock);
5377 if ((current->euid != p->euid) && (current->euid != p->uid) &&
5378 !capable(CAP_SYS_NICE))
5381 retval = security_task_setscheduler(p, 0, NULL);
5385 cpuset_cpus_allowed(p, &cpus_allowed);
5386 cpus_and(new_mask, new_mask, cpus_allowed);
5388 retval = set_cpus_allowed_ptr(p, &new_mask);
5391 cpuset_cpus_allowed(p, &cpus_allowed);
5392 if (!cpus_subset(new_mask, cpus_allowed)) {
5394 * We must have raced with a concurrent cpuset
5395 * update. Just reset the cpus_allowed to the
5396 * cpuset's cpus_allowed
5398 new_mask = cpus_allowed;
5408 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
5409 cpumask_t *new_mask)
5411 if (len < sizeof(cpumask_t)) {
5412 memset(new_mask, 0, sizeof(cpumask_t));
5413 } else if (len > sizeof(cpumask_t)) {
5414 len = sizeof(cpumask_t);
5416 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
5420 * sys_sched_setaffinity - set the cpu affinity of a process
5421 * @pid: pid of the process
5422 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5423 * @user_mask_ptr: user-space pointer to the new cpu mask
5425 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
5426 unsigned long __user *user_mask_ptr)
5431 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
5435 return sched_setaffinity(pid, &new_mask);
5439 * Represents all cpu's present in the system
5440 * In systems capable of hotplug, this map could dynamically grow
5441 * as new cpu's are detected in the system via any platform specific
5442 * method, such as ACPI for e.g.
5445 cpumask_t cpu_present_map __read_mostly;
5446 EXPORT_SYMBOL(cpu_present_map);
5449 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
5450 EXPORT_SYMBOL(cpu_online_map);
5452 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
5453 EXPORT_SYMBOL(cpu_possible_map);
5456 long sched_getaffinity(pid_t pid, cpumask_t *mask)
5458 struct task_struct *p;
5462 read_lock(&tasklist_lock);
5465 p = find_process_by_pid(pid);
5469 retval = security_task_getscheduler(p);
5473 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
5476 read_unlock(&tasklist_lock);
5483 * sys_sched_getaffinity - get the cpu affinity of a process
5484 * @pid: pid of the process
5485 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5486 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5488 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
5489 unsigned long __user *user_mask_ptr)
5494 if (len < sizeof(cpumask_t))
5497 ret = sched_getaffinity(pid, &mask);
5501 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
5504 return sizeof(cpumask_t);
5508 * sys_sched_yield - yield the current processor to other threads.
5510 * This function yields the current CPU to other tasks. If there are no
5511 * other threads running on this CPU then this function will return.
5513 asmlinkage long sys_sched_yield(void)
5515 struct rq *rq = this_rq_lock();
5517 schedstat_inc(rq, yld_count);
5518 current->sched_class->yield_task(rq);
5521 * Since we are going to call schedule() anyway, there's
5522 * no need to preempt or enable interrupts:
5524 __release(rq->lock);
5525 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5526 _raw_spin_unlock(&rq->lock);
5527 preempt_enable_no_resched();
5534 static void __cond_resched(void)
5536 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5537 __might_sleep(__FILE__, __LINE__);
5540 * The BKS might be reacquired before we have dropped
5541 * PREEMPT_ACTIVE, which could trigger a second
5542 * cond_resched() call.
5545 add_preempt_count(PREEMPT_ACTIVE);
5547 sub_preempt_count(PREEMPT_ACTIVE);
5548 } while (need_resched());
5551 #if !defined(CONFIG_PREEMPT) || defined(CONFIG_PREEMPT_VOLUNTARY)
5552 int __sched _cond_resched(void)
5554 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
5555 system_state == SYSTEM_RUNNING) {
5561 EXPORT_SYMBOL(_cond_resched);
5565 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5566 * call schedule, and on return reacquire the lock.
5568 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5569 * operations here to prevent schedule() from being called twice (once via
5570 * spin_unlock(), once by hand).
5572 int cond_resched_lock(spinlock_t *lock)
5574 int resched = need_resched() && system_state == SYSTEM_RUNNING;
5577 if (spin_needbreak(lock) || resched) {
5579 if (resched && need_resched())
5588 EXPORT_SYMBOL(cond_resched_lock);
5590 int __sched cond_resched_softirq(void)
5592 BUG_ON(!in_softirq());
5594 if (need_resched() && system_state == SYSTEM_RUNNING) {
5602 EXPORT_SYMBOL(cond_resched_softirq);
5605 * yield - yield the current processor to other threads.
5607 * This is a shortcut for kernel-space yielding - it marks the
5608 * thread runnable and calls sys_sched_yield().
5610 void __sched yield(void)
5612 set_current_state(TASK_RUNNING);
5615 EXPORT_SYMBOL(yield);
5618 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5619 * that process accounting knows that this is a task in IO wait state.
5621 * But don't do that if it is a deliberate, throttling IO wait (this task
5622 * has set its backing_dev_info: the queue against which it should throttle)
5624 void __sched io_schedule(void)
5626 struct rq *rq = &__raw_get_cpu_var(runqueues);
5628 delayacct_blkio_start();
5629 atomic_inc(&rq->nr_iowait);
5631 atomic_dec(&rq->nr_iowait);
5632 delayacct_blkio_end();
5634 EXPORT_SYMBOL(io_schedule);
5636 long __sched io_schedule_timeout(long timeout)
5638 struct rq *rq = &__raw_get_cpu_var(runqueues);
5641 delayacct_blkio_start();
5642 atomic_inc(&rq->nr_iowait);
5643 ret = schedule_timeout(timeout);
5644 atomic_dec(&rq->nr_iowait);
5645 delayacct_blkio_end();
5650 * sys_sched_get_priority_max - return maximum RT priority.
5651 * @policy: scheduling class.
5653 * this syscall returns the maximum rt_priority that can be used
5654 * by a given scheduling class.
5656 asmlinkage long sys_sched_get_priority_max(int policy)
5663 ret = MAX_USER_RT_PRIO-1;
5675 * sys_sched_get_priority_min - return minimum RT priority.
5676 * @policy: scheduling class.
5678 * this syscall returns the minimum rt_priority that can be used
5679 * by a given scheduling class.
5681 asmlinkage long sys_sched_get_priority_min(int policy)
5699 * sys_sched_rr_get_interval - return the default timeslice of a process.
5700 * @pid: pid of the process.
5701 * @interval: userspace pointer to the timeslice value.
5703 * this syscall writes the default timeslice value of a given process
5704 * into the user-space timespec buffer. A value of '0' means infinity.
5707 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
5709 struct task_struct *p;
5710 unsigned int time_slice;
5718 read_lock(&tasklist_lock);
5719 p = find_process_by_pid(pid);
5723 retval = security_task_getscheduler(p);
5728 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5729 * tasks that are on an otherwise idle runqueue:
5732 if (p->policy == SCHED_RR) {
5733 time_slice = DEF_TIMESLICE;
5734 } else if (p->policy != SCHED_FIFO) {
5735 struct sched_entity *se = &p->se;
5736 unsigned long flags;
5739 rq = task_rq_lock(p, &flags);
5740 if (rq->cfs.load.weight)
5741 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
5742 task_rq_unlock(rq, &flags);
5744 read_unlock(&tasklist_lock);
5745 jiffies_to_timespec(time_slice, &t);
5746 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5750 read_unlock(&tasklist_lock);
5754 static const char stat_nam[] = "RSDTtZX";
5756 void sched_show_task(struct task_struct *p)
5758 unsigned long free = 0;
5761 state = p->state ? __ffs(p->state) + 1 : 0;
5762 printk(KERN_INFO "%-13.13s %c", p->comm,
5763 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5764 #if BITS_PER_LONG == 32
5765 if (state == TASK_RUNNING)
5766 printk(KERN_CONT " running ");
5768 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5770 if (state == TASK_RUNNING)
5771 printk(KERN_CONT " running task ");
5773 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5775 #ifdef CONFIG_DEBUG_STACK_USAGE
5777 unsigned long *n = end_of_stack(p);
5780 free = (unsigned long)n - (unsigned long)end_of_stack(p);
5783 printk(KERN_CONT "%5lu %5d %6d\n", free,
5784 task_pid_nr(p), task_pid_nr(p->real_parent));
5786 show_stack(p, NULL);
5789 void show_state_filter(unsigned long state_filter)
5791 struct task_struct *g, *p;
5793 #if BITS_PER_LONG == 32
5795 " task PC stack pid father\n");
5798 " task PC stack pid father\n");
5800 read_lock(&tasklist_lock);
5801 do_each_thread(g, p) {
5803 * reset the NMI-timeout, listing all files on a slow
5804 * console might take alot of time:
5806 touch_nmi_watchdog();
5807 if (!state_filter || (p->state & state_filter))
5809 } while_each_thread(g, p);
5811 touch_all_softlockup_watchdogs();
5813 #ifdef CONFIG_SCHED_DEBUG
5814 sysrq_sched_debug_show();
5816 read_unlock(&tasklist_lock);
5818 * Only show locks if all tasks are dumped:
5820 if (state_filter == -1)
5821 debug_show_all_locks();
5824 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5826 idle->sched_class = &idle_sched_class;
5830 * init_idle - set up an idle thread for a given CPU
5831 * @idle: task in question
5832 * @cpu: cpu the idle task belongs to
5834 * NOTE: this function does not set the idle thread's NEED_RESCHED
5835 * flag, to make booting more robust.
5837 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5839 struct rq *rq = cpu_rq(cpu);
5840 unsigned long flags;
5843 idle->se.exec_start = sched_clock();
5845 idle->prio = idle->normal_prio = MAX_PRIO;
5846 idle->cpus_allowed = cpumask_of_cpu(cpu);
5847 __set_task_cpu(idle, cpu);
5849 spin_lock_irqsave(&rq->lock, flags);
5850 rq->curr = rq->idle = idle;
5851 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5854 spin_unlock_irqrestore(&rq->lock, flags);
5856 /* Set the preempt count _outside_ the spinlocks! */
5857 task_thread_info(idle)->preempt_count = 0;
5860 * The idle tasks have their own, simple scheduling class:
5862 idle->sched_class = &idle_sched_class;
5866 * In a system that switches off the HZ timer nohz_cpu_mask
5867 * indicates which cpus entered this state. This is used
5868 * in the rcu update to wait only for active cpus. For system
5869 * which do not switch off the HZ timer nohz_cpu_mask should
5870 * always be CPU_MASK_NONE.
5872 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
5875 * Increase the granularity value when there are more CPUs,
5876 * because with more CPUs the 'effective latency' as visible
5877 * to users decreases. But the relationship is not linear,
5878 * so pick a second-best guess by going with the log2 of the
5881 * This idea comes from the SD scheduler of Con Kolivas:
5883 static inline void sched_init_granularity(void)
5885 unsigned int factor = 1 + ilog2(num_online_cpus());
5886 const unsigned long limit = 200000000;
5888 sysctl_sched_min_granularity *= factor;
5889 if (sysctl_sched_min_granularity > limit)
5890 sysctl_sched_min_granularity = limit;
5892 sysctl_sched_latency *= factor;
5893 if (sysctl_sched_latency > limit)
5894 sysctl_sched_latency = limit;
5896 sysctl_sched_wakeup_granularity *= factor;
5901 * This is how migration works:
5903 * 1) we queue a struct migration_req structure in the source CPU's
5904 * runqueue and wake up that CPU's migration thread.
5905 * 2) we down() the locked semaphore => thread blocks.
5906 * 3) migration thread wakes up (implicitly it forces the migrated
5907 * thread off the CPU)
5908 * 4) it gets the migration request and checks whether the migrated
5909 * task is still in the wrong runqueue.
5910 * 5) if it's in the wrong runqueue then the migration thread removes
5911 * it and puts it into the right queue.
5912 * 6) migration thread up()s the semaphore.
5913 * 7) we wake up and the migration is done.
5917 * Change a given task's CPU affinity. Migrate the thread to a
5918 * proper CPU and schedule it away if the CPU it's executing on
5919 * is removed from the allowed bitmask.
5921 * NOTE: the caller must have a valid reference to the task, the
5922 * task must not exit() & deallocate itself prematurely. The
5923 * call is not atomic; no spinlocks may be held.
5925 int set_cpus_allowed_ptr(struct task_struct *p, const cpumask_t *new_mask)
5927 struct migration_req req;
5928 unsigned long flags;
5932 rq = task_rq_lock(p, &flags);
5933 if (!cpus_intersects(*new_mask, cpu_online_map)) {
5938 if (p->sched_class->set_cpus_allowed)
5939 p->sched_class->set_cpus_allowed(p, new_mask);
5941 p->cpus_allowed = *new_mask;
5942 p->rt.nr_cpus_allowed = cpus_weight(*new_mask);
5945 /* Can the task run on the task's current CPU? If so, we're done */
5946 if (cpu_isset(task_cpu(p), *new_mask))
5949 if (migrate_task(p, any_online_cpu(*new_mask), &req)) {
5950 /* Need help from migration thread: drop lock and wait. */
5951 task_rq_unlock(rq, &flags);
5952 wake_up_process(rq->migration_thread);
5953 wait_for_completion(&req.done);
5954 tlb_migrate_finish(p->mm);
5958 task_rq_unlock(rq, &flags);
5962 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
5965 * Move (not current) task off this cpu, onto dest cpu. We're doing
5966 * this because either it can't run here any more (set_cpus_allowed()
5967 * away from this CPU, or CPU going down), or because we're
5968 * attempting to rebalance this task on exec (sched_exec).
5970 * So we race with normal scheduler movements, but that's OK, as long
5971 * as the task is no longer on this CPU.
5973 * Returns non-zero if task was successfully migrated.
5975 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
5977 struct rq *rq_dest, *rq_src;
5980 if (unlikely(cpu_is_offline(dest_cpu)))
5983 rq_src = cpu_rq(src_cpu);
5984 rq_dest = cpu_rq(dest_cpu);
5986 double_rq_lock(rq_src, rq_dest);
5987 /* Already moved. */
5988 if (task_cpu(p) != src_cpu)
5990 /* Affinity changed (again). */
5991 if (!cpu_isset(dest_cpu, p->cpus_allowed))
5994 on_rq = p->se.on_rq;
5996 deactivate_task(rq_src, p, 0);
5998 set_task_cpu(p, dest_cpu);
6000 activate_task(rq_dest, p, 0);
6001 check_preempt_curr(rq_dest, p);
6005 double_rq_unlock(rq_src, rq_dest);
6010 * migration_thread - this is a highprio system thread that performs
6011 * thread migration by bumping thread off CPU then 'pushing' onto
6014 static int migration_thread(void *data)
6016 int cpu = (long)data;
6020 BUG_ON(rq->migration_thread != current);
6022 set_current_state(TASK_INTERRUPTIBLE);
6023 while (!kthread_should_stop()) {
6024 struct migration_req *req;
6025 struct list_head *head;
6027 spin_lock_irq(&rq->lock);
6029 if (cpu_is_offline(cpu)) {
6030 spin_unlock_irq(&rq->lock);
6034 if (rq->active_balance) {
6035 active_load_balance(rq, cpu);
6036 rq->active_balance = 0;
6039 head = &rq->migration_queue;
6041 if (list_empty(head)) {
6042 spin_unlock_irq(&rq->lock);
6044 set_current_state(TASK_INTERRUPTIBLE);
6047 req = list_entry(head->next, struct migration_req, list);
6048 list_del_init(head->next);
6050 spin_unlock(&rq->lock);
6051 __migrate_task(req->task, cpu, req->dest_cpu);
6054 complete(&req->done);
6056 __set_current_state(TASK_RUNNING);
6060 /* Wait for kthread_stop */
6061 set_current_state(TASK_INTERRUPTIBLE);
6062 while (!kthread_should_stop()) {
6064 set_current_state(TASK_INTERRUPTIBLE);
6066 __set_current_state(TASK_RUNNING);
6070 #ifdef CONFIG_HOTPLUG_CPU
6072 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
6076 local_irq_disable();
6077 ret = __migrate_task(p, src_cpu, dest_cpu);
6083 * Figure out where task on dead CPU should go, use force if necessary.
6084 * NOTE: interrupts should be disabled by the caller
6086 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
6088 unsigned long flags;
6095 mask = node_to_cpumask(cpu_to_node(dead_cpu));
6096 cpus_and(mask, mask, p->cpus_allowed);
6097 dest_cpu = any_online_cpu(mask);
6099 /* On any allowed CPU? */
6100 if (dest_cpu >= nr_cpu_ids)
6101 dest_cpu = any_online_cpu(p->cpus_allowed);
6103 /* No more Mr. Nice Guy. */
6104 if (dest_cpu >= nr_cpu_ids) {
6105 cpumask_t cpus_allowed;
6107 cpuset_cpus_allowed_locked(p, &cpus_allowed);
6109 * Try to stay on the same cpuset, where the
6110 * current cpuset may be a subset of all cpus.
6111 * The cpuset_cpus_allowed_locked() variant of
6112 * cpuset_cpus_allowed() will not block. It must be
6113 * called within calls to cpuset_lock/cpuset_unlock.
6115 rq = task_rq_lock(p, &flags);
6116 p->cpus_allowed = cpus_allowed;
6117 dest_cpu = any_online_cpu(p->cpus_allowed);
6118 task_rq_unlock(rq, &flags);
6121 * Don't tell them about moving exiting tasks or
6122 * kernel threads (both mm NULL), since they never
6125 if (p->mm && printk_ratelimit()) {
6126 printk(KERN_INFO "process %d (%s) no "
6127 "longer affine to cpu%d\n",
6128 task_pid_nr(p), p->comm, dead_cpu);
6131 } while (!__migrate_task_irq(p, dead_cpu, dest_cpu));
6135 * While a dead CPU has no uninterruptible tasks queued at this point,
6136 * it might still have a nonzero ->nr_uninterruptible counter, because
6137 * for performance reasons the counter is not stricly tracking tasks to
6138 * their home CPUs. So we just add the counter to another CPU's counter,
6139 * to keep the global sum constant after CPU-down:
6141 static void migrate_nr_uninterruptible(struct rq *rq_src)
6143 struct rq *rq_dest = cpu_rq(any_online_cpu(*CPU_MASK_ALL_PTR));
6144 unsigned long flags;
6146 local_irq_save(flags);
6147 double_rq_lock(rq_src, rq_dest);
6148 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
6149 rq_src->nr_uninterruptible = 0;
6150 double_rq_unlock(rq_src, rq_dest);
6151 local_irq_restore(flags);
6154 /* Run through task list and migrate tasks from the dead cpu. */
6155 static void migrate_live_tasks(int src_cpu)
6157 struct task_struct *p, *t;
6159 read_lock(&tasklist_lock);
6161 do_each_thread(t, p) {
6165 if (task_cpu(p) == src_cpu)
6166 move_task_off_dead_cpu(src_cpu, p);
6167 } while_each_thread(t, p);
6169 read_unlock(&tasklist_lock);
6173 * Schedules idle task to be the next runnable task on current CPU.
6174 * It does so by boosting its priority to highest possible.
6175 * Used by CPU offline code.
6177 void sched_idle_next(void)
6179 int this_cpu = smp_processor_id();
6180 struct rq *rq = cpu_rq(this_cpu);
6181 struct task_struct *p = rq->idle;
6182 unsigned long flags;
6184 /* cpu has to be offline */
6185 BUG_ON(cpu_online(this_cpu));
6188 * Strictly not necessary since rest of the CPUs are stopped by now
6189 * and interrupts disabled on the current cpu.
6191 spin_lock_irqsave(&rq->lock, flags);
6193 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6195 update_rq_clock(rq);
6196 activate_task(rq, p, 0);
6198 spin_unlock_irqrestore(&rq->lock, flags);
6202 * Ensures that the idle task is using init_mm right before its cpu goes
6205 void idle_task_exit(void)
6207 struct mm_struct *mm = current->active_mm;
6209 BUG_ON(cpu_online(smp_processor_id()));
6212 switch_mm(mm, &init_mm, current);
6216 /* called under rq->lock with disabled interrupts */
6217 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
6219 struct rq *rq = cpu_rq(dead_cpu);
6221 /* Must be exiting, otherwise would be on tasklist. */
6222 BUG_ON(!p->exit_state);
6224 /* Cannot have done final schedule yet: would have vanished. */
6225 BUG_ON(p->state == TASK_DEAD);
6230 * Drop lock around migration; if someone else moves it,
6231 * that's OK. No task can be added to this CPU, so iteration is
6234 spin_unlock_irq(&rq->lock);
6235 move_task_off_dead_cpu(dead_cpu, p);
6236 spin_lock_irq(&rq->lock);
6241 /* release_task() removes task from tasklist, so we won't find dead tasks. */
6242 static void migrate_dead_tasks(unsigned int dead_cpu)
6244 struct rq *rq = cpu_rq(dead_cpu);
6245 struct task_struct *next;
6248 if (!rq->nr_running)
6250 update_rq_clock(rq);
6251 next = pick_next_task(rq, rq->curr);
6254 migrate_dead(dead_cpu, next);
6258 #endif /* CONFIG_HOTPLUG_CPU */
6260 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
6262 static struct ctl_table sd_ctl_dir[] = {
6264 .procname = "sched_domain",
6270 static struct ctl_table sd_ctl_root[] = {
6272 .ctl_name = CTL_KERN,
6273 .procname = "kernel",
6275 .child = sd_ctl_dir,
6280 static struct ctl_table *sd_alloc_ctl_entry(int n)
6282 struct ctl_table *entry =
6283 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
6288 static void sd_free_ctl_entry(struct ctl_table **tablep)
6290 struct ctl_table *entry;
6293 * In the intermediate directories, both the child directory and
6294 * procname are dynamically allocated and could fail but the mode
6295 * will always be set. In the lowest directory the names are
6296 * static strings and all have proc handlers.
6298 for (entry = *tablep; entry->mode; entry++) {
6300 sd_free_ctl_entry(&entry->child);
6301 if (entry->proc_handler == NULL)
6302 kfree(entry->procname);
6310 set_table_entry(struct ctl_table *entry,
6311 const char *procname, void *data, int maxlen,
6312 mode_t mode, proc_handler *proc_handler)
6314 entry->procname = procname;
6316 entry->maxlen = maxlen;
6318 entry->proc_handler = proc_handler;
6321 static struct ctl_table *
6322 sd_alloc_ctl_domain_table(struct sched_domain *sd)
6324 struct ctl_table *table = sd_alloc_ctl_entry(12);
6329 set_table_entry(&table[0], "min_interval", &sd->min_interval,
6330 sizeof(long), 0644, proc_doulongvec_minmax);
6331 set_table_entry(&table[1], "max_interval", &sd->max_interval,
6332 sizeof(long), 0644, proc_doulongvec_minmax);
6333 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
6334 sizeof(int), 0644, proc_dointvec_minmax);
6335 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
6336 sizeof(int), 0644, proc_dointvec_minmax);
6337 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
6338 sizeof(int), 0644, proc_dointvec_minmax);
6339 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
6340 sizeof(int), 0644, proc_dointvec_minmax);
6341 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
6342 sizeof(int), 0644, proc_dointvec_minmax);
6343 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
6344 sizeof(int), 0644, proc_dointvec_minmax);
6345 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
6346 sizeof(int), 0644, proc_dointvec_minmax);
6347 set_table_entry(&table[9], "cache_nice_tries",
6348 &sd->cache_nice_tries,
6349 sizeof(int), 0644, proc_dointvec_minmax);
6350 set_table_entry(&table[10], "flags", &sd->flags,
6351 sizeof(int), 0644, proc_dointvec_minmax);
6352 /* &table[11] is terminator */
6357 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
6359 struct ctl_table *entry, *table;
6360 struct sched_domain *sd;
6361 int domain_num = 0, i;
6364 for_each_domain(cpu, sd)
6366 entry = table = sd_alloc_ctl_entry(domain_num + 1);
6371 for_each_domain(cpu, sd) {
6372 snprintf(buf, 32, "domain%d", i);
6373 entry->procname = kstrdup(buf, GFP_KERNEL);
6375 entry->child = sd_alloc_ctl_domain_table(sd);
6382 static struct ctl_table_header *sd_sysctl_header;
6383 static void register_sched_domain_sysctl(void)
6385 int i, cpu_num = num_online_cpus();
6386 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
6389 WARN_ON(sd_ctl_dir[0].child);
6390 sd_ctl_dir[0].child = entry;
6395 for_each_online_cpu(i) {
6396 snprintf(buf, 32, "cpu%d", i);
6397 entry->procname = kstrdup(buf, GFP_KERNEL);
6399 entry->child = sd_alloc_ctl_cpu_table(i);
6403 WARN_ON(sd_sysctl_header);
6404 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
6407 /* may be called multiple times per register */
6408 static void unregister_sched_domain_sysctl(void)
6410 if (sd_sysctl_header)
6411 unregister_sysctl_table(sd_sysctl_header);
6412 sd_sysctl_header = NULL;
6413 if (sd_ctl_dir[0].child)
6414 sd_free_ctl_entry(&sd_ctl_dir[0].child);
6417 static void register_sched_domain_sysctl(void)
6420 static void unregister_sched_domain_sysctl(void)
6426 * migration_call - callback that gets triggered when a CPU is added.
6427 * Here we can start up the necessary migration thread for the new CPU.
6429 static int __cpuinit
6430 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
6432 struct task_struct *p;
6433 int cpu = (long)hcpu;
6434 unsigned long flags;
6439 case CPU_UP_PREPARE:
6440 case CPU_UP_PREPARE_FROZEN:
6441 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
6444 kthread_bind(p, cpu);
6445 /* Must be high prio: stop_machine expects to yield to it. */
6446 rq = task_rq_lock(p, &flags);
6447 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6448 task_rq_unlock(rq, &flags);
6449 cpu_rq(cpu)->migration_thread = p;
6453 case CPU_ONLINE_FROZEN:
6454 /* Strictly unnecessary, as first user will wake it. */
6455 wake_up_process(cpu_rq(cpu)->migration_thread);
6457 /* Update our root-domain */
6459 spin_lock_irqsave(&rq->lock, flags);
6461 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6462 cpu_set(cpu, rq->rd->online);
6464 spin_unlock_irqrestore(&rq->lock, flags);
6467 #ifdef CONFIG_HOTPLUG_CPU
6468 case CPU_UP_CANCELED:
6469 case CPU_UP_CANCELED_FROZEN:
6470 if (!cpu_rq(cpu)->migration_thread)
6472 /* Unbind it from offline cpu so it can run. Fall thru. */
6473 kthread_bind(cpu_rq(cpu)->migration_thread,
6474 any_online_cpu(cpu_online_map));
6475 kthread_stop(cpu_rq(cpu)->migration_thread);
6476 cpu_rq(cpu)->migration_thread = NULL;
6480 case CPU_DEAD_FROZEN:
6481 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
6482 migrate_live_tasks(cpu);
6484 kthread_stop(rq->migration_thread);
6485 rq->migration_thread = NULL;
6486 /* Idle task back to normal (off runqueue, low prio) */
6487 spin_lock_irq(&rq->lock);
6488 update_rq_clock(rq);
6489 deactivate_task(rq, rq->idle, 0);
6490 rq->idle->static_prio = MAX_PRIO;
6491 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
6492 rq->idle->sched_class = &idle_sched_class;
6493 migrate_dead_tasks(cpu);
6494 spin_unlock_irq(&rq->lock);
6496 migrate_nr_uninterruptible(rq);
6497 BUG_ON(rq->nr_running != 0);
6500 * No need to migrate the tasks: it was best-effort if
6501 * they didn't take sched_hotcpu_mutex. Just wake up
6504 spin_lock_irq(&rq->lock);
6505 while (!list_empty(&rq->migration_queue)) {
6506 struct migration_req *req;
6508 req = list_entry(rq->migration_queue.next,
6509 struct migration_req, list);
6510 list_del_init(&req->list);
6511 complete(&req->done);
6513 spin_unlock_irq(&rq->lock);
6517 case CPU_DYING_FROZEN:
6518 /* Update our root-domain */
6520 spin_lock_irqsave(&rq->lock, flags);
6522 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6523 cpu_clear(cpu, rq->rd->online);
6525 spin_unlock_irqrestore(&rq->lock, flags);
6532 /* Register at highest priority so that task migration (migrate_all_tasks)
6533 * happens before everything else.
6535 static struct notifier_block __cpuinitdata migration_notifier = {
6536 .notifier_call = migration_call,
6540 void __init migration_init(void)
6542 void *cpu = (void *)(long)smp_processor_id();
6545 /* Start one for the boot CPU: */
6546 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
6547 BUG_ON(err == NOTIFY_BAD);
6548 migration_call(&migration_notifier, CPU_ONLINE, cpu);
6549 register_cpu_notifier(&migration_notifier);
6555 #ifdef CONFIG_SCHED_DEBUG
6557 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
6558 cpumask_t *groupmask)
6560 struct sched_group *group = sd->groups;
6563 cpulist_scnprintf(str, sizeof(str), sd->span);
6564 cpus_clear(*groupmask);
6566 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6568 if (!(sd->flags & SD_LOAD_BALANCE)) {
6569 printk("does not load-balance\n");
6571 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6576 printk(KERN_CONT "span %s\n", str);
6578 if (!cpu_isset(cpu, sd->span)) {
6579 printk(KERN_ERR "ERROR: domain->span does not contain "
6582 if (!cpu_isset(cpu, group->cpumask)) {
6583 printk(KERN_ERR "ERROR: domain->groups does not contain"
6587 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6591 printk(KERN_ERR "ERROR: group is NULL\n");
6595 if (!group->__cpu_power) {
6596 printk(KERN_CONT "\n");
6597 printk(KERN_ERR "ERROR: domain->cpu_power not "
6602 if (!cpus_weight(group->cpumask)) {
6603 printk(KERN_CONT "\n");
6604 printk(KERN_ERR "ERROR: empty group\n");
6608 if (cpus_intersects(*groupmask, group->cpumask)) {
6609 printk(KERN_CONT "\n");
6610 printk(KERN_ERR "ERROR: repeated CPUs\n");
6614 cpus_or(*groupmask, *groupmask, group->cpumask);
6616 cpulist_scnprintf(str, sizeof(str), group->cpumask);
6617 printk(KERN_CONT " %s", str);
6619 group = group->next;
6620 } while (group != sd->groups);
6621 printk(KERN_CONT "\n");
6623 if (!cpus_equal(sd->span, *groupmask))
6624 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6626 if (sd->parent && !cpus_subset(*groupmask, sd->parent->span))
6627 printk(KERN_ERR "ERROR: parent span is not a superset "
6628 "of domain->span\n");
6632 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6634 cpumask_t *groupmask;
6638 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6642 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6644 groupmask = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
6646 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
6651 if (sched_domain_debug_one(sd, cpu, level, groupmask))
6661 # define sched_domain_debug(sd, cpu) do { } while (0)
6664 static int sd_degenerate(struct sched_domain *sd)
6666 if (cpus_weight(sd->span) == 1)
6669 /* Following flags need at least 2 groups */
6670 if (sd->flags & (SD_LOAD_BALANCE |
6671 SD_BALANCE_NEWIDLE |
6675 SD_SHARE_PKG_RESOURCES)) {
6676 if (sd->groups != sd->groups->next)
6680 /* Following flags don't use groups */
6681 if (sd->flags & (SD_WAKE_IDLE |
6690 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6692 unsigned long cflags = sd->flags, pflags = parent->flags;
6694 if (sd_degenerate(parent))
6697 if (!cpus_equal(sd->span, parent->span))
6700 /* Does parent contain flags not in child? */
6701 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6702 if (cflags & SD_WAKE_AFFINE)
6703 pflags &= ~SD_WAKE_BALANCE;
6704 /* Flags needing groups don't count if only 1 group in parent */
6705 if (parent->groups == parent->groups->next) {
6706 pflags &= ~(SD_LOAD_BALANCE |
6707 SD_BALANCE_NEWIDLE |
6711 SD_SHARE_PKG_RESOURCES);
6713 if (~cflags & pflags)
6719 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6721 unsigned long flags;
6722 const struct sched_class *class;
6724 spin_lock_irqsave(&rq->lock, flags);
6727 struct root_domain *old_rd = rq->rd;
6729 for (class = sched_class_highest; class; class = class->next) {
6730 if (class->leave_domain)
6731 class->leave_domain(rq);
6734 cpu_clear(rq->cpu, old_rd->span);
6735 cpu_clear(rq->cpu, old_rd->online);
6737 if (atomic_dec_and_test(&old_rd->refcount))
6741 atomic_inc(&rd->refcount);
6744 cpu_set(rq->cpu, rd->span);
6745 if (cpu_isset(rq->cpu, cpu_online_map))
6746 cpu_set(rq->cpu, rd->online);
6748 for (class = sched_class_highest; class; class = class->next) {
6749 if (class->join_domain)
6750 class->join_domain(rq);
6753 spin_unlock_irqrestore(&rq->lock, flags);
6756 static void init_rootdomain(struct root_domain *rd)
6758 memset(rd, 0, sizeof(*rd));
6760 cpus_clear(rd->span);
6761 cpus_clear(rd->online);
6764 static void init_defrootdomain(void)
6766 init_rootdomain(&def_root_domain);
6767 atomic_set(&def_root_domain.refcount, 1);
6770 static struct root_domain *alloc_rootdomain(void)
6772 struct root_domain *rd;
6774 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6778 init_rootdomain(rd);
6784 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6785 * hold the hotplug lock.
6788 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6790 struct rq *rq = cpu_rq(cpu);
6791 struct sched_domain *tmp;
6793 /* Remove the sched domains which do not contribute to scheduling. */
6794 for (tmp = sd; tmp; tmp = tmp->parent) {
6795 struct sched_domain *parent = tmp->parent;
6798 if (sd_parent_degenerate(tmp, parent)) {
6799 tmp->parent = parent->parent;
6801 parent->parent->child = tmp;
6805 if (sd && sd_degenerate(sd)) {
6811 sched_domain_debug(sd, cpu);
6813 rq_attach_root(rq, rd);
6814 rcu_assign_pointer(rq->sd, sd);
6817 /* cpus with isolated domains */
6818 static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
6820 /* Setup the mask of cpus configured for isolated domains */
6821 static int __init isolated_cpu_setup(char *str)
6823 int ints[NR_CPUS], i;
6825 str = get_options(str, ARRAY_SIZE(ints), ints);
6826 cpus_clear(cpu_isolated_map);
6827 for (i = 1; i <= ints[0]; i++)
6828 if (ints[i] < NR_CPUS)
6829 cpu_set(ints[i], cpu_isolated_map);
6833 __setup("isolcpus=", isolated_cpu_setup);
6836 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6837 * to a function which identifies what group(along with sched group) a CPU
6838 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6839 * (due to the fact that we keep track of groups covered with a cpumask_t).
6841 * init_sched_build_groups will build a circular linked list of the groups
6842 * covered by the given span, and will set each group's ->cpumask correctly,
6843 * and ->cpu_power to 0.
6846 init_sched_build_groups(const cpumask_t *span, const cpumask_t *cpu_map,
6847 int (*group_fn)(int cpu, const cpumask_t *cpu_map,
6848 struct sched_group **sg,
6849 cpumask_t *tmpmask),
6850 cpumask_t *covered, cpumask_t *tmpmask)
6852 struct sched_group *first = NULL, *last = NULL;
6855 cpus_clear(*covered);
6857 for_each_cpu_mask(i, *span) {
6858 struct sched_group *sg;
6859 int group = group_fn(i, cpu_map, &sg, tmpmask);
6862 if (cpu_isset(i, *covered))
6865 cpus_clear(sg->cpumask);
6866 sg->__cpu_power = 0;
6868 for_each_cpu_mask(j, *span) {
6869 if (group_fn(j, cpu_map, NULL, tmpmask) != group)
6872 cpu_set(j, *covered);
6873 cpu_set(j, sg->cpumask);
6884 #define SD_NODES_PER_DOMAIN 16
6889 * find_next_best_node - find the next node to include in a sched_domain
6890 * @node: node whose sched_domain we're building
6891 * @used_nodes: nodes already in the sched_domain
6893 * Find the next node to include in a given scheduling domain. Simply
6894 * finds the closest node not already in the @used_nodes map.
6896 * Should use nodemask_t.
6898 static int find_next_best_node(int node, nodemask_t *used_nodes)
6900 int i, n, val, min_val, best_node = 0;
6904 for (i = 0; i < MAX_NUMNODES; i++) {
6905 /* Start at @node */
6906 n = (node + i) % MAX_NUMNODES;
6908 if (!nr_cpus_node(n))
6911 /* Skip already used nodes */
6912 if (node_isset(n, *used_nodes))
6915 /* Simple min distance search */
6916 val = node_distance(node, n);
6918 if (val < min_val) {
6924 node_set(best_node, *used_nodes);
6929 * sched_domain_node_span - get a cpumask for a node's sched_domain
6930 * @node: node whose cpumask we're constructing
6932 * Given a node, construct a good cpumask for its sched_domain to span. It
6933 * should be one that prevents unnecessary balancing, but also spreads tasks
6936 static void sched_domain_node_span(int node, cpumask_t *span)
6938 nodemask_t used_nodes;
6939 node_to_cpumask_ptr(nodemask, node);
6943 nodes_clear(used_nodes);
6945 cpus_or(*span, *span, *nodemask);
6946 node_set(node, used_nodes);
6948 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
6949 int next_node = find_next_best_node(node, &used_nodes);
6951 node_to_cpumask_ptr_next(nodemask, next_node);
6952 cpus_or(*span, *span, *nodemask);
6957 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6960 * SMT sched-domains:
6962 #ifdef CONFIG_SCHED_SMT
6963 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
6964 static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
6967 cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
6971 *sg = &per_cpu(sched_group_cpus, cpu);
6977 * multi-core sched-domains:
6979 #ifdef CONFIG_SCHED_MC
6980 static DEFINE_PER_CPU(struct sched_domain, core_domains);
6981 static DEFINE_PER_CPU(struct sched_group, sched_group_core);
6984 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6986 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
6991 *mask = per_cpu(cpu_sibling_map, cpu);
6992 cpus_and(*mask, *mask, *cpu_map);
6993 group = first_cpu(*mask);
6995 *sg = &per_cpu(sched_group_core, group);
6998 #elif defined(CONFIG_SCHED_MC)
7000 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7004 *sg = &per_cpu(sched_group_core, cpu);
7009 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
7010 static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
7013 cpu_to_phys_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
7017 #ifdef CONFIG_SCHED_MC
7018 *mask = cpu_coregroup_map(cpu);
7019 cpus_and(*mask, *mask, *cpu_map);
7020 group = first_cpu(*mask);
7021 #elif defined(CONFIG_SCHED_SMT)
7022 *mask = per_cpu(cpu_sibling_map, cpu);
7023 cpus_and(*mask, *mask, *cpu_map);
7024 group = first_cpu(*mask);
7029 *sg = &per_cpu(sched_group_phys, group);
7035 * The init_sched_build_groups can't handle what we want to do with node
7036 * groups, so roll our own. Now each node has its own list of groups which
7037 * gets dynamically allocated.
7039 static DEFINE_PER_CPU(struct sched_domain, node_domains);
7040 static struct sched_group ***sched_group_nodes_bycpu;
7042 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
7043 static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
7045 static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
7046 struct sched_group **sg, cpumask_t *nodemask)
7050 *nodemask = node_to_cpumask(cpu_to_node(cpu));
7051 cpus_and(*nodemask, *nodemask, *cpu_map);
7052 group = first_cpu(*nodemask);
7055 *sg = &per_cpu(sched_group_allnodes, group);
7059 static void init_numa_sched_groups_power(struct sched_group *group_head)
7061 struct sched_group *sg = group_head;
7067 for_each_cpu_mask(j, sg->cpumask) {
7068 struct sched_domain *sd;
7070 sd = &per_cpu(phys_domains, j);
7071 if (j != first_cpu(sd->groups->cpumask)) {
7073 * Only add "power" once for each
7079 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
7082 } while (sg != group_head);
7087 /* Free memory allocated for various sched_group structures */
7088 static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
7092 for_each_cpu_mask(cpu, *cpu_map) {
7093 struct sched_group **sched_group_nodes
7094 = sched_group_nodes_bycpu[cpu];
7096 if (!sched_group_nodes)
7099 for (i = 0; i < MAX_NUMNODES; i++) {
7100 struct sched_group *oldsg, *sg = sched_group_nodes[i];
7102 *nodemask = node_to_cpumask(i);
7103 cpus_and(*nodemask, *nodemask, *cpu_map);
7104 if (cpus_empty(*nodemask))
7114 if (oldsg != sched_group_nodes[i])
7117 kfree(sched_group_nodes);
7118 sched_group_nodes_bycpu[cpu] = NULL;
7122 static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
7128 * Initialize sched groups cpu_power.
7130 * cpu_power indicates the capacity of sched group, which is used while
7131 * distributing the load between different sched groups in a sched domain.
7132 * Typically cpu_power for all the groups in a sched domain will be same unless
7133 * there are asymmetries in the topology. If there are asymmetries, group
7134 * having more cpu_power will pickup more load compared to the group having
7137 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
7138 * the maximum number of tasks a group can handle in the presence of other idle
7139 * or lightly loaded groups in the same sched domain.
7141 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
7143 struct sched_domain *child;
7144 struct sched_group *group;
7146 WARN_ON(!sd || !sd->groups);
7148 if (cpu != first_cpu(sd->groups->cpumask))
7153 sd->groups->__cpu_power = 0;
7156 * For perf policy, if the groups in child domain share resources
7157 * (for example cores sharing some portions of the cache hierarchy
7158 * or SMT), then set this domain groups cpu_power such that each group
7159 * can handle only one task, when there are other idle groups in the
7160 * same sched domain.
7162 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
7164 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
7165 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
7170 * add cpu_power of each child group to this groups cpu_power
7172 group = child->groups;
7174 sg_inc_cpu_power(sd->groups, group->__cpu_power);
7175 group = group->next;
7176 } while (group != child->groups);
7180 * Initializers for schedule domains
7181 * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
7184 #define SD_INIT(sd, type) sd_init_##type(sd)
7185 #define SD_INIT_FUNC(type) \
7186 static noinline void sd_init_##type(struct sched_domain *sd) \
7188 memset(sd, 0, sizeof(*sd)); \
7189 *sd = SD_##type##_INIT; \
7190 sd->level = SD_LV_##type; \
7195 SD_INIT_FUNC(ALLNODES)
7198 #ifdef CONFIG_SCHED_SMT
7199 SD_INIT_FUNC(SIBLING)
7201 #ifdef CONFIG_SCHED_MC
7206 * To minimize stack usage kmalloc room for cpumasks and share the
7207 * space as the usage in build_sched_domains() dictates. Used only
7208 * if the amount of space is significant.
7211 cpumask_t tmpmask; /* make this one first */
7214 cpumask_t this_sibling_map;
7215 cpumask_t this_core_map;
7217 cpumask_t send_covered;
7220 cpumask_t domainspan;
7222 cpumask_t notcovered;
7227 #define SCHED_CPUMASK_ALLOC 1
7228 #define SCHED_CPUMASK_FREE(v) kfree(v)
7229 #define SCHED_CPUMASK_DECLARE(v) struct allmasks *v
7231 #define SCHED_CPUMASK_ALLOC 0
7232 #define SCHED_CPUMASK_FREE(v)
7233 #define SCHED_CPUMASK_DECLARE(v) struct allmasks _v, *v = &_v
7236 #define SCHED_CPUMASK_VAR(v, a) cpumask_t *v = (cpumask_t *) \
7237 ((unsigned long)(a) + offsetof(struct allmasks, v))
7239 static int default_relax_domain_level = -1;
7241 static int __init setup_relax_domain_level(char *str)
7243 default_relax_domain_level = simple_strtoul(str, NULL, 0);
7246 __setup("relax_domain_level=", setup_relax_domain_level);
7248 static void set_domain_attribute(struct sched_domain *sd,
7249 struct sched_domain_attr *attr)
7253 if (!attr || attr->relax_domain_level < 0) {
7254 if (default_relax_domain_level < 0)
7257 request = default_relax_domain_level;
7259 request = attr->relax_domain_level;
7260 if (request < sd->level) {
7261 /* turn off idle balance on this domain */
7262 sd->flags &= ~(SD_WAKE_IDLE|SD_BALANCE_NEWIDLE);
7264 /* turn on idle balance on this domain */
7265 sd->flags |= (SD_WAKE_IDLE_FAR|SD_BALANCE_NEWIDLE);
7270 * Build sched domains for a given set of cpus and attach the sched domains
7271 * to the individual cpus
7273 static int __build_sched_domains(const cpumask_t *cpu_map,
7274 struct sched_domain_attr *attr)
7277 struct root_domain *rd;
7278 SCHED_CPUMASK_DECLARE(allmasks);
7281 struct sched_group **sched_group_nodes = NULL;
7282 int sd_allnodes = 0;
7285 * Allocate the per-node list of sched groups
7287 sched_group_nodes = kcalloc(MAX_NUMNODES, sizeof(struct sched_group *),
7289 if (!sched_group_nodes) {
7290 printk(KERN_WARNING "Can not alloc sched group node list\n");
7295 rd = alloc_rootdomain();
7297 printk(KERN_WARNING "Cannot alloc root domain\n");
7299 kfree(sched_group_nodes);
7304 #if SCHED_CPUMASK_ALLOC
7305 /* get space for all scratch cpumask variables */
7306 allmasks = kmalloc(sizeof(*allmasks), GFP_KERNEL);
7308 printk(KERN_WARNING "Cannot alloc cpumask array\n");
7311 kfree(sched_group_nodes);
7316 tmpmask = (cpumask_t *)allmasks;
7320 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
7324 * Set up domains for cpus specified by the cpu_map.
7326 for_each_cpu_mask(i, *cpu_map) {
7327 struct sched_domain *sd = NULL, *p;
7328 SCHED_CPUMASK_VAR(nodemask, allmasks);
7330 *nodemask = node_to_cpumask(cpu_to_node(i));
7331 cpus_and(*nodemask, *nodemask, *cpu_map);
7334 if (cpus_weight(*cpu_map) >
7335 SD_NODES_PER_DOMAIN*cpus_weight(*nodemask)) {
7336 sd = &per_cpu(allnodes_domains, i);
7337 SD_INIT(sd, ALLNODES);
7338 set_domain_attribute(sd, attr);
7339 sd->span = *cpu_map;
7340 sd->first_cpu = first_cpu(sd->span);
7341 cpu_to_allnodes_group(i, cpu_map, &sd->groups, tmpmask);
7347 sd = &per_cpu(node_domains, i);
7349 set_domain_attribute(sd, attr);
7350 sched_domain_node_span(cpu_to_node(i), &sd->span);
7351 sd->first_cpu = first_cpu(sd->span);
7355 cpus_and(sd->span, sd->span, *cpu_map);
7359 sd = &per_cpu(phys_domains, i);
7361 set_domain_attribute(sd, attr);
7362 sd->span = *nodemask;
7363 sd->first_cpu = first_cpu(sd->span);
7367 cpu_to_phys_group(i, cpu_map, &sd->groups, tmpmask);
7369 #ifdef CONFIG_SCHED_MC
7371 sd = &per_cpu(core_domains, i);
7373 set_domain_attribute(sd, attr);
7374 sd->span = cpu_coregroup_map(i);
7375 sd->first_cpu = first_cpu(sd->span);
7376 cpus_and(sd->span, sd->span, *cpu_map);
7379 cpu_to_core_group(i, cpu_map, &sd->groups, tmpmask);
7382 #ifdef CONFIG_SCHED_SMT
7384 sd = &per_cpu(cpu_domains, i);
7385 SD_INIT(sd, SIBLING);
7386 set_domain_attribute(sd, attr);
7387 sd->span = per_cpu(cpu_sibling_map, i);
7388 sd->first_cpu = first_cpu(sd->span);
7389 cpus_and(sd->span, sd->span, *cpu_map);
7392 cpu_to_cpu_group(i, cpu_map, &sd->groups, tmpmask);
7396 #ifdef CONFIG_SCHED_SMT
7397 /* Set up CPU (sibling) groups */
7398 for_each_cpu_mask(i, *cpu_map) {
7399 SCHED_CPUMASK_VAR(this_sibling_map, allmasks);
7400 SCHED_CPUMASK_VAR(send_covered, allmasks);
7402 *this_sibling_map = per_cpu(cpu_sibling_map, i);
7403 cpus_and(*this_sibling_map, *this_sibling_map, *cpu_map);
7404 if (i != first_cpu(*this_sibling_map))
7407 init_sched_build_groups(this_sibling_map, cpu_map,
7409 send_covered, tmpmask);
7413 #ifdef CONFIG_SCHED_MC
7414 /* Set up multi-core groups */
7415 for_each_cpu_mask(i, *cpu_map) {
7416 SCHED_CPUMASK_VAR(this_core_map, allmasks);
7417 SCHED_CPUMASK_VAR(send_covered, allmasks);
7419 *this_core_map = cpu_coregroup_map(i);
7420 cpus_and(*this_core_map, *this_core_map, *cpu_map);
7421 if (i != first_cpu(*this_core_map))
7424 init_sched_build_groups(this_core_map, cpu_map,
7426 send_covered, tmpmask);
7430 /* Set up physical groups */
7431 for (i = 0; i < MAX_NUMNODES; i++) {
7432 SCHED_CPUMASK_VAR(nodemask, allmasks);
7433 SCHED_CPUMASK_VAR(send_covered, allmasks);
7435 *nodemask = node_to_cpumask(i);
7436 cpus_and(*nodemask, *nodemask, *cpu_map);
7437 if (cpus_empty(*nodemask))
7440 init_sched_build_groups(nodemask, cpu_map,
7442 send_covered, tmpmask);
7446 /* Set up node groups */
7448 SCHED_CPUMASK_VAR(send_covered, allmasks);
7450 init_sched_build_groups(cpu_map, cpu_map,
7451 &cpu_to_allnodes_group,
7452 send_covered, tmpmask);
7455 for (i = 0; i < MAX_NUMNODES; i++) {
7456 /* Set up node groups */
7457 struct sched_group *sg, *prev;
7458 SCHED_CPUMASK_VAR(nodemask, allmasks);
7459 SCHED_CPUMASK_VAR(domainspan, allmasks);
7460 SCHED_CPUMASK_VAR(covered, allmasks);
7463 *nodemask = node_to_cpumask(i);
7464 cpus_clear(*covered);
7466 cpus_and(*nodemask, *nodemask, *cpu_map);
7467 if (cpus_empty(*nodemask)) {
7468 sched_group_nodes[i] = NULL;
7472 sched_domain_node_span(i, domainspan);
7473 cpus_and(*domainspan, *domainspan, *cpu_map);
7475 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
7477 printk(KERN_WARNING "Can not alloc domain group for "
7481 sched_group_nodes[i] = sg;
7482 for_each_cpu_mask(j, *nodemask) {
7483 struct sched_domain *sd;
7485 sd = &per_cpu(node_domains, j);
7488 sg->__cpu_power = 0;
7489 sg->cpumask = *nodemask;
7491 cpus_or(*covered, *covered, *nodemask);
7494 for (j = 0; j < MAX_NUMNODES; j++) {
7495 SCHED_CPUMASK_VAR(notcovered, allmasks);
7496 int n = (i + j) % MAX_NUMNODES;
7497 node_to_cpumask_ptr(pnodemask, n);
7499 cpus_complement(*notcovered, *covered);
7500 cpus_and(*tmpmask, *notcovered, *cpu_map);
7501 cpus_and(*tmpmask, *tmpmask, *domainspan);
7502 if (cpus_empty(*tmpmask))
7505 cpus_and(*tmpmask, *tmpmask, *pnodemask);
7506 if (cpus_empty(*tmpmask))
7509 sg = kmalloc_node(sizeof(struct sched_group),
7513 "Can not alloc domain group for node %d\n", j);
7516 sg->__cpu_power = 0;
7517 sg->cpumask = *tmpmask;
7518 sg->next = prev->next;
7519 cpus_or(*covered, *covered, *tmpmask);
7526 /* Calculate CPU power for physical packages and nodes */
7527 #ifdef CONFIG_SCHED_SMT
7528 for_each_cpu_mask(i, *cpu_map) {
7529 struct sched_domain *sd = &per_cpu(cpu_domains, i);
7531 init_sched_groups_power(i, sd);
7534 #ifdef CONFIG_SCHED_MC
7535 for_each_cpu_mask(i, *cpu_map) {
7536 struct sched_domain *sd = &per_cpu(core_domains, i);
7538 init_sched_groups_power(i, sd);
7542 for_each_cpu_mask(i, *cpu_map) {
7543 struct sched_domain *sd = &per_cpu(phys_domains, i);
7545 init_sched_groups_power(i, sd);
7549 for (i = 0; i < MAX_NUMNODES; i++)
7550 init_numa_sched_groups_power(sched_group_nodes[i]);
7553 struct sched_group *sg;
7555 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg,
7557 init_numa_sched_groups_power(sg);
7561 /* Attach the domains */
7562 for_each_cpu_mask(i, *cpu_map) {
7563 struct sched_domain *sd;
7564 #ifdef CONFIG_SCHED_SMT
7565 sd = &per_cpu(cpu_domains, i);
7566 #elif defined(CONFIG_SCHED_MC)
7567 sd = &per_cpu(core_domains, i);
7569 sd = &per_cpu(phys_domains, i);
7571 cpu_attach_domain(sd, rd, i);
7574 SCHED_CPUMASK_FREE((void *)allmasks);
7579 free_sched_groups(cpu_map, tmpmask);
7580 SCHED_CPUMASK_FREE((void *)allmasks);
7585 static int build_sched_domains(const cpumask_t *cpu_map)
7587 return __build_sched_domains(cpu_map, NULL);
7590 static cpumask_t *doms_cur; /* current sched domains */
7591 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7592 static struct sched_domain_attr *dattr_cur; /* attribues of custom domains
7596 * Special case: If a kmalloc of a doms_cur partition (array of
7597 * cpumask_t) fails, then fallback to a single sched domain,
7598 * as determined by the single cpumask_t fallback_doms.
7600 static cpumask_t fallback_doms;
7602 void __attribute__((weak)) arch_update_cpu_topology(void)
7607 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7608 * For now this just excludes isolated cpus, but could be used to
7609 * exclude other special cases in the future.
7611 static int arch_init_sched_domains(const cpumask_t *cpu_map)
7615 arch_update_cpu_topology();
7617 doms_cur = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
7619 doms_cur = &fallback_doms;
7620 cpus_andnot(*doms_cur, *cpu_map, cpu_isolated_map);
7622 err = build_sched_domains(doms_cur);
7623 register_sched_domain_sysctl();
7628 static void arch_destroy_sched_domains(const cpumask_t *cpu_map,
7631 free_sched_groups(cpu_map, tmpmask);
7635 * Detach sched domains from a group of cpus specified in cpu_map
7636 * These cpus will now be attached to the NULL domain
7638 static void detach_destroy_domains(const cpumask_t *cpu_map)
7643 unregister_sched_domain_sysctl();
7645 for_each_cpu_mask(i, *cpu_map)
7646 cpu_attach_domain(NULL, &def_root_domain, i);
7647 synchronize_sched();
7648 arch_destroy_sched_domains(cpu_map, &tmpmask);
7651 /* handle null as "default" */
7652 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7653 struct sched_domain_attr *new, int idx_new)
7655 struct sched_domain_attr tmp;
7662 return !memcmp(cur ? (cur + idx_cur) : &tmp,
7663 new ? (new + idx_new) : &tmp,
7664 sizeof(struct sched_domain_attr));
7668 * Partition sched domains as specified by the 'ndoms_new'
7669 * cpumasks in the array doms_new[] of cpumasks. This compares
7670 * doms_new[] to the current sched domain partitioning, doms_cur[].
7671 * It destroys each deleted domain and builds each new domain.
7673 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
7674 * The masks don't intersect (don't overlap.) We should setup one
7675 * sched domain for each mask. CPUs not in any of the cpumasks will
7676 * not be load balanced. If the same cpumask appears both in the
7677 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7680 * The passed in 'doms_new' should be kmalloc'd. This routine takes
7681 * ownership of it and will kfree it when done with it. If the caller
7682 * failed the kmalloc call, then it can pass in doms_new == NULL,
7683 * and partition_sched_domains() will fallback to the single partition
7686 * Call with hotplug lock held
7688 void partition_sched_domains(int ndoms_new, cpumask_t *doms_new,
7689 struct sched_domain_attr *dattr_new)
7695 /* always unregister in case we don't destroy any domains */
7696 unregister_sched_domain_sysctl();
7698 if (doms_new == NULL) {
7700 doms_new = &fallback_doms;
7701 cpus_andnot(doms_new[0], cpu_online_map, cpu_isolated_map);
7705 /* Destroy deleted domains */
7706 for (i = 0; i < ndoms_cur; i++) {
7707 for (j = 0; j < ndoms_new; j++) {
7708 if (cpus_equal(doms_cur[i], doms_new[j])
7709 && dattrs_equal(dattr_cur, i, dattr_new, j))
7712 /* no match - a current sched domain not in new doms_new[] */
7713 detach_destroy_domains(doms_cur + i);
7718 /* Build new domains */
7719 for (i = 0; i < ndoms_new; i++) {
7720 for (j = 0; j < ndoms_cur; j++) {
7721 if (cpus_equal(doms_new[i], doms_cur[j])
7722 && dattrs_equal(dattr_new, i, dattr_cur, j))
7725 /* no match - add a new doms_new */
7726 __build_sched_domains(doms_new + i,
7727 dattr_new ? dattr_new + i : NULL);
7732 /* Remember the new sched domains */
7733 if (doms_cur != &fallback_doms)
7735 kfree(dattr_cur); /* kfree(NULL) is safe */
7736 doms_cur = doms_new;
7737 dattr_cur = dattr_new;
7738 ndoms_cur = ndoms_new;
7740 register_sched_domain_sysctl();
7745 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7746 int arch_reinit_sched_domains(void)
7751 detach_destroy_domains(&cpu_online_map);
7752 err = arch_init_sched_domains(&cpu_online_map);
7758 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7762 if (buf[0] != '0' && buf[0] != '1')
7766 sched_smt_power_savings = (buf[0] == '1');
7768 sched_mc_power_savings = (buf[0] == '1');
7770 ret = arch_reinit_sched_domains();
7772 return ret ? ret : count;
7775 #ifdef CONFIG_SCHED_MC
7776 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
7778 return sprintf(page, "%u\n", sched_mc_power_savings);
7780 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
7781 const char *buf, size_t count)
7783 return sched_power_savings_store(buf, count, 0);
7785 static SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
7786 sched_mc_power_savings_store);
7789 #ifdef CONFIG_SCHED_SMT
7790 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
7792 return sprintf(page, "%u\n", sched_smt_power_savings);
7794 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
7795 const char *buf, size_t count)
7797 return sched_power_savings_store(buf, count, 1);
7799 static SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
7800 sched_smt_power_savings_store);
7803 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7807 #ifdef CONFIG_SCHED_SMT
7809 err = sysfs_create_file(&cls->kset.kobj,
7810 &attr_sched_smt_power_savings.attr);
7812 #ifdef CONFIG_SCHED_MC
7813 if (!err && mc_capable())
7814 err = sysfs_create_file(&cls->kset.kobj,
7815 &attr_sched_mc_power_savings.attr);
7822 * Force a reinitialization of the sched domains hierarchy. The domains
7823 * and groups cannot be updated in place without racing with the balancing
7824 * code, so we temporarily attach all running cpus to the NULL domain
7825 * which will prevent rebalancing while the sched domains are recalculated.
7827 static int update_sched_domains(struct notifier_block *nfb,
7828 unsigned long action, void *hcpu)
7831 case CPU_UP_PREPARE:
7832 case CPU_UP_PREPARE_FROZEN:
7833 case CPU_DOWN_PREPARE:
7834 case CPU_DOWN_PREPARE_FROZEN:
7835 detach_destroy_domains(&cpu_online_map);
7838 case CPU_UP_CANCELED:
7839 case CPU_UP_CANCELED_FROZEN:
7840 case CPU_DOWN_FAILED:
7841 case CPU_DOWN_FAILED_FROZEN:
7843 case CPU_ONLINE_FROZEN:
7845 case CPU_DEAD_FROZEN:
7847 * Fall through and re-initialise the domains.
7854 /* The hotplug lock is already held by cpu_up/cpu_down */
7855 arch_init_sched_domains(&cpu_online_map);
7860 void __init sched_init_smp(void)
7862 cpumask_t non_isolated_cpus;
7864 #if defined(CONFIG_NUMA)
7865 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
7867 BUG_ON(sched_group_nodes_bycpu == NULL);
7870 arch_init_sched_domains(&cpu_online_map);
7871 cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
7872 if (cpus_empty(non_isolated_cpus))
7873 cpu_set(smp_processor_id(), non_isolated_cpus);
7875 /* XXX: Theoretical race here - CPU may be hotplugged now */
7876 hotcpu_notifier(update_sched_domains, 0);
7878 /* Move init over to a non-isolated CPU */
7879 if (set_cpus_allowed_ptr(current, &non_isolated_cpus) < 0)
7881 sched_init_granularity();
7884 void __init sched_init_smp(void)
7886 #if defined(CONFIG_NUMA)
7887 sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
7889 BUG_ON(sched_group_nodes_bycpu == NULL);
7891 sched_init_granularity();
7893 #endif /* CONFIG_SMP */
7895 int in_sched_functions(unsigned long addr)
7897 return in_lock_functions(addr) ||
7898 (addr >= (unsigned long)__sched_text_start
7899 && addr < (unsigned long)__sched_text_end);
7902 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
7904 cfs_rq->tasks_timeline = RB_ROOT;
7905 INIT_LIST_HEAD(&cfs_rq->tasks);
7906 #ifdef CONFIG_FAIR_GROUP_SCHED
7909 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7912 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
7914 struct rt_prio_array *array;
7917 array = &rt_rq->active;
7918 for (i = 0; i < MAX_RT_PRIO; i++) {
7919 INIT_LIST_HEAD(array->queue + i);
7920 __clear_bit(i, array->bitmap);
7922 /* delimiter for bitsearch: */
7923 __set_bit(MAX_RT_PRIO, array->bitmap);
7925 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
7926 rt_rq->highest_prio = MAX_RT_PRIO;
7929 rt_rq->rt_nr_migratory = 0;
7930 rt_rq->overloaded = 0;
7934 rt_rq->rt_throttled = 0;
7935 rt_rq->rt_runtime = 0;
7936 spin_lock_init(&rt_rq->rt_runtime_lock);
7938 #ifdef CONFIG_RT_GROUP_SCHED
7939 rt_rq->rt_nr_boosted = 0;
7944 #ifdef CONFIG_FAIR_GROUP_SCHED
7945 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
7946 struct sched_entity *se, int cpu, int add,
7947 struct sched_entity *parent)
7949 struct rq *rq = cpu_rq(cpu);
7950 tg->cfs_rq[cpu] = cfs_rq;
7951 init_cfs_rq(cfs_rq, rq);
7954 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
7957 /* se could be NULL for init_task_group */
7962 se->cfs_rq = &rq->cfs;
7964 se->cfs_rq = parent->my_q;
7967 se->load.weight = tg->shares;
7968 se->load.inv_weight = div64_64(1ULL<<32, se->load.weight);
7969 se->parent = parent;
7973 #ifdef CONFIG_RT_GROUP_SCHED
7974 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
7975 struct sched_rt_entity *rt_se, int cpu, int add,
7976 struct sched_rt_entity *parent)
7978 struct rq *rq = cpu_rq(cpu);
7980 tg->rt_rq[cpu] = rt_rq;
7981 init_rt_rq(rt_rq, rq);
7983 rt_rq->rt_se = rt_se;
7984 rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
7986 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
7988 tg->rt_se[cpu] = rt_se;
7993 rt_se->rt_rq = &rq->rt;
7995 rt_se->rt_rq = parent->my_q;
7997 rt_se->rt_rq = &rq->rt;
7998 rt_se->my_q = rt_rq;
7999 rt_se->parent = parent;
8000 INIT_LIST_HEAD(&rt_se->run_list);
8004 void __init sched_init(void)
8007 unsigned long alloc_size = 0, ptr;
8009 #ifdef CONFIG_FAIR_GROUP_SCHED
8010 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8012 #ifdef CONFIG_RT_GROUP_SCHED
8013 alloc_size += 2 * nr_cpu_ids * sizeof(void **);
8015 #ifdef CONFIG_USER_SCHED
8019 * As sched_init() is called before page_alloc is setup,
8020 * we use alloc_bootmem().
8023 ptr = (unsigned long)alloc_bootmem_low(alloc_size);
8025 #ifdef CONFIG_FAIR_GROUP_SCHED
8026 init_task_group.se = (struct sched_entity **)ptr;
8027 ptr += nr_cpu_ids * sizeof(void **);
8029 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
8030 ptr += nr_cpu_ids * sizeof(void **);
8032 #ifdef CONFIG_USER_SCHED
8033 root_task_group.se = (struct sched_entity **)ptr;
8034 ptr += nr_cpu_ids * sizeof(void **);
8036 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
8037 ptr += nr_cpu_ids * sizeof(void **);
8040 #ifdef CONFIG_RT_GROUP_SCHED
8041 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
8042 ptr += nr_cpu_ids * sizeof(void **);
8044 init_task_group.rt_rq = (struct rt_rq **)ptr;
8045 ptr += nr_cpu_ids * sizeof(void **);
8047 #ifdef CONFIG_USER_SCHED
8048 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
8049 ptr += nr_cpu_ids * sizeof(void **);
8051 root_task_group.rt_rq = (struct rt_rq **)ptr;
8052 ptr += nr_cpu_ids * sizeof(void **);
8059 init_defrootdomain();
8062 init_rt_bandwidth(&def_rt_bandwidth,
8063 global_rt_period(), global_rt_runtime());
8065 #ifdef CONFIG_RT_GROUP_SCHED
8066 init_rt_bandwidth(&init_task_group.rt_bandwidth,
8067 global_rt_period(), global_rt_runtime());
8068 #ifdef CONFIG_USER_SCHED
8069 init_rt_bandwidth(&root_task_group.rt_bandwidth,
8070 global_rt_period(), RUNTIME_INF);
8074 #ifdef CONFIG_GROUP_SCHED
8075 list_add(&init_task_group.list, &task_groups);
8076 INIT_LIST_HEAD(&init_task_group.children);
8078 #ifdef CONFIG_USER_SCHED
8079 INIT_LIST_HEAD(&root_task_group.children);
8080 init_task_group.parent = &root_task_group;
8081 list_add(&init_task_group.siblings, &root_task_group.children);
8085 for_each_possible_cpu(i) {
8089 spin_lock_init(&rq->lock);
8090 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
8093 update_last_tick_seen(rq);
8094 init_cfs_rq(&rq->cfs, rq);
8095 init_rt_rq(&rq->rt, rq);
8096 #ifdef CONFIG_FAIR_GROUP_SCHED
8097 init_task_group.shares = init_task_group_load;
8098 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
8099 #ifdef CONFIG_CGROUP_SCHED
8101 * How much cpu bandwidth does init_task_group get?
8103 * In case of task-groups formed thr' the cgroup filesystem, it
8104 * gets 100% of the cpu resources in the system. This overall
8105 * system cpu resource is divided among the tasks of
8106 * init_task_group and its child task-groups in a fair manner,
8107 * based on each entity's (task or task-group's) weight
8108 * (se->load.weight).
8110 * In other words, if init_task_group has 10 tasks of weight
8111 * 1024) and two child groups A0 and A1 (of weight 1024 each),
8112 * then A0's share of the cpu resource is:
8114 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
8116 * We achieve this by letting init_task_group's tasks sit
8117 * directly in rq->cfs (i.e init_task_group->se[] = NULL).
8119 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL);
8120 #elif defined CONFIG_USER_SCHED
8121 root_task_group.shares = NICE_0_LOAD;
8122 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, 0, NULL);
8124 * In case of task-groups formed thr' the user id of tasks,
8125 * init_task_group represents tasks belonging to root user.
8126 * Hence it forms a sibling of all subsequent groups formed.
8127 * In this case, init_task_group gets only a fraction of overall
8128 * system cpu resource, based on the weight assigned to root
8129 * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
8130 * by letting tasks of init_task_group sit in a separate cfs_rq
8131 * (init_cfs_rq) and having one entity represent this group of
8132 * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
8134 init_tg_cfs_entry(&init_task_group,
8135 &per_cpu(init_cfs_rq, i),
8136 &per_cpu(init_sched_entity, i), i, 1,
8137 root_task_group.se[i]);
8140 #endif /* CONFIG_FAIR_GROUP_SCHED */
8142 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
8143 #ifdef CONFIG_RT_GROUP_SCHED
8144 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
8145 #ifdef CONFIG_CGROUP_SCHED
8146 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL);
8147 #elif defined CONFIG_USER_SCHED
8148 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, 0, NULL);
8149 init_tg_rt_entry(&init_task_group,
8150 &per_cpu(init_rt_rq, i),
8151 &per_cpu(init_sched_rt_entity, i), i, 1,
8152 root_task_group.rt_se[i]);
8156 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
8157 rq->cpu_load[j] = 0;
8161 rq->active_balance = 0;
8162 rq->next_balance = jiffies;
8165 rq->migration_thread = NULL;
8166 INIT_LIST_HEAD(&rq->migration_queue);
8167 rq_attach_root(rq, &def_root_domain);
8170 atomic_set(&rq->nr_iowait, 0);
8173 set_load_weight(&init_task);
8175 #ifdef CONFIG_PREEMPT_NOTIFIERS
8176 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
8180 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
8183 #ifdef CONFIG_RT_MUTEXES
8184 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
8188 * The boot idle thread does lazy MMU switching as well:
8190 atomic_inc(&init_mm.mm_count);
8191 enter_lazy_tlb(&init_mm, current);
8194 * Make us the idle thread. Technically, schedule() should not be
8195 * called from this thread, however somewhere below it might be,
8196 * but because we are the idle thread, we just pick up running again
8197 * when this runqueue becomes "idle".
8199 init_idle(current, smp_processor_id());
8201 * During early bootup we pretend to be a normal task:
8203 current->sched_class = &fair_sched_class;
8205 scheduler_running = 1;
8208 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
8209 void __might_sleep(char *file, int line)
8212 static unsigned long prev_jiffy; /* ratelimiting */
8214 if ((in_atomic() || irqs_disabled()) &&
8215 system_state == SYSTEM_RUNNING && !oops_in_progress) {
8216 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
8218 prev_jiffy = jiffies;
8219 printk(KERN_ERR "BUG: sleeping function called from invalid"
8220 " context at %s:%d\n", file, line);
8221 printk("in_atomic():%d, irqs_disabled():%d\n",
8222 in_atomic(), irqs_disabled());
8223 debug_show_held_locks(current);
8224 if (irqs_disabled())
8225 print_irqtrace_events(current);
8230 EXPORT_SYMBOL(__might_sleep);
8233 #ifdef CONFIG_MAGIC_SYSRQ
8234 static void normalize_task(struct rq *rq, struct task_struct *p)
8237 update_rq_clock(rq);
8238 on_rq = p->se.on_rq;
8240 deactivate_task(rq, p, 0);
8241 __setscheduler(rq, p, SCHED_NORMAL, 0);
8243 activate_task(rq, p, 0);
8244 resched_task(rq->curr);
8248 void normalize_rt_tasks(void)
8250 struct task_struct *g, *p;
8251 unsigned long flags;
8254 read_lock_irqsave(&tasklist_lock, flags);
8255 do_each_thread(g, p) {
8257 * Only normalize user tasks:
8262 p->se.exec_start = 0;
8263 #ifdef CONFIG_SCHEDSTATS
8264 p->se.wait_start = 0;
8265 p->se.sleep_start = 0;
8266 p->se.block_start = 0;
8268 task_rq(p)->clock = 0;
8272 * Renice negative nice level userspace
8275 if (TASK_NICE(p) < 0 && p->mm)
8276 set_user_nice(p, 0);
8280 spin_lock(&p->pi_lock);
8281 rq = __task_rq_lock(p);
8283 normalize_task(rq, p);
8285 __task_rq_unlock(rq);
8286 spin_unlock(&p->pi_lock);
8287 } while_each_thread(g, p);
8289 read_unlock_irqrestore(&tasklist_lock, flags);
8292 #endif /* CONFIG_MAGIC_SYSRQ */
8296 * These functions are only useful for the IA64 MCA handling.
8298 * They can only be called when the whole system has been
8299 * stopped - every CPU needs to be quiescent, and no scheduling
8300 * activity can take place. Using them for anything else would
8301 * be a serious bug, and as a result, they aren't even visible
8302 * under any other configuration.
8306 * curr_task - return the current task for a given cpu.
8307 * @cpu: the processor in question.
8309 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8311 struct task_struct *curr_task(int cpu)
8313 return cpu_curr(cpu);
8317 * set_curr_task - set the current task for a given cpu.
8318 * @cpu: the processor in question.
8319 * @p: the task pointer to set.
8321 * Description: This function must only be used when non-maskable interrupts
8322 * are serviced on a separate stack. It allows the architecture to switch the
8323 * notion of the current task on a cpu in a non-blocking manner. This function
8324 * must be called with all CPU's synchronized, and interrupts disabled, the
8325 * and caller must save the original value of the current task (see
8326 * curr_task() above) and restore that value before reenabling interrupts and
8327 * re-starting the system.
8329 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8331 void set_curr_task(int cpu, struct task_struct *p)
8338 #ifdef CONFIG_FAIR_GROUP_SCHED
8339 static void free_fair_sched_group(struct task_group *tg)
8343 for_each_possible_cpu(i) {
8345 kfree(tg->cfs_rq[i]);
8355 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8357 struct cfs_rq *cfs_rq;
8358 struct sched_entity *se, *parent_se;
8362 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
8365 tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
8369 tg->shares = NICE_0_LOAD;
8371 for_each_possible_cpu(i) {
8374 cfs_rq = kmalloc_node(sizeof(struct cfs_rq),
8375 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8379 se = kmalloc_node(sizeof(struct sched_entity),
8380 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8384 parent_se = parent ? parent->se[i] : NULL;
8385 init_tg_cfs_entry(tg, cfs_rq, se, i, 0, parent_se);
8394 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8396 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
8397 &cpu_rq(cpu)->leaf_cfs_rq_list);
8400 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8402 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
8405 static inline void free_fair_sched_group(struct task_group *tg)
8410 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8415 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8419 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8424 #ifdef CONFIG_RT_GROUP_SCHED
8425 static void free_rt_sched_group(struct task_group *tg)
8429 destroy_rt_bandwidth(&tg->rt_bandwidth);
8431 for_each_possible_cpu(i) {
8433 kfree(tg->rt_rq[i]);
8435 kfree(tg->rt_se[i]);
8443 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8445 struct rt_rq *rt_rq;
8446 struct sched_rt_entity *rt_se, *parent_se;
8450 tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
8453 tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
8457 init_rt_bandwidth(&tg->rt_bandwidth,
8458 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
8460 for_each_possible_cpu(i) {
8463 rt_rq = kmalloc_node(sizeof(struct rt_rq),
8464 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8468 rt_se = kmalloc_node(sizeof(struct sched_rt_entity),
8469 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8473 parent_se = parent ? parent->rt_se[i] : NULL;
8474 init_tg_rt_entry(tg, rt_rq, rt_se, i, 0, parent_se);
8483 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8485 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
8486 &cpu_rq(cpu)->leaf_rt_rq_list);
8489 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8491 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
8494 static inline void free_rt_sched_group(struct task_group *tg)
8499 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8504 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8508 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8513 #ifdef CONFIG_GROUP_SCHED
8514 static void free_sched_group(struct task_group *tg)
8516 free_fair_sched_group(tg);
8517 free_rt_sched_group(tg);
8521 /* allocate runqueue etc for a new task group */
8522 struct task_group *sched_create_group(struct task_group *parent)
8524 struct task_group *tg;
8525 unsigned long flags;
8528 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
8530 return ERR_PTR(-ENOMEM);
8532 if (!alloc_fair_sched_group(tg, parent))
8535 if (!alloc_rt_sched_group(tg, parent))
8538 spin_lock_irqsave(&task_group_lock, flags);
8539 for_each_possible_cpu(i) {
8540 register_fair_sched_group(tg, i);
8541 register_rt_sched_group(tg, i);
8543 list_add_rcu(&tg->list, &task_groups);
8545 WARN_ON(!parent); /* root should already exist */
8547 tg->parent = parent;
8548 list_add_rcu(&tg->siblings, &parent->children);
8549 INIT_LIST_HEAD(&tg->children);
8550 spin_unlock_irqrestore(&task_group_lock, flags);
8555 free_sched_group(tg);
8556 return ERR_PTR(-ENOMEM);
8559 /* rcu callback to free various structures associated with a task group */
8560 static void free_sched_group_rcu(struct rcu_head *rhp)
8562 /* now it should be safe to free those cfs_rqs */
8563 free_sched_group(container_of(rhp, struct task_group, rcu));
8566 /* Destroy runqueue etc associated with a task group */
8567 void sched_destroy_group(struct task_group *tg)
8569 unsigned long flags;
8572 spin_lock_irqsave(&task_group_lock, flags);
8573 for_each_possible_cpu(i) {
8574 unregister_fair_sched_group(tg, i);
8575 unregister_rt_sched_group(tg, i);
8577 list_del_rcu(&tg->list);
8578 list_del_rcu(&tg->siblings);
8579 spin_unlock_irqrestore(&task_group_lock, flags);
8581 /* wait for possible concurrent references to cfs_rqs complete */
8582 call_rcu(&tg->rcu, free_sched_group_rcu);
8585 /* change task's runqueue when it moves between groups.
8586 * The caller of this function should have put the task in its new group
8587 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8588 * reflect its new group.
8590 void sched_move_task(struct task_struct *tsk)
8593 unsigned long flags;
8596 rq = task_rq_lock(tsk, &flags);
8598 update_rq_clock(rq);
8600 running = task_current(rq, tsk);
8601 on_rq = tsk->se.on_rq;
8604 dequeue_task(rq, tsk, 0);
8605 if (unlikely(running))
8606 tsk->sched_class->put_prev_task(rq, tsk);
8608 set_task_rq(tsk, task_cpu(tsk));
8610 #ifdef CONFIG_FAIR_GROUP_SCHED
8611 if (tsk->sched_class->moved_group)
8612 tsk->sched_class->moved_group(tsk);
8615 if (unlikely(running))
8616 tsk->sched_class->set_curr_task(rq);
8618 enqueue_task(rq, tsk, 0);
8620 task_rq_unlock(rq, &flags);
8624 #ifdef CONFIG_FAIR_GROUP_SCHED
8625 static void __set_se_shares(struct sched_entity *se, unsigned long shares)
8627 struct cfs_rq *cfs_rq = se->cfs_rq;
8632 dequeue_entity(cfs_rq, se, 0);
8634 se->load.weight = shares;
8635 se->load.inv_weight = div64_64((1ULL<<32), shares);
8638 enqueue_entity(cfs_rq, se, 0);
8641 static void set_se_shares(struct sched_entity *se, unsigned long shares)
8643 struct cfs_rq *cfs_rq = se->cfs_rq;
8644 struct rq *rq = cfs_rq->rq;
8645 unsigned long flags;
8647 spin_lock_irqsave(&rq->lock, flags);
8648 __set_se_shares(se, shares);
8649 spin_unlock_irqrestore(&rq->lock, flags);
8652 static DEFINE_MUTEX(shares_mutex);
8654 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8657 unsigned long flags;
8660 * We can't change the weight of the root cgroup.
8666 * A weight of 0 or 1 can cause arithmetics problems.
8667 * (The default weight is 1024 - so there's no practical
8668 * limitation from this.)
8670 if (shares < MIN_SHARES)
8671 shares = MIN_SHARES;
8673 mutex_lock(&shares_mutex);
8674 if (tg->shares == shares)
8677 spin_lock_irqsave(&task_group_lock, flags);
8678 for_each_possible_cpu(i)
8679 unregister_fair_sched_group(tg, i);
8680 list_del_rcu(&tg->siblings);
8681 spin_unlock_irqrestore(&task_group_lock, flags);
8683 /* wait for any ongoing reference to this group to finish */
8684 synchronize_sched();
8687 * Now we are free to modify the group's share on each cpu
8688 * w/o tripping rebalance_share or load_balance_fair.
8690 tg->shares = shares;
8691 for_each_possible_cpu(i) {
8695 cfs_rq_set_shares(tg->cfs_rq[i], 0);
8696 set_se_shares(tg->se[i], shares/nr_cpu_ids);
8700 * Enable load balance activity on this group, by inserting it back on
8701 * each cpu's rq->leaf_cfs_rq_list.
8703 spin_lock_irqsave(&task_group_lock, flags);
8704 for_each_possible_cpu(i)
8705 register_fair_sched_group(tg, i);
8706 list_add_rcu(&tg->siblings, &tg->parent->children);
8707 spin_unlock_irqrestore(&task_group_lock, flags);
8709 mutex_unlock(&shares_mutex);
8713 unsigned long sched_group_shares(struct task_group *tg)
8719 #ifdef CONFIG_RT_GROUP_SCHED
8721 * Ensure that the real time constraints are schedulable.
8723 static DEFINE_MUTEX(rt_constraints_mutex);
8725 static unsigned long to_ratio(u64 period, u64 runtime)
8727 if (runtime == RUNTIME_INF)
8730 return div64_64(runtime << 16, period);
8733 #ifdef CONFIG_CGROUP_SCHED
8734 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8736 struct task_group *tgi, *parent = tg->parent;
8737 unsigned long total = 0;
8740 if (global_rt_period() < period)
8743 return to_ratio(period, runtime) <
8744 to_ratio(global_rt_period(), global_rt_runtime());
8747 if (ktime_to_ns(parent->rt_bandwidth.rt_period) < period)
8751 list_for_each_entry_rcu(tgi, &parent->children, siblings) {
8755 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
8756 tgi->rt_bandwidth.rt_runtime);
8760 return total + to_ratio(period, runtime) <
8761 to_ratio(ktime_to_ns(parent->rt_bandwidth.rt_period),
8762 parent->rt_bandwidth.rt_runtime);
8764 #elif defined CONFIG_USER_SCHED
8765 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8767 struct task_group *tgi;
8768 unsigned long total = 0;
8769 unsigned long global_ratio =
8770 to_ratio(global_rt_period(), global_rt_runtime());
8773 list_for_each_entry_rcu(tgi, &task_groups, list) {
8777 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
8778 tgi->rt_bandwidth.rt_runtime);
8782 return total + to_ratio(period, runtime) < global_ratio;
8786 /* Must be called with tasklist_lock held */
8787 static inline int tg_has_rt_tasks(struct task_group *tg)
8789 struct task_struct *g, *p;
8790 do_each_thread(g, p) {
8791 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
8793 } while_each_thread(g, p);
8797 static int tg_set_bandwidth(struct task_group *tg,
8798 u64 rt_period, u64 rt_runtime)
8802 mutex_lock(&rt_constraints_mutex);
8803 read_lock(&tasklist_lock);
8804 if (rt_runtime == 0 && tg_has_rt_tasks(tg)) {
8808 if (!__rt_schedulable(tg, rt_period, rt_runtime)) {
8813 spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8814 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8815 tg->rt_bandwidth.rt_runtime = rt_runtime;
8817 for_each_possible_cpu(i) {
8818 struct rt_rq *rt_rq = tg->rt_rq[i];
8820 spin_lock(&rt_rq->rt_runtime_lock);
8821 rt_rq->rt_runtime = rt_runtime;
8822 spin_unlock(&rt_rq->rt_runtime_lock);
8824 spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8826 read_unlock(&tasklist_lock);
8827 mutex_unlock(&rt_constraints_mutex);
8832 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8834 u64 rt_runtime, rt_period;
8836 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8837 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8838 if (rt_runtime_us < 0)
8839 rt_runtime = RUNTIME_INF;
8841 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8844 long sched_group_rt_runtime(struct task_group *tg)
8848 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8851 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8852 do_div(rt_runtime_us, NSEC_PER_USEC);
8853 return rt_runtime_us;
8856 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
8858 u64 rt_runtime, rt_period;
8860 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
8861 rt_runtime = tg->rt_bandwidth.rt_runtime;
8863 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8866 long sched_group_rt_period(struct task_group *tg)
8870 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8871 do_div(rt_period_us, NSEC_PER_USEC);
8872 return rt_period_us;
8875 static int sched_rt_global_constraints(void)
8879 mutex_lock(&rt_constraints_mutex);
8880 if (!__rt_schedulable(NULL, 1, 0))
8882 mutex_unlock(&rt_constraints_mutex);
8887 static int sched_rt_global_constraints(void)
8889 unsigned long flags;
8892 spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
8893 for_each_possible_cpu(i) {
8894 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
8896 spin_lock(&rt_rq->rt_runtime_lock);
8897 rt_rq->rt_runtime = global_rt_runtime();
8898 spin_unlock(&rt_rq->rt_runtime_lock);
8900 spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
8906 int sched_rt_handler(struct ctl_table *table, int write,
8907 struct file *filp, void __user *buffer, size_t *lenp,
8911 int old_period, old_runtime;
8912 static DEFINE_MUTEX(mutex);
8915 old_period = sysctl_sched_rt_period;
8916 old_runtime = sysctl_sched_rt_runtime;
8918 ret = proc_dointvec(table, write, filp, buffer, lenp, ppos);
8920 if (!ret && write) {
8921 ret = sched_rt_global_constraints();
8923 sysctl_sched_rt_period = old_period;
8924 sysctl_sched_rt_runtime = old_runtime;
8926 def_rt_bandwidth.rt_runtime = global_rt_runtime();
8927 def_rt_bandwidth.rt_period =
8928 ns_to_ktime(global_rt_period());
8931 mutex_unlock(&mutex);
8936 #ifdef CONFIG_CGROUP_SCHED
8938 /* return corresponding task_group object of a cgroup */
8939 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
8941 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
8942 struct task_group, css);
8945 static struct cgroup_subsys_state *
8946 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
8948 struct task_group *tg, *parent;
8950 if (!cgrp->parent) {
8951 /* This is early initialization for the top cgroup */
8952 init_task_group.css.cgroup = cgrp;
8953 return &init_task_group.css;
8956 parent = cgroup_tg(cgrp->parent);
8957 tg = sched_create_group(parent);
8959 return ERR_PTR(-ENOMEM);
8961 /* Bind the cgroup to task_group object we just created */
8962 tg->css.cgroup = cgrp;
8968 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
8970 struct task_group *tg = cgroup_tg(cgrp);
8972 sched_destroy_group(tg);
8976 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8977 struct task_struct *tsk)
8979 #ifdef CONFIG_RT_GROUP_SCHED
8980 /* Don't accept realtime tasks when there is no way for them to run */
8981 if (rt_task(tsk) && cgroup_tg(cgrp)->rt_bandwidth.rt_runtime == 0)
8984 /* We don't support RT-tasks being in separate groups */
8985 if (tsk->sched_class != &fair_sched_class)
8993 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8994 struct cgroup *old_cont, struct task_struct *tsk)
8996 sched_move_task(tsk);
8999 #ifdef CONFIG_FAIR_GROUP_SCHED
9000 static int cpu_shares_write_uint(struct cgroup *cgrp, struct cftype *cftype,
9003 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
9006 static u64 cpu_shares_read_uint(struct cgroup *cgrp, struct cftype *cft)
9008 struct task_group *tg = cgroup_tg(cgrp);
9010 return (u64) tg->shares;
9014 #ifdef CONFIG_RT_GROUP_SCHED
9015 static ssize_t cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
9017 const char __user *userbuf,
9018 size_t nbytes, loff_t *unused_ppos)
9027 if (nbytes >= sizeof(buffer))
9029 if (copy_from_user(buffer, userbuf, nbytes))
9032 buffer[nbytes] = 0; /* nul-terminate */
9034 /* strip newline if necessary */
9035 if (nbytes && (buffer[nbytes-1] == '\n'))
9036 buffer[nbytes-1] = 0;
9037 val = simple_strtoll(buffer, &end, 0);
9041 /* Pass to subsystem */
9042 retval = sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
9048 static ssize_t cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft,
9050 char __user *buf, size_t nbytes,
9054 long val = sched_group_rt_runtime(cgroup_tg(cgrp));
9055 int len = sprintf(tmp, "%ld\n", val);
9057 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
9060 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
9063 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
9066 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
9068 return sched_group_rt_period(cgroup_tg(cgrp));
9072 static struct cftype cpu_files[] = {
9073 #ifdef CONFIG_FAIR_GROUP_SCHED
9076 .read_uint = cpu_shares_read_uint,
9077 .write_uint = cpu_shares_write_uint,
9080 #ifdef CONFIG_RT_GROUP_SCHED
9082 .name = "rt_runtime_us",
9083 .read = cpu_rt_runtime_read,
9084 .write = cpu_rt_runtime_write,
9087 .name = "rt_period_us",
9088 .read_uint = cpu_rt_period_read_uint,
9089 .write_uint = cpu_rt_period_write_uint,
9094 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
9096 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
9099 struct cgroup_subsys cpu_cgroup_subsys = {
9101 .create = cpu_cgroup_create,
9102 .destroy = cpu_cgroup_destroy,
9103 .can_attach = cpu_cgroup_can_attach,
9104 .attach = cpu_cgroup_attach,
9105 .populate = cpu_cgroup_populate,
9106 .subsys_id = cpu_cgroup_subsys_id,
9110 #endif /* CONFIG_CGROUP_SCHED */
9112 #ifdef CONFIG_CGROUP_CPUACCT
9115 * CPU accounting code for task groups.
9117 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
9118 * (balbir@in.ibm.com).
9121 /* track cpu usage of a group of tasks */
9123 struct cgroup_subsys_state css;
9124 /* cpuusage holds pointer to a u64-type object on every cpu */
9128 struct cgroup_subsys cpuacct_subsys;
9130 /* return cpu accounting group corresponding to this container */
9131 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
9133 return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
9134 struct cpuacct, css);
9137 /* return cpu accounting group to which this task belongs */
9138 static inline struct cpuacct *task_ca(struct task_struct *tsk)
9140 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
9141 struct cpuacct, css);
9144 /* create a new cpu accounting group */
9145 static struct cgroup_subsys_state *cpuacct_create(
9146 struct cgroup_subsys *ss, struct cgroup *cgrp)
9148 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
9151 return ERR_PTR(-ENOMEM);
9153 ca->cpuusage = alloc_percpu(u64);
9154 if (!ca->cpuusage) {
9156 return ERR_PTR(-ENOMEM);
9162 /* destroy an existing cpu accounting group */
9164 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
9166 struct cpuacct *ca = cgroup_ca(cgrp);
9168 free_percpu(ca->cpuusage);
9172 /* return total cpu usage (in nanoseconds) of a group */
9173 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
9175 struct cpuacct *ca = cgroup_ca(cgrp);
9176 u64 totalcpuusage = 0;
9179 for_each_possible_cpu(i) {
9180 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
9183 * Take rq->lock to make 64-bit addition safe on 32-bit
9186 spin_lock_irq(&cpu_rq(i)->lock);
9187 totalcpuusage += *cpuusage;
9188 spin_unlock_irq(&cpu_rq(i)->lock);
9191 return totalcpuusage;
9194 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
9197 struct cpuacct *ca = cgroup_ca(cgrp);
9206 for_each_possible_cpu(i) {
9207 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
9209 spin_lock_irq(&cpu_rq(i)->lock);
9211 spin_unlock_irq(&cpu_rq(i)->lock);
9217 static struct cftype files[] = {
9220 .read_uint = cpuusage_read,
9221 .write_uint = cpuusage_write,
9225 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
9227 return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
9231 * charge this task's execution time to its accounting group.
9233 * called with rq->lock held.
9235 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
9239 if (!cpuacct_subsys.active)
9244 u64 *cpuusage = percpu_ptr(ca->cpuusage, task_cpu(tsk));
9246 *cpuusage += cputime;
9250 struct cgroup_subsys cpuacct_subsys = {
9252 .create = cpuacct_create,
9253 .destroy = cpuacct_destroy,
9254 .populate = cpuacct_populate,
9255 .subsys_id = cpuacct_subsys_id,
9257 #endif /* CONFIG_CGROUP_CPUACCT */