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_FAIR_GROUP_SCHED
160 #include <linux/cgroup.h>
164 static LIST_HEAD(task_groups
);
166 /* task group related information */
168 #ifdef CONFIG_FAIR_CGROUP_SCHED
169 struct cgroup_subsys_state css
;
171 /* schedulable entities of this group on each cpu */
172 struct sched_entity
**se
;
173 /* runqueue "owned" by this group on each cpu */
174 struct cfs_rq
**cfs_rq
;
176 struct sched_rt_entity
**rt_se
;
177 struct rt_rq
**rt_rq
;
179 unsigned int rt_ratio
;
182 * shares assigned to a task group governs how much of cpu bandwidth
183 * is allocated to the group. The more shares a group has, the more is
184 * the cpu bandwidth allocated to it.
186 * For ex, lets say that there are three task groups, A, B and C which
187 * have been assigned shares 1000, 2000 and 3000 respectively. Then,
188 * cpu bandwidth allocated by the scheduler to task groups A, B and C
191 * Bw(A) = 1000/(1000+2000+3000) * 100 = 16.66%
192 * Bw(B) = 2000/(1000+2000+3000) * 100 = 33.33%
193 * Bw(C) = 3000/(1000+2000+3000) * 100 = 50%
195 * The weight assigned to a task group's schedulable entities on every
196 * cpu (task_group.se[a_cpu]->load.weight) is derived from the task
197 * group's shares. For ex: lets say that task group A has been
198 * assigned shares of 1000 and there are two CPUs in a system. Then,
200 * tg_A->se[0]->load.weight = tg_A->se[1]->load.weight = 1000;
202 * Note: It's not necessary that each of a task's group schedulable
203 * entity have the same weight on all CPUs. If the group
204 * has 2 of its tasks on CPU0 and 1 task on CPU1, then a
205 * better distribution of weight could be:
207 * tg_A->se[0]->load.weight = 2/3 * 2000 = 1333
208 * tg_A->se[1]->load.weight = 1/2 * 2000 = 667
210 * rebalance_shares() is responsible for distributing the shares of a
211 * task groups like this among the group's schedulable entities across
215 unsigned long shares
;
218 struct list_head list
;
221 /* Default task group's sched entity on each cpu */
222 static DEFINE_PER_CPU(struct sched_entity
, init_sched_entity
);
223 /* Default task group's cfs_rq on each cpu */
224 static DEFINE_PER_CPU(struct cfs_rq
, init_cfs_rq
) ____cacheline_aligned_in_smp
;
226 static DEFINE_PER_CPU(struct sched_rt_entity
, init_sched_rt_entity
);
227 static DEFINE_PER_CPU(struct rt_rq
, init_rt_rq
) ____cacheline_aligned_in_smp
;
229 static struct sched_entity
*init_sched_entity_p
[NR_CPUS
];
230 static struct cfs_rq
*init_cfs_rq_p
[NR_CPUS
];
232 static struct sched_rt_entity
*init_sched_rt_entity_p
[NR_CPUS
];
233 static struct rt_rq
*init_rt_rq_p
[NR_CPUS
];
235 /* task_group_lock serializes add/remove of task groups and also changes to
236 * a task group's cpu shares.
238 static DEFINE_SPINLOCK(task_group_lock
);
240 /* doms_cur_mutex serializes access to doms_cur[] array */
241 static DEFINE_MUTEX(doms_cur_mutex
);
244 /* kernel thread that runs rebalance_shares() periodically */
245 static struct task_struct
*lb_monitor_task
;
246 static int load_balance_monitor(void *unused
);
249 static void set_se_shares(struct sched_entity
*se
, unsigned long shares
);
251 /* Default task group.
252 * Every task in system belong to this group at bootup.
254 struct task_group init_task_group
= {
255 .se
= init_sched_entity_p
,
256 .cfs_rq
= init_cfs_rq_p
,
258 .rt_se
= init_sched_rt_entity_p
,
259 .rt_rq
= init_rt_rq_p
,
262 #ifdef CONFIG_FAIR_USER_SCHED
263 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
265 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
268 #define MIN_GROUP_SHARES 2
270 static int init_task_group_load
= INIT_TASK_GROUP_LOAD
;
272 /* return group to which a task belongs */
273 static inline struct task_group
*task_group(struct task_struct
*p
)
275 struct task_group
*tg
;
277 #ifdef CONFIG_FAIR_USER_SCHED
279 #elif defined(CONFIG_FAIR_CGROUP_SCHED)
280 tg
= container_of(task_subsys_state(p
, cpu_cgroup_subsys_id
),
281 struct task_group
, css
);
283 tg
= &init_task_group
;
288 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
289 static inline void set_task_rq(struct task_struct
*p
, unsigned int cpu
)
291 p
->se
.cfs_rq
= task_group(p
)->cfs_rq
[cpu
];
292 p
->se
.parent
= task_group(p
)->se
[cpu
];
294 p
->rt
.rt_rq
= task_group(p
)->rt_rq
[cpu
];
295 p
->rt
.parent
= task_group(p
)->rt_se
[cpu
];
298 static inline void lock_doms_cur(void)
300 mutex_lock(&doms_cur_mutex
);
303 static inline void unlock_doms_cur(void)
305 mutex_unlock(&doms_cur_mutex
);
310 static inline void set_task_rq(struct task_struct
*p
, unsigned int cpu
) { }
311 static inline void lock_doms_cur(void) { }
312 static inline void unlock_doms_cur(void) { }
314 #endif /* CONFIG_FAIR_GROUP_SCHED */
316 /* CFS-related fields in a runqueue */
318 struct load_weight load
;
319 unsigned long nr_running
;
324 struct rb_root tasks_timeline
;
325 struct rb_node
*rb_leftmost
;
326 struct rb_node
*rb_load_balance_curr
;
327 /* 'curr' points to currently running entity on this cfs_rq.
328 * It is set to NULL otherwise (i.e when none are currently running).
330 struct sched_entity
*curr
;
332 unsigned long nr_spread_over
;
334 #ifdef CONFIG_FAIR_GROUP_SCHED
335 struct rq
*rq
; /* cpu runqueue to which this cfs_rq is attached */
338 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
339 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
340 * (like users, containers etc.)
342 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
343 * list is used during load balance.
345 struct list_head leaf_cfs_rq_list
;
346 struct task_group
*tg
; /* group that "owns" this runqueue */
350 /* Real-Time classes' related field in a runqueue: */
352 struct rt_prio_array active
;
353 unsigned long rt_nr_running
;
354 #if defined CONFIG_SMP || defined CONFIG_FAIR_GROUP_SCHED
355 int highest_prio
; /* highest queued rt task prio */
358 unsigned long rt_nr_migratory
;
364 #ifdef CONFIG_FAIR_GROUP_SCHED
366 struct list_head leaf_rt_rq_list
;
367 struct task_group
*tg
;
368 struct sched_rt_entity
*rt_se
;
375 * We add the notion of a root-domain which will be used to define per-domain
376 * variables. Each exclusive cpuset essentially defines an island domain by
377 * fully partitioning the member cpus from any other cpuset. Whenever a new
378 * exclusive cpuset is created, we also create and attach a new root-domain
388 * The "RT overload" flag: it gets set if a CPU has more than
389 * one runnable RT task.
396 * By default the system creates a single root-domain with all cpus as
397 * members (mimicking the global state we have today).
399 static struct root_domain def_root_domain
;
404 * This is the main, per-CPU runqueue data structure.
406 * Locking rule: those places that want to lock multiple runqueues
407 * (such as the load balancing or the thread migration code), lock
408 * acquire operations must be ordered by ascending &runqueue.
415 * nr_running and cpu_load should be in the same cacheline because
416 * remote CPUs use both these fields when doing load calculation.
418 unsigned long nr_running
;
419 #define CPU_LOAD_IDX_MAX 5
420 unsigned long cpu_load
[CPU_LOAD_IDX_MAX
];
421 unsigned char idle_at_tick
;
423 unsigned char in_nohz_recently
;
425 /* capture load from *all* tasks on this cpu: */
426 struct load_weight load
;
427 unsigned long nr_load_updates
;
432 u64 rt_period_expire
;
435 #ifdef CONFIG_FAIR_GROUP_SCHED
436 /* list of leaf cfs_rq on this cpu: */
437 struct list_head leaf_cfs_rq_list
;
438 struct list_head leaf_rt_rq_list
;
442 * This is part of a global counter where only the total sum
443 * over all CPUs matters. A task can increase this counter on
444 * one CPU and if it got migrated afterwards it may decrease
445 * it on another CPU. Always updated under the runqueue lock:
447 unsigned long nr_uninterruptible
;
449 struct task_struct
*curr
, *idle
;
450 unsigned long next_balance
;
451 struct mm_struct
*prev_mm
;
453 u64 clock
, prev_clock_raw
;
456 unsigned int clock_warps
, clock_overflows
, clock_underflows
;
458 unsigned int clock_deep_idle_events
;
464 struct root_domain
*rd
;
465 struct sched_domain
*sd
;
467 /* For active balancing */
470 /* cpu of this runqueue: */
473 struct task_struct
*migration_thread
;
474 struct list_head migration_queue
;
477 #ifdef CONFIG_SCHED_HRTICK
478 unsigned long hrtick_flags
;
479 ktime_t hrtick_expire
;
480 struct hrtimer hrtick_timer
;
483 #ifdef CONFIG_SCHEDSTATS
485 struct sched_info rq_sched_info
;
487 /* sys_sched_yield() stats */
488 unsigned int yld_exp_empty
;
489 unsigned int yld_act_empty
;
490 unsigned int yld_both_empty
;
491 unsigned int yld_count
;
493 /* schedule() stats */
494 unsigned int sched_switch
;
495 unsigned int sched_count
;
496 unsigned int sched_goidle
;
498 /* try_to_wake_up() stats */
499 unsigned int ttwu_count
;
500 unsigned int ttwu_local
;
503 unsigned int bkl_count
;
505 struct lock_class_key rq_lock_key
;
508 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq
, runqueues
);
510 static inline void check_preempt_curr(struct rq
*rq
, struct task_struct
*p
)
512 rq
->curr
->sched_class
->check_preempt_curr(rq
, p
);
515 static inline int cpu_of(struct rq
*rq
)
525 * Update the per-runqueue clock, as finegrained as the platform can give
526 * us, but without assuming monotonicity, etc.:
528 static void __update_rq_clock(struct rq
*rq
)
530 u64 prev_raw
= rq
->prev_clock_raw
;
531 u64 now
= sched_clock();
532 s64 delta
= now
- prev_raw
;
533 u64 clock
= rq
->clock
;
535 #ifdef CONFIG_SCHED_DEBUG
536 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
539 * Protect against sched_clock() occasionally going backwards:
541 if (unlikely(delta
< 0)) {
546 * Catch too large forward jumps too:
548 if (unlikely(clock
+ delta
> rq
->tick_timestamp
+ TICK_NSEC
)) {
549 if (clock
< rq
->tick_timestamp
+ TICK_NSEC
)
550 clock
= rq
->tick_timestamp
+ TICK_NSEC
;
553 rq
->clock_overflows
++;
555 if (unlikely(delta
> rq
->clock_max_delta
))
556 rq
->clock_max_delta
= delta
;
561 rq
->prev_clock_raw
= now
;
565 static void update_rq_clock(struct rq
*rq
)
567 if (likely(smp_processor_id() == cpu_of(rq
)))
568 __update_rq_clock(rq
);
572 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
573 * See detach_destroy_domains: synchronize_sched for details.
575 * The domain tree of any CPU may only be accessed from within
576 * preempt-disabled sections.
578 #define for_each_domain(cpu, __sd) \
579 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
581 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
582 #define this_rq() (&__get_cpu_var(runqueues))
583 #define task_rq(p) cpu_rq(task_cpu(p))
584 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
586 unsigned long rt_needs_cpu(int cpu
)
588 struct rq
*rq
= cpu_rq(cpu
);
591 if (!rq
->rt_throttled
)
594 if (rq
->clock
> rq
->rt_period_expire
)
597 delta
= rq
->rt_period_expire
- rq
->clock
;
598 do_div(delta
, NSEC_PER_SEC
/ HZ
);
600 return (unsigned long)delta
;
604 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
606 #ifdef CONFIG_SCHED_DEBUG
607 # define const_debug __read_mostly
609 # define const_debug static const
613 * Debugging: various feature bits
616 SCHED_FEAT_NEW_FAIR_SLEEPERS
= 1,
617 SCHED_FEAT_WAKEUP_PREEMPT
= 2,
618 SCHED_FEAT_START_DEBIT
= 4,
619 SCHED_FEAT_TREE_AVG
= 8,
620 SCHED_FEAT_APPROX_AVG
= 16,
621 SCHED_FEAT_HRTICK
= 32,
622 SCHED_FEAT_DOUBLE_TICK
= 64,
625 const_debug
unsigned int sysctl_sched_features
=
626 SCHED_FEAT_NEW_FAIR_SLEEPERS
* 1 |
627 SCHED_FEAT_WAKEUP_PREEMPT
* 1 |
628 SCHED_FEAT_START_DEBIT
* 1 |
629 SCHED_FEAT_TREE_AVG
* 0 |
630 SCHED_FEAT_APPROX_AVG
* 0 |
631 SCHED_FEAT_HRTICK
* 1 |
632 SCHED_FEAT_DOUBLE_TICK
* 0;
634 #define sched_feat(x) (sysctl_sched_features & SCHED_FEAT_##x)
637 * Number of tasks to iterate in a single balance run.
638 * Limited because this is done with IRQs disabled.
640 const_debug
unsigned int sysctl_sched_nr_migrate
= 32;
643 * period over which we measure -rt task cpu usage in ms.
646 const_debug
unsigned int sysctl_sched_rt_period
= 1000;
648 #define SCHED_RT_FRAC_SHIFT 16
649 #define SCHED_RT_FRAC (1UL << SCHED_RT_FRAC_SHIFT)
652 * ratio of time -rt tasks may consume.
655 const_debug
unsigned int sysctl_sched_rt_ratio
= 62259;
658 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
659 * clock constructed from sched_clock():
661 unsigned long long cpu_clock(int cpu
)
663 unsigned long long now
;
667 local_irq_save(flags
);
670 * Only call sched_clock() if the scheduler has already been
671 * initialized (some code might call cpu_clock() very early):
676 local_irq_restore(flags
);
680 EXPORT_SYMBOL_GPL(cpu_clock
);
682 #ifndef prepare_arch_switch
683 # define prepare_arch_switch(next) do { } while (0)
685 #ifndef finish_arch_switch
686 # define finish_arch_switch(prev) do { } while (0)
689 static inline int task_current(struct rq
*rq
, struct task_struct
*p
)
691 return rq
->curr
== p
;
694 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
695 static inline int task_running(struct rq
*rq
, struct task_struct
*p
)
697 return task_current(rq
, p
);
700 static inline void prepare_lock_switch(struct rq
*rq
, struct task_struct
*next
)
704 static inline void finish_lock_switch(struct rq
*rq
, struct task_struct
*prev
)
706 #ifdef CONFIG_DEBUG_SPINLOCK
707 /* this is a valid case when another task releases the spinlock */
708 rq
->lock
.owner
= current
;
711 * If we are tracking spinlock dependencies then we have to
712 * fix up the runqueue lock - which gets 'carried over' from
715 spin_acquire(&rq
->lock
.dep_map
, 0, 0, _THIS_IP_
);
717 spin_unlock_irq(&rq
->lock
);
720 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
721 static inline int task_running(struct rq
*rq
, struct task_struct
*p
)
726 return task_current(rq
, p
);
730 static inline void prepare_lock_switch(struct rq
*rq
, struct task_struct
*next
)
734 * We can optimise this out completely for !SMP, because the
735 * SMP rebalancing from interrupt is the only thing that cares
740 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
741 spin_unlock_irq(&rq
->lock
);
743 spin_unlock(&rq
->lock
);
747 static inline void finish_lock_switch(struct rq
*rq
, struct task_struct
*prev
)
751 * After ->oncpu is cleared, the task can be moved to a different CPU.
752 * We must ensure this doesn't happen until the switch is completely
758 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
762 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
765 * __task_rq_lock - lock the runqueue a given task resides on.
766 * Must be called interrupts disabled.
768 static inline struct rq
*__task_rq_lock(struct task_struct
*p
)
772 struct rq
*rq
= task_rq(p
);
773 spin_lock(&rq
->lock
);
774 if (likely(rq
== task_rq(p
)))
776 spin_unlock(&rq
->lock
);
781 * task_rq_lock - lock the runqueue a given task resides on and disable
782 * interrupts. Note the ordering: we can safely lookup the task_rq without
783 * explicitly disabling preemption.
785 static struct rq
*task_rq_lock(struct task_struct
*p
, unsigned long *flags
)
791 local_irq_save(*flags
);
793 spin_lock(&rq
->lock
);
794 if (likely(rq
== task_rq(p
)))
796 spin_unlock_irqrestore(&rq
->lock
, *flags
);
800 static void __task_rq_unlock(struct rq
*rq
)
803 spin_unlock(&rq
->lock
);
806 static inline void task_rq_unlock(struct rq
*rq
, unsigned long *flags
)
809 spin_unlock_irqrestore(&rq
->lock
, *flags
);
813 * this_rq_lock - lock this runqueue and disable interrupts.
815 static struct rq
*this_rq_lock(void)
822 spin_lock(&rq
->lock
);
828 * We are going deep-idle (irqs are disabled):
830 void sched_clock_idle_sleep_event(void)
832 struct rq
*rq
= cpu_rq(smp_processor_id());
834 spin_lock(&rq
->lock
);
835 __update_rq_clock(rq
);
836 spin_unlock(&rq
->lock
);
837 rq
->clock_deep_idle_events
++;
839 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event
);
842 * We just idled delta nanoseconds (called with irqs disabled):
844 void sched_clock_idle_wakeup_event(u64 delta_ns
)
846 struct rq
*rq
= cpu_rq(smp_processor_id());
847 u64 now
= sched_clock();
849 rq
->idle_clock
+= delta_ns
;
851 * Override the previous timestamp and ignore all
852 * sched_clock() deltas that occured while we idled,
853 * and use the PM-provided delta_ns to advance the
856 spin_lock(&rq
->lock
);
857 rq
->prev_clock_raw
= now
;
858 rq
->clock
+= delta_ns
;
859 spin_unlock(&rq
->lock
);
860 touch_softlockup_watchdog();
862 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event
);
864 static void __resched_task(struct task_struct
*p
, int tif_bit
);
866 static inline void resched_task(struct task_struct
*p
)
868 __resched_task(p
, TIF_NEED_RESCHED
);
871 #ifdef CONFIG_SCHED_HRTICK
873 * Use HR-timers to deliver accurate preemption points.
875 * Its all a bit involved since we cannot program an hrt while holding the
876 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
879 * When we get rescheduled we reprogram the hrtick_timer outside of the
882 static inline void resched_hrt(struct task_struct
*p
)
884 __resched_task(p
, TIF_HRTICK_RESCHED
);
887 static inline void resched_rq(struct rq
*rq
)
891 spin_lock_irqsave(&rq
->lock
, flags
);
892 resched_task(rq
->curr
);
893 spin_unlock_irqrestore(&rq
->lock
, flags
);
897 HRTICK_SET
, /* re-programm hrtick_timer */
898 HRTICK_RESET
, /* not a new slice */
903 * - enabled by features
904 * - hrtimer is actually high res
906 static inline int hrtick_enabled(struct rq
*rq
)
908 if (!sched_feat(HRTICK
))
910 return hrtimer_is_hres_active(&rq
->hrtick_timer
);
914 * Called to set the hrtick timer state.
916 * called with rq->lock held and irqs disabled
918 static void hrtick_start(struct rq
*rq
, u64 delay
, int reset
)
920 assert_spin_locked(&rq
->lock
);
923 * preempt at: now + delay
926 ktime_add_ns(rq
->hrtick_timer
.base
->get_time(), delay
);
928 * indicate we need to program the timer
930 __set_bit(HRTICK_SET
, &rq
->hrtick_flags
);
932 __set_bit(HRTICK_RESET
, &rq
->hrtick_flags
);
935 * New slices are called from the schedule path and don't need a
939 resched_hrt(rq
->curr
);
942 static void hrtick_clear(struct rq
*rq
)
944 if (hrtimer_active(&rq
->hrtick_timer
))
945 hrtimer_cancel(&rq
->hrtick_timer
);
949 * Update the timer from the possible pending state.
951 static void hrtick_set(struct rq
*rq
)
957 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
959 spin_lock_irqsave(&rq
->lock
, flags
);
960 set
= __test_and_clear_bit(HRTICK_SET
, &rq
->hrtick_flags
);
961 reset
= __test_and_clear_bit(HRTICK_RESET
, &rq
->hrtick_flags
);
962 time
= rq
->hrtick_expire
;
963 clear_thread_flag(TIF_HRTICK_RESCHED
);
964 spin_unlock_irqrestore(&rq
->lock
, flags
);
967 hrtimer_start(&rq
->hrtick_timer
, time
, HRTIMER_MODE_ABS
);
968 if (reset
&& !hrtimer_active(&rq
->hrtick_timer
))
975 * High-resolution timer tick.
976 * Runs from hardirq context with interrupts disabled.
978 static enum hrtimer_restart
hrtick(struct hrtimer
*timer
)
980 struct rq
*rq
= container_of(timer
, struct rq
, hrtick_timer
);
982 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
984 spin_lock(&rq
->lock
);
985 __update_rq_clock(rq
);
986 rq
->curr
->sched_class
->task_tick(rq
, rq
->curr
, 1);
987 spin_unlock(&rq
->lock
);
989 return HRTIMER_NORESTART
;
992 static inline void init_rq_hrtick(struct rq
*rq
)
994 rq
->hrtick_flags
= 0;
995 hrtimer_init(&rq
->hrtick_timer
, CLOCK_MONOTONIC
, HRTIMER_MODE_REL
);
996 rq
->hrtick_timer
.function
= hrtick
;
997 rq
->hrtick_timer
.cb_mode
= HRTIMER_CB_IRQSAFE_NO_SOFTIRQ
;
1000 void hrtick_resched(void)
1003 unsigned long flags
;
1005 if (!test_thread_flag(TIF_HRTICK_RESCHED
))
1008 local_irq_save(flags
);
1009 rq
= cpu_rq(smp_processor_id());
1011 local_irq_restore(flags
);
1014 static inline void hrtick_clear(struct rq
*rq
)
1018 static inline void hrtick_set(struct rq
*rq
)
1022 static inline void init_rq_hrtick(struct rq
*rq
)
1026 void hrtick_resched(void)
1032 * resched_task - mark a task 'to be rescheduled now'.
1034 * On UP this means the setting of the need_resched flag, on SMP it
1035 * might also involve a cross-CPU call to trigger the scheduler on
1040 #ifndef tsk_is_polling
1041 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1044 static void __resched_task(struct task_struct
*p
, int tif_bit
)
1048 assert_spin_locked(&task_rq(p
)->lock
);
1050 if (unlikely(test_tsk_thread_flag(p
, tif_bit
)))
1053 set_tsk_thread_flag(p
, tif_bit
);
1056 if (cpu
== smp_processor_id())
1059 /* NEED_RESCHED must be visible before we test polling */
1061 if (!tsk_is_polling(p
))
1062 smp_send_reschedule(cpu
);
1065 static void resched_cpu(int cpu
)
1067 struct rq
*rq
= cpu_rq(cpu
);
1068 unsigned long flags
;
1070 if (!spin_trylock_irqsave(&rq
->lock
, flags
))
1072 resched_task(cpu_curr(cpu
));
1073 spin_unlock_irqrestore(&rq
->lock
, flags
);
1076 static void __resched_task(struct task_struct
*p
, int tif_bit
)
1078 assert_spin_locked(&task_rq(p
)->lock
);
1079 set_tsk_thread_flag(p
, tif_bit
);
1083 #if BITS_PER_LONG == 32
1084 # define WMULT_CONST (~0UL)
1086 # define WMULT_CONST (1UL << 32)
1089 #define WMULT_SHIFT 32
1092 * Shift right and round:
1094 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1096 static unsigned long
1097 calc_delta_mine(unsigned long delta_exec
, unsigned long weight
,
1098 struct load_weight
*lw
)
1102 if (unlikely(!lw
->inv_weight
))
1103 lw
->inv_weight
= (WMULT_CONST
- lw
->weight
/2) / lw
->weight
+ 1;
1105 tmp
= (u64
)delta_exec
* weight
;
1107 * Check whether we'd overflow the 64-bit multiplication:
1109 if (unlikely(tmp
> WMULT_CONST
))
1110 tmp
= SRR(SRR(tmp
, WMULT_SHIFT
/2) * lw
->inv_weight
,
1113 tmp
= SRR(tmp
* lw
->inv_weight
, WMULT_SHIFT
);
1115 return (unsigned long)min(tmp
, (u64
)(unsigned long)LONG_MAX
);
1118 static inline unsigned long
1119 calc_delta_fair(unsigned long delta_exec
, struct load_weight
*lw
)
1121 return calc_delta_mine(delta_exec
, NICE_0_LOAD
, lw
);
1124 static inline void update_load_add(struct load_weight
*lw
, unsigned long inc
)
1129 static inline void update_load_sub(struct load_weight
*lw
, unsigned long dec
)
1135 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1136 * of tasks with abnormal "nice" values across CPUs the contribution that
1137 * each task makes to its run queue's load is weighted according to its
1138 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1139 * scaled version of the new time slice allocation that they receive on time
1143 #define WEIGHT_IDLEPRIO 2
1144 #define WMULT_IDLEPRIO (1 << 31)
1147 * Nice levels are multiplicative, with a gentle 10% change for every
1148 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1149 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1150 * that remained on nice 0.
1152 * The "10% effect" is relative and cumulative: from _any_ nice level,
1153 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1154 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1155 * If a task goes up by ~10% and another task goes down by ~10% then
1156 * the relative distance between them is ~25%.)
1158 static const int prio_to_weight
[40] = {
1159 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1160 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1161 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1162 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1163 /* 0 */ 1024, 820, 655, 526, 423,
1164 /* 5 */ 335, 272, 215, 172, 137,
1165 /* 10 */ 110, 87, 70, 56, 45,
1166 /* 15 */ 36, 29, 23, 18, 15,
1170 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1172 * In cases where the weight does not change often, we can use the
1173 * precalculated inverse to speed up arithmetics by turning divisions
1174 * into multiplications:
1176 static const u32 prio_to_wmult
[40] = {
1177 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1178 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1179 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1180 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1181 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1182 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1183 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1184 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1187 static void activate_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
);
1190 * runqueue iterator, to support SMP load-balancing between different
1191 * scheduling classes, without having to expose their internal data
1192 * structures to the load-balancing proper:
1194 struct rq_iterator
{
1196 struct task_struct
*(*start
)(void *);
1197 struct task_struct
*(*next
)(void *);
1201 static unsigned long
1202 balance_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
1203 unsigned long max_load_move
, struct sched_domain
*sd
,
1204 enum cpu_idle_type idle
, int *all_pinned
,
1205 int *this_best_prio
, struct rq_iterator
*iterator
);
1208 iter_move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
1209 struct sched_domain
*sd
, enum cpu_idle_type idle
,
1210 struct rq_iterator
*iterator
);
1213 #ifdef CONFIG_CGROUP_CPUACCT
1214 static void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
);
1216 static inline void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
) {}
1219 static inline void inc_cpu_load(struct rq
*rq
, unsigned long load
)
1221 update_load_add(&rq
->load
, load
);
1224 static inline void dec_cpu_load(struct rq
*rq
, unsigned long load
)
1226 update_load_sub(&rq
->load
, load
);
1230 static unsigned long source_load(int cpu
, int type
);
1231 static unsigned long target_load(int cpu
, int type
);
1232 static unsigned long cpu_avg_load_per_task(int cpu
);
1233 static int task_hot(struct task_struct
*p
, u64 now
, struct sched_domain
*sd
);
1234 #endif /* CONFIG_SMP */
1236 #include "sched_stats.h"
1237 #include "sched_idletask.c"
1238 #include "sched_fair.c"
1239 #include "sched_rt.c"
1240 #ifdef CONFIG_SCHED_DEBUG
1241 # include "sched_debug.c"
1244 #define sched_class_highest (&rt_sched_class)
1246 static void inc_nr_running(struct rq
*rq
)
1251 static void dec_nr_running(struct rq
*rq
)
1256 static void set_load_weight(struct task_struct
*p
)
1258 if (task_has_rt_policy(p
)) {
1259 p
->se
.load
.weight
= prio_to_weight
[0] * 2;
1260 p
->se
.load
.inv_weight
= prio_to_wmult
[0] >> 1;
1265 * SCHED_IDLE tasks get minimal weight:
1267 if (p
->policy
== SCHED_IDLE
) {
1268 p
->se
.load
.weight
= WEIGHT_IDLEPRIO
;
1269 p
->se
.load
.inv_weight
= WMULT_IDLEPRIO
;
1273 p
->se
.load
.weight
= prio_to_weight
[p
->static_prio
- MAX_RT_PRIO
];
1274 p
->se
.load
.inv_weight
= prio_to_wmult
[p
->static_prio
- MAX_RT_PRIO
];
1277 static void enqueue_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
)
1279 sched_info_queued(p
);
1280 p
->sched_class
->enqueue_task(rq
, p
, wakeup
);
1284 static void dequeue_task(struct rq
*rq
, struct task_struct
*p
, int sleep
)
1286 p
->sched_class
->dequeue_task(rq
, p
, sleep
);
1291 * __normal_prio - return the priority that is based on the static prio
1293 static inline int __normal_prio(struct task_struct
*p
)
1295 return p
->static_prio
;
1299 * Calculate the expected normal priority: i.e. priority
1300 * without taking RT-inheritance into account. Might be
1301 * boosted by interactivity modifiers. Changes upon fork,
1302 * setprio syscalls, and whenever the interactivity
1303 * estimator recalculates.
1305 static inline int normal_prio(struct task_struct
*p
)
1309 if (task_has_rt_policy(p
))
1310 prio
= MAX_RT_PRIO
-1 - p
->rt_priority
;
1312 prio
= __normal_prio(p
);
1317 * Calculate the current priority, i.e. the priority
1318 * taken into account by the scheduler. This value might
1319 * be boosted by RT tasks, or might be boosted by
1320 * interactivity modifiers. Will be RT if the task got
1321 * RT-boosted. If not then it returns p->normal_prio.
1323 static int effective_prio(struct task_struct
*p
)
1325 p
->normal_prio
= normal_prio(p
);
1327 * If we are RT tasks or we were boosted to RT priority,
1328 * keep the priority unchanged. Otherwise, update priority
1329 * to the normal priority:
1331 if (!rt_prio(p
->prio
))
1332 return p
->normal_prio
;
1337 * activate_task - move a task to the runqueue.
1339 static void activate_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
)
1341 if (task_contributes_to_load(p
))
1342 rq
->nr_uninterruptible
--;
1344 enqueue_task(rq
, p
, wakeup
);
1349 * deactivate_task - remove a task from the runqueue.
1351 static void deactivate_task(struct rq
*rq
, struct task_struct
*p
, int sleep
)
1353 if (task_contributes_to_load(p
))
1354 rq
->nr_uninterruptible
++;
1356 dequeue_task(rq
, p
, sleep
);
1361 * task_curr - is this task currently executing on a CPU?
1362 * @p: the task in question.
1364 inline int task_curr(const struct task_struct
*p
)
1366 return cpu_curr(task_cpu(p
)) == p
;
1369 /* Used instead of source_load when we know the type == 0 */
1370 unsigned long weighted_cpuload(const int cpu
)
1372 return cpu_rq(cpu
)->load
.weight
;
1375 static inline void __set_task_cpu(struct task_struct
*p
, unsigned int cpu
)
1377 set_task_rq(p
, cpu
);
1380 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1381 * successfuly executed on another CPU. We must ensure that updates of
1382 * per-task data have been completed by this moment.
1385 task_thread_info(p
)->cpu
= cpu
;
1389 static inline void check_class_changed(struct rq
*rq
, struct task_struct
*p
,
1390 const struct sched_class
*prev_class
,
1391 int oldprio
, int running
)
1393 if (prev_class
!= p
->sched_class
) {
1394 if (prev_class
->switched_from
)
1395 prev_class
->switched_from(rq
, p
, running
);
1396 p
->sched_class
->switched_to(rq
, p
, running
);
1398 p
->sched_class
->prio_changed(rq
, p
, oldprio
, running
);
1404 * Is this task likely cache-hot:
1407 task_hot(struct task_struct
*p
, u64 now
, struct sched_domain
*sd
)
1411 if (p
->sched_class
!= &fair_sched_class
)
1414 if (sysctl_sched_migration_cost
== -1)
1416 if (sysctl_sched_migration_cost
== 0)
1419 delta
= now
- p
->se
.exec_start
;
1421 return delta
< (s64
)sysctl_sched_migration_cost
;
1425 void set_task_cpu(struct task_struct
*p
, unsigned int new_cpu
)
1427 int old_cpu
= task_cpu(p
);
1428 struct rq
*old_rq
= cpu_rq(old_cpu
), *new_rq
= cpu_rq(new_cpu
);
1429 struct cfs_rq
*old_cfsrq
= task_cfs_rq(p
),
1430 *new_cfsrq
= cpu_cfs_rq(old_cfsrq
, new_cpu
);
1433 clock_offset
= old_rq
->clock
- new_rq
->clock
;
1435 #ifdef CONFIG_SCHEDSTATS
1436 if (p
->se
.wait_start
)
1437 p
->se
.wait_start
-= clock_offset
;
1438 if (p
->se
.sleep_start
)
1439 p
->se
.sleep_start
-= clock_offset
;
1440 if (p
->se
.block_start
)
1441 p
->se
.block_start
-= clock_offset
;
1442 if (old_cpu
!= new_cpu
) {
1443 schedstat_inc(p
, se
.nr_migrations
);
1444 if (task_hot(p
, old_rq
->clock
, NULL
))
1445 schedstat_inc(p
, se
.nr_forced2_migrations
);
1448 p
->se
.vruntime
-= old_cfsrq
->min_vruntime
-
1449 new_cfsrq
->min_vruntime
;
1451 __set_task_cpu(p
, new_cpu
);
1454 struct migration_req
{
1455 struct list_head list
;
1457 struct task_struct
*task
;
1460 struct completion done
;
1464 * The task's runqueue lock must be held.
1465 * Returns true if you have to wait for migration thread.
1468 migrate_task(struct task_struct
*p
, int dest_cpu
, struct migration_req
*req
)
1470 struct rq
*rq
= task_rq(p
);
1473 * If the task is not on a runqueue (and not running), then
1474 * it is sufficient to simply update the task's cpu field.
1476 if (!p
->se
.on_rq
&& !task_running(rq
, p
)) {
1477 set_task_cpu(p
, dest_cpu
);
1481 init_completion(&req
->done
);
1483 req
->dest_cpu
= dest_cpu
;
1484 list_add(&req
->list
, &rq
->migration_queue
);
1490 * wait_task_inactive - wait for a thread to unschedule.
1492 * The caller must ensure that the task *will* unschedule sometime soon,
1493 * else this function might spin for a *long* time. This function can't
1494 * be called with interrupts off, or it may introduce deadlock with
1495 * smp_call_function() if an IPI is sent by the same process we are
1496 * waiting to become inactive.
1498 void wait_task_inactive(struct task_struct
*p
)
1500 unsigned long flags
;
1506 * We do the initial early heuristics without holding
1507 * any task-queue locks at all. We'll only try to get
1508 * the runqueue lock when things look like they will
1514 * If the task is actively running on another CPU
1515 * still, just relax and busy-wait without holding
1518 * NOTE! Since we don't hold any locks, it's not
1519 * even sure that "rq" stays as the right runqueue!
1520 * But we don't care, since "task_running()" will
1521 * return false if the runqueue has changed and p
1522 * is actually now running somewhere else!
1524 while (task_running(rq
, p
))
1528 * Ok, time to look more closely! We need the rq
1529 * lock now, to be *sure*. If we're wrong, we'll
1530 * just go back and repeat.
1532 rq
= task_rq_lock(p
, &flags
);
1533 running
= task_running(rq
, p
);
1534 on_rq
= p
->se
.on_rq
;
1535 task_rq_unlock(rq
, &flags
);
1538 * Was it really running after all now that we
1539 * checked with the proper locks actually held?
1541 * Oops. Go back and try again..
1543 if (unlikely(running
)) {
1549 * It's not enough that it's not actively running,
1550 * it must be off the runqueue _entirely_, and not
1553 * So if it wa still runnable (but just not actively
1554 * running right now), it's preempted, and we should
1555 * yield - it could be a while.
1557 if (unlikely(on_rq
)) {
1558 schedule_timeout_uninterruptible(1);
1563 * Ahh, all good. It wasn't running, and it wasn't
1564 * runnable, which means that it will never become
1565 * running in the future either. We're all done!
1572 * kick_process - kick a running thread to enter/exit the kernel
1573 * @p: the to-be-kicked thread
1575 * Cause a process which is running on another CPU to enter
1576 * kernel-mode, without any delay. (to get signals handled.)
1578 * NOTE: this function doesnt have to take the runqueue lock,
1579 * because all it wants to ensure is that the remote task enters
1580 * the kernel. If the IPI races and the task has been migrated
1581 * to another CPU then no harm is done and the purpose has been
1584 void kick_process(struct task_struct
*p
)
1590 if ((cpu
!= smp_processor_id()) && task_curr(p
))
1591 smp_send_reschedule(cpu
);
1596 * Return a low guess at the load of a migration-source cpu weighted
1597 * according to the scheduling class and "nice" value.
1599 * We want to under-estimate the load of migration sources, to
1600 * balance conservatively.
1602 static unsigned long source_load(int cpu
, int type
)
1604 struct rq
*rq
= cpu_rq(cpu
);
1605 unsigned long total
= weighted_cpuload(cpu
);
1610 return min(rq
->cpu_load
[type
-1], total
);
1614 * Return a high guess at the load of a migration-target cpu weighted
1615 * according to the scheduling class and "nice" value.
1617 static unsigned long target_load(int cpu
, int type
)
1619 struct rq
*rq
= cpu_rq(cpu
);
1620 unsigned long total
= weighted_cpuload(cpu
);
1625 return max(rq
->cpu_load
[type
-1], total
);
1629 * Return the average load per task on the cpu's run queue
1631 static unsigned long cpu_avg_load_per_task(int cpu
)
1633 struct rq
*rq
= cpu_rq(cpu
);
1634 unsigned long total
= weighted_cpuload(cpu
);
1635 unsigned long n
= rq
->nr_running
;
1637 return n
? total
/ n
: SCHED_LOAD_SCALE
;
1641 * find_idlest_group finds and returns the least busy CPU group within the
1644 static struct sched_group
*
1645 find_idlest_group(struct sched_domain
*sd
, struct task_struct
*p
, int this_cpu
)
1647 struct sched_group
*idlest
= NULL
, *this = NULL
, *group
= sd
->groups
;
1648 unsigned long min_load
= ULONG_MAX
, this_load
= 0;
1649 int load_idx
= sd
->forkexec_idx
;
1650 int imbalance
= 100 + (sd
->imbalance_pct
-100)/2;
1653 unsigned long load
, avg_load
;
1657 /* Skip over this group if it has no CPUs allowed */
1658 if (!cpus_intersects(group
->cpumask
, p
->cpus_allowed
))
1661 local_group
= cpu_isset(this_cpu
, group
->cpumask
);
1663 /* Tally up the load of all CPUs in the group */
1666 for_each_cpu_mask(i
, group
->cpumask
) {
1667 /* Bias balancing toward cpus of our domain */
1669 load
= source_load(i
, load_idx
);
1671 load
= target_load(i
, load_idx
);
1676 /* Adjust by relative CPU power of the group */
1677 avg_load
= sg_div_cpu_power(group
,
1678 avg_load
* SCHED_LOAD_SCALE
);
1681 this_load
= avg_load
;
1683 } else if (avg_load
< min_load
) {
1684 min_load
= avg_load
;
1687 } while (group
= group
->next
, group
!= sd
->groups
);
1689 if (!idlest
|| 100*this_load
< imbalance
*min_load
)
1695 * find_idlest_cpu - find the idlest cpu among the cpus in group.
1698 find_idlest_cpu(struct sched_group
*group
, struct task_struct
*p
, int this_cpu
)
1701 unsigned long load
, min_load
= ULONG_MAX
;
1705 /* Traverse only the allowed CPUs */
1706 cpus_and(tmp
, group
->cpumask
, p
->cpus_allowed
);
1708 for_each_cpu_mask(i
, tmp
) {
1709 load
= weighted_cpuload(i
);
1711 if (load
< min_load
|| (load
== min_load
&& i
== this_cpu
)) {
1721 * sched_balance_self: balance the current task (running on cpu) in domains
1722 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1725 * Balance, ie. select the least loaded group.
1727 * Returns the target CPU number, or the same CPU if no balancing is needed.
1729 * preempt must be disabled.
1731 static int sched_balance_self(int cpu
, int flag
)
1733 struct task_struct
*t
= current
;
1734 struct sched_domain
*tmp
, *sd
= NULL
;
1736 for_each_domain(cpu
, tmp
) {
1738 * If power savings logic is enabled for a domain, stop there.
1740 if (tmp
->flags
& SD_POWERSAVINGS_BALANCE
)
1742 if (tmp
->flags
& flag
)
1748 struct sched_group
*group
;
1749 int new_cpu
, weight
;
1751 if (!(sd
->flags
& flag
)) {
1757 group
= find_idlest_group(sd
, t
, cpu
);
1763 new_cpu
= find_idlest_cpu(group
, t
, cpu
);
1764 if (new_cpu
== -1 || new_cpu
== cpu
) {
1765 /* Now try balancing at a lower domain level of cpu */
1770 /* Now try balancing at a lower domain level of new_cpu */
1773 weight
= cpus_weight(span
);
1774 for_each_domain(cpu
, tmp
) {
1775 if (weight
<= cpus_weight(tmp
->span
))
1777 if (tmp
->flags
& flag
)
1780 /* while loop will break here if sd == NULL */
1786 #endif /* CONFIG_SMP */
1789 * try_to_wake_up - wake up a thread
1790 * @p: the to-be-woken-up thread
1791 * @state: the mask of task states that can be woken
1792 * @sync: do a synchronous wakeup?
1794 * Put it on the run-queue if it's not already there. The "current"
1795 * thread is always on the run-queue (except when the actual
1796 * re-schedule is in progress), and as such you're allowed to do
1797 * the simpler "current->state = TASK_RUNNING" to mark yourself
1798 * runnable without the overhead of this.
1800 * returns failure only if the task is already active.
1802 static int try_to_wake_up(struct task_struct
*p
, unsigned int state
, int sync
)
1804 int cpu
, orig_cpu
, this_cpu
, success
= 0;
1805 unsigned long flags
;
1809 rq
= task_rq_lock(p
, &flags
);
1810 old_state
= p
->state
;
1811 if (!(old_state
& state
))
1819 this_cpu
= smp_processor_id();
1822 if (unlikely(task_running(rq
, p
)))
1825 cpu
= p
->sched_class
->select_task_rq(p
, sync
);
1826 if (cpu
!= orig_cpu
) {
1827 set_task_cpu(p
, cpu
);
1828 task_rq_unlock(rq
, &flags
);
1829 /* might preempt at this point */
1830 rq
= task_rq_lock(p
, &flags
);
1831 old_state
= p
->state
;
1832 if (!(old_state
& state
))
1837 this_cpu
= smp_processor_id();
1841 #ifdef CONFIG_SCHEDSTATS
1842 schedstat_inc(rq
, ttwu_count
);
1843 if (cpu
== this_cpu
)
1844 schedstat_inc(rq
, ttwu_local
);
1846 struct sched_domain
*sd
;
1847 for_each_domain(this_cpu
, sd
) {
1848 if (cpu_isset(cpu
, sd
->span
)) {
1849 schedstat_inc(sd
, ttwu_wake_remote
);
1857 #endif /* CONFIG_SMP */
1858 schedstat_inc(p
, se
.nr_wakeups
);
1860 schedstat_inc(p
, se
.nr_wakeups_sync
);
1861 if (orig_cpu
!= cpu
)
1862 schedstat_inc(p
, se
.nr_wakeups_migrate
);
1863 if (cpu
== this_cpu
)
1864 schedstat_inc(p
, se
.nr_wakeups_local
);
1866 schedstat_inc(p
, se
.nr_wakeups_remote
);
1867 update_rq_clock(rq
);
1868 activate_task(rq
, p
, 1);
1869 check_preempt_curr(rq
, p
);
1873 p
->state
= TASK_RUNNING
;
1875 if (p
->sched_class
->task_wake_up
)
1876 p
->sched_class
->task_wake_up(rq
, p
);
1879 task_rq_unlock(rq
, &flags
);
1884 int wake_up_process(struct task_struct
*p
)
1886 return try_to_wake_up(p
, TASK_ALL
, 0);
1888 EXPORT_SYMBOL(wake_up_process
);
1890 int wake_up_state(struct task_struct
*p
, unsigned int state
)
1892 return try_to_wake_up(p
, state
, 0);
1896 * Perform scheduler related setup for a newly forked process p.
1897 * p is forked by current.
1899 * __sched_fork() is basic setup used by init_idle() too:
1901 static void __sched_fork(struct task_struct
*p
)
1903 p
->se
.exec_start
= 0;
1904 p
->se
.sum_exec_runtime
= 0;
1905 p
->se
.prev_sum_exec_runtime
= 0;
1907 #ifdef CONFIG_SCHEDSTATS
1908 p
->se
.wait_start
= 0;
1909 p
->se
.sum_sleep_runtime
= 0;
1910 p
->se
.sleep_start
= 0;
1911 p
->se
.block_start
= 0;
1912 p
->se
.sleep_max
= 0;
1913 p
->se
.block_max
= 0;
1915 p
->se
.slice_max
= 0;
1919 INIT_LIST_HEAD(&p
->rt
.run_list
);
1922 #ifdef CONFIG_PREEMPT_NOTIFIERS
1923 INIT_HLIST_HEAD(&p
->preempt_notifiers
);
1927 * We mark the process as running here, but have not actually
1928 * inserted it onto the runqueue yet. This guarantees that
1929 * nobody will actually run it, and a signal or other external
1930 * event cannot wake it up and insert it on the runqueue either.
1932 p
->state
= TASK_RUNNING
;
1936 * fork()/clone()-time setup:
1938 void sched_fork(struct task_struct
*p
, int clone_flags
)
1940 int cpu
= get_cpu();
1945 cpu
= sched_balance_self(cpu
, SD_BALANCE_FORK
);
1947 set_task_cpu(p
, cpu
);
1950 * Make sure we do not leak PI boosting priority to the child:
1952 p
->prio
= current
->normal_prio
;
1953 if (!rt_prio(p
->prio
))
1954 p
->sched_class
= &fair_sched_class
;
1956 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
1957 if (likely(sched_info_on()))
1958 memset(&p
->sched_info
, 0, sizeof(p
->sched_info
));
1960 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
1963 #ifdef CONFIG_PREEMPT
1964 /* Want to start with kernel preemption disabled. */
1965 task_thread_info(p
)->preempt_count
= 1;
1971 * wake_up_new_task - wake up a newly created task for the first time.
1973 * This function will do some initial scheduler statistics housekeeping
1974 * that must be done for every newly created context, then puts the task
1975 * on the runqueue and wakes it.
1977 void wake_up_new_task(struct task_struct
*p
, unsigned long clone_flags
)
1979 unsigned long flags
;
1982 rq
= task_rq_lock(p
, &flags
);
1983 BUG_ON(p
->state
!= TASK_RUNNING
);
1984 update_rq_clock(rq
);
1986 p
->prio
= effective_prio(p
);
1988 if (!p
->sched_class
->task_new
|| !current
->se
.on_rq
) {
1989 activate_task(rq
, p
, 0);
1992 * Let the scheduling class do new task startup
1993 * management (if any):
1995 p
->sched_class
->task_new(rq
, p
);
1998 check_preempt_curr(rq
, p
);
2000 if (p
->sched_class
->task_wake_up
)
2001 p
->sched_class
->task_wake_up(rq
, p
);
2003 task_rq_unlock(rq
, &flags
);
2006 #ifdef CONFIG_PREEMPT_NOTIFIERS
2009 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
2010 * @notifier: notifier struct to register
2012 void preempt_notifier_register(struct preempt_notifier
*notifier
)
2014 hlist_add_head(¬ifier
->link
, ¤t
->preempt_notifiers
);
2016 EXPORT_SYMBOL_GPL(preempt_notifier_register
);
2019 * preempt_notifier_unregister - no longer interested in preemption notifications
2020 * @notifier: notifier struct to unregister
2022 * This is safe to call from within a preemption notifier.
2024 void preempt_notifier_unregister(struct preempt_notifier
*notifier
)
2026 hlist_del(¬ifier
->link
);
2028 EXPORT_SYMBOL_GPL(preempt_notifier_unregister
);
2030 static void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2032 struct preempt_notifier
*notifier
;
2033 struct hlist_node
*node
;
2035 hlist_for_each_entry(notifier
, node
, &curr
->preempt_notifiers
, link
)
2036 notifier
->ops
->sched_in(notifier
, raw_smp_processor_id());
2040 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2041 struct task_struct
*next
)
2043 struct preempt_notifier
*notifier
;
2044 struct hlist_node
*node
;
2046 hlist_for_each_entry(notifier
, node
, &curr
->preempt_notifiers
, link
)
2047 notifier
->ops
->sched_out(notifier
, next
);
2052 static void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2057 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2058 struct task_struct
*next
)
2065 * prepare_task_switch - prepare to switch tasks
2066 * @rq: the runqueue preparing to switch
2067 * @prev: the current task that is being switched out
2068 * @next: the task we are going to switch to.
2070 * This is called with the rq lock held and interrupts off. It must
2071 * be paired with a subsequent finish_task_switch after the context
2074 * prepare_task_switch sets up locking and calls architecture specific
2078 prepare_task_switch(struct rq
*rq
, struct task_struct
*prev
,
2079 struct task_struct
*next
)
2081 fire_sched_out_preempt_notifiers(prev
, next
);
2082 prepare_lock_switch(rq
, next
);
2083 prepare_arch_switch(next
);
2087 * finish_task_switch - clean up after a task-switch
2088 * @rq: runqueue associated with task-switch
2089 * @prev: the thread we just switched away from.
2091 * finish_task_switch must be called after the context switch, paired
2092 * with a prepare_task_switch call before the context switch.
2093 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2094 * and do any other architecture-specific cleanup actions.
2096 * Note that we may have delayed dropping an mm in context_switch(). If
2097 * so, we finish that here outside of the runqueue lock. (Doing it
2098 * with the lock held can cause deadlocks; see schedule() for
2101 static void finish_task_switch(struct rq
*rq
, struct task_struct
*prev
)
2102 __releases(rq
->lock
)
2104 struct mm_struct
*mm
= rq
->prev_mm
;
2110 * A task struct has one reference for the use as "current".
2111 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2112 * schedule one last time. The schedule call will never return, and
2113 * the scheduled task must drop that reference.
2114 * The test for TASK_DEAD must occur while the runqueue locks are
2115 * still held, otherwise prev could be scheduled on another cpu, die
2116 * there before we look at prev->state, and then the reference would
2118 * Manfred Spraul <manfred@colorfullife.com>
2120 prev_state
= prev
->state
;
2121 finish_arch_switch(prev
);
2122 finish_lock_switch(rq
, prev
);
2124 if (current
->sched_class
->post_schedule
)
2125 current
->sched_class
->post_schedule(rq
);
2128 fire_sched_in_preempt_notifiers(current
);
2131 if (unlikely(prev_state
== TASK_DEAD
)) {
2133 * Remove function-return probe instances associated with this
2134 * task and put them back on the free list.
2136 kprobe_flush_task(prev
);
2137 put_task_struct(prev
);
2142 * schedule_tail - first thing a freshly forked thread must call.
2143 * @prev: the thread we just switched away from.
2145 asmlinkage
void schedule_tail(struct task_struct
*prev
)
2146 __releases(rq
->lock
)
2148 struct rq
*rq
= this_rq();
2150 finish_task_switch(rq
, prev
);
2151 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2152 /* In this case, finish_task_switch does not reenable preemption */
2155 if (current
->set_child_tid
)
2156 put_user(task_pid_vnr(current
), current
->set_child_tid
);
2160 * context_switch - switch to the new MM and the new
2161 * thread's register state.
2164 context_switch(struct rq
*rq
, struct task_struct
*prev
,
2165 struct task_struct
*next
)
2167 struct mm_struct
*mm
, *oldmm
;
2169 prepare_task_switch(rq
, prev
, next
);
2171 oldmm
= prev
->active_mm
;
2173 * For paravirt, this is coupled with an exit in switch_to to
2174 * combine the page table reload and the switch backend into
2177 arch_enter_lazy_cpu_mode();
2179 if (unlikely(!mm
)) {
2180 next
->active_mm
= oldmm
;
2181 atomic_inc(&oldmm
->mm_count
);
2182 enter_lazy_tlb(oldmm
, next
);
2184 switch_mm(oldmm
, mm
, next
);
2186 if (unlikely(!prev
->mm
)) {
2187 prev
->active_mm
= NULL
;
2188 rq
->prev_mm
= oldmm
;
2191 * Since the runqueue lock will be released by the next
2192 * task (which is an invalid locking op but in the case
2193 * of the scheduler it's an obvious special-case), so we
2194 * do an early lockdep release here:
2196 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2197 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
2200 /* Here we just switch the register state and the stack. */
2201 switch_to(prev
, next
, prev
);
2205 * this_rq must be evaluated again because prev may have moved
2206 * CPUs since it called schedule(), thus the 'rq' on its stack
2207 * frame will be invalid.
2209 finish_task_switch(this_rq(), prev
);
2213 * nr_running, nr_uninterruptible and nr_context_switches:
2215 * externally visible scheduler statistics: current number of runnable
2216 * threads, current number of uninterruptible-sleeping threads, total
2217 * number of context switches performed since bootup.
2219 unsigned long nr_running(void)
2221 unsigned long i
, sum
= 0;
2223 for_each_online_cpu(i
)
2224 sum
+= cpu_rq(i
)->nr_running
;
2229 unsigned long nr_uninterruptible(void)
2231 unsigned long i
, sum
= 0;
2233 for_each_possible_cpu(i
)
2234 sum
+= cpu_rq(i
)->nr_uninterruptible
;
2237 * Since we read the counters lockless, it might be slightly
2238 * inaccurate. Do not allow it to go below zero though:
2240 if (unlikely((long)sum
< 0))
2246 unsigned long long nr_context_switches(void)
2249 unsigned long long sum
= 0;
2251 for_each_possible_cpu(i
)
2252 sum
+= cpu_rq(i
)->nr_switches
;
2257 unsigned long nr_iowait(void)
2259 unsigned long i
, sum
= 0;
2261 for_each_possible_cpu(i
)
2262 sum
+= atomic_read(&cpu_rq(i
)->nr_iowait
);
2267 unsigned long nr_active(void)
2269 unsigned long i
, running
= 0, uninterruptible
= 0;
2271 for_each_online_cpu(i
) {
2272 running
+= cpu_rq(i
)->nr_running
;
2273 uninterruptible
+= cpu_rq(i
)->nr_uninterruptible
;
2276 if (unlikely((long)uninterruptible
< 0))
2277 uninterruptible
= 0;
2279 return running
+ uninterruptible
;
2283 * Update rq->cpu_load[] statistics. This function is usually called every
2284 * scheduler tick (TICK_NSEC).
2286 static void update_cpu_load(struct rq
*this_rq
)
2288 unsigned long this_load
= this_rq
->load
.weight
;
2291 this_rq
->nr_load_updates
++;
2293 /* Update our load: */
2294 for (i
= 0, scale
= 1; i
< CPU_LOAD_IDX_MAX
; i
++, scale
+= scale
) {
2295 unsigned long old_load
, new_load
;
2297 /* scale is effectively 1 << i now, and >> i divides by scale */
2299 old_load
= this_rq
->cpu_load
[i
];
2300 new_load
= this_load
;
2302 * Round up the averaging division if load is increasing. This
2303 * prevents us from getting stuck on 9 if the load is 10, for
2306 if (new_load
> old_load
)
2307 new_load
+= scale
-1;
2308 this_rq
->cpu_load
[i
] = (old_load
*(scale
-1) + new_load
) >> i
;
2315 * double_rq_lock - safely lock two runqueues
2317 * Note this does not disable interrupts like task_rq_lock,
2318 * you need to do so manually before calling.
2320 static void double_rq_lock(struct rq
*rq1
, struct rq
*rq2
)
2321 __acquires(rq1
->lock
)
2322 __acquires(rq2
->lock
)
2324 BUG_ON(!irqs_disabled());
2326 spin_lock(&rq1
->lock
);
2327 __acquire(rq2
->lock
); /* Fake it out ;) */
2330 spin_lock(&rq1
->lock
);
2331 spin_lock(&rq2
->lock
);
2333 spin_lock(&rq2
->lock
);
2334 spin_lock(&rq1
->lock
);
2337 update_rq_clock(rq1
);
2338 update_rq_clock(rq2
);
2342 * double_rq_unlock - safely unlock two runqueues
2344 * Note this does not restore interrupts like task_rq_unlock,
2345 * you need to do so manually after calling.
2347 static void double_rq_unlock(struct rq
*rq1
, struct rq
*rq2
)
2348 __releases(rq1
->lock
)
2349 __releases(rq2
->lock
)
2351 spin_unlock(&rq1
->lock
);
2353 spin_unlock(&rq2
->lock
);
2355 __release(rq2
->lock
);
2359 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2361 static int double_lock_balance(struct rq
*this_rq
, struct rq
*busiest
)
2362 __releases(this_rq
->lock
)
2363 __acquires(busiest
->lock
)
2364 __acquires(this_rq
->lock
)
2368 if (unlikely(!irqs_disabled())) {
2369 /* printk() doesn't work good under rq->lock */
2370 spin_unlock(&this_rq
->lock
);
2373 if (unlikely(!spin_trylock(&busiest
->lock
))) {
2374 if (busiest
< this_rq
) {
2375 spin_unlock(&this_rq
->lock
);
2376 spin_lock(&busiest
->lock
);
2377 spin_lock(&this_rq
->lock
);
2380 spin_lock(&busiest
->lock
);
2386 * If dest_cpu is allowed for this process, migrate the task to it.
2387 * This is accomplished by forcing the cpu_allowed mask to only
2388 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2389 * the cpu_allowed mask is restored.
2391 static void sched_migrate_task(struct task_struct
*p
, int dest_cpu
)
2393 struct migration_req req
;
2394 unsigned long flags
;
2397 rq
= task_rq_lock(p
, &flags
);
2398 if (!cpu_isset(dest_cpu
, p
->cpus_allowed
)
2399 || unlikely(cpu_is_offline(dest_cpu
)))
2402 /* force the process onto the specified CPU */
2403 if (migrate_task(p
, dest_cpu
, &req
)) {
2404 /* Need to wait for migration thread (might exit: take ref). */
2405 struct task_struct
*mt
= rq
->migration_thread
;
2407 get_task_struct(mt
);
2408 task_rq_unlock(rq
, &flags
);
2409 wake_up_process(mt
);
2410 put_task_struct(mt
);
2411 wait_for_completion(&req
.done
);
2416 task_rq_unlock(rq
, &flags
);
2420 * sched_exec - execve() is a valuable balancing opportunity, because at
2421 * this point the task has the smallest effective memory and cache footprint.
2423 void sched_exec(void)
2425 int new_cpu
, this_cpu
= get_cpu();
2426 new_cpu
= sched_balance_self(this_cpu
, SD_BALANCE_EXEC
);
2428 if (new_cpu
!= this_cpu
)
2429 sched_migrate_task(current
, new_cpu
);
2433 * pull_task - move a task from a remote runqueue to the local runqueue.
2434 * Both runqueues must be locked.
2436 static void pull_task(struct rq
*src_rq
, struct task_struct
*p
,
2437 struct rq
*this_rq
, int this_cpu
)
2439 deactivate_task(src_rq
, p
, 0);
2440 set_task_cpu(p
, this_cpu
);
2441 activate_task(this_rq
, p
, 0);
2443 * Note that idle threads have a prio of MAX_PRIO, for this test
2444 * to be always true for them.
2446 check_preempt_curr(this_rq
, p
);
2450 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2453 int can_migrate_task(struct task_struct
*p
, struct rq
*rq
, int this_cpu
,
2454 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2458 * We do not migrate tasks that are:
2459 * 1) running (obviously), or
2460 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2461 * 3) are cache-hot on their current CPU.
2463 if (!cpu_isset(this_cpu
, p
->cpus_allowed
)) {
2464 schedstat_inc(p
, se
.nr_failed_migrations_affine
);
2469 if (task_running(rq
, p
)) {
2470 schedstat_inc(p
, se
.nr_failed_migrations_running
);
2475 * Aggressive migration if:
2476 * 1) task is cache cold, or
2477 * 2) too many balance attempts have failed.
2480 if (!task_hot(p
, rq
->clock
, sd
) ||
2481 sd
->nr_balance_failed
> sd
->cache_nice_tries
) {
2482 #ifdef CONFIG_SCHEDSTATS
2483 if (task_hot(p
, rq
->clock
, sd
)) {
2484 schedstat_inc(sd
, lb_hot_gained
[idle
]);
2485 schedstat_inc(p
, se
.nr_forced_migrations
);
2491 if (task_hot(p
, rq
->clock
, sd
)) {
2492 schedstat_inc(p
, se
.nr_failed_migrations_hot
);
2498 static unsigned long
2499 balance_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2500 unsigned long max_load_move
, struct sched_domain
*sd
,
2501 enum cpu_idle_type idle
, int *all_pinned
,
2502 int *this_best_prio
, struct rq_iterator
*iterator
)
2504 int loops
= 0, pulled
= 0, pinned
= 0, skip_for_load
;
2505 struct task_struct
*p
;
2506 long rem_load_move
= max_load_move
;
2508 if (max_load_move
== 0)
2514 * Start the load-balancing iterator:
2516 p
= iterator
->start(iterator
->arg
);
2518 if (!p
|| loops
++ > sysctl_sched_nr_migrate
)
2521 * To help distribute high priority tasks across CPUs we don't
2522 * skip a task if it will be the highest priority task (i.e. smallest
2523 * prio value) on its new queue regardless of its load weight
2525 skip_for_load
= (p
->se
.load
.weight
>> 1) > rem_load_move
+
2526 SCHED_LOAD_SCALE_FUZZ
;
2527 if ((skip_for_load
&& p
->prio
>= *this_best_prio
) ||
2528 !can_migrate_task(p
, busiest
, this_cpu
, sd
, idle
, &pinned
)) {
2529 p
= iterator
->next(iterator
->arg
);
2533 pull_task(busiest
, p
, this_rq
, this_cpu
);
2535 rem_load_move
-= p
->se
.load
.weight
;
2538 * We only want to steal up to the prescribed amount of weighted load.
2540 if (rem_load_move
> 0) {
2541 if (p
->prio
< *this_best_prio
)
2542 *this_best_prio
= p
->prio
;
2543 p
= iterator
->next(iterator
->arg
);
2548 * Right now, this is one of only two places pull_task() is called,
2549 * so we can safely collect pull_task() stats here rather than
2550 * inside pull_task().
2552 schedstat_add(sd
, lb_gained
[idle
], pulled
);
2555 *all_pinned
= pinned
;
2557 return max_load_move
- rem_load_move
;
2561 * move_tasks tries to move up to max_load_move weighted load from busiest to
2562 * this_rq, as part of a balancing operation within domain "sd".
2563 * Returns 1 if successful and 0 otherwise.
2565 * Called with both runqueues locked.
2567 static int move_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2568 unsigned long max_load_move
,
2569 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2572 const struct sched_class
*class = sched_class_highest
;
2573 unsigned long total_load_moved
= 0;
2574 int this_best_prio
= this_rq
->curr
->prio
;
2578 class->load_balance(this_rq
, this_cpu
, busiest
,
2579 max_load_move
- total_load_moved
,
2580 sd
, idle
, all_pinned
, &this_best_prio
);
2581 class = class->next
;
2582 } while (class && max_load_move
> total_load_moved
);
2584 return total_load_moved
> 0;
2588 iter_move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2589 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2590 struct rq_iterator
*iterator
)
2592 struct task_struct
*p
= iterator
->start(iterator
->arg
);
2596 if (can_migrate_task(p
, busiest
, this_cpu
, sd
, idle
, &pinned
)) {
2597 pull_task(busiest
, p
, this_rq
, this_cpu
);
2599 * Right now, this is only the second place pull_task()
2600 * is called, so we can safely collect pull_task()
2601 * stats here rather than inside pull_task().
2603 schedstat_inc(sd
, lb_gained
[idle
]);
2607 p
= iterator
->next(iterator
->arg
);
2614 * move_one_task tries to move exactly one task from busiest to this_rq, as
2615 * part of active balancing operations within "domain".
2616 * Returns 1 if successful and 0 otherwise.
2618 * Called with both runqueues locked.
2620 static int move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2621 struct sched_domain
*sd
, enum cpu_idle_type idle
)
2623 const struct sched_class
*class;
2625 for (class = sched_class_highest
; class; class = class->next
)
2626 if (class->move_one_task(this_rq
, this_cpu
, busiest
, sd
, idle
))
2633 * find_busiest_group finds and returns the busiest CPU group within the
2634 * domain. It calculates and returns the amount of weighted load which
2635 * should be moved to restore balance via the imbalance parameter.
2637 static struct sched_group
*
2638 find_busiest_group(struct sched_domain
*sd
, int this_cpu
,
2639 unsigned long *imbalance
, enum cpu_idle_type idle
,
2640 int *sd_idle
, cpumask_t
*cpus
, int *balance
)
2642 struct sched_group
*busiest
= NULL
, *this = NULL
, *group
= sd
->groups
;
2643 unsigned long max_load
, avg_load
, total_load
, this_load
, total_pwr
;
2644 unsigned long max_pull
;
2645 unsigned long busiest_load_per_task
, busiest_nr_running
;
2646 unsigned long this_load_per_task
, this_nr_running
;
2647 int load_idx
, group_imb
= 0;
2648 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2649 int power_savings_balance
= 1;
2650 unsigned long leader_nr_running
= 0, min_load_per_task
= 0;
2651 unsigned long min_nr_running
= ULONG_MAX
;
2652 struct sched_group
*group_min
= NULL
, *group_leader
= NULL
;
2655 max_load
= this_load
= total_load
= total_pwr
= 0;
2656 busiest_load_per_task
= busiest_nr_running
= 0;
2657 this_load_per_task
= this_nr_running
= 0;
2658 if (idle
== CPU_NOT_IDLE
)
2659 load_idx
= sd
->busy_idx
;
2660 else if (idle
== CPU_NEWLY_IDLE
)
2661 load_idx
= sd
->newidle_idx
;
2663 load_idx
= sd
->idle_idx
;
2666 unsigned long load
, group_capacity
, max_cpu_load
, min_cpu_load
;
2669 int __group_imb
= 0;
2670 unsigned int balance_cpu
= -1, first_idle_cpu
= 0;
2671 unsigned long sum_nr_running
, sum_weighted_load
;
2673 local_group
= cpu_isset(this_cpu
, group
->cpumask
);
2676 balance_cpu
= first_cpu(group
->cpumask
);
2678 /* Tally up the load of all CPUs in the group */
2679 sum_weighted_load
= sum_nr_running
= avg_load
= 0;
2681 min_cpu_load
= ~0UL;
2683 for_each_cpu_mask(i
, group
->cpumask
) {
2686 if (!cpu_isset(i
, *cpus
))
2691 if (*sd_idle
&& rq
->nr_running
)
2694 /* Bias balancing toward cpus of our domain */
2696 if (idle_cpu(i
) && !first_idle_cpu
) {
2701 load
= target_load(i
, load_idx
);
2703 load
= source_load(i
, load_idx
);
2704 if (load
> max_cpu_load
)
2705 max_cpu_load
= load
;
2706 if (min_cpu_load
> load
)
2707 min_cpu_load
= load
;
2711 sum_nr_running
+= rq
->nr_running
;
2712 sum_weighted_load
+= weighted_cpuload(i
);
2716 * First idle cpu or the first cpu(busiest) in this sched group
2717 * is eligible for doing load balancing at this and above
2718 * domains. In the newly idle case, we will allow all the cpu's
2719 * to do the newly idle load balance.
2721 if (idle
!= CPU_NEWLY_IDLE
&& local_group
&&
2722 balance_cpu
!= this_cpu
&& balance
) {
2727 total_load
+= avg_load
;
2728 total_pwr
+= group
->__cpu_power
;
2730 /* Adjust by relative CPU power of the group */
2731 avg_load
= sg_div_cpu_power(group
,
2732 avg_load
* SCHED_LOAD_SCALE
);
2734 if ((max_cpu_load
- min_cpu_load
) > SCHED_LOAD_SCALE
)
2737 group_capacity
= group
->__cpu_power
/ SCHED_LOAD_SCALE
;
2740 this_load
= avg_load
;
2742 this_nr_running
= sum_nr_running
;
2743 this_load_per_task
= sum_weighted_load
;
2744 } else if (avg_load
> max_load
&&
2745 (sum_nr_running
> group_capacity
|| __group_imb
)) {
2746 max_load
= avg_load
;
2748 busiest_nr_running
= sum_nr_running
;
2749 busiest_load_per_task
= sum_weighted_load
;
2750 group_imb
= __group_imb
;
2753 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2755 * Busy processors will not participate in power savings
2758 if (idle
== CPU_NOT_IDLE
||
2759 !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
2763 * If the local group is idle or completely loaded
2764 * no need to do power savings balance at this domain
2766 if (local_group
&& (this_nr_running
>= group_capacity
||
2768 power_savings_balance
= 0;
2771 * If a group is already running at full capacity or idle,
2772 * don't include that group in power savings calculations
2774 if (!power_savings_balance
|| sum_nr_running
>= group_capacity
2779 * Calculate the group which has the least non-idle load.
2780 * This is the group from where we need to pick up the load
2783 if ((sum_nr_running
< min_nr_running
) ||
2784 (sum_nr_running
== min_nr_running
&&
2785 first_cpu(group
->cpumask
) <
2786 first_cpu(group_min
->cpumask
))) {
2788 min_nr_running
= sum_nr_running
;
2789 min_load_per_task
= sum_weighted_load
/
2794 * Calculate the group which is almost near its
2795 * capacity but still has some space to pick up some load
2796 * from other group and save more power
2798 if (sum_nr_running
<= group_capacity
- 1) {
2799 if (sum_nr_running
> leader_nr_running
||
2800 (sum_nr_running
== leader_nr_running
&&
2801 first_cpu(group
->cpumask
) >
2802 first_cpu(group_leader
->cpumask
))) {
2803 group_leader
= group
;
2804 leader_nr_running
= sum_nr_running
;
2809 group
= group
->next
;
2810 } while (group
!= sd
->groups
);
2812 if (!busiest
|| this_load
>= max_load
|| busiest_nr_running
== 0)
2815 avg_load
= (SCHED_LOAD_SCALE
* total_load
) / total_pwr
;
2817 if (this_load
>= avg_load
||
2818 100*max_load
<= sd
->imbalance_pct
*this_load
)
2821 busiest_load_per_task
/= busiest_nr_running
;
2823 busiest_load_per_task
= min(busiest_load_per_task
, avg_load
);
2826 * We're trying to get all the cpus to the average_load, so we don't
2827 * want to push ourselves above the average load, nor do we wish to
2828 * reduce the max loaded cpu below the average load, as either of these
2829 * actions would just result in more rebalancing later, and ping-pong
2830 * tasks around. Thus we look for the minimum possible imbalance.
2831 * Negative imbalances (*we* are more loaded than anyone else) will
2832 * be counted as no imbalance for these purposes -- we can't fix that
2833 * by pulling tasks to us. Be careful of negative numbers as they'll
2834 * appear as very large values with unsigned longs.
2836 if (max_load
<= busiest_load_per_task
)
2840 * In the presence of smp nice balancing, certain scenarios can have
2841 * max load less than avg load(as we skip the groups at or below
2842 * its cpu_power, while calculating max_load..)
2844 if (max_load
< avg_load
) {
2846 goto small_imbalance
;
2849 /* Don't want to pull so many tasks that a group would go idle */
2850 max_pull
= min(max_load
- avg_load
, max_load
- busiest_load_per_task
);
2852 /* How much load to actually move to equalise the imbalance */
2853 *imbalance
= min(max_pull
* busiest
->__cpu_power
,
2854 (avg_load
- this_load
) * this->__cpu_power
)
2858 * if *imbalance is less than the average load per runnable task
2859 * there is no gaurantee that any tasks will be moved so we'll have
2860 * a think about bumping its value to force at least one task to be
2863 if (*imbalance
< busiest_load_per_task
) {
2864 unsigned long tmp
, pwr_now
, pwr_move
;
2868 pwr_move
= pwr_now
= 0;
2870 if (this_nr_running
) {
2871 this_load_per_task
/= this_nr_running
;
2872 if (busiest_load_per_task
> this_load_per_task
)
2875 this_load_per_task
= SCHED_LOAD_SCALE
;
2877 if (max_load
- this_load
+ SCHED_LOAD_SCALE_FUZZ
>=
2878 busiest_load_per_task
* imbn
) {
2879 *imbalance
= busiest_load_per_task
;
2884 * OK, we don't have enough imbalance to justify moving tasks,
2885 * however we may be able to increase total CPU power used by
2889 pwr_now
+= busiest
->__cpu_power
*
2890 min(busiest_load_per_task
, max_load
);
2891 pwr_now
+= this->__cpu_power
*
2892 min(this_load_per_task
, this_load
);
2893 pwr_now
/= SCHED_LOAD_SCALE
;
2895 /* Amount of load we'd subtract */
2896 tmp
= sg_div_cpu_power(busiest
,
2897 busiest_load_per_task
* SCHED_LOAD_SCALE
);
2899 pwr_move
+= busiest
->__cpu_power
*
2900 min(busiest_load_per_task
, max_load
- tmp
);
2902 /* Amount of load we'd add */
2903 if (max_load
* busiest
->__cpu_power
<
2904 busiest_load_per_task
* SCHED_LOAD_SCALE
)
2905 tmp
= sg_div_cpu_power(this,
2906 max_load
* busiest
->__cpu_power
);
2908 tmp
= sg_div_cpu_power(this,
2909 busiest_load_per_task
* SCHED_LOAD_SCALE
);
2910 pwr_move
+= this->__cpu_power
*
2911 min(this_load_per_task
, this_load
+ tmp
);
2912 pwr_move
/= SCHED_LOAD_SCALE
;
2914 /* Move if we gain throughput */
2915 if (pwr_move
> pwr_now
)
2916 *imbalance
= busiest_load_per_task
;
2922 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2923 if (idle
== CPU_NOT_IDLE
|| !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
2926 if (this == group_leader
&& group_leader
!= group_min
) {
2927 *imbalance
= min_load_per_task
;
2937 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2940 find_busiest_queue(struct sched_group
*group
, enum cpu_idle_type idle
,
2941 unsigned long imbalance
, cpumask_t
*cpus
)
2943 struct rq
*busiest
= NULL
, *rq
;
2944 unsigned long max_load
= 0;
2947 for_each_cpu_mask(i
, group
->cpumask
) {
2950 if (!cpu_isset(i
, *cpus
))
2954 wl
= weighted_cpuload(i
);
2956 if (rq
->nr_running
== 1 && wl
> imbalance
)
2959 if (wl
> max_load
) {
2969 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2970 * so long as it is large enough.
2972 #define MAX_PINNED_INTERVAL 512
2975 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2976 * tasks if there is an imbalance.
2978 static int load_balance(int this_cpu
, struct rq
*this_rq
,
2979 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2982 int ld_moved
, all_pinned
= 0, active_balance
= 0, sd_idle
= 0;
2983 struct sched_group
*group
;
2984 unsigned long imbalance
;
2986 cpumask_t cpus
= CPU_MASK_ALL
;
2987 unsigned long flags
;
2990 * When power savings policy is enabled for the parent domain, idle
2991 * sibling can pick up load irrespective of busy siblings. In this case,
2992 * let the state of idle sibling percolate up as CPU_IDLE, instead of
2993 * portraying it as CPU_NOT_IDLE.
2995 if (idle
!= CPU_NOT_IDLE
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
2996 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
2999 schedstat_inc(sd
, lb_count
[idle
]);
3002 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, idle
, &sd_idle
,
3009 schedstat_inc(sd
, lb_nobusyg
[idle
]);
3013 busiest
= find_busiest_queue(group
, idle
, imbalance
, &cpus
);
3015 schedstat_inc(sd
, lb_nobusyq
[idle
]);
3019 BUG_ON(busiest
== this_rq
);
3021 schedstat_add(sd
, lb_imbalance
[idle
], imbalance
);
3024 if (busiest
->nr_running
> 1) {
3026 * Attempt to move tasks. If find_busiest_group has found
3027 * an imbalance but busiest->nr_running <= 1, the group is
3028 * still unbalanced. ld_moved simply stays zero, so it is
3029 * correctly treated as an imbalance.
3031 local_irq_save(flags
);
3032 double_rq_lock(this_rq
, busiest
);
3033 ld_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
3034 imbalance
, sd
, idle
, &all_pinned
);
3035 double_rq_unlock(this_rq
, busiest
);
3036 local_irq_restore(flags
);
3039 * some other cpu did the load balance for us.
3041 if (ld_moved
&& this_cpu
!= smp_processor_id())
3042 resched_cpu(this_cpu
);
3044 /* All tasks on this runqueue were pinned by CPU affinity */
3045 if (unlikely(all_pinned
)) {
3046 cpu_clear(cpu_of(busiest
), cpus
);
3047 if (!cpus_empty(cpus
))
3054 schedstat_inc(sd
, lb_failed
[idle
]);
3055 sd
->nr_balance_failed
++;
3057 if (unlikely(sd
->nr_balance_failed
> sd
->cache_nice_tries
+2)) {
3059 spin_lock_irqsave(&busiest
->lock
, flags
);
3061 /* don't kick the migration_thread, if the curr
3062 * task on busiest cpu can't be moved to this_cpu
3064 if (!cpu_isset(this_cpu
, busiest
->curr
->cpus_allowed
)) {
3065 spin_unlock_irqrestore(&busiest
->lock
, flags
);
3067 goto out_one_pinned
;
3070 if (!busiest
->active_balance
) {
3071 busiest
->active_balance
= 1;
3072 busiest
->push_cpu
= this_cpu
;
3075 spin_unlock_irqrestore(&busiest
->lock
, flags
);
3077 wake_up_process(busiest
->migration_thread
);
3080 * We've kicked active balancing, reset the failure
3083 sd
->nr_balance_failed
= sd
->cache_nice_tries
+1;
3086 sd
->nr_balance_failed
= 0;
3088 if (likely(!active_balance
)) {
3089 /* We were unbalanced, so reset the balancing interval */
3090 sd
->balance_interval
= sd
->min_interval
;
3093 * If we've begun active balancing, start to back off. This
3094 * case may not be covered by the all_pinned logic if there
3095 * is only 1 task on the busy runqueue (because we don't call
3098 if (sd
->balance_interval
< sd
->max_interval
)
3099 sd
->balance_interval
*= 2;
3102 if (!ld_moved
&& !sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3103 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3108 schedstat_inc(sd
, lb_balanced
[idle
]);
3110 sd
->nr_balance_failed
= 0;
3113 /* tune up the balancing interval */
3114 if ((all_pinned
&& sd
->balance_interval
< MAX_PINNED_INTERVAL
) ||
3115 (sd
->balance_interval
< sd
->max_interval
))
3116 sd
->balance_interval
*= 2;
3118 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3119 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3125 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3126 * tasks if there is an imbalance.
3128 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3129 * this_rq is locked.
3132 load_balance_newidle(int this_cpu
, struct rq
*this_rq
, struct sched_domain
*sd
)
3134 struct sched_group
*group
;
3135 struct rq
*busiest
= NULL
;
3136 unsigned long imbalance
;
3140 cpumask_t cpus
= CPU_MASK_ALL
;
3143 * When power savings policy is enabled for the parent domain, idle
3144 * sibling can pick up load irrespective of busy siblings. In this case,
3145 * let the state of idle sibling percolate up as IDLE, instead of
3146 * portraying it as CPU_NOT_IDLE.
3148 if (sd
->flags
& SD_SHARE_CPUPOWER
&&
3149 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3152 schedstat_inc(sd
, lb_count
[CPU_NEWLY_IDLE
]);
3154 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, CPU_NEWLY_IDLE
,
3155 &sd_idle
, &cpus
, NULL
);
3157 schedstat_inc(sd
, lb_nobusyg
[CPU_NEWLY_IDLE
]);
3161 busiest
= find_busiest_queue(group
, CPU_NEWLY_IDLE
, imbalance
,
3164 schedstat_inc(sd
, lb_nobusyq
[CPU_NEWLY_IDLE
]);
3168 BUG_ON(busiest
== this_rq
);
3170 schedstat_add(sd
, lb_imbalance
[CPU_NEWLY_IDLE
], imbalance
);
3173 if (busiest
->nr_running
> 1) {
3174 /* Attempt to move tasks */
3175 double_lock_balance(this_rq
, busiest
);
3176 /* this_rq->clock is already updated */
3177 update_rq_clock(busiest
);
3178 ld_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
3179 imbalance
, sd
, CPU_NEWLY_IDLE
,
3181 spin_unlock(&busiest
->lock
);
3183 if (unlikely(all_pinned
)) {
3184 cpu_clear(cpu_of(busiest
), cpus
);
3185 if (!cpus_empty(cpus
))
3191 schedstat_inc(sd
, lb_failed
[CPU_NEWLY_IDLE
]);
3192 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3193 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3196 sd
->nr_balance_failed
= 0;
3201 schedstat_inc(sd
, lb_balanced
[CPU_NEWLY_IDLE
]);
3202 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3203 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3205 sd
->nr_balance_failed
= 0;
3211 * idle_balance is called by schedule() if this_cpu is about to become
3212 * idle. Attempts to pull tasks from other CPUs.
3214 static void idle_balance(int this_cpu
, struct rq
*this_rq
)
3216 struct sched_domain
*sd
;
3217 int pulled_task
= -1;
3218 unsigned long next_balance
= jiffies
+ HZ
;
3220 for_each_domain(this_cpu
, sd
) {
3221 unsigned long interval
;
3223 if (!(sd
->flags
& SD_LOAD_BALANCE
))
3226 if (sd
->flags
& SD_BALANCE_NEWIDLE
)
3227 /* If we've pulled tasks over stop searching: */
3228 pulled_task
= load_balance_newidle(this_cpu
,
3231 interval
= msecs_to_jiffies(sd
->balance_interval
);
3232 if (time_after(next_balance
, sd
->last_balance
+ interval
))
3233 next_balance
= sd
->last_balance
+ interval
;
3237 if (pulled_task
|| time_after(jiffies
, this_rq
->next_balance
)) {
3239 * We are going idle. next_balance may be set based on
3240 * a busy processor. So reset next_balance.
3242 this_rq
->next_balance
= next_balance
;
3247 * active_load_balance is run by migration threads. It pushes running tasks
3248 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3249 * running on each physical CPU where possible, and avoids physical /
3250 * logical imbalances.
3252 * Called with busiest_rq locked.
3254 static void active_load_balance(struct rq
*busiest_rq
, int busiest_cpu
)
3256 int target_cpu
= busiest_rq
->push_cpu
;
3257 struct sched_domain
*sd
;
3258 struct rq
*target_rq
;
3260 /* Is there any task to move? */
3261 if (busiest_rq
->nr_running
<= 1)
3264 target_rq
= cpu_rq(target_cpu
);
3267 * This condition is "impossible", if it occurs
3268 * we need to fix it. Originally reported by
3269 * Bjorn Helgaas on a 128-cpu setup.
3271 BUG_ON(busiest_rq
== target_rq
);
3273 /* move a task from busiest_rq to target_rq */
3274 double_lock_balance(busiest_rq
, target_rq
);
3275 update_rq_clock(busiest_rq
);
3276 update_rq_clock(target_rq
);
3278 /* Search for an sd spanning us and the target CPU. */
3279 for_each_domain(target_cpu
, sd
) {
3280 if ((sd
->flags
& SD_LOAD_BALANCE
) &&
3281 cpu_isset(busiest_cpu
, sd
->span
))
3286 schedstat_inc(sd
, alb_count
);
3288 if (move_one_task(target_rq
, target_cpu
, busiest_rq
,
3290 schedstat_inc(sd
, alb_pushed
);
3292 schedstat_inc(sd
, alb_failed
);
3294 spin_unlock(&target_rq
->lock
);
3299 atomic_t load_balancer
;
3301 } nohz ____cacheline_aligned
= {
3302 .load_balancer
= ATOMIC_INIT(-1),
3303 .cpu_mask
= CPU_MASK_NONE
,
3307 * This routine will try to nominate the ilb (idle load balancing)
3308 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3309 * load balancing on behalf of all those cpus. If all the cpus in the system
3310 * go into this tickless mode, then there will be no ilb owner (as there is
3311 * no need for one) and all the cpus will sleep till the next wakeup event
3314 * For the ilb owner, tick is not stopped. And this tick will be used
3315 * for idle load balancing. ilb owner will still be part of
3318 * While stopping the tick, this cpu will become the ilb owner if there
3319 * is no other owner. And will be the owner till that cpu becomes busy
3320 * or if all cpus in the system stop their ticks at which point
3321 * there is no need for ilb owner.
3323 * When the ilb owner becomes busy, it nominates another owner, during the
3324 * next busy scheduler_tick()
3326 int select_nohz_load_balancer(int stop_tick
)
3328 int cpu
= smp_processor_id();
3331 cpu_set(cpu
, nohz
.cpu_mask
);
3332 cpu_rq(cpu
)->in_nohz_recently
= 1;
3335 * If we are going offline and still the leader, give up!
3337 if (cpu_is_offline(cpu
) &&
3338 atomic_read(&nohz
.load_balancer
) == cpu
) {
3339 if (atomic_cmpxchg(&nohz
.load_balancer
, cpu
, -1) != cpu
)
3344 /* time for ilb owner also to sleep */
3345 if (cpus_weight(nohz
.cpu_mask
) == num_online_cpus()) {
3346 if (atomic_read(&nohz
.load_balancer
) == cpu
)
3347 atomic_set(&nohz
.load_balancer
, -1);
3351 if (atomic_read(&nohz
.load_balancer
) == -1) {
3352 /* make me the ilb owner */
3353 if (atomic_cmpxchg(&nohz
.load_balancer
, -1, cpu
) == -1)
3355 } else if (atomic_read(&nohz
.load_balancer
) == cpu
)
3358 if (!cpu_isset(cpu
, nohz
.cpu_mask
))
3361 cpu_clear(cpu
, nohz
.cpu_mask
);
3363 if (atomic_read(&nohz
.load_balancer
) == cpu
)
3364 if (atomic_cmpxchg(&nohz
.load_balancer
, cpu
, -1) != cpu
)
3371 static DEFINE_SPINLOCK(balancing
);
3374 * It checks each scheduling domain to see if it is due to be balanced,
3375 * and initiates a balancing operation if so.
3377 * Balancing parameters are set up in arch_init_sched_domains.
3379 static void rebalance_domains(int cpu
, enum cpu_idle_type idle
)
3382 struct rq
*rq
= cpu_rq(cpu
);
3383 unsigned long interval
;
3384 struct sched_domain
*sd
;
3385 /* Earliest time when we have to do rebalance again */
3386 unsigned long next_balance
= jiffies
+ 60*HZ
;
3387 int update_next_balance
= 0;
3389 for_each_domain(cpu
, sd
) {
3390 if (!(sd
->flags
& SD_LOAD_BALANCE
))
3393 interval
= sd
->balance_interval
;
3394 if (idle
!= CPU_IDLE
)
3395 interval
*= sd
->busy_factor
;
3397 /* scale ms to jiffies */
3398 interval
= msecs_to_jiffies(interval
);
3399 if (unlikely(!interval
))
3401 if (interval
> HZ
*NR_CPUS
/10)
3402 interval
= HZ
*NR_CPUS
/10;
3405 if (sd
->flags
& SD_SERIALIZE
) {
3406 if (!spin_trylock(&balancing
))
3410 if (time_after_eq(jiffies
, sd
->last_balance
+ interval
)) {
3411 if (load_balance(cpu
, rq
, sd
, idle
, &balance
)) {
3413 * We've pulled tasks over so either we're no
3414 * longer idle, or one of our SMT siblings is
3417 idle
= CPU_NOT_IDLE
;
3419 sd
->last_balance
= jiffies
;
3421 if (sd
->flags
& SD_SERIALIZE
)
3422 spin_unlock(&balancing
);
3424 if (time_after(next_balance
, sd
->last_balance
+ interval
)) {
3425 next_balance
= sd
->last_balance
+ interval
;
3426 update_next_balance
= 1;
3430 * Stop the load balance at this level. There is another
3431 * CPU in our sched group which is doing load balancing more
3439 * next_balance will be updated only when there is a need.
3440 * When the cpu is attached to null domain for ex, it will not be
3443 if (likely(update_next_balance
))
3444 rq
->next_balance
= next_balance
;
3448 * run_rebalance_domains is triggered when needed from the scheduler tick.
3449 * In CONFIG_NO_HZ case, the idle load balance owner will do the
3450 * rebalancing for all the cpus for whom scheduler ticks are stopped.
3452 static void run_rebalance_domains(struct softirq_action
*h
)
3454 int this_cpu
= smp_processor_id();
3455 struct rq
*this_rq
= cpu_rq(this_cpu
);
3456 enum cpu_idle_type idle
= this_rq
->idle_at_tick
?
3457 CPU_IDLE
: CPU_NOT_IDLE
;
3459 rebalance_domains(this_cpu
, idle
);
3463 * If this cpu is the owner for idle load balancing, then do the
3464 * balancing on behalf of the other idle cpus whose ticks are
3467 if (this_rq
->idle_at_tick
&&
3468 atomic_read(&nohz
.load_balancer
) == this_cpu
) {
3469 cpumask_t cpus
= nohz
.cpu_mask
;
3473 cpu_clear(this_cpu
, cpus
);
3474 for_each_cpu_mask(balance_cpu
, cpus
) {
3476 * If this cpu gets work to do, stop the load balancing
3477 * work being done for other cpus. Next load
3478 * balancing owner will pick it up.
3483 rebalance_domains(balance_cpu
, CPU_IDLE
);
3485 rq
= cpu_rq(balance_cpu
);
3486 if (time_after(this_rq
->next_balance
, rq
->next_balance
))
3487 this_rq
->next_balance
= rq
->next_balance
;
3494 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
3496 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
3497 * idle load balancing owner or decide to stop the periodic load balancing,
3498 * if the whole system is idle.
3500 static inline void trigger_load_balance(struct rq
*rq
, int cpu
)
3504 * If we were in the nohz mode recently and busy at the current
3505 * scheduler tick, then check if we need to nominate new idle
3508 if (rq
->in_nohz_recently
&& !rq
->idle_at_tick
) {
3509 rq
->in_nohz_recently
= 0;
3511 if (atomic_read(&nohz
.load_balancer
) == cpu
) {
3512 cpu_clear(cpu
, nohz
.cpu_mask
);
3513 atomic_set(&nohz
.load_balancer
, -1);
3516 if (atomic_read(&nohz
.load_balancer
) == -1) {
3518 * simple selection for now: Nominate the
3519 * first cpu in the nohz list to be the next
3522 * TBD: Traverse the sched domains and nominate
3523 * the nearest cpu in the nohz.cpu_mask.
3525 int ilb
= first_cpu(nohz
.cpu_mask
);
3533 * If this cpu is idle and doing idle load balancing for all the
3534 * cpus with ticks stopped, is it time for that to stop?
3536 if (rq
->idle_at_tick
&& atomic_read(&nohz
.load_balancer
) == cpu
&&
3537 cpus_weight(nohz
.cpu_mask
) == num_online_cpus()) {
3543 * If this cpu is idle and the idle load balancing is done by
3544 * someone else, then no need raise the SCHED_SOFTIRQ
3546 if (rq
->idle_at_tick
&& atomic_read(&nohz
.load_balancer
) != cpu
&&
3547 cpu_isset(cpu
, nohz
.cpu_mask
))
3550 if (time_after_eq(jiffies
, rq
->next_balance
))
3551 raise_softirq(SCHED_SOFTIRQ
);
3554 #else /* CONFIG_SMP */
3557 * on UP we do not need to balance between CPUs:
3559 static inline void idle_balance(int cpu
, struct rq
*rq
)
3565 DEFINE_PER_CPU(struct kernel_stat
, kstat
);
3567 EXPORT_PER_CPU_SYMBOL(kstat
);
3570 * Return p->sum_exec_runtime plus any more ns on the sched_clock
3571 * that have not yet been banked in case the task is currently running.
3573 unsigned long long task_sched_runtime(struct task_struct
*p
)
3575 unsigned long flags
;
3579 rq
= task_rq_lock(p
, &flags
);
3580 ns
= p
->se
.sum_exec_runtime
;
3581 if (task_current(rq
, p
)) {
3582 update_rq_clock(rq
);
3583 delta_exec
= rq
->clock
- p
->se
.exec_start
;
3584 if ((s64
)delta_exec
> 0)
3587 task_rq_unlock(rq
, &flags
);
3593 * Account user cpu time to a process.
3594 * @p: the process that the cpu time gets accounted to
3595 * @cputime: the cpu time spent in user space since the last update
3597 void account_user_time(struct task_struct
*p
, cputime_t cputime
)
3599 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3602 p
->utime
= cputime_add(p
->utime
, cputime
);
3604 /* Add user time to cpustat. */
3605 tmp
= cputime_to_cputime64(cputime
);
3606 if (TASK_NICE(p
) > 0)
3607 cpustat
->nice
= cputime64_add(cpustat
->nice
, tmp
);
3609 cpustat
->user
= cputime64_add(cpustat
->user
, tmp
);
3613 * Account guest cpu time to a process.
3614 * @p: the process that the cpu time gets accounted to
3615 * @cputime: the cpu time spent in virtual machine since the last update
3617 static void account_guest_time(struct task_struct
*p
, cputime_t cputime
)
3620 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3622 tmp
= cputime_to_cputime64(cputime
);
3624 p
->utime
= cputime_add(p
->utime
, cputime
);
3625 p
->gtime
= cputime_add(p
->gtime
, cputime
);
3627 cpustat
->user
= cputime64_add(cpustat
->user
, tmp
);
3628 cpustat
->guest
= cputime64_add(cpustat
->guest
, tmp
);
3632 * Account scaled user cpu time to a process.
3633 * @p: the process that the cpu time gets accounted to
3634 * @cputime: the cpu time spent in user space since the last update
3636 void account_user_time_scaled(struct task_struct
*p
, cputime_t cputime
)
3638 p
->utimescaled
= cputime_add(p
->utimescaled
, cputime
);
3642 * Account system cpu time to a process.
3643 * @p: the process that the cpu time gets accounted to
3644 * @hardirq_offset: the offset to subtract from hardirq_count()
3645 * @cputime: the cpu time spent in kernel space since the last update
3647 void account_system_time(struct task_struct
*p
, int hardirq_offset
,
3650 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3651 struct rq
*rq
= this_rq();
3654 if ((p
->flags
& PF_VCPU
) && (irq_count() - hardirq_offset
== 0))
3655 return account_guest_time(p
, cputime
);
3657 p
->stime
= cputime_add(p
->stime
, cputime
);
3659 /* Add system time to cpustat. */
3660 tmp
= cputime_to_cputime64(cputime
);
3661 if (hardirq_count() - hardirq_offset
)
3662 cpustat
->irq
= cputime64_add(cpustat
->irq
, tmp
);
3663 else if (softirq_count())
3664 cpustat
->softirq
= cputime64_add(cpustat
->softirq
, tmp
);
3665 else if (p
!= rq
->idle
)
3666 cpustat
->system
= cputime64_add(cpustat
->system
, tmp
);
3667 else if (atomic_read(&rq
->nr_iowait
) > 0)
3668 cpustat
->iowait
= cputime64_add(cpustat
->iowait
, tmp
);
3670 cpustat
->idle
= cputime64_add(cpustat
->idle
, tmp
);
3671 /* Account for system time used */
3672 acct_update_integrals(p
);
3676 * Account scaled system cpu time to a process.
3677 * @p: the process that the cpu time gets accounted to
3678 * @hardirq_offset: the offset to subtract from hardirq_count()
3679 * @cputime: the cpu time spent in kernel space since the last update
3681 void account_system_time_scaled(struct task_struct
*p
, cputime_t cputime
)
3683 p
->stimescaled
= cputime_add(p
->stimescaled
, cputime
);
3687 * Account for involuntary wait time.
3688 * @p: the process from which the cpu time has been stolen
3689 * @steal: the cpu time spent in involuntary wait
3691 void account_steal_time(struct task_struct
*p
, cputime_t steal
)
3693 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3694 cputime64_t tmp
= cputime_to_cputime64(steal
);
3695 struct rq
*rq
= this_rq();
3697 if (p
== rq
->idle
) {
3698 p
->stime
= cputime_add(p
->stime
, steal
);
3699 if (atomic_read(&rq
->nr_iowait
) > 0)
3700 cpustat
->iowait
= cputime64_add(cpustat
->iowait
, tmp
);
3702 cpustat
->idle
= cputime64_add(cpustat
->idle
, tmp
);
3704 cpustat
->steal
= cputime64_add(cpustat
->steal
, tmp
);
3708 * This function gets called by the timer code, with HZ frequency.
3709 * We call it with interrupts disabled.
3711 * It also gets called by the fork code, when changing the parent's
3714 void scheduler_tick(void)
3716 int cpu
= smp_processor_id();
3717 struct rq
*rq
= cpu_rq(cpu
);
3718 struct task_struct
*curr
= rq
->curr
;
3719 u64 next_tick
= rq
->tick_timestamp
+ TICK_NSEC
;
3721 spin_lock(&rq
->lock
);
3722 __update_rq_clock(rq
);
3724 * Let rq->clock advance by at least TICK_NSEC:
3726 if (unlikely(rq
->clock
< next_tick
)) {
3727 rq
->clock
= next_tick
;
3728 rq
->clock_underflows
++;
3730 rq
->tick_timestamp
= rq
->clock
;
3731 update_cpu_load(rq
);
3732 curr
->sched_class
->task_tick(rq
, curr
, 0);
3733 update_sched_rt_period(rq
);
3734 spin_unlock(&rq
->lock
);
3737 rq
->idle_at_tick
= idle_cpu(cpu
);
3738 trigger_load_balance(rq
, cpu
);
3742 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3744 void add_preempt_count(int val
)
3749 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3751 preempt_count() += val
;
3753 * Spinlock count overflowing soon?
3755 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK
) >=
3758 EXPORT_SYMBOL(add_preempt_count
);
3760 void sub_preempt_count(int val
)
3765 if (DEBUG_LOCKS_WARN_ON(val
> preempt_count()))
3768 * Is the spinlock portion underflowing?
3770 if (DEBUG_LOCKS_WARN_ON((val
< PREEMPT_MASK
) &&
3771 !(preempt_count() & PREEMPT_MASK
)))
3774 preempt_count() -= val
;
3776 EXPORT_SYMBOL(sub_preempt_count
);
3781 * Print scheduling while atomic bug:
3783 static noinline
void __schedule_bug(struct task_struct
*prev
)
3785 struct pt_regs
*regs
= get_irq_regs();
3787 printk(KERN_ERR
"BUG: scheduling while atomic: %s/%d/0x%08x\n",
3788 prev
->comm
, prev
->pid
, preempt_count());
3790 debug_show_held_locks(prev
);
3791 if (irqs_disabled())
3792 print_irqtrace_events(prev
);
3801 * Various schedule()-time debugging checks and statistics:
3803 static inline void schedule_debug(struct task_struct
*prev
)
3806 * Test if we are atomic. Since do_exit() needs to call into
3807 * schedule() atomically, we ignore that path for now.
3808 * Otherwise, whine if we are scheduling when we should not be.
3810 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev
->exit_state
))
3811 __schedule_bug(prev
);
3813 profile_hit(SCHED_PROFILING
, __builtin_return_address(0));
3815 schedstat_inc(this_rq(), sched_count
);
3816 #ifdef CONFIG_SCHEDSTATS
3817 if (unlikely(prev
->lock_depth
>= 0)) {
3818 schedstat_inc(this_rq(), bkl_count
);
3819 schedstat_inc(prev
, sched_info
.bkl_count
);
3825 * Pick up the highest-prio task:
3827 static inline struct task_struct
*
3828 pick_next_task(struct rq
*rq
, struct task_struct
*prev
)
3830 const struct sched_class
*class;
3831 struct task_struct
*p
;
3834 * Optimization: we know that if all tasks are in
3835 * the fair class we can call that function directly:
3837 if (likely(rq
->nr_running
== rq
->cfs
.nr_running
)) {
3838 p
= fair_sched_class
.pick_next_task(rq
);
3843 class = sched_class_highest
;
3845 p
= class->pick_next_task(rq
);
3849 * Will never be NULL as the idle class always
3850 * returns a non-NULL p:
3852 class = class->next
;
3857 * schedule() is the main scheduler function.
3859 asmlinkage
void __sched
schedule(void)
3861 struct task_struct
*prev
, *next
;
3868 cpu
= smp_processor_id();
3872 switch_count
= &prev
->nivcsw
;
3874 release_kernel_lock(prev
);
3875 need_resched_nonpreemptible
:
3877 schedule_debug(prev
);
3882 * Do the rq-clock update outside the rq lock:
3884 local_irq_disable();
3885 __update_rq_clock(rq
);
3886 spin_lock(&rq
->lock
);
3887 clear_tsk_need_resched(prev
);
3889 if (prev
->state
&& !(preempt_count() & PREEMPT_ACTIVE
)) {
3890 if (unlikely((prev
->state
& TASK_INTERRUPTIBLE
) &&
3891 unlikely(signal_pending(prev
)))) {
3892 prev
->state
= TASK_RUNNING
;
3894 deactivate_task(rq
, prev
, 1);
3896 switch_count
= &prev
->nvcsw
;
3900 if (prev
->sched_class
->pre_schedule
)
3901 prev
->sched_class
->pre_schedule(rq
, prev
);
3904 if (unlikely(!rq
->nr_running
))
3905 idle_balance(cpu
, rq
);
3907 prev
->sched_class
->put_prev_task(rq
, prev
);
3908 next
= pick_next_task(rq
, prev
);
3910 sched_info_switch(prev
, next
);
3912 if (likely(prev
!= next
)) {
3917 context_switch(rq
, prev
, next
); /* unlocks the rq */
3919 * the context switch might have flipped the stack from under
3920 * us, hence refresh the local variables.
3922 cpu
= smp_processor_id();
3925 spin_unlock_irq(&rq
->lock
);
3929 if (unlikely(reacquire_kernel_lock(current
) < 0))
3930 goto need_resched_nonpreemptible
;
3932 preempt_enable_no_resched();
3933 if (unlikely(test_thread_flag(TIF_NEED_RESCHED
)))
3936 EXPORT_SYMBOL(schedule
);
3938 #ifdef CONFIG_PREEMPT
3940 * this is the entry point to schedule() from in-kernel preemption
3941 * off of preempt_enable. Kernel preemptions off return from interrupt
3942 * occur there and call schedule directly.
3944 asmlinkage
void __sched
preempt_schedule(void)
3946 struct thread_info
*ti
= current_thread_info();
3947 struct task_struct
*task
= current
;
3948 int saved_lock_depth
;
3951 * If there is a non-zero preempt_count or interrupts are disabled,
3952 * we do not want to preempt the current task. Just return..
3954 if (likely(ti
->preempt_count
|| irqs_disabled()))
3958 add_preempt_count(PREEMPT_ACTIVE
);
3961 * We keep the big kernel semaphore locked, but we
3962 * clear ->lock_depth so that schedule() doesnt
3963 * auto-release the semaphore:
3965 saved_lock_depth
= task
->lock_depth
;
3966 task
->lock_depth
= -1;
3968 task
->lock_depth
= saved_lock_depth
;
3969 sub_preempt_count(PREEMPT_ACTIVE
);
3972 * Check again in case we missed a preemption opportunity
3973 * between schedule and now.
3976 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED
)));
3978 EXPORT_SYMBOL(preempt_schedule
);
3981 * this is the entry point to schedule() from kernel preemption
3982 * off of irq context.
3983 * Note, that this is called and return with irqs disabled. This will
3984 * protect us against recursive calling from irq.
3986 asmlinkage
void __sched
preempt_schedule_irq(void)
3988 struct thread_info
*ti
= current_thread_info();
3989 struct task_struct
*task
= current
;
3990 int saved_lock_depth
;
3992 /* Catch callers which need to be fixed */
3993 BUG_ON(ti
->preempt_count
|| !irqs_disabled());
3996 add_preempt_count(PREEMPT_ACTIVE
);
3999 * We keep the big kernel semaphore locked, but we
4000 * clear ->lock_depth so that schedule() doesnt
4001 * auto-release the semaphore:
4003 saved_lock_depth
= task
->lock_depth
;
4004 task
->lock_depth
= -1;
4007 local_irq_disable();
4008 task
->lock_depth
= saved_lock_depth
;
4009 sub_preempt_count(PREEMPT_ACTIVE
);
4012 * Check again in case we missed a preemption opportunity
4013 * between schedule and now.
4016 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED
)));
4019 #endif /* CONFIG_PREEMPT */
4021 int default_wake_function(wait_queue_t
*curr
, unsigned mode
, int sync
,
4024 return try_to_wake_up(curr
->private, mode
, sync
);
4026 EXPORT_SYMBOL(default_wake_function
);
4029 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4030 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4031 * number) then we wake all the non-exclusive tasks and one exclusive task.
4033 * There are circumstances in which we can try to wake a task which has already
4034 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4035 * zero in this (rare) case, and we handle it by continuing to scan the queue.
4037 static void __wake_up_common(wait_queue_head_t
*q
, unsigned int mode
,
4038 int nr_exclusive
, int sync
, void *key
)
4040 wait_queue_t
*curr
, *next
;
4042 list_for_each_entry_safe(curr
, next
, &q
->task_list
, task_list
) {
4043 unsigned flags
= curr
->flags
;
4045 if (curr
->func(curr
, mode
, sync
, key
) &&
4046 (flags
& WQ_FLAG_EXCLUSIVE
) && !--nr_exclusive
)
4052 * __wake_up - wake up threads blocked on a waitqueue.
4054 * @mode: which threads
4055 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4056 * @key: is directly passed to the wakeup function
4058 void __wake_up(wait_queue_head_t
*q
, unsigned int mode
,
4059 int nr_exclusive
, void *key
)
4061 unsigned long flags
;
4063 spin_lock_irqsave(&q
->lock
, flags
);
4064 __wake_up_common(q
, mode
, nr_exclusive
, 0, key
);
4065 spin_unlock_irqrestore(&q
->lock
, flags
);
4067 EXPORT_SYMBOL(__wake_up
);
4070 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4072 void __wake_up_locked(wait_queue_head_t
*q
, unsigned int mode
)
4074 __wake_up_common(q
, mode
, 1, 0, NULL
);
4078 * __wake_up_sync - 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
4083 * The sync wakeup differs that the waker knows that it will schedule
4084 * away soon, so while the target thread will be woken up, it will not
4085 * be migrated to another CPU - ie. the two threads are 'synchronized'
4086 * with each other. This can prevent needless bouncing between CPUs.
4088 * On UP it can prevent extra preemption.
4091 __wake_up_sync(wait_queue_head_t
*q
, unsigned int mode
, int nr_exclusive
)
4093 unsigned long flags
;
4099 if (unlikely(!nr_exclusive
))
4102 spin_lock_irqsave(&q
->lock
, flags
);
4103 __wake_up_common(q
, mode
, nr_exclusive
, sync
, NULL
);
4104 spin_unlock_irqrestore(&q
->lock
, flags
);
4106 EXPORT_SYMBOL_GPL(__wake_up_sync
); /* For internal use only */
4108 void complete(struct completion
*x
)
4110 unsigned long flags
;
4112 spin_lock_irqsave(&x
->wait
.lock
, flags
);
4114 __wake_up_common(&x
->wait
, TASK_NORMAL
, 1, 0, NULL
);
4115 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
4117 EXPORT_SYMBOL(complete
);
4119 void complete_all(struct completion
*x
)
4121 unsigned long flags
;
4123 spin_lock_irqsave(&x
->wait
.lock
, flags
);
4124 x
->done
+= UINT_MAX
/2;
4125 __wake_up_common(&x
->wait
, TASK_NORMAL
, 0, 0, NULL
);
4126 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
4128 EXPORT_SYMBOL(complete_all
);
4130 static inline long __sched
4131 do_wait_for_common(struct completion
*x
, long timeout
, int state
)
4134 DECLARE_WAITQUEUE(wait
, current
);
4136 wait
.flags
|= WQ_FLAG_EXCLUSIVE
;
4137 __add_wait_queue_tail(&x
->wait
, &wait
);
4139 if ((state
== TASK_INTERRUPTIBLE
&&
4140 signal_pending(current
)) ||
4141 (state
== TASK_KILLABLE
&&
4142 fatal_signal_pending(current
))) {
4143 __remove_wait_queue(&x
->wait
, &wait
);
4144 return -ERESTARTSYS
;
4146 __set_current_state(state
);
4147 spin_unlock_irq(&x
->wait
.lock
);
4148 timeout
= schedule_timeout(timeout
);
4149 spin_lock_irq(&x
->wait
.lock
);
4151 __remove_wait_queue(&x
->wait
, &wait
);
4155 __remove_wait_queue(&x
->wait
, &wait
);
4162 wait_for_common(struct completion
*x
, long timeout
, int state
)
4166 spin_lock_irq(&x
->wait
.lock
);
4167 timeout
= do_wait_for_common(x
, timeout
, state
);
4168 spin_unlock_irq(&x
->wait
.lock
);
4172 void __sched
wait_for_completion(struct completion
*x
)
4174 wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_UNINTERRUPTIBLE
);
4176 EXPORT_SYMBOL(wait_for_completion
);
4178 unsigned long __sched
4179 wait_for_completion_timeout(struct completion
*x
, unsigned long timeout
)
4181 return wait_for_common(x
, timeout
, TASK_UNINTERRUPTIBLE
);
4183 EXPORT_SYMBOL(wait_for_completion_timeout
);
4185 int __sched
wait_for_completion_interruptible(struct completion
*x
)
4187 long t
= wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_INTERRUPTIBLE
);
4188 if (t
== -ERESTARTSYS
)
4192 EXPORT_SYMBOL(wait_for_completion_interruptible
);
4194 unsigned long __sched
4195 wait_for_completion_interruptible_timeout(struct completion
*x
,
4196 unsigned long timeout
)
4198 return wait_for_common(x
, timeout
, TASK_INTERRUPTIBLE
);
4200 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout
);
4202 int __sched
wait_for_completion_killable(struct completion
*x
)
4204 long t
= wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_KILLABLE
);
4205 if (t
== -ERESTARTSYS
)
4209 EXPORT_SYMBOL(wait_for_completion_killable
);
4212 sleep_on_common(wait_queue_head_t
*q
, int state
, long timeout
)
4214 unsigned long flags
;
4217 init_waitqueue_entry(&wait
, current
);
4219 __set_current_state(state
);
4221 spin_lock_irqsave(&q
->lock
, flags
);
4222 __add_wait_queue(q
, &wait
);
4223 spin_unlock(&q
->lock
);
4224 timeout
= schedule_timeout(timeout
);
4225 spin_lock_irq(&q
->lock
);
4226 __remove_wait_queue(q
, &wait
);
4227 spin_unlock_irqrestore(&q
->lock
, flags
);
4232 void __sched
interruptible_sleep_on(wait_queue_head_t
*q
)
4234 sleep_on_common(q
, TASK_INTERRUPTIBLE
, MAX_SCHEDULE_TIMEOUT
);
4236 EXPORT_SYMBOL(interruptible_sleep_on
);
4239 interruptible_sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
4241 return sleep_on_common(q
, TASK_INTERRUPTIBLE
, timeout
);
4243 EXPORT_SYMBOL(interruptible_sleep_on_timeout
);
4245 void __sched
sleep_on(wait_queue_head_t
*q
)
4247 sleep_on_common(q
, TASK_UNINTERRUPTIBLE
, MAX_SCHEDULE_TIMEOUT
);
4249 EXPORT_SYMBOL(sleep_on
);
4251 long __sched
sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
4253 return sleep_on_common(q
, TASK_UNINTERRUPTIBLE
, timeout
);
4255 EXPORT_SYMBOL(sleep_on_timeout
);
4257 #ifdef CONFIG_RT_MUTEXES
4260 * rt_mutex_setprio - set the current priority of a task
4262 * @prio: prio value (kernel-internal form)
4264 * This function changes the 'effective' priority of a task. It does
4265 * not touch ->normal_prio like __setscheduler().
4267 * Used by the rt_mutex code to implement priority inheritance logic.
4269 void rt_mutex_setprio(struct task_struct
*p
, int prio
)
4271 unsigned long flags
;
4272 int oldprio
, on_rq
, running
;
4274 const struct sched_class
*prev_class
= p
->sched_class
;
4276 BUG_ON(prio
< 0 || prio
> MAX_PRIO
);
4278 rq
= task_rq_lock(p
, &flags
);
4279 update_rq_clock(rq
);
4282 on_rq
= p
->se
.on_rq
;
4283 running
= task_current(rq
, p
);
4285 dequeue_task(rq
, p
, 0);
4287 p
->sched_class
->put_prev_task(rq
, p
);
4291 p
->sched_class
= &rt_sched_class
;
4293 p
->sched_class
= &fair_sched_class
;
4299 p
->sched_class
->set_curr_task(rq
);
4301 enqueue_task(rq
, p
, 0);
4303 check_class_changed(rq
, p
, prev_class
, oldprio
, running
);
4305 task_rq_unlock(rq
, &flags
);
4310 void set_user_nice(struct task_struct
*p
, long nice
)
4312 int old_prio
, delta
, on_rq
;
4313 unsigned long flags
;
4316 if (TASK_NICE(p
) == nice
|| nice
< -20 || nice
> 19)
4319 * We have to be careful, if called from sys_setpriority(),
4320 * the task might be in the middle of scheduling on another CPU.
4322 rq
= task_rq_lock(p
, &flags
);
4323 update_rq_clock(rq
);
4325 * The RT priorities are set via sched_setscheduler(), but we still
4326 * allow the 'normal' nice value to be set - but as expected
4327 * it wont have any effect on scheduling until the task is
4328 * SCHED_FIFO/SCHED_RR:
4330 if (task_has_rt_policy(p
)) {
4331 p
->static_prio
= NICE_TO_PRIO(nice
);
4334 on_rq
= p
->se
.on_rq
;
4336 dequeue_task(rq
, p
, 0);
4338 p
->static_prio
= NICE_TO_PRIO(nice
);
4341 p
->prio
= effective_prio(p
);
4342 delta
= p
->prio
- old_prio
;
4345 enqueue_task(rq
, p
, 0);
4347 * If the task increased its priority or is running and
4348 * lowered its priority, then reschedule its CPU:
4350 if (delta
< 0 || (delta
> 0 && task_running(rq
, p
)))
4351 resched_task(rq
->curr
);
4354 task_rq_unlock(rq
, &flags
);
4356 EXPORT_SYMBOL(set_user_nice
);
4359 * can_nice - check if a task can reduce its nice value
4363 int can_nice(const struct task_struct
*p
, const int nice
)
4365 /* convert nice value [19,-20] to rlimit style value [1,40] */
4366 int nice_rlim
= 20 - nice
;
4368 return (nice_rlim
<= p
->signal
->rlim
[RLIMIT_NICE
].rlim_cur
||
4369 capable(CAP_SYS_NICE
));
4372 #ifdef __ARCH_WANT_SYS_NICE
4375 * sys_nice - change the priority of the current process.
4376 * @increment: priority increment
4378 * sys_setpriority is a more generic, but much slower function that
4379 * does similar things.
4381 asmlinkage
long sys_nice(int increment
)
4386 * Setpriority might change our priority at the same moment.
4387 * We don't have to worry. Conceptually one call occurs first
4388 * and we have a single winner.
4390 if (increment
< -40)
4395 nice
= PRIO_TO_NICE(current
->static_prio
) + increment
;
4401 if (increment
< 0 && !can_nice(current
, nice
))
4404 retval
= security_task_setnice(current
, nice
);
4408 set_user_nice(current
, nice
);
4415 * task_prio - return the priority value of a given task.
4416 * @p: the task in question.
4418 * This is the priority value as seen by users in /proc.
4419 * RT tasks are offset by -200. Normal tasks are centered
4420 * around 0, value goes from -16 to +15.
4422 int task_prio(const struct task_struct
*p
)
4424 return p
->prio
- MAX_RT_PRIO
;
4428 * task_nice - return the nice value of a given task.
4429 * @p: the task in question.
4431 int task_nice(const struct task_struct
*p
)
4433 return TASK_NICE(p
);
4435 EXPORT_SYMBOL_GPL(task_nice
);
4438 * idle_cpu - is a given cpu idle currently?
4439 * @cpu: the processor in question.
4441 int idle_cpu(int cpu
)
4443 return cpu_curr(cpu
) == cpu_rq(cpu
)->idle
;
4447 * idle_task - return the idle task for a given cpu.
4448 * @cpu: the processor in question.
4450 struct task_struct
*idle_task(int cpu
)
4452 return cpu_rq(cpu
)->idle
;
4456 * find_process_by_pid - find a process with a matching PID value.
4457 * @pid: the pid in question.
4459 static struct task_struct
*find_process_by_pid(pid_t pid
)
4461 return pid
? find_task_by_vpid(pid
) : current
;
4464 /* Actually do priority change: must hold rq lock. */
4466 __setscheduler(struct rq
*rq
, struct task_struct
*p
, int policy
, int prio
)
4468 BUG_ON(p
->se
.on_rq
);
4471 switch (p
->policy
) {
4475 p
->sched_class
= &fair_sched_class
;
4479 p
->sched_class
= &rt_sched_class
;
4483 p
->rt_priority
= prio
;
4484 p
->normal_prio
= normal_prio(p
);
4485 /* we are holding p->pi_lock already */
4486 p
->prio
= rt_mutex_getprio(p
);
4491 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4492 * @p: the task in question.
4493 * @policy: new policy.
4494 * @param: structure containing the new RT priority.
4496 * NOTE that the task may be already dead.
4498 int sched_setscheduler(struct task_struct
*p
, int policy
,
4499 struct sched_param
*param
)
4501 int retval
, oldprio
, oldpolicy
= -1, on_rq
, running
;
4502 unsigned long flags
;
4503 const struct sched_class
*prev_class
= p
->sched_class
;
4506 /* may grab non-irq protected spin_locks */
4507 BUG_ON(in_interrupt());
4509 /* double check policy once rq lock held */
4511 policy
= oldpolicy
= p
->policy
;
4512 else if (policy
!= SCHED_FIFO
&& policy
!= SCHED_RR
&&
4513 policy
!= SCHED_NORMAL
&& policy
!= SCHED_BATCH
&&
4514 policy
!= SCHED_IDLE
)
4517 * Valid priorities for SCHED_FIFO and SCHED_RR are
4518 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4519 * SCHED_BATCH and SCHED_IDLE is 0.
4521 if (param
->sched_priority
< 0 ||
4522 (p
->mm
&& param
->sched_priority
> MAX_USER_RT_PRIO
-1) ||
4523 (!p
->mm
&& param
->sched_priority
> MAX_RT_PRIO
-1))
4525 if (rt_policy(policy
) != (param
->sched_priority
!= 0))
4529 * Allow unprivileged RT tasks to decrease priority:
4531 if (!capable(CAP_SYS_NICE
)) {
4532 if (rt_policy(policy
)) {
4533 unsigned long rlim_rtprio
;
4535 if (!lock_task_sighand(p
, &flags
))
4537 rlim_rtprio
= p
->signal
->rlim
[RLIMIT_RTPRIO
].rlim_cur
;
4538 unlock_task_sighand(p
, &flags
);
4540 /* can't set/change the rt policy */
4541 if (policy
!= p
->policy
&& !rlim_rtprio
)
4544 /* can't increase priority */
4545 if (param
->sched_priority
> p
->rt_priority
&&
4546 param
->sched_priority
> rlim_rtprio
)
4550 * Like positive nice levels, dont allow tasks to
4551 * move out of SCHED_IDLE either:
4553 if (p
->policy
== SCHED_IDLE
&& policy
!= SCHED_IDLE
)
4556 /* can't change other user's priorities */
4557 if ((current
->euid
!= p
->euid
) &&
4558 (current
->euid
!= p
->uid
))
4562 retval
= security_task_setscheduler(p
, policy
, param
);
4566 * make sure no PI-waiters arrive (or leave) while we are
4567 * changing the priority of the task:
4569 spin_lock_irqsave(&p
->pi_lock
, flags
);
4571 * To be able to change p->policy safely, the apropriate
4572 * runqueue lock must be held.
4574 rq
= __task_rq_lock(p
);
4575 /* recheck policy now with rq lock held */
4576 if (unlikely(oldpolicy
!= -1 && oldpolicy
!= p
->policy
)) {
4577 policy
= oldpolicy
= -1;
4578 __task_rq_unlock(rq
);
4579 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
4582 update_rq_clock(rq
);
4583 on_rq
= p
->se
.on_rq
;
4584 running
= task_current(rq
, p
);
4586 deactivate_task(rq
, p
, 0);
4588 p
->sched_class
->put_prev_task(rq
, p
);
4592 __setscheduler(rq
, p
, policy
, param
->sched_priority
);
4596 p
->sched_class
->set_curr_task(rq
);
4598 activate_task(rq
, p
, 0);
4600 check_class_changed(rq
, p
, prev_class
, oldprio
, running
);
4602 __task_rq_unlock(rq
);
4603 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
4605 rt_mutex_adjust_pi(p
);
4609 EXPORT_SYMBOL_GPL(sched_setscheduler
);
4612 do_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
4614 struct sched_param lparam
;
4615 struct task_struct
*p
;
4618 if (!param
|| pid
< 0)
4620 if (copy_from_user(&lparam
, param
, sizeof(struct sched_param
)))
4625 p
= find_process_by_pid(pid
);
4627 retval
= sched_setscheduler(p
, policy
, &lparam
);
4634 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4635 * @pid: the pid in question.
4636 * @policy: new policy.
4637 * @param: structure containing the new RT priority.
4640 sys_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
4642 /* negative values for policy are not valid */
4646 return do_sched_setscheduler(pid
, policy
, param
);
4650 * sys_sched_setparam - set/change the RT priority of a thread
4651 * @pid: the pid in question.
4652 * @param: structure containing the new RT priority.
4654 asmlinkage
long sys_sched_setparam(pid_t pid
, struct sched_param __user
*param
)
4656 return do_sched_setscheduler(pid
, -1, param
);
4660 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4661 * @pid: the pid in question.
4663 asmlinkage
long sys_sched_getscheduler(pid_t pid
)
4665 struct task_struct
*p
;
4672 read_lock(&tasklist_lock
);
4673 p
= find_process_by_pid(pid
);
4675 retval
= security_task_getscheduler(p
);
4679 read_unlock(&tasklist_lock
);
4684 * sys_sched_getscheduler - get the RT priority of a thread
4685 * @pid: the pid in question.
4686 * @param: structure containing the RT priority.
4688 asmlinkage
long sys_sched_getparam(pid_t pid
, struct sched_param __user
*param
)
4690 struct sched_param lp
;
4691 struct task_struct
*p
;
4694 if (!param
|| pid
< 0)
4697 read_lock(&tasklist_lock
);
4698 p
= find_process_by_pid(pid
);
4703 retval
= security_task_getscheduler(p
);
4707 lp
.sched_priority
= p
->rt_priority
;
4708 read_unlock(&tasklist_lock
);
4711 * This one might sleep, we cannot do it with a spinlock held ...
4713 retval
= copy_to_user(param
, &lp
, sizeof(*param
)) ? -EFAULT
: 0;
4718 read_unlock(&tasklist_lock
);
4722 long sched_setaffinity(pid_t pid
, cpumask_t new_mask
)
4724 cpumask_t cpus_allowed
;
4725 struct task_struct
*p
;
4729 read_lock(&tasklist_lock
);
4731 p
= find_process_by_pid(pid
);
4733 read_unlock(&tasklist_lock
);
4739 * It is not safe to call set_cpus_allowed with the
4740 * tasklist_lock held. We will bump the task_struct's
4741 * usage count and then drop tasklist_lock.
4744 read_unlock(&tasklist_lock
);
4747 if ((current
->euid
!= p
->euid
) && (current
->euid
!= p
->uid
) &&
4748 !capable(CAP_SYS_NICE
))
4751 retval
= security_task_setscheduler(p
, 0, NULL
);
4755 cpus_allowed
= cpuset_cpus_allowed(p
);
4756 cpus_and(new_mask
, new_mask
, cpus_allowed
);
4758 retval
= set_cpus_allowed(p
, new_mask
);
4761 cpus_allowed
= cpuset_cpus_allowed(p
);
4762 if (!cpus_subset(new_mask
, cpus_allowed
)) {
4764 * We must have raced with a concurrent cpuset
4765 * update. Just reset the cpus_allowed to the
4766 * cpuset's cpus_allowed
4768 new_mask
= cpus_allowed
;
4778 static int get_user_cpu_mask(unsigned long __user
*user_mask_ptr
, unsigned len
,
4779 cpumask_t
*new_mask
)
4781 if (len
< sizeof(cpumask_t
)) {
4782 memset(new_mask
, 0, sizeof(cpumask_t
));
4783 } else if (len
> sizeof(cpumask_t
)) {
4784 len
= sizeof(cpumask_t
);
4786 return copy_from_user(new_mask
, user_mask_ptr
, len
) ? -EFAULT
: 0;
4790 * sys_sched_setaffinity - set the cpu affinity of a process
4791 * @pid: pid of the process
4792 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4793 * @user_mask_ptr: user-space pointer to the new cpu mask
4795 asmlinkage
long sys_sched_setaffinity(pid_t pid
, unsigned int len
,
4796 unsigned long __user
*user_mask_ptr
)
4801 retval
= get_user_cpu_mask(user_mask_ptr
, len
, &new_mask
);
4805 return sched_setaffinity(pid
, new_mask
);
4809 * Represents all cpu's present in the system
4810 * In systems capable of hotplug, this map could dynamically grow
4811 * as new cpu's are detected in the system via any platform specific
4812 * method, such as ACPI for e.g.
4815 cpumask_t cpu_present_map __read_mostly
;
4816 EXPORT_SYMBOL(cpu_present_map
);
4819 cpumask_t cpu_online_map __read_mostly
= CPU_MASK_ALL
;
4820 EXPORT_SYMBOL(cpu_online_map
);
4822 cpumask_t cpu_possible_map __read_mostly
= CPU_MASK_ALL
;
4823 EXPORT_SYMBOL(cpu_possible_map
);
4826 long sched_getaffinity(pid_t pid
, cpumask_t
*mask
)
4828 struct task_struct
*p
;
4832 read_lock(&tasklist_lock
);
4835 p
= find_process_by_pid(pid
);
4839 retval
= security_task_getscheduler(p
);
4843 cpus_and(*mask
, p
->cpus_allowed
, cpu_online_map
);
4846 read_unlock(&tasklist_lock
);
4853 * sys_sched_getaffinity - get the cpu affinity of a process
4854 * @pid: pid of the process
4855 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4856 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4858 asmlinkage
long sys_sched_getaffinity(pid_t pid
, unsigned int len
,
4859 unsigned long __user
*user_mask_ptr
)
4864 if (len
< sizeof(cpumask_t
))
4867 ret
= sched_getaffinity(pid
, &mask
);
4871 if (copy_to_user(user_mask_ptr
, &mask
, sizeof(cpumask_t
)))
4874 return sizeof(cpumask_t
);
4878 * sys_sched_yield - yield the current processor to other threads.
4880 * This function yields the current CPU to other tasks. If there are no
4881 * other threads running on this CPU then this function will return.
4883 asmlinkage
long sys_sched_yield(void)
4885 struct rq
*rq
= this_rq_lock();
4887 schedstat_inc(rq
, yld_count
);
4888 current
->sched_class
->yield_task(rq
);
4891 * Since we are going to call schedule() anyway, there's
4892 * no need to preempt or enable interrupts:
4894 __release(rq
->lock
);
4895 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
4896 _raw_spin_unlock(&rq
->lock
);
4897 preempt_enable_no_resched();
4904 static void __cond_resched(void)
4906 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4907 __might_sleep(__FILE__
, __LINE__
);
4910 * The BKS might be reacquired before we have dropped
4911 * PREEMPT_ACTIVE, which could trigger a second
4912 * cond_resched() call.
4915 add_preempt_count(PREEMPT_ACTIVE
);
4917 sub_preempt_count(PREEMPT_ACTIVE
);
4918 } while (need_resched());
4921 #if !defined(CONFIG_PREEMPT) || defined(CONFIG_PREEMPT_VOLUNTARY)
4922 int __sched
_cond_resched(void)
4924 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE
) &&
4925 system_state
== SYSTEM_RUNNING
) {
4931 EXPORT_SYMBOL(_cond_resched
);
4935 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4936 * call schedule, and on return reacquire the lock.
4938 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4939 * operations here to prevent schedule() from being called twice (once via
4940 * spin_unlock(), once by hand).
4942 int cond_resched_lock(spinlock_t
*lock
)
4944 int resched
= need_resched() && system_state
== SYSTEM_RUNNING
;
4947 if (spin_needbreak(lock
) || resched
) {
4949 if (resched
&& need_resched())
4958 EXPORT_SYMBOL(cond_resched_lock
);
4960 int __sched
cond_resched_softirq(void)
4962 BUG_ON(!in_softirq());
4964 if (need_resched() && system_state
== SYSTEM_RUNNING
) {
4972 EXPORT_SYMBOL(cond_resched_softirq
);
4975 * yield - yield the current processor to other threads.
4977 * This is a shortcut for kernel-space yielding - it marks the
4978 * thread runnable and calls sys_sched_yield().
4980 void __sched
yield(void)
4982 set_current_state(TASK_RUNNING
);
4985 EXPORT_SYMBOL(yield
);
4988 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4989 * that process accounting knows that this is a task in IO wait state.
4991 * But don't do that if it is a deliberate, throttling IO wait (this task
4992 * has set its backing_dev_info: the queue against which it should throttle)
4994 void __sched
io_schedule(void)
4996 struct rq
*rq
= &__raw_get_cpu_var(runqueues
);
4998 delayacct_blkio_start();
4999 atomic_inc(&rq
->nr_iowait
);
5001 atomic_dec(&rq
->nr_iowait
);
5002 delayacct_blkio_end();
5004 EXPORT_SYMBOL(io_schedule
);
5006 long __sched
io_schedule_timeout(long timeout
)
5008 struct rq
*rq
= &__raw_get_cpu_var(runqueues
);
5011 delayacct_blkio_start();
5012 atomic_inc(&rq
->nr_iowait
);
5013 ret
= schedule_timeout(timeout
);
5014 atomic_dec(&rq
->nr_iowait
);
5015 delayacct_blkio_end();
5020 * sys_sched_get_priority_max - return maximum RT priority.
5021 * @policy: scheduling class.
5023 * this syscall returns the maximum rt_priority that can be used
5024 * by a given scheduling class.
5026 asmlinkage
long sys_sched_get_priority_max(int policy
)
5033 ret
= MAX_USER_RT_PRIO
-1;
5045 * sys_sched_get_priority_min - return minimum RT priority.
5046 * @policy: scheduling class.
5048 * this syscall returns the minimum rt_priority that can be used
5049 * by a given scheduling class.
5051 asmlinkage
long sys_sched_get_priority_min(int policy
)
5069 * sys_sched_rr_get_interval - return the default timeslice of a process.
5070 * @pid: pid of the process.
5071 * @interval: userspace pointer to the timeslice value.
5073 * this syscall writes the default timeslice value of a given process
5074 * into the user-space timespec buffer. A value of '0' means infinity.
5077 long sys_sched_rr_get_interval(pid_t pid
, struct timespec __user
*interval
)
5079 struct task_struct
*p
;
5080 unsigned int time_slice
;
5088 read_lock(&tasklist_lock
);
5089 p
= find_process_by_pid(pid
);
5093 retval
= security_task_getscheduler(p
);
5098 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5099 * tasks that are on an otherwise idle runqueue:
5102 if (p
->policy
== SCHED_RR
) {
5103 time_slice
= DEF_TIMESLICE
;
5105 struct sched_entity
*se
= &p
->se
;
5106 unsigned long flags
;
5109 rq
= task_rq_lock(p
, &flags
);
5110 if (rq
->cfs
.load
.weight
)
5111 time_slice
= NS_TO_JIFFIES(sched_slice(&rq
->cfs
, se
));
5112 task_rq_unlock(rq
, &flags
);
5114 read_unlock(&tasklist_lock
);
5115 jiffies_to_timespec(time_slice
, &t
);
5116 retval
= copy_to_user(interval
, &t
, sizeof(t
)) ? -EFAULT
: 0;
5120 read_unlock(&tasklist_lock
);
5124 static const char stat_nam
[] = "RSDTtZX";
5126 void sched_show_task(struct task_struct
*p
)
5128 unsigned long free
= 0;
5131 state
= p
->state
? __ffs(p
->state
) + 1 : 0;
5132 printk(KERN_INFO
"%-13.13s %c", p
->comm
,
5133 state
< sizeof(stat_nam
) - 1 ? stat_nam
[state
] : '?');
5134 #if BITS_PER_LONG == 32
5135 if (state
== TASK_RUNNING
)
5136 printk(KERN_CONT
" running ");
5138 printk(KERN_CONT
" %08lx ", thread_saved_pc(p
));
5140 if (state
== TASK_RUNNING
)
5141 printk(KERN_CONT
" running task ");
5143 printk(KERN_CONT
" %016lx ", thread_saved_pc(p
));
5145 #ifdef CONFIG_DEBUG_STACK_USAGE
5147 unsigned long *n
= end_of_stack(p
);
5150 free
= (unsigned long)n
- (unsigned long)end_of_stack(p
);
5153 printk(KERN_CONT
"%5lu %5d %6d\n", free
,
5154 task_pid_nr(p
), task_pid_nr(p
->real_parent
));
5156 show_stack(p
, NULL
);
5159 void show_state_filter(unsigned long state_filter
)
5161 struct task_struct
*g
, *p
;
5163 #if BITS_PER_LONG == 32
5165 " task PC stack pid father\n");
5168 " task PC stack pid father\n");
5170 read_lock(&tasklist_lock
);
5171 do_each_thread(g
, p
) {
5173 * reset the NMI-timeout, listing all files on a slow
5174 * console might take alot of time:
5176 touch_nmi_watchdog();
5177 if (!state_filter
|| (p
->state
& state_filter
))
5179 } while_each_thread(g
, p
);
5181 touch_all_softlockup_watchdogs();
5183 #ifdef CONFIG_SCHED_DEBUG
5184 sysrq_sched_debug_show();
5186 read_unlock(&tasklist_lock
);
5188 * Only show locks if all tasks are dumped:
5190 if (state_filter
== -1)
5191 debug_show_all_locks();
5194 void __cpuinit
init_idle_bootup_task(struct task_struct
*idle
)
5196 idle
->sched_class
= &idle_sched_class
;
5200 * init_idle - set up an idle thread for a given CPU
5201 * @idle: task in question
5202 * @cpu: cpu the idle task belongs to
5204 * NOTE: this function does not set the idle thread's NEED_RESCHED
5205 * flag, to make booting more robust.
5207 void __cpuinit
init_idle(struct task_struct
*idle
, int cpu
)
5209 struct rq
*rq
= cpu_rq(cpu
);
5210 unsigned long flags
;
5213 idle
->se
.exec_start
= sched_clock();
5215 idle
->prio
= idle
->normal_prio
= MAX_PRIO
;
5216 idle
->cpus_allowed
= cpumask_of_cpu(cpu
);
5217 __set_task_cpu(idle
, cpu
);
5219 spin_lock_irqsave(&rq
->lock
, flags
);
5220 rq
->curr
= rq
->idle
= idle
;
5221 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5224 spin_unlock_irqrestore(&rq
->lock
, flags
);
5226 /* Set the preempt count _outside_ the spinlocks! */
5227 task_thread_info(idle
)->preempt_count
= 0;
5230 * The idle tasks have their own, simple scheduling class:
5232 idle
->sched_class
= &idle_sched_class
;
5236 * In a system that switches off the HZ timer nohz_cpu_mask
5237 * indicates which cpus entered this state. This is used
5238 * in the rcu update to wait only for active cpus. For system
5239 * which do not switch off the HZ timer nohz_cpu_mask should
5240 * always be CPU_MASK_NONE.
5242 cpumask_t nohz_cpu_mask
= CPU_MASK_NONE
;
5245 * Increase the granularity value when there are more CPUs,
5246 * because with more CPUs the 'effective latency' as visible
5247 * to users decreases. But the relationship is not linear,
5248 * so pick a second-best guess by going with the log2 of the
5251 * This idea comes from the SD scheduler of Con Kolivas:
5253 static inline void sched_init_granularity(void)
5255 unsigned int factor
= 1 + ilog2(num_online_cpus());
5256 const unsigned long limit
= 200000000;
5258 sysctl_sched_min_granularity
*= factor
;
5259 if (sysctl_sched_min_granularity
> limit
)
5260 sysctl_sched_min_granularity
= limit
;
5262 sysctl_sched_latency
*= factor
;
5263 if (sysctl_sched_latency
> limit
)
5264 sysctl_sched_latency
= limit
;
5266 sysctl_sched_wakeup_granularity
*= factor
;
5267 sysctl_sched_batch_wakeup_granularity
*= factor
;
5272 * This is how migration works:
5274 * 1) we queue a struct migration_req structure in the source CPU's
5275 * runqueue and wake up that CPU's migration thread.
5276 * 2) we down() the locked semaphore => thread blocks.
5277 * 3) migration thread wakes up (implicitly it forces the migrated
5278 * thread off the CPU)
5279 * 4) it gets the migration request and checks whether the migrated
5280 * task is still in the wrong runqueue.
5281 * 5) if it's in the wrong runqueue then the migration thread removes
5282 * it and puts it into the right queue.
5283 * 6) migration thread up()s the semaphore.
5284 * 7) we wake up and the migration is done.
5288 * Change a given task's CPU affinity. Migrate the thread to a
5289 * proper CPU and schedule it away if the CPU it's executing on
5290 * is removed from the allowed bitmask.
5292 * NOTE: the caller must have a valid reference to the task, the
5293 * task must not exit() & deallocate itself prematurely. The
5294 * call is not atomic; no spinlocks may be held.
5296 int set_cpus_allowed(struct task_struct
*p
, cpumask_t new_mask
)
5298 struct migration_req req
;
5299 unsigned long flags
;
5303 rq
= task_rq_lock(p
, &flags
);
5304 if (!cpus_intersects(new_mask
, cpu_online_map
)) {
5309 if (p
->sched_class
->set_cpus_allowed
)
5310 p
->sched_class
->set_cpus_allowed(p
, &new_mask
);
5312 p
->cpus_allowed
= new_mask
;
5313 p
->rt
.nr_cpus_allowed
= cpus_weight(new_mask
);
5316 /* Can the task run on the task's current CPU? If so, we're done */
5317 if (cpu_isset(task_cpu(p
), new_mask
))
5320 if (migrate_task(p
, any_online_cpu(new_mask
), &req
)) {
5321 /* Need help from migration thread: drop lock and wait. */
5322 task_rq_unlock(rq
, &flags
);
5323 wake_up_process(rq
->migration_thread
);
5324 wait_for_completion(&req
.done
);
5325 tlb_migrate_finish(p
->mm
);
5329 task_rq_unlock(rq
, &flags
);
5333 EXPORT_SYMBOL_GPL(set_cpus_allowed
);
5336 * Move (not current) task off this cpu, onto dest cpu. We're doing
5337 * this because either it can't run here any more (set_cpus_allowed()
5338 * away from this CPU, or CPU going down), or because we're
5339 * attempting to rebalance this task on exec (sched_exec).
5341 * So we race with normal scheduler movements, but that's OK, as long
5342 * as the task is no longer on this CPU.
5344 * Returns non-zero if task was successfully migrated.
5346 static int __migrate_task(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
5348 struct rq
*rq_dest
, *rq_src
;
5351 if (unlikely(cpu_is_offline(dest_cpu
)))
5354 rq_src
= cpu_rq(src_cpu
);
5355 rq_dest
= cpu_rq(dest_cpu
);
5357 double_rq_lock(rq_src
, rq_dest
);
5358 /* Already moved. */
5359 if (task_cpu(p
) != src_cpu
)
5361 /* Affinity changed (again). */
5362 if (!cpu_isset(dest_cpu
, p
->cpus_allowed
))
5365 on_rq
= p
->se
.on_rq
;
5367 deactivate_task(rq_src
, p
, 0);
5369 set_task_cpu(p
, dest_cpu
);
5371 activate_task(rq_dest
, p
, 0);
5372 check_preempt_curr(rq_dest
, p
);
5376 double_rq_unlock(rq_src
, rq_dest
);
5381 * migration_thread - this is a highprio system thread that performs
5382 * thread migration by bumping thread off CPU then 'pushing' onto
5385 static int migration_thread(void *data
)
5387 int cpu
= (long)data
;
5391 BUG_ON(rq
->migration_thread
!= current
);
5393 set_current_state(TASK_INTERRUPTIBLE
);
5394 while (!kthread_should_stop()) {
5395 struct migration_req
*req
;
5396 struct list_head
*head
;
5398 spin_lock_irq(&rq
->lock
);
5400 if (cpu_is_offline(cpu
)) {
5401 spin_unlock_irq(&rq
->lock
);
5405 if (rq
->active_balance
) {
5406 active_load_balance(rq
, cpu
);
5407 rq
->active_balance
= 0;
5410 head
= &rq
->migration_queue
;
5412 if (list_empty(head
)) {
5413 spin_unlock_irq(&rq
->lock
);
5415 set_current_state(TASK_INTERRUPTIBLE
);
5418 req
= list_entry(head
->next
, struct migration_req
, list
);
5419 list_del_init(head
->next
);
5421 spin_unlock(&rq
->lock
);
5422 __migrate_task(req
->task
, cpu
, req
->dest_cpu
);
5425 complete(&req
->done
);
5427 __set_current_state(TASK_RUNNING
);
5431 /* Wait for kthread_stop */
5432 set_current_state(TASK_INTERRUPTIBLE
);
5433 while (!kthread_should_stop()) {
5435 set_current_state(TASK_INTERRUPTIBLE
);
5437 __set_current_state(TASK_RUNNING
);
5441 #ifdef CONFIG_HOTPLUG_CPU
5443 static int __migrate_task_irq(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
5447 local_irq_disable();
5448 ret
= __migrate_task(p
, src_cpu
, dest_cpu
);
5454 * Figure out where task on dead CPU should go, use force if necessary.
5455 * NOTE: interrupts should be disabled by the caller
5457 static void move_task_off_dead_cpu(int dead_cpu
, struct task_struct
*p
)
5459 unsigned long flags
;
5466 mask
= node_to_cpumask(cpu_to_node(dead_cpu
));
5467 cpus_and(mask
, mask
, p
->cpus_allowed
);
5468 dest_cpu
= any_online_cpu(mask
);
5470 /* On any allowed CPU? */
5471 if (dest_cpu
== NR_CPUS
)
5472 dest_cpu
= any_online_cpu(p
->cpus_allowed
);
5474 /* No more Mr. Nice Guy. */
5475 if (dest_cpu
== NR_CPUS
) {
5476 cpumask_t cpus_allowed
= cpuset_cpus_allowed_locked(p
);
5478 * Try to stay on the same cpuset, where the
5479 * current cpuset may be a subset of all cpus.
5480 * The cpuset_cpus_allowed_locked() variant of
5481 * cpuset_cpus_allowed() will not block. It must be
5482 * called within calls to cpuset_lock/cpuset_unlock.
5484 rq
= task_rq_lock(p
, &flags
);
5485 p
->cpus_allowed
= cpus_allowed
;
5486 dest_cpu
= any_online_cpu(p
->cpus_allowed
);
5487 task_rq_unlock(rq
, &flags
);
5490 * Don't tell them about moving exiting tasks or
5491 * kernel threads (both mm NULL), since they never
5494 if (p
->mm
&& printk_ratelimit()) {
5495 printk(KERN_INFO
"process %d (%s) no "
5496 "longer affine to cpu%d\n",
5497 task_pid_nr(p
), p
->comm
, dead_cpu
);
5500 } while (!__migrate_task_irq(p
, dead_cpu
, dest_cpu
));
5504 * While a dead CPU has no uninterruptible tasks queued at this point,
5505 * it might still have a nonzero ->nr_uninterruptible counter, because
5506 * for performance reasons the counter is not stricly tracking tasks to
5507 * their home CPUs. So we just add the counter to another CPU's counter,
5508 * to keep the global sum constant after CPU-down:
5510 static void migrate_nr_uninterruptible(struct rq
*rq_src
)
5512 struct rq
*rq_dest
= cpu_rq(any_online_cpu(CPU_MASK_ALL
));
5513 unsigned long flags
;
5515 local_irq_save(flags
);
5516 double_rq_lock(rq_src
, rq_dest
);
5517 rq_dest
->nr_uninterruptible
+= rq_src
->nr_uninterruptible
;
5518 rq_src
->nr_uninterruptible
= 0;
5519 double_rq_unlock(rq_src
, rq_dest
);
5520 local_irq_restore(flags
);
5523 /* Run through task list and migrate tasks from the dead cpu. */
5524 static void migrate_live_tasks(int src_cpu
)
5526 struct task_struct
*p
, *t
;
5528 read_lock(&tasklist_lock
);
5530 do_each_thread(t
, p
) {
5534 if (task_cpu(p
) == src_cpu
)
5535 move_task_off_dead_cpu(src_cpu
, p
);
5536 } while_each_thread(t
, p
);
5538 read_unlock(&tasklist_lock
);
5542 * Schedules idle task to be the next runnable task on current CPU.
5543 * It does so by boosting its priority to highest possible.
5544 * Used by CPU offline code.
5546 void sched_idle_next(void)
5548 int this_cpu
= smp_processor_id();
5549 struct rq
*rq
= cpu_rq(this_cpu
);
5550 struct task_struct
*p
= rq
->idle
;
5551 unsigned long flags
;
5553 /* cpu has to be offline */
5554 BUG_ON(cpu_online(this_cpu
));
5557 * Strictly not necessary since rest of the CPUs are stopped by now
5558 * and interrupts disabled on the current cpu.
5560 spin_lock_irqsave(&rq
->lock
, flags
);
5562 __setscheduler(rq
, p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
5564 update_rq_clock(rq
);
5565 activate_task(rq
, p
, 0);
5567 spin_unlock_irqrestore(&rq
->lock
, flags
);
5571 * Ensures that the idle task is using init_mm right before its cpu goes
5574 void idle_task_exit(void)
5576 struct mm_struct
*mm
= current
->active_mm
;
5578 BUG_ON(cpu_online(smp_processor_id()));
5581 switch_mm(mm
, &init_mm
, current
);
5585 /* called under rq->lock with disabled interrupts */
5586 static void migrate_dead(unsigned int dead_cpu
, struct task_struct
*p
)
5588 struct rq
*rq
= cpu_rq(dead_cpu
);
5590 /* Must be exiting, otherwise would be on tasklist. */
5591 BUG_ON(!p
->exit_state
);
5593 /* Cannot have done final schedule yet: would have vanished. */
5594 BUG_ON(p
->state
== TASK_DEAD
);
5599 * Drop lock around migration; if someone else moves it,
5600 * that's OK. No task can be added to this CPU, so iteration is
5603 spin_unlock_irq(&rq
->lock
);
5604 move_task_off_dead_cpu(dead_cpu
, p
);
5605 spin_lock_irq(&rq
->lock
);
5610 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5611 static void migrate_dead_tasks(unsigned int dead_cpu
)
5613 struct rq
*rq
= cpu_rq(dead_cpu
);
5614 struct task_struct
*next
;
5617 if (!rq
->nr_running
)
5619 update_rq_clock(rq
);
5620 next
= pick_next_task(rq
, rq
->curr
);
5623 migrate_dead(dead_cpu
, next
);
5627 #endif /* CONFIG_HOTPLUG_CPU */
5629 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5631 static struct ctl_table sd_ctl_dir
[] = {
5633 .procname
= "sched_domain",
5639 static struct ctl_table sd_ctl_root
[] = {
5641 .ctl_name
= CTL_KERN
,
5642 .procname
= "kernel",
5644 .child
= sd_ctl_dir
,
5649 static struct ctl_table
*sd_alloc_ctl_entry(int n
)
5651 struct ctl_table
*entry
=
5652 kcalloc(n
, sizeof(struct ctl_table
), GFP_KERNEL
);
5657 static void sd_free_ctl_entry(struct ctl_table
**tablep
)
5659 struct ctl_table
*entry
;
5662 * In the intermediate directories, both the child directory and
5663 * procname are dynamically allocated and could fail but the mode
5664 * will always be set. In the lowest directory the names are
5665 * static strings and all have proc handlers.
5667 for (entry
= *tablep
; entry
->mode
; entry
++) {
5669 sd_free_ctl_entry(&entry
->child
);
5670 if (entry
->proc_handler
== NULL
)
5671 kfree(entry
->procname
);
5679 set_table_entry(struct ctl_table
*entry
,
5680 const char *procname
, void *data
, int maxlen
,
5681 mode_t mode
, proc_handler
*proc_handler
)
5683 entry
->procname
= procname
;
5685 entry
->maxlen
= maxlen
;
5687 entry
->proc_handler
= proc_handler
;
5690 static struct ctl_table
*
5691 sd_alloc_ctl_domain_table(struct sched_domain
*sd
)
5693 struct ctl_table
*table
= sd_alloc_ctl_entry(12);
5698 set_table_entry(&table
[0], "min_interval", &sd
->min_interval
,
5699 sizeof(long), 0644, proc_doulongvec_minmax
);
5700 set_table_entry(&table
[1], "max_interval", &sd
->max_interval
,
5701 sizeof(long), 0644, proc_doulongvec_minmax
);
5702 set_table_entry(&table
[2], "busy_idx", &sd
->busy_idx
,
5703 sizeof(int), 0644, proc_dointvec_minmax
);
5704 set_table_entry(&table
[3], "idle_idx", &sd
->idle_idx
,
5705 sizeof(int), 0644, proc_dointvec_minmax
);
5706 set_table_entry(&table
[4], "newidle_idx", &sd
->newidle_idx
,
5707 sizeof(int), 0644, proc_dointvec_minmax
);
5708 set_table_entry(&table
[5], "wake_idx", &sd
->wake_idx
,
5709 sizeof(int), 0644, proc_dointvec_minmax
);
5710 set_table_entry(&table
[6], "forkexec_idx", &sd
->forkexec_idx
,
5711 sizeof(int), 0644, proc_dointvec_minmax
);
5712 set_table_entry(&table
[7], "busy_factor", &sd
->busy_factor
,
5713 sizeof(int), 0644, proc_dointvec_minmax
);
5714 set_table_entry(&table
[8], "imbalance_pct", &sd
->imbalance_pct
,
5715 sizeof(int), 0644, proc_dointvec_minmax
);
5716 set_table_entry(&table
[9], "cache_nice_tries",
5717 &sd
->cache_nice_tries
,
5718 sizeof(int), 0644, proc_dointvec_minmax
);
5719 set_table_entry(&table
[10], "flags", &sd
->flags
,
5720 sizeof(int), 0644, proc_dointvec_minmax
);
5721 /* &table[11] is terminator */
5726 static ctl_table
*sd_alloc_ctl_cpu_table(int cpu
)
5728 struct ctl_table
*entry
, *table
;
5729 struct sched_domain
*sd
;
5730 int domain_num
= 0, i
;
5733 for_each_domain(cpu
, sd
)
5735 entry
= table
= sd_alloc_ctl_entry(domain_num
+ 1);
5740 for_each_domain(cpu
, sd
) {
5741 snprintf(buf
, 32, "domain%d", i
);
5742 entry
->procname
= kstrdup(buf
, GFP_KERNEL
);
5744 entry
->child
= sd_alloc_ctl_domain_table(sd
);
5751 static struct ctl_table_header
*sd_sysctl_header
;
5752 static void register_sched_domain_sysctl(void)
5754 int i
, cpu_num
= num_online_cpus();
5755 struct ctl_table
*entry
= sd_alloc_ctl_entry(cpu_num
+ 1);
5758 WARN_ON(sd_ctl_dir
[0].child
);
5759 sd_ctl_dir
[0].child
= entry
;
5764 for_each_online_cpu(i
) {
5765 snprintf(buf
, 32, "cpu%d", i
);
5766 entry
->procname
= kstrdup(buf
, GFP_KERNEL
);
5768 entry
->child
= sd_alloc_ctl_cpu_table(i
);
5772 WARN_ON(sd_sysctl_header
);
5773 sd_sysctl_header
= register_sysctl_table(sd_ctl_root
);
5776 /* may be called multiple times per register */
5777 static void unregister_sched_domain_sysctl(void)
5779 if (sd_sysctl_header
)
5780 unregister_sysctl_table(sd_sysctl_header
);
5781 sd_sysctl_header
= NULL
;
5782 if (sd_ctl_dir
[0].child
)
5783 sd_free_ctl_entry(&sd_ctl_dir
[0].child
);
5786 static void register_sched_domain_sysctl(void)
5789 static void unregister_sched_domain_sysctl(void)
5795 * migration_call - callback that gets triggered when a CPU is added.
5796 * Here we can start up the necessary migration thread for the new CPU.
5798 static int __cpuinit
5799 migration_call(struct notifier_block
*nfb
, unsigned long action
, void *hcpu
)
5801 struct task_struct
*p
;
5802 int cpu
= (long)hcpu
;
5803 unsigned long flags
;
5808 case CPU_UP_PREPARE
:
5809 case CPU_UP_PREPARE_FROZEN
:
5810 p
= kthread_create(migration_thread
, hcpu
, "migration/%d", cpu
);
5813 kthread_bind(p
, cpu
);
5814 /* Must be high prio: stop_machine expects to yield to it. */
5815 rq
= task_rq_lock(p
, &flags
);
5816 __setscheduler(rq
, p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
5817 task_rq_unlock(rq
, &flags
);
5818 cpu_rq(cpu
)->migration_thread
= p
;
5822 case CPU_ONLINE_FROZEN
:
5823 /* Strictly unnecessary, as first user will wake it. */
5824 wake_up_process(cpu_rq(cpu
)->migration_thread
);
5826 /* Update our root-domain */
5828 spin_lock_irqsave(&rq
->lock
, flags
);
5830 BUG_ON(!cpu_isset(cpu
, rq
->rd
->span
));
5831 cpu_set(cpu
, rq
->rd
->online
);
5833 spin_unlock_irqrestore(&rq
->lock
, flags
);
5836 #ifdef CONFIG_HOTPLUG_CPU
5837 case CPU_UP_CANCELED
:
5838 case CPU_UP_CANCELED_FROZEN
:
5839 if (!cpu_rq(cpu
)->migration_thread
)
5841 /* Unbind it from offline cpu so it can run. Fall thru. */
5842 kthread_bind(cpu_rq(cpu
)->migration_thread
,
5843 any_online_cpu(cpu_online_map
));
5844 kthread_stop(cpu_rq(cpu
)->migration_thread
);
5845 cpu_rq(cpu
)->migration_thread
= NULL
;
5849 case CPU_DEAD_FROZEN
:
5850 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
5851 migrate_live_tasks(cpu
);
5853 kthread_stop(rq
->migration_thread
);
5854 rq
->migration_thread
= NULL
;
5855 /* Idle task back to normal (off runqueue, low prio) */
5856 spin_lock_irq(&rq
->lock
);
5857 update_rq_clock(rq
);
5858 deactivate_task(rq
, rq
->idle
, 0);
5859 rq
->idle
->static_prio
= MAX_PRIO
;
5860 __setscheduler(rq
, rq
->idle
, SCHED_NORMAL
, 0);
5861 rq
->idle
->sched_class
= &idle_sched_class
;
5862 migrate_dead_tasks(cpu
);
5863 spin_unlock_irq(&rq
->lock
);
5865 migrate_nr_uninterruptible(rq
);
5866 BUG_ON(rq
->nr_running
!= 0);
5869 * No need to migrate the tasks: it was best-effort if
5870 * they didn't take sched_hotcpu_mutex. Just wake up
5873 spin_lock_irq(&rq
->lock
);
5874 while (!list_empty(&rq
->migration_queue
)) {
5875 struct migration_req
*req
;
5877 req
= list_entry(rq
->migration_queue
.next
,
5878 struct migration_req
, list
);
5879 list_del_init(&req
->list
);
5880 complete(&req
->done
);
5882 spin_unlock_irq(&rq
->lock
);
5885 case CPU_DOWN_PREPARE
:
5886 /* Update our root-domain */
5888 spin_lock_irqsave(&rq
->lock
, flags
);
5890 BUG_ON(!cpu_isset(cpu
, rq
->rd
->span
));
5891 cpu_clear(cpu
, rq
->rd
->online
);
5893 spin_unlock_irqrestore(&rq
->lock
, flags
);
5900 /* Register at highest priority so that task migration (migrate_all_tasks)
5901 * happens before everything else.
5903 static struct notifier_block __cpuinitdata migration_notifier
= {
5904 .notifier_call
= migration_call
,
5908 void __init
migration_init(void)
5910 void *cpu
= (void *)(long)smp_processor_id();
5913 /* Start one for the boot CPU: */
5914 err
= migration_call(&migration_notifier
, CPU_UP_PREPARE
, cpu
);
5915 BUG_ON(err
== NOTIFY_BAD
);
5916 migration_call(&migration_notifier
, CPU_ONLINE
, cpu
);
5917 register_cpu_notifier(&migration_notifier
);
5923 /* Number of possible processor ids */
5924 int nr_cpu_ids __read_mostly
= NR_CPUS
;
5925 EXPORT_SYMBOL(nr_cpu_ids
);
5927 #ifdef CONFIG_SCHED_DEBUG
5929 static int sched_domain_debug_one(struct sched_domain
*sd
, int cpu
, int level
)
5931 struct sched_group
*group
= sd
->groups
;
5932 cpumask_t groupmask
;
5935 cpumask_scnprintf(str
, NR_CPUS
, sd
->span
);
5936 cpus_clear(groupmask
);
5938 printk(KERN_DEBUG
"%*s domain %d: ", level
, "", level
);
5940 if (!(sd
->flags
& SD_LOAD_BALANCE
)) {
5941 printk("does not load-balance\n");
5943 printk(KERN_ERR
"ERROR: !SD_LOAD_BALANCE domain"
5948 printk(KERN_CONT
"span %s\n", str
);
5950 if (!cpu_isset(cpu
, sd
->span
)) {
5951 printk(KERN_ERR
"ERROR: domain->span does not contain "
5954 if (!cpu_isset(cpu
, group
->cpumask
)) {
5955 printk(KERN_ERR
"ERROR: domain->groups does not contain"
5959 printk(KERN_DEBUG
"%*s groups:", level
+ 1, "");
5963 printk(KERN_ERR
"ERROR: group is NULL\n");
5967 if (!group
->__cpu_power
) {
5968 printk(KERN_CONT
"\n");
5969 printk(KERN_ERR
"ERROR: domain->cpu_power not "
5974 if (!cpus_weight(group
->cpumask
)) {
5975 printk(KERN_CONT
"\n");
5976 printk(KERN_ERR
"ERROR: empty group\n");
5980 if (cpus_intersects(groupmask
, group
->cpumask
)) {
5981 printk(KERN_CONT
"\n");
5982 printk(KERN_ERR
"ERROR: repeated CPUs\n");
5986 cpus_or(groupmask
, groupmask
, group
->cpumask
);
5988 cpumask_scnprintf(str
, NR_CPUS
, group
->cpumask
);
5989 printk(KERN_CONT
" %s", str
);
5991 group
= group
->next
;
5992 } while (group
!= sd
->groups
);
5993 printk(KERN_CONT
"\n");
5995 if (!cpus_equal(sd
->span
, groupmask
))
5996 printk(KERN_ERR
"ERROR: groups don't span domain->span\n");
5998 if (sd
->parent
&& !cpus_subset(groupmask
, sd
->parent
->span
))
5999 printk(KERN_ERR
"ERROR: parent span is not a superset "
6000 "of domain->span\n");
6004 static void sched_domain_debug(struct sched_domain
*sd
, int cpu
)
6009 printk(KERN_DEBUG
"CPU%d attaching NULL sched-domain.\n", cpu
);
6013 printk(KERN_DEBUG
"CPU%d attaching sched-domain:\n", cpu
);
6016 if (sched_domain_debug_one(sd
, cpu
, level
))
6025 # define sched_domain_debug(sd, cpu) do { } while (0)
6028 static int sd_degenerate(struct sched_domain
*sd
)
6030 if (cpus_weight(sd
->span
) == 1)
6033 /* Following flags need at least 2 groups */
6034 if (sd
->flags
& (SD_LOAD_BALANCE
|
6035 SD_BALANCE_NEWIDLE
|
6039 SD_SHARE_PKG_RESOURCES
)) {
6040 if (sd
->groups
!= sd
->groups
->next
)
6044 /* Following flags don't use groups */
6045 if (sd
->flags
& (SD_WAKE_IDLE
|
6054 sd_parent_degenerate(struct sched_domain
*sd
, struct sched_domain
*parent
)
6056 unsigned long cflags
= sd
->flags
, pflags
= parent
->flags
;
6058 if (sd_degenerate(parent
))
6061 if (!cpus_equal(sd
->span
, parent
->span
))
6064 /* Does parent contain flags not in child? */
6065 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6066 if (cflags
& SD_WAKE_AFFINE
)
6067 pflags
&= ~SD_WAKE_BALANCE
;
6068 /* Flags needing groups don't count if only 1 group in parent */
6069 if (parent
->groups
== parent
->groups
->next
) {
6070 pflags
&= ~(SD_LOAD_BALANCE
|
6071 SD_BALANCE_NEWIDLE
|
6075 SD_SHARE_PKG_RESOURCES
);
6077 if (~cflags
& pflags
)
6083 static void rq_attach_root(struct rq
*rq
, struct root_domain
*rd
)
6085 unsigned long flags
;
6086 const struct sched_class
*class;
6088 spin_lock_irqsave(&rq
->lock
, flags
);
6091 struct root_domain
*old_rd
= rq
->rd
;
6093 for (class = sched_class_highest
; class; class = class->next
) {
6094 if (class->leave_domain
)
6095 class->leave_domain(rq
);
6098 cpu_clear(rq
->cpu
, old_rd
->span
);
6099 cpu_clear(rq
->cpu
, old_rd
->online
);
6101 if (atomic_dec_and_test(&old_rd
->refcount
))
6105 atomic_inc(&rd
->refcount
);
6108 cpu_set(rq
->cpu
, rd
->span
);
6109 if (cpu_isset(rq
->cpu
, cpu_online_map
))
6110 cpu_set(rq
->cpu
, rd
->online
);
6112 for (class = sched_class_highest
; class; class = class->next
) {
6113 if (class->join_domain
)
6114 class->join_domain(rq
);
6117 spin_unlock_irqrestore(&rq
->lock
, flags
);
6120 static void init_rootdomain(struct root_domain
*rd
)
6122 memset(rd
, 0, sizeof(*rd
));
6124 cpus_clear(rd
->span
);
6125 cpus_clear(rd
->online
);
6128 static void init_defrootdomain(void)
6130 init_rootdomain(&def_root_domain
);
6131 atomic_set(&def_root_domain
.refcount
, 1);
6134 static struct root_domain
*alloc_rootdomain(void)
6136 struct root_domain
*rd
;
6138 rd
= kmalloc(sizeof(*rd
), GFP_KERNEL
);
6142 init_rootdomain(rd
);
6148 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6149 * hold the hotplug lock.
6152 cpu_attach_domain(struct sched_domain
*sd
, struct root_domain
*rd
, int cpu
)
6154 struct rq
*rq
= cpu_rq(cpu
);
6155 struct sched_domain
*tmp
;
6157 /* Remove the sched domains which do not contribute to scheduling. */
6158 for (tmp
= sd
; tmp
; tmp
= tmp
->parent
) {
6159 struct sched_domain
*parent
= tmp
->parent
;
6162 if (sd_parent_degenerate(tmp
, parent
)) {
6163 tmp
->parent
= parent
->parent
;
6165 parent
->parent
->child
= tmp
;
6169 if (sd
&& sd_degenerate(sd
)) {
6175 sched_domain_debug(sd
, cpu
);
6177 rq_attach_root(rq
, rd
);
6178 rcu_assign_pointer(rq
->sd
, sd
);
6181 /* cpus with isolated domains */
6182 static cpumask_t cpu_isolated_map
= CPU_MASK_NONE
;
6184 /* Setup the mask of cpus configured for isolated domains */
6185 static int __init
isolated_cpu_setup(char *str
)
6187 int ints
[NR_CPUS
], i
;
6189 str
= get_options(str
, ARRAY_SIZE(ints
), ints
);
6190 cpus_clear(cpu_isolated_map
);
6191 for (i
= 1; i
<= ints
[0]; i
++)
6192 if (ints
[i
] < NR_CPUS
)
6193 cpu_set(ints
[i
], cpu_isolated_map
);
6197 __setup("isolcpus=", isolated_cpu_setup
);
6200 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6201 * to a function which identifies what group(along with sched group) a CPU
6202 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6203 * (due to the fact that we keep track of groups covered with a cpumask_t).
6205 * init_sched_build_groups will build a circular linked list of the groups
6206 * covered by the given span, and will set each group's ->cpumask correctly,
6207 * and ->cpu_power to 0.
6210 init_sched_build_groups(cpumask_t span
, const cpumask_t
*cpu_map
,
6211 int (*group_fn
)(int cpu
, const cpumask_t
*cpu_map
,
6212 struct sched_group
**sg
))
6214 struct sched_group
*first
= NULL
, *last
= NULL
;
6215 cpumask_t covered
= CPU_MASK_NONE
;
6218 for_each_cpu_mask(i
, span
) {
6219 struct sched_group
*sg
;
6220 int group
= group_fn(i
, cpu_map
, &sg
);
6223 if (cpu_isset(i
, covered
))
6226 sg
->cpumask
= CPU_MASK_NONE
;
6227 sg
->__cpu_power
= 0;
6229 for_each_cpu_mask(j
, span
) {
6230 if (group_fn(j
, cpu_map
, NULL
) != group
)
6233 cpu_set(j
, covered
);
6234 cpu_set(j
, sg
->cpumask
);
6245 #define SD_NODES_PER_DOMAIN 16
6250 * find_next_best_node - find the next node to include in a sched_domain
6251 * @node: node whose sched_domain we're building
6252 * @used_nodes: nodes already in the sched_domain
6254 * Find the next node to include in a given scheduling domain. Simply
6255 * finds the closest node not already in the @used_nodes map.
6257 * Should use nodemask_t.
6259 static int find_next_best_node(int node
, unsigned long *used_nodes
)
6261 int i
, n
, val
, min_val
, best_node
= 0;
6265 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6266 /* Start at @node */
6267 n
= (node
+ i
) % MAX_NUMNODES
;
6269 if (!nr_cpus_node(n
))
6272 /* Skip already used nodes */
6273 if (test_bit(n
, used_nodes
))
6276 /* Simple min distance search */
6277 val
= node_distance(node
, n
);
6279 if (val
< min_val
) {
6285 set_bit(best_node
, used_nodes
);
6290 * sched_domain_node_span - get a cpumask for a node's sched_domain
6291 * @node: node whose cpumask we're constructing
6292 * @size: number of nodes to include in this span
6294 * Given a node, construct a good cpumask for its sched_domain to span. It
6295 * should be one that prevents unnecessary balancing, but also spreads tasks
6298 static cpumask_t
sched_domain_node_span(int node
)
6300 DECLARE_BITMAP(used_nodes
, MAX_NUMNODES
);
6301 cpumask_t span
, nodemask
;
6305 bitmap_zero(used_nodes
, MAX_NUMNODES
);
6307 nodemask
= node_to_cpumask(node
);
6308 cpus_or(span
, span
, nodemask
);
6309 set_bit(node
, used_nodes
);
6311 for (i
= 1; i
< SD_NODES_PER_DOMAIN
; i
++) {
6312 int next_node
= find_next_best_node(node
, used_nodes
);
6314 nodemask
= node_to_cpumask(next_node
);
6315 cpus_or(span
, span
, nodemask
);
6322 int sched_smt_power_savings
= 0, sched_mc_power_savings
= 0;
6325 * SMT sched-domains:
6327 #ifdef CONFIG_SCHED_SMT
6328 static DEFINE_PER_CPU(struct sched_domain
, cpu_domains
);
6329 static DEFINE_PER_CPU(struct sched_group
, sched_group_cpus
);
6332 cpu_to_cpu_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
)
6335 *sg
= &per_cpu(sched_group_cpus
, cpu
);
6341 * multi-core sched-domains:
6343 #ifdef CONFIG_SCHED_MC
6344 static DEFINE_PER_CPU(struct sched_domain
, core_domains
);
6345 static DEFINE_PER_CPU(struct sched_group
, sched_group_core
);
6348 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6350 cpu_to_core_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
)
6353 cpumask_t mask
= per_cpu(cpu_sibling_map
, cpu
);
6354 cpus_and(mask
, mask
, *cpu_map
);
6355 group
= first_cpu(mask
);
6357 *sg
= &per_cpu(sched_group_core
, group
);
6360 #elif defined(CONFIG_SCHED_MC)
6362 cpu_to_core_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
)
6365 *sg
= &per_cpu(sched_group_core
, cpu
);
6370 static DEFINE_PER_CPU(struct sched_domain
, phys_domains
);
6371 static DEFINE_PER_CPU(struct sched_group
, sched_group_phys
);
6374 cpu_to_phys_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
)
6377 #ifdef CONFIG_SCHED_MC
6378 cpumask_t mask
= cpu_coregroup_map(cpu
);
6379 cpus_and(mask
, mask
, *cpu_map
);
6380 group
= first_cpu(mask
);
6381 #elif defined(CONFIG_SCHED_SMT)
6382 cpumask_t mask
= per_cpu(cpu_sibling_map
, cpu
);
6383 cpus_and(mask
, mask
, *cpu_map
);
6384 group
= first_cpu(mask
);
6389 *sg
= &per_cpu(sched_group_phys
, group
);
6395 * The init_sched_build_groups can't handle what we want to do with node
6396 * groups, so roll our own. Now each node has its own list of groups which
6397 * gets dynamically allocated.
6399 static DEFINE_PER_CPU(struct sched_domain
, node_domains
);
6400 static struct sched_group
**sched_group_nodes_bycpu
[NR_CPUS
];
6402 static DEFINE_PER_CPU(struct sched_domain
, allnodes_domains
);
6403 static DEFINE_PER_CPU(struct sched_group
, sched_group_allnodes
);
6405 static int cpu_to_allnodes_group(int cpu
, const cpumask_t
*cpu_map
,
6406 struct sched_group
**sg
)
6408 cpumask_t nodemask
= node_to_cpumask(cpu_to_node(cpu
));
6411 cpus_and(nodemask
, nodemask
, *cpu_map
);
6412 group
= first_cpu(nodemask
);
6415 *sg
= &per_cpu(sched_group_allnodes
, group
);
6419 static void init_numa_sched_groups_power(struct sched_group
*group_head
)
6421 struct sched_group
*sg
= group_head
;
6427 for_each_cpu_mask(j
, sg
->cpumask
) {
6428 struct sched_domain
*sd
;
6430 sd
= &per_cpu(phys_domains
, j
);
6431 if (j
!= first_cpu(sd
->groups
->cpumask
)) {
6433 * Only add "power" once for each
6439 sg_inc_cpu_power(sg
, sd
->groups
->__cpu_power
);
6442 } while (sg
!= group_head
);
6447 /* Free memory allocated for various sched_group structures */
6448 static void free_sched_groups(const cpumask_t
*cpu_map
)
6452 for_each_cpu_mask(cpu
, *cpu_map
) {
6453 struct sched_group
**sched_group_nodes
6454 = sched_group_nodes_bycpu
[cpu
];
6456 if (!sched_group_nodes
)
6459 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6460 cpumask_t nodemask
= node_to_cpumask(i
);
6461 struct sched_group
*oldsg
, *sg
= sched_group_nodes
[i
];
6463 cpus_and(nodemask
, nodemask
, *cpu_map
);
6464 if (cpus_empty(nodemask
))
6474 if (oldsg
!= sched_group_nodes
[i
])
6477 kfree(sched_group_nodes
);
6478 sched_group_nodes_bycpu
[cpu
] = NULL
;
6482 static void free_sched_groups(const cpumask_t
*cpu_map
)
6488 * Initialize sched groups cpu_power.
6490 * cpu_power indicates the capacity of sched group, which is used while
6491 * distributing the load between different sched groups in a sched domain.
6492 * Typically cpu_power for all the groups in a sched domain will be same unless
6493 * there are asymmetries in the topology. If there are asymmetries, group
6494 * having more cpu_power will pickup more load compared to the group having
6497 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
6498 * the maximum number of tasks a group can handle in the presence of other idle
6499 * or lightly loaded groups in the same sched domain.
6501 static void init_sched_groups_power(int cpu
, struct sched_domain
*sd
)
6503 struct sched_domain
*child
;
6504 struct sched_group
*group
;
6506 WARN_ON(!sd
|| !sd
->groups
);
6508 if (cpu
!= first_cpu(sd
->groups
->cpumask
))
6513 sd
->groups
->__cpu_power
= 0;
6516 * For perf policy, if the groups in child domain share resources
6517 * (for example cores sharing some portions of the cache hierarchy
6518 * or SMT), then set this domain groups cpu_power such that each group
6519 * can handle only one task, when there are other idle groups in the
6520 * same sched domain.
6522 if (!child
|| (!(sd
->flags
& SD_POWERSAVINGS_BALANCE
) &&
6524 (SD_SHARE_CPUPOWER
| SD_SHARE_PKG_RESOURCES
)))) {
6525 sg_inc_cpu_power(sd
->groups
, SCHED_LOAD_SCALE
);
6530 * add cpu_power of each child group to this groups cpu_power
6532 group
= child
->groups
;
6534 sg_inc_cpu_power(sd
->groups
, group
->__cpu_power
);
6535 group
= group
->next
;
6536 } while (group
!= child
->groups
);
6540 * Build sched domains for a given set of cpus and attach the sched domains
6541 * to the individual cpus
6543 static int build_sched_domains(const cpumask_t
*cpu_map
)
6546 struct root_domain
*rd
;
6548 struct sched_group
**sched_group_nodes
= NULL
;
6549 int sd_allnodes
= 0;
6552 * Allocate the per-node list of sched groups
6554 sched_group_nodes
= kcalloc(MAX_NUMNODES
, sizeof(struct sched_group
*),
6556 if (!sched_group_nodes
) {
6557 printk(KERN_WARNING
"Can not alloc sched group node list\n");
6560 sched_group_nodes_bycpu
[first_cpu(*cpu_map
)] = sched_group_nodes
;
6563 rd
= alloc_rootdomain();
6565 printk(KERN_WARNING
"Cannot alloc root domain\n");
6570 * Set up domains for cpus specified by the cpu_map.
6572 for_each_cpu_mask(i
, *cpu_map
) {
6573 struct sched_domain
*sd
= NULL
, *p
;
6574 cpumask_t nodemask
= node_to_cpumask(cpu_to_node(i
));
6576 cpus_and(nodemask
, nodemask
, *cpu_map
);
6579 if (cpus_weight(*cpu_map
) >
6580 SD_NODES_PER_DOMAIN
*cpus_weight(nodemask
)) {
6581 sd
= &per_cpu(allnodes_domains
, i
);
6582 *sd
= SD_ALLNODES_INIT
;
6583 sd
->span
= *cpu_map
;
6584 cpu_to_allnodes_group(i
, cpu_map
, &sd
->groups
);
6590 sd
= &per_cpu(node_domains
, i
);
6592 sd
->span
= sched_domain_node_span(cpu_to_node(i
));
6596 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6600 sd
= &per_cpu(phys_domains
, i
);
6602 sd
->span
= nodemask
;
6606 cpu_to_phys_group(i
, cpu_map
, &sd
->groups
);
6608 #ifdef CONFIG_SCHED_MC
6610 sd
= &per_cpu(core_domains
, i
);
6612 sd
->span
= cpu_coregroup_map(i
);
6613 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6616 cpu_to_core_group(i
, cpu_map
, &sd
->groups
);
6619 #ifdef CONFIG_SCHED_SMT
6621 sd
= &per_cpu(cpu_domains
, i
);
6622 *sd
= SD_SIBLING_INIT
;
6623 sd
->span
= per_cpu(cpu_sibling_map
, i
);
6624 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6627 cpu_to_cpu_group(i
, cpu_map
, &sd
->groups
);
6631 #ifdef CONFIG_SCHED_SMT
6632 /* Set up CPU (sibling) groups */
6633 for_each_cpu_mask(i
, *cpu_map
) {
6634 cpumask_t this_sibling_map
= per_cpu(cpu_sibling_map
, i
);
6635 cpus_and(this_sibling_map
, this_sibling_map
, *cpu_map
);
6636 if (i
!= first_cpu(this_sibling_map
))
6639 init_sched_build_groups(this_sibling_map
, cpu_map
,
6644 #ifdef CONFIG_SCHED_MC
6645 /* Set up multi-core groups */
6646 for_each_cpu_mask(i
, *cpu_map
) {
6647 cpumask_t this_core_map
= cpu_coregroup_map(i
);
6648 cpus_and(this_core_map
, this_core_map
, *cpu_map
);
6649 if (i
!= first_cpu(this_core_map
))
6651 init_sched_build_groups(this_core_map
, cpu_map
,
6652 &cpu_to_core_group
);
6656 /* Set up physical groups */
6657 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6658 cpumask_t nodemask
= node_to_cpumask(i
);
6660 cpus_and(nodemask
, nodemask
, *cpu_map
);
6661 if (cpus_empty(nodemask
))
6664 init_sched_build_groups(nodemask
, cpu_map
, &cpu_to_phys_group
);
6668 /* Set up node groups */
6670 init_sched_build_groups(*cpu_map
, cpu_map
,
6671 &cpu_to_allnodes_group
);
6673 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6674 /* Set up node groups */
6675 struct sched_group
*sg
, *prev
;
6676 cpumask_t nodemask
= node_to_cpumask(i
);
6677 cpumask_t domainspan
;
6678 cpumask_t covered
= CPU_MASK_NONE
;
6681 cpus_and(nodemask
, nodemask
, *cpu_map
);
6682 if (cpus_empty(nodemask
)) {
6683 sched_group_nodes
[i
] = NULL
;
6687 domainspan
= sched_domain_node_span(i
);
6688 cpus_and(domainspan
, domainspan
, *cpu_map
);
6690 sg
= kmalloc_node(sizeof(struct sched_group
), GFP_KERNEL
, i
);
6692 printk(KERN_WARNING
"Can not alloc domain group for "
6696 sched_group_nodes
[i
] = sg
;
6697 for_each_cpu_mask(j
, nodemask
) {
6698 struct sched_domain
*sd
;
6700 sd
= &per_cpu(node_domains
, j
);
6703 sg
->__cpu_power
= 0;
6704 sg
->cpumask
= nodemask
;
6706 cpus_or(covered
, covered
, nodemask
);
6709 for (j
= 0; j
< MAX_NUMNODES
; j
++) {
6710 cpumask_t tmp
, notcovered
;
6711 int n
= (i
+ j
) % MAX_NUMNODES
;
6713 cpus_complement(notcovered
, covered
);
6714 cpus_and(tmp
, notcovered
, *cpu_map
);
6715 cpus_and(tmp
, tmp
, domainspan
);
6716 if (cpus_empty(tmp
))
6719 nodemask
= node_to_cpumask(n
);
6720 cpus_and(tmp
, tmp
, nodemask
);
6721 if (cpus_empty(tmp
))
6724 sg
= kmalloc_node(sizeof(struct sched_group
),
6728 "Can not alloc domain group for node %d\n", j
);
6731 sg
->__cpu_power
= 0;
6733 sg
->next
= prev
->next
;
6734 cpus_or(covered
, covered
, tmp
);
6741 /* Calculate CPU power for physical packages and nodes */
6742 #ifdef CONFIG_SCHED_SMT
6743 for_each_cpu_mask(i
, *cpu_map
) {
6744 struct sched_domain
*sd
= &per_cpu(cpu_domains
, i
);
6746 init_sched_groups_power(i
, sd
);
6749 #ifdef CONFIG_SCHED_MC
6750 for_each_cpu_mask(i
, *cpu_map
) {
6751 struct sched_domain
*sd
= &per_cpu(core_domains
, i
);
6753 init_sched_groups_power(i
, sd
);
6757 for_each_cpu_mask(i
, *cpu_map
) {
6758 struct sched_domain
*sd
= &per_cpu(phys_domains
, i
);
6760 init_sched_groups_power(i
, sd
);
6764 for (i
= 0; i
< MAX_NUMNODES
; i
++)
6765 init_numa_sched_groups_power(sched_group_nodes
[i
]);
6768 struct sched_group
*sg
;
6770 cpu_to_allnodes_group(first_cpu(*cpu_map
), cpu_map
, &sg
);
6771 init_numa_sched_groups_power(sg
);
6775 /* Attach the domains */
6776 for_each_cpu_mask(i
, *cpu_map
) {
6777 struct sched_domain
*sd
;
6778 #ifdef CONFIG_SCHED_SMT
6779 sd
= &per_cpu(cpu_domains
, i
);
6780 #elif defined(CONFIG_SCHED_MC)
6781 sd
= &per_cpu(core_domains
, i
);
6783 sd
= &per_cpu(phys_domains
, i
);
6785 cpu_attach_domain(sd
, rd
, i
);
6792 free_sched_groups(cpu_map
);
6797 static cpumask_t
*doms_cur
; /* current sched domains */
6798 static int ndoms_cur
; /* number of sched domains in 'doms_cur' */
6801 * Special case: If a kmalloc of a doms_cur partition (array of
6802 * cpumask_t) fails, then fallback to a single sched domain,
6803 * as determined by the single cpumask_t fallback_doms.
6805 static cpumask_t fallback_doms
;
6808 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6809 * For now this just excludes isolated cpus, but could be used to
6810 * exclude other special cases in the future.
6812 static int arch_init_sched_domains(const cpumask_t
*cpu_map
)
6817 doms_cur
= kmalloc(sizeof(cpumask_t
), GFP_KERNEL
);
6819 doms_cur
= &fallback_doms
;
6820 cpus_andnot(*doms_cur
, *cpu_map
, cpu_isolated_map
);
6821 err
= build_sched_domains(doms_cur
);
6822 register_sched_domain_sysctl();
6827 static void arch_destroy_sched_domains(const cpumask_t
*cpu_map
)
6829 free_sched_groups(cpu_map
);
6833 * Detach sched domains from a group of cpus specified in cpu_map
6834 * These cpus will now be attached to the NULL domain
6836 static void detach_destroy_domains(const cpumask_t
*cpu_map
)
6840 unregister_sched_domain_sysctl();
6842 for_each_cpu_mask(i
, *cpu_map
)
6843 cpu_attach_domain(NULL
, &def_root_domain
, i
);
6844 synchronize_sched();
6845 arch_destroy_sched_domains(cpu_map
);
6849 * Partition sched domains as specified by the 'ndoms_new'
6850 * cpumasks in the array doms_new[] of cpumasks. This compares
6851 * doms_new[] to the current sched domain partitioning, doms_cur[].
6852 * It destroys each deleted domain and builds each new domain.
6854 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
6855 * The masks don't intersect (don't overlap.) We should setup one
6856 * sched domain for each mask. CPUs not in any of the cpumasks will
6857 * not be load balanced. If the same cpumask appears both in the
6858 * current 'doms_cur' domains and in the new 'doms_new', we can leave
6861 * The passed in 'doms_new' should be kmalloc'd. This routine takes
6862 * ownership of it and will kfree it when done with it. If the caller
6863 * failed the kmalloc call, then it can pass in doms_new == NULL,
6864 * and partition_sched_domains() will fallback to the single partition
6867 * Call with hotplug lock held
6869 void partition_sched_domains(int ndoms_new
, cpumask_t
*doms_new
)
6875 /* always unregister in case we don't destroy any domains */
6876 unregister_sched_domain_sysctl();
6878 if (doms_new
== NULL
) {
6880 doms_new
= &fallback_doms
;
6881 cpus_andnot(doms_new
[0], cpu_online_map
, cpu_isolated_map
);
6884 /* Destroy deleted domains */
6885 for (i
= 0; i
< ndoms_cur
; i
++) {
6886 for (j
= 0; j
< ndoms_new
; j
++) {
6887 if (cpus_equal(doms_cur
[i
], doms_new
[j
]))
6890 /* no match - a current sched domain not in new doms_new[] */
6891 detach_destroy_domains(doms_cur
+ i
);
6896 /* Build new domains */
6897 for (i
= 0; i
< ndoms_new
; i
++) {
6898 for (j
= 0; j
< ndoms_cur
; j
++) {
6899 if (cpus_equal(doms_new
[i
], doms_cur
[j
]))
6902 /* no match - add a new doms_new */
6903 build_sched_domains(doms_new
+ i
);
6908 /* Remember the new sched domains */
6909 if (doms_cur
!= &fallback_doms
)
6911 doms_cur
= doms_new
;
6912 ndoms_cur
= ndoms_new
;
6914 register_sched_domain_sysctl();
6919 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
6920 static int arch_reinit_sched_domains(void)
6925 detach_destroy_domains(&cpu_online_map
);
6926 err
= arch_init_sched_domains(&cpu_online_map
);
6932 static ssize_t
sched_power_savings_store(const char *buf
, size_t count
, int smt
)
6936 if (buf
[0] != '0' && buf
[0] != '1')
6940 sched_smt_power_savings
= (buf
[0] == '1');
6942 sched_mc_power_savings
= (buf
[0] == '1');
6944 ret
= arch_reinit_sched_domains();
6946 return ret
? ret
: count
;
6949 #ifdef CONFIG_SCHED_MC
6950 static ssize_t
sched_mc_power_savings_show(struct sys_device
*dev
, char *page
)
6952 return sprintf(page
, "%u\n", sched_mc_power_savings
);
6954 static ssize_t
sched_mc_power_savings_store(struct sys_device
*dev
,
6955 const char *buf
, size_t count
)
6957 return sched_power_savings_store(buf
, count
, 0);
6959 static SYSDEV_ATTR(sched_mc_power_savings
, 0644, sched_mc_power_savings_show
,
6960 sched_mc_power_savings_store
);
6963 #ifdef CONFIG_SCHED_SMT
6964 static ssize_t
sched_smt_power_savings_show(struct sys_device
*dev
, char *page
)
6966 return sprintf(page
, "%u\n", sched_smt_power_savings
);
6968 static ssize_t
sched_smt_power_savings_store(struct sys_device
*dev
,
6969 const char *buf
, size_t count
)
6971 return sched_power_savings_store(buf
, count
, 1);
6973 static SYSDEV_ATTR(sched_smt_power_savings
, 0644, sched_smt_power_savings_show
,
6974 sched_smt_power_savings_store
);
6977 int sched_create_sysfs_power_savings_entries(struct sysdev_class
*cls
)
6981 #ifdef CONFIG_SCHED_SMT
6983 err
= sysfs_create_file(&cls
->kset
.kobj
,
6984 &attr_sched_smt_power_savings
.attr
);
6986 #ifdef CONFIG_SCHED_MC
6987 if (!err
&& mc_capable())
6988 err
= sysfs_create_file(&cls
->kset
.kobj
,
6989 &attr_sched_mc_power_savings
.attr
);
6996 * Force a reinitialization of the sched domains hierarchy. The domains
6997 * and groups cannot be updated in place without racing with the balancing
6998 * code, so we temporarily attach all running cpus to the NULL domain
6999 * which will prevent rebalancing while the sched domains are recalculated.
7001 static int update_sched_domains(struct notifier_block
*nfb
,
7002 unsigned long action
, void *hcpu
)
7005 case CPU_UP_PREPARE
:
7006 case CPU_UP_PREPARE_FROZEN
:
7007 case CPU_DOWN_PREPARE
:
7008 case CPU_DOWN_PREPARE_FROZEN
:
7009 detach_destroy_domains(&cpu_online_map
);
7012 case CPU_UP_CANCELED
:
7013 case CPU_UP_CANCELED_FROZEN
:
7014 case CPU_DOWN_FAILED
:
7015 case CPU_DOWN_FAILED_FROZEN
:
7017 case CPU_ONLINE_FROZEN
:
7019 case CPU_DEAD_FROZEN
:
7021 * Fall through and re-initialise the domains.
7028 /* The hotplug lock is already held by cpu_up/cpu_down */
7029 arch_init_sched_domains(&cpu_online_map
);
7034 void __init
sched_init_smp(void)
7036 cpumask_t non_isolated_cpus
;
7039 arch_init_sched_domains(&cpu_online_map
);
7040 cpus_andnot(non_isolated_cpus
, cpu_possible_map
, cpu_isolated_map
);
7041 if (cpus_empty(non_isolated_cpus
))
7042 cpu_set(smp_processor_id(), non_isolated_cpus
);
7044 /* XXX: Theoretical race here - CPU may be hotplugged now */
7045 hotcpu_notifier(update_sched_domains
, 0);
7047 /* Move init over to a non-isolated CPU */
7048 if (set_cpus_allowed(current
, non_isolated_cpus
) < 0)
7050 sched_init_granularity();
7052 #ifdef CONFIG_FAIR_GROUP_SCHED
7053 if (nr_cpu_ids
== 1)
7056 lb_monitor_task
= kthread_create(load_balance_monitor
, NULL
,
7058 if (!IS_ERR(lb_monitor_task
)) {
7059 lb_monitor_task
->flags
|= PF_NOFREEZE
;
7060 wake_up_process(lb_monitor_task
);
7062 printk(KERN_ERR
"Could not create load balance monitor thread"
7063 "(error = %ld) \n", PTR_ERR(lb_monitor_task
));
7068 void __init
sched_init_smp(void)
7070 sched_init_granularity();
7072 #endif /* CONFIG_SMP */
7074 int in_sched_functions(unsigned long addr
)
7076 return in_lock_functions(addr
) ||
7077 (addr
>= (unsigned long)__sched_text_start
7078 && addr
< (unsigned long)__sched_text_end
);
7081 static void init_cfs_rq(struct cfs_rq
*cfs_rq
, struct rq
*rq
)
7083 cfs_rq
->tasks_timeline
= RB_ROOT
;
7084 #ifdef CONFIG_FAIR_GROUP_SCHED
7087 cfs_rq
->min_vruntime
= (u64
)(-(1LL << 20));
7090 static void init_rt_rq(struct rt_rq
*rt_rq
, struct rq
*rq
)
7092 struct rt_prio_array
*array
;
7095 array
= &rt_rq
->active
;
7096 for (i
= 0; i
< MAX_RT_PRIO
; i
++) {
7097 INIT_LIST_HEAD(array
->queue
+ i
);
7098 __clear_bit(i
, array
->bitmap
);
7100 /* delimiter for bitsearch: */
7101 __set_bit(MAX_RT_PRIO
, array
->bitmap
);
7103 #if defined CONFIG_SMP || defined CONFIG_FAIR_GROUP_SCHED
7104 rt_rq
->highest_prio
= MAX_RT_PRIO
;
7107 rt_rq
->rt_nr_migratory
= 0;
7108 rt_rq
->overloaded
= 0;
7112 rt_rq
->rt_throttled
= 0;
7114 #ifdef CONFIG_FAIR_GROUP_SCHED
7119 #ifdef CONFIG_FAIR_GROUP_SCHED
7120 static void init_tg_cfs_entry(struct rq
*rq
, struct task_group
*tg
,
7121 struct cfs_rq
*cfs_rq
, struct sched_entity
*se
,
7124 tg
->cfs_rq
[cpu
] = cfs_rq
;
7125 init_cfs_rq(cfs_rq
, rq
);
7128 list_add(&cfs_rq
->leaf_cfs_rq_list
, &rq
->leaf_cfs_rq_list
);
7131 se
->cfs_rq
= &rq
->cfs
;
7133 se
->load
.weight
= tg
->shares
;
7134 se
->load
.inv_weight
= div64_64(1ULL<<32, se
->load
.weight
);
7138 static void init_tg_rt_entry(struct rq
*rq
, struct task_group
*tg
,
7139 struct rt_rq
*rt_rq
, struct sched_rt_entity
*rt_se
,
7142 tg
->rt_rq
[cpu
] = rt_rq
;
7143 init_rt_rq(rt_rq
, rq
);
7145 rt_rq
->rt_se
= rt_se
;
7147 list_add(&rt_rq
->leaf_rt_rq_list
, &rq
->leaf_rt_rq_list
);
7149 tg
->rt_se
[cpu
] = rt_se
;
7150 rt_se
->rt_rq
= &rq
->rt
;
7151 rt_se
->my_q
= rt_rq
;
7152 rt_se
->parent
= NULL
;
7153 INIT_LIST_HEAD(&rt_se
->run_list
);
7157 void __init
sched_init(void)
7159 int highest_cpu
= 0;
7163 init_defrootdomain();
7166 #ifdef CONFIG_FAIR_GROUP_SCHED
7167 list_add(&init_task_group
.list
, &task_groups
);
7170 for_each_possible_cpu(i
) {
7174 spin_lock_init(&rq
->lock
);
7175 lockdep_set_class(&rq
->lock
, &rq
->rq_lock_key
);
7178 init_cfs_rq(&rq
->cfs
, rq
);
7179 init_rt_rq(&rq
->rt
, rq
);
7180 #ifdef CONFIG_FAIR_GROUP_SCHED
7181 init_task_group
.shares
= init_task_group_load
;
7182 INIT_LIST_HEAD(&rq
->leaf_cfs_rq_list
);
7183 init_tg_cfs_entry(rq
, &init_task_group
,
7184 &per_cpu(init_cfs_rq
, i
),
7185 &per_cpu(init_sched_entity
, i
), i
, 1);
7187 init_task_group
.rt_ratio
= sysctl_sched_rt_ratio
; /* XXX */
7188 INIT_LIST_HEAD(&rq
->leaf_rt_rq_list
);
7189 init_tg_rt_entry(rq
, &init_task_group
,
7190 &per_cpu(init_rt_rq
, i
),
7191 &per_cpu(init_sched_rt_entity
, i
), i
, 1);
7193 rq
->rt_period_expire
= 0;
7194 rq
->rt_throttled
= 0;
7196 for (j
= 0; j
< CPU_LOAD_IDX_MAX
; j
++)
7197 rq
->cpu_load
[j
] = 0;
7201 rq
->active_balance
= 0;
7202 rq
->next_balance
= jiffies
;
7205 rq
->migration_thread
= NULL
;
7206 INIT_LIST_HEAD(&rq
->migration_queue
);
7207 rq_attach_root(rq
, &def_root_domain
);
7210 atomic_set(&rq
->nr_iowait
, 0);
7214 set_load_weight(&init_task
);
7216 #ifdef CONFIG_PREEMPT_NOTIFIERS
7217 INIT_HLIST_HEAD(&init_task
.preempt_notifiers
);
7221 nr_cpu_ids
= highest_cpu
+ 1;
7222 open_softirq(SCHED_SOFTIRQ
, run_rebalance_domains
, NULL
);
7225 #ifdef CONFIG_RT_MUTEXES
7226 plist_head_init(&init_task
.pi_waiters
, &init_task
.pi_lock
);
7230 * The boot idle thread does lazy MMU switching as well:
7232 atomic_inc(&init_mm
.mm_count
);
7233 enter_lazy_tlb(&init_mm
, current
);
7236 * Make us the idle thread. Technically, schedule() should not be
7237 * called from this thread, however somewhere below it might be,
7238 * but because we are the idle thread, we just pick up running again
7239 * when this runqueue becomes "idle".
7241 init_idle(current
, smp_processor_id());
7243 * During early bootup we pretend to be a normal task:
7245 current
->sched_class
= &fair_sched_class
;
7248 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
7249 void __might_sleep(char *file
, int line
)
7252 static unsigned long prev_jiffy
; /* ratelimiting */
7254 if ((in_atomic() || irqs_disabled()) &&
7255 system_state
== SYSTEM_RUNNING
&& !oops_in_progress
) {
7256 if (time_before(jiffies
, prev_jiffy
+ HZ
) && prev_jiffy
)
7258 prev_jiffy
= jiffies
;
7259 printk(KERN_ERR
"BUG: sleeping function called from invalid"
7260 " context at %s:%d\n", file
, line
);
7261 printk("in_atomic():%d, irqs_disabled():%d\n",
7262 in_atomic(), irqs_disabled());
7263 debug_show_held_locks(current
);
7264 if (irqs_disabled())
7265 print_irqtrace_events(current
);
7270 EXPORT_SYMBOL(__might_sleep
);
7273 #ifdef CONFIG_MAGIC_SYSRQ
7274 static void normalize_task(struct rq
*rq
, struct task_struct
*p
)
7277 update_rq_clock(rq
);
7278 on_rq
= p
->se
.on_rq
;
7280 deactivate_task(rq
, p
, 0);
7281 __setscheduler(rq
, p
, SCHED_NORMAL
, 0);
7283 activate_task(rq
, p
, 0);
7284 resched_task(rq
->curr
);
7288 void normalize_rt_tasks(void)
7290 struct task_struct
*g
, *p
;
7291 unsigned long flags
;
7294 read_lock_irqsave(&tasklist_lock
, flags
);
7295 do_each_thread(g
, p
) {
7297 * Only normalize user tasks:
7302 p
->se
.exec_start
= 0;
7303 #ifdef CONFIG_SCHEDSTATS
7304 p
->se
.wait_start
= 0;
7305 p
->se
.sleep_start
= 0;
7306 p
->se
.block_start
= 0;
7308 task_rq(p
)->clock
= 0;
7312 * Renice negative nice level userspace
7315 if (TASK_NICE(p
) < 0 && p
->mm
)
7316 set_user_nice(p
, 0);
7320 spin_lock(&p
->pi_lock
);
7321 rq
= __task_rq_lock(p
);
7323 normalize_task(rq
, p
);
7325 __task_rq_unlock(rq
);
7326 spin_unlock(&p
->pi_lock
);
7327 } while_each_thread(g
, p
);
7329 read_unlock_irqrestore(&tasklist_lock
, flags
);
7332 #endif /* CONFIG_MAGIC_SYSRQ */
7336 * These functions are only useful for the IA64 MCA handling.
7338 * They can only be called when the whole system has been
7339 * stopped - every CPU needs to be quiescent, and no scheduling
7340 * activity can take place. Using them for anything else would
7341 * be a serious bug, and as a result, they aren't even visible
7342 * under any other configuration.
7346 * curr_task - return the current task for a given cpu.
7347 * @cpu: the processor in question.
7349 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7351 struct task_struct
*curr_task(int cpu
)
7353 return cpu_curr(cpu
);
7357 * set_curr_task - set the current task for a given cpu.
7358 * @cpu: the processor in question.
7359 * @p: the task pointer to set.
7361 * Description: This function must only be used when non-maskable interrupts
7362 * are serviced on a separate stack. It allows the architecture to switch the
7363 * notion of the current task on a cpu in a non-blocking manner. This function
7364 * must be called with all CPU's synchronized, and interrupts disabled, the
7365 * and caller must save the original value of the current task (see
7366 * curr_task() above) and restore that value before reenabling interrupts and
7367 * re-starting the system.
7369 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7371 void set_curr_task(int cpu
, struct task_struct
*p
)
7378 #ifdef CONFIG_FAIR_GROUP_SCHED
7382 * distribute shares of all task groups among their schedulable entities,
7383 * to reflect load distribution across cpus.
7385 static int rebalance_shares(struct sched_domain
*sd
, int this_cpu
)
7387 struct cfs_rq
*cfs_rq
;
7388 struct rq
*rq
= cpu_rq(this_cpu
);
7389 cpumask_t sdspan
= sd
->span
;
7392 /* Walk thr' all the task groups that we have */
7393 for_each_leaf_cfs_rq(rq
, cfs_rq
) {
7395 unsigned long total_load
= 0, total_shares
;
7396 struct task_group
*tg
= cfs_rq
->tg
;
7398 /* Gather total task load of this group across cpus */
7399 for_each_cpu_mask(i
, sdspan
)
7400 total_load
+= tg
->cfs_rq
[i
]->load
.weight
;
7402 /* Nothing to do if this group has no load */
7407 * tg->shares represents the number of cpu shares the task group
7408 * is eligible to hold on a single cpu. On N cpus, it is
7409 * eligible to hold (N * tg->shares) number of cpu shares.
7411 total_shares
= tg
->shares
* cpus_weight(sdspan
);
7414 * redistribute total_shares across cpus as per the task load
7417 for_each_cpu_mask(i
, sdspan
) {
7418 unsigned long local_load
, local_shares
;
7420 local_load
= tg
->cfs_rq
[i
]->load
.weight
;
7421 local_shares
= (local_load
* total_shares
) / total_load
;
7423 local_shares
= MIN_GROUP_SHARES
;
7424 if (local_shares
== tg
->se
[i
]->load
.weight
)
7427 spin_lock_irq(&cpu_rq(i
)->lock
);
7428 set_se_shares(tg
->se
[i
], local_shares
);
7429 spin_unlock_irq(&cpu_rq(i
)->lock
);
7438 * How frequently should we rebalance_shares() across cpus?
7440 * The more frequently we rebalance shares, the more accurate is the fairness
7441 * of cpu bandwidth distribution between task groups. However higher frequency
7442 * also implies increased scheduling overhead.
7444 * sysctl_sched_min_bal_int_shares represents the minimum interval between
7445 * consecutive calls to rebalance_shares() in the same sched domain.
7447 * sysctl_sched_max_bal_int_shares represents the maximum interval between
7448 * consecutive calls to rebalance_shares() in the same sched domain.
7450 * These settings allows for the appropriate trade-off between accuracy of
7451 * fairness and the associated overhead.
7455 /* default: 8ms, units: milliseconds */
7456 const_debug
unsigned int sysctl_sched_min_bal_int_shares
= 8;
7458 /* default: 128ms, units: milliseconds */
7459 const_debug
unsigned int sysctl_sched_max_bal_int_shares
= 128;
7461 /* kernel thread that runs rebalance_shares() periodically */
7462 static int load_balance_monitor(void *unused
)
7464 unsigned int timeout
= sysctl_sched_min_bal_int_shares
;
7465 struct sched_param schedparm
;
7469 * We don't want this thread's execution to be limited by the shares
7470 * assigned to default group (init_task_group). Hence make it run
7471 * as a SCHED_RR RT task at the lowest priority.
7473 schedparm
.sched_priority
= 1;
7474 ret
= sched_setscheduler(current
, SCHED_RR
, &schedparm
);
7476 printk(KERN_ERR
"Couldn't set SCHED_RR policy for load balance"
7477 " monitor thread (error = %d) \n", ret
);
7479 while (!kthread_should_stop()) {
7480 int i
, cpu
, balanced
= 1;
7482 /* Prevent cpus going down or coming up */
7484 /* lockout changes to doms_cur[] array */
7487 * Enter a rcu read-side critical section to safely walk rq->sd
7488 * chain on various cpus and to walk task group list
7489 * (rq->leaf_cfs_rq_list) in rebalance_shares().
7493 for (i
= 0; i
< ndoms_cur
; i
++) {
7494 cpumask_t cpumap
= doms_cur
[i
];
7495 struct sched_domain
*sd
= NULL
, *sd_prev
= NULL
;
7497 cpu
= first_cpu(cpumap
);
7499 /* Find the highest domain at which to balance shares */
7500 for_each_domain(cpu
, sd
) {
7501 if (!(sd
->flags
& SD_LOAD_BALANCE
))
7507 /* sd == NULL? No load balance reqd in this domain */
7511 balanced
&= rebalance_shares(sd
, cpu
);
7520 timeout
= sysctl_sched_min_bal_int_shares
;
7521 else if (timeout
< sysctl_sched_max_bal_int_shares
)
7524 msleep_interruptible(timeout
);
7529 #endif /* CONFIG_SMP */
7531 static void free_sched_group(struct task_group
*tg
)
7535 for_each_possible_cpu(i
) {
7537 kfree(tg
->cfs_rq
[i
]);
7541 kfree(tg
->rt_rq
[i
]);
7543 kfree(tg
->rt_se
[i
]);
7553 /* allocate runqueue etc for a new task group */
7554 struct task_group
*sched_create_group(void)
7556 struct task_group
*tg
;
7557 struct cfs_rq
*cfs_rq
;
7558 struct sched_entity
*se
;
7559 struct rt_rq
*rt_rq
;
7560 struct sched_rt_entity
*rt_se
;
7562 unsigned long flags
;
7565 tg
= kzalloc(sizeof(*tg
), GFP_KERNEL
);
7567 return ERR_PTR(-ENOMEM
);
7569 tg
->cfs_rq
= kzalloc(sizeof(cfs_rq
) * NR_CPUS
, GFP_KERNEL
);
7572 tg
->se
= kzalloc(sizeof(se
) * NR_CPUS
, GFP_KERNEL
);
7575 tg
->rt_rq
= kzalloc(sizeof(rt_rq
) * NR_CPUS
, GFP_KERNEL
);
7578 tg
->rt_se
= kzalloc(sizeof(rt_se
) * NR_CPUS
, GFP_KERNEL
);
7582 tg
->shares
= NICE_0_LOAD
;
7583 tg
->rt_ratio
= 0; /* XXX */
7585 for_each_possible_cpu(i
) {
7588 cfs_rq
= kmalloc_node(sizeof(struct cfs_rq
),
7589 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
7593 se
= kmalloc_node(sizeof(struct sched_entity
),
7594 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
7598 rt_rq
= kmalloc_node(sizeof(struct rt_rq
),
7599 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
7603 rt_se
= kmalloc_node(sizeof(struct sched_rt_entity
),
7604 GFP_KERNEL
|__GFP_ZERO
, cpu_to_node(i
));
7608 init_tg_cfs_entry(rq
, tg
, cfs_rq
, se
, i
, 0);
7609 init_tg_rt_entry(rq
, tg
, rt_rq
, rt_se
, i
, 0);
7612 spin_lock_irqsave(&task_group_lock
, flags
);
7613 for_each_possible_cpu(i
) {
7615 cfs_rq
= tg
->cfs_rq
[i
];
7616 list_add_rcu(&cfs_rq
->leaf_cfs_rq_list
, &rq
->leaf_cfs_rq_list
);
7617 rt_rq
= tg
->rt_rq
[i
];
7618 list_add_rcu(&rt_rq
->leaf_rt_rq_list
, &rq
->leaf_rt_rq_list
);
7620 list_add_rcu(&tg
->list
, &task_groups
);
7621 spin_unlock_irqrestore(&task_group_lock
, flags
);
7626 free_sched_group(tg
);
7627 return ERR_PTR(-ENOMEM
);
7630 /* rcu callback to free various structures associated with a task group */
7631 static void free_sched_group_rcu(struct rcu_head
*rhp
)
7633 /* now it should be safe to free those cfs_rqs */
7634 free_sched_group(container_of(rhp
, struct task_group
, rcu
));
7637 /* Destroy runqueue etc associated with a task group */
7638 void sched_destroy_group(struct task_group
*tg
)
7640 struct cfs_rq
*cfs_rq
= NULL
;
7641 struct rt_rq
*rt_rq
= NULL
;
7642 unsigned long flags
;
7645 spin_lock_irqsave(&task_group_lock
, flags
);
7646 for_each_possible_cpu(i
) {
7647 cfs_rq
= tg
->cfs_rq
[i
];
7648 list_del_rcu(&cfs_rq
->leaf_cfs_rq_list
);
7649 rt_rq
= tg
->rt_rq
[i
];
7650 list_del_rcu(&rt_rq
->leaf_rt_rq_list
);
7652 list_del_rcu(&tg
->list
);
7653 spin_unlock_irqrestore(&task_group_lock
, flags
);
7657 /* wait for possible concurrent references to cfs_rqs complete */
7658 call_rcu(&tg
->rcu
, free_sched_group_rcu
);
7661 /* change task's runqueue when it moves between groups.
7662 * The caller of this function should have put the task in its new group
7663 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7664 * reflect its new group.
7666 void sched_move_task(struct task_struct
*tsk
)
7669 unsigned long flags
;
7672 rq
= task_rq_lock(tsk
, &flags
);
7674 update_rq_clock(rq
);
7676 running
= task_current(rq
, tsk
);
7677 on_rq
= tsk
->se
.on_rq
;
7680 dequeue_task(rq
, tsk
, 0);
7681 if (unlikely(running
))
7682 tsk
->sched_class
->put_prev_task(rq
, tsk
);
7685 set_task_rq(tsk
, task_cpu(tsk
));
7688 if (unlikely(running
))
7689 tsk
->sched_class
->set_curr_task(rq
);
7690 enqueue_task(rq
, tsk
, 0);
7693 task_rq_unlock(rq
, &flags
);
7696 /* rq->lock to be locked by caller */
7697 static void set_se_shares(struct sched_entity
*se
, unsigned long shares
)
7699 struct cfs_rq
*cfs_rq
= se
->cfs_rq
;
7700 struct rq
*rq
= cfs_rq
->rq
;
7704 shares
= MIN_GROUP_SHARES
;
7708 dequeue_entity(cfs_rq
, se
, 0);
7709 dec_cpu_load(rq
, se
->load
.weight
);
7712 se
->load
.weight
= shares
;
7713 se
->load
.inv_weight
= div64_64((1ULL<<32), shares
);
7716 enqueue_entity(cfs_rq
, se
, 0);
7717 inc_cpu_load(rq
, se
->load
.weight
);
7721 static DEFINE_MUTEX(shares_mutex
);
7723 int sched_group_set_shares(struct task_group
*tg
, unsigned long shares
)
7726 struct cfs_rq
*cfs_rq
;
7728 unsigned long flags
;
7730 mutex_lock(&shares_mutex
);
7731 if (tg
->shares
== shares
)
7734 if (shares
< MIN_GROUP_SHARES
)
7735 shares
= MIN_GROUP_SHARES
;
7738 * Prevent any load balance activity (rebalance_shares,
7739 * load_balance_fair) from referring to this group first,
7740 * by taking it off the rq->leaf_cfs_rq_list on each cpu.
7742 spin_lock_irqsave(&task_group_lock
, flags
);
7743 for_each_possible_cpu(i
) {
7744 cfs_rq
= tg
->cfs_rq
[i
];
7745 list_del_rcu(&cfs_rq
->leaf_cfs_rq_list
);
7747 spin_unlock_irqrestore(&task_group_lock
, flags
);
7749 /* wait for any ongoing reference to this group to finish */
7750 synchronize_sched();
7753 * Now we are free to modify the group's share on each cpu
7754 * w/o tripping rebalance_share or load_balance_fair.
7756 tg
->shares
= shares
;
7757 for_each_possible_cpu(i
) {
7758 spin_lock_irq(&cpu_rq(i
)->lock
);
7759 set_se_shares(tg
->se
[i
], shares
);
7760 spin_unlock_irq(&cpu_rq(i
)->lock
);
7764 * Enable load balance activity on this group, by inserting it back on
7765 * each cpu's rq->leaf_cfs_rq_list.
7767 spin_lock_irqsave(&task_group_lock
, flags
);
7768 for_each_possible_cpu(i
) {
7770 cfs_rq
= tg
->cfs_rq
[i
];
7771 list_add_rcu(&cfs_rq
->leaf_cfs_rq_list
, &rq
->leaf_cfs_rq_list
);
7773 spin_unlock_irqrestore(&task_group_lock
, flags
);
7775 mutex_unlock(&shares_mutex
);
7779 unsigned long sched_group_shares(struct task_group
*tg
)
7785 * Ensure the total rt_ratio <= sysctl_sched_rt_ratio
7787 int sched_group_set_rt_ratio(struct task_group
*tg
, unsigned long rt_ratio
)
7789 struct task_group
*tgi
;
7790 unsigned long total
= 0;
7793 list_for_each_entry_rcu(tgi
, &task_groups
, list
)
7794 total
+= tgi
->rt_ratio
;
7797 if (total
+ rt_ratio
- tg
->rt_ratio
> sysctl_sched_rt_ratio
)
7800 tg
->rt_ratio
= rt_ratio
;
7804 unsigned long sched_group_rt_ratio(struct task_group
*tg
)
7806 return tg
->rt_ratio
;
7809 #endif /* CONFIG_FAIR_GROUP_SCHED */
7811 #ifdef CONFIG_FAIR_CGROUP_SCHED
7813 /* return corresponding task_group object of a cgroup */
7814 static inline struct task_group
*cgroup_tg(struct cgroup
*cgrp
)
7816 return container_of(cgroup_subsys_state(cgrp
, cpu_cgroup_subsys_id
),
7817 struct task_group
, css
);
7820 static struct cgroup_subsys_state
*
7821 cpu_cgroup_create(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
7823 struct task_group
*tg
;
7825 if (!cgrp
->parent
) {
7826 /* This is early initialization for the top cgroup */
7827 init_task_group
.css
.cgroup
= cgrp
;
7828 return &init_task_group
.css
;
7831 /* we support only 1-level deep hierarchical scheduler atm */
7832 if (cgrp
->parent
->parent
)
7833 return ERR_PTR(-EINVAL
);
7835 tg
= sched_create_group();
7837 return ERR_PTR(-ENOMEM
);
7839 /* Bind the cgroup to task_group object we just created */
7840 tg
->css
.cgroup
= cgrp
;
7846 cpu_cgroup_destroy(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
7848 struct task_group
*tg
= cgroup_tg(cgrp
);
7850 sched_destroy_group(tg
);
7854 cpu_cgroup_can_attach(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
,
7855 struct task_struct
*tsk
)
7857 /* We don't support RT-tasks being in separate groups */
7858 if (tsk
->sched_class
!= &fair_sched_class
)
7865 cpu_cgroup_attach(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
,
7866 struct cgroup
*old_cont
, struct task_struct
*tsk
)
7868 sched_move_task(tsk
);
7871 static int cpu_shares_write_uint(struct cgroup
*cgrp
, struct cftype
*cftype
,
7874 return sched_group_set_shares(cgroup_tg(cgrp
), shareval
);
7877 static u64
cpu_shares_read_uint(struct cgroup
*cgrp
, struct cftype
*cft
)
7879 struct task_group
*tg
= cgroup_tg(cgrp
);
7881 return (u64
) tg
->shares
;
7884 static int cpu_rt_ratio_write_uint(struct cgroup
*cgrp
, struct cftype
*cftype
,
7887 return sched_group_set_rt_ratio(cgroup_tg(cgrp
), rt_ratio_val
);
7890 static u64
cpu_rt_ratio_read_uint(struct cgroup
*cgrp
, struct cftype
*cft
)
7892 struct task_group
*tg
= cgroup_tg(cgrp
);
7894 return (u64
) tg
->rt_ratio
;
7897 static struct cftype cpu_files
[] = {
7900 .read_uint
= cpu_shares_read_uint
,
7901 .write_uint
= cpu_shares_write_uint
,
7905 .read_uint
= cpu_rt_ratio_read_uint
,
7906 .write_uint
= cpu_rt_ratio_write_uint
,
7910 static int cpu_cgroup_populate(struct cgroup_subsys
*ss
, struct cgroup
*cont
)
7912 return cgroup_add_files(cont
, ss
, cpu_files
, ARRAY_SIZE(cpu_files
));
7915 struct cgroup_subsys cpu_cgroup_subsys
= {
7917 .create
= cpu_cgroup_create
,
7918 .destroy
= cpu_cgroup_destroy
,
7919 .can_attach
= cpu_cgroup_can_attach
,
7920 .attach
= cpu_cgroup_attach
,
7921 .populate
= cpu_cgroup_populate
,
7922 .subsys_id
= cpu_cgroup_subsys_id
,
7926 #endif /* CONFIG_FAIR_CGROUP_SCHED */
7928 #ifdef CONFIG_CGROUP_CPUACCT
7931 * CPU accounting code for task groups.
7933 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
7934 * (balbir@in.ibm.com).
7937 /* track cpu usage of a group of tasks */
7939 struct cgroup_subsys_state css
;
7940 /* cpuusage holds pointer to a u64-type object on every cpu */
7944 struct cgroup_subsys cpuacct_subsys
;
7946 /* return cpu accounting group corresponding to this container */
7947 static inline struct cpuacct
*cgroup_ca(struct cgroup
*cont
)
7949 return container_of(cgroup_subsys_state(cont
, cpuacct_subsys_id
),
7950 struct cpuacct
, css
);
7953 /* return cpu accounting group to which this task belongs */
7954 static inline struct cpuacct
*task_ca(struct task_struct
*tsk
)
7956 return container_of(task_subsys_state(tsk
, cpuacct_subsys_id
),
7957 struct cpuacct
, css
);
7960 /* create a new cpu accounting group */
7961 static struct cgroup_subsys_state
*cpuacct_create(
7962 struct cgroup_subsys
*ss
, struct cgroup
*cont
)
7964 struct cpuacct
*ca
= kzalloc(sizeof(*ca
), GFP_KERNEL
);
7967 return ERR_PTR(-ENOMEM
);
7969 ca
->cpuusage
= alloc_percpu(u64
);
7970 if (!ca
->cpuusage
) {
7972 return ERR_PTR(-ENOMEM
);
7978 /* destroy an existing cpu accounting group */
7980 cpuacct_destroy(struct cgroup_subsys
*ss
, struct cgroup
*cont
)
7982 struct cpuacct
*ca
= cgroup_ca(cont
);
7984 free_percpu(ca
->cpuusage
);
7988 /* return total cpu usage (in nanoseconds) of a group */
7989 static u64
cpuusage_read(struct cgroup
*cont
, struct cftype
*cft
)
7991 struct cpuacct
*ca
= cgroup_ca(cont
);
7992 u64 totalcpuusage
= 0;
7995 for_each_possible_cpu(i
) {
7996 u64
*cpuusage
= percpu_ptr(ca
->cpuusage
, i
);
7999 * Take rq->lock to make 64-bit addition safe on 32-bit
8002 spin_lock_irq(&cpu_rq(i
)->lock
);
8003 totalcpuusage
+= *cpuusage
;
8004 spin_unlock_irq(&cpu_rq(i
)->lock
);
8007 return totalcpuusage
;
8010 static struct cftype files
[] = {
8013 .read_uint
= cpuusage_read
,
8017 static int cpuacct_populate(struct cgroup_subsys
*ss
, struct cgroup
*cont
)
8019 return cgroup_add_files(cont
, ss
, files
, ARRAY_SIZE(files
));
8023 * charge this task's execution time to its accounting group.
8025 * called with rq->lock held.
8027 static void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
)
8031 if (!cpuacct_subsys
.active
)
8036 u64
*cpuusage
= percpu_ptr(ca
->cpuusage
, task_cpu(tsk
));
8038 *cpuusage
+= cputime
;
8042 struct cgroup_subsys cpuacct_subsys
= {
8044 .create
= cpuacct_create
,
8045 .destroy
= cpuacct_destroy
,
8046 .populate
= cpuacct_populate
,
8047 .subsys_id
= cpuacct_subsys_id
,
8049 #endif /* CONFIG_CGROUP_CPUACCT */