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)
119 * single value that denotes runtime == period, ie unlimited time.
121 #define RUNTIME_INF ((u64)~0ULL)
125 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
126 * Since cpu_power is a 'constant', we can use a reciprocal divide.
128 static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
130 return reciprocal_divide(load, sg->reciprocal_cpu_power);
134 * Each time a sched group cpu_power is changed,
135 * we must compute its reciprocal value
137 static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
139 sg->__cpu_power += val;
140 sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
144 static inline int rt_policy(int policy)
146 if (unlikely(policy == SCHED_FIFO) || unlikely(policy == SCHED_RR))
151 static inline int task_has_rt_policy(struct task_struct *p)
153 return rt_policy(p->policy);
157 * This is the priority-queue data structure of the RT scheduling class:
159 struct rt_prio_array {
160 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
161 struct list_head queue[MAX_RT_PRIO];
164 struct rt_bandwidth {
167 struct hrtimer rt_period_timer;
170 static struct rt_bandwidth def_rt_bandwidth;
172 static int do_sched_rt_period_timer(struct rt_bandwidth *rt_b, int overrun);
174 static enum hrtimer_restart sched_rt_period_timer(struct hrtimer *timer)
176 struct rt_bandwidth *rt_b =
177 container_of(timer, struct rt_bandwidth, rt_period_timer);
183 now = hrtimer_cb_get_time(timer);
184 overrun = hrtimer_forward(timer, now, rt_b->rt_period);
189 idle = do_sched_rt_period_timer(rt_b, overrun);
192 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART;
196 void init_rt_bandwidth(struct rt_bandwidth *rt_b, u64 period, u64 runtime)
198 rt_b->rt_period = ns_to_ktime(period);
199 rt_b->rt_runtime = runtime;
201 hrtimer_init(&rt_b->rt_period_timer,
202 CLOCK_MONOTONIC, HRTIMER_MODE_REL);
203 rt_b->rt_period_timer.function = sched_rt_period_timer;
204 rt_b->rt_period_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
207 static void start_rt_bandwidth(struct rt_bandwidth *rt_b)
211 if (rt_b->rt_runtime == RUNTIME_INF)
214 if (hrtimer_active(&rt_b->rt_period_timer))
217 spin_lock(&rt_b->rt_runtime_lock);
219 if (hrtimer_active(&rt_b->rt_period_timer))
222 now = hrtimer_cb_get_time(&rt_b->rt_period_timer);
223 hrtimer_forward(&rt_b->rt_period_timer, now, rt_b->rt_period);
224 hrtimer_start(&rt_b->rt_period_timer,
225 rt_b->rt_period_timer.expires,
228 spin_unlock(&rt_b->rt_runtime_lock);
231 #ifdef CONFIG_RT_GROUP_SCHED
232 static void destroy_rt_bandwidth(struct rt_bandwidth *rt_b)
234 hrtimer_cancel(&rt_b->rt_period_timer);
238 #ifdef CONFIG_GROUP_SCHED
240 #include <linux/cgroup.h>
244 static LIST_HEAD(task_groups);
246 /* task group related information */
248 #ifdef CONFIG_CGROUP_SCHED
249 struct cgroup_subsys_state css;
252 #ifdef CONFIG_FAIR_GROUP_SCHED
253 /* schedulable entities of this group on each cpu */
254 struct sched_entity **se;
255 /* runqueue "owned" by this group on each cpu */
256 struct cfs_rq **cfs_rq;
257 unsigned long shares;
260 #ifdef CONFIG_RT_GROUP_SCHED
261 struct sched_rt_entity **rt_se;
262 struct rt_rq **rt_rq;
264 struct rt_bandwidth rt_bandwidth;
268 struct list_head list;
271 #ifdef CONFIG_FAIR_GROUP_SCHED
272 /* Default task group's sched entity on each cpu */
273 static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
274 /* Default task group's cfs_rq on each cpu */
275 static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;
277 static struct sched_entity *init_sched_entity_p[NR_CPUS];
278 static struct cfs_rq *init_cfs_rq_p[NR_CPUS];
281 #ifdef CONFIG_RT_GROUP_SCHED
282 static DEFINE_PER_CPU(struct sched_rt_entity, init_sched_rt_entity);
283 static DEFINE_PER_CPU(struct rt_rq, init_rt_rq) ____cacheline_aligned_in_smp;
285 static struct sched_rt_entity *init_sched_rt_entity_p[NR_CPUS];
286 static struct rt_rq *init_rt_rq_p[NR_CPUS];
289 /* task_group_lock serializes add/remove of task groups and also changes to
290 * a task group's cpu shares.
292 static DEFINE_SPINLOCK(task_group_lock);
294 /* doms_cur_mutex serializes access to doms_cur[] array */
295 static DEFINE_MUTEX(doms_cur_mutex);
297 #ifdef CONFIG_FAIR_GROUP_SCHED
298 #ifdef CONFIG_USER_SCHED
299 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
301 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
304 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
307 /* Default task group.
308 * Every task in system belong to this group at bootup.
310 struct task_group init_task_group = {
311 #ifdef CONFIG_FAIR_GROUP_SCHED
312 .se = init_sched_entity_p,
313 .cfs_rq = init_cfs_rq_p,
316 #ifdef CONFIG_RT_GROUP_SCHED
317 .rt_se = init_sched_rt_entity_p,
318 .rt_rq = init_rt_rq_p,
322 /* return group to which a task belongs */
323 static inline struct task_group *task_group(struct task_struct *p)
325 struct task_group *tg;
327 #ifdef CONFIG_USER_SCHED
329 #elif defined(CONFIG_CGROUP_SCHED)
330 tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
331 struct task_group, css);
333 tg = &init_task_group;
338 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
339 static inline void set_task_rq(struct task_struct *p, unsigned int cpu)
341 #ifdef CONFIG_FAIR_GROUP_SCHED
342 p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
343 p->se.parent = task_group(p)->se[cpu];
346 #ifdef CONFIG_RT_GROUP_SCHED
347 p->rt.rt_rq = task_group(p)->rt_rq[cpu];
348 p->rt.parent = task_group(p)->rt_se[cpu];
352 static inline void lock_doms_cur(void)
354 mutex_lock(&doms_cur_mutex);
357 static inline void unlock_doms_cur(void)
359 mutex_unlock(&doms_cur_mutex);
364 static inline void set_task_rq(struct task_struct *p, unsigned int cpu) { }
365 static inline void lock_doms_cur(void) { }
366 static inline void unlock_doms_cur(void) { }
368 #endif /* CONFIG_GROUP_SCHED */
370 /* CFS-related fields in a runqueue */
372 struct load_weight load;
373 unsigned long nr_running;
378 struct rb_root tasks_timeline;
379 struct rb_node *rb_leftmost;
380 struct rb_node *rb_load_balance_curr;
381 /* 'curr' points to currently running entity on this cfs_rq.
382 * It is set to NULL otherwise (i.e when none are currently running).
384 struct sched_entity *curr, *next;
386 unsigned long nr_spread_over;
388 #ifdef CONFIG_FAIR_GROUP_SCHED
389 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
392 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
393 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
394 * (like users, containers etc.)
396 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
397 * list is used during load balance.
399 struct list_head leaf_cfs_rq_list;
400 struct task_group *tg; /* group that "owns" this runqueue */
404 /* Real-Time classes' related field in a runqueue: */
406 struct rt_prio_array active;
407 unsigned long rt_nr_running;
408 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
409 int highest_prio; /* highest queued rt task prio */
412 unsigned long rt_nr_migratory;
418 #ifdef CONFIG_RT_GROUP_SCHED
419 unsigned long rt_nr_boosted;
422 struct list_head leaf_rt_rq_list;
423 struct task_group *tg;
424 struct sched_rt_entity *rt_se;
431 * We add the notion of a root-domain which will be used to define per-domain
432 * variables. Each exclusive cpuset essentially defines an island domain by
433 * fully partitioning the member cpus from any other cpuset. Whenever a new
434 * exclusive cpuset is created, we also create and attach a new root-domain
444 * The "RT overload" flag: it gets set if a CPU has more than
445 * one runnable RT task.
452 * By default the system creates a single root-domain with all cpus as
453 * members (mimicking the global state we have today).
455 static struct root_domain def_root_domain;
460 * This is the main, per-CPU runqueue data structure.
462 * Locking rule: those places that want to lock multiple runqueues
463 * (such as the load balancing or the thread migration code), lock
464 * acquire operations must be ordered by ascending &runqueue.
471 * nr_running and cpu_load should be in the same cacheline because
472 * remote CPUs use both these fields when doing load calculation.
474 unsigned long nr_running;
475 #define CPU_LOAD_IDX_MAX 5
476 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
477 unsigned char idle_at_tick;
479 unsigned long last_tick_seen;
480 unsigned char in_nohz_recently;
482 /* capture load from *all* tasks on this cpu: */
483 struct load_weight load;
484 unsigned long nr_load_updates;
490 #ifdef CONFIG_FAIR_GROUP_SCHED
491 /* list of leaf cfs_rq on this cpu: */
492 struct list_head leaf_cfs_rq_list;
494 #ifdef CONFIG_RT_GROUP_SCHED
495 struct list_head leaf_rt_rq_list;
499 * This is part of a global counter where only the total sum
500 * over all CPUs matters. A task can increase this counter on
501 * one CPU and if it got migrated afterwards it may decrease
502 * it on another CPU. Always updated under the runqueue lock:
504 unsigned long nr_uninterruptible;
506 struct task_struct *curr, *idle;
507 unsigned long next_balance;
508 struct mm_struct *prev_mm;
510 u64 clock, prev_clock_raw;
513 unsigned int clock_warps, clock_overflows, clock_underflows;
515 unsigned int clock_deep_idle_events;
521 struct root_domain *rd;
522 struct sched_domain *sd;
524 /* For active balancing */
527 /* cpu of this runqueue: */
530 struct task_struct *migration_thread;
531 struct list_head migration_queue;
534 #ifdef CONFIG_SCHED_HRTICK
535 unsigned long hrtick_flags;
536 ktime_t hrtick_expire;
537 struct hrtimer hrtick_timer;
540 #ifdef CONFIG_SCHEDSTATS
542 struct sched_info rq_sched_info;
544 /* sys_sched_yield() stats */
545 unsigned int yld_exp_empty;
546 unsigned int yld_act_empty;
547 unsigned int yld_both_empty;
548 unsigned int yld_count;
550 /* schedule() stats */
551 unsigned int sched_switch;
552 unsigned int sched_count;
553 unsigned int sched_goidle;
555 /* try_to_wake_up() stats */
556 unsigned int ttwu_count;
557 unsigned int ttwu_local;
560 unsigned int bkl_count;
562 struct lock_class_key rq_lock_key;
565 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
567 static inline void check_preempt_curr(struct rq *rq, struct task_struct *p)
569 rq->curr->sched_class->check_preempt_curr(rq, p);
572 static inline int cpu_of(struct rq *rq)
582 static inline bool nohz_on(int cpu)
584 return tick_get_tick_sched(cpu)->nohz_mode != NOHZ_MODE_INACTIVE;
587 static inline u64 max_skipped_ticks(struct rq *rq)
589 return nohz_on(cpu_of(rq)) ? jiffies - rq->last_tick_seen + 2 : 1;
592 static inline void update_last_tick_seen(struct rq *rq)
594 rq->last_tick_seen = jiffies;
597 static inline u64 max_skipped_ticks(struct rq *rq)
602 static inline void update_last_tick_seen(struct rq *rq)
608 * Update the per-runqueue clock, as finegrained as the platform can give
609 * us, but without assuming monotonicity, etc.:
611 static void __update_rq_clock(struct rq *rq)
613 u64 prev_raw = rq->prev_clock_raw;
614 u64 now = sched_clock();
615 s64 delta = now - prev_raw;
616 u64 clock = rq->clock;
618 #ifdef CONFIG_SCHED_DEBUG
619 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
622 * Protect against sched_clock() occasionally going backwards:
624 if (unlikely(delta < 0)) {
629 * Catch too large forward jumps too:
631 u64 max_jump = max_skipped_ticks(rq) * TICK_NSEC;
632 u64 max_time = rq->tick_timestamp + max_jump;
634 if (unlikely(clock + delta > max_time)) {
635 if (clock < max_time)
639 rq->clock_overflows++;
641 if (unlikely(delta > rq->clock_max_delta))
642 rq->clock_max_delta = delta;
647 rq->prev_clock_raw = now;
651 static void update_rq_clock(struct rq *rq)
653 if (likely(smp_processor_id() == cpu_of(rq)))
654 __update_rq_clock(rq);
658 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
659 * See detach_destroy_domains: synchronize_sched for details.
661 * The domain tree of any CPU may only be accessed from within
662 * preempt-disabled sections.
664 #define for_each_domain(cpu, __sd) \
665 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
667 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
668 #define this_rq() (&__get_cpu_var(runqueues))
669 #define task_rq(p) cpu_rq(task_cpu(p))
670 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
673 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
675 #ifdef CONFIG_SCHED_DEBUG
676 # define const_debug __read_mostly
678 # define const_debug static const
682 * Debugging: various feature bits
685 SCHED_FEAT_NEW_FAIR_SLEEPERS = 1,
686 SCHED_FEAT_WAKEUP_PREEMPT = 2,
687 SCHED_FEAT_START_DEBIT = 4,
688 SCHED_FEAT_AFFINE_WAKEUPS = 8,
689 SCHED_FEAT_CACHE_HOT_BUDDY = 16,
690 SCHED_FEAT_SYNC_WAKEUPS = 32,
691 SCHED_FEAT_HRTICK = 64,
692 SCHED_FEAT_DOUBLE_TICK = 128,
695 const_debug unsigned int sysctl_sched_features =
696 SCHED_FEAT_NEW_FAIR_SLEEPERS * 1 |
697 SCHED_FEAT_WAKEUP_PREEMPT * 1 |
698 SCHED_FEAT_START_DEBIT * 1 |
699 SCHED_FEAT_AFFINE_WAKEUPS * 1 |
700 SCHED_FEAT_CACHE_HOT_BUDDY * 1 |
701 SCHED_FEAT_SYNC_WAKEUPS * 1 |
702 SCHED_FEAT_HRTICK * 1 |
703 SCHED_FEAT_DOUBLE_TICK * 0;
705 #define sched_feat(x) (sysctl_sched_features & SCHED_FEAT_##x)
708 * Number of tasks to iterate in a single balance run.
709 * Limited because this is done with IRQs disabled.
711 const_debug unsigned int sysctl_sched_nr_migrate = 32;
714 * period over which we measure -rt task cpu usage in us.
717 unsigned int sysctl_sched_rt_period = 1000000;
719 static __read_mostly int scheduler_running;
722 * part of the period that we allow rt tasks to run in us.
725 int sysctl_sched_rt_runtime = 950000;
727 static inline u64 global_rt_period(void)
729 return (u64)sysctl_sched_rt_period * NSEC_PER_USEC;
732 static inline u64 global_rt_runtime(void)
734 if (sysctl_sched_rt_period < 0)
737 return (u64)sysctl_sched_rt_runtime * NSEC_PER_USEC;
740 static const unsigned long long time_sync_thresh = 100000;
742 static DEFINE_PER_CPU(unsigned long long, time_offset);
743 static DEFINE_PER_CPU(unsigned long long, prev_cpu_time);
746 * Global lock which we take every now and then to synchronize
747 * the CPUs time. This method is not warp-safe, but it's good
748 * enough to synchronize slowly diverging time sources and thus
749 * it's good enough for tracing:
751 static DEFINE_SPINLOCK(time_sync_lock);
752 static unsigned long long prev_global_time;
754 static unsigned long long __sync_cpu_clock(cycles_t time, int cpu)
758 spin_lock_irqsave(&time_sync_lock, flags);
760 if (time < prev_global_time) {
761 per_cpu(time_offset, cpu) += prev_global_time - time;
762 time = prev_global_time;
764 prev_global_time = time;
767 spin_unlock_irqrestore(&time_sync_lock, flags);
772 static unsigned long long __cpu_clock(int cpu)
774 unsigned long long now;
779 * Only call sched_clock() if the scheduler has already been
780 * initialized (some code might call cpu_clock() very early):
782 if (unlikely(!scheduler_running))
785 local_irq_save(flags);
789 local_irq_restore(flags);
795 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
796 * clock constructed from sched_clock():
798 unsigned long long cpu_clock(int cpu)
800 unsigned long long prev_cpu_time, time, delta_time;
802 prev_cpu_time = per_cpu(prev_cpu_time, cpu);
803 time = __cpu_clock(cpu) + per_cpu(time_offset, cpu);
804 delta_time = time-prev_cpu_time;
806 if (unlikely(delta_time > time_sync_thresh))
807 time = __sync_cpu_clock(time, cpu);
811 EXPORT_SYMBOL_GPL(cpu_clock);
813 #ifndef prepare_arch_switch
814 # define prepare_arch_switch(next) do { } while (0)
816 #ifndef finish_arch_switch
817 # define finish_arch_switch(prev) do { } while (0)
820 static inline int task_current(struct rq *rq, struct task_struct *p)
822 return rq->curr == p;
825 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
826 static inline int task_running(struct rq *rq, struct task_struct *p)
828 return task_current(rq, p);
831 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
835 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
837 #ifdef CONFIG_DEBUG_SPINLOCK
838 /* this is a valid case when another task releases the spinlock */
839 rq->lock.owner = current;
842 * If we are tracking spinlock dependencies then we have to
843 * fix up the runqueue lock - which gets 'carried over' from
846 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
848 spin_unlock_irq(&rq->lock);
851 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
852 static inline int task_running(struct rq *rq, struct task_struct *p)
857 return task_current(rq, p);
861 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
865 * We can optimise this out completely for !SMP, because the
866 * SMP rebalancing from interrupt is the only thing that cares
871 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
872 spin_unlock_irq(&rq->lock);
874 spin_unlock(&rq->lock);
878 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
882 * After ->oncpu is cleared, the task can be moved to a different CPU.
883 * We must ensure this doesn't happen until the switch is completely
889 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
893 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
896 * __task_rq_lock - lock the runqueue a given task resides on.
897 * Must be called interrupts disabled.
899 static inline struct rq *__task_rq_lock(struct task_struct *p)
903 struct rq *rq = task_rq(p);
904 spin_lock(&rq->lock);
905 if (likely(rq == task_rq(p)))
907 spin_unlock(&rq->lock);
912 * task_rq_lock - lock the runqueue a given task resides on and disable
913 * interrupts. Note the ordering: we can safely lookup the task_rq without
914 * explicitly disabling preemption.
916 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
922 local_irq_save(*flags);
924 spin_lock(&rq->lock);
925 if (likely(rq == task_rq(p)))
927 spin_unlock_irqrestore(&rq->lock, *flags);
931 static void __task_rq_unlock(struct rq *rq)
934 spin_unlock(&rq->lock);
937 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
940 spin_unlock_irqrestore(&rq->lock, *flags);
944 * this_rq_lock - lock this runqueue and disable interrupts.
946 static struct rq *this_rq_lock(void)
953 spin_lock(&rq->lock);
959 * We are going deep-idle (irqs are disabled):
961 void sched_clock_idle_sleep_event(void)
963 struct rq *rq = cpu_rq(smp_processor_id());
965 spin_lock(&rq->lock);
966 __update_rq_clock(rq);
967 spin_unlock(&rq->lock);
968 rq->clock_deep_idle_events++;
970 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
973 * We just idled delta nanoseconds (called with irqs disabled):
975 void sched_clock_idle_wakeup_event(u64 delta_ns)
977 struct rq *rq = cpu_rq(smp_processor_id());
978 u64 now = sched_clock();
980 rq->idle_clock += delta_ns;
982 * Override the previous timestamp and ignore all
983 * sched_clock() deltas that occured while we idled,
984 * and use the PM-provided delta_ns to advance the
987 spin_lock(&rq->lock);
988 rq->prev_clock_raw = now;
989 rq->clock += delta_ns;
990 spin_unlock(&rq->lock);
991 touch_softlockup_watchdog();
993 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
995 static void __resched_task(struct task_struct *p, int tif_bit);
997 static inline void resched_task(struct task_struct *p)
999 __resched_task(p, TIF_NEED_RESCHED);
1002 #ifdef CONFIG_SCHED_HRTICK
1004 * Use HR-timers to deliver accurate preemption points.
1006 * Its all a bit involved since we cannot program an hrt while holding the
1007 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
1010 * When we get rescheduled we reprogram the hrtick_timer outside of the
1013 static inline void resched_hrt(struct task_struct *p)
1015 __resched_task(p, TIF_HRTICK_RESCHED);
1018 static inline void resched_rq(struct rq *rq)
1020 unsigned long flags;
1022 spin_lock_irqsave(&rq->lock, flags);
1023 resched_task(rq->curr);
1024 spin_unlock_irqrestore(&rq->lock, flags);
1028 HRTICK_SET, /* re-programm hrtick_timer */
1029 HRTICK_RESET, /* not a new slice */
1034 * - enabled by features
1035 * - hrtimer is actually high res
1037 static inline int hrtick_enabled(struct rq *rq)
1039 if (!sched_feat(HRTICK))
1041 return hrtimer_is_hres_active(&rq->hrtick_timer);
1045 * Called to set the hrtick timer state.
1047 * called with rq->lock held and irqs disabled
1049 static void hrtick_start(struct rq *rq, u64 delay, int reset)
1051 assert_spin_locked(&rq->lock);
1054 * preempt at: now + delay
1057 ktime_add_ns(rq->hrtick_timer.base->get_time(), delay);
1059 * indicate we need to program the timer
1061 __set_bit(HRTICK_SET, &rq->hrtick_flags);
1063 __set_bit(HRTICK_RESET, &rq->hrtick_flags);
1066 * New slices are called from the schedule path and don't need a
1067 * forced reschedule.
1070 resched_hrt(rq->curr);
1073 static void hrtick_clear(struct rq *rq)
1075 if (hrtimer_active(&rq->hrtick_timer))
1076 hrtimer_cancel(&rq->hrtick_timer);
1080 * Update the timer from the possible pending state.
1082 static void hrtick_set(struct rq *rq)
1086 unsigned long flags;
1088 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1090 spin_lock_irqsave(&rq->lock, flags);
1091 set = __test_and_clear_bit(HRTICK_SET, &rq->hrtick_flags);
1092 reset = __test_and_clear_bit(HRTICK_RESET, &rq->hrtick_flags);
1093 time = rq->hrtick_expire;
1094 clear_thread_flag(TIF_HRTICK_RESCHED);
1095 spin_unlock_irqrestore(&rq->lock, flags);
1098 hrtimer_start(&rq->hrtick_timer, time, HRTIMER_MODE_ABS);
1099 if (reset && !hrtimer_active(&rq->hrtick_timer))
1106 * High-resolution timer tick.
1107 * Runs from hardirq context with interrupts disabled.
1109 static enum hrtimer_restart hrtick(struct hrtimer *timer)
1111 struct rq *rq = container_of(timer, struct rq, hrtick_timer);
1113 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
1115 spin_lock(&rq->lock);
1116 __update_rq_clock(rq);
1117 rq->curr->sched_class->task_tick(rq, rq->curr, 1);
1118 spin_unlock(&rq->lock);
1120 return HRTIMER_NORESTART;
1123 static inline void init_rq_hrtick(struct rq *rq)
1125 rq->hrtick_flags = 0;
1126 hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
1127 rq->hrtick_timer.function = hrtick;
1128 rq->hrtick_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
1131 void hrtick_resched(void)
1134 unsigned long flags;
1136 if (!test_thread_flag(TIF_HRTICK_RESCHED))
1139 local_irq_save(flags);
1140 rq = cpu_rq(smp_processor_id());
1142 local_irq_restore(flags);
1145 static inline void hrtick_clear(struct rq *rq)
1149 static inline void hrtick_set(struct rq *rq)
1153 static inline void init_rq_hrtick(struct rq *rq)
1157 void hrtick_resched(void)
1163 * resched_task - mark a task 'to be rescheduled now'.
1165 * On UP this means the setting of the need_resched flag, on SMP it
1166 * might also involve a cross-CPU call to trigger the scheduler on
1171 #ifndef tsk_is_polling
1172 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1175 static void __resched_task(struct task_struct *p, int tif_bit)
1179 assert_spin_locked(&task_rq(p)->lock);
1181 if (unlikely(test_tsk_thread_flag(p, tif_bit)))
1184 set_tsk_thread_flag(p, tif_bit);
1187 if (cpu == smp_processor_id())
1190 /* NEED_RESCHED must be visible before we test polling */
1192 if (!tsk_is_polling(p))
1193 smp_send_reschedule(cpu);
1196 static void resched_cpu(int cpu)
1198 struct rq *rq = cpu_rq(cpu);
1199 unsigned long flags;
1201 if (!spin_trylock_irqsave(&rq->lock, flags))
1203 resched_task(cpu_curr(cpu));
1204 spin_unlock_irqrestore(&rq->lock, flags);
1209 * When add_timer_on() enqueues a timer into the timer wheel of an
1210 * idle CPU then this timer might expire before the next timer event
1211 * which is scheduled to wake up that CPU. In case of a completely
1212 * idle system the next event might even be infinite time into the
1213 * future. wake_up_idle_cpu() ensures that the CPU is woken up and
1214 * leaves the inner idle loop so the newly added timer is taken into
1215 * account when the CPU goes back to idle and evaluates the timer
1216 * wheel for the next timer event.
1218 void wake_up_idle_cpu(int cpu)
1220 struct rq *rq = cpu_rq(cpu);
1222 if (cpu == smp_processor_id())
1226 * This is safe, as this function is called with the timer
1227 * wheel base lock of (cpu) held. When the CPU is on the way
1228 * to idle and has not yet set rq->curr to idle then it will
1229 * be serialized on the timer wheel base lock and take the new
1230 * timer into account automatically.
1232 if (rq->curr != rq->idle)
1236 * We can set TIF_RESCHED on the idle task of the other CPU
1237 * lockless. The worst case is that the other CPU runs the
1238 * idle task through an additional NOOP schedule()
1240 set_tsk_thread_flag(rq->idle, TIF_NEED_RESCHED);
1242 /* NEED_RESCHED must be visible before we test polling */
1244 if (!tsk_is_polling(rq->idle))
1245 smp_send_reschedule(cpu);
1250 static void __resched_task(struct task_struct *p, int tif_bit)
1252 assert_spin_locked(&task_rq(p)->lock);
1253 set_tsk_thread_flag(p, tif_bit);
1257 #if BITS_PER_LONG == 32
1258 # define WMULT_CONST (~0UL)
1260 # define WMULT_CONST (1UL << 32)
1263 #define WMULT_SHIFT 32
1266 * Shift right and round:
1268 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1270 static unsigned long
1271 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1272 struct load_weight *lw)
1276 if (unlikely(!lw->inv_weight))
1277 lw->inv_weight = (WMULT_CONST-lw->weight/2) / (lw->weight+1);
1279 tmp = (u64)delta_exec * weight;
1281 * Check whether we'd overflow the 64-bit multiplication:
1283 if (unlikely(tmp > WMULT_CONST))
1284 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1287 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1289 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1292 static inline unsigned long
1293 calc_delta_fair(unsigned long delta_exec, struct load_weight *lw)
1295 return calc_delta_mine(delta_exec, NICE_0_LOAD, lw);
1298 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1304 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1311 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1312 * of tasks with abnormal "nice" values across CPUs the contribution that
1313 * each task makes to its run queue's load is weighted according to its
1314 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1315 * scaled version of the new time slice allocation that they receive on time
1319 #define WEIGHT_IDLEPRIO 2
1320 #define WMULT_IDLEPRIO (1 << 31)
1323 * Nice levels are multiplicative, with a gentle 10% change for every
1324 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1325 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1326 * that remained on nice 0.
1328 * The "10% effect" is relative and cumulative: from _any_ nice level,
1329 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1330 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1331 * If a task goes up by ~10% and another task goes down by ~10% then
1332 * the relative distance between them is ~25%.)
1334 static const int prio_to_weight[40] = {
1335 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1336 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1337 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1338 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1339 /* 0 */ 1024, 820, 655, 526, 423,
1340 /* 5 */ 335, 272, 215, 172, 137,
1341 /* 10 */ 110, 87, 70, 56, 45,
1342 /* 15 */ 36, 29, 23, 18, 15,
1346 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1348 * In cases where the weight does not change often, we can use the
1349 * precalculated inverse to speed up arithmetics by turning divisions
1350 * into multiplications:
1352 static const u32 prio_to_wmult[40] = {
1353 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1354 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1355 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1356 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1357 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1358 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1359 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1360 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1363 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1366 * runqueue iterator, to support SMP load-balancing between different
1367 * scheduling classes, without having to expose their internal data
1368 * structures to the load-balancing proper:
1370 struct rq_iterator {
1372 struct task_struct *(*start)(void *);
1373 struct task_struct *(*next)(void *);
1377 static unsigned long
1378 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1379 unsigned long max_load_move, struct sched_domain *sd,
1380 enum cpu_idle_type idle, int *all_pinned,
1381 int *this_best_prio, struct rq_iterator *iterator);
1384 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1385 struct sched_domain *sd, enum cpu_idle_type idle,
1386 struct rq_iterator *iterator);
1389 #ifdef CONFIG_CGROUP_CPUACCT
1390 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1392 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1396 static unsigned long source_load(int cpu, int type);
1397 static unsigned long target_load(int cpu, int type);
1398 static unsigned long cpu_avg_load_per_task(int cpu);
1399 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1400 #endif /* CONFIG_SMP */
1402 #include "sched_stats.h"
1403 #include "sched_idletask.c"
1404 #include "sched_fair.c"
1405 #include "sched_rt.c"
1406 #ifdef CONFIG_SCHED_DEBUG
1407 # include "sched_debug.c"
1410 #define sched_class_highest (&rt_sched_class)
1412 static inline void inc_load(struct rq *rq, const struct task_struct *p)
1414 update_load_add(&rq->load, p->se.load.weight);
1417 static inline void dec_load(struct rq *rq, const struct task_struct *p)
1419 update_load_sub(&rq->load, p->se.load.weight);
1422 static void inc_nr_running(struct task_struct *p, struct rq *rq)
1428 static void dec_nr_running(struct task_struct *p, struct rq *rq)
1434 static void set_load_weight(struct task_struct *p)
1436 if (task_has_rt_policy(p)) {
1437 p->se.load.weight = prio_to_weight[0] * 2;
1438 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1443 * SCHED_IDLE tasks get minimal weight:
1445 if (p->policy == SCHED_IDLE) {
1446 p->se.load.weight = WEIGHT_IDLEPRIO;
1447 p->se.load.inv_weight = WMULT_IDLEPRIO;
1451 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1452 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1455 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1457 sched_info_queued(p);
1458 p->sched_class->enqueue_task(rq, p, wakeup);
1462 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1464 p->sched_class->dequeue_task(rq, p, sleep);
1469 * __normal_prio - return the priority that is based on the static prio
1471 static inline int __normal_prio(struct task_struct *p)
1473 return p->static_prio;
1477 * Calculate the expected normal priority: i.e. priority
1478 * without taking RT-inheritance into account. Might be
1479 * boosted by interactivity modifiers. Changes upon fork,
1480 * setprio syscalls, and whenever the interactivity
1481 * estimator recalculates.
1483 static inline int normal_prio(struct task_struct *p)
1487 if (task_has_rt_policy(p))
1488 prio = MAX_RT_PRIO-1 - p->rt_priority;
1490 prio = __normal_prio(p);
1495 * Calculate the current priority, i.e. the priority
1496 * taken into account by the scheduler. This value might
1497 * be boosted by RT tasks, or might be boosted by
1498 * interactivity modifiers. Will be RT if the task got
1499 * RT-boosted. If not then it returns p->normal_prio.
1501 static int effective_prio(struct task_struct *p)
1503 p->normal_prio = normal_prio(p);
1505 * If we are RT tasks or we were boosted to RT priority,
1506 * keep the priority unchanged. Otherwise, update priority
1507 * to the normal priority:
1509 if (!rt_prio(p->prio))
1510 return p->normal_prio;
1515 * activate_task - move a task to the runqueue.
1517 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1519 if (task_contributes_to_load(p))
1520 rq->nr_uninterruptible--;
1522 enqueue_task(rq, p, wakeup);
1523 inc_nr_running(p, rq);
1527 * deactivate_task - remove a task from the runqueue.
1529 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1531 if (task_contributes_to_load(p))
1532 rq->nr_uninterruptible++;
1534 dequeue_task(rq, p, sleep);
1535 dec_nr_running(p, rq);
1539 * task_curr - is this task currently executing on a CPU?
1540 * @p: the task in question.
1542 inline int task_curr(const struct task_struct *p)
1544 return cpu_curr(task_cpu(p)) == p;
1547 /* Used instead of source_load when we know the type == 0 */
1548 unsigned long weighted_cpuload(const int cpu)
1550 return cpu_rq(cpu)->load.weight;
1553 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1555 set_task_rq(p, cpu);
1558 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1559 * successfuly executed on another CPU. We must ensure that updates of
1560 * per-task data have been completed by this moment.
1563 task_thread_info(p)->cpu = cpu;
1567 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1568 const struct sched_class *prev_class,
1569 int oldprio, int running)
1571 if (prev_class != p->sched_class) {
1572 if (prev_class->switched_from)
1573 prev_class->switched_from(rq, p, running);
1574 p->sched_class->switched_to(rq, p, running);
1576 p->sched_class->prio_changed(rq, p, oldprio, running);
1582 * Is this task likely cache-hot:
1585 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
1590 * Buddy candidates are cache hot:
1592 if (sched_feat(CACHE_HOT_BUDDY) && (&p->se == cfs_rq_of(&p->se)->next))
1595 if (p->sched_class != &fair_sched_class)
1598 if (sysctl_sched_migration_cost == -1)
1600 if (sysctl_sched_migration_cost == 0)
1603 delta = now - p->se.exec_start;
1605 return delta < (s64)sysctl_sched_migration_cost;
1609 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1611 int old_cpu = task_cpu(p);
1612 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
1613 struct cfs_rq *old_cfsrq = task_cfs_rq(p),
1614 *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
1617 clock_offset = old_rq->clock - new_rq->clock;
1619 #ifdef CONFIG_SCHEDSTATS
1620 if (p->se.wait_start)
1621 p->se.wait_start -= clock_offset;
1622 if (p->se.sleep_start)
1623 p->se.sleep_start -= clock_offset;
1624 if (p->se.block_start)
1625 p->se.block_start -= clock_offset;
1626 if (old_cpu != new_cpu) {
1627 schedstat_inc(p, se.nr_migrations);
1628 if (task_hot(p, old_rq->clock, NULL))
1629 schedstat_inc(p, se.nr_forced2_migrations);
1632 p->se.vruntime -= old_cfsrq->min_vruntime -
1633 new_cfsrq->min_vruntime;
1635 __set_task_cpu(p, new_cpu);
1638 struct migration_req {
1639 struct list_head list;
1641 struct task_struct *task;
1644 struct completion done;
1648 * The task's runqueue lock must be held.
1649 * Returns true if you have to wait for migration thread.
1652 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1654 struct rq *rq = task_rq(p);
1657 * If the task is not on a runqueue (and not running), then
1658 * it is sufficient to simply update the task's cpu field.
1660 if (!p->se.on_rq && !task_running(rq, p)) {
1661 set_task_cpu(p, dest_cpu);
1665 init_completion(&req->done);
1667 req->dest_cpu = dest_cpu;
1668 list_add(&req->list, &rq->migration_queue);
1674 * wait_task_inactive - wait for a thread to unschedule.
1676 * The caller must ensure that the task *will* unschedule sometime soon,
1677 * else this function might spin for a *long* time. This function can't
1678 * be called with interrupts off, or it may introduce deadlock with
1679 * smp_call_function() if an IPI is sent by the same process we are
1680 * waiting to become inactive.
1682 void wait_task_inactive(struct task_struct *p)
1684 unsigned long flags;
1690 * We do the initial early heuristics without holding
1691 * any task-queue locks at all. We'll only try to get
1692 * the runqueue lock when things look like they will
1698 * If the task is actively running on another CPU
1699 * still, just relax and busy-wait without holding
1702 * NOTE! Since we don't hold any locks, it's not
1703 * even sure that "rq" stays as the right runqueue!
1704 * But we don't care, since "task_running()" will
1705 * return false if the runqueue has changed and p
1706 * is actually now running somewhere else!
1708 while (task_running(rq, p))
1712 * Ok, time to look more closely! We need the rq
1713 * lock now, to be *sure*. If we're wrong, we'll
1714 * just go back and repeat.
1716 rq = task_rq_lock(p, &flags);
1717 running = task_running(rq, p);
1718 on_rq = p->se.on_rq;
1719 task_rq_unlock(rq, &flags);
1722 * Was it really running after all now that we
1723 * checked with the proper locks actually held?
1725 * Oops. Go back and try again..
1727 if (unlikely(running)) {
1733 * It's not enough that it's not actively running,
1734 * it must be off the runqueue _entirely_, and not
1737 * So if it wa still runnable (but just not actively
1738 * running right now), it's preempted, and we should
1739 * yield - it could be a while.
1741 if (unlikely(on_rq)) {
1742 schedule_timeout_uninterruptible(1);
1747 * Ahh, all good. It wasn't running, and it wasn't
1748 * runnable, which means that it will never become
1749 * running in the future either. We're all done!
1756 * kick_process - kick a running thread to enter/exit the kernel
1757 * @p: the to-be-kicked thread
1759 * Cause a process which is running on another CPU to enter
1760 * kernel-mode, without any delay. (to get signals handled.)
1762 * NOTE: this function doesnt have to take the runqueue lock,
1763 * because all it wants to ensure is that the remote task enters
1764 * the kernel. If the IPI races and the task has been migrated
1765 * to another CPU then no harm is done and the purpose has been
1768 void kick_process(struct task_struct *p)
1774 if ((cpu != smp_processor_id()) && task_curr(p))
1775 smp_send_reschedule(cpu);
1780 * Return a low guess at the load of a migration-source cpu weighted
1781 * according to the scheduling class and "nice" value.
1783 * We want to under-estimate the load of migration sources, to
1784 * balance conservatively.
1786 static unsigned long source_load(int cpu, int type)
1788 struct rq *rq = cpu_rq(cpu);
1789 unsigned long total = weighted_cpuload(cpu);
1794 return min(rq->cpu_load[type-1], total);
1798 * Return a high guess at the load of a migration-target cpu weighted
1799 * according to the scheduling class and "nice" value.
1801 static unsigned long target_load(int cpu, int type)
1803 struct rq *rq = cpu_rq(cpu);
1804 unsigned long total = weighted_cpuload(cpu);
1809 return max(rq->cpu_load[type-1], total);
1813 * Return the average load per task on the cpu's run queue
1815 static unsigned long cpu_avg_load_per_task(int cpu)
1817 struct rq *rq = cpu_rq(cpu);
1818 unsigned long total = weighted_cpuload(cpu);
1819 unsigned long n = rq->nr_running;
1821 return n ? total / n : SCHED_LOAD_SCALE;
1825 * find_idlest_group finds and returns the least busy CPU group within the
1828 static struct sched_group *
1829 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1831 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1832 unsigned long min_load = ULONG_MAX, this_load = 0;
1833 int load_idx = sd->forkexec_idx;
1834 int imbalance = 100 + (sd->imbalance_pct-100)/2;
1837 unsigned long load, avg_load;
1841 /* Skip over this group if it has no CPUs allowed */
1842 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
1845 local_group = cpu_isset(this_cpu, group->cpumask);
1847 /* Tally up the load of all CPUs in the group */
1850 for_each_cpu_mask(i, group->cpumask) {
1851 /* Bias balancing toward cpus of our domain */
1853 load = source_load(i, load_idx);
1855 load = target_load(i, load_idx);
1860 /* Adjust by relative CPU power of the group */
1861 avg_load = sg_div_cpu_power(group,
1862 avg_load * SCHED_LOAD_SCALE);
1865 this_load = avg_load;
1867 } else if (avg_load < min_load) {
1868 min_load = avg_load;
1871 } while (group = group->next, group != sd->groups);
1873 if (!idlest || 100*this_load < imbalance*min_load)
1879 * find_idlest_cpu - find the idlest cpu among the cpus in group.
1882 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
1885 unsigned long load, min_load = ULONG_MAX;
1889 /* Traverse only the allowed CPUs */
1890 cpus_and(tmp, group->cpumask, p->cpus_allowed);
1892 for_each_cpu_mask(i, tmp) {
1893 load = weighted_cpuload(i);
1895 if (load < min_load || (load == min_load && i == this_cpu)) {
1905 * sched_balance_self: balance the current task (running on cpu) in domains
1906 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1909 * Balance, ie. select the least loaded group.
1911 * Returns the target CPU number, or the same CPU if no balancing is needed.
1913 * preempt must be disabled.
1915 static int sched_balance_self(int cpu, int flag)
1917 struct task_struct *t = current;
1918 struct sched_domain *tmp, *sd = NULL;
1920 for_each_domain(cpu, tmp) {
1922 * If power savings logic is enabled for a domain, stop there.
1924 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
1926 if (tmp->flags & flag)
1932 struct sched_group *group;
1933 int new_cpu, weight;
1935 if (!(sd->flags & flag)) {
1941 group = find_idlest_group(sd, t, cpu);
1947 new_cpu = find_idlest_cpu(group, t, cpu);
1948 if (new_cpu == -1 || new_cpu == cpu) {
1949 /* Now try balancing at a lower domain level of cpu */
1954 /* Now try balancing at a lower domain level of new_cpu */
1957 weight = cpus_weight(span);
1958 for_each_domain(cpu, tmp) {
1959 if (weight <= cpus_weight(tmp->span))
1961 if (tmp->flags & flag)
1964 /* while loop will break here if sd == NULL */
1970 #endif /* CONFIG_SMP */
1973 * try_to_wake_up - wake up a thread
1974 * @p: the to-be-woken-up thread
1975 * @state: the mask of task states that can be woken
1976 * @sync: do a synchronous wakeup?
1978 * Put it on the run-queue if it's not already there. The "current"
1979 * thread is always on the run-queue (except when the actual
1980 * re-schedule is in progress), and as such you're allowed to do
1981 * the simpler "current->state = TASK_RUNNING" to mark yourself
1982 * runnable without the overhead of this.
1984 * returns failure only if the task is already active.
1986 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
1988 int cpu, orig_cpu, this_cpu, success = 0;
1989 unsigned long flags;
1993 if (!sched_feat(SYNC_WAKEUPS))
1997 rq = task_rq_lock(p, &flags);
1998 old_state = p->state;
1999 if (!(old_state & state))
2007 this_cpu = smp_processor_id();
2010 if (unlikely(task_running(rq, p)))
2013 cpu = p->sched_class->select_task_rq(p, sync);
2014 if (cpu != orig_cpu) {
2015 set_task_cpu(p, cpu);
2016 task_rq_unlock(rq, &flags);
2017 /* might preempt at this point */
2018 rq = task_rq_lock(p, &flags);
2019 old_state = p->state;
2020 if (!(old_state & state))
2025 this_cpu = smp_processor_id();
2029 #ifdef CONFIG_SCHEDSTATS
2030 schedstat_inc(rq, ttwu_count);
2031 if (cpu == this_cpu)
2032 schedstat_inc(rq, ttwu_local);
2034 struct sched_domain *sd;
2035 for_each_domain(this_cpu, sd) {
2036 if (cpu_isset(cpu, sd->span)) {
2037 schedstat_inc(sd, ttwu_wake_remote);
2045 #endif /* CONFIG_SMP */
2046 schedstat_inc(p, se.nr_wakeups);
2048 schedstat_inc(p, se.nr_wakeups_sync);
2049 if (orig_cpu != cpu)
2050 schedstat_inc(p, se.nr_wakeups_migrate);
2051 if (cpu == this_cpu)
2052 schedstat_inc(p, se.nr_wakeups_local);
2054 schedstat_inc(p, se.nr_wakeups_remote);
2055 update_rq_clock(rq);
2056 activate_task(rq, p, 1);
2060 check_preempt_curr(rq, p);
2062 p->state = TASK_RUNNING;
2064 if (p->sched_class->task_wake_up)
2065 p->sched_class->task_wake_up(rq, p);
2068 task_rq_unlock(rq, &flags);
2073 int wake_up_process(struct task_struct *p)
2075 return try_to_wake_up(p, TASK_ALL, 0);
2077 EXPORT_SYMBOL(wake_up_process);
2079 int wake_up_state(struct task_struct *p, unsigned int state)
2081 return try_to_wake_up(p, state, 0);
2085 * Perform scheduler related setup for a newly forked process p.
2086 * p is forked by current.
2088 * __sched_fork() is basic setup used by init_idle() too:
2090 static void __sched_fork(struct task_struct *p)
2092 p->se.exec_start = 0;
2093 p->se.sum_exec_runtime = 0;
2094 p->se.prev_sum_exec_runtime = 0;
2095 p->se.last_wakeup = 0;
2096 p->se.avg_overlap = 0;
2098 #ifdef CONFIG_SCHEDSTATS
2099 p->se.wait_start = 0;
2100 p->se.sum_sleep_runtime = 0;
2101 p->se.sleep_start = 0;
2102 p->se.block_start = 0;
2103 p->se.sleep_max = 0;
2104 p->se.block_max = 0;
2106 p->se.slice_max = 0;
2110 INIT_LIST_HEAD(&p->rt.run_list);
2113 #ifdef CONFIG_PREEMPT_NOTIFIERS
2114 INIT_HLIST_HEAD(&p->preempt_notifiers);
2118 * We mark the process as running here, but have not actually
2119 * inserted it onto the runqueue yet. This guarantees that
2120 * nobody will actually run it, and a signal or other external
2121 * event cannot wake it up and insert it on the runqueue either.
2123 p->state = TASK_RUNNING;
2127 * fork()/clone()-time setup:
2129 void sched_fork(struct task_struct *p, int clone_flags)
2131 int cpu = get_cpu();
2136 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
2138 set_task_cpu(p, cpu);
2141 * Make sure we do not leak PI boosting priority to the child:
2143 p->prio = current->normal_prio;
2144 if (!rt_prio(p->prio))
2145 p->sched_class = &fair_sched_class;
2147 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2148 if (likely(sched_info_on()))
2149 memset(&p->sched_info, 0, sizeof(p->sched_info));
2151 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2154 #ifdef CONFIG_PREEMPT
2155 /* Want to start with kernel preemption disabled. */
2156 task_thread_info(p)->preempt_count = 1;
2162 * wake_up_new_task - wake up a newly created task for the first time.
2164 * This function will do some initial scheduler statistics housekeeping
2165 * that must be done for every newly created context, then puts the task
2166 * on the runqueue and wakes it.
2168 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2170 unsigned long flags;
2173 rq = task_rq_lock(p, &flags);
2174 BUG_ON(p->state != TASK_RUNNING);
2175 update_rq_clock(rq);
2177 p->prio = effective_prio(p);
2179 if (!p->sched_class->task_new || !current->se.on_rq) {
2180 activate_task(rq, p, 0);
2183 * Let the scheduling class do new task startup
2184 * management (if any):
2186 p->sched_class->task_new(rq, p);
2187 inc_nr_running(p, rq);
2189 check_preempt_curr(rq, p);
2191 if (p->sched_class->task_wake_up)
2192 p->sched_class->task_wake_up(rq, p);
2194 task_rq_unlock(rq, &flags);
2197 #ifdef CONFIG_PREEMPT_NOTIFIERS
2200 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2201 * @notifier: notifier struct to register
2203 void preempt_notifier_register(struct preempt_notifier *notifier)
2205 hlist_add_head(¬ifier->link, ¤t->preempt_notifiers);
2207 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2210 * preempt_notifier_unregister - no longer interested in preemption notifications
2211 * @notifier: notifier struct to unregister
2213 * This is safe to call from within a preemption notifier.
2215 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2217 hlist_del(¬ifier->link);
2219 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2221 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2223 struct preempt_notifier *notifier;
2224 struct hlist_node *node;
2226 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2227 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2231 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2232 struct task_struct *next)
2234 struct preempt_notifier *notifier;
2235 struct hlist_node *node;
2237 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2238 notifier->ops->sched_out(notifier, next);
2243 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2248 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2249 struct task_struct *next)
2256 * prepare_task_switch - prepare to switch tasks
2257 * @rq: the runqueue preparing to switch
2258 * @prev: the current task that is being switched out
2259 * @next: the task we are going to switch to.
2261 * This is called with the rq lock held and interrupts off. It must
2262 * be paired with a subsequent finish_task_switch after the context
2265 * prepare_task_switch sets up locking and calls architecture specific
2269 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2270 struct task_struct *next)
2272 fire_sched_out_preempt_notifiers(prev, next);
2273 prepare_lock_switch(rq, next);
2274 prepare_arch_switch(next);
2278 * finish_task_switch - clean up after a task-switch
2279 * @rq: runqueue associated with task-switch
2280 * @prev: the thread we just switched away from.
2282 * finish_task_switch must be called after the context switch, paired
2283 * with a prepare_task_switch call before the context switch.
2284 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2285 * and do any other architecture-specific cleanup actions.
2287 * Note that we may have delayed dropping an mm in context_switch(). If
2288 * so, we finish that here outside of the runqueue lock. (Doing it
2289 * with the lock held can cause deadlocks; see schedule() for
2292 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2293 __releases(rq->lock)
2295 struct mm_struct *mm = rq->prev_mm;
2301 * A task struct has one reference for the use as "current".
2302 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2303 * schedule one last time. The schedule call will never return, and
2304 * the scheduled task must drop that reference.
2305 * The test for TASK_DEAD must occur while the runqueue locks are
2306 * still held, otherwise prev could be scheduled on another cpu, die
2307 * there before we look at prev->state, and then the reference would
2309 * Manfred Spraul <manfred@colorfullife.com>
2311 prev_state = prev->state;
2312 finish_arch_switch(prev);
2313 finish_lock_switch(rq, prev);
2315 if (current->sched_class->post_schedule)
2316 current->sched_class->post_schedule(rq);
2319 fire_sched_in_preempt_notifiers(current);
2322 if (unlikely(prev_state == TASK_DEAD)) {
2324 * Remove function-return probe instances associated with this
2325 * task and put them back on the free list.
2327 kprobe_flush_task(prev);
2328 put_task_struct(prev);
2333 * schedule_tail - first thing a freshly forked thread must call.
2334 * @prev: the thread we just switched away from.
2336 asmlinkage void schedule_tail(struct task_struct *prev)
2337 __releases(rq->lock)
2339 struct rq *rq = this_rq();
2341 finish_task_switch(rq, prev);
2342 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2343 /* In this case, finish_task_switch does not reenable preemption */
2346 if (current->set_child_tid)
2347 put_user(task_pid_vnr(current), current->set_child_tid);
2351 * context_switch - switch to the new MM and the new
2352 * thread's register state.
2355 context_switch(struct rq *rq, struct task_struct *prev,
2356 struct task_struct *next)
2358 struct mm_struct *mm, *oldmm;
2360 prepare_task_switch(rq, prev, next);
2362 oldmm = prev->active_mm;
2364 * For paravirt, this is coupled with an exit in switch_to to
2365 * combine the page table reload and the switch backend into
2368 arch_enter_lazy_cpu_mode();
2370 if (unlikely(!mm)) {
2371 next->active_mm = oldmm;
2372 atomic_inc(&oldmm->mm_count);
2373 enter_lazy_tlb(oldmm, next);
2375 switch_mm(oldmm, mm, next);
2377 if (unlikely(!prev->mm)) {
2378 prev->active_mm = NULL;
2379 rq->prev_mm = oldmm;
2382 * Since the runqueue lock will be released by the next
2383 * task (which is an invalid locking op but in the case
2384 * of the scheduler it's an obvious special-case), so we
2385 * do an early lockdep release here:
2387 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2388 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2391 /* Here we just switch the register state and the stack. */
2392 switch_to(prev, next, prev);
2396 * this_rq must be evaluated again because prev may have moved
2397 * CPUs since it called schedule(), thus the 'rq' on its stack
2398 * frame will be invalid.
2400 finish_task_switch(this_rq(), prev);
2404 * nr_running, nr_uninterruptible and nr_context_switches:
2406 * externally visible scheduler statistics: current number of runnable
2407 * threads, current number of uninterruptible-sleeping threads, total
2408 * number of context switches performed since bootup.
2410 unsigned long nr_running(void)
2412 unsigned long i, sum = 0;
2414 for_each_online_cpu(i)
2415 sum += cpu_rq(i)->nr_running;
2420 unsigned long nr_uninterruptible(void)
2422 unsigned long i, sum = 0;
2424 for_each_possible_cpu(i)
2425 sum += cpu_rq(i)->nr_uninterruptible;
2428 * Since we read the counters lockless, it might be slightly
2429 * inaccurate. Do not allow it to go below zero though:
2431 if (unlikely((long)sum < 0))
2437 unsigned long long nr_context_switches(void)
2440 unsigned long long sum = 0;
2442 for_each_possible_cpu(i)
2443 sum += cpu_rq(i)->nr_switches;
2448 unsigned long nr_iowait(void)
2450 unsigned long i, sum = 0;
2452 for_each_possible_cpu(i)
2453 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2458 unsigned long nr_active(void)
2460 unsigned long i, running = 0, uninterruptible = 0;
2462 for_each_online_cpu(i) {
2463 running += cpu_rq(i)->nr_running;
2464 uninterruptible += cpu_rq(i)->nr_uninterruptible;
2467 if (unlikely((long)uninterruptible < 0))
2468 uninterruptible = 0;
2470 return running + uninterruptible;
2474 * Update rq->cpu_load[] statistics. This function is usually called every
2475 * scheduler tick (TICK_NSEC).
2477 static void update_cpu_load(struct rq *this_rq)
2479 unsigned long this_load = this_rq->load.weight;
2482 this_rq->nr_load_updates++;
2484 /* Update our load: */
2485 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
2486 unsigned long old_load, new_load;
2488 /* scale is effectively 1 << i now, and >> i divides by scale */
2490 old_load = this_rq->cpu_load[i];
2491 new_load = this_load;
2493 * Round up the averaging division if load is increasing. This
2494 * prevents us from getting stuck on 9 if the load is 10, for
2497 if (new_load > old_load)
2498 new_load += scale-1;
2499 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
2506 * double_rq_lock - safely lock two runqueues
2508 * Note this does not disable interrupts like task_rq_lock,
2509 * you need to do so manually before calling.
2511 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
2512 __acquires(rq1->lock)
2513 __acquires(rq2->lock)
2515 BUG_ON(!irqs_disabled());
2517 spin_lock(&rq1->lock);
2518 __acquire(rq2->lock); /* Fake it out ;) */
2521 spin_lock(&rq1->lock);
2522 spin_lock(&rq2->lock);
2524 spin_lock(&rq2->lock);
2525 spin_lock(&rq1->lock);
2528 update_rq_clock(rq1);
2529 update_rq_clock(rq2);
2533 * double_rq_unlock - safely unlock two runqueues
2535 * Note this does not restore interrupts like task_rq_unlock,
2536 * you need to do so manually after calling.
2538 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
2539 __releases(rq1->lock)
2540 __releases(rq2->lock)
2542 spin_unlock(&rq1->lock);
2544 spin_unlock(&rq2->lock);
2546 __release(rq2->lock);
2550 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2552 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
2553 __releases(this_rq->lock)
2554 __acquires(busiest->lock)
2555 __acquires(this_rq->lock)
2559 if (unlikely(!irqs_disabled())) {
2560 /* printk() doesn't work good under rq->lock */
2561 spin_unlock(&this_rq->lock);
2564 if (unlikely(!spin_trylock(&busiest->lock))) {
2565 if (busiest < this_rq) {
2566 spin_unlock(&this_rq->lock);
2567 spin_lock(&busiest->lock);
2568 spin_lock(&this_rq->lock);
2571 spin_lock(&busiest->lock);
2577 * If dest_cpu is allowed for this process, migrate the task to it.
2578 * This is accomplished by forcing the cpu_allowed mask to only
2579 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2580 * the cpu_allowed mask is restored.
2582 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
2584 struct migration_req req;
2585 unsigned long flags;
2588 rq = task_rq_lock(p, &flags);
2589 if (!cpu_isset(dest_cpu, p->cpus_allowed)
2590 || unlikely(cpu_is_offline(dest_cpu)))
2593 /* force the process onto the specified CPU */
2594 if (migrate_task(p, dest_cpu, &req)) {
2595 /* Need to wait for migration thread (might exit: take ref). */
2596 struct task_struct *mt = rq->migration_thread;
2598 get_task_struct(mt);
2599 task_rq_unlock(rq, &flags);
2600 wake_up_process(mt);
2601 put_task_struct(mt);
2602 wait_for_completion(&req.done);
2607 task_rq_unlock(rq, &flags);
2611 * sched_exec - execve() is a valuable balancing opportunity, because at
2612 * this point the task has the smallest effective memory and cache footprint.
2614 void sched_exec(void)
2616 int new_cpu, this_cpu = get_cpu();
2617 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
2619 if (new_cpu != this_cpu)
2620 sched_migrate_task(current, new_cpu);
2624 * pull_task - move a task from a remote runqueue to the local runqueue.
2625 * Both runqueues must be locked.
2627 static void pull_task(struct rq *src_rq, struct task_struct *p,
2628 struct rq *this_rq, int this_cpu)
2630 deactivate_task(src_rq, p, 0);
2631 set_task_cpu(p, this_cpu);
2632 activate_task(this_rq, p, 0);
2634 * Note that idle threads have a prio of MAX_PRIO, for this test
2635 * to be always true for them.
2637 check_preempt_curr(this_rq, p);
2641 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2644 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
2645 struct sched_domain *sd, enum cpu_idle_type idle,
2649 * We do not migrate tasks that are:
2650 * 1) running (obviously), or
2651 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2652 * 3) are cache-hot on their current CPU.
2654 if (!cpu_isset(this_cpu, p->cpus_allowed)) {
2655 schedstat_inc(p, se.nr_failed_migrations_affine);
2660 if (task_running(rq, p)) {
2661 schedstat_inc(p, se.nr_failed_migrations_running);
2666 * Aggressive migration if:
2667 * 1) task is cache cold, or
2668 * 2) too many balance attempts have failed.
2671 if (!task_hot(p, rq->clock, sd) ||
2672 sd->nr_balance_failed > sd->cache_nice_tries) {
2673 #ifdef CONFIG_SCHEDSTATS
2674 if (task_hot(p, rq->clock, sd)) {
2675 schedstat_inc(sd, lb_hot_gained[idle]);
2676 schedstat_inc(p, se.nr_forced_migrations);
2682 if (task_hot(p, rq->clock, sd)) {
2683 schedstat_inc(p, se.nr_failed_migrations_hot);
2689 static unsigned long
2690 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2691 unsigned long max_load_move, struct sched_domain *sd,
2692 enum cpu_idle_type idle, int *all_pinned,
2693 int *this_best_prio, struct rq_iterator *iterator)
2695 int loops = 0, pulled = 0, pinned = 0, skip_for_load;
2696 struct task_struct *p;
2697 long rem_load_move = max_load_move;
2699 if (max_load_move == 0)
2705 * Start the load-balancing iterator:
2707 p = iterator->start(iterator->arg);
2709 if (!p || loops++ > sysctl_sched_nr_migrate)
2712 * To help distribute high priority tasks across CPUs we don't
2713 * skip a task if it will be the highest priority task (i.e. smallest
2714 * prio value) on its new queue regardless of its load weight
2716 skip_for_load = (p->se.load.weight >> 1) > rem_load_move +
2717 SCHED_LOAD_SCALE_FUZZ;
2718 if ((skip_for_load && p->prio >= *this_best_prio) ||
2719 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
2720 p = iterator->next(iterator->arg);
2724 pull_task(busiest, p, this_rq, this_cpu);
2726 rem_load_move -= p->se.load.weight;
2729 * We only want to steal up to the prescribed amount of weighted load.
2731 if (rem_load_move > 0) {
2732 if (p->prio < *this_best_prio)
2733 *this_best_prio = p->prio;
2734 p = iterator->next(iterator->arg);
2739 * Right now, this is one of only two places pull_task() is called,
2740 * so we can safely collect pull_task() stats here rather than
2741 * inside pull_task().
2743 schedstat_add(sd, lb_gained[idle], pulled);
2746 *all_pinned = pinned;
2748 return max_load_move - rem_load_move;
2752 * move_tasks tries to move up to max_load_move weighted load from busiest to
2753 * this_rq, as part of a balancing operation within domain "sd".
2754 * Returns 1 if successful and 0 otherwise.
2756 * Called with both runqueues locked.
2758 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2759 unsigned long max_load_move,
2760 struct sched_domain *sd, enum cpu_idle_type idle,
2763 const struct sched_class *class = sched_class_highest;
2764 unsigned long total_load_moved = 0;
2765 int this_best_prio = this_rq->curr->prio;
2769 class->load_balance(this_rq, this_cpu, busiest,
2770 max_load_move - total_load_moved,
2771 sd, idle, all_pinned, &this_best_prio);
2772 class = class->next;
2773 } while (class && max_load_move > total_load_moved);
2775 return total_load_moved > 0;
2779 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
2780 struct sched_domain *sd, enum cpu_idle_type idle,
2781 struct rq_iterator *iterator)
2783 struct task_struct *p = iterator->start(iterator->arg);
2787 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
2788 pull_task(busiest, p, this_rq, this_cpu);
2790 * Right now, this is only the second place pull_task()
2791 * is called, so we can safely collect pull_task()
2792 * stats here rather than inside pull_task().
2794 schedstat_inc(sd, lb_gained[idle]);
2798 p = iterator->next(iterator->arg);
2805 * move_one_task tries to move exactly one task from busiest to this_rq, as
2806 * part of active balancing operations within "domain".
2807 * Returns 1 if successful and 0 otherwise.
2809 * Called with both runqueues locked.
2811 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
2812 struct sched_domain *sd, enum cpu_idle_type idle)
2814 const struct sched_class *class;
2816 for (class = sched_class_highest; class; class = class->next)
2817 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
2824 * find_busiest_group finds and returns the busiest CPU group within the
2825 * domain. It calculates and returns the amount of weighted load which
2826 * should be moved to restore balance via the imbalance parameter.
2828 static struct sched_group *
2829 find_busiest_group(struct sched_domain *sd, int this_cpu,
2830 unsigned long *imbalance, enum cpu_idle_type idle,
2831 int *sd_idle, cpumask_t *cpus, int *balance)
2833 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2834 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2835 unsigned long max_pull;
2836 unsigned long busiest_load_per_task, busiest_nr_running;
2837 unsigned long this_load_per_task, this_nr_running;
2838 int load_idx, group_imb = 0;
2839 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2840 int power_savings_balance = 1;
2841 unsigned long leader_nr_running = 0, min_load_per_task = 0;
2842 unsigned long min_nr_running = ULONG_MAX;
2843 struct sched_group *group_min = NULL, *group_leader = NULL;
2846 max_load = this_load = total_load = total_pwr = 0;
2847 busiest_load_per_task = busiest_nr_running = 0;
2848 this_load_per_task = this_nr_running = 0;
2849 if (idle == CPU_NOT_IDLE)
2850 load_idx = sd->busy_idx;
2851 else if (idle == CPU_NEWLY_IDLE)
2852 load_idx = sd->newidle_idx;
2854 load_idx = sd->idle_idx;
2857 unsigned long load, group_capacity, max_cpu_load, min_cpu_load;
2860 int __group_imb = 0;
2861 unsigned int balance_cpu = -1, first_idle_cpu = 0;
2862 unsigned long sum_nr_running, sum_weighted_load;
2864 local_group = cpu_isset(this_cpu, group->cpumask);
2867 balance_cpu = first_cpu(group->cpumask);
2869 /* Tally up the load of all CPUs in the group */
2870 sum_weighted_load = sum_nr_running = avg_load = 0;
2872 min_cpu_load = ~0UL;
2874 for_each_cpu_mask(i, group->cpumask) {
2877 if (!cpu_isset(i, *cpus))
2882 if (*sd_idle && rq->nr_running)
2885 /* Bias balancing toward cpus of our domain */
2887 if (idle_cpu(i) && !first_idle_cpu) {
2892 load = target_load(i, load_idx);
2894 load = source_load(i, load_idx);
2895 if (load > max_cpu_load)
2896 max_cpu_load = load;
2897 if (min_cpu_load > load)
2898 min_cpu_load = load;
2902 sum_nr_running += rq->nr_running;
2903 sum_weighted_load += weighted_cpuload(i);
2907 * First idle cpu or the first cpu(busiest) in this sched group
2908 * is eligible for doing load balancing at this and above
2909 * domains. In the newly idle case, we will allow all the cpu's
2910 * to do the newly idle load balance.
2912 if (idle != CPU_NEWLY_IDLE && local_group &&
2913 balance_cpu != this_cpu && balance) {
2918 total_load += avg_load;
2919 total_pwr += group->__cpu_power;
2921 /* Adjust by relative CPU power of the group */
2922 avg_load = sg_div_cpu_power(group,
2923 avg_load * SCHED_LOAD_SCALE);
2925 if ((max_cpu_load - min_cpu_load) > SCHED_LOAD_SCALE)
2928 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
2931 this_load = avg_load;
2933 this_nr_running = sum_nr_running;
2934 this_load_per_task = sum_weighted_load;
2935 } else if (avg_load > max_load &&
2936 (sum_nr_running > group_capacity || __group_imb)) {
2937 max_load = avg_load;
2939 busiest_nr_running = sum_nr_running;
2940 busiest_load_per_task = sum_weighted_load;
2941 group_imb = __group_imb;
2944 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2946 * Busy processors will not participate in power savings
2949 if (idle == CPU_NOT_IDLE ||
2950 !(sd->flags & SD_POWERSAVINGS_BALANCE))
2954 * If the local group is idle or completely loaded
2955 * no need to do power savings balance at this domain
2957 if (local_group && (this_nr_running >= group_capacity ||
2959 power_savings_balance = 0;
2962 * If a group is already running at full capacity or idle,
2963 * don't include that group in power savings calculations
2965 if (!power_savings_balance || sum_nr_running >= group_capacity
2970 * Calculate the group which has the least non-idle load.
2971 * This is the group from where we need to pick up the load
2974 if ((sum_nr_running < min_nr_running) ||
2975 (sum_nr_running == min_nr_running &&
2976 first_cpu(group->cpumask) <
2977 first_cpu(group_min->cpumask))) {
2979 min_nr_running = sum_nr_running;
2980 min_load_per_task = sum_weighted_load /
2985 * Calculate the group which is almost near its
2986 * capacity but still has some space to pick up some load
2987 * from other group and save more power
2989 if (sum_nr_running <= group_capacity - 1) {
2990 if (sum_nr_running > leader_nr_running ||
2991 (sum_nr_running == leader_nr_running &&
2992 first_cpu(group->cpumask) >
2993 first_cpu(group_leader->cpumask))) {
2994 group_leader = group;
2995 leader_nr_running = sum_nr_running;
3000 group = group->next;
3001 } while (group != sd->groups);
3003 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
3006 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
3008 if (this_load >= avg_load ||
3009 100*max_load <= sd->imbalance_pct*this_load)
3012 busiest_load_per_task /= busiest_nr_running;
3014 busiest_load_per_task = min(busiest_load_per_task, avg_load);
3017 * We're trying to get all the cpus to the average_load, so we don't
3018 * want to push ourselves above the average load, nor do we wish to
3019 * reduce the max loaded cpu below the average load, as either of these
3020 * actions would just result in more rebalancing later, and ping-pong
3021 * tasks around. Thus we look for the minimum possible imbalance.
3022 * Negative imbalances (*we* are more loaded than anyone else) will
3023 * be counted as no imbalance for these purposes -- we can't fix that
3024 * by pulling tasks to us. Be careful of negative numbers as they'll
3025 * appear as very large values with unsigned longs.
3027 if (max_load <= busiest_load_per_task)
3031 * In the presence of smp nice balancing, certain scenarios can have
3032 * max load less than avg load(as we skip the groups at or below
3033 * its cpu_power, while calculating max_load..)
3035 if (max_load < avg_load) {
3037 goto small_imbalance;
3040 /* Don't want to pull so many tasks that a group would go idle */
3041 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
3043 /* How much load to actually move to equalise the imbalance */
3044 *imbalance = min(max_pull * busiest->__cpu_power,
3045 (avg_load - this_load) * this->__cpu_power)
3049 * if *imbalance is less than the average load per runnable task
3050 * there is no gaurantee that any tasks will be moved so we'll have
3051 * a think about bumping its value to force at least one task to be
3054 if (*imbalance < busiest_load_per_task) {
3055 unsigned long tmp, pwr_now, pwr_move;
3059 pwr_move = pwr_now = 0;
3061 if (this_nr_running) {
3062 this_load_per_task /= this_nr_running;
3063 if (busiest_load_per_task > this_load_per_task)
3066 this_load_per_task = SCHED_LOAD_SCALE;
3068 if (max_load - this_load + SCHED_LOAD_SCALE_FUZZ >=
3069 busiest_load_per_task * imbn) {
3070 *imbalance = busiest_load_per_task;
3075 * OK, we don't have enough imbalance to justify moving tasks,
3076 * however we may be able to increase total CPU power used by
3080 pwr_now += busiest->__cpu_power *
3081 min(busiest_load_per_task, max_load);
3082 pwr_now += this->__cpu_power *
3083 min(this_load_per_task, this_load);
3084 pwr_now /= SCHED_LOAD_SCALE;
3086 /* Amount of load we'd subtract */
3087 tmp = sg_div_cpu_power(busiest,
3088 busiest_load_per_task * SCHED_LOAD_SCALE);
3090 pwr_move += busiest->__cpu_power *
3091 min(busiest_load_per_task, max_load - tmp);
3093 /* Amount of load we'd add */
3094 if (max_load * busiest->__cpu_power <
3095 busiest_load_per_task * SCHED_LOAD_SCALE)
3096 tmp = sg_div_cpu_power(this,
3097 max_load * busiest->__cpu_power);
3099 tmp = sg_div_cpu_power(this,
3100 busiest_load_per_task * SCHED_LOAD_SCALE);
3101 pwr_move += this->__cpu_power *
3102 min(this_load_per_task, this_load + tmp);
3103 pwr_move /= SCHED_LOAD_SCALE;
3105 /* Move if we gain throughput */
3106 if (pwr_move > pwr_now)
3107 *imbalance = busiest_load_per_task;
3113 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
3114 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
3117 if (this == group_leader && group_leader != group_min) {
3118 *imbalance = min_load_per_task;
3128 * find_busiest_queue - find the busiest runqueue among the cpus in group.
3131 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
3132 unsigned long imbalance, cpumask_t *cpus)
3134 struct rq *busiest = NULL, *rq;
3135 unsigned long max_load = 0;
3138 for_each_cpu_mask(i, group->cpumask) {
3141 if (!cpu_isset(i, *cpus))
3145 wl = weighted_cpuload(i);
3147 if (rq->nr_running == 1 && wl > imbalance)
3150 if (wl > max_load) {
3160 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
3161 * so long as it is large enough.
3163 #define MAX_PINNED_INTERVAL 512
3166 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3167 * tasks if there is an imbalance.
3169 static int load_balance(int this_cpu, struct rq *this_rq,
3170 struct sched_domain *sd, enum cpu_idle_type idle,
3173 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
3174 struct sched_group *group;
3175 unsigned long imbalance;
3177 cpumask_t cpus = CPU_MASK_ALL;
3178 unsigned long flags;
3181 * When power savings policy is enabled for the parent domain, idle
3182 * sibling can pick up load irrespective of busy siblings. In this case,
3183 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3184 * portraying it as CPU_NOT_IDLE.
3186 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
3187 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3190 schedstat_inc(sd, lb_count[idle]);
3193 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
3200 schedstat_inc(sd, lb_nobusyg[idle]);
3204 busiest = find_busiest_queue(group, idle, imbalance, &cpus);
3206 schedstat_inc(sd, lb_nobusyq[idle]);
3210 BUG_ON(busiest == this_rq);
3212 schedstat_add(sd, lb_imbalance[idle], imbalance);
3215 if (busiest->nr_running > 1) {
3217 * Attempt to move tasks. If find_busiest_group has found
3218 * an imbalance but busiest->nr_running <= 1, the group is
3219 * still unbalanced. ld_moved simply stays zero, so it is
3220 * correctly treated as an imbalance.
3222 local_irq_save(flags);
3223 double_rq_lock(this_rq, busiest);
3224 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3225 imbalance, sd, idle, &all_pinned);
3226 double_rq_unlock(this_rq, busiest);
3227 local_irq_restore(flags);
3230 * some other cpu did the load balance for us.
3232 if (ld_moved && this_cpu != smp_processor_id())
3233 resched_cpu(this_cpu);
3235 /* All tasks on this runqueue were pinned by CPU affinity */
3236 if (unlikely(all_pinned)) {
3237 cpu_clear(cpu_of(busiest), cpus);
3238 if (!cpus_empty(cpus))
3245 schedstat_inc(sd, lb_failed[idle]);
3246 sd->nr_balance_failed++;
3248 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
3250 spin_lock_irqsave(&busiest->lock, flags);
3252 /* don't kick the migration_thread, if the curr
3253 * task on busiest cpu can't be moved to this_cpu
3255 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
3256 spin_unlock_irqrestore(&busiest->lock, flags);
3258 goto out_one_pinned;
3261 if (!busiest->active_balance) {
3262 busiest->active_balance = 1;
3263 busiest->push_cpu = this_cpu;
3266 spin_unlock_irqrestore(&busiest->lock, flags);
3268 wake_up_process(busiest->migration_thread);
3271 * We've kicked active balancing, reset the failure
3274 sd->nr_balance_failed = sd->cache_nice_tries+1;
3277 sd->nr_balance_failed = 0;
3279 if (likely(!active_balance)) {
3280 /* We were unbalanced, so reset the balancing interval */
3281 sd->balance_interval = sd->min_interval;
3284 * If we've begun active balancing, start to back off. This
3285 * case may not be covered by the all_pinned logic if there
3286 * is only 1 task on the busy runqueue (because we don't call
3289 if (sd->balance_interval < sd->max_interval)
3290 sd->balance_interval *= 2;
3293 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3294 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3299 schedstat_inc(sd, lb_balanced[idle]);
3301 sd->nr_balance_failed = 0;
3304 /* tune up the balancing interval */
3305 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
3306 (sd->balance_interval < sd->max_interval))
3307 sd->balance_interval *= 2;
3309 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3310 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3316 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3317 * tasks if there is an imbalance.
3319 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3320 * this_rq is locked.
3323 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
3325 struct sched_group *group;
3326 struct rq *busiest = NULL;
3327 unsigned long imbalance;
3331 cpumask_t cpus = CPU_MASK_ALL;
3334 * When power savings policy is enabled for the parent domain, idle
3335 * sibling can pick up load irrespective of busy siblings. In this case,
3336 * let the state of idle sibling percolate up as IDLE, instead of
3337 * portraying it as CPU_NOT_IDLE.
3339 if (sd->flags & SD_SHARE_CPUPOWER &&
3340 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3343 schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
3345 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
3346 &sd_idle, &cpus, NULL);
3348 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
3352 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance,
3355 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
3359 BUG_ON(busiest == this_rq);
3361 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
3364 if (busiest->nr_running > 1) {
3365 /* Attempt to move tasks */
3366 double_lock_balance(this_rq, busiest);
3367 /* this_rq->clock is already updated */
3368 update_rq_clock(busiest);
3369 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3370 imbalance, sd, CPU_NEWLY_IDLE,
3372 spin_unlock(&busiest->lock);
3374 if (unlikely(all_pinned)) {
3375 cpu_clear(cpu_of(busiest), cpus);
3376 if (!cpus_empty(cpus))
3382 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
3383 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3384 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3387 sd->nr_balance_failed = 0;
3392 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
3393 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3394 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3396 sd->nr_balance_failed = 0;
3402 * idle_balance is called by schedule() if this_cpu is about to become
3403 * idle. Attempts to pull tasks from other CPUs.
3405 static void idle_balance(int this_cpu, struct rq *this_rq)
3407 struct sched_domain *sd;
3408 int pulled_task = -1;
3409 unsigned long next_balance = jiffies + HZ;
3411 for_each_domain(this_cpu, sd) {
3412 unsigned long interval;
3414 if (!(sd->flags & SD_LOAD_BALANCE))
3417 if (sd->flags & SD_BALANCE_NEWIDLE)
3418 /* If we've pulled tasks over stop searching: */
3419 pulled_task = load_balance_newidle(this_cpu,
3422 interval = msecs_to_jiffies(sd->balance_interval);
3423 if (time_after(next_balance, sd->last_balance + interval))
3424 next_balance = sd->last_balance + interval;
3428 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
3430 * We are going idle. next_balance may be set based on
3431 * a busy processor. So reset next_balance.
3433 this_rq->next_balance = next_balance;
3438 * active_load_balance is run by migration threads. It pushes running tasks
3439 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3440 * running on each physical CPU where possible, and avoids physical /
3441 * logical imbalances.
3443 * Called with busiest_rq locked.
3445 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
3447 int target_cpu = busiest_rq->push_cpu;
3448 struct sched_domain *sd;
3449 struct rq *target_rq;
3451 /* Is there any task to move? */
3452 if (busiest_rq->nr_running <= 1)
3455 target_rq = cpu_rq(target_cpu);
3458 * This condition is "impossible", if it occurs
3459 * we need to fix it. Originally reported by
3460 * Bjorn Helgaas on a 128-cpu setup.
3462 BUG_ON(busiest_rq == target_rq);
3464 /* move a task from busiest_rq to target_rq */
3465 double_lock_balance(busiest_rq, target_rq);
3466 update_rq_clock(busiest_rq);
3467 update_rq_clock(target_rq);
3469 /* Search for an sd spanning us and the target CPU. */
3470 for_each_domain(target_cpu, sd) {
3471 if ((sd->flags & SD_LOAD_BALANCE) &&
3472 cpu_isset(busiest_cpu, sd->span))
3477 schedstat_inc(sd, alb_count);
3479 if (move_one_task(target_rq, target_cpu, busiest_rq,
3481 schedstat_inc(sd, alb_pushed);
3483 schedstat_inc(sd, alb_failed);
3485 spin_unlock(&target_rq->lock);
3490 atomic_t load_balancer;
3492 } nohz ____cacheline_aligned = {
3493 .load_balancer = ATOMIC_INIT(-1),
3494 .cpu_mask = CPU_MASK_NONE,
3498 * This routine will try to nominate the ilb (idle load balancing)
3499 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3500 * load balancing on behalf of all those cpus. If all the cpus in the system
3501 * go into this tickless mode, then there will be no ilb owner (as there is
3502 * no need for one) and all the cpus will sleep till the next wakeup event
3505 * For the ilb owner, tick is not stopped. And this tick will be used
3506 * for idle load balancing. ilb owner will still be part of
3509 * While stopping the tick, this cpu will become the ilb owner if there
3510 * is no other owner. And will be the owner till that cpu becomes busy
3511 * or if all cpus in the system stop their ticks at which point
3512 * there is no need for ilb owner.
3514 * When the ilb owner becomes busy, it nominates another owner, during the
3515 * next busy scheduler_tick()
3517 int select_nohz_load_balancer(int stop_tick)
3519 int cpu = smp_processor_id();
3522 cpu_set(cpu, nohz.cpu_mask);
3523 cpu_rq(cpu)->in_nohz_recently = 1;
3526 * If we are going offline and still the leader, give up!
3528 if (cpu_is_offline(cpu) &&
3529 atomic_read(&nohz.load_balancer) == cpu) {
3530 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3535 /* time for ilb owner also to sleep */
3536 if (cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3537 if (atomic_read(&nohz.load_balancer) == cpu)
3538 atomic_set(&nohz.load_balancer, -1);
3542 if (atomic_read(&nohz.load_balancer) == -1) {
3543 /* make me the ilb owner */
3544 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
3546 } else if (atomic_read(&nohz.load_balancer) == cpu)
3549 if (!cpu_isset(cpu, nohz.cpu_mask))
3552 cpu_clear(cpu, nohz.cpu_mask);
3554 if (atomic_read(&nohz.load_balancer) == cpu)
3555 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3562 static DEFINE_SPINLOCK(balancing);
3565 * It checks each scheduling domain to see if it is due to be balanced,
3566 * and initiates a balancing operation if so.
3568 * Balancing parameters are set up in arch_init_sched_domains.
3570 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
3573 struct rq *rq = cpu_rq(cpu);
3574 unsigned long interval;
3575 struct sched_domain *sd;
3576 /* Earliest time when we have to do rebalance again */
3577 unsigned long next_balance = jiffies + 60*HZ;
3578 int update_next_balance = 0;
3580 for_each_domain(cpu, sd) {
3581 if (!(sd->flags & SD_LOAD_BALANCE))
3584 interval = sd->balance_interval;
3585 if (idle != CPU_IDLE)
3586 interval *= sd->busy_factor;
3588 /* scale ms to jiffies */
3589 interval = msecs_to_jiffies(interval);
3590 if (unlikely(!interval))
3592 if (interval > HZ*NR_CPUS/10)
3593 interval = HZ*NR_CPUS/10;
3596 if (sd->flags & SD_SERIALIZE) {
3597 if (!spin_trylock(&balancing))
3601 if (time_after_eq(jiffies, sd->last_balance + interval)) {
3602 if (load_balance(cpu, rq, sd, idle, &balance)) {
3604 * We've pulled tasks over so either we're no
3605 * longer idle, or one of our SMT siblings is
3608 idle = CPU_NOT_IDLE;
3610 sd->last_balance = jiffies;
3612 if (sd->flags & SD_SERIALIZE)
3613 spin_unlock(&balancing);
3615 if (time_after(next_balance, sd->last_balance + interval)) {
3616 next_balance = sd->last_balance + interval;
3617 update_next_balance = 1;
3621 * Stop the load balance at this level. There is another
3622 * CPU in our sched group which is doing load balancing more
3630 * next_balance will be updated only when there is a need.
3631 * When the cpu is attached to null domain for ex, it will not be
3634 if (likely(update_next_balance))
3635 rq->next_balance = next_balance;
3639 * run_rebalance_domains is triggered when needed from the scheduler tick.
3640 * In CONFIG_NO_HZ case, the idle load balance owner will do the
3641 * rebalancing for all the cpus for whom scheduler ticks are stopped.
3643 static void run_rebalance_domains(struct softirq_action *h)
3645 int this_cpu = smp_processor_id();
3646 struct rq *this_rq = cpu_rq(this_cpu);
3647 enum cpu_idle_type idle = this_rq->idle_at_tick ?
3648 CPU_IDLE : CPU_NOT_IDLE;
3650 rebalance_domains(this_cpu, idle);
3654 * If this cpu is the owner for idle load balancing, then do the
3655 * balancing on behalf of the other idle cpus whose ticks are
3658 if (this_rq->idle_at_tick &&
3659 atomic_read(&nohz.load_balancer) == this_cpu) {
3660 cpumask_t cpus = nohz.cpu_mask;
3664 cpu_clear(this_cpu, cpus);
3665 for_each_cpu_mask(balance_cpu, cpus) {
3667 * If this cpu gets work to do, stop the load balancing
3668 * work being done for other cpus. Next load
3669 * balancing owner will pick it up.
3674 rebalance_domains(balance_cpu, CPU_IDLE);
3676 rq = cpu_rq(balance_cpu);
3677 if (time_after(this_rq->next_balance, rq->next_balance))
3678 this_rq->next_balance = rq->next_balance;
3685 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
3687 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
3688 * idle load balancing owner or decide to stop the periodic load balancing,
3689 * if the whole system is idle.
3691 static inline void trigger_load_balance(struct rq *rq, int cpu)
3695 * If we were in the nohz mode recently and busy at the current
3696 * scheduler tick, then check if we need to nominate new idle
3699 if (rq->in_nohz_recently && !rq->idle_at_tick) {
3700 rq->in_nohz_recently = 0;
3702 if (atomic_read(&nohz.load_balancer) == cpu) {
3703 cpu_clear(cpu, nohz.cpu_mask);
3704 atomic_set(&nohz.load_balancer, -1);
3707 if (atomic_read(&nohz.load_balancer) == -1) {
3709 * simple selection for now: Nominate the
3710 * first cpu in the nohz list to be the next
3713 * TBD: Traverse the sched domains and nominate
3714 * the nearest cpu in the nohz.cpu_mask.
3716 int ilb = first_cpu(nohz.cpu_mask);
3724 * If this cpu is idle and doing idle load balancing for all the
3725 * cpus with ticks stopped, is it time for that to stop?
3727 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
3728 cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3734 * If this cpu is idle and the idle load balancing is done by
3735 * someone else, then no need raise the SCHED_SOFTIRQ
3737 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
3738 cpu_isset(cpu, nohz.cpu_mask))
3741 if (time_after_eq(jiffies, rq->next_balance))
3742 raise_softirq(SCHED_SOFTIRQ);
3745 #else /* CONFIG_SMP */
3748 * on UP we do not need to balance between CPUs:
3750 static inline void idle_balance(int cpu, struct rq *rq)
3756 DEFINE_PER_CPU(struct kernel_stat, kstat);
3758 EXPORT_PER_CPU_SYMBOL(kstat);
3761 * Return p->sum_exec_runtime plus any more ns on the sched_clock
3762 * that have not yet been banked in case the task is currently running.
3764 unsigned long long task_sched_runtime(struct task_struct *p)
3766 unsigned long flags;
3770 rq = task_rq_lock(p, &flags);
3771 ns = p->se.sum_exec_runtime;
3772 if (task_current(rq, p)) {
3773 update_rq_clock(rq);
3774 delta_exec = rq->clock - p->se.exec_start;
3775 if ((s64)delta_exec > 0)
3778 task_rq_unlock(rq, &flags);
3784 * Account user cpu time to a process.
3785 * @p: the process that the cpu time gets accounted to
3786 * @cputime: the cpu time spent in user space since the last update
3788 void account_user_time(struct task_struct *p, cputime_t cputime)
3790 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3793 p->utime = cputime_add(p->utime, cputime);
3795 /* Add user time to cpustat. */
3796 tmp = cputime_to_cputime64(cputime);
3797 if (TASK_NICE(p) > 0)
3798 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3800 cpustat->user = cputime64_add(cpustat->user, tmp);
3804 * Account guest cpu time to a process.
3805 * @p: the process that the cpu time gets accounted to
3806 * @cputime: the cpu time spent in virtual machine since the last update
3808 static void account_guest_time(struct task_struct *p, cputime_t cputime)
3811 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3813 tmp = cputime_to_cputime64(cputime);
3815 p->utime = cputime_add(p->utime, cputime);
3816 p->gtime = cputime_add(p->gtime, cputime);
3818 cpustat->user = cputime64_add(cpustat->user, tmp);
3819 cpustat->guest = cputime64_add(cpustat->guest, tmp);
3823 * Account scaled user cpu time to a process.
3824 * @p: the process that the cpu time gets accounted to
3825 * @cputime: the cpu time spent in user space since the last update
3827 void account_user_time_scaled(struct task_struct *p, cputime_t cputime)
3829 p->utimescaled = cputime_add(p->utimescaled, cputime);
3833 * Account system cpu time to a process.
3834 * @p: the process that the cpu time gets accounted to
3835 * @hardirq_offset: the offset to subtract from hardirq_count()
3836 * @cputime: the cpu time spent in kernel space since the last update
3838 void account_system_time(struct task_struct *p, int hardirq_offset,
3841 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3842 struct rq *rq = this_rq();
3845 if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0))
3846 return account_guest_time(p, cputime);
3848 p->stime = cputime_add(p->stime, cputime);
3850 /* Add system time to cpustat. */
3851 tmp = cputime_to_cputime64(cputime);
3852 if (hardirq_count() - hardirq_offset)
3853 cpustat->irq = cputime64_add(cpustat->irq, tmp);
3854 else if (softirq_count())
3855 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
3856 else if (p != rq->idle)
3857 cpustat->system = cputime64_add(cpustat->system, tmp);
3858 else if (atomic_read(&rq->nr_iowait) > 0)
3859 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3861 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3862 /* Account for system time used */
3863 acct_update_integrals(p);
3867 * Account scaled system cpu time to a process.
3868 * @p: the process that the cpu time gets accounted to
3869 * @hardirq_offset: the offset to subtract from hardirq_count()
3870 * @cputime: the cpu time spent in kernel space since the last update
3872 void account_system_time_scaled(struct task_struct *p, cputime_t cputime)
3874 p->stimescaled = cputime_add(p->stimescaled, cputime);
3878 * Account for involuntary wait time.
3879 * @p: the process from which the cpu time has been stolen
3880 * @steal: the cpu time spent in involuntary wait
3882 void account_steal_time(struct task_struct *p, cputime_t steal)
3884 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3885 cputime64_t tmp = cputime_to_cputime64(steal);
3886 struct rq *rq = this_rq();
3888 if (p == rq->idle) {
3889 p->stime = cputime_add(p->stime, steal);
3890 if (atomic_read(&rq->nr_iowait) > 0)
3891 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3893 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3895 cpustat->steal = cputime64_add(cpustat->steal, tmp);
3899 * This function gets called by the timer code, with HZ frequency.
3900 * We call it with interrupts disabled.
3902 * It also gets called by the fork code, when changing the parent's
3905 void scheduler_tick(void)
3907 int cpu = smp_processor_id();
3908 struct rq *rq = cpu_rq(cpu);
3909 struct task_struct *curr = rq->curr;
3910 u64 next_tick = rq->tick_timestamp + TICK_NSEC;
3912 spin_lock(&rq->lock);
3913 __update_rq_clock(rq);
3915 * Let rq->clock advance by at least TICK_NSEC:
3917 if (unlikely(rq->clock < next_tick)) {
3918 rq->clock = next_tick;
3919 rq->clock_underflows++;
3921 rq->tick_timestamp = rq->clock;
3922 update_last_tick_seen(rq);
3923 update_cpu_load(rq);
3924 curr->sched_class->task_tick(rq, curr, 0);
3925 spin_unlock(&rq->lock);
3928 rq->idle_at_tick = idle_cpu(cpu);
3929 trigger_load_balance(rq, cpu);
3933 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3935 void __kprobes add_preempt_count(int val)
3940 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3942 preempt_count() += val;
3944 * Spinlock count overflowing soon?
3946 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3949 EXPORT_SYMBOL(add_preempt_count);
3951 void __kprobes sub_preempt_count(int val)
3956 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3959 * Is the spinlock portion underflowing?
3961 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3962 !(preempt_count() & PREEMPT_MASK)))
3965 preempt_count() -= val;
3967 EXPORT_SYMBOL(sub_preempt_count);
3972 * Print scheduling while atomic bug:
3974 static noinline void __schedule_bug(struct task_struct *prev)
3976 struct pt_regs *regs = get_irq_regs();
3978 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3979 prev->comm, prev->pid, preempt_count());
3981 debug_show_held_locks(prev);
3982 if (irqs_disabled())
3983 print_irqtrace_events(prev);
3992 * Various schedule()-time debugging checks and statistics:
3994 static inline void schedule_debug(struct task_struct *prev)
3997 * Test if we are atomic. Since do_exit() needs to call into
3998 * schedule() atomically, we ignore that path for now.
3999 * Otherwise, whine if we are scheduling when we should not be.
4001 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev->exit_state))
4002 __schedule_bug(prev);
4004 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
4006 schedstat_inc(this_rq(), sched_count);
4007 #ifdef CONFIG_SCHEDSTATS
4008 if (unlikely(prev->lock_depth >= 0)) {
4009 schedstat_inc(this_rq(), bkl_count);
4010 schedstat_inc(prev, sched_info.bkl_count);
4016 * Pick up the highest-prio task:
4018 static inline struct task_struct *
4019 pick_next_task(struct rq *rq, struct task_struct *prev)
4021 const struct sched_class *class;
4022 struct task_struct *p;
4025 * Optimization: we know that if all tasks are in
4026 * the fair class we can call that function directly:
4028 if (likely(rq->nr_running == rq->cfs.nr_running)) {
4029 p = fair_sched_class.pick_next_task(rq);
4034 class = sched_class_highest;
4036 p = class->pick_next_task(rq);
4040 * Will never be NULL as the idle class always
4041 * returns a non-NULL p:
4043 class = class->next;
4048 * schedule() is the main scheduler function.
4050 asmlinkage void __sched schedule(void)
4052 struct task_struct *prev, *next;
4053 unsigned long *switch_count;
4059 cpu = smp_processor_id();
4063 switch_count = &prev->nivcsw;
4065 release_kernel_lock(prev);
4066 need_resched_nonpreemptible:
4068 schedule_debug(prev);
4073 * Do the rq-clock update outside the rq lock:
4075 local_irq_disable();
4076 __update_rq_clock(rq);
4077 spin_lock(&rq->lock);
4078 clear_tsk_need_resched(prev);
4080 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
4081 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
4082 signal_pending(prev))) {
4083 prev->state = TASK_RUNNING;
4085 deactivate_task(rq, prev, 1);
4087 switch_count = &prev->nvcsw;
4091 if (prev->sched_class->pre_schedule)
4092 prev->sched_class->pre_schedule(rq, prev);
4095 if (unlikely(!rq->nr_running))
4096 idle_balance(cpu, rq);
4098 prev->sched_class->put_prev_task(rq, prev);
4099 next = pick_next_task(rq, prev);
4101 sched_info_switch(prev, next);
4103 if (likely(prev != next)) {
4108 context_switch(rq, prev, next); /* unlocks the rq */
4110 * the context switch might have flipped the stack from under
4111 * us, hence refresh the local variables.
4113 cpu = smp_processor_id();
4116 spin_unlock_irq(&rq->lock);
4120 if (unlikely(reacquire_kernel_lock(current) < 0))
4121 goto need_resched_nonpreemptible;
4123 preempt_enable_no_resched();
4124 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
4127 EXPORT_SYMBOL(schedule);
4129 #ifdef CONFIG_PREEMPT
4131 * this is the entry point to schedule() from in-kernel preemption
4132 * off of preempt_enable. Kernel preemptions off return from interrupt
4133 * occur there and call schedule directly.
4135 asmlinkage void __sched preempt_schedule(void)
4137 struct thread_info *ti = current_thread_info();
4138 struct task_struct *task = current;
4139 int saved_lock_depth;
4142 * If there is a non-zero preempt_count or interrupts are disabled,
4143 * we do not want to preempt the current task. Just return..
4145 if (likely(ti->preempt_count || irqs_disabled()))
4149 add_preempt_count(PREEMPT_ACTIVE);
4152 * We keep the big kernel semaphore locked, but we
4153 * clear ->lock_depth so that schedule() doesnt
4154 * auto-release the semaphore:
4156 saved_lock_depth = task->lock_depth;
4157 task->lock_depth = -1;
4159 task->lock_depth = saved_lock_depth;
4160 sub_preempt_count(PREEMPT_ACTIVE);
4163 * Check again in case we missed a preemption opportunity
4164 * between schedule and now.
4167 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4169 EXPORT_SYMBOL(preempt_schedule);
4172 * this is the entry point to schedule() from kernel preemption
4173 * off of irq context.
4174 * Note, that this is called and return with irqs disabled. This will
4175 * protect us against recursive calling from irq.
4177 asmlinkage void __sched preempt_schedule_irq(void)
4179 struct thread_info *ti = current_thread_info();
4180 struct task_struct *task = current;
4181 int saved_lock_depth;
4183 /* Catch callers which need to be fixed */
4184 BUG_ON(ti->preempt_count || !irqs_disabled());
4187 add_preempt_count(PREEMPT_ACTIVE);
4190 * We keep the big kernel semaphore locked, but we
4191 * clear ->lock_depth so that schedule() doesnt
4192 * auto-release the semaphore:
4194 saved_lock_depth = task->lock_depth;
4195 task->lock_depth = -1;
4198 local_irq_disable();
4199 task->lock_depth = saved_lock_depth;
4200 sub_preempt_count(PREEMPT_ACTIVE);
4203 * Check again in case we missed a preemption opportunity
4204 * between schedule and now.
4207 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4210 #endif /* CONFIG_PREEMPT */
4212 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
4215 return try_to_wake_up(curr->private, mode, sync);
4217 EXPORT_SYMBOL(default_wake_function);
4220 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4221 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4222 * number) then we wake all the non-exclusive tasks and one exclusive task.
4224 * There are circumstances in which we can try to wake a task which has already
4225 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4226 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4228 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
4229 int nr_exclusive, int sync, void *key)
4231 wait_queue_t *curr, *next;
4233 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
4234 unsigned flags = curr->flags;
4236 if (curr->func(curr, mode, sync, key) &&
4237 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
4243 * __wake_up - wake up threads blocked on a waitqueue.
4245 * @mode: which threads
4246 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4247 * @key: is directly passed to the wakeup function
4249 void __wake_up(wait_queue_head_t *q, unsigned int mode,
4250 int nr_exclusive, void *key)
4252 unsigned long flags;
4254 spin_lock_irqsave(&q->lock, flags);
4255 __wake_up_common(q, mode, nr_exclusive, 0, key);
4256 spin_unlock_irqrestore(&q->lock, flags);
4258 EXPORT_SYMBOL(__wake_up);
4261 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4263 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4265 __wake_up_common(q, mode, 1, 0, NULL);
4269 * __wake_up_sync - wake up threads blocked on a waitqueue.
4271 * @mode: which threads
4272 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4274 * The sync wakeup differs that the waker knows that it will schedule
4275 * away soon, so while the target thread will be woken up, it will not
4276 * be migrated to another CPU - ie. the two threads are 'synchronized'
4277 * with each other. This can prevent needless bouncing between CPUs.
4279 * On UP it can prevent extra preemption.
4282 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4284 unsigned long flags;
4290 if (unlikely(!nr_exclusive))
4293 spin_lock_irqsave(&q->lock, flags);
4294 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
4295 spin_unlock_irqrestore(&q->lock, flags);
4297 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
4299 void complete(struct completion *x)
4301 unsigned long flags;
4303 spin_lock_irqsave(&x->wait.lock, flags);
4305 __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4306 spin_unlock_irqrestore(&x->wait.lock, flags);
4308 EXPORT_SYMBOL(complete);
4310 void complete_all(struct completion *x)
4312 unsigned long flags;
4314 spin_lock_irqsave(&x->wait.lock, flags);
4315 x->done += UINT_MAX/2;
4316 __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4317 spin_unlock_irqrestore(&x->wait.lock, flags);
4319 EXPORT_SYMBOL(complete_all);
4321 static inline long __sched
4322 do_wait_for_common(struct completion *x, long timeout, int state)
4325 DECLARE_WAITQUEUE(wait, current);
4327 wait.flags |= WQ_FLAG_EXCLUSIVE;
4328 __add_wait_queue_tail(&x->wait, &wait);
4330 if ((state == TASK_INTERRUPTIBLE &&
4331 signal_pending(current)) ||
4332 (state == TASK_KILLABLE &&
4333 fatal_signal_pending(current))) {
4334 __remove_wait_queue(&x->wait, &wait);
4335 return -ERESTARTSYS;
4337 __set_current_state(state);
4338 spin_unlock_irq(&x->wait.lock);
4339 timeout = schedule_timeout(timeout);
4340 spin_lock_irq(&x->wait.lock);
4342 __remove_wait_queue(&x->wait, &wait);
4346 __remove_wait_queue(&x->wait, &wait);
4353 wait_for_common(struct completion *x, long timeout, int state)
4357 spin_lock_irq(&x->wait.lock);
4358 timeout = do_wait_for_common(x, timeout, state);
4359 spin_unlock_irq(&x->wait.lock);
4363 void __sched wait_for_completion(struct completion *x)
4365 wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4367 EXPORT_SYMBOL(wait_for_completion);
4369 unsigned long __sched
4370 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4372 return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4374 EXPORT_SYMBOL(wait_for_completion_timeout);
4376 int __sched wait_for_completion_interruptible(struct completion *x)
4378 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4379 if (t == -ERESTARTSYS)
4383 EXPORT_SYMBOL(wait_for_completion_interruptible);
4385 unsigned long __sched
4386 wait_for_completion_interruptible_timeout(struct completion *x,
4387 unsigned long timeout)
4389 return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4391 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4393 int __sched wait_for_completion_killable(struct completion *x)
4395 long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4396 if (t == -ERESTARTSYS)
4400 EXPORT_SYMBOL(wait_for_completion_killable);
4403 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4405 unsigned long flags;
4408 init_waitqueue_entry(&wait, current);
4410 __set_current_state(state);
4412 spin_lock_irqsave(&q->lock, flags);
4413 __add_wait_queue(q, &wait);
4414 spin_unlock(&q->lock);
4415 timeout = schedule_timeout(timeout);
4416 spin_lock_irq(&q->lock);
4417 __remove_wait_queue(q, &wait);
4418 spin_unlock_irqrestore(&q->lock, flags);
4423 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4425 sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4427 EXPORT_SYMBOL(interruptible_sleep_on);
4430 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4432 return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4434 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4436 void __sched sleep_on(wait_queue_head_t *q)
4438 sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4440 EXPORT_SYMBOL(sleep_on);
4442 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4444 return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
4446 EXPORT_SYMBOL(sleep_on_timeout);
4448 #ifdef CONFIG_RT_MUTEXES
4451 * rt_mutex_setprio - set the current priority of a task
4453 * @prio: prio value (kernel-internal form)
4455 * This function changes the 'effective' priority of a task. It does
4456 * not touch ->normal_prio like __setscheduler().
4458 * Used by the rt_mutex code to implement priority inheritance logic.
4460 void rt_mutex_setprio(struct task_struct *p, int prio)
4462 unsigned long flags;
4463 int oldprio, on_rq, running;
4465 const struct sched_class *prev_class = p->sched_class;
4467 BUG_ON(prio < 0 || prio > MAX_PRIO);
4469 rq = task_rq_lock(p, &flags);
4470 update_rq_clock(rq);
4473 on_rq = p->se.on_rq;
4474 running = task_current(rq, p);
4476 dequeue_task(rq, p, 0);
4478 p->sched_class->put_prev_task(rq, p);
4481 p->sched_class = &rt_sched_class;
4483 p->sched_class = &fair_sched_class;
4488 p->sched_class->set_curr_task(rq);
4490 enqueue_task(rq, p, 0);
4492 check_class_changed(rq, p, prev_class, oldprio, running);
4494 task_rq_unlock(rq, &flags);
4499 void set_user_nice(struct task_struct *p, long nice)
4501 int old_prio, delta, on_rq;
4502 unsigned long flags;
4505 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4508 * We have to be careful, if called from sys_setpriority(),
4509 * the task might be in the middle of scheduling on another CPU.
4511 rq = task_rq_lock(p, &flags);
4512 update_rq_clock(rq);
4514 * The RT priorities are set via sched_setscheduler(), but we still
4515 * allow the 'normal' nice value to be set - but as expected
4516 * it wont have any effect on scheduling until the task is
4517 * SCHED_FIFO/SCHED_RR:
4519 if (task_has_rt_policy(p)) {
4520 p->static_prio = NICE_TO_PRIO(nice);
4523 on_rq = p->se.on_rq;
4525 dequeue_task(rq, p, 0);
4529 p->static_prio = NICE_TO_PRIO(nice);
4532 p->prio = effective_prio(p);
4533 delta = p->prio - old_prio;
4536 enqueue_task(rq, p, 0);
4539 * If the task increased its priority or is running and
4540 * lowered its priority, then reschedule its CPU:
4542 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4543 resched_task(rq->curr);
4546 task_rq_unlock(rq, &flags);
4548 EXPORT_SYMBOL(set_user_nice);
4551 * can_nice - check if a task can reduce its nice value
4555 int can_nice(const struct task_struct *p, const int nice)
4557 /* convert nice value [19,-20] to rlimit style value [1,40] */
4558 int nice_rlim = 20 - nice;
4560 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
4561 capable(CAP_SYS_NICE));
4564 #ifdef __ARCH_WANT_SYS_NICE
4567 * sys_nice - change the priority of the current process.
4568 * @increment: priority increment
4570 * sys_setpriority is a more generic, but much slower function that
4571 * does similar things.
4573 asmlinkage long sys_nice(int increment)
4578 * Setpriority might change our priority at the same moment.
4579 * We don't have to worry. Conceptually one call occurs first
4580 * and we have a single winner.
4582 if (increment < -40)
4587 nice = PRIO_TO_NICE(current->static_prio) + increment;
4593 if (increment < 0 && !can_nice(current, nice))
4596 retval = security_task_setnice(current, nice);
4600 set_user_nice(current, nice);
4607 * task_prio - return the priority value of a given task.
4608 * @p: the task in question.
4610 * This is the priority value as seen by users in /proc.
4611 * RT tasks are offset by -200. Normal tasks are centered
4612 * around 0, value goes from -16 to +15.
4614 int task_prio(const struct task_struct *p)
4616 return p->prio - MAX_RT_PRIO;
4620 * task_nice - return the nice value of a given task.
4621 * @p: the task in question.
4623 int task_nice(const struct task_struct *p)
4625 return TASK_NICE(p);
4627 EXPORT_SYMBOL(task_nice);
4630 * idle_cpu - is a given cpu idle currently?
4631 * @cpu: the processor in question.
4633 int idle_cpu(int cpu)
4635 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
4639 * idle_task - return the idle task for a given cpu.
4640 * @cpu: the processor in question.
4642 struct task_struct *idle_task(int cpu)
4644 return cpu_rq(cpu)->idle;
4648 * find_process_by_pid - find a process with a matching PID value.
4649 * @pid: the pid in question.
4651 static struct task_struct *find_process_by_pid(pid_t pid)
4653 return pid ? find_task_by_vpid(pid) : current;
4656 /* Actually do priority change: must hold rq lock. */
4658 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
4660 BUG_ON(p->se.on_rq);
4663 switch (p->policy) {
4667 p->sched_class = &fair_sched_class;
4671 p->sched_class = &rt_sched_class;
4675 p->rt_priority = prio;
4676 p->normal_prio = normal_prio(p);
4677 /* we are holding p->pi_lock already */
4678 p->prio = rt_mutex_getprio(p);
4683 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4684 * @p: the task in question.
4685 * @policy: new policy.
4686 * @param: structure containing the new RT priority.
4688 * NOTE that the task may be already dead.
4690 int sched_setscheduler(struct task_struct *p, int policy,
4691 struct sched_param *param)
4693 int retval, oldprio, oldpolicy = -1, on_rq, running;
4694 unsigned long flags;
4695 const struct sched_class *prev_class = p->sched_class;
4698 /* may grab non-irq protected spin_locks */
4699 BUG_ON(in_interrupt());
4701 /* double check policy once rq lock held */
4703 policy = oldpolicy = p->policy;
4704 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
4705 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
4706 policy != SCHED_IDLE)
4709 * Valid priorities for SCHED_FIFO and SCHED_RR are
4710 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4711 * SCHED_BATCH and SCHED_IDLE is 0.
4713 if (param->sched_priority < 0 ||
4714 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
4715 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
4717 if (rt_policy(policy) != (param->sched_priority != 0))
4721 * Allow unprivileged RT tasks to decrease priority:
4723 if (!capable(CAP_SYS_NICE)) {
4724 if (rt_policy(policy)) {
4725 unsigned long rlim_rtprio;
4727 if (!lock_task_sighand(p, &flags))
4729 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
4730 unlock_task_sighand(p, &flags);
4732 /* can't set/change the rt policy */
4733 if (policy != p->policy && !rlim_rtprio)
4736 /* can't increase priority */
4737 if (param->sched_priority > p->rt_priority &&
4738 param->sched_priority > rlim_rtprio)
4742 * Like positive nice levels, dont allow tasks to
4743 * move out of SCHED_IDLE either:
4745 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
4748 /* can't change other user's priorities */
4749 if ((current->euid != p->euid) &&
4750 (current->euid != p->uid))
4754 #ifdef CONFIG_RT_GROUP_SCHED
4756 * Do not allow realtime tasks into groups that have no runtime
4759 if (rt_policy(policy) && task_group(p)->rt_bandwidth.rt_runtime == 0)
4763 retval = security_task_setscheduler(p, policy, param);
4767 * make sure no PI-waiters arrive (or leave) while we are
4768 * changing the priority of the task:
4770 spin_lock_irqsave(&p->pi_lock, flags);
4772 * To be able to change p->policy safely, the apropriate
4773 * runqueue lock must be held.
4775 rq = __task_rq_lock(p);
4776 /* recheck policy now with rq lock held */
4777 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4778 policy = oldpolicy = -1;
4779 __task_rq_unlock(rq);
4780 spin_unlock_irqrestore(&p->pi_lock, flags);
4783 update_rq_clock(rq);
4784 on_rq = p->se.on_rq;
4785 running = task_current(rq, p);
4787 deactivate_task(rq, p, 0);
4789 p->sched_class->put_prev_task(rq, p);
4792 __setscheduler(rq, p, policy, param->sched_priority);
4795 p->sched_class->set_curr_task(rq);
4797 activate_task(rq, p, 0);
4799 check_class_changed(rq, p, prev_class, oldprio, running);
4801 __task_rq_unlock(rq);
4802 spin_unlock_irqrestore(&p->pi_lock, flags);
4804 rt_mutex_adjust_pi(p);
4808 EXPORT_SYMBOL_GPL(sched_setscheduler);
4811 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4813 struct sched_param lparam;
4814 struct task_struct *p;
4817 if (!param || pid < 0)
4819 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4824 p = find_process_by_pid(pid);
4826 retval = sched_setscheduler(p, policy, &lparam);
4833 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4834 * @pid: the pid in question.
4835 * @policy: new policy.
4836 * @param: structure containing the new RT priority.
4839 sys_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4841 /* negative values for policy are not valid */
4845 return do_sched_setscheduler(pid, policy, param);
4849 * sys_sched_setparam - set/change the RT priority of a thread
4850 * @pid: the pid in question.
4851 * @param: structure containing the new RT priority.
4853 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
4855 return do_sched_setscheduler(pid, -1, param);
4859 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4860 * @pid: the pid in question.
4862 asmlinkage long sys_sched_getscheduler(pid_t pid)
4864 struct task_struct *p;
4871 read_lock(&tasklist_lock);
4872 p = find_process_by_pid(pid);
4874 retval = security_task_getscheduler(p);
4878 read_unlock(&tasklist_lock);
4883 * sys_sched_getscheduler - get the RT priority of a thread
4884 * @pid: the pid in question.
4885 * @param: structure containing the RT priority.
4887 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
4889 struct sched_param lp;
4890 struct task_struct *p;
4893 if (!param || pid < 0)
4896 read_lock(&tasklist_lock);
4897 p = find_process_by_pid(pid);
4902 retval = security_task_getscheduler(p);
4906 lp.sched_priority = p->rt_priority;
4907 read_unlock(&tasklist_lock);
4910 * This one might sleep, we cannot do it with a spinlock held ...
4912 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4917 read_unlock(&tasklist_lock);
4921 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
4923 cpumask_t cpus_allowed;
4924 struct task_struct *p;
4928 read_lock(&tasklist_lock);
4930 p = find_process_by_pid(pid);
4932 read_unlock(&tasklist_lock);
4938 * It is not safe to call set_cpus_allowed with the
4939 * tasklist_lock held. We will bump the task_struct's
4940 * usage count and then drop tasklist_lock.
4943 read_unlock(&tasklist_lock);
4946 if ((current->euid != p->euid) && (current->euid != p->uid) &&
4947 !capable(CAP_SYS_NICE))
4950 retval = security_task_setscheduler(p, 0, NULL);
4954 cpus_allowed = cpuset_cpus_allowed(p);
4955 cpus_and(new_mask, new_mask, cpus_allowed);
4957 retval = set_cpus_allowed(p, new_mask);
4960 cpus_allowed = cpuset_cpus_allowed(p);
4961 if (!cpus_subset(new_mask, cpus_allowed)) {
4963 * We must have raced with a concurrent cpuset
4964 * update. Just reset the cpus_allowed to the
4965 * cpuset's cpus_allowed
4967 new_mask = cpus_allowed;
4977 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4978 cpumask_t *new_mask)
4980 if (len < sizeof(cpumask_t)) {
4981 memset(new_mask, 0, sizeof(cpumask_t));
4982 } else if (len > sizeof(cpumask_t)) {
4983 len = sizeof(cpumask_t);
4985 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4989 * sys_sched_setaffinity - set the cpu affinity of a process
4990 * @pid: pid of the process
4991 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4992 * @user_mask_ptr: user-space pointer to the new cpu mask
4994 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
4995 unsigned long __user *user_mask_ptr)
5000 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
5004 return sched_setaffinity(pid, new_mask);
5008 * Represents all cpu's present in the system
5009 * In systems capable of hotplug, this map could dynamically grow
5010 * as new cpu's are detected in the system via any platform specific
5011 * method, such as ACPI for e.g.
5014 cpumask_t cpu_present_map __read_mostly;
5015 EXPORT_SYMBOL(cpu_present_map);
5018 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
5019 EXPORT_SYMBOL(cpu_online_map);
5021 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
5022 EXPORT_SYMBOL(cpu_possible_map);
5025 long sched_getaffinity(pid_t pid, cpumask_t *mask)
5027 struct task_struct *p;
5031 read_lock(&tasklist_lock);
5034 p = find_process_by_pid(pid);
5038 retval = security_task_getscheduler(p);
5042 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
5045 read_unlock(&tasklist_lock);
5052 * sys_sched_getaffinity - get the cpu affinity of a process
5053 * @pid: pid of the process
5054 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5055 * @user_mask_ptr: user-space pointer to hold the current cpu mask
5057 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
5058 unsigned long __user *user_mask_ptr)
5063 if (len < sizeof(cpumask_t))
5066 ret = sched_getaffinity(pid, &mask);
5070 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
5073 return sizeof(cpumask_t);
5077 * sys_sched_yield - yield the current processor to other threads.
5079 * This function yields the current CPU to other tasks. If there are no
5080 * other threads running on this CPU then this function will return.
5082 asmlinkage long sys_sched_yield(void)
5084 struct rq *rq = this_rq_lock();
5086 schedstat_inc(rq, yld_count);
5087 current->sched_class->yield_task(rq);
5090 * Since we are going to call schedule() anyway, there's
5091 * no need to preempt or enable interrupts:
5093 __release(rq->lock);
5094 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5095 _raw_spin_unlock(&rq->lock);
5096 preempt_enable_no_resched();
5103 static void __cond_resched(void)
5105 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5106 __might_sleep(__FILE__, __LINE__);
5109 * The BKS might be reacquired before we have dropped
5110 * PREEMPT_ACTIVE, which could trigger a second
5111 * cond_resched() call.
5114 add_preempt_count(PREEMPT_ACTIVE);
5116 sub_preempt_count(PREEMPT_ACTIVE);
5117 } while (need_resched());
5120 #if !defined(CONFIG_PREEMPT) || defined(CONFIG_PREEMPT_VOLUNTARY)
5121 int __sched _cond_resched(void)
5123 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
5124 system_state == SYSTEM_RUNNING) {
5130 EXPORT_SYMBOL(_cond_resched);
5134 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5135 * call schedule, and on return reacquire the lock.
5137 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5138 * operations here to prevent schedule() from being called twice (once via
5139 * spin_unlock(), once by hand).
5141 int cond_resched_lock(spinlock_t *lock)
5143 int resched = need_resched() && system_state == SYSTEM_RUNNING;
5146 if (spin_needbreak(lock) || resched) {
5148 if (resched && need_resched())
5157 EXPORT_SYMBOL(cond_resched_lock);
5159 int __sched cond_resched_softirq(void)
5161 BUG_ON(!in_softirq());
5163 if (need_resched() && system_state == SYSTEM_RUNNING) {
5171 EXPORT_SYMBOL(cond_resched_softirq);
5174 * yield - yield the current processor to other threads.
5176 * This is a shortcut for kernel-space yielding - it marks the
5177 * thread runnable and calls sys_sched_yield().
5179 void __sched yield(void)
5181 set_current_state(TASK_RUNNING);
5184 EXPORT_SYMBOL(yield);
5187 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5188 * that process accounting knows that this is a task in IO wait state.
5190 * But don't do that if it is a deliberate, throttling IO wait (this task
5191 * has set its backing_dev_info: the queue against which it should throttle)
5193 void __sched io_schedule(void)
5195 struct rq *rq = &__raw_get_cpu_var(runqueues);
5197 delayacct_blkio_start();
5198 atomic_inc(&rq->nr_iowait);
5200 atomic_dec(&rq->nr_iowait);
5201 delayacct_blkio_end();
5203 EXPORT_SYMBOL(io_schedule);
5205 long __sched io_schedule_timeout(long timeout)
5207 struct rq *rq = &__raw_get_cpu_var(runqueues);
5210 delayacct_blkio_start();
5211 atomic_inc(&rq->nr_iowait);
5212 ret = schedule_timeout(timeout);
5213 atomic_dec(&rq->nr_iowait);
5214 delayacct_blkio_end();
5219 * sys_sched_get_priority_max - return maximum RT priority.
5220 * @policy: scheduling class.
5222 * this syscall returns the maximum rt_priority that can be used
5223 * by a given scheduling class.
5225 asmlinkage long sys_sched_get_priority_max(int policy)
5232 ret = MAX_USER_RT_PRIO-1;
5244 * sys_sched_get_priority_min - return minimum RT priority.
5245 * @policy: scheduling class.
5247 * this syscall returns the minimum rt_priority that can be used
5248 * by a given scheduling class.
5250 asmlinkage long sys_sched_get_priority_min(int policy)
5268 * sys_sched_rr_get_interval - return the default timeslice of a process.
5269 * @pid: pid of the process.
5270 * @interval: userspace pointer to the timeslice value.
5272 * this syscall writes the default timeslice value of a given process
5273 * into the user-space timespec buffer. A value of '0' means infinity.
5276 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
5278 struct task_struct *p;
5279 unsigned int time_slice;
5287 read_lock(&tasklist_lock);
5288 p = find_process_by_pid(pid);
5292 retval = security_task_getscheduler(p);
5297 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5298 * tasks that are on an otherwise idle runqueue:
5301 if (p->policy == SCHED_RR) {
5302 time_slice = DEF_TIMESLICE;
5303 } else if (p->policy != SCHED_FIFO) {
5304 struct sched_entity *se = &p->se;
5305 unsigned long flags;
5308 rq = task_rq_lock(p, &flags);
5309 if (rq->cfs.load.weight)
5310 time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
5311 task_rq_unlock(rq, &flags);
5313 read_unlock(&tasklist_lock);
5314 jiffies_to_timespec(time_slice, &t);
5315 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5319 read_unlock(&tasklist_lock);
5323 static const char stat_nam[] = "RSDTtZX";
5325 void sched_show_task(struct task_struct *p)
5327 unsigned long free = 0;
5330 state = p->state ? __ffs(p->state) + 1 : 0;
5331 printk(KERN_INFO "%-13.13s %c", p->comm,
5332 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5333 #if BITS_PER_LONG == 32
5334 if (state == TASK_RUNNING)
5335 printk(KERN_CONT " running ");
5337 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5339 if (state == TASK_RUNNING)
5340 printk(KERN_CONT " running task ");
5342 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5344 #ifdef CONFIG_DEBUG_STACK_USAGE
5346 unsigned long *n = end_of_stack(p);
5349 free = (unsigned long)n - (unsigned long)end_of_stack(p);
5352 printk(KERN_CONT "%5lu %5d %6d\n", free,
5353 task_pid_nr(p), task_pid_nr(p->real_parent));
5355 show_stack(p, NULL);
5358 void show_state_filter(unsigned long state_filter)
5360 struct task_struct *g, *p;
5362 #if BITS_PER_LONG == 32
5364 " task PC stack pid father\n");
5367 " task PC stack pid father\n");
5369 read_lock(&tasklist_lock);
5370 do_each_thread(g, p) {
5372 * reset the NMI-timeout, listing all files on a slow
5373 * console might take alot of time:
5375 touch_nmi_watchdog();
5376 if (!state_filter || (p->state & state_filter))
5378 } while_each_thread(g, p);
5380 touch_all_softlockup_watchdogs();
5382 #ifdef CONFIG_SCHED_DEBUG
5383 sysrq_sched_debug_show();
5385 read_unlock(&tasklist_lock);
5387 * Only show locks if all tasks are dumped:
5389 if (state_filter == -1)
5390 debug_show_all_locks();
5393 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5395 idle->sched_class = &idle_sched_class;
5399 * init_idle - set up an idle thread for a given CPU
5400 * @idle: task in question
5401 * @cpu: cpu the idle task belongs to
5403 * NOTE: this function does not set the idle thread's NEED_RESCHED
5404 * flag, to make booting more robust.
5406 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5408 struct rq *rq = cpu_rq(cpu);
5409 unsigned long flags;
5412 idle->se.exec_start = sched_clock();
5414 idle->prio = idle->normal_prio = MAX_PRIO;
5415 idle->cpus_allowed = cpumask_of_cpu(cpu);
5416 __set_task_cpu(idle, cpu);
5418 spin_lock_irqsave(&rq->lock, flags);
5419 rq->curr = rq->idle = idle;
5420 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5423 spin_unlock_irqrestore(&rq->lock, flags);
5425 /* Set the preempt count _outside_ the spinlocks! */
5426 task_thread_info(idle)->preempt_count = 0;
5429 * The idle tasks have their own, simple scheduling class:
5431 idle->sched_class = &idle_sched_class;
5435 * In a system that switches off the HZ timer nohz_cpu_mask
5436 * indicates which cpus entered this state. This is used
5437 * in the rcu update to wait only for active cpus. For system
5438 * which do not switch off the HZ timer nohz_cpu_mask should
5439 * always be CPU_MASK_NONE.
5441 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
5444 * Increase the granularity value when there are more CPUs,
5445 * because with more CPUs the 'effective latency' as visible
5446 * to users decreases. But the relationship is not linear,
5447 * so pick a second-best guess by going with the log2 of the
5450 * This idea comes from the SD scheduler of Con Kolivas:
5452 static inline void sched_init_granularity(void)
5454 unsigned int factor = 1 + ilog2(num_online_cpus());
5455 const unsigned long limit = 200000000;
5457 sysctl_sched_min_granularity *= factor;
5458 if (sysctl_sched_min_granularity > limit)
5459 sysctl_sched_min_granularity = limit;
5461 sysctl_sched_latency *= factor;
5462 if (sysctl_sched_latency > limit)
5463 sysctl_sched_latency = limit;
5465 sysctl_sched_wakeup_granularity *= factor;
5470 * This is how migration works:
5472 * 1) we queue a struct migration_req structure in the source CPU's
5473 * runqueue and wake up that CPU's migration thread.
5474 * 2) we down() the locked semaphore => thread blocks.
5475 * 3) migration thread wakes up (implicitly it forces the migrated
5476 * thread off the CPU)
5477 * 4) it gets the migration request and checks whether the migrated
5478 * task is still in the wrong runqueue.
5479 * 5) if it's in the wrong runqueue then the migration thread removes
5480 * it and puts it into the right queue.
5481 * 6) migration thread up()s the semaphore.
5482 * 7) we wake up and the migration is done.
5486 * Change a given task's CPU affinity. Migrate the thread to a
5487 * proper CPU and schedule it away if the CPU it's executing on
5488 * is removed from the allowed bitmask.
5490 * NOTE: the caller must have a valid reference to the task, the
5491 * task must not exit() & deallocate itself prematurely. The
5492 * call is not atomic; no spinlocks may be held.
5494 int set_cpus_allowed(struct task_struct *p, cpumask_t new_mask)
5496 struct migration_req req;
5497 unsigned long flags;
5501 rq = task_rq_lock(p, &flags);
5502 if (!cpus_intersects(new_mask, cpu_online_map)) {
5507 if (p->sched_class->set_cpus_allowed)
5508 p->sched_class->set_cpus_allowed(p, &new_mask);
5510 p->cpus_allowed = new_mask;
5511 p->rt.nr_cpus_allowed = cpus_weight(new_mask);
5514 /* Can the task run on the task's current CPU? If so, we're done */
5515 if (cpu_isset(task_cpu(p), new_mask))
5518 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
5519 /* Need help from migration thread: drop lock and wait. */
5520 task_rq_unlock(rq, &flags);
5521 wake_up_process(rq->migration_thread);
5522 wait_for_completion(&req.done);
5523 tlb_migrate_finish(p->mm);
5527 task_rq_unlock(rq, &flags);
5531 EXPORT_SYMBOL_GPL(set_cpus_allowed);
5534 * Move (not current) task off this cpu, onto dest cpu. We're doing
5535 * this because either it can't run here any more (set_cpus_allowed()
5536 * away from this CPU, or CPU going down), or because we're
5537 * attempting to rebalance this task on exec (sched_exec).
5539 * So we race with normal scheduler movements, but that's OK, as long
5540 * as the task is no longer on this CPU.
5542 * Returns non-zero if task was successfully migrated.
5544 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
5546 struct rq *rq_dest, *rq_src;
5549 if (unlikely(cpu_is_offline(dest_cpu)))
5552 rq_src = cpu_rq(src_cpu);
5553 rq_dest = cpu_rq(dest_cpu);
5555 double_rq_lock(rq_src, rq_dest);
5556 /* Already moved. */
5557 if (task_cpu(p) != src_cpu)
5559 /* Affinity changed (again). */
5560 if (!cpu_isset(dest_cpu, p->cpus_allowed))
5563 on_rq = p->se.on_rq;
5565 deactivate_task(rq_src, p, 0);
5567 set_task_cpu(p, dest_cpu);
5569 activate_task(rq_dest, p, 0);
5570 check_preempt_curr(rq_dest, p);
5574 double_rq_unlock(rq_src, rq_dest);
5579 * migration_thread - this is a highprio system thread that performs
5580 * thread migration by bumping thread off CPU then 'pushing' onto
5583 static int migration_thread(void *data)
5585 int cpu = (long)data;
5589 BUG_ON(rq->migration_thread != current);
5591 set_current_state(TASK_INTERRUPTIBLE);
5592 while (!kthread_should_stop()) {
5593 struct migration_req *req;
5594 struct list_head *head;
5596 spin_lock_irq(&rq->lock);
5598 if (cpu_is_offline(cpu)) {
5599 spin_unlock_irq(&rq->lock);
5603 if (rq->active_balance) {
5604 active_load_balance(rq, cpu);
5605 rq->active_balance = 0;
5608 head = &rq->migration_queue;
5610 if (list_empty(head)) {
5611 spin_unlock_irq(&rq->lock);
5613 set_current_state(TASK_INTERRUPTIBLE);
5616 req = list_entry(head->next, struct migration_req, list);
5617 list_del_init(head->next);
5619 spin_unlock(&rq->lock);
5620 __migrate_task(req->task, cpu, req->dest_cpu);
5623 complete(&req->done);
5625 __set_current_state(TASK_RUNNING);
5629 /* Wait for kthread_stop */
5630 set_current_state(TASK_INTERRUPTIBLE);
5631 while (!kthread_should_stop()) {
5633 set_current_state(TASK_INTERRUPTIBLE);
5635 __set_current_state(TASK_RUNNING);
5639 #ifdef CONFIG_HOTPLUG_CPU
5641 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
5645 local_irq_disable();
5646 ret = __migrate_task(p, src_cpu, dest_cpu);
5652 * Figure out where task on dead CPU should go, use force if necessary.
5653 * NOTE: interrupts should be disabled by the caller
5655 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
5657 unsigned long flags;
5664 mask = node_to_cpumask(cpu_to_node(dead_cpu));
5665 cpus_and(mask, mask, p->cpus_allowed);
5666 dest_cpu = any_online_cpu(mask);
5668 /* On any allowed CPU? */
5669 if (dest_cpu == NR_CPUS)
5670 dest_cpu = any_online_cpu(p->cpus_allowed);
5672 /* No more Mr. Nice Guy. */
5673 if (dest_cpu == NR_CPUS) {
5674 cpumask_t cpus_allowed = cpuset_cpus_allowed_locked(p);
5676 * Try to stay on the same cpuset, where the
5677 * current cpuset may be a subset of all cpus.
5678 * The cpuset_cpus_allowed_locked() variant of
5679 * cpuset_cpus_allowed() will not block. It must be
5680 * called within calls to cpuset_lock/cpuset_unlock.
5682 rq = task_rq_lock(p, &flags);
5683 p->cpus_allowed = cpus_allowed;
5684 dest_cpu = any_online_cpu(p->cpus_allowed);
5685 task_rq_unlock(rq, &flags);
5688 * Don't tell them about moving exiting tasks or
5689 * kernel threads (both mm NULL), since they never
5692 if (p->mm && printk_ratelimit()) {
5693 printk(KERN_INFO "process %d (%s) no "
5694 "longer affine to cpu%d\n",
5695 task_pid_nr(p), p->comm, dead_cpu);
5698 } while (!__migrate_task_irq(p, dead_cpu, dest_cpu));
5702 * While a dead CPU has no uninterruptible tasks queued at this point,
5703 * it might still have a nonzero ->nr_uninterruptible counter, because
5704 * for performance reasons the counter is not stricly tracking tasks to
5705 * their home CPUs. So we just add the counter to another CPU's counter,
5706 * to keep the global sum constant after CPU-down:
5708 static void migrate_nr_uninterruptible(struct rq *rq_src)
5710 struct rq *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
5711 unsigned long flags;
5713 local_irq_save(flags);
5714 double_rq_lock(rq_src, rq_dest);
5715 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5716 rq_src->nr_uninterruptible = 0;
5717 double_rq_unlock(rq_src, rq_dest);
5718 local_irq_restore(flags);
5721 /* Run through task list and migrate tasks from the dead cpu. */
5722 static void migrate_live_tasks(int src_cpu)
5724 struct task_struct *p, *t;
5726 read_lock(&tasklist_lock);
5728 do_each_thread(t, p) {
5732 if (task_cpu(p) == src_cpu)
5733 move_task_off_dead_cpu(src_cpu, p);
5734 } while_each_thread(t, p);
5736 read_unlock(&tasklist_lock);
5740 * Schedules idle task to be the next runnable task on current CPU.
5741 * It does so by boosting its priority to highest possible.
5742 * Used by CPU offline code.
5744 void sched_idle_next(void)
5746 int this_cpu = smp_processor_id();
5747 struct rq *rq = cpu_rq(this_cpu);
5748 struct task_struct *p = rq->idle;
5749 unsigned long flags;
5751 /* cpu has to be offline */
5752 BUG_ON(cpu_online(this_cpu));
5755 * Strictly not necessary since rest of the CPUs are stopped by now
5756 * and interrupts disabled on the current cpu.
5758 spin_lock_irqsave(&rq->lock, flags);
5760 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
5762 update_rq_clock(rq);
5763 activate_task(rq, p, 0);
5765 spin_unlock_irqrestore(&rq->lock, flags);
5769 * Ensures that the idle task is using init_mm right before its cpu goes
5772 void idle_task_exit(void)
5774 struct mm_struct *mm = current->active_mm;
5776 BUG_ON(cpu_online(smp_processor_id()));
5779 switch_mm(mm, &init_mm, current);
5783 /* called under rq->lock with disabled interrupts */
5784 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
5786 struct rq *rq = cpu_rq(dead_cpu);
5788 /* Must be exiting, otherwise would be on tasklist. */
5789 BUG_ON(!p->exit_state);
5791 /* Cannot have done final schedule yet: would have vanished. */
5792 BUG_ON(p->state == TASK_DEAD);
5797 * Drop lock around migration; if someone else moves it,
5798 * that's OK. No task can be added to this CPU, so iteration is
5801 spin_unlock_irq(&rq->lock);
5802 move_task_off_dead_cpu(dead_cpu, p);
5803 spin_lock_irq(&rq->lock);
5808 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5809 static void migrate_dead_tasks(unsigned int dead_cpu)
5811 struct rq *rq = cpu_rq(dead_cpu);
5812 struct task_struct *next;
5815 if (!rq->nr_running)
5817 update_rq_clock(rq);
5818 next = pick_next_task(rq, rq->curr);
5821 migrate_dead(dead_cpu, next);
5825 #endif /* CONFIG_HOTPLUG_CPU */
5827 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5829 static struct ctl_table sd_ctl_dir[] = {
5831 .procname = "sched_domain",
5837 static struct ctl_table sd_ctl_root[] = {
5839 .ctl_name = CTL_KERN,
5840 .procname = "kernel",
5842 .child = sd_ctl_dir,
5847 static struct ctl_table *sd_alloc_ctl_entry(int n)
5849 struct ctl_table *entry =
5850 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
5855 static void sd_free_ctl_entry(struct ctl_table **tablep)
5857 struct ctl_table *entry;
5860 * In the intermediate directories, both the child directory and
5861 * procname are dynamically allocated and could fail but the mode
5862 * will always be set. In the lowest directory the names are
5863 * static strings and all have proc handlers.
5865 for (entry = *tablep; entry->mode; entry++) {
5867 sd_free_ctl_entry(&entry->child);
5868 if (entry->proc_handler == NULL)
5869 kfree(entry->procname);
5877 set_table_entry(struct ctl_table *entry,
5878 const char *procname, void *data, int maxlen,
5879 mode_t mode, proc_handler *proc_handler)
5881 entry->procname = procname;
5883 entry->maxlen = maxlen;
5885 entry->proc_handler = proc_handler;
5888 static struct ctl_table *
5889 sd_alloc_ctl_domain_table(struct sched_domain *sd)
5891 struct ctl_table *table = sd_alloc_ctl_entry(12);
5896 set_table_entry(&table[0], "min_interval", &sd->min_interval,
5897 sizeof(long), 0644, proc_doulongvec_minmax);
5898 set_table_entry(&table[1], "max_interval", &sd->max_interval,
5899 sizeof(long), 0644, proc_doulongvec_minmax);
5900 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
5901 sizeof(int), 0644, proc_dointvec_minmax);
5902 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
5903 sizeof(int), 0644, proc_dointvec_minmax);
5904 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
5905 sizeof(int), 0644, proc_dointvec_minmax);
5906 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
5907 sizeof(int), 0644, proc_dointvec_minmax);
5908 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
5909 sizeof(int), 0644, proc_dointvec_minmax);
5910 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
5911 sizeof(int), 0644, proc_dointvec_minmax);
5912 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
5913 sizeof(int), 0644, proc_dointvec_minmax);
5914 set_table_entry(&table[9], "cache_nice_tries",
5915 &sd->cache_nice_tries,
5916 sizeof(int), 0644, proc_dointvec_minmax);
5917 set_table_entry(&table[10], "flags", &sd->flags,
5918 sizeof(int), 0644, proc_dointvec_minmax);
5919 /* &table[11] is terminator */
5924 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
5926 struct ctl_table *entry, *table;
5927 struct sched_domain *sd;
5928 int domain_num = 0, i;
5931 for_each_domain(cpu, sd)
5933 entry = table = sd_alloc_ctl_entry(domain_num + 1);
5938 for_each_domain(cpu, sd) {
5939 snprintf(buf, 32, "domain%d", i);
5940 entry->procname = kstrdup(buf, GFP_KERNEL);
5942 entry->child = sd_alloc_ctl_domain_table(sd);
5949 static struct ctl_table_header *sd_sysctl_header;
5950 static void register_sched_domain_sysctl(void)
5952 int i, cpu_num = num_online_cpus();
5953 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5956 WARN_ON(sd_ctl_dir[0].child);
5957 sd_ctl_dir[0].child = entry;
5962 for_each_online_cpu(i) {
5963 snprintf(buf, 32, "cpu%d", i);
5964 entry->procname = kstrdup(buf, GFP_KERNEL);
5966 entry->child = sd_alloc_ctl_cpu_table(i);
5970 WARN_ON(sd_sysctl_header);
5971 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
5974 /* may be called multiple times per register */
5975 static void unregister_sched_domain_sysctl(void)
5977 if (sd_sysctl_header)
5978 unregister_sysctl_table(sd_sysctl_header);
5979 sd_sysctl_header = NULL;
5980 if (sd_ctl_dir[0].child)
5981 sd_free_ctl_entry(&sd_ctl_dir[0].child);
5984 static void register_sched_domain_sysctl(void)
5987 static void unregister_sched_domain_sysctl(void)
5993 * migration_call - callback that gets triggered when a CPU is added.
5994 * Here we can start up the necessary migration thread for the new CPU.
5996 static int __cpuinit
5997 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
5999 struct task_struct *p;
6000 int cpu = (long)hcpu;
6001 unsigned long flags;
6006 case CPU_UP_PREPARE:
6007 case CPU_UP_PREPARE_FROZEN:
6008 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
6011 kthread_bind(p, cpu);
6012 /* Must be high prio: stop_machine expects to yield to it. */
6013 rq = task_rq_lock(p, &flags);
6014 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6015 task_rq_unlock(rq, &flags);
6016 cpu_rq(cpu)->migration_thread = p;
6020 case CPU_ONLINE_FROZEN:
6021 /* Strictly unnecessary, as first user will wake it. */
6022 wake_up_process(cpu_rq(cpu)->migration_thread);
6024 /* Update our root-domain */
6026 spin_lock_irqsave(&rq->lock, flags);
6028 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6029 cpu_set(cpu, rq->rd->online);
6031 spin_unlock_irqrestore(&rq->lock, flags);
6034 #ifdef CONFIG_HOTPLUG_CPU
6035 case CPU_UP_CANCELED:
6036 case CPU_UP_CANCELED_FROZEN:
6037 if (!cpu_rq(cpu)->migration_thread)
6039 /* Unbind it from offline cpu so it can run. Fall thru. */
6040 kthread_bind(cpu_rq(cpu)->migration_thread,
6041 any_online_cpu(cpu_online_map));
6042 kthread_stop(cpu_rq(cpu)->migration_thread);
6043 cpu_rq(cpu)->migration_thread = NULL;
6047 case CPU_DEAD_FROZEN:
6048 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
6049 migrate_live_tasks(cpu);
6051 kthread_stop(rq->migration_thread);
6052 rq->migration_thread = NULL;
6053 /* Idle task back to normal (off runqueue, low prio) */
6054 spin_lock_irq(&rq->lock);
6055 update_rq_clock(rq);
6056 deactivate_task(rq, rq->idle, 0);
6057 rq->idle->static_prio = MAX_PRIO;
6058 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
6059 rq->idle->sched_class = &idle_sched_class;
6060 migrate_dead_tasks(cpu);
6061 spin_unlock_irq(&rq->lock);
6063 migrate_nr_uninterruptible(rq);
6064 BUG_ON(rq->nr_running != 0);
6067 * No need to migrate the tasks: it was best-effort if
6068 * they didn't take sched_hotcpu_mutex. Just wake up
6071 spin_lock_irq(&rq->lock);
6072 while (!list_empty(&rq->migration_queue)) {
6073 struct migration_req *req;
6075 req = list_entry(rq->migration_queue.next,
6076 struct migration_req, list);
6077 list_del_init(&req->list);
6078 complete(&req->done);
6080 spin_unlock_irq(&rq->lock);
6084 case CPU_DYING_FROZEN:
6085 /* Update our root-domain */
6087 spin_lock_irqsave(&rq->lock, flags);
6089 BUG_ON(!cpu_isset(cpu, rq->rd->span));
6090 cpu_clear(cpu, rq->rd->online);
6092 spin_unlock_irqrestore(&rq->lock, flags);
6099 /* Register at highest priority so that task migration (migrate_all_tasks)
6100 * happens before everything else.
6102 static struct notifier_block __cpuinitdata migration_notifier = {
6103 .notifier_call = migration_call,
6107 void __init migration_init(void)
6109 void *cpu = (void *)(long)smp_processor_id();
6112 /* Start one for the boot CPU: */
6113 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
6114 BUG_ON(err == NOTIFY_BAD);
6115 migration_call(&migration_notifier, CPU_ONLINE, cpu);
6116 register_cpu_notifier(&migration_notifier);
6122 /* Number of possible processor ids */
6123 int nr_cpu_ids __read_mostly = NR_CPUS;
6124 EXPORT_SYMBOL(nr_cpu_ids);
6126 #ifdef CONFIG_SCHED_DEBUG
6128 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level)
6130 struct sched_group *group = sd->groups;
6131 cpumask_t groupmask;
6134 cpumask_scnprintf(str, NR_CPUS, sd->span);
6135 cpus_clear(groupmask);
6137 printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6139 if (!(sd->flags & SD_LOAD_BALANCE)) {
6140 printk("does not load-balance\n");
6142 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6147 printk(KERN_CONT "span %s\n", str);
6149 if (!cpu_isset(cpu, sd->span)) {
6150 printk(KERN_ERR "ERROR: domain->span does not contain "
6153 if (!cpu_isset(cpu, group->cpumask)) {
6154 printk(KERN_ERR "ERROR: domain->groups does not contain"
6158 printk(KERN_DEBUG "%*s groups:", level + 1, "");
6162 printk(KERN_ERR "ERROR: group is NULL\n");
6166 if (!group->__cpu_power) {
6167 printk(KERN_CONT "\n");
6168 printk(KERN_ERR "ERROR: domain->cpu_power not "
6173 if (!cpus_weight(group->cpumask)) {
6174 printk(KERN_CONT "\n");
6175 printk(KERN_ERR "ERROR: empty group\n");
6179 if (cpus_intersects(groupmask, group->cpumask)) {
6180 printk(KERN_CONT "\n");
6181 printk(KERN_ERR "ERROR: repeated CPUs\n");
6185 cpus_or(groupmask, groupmask, group->cpumask);
6187 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
6188 printk(KERN_CONT " %s", str);
6190 group = group->next;
6191 } while (group != sd->groups);
6192 printk(KERN_CONT "\n");
6194 if (!cpus_equal(sd->span, groupmask))
6195 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6197 if (sd->parent && !cpus_subset(groupmask, sd->parent->span))
6198 printk(KERN_ERR "ERROR: parent span is not a superset "
6199 "of domain->span\n");
6203 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6208 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6212 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6215 if (sched_domain_debug_one(sd, cpu, level))
6224 # define sched_domain_debug(sd, cpu) do { } while (0)
6227 static int sd_degenerate(struct sched_domain *sd)
6229 if (cpus_weight(sd->span) == 1)
6232 /* Following flags need at least 2 groups */
6233 if (sd->flags & (SD_LOAD_BALANCE |
6234 SD_BALANCE_NEWIDLE |
6238 SD_SHARE_PKG_RESOURCES)) {
6239 if (sd->groups != sd->groups->next)
6243 /* Following flags don't use groups */
6244 if (sd->flags & (SD_WAKE_IDLE |
6253 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6255 unsigned long cflags = sd->flags, pflags = parent->flags;
6257 if (sd_degenerate(parent))
6260 if (!cpus_equal(sd->span, parent->span))
6263 /* Does parent contain flags not in child? */
6264 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6265 if (cflags & SD_WAKE_AFFINE)
6266 pflags &= ~SD_WAKE_BALANCE;
6267 /* Flags needing groups don't count if only 1 group in parent */
6268 if (parent->groups == parent->groups->next) {
6269 pflags &= ~(SD_LOAD_BALANCE |
6270 SD_BALANCE_NEWIDLE |
6274 SD_SHARE_PKG_RESOURCES);
6276 if (~cflags & pflags)
6282 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6284 unsigned long flags;
6285 const struct sched_class *class;
6287 spin_lock_irqsave(&rq->lock, flags);
6290 struct root_domain *old_rd = rq->rd;
6292 for (class = sched_class_highest; class; class = class->next) {
6293 if (class->leave_domain)
6294 class->leave_domain(rq);
6297 cpu_clear(rq->cpu, old_rd->span);
6298 cpu_clear(rq->cpu, old_rd->online);
6300 if (atomic_dec_and_test(&old_rd->refcount))
6304 atomic_inc(&rd->refcount);
6307 cpu_set(rq->cpu, rd->span);
6308 if (cpu_isset(rq->cpu, cpu_online_map))
6309 cpu_set(rq->cpu, rd->online);
6311 for (class = sched_class_highest; class; class = class->next) {
6312 if (class->join_domain)
6313 class->join_domain(rq);
6316 spin_unlock_irqrestore(&rq->lock, flags);
6319 static void init_rootdomain(struct root_domain *rd)
6321 memset(rd, 0, sizeof(*rd));
6323 cpus_clear(rd->span);
6324 cpus_clear(rd->online);
6327 static void init_defrootdomain(void)
6329 init_rootdomain(&def_root_domain);
6330 atomic_set(&def_root_domain.refcount, 1);
6333 static struct root_domain *alloc_rootdomain(void)
6335 struct root_domain *rd;
6337 rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6341 init_rootdomain(rd);
6347 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6348 * hold the hotplug lock.
6351 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6353 struct rq *rq = cpu_rq(cpu);
6354 struct sched_domain *tmp;
6356 /* Remove the sched domains which do not contribute to scheduling. */
6357 for (tmp = sd; tmp; tmp = tmp->parent) {
6358 struct sched_domain *parent = tmp->parent;
6361 if (sd_parent_degenerate(tmp, parent)) {
6362 tmp->parent = parent->parent;
6364 parent->parent->child = tmp;
6368 if (sd && sd_degenerate(sd)) {
6374 sched_domain_debug(sd, cpu);
6376 rq_attach_root(rq, rd);
6377 rcu_assign_pointer(rq->sd, sd);
6380 /* cpus with isolated domains */
6381 static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
6383 /* Setup the mask of cpus configured for isolated domains */
6384 static int __init isolated_cpu_setup(char *str)
6386 int ints[NR_CPUS], i;
6388 str = get_options(str, ARRAY_SIZE(ints), ints);
6389 cpus_clear(cpu_isolated_map);
6390 for (i = 1; i <= ints[0]; i++)
6391 if (ints[i] < NR_CPUS)
6392 cpu_set(ints[i], cpu_isolated_map);
6396 __setup("isolcpus=", isolated_cpu_setup);
6399 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6400 * to a function which identifies what group(along with sched group) a CPU
6401 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6402 * (due to the fact that we keep track of groups covered with a cpumask_t).
6404 * init_sched_build_groups will build a circular linked list of the groups
6405 * covered by the given span, and will set each group's ->cpumask correctly,
6406 * and ->cpu_power to 0.
6409 init_sched_build_groups(cpumask_t span, const cpumask_t *cpu_map,
6410 int (*group_fn)(int cpu, const cpumask_t *cpu_map,
6411 struct sched_group **sg))
6413 struct sched_group *first = NULL, *last = NULL;
6414 cpumask_t covered = CPU_MASK_NONE;
6417 for_each_cpu_mask(i, span) {
6418 struct sched_group *sg;
6419 int group = group_fn(i, cpu_map, &sg);
6422 if (cpu_isset(i, covered))
6425 sg->cpumask = CPU_MASK_NONE;
6426 sg->__cpu_power = 0;
6428 for_each_cpu_mask(j, span) {
6429 if (group_fn(j, cpu_map, NULL) != group)
6432 cpu_set(j, covered);
6433 cpu_set(j, sg->cpumask);
6444 #define SD_NODES_PER_DOMAIN 16
6449 * find_next_best_node - find the next node to include in a sched_domain
6450 * @node: node whose sched_domain we're building
6451 * @used_nodes: nodes already in the sched_domain
6453 * Find the next node to include in a given scheduling domain. Simply
6454 * finds the closest node not already in the @used_nodes map.
6456 * Should use nodemask_t.
6458 static int find_next_best_node(int node, unsigned long *used_nodes)
6460 int i, n, val, min_val, best_node = 0;
6464 for (i = 0; i < MAX_NUMNODES; i++) {
6465 /* Start at @node */
6466 n = (node + i) % MAX_NUMNODES;
6468 if (!nr_cpus_node(n))
6471 /* Skip already used nodes */
6472 if (test_bit(n, used_nodes))
6475 /* Simple min distance search */
6476 val = node_distance(node, n);
6478 if (val < min_val) {
6484 set_bit(best_node, used_nodes);
6489 * sched_domain_node_span - get a cpumask for a node's sched_domain
6490 * @node: node whose cpumask we're constructing
6491 * @size: number of nodes to include in this span
6493 * Given a node, construct a good cpumask for its sched_domain to span. It
6494 * should be one that prevents unnecessary balancing, but also spreads tasks
6497 static cpumask_t sched_domain_node_span(int node)
6499 DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
6500 cpumask_t span, nodemask;
6504 bitmap_zero(used_nodes, MAX_NUMNODES);
6506 nodemask = node_to_cpumask(node);
6507 cpus_or(span, span, nodemask);
6508 set_bit(node, used_nodes);
6510 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
6511 int next_node = find_next_best_node(node, used_nodes);
6513 nodemask = node_to_cpumask(next_node);
6514 cpus_or(span, span, nodemask);
6521 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6524 * SMT sched-domains:
6526 #ifdef CONFIG_SCHED_SMT
6527 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
6528 static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
6531 cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6534 *sg = &per_cpu(sched_group_cpus, cpu);
6540 * multi-core sched-domains:
6542 #ifdef CONFIG_SCHED_MC
6543 static DEFINE_PER_CPU(struct sched_domain, core_domains);
6544 static DEFINE_PER_CPU(struct sched_group, sched_group_core);
6547 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6549 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6552 cpumask_t mask = per_cpu(cpu_sibling_map, cpu);
6553 cpus_and(mask, mask, *cpu_map);
6554 group = first_cpu(mask);
6556 *sg = &per_cpu(sched_group_core, group);
6559 #elif defined(CONFIG_SCHED_MC)
6561 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6564 *sg = &per_cpu(sched_group_core, cpu);
6569 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
6570 static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
6573 cpu_to_phys_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6576 #ifdef CONFIG_SCHED_MC
6577 cpumask_t mask = cpu_coregroup_map(cpu);
6578 cpus_and(mask, mask, *cpu_map);
6579 group = first_cpu(mask);
6580 #elif defined(CONFIG_SCHED_SMT)
6581 cpumask_t mask = per_cpu(cpu_sibling_map, cpu);
6582 cpus_and(mask, mask, *cpu_map);
6583 group = first_cpu(mask);
6588 *sg = &per_cpu(sched_group_phys, group);
6594 * The init_sched_build_groups can't handle what we want to do with node
6595 * groups, so roll our own. Now each node has its own list of groups which
6596 * gets dynamically allocated.
6598 static DEFINE_PER_CPU(struct sched_domain, node_domains);
6599 static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
6601 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
6602 static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
6604 static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
6605 struct sched_group **sg)
6607 cpumask_t nodemask = node_to_cpumask(cpu_to_node(cpu));
6610 cpus_and(nodemask, nodemask, *cpu_map);
6611 group = first_cpu(nodemask);
6614 *sg = &per_cpu(sched_group_allnodes, group);
6618 static void init_numa_sched_groups_power(struct sched_group *group_head)
6620 struct sched_group *sg = group_head;
6626 for_each_cpu_mask(j, sg->cpumask) {
6627 struct sched_domain *sd;
6629 sd = &per_cpu(phys_domains, j);
6630 if (j != first_cpu(sd->groups->cpumask)) {
6632 * Only add "power" once for each
6638 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
6641 } while (sg != group_head);
6646 /* Free memory allocated for various sched_group structures */
6647 static void free_sched_groups(const cpumask_t *cpu_map)
6651 for_each_cpu_mask(cpu, *cpu_map) {
6652 struct sched_group **sched_group_nodes
6653 = sched_group_nodes_bycpu[cpu];
6655 if (!sched_group_nodes)
6658 for (i = 0; i < MAX_NUMNODES; i++) {
6659 cpumask_t nodemask = node_to_cpumask(i);
6660 struct sched_group *oldsg, *sg = sched_group_nodes[i];
6662 cpus_and(nodemask, nodemask, *cpu_map);
6663 if (cpus_empty(nodemask))
6673 if (oldsg != sched_group_nodes[i])
6676 kfree(sched_group_nodes);
6677 sched_group_nodes_bycpu[cpu] = NULL;
6681 static void free_sched_groups(const cpumask_t *cpu_map)
6687 * Initialize sched groups cpu_power.
6689 * cpu_power indicates the capacity of sched group, which is used while
6690 * distributing the load between different sched groups in a sched domain.
6691 * Typically cpu_power for all the groups in a sched domain will be same unless
6692 * there are asymmetries in the topology. If there are asymmetries, group
6693 * having more cpu_power will pickup more load compared to the group having
6696 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
6697 * the maximum number of tasks a group can handle in the presence of other idle
6698 * or lightly loaded groups in the same sched domain.
6700 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
6702 struct sched_domain *child;
6703 struct sched_group *group;
6705 WARN_ON(!sd || !sd->groups);
6707 if (cpu != first_cpu(sd->groups->cpumask))
6712 sd->groups->__cpu_power = 0;
6715 * For perf policy, if the groups in child domain share resources
6716 * (for example cores sharing some portions of the cache hierarchy
6717 * or SMT), then set this domain groups cpu_power such that each group
6718 * can handle only one task, when there are other idle groups in the
6719 * same sched domain.
6721 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
6723 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
6724 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
6729 * add cpu_power of each child group to this groups cpu_power
6731 group = child->groups;
6733 sg_inc_cpu_power(sd->groups, group->__cpu_power);
6734 group = group->next;
6735 } while (group != child->groups);
6739 * Build sched domains for a given set of cpus and attach the sched domains
6740 * to the individual cpus
6742 static int build_sched_domains(const cpumask_t *cpu_map)
6745 struct root_domain *rd;
6747 struct sched_group **sched_group_nodes = NULL;
6748 int sd_allnodes = 0;
6751 * Allocate the per-node list of sched groups
6753 sched_group_nodes = kcalloc(MAX_NUMNODES, sizeof(struct sched_group *),
6755 if (!sched_group_nodes) {
6756 printk(KERN_WARNING "Can not alloc sched group node list\n");
6759 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
6762 rd = alloc_rootdomain();
6764 printk(KERN_WARNING "Cannot alloc root domain\n");
6769 * Set up domains for cpus specified by the cpu_map.
6771 for_each_cpu_mask(i, *cpu_map) {
6772 struct sched_domain *sd = NULL, *p;
6773 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
6775 cpus_and(nodemask, nodemask, *cpu_map);
6778 if (cpus_weight(*cpu_map) >
6779 SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
6780 sd = &per_cpu(allnodes_domains, i);
6781 *sd = SD_ALLNODES_INIT;
6782 sd->span = *cpu_map;
6783 cpu_to_allnodes_group(i, cpu_map, &sd->groups);
6789 sd = &per_cpu(node_domains, i);
6791 sd->span = sched_domain_node_span(cpu_to_node(i));
6795 cpus_and(sd->span, sd->span, *cpu_map);
6799 sd = &per_cpu(phys_domains, i);
6801 sd->span = nodemask;
6805 cpu_to_phys_group(i, cpu_map, &sd->groups);
6807 #ifdef CONFIG_SCHED_MC
6809 sd = &per_cpu(core_domains, i);
6811 sd->span = cpu_coregroup_map(i);
6812 cpus_and(sd->span, sd->span, *cpu_map);
6815 cpu_to_core_group(i, cpu_map, &sd->groups);
6818 #ifdef CONFIG_SCHED_SMT
6820 sd = &per_cpu(cpu_domains, i);
6821 *sd = SD_SIBLING_INIT;
6822 sd->span = per_cpu(cpu_sibling_map, i);
6823 cpus_and(sd->span, sd->span, *cpu_map);
6826 cpu_to_cpu_group(i, cpu_map, &sd->groups);
6830 #ifdef CONFIG_SCHED_SMT
6831 /* Set up CPU (sibling) groups */
6832 for_each_cpu_mask(i, *cpu_map) {
6833 cpumask_t this_sibling_map = per_cpu(cpu_sibling_map, i);
6834 cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
6835 if (i != first_cpu(this_sibling_map))
6838 init_sched_build_groups(this_sibling_map, cpu_map,
6843 #ifdef CONFIG_SCHED_MC
6844 /* Set up multi-core groups */
6845 for_each_cpu_mask(i, *cpu_map) {
6846 cpumask_t this_core_map = cpu_coregroup_map(i);
6847 cpus_and(this_core_map, this_core_map, *cpu_map);
6848 if (i != first_cpu(this_core_map))
6850 init_sched_build_groups(this_core_map, cpu_map,
6851 &cpu_to_core_group);
6855 /* Set up physical groups */
6856 for (i = 0; i < MAX_NUMNODES; i++) {
6857 cpumask_t nodemask = node_to_cpumask(i);
6859 cpus_and(nodemask, nodemask, *cpu_map);
6860 if (cpus_empty(nodemask))
6863 init_sched_build_groups(nodemask, cpu_map, &cpu_to_phys_group);
6867 /* Set up node groups */
6869 init_sched_build_groups(*cpu_map, cpu_map,
6870 &cpu_to_allnodes_group);
6872 for (i = 0; i < MAX_NUMNODES; i++) {
6873 /* Set up node groups */
6874 struct sched_group *sg, *prev;
6875 cpumask_t nodemask = node_to_cpumask(i);
6876 cpumask_t domainspan;
6877 cpumask_t covered = CPU_MASK_NONE;
6880 cpus_and(nodemask, nodemask, *cpu_map);
6881 if (cpus_empty(nodemask)) {
6882 sched_group_nodes[i] = NULL;
6886 domainspan = sched_domain_node_span(i);
6887 cpus_and(domainspan, domainspan, *cpu_map);
6889 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
6891 printk(KERN_WARNING "Can not alloc domain group for "
6895 sched_group_nodes[i] = sg;
6896 for_each_cpu_mask(j, nodemask) {
6897 struct sched_domain *sd;
6899 sd = &per_cpu(node_domains, j);
6902 sg->__cpu_power = 0;
6903 sg->cpumask = nodemask;
6905 cpus_or(covered, covered, nodemask);
6908 for (j = 0; j < MAX_NUMNODES; j++) {
6909 cpumask_t tmp, notcovered;
6910 int n = (i + j) % MAX_NUMNODES;
6912 cpus_complement(notcovered, covered);
6913 cpus_and(tmp, notcovered, *cpu_map);
6914 cpus_and(tmp, tmp, domainspan);
6915 if (cpus_empty(tmp))
6918 nodemask = node_to_cpumask(n);
6919 cpus_and(tmp, tmp, nodemask);
6920 if (cpus_empty(tmp))
6923 sg = kmalloc_node(sizeof(struct sched_group),
6927 "Can not alloc domain group for node %d\n", j);
6930 sg->__cpu_power = 0;
6932 sg->next = prev->next;
6933 cpus_or(covered, covered, tmp);
6940 /* Calculate CPU power for physical packages and nodes */
6941 #ifdef CONFIG_SCHED_SMT
6942 for_each_cpu_mask(i, *cpu_map) {
6943 struct sched_domain *sd = &per_cpu(cpu_domains, i);
6945 init_sched_groups_power(i, sd);
6948 #ifdef CONFIG_SCHED_MC
6949 for_each_cpu_mask(i, *cpu_map) {
6950 struct sched_domain *sd = &per_cpu(core_domains, i);
6952 init_sched_groups_power(i, sd);
6956 for_each_cpu_mask(i, *cpu_map) {
6957 struct sched_domain *sd = &per_cpu(phys_domains, i);
6959 init_sched_groups_power(i, sd);
6963 for (i = 0; i < MAX_NUMNODES; i++)
6964 init_numa_sched_groups_power(sched_group_nodes[i]);
6967 struct sched_group *sg;
6969 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg);
6970 init_numa_sched_groups_power(sg);
6974 /* Attach the domains */
6975 for_each_cpu_mask(i, *cpu_map) {
6976 struct sched_domain *sd;
6977 #ifdef CONFIG_SCHED_SMT
6978 sd = &per_cpu(cpu_domains, i);
6979 #elif defined(CONFIG_SCHED_MC)
6980 sd = &per_cpu(core_domains, i);
6982 sd = &per_cpu(phys_domains, i);
6984 cpu_attach_domain(sd, rd, i);
6991 free_sched_groups(cpu_map);
6996 static cpumask_t *doms_cur; /* current sched domains */
6997 static int ndoms_cur; /* number of sched domains in 'doms_cur' */
7000 * Special case: If a kmalloc of a doms_cur partition (array of
7001 * cpumask_t) fails, then fallback to a single sched domain,
7002 * as determined by the single cpumask_t fallback_doms.
7004 static cpumask_t fallback_doms;
7006 void __attribute__((weak)) arch_update_cpu_topology(void)
7011 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7012 * For now this just excludes isolated cpus, but could be used to
7013 * exclude other special cases in the future.
7015 static int arch_init_sched_domains(const cpumask_t *cpu_map)
7019 arch_update_cpu_topology();
7021 doms_cur = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
7023 doms_cur = &fallback_doms;
7024 cpus_andnot(*doms_cur, *cpu_map, cpu_isolated_map);
7025 err = build_sched_domains(doms_cur);
7026 register_sched_domain_sysctl();
7031 static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
7033 free_sched_groups(cpu_map);
7037 * Detach sched domains from a group of cpus specified in cpu_map
7038 * These cpus will now be attached to the NULL domain
7040 static void detach_destroy_domains(const cpumask_t *cpu_map)
7044 unregister_sched_domain_sysctl();
7046 for_each_cpu_mask(i, *cpu_map)
7047 cpu_attach_domain(NULL, &def_root_domain, i);
7048 synchronize_sched();
7049 arch_destroy_sched_domains(cpu_map);
7053 * Partition sched domains as specified by the 'ndoms_new'
7054 * cpumasks in the array doms_new[] of cpumasks. This compares
7055 * doms_new[] to the current sched domain partitioning, doms_cur[].
7056 * It destroys each deleted domain and builds each new domain.
7058 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
7059 * The masks don't intersect (don't overlap.) We should setup one
7060 * sched domain for each mask. CPUs not in any of the cpumasks will
7061 * not be load balanced. If the same cpumask appears both in the
7062 * current 'doms_cur' domains and in the new 'doms_new', we can leave
7065 * The passed in 'doms_new' should be kmalloc'd. This routine takes
7066 * ownership of it and will kfree it when done with it. If the caller
7067 * failed the kmalloc call, then it can pass in doms_new == NULL,
7068 * and partition_sched_domains() will fallback to the single partition
7071 * Call with hotplug lock held
7073 void partition_sched_domains(int ndoms_new, cpumask_t *doms_new)
7079 /* always unregister in case we don't destroy any domains */
7080 unregister_sched_domain_sysctl();
7082 if (doms_new == NULL) {
7084 doms_new = &fallback_doms;
7085 cpus_andnot(doms_new[0], cpu_online_map, cpu_isolated_map);
7088 /* Destroy deleted domains */
7089 for (i = 0; i < ndoms_cur; i++) {
7090 for (j = 0; j < ndoms_new; j++) {
7091 if (cpus_equal(doms_cur[i], doms_new[j]))
7094 /* no match - a current sched domain not in new doms_new[] */
7095 detach_destroy_domains(doms_cur + i);
7100 /* Build new domains */
7101 for (i = 0; i < ndoms_new; i++) {
7102 for (j = 0; j < ndoms_cur; j++) {
7103 if (cpus_equal(doms_new[i], doms_cur[j]))
7106 /* no match - add a new doms_new */
7107 build_sched_domains(doms_new + i);
7112 /* Remember the new sched domains */
7113 if (doms_cur != &fallback_doms)
7115 doms_cur = doms_new;
7116 ndoms_cur = ndoms_new;
7118 register_sched_domain_sysctl();
7123 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7124 int arch_reinit_sched_domains(void)
7129 detach_destroy_domains(&cpu_online_map);
7130 err = arch_init_sched_domains(&cpu_online_map);
7136 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7140 if (buf[0] != '0' && buf[0] != '1')
7144 sched_smt_power_savings = (buf[0] == '1');
7146 sched_mc_power_savings = (buf[0] == '1');
7148 ret = arch_reinit_sched_domains();
7150 return ret ? ret : count;
7153 #ifdef CONFIG_SCHED_MC
7154 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
7156 return sprintf(page, "%u\n", sched_mc_power_savings);
7158 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
7159 const char *buf, size_t count)
7161 return sched_power_savings_store(buf, count, 0);
7163 static SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
7164 sched_mc_power_savings_store);
7167 #ifdef CONFIG_SCHED_SMT
7168 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
7170 return sprintf(page, "%u\n", sched_smt_power_savings);
7172 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
7173 const char *buf, size_t count)
7175 return sched_power_savings_store(buf, count, 1);
7177 static SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
7178 sched_smt_power_savings_store);
7181 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7185 #ifdef CONFIG_SCHED_SMT
7187 err = sysfs_create_file(&cls->kset.kobj,
7188 &attr_sched_smt_power_savings.attr);
7190 #ifdef CONFIG_SCHED_MC
7191 if (!err && mc_capable())
7192 err = sysfs_create_file(&cls->kset.kobj,
7193 &attr_sched_mc_power_savings.attr);
7200 * Force a reinitialization of the sched domains hierarchy. The domains
7201 * and groups cannot be updated in place without racing with the balancing
7202 * code, so we temporarily attach all running cpus to the NULL domain
7203 * which will prevent rebalancing while the sched domains are recalculated.
7205 static int update_sched_domains(struct notifier_block *nfb,
7206 unsigned long action, void *hcpu)
7209 case CPU_UP_PREPARE:
7210 case CPU_UP_PREPARE_FROZEN:
7211 case CPU_DOWN_PREPARE:
7212 case CPU_DOWN_PREPARE_FROZEN:
7213 detach_destroy_domains(&cpu_online_map);
7216 case CPU_UP_CANCELED:
7217 case CPU_UP_CANCELED_FROZEN:
7218 case CPU_DOWN_FAILED:
7219 case CPU_DOWN_FAILED_FROZEN:
7221 case CPU_ONLINE_FROZEN:
7223 case CPU_DEAD_FROZEN:
7225 * Fall through and re-initialise the domains.
7232 /* The hotplug lock is already held by cpu_up/cpu_down */
7233 arch_init_sched_domains(&cpu_online_map);
7238 void __init sched_init_smp(void)
7240 cpumask_t non_isolated_cpus;
7243 arch_init_sched_domains(&cpu_online_map);
7244 cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
7245 if (cpus_empty(non_isolated_cpus))
7246 cpu_set(smp_processor_id(), non_isolated_cpus);
7248 /* XXX: Theoretical race here - CPU may be hotplugged now */
7249 hotcpu_notifier(update_sched_domains, 0);
7251 /* Move init over to a non-isolated CPU */
7252 if (set_cpus_allowed(current, non_isolated_cpus) < 0)
7254 sched_init_granularity();
7257 void __init sched_init_smp(void)
7259 sched_init_granularity();
7261 #endif /* CONFIG_SMP */
7263 int in_sched_functions(unsigned long addr)
7265 return in_lock_functions(addr) ||
7266 (addr >= (unsigned long)__sched_text_start
7267 && addr < (unsigned long)__sched_text_end);
7270 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
7272 cfs_rq->tasks_timeline = RB_ROOT;
7273 #ifdef CONFIG_FAIR_GROUP_SCHED
7276 cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7279 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
7281 struct rt_prio_array *array;
7284 array = &rt_rq->active;
7285 for (i = 0; i < MAX_RT_PRIO; i++) {
7286 INIT_LIST_HEAD(array->queue + i);
7287 __clear_bit(i, array->bitmap);
7289 /* delimiter for bitsearch: */
7290 __set_bit(MAX_RT_PRIO, array->bitmap);
7292 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
7293 rt_rq->highest_prio = MAX_RT_PRIO;
7296 rt_rq->rt_nr_migratory = 0;
7297 rt_rq->overloaded = 0;
7301 rt_rq->rt_throttled = 0;
7303 #ifdef CONFIG_RT_GROUP_SCHED
7304 rt_rq->rt_nr_boosted = 0;
7309 #ifdef CONFIG_FAIR_GROUP_SCHED
7310 static void init_tg_cfs_entry(struct rq *rq, struct task_group *tg,
7311 struct cfs_rq *cfs_rq, struct sched_entity *se,
7314 tg->cfs_rq[cpu] = cfs_rq;
7315 init_cfs_rq(cfs_rq, rq);
7318 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
7321 se->cfs_rq = &rq->cfs;
7323 se->load.weight = tg->shares;
7324 se->load.inv_weight = div64_64(1ULL<<32, se->load.weight);
7329 #ifdef CONFIG_RT_GROUP_SCHED
7330 static void init_tg_rt_entry(struct rq *rq, struct task_group *tg,
7331 struct rt_rq *rt_rq, struct sched_rt_entity *rt_se,
7334 tg->rt_rq[cpu] = rt_rq;
7335 init_rt_rq(rt_rq, rq);
7337 rt_rq->rt_se = rt_se;
7339 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
7341 tg->rt_se[cpu] = rt_se;
7342 rt_se->rt_rq = &rq->rt;
7343 rt_se->my_q = rt_rq;
7344 rt_se->parent = NULL;
7345 INIT_LIST_HEAD(&rt_se->run_list);
7349 void __init sched_init(void)
7351 int highest_cpu = 0;
7355 init_defrootdomain();
7358 init_rt_bandwidth(&def_rt_bandwidth,
7359 global_rt_period(), global_rt_runtime());
7361 #ifdef CONFIG_RT_GROUP_SCHED
7362 init_rt_bandwidth(&init_task_group.rt_bandwidth,
7363 global_rt_period(), global_rt_runtime());
7366 #ifdef CONFIG_GROUP_SCHED
7367 list_add(&init_task_group.list, &task_groups);
7370 for_each_possible_cpu(i) {
7374 spin_lock_init(&rq->lock);
7375 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
7378 update_last_tick_seen(rq);
7379 init_cfs_rq(&rq->cfs, rq);
7380 init_rt_rq(&rq->rt, rq);
7381 #ifdef CONFIG_FAIR_GROUP_SCHED
7382 init_task_group.shares = init_task_group_load;
7383 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7384 init_tg_cfs_entry(rq, &init_task_group,
7385 &per_cpu(init_cfs_rq, i),
7386 &per_cpu(init_sched_entity, i), i, 1);
7389 #ifdef CONFIG_RT_GROUP_SCHED
7390 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
7391 init_tg_rt_entry(rq, &init_task_group,
7392 &per_cpu(init_rt_rq, i),
7393 &per_cpu(init_sched_rt_entity, i), i, 1);
7396 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7397 rq->cpu_load[j] = 0;
7401 rq->active_balance = 0;
7402 rq->next_balance = jiffies;
7405 rq->migration_thread = NULL;
7406 INIT_LIST_HEAD(&rq->migration_queue);
7407 rq_attach_root(rq, &def_root_domain);
7410 atomic_set(&rq->nr_iowait, 0);
7414 set_load_weight(&init_task);
7416 #ifdef CONFIG_PREEMPT_NOTIFIERS
7417 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
7421 nr_cpu_ids = highest_cpu + 1;
7422 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
7425 #ifdef CONFIG_RT_MUTEXES
7426 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
7430 * The boot idle thread does lazy MMU switching as well:
7432 atomic_inc(&init_mm.mm_count);
7433 enter_lazy_tlb(&init_mm, current);
7436 * Make us the idle thread. Technically, schedule() should not be
7437 * called from this thread, however somewhere below it might be,
7438 * but because we are the idle thread, we just pick up running again
7439 * when this runqueue becomes "idle".
7441 init_idle(current, smp_processor_id());
7443 * During early bootup we pretend to be a normal task:
7445 current->sched_class = &fair_sched_class;
7447 scheduler_running = 1;
7450 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
7451 void __might_sleep(char *file, int line)
7454 static unsigned long prev_jiffy; /* ratelimiting */
7456 if ((in_atomic() || irqs_disabled()) &&
7457 system_state == SYSTEM_RUNNING && !oops_in_progress) {
7458 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7460 prev_jiffy = jiffies;
7461 printk(KERN_ERR "BUG: sleeping function called from invalid"
7462 " context at %s:%d\n", file, line);
7463 printk("in_atomic():%d, irqs_disabled():%d\n",
7464 in_atomic(), irqs_disabled());
7465 debug_show_held_locks(current);
7466 if (irqs_disabled())
7467 print_irqtrace_events(current);
7472 EXPORT_SYMBOL(__might_sleep);
7475 #ifdef CONFIG_MAGIC_SYSRQ
7476 static void normalize_task(struct rq *rq, struct task_struct *p)
7479 update_rq_clock(rq);
7480 on_rq = p->se.on_rq;
7482 deactivate_task(rq, p, 0);
7483 __setscheduler(rq, p, SCHED_NORMAL, 0);
7485 activate_task(rq, p, 0);
7486 resched_task(rq->curr);
7490 void normalize_rt_tasks(void)
7492 struct task_struct *g, *p;
7493 unsigned long flags;
7496 read_lock_irqsave(&tasklist_lock, flags);
7497 do_each_thread(g, p) {
7499 * Only normalize user tasks:
7504 p->se.exec_start = 0;
7505 #ifdef CONFIG_SCHEDSTATS
7506 p->se.wait_start = 0;
7507 p->se.sleep_start = 0;
7508 p->se.block_start = 0;
7510 task_rq(p)->clock = 0;
7514 * Renice negative nice level userspace
7517 if (TASK_NICE(p) < 0 && p->mm)
7518 set_user_nice(p, 0);
7522 spin_lock(&p->pi_lock);
7523 rq = __task_rq_lock(p);
7525 normalize_task(rq, p);
7527 __task_rq_unlock(rq);
7528 spin_unlock(&p->pi_lock);
7529 } while_each_thread(g, p);
7531 read_unlock_irqrestore(&tasklist_lock, flags);
7534 #endif /* CONFIG_MAGIC_SYSRQ */
7538 * These functions are only useful for the IA64 MCA handling.
7540 * They can only be called when the whole system has been
7541 * stopped - every CPU needs to be quiescent, and no scheduling
7542 * activity can take place. Using them for anything else would
7543 * be a serious bug, and as a result, they aren't even visible
7544 * under any other configuration.
7548 * curr_task - return the current task for a given cpu.
7549 * @cpu: the processor in question.
7551 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7553 struct task_struct *curr_task(int cpu)
7555 return cpu_curr(cpu);
7559 * set_curr_task - set the current task for a given cpu.
7560 * @cpu: the processor in question.
7561 * @p: the task pointer to set.
7563 * Description: This function must only be used when non-maskable interrupts
7564 * are serviced on a separate stack. It allows the architecture to switch the
7565 * notion of the current task on a cpu in a non-blocking manner. This function
7566 * must be called with all CPU's synchronized, and interrupts disabled, the
7567 * and caller must save the original value of the current task (see
7568 * curr_task() above) and restore that value before reenabling interrupts and
7569 * re-starting the system.
7571 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7573 void set_curr_task(int cpu, struct task_struct *p)
7580 #ifdef CONFIG_FAIR_GROUP_SCHED
7581 static void free_fair_sched_group(struct task_group *tg)
7585 for_each_possible_cpu(i) {
7587 kfree(tg->cfs_rq[i]);
7596 static int alloc_fair_sched_group(struct task_group *tg)
7598 struct cfs_rq *cfs_rq;
7599 struct sched_entity *se;
7603 tg->cfs_rq = kzalloc(sizeof(cfs_rq) * NR_CPUS, GFP_KERNEL);
7606 tg->se = kzalloc(sizeof(se) * NR_CPUS, GFP_KERNEL);
7610 tg->shares = NICE_0_LOAD;
7612 for_each_possible_cpu(i) {
7615 cfs_rq = kmalloc_node(sizeof(struct cfs_rq),
7616 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
7620 se = kmalloc_node(sizeof(struct sched_entity),
7621 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
7625 init_tg_cfs_entry(rq, tg, cfs_rq, se, i, 0);
7634 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
7636 list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
7637 &cpu_rq(cpu)->leaf_cfs_rq_list);
7640 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
7642 list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
7645 static inline void free_fair_sched_group(struct task_group *tg)
7649 static inline int alloc_fair_sched_group(struct task_group *tg)
7654 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
7658 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
7663 #ifdef CONFIG_RT_GROUP_SCHED
7664 static void free_rt_sched_group(struct task_group *tg)
7668 destroy_rt_bandwidth(&tg->rt_bandwidth);
7670 for_each_possible_cpu(i) {
7672 kfree(tg->rt_rq[i]);
7674 kfree(tg->rt_se[i]);
7681 static int alloc_rt_sched_group(struct task_group *tg)
7683 struct rt_rq *rt_rq;
7684 struct sched_rt_entity *rt_se;
7688 tg->rt_rq = kzalloc(sizeof(rt_rq) * NR_CPUS, GFP_KERNEL);
7691 tg->rt_se = kzalloc(sizeof(rt_se) * NR_CPUS, GFP_KERNEL);
7695 init_rt_bandwidth(&tg->rt_bandwidth,
7696 ktime_to_ns(def_rt_bandwidth.rt_period), 0);
7698 for_each_possible_cpu(i) {
7701 rt_rq = kmalloc_node(sizeof(struct rt_rq),
7702 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
7706 rt_se = kmalloc_node(sizeof(struct sched_rt_entity),
7707 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
7711 init_tg_rt_entry(rq, tg, rt_rq, rt_se, i, 0);
7720 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
7722 list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
7723 &cpu_rq(cpu)->leaf_rt_rq_list);
7726 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
7728 list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
7731 static inline void free_rt_sched_group(struct task_group *tg)
7735 static inline int alloc_rt_sched_group(struct task_group *tg)
7740 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
7744 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
7749 #ifdef CONFIG_GROUP_SCHED
7750 static void free_sched_group(struct task_group *tg)
7752 free_fair_sched_group(tg);
7753 free_rt_sched_group(tg);
7757 /* allocate runqueue etc for a new task group */
7758 struct task_group *sched_create_group(void)
7760 struct task_group *tg;
7761 unsigned long flags;
7764 tg = kzalloc(sizeof(*tg), GFP_KERNEL);
7766 return ERR_PTR(-ENOMEM);
7768 if (!alloc_fair_sched_group(tg))
7771 if (!alloc_rt_sched_group(tg))
7774 spin_lock_irqsave(&task_group_lock, flags);
7775 for_each_possible_cpu(i) {
7776 register_fair_sched_group(tg, i);
7777 register_rt_sched_group(tg, i);
7779 list_add_rcu(&tg->list, &task_groups);
7780 spin_unlock_irqrestore(&task_group_lock, flags);
7785 free_sched_group(tg);
7786 return ERR_PTR(-ENOMEM);
7789 /* rcu callback to free various structures associated with a task group */
7790 static void free_sched_group_rcu(struct rcu_head *rhp)
7792 /* now it should be safe to free those cfs_rqs */
7793 free_sched_group(container_of(rhp, struct task_group, rcu));
7796 /* Destroy runqueue etc associated with a task group */
7797 void sched_destroy_group(struct task_group *tg)
7799 unsigned long flags;
7802 spin_lock_irqsave(&task_group_lock, flags);
7803 for_each_possible_cpu(i) {
7804 unregister_fair_sched_group(tg, i);
7805 unregister_rt_sched_group(tg, i);
7807 list_del_rcu(&tg->list);
7808 spin_unlock_irqrestore(&task_group_lock, flags);
7810 /* wait for possible concurrent references to cfs_rqs complete */
7811 call_rcu(&tg->rcu, free_sched_group_rcu);
7814 /* change task's runqueue when it moves between groups.
7815 * The caller of this function should have put the task in its new group
7816 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7817 * reflect its new group.
7819 void sched_move_task(struct task_struct *tsk)
7822 unsigned long flags;
7825 rq = task_rq_lock(tsk, &flags);
7827 update_rq_clock(rq);
7829 running = task_current(rq, tsk);
7830 on_rq = tsk->se.on_rq;
7833 dequeue_task(rq, tsk, 0);
7834 if (unlikely(running))
7835 tsk->sched_class->put_prev_task(rq, tsk);
7837 set_task_rq(tsk, task_cpu(tsk));
7839 #ifdef CONFIG_FAIR_GROUP_SCHED
7840 if (tsk->sched_class->moved_group)
7841 tsk->sched_class->moved_group(tsk);
7844 if (unlikely(running))
7845 tsk->sched_class->set_curr_task(rq);
7847 enqueue_task(rq, tsk, 0);
7849 task_rq_unlock(rq, &flags);
7853 #ifdef CONFIG_FAIR_GROUP_SCHED
7854 static void set_se_shares(struct sched_entity *se, unsigned long shares)
7856 struct cfs_rq *cfs_rq = se->cfs_rq;
7857 struct rq *rq = cfs_rq->rq;
7860 spin_lock_irq(&rq->lock);
7864 dequeue_entity(cfs_rq, se, 0);
7866 se->load.weight = shares;
7867 se->load.inv_weight = div64_64((1ULL<<32), shares);
7870 enqueue_entity(cfs_rq, se, 0);
7872 spin_unlock_irq(&rq->lock);
7875 static DEFINE_MUTEX(shares_mutex);
7877 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
7880 unsigned long flags;
7883 * A weight of 0 or 1 can cause arithmetics problems.
7884 * (The default weight is 1024 - so there's no practical
7885 * limitation from this.)
7890 mutex_lock(&shares_mutex);
7891 if (tg->shares == shares)
7894 spin_lock_irqsave(&task_group_lock, flags);
7895 for_each_possible_cpu(i)
7896 unregister_fair_sched_group(tg, i);
7897 spin_unlock_irqrestore(&task_group_lock, flags);
7899 /* wait for any ongoing reference to this group to finish */
7900 synchronize_sched();
7903 * Now we are free to modify the group's share on each cpu
7904 * w/o tripping rebalance_share or load_balance_fair.
7906 tg->shares = shares;
7907 for_each_possible_cpu(i)
7908 set_se_shares(tg->se[i], shares);
7911 * Enable load balance activity on this group, by inserting it back on
7912 * each cpu's rq->leaf_cfs_rq_list.
7914 spin_lock_irqsave(&task_group_lock, flags);
7915 for_each_possible_cpu(i)
7916 register_fair_sched_group(tg, i);
7917 spin_unlock_irqrestore(&task_group_lock, flags);
7919 mutex_unlock(&shares_mutex);
7923 unsigned long sched_group_shares(struct task_group *tg)
7929 #ifdef CONFIG_RT_GROUP_SCHED
7931 * Ensure that the real time constraints are schedulable.
7933 static DEFINE_MUTEX(rt_constraints_mutex);
7935 static unsigned long to_ratio(u64 period, u64 runtime)
7937 if (runtime == RUNTIME_INF)
7940 return div64_64(runtime << 16, period);
7943 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
7945 struct task_group *tgi;
7946 unsigned long total = 0;
7947 unsigned long global_ratio =
7948 to_ratio(global_rt_period(), global_rt_runtime());
7951 list_for_each_entry_rcu(tgi, &task_groups, list) {
7955 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
7956 tgi->rt_bandwidth.rt_runtime);
7960 return total + to_ratio(period, runtime) < global_ratio;
7963 /* Must be called with tasklist_lock held */
7964 static inline int tg_has_rt_tasks(struct task_group *tg)
7966 struct task_struct *g, *p;
7967 do_each_thread(g, p) {
7968 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
7970 } while_each_thread(g, p);
7974 static int tg_set_bandwidth(struct task_group *tg,
7975 u64 rt_period, u64 rt_runtime)
7979 mutex_lock(&rt_constraints_mutex);
7980 read_lock(&tasklist_lock);
7981 if (rt_runtime_us == 0 && tg_has_rt_tasks(tg)) {
7985 if (!__rt_schedulable(tg, rt_period, rt_runtime)) {
7989 tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
7990 tg->rt_bandwidth.rt_runtime = rt_runtime;
7992 read_unlock(&tasklist_lock);
7993 mutex_unlock(&rt_constraints_mutex);
7998 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8000 u64 rt_runtime, rt_period;
8002 rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8003 rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8004 if (rt_runtime_us < 0)
8005 rt_runtime = RUNTIME_INF;
8007 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8010 long sched_group_rt_runtime(struct task_group *tg)
8014 if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8017 rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8018 do_div(rt_runtime_us, NSEC_PER_USEC);
8019 return rt_runtime_us;
8022 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
8024 u64 rt_runtime, rt_period;
8026 rt_period = (u64)rt_period_us * NSEC_PER_USEC;
8027 rt_runtime = tg->rt_bandwidth.rt_runtime;
8029 return tg_set_bandwidth(tg, rt_period, rt_runtime);
8032 long sched_group_rt_period(struct task_group *tg)
8036 rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8037 do_div(rt_period_us, NSEC_PER_USEC);
8038 return rt_period_us;
8041 static int sched_rt_global_constraints(void)
8045 mutex_lock(&rt_constraints_mutex);
8046 if (!__rt_schedulable(NULL, 1, 0))
8048 mutex_unlock(&rt_constraints_mutex);
8053 static int sched_rt_global_constraints(void)
8059 int sched_rt_handler(struct ctl_table *table, int write,
8060 struct file *filp, void __user *buffer, size_t *lenp,
8064 int old_period, old_runtime;
8065 static DEFINE_MUTEX(mutex);
8068 old_period = sysctl_sched_rt_period;
8069 old_runtime = sysctl_sched_rt_runtime;
8071 ret = proc_dointvec(table, write, filp, buffer, lenp, ppos);
8073 if (!ret && write) {
8074 ret = sched_rt_global_constraints();
8076 sysctl_sched_rt_period = old_period;
8077 sysctl_sched_rt_runtime = old_runtime;
8079 def_rt_bandwidth.rt_runtime = global_rt_runtime();
8080 def_rt_bandwidth.rt_period =
8081 ns_to_ktime(global_rt_period());
8084 mutex_unlock(&mutex);
8089 #ifdef CONFIG_CGROUP_SCHED
8091 /* return corresponding task_group object of a cgroup */
8092 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
8094 return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
8095 struct task_group, css);
8098 static struct cgroup_subsys_state *
8099 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
8101 struct task_group *tg;
8103 if (!cgrp->parent) {
8104 /* This is early initialization for the top cgroup */
8105 init_task_group.css.cgroup = cgrp;
8106 return &init_task_group.css;
8109 /* we support only 1-level deep hierarchical scheduler atm */
8110 if (cgrp->parent->parent)
8111 return ERR_PTR(-EINVAL);
8113 tg = sched_create_group();
8115 return ERR_PTR(-ENOMEM);
8117 /* Bind the cgroup to task_group object we just created */
8118 tg->css.cgroup = cgrp;
8124 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
8126 struct task_group *tg = cgroup_tg(cgrp);
8128 sched_destroy_group(tg);
8132 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8133 struct task_struct *tsk)
8135 #ifdef CONFIG_RT_GROUP_SCHED
8136 /* Don't accept realtime tasks when there is no way for them to run */
8137 if (rt_task(tsk) && cgroup_tg(cgrp)->rt_bandwidth.rt_runtime == 0)
8140 /* We don't support RT-tasks being in separate groups */
8141 if (tsk->sched_class != &fair_sched_class)
8149 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8150 struct cgroup *old_cont, struct task_struct *tsk)
8152 sched_move_task(tsk);
8155 #ifdef CONFIG_FAIR_GROUP_SCHED
8156 static int cpu_shares_write_uint(struct cgroup *cgrp, struct cftype *cftype,
8159 return sched_group_set_shares(cgroup_tg(cgrp), shareval);
8162 static u64 cpu_shares_read_uint(struct cgroup *cgrp, struct cftype *cft)
8164 struct task_group *tg = cgroup_tg(cgrp);
8166 return (u64) tg->shares;
8170 #ifdef CONFIG_RT_GROUP_SCHED
8171 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
8173 const char __user *userbuf,
8174 size_t nbytes, loff_t *unused_ppos)
8183 if (nbytes >= sizeof(buffer))
8185 if (copy_from_user(buffer, userbuf, nbytes))
8188 buffer[nbytes] = 0; /* nul-terminate */
8190 /* strip newline if necessary */
8191 if (nbytes && (buffer[nbytes-1] == '\n'))
8192 buffer[nbytes-1] = 0;
8193 val = simple_strtoll(buffer, &end, 0);
8197 /* Pass to subsystem */
8198 retval = sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
8204 static ssize_t cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft,
8206 char __user *buf, size_t nbytes,
8210 long val = sched_group_rt_runtime(cgroup_tg(cgrp));
8211 int len = sprintf(tmp, "%ld\n", val);
8213 return simple_read_from_buffer(buf, nbytes, ppos, tmp, len);
8216 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
8219 return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
8222 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
8224 return sched_group_rt_period(cgroup_tg(cgrp));
8228 static struct cftype cpu_files[] = {
8229 #ifdef CONFIG_FAIR_GROUP_SCHED
8232 .read_uint = cpu_shares_read_uint,
8233 .write_uint = cpu_shares_write_uint,
8236 #ifdef CONFIG_RT_GROUP_SCHED
8238 .name = "rt_runtime_us",
8239 .read = cpu_rt_runtime_read,
8240 .write = cpu_rt_runtime_write,
8243 .name = "rt_period_us",
8244 .read_uint = cpu_rt_period_read_uint,
8245 .write_uint = cpu_rt_period_write_uint,
8250 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
8252 return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
8255 struct cgroup_subsys cpu_cgroup_subsys = {
8257 .create = cpu_cgroup_create,
8258 .destroy = cpu_cgroup_destroy,
8259 .can_attach = cpu_cgroup_can_attach,
8260 .attach = cpu_cgroup_attach,
8261 .populate = cpu_cgroup_populate,
8262 .subsys_id = cpu_cgroup_subsys_id,
8266 #endif /* CONFIG_CGROUP_SCHED */
8268 #ifdef CONFIG_CGROUP_CPUACCT
8271 * CPU accounting code for task groups.
8273 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
8274 * (balbir@in.ibm.com).
8277 /* track cpu usage of a group of tasks */
8279 struct cgroup_subsys_state css;
8280 /* cpuusage holds pointer to a u64-type object on every cpu */
8284 struct cgroup_subsys cpuacct_subsys;
8286 /* return cpu accounting group corresponding to this container */
8287 static inline struct cpuacct *cgroup_ca(struct cgroup *cont)
8289 return container_of(cgroup_subsys_state(cont, cpuacct_subsys_id),
8290 struct cpuacct, css);
8293 /* return cpu accounting group to which this task belongs */
8294 static inline struct cpuacct *task_ca(struct task_struct *tsk)
8296 return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
8297 struct cpuacct, css);
8300 /* create a new cpu accounting group */
8301 static struct cgroup_subsys_state *cpuacct_create(
8302 struct cgroup_subsys *ss, struct cgroup *cont)
8304 struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
8307 return ERR_PTR(-ENOMEM);
8309 ca->cpuusage = alloc_percpu(u64);
8310 if (!ca->cpuusage) {
8312 return ERR_PTR(-ENOMEM);
8318 /* destroy an existing cpu accounting group */
8320 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cont)
8322 struct cpuacct *ca = cgroup_ca(cont);
8324 free_percpu(ca->cpuusage);
8328 /* return total cpu usage (in nanoseconds) of a group */
8329 static u64 cpuusage_read(struct cgroup *cont, struct cftype *cft)
8331 struct cpuacct *ca = cgroup_ca(cont);
8332 u64 totalcpuusage = 0;
8335 for_each_possible_cpu(i) {
8336 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
8339 * Take rq->lock to make 64-bit addition safe on 32-bit
8342 spin_lock_irq(&cpu_rq(i)->lock);
8343 totalcpuusage += *cpuusage;
8344 spin_unlock_irq(&cpu_rq(i)->lock);
8347 return totalcpuusage;
8350 static struct cftype files[] = {
8353 .read_uint = cpuusage_read,
8357 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cont)
8359 return cgroup_add_files(cont, ss, files, ARRAY_SIZE(files));
8363 * charge this task's execution time to its accounting group.
8365 * called with rq->lock held.
8367 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
8371 if (!cpuacct_subsys.active)
8376 u64 *cpuusage = percpu_ptr(ca->cpuusage, task_cpu(tsk));
8378 *cpuusage += cputime;
8382 struct cgroup_subsys cpuacct_subsys = {
8384 .create = cpuacct_create,
8385 .destroy = cpuacct_destroy,
8386 .populate = cpuacct_populate,
8387 .subsys_id = cpuacct_subsys_id,
8389 #endif /* CONFIG_CGROUP_CPUACCT */