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>
72 #include <asm/irq_regs.h>
75 * Scheduler clock - returns current time in nanosec units.
76 * This is default implementation.
77 * Architectures and sub-architectures can override this.
79 unsigned long long __attribute__((weak)) sched_clock(void)
81 return (unsigned long long)jiffies * (NSEC_PER_SEC / HZ);
85 * Convert user-nice values [ -20 ... 0 ... 19 ]
86 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
89 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
90 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
91 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
94 * 'User priority' is the nice value converted to something we
95 * can work with better when scaling various scheduler parameters,
96 * it's a [ 0 ... 39 ] range.
98 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
99 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
100 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
103 * Helpers for converting nanosecond timing to jiffy resolution
105 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
107 #define NICE_0_LOAD SCHED_LOAD_SCALE
108 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
111 * These are the 'tuning knobs' of the scheduler:
113 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
114 * Timeslices get refilled after they expire.
116 #define DEF_TIMESLICE (100 * HZ / 1000)
120 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
121 * Since cpu_power is a 'constant', we can use a reciprocal divide.
123 static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
125 return reciprocal_divide(load, sg->reciprocal_cpu_power);
129 * Each time a sched group cpu_power is changed,
130 * we must compute its reciprocal value
132 static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
134 sg->__cpu_power += val;
135 sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
139 static inline int rt_policy(int policy)
141 if (unlikely(policy == SCHED_FIFO) || unlikely(policy == SCHED_RR))
146 static inline int task_has_rt_policy(struct task_struct *p)
148 return rt_policy(p->policy);
152 * This is the priority-queue data structure of the RT scheduling class:
154 struct rt_prio_array {
155 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
156 struct list_head queue[MAX_RT_PRIO];
159 #ifdef CONFIG_GROUP_SCHED
161 #include <linux/cgroup.h>
165 static LIST_HEAD(task_groups);
167 /* task group related information */
169 #ifdef CONFIG_CGROUP_SCHED
170 struct cgroup_subsys_state css;
173 #ifdef CONFIG_FAIR_GROUP_SCHED
174 /* schedulable entities of this group on each cpu */
175 struct sched_entity **se;
176 /* runqueue "owned" by this group on each cpu */
177 struct cfs_rq **cfs_rq;
178 unsigned long shares;
181 #ifdef CONFIG_RT_GROUP_SCHED
182 struct sched_rt_entity **rt_se;
183 struct rt_rq **rt_rq;
189 struct list_head list;
192 #ifdef CONFIG_FAIR_GROUP_SCHED
193 /* Default task group's sched entity on each cpu */
194 static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
195 /* Default task group's cfs_rq on each cpu */
196 static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;
198 static struct sched_entity *init_sched_entity_p[NR_CPUS];
199 static struct cfs_rq *init_cfs_rq_p[NR_CPUS];
202 #ifdef CONFIG_RT_GROUP_SCHED
203 static DEFINE_PER_CPU(struct sched_rt_entity, init_sched_rt_entity);
204 static DEFINE_PER_CPU(struct rt_rq, init_rt_rq) ____cacheline_aligned_in_smp;
206 static struct sched_rt_entity *init_sched_rt_entity_p[NR_CPUS];
207 static struct rt_rq *init_rt_rq_p[NR_CPUS];
210 /* task_group_lock serializes add/remove of task groups and also changes to
211 * a task group's cpu shares.
213 static DEFINE_SPINLOCK(task_group_lock);
215 /* doms_cur_mutex serializes access to doms_cur[] array */
216 static DEFINE_MUTEX(doms_cur_mutex);
218 #ifdef CONFIG_FAIR_GROUP_SCHED
219 #ifdef CONFIG_USER_SCHED
220 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
222 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
225 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
228 /* Default task group.
229 * Every task in system belong to this group at bootup.
231 struct task_group init_task_group = {
232 #ifdef CONFIG_FAIR_GROUP_SCHED
233 .se = init_sched_entity_p,
234 .cfs_rq = init_cfs_rq_p,
237 #ifdef CONFIG_RT_GROUP_SCHED
238 .rt_se = init_sched_rt_entity_p,
239 .rt_rq = init_rt_rq_p,
243 /* return group to which a task belongs */
244 static inline struct task_group *task_group(struct task_struct *p)
246 struct task_group *tg;
248 #ifdef CONFIG_USER_SCHED
250 #elif defined(CONFIG_CGROUP_SCHED)
251 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
252 struct task_group, css);
254 tg = &init_task_group;
259 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
260 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
262 #ifdef CONFIG_FAIR_GROUP_SCHED
263 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
264 p->se.parent = task_group(p)->se[cpu];
267 #ifdef CONFIG_RT_GROUP_SCHED
268 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
269 p->rt.parent = task_group(p)->rt_se[cpu];
273 static inline void lock_doms_cur(void)
275 mutex_lock(&doms_cur_mutex);
278 static inline void unlock_doms_cur(void)
280 mutex_unlock(&doms_cur_mutex);
285 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
286 static inline void lock_doms_cur(void) { }
287 static inline void unlock_doms_cur(void) { }
289 #endif /* CONFIG_GROUP_SCHED */
291 /* CFS-related fields in a runqueue */
293 struct load_weight load;
294 unsigned long nr_running;
299 struct rb_root tasks_timeline;
300 struct rb_node *rb_leftmost;
301 struct rb_node *rb_load_balance_curr;
302 /* 'curr' points to currently running entity on this cfs_rq.
303 * It is set to NULL otherwise (i.e when none are currently running).
305 struct sched_entity *curr, *next;
307 unsigned long nr_spread_over;
309 #ifdef CONFIG_FAIR_GROUP_SCHED
310 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
313 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
314 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
315 * (like users, containers etc.)
317 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
318 * list is used during load balance.
320 struct list_head leaf_cfs_rq_list;
321 struct task_group *tg; /* group that "owns" this runqueue */
325 /* Real-Time classes' related field in a runqueue: */
327 struct rt_prio_array active;
328 unsigned long rt_nr_running;
329 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
330 int highest_prio; /* highest queued rt task prio */
333 unsigned long rt_nr_migratory;
339 #ifdef CONFIG_RT_GROUP_SCHED
340 unsigned long rt_nr_boosted;
343 struct list_head leaf_rt_rq_list;
344 struct task_group *tg;
345 struct sched_rt_entity *rt_se;
352 * We add the notion of a root-domain which will be used to define per-domain
353 * variables. Each exclusive cpuset essentially defines an island domain by
354 * fully partitioning the member cpus from any other cpuset. Whenever a new
355 * exclusive cpuset is created, we also create and attach a new root-domain
365 * The "RT overload" flag: it gets set if a CPU has more than
366 * one runnable RT task.
373 * By default the system creates a single root-domain with all cpus as
374 * members (mimicking the global state we have today).
376 static struct root_domain def_root_domain;
381 * This is the main, per-CPU runqueue data structure.
383 * Locking rule: those places that want to lock multiple runqueues
384 * (such as the load balancing or the thread migration code), lock
385 * acquire operations must be ordered by ascending &runqueue.
392 * nr_running and cpu_load should be in the same cacheline because
393 * remote CPUs use both these fields when doing load calculation.
395 unsigned long nr_running;
396 #define CPU_LOAD_IDX_MAX 5
397 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
398 unsigned char idle_at_tick;
400 unsigned long last_tick_seen;
401 unsigned char in_nohz_recently;
403 /* capture load from *all* tasks on this cpu: */
404 struct load_weight load;
405 unsigned long nr_load_updates;
410 u64 rt_period_expire;
413 #ifdef CONFIG_FAIR_GROUP_SCHED
414 /* list of leaf cfs_rq on this cpu: */
415 struct list_head leaf_cfs_rq_list;
417 #ifdef CONFIG_RT_GROUP_SCHED
418 struct list_head leaf_rt_rq_list;
422 * This is part of a global counter where only the total sum
423 * over all CPUs matters. A task can increase this counter on
424 * one CPU and if it got migrated afterwards it may decrease
425 * it on another CPU. Always updated under the runqueue lock:
427 unsigned long nr_uninterruptible;
429 struct task_struct *curr, *idle;
430 unsigned long next_balance;
431 struct mm_struct *prev_mm;
433 u64 clock, prev_clock_raw;
436 unsigned int clock_warps, clock_overflows, clock_underflows;
438 unsigned int clock_deep_idle_events;
444 struct root_domain *rd;
445 struct sched_domain *sd;
447 /* For active balancing */
450 /* cpu of this runqueue: */
453 struct task_struct *migration_thread;
454 struct list_head migration_queue;
457 #ifdef CONFIG_SCHED_HRTICK
458 unsigned long hrtick_flags;
459 ktime_t hrtick_expire;
460 struct hrtimer hrtick_timer;
463 #ifdef CONFIG_SCHEDSTATS
465 struct sched_info rq_sched_info;
467 /* sys_sched_yield() stats */
468 unsigned int yld_exp_empty;
469 unsigned int yld_act_empty;
470 unsigned int yld_both_empty;
471 unsigned int yld_count;
473 /* schedule() stats */
474 unsigned int sched_switch;
475 unsigned int sched_count;
476 unsigned int sched_goidle;
478 /* try_to_wake_up() stats */
479 unsigned int ttwu_count;
480 unsigned int ttwu_local;
483 unsigned int bkl_count;
485 struct lock_class_key rq_lock_key;
488 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
490 static inline void check_preempt_curr(struct rq *rq, struct task_struct *p)
492 rq->curr->sched_class->check_preempt_curr(rq, p);
495 static inline int cpu_of(struct rq *rq)
505 static inline bool nohz_on(int cpu)
507 return tick_get_tick_sched(cpu)->nohz_mode != NOHZ_MODE_INACTIVE;
510 static inline u64 max_skipped_ticks(struct rq *rq)
512 return nohz_on(cpu_of(rq)) ? jiffies - rq->last_tick_seen + 2 : 1;
515 static inline void update_last_tick_seen(struct rq *rq)
517 rq->last_tick_seen = jiffies;
520 static inline u64 max_skipped_ticks(struct rq *rq)
525 static inline void update_last_tick_seen(struct rq *rq)
531 * Update the per-runqueue clock, as finegrained as the platform can give
532 * us, but without assuming monotonicity, etc.:
534 static void __update_rq_clock(struct rq *rq)
536 u64 prev_raw = rq->prev_clock_raw;
537 u64 now = sched_clock();
538 s64 delta = now - prev_raw;
539 u64 clock = rq->clock;
541 #ifdef CONFIG_SCHED_DEBUG
542 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
545 * Protect against sched_clock() occasionally going backwards:
547 if (unlikely(delta < 0)) {
552 * Catch too large forward jumps too:
554 u64 max_jump = max_skipped_ticks(rq) * TICK_NSEC;
555 u64 max_time = rq->tick_timestamp + max_jump;
557 if (unlikely(clock + delta > max_time)) {
558 if (clock < max_time)
562 rq->clock_overflows++;
564 if (unlikely(delta > rq->clock_max_delta))
565 rq->clock_max_delta = delta;
570 rq->prev_clock_raw = now;
574 static void update_rq_clock(struct rq *rq)
576 if (likely(smp_processor_id() == cpu_of(rq)))
577 __update_rq_clock(rq);
581 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
582 * See detach_destroy_domains: synchronize_sched for details.
584 * The domain tree of any CPU may only be accessed from within
585 * preempt-disabled sections.
587 #define for_each_domain(cpu, __sd) \
588 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
590 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
591 #define this_rq() (&__get_cpu_var(runqueues))
592 #define task_rq(p) cpu_rq(task_cpu(p))
593 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
595 unsigned long rt_needs_cpu(int cpu)
597 struct rq *rq = cpu_rq(cpu);
600 if (!rq->rt_throttled)
603 if (rq->clock > rq->rt_period_expire)
606 delta = rq->rt_period_expire - rq->clock;
607 do_div(delta, NSEC_PER_SEC / HZ);
609 return (unsigned long)delta;
613 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
615 #ifdef CONFIG_SCHED_DEBUG
616 # define const_debug __read_mostly
618 # define const_debug static const
622 * Debugging: various feature bits
625 SCHED_FEAT_NEW_FAIR_SLEEPERS = 1,
626 SCHED_FEAT_WAKEUP_PREEMPT = 2,
627 SCHED_FEAT_START_DEBIT = 4,
628 SCHED_FEAT_HRTICK = 8,
629 SCHED_FEAT_DOUBLE_TICK = 16,
630 SCHED_FEAT_SYNC_WAKEUPS = 32,
631 SCHED_FEAT_AFFINE_WAKEUPS = 64,
634 const_debug unsigned int sysctl_sched_features =
635 SCHED_FEAT_NEW_FAIR_SLEEPERS * 1 |
636 SCHED_FEAT_WAKEUP_PREEMPT * 1 |
637 SCHED_FEAT_START_DEBIT * 1 |
638 SCHED_FEAT_HRTICK * 1 |
639 SCHED_FEAT_DOUBLE_TICK * 0 |
640 SCHED_FEAT_SYNC_WAKEUPS * 0 |
641 SCHED_FEAT_AFFINE_WAKEUPS * 1;
643 #define sched_feat(x) (sysctl_sched_features & SCHED_FEAT_##x)
646 * Number of tasks to iterate in a single balance run.
647 * Limited because this is done with IRQs disabled.
649 const_debug unsigned int sysctl_sched_nr_migrate = 32;
652 * period over which we measure -rt task cpu usage in us.
655 unsigned int sysctl_sched_rt_period = 1000000;
657 static __read_mostly int scheduler_running;
660 * part of the period that we allow rt tasks to run in us.
663 int sysctl_sched_rt_runtime = 950000;
666 * single value that denotes runtime == period, ie unlimited time.
668 #define RUNTIME_INF ((u64)~0ULL)
670 static const unsigned long long time_sync_thresh = 100000;
672 static DEFINE_PER_CPU(unsigned long long, time_offset);
673 static DEFINE_PER_CPU(unsigned long long, prev_cpu_time);
676 * Global lock which we take every now and then to synchronize
677 * the CPUs time. This method is not warp-safe, but it's good
678 * enough to synchronize slowly diverging time sources and thus
679 * it's good enough for tracing:
681 static DEFINE_SPINLOCK(time_sync_lock);
682 static unsigned long long prev_global_time;
684 static unsigned long long __sync_cpu_clock(cycles_t time, int cpu)
688 spin_lock_irqsave(&time_sync_lock, flags);
690 if (time < prev_global_time) {
691 per_cpu(time_offset, cpu) += prev_global_time - time;
692 time = prev_global_time;
694 prev_global_time = time;
697 spin_unlock_irqrestore(&time_sync_lock, flags);
702 static unsigned long long __cpu_clock(int cpu)
704 unsigned long long now;
709 * Only call sched_clock() if the scheduler has already been
710 * initialized (some code might call cpu_clock() very early):
712 if (unlikely(!scheduler_running))
715 local_irq_save(flags);
719 local_irq_restore(flags);
725 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
726 * clock constructed from sched_clock():
728 unsigned long long cpu_clock(int cpu)
730 unsigned long long prev_cpu_time, time, delta_time;
732 prev_cpu_time = per_cpu(prev_cpu_time, cpu);
733 time = __cpu_clock(cpu) + per_cpu(time_offset, cpu);
734 delta_time = time-prev_cpu_time;
736 if (unlikely(delta_time > time_sync_thresh))
737 time = __sync_cpu_clock(time, cpu);
741 EXPORT_SYMBOL_GPL(cpu_clock);
743 #ifndef prepare_arch_switch
744 # define prepare_arch_switch(next) do { } while (0)
746 #ifndef finish_arch_switch
747 # define finish_arch_switch(prev) do { } while (0)
750 static inline int task_current(struct rq *rq, struct task_struct *p)
752 return rq->curr == p;
755 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
756 static inline int task_running(struct rq *rq, struct task_struct *p)
758 return task_current(rq, p);
761 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
765 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
767 #ifdef CONFIG_DEBUG_SPINLOCK
768 /* this is a valid case when another task releases the spinlock */
769 rq->lock.owner = current;
772 * If we are tracking spinlock dependencies then we have to
773 * fix up the runqueue lock - which gets 'carried over' from
776 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
778 spin_unlock_irq(&rq->lock);
781 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
782 static inline int task_running(struct rq *rq, struct task_struct *p)
787 return task_current(rq, p);
791 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
795 * We can optimise this out completely for !SMP, because the
796 * SMP rebalancing from interrupt is the only thing that cares
801 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
802 spin_unlock_irq(&rq->lock);
804 spin_unlock(&rq->lock);
808 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
812 * After ->oncpu is cleared, the task can be moved to a different CPU.
813 * We must ensure this doesn't happen until the switch is completely
819 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
823 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
826 * __task_rq_lock - lock the runqueue a given task resides on.
827 * Must be called interrupts disabled.
829 static inline struct rq *__task_rq_lock(struct task_struct *p)
833 struct rq *rq = task_rq(p);
834 spin_lock(&rq->lock);
835 if (likely(rq == task_rq(p)))
837 spin_unlock(&rq->lock);
842 * task_rq_lock - lock the runqueue a given task resides on and disable
843 * interrupts. Note the ordering: we can safely lookup the task_rq without
844 * explicitly disabling preemption.
846 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
852 local_irq_save(*flags);
854 spin_lock(&rq->lock);
855 if (likely(rq == task_rq(p)))
857 spin_unlock_irqrestore(&rq->lock, *flags);
861 static void __task_rq_unlock(struct rq *rq)
864 spin_unlock(&rq->lock);
867 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
870 spin_unlock_irqrestore(&rq->lock, *flags);
874 * this_rq_lock - lock this runqueue and disable interrupts.
876 static struct rq *this_rq_lock(void)
883 spin_lock(&rq->lock);
889 * We are going deep-idle (irqs are disabled):
891 void sched_clock_idle_sleep_event(void)
893 struct rq *rq = cpu_rq(smp_processor_id());
895 spin_lock(&rq->lock);
896 __update_rq_clock(rq);
897 spin_unlock(&rq->lock);
898 rq->clock_deep_idle_events++;
900 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
903 * We just idled delta nanoseconds (called with irqs disabled):
905 void sched_clock_idle_wakeup_event(u64 delta_ns)
907 struct rq *rq = cpu_rq(smp_processor_id());
908 u64 now = sched_clock();
910 rq->idle_clock += delta_ns;
912 * Override the previous timestamp and ignore all
913 * sched_clock() deltas that occured while we idled,
914 * and use the PM-provided delta_ns to advance the
917 spin_lock(&rq->lock);
918 rq->prev_clock_raw = now;
919 rq->clock += delta_ns;
920 spin_unlock(&rq->lock);
921 touch_softlockup_watchdog();
923 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
925 static void __resched_task(struct task_struct *p, int tif_bit);
927 static inline void resched_task(struct task_struct *p)
929 __resched_task(p, TIF_NEED_RESCHED);
932 #ifdef CONFIG_SCHED_HRTICK
934 * Use HR-timers to deliver accurate preemption points.
936 * Its all a bit involved since we cannot program an hrt while holding the
937 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
940 * When we get rescheduled we reprogram the hrtick_timer outside of the
943 static inline void resched_hrt(struct task_struct *p)
945 __resched_task(p, TIF_HRTICK_RESCHED);
948 static inline void resched_rq(struct rq *rq)
952 spin_lock_irqsave(&rq->lock, flags);
953 resched_task(rq->curr);
954 spin_unlock_irqrestore(&rq->lock, flags);
958 HRTICK_SET, /* re-programm hrtick_timer */
959 HRTICK_RESET, /* not a new slice */
964 * - enabled by features
965 * - hrtimer is actually high res
967 static inline int hrtick_enabled(struct rq *rq)
969 if (!sched_feat(HRTICK))
971 return hrtimer_is_hres_active(&rq->hrtick_timer);
975 * Called to set the hrtick timer state.
977 * called with rq->lock held and irqs disabled
979 static void hrtick_start(struct rq *rq, u64 delay, int reset)
981 assert_spin_locked(&rq->lock);
984 * preempt at: now + delay
987 ktime_add_ns(rq->hrtick_timer.base->get_time(), delay);
989 * indicate we need to program the timer
991 __set_bit(HRTICK_SET, &rq->hrtick_flags);
993 __set_bit(HRTICK_RESET, &rq->hrtick_flags);
996 * New slices are called from the schedule path and don't need a
1000 resched_hrt(rq->curr);
1003 static void hrtick_clear(struct rq *rq)
1005 if (hrtimer_active(&rq->hrtick_timer))
1006 hrtimer_cancel(&rq->hrtick_timer);
1010 * Update the timer from the possible pending state.
1012 static void hrtick_set(struct rq *rq)
1016 unsigned long flags;
1018 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1020 spin_lock_irqsave(&rq->lock, flags);
1021 set = __test_and_clear_bit(HRTICK_SET, &rq->hrtick_flags);
1022 reset = __test_and_clear_bit(HRTICK_RESET, &rq->hrtick_flags);
1023 time = rq->hrtick_expire;
1024 clear_thread_flag(TIF_HRTICK_RESCHED);
1025 spin_unlock_irqrestore(&rq->lock, flags);
1028 hrtimer_start(&rq->hrtick_timer, time, HRTIMER_MODE_ABS);
1029 if (reset && !hrtimer_active(&rq->hrtick_timer))
1036 * High-resolution timer tick.
1037 * Runs from hardirq context with interrupts disabled.
1039 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1041 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1043 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1045 spin_lock(&rq->lock);
1046 __update_rq_clock(rq);
1047 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1048 spin_unlock(&rq->lock);
1050 return HRTIMER_NORESTART;
1053 static inline void init_rq_hrtick(struct rq *rq)
1055 rq->hrtick_flags = 0;
1056 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1057 rq->hrtick_timer.function = hrtick;
1058 rq->hrtick_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
1061 void hrtick_resched(void)
1064 unsigned long flags;
1066 if (!test_thread_flag(TIF_HRTICK_RESCHED))
1069 local_irq_save(flags);
1070 rq = cpu_rq(smp_processor_id());
1072 local_irq_restore(flags);
1075 static inline void hrtick_clear(struct rq *rq)
1079 static inline void hrtick_set(struct rq *rq)
1083 static inline void init_rq_hrtick(struct rq *rq)
1087 void hrtick_resched(void)
1093 * resched_task - mark a task 'to be rescheduled now'.
1095 * On UP this means the setting of the need_resched flag, on SMP it
1096 * might also involve a cross-CPU call to trigger the scheduler on
1101 #ifndef tsk_is_polling
1102 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1105 static void __resched_task(struct task_struct *p, int tif_bit)
1109 assert_spin_locked(&task_rq(p)->lock);
1111 if (unlikely(test_tsk_thread_flag(p, tif_bit)))
1114 set_tsk_thread_flag(p, tif_bit);
1117 if (cpu == smp_processor_id())
1120 /* NEED_RESCHED must be visible before we test polling */
1122 if (!tsk_is_polling(p))
1123 smp_send_reschedule(cpu);
1126 static void resched_cpu(int cpu)
1128 struct rq *rq = cpu_rq(cpu);
1129 unsigned long flags;
1131 if (!spin_trylock_irqsave(&rq->lock, flags))
1133 resched_task(cpu_curr(cpu));
1134 spin_unlock_irqrestore(&rq->lock, flags);
1139 * When add_timer_on() enqueues a timer into the timer wheel of an
1140 * idle CPU then this timer might expire before the next timer event
1141 * which is scheduled to wake up that CPU. In case of a completely
1142 * idle system the next event might even be infinite time into the
1143 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1144 * leaves the inner idle loop so the newly added timer is taken into
1145 * account when the CPU goes back to idle and evaluates the timer
1146 * wheel for the next timer event.
1148 void wake_up_idle_cpu(int cpu)
1150 struct rq *rq = cpu_rq(cpu);
1152 if (cpu == smp_processor_id())
1156 * This is safe, as this function is called with the timer
1157 * wheel base lock of (cpu) held. When the CPU is on the way
1158 * to idle and has not yet set rq->curr to idle then it will
1159 * be serialized on the timer wheel base lock and take the new
1160 * timer into account automatically.
1162 if (rq->curr != rq->idle)
1166 * We can set TIF_RESCHED on the idle task of the other CPU
1167 * lockless. The worst case is that the other CPU runs the
1168 * idle task through an additional NOOP schedule()
1170 set_tsk_thread_flag(rq->idle, TIF_NEED_RESCHED);
1172 /* NEED_RESCHED must be visible before we test polling */
1174 if (!tsk_is_polling(rq->idle))
1175 smp_send_reschedule(cpu);
1180 static void __resched_task(struct task_struct *p, int tif_bit)
1182 assert_spin_locked(&task_rq(p)->lock);
1183 set_tsk_thread_flag(p, tif_bit);
1187 #if BITS_PER_LONG == 32
1188 # define WMULT_CONST (~0UL)
1190 # define WMULT_CONST (1UL << 32)
1193 #define WMULT_SHIFT 32
1196 * Shift right and round:
1198 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1200 static unsigned long
1201 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1202 struct load_weight *lw)
1206 if (unlikely(!lw->inv_weight))
1207 lw->inv_weight = (WMULT_CONST-lw->weight/2) / (lw->weight+1);
1209 tmp = (u64)delta_exec * weight;
1211 * Check whether we'd overflow the 64-bit multiplication:
1213 if (unlikely(tmp > WMULT_CONST))
1214 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1217 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1219 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1222 static inline unsigned long
1223 calc_delta_fair(unsigned long delta_exec, struct load_weight *lw)
1225 return calc_delta_mine(delta_exec, NICE_0_LOAD, lw);
1228 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1234 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1241 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1242 * of tasks with abnormal "nice" values across CPUs the contribution that
1243 * each task makes to its run queue's load is weighted according to its
1244 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1245 * scaled version of the new time slice allocation that they receive on time
1249 #define WEIGHT_IDLEPRIO 2
1250 #define WMULT_IDLEPRIO (1 << 31)
1253 * Nice levels are multiplicative, with a gentle 10% change for every
1254 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1255 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1256 * that remained on nice 0.
1258 * The "10% effect" is relative and cumulative: from _any_ nice level,
1259 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1260 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1261 * If a task goes up by ~10% and another task goes down by ~10% then
1262 * the relative distance between them is ~25%.)
1264 static const int prio_to_weight[40] = {
1265 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1266 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1267 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1268 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1269 /* 0 */ 1024, 820, 655, 526, 423,
1270 /* 5 */ 335, 272, 215, 172, 137,
1271 /* 10 */ 110, 87, 70, 56, 45,
1272 /* 15 */ 36, 29, 23, 18, 15,
1276 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1278 * In cases where the weight does not change often, we can use the
1279 * precalculated inverse to speed up arithmetics by turning divisions
1280 * into multiplications:
1282 static const u32 prio_to_wmult[40] = {
1283 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1284 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1285 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1286 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1287 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1288 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1289 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1290 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1293 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1296 * runqueue iterator, to support SMP load-balancing between different
1297 * scheduling classes, without having to expose their internal data
1298 * structures to the load-balancing proper:
1300 struct rq_iterator {
1302 struct task_struct *(*start)(void *);
1303 struct task_struct *(*next)(void *);
1307 static unsigned long
1308 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1309 unsigned long max_load_move, struct sched_domain *sd,
1310 enum cpu_idle_type idle, int *all_pinned,
1311 int *this_best_prio, struct rq_iterator *iterator);
1314 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1315 struct sched_domain *sd, enum cpu_idle_type idle,
1316 struct rq_iterator *iterator);
1319 #ifdef CONFIG_CGROUP_CPUACCT
1320 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1322 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1326 static unsigned long source_load(int cpu, int type);
1327 static unsigned long target_load(int cpu, int type);
1328 static unsigned long cpu_avg_load_per_task(int cpu);
1329 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1330 #endif /* CONFIG_SMP */
1332 #include "sched_stats.h"
1333 #include "sched_idletask.c"
1334 #include "sched_fair.c"
1335 #include "sched_rt.c"
1336 #ifdef CONFIG_SCHED_DEBUG
1337 # include "sched_debug.c"
1340 #define sched_class_highest (&rt_sched_class)
1342 static inline void inc_load(struct rq *rq, const struct task_struct *p)
1344 update_load_add(&rq->load, p->se.load.weight);
1347 static inline void dec_load(struct rq *rq, const struct task_struct *p)
1349 update_load_sub(&rq->load, p->se.load.weight);
1352 static void inc_nr_running(struct task_struct *p, struct rq *rq)
1358 static void dec_nr_running(struct task_struct *p, struct rq *rq)
1364 static void set_load_weight(struct task_struct *p)
1366 if (task_has_rt_policy(p)) {
1367 p->se.load.weight = prio_to_weight[0] * 2;
1368 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1373 * SCHED_IDLE tasks get minimal weight:
1375 if (p->policy == SCHED_IDLE) {
1376 p->se.load.weight = WEIGHT_IDLEPRIO;
1377 p->se.load.inv_weight = WMULT_IDLEPRIO;
1381 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1382 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1385 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1387 sched_info_queued(p);
1388 p->sched_class->enqueue_task(rq, p, wakeup);
1392 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1394 p->sched_class->dequeue_task(rq, p, sleep);
1399 * __normal_prio - return the priority that is based on the static prio
1401 static inline int __normal_prio(struct task_struct *p)
1403 return p->static_prio;
1407 * Calculate the expected normal priority: i.e. priority
1408 * without taking RT-inheritance into account. Might be
1409 * boosted by interactivity modifiers. Changes upon fork,
1410 * setprio syscalls, and whenever the interactivity
1411 * estimator recalculates.
1413 static inline int normal_prio(struct task_struct *p)
1417 if (task_has_rt_policy(p))
1418 prio = MAX_RT_PRIO-1 - p->rt_priority;
1420 prio = __normal_prio(p);
1425 * Calculate the current priority, i.e. the priority
1426 * taken into account by the scheduler. This value might
1427 * be boosted by RT tasks, or might be boosted by
1428 * interactivity modifiers. Will be RT if the task got
1429 * RT-boosted. If not then it returns p->normal_prio.
1431 static int effective_prio(struct task_struct *p)
1433 p->normal_prio = normal_prio(p);
1435 * If we are RT tasks or we were boosted to RT priority,
1436 * keep the priority unchanged. Otherwise, update priority
1437 * to the normal priority:
1439 if (!rt_prio(p->prio))
1440 return p->normal_prio;
1445 * activate_task - move a task to the runqueue.
1447 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1449 if (task_contributes_to_load(p))
1450 rq->nr_uninterruptible--;
1452 enqueue_task(rq, p, wakeup);
1453 inc_nr_running(p, rq);
1457 * deactivate_task - remove a task from the runqueue.
1459 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1461 if (task_contributes_to_load(p))
1462 rq->nr_uninterruptible++;
1464 dequeue_task(rq, p, sleep);
1465 dec_nr_running(p, rq);
1469 * task_curr - is this task currently executing on a CPU?
1470 * @p: the task in question.
1472 inline int task_curr(const struct task_struct *p)
1474 return cpu_curr(task_cpu(p)) == p;
1477 /* Used instead of source_load when we know the type == 0 */
1478 unsigned long weighted_cpuload(const int cpu)
1480 return cpu_rq(cpu)->load.weight;
1483 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1485 set_task_rq(p, cpu);
1488 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1489 * successfuly executed on another CPU. We must ensure that updates of
1490 * per-task data have been completed by this moment.
1493 task_thread_info(p)->cpu = cpu;
1497 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1498 const struct sched_class *prev_class,
1499 int oldprio, int running)
1501 if (prev_class != p->sched_class) {
1502 if (prev_class->switched_from)
1503 prev_class->switched_from(rq, p, running);
1504 p->sched_class->switched_to(rq, p, running);
1506 p->sched_class->prio_changed(rq, p, oldprio, running);
1512 * Is this task likely cache-hot:
1515 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
1520 * Buddy candidates are cache hot:
1522 if (&p->se == cfs_rq_of(&p->se)->next)
1525 if (p->sched_class != &fair_sched_class)
1528 if (sysctl_sched_migration_cost == -1)
1530 if (sysctl_sched_migration_cost == 0)
1533 delta = now - p->se.exec_start;
1535 return delta < (s64)sysctl_sched_migration_cost;
1539 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1541 int old_cpu = task_cpu(p);
1542 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
1543 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
1544 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
1547 clock_offset = old_rq->clock - new_rq->clock;
1549 #ifdef CONFIG_SCHEDSTATS
1550 if (p->se.wait_start)
1551 p->se.wait_start -= clock_offset;
1552 if (p->se.sleep_start)
1553 p->se.sleep_start -= clock_offset;
1554 if (p->se.block_start)
1555 p->se.block_start -= clock_offset;
1556 if (old_cpu != new_cpu) {
1557 schedstat_inc(p, se.nr_migrations);
1558 if (task_hot(p, old_rq->clock, NULL))
1559 schedstat_inc(p, se.nr_forced2_migrations);
1562 p->se.vruntime -= old_cfsrq->min_vruntime -
1563 new_cfsrq->min_vruntime;
1565 __set_task_cpu(p, new_cpu);
1568 struct migration_req {
1569 struct list_head list;
1571 struct task_struct *task;
1574 struct completion done;
1578 * The task's runqueue lock must be held.
1579 * Returns true if you have to wait for migration thread.
1582 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1584 struct rq *rq = task_rq(p);
1587 * If the task is not on a runqueue (and not running), then
1588 * it is sufficient to simply update the task's cpu field.
1590 if (!p->se.on_rq && !task_running(rq, p)) {
1591 set_task_cpu(p, dest_cpu);
1595 init_completion(&req->done);
1597 req->dest_cpu = dest_cpu;
1598 list_add(&req->list, &rq->migration_queue);
1604 * wait_task_inactive - wait for a thread to unschedule.
1606 * The caller must ensure that the task *will* unschedule sometime soon,
1607 * else this function might spin for a *long* time. This function can't
1608 * be called with interrupts off, or it may introduce deadlock with
1609 * smp_call_function() if an IPI is sent by the same process we are
1610 * waiting to become inactive.
1612 void wait_task_inactive(struct task_struct *p)
1614 unsigned long flags;
1620 * We do the initial early heuristics without holding
1621 * any task-queue locks at all. We'll only try to get
1622 * the runqueue lock when things look like they will
1628 * If the task is actively running on another CPU
1629 * still, just relax and busy-wait without holding
1632 * NOTE! Since we don't hold any locks, it's not
1633 * even sure that "rq" stays as the right runqueue!
1634 * But we don't care, since "task_running()" will
1635 * return false if the runqueue has changed and p
1636 * is actually now running somewhere else!
1638 while (task_running(rq, p))
1642 * Ok, time to look more closely! We need the rq
1643 * lock now, to be *sure*. If we're wrong, we'll
1644 * just go back and repeat.
1646 rq = task_rq_lock(p, &flags);
1647 running = task_running(rq, p);
1648 on_rq = p->se.on_rq;
1649 task_rq_unlock(rq, &flags);
1652 * Was it really running after all now that we
1653 * checked with the proper locks actually held?
1655 * Oops. Go back and try again..
1657 if (unlikely(running)) {
1663 * It's not enough that it's not actively running,
1664 * it must be off the runqueue _entirely_, and not
1667 * So if it wa still runnable (but just not actively
1668 * running right now), it's preempted, and we should
1669 * yield - it could be a while.
1671 if (unlikely(on_rq)) {
1672 schedule_timeout_uninterruptible(1);
1677 * Ahh, all good. It wasn't running, and it wasn't
1678 * runnable, which means that it will never become
1679 * running in the future either. We're all done!
1686 * kick_process - kick a running thread to enter/exit the kernel
1687 * @p: the to-be-kicked thread
1689 * Cause a process which is running on another CPU to enter
1690 * kernel-mode, without any delay. (to get signals handled.)
1692 * NOTE: this function doesnt have to take the runqueue lock,
1693 * because all it wants to ensure is that the remote task enters
1694 * the kernel. If the IPI races and the task has been migrated
1695 * to another CPU then no harm is done and the purpose has been
1698 void kick_process(struct task_struct *p)
1704 if ((cpu != smp_processor_id()) && task_curr(p))
1705 smp_send_reschedule(cpu);
1710 * Return a low guess at the load of a migration-source cpu weighted
1711 * according to the scheduling class and "nice" value.
1713 * We want to under-estimate the load of migration sources, to
1714 * balance conservatively.
1716 static unsigned long source_load(int cpu, int type)
1718 struct rq *rq = cpu_rq(cpu);
1719 unsigned long total = weighted_cpuload(cpu);
1724 return min(rq->cpu_load[type-1], total);
1728 * Return a high guess at the load of a migration-target cpu weighted
1729 * according to the scheduling class and "nice" value.
1731 static unsigned long target_load(int cpu, int type)
1733 struct rq *rq = cpu_rq(cpu);
1734 unsigned long total = weighted_cpuload(cpu);
1739 return max(rq->cpu_load[type-1], total);
1743 * Return the average load per task on the cpu's run queue
1745 static unsigned long cpu_avg_load_per_task(int cpu)
1747 struct rq *rq = cpu_rq(cpu);
1748 unsigned long total = weighted_cpuload(cpu);
1749 unsigned long n = rq->nr_running;
1751 return n ? total / n : SCHED_LOAD_SCALE;
1755 * find_idlest_group finds and returns the least busy CPU group within the
1758 static struct sched_group *
1759 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1761 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1762 unsigned long min_load = ULONG_MAX, this_load = 0;
1763 int load_idx = sd->forkexec_idx;
1764 int imbalance = 100 + (sd->imbalance_pct-100)/2;
1767 unsigned long load, avg_load;
1771 /* Skip over this group if it has no CPUs allowed */
1772 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
1775 local_group = cpu_isset(this_cpu, group->cpumask);
1777 /* Tally up the load of all CPUs in the group */
1780 for_each_cpu_mask(i, group->cpumask) {
1781 /* Bias balancing toward cpus of our domain */
1783 load = source_load(i, load_idx);
1785 load = target_load(i, load_idx);
1790 /* Adjust by relative CPU power of the group */
1791 avg_load = sg_div_cpu_power(group,
1792 avg_load * SCHED_LOAD_SCALE);
1795 this_load = avg_load;
1797 } else if (avg_load < min_load) {
1798 min_load = avg_load;
1801 } while (group = group->next, group != sd->groups);
1803 if (!idlest || 100*this_load < imbalance*min_load)
1809 * find_idlest_cpu - find the idlest cpu among the cpus in group.
1812 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
1815 unsigned long load, min_load = ULONG_MAX;
1819 /* Traverse only the allowed CPUs */
1820 cpus_and(tmp, group->cpumask, p->cpus_allowed);
1822 for_each_cpu_mask(i, tmp) {
1823 load = weighted_cpuload(i);
1825 if (load < min_load || (load == min_load && i == this_cpu)) {
1835 * sched_balance_self: balance the current task (running on cpu) in domains
1836 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1839 * Balance, ie. select the least loaded group.
1841 * Returns the target CPU number, or the same CPU if no balancing is needed.
1843 * preempt must be disabled.
1845 static int sched_balance_self(int cpu, int flag)
1847 struct task_struct *t = current;
1848 struct sched_domain *tmp, *sd = NULL;
1850 for_each_domain(cpu, tmp) {
1852 * If power savings logic is enabled for a domain, stop there.
1854 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
1856 if (tmp->flags & flag)
1862 struct sched_group *group;
1863 int new_cpu, weight;
1865 if (!(sd->flags & flag)) {
1871 group = find_idlest_group(sd, t, cpu);
1877 new_cpu = find_idlest_cpu(group, t, cpu);
1878 if (new_cpu == -1 || new_cpu == cpu) {
1879 /* Now try balancing at a lower domain level of cpu */
1884 /* Now try balancing at a lower domain level of new_cpu */
1887 weight = cpus_weight(span);
1888 for_each_domain(cpu, tmp) {
1889 if (weight <= cpus_weight(tmp->span))
1891 if (tmp->flags & flag)
1894 /* while loop will break here if sd == NULL */
1900 #endif /* CONFIG_SMP */
1903 * try_to_wake_up - wake up a thread
1904 * @p: the to-be-woken-up thread
1905 * @state: the mask of task states that can be woken
1906 * @sync: do a synchronous wakeup?
1908 * Put it on the run-queue if it's not already there. The "current"
1909 * thread is always on the run-queue (except when the actual
1910 * re-schedule is in progress), and as such you're allowed to do
1911 * the simpler "current->state = TASK_RUNNING" to mark yourself
1912 * runnable without the overhead of this.
1914 * returns failure only if the task is already active.
1916 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
1918 int cpu, orig_cpu, this_cpu, success = 0;
1919 unsigned long flags;
1923 if (!sched_feat(SYNC_WAKEUPS))
1927 rq = task_rq_lock(p, &flags);
1928 old_state = p->state;
1929 if (!(old_state & state))
1937 this_cpu = smp_processor_id();
1940 if (unlikely(task_running(rq, p)))
1943 cpu = p->sched_class->select_task_rq(p, sync);
1944 if (cpu != orig_cpu) {
1945 set_task_cpu(p, cpu);
1946 task_rq_unlock(rq, &flags);
1947 /* might preempt at this point */
1948 rq = task_rq_lock(p, &flags);
1949 old_state = p->state;
1950 if (!(old_state & state))
1955 this_cpu = smp_processor_id();
1959 #ifdef CONFIG_SCHEDSTATS
1960 schedstat_inc(rq, ttwu_count);
1961 if (cpu == this_cpu)
1962 schedstat_inc(rq, ttwu_local);
1964 struct sched_domain *sd;
1965 for_each_domain(this_cpu, sd) {
1966 if (cpu_isset(cpu, sd->span)) {
1967 schedstat_inc(sd, ttwu_wake_remote);
1975 #endif /* CONFIG_SMP */
1976 schedstat_inc(p, se.nr_wakeups);
1978 schedstat_inc(p, se.nr_wakeups_sync);
1979 if (orig_cpu != cpu)
1980 schedstat_inc(p, se.nr_wakeups_migrate);
1981 if (cpu == this_cpu)
1982 schedstat_inc(p, se.nr_wakeups_local);
1984 schedstat_inc(p, se.nr_wakeups_remote);
1985 update_rq_clock(rq);
1986 activate_task(rq, p, 1);
1990 check_preempt_curr(rq, p);
1992 p->state = TASK_RUNNING;
1994 if (p->sched_class->task_wake_up)
1995 p->sched_class->task_wake_up(rq, p);
1998 task_rq_unlock(rq, &flags);
2003 int wake_up_process(struct task_struct *p)
2005 return try_to_wake_up(p, TASK_ALL, 0);
2007 EXPORT_SYMBOL(wake_up_process);
2009 int wake_up_state(struct task_struct *p, unsigned int state)
2011 return try_to_wake_up(p, state, 0);
2015 * Perform scheduler related setup for a newly forked process p.
2016 * p is forked by current.
2018 * __sched_fork() is basic setup used by init_idle() too:
2020 static void __sched_fork(struct task_struct *p)
2022 p->se.exec_start = 0;
2023 p->se.sum_exec_runtime = 0;
2024 p->se.prev_sum_exec_runtime = 0;
2025 p->se.last_wakeup = 0;
2026 p->se.avg_overlap = 0;
2028 #ifdef CONFIG_SCHEDSTATS
2029 p->se.wait_start = 0;
2030 p->se.sum_sleep_runtime = 0;
2031 p->se.sleep_start = 0;
2032 p->se.block_start = 0;
2033 p->se.sleep_max = 0;
2034 p->se.block_max = 0;
2036 p->se.slice_max = 0;
2040 INIT_LIST_HEAD(&p->rt.run_list);
2043 #ifdef CONFIG_PREEMPT_NOTIFIERS
2044 INIT_HLIST_HEAD(&p->preempt_notifiers);
2048 * We mark the process as running here, but have not actually
2049 * inserted it onto the runqueue yet. This guarantees that
2050 * nobody will actually run it, and a signal or other external
2051 * event cannot wake it up and insert it on the runqueue either.
2053 p->state = TASK_RUNNING;
2057 * fork()/clone()-time setup:
2059 void sched_fork(struct task_struct *p, int clone_flags)
2061 int cpu = get_cpu();
2066 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
2068 set_task_cpu(p, cpu);
2071 * Make sure we do not leak PI boosting priority to the child:
2073 p->prio = current->normal_prio;
2074 if (!rt_prio(p->prio))
2075 p->sched_class = &fair_sched_class;
2077 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2078 if (likely(sched_info_on()))
2079 memset(&p->sched_info, 0, sizeof(p->sched_info));
2081 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2084 #ifdef CONFIG_PREEMPT
2085 /* Want to start with kernel preemption disabled. */
2086 task_thread_info(p)->preempt_count = 1;
2092 * wake_up_new_task - wake up a newly created task for the first time.
2094 * This function will do some initial scheduler statistics housekeeping
2095 * that must be done for every newly created context, then puts the task
2096 * on the runqueue and wakes it.
2098 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2100 unsigned long flags;
2103 rq = task_rq_lock(p, &flags);
2104 BUG_ON(p->state != TASK_RUNNING);
2105 update_rq_clock(rq);
2107 p->prio = effective_prio(p);
2109 if (!p->sched_class->task_new || !current->se.on_rq) {
2110 activate_task(rq, p, 0);
2113 * Let the scheduling class do new task startup
2114 * management (if any):
2116 p->sched_class->task_new(rq, p);
2117 inc_nr_running(p, rq);
2119 check_preempt_curr(rq, p);
2121 if (p->sched_class->task_wake_up)
2122 p->sched_class->task_wake_up(rq, p);
2124 task_rq_unlock(rq, &flags);
2127 #ifdef CONFIG_PREEMPT_NOTIFIERS
2130 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2131 * @notifier: notifier struct to register
2133 void preempt_notifier_register(struct preempt_notifier *notifier)
2135 hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
2137 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2140 * preempt_notifier_unregister - no longer interested in preemption notifications
2141 * @notifier: notifier struct to unregister
2143 * This is safe to call from within a preemption notifier.
2145 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2147 hlist_del(¬ifier->link);
2149 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2151 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2153 struct preempt_notifier *notifier;
2154 struct hlist_node *node;
2156 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2157 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2161 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2162 struct task_struct *next)
2164 struct preempt_notifier *notifier;
2165 struct hlist_node *node;
2167 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2168 notifier->ops->sched_out(notifier, next);
2173 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2178 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2179 struct task_struct *next)
2186 * prepare_task_switch - prepare to switch tasks
2187 * @rq: the runqueue preparing to switch
2188 * @prev: the current task that is being switched out
2189 * @next: the task we are going to switch to.
2191 * This is called with the rq lock held and interrupts off. It must
2192 * be paired with a subsequent finish_task_switch after the context
2195 * prepare_task_switch sets up locking and calls architecture specific
2199 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2200 struct task_struct *next)
2202 fire_sched_out_preempt_notifiers(prev, next);
2203 prepare_lock_switch(rq, next);
2204 prepare_arch_switch(next);
2208 * finish_task_switch - clean up after a task-switch
2209 * @rq: runqueue associated with task-switch
2210 * @prev: the thread we just switched away from.
2212 * finish_task_switch must be called after the context switch, paired
2213 * with a prepare_task_switch call before the context switch.
2214 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2215 * and do any other architecture-specific cleanup actions.
2217 * Note that we may have delayed dropping an mm in context_switch(). If
2218 * so, we finish that here outside of the runqueue lock. (Doing it
2219 * with the lock held can cause deadlocks; see schedule() for
2222 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2223 __releases(rq->lock)
2225 struct mm_struct *mm = rq->prev_mm;
2231 * A task struct has one reference for the use as "current".
2232 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2233 * schedule one last time. The schedule call will never return, and
2234 * the scheduled task must drop that reference.
2235 * The test for TASK_DEAD must occur while the runqueue locks are
2236 * still held, otherwise prev could be scheduled on another cpu, die
2237 * there before we look at prev->state, and then the reference would
2239 * Manfred Spraul <manfred@colorfullife.com>
2241 prev_state = prev->state;
2242 finish_arch_switch(prev);
2243 finish_lock_switch(rq, prev);
2245 if (current->sched_class->post_schedule)
2246 current->sched_class->post_schedule(rq);
2249 fire_sched_in_preempt_notifiers(current);
2252 if (unlikely(prev_state == TASK_DEAD)) {
2254 * Remove function-return probe instances associated with this
2255 * task and put them back on the free list.
2257 kprobe_flush_task(prev);
2258 put_task_struct(prev);
2263 * schedule_tail - first thing a freshly forked thread must call.
2264 * @prev: the thread we just switched away from.
2266 asmlinkage void schedule_tail(struct task_struct *prev)
2267 __releases(rq->lock)
2269 struct rq *rq = this_rq();
2271 finish_task_switch(rq, prev);
2272 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2273 /* In this case, finish_task_switch does not reenable preemption */
2276 if (current->set_child_tid)
2277 put_user(task_pid_vnr(current), current->set_child_tid);
2281 * context_switch - switch to the new MM and the new
2282 * thread's register state.
2285 context_switch(struct rq *rq, struct task_struct *prev,
2286 struct task_struct *next)
2288 struct mm_struct *mm, *oldmm;
2290 prepare_task_switch(rq, prev, next);
2292 oldmm = prev->active_mm;
2294 * For paravirt, this is coupled with an exit in switch_to to
2295 * combine the page table reload and the switch backend into
2298 arch_enter_lazy_cpu_mode();
2300 if (unlikely(!mm)) {
2301 next->active_mm = oldmm;
2302 atomic_inc(&oldmm->mm_count);
2303 enter_lazy_tlb(oldmm, next);
2305 switch_mm(oldmm, mm, next);
2307 if (unlikely(!prev->mm)) {
2308 prev->active_mm = NULL;
2309 rq->prev_mm = oldmm;
2312 * Since the runqueue lock will be released by the next
2313 * task (which is an invalid locking op but in the case
2314 * of the scheduler it's an obvious special-case), so we
2315 * do an early lockdep release here:
2317 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2318 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2321 /* Here we just switch the register state and the stack. */
2322 switch_to(prev, next, prev);
2326 * this_rq must be evaluated again because prev may have moved
2327 * CPUs since it called schedule(), thus the 'rq' on its stack
2328 * frame will be invalid.
2330 finish_task_switch(this_rq(), prev);
2334 * nr_running, nr_uninterruptible and nr_context_switches:
2336 * externally visible scheduler statistics: current number of runnable
2337 * threads, current number of uninterruptible-sleeping threads, total
2338 * number of context switches performed since bootup.
2340 unsigned long nr_running(void)
2342 unsigned long i, sum = 0;
2344 for_each_online_cpu(i)
2345 sum += cpu_rq(i)->nr_running;
2350 unsigned long nr_uninterruptible(void)
2352 unsigned long i, sum = 0;
2354 for_each_possible_cpu(i)
2355 sum += cpu_rq(i)->nr_uninterruptible;
2358 * Since we read the counters lockless, it might be slightly
2359 * inaccurate. Do not allow it to go below zero though:
2361 if (unlikely((long)sum < 0))
2367 unsigned long long nr_context_switches(void)
2370 unsigned long long sum = 0;
2372 for_each_possible_cpu(i)
2373 sum += cpu_rq(i)->nr_switches;
2378 unsigned long nr_iowait(void)
2380 unsigned long i, sum = 0;
2382 for_each_possible_cpu(i)
2383 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2388 unsigned long nr_active(void)
2390 unsigned long i, running = 0, uninterruptible = 0;
2392 for_each_online_cpu(i) {
2393 running += cpu_rq(i)->nr_running;
2394 uninterruptible += cpu_rq(i)->nr_uninterruptible;
2397 if (unlikely((long)uninterruptible < 0))
2398 uninterruptible = 0;
2400 return running + uninterruptible;
2404 * Update rq->cpu_load[] statistics. This function is usually called every
2405 * scheduler tick (TICK_NSEC).
2407 static void update_cpu_load(struct rq *this_rq)
2409 unsigned long this_load = this_rq->load.weight;
2412 this_rq->nr_load_updates++;
2414 /* Update our load: */
2415 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
2416 unsigned long old_load, new_load;
2418 /* scale is effectively 1 << i now, and >> i divides by scale */
2420 old_load = this_rq->cpu_load[i];
2421 new_load = this_load;
2423 * Round up the averaging division if load is increasing. This
2424 * prevents us from getting stuck on 9 if the load is 10, for
2427 if (new_load > old_load)
2428 new_load += scale-1;
2429 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
2436 * double_rq_lock - safely lock two runqueues
2438 * Note this does not disable interrupts like task_rq_lock,
2439 * you need to do so manually before calling.
2441 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
2442 __acquires(rq1->lock)
2443 __acquires(rq2->lock)
2445 BUG_ON(!irqs_disabled());
2447 spin_lock(&rq1->lock);
2448 __acquire(rq2->lock); /* Fake it out ;) */
2451 spin_lock(&rq1->lock);
2452 spin_lock(&rq2->lock);
2454 spin_lock(&rq2->lock);
2455 spin_lock(&rq1->lock);
2458 update_rq_clock(rq1);
2459 update_rq_clock(rq2);
2463 * double_rq_unlock - safely unlock two runqueues
2465 * Note this does not restore interrupts like task_rq_unlock,
2466 * you need to do so manually after calling.
2468 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
2469 __releases(rq1->lock)
2470 __releases(rq2->lock)
2472 spin_unlock(&rq1->lock);
2474 spin_unlock(&rq2->lock);
2476 __release(rq2->lock);
2480 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2482 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
2483 __releases(this_rq->lock)
2484 __acquires(busiest->lock)
2485 __acquires(this_rq->lock)
2489 if (unlikely(!irqs_disabled())) {
2490 /* printk() doesn't work good under rq->lock */
2491 spin_unlock(&this_rq->lock);
2494 if (unlikely(!spin_trylock(&busiest->lock))) {
2495 if (busiest < this_rq) {
2496 spin_unlock(&this_rq->lock);
2497 spin_lock(&busiest->lock);
2498 spin_lock(&this_rq->lock);
2501 spin_lock(&busiest->lock);
2507 * If dest_cpu is allowed for this process, migrate the task to it.
2508 * This is accomplished by forcing the cpu_allowed mask to only
2509 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2510 * the cpu_allowed mask is restored.
2512 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
2514 struct migration_req req;
2515 unsigned long flags;
2518 rq = task_rq_lock(p, &flags);
2519 if (!cpu_isset(dest_cpu, p->cpus_allowed)
2520 || unlikely(cpu_is_offline(dest_cpu)))
2523 /* force the process onto the specified CPU */
2524 if (migrate_task(p, dest_cpu, &req)) {
2525 /* Need to wait for migration thread (might exit: take ref). */
2526 struct task_struct *mt = rq->migration_thread;
2528 get_task_struct(mt);
2529 task_rq_unlock(rq, &flags);
2530 wake_up_process(mt);
2531 put_task_struct(mt);
2532 wait_for_completion(&req.done);
2537 task_rq_unlock(rq, &flags);
2541 * sched_exec - execve() is a valuable balancing opportunity, because at
2542 * this point the task has the smallest effective memory and cache footprint.
2544 void sched_exec(void)
2546 int new_cpu, this_cpu = get_cpu();
2547 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
2549 if (new_cpu != this_cpu)
2550 sched_migrate_task(current, new_cpu);
2554 * pull_task - move a task from a remote runqueue to the local runqueue.
2555 * Both runqueues must be locked.
2557 static void pull_task(struct rq *src_rq, struct task_struct *p,
2558 struct rq *this_rq, int this_cpu)
2560 deactivate_task(src_rq, p, 0);
2561 set_task_cpu(p, this_cpu);
2562 activate_task(this_rq, p, 0);
2564 * Note that idle threads have a prio of MAX_PRIO, for this test
2565 * to be always true for them.
2567 check_preempt_curr(this_rq, p);
2571 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2574 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
2575 struct sched_domain *sd, enum cpu_idle_type idle,
2579 * We do not migrate tasks that are:
2580 * 1) running (obviously), or
2581 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2582 * 3) are cache-hot on their current CPU.
2584 if (!cpu_isset(this_cpu, p->cpus_allowed)) {
2585 schedstat_inc(p, se.nr_failed_migrations_affine);
2590 if (task_running(rq, p)) {
2591 schedstat_inc(p, se.nr_failed_migrations_running);
2596 * Aggressive migration if:
2597 * 1) task is cache cold, or
2598 * 2) too many balance attempts have failed.
2601 if (!task_hot(p, rq->clock, sd) ||
2602 sd->nr_balance_failed > sd->cache_nice_tries) {
2603 #ifdef CONFIG_SCHEDSTATS
2604 if (task_hot(p, rq->clock, sd)) {
2605 schedstat_inc(sd, lb_hot_gained[idle]);
2606 schedstat_inc(p, se.nr_forced_migrations);
2612 if (task_hot(p, rq->clock, sd)) {
2613 schedstat_inc(p, se.nr_failed_migrations_hot);
2619 static unsigned long
2620 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2621 unsigned long max_load_move, struct sched_domain *sd,
2622 enum cpu_idle_type idle, int *all_pinned,
2623 int *this_best_prio, struct rq_iterator *iterator)
2625 int loops = 0, pulled = 0, pinned = 0, skip_for_load;
2626 struct task_struct *p;
2627 long rem_load_move = max_load_move;
2629 if (max_load_move == 0)
2635 * Start the load-balancing iterator:
2637 p = iterator->start(iterator->arg);
2639 if (!p || loops++ > sysctl_sched_nr_migrate)
2642 * To help distribute high priority tasks across CPUs we don't
2643 * skip a task if it will be the highest priority task (i.e. smallest
2644 * prio value) on its new queue regardless of its load weight
2646 skip_for_load = (p->se.load.weight >> 1) > rem_load_move +
2647 SCHED_LOAD_SCALE_FUZZ;
2648 if ((skip_for_load && p->prio >= *this_best_prio) ||
2649 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
2650 p = iterator->next(iterator->arg);
2654 pull_task(busiest, p, this_rq, this_cpu);
2656 rem_load_move -= p->se.load.weight;
2659 * We only want to steal up to the prescribed amount of weighted load.
2661 if (rem_load_move > 0) {
2662 if (p->prio < *this_best_prio)
2663 *this_best_prio = p->prio;
2664 p = iterator->next(iterator->arg);
2669 * Right now, this is one of only two places pull_task() is called,
2670 * so we can safely collect pull_task() stats here rather than
2671 * inside pull_task().
2673 schedstat_add(sd, lb_gained[idle], pulled);
2676 *all_pinned = pinned;
2678 return max_load_move - rem_load_move;
2682 * move_tasks tries to move up to max_load_move weighted load from busiest to
2683 * this_rq, as part of a balancing operation within domain "sd".
2684 * Returns 1 if successful and 0 otherwise.
2686 * Called with both runqueues locked.
2688 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2689 unsigned long max_load_move,
2690 struct sched_domain *sd, enum cpu_idle_type idle,
2693 const struct sched_class *class = sched_class_highest;
2694 unsigned long total_load_moved = 0;
2695 int this_best_prio = this_rq->curr->prio;
2699 class->load_balance(this_rq, this_cpu, busiest,
2700 max_load_move - total_load_moved,
2701 sd, idle, all_pinned, &this_best_prio);
2702 class = class->next;
2703 } while (class && max_load_move > total_load_moved);
2705 return total_load_moved > 0;
2709 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
2710 struct sched_domain *sd, enum cpu_idle_type idle,
2711 struct rq_iterator *iterator)
2713 struct task_struct *p = iterator->start(iterator->arg);
2717 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
2718 pull_task(busiest, p, this_rq, this_cpu);
2720 * Right now, this is only the second place pull_task()
2721 * is called, so we can safely collect pull_task()
2722 * stats here rather than inside pull_task().
2724 schedstat_inc(sd, lb_gained[idle]);
2728 p = iterator->next(iterator->arg);
2735 * move_one_task tries to move exactly one task from busiest to this_rq, as
2736 * part of active balancing operations within "domain".
2737 * Returns 1 if successful and 0 otherwise.
2739 * Called with both runqueues locked.
2741 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
2742 struct sched_domain *sd, enum cpu_idle_type idle)
2744 const struct sched_class *class;
2746 for (class = sched_class_highest; class; class = class->next)
2747 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
2754 * find_busiest_group finds and returns the busiest CPU group within the
2755 * domain. It calculates and returns the amount of weighted load which
2756 * should be moved to restore balance via the imbalance parameter.
2758 static struct sched_group *
2759 find_busiest_group(struct sched_domain *sd, int this_cpu,
2760 unsigned long *imbalance, enum cpu_idle_type idle,
2761 int *sd_idle, cpumask_t *cpus, int *balance)
2763 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2764 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2765 unsigned long max_pull;
2766 unsigned long busiest_load_per_task, busiest_nr_running;
2767 unsigned long this_load_per_task, this_nr_running;
2768 int load_idx, group_imb = 0;
2769 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2770 int power_savings_balance = 1;
2771 unsigned long leader_nr_running = 0, min_load_per_task = 0;
2772 unsigned long min_nr_running = ULONG_MAX;
2773 struct sched_group *group_min = NULL, *group_leader = NULL;
2776 max_load = this_load = total_load = total_pwr = 0;
2777 busiest_load_per_task = busiest_nr_running = 0;
2778 this_load_per_task = this_nr_running = 0;
2779 if (idle == CPU_NOT_IDLE)
2780 load_idx = sd->busy_idx;
2781 else if (idle == CPU_NEWLY_IDLE)
2782 load_idx = sd->newidle_idx;
2784 load_idx = sd->idle_idx;
2787 unsigned long load, group_capacity, max_cpu_load, min_cpu_load;
2790 int __group_imb = 0;
2791 unsigned int balance_cpu = -1, first_idle_cpu = 0;
2792 unsigned long sum_nr_running, sum_weighted_load;
2794 local_group = cpu_isset(this_cpu, group->cpumask);
2797 balance_cpu = first_cpu(group->cpumask);
2799 /* Tally up the load of all CPUs in the group */
2800 sum_weighted_load = sum_nr_running = avg_load = 0;
2802 min_cpu_load = ~0UL;
2804 for_each_cpu_mask(i, group->cpumask) {
2807 if (!cpu_isset(i, *cpus))
2812 if (*sd_idle && rq->nr_running)
2815 /* Bias balancing toward cpus of our domain */
2817 if (idle_cpu(i) && !first_idle_cpu) {
2822 load = target_load(i, load_idx);
2824 load = source_load(i, load_idx);
2825 if (load > max_cpu_load)
2826 max_cpu_load = load;
2827 if (min_cpu_load > load)
2828 min_cpu_load = load;
2832 sum_nr_running += rq->nr_running;
2833 sum_weighted_load += weighted_cpuload(i);
2837 * First idle cpu or the first cpu(busiest) in this sched group
2838 * is eligible for doing load balancing at this and above
2839 * domains. In the newly idle case, we will allow all the cpu's
2840 * to do the newly idle load balance.
2842 if (idle != CPU_NEWLY_IDLE && local_group &&
2843 balance_cpu != this_cpu && balance) {
2848 total_load += avg_load;
2849 total_pwr += group->__cpu_power;
2851 /* Adjust by relative CPU power of the group */
2852 avg_load = sg_div_cpu_power(group,
2853 avg_load * SCHED_LOAD_SCALE);
2855 if ((max_cpu_load - min_cpu_load) > SCHED_LOAD_SCALE)
2858 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
2861 this_load = avg_load;
2863 this_nr_running = sum_nr_running;
2864 this_load_per_task = sum_weighted_load;
2865 } else if (avg_load > max_load &&
2866 (sum_nr_running > group_capacity || __group_imb)) {
2867 max_load = avg_load;
2869 busiest_nr_running = sum_nr_running;
2870 busiest_load_per_task = sum_weighted_load;
2871 group_imb = __group_imb;
2874 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2876 * Busy processors will not participate in power savings
2879 if (idle == CPU_NOT_IDLE ||
2880 !(sd->flags & SD_POWERSAVINGS_BALANCE))
2884 * If the local group is idle or completely loaded
2885 * no need to do power savings balance at this domain
2887 if (local_group && (this_nr_running >= group_capacity ||
2889 power_savings_balance = 0;
2892 * If a group is already running at full capacity or idle,
2893 * don't include that group in power savings calculations
2895 if (!power_savings_balance || sum_nr_running >= group_capacity
2900 * Calculate the group which has the least non-idle load.
2901 * This is the group from where we need to pick up the load
2904 if ((sum_nr_running < min_nr_running) ||
2905 (sum_nr_running == min_nr_running &&
2906 first_cpu(group->cpumask) <
2907 first_cpu(group_min->cpumask))) {
2909 min_nr_running = sum_nr_running;
2910 min_load_per_task = sum_weighted_load /
2915 * Calculate the group which is almost near its
2916 * capacity but still has some space to pick up some load
2917 * from other group and save more power
2919 if (sum_nr_running <= group_capacity - 1) {
2920 if (sum_nr_running > leader_nr_running ||
2921 (sum_nr_running == leader_nr_running &&
2922 first_cpu(group->cpumask) >
2923 first_cpu(group_leader->cpumask))) {
2924 group_leader = group;
2925 leader_nr_running = sum_nr_running;
2930 group = group->next;
2931 } while (group != sd->groups);
2933 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
2936 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2938 if (this_load >= avg_load ||
2939 100*max_load <= sd->imbalance_pct*this_load)
2942 busiest_load_per_task /= busiest_nr_running;
2944 busiest_load_per_task = min(busiest_load_per_task, avg_load);
2947 * We're trying to get all the cpus to the average_load, so we don't
2948 * want to push ourselves above the average load, nor do we wish to
2949 * reduce the max loaded cpu below the average load, as either of these
2950 * actions would just result in more rebalancing later, and ping-pong
2951 * tasks around. Thus we look for the minimum possible imbalance.
2952 * Negative imbalances (*we* are more loaded than anyone else) will
2953 * be counted as no imbalance for these purposes -- we can't fix that
2954 * by pulling tasks to us. Be careful of negative numbers as they'll
2955 * appear as very large values with unsigned longs.
2957 if (max_load <= busiest_load_per_task)
2961 * In the presence of smp nice balancing, certain scenarios can have
2962 * max load less than avg load(as we skip the groups at or below
2963 * its cpu_power, while calculating max_load..)
2965 if (max_load < avg_load) {
2967 goto small_imbalance;
2970 /* Don't want to pull so many tasks that a group would go idle */
2971 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
2973 /* How much load to actually move to equalise the imbalance */
2974 *imbalance = min(max_pull * busiest->__cpu_power,
2975 (avg_load - this_load) * this->__cpu_power)
2979 * if *imbalance is less than the average load per runnable task
2980 * there is no gaurantee that any tasks will be moved so we'll have
2981 * a think about bumping its value to force at least one task to be
2984 if (*imbalance < busiest_load_per_task) {
2985 unsigned long tmp, pwr_now, pwr_move;
2989 pwr_move = pwr_now = 0;
2991 if (this_nr_running) {
2992 this_load_per_task /= this_nr_running;
2993 if (busiest_load_per_task > this_load_per_task)
2996 this_load_per_task = SCHED_LOAD_SCALE;
2998 if (max_load - this_load + SCHED_LOAD_SCALE_FUZZ >=
2999 busiest_load_per_task * imbn) {
3000 *imbalance = busiest_load_per_task;
3005 * OK, we don't have enough imbalance to justify moving tasks,
3006 * however we may be able to increase total CPU power used by
3010 pwr_now += busiest->__cpu_power *
3011 min(busiest_load_per_task, max_load);
3012 pwr_now += this->__cpu_power *
3013 min(this_load_per_task, this_load);
3014 pwr_now /= SCHED_LOAD_SCALE;
3016 /* Amount of load we'd subtract */
3017 tmp = sg_div_cpu_power(busiest,
3018 busiest_load_per_task * SCHED_LOAD_SCALE);
3020 pwr_move += busiest->__cpu_power *
3021 min(busiest_load_per_task, max_load - tmp);
3023 /* Amount of load we'd add */
3024 if (max_load * busiest->__cpu_power <
3025 busiest_load_per_task * SCHED_LOAD_SCALE)
3026 tmp = sg_div_cpu_power(this,
3027 max_load * busiest->__cpu_power);
3029 tmp = sg_div_cpu_power(this,
3030 busiest_load_per_task * SCHED_LOAD_SCALE);
3031 pwr_move += this->__cpu_power *
3032 min(this_load_per_task, this_load + tmp);
3033 pwr_move /= SCHED_LOAD_SCALE;
3035 /* Move if we gain throughput */
3036 if (pwr_move > pwr_now)
3037 *imbalance = busiest_load_per_task;
3043 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3044 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3047 if (this == group_leader && group_leader != group_min) {
3048 *imbalance = min_load_per_task;
3058 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3061 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
3062 unsigned long imbalance, cpumask_t *cpus)
3064 struct rq *busiest = NULL, *rq;
3065 unsigned long max_load = 0;
3068 for_each_cpu_mask(i, group->cpumask) {
3071 if (!cpu_isset(i, *cpus))
3075 wl = weighted_cpuload(i);
3077 if (rq->nr_running == 1 && wl > imbalance)
3080 if (wl > max_load) {
3090 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3091 * so long as it is large enough.
3093 #define MAX_PINNED_INTERVAL 512
3096 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3097 * tasks if there is an imbalance.
3099 static int load_balance(int this_cpu, struct rq *this_rq,
3100 struct sched_domain *sd, enum cpu_idle_type idle,
3103 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
3104 struct sched_group *group;
3105 unsigned long imbalance;
3107 cpumask_t cpus = CPU_MASK_ALL;
3108 unsigned long flags;
3111 * When power savings policy is enabled for the parent domain, idle
3112 * sibling can pick up load irrespective of busy siblings. In this case,
3113 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3114 * portraying it as CPU_NOT_IDLE.
3116 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
3117 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3120 schedstat_inc(sd, lb_count[idle]);
3123 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
3130 schedstat_inc(sd, lb_nobusyg[idle]);
3134 busiest = find_busiest_queue(group, idle, imbalance, &cpus);
3136 schedstat_inc(sd, lb_nobusyq[idle]);
3140 BUG_ON(busiest == this_rq);
3142 schedstat_add(sd, lb_imbalance[idle], imbalance);
3145 if (busiest->nr_running > 1) {
3147 * Attempt to move tasks. If find_busiest_group has found
3148 * an imbalance but busiest->nr_running <= 1, the group is
3149 * still unbalanced. ld_moved simply stays zero, so it is
3150 * correctly treated as an imbalance.
3152 local_irq_save(flags);
3153 double_rq_lock(this_rq, busiest);
3154 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3155 imbalance, sd, idle, &all_pinned);
3156 double_rq_unlock(this_rq, busiest);
3157 local_irq_restore(flags);
3160 * some other cpu did the load balance for us.
3162 if (ld_moved && this_cpu != smp_processor_id())
3163 resched_cpu(this_cpu);
3165 /* All tasks on this runqueue were pinned by CPU affinity */
3166 if (unlikely(all_pinned)) {
3167 cpu_clear(cpu_of(busiest), cpus);
3168 if (!cpus_empty(cpus))
3175 schedstat_inc(sd, lb_failed[idle]);
3176 sd->nr_balance_failed++;
3178 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
3180 spin_lock_irqsave(&busiest->lock, flags);
3182 /* don't kick the migration_thread, if the curr
3183 * task on busiest cpu can't be moved to this_cpu
3185 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
3186 spin_unlock_irqrestore(&busiest->lock, flags);
3188 goto out_one_pinned;
3191 if (!busiest->active_balance) {
3192 busiest->active_balance = 1;
3193 busiest->push_cpu = this_cpu;
3196 spin_unlock_irqrestore(&busiest->lock, flags);
3198 wake_up_process(busiest->migration_thread);
3201 * We've kicked active balancing, reset the failure
3204 sd->nr_balance_failed = sd->cache_nice_tries+1;
3207 sd->nr_balance_failed = 0;
3209 if (likely(!active_balance)) {
3210 /* We were unbalanced, so reset the balancing interval */
3211 sd->balance_interval = sd->min_interval;
3214 * If we've begun active balancing, start to back off. This
3215 * case may not be covered by the all_pinned logic if there
3216 * is only 1 task on the busy runqueue (because we don't call
3219 if (sd->balance_interval < sd->max_interval)
3220 sd->balance_interval *= 2;
3223 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3224 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3229 schedstat_inc(sd, lb_balanced[idle]);
3231 sd->nr_balance_failed = 0;
3234 /* tune up the balancing interval */
3235 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
3236 (sd->balance_interval < sd->max_interval))
3237 sd->balance_interval *= 2;
3239 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3240 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3246 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3247 * tasks if there is an imbalance.
3249 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3250 * this_rq is locked.
3253 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
3255 struct sched_group *group;
3256 struct rq *busiest = NULL;
3257 unsigned long imbalance;
3261 cpumask_t cpus = CPU_MASK_ALL;
3264 * When power savings policy is enabled for the parent domain, idle
3265 * sibling can pick up load irrespective of busy siblings. In this case,
3266 * let the state of idle sibling percolate up as IDLE, instead of
3267 * portraying it as CPU_NOT_IDLE.
3269 if (sd->flags & SD_SHARE_CPUPOWER &&
3270 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3273 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
3275 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
3276 &sd_idle, &cpus, NULL);
3278 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
3282 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance,
3285 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
3289 BUG_ON(busiest == this_rq);
3291 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
3294 if (busiest->nr_running > 1) {
3295 /* Attempt to move tasks */
3296 double_lock_balance(this_rq, busiest);
3297 /* this_rq->clock is already updated */
3298 update_rq_clock(busiest);
3299 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3300 imbalance, sd, CPU_NEWLY_IDLE,
3302 spin_unlock(&busiest->lock);
3304 if (unlikely(all_pinned)) {
3305 cpu_clear(cpu_of(busiest), cpus);
3306 if (!cpus_empty(cpus))
3312 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
3313 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3314 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3317 sd->nr_balance_failed = 0;
3322 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
3323 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3324 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3326 sd->nr_balance_failed = 0;
3332 * idle_balance is called by schedule() if this_cpu is about to become
3333 * idle. Attempts to pull tasks from other CPUs.
3335 static void idle_balance(int this_cpu, struct rq *this_rq)
3337 struct sched_domain *sd;
3338 int pulled_task = -1;
3339 unsigned long next_balance = jiffies + HZ;
3341 for_each_domain(this_cpu, sd) {
3342 unsigned long interval;
3344 if (!(sd->flags & SD_LOAD_BALANCE))
3347 if (sd->flags & SD_BALANCE_NEWIDLE)
3348 /* If we've pulled tasks over stop searching: */
3349 pulled_task = load_balance_newidle(this_cpu,
3352 interval = msecs_to_jiffies(sd->balance_interval);
3353 if (time_after(next_balance, sd->last_balance + interval))
3354 next_balance = sd->last_balance + interval;
3358 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
3360 * We are going idle. next_balance may be set based on
3361 * a busy processor. So reset next_balance.
3363 this_rq->next_balance = next_balance;
3368 * active_load_balance is run by migration threads. It pushes running tasks
3369 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3370 * running on each physical CPU where possible, and avoids physical /
3371 * logical imbalances.
3373 * Called with busiest_rq locked.
3375 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
3377 int target_cpu = busiest_rq->push_cpu;
3378 struct sched_domain *sd;
3379 struct rq *target_rq;
3381 /* Is there any task to move? */
3382 if (busiest_rq->nr_running <= 1)
3385 target_rq = cpu_rq(target_cpu);
3388 * This condition is "impossible", if it occurs
3389 * we need to fix it. Originally reported by
3390 * Bjorn Helgaas on a 128-cpu setup.
3392 BUG_ON(busiest_rq == target_rq);
3394 /* move a task from busiest_rq to target_rq */
3395 double_lock_balance(busiest_rq, target_rq);
3396 update_rq_clock(busiest_rq);
3397 update_rq_clock(target_rq);
3399 /* Search for an sd spanning us and the target CPU. */
3400 for_each_domain(target_cpu, sd) {
3401 if ((sd->flags & SD_LOAD_BALANCE) &&
3402 cpu_isset(busiest_cpu, sd->span))
3407 schedstat_inc(sd, alb_count);
3409 if (move_one_task(target_rq, target_cpu, busiest_rq,
3411 schedstat_inc(sd, alb_pushed);
3413 schedstat_inc(sd, alb_failed);
3415 spin_unlock(&target_rq->lock);
3420 atomic_t load_balancer;
3422 } nohz ____cacheline_aligned = {
3423 .load_balancer = ATOMIC_INIT(-1),
3424 .cpu_mask = CPU_MASK_NONE,
3428 * This routine will try to nominate the ilb (idle load balancing)
3429 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3430 * load balancing on behalf of all those cpus. If all the cpus in the system
3431 * go into this tickless mode, then there will be no ilb owner (as there is
3432 * no need for one) and all the cpus will sleep till the next wakeup event
3435 * For the ilb owner, tick is not stopped. And this tick will be used
3436 * for idle load balancing. ilb owner will still be part of
3439 * While stopping the tick, this cpu will become the ilb owner if there
3440 * is no other owner. And will be the owner till that cpu becomes busy
3441 * or if all cpus in the system stop their ticks at which point
3442 * there is no need for ilb owner.
3444 * When the ilb owner becomes busy, it nominates another owner, during the
3445 * next busy scheduler_tick()
3447 int select_nohz_load_balancer(int stop_tick)
3449 int cpu = smp_processor_id();
3452 cpu_set(cpu, nohz.cpu_mask);
3453 cpu_rq(cpu)->in_nohz_recently = 1;
3456 * If we are going offline and still the leader, give up!
3458 if (cpu_is_offline(cpu) &&
3459 atomic_read(&nohz.load_balancer) == cpu) {
3460 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3465 /* time for ilb owner also to sleep */
3466 if (cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3467 if (atomic_read(&nohz.load_balancer) == cpu)
3468 atomic_set(&nohz.load_balancer, -1);
3472 if (atomic_read(&nohz.load_balancer) == -1) {
3473 /* make me the ilb owner */
3474 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
3476 } else if (atomic_read(&nohz.load_balancer) == cpu)
3479 if (!cpu_isset(cpu, nohz.cpu_mask))
3482 cpu_clear(cpu, nohz.cpu_mask);
3484 if (atomic_read(&nohz.load_balancer) == cpu)
3485 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3492 static DEFINE_SPINLOCK(balancing);
3495 * It checks each scheduling domain to see if it is due to be balanced,
3496 * and initiates a balancing operation if so.
3498 * Balancing parameters are set up in arch_init_sched_domains.
3500 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
3503 struct rq *rq = cpu_rq(cpu);
3504 unsigned long interval;
3505 struct sched_domain *sd;
3506 /* Earliest time when we have to do rebalance again */
3507 unsigned long next_balance = jiffies + 60*HZ;
3508 int update_next_balance = 0;
3510 for_each_domain(cpu, sd) {
3511 if (!(sd->flags & SD_LOAD_BALANCE))
3514 interval = sd->balance_interval;
3515 if (idle != CPU_IDLE)
3516 interval *= sd->busy_factor;
3518 /* scale ms to jiffies */
3519 interval = msecs_to_jiffies(interval);
3520 if (unlikely(!interval))
3522 if (interval > HZ*NR_CPUS/10)
3523 interval = HZ*NR_CPUS/10;
3526 if (sd->flags & SD_SERIALIZE) {
3527 if (!spin_trylock(&balancing))
3531 if (time_after_eq(jiffies, sd->last_balance + interval)) {
3532 if (load_balance(cpu, rq, sd, idle, &balance)) {
3534 * We've pulled tasks over so either we're no
3535 * longer idle, or one of our SMT siblings is
3538 idle = CPU_NOT_IDLE;
3540 sd->last_balance = jiffies;
3542 if (sd->flags & SD_SERIALIZE)
3543 spin_unlock(&balancing);
3545 if (time_after(next_balance, sd->last_balance + interval)) {
3546 next_balance = sd->last_balance + interval;
3547 update_next_balance = 1;
3551 * Stop the load balance at this level. There is another
3552 * CPU in our sched group which is doing load balancing more
3560 * next_balance will be updated only when there is a need.
3561 * When the cpu is attached to null domain for ex, it will not be
3564 if (likely(update_next_balance))
3565 rq->next_balance = next_balance;
3569 * run_rebalance_domains is triggered when needed from the scheduler tick.
3570 * In CONFIG_NO_HZ case, the idle load balance owner will do the
3571 * rebalancing for all the cpus for whom scheduler ticks are stopped.
3573 static void run_rebalance_domains(struct softirq_action *h)
3575 int this_cpu = smp_processor_id();
3576 struct rq *this_rq = cpu_rq(this_cpu);
3577 enum cpu_idle_type idle = this_rq->idle_at_tick ?
3578 CPU_IDLE : CPU_NOT_IDLE;
3580 rebalance_domains(this_cpu, idle);
3584 * If this cpu is the owner for idle load balancing, then do the
3585 * balancing on behalf of the other idle cpus whose ticks are
3588 if (this_rq->idle_at_tick &&
3589 atomic_read(&nohz.load_balancer) == this_cpu) {
3590 cpumask_t cpus = nohz.cpu_mask;
3594 cpu_clear(this_cpu, cpus);
3595 for_each_cpu_mask(balance_cpu, cpus) {
3597 * If this cpu gets work to do, stop the load balancing
3598 * work being done for other cpus. Next load
3599 * balancing owner will pick it up.
3604 rebalance_domains(balance_cpu, CPU_IDLE);
3606 rq = cpu_rq(balance_cpu);
3607 if (time_after(this_rq->next_balance, rq->next_balance))
3608 this_rq->next_balance = rq->next_balance;
3615 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
3617 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
3618 * idle load balancing owner or decide to stop the periodic load balancing,
3619 * if the whole system is idle.
3621 static inline void trigger_load_balance(struct rq *rq, int cpu)
3625 * If we were in the nohz mode recently and busy at the current
3626 * scheduler tick, then check if we need to nominate new idle
3629 if (rq->in_nohz_recently && !rq->idle_at_tick) {
3630 rq->in_nohz_recently = 0;
3632 if (atomic_read(&nohz.load_balancer) == cpu) {
3633 cpu_clear(cpu, nohz.cpu_mask);
3634 atomic_set(&nohz.load_balancer, -1);
3637 if (atomic_read(&nohz.load_balancer) == -1) {
3639 * simple selection for now: Nominate the
3640 * first cpu in the nohz list to be the next
3643 * TBD: Traverse the sched domains and nominate
3644 * the nearest cpu in the nohz.cpu_mask.
3646 int ilb = first_cpu(nohz.cpu_mask);
3654 * If this cpu is idle and doing idle load balancing for all the
3655 * cpus with ticks stopped, is it time for that to stop?
3657 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
3658 cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3664 * If this cpu is idle and the idle load balancing is done by
3665 * someone else, then no need raise the SCHED_SOFTIRQ
3667 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
3668 cpu_isset(cpu, nohz.cpu_mask))
3671 if (time_after_eq(jiffies, rq->next_balance))
3672 raise_softirq(SCHED_SOFTIRQ);
3675 #else /* CONFIG_SMP */
3678 * on UP we do not need to balance between CPUs:
3680 static inline void idle_balance(int cpu, struct rq *rq)
3686 DEFINE_PER_CPU(struct kernel_stat, kstat);
3688 EXPORT_PER_CPU_SYMBOL(kstat);
3691 * Return p->sum_exec_runtime plus any more ns on the sched_clock
3692 * that have not yet been banked in case the task is currently running.
3694 unsigned long long task_sched_runtime(struct task_struct *p)
3696 unsigned long flags;
3700 rq = task_rq_lock(p, &flags);
3701 ns = p->se.sum_exec_runtime;
3702 if (task_current(rq, p)) {
3703 update_rq_clock(rq);
3704 delta_exec = rq->clock - p->se.exec_start;
3705 if ((s64)delta_exec > 0)
3708 task_rq_unlock(rq, &flags);
3714 * Account user cpu time to a process.
3715 * @p: the process that the cpu time gets accounted to
3716 * @cputime: the cpu time spent in user space since the last update
3718 void account_user_time(struct task_struct *p, cputime_t cputime)
3720 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3723 p->utime = cputime_add(p->utime, cputime);
3725 /* Add user time to cpustat. */
3726 tmp = cputime_to_cputime64(cputime);
3727 if (TASK_NICE(p) > 0)
3728 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3730 cpustat->user = cputime64_add(cpustat->user, tmp);
3734 * Account guest cpu time to a process.
3735 * @p: the process that the cpu time gets accounted to
3736 * @cputime: the cpu time spent in virtual machine since the last update
3738 static void account_guest_time(struct task_struct *p, cputime_t cputime)
3741 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3743 tmp = cputime_to_cputime64(cputime);
3745 p->utime = cputime_add(p->utime, cputime);
3746 p->gtime = cputime_add(p->gtime, cputime);
3748 cpustat->user = cputime64_add(cpustat->user, tmp);
3749 cpustat->guest = cputime64_add(cpustat->guest, tmp);
3753 * Account scaled user cpu time to a process.
3754 * @p: the process that the cpu time gets accounted to
3755 * @cputime: the cpu time spent in user space since the last update
3757 void account_user_time_scaled(struct task_struct *p, cputime_t cputime)
3759 p->utimescaled = cputime_add(p->utimescaled, cputime);
3763 * Account system cpu time to a process.
3764 * @p: the process that the cpu time gets accounted to
3765 * @hardirq_offset: the offset to subtract from hardirq_count()
3766 * @cputime: the cpu time spent in kernel space since the last update
3768 void account_system_time(struct task_struct *p, int hardirq_offset,
3771 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3772 struct rq *rq = this_rq();
3775 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0))
3776 return account_guest_time(p, cputime);
3778 p->stime = cputime_add(p->stime, cputime);
3780 /* Add system time to cpustat. */
3781 tmp = cputime_to_cputime64(cputime);
3782 if (hardirq_count() - hardirq_offset)
3783 cpustat->irq = cputime64_add(cpustat->irq, tmp);
3784 else if (softirq_count())
3785 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
3786 else if (p != rq->idle)
3787 cpustat->system = cputime64_add(cpustat->system, tmp);
3788 else if (atomic_read(&rq->nr_iowait) > 0)
3789 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3791 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3792 /* Account for system time used */
3793 acct_update_integrals(p);
3797 * Account scaled system cpu time to a process.
3798 * @p: the process that the cpu time gets accounted to
3799 * @hardirq_offset: the offset to subtract from hardirq_count()
3800 * @cputime: the cpu time spent in kernel space since the last update
3802 void account_system_time_scaled(struct task_struct *p, cputime_t cputime)
3804 p->stimescaled = cputime_add(p->stimescaled, cputime);
3808 * Account for involuntary wait time.
3809 * @p: the process from which the cpu time has been stolen
3810 * @steal: the cpu time spent in involuntary wait
3812 void account_steal_time(struct task_struct *p, cputime_t steal)
3814 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3815 cputime64_t tmp = cputime_to_cputime64(steal);
3816 struct rq *rq = this_rq();
3818 if (p == rq->idle) {
3819 p->stime = cputime_add(p->stime, steal);
3820 if (atomic_read(&rq->nr_iowait) > 0)
3821 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3823 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3825 cpustat->steal = cputime64_add(cpustat->steal, tmp);
3829 * This function gets called by the timer code, with HZ frequency.
3830 * We call it with interrupts disabled.
3832 * It also gets called by the fork code, when changing the parent's
3835 void scheduler_tick(void)
3837 int cpu = smp_processor_id();
3838 struct rq *rq = cpu_rq(cpu);
3839 struct task_struct *curr = rq->curr;
3840 u64 next_tick = rq->tick_timestamp + TICK_NSEC;
3842 spin_lock(&rq->lock);
3843 __update_rq_clock(rq);
3845 * Let rq->clock advance by at least TICK_NSEC:
3847 if (unlikely(rq->clock < next_tick)) {
3848 rq->clock = next_tick;
3849 rq->clock_underflows++;
3851 rq->tick_timestamp = rq->clock;
3852 update_last_tick_seen(rq);
3853 update_cpu_load(rq);
3854 curr->sched_class->task_tick(rq, curr, 0);
3855 update_sched_rt_period(rq);
3856 spin_unlock(&rq->lock);
3859 rq->idle_at_tick = idle_cpu(cpu);
3860 trigger_load_balance(rq, cpu);
3864 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3866 void __kprobes add_preempt_count(int val)
3871 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3873 preempt_count() += val;
3875 * Spinlock count overflowing soon?
3877 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3880 EXPORT_SYMBOL(add_preempt_count);
3882 void __kprobes sub_preempt_count(int val)
3887 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3890 * Is the spinlock portion underflowing?
3892 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3893 !(preempt_count() & PREEMPT_MASK)))
3896 preempt_count() -= val;
3898 EXPORT_SYMBOL(sub_preempt_count);
3903 * Print scheduling while atomic bug:
3905 static noinline void __schedule_bug(struct task_struct *prev)
3907 struct pt_regs *regs = get_irq_regs();
3909 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3910 prev->comm, prev->pid, preempt_count());
3912 debug_show_held_locks(prev);
3913 if (irqs_disabled())
3914 print_irqtrace_events(prev);
3923 * Various schedule()-time debugging checks and statistics:
3925 static inline void schedule_debug(struct task_struct *prev)
3928 * Test if we are atomic. Since do_exit() needs to call into
3929 * schedule() atomically, we ignore that path for now.
3930 * Otherwise, whine if we are scheduling when we should not be.
3932 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev->exit_state))
3933 __schedule_bug(prev);
3935 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3937 schedstat_inc(this_rq(), sched_count);
3938 #ifdef CONFIG_SCHEDSTATS
3939 if (unlikely(prev->lock_depth >= 0)) {
3940 schedstat_inc(this_rq(), bkl_count);
3941 schedstat_inc(prev, sched_info.bkl_count);
3947 * Pick up the highest-prio task:
3949 static inline struct task_struct *
3950 pick_next_task(struct rq *rq, struct task_struct *prev)
3952 const struct sched_class *class;
3953 struct task_struct *p;
3956 * Optimization: we know that if all tasks are in
3957 * the fair class we can call that function directly:
3959 if (likely(rq->nr_running == rq->cfs.nr_running)) {
3960 p = fair_sched_class.pick_next_task(rq);
3965 class = sched_class_highest;
3967 p = class->pick_next_task(rq);
3971 * Will never be NULL as the idle class always
3972 * returns a non-NULL p:
3974 class = class->next;
3979 * schedule() is the main scheduler function.
3981 asmlinkage void __sched schedule(void)
3983 struct task_struct *prev, *next;
3984 unsigned long *switch_count;
3990 cpu = smp_processor_id();
3994 switch_count = &prev->nivcsw;
3996 release_kernel_lock(prev);
3997 need_resched_nonpreemptible:
3999 schedule_debug(prev);
4004 * Do the rq-clock update outside the rq lock:
4006 local_irq_disable();
4007 __update_rq_clock(rq);
4008 spin_lock(&rq->lock);
4009 clear_tsk_need_resched(prev);
4011 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
4012 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
4013 signal_pending(prev))) {
4014 prev->state = TASK_RUNNING;
4016 deactivate_task(rq, prev, 1);
4018 switch_count = &prev->nvcsw;
4022 if (prev->sched_class->pre_schedule)
4023 prev->sched_class->pre_schedule(rq, prev);
4026 if (unlikely(!rq->nr_running))
4027 idle_balance(cpu, rq);
4029 prev->sched_class->put_prev_task(rq, prev);
4030 next = pick_next_task(rq, prev);
4032 sched_info_switch(prev, next);
4034 if (likely(prev != next)) {
4039 context_switch(rq, prev, next); /* unlocks the rq */
4041 * the context switch might have flipped the stack from under
4042 * us, hence refresh the local variables.
4044 cpu = smp_processor_id();
4047 spin_unlock_irq(&rq->lock);
4051 if (unlikely(reacquire_kernel_lock(current) < 0))
4052 goto need_resched_nonpreemptible;
4054 preempt_enable_no_resched();
4055 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
4058 EXPORT_SYMBOL(schedule);
4060 #ifdef CONFIG_PREEMPT
4062 * this is the entry point to schedule() from in-kernel preemption
4063 * off of preempt_enable. Kernel preemptions off return from interrupt
4064 * occur there and call schedule directly.
4066 asmlinkage void __sched preempt_schedule(void)
4068 struct thread_info *ti = current_thread_info();
4069 struct task_struct *task = current;
4070 int saved_lock_depth;
4073 * If there is a non-zero preempt_count or interrupts are disabled,
4074 * we do not want to preempt the current task. Just return..
4076 if (likely(ti->preempt_count || irqs_disabled()))
4080 add_preempt_count(PREEMPT_ACTIVE);
4083 * We keep the big kernel semaphore locked, but we
4084 * clear ->lock_depth so that schedule() doesnt
4085 * auto-release the semaphore:
4087 saved_lock_depth = task->lock_depth;
4088 task->lock_depth = -1;
4090 task->lock_depth = saved_lock_depth;
4091 sub_preempt_count(PREEMPT_ACTIVE);
4094 * Check again in case we missed a preemption opportunity
4095 * between schedule and now.
4098 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4100 EXPORT_SYMBOL(preempt_schedule);
4103 * this is the entry point to schedule() from kernel preemption
4104 * off of irq context.
4105 * Note, that this is called and return with irqs disabled. This will
4106 * protect us against recursive calling from irq.
4108 asmlinkage void __sched preempt_schedule_irq(void)
4110 struct thread_info *ti = current_thread_info();
4111 struct task_struct *task = current;
4112 int saved_lock_depth;
4114 /* Catch callers which need to be fixed */
4115 BUG_ON(ti->preempt_count || !irqs_disabled());
4118 add_preempt_count(PREEMPT_ACTIVE);
4121 * We keep the big kernel semaphore locked, but we
4122 * clear ->lock_depth so that schedule() doesnt
4123 * auto-release the semaphore:
4125 saved_lock_depth = task->lock_depth;
4126 task->lock_depth = -1;
4129 local_irq_disable();
4130 task->lock_depth = saved_lock_depth;
4131 sub_preempt_count(PREEMPT_ACTIVE);
4134 * Check again in case we missed a preemption opportunity
4135 * between schedule and now.
4138 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4141 #endif /* CONFIG_PREEMPT */
4143 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
4146 return try_to_wake_up(curr->private, mode, sync);
4148 EXPORT_SYMBOL(default_wake_function);
4151 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4152 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4153 * number) then we wake all the non-exclusive tasks and one exclusive task.
4155 * There are circumstances in which we can try to wake a task which has already
4156 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4157 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4159 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
4160 int nr_exclusive, int sync, void *key)
4162 wait_queue_t *curr, *next;
4164 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
4165 unsigned flags = curr->flags;
4167 if (curr->func(curr, mode, sync, key) &&
4168 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
4174 * __wake_up - wake up threads blocked on a waitqueue.
4176 * @mode: which threads
4177 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4178 * @key: is directly passed to the wakeup function
4180 void __wake_up(wait_queue_head_t *q, unsigned int mode,
4181 int nr_exclusive, void *key)
4183 unsigned long flags;
4185 spin_lock_irqsave(&q->lock, flags);
4186 __wake_up_common(q, mode, nr_exclusive, 0, key);
4187 spin_unlock_irqrestore(&q->lock, flags);
4189 EXPORT_SYMBOL(__wake_up);
4192 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4194 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4196 __wake_up_common(q, mode, 1, 0, NULL);
4200 * __wake_up_sync - wake up threads blocked on a waitqueue.
4202 * @mode: which threads
4203 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4205 * The sync wakeup differs that the waker knows that it will schedule
4206 * away soon, so while the target thread will be woken up, it will not
4207 * be migrated to another CPU - ie. the two threads are 'synchronized'
4208 * with each other. This can prevent needless bouncing between CPUs.
4210 * On UP it can prevent extra preemption.
4213 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4215 unsigned long flags;
4221 if (unlikely(!nr_exclusive))
4224 spin_lock_irqsave(&q->lock, flags);
4225 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
4226 spin_unlock_irqrestore(&q->lock, flags);
4228 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
4230 void complete(struct completion *x)
4232 unsigned long flags;
4234 spin_lock_irqsave(&x->wait.lock, flags);
4236 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4237 spin_unlock_irqrestore(&x->wait.lock, flags);
4239 EXPORT_SYMBOL(complete);
4241 void complete_all(struct completion *x)
4243 unsigned long flags;
4245 spin_lock_irqsave(&x->wait.lock, flags);
4246 x->done += UINT_MAX/2;
4247 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4248 spin_unlock_irqrestore(&x->wait.lock, flags);
4250 EXPORT_SYMBOL(complete_all);
4252 static inline long __sched
4253 do_wait_for_common(struct completion *x, long timeout, int state)
4256 DECLARE_WAITQUEUE(wait, current);
4258 wait.flags |= WQ_FLAG_EXCLUSIVE;
4259 __add_wait_queue_tail(&x->wait, &wait);
4261 if ((state == TASK_INTERRUPTIBLE &&
4262 signal_pending(current)) ||
4263 (state == TASK_KILLABLE &&
4264 fatal_signal_pending(current))) {
4265 __remove_wait_queue(&x->wait, &wait);
4266 return -ERESTARTSYS;
4268 __set_current_state(state);
4269 spin_unlock_irq(&x->wait.lock);
4270 timeout = schedule_timeout(timeout);
4271 spin_lock_irq(&x->wait.lock);
4273 __remove_wait_queue(&x->wait, &wait);
4277 __remove_wait_queue(&x->wait, &wait);
4284 wait_for_common(struct completion *x, long timeout, int state)
4288 spin_lock_irq(&x->wait.lock);
4289 timeout = do_wait_for_common(x, timeout, state);
4290 spin_unlock_irq(&x->wait.lock);
4294 void __sched wait_for_completion(struct completion *x)
4296 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4298 EXPORT_SYMBOL(wait_for_completion);
4300 unsigned long __sched
4301 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4303 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4305 EXPORT_SYMBOL(wait_for_completion_timeout);
4307 int __sched wait_for_completion_interruptible(struct completion *x)
4309 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4310 if (t == -ERESTARTSYS)
4314 EXPORT_SYMBOL(wait_for_completion_interruptible);
4316 unsigned long __sched
4317 wait_for_completion_interruptible_timeout(struct completion *x,
4318 unsigned long timeout)
4320 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4322 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4324 int __sched wait_for_completion_killable(struct completion *x)
4326 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4327 if (t == -ERESTARTSYS)
4331 EXPORT_SYMBOL(wait_for_completion_killable);
4334 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4336 unsigned long flags;
4339 init_waitqueue_entry(&wait, current);
4341 __set_current_state(state);
4343 spin_lock_irqsave(&q->lock, flags);
4344 __add_wait_queue(q, &wait);
4345 spin_unlock(&q->lock);
4346 timeout = schedule_timeout(timeout);
4347 spin_lock_irq(&q->lock);
4348 __remove_wait_queue(q, &wait);
4349 spin_unlock_irqrestore(&q->lock, flags);
4354 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4356 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4358 EXPORT_SYMBOL(interruptible_sleep_on);
4361 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4363 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4365 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4367 void __sched sleep_on(wait_queue_head_t *q)
4369 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4371 EXPORT_SYMBOL(sleep_on);
4373 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4375 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
4377 EXPORT_SYMBOL(sleep_on_timeout);
4379 #ifdef CONFIG_RT_MUTEXES
4382 * rt_mutex_setprio - set the current priority of a task
4384 * @prio: prio value (kernel-internal form)
4386 * This function changes the 'effective' priority of a task. It does
4387 * not touch ->normal_prio like __setscheduler().
4389 * Used by the rt_mutex code to implement priority inheritance logic.
4391 void rt_mutex_setprio(struct task_struct *p, int prio)
4393 unsigned long flags;
4394 int oldprio, on_rq, running;
4396 const struct sched_class *prev_class = p->sched_class;
4398 BUG_ON(prio < 0 || prio > MAX_PRIO);
4400 rq = task_rq_lock(p, &flags);
4401 update_rq_clock(rq);
4404 on_rq = p->se.on_rq;
4405 running = task_current(rq, p);
4407 dequeue_task(rq, p, 0);
4409 p->sched_class->put_prev_task(rq, p);
4412 p->sched_class = &rt_sched_class;
4414 p->sched_class = &fair_sched_class;
4419 p->sched_class->set_curr_task(rq);
4421 enqueue_task(rq, p, 0);
4423 check_class_changed(rq, p, prev_class, oldprio, running);
4425 task_rq_unlock(rq, &flags);
4430 void set_user_nice(struct task_struct *p, long nice)
4432 int old_prio, delta, on_rq;
4433 unsigned long flags;
4436 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4439 * We have to be careful, if called from sys_setpriority(),
4440 * the task might be in the middle of scheduling on another CPU.
4442 rq = task_rq_lock(p, &flags);
4443 update_rq_clock(rq);
4445 * The RT priorities are set via sched_setscheduler(), but we still
4446 * allow the 'normal' nice value to be set - but as expected
4447 * it wont have any effect on scheduling until the task is
4448 * SCHED_FIFO/SCHED_RR:
4450 if (task_has_rt_policy(p)) {
4451 p->static_prio = NICE_TO_PRIO(nice);
4454 on_rq = p->se.on_rq;
4456 dequeue_task(rq, p, 0);
4460 p->static_prio = NICE_TO_PRIO(nice);
4463 p->prio = effective_prio(p);
4464 delta = p->prio - old_prio;
4467 enqueue_task(rq, p, 0);
4470 * If the task increased its priority or is running and
4471 * lowered its priority, then reschedule its CPU:
4473 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4474 resched_task(rq->curr);
4477 task_rq_unlock(rq, &flags);
4479 EXPORT_SYMBOL(set_user_nice);
4482 * can_nice - check if a task can reduce its nice value
4486 int can_nice(const struct task_struct *p, const int nice)
4488 /* convert nice value [19,-20] to rlimit style value [1,40] */
4489 int nice_rlim = 20 - nice;
4491 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
4492 capable(CAP_SYS_NICE));
4495 #ifdef __ARCH_WANT_SYS_NICE
4498 * sys_nice - change the priority of the current process.
4499 * @increment: priority increment
4501 * sys_setpriority is a more generic, but much slower function that
4502 * does similar things.
4504 asmlinkage long sys_nice(int increment)
4509 * Setpriority might change our priority at the same moment.
4510 * We don't have to worry. Conceptually one call occurs first
4511 * and we have a single winner.
4513 if (increment < -40)
4518 nice = PRIO_TO_NICE(current->static_prio) + increment;
4524 if (increment < 0 && !can_nice(current, nice))
4527 retval = security_task_setnice(current, nice);
4531 set_user_nice(current, nice);
4538 * task_prio - return the priority value of a given task.
4539 * @p: the task in question.
4541 * This is the priority value as seen by users in /proc.
4542 * RT tasks are offset by -200. Normal tasks are centered
4543 * around 0, value goes from -16 to +15.
4545 int task_prio(const struct task_struct *p)
4547 return p->prio - MAX_RT_PRIO;
4551 * task_nice - return the nice value of a given task.
4552 * @p: the task in question.
4554 int task_nice(const struct task_struct *p)
4556 return TASK_NICE(p);
4558 EXPORT_SYMBOL(task_nice);
4561 * idle_cpu - is a given cpu idle currently?
4562 * @cpu: the processor in question.
4564 int idle_cpu(int cpu)
4566 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
4570 * idle_task - return the idle task for a given cpu.
4571 * @cpu: the processor in question.
4573 struct task_struct *idle_task(int cpu)
4575 return cpu_rq(cpu)->idle;
4579 * find_process_by_pid - find a process with a matching PID value.
4580 * @pid: the pid in question.
4582 static struct task_struct *find_process_by_pid(pid_t pid)
4584 return pid ? find_task_by_vpid(pid) : current;
4587 /* Actually do priority change: must hold rq lock. */
4589 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
4591 BUG_ON(p->se.on_rq);
4594 switch (p->policy) {
4598 p->sched_class = &fair_sched_class;
4602 p->sched_class = &rt_sched_class;
4606 p->rt_priority = prio;
4607 p->normal_prio = normal_prio(p);
4608 /* we are holding p->pi_lock already */
4609 p->prio = rt_mutex_getprio(p);
4614 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4615 * @p: the task in question.
4616 * @policy: new policy.
4617 * @param: structure containing the new RT priority.
4619 * NOTE that the task may be already dead.
4621 int sched_setscheduler(struct task_struct *p, int policy,
4622 struct sched_param *param)
4624 int retval, oldprio, oldpolicy = -1, on_rq, running;
4625 unsigned long flags;
4626 const struct sched_class *prev_class = p->sched_class;
4629 /* may grab non-irq protected spin_locks */
4630 BUG_ON(in_interrupt());
4632 /* double check policy once rq lock held */
4634 policy = oldpolicy = p->policy;
4635 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
4636 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
4637 policy != SCHED_IDLE)
4640 * Valid priorities for SCHED_FIFO and SCHED_RR are
4641 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4642 * SCHED_BATCH and SCHED_IDLE is 0.
4644 if (param->sched_priority < 0 ||
4645 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
4646 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
4648 if (rt_policy(policy) != (param->sched_priority != 0))
4652 * Allow unprivileged RT tasks to decrease priority:
4654 if (!capable(CAP_SYS_NICE)) {
4655 if (rt_policy(policy)) {
4656 unsigned long rlim_rtprio;
4658 if (!lock_task_sighand(p, &flags))
4660 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
4661 unlock_task_sighand(p, &flags);
4663 /* can't set/change the rt policy */
4664 if (policy != p->policy && !rlim_rtprio)
4667 /* can't increase priority */
4668 if (param->sched_priority > p->rt_priority &&
4669 param->sched_priority > rlim_rtprio)
4673 * Like positive nice levels, dont allow tasks to
4674 * move out of SCHED_IDLE either:
4676 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
4679 /* can't change other user's priorities */
4680 if ((current->euid != p->euid) &&
4681 (current->euid != p->uid))
4685 #ifdef CONFIG_RT_GROUP_SCHED
4687 * Do not allow realtime tasks into groups that have no runtime
4690 if (rt_policy(policy) && task_group(p)->rt_runtime == 0)
4694 retval = security_task_setscheduler(p, policy, param);
4698 * make sure no PI-waiters arrive (or leave) while we are
4699 * changing the priority of the task:
4701 spin_lock_irqsave(&p->pi_lock, flags);
4703 * To be able to change p->policy safely, the apropriate
4704 * runqueue lock must be held.
4706 rq = __task_rq_lock(p);
4707 /* recheck policy now with rq lock held */
4708 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4709 policy = oldpolicy = -1;
4710 __task_rq_unlock(rq);
4711 spin_unlock_irqrestore(&p->pi_lock, flags);
4714 update_rq_clock(rq);
4715 on_rq = p->se.on_rq;
4716 running = task_current(rq, p);
4718 deactivate_task(rq, p, 0);
4720 p->sched_class->put_prev_task(rq, p);
4723 __setscheduler(rq, p, policy, param->sched_priority);
4726 p->sched_class->set_curr_task(rq);
4728 activate_task(rq, p, 0);
4730 check_class_changed(rq, p, prev_class, oldprio, running);
4732 __task_rq_unlock(rq);
4733 spin_unlock_irqrestore(&p->pi_lock, flags);
4735 rt_mutex_adjust_pi(p);
4739 EXPORT_SYMBOL_GPL(sched_setscheduler);
4742 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4744 struct sched_param lparam;
4745 struct task_struct *p;
4748 if (!param || pid < 0)
4750 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4755 p = find_process_by_pid(pid);
4757 retval = sched_setscheduler(p, policy, &lparam);
4764 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4765 * @pid: the pid in question.
4766 * @policy: new policy.
4767 * @param: structure containing the new RT priority.
4770 sys_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4772 /* negative values for policy are not valid */
4776 return do_sched_setscheduler(pid, policy, param);
4780 * sys_sched_setparam - set/change the RT priority of a thread
4781 * @pid: the pid in question.
4782 * @param: structure containing the new RT priority.
4784 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
4786 return do_sched_setscheduler(pid, -1, param);
4790 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4791 * @pid: the pid in question.
4793 asmlinkage long sys_sched_getscheduler(pid_t pid)
4795 struct task_struct *p;
4802 read_lock(&tasklist_lock);
4803 p = find_process_by_pid(pid);
4805 retval = security_task_getscheduler(p);
4809 read_unlock(&tasklist_lock);
4814 * sys_sched_getscheduler - get the RT priority of a thread
4815 * @pid: the pid in question.
4816 * @param: structure containing the RT priority.
4818 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
4820 struct sched_param lp;
4821 struct task_struct *p;
4824 if (!param || pid < 0)
4827 read_lock(&tasklist_lock);
4828 p = find_process_by_pid(pid);
4833 retval = security_task_getscheduler(p);
4837 lp.sched_priority = p->rt_priority;
4838 read_unlock(&tasklist_lock);
4841 * This one might sleep, we cannot do it with a spinlock held ...
4843 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4848 read_unlock(&tasklist_lock);
4852 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
4854 cpumask_t cpus_allowed;
4855 struct task_struct *p;
4859 read_lock(&tasklist_lock);
4861 p = find_process_by_pid(pid);
4863 read_unlock(&tasklist_lock);
4869 * It is not safe to call set_cpus_allowed with the
4870 * tasklist_lock held. We will bump the task_struct's
4871 * usage count and then drop tasklist_lock.
4874 read_unlock(&tasklist_lock);
4877 if ((current->euid != p->euid) && (current->euid != p->uid) &&
4878 !capable(CAP_SYS_NICE))
4881 retval = security_task_setscheduler(p, 0, NULL);
4885 cpus_allowed = cpuset_cpus_allowed(p);
4886 cpus_and(new_mask, new_mask, cpus_allowed);
4888 retval = set_cpus_allowed(p, new_mask);
4891 cpus_allowed = cpuset_cpus_allowed(p);
4892 if (!cpus_subset(new_mask, cpus_allowed)) {
4894 * We must have raced with a concurrent cpuset
4895 * update. Just reset the cpus_allowed to the
4896 * cpuset's cpus_allowed
4898 new_mask = cpus_allowed;
4908 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4909 cpumask_t *new_mask)
4911 if (len < sizeof(cpumask_t)) {
4912 memset(new_mask, 0, sizeof(cpumask_t));
4913 } else if (len > sizeof(cpumask_t)) {
4914 len = sizeof(cpumask_t);
4916 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4920 * sys_sched_setaffinity - set the cpu affinity of a process
4921 * @pid: pid of the process
4922 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4923 * @user_mask_ptr: user-space pointer to the new cpu mask
4925 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
4926 unsigned long __user *user_mask_ptr)
4931 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
4935 return sched_setaffinity(pid, new_mask);
4939 * Represents all cpu's present in the system
4940 * In systems capable of hotplug, this map could dynamically grow
4941 * as new cpu's are detected in the system via any platform specific
4942 * method, such as ACPI for e.g.
4945 cpumask_t cpu_present_map __read_mostly;
4946 EXPORT_SYMBOL(cpu_present_map);
4949 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
4950 EXPORT_SYMBOL(cpu_online_map);
4952 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
4953 EXPORT_SYMBOL(cpu_possible_map);
4956 long sched_getaffinity(pid_t pid, cpumask_t *mask)
4958 struct task_struct *p;
4962 read_lock(&tasklist_lock);
4965 p = find_process_by_pid(pid);
4969 retval = security_task_getscheduler(p);
4973 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
4976 read_unlock(&tasklist_lock);
4983 * sys_sched_getaffinity - get the cpu affinity of a process
4984 * @pid: pid of the process
4985 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4986 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4988 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
4989 unsigned long __user *user_mask_ptr)
4994 if (len < sizeof(cpumask_t))
4997 ret = sched_getaffinity(pid, &mask);
5001 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
5004 return sizeof(cpumask_t);
5008 * sys_sched_yield - yield the current processor to other threads.
5010 * This function yields the current CPU to other tasks. If there are no
5011 * other threads running on this CPU then this function will return.
5013 asmlinkage long sys_sched_yield(void)
5015 struct rq *rq = this_rq_lock();
5017 schedstat_inc(rq, yld_count);
5018 current->sched_class->yield_task(rq);
5021 * Since we are going to call schedule() anyway, there's
5022 * no need to preempt or enable interrupts:
5024 __release(rq->lock);
5025 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5026 _raw_spin_unlock(&rq->lock);
5027 preempt_enable_no_resched();
5034 static void __cond_resched(void)
5036 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5037 __might_sleep(__FILE__, __LINE__);
5040 * The BKS might be reacquired before we have dropped
5041 * PREEMPT_ACTIVE, which could trigger a second
5042 * cond_resched() call.
5045 add_preempt_count(PREEMPT_ACTIVE);
5047 sub_preempt_count(PREEMPT_ACTIVE);
5048 } while (need_resched());
5051 #if !defined(CONFIG_PREEMPT) || defined(CONFIG_PREEMPT_VOLUNTARY)
5052 int __sched _cond_resched(void)
5054 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
5055 system_state == SYSTEM_RUNNING) {
5061 EXPORT_SYMBOL(_cond_resched);
5065 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5066 * call schedule, and on return reacquire the lock.
5068 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5069 * operations here to prevent schedule() from being called twice (once via
5070 * spin_unlock(), once by hand).
5072 int cond_resched_lock(spinlock_t *lock)
5074 int resched = need_resched() && system_state == SYSTEM_RUNNING;
5077 if (spin_needbreak(lock) || resched) {
5079 if (resched && need_resched())
5088 EXPORT_SYMBOL(cond_resched_lock);
5090 int __sched cond_resched_softirq(void)
5092 BUG_ON(!in_softirq());
5094 if (need_resched() && system_state == SYSTEM_RUNNING) {
5102 EXPORT_SYMBOL(cond_resched_softirq);
5105 * yield - yield the current processor to other threads.
5107 * This is a shortcut for kernel-space yielding - it marks the
5108 * thread runnable and calls sys_sched_yield().
5110 void __sched yield(void)
5112 set_current_state(TASK_RUNNING);
5115 EXPORT_SYMBOL(yield);
5118 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5119 * that process accounting knows that this is a task in IO wait state.
5121 * But don't do that if it is a deliberate, throttling IO wait (this task
5122 * has set its backing_dev_info: the queue against which it should throttle)
5124 void __sched io_schedule(void)
5126 struct rq *rq = &__raw_get_cpu_var(runqueues);
5128 delayacct_blkio_start();
5129 atomic_inc(&rq->nr_iowait);
5131 atomic_dec(&rq->nr_iowait);
5132 delayacct_blkio_end();
5134 EXPORT_SYMBOL(io_schedule);
5136 long __sched io_schedule_timeout(long timeout)
5138 struct rq *rq = &__raw_get_cpu_var(runqueues);
5141 delayacct_blkio_start();
5142 atomic_inc(&rq->nr_iowait);
5143 ret = schedule_timeout(timeout);
5144 atomic_dec(&rq->nr_iowait);
5145 delayacct_blkio_end();
5150 * sys_sched_get_priority_max - return maximum RT priority.
5151 * @policy: scheduling class.
5153 * this syscall returns the maximum rt_priority that can be used
5154 * by a given scheduling class.
5156 asmlinkage long sys_sched_get_priority_max(int policy)
5163 ret = MAX_USER_RT_PRIO-1;
5175 * sys_sched_get_priority_min - return minimum RT priority.
5176 * @policy: scheduling class.
5178 * this syscall returns the minimum rt_priority that can be used
5179 * by a given scheduling class.
5181 asmlinkage long sys_sched_get_priority_min(int policy)
5199 * sys_sched_rr_get_interval - return the default timeslice of a process.
5200 * @pid: pid of the process.
5201 * @interval: userspace pointer to the timeslice value.
5203 * this syscall writes the default timeslice value of a given process
5204 * into the user-space timespec buffer. A value of '0' means infinity.
5207 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
5209 struct task_struct *p;
5210 unsigned int time_slice;
5218 read_lock(&tasklist_lock);
5219 p = find_process_by_pid(pid);
5223 retval = security_task_getscheduler(p);
5228 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5229 * tasks that are on an otherwise idle runqueue:
5232 if (p->policy == SCHED_RR) {
5233 time_slice = DEF_TIMESLICE;
5234 } else if (p->policy != SCHED_FIFO) {
5235 struct sched_entity *se = &p->se;
5236 unsigned long flags;
5239 rq = task_rq_lock(p, &flags);
5240 if (rq->cfs.load.weight)
5241 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
5242 task_rq_unlock(rq, &flags);
5244 read_unlock(&tasklist_lock);
5245 jiffies_to_timespec(time_slice, &t);
5246 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5250 read_unlock(&tasklist_lock);
5254 static const char stat_nam[] = "RSDTtZX";
5256 void sched_show_task(struct task_struct *p)
5258 unsigned long free = 0;
5261 state = p->state ? __ffs(p->state) + 1 : 0;
5262 printk(KERN_INFO "%-13.13s %c", p->comm,
5263 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5264 #if BITS_PER_LONG == 32
5265 if (state == TASK_RUNNING)
5266 printk(KERN_CONT " running ");
5268 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5270 if (state == TASK_RUNNING)
5271 printk(KERN_CONT " running task ");
5273 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5275 #ifdef CONFIG_DEBUG_STACK_USAGE
5277 unsigned long *n = end_of_stack(p);
5280 free = (unsigned long)n - (unsigned long)end_of_stack(p);
5283 printk(KERN_CONT "%5lu %5d %6d\n", free,
5284 task_pid_nr(p), task_pid_nr(p->real_parent));
5286 show_stack(p, NULL);
5289 void show_state_filter(unsigned long state_filter)
5291 struct task_struct *g, *p;
5293 #if BITS_PER_LONG == 32
5295 " task PC stack pid father\n");
5298 " task PC stack pid father\n");
5300 read_lock(&tasklist_lock);
5301 do_each_thread(g, p) {
5303 * reset the NMI-timeout, listing all files on a slow
5304 * console might take alot of time:
5306 touch_nmi_watchdog();
5307 if (!state_filter || (p->state & state_filter))
5309 } while_each_thread(g, p);
5311 touch_all_softlockup_watchdogs();
5313 #ifdef CONFIG_SCHED_DEBUG
5314 sysrq_sched_debug_show();
5316 read_unlock(&tasklist_lock);
5318 * Only show locks if all tasks are dumped:
5320 if (state_filter == -1)
5321 debug_show_all_locks();
5324 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5326 idle->sched_class = &idle_sched_class;
5330 * init_idle - set up an idle thread for a given CPU
5331 * @idle: task in question
5332 * @cpu: cpu the idle task belongs to
5334 * NOTE: this function does not set the idle thread's NEED_RESCHED
5335 * flag, to make booting more robust.
5337 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5339 struct rq *rq = cpu_rq(cpu);
5340 unsigned long flags;
5343 idle->se.exec_start = sched_clock();
5345 idle->prio = idle->normal_prio = MAX_PRIO;
5346 idle->cpus_allowed = cpumask_of_cpu(cpu);
5347 __set_task_cpu(idle, cpu);
5349 spin_lock_irqsave(&rq->lock, flags);
5350 rq->curr = rq->idle = idle;
5351 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5354 spin_unlock_irqrestore(&rq->lock, flags);
5356 /* Set the preempt count _outside_ the spinlocks! */
5357 task_thread_info(idle)->preempt_count = 0;
5360 * The idle tasks have their own, simple scheduling class:
5362 idle->sched_class = &idle_sched_class;
5366 * In a system that switches off the HZ timer nohz_cpu_mask
5367 * indicates which cpus entered this state. This is used
5368 * in the rcu update to wait only for active cpus. For system
5369 * which do not switch off the HZ timer nohz_cpu_mask should
5370 * always be CPU_MASK_NONE.
5372 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
5375 * Increase the granularity value when there are more CPUs,
5376 * because with more CPUs the 'effective latency' as visible
5377 * to users decreases. But the relationship is not linear,
5378 * so pick a second-best guess by going with the log2 of the
5381 * This idea comes from the SD scheduler of Con Kolivas:
5383 static inline void sched_init_granularity(void)
5385 unsigned int factor = 1 + ilog2(num_online_cpus());
5386 const unsigned long limit = 200000000;
5388 sysctl_sched_min_granularity *= factor;
5389 if (sysctl_sched_min_granularity > limit)
5390 sysctl_sched_min_granularity = limit;
5392 sysctl_sched_latency *= factor;
5393 if (sysctl_sched_latency > limit)
5394 sysctl_sched_latency = limit;
5396 sysctl_sched_wakeup_granularity *= factor;
5397 sysctl_sched_batch_wakeup_granularity *= factor;
5402 * This is how migration works:
5404 * 1) we queue a struct migration_req structure in the source CPU's
5405 * runqueue and wake up that CPU's migration thread.
5406 * 2) we down() the locked semaphore => thread blocks.
5407 * 3) migration thread wakes up (implicitly it forces the migrated
5408 * thread off the CPU)
5409 * 4) it gets the migration request and checks whether the migrated
5410 * task is still in the wrong runqueue.
5411 * 5) if it's in the wrong runqueue then the migration thread removes
5412 * it and puts it into the right queue.
5413 * 6) migration thread up()s the semaphore.
5414 * 7) we wake up and the migration is done.
5418 * Change a given task's CPU affinity. Migrate the thread to a
5419 * proper CPU and schedule it away if the CPU it's executing on
5420 * is removed from the allowed bitmask.
5422 * NOTE: the caller must have a valid reference to the task, the
5423 * task must not exit() & deallocate itself prematurely. The
5424 * call is not atomic; no spinlocks may be held.
5426 int set_cpus_allowed(struct task_struct *p, cpumask_t new_mask)
5428 struct migration_req req;
5429 unsigned long flags;
5433 rq = task_rq_lock(p, &flags);
5434 if (!cpus_intersects(new_mask, cpu_online_map)) {
5439 if (p->sched_class->set_cpus_allowed)
5440 p->sched_class->set_cpus_allowed(p, &new_mask);
5442 p->cpus_allowed = new_mask;
5443 p->rt.nr_cpus_allowed = cpus_weight(new_mask);
5446 /* Can the task run on the task's current CPU? If so, we're done */
5447 if (cpu_isset(task_cpu(p), new_mask))
5450 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
5451 /* Need help from migration thread: drop lock and wait. */
5452 task_rq_unlock(rq, &flags);
5453 wake_up_process(rq->migration_thread);
5454 wait_for_completion(&req.done);
5455 tlb_migrate_finish(p->mm);
5459 task_rq_unlock(rq, &flags);
5463 EXPORT_SYMBOL_GPL(set_cpus_allowed);
5466 * Move (not current) task off this cpu, onto dest cpu. We're doing
5467 * this because either it can't run here any more (set_cpus_allowed()
5468 * away from this CPU, or CPU going down), or because we're
5469 * attempting to rebalance this task on exec (sched_exec).
5471 * So we race with normal scheduler movements, but that's OK, as long
5472 * as the task is no longer on this CPU.
5474 * Returns non-zero if task was successfully migrated.
5476 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
5478 struct rq *rq_dest, *rq_src;
5481 if (unlikely(cpu_is_offline(dest_cpu)))
5484 rq_src = cpu_rq(src_cpu);
5485 rq_dest = cpu_rq(dest_cpu);
5487 double_rq_lock(rq_src, rq_dest);
5488 /* Already moved. */
5489 if (task_cpu(p) != src_cpu)
5491 /* Affinity changed (again). */
5492 if (!cpu_isset(dest_cpu, p->cpus_allowed))
5495 on_rq = p->se.on_rq;
5497 deactivate_task(rq_src, p, 0);
5499 set_task_cpu(p, dest_cpu);
5501 activate_task(rq_dest, p, 0);
5502 check_preempt_curr(rq_dest, p);
5506 double_rq_unlock(rq_src, rq_dest);
5511 * migration_thread - this is a highprio system thread that performs
5512 * thread migration by bumping thread off CPU then 'pushing' onto
5515 static int migration_thread(void *data)
5517 int cpu = (long)data;
5521 BUG_ON(rq->migration_thread != current);
5523 set_current_state(TASK_INTERRUPTIBLE);
5524 while (!kthread_should_stop()) {
5525 struct migration_req *req;
5526 struct list_head *head;
5528 spin_lock_irq(&rq->lock);
5530 if (cpu_is_offline(cpu)) {
5531 spin_unlock_irq(&rq->lock);
5535 if (rq->active_balance) {
5536 active_load_balance(rq, cpu);
5537 rq->active_balance = 0;
5540 head = &rq->migration_queue;
5542 if (list_empty(head)) {
5543 spin_unlock_irq(&rq->lock);
5545 set_current_state(TASK_INTERRUPTIBLE);
5548 req = list_entry(head->next, struct migration_req, list);
5549 list_del_init(head->next);
5551 spin_unlock(&rq->lock);
5552 __migrate_task(req->task, cpu, req->dest_cpu);
5555 complete(&req->done);
5557 __set_current_state(TASK_RUNNING);
5561 /* Wait for kthread_stop */
5562 set_current_state(TASK_INTERRUPTIBLE);
5563 while (!kthread_should_stop()) {
5565 set_current_state(TASK_INTERRUPTIBLE);
5567 __set_current_state(TASK_RUNNING);
5571 #ifdef CONFIG_HOTPLUG_CPU
5573 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
5577 local_irq_disable();
5578 ret = __migrate_task(p, src_cpu, dest_cpu);
5584 * Figure out where task on dead CPU should go, use force if necessary.
5585 * NOTE: interrupts should be disabled by the caller
5587 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
5589 unsigned long flags;
5596 mask = node_to_cpumask(cpu_to_node(dead_cpu));
5597 cpus_and(mask, mask, p->cpus_allowed);
5598 dest_cpu = any_online_cpu(mask);
5600 /* On any allowed CPU? */
5601 if (dest_cpu == NR_CPUS)
5602 dest_cpu = any_online_cpu(p->cpus_allowed);
5604 /* No more Mr. Nice Guy. */
5605 if (dest_cpu == NR_CPUS) {
5606 cpumask_t cpus_allowed = cpuset_cpus_allowed_locked(p);
5608 * Try to stay on the same cpuset, where the
5609 * current cpuset may be a subset of all cpus.
5610 * The cpuset_cpus_allowed_locked() variant of
5611 * cpuset_cpus_allowed() will not block. It must be
5612 * called within calls to cpuset_lock/cpuset_unlock.
5614 rq = task_rq_lock(p, &flags);
5615 p->cpus_allowed = cpus_allowed;
5616 dest_cpu = any_online_cpu(p->cpus_allowed);
5617 task_rq_unlock(rq, &flags);
5620 * Don't tell them about moving exiting tasks or
5621 * kernel threads (both mm NULL), since they never
5624 if (p->mm && printk_ratelimit()) {
5625 printk(KERN_INFO "process %d (%s) no "
5626 "longer affine to cpu%d\n",
5627 task_pid_nr(p), p->comm, dead_cpu);
5630 } while (!__migrate_task_irq(p, dead_cpu, dest_cpu));
5634 * While a dead CPU has no uninterruptible tasks queued at this point,
5635 * it might still have a nonzero ->nr_uninterruptible counter, because
5636 * for performance reasons the counter is not stricly tracking tasks to
5637 * their home CPUs. So we just add the counter to another CPU's counter,
5638 * to keep the global sum constant after CPU-down:
5640 static void migrate_nr_uninterruptible(struct rq *rq_src)
5642 struct rq *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
5643 unsigned long flags;
5645 local_irq_save(flags);
5646 double_rq_lock(rq_src, rq_dest);
5647 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5648 rq_src->nr_uninterruptible = 0;
5649 double_rq_unlock(rq_src, rq_dest);
5650 local_irq_restore(flags);
5653 /* Run through task list and migrate tasks from the dead cpu. */
5654 static void migrate_live_tasks(int src_cpu)
5656 struct task_struct *p, *t;
5658 read_lock(&tasklist_lock);
5660 do_each_thread(t, p) {
5664 if (task_cpu(p) == src_cpu)
5665 move_task_off_dead_cpu(src_cpu, p);
5666 } while_each_thread(t, p);
5668 read_unlock(&tasklist_lock);
5672 * Schedules idle task to be the next runnable task on current CPU.
5673 * It does so by boosting its priority to highest possible.
5674 * Used by CPU offline code.
5676 void sched_idle_next(void)
5678 int this_cpu = smp_processor_id();
5679 struct rq *rq = cpu_rq(this_cpu);
5680 struct task_struct *p = rq->idle;
5681 unsigned long flags;
5683 /* cpu has to be offline */
5684 BUG_ON(cpu_online(this_cpu));
5687 * Strictly not necessary since rest of the CPUs are stopped by now
5688 * and interrupts disabled on the current cpu.
5690 spin_lock_irqsave(&rq->lock, flags);
5692 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
5694 update_rq_clock(rq);
5695 activate_task(rq, p, 0);
5697 spin_unlock_irqrestore(&rq->lock, flags);
5701 * Ensures that the idle task is using init_mm right before its cpu goes
5704 void idle_task_exit(void)
5706 struct mm_struct *mm = current->active_mm;
5708 BUG_ON(cpu_online(smp_processor_id()));
5711 switch_mm(mm, &init_mm, current);
5715 /* called under rq->lock with disabled interrupts */
5716 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
5718 struct rq *rq = cpu_rq(dead_cpu);
5720 /* Must be exiting, otherwise would be on tasklist. */
5721 BUG_ON(!p->exit_state);
5723 /* Cannot have done final schedule yet: would have vanished. */
5724 BUG_ON(p->state == TASK_DEAD);
5729 * Drop lock around migration; if someone else moves it,
5730 * that's OK. No task can be added to this CPU, so iteration is
5733 spin_unlock_irq(&rq->lock);
5734 move_task_off_dead_cpu(dead_cpu, p);
5735 spin_lock_irq(&rq->lock);
5740 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5741 static void migrate_dead_tasks(unsigned int dead_cpu)
5743 struct rq *rq = cpu_rq(dead_cpu);
5744 struct task_struct *next;
5747 if (!rq->nr_running)
5749 update_rq_clock(rq);
5750 next = pick_next_task(rq, rq->curr);
5753 migrate_dead(dead_cpu, next);
5757 #endif /* CONFIG_HOTPLUG_CPU */
5759 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5761 static struct ctl_table sd_ctl_dir[] = {
5763 .procname = "sched_domain",
5769 static struct ctl_table sd_ctl_root[] = {
5771 .ctl_name = CTL_KERN,
5772 .procname = "kernel",
5774 .child = sd_ctl_dir,
5779 static struct ctl_table *sd_alloc_ctl_entry(int n)
5781 struct ctl_table *entry =
5782 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
5787 static void sd_free_ctl_entry(struct ctl_table **tablep)
5789 struct ctl_table *entry;
5792 * In the intermediate directories, both the child directory and
5793 * procname are dynamically allocated and could fail but the mode
5794 * will always be set. In the lowest directory the names are
5795 * static strings and all have proc handlers.
5797 for (entry = *tablep; entry->mode; entry++) {
5799 sd_free_ctl_entry(&entry->child);
5800 if (entry->proc_handler == NULL)
5801 kfree(entry->procname);
5809 set_table_entry(struct ctl_table *entry,
5810 const char *procname, void *data, int maxlen,
5811 mode_t mode, proc_handler *proc_handler)
5813 entry->procname = procname;
5815 entry->maxlen = maxlen;
5817 entry->proc_handler = proc_handler;
5820 static struct ctl_table *
5821 sd_alloc_ctl_domain_table(struct sched_domain *sd)
5823 struct ctl_table *table = sd_alloc_ctl_entry(12);
5828 set_table_entry(&table[0], "min_interval", &sd->min_interval,
5829 sizeof(long), 0644, proc_doulongvec_minmax);
5830 set_table_entry(&table[1], "max_interval", &sd->max_interval,
5831 sizeof(long), 0644, proc_doulongvec_minmax);
5832 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
5833 sizeof(int), 0644, proc_dointvec_minmax);
5834 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
5835 sizeof(int), 0644, proc_dointvec_minmax);
5836 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
5837 sizeof(int), 0644, proc_dointvec_minmax);
5838 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
5839 sizeof(int), 0644, proc_dointvec_minmax);
5840 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
5841 sizeof(int), 0644, proc_dointvec_minmax);
5842 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
5843 sizeof(int), 0644, proc_dointvec_minmax);
5844 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
5845 sizeof(int), 0644, proc_dointvec_minmax);
5846 set_table_entry(&table[9], "cache_nice_tries",
5847 &sd->cache_nice_tries,
5848 sizeof(int), 0644, proc_dointvec_minmax);
5849 set_table_entry(&table[10], "flags", &sd->flags,
5850 sizeof(int), 0644, proc_dointvec_minmax);
5851 /* &table[11] is terminator */
5856 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
5858 struct ctl_table *entry, *table;
5859 struct sched_domain *sd;
5860 int domain_num = 0, i;
5863 for_each_domain(cpu, sd)
5865 entry = table = sd_alloc_ctl_entry(domain_num + 1);
5870 for_each_domain(cpu, sd) {
5871 snprintf(buf, 32, "domain%d", i);
5872 entry->procname = kstrdup(buf, GFP_KERNEL);
5874 entry->child = sd_alloc_ctl_domain_table(sd);
5881 static struct ctl_table_header *sd_sysctl_header;
5882 static void register_sched_domain_sysctl(void)
5884 int i, cpu_num = num_online_cpus();
5885 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5888 WARN_ON(sd_ctl_dir[0].child);
5889 sd_ctl_dir[0].child = entry;
5894 for_each_online_cpu(i) {
5895 snprintf(buf, 32, "cpu%d", i);
5896 entry->procname = kstrdup(buf, GFP_KERNEL);
5898 entry->child = sd_alloc_ctl_cpu_table(i);
5902 WARN_ON(sd_sysctl_header);
5903 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
5906 /* may be called multiple times per register */
5907 static void unregister_sched_domain_sysctl(void)
5909 if (sd_sysctl_header)
5910 unregister_sysctl_table(sd_sysctl_header);
5911 sd_sysctl_header = NULL;
5912 if (sd_ctl_dir[0].child)
5913 sd_free_ctl_entry(&sd_ctl_dir[0].child);
5916 static void register_sched_domain_sysctl(void)
5919 static void unregister_sched_domain_sysctl(void)
5925 * migration_call - callback that gets triggered when a CPU is added.
5926 * Here we can start up the necessary migration thread for the new CPU.
5928 static int __cpuinit
5929 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
5931 struct task_struct *p;
5932 int cpu = (long)hcpu;
5933 unsigned long flags;
5938 case CPU_UP_PREPARE:
5939 case CPU_UP_PREPARE_FROZEN:
5940 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
5943 kthread_bind(p, cpu);
5944 /* Must be high prio: stop_machine expects to yield to it. */
5945 rq = task_rq_lock(p, &flags);
5946 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
5947 task_rq_unlock(rq, &flags);
5948 cpu_rq(cpu)->migration_thread = p;
5952 case CPU_ONLINE_FROZEN:
5953 /* Strictly unnecessary, as first user will wake it. */
5954 wake_up_process(cpu_rq(cpu)->migration_thread);
5956 /* Update our root-domain */
5958 spin_lock_irqsave(&rq->lock, flags);
5960 BUG_ON(!cpu_isset(cpu, rq->rd->span));
5961 cpu_set(cpu, rq->rd->online);
5963 spin_unlock_irqrestore(&rq->lock, flags);
5966 #ifdef CONFIG_HOTPLUG_CPU
5967 case CPU_UP_CANCELED:
5968 case CPU_UP_CANCELED_FROZEN:
5969 if (!cpu_rq(cpu)->migration_thread)
5971 /* Unbind it from offline cpu so it can run. Fall thru. */
5972 kthread_bind(cpu_rq(cpu)->migration_thread,
5973 any_online_cpu(cpu_online_map));
5974 kthread_stop(cpu_rq(cpu)->migration_thread);
5975 cpu_rq(cpu)->migration_thread = NULL;
5979 case CPU_DEAD_FROZEN:
5980 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
5981 migrate_live_tasks(cpu);
5983 kthread_stop(rq->migration_thread);
5984 rq->migration_thread = NULL;
5985 /* Idle task back to normal (off runqueue, low prio) */
5986 spin_lock_irq(&rq->lock);
5987 update_rq_clock(rq);
5988 deactivate_task(rq, rq->idle, 0);
5989 rq->idle->static_prio = MAX_PRIO;
5990 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
5991 rq->idle->sched_class = &idle_sched_class;
5992 migrate_dead_tasks(cpu);
5993 spin_unlock_irq(&rq->lock);
5995 migrate_nr_uninterruptible(rq);
5996 BUG_ON(rq->nr_running != 0);
5999 * No need to migrate the tasks: it was best-effort if
6000 * they didn't take sched_hotcpu_mutex. Just wake up
6003 spin_lock_irq(&rq->lock);
6004 while (!list_empty(&rq->migration_queue)) {
6005 struct migration_req *req;
6007 req = list_entry(rq->migration_queue.next,
6008 struct migration_req, list);
6009 list_del_init(&req->list);
6010 complete(&req->done);
6012 spin_unlock_irq(&rq->lock);
6016 case CPU_DYING_FROZEN:
6017 /* Update our root-domain */
6019 spin_lock_irqsave(&rq->lock, flags);
6021 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6022 cpu_clear(cpu, rq->rd->online);
6024 spin_unlock_irqrestore(&rq->lock, flags);
6031 /* Register at highest priority so that task migration (migrate_all_tasks)
6032 * happens before everything else.
6034 static struct notifier_block __cpuinitdata migration_notifier = {
6035 .notifier_call = migration_call,
6039 void __init migration_init(void)
6041 void *cpu = (void *)(long)smp_processor_id();
6044 /* Start one for the boot CPU: */
6045 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
6046 BUG_ON(err == NOTIFY_BAD);
6047 migration_call(&migration_notifier, CPU_ONLINE, cpu);
6048 register_cpu_notifier(&migration_notifier);
6054 /* Number of possible processor ids */
6055 int nr_cpu_ids __read_mostly = NR_CPUS;
6056 EXPORT_SYMBOL(nr_cpu_ids);
6058 #ifdef CONFIG_SCHED_DEBUG
6060 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level)
6062 struct sched_group *group = sd->groups;
6063 cpumask_t groupmask;
6066 cpumask_scnprintf(str, NR_CPUS, sd->span);
6067 cpus_clear(groupmask);
6069 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6071 if (!(sd->flags & SD_LOAD_BALANCE)) {
6072 printk("does not load-balance\n");
6074 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6079 printk(KERN_CONT "span %s\n", str);
6081 if (!cpu_isset(cpu, sd->span)) {
6082 printk(KERN_ERR "ERROR: domain->span does not contain "
6085 if (!cpu_isset(cpu, group->cpumask)) {
6086 printk(KERN_ERR "ERROR: domain->groups does not contain"
6090 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6094 printk(KERN_ERR "ERROR: group is NULL\n");
6098 if (!group->__cpu_power) {
6099 printk(KERN_CONT "\n");
6100 printk(KERN_ERR "ERROR: domain->cpu_power not "
6105 if (!cpus_weight(group->cpumask)) {
6106 printk(KERN_CONT "\n");
6107 printk(KERN_ERR "ERROR: empty group\n");
6111 if (cpus_intersects(groupmask, group->cpumask)) {
6112 printk(KERN_CONT "\n");
6113 printk(KERN_ERR "ERROR: repeated CPUs\n");
6117 cpus_or(groupmask, groupmask, group->cpumask);
6119 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
6120 printk(KERN_CONT " %s", str);
6122 group = group->next;
6123 } while (group != sd->groups);
6124 printk(KERN_CONT "\n");
6126 if (!cpus_equal(sd->span, groupmask))
6127 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6129 if (sd->parent && !cpus_subset(groupmask, sd->parent->span))
6130 printk(KERN_ERR "ERROR: parent span is not a superset "
6131 "of domain->span\n");
6135 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6140 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6144 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6147 if (sched_domain_debug_one(sd, cpu, level))
6156 # define sched_domain_debug(sd, cpu) do { } while (0)
6159 static int sd_degenerate(struct sched_domain *sd)
6161 if (cpus_weight(sd->span) == 1)
6164 /* Following flags need at least 2 groups */
6165 if (sd->flags & (SD_LOAD_BALANCE |
6166 SD_BALANCE_NEWIDLE |
6170 SD_SHARE_PKG_RESOURCES)) {
6171 if (sd->groups != sd->groups->next)
6175 /* Following flags don't use groups */
6176 if (sd->flags & (SD_WAKE_IDLE |
6185 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6187 unsigned long cflags = sd->flags, pflags = parent->flags;
6189 if (sd_degenerate(parent))
6192 if (!cpus_equal(sd->span, parent->span))
6195 /* Does parent contain flags not in child? */
6196 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6197 if (cflags & SD_WAKE_AFFINE)
6198 pflags &= ~SD_WAKE_BALANCE;
6199 /* Flags needing groups don't count if only 1 group in parent */
6200 if (parent->groups == parent->groups->next) {
6201 pflags &= ~(SD_LOAD_BALANCE |
6202 SD_BALANCE_NEWIDLE |
6206 SD_SHARE_PKG_RESOURCES);
6208 if (~cflags & pflags)
6214 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6216 unsigned long flags;
6217 const struct sched_class *class;
6219 spin_lock_irqsave(&rq->lock, flags);
6222 struct root_domain *old_rd = rq->rd;
6224 for (class = sched_class_highest; class; class = class->next) {
6225 if (class->leave_domain)
6226 class->leave_domain(rq);
6229 cpu_clear(rq->cpu, old_rd->span);
6230 cpu_clear(rq->cpu, old_rd->online);
6232 if (atomic_dec_and_test(&old_rd->refcount))
6236 atomic_inc(&rd->refcount);
6239 cpu_set(rq->cpu, rd->span);
6240 if (cpu_isset(rq->cpu, cpu_online_map))
6241 cpu_set(rq->cpu, rd->online);
6243 for (class = sched_class_highest; class; class = class->next) {
6244 if (class->join_domain)
6245 class->join_domain(rq);
6248 spin_unlock_irqrestore(&rq->lock, flags);
6251 static void init_rootdomain(struct root_domain *rd)
6253 memset(rd, 0, sizeof(*rd));
6255 cpus_clear(rd->span);
6256 cpus_clear(rd->online);
6259 static void init_defrootdomain(void)
6261 init_rootdomain(&def_root_domain);
6262 atomic_set(&def_root_domain.refcount, 1);
6265 static struct root_domain *alloc_rootdomain(void)
6267 struct root_domain *rd;
6269 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6273 init_rootdomain(rd);
6279 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6280 * hold the hotplug lock.
6283 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6285 struct rq *rq = cpu_rq(cpu);
6286 struct sched_domain *tmp;
6288 /* Remove the sched domains which do not contribute to scheduling. */
6289 for (tmp = sd; tmp; tmp = tmp->parent) {
6290 struct sched_domain *parent = tmp->parent;
6293 if (sd_parent_degenerate(tmp, parent)) {
6294 tmp->parent = parent->parent;
6296 parent->parent->child = tmp;
6300 if (sd && sd_degenerate(sd)) {
6306 sched_domain_debug(sd, cpu);
6308 rq_attach_root(rq, rd);
6309 rcu_assign_pointer(rq->sd, sd);
6312 /* cpus with isolated domains */
6313 static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
6315 /* Setup the mask of cpus configured for isolated domains */
6316 static int __init isolated_cpu_setup(char *str)
6318 int ints[NR_CPUS], i;
6320 str = get_options(str, ARRAY_SIZE(ints), ints);
6321 cpus_clear(cpu_isolated_map);
6322 for (i = 1; i <= ints[0]; i++)
6323 if (ints[i] < NR_CPUS)
6324 cpu_set(ints[i], cpu_isolated_map);
6328 __setup("isolcpus=", isolated_cpu_setup);
6331 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6332 * to a function which identifies what group(along with sched group) a CPU
6333 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6334 * (due to the fact that we keep track of groups covered with a cpumask_t).
6336 * init_sched_build_groups will build a circular linked list of the groups
6337 * covered by the given span, and will set each group's ->cpumask correctly,
6338 * and ->cpu_power to 0.
6341 init_sched_build_groups(cpumask_t span, const cpumask_t *cpu_map,
6342 int (*group_fn)(int cpu, const cpumask_t *cpu_map,
6343 struct sched_group **sg))
6345 struct sched_group *first = NULL, *last = NULL;
6346 cpumask_t covered = CPU_MASK_NONE;
6349 for_each_cpu_mask(i, span) {
6350 struct sched_group *sg;
6351 int group = group_fn(i, cpu_map, &sg);
6354 if (cpu_isset(i, covered))
6357 sg->cpumask = CPU_MASK_NONE;
6358 sg->__cpu_power = 0;
6360 for_each_cpu_mask(j, span) {
6361 if (group_fn(j, cpu_map, NULL) != group)
6364 cpu_set(j, covered);
6365 cpu_set(j, sg->cpumask);
6376 #define SD_NODES_PER_DOMAIN 16
6381 * find_next_best_node - find the next node to include in a sched_domain
6382 * @node: node whose sched_domain we're building
6383 * @used_nodes: nodes already in the sched_domain
6385 * Find the next node to include in a given scheduling domain. Simply
6386 * finds the closest node not already in the @used_nodes map.
6388 * Should use nodemask_t.
6390 static int find_next_best_node(int node, unsigned long *used_nodes)
6392 int i, n, val, min_val, best_node = 0;
6396 for (i = 0; i < MAX_NUMNODES; i++) {
6397 /* Start at @node */
6398 n = (node + i) % MAX_NUMNODES;
6400 if (!nr_cpus_node(n))
6403 /* Skip already used nodes */
6404 if (test_bit(n, used_nodes))
6407 /* Simple min distance search */
6408 val = node_distance(node, n);
6410 if (val < min_val) {
6416 set_bit(best_node, used_nodes);
6421 * sched_domain_node_span - get a cpumask for a node's sched_domain
6422 * @node: node whose cpumask we're constructing
6423 * @size: number of nodes to include in this span
6425 * Given a node, construct a good cpumask for its sched_domain to span. It
6426 * should be one that prevents unnecessary balancing, but also spreads tasks
6429 static cpumask_t sched_domain_node_span(int node)
6431 DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
6432 cpumask_t span, nodemask;
6436 bitmap_zero(used_nodes, MAX_NUMNODES);
6438 nodemask = node_to_cpumask(node);
6439 cpus_or(span, span, nodemask);
6440 set_bit(node, used_nodes);
6442 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
6443 int next_node = find_next_best_node(node, used_nodes);
6445 nodemask = node_to_cpumask(next_node);
6446 cpus_or(span, span, nodemask);
6453 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6456 * SMT sched-domains:
6458 #ifdef CONFIG_SCHED_SMT
6459 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
6460 static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
6463 cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6466 *sg = &per_cpu(sched_group_cpus, cpu);
6472 * multi-core sched-domains:
6474 #ifdef CONFIG_SCHED_MC
6475 static DEFINE_PER_CPU(struct sched_domain, core_domains);
6476 static DEFINE_PER_CPU(struct sched_group, sched_group_core);
6479 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6481 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6484 cpumask_t mask = per_cpu(cpu_sibling_map, cpu);
6485 cpus_and(mask, mask, *cpu_map);
6486 group = first_cpu(mask);
6488 *sg = &per_cpu(sched_group_core, group);
6491 #elif defined(CONFIG_SCHED_MC)
6493 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6496 *sg = &per_cpu(sched_group_core, cpu);
6501 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
6502 static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
6505 cpu_to_phys_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6508 #ifdef CONFIG_SCHED_MC
6509 cpumask_t mask = cpu_coregroup_map(cpu);
6510 cpus_and(mask, mask, *cpu_map);
6511 group = first_cpu(mask);
6512 #elif defined(CONFIG_SCHED_SMT)
6513 cpumask_t mask = per_cpu(cpu_sibling_map, cpu);
6514 cpus_and(mask, mask, *cpu_map);
6515 group = first_cpu(mask);
6520 *sg = &per_cpu(sched_group_phys, group);
6526 * The init_sched_build_groups can't handle what we want to do with node
6527 * groups, so roll our own. Now each node has its own list of groups which
6528 * gets dynamically allocated.
6530 static DEFINE_PER_CPU(struct sched_domain, node_domains);
6531 static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
6533 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
6534 static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
6536 static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
6537 struct sched_group **sg)
6539 cpumask_t nodemask = node_to_cpumask(cpu_to_node(cpu));
6542 cpus_and(nodemask, nodemask, *cpu_map);
6543 group = first_cpu(nodemask);
6546 *sg = &per_cpu(sched_group_allnodes, group);
6550 static void init_numa_sched_groups_power(struct sched_group *group_head)
6552 struct sched_group *sg = group_head;
6558 for_each_cpu_mask(j, sg->cpumask) {
6559 struct sched_domain *sd;
6561 sd = &per_cpu(phys_domains, j);
6562 if (j != first_cpu(sd->groups->cpumask)) {
6564 * Only add "power" once for each
6570 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
6573 } while (sg != group_head);
6578 /* Free memory allocated for various sched_group structures */
6579 static void free_sched_groups(const cpumask_t *cpu_map)
6583 for_each_cpu_mask(cpu, *cpu_map) {
6584 struct sched_group **sched_group_nodes
6585 = sched_group_nodes_bycpu[cpu];
6587 if (!sched_group_nodes)
6590 for (i = 0; i < MAX_NUMNODES; i++) {
6591 cpumask_t nodemask = node_to_cpumask(i);
6592 struct sched_group *oldsg, *sg = sched_group_nodes[i];
6594 cpus_and(nodemask, nodemask, *cpu_map);
6595 if (cpus_empty(nodemask))
6605 if (oldsg != sched_group_nodes[i])
6608 kfree(sched_group_nodes);
6609 sched_group_nodes_bycpu[cpu] = NULL;
6613 static void free_sched_groups(const cpumask_t *cpu_map)
6619 * Initialize sched groups cpu_power.
6621 * cpu_power indicates the capacity of sched group, which is used while
6622 * distributing the load between different sched groups in a sched domain.
6623 * Typically cpu_power for all the groups in a sched domain will be same unless
6624 * there are asymmetries in the topology. If there are asymmetries, group
6625 * having more cpu_power will pickup more load compared to the group having
6628 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
6629 * the maximum number of tasks a group can handle in the presence of other idle
6630 * or lightly loaded groups in the same sched domain.
6632 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
6634 struct sched_domain *child;
6635 struct sched_group *group;
6637 WARN_ON(!sd || !sd->groups);
6639 if (cpu != first_cpu(sd->groups->cpumask))
6644 sd->groups->__cpu_power = 0;
6647 * For perf policy, if the groups in child domain share resources
6648 * (for example cores sharing some portions of the cache hierarchy
6649 * or SMT), then set this domain groups cpu_power such that each group
6650 * can handle only one task, when there are other idle groups in the
6651 * same sched domain.
6653 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
6655 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
6656 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
6661 * add cpu_power of each child group to this groups cpu_power
6663 group = child->groups;
6665 sg_inc_cpu_power(sd->groups, group->__cpu_power);
6666 group = group->next;
6667 } while (group != child->groups);
6671 * Build sched domains for a given set of cpus and attach the sched domains
6672 * to the individual cpus
6674 static int build_sched_domains(const cpumask_t *cpu_map)
6677 struct root_domain *rd;
6679 struct sched_group **sched_group_nodes = NULL;
6680 int sd_allnodes = 0;
6683 * Allocate the per-node list of sched groups
6685 sched_group_nodes = kcalloc(MAX_NUMNODES, sizeof(struct sched_group *),
6687 if (!sched_group_nodes) {
6688 printk(KERN_WARNING "Can not alloc sched group node list\n");
6691 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
6694 rd = alloc_rootdomain();
6696 printk(KERN_WARNING "Cannot alloc root domain\n");
6701 * Set up domains for cpus specified by the cpu_map.
6703 for_each_cpu_mask(i, *cpu_map) {
6704 struct sched_domain *sd = NULL, *p;
6705 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
6707 cpus_and(nodemask, nodemask, *cpu_map);
6710 if (cpus_weight(*cpu_map) >
6711 SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
6712 sd = &per_cpu(allnodes_domains, i);
6713 *sd = SD_ALLNODES_INIT;
6714 sd->span = *cpu_map;
6715 cpu_to_allnodes_group(i, cpu_map, &sd->groups);
6721 sd = &per_cpu(node_domains, i);
6723 sd->span = sched_domain_node_span(cpu_to_node(i));
6727 cpus_and(sd->span, sd->span, *cpu_map);
6731 sd = &per_cpu(phys_domains, i);
6733 sd->span = nodemask;
6737 cpu_to_phys_group(i, cpu_map, &sd->groups);
6739 #ifdef CONFIG_SCHED_MC
6741 sd = &per_cpu(core_domains, i);
6743 sd->span = cpu_coregroup_map(i);
6744 cpus_and(sd->span, sd->span, *cpu_map);
6747 cpu_to_core_group(i, cpu_map, &sd->groups);
6750 #ifdef CONFIG_SCHED_SMT
6752 sd = &per_cpu(cpu_domains, i);
6753 *sd = SD_SIBLING_INIT;
6754 sd->span = per_cpu(cpu_sibling_map, i);
6755 cpus_and(sd->span, sd->span, *cpu_map);
6758 cpu_to_cpu_group(i, cpu_map, &sd->groups);
6762 #ifdef CONFIG_SCHED_SMT
6763 /* Set up CPU (sibling) groups */
6764 for_each_cpu_mask(i, *cpu_map) {
6765 cpumask_t this_sibling_map = per_cpu(cpu_sibling_map, i);
6766 cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
6767 if (i != first_cpu(this_sibling_map))
6770 init_sched_build_groups(this_sibling_map, cpu_map,
6775 #ifdef CONFIG_SCHED_MC
6776 /* Set up multi-core groups */
6777 for_each_cpu_mask(i, *cpu_map) {
6778 cpumask_t this_core_map = cpu_coregroup_map(i);
6779 cpus_and(this_core_map, this_core_map, *cpu_map);
6780 if (i != first_cpu(this_core_map))
6782 init_sched_build_groups(this_core_map, cpu_map,
6783 &cpu_to_core_group);
6787 /* Set up physical groups */
6788 for (i = 0; i < MAX_NUMNODES; i++) {
6789 cpumask_t nodemask = node_to_cpumask(i);
6791 cpus_and(nodemask, nodemask, *cpu_map);
6792 if (cpus_empty(nodemask))
6795 init_sched_build_groups(nodemask, cpu_map, &cpu_to_phys_group);
6799 /* Set up node groups */
6801 init_sched_build_groups(*cpu_map, cpu_map,
6802 &cpu_to_allnodes_group);
6804 for (i = 0; i < MAX_NUMNODES; i++) {
6805 /* Set up node groups */
6806 struct sched_group *sg, *prev;
6807 cpumask_t nodemask = node_to_cpumask(i);
6808 cpumask_t domainspan;
6809 cpumask_t covered = CPU_MASK_NONE;
6812 cpus_and(nodemask, nodemask, *cpu_map);
6813 if (cpus_empty(nodemask)) {
6814 sched_group_nodes[i] = NULL;
6818 domainspan = sched_domain_node_span(i);
6819 cpus_and(domainspan, domainspan, *cpu_map);
6821 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
6823 printk(KERN_WARNING "Can not alloc domain group for "
6827 sched_group_nodes[i] = sg;
6828 for_each_cpu_mask(j, nodemask) {
6829 struct sched_domain *sd;
6831 sd = &per_cpu(node_domains, j);
6834 sg->__cpu_power = 0;
6835 sg->cpumask = nodemask;
6837 cpus_or(covered, covered, nodemask);
6840 for (j = 0; j < MAX_NUMNODES; j++) {
6841 cpumask_t tmp, notcovered;
6842 int n = (i + j) % MAX_NUMNODES;
6844 cpus_complement(notcovered, covered);
6845 cpus_and(tmp, notcovered, *cpu_map);
6846 cpus_and(tmp, tmp, domainspan);
6847 if (cpus_empty(tmp))
6850 nodemask = node_to_cpumask(n);
6851 cpus_and(tmp, tmp, nodemask);
6852 if (cpus_empty(tmp))
6855 sg = kmalloc_node(sizeof(struct sched_group),
6859 "Can not alloc domain group for node %d\n", j);
6862 sg->__cpu_power = 0;
6864 sg->next = prev->next;
6865 cpus_or(covered, covered, tmp);
6872 /* Calculate CPU power for physical packages and nodes */
6873 #ifdef CONFIG_SCHED_SMT
6874 for_each_cpu_mask(i, *cpu_map) {
6875 struct sched_domain *sd = &per_cpu(cpu_domains, i);
6877 init_sched_groups_power(i, sd);
6880 #ifdef CONFIG_SCHED_MC
6881 for_each_cpu_mask(i, *cpu_map) {
6882 struct sched_domain *sd = &per_cpu(core_domains, i);
6884 init_sched_groups_power(i, sd);
6888 for_each_cpu_mask(i, *cpu_map) {
6889 struct sched_domain *sd = &per_cpu(phys_domains, i);
6891 init_sched_groups_power(i, sd);
6895 for (i = 0; i < MAX_NUMNODES; i++)
6896 init_numa_sched_groups_power(sched_group_nodes[i]);
6899 struct sched_group *sg;
6901 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg);
6902 init_numa_sched_groups_power(sg);
6906 /* Attach the domains */
6907 for_each_cpu_mask(i, *cpu_map) {
6908 struct sched_domain *sd;
6909 #ifdef CONFIG_SCHED_SMT
6910 sd = &per_cpu(cpu_domains, i);
6911 #elif defined(CONFIG_SCHED_MC)
6912 sd = &per_cpu(core_domains, i);
6914 sd = &per_cpu(phys_domains, i);
6916 cpu_attach_domain(sd, rd, i);
6923 free_sched_groups(cpu_map);
6928 static cpumask_t *doms_cur; /* current sched domains */
6929 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
6932 * Special case: If a kmalloc of a doms_cur partition (array of
6933 * cpumask_t) fails, then fallback to a single sched domain,
6934 * as determined by the single cpumask_t fallback_doms.
6936 static cpumask_t fallback_doms;
6938 void __attribute__((weak)) arch_update_cpu_topology(void)
6943 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6944 * For now this just excludes isolated cpus, but could be used to
6945 * exclude other special cases in the future.
6947 static int arch_init_sched_domains(const cpumask_t *cpu_map)
6951 arch_update_cpu_topology();
6953 doms_cur = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
6955 doms_cur = &fallback_doms;
6956 cpus_andnot(*doms_cur, *cpu_map, cpu_isolated_map);
6957 err = build_sched_domains(doms_cur);
6958 register_sched_domain_sysctl();
6963 static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
6965 free_sched_groups(cpu_map);
6969 * Detach sched domains from a group of cpus specified in cpu_map
6970 * These cpus will now be attached to the NULL domain
6972 static void detach_destroy_domains(const cpumask_t *cpu_map)
6976 unregister_sched_domain_sysctl();
6978 for_each_cpu_mask(i, *cpu_map)
6979 cpu_attach_domain(NULL, &def_root_domain, i);
6980 synchronize_sched();
6981 arch_destroy_sched_domains(cpu_map);
6985 * Partition sched domains as specified by the 'ndoms_new'
6986 * cpumasks in the array doms_new[] of cpumasks. This compares
6987 * doms_new[] to the current sched domain partitioning, doms_cur[].
6988 * It destroys each deleted domain and builds each new domain.
6990 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
6991 * The masks don't intersect (don't overlap.) We should setup one
6992 * sched domain for each mask. CPUs not in any of the cpumasks will
6993 * not be load balanced. If the same cpumask appears both in the
6994 * current 'doms_cur' domains and in the new 'doms_new', we can leave
6997 * The passed in 'doms_new' should be kmalloc'd. This routine takes
6998 * ownership of it and will kfree it when done with it. If the caller
6999 * failed the kmalloc call, then it can pass in doms_new == NULL,
7000 * and partition_sched_domains() will fallback to the single partition
7003 * Call with hotplug lock held
7005 void partition_sched_domains(int ndoms_new, cpumask_t *doms_new)
7011 /* always unregister in case we don't destroy any domains */
7012 unregister_sched_domain_sysctl();
7014 if (doms_new == NULL) {
7016 doms_new = &fallback_doms;
7017 cpus_andnot(doms_new[0], cpu_online_map, cpu_isolated_map);
7020 /* Destroy deleted domains */
7021 for (i = 0; i < ndoms_cur; i++) {
7022 for (j = 0; j < ndoms_new; j++) {
7023 if (cpus_equal(doms_cur[i], doms_new[j]))
7026 /* no match - a current sched domain not in new doms_new[] */
7027 detach_destroy_domains(doms_cur + i);
7032 /* Build new domains */
7033 for (i = 0; i < ndoms_new; i++) {
7034 for (j = 0; j < ndoms_cur; j++) {
7035 if (cpus_equal(doms_new[i], doms_cur[j]))
7038 /* no match - add a new doms_new */
7039 build_sched_domains(doms_new + i);
7044 /* Remember the new sched domains */
7045 if (doms_cur != &fallback_doms)
7047 doms_cur = doms_new;
7048 ndoms_cur = ndoms_new;
7050 register_sched_domain_sysctl();
7055 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7056 int arch_reinit_sched_domains(void)
7061 detach_destroy_domains(&cpu_online_map);
7062 err = arch_init_sched_domains(&cpu_online_map);
7068 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7072 if (buf[0] != '0' && buf[0] != '1')
7076 sched_smt_power_savings = (buf[0] == '1');
7078 sched_mc_power_savings = (buf[0] == '1');
7080 ret = arch_reinit_sched_domains();
7082 return ret ? ret : count;
7085 #ifdef CONFIG_SCHED_MC
7086 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
7088 return sprintf(page, "%u\n", sched_mc_power_savings);
7090 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
7091 const char *buf, size_t count)
7093 return sched_power_savings_store(buf, count, 0);
7095 static SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
7096 sched_mc_power_savings_store);
7099 #ifdef CONFIG_SCHED_SMT
7100 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
7102 return sprintf(page, "%u\n", sched_smt_power_savings);
7104 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
7105 const char *buf, size_t count)
7107 return sched_power_savings_store(buf, count, 1);
7109 static SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
7110 sched_smt_power_savings_store);
7113 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7117 #ifdef CONFIG_SCHED_SMT
7119 err = sysfs_create_file(&cls->kset.kobj,
7120 &attr_sched_smt_power_savings.attr);
7122 #ifdef CONFIG_SCHED_MC
7123 if (!err && mc_capable())
7124 err = sysfs_create_file(&cls->kset.kobj,
7125 &attr_sched_mc_power_savings.attr);
7132 * Force a reinitialization of the sched domains hierarchy. The domains
7133 * and groups cannot be updated in place without racing with the balancing
7134 * code, so we temporarily attach all running cpus to the NULL domain
7135 * which will prevent rebalancing while the sched domains are recalculated.
7137 static int update_sched_domains(struct notifier_block *nfb,
7138 unsigned long action, void *hcpu)
7141 case CPU_UP_PREPARE:
7142 case CPU_UP_PREPARE_FROZEN:
7143 case CPU_DOWN_PREPARE:
7144 case CPU_DOWN_PREPARE_FROZEN:
7145 detach_destroy_domains(&cpu_online_map);
7148 case CPU_UP_CANCELED:
7149 case CPU_UP_CANCELED_FROZEN:
7150 case CPU_DOWN_FAILED:
7151 case CPU_DOWN_FAILED_FROZEN:
7153 case CPU_ONLINE_FROZEN:
7155 case CPU_DEAD_FROZEN:
7157 * Fall through and re-initialise the domains.
7164 /* The hotplug lock is already held by cpu_up/cpu_down */
7165 arch_init_sched_domains(&cpu_online_map);
7170 void __init sched_init_smp(void)
7172 cpumask_t non_isolated_cpus;
7175 arch_init_sched_domains(&cpu_online_map);
7176 cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
7177 if (cpus_empty(non_isolated_cpus))
7178 cpu_set(smp_processor_id(), non_isolated_cpus);
7180 /* XXX: Theoretical race here - CPU may be hotplugged now */
7181 hotcpu_notifier(update_sched_domains, 0);
7183 /* Move init over to a non-isolated CPU */
7184 if (set_cpus_allowed(current, non_isolated_cpus) < 0)
7186 sched_init_granularity();
7189 void __init sched_init_smp(void)
7191 sched_init_granularity();
7193 #endif /* CONFIG_SMP */
7195 int in_sched_functions(unsigned long addr)
7197 return in_lock_functions(addr) ||
7198 (addr >= (unsigned long)__sched_text_start
7199 && addr < (unsigned long)__sched_text_end);
7202 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
7204 cfs_rq->tasks_timeline = RB_ROOT;
7205 #ifdef CONFIG_FAIR_GROUP_SCHED
7208 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7211 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
7213 struct rt_prio_array *array;
7216 array = &rt_rq->active;
7217 for (i = 0; i < MAX_RT_PRIO; i++) {
7218 INIT_LIST_HEAD(array->queue + i);
7219 __clear_bit(i, array->bitmap);
7221 /* delimiter for bitsearch: */
7222 __set_bit(MAX_RT_PRIO, array->bitmap);
7224 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
7225 rt_rq->highest_prio = MAX_RT_PRIO;
7228 rt_rq->rt_nr_migratory = 0;
7229 rt_rq->overloaded = 0;
7233 rt_rq->rt_throttled = 0;
7235 #ifdef CONFIG_RT_GROUP_SCHED
7236 rt_rq->rt_nr_boosted = 0;
7241 #ifdef CONFIG_FAIR_GROUP_SCHED
7242 static void init_tg_cfs_entry(struct rq *rq, struct task_group *tg,
7243 struct cfs_rq *cfs_rq, struct sched_entity *se,
7246 tg->cfs_rq[cpu] = cfs_rq;
7247 init_cfs_rq(cfs_rq, rq);
7250 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
7253 se->cfs_rq = &rq->cfs;
7255 se->load.weight = tg->shares;
7256 se->load.inv_weight = div64_64(1ULL<<32, se->load.weight);
7261 #ifdef CONFIG_RT_GROUP_SCHED
7262 static void init_tg_rt_entry(struct rq *rq, struct task_group *tg,
7263 struct rt_rq *rt_rq, struct sched_rt_entity *rt_se,
7266 tg->rt_rq[cpu] = rt_rq;
7267 init_rt_rq(rt_rq, rq);
7269 rt_rq->rt_se = rt_se;
7271 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
7273 tg->rt_se[cpu] = rt_se;
7274 rt_se->rt_rq = &rq->rt;
7275 rt_se->my_q = rt_rq;
7276 rt_se->parent = NULL;
7277 INIT_LIST_HEAD(&rt_se->run_list);
7281 void __init sched_init(void)
7283 int highest_cpu = 0;
7287 init_defrootdomain();
7290 #ifdef CONFIG_GROUP_SCHED
7291 list_add(&init_task_group.list, &task_groups);
7294 for_each_possible_cpu(i) {
7298 spin_lock_init(&rq->lock);
7299 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
7302 update_last_tick_seen(rq);
7303 init_cfs_rq(&rq->cfs, rq);
7304 init_rt_rq(&rq->rt, rq);
7305 #ifdef CONFIG_FAIR_GROUP_SCHED
7306 init_task_group.shares = init_task_group_load;
7307 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7308 init_tg_cfs_entry(rq, &init_task_group,
7309 &per_cpu(init_cfs_rq, i),
7310 &per_cpu(init_sched_entity, i), i, 1);
7313 #ifdef CONFIG_RT_GROUP_SCHED
7314 init_task_group.rt_runtime =
7315 sysctl_sched_rt_runtime * NSEC_PER_USEC;
7316 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
7317 init_tg_rt_entry(rq, &init_task_group,
7318 &per_cpu(init_rt_rq, i),
7319 &per_cpu(init_sched_rt_entity, i), i, 1);
7321 rq->rt_period_expire = 0;
7322 rq->rt_throttled = 0;
7324 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7325 rq->cpu_load[j] = 0;
7329 rq->active_balance = 0;
7330 rq->next_balance = jiffies;
7333 rq->migration_thread = NULL;
7334 INIT_LIST_HEAD(&rq->migration_queue);
7335 rq_attach_root(rq, &def_root_domain);
7338 atomic_set(&rq->nr_iowait, 0);
7342 set_load_weight(&init_task);
7344 #ifdef CONFIG_PREEMPT_NOTIFIERS
7345 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
7349 nr_cpu_ids = highest_cpu + 1;
7350 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
7353 #ifdef CONFIG_RT_MUTEXES
7354 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
7358 * The boot idle thread does lazy MMU switching as well:
7360 atomic_inc(&init_mm.mm_count);
7361 enter_lazy_tlb(&init_mm, current);
7364 * Make us the idle thread. Technically, schedule() should not be
7365 * called from this thread, however somewhere below it might be,
7366 * but because we are the idle thread, we just pick up running again
7367 * when this runqueue becomes "idle".
7369 init_idle(current, smp_processor_id());
7371 * During early bootup we pretend to be a normal task:
7373 current->sched_class = &fair_sched_class;
7375 scheduler_running = 1;
7378 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
7379 void __might_sleep(char *file, int line)
7382 static unsigned long prev_jiffy; /* ratelimiting */
7384 if ((in_atomic() || irqs_disabled()) &&
7385 system_state == SYSTEM_RUNNING && !oops_in_progress) {
7386 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7388 prev_jiffy = jiffies;
7389 printk(KERN_ERR "BUG: sleeping function called from invalid"
7390 " context at %s:%d\n", file, line);
7391 printk("in_atomic():%d, irqs_disabled():%d\n",
7392 in_atomic(), irqs_disabled());
7393 debug_show_held_locks(current);
7394 if (irqs_disabled())
7395 print_irqtrace_events(current);
7400 EXPORT_SYMBOL(__might_sleep);
7403 #ifdef CONFIG_MAGIC_SYSRQ
7404 static void normalize_task(struct rq *rq, struct task_struct *p)
7407 update_rq_clock(rq);
7408 on_rq = p->se.on_rq;
7410 deactivate_task(rq, p, 0);
7411 __setscheduler(rq, p, SCHED_NORMAL, 0);
7413 activate_task(rq, p, 0);
7414 resched_task(rq->curr);
7418 void normalize_rt_tasks(void)
7420 struct task_struct *g, *p;
7421 unsigned long flags;
7424 read_lock_irqsave(&tasklist_lock, flags);
7425 do_each_thread(g, p) {
7427 * Only normalize user tasks:
7432 p->se.exec_start = 0;
7433 #ifdef CONFIG_SCHEDSTATS
7434 p->se.wait_start = 0;
7435 p->se.sleep_start = 0;
7436 p->se.block_start = 0;
7438 task_rq(p)->clock = 0;
7442 * Renice negative nice level userspace
7445 if (TASK_NICE(p) < 0 && p->mm)
7446 set_user_nice(p, 0);
7450 spin_lock(&p->pi_lock);
7451 rq = __task_rq_lock(p);
7453 normalize_task(rq, p);
7455 __task_rq_unlock(rq);
7456 spin_unlock(&p->pi_lock);
7457 } while_each_thread(g, p);
7459 read_unlock_irqrestore(&tasklist_lock, flags);
7462 #endif /* CONFIG_MAGIC_SYSRQ */
7466 * These functions are only useful for the IA64 MCA handling.
7468 * They can only be called when the whole system has been
7469 * stopped - every CPU needs to be quiescent, and no scheduling
7470 * activity can take place. Using them for anything else would
7471 * be a serious bug, and as a result, they aren't even visible
7472 * under any other configuration.
7476 * curr_task - return the current task for a given cpu.
7477 * @cpu: the processor in question.
7479 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7481 struct task_struct *curr_task(int cpu)
7483 return cpu_curr(cpu);
7487 * set_curr_task - set the current task for a given cpu.
7488 * @cpu: the processor in question.
7489 * @p: the task pointer to set.
7491 * Description: This function must only be used when non-maskable interrupts
7492 * are serviced on a separate stack. It allows the architecture to switch the
7493 * notion of the current task on a cpu in a non-blocking manner. This function
7494 * must be called with all CPU's synchronized, and interrupts disabled, the
7495 * and caller must save the original value of the current task (see
7496 * curr_task() above) and restore that value before reenabling interrupts and
7497 * re-starting the system.
7499 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7501 void set_curr_task(int cpu, struct task_struct *p)
7508 #ifdef CONFIG_GROUP_SCHED
7510 #ifdef CONFIG_FAIR_GROUP_SCHED
7511 static void free_fair_sched_group(struct task_group *tg)
7515 for_each_possible_cpu(i) {
7517 kfree(tg->cfs_rq[i]);
7526 static int alloc_fair_sched_group(struct task_group *tg)
7528 struct cfs_rq *cfs_rq;
7529 struct sched_entity *se;
7533 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * NR_CPUS, GFP_KERNEL);
7536 tg->se = kzalloc(sizeof(se) * NR_CPUS, GFP_KERNEL);
7540 tg->shares = NICE_0_LOAD;
7542 for_each_possible_cpu(i) {
7545 cfs_rq = kmalloc_node(sizeof(struct cfs_rq),
7546 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
7550 se = kmalloc_node(sizeof(struct sched_entity),
7551 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
7555 init_tg_cfs_entry(rq, tg, cfs_rq, se, i, 0);
7564 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
7566 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
7567 &cpu_rq(cpu)->leaf_cfs_rq_list);
7570 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
7572 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
7575 static inline void free_fair_sched_group(struct task_group *tg)
7579 static inline int alloc_fair_sched_group(struct task_group *tg)
7584 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
7588 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
7593 #ifdef CONFIG_RT_GROUP_SCHED
7594 static void free_rt_sched_group(struct task_group *tg)
7598 for_each_possible_cpu(i) {
7600 kfree(tg->rt_rq[i]);
7602 kfree(tg->rt_se[i]);
7609 static int alloc_rt_sched_group(struct task_group *tg)
7611 struct rt_rq *rt_rq;
7612 struct sched_rt_entity *rt_se;
7616 tg->rt_rq = kzalloc(sizeof(rt_rq) * NR_CPUS, GFP_KERNEL);
7619 tg->rt_se = kzalloc(sizeof(rt_se) * NR_CPUS, GFP_KERNEL);
7625 for_each_possible_cpu(i) {
7628 rt_rq = kmalloc_node(sizeof(struct rt_rq),
7629 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
7633 rt_se = kmalloc_node(sizeof(struct sched_rt_entity),
7634 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
7638 init_tg_rt_entry(rq, tg, rt_rq, rt_se, i, 0);
7647 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
7649 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
7650 &cpu_rq(cpu)->leaf_rt_rq_list);
7653 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
7655 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
7658 static inline void free_rt_sched_group(struct task_group *tg)
7662 static inline int alloc_rt_sched_group(struct task_group *tg)
7667 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
7671 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
7676 static void free_sched_group(struct task_group *tg)
7678 free_fair_sched_group(tg);
7679 free_rt_sched_group(tg);
7683 /* allocate runqueue etc for a new task group */
7684 struct task_group *sched_create_group(void)
7686 struct task_group *tg;
7687 unsigned long flags;
7690 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
7692 return ERR_PTR(-ENOMEM);
7694 if (!alloc_fair_sched_group(tg))
7697 if (!alloc_rt_sched_group(tg))
7700 spin_lock_irqsave(&task_group_lock, flags);
7701 for_each_possible_cpu(i) {
7702 register_fair_sched_group(tg, i);
7703 register_rt_sched_group(tg, i);
7705 list_add_rcu(&tg->list, &task_groups);
7706 spin_unlock_irqrestore(&task_group_lock, flags);
7711 free_sched_group(tg);
7712 return ERR_PTR(-ENOMEM);
7715 /* rcu callback to free various structures associated with a task group */
7716 static void free_sched_group_rcu(struct rcu_head *rhp)
7718 /* now it should be safe to free those cfs_rqs */
7719 free_sched_group(container_of(rhp, struct task_group, rcu));
7722 /* Destroy runqueue etc associated with a task group */
7723 void sched_destroy_group(struct task_group *tg)
7725 unsigned long flags;
7728 spin_lock_irqsave(&task_group_lock, flags);
7729 for_each_possible_cpu(i) {
7730 unregister_fair_sched_group(tg, i);
7731 unregister_rt_sched_group(tg, i);
7733 list_del_rcu(&tg->list);
7734 spin_unlock_irqrestore(&task_group_lock, flags);
7736 /* wait for possible concurrent references to cfs_rqs complete */
7737 call_rcu(&tg->rcu, free_sched_group_rcu);
7740 /* change task's runqueue when it moves between groups.
7741 * The caller of this function should have put the task in its new group
7742 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7743 * reflect its new group.
7745 void sched_move_task(struct task_struct *tsk)
7748 unsigned long flags;
7751 rq = task_rq_lock(tsk, &flags);
7753 update_rq_clock(rq);
7755 running = task_current(rq, tsk);
7756 on_rq = tsk->se.on_rq;
7759 dequeue_task(rq, tsk, 0);
7760 if (unlikely(running))
7761 tsk->sched_class->put_prev_task(rq, tsk);
7763 set_task_rq(tsk, task_cpu(tsk));
7765 #ifdef CONFIG_FAIR_GROUP_SCHED
7766 if (tsk->sched_class->moved_group)
7767 tsk->sched_class->moved_group(tsk);
7770 if (unlikely(running))
7771 tsk->sched_class->set_curr_task(rq);
7773 enqueue_task(rq, tsk, 0);
7775 task_rq_unlock(rq, &flags);
7778 #ifdef CONFIG_FAIR_GROUP_SCHED
7779 static void set_se_shares(struct sched_entity *se, unsigned long shares)
7781 struct cfs_rq *cfs_rq = se->cfs_rq;
7782 struct rq *rq = cfs_rq->rq;
7785 spin_lock_irq(&rq->lock);
7789 dequeue_entity(cfs_rq, se, 0);
7791 se->load.weight = shares;
7792 se->load.inv_weight = div64_64((1ULL<<32), shares);
7795 enqueue_entity(cfs_rq, se, 0);
7797 spin_unlock_irq(&rq->lock);
7800 static DEFINE_MUTEX(shares_mutex);
7802 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
7805 unsigned long flags;
7808 * A weight of 0 or 1 can cause arithmetics problems.
7809 * (The default weight is 1024 - so there's no practical
7810 * limitation from this.)
7815 mutex_lock(&shares_mutex);
7816 if (tg->shares == shares)
7819 spin_lock_irqsave(&task_group_lock, flags);
7820 for_each_possible_cpu(i)
7821 unregister_fair_sched_group(tg, i);
7822 spin_unlock_irqrestore(&task_group_lock, flags);
7824 /* wait for any ongoing reference to this group to finish */
7825 synchronize_sched();
7828 * Now we are free to modify the group's share on each cpu
7829 * w/o tripping rebalance_share or load_balance_fair.
7831 tg->shares = shares;
7832 for_each_possible_cpu(i)
7833 set_se_shares(tg->se[i], shares);
7836 * Enable load balance activity on this group, by inserting it back on
7837 * each cpu's rq->leaf_cfs_rq_list.
7839 spin_lock_irqsave(&task_group_lock, flags);
7840 for_each_possible_cpu(i)
7841 register_fair_sched_group(tg, i);
7842 spin_unlock_irqrestore(&task_group_lock, flags);
7844 mutex_unlock(&shares_mutex);
7848 unsigned long sched_group_shares(struct task_group *tg)
7854 #ifdef CONFIG_RT_GROUP_SCHED
7856 * Ensure that the real time constraints are schedulable.
7858 static DEFINE_MUTEX(rt_constraints_mutex);
7860 static unsigned long to_ratio(u64 period, u64 runtime)
7862 if (runtime == RUNTIME_INF)
7865 return div64_64(runtime << 16, period);
7868 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
7870 struct task_group *tgi;
7871 unsigned long total = 0;
7872 unsigned long global_ratio =
7873 to_ratio(sysctl_sched_rt_period,
7874 sysctl_sched_rt_runtime < 0 ?
7875 RUNTIME_INF : sysctl_sched_rt_runtime);
7878 list_for_each_entry_rcu(tgi, &task_groups, list) {
7882 total += to_ratio(period, tgi->rt_runtime);
7886 return total + to_ratio(period, runtime) < global_ratio;
7889 /* Must be called with tasklist_lock held */
7890 static inline int tg_has_rt_tasks(struct task_group *tg)
7892 struct task_struct *g, *p;
7893 do_each_thread(g, p) {
7894 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
7896 } while_each_thread(g, p);
7900 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
7902 u64 rt_runtime, rt_period;
7905 rt_period = (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
7906 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
7907 if (rt_runtime_us == -1)
7908 rt_runtime = RUNTIME_INF;
7910 mutex_lock(&rt_constraints_mutex);
7911 read_lock(&tasklist_lock);
7912 if (rt_runtime_us == 0 && tg_has_rt_tasks(tg)) {
7916 if (!__rt_schedulable(tg, rt_period, rt_runtime)) {
7920 tg->rt_runtime = rt_runtime;
7922 read_unlock(&tasklist_lock);
7923 mutex_unlock(&rt_constraints_mutex);
7928 long sched_group_rt_runtime(struct task_group *tg)
7932 if (tg->rt_runtime == RUNTIME_INF)
7935 rt_runtime_us = tg->rt_runtime;
7936 do_div(rt_runtime_us, NSEC_PER_USEC);
7937 return rt_runtime_us;
7940 #endif /* CONFIG_GROUP_SCHED */
7942 #ifdef CONFIG_CGROUP_SCHED
7944 /* return corresponding task_group object of a cgroup */
7945 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
7947 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
7948 struct task_group, css);
7951 static struct cgroup_subsys_state *
7952 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
7954 struct task_group *tg;
7956 if (!cgrp->parent) {
7957 /* This is early initialization for the top cgroup */
7958 init_task_group.css.cgroup = cgrp;
7959 return &init_task_group.css;
7962 /* we support only 1-level deep hierarchical scheduler atm */
7963 if (cgrp->parent->parent)
7964 return ERR_PTR(-EINVAL);
7966 tg = sched_create_group();
7968 return ERR_PTR(-ENOMEM);
7970 /* Bind the cgroup to task_group object we just created */
7971 tg->css.cgroup = cgrp;
7977 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
7979 struct task_group *tg = cgroup_tg(cgrp);
7981 sched_destroy_group(tg);
7985 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
7986 struct task_struct *tsk)
7988 #ifdef CONFIG_RT_GROUP_SCHED
7989 /* Don't accept realtime tasks when there is no way for them to run */
7990 if (rt_task(tsk) && cgroup_tg(cgrp)->rt_runtime == 0)
7993 /* We don't support RT-tasks being in separate groups */
7994 if (tsk->sched_class != &fair_sched_class)
8002 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8003 struct cgroup *old_cont, struct task_struct *tsk)
8005 sched_move_task(tsk);
8008 #ifdef CONFIG_FAIR_GROUP_SCHED
8009 static int cpu_shares_write_uint(struct cgroup *cgrp, struct cftype *cftype,
8012 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
8015 static u64 cpu_shares_read_uint(struct cgroup *cgrp, struct cftype *cft)
8017 struct task_group *tg = cgroup_tg(cgrp);
8019 return (u64) tg->shares;
8023 #ifdef CONFIG_RT_GROUP_SCHED
8024 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
8026 const char __user *userbuf,
8027 size_t nbytes, loff_t *unused_ppos)
8036 if (nbytes >= sizeof(buffer))
8038 if (copy_from_user(buffer, userbuf, nbytes))
8041 buffer[nbytes] = 0; /* nul-terminate */
8043 /* strip newline if necessary */
8044 if (nbytes && (buffer[nbytes-1] == '\n'))
8045 buffer[nbytes-1] = 0;
8046 val = simple_strtoll(buffer, &end, 0);
8050 /* Pass to subsystem */
8051 retval = sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
8057 static ssize_t cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft,
8059 char __user *buf, size_t nbytes,
8063 long val = sched_group_rt_runtime(cgroup_tg(cgrp));
8064 int len = sprintf(tmp, "%ld\n", val);
8066 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
8070 static struct cftype cpu_files[] = {
8071 #ifdef CONFIG_FAIR_GROUP_SCHED
8074 .read_uint = cpu_shares_read_uint,
8075 .write_uint = cpu_shares_write_uint,
8078 #ifdef CONFIG_RT_GROUP_SCHED
8080 .name = "rt_runtime_us",
8081 .read = cpu_rt_runtime_read,
8082 .write = cpu_rt_runtime_write,
8087 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
8089 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
8092 struct cgroup_subsys cpu_cgroup_subsys = {
8094 .create = cpu_cgroup_create,
8095 .destroy = cpu_cgroup_destroy,
8096 .can_attach = cpu_cgroup_can_attach,
8097 .attach = cpu_cgroup_attach,
8098 .populate = cpu_cgroup_populate,
8099 .subsys_id = cpu_cgroup_subsys_id,
8103 #endif /* CONFIG_CGROUP_SCHED */
8105 #ifdef CONFIG_CGROUP_CPUACCT
8108 * CPU accounting code for task groups.
8110 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
8111 * (balbir@in.ibm.com).
8114 /* track cpu usage of a group of tasks */
8116 struct cgroup_subsys_state css;
8117 /* cpuusage holds pointer to a u64-type object on every cpu */
8121 struct cgroup_subsys cpuacct_subsys;
8123 /* return cpu accounting group corresponding to this container */
8124 static inline struct cpuacct *cgroup_ca(struct cgroup *cont)
8126 return container_of(cgroup_subsys_state(cont, cpuacct_subsys_id),
8127 struct cpuacct, css);
8130 /* return cpu accounting group to which this task belongs */
8131 static inline struct cpuacct *task_ca(struct task_struct *tsk)
8133 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
8134 struct cpuacct, css);
8137 /* create a new cpu accounting group */
8138 static struct cgroup_subsys_state *cpuacct_create(
8139 struct cgroup_subsys *ss, struct cgroup *cont)
8141 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
8144 return ERR_PTR(-ENOMEM);
8146 ca->cpuusage = alloc_percpu(u64);
8147 if (!ca->cpuusage) {
8149 return ERR_PTR(-ENOMEM);
8155 /* destroy an existing cpu accounting group */
8157 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cont)
8159 struct cpuacct *ca = cgroup_ca(cont);
8161 free_percpu(ca->cpuusage);
8165 /* return total cpu usage (in nanoseconds) of a group */
8166 static u64 cpuusage_read(struct cgroup *cont, struct cftype *cft)
8168 struct cpuacct *ca = cgroup_ca(cont);
8169 u64 totalcpuusage = 0;
8172 for_each_possible_cpu(i) {
8173 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
8176 * Take rq->lock to make 64-bit addition safe on 32-bit
8179 spin_lock_irq(&cpu_rq(i)->lock);
8180 totalcpuusage += *cpuusage;
8181 spin_unlock_irq(&cpu_rq(i)->lock);
8184 return totalcpuusage;
8187 static struct cftype files[] = {
8190 .read_uint = cpuusage_read,
8194 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cont)
8196 return cgroup_add_files(cont, ss, files, ARRAY_SIZE(files));
8200 * charge this task's execution time to its accounting group.
8202 * called with rq->lock held.
8204 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
8208 if (!cpuacct_subsys.active)
8213 u64 *cpuusage = percpu_ptr(ca->cpuusage, task_cpu(tsk));
8215 *cpuusage += cputime;
8219 struct cgroup_subsys cpuacct_subsys = {
8221 .create = cpuacct_create,
8222 .destroy = cpuacct_destroy,
8223 .populate = cpuacct_populate,
8224 .subsys_id = cpuacct_subsys_id,
8226 #endif /* CONFIG_CGROUP_CPUACCT */