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 /* task group related information */
166 #ifdef CONFIG_FAIR_CGROUP_SCHED
167 struct cgroup_subsys_state css
;
169 /* schedulable entities of this group on each cpu */
170 struct sched_entity
**se
;
171 /* runqueue "owned" by this group on each cpu */
172 struct cfs_rq
**cfs_rq
;
175 * shares assigned to a task group governs how much of cpu bandwidth
176 * is allocated to the group. The more shares a group has, the more is
177 * the cpu bandwidth allocated to it.
179 * For ex, lets say that there are three task groups, A, B and C which
180 * have been assigned shares 1000, 2000 and 3000 respectively. Then,
181 * cpu bandwidth allocated by the scheduler to task groups A, B and C
184 * Bw(A) = 1000/(1000+2000+3000) * 100 = 16.66%
185 * Bw(B) = 2000/(1000+2000+3000) * 100 = 33.33%
186 * Bw(C) = 3000/(1000+2000+3000) * 100 = 50%
188 * The weight assigned to a task group's schedulable entities on every
189 * cpu (task_group.se[a_cpu]->load.weight) is derived from the task
190 * group's shares. For ex: lets say that task group A has been
191 * assigned shares of 1000 and there are two CPUs in a system. Then,
193 * tg_A->se[0]->load.weight = tg_A->se[1]->load.weight = 1000;
195 * Note: It's not necessary that each of a task's group schedulable
196 * entity have the same weight on all CPUs. If the group
197 * has 2 of its tasks on CPU0 and 1 task on CPU1, then a
198 * better distribution of weight could be:
200 * tg_A->se[0]->load.weight = 2/3 * 2000 = 1333
201 * tg_A->se[1]->load.weight = 1/2 * 2000 = 667
203 * rebalance_shares() is responsible for distributing the shares of a
204 * task groups like this among the group's schedulable entities across
208 unsigned long shares
;
213 /* Default task group's sched entity on each cpu */
214 static DEFINE_PER_CPU(struct sched_entity
, init_sched_entity
);
215 /* Default task group's cfs_rq on each cpu */
216 static DEFINE_PER_CPU(struct cfs_rq
, init_cfs_rq
) ____cacheline_aligned_in_smp
;
218 static struct sched_entity
*init_sched_entity_p
[NR_CPUS
];
219 static struct cfs_rq
*init_cfs_rq_p
[NR_CPUS
];
221 /* task_group_mutex serializes add/remove of task groups and also changes to
222 * a task group's cpu shares.
224 static DEFINE_MUTEX(task_group_mutex
);
226 /* doms_cur_mutex serializes access to doms_cur[] array */
227 static DEFINE_MUTEX(doms_cur_mutex
);
230 /* kernel thread that runs rebalance_shares() periodically */
231 static struct task_struct
*lb_monitor_task
;
232 static int load_balance_monitor(void *unused
);
235 static void set_se_shares(struct sched_entity
*se
, unsigned long shares
);
237 /* Default task group.
238 * Every task in system belong to this group at bootup.
240 struct task_group init_task_group
= {
241 .se
= init_sched_entity_p
,
242 .cfs_rq
= init_cfs_rq_p
,
245 #ifdef CONFIG_FAIR_USER_SCHED
246 # define INIT_TASK_GROUP_LOAD (2*NICE_0_LOAD)
248 # define INIT_TASK_GROUP_LOAD NICE_0_LOAD
251 #define MIN_GROUP_SHARES 2
253 static int init_task_group_load
= INIT_TASK_GROUP_LOAD
;
255 /* return group to which a task belongs */
256 static inline struct task_group
*task_group(struct task_struct
*p
)
258 struct task_group
*tg
;
260 #ifdef CONFIG_FAIR_USER_SCHED
262 #elif defined(CONFIG_FAIR_CGROUP_SCHED)
263 tg
= container_of(task_subsys_state(p
, cpu_cgroup_subsys_id
),
264 struct task_group
, css
);
266 tg
= &init_task_group
;
271 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
272 static inline void set_task_cfs_rq(struct task_struct
*p
, unsigned int cpu
)
274 p
->se
.cfs_rq
= task_group(p
)->cfs_rq
[cpu
];
275 p
->se
.parent
= task_group(p
)->se
[cpu
];
278 static inline void lock_task_group_list(void)
280 mutex_lock(&task_group_mutex
);
283 static inline void unlock_task_group_list(void)
285 mutex_unlock(&task_group_mutex
);
288 static inline void lock_doms_cur(void)
290 mutex_lock(&doms_cur_mutex
);
293 static inline void unlock_doms_cur(void)
295 mutex_unlock(&doms_cur_mutex
);
300 static inline void set_task_cfs_rq(struct task_struct
*p
, unsigned int cpu
) { }
301 static inline void lock_task_group_list(void) { }
302 static inline void unlock_task_group_list(void) { }
303 static inline void lock_doms_cur(void) { }
304 static inline void unlock_doms_cur(void) { }
306 #endif /* CONFIG_FAIR_GROUP_SCHED */
308 /* CFS-related fields in a runqueue */
310 struct load_weight load
;
311 unsigned long nr_running
;
316 struct rb_root tasks_timeline
;
317 struct rb_node
*rb_leftmost
;
318 struct rb_node
*rb_load_balance_curr
;
319 /* 'curr' points to currently running entity on this cfs_rq.
320 * It is set to NULL otherwise (i.e when none are currently running).
322 struct sched_entity
*curr
;
324 unsigned long nr_spread_over
;
326 #ifdef CONFIG_FAIR_GROUP_SCHED
327 struct rq
*rq
; /* cpu runqueue to which this cfs_rq is attached */
330 * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
331 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
332 * (like users, containers etc.)
334 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
335 * list is used during load balance.
337 struct list_head leaf_cfs_rq_list
;
338 struct task_group
*tg
; /* group that "owns" this runqueue */
342 /* Real-Time classes' related field in a runqueue: */
344 struct rt_prio_array active
;
345 int rt_load_balance_idx
;
346 struct list_head
*rt_load_balance_head
, *rt_load_balance_curr
;
347 unsigned long rt_nr_running
;
348 unsigned long rt_nr_migratory
;
349 /* highest queued rt task prio */
357 * We add the notion of a root-domain which will be used to define per-domain
358 * variables. Each exclusive cpuset essentially defines an island domain by
359 * fully partitioning the member cpus from any other cpuset. Whenever a new
360 * exclusive cpuset is created, we also create and attach a new root-domain
370 * The "RT overload" flag: it gets set if a CPU has more than
371 * one runnable RT task.
378 * By default the system creates a single root-domain with all cpus as
379 * members (mimicking the global state we have today).
381 static struct root_domain def_root_domain
;
386 * This is the main, per-CPU runqueue data structure.
388 * Locking rule: those places that want to lock multiple runqueues
389 * (such as the load balancing or the thread migration code), lock
390 * acquire operations must be ordered by ascending &runqueue.
397 * nr_running and cpu_load should be in the same cacheline because
398 * remote CPUs use both these fields when doing load calculation.
400 unsigned long nr_running
;
401 #define CPU_LOAD_IDX_MAX 5
402 unsigned long cpu_load
[CPU_LOAD_IDX_MAX
];
403 unsigned char idle_at_tick
;
405 unsigned char in_nohz_recently
;
407 /* capture load from *all* tasks on this cpu: */
408 struct load_weight load
;
409 unsigned long nr_load_updates
;
413 #ifdef CONFIG_FAIR_GROUP_SCHED
414 /* list of leaf cfs_rq on this cpu: */
415 struct list_head leaf_cfs_rq_list
;
420 * This is part of a global counter where only the total sum
421 * over all CPUs matters. A task can increase this counter on
422 * one CPU and if it got migrated afterwards it may decrease
423 * it on another CPU. Always updated under the runqueue lock:
425 unsigned long nr_uninterruptible
;
427 struct task_struct
*curr
, *idle
;
428 unsigned long next_balance
;
429 struct mm_struct
*prev_mm
;
431 u64 clock
, prev_clock_raw
;
434 unsigned int clock_warps
, clock_overflows
;
436 unsigned int clock_deep_idle_events
;
442 struct root_domain
*rd
;
443 struct sched_domain
*sd
;
445 /* For active balancing */
448 /* cpu of this runqueue: */
451 struct task_struct
*migration_thread
;
452 struct list_head migration_queue
;
455 #ifdef CONFIG_SCHED_HRTICK
456 unsigned long hrtick_flags
;
457 ktime_t hrtick_expire
;
458 struct hrtimer hrtick_timer
;
461 #ifdef CONFIG_SCHEDSTATS
463 struct sched_info rq_sched_info
;
465 /* sys_sched_yield() stats */
466 unsigned int yld_exp_empty
;
467 unsigned int yld_act_empty
;
468 unsigned int yld_both_empty
;
469 unsigned int yld_count
;
471 /* schedule() stats */
472 unsigned int sched_switch
;
473 unsigned int sched_count
;
474 unsigned int sched_goidle
;
476 /* try_to_wake_up() stats */
477 unsigned int ttwu_count
;
478 unsigned int ttwu_local
;
481 unsigned int bkl_count
;
483 struct lock_class_key rq_lock_key
;
486 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq
, runqueues
);
488 static inline void check_preempt_curr(struct rq
*rq
, struct task_struct
*p
)
490 rq
->curr
->sched_class
->check_preempt_curr(rq
, p
);
493 static inline int cpu_of(struct rq
*rq
)
503 * Update the per-runqueue clock, as finegrained as the platform can give
504 * us, but without assuming monotonicity, etc.:
506 static void __update_rq_clock(struct rq
*rq
)
508 u64 prev_raw
= rq
->prev_clock_raw
;
509 u64 now
= sched_clock();
510 s64 delta
= now
- prev_raw
;
511 u64 clock
= rq
->clock
;
513 #ifdef CONFIG_SCHED_DEBUG
514 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
517 * Protect against sched_clock() occasionally going backwards:
519 if (unlikely(delta
< 0)) {
524 * Catch too large forward jumps too:
526 if (unlikely(clock
+ delta
> rq
->tick_timestamp
+ TICK_NSEC
)) {
527 if (clock
< rq
->tick_timestamp
+ TICK_NSEC
)
528 clock
= rq
->tick_timestamp
+ TICK_NSEC
;
531 rq
->clock_overflows
++;
533 if (unlikely(delta
> rq
->clock_max_delta
))
534 rq
->clock_max_delta
= delta
;
539 rq
->prev_clock_raw
= now
;
543 static void update_rq_clock(struct rq
*rq
)
545 if (likely(smp_processor_id() == cpu_of(rq
)))
546 __update_rq_clock(rq
);
550 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
551 * See detach_destroy_domains: synchronize_sched for details.
553 * The domain tree of any CPU may only be accessed from within
554 * preempt-disabled sections.
556 #define for_each_domain(cpu, __sd) \
557 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
559 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
560 #define this_rq() (&__get_cpu_var(runqueues))
561 #define task_rq(p) cpu_rq(task_cpu(p))
562 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
565 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
567 #ifdef CONFIG_SCHED_DEBUG
568 # define const_debug __read_mostly
570 # define const_debug static const
574 * Debugging: various feature bits
577 SCHED_FEAT_NEW_FAIR_SLEEPERS
= 1,
578 SCHED_FEAT_WAKEUP_PREEMPT
= 2,
579 SCHED_FEAT_START_DEBIT
= 4,
580 SCHED_FEAT_TREE_AVG
= 8,
581 SCHED_FEAT_APPROX_AVG
= 16,
582 SCHED_FEAT_HRTICK
= 32,
583 SCHED_FEAT_DOUBLE_TICK
= 64,
586 const_debug
unsigned int sysctl_sched_features
=
587 SCHED_FEAT_NEW_FAIR_SLEEPERS
* 1 |
588 SCHED_FEAT_WAKEUP_PREEMPT
* 1 |
589 SCHED_FEAT_START_DEBIT
* 1 |
590 SCHED_FEAT_TREE_AVG
* 0 |
591 SCHED_FEAT_APPROX_AVG
* 0 |
592 SCHED_FEAT_HRTICK
* 1 |
593 SCHED_FEAT_DOUBLE_TICK
* 0;
595 #define sched_feat(x) (sysctl_sched_features & SCHED_FEAT_##x)
598 * Number of tasks to iterate in a single balance run.
599 * Limited because this is done with IRQs disabled.
601 const_debug
unsigned int sysctl_sched_nr_migrate
= 32;
604 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
605 * clock constructed from sched_clock():
607 unsigned long long cpu_clock(int cpu
)
609 unsigned long long now
;
613 local_irq_save(flags
);
616 * Only call sched_clock() if the scheduler has already been
617 * initialized (some code might call cpu_clock() very early):
622 local_irq_restore(flags
);
626 EXPORT_SYMBOL_GPL(cpu_clock
);
628 #ifndef prepare_arch_switch
629 # define prepare_arch_switch(next) do { } while (0)
631 #ifndef finish_arch_switch
632 # define finish_arch_switch(prev) do { } while (0)
635 static inline int task_current(struct rq
*rq
, struct task_struct
*p
)
637 return rq
->curr
== p
;
640 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
641 static inline int task_running(struct rq
*rq
, struct task_struct
*p
)
643 return task_current(rq
, p
);
646 static inline void prepare_lock_switch(struct rq
*rq
, struct task_struct
*next
)
650 static inline void finish_lock_switch(struct rq
*rq
, struct task_struct
*prev
)
652 #ifdef CONFIG_DEBUG_SPINLOCK
653 /* this is a valid case when another task releases the spinlock */
654 rq
->lock
.owner
= current
;
657 * If we are tracking spinlock dependencies then we have to
658 * fix up the runqueue lock - which gets 'carried over' from
661 spin_acquire(&rq
->lock
.dep_map
, 0, 0, _THIS_IP_
);
663 spin_unlock_irq(&rq
->lock
);
666 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
667 static inline int task_running(struct rq
*rq
, struct task_struct
*p
)
672 return task_current(rq
, p
);
676 static inline void prepare_lock_switch(struct rq
*rq
, struct task_struct
*next
)
680 * We can optimise this out completely for !SMP, because the
681 * SMP rebalancing from interrupt is the only thing that cares
686 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
687 spin_unlock_irq(&rq
->lock
);
689 spin_unlock(&rq
->lock
);
693 static inline void finish_lock_switch(struct rq
*rq
, struct task_struct
*prev
)
697 * After ->oncpu is cleared, the task can be moved to a different CPU.
698 * We must ensure this doesn't happen until the switch is completely
704 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
708 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
711 * __task_rq_lock - lock the runqueue a given task resides on.
712 * Must be called interrupts disabled.
714 static inline struct rq
*__task_rq_lock(struct task_struct
*p
)
718 struct rq
*rq
= task_rq(p
);
719 spin_lock(&rq
->lock
);
720 if (likely(rq
== task_rq(p
)))
722 spin_unlock(&rq
->lock
);
727 * task_rq_lock - lock the runqueue a given task resides on and disable
728 * interrupts. Note the ordering: we can safely lookup the task_rq without
729 * explicitly disabling preemption.
731 static struct rq
*task_rq_lock(struct task_struct
*p
, unsigned long *flags
)
737 local_irq_save(*flags
);
739 spin_lock(&rq
->lock
);
740 if (likely(rq
== task_rq(p
)))
742 spin_unlock_irqrestore(&rq
->lock
, *flags
);
746 static void __task_rq_unlock(struct rq
*rq
)
749 spin_unlock(&rq
->lock
);
752 static inline void task_rq_unlock(struct rq
*rq
, unsigned long *flags
)
755 spin_unlock_irqrestore(&rq
->lock
, *flags
);
759 * this_rq_lock - lock this runqueue and disable interrupts.
761 static struct rq
*this_rq_lock(void)
768 spin_lock(&rq
->lock
);
774 * We are going deep-idle (irqs are disabled):
776 void sched_clock_idle_sleep_event(void)
778 struct rq
*rq
= cpu_rq(smp_processor_id());
780 spin_lock(&rq
->lock
);
781 __update_rq_clock(rq
);
782 spin_unlock(&rq
->lock
);
783 rq
->clock_deep_idle_events
++;
785 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event
);
788 * We just idled delta nanoseconds (called with irqs disabled):
790 void sched_clock_idle_wakeup_event(u64 delta_ns
)
792 struct rq
*rq
= cpu_rq(smp_processor_id());
793 u64 now
= sched_clock();
795 touch_softlockup_watchdog();
796 rq
->idle_clock
+= delta_ns
;
798 * Override the previous timestamp and ignore all
799 * sched_clock() deltas that occured while we idled,
800 * and use the PM-provided delta_ns to advance the
803 spin_lock(&rq
->lock
);
804 rq
->prev_clock_raw
= now
;
805 rq
->clock
+= delta_ns
;
806 spin_unlock(&rq
->lock
);
808 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event
);
810 static void __resched_task(struct task_struct
*p
, int tif_bit
);
812 static inline void resched_task(struct task_struct
*p
)
814 __resched_task(p
, TIF_NEED_RESCHED
);
817 #ifdef CONFIG_SCHED_HRTICK
819 * Use HR-timers to deliver accurate preemption points.
821 * Its all a bit involved since we cannot program an hrt while holding the
822 * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
825 * When we get rescheduled we reprogram the hrtick_timer outside of the
828 static inline void resched_hrt(struct task_struct
*p
)
830 __resched_task(p
, TIF_HRTICK_RESCHED
);
833 static inline void resched_rq(struct rq
*rq
)
837 spin_lock_irqsave(&rq
->lock
, flags
);
838 resched_task(rq
->curr
);
839 spin_unlock_irqrestore(&rq
->lock
, flags
);
843 HRTICK_SET
, /* re-programm hrtick_timer */
844 HRTICK_RESET
, /* not a new slice */
849 * - enabled by features
850 * - hrtimer is actually high res
852 static inline int hrtick_enabled(struct rq
*rq
)
854 if (!sched_feat(HRTICK
))
856 return hrtimer_is_hres_active(&rq
->hrtick_timer
);
860 * Called to set the hrtick timer state.
862 * called with rq->lock held and irqs disabled
864 static void hrtick_start(struct rq
*rq
, u64 delay
, int reset
)
866 assert_spin_locked(&rq
->lock
);
869 * preempt at: now + delay
872 ktime_add_ns(rq
->hrtick_timer
.base
->get_time(), delay
);
874 * indicate we need to program the timer
876 __set_bit(HRTICK_SET
, &rq
->hrtick_flags
);
878 __set_bit(HRTICK_RESET
, &rq
->hrtick_flags
);
881 * New slices are called from the schedule path and don't need a
885 resched_hrt(rq
->curr
);
888 static void hrtick_clear(struct rq
*rq
)
890 if (hrtimer_active(&rq
->hrtick_timer
))
891 hrtimer_cancel(&rq
->hrtick_timer
);
895 * Update the timer from the possible pending state.
897 static void hrtick_set(struct rq
*rq
)
903 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
905 spin_lock_irqsave(&rq
->lock
, flags
);
906 set
= __test_and_clear_bit(HRTICK_SET
, &rq
->hrtick_flags
);
907 reset
= __test_and_clear_bit(HRTICK_RESET
, &rq
->hrtick_flags
);
908 time
= rq
->hrtick_expire
;
909 clear_thread_flag(TIF_HRTICK_RESCHED
);
910 spin_unlock_irqrestore(&rq
->lock
, flags
);
913 hrtimer_start(&rq
->hrtick_timer
, time
, HRTIMER_MODE_ABS
);
914 if (reset
&& !hrtimer_active(&rq
->hrtick_timer
))
921 * High-resolution timer tick.
922 * Runs from hardirq context with interrupts disabled.
924 static enum hrtimer_restart
hrtick(struct hrtimer
*timer
)
926 struct rq
*rq
= container_of(timer
, struct rq
, hrtick_timer
);
928 WARN_ON_ONCE(cpu_of(rq
) != smp_processor_id());
930 spin_lock(&rq
->lock
);
931 __update_rq_clock(rq
);
932 rq
->curr
->sched_class
->task_tick(rq
, rq
->curr
, 1);
933 spin_unlock(&rq
->lock
);
935 return HRTIMER_NORESTART
;
938 static inline void init_rq_hrtick(struct rq
*rq
)
940 rq
->hrtick_flags
= 0;
941 hrtimer_init(&rq
->hrtick_timer
, CLOCK_MONOTONIC
, HRTIMER_MODE_REL
);
942 rq
->hrtick_timer
.function
= hrtick
;
943 rq
->hrtick_timer
.cb_mode
= HRTIMER_CB_IRQSAFE_NO_SOFTIRQ
;
946 void hrtick_resched(void)
951 if (!test_thread_flag(TIF_HRTICK_RESCHED
))
954 local_irq_save(flags
);
955 rq
= cpu_rq(smp_processor_id());
957 local_irq_restore(flags
);
960 static inline void hrtick_clear(struct rq
*rq
)
964 static inline void hrtick_set(struct rq
*rq
)
968 static inline void init_rq_hrtick(struct rq
*rq
)
972 void hrtick_resched(void)
978 * resched_task - mark a task 'to be rescheduled now'.
980 * On UP this means the setting of the need_resched flag, on SMP it
981 * might also involve a cross-CPU call to trigger the scheduler on
986 #ifndef tsk_is_polling
987 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
990 static void __resched_task(struct task_struct
*p
, int tif_bit
)
994 assert_spin_locked(&task_rq(p
)->lock
);
996 if (unlikely(test_tsk_thread_flag(p
, tif_bit
)))
999 set_tsk_thread_flag(p
, tif_bit
);
1002 if (cpu
== smp_processor_id())
1005 /* NEED_RESCHED must be visible before we test polling */
1007 if (!tsk_is_polling(p
))
1008 smp_send_reschedule(cpu
);
1011 static void resched_cpu(int cpu
)
1013 struct rq
*rq
= cpu_rq(cpu
);
1014 unsigned long flags
;
1016 if (!spin_trylock_irqsave(&rq
->lock
, flags
))
1018 resched_task(cpu_curr(cpu
));
1019 spin_unlock_irqrestore(&rq
->lock
, flags
);
1022 static void __resched_task(struct task_struct
*p
, int tif_bit
)
1024 assert_spin_locked(&task_rq(p
)->lock
);
1025 set_tsk_thread_flag(p
, tif_bit
);
1029 #if BITS_PER_LONG == 32
1030 # define WMULT_CONST (~0UL)
1032 # define WMULT_CONST (1UL << 32)
1035 #define WMULT_SHIFT 32
1038 * Shift right and round:
1040 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1042 static unsigned long
1043 calc_delta_mine(unsigned long delta_exec
, unsigned long weight
,
1044 struct load_weight
*lw
)
1048 if (unlikely(!lw
->inv_weight
))
1049 lw
->inv_weight
= (WMULT_CONST
- lw
->weight
/2) / lw
->weight
+ 1;
1051 tmp
= (u64
)delta_exec
* weight
;
1053 * Check whether we'd overflow the 64-bit multiplication:
1055 if (unlikely(tmp
> WMULT_CONST
))
1056 tmp
= SRR(SRR(tmp
, WMULT_SHIFT
/2) * lw
->inv_weight
,
1059 tmp
= SRR(tmp
* lw
->inv_weight
, WMULT_SHIFT
);
1061 return (unsigned long)min(tmp
, (u64
)(unsigned long)LONG_MAX
);
1064 static inline unsigned long
1065 calc_delta_fair(unsigned long delta_exec
, struct load_weight
*lw
)
1067 return calc_delta_mine(delta_exec
, NICE_0_LOAD
, lw
);
1070 static inline void update_load_add(struct load_weight
*lw
, unsigned long inc
)
1075 static inline void update_load_sub(struct load_weight
*lw
, unsigned long dec
)
1081 * To aid in avoiding the subversion of "niceness" due to uneven distribution
1082 * of tasks with abnormal "nice" values across CPUs the contribution that
1083 * each task makes to its run queue's load is weighted according to its
1084 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1085 * scaled version of the new time slice allocation that they receive on time
1089 #define WEIGHT_IDLEPRIO 2
1090 #define WMULT_IDLEPRIO (1 << 31)
1093 * Nice levels are multiplicative, with a gentle 10% change for every
1094 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1095 * nice 1, it will get ~10% less CPU time than another CPU-bound task
1096 * that remained on nice 0.
1098 * The "10% effect" is relative and cumulative: from _any_ nice level,
1099 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1100 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1101 * If a task goes up by ~10% and another task goes down by ~10% then
1102 * the relative distance between them is ~25%.)
1104 static const int prio_to_weight
[40] = {
1105 /* -20 */ 88761, 71755, 56483, 46273, 36291,
1106 /* -15 */ 29154, 23254, 18705, 14949, 11916,
1107 /* -10 */ 9548, 7620, 6100, 4904, 3906,
1108 /* -5 */ 3121, 2501, 1991, 1586, 1277,
1109 /* 0 */ 1024, 820, 655, 526, 423,
1110 /* 5 */ 335, 272, 215, 172, 137,
1111 /* 10 */ 110, 87, 70, 56, 45,
1112 /* 15 */ 36, 29, 23, 18, 15,
1116 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1118 * In cases where the weight does not change often, we can use the
1119 * precalculated inverse to speed up arithmetics by turning divisions
1120 * into multiplications:
1122 static const u32 prio_to_wmult
[40] = {
1123 /* -20 */ 48388, 59856, 76040, 92818, 118348,
1124 /* -15 */ 147320, 184698, 229616, 287308, 360437,
1125 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
1126 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
1127 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
1128 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
1129 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
1130 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1133 static void activate_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
);
1136 * runqueue iterator, to support SMP load-balancing between different
1137 * scheduling classes, without having to expose their internal data
1138 * structures to the load-balancing proper:
1140 struct rq_iterator
{
1142 struct task_struct
*(*start
)(void *);
1143 struct task_struct
*(*next
)(void *);
1147 static unsigned long
1148 balance_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
1149 unsigned long max_load_move
, struct sched_domain
*sd
,
1150 enum cpu_idle_type idle
, int *all_pinned
,
1151 int *this_best_prio
, struct rq_iterator
*iterator
);
1154 iter_move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
1155 struct sched_domain
*sd
, enum cpu_idle_type idle
,
1156 struct rq_iterator
*iterator
);
1159 #ifdef CONFIG_CGROUP_CPUACCT
1160 static void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
);
1162 static inline void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
) {}
1165 static inline void inc_cpu_load(struct rq
*rq
, unsigned long load
)
1167 update_load_add(&rq
->load
, load
);
1170 static inline void dec_cpu_load(struct rq
*rq
, unsigned long load
)
1172 update_load_sub(&rq
->load
, load
);
1176 static unsigned long source_load(int cpu
, int type
);
1177 static unsigned long target_load(int cpu
, int type
);
1178 static unsigned long cpu_avg_load_per_task(int cpu
);
1179 static int task_hot(struct task_struct
*p
, u64 now
, struct sched_domain
*sd
);
1180 #endif /* CONFIG_SMP */
1182 #include "sched_stats.h"
1183 #include "sched_idletask.c"
1184 #include "sched_fair.c"
1185 #include "sched_rt.c"
1186 #ifdef CONFIG_SCHED_DEBUG
1187 # include "sched_debug.c"
1190 #define sched_class_highest (&rt_sched_class)
1192 static void inc_nr_running(struct task_struct
*p
, struct rq
*rq
)
1197 static void dec_nr_running(struct task_struct
*p
, struct rq
*rq
)
1202 static void set_load_weight(struct task_struct
*p
)
1204 if (task_has_rt_policy(p
)) {
1205 p
->se
.load
.weight
= prio_to_weight
[0] * 2;
1206 p
->se
.load
.inv_weight
= prio_to_wmult
[0] >> 1;
1211 * SCHED_IDLE tasks get minimal weight:
1213 if (p
->policy
== SCHED_IDLE
) {
1214 p
->se
.load
.weight
= WEIGHT_IDLEPRIO
;
1215 p
->se
.load
.inv_weight
= WMULT_IDLEPRIO
;
1219 p
->se
.load
.weight
= prio_to_weight
[p
->static_prio
- MAX_RT_PRIO
];
1220 p
->se
.load
.inv_weight
= prio_to_wmult
[p
->static_prio
- MAX_RT_PRIO
];
1223 static void enqueue_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
)
1225 sched_info_queued(p
);
1226 p
->sched_class
->enqueue_task(rq
, p
, wakeup
);
1230 static void dequeue_task(struct rq
*rq
, struct task_struct
*p
, int sleep
)
1232 p
->sched_class
->dequeue_task(rq
, p
, sleep
);
1237 * __normal_prio - return the priority that is based on the static prio
1239 static inline int __normal_prio(struct task_struct
*p
)
1241 return p
->static_prio
;
1245 * Calculate the expected normal priority: i.e. priority
1246 * without taking RT-inheritance into account. Might be
1247 * boosted by interactivity modifiers. Changes upon fork,
1248 * setprio syscalls, and whenever the interactivity
1249 * estimator recalculates.
1251 static inline int normal_prio(struct task_struct
*p
)
1255 if (task_has_rt_policy(p
))
1256 prio
= MAX_RT_PRIO
-1 - p
->rt_priority
;
1258 prio
= __normal_prio(p
);
1263 * Calculate the current priority, i.e. the priority
1264 * taken into account by the scheduler. This value might
1265 * be boosted by RT tasks, or might be boosted by
1266 * interactivity modifiers. Will be RT if the task got
1267 * RT-boosted. If not then it returns p->normal_prio.
1269 static int effective_prio(struct task_struct
*p
)
1271 p
->normal_prio
= normal_prio(p
);
1273 * If we are RT tasks or we were boosted to RT priority,
1274 * keep the priority unchanged. Otherwise, update priority
1275 * to the normal priority:
1277 if (!rt_prio(p
->prio
))
1278 return p
->normal_prio
;
1283 * activate_task - move a task to the runqueue.
1285 static void activate_task(struct rq
*rq
, struct task_struct
*p
, int wakeup
)
1287 if (p
->state
== TASK_UNINTERRUPTIBLE
)
1288 rq
->nr_uninterruptible
--;
1290 enqueue_task(rq
, p
, wakeup
);
1291 inc_nr_running(p
, rq
);
1295 * deactivate_task - remove a task from the runqueue.
1297 static void deactivate_task(struct rq
*rq
, struct task_struct
*p
, int sleep
)
1299 if (p
->state
== TASK_UNINTERRUPTIBLE
)
1300 rq
->nr_uninterruptible
++;
1302 dequeue_task(rq
, p
, sleep
);
1303 dec_nr_running(p
, rq
);
1307 * task_curr - is this task currently executing on a CPU?
1308 * @p: the task in question.
1310 inline int task_curr(const struct task_struct
*p
)
1312 return cpu_curr(task_cpu(p
)) == p
;
1315 /* Used instead of source_load when we know the type == 0 */
1316 unsigned long weighted_cpuload(const int cpu
)
1318 return cpu_rq(cpu
)->load
.weight
;
1321 static inline void __set_task_cpu(struct task_struct
*p
, unsigned int cpu
)
1323 set_task_cfs_rq(p
, cpu
);
1326 * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1327 * successfuly executed on another CPU. We must ensure that updates of
1328 * per-task data have been completed by this moment.
1331 task_thread_info(p
)->cpu
= cpu
;
1335 static inline void check_class_changed(struct rq
*rq
, struct task_struct
*p
,
1336 const struct sched_class
*prev_class
,
1337 int oldprio
, int running
)
1339 if (prev_class
!= p
->sched_class
) {
1340 if (prev_class
->switched_from
)
1341 prev_class
->switched_from(rq
, p
, running
);
1342 p
->sched_class
->switched_to(rq
, p
, running
);
1344 p
->sched_class
->prio_changed(rq
, p
, oldprio
, running
);
1350 * Is this task likely cache-hot:
1353 task_hot(struct task_struct
*p
, u64 now
, struct sched_domain
*sd
)
1357 if (p
->sched_class
!= &fair_sched_class
)
1360 if (sysctl_sched_migration_cost
== -1)
1362 if (sysctl_sched_migration_cost
== 0)
1365 delta
= now
- p
->se
.exec_start
;
1367 return delta
< (s64
)sysctl_sched_migration_cost
;
1371 void set_task_cpu(struct task_struct
*p
, unsigned int new_cpu
)
1373 int old_cpu
= task_cpu(p
);
1374 struct rq
*old_rq
= cpu_rq(old_cpu
), *new_rq
= cpu_rq(new_cpu
);
1375 struct cfs_rq
*old_cfsrq
= task_cfs_rq(p
),
1376 *new_cfsrq
= cpu_cfs_rq(old_cfsrq
, new_cpu
);
1379 clock_offset
= old_rq
->clock
- new_rq
->clock
;
1381 #ifdef CONFIG_SCHEDSTATS
1382 if (p
->se
.wait_start
)
1383 p
->se
.wait_start
-= clock_offset
;
1384 if (p
->se
.sleep_start
)
1385 p
->se
.sleep_start
-= clock_offset
;
1386 if (p
->se
.block_start
)
1387 p
->se
.block_start
-= clock_offset
;
1388 if (old_cpu
!= new_cpu
) {
1389 schedstat_inc(p
, se
.nr_migrations
);
1390 if (task_hot(p
, old_rq
->clock
, NULL
))
1391 schedstat_inc(p
, se
.nr_forced2_migrations
);
1394 p
->se
.vruntime
-= old_cfsrq
->min_vruntime
-
1395 new_cfsrq
->min_vruntime
;
1397 __set_task_cpu(p
, new_cpu
);
1400 struct migration_req
{
1401 struct list_head list
;
1403 struct task_struct
*task
;
1406 struct completion done
;
1410 * The task's runqueue lock must be held.
1411 * Returns true if you have to wait for migration thread.
1414 migrate_task(struct task_struct
*p
, int dest_cpu
, struct migration_req
*req
)
1416 struct rq
*rq
= task_rq(p
);
1419 * If the task is not on a runqueue (and not running), then
1420 * it is sufficient to simply update the task's cpu field.
1422 if (!p
->se
.on_rq
&& !task_running(rq
, p
)) {
1423 set_task_cpu(p
, dest_cpu
);
1427 init_completion(&req
->done
);
1429 req
->dest_cpu
= dest_cpu
;
1430 list_add(&req
->list
, &rq
->migration_queue
);
1436 * wait_task_inactive - wait for a thread to unschedule.
1438 * The caller must ensure that the task *will* unschedule sometime soon,
1439 * else this function might spin for a *long* time. This function can't
1440 * be called with interrupts off, or it may introduce deadlock with
1441 * smp_call_function() if an IPI is sent by the same process we are
1442 * waiting to become inactive.
1444 void wait_task_inactive(struct task_struct
*p
)
1446 unsigned long flags
;
1452 * We do the initial early heuristics without holding
1453 * any task-queue locks at all. We'll only try to get
1454 * the runqueue lock when things look like they will
1460 * If the task is actively running on another CPU
1461 * still, just relax and busy-wait without holding
1464 * NOTE! Since we don't hold any locks, it's not
1465 * even sure that "rq" stays as the right runqueue!
1466 * But we don't care, since "task_running()" will
1467 * return false if the runqueue has changed and p
1468 * is actually now running somewhere else!
1470 while (task_running(rq
, p
))
1474 * Ok, time to look more closely! We need the rq
1475 * lock now, to be *sure*. If we're wrong, we'll
1476 * just go back and repeat.
1478 rq
= task_rq_lock(p
, &flags
);
1479 running
= task_running(rq
, p
);
1480 on_rq
= p
->se
.on_rq
;
1481 task_rq_unlock(rq
, &flags
);
1484 * Was it really running after all now that we
1485 * checked with the proper locks actually held?
1487 * Oops. Go back and try again..
1489 if (unlikely(running
)) {
1495 * It's not enough that it's not actively running,
1496 * it must be off the runqueue _entirely_, and not
1499 * So if it wa still runnable (but just not actively
1500 * running right now), it's preempted, and we should
1501 * yield - it could be a while.
1503 if (unlikely(on_rq
)) {
1504 schedule_timeout_uninterruptible(1);
1509 * Ahh, all good. It wasn't running, and it wasn't
1510 * runnable, which means that it will never become
1511 * running in the future either. We're all done!
1518 * kick_process - kick a running thread to enter/exit the kernel
1519 * @p: the to-be-kicked thread
1521 * Cause a process which is running on another CPU to enter
1522 * kernel-mode, without any delay. (to get signals handled.)
1524 * NOTE: this function doesnt have to take the runqueue lock,
1525 * because all it wants to ensure is that the remote task enters
1526 * the kernel. If the IPI races and the task has been migrated
1527 * to another CPU then no harm is done and the purpose has been
1530 void kick_process(struct task_struct
*p
)
1536 if ((cpu
!= smp_processor_id()) && task_curr(p
))
1537 smp_send_reschedule(cpu
);
1542 * Return a low guess at the load of a migration-source cpu weighted
1543 * according to the scheduling class and "nice" value.
1545 * We want to under-estimate the load of migration sources, to
1546 * balance conservatively.
1548 static unsigned long source_load(int cpu
, int type
)
1550 struct rq
*rq
= cpu_rq(cpu
);
1551 unsigned long total
= weighted_cpuload(cpu
);
1556 return min(rq
->cpu_load
[type
-1], total
);
1560 * Return a high guess at the load of a migration-target cpu weighted
1561 * according to the scheduling class and "nice" value.
1563 static unsigned long target_load(int cpu
, int type
)
1565 struct rq
*rq
= cpu_rq(cpu
);
1566 unsigned long total
= weighted_cpuload(cpu
);
1571 return max(rq
->cpu_load
[type
-1], total
);
1575 * Return the average load per task on the cpu's run queue
1577 static unsigned long cpu_avg_load_per_task(int cpu
)
1579 struct rq
*rq
= cpu_rq(cpu
);
1580 unsigned long total
= weighted_cpuload(cpu
);
1581 unsigned long n
= rq
->nr_running
;
1583 return n
? total
/ n
: SCHED_LOAD_SCALE
;
1587 * find_idlest_group finds and returns the least busy CPU group within the
1590 static struct sched_group
*
1591 find_idlest_group(struct sched_domain
*sd
, struct task_struct
*p
, int this_cpu
)
1593 struct sched_group
*idlest
= NULL
, *this = NULL
, *group
= sd
->groups
;
1594 unsigned long min_load
= ULONG_MAX
, this_load
= 0;
1595 int load_idx
= sd
->forkexec_idx
;
1596 int imbalance
= 100 + (sd
->imbalance_pct
-100)/2;
1599 unsigned long load
, avg_load
;
1603 /* Skip over this group if it has no CPUs allowed */
1604 if (!cpus_intersects(group
->cpumask
, p
->cpus_allowed
))
1607 local_group
= cpu_isset(this_cpu
, group
->cpumask
);
1609 /* Tally up the load of all CPUs in the group */
1612 for_each_cpu_mask(i
, group
->cpumask
) {
1613 /* Bias balancing toward cpus of our domain */
1615 load
= source_load(i
, load_idx
);
1617 load
= target_load(i
, load_idx
);
1622 /* Adjust by relative CPU power of the group */
1623 avg_load
= sg_div_cpu_power(group
,
1624 avg_load
* SCHED_LOAD_SCALE
);
1627 this_load
= avg_load
;
1629 } else if (avg_load
< min_load
) {
1630 min_load
= avg_load
;
1633 } while (group
= group
->next
, group
!= sd
->groups
);
1635 if (!idlest
|| 100*this_load
< imbalance
*min_load
)
1641 * find_idlest_cpu - find the idlest cpu among the cpus in group.
1644 find_idlest_cpu(struct sched_group
*group
, struct task_struct
*p
, int this_cpu
)
1647 unsigned long load
, min_load
= ULONG_MAX
;
1651 /* Traverse only the allowed CPUs */
1652 cpus_and(tmp
, group
->cpumask
, p
->cpus_allowed
);
1654 for_each_cpu_mask(i
, tmp
) {
1655 load
= weighted_cpuload(i
);
1657 if (load
< min_load
|| (load
== min_load
&& i
== this_cpu
)) {
1667 * sched_balance_self: balance the current task (running on cpu) in domains
1668 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1671 * Balance, ie. select the least loaded group.
1673 * Returns the target CPU number, or the same CPU if no balancing is needed.
1675 * preempt must be disabled.
1677 static int sched_balance_self(int cpu
, int flag
)
1679 struct task_struct
*t
= current
;
1680 struct sched_domain
*tmp
, *sd
= NULL
;
1682 for_each_domain(cpu
, tmp
) {
1684 * If power savings logic is enabled for a domain, stop there.
1686 if (tmp
->flags
& SD_POWERSAVINGS_BALANCE
)
1688 if (tmp
->flags
& flag
)
1694 struct sched_group
*group
;
1695 int new_cpu
, weight
;
1697 if (!(sd
->flags
& flag
)) {
1703 group
= find_idlest_group(sd
, t
, cpu
);
1709 new_cpu
= find_idlest_cpu(group
, t
, cpu
);
1710 if (new_cpu
== -1 || new_cpu
== cpu
) {
1711 /* Now try balancing at a lower domain level of cpu */
1716 /* Now try balancing at a lower domain level of new_cpu */
1719 weight
= cpus_weight(span
);
1720 for_each_domain(cpu
, tmp
) {
1721 if (weight
<= cpus_weight(tmp
->span
))
1723 if (tmp
->flags
& flag
)
1726 /* while loop will break here if sd == NULL */
1732 #endif /* CONFIG_SMP */
1735 * try_to_wake_up - wake up a thread
1736 * @p: the to-be-woken-up thread
1737 * @state: the mask of task states that can be woken
1738 * @sync: do a synchronous wakeup?
1740 * Put it on the run-queue if it's not already there. The "current"
1741 * thread is always on the run-queue (except when the actual
1742 * re-schedule is in progress), and as such you're allowed to do
1743 * the simpler "current->state = TASK_RUNNING" to mark yourself
1744 * runnable without the overhead of this.
1746 * returns failure only if the task is already active.
1748 static int try_to_wake_up(struct task_struct
*p
, unsigned int state
, int sync
)
1750 int cpu
, orig_cpu
, this_cpu
, success
= 0;
1751 unsigned long flags
;
1755 rq
= task_rq_lock(p
, &flags
);
1756 old_state
= p
->state
;
1757 if (!(old_state
& state
))
1765 this_cpu
= smp_processor_id();
1768 if (unlikely(task_running(rq
, p
)))
1771 cpu
= p
->sched_class
->select_task_rq(p
, sync
);
1772 if (cpu
!= orig_cpu
) {
1773 set_task_cpu(p
, cpu
);
1774 task_rq_unlock(rq
, &flags
);
1775 /* might preempt at this point */
1776 rq
= task_rq_lock(p
, &flags
);
1777 old_state
= p
->state
;
1778 if (!(old_state
& state
))
1783 this_cpu
= smp_processor_id();
1787 #ifdef CONFIG_SCHEDSTATS
1788 schedstat_inc(rq
, ttwu_count
);
1789 if (cpu
== this_cpu
)
1790 schedstat_inc(rq
, ttwu_local
);
1792 struct sched_domain
*sd
;
1793 for_each_domain(this_cpu
, sd
) {
1794 if (cpu_isset(cpu
, sd
->span
)) {
1795 schedstat_inc(sd
, ttwu_wake_remote
);
1803 #endif /* CONFIG_SMP */
1804 schedstat_inc(p
, se
.nr_wakeups
);
1806 schedstat_inc(p
, se
.nr_wakeups_sync
);
1807 if (orig_cpu
!= cpu
)
1808 schedstat_inc(p
, se
.nr_wakeups_migrate
);
1809 if (cpu
== this_cpu
)
1810 schedstat_inc(p
, se
.nr_wakeups_local
);
1812 schedstat_inc(p
, se
.nr_wakeups_remote
);
1813 update_rq_clock(rq
);
1814 activate_task(rq
, p
, 1);
1815 check_preempt_curr(rq
, p
);
1819 p
->state
= TASK_RUNNING
;
1821 if (p
->sched_class
->task_wake_up
)
1822 p
->sched_class
->task_wake_up(rq
, p
);
1825 task_rq_unlock(rq
, &flags
);
1830 int fastcall
wake_up_process(struct task_struct
*p
)
1832 return try_to_wake_up(p
, TASK_STOPPED
| TASK_TRACED
|
1833 TASK_INTERRUPTIBLE
| TASK_UNINTERRUPTIBLE
, 0);
1835 EXPORT_SYMBOL(wake_up_process
);
1837 int fastcall
wake_up_state(struct task_struct
*p
, unsigned int state
)
1839 return try_to_wake_up(p
, state
, 0);
1843 * Perform scheduler related setup for a newly forked process p.
1844 * p is forked by current.
1846 * __sched_fork() is basic setup used by init_idle() too:
1848 static void __sched_fork(struct task_struct
*p
)
1850 p
->se
.exec_start
= 0;
1851 p
->se
.sum_exec_runtime
= 0;
1852 p
->se
.prev_sum_exec_runtime
= 0;
1854 #ifdef CONFIG_SCHEDSTATS
1855 p
->se
.wait_start
= 0;
1856 p
->se
.sum_sleep_runtime
= 0;
1857 p
->se
.sleep_start
= 0;
1858 p
->se
.block_start
= 0;
1859 p
->se
.sleep_max
= 0;
1860 p
->se
.block_max
= 0;
1862 p
->se
.slice_max
= 0;
1866 INIT_LIST_HEAD(&p
->rt
.run_list
);
1869 #ifdef CONFIG_PREEMPT_NOTIFIERS
1870 INIT_HLIST_HEAD(&p
->preempt_notifiers
);
1874 * We mark the process as running here, but have not actually
1875 * inserted it onto the runqueue yet. This guarantees that
1876 * nobody will actually run it, and a signal or other external
1877 * event cannot wake it up and insert it on the runqueue either.
1879 p
->state
= TASK_RUNNING
;
1883 * fork()/clone()-time setup:
1885 void sched_fork(struct task_struct
*p
, int clone_flags
)
1887 int cpu
= get_cpu();
1892 cpu
= sched_balance_self(cpu
, SD_BALANCE_FORK
);
1894 set_task_cpu(p
, cpu
);
1897 * Make sure we do not leak PI boosting priority to the child:
1899 p
->prio
= current
->normal_prio
;
1900 if (!rt_prio(p
->prio
))
1901 p
->sched_class
= &fair_sched_class
;
1903 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
1904 if (likely(sched_info_on()))
1905 memset(&p
->sched_info
, 0, sizeof(p
->sched_info
));
1907 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
1910 #ifdef CONFIG_PREEMPT
1911 /* Want to start with kernel preemption disabled. */
1912 task_thread_info(p
)->preempt_count
= 1;
1918 * wake_up_new_task - wake up a newly created task for the first time.
1920 * This function will do some initial scheduler statistics housekeeping
1921 * that must be done for every newly created context, then puts the task
1922 * on the runqueue and wakes it.
1924 void fastcall
wake_up_new_task(struct task_struct
*p
, unsigned long clone_flags
)
1926 unsigned long flags
;
1929 rq
= task_rq_lock(p
, &flags
);
1930 BUG_ON(p
->state
!= TASK_RUNNING
);
1931 update_rq_clock(rq
);
1933 p
->prio
= effective_prio(p
);
1935 if (!p
->sched_class
->task_new
|| !current
->se
.on_rq
) {
1936 activate_task(rq
, p
, 0);
1939 * Let the scheduling class do new task startup
1940 * management (if any):
1942 p
->sched_class
->task_new(rq
, p
);
1943 inc_nr_running(p
, rq
);
1945 check_preempt_curr(rq
, p
);
1947 if (p
->sched_class
->task_wake_up
)
1948 p
->sched_class
->task_wake_up(rq
, p
);
1950 task_rq_unlock(rq
, &flags
);
1953 #ifdef CONFIG_PREEMPT_NOTIFIERS
1956 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
1957 * @notifier: notifier struct to register
1959 void preempt_notifier_register(struct preempt_notifier
*notifier
)
1961 hlist_add_head(¬ifier
->link
, ¤t
->preempt_notifiers
);
1963 EXPORT_SYMBOL_GPL(preempt_notifier_register
);
1966 * preempt_notifier_unregister - no longer interested in preemption notifications
1967 * @notifier: notifier struct to unregister
1969 * This is safe to call from within a preemption notifier.
1971 void preempt_notifier_unregister(struct preempt_notifier
*notifier
)
1973 hlist_del(¬ifier
->link
);
1975 EXPORT_SYMBOL_GPL(preempt_notifier_unregister
);
1977 static void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
1979 struct preempt_notifier
*notifier
;
1980 struct hlist_node
*node
;
1982 hlist_for_each_entry(notifier
, node
, &curr
->preempt_notifiers
, link
)
1983 notifier
->ops
->sched_in(notifier
, raw_smp_processor_id());
1987 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
1988 struct task_struct
*next
)
1990 struct preempt_notifier
*notifier
;
1991 struct hlist_node
*node
;
1993 hlist_for_each_entry(notifier
, node
, &curr
->preempt_notifiers
, link
)
1994 notifier
->ops
->sched_out(notifier
, next
);
1999 static void fire_sched_in_preempt_notifiers(struct task_struct
*curr
)
2004 fire_sched_out_preempt_notifiers(struct task_struct
*curr
,
2005 struct task_struct
*next
)
2012 * prepare_task_switch - prepare to switch tasks
2013 * @rq: the runqueue preparing to switch
2014 * @prev: the current task that is being switched out
2015 * @next: the task we are going to switch to.
2017 * This is called with the rq lock held and interrupts off. It must
2018 * be paired with a subsequent finish_task_switch after the context
2021 * prepare_task_switch sets up locking and calls architecture specific
2025 prepare_task_switch(struct rq
*rq
, struct task_struct
*prev
,
2026 struct task_struct
*next
)
2028 fire_sched_out_preempt_notifiers(prev
, next
);
2029 prepare_lock_switch(rq
, next
);
2030 prepare_arch_switch(next
);
2034 * finish_task_switch - clean up after a task-switch
2035 * @rq: runqueue associated with task-switch
2036 * @prev: the thread we just switched away from.
2038 * finish_task_switch must be called after the context switch, paired
2039 * with a prepare_task_switch call before the context switch.
2040 * finish_task_switch will reconcile locking set up by prepare_task_switch,
2041 * and do any other architecture-specific cleanup actions.
2043 * Note that we may have delayed dropping an mm in context_switch(). If
2044 * so, we finish that here outside of the runqueue lock. (Doing it
2045 * with the lock held can cause deadlocks; see schedule() for
2048 static void finish_task_switch(struct rq
*rq
, struct task_struct
*prev
)
2049 __releases(rq
->lock
)
2051 struct mm_struct
*mm
= rq
->prev_mm
;
2057 * A task struct has one reference for the use as "current".
2058 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2059 * schedule one last time. The schedule call will never return, and
2060 * the scheduled task must drop that reference.
2061 * The test for TASK_DEAD must occur while the runqueue locks are
2062 * still held, otherwise prev could be scheduled on another cpu, die
2063 * there before we look at prev->state, and then the reference would
2065 * Manfred Spraul <manfred@colorfullife.com>
2067 prev_state
= prev
->state
;
2068 finish_arch_switch(prev
);
2069 finish_lock_switch(rq
, prev
);
2071 if (current
->sched_class
->post_schedule
)
2072 current
->sched_class
->post_schedule(rq
);
2075 fire_sched_in_preempt_notifiers(current
);
2078 if (unlikely(prev_state
== TASK_DEAD
)) {
2080 * Remove function-return probe instances associated with this
2081 * task and put them back on the free list.
2083 kprobe_flush_task(prev
);
2084 put_task_struct(prev
);
2089 * schedule_tail - first thing a freshly forked thread must call.
2090 * @prev: the thread we just switched away from.
2092 asmlinkage
void schedule_tail(struct task_struct
*prev
)
2093 __releases(rq
->lock
)
2095 struct rq
*rq
= this_rq();
2097 finish_task_switch(rq
, prev
);
2098 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2099 /* In this case, finish_task_switch does not reenable preemption */
2102 if (current
->set_child_tid
)
2103 put_user(task_pid_vnr(current
), current
->set_child_tid
);
2107 * context_switch - switch to the new MM and the new
2108 * thread's register state.
2111 context_switch(struct rq
*rq
, struct task_struct
*prev
,
2112 struct task_struct
*next
)
2114 struct mm_struct
*mm
, *oldmm
;
2116 prepare_task_switch(rq
, prev
, next
);
2118 oldmm
= prev
->active_mm
;
2120 * For paravirt, this is coupled with an exit in switch_to to
2121 * combine the page table reload and the switch backend into
2124 arch_enter_lazy_cpu_mode();
2126 if (unlikely(!mm
)) {
2127 next
->active_mm
= oldmm
;
2128 atomic_inc(&oldmm
->mm_count
);
2129 enter_lazy_tlb(oldmm
, next
);
2131 switch_mm(oldmm
, mm
, next
);
2133 if (unlikely(!prev
->mm
)) {
2134 prev
->active_mm
= NULL
;
2135 rq
->prev_mm
= oldmm
;
2138 * Since the runqueue lock will be released by the next
2139 * task (which is an invalid locking op but in the case
2140 * of the scheduler it's an obvious special-case), so we
2141 * do an early lockdep release here:
2143 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2144 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
2147 /* Here we just switch the register state and the stack. */
2148 switch_to(prev
, next
, prev
);
2152 * this_rq must be evaluated again because prev may have moved
2153 * CPUs since it called schedule(), thus the 'rq' on its stack
2154 * frame will be invalid.
2156 finish_task_switch(this_rq(), prev
);
2160 * nr_running, nr_uninterruptible and nr_context_switches:
2162 * externally visible scheduler statistics: current number of runnable
2163 * threads, current number of uninterruptible-sleeping threads, total
2164 * number of context switches performed since bootup.
2166 unsigned long nr_running(void)
2168 unsigned long i
, sum
= 0;
2170 for_each_online_cpu(i
)
2171 sum
+= cpu_rq(i
)->nr_running
;
2176 unsigned long nr_uninterruptible(void)
2178 unsigned long i
, sum
= 0;
2180 for_each_possible_cpu(i
)
2181 sum
+= cpu_rq(i
)->nr_uninterruptible
;
2184 * Since we read the counters lockless, it might be slightly
2185 * inaccurate. Do not allow it to go below zero though:
2187 if (unlikely((long)sum
< 0))
2193 unsigned long long nr_context_switches(void)
2196 unsigned long long sum
= 0;
2198 for_each_possible_cpu(i
)
2199 sum
+= cpu_rq(i
)->nr_switches
;
2204 unsigned long nr_iowait(void)
2206 unsigned long i
, sum
= 0;
2208 for_each_possible_cpu(i
)
2209 sum
+= atomic_read(&cpu_rq(i
)->nr_iowait
);
2214 unsigned long nr_active(void)
2216 unsigned long i
, running
= 0, uninterruptible
= 0;
2218 for_each_online_cpu(i
) {
2219 running
+= cpu_rq(i
)->nr_running
;
2220 uninterruptible
+= cpu_rq(i
)->nr_uninterruptible
;
2223 if (unlikely((long)uninterruptible
< 0))
2224 uninterruptible
= 0;
2226 return running
+ uninterruptible
;
2230 * Update rq->cpu_load[] statistics. This function is usually called every
2231 * scheduler tick (TICK_NSEC).
2233 static void update_cpu_load(struct rq
*this_rq
)
2235 unsigned long this_load
= this_rq
->load
.weight
;
2238 this_rq
->nr_load_updates
++;
2240 /* Update our load: */
2241 for (i
= 0, scale
= 1; i
< CPU_LOAD_IDX_MAX
; i
++, scale
+= scale
) {
2242 unsigned long old_load
, new_load
;
2244 /* scale is effectively 1 << i now, and >> i divides by scale */
2246 old_load
= this_rq
->cpu_load
[i
];
2247 new_load
= this_load
;
2249 * Round up the averaging division if load is increasing. This
2250 * prevents us from getting stuck on 9 if the load is 10, for
2253 if (new_load
> old_load
)
2254 new_load
+= scale
-1;
2255 this_rq
->cpu_load
[i
] = (old_load
*(scale
-1) + new_load
) >> i
;
2262 * double_rq_lock - safely lock two runqueues
2264 * Note this does not disable interrupts like task_rq_lock,
2265 * you need to do so manually before calling.
2267 static void double_rq_lock(struct rq
*rq1
, struct rq
*rq2
)
2268 __acquires(rq1
->lock
)
2269 __acquires(rq2
->lock
)
2271 BUG_ON(!irqs_disabled());
2273 spin_lock(&rq1
->lock
);
2274 __acquire(rq2
->lock
); /* Fake it out ;) */
2277 spin_lock(&rq1
->lock
);
2278 spin_lock(&rq2
->lock
);
2280 spin_lock(&rq2
->lock
);
2281 spin_lock(&rq1
->lock
);
2284 update_rq_clock(rq1
);
2285 update_rq_clock(rq2
);
2289 * double_rq_unlock - safely unlock two runqueues
2291 * Note this does not restore interrupts like task_rq_unlock,
2292 * you need to do so manually after calling.
2294 static void double_rq_unlock(struct rq
*rq1
, struct rq
*rq2
)
2295 __releases(rq1
->lock
)
2296 __releases(rq2
->lock
)
2298 spin_unlock(&rq1
->lock
);
2300 spin_unlock(&rq2
->lock
);
2302 __release(rq2
->lock
);
2306 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2308 static int double_lock_balance(struct rq
*this_rq
, struct rq
*busiest
)
2309 __releases(this_rq
->lock
)
2310 __acquires(busiest
->lock
)
2311 __acquires(this_rq
->lock
)
2315 if (unlikely(!irqs_disabled())) {
2316 /* printk() doesn't work good under rq->lock */
2317 spin_unlock(&this_rq
->lock
);
2320 if (unlikely(!spin_trylock(&busiest
->lock
))) {
2321 if (busiest
< this_rq
) {
2322 spin_unlock(&this_rq
->lock
);
2323 spin_lock(&busiest
->lock
);
2324 spin_lock(&this_rq
->lock
);
2327 spin_lock(&busiest
->lock
);
2333 * If dest_cpu is allowed for this process, migrate the task to it.
2334 * This is accomplished by forcing the cpu_allowed mask to only
2335 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2336 * the cpu_allowed mask is restored.
2338 static void sched_migrate_task(struct task_struct
*p
, int dest_cpu
)
2340 struct migration_req req
;
2341 unsigned long flags
;
2344 rq
= task_rq_lock(p
, &flags
);
2345 if (!cpu_isset(dest_cpu
, p
->cpus_allowed
)
2346 || unlikely(cpu_is_offline(dest_cpu
)))
2349 /* force the process onto the specified CPU */
2350 if (migrate_task(p
, dest_cpu
, &req
)) {
2351 /* Need to wait for migration thread (might exit: take ref). */
2352 struct task_struct
*mt
= rq
->migration_thread
;
2354 get_task_struct(mt
);
2355 task_rq_unlock(rq
, &flags
);
2356 wake_up_process(mt
);
2357 put_task_struct(mt
);
2358 wait_for_completion(&req
.done
);
2363 task_rq_unlock(rq
, &flags
);
2367 * sched_exec - execve() is a valuable balancing opportunity, because at
2368 * this point the task has the smallest effective memory and cache footprint.
2370 void sched_exec(void)
2372 int new_cpu
, this_cpu
= get_cpu();
2373 new_cpu
= sched_balance_self(this_cpu
, SD_BALANCE_EXEC
);
2375 if (new_cpu
!= this_cpu
)
2376 sched_migrate_task(current
, new_cpu
);
2380 * pull_task - move a task from a remote runqueue to the local runqueue.
2381 * Both runqueues must be locked.
2383 static void pull_task(struct rq
*src_rq
, struct task_struct
*p
,
2384 struct rq
*this_rq
, int this_cpu
)
2386 deactivate_task(src_rq
, p
, 0);
2387 set_task_cpu(p
, this_cpu
);
2388 activate_task(this_rq
, p
, 0);
2390 * Note that idle threads have a prio of MAX_PRIO, for this test
2391 * to be always true for them.
2393 check_preempt_curr(this_rq
, p
);
2397 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2400 int can_migrate_task(struct task_struct
*p
, struct rq
*rq
, int this_cpu
,
2401 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2405 * We do not migrate tasks that are:
2406 * 1) running (obviously), or
2407 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2408 * 3) are cache-hot on their current CPU.
2410 if (!cpu_isset(this_cpu
, p
->cpus_allowed
)) {
2411 schedstat_inc(p
, se
.nr_failed_migrations_affine
);
2416 if (task_running(rq
, p
)) {
2417 schedstat_inc(p
, se
.nr_failed_migrations_running
);
2422 * Aggressive migration if:
2423 * 1) task is cache cold, or
2424 * 2) too many balance attempts have failed.
2427 if (!task_hot(p
, rq
->clock
, sd
) ||
2428 sd
->nr_balance_failed
> sd
->cache_nice_tries
) {
2429 #ifdef CONFIG_SCHEDSTATS
2430 if (task_hot(p
, rq
->clock
, sd
)) {
2431 schedstat_inc(sd
, lb_hot_gained
[idle
]);
2432 schedstat_inc(p
, se
.nr_forced_migrations
);
2438 if (task_hot(p
, rq
->clock
, sd
)) {
2439 schedstat_inc(p
, se
.nr_failed_migrations_hot
);
2445 static unsigned long
2446 balance_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2447 unsigned long max_load_move
, struct sched_domain
*sd
,
2448 enum cpu_idle_type idle
, int *all_pinned
,
2449 int *this_best_prio
, struct rq_iterator
*iterator
)
2451 int loops
= 0, pulled
= 0, pinned
= 0, skip_for_load
;
2452 struct task_struct
*p
;
2453 long rem_load_move
= max_load_move
;
2455 if (max_load_move
== 0)
2461 * Start the load-balancing iterator:
2463 p
= iterator
->start(iterator
->arg
);
2465 if (!p
|| loops
++ > sysctl_sched_nr_migrate
)
2468 * To help distribute high priority tasks across CPUs we don't
2469 * skip a task if it will be the highest priority task (i.e. smallest
2470 * prio value) on its new queue regardless of its load weight
2472 skip_for_load
= (p
->se
.load
.weight
>> 1) > rem_load_move
+
2473 SCHED_LOAD_SCALE_FUZZ
;
2474 if ((skip_for_load
&& p
->prio
>= *this_best_prio
) ||
2475 !can_migrate_task(p
, busiest
, this_cpu
, sd
, idle
, &pinned
)) {
2476 p
= iterator
->next(iterator
->arg
);
2480 pull_task(busiest
, p
, this_rq
, this_cpu
);
2482 rem_load_move
-= p
->se
.load
.weight
;
2485 * We only want to steal up to the prescribed amount of weighted load.
2487 if (rem_load_move
> 0) {
2488 if (p
->prio
< *this_best_prio
)
2489 *this_best_prio
= p
->prio
;
2490 p
= iterator
->next(iterator
->arg
);
2495 * Right now, this is one of only two places pull_task() is called,
2496 * so we can safely collect pull_task() stats here rather than
2497 * inside pull_task().
2499 schedstat_add(sd
, lb_gained
[idle
], pulled
);
2502 *all_pinned
= pinned
;
2504 return max_load_move
- rem_load_move
;
2508 * move_tasks tries to move up to max_load_move weighted load from busiest to
2509 * this_rq, as part of a balancing operation within domain "sd".
2510 * Returns 1 if successful and 0 otherwise.
2512 * Called with both runqueues locked.
2514 static int move_tasks(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2515 unsigned long max_load_move
,
2516 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2519 const struct sched_class
*class = sched_class_highest
;
2520 unsigned long total_load_moved
= 0;
2521 int this_best_prio
= this_rq
->curr
->prio
;
2525 class->load_balance(this_rq
, this_cpu
, busiest
,
2526 max_load_move
- total_load_moved
,
2527 sd
, idle
, all_pinned
, &this_best_prio
);
2528 class = class->next
;
2529 } while (class && max_load_move
> total_load_moved
);
2531 return total_load_moved
> 0;
2535 iter_move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2536 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2537 struct rq_iterator
*iterator
)
2539 struct task_struct
*p
= iterator
->start(iterator
->arg
);
2543 if (can_migrate_task(p
, busiest
, this_cpu
, sd
, idle
, &pinned
)) {
2544 pull_task(busiest
, p
, this_rq
, this_cpu
);
2546 * Right now, this is only the second place pull_task()
2547 * is called, so we can safely collect pull_task()
2548 * stats here rather than inside pull_task().
2550 schedstat_inc(sd
, lb_gained
[idle
]);
2554 p
= iterator
->next(iterator
->arg
);
2561 * move_one_task tries to move exactly one task from busiest to this_rq, as
2562 * part of active balancing operations within "domain".
2563 * Returns 1 if successful and 0 otherwise.
2565 * Called with both runqueues locked.
2567 static int move_one_task(struct rq
*this_rq
, int this_cpu
, struct rq
*busiest
,
2568 struct sched_domain
*sd
, enum cpu_idle_type idle
)
2570 const struct sched_class
*class;
2572 for (class = sched_class_highest
; class; class = class->next
)
2573 if (class->move_one_task(this_rq
, this_cpu
, busiest
, sd
, idle
))
2580 * find_busiest_group finds and returns the busiest CPU group within the
2581 * domain. It calculates and returns the amount of weighted load which
2582 * should be moved to restore balance via the imbalance parameter.
2584 static struct sched_group
*
2585 find_busiest_group(struct sched_domain
*sd
, int this_cpu
,
2586 unsigned long *imbalance
, enum cpu_idle_type idle
,
2587 int *sd_idle
, cpumask_t
*cpus
, int *balance
)
2589 struct sched_group
*busiest
= NULL
, *this = NULL
, *group
= sd
->groups
;
2590 unsigned long max_load
, avg_load
, total_load
, this_load
, total_pwr
;
2591 unsigned long max_pull
;
2592 unsigned long busiest_load_per_task
, busiest_nr_running
;
2593 unsigned long this_load_per_task
, this_nr_running
;
2594 int load_idx
, group_imb
= 0;
2595 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2596 int power_savings_balance
= 1;
2597 unsigned long leader_nr_running
= 0, min_load_per_task
= 0;
2598 unsigned long min_nr_running
= ULONG_MAX
;
2599 struct sched_group
*group_min
= NULL
, *group_leader
= NULL
;
2602 max_load
= this_load
= total_load
= total_pwr
= 0;
2603 busiest_load_per_task
= busiest_nr_running
= 0;
2604 this_load_per_task
= this_nr_running
= 0;
2605 if (idle
== CPU_NOT_IDLE
)
2606 load_idx
= sd
->busy_idx
;
2607 else if (idle
== CPU_NEWLY_IDLE
)
2608 load_idx
= sd
->newidle_idx
;
2610 load_idx
= sd
->idle_idx
;
2613 unsigned long load
, group_capacity
, max_cpu_load
, min_cpu_load
;
2616 int __group_imb
= 0;
2617 unsigned int balance_cpu
= -1, first_idle_cpu
= 0;
2618 unsigned long sum_nr_running
, sum_weighted_load
;
2620 local_group
= cpu_isset(this_cpu
, group
->cpumask
);
2623 balance_cpu
= first_cpu(group
->cpumask
);
2625 /* Tally up the load of all CPUs in the group */
2626 sum_weighted_load
= sum_nr_running
= avg_load
= 0;
2628 min_cpu_load
= ~0UL;
2630 for_each_cpu_mask(i
, group
->cpumask
) {
2633 if (!cpu_isset(i
, *cpus
))
2638 if (*sd_idle
&& rq
->nr_running
)
2641 /* Bias balancing toward cpus of our domain */
2643 if (idle_cpu(i
) && !first_idle_cpu
) {
2648 load
= target_load(i
, load_idx
);
2650 load
= source_load(i
, load_idx
);
2651 if (load
> max_cpu_load
)
2652 max_cpu_load
= load
;
2653 if (min_cpu_load
> load
)
2654 min_cpu_load
= load
;
2658 sum_nr_running
+= rq
->nr_running
;
2659 sum_weighted_load
+= weighted_cpuload(i
);
2663 * First idle cpu or the first cpu(busiest) in this sched group
2664 * is eligible for doing load balancing at this and above
2665 * domains. In the newly idle case, we will allow all the cpu's
2666 * to do the newly idle load balance.
2668 if (idle
!= CPU_NEWLY_IDLE
&& local_group
&&
2669 balance_cpu
!= this_cpu
&& balance
) {
2674 total_load
+= avg_load
;
2675 total_pwr
+= group
->__cpu_power
;
2677 /* Adjust by relative CPU power of the group */
2678 avg_load
= sg_div_cpu_power(group
,
2679 avg_load
* SCHED_LOAD_SCALE
);
2681 if ((max_cpu_load
- min_cpu_load
) > SCHED_LOAD_SCALE
)
2684 group_capacity
= group
->__cpu_power
/ SCHED_LOAD_SCALE
;
2687 this_load
= avg_load
;
2689 this_nr_running
= sum_nr_running
;
2690 this_load_per_task
= sum_weighted_load
;
2691 } else if (avg_load
> max_load
&&
2692 (sum_nr_running
> group_capacity
|| __group_imb
)) {
2693 max_load
= avg_load
;
2695 busiest_nr_running
= sum_nr_running
;
2696 busiest_load_per_task
= sum_weighted_load
;
2697 group_imb
= __group_imb
;
2700 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2702 * Busy processors will not participate in power savings
2705 if (idle
== CPU_NOT_IDLE
||
2706 !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
2710 * If the local group is idle or completely loaded
2711 * no need to do power savings balance at this domain
2713 if (local_group
&& (this_nr_running
>= group_capacity
||
2715 power_savings_balance
= 0;
2718 * If a group is already running at full capacity or idle,
2719 * don't include that group in power savings calculations
2721 if (!power_savings_balance
|| sum_nr_running
>= group_capacity
2726 * Calculate the group which has the least non-idle load.
2727 * This is the group from where we need to pick up the load
2730 if ((sum_nr_running
< min_nr_running
) ||
2731 (sum_nr_running
== min_nr_running
&&
2732 first_cpu(group
->cpumask
) <
2733 first_cpu(group_min
->cpumask
))) {
2735 min_nr_running
= sum_nr_running
;
2736 min_load_per_task
= sum_weighted_load
/
2741 * Calculate the group which is almost near its
2742 * capacity but still has some space to pick up some load
2743 * from other group and save more power
2745 if (sum_nr_running
<= group_capacity
- 1) {
2746 if (sum_nr_running
> leader_nr_running
||
2747 (sum_nr_running
== leader_nr_running
&&
2748 first_cpu(group
->cpumask
) >
2749 first_cpu(group_leader
->cpumask
))) {
2750 group_leader
= group
;
2751 leader_nr_running
= sum_nr_running
;
2756 group
= group
->next
;
2757 } while (group
!= sd
->groups
);
2759 if (!busiest
|| this_load
>= max_load
|| busiest_nr_running
== 0)
2762 avg_load
= (SCHED_LOAD_SCALE
* total_load
) / total_pwr
;
2764 if (this_load
>= avg_load
||
2765 100*max_load
<= sd
->imbalance_pct
*this_load
)
2768 busiest_load_per_task
/= busiest_nr_running
;
2770 busiest_load_per_task
= min(busiest_load_per_task
, avg_load
);
2773 * We're trying to get all the cpus to the average_load, so we don't
2774 * want to push ourselves above the average load, nor do we wish to
2775 * reduce the max loaded cpu below the average load, as either of these
2776 * actions would just result in more rebalancing later, and ping-pong
2777 * tasks around. Thus we look for the minimum possible imbalance.
2778 * Negative imbalances (*we* are more loaded than anyone else) will
2779 * be counted as no imbalance for these purposes -- we can't fix that
2780 * by pulling tasks to us. Be careful of negative numbers as they'll
2781 * appear as very large values with unsigned longs.
2783 if (max_load
<= busiest_load_per_task
)
2787 * In the presence of smp nice balancing, certain scenarios can have
2788 * max load less than avg load(as we skip the groups at or below
2789 * its cpu_power, while calculating max_load..)
2791 if (max_load
< avg_load
) {
2793 goto small_imbalance
;
2796 /* Don't want to pull so many tasks that a group would go idle */
2797 max_pull
= min(max_load
- avg_load
, max_load
- busiest_load_per_task
);
2799 /* How much load to actually move to equalise the imbalance */
2800 *imbalance
= min(max_pull
* busiest
->__cpu_power
,
2801 (avg_load
- this_load
) * this->__cpu_power
)
2805 * if *imbalance is less than the average load per runnable task
2806 * there is no gaurantee that any tasks will be moved so we'll have
2807 * a think about bumping its value to force at least one task to be
2810 if (*imbalance
< busiest_load_per_task
) {
2811 unsigned long tmp
, pwr_now
, pwr_move
;
2815 pwr_move
= pwr_now
= 0;
2817 if (this_nr_running
) {
2818 this_load_per_task
/= this_nr_running
;
2819 if (busiest_load_per_task
> this_load_per_task
)
2822 this_load_per_task
= SCHED_LOAD_SCALE
;
2824 if (max_load
- this_load
+ SCHED_LOAD_SCALE_FUZZ
>=
2825 busiest_load_per_task
* imbn
) {
2826 *imbalance
= busiest_load_per_task
;
2831 * OK, we don't have enough imbalance to justify moving tasks,
2832 * however we may be able to increase total CPU power used by
2836 pwr_now
+= busiest
->__cpu_power
*
2837 min(busiest_load_per_task
, max_load
);
2838 pwr_now
+= this->__cpu_power
*
2839 min(this_load_per_task
, this_load
);
2840 pwr_now
/= SCHED_LOAD_SCALE
;
2842 /* Amount of load we'd subtract */
2843 tmp
= sg_div_cpu_power(busiest
,
2844 busiest_load_per_task
* SCHED_LOAD_SCALE
);
2846 pwr_move
+= busiest
->__cpu_power
*
2847 min(busiest_load_per_task
, max_load
- tmp
);
2849 /* Amount of load we'd add */
2850 if (max_load
* busiest
->__cpu_power
<
2851 busiest_load_per_task
* SCHED_LOAD_SCALE
)
2852 tmp
= sg_div_cpu_power(this,
2853 max_load
* busiest
->__cpu_power
);
2855 tmp
= sg_div_cpu_power(this,
2856 busiest_load_per_task
* SCHED_LOAD_SCALE
);
2857 pwr_move
+= this->__cpu_power
*
2858 min(this_load_per_task
, this_load
+ tmp
);
2859 pwr_move
/= SCHED_LOAD_SCALE
;
2861 /* Move if we gain throughput */
2862 if (pwr_move
> pwr_now
)
2863 *imbalance
= busiest_load_per_task
;
2869 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2870 if (idle
== CPU_NOT_IDLE
|| !(sd
->flags
& SD_POWERSAVINGS_BALANCE
))
2873 if (this == group_leader
&& group_leader
!= group_min
) {
2874 *imbalance
= min_load_per_task
;
2884 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2887 find_busiest_queue(struct sched_group
*group
, enum cpu_idle_type idle
,
2888 unsigned long imbalance
, cpumask_t
*cpus
)
2890 struct rq
*busiest
= NULL
, *rq
;
2891 unsigned long max_load
= 0;
2894 for_each_cpu_mask(i
, group
->cpumask
) {
2897 if (!cpu_isset(i
, *cpus
))
2901 wl
= weighted_cpuload(i
);
2903 if (rq
->nr_running
== 1 && wl
> imbalance
)
2906 if (wl
> max_load
) {
2916 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2917 * so long as it is large enough.
2919 #define MAX_PINNED_INTERVAL 512
2922 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2923 * tasks if there is an imbalance.
2925 static int load_balance(int this_cpu
, struct rq
*this_rq
,
2926 struct sched_domain
*sd
, enum cpu_idle_type idle
,
2929 int ld_moved
, all_pinned
= 0, active_balance
= 0, sd_idle
= 0;
2930 struct sched_group
*group
;
2931 unsigned long imbalance
;
2933 cpumask_t cpus
= CPU_MASK_ALL
;
2934 unsigned long flags
;
2937 * When power savings policy is enabled for the parent domain, idle
2938 * sibling can pick up load irrespective of busy siblings. In this case,
2939 * let the state of idle sibling percolate up as CPU_IDLE, instead of
2940 * portraying it as CPU_NOT_IDLE.
2942 if (idle
!= CPU_NOT_IDLE
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
2943 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
2946 schedstat_inc(sd
, lb_count
[idle
]);
2949 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, idle
, &sd_idle
,
2956 schedstat_inc(sd
, lb_nobusyg
[idle
]);
2960 busiest
= find_busiest_queue(group
, idle
, imbalance
, &cpus
);
2962 schedstat_inc(sd
, lb_nobusyq
[idle
]);
2966 BUG_ON(busiest
== this_rq
);
2968 schedstat_add(sd
, lb_imbalance
[idle
], imbalance
);
2971 if (busiest
->nr_running
> 1) {
2973 * Attempt to move tasks. If find_busiest_group has found
2974 * an imbalance but busiest->nr_running <= 1, the group is
2975 * still unbalanced. ld_moved simply stays zero, so it is
2976 * correctly treated as an imbalance.
2978 local_irq_save(flags
);
2979 double_rq_lock(this_rq
, busiest
);
2980 ld_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
2981 imbalance
, sd
, idle
, &all_pinned
);
2982 double_rq_unlock(this_rq
, busiest
);
2983 local_irq_restore(flags
);
2986 * some other cpu did the load balance for us.
2988 if (ld_moved
&& this_cpu
!= smp_processor_id())
2989 resched_cpu(this_cpu
);
2991 /* All tasks on this runqueue were pinned by CPU affinity */
2992 if (unlikely(all_pinned
)) {
2993 cpu_clear(cpu_of(busiest
), cpus
);
2994 if (!cpus_empty(cpus
))
3001 schedstat_inc(sd
, lb_failed
[idle
]);
3002 sd
->nr_balance_failed
++;
3004 if (unlikely(sd
->nr_balance_failed
> sd
->cache_nice_tries
+2)) {
3006 spin_lock_irqsave(&busiest
->lock
, flags
);
3008 /* don't kick the migration_thread, if the curr
3009 * task on busiest cpu can't be moved to this_cpu
3011 if (!cpu_isset(this_cpu
, busiest
->curr
->cpus_allowed
)) {
3012 spin_unlock_irqrestore(&busiest
->lock
, flags
);
3014 goto out_one_pinned
;
3017 if (!busiest
->active_balance
) {
3018 busiest
->active_balance
= 1;
3019 busiest
->push_cpu
= this_cpu
;
3022 spin_unlock_irqrestore(&busiest
->lock
, flags
);
3024 wake_up_process(busiest
->migration_thread
);
3027 * We've kicked active balancing, reset the failure
3030 sd
->nr_balance_failed
= sd
->cache_nice_tries
+1;
3033 sd
->nr_balance_failed
= 0;
3035 if (likely(!active_balance
)) {
3036 /* We were unbalanced, so reset the balancing interval */
3037 sd
->balance_interval
= sd
->min_interval
;
3040 * If we've begun active balancing, start to back off. This
3041 * case may not be covered by the all_pinned logic if there
3042 * is only 1 task on the busy runqueue (because we don't call
3045 if (sd
->balance_interval
< sd
->max_interval
)
3046 sd
->balance_interval
*= 2;
3049 if (!ld_moved
&& !sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3050 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3055 schedstat_inc(sd
, lb_balanced
[idle
]);
3057 sd
->nr_balance_failed
= 0;
3060 /* tune up the balancing interval */
3061 if ((all_pinned
&& sd
->balance_interval
< MAX_PINNED_INTERVAL
) ||
3062 (sd
->balance_interval
< sd
->max_interval
))
3063 sd
->balance_interval
*= 2;
3065 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3066 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3072 * Check this_cpu to ensure it is balanced within domain. Attempt to move
3073 * tasks if there is an imbalance.
3075 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3076 * this_rq is locked.
3079 load_balance_newidle(int this_cpu
, struct rq
*this_rq
, struct sched_domain
*sd
)
3081 struct sched_group
*group
;
3082 struct rq
*busiest
= NULL
;
3083 unsigned long imbalance
;
3087 cpumask_t cpus
= CPU_MASK_ALL
;
3090 * When power savings policy is enabled for the parent domain, idle
3091 * sibling can pick up load irrespective of busy siblings. In this case,
3092 * let the state of idle sibling percolate up as IDLE, instead of
3093 * portraying it as CPU_NOT_IDLE.
3095 if (sd
->flags
& SD_SHARE_CPUPOWER
&&
3096 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3099 schedstat_inc(sd
, lb_count
[CPU_NEWLY_IDLE
]);
3101 group
= find_busiest_group(sd
, this_cpu
, &imbalance
, CPU_NEWLY_IDLE
,
3102 &sd_idle
, &cpus
, NULL
);
3104 schedstat_inc(sd
, lb_nobusyg
[CPU_NEWLY_IDLE
]);
3108 busiest
= find_busiest_queue(group
, CPU_NEWLY_IDLE
, imbalance
,
3111 schedstat_inc(sd
, lb_nobusyq
[CPU_NEWLY_IDLE
]);
3115 BUG_ON(busiest
== this_rq
);
3117 schedstat_add(sd
, lb_imbalance
[CPU_NEWLY_IDLE
], imbalance
);
3120 if (busiest
->nr_running
> 1) {
3121 /* Attempt to move tasks */
3122 double_lock_balance(this_rq
, busiest
);
3123 /* this_rq->clock is already updated */
3124 update_rq_clock(busiest
);
3125 ld_moved
= move_tasks(this_rq
, this_cpu
, busiest
,
3126 imbalance
, sd
, CPU_NEWLY_IDLE
,
3128 spin_unlock(&busiest
->lock
);
3130 if (unlikely(all_pinned
)) {
3131 cpu_clear(cpu_of(busiest
), cpus
);
3132 if (!cpus_empty(cpus
))
3138 schedstat_inc(sd
, lb_failed
[CPU_NEWLY_IDLE
]);
3139 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3140 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3143 sd
->nr_balance_failed
= 0;
3148 schedstat_inc(sd
, lb_balanced
[CPU_NEWLY_IDLE
]);
3149 if (!sd_idle
&& sd
->flags
& SD_SHARE_CPUPOWER
&&
3150 !test_sd_parent(sd
, SD_POWERSAVINGS_BALANCE
))
3152 sd
->nr_balance_failed
= 0;
3158 * idle_balance is called by schedule() if this_cpu is about to become
3159 * idle. Attempts to pull tasks from other CPUs.
3161 static void idle_balance(int this_cpu
, struct rq
*this_rq
)
3163 struct sched_domain
*sd
;
3164 int pulled_task
= -1;
3165 unsigned long next_balance
= jiffies
+ HZ
;
3167 for_each_domain(this_cpu
, sd
) {
3168 unsigned long interval
;
3170 if (!(sd
->flags
& SD_LOAD_BALANCE
))
3173 if (sd
->flags
& SD_BALANCE_NEWIDLE
)
3174 /* If we've pulled tasks over stop searching: */
3175 pulled_task
= load_balance_newidle(this_cpu
,
3178 interval
= msecs_to_jiffies(sd
->balance_interval
);
3179 if (time_after(next_balance
, sd
->last_balance
+ interval
))
3180 next_balance
= sd
->last_balance
+ interval
;
3184 if (pulled_task
|| time_after(jiffies
, this_rq
->next_balance
)) {
3186 * We are going idle. next_balance may be set based on
3187 * a busy processor. So reset next_balance.
3189 this_rq
->next_balance
= next_balance
;
3194 * active_load_balance is run by migration threads. It pushes running tasks
3195 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3196 * running on each physical CPU where possible, and avoids physical /
3197 * logical imbalances.
3199 * Called with busiest_rq locked.
3201 static void active_load_balance(struct rq
*busiest_rq
, int busiest_cpu
)
3203 int target_cpu
= busiest_rq
->push_cpu
;
3204 struct sched_domain
*sd
;
3205 struct rq
*target_rq
;
3207 /* Is there any task to move? */
3208 if (busiest_rq
->nr_running
<= 1)
3211 target_rq
= cpu_rq(target_cpu
);
3214 * This condition is "impossible", if it occurs
3215 * we need to fix it. Originally reported by
3216 * Bjorn Helgaas on a 128-cpu setup.
3218 BUG_ON(busiest_rq
== target_rq
);
3220 /* move a task from busiest_rq to target_rq */
3221 double_lock_balance(busiest_rq
, target_rq
);
3222 update_rq_clock(busiest_rq
);
3223 update_rq_clock(target_rq
);
3225 /* Search for an sd spanning us and the target CPU. */
3226 for_each_domain(target_cpu
, sd
) {
3227 if ((sd
->flags
& SD_LOAD_BALANCE
) &&
3228 cpu_isset(busiest_cpu
, sd
->span
))
3233 schedstat_inc(sd
, alb_count
);
3235 if (move_one_task(target_rq
, target_cpu
, busiest_rq
,
3237 schedstat_inc(sd
, alb_pushed
);
3239 schedstat_inc(sd
, alb_failed
);
3241 spin_unlock(&target_rq
->lock
);
3246 atomic_t load_balancer
;
3248 } nohz ____cacheline_aligned
= {
3249 .load_balancer
= ATOMIC_INIT(-1),
3250 .cpu_mask
= CPU_MASK_NONE
,
3254 * This routine will try to nominate the ilb (idle load balancing)
3255 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3256 * load balancing on behalf of all those cpus. If all the cpus in the system
3257 * go into this tickless mode, then there will be no ilb owner (as there is
3258 * no need for one) and all the cpus will sleep till the next wakeup event
3261 * For the ilb owner, tick is not stopped. And this tick will be used
3262 * for idle load balancing. ilb owner will still be part of
3265 * While stopping the tick, this cpu will become the ilb owner if there
3266 * is no other owner. And will be the owner till that cpu becomes busy
3267 * or if all cpus in the system stop their ticks at which point
3268 * there is no need for ilb owner.
3270 * When the ilb owner becomes busy, it nominates another owner, during the
3271 * next busy scheduler_tick()
3273 int select_nohz_load_balancer(int stop_tick
)
3275 int cpu
= smp_processor_id();
3278 cpu_set(cpu
, nohz
.cpu_mask
);
3279 cpu_rq(cpu
)->in_nohz_recently
= 1;
3282 * If we are going offline and still the leader, give up!
3284 if (cpu_is_offline(cpu
) &&
3285 atomic_read(&nohz
.load_balancer
) == cpu
) {
3286 if (atomic_cmpxchg(&nohz
.load_balancer
, cpu
, -1) != cpu
)
3291 /* time for ilb owner also to sleep */
3292 if (cpus_weight(nohz
.cpu_mask
) == num_online_cpus()) {
3293 if (atomic_read(&nohz
.load_balancer
) == cpu
)
3294 atomic_set(&nohz
.load_balancer
, -1);
3298 if (atomic_read(&nohz
.load_balancer
) == -1) {
3299 /* make me the ilb owner */
3300 if (atomic_cmpxchg(&nohz
.load_balancer
, -1, cpu
) == -1)
3302 } else if (atomic_read(&nohz
.load_balancer
) == cpu
)
3305 if (!cpu_isset(cpu
, nohz
.cpu_mask
))
3308 cpu_clear(cpu
, nohz
.cpu_mask
);
3310 if (atomic_read(&nohz
.load_balancer
) == cpu
)
3311 if (atomic_cmpxchg(&nohz
.load_balancer
, cpu
, -1) != cpu
)
3318 static DEFINE_SPINLOCK(balancing
);
3321 * It checks each scheduling domain to see if it is due to be balanced,
3322 * and initiates a balancing operation if so.
3324 * Balancing parameters are set up in arch_init_sched_domains.
3326 static void rebalance_domains(int cpu
, enum cpu_idle_type idle
)
3329 struct rq
*rq
= cpu_rq(cpu
);
3330 unsigned long interval
;
3331 struct sched_domain
*sd
;
3332 /* Earliest time when we have to do rebalance again */
3333 unsigned long next_balance
= jiffies
+ 60*HZ
;
3334 int update_next_balance
= 0;
3336 for_each_domain(cpu
, sd
) {
3337 if (!(sd
->flags
& SD_LOAD_BALANCE
))
3340 interval
= sd
->balance_interval
;
3341 if (idle
!= CPU_IDLE
)
3342 interval
*= sd
->busy_factor
;
3344 /* scale ms to jiffies */
3345 interval
= msecs_to_jiffies(interval
);
3346 if (unlikely(!interval
))
3348 if (interval
> HZ
*NR_CPUS
/10)
3349 interval
= HZ
*NR_CPUS
/10;
3352 if (sd
->flags
& SD_SERIALIZE
) {
3353 if (!spin_trylock(&balancing
))
3357 if (time_after_eq(jiffies
, sd
->last_balance
+ interval
)) {
3358 if (load_balance(cpu
, rq
, sd
, idle
, &balance
)) {
3360 * We've pulled tasks over so either we're no
3361 * longer idle, or one of our SMT siblings is
3364 idle
= CPU_NOT_IDLE
;
3366 sd
->last_balance
= jiffies
;
3368 if (sd
->flags
& SD_SERIALIZE
)
3369 spin_unlock(&balancing
);
3371 if (time_after(next_balance
, sd
->last_balance
+ interval
)) {
3372 next_balance
= sd
->last_balance
+ interval
;
3373 update_next_balance
= 1;
3377 * Stop the load balance at this level. There is another
3378 * CPU in our sched group which is doing load balancing more
3386 * next_balance will be updated only when there is a need.
3387 * When the cpu is attached to null domain for ex, it will not be
3390 if (likely(update_next_balance
))
3391 rq
->next_balance
= next_balance
;
3395 * run_rebalance_domains is triggered when needed from the scheduler tick.
3396 * In CONFIG_NO_HZ case, the idle load balance owner will do the
3397 * rebalancing for all the cpus for whom scheduler ticks are stopped.
3399 static void run_rebalance_domains(struct softirq_action
*h
)
3401 int this_cpu
= smp_processor_id();
3402 struct rq
*this_rq
= cpu_rq(this_cpu
);
3403 enum cpu_idle_type idle
= this_rq
->idle_at_tick
?
3404 CPU_IDLE
: CPU_NOT_IDLE
;
3406 rebalance_domains(this_cpu
, idle
);
3410 * If this cpu is the owner for idle load balancing, then do the
3411 * balancing on behalf of the other idle cpus whose ticks are
3414 if (this_rq
->idle_at_tick
&&
3415 atomic_read(&nohz
.load_balancer
) == this_cpu
) {
3416 cpumask_t cpus
= nohz
.cpu_mask
;
3420 cpu_clear(this_cpu
, cpus
);
3421 for_each_cpu_mask(balance_cpu
, cpus
) {
3423 * If this cpu gets work to do, stop the load balancing
3424 * work being done for other cpus. Next load
3425 * balancing owner will pick it up.
3430 rebalance_domains(balance_cpu
, CPU_IDLE
);
3432 rq
= cpu_rq(balance_cpu
);
3433 if (time_after(this_rq
->next_balance
, rq
->next_balance
))
3434 this_rq
->next_balance
= rq
->next_balance
;
3441 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
3443 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
3444 * idle load balancing owner or decide to stop the periodic load balancing,
3445 * if the whole system is idle.
3447 static inline void trigger_load_balance(struct rq
*rq
, int cpu
)
3451 * If we were in the nohz mode recently and busy at the current
3452 * scheduler tick, then check if we need to nominate new idle
3455 if (rq
->in_nohz_recently
&& !rq
->idle_at_tick
) {
3456 rq
->in_nohz_recently
= 0;
3458 if (atomic_read(&nohz
.load_balancer
) == cpu
) {
3459 cpu_clear(cpu
, nohz
.cpu_mask
);
3460 atomic_set(&nohz
.load_balancer
, -1);
3463 if (atomic_read(&nohz
.load_balancer
) == -1) {
3465 * simple selection for now: Nominate the
3466 * first cpu in the nohz list to be the next
3469 * TBD: Traverse the sched domains and nominate
3470 * the nearest cpu in the nohz.cpu_mask.
3472 int ilb
= first_cpu(nohz
.cpu_mask
);
3480 * If this cpu is idle and doing idle load balancing for all the
3481 * cpus with ticks stopped, is it time for that to stop?
3483 if (rq
->idle_at_tick
&& atomic_read(&nohz
.load_balancer
) == cpu
&&
3484 cpus_weight(nohz
.cpu_mask
) == num_online_cpus()) {
3490 * If this cpu is idle and the idle load balancing is done by
3491 * someone else, then no need raise the SCHED_SOFTIRQ
3493 if (rq
->idle_at_tick
&& atomic_read(&nohz
.load_balancer
) != cpu
&&
3494 cpu_isset(cpu
, nohz
.cpu_mask
))
3497 if (time_after_eq(jiffies
, rq
->next_balance
))
3498 raise_softirq(SCHED_SOFTIRQ
);
3501 #else /* CONFIG_SMP */
3504 * on UP we do not need to balance between CPUs:
3506 static inline void idle_balance(int cpu
, struct rq
*rq
)
3512 DEFINE_PER_CPU(struct kernel_stat
, kstat
);
3514 EXPORT_PER_CPU_SYMBOL(kstat
);
3517 * Return p->sum_exec_runtime plus any more ns on the sched_clock
3518 * that have not yet been banked in case the task is currently running.
3520 unsigned long long task_sched_runtime(struct task_struct
*p
)
3522 unsigned long flags
;
3526 rq
= task_rq_lock(p
, &flags
);
3527 ns
= p
->se
.sum_exec_runtime
;
3528 if (task_current(rq
, p
)) {
3529 update_rq_clock(rq
);
3530 delta_exec
= rq
->clock
- p
->se
.exec_start
;
3531 if ((s64
)delta_exec
> 0)
3534 task_rq_unlock(rq
, &flags
);
3540 * Account user cpu time to a process.
3541 * @p: the process that the cpu time gets accounted to
3542 * @cputime: the cpu time spent in user space since the last update
3544 void account_user_time(struct task_struct
*p
, cputime_t cputime
)
3546 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3549 p
->utime
= cputime_add(p
->utime
, cputime
);
3551 /* Add user time to cpustat. */
3552 tmp
= cputime_to_cputime64(cputime
);
3553 if (TASK_NICE(p
) > 0)
3554 cpustat
->nice
= cputime64_add(cpustat
->nice
, tmp
);
3556 cpustat
->user
= cputime64_add(cpustat
->user
, tmp
);
3560 * Account guest cpu time to a process.
3561 * @p: the process that the cpu time gets accounted to
3562 * @cputime: the cpu time spent in virtual machine since the last update
3564 static void account_guest_time(struct task_struct
*p
, cputime_t cputime
)
3567 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3569 tmp
= cputime_to_cputime64(cputime
);
3571 p
->utime
= cputime_add(p
->utime
, cputime
);
3572 p
->gtime
= cputime_add(p
->gtime
, cputime
);
3574 cpustat
->user
= cputime64_add(cpustat
->user
, tmp
);
3575 cpustat
->guest
= cputime64_add(cpustat
->guest
, tmp
);
3579 * Account scaled user cpu time to a process.
3580 * @p: the process that the cpu time gets accounted to
3581 * @cputime: the cpu time spent in user space since the last update
3583 void account_user_time_scaled(struct task_struct
*p
, cputime_t cputime
)
3585 p
->utimescaled
= cputime_add(p
->utimescaled
, cputime
);
3589 * Account system cpu time to a process.
3590 * @p: the process that the cpu time gets accounted to
3591 * @hardirq_offset: the offset to subtract from hardirq_count()
3592 * @cputime: the cpu time spent in kernel space since the last update
3594 void account_system_time(struct task_struct
*p
, int hardirq_offset
,
3597 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3598 struct rq
*rq
= this_rq();
3601 if ((p
->flags
& PF_VCPU
) && (irq_count() - hardirq_offset
== 0))
3602 return account_guest_time(p
, cputime
);
3604 p
->stime
= cputime_add(p
->stime
, cputime
);
3606 /* Add system time to cpustat. */
3607 tmp
= cputime_to_cputime64(cputime
);
3608 if (hardirq_count() - hardirq_offset
)
3609 cpustat
->irq
= cputime64_add(cpustat
->irq
, tmp
);
3610 else if (softirq_count())
3611 cpustat
->softirq
= cputime64_add(cpustat
->softirq
, tmp
);
3612 else if (p
!= rq
->idle
)
3613 cpustat
->system
= cputime64_add(cpustat
->system
, tmp
);
3614 else if (atomic_read(&rq
->nr_iowait
) > 0)
3615 cpustat
->iowait
= cputime64_add(cpustat
->iowait
, tmp
);
3617 cpustat
->idle
= cputime64_add(cpustat
->idle
, tmp
);
3618 /* Account for system time used */
3619 acct_update_integrals(p
);
3623 * Account scaled system cpu time to a process.
3624 * @p: the process that the cpu time gets accounted to
3625 * @hardirq_offset: the offset to subtract from hardirq_count()
3626 * @cputime: the cpu time spent in kernel space since the last update
3628 void account_system_time_scaled(struct task_struct
*p
, cputime_t cputime
)
3630 p
->stimescaled
= cputime_add(p
->stimescaled
, cputime
);
3634 * Account for involuntary wait time.
3635 * @p: the process from which the cpu time has been stolen
3636 * @steal: the cpu time spent in involuntary wait
3638 void account_steal_time(struct task_struct
*p
, cputime_t steal
)
3640 struct cpu_usage_stat
*cpustat
= &kstat_this_cpu
.cpustat
;
3641 cputime64_t tmp
= cputime_to_cputime64(steal
);
3642 struct rq
*rq
= this_rq();
3644 if (p
== rq
->idle
) {
3645 p
->stime
= cputime_add(p
->stime
, steal
);
3646 if (atomic_read(&rq
->nr_iowait
) > 0)
3647 cpustat
->iowait
= cputime64_add(cpustat
->iowait
, tmp
);
3649 cpustat
->idle
= cputime64_add(cpustat
->idle
, tmp
);
3651 cpustat
->steal
= cputime64_add(cpustat
->steal
, tmp
);
3655 * This function gets called by the timer code, with HZ frequency.
3656 * We call it with interrupts disabled.
3658 * It also gets called by the fork code, when changing the parent's
3661 void scheduler_tick(void)
3663 int cpu
= smp_processor_id();
3664 struct rq
*rq
= cpu_rq(cpu
);
3665 struct task_struct
*curr
= rq
->curr
;
3666 u64 next_tick
= rq
->tick_timestamp
+ TICK_NSEC
;
3668 spin_lock(&rq
->lock
);
3669 __update_rq_clock(rq
);
3671 * Let rq->clock advance by at least TICK_NSEC:
3673 if (unlikely(rq
->clock
< next_tick
))
3674 rq
->clock
= next_tick
;
3675 rq
->tick_timestamp
= rq
->clock
;
3676 update_cpu_load(rq
);
3677 if (curr
!= rq
->idle
) /* FIXME: needed? */
3678 curr
->sched_class
->task_tick(rq
, curr
, 0);
3679 spin_unlock(&rq
->lock
);
3682 rq
->idle_at_tick
= idle_cpu(cpu
);
3683 trigger_load_balance(rq
, cpu
);
3687 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3689 void fastcall
add_preempt_count(int val
)
3694 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3696 preempt_count() += val
;
3698 * Spinlock count overflowing soon?
3700 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK
) >=
3703 EXPORT_SYMBOL(add_preempt_count
);
3705 void fastcall
sub_preempt_count(int val
)
3710 if (DEBUG_LOCKS_WARN_ON(val
> preempt_count()))
3713 * Is the spinlock portion underflowing?
3715 if (DEBUG_LOCKS_WARN_ON((val
< PREEMPT_MASK
) &&
3716 !(preempt_count() & PREEMPT_MASK
)))
3719 preempt_count() -= val
;
3721 EXPORT_SYMBOL(sub_preempt_count
);
3726 * Print scheduling while atomic bug:
3728 static noinline
void __schedule_bug(struct task_struct
*prev
)
3730 struct pt_regs
*regs
= get_irq_regs();
3732 printk(KERN_ERR
"BUG: scheduling while atomic: %s/%d/0x%08x\n",
3733 prev
->comm
, prev
->pid
, preempt_count());
3735 debug_show_held_locks(prev
);
3736 if (irqs_disabled())
3737 print_irqtrace_events(prev
);
3746 * Various schedule()-time debugging checks and statistics:
3748 static inline void schedule_debug(struct task_struct
*prev
)
3751 * Test if we are atomic. Since do_exit() needs to call into
3752 * schedule() atomically, we ignore that path for now.
3753 * Otherwise, whine if we are scheduling when we should not be.
3755 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev
->exit_state
))
3756 __schedule_bug(prev
);
3758 profile_hit(SCHED_PROFILING
, __builtin_return_address(0));
3760 schedstat_inc(this_rq(), sched_count
);
3761 #ifdef CONFIG_SCHEDSTATS
3762 if (unlikely(prev
->lock_depth
>= 0)) {
3763 schedstat_inc(this_rq(), bkl_count
);
3764 schedstat_inc(prev
, sched_info
.bkl_count
);
3770 * Pick up the highest-prio task:
3772 static inline struct task_struct
*
3773 pick_next_task(struct rq
*rq
, struct task_struct
*prev
)
3775 const struct sched_class
*class;
3776 struct task_struct
*p
;
3779 * Optimization: we know that if all tasks are in
3780 * the fair class we can call that function directly:
3782 if (likely(rq
->nr_running
== rq
->cfs
.nr_running
)) {
3783 p
= fair_sched_class
.pick_next_task(rq
);
3788 class = sched_class_highest
;
3790 p
= class->pick_next_task(rq
);
3794 * Will never be NULL as the idle class always
3795 * returns a non-NULL p:
3797 class = class->next
;
3802 * schedule() is the main scheduler function.
3804 asmlinkage
void __sched
schedule(void)
3806 struct task_struct
*prev
, *next
;
3813 cpu
= smp_processor_id();
3817 switch_count
= &prev
->nivcsw
;
3819 release_kernel_lock(prev
);
3820 need_resched_nonpreemptible
:
3822 schedule_debug(prev
);
3827 * Do the rq-clock update outside the rq lock:
3829 local_irq_disable();
3830 __update_rq_clock(rq
);
3831 spin_lock(&rq
->lock
);
3832 clear_tsk_need_resched(prev
);
3834 if (prev
->state
&& !(preempt_count() & PREEMPT_ACTIVE
)) {
3835 if (unlikely((prev
->state
& TASK_INTERRUPTIBLE
) &&
3836 unlikely(signal_pending(prev
)))) {
3837 prev
->state
= TASK_RUNNING
;
3839 deactivate_task(rq
, prev
, 1);
3841 switch_count
= &prev
->nvcsw
;
3845 if (prev
->sched_class
->pre_schedule
)
3846 prev
->sched_class
->pre_schedule(rq
, prev
);
3849 if (unlikely(!rq
->nr_running
))
3850 idle_balance(cpu
, rq
);
3852 prev
->sched_class
->put_prev_task(rq
, prev
);
3853 next
= pick_next_task(rq
, prev
);
3855 sched_info_switch(prev
, next
);
3857 if (likely(prev
!= next
)) {
3862 context_switch(rq
, prev
, next
); /* unlocks the rq */
3864 * the context switch might have flipped the stack from under
3865 * us, hence refresh the local variables.
3867 cpu
= smp_processor_id();
3870 spin_unlock_irq(&rq
->lock
);
3874 if (unlikely(reacquire_kernel_lock(current
) < 0))
3875 goto need_resched_nonpreemptible
;
3877 preempt_enable_no_resched();
3878 if (unlikely(test_thread_flag(TIF_NEED_RESCHED
)))
3881 EXPORT_SYMBOL(schedule
);
3883 #ifdef CONFIG_PREEMPT
3885 * this is the entry point to schedule() from in-kernel preemption
3886 * off of preempt_enable. Kernel preemptions off return from interrupt
3887 * occur there and call schedule directly.
3889 asmlinkage
void __sched
preempt_schedule(void)
3891 struct thread_info
*ti
= current_thread_info();
3892 #ifdef CONFIG_PREEMPT_BKL
3893 struct task_struct
*task
= current
;
3894 int saved_lock_depth
;
3897 * If there is a non-zero preempt_count or interrupts are disabled,
3898 * we do not want to preempt the current task. Just return..
3900 if (likely(ti
->preempt_count
|| irqs_disabled()))
3904 add_preempt_count(PREEMPT_ACTIVE
);
3907 * We keep the big kernel semaphore locked, but we
3908 * clear ->lock_depth so that schedule() doesnt
3909 * auto-release the semaphore:
3911 #ifdef CONFIG_PREEMPT_BKL
3912 saved_lock_depth
= task
->lock_depth
;
3913 task
->lock_depth
= -1;
3916 #ifdef CONFIG_PREEMPT_BKL
3917 task
->lock_depth
= saved_lock_depth
;
3919 sub_preempt_count(PREEMPT_ACTIVE
);
3922 * Check again in case we missed a preemption opportunity
3923 * between schedule and now.
3926 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED
)));
3928 EXPORT_SYMBOL(preempt_schedule
);
3931 * this is the entry point to schedule() from kernel preemption
3932 * off of irq context.
3933 * Note, that this is called and return with irqs disabled. This will
3934 * protect us against recursive calling from irq.
3936 asmlinkage
void __sched
preempt_schedule_irq(void)
3938 struct thread_info
*ti
= current_thread_info();
3939 #ifdef CONFIG_PREEMPT_BKL
3940 struct task_struct
*task
= current
;
3941 int saved_lock_depth
;
3943 /* Catch callers which need to be fixed */
3944 BUG_ON(ti
->preempt_count
|| !irqs_disabled());
3947 add_preempt_count(PREEMPT_ACTIVE
);
3950 * We keep the big kernel semaphore locked, but we
3951 * clear ->lock_depth so that schedule() doesnt
3952 * auto-release the semaphore:
3954 #ifdef CONFIG_PREEMPT_BKL
3955 saved_lock_depth
= task
->lock_depth
;
3956 task
->lock_depth
= -1;
3960 local_irq_disable();
3961 #ifdef CONFIG_PREEMPT_BKL
3962 task
->lock_depth
= saved_lock_depth
;
3964 sub_preempt_count(PREEMPT_ACTIVE
);
3967 * Check again in case we missed a preemption opportunity
3968 * between schedule and now.
3971 } while (unlikely(test_thread_flag(TIF_NEED_RESCHED
)));
3974 #endif /* CONFIG_PREEMPT */
3976 int default_wake_function(wait_queue_t
*curr
, unsigned mode
, int sync
,
3979 return try_to_wake_up(curr
->private, mode
, sync
);
3981 EXPORT_SYMBOL(default_wake_function
);
3984 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3985 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3986 * number) then we wake all the non-exclusive tasks and one exclusive task.
3988 * There are circumstances in which we can try to wake a task which has already
3989 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3990 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3992 static void __wake_up_common(wait_queue_head_t
*q
, unsigned int mode
,
3993 int nr_exclusive
, int sync
, void *key
)
3995 wait_queue_t
*curr
, *next
;
3997 list_for_each_entry_safe(curr
, next
, &q
->task_list
, task_list
) {
3998 unsigned flags
= curr
->flags
;
4000 if (curr
->func(curr
, mode
, sync
, key
) &&
4001 (flags
& WQ_FLAG_EXCLUSIVE
) && !--nr_exclusive
)
4007 * __wake_up - wake up threads blocked on a waitqueue.
4009 * @mode: which threads
4010 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4011 * @key: is directly passed to the wakeup function
4013 void fastcall
__wake_up(wait_queue_head_t
*q
, unsigned int mode
,
4014 int nr_exclusive
, void *key
)
4016 unsigned long flags
;
4018 spin_lock_irqsave(&q
->lock
, flags
);
4019 __wake_up_common(q
, mode
, nr_exclusive
, 0, key
);
4020 spin_unlock_irqrestore(&q
->lock
, flags
);
4022 EXPORT_SYMBOL(__wake_up
);
4025 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4027 void fastcall
__wake_up_locked(wait_queue_head_t
*q
, unsigned int mode
)
4029 __wake_up_common(q
, mode
, 1, 0, NULL
);
4033 * __wake_up_sync - wake up threads blocked on a waitqueue.
4035 * @mode: which threads
4036 * @nr_exclusive: how many wake-one or wake-many threads to wake up
4038 * The sync wakeup differs that the waker knows that it will schedule
4039 * away soon, so while the target thread will be woken up, it will not
4040 * be migrated to another CPU - ie. the two threads are 'synchronized'
4041 * with each other. This can prevent needless bouncing between CPUs.
4043 * On UP it can prevent extra preemption.
4046 __wake_up_sync(wait_queue_head_t
*q
, unsigned int mode
, int nr_exclusive
)
4048 unsigned long flags
;
4054 if (unlikely(!nr_exclusive
))
4057 spin_lock_irqsave(&q
->lock
, flags
);
4058 __wake_up_common(q
, mode
, nr_exclusive
, sync
, NULL
);
4059 spin_unlock_irqrestore(&q
->lock
, flags
);
4061 EXPORT_SYMBOL_GPL(__wake_up_sync
); /* For internal use only */
4063 void complete(struct completion
*x
)
4065 unsigned long flags
;
4067 spin_lock_irqsave(&x
->wait
.lock
, flags
);
4069 __wake_up_common(&x
->wait
, TASK_UNINTERRUPTIBLE
| TASK_INTERRUPTIBLE
,
4071 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
4073 EXPORT_SYMBOL(complete
);
4075 void complete_all(struct completion
*x
)
4077 unsigned long flags
;
4079 spin_lock_irqsave(&x
->wait
.lock
, flags
);
4080 x
->done
+= UINT_MAX
/2;
4081 __wake_up_common(&x
->wait
, TASK_UNINTERRUPTIBLE
| TASK_INTERRUPTIBLE
,
4083 spin_unlock_irqrestore(&x
->wait
.lock
, flags
);
4085 EXPORT_SYMBOL(complete_all
);
4087 static inline long __sched
4088 do_wait_for_common(struct completion
*x
, long timeout
, int state
)
4091 DECLARE_WAITQUEUE(wait
, current
);
4093 wait
.flags
|= WQ_FLAG_EXCLUSIVE
;
4094 __add_wait_queue_tail(&x
->wait
, &wait
);
4096 if (state
== TASK_INTERRUPTIBLE
&&
4097 signal_pending(current
)) {
4098 __remove_wait_queue(&x
->wait
, &wait
);
4099 return -ERESTARTSYS
;
4101 __set_current_state(state
);
4102 spin_unlock_irq(&x
->wait
.lock
);
4103 timeout
= schedule_timeout(timeout
);
4104 spin_lock_irq(&x
->wait
.lock
);
4106 __remove_wait_queue(&x
->wait
, &wait
);
4110 __remove_wait_queue(&x
->wait
, &wait
);
4117 wait_for_common(struct completion
*x
, long timeout
, int state
)
4121 spin_lock_irq(&x
->wait
.lock
);
4122 timeout
= do_wait_for_common(x
, timeout
, state
);
4123 spin_unlock_irq(&x
->wait
.lock
);
4127 void __sched
wait_for_completion(struct completion
*x
)
4129 wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_UNINTERRUPTIBLE
);
4131 EXPORT_SYMBOL(wait_for_completion
);
4133 unsigned long __sched
4134 wait_for_completion_timeout(struct completion
*x
, unsigned long timeout
)
4136 return wait_for_common(x
, timeout
, TASK_UNINTERRUPTIBLE
);
4138 EXPORT_SYMBOL(wait_for_completion_timeout
);
4140 int __sched
wait_for_completion_interruptible(struct completion
*x
)
4142 long t
= wait_for_common(x
, MAX_SCHEDULE_TIMEOUT
, TASK_INTERRUPTIBLE
);
4143 if (t
== -ERESTARTSYS
)
4147 EXPORT_SYMBOL(wait_for_completion_interruptible
);
4149 unsigned long __sched
4150 wait_for_completion_interruptible_timeout(struct completion
*x
,
4151 unsigned long timeout
)
4153 return wait_for_common(x
, timeout
, TASK_INTERRUPTIBLE
);
4155 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout
);
4158 sleep_on_common(wait_queue_head_t
*q
, int state
, long timeout
)
4160 unsigned long flags
;
4163 init_waitqueue_entry(&wait
, current
);
4165 __set_current_state(state
);
4167 spin_lock_irqsave(&q
->lock
, flags
);
4168 __add_wait_queue(q
, &wait
);
4169 spin_unlock(&q
->lock
);
4170 timeout
= schedule_timeout(timeout
);
4171 spin_lock_irq(&q
->lock
);
4172 __remove_wait_queue(q
, &wait
);
4173 spin_unlock_irqrestore(&q
->lock
, flags
);
4178 void __sched
interruptible_sleep_on(wait_queue_head_t
*q
)
4180 sleep_on_common(q
, TASK_INTERRUPTIBLE
, MAX_SCHEDULE_TIMEOUT
);
4182 EXPORT_SYMBOL(interruptible_sleep_on
);
4185 interruptible_sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
4187 return sleep_on_common(q
, TASK_INTERRUPTIBLE
, timeout
);
4189 EXPORT_SYMBOL(interruptible_sleep_on_timeout
);
4191 void __sched
sleep_on(wait_queue_head_t
*q
)
4193 sleep_on_common(q
, TASK_UNINTERRUPTIBLE
, MAX_SCHEDULE_TIMEOUT
);
4195 EXPORT_SYMBOL(sleep_on
);
4197 long __sched
sleep_on_timeout(wait_queue_head_t
*q
, long timeout
)
4199 return sleep_on_common(q
, TASK_UNINTERRUPTIBLE
, timeout
);
4201 EXPORT_SYMBOL(sleep_on_timeout
);
4203 #ifdef CONFIG_RT_MUTEXES
4206 * rt_mutex_setprio - set the current priority of a task
4208 * @prio: prio value (kernel-internal form)
4210 * This function changes the 'effective' priority of a task. It does
4211 * not touch ->normal_prio like __setscheduler().
4213 * Used by the rt_mutex code to implement priority inheritance logic.
4215 void rt_mutex_setprio(struct task_struct
*p
, int prio
)
4217 unsigned long flags
;
4218 int oldprio
, on_rq
, running
;
4220 const struct sched_class
*prev_class
= p
->sched_class
;
4222 BUG_ON(prio
< 0 || prio
> MAX_PRIO
);
4224 rq
= task_rq_lock(p
, &flags
);
4225 update_rq_clock(rq
);
4228 on_rq
= p
->se
.on_rq
;
4229 running
= task_current(rq
, p
);
4231 dequeue_task(rq
, p
, 0);
4233 p
->sched_class
->put_prev_task(rq
, p
);
4237 p
->sched_class
= &rt_sched_class
;
4239 p
->sched_class
= &fair_sched_class
;
4245 p
->sched_class
->set_curr_task(rq
);
4247 enqueue_task(rq
, p
, 0);
4249 check_class_changed(rq
, p
, prev_class
, oldprio
, running
);
4251 task_rq_unlock(rq
, &flags
);
4256 void set_user_nice(struct task_struct
*p
, long nice
)
4258 int old_prio
, delta
, on_rq
;
4259 unsigned long flags
;
4262 if (TASK_NICE(p
) == nice
|| nice
< -20 || nice
> 19)
4265 * We have to be careful, if called from sys_setpriority(),
4266 * the task might be in the middle of scheduling on another CPU.
4268 rq
= task_rq_lock(p
, &flags
);
4269 update_rq_clock(rq
);
4271 * The RT priorities are set via sched_setscheduler(), but we still
4272 * allow the 'normal' nice value to be set - but as expected
4273 * it wont have any effect on scheduling until the task is
4274 * SCHED_FIFO/SCHED_RR:
4276 if (task_has_rt_policy(p
)) {
4277 p
->static_prio
= NICE_TO_PRIO(nice
);
4280 on_rq
= p
->se
.on_rq
;
4282 dequeue_task(rq
, p
, 0);
4284 p
->static_prio
= NICE_TO_PRIO(nice
);
4287 p
->prio
= effective_prio(p
);
4288 delta
= p
->prio
- old_prio
;
4291 enqueue_task(rq
, p
, 0);
4293 * If the task increased its priority or is running and
4294 * lowered its priority, then reschedule its CPU:
4296 if (delta
< 0 || (delta
> 0 && task_running(rq
, p
)))
4297 resched_task(rq
->curr
);
4300 task_rq_unlock(rq
, &flags
);
4302 EXPORT_SYMBOL(set_user_nice
);
4305 * can_nice - check if a task can reduce its nice value
4309 int can_nice(const struct task_struct
*p
, const int nice
)
4311 /* convert nice value [19,-20] to rlimit style value [1,40] */
4312 int nice_rlim
= 20 - nice
;
4314 return (nice_rlim
<= p
->signal
->rlim
[RLIMIT_NICE
].rlim_cur
||
4315 capable(CAP_SYS_NICE
));
4318 #ifdef __ARCH_WANT_SYS_NICE
4321 * sys_nice - change the priority of the current process.
4322 * @increment: priority increment
4324 * sys_setpriority is a more generic, but much slower function that
4325 * does similar things.
4327 asmlinkage
long sys_nice(int increment
)
4332 * Setpriority might change our priority at the same moment.
4333 * We don't have to worry. Conceptually one call occurs first
4334 * and we have a single winner.
4336 if (increment
< -40)
4341 nice
= PRIO_TO_NICE(current
->static_prio
) + increment
;
4347 if (increment
< 0 && !can_nice(current
, nice
))
4350 retval
= security_task_setnice(current
, nice
);
4354 set_user_nice(current
, nice
);
4361 * task_prio - return the priority value of a given task.
4362 * @p: the task in question.
4364 * This is the priority value as seen by users in /proc.
4365 * RT tasks are offset by -200. Normal tasks are centered
4366 * around 0, value goes from -16 to +15.
4368 int task_prio(const struct task_struct
*p
)
4370 return p
->prio
- MAX_RT_PRIO
;
4374 * task_nice - return the nice value of a given task.
4375 * @p: the task in question.
4377 int task_nice(const struct task_struct
*p
)
4379 return TASK_NICE(p
);
4381 EXPORT_SYMBOL_GPL(task_nice
);
4384 * idle_cpu - is a given cpu idle currently?
4385 * @cpu: the processor in question.
4387 int idle_cpu(int cpu
)
4389 return cpu_curr(cpu
) == cpu_rq(cpu
)->idle
;
4393 * idle_task - return the idle task for a given cpu.
4394 * @cpu: the processor in question.
4396 struct task_struct
*idle_task(int cpu
)
4398 return cpu_rq(cpu
)->idle
;
4402 * find_process_by_pid - find a process with a matching PID value.
4403 * @pid: the pid in question.
4405 static struct task_struct
*find_process_by_pid(pid_t pid
)
4407 return pid
? find_task_by_vpid(pid
) : current
;
4410 /* Actually do priority change: must hold rq lock. */
4412 __setscheduler(struct rq
*rq
, struct task_struct
*p
, int policy
, int prio
)
4414 BUG_ON(p
->se
.on_rq
);
4417 switch (p
->policy
) {
4421 p
->sched_class
= &fair_sched_class
;
4425 p
->sched_class
= &rt_sched_class
;
4429 p
->rt_priority
= prio
;
4430 p
->normal_prio
= normal_prio(p
);
4431 /* we are holding p->pi_lock already */
4432 p
->prio
= rt_mutex_getprio(p
);
4437 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4438 * @p: the task in question.
4439 * @policy: new policy.
4440 * @param: structure containing the new RT priority.
4442 * NOTE that the task may be already dead.
4444 int sched_setscheduler(struct task_struct
*p
, int policy
,
4445 struct sched_param
*param
)
4447 int retval
, oldprio
, oldpolicy
= -1, on_rq
, running
;
4448 unsigned long flags
;
4449 const struct sched_class
*prev_class
= p
->sched_class
;
4452 /* may grab non-irq protected spin_locks */
4453 BUG_ON(in_interrupt());
4455 /* double check policy once rq lock held */
4457 policy
= oldpolicy
= p
->policy
;
4458 else if (policy
!= SCHED_FIFO
&& policy
!= SCHED_RR
&&
4459 policy
!= SCHED_NORMAL
&& policy
!= SCHED_BATCH
&&
4460 policy
!= SCHED_IDLE
)
4463 * Valid priorities for SCHED_FIFO and SCHED_RR are
4464 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4465 * SCHED_BATCH and SCHED_IDLE is 0.
4467 if (param
->sched_priority
< 0 ||
4468 (p
->mm
&& param
->sched_priority
> MAX_USER_RT_PRIO
-1) ||
4469 (!p
->mm
&& param
->sched_priority
> MAX_RT_PRIO
-1))
4471 if (rt_policy(policy
) != (param
->sched_priority
!= 0))
4475 * Allow unprivileged RT tasks to decrease priority:
4477 if (!capable(CAP_SYS_NICE
)) {
4478 if (rt_policy(policy
)) {
4479 unsigned long rlim_rtprio
;
4481 if (!lock_task_sighand(p
, &flags
))
4483 rlim_rtprio
= p
->signal
->rlim
[RLIMIT_RTPRIO
].rlim_cur
;
4484 unlock_task_sighand(p
, &flags
);
4486 /* can't set/change the rt policy */
4487 if (policy
!= p
->policy
&& !rlim_rtprio
)
4490 /* can't increase priority */
4491 if (param
->sched_priority
> p
->rt_priority
&&
4492 param
->sched_priority
> rlim_rtprio
)
4496 * Like positive nice levels, dont allow tasks to
4497 * move out of SCHED_IDLE either:
4499 if (p
->policy
== SCHED_IDLE
&& policy
!= SCHED_IDLE
)
4502 /* can't change other user's priorities */
4503 if ((current
->euid
!= p
->euid
) &&
4504 (current
->euid
!= p
->uid
))
4508 retval
= security_task_setscheduler(p
, policy
, param
);
4512 * make sure no PI-waiters arrive (or leave) while we are
4513 * changing the priority of the task:
4515 spin_lock_irqsave(&p
->pi_lock
, flags
);
4517 * To be able to change p->policy safely, the apropriate
4518 * runqueue lock must be held.
4520 rq
= __task_rq_lock(p
);
4521 /* recheck policy now with rq lock held */
4522 if (unlikely(oldpolicy
!= -1 && oldpolicy
!= p
->policy
)) {
4523 policy
= oldpolicy
= -1;
4524 __task_rq_unlock(rq
);
4525 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
4528 update_rq_clock(rq
);
4529 on_rq
= p
->se
.on_rq
;
4530 running
= task_current(rq
, p
);
4532 deactivate_task(rq
, p
, 0);
4534 p
->sched_class
->put_prev_task(rq
, p
);
4538 __setscheduler(rq
, p
, policy
, param
->sched_priority
);
4542 p
->sched_class
->set_curr_task(rq
);
4544 activate_task(rq
, p
, 0);
4546 check_class_changed(rq
, p
, prev_class
, oldprio
, running
);
4548 __task_rq_unlock(rq
);
4549 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
4551 rt_mutex_adjust_pi(p
);
4555 EXPORT_SYMBOL_GPL(sched_setscheduler
);
4558 do_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
4560 struct sched_param lparam
;
4561 struct task_struct
*p
;
4564 if (!param
|| pid
< 0)
4566 if (copy_from_user(&lparam
, param
, sizeof(struct sched_param
)))
4571 p
= find_process_by_pid(pid
);
4573 retval
= sched_setscheduler(p
, policy
, &lparam
);
4580 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4581 * @pid: the pid in question.
4582 * @policy: new policy.
4583 * @param: structure containing the new RT priority.
4586 sys_sched_setscheduler(pid_t pid
, int policy
, struct sched_param __user
*param
)
4588 /* negative values for policy are not valid */
4592 return do_sched_setscheduler(pid
, policy
, param
);
4596 * sys_sched_setparam - set/change the RT priority of a thread
4597 * @pid: the pid in question.
4598 * @param: structure containing the new RT priority.
4600 asmlinkage
long sys_sched_setparam(pid_t pid
, struct sched_param __user
*param
)
4602 return do_sched_setscheduler(pid
, -1, param
);
4606 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4607 * @pid: the pid in question.
4609 asmlinkage
long sys_sched_getscheduler(pid_t pid
)
4611 struct task_struct
*p
;
4618 read_lock(&tasklist_lock
);
4619 p
= find_process_by_pid(pid
);
4621 retval
= security_task_getscheduler(p
);
4625 read_unlock(&tasklist_lock
);
4630 * sys_sched_getscheduler - get the RT priority of a thread
4631 * @pid: the pid in question.
4632 * @param: structure containing the RT priority.
4634 asmlinkage
long sys_sched_getparam(pid_t pid
, struct sched_param __user
*param
)
4636 struct sched_param lp
;
4637 struct task_struct
*p
;
4640 if (!param
|| pid
< 0)
4643 read_lock(&tasklist_lock
);
4644 p
= find_process_by_pid(pid
);
4649 retval
= security_task_getscheduler(p
);
4653 lp
.sched_priority
= p
->rt_priority
;
4654 read_unlock(&tasklist_lock
);
4657 * This one might sleep, we cannot do it with a spinlock held ...
4659 retval
= copy_to_user(param
, &lp
, sizeof(*param
)) ? -EFAULT
: 0;
4664 read_unlock(&tasklist_lock
);
4668 long sched_setaffinity(pid_t pid
, cpumask_t new_mask
)
4670 cpumask_t cpus_allowed
;
4671 struct task_struct
*p
;
4675 read_lock(&tasklist_lock
);
4677 p
= find_process_by_pid(pid
);
4679 read_unlock(&tasklist_lock
);
4685 * It is not safe to call set_cpus_allowed with the
4686 * tasklist_lock held. We will bump the task_struct's
4687 * usage count and then drop tasklist_lock.
4690 read_unlock(&tasklist_lock
);
4693 if ((current
->euid
!= p
->euid
) && (current
->euid
!= p
->uid
) &&
4694 !capable(CAP_SYS_NICE
))
4697 retval
= security_task_setscheduler(p
, 0, NULL
);
4701 cpus_allowed
= cpuset_cpus_allowed(p
);
4702 cpus_and(new_mask
, new_mask
, cpus_allowed
);
4704 retval
= set_cpus_allowed(p
, new_mask
);
4707 cpus_allowed
= cpuset_cpus_allowed(p
);
4708 if (!cpus_subset(new_mask
, cpus_allowed
)) {
4710 * We must have raced with a concurrent cpuset
4711 * update. Just reset the cpus_allowed to the
4712 * cpuset's cpus_allowed
4714 new_mask
= cpus_allowed
;
4724 static int get_user_cpu_mask(unsigned long __user
*user_mask_ptr
, unsigned len
,
4725 cpumask_t
*new_mask
)
4727 if (len
< sizeof(cpumask_t
)) {
4728 memset(new_mask
, 0, sizeof(cpumask_t
));
4729 } else if (len
> sizeof(cpumask_t
)) {
4730 len
= sizeof(cpumask_t
);
4732 return copy_from_user(new_mask
, user_mask_ptr
, len
) ? -EFAULT
: 0;
4736 * sys_sched_setaffinity - set the cpu affinity of a process
4737 * @pid: pid of the process
4738 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4739 * @user_mask_ptr: user-space pointer to the new cpu mask
4741 asmlinkage
long sys_sched_setaffinity(pid_t pid
, unsigned int len
,
4742 unsigned long __user
*user_mask_ptr
)
4747 retval
= get_user_cpu_mask(user_mask_ptr
, len
, &new_mask
);
4751 return sched_setaffinity(pid
, new_mask
);
4755 * Represents all cpu's present in the system
4756 * In systems capable of hotplug, this map could dynamically grow
4757 * as new cpu's are detected in the system via any platform specific
4758 * method, such as ACPI for e.g.
4761 cpumask_t cpu_present_map __read_mostly
;
4762 EXPORT_SYMBOL(cpu_present_map
);
4765 cpumask_t cpu_online_map __read_mostly
= CPU_MASK_ALL
;
4766 EXPORT_SYMBOL(cpu_online_map
);
4768 cpumask_t cpu_possible_map __read_mostly
= CPU_MASK_ALL
;
4769 EXPORT_SYMBOL(cpu_possible_map
);
4772 long sched_getaffinity(pid_t pid
, cpumask_t
*mask
)
4774 struct task_struct
*p
;
4778 read_lock(&tasklist_lock
);
4781 p
= find_process_by_pid(pid
);
4785 retval
= security_task_getscheduler(p
);
4789 cpus_and(*mask
, p
->cpus_allowed
, cpu_online_map
);
4792 read_unlock(&tasklist_lock
);
4799 * sys_sched_getaffinity - get the cpu affinity of a process
4800 * @pid: pid of the process
4801 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4802 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4804 asmlinkage
long sys_sched_getaffinity(pid_t pid
, unsigned int len
,
4805 unsigned long __user
*user_mask_ptr
)
4810 if (len
< sizeof(cpumask_t
))
4813 ret
= sched_getaffinity(pid
, &mask
);
4817 if (copy_to_user(user_mask_ptr
, &mask
, sizeof(cpumask_t
)))
4820 return sizeof(cpumask_t
);
4824 * sys_sched_yield - yield the current processor to other threads.
4826 * This function yields the current CPU to other tasks. If there are no
4827 * other threads running on this CPU then this function will return.
4829 asmlinkage
long sys_sched_yield(void)
4831 struct rq
*rq
= this_rq_lock();
4833 schedstat_inc(rq
, yld_count
);
4834 current
->sched_class
->yield_task(rq
);
4837 * Since we are going to call schedule() anyway, there's
4838 * no need to preempt or enable interrupts:
4840 __release(rq
->lock
);
4841 spin_release(&rq
->lock
.dep_map
, 1, _THIS_IP_
);
4842 _raw_spin_unlock(&rq
->lock
);
4843 preempt_enable_no_resched();
4850 static void __cond_resched(void)
4852 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4853 __might_sleep(__FILE__
, __LINE__
);
4856 * The BKS might be reacquired before we have dropped
4857 * PREEMPT_ACTIVE, which could trigger a second
4858 * cond_resched() call.
4861 add_preempt_count(PREEMPT_ACTIVE
);
4863 sub_preempt_count(PREEMPT_ACTIVE
);
4864 } while (need_resched());
4867 #if !defined(CONFIG_PREEMPT) || defined(CONFIG_PREEMPT_VOLUNTARY)
4868 int __sched
_cond_resched(void)
4870 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE
) &&
4871 system_state
== SYSTEM_RUNNING
) {
4877 EXPORT_SYMBOL(_cond_resched
);
4881 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4882 * call schedule, and on return reacquire the lock.
4884 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4885 * operations here to prevent schedule() from being called twice (once via
4886 * spin_unlock(), once by hand).
4888 int cond_resched_lock(spinlock_t
*lock
)
4892 if (need_lockbreak(lock
)) {
4898 if (need_resched() && system_state
== SYSTEM_RUNNING
) {
4899 spin_release(&lock
->dep_map
, 1, _THIS_IP_
);
4900 _raw_spin_unlock(lock
);
4901 preempt_enable_no_resched();
4908 EXPORT_SYMBOL(cond_resched_lock
);
4910 int __sched
cond_resched_softirq(void)
4912 BUG_ON(!in_softirq());
4914 if (need_resched() && system_state
== SYSTEM_RUNNING
) {
4922 EXPORT_SYMBOL(cond_resched_softirq
);
4925 * yield - yield the current processor to other threads.
4927 * This is a shortcut for kernel-space yielding - it marks the
4928 * thread runnable and calls sys_sched_yield().
4930 void __sched
yield(void)
4932 set_current_state(TASK_RUNNING
);
4935 EXPORT_SYMBOL(yield
);
4938 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4939 * that process accounting knows that this is a task in IO wait state.
4941 * But don't do that if it is a deliberate, throttling IO wait (this task
4942 * has set its backing_dev_info: the queue against which it should throttle)
4944 void __sched
io_schedule(void)
4946 struct rq
*rq
= &__raw_get_cpu_var(runqueues
);
4948 delayacct_blkio_start();
4949 atomic_inc(&rq
->nr_iowait
);
4951 atomic_dec(&rq
->nr_iowait
);
4952 delayacct_blkio_end();
4954 EXPORT_SYMBOL(io_schedule
);
4956 long __sched
io_schedule_timeout(long timeout
)
4958 struct rq
*rq
= &__raw_get_cpu_var(runqueues
);
4961 delayacct_blkio_start();
4962 atomic_inc(&rq
->nr_iowait
);
4963 ret
= schedule_timeout(timeout
);
4964 atomic_dec(&rq
->nr_iowait
);
4965 delayacct_blkio_end();
4970 * sys_sched_get_priority_max - return maximum RT priority.
4971 * @policy: scheduling class.
4973 * this syscall returns the maximum rt_priority that can be used
4974 * by a given scheduling class.
4976 asmlinkage
long sys_sched_get_priority_max(int policy
)
4983 ret
= MAX_USER_RT_PRIO
-1;
4995 * sys_sched_get_priority_min - return minimum RT priority.
4996 * @policy: scheduling class.
4998 * this syscall returns the minimum rt_priority that can be used
4999 * by a given scheduling class.
5001 asmlinkage
long sys_sched_get_priority_min(int policy
)
5019 * sys_sched_rr_get_interval - return the default timeslice of a process.
5020 * @pid: pid of the process.
5021 * @interval: userspace pointer to the timeslice value.
5023 * this syscall writes the default timeslice value of a given process
5024 * into the user-space timespec buffer. A value of '0' means infinity.
5027 long sys_sched_rr_get_interval(pid_t pid
, struct timespec __user
*interval
)
5029 struct task_struct
*p
;
5030 unsigned int time_slice
;
5038 read_lock(&tasklist_lock
);
5039 p
= find_process_by_pid(pid
);
5043 retval
= security_task_getscheduler(p
);
5048 * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5049 * tasks that are on an otherwise idle runqueue:
5052 if (p
->policy
== SCHED_RR
) {
5053 time_slice
= DEF_TIMESLICE
;
5055 struct sched_entity
*se
= &p
->se
;
5056 unsigned long flags
;
5059 rq
= task_rq_lock(p
, &flags
);
5060 if (rq
->cfs
.load
.weight
)
5061 time_slice
= NS_TO_JIFFIES(sched_slice(&rq
->cfs
, se
));
5062 task_rq_unlock(rq
, &flags
);
5064 read_unlock(&tasklist_lock
);
5065 jiffies_to_timespec(time_slice
, &t
);
5066 retval
= copy_to_user(interval
, &t
, sizeof(t
)) ? -EFAULT
: 0;
5070 read_unlock(&tasklist_lock
);
5074 static const char stat_nam
[] = "RSDTtZX";
5076 void sched_show_task(struct task_struct
*p
)
5078 unsigned long free
= 0;
5081 state
= p
->state
? __ffs(p
->state
) + 1 : 0;
5082 printk(KERN_INFO
"%-13.13s %c", p
->comm
,
5083 state
< sizeof(stat_nam
) - 1 ? stat_nam
[state
] : '?');
5084 #if BITS_PER_LONG == 32
5085 if (state
== TASK_RUNNING
)
5086 printk(KERN_CONT
" running ");
5088 printk(KERN_CONT
" %08lx ", thread_saved_pc(p
));
5090 if (state
== TASK_RUNNING
)
5091 printk(KERN_CONT
" running task ");
5093 printk(KERN_CONT
" %016lx ", thread_saved_pc(p
));
5095 #ifdef CONFIG_DEBUG_STACK_USAGE
5097 unsigned long *n
= end_of_stack(p
);
5100 free
= (unsigned long)n
- (unsigned long)end_of_stack(p
);
5103 printk(KERN_CONT
"%5lu %5d %6d\n", free
,
5104 task_pid_nr(p
), task_pid_nr(p
->real_parent
));
5106 if (state
!= TASK_RUNNING
)
5107 show_stack(p
, NULL
);
5110 void show_state_filter(unsigned long state_filter
)
5112 struct task_struct
*g
, *p
;
5114 #if BITS_PER_LONG == 32
5116 " task PC stack pid father\n");
5119 " task PC stack pid father\n");
5121 read_lock(&tasklist_lock
);
5122 do_each_thread(g
, p
) {
5124 * reset the NMI-timeout, listing all files on a slow
5125 * console might take alot of time:
5127 touch_nmi_watchdog();
5128 if (!state_filter
|| (p
->state
& state_filter
))
5130 } while_each_thread(g
, p
);
5132 touch_all_softlockup_watchdogs();
5134 #ifdef CONFIG_SCHED_DEBUG
5135 sysrq_sched_debug_show();
5137 read_unlock(&tasklist_lock
);
5139 * Only show locks if all tasks are dumped:
5141 if (state_filter
== -1)
5142 debug_show_all_locks();
5145 void __cpuinit
init_idle_bootup_task(struct task_struct
*idle
)
5147 idle
->sched_class
= &idle_sched_class
;
5151 * init_idle - set up an idle thread for a given CPU
5152 * @idle: task in question
5153 * @cpu: cpu the idle task belongs to
5155 * NOTE: this function does not set the idle thread's NEED_RESCHED
5156 * flag, to make booting more robust.
5158 void __cpuinit
init_idle(struct task_struct
*idle
, int cpu
)
5160 struct rq
*rq
= cpu_rq(cpu
);
5161 unsigned long flags
;
5164 idle
->se
.exec_start
= sched_clock();
5166 idle
->prio
= idle
->normal_prio
= MAX_PRIO
;
5167 idle
->cpus_allowed
= cpumask_of_cpu(cpu
);
5168 __set_task_cpu(idle
, cpu
);
5170 spin_lock_irqsave(&rq
->lock
, flags
);
5171 rq
->curr
= rq
->idle
= idle
;
5172 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5175 spin_unlock_irqrestore(&rq
->lock
, flags
);
5177 /* Set the preempt count _outside_ the spinlocks! */
5178 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
5179 task_thread_info(idle
)->preempt_count
= (idle
->lock_depth
>= 0);
5181 task_thread_info(idle
)->preempt_count
= 0;
5184 * The idle tasks have their own, simple scheduling class:
5186 idle
->sched_class
= &idle_sched_class
;
5190 * In a system that switches off the HZ timer nohz_cpu_mask
5191 * indicates which cpus entered this state. This is used
5192 * in the rcu update to wait only for active cpus. For system
5193 * which do not switch off the HZ timer nohz_cpu_mask should
5194 * always be CPU_MASK_NONE.
5196 cpumask_t nohz_cpu_mask
= CPU_MASK_NONE
;
5199 * Increase the granularity value when there are more CPUs,
5200 * because with more CPUs the 'effective latency' as visible
5201 * to users decreases. But the relationship is not linear,
5202 * so pick a second-best guess by going with the log2 of the
5205 * This idea comes from the SD scheduler of Con Kolivas:
5207 static inline void sched_init_granularity(void)
5209 unsigned int factor
= 1 + ilog2(num_online_cpus());
5210 const unsigned long limit
= 200000000;
5212 sysctl_sched_min_granularity
*= factor
;
5213 if (sysctl_sched_min_granularity
> limit
)
5214 sysctl_sched_min_granularity
= limit
;
5216 sysctl_sched_latency
*= factor
;
5217 if (sysctl_sched_latency
> limit
)
5218 sysctl_sched_latency
= limit
;
5220 sysctl_sched_wakeup_granularity
*= factor
;
5221 sysctl_sched_batch_wakeup_granularity
*= factor
;
5226 * This is how migration works:
5228 * 1) we queue a struct migration_req structure in the source CPU's
5229 * runqueue and wake up that CPU's migration thread.
5230 * 2) we down() the locked semaphore => thread blocks.
5231 * 3) migration thread wakes up (implicitly it forces the migrated
5232 * thread off the CPU)
5233 * 4) it gets the migration request and checks whether the migrated
5234 * task is still in the wrong runqueue.
5235 * 5) if it's in the wrong runqueue then the migration thread removes
5236 * it and puts it into the right queue.
5237 * 6) migration thread up()s the semaphore.
5238 * 7) we wake up and the migration is done.
5242 * Change a given task's CPU affinity. Migrate the thread to a
5243 * proper CPU and schedule it away if the CPU it's executing on
5244 * is removed from the allowed bitmask.
5246 * NOTE: the caller must have a valid reference to the task, the
5247 * task must not exit() & deallocate itself prematurely. The
5248 * call is not atomic; no spinlocks may be held.
5250 int set_cpus_allowed(struct task_struct
*p
, cpumask_t new_mask
)
5252 struct migration_req req
;
5253 unsigned long flags
;
5257 rq
= task_rq_lock(p
, &flags
);
5258 if (!cpus_intersects(new_mask
, cpu_online_map
)) {
5263 if (p
->sched_class
->set_cpus_allowed
)
5264 p
->sched_class
->set_cpus_allowed(p
, &new_mask
);
5266 p
->cpus_allowed
= new_mask
;
5267 p
->nr_cpus_allowed
= cpus_weight(new_mask
);
5270 /* Can the task run on the task's current CPU? If so, we're done */
5271 if (cpu_isset(task_cpu(p
), new_mask
))
5274 if (migrate_task(p
, any_online_cpu(new_mask
), &req
)) {
5275 /* Need help from migration thread: drop lock and wait. */
5276 task_rq_unlock(rq
, &flags
);
5277 wake_up_process(rq
->migration_thread
);
5278 wait_for_completion(&req
.done
);
5279 tlb_migrate_finish(p
->mm
);
5283 task_rq_unlock(rq
, &flags
);
5287 EXPORT_SYMBOL_GPL(set_cpus_allowed
);
5290 * Move (not current) task off this cpu, onto dest cpu. We're doing
5291 * this because either it can't run here any more (set_cpus_allowed()
5292 * away from this CPU, or CPU going down), or because we're
5293 * attempting to rebalance this task on exec (sched_exec).
5295 * So we race with normal scheduler movements, but that's OK, as long
5296 * as the task is no longer on this CPU.
5298 * Returns non-zero if task was successfully migrated.
5300 static int __migrate_task(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
5302 struct rq
*rq_dest
, *rq_src
;
5305 if (unlikely(cpu_is_offline(dest_cpu
)))
5308 rq_src
= cpu_rq(src_cpu
);
5309 rq_dest
= cpu_rq(dest_cpu
);
5311 double_rq_lock(rq_src
, rq_dest
);
5312 /* Already moved. */
5313 if (task_cpu(p
) != src_cpu
)
5315 /* Affinity changed (again). */
5316 if (!cpu_isset(dest_cpu
, p
->cpus_allowed
))
5319 on_rq
= p
->se
.on_rq
;
5321 deactivate_task(rq_src
, p
, 0);
5323 set_task_cpu(p
, dest_cpu
);
5325 activate_task(rq_dest
, p
, 0);
5326 check_preempt_curr(rq_dest
, p
);
5330 double_rq_unlock(rq_src
, rq_dest
);
5335 * migration_thread - this is a highprio system thread that performs
5336 * thread migration by bumping thread off CPU then 'pushing' onto
5339 static int migration_thread(void *data
)
5341 int cpu
= (long)data
;
5345 BUG_ON(rq
->migration_thread
!= current
);
5347 set_current_state(TASK_INTERRUPTIBLE
);
5348 while (!kthread_should_stop()) {
5349 struct migration_req
*req
;
5350 struct list_head
*head
;
5352 spin_lock_irq(&rq
->lock
);
5354 if (cpu_is_offline(cpu
)) {
5355 spin_unlock_irq(&rq
->lock
);
5359 if (rq
->active_balance
) {
5360 active_load_balance(rq
, cpu
);
5361 rq
->active_balance
= 0;
5364 head
= &rq
->migration_queue
;
5366 if (list_empty(head
)) {
5367 spin_unlock_irq(&rq
->lock
);
5369 set_current_state(TASK_INTERRUPTIBLE
);
5372 req
= list_entry(head
->next
, struct migration_req
, list
);
5373 list_del_init(head
->next
);
5375 spin_unlock(&rq
->lock
);
5376 __migrate_task(req
->task
, cpu
, req
->dest_cpu
);
5379 complete(&req
->done
);
5381 __set_current_state(TASK_RUNNING
);
5385 /* Wait for kthread_stop */
5386 set_current_state(TASK_INTERRUPTIBLE
);
5387 while (!kthread_should_stop()) {
5389 set_current_state(TASK_INTERRUPTIBLE
);
5391 __set_current_state(TASK_RUNNING
);
5395 #ifdef CONFIG_HOTPLUG_CPU
5397 static int __migrate_task_irq(struct task_struct
*p
, int src_cpu
, int dest_cpu
)
5401 local_irq_disable();
5402 ret
= __migrate_task(p
, src_cpu
, dest_cpu
);
5408 * Figure out where task on dead CPU should go, use force if necessary.
5409 * NOTE: interrupts should be disabled by the caller
5411 static void move_task_off_dead_cpu(int dead_cpu
, struct task_struct
*p
)
5413 unsigned long flags
;
5420 mask
= node_to_cpumask(cpu_to_node(dead_cpu
));
5421 cpus_and(mask
, mask
, p
->cpus_allowed
);
5422 dest_cpu
= any_online_cpu(mask
);
5424 /* On any allowed CPU? */
5425 if (dest_cpu
== NR_CPUS
)
5426 dest_cpu
= any_online_cpu(p
->cpus_allowed
);
5428 /* No more Mr. Nice Guy. */
5429 if (dest_cpu
== NR_CPUS
) {
5430 cpumask_t cpus_allowed
= cpuset_cpus_allowed_locked(p
);
5432 * Try to stay on the same cpuset, where the
5433 * current cpuset may be a subset of all cpus.
5434 * The cpuset_cpus_allowed_locked() variant of
5435 * cpuset_cpus_allowed() will not block. It must be
5436 * called within calls to cpuset_lock/cpuset_unlock.
5438 rq
= task_rq_lock(p
, &flags
);
5439 p
->cpus_allowed
= cpus_allowed
;
5440 dest_cpu
= any_online_cpu(p
->cpus_allowed
);
5441 task_rq_unlock(rq
, &flags
);
5444 * Don't tell them about moving exiting tasks or
5445 * kernel threads (both mm NULL), since they never
5448 if (p
->mm
&& printk_ratelimit()) {
5449 printk(KERN_INFO
"process %d (%s) no "
5450 "longer affine to cpu%d\n",
5451 task_pid_nr(p
), p
->comm
, dead_cpu
);
5454 } while (!__migrate_task_irq(p
, dead_cpu
, dest_cpu
));
5458 * While a dead CPU has no uninterruptible tasks queued at this point,
5459 * it might still have a nonzero ->nr_uninterruptible counter, because
5460 * for performance reasons the counter is not stricly tracking tasks to
5461 * their home CPUs. So we just add the counter to another CPU's counter,
5462 * to keep the global sum constant after CPU-down:
5464 static void migrate_nr_uninterruptible(struct rq
*rq_src
)
5466 struct rq
*rq_dest
= cpu_rq(any_online_cpu(CPU_MASK_ALL
));
5467 unsigned long flags
;
5469 local_irq_save(flags
);
5470 double_rq_lock(rq_src
, rq_dest
);
5471 rq_dest
->nr_uninterruptible
+= rq_src
->nr_uninterruptible
;
5472 rq_src
->nr_uninterruptible
= 0;
5473 double_rq_unlock(rq_src
, rq_dest
);
5474 local_irq_restore(flags
);
5477 /* Run through task list and migrate tasks from the dead cpu. */
5478 static void migrate_live_tasks(int src_cpu
)
5480 struct task_struct
*p
, *t
;
5482 read_lock(&tasklist_lock
);
5484 do_each_thread(t
, p
) {
5488 if (task_cpu(p
) == src_cpu
)
5489 move_task_off_dead_cpu(src_cpu
, p
);
5490 } while_each_thread(t
, p
);
5492 read_unlock(&tasklist_lock
);
5496 * Schedules idle task to be the next runnable task on current CPU.
5497 * It does so by boosting its priority to highest possible.
5498 * Used by CPU offline code.
5500 void sched_idle_next(void)
5502 int this_cpu
= smp_processor_id();
5503 struct rq
*rq
= cpu_rq(this_cpu
);
5504 struct task_struct
*p
= rq
->idle
;
5505 unsigned long flags
;
5507 /* cpu has to be offline */
5508 BUG_ON(cpu_online(this_cpu
));
5511 * Strictly not necessary since rest of the CPUs are stopped by now
5512 * and interrupts disabled on the current cpu.
5514 spin_lock_irqsave(&rq
->lock
, flags
);
5516 __setscheduler(rq
, p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
5518 update_rq_clock(rq
);
5519 activate_task(rq
, p
, 0);
5521 spin_unlock_irqrestore(&rq
->lock
, flags
);
5525 * Ensures that the idle task is using init_mm right before its cpu goes
5528 void idle_task_exit(void)
5530 struct mm_struct
*mm
= current
->active_mm
;
5532 BUG_ON(cpu_online(smp_processor_id()));
5535 switch_mm(mm
, &init_mm
, current
);
5539 /* called under rq->lock with disabled interrupts */
5540 static void migrate_dead(unsigned int dead_cpu
, struct task_struct
*p
)
5542 struct rq
*rq
= cpu_rq(dead_cpu
);
5544 /* Must be exiting, otherwise would be on tasklist. */
5545 BUG_ON(!p
->exit_state
);
5547 /* Cannot have done final schedule yet: would have vanished. */
5548 BUG_ON(p
->state
== TASK_DEAD
);
5553 * Drop lock around migration; if someone else moves it,
5554 * that's OK. No task can be added to this CPU, so iteration is
5557 spin_unlock_irq(&rq
->lock
);
5558 move_task_off_dead_cpu(dead_cpu
, p
);
5559 spin_lock_irq(&rq
->lock
);
5564 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5565 static void migrate_dead_tasks(unsigned int dead_cpu
)
5567 struct rq
*rq
= cpu_rq(dead_cpu
);
5568 struct task_struct
*next
;
5571 if (!rq
->nr_running
)
5573 update_rq_clock(rq
);
5574 next
= pick_next_task(rq
, rq
->curr
);
5577 migrate_dead(dead_cpu
, next
);
5581 #endif /* CONFIG_HOTPLUG_CPU */
5583 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5585 static struct ctl_table sd_ctl_dir
[] = {
5587 .procname
= "sched_domain",
5593 static struct ctl_table sd_ctl_root
[] = {
5595 .ctl_name
= CTL_KERN
,
5596 .procname
= "kernel",
5598 .child
= sd_ctl_dir
,
5603 static struct ctl_table
*sd_alloc_ctl_entry(int n
)
5605 struct ctl_table
*entry
=
5606 kcalloc(n
, sizeof(struct ctl_table
), GFP_KERNEL
);
5611 static void sd_free_ctl_entry(struct ctl_table
**tablep
)
5613 struct ctl_table
*entry
;
5616 * In the intermediate directories, both the child directory and
5617 * procname are dynamically allocated and could fail but the mode
5618 * will always be set. In the lowest directory the names are
5619 * static strings and all have proc handlers.
5621 for (entry
= *tablep
; entry
->mode
; entry
++) {
5623 sd_free_ctl_entry(&entry
->child
);
5624 if (entry
->proc_handler
== NULL
)
5625 kfree(entry
->procname
);
5633 set_table_entry(struct ctl_table
*entry
,
5634 const char *procname
, void *data
, int maxlen
,
5635 mode_t mode
, proc_handler
*proc_handler
)
5637 entry
->procname
= procname
;
5639 entry
->maxlen
= maxlen
;
5641 entry
->proc_handler
= proc_handler
;
5644 static struct ctl_table
*
5645 sd_alloc_ctl_domain_table(struct sched_domain
*sd
)
5647 struct ctl_table
*table
= sd_alloc_ctl_entry(12);
5652 set_table_entry(&table
[0], "min_interval", &sd
->min_interval
,
5653 sizeof(long), 0644, proc_doulongvec_minmax
);
5654 set_table_entry(&table
[1], "max_interval", &sd
->max_interval
,
5655 sizeof(long), 0644, proc_doulongvec_minmax
);
5656 set_table_entry(&table
[2], "busy_idx", &sd
->busy_idx
,
5657 sizeof(int), 0644, proc_dointvec_minmax
);
5658 set_table_entry(&table
[3], "idle_idx", &sd
->idle_idx
,
5659 sizeof(int), 0644, proc_dointvec_minmax
);
5660 set_table_entry(&table
[4], "newidle_idx", &sd
->newidle_idx
,
5661 sizeof(int), 0644, proc_dointvec_minmax
);
5662 set_table_entry(&table
[5], "wake_idx", &sd
->wake_idx
,
5663 sizeof(int), 0644, proc_dointvec_minmax
);
5664 set_table_entry(&table
[6], "forkexec_idx", &sd
->forkexec_idx
,
5665 sizeof(int), 0644, proc_dointvec_minmax
);
5666 set_table_entry(&table
[7], "busy_factor", &sd
->busy_factor
,
5667 sizeof(int), 0644, proc_dointvec_minmax
);
5668 set_table_entry(&table
[8], "imbalance_pct", &sd
->imbalance_pct
,
5669 sizeof(int), 0644, proc_dointvec_minmax
);
5670 set_table_entry(&table
[9], "cache_nice_tries",
5671 &sd
->cache_nice_tries
,
5672 sizeof(int), 0644, proc_dointvec_minmax
);
5673 set_table_entry(&table
[10], "flags", &sd
->flags
,
5674 sizeof(int), 0644, proc_dointvec_minmax
);
5675 /* &table[11] is terminator */
5680 static ctl_table
*sd_alloc_ctl_cpu_table(int cpu
)
5682 struct ctl_table
*entry
, *table
;
5683 struct sched_domain
*sd
;
5684 int domain_num
= 0, i
;
5687 for_each_domain(cpu
, sd
)
5689 entry
= table
= sd_alloc_ctl_entry(domain_num
+ 1);
5694 for_each_domain(cpu
, sd
) {
5695 snprintf(buf
, 32, "domain%d", i
);
5696 entry
->procname
= kstrdup(buf
, GFP_KERNEL
);
5698 entry
->child
= sd_alloc_ctl_domain_table(sd
);
5705 static struct ctl_table_header
*sd_sysctl_header
;
5706 static void register_sched_domain_sysctl(void)
5708 int i
, cpu_num
= num_online_cpus();
5709 struct ctl_table
*entry
= sd_alloc_ctl_entry(cpu_num
+ 1);
5712 WARN_ON(sd_ctl_dir
[0].child
);
5713 sd_ctl_dir
[0].child
= entry
;
5718 for_each_online_cpu(i
) {
5719 snprintf(buf
, 32, "cpu%d", i
);
5720 entry
->procname
= kstrdup(buf
, GFP_KERNEL
);
5722 entry
->child
= sd_alloc_ctl_cpu_table(i
);
5726 WARN_ON(sd_sysctl_header
);
5727 sd_sysctl_header
= register_sysctl_table(sd_ctl_root
);
5730 /* may be called multiple times per register */
5731 static void unregister_sched_domain_sysctl(void)
5733 if (sd_sysctl_header
)
5734 unregister_sysctl_table(sd_sysctl_header
);
5735 sd_sysctl_header
= NULL
;
5736 if (sd_ctl_dir
[0].child
)
5737 sd_free_ctl_entry(&sd_ctl_dir
[0].child
);
5740 static void register_sched_domain_sysctl(void)
5743 static void unregister_sched_domain_sysctl(void)
5749 * migration_call - callback that gets triggered when a CPU is added.
5750 * Here we can start up the necessary migration thread for the new CPU.
5752 static int __cpuinit
5753 migration_call(struct notifier_block
*nfb
, unsigned long action
, void *hcpu
)
5755 struct task_struct
*p
;
5756 int cpu
= (long)hcpu
;
5757 unsigned long flags
;
5762 case CPU_UP_PREPARE
:
5763 case CPU_UP_PREPARE_FROZEN
:
5764 p
= kthread_create(migration_thread
, hcpu
, "migration/%d", cpu
);
5767 kthread_bind(p
, cpu
);
5768 /* Must be high prio: stop_machine expects to yield to it. */
5769 rq
= task_rq_lock(p
, &flags
);
5770 __setscheduler(rq
, p
, SCHED_FIFO
, MAX_RT_PRIO
-1);
5771 task_rq_unlock(rq
, &flags
);
5772 cpu_rq(cpu
)->migration_thread
= p
;
5776 case CPU_ONLINE_FROZEN
:
5777 /* Strictly unnecessary, as first user will wake it. */
5778 wake_up_process(cpu_rq(cpu
)->migration_thread
);
5780 /* Update our root-domain */
5782 spin_lock_irqsave(&rq
->lock
, flags
);
5784 BUG_ON(!cpu_isset(cpu
, rq
->rd
->span
));
5785 cpu_set(cpu
, rq
->rd
->online
);
5787 spin_unlock_irqrestore(&rq
->lock
, flags
);
5790 #ifdef CONFIG_HOTPLUG_CPU
5791 case CPU_UP_CANCELED
:
5792 case CPU_UP_CANCELED_FROZEN
:
5793 if (!cpu_rq(cpu
)->migration_thread
)
5795 /* Unbind it from offline cpu so it can run. Fall thru. */
5796 kthread_bind(cpu_rq(cpu
)->migration_thread
,
5797 any_online_cpu(cpu_online_map
));
5798 kthread_stop(cpu_rq(cpu
)->migration_thread
);
5799 cpu_rq(cpu
)->migration_thread
= NULL
;
5803 case CPU_DEAD_FROZEN
:
5804 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
5805 migrate_live_tasks(cpu
);
5807 kthread_stop(rq
->migration_thread
);
5808 rq
->migration_thread
= NULL
;
5809 /* Idle task back to normal (off runqueue, low prio) */
5810 spin_lock_irq(&rq
->lock
);
5811 update_rq_clock(rq
);
5812 deactivate_task(rq
, rq
->idle
, 0);
5813 rq
->idle
->static_prio
= MAX_PRIO
;
5814 __setscheduler(rq
, rq
->idle
, SCHED_NORMAL
, 0);
5815 rq
->idle
->sched_class
= &idle_sched_class
;
5816 migrate_dead_tasks(cpu
);
5817 spin_unlock_irq(&rq
->lock
);
5819 migrate_nr_uninterruptible(rq
);
5820 BUG_ON(rq
->nr_running
!= 0);
5823 * No need to migrate the tasks: it was best-effort if
5824 * they didn't take sched_hotcpu_mutex. Just wake up
5827 spin_lock_irq(&rq
->lock
);
5828 while (!list_empty(&rq
->migration_queue
)) {
5829 struct migration_req
*req
;
5831 req
= list_entry(rq
->migration_queue
.next
,
5832 struct migration_req
, list
);
5833 list_del_init(&req
->list
);
5834 complete(&req
->done
);
5836 spin_unlock_irq(&rq
->lock
);
5839 case CPU_DOWN_PREPARE
:
5840 /* Update our root-domain */
5842 spin_lock_irqsave(&rq
->lock
, flags
);
5844 BUG_ON(!cpu_isset(cpu
, rq
->rd
->span
));
5845 cpu_clear(cpu
, rq
->rd
->online
);
5847 spin_unlock_irqrestore(&rq
->lock
, flags
);
5854 /* Register at highest priority so that task migration (migrate_all_tasks)
5855 * happens before everything else.
5857 static struct notifier_block __cpuinitdata migration_notifier
= {
5858 .notifier_call
= migration_call
,
5862 void __init
migration_init(void)
5864 void *cpu
= (void *)(long)smp_processor_id();
5867 /* Start one for the boot CPU: */
5868 err
= migration_call(&migration_notifier
, CPU_UP_PREPARE
, cpu
);
5869 BUG_ON(err
== NOTIFY_BAD
);
5870 migration_call(&migration_notifier
, CPU_ONLINE
, cpu
);
5871 register_cpu_notifier(&migration_notifier
);
5877 /* Number of possible processor ids */
5878 int nr_cpu_ids __read_mostly
= NR_CPUS
;
5879 EXPORT_SYMBOL(nr_cpu_ids
);
5881 #ifdef CONFIG_SCHED_DEBUG
5883 static int sched_domain_debug_one(struct sched_domain
*sd
, int cpu
, int level
)
5885 struct sched_group
*group
= sd
->groups
;
5886 cpumask_t groupmask
;
5889 cpumask_scnprintf(str
, NR_CPUS
, sd
->span
);
5890 cpus_clear(groupmask
);
5892 printk(KERN_DEBUG
"%*s domain %d: ", level
, "", level
);
5894 if (!(sd
->flags
& SD_LOAD_BALANCE
)) {
5895 printk("does not load-balance\n");
5897 printk(KERN_ERR
"ERROR: !SD_LOAD_BALANCE domain"
5902 printk(KERN_CONT
"span %s\n", str
);
5904 if (!cpu_isset(cpu
, sd
->span
)) {
5905 printk(KERN_ERR
"ERROR: domain->span does not contain "
5908 if (!cpu_isset(cpu
, group
->cpumask
)) {
5909 printk(KERN_ERR
"ERROR: domain->groups does not contain"
5913 printk(KERN_DEBUG
"%*s groups:", level
+ 1, "");
5917 printk(KERN_ERR
"ERROR: group is NULL\n");
5921 if (!group
->__cpu_power
) {
5922 printk(KERN_CONT
"\n");
5923 printk(KERN_ERR
"ERROR: domain->cpu_power not "
5928 if (!cpus_weight(group
->cpumask
)) {
5929 printk(KERN_CONT
"\n");
5930 printk(KERN_ERR
"ERROR: empty group\n");
5934 if (cpus_intersects(groupmask
, group
->cpumask
)) {
5935 printk(KERN_CONT
"\n");
5936 printk(KERN_ERR
"ERROR: repeated CPUs\n");
5940 cpus_or(groupmask
, groupmask
, group
->cpumask
);
5942 cpumask_scnprintf(str
, NR_CPUS
, group
->cpumask
);
5943 printk(KERN_CONT
" %s", str
);
5945 group
= group
->next
;
5946 } while (group
!= sd
->groups
);
5947 printk(KERN_CONT
"\n");
5949 if (!cpus_equal(sd
->span
, groupmask
))
5950 printk(KERN_ERR
"ERROR: groups don't span domain->span\n");
5952 if (sd
->parent
&& !cpus_subset(groupmask
, sd
->parent
->span
))
5953 printk(KERN_ERR
"ERROR: parent span is not a superset "
5954 "of domain->span\n");
5958 static void sched_domain_debug(struct sched_domain
*sd
, int cpu
)
5963 printk(KERN_DEBUG
"CPU%d attaching NULL sched-domain.\n", cpu
);
5967 printk(KERN_DEBUG
"CPU%d attaching sched-domain:\n", cpu
);
5970 if (sched_domain_debug_one(sd
, cpu
, level
))
5979 # define sched_domain_debug(sd, cpu) do { } while (0)
5982 static int sd_degenerate(struct sched_domain
*sd
)
5984 if (cpus_weight(sd
->span
) == 1)
5987 /* Following flags need at least 2 groups */
5988 if (sd
->flags
& (SD_LOAD_BALANCE
|
5989 SD_BALANCE_NEWIDLE
|
5993 SD_SHARE_PKG_RESOURCES
)) {
5994 if (sd
->groups
!= sd
->groups
->next
)
5998 /* Following flags don't use groups */
5999 if (sd
->flags
& (SD_WAKE_IDLE
|
6008 sd_parent_degenerate(struct sched_domain
*sd
, struct sched_domain
*parent
)
6010 unsigned long cflags
= sd
->flags
, pflags
= parent
->flags
;
6012 if (sd_degenerate(parent
))
6015 if (!cpus_equal(sd
->span
, parent
->span
))
6018 /* Does parent contain flags not in child? */
6019 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6020 if (cflags
& SD_WAKE_AFFINE
)
6021 pflags
&= ~SD_WAKE_BALANCE
;
6022 /* Flags needing groups don't count if only 1 group in parent */
6023 if (parent
->groups
== parent
->groups
->next
) {
6024 pflags
&= ~(SD_LOAD_BALANCE
|
6025 SD_BALANCE_NEWIDLE
|
6029 SD_SHARE_PKG_RESOURCES
);
6031 if (~cflags
& pflags
)
6037 static void rq_attach_root(struct rq
*rq
, struct root_domain
*rd
)
6039 unsigned long flags
;
6040 const struct sched_class
*class;
6042 spin_lock_irqsave(&rq
->lock
, flags
);
6045 struct root_domain
*old_rd
= rq
->rd
;
6047 for (class = sched_class_highest
; class; class = class->next
) {
6048 if (class->leave_domain
)
6049 class->leave_domain(rq
);
6052 cpu_clear(rq
->cpu
, old_rd
->span
);
6053 cpu_clear(rq
->cpu
, old_rd
->online
);
6055 if (atomic_dec_and_test(&old_rd
->refcount
))
6059 atomic_inc(&rd
->refcount
);
6062 cpu_set(rq
->cpu
, rd
->span
);
6063 if (cpu_isset(rq
->cpu
, cpu_online_map
))
6064 cpu_set(rq
->cpu
, rd
->online
);
6066 for (class = sched_class_highest
; class; class = class->next
) {
6067 if (class->join_domain
)
6068 class->join_domain(rq
);
6071 spin_unlock_irqrestore(&rq
->lock
, flags
);
6074 static void init_rootdomain(struct root_domain
*rd
)
6076 memset(rd
, 0, sizeof(*rd
));
6078 cpus_clear(rd
->span
);
6079 cpus_clear(rd
->online
);
6082 static void init_defrootdomain(void)
6084 init_rootdomain(&def_root_domain
);
6085 atomic_set(&def_root_domain
.refcount
, 1);
6088 static struct root_domain
*alloc_rootdomain(void)
6090 struct root_domain
*rd
;
6092 rd
= kmalloc(sizeof(*rd
), GFP_KERNEL
);
6096 init_rootdomain(rd
);
6102 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6103 * hold the hotplug lock.
6106 cpu_attach_domain(struct sched_domain
*sd
, struct root_domain
*rd
, int cpu
)
6108 struct rq
*rq
= cpu_rq(cpu
);
6109 struct sched_domain
*tmp
;
6111 /* Remove the sched domains which do not contribute to scheduling. */
6112 for (tmp
= sd
; tmp
; tmp
= tmp
->parent
) {
6113 struct sched_domain
*parent
= tmp
->parent
;
6116 if (sd_parent_degenerate(tmp
, parent
)) {
6117 tmp
->parent
= parent
->parent
;
6119 parent
->parent
->child
= tmp
;
6123 if (sd
&& sd_degenerate(sd
)) {
6129 sched_domain_debug(sd
, cpu
);
6131 rq_attach_root(rq
, rd
);
6132 rcu_assign_pointer(rq
->sd
, sd
);
6135 /* cpus with isolated domains */
6136 static cpumask_t cpu_isolated_map
= CPU_MASK_NONE
;
6138 /* Setup the mask of cpus configured for isolated domains */
6139 static int __init
isolated_cpu_setup(char *str
)
6141 int ints
[NR_CPUS
], i
;
6143 str
= get_options(str
, ARRAY_SIZE(ints
), ints
);
6144 cpus_clear(cpu_isolated_map
);
6145 for (i
= 1; i
<= ints
[0]; i
++)
6146 if (ints
[i
] < NR_CPUS
)
6147 cpu_set(ints
[i
], cpu_isolated_map
);
6151 __setup("isolcpus=", isolated_cpu_setup
);
6154 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6155 * to a function which identifies what group(along with sched group) a CPU
6156 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6157 * (due to the fact that we keep track of groups covered with a cpumask_t).
6159 * init_sched_build_groups will build a circular linked list of the groups
6160 * covered by the given span, and will set each group's ->cpumask correctly,
6161 * and ->cpu_power to 0.
6164 init_sched_build_groups(cpumask_t span
, const cpumask_t
*cpu_map
,
6165 int (*group_fn
)(int cpu
, const cpumask_t
*cpu_map
,
6166 struct sched_group
**sg
))
6168 struct sched_group
*first
= NULL
, *last
= NULL
;
6169 cpumask_t covered
= CPU_MASK_NONE
;
6172 for_each_cpu_mask(i
, span
) {
6173 struct sched_group
*sg
;
6174 int group
= group_fn(i
, cpu_map
, &sg
);
6177 if (cpu_isset(i
, covered
))
6180 sg
->cpumask
= CPU_MASK_NONE
;
6181 sg
->__cpu_power
= 0;
6183 for_each_cpu_mask(j
, span
) {
6184 if (group_fn(j
, cpu_map
, NULL
) != group
)
6187 cpu_set(j
, covered
);
6188 cpu_set(j
, sg
->cpumask
);
6199 #define SD_NODES_PER_DOMAIN 16
6204 * find_next_best_node - find the next node to include in a sched_domain
6205 * @node: node whose sched_domain we're building
6206 * @used_nodes: nodes already in the sched_domain
6208 * Find the next node to include in a given scheduling domain. Simply
6209 * finds the closest node not already in the @used_nodes map.
6211 * Should use nodemask_t.
6213 static int find_next_best_node(int node
, unsigned long *used_nodes
)
6215 int i
, n
, val
, min_val
, best_node
= 0;
6219 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6220 /* Start at @node */
6221 n
= (node
+ i
) % MAX_NUMNODES
;
6223 if (!nr_cpus_node(n
))
6226 /* Skip already used nodes */
6227 if (test_bit(n
, used_nodes
))
6230 /* Simple min distance search */
6231 val
= node_distance(node
, n
);
6233 if (val
< min_val
) {
6239 set_bit(best_node
, used_nodes
);
6244 * sched_domain_node_span - get a cpumask for a node's sched_domain
6245 * @node: node whose cpumask we're constructing
6246 * @size: number of nodes to include in this span
6248 * Given a node, construct a good cpumask for its sched_domain to span. It
6249 * should be one that prevents unnecessary balancing, but also spreads tasks
6252 static cpumask_t
sched_domain_node_span(int node
)
6254 DECLARE_BITMAP(used_nodes
, MAX_NUMNODES
);
6255 cpumask_t span
, nodemask
;
6259 bitmap_zero(used_nodes
, MAX_NUMNODES
);
6261 nodemask
= node_to_cpumask(node
);
6262 cpus_or(span
, span
, nodemask
);
6263 set_bit(node
, used_nodes
);
6265 for (i
= 1; i
< SD_NODES_PER_DOMAIN
; i
++) {
6266 int next_node
= find_next_best_node(node
, used_nodes
);
6268 nodemask
= node_to_cpumask(next_node
);
6269 cpus_or(span
, span
, nodemask
);
6276 int sched_smt_power_savings
= 0, sched_mc_power_savings
= 0;
6279 * SMT sched-domains:
6281 #ifdef CONFIG_SCHED_SMT
6282 static DEFINE_PER_CPU(struct sched_domain
, cpu_domains
);
6283 static DEFINE_PER_CPU(struct sched_group
, sched_group_cpus
);
6286 cpu_to_cpu_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
)
6289 *sg
= &per_cpu(sched_group_cpus
, cpu
);
6295 * multi-core sched-domains:
6297 #ifdef CONFIG_SCHED_MC
6298 static DEFINE_PER_CPU(struct sched_domain
, core_domains
);
6299 static DEFINE_PER_CPU(struct sched_group
, sched_group_core
);
6302 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6304 cpu_to_core_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
)
6307 cpumask_t mask
= per_cpu(cpu_sibling_map
, cpu
);
6308 cpus_and(mask
, mask
, *cpu_map
);
6309 group
= first_cpu(mask
);
6311 *sg
= &per_cpu(sched_group_core
, group
);
6314 #elif defined(CONFIG_SCHED_MC)
6316 cpu_to_core_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
)
6319 *sg
= &per_cpu(sched_group_core
, cpu
);
6324 static DEFINE_PER_CPU(struct sched_domain
, phys_domains
);
6325 static DEFINE_PER_CPU(struct sched_group
, sched_group_phys
);
6328 cpu_to_phys_group(int cpu
, const cpumask_t
*cpu_map
, struct sched_group
**sg
)
6331 #ifdef CONFIG_SCHED_MC
6332 cpumask_t mask
= cpu_coregroup_map(cpu
);
6333 cpus_and(mask
, mask
, *cpu_map
);
6334 group
= first_cpu(mask
);
6335 #elif defined(CONFIG_SCHED_SMT)
6336 cpumask_t mask
= per_cpu(cpu_sibling_map
, cpu
);
6337 cpus_and(mask
, mask
, *cpu_map
);
6338 group
= first_cpu(mask
);
6343 *sg
= &per_cpu(sched_group_phys
, group
);
6349 * The init_sched_build_groups can't handle what we want to do with node
6350 * groups, so roll our own. Now each node has its own list of groups which
6351 * gets dynamically allocated.
6353 static DEFINE_PER_CPU(struct sched_domain
, node_domains
);
6354 static struct sched_group
**sched_group_nodes_bycpu
[NR_CPUS
];
6356 static DEFINE_PER_CPU(struct sched_domain
, allnodes_domains
);
6357 static DEFINE_PER_CPU(struct sched_group
, sched_group_allnodes
);
6359 static int cpu_to_allnodes_group(int cpu
, const cpumask_t
*cpu_map
,
6360 struct sched_group
**sg
)
6362 cpumask_t nodemask
= node_to_cpumask(cpu_to_node(cpu
));
6365 cpus_and(nodemask
, nodemask
, *cpu_map
);
6366 group
= first_cpu(nodemask
);
6369 *sg
= &per_cpu(sched_group_allnodes
, group
);
6373 static void init_numa_sched_groups_power(struct sched_group
*group_head
)
6375 struct sched_group
*sg
= group_head
;
6381 for_each_cpu_mask(j
, sg
->cpumask
) {
6382 struct sched_domain
*sd
;
6384 sd
= &per_cpu(phys_domains
, j
);
6385 if (j
!= first_cpu(sd
->groups
->cpumask
)) {
6387 * Only add "power" once for each
6393 sg_inc_cpu_power(sg
, sd
->groups
->__cpu_power
);
6396 } while (sg
!= group_head
);
6401 /* Free memory allocated for various sched_group structures */
6402 static void free_sched_groups(const cpumask_t
*cpu_map
)
6406 for_each_cpu_mask(cpu
, *cpu_map
) {
6407 struct sched_group
**sched_group_nodes
6408 = sched_group_nodes_bycpu
[cpu
];
6410 if (!sched_group_nodes
)
6413 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6414 cpumask_t nodemask
= node_to_cpumask(i
);
6415 struct sched_group
*oldsg
, *sg
= sched_group_nodes
[i
];
6417 cpus_and(nodemask
, nodemask
, *cpu_map
);
6418 if (cpus_empty(nodemask
))
6428 if (oldsg
!= sched_group_nodes
[i
])
6431 kfree(sched_group_nodes
);
6432 sched_group_nodes_bycpu
[cpu
] = NULL
;
6436 static void free_sched_groups(const cpumask_t
*cpu_map
)
6442 * Initialize sched groups cpu_power.
6444 * cpu_power indicates the capacity of sched group, which is used while
6445 * distributing the load between different sched groups in a sched domain.
6446 * Typically cpu_power for all the groups in a sched domain will be same unless
6447 * there are asymmetries in the topology. If there are asymmetries, group
6448 * having more cpu_power will pickup more load compared to the group having
6451 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
6452 * the maximum number of tasks a group can handle in the presence of other idle
6453 * or lightly loaded groups in the same sched domain.
6455 static void init_sched_groups_power(int cpu
, struct sched_domain
*sd
)
6457 struct sched_domain
*child
;
6458 struct sched_group
*group
;
6460 WARN_ON(!sd
|| !sd
->groups
);
6462 if (cpu
!= first_cpu(sd
->groups
->cpumask
))
6467 sd
->groups
->__cpu_power
= 0;
6470 * For perf policy, if the groups in child domain share resources
6471 * (for example cores sharing some portions of the cache hierarchy
6472 * or SMT), then set this domain groups cpu_power such that each group
6473 * can handle only one task, when there are other idle groups in the
6474 * same sched domain.
6476 if (!child
|| (!(sd
->flags
& SD_POWERSAVINGS_BALANCE
) &&
6478 (SD_SHARE_CPUPOWER
| SD_SHARE_PKG_RESOURCES
)))) {
6479 sg_inc_cpu_power(sd
->groups
, SCHED_LOAD_SCALE
);
6484 * add cpu_power of each child group to this groups cpu_power
6486 group
= child
->groups
;
6488 sg_inc_cpu_power(sd
->groups
, group
->__cpu_power
);
6489 group
= group
->next
;
6490 } while (group
!= child
->groups
);
6494 * Build sched domains for a given set of cpus and attach the sched domains
6495 * to the individual cpus
6497 static int build_sched_domains(const cpumask_t
*cpu_map
)
6500 struct root_domain
*rd
;
6502 struct sched_group
**sched_group_nodes
= NULL
;
6503 int sd_allnodes
= 0;
6506 * Allocate the per-node list of sched groups
6508 sched_group_nodes
= kcalloc(MAX_NUMNODES
, sizeof(struct sched_group
*),
6510 if (!sched_group_nodes
) {
6511 printk(KERN_WARNING
"Can not alloc sched group node list\n");
6514 sched_group_nodes_bycpu
[first_cpu(*cpu_map
)] = sched_group_nodes
;
6517 rd
= alloc_rootdomain();
6519 printk(KERN_WARNING
"Cannot alloc root domain\n");
6524 * Set up domains for cpus specified by the cpu_map.
6526 for_each_cpu_mask(i
, *cpu_map
) {
6527 struct sched_domain
*sd
= NULL
, *p
;
6528 cpumask_t nodemask
= node_to_cpumask(cpu_to_node(i
));
6530 cpus_and(nodemask
, nodemask
, *cpu_map
);
6533 if (cpus_weight(*cpu_map
) >
6534 SD_NODES_PER_DOMAIN
*cpus_weight(nodemask
)) {
6535 sd
= &per_cpu(allnodes_domains
, i
);
6536 *sd
= SD_ALLNODES_INIT
;
6537 sd
->span
= *cpu_map
;
6538 cpu_to_allnodes_group(i
, cpu_map
, &sd
->groups
);
6544 sd
= &per_cpu(node_domains
, i
);
6546 sd
->span
= sched_domain_node_span(cpu_to_node(i
));
6550 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6554 sd
= &per_cpu(phys_domains
, i
);
6556 sd
->span
= nodemask
;
6560 cpu_to_phys_group(i
, cpu_map
, &sd
->groups
);
6562 #ifdef CONFIG_SCHED_MC
6564 sd
= &per_cpu(core_domains
, i
);
6566 sd
->span
= cpu_coregroup_map(i
);
6567 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6570 cpu_to_core_group(i
, cpu_map
, &sd
->groups
);
6573 #ifdef CONFIG_SCHED_SMT
6575 sd
= &per_cpu(cpu_domains
, i
);
6576 *sd
= SD_SIBLING_INIT
;
6577 sd
->span
= per_cpu(cpu_sibling_map
, i
);
6578 cpus_and(sd
->span
, sd
->span
, *cpu_map
);
6581 cpu_to_cpu_group(i
, cpu_map
, &sd
->groups
);
6585 #ifdef CONFIG_SCHED_SMT
6586 /* Set up CPU (sibling) groups */
6587 for_each_cpu_mask(i
, *cpu_map
) {
6588 cpumask_t this_sibling_map
= per_cpu(cpu_sibling_map
, i
);
6589 cpus_and(this_sibling_map
, this_sibling_map
, *cpu_map
);
6590 if (i
!= first_cpu(this_sibling_map
))
6593 init_sched_build_groups(this_sibling_map
, cpu_map
,
6598 #ifdef CONFIG_SCHED_MC
6599 /* Set up multi-core groups */
6600 for_each_cpu_mask(i
, *cpu_map
) {
6601 cpumask_t this_core_map
= cpu_coregroup_map(i
);
6602 cpus_and(this_core_map
, this_core_map
, *cpu_map
);
6603 if (i
!= first_cpu(this_core_map
))
6605 init_sched_build_groups(this_core_map
, cpu_map
,
6606 &cpu_to_core_group
);
6610 /* Set up physical groups */
6611 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6612 cpumask_t nodemask
= node_to_cpumask(i
);
6614 cpus_and(nodemask
, nodemask
, *cpu_map
);
6615 if (cpus_empty(nodemask
))
6618 init_sched_build_groups(nodemask
, cpu_map
, &cpu_to_phys_group
);
6622 /* Set up node groups */
6624 init_sched_build_groups(*cpu_map
, cpu_map
,
6625 &cpu_to_allnodes_group
);
6627 for (i
= 0; i
< MAX_NUMNODES
; i
++) {
6628 /* Set up node groups */
6629 struct sched_group
*sg
, *prev
;
6630 cpumask_t nodemask
= node_to_cpumask(i
);
6631 cpumask_t domainspan
;
6632 cpumask_t covered
= CPU_MASK_NONE
;
6635 cpus_and(nodemask
, nodemask
, *cpu_map
);
6636 if (cpus_empty(nodemask
)) {
6637 sched_group_nodes
[i
] = NULL
;
6641 domainspan
= sched_domain_node_span(i
);
6642 cpus_and(domainspan
, domainspan
, *cpu_map
);
6644 sg
= kmalloc_node(sizeof(struct sched_group
), GFP_KERNEL
, i
);
6646 printk(KERN_WARNING
"Can not alloc domain group for "
6650 sched_group_nodes
[i
] = sg
;
6651 for_each_cpu_mask(j
, nodemask
) {
6652 struct sched_domain
*sd
;
6654 sd
= &per_cpu(node_domains
, j
);
6657 sg
->__cpu_power
= 0;
6658 sg
->cpumask
= nodemask
;
6660 cpus_or(covered
, covered
, nodemask
);
6663 for (j
= 0; j
< MAX_NUMNODES
; j
++) {
6664 cpumask_t tmp
, notcovered
;
6665 int n
= (i
+ j
) % MAX_NUMNODES
;
6667 cpus_complement(notcovered
, covered
);
6668 cpus_and(tmp
, notcovered
, *cpu_map
);
6669 cpus_and(tmp
, tmp
, domainspan
);
6670 if (cpus_empty(tmp
))
6673 nodemask
= node_to_cpumask(n
);
6674 cpus_and(tmp
, tmp
, nodemask
);
6675 if (cpus_empty(tmp
))
6678 sg
= kmalloc_node(sizeof(struct sched_group
),
6682 "Can not alloc domain group for node %d\n", j
);
6685 sg
->__cpu_power
= 0;
6687 sg
->next
= prev
->next
;
6688 cpus_or(covered
, covered
, tmp
);
6695 /* Calculate CPU power for physical packages and nodes */
6696 #ifdef CONFIG_SCHED_SMT
6697 for_each_cpu_mask(i
, *cpu_map
) {
6698 struct sched_domain
*sd
= &per_cpu(cpu_domains
, i
);
6700 init_sched_groups_power(i
, sd
);
6703 #ifdef CONFIG_SCHED_MC
6704 for_each_cpu_mask(i
, *cpu_map
) {
6705 struct sched_domain
*sd
= &per_cpu(core_domains
, i
);
6707 init_sched_groups_power(i
, sd
);
6711 for_each_cpu_mask(i
, *cpu_map
) {
6712 struct sched_domain
*sd
= &per_cpu(phys_domains
, i
);
6714 init_sched_groups_power(i
, sd
);
6718 for (i
= 0; i
< MAX_NUMNODES
; i
++)
6719 init_numa_sched_groups_power(sched_group_nodes
[i
]);
6722 struct sched_group
*sg
;
6724 cpu_to_allnodes_group(first_cpu(*cpu_map
), cpu_map
, &sg
);
6725 init_numa_sched_groups_power(sg
);
6729 /* Attach the domains */
6730 for_each_cpu_mask(i
, *cpu_map
) {
6731 struct sched_domain
*sd
;
6732 #ifdef CONFIG_SCHED_SMT
6733 sd
= &per_cpu(cpu_domains
, i
);
6734 #elif defined(CONFIG_SCHED_MC)
6735 sd
= &per_cpu(core_domains
, i
);
6737 sd
= &per_cpu(phys_domains
, i
);
6739 cpu_attach_domain(sd
, rd
, i
);
6746 free_sched_groups(cpu_map
);
6751 static cpumask_t
*doms_cur
; /* current sched domains */
6752 static int ndoms_cur
; /* number of sched domains in 'doms_cur' */
6755 * Special case: If a kmalloc of a doms_cur partition (array of
6756 * cpumask_t) fails, then fallback to a single sched domain,
6757 * as determined by the single cpumask_t fallback_doms.
6759 static cpumask_t fallback_doms
;
6762 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6763 * For now this just excludes isolated cpus, but could be used to
6764 * exclude other special cases in the future.
6766 static int arch_init_sched_domains(const cpumask_t
*cpu_map
)
6771 doms_cur
= kmalloc(sizeof(cpumask_t
), GFP_KERNEL
);
6773 doms_cur
= &fallback_doms
;
6774 cpus_andnot(*doms_cur
, *cpu_map
, cpu_isolated_map
);
6775 err
= build_sched_domains(doms_cur
);
6776 register_sched_domain_sysctl();
6781 static void arch_destroy_sched_domains(const cpumask_t
*cpu_map
)
6783 free_sched_groups(cpu_map
);
6787 * Detach sched domains from a group of cpus specified in cpu_map
6788 * These cpus will now be attached to the NULL domain
6790 static void detach_destroy_domains(const cpumask_t
*cpu_map
)
6794 unregister_sched_domain_sysctl();
6796 for_each_cpu_mask(i
, *cpu_map
)
6797 cpu_attach_domain(NULL
, &def_root_domain
, i
);
6798 synchronize_sched();
6799 arch_destroy_sched_domains(cpu_map
);
6803 * Partition sched domains as specified by the 'ndoms_new'
6804 * cpumasks in the array doms_new[] of cpumasks. This compares
6805 * doms_new[] to the current sched domain partitioning, doms_cur[].
6806 * It destroys each deleted domain and builds each new domain.
6808 * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
6809 * The masks don't intersect (don't overlap.) We should setup one
6810 * sched domain for each mask. CPUs not in any of the cpumasks will
6811 * not be load balanced. If the same cpumask appears both in the
6812 * current 'doms_cur' domains and in the new 'doms_new', we can leave
6815 * The passed in 'doms_new' should be kmalloc'd. This routine takes
6816 * ownership of it and will kfree it when done with it. If the caller
6817 * failed the kmalloc call, then it can pass in doms_new == NULL,
6818 * and partition_sched_domains() will fallback to the single partition
6821 * Call with hotplug lock held
6823 void partition_sched_domains(int ndoms_new
, cpumask_t
*doms_new
)
6829 /* always unregister in case we don't destroy any domains */
6830 unregister_sched_domain_sysctl();
6832 if (doms_new
== NULL
) {
6834 doms_new
= &fallback_doms
;
6835 cpus_andnot(doms_new
[0], cpu_online_map
, cpu_isolated_map
);
6838 /* Destroy deleted domains */
6839 for (i
= 0; i
< ndoms_cur
; i
++) {
6840 for (j
= 0; j
< ndoms_new
; j
++) {
6841 if (cpus_equal(doms_cur
[i
], doms_new
[j
]))
6844 /* no match - a current sched domain not in new doms_new[] */
6845 detach_destroy_domains(doms_cur
+ i
);
6850 /* Build new domains */
6851 for (i
= 0; i
< ndoms_new
; i
++) {
6852 for (j
= 0; j
< ndoms_cur
; j
++) {
6853 if (cpus_equal(doms_new
[i
], doms_cur
[j
]))
6856 /* no match - add a new doms_new */
6857 build_sched_domains(doms_new
+ i
);
6862 /* Remember the new sched domains */
6863 if (doms_cur
!= &fallback_doms
)
6865 doms_cur
= doms_new
;
6866 ndoms_cur
= ndoms_new
;
6868 register_sched_domain_sysctl();
6873 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
6874 static int arch_reinit_sched_domains(void)
6879 detach_destroy_domains(&cpu_online_map
);
6880 err
= arch_init_sched_domains(&cpu_online_map
);
6886 static ssize_t
sched_power_savings_store(const char *buf
, size_t count
, int smt
)
6890 if (buf
[0] != '0' && buf
[0] != '1')
6894 sched_smt_power_savings
= (buf
[0] == '1');
6896 sched_mc_power_savings
= (buf
[0] == '1');
6898 ret
= arch_reinit_sched_domains();
6900 return ret
? ret
: count
;
6903 #ifdef CONFIG_SCHED_MC
6904 static ssize_t
sched_mc_power_savings_show(struct sys_device
*dev
, char *page
)
6906 return sprintf(page
, "%u\n", sched_mc_power_savings
);
6908 static ssize_t
sched_mc_power_savings_store(struct sys_device
*dev
,
6909 const char *buf
, size_t count
)
6911 return sched_power_savings_store(buf
, count
, 0);
6913 static SYSDEV_ATTR(sched_mc_power_savings
, 0644, sched_mc_power_savings_show
,
6914 sched_mc_power_savings_store
);
6917 #ifdef CONFIG_SCHED_SMT
6918 static ssize_t
sched_smt_power_savings_show(struct sys_device
*dev
, char *page
)
6920 return sprintf(page
, "%u\n", sched_smt_power_savings
);
6922 static ssize_t
sched_smt_power_savings_store(struct sys_device
*dev
,
6923 const char *buf
, size_t count
)
6925 return sched_power_savings_store(buf
, count
, 1);
6927 static SYSDEV_ATTR(sched_smt_power_savings
, 0644, sched_smt_power_savings_show
,
6928 sched_smt_power_savings_store
);
6931 int sched_create_sysfs_power_savings_entries(struct sysdev_class
*cls
)
6935 #ifdef CONFIG_SCHED_SMT
6937 err
= sysfs_create_file(&cls
->kset
.kobj
,
6938 &attr_sched_smt_power_savings
.attr
);
6940 #ifdef CONFIG_SCHED_MC
6941 if (!err
&& mc_capable())
6942 err
= sysfs_create_file(&cls
->kset
.kobj
,
6943 &attr_sched_mc_power_savings
.attr
);
6950 * Force a reinitialization of the sched domains hierarchy. The domains
6951 * and groups cannot be updated in place without racing with the balancing
6952 * code, so we temporarily attach all running cpus to the NULL domain
6953 * which will prevent rebalancing while the sched domains are recalculated.
6955 static int update_sched_domains(struct notifier_block
*nfb
,
6956 unsigned long action
, void *hcpu
)
6959 case CPU_UP_PREPARE
:
6960 case CPU_UP_PREPARE_FROZEN
:
6961 case CPU_DOWN_PREPARE
:
6962 case CPU_DOWN_PREPARE_FROZEN
:
6963 detach_destroy_domains(&cpu_online_map
);
6966 case CPU_UP_CANCELED
:
6967 case CPU_UP_CANCELED_FROZEN
:
6968 case CPU_DOWN_FAILED
:
6969 case CPU_DOWN_FAILED_FROZEN
:
6971 case CPU_ONLINE_FROZEN
:
6973 case CPU_DEAD_FROZEN
:
6975 * Fall through and re-initialise the domains.
6982 /* The hotplug lock is already held by cpu_up/cpu_down */
6983 arch_init_sched_domains(&cpu_online_map
);
6988 void __init
sched_init_smp(void)
6990 cpumask_t non_isolated_cpus
;
6993 arch_init_sched_domains(&cpu_online_map
);
6994 cpus_andnot(non_isolated_cpus
, cpu_possible_map
, cpu_isolated_map
);
6995 if (cpus_empty(non_isolated_cpus
))
6996 cpu_set(smp_processor_id(), non_isolated_cpus
);
6998 /* XXX: Theoretical race here - CPU may be hotplugged now */
6999 hotcpu_notifier(update_sched_domains
, 0);
7001 /* Move init over to a non-isolated CPU */
7002 if (set_cpus_allowed(current
, non_isolated_cpus
) < 0)
7004 sched_init_granularity();
7006 #ifdef CONFIG_FAIR_GROUP_SCHED
7007 if (nr_cpu_ids
== 1)
7010 lb_monitor_task
= kthread_create(load_balance_monitor
, NULL
,
7012 if (!IS_ERR(lb_monitor_task
)) {
7013 lb_monitor_task
->flags
|= PF_NOFREEZE
;
7014 wake_up_process(lb_monitor_task
);
7016 printk(KERN_ERR
"Could not create load balance monitor thread"
7017 "(error = %ld) \n", PTR_ERR(lb_monitor_task
));
7022 void __init
sched_init_smp(void)
7024 sched_init_granularity();
7026 #endif /* CONFIG_SMP */
7028 int in_sched_functions(unsigned long addr
)
7030 return in_lock_functions(addr
) ||
7031 (addr
>= (unsigned long)__sched_text_start
7032 && addr
< (unsigned long)__sched_text_end
);
7035 static void init_cfs_rq(struct cfs_rq
*cfs_rq
, struct rq
*rq
)
7037 cfs_rq
->tasks_timeline
= RB_ROOT
;
7038 #ifdef CONFIG_FAIR_GROUP_SCHED
7041 cfs_rq
->min_vruntime
= (u64
)(-(1LL << 20));
7044 void __init
sched_init(void)
7046 int highest_cpu
= 0;
7050 init_defrootdomain();
7053 for_each_possible_cpu(i
) {
7054 struct rt_prio_array
*array
;
7058 spin_lock_init(&rq
->lock
);
7059 lockdep_set_class(&rq
->lock
, &rq
->rq_lock_key
);
7062 init_cfs_rq(&rq
->cfs
, rq
);
7063 #ifdef CONFIG_FAIR_GROUP_SCHED
7064 INIT_LIST_HEAD(&rq
->leaf_cfs_rq_list
);
7066 struct cfs_rq
*cfs_rq
= &per_cpu(init_cfs_rq
, i
);
7067 struct sched_entity
*se
=
7068 &per_cpu(init_sched_entity
, i
);
7070 init_cfs_rq_p
[i
] = cfs_rq
;
7071 init_cfs_rq(cfs_rq
, rq
);
7072 cfs_rq
->tg
= &init_task_group
;
7073 list_add(&cfs_rq
->leaf_cfs_rq_list
,
7074 &rq
->leaf_cfs_rq_list
);
7076 init_sched_entity_p
[i
] = se
;
7077 se
->cfs_rq
= &rq
->cfs
;
7079 se
->load
.weight
= init_task_group_load
;
7080 se
->load
.inv_weight
=
7081 div64_64(1ULL<<32, init_task_group_load
);
7084 init_task_group
.shares
= init_task_group_load
;
7087 for (j
= 0; j
< CPU_LOAD_IDX_MAX
; j
++)
7088 rq
->cpu_load
[j
] = 0;
7092 rq
->active_balance
= 0;
7093 rq
->next_balance
= jiffies
;
7096 rq
->migration_thread
= NULL
;
7097 INIT_LIST_HEAD(&rq
->migration_queue
);
7098 rq
->rt
.highest_prio
= MAX_RT_PRIO
;
7099 rq
->rt
.overloaded
= 0;
7100 rq_attach_root(rq
, &def_root_domain
);
7104 atomic_set(&rq
->nr_iowait
, 0);
7106 array
= &rq
->rt
.active
;
7107 for (j
= 0; j
< MAX_RT_PRIO
; j
++) {
7108 INIT_LIST_HEAD(array
->queue
+ j
);
7109 __clear_bit(j
, array
->bitmap
);
7112 /* delimiter for bitsearch: */
7113 __set_bit(MAX_RT_PRIO
, array
->bitmap
);
7116 set_load_weight(&init_task
);
7118 #ifdef CONFIG_PREEMPT_NOTIFIERS
7119 INIT_HLIST_HEAD(&init_task
.preempt_notifiers
);
7123 nr_cpu_ids
= highest_cpu
+ 1;
7124 open_softirq(SCHED_SOFTIRQ
, run_rebalance_domains
, NULL
);
7127 #ifdef CONFIG_RT_MUTEXES
7128 plist_head_init(&init_task
.pi_waiters
, &init_task
.pi_lock
);
7132 * The boot idle thread does lazy MMU switching as well:
7134 atomic_inc(&init_mm
.mm_count
);
7135 enter_lazy_tlb(&init_mm
, current
);
7138 * Make us the idle thread. Technically, schedule() should not be
7139 * called from this thread, however somewhere below it might be,
7140 * but because we are the idle thread, we just pick up running again
7141 * when this runqueue becomes "idle".
7143 init_idle(current
, smp_processor_id());
7145 * During early bootup we pretend to be a normal task:
7147 current
->sched_class
= &fair_sched_class
;
7150 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
7151 void __might_sleep(char *file
, int line
)
7154 static unsigned long prev_jiffy
; /* ratelimiting */
7156 if ((in_atomic() || irqs_disabled()) &&
7157 system_state
== SYSTEM_RUNNING
&& !oops_in_progress
) {
7158 if (time_before(jiffies
, prev_jiffy
+ HZ
) && prev_jiffy
)
7160 prev_jiffy
= jiffies
;
7161 printk(KERN_ERR
"BUG: sleeping function called from invalid"
7162 " context at %s:%d\n", file
, line
);
7163 printk("in_atomic():%d, irqs_disabled():%d\n",
7164 in_atomic(), irqs_disabled());
7165 debug_show_held_locks(current
);
7166 if (irqs_disabled())
7167 print_irqtrace_events(current
);
7172 EXPORT_SYMBOL(__might_sleep
);
7175 #ifdef CONFIG_MAGIC_SYSRQ
7176 static void normalize_task(struct rq
*rq
, struct task_struct
*p
)
7179 update_rq_clock(rq
);
7180 on_rq
= p
->se
.on_rq
;
7182 deactivate_task(rq
, p
, 0);
7183 __setscheduler(rq
, p
, SCHED_NORMAL
, 0);
7185 activate_task(rq
, p
, 0);
7186 resched_task(rq
->curr
);
7190 void normalize_rt_tasks(void)
7192 struct task_struct
*g
, *p
;
7193 unsigned long flags
;
7196 read_lock_irq(&tasklist_lock
);
7197 do_each_thread(g
, p
) {
7199 * Only normalize user tasks:
7204 p
->se
.exec_start
= 0;
7205 #ifdef CONFIG_SCHEDSTATS
7206 p
->se
.wait_start
= 0;
7207 p
->se
.sleep_start
= 0;
7208 p
->se
.block_start
= 0;
7210 task_rq(p
)->clock
= 0;
7214 * Renice negative nice level userspace
7217 if (TASK_NICE(p
) < 0 && p
->mm
)
7218 set_user_nice(p
, 0);
7222 spin_lock_irqsave(&p
->pi_lock
, flags
);
7223 rq
= __task_rq_lock(p
);
7225 normalize_task(rq
, p
);
7227 __task_rq_unlock(rq
);
7228 spin_unlock_irqrestore(&p
->pi_lock
, flags
);
7229 } while_each_thread(g
, p
);
7231 read_unlock_irq(&tasklist_lock
);
7234 #endif /* CONFIG_MAGIC_SYSRQ */
7238 * These functions are only useful for the IA64 MCA handling.
7240 * They can only be called when the whole system has been
7241 * stopped - every CPU needs to be quiescent, and no scheduling
7242 * activity can take place. Using them for anything else would
7243 * be a serious bug, and as a result, they aren't even visible
7244 * under any other configuration.
7248 * curr_task - return the current task for a given cpu.
7249 * @cpu: the processor in question.
7251 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7253 struct task_struct
*curr_task(int cpu
)
7255 return cpu_curr(cpu
);
7259 * set_curr_task - set the current task for a given cpu.
7260 * @cpu: the processor in question.
7261 * @p: the task pointer to set.
7263 * Description: This function must only be used when non-maskable interrupts
7264 * are serviced on a separate stack. It allows the architecture to switch the
7265 * notion of the current task on a cpu in a non-blocking manner. This function
7266 * must be called with all CPU's synchronized, and interrupts disabled, the
7267 * and caller must save the original value of the current task (see
7268 * curr_task() above) and restore that value before reenabling interrupts and
7269 * re-starting the system.
7271 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7273 void set_curr_task(int cpu
, struct task_struct
*p
)
7280 #ifdef CONFIG_FAIR_GROUP_SCHED
7284 * distribute shares of all task groups among their schedulable entities,
7285 * to reflect load distrbution across cpus.
7287 static int rebalance_shares(struct sched_domain
*sd
, int this_cpu
)
7289 struct cfs_rq
*cfs_rq
;
7290 struct rq
*rq
= cpu_rq(this_cpu
);
7291 cpumask_t sdspan
= sd
->span
;
7294 /* Walk thr' all the task groups that we have */
7295 for_each_leaf_cfs_rq(rq
, cfs_rq
) {
7297 unsigned long total_load
= 0, total_shares
;
7298 struct task_group
*tg
= cfs_rq
->tg
;
7300 /* Gather total task load of this group across cpus */
7301 for_each_cpu_mask(i
, sdspan
)
7302 total_load
+= tg
->cfs_rq
[i
]->load
.weight
;
7304 /* Nothing to do if this group has no load */
7309 * tg->shares represents the number of cpu shares the task group
7310 * is eligible to hold on a single cpu. On N cpus, it is
7311 * eligible to hold (N * tg->shares) number of cpu shares.
7313 total_shares
= tg
->shares
* cpus_weight(sdspan
);
7316 * redistribute total_shares across cpus as per the task load
7319 for_each_cpu_mask(i
, sdspan
) {
7320 unsigned long local_load
, local_shares
;
7322 local_load
= tg
->cfs_rq
[i
]->load
.weight
;
7323 local_shares
= (local_load
* total_shares
) / total_load
;
7325 local_shares
= MIN_GROUP_SHARES
;
7326 if (local_shares
== tg
->se
[i
]->load
.weight
)
7329 spin_lock_irq(&cpu_rq(i
)->lock
);
7330 set_se_shares(tg
->se
[i
], local_shares
);
7331 spin_unlock_irq(&cpu_rq(i
)->lock
);
7340 * How frequently should we rebalance_shares() across cpus?
7342 * The more frequently we rebalance shares, the more accurate is the fairness
7343 * of cpu bandwidth distribution between task groups. However higher frequency
7344 * also implies increased scheduling overhead.
7346 * sysctl_sched_min_bal_int_shares represents the minimum interval between
7347 * consecutive calls to rebalance_shares() in the same sched domain.
7349 * sysctl_sched_max_bal_int_shares represents the maximum interval between
7350 * consecutive calls to rebalance_shares() in the same sched domain.
7352 * These settings allows for the appropriate tradeoff between accuracy of
7353 * fairness and the associated overhead.
7357 /* default: 8ms, units: milliseconds */
7358 const_debug
unsigned int sysctl_sched_min_bal_int_shares
= 8;
7360 /* default: 128ms, units: milliseconds */
7361 const_debug
unsigned int sysctl_sched_max_bal_int_shares
= 128;
7363 /* kernel thread that runs rebalance_shares() periodically */
7364 static int load_balance_monitor(void *unused
)
7366 unsigned int timeout
= sysctl_sched_min_bal_int_shares
;
7367 struct sched_param schedparm
;
7371 * We don't want this thread's execution to be limited by the shares
7372 * assigned to default group (init_task_group). Hence make it run
7373 * as a SCHED_RR RT task at the lowest priority.
7375 schedparm
.sched_priority
= 1;
7376 ret
= sched_setscheduler(current
, SCHED_RR
, &schedparm
);
7378 printk(KERN_ERR
"Couldn't set SCHED_RR policy for load balance"
7379 " monitor thread (error = %d) \n", ret
);
7381 while (!kthread_should_stop()) {
7382 int i
, cpu
, balanced
= 1;
7384 /* Prevent cpus going down or coming up */
7386 /* lockout changes to doms_cur[] array */
7389 * Enter a rcu read-side critical section to safely walk rq->sd
7390 * chain on various cpus and to walk task group list
7391 * (rq->leaf_cfs_rq_list) in rebalance_shares().
7395 for (i
= 0; i
< ndoms_cur
; i
++) {
7396 cpumask_t cpumap
= doms_cur
[i
];
7397 struct sched_domain
*sd
= NULL
, *sd_prev
= NULL
;
7399 cpu
= first_cpu(cpumap
);
7401 /* Find the highest domain at which to balance shares */
7402 for_each_domain(cpu
, sd
) {
7403 if (!(sd
->flags
& SD_LOAD_BALANCE
))
7409 /* sd == NULL? No load balance reqd in this domain */
7413 balanced
&= rebalance_shares(sd
, cpu
);
7422 timeout
= sysctl_sched_min_bal_int_shares
;
7423 else if (timeout
< sysctl_sched_max_bal_int_shares
)
7426 msleep_interruptible(timeout
);
7431 #endif /* CONFIG_SMP */
7433 /* allocate runqueue etc for a new task group */
7434 struct task_group
*sched_create_group(void)
7436 struct task_group
*tg
;
7437 struct cfs_rq
*cfs_rq
;
7438 struct sched_entity
*se
;
7442 tg
= kzalloc(sizeof(*tg
), GFP_KERNEL
);
7444 return ERR_PTR(-ENOMEM
);
7446 tg
->cfs_rq
= kzalloc(sizeof(cfs_rq
) * NR_CPUS
, GFP_KERNEL
);
7449 tg
->se
= kzalloc(sizeof(se
) * NR_CPUS
, GFP_KERNEL
);
7453 for_each_possible_cpu(i
) {
7456 cfs_rq
= kmalloc_node(sizeof(struct cfs_rq
), GFP_KERNEL
,
7461 se
= kmalloc_node(sizeof(struct sched_entity
), GFP_KERNEL
,
7466 memset(cfs_rq
, 0, sizeof(struct cfs_rq
));
7467 memset(se
, 0, sizeof(struct sched_entity
));
7469 tg
->cfs_rq
[i
] = cfs_rq
;
7470 init_cfs_rq(cfs_rq
, rq
);
7474 se
->cfs_rq
= &rq
->cfs
;
7476 se
->load
.weight
= NICE_0_LOAD
;
7477 se
->load
.inv_weight
= div64_64(1ULL<<32, NICE_0_LOAD
);
7481 tg
->shares
= NICE_0_LOAD
;
7483 lock_task_group_list();
7484 for_each_possible_cpu(i
) {
7486 cfs_rq
= tg
->cfs_rq
[i
];
7487 list_add_rcu(&cfs_rq
->leaf_cfs_rq_list
, &rq
->leaf_cfs_rq_list
);
7489 unlock_task_group_list();
7494 for_each_possible_cpu(i
) {
7496 kfree(tg
->cfs_rq
[i
]);
7504 return ERR_PTR(-ENOMEM
);
7507 /* rcu callback to free various structures associated with a task group */
7508 static void free_sched_group(struct rcu_head
*rhp
)
7510 struct task_group
*tg
= container_of(rhp
, struct task_group
, rcu
);
7511 struct cfs_rq
*cfs_rq
;
7512 struct sched_entity
*se
;
7515 /* now it should be safe to free those cfs_rqs */
7516 for_each_possible_cpu(i
) {
7517 cfs_rq
= tg
->cfs_rq
[i
];
7529 /* Destroy runqueue etc associated with a task group */
7530 void sched_destroy_group(struct task_group
*tg
)
7532 struct cfs_rq
*cfs_rq
= NULL
;
7535 lock_task_group_list();
7536 for_each_possible_cpu(i
) {
7537 cfs_rq
= tg
->cfs_rq
[i
];
7538 list_del_rcu(&cfs_rq
->leaf_cfs_rq_list
);
7540 unlock_task_group_list();
7544 /* wait for possible concurrent references to cfs_rqs complete */
7545 call_rcu(&tg
->rcu
, free_sched_group
);
7548 /* change task's runqueue when it moves between groups.
7549 * The caller of this function should have put the task in its new group
7550 * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7551 * reflect its new group.
7553 void sched_move_task(struct task_struct
*tsk
)
7556 unsigned long flags
;
7559 rq
= task_rq_lock(tsk
, &flags
);
7561 if (tsk
->sched_class
!= &fair_sched_class
) {
7562 set_task_cfs_rq(tsk
, task_cpu(tsk
));
7566 update_rq_clock(rq
);
7568 running
= task_current(rq
, tsk
);
7569 on_rq
= tsk
->se
.on_rq
;
7572 dequeue_task(rq
, tsk
, 0);
7573 if (unlikely(running
))
7574 tsk
->sched_class
->put_prev_task(rq
, tsk
);
7577 set_task_cfs_rq(tsk
, task_cpu(tsk
));
7580 if (unlikely(running
))
7581 tsk
->sched_class
->set_curr_task(rq
);
7582 enqueue_task(rq
, tsk
, 0);
7586 task_rq_unlock(rq
, &flags
);
7589 /* rq->lock to be locked by caller */
7590 static void set_se_shares(struct sched_entity
*se
, unsigned long shares
)
7592 struct cfs_rq
*cfs_rq
= se
->cfs_rq
;
7593 struct rq
*rq
= cfs_rq
->rq
;
7597 shares
= MIN_GROUP_SHARES
;
7601 dequeue_entity(cfs_rq
, se
, 0);
7602 dec_cpu_load(rq
, se
->load
.weight
);
7605 se
->load
.weight
= shares
;
7606 se
->load
.inv_weight
= div64_64((1ULL<<32), shares
);
7609 enqueue_entity(cfs_rq
, se
, 0);
7610 inc_cpu_load(rq
, se
->load
.weight
);
7614 int sched_group_set_shares(struct task_group
*tg
, unsigned long shares
)
7617 struct cfs_rq
*cfs_rq
;
7620 lock_task_group_list();
7621 if (tg
->shares
== shares
)
7624 if (shares
< MIN_GROUP_SHARES
)
7625 shares
= MIN_GROUP_SHARES
;
7628 * Prevent any load balance activity (rebalance_shares,
7629 * load_balance_fair) from referring to this group first,
7630 * by taking it off the rq->leaf_cfs_rq_list on each cpu.
7632 for_each_possible_cpu(i
) {
7633 cfs_rq
= tg
->cfs_rq
[i
];
7634 list_del_rcu(&cfs_rq
->leaf_cfs_rq_list
);
7637 /* wait for any ongoing reference to this group to finish */
7638 synchronize_sched();
7641 * Now we are free to modify the group's share on each cpu
7642 * w/o tripping rebalance_share or load_balance_fair.
7644 tg
->shares
= shares
;
7645 for_each_possible_cpu(i
) {
7646 spin_lock_irq(&cpu_rq(i
)->lock
);
7647 set_se_shares(tg
->se
[i
], shares
);
7648 spin_unlock_irq(&cpu_rq(i
)->lock
);
7652 * Enable load balance activity on this group, by inserting it back on
7653 * each cpu's rq->leaf_cfs_rq_list.
7655 for_each_possible_cpu(i
) {
7657 cfs_rq
= tg
->cfs_rq
[i
];
7658 list_add_rcu(&cfs_rq
->leaf_cfs_rq_list
, &rq
->leaf_cfs_rq_list
);
7661 unlock_task_group_list();
7665 unsigned long sched_group_shares(struct task_group
*tg
)
7670 #endif /* CONFIG_FAIR_GROUP_SCHED */
7672 #ifdef CONFIG_FAIR_CGROUP_SCHED
7674 /* return corresponding task_group object of a cgroup */
7675 static inline struct task_group
*cgroup_tg(struct cgroup
*cgrp
)
7677 return container_of(cgroup_subsys_state(cgrp
, cpu_cgroup_subsys_id
),
7678 struct task_group
, css
);
7681 static struct cgroup_subsys_state
*
7682 cpu_cgroup_create(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
7684 struct task_group
*tg
;
7686 if (!cgrp
->parent
) {
7687 /* This is early initialization for the top cgroup */
7688 init_task_group
.css
.cgroup
= cgrp
;
7689 return &init_task_group
.css
;
7692 /* we support only 1-level deep hierarchical scheduler atm */
7693 if (cgrp
->parent
->parent
)
7694 return ERR_PTR(-EINVAL
);
7696 tg
= sched_create_group();
7698 return ERR_PTR(-ENOMEM
);
7700 /* Bind the cgroup to task_group object we just created */
7701 tg
->css
.cgroup
= cgrp
;
7707 cpu_cgroup_destroy(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
)
7709 struct task_group
*tg
= cgroup_tg(cgrp
);
7711 sched_destroy_group(tg
);
7715 cpu_cgroup_can_attach(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
,
7716 struct task_struct
*tsk
)
7718 /* We don't support RT-tasks being in separate groups */
7719 if (tsk
->sched_class
!= &fair_sched_class
)
7726 cpu_cgroup_attach(struct cgroup_subsys
*ss
, struct cgroup
*cgrp
,
7727 struct cgroup
*old_cont
, struct task_struct
*tsk
)
7729 sched_move_task(tsk
);
7732 static int cpu_shares_write_uint(struct cgroup
*cgrp
, struct cftype
*cftype
,
7735 return sched_group_set_shares(cgroup_tg(cgrp
), shareval
);
7738 static u64
cpu_shares_read_uint(struct cgroup
*cgrp
, struct cftype
*cft
)
7740 struct task_group
*tg
= cgroup_tg(cgrp
);
7742 return (u64
) tg
->shares
;
7745 static struct cftype cpu_files
[] = {
7748 .read_uint
= cpu_shares_read_uint
,
7749 .write_uint
= cpu_shares_write_uint
,
7753 static int cpu_cgroup_populate(struct cgroup_subsys
*ss
, struct cgroup
*cont
)
7755 return cgroup_add_files(cont
, ss
, cpu_files
, ARRAY_SIZE(cpu_files
));
7758 struct cgroup_subsys cpu_cgroup_subsys
= {
7760 .create
= cpu_cgroup_create
,
7761 .destroy
= cpu_cgroup_destroy
,
7762 .can_attach
= cpu_cgroup_can_attach
,
7763 .attach
= cpu_cgroup_attach
,
7764 .populate
= cpu_cgroup_populate
,
7765 .subsys_id
= cpu_cgroup_subsys_id
,
7769 #endif /* CONFIG_FAIR_CGROUP_SCHED */
7771 #ifdef CONFIG_CGROUP_CPUACCT
7774 * CPU accounting code for task groups.
7776 * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
7777 * (balbir@in.ibm.com).
7780 /* track cpu usage of a group of tasks */
7782 struct cgroup_subsys_state css
;
7783 /* cpuusage holds pointer to a u64-type object on every cpu */
7787 struct cgroup_subsys cpuacct_subsys
;
7789 /* return cpu accounting group corresponding to this container */
7790 static inline struct cpuacct
*cgroup_ca(struct cgroup
*cont
)
7792 return container_of(cgroup_subsys_state(cont
, cpuacct_subsys_id
),
7793 struct cpuacct
, css
);
7796 /* return cpu accounting group to which this task belongs */
7797 static inline struct cpuacct
*task_ca(struct task_struct
*tsk
)
7799 return container_of(task_subsys_state(tsk
, cpuacct_subsys_id
),
7800 struct cpuacct
, css
);
7803 /* create a new cpu accounting group */
7804 static struct cgroup_subsys_state
*cpuacct_create(
7805 struct cgroup_subsys
*ss
, struct cgroup
*cont
)
7807 struct cpuacct
*ca
= kzalloc(sizeof(*ca
), GFP_KERNEL
);
7810 return ERR_PTR(-ENOMEM
);
7812 ca
->cpuusage
= alloc_percpu(u64
);
7813 if (!ca
->cpuusage
) {
7815 return ERR_PTR(-ENOMEM
);
7821 /* destroy an existing cpu accounting group */
7823 cpuacct_destroy(struct cgroup_subsys
*ss
, struct cgroup
*cont
)
7825 struct cpuacct
*ca
= cgroup_ca(cont
);
7827 free_percpu(ca
->cpuusage
);
7831 /* return total cpu usage (in nanoseconds) of a group */
7832 static u64
cpuusage_read(struct cgroup
*cont
, struct cftype
*cft
)
7834 struct cpuacct
*ca
= cgroup_ca(cont
);
7835 u64 totalcpuusage
= 0;
7838 for_each_possible_cpu(i
) {
7839 u64
*cpuusage
= percpu_ptr(ca
->cpuusage
, i
);
7842 * Take rq->lock to make 64-bit addition safe on 32-bit
7845 spin_lock_irq(&cpu_rq(i
)->lock
);
7846 totalcpuusage
+= *cpuusage
;
7847 spin_unlock_irq(&cpu_rq(i
)->lock
);
7850 return totalcpuusage
;
7853 static struct cftype files
[] = {
7856 .read_uint
= cpuusage_read
,
7860 static int cpuacct_populate(struct cgroup_subsys
*ss
, struct cgroup
*cont
)
7862 return cgroup_add_files(cont
, ss
, files
, ARRAY_SIZE(files
));
7866 * charge this task's execution time to its accounting group.
7868 * called with rq->lock held.
7870 static void cpuacct_charge(struct task_struct
*tsk
, u64 cputime
)
7874 if (!cpuacct_subsys
.active
)
7879 u64
*cpuusage
= percpu_ptr(ca
->cpuusage
, task_cpu(tsk
));
7881 *cpuusage
+= cputime
;
7885 struct cgroup_subsys cpuacct_subsys
= {
7887 .create
= cpuacct_create
,
7888 .destroy
= cpuacct_destroy
,
7889 .populate
= cpuacct_populate
,
7890 .subsys_id
= cpuacct_subsys_id
,
7892 #endif /* CONFIG_CGROUP_CPUACCT */