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>
71 #include <asm/irq_regs.h>
74 * Scheduler clock - returns current time in nanosec units.
75 * This is default implementation.
76 * Architectures and sub-architectures can override this.
78 unsigned long long __attribute__((weak
)) sched_clock(void)
80 return (unsigned long long)jiffies
* (NSEC_PER_SEC
/ HZ
);
84 * Convert user-nice values [ -20 ... 0 ... 19 ]
85 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
88 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
89 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
90 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
93 * 'User priority' is the nice value converted to something we
94 * can work with better when scaling various scheduler parameters,
95 * it's a [ 0 ... 39 ] range.
97 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
98 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
99 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
102 * Helpers for converting nanosecond timing to jiffy resolution
104 #define NS_TO_JIFFIES(TIME) ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
106 #define NICE_0_LOAD SCHED_LOAD_SCALE
107 #define NICE_0_SHIFT SCHED_LOAD_SHIFT
110 * These are the 'tuning knobs' of the scheduler:
112 * default timeslice is 100 msecs (used only for SCHED_RR tasks).
113 * Timeslices get refilled after they expire.
115 #define DEF_TIMESLICE (100 * HZ / 1000)
119 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
120 * Since cpu_power is a 'constant', we can use a reciprocal divide.
122 static inline u32
sg_div_cpu_power(const struct sched_group
*sg
, u32 load
)
124 return reciprocal_divide(load
, sg
->reciprocal_cpu_power
);
128 * Each time a sched group cpu_power is changed,
129 * we must compute its reciprocal value
131 static inline void sg_inc_cpu_power(struct sched_group
*sg
, u32 val
)
133 sg
->__cpu_power
+= val
;
134 sg
->reciprocal_cpu_power
= reciprocal_value(sg
->__cpu_power
);
138 static inline int rt_policy(int policy
)
140 if (unlikely(policy
== SCHED_FIFO
) || unlikely(policy
== SCHED_RR
))
145 static inline int task_has_rt_policy(struct task_struct
*p
)
147 return rt_policy(p
->policy
);
151 * This is the priority-queue data structure of the RT scheduling class:
153 struct rt_prio_array
{
154 DECLARE_BITMAP(bitmap
, MAX_RT_PRIO
+1); /* include 1 bit for delimiter */
155 struct list_head queue
[MAX_RT_PRIO
];
158 #ifdef CONFIG_GROUP_SCHED
160 #include <linux/cgroup.h>
164 static LIST_HEAD(task_groups
);
166 /* task group related information */
168 #ifdef CONFIG_CGROUP_SCHED
169 struct cgroup_subsys_state css
;
172 #ifdef CONFIG_FAIR_GROUP_SCHED
173 /* schedulable entities of this group on each cpu */
174 struct sched_entity
**se
;
175 /* runqueue "owned" by this group on each cpu */
176 struct cfs_rq
**cfs_rq
;
179 * shares assigned to a task group governs how much of cpu bandwidth
180 * is allocated to the group. The more shares a group has, the more is
181 * the cpu bandwidth allocated to it.
183 * For ex, lets say that there are three task groups, A, B and C which
184 * have been assigned shares 1000, 2000 and 3000 respectively. Then,
185 * cpu bandwidth allocated by the scheduler to task groups A, B and C
188 * Bw(A) = 1000/(1000+2000+3000) * 100 = 16.66%
189 * Bw(B) = 2000/(1000+2000+3000) * 100 = 33.33%
190 * Bw(C) = 3000/(1000+2000+3000) * 100 = 50%
192 * The weight assigned to a task group's schedulable entities on every
193 * cpu (task_group.se[a_cpu]->load.weight) is derived from the task
194 * group's shares. For ex: lets say that task group A has been
195 * assigned shares of 1000 and there are two CPUs in a system. Then,
197 * tg_A->se[0]->load.weight = tg_A->se[1]->load.weight = 1000;
199 * Note: It's not necessary that each of a task's group schedulable
200 * entity have the same weight on all CPUs. If the group
201 * has 2 of its tasks on CPU0 and 1 task on CPU1, then a
202 * better distribution of weight could be:
204 * tg_A->se[0]->load.weight = 2/3 * 2000 = 1333
205 * tg_A->se[1]->load.weight = 1/2 * 2000 = 667
207 * rebalance_shares() is responsible for distributing the shares of a
208 * task groups like this among the group's schedulable entities across
212 unsigned long shares
;
215 #ifdef CONFIG_RT_GROUP_SCHED
216 struct sched_rt_entity
**rt_se
;
217 struct rt_rq
**rt_rq
;
223 struct list_head list
;
226 #ifdef CONFIG_FAIR_GROUP_SCHED
227 /* Default task group's sched entity on each cpu */
228 static DEFINE_PER_CPU(struct sched_entity
, init_sched_entity
);
229 /* Default task group's cfs_rq on each cpu */
230 static DEFINE_PER_CPU(struct cfs_rq
, init_cfs_rq
) ____cacheline_aligned_in_smp
;
232 static struct sched_entity
*init_sched_entity_p
[NR_CPUS
];
233 static struct cfs_rq
*init_cfs_rq_p
[NR_CPUS
];
236 #ifdef CONFIG_RT_GROUP_SCHED
237 static DEFINE_PER_CPU(struct sched_rt_entity
, init_sched_rt_entity
);
238 static DEFINE_PER_CPU(struct rt_rq
, init_rt_rq
) ____cacheline_aligned_in_smp
;
240 static struct sched_rt_entity
*init_sched_rt_entity_p
[NR_CPUS
];
241 static struct rt_rq
*init_rt_rq_p
[NR_CPUS
];
244 /* task_group_lock serializes add/remove of task groups and also changes to
245 * a task group's cpu shares.
247 static DEFINE_SPINLOCK(task_group_lock
);
249 /* doms_cur_mutex serializes access to doms_cur[] array */
250 static DEFINE_MUTEX(doms_cur_mutex
);
252 #ifdef CONFIG_FAIR_GROUP_SCHED
254 /* kernel thread that runs rebalance_shares() periodically */
255 static struct task_struct
*lb_monitor_task
;
256 static int load_balance_monitor(void *unused
);
259 static void set_se_shares(struct sched_entity
*se
, unsigned long shares
);
261 #ifdef CONFIG_USER_SCHED
262 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
264 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
267 #define MIN_GROUP_SHARES 2
269 static int init_task_group_load
= INIT_TASK_GROUP_LOAD
;
272 /* Default task group.
273 * Every task in system belong to this group at bootup.
275 struct task_group init_task_group
= {
276 #ifdef CONFIG_FAIR_GROUP_SCHED
277 .se
= init_sched_entity_p
,
278 .cfs_rq
= init_cfs_rq_p
,
281 #ifdef CONFIG_RT_GROUP_SCHED
282 .rt_se
= init_sched_rt_entity_p
,
283 .rt_rq
= init_rt_rq_p
,
287 /* return group to which a task belongs */
288 static inline struct task_group
*task_group(struct task_struct
*p
)
290 struct task_group
*tg
;
292 #ifdef CONFIG_USER_SCHED
294 #elif defined(CONFIG_CGROUP_SCHED)
295 tg
= container_of(task_subsys_state(p
, cpu_cgroup_subsys_id
),
296 struct task_group
, css
);
298 tg
= &init_task_group
;
303 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
304 static inline void set_task_rq(struct task_struct
*p
, unsigned int cpu
)
306 #ifdef CONFIG_FAIR_GROUP_SCHED
307 p
->se
.cfs_rq
= task_group(p
)->cfs_rq
[cpu
];
308 p
->se
.parent
= task_group(p
)->se
[cpu
];
311 #ifdef CONFIG_RT_GROUP_SCHED
312 p
->rt
.rt_rq
= task_group(p
)->rt_rq
[cpu
];
313 p
->rt
.parent
= task_group(p
)->rt_se
[cpu
];
317 static inline void lock_doms_cur(void)
319 mutex_lock(&doms_cur_mutex
);
322 static inline void unlock_doms_cur(void)
324 mutex_unlock(&doms_cur_mutex
);
329 static inline void set_task_rq(struct task_struct
*p
, unsigned int cpu
) { }
330 static inline void lock_doms_cur(void) { }
331 static inline void unlock_doms_cur(void) { }
333 #endif /* CONFIG_GROUP_SCHED */
335 /* CFS-related fields in a runqueue */
337 struct load_weight load
;
338 unsigned long nr_running
;
343 struct rb_root tasks_timeline
;
344 struct rb_node
*rb_leftmost
;
345 struct rb_node
*rb_load_balance_curr
;
346 /* 'curr' points to currently running entity on this cfs_rq.
347 * It is set to NULL otherwise (i.e when none are currently running).
349 struct sched_entity
*curr
;
351 unsigned long nr_spread_over
;
353 #ifdef CONFIG_FAIR_GROUP_SCHED
354 struct rq
*rq
; /* cpu runqueue to which this cfs_rq is attached */
357 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
358 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
359 * (like users, containers etc.)
361 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
362 * list is used during load balance.
364 struct list_head leaf_cfs_rq_list
;
365 struct task_group
*tg
; /* group that "owns" this runqueue */
369 /* Real-Time classes' related field in a runqueue: */
371 struct rt_prio_array active
;
372 unsigned long rt_nr_running
;
373 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
374 int highest_prio
; /* highest queued rt task prio */
377 unsigned long rt_nr_migratory
;
383 #ifdef CONFIG_RT_GROUP_SCHED
384 unsigned long rt_nr_boosted
;
387 struct list_head leaf_rt_rq_list
;
388 struct task_group
*tg
;
389 struct sched_rt_entity
*rt_se
;
396 * We add the notion of a root-domain which will be used to define per-domain
397 * variables. Each exclusive cpuset essentially defines an island domain by
398 * fully partitioning the member cpus from any other cpuset. Whenever a new
399 * exclusive cpuset is created, we also create and attach a new root-domain
409 * The "RT overload" flag: it gets set if a CPU has more than
410 * one runnable RT task.
417 * By default the system creates a single root-domain with all cpus as
418 * members (mimicking the global state we have today).
420 static struct root_domain def_root_domain
;
425 * This is the main, per-CPU runqueue data structure.
427 * Locking rule: those places that want to lock multiple runqueues
428 * (such as the load balancing or the thread migration code), lock
429 * acquire operations must be ordered by ascending &runqueue.
436 * nr_running and cpu_load should be in the same cacheline because
437 * remote CPUs use both these fields when doing load calculation.
439 unsigned long nr_running
;
440 #define CPU_LOAD_IDX_MAX 5
441 unsigned long cpu_load
[CPU_LOAD_IDX_MAX
];
442 unsigned char idle_at_tick
;
444 unsigned char in_nohz_recently
;
446 /* capture load from *all* tasks on this cpu: */
447 struct load_weight load
;
448 unsigned long nr_load_updates
;
453 u64 rt_period_expire
;
456 #ifdef CONFIG_FAIR_GROUP_SCHED
457 /* list of leaf cfs_rq on this cpu: */
458 struct list_head leaf_cfs_rq_list
;
460 #ifdef CONFIG_RT_GROUP_SCHED
461 struct list_head leaf_rt_rq_list
;
465 * This is part of a global counter where only the total sum
466 * over all CPUs matters. A task can increase this counter on
467 * one CPU and if it got migrated afterwards it may decrease
468 * it on another CPU. Always updated under the runqueue lock:
470 unsigned long nr_uninterruptible
;
472 struct task_struct
*curr
, *idle
;
473 unsigned long next_balance
;
474 struct mm_struct
*prev_mm
;
476 u64 clock
, prev_clock_raw
;
479 unsigned int clock_warps
, clock_overflows
, clock_underflows
;
481 unsigned int clock_deep_idle_events
;
487 struct root_domain
*rd
;
488 struct sched_domain
*sd
;
490 /* For active balancing */
493 /* cpu of this runqueue: */
496 struct task_struct
*migration_thread
;
497 struct list_head migration_queue
;
500 #ifdef CONFIG_SCHED_HRTICK
501 unsigned long hrtick_flags
;
502 ktime_t hrtick_expire
;
503 struct hrtimer hrtick_timer
;
506 #ifdef CONFIG_SCHEDSTATS
508 struct sched_info rq_sched_info
;
510 /* sys_sched_yield() stats */
511 unsigned int yld_exp_empty
;
512 unsigned int yld_act_empty
;
513 unsigned int yld_both_empty
;
514 unsigned int yld_count
;
516 /* schedule() stats */
517 unsigned int sched_switch
;
518 unsigned int sched_count
;
519 unsigned int sched_goidle
;
521 /* try_to_wake_up() stats */
522 unsigned int ttwu_count
;
523 unsigned int ttwu_local
;
526 unsigned int bkl_count
;
528 struct lock_class_key rq_lock_key
;
531 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq
, runqueues
);
533 static inline void check_preempt_curr(struct rq
*rq
, struct task_struct
*p
)
535 rq
->curr
->sched_class
->check_preempt_curr(rq
, p
);
538 static inline int cpu_of(struct rq
*rq
)
548 * Update the per-runqueue clock, as finegrained as the platform can give
549 * us, but without assuming monotonicity, etc.:
551 static void __update_rq_clock(struct rq
*rq
)
553 u64 prev_raw
= rq
->prev_clock_raw
;
554 u64 now
= sched_clock();
555 s64 delta
= now
- prev_raw
;
556 u64 clock
= rq
->clock
;
558 #ifdef CONFIG_SCHED_DEBUG
559 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
562 * Protect against sched_clock() occasionally going backwards:
564 if (unlikely(delta
< 0)) {
569 * Catch too large forward jumps too:
571 if (unlikely(clock
+ delta
> rq
->tick_timestamp
+ TICK_NSEC
)) {
572 if (clock
< rq
->tick_timestamp
+ TICK_NSEC
)
573 clock
= rq
->tick_timestamp
+ TICK_NSEC
;
576 rq
->clock_overflows
++;
578 if (unlikely(delta
> rq
->clock_max_delta
))
579 rq
->clock_max_delta
= delta
;
584 rq
->prev_clock_raw
= now
;
588 static void update_rq_clock(struct rq
*rq
)
590 if (likely(smp_processor_id() == cpu_of(rq
)))
591 __update_rq_clock(rq
);
595 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
596 * See detach_destroy_domains: synchronize_sched for details.
598 * The domain tree of any CPU may only be accessed from within
599 * preempt-disabled sections.
601 #define for_each_domain(cpu, __sd) \
602 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
604 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
605 #define this_rq() (&__get_cpu_var(runqueues))
606 #define task_rq(p) cpu_rq(task_cpu(p))
607 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
609 unsigned long rt_needs_cpu(int cpu
)
611 struct rq
*rq
= cpu_rq(cpu
);
614 if (!rq
->rt_throttled
)
617 if (rq
->clock
> rq
->rt_period_expire
)
620 delta
= rq
->rt_period_expire
- rq
->clock
;
621 do_div(delta
, NSEC_PER_SEC
/ HZ
);
623 return (unsigned long)delta
;
627 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
629 #ifdef CONFIG_SCHED_DEBUG
630 # define const_debug __read_mostly
632 # define const_debug static const
636 * Debugging: various feature bits
639 SCHED_FEAT_NEW_FAIR_SLEEPERS
= 1,
640 SCHED_FEAT_WAKEUP_PREEMPT
= 2,
641 SCHED_FEAT_START_DEBIT
= 4,
642 SCHED_FEAT_TREE_AVG
= 8,
643 SCHED_FEAT_APPROX_AVG
= 16,
644 SCHED_FEAT_HRTICK
= 32,
645 SCHED_FEAT_DOUBLE_TICK
= 64,
648 const_debug
unsigned int sysctl_sched_features
=
649 SCHED_FEAT_NEW_FAIR_SLEEPERS
* 1 |
650 SCHED_FEAT_WAKEUP_PREEMPT
* 1 |
651 SCHED_FEAT_START_DEBIT
* 1 |
652 SCHED_FEAT_TREE_AVG
* 0 |
653 SCHED_FEAT_APPROX_AVG
* 0 |
654 SCHED_FEAT_HRTICK
* 1 |
655 SCHED_FEAT_DOUBLE_TICK
* 0;
657 #define sched_feat(x) (sysctl_sched_features & SCHED_FEAT_##x)
660 * Number of tasks to iterate in a single balance run.
661 * Limited because this is done with IRQs disabled.
663 const_debug
unsigned int sysctl_sched_nr_migrate
= 32;
666 * period over which we measure -rt task cpu usage in us.
669 unsigned int sysctl_sched_rt_period
= 1000000;
672 * part of the period that we allow rt tasks to run in us.
675 int sysctl_sched_rt_runtime
= 950000;
678 * single value that denotes runtime == period, ie unlimited time.
680 #define RUNTIME_INF ((u64)~0ULL)
683 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
684 * clock constructed from sched_clock():
686 unsigned long long cpu_clock(int cpu
)
688 unsigned long long now
;
692 local_irq_save(flags
);
695 * Only call sched_clock() if the scheduler has already been
696 * initialized (some code might call cpu_clock() very early):
701 local_irq_restore(flags
);
705 EXPORT_SYMBOL_GPL(cpu_clock
);
707 #ifndef prepare_arch_switch
708 # define prepare_arch_switch(next) do { } while (0)
710 #ifndef finish_arch_switch
711 # define finish_arch_switch(prev) do { } while (0)
714 static inline int task_current(struct rq
*rq
, struct task_struct
*p
)
716 return rq
->curr
== p
;
719 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
720 static inline int task_running(struct rq
*rq
, struct task_struct
*p
)
722 return task_current(rq
, p
);
725 static inline void prepare_lock_switch(struct rq
*rq
, struct task_struct
*next
)
729 static inline void finish_lock_switch(struct rq
*rq
, struct task_struct
*prev
)
731 #ifdef CONFIG_DEBUG_SPINLOCK
732 /* this is a valid case when another task releases the spinlock */
733 rq
->lock
.owner
= current
;
736 * If we are tracking spinlock dependencies then we have to
737 * fix up the runqueue lock - which gets 'carried over' from
740 spin_acquire(&rq
->lock
.dep_map
, 0, 0, _THIS_IP_
);
742 spin_unlock_irq(&rq
->lock
);
745 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
746 static inline int task_running(struct rq
*rq
, struct task_struct
*p
)
751 return task_current(rq
, p
);
755 static inline void prepare_lock_switch(struct rq
*rq
, struct task_struct
*next
)
759 * We can optimise this out completely for !SMP, because the
760 * SMP rebalancing from interrupt is the only thing that cares
765 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
766 spin_unlock_irq(&rq
->lock
);
768 spin_unlock(&rq
->lock
);
772 static inline void finish_lock_switch(struct rq
*rq
, struct task_struct
*prev
)
776 * After ->oncpu is cleared, the task can be moved to a different CPU.
777 * We must ensure this doesn't happen until the switch is completely
783 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
787 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
790 * __task_rq_lock - lock the runqueue a given task resides on.
791 * Must be called interrupts disabled.
793 static inline struct rq
*__task_rq_lock(struct task_struct
*p
)
797 struct rq
*rq
= task_rq(p
);
798 spin_lock(&rq
->lock
);
799 if (likely(rq
== task_rq(p
)))
801 spin_unlock(&rq
->lock
);
806 * task_rq_lock - lock the runqueue a given task resides on and disable
807 * interrupts. Note the ordering: we can safely lookup the task_rq without
808 * explicitly disabling preemption.
810 static struct rq
*task_rq_lock(struct task_struct
*p
, unsigned long *flags
)
816 local_irq_save(*flags
);
818 spin_lock(&rq
->lock
);
819 if (likely(rq
== task_rq(p
)))
821 spin_unlock_irqrestore(&rq
->lock
, *flags
);
825 static void __task_rq_unlock(struct rq
*rq
)
828 spin_unlock(&rq
->lock
);
831 static inline void task_rq_unlock(struct rq
*rq
, unsigned long *flags
)
834 spin_unlock_irqrestore(&rq
->lock
, *flags
);
838 * this_rq_lock - lock this runqueue and disable interrupts.
840 static struct rq
*this_rq_lock(void)
847 spin_lock(&rq
->lock
);
853 * We are going deep-idle (irqs are disabled):
855 void sched_clock_idle_sleep_event(void)
857 struct rq
*rq
= cpu_rq(smp_processor_id());
859 spin_lock(&rq
->lock
);
860 __update_rq_clock(rq
);
861 spin_unlock(&rq
->lock
);
862 rq
->clock_deep_idle_events
++;
864 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event
);
867 * We just idled delta nanoseconds (called with irqs disabled):
869 void sched_clock_idle_wakeup_event(u64 delta_ns
)
871 struct rq
*rq
= cpu_rq(smp_processor_id());
872 u64 now
= sched_clock();
874 rq
->idle_clock
+= delta_ns
;
876 * Override the previous timestamp and ignore all
877 * sched_clock() deltas that occured while we idled,
878 * and use the PM-provided delta_ns to advance the
881 spin_lock(&rq
->lock
);
882 rq
->prev_clock_raw
= now
;
883 rq
->clock
+= delta_ns
;
884 spin_unlock(&rq
->lock
);
885 touch_softlockup_watchdog();
887 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event
);
889 static void __resched_task(struct task_struct
*p
, int tif_bit
);
891 static inline void resched_task(struct task_struct
*p
)
893 __resched_task(p
, TIF_NEED_RESCHED
);
896 #ifdef CONFIG_SCHED_HRTICK
898 * Use HR-timers to deliver accurate preemption points.
900 * Its all a bit involved since we cannot program an hrt while holding the
901 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
904 * When we get rescheduled we reprogram the hrtick_timer outside of the
907 static inline void resched_hrt(struct task_struct
*p
)
909 __resched_task(p
, TIF_HRTICK_RESCHED
);
912 static inline void resched_rq(struct rq
*rq
)
916 spin_lock_irqsave(&rq
->lock
, flags
);
917 resched_task(rq
->curr
);
918 spin_unlock_irqrestore(&rq
->lock
, flags
);
922 HRTICK_SET
, /* re-programm hrtick_timer */
923 HRTICK_RESET
, /* not a new slice */
928 * - enabled by features
929 * - hrtimer is actually high res
931 static inline int hrtick_enabled(struct rq
*rq
)
933 if (!sched_feat(HRTICK
))
935 return hrtimer_is_hres_active(&rq
->hrtick_timer
);
939 * Called to set the hrtick timer state.
941 * called with rq->lock held and irqs disabled
943 static void hrtick_start(struct rq
*rq
, u64 delay
, int reset
)
945 assert_spin_locked(&rq
->lock
);
948 * preempt at: now + delay
951 ktime_add_ns(rq
->hrtick_timer
.base
->get_time(), delay
);
953 * indicate we need to program the timer
955 __set_bit(HRTICK_SET
, &rq
->hrtick_flags
);
957 __set_bit(HRTICK_RESET
, &rq
->hrtick_flags
);
960 * New slices are called from the schedule path and don't need a
964 resched_hrt(rq
->curr
);
967 static void hrtick_clear(struct rq
*rq
)
969 if (hrtimer_active(&rq
->hrtick_timer
))
970 hrtimer_cancel(&rq
->hrtick_timer
);
974 * Update the timer from the possible pending state.
976 static void hrtick_set(struct rq
*rq
)
982 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
984 spin_lock_irqsave(&rq
->lock
, flags
);
985 set
= __test_and_clear_bit(HRTICK_SET
, &rq
->hrtick_flags
);
986 reset
= __test_and_clear_bit(HRTICK_RESET
, &rq
->hrtick_flags
);
987 time
= rq
->hrtick_expire
;
988 clear_thread_flag(TIF_HRTICK_RESCHED
);
989 spin_unlock_irqrestore(&rq
->lock
, flags
);
992 hrtimer_start(&rq
->hrtick_timer
, time
, HRTIMER_MODE_ABS
);
993 if (reset
&& !hrtimer_active(&rq
->hrtick_timer
))
1000 * High-resolution timer tick.
1001 * Runs from hardirq context with interrupts disabled.
1003 static enum hrtimer_restart
hrtick(struct hrtimer
*timer
)
1005 struct rq
*rq
= container_of(timer
, struct rq
, hrtick_timer
);
1007 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
1009 spin_lock(&rq
->lock
);
1010 __update_rq_clock(rq
);
1011 rq
->curr
->sched_class
->task_tick(rq
, rq
->curr
, 1);
1012 spin_unlock(&rq
->lock
);
1014 return HRTIMER_NORESTART
;
1017 static inline void init_rq_hrtick(struct rq
*rq
)
1019 rq
->hrtick_flags
= 0;
1020 hrtimer_init(&rq
->hrtick_timer
, CLOCK_MONOTONIC
, HRTIMER_MODE_REL
);
1021 rq
->hrtick_timer
.function
= hrtick
;
1022 rq
->hrtick_timer
.cb_mode
= HRTIMER_CB_IRQSAFE_NO_SOFTIRQ
;
1025 void hrtick_resched(void)
1028 unsigned long flags
;
1030 if (!test_thread_flag(TIF_HRTICK_RESCHED
))
1033 local_irq_save(flags
);
1034 rq
= cpu_rq(smp_processor_id());
1036 local_irq_restore(flags
);
1039 static inline void hrtick_clear(struct rq
*rq
)
1043 static inline void hrtick_set(struct rq
*rq
)
1047 static inline void init_rq_hrtick(struct rq
*rq
)
1051 void hrtick_resched(void)
1057 * resched_task - mark a task 'to be rescheduled now'.
1059 * On UP this means the setting of the need_resched flag, on SMP it
1060 * might also involve a cross-CPU call to trigger the scheduler on
1065 #ifndef tsk_is_polling
1066 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1069 static void __resched_task(struct task_struct
*p
, int tif_bit
)
1073 assert_spin_locked(&task_rq(p
)->lock
);
1075 if (unlikely(test_tsk_thread_flag(p
, tif_bit
)))
1078 set_tsk_thread_flag(p
, tif_bit
);
1081 if (cpu
== smp_processor_id())
1084 /* NEED_RESCHED must be visible before we test polling */
1086 if (!tsk_is_polling(p
))
1087 smp_send_reschedule(cpu
);
1090 static void resched_cpu(int cpu
)
1092 struct rq
*rq
= cpu_rq(cpu
);
1093 unsigned long flags
;
1095 if (!spin_trylock_irqsave(&rq
->lock
, flags
))
1097 resched_task(cpu_curr(cpu
));
1098 spin_unlock_irqrestore(&rq
->lock
, flags
);
1101 static void __resched_task(struct task_struct
*p
, int tif_bit
)
1103 assert_spin_locked(&task_rq(p
)->lock
);
1104 set_tsk_thread_flag(p
, tif_bit
);
1108 #if BITS_PER_LONG == 32
1109 # define WMULT_CONST (~0UL)
1111 # define WMULT_CONST (1UL << 32)
1114 #define WMULT_SHIFT 32
1117 * Shift right and round:
1119 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1121 static unsigned long
1122 calc_delta_mine(unsigned long delta_exec
, unsigned long weight
,
1123 struct load_weight
*lw
)
1127 if (unlikely(!lw
->inv_weight
))
1128 lw
->inv_weight
= (WMULT_CONST
- lw
->weight
/2) / lw
->weight
+ 1;
1130 tmp
= (u64
)delta_exec
* weight
;
1132 * Check whether we'd overflow the 64-bit multiplication:
1134 if (unlikely(tmp
> WMULT_CONST
))
1135 tmp
= SRR(SRR(tmp
, WMULT_SHIFT
/2) * lw
->inv_weight
,
1138 tmp
= SRR(tmp
* lw
->inv_weight
, WMULT_SHIFT
);
1140 return (unsigned long)min(tmp
, (u64
)(unsigned long)LONG_MAX
);
1143 static inline unsigned long
1144 calc_delta_fair(unsigned long delta_exec
, struct load_weight
*lw
)
1146 return calc_delta_mine(delta_exec
, NICE_0_LOAD
, lw
);
1149 static inline void update_load_add(struct load_weight
*lw
, unsigned long inc
)
1154 static inline void update_load_sub(struct load_weight
*lw
, unsigned long dec
)
1160 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1161 * of tasks with abnormal "nice" values across CPUs the contribution that
1162 * each task makes to its run queue's load is weighted according to its
1163 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1164 * scaled version of the new time slice allocation that they receive on time
1168 #define WEIGHT_IDLEPRIO 2
1169 #define WMULT_IDLEPRIO (1 << 31)
1172 * Nice levels are multiplicative, with a gentle 10% change for every
1173 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1174 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1175 * that remained on nice 0.
1177 * The "10% effect" is relative and cumulative: from _any_ nice level,
1178 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1179 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1180 * If a task goes up by ~10% and another task goes down by ~10% then
1181 * the relative distance between them is ~25%.)
1183 static const int prio_to_weight
[40] = {
1184 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1185 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1186 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1187 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1188 /* 0 */ 1024, 820, 655, 526, 423,
1189 /* 5 */ 335, 272, 215, 172, 137,
1190 /* 10 */ 110, 87, 70, 56, 45,
1191 /* 15 */ 36, 29, 23, 18, 15,
1195 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1197 * In cases where the weight does not change often, we can use the
1198 * precalculated inverse to speed up arithmetics by turning divisions
1199 * into multiplications:
1201 static const u32 prio_to_wmult
[40] = {
1202 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1203 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1204 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1205 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1206 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1207 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1208 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1209 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1212 static void activate_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
);
1215 * runqueue iterator, to support SMP load-balancing between different
1216 * scheduling classes, without having to expose their internal data
1217 * structures to the load-balancing proper:
1219 struct rq_iterator
{
1221 struct task_struct
*(*start
)(void *);
1222 struct task_struct
*(*next
)(void *);
1226 static unsigned long
1227 balance_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
1228 unsigned long max_load_move
, struct sched_domain
*sd
,
1229 enum cpu_idle_type idle
, int *all_pinned
,
1230 int *this_best_prio
, struct rq_iterator
*iterator
);
1233 iter_move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
1234 struct sched_domain
*sd
, enum cpu_idle_type idle
,
1235 struct rq_iterator
*iterator
);
1238 #ifdef CONFIG_CGROUP_CPUACCT
1239 static void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
);
1241 static inline void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
) {}
1244 static inline void inc_cpu_load(struct rq
*rq
, unsigned long load
)
1246 update_load_add(&rq
->load
, load
);
1249 static inline void dec_cpu_load(struct rq
*rq
, unsigned long load
)
1251 update_load_sub(&rq
->load
, load
);
1255 static unsigned long source_load(int cpu
, int type
);
1256 static unsigned long target_load(int cpu
, int type
);
1257 static unsigned long cpu_avg_load_per_task(int cpu
);
1258 static int task_hot(struct task_struct
*p
, u64 now
, struct sched_domain
*sd
);
1259 #endif /* CONFIG_SMP */
1261 #include "sched_stats.h"
1262 #include "sched_idletask.c"
1263 #include "sched_fair.c"
1264 #include "sched_rt.c"
1265 #ifdef CONFIG_SCHED_DEBUG
1266 # include "sched_debug.c"
1269 #define sched_class_highest (&rt_sched_class)
1271 static void inc_nr_running(struct rq
*rq
)
1276 static void dec_nr_running(struct rq
*rq
)
1281 static void set_load_weight(struct task_struct
*p
)
1283 if (task_has_rt_policy(p
)) {
1284 p
->se
.load
.weight
= prio_to_weight
[0] * 2;
1285 p
->se
.load
.inv_weight
= prio_to_wmult
[0] >> 1;
1290 * SCHED_IDLE tasks get minimal weight:
1292 if (p
->policy
== SCHED_IDLE
) {
1293 p
->se
.load
.weight
= WEIGHT_IDLEPRIO
;
1294 p
->se
.load
.inv_weight
= WMULT_IDLEPRIO
;
1298 p
->se
.load
.weight
= prio_to_weight
[p
->static_prio
- MAX_RT_PRIO
];
1299 p
->se
.load
.inv_weight
= prio_to_wmult
[p
->static_prio
- MAX_RT_PRIO
];
1302 static void enqueue_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
)
1304 sched_info_queued(p
);
1305 p
->sched_class
->enqueue_task(rq
, p
, wakeup
);
1309 static void dequeue_task(struct rq
*rq
, struct task_struct
*p
, int sleep
)
1311 p
->sched_class
->dequeue_task(rq
, p
, sleep
);
1316 * __normal_prio - return the priority that is based on the static prio
1318 static inline int __normal_prio(struct task_struct
*p
)
1320 return p
->static_prio
;
1324 * Calculate the expected normal priority: i.e. priority
1325 * without taking RT-inheritance into account. Might be
1326 * boosted by interactivity modifiers. Changes upon fork,
1327 * setprio syscalls, and whenever the interactivity
1328 * estimator recalculates.
1330 static inline int normal_prio(struct task_struct
*p
)
1334 if (task_has_rt_policy(p
))
1335 prio
= MAX_RT_PRIO
-1 - p
->rt_priority
;
1337 prio
= __normal_prio(p
);
1342 * Calculate the current priority, i.e. the priority
1343 * taken into account by the scheduler. This value might
1344 * be boosted by RT tasks, or might be boosted by
1345 * interactivity modifiers. Will be RT if the task got
1346 * RT-boosted. If not then it returns p->normal_prio.
1348 static int effective_prio(struct task_struct
*p
)
1350 p
->normal_prio
= normal_prio(p
);
1352 * If we are RT tasks or we were boosted to RT priority,
1353 * keep the priority unchanged. Otherwise, update priority
1354 * to the normal priority:
1356 if (!rt_prio(p
->prio
))
1357 return p
->normal_prio
;
1362 * activate_task - move a task to the runqueue.
1364 static void activate_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
)
1366 if (task_contributes_to_load(p
))
1367 rq
->nr_uninterruptible
--;
1369 enqueue_task(rq
, p
, wakeup
);
1374 * deactivate_task - remove a task from the runqueue.
1376 static void deactivate_task(struct rq
*rq
, struct task_struct
*p
, int sleep
)
1378 if (task_contributes_to_load(p
))
1379 rq
->nr_uninterruptible
++;
1381 dequeue_task(rq
, p
, sleep
);
1386 * task_curr - is this task currently executing on a CPU?
1387 * @p: the task in question.
1389 inline int task_curr(const struct task_struct
*p
)
1391 return cpu_curr(task_cpu(p
)) == p
;
1394 /* Used instead of source_load when we know the type == 0 */
1395 unsigned long weighted_cpuload(const int cpu
)
1397 return cpu_rq(cpu
)->load
.weight
;
1400 static inline void __set_task_cpu(struct task_struct
*p
, unsigned int cpu
)
1402 set_task_rq(p
, cpu
);
1405 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1406 * successfuly executed on another CPU. We must ensure that updates of
1407 * per-task data have been completed by this moment.
1410 task_thread_info(p
)->cpu
= cpu
;
1414 static inline void check_class_changed(struct rq
*rq
, struct task_struct
*p
,
1415 const struct sched_class
*prev_class
,
1416 int oldprio
, int running
)
1418 if (prev_class
!= p
->sched_class
) {
1419 if (prev_class
->switched_from
)
1420 prev_class
->switched_from(rq
, p
, running
);
1421 p
->sched_class
->switched_to(rq
, p
, running
);
1423 p
->sched_class
->prio_changed(rq
, p
, oldprio
, running
);
1429 * Is this task likely cache-hot:
1432 task_hot(struct task_struct
*p
, u64 now
, struct sched_domain
*sd
)
1436 if (p
->sched_class
!= &fair_sched_class
)
1439 if (sysctl_sched_migration_cost
== -1)
1441 if (sysctl_sched_migration_cost
== 0)
1444 delta
= now
- p
->se
.exec_start
;
1446 return delta
< (s64
)sysctl_sched_migration_cost
;
1450 void set_task_cpu(struct task_struct
*p
, unsigned int new_cpu
)
1452 int old_cpu
= task_cpu(p
);
1453 struct rq
*old_rq
= cpu_rq(old_cpu
), *new_rq
= cpu_rq(new_cpu
);
1454 struct cfs_rq
*old_cfsrq
= task_cfs_rq(p
),
1455 *new_cfsrq
= cpu_cfs_rq(old_cfsrq
, new_cpu
);
1458 clock_offset
= old_rq
->clock
- new_rq
->clock
;
1460 #ifdef CONFIG_SCHEDSTATS
1461 if (p
->se
.wait_start
)
1462 p
->se
.wait_start
-= clock_offset
;
1463 if (p
->se
.sleep_start
)
1464 p
->se
.sleep_start
-= clock_offset
;
1465 if (p
->se
.block_start
)
1466 p
->se
.block_start
-= clock_offset
;
1467 if (old_cpu
!= new_cpu
) {
1468 schedstat_inc(p
, se
.nr_migrations
);
1469 if (task_hot(p
, old_rq
->clock
, NULL
))
1470 schedstat_inc(p
, se
.nr_forced2_migrations
);
1473 p
->se
.vruntime
-= old_cfsrq
->min_vruntime
-
1474 new_cfsrq
->min_vruntime
;
1476 __set_task_cpu(p
, new_cpu
);
1479 struct migration_req
{
1480 struct list_head list
;
1482 struct task_struct
*task
;
1485 struct completion done
;
1489 * The task's runqueue lock must be held.
1490 * Returns true if you have to wait for migration thread.
1493 migrate_task(struct task_struct
*p
, int dest_cpu
, struct migration_req
*req
)
1495 struct rq
*rq
= task_rq(p
);
1498 * If the task is not on a runqueue (and not running), then
1499 * it is sufficient to simply update the task's cpu field.
1501 if (!p
->se
.on_rq
&& !task_running(rq
, p
)) {
1502 set_task_cpu(p
, dest_cpu
);
1506 init_completion(&req
->done
);
1508 req
->dest_cpu
= dest_cpu
;
1509 list_add(&req
->list
, &rq
->migration_queue
);
1515 * wait_task_inactive - wait for a thread to unschedule.
1517 * The caller must ensure that the task *will* unschedule sometime soon,
1518 * else this function might spin for a *long* time. This function can't
1519 * be called with interrupts off, or it may introduce deadlock with
1520 * smp_call_function() if an IPI is sent by the same process we are
1521 * waiting to become inactive.
1523 void wait_task_inactive(struct task_struct
*p
)
1525 unsigned long flags
;
1531 * We do the initial early heuristics without holding
1532 * any task-queue locks at all. We'll only try to get
1533 * the runqueue lock when things look like they will
1539 * If the task is actively running on another CPU
1540 * still, just relax and busy-wait without holding
1543 * NOTE! Since we don't hold any locks, it's not
1544 * even sure that "rq" stays as the right runqueue!
1545 * But we don't care, since "task_running()" will
1546 * return false if the runqueue has changed and p
1547 * is actually now running somewhere else!
1549 while (task_running(rq
, p
))
1553 * Ok, time to look more closely! We need the rq
1554 * lock now, to be *sure*. If we're wrong, we'll
1555 * just go back and repeat.
1557 rq
= task_rq_lock(p
, &flags
);
1558 running
= task_running(rq
, p
);
1559 on_rq
= p
->se
.on_rq
;
1560 task_rq_unlock(rq
, &flags
);
1563 * Was it really running after all now that we
1564 * checked with the proper locks actually held?
1566 * Oops. Go back and try again..
1568 if (unlikely(running
)) {
1574 * It's not enough that it's not actively running,
1575 * it must be off the runqueue _entirely_, and not
1578 * So if it wa still runnable (but just not actively
1579 * running right now), it's preempted, and we should
1580 * yield - it could be a while.
1582 if (unlikely(on_rq
)) {
1583 schedule_timeout_uninterruptible(1);
1588 * Ahh, all good. It wasn't running, and it wasn't
1589 * runnable, which means that it will never become
1590 * running in the future either. We're all done!
1597 * kick_process - kick a running thread to enter/exit the kernel
1598 * @p: the to-be-kicked thread
1600 * Cause a process which is running on another CPU to enter
1601 * kernel-mode, without any delay. (to get signals handled.)
1603 * NOTE: this function doesnt have to take the runqueue lock,
1604 * because all it wants to ensure is that the remote task enters
1605 * the kernel. If the IPI races and the task has been migrated
1606 * to another CPU then no harm is done and the purpose has been
1609 void kick_process(struct task_struct
*p
)
1615 if ((cpu
!= smp_processor_id()) && task_curr(p
))
1616 smp_send_reschedule(cpu
);
1621 * Return a low guess at the load of a migration-source cpu weighted
1622 * according to the scheduling class and "nice" value.
1624 * We want to under-estimate the load of migration sources, to
1625 * balance conservatively.
1627 static unsigned long source_load(int cpu
, int type
)
1629 struct rq
*rq
= cpu_rq(cpu
);
1630 unsigned long total
= weighted_cpuload(cpu
);
1635 return min(rq
->cpu_load
[type
-1], total
);
1639 * Return a high guess at the load of a migration-target cpu weighted
1640 * according to the scheduling class and "nice" value.
1642 static unsigned long target_load(int cpu
, int type
)
1644 struct rq
*rq
= cpu_rq(cpu
);
1645 unsigned long total
= weighted_cpuload(cpu
);
1650 return max(rq
->cpu_load
[type
-1], total
);
1654 * Return the average load per task on the cpu's run queue
1656 static unsigned long cpu_avg_load_per_task(int cpu
)
1658 struct rq
*rq
= cpu_rq(cpu
);
1659 unsigned long total
= weighted_cpuload(cpu
);
1660 unsigned long n
= rq
->nr_running
;
1662 return n
? total
/ n
: SCHED_LOAD_SCALE
;
1666 * find_idlest_group finds and returns the least busy CPU group within the
1669 static struct sched_group
*
1670 find_idlest_group(struct sched_domain
*sd
, struct task_struct
*p
, int this_cpu
)
1672 struct sched_group
*idlest
= NULL
, *this = NULL
, *group
= sd
->groups
;
1673 unsigned long min_load
= ULONG_MAX
, this_load
= 0;
1674 int load_idx
= sd
->forkexec_idx
;
1675 int imbalance
= 100 + (sd
->imbalance_pct
-100)/2;
1678 unsigned long load
, avg_load
;
1682 /* Skip over this group if it has no CPUs allowed */
1683 if (!cpus_intersects(group
->cpumask
, p
->cpus_allowed
))
1686 local_group
= cpu_isset(this_cpu
, group
->cpumask
);
1688 /* Tally up the load of all CPUs in the group */
1691 for_each_cpu_mask(i
, group
->cpumask
) {
1692 /* Bias balancing toward cpus of our domain */
1694 load
= source_load(i
, load_idx
);
1696 load
= target_load(i
, load_idx
);
1701 /* Adjust by relative CPU power of the group */
1702 avg_load
= sg_div_cpu_power(group
,
1703 avg_load
* SCHED_LOAD_SCALE
);
1706 this_load
= avg_load
;
1708 } else if (avg_load
< min_load
) {
1709 min_load
= avg_load
;
1712 } while (group
= group
->next
, group
!= sd
->groups
);
1714 if (!idlest
|| 100*this_load
< imbalance
*min_load
)
1720 * find_idlest_cpu - find the idlest cpu among the cpus in group.
1723 find_idlest_cpu(struct sched_group
*group
, struct task_struct
*p
, int this_cpu
)
1726 unsigned long load
, min_load
= ULONG_MAX
;
1730 /* Traverse only the allowed CPUs */
1731 cpus_and(tmp
, group
->cpumask
, p
->cpus_allowed
);
1733 for_each_cpu_mask(i
, tmp
) {
1734 load
= weighted_cpuload(i
);
1736 if (load
< min_load
|| (load
== min_load
&& i
== this_cpu
)) {
1746 * sched_balance_self: balance the current task (running on cpu) in domains
1747 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1750 * Balance, ie. select the least loaded group.
1752 * Returns the target CPU number, or the same CPU if no balancing is needed.
1754 * preempt must be disabled.
1756 static int sched_balance_self(int cpu
, int flag
)
1758 struct task_struct
*t
= current
;
1759 struct sched_domain
*tmp
, *sd
= NULL
;
1761 for_each_domain(cpu
, tmp
) {
1763 * If power savings logic is enabled for a domain, stop there.
1765 if (tmp
->flags
& SD_POWERSAVINGS_BALANCE
)
1767 if (tmp
->flags
& flag
)
1773 struct sched_group
*group
;
1774 int new_cpu
, weight
;
1776 if (!(sd
->flags
& flag
)) {
1782 group
= find_idlest_group(sd
, t
, cpu
);
1788 new_cpu
= find_idlest_cpu(group
, t
, cpu
);
1789 if (new_cpu
== -1 || new_cpu
== cpu
) {
1790 /* Now try balancing at a lower domain level of cpu */
1795 /* Now try balancing at a lower domain level of new_cpu */
1798 weight
= cpus_weight(span
);
1799 for_each_domain(cpu
, tmp
) {
1800 if (weight
<= cpus_weight(tmp
->span
))
1802 if (tmp
->flags
& flag
)
1805 /* while loop will break here if sd == NULL */
1811 #endif /* CONFIG_SMP */
1814 * try_to_wake_up - wake up a thread
1815 * @p: the to-be-woken-up thread
1816 * @state: the mask of task states that can be woken
1817 * @sync: do a synchronous wakeup?
1819 * Put it on the run-queue if it's not already there. The "current"
1820 * thread is always on the run-queue (except when the actual
1821 * re-schedule is in progress), and as such you're allowed to do
1822 * the simpler "current->state = TASK_RUNNING" to mark yourself
1823 * runnable without the overhead of this.
1825 * returns failure only if the task is already active.
1827 static int try_to_wake_up(struct task_struct
*p
, unsigned int state
, int sync
)
1829 int cpu
, orig_cpu
, this_cpu
, success
= 0;
1830 unsigned long flags
;
1835 rq
= task_rq_lock(p
, &flags
);
1836 old_state
= p
->state
;
1837 if (!(old_state
& state
))
1845 this_cpu
= smp_processor_id();
1848 if (unlikely(task_running(rq
, p
)))
1851 cpu
= p
->sched_class
->select_task_rq(p
, sync
);
1852 if (cpu
!= orig_cpu
) {
1853 set_task_cpu(p
, cpu
);
1854 task_rq_unlock(rq
, &flags
);
1855 /* might preempt at this point */
1856 rq
= task_rq_lock(p
, &flags
);
1857 old_state
= p
->state
;
1858 if (!(old_state
& state
))
1863 this_cpu
= smp_processor_id();
1867 #ifdef CONFIG_SCHEDSTATS
1868 schedstat_inc(rq
, ttwu_count
);
1869 if (cpu
== this_cpu
)
1870 schedstat_inc(rq
, ttwu_local
);
1872 struct sched_domain
*sd
;
1873 for_each_domain(this_cpu
, sd
) {
1874 if (cpu_isset(cpu
, sd
->span
)) {
1875 schedstat_inc(sd
, ttwu_wake_remote
);
1883 #endif /* CONFIG_SMP */
1884 schedstat_inc(p
, se
.nr_wakeups
);
1886 schedstat_inc(p
, se
.nr_wakeups_sync
);
1887 if (orig_cpu
!= cpu
)
1888 schedstat_inc(p
, se
.nr_wakeups_migrate
);
1889 if (cpu
== this_cpu
)
1890 schedstat_inc(p
, se
.nr_wakeups_local
);
1892 schedstat_inc(p
, se
.nr_wakeups_remote
);
1893 update_rq_clock(rq
);
1894 activate_task(rq
, p
, 1);
1895 check_preempt_curr(rq
, p
);
1899 p
->state
= TASK_RUNNING
;
1901 if (p
->sched_class
->task_wake_up
)
1902 p
->sched_class
->task_wake_up(rq
, p
);
1905 task_rq_unlock(rq
, &flags
);
1910 int wake_up_process(struct task_struct
*p
)
1912 return try_to_wake_up(p
, TASK_ALL
, 0);
1914 EXPORT_SYMBOL(wake_up_process
);
1916 int wake_up_state(struct task_struct
*p
, unsigned int state
)
1918 return try_to_wake_up(p
, state
, 0);
1922 * Perform scheduler related setup for a newly forked process p.
1923 * p is forked by current.
1925 * __sched_fork() is basic setup used by init_idle() too:
1927 static void __sched_fork(struct task_struct
*p
)
1929 p
->se
.exec_start
= 0;
1930 p
->se
.sum_exec_runtime
= 0;
1931 p
->se
.prev_sum_exec_runtime
= 0;
1933 #ifdef CONFIG_SCHEDSTATS
1934 p
->se
.wait_start
= 0;
1935 p
->se
.sum_sleep_runtime
= 0;
1936 p
->se
.sleep_start
= 0;
1937 p
->se
.block_start
= 0;
1938 p
->se
.sleep_max
= 0;
1939 p
->se
.block_max
= 0;
1941 p
->se
.slice_max
= 0;
1945 INIT_LIST_HEAD(&p
->rt
.run_list
);
1948 #ifdef CONFIG_PREEMPT_NOTIFIERS
1949 INIT_HLIST_HEAD(&p
->preempt_notifiers
);
1953 * We mark the process as running here, but have not actually
1954 * inserted it onto the runqueue yet. This guarantees that
1955 * nobody will actually run it, and a signal or other external
1956 * event cannot wake it up and insert it on the runqueue either.
1958 p
->state
= TASK_RUNNING
;
1962 * fork()/clone()-time setup:
1964 void sched_fork(struct task_struct
*p
, int clone_flags
)
1966 int cpu
= get_cpu();
1971 cpu
= sched_balance_self(cpu
, SD_BALANCE_FORK
);
1973 set_task_cpu(p
, cpu
);
1976 * Make sure we do not leak PI boosting priority to the child:
1978 p
->prio
= current
->normal_prio
;
1979 if (!rt_prio(p
->prio
))
1980 p
->sched_class
= &fair_sched_class
;
1982 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
1983 if (likely(sched_info_on()))
1984 memset(&p
->sched_info
, 0, sizeof(p
->sched_info
));
1986 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
1989 #ifdef CONFIG_PREEMPT
1990 /* Want to start with kernel preemption disabled. */
1991 task_thread_info(p
)->preempt_count
= 1;
1997 * wake_up_new_task - wake up a newly created task for the first time.
1999 * This function will do some initial scheduler statistics housekeeping
2000 * that must be done for every newly created context, then puts the task
2001 * on the runqueue and wakes it.
2003 void wake_up_new_task(struct task_struct
*p
, unsigned long clone_flags
)
2005 unsigned long flags
;
2008 rq
= task_rq_lock(p
, &flags
);
2009 BUG_ON(p
->state
!= TASK_RUNNING
);
2010 update_rq_clock(rq
);
2012 p
->prio
= effective_prio(p
);
2014 if (!p
->sched_class
->task_new
|| !current
->se
.on_rq
) {
2015 activate_task(rq
, p
, 0);
2018 * Let the scheduling class do new task startup
2019 * management (if any):
2021 p
->sched_class
->task_new(rq
, p
);
2024 check_preempt_curr(rq
, p
);
2026 if (p
->sched_class
->task_wake_up
)
2027 p
->sched_class
->task_wake_up(rq
, p
);
2029 task_rq_unlock(rq
, &flags
);
2032 #ifdef CONFIG_PREEMPT_NOTIFIERS
2035 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2036 * @notifier: notifier struct to register
2038 void preempt_notifier_register(struct preempt_notifier
*notifier
)
2040 hlist_add_head(¬ifier
->link
, ¤t
->preempt_notifiers
);
2042 EXPORT_SYMBOL_GPL(preempt_notifier_register
);
2045 * preempt_notifier_unregister - no longer interested in preemption notifications
2046 * @notifier: notifier struct to unregister
2048 * This is safe to call from within a preemption notifier.
2050 void preempt_notifier_unregister(struct preempt_notifier
*notifier
)
2052 hlist_del(¬ifier
->link
);
2054 EXPORT_SYMBOL_GPL(preempt_notifier_unregister
);
2056 static void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2058 struct preempt_notifier
*notifier
;
2059 struct hlist_node
*node
;
2061 hlist_for_each_entry(notifier
, node
, &curr
->preempt_notifiers
, link
)
2062 notifier
->ops
->sched_in(notifier
, raw_smp_processor_id());
2066 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2067 struct task_struct
*next
)
2069 struct preempt_notifier
*notifier
;
2070 struct hlist_node
*node
;
2072 hlist_for_each_entry(notifier
, node
, &curr
->preempt_notifiers
, link
)
2073 notifier
->ops
->sched_out(notifier
, next
);
2078 static void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2083 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2084 struct task_struct
*next
)
2091 * prepare_task_switch - prepare to switch tasks
2092 * @rq: the runqueue preparing to switch
2093 * @prev: the current task that is being switched out
2094 * @next: the task we are going to switch to.
2096 * This is called with the rq lock held and interrupts off. It must
2097 * be paired with a subsequent finish_task_switch after the context
2100 * prepare_task_switch sets up locking and calls architecture specific
2104 prepare_task_switch(struct rq
*rq
, struct task_struct
*prev
,
2105 struct task_struct
*next
)
2107 fire_sched_out_preempt_notifiers(prev
, next
);
2108 prepare_lock_switch(rq
, next
);
2109 prepare_arch_switch(next
);
2113 * finish_task_switch - clean up after a task-switch
2114 * @rq: runqueue associated with task-switch
2115 * @prev: the thread we just switched away from.
2117 * finish_task_switch must be called after the context switch, paired
2118 * with a prepare_task_switch call before the context switch.
2119 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2120 * and do any other architecture-specific cleanup actions.
2122 * Note that we may have delayed dropping an mm in context_switch(). If
2123 * so, we finish that here outside of the runqueue lock. (Doing it
2124 * with the lock held can cause deadlocks; see schedule() for
2127 static void finish_task_switch(struct rq
*rq
, struct task_struct
*prev
)
2128 __releases(rq
->lock
)
2130 struct mm_struct
*mm
= rq
->prev_mm
;
2136 * A task struct has one reference for the use as "current".
2137 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2138 * schedule one last time. The schedule call will never return, and
2139 * the scheduled task must drop that reference.
2140 * The test for TASK_DEAD must occur while the runqueue locks are
2141 * still held, otherwise prev could be scheduled on another cpu, die
2142 * there before we look at prev->state, and then the reference would
2144 * Manfred Spraul <manfred@colorfullife.com>
2146 prev_state
= prev
->state
;
2147 finish_arch_switch(prev
);
2148 finish_lock_switch(rq
, prev
);
2150 if (current
->sched_class
->post_schedule
)
2151 current
->sched_class
->post_schedule(rq
);
2154 fire_sched_in_preempt_notifiers(current
);
2157 if (unlikely(prev_state
== TASK_DEAD
)) {
2159 * Remove function-return probe instances associated with this
2160 * task and put them back on the free list.
2162 kprobe_flush_task(prev
);
2163 put_task_struct(prev
);
2168 * schedule_tail - first thing a freshly forked thread must call.
2169 * @prev: the thread we just switched away from.
2171 asmlinkage
void schedule_tail(struct task_struct
*prev
)
2172 __releases(rq
->lock
)
2174 struct rq
*rq
= this_rq();
2176 finish_task_switch(rq
, prev
);
2177 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2178 /* In this case, finish_task_switch does not reenable preemption */
2181 if (current
->set_child_tid
)
2182 put_user(task_pid_vnr(current
), current
->set_child_tid
);
2186 * context_switch - switch to the new MM and the new
2187 * thread's register state.
2190 context_switch(struct rq
*rq
, struct task_struct
*prev
,
2191 struct task_struct
*next
)
2193 struct mm_struct
*mm
, *oldmm
;
2195 prepare_task_switch(rq
, prev
, next
);
2197 oldmm
= prev
->active_mm
;
2199 * For paravirt, this is coupled with an exit in switch_to to
2200 * combine the page table reload and the switch backend into
2203 arch_enter_lazy_cpu_mode();
2205 if (unlikely(!mm
)) {
2206 next
->active_mm
= oldmm
;
2207 atomic_inc(&oldmm
->mm_count
);
2208 enter_lazy_tlb(oldmm
, next
);
2210 switch_mm(oldmm
, mm
, next
);
2212 if (unlikely(!prev
->mm
)) {
2213 prev
->active_mm
= NULL
;
2214 rq
->prev_mm
= oldmm
;
2217 * Since the runqueue lock will be released by the next
2218 * task (which is an invalid locking op but in the case
2219 * of the scheduler it's an obvious special-case), so we
2220 * do an early lockdep release here:
2222 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2223 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
2226 /* Here we just switch the register state and the stack. */
2227 switch_to(prev
, next
, prev
);
2231 * this_rq must be evaluated again because prev may have moved
2232 * CPUs since it called schedule(), thus the 'rq' on its stack
2233 * frame will be invalid.
2235 finish_task_switch(this_rq(), prev
);
2239 * nr_running, nr_uninterruptible and nr_context_switches:
2241 * externally visible scheduler statistics: current number of runnable
2242 * threads, current number of uninterruptible-sleeping threads, total
2243 * number of context switches performed since bootup.
2245 unsigned long nr_running(void)
2247 unsigned long i
, sum
= 0;
2249 for_each_online_cpu(i
)
2250 sum
+= cpu_rq(i
)->nr_running
;
2255 unsigned long nr_uninterruptible(void)
2257 unsigned long i
, sum
= 0;
2259 for_each_possible_cpu(i
)
2260 sum
+= cpu_rq(i
)->nr_uninterruptible
;
2263 * Since we read the counters lockless, it might be slightly
2264 * inaccurate. Do not allow it to go below zero though:
2266 if (unlikely((long)sum
< 0))
2272 unsigned long long nr_context_switches(void)
2275 unsigned long long sum
= 0;
2277 for_each_possible_cpu(i
)
2278 sum
+= cpu_rq(i
)->nr_switches
;
2283 unsigned long nr_iowait(void)
2285 unsigned long i
, sum
= 0;
2287 for_each_possible_cpu(i
)
2288 sum
+= atomic_read(&cpu_rq(i
)->nr_iowait
);
2293 unsigned long nr_active(void)
2295 unsigned long i
, running
= 0, uninterruptible
= 0;
2297 for_each_online_cpu(i
) {
2298 running
+= cpu_rq(i
)->nr_running
;
2299 uninterruptible
+= cpu_rq(i
)->nr_uninterruptible
;
2302 if (unlikely((long)uninterruptible
< 0))
2303 uninterruptible
= 0;
2305 return running
+ uninterruptible
;
2309 * Update rq->cpu_load[] statistics. This function is usually called every
2310 * scheduler tick (TICK_NSEC).
2312 static void update_cpu_load(struct rq
*this_rq
)
2314 unsigned long this_load
= this_rq
->load
.weight
;
2317 this_rq
->nr_load_updates
++;
2319 /* Update our load: */
2320 for (i
= 0, scale
= 1; i
< CPU_LOAD_IDX_MAX
; i
++, scale
+= scale
) {
2321 unsigned long old_load
, new_load
;
2323 /* scale is effectively 1 << i now, and >> i divides by scale */
2325 old_load
= this_rq
->cpu_load
[i
];
2326 new_load
= this_load
;
2328 * Round up the averaging division if load is increasing. This
2329 * prevents us from getting stuck on 9 if the load is 10, for
2332 if (new_load
> old_load
)
2333 new_load
+= scale
-1;
2334 this_rq
->cpu_load
[i
] = (old_load
*(scale
-1) + new_load
) >> i
;
2341 * double_rq_lock - safely lock two runqueues
2343 * Note this does not disable interrupts like task_rq_lock,
2344 * you need to do so manually before calling.
2346 static void double_rq_lock(struct rq
*rq1
, struct rq
*rq2
)
2347 __acquires(rq1
->lock
)
2348 __acquires(rq2
->lock
)
2350 BUG_ON(!irqs_disabled());
2352 spin_lock(&rq1
->lock
);
2353 __acquire(rq2
->lock
); /* Fake it out ;) */
2356 spin_lock(&rq1
->lock
);
2357 spin_lock(&rq2
->lock
);
2359 spin_lock(&rq2
->lock
);
2360 spin_lock(&rq1
->lock
);
2363 update_rq_clock(rq1
);
2364 update_rq_clock(rq2
);
2368 * double_rq_unlock - safely unlock two runqueues
2370 * Note this does not restore interrupts like task_rq_unlock,
2371 * you need to do so manually after calling.
2373 static void double_rq_unlock(struct rq
*rq1
, struct rq
*rq2
)
2374 __releases(rq1
->lock
)
2375 __releases(rq2
->lock
)
2377 spin_unlock(&rq1
->lock
);
2379 spin_unlock(&rq2
->lock
);
2381 __release(rq2
->lock
);
2385 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2387 static int double_lock_balance(struct rq
*this_rq
, struct rq
*busiest
)
2388 __releases(this_rq
->lock
)
2389 __acquires(busiest
->lock
)
2390 __acquires(this_rq
->lock
)
2394 if (unlikely(!irqs_disabled())) {
2395 /* printk() doesn't work good under rq->lock */
2396 spin_unlock(&this_rq
->lock
);
2399 if (unlikely(!spin_trylock(&busiest
->lock
))) {
2400 if (busiest
< this_rq
) {
2401 spin_unlock(&this_rq
->lock
);
2402 spin_lock(&busiest
->lock
);
2403 spin_lock(&this_rq
->lock
);
2406 spin_lock(&busiest
->lock
);
2412 * If dest_cpu is allowed for this process, migrate the task to it.
2413 * This is accomplished by forcing the cpu_allowed mask to only
2414 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2415 * the cpu_allowed mask is restored.
2417 static void sched_migrate_task(struct task_struct
*p
, int dest_cpu
)
2419 struct migration_req req
;
2420 unsigned long flags
;
2423 rq
= task_rq_lock(p
, &flags
);
2424 if (!cpu_isset(dest_cpu
, p
->cpus_allowed
)
2425 || unlikely(cpu_is_offline(dest_cpu
)))
2428 /* force the process onto the specified CPU */
2429 if (migrate_task(p
, dest_cpu
, &req
)) {
2430 /* Need to wait for migration thread (might exit: take ref). */
2431 struct task_struct
*mt
= rq
->migration_thread
;
2433 get_task_struct(mt
);
2434 task_rq_unlock(rq
, &flags
);
2435 wake_up_process(mt
);
2436 put_task_struct(mt
);
2437 wait_for_completion(&req
.done
);
2442 task_rq_unlock(rq
, &flags
);
2446 * sched_exec - execve() is a valuable balancing opportunity, because at
2447 * this point the task has the smallest effective memory and cache footprint.
2449 void sched_exec(void)
2451 int new_cpu
, this_cpu
= get_cpu();
2452 new_cpu
= sched_balance_self(this_cpu
, SD_BALANCE_EXEC
);
2454 if (new_cpu
!= this_cpu
)
2455 sched_migrate_task(current
, new_cpu
);
2459 * pull_task - move a task from a remote runqueue to the local runqueue.
2460 * Both runqueues must be locked.
2462 static void pull_task(struct rq
*src_rq
, struct task_struct
*p
,
2463 struct rq
*this_rq
, int this_cpu
)
2465 deactivate_task(src_rq
, p
, 0);
2466 set_task_cpu(p
, this_cpu
);
2467 activate_task(this_rq
, p
, 0);
2469 * Note that idle threads have a prio of MAX_PRIO, for this test
2470 * to be always true for them.
2472 check_preempt_curr(this_rq
, p
);
2476 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2479 int can_migrate_task(struct task_struct
*p
, struct rq
*rq
, int this_cpu
,
2480 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2484 * We do not migrate tasks that are:
2485 * 1) running (obviously), or
2486 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2487 * 3) are cache-hot on their current CPU.
2489 if (!cpu_isset(this_cpu
, p
->cpus_allowed
)) {
2490 schedstat_inc(p
, se
.nr_failed_migrations_affine
);
2495 if (task_running(rq
, p
)) {
2496 schedstat_inc(p
, se
.nr_failed_migrations_running
);
2501 * Aggressive migration if:
2502 * 1) task is cache cold, or
2503 * 2) too many balance attempts have failed.
2506 if (!task_hot(p
, rq
->clock
, sd
) ||
2507 sd
->nr_balance_failed
> sd
->cache_nice_tries
) {
2508 #ifdef CONFIG_SCHEDSTATS
2509 if (task_hot(p
, rq
->clock
, sd
)) {
2510 schedstat_inc(sd
, lb_hot_gained
[idle
]);
2511 schedstat_inc(p
, se
.nr_forced_migrations
);
2517 if (task_hot(p
, rq
->clock
, sd
)) {
2518 schedstat_inc(p
, se
.nr_failed_migrations_hot
);
2524 static unsigned long
2525 balance_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2526 unsigned long max_load_move
, struct sched_domain
*sd
,
2527 enum cpu_idle_type idle
, int *all_pinned
,
2528 int *this_best_prio
, struct rq_iterator
*iterator
)
2530 int loops
= 0, pulled
= 0, pinned
= 0, skip_for_load
;
2531 struct task_struct
*p
;
2532 long rem_load_move
= max_load_move
;
2534 if (max_load_move
== 0)
2540 * Start the load-balancing iterator:
2542 p
= iterator
->start(iterator
->arg
);
2544 if (!p
|| loops
++ > sysctl_sched_nr_migrate
)
2547 * To help distribute high priority tasks across CPUs we don't
2548 * skip a task if it will be the highest priority task (i.e. smallest
2549 * prio value) on its new queue regardless of its load weight
2551 skip_for_load
= (p
->se
.load
.weight
>> 1) > rem_load_move
+
2552 SCHED_LOAD_SCALE_FUZZ
;
2553 if ((skip_for_load
&& p
->prio
>= *this_best_prio
) ||
2554 !can_migrate_task(p
, busiest
, this_cpu
, sd
, idle
, &pinned
)) {
2555 p
= iterator
->next(iterator
->arg
);
2559 pull_task(busiest
, p
, this_rq
, this_cpu
);
2561 rem_load_move
-= p
->se
.load
.weight
;
2564 * We only want to steal up to the prescribed amount of weighted load.
2566 if (rem_load_move
> 0) {
2567 if (p
->prio
< *this_best_prio
)
2568 *this_best_prio
= p
->prio
;
2569 p
= iterator
->next(iterator
->arg
);
2574 * Right now, this is one of only two places pull_task() is called,
2575 * so we can safely collect pull_task() stats here rather than
2576 * inside pull_task().
2578 schedstat_add(sd
, lb_gained
[idle
], pulled
);
2581 *all_pinned
= pinned
;
2583 return max_load_move
- rem_load_move
;
2587 * move_tasks tries to move up to max_load_move weighted load from busiest to
2588 * this_rq, as part of a balancing operation within domain "sd".
2589 * Returns 1 if successful and 0 otherwise.
2591 * Called with both runqueues locked.
2593 static int move_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2594 unsigned long max_load_move
,
2595 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2598 const struct sched_class
*class = sched_class_highest
;
2599 unsigned long total_load_moved
= 0;
2600 int this_best_prio
= this_rq
->curr
->prio
;
2604 class->load_balance(this_rq
, this_cpu
, busiest
,
2605 max_load_move
- total_load_moved
,
2606 sd
, idle
, all_pinned
, &this_best_prio
);
2607 class = class->next
;
2608 } while (class && max_load_move
> total_load_moved
);
2610 return total_load_moved
> 0;
2614 iter_move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2615 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2616 struct rq_iterator
*iterator
)
2618 struct task_struct
*p
= iterator
->start(iterator
->arg
);
2622 if (can_migrate_task(p
, busiest
, this_cpu
, sd
, idle
, &pinned
)) {
2623 pull_task(busiest
, p
, this_rq
, this_cpu
);
2625 * Right now, this is only the second place pull_task()
2626 * is called, so we can safely collect pull_task()
2627 * stats here rather than inside pull_task().
2629 schedstat_inc(sd
, lb_gained
[idle
]);
2633 p
= iterator
->next(iterator
->arg
);
2640 * move_one_task tries to move exactly one task from busiest to this_rq, as
2641 * part of active balancing operations within "domain".
2642 * Returns 1 if successful and 0 otherwise.
2644 * Called with both runqueues locked.
2646 static int move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2647 struct sched_domain
*sd
, enum cpu_idle_type idle
)
2649 const struct sched_class
*class;
2651 for (class = sched_class_highest
; class; class = class->next
)
2652 if (class->move_one_task(this_rq
, this_cpu
, busiest
, sd
, idle
))
2659 * find_busiest_group finds and returns the busiest CPU group within the
2660 * domain. It calculates and returns the amount of weighted load which
2661 * should be moved to restore balance via the imbalance parameter.
2663 static struct sched_group
*
2664 find_busiest_group(struct sched_domain
*sd
, int this_cpu
,
2665 unsigned long *imbalance
, enum cpu_idle_type idle
,
2666 int *sd_idle
, cpumask_t
*cpus
, int *balance
)
2668 struct sched_group
*busiest
= NULL
, *this = NULL
, *group
= sd
->groups
;
2669 unsigned long max_load
, avg_load
, total_load
, this_load
, total_pwr
;
2670 unsigned long max_pull
;
2671 unsigned long busiest_load_per_task
, busiest_nr_running
;
2672 unsigned long this_load_per_task
, this_nr_running
;
2673 int load_idx
, group_imb
= 0;
2674 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2675 int power_savings_balance
= 1;
2676 unsigned long leader_nr_running
= 0, min_load_per_task
= 0;
2677 unsigned long min_nr_running
= ULONG_MAX
;
2678 struct sched_group
*group_min
= NULL
, *group_leader
= NULL
;
2681 max_load
= this_load
= total_load
= total_pwr
= 0;
2682 busiest_load_per_task
= busiest_nr_running
= 0;
2683 this_load_per_task
= this_nr_running
= 0;
2684 if (idle
== CPU_NOT_IDLE
)
2685 load_idx
= sd
->busy_idx
;
2686 else if (idle
== CPU_NEWLY_IDLE
)
2687 load_idx
= sd
->newidle_idx
;
2689 load_idx
= sd
->idle_idx
;
2692 unsigned long load
, group_capacity
, max_cpu_load
, min_cpu_load
;
2695 int __group_imb
= 0;
2696 unsigned int balance_cpu
= -1, first_idle_cpu
= 0;
2697 unsigned long sum_nr_running
, sum_weighted_load
;
2699 local_group
= cpu_isset(this_cpu
, group
->cpumask
);
2702 balance_cpu
= first_cpu(group
->cpumask
);
2704 /* Tally up the load of all CPUs in the group */
2705 sum_weighted_load
= sum_nr_running
= avg_load
= 0;
2707 min_cpu_load
= ~0UL;
2709 for_each_cpu_mask(i
, group
->cpumask
) {
2712 if (!cpu_isset(i
, *cpus
))
2717 if (*sd_idle
&& rq
->nr_running
)
2720 /* Bias balancing toward cpus of our domain */
2722 if (idle_cpu(i
) && !first_idle_cpu
) {
2727 load
= target_load(i
, load_idx
);
2729 load
= source_load(i
, load_idx
);
2730 if (load
> max_cpu_load
)
2731 max_cpu_load
= load
;
2732 if (min_cpu_load
> load
)
2733 min_cpu_load
= load
;
2737 sum_nr_running
+= rq
->nr_running
;
2738 sum_weighted_load
+= weighted_cpuload(i
);
2742 * First idle cpu or the first cpu(busiest) in this sched group
2743 * is eligible for doing load balancing at this and above
2744 * domains. In the newly idle case, we will allow all the cpu's
2745 * to do the newly idle load balance.
2747 if (idle
!= CPU_NEWLY_IDLE
&& local_group
&&
2748 balance_cpu
!= this_cpu
&& balance
) {
2753 total_load
+= avg_load
;
2754 total_pwr
+= group
->__cpu_power
;
2756 /* Adjust by relative CPU power of the group */
2757 avg_load
= sg_div_cpu_power(group
,
2758 avg_load
* SCHED_LOAD_SCALE
);
2760 if ((max_cpu_load
- min_cpu_load
) > SCHED_LOAD_SCALE
)
2763 group_capacity
= group
->__cpu_power
/ SCHED_LOAD_SCALE
;
2766 this_load
= avg_load
;
2768 this_nr_running
= sum_nr_running
;
2769 this_load_per_task
= sum_weighted_load
;
2770 } else if (avg_load
> max_load
&&
2771 (sum_nr_running
> group_capacity
|| __group_imb
)) {
2772 max_load
= avg_load
;
2774 busiest_nr_running
= sum_nr_running
;
2775 busiest_load_per_task
= sum_weighted_load
;
2776 group_imb
= __group_imb
;
2779 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2781 * Busy processors will not participate in power savings
2784 if (idle
== CPU_NOT_IDLE
||
2785 !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
2789 * If the local group is idle or completely loaded
2790 * no need to do power savings balance at this domain
2792 if (local_group
&& (this_nr_running
>= group_capacity
||
2794 power_savings_balance
= 0;
2797 * If a group is already running at full capacity or idle,
2798 * don't include that group in power savings calculations
2800 if (!power_savings_balance
|| sum_nr_running
>= group_capacity
2805 * Calculate the group which has the least non-idle load.
2806 * This is the group from where we need to pick up the load
2809 if ((sum_nr_running
< min_nr_running
) ||
2810 (sum_nr_running
== min_nr_running
&&
2811 first_cpu(group
->cpumask
) <
2812 first_cpu(group_min
->cpumask
))) {
2814 min_nr_running
= sum_nr_running
;
2815 min_load_per_task
= sum_weighted_load
/
2820 * Calculate the group which is almost near its
2821 * capacity but still has some space to pick up some load
2822 * from other group and save more power
2824 if (sum_nr_running
<= group_capacity
- 1) {
2825 if (sum_nr_running
> leader_nr_running
||
2826 (sum_nr_running
== leader_nr_running
&&
2827 first_cpu(group
->cpumask
) >
2828 first_cpu(group_leader
->cpumask
))) {
2829 group_leader
= group
;
2830 leader_nr_running
= sum_nr_running
;
2835 group
= group
->next
;
2836 } while (group
!= sd
->groups
);
2838 if (!busiest
|| this_load
>= max_load
|| busiest_nr_running
== 0)
2841 avg_load
= (SCHED_LOAD_SCALE
* total_load
) / total_pwr
;
2843 if (this_load
>= avg_load
||
2844 100*max_load
<= sd
->imbalance_pct
*this_load
)
2847 busiest_load_per_task
/= busiest_nr_running
;
2849 busiest_load_per_task
= min(busiest_load_per_task
, avg_load
);
2852 * We're trying to get all the cpus to the average_load, so we don't
2853 * want to push ourselves above the average load, nor do we wish to
2854 * reduce the max loaded cpu below the average load, as either of these
2855 * actions would just result in more rebalancing later, and ping-pong
2856 * tasks around. Thus we look for the minimum possible imbalance.
2857 * Negative imbalances (*we* are more loaded than anyone else) will
2858 * be counted as no imbalance for these purposes -- we can't fix that
2859 * by pulling tasks to us. Be careful of negative numbers as they'll
2860 * appear as very large values with unsigned longs.
2862 if (max_load
<= busiest_load_per_task
)
2866 * In the presence of smp nice balancing, certain scenarios can have
2867 * max load less than avg load(as we skip the groups at or below
2868 * its cpu_power, while calculating max_load..)
2870 if (max_load
< avg_load
) {
2872 goto small_imbalance
;
2875 /* Don't want to pull so many tasks that a group would go idle */
2876 max_pull
= min(max_load
- avg_load
, max_load
- busiest_load_per_task
);
2878 /* How much load to actually move to equalise the imbalance */
2879 *imbalance
= min(max_pull
* busiest
->__cpu_power
,
2880 (avg_load
- this_load
) * this->__cpu_power
)
2884 * if *imbalance is less than the average load per runnable task
2885 * there is no gaurantee that any tasks will be moved so we'll have
2886 * a think about bumping its value to force at least one task to be
2889 if (*imbalance
< busiest_load_per_task
) {
2890 unsigned long tmp
, pwr_now
, pwr_move
;
2894 pwr_move
= pwr_now
= 0;
2896 if (this_nr_running
) {
2897 this_load_per_task
/= this_nr_running
;
2898 if (busiest_load_per_task
> this_load_per_task
)
2901 this_load_per_task
= SCHED_LOAD_SCALE
;
2903 if (max_load
- this_load
+ SCHED_LOAD_SCALE_FUZZ
>=
2904 busiest_load_per_task
* imbn
) {
2905 *imbalance
= busiest_load_per_task
;
2910 * OK, we don't have enough imbalance to justify moving tasks,
2911 * however we may be able to increase total CPU power used by
2915 pwr_now
+= busiest
->__cpu_power
*
2916 min(busiest_load_per_task
, max_load
);
2917 pwr_now
+= this->__cpu_power
*
2918 min(this_load_per_task
, this_load
);
2919 pwr_now
/= SCHED_LOAD_SCALE
;
2921 /* Amount of load we'd subtract */
2922 tmp
= sg_div_cpu_power(busiest
,
2923 busiest_load_per_task
* SCHED_LOAD_SCALE
);
2925 pwr_move
+= busiest
->__cpu_power
*
2926 min(busiest_load_per_task
, max_load
- tmp
);
2928 /* Amount of load we'd add */
2929 if (max_load
* busiest
->__cpu_power
<
2930 busiest_load_per_task
* SCHED_LOAD_SCALE
)
2931 tmp
= sg_div_cpu_power(this,
2932 max_load
* busiest
->__cpu_power
);
2934 tmp
= sg_div_cpu_power(this,
2935 busiest_load_per_task
* SCHED_LOAD_SCALE
);
2936 pwr_move
+= this->__cpu_power
*
2937 min(this_load_per_task
, this_load
+ tmp
);
2938 pwr_move
/= SCHED_LOAD_SCALE
;
2940 /* Move if we gain throughput */
2941 if (pwr_move
> pwr_now
)
2942 *imbalance
= busiest_load_per_task
;
2948 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2949 if (idle
== CPU_NOT_IDLE
|| !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
2952 if (this == group_leader
&& group_leader
!= group_min
) {
2953 *imbalance
= min_load_per_task
;
2963 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2966 find_busiest_queue(struct sched_group
*group
, enum cpu_idle_type idle
,
2967 unsigned long imbalance
, cpumask_t
*cpus
)
2969 struct rq
*busiest
= NULL
, *rq
;
2970 unsigned long max_load
= 0;
2973 for_each_cpu_mask(i
, group
->cpumask
) {
2976 if (!cpu_isset(i
, *cpus
))
2980 wl
= weighted_cpuload(i
);
2982 if (rq
->nr_running
== 1 && wl
> imbalance
)
2985 if (wl
> max_load
) {
2995 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2996 * so long as it is large enough.
2998 #define MAX_PINNED_INTERVAL 512
3001 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3002 * tasks if there is an imbalance.
3004 static int load_balance(int this_cpu
, struct rq
*this_rq
,
3005 struct sched_domain
*sd
, enum cpu_idle_type idle
,
3008 int ld_moved
, all_pinned
= 0, active_balance
= 0, sd_idle
= 0;
3009 struct sched_group
*group
;
3010 unsigned long imbalance
;
3012 cpumask_t cpus
= CPU_MASK_ALL
;
3013 unsigned long flags
;
3016 * When power savings policy is enabled for the parent domain, idle
3017 * sibling can pick up load irrespective of busy siblings. In this case,
3018 * let the state of idle sibling percolate up as CPU_IDLE, instead of
3019 * portraying it as CPU_NOT_IDLE.
3021 if (idle
!= CPU_NOT_IDLE
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3022 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3025 schedstat_inc(sd
, lb_count
[idle
]);
3028 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, idle
, &sd_idle
,
3035 schedstat_inc(sd
, lb_nobusyg
[idle
]);
3039 busiest
= find_busiest_queue(group
, idle
, imbalance
, &cpus
);
3041 schedstat_inc(sd
, lb_nobusyq
[idle
]);
3045 BUG_ON(busiest
== this_rq
);
3047 schedstat_add(sd
, lb_imbalance
[idle
], imbalance
);
3050 if (busiest
->nr_running
> 1) {
3052 * Attempt to move tasks. If find_busiest_group has found
3053 * an imbalance but busiest->nr_running <= 1, the group is
3054 * still unbalanced. ld_moved simply stays zero, so it is
3055 * correctly treated as an imbalance.
3057 local_irq_save(flags
);
3058 double_rq_lock(this_rq
, busiest
);
3059 ld_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
3060 imbalance
, sd
, idle
, &all_pinned
);
3061 double_rq_unlock(this_rq
, busiest
);
3062 local_irq_restore(flags
);
3065 * some other cpu did the load balance for us.
3067 if (ld_moved
&& this_cpu
!= smp_processor_id())
3068 resched_cpu(this_cpu
);
3070 /* All tasks on this runqueue were pinned by CPU affinity */
3071 if (unlikely(all_pinned
)) {
3072 cpu_clear(cpu_of(busiest
), cpus
);
3073 if (!cpus_empty(cpus
))
3080 schedstat_inc(sd
, lb_failed
[idle
]);
3081 sd
->nr_balance_failed
++;
3083 if (unlikely(sd
->nr_balance_failed
> sd
->cache_nice_tries
+2)) {
3085 spin_lock_irqsave(&busiest
->lock
, flags
);
3087 /* don't kick the migration_thread, if the curr
3088 * task on busiest cpu can't be moved to this_cpu
3090 if (!cpu_isset(this_cpu
, busiest
->curr
->cpus_allowed
)) {
3091 spin_unlock_irqrestore(&busiest
->lock
, flags
);
3093 goto out_one_pinned
;
3096 if (!busiest
->active_balance
) {
3097 busiest
->active_balance
= 1;
3098 busiest
->push_cpu
= this_cpu
;
3101 spin_unlock_irqrestore(&busiest
->lock
, flags
);
3103 wake_up_process(busiest
->migration_thread
);
3106 * We've kicked active balancing, reset the failure
3109 sd
->nr_balance_failed
= sd
->cache_nice_tries
+1;
3112 sd
->nr_balance_failed
= 0;
3114 if (likely(!active_balance
)) {
3115 /* We were unbalanced, so reset the balancing interval */
3116 sd
->balance_interval
= sd
->min_interval
;
3119 * If we've begun active balancing, start to back off. This
3120 * case may not be covered by the all_pinned logic if there
3121 * is only 1 task on the busy runqueue (because we don't call
3124 if (sd
->balance_interval
< sd
->max_interval
)
3125 sd
->balance_interval
*= 2;
3128 if (!ld_moved
&& !sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3129 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3134 schedstat_inc(sd
, lb_balanced
[idle
]);
3136 sd
->nr_balance_failed
= 0;
3139 /* tune up the balancing interval */
3140 if ((all_pinned
&& sd
->balance_interval
< MAX_PINNED_INTERVAL
) ||
3141 (sd
->balance_interval
< sd
->max_interval
))
3142 sd
->balance_interval
*= 2;
3144 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3145 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3151 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3152 * tasks if there is an imbalance.
3154 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3155 * this_rq is locked.
3158 load_balance_newidle(int this_cpu
, struct rq
*this_rq
, struct sched_domain
*sd
)
3160 struct sched_group
*group
;
3161 struct rq
*busiest
= NULL
;
3162 unsigned long imbalance
;
3166 cpumask_t cpus
= CPU_MASK_ALL
;
3169 * When power savings policy is enabled for the parent domain, idle
3170 * sibling can pick up load irrespective of busy siblings. In this case,
3171 * let the state of idle sibling percolate up as IDLE, instead of
3172 * portraying it as CPU_NOT_IDLE.
3174 if (sd
->flags
& SD_SHARE_CPUPOWER
&&
3175 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3178 schedstat_inc(sd
, lb_count
[CPU_NEWLY_IDLE
]);
3180 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, CPU_NEWLY_IDLE
,
3181 &sd_idle
, &cpus
, NULL
);
3183 schedstat_inc(sd
, lb_nobusyg
[CPU_NEWLY_IDLE
]);
3187 busiest
= find_busiest_queue(group
, CPU_NEWLY_IDLE
, imbalance
,
3190 schedstat_inc(sd
, lb_nobusyq
[CPU_NEWLY_IDLE
]);
3194 BUG_ON(busiest
== this_rq
);
3196 schedstat_add(sd
, lb_imbalance
[CPU_NEWLY_IDLE
], imbalance
);
3199 if (busiest
->nr_running
> 1) {
3200 /* Attempt to move tasks */
3201 double_lock_balance(this_rq
, busiest
);
3202 /* this_rq->clock is already updated */
3203 update_rq_clock(busiest
);
3204 ld_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
3205 imbalance
, sd
, CPU_NEWLY_IDLE
,
3207 spin_unlock(&busiest
->lock
);
3209 if (unlikely(all_pinned
)) {
3210 cpu_clear(cpu_of(busiest
), cpus
);
3211 if (!cpus_empty(cpus
))
3217 schedstat_inc(sd
, lb_failed
[CPU_NEWLY_IDLE
]);
3218 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3219 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3222 sd
->nr_balance_failed
= 0;
3227 schedstat_inc(sd
, lb_balanced
[CPU_NEWLY_IDLE
]);
3228 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3229 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3231 sd
->nr_balance_failed
= 0;
3237 * idle_balance is called by schedule() if this_cpu is about to become
3238 * idle. Attempts to pull tasks from other CPUs.
3240 static void idle_balance(int this_cpu
, struct rq
*this_rq
)
3242 struct sched_domain
*sd
;
3243 int pulled_task
= -1;
3244 unsigned long next_balance
= jiffies
+ HZ
;
3246 for_each_domain(this_cpu
, sd
) {
3247 unsigned long interval
;
3249 if (!(sd
->flags
& SD_LOAD_BALANCE
))
3252 if (sd
->flags
& SD_BALANCE_NEWIDLE
)
3253 /* If we've pulled tasks over stop searching: */
3254 pulled_task
= load_balance_newidle(this_cpu
,
3257 interval
= msecs_to_jiffies(sd
->balance_interval
);
3258 if (time_after(next_balance
, sd
->last_balance
+ interval
))
3259 next_balance
= sd
->last_balance
+ interval
;
3263 if (pulled_task
|| time_after(jiffies
, this_rq
->next_balance
)) {
3265 * We are going idle. next_balance may be set based on
3266 * a busy processor. So reset next_balance.
3268 this_rq
->next_balance
= next_balance
;
3273 * active_load_balance is run by migration threads. It pushes running tasks
3274 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3275 * running on each physical CPU where possible, and avoids physical /
3276 * logical imbalances.
3278 * Called with busiest_rq locked.
3280 static void active_load_balance(struct rq
*busiest_rq
, int busiest_cpu
)
3282 int target_cpu
= busiest_rq
->push_cpu
;
3283 struct sched_domain
*sd
;
3284 struct rq
*target_rq
;
3286 /* Is there any task to move? */
3287 if (busiest_rq
->nr_running
<= 1)
3290 target_rq
= cpu_rq(target_cpu
);
3293 * This condition is "impossible", if it occurs
3294 * we need to fix it. Originally reported by
3295 * Bjorn Helgaas on a 128-cpu setup.
3297 BUG_ON(busiest_rq
== target_rq
);
3299 /* move a task from busiest_rq to target_rq */
3300 double_lock_balance(busiest_rq
, target_rq
);
3301 update_rq_clock(busiest_rq
);
3302 update_rq_clock(target_rq
);
3304 /* Search for an sd spanning us and the target CPU. */
3305 for_each_domain(target_cpu
, sd
) {
3306 if ((sd
->flags
& SD_LOAD_BALANCE
) &&
3307 cpu_isset(busiest_cpu
, sd
->span
))
3312 schedstat_inc(sd
, alb_count
);
3314 if (move_one_task(target_rq
, target_cpu
, busiest_rq
,
3316 schedstat_inc(sd
, alb_pushed
);
3318 schedstat_inc(sd
, alb_failed
);
3320 spin_unlock(&target_rq
->lock
);
3325 atomic_t load_balancer
;
3327 } nohz ____cacheline_aligned
= {
3328 .load_balancer
= ATOMIC_INIT(-1),
3329 .cpu_mask
= CPU_MASK_NONE
,
3333 * This routine will try to nominate the ilb (idle load balancing)
3334 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3335 * load balancing on behalf of all those cpus. If all the cpus in the system
3336 * go into this tickless mode, then there will be no ilb owner (as there is
3337 * no need for one) and all the cpus will sleep till the next wakeup event
3340 * For the ilb owner, tick is not stopped. And this tick will be used
3341 * for idle load balancing. ilb owner will still be part of
3344 * While stopping the tick, this cpu will become the ilb owner if there
3345 * is no other owner. And will be the owner till that cpu becomes busy
3346 * or if all cpus in the system stop their ticks at which point
3347 * there is no need for ilb owner.
3349 * When the ilb owner becomes busy, it nominates another owner, during the
3350 * next busy scheduler_tick()
3352 int select_nohz_load_balancer(int stop_tick
)
3354 int cpu
= smp_processor_id();
3357 cpu_set(cpu
, nohz
.cpu_mask
);
3358 cpu_rq(cpu
)->in_nohz_recently
= 1;
3361 * If we are going offline and still the leader, give up!
3363 if (cpu_is_offline(cpu
) &&
3364 atomic_read(&nohz
.load_balancer
) == cpu
) {
3365 if (atomic_cmpxchg(&nohz
.load_balancer
, cpu
, -1) != cpu
)
3370 /* time for ilb owner also to sleep */
3371 if (cpus_weight(nohz
.cpu_mask
) == num_online_cpus()) {
3372 if (atomic_read(&nohz
.load_balancer
) == cpu
)
3373 atomic_set(&nohz
.load_balancer
, -1);
3377 if (atomic_read(&nohz
.load_balancer
) == -1) {
3378 /* make me the ilb owner */
3379 if (atomic_cmpxchg(&nohz
.load_balancer
, -1, cpu
) == -1)
3381 } else if (atomic_read(&nohz
.load_balancer
) == cpu
)
3384 if (!cpu_isset(cpu
, nohz
.cpu_mask
))
3387 cpu_clear(cpu
, nohz
.cpu_mask
);
3389 if (atomic_read(&nohz
.load_balancer
) == cpu
)
3390 if (atomic_cmpxchg(&nohz
.load_balancer
, cpu
, -1) != cpu
)
3397 static DEFINE_SPINLOCK(balancing
);
3400 * It checks each scheduling domain to see if it is due to be balanced,
3401 * and initiates a balancing operation if so.
3403 * Balancing parameters are set up in arch_init_sched_domains.
3405 static void rebalance_domains(int cpu
, enum cpu_idle_type idle
)
3408 struct rq
*rq
= cpu_rq(cpu
);
3409 unsigned long interval
;
3410 struct sched_domain
*sd
;
3411 /* Earliest time when we have to do rebalance again */
3412 unsigned long next_balance
= jiffies
+ 60*HZ
;
3413 int update_next_balance
= 0;
3415 for_each_domain(cpu
, sd
) {
3416 if (!(sd
->flags
& SD_LOAD_BALANCE
))
3419 interval
= sd
->balance_interval
;
3420 if (idle
!= CPU_IDLE
)
3421 interval
*= sd
->busy_factor
;
3423 /* scale ms to jiffies */
3424 interval
= msecs_to_jiffies(interval
);
3425 if (unlikely(!interval
))
3427 if (interval
> HZ
*NR_CPUS
/10)
3428 interval
= HZ
*NR_CPUS
/10;
3431 if (sd
->flags
& SD_SERIALIZE
) {
3432 if (!spin_trylock(&balancing
))
3436 if (time_after_eq(jiffies
, sd
->last_balance
+ interval
)) {
3437 if (load_balance(cpu
, rq
, sd
, idle
, &balance
)) {
3439 * We've pulled tasks over so either we're no
3440 * longer idle, or one of our SMT siblings is
3443 idle
= CPU_NOT_IDLE
;
3445 sd
->last_balance
= jiffies
;
3447 if (sd
->flags
& SD_SERIALIZE
)
3448 spin_unlock(&balancing
);
3450 if (time_after(next_balance
, sd
->last_balance
+ interval
)) {
3451 next_balance
= sd
->last_balance
+ interval
;
3452 update_next_balance
= 1;
3456 * Stop the load balance at this level. There is another
3457 * CPU in our sched group which is doing load balancing more
3465 * next_balance will be updated only when there is a need.
3466 * When the cpu is attached to null domain for ex, it will not be
3469 if (likely(update_next_balance
))
3470 rq
->next_balance
= next_balance
;
3474 * run_rebalance_domains is triggered when needed from the scheduler tick.
3475 * In CONFIG_NO_HZ case, the idle load balance owner will do the
3476 * rebalancing for all the cpus for whom scheduler ticks are stopped.
3478 static void run_rebalance_domains(struct softirq_action
*h
)
3480 int this_cpu
= smp_processor_id();
3481 struct rq
*this_rq
= cpu_rq(this_cpu
);
3482 enum cpu_idle_type idle
= this_rq
->idle_at_tick
?
3483 CPU_IDLE
: CPU_NOT_IDLE
;
3485 rebalance_domains(this_cpu
, idle
);
3489 * If this cpu is the owner for idle load balancing, then do the
3490 * balancing on behalf of the other idle cpus whose ticks are
3493 if (this_rq
->idle_at_tick
&&
3494 atomic_read(&nohz
.load_balancer
) == this_cpu
) {
3495 cpumask_t cpus
= nohz
.cpu_mask
;
3499 cpu_clear(this_cpu
, cpus
);
3500 for_each_cpu_mask(balance_cpu
, cpus
) {
3502 * If this cpu gets work to do, stop the load balancing
3503 * work being done for other cpus. Next load
3504 * balancing owner will pick it up.
3509 rebalance_domains(balance_cpu
, CPU_IDLE
);
3511 rq
= cpu_rq(balance_cpu
);
3512 if (time_after(this_rq
->next_balance
, rq
->next_balance
))
3513 this_rq
->next_balance
= rq
->next_balance
;
3520 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
3522 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
3523 * idle load balancing owner or decide to stop the periodic load balancing,
3524 * if the whole system is idle.
3526 static inline void trigger_load_balance(struct rq
*rq
, int cpu
)
3530 * If we were in the nohz mode recently and busy at the current
3531 * scheduler tick, then check if we need to nominate new idle
3534 if (rq
->in_nohz_recently
&& !rq
->idle_at_tick
) {
3535 rq
->in_nohz_recently
= 0;
3537 if (atomic_read(&nohz
.load_balancer
) == cpu
) {
3538 cpu_clear(cpu
, nohz
.cpu_mask
);
3539 atomic_set(&nohz
.load_balancer
, -1);
3542 if (atomic_read(&nohz
.load_balancer
) == -1) {
3544 * simple selection for now: Nominate the
3545 * first cpu in the nohz list to be the next
3548 * TBD: Traverse the sched domains and nominate
3549 * the nearest cpu in the nohz.cpu_mask.
3551 int ilb
= first_cpu(nohz
.cpu_mask
);
3559 * If this cpu is idle and doing idle load balancing for all the
3560 * cpus with ticks stopped, is it time for that to stop?
3562 if (rq
->idle_at_tick
&& atomic_read(&nohz
.load_balancer
) == cpu
&&
3563 cpus_weight(nohz
.cpu_mask
) == num_online_cpus()) {
3569 * If this cpu is idle and the idle load balancing is done by
3570 * someone else, then no need raise the SCHED_SOFTIRQ
3572 if (rq
->idle_at_tick
&& atomic_read(&nohz
.load_balancer
) != cpu
&&
3573 cpu_isset(cpu
, nohz
.cpu_mask
))
3576 if (time_after_eq(jiffies
, rq
->next_balance
))
3577 raise_softirq(SCHED_SOFTIRQ
);
3580 #else /* CONFIG_SMP */
3583 * on UP we do not need to balance between CPUs:
3585 static inline void idle_balance(int cpu
, struct rq
*rq
)
3591 DEFINE_PER_CPU(struct kernel_stat
, kstat
);
3593 EXPORT_PER_CPU_SYMBOL(kstat
);
3596 * Return p->sum_exec_runtime plus any more ns on the sched_clock
3597 * that have not yet been banked in case the task is currently running.
3599 unsigned long long task_sched_runtime(struct task_struct
*p
)
3601 unsigned long flags
;
3605 rq
= task_rq_lock(p
, &flags
);
3606 ns
= p
->se
.sum_exec_runtime
;
3607 if (task_current(rq
, p
)) {
3608 update_rq_clock(rq
);
3609 delta_exec
= rq
->clock
- p
->se
.exec_start
;
3610 if ((s64
)delta_exec
> 0)
3613 task_rq_unlock(rq
, &flags
);
3619 * Account user cpu time to a process.
3620 * @p: the process that the cpu time gets accounted to
3621 * @cputime: the cpu time spent in user space since the last update
3623 void account_user_time(struct task_struct
*p
, cputime_t cputime
)
3625 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3628 p
->utime
= cputime_add(p
->utime
, cputime
);
3630 /* Add user time to cpustat. */
3631 tmp
= cputime_to_cputime64(cputime
);
3632 if (TASK_NICE(p
) > 0)
3633 cpustat
->nice
= cputime64_add(cpustat
->nice
, tmp
);
3635 cpustat
->user
= cputime64_add(cpustat
->user
, tmp
);
3639 * Account guest cpu time to a process.
3640 * @p: the process that the cpu time gets accounted to
3641 * @cputime: the cpu time spent in virtual machine since the last update
3643 static void account_guest_time(struct task_struct
*p
, cputime_t cputime
)
3646 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3648 tmp
= cputime_to_cputime64(cputime
);
3650 p
->utime
= cputime_add(p
->utime
, cputime
);
3651 p
->gtime
= cputime_add(p
->gtime
, cputime
);
3653 cpustat
->user
= cputime64_add(cpustat
->user
, tmp
);
3654 cpustat
->guest
= cputime64_add(cpustat
->guest
, tmp
);
3658 * Account scaled user cpu time to a process.
3659 * @p: the process that the cpu time gets accounted to
3660 * @cputime: the cpu time spent in user space since the last update
3662 void account_user_time_scaled(struct task_struct
*p
, cputime_t cputime
)
3664 p
->utimescaled
= cputime_add(p
->utimescaled
, cputime
);
3668 * Account system cpu time to a process.
3669 * @p: the process that the cpu time gets accounted to
3670 * @hardirq_offset: the offset to subtract from hardirq_count()
3671 * @cputime: the cpu time spent in kernel space since the last update
3673 void account_system_time(struct task_struct
*p
, int hardirq_offset
,
3676 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3677 struct rq
*rq
= this_rq();
3680 if ((p
->flags
& PF_VCPU
) && (irq_count() - hardirq_offset
== 0))
3681 return account_guest_time(p
, cputime
);
3683 p
->stime
= cputime_add(p
->stime
, cputime
);
3685 /* Add system time to cpustat. */
3686 tmp
= cputime_to_cputime64(cputime
);
3687 if (hardirq_count() - hardirq_offset
)
3688 cpustat
->irq
= cputime64_add(cpustat
->irq
, tmp
);
3689 else if (softirq_count())
3690 cpustat
->softirq
= cputime64_add(cpustat
->softirq
, tmp
);
3691 else if (p
!= rq
->idle
)
3692 cpustat
->system
= cputime64_add(cpustat
->system
, tmp
);
3693 else if (atomic_read(&rq
->nr_iowait
) > 0)
3694 cpustat
->iowait
= cputime64_add(cpustat
->iowait
, tmp
);
3696 cpustat
->idle
= cputime64_add(cpustat
->idle
, tmp
);
3697 /* Account for system time used */
3698 acct_update_integrals(p
);
3702 * Account scaled system cpu time to a process.
3703 * @p: the process that the cpu time gets accounted to
3704 * @hardirq_offset: the offset to subtract from hardirq_count()
3705 * @cputime: the cpu time spent in kernel space since the last update
3707 void account_system_time_scaled(struct task_struct
*p
, cputime_t cputime
)
3709 p
->stimescaled
= cputime_add(p
->stimescaled
, cputime
);
3713 * Account for involuntary wait time.
3714 * @p: the process from which the cpu time has been stolen
3715 * @steal: the cpu time spent in involuntary wait
3717 void account_steal_time(struct task_struct
*p
, cputime_t steal
)
3719 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3720 cputime64_t tmp
= cputime_to_cputime64(steal
);
3721 struct rq
*rq
= this_rq();
3723 if (p
== rq
->idle
) {
3724 p
->stime
= cputime_add(p
->stime
, steal
);
3725 if (atomic_read(&rq
->nr_iowait
) > 0)
3726 cpustat
->iowait
= cputime64_add(cpustat
->iowait
, tmp
);
3728 cpustat
->idle
= cputime64_add(cpustat
->idle
, tmp
);
3730 cpustat
->steal
= cputime64_add(cpustat
->steal
, tmp
);
3734 * This function gets called by the timer code, with HZ frequency.
3735 * We call it with interrupts disabled.
3737 * It also gets called by the fork code, when changing the parent's
3740 void scheduler_tick(void)
3742 int cpu
= smp_processor_id();
3743 struct rq
*rq
= cpu_rq(cpu
);
3744 struct task_struct
*curr
= rq
->curr
;
3745 u64 next_tick
= rq
->tick_timestamp
+ TICK_NSEC
;
3747 spin_lock(&rq
->lock
);
3748 __update_rq_clock(rq
);
3750 * Let rq->clock advance by at least TICK_NSEC:
3752 if (unlikely(rq
->clock
< next_tick
)) {
3753 rq
->clock
= next_tick
;
3754 rq
->clock_underflows
++;
3756 rq
->tick_timestamp
= rq
->clock
;
3757 update_cpu_load(rq
);
3758 curr
->sched_class
->task_tick(rq
, curr
, 0);
3759 update_sched_rt_period(rq
);
3760 spin_unlock(&rq
->lock
);
3763 rq
->idle_at_tick
= idle_cpu(cpu
);
3764 trigger_load_balance(rq
, cpu
);
3768 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3770 void __kprobes
add_preempt_count(int val
)
3775 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3777 preempt_count() += val
;
3779 * Spinlock count overflowing soon?
3781 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK
) >=
3784 EXPORT_SYMBOL(add_preempt_count
);
3786 void __kprobes
sub_preempt_count(int val
)
3791 if (DEBUG_LOCKS_WARN_ON(val
> preempt_count()))
3794 * Is the spinlock portion underflowing?
3796 if (DEBUG_LOCKS_WARN_ON((val
< PREEMPT_MASK
) &&
3797 !(preempt_count() & PREEMPT_MASK
)))
3800 preempt_count() -= val
;
3802 EXPORT_SYMBOL(sub_preempt_count
);
3807 * Print scheduling while atomic bug:
3809 static noinline
void __schedule_bug(struct task_struct
*prev
)
3811 struct pt_regs
*regs
= get_irq_regs();
3813 printk(KERN_ERR
"BUG: scheduling while atomic: %s/%d/0x%08x\n",
3814 prev
->comm
, prev
->pid
, preempt_count());
3816 debug_show_held_locks(prev
);
3817 if (irqs_disabled())
3818 print_irqtrace_events(prev
);
3827 * Various schedule()-time debugging checks and statistics:
3829 static inline void schedule_debug(struct task_struct
*prev
)
3832 * Test if we are atomic. Since do_exit() needs to call into
3833 * schedule() atomically, we ignore that path for now.
3834 * Otherwise, whine if we are scheduling when we should not be.
3836 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev
->exit_state
))
3837 __schedule_bug(prev
);
3839 profile_hit(SCHED_PROFILING
, __builtin_return_address(0));
3841 schedstat_inc(this_rq(), sched_count
);
3842 #ifdef CONFIG_SCHEDSTATS
3843 if (unlikely(prev
->lock_depth
>= 0)) {
3844 schedstat_inc(this_rq(), bkl_count
);
3845 schedstat_inc(prev
, sched_info
.bkl_count
);
3851 * Pick up the highest-prio task:
3853 static inline struct task_struct
*
3854 pick_next_task(struct rq
*rq
, struct task_struct
*prev
)
3856 const struct sched_class
*class;
3857 struct task_struct
*p
;
3860 * Optimization: we know that if all tasks are in
3861 * the fair class we can call that function directly:
3863 if (likely(rq
->nr_running
== rq
->cfs
.nr_running
)) {
3864 p
= fair_sched_class
.pick_next_task(rq
);
3869 class = sched_class_highest
;
3871 p
= class->pick_next_task(rq
);
3875 * Will never be NULL as the idle class always
3876 * returns a non-NULL p:
3878 class = class->next
;
3883 * schedule() is the main scheduler function.
3885 asmlinkage
void __sched
schedule(void)
3887 struct task_struct
*prev
, *next
;
3894 cpu
= smp_processor_id();
3898 switch_count
= &prev
->nivcsw
;
3900 release_kernel_lock(prev
);
3901 need_resched_nonpreemptible
:
3903 schedule_debug(prev
);
3908 * Do the rq-clock update outside the rq lock:
3910 local_irq_disable();
3911 __update_rq_clock(rq
);
3912 spin_lock(&rq
->lock
);
3913 clear_tsk_need_resched(prev
);
3915 if (prev
->state
&& !(preempt_count() & PREEMPT_ACTIVE
)) {
3916 if (unlikely((prev
->state
& TASK_INTERRUPTIBLE
) &&
3917 unlikely(signal_pending(prev
)))) {
3918 prev
->state
= TASK_RUNNING
;
3920 deactivate_task(rq
, prev
, 1);
3922 switch_count
= &prev
->nvcsw
;
3926 if (prev
->sched_class
->pre_schedule
)
3927 prev
->sched_class
->pre_schedule(rq
, prev
);
3930 if (unlikely(!rq
->nr_running
))
3931 idle_balance(cpu
, rq
);
3933 prev
->sched_class
->put_prev_task(rq
, prev
);
3934 next
= pick_next_task(rq
, prev
);
3936 sched_info_switch(prev
, next
);
3938 if (likely(prev
!= next
)) {
3943 context_switch(rq
, prev
, next
); /* unlocks the rq */
3945 * the context switch might have flipped the stack from under
3946 * us, hence refresh the local variables.
3948 cpu
= smp_processor_id();
3951 spin_unlock_irq(&rq
->lock
);
3955 if (unlikely(reacquire_kernel_lock(current
) < 0))
3956 goto need_resched_nonpreemptible
;
3958 preempt_enable_no_resched();
3959 if (unlikely(test_thread_flag(TIF_NEED_RESCHED
)))
3962 EXPORT_SYMBOL(schedule
);
3964 #ifdef CONFIG_PREEMPT
3966 * this is the entry point to schedule() from in-kernel preemption
3967 * off of preempt_enable. Kernel preemptions off return from interrupt
3968 * occur there and call schedule directly.
3970 asmlinkage
void __sched
preempt_schedule(void)
3972 struct thread_info
*ti
= current_thread_info();
3973 struct task_struct
*task
= current
;
3974 int saved_lock_depth
;
3977 * If there is a non-zero preempt_count or interrupts are disabled,
3978 * we do not want to preempt the current task. Just return..
3980 if (likely(ti
->preempt_count
|| irqs_disabled()))
3984 add_preempt_count(PREEMPT_ACTIVE
);
3987 * We keep the big kernel semaphore locked, but we
3988 * clear ->lock_depth so that schedule() doesnt
3989 * auto-release the semaphore:
3991 saved_lock_depth
= task
->lock_depth
;
3992 task
->lock_depth
= -1;
3994 task
->lock_depth
= saved_lock_depth
;
3995 sub_preempt_count(PREEMPT_ACTIVE
);
3998 * Check again in case we missed a preemption opportunity
3999 * between schedule and now.
4002 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED
)));
4004 EXPORT_SYMBOL(preempt_schedule
);
4007 * this is the entry point to schedule() from kernel preemption
4008 * off of irq context.
4009 * Note, that this is called and return with irqs disabled. This will
4010 * protect us against recursive calling from irq.
4012 asmlinkage
void __sched
preempt_schedule_irq(void)
4014 struct thread_info
*ti
= current_thread_info();
4015 struct task_struct
*task
= current
;
4016 int saved_lock_depth
;
4018 /* Catch callers which need to be fixed */
4019 BUG_ON(ti
->preempt_count
|| !irqs_disabled());
4022 add_preempt_count(PREEMPT_ACTIVE
);
4025 * We keep the big kernel semaphore locked, but we
4026 * clear ->lock_depth so that schedule() doesnt
4027 * auto-release the semaphore:
4029 saved_lock_depth
= task
->lock_depth
;
4030 task
->lock_depth
= -1;
4033 local_irq_disable();
4034 task
->lock_depth
= saved_lock_depth
;
4035 sub_preempt_count(PREEMPT_ACTIVE
);
4038 * Check again in case we missed a preemption opportunity
4039 * between schedule and now.
4042 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED
)));
4045 #endif /* CONFIG_PREEMPT */
4047 int default_wake_function(wait_queue_t
*curr
, unsigned mode
, int sync
,
4050 return try_to_wake_up(curr
->private, mode
, sync
);
4052 EXPORT_SYMBOL(default_wake_function
);
4055 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4056 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4057 * number) then we wake all the non-exclusive tasks and one exclusive task.
4059 * There are circumstances in which we can try to wake a task which has already
4060 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4061 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4063 static void __wake_up_common(wait_queue_head_t
*q
, unsigned int mode
,
4064 int nr_exclusive
, int sync
, void *key
)
4066 wait_queue_t
*curr
, *next
;
4068 list_for_each_entry_safe(curr
, next
, &q
->task_list
, task_list
) {
4069 unsigned flags
= curr
->flags
;
4071 if (curr
->func(curr
, mode
, sync
, key
) &&
4072 (flags
& WQ_FLAG_EXCLUSIVE
) && !--nr_exclusive
)
4078 * __wake_up - wake up threads blocked on a waitqueue.
4080 * @mode: which threads
4081 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4082 * @key: is directly passed to the wakeup function
4084 void __wake_up(wait_queue_head_t
*q
, unsigned int mode
,
4085 int nr_exclusive
, void *key
)
4087 unsigned long flags
;
4089 spin_lock_irqsave(&q
->lock
, flags
);
4090 __wake_up_common(q
, mode
, nr_exclusive
, 0, key
);
4091 spin_unlock_irqrestore(&q
->lock
, flags
);
4093 EXPORT_SYMBOL(__wake_up
);
4096 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4098 void __wake_up_locked(wait_queue_head_t
*q
, unsigned int mode
)
4100 __wake_up_common(q
, mode
, 1, 0, NULL
);
4104 * __wake_up_sync - wake up threads blocked on a waitqueue.
4106 * @mode: which threads
4107 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4109 * The sync wakeup differs that the waker knows that it will schedule
4110 * away soon, so while the target thread will be woken up, it will not
4111 * be migrated to another CPU - ie. the two threads are 'synchronized'
4112 * with each other. This can prevent needless bouncing between CPUs.
4114 * On UP it can prevent extra preemption.
4117 __wake_up_sync(wait_queue_head_t
*q
, unsigned int mode
, int nr_exclusive
)
4119 unsigned long flags
;
4125 if (unlikely(!nr_exclusive
))
4128 spin_lock_irqsave(&q
->lock
, flags
);
4129 __wake_up_common(q
, mode
, nr_exclusive
, sync
, NULL
);
4130 spin_unlock_irqrestore(&q
->lock
, flags
);
4132 EXPORT_SYMBOL_GPL(__wake_up_sync
); /* For internal use only */
4134 void complete(struct completion
*x
)
4136 unsigned long flags
;
4138 spin_lock_irqsave(&x
->wait
.lock
, flags
);
4140 __wake_up_common(&x
->wait
, TASK_NORMAL
, 1, 0, NULL
);
4141 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
4143 EXPORT_SYMBOL(complete
);
4145 void complete_all(struct completion
*x
)
4147 unsigned long flags
;
4149 spin_lock_irqsave(&x
->wait
.lock
, flags
);
4150 x
->done
+= UINT_MAX
/2;
4151 __wake_up_common(&x
->wait
, TASK_NORMAL
, 0, 0, NULL
);
4152 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
4154 EXPORT_SYMBOL(complete_all
);
4156 static inline long __sched
4157 do_wait_for_common(struct completion
*x
, long timeout
, int state
)
4160 DECLARE_WAITQUEUE(wait
, current
);
4162 wait
.flags
|= WQ_FLAG_EXCLUSIVE
;
4163 __add_wait_queue_tail(&x
->wait
, &wait
);
4165 if ((state
== TASK_INTERRUPTIBLE
&&
4166 signal_pending(current
)) ||
4167 (state
== TASK_KILLABLE
&&
4168 fatal_signal_pending(current
))) {
4169 __remove_wait_queue(&x
->wait
, &wait
);
4170 return -ERESTARTSYS
;
4172 __set_current_state(state
);
4173 spin_unlock_irq(&x
->wait
.lock
);
4174 timeout
= schedule_timeout(timeout
);
4175 spin_lock_irq(&x
->wait
.lock
);
4177 __remove_wait_queue(&x
->wait
, &wait
);
4181 __remove_wait_queue(&x
->wait
, &wait
);
4188 wait_for_common(struct completion
*x
, long timeout
, int state
)
4192 spin_lock_irq(&x
->wait
.lock
);
4193 timeout
= do_wait_for_common(x
, timeout
, state
);
4194 spin_unlock_irq(&x
->wait
.lock
);
4198 void __sched
wait_for_completion(struct completion
*x
)
4200 wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_UNINTERRUPTIBLE
);
4202 EXPORT_SYMBOL(wait_for_completion
);
4204 unsigned long __sched
4205 wait_for_completion_timeout(struct completion
*x
, unsigned long timeout
)
4207 return wait_for_common(x
, timeout
, TASK_UNINTERRUPTIBLE
);
4209 EXPORT_SYMBOL(wait_for_completion_timeout
);
4211 int __sched
wait_for_completion_interruptible(struct completion
*x
)
4213 long t
= wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_INTERRUPTIBLE
);
4214 if (t
== -ERESTARTSYS
)
4218 EXPORT_SYMBOL(wait_for_completion_interruptible
);
4220 unsigned long __sched
4221 wait_for_completion_interruptible_timeout(struct completion
*x
,
4222 unsigned long timeout
)
4224 return wait_for_common(x
, timeout
, TASK_INTERRUPTIBLE
);
4226 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout
);
4228 int __sched
wait_for_completion_killable(struct completion
*x
)
4230 long t
= wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_KILLABLE
);
4231 if (t
== -ERESTARTSYS
)
4235 EXPORT_SYMBOL(wait_for_completion_killable
);
4238 sleep_on_common(wait_queue_head_t
*q
, int state
, long timeout
)
4240 unsigned long flags
;
4243 init_waitqueue_entry(&wait
, current
);
4245 __set_current_state(state
);
4247 spin_lock_irqsave(&q
->lock
, flags
);
4248 __add_wait_queue(q
, &wait
);
4249 spin_unlock(&q
->lock
);
4250 timeout
= schedule_timeout(timeout
);
4251 spin_lock_irq(&q
->lock
);
4252 __remove_wait_queue(q
, &wait
);
4253 spin_unlock_irqrestore(&q
->lock
, flags
);
4258 void __sched
interruptible_sleep_on(wait_queue_head_t
*q
)
4260 sleep_on_common(q
, TASK_INTERRUPTIBLE
, MAX_SCHEDULE_TIMEOUT
);
4262 EXPORT_SYMBOL(interruptible_sleep_on
);
4265 interruptible_sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
4267 return sleep_on_common(q
, TASK_INTERRUPTIBLE
, timeout
);
4269 EXPORT_SYMBOL(interruptible_sleep_on_timeout
);
4271 void __sched
sleep_on(wait_queue_head_t
*q
)
4273 sleep_on_common(q
, TASK_UNINTERRUPTIBLE
, MAX_SCHEDULE_TIMEOUT
);
4275 EXPORT_SYMBOL(sleep_on
);
4277 long __sched
sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
4279 return sleep_on_common(q
, TASK_UNINTERRUPTIBLE
, timeout
);
4281 EXPORT_SYMBOL(sleep_on_timeout
);
4283 #ifdef CONFIG_RT_MUTEXES
4286 * rt_mutex_setprio - set the current priority of a task
4288 * @prio: prio value (kernel-internal form)
4290 * This function changes the 'effective' priority of a task. It does
4291 * not touch ->normal_prio like __setscheduler().
4293 * Used by the rt_mutex code to implement priority inheritance logic.
4295 void rt_mutex_setprio(struct task_struct
*p
, int prio
)
4297 unsigned long flags
;
4298 int oldprio
, on_rq
, running
;
4300 const struct sched_class
*prev_class
= p
->sched_class
;
4302 BUG_ON(prio
< 0 || prio
> MAX_PRIO
);
4304 rq
= task_rq_lock(p
, &flags
);
4305 update_rq_clock(rq
);
4308 on_rq
= p
->se
.on_rq
;
4309 running
= task_current(rq
, p
);
4311 dequeue_task(rq
, p
, 0);
4313 p
->sched_class
->put_prev_task(rq
, p
);
4317 p
->sched_class
= &rt_sched_class
;
4319 p
->sched_class
= &fair_sched_class
;
4325 p
->sched_class
->set_curr_task(rq
);
4327 enqueue_task(rq
, p
, 0);
4329 check_class_changed(rq
, p
, prev_class
, oldprio
, running
);
4331 task_rq_unlock(rq
, &flags
);
4336 void set_user_nice(struct task_struct
*p
, long nice
)
4338 int old_prio
, delta
, on_rq
;
4339 unsigned long flags
;
4342 if (TASK_NICE(p
) == nice
|| nice
< -20 || nice
> 19)
4345 * We have to be careful, if called from sys_setpriority(),
4346 * the task might be in the middle of scheduling on another CPU.
4348 rq
= task_rq_lock(p
, &flags
);
4349 update_rq_clock(rq
);
4351 * The RT priorities are set via sched_setscheduler(), but we still
4352 * allow the 'normal' nice value to be set - but as expected
4353 * it wont have any effect on scheduling until the task is
4354 * SCHED_FIFO/SCHED_RR:
4356 if (task_has_rt_policy(p
)) {
4357 p
->static_prio
= NICE_TO_PRIO(nice
);
4360 on_rq
= p
->se
.on_rq
;
4362 dequeue_task(rq
, p
, 0);
4364 p
->static_prio
= NICE_TO_PRIO(nice
);
4367 p
->prio
= effective_prio(p
);
4368 delta
= p
->prio
- old_prio
;
4371 enqueue_task(rq
, p
, 0);
4373 * If the task increased its priority or is running and
4374 * lowered its priority, then reschedule its CPU:
4376 if (delta
< 0 || (delta
> 0 && task_running(rq
, p
)))
4377 resched_task(rq
->curr
);
4380 task_rq_unlock(rq
, &flags
);
4382 EXPORT_SYMBOL(set_user_nice
);
4385 * can_nice - check if a task can reduce its nice value
4389 int can_nice(const struct task_struct
*p
, const int nice
)
4391 /* convert nice value [19,-20] to rlimit style value [1,40] */
4392 int nice_rlim
= 20 - nice
;
4394 return (nice_rlim
<= p
->signal
->rlim
[RLIMIT_NICE
].rlim_cur
||
4395 capable(CAP_SYS_NICE
));
4398 #ifdef __ARCH_WANT_SYS_NICE
4401 * sys_nice - change the priority of the current process.
4402 * @increment: priority increment
4404 * sys_setpriority is a more generic, but much slower function that
4405 * does similar things.
4407 asmlinkage
long sys_nice(int increment
)
4412 * Setpriority might change our priority at the same moment.
4413 * We don't have to worry. Conceptually one call occurs first
4414 * and we have a single winner.
4416 if (increment
< -40)
4421 nice
= PRIO_TO_NICE(current
->static_prio
) + increment
;
4427 if (increment
< 0 && !can_nice(current
, nice
))
4430 retval
= security_task_setnice(current
, nice
);
4434 set_user_nice(current
, nice
);
4441 * task_prio - return the priority value of a given task.
4442 * @p: the task in question.
4444 * This is the priority value as seen by users in /proc.
4445 * RT tasks are offset by -200. Normal tasks are centered
4446 * around 0, value goes from -16 to +15.
4448 int task_prio(const struct task_struct
*p
)
4450 return p
->prio
- MAX_RT_PRIO
;
4454 * task_nice - return the nice value of a given task.
4455 * @p: the task in question.
4457 int task_nice(const struct task_struct
*p
)
4459 return TASK_NICE(p
);
4461 EXPORT_SYMBOL_GPL(task_nice
);
4464 * idle_cpu - is a given cpu idle currently?
4465 * @cpu: the processor in question.
4467 int idle_cpu(int cpu
)
4469 return cpu_curr(cpu
) == cpu_rq(cpu
)->idle
;
4473 * idle_task - return the idle task for a given cpu.
4474 * @cpu: the processor in question.
4476 struct task_struct
*idle_task(int cpu
)
4478 return cpu_rq(cpu
)->idle
;
4482 * find_process_by_pid - find a process with a matching PID value.
4483 * @pid: the pid in question.
4485 static struct task_struct
*find_process_by_pid(pid_t pid
)
4487 return pid
? find_task_by_vpid(pid
) : current
;
4490 /* Actually do priority change: must hold rq lock. */
4492 __setscheduler(struct rq
*rq
, struct task_struct
*p
, int policy
, int prio
)
4494 BUG_ON(p
->se
.on_rq
);
4497 switch (p
->policy
) {
4501 p
->sched_class
= &fair_sched_class
;
4505 p
->sched_class
= &rt_sched_class
;
4509 p
->rt_priority
= prio
;
4510 p
->normal_prio
= normal_prio(p
);
4511 /* we are holding p->pi_lock already */
4512 p
->prio
= rt_mutex_getprio(p
);
4517 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4518 * @p: the task in question.
4519 * @policy: new policy.
4520 * @param: structure containing the new RT priority.
4522 * NOTE that the task may be already dead.
4524 int sched_setscheduler(struct task_struct
*p
, int policy
,
4525 struct sched_param
*param
)
4527 int retval
, oldprio
, oldpolicy
= -1, on_rq
, running
;
4528 unsigned long flags
;
4529 const struct sched_class
*prev_class
= p
->sched_class
;
4532 /* may grab non-irq protected spin_locks */
4533 BUG_ON(in_interrupt());
4535 /* double check policy once rq lock held */
4537 policy
= oldpolicy
= p
->policy
;
4538 else if (policy
!= SCHED_FIFO
&& policy
!= SCHED_RR
&&
4539 policy
!= SCHED_NORMAL
&& policy
!= SCHED_BATCH
&&
4540 policy
!= SCHED_IDLE
)
4543 * Valid priorities for SCHED_FIFO and SCHED_RR are
4544 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4545 * SCHED_BATCH and SCHED_IDLE is 0.
4547 if (param
->sched_priority
< 0 ||
4548 (p
->mm
&& param
->sched_priority
> MAX_USER_RT_PRIO
-1) ||
4549 (!p
->mm
&& param
->sched_priority
> MAX_RT_PRIO
-1))
4551 if (rt_policy(policy
) != (param
->sched_priority
!= 0))
4555 * Allow unprivileged RT tasks to decrease priority:
4557 if (!capable(CAP_SYS_NICE
)) {
4558 if (rt_policy(policy
)) {
4559 unsigned long rlim_rtprio
;
4561 if (!lock_task_sighand(p
, &flags
))
4563 rlim_rtprio
= p
->signal
->rlim
[RLIMIT_RTPRIO
].rlim_cur
;
4564 unlock_task_sighand(p
, &flags
);
4566 /* can't set/change the rt policy */
4567 if (policy
!= p
->policy
&& !rlim_rtprio
)
4570 /* can't increase priority */
4571 if (param
->sched_priority
> p
->rt_priority
&&
4572 param
->sched_priority
> rlim_rtprio
)
4576 * Like positive nice levels, dont allow tasks to
4577 * move out of SCHED_IDLE either:
4579 if (p
->policy
== SCHED_IDLE
&& policy
!= SCHED_IDLE
)
4582 /* can't change other user's priorities */
4583 if ((current
->euid
!= p
->euid
) &&
4584 (current
->euid
!= p
->uid
))
4588 #ifdef CONFIG_RT_GROUP_SCHED
4590 * Do not allow realtime tasks into groups that have no runtime
4593 if (rt_policy(policy
) && task_group(p
)->rt_runtime
== 0)
4597 retval
= security_task_setscheduler(p
, policy
, param
);
4601 * make sure no PI-waiters arrive (or leave) while we are
4602 * changing the priority of the task:
4604 spin_lock_irqsave(&p
->pi_lock
, flags
);
4606 * To be able to change p->policy safely, the apropriate
4607 * runqueue lock must be held.
4609 rq
= __task_rq_lock(p
);
4610 /* recheck policy now with rq lock held */
4611 if (unlikely(oldpolicy
!= -1 && oldpolicy
!= p
->policy
)) {
4612 policy
= oldpolicy
= -1;
4613 __task_rq_unlock(rq
);
4614 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
4617 update_rq_clock(rq
);
4618 on_rq
= p
->se
.on_rq
;
4619 running
= task_current(rq
, p
);
4621 deactivate_task(rq
, p
, 0);
4623 p
->sched_class
->put_prev_task(rq
, p
);
4627 __setscheduler(rq
, p
, policy
, param
->sched_priority
);
4631 p
->sched_class
->set_curr_task(rq
);
4633 activate_task(rq
, p
, 0);
4635 check_class_changed(rq
, p
, prev_class
, oldprio
, running
);
4637 __task_rq_unlock(rq
);
4638 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
4640 rt_mutex_adjust_pi(p
);
4644 EXPORT_SYMBOL_GPL(sched_setscheduler
);
4647 do_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
4649 struct sched_param lparam
;
4650 struct task_struct
*p
;
4653 if (!param
|| pid
< 0)
4655 if (copy_from_user(&lparam
, param
, sizeof(struct sched_param
)))
4660 p
= find_process_by_pid(pid
);
4662 retval
= sched_setscheduler(p
, policy
, &lparam
);
4669 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4670 * @pid: the pid in question.
4671 * @policy: new policy.
4672 * @param: structure containing the new RT priority.
4675 sys_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
4677 /* negative values for policy are not valid */
4681 return do_sched_setscheduler(pid
, policy
, param
);
4685 * sys_sched_setparam - set/change the RT priority of a thread
4686 * @pid: the pid in question.
4687 * @param: structure containing the new RT priority.
4689 asmlinkage
long sys_sched_setparam(pid_t pid
, struct sched_param __user
*param
)
4691 return do_sched_setscheduler(pid
, -1, param
);
4695 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4696 * @pid: the pid in question.
4698 asmlinkage
long sys_sched_getscheduler(pid_t pid
)
4700 struct task_struct
*p
;
4707 read_lock(&tasklist_lock
);
4708 p
= find_process_by_pid(pid
);
4710 retval
= security_task_getscheduler(p
);
4714 read_unlock(&tasklist_lock
);
4719 * sys_sched_getscheduler - get the RT priority of a thread
4720 * @pid: the pid in question.
4721 * @param: structure containing the RT priority.
4723 asmlinkage
long sys_sched_getparam(pid_t pid
, struct sched_param __user
*param
)
4725 struct sched_param lp
;
4726 struct task_struct
*p
;
4729 if (!param
|| pid
< 0)
4732 read_lock(&tasklist_lock
);
4733 p
= find_process_by_pid(pid
);
4738 retval
= security_task_getscheduler(p
);
4742 lp
.sched_priority
= p
->rt_priority
;
4743 read_unlock(&tasklist_lock
);
4746 * This one might sleep, we cannot do it with a spinlock held ...
4748 retval
= copy_to_user(param
, &lp
, sizeof(*param
)) ? -EFAULT
: 0;
4753 read_unlock(&tasklist_lock
);
4757 long sched_setaffinity(pid_t pid
, cpumask_t new_mask
)
4759 cpumask_t cpus_allowed
;
4760 struct task_struct
*p
;
4764 read_lock(&tasklist_lock
);
4766 p
= find_process_by_pid(pid
);
4768 read_unlock(&tasklist_lock
);
4774 * It is not safe to call set_cpus_allowed with the
4775 * tasklist_lock held. We will bump the task_struct's
4776 * usage count and then drop tasklist_lock.
4779 read_unlock(&tasklist_lock
);
4782 if ((current
->euid
!= p
->euid
) && (current
->euid
!= p
->uid
) &&
4783 !capable(CAP_SYS_NICE
))
4786 retval
= security_task_setscheduler(p
, 0, NULL
);
4790 cpus_allowed
= cpuset_cpus_allowed(p
);
4791 cpus_and(new_mask
, new_mask
, cpus_allowed
);
4793 retval
= set_cpus_allowed(p
, new_mask
);
4796 cpus_allowed
= cpuset_cpus_allowed(p
);
4797 if (!cpus_subset(new_mask
, cpus_allowed
)) {
4799 * We must have raced with a concurrent cpuset
4800 * update. Just reset the cpus_allowed to the
4801 * cpuset's cpus_allowed
4803 new_mask
= cpus_allowed
;
4813 static int get_user_cpu_mask(unsigned long __user
*user_mask_ptr
, unsigned len
,
4814 cpumask_t
*new_mask
)
4816 if (len
< sizeof(cpumask_t
)) {
4817 memset(new_mask
, 0, sizeof(cpumask_t
));
4818 } else if (len
> sizeof(cpumask_t
)) {
4819 len
= sizeof(cpumask_t
);
4821 return copy_from_user(new_mask
, user_mask_ptr
, len
) ? -EFAULT
: 0;
4825 * sys_sched_setaffinity - set the cpu affinity of a process
4826 * @pid: pid of the process
4827 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4828 * @user_mask_ptr: user-space pointer to the new cpu mask
4830 asmlinkage
long sys_sched_setaffinity(pid_t pid
, unsigned int len
,
4831 unsigned long __user
*user_mask_ptr
)
4836 retval
= get_user_cpu_mask(user_mask_ptr
, len
, &new_mask
);
4840 return sched_setaffinity(pid
, new_mask
);
4844 * Represents all cpu's present in the system
4845 * In systems capable of hotplug, this map could dynamically grow
4846 * as new cpu's are detected in the system via any platform specific
4847 * method, such as ACPI for e.g.
4850 cpumask_t cpu_present_map __read_mostly
;
4851 EXPORT_SYMBOL(cpu_present_map
);
4854 cpumask_t cpu_online_map __read_mostly
= CPU_MASK_ALL
;
4855 EXPORT_SYMBOL(cpu_online_map
);
4857 cpumask_t cpu_possible_map __read_mostly
= CPU_MASK_ALL
;
4858 EXPORT_SYMBOL(cpu_possible_map
);
4861 long sched_getaffinity(pid_t pid
, cpumask_t
*mask
)
4863 struct task_struct
*p
;
4867 read_lock(&tasklist_lock
);
4870 p
= find_process_by_pid(pid
);
4874 retval
= security_task_getscheduler(p
);
4878 cpus_and(*mask
, p
->cpus_allowed
, cpu_online_map
);
4881 read_unlock(&tasklist_lock
);
4888 * sys_sched_getaffinity - get the cpu affinity of a process
4889 * @pid: pid of the process
4890 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4891 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4893 asmlinkage
long sys_sched_getaffinity(pid_t pid
, unsigned int len
,
4894 unsigned long __user
*user_mask_ptr
)
4899 if (len
< sizeof(cpumask_t
))
4902 ret
= sched_getaffinity(pid
, &mask
);
4906 if (copy_to_user(user_mask_ptr
, &mask
, sizeof(cpumask_t
)))
4909 return sizeof(cpumask_t
);
4913 * sys_sched_yield - yield the current processor to other threads.
4915 * This function yields the current CPU to other tasks. If there are no
4916 * other threads running on this CPU then this function will return.
4918 asmlinkage
long sys_sched_yield(void)
4920 struct rq
*rq
= this_rq_lock();
4922 schedstat_inc(rq
, yld_count
);
4923 current
->sched_class
->yield_task(rq
);
4926 * Since we are going to call schedule() anyway, there's
4927 * no need to preempt or enable interrupts:
4929 __release(rq
->lock
);
4930 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
4931 _raw_spin_unlock(&rq
->lock
);
4932 preempt_enable_no_resched();
4939 static void __cond_resched(void)
4941 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4942 __might_sleep(__FILE__
, __LINE__
);
4945 * The BKS might be reacquired before we have dropped
4946 * PREEMPT_ACTIVE, which could trigger a second
4947 * cond_resched() call.
4950 add_preempt_count(PREEMPT_ACTIVE
);
4952 sub_preempt_count(PREEMPT_ACTIVE
);
4953 } while (need_resched());
4956 #if !defined(CONFIG_PREEMPT) || defined(CONFIG_PREEMPT_VOLUNTARY)
4957 int __sched
_cond_resched(void)
4959 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE
) &&
4960 system_state
== SYSTEM_RUNNING
) {
4966 EXPORT_SYMBOL(_cond_resched
);
4970 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4971 * call schedule, and on return reacquire the lock.
4973 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4974 * operations here to prevent schedule() from being called twice (once via
4975 * spin_unlock(), once by hand).
4977 int cond_resched_lock(spinlock_t
*lock
)
4979 int resched
= need_resched() && system_state
== SYSTEM_RUNNING
;
4982 if (spin_needbreak(lock
) || resched
) {
4984 if (resched
&& need_resched())
4993 EXPORT_SYMBOL(cond_resched_lock
);
4995 int __sched
cond_resched_softirq(void)
4997 BUG_ON(!in_softirq());
4999 if (need_resched() && system_state
== SYSTEM_RUNNING
) {
5007 EXPORT_SYMBOL(cond_resched_softirq
);
5010 * yield - yield the current processor to other threads.
5012 * This is a shortcut for kernel-space yielding - it marks the
5013 * thread runnable and calls sys_sched_yield().
5015 void __sched
yield(void)
5017 set_current_state(TASK_RUNNING
);
5020 EXPORT_SYMBOL(yield
);
5023 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5024 * that process accounting knows that this is a task in IO wait state.
5026 * But don't do that if it is a deliberate, throttling IO wait (this task
5027 * has set its backing_dev_info: the queue against which it should throttle)
5029 void __sched
io_schedule(void)
5031 struct rq
*rq
= &__raw_get_cpu_var(runqueues
);
5033 delayacct_blkio_start();
5034 atomic_inc(&rq
->nr_iowait
);
5036 atomic_dec(&rq
->nr_iowait
);
5037 delayacct_blkio_end();
5039 EXPORT_SYMBOL(io_schedule
);
5041 long __sched
io_schedule_timeout(long timeout
)
5043 struct rq
*rq
= &__raw_get_cpu_var(runqueues
);
5046 delayacct_blkio_start();
5047 atomic_inc(&rq
->nr_iowait
);
5048 ret
= schedule_timeout(timeout
);
5049 atomic_dec(&rq
->nr_iowait
);
5050 delayacct_blkio_end();
5055 * sys_sched_get_priority_max - return maximum RT priority.
5056 * @policy: scheduling class.
5058 * this syscall returns the maximum rt_priority that can be used
5059 * by a given scheduling class.
5061 asmlinkage
long sys_sched_get_priority_max(int policy
)
5068 ret
= MAX_USER_RT_PRIO
-1;
5080 * sys_sched_get_priority_min - return minimum RT priority.
5081 * @policy: scheduling class.
5083 * this syscall returns the minimum rt_priority that can be used
5084 * by a given scheduling class.
5086 asmlinkage
long sys_sched_get_priority_min(int policy
)
5104 * sys_sched_rr_get_interval - return the default timeslice of a process.
5105 * @pid: pid of the process.
5106 * @interval: userspace pointer to the timeslice value.
5108 * this syscall writes the default timeslice value of a given process
5109 * into the user-space timespec buffer. A value of '0' means infinity.
5112 long sys_sched_rr_get_interval(pid_t pid
, struct timespec __user
*interval
)
5114 struct task_struct
*p
;
5115 unsigned int time_slice
;
5123 read_lock(&tasklist_lock
);
5124 p
= find_process_by_pid(pid
);
5128 retval
= security_task_getscheduler(p
);
5133 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5134 * tasks that are on an otherwise idle runqueue:
5137 if (p
->policy
== SCHED_RR
) {
5138 time_slice
= DEF_TIMESLICE
;
5140 struct sched_entity
*se
= &p
->se
;
5141 unsigned long flags
;
5144 rq
= task_rq_lock(p
, &flags
);
5145 if (rq
->cfs
.load
.weight
)
5146 time_slice
= NS_TO_JIFFIES(sched_slice(&rq
->cfs
, se
));
5147 task_rq_unlock(rq
, &flags
);
5149 read_unlock(&tasklist_lock
);
5150 jiffies_to_timespec(time_slice
, &t
);
5151 retval
= copy_to_user(interval
, &t
, sizeof(t
)) ? -EFAULT
: 0;
5155 read_unlock(&tasklist_lock
);
5159 static const char stat_nam
[] = "RSDTtZX";
5161 void sched_show_task(struct task_struct
*p
)
5163 unsigned long free
= 0;
5166 state
= p
->state
? __ffs(p
->state
) + 1 : 0;
5167 printk(KERN_INFO
"%-13.13s %c", p
->comm
,
5168 state
< sizeof(stat_nam
) - 1 ? stat_nam
[state
] : '?');
5169 #if BITS_PER_LONG == 32
5170 if (state
== TASK_RUNNING
)
5171 printk(KERN_CONT
" running ");
5173 printk(KERN_CONT
" %08lx ", thread_saved_pc(p
));
5175 if (state
== TASK_RUNNING
)
5176 printk(KERN_CONT
" running task ");
5178 printk(KERN_CONT
" %016lx ", thread_saved_pc(p
));
5180 #ifdef CONFIG_DEBUG_STACK_USAGE
5182 unsigned long *n
= end_of_stack(p
);
5185 free
= (unsigned long)n
- (unsigned long)end_of_stack(p
);
5188 printk(KERN_CONT
"%5lu %5d %6d\n", free
,
5189 task_pid_nr(p
), task_pid_nr(p
->real_parent
));
5191 show_stack(p
, NULL
);
5194 void show_state_filter(unsigned long state_filter
)
5196 struct task_struct
*g
, *p
;
5198 #if BITS_PER_LONG == 32
5200 " task PC stack pid father\n");
5203 " task PC stack pid father\n");
5205 read_lock(&tasklist_lock
);
5206 do_each_thread(g
, p
) {
5208 * reset the NMI-timeout, listing all files on a slow
5209 * console might take alot of time:
5211 touch_nmi_watchdog();
5212 if (!state_filter
|| (p
->state
& state_filter
))
5214 } while_each_thread(g
, p
);
5216 touch_all_softlockup_watchdogs();
5218 #ifdef CONFIG_SCHED_DEBUG
5219 sysrq_sched_debug_show();
5221 read_unlock(&tasklist_lock
);
5223 * Only show locks if all tasks are dumped:
5225 if (state_filter
== -1)
5226 debug_show_all_locks();
5229 void __cpuinit
init_idle_bootup_task(struct task_struct
*idle
)
5231 idle
->sched_class
= &idle_sched_class
;
5235 * init_idle - set up an idle thread for a given CPU
5236 * @idle: task in question
5237 * @cpu: cpu the idle task belongs to
5239 * NOTE: this function does not set the idle thread's NEED_RESCHED
5240 * flag, to make booting more robust.
5242 void __cpuinit
init_idle(struct task_struct
*idle
, int cpu
)
5244 struct rq
*rq
= cpu_rq(cpu
);
5245 unsigned long flags
;
5248 idle
->se
.exec_start
= sched_clock();
5250 idle
->prio
= idle
->normal_prio
= MAX_PRIO
;
5251 idle
->cpus_allowed
= cpumask_of_cpu(cpu
);
5252 __set_task_cpu(idle
, cpu
);
5254 spin_lock_irqsave(&rq
->lock
, flags
);
5255 rq
->curr
= rq
->idle
= idle
;
5256 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5259 spin_unlock_irqrestore(&rq
->lock
, flags
);
5261 /* Set the preempt count _outside_ the spinlocks! */
5262 task_thread_info(idle
)->preempt_count
= 0;
5265 * The idle tasks have their own, simple scheduling class:
5267 idle
->sched_class
= &idle_sched_class
;
5271 * In a system that switches off the HZ timer nohz_cpu_mask
5272 * indicates which cpus entered this state. This is used
5273 * in the rcu update to wait only for active cpus. For system
5274 * which do not switch off the HZ timer nohz_cpu_mask should
5275 * always be CPU_MASK_NONE.
5277 cpumask_t nohz_cpu_mask
= CPU_MASK_NONE
;
5280 * Increase the granularity value when there are more CPUs,
5281 * because with more CPUs the 'effective latency' as visible
5282 * to users decreases. But the relationship is not linear,
5283 * so pick a second-best guess by going with the log2 of the
5286 * This idea comes from the SD scheduler of Con Kolivas:
5288 static inline void sched_init_granularity(void)
5290 unsigned int factor
= 1 + ilog2(num_online_cpus());
5291 const unsigned long limit
= 200000000;
5293 sysctl_sched_min_granularity
*= factor
;
5294 if (sysctl_sched_min_granularity
> limit
)
5295 sysctl_sched_min_granularity
= limit
;
5297 sysctl_sched_latency
*= factor
;
5298 if (sysctl_sched_latency
> limit
)
5299 sysctl_sched_latency
= limit
;
5301 sysctl_sched_wakeup_granularity
*= factor
;
5302 sysctl_sched_batch_wakeup_granularity
*= factor
;
5307 * This is how migration works:
5309 * 1) we queue a struct migration_req structure in the source CPU's
5310 * runqueue and wake up that CPU's migration thread.
5311 * 2) we down() the locked semaphore => thread blocks.
5312 * 3) migration thread wakes up (implicitly it forces the migrated
5313 * thread off the CPU)
5314 * 4) it gets the migration request and checks whether the migrated
5315 * task is still in the wrong runqueue.
5316 * 5) if it's in the wrong runqueue then the migration thread removes
5317 * it and puts it into the right queue.
5318 * 6) migration thread up()s the semaphore.
5319 * 7) we wake up and the migration is done.
5323 * Change a given task's CPU affinity. Migrate the thread to a
5324 * proper CPU and schedule it away if the CPU it's executing on
5325 * is removed from the allowed bitmask.
5327 * NOTE: the caller must have a valid reference to the task, the
5328 * task must not exit() & deallocate itself prematurely. The
5329 * call is not atomic; no spinlocks may be held.
5331 int set_cpus_allowed(struct task_struct
*p
, cpumask_t new_mask
)
5333 struct migration_req req
;
5334 unsigned long flags
;
5338 rq
= task_rq_lock(p
, &flags
);
5339 if (!cpus_intersects(new_mask
, cpu_online_map
)) {
5344 if (p
->sched_class
->set_cpus_allowed
)
5345 p
->sched_class
->set_cpus_allowed(p
, &new_mask
);
5347 p
->cpus_allowed
= new_mask
;
5348 p
->rt
.nr_cpus_allowed
= cpus_weight(new_mask
);
5351 /* Can the task run on the task's current CPU? If so, we're done */
5352 if (cpu_isset(task_cpu(p
), new_mask
))
5355 if (migrate_task(p
, any_online_cpu(new_mask
), &req
)) {
5356 /* Need help from migration thread: drop lock and wait. */
5357 task_rq_unlock(rq
, &flags
);
5358 wake_up_process(rq
->migration_thread
);
5359 wait_for_completion(&req
.done
);
5360 tlb_migrate_finish(p
->mm
);
5364 task_rq_unlock(rq
, &flags
);
5368 EXPORT_SYMBOL_GPL(set_cpus_allowed
);
5371 * Move (not current) task off this cpu, onto dest cpu. We're doing
5372 * this because either it can't run here any more (set_cpus_allowed()
5373 * away from this CPU, or CPU going down), or because we're
5374 * attempting to rebalance this task on exec (sched_exec).
5376 * So we race with normal scheduler movements, but that's OK, as long
5377 * as the task is no longer on this CPU.
5379 * Returns non-zero if task was successfully migrated.
5381 static int __migrate_task(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
5383 struct rq
*rq_dest
, *rq_src
;
5386 if (unlikely(cpu_is_offline(dest_cpu
)))
5389 rq_src
= cpu_rq(src_cpu
);
5390 rq_dest
= cpu_rq(dest_cpu
);
5392 double_rq_lock(rq_src
, rq_dest
);
5393 /* Already moved. */
5394 if (task_cpu(p
) != src_cpu
)
5396 /* Affinity changed (again). */
5397 if (!cpu_isset(dest_cpu
, p
->cpus_allowed
))
5400 on_rq
= p
->se
.on_rq
;
5402 deactivate_task(rq_src
, p
, 0);
5404 set_task_cpu(p
, dest_cpu
);
5406 activate_task(rq_dest
, p
, 0);
5407 check_preempt_curr(rq_dest
, p
);
5411 double_rq_unlock(rq_src
, rq_dest
);
5416 * migration_thread - this is a highprio system thread that performs
5417 * thread migration by bumping thread off CPU then 'pushing' onto
5420 static int migration_thread(void *data
)
5422 int cpu
= (long)data
;
5426 BUG_ON(rq
->migration_thread
!= current
);
5428 set_current_state(TASK_INTERRUPTIBLE
);
5429 while (!kthread_should_stop()) {
5430 struct migration_req
*req
;
5431 struct list_head
*head
;
5433 spin_lock_irq(&rq
->lock
);
5435 if (cpu_is_offline(cpu
)) {
5436 spin_unlock_irq(&rq
->lock
);
5440 if (rq
->active_balance
) {
5441 active_load_balance(rq
, cpu
);
5442 rq
->active_balance
= 0;
5445 head
= &rq
->migration_queue
;
5447 if (list_empty(head
)) {
5448 spin_unlock_irq(&rq
->lock
);
5450 set_current_state(TASK_INTERRUPTIBLE
);
5453 req
= list_entry(head
->next
, struct migration_req
, list
);
5454 list_del_init(head
->next
);
5456 spin_unlock(&rq
->lock
);
5457 __migrate_task(req
->task
, cpu
, req
->dest_cpu
);
5460 complete(&req
->done
);
5462 __set_current_state(TASK_RUNNING
);
5466 /* Wait for kthread_stop */
5467 set_current_state(TASK_INTERRUPTIBLE
);
5468 while (!kthread_should_stop()) {
5470 set_current_state(TASK_INTERRUPTIBLE
);
5472 __set_current_state(TASK_RUNNING
);
5476 #ifdef CONFIG_HOTPLUG_CPU
5478 static int __migrate_task_irq(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
5482 local_irq_disable();
5483 ret
= __migrate_task(p
, src_cpu
, dest_cpu
);
5489 * Figure out where task on dead CPU should go, use force if necessary.
5490 * NOTE: interrupts should be disabled by the caller
5492 static void move_task_off_dead_cpu(int dead_cpu
, struct task_struct
*p
)
5494 unsigned long flags
;
5501 mask
= node_to_cpumask(cpu_to_node(dead_cpu
));
5502 cpus_and(mask
, mask
, p
->cpus_allowed
);
5503 dest_cpu
= any_online_cpu(mask
);
5505 /* On any allowed CPU? */
5506 if (dest_cpu
== NR_CPUS
)
5507 dest_cpu
= any_online_cpu(p
->cpus_allowed
);
5509 /* No more Mr. Nice Guy. */
5510 if (dest_cpu
== NR_CPUS
) {
5511 cpumask_t cpus_allowed
= cpuset_cpus_allowed_locked(p
);
5513 * Try to stay on the same cpuset, where the
5514 * current cpuset may be a subset of all cpus.
5515 * The cpuset_cpus_allowed_locked() variant of
5516 * cpuset_cpus_allowed() will not block. It must be
5517 * called within calls to cpuset_lock/cpuset_unlock.
5519 rq
= task_rq_lock(p
, &flags
);
5520 p
->cpus_allowed
= cpus_allowed
;
5521 dest_cpu
= any_online_cpu(p
->cpus_allowed
);
5522 task_rq_unlock(rq
, &flags
);
5525 * Don't tell them about moving exiting tasks or
5526 * kernel threads (both mm NULL), since they never
5529 if (p
->mm
&& printk_ratelimit()) {
5530 printk(KERN_INFO
"process %d (%s) no "
5531 "longer affine to cpu%d\n",
5532 task_pid_nr(p
), p
->comm
, dead_cpu
);
5535 } while (!__migrate_task_irq(p
, dead_cpu
, dest_cpu
));
5539 * While a dead CPU has no uninterruptible tasks queued at this point,
5540 * it might still have a nonzero ->nr_uninterruptible counter, because
5541 * for performance reasons the counter is not stricly tracking tasks to
5542 * their home CPUs. So we just add the counter to another CPU's counter,
5543 * to keep the global sum constant after CPU-down:
5545 static void migrate_nr_uninterruptible(struct rq
*rq_src
)
5547 struct rq
*rq_dest
= cpu_rq(any_online_cpu(CPU_MASK_ALL
));
5548 unsigned long flags
;
5550 local_irq_save(flags
);
5551 double_rq_lock(rq_src
, rq_dest
);
5552 rq_dest
->nr_uninterruptible
+= rq_src
->nr_uninterruptible
;
5553 rq_src
->nr_uninterruptible
= 0;
5554 double_rq_unlock(rq_src
, rq_dest
);
5555 local_irq_restore(flags
);
5558 /* Run through task list and migrate tasks from the dead cpu. */
5559 static void migrate_live_tasks(int src_cpu
)
5561 struct task_struct
*p
, *t
;
5563 read_lock(&tasklist_lock
);
5565 do_each_thread(t
, p
) {
5569 if (task_cpu(p
) == src_cpu
)
5570 move_task_off_dead_cpu(src_cpu
, p
);
5571 } while_each_thread(t
, p
);
5573 read_unlock(&tasklist_lock
);
5577 * Schedules idle task to be the next runnable task on current CPU.
5578 * It does so by boosting its priority to highest possible.
5579 * Used by CPU offline code.
5581 void sched_idle_next(void)
5583 int this_cpu
= smp_processor_id();
5584 struct rq
*rq
= cpu_rq(this_cpu
);
5585 struct task_struct
*p
= rq
->idle
;
5586 unsigned long flags
;
5588 /* cpu has to be offline */
5589 BUG_ON(cpu_online(this_cpu
));
5592 * Strictly not necessary since rest of the CPUs are stopped by now
5593 * and interrupts disabled on the current cpu.
5595 spin_lock_irqsave(&rq
->lock
, flags
);
5597 __setscheduler(rq
, p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
5599 update_rq_clock(rq
);
5600 activate_task(rq
, p
, 0);
5602 spin_unlock_irqrestore(&rq
->lock
, flags
);
5606 * Ensures that the idle task is using init_mm right before its cpu goes
5609 void idle_task_exit(void)
5611 struct mm_struct
*mm
= current
->active_mm
;
5613 BUG_ON(cpu_online(smp_processor_id()));
5616 switch_mm(mm
, &init_mm
, current
);
5620 /* called under rq->lock with disabled interrupts */
5621 static void migrate_dead(unsigned int dead_cpu
, struct task_struct
*p
)
5623 struct rq
*rq
= cpu_rq(dead_cpu
);
5625 /* Must be exiting, otherwise would be on tasklist. */
5626 BUG_ON(!p
->exit_state
);
5628 /* Cannot have done final schedule yet: would have vanished. */
5629 BUG_ON(p
->state
== TASK_DEAD
);
5634 * Drop lock around migration; if someone else moves it,
5635 * that's OK. No task can be added to this CPU, so iteration is
5638 spin_unlock_irq(&rq
->lock
);
5639 move_task_off_dead_cpu(dead_cpu
, p
);
5640 spin_lock_irq(&rq
->lock
);
5645 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5646 static void migrate_dead_tasks(unsigned int dead_cpu
)
5648 struct rq
*rq
= cpu_rq(dead_cpu
);
5649 struct task_struct
*next
;
5652 if (!rq
->nr_running
)
5654 update_rq_clock(rq
);
5655 next
= pick_next_task(rq
, rq
->curr
);
5658 migrate_dead(dead_cpu
, next
);
5662 #endif /* CONFIG_HOTPLUG_CPU */
5664 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5666 static struct ctl_table sd_ctl_dir
[] = {
5668 .procname
= "sched_domain",
5674 static struct ctl_table sd_ctl_root
[] = {
5676 .ctl_name
= CTL_KERN
,
5677 .procname
= "kernel",
5679 .child
= sd_ctl_dir
,
5684 static struct ctl_table
*sd_alloc_ctl_entry(int n
)
5686 struct ctl_table
*entry
=
5687 kcalloc(n
, sizeof(struct ctl_table
), GFP_KERNEL
);
5692 static void sd_free_ctl_entry(struct ctl_table
**tablep
)
5694 struct ctl_table
*entry
;
5697 * In the intermediate directories, both the child directory and
5698 * procname are dynamically allocated and could fail but the mode
5699 * will always be set. In the lowest directory the names are
5700 * static strings and all have proc handlers.
5702 for (entry
= *tablep
; entry
->mode
; entry
++) {
5704 sd_free_ctl_entry(&entry
->child
);
5705 if (entry
->proc_handler
== NULL
)
5706 kfree(entry
->procname
);
5714 set_table_entry(struct ctl_table
*entry
,
5715 const char *procname
, void *data
, int maxlen
,
5716 mode_t mode
, proc_handler
*proc_handler
)
5718 entry
->procname
= procname
;
5720 entry
->maxlen
= maxlen
;
5722 entry
->proc_handler
= proc_handler
;
5725 static struct ctl_table
*
5726 sd_alloc_ctl_domain_table(struct sched_domain
*sd
)
5728 struct ctl_table
*table
= sd_alloc_ctl_entry(12);
5733 set_table_entry(&table
[0], "min_interval", &sd
->min_interval
,
5734 sizeof(long), 0644, proc_doulongvec_minmax
);
5735 set_table_entry(&table
[1], "max_interval", &sd
->max_interval
,
5736 sizeof(long), 0644, proc_doulongvec_minmax
);
5737 set_table_entry(&table
[2], "busy_idx", &sd
->busy_idx
,
5738 sizeof(int), 0644, proc_dointvec_minmax
);
5739 set_table_entry(&table
[3], "idle_idx", &sd
->idle_idx
,
5740 sizeof(int), 0644, proc_dointvec_minmax
);
5741 set_table_entry(&table
[4], "newidle_idx", &sd
->newidle_idx
,
5742 sizeof(int), 0644, proc_dointvec_minmax
);
5743 set_table_entry(&table
[5], "wake_idx", &sd
->wake_idx
,
5744 sizeof(int), 0644, proc_dointvec_minmax
);
5745 set_table_entry(&table
[6], "forkexec_idx", &sd
->forkexec_idx
,
5746 sizeof(int), 0644, proc_dointvec_minmax
);
5747 set_table_entry(&table
[7], "busy_factor", &sd
->busy_factor
,
5748 sizeof(int), 0644, proc_dointvec_minmax
);
5749 set_table_entry(&table
[8], "imbalance_pct", &sd
->imbalance_pct
,
5750 sizeof(int), 0644, proc_dointvec_minmax
);
5751 set_table_entry(&table
[9], "cache_nice_tries",
5752 &sd
->cache_nice_tries
,
5753 sizeof(int), 0644, proc_dointvec_minmax
);
5754 set_table_entry(&table
[10], "flags", &sd
->flags
,
5755 sizeof(int), 0644, proc_dointvec_minmax
);
5756 /* &table[11] is terminator */
5761 static ctl_table
*sd_alloc_ctl_cpu_table(int cpu
)
5763 struct ctl_table
*entry
, *table
;
5764 struct sched_domain
*sd
;
5765 int domain_num
= 0, i
;
5768 for_each_domain(cpu
, sd
)
5770 entry
= table
= sd_alloc_ctl_entry(domain_num
+ 1);
5775 for_each_domain(cpu
, sd
) {
5776 snprintf(buf
, 32, "domain%d", i
);
5777 entry
->procname
= kstrdup(buf
, GFP_KERNEL
);
5779 entry
->child
= sd_alloc_ctl_domain_table(sd
);
5786 static struct ctl_table_header
*sd_sysctl_header
;
5787 static void register_sched_domain_sysctl(void)
5789 int i
, cpu_num
= num_online_cpus();
5790 struct ctl_table
*entry
= sd_alloc_ctl_entry(cpu_num
+ 1);
5793 WARN_ON(sd_ctl_dir
[0].child
);
5794 sd_ctl_dir
[0].child
= entry
;
5799 for_each_online_cpu(i
) {
5800 snprintf(buf
, 32, "cpu%d", i
);
5801 entry
->procname
= kstrdup(buf
, GFP_KERNEL
);
5803 entry
->child
= sd_alloc_ctl_cpu_table(i
);
5807 WARN_ON(sd_sysctl_header
);
5808 sd_sysctl_header
= register_sysctl_table(sd_ctl_root
);
5811 /* may be called multiple times per register */
5812 static void unregister_sched_domain_sysctl(void)
5814 if (sd_sysctl_header
)
5815 unregister_sysctl_table(sd_sysctl_header
);
5816 sd_sysctl_header
= NULL
;
5817 if (sd_ctl_dir
[0].child
)
5818 sd_free_ctl_entry(&sd_ctl_dir
[0].child
);
5821 static void register_sched_domain_sysctl(void)
5824 static void unregister_sched_domain_sysctl(void)
5830 * migration_call - callback that gets triggered when a CPU is added.
5831 * Here we can start up the necessary migration thread for the new CPU.
5833 static int __cpuinit
5834 migration_call(struct notifier_block
*nfb
, unsigned long action
, void *hcpu
)
5836 struct task_struct
*p
;
5837 int cpu
= (long)hcpu
;
5838 unsigned long flags
;
5843 case CPU_UP_PREPARE
:
5844 case CPU_UP_PREPARE_FROZEN
:
5845 p
= kthread_create(migration_thread
, hcpu
, "migration/%d", cpu
);
5848 kthread_bind(p
, cpu
);
5849 /* Must be high prio: stop_machine expects to yield to it. */
5850 rq
= task_rq_lock(p
, &flags
);
5851 __setscheduler(rq
, p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
5852 task_rq_unlock(rq
, &flags
);
5853 cpu_rq(cpu
)->migration_thread
= p
;
5857 case CPU_ONLINE_FROZEN
:
5858 /* Strictly unnecessary, as first user will wake it. */
5859 wake_up_process(cpu_rq(cpu
)->migration_thread
);
5861 /* Update our root-domain */
5863 spin_lock_irqsave(&rq
->lock
, flags
);
5865 BUG_ON(!cpu_isset(cpu
, rq
->rd
->span
));
5866 cpu_set(cpu
, rq
->rd
->online
);
5868 spin_unlock_irqrestore(&rq
->lock
, flags
);
5871 #ifdef CONFIG_HOTPLUG_CPU
5872 case CPU_UP_CANCELED
:
5873 case CPU_UP_CANCELED_FROZEN
:
5874 if (!cpu_rq(cpu
)->migration_thread
)
5876 /* Unbind it from offline cpu so it can run. Fall thru. */
5877 kthread_bind(cpu_rq(cpu
)->migration_thread
,
5878 any_online_cpu(cpu_online_map
));
5879 kthread_stop(cpu_rq(cpu
)->migration_thread
);
5880 cpu_rq(cpu
)->migration_thread
= NULL
;
5884 case CPU_DEAD_FROZEN
:
5885 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
5886 migrate_live_tasks(cpu
);
5888 kthread_stop(rq
->migration_thread
);
5889 rq
->migration_thread
= NULL
;
5890 /* Idle task back to normal (off runqueue, low prio) */
5891 spin_lock_irq(&rq
->lock
);
5892 update_rq_clock(rq
);
5893 deactivate_task(rq
, rq
->idle
, 0);
5894 rq
->idle
->static_prio
= MAX_PRIO
;
5895 __setscheduler(rq
, rq
->idle
, SCHED_NORMAL
, 0);
5896 rq
->idle
->sched_class
= &idle_sched_class
;
5897 migrate_dead_tasks(cpu
);
5898 spin_unlock_irq(&rq
->lock
);
5900 migrate_nr_uninterruptible(rq
);
5901 BUG_ON(rq
->nr_running
!= 0);
5904 * No need to migrate the tasks: it was best-effort if
5905 * they didn't take sched_hotcpu_mutex. Just wake up
5908 spin_lock_irq(&rq
->lock
);
5909 while (!list_empty(&rq
->migration_queue
)) {
5910 struct migration_req
*req
;
5912 req
= list_entry(rq
->migration_queue
.next
,
5913 struct migration_req
, list
);
5914 list_del_init(&req
->list
);
5915 complete(&req
->done
);
5917 spin_unlock_irq(&rq
->lock
);
5920 case CPU_DOWN_PREPARE
:
5921 /* Update our root-domain */
5923 spin_lock_irqsave(&rq
->lock
, flags
);
5925 BUG_ON(!cpu_isset(cpu
, rq
->rd
->span
));
5926 cpu_clear(cpu
, rq
->rd
->online
);
5928 spin_unlock_irqrestore(&rq
->lock
, flags
);
5935 /* Register at highest priority so that task migration (migrate_all_tasks)
5936 * happens before everything else.
5938 static struct notifier_block __cpuinitdata migration_notifier
= {
5939 .notifier_call
= migration_call
,
5943 void __init
migration_init(void)
5945 void *cpu
= (void *)(long)smp_processor_id();
5948 /* Start one for the boot CPU: */
5949 err
= migration_call(&migration_notifier
, CPU_UP_PREPARE
, cpu
);
5950 BUG_ON(err
== NOTIFY_BAD
);
5951 migration_call(&migration_notifier
, CPU_ONLINE
, cpu
);
5952 register_cpu_notifier(&migration_notifier
);
5958 /* Number of possible processor ids */
5959 int nr_cpu_ids __read_mostly
= NR_CPUS
;
5960 EXPORT_SYMBOL(nr_cpu_ids
);
5962 #ifdef CONFIG_SCHED_DEBUG
5964 static int sched_domain_debug_one(struct sched_domain
*sd
, int cpu
, int level
)
5966 struct sched_group
*group
= sd
->groups
;
5967 cpumask_t groupmask
;
5970 cpumask_scnprintf(str
, NR_CPUS
, sd
->span
);
5971 cpus_clear(groupmask
);
5973 printk(KERN_DEBUG
"%*s domain %d: ", level
, "", level
);
5975 if (!(sd
->flags
& SD_LOAD_BALANCE
)) {
5976 printk("does not load-balance\n");
5978 printk(KERN_ERR
"ERROR: !SD_LOAD_BALANCE domain"
5983 printk(KERN_CONT
"span %s\n", str
);
5985 if (!cpu_isset(cpu
, sd
->span
)) {
5986 printk(KERN_ERR
"ERROR: domain->span does not contain "
5989 if (!cpu_isset(cpu
, group
->cpumask
)) {
5990 printk(KERN_ERR
"ERROR: domain->groups does not contain"
5994 printk(KERN_DEBUG
"%*s groups:", level
+ 1, "");
5998 printk(KERN_ERR
"ERROR: group is NULL\n");
6002 if (!group
->__cpu_power
) {
6003 printk(KERN_CONT
"\n");
6004 printk(KERN_ERR
"ERROR: domain->cpu_power not "
6009 if (!cpus_weight(group
->cpumask
)) {
6010 printk(KERN_CONT
"\n");
6011 printk(KERN_ERR
"ERROR: empty group\n");
6015 if (cpus_intersects(groupmask
, group
->cpumask
)) {
6016 printk(KERN_CONT
"\n");
6017 printk(KERN_ERR
"ERROR: repeated CPUs\n");
6021 cpus_or(groupmask
, groupmask
, group
->cpumask
);
6023 cpumask_scnprintf(str
, NR_CPUS
, group
->cpumask
);
6024 printk(KERN_CONT
" %s", str
);
6026 group
= group
->next
;
6027 } while (group
!= sd
->groups
);
6028 printk(KERN_CONT
"\n");
6030 if (!cpus_equal(sd
->span
, groupmask
))
6031 printk(KERN_ERR
"ERROR: groups don't span domain->span\n");
6033 if (sd
->parent
&& !cpus_subset(groupmask
, sd
->parent
->span
))
6034 printk(KERN_ERR
"ERROR: parent span is not a superset "
6035 "of domain->span\n");
6039 static void sched_domain_debug(struct sched_domain
*sd
, int cpu
)
6044 printk(KERN_DEBUG
"CPU%d attaching NULL sched-domain.\n", cpu
);
6048 printk(KERN_DEBUG
"CPU%d attaching sched-domain:\n", cpu
);
6051 if (sched_domain_debug_one(sd
, cpu
, level
))
6060 # define sched_domain_debug(sd, cpu) do { } while (0)
6063 static int sd_degenerate(struct sched_domain
*sd
)
6065 if (cpus_weight(sd
->span
) == 1)
6068 /* Following flags need at least 2 groups */
6069 if (sd
->flags
& (SD_LOAD_BALANCE
|
6070 SD_BALANCE_NEWIDLE
|
6074 SD_SHARE_PKG_RESOURCES
)) {
6075 if (sd
->groups
!= sd
->groups
->next
)
6079 /* Following flags don't use groups */
6080 if (sd
->flags
& (SD_WAKE_IDLE
|
6089 sd_parent_degenerate(struct sched_domain
*sd
, struct sched_domain
*parent
)
6091 unsigned long cflags
= sd
->flags
, pflags
= parent
->flags
;
6093 if (sd_degenerate(parent
))
6096 if (!cpus_equal(sd
->span
, parent
->span
))
6099 /* Does parent contain flags not in child? */
6100 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6101 if (cflags
& SD_WAKE_AFFINE
)
6102 pflags
&= ~SD_WAKE_BALANCE
;
6103 /* Flags needing groups don't count if only 1 group in parent */
6104 if (parent
->groups
== parent
->groups
->next
) {
6105 pflags
&= ~(SD_LOAD_BALANCE
|
6106 SD_BALANCE_NEWIDLE
|
6110 SD_SHARE_PKG_RESOURCES
);
6112 if (~cflags
& pflags
)
6118 static void rq_attach_root(struct rq
*rq
, struct root_domain
*rd
)
6120 unsigned long flags
;
6121 const struct sched_class
*class;
6123 spin_lock_irqsave(&rq
->lock
, flags
);
6126 struct root_domain
*old_rd
= rq
->rd
;
6128 for (class = sched_class_highest
; class; class = class->next
) {
6129 if (class->leave_domain
)
6130 class->leave_domain(rq
);
6133 cpu_clear(rq
->cpu
, old_rd
->span
);
6134 cpu_clear(rq
->cpu
, old_rd
->online
);
6136 if (atomic_dec_and_test(&old_rd
->refcount
))
6140 atomic_inc(&rd
->refcount
);
6143 cpu_set(rq
->cpu
, rd
->span
);
6144 if (cpu_isset(rq
->cpu
, cpu_online_map
))
6145 cpu_set(rq
->cpu
, rd
->online
);
6147 for (class = sched_class_highest
; class; class = class->next
) {
6148 if (class->join_domain
)
6149 class->join_domain(rq
);
6152 spin_unlock_irqrestore(&rq
->lock
, flags
);
6155 static void init_rootdomain(struct root_domain
*rd
)
6157 memset(rd
, 0, sizeof(*rd
));
6159 cpus_clear(rd
->span
);
6160 cpus_clear(rd
->online
);
6163 static void init_defrootdomain(void)
6165 init_rootdomain(&def_root_domain
);
6166 atomic_set(&def_root_domain
.refcount
, 1);
6169 static struct root_domain
*alloc_rootdomain(void)
6171 struct root_domain
*rd
;
6173 rd
= kmalloc(sizeof(*rd
), GFP_KERNEL
);
6177 init_rootdomain(rd
);
6183 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6184 * hold the hotplug lock.
6187 cpu_attach_domain(struct sched_domain
*sd
, struct root_domain
*rd
, int cpu
)
6189 struct rq
*rq
= cpu_rq(cpu
);
6190 struct sched_domain
*tmp
;
6192 /* Remove the sched domains which do not contribute to scheduling. */
6193 for (tmp
= sd
; tmp
; tmp
= tmp
->parent
) {
6194 struct sched_domain
*parent
= tmp
->parent
;
6197 if (sd_parent_degenerate(tmp
, parent
)) {
6198 tmp
->parent
= parent
->parent
;
6200 parent
->parent
->child
= tmp
;
6204 if (sd
&& sd_degenerate(sd
)) {
6210 sched_domain_debug(sd
, cpu
);
6212 rq_attach_root(rq
, rd
);
6213 rcu_assign_pointer(rq
->sd
, sd
);
6216 /* cpus with isolated domains */
6217 static cpumask_t cpu_isolated_map
= CPU_MASK_NONE
;
6219 /* Setup the mask of cpus configured for isolated domains */
6220 static int __init
isolated_cpu_setup(char *str
)
6222 int ints
[NR_CPUS
], i
;
6224 str
= get_options(str
, ARRAY_SIZE(ints
), ints
);
6225 cpus_clear(cpu_isolated_map
);
6226 for (i
= 1; i
<= ints
[0]; i
++)
6227 if (ints
[i
] < NR_CPUS
)
6228 cpu_set(ints
[i
], cpu_isolated_map
);
6232 __setup("isolcpus=", isolated_cpu_setup
);
6235 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6236 * to a function which identifies what group(along with sched group) a CPU
6237 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6238 * (due to the fact that we keep track of groups covered with a cpumask_t).
6240 * init_sched_build_groups will build a circular linked list of the groups
6241 * covered by the given span, and will set each group's ->cpumask correctly,
6242 * and ->cpu_power to 0.
6245 init_sched_build_groups(cpumask_t span
, const cpumask_t
*cpu_map
,
6246 int (*group_fn
)(int cpu
, const cpumask_t
*cpu_map
,
6247 struct sched_group
**sg
))
6249 struct sched_group
*first
= NULL
, *last
= NULL
;
6250 cpumask_t covered
= CPU_MASK_NONE
;
6253 for_each_cpu_mask(i
, span
) {
6254 struct sched_group
*sg
;
6255 int group
= group_fn(i
, cpu_map
, &sg
);
6258 if (cpu_isset(i
, covered
))
6261 sg
->cpumask
= CPU_MASK_NONE
;
6262 sg
->__cpu_power
= 0;
6264 for_each_cpu_mask(j
, span
) {
6265 if (group_fn(j
, cpu_map
, NULL
) != group
)
6268 cpu_set(j
, covered
);
6269 cpu_set(j
, sg
->cpumask
);
6280 #define SD_NODES_PER_DOMAIN 16
6285 * find_next_best_node - find the next node to include in a sched_domain
6286 * @node: node whose sched_domain we're building
6287 * @used_nodes: nodes already in the sched_domain
6289 * Find the next node to include in a given scheduling domain. Simply
6290 * finds the closest node not already in the @used_nodes map.
6292 * Should use nodemask_t.
6294 static int find_next_best_node(int node
, unsigned long *used_nodes
)
6296 int i
, n
, val
, min_val
, best_node
= 0;
6300 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6301 /* Start at @node */
6302 n
= (node
+ i
) % MAX_NUMNODES
;
6304 if (!nr_cpus_node(n
))
6307 /* Skip already used nodes */
6308 if (test_bit(n
, used_nodes
))
6311 /* Simple min distance search */
6312 val
= node_distance(node
, n
);
6314 if (val
< min_val
) {
6320 set_bit(best_node
, used_nodes
);
6325 * sched_domain_node_span - get a cpumask for a node's sched_domain
6326 * @node: node whose cpumask we're constructing
6327 * @size: number of nodes to include in this span
6329 * Given a node, construct a good cpumask for its sched_domain to span. It
6330 * should be one that prevents unnecessary balancing, but also spreads tasks
6333 static cpumask_t
sched_domain_node_span(int node
)
6335 DECLARE_BITMAP(used_nodes
, MAX_NUMNODES
);
6336 cpumask_t span
, nodemask
;
6340 bitmap_zero(used_nodes
, MAX_NUMNODES
);
6342 nodemask
= node_to_cpumask(node
);
6343 cpus_or(span
, span
, nodemask
);
6344 set_bit(node
, used_nodes
);
6346 for (i
= 1; i
< SD_NODES_PER_DOMAIN
; i
++) {
6347 int next_node
= find_next_best_node(node
, used_nodes
);
6349 nodemask
= node_to_cpumask(next_node
);
6350 cpus_or(span
, span
, nodemask
);
6357 int sched_smt_power_savings
= 0, sched_mc_power_savings
= 0;
6360 * SMT sched-domains:
6362 #ifdef CONFIG_SCHED_SMT
6363 static DEFINE_PER_CPU(struct sched_domain
, cpu_domains
);
6364 static DEFINE_PER_CPU(struct sched_group
, sched_group_cpus
);
6367 cpu_to_cpu_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
)
6370 *sg
= &per_cpu(sched_group_cpus
, cpu
);
6376 * multi-core sched-domains:
6378 #ifdef CONFIG_SCHED_MC
6379 static DEFINE_PER_CPU(struct sched_domain
, core_domains
);
6380 static DEFINE_PER_CPU(struct sched_group
, sched_group_core
);
6383 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6385 cpu_to_core_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
)
6388 cpumask_t mask
= per_cpu(cpu_sibling_map
, cpu
);
6389 cpus_and(mask
, mask
, *cpu_map
);
6390 group
= first_cpu(mask
);
6392 *sg
= &per_cpu(sched_group_core
, group
);
6395 #elif defined(CONFIG_SCHED_MC)
6397 cpu_to_core_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
)
6400 *sg
= &per_cpu(sched_group_core
, cpu
);
6405 static DEFINE_PER_CPU(struct sched_domain
, phys_domains
);
6406 static DEFINE_PER_CPU(struct sched_group
, sched_group_phys
);
6409 cpu_to_phys_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
)
6412 #ifdef CONFIG_SCHED_MC
6413 cpumask_t mask
= cpu_coregroup_map(cpu
);
6414 cpus_and(mask
, mask
, *cpu_map
);
6415 group
= first_cpu(mask
);
6416 #elif defined(CONFIG_SCHED_SMT)
6417 cpumask_t mask
= per_cpu(cpu_sibling_map
, cpu
);
6418 cpus_and(mask
, mask
, *cpu_map
);
6419 group
= first_cpu(mask
);
6424 *sg
= &per_cpu(sched_group_phys
, group
);
6430 * The init_sched_build_groups can't handle what we want to do with node
6431 * groups, so roll our own. Now each node has its own list of groups which
6432 * gets dynamically allocated.
6434 static DEFINE_PER_CPU(struct sched_domain
, node_domains
);
6435 static struct sched_group
**sched_group_nodes_bycpu
[NR_CPUS
];
6437 static DEFINE_PER_CPU(struct sched_domain
, allnodes_domains
);
6438 static DEFINE_PER_CPU(struct sched_group
, sched_group_allnodes
);
6440 static int cpu_to_allnodes_group(int cpu
, const cpumask_t
*cpu_map
,
6441 struct sched_group
**sg
)
6443 cpumask_t nodemask
= node_to_cpumask(cpu_to_node(cpu
));
6446 cpus_and(nodemask
, nodemask
, *cpu_map
);
6447 group
= first_cpu(nodemask
);
6450 *sg
= &per_cpu(sched_group_allnodes
, group
);
6454 static void init_numa_sched_groups_power(struct sched_group
*group_head
)
6456 struct sched_group
*sg
= group_head
;
6462 for_each_cpu_mask(j
, sg
->cpumask
) {
6463 struct sched_domain
*sd
;
6465 sd
= &per_cpu(phys_domains
, j
);
6466 if (j
!= first_cpu(sd
->groups
->cpumask
)) {
6468 * Only add "power" once for each
6474 sg_inc_cpu_power(sg
, sd
->groups
->__cpu_power
);
6477 } while (sg
!= group_head
);
6482 /* Free memory allocated for various sched_group structures */
6483 static void free_sched_groups(const cpumask_t
*cpu_map
)
6487 for_each_cpu_mask(cpu
, *cpu_map
) {
6488 struct sched_group
**sched_group_nodes
6489 = sched_group_nodes_bycpu
[cpu
];
6491 if (!sched_group_nodes
)
6494 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6495 cpumask_t nodemask
= node_to_cpumask(i
);
6496 struct sched_group
*oldsg
, *sg
= sched_group_nodes
[i
];
6498 cpus_and(nodemask
, nodemask
, *cpu_map
);
6499 if (cpus_empty(nodemask
))
6509 if (oldsg
!= sched_group_nodes
[i
])
6512 kfree(sched_group_nodes
);
6513 sched_group_nodes_bycpu
[cpu
] = NULL
;
6517 static void free_sched_groups(const cpumask_t
*cpu_map
)
6523 * Initialize sched groups cpu_power.
6525 * cpu_power indicates the capacity of sched group, which is used while
6526 * distributing the load between different sched groups in a sched domain.
6527 * Typically cpu_power for all the groups in a sched domain will be same unless
6528 * there are asymmetries in the topology. If there are asymmetries, group
6529 * having more cpu_power will pickup more load compared to the group having
6532 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
6533 * the maximum number of tasks a group can handle in the presence of other idle
6534 * or lightly loaded groups in the same sched domain.
6536 static void init_sched_groups_power(int cpu
, struct sched_domain
*sd
)
6538 struct sched_domain
*child
;
6539 struct sched_group
*group
;
6541 WARN_ON(!sd
|| !sd
->groups
);
6543 if (cpu
!= first_cpu(sd
->groups
->cpumask
))
6548 sd
->groups
->__cpu_power
= 0;
6551 * For perf policy, if the groups in child domain share resources
6552 * (for example cores sharing some portions of the cache hierarchy
6553 * or SMT), then set this domain groups cpu_power such that each group
6554 * can handle only one task, when there are other idle groups in the
6555 * same sched domain.
6557 if (!child
|| (!(sd
->flags
& SD_POWERSAVINGS_BALANCE
) &&
6559 (SD_SHARE_CPUPOWER
| SD_SHARE_PKG_RESOURCES
)))) {
6560 sg_inc_cpu_power(sd
->groups
, SCHED_LOAD_SCALE
);
6565 * add cpu_power of each child group to this groups cpu_power
6567 group
= child
->groups
;
6569 sg_inc_cpu_power(sd
->groups
, group
->__cpu_power
);
6570 group
= group
->next
;
6571 } while (group
!= child
->groups
);
6575 * Build sched domains for a given set of cpus and attach the sched domains
6576 * to the individual cpus
6578 static int build_sched_domains(const cpumask_t
*cpu_map
)
6581 struct root_domain
*rd
;
6583 struct sched_group
**sched_group_nodes
= NULL
;
6584 int sd_allnodes
= 0;
6587 * Allocate the per-node list of sched groups
6589 sched_group_nodes
= kcalloc(MAX_NUMNODES
, sizeof(struct sched_group
*),
6591 if (!sched_group_nodes
) {
6592 printk(KERN_WARNING
"Can not alloc sched group node list\n");
6595 sched_group_nodes_bycpu
[first_cpu(*cpu_map
)] = sched_group_nodes
;
6598 rd
= alloc_rootdomain();
6600 printk(KERN_WARNING
"Cannot alloc root domain\n");
6605 * Set up domains for cpus specified by the cpu_map.
6607 for_each_cpu_mask(i
, *cpu_map
) {
6608 struct sched_domain
*sd
= NULL
, *p
;
6609 cpumask_t nodemask
= node_to_cpumask(cpu_to_node(i
));
6611 cpus_and(nodemask
, nodemask
, *cpu_map
);
6614 if (cpus_weight(*cpu_map
) >
6615 SD_NODES_PER_DOMAIN
*cpus_weight(nodemask
)) {
6616 sd
= &per_cpu(allnodes_domains
, i
);
6617 *sd
= SD_ALLNODES_INIT
;
6618 sd
->span
= *cpu_map
;
6619 cpu_to_allnodes_group(i
, cpu_map
, &sd
->groups
);
6625 sd
= &per_cpu(node_domains
, i
);
6627 sd
->span
= sched_domain_node_span(cpu_to_node(i
));
6631 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6635 sd
= &per_cpu(phys_domains
, i
);
6637 sd
->span
= nodemask
;
6641 cpu_to_phys_group(i
, cpu_map
, &sd
->groups
);
6643 #ifdef CONFIG_SCHED_MC
6645 sd
= &per_cpu(core_domains
, i
);
6647 sd
->span
= cpu_coregroup_map(i
);
6648 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6651 cpu_to_core_group(i
, cpu_map
, &sd
->groups
);
6654 #ifdef CONFIG_SCHED_SMT
6656 sd
= &per_cpu(cpu_domains
, i
);
6657 *sd
= SD_SIBLING_INIT
;
6658 sd
->span
= per_cpu(cpu_sibling_map
, i
);
6659 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6662 cpu_to_cpu_group(i
, cpu_map
, &sd
->groups
);
6666 #ifdef CONFIG_SCHED_SMT
6667 /* Set up CPU (sibling) groups */
6668 for_each_cpu_mask(i
, *cpu_map
) {
6669 cpumask_t this_sibling_map
= per_cpu(cpu_sibling_map
, i
);
6670 cpus_and(this_sibling_map
, this_sibling_map
, *cpu_map
);
6671 if (i
!= first_cpu(this_sibling_map
))
6674 init_sched_build_groups(this_sibling_map
, cpu_map
,
6679 #ifdef CONFIG_SCHED_MC
6680 /* Set up multi-core groups */
6681 for_each_cpu_mask(i
, *cpu_map
) {
6682 cpumask_t this_core_map
= cpu_coregroup_map(i
);
6683 cpus_and(this_core_map
, this_core_map
, *cpu_map
);
6684 if (i
!= first_cpu(this_core_map
))
6686 init_sched_build_groups(this_core_map
, cpu_map
,
6687 &cpu_to_core_group
);
6691 /* Set up physical groups */
6692 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6693 cpumask_t nodemask
= node_to_cpumask(i
);
6695 cpus_and(nodemask
, nodemask
, *cpu_map
);
6696 if (cpus_empty(nodemask
))
6699 init_sched_build_groups(nodemask
, cpu_map
, &cpu_to_phys_group
);
6703 /* Set up node groups */
6705 init_sched_build_groups(*cpu_map
, cpu_map
,
6706 &cpu_to_allnodes_group
);
6708 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6709 /* Set up node groups */
6710 struct sched_group
*sg
, *prev
;
6711 cpumask_t nodemask
= node_to_cpumask(i
);
6712 cpumask_t domainspan
;
6713 cpumask_t covered
= CPU_MASK_NONE
;
6716 cpus_and(nodemask
, nodemask
, *cpu_map
);
6717 if (cpus_empty(nodemask
)) {
6718 sched_group_nodes
[i
] = NULL
;
6722 domainspan
= sched_domain_node_span(i
);
6723 cpus_and(domainspan
, domainspan
, *cpu_map
);
6725 sg
= kmalloc_node(sizeof(struct sched_group
), GFP_KERNEL
, i
);
6727 printk(KERN_WARNING
"Can not alloc domain group for "
6731 sched_group_nodes
[i
] = sg
;
6732 for_each_cpu_mask(j
, nodemask
) {
6733 struct sched_domain
*sd
;
6735 sd
= &per_cpu(node_domains
, j
);
6738 sg
->__cpu_power
= 0;
6739 sg
->cpumask
= nodemask
;
6741 cpus_or(covered
, covered
, nodemask
);
6744 for (j
= 0; j
< MAX_NUMNODES
; j
++) {
6745 cpumask_t tmp
, notcovered
;
6746 int n
= (i
+ j
) % MAX_NUMNODES
;
6748 cpus_complement(notcovered
, covered
);
6749 cpus_and(tmp
, notcovered
, *cpu_map
);
6750 cpus_and(tmp
, tmp
, domainspan
);
6751 if (cpus_empty(tmp
))
6754 nodemask
= node_to_cpumask(n
);
6755 cpus_and(tmp
, tmp
, nodemask
);
6756 if (cpus_empty(tmp
))
6759 sg
= kmalloc_node(sizeof(struct sched_group
),
6763 "Can not alloc domain group for node %d\n", j
);
6766 sg
->__cpu_power
= 0;
6768 sg
->next
= prev
->next
;
6769 cpus_or(covered
, covered
, tmp
);
6776 /* Calculate CPU power for physical packages and nodes */
6777 #ifdef CONFIG_SCHED_SMT
6778 for_each_cpu_mask(i
, *cpu_map
) {
6779 struct sched_domain
*sd
= &per_cpu(cpu_domains
, i
);
6781 init_sched_groups_power(i
, sd
);
6784 #ifdef CONFIG_SCHED_MC
6785 for_each_cpu_mask(i
, *cpu_map
) {
6786 struct sched_domain
*sd
= &per_cpu(core_domains
, i
);
6788 init_sched_groups_power(i
, sd
);
6792 for_each_cpu_mask(i
, *cpu_map
) {
6793 struct sched_domain
*sd
= &per_cpu(phys_domains
, i
);
6795 init_sched_groups_power(i
, sd
);
6799 for (i
= 0; i
< MAX_NUMNODES
; i
++)
6800 init_numa_sched_groups_power(sched_group_nodes
[i
]);
6803 struct sched_group
*sg
;
6805 cpu_to_allnodes_group(first_cpu(*cpu_map
), cpu_map
, &sg
);
6806 init_numa_sched_groups_power(sg
);
6810 /* Attach the domains */
6811 for_each_cpu_mask(i
, *cpu_map
) {
6812 struct sched_domain
*sd
;
6813 #ifdef CONFIG_SCHED_SMT
6814 sd
= &per_cpu(cpu_domains
, i
);
6815 #elif defined(CONFIG_SCHED_MC)
6816 sd
= &per_cpu(core_domains
, i
);
6818 sd
= &per_cpu(phys_domains
, i
);
6820 cpu_attach_domain(sd
, rd
, i
);
6827 free_sched_groups(cpu_map
);
6832 static cpumask_t
*doms_cur
; /* current sched domains */
6833 static int ndoms_cur
; /* number of sched domains in 'doms_cur' */
6836 * Special case: If a kmalloc of a doms_cur partition (array of
6837 * cpumask_t) fails, then fallback to a single sched domain,
6838 * as determined by the single cpumask_t fallback_doms.
6840 static cpumask_t fallback_doms
;
6843 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6844 * For now this just excludes isolated cpus, but could be used to
6845 * exclude other special cases in the future.
6847 static int arch_init_sched_domains(const cpumask_t
*cpu_map
)
6852 doms_cur
= kmalloc(sizeof(cpumask_t
), GFP_KERNEL
);
6854 doms_cur
= &fallback_doms
;
6855 cpus_andnot(*doms_cur
, *cpu_map
, cpu_isolated_map
);
6856 err
= build_sched_domains(doms_cur
);
6857 register_sched_domain_sysctl();
6862 static void arch_destroy_sched_domains(const cpumask_t
*cpu_map
)
6864 free_sched_groups(cpu_map
);
6868 * Detach sched domains from a group of cpus specified in cpu_map
6869 * These cpus will now be attached to the NULL domain
6871 static void detach_destroy_domains(const cpumask_t
*cpu_map
)
6875 unregister_sched_domain_sysctl();
6877 for_each_cpu_mask(i
, *cpu_map
)
6878 cpu_attach_domain(NULL
, &def_root_domain
, i
);
6879 synchronize_sched();
6880 arch_destroy_sched_domains(cpu_map
);
6884 * Partition sched domains as specified by the 'ndoms_new'
6885 * cpumasks in the array doms_new[] of cpumasks. This compares
6886 * doms_new[] to the current sched domain partitioning, doms_cur[].
6887 * It destroys each deleted domain and builds each new domain.
6889 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
6890 * The masks don't intersect (don't overlap.) We should setup one
6891 * sched domain for each mask. CPUs not in any of the cpumasks will
6892 * not be load balanced. If the same cpumask appears both in the
6893 * current 'doms_cur' domains and in the new 'doms_new', we can leave
6896 * The passed in 'doms_new' should be kmalloc'd. This routine takes
6897 * ownership of it and will kfree it when done with it. If the caller
6898 * failed the kmalloc call, then it can pass in doms_new == NULL,
6899 * and partition_sched_domains() will fallback to the single partition
6902 * Call with hotplug lock held
6904 void partition_sched_domains(int ndoms_new
, cpumask_t
*doms_new
)
6910 /* always unregister in case we don't destroy any domains */
6911 unregister_sched_domain_sysctl();
6913 if (doms_new
== NULL
) {
6915 doms_new
= &fallback_doms
;
6916 cpus_andnot(doms_new
[0], cpu_online_map
, cpu_isolated_map
);
6919 /* Destroy deleted domains */
6920 for (i
= 0; i
< ndoms_cur
; i
++) {
6921 for (j
= 0; j
< ndoms_new
; j
++) {
6922 if (cpus_equal(doms_cur
[i
], doms_new
[j
]))
6925 /* no match - a current sched domain not in new doms_new[] */
6926 detach_destroy_domains(doms_cur
+ i
);
6931 /* Build new domains */
6932 for (i
= 0; i
< ndoms_new
; i
++) {
6933 for (j
= 0; j
< ndoms_cur
; j
++) {
6934 if (cpus_equal(doms_new
[i
], doms_cur
[j
]))
6937 /* no match - add a new doms_new */
6938 build_sched_domains(doms_new
+ i
);
6943 /* Remember the new sched domains */
6944 if (doms_cur
!= &fallback_doms
)
6946 doms_cur
= doms_new
;
6947 ndoms_cur
= ndoms_new
;
6949 register_sched_domain_sysctl();
6954 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
6955 static int arch_reinit_sched_domains(void)
6960 detach_destroy_domains(&cpu_online_map
);
6961 err
= arch_init_sched_domains(&cpu_online_map
);
6967 static ssize_t
sched_power_savings_store(const char *buf
, size_t count
, int smt
)
6971 if (buf
[0] != '0' && buf
[0] != '1')
6975 sched_smt_power_savings
= (buf
[0] == '1');
6977 sched_mc_power_savings
= (buf
[0] == '1');
6979 ret
= arch_reinit_sched_domains();
6981 return ret
? ret
: count
;
6984 #ifdef CONFIG_SCHED_MC
6985 static ssize_t
sched_mc_power_savings_show(struct sys_device
*dev
, char *page
)
6987 return sprintf(page
, "%u\n", sched_mc_power_savings
);
6989 static ssize_t
sched_mc_power_savings_store(struct sys_device
*dev
,
6990 const char *buf
, size_t count
)
6992 return sched_power_savings_store(buf
, count
, 0);
6994 static SYSDEV_ATTR(sched_mc_power_savings
, 0644, sched_mc_power_savings_show
,
6995 sched_mc_power_savings_store
);
6998 #ifdef CONFIG_SCHED_SMT
6999 static ssize_t
sched_smt_power_savings_show(struct sys_device
*dev
, char *page
)
7001 return sprintf(page
, "%u\n", sched_smt_power_savings
);
7003 static ssize_t
sched_smt_power_savings_store(struct sys_device
*dev
,
7004 const char *buf
, size_t count
)
7006 return sched_power_savings_store(buf
, count
, 1);
7008 static SYSDEV_ATTR(sched_smt_power_savings
, 0644, sched_smt_power_savings_show
,
7009 sched_smt_power_savings_store
);
7012 int sched_create_sysfs_power_savings_entries(struct sysdev_class
*cls
)
7016 #ifdef CONFIG_SCHED_SMT
7018 err
= sysfs_create_file(&cls
->kset
.kobj
,
7019 &attr_sched_smt_power_savings
.attr
);
7021 #ifdef CONFIG_SCHED_MC
7022 if (!err
&& mc_capable())
7023 err
= sysfs_create_file(&cls
->kset
.kobj
,
7024 &attr_sched_mc_power_savings
.attr
);
7031 * Force a reinitialization of the sched domains hierarchy. The domains
7032 * and groups cannot be updated in place without racing with the balancing
7033 * code, so we temporarily attach all running cpus to the NULL domain
7034 * which will prevent rebalancing while the sched domains are recalculated.
7036 static int update_sched_domains(struct notifier_block
*nfb
,
7037 unsigned long action
, void *hcpu
)
7040 case CPU_UP_PREPARE
:
7041 case CPU_UP_PREPARE_FROZEN
:
7042 case CPU_DOWN_PREPARE
:
7043 case CPU_DOWN_PREPARE_FROZEN
:
7044 detach_destroy_domains(&cpu_online_map
);
7047 case CPU_UP_CANCELED
:
7048 case CPU_UP_CANCELED_FROZEN
:
7049 case CPU_DOWN_FAILED
:
7050 case CPU_DOWN_FAILED_FROZEN
:
7052 case CPU_ONLINE_FROZEN
:
7054 case CPU_DEAD_FROZEN
:
7056 * Fall through and re-initialise the domains.
7063 /* The hotplug lock is already held by cpu_up/cpu_down */
7064 arch_init_sched_domains(&cpu_online_map
);
7069 void __init
sched_init_smp(void)
7071 cpumask_t non_isolated_cpus
;
7074 arch_init_sched_domains(&cpu_online_map
);
7075 cpus_andnot(non_isolated_cpus
, cpu_possible_map
, cpu_isolated_map
);
7076 if (cpus_empty(non_isolated_cpus
))
7077 cpu_set(smp_processor_id(), non_isolated_cpus
);
7079 /* XXX: Theoretical race here - CPU may be hotplugged now */
7080 hotcpu_notifier(update_sched_domains
, 0);
7082 /* Move init over to a non-isolated CPU */
7083 if (set_cpus_allowed(current
, non_isolated_cpus
) < 0)
7085 sched_init_granularity();
7087 #ifdef CONFIG_FAIR_GROUP_SCHED
7088 if (nr_cpu_ids
== 1)
7091 lb_monitor_task
= kthread_create(load_balance_monitor
, NULL
,
7093 if (!IS_ERR(lb_monitor_task
)) {
7094 lb_monitor_task
->flags
|= PF_NOFREEZE
;
7095 wake_up_process(lb_monitor_task
);
7097 printk(KERN_ERR
"Could not create load balance monitor thread"
7098 "(error = %ld) \n", PTR_ERR(lb_monitor_task
));
7103 void __init
sched_init_smp(void)
7105 sched_init_granularity();
7107 #endif /* CONFIG_SMP */
7109 int in_sched_functions(unsigned long addr
)
7111 return in_lock_functions(addr
) ||
7112 (addr
>= (unsigned long)__sched_text_start
7113 && addr
< (unsigned long)__sched_text_end
);
7116 static void init_cfs_rq(struct cfs_rq
*cfs_rq
, struct rq
*rq
)
7118 cfs_rq
->tasks_timeline
= RB_ROOT
;
7119 #ifdef CONFIG_FAIR_GROUP_SCHED
7122 cfs_rq
->min_vruntime
= (u64
)(-(1LL << 20));
7125 static void init_rt_rq(struct rt_rq
*rt_rq
, struct rq
*rq
)
7127 struct rt_prio_array
*array
;
7130 array
= &rt_rq
->active
;
7131 for (i
= 0; i
< MAX_RT_PRIO
; i
++) {
7132 INIT_LIST_HEAD(array
->queue
+ i
);
7133 __clear_bit(i
, array
->bitmap
);
7135 /* delimiter for bitsearch: */
7136 __set_bit(MAX_RT_PRIO
, array
->bitmap
);
7138 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
7139 rt_rq
->highest_prio
= MAX_RT_PRIO
;
7142 rt_rq
->rt_nr_migratory
= 0;
7143 rt_rq
->overloaded
= 0;
7147 rt_rq
->rt_throttled
= 0;
7149 #ifdef CONFIG_RT_GROUP_SCHED
7150 rt_rq
->rt_nr_boosted
= 0;
7155 #ifdef CONFIG_FAIR_GROUP_SCHED
7156 static void init_tg_cfs_entry(struct rq
*rq
, struct task_group
*tg
,
7157 struct cfs_rq
*cfs_rq
, struct sched_entity
*se
,
7160 tg
->cfs_rq
[cpu
] = cfs_rq
;
7161 init_cfs_rq(cfs_rq
, rq
);
7164 list_add(&cfs_rq
->leaf_cfs_rq_list
, &rq
->leaf_cfs_rq_list
);
7167 se
->cfs_rq
= &rq
->cfs
;
7169 se
->load
.weight
= tg
->shares
;
7170 se
->load
.inv_weight
= div64_64(1ULL<<32, se
->load
.weight
);
7175 #ifdef CONFIG_RT_GROUP_SCHED
7176 static void init_tg_rt_entry(struct rq
*rq
, struct task_group
*tg
,
7177 struct rt_rq
*rt_rq
, struct sched_rt_entity
*rt_se
,
7180 tg
->rt_rq
[cpu
] = rt_rq
;
7181 init_rt_rq(rt_rq
, rq
);
7183 rt_rq
->rt_se
= rt_se
;
7185 list_add(&rt_rq
->leaf_rt_rq_list
, &rq
->leaf_rt_rq_list
);
7187 tg
->rt_se
[cpu
] = rt_se
;
7188 rt_se
->rt_rq
= &rq
->rt
;
7189 rt_se
->my_q
= rt_rq
;
7190 rt_se
->parent
= NULL
;
7191 INIT_LIST_HEAD(&rt_se
->run_list
);
7195 void __init
sched_init(void)
7197 int highest_cpu
= 0;
7201 init_defrootdomain();
7204 #ifdef CONFIG_GROUP_SCHED
7205 list_add(&init_task_group
.list
, &task_groups
);
7208 for_each_possible_cpu(i
) {
7212 spin_lock_init(&rq
->lock
);
7213 lockdep_set_class(&rq
->lock
, &rq
->rq_lock_key
);
7216 init_cfs_rq(&rq
->cfs
, rq
);
7217 init_rt_rq(&rq
->rt
, rq
);
7218 #ifdef CONFIG_FAIR_GROUP_SCHED
7219 init_task_group
.shares
= init_task_group_load
;
7220 INIT_LIST_HEAD(&rq
->leaf_cfs_rq_list
);
7221 init_tg_cfs_entry(rq
, &init_task_group
,
7222 &per_cpu(init_cfs_rq
, i
),
7223 &per_cpu(init_sched_entity
, i
), i
, 1);
7226 #ifdef CONFIG_RT_GROUP_SCHED
7227 init_task_group
.rt_runtime
=
7228 sysctl_sched_rt_runtime
* NSEC_PER_USEC
;
7229 INIT_LIST_HEAD(&rq
->leaf_rt_rq_list
);
7230 init_tg_rt_entry(rq
, &init_task_group
,
7231 &per_cpu(init_rt_rq
, i
),
7232 &per_cpu(init_sched_rt_entity
, i
), i
, 1);
7234 rq
->rt_period_expire
= 0;
7235 rq
->rt_throttled
= 0;
7237 for (j
= 0; j
< CPU_LOAD_IDX_MAX
; j
++)
7238 rq
->cpu_load
[j
] = 0;
7242 rq
->active_balance
= 0;
7243 rq
->next_balance
= jiffies
;
7246 rq
->migration_thread
= NULL
;
7247 INIT_LIST_HEAD(&rq
->migration_queue
);
7248 rq_attach_root(rq
, &def_root_domain
);
7251 atomic_set(&rq
->nr_iowait
, 0);
7255 set_load_weight(&init_task
);
7257 #ifdef CONFIG_PREEMPT_NOTIFIERS
7258 INIT_HLIST_HEAD(&init_task
.preempt_notifiers
);
7262 nr_cpu_ids
= highest_cpu
+ 1;
7263 open_softirq(SCHED_SOFTIRQ
, run_rebalance_domains
, NULL
);
7266 #ifdef CONFIG_RT_MUTEXES
7267 plist_head_init(&init_task
.pi_waiters
, &init_task
.pi_lock
);
7271 * The boot idle thread does lazy MMU switching as well:
7273 atomic_inc(&init_mm
.mm_count
);
7274 enter_lazy_tlb(&init_mm
, current
);
7277 * Make us the idle thread. Technically, schedule() should not be
7278 * called from this thread, however somewhere below it might be,
7279 * but because we are the idle thread, we just pick up running again
7280 * when this runqueue becomes "idle".
7282 init_idle(current
, smp_processor_id());
7284 * During early bootup we pretend to be a normal task:
7286 current
->sched_class
= &fair_sched_class
;
7289 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
7290 void __might_sleep(char *file
, int line
)
7293 static unsigned long prev_jiffy
; /* ratelimiting */
7295 if ((in_atomic() || irqs_disabled()) &&
7296 system_state
== SYSTEM_RUNNING
&& !oops_in_progress
) {
7297 if (time_before(jiffies
, prev_jiffy
+ HZ
) && prev_jiffy
)
7299 prev_jiffy
= jiffies
;
7300 printk(KERN_ERR
"BUG: sleeping function called from invalid"
7301 " context at %s:%d\n", file
, line
);
7302 printk("in_atomic():%d, irqs_disabled():%d\n",
7303 in_atomic(), irqs_disabled());
7304 debug_show_held_locks(current
);
7305 if (irqs_disabled())
7306 print_irqtrace_events(current
);
7311 EXPORT_SYMBOL(__might_sleep
);
7314 #ifdef CONFIG_MAGIC_SYSRQ
7315 static void normalize_task(struct rq
*rq
, struct task_struct
*p
)
7318 update_rq_clock(rq
);
7319 on_rq
= p
->se
.on_rq
;
7321 deactivate_task(rq
, p
, 0);
7322 __setscheduler(rq
, p
, SCHED_NORMAL
, 0);
7324 activate_task(rq
, p
, 0);
7325 resched_task(rq
->curr
);
7329 void normalize_rt_tasks(void)
7331 struct task_struct
*g
, *p
;
7332 unsigned long flags
;
7335 read_lock_irqsave(&tasklist_lock
, flags
);
7336 do_each_thread(g
, p
) {
7338 * Only normalize user tasks:
7343 p
->se
.exec_start
= 0;
7344 #ifdef CONFIG_SCHEDSTATS
7345 p
->se
.wait_start
= 0;
7346 p
->se
.sleep_start
= 0;
7347 p
->se
.block_start
= 0;
7349 task_rq(p
)->clock
= 0;
7353 * Renice negative nice level userspace
7356 if (TASK_NICE(p
) < 0 && p
->mm
)
7357 set_user_nice(p
, 0);
7361 spin_lock(&p
->pi_lock
);
7362 rq
= __task_rq_lock(p
);
7364 normalize_task(rq
, p
);
7366 __task_rq_unlock(rq
);
7367 spin_unlock(&p
->pi_lock
);
7368 } while_each_thread(g
, p
);
7370 read_unlock_irqrestore(&tasklist_lock
, flags
);
7373 #endif /* CONFIG_MAGIC_SYSRQ */
7377 * These functions are only useful for the IA64 MCA handling.
7379 * They can only be called when the whole system has been
7380 * stopped - every CPU needs to be quiescent, and no scheduling
7381 * activity can take place. Using them for anything else would
7382 * be a serious bug, and as a result, they aren't even visible
7383 * under any other configuration.
7387 * curr_task - return the current task for a given cpu.
7388 * @cpu: the processor in question.
7390 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7392 struct task_struct
*curr_task(int cpu
)
7394 return cpu_curr(cpu
);
7398 * set_curr_task - set the current task for a given cpu.
7399 * @cpu: the processor in question.
7400 * @p: the task pointer to set.
7402 * Description: This function must only be used when non-maskable interrupts
7403 * are serviced on a separate stack. It allows the architecture to switch the
7404 * notion of the current task on a cpu in a non-blocking manner. This function
7405 * must be called with all CPU's synchronized, and interrupts disabled, the
7406 * and caller must save the original value of the current task (see
7407 * curr_task() above) and restore that value before reenabling interrupts and
7408 * re-starting the system.
7410 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7412 void set_curr_task(int cpu
, struct task_struct
*p
)
7419 #ifdef CONFIG_GROUP_SCHED
7421 #if defined CONFIG_FAIR_GROUP_SCHED && defined CONFIG_SMP
7423 * distribute shares of all task groups among their schedulable entities,
7424 * to reflect load distribution across cpus.
7426 static int rebalance_shares(struct sched_domain
*sd
, int this_cpu
)
7428 struct cfs_rq
*cfs_rq
;
7429 struct rq
*rq
= cpu_rq(this_cpu
);
7430 cpumask_t sdspan
= sd
->span
;
7433 /* Walk thr' all the task groups that we have */
7434 for_each_leaf_cfs_rq(rq
, cfs_rq
) {
7436 unsigned long total_load
= 0, total_shares
;
7437 struct task_group
*tg
= cfs_rq
->tg
;
7439 /* Gather total task load of this group across cpus */
7440 for_each_cpu_mask(i
, sdspan
)
7441 total_load
+= tg
->cfs_rq
[i
]->load
.weight
;
7443 /* Nothing to do if this group has no load */
7448 * tg->shares represents the number of cpu shares the task group
7449 * is eligible to hold on a single cpu. On N cpus, it is
7450 * eligible to hold (N * tg->shares) number of cpu shares.
7452 total_shares
= tg
->shares
* cpus_weight(sdspan
);
7455 * redistribute total_shares across cpus as per the task load
7458 for_each_cpu_mask(i
, sdspan
) {
7459 unsigned long local_load
, local_shares
;
7461 local_load
= tg
->cfs_rq
[i
]->load
.weight
;
7462 local_shares
= (local_load
* total_shares
) / total_load
;
7464 local_shares
= MIN_GROUP_SHARES
;
7465 if (local_shares
== tg
->se
[i
]->load
.weight
)
7468 spin_lock_irq(&cpu_rq(i
)->lock
);
7469 set_se_shares(tg
->se
[i
], local_shares
);
7470 spin_unlock_irq(&cpu_rq(i
)->lock
);
7479 * How frequently should we rebalance_shares() across cpus?
7481 * The more frequently we rebalance shares, the more accurate is the fairness
7482 * of cpu bandwidth distribution between task groups. However higher frequency
7483 * also implies increased scheduling overhead.
7485 * sysctl_sched_min_bal_int_shares represents the minimum interval between
7486 * consecutive calls to rebalance_shares() in the same sched domain.
7488 * sysctl_sched_max_bal_int_shares represents the maximum interval between
7489 * consecutive calls to rebalance_shares() in the same sched domain.
7491 * These settings allows for the appropriate trade-off between accuracy of
7492 * fairness and the associated overhead.
7496 /* default: 8ms, units: milliseconds */
7497 const_debug
unsigned int sysctl_sched_min_bal_int_shares
= 8;
7499 /* default: 128ms, units: milliseconds */
7500 const_debug
unsigned int sysctl_sched_max_bal_int_shares
= 128;
7502 /* kernel thread that runs rebalance_shares() periodically */
7503 static int load_balance_monitor(void *unused
)
7505 unsigned int timeout
= sysctl_sched_min_bal_int_shares
;
7506 struct sched_param schedparm
;
7510 * We don't want this thread's execution to be limited by the shares
7511 * assigned to default group (init_task_group). Hence make it run
7512 * as a SCHED_RR RT task at the lowest priority.
7514 schedparm
.sched_priority
= 1;
7515 ret
= sched_setscheduler(current
, SCHED_RR
, &schedparm
);
7517 printk(KERN_ERR
"Couldn't set SCHED_RR policy for load balance"
7518 " monitor thread (error = %d) \n", ret
);
7520 while (!kthread_should_stop()) {
7521 int i
, cpu
, balanced
= 1;
7523 /* Prevent cpus going down or coming up */
7525 /* lockout changes to doms_cur[] array */
7528 * Enter a rcu read-side critical section to safely walk rq->sd
7529 * chain on various cpus and to walk task group list
7530 * (rq->leaf_cfs_rq_list) in rebalance_shares().
7534 for (i
= 0; i
< ndoms_cur
; i
++) {
7535 cpumask_t cpumap
= doms_cur
[i
];
7536 struct sched_domain
*sd
= NULL
, *sd_prev
= NULL
;
7538 cpu
= first_cpu(cpumap
);
7540 /* Find the highest domain at which to balance shares */
7541 for_each_domain(cpu
, sd
) {
7542 if (!(sd
->flags
& SD_LOAD_BALANCE
))
7548 /* sd == NULL? No load balance reqd in this domain */
7552 balanced
&= rebalance_shares(sd
, cpu
);
7561 timeout
= sysctl_sched_min_bal_int_shares
;
7562 else if (timeout
< sysctl_sched_max_bal_int_shares
)
7565 msleep_interruptible(timeout
);
7570 #endif /* CONFIG_SMP */
7572 #ifdef CONFIG_FAIR_GROUP_SCHED
7573 static void free_fair_sched_group(struct task_group
*tg
)
7577 for_each_possible_cpu(i
) {
7579 kfree(tg
->cfs_rq
[i
]);
7588 static int alloc_fair_sched_group(struct task_group
*tg
)
7590 struct cfs_rq
*cfs_rq
;
7591 struct sched_entity
*se
;
7595 tg
->cfs_rq
= kzalloc(sizeof(cfs_rq
) * NR_CPUS
, GFP_KERNEL
);
7598 tg
->se
= kzalloc(sizeof(se
) * NR_CPUS
, GFP_KERNEL
);
7602 tg
->shares
= NICE_0_LOAD
;
7604 for_each_possible_cpu(i
) {
7607 cfs_rq
= kmalloc_node(sizeof(struct cfs_rq
),
7608 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
7612 se
= kmalloc_node(sizeof(struct sched_entity
),
7613 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
7617 init_tg_cfs_entry(rq
, tg
, cfs_rq
, se
, i
, 0);
7626 static inline void register_fair_sched_group(struct task_group
*tg
, int cpu
)
7628 list_add_rcu(&tg
->cfs_rq
[cpu
]->leaf_cfs_rq_list
,
7629 &cpu_rq(cpu
)->leaf_cfs_rq_list
);
7632 static inline void unregister_fair_sched_group(struct task_group
*tg
, int cpu
)
7634 list_del_rcu(&tg
->cfs_rq
[cpu
]->leaf_cfs_rq_list
);
7637 static inline void free_fair_sched_group(struct task_group
*tg
)
7641 static inline int alloc_fair_sched_group(struct task_group
*tg
)
7646 static inline void register_fair_sched_group(struct task_group
*tg
, int cpu
)
7650 static inline void unregister_fair_sched_group(struct task_group
*tg
, int cpu
)
7655 #ifdef CONFIG_RT_GROUP_SCHED
7656 static void free_rt_sched_group(struct task_group
*tg
)
7660 for_each_possible_cpu(i
) {
7662 kfree(tg
->rt_rq
[i
]);
7664 kfree(tg
->rt_se
[i
]);
7671 static int alloc_rt_sched_group(struct task_group
*tg
)
7673 struct rt_rq
*rt_rq
;
7674 struct sched_rt_entity
*rt_se
;
7678 tg
->rt_rq
= kzalloc(sizeof(rt_rq
) * NR_CPUS
, GFP_KERNEL
);
7681 tg
->rt_se
= kzalloc(sizeof(rt_se
) * NR_CPUS
, GFP_KERNEL
);
7687 for_each_possible_cpu(i
) {
7690 rt_rq
= kmalloc_node(sizeof(struct rt_rq
),
7691 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
7695 rt_se
= kmalloc_node(sizeof(struct sched_rt_entity
),
7696 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
7700 init_tg_rt_entry(rq
, tg
, rt_rq
, rt_se
, i
, 0);
7709 static inline void register_rt_sched_group(struct task_group
*tg
, int cpu
)
7711 list_add_rcu(&tg
->rt_rq
[cpu
]->leaf_rt_rq_list
,
7712 &cpu_rq(cpu
)->leaf_rt_rq_list
);
7715 static inline void unregister_rt_sched_group(struct task_group
*tg
, int cpu
)
7717 list_del_rcu(&tg
->rt_rq
[cpu
]->leaf_rt_rq_list
);
7720 static inline void free_rt_sched_group(struct task_group
*tg
)
7724 static inline int alloc_rt_sched_group(struct task_group
*tg
)
7729 static inline void register_rt_sched_group(struct task_group
*tg
, int cpu
)
7733 static inline void unregister_rt_sched_group(struct task_group
*tg
, int cpu
)
7738 static void free_sched_group(struct task_group
*tg
)
7740 free_fair_sched_group(tg
);
7741 free_rt_sched_group(tg
);
7745 /* allocate runqueue etc for a new task group */
7746 struct task_group
*sched_create_group(void)
7748 struct task_group
*tg
;
7749 unsigned long flags
;
7752 tg
= kzalloc(sizeof(*tg
), GFP_KERNEL
);
7754 return ERR_PTR(-ENOMEM
);
7756 if (!alloc_fair_sched_group(tg
))
7759 if (!alloc_rt_sched_group(tg
))
7762 spin_lock_irqsave(&task_group_lock
, flags
);
7763 for_each_possible_cpu(i
) {
7764 register_fair_sched_group(tg
, i
);
7765 register_rt_sched_group(tg
, i
);
7767 list_add_rcu(&tg
->list
, &task_groups
);
7768 spin_unlock_irqrestore(&task_group_lock
, flags
);
7773 free_sched_group(tg
);
7774 return ERR_PTR(-ENOMEM
);
7777 /* rcu callback to free various structures associated with a task group */
7778 static void free_sched_group_rcu(struct rcu_head
*rhp
)
7780 /* now it should be safe to free those cfs_rqs */
7781 free_sched_group(container_of(rhp
, struct task_group
, rcu
));
7784 /* Destroy runqueue etc associated with a task group */
7785 void sched_destroy_group(struct task_group
*tg
)
7787 unsigned long flags
;
7790 spin_lock_irqsave(&task_group_lock
, flags
);
7791 for_each_possible_cpu(i
) {
7792 unregister_fair_sched_group(tg
, i
);
7793 unregister_rt_sched_group(tg
, i
);
7795 list_del_rcu(&tg
->list
);
7796 spin_unlock_irqrestore(&task_group_lock
, flags
);
7798 /* wait for possible concurrent references to cfs_rqs complete */
7799 call_rcu(&tg
->rcu
, free_sched_group_rcu
);
7802 /* change task's runqueue when it moves between groups.
7803 * The caller of this function should have put the task in its new group
7804 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7805 * reflect its new group.
7807 void sched_move_task(struct task_struct
*tsk
)
7810 unsigned long flags
;
7813 rq
= task_rq_lock(tsk
, &flags
);
7815 update_rq_clock(rq
);
7817 running
= task_current(rq
, tsk
);
7818 on_rq
= tsk
->se
.on_rq
;
7821 dequeue_task(rq
, tsk
, 0);
7822 if (unlikely(running
))
7823 tsk
->sched_class
->put_prev_task(rq
, tsk
);
7826 set_task_rq(tsk
, task_cpu(tsk
));
7829 if (unlikely(running
))
7830 tsk
->sched_class
->set_curr_task(rq
);
7831 enqueue_task(rq
, tsk
, 0);
7834 task_rq_unlock(rq
, &flags
);
7837 #ifdef CONFIG_FAIR_GROUP_SCHED
7838 /* rq->lock to be locked by caller */
7839 static void set_se_shares(struct sched_entity
*se
, unsigned long shares
)
7841 struct cfs_rq
*cfs_rq
= se
->cfs_rq
;
7842 struct rq
*rq
= cfs_rq
->rq
;
7846 shares
= MIN_GROUP_SHARES
;
7850 dequeue_entity(cfs_rq
, se
, 0);
7851 dec_cpu_load(rq
, se
->load
.weight
);
7854 se
->load
.weight
= shares
;
7855 se
->load
.inv_weight
= div64_64((1ULL<<32), shares
);
7858 enqueue_entity(cfs_rq
, se
, 0);
7859 inc_cpu_load(rq
, se
->load
.weight
);
7863 static DEFINE_MUTEX(shares_mutex
);
7865 int sched_group_set_shares(struct task_group
*tg
, unsigned long shares
)
7868 unsigned long flags
;
7870 mutex_lock(&shares_mutex
);
7871 if (tg
->shares
== shares
)
7874 if (shares
< MIN_GROUP_SHARES
)
7875 shares
= MIN_GROUP_SHARES
;
7878 * Prevent any load balance activity (rebalance_shares,
7879 * load_balance_fair) from referring to this group first,
7880 * by taking it off the rq->leaf_cfs_rq_list on each cpu.
7882 spin_lock_irqsave(&task_group_lock
, flags
);
7883 for_each_possible_cpu(i
)
7884 unregister_fair_sched_group(tg
, i
);
7885 spin_unlock_irqrestore(&task_group_lock
, flags
);
7887 /* wait for any ongoing reference to this group to finish */
7888 synchronize_sched();
7891 * Now we are free to modify the group's share on each cpu
7892 * w/o tripping rebalance_share or load_balance_fair.
7894 tg
->shares
= shares
;
7895 for_each_possible_cpu(i
) {
7896 spin_lock_irq(&cpu_rq(i
)->lock
);
7897 set_se_shares(tg
->se
[i
], shares
);
7898 spin_unlock_irq(&cpu_rq(i
)->lock
);
7902 * Enable load balance activity on this group, by inserting it back on
7903 * each cpu's rq->leaf_cfs_rq_list.
7905 spin_lock_irqsave(&task_group_lock
, flags
);
7906 for_each_possible_cpu(i
)
7907 register_fair_sched_group(tg
, i
);
7908 spin_unlock_irqrestore(&task_group_lock
, flags
);
7910 mutex_unlock(&shares_mutex
);
7914 unsigned long sched_group_shares(struct task_group
*tg
)
7920 #ifdef CONFIG_RT_GROUP_SCHED
7922 * Ensure that the real time constraints are schedulable.
7924 static DEFINE_MUTEX(rt_constraints_mutex
);
7926 static unsigned long to_ratio(u64 period
, u64 runtime
)
7928 if (runtime
== RUNTIME_INF
)
7931 runtime
*= (1ULL << 16);
7932 div64_64(runtime
, period
);
7936 static int __rt_schedulable(struct task_group
*tg
, u64 period
, u64 runtime
)
7938 struct task_group
*tgi
;
7939 unsigned long total
= 0;
7940 unsigned long global_ratio
=
7941 to_ratio(sysctl_sched_rt_period
,
7942 sysctl_sched_rt_runtime
< 0 ?
7943 RUNTIME_INF
: sysctl_sched_rt_runtime
);
7946 list_for_each_entry_rcu(tgi
, &task_groups
, list
) {
7950 total
+= to_ratio(period
, tgi
->rt_runtime
);
7954 return total
+ to_ratio(period
, runtime
) < global_ratio
;
7957 int sched_group_set_rt_runtime(struct task_group
*tg
, long rt_runtime_us
)
7959 u64 rt_runtime
, rt_period
;
7962 rt_period
= sysctl_sched_rt_period
* NSEC_PER_USEC
;
7963 rt_runtime
= (u64
)rt_runtime_us
* NSEC_PER_USEC
;
7964 if (rt_runtime_us
== -1)
7965 rt_runtime
= rt_period
;
7967 mutex_lock(&rt_constraints_mutex
);
7968 if (!__rt_schedulable(tg
, rt_period
, rt_runtime
)) {
7972 if (rt_runtime_us
== -1)
7973 rt_runtime
= RUNTIME_INF
;
7974 tg
->rt_runtime
= rt_runtime
;
7976 mutex_unlock(&rt_constraints_mutex
);
7981 long sched_group_rt_runtime(struct task_group
*tg
)
7985 if (tg
->rt_runtime
== RUNTIME_INF
)
7988 rt_runtime_us
= tg
->rt_runtime
;
7989 do_div(rt_runtime_us
, NSEC_PER_USEC
);
7990 return rt_runtime_us
;
7993 #endif /* CONFIG_GROUP_SCHED */
7995 #ifdef CONFIG_CGROUP_SCHED
7997 /* return corresponding task_group object of a cgroup */
7998 static inline struct task_group
*cgroup_tg(struct cgroup
*cgrp
)
8000 return container_of(cgroup_subsys_state(cgrp
, cpu_cgroup_subsys_id
),
8001 struct task_group
, css
);
8004 static struct cgroup_subsys_state
*
8005 cpu_cgroup_create(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
8007 struct task_group
*tg
;
8009 if (!cgrp
->parent
) {
8010 /* This is early initialization for the top cgroup */
8011 init_task_group
.css
.cgroup
= cgrp
;
8012 return &init_task_group
.css
;
8015 /* we support only 1-level deep hierarchical scheduler atm */
8016 if (cgrp
->parent
->parent
)
8017 return ERR_PTR(-EINVAL
);
8019 tg
= sched_create_group();
8021 return ERR_PTR(-ENOMEM
);
8023 /* Bind the cgroup to task_group object we just created */
8024 tg
->css
.cgroup
= cgrp
;
8030 cpu_cgroup_destroy(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
8032 struct task_group
*tg
= cgroup_tg(cgrp
);
8034 sched_destroy_group(tg
);
8038 cpu_cgroup_can_attach(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
,
8039 struct task_struct
*tsk
)
8041 #ifdef CONFIG_RT_GROUP_SCHED
8042 /* Don't accept realtime tasks when there is no way for them to run */
8043 if (rt_task(tsk
) && cgroup_tg(cgrp
)->rt_runtime
== 0)
8046 /* We don't support RT-tasks being in separate groups */
8047 if (tsk
->sched_class
!= &fair_sched_class
)
8055 cpu_cgroup_attach(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
,
8056 struct cgroup
*old_cont
, struct task_struct
*tsk
)
8058 sched_move_task(tsk
);
8061 #ifdef CONFIG_FAIR_GROUP_SCHED
8062 static int cpu_shares_write_uint(struct cgroup
*cgrp
, struct cftype
*cftype
,
8065 return sched_group_set_shares(cgroup_tg(cgrp
), shareval
);
8068 static u64
cpu_shares_read_uint(struct cgroup
*cgrp
, struct cftype
*cft
)
8070 struct task_group
*tg
= cgroup_tg(cgrp
);
8072 return (u64
) tg
->shares
;
8076 #ifdef CONFIG_RT_GROUP_SCHED
8077 static int cpu_rt_runtime_write(struct cgroup
*cgrp
, struct cftype
*cft
,
8079 const char __user
*userbuf
,
8080 size_t nbytes
, loff_t
*unused_ppos
)
8089 if (nbytes
>= sizeof(buffer
))
8091 if (copy_from_user(buffer
, userbuf
, nbytes
))
8094 buffer
[nbytes
] = 0; /* nul-terminate */
8096 /* strip newline if necessary */
8097 if (nbytes
&& (buffer
[nbytes
-1] == '\n'))
8098 buffer
[nbytes
-1] = 0;
8099 val
= simple_strtoll(buffer
, &end
, 0);
8103 /* Pass to subsystem */
8104 retval
= sched_group_set_rt_runtime(cgroup_tg(cgrp
), val
);
8110 static ssize_t
cpu_rt_runtime_read(struct cgroup
*cgrp
, struct cftype
*cft
,
8112 char __user
*buf
, size_t nbytes
,
8116 long val
= sched_group_rt_runtime(cgroup_tg(cgrp
));
8117 int len
= sprintf(tmp
, "%ld\n", val
);
8119 return simple_read_from_buffer(buf
, nbytes
, ppos
, tmp
, len
);
8123 static struct cftype cpu_files
[] = {
8124 #ifdef CONFIG_FAIR_GROUP_SCHED
8127 .read_uint
= cpu_shares_read_uint
,
8128 .write_uint
= cpu_shares_write_uint
,
8131 #ifdef CONFIG_RT_GROUP_SCHED
8133 .name
= "rt_runtime_us",
8134 .read
= cpu_rt_runtime_read
,
8135 .write
= cpu_rt_runtime_write
,
8140 static int cpu_cgroup_populate(struct cgroup_subsys
*ss
, struct cgroup
*cont
)
8142 return cgroup_add_files(cont
, ss
, cpu_files
, ARRAY_SIZE(cpu_files
));
8145 struct cgroup_subsys cpu_cgroup_subsys
= {
8147 .create
= cpu_cgroup_create
,
8148 .destroy
= cpu_cgroup_destroy
,
8149 .can_attach
= cpu_cgroup_can_attach
,
8150 .attach
= cpu_cgroup_attach
,
8151 .populate
= cpu_cgroup_populate
,
8152 .subsys_id
= cpu_cgroup_subsys_id
,
8156 #endif /* CONFIG_CGROUP_SCHED */
8158 #ifdef CONFIG_CGROUP_CPUACCT
8161 * CPU accounting code for task groups.
8163 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
8164 * (balbir@in.ibm.com).
8167 /* track cpu usage of a group of tasks */
8169 struct cgroup_subsys_state css
;
8170 /* cpuusage holds pointer to a u64-type object on every cpu */
8174 struct cgroup_subsys cpuacct_subsys
;
8176 /* return cpu accounting group corresponding to this container */
8177 static inline struct cpuacct
*cgroup_ca(struct cgroup
*cont
)
8179 return container_of(cgroup_subsys_state(cont
, cpuacct_subsys_id
),
8180 struct cpuacct
, css
);
8183 /* return cpu accounting group to which this task belongs */
8184 static inline struct cpuacct
*task_ca(struct task_struct
*tsk
)
8186 return container_of(task_subsys_state(tsk
, cpuacct_subsys_id
),
8187 struct cpuacct
, css
);
8190 /* create a new cpu accounting group */
8191 static struct cgroup_subsys_state
*cpuacct_create(
8192 struct cgroup_subsys
*ss
, struct cgroup
*cont
)
8194 struct cpuacct
*ca
= kzalloc(sizeof(*ca
), GFP_KERNEL
);
8197 return ERR_PTR(-ENOMEM
);
8199 ca
->cpuusage
= alloc_percpu(u64
);
8200 if (!ca
->cpuusage
) {
8202 return ERR_PTR(-ENOMEM
);
8208 /* destroy an existing cpu accounting group */
8210 cpuacct_destroy(struct cgroup_subsys
*ss
, struct cgroup
*cont
)
8212 struct cpuacct
*ca
= cgroup_ca(cont
);
8214 free_percpu(ca
->cpuusage
);
8218 /* return total cpu usage (in nanoseconds) of a group */
8219 static u64
cpuusage_read(struct cgroup
*cont
, struct cftype
*cft
)
8221 struct cpuacct
*ca
= cgroup_ca(cont
);
8222 u64 totalcpuusage
= 0;
8225 for_each_possible_cpu(i
) {
8226 u64
*cpuusage
= percpu_ptr(ca
->cpuusage
, i
);
8229 * Take rq->lock to make 64-bit addition safe on 32-bit
8232 spin_lock_irq(&cpu_rq(i
)->lock
);
8233 totalcpuusage
+= *cpuusage
;
8234 spin_unlock_irq(&cpu_rq(i
)->lock
);
8237 return totalcpuusage
;
8240 static struct cftype files
[] = {
8243 .read_uint
= cpuusage_read
,
8247 static int cpuacct_populate(struct cgroup_subsys
*ss
, struct cgroup
*cont
)
8249 return cgroup_add_files(cont
, ss
, files
, ARRAY_SIZE(files
));
8253 * charge this task's execution time to its accounting group.
8255 * called with rq->lock held.
8257 static void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
)
8261 if (!cpuacct_subsys
.active
)
8266 u64
*cpuusage
= percpu_ptr(ca
->cpuusage
, task_cpu(tsk
));
8268 *cpuusage
+= cputime
;
8272 struct cgroup_subsys cpuacct_subsys
= {
8274 .create
= cpuacct_create
,
8275 .destroy
= cpuacct_destroy
,
8276 .populate
= cpuacct_populate
,
8277 .subsys_id
= cpuacct_subsys_id
,
8279 #endif /* CONFIG_CGROUP_CPUACCT */