sched: clean up schedstat block in dequeue_entity()
[GitHub/mt8127/android_kernel_alcatel_ttab.git] / kernel / sched.c
CommitLineData
1da177e4
LT
1/*
2 * kernel/sched.c
3 *
4 * Kernel scheduler and related syscalls
5 *
6 * Copyright (C) 1991-2002 Linus Torvalds
7 *
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
11 * by Andrea Arcangeli
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
c31f2e8a
IM
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
22 * by Peter Williams
23 * 2007-05-06 Interactivity improvements to CFS by Mike Galbraith
24 * 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri
1da177e4
LT
25 */
26
27#include <linux/mm.h>
28#include <linux/module.h>
29#include <linux/nmi.h>
30#include <linux/init.h>
dff06c15 31#include <linux/uaccess.h>
1da177e4
LT
32#include <linux/highmem.h>
33#include <linux/smp_lock.h>
34#include <asm/mmu_context.h>
35#include <linux/interrupt.h>
c59ede7b 36#include <linux/capability.h>
1da177e4
LT
37#include <linux/completion.h>
38#include <linux/kernel_stat.h>
9a11b49a 39#include <linux/debug_locks.h>
1da177e4
LT
40#include <linux/security.h>
41#include <linux/notifier.h>
42#include <linux/profile.h>
7dfb7103 43#include <linux/freezer.h>
198e2f18 44#include <linux/vmalloc.h>
1da177e4
LT
45#include <linux/blkdev.h>
46#include <linux/delay.h>
47#include <linux/smp.h>
48#include <linux/threads.h>
49#include <linux/timer.h>
50#include <linux/rcupdate.h>
51#include <linux/cpu.h>
52#include <linux/cpuset.h>
53#include <linux/percpu.h>
54#include <linux/kthread.h>
55#include <linux/seq_file.h>
e692ab53 56#include <linux/sysctl.h>
1da177e4
LT
57#include <linux/syscalls.h>
58#include <linux/times.h>
8f0ab514 59#include <linux/tsacct_kern.h>
c6fd91f0 60#include <linux/kprobes.h>
0ff92245 61#include <linux/delayacct.h>
5517d86b 62#include <linux/reciprocal_div.h>
dff06c15 63#include <linux/unistd.h>
f5ff8422 64#include <linux/pagemap.h>
1da177e4 65
5517d86b 66#include <asm/tlb.h>
1da177e4 67
b035b6de
AD
68/*
69 * Scheduler clock - returns current time in nanosec units.
70 * This is default implementation.
71 * Architectures and sub-architectures can override this.
72 */
73unsigned long long __attribute__((weak)) sched_clock(void)
74{
75 return (unsigned long long)jiffies * (1000000000 / HZ);
76}
77
1da177e4
LT
78/*
79 * Convert user-nice values [ -20 ... 0 ... 19 ]
80 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
81 * and back.
82 */
83#define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
84#define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
85#define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
86
87/*
88 * 'User priority' is the nice value converted to something we
89 * can work with better when scaling various scheduler parameters,
90 * it's a [ 0 ... 39 ] range.
91 */
92#define USER_PRIO(p) ((p)-MAX_RT_PRIO)
93#define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
94#define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
95
96/*
97 * Some helpers for converting nanosecond timing to jiffy resolution
98 */
99#define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
100#define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
101
6aa645ea
IM
102#define NICE_0_LOAD SCHED_LOAD_SCALE
103#define NICE_0_SHIFT SCHED_LOAD_SHIFT
104
1da177e4
LT
105/*
106 * These are the 'tuning knobs' of the scheduler:
107 *
108 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
109 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
110 * Timeslices get refilled after they expire.
111 */
112#define MIN_TIMESLICE max(5 * HZ / 1000, 1)
113#define DEF_TIMESLICE (100 * HZ / 1000)
2dd73a4f 114
5517d86b
ED
115#ifdef CONFIG_SMP
116/*
117 * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
118 * Since cpu_power is a 'constant', we can use a reciprocal divide.
119 */
120static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
121{
122 return reciprocal_divide(load, sg->reciprocal_cpu_power);
123}
124
125/*
126 * Each time a sched group cpu_power is changed,
127 * we must compute its reciprocal value
128 */
129static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
130{
131 sg->__cpu_power += val;
132 sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
133}
134#endif
135
634fa8c9
IM
136#define SCALE_PRIO(x, prio) \
137 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO / 2), MIN_TIMESLICE)
138
91fcdd4e 139/*
634fa8c9 140 * static_prio_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
91fcdd4e 141 * to time slice values: [800ms ... 100ms ... 5ms]
91fcdd4e 142 */
634fa8c9 143static unsigned int static_prio_timeslice(int static_prio)
2dd73a4f 144{
634fa8c9
IM
145 if (static_prio == NICE_TO_PRIO(19))
146 return 1;
147
148 if (static_prio < NICE_TO_PRIO(0))
149 return SCALE_PRIO(DEF_TIMESLICE * 4, static_prio);
150 else
151 return SCALE_PRIO(DEF_TIMESLICE, static_prio);
2dd73a4f
PW
152}
153
e05606d3
IM
154static inline int rt_policy(int policy)
155{
156 if (unlikely(policy == SCHED_FIFO) || unlikely(policy == SCHED_RR))
157 return 1;
158 return 0;
159}
160
161static inline int task_has_rt_policy(struct task_struct *p)
162{
163 return rt_policy(p->policy);
164}
165
1da177e4 166/*
6aa645ea 167 * This is the priority-queue data structure of the RT scheduling class:
1da177e4 168 */
6aa645ea
IM
169struct rt_prio_array {
170 DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
171 struct list_head queue[MAX_RT_PRIO];
172};
173
6aa645ea
IM
174/* CFS-related fields in a runqueue */
175struct cfs_rq {
176 struct load_weight load;
177 unsigned long nr_running;
178
6aa645ea 179 u64 exec_clock;
e9acbff6 180 u64 min_vruntime;
6aa645ea
IM
181
182 struct rb_root tasks_timeline;
183 struct rb_node *rb_leftmost;
184 struct rb_node *rb_load_balance_curr;
6aa645ea
IM
185 /* 'curr' points to currently running entity on this cfs_rq.
186 * It is set to NULL otherwise (i.e when none are currently running).
187 */
188 struct sched_entity *curr;
62160e3f 189#ifdef CONFIG_FAIR_GROUP_SCHED
6aa645ea
IM
190 struct rq *rq; /* cpu runqueue to which this cfs_rq is attached */
191
192 /* leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
193 * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
194 * (like users, containers etc.)
195 *
196 * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
197 * list is used during load balance.
198 */
199 struct list_head leaf_cfs_rq_list; /* Better name : task_cfs_rq_list? */
200#endif
201};
1da177e4 202
6aa645ea
IM
203/* Real-Time classes' related field in a runqueue: */
204struct rt_rq {
205 struct rt_prio_array active;
206 int rt_load_balance_idx;
207 struct list_head *rt_load_balance_head, *rt_load_balance_curr;
208};
209
1da177e4
LT
210/*
211 * This is the main, per-CPU runqueue data structure.
212 *
213 * Locking rule: those places that want to lock multiple runqueues
214 * (such as the load balancing or the thread migration code), lock
215 * acquire operations must be ordered by ascending &runqueue.
216 */
70b97a7f 217struct rq {
6aa645ea 218 spinlock_t lock; /* runqueue lock */
1da177e4
LT
219
220 /*
221 * nr_running and cpu_load should be in the same cacheline because
222 * remote CPUs use both these fields when doing load calculation.
223 */
224 unsigned long nr_running;
6aa645ea
IM
225 #define CPU_LOAD_IDX_MAX 5
226 unsigned long cpu_load[CPU_LOAD_IDX_MAX];
bdecea3a 227 unsigned char idle_at_tick;
46cb4b7c
SS
228#ifdef CONFIG_NO_HZ
229 unsigned char in_nohz_recently;
230#endif
495eca49 231 struct load_weight load; /* capture load from *all* tasks on this cpu */
6aa645ea
IM
232 unsigned long nr_load_updates;
233 u64 nr_switches;
234
235 struct cfs_rq cfs;
236#ifdef CONFIG_FAIR_GROUP_SCHED
237 struct list_head leaf_cfs_rq_list; /* list of leaf cfs_rq on this cpu */
1da177e4 238#endif
6aa645ea 239 struct rt_rq rt;
1da177e4
LT
240
241 /*
242 * This is part of a global counter where only the total sum
243 * over all CPUs matters. A task can increase this counter on
244 * one CPU and if it got migrated afterwards it may decrease
245 * it on another CPU. Always updated under the runqueue lock:
246 */
247 unsigned long nr_uninterruptible;
248
36c8b586 249 struct task_struct *curr, *idle;
c9819f45 250 unsigned long next_balance;
1da177e4 251 struct mm_struct *prev_mm;
6aa645ea 252
6aa645ea
IM
253 u64 clock, prev_clock_raw;
254 s64 clock_max_delta;
255
256 unsigned int clock_warps, clock_overflows;
2aa44d05
IM
257 u64 idle_clock;
258 unsigned int clock_deep_idle_events;
529c7726 259 u64 tick_timestamp;
6aa645ea 260
1da177e4
LT
261 atomic_t nr_iowait;
262
263#ifdef CONFIG_SMP
264 struct sched_domain *sd;
265
266 /* For active balancing */
267 int active_balance;
268 int push_cpu;
0a2966b4 269 int cpu; /* cpu of this runqueue */
1da177e4 270
36c8b586 271 struct task_struct *migration_thread;
1da177e4
LT
272 struct list_head migration_queue;
273#endif
274
275#ifdef CONFIG_SCHEDSTATS
276 /* latency stats */
277 struct sched_info rq_sched_info;
278
279 /* sys_sched_yield() stats */
280 unsigned long yld_exp_empty;
281 unsigned long yld_act_empty;
282 unsigned long yld_both_empty;
283 unsigned long yld_cnt;
284
285 /* schedule() stats */
286 unsigned long sched_switch;
287 unsigned long sched_cnt;
288 unsigned long sched_goidle;
289
290 /* try_to_wake_up() stats */
291 unsigned long ttwu_cnt;
292 unsigned long ttwu_local;
293#endif
fcb99371 294 struct lock_class_key rq_lock_key;
1da177e4
LT
295};
296
f34e3b61 297static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
5be9361c 298static DEFINE_MUTEX(sched_hotcpu_mutex);
1da177e4 299
dd41f596
IM
300static inline void check_preempt_curr(struct rq *rq, struct task_struct *p)
301{
302 rq->curr->sched_class->check_preempt_curr(rq, p);
303}
304
0a2966b4
CL
305static inline int cpu_of(struct rq *rq)
306{
307#ifdef CONFIG_SMP
308 return rq->cpu;
309#else
310 return 0;
311#endif
312}
313
20d315d4 314/*
b04a0f4c
IM
315 * Update the per-runqueue clock, as finegrained as the platform can give
316 * us, but without assuming monotonicity, etc.:
20d315d4 317 */
b04a0f4c 318static void __update_rq_clock(struct rq *rq)
20d315d4
IM
319{
320 u64 prev_raw = rq->prev_clock_raw;
321 u64 now = sched_clock();
322 s64 delta = now - prev_raw;
323 u64 clock = rq->clock;
324
b04a0f4c
IM
325#ifdef CONFIG_SCHED_DEBUG
326 WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
327#endif
20d315d4
IM
328 /*
329 * Protect against sched_clock() occasionally going backwards:
330 */
331 if (unlikely(delta < 0)) {
332 clock++;
333 rq->clock_warps++;
334 } else {
335 /*
336 * Catch too large forward jumps too:
337 */
529c7726
IM
338 if (unlikely(clock + delta > rq->tick_timestamp + TICK_NSEC)) {
339 if (clock < rq->tick_timestamp + TICK_NSEC)
340 clock = rq->tick_timestamp + TICK_NSEC;
341 else
342 clock++;
20d315d4
IM
343 rq->clock_overflows++;
344 } else {
345 if (unlikely(delta > rq->clock_max_delta))
346 rq->clock_max_delta = delta;
347 clock += delta;
348 }
349 }
350
351 rq->prev_clock_raw = now;
352 rq->clock = clock;
b04a0f4c 353}
20d315d4 354
b04a0f4c
IM
355static void update_rq_clock(struct rq *rq)
356{
357 if (likely(smp_processor_id() == cpu_of(rq)))
358 __update_rq_clock(rq);
20d315d4
IM
359}
360
674311d5
NP
361/*
362 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
1a20ff27 363 * See detach_destroy_domains: synchronize_sched for details.
674311d5
NP
364 *
365 * The domain tree of any CPU may only be accessed from within
366 * preempt-disabled sections.
367 */
48f24c4d
IM
368#define for_each_domain(cpu, __sd) \
369 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
1da177e4
LT
370
371#define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
372#define this_rq() (&__get_cpu_var(runqueues))
373#define task_rq(p) cpu_rq(task_cpu(p))
374#define cpu_curr(cpu) (cpu_rq(cpu)->curr)
375
bf5c91ba
IM
376/*
377 * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
378 */
379#ifdef CONFIG_SCHED_DEBUG
380# define const_debug __read_mostly
381#else
382# define const_debug static const
383#endif
384
385/*
386 * Debugging: various feature bits
387 */
388enum {
bbdba7c0
IM
389 SCHED_FEAT_NEW_FAIR_SLEEPERS = 1,
390 SCHED_FEAT_START_DEBIT = 2,
391 SCHED_FEAT_USE_TREE_AVG = 4,
392 SCHED_FEAT_APPROX_AVG = 8,
bf5c91ba
IM
393};
394
395const_debug unsigned int sysctl_sched_features =
bf5c91ba 396 SCHED_FEAT_NEW_FAIR_SLEEPERS *1 |
94dfb5e7
PZ
397 SCHED_FEAT_START_DEBIT *1 |
398 SCHED_FEAT_USE_TREE_AVG *0 |
399 SCHED_FEAT_APPROX_AVG *0;
bf5c91ba
IM
400
401#define sched_feat(x) (sysctl_sched_features & SCHED_FEAT_##x)
402
e436d800
IM
403/*
404 * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
405 * clock constructed from sched_clock():
406 */
407unsigned long long cpu_clock(int cpu)
408{
e436d800
IM
409 unsigned long long now;
410 unsigned long flags;
b04a0f4c 411 struct rq *rq;
e436d800 412
2cd4d0ea 413 local_irq_save(flags);
b04a0f4c
IM
414 rq = cpu_rq(cpu);
415 update_rq_clock(rq);
416 now = rq->clock;
2cd4d0ea 417 local_irq_restore(flags);
e436d800
IM
418
419 return now;
420}
421
138a8aeb
IM
422#ifdef CONFIG_FAIR_GROUP_SCHED
423/* Change a task's ->cfs_rq if it moves across CPUs */
424static inline void set_task_cfs_rq(struct task_struct *p)
425{
426 p->se.cfs_rq = &task_rq(p)->cfs;
427}
428#else
429static inline void set_task_cfs_rq(struct task_struct *p)
430{
431}
432#endif
433
1da177e4 434#ifndef prepare_arch_switch
4866cde0
NP
435# define prepare_arch_switch(next) do { } while (0)
436#endif
437#ifndef finish_arch_switch
438# define finish_arch_switch(prev) do { } while (0)
439#endif
440
441#ifndef __ARCH_WANT_UNLOCKED_CTXSW
70b97a7f 442static inline int task_running(struct rq *rq, struct task_struct *p)
4866cde0
NP
443{
444 return rq->curr == p;
445}
446
70b97a7f 447static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
4866cde0
NP
448{
449}
450
70b97a7f 451static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
4866cde0 452{
da04c035
IM
453#ifdef CONFIG_DEBUG_SPINLOCK
454 /* this is a valid case when another task releases the spinlock */
455 rq->lock.owner = current;
456#endif
8a25d5de
IM
457 /*
458 * If we are tracking spinlock dependencies then we have to
459 * fix up the runqueue lock - which gets 'carried over' from
460 * prev into current:
461 */
462 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
463
4866cde0
NP
464 spin_unlock_irq(&rq->lock);
465}
466
467#else /* __ARCH_WANT_UNLOCKED_CTXSW */
70b97a7f 468static inline int task_running(struct rq *rq, struct task_struct *p)
4866cde0
NP
469{
470#ifdef CONFIG_SMP
471 return p->oncpu;
472#else
473 return rq->curr == p;
474#endif
475}
476
70b97a7f 477static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
4866cde0
NP
478{
479#ifdef CONFIG_SMP
480 /*
481 * We can optimise this out completely for !SMP, because the
482 * SMP rebalancing from interrupt is the only thing that cares
483 * here.
484 */
485 next->oncpu = 1;
486#endif
487#ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
488 spin_unlock_irq(&rq->lock);
489#else
490 spin_unlock(&rq->lock);
491#endif
492}
493
70b97a7f 494static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
4866cde0
NP
495{
496#ifdef CONFIG_SMP
497 /*
498 * After ->oncpu is cleared, the task can be moved to a different CPU.
499 * We must ensure this doesn't happen until the switch is completely
500 * finished.
501 */
502 smp_wmb();
503 prev->oncpu = 0;
504#endif
505#ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
506 local_irq_enable();
1da177e4 507#endif
4866cde0
NP
508}
509#endif /* __ARCH_WANT_UNLOCKED_CTXSW */
1da177e4 510
b29739f9
IM
511/*
512 * __task_rq_lock - lock the runqueue a given task resides on.
513 * Must be called interrupts disabled.
514 */
70b97a7f 515static inline struct rq *__task_rq_lock(struct task_struct *p)
b29739f9
IM
516 __acquires(rq->lock)
517{
70b97a7f 518 struct rq *rq;
b29739f9
IM
519
520repeat_lock_task:
521 rq = task_rq(p);
522 spin_lock(&rq->lock);
523 if (unlikely(rq != task_rq(p))) {
524 spin_unlock(&rq->lock);
525 goto repeat_lock_task;
526 }
527 return rq;
528}
529
1da177e4
LT
530/*
531 * task_rq_lock - lock the runqueue a given task resides on and disable
532 * interrupts. Note the ordering: we can safely lookup the task_rq without
533 * explicitly disabling preemption.
534 */
70b97a7f 535static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
1da177e4
LT
536 __acquires(rq->lock)
537{
70b97a7f 538 struct rq *rq;
1da177e4
LT
539
540repeat_lock_task:
541 local_irq_save(*flags);
542 rq = task_rq(p);
543 spin_lock(&rq->lock);
544 if (unlikely(rq != task_rq(p))) {
545 spin_unlock_irqrestore(&rq->lock, *flags);
546 goto repeat_lock_task;
547 }
548 return rq;
549}
550
70b97a7f 551static inline void __task_rq_unlock(struct rq *rq)
b29739f9
IM
552 __releases(rq->lock)
553{
554 spin_unlock(&rq->lock);
555}
556
70b97a7f 557static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
1da177e4
LT
558 __releases(rq->lock)
559{
560 spin_unlock_irqrestore(&rq->lock, *flags);
561}
562
1da177e4 563/*
cc2a73b5 564 * this_rq_lock - lock this runqueue and disable interrupts.
1da177e4 565 */
70b97a7f 566static inline struct rq *this_rq_lock(void)
1da177e4
LT
567 __acquires(rq->lock)
568{
70b97a7f 569 struct rq *rq;
1da177e4
LT
570
571 local_irq_disable();
572 rq = this_rq();
573 spin_lock(&rq->lock);
574
575 return rq;
576}
577
1b9f19c2 578/*
2aa44d05 579 * We are going deep-idle (irqs are disabled):
1b9f19c2 580 */
2aa44d05 581void sched_clock_idle_sleep_event(void)
1b9f19c2 582{
2aa44d05
IM
583 struct rq *rq = cpu_rq(smp_processor_id());
584
585 spin_lock(&rq->lock);
586 __update_rq_clock(rq);
587 spin_unlock(&rq->lock);
588 rq->clock_deep_idle_events++;
589}
590EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
591
592/*
593 * We just idled delta nanoseconds (called with irqs disabled):
594 */
595void sched_clock_idle_wakeup_event(u64 delta_ns)
596{
597 struct rq *rq = cpu_rq(smp_processor_id());
598 u64 now = sched_clock();
1b9f19c2 599
2aa44d05
IM
600 rq->idle_clock += delta_ns;
601 /*
602 * Override the previous timestamp and ignore all
603 * sched_clock() deltas that occured while we idled,
604 * and use the PM-provided delta_ns to advance the
605 * rq clock:
606 */
607 spin_lock(&rq->lock);
608 rq->prev_clock_raw = now;
609 rq->clock += delta_ns;
610 spin_unlock(&rq->lock);
1b9f19c2 611}
2aa44d05 612EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
1b9f19c2 613
c24d20db
IM
614/*
615 * resched_task - mark a task 'to be rescheduled now'.
616 *
617 * On UP this means the setting of the need_resched flag, on SMP it
618 * might also involve a cross-CPU call to trigger the scheduler on
619 * the target CPU.
620 */
621#ifdef CONFIG_SMP
622
623#ifndef tsk_is_polling
624#define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
625#endif
626
627static void resched_task(struct task_struct *p)
628{
629 int cpu;
630
631 assert_spin_locked(&task_rq(p)->lock);
632
633 if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
634 return;
635
636 set_tsk_thread_flag(p, TIF_NEED_RESCHED);
637
638 cpu = task_cpu(p);
639 if (cpu == smp_processor_id())
640 return;
641
642 /* NEED_RESCHED must be visible before we test polling */
643 smp_mb();
644 if (!tsk_is_polling(p))
645 smp_send_reschedule(cpu);
646}
647
648static void resched_cpu(int cpu)
649{
650 struct rq *rq = cpu_rq(cpu);
651 unsigned long flags;
652
653 if (!spin_trylock_irqsave(&rq->lock, flags))
654 return;
655 resched_task(cpu_curr(cpu));
656 spin_unlock_irqrestore(&rq->lock, flags);
657}
658#else
659static inline void resched_task(struct task_struct *p)
660{
661 assert_spin_locked(&task_rq(p)->lock);
662 set_tsk_need_resched(p);
663}
664#endif
665
45bf76df
IM
666#if BITS_PER_LONG == 32
667# define WMULT_CONST (~0UL)
668#else
669# define WMULT_CONST (1UL << 32)
670#endif
671
672#define WMULT_SHIFT 32
673
194081eb
IM
674/*
675 * Shift right and round:
676 */
cf2ab469 677#define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
194081eb 678
cb1c4fc9 679static unsigned long
45bf76df
IM
680calc_delta_mine(unsigned long delta_exec, unsigned long weight,
681 struct load_weight *lw)
682{
683 u64 tmp;
684
685 if (unlikely(!lw->inv_weight))
194081eb 686 lw->inv_weight = (WMULT_CONST - lw->weight/2) / lw->weight + 1;
45bf76df
IM
687
688 tmp = (u64)delta_exec * weight;
689 /*
690 * Check whether we'd overflow the 64-bit multiplication:
691 */
194081eb 692 if (unlikely(tmp > WMULT_CONST))
cf2ab469 693 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
194081eb
IM
694 WMULT_SHIFT/2);
695 else
cf2ab469 696 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
45bf76df 697
ecf691da 698 return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
45bf76df
IM
699}
700
701static inline unsigned long
702calc_delta_fair(unsigned long delta_exec, struct load_weight *lw)
703{
704 return calc_delta_mine(delta_exec, NICE_0_LOAD, lw);
705}
706
1091985b 707static inline void update_load_add(struct load_weight *lw, unsigned long inc)
45bf76df
IM
708{
709 lw->weight += inc;
45bf76df
IM
710}
711
1091985b 712static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
45bf76df
IM
713{
714 lw->weight -= dec;
45bf76df
IM
715}
716
2dd73a4f
PW
717/*
718 * To aid in avoiding the subversion of "niceness" due to uneven distribution
719 * of tasks with abnormal "nice" values across CPUs the contribution that
720 * each task makes to its run queue's load is weighted according to its
721 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
722 * scaled version of the new time slice allocation that they receive on time
723 * slice expiry etc.
724 */
725
dd41f596
IM
726#define WEIGHT_IDLEPRIO 2
727#define WMULT_IDLEPRIO (1 << 31)
728
729/*
730 * Nice levels are multiplicative, with a gentle 10% change for every
731 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
732 * nice 1, it will get ~10% less CPU time than another CPU-bound task
733 * that remained on nice 0.
734 *
735 * The "10% effect" is relative and cumulative: from _any_ nice level,
736 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
f9153ee6
IM
737 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
738 * If a task goes up by ~10% and another task goes down by ~10% then
739 * the relative distance between them is ~25%.)
dd41f596
IM
740 */
741static const int prio_to_weight[40] = {
254753dc
IM
742 /* -20 */ 88761, 71755, 56483, 46273, 36291,
743 /* -15 */ 29154, 23254, 18705, 14949, 11916,
744 /* -10 */ 9548, 7620, 6100, 4904, 3906,
745 /* -5 */ 3121, 2501, 1991, 1586, 1277,
746 /* 0 */ 1024, 820, 655, 526, 423,
747 /* 5 */ 335, 272, 215, 172, 137,
748 /* 10 */ 110, 87, 70, 56, 45,
749 /* 15 */ 36, 29, 23, 18, 15,
dd41f596
IM
750};
751
5714d2de
IM
752/*
753 * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
754 *
755 * In cases where the weight does not change often, we can use the
756 * precalculated inverse to speed up arithmetics by turning divisions
757 * into multiplications:
758 */
dd41f596 759static const u32 prio_to_wmult[40] = {
254753dc
IM
760 /* -20 */ 48388, 59856, 76040, 92818, 118348,
761 /* -15 */ 147320, 184698, 229616, 287308, 360437,
762 /* -10 */ 449829, 563644, 704093, 875809, 1099582,
763 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326,
764 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587,
765 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126,
766 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717,
767 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
dd41f596 768};
2dd73a4f 769
dd41f596
IM
770static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
771
772/*
773 * runqueue iterator, to support SMP load-balancing between different
774 * scheduling classes, without having to expose their internal data
775 * structures to the load-balancing proper:
776 */
777struct rq_iterator {
778 void *arg;
779 struct task_struct *(*start)(void *);
780 struct task_struct *(*next)(void *);
781};
782
783static int balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
784 unsigned long max_nr_move, unsigned long max_load_move,
785 struct sched_domain *sd, enum cpu_idle_type idle,
786 int *all_pinned, unsigned long *load_moved,
a4ac01c3 787 int *this_best_prio, struct rq_iterator *iterator);
dd41f596
IM
788
789#include "sched_stats.h"
790#include "sched_rt.c"
791#include "sched_fair.c"
792#include "sched_idletask.c"
793#ifdef CONFIG_SCHED_DEBUG
794# include "sched_debug.c"
795#endif
796
797#define sched_class_highest (&rt_sched_class)
798
9c217245
IM
799/*
800 * Update delta_exec, delta_fair fields for rq.
801 *
802 * delta_fair clock advances at a rate inversely proportional to
495eca49 803 * total load (rq->load.weight) on the runqueue, while
9c217245
IM
804 * delta_exec advances at the same rate as wall-clock (provided
805 * cpu is not idle).
806 *
807 * delta_exec / delta_fair is a measure of the (smoothened) load on this
808 * runqueue over any given interval. This (smoothened) load is used
809 * during load balance.
810 *
495eca49 811 * This function is called /before/ updating rq->load
9c217245
IM
812 * and when switching tasks.
813 */
29b4b623 814static inline void inc_load(struct rq *rq, const struct task_struct *p)
9c217245 815{
495eca49 816 update_load_add(&rq->load, p->se.load.weight);
9c217245
IM
817}
818
79b5dddf 819static inline void dec_load(struct rq *rq, const struct task_struct *p)
9c217245 820{
495eca49 821 update_load_sub(&rq->load, p->se.load.weight);
9c217245
IM
822}
823
e5fa2237 824static void inc_nr_running(struct task_struct *p, struct rq *rq)
9c217245
IM
825{
826 rq->nr_running++;
29b4b623 827 inc_load(rq, p);
9c217245
IM
828}
829
db53181e 830static void dec_nr_running(struct task_struct *p, struct rq *rq)
9c217245
IM
831{
832 rq->nr_running--;
79b5dddf 833 dec_load(rq, p);
9c217245
IM
834}
835
45bf76df
IM
836static void set_load_weight(struct task_struct *p)
837{
838 if (task_has_rt_policy(p)) {
dd41f596
IM
839 p->se.load.weight = prio_to_weight[0] * 2;
840 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
841 return;
842 }
45bf76df 843
dd41f596
IM
844 /*
845 * SCHED_IDLE tasks get minimal weight:
846 */
847 if (p->policy == SCHED_IDLE) {
848 p->se.load.weight = WEIGHT_IDLEPRIO;
849 p->se.load.inv_weight = WMULT_IDLEPRIO;
850 return;
851 }
71f8bd46 852
dd41f596
IM
853 p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
854 p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
71f8bd46
IM
855}
856
8159f87e 857static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
71f8bd46 858{
dd41f596 859 sched_info_queued(p);
fd390f6a 860 p->sched_class->enqueue_task(rq, p, wakeup);
dd41f596 861 p->se.on_rq = 1;
71f8bd46
IM
862}
863
69be72c1 864static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
71f8bd46 865{
f02231e5 866 p->sched_class->dequeue_task(rq, p, sleep);
dd41f596 867 p->se.on_rq = 0;
71f8bd46
IM
868}
869
14531189 870/*
dd41f596 871 * __normal_prio - return the priority that is based on the static prio
14531189 872 */
14531189
IM
873static inline int __normal_prio(struct task_struct *p)
874{
dd41f596 875 return p->static_prio;
14531189
IM
876}
877
b29739f9
IM
878/*
879 * Calculate the expected normal priority: i.e. priority
880 * without taking RT-inheritance into account. Might be
881 * boosted by interactivity modifiers. Changes upon fork,
882 * setprio syscalls, and whenever the interactivity
883 * estimator recalculates.
884 */
36c8b586 885static inline int normal_prio(struct task_struct *p)
b29739f9
IM
886{
887 int prio;
888
e05606d3 889 if (task_has_rt_policy(p))
b29739f9
IM
890 prio = MAX_RT_PRIO-1 - p->rt_priority;
891 else
892 prio = __normal_prio(p);
893 return prio;
894}
895
896/*
897 * Calculate the current priority, i.e. the priority
898 * taken into account by the scheduler. This value might
899 * be boosted by RT tasks, or might be boosted by
900 * interactivity modifiers. Will be RT if the task got
901 * RT-boosted. If not then it returns p->normal_prio.
902 */
36c8b586 903static int effective_prio(struct task_struct *p)
b29739f9
IM
904{
905 p->normal_prio = normal_prio(p);
906 /*
907 * If we are RT tasks or we were boosted to RT priority,
908 * keep the priority unchanged. Otherwise, update priority
909 * to the normal priority:
910 */
911 if (!rt_prio(p->prio))
912 return p->normal_prio;
913 return p->prio;
914}
915
1da177e4 916/*
dd41f596 917 * activate_task - move a task to the runqueue.
1da177e4 918 */
dd41f596 919static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1da177e4 920{
dd41f596
IM
921 if (p->state == TASK_UNINTERRUPTIBLE)
922 rq->nr_uninterruptible--;
1da177e4 923
8159f87e 924 enqueue_task(rq, p, wakeup);
e5fa2237 925 inc_nr_running(p, rq);
1da177e4
LT
926}
927
928/*
dd41f596 929 * activate_idle_task - move idle task to the _front_ of runqueue.
1da177e4 930 */
dd41f596 931static inline void activate_idle_task(struct task_struct *p, struct rq *rq)
1da177e4 932{
a8e504d2 933 update_rq_clock(rq);
1da177e4 934
dd41f596
IM
935 if (p->state == TASK_UNINTERRUPTIBLE)
936 rq->nr_uninterruptible--;
ece8a684 937
8159f87e 938 enqueue_task(rq, p, 0);
e5fa2237 939 inc_nr_running(p, rq);
1da177e4
LT
940}
941
942/*
943 * deactivate_task - remove a task from the runqueue.
944 */
2e1cb74a 945static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1da177e4 946{
dd41f596
IM
947 if (p->state == TASK_UNINTERRUPTIBLE)
948 rq->nr_uninterruptible++;
949
69be72c1 950 dequeue_task(rq, p, sleep);
db53181e 951 dec_nr_running(p, rq);
1da177e4
LT
952}
953
1da177e4
LT
954/**
955 * task_curr - is this task currently executing on a CPU?
956 * @p: the task in question.
957 */
36c8b586 958inline int task_curr(const struct task_struct *p)
1da177e4
LT
959{
960 return cpu_curr(task_cpu(p)) == p;
961}
962
2dd73a4f
PW
963/* Used instead of source_load when we know the type == 0 */
964unsigned long weighted_cpuload(const int cpu)
965{
495eca49 966 return cpu_rq(cpu)->load.weight;
dd41f596
IM
967}
968
969static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
970{
971#ifdef CONFIG_SMP
972 task_thread_info(p)->cpu = cpu;
973 set_task_cfs_rq(p);
974#endif
2dd73a4f
PW
975}
976
1da177e4 977#ifdef CONFIG_SMP
c65cc870 978
dd41f596 979void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
c65cc870 980{
dd41f596
IM
981 int old_cpu = task_cpu(p);
982 struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
bbdba7c0 983 u64 clock_offset;
dd41f596
IM
984
985 clock_offset = old_rq->clock - new_rq->clock;
6cfb0d5d
IM
986
987#ifdef CONFIG_SCHEDSTATS
988 if (p->se.wait_start)
989 p->se.wait_start -= clock_offset;
dd41f596
IM
990 if (p->se.sleep_start)
991 p->se.sleep_start -= clock_offset;
992 if (p->se.block_start)
993 p->se.block_start -= clock_offset;
6cfb0d5d 994#endif
dd41f596
IM
995
996 __set_task_cpu(p, new_cpu);
c65cc870
IM
997}
998
70b97a7f 999struct migration_req {
1da177e4 1000 struct list_head list;
1da177e4 1001
36c8b586 1002 struct task_struct *task;
1da177e4
LT
1003 int dest_cpu;
1004
1da177e4 1005 struct completion done;
70b97a7f 1006};
1da177e4
LT
1007
1008/*
1009 * The task's runqueue lock must be held.
1010 * Returns true if you have to wait for migration thread.
1011 */
36c8b586 1012static int
70b97a7f 1013migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1da177e4 1014{
70b97a7f 1015 struct rq *rq = task_rq(p);
1da177e4
LT
1016
1017 /*
1018 * If the task is not on a runqueue (and not running), then
1019 * it is sufficient to simply update the task's cpu field.
1020 */
dd41f596 1021 if (!p->se.on_rq && !task_running(rq, p)) {
1da177e4
LT
1022 set_task_cpu(p, dest_cpu);
1023 return 0;
1024 }
1025
1026 init_completion(&req->done);
1da177e4
LT
1027 req->task = p;
1028 req->dest_cpu = dest_cpu;
1029 list_add(&req->list, &rq->migration_queue);
48f24c4d 1030
1da177e4
LT
1031 return 1;
1032}
1033
1034/*
1035 * wait_task_inactive - wait for a thread to unschedule.
1036 *
1037 * The caller must ensure that the task *will* unschedule sometime soon,
1038 * else this function might spin for a *long* time. This function can't
1039 * be called with interrupts off, or it may introduce deadlock with
1040 * smp_call_function() if an IPI is sent by the same process we are
1041 * waiting to become inactive.
1042 */
36c8b586 1043void wait_task_inactive(struct task_struct *p)
1da177e4
LT
1044{
1045 unsigned long flags;
dd41f596 1046 int running, on_rq;
70b97a7f 1047 struct rq *rq;
1da177e4
LT
1048
1049repeat:
fa490cfd
LT
1050 /*
1051 * We do the initial early heuristics without holding
1052 * any task-queue locks at all. We'll only try to get
1053 * the runqueue lock when things look like they will
1054 * work out!
1055 */
1056 rq = task_rq(p);
1057
1058 /*
1059 * If the task is actively running on another CPU
1060 * still, just relax and busy-wait without holding
1061 * any locks.
1062 *
1063 * NOTE! Since we don't hold any locks, it's not
1064 * even sure that "rq" stays as the right runqueue!
1065 * But we don't care, since "task_running()" will
1066 * return false if the runqueue has changed and p
1067 * is actually now running somewhere else!
1068 */
1069 while (task_running(rq, p))
1070 cpu_relax();
1071
1072 /*
1073 * Ok, time to look more closely! We need the rq
1074 * lock now, to be *sure*. If we're wrong, we'll
1075 * just go back and repeat.
1076 */
1da177e4 1077 rq = task_rq_lock(p, &flags);
fa490cfd 1078 running = task_running(rq, p);
dd41f596 1079 on_rq = p->se.on_rq;
fa490cfd
LT
1080 task_rq_unlock(rq, &flags);
1081
1082 /*
1083 * Was it really running after all now that we
1084 * checked with the proper locks actually held?
1085 *
1086 * Oops. Go back and try again..
1087 */
1088 if (unlikely(running)) {
1da177e4 1089 cpu_relax();
1da177e4
LT
1090 goto repeat;
1091 }
fa490cfd
LT
1092
1093 /*
1094 * It's not enough that it's not actively running,
1095 * it must be off the runqueue _entirely_, and not
1096 * preempted!
1097 *
1098 * So if it wa still runnable (but just not actively
1099 * running right now), it's preempted, and we should
1100 * yield - it could be a while.
1101 */
dd41f596 1102 if (unlikely(on_rq)) {
fa490cfd
LT
1103 yield();
1104 goto repeat;
1105 }
1106
1107 /*
1108 * Ahh, all good. It wasn't running, and it wasn't
1109 * runnable, which means that it will never become
1110 * running in the future either. We're all done!
1111 */
1da177e4
LT
1112}
1113
1114/***
1115 * kick_process - kick a running thread to enter/exit the kernel
1116 * @p: the to-be-kicked thread
1117 *
1118 * Cause a process which is running on another CPU to enter
1119 * kernel-mode, without any delay. (to get signals handled.)
1120 *
1121 * NOTE: this function doesnt have to take the runqueue lock,
1122 * because all it wants to ensure is that the remote task enters
1123 * the kernel. If the IPI races and the task has been migrated
1124 * to another CPU then no harm is done and the purpose has been
1125 * achieved as well.
1126 */
36c8b586 1127void kick_process(struct task_struct *p)
1da177e4
LT
1128{
1129 int cpu;
1130
1131 preempt_disable();
1132 cpu = task_cpu(p);
1133 if ((cpu != smp_processor_id()) && task_curr(p))
1134 smp_send_reschedule(cpu);
1135 preempt_enable();
1136}
1137
1138/*
2dd73a4f
PW
1139 * Return a low guess at the load of a migration-source cpu weighted
1140 * according to the scheduling class and "nice" value.
1da177e4
LT
1141 *
1142 * We want to under-estimate the load of migration sources, to
1143 * balance conservatively.
1144 */
a2000572 1145static inline unsigned long source_load(int cpu, int type)
1da177e4 1146{
70b97a7f 1147 struct rq *rq = cpu_rq(cpu);
dd41f596 1148 unsigned long total = weighted_cpuload(cpu);
2dd73a4f 1149
3b0bd9bc 1150 if (type == 0)
dd41f596 1151 return total;
b910472d 1152
dd41f596 1153 return min(rq->cpu_load[type-1], total);
1da177e4
LT
1154}
1155
1156/*
2dd73a4f
PW
1157 * Return a high guess at the load of a migration-target cpu weighted
1158 * according to the scheduling class and "nice" value.
1da177e4 1159 */
a2000572 1160static inline unsigned long target_load(int cpu, int type)
1da177e4 1161{
70b97a7f 1162 struct rq *rq = cpu_rq(cpu);
dd41f596 1163 unsigned long total = weighted_cpuload(cpu);
2dd73a4f 1164
7897986b 1165 if (type == 0)
dd41f596 1166 return total;
3b0bd9bc 1167
dd41f596 1168 return max(rq->cpu_load[type-1], total);
2dd73a4f
PW
1169}
1170
1171/*
1172 * Return the average load per task on the cpu's run queue
1173 */
1174static inline unsigned long cpu_avg_load_per_task(int cpu)
1175{
70b97a7f 1176 struct rq *rq = cpu_rq(cpu);
dd41f596 1177 unsigned long total = weighted_cpuload(cpu);
2dd73a4f
PW
1178 unsigned long n = rq->nr_running;
1179
dd41f596 1180 return n ? total / n : SCHED_LOAD_SCALE;
1da177e4
LT
1181}
1182
147cbb4b
NP
1183/*
1184 * find_idlest_group finds and returns the least busy CPU group within the
1185 * domain.
1186 */
1187static struct sched_group *
1188find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1189{
1190 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1191 unsigned long min_load = ULONG_MAX, this_load = 0;
1192 int load_idx = sd->forkexec_idx;
1193 int imbalance = 100 + (sd->imbalance_pct-100)/2;
1194
1195 do {
1196 unsigned long load, avg_load;
1197 int local_group;
1198 int i;
1199
da5a5522
BD
1200 /* Skip over this group if it has no CPUs allowed */
1201 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
1202 goto nextgroup;
1203
147cbb4b 1204 local_group = cpu_isset(this_cpu, group->cpumask);
147cbb4b
NP
1205
1206 /* Tally up the load of all CPUs in the group */
1207 avg_load = 0;
1208
1209 for_each_cpu_mask(i, group->cpumask) {
1210 /* Bias balancing toward cpus of our domain */
1211 if (local_group)
1212 load = source_load(i, load_idx);
1213 else
1214 load = target_load(i, load_idx);
1215
1216 avg_load += load;
1217 }
1218
1219 /* Adjust by relative CPU power of the group */
5517d86b
ED
1220 avg_load = sg_div_cpu_power(group,
1221 avg_load * SCHED_LOAD_SCALE);
147cbb4b
NP
1222
1223 if (local_group) {
1224 this_load = avg_load;
1225 this = group;
1226 } else if (avg_load < min_load) {
1227 min_load = avg_load;
1228 idlest = group;
1229 }
da5a5522 1230nextgroup:
147cbb4b
NP
1231 group = group->next;
1232 } while (group != sd->groups);
1233
1234 if (!idlest || 100*this_load < imbalance*min_load)
1235 return NULL;
1236 return idlest;
1237}
1238
1239/*
0feaece9 1240 * find_idlest_cpu - find the idlest cpu among the cpus in group.
147cbb4b 1241 */
95cdf3b7
IM
1242static int
1243find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
147cbb4b 1244{
da5a5522 1245 cpumask_t tmp;
147cbb4b
NP
1246 unsigned long load, min_load = ULONG_MAX;
1247 int idlest = -1;
1248 int i;
1249
da5a5522
BD
1250 /* Traverse only the allowed CPUs */
1251 cpus_and(tmp, group->cpumask, p->cpus_allowed);
1252
1253 for_each_cpu_mask(i, tmp) {
2dd73a4f 1254 load = weighted_cpuload(i);
147cbb4b
NP
1255
1256 if (load < min_load || (load == min_load && i == this_cpu)) {
1257 min_load = load;
1258 idlest = i;
1259 }
1260 }
1261
1262 return idlest;
1263}
1264
476d139c
NP
1265/*
1266 * sched_balance_self: balance the current task (running on cpu) in domains
1267 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1268 * SD_BALANCE_EXEC.
1269 *
1270 * Balance, ie. select the least loaded group.
1271 *
1272 * Returns the target CPU number, or the same CPU if no balancing is needed.
1273 *
1274 * preempt must be disabled.
1275 */
1276static int sched_balance_self(int cpu, int flag)
1277{
1278 struct task_struct *t = current;
1279 struct sched_domain *tmp, *sd = NULL;
147cbb4b 1280
c96d145e 1281 for_each_domain(cpu, tmp) {
9761eea8
IM
1282 /*
1283 * If power savings logic is enabled for a domain, stop there.
1284 */
5c45bf27
SS
1285 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
1286 break;
476d139c
NP
1287 if (tmp->flags & flag)
1288 sd = tmp;
c96d145e 1289 }
476d139c
NP
1290
1291 while (sd) {
1292 cpumask_t span;
1293 struct sched_group *group;
1a848870
SS
1294 int new_cpu, weight;
1295
1296 if (!(sd->flags & flag)) {
1297 sd = sd->child;
1298 continue;
1299 }
476d139c
NP
1300
1301 span = sd->span;
1302 group = find_idlest_group(sd, t, cpu);
1a848870
SS
1303 if (!group) {
1304 sd = sd->child;
1305 continue;
1306 }
476d139c 1307
da5a5522 1308 new_cpu = find_idlest_cpu(group, t, cpu);
1a848870
SS
1309 if (new_cpu == -1 || new_cpu == cpu) {
1310 /* Now try balancing at a lower domain level of cpu */
1311 sd = sd->child;
1312 continue;
1313 }
476d139c 1314
1a848870 1315 /* Now try balancing at a lower domain level of new_cpu */
476d139c 1316 cpu = new_cpu;
476d139c
NP
1317 sd = NULL;
1318 weight = cpus_weight(span);
1319 for_each_domain(cpu, tmp) {
1320 if (weight <= cpus_weight(tmp->span))
1321 break;
1322 if (tmp->flags & flag)
1323 sd = tmp;
1324 }
1325 /* while loop will break here if sd == NULL */
1326 }
1327
1328 return cpu;
1329}
1330
1331#endif /* CONFIG_SMP */
1da177e4
LT
1332
1333/*
1334 * wake_idle() will wake a task on an idle cpu if task->cpu is
1335 * not idle and an idle cpu is available. The span of cpus to
1336 * search starts with cpus closest then further out as needed,
1337 * so we always favor a closer, idle cpu.
1338 *
1339 * Returns the CPU we should wake onto.
1340 */
1341#if defined(ARCH_HAS_SCHED_WAKE_IDLE)
36c8b586 1342static int wake_idle(int cpu, struct task_struct *p)
1da177e4
LT
1343{
1344 cpumask_t tmp;
1345 struct sched_domain *sd;
1346 int i;
1347
4953198b
SS
1348 /*
1349 * If it is idle, then it is the best cpu to run this task.
1350 *
1351 * This cpu is also the best, if it has more than one task already.
1352 * Siblings must be also busy(in most cases) as they didn't already
1353 * pickup the extra load from this cpu and hence we need not check
1354 * sibling runqueue info. This will avoid the checks and cache miss
1355 * penalities associated with that.
1356 */
1357 if (idle_cpu(cpu) || cpu_rq(cpu)->nr_running > 1)
1da177e4
LT
1358 return cpu;
1359
1360 for_each_domain(cpu, sd) {
1361 if (sd->flags & SD_WAKE_IDLE) {
e0f364f4 1362 cpus_and(tmp, sd->span, p->cpus_allowed);
1da177e4
LT
1363 for_each_cpu_mask(i, tmp) {
1364 if (idle_cpu(i))
1365 return i;
1366 }
9761eea8 1367 } else {
e0f364f4 1368 break;
9761eea8 1369 }
1da177e4
LT
1370 }
1371 return cpu;
1372}
1373#else
36c8b586 1374static inline int wake_idle(int cpu, struct task_struct *p)
1da177e4
LT
1375{
1376 return cpu;
1377}
1378#endif
1379
1380/***
1381 * try_to_wake_up - wake up a thread
1382 * @p: the to-be-woken-up thread
1383 * @state: the mask of task states that can be woken
1384 * @sync: do a synchronous wakeup?
1385 *
1386 * Put it on the run-queue if it's not already there. The "current"
1387 * thread is always on the run-queue (except when the actual
1388 * re-schedule is in progress), and as such you're allowed to do
1389 * the simpler "current->state = TASK_RUNNING" to mark yourself
1390 * runnable without the overhead of this.
1391 *
1392 * returns failure only if the task is already active.
1393 */
36c8b586 1394static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
1da177e4
LT
1395{
1396 int cpu, this_cpu, success = 0;
1397 unsigned long flags;
1398 long old_state;
70b97a7f 1399 struct rq *rq;
1da177e4 1400#ifdef CONFIG_SMP
7897986b 1401 struct sched_domain *sd, *this_sd = NULL;
70b97a7f 1402 unsigned long load, this_load;
1da177e4
LT
1403 int new_cpu;
1404#endif
1405
1406 rq = task_rq_lock(p, &flags);
1407 old_state = p->state;
1408 if (!(old_state & state))
1409 goto out;
1410
dd41f596 1411 if (p->se.on_rq)
1da177e4
LT
1412 goto out_running;
1413
1414 cpu = task_cpu(p);
1415 this_cpu = smp_processor_id();
1416
1417#ifdef CONFIG_SMP
1418 if (unlikely(task_running(rq, p)))
1419 goto out_activate;
1420
7897986b
NP
1421 new_cpu = cpu;
1422
1da177e4
LT
1423 schedstat_inc(rq, ttwu_cnt);
1424 if (cpu == this_cpu) {
1425 schedstat_inc(rq, ttwu_local);
7897986b
NP
1426 goto out_set_cpu;
1427 }
1428
1429 for_each_domain(this_cpu, sd) {
1430 if (cpu_isset(cpu, sd->span)) {
1431 schedstat_inc(sd, ttwu_wake_remote);
1432 this_sd = sd;
1433 break;
1da177e4
LT
1434 }
1435 }
1da177e4 1436
7897986b 1437 if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1da177e4
LT
1438 goto out_set_cpu;
1439
1da177e4 1440 /*
7897986b 1441 * Check for affine wakeup and passive balancing possibilities.
1da177e4 1442 */
7897986b
NP
1443 if (this_sd) {
1444 int idx = this_sd->wake_idx;
1445 unsigned int imbalance;
1da177e4 1446
a3f21bce
NP
1447 imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
1448
7897986b
NP
1449 load = source_load(cpu, idx);
1450 this_load = target_load(this_cpu, idx);
1da177e4 1451
7897986b
NP
1452 new_cpu = this_cpu; /* Wake to this CPU if we can */
1453
a3f21bce
NP
1454 if (this_sd->flags & SD_WAKE_AFFINE) {
1455 unsigned long tl = this_load;
33859f7f
MOS
1456 unsigned long tl_per_task;
1457
1458 tl_per_task = cpu_avg_load_per_task(this_cpu);
2dd73a4f 1459
1da177e4 1460 /*
a3f21bce
NP
1461 * If sync wakeup then subtract the (maximum possible)
1462 * effect of the currently running task from the load
1463 * of the current CPU:
1da177e4 1464 */
a3f21bce 1465 if (sync)
dd41f596 1466 tl -= current->se.load.weight;
a3f21bce
NP
1467
1468 if ((tl <= load &&
2dd73a4f 1469 tl + target_load(cpu, idx) <= tl_per_task) ||
dd41f596 1470 100*(tl + p->se.load.weight) <= imbalance*load) {
a3f21bce
NP
1471 /*
1472 * This domain has SD_WAKE_AFFINE and
1473 * p is cache cold in this domain, and
1474 * there is no bad imbalance.
1475 */
1476 schedstat_inc(this_sd, ttwu_move_affine);
1477 goto out_set_cpu;
1478 }
1479 }
1480
1481 /*
1482 * Start passive balancing when half the imbalance_pct
1483 * limit is reached.
1484 */
1485 if (this_sd->flags & SD_WAKE_BALANCE) {
1486 if (imbalance*this_load <= 100*load) {
1487 schedstat_inc(this_sd, ttwu_move_balance);
1488 goto out_set_cpu;
1489 }
1da177e4
LT
1490 }
1491 }
1492
1493 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1494out_set_cpu:
1495 new_cpu = wake_idle(new_cpu, p);
1496 if (new_cpu != cpu) {
1497 set_task_cpu(p, new_cpu);
1498 task_rq_unlock(rq, &flags);
1499 /* might preempt at this point */
1500 rq = task_rq_lock(p, &flags);
1501 old_state = p->state;
1502 if (!(old_state & state))
1503 goto out;
dd41f596 1504 if (p->se.on_rq)
1da177e4
LT
1505 goto out_running;
1506
1507 this_cpu = smp_processor_id();
1508 cpu = task_cpu(p);
1509 }
1510
1511out_activate:
1512#endif /* CONFIG_SMP */
2daa3577 1513 update_rq_clock(rq);
dd41f596 1514 activate_task(rq, p, 1);
1da177e4
LT
1515 /*
1516 * Sync wakeups (i.e. those types of wakeups where the waker
1517 * has indicated that it will leave the CPU in short order)
1518 * don't trigger a preemption, if the woken up task will run on
1519 * this cpu. (in this case the 'I will reschedule' promise of
1520 * the waker guarantees that the freshly woken up task is going
1521 * to be considered on this CPU.)
1522 */
dd41f596
IM
1523 if (!sync || cpu != this_cpu)
1524 check_preempt_curr(rq, p);
1da177e4
LT
1525 success = 1;
1526
1527out_running:
1528 p->state = TASK_RUNNING;
1529out:
1530 task_rq_unlock(rq, &flags);
1531
1532 return success;
1533}
1534
36c8b586 1535int fastcall wake_up_process(struct task_struct *p)
1da177e4
LT
1536{
1537 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1538 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1539}
1da177e4
LT
1540EXPORT_SYMBOL(wake_up_process);
1541
36c8b586 1542int fastcall wake_up_state(struct task_struct *p, unsigned int state)
1da177e4
LT
1543{
1544 return try_to_wake_up(p, state, 0);
1545}
1546
1da177e4
LT
1547/*
1548 * Perform scheduler related setup for a newly forked process p.
1549 * p is forked by current.
dd41f596
IM
1550 *
1551 * __sched_fork() is basic setup used by init_idle() too:
1552 */
1553static void __sched_fork(struct task_struct *p)
1554{
dd41f596
IM
1555 p->se.exec_start = 0;
1556 p->se.sum_exec_runtime = 0;
f6cf891c 1557 p->se.prev_sum_exec_runtime = 0;
6cfb0d5d
IM
1558
1559#ifdef CONFIG_SCHEDSTATS
1560 p->se.wait_start = 0;
dd41f596
IM
1561 p->se.sum_sleep_runtime = 0;
1562 p->se.sleep_start = 0;
dd41f596
IM
1563 p->se.block_start = 0;
1564 p->se.sleep_max = 0;
1565 p->se.block_max = 0;
1566 p->se.exec_max = 0;
eba1ed4b 1567 p->se.slice_max = 0;
dd41f596 1568 p->se.wait_max = 0;
6cfb0d5d 1569#endif
476d139c 1570
dd41f596
IM
1571 INIT_LIST_HEAD(&p->run_list);
1572 p->se.on_rq = 0;
476d139c 1573
e107be36
AK
1574#ifdef CONFIG_PREEMPT_NOTIFIERS
1575 INIT_HLIST_HEAD(&p->preempt_notifiers);
1576#endif
1577
1da177e4
LT
1578 /*
1579 * We mark the process as running here, but have not actually
1580 * inserted it onto the runqueue yet. This guarantees that
1581 * nobody will actually run it, and a signal or other external
1582 * event cannot wake it up and insert it on the runqueue either.
1583 */
1584 p->state = TASK_RUNNING;
dd41f596
IM
1585}
1586
1587/*
1588 * fork()/clone()-time setup:
1589 */
1590void sched_fork(struct task_struct *p, int clone_flags)
1591{
1592 int cpu = get_cpu();
1593
1594 __sched_fork(p);
1595
1596#ifdef CONFIG_SMP
1597 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
1598#endif
1599 __set_task_cpu(p, cpu);
b29739f9
IM
1600
1601 /*
1602 * Make sure we do not leak PI boosting priority to the child:
1603 */
1604 p->prio = current->normal_prio;
1605
52f17b6c 1606#if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
dd41f596 1607 if (likely(sched_info_on()))
52f17b6c 1608 memset(&p->sched_info, 0, sizeof(p->sched_info));
1da177e4 1609#endif
d6077cb8 1610#if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
4866cde0
NP
1611 p->oncpu = 0;
1612#endif
1da177e4 1613#ifdef CONFIG_PREEMPT
4866cde0 1614 /* Want to start with kernel preemption disabled. */
a1261f54 1615 task_thread_info(p)->preempt_count = 1;
1da177e4 1616#endif
476d139c 1617 put_cpu();
1da177e4
LT
1618}
1619
1620/*
1621 * wake_up_new_task - wake up a newly created task for the first time.
1622 *
1623 * This function will do some initial scheduler statistics housekeeping
1624 * that must be done for every newly created context, then puts the task
1625 * on the runqueue and wakes it.
1626 */
36c8b586 1627void fastcall wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
1da177e4
LT
1628{
1629 unsigned long flags;
dd41f596
IM
1630 struct rq *rq;
1631 int this_cpu;
1da177e4
LT
1632
1633 rq = task_rq_lock(p, &flags);
147cbb4b 1634 BUG_ON(p->state != TASK_RUNNING);
dd41f596 1635 this_cpu = smp_processor_id(); /* parent's CPU */
a8e504d2 1636 update_rq_clock(rq);
1da177e4
LT
1637
1638 p->prio = effective_prio(p);
1639
9c95e731
HS
1640 if (rt_prio(p->prio))
1641 p->sched_class = &rt_sched_class;
1642 else
1643 p->sched_class = &fair_sched_class;
1644
44142fac
IM
1645 if (task_cpu(p) != this_cpu || !p->sched_class->task_new ||
1646 !current->se.on_rq) {
dd41f596 1647 activate_task(rq, p, 0);
1da177e4 1648 } else {
1da177e4 1649 /*
dd41f596
IM
1650 * Let the scheduling class do new task startup
1651 * management (if any):
1da177e4 1652 */
ee0827d8 1653 p->sched_class->task_new(rq, p);
e5fa2237 1654 inc_nr_running(p, rq);
1da177e4 1655 }
dd41f596
IM
1656 check_preempt_curr(rq, p);
1657 task_rq_unlock(rq, &flags);
1da177e4
LT
1658}
1659
e107be36
AK
1660#ifdef CONFIG_PREEMPT_NOTIFIERS
1661
1662/**
421cee29
RD
1663 * preempt_notifier_register - tell me when current is being being preempted & rescheduled
1664 * @notifier: notifier struct to register
e107be36
AK
1665 */
1666void preempt_notifier_register(struct preempt_notifier *notifier)
1667{
1668 hlist_add_head(&notifier->link, &current->preempt_notifiers);
1669}
1670EXPORT_SYMBOL_GPL(preempt_notifier_register);
1671
1672/**
1673 * preempt_notifier_unregister - no longer interested in preemption notifications
421cee29 1674 * @notifier: notifier struct to unregister
e107be36
AK
1675 *
1676 * This is safe to call from within a preemption notifier.
1677 */
1678void preempt_notifier_unregister(struct preempt_notifier *notifier)
1679{
1680 hlist_del(&notifier->link);
1681}
1682EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
1683
1684static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
1685{
1686 struct preempt_notifier *notifier;
1687 struct hlist_node *node;
1688
1689 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
1690 notifier->ops->sched_in(notifier, raw_smp_processor_id());
1691}
1692
1693static void
1694fire_sched_out_preempt_notifiers(struct task_struct *curr,
1695 struct task_struct *next)
1696{
1697 struct preempt_notifier *notifier;
1698 struct hlist_node *node;
1699
1700 hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
1701 notifier->ops->sched_out(notifier, next);
1702}
1703
1704#else
1705
1706static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
1707{
1708}
1709
1710static void
1711fire_sched_out_preempt_notifiers(struct task_struct *curr,
1712 struct task_struct *next)
1713{
1714}
1715
1716#endif
1717
4866cde0
NP
1718/**
1719 * prepare_task_switch - prepare to switch tasks
1720 * @rq: the runqueue preparing to switch
421cee29 1721 * @prev: the current task that is being switched out
4866cde0
NP
1722 * @next: the task we are going to switch to.
1723 *
1724 * This is called with the rq lock held and interrupts off. It must
1725 * be paired with a subsequent finish_task_switch after the context
1726 * switch.
1727 *
1728 * prepare_task_switch sets up locking and calls architecture specific
1729 * hooks.
1730 */
e107be36
AK
1731static inline void
1732prepare_task_switch(struct rq *rq, struct task_struct *prev,
1733 struct task_struct *next)
4866cde0 1734{
e107be36 1735 fire_sched_out_preempt_notifiers(prev, next);
4866cde0
NP
1736 prepare_lock_switch(rq, next);
1737 prepare_arch_switch(next);
1738}
1739
1da177e4
LT
1740/**
1741 * finish_task_switch - clean up after a task-switch
344babaa 1742 * @rq: runqueue associated with task-switch
1da177e4
LT
1743 * @prev: the thread we just switched away from.
1744 *
4866cde0
NP
1745 * finish_task_switch must be called after the context switch, paired
1746 * with a prepare_task_switch call before the context switch.
1747 * finish_task_switch will reconcile locking set up by prepare_task_switch,
1748 * and do any other architecture-specific cleanup actions.
1da177e4
LT
1749 *
1750 * Note that we may have delayed dropping an mm in context_switch(). If
1751 * so, we finish that here outside of the runqueue lock. (Doing it
1752 * with the lock held can cause deadlocks; see schedule() for
1753 * details.)
1754 */
70b97a7f 1755static inline void finish_task_switch(struct rq *rq, struct task_struct *prev)
1da177e4
LT
1756 __releases(rq->lock)
1757{
1da177e4 1758 struct mm_struct *mm = rq->prev_mm;
55a101f8 1759 long prev_state;
1da177e4
LT
1760
1761 rq->prev_mm = NULL;
1762
1763 /*
1764 * A task struct has one reference for the use as "current".
c394cc9f 1765 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
55a101f8
ON
1766 * schedule one last time. The schedule call will never return, and
1767 * the scheduled task must drop that reference.
c394cc9f 1768 * The test for TASK_DEAD must occur while the runqueue locks are
1da177e4
LT
1769 * still held, otherwise prev could be scheduled on another cpu, die
1770 * there before we look at prev->state, and then the reference would
1771 * be dropped twice.
1772 * Manfred Spraul <manfred@colorfullife.com>
1773 */
55a101f8 1774 prev_state = prev->state;
4866cde0
NP
1775 finish_arch_switch(prev);
1776 finish_lock_switch(rq, prev);
e107be36 1777 fire_sched_in_preempt_notifiers(current);
1da177e4
LT
1778 if (mm)
1779 mmdrop(mm);
c394cc9f 1780 if (unlikely(prev_state == TASK_DEAD)) {
c6fd91f0 1781 /*
1782 * Remove function-return probe instances associated with this
1783 * task and put them back on the free list.
9761eea8 1784 */
c6fd91f0 1785 kprobe_flush_task(prev);
1da177e4 1786 put_task_struct(prev);
c6fd91f0 1787 }
1da177e4
LT
1788}
1789
1790/**
1791 * schedule_tail - first thing a freshly forked thread must call.
1792 * @prev: the thread we just switched away from.
1793 */
36c8b586 1794asmlinkage void schedule_tail(struct task_struct *prev)
1da177e4
LT
1795 __releases(rq->lock)
1796{
70b97a7f
IM
1797 struct rq *rq = this_rq();
1798
4866cde0
NP
1799 finish_task_switch(rq, prev);
1800#ifdef __ARCH_WANT_UNLOCKED_CTXSW
1801 /* In this case, finish_task_switch does not reenable preemption */
1802 preempt_enable();
1803#endif
1da177e4
LT
1804 if (current->set_child_tid)
1805 put_user(current->pid, current->set_child_tid);
1806}
1807
1808/*
1809 * context_switch - switch to the new MM and the new
1810 * thread's register state.
1811 */
dd41f596 1812static inline void
70b97a7f 1813context_switch(struct rq *rq, struct task_struct *prev,
36c8b586 1814 struct task_struct *next)
1da177e4 1815{
dd41f596 1816 struct mm_struct *mm, *oldmm;
1da177e4 1817
e107be36 1818 prepare_task_switch(rq, prev, next);
dd41f596
IM
1819 mm = next->mm;
1820 oldmm = prev->active_mm;
9226d125
ZA
1821 /*
1822 * For paravirt, this is coupled with an exit in switch_to to
1823 * combine the page table reload and the switch backend into
1824 * one hypercall.
1825 */
1826 arch_enter_lazy_cpu_mode();
1827
dd41f596 1828 if (unlikely(!mm)) {
1da177e4
LT
1829 next->active_mm = oldmm;
1830 atomic_inc(&oldmm->mm_count);
1831 enter_lazy_tlb(oldmm, next);
1832 } else
1833 switch_mm(oldmm, mm, next);
1834
dd41f596 1835 if (unlikely(!prev->mm)) {
1da177e4 1836 prev->active_mm = NULL;
1da177e4
LT
1837 rq->prev_mm = oldmm;
1838 }
3a5f5e48
IM
1839 /*
1840 * Since the runqueue lock will be released by the next
1841 * task (which is an invalid locking op but in the case
1842 * of the scheduler it's an obvious special-case), so we
1843 * do an early lockdep release here:
1844 */
1845#ifndef __ARCH_WANT_UNLOCKED_CTXSW
8a25d5de 1846 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
3a5f5e48 1847#endif
1da177e4
LT
1848
1849 /* Here we just switch the register state and the stack. */
1850 switch_to(prev, next, prev);
1851
dd41f596
IM
1852 barrier();
1853 /*
1854 * this_rq must be evaluated again because prev may have moved
1855 * CPUs since it called schedule(), thus the 'rq' on its stack
1856 * frame will be invalid.
1857 */
1858 finish_task_switch(this_rq(), prev);
1da177e4
LT
1859}
1860
1861/*
1862 * nr_running, nr_uninterruptible and nr_context_switches:
1863 *
1864 * externally visible scheduler statistics: current number of runnable
1865 * threads, current number of uninterruptible-sleeping threads, total
1866 * number of context switches performed since bootup.
1867 */
1868unsigned long nr_running(void)
1869{
1870 unsigned long i, sum = 0;
1871
1872 for_each_online_cpu(i)
1873 sum += cpu_rq(i)->nr_running;
1874
1875 return sum;
1876}
1877
1878unsigned long nr_uninterruptible(void)
1879{
1880 unsigned long i, sum = 0;
1881
0a945022 1882 for_each_possible_cpu(i)
1da177e4
LT
1883 sum += cpu_rq(i)->nr_uninterruptible;
1884
1885 /*
1886 * Since we read the counters lockless, it might be slightly
1887 * inaccurate. Do not allow it to go below zero though:
1888 */
1889 if (unlikely((long)sum < 0))
1890 sum = 0;
1891
1892 return sum;
1893}
1894
1895unsigned long long nr_context_switches(void)
1896{
cc94abfc
SR
1897 int i;
1898 unsigned long long sum = 0;
1da177e4 1899
0a945022 1900 for_each_possible_cpu(i)
1da177e4
LT
1901 sum += cpu_rq(i)->nr_switches;
1902
1903 return sum;
1904}
1905
1906unsigned long nr_iowait(void)
1907{
1908 unsigned long i, sum = 0;
1909
0a945022 1910 for_each_possible_cpu(i)
1da177e4
LT
1911 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1912
1913 return sum;
1914}
1915
db1b1fef
JS
1916unsigned long nr_active(void)
1917{
1918 unsigned long i, running = 0, uninterruptible = 0;
1919
1920 for_each_online_cpu(i) {
1921 running += cpu_rq(i)->nr_running;
1922 uninterruptible += cpu_rq(i)->nr_uninterruptible;
1923 }
1924
1925 if (unlikely((long)uninterruptible < 0))
1926 uninterruptible = 0;
1927
1928 return running + uninterruptible;
1929}
1930
48f24c4d 1931/*
dd41f596
IM
1932 * Update rq->cpu_load[] statistics. This function is usually called every
1933 * scheduler tick (TICK_NSEC).
48f24c4d 1934 */
dd41f596 1935static void update_cpu_load(struct rq *this_rq)
48f24c4d 1936{
495eca49 1937 unsigned long this_load = this_rq->load.weight;
dd41f596
IM
1938 int i, scale;
1939
1940 this_rq->nr_load_updates++;
dd41f596
IM
1941
1942 /* Update our load: */
1943 for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
1944 unsigned long old_load, new_load;
1945
1946 /* scale is effectively 1 << i now, and >> i divides by scale */
1947
1948 old_load = this_rq->cpu_load[i];
1949 new_load = this_load;
a25707f3
IM
1950 /*
1951 * Round up the averaging division if load is increasing. This
1952 * prevents us from getting stuck on 9 if the load is 10, for
1953 * example.
1954 */
1955 if (new_load > old_load)
1956 new_load += scale-1;
dd41f596
IM
1957 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
1958 }
48f24c4d
IM
1959}
1960
dd41f596
IM
1961#ifdef CONFIG_SMP
1962
1da177e4
LT
1963/*
1964 * double_rq_lock - safely lock two runqueues
1965 *
1966 * Note this does not disable interrupts like task_rq_lock,
1967 * you need to do so manually before calling.
1968 */
70b97a7f 1969static void double_rq_lock(struct rq *rq1, struct rq *rq2)
1da177e4
LT
1970 __acquires(rq1->lock)
1971 __acquires(rq2->lock)
1972{
054b9108 1973 BUG_ON(!irqs_disabled());
1da177e4
LT
1974 if (rq1 == rq2) {
1975 spin_lock(&rq1->lock);
1976 __acquire(rq2->lock); /* Fake it out ;) */
1977 } else {
c96d145e 1978 if (rq1 < rq2) {
1da177e4
LT
1979 spin_lock(&rq1->lock);
1980 spin_lock(&rq2->lock);
1981 } else {
1982 spin_lock(&rq2->lock);
1983 spin_lock(&rq1->lock);
1984 }
1985 }
6e82a3be
IM
1986 update_rq_clock(rq1);
1987 update_rq_clock(rq2);
1da177e4
LT
1988}
1989
1990/*
1991 * double_rq_unlock - safely unlock two runqueues
1992 *
1993 * Note this does not restore interrupts like task_rq_unlock,
1994 * you need to do so manually after calling.
1995 */
70b97a7f 1996static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
1da177e4
LT
1997 __releases(rq1->lock)
1998 __releases(rq2->lock)
1999{
2000 spin_unlock(&rq1->lock);
2001 if (rq1 != rq2)
2002 spin_unlock(&rq2->lock);
2003 else
2004 __release(rq2->lock);
2005}
2006
2007/*
2008 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2009 */
70b97a7f 2010static void double_lock_balance(struct rq *this_rq, struct rq *busiest)
1da177e4
LT
2011 __releases(this_rq->lock)
2012 __acquires(busiest->lock)
2013 __acquires(this_rq->lock)
2014{
054b9108
KK
2015 if (unlikely(!irqs_disabled())) {
2016 /* printk() doesn't work good under rq->lock */
2017 spin_unlock(&this_rq->lock);
2018 BUG_ON(1);
2019 }
1da177e4 2020 if (unlikely(!spin_trylock(&busiest->lock))) {
c96d145e 2021 if (busiest < this_rq) {
1da177e4
LT
2022 spin_unlock(&this_rq->lock);
2023 spin_lock(&busiest->lock);
2024 spin_lock(&this_rq->lock);
2025 } else
2026 spin_lock(&busiest->lock);
2027 }
2028}
2029
1da177e4
LT
2030/*
2031 * If dest_cpu is allowed for this process, migrate the task to it.
2032 * This is accomplished by forcing the cpu_allowed mask to only
2033 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2034 * the cpu_allowed mask is restored.
2035 */
36c8b586 2036static void sched_migrate_task(struct task_struct *p, int dest_cpu)
1da177e4 2037{
70b97a7f 2038 struct migration_req req;
1da177e4 2039 unsigned long flags;
70b97a7f 2040 struct rq *rq;
1da177e4
LT
2041
2042 rq = task_rq_lock(p, &flags);
2043 if (!cpu_isset(dest_cpu, p->cpus_allowed)
2044 || unlikely(cpu_is_offline(dest_cpu)))
2045 goto out;
2046
2047 /* force the process onto the specified CPU */
2048 if (migrate_task(p, dest_cpu, &req)) {
2049 /* Need to wait for migration thread (might exit: take ref). */
2050 struct task_struct *mt = rq->migration_thread;
36c8b586 2051
1da177e4
LT
2052 get_task_struct(mt);
2053 task_rq_unlock(rq, &flags);
2054 wake_up_process(mt);
2055 put_task_struct(mt);
2056 wait_for_completion(&req.done);
36c8b586 2057
1da177e4
LT
2058 return;
2059 }
2060out:
2061 task_rq_unlock(rq, &flags);
2062}
2063
2064/*
476d139c
NP
2065 * sched_exec - execve() is a valuable balancing opportunity, because at
2066 * this point the task has the smallest effective memory and cache footprint.
1da177e4
LT
2067 */
2068void sched_exec(void)
2069{
1da177e4 2070 int new_cpu, this_cpu = get_cpu();
476d139c 2071 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
1da177e4 2072 put_cpu();
476d139c
NP
2073 if (new_cpu != this_cpu)
2074 sched_migrate_task(current, new_cpu);
1da177e4
LT
2075}
2076
2077/*
2078 * pull_task - move a task from a remote runqueue to the local runqueue.
2079 * Both runqueues must be locked.
2080 */
dd41f596
IM
2081static void pull_task(struct rq *src_rq, struct task_struct *p,
2082 struct rq *this_rq, int this_cpu)
1da177e4 2083{
2e1cb74a 2084 deactivate_task(src_rq, p, 0);
1da177e4 2085 set_task_cpu(p, this_cpu);
dd41f596 2086 activate_task(this_rq, p, 0);
1da177e4
LT
2087 /*
2088 * Note that idle threads have a prio of MAX_PRIO, for this test
2089 * to be always true for them.
2090 */
dd41f596 2091 check_preempt_curr(this_rq, p);
1da177e4
LT
2092}
2093
2094/*
2095 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2096 */
858119e1 2097static
70b97a7f 2098int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
d15bcfdb 2099 struct sched_domain *sd, enum cpu_idle_type idle,
95cdf3b7 2100 int *all_pinned)
1da177e4
LT
2101{
2102 /*
2103 * We do not migrate tasks that are:
2104 * 1) running (obviously), or
2105 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2106 * 3) are cache-hot on their current CPU.
2107 */
1da177e4
LT
2108 if (!cpu_isset(this_cpu, p->cpus_allowed))
2109 return 0;
81026794
NP
2110 *all_pinned = 0;
2111
2112 if (task_running(rq, p))
2113 return 0;
1da177e4 2114
1da177e4
LT
2115 return 1;
2116}
2117
dd41f596 2118static int balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2dd73a4f 2119 unsigned long max_nr_move, unsigned long max_load_move,
d15bcfdb 2120 struct sched_domain *sd, enum cpu_idle_type idle,
dd41f596 2121 int *all_pinned, unsigned long *load_moved,
a4ac01c3 2122 int *this_best_prio, struct rq_iterator *iterator)
1da177e4 2123{
dd41f596
IM
2124 int pulled = 0, pinned = 0, skip_for_load;
2125 struct task_struct *p;
2126 long rem_load_move = max_load_move;
1da177e4 2127
2dd73a4f 2128 if (max_nr_move == 0 || max_load_move == 0)
1da177e4
LT
2129 goto out;
2130
81026794
NP
2131 pinned = 1;
2132
1da177e4 2133 /*
dd41f596 2134 * Start the load-balancing iterator:
1da177e4 2135 */
dd41f596
IM
2136 p = iterator->start(iterator->arg);
2137next:
2138 if (!p)
1da177e4 2139 goto out;
50ddd969
PW
2140 /*
2141 * To help distribute high priority tasks accross CPUs we don't
2142 * skip a task if it will be the highest priority task (i.e. smallest
2143 * prio value) on its new queue regardless of its load weight
2144 */
dd41f596
IM
2145 skip_for_load = (p->se.load.weight >> 1) > rem_load_move +
2146 SCHED_LOAD_SCALE_FUZZ;
a4ac01c3 2147 if ((skip_for_load && p->prio >= *this_best_prio) ||
dd41f596 2148 !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
dd41f596
IM
2149 p = iterator->next(iterator->arg);
2150 goto next;
1da177e4
LT
2151 }
2152
dd41f596 2153 pull_task(busiest, p, this_rq, this_cpu);
1da177e4 2154 pulled++;
dd41f596 2155 rem_load_move -= p->se.load.weight;
1da177e4 2156
2dd73a4f
PW
2157 /*
2158 * We only want to steal up to the prescribed number of tasks
2159 * and the prescribed amount of weighted load.
2160 */
2161 if (pulled < max_nr_move && rem_load_move > 0) {
a4ac01c3
PW
2162 if (p->prio < *this_best_prio)
2163 *this_best_prio = p->prio;
dd41f596
IM
2164 p = iterator->next(iterator->arg);
2165 goto next;
1da177e4
LT
2166 }
2167out:
2168 /*
2169 * Right now, this is the only place pull_task() is called,
2170 * so we can safely collect pull_task() stats here rather than
2171 * inside pull_task().
2172 */
2173 schedstat_add(sd, lb_gained[idle], pulled);
81026794
NP
2174
2175 if (all_pinned)
2176 *all_pinned = pinned;
dd41f596 2177 *load_moved = max_load_move - rem_load_move;
1da177e4
LT
2178 return pulled;
2179}
2180
dd41f596 2181/*
43010659
PW
2182 * move_tasks tries to move up to max_load_move weighted load from busiest to
2183 * this_rq, as part of a balancing operation within domain "sd".
2184 * Returns 1 if successful and 0 otherwise.
dd41f596
IM
2185 *
2186 * Called with both runqueues locked.
2187 */
2188static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
43010659 2189 unsigned long max_load_move,
dd41f596
IM
2190 struct sched_domain *sd, enum cpu_idle_type idle,
2191 int *all_pinned)
2192{
2193 struct sched_class *class = sched_class_highest;
43010659 2194 unsigned long total_load_moved = 0;
a4ac01c3 2195 int this_best_prio = this_rq->curr->prio;
dd41f596
IM
2196
2197 do {
43010659
PW
2198 total_load_moved +=
2199 class->load_balance(this_rq, this_cpu, busiest,
2200 ULONG_MAX, max_load_move - total_load_moved,
a4ac01c3 2201 sd, idle, all_pinned, &this_best_prio);
dd41f596 2202 class = class->next;
43010659 2203 } while (class && max_load_move > total_load_moved);
dd41f596 2204
43010659
PW
2205 return total_load_moved > 0;
2206}
2207
2208/*
2209 * move_one_task tries to move exactly one task from busiest to this_rq, as
2210 * part of active balancing operations within "domain".
2211 * Returns 1 if successful and 0 otherwise.
2212 *
2213 * Called with both runqueues locked.
2214 */
2215static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
2216 struct sched_domain *sd, enum cpu_idle_type idle)
2217{
2218 struct sched_class *class;
a4ac01c3 2219 int this_best_prio = MAX_PRIO;
43010659
PW
2220
2221 for (class = sched_class_highest; class; class = class->next)
2222 if (class->load_balance(this_rq, this_cpu, busiest,
a4ac01c3
PW
2223 1, ULONG_MAX, sd, idle, NULL,
2224 &this_best_prio))
43010659
PW
2225 return 1;
2226
2227 return 0;
dd41f596
IM
2228}
2229
1da177e4
LT
2230/*
2231 * find_busiest_group finds and returns the busiest CPU group within the
48f24c4d
IM
2232 * domain. It calculates and returns the amount of weighted load which
2233 * should be moved to restore balance via the imbalance parameter.
1da177e4
LT
2234 */
2235static struct sched_group *
2236find_busiest_group(struct sched_domain *sd, int this_cpu,
dd41f596
IM
2237 unsigned long *imbalance, enum cpu_idle_type idle,
2238 int *sd_idle, cpumask_t *cpus, int *balance)
1da177e4
LT
2239{
2240 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2241 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
0c117f1b 2242 unsigned long max_pull;
2dd73a4f
PW
2243 unsigned long busiest_load_per_task, busiest_nr_running;
2244 unsigned long this_load_per_task, this_nr_running;
7897986b 2245 int load_idx;
5c45bf27
SS
2246#if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2247 int power_savings_balance = 1;
2248 unsigned long leader_nr_running = 0, min_load_per_task = 0;
2249 unsigned long min_nr_running = ULONG_MAX;
2250 struct sched_group *group_min = NULL, *group_leader = NULL;
2251#endif
1da177e4
LT
2252
2253 max_load = this_load = total_load = total_pwr = 0;
2dd73a4f
PW
2254 busiest_load_per_task = busiest_nr_running = 0;
2255 this_load_per_task = this_nr_running = 0;
d15bcfdb 2256 if (idle == CPU_NOT_IDLE)
7897986b 2257 load_idx = sd->busy_idx;
d15bcfdb 2258 else if (idle == CPU_NEWLY_IDLE)
7897986b
NP
2259 load_idx = sd->newidle_idx;
2260 else
2261 load_idx = sd->idle_idx;
1da177e4
LT
2262
2263 do {
5c45bf27 2264 unsigned long load, group_capacity;
1da177e4
LT
2265 int local_group;
2266 int i;
783609c6 2267 unsigned int balance_cpu = -1, first_idle_cpu = 0;
2dd73a4f 2268 unsigned long sum_nr_running, sum_weighted_load;
1da177e4
LT
2269
2270 local_group = cpu_isset(this_cpu, group->cpumask);
2271
783609c6
SS
2272 if (local_group)
2273 balance_cpu = first_cpu(group->cpumask);
2274
1da177e4 2275 /* Tally up the load of all CPUs in the group */
2dd73a4f 2276 sum_weighted_load = sum_nr_running = avg_load = 0;
1da177e4
LT
2277
2278 for_each_cpu_mask(i, group->cpumask) {
0a2966b4
CL
2279 struct rq *rq;
2280
2281 if (!cpu_isset(i, *cpus))
2282 continue;
2283
2284 rq = cpu_rq(i);
2dd73a4f 2285
9439aab8 2286 if (*sd_idle && rq->nr_running)
5969fe06
NP
2287 *sd_idle = 0;
2288
1da177e4 2289 /* Bias balancing toward cpus of our domain */
783609c6
SS
2290 if (local_group) {
2291 if (idle_cpu(i) && !first_idle_cpu) {
2292 first_idle_cpu = 1;
2293 balance_cpu = i;
2294 }
2295
a2000572 2296 load = target_load(i, load_idx);
783609c6 2297 } else
a2000572 2298 load = source_load(i, load_idx);
1da177e4
LT
2299
2300 avg_load += load;
2dd73a4f 2301 sum_nr_running += rq->nr_running;
dd41f596 2302 sum_weighted_load += weighted_cpuload(i);
1da177e4
LT
2303 }
2304
783609c6
SS
2305 /*
2306 * First idle cpu or the first cpu(busiest) in this sched group
2307 * is eligible for doing load balancing at this and above
9439aab8
SS
2308 * domains. In the newly idle case, we will allow all the cpu's
2309 * to do the newly idle load balance.
783609c6 2310 */
9439aab8
SS
2311 if (idle != CPU_NEWLY_IDLE && local_group &&
2312 balance_cpu != this_cpu && balance) {
783609c6
SS
2313 *balance = 0;
2314 goto ret;
2315 }
2316
1da177e4 2317 total_load += avg_load;
5517d86b 2318 total_pwr += group->__cpu_power;
1da177e4
LT
2319
2320 /* Adjust by relative CPU power of the group */
5517d86b
ED
2321 avg_load = sg_div_cpu_power(group,
2322 avg_load * SCHED_LOAD_SCALE);
1da177e4 2323
5517d86b 2324 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
5c45bf27 2325
1da177e4
LT
2326 if (local_group) {
2327 this_load = avg_load;
2328 this = group;
2dd73a4f
PW
2329 this_nr_running = sum_nr_running;
2330 this_load_per_task = sum_weighted_load;
2331 } else if (avg_load > max_load &&
5c45bf27 2332 sum_nr_running > group_capacity) {
1da177e4
LT
2333 max_load = avg_load;
2334 busiest = group;
2dd73a4f
PW
2335 busiest_nr_running = sum_nr_running;
2336 busiest_load_per_task = sum_weighted_load;
1da177e4 2337 }
5c45bf27
SS
2338
2339#if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2340 /*
2341 * Busy processors will not participate in power savings
2342 * balance.
2343 */
dd41f596
IM
2344 if (idle == CPU_NOT_IDLE ||
2345 !(sd->flags & SD_POWERSAVINGS_BALANCE))
2346 goto group_next;
5c45bf27
SS
2347
2348 /*
2349 * If the local group is idle or completely loaded
2350 * no need to do power savings balance at this domain
2351 */
2352 if (local_group && (this_nr_running >= group_capacity ||
2353 !this_nr_running))
2354 power_savings_balance = 0;
2355
dd41f596 2356 /*
5c45bf27
SS
2357 * If a group is already running at full capacity or idle,
2358 * don't include that group in power savings calculations
dd41f596
IM
2359 */
2360 if (!power_savings_balance || sum_nr_running >= group_capacity
5c45bf27 2361 || !sum_nr_running)
dd41f596 2362 goto group_next;
5c45bf27 2363
dd41f596 2364 /*
5c45bf27 2365 * Calculate the group which has the least non-idle load.
dd41f596
IM
2366 * This is the group from where we need to pick up the load
2367 * for saving power
2368 */
2369 if ((sum_nr_running < min_nr_running) ||
2370 (sum_nr_running == min_nr_running &&
5c45bf27
SS
2371 first_cpu(group->cpumask) <
2372 first_cpu(group_min->cpumask))) {
dd41f596
IM
2373 group_min = group;
2374 min_nr_running = sum_nr_running;
5c45bf27
SS
2375 min_load_per_task = sum_weighted_load /
2376 sum_nr_running;
dd41f596 2377 }
5c45bf27 2378
dd41f596 2379 /*
5c45bf27 2380 * Calculate the group which is almost near its
dd41f596
IM
2381 * capacity but still has some space to pick up some load
2382 * from other group and save more power
2383 */
2384 if (sum_nr_running <= group_capacity - 1) {
2385 if (sum_nr_running > leader_nr_running ||
2386 (sum_nr_running == leader_nr_running &&
2387 first_cpu(group->cpumask) >
2388 first_cpu(group_leader->cpumask))) {
2389 group_leader = group;
2390 leader_nr_running = sum_nr_running;
2391 }
48f24c4d 2392 }
5c45bf27
SS
2393group_next:
2394#endif
1da177e4
LT
2395 group = group->next;
2396 } while (group != sd->groups);
2397
2dd73a4f 2398 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
1da177e4
LT
2399 goto out_balanced;
2400
2401 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2402
2403 if (this_load >= avg_load ||
2404 100*max_load <= sd->imbalance_pct*this_load)
2405 goto out_balanced;
2406
2dd73a4f 2407 busiest_load_per_task /= busiest_nr_running;
1da177e4
LT
2408 /*
2409 * We're trying to get all the cpus to the average_load, so we don't
2410 * want to push ourselves above the average load, nor do we wish to
2411 * reduce the max loaded cpu below the average load, as either of these
2412 * actions would just result in more rebalancing later, and ping-pong
2413 * tasks around. Thus we look for the minimum possible imbalance.
2414 * Negative imbalances (*we* are more loaded than anyone else) will
2415 * be counted as no imbalance for these purposes -- we can't fix that
2416 * by pulling tasks to us. Be careful of negative numbers as they'll
2417 * appear as very large values with unsigned longs.
2418 */
2dd73a4f
PW
2419 if (max_load <= busiest_load_per_task)
2420 goto out_balanced;
2421
2422 /*
2423 * In the presence of smp nice balancing, certain scenarios can have
2424 * max load less than avg load(as we skip the groups at or below
2425 * its cpu_power, while calculating max_load..)
2426 */
2427 if (max_load < avg_load) {
2428 *imbalance = 0;
2429 goto small_imbalance;
2430 }
0c117f1b
SS
2431
2432 /* Don't want to pull so many tasks that a group would go idle */
2dd73a4f 2433 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
0c117f1b 2434
1da177e4 2435 /* How much load to actually move to equalise the imbalance */
5517d86b
ED
2436 *imbalance = min(max_pull * busiest->__cpu_power,
2437 (avg_load - this_load) * this->__cpu_power)
1da177e4
LT
2438 / SCHED_LOAD_SCALE;
2439
2dd73a4f
PW
2440 /*
2441 * if *imbalance is less than the average load per runnable task
2442 * there is no gaurantee that any tasks will be moved so we'll have
2443 * a think about bumping its value to force at least one task to be
2444 * moved
2445 */
7fd0d2dd 2446 if (*imbalance < busiest_load_per_task) {
48f24c4d 2447 unsigned long tmp, pwr_now, pwr_move;
2dd73a4f
PW
2448 unsigned int imbn;
2449
2450small_imbalance:
2451 pwr_move = pwr_now = 0;
2452 imbn = 2;
2453 if (this_nr_running) {
2454 this_load_per_task /= this_nr_running;
2455 if (busiest_load_per_task > this_load_per_task)
2456 imbn = 1;
2457 } else
2458 this_load_per_task = SCHED_LOAD_SCALE;
1da177e4 2459
dd41f596
IM
2460 if (max_load - this_load + SCHED_LOAD_SCALE_FUZZ >=
2461 busiest_load_per_task * imbn) {
2dd73a4f 2462 *imbalance = busiest_load_per_task;
1da177e4
LT
2463 return busiest;
2464 }
2465
2466 /*
2467 * OK, we don't have enough imbalance to justify moving tasks,
2468 * however we may be able to increase total CPU power used by
2469 * moving them.
2470 */
2471
5517d86b
ED
2472 pwr_now += busiest->__cpu_power *
2473 min(busiest_load_per_task, max_load);
2474 pwr_now += this->__cpu_power *
2475 min(this_load_per_task, this_load);
1da177e4
LT
2476 pwr_now /= SCHED_LOAD_SCALE;
2477
2478 /* Amount of load we'd subtract */
5517d86b
ED
2479 tmp = sg_div_cpu_power(busiest,
2480 busiest_load_per_task * SCHED_LOAD_SCALE);
1da177e4 2481 if (max_load > tmp)
5517d86b 2482 pwr_move += busiest->__cpu_power *
2dd73a4f 2483 min(busiest_load_per_task, max_load - tmp);
1da177e4
LT
2484
2485 /* Amount of load we'd add */
5517d86b 2486 if (max_load * busiest->__cpu_power <
33859f7f 2487 busiest_load_per_task * SCHED_LOAD_SCALE)
5517d86b
ED
2488 tmp = sg_div_cpu_power(this,
2489 max_load * busiest->__cpu_power);
1da177e4 2490 else
5517d86b
ED
2491 tmp = sg_div_cpu_power(this,
2492 busiest_load_per_task * SCHED_LOAD_SCALE);
2493 pwr_move += this->__cpu_power *
2494 min(this_load_per_task, this_load + tmp);
1da177e4
LT
2495 pwr_move /= SCHED_LOAD_SCALE;
2496
2497 /* Move if we gain throughput */
7fd0d2dd
SS
2498 if (pwr_move > pwr_now)
2499 *imbalance = busiest_load_per_task;
1da177e4
LT
2500 }
2501
1da177e4
LT
2502 return busiest;
2503
2504out_balanced:
5c45bf27 2505#if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
d15bcfdb 2506 if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
5c45bf27 2507 goto ret;
1da177e4 2508
5c45bf27
SS
2509 if (this == group_leader && group_leader != group_min) {
2510 *imbalance = min_load_per_task;
2511 return group_min;
2512 }
5c45bf27 2513#endif
783609c6 2514ret:
1da177e4
LT
2515 *imbalance = 0;
2516 return NULL;
2517}
2518
2519/*
2520 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2521 */
70b97a7f 2522static struct rq *
d15bcfdb 2523find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
0a2966b4 2524 unsigned long imbalance, cpumask_t *cpus)
1da177e4 2525{
70b97a7f 2526 struct rq *busiest = NULL, *rq;
2dd73a4f 2527 unsigned long max_load = 0;
1da177e4
LT
2528 int i;
2529
2530 for_each_cpu_mask(i, group->cpumask) {
dd41f596 2531 unsigned long wl;
0a2966b4
CL
2532
2533 if (!cpu_isset(i, *cpus))
2534 continue;
2535
48f24c4d 2536 rq = cpu_rq(i);
dd41f596 2537 wl = weighted_cpuload(i);
2dd73a4f 2538
dd41f596 2539 if (rq->nr_running == 1 && wl > imbalance)
2dd73a4f 2540 continue;
1da177e4 2541
dd41f596
IM
2542 if (wl > max_load) {
2543 max_load = wl;
48f24c4d 2544 busiest = rq;
1da177e4
LT
2545 }
2546 }
2547
2548 return busiest;
2549}
2550
77391d71
NP
2551/*
2552 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2553 * so long as it is large enough.
2554 */
2555#define MAX_PINNED_INTERVAL 512
2556
1da177e4
LT
2557/*
2558 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2559 * tasks if there is an imbalance.
1da177e4 2560 */
70b97a7f 2561static int load_balance(int this_cpu, struct rq *this_rq,
d15bcfdb 2562 struct sched_domain *sd, enum cpu_idle_type idle,
783609c6 2563 int *balance)
1da177e4 2564{
43010659 2565 int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
1da177e4 2566 struct sched_group *group;
1da177e4 2567 unsigned long imbalance;
70b97a7f 2568 struct rq *busiest;
0a2966b4 2569 cpumask_t cpus = CPU_MASK_ALL;
fe2eea3f 2570 unsigned long flags;
5969fe06 2571
89c4710e
SS
2572 /*
2573 * When power savings policy is enabled for the parent domain, idle
2574 * sibling can pick up load irrespective of busy siblings. In this case,
dd41f596 2575 * let the state of idle sibling percolate up as CPU_IDLE, instead of
d15bcfdb 2576 * portraying it as CPU_NOT_IDLE.
89c4710e 2577 */
d15bcfdb 2578 if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
89c4710e 2579 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
5969fe06 2580 sd_idle = 1;
1da177e4 2581
1da177e4
LT
2582 schedstat_inc(sd, lb_cnt[idle]);
2583
0a2966b4
CL
2584redo:
2585 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
783609c6
SS
2586 &cpus, balance);
2587
06066714 2588 if (*balance == 0)
783609c6 2589 goto out_balanced;
783609c6 2590
1da177e4
LT
2591 if (!group) {
2592 schedstat_inc(sd, lb_nobusyg[idle]);
2593 goto out_balanced;
2594 }
2595
0a2966b4 2596 busiest = find_busiest_queue(group, idle, imbalance, &cpus);
1da177e4
LT
2597 if (!busiest) {
2598 schedstat_inc(sd, lb_nobusyq[idle]);
2599 goto out_balanced;
2600 }
2601
db935dbd 2602 BUG_ON(busiest == this_rq);
1da177e4
LT
2603
2604 schedstat_add(sd, lb_imbalance[idle], imbalance);
2605
43010659 2606 ld_moved = 0;
1da177e4
LT
2607 if (busiest->nr_running > 1) {
2608 /*
2609 * Attempt to move tasks. If find_busiest_group has found
2610 * an imbalance but busiest->nr_running <= 1, the group is
43010659 2611 * still unbalanced. ld_moved simply stays zero, so it is
1da177e4
LT
2612 * correctly treated as an imbalance.
2613 */
fe2eea3f 2614 local_irq_save(flags);
e17224bf 2615 double_rq_lock(this_rq, busiest);
43010659 2616 ld_moved = move_tasks(this_rq, this_cpu, busiest,
48f24c4d 2617 imbalance, sd, idle, &all_pinned);
e17224bf 2618 double_rq_unlock(this_rq, busiest);
fe2eea3f 2619 local_irq_restore(flags);
81026794 2620
46cb4b7c
SS
2621 /*
2622 * some other cpu did the load balance for us.
2623 */
43010659 2624 if (ld_moved && this_cpu != smp_processor_id())
46cb4b7c
SS
2625 resched_cpu(this_cpu);
2626
81026794 2627 /* All tasks on this runqueue were pinned by CPU affinity */
0a2966b4
CL
2628 if (unlikely(all_pinned)) {
2629 cpu_clear(cpu_of(busiest), cpus);
2630 if (!cpus_empty(cpus))
2631 goto redo;
81026794 2632 goto out_balanced;
0a2966b4 2633 }
1da177e4 2634 }
81026794 2635
43010659 2636 if (!ld_moved) {
1da177e4
LT
2637 schedstat_inc(sd, lb_failed[idle]);
2638 sd->nr_balance_failed++;
2639
2640 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
1da177e4 2641
fe2eea3f 2642 spin_lock_irqsave(&busiest->lock, flags);
fa3b6ddc
SS
2643
2644 /* don't kick the migration_thread, if the curr
2645 * task on busiest cpu can't be moved to this_cpu
2646 */
2647 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
fe2eea3f 2648 spin_unlock_irqrestore(&busiest->lock, flags);
fa3b6ddc
SS
2649 all_pinned = 1;
2650 goto out_one_pinned;
2651 }
2652
1da177e4
LT
2653 if (!busiest->active_balance) {
2654 busiest->active_balance = 1;
2655 busiest->push_cpu = this_cpu;
81026794 2656 active_balance = 1;
1da177e4 2657 }
fe2eea3f 2658 spin_unlock_irqrestore(&busiest->lock, flags);
81026794 2659 if (active_balance)
1da177e4
LT
2660 wake_up_process(busiest->migration_thread);
2661
2662 /*
2663 * We've kicked active balancing, reset the failure
2664 * counter.
2665 */
39507451 2666 sd->nr_balance_failed = sd->cache_nice_tries+1;
1da177e4 2667 }
81026794 2668 } else
1da177e4
LT
2669 sd->nr_balance_failed = 0;
2670
81026794 2671 if (likely(!active_balance)) {
1da177e4
LT
2672 /* We were unbalanced, so reset the balancing interval */
2673 sd->balance_interval = sd->min_interval;
81026794
NP
2674 } else {
2675 /*
2676 * If we've begun active balancing, start to back off. This
2677 * case may not be covered by the all_pinned logic if there
2678 * is only 1 task on the busy runqueue (because we don't call
2679 * move_tasks).
2680 */
2681 if (sd->balance_interval < sd->max_interval)
2682 sd->balance_interval *= 2;
1da177e4
LT
2683 }
2684
43010659 2685 if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
89c4710e 2686 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
5969fe06 2687 return -1;
43010659 2688 return ld_moved;
1da177e4
LT
2689
2690out_balanced:
1da177e4
LT
2691 schedstat_inc(sd, lb_balanced[idle]);
2692
16cfb1c0 2693 sd->nr_balance_failed = 0;
fa3b6ddc
SS
2694
2695out_one_pinned:
1da177e4 2696 /* tune up the balancing interval */
77391d71
NP
2697 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
2698 (sd->balance_interval < sd->max_interval))
1da177e4
LT
2699 sd->balance_interval *= 2;
2700
48f24c4d 2701 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
89c4710e 2702 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
5969fe06 2703 return -1;
1da177e4
LT
2704 return 0;
2705}
2706
2707/*
2708 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2709 * tasks if there is an imbalance.
2710 *
d15bcfdb 2711 * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
1da177e4
LT
2712 * this_rq is locked.
2713 */
48f24c4d 2714static int
70b97a7f 2715load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
1da177e4
LT
2716{
2717 struct sched_group *group;
70b97a7f 2718 struct rq *busiest = NULL;
1da177e4 2719 unsigned long imbalance;
43010659 2720 int ld_moved = 0;
5969fe06 2721 int sd_idle = 0;
969bb4e4 2722 int all_pinned = 0;
0a2966b4 2723 cpumask_t cpus = CPU_MASK_ALL;
5969fe06 2724
89c4710e
SS
2725 /*
2726 * When power savings policy is enabled for the parent domain, idle
2727 * sibling can pick up load irrespective of busy siblings. In this case,
2728 * let the state of idle sibling percolate up as IDLE, instead of
d15bcfdb 2729 * portraying it as CPU_NOT_IDLE.
89c4710e
SS
2730 */
2731 if (sd->flags & SD_SHARE_CPUPOWER &&
2732 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
5969fe06 2733 sd_idle = 1;
1da177e4 2734
d15bcfdb 2735 schedstat_inc(sd, lb_cnt[CPU_NEWLY_IDLE]);
0a2966b4 2736redo:
d15bcfdb 2737 group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
783609c6 2738 &sd_idle, &cpus, NULL);
1da177e4 2739 if (!group) {
d15bcfdb 2740 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
16cfb1c0 2741 goto out_balanced;
1da177e4
LT
2742 }
2743
d15bcfdb 2744 busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance,
0a2966b4 2745 &cpus);
db935dbd 2746 if (!busiest) {
d15bcfdb 2747 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
16cfb1c0 2748 goto out_balanced;
1da177e4
LT
2749 }
2750
db935dbd
NP
2751 BUG_ON(busiest == this_rq);
2752
d15bcfdb 2753 schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
d6d5cfaf 2754
43010659 2755 ld_moved = 0;
d6d5cfaf
NP
2756 if (busiest->nr_running > 1) {
2757 /* Attempt to move tasks */
2758 double_lock_balance(this_rq, busiest);
6e82a3be
IM
2759 /* this_rq->clock is already updated */
2760 update_rq_clock(busiest);
43010659 2761 ld_moved = move_tasks(this_rq, this_cpu, busiest,
969bb4e4
SS
2762 imbalance, sd, CPU_NEWLY_IDLE,
2763 &all_pinned);
d6d5cfaf 2764 spin_unlock(&busiest->lock);
0a2966b4 2765
969bb4e4 2766 if (unlikely(all_pinned)) {
0a2966b4
CL
2767 cpu_clear(cpu_of(busiest), cpus);
2768 if (!cpus_empty(cpus))
2769 goto redo;
2770 }
d6d5cfaf
NP
2771 }
2772
43010659 2773 if (!ld_moved) {
d15bcfdb 2774 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
89c4710e
SS
2775 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2776 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
5969fe06
NP
2777 return -1;
2778 } else
16cfb1c0 2779 sd->nr_balance_failed = 0;
1da177e4 2780
43010659 2781 return ld_moved;
16cfb1c0
NP
2782
2783out_balanced:
d15bcfdb 2784 schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
48f24c4d 2785 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
89c4710e 2786 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
5969fe06 2787 return -1;
16cfb1c0 2788 sd->nr_balance_failed = 0;
48f24c4d 2789
16cfb1c0 2790 return 0;
1da177e4
LT
2791}
2792
2793/*
2794 * idle_balance is called by schedule() if this_cpu is about to become
2795 * idle. Attempts to pull tasks from other CPUs.
2796 */
70b97a7f 2797static void idle_balance(int this_cpu, struct rq *this_rq)
1da177e4
LT
2798{
2799 struct sched_domain *sd;
dd41f596
IM
2800 int pulled_task = -1;
2801 unsigned long next_balance = jiffies + HZ;
1da177e4
LT
2802
2803 for_each_domain(this_cpu, sd) {
92c4ca5c
CL
2804 unsigned long interval;
2805
2806 if (!(sd->flags & SD_LOAD_BALANCE))
2807 continue;
2808
2809 if (sd->flags & SD_BALANCE_NEWIDLE)
48f24c4d 2810 /* If we've pulled tasks over stop searching: */
1bd77f2d 2811 pulled_task = load_balance_newidle(this_cpu,
92c4ca5c
CL
2812 this_rq, sd);
2813
2814 interval = msecs_to_jiffies(sd->balance_interval);
2815 if (time_after(next_balance, sd->last_balance + interval))
2816 next_balance = sd->last_balance + interval;
2817 if (pulled_task)
2818 break;
1da177e4 2819 }
dd41f596 2820 if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
1bd77f2d
CL
2821 /*
2822 * We are going idle. next_balance may be set based on
2823 * a busy processor. So reset next_balance.
2824 */
2825 this_rq->next_balance = next_balance;
dd41f596 2826 }
1da177e4
LT
2827}
2828
2829/*
2830 * active_load_balance is run by migration threads. It pushes running tasks
2831 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2832 * running on each physical CPU where possible, and avoids physical /
2833 * logical imbalances.
2834 *
2835 * Called with busiest_rq locked.
2836 */
70b97a7f 2837static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
1da177e4 2838{
39507451 2839 int target_cpu = busiest_rq->push_cpu;
70b97a7f
IM
2840 struct sched_domain *sd;
2841 struct rq *target_rq;
39507451 2842
48f24c4d 2843 /* Is there any task to move? */
39507451 2844 if (busiest_rq->nr_running <= 1)
39507451
NP
2845 return;
2846
2847 target_rq = cpu_rq(target_cpu);
1da177e4
LT
2848
2849 /*
39507451
NP
2850 * This condition is "impossible", if it occurs
2851 * we need to fix it. Originally reported by
2852 * Bjorn Helgaas on a 128-cpu setup.
1da177e4 2853 */
39507451 2854 BUG_ON(busiest_rq == target_rq);
1da177e4 2855
39507451
NP
2856 /* move a task from busiest_rq to target_rq */
2857 double_lock_balance(busiest_rq, target_rq);
6e82a3be
IM
2858 update_rq_clock(busiest_rq);
2859 update_rq_clock(target_rq);
39507451
NP
2860
2861 /* Search for an sd spanning us and the target CPU. */
c96d145e 2862 for_each_domain(target_cpu, sd) {
39507451 2863 if ((sd->flags & SD_LOAD_BALANCE) &&
48f24c4d 2864 cpu_isset(busiest_cpu, sd->span))
39507451 2865 break;
c96d145e 2866 }
39507451 2867
48f24c4d
IM
2868 if (likely(sd)) {
2869 schedstat_inc(sd, alb_cnt);
39507451 2870
43010659
PW
2871 if (move_one_task(target_rq, target_cpu, busiest_rq,
2872 sd, CPU_IDLE))
48f24c4d
IM
2873 schedstat_inc(sd, alb_pushed);
2874 else
2875 schedstat_inc(sd, alb_failed);
2876 }
39507451 2877 spin_unlock(&target_rq->lock);
1da177e4
LT
2878}
2879
46cb4b7c
SS
2880#ifdef CONFIG_NO_HZ
2881static struct {
2882 atomic_t load_balancer;
2883 cpumask_t cpu_mask;
2884} nohz ____cacheline_aligned = {
2885 .load_balancer = ATOMIC_INIT(-1),
2886 .cpu_mask = CPU_MASK_NONE,
2887};
2888
7835b98b 2889/*
46cb4b7c
SS
2890 * This routine will try to nominate the ilb (idle load balancing)
2891 * owner among the cpus whose ticks are stopped. ilb owner will do the idle
2892 * load balancing on behalf of all those cpus. If all the cpus in the system
2893 * go into this tickless mode, then there will be no ilb owner (as there is
2894 * no need for one) and all the cpus will sleep till the next wakeup event
2895 * arrives...
2896 *
2897 * For the ilb owner, tick is not stopped. And this tick will be used
2898 * for idle load balancing. ilb owner will still be part of
2899 * nohz.cpu_mask..
7835b98b 2900 *
46cb4b7c
SS
2901 * While stopping the tick, this cpu will become the ilb owner if there
2902 * is no other owner. And will be the owner till that cpu becomes busy
2903 * or if all cpus in the system stop their ticks at which point
2904 * there is no need for ilb owner.
2905 *
2906 * When the ilb owner becomes busy, it nominates another owner, during the
2907 * next busy scheduler_tick()
2908 */
2909int select_nohz_load_balancer(int stop_tick)
2910{
2911 int cpu = smp_processor_id();
2912
2913 if (stop_tick) {
2914 cpu_set(cpu, nohz.cpu_mask);
2915 cpu_rq(cpu)->in_nohz_recently = 1;
2916
2917 /*
2918 * If we are going offline and still the leader, give up!
2919 */
2920 if (cpu_is_offline(cpu) &&
2921 atomic_read(&nohz.load_balancer) == cpu) {
2922 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
2923 BUG();
2924 return 0;
2925 }
2926
2927 /* time for ilb owner also to sleep */
2928 if (cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
2929 if (atomic_read(&nohz.load_balancer) == cpu)
2930 atomic_set(&nohz.load_balancer, -1);
2931 return 0;
2932 }
2933
2934 if (atomic_read(&nohz.load_balancer) == -1) {
2935 /* make me the ilb owner */
2936 if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
2937 return 1;
2938 } else if (atomic_read(&nohz.load_balancer) == cpu)
2939 return 1;
2940 } else {
2941 if (!cpu_isset(cpu, nohz.cpu_mask))
2942 return 0;
2943
2944 cpu_clear(cpu, nohz.cpu_mask);
2945
2946 if (atomic_read(&nohz.load_balancer) == cpu)
2947 if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
2948 BUG();
2949 }
2950 return 0;
2951}
2952#endif
2953
2954static DEFINE_SPINLOCK(balancing);
2955
2956/*
7835b98b
CL
2957 * It checks each scheduling domain to see if it is due to be balanced,
2958 * and initiates a balancing operation if so.
2959 *
2960 * Balancing parameters are set up in arch_init_sched_domains.
2961 */
d15bcfdb 2962static inline void rebalance_domains(int cpu, enum cpu_idle_type idle)
7835b98b 2963{
46cb4b7c
SS
2964 int balance = 1;
2965 struct rq *rq = cpu_rq(cpu);
7835b98b
CL
2966 unsigned long interval;
2967 struct sched_domain *sd;
46cb4b7c 2968 /* Earliest time when we have to do rebalance again */
c9819f45 2969 unsigned long next_balance = jiffies + 60*HZ;
f549da84 2970 int update_next_balance = 0;
1da177e4 2971
46cb4b7c 2972 for_each_domain(cpu, sd) {
1da177e4
LT
2973 if (!(sd->flags & SD_LOAD_BALANCE))
2974 continue;
2975
2976 interval = sd->balance_interval;
d15bcfdb 2977 if (idle != CPU_IDLE)
1da177e4
LT
2978 interval *= sd->busy_factor;
2979
2980 /* scale ms to jiffies */
2981 interval = msecs_to_jiffies(interval);
2982 if (unlikely(!interval))
2983 interval = 1;
dd41f596
IM
2984 if (interval > HZ*NR_CPUS/10)
2985 interval = HZ*NR_CPUS/10;
2986
1da177e4 2987
08c183f3
CL
2988 if (sd->flags & SD_SERIALIZE) {
2989 if (!spin_trylock(&balancing))
2990 goto out;
2991 }
2992
c9819f45 2993 if (time_after_eq(jiffies, sd->last_balance + interval)) {
46cb4b7c 2994 if (load_balance(cpu, rq, sd, idle, &balance)) {
fa3b6ddc
SS
2995 /*
2996 * We've pulled tasks over so either we're no
5969fe06
NP
2997 * longer idle, or one of our SMT siblings is
2998 * not idle.
2999 */
d15bcfdb 3000 idle = CPU_NOT_IDLE;
1da177e4 3001 }
1bd77f2d 3002 sd->last_balance = jiffies;
1da177e4 3003 }
08c183f3
CL
3004 if (sd->flags & SD_SERIALIZE)
3005 spin_unlock(&balancing);
3006out:
f549da84 3007 if (time_after(next_balance, sd->last_balance + interval)) {
c9819f45 3008 next_balance = sd->last_balance + interval;
f549da84
SS
3009 update_next_balance = 1;
3010 }
783609c6
SS
3011
3012 /*
3013 * Stop the load balance at this level. There is another
3014 * CPU in our sched group which is doing load balancing more
3015 * actively.
3016 */
3017 if (!balance)
3018 break;
1da177e4 3019 }
f549da84
SS
3020
3021 /*
3022 * next_balance will be updated only when there is a need.
3023 * When the cpu is attached to null domain for ex, it will not be
3024 * updated.
3025 */
3026 if (likely(update_next_balance))
3027 rq->next_balance = next_balance;
46cb4b7c
SS
3028}
3029
3030/*
3031 * run_rebalance_domains is triggered when needed from the scheduler tick.
3032 * In CONFIG_NO_HZ case, the idle load balance owner will do the
3033 * rebalancing for all the cpus for whom scheduler ticks are stopped.
3034 */
3035static void run_rebalance_domains(struct softirq_action *h)
3036{
dd41f596
IM
3037 int this_cpu = smp_processor_id();
3038 struct rq *this_rq = cpu_rq(this_cpu);
3039 enum cpu_idle_type idle = this_rq->idle_at_tick ?
3040 CPU_IDLE : CPU_NOT_IDLE;
46cb4b7c 3041
dd41f596 3042 rebalance_domains(this_cpu, idle);
46cb4b7c
SS
3043
3044#ifdef CONFIG_NO_HZ
3045 /*
3046 * If this cpu is the owner for idle load balancing, then do the
3047 * balancing on behalf of the other idle cpus whose ticks are
3048 * stopped.
3049 */
dd41f596
IM
3050 if (this_rq->idle_at_tick &&
3051 atomic_read(&nohz.load_balancer) == this_cpu) {
46cb4b7c
SS
3052 cpumask_t cpus = nohz.cpu_mask;
3053 struct rq *rq;
3054 int balance_cpu;
3055
dd41f596 3056 cpu_clear(this_cpu, cpus);
46cb4b7c
SS
3057 for_each_cpu_mask(balance_cpu, cpus) {
3058 /*
3059 * If this cpu gets work to do, stop the load balancing
3060 * work being done for other cpus. Next load
3061 * balancing owner will pick it up.
3062 */
3063 if (need_resched())
3064 break;
3065
de0cf899 3066 rebalance_domains(balance_cpu, CPU_IDLE);
46cb4b7c
SS
3067
3068 rq = cpu_rq(balance_cpu);
dd41f596
IM
3069 if (time_after(this_rq->next_balance, rq->next_balance))
3070 this_rq->next_balance = rq->next_balance;
46cb4b7c
SS
3071 }
3072 }
3073#endif
3074}
3075
3076/*
3077 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
3078 *
3079 * In case of CONFIG_NO_HZ, this is the place where we nominate a new
3080 * idle load balancing owner or decide to stop the periodic load balancing,
3081 * if the whole system is idle.
3082 */
dd41f596 3083static inline void trigger_load_balance(struct rq *rq, int cpu)
46cb4b7c 3084{
46cb4b7c
SS
3085#ifdef CONFIG_NO_HZ
3086 /*
3087 * If we were in the nohz mode recently and busy at the current
3088 * scheduler tick, then check if we need to nominate new idle
3089 * load balancer.
3090 */
3091 if (rq->in_nohz_recently && !rq->idle_at_tick) {
3092 rq->in_nohz_recently = 0;
3093
3094 if (atomic_read(&nohz.load_balancer) == cpu) {
3095 cpu_clear(cpu, nohz.cpu_mask);
3096 atomic_set(&nohz.load_balancer, -1);
3097 }
3098
3099 if (atomic_read(&nohz.load_balancer) == -1) {
3100 /*
3101 * simple selection for now: Nominate the
3102 * first cpu in the nohz list to be the next
3103 * ilb owner.
3104 *
3105 * TBD: Traverse the sched domains and nominate
3106 * the nearest cpu in the nohz.cpu_mask.
3107 */
3108 int ilb = first_cpu(nohz.cpu_mask);
3109
3110 if (ilb != NR_CPUS)
3111 resched_cpu(ilb);
3112 }
3113 }
3114
3115 /*
3116 * If this cpu is idle and doing idle load balancing for all the
3117 * cpus with ticks stopped, is it time for that to stop?
3118 */
3119 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
3120 cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3121 resched_cpu(cpu);
3122 return;
3123 }
3124
3125 /*
3126 * If this cpu is idle and the idle load balancing is done by
3127 * someone else, then no need raise the SCHED_SOFTIRQ
3128 */
3129 if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
3130 cpu_isset(cpu, nohz.cpu_mask))
3131 return;
3132#endif
3133 if (time_after_eq(jiffies, rq->next_balance))
3134 raise_softirq(SCHED_SOFTIRQ);
1da177e4 3135}
dd41f596
IM
3136
3137#else /* CONFIG_SMP */
3138
1da177e4
LT
3139/*
3140 * on UP we do not need to balance between CPUs:
3141 */
70b97a7f 3142static inline void idle_balance(int cpu, struct rq *rq)
1da177e4
LT
3143{
3144}
dd41f596
IM
3145
3146/* Avoid "used but not defined" warning on UP */
3147static int balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
3148 unsigned long max_nr_move, unsigned long max_load_move,
3149 struct sched_domain *sd, enum cpu_idle_type idle,
3150 int *all_pinned, unsigned long *load_moved,
a4ac01c3 3151 int *this_best_prio, struct rq_iterator *iterator)
dd41f596
IM
3152{
3153 *load_moved = 0;
3154
3155 return 0;
3156}
3157
1da177e4
LT
3158#endif
3159
1da177e4
LT
3160DEFINE_PER_CPU(struct kernel_stat, kstat);
3161
3162EXPORT_PER_CPU_SYMBOL(kstat);
3163
3164/*
41b86e9c
IM
3165 * Return p->sum_exec_runtime plus any more ns on the sched_clock
3166 * that have not yet been banked in case the task is currently running.
1da177e4 3167 */
41b86e9c 3168unsigned long long task_sched_runtime(struct task_struct *p)
1da177e4 3169{
1da177e4 3170 unsigned long flags;
41b86e9c
IM
3171 u64 ns, delta_exec;
3172 struct rq *rq;
48f24c4d 3173
41b86e9c
IM
3174 rq = task_rq_lock(p, &flags);
3175 ns = p->se.sum_exec_runtime;
3176 if (rq->curr == p) {
a8e504d2
IM
3177 update_rq_clock(rq);
3178 delta_exec = rq->clock - p->se.exec_start;
41b86e9c
IM
3179 if ((s64)delta_exec > 0)
3180 ns += delta_exec;
3181 }
3182 task_rq_unlock(rq, &flags);
48f24c4d 3183
1da177e4
LT
3184 return ns;
3185}
3186
1da177e4
LT
3187/*
3188 * Account user cpu time to a process.
3189 * @p: the process that the cpu time gets accounted to
3190 * @hardirq_offset: the offset to subtract from hardirq_count()
3191 * @cputime: the cpu time spent in user space since the last update
3192 */
3193void account_user_time(struct task_struct *p, cputime_t cputime)
3194{
3195 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3196 cputime64_t tmp;
3197
3198 p->utime = cputime_add(p->utime, cputime);
3199
3200 /* Add user time to cpustat. */
3201 tmp = cputime_to_cputime64(cputime);
3202 if (TASK_NICE(p) > 0)
3203 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3204 else
3205 cpustat->user = cputime64_add(cpustat->user, tmp);
3206}
3207
3208/*
3209 * Account system cpu time to a process.
3210 * @p: the process that the cpu time gets accounted to
3211 * @hardirq_offset: the offset to subtract from hardirq_count()
3212 * @cputime: the cpu time spent in kernel space since the last update
3213 */
3214void account_system_time(struct task_struct *p, int hardirq_offset,
3215 cputime_t cputime)
3216{
3217 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
70b97a7f 3218 struct rq *rq = this_rq();
1da177e4
LT
3219 cputime64_t tmp;
3220
3221 p->stime = cputime_add(p->stime, cputime);
3222
3223 /* Add system time to cpustat. */
3224 tmp = cputime_to_cputime64(cputime);
3225 if (hardirq_count() - hardirq_offset)
3226 cpustat->irq = cputime64_add(cpustat->irq, tmp);
3227 else if (softirq_count())
3228 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
3229 else if (p != rq->idle)
3230 cpustat->system = cputime64_add(cpustat->system, tmp);
3231 else if (atomic_read(&rq->nr_iowait) > 0)
3232 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3233 else
3234 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3235 /* Account for system time used */
3236 acct_update_integrals(p);
1da177e4
LT
3237}
3238
3239/*
3240 * Account for involuntary wait time.
3241 * @p: the process from which the cpu time has been stolen
3242 * @steal: the cpu time spent in involuntary wait
3243 */
3244void account_steal_time(struct task_struct *p, cputime_t steal)
3245{
3246 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3247 cputime64_t tmp = cputime_to_cputime64(steal);
70b97a7f 3248 struct rq *rq = this_rq();
1da177e4
LT
3249
3250 if (p == rq->idle) {
3251 p->stime = cputime_add(p->stime, steal);
3252 if (atomic_read(&rq->nr_iowait) > 0)
3253 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3254 else
3255 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3256 } else
3257 cpustat->steal = cputime64_add(cpustat->steal, tmp);
3258}
3259
7835b98b
CL
3260/*
3261 * This function gets called by the timer code, with HZ frequency.
3262 * We call it with interrupts disabled.
3263 *
3264 * It also gets called by the fork code, when changing the parent's
3265 * timeslices.
3266 */
3267void scheduler_tick(void)
3268{
7835b98b
CL
3269 int cpu = smp_processor_id();
3270 struct rq *rq = cpu_rq(cpu);
dd41f596 3271 struct task_struct *curr = rq->curr;
529c7726 3272 u64 next_tick = rq->tick_timestamp + TICK_NSEC;
dd41f596
IM
3273
3274 spin_lock(&rq->lock);
546fe3c9 3275 __update_rq_clock(rq);
529c7726
IM
3276 /*
3277 * Let rq->clock advance by at least TICK_NSEC:
3278 */
3279 if (unlikely(rq->clock < next_tick))
3280 rq->clock = next_tick;
3281 rq->tick_timestamp = rq->clock;
f1a438d8 3282 update_cpu_load(rq);
dd41f596
IM
3283 if (curr != rq->idle) /* FIXME: needed? */
3284 curr->sched_class->task_tick(rq, curr);
dd41f596 3285 spin_unlock(&rq->lock);
7835b98b 3286
e418e1c2 3287#ifdef CONFIG_SMP
dd41f596
IM
3288 rq->idle_at_tick = idle_cpu(cpu);
3289 trigger_load_balance(rq, cpu);
e418e1c2 3290#endif
1da177e4
LT
3291}
3292
1da177e4
LT
3293#if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3294
3295void fastcall add_preempt_count(int val)
3296{
3297 /*
3298 * Underflow?
3299 */
9a11b49a
IM
3300 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3301 return;
1da177e4
LT
3302 preempt_count() += val;
3303 /*
3304 * Spinlock count overflowing soon?
3305 */
33859f7f
MOS
3306 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3307 PREEMPT_MASK - 10);
1da177e4
LT
3308}
3309EXPORT_SYMBOL(add_preempt_count);
3310
3311void fastcall sub_preempt_count(int val)
3312{
3313 /*
3314 * Underflow?
3315 */
9a11b49a
IM
3316 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3317 return;
1da177e4
LT
3318 /*
3319 * Is the spinlock portion underflowing?
3320 */
9a11b49a
IM
3321 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3322 !(preempt_count() & PREEMPT_MASK)))
3323 return;
3324
1da177e4
LT
3325 preempt_count() -= val;
3326}
3327EXPORT_SYMBOL(sub_preempt_count);
3328
3329#endif
3330
3331/*
dd41f596 3332 * Print scheduling while atomic bug:
1da177e4 3333 */
dd41f596 3334static noinline void __schedule_bug(struct task_struct *prev)
1da177e4 3335{
dd41f596
IM
3336 printk(KERN_ERR "BUG: scheduling while atomic: %s/0x%08x/%d\n",
3337 prev->comm, preempt_count(), prev->pid);
3338 debug_show_held_locks(prev);
3339 if (irqs_disabled())
3340 print_irqtrace_events(prev);
3341 dump_stack();
3342}
1da177e4 3343
dd41f596
IM
3344/*
3345 * Various schedule()-time debugging checks and statistics:
3346 */
3347static inline void schedule_debug(struct task_struct *prev)
3348{
1da177e4
LT
3349 /*
3350 * Test if we are atomic. Since do_exit() needs to call into
3351 * schedule() atomically, we ignore that path for now.
3352 * Otherwise, whine if we are scheduling when we should not be.
3353 */
dd41f596
IM
3354 if (unlikely(in_atomic_preempt_off()) && unlikely(!prev->exit_state))
3355 __schedule_bug(prev);
3356
1da177e4
LT
3357 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3358
dd41f596
IM
3359 schedstat_inc(this_rq(), sched_cnt);
3360}
3361
3362/*
3363 * Pick up the highest-prio task:
3364 */
3365static inline struct task_struct *
ff95f3df 3366pick_next_task(struct rq *rq, struct task_struct *prev)
dd41f596
IM
3367{
3368 struct sched_class *class;
3369 struct task_struct *p;
1da177e4
LT
3370
3371 /*
dd41f596
IM
3372 * Optimization: we know that if all tasks are in
3373 * the fair class we can call that function directly:
1da177e4 3374 */
dd41f596 3375 if (likely(rq->nr_running == rq->cfs.nr_running)) {
fb8d4724 3376 p = fair_sched_class.pick_next_task(rq);
dd41f596
IM
3377 if (likely(p))
3378 return p;
1da177e4
LT
3379 }
3380
dd41f596
IM
3381 class = sched_class_highest;
3382 for ( ; ; ) {
fb8d4724 3383 p = class->pick_next_task(rq);
dd41f596
IM
3384 if (p)
3385 return p;
3386 /*
3387 * Will never be NULL as the idle class always
3388 * returns a non-NULL p:
3389 */
3390 class = class->next;
3391 }
3392}
1da177e4 3393
dd41f596
IM
3394/*
3395 * schedule() is the main scheduler function.
3396 */
3397asmlinkage void __sched schedule(void)
3398{
3399 struct task_struct *prev, *next;
3400 long *switch_count;
3401 struct rq *rq;
dd41f596
IM
3402 int cpu;
3403
3404need_resched:
3405 preempt_disable();
3406 cpu = smp_processor_id();
3407 rq = cpu_rq(cpu);
3408 rcu_qsctr_inc(cpu);
3409 prev = rq->curr;
3410 switch_count = &prev->nivcsw;
3411
3412 release_kernel_lock(prev);
3413need_resched_nonpreemptible:
3414
3415 schedule_debug(prev);
1da177e4
LT
3416
3417 spin_lock_irq(&rq->lock);
dd41f596 3418 clear_tsk_need_resched(prev);
c1b3da3e 3419 __update_rq_clock(rq);
1da177e4 3420
1da177e4 3421 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
1da177e4 3422 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
dd41f596 3423 unlikely(signal_pending(prev)))) {
1da177e4 3424 prev->state = TASK_RUNNING;
dd41f596 3425 } else {
2e1cb74a 3426 deactivate_task(rq, prev, 1);
1da177e4 3427 }
dd41f596 3428 switch_count = &prev->nvcsw;
1da177e4
LT
3429 }
3430
dd41f596 3431 if (unlikely(!rq->nr_running))
1da177e4 3432 idle_balance(cpu, rq);
1da177e4 3433
31ee529c 3434 prev->sched_class->put_prev_task(rq, prev);
ff95f3df 3435 next = pick_next_task(rq, prev);
1da177e4
LT
3436
3437 sched_info_switch(prev, next);
dd41f596 3438
1da177e4 3439 if (likely(prev != next)) {
1da177e4
LT
3440 rq->nr_switches++;
3441 rq->curr = next;
3442 ++*switch_count;
3443
dd41f596 3444 context_switch(rq, prev, next); /* unlocks the rq */
1da177e4
LT
3445 } else
3446 spin_unlock_irq(&rq->lock);
3447
dd41f596
IM
3448 if (unlikely(reacquire_kernel_lock(current) < 0)) {
3449 cpu = smp_processor_id();
3450 rq = cpu_rq(cpu);
1da177e4 3451 goto need_resched_nonpreemptible;
dd41f596 3452 }
1da177e4
LT
3453 preempt_enable_no_resched();
3454 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3455 goto need_resched;
3456}
1da177e4
LT
3457EXPORT_SYMBOL(schedule);
3458
3459#ifdef CONFIG_PREEMPT
3460/*
2ed6e34f 3461 * this is the entry point to schedule() from in-kernel preemption
1da177e4
LT
3462 * off of preempt_enable. Kernel preemptions off return from interrupt
3463 * occur there and call schedule directly.
3464 */
3465asmlinkage void __sched preempt_schedule(void)
3466{
3467 struct thread_info *ti = current_thread_info();
3468#ifdef CONFIG_PREEMPT_BKL
3469 struct task_struct *task = current;
3470 int saved_lock_depth;
3471#endif
3472 /*
3473 * If there is a non-zero preempt_count or interrupts are disabled,
3474 * we do not want to preempt the current task. Just return..
3475 */
beed33a8 3476 if (likely(ti->preempt_count || irqs_disabled()))
1da177e4
LT
3477 return;
3478
3479need_resched:
3480 add_preempt_count(PREEMPT_ACTIVE);
3481 /*
3482 * We keep the big kernel semaphore locked, but we
3483 * clear ->lock_depth so that schedule() doesnt
3484 * auto-release the semaphore:
3485 */
3486#ifdef CONFIG_PREEMPT_BKL
3487 saved_lock_depth = task->lock_depth;
3488 task->lock_depth = -1;
3489#endif
3490 schedule();
3491#ifdef CONFIG_PREEMPT_BKL
3492 task->lock_depth = saved_lock_depth;
3493#endif
3494 sub_preempt_count(PREEMPT_ACTIVE);
3495
3496 /* we could miss a preemption opportunity between schedule and now */
3497 barrier();
3498 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3499 goto need_resched;
3500}
1da177e4
LT
3501EXPORT_SYMBOL(preempt_schedule);
3502
3503/*
2ed6e34f 3504 * this is the entry point to schedule() from kernel preemption
1da177e4
LT
3505 * off of irq context.
3506 * Note, that this is called and return with irqs disabled. This will
3507 * protect us against recursive calling from irq.
3508 */
3509asmlinkage void __sched preempt_schedule_irq(void)
3510{
3511 struct thread_info *ti = current_thread_info();
3512#ifdef CONFIG_PREEMPT_BKL
3513 struct task_struct *task = current;
3514 int saved_lock_depth;
3515#endif
2ed6e34f 3516 /* Catch callers which need to be fixed */
1da177e4
LT
3517 BUG_ON(ti->preempt_count || !irqs_disabled());
3518
3519need_resched:
3520 add_preempt_count(PREEMPT_ACTIVE);
3521 /*
3522 * We keep the big kernel semaphore locked, but we
3523 * clear ->lock_depth so that schedule() doesnt
3524 * auto-release the semaphore:
3525 */
3526#ifdef CONFIG_PREEMPT_BKL
3527 saved_lock_depth = task->lock_depth;
3528 task->lock_depth = -1;
3529#endif
3530 local_irq_enable();
3531 schedule();
3532 local_irq_disable();
3533#ifdef CONFIG_PREEMPT_BKL
3534 task->lock_depth = saved_lock_depth;
3535#endif
3536 sub_preempt_count(PREEMPT_ACTIVE);
3537
3538 /* we could miss a preemption opportunity between schedule and now */
3539 barrier();
3540 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3541 goto need_resched;
3542}
3543
3544#endif /* CONFIG_PREEMPT */
3545
95cdf3b7
IM
3546int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
3547 void *key)
1da177e4 3548{
48f24c4d 3549 return try_to_wake_up(curr->private, mode, sync);
1da177e4 3550}
1da177e4
LT
3551EXPORT_SYMBOL(default_wake_function);
3552
3553/*
3554 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3555 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3556 * number) then we wake all the non-exclusive tasks and one exclusive task.
3557 *
3558 * There are circumstances in which we can try to wake a task which has already
3559 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3560 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3561 */
3562static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3563 int nr_exclusive, int sync, void *key)
3564{
2e45874c 3565 wait_queue_t *curr, *next;
1da177e4 3566
2e45874c 3567 list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
48f24c4d
IM
3568 unsigned flags = curr->flags;
3569
1da177e4 3570 if (curr->func(curr, mode, sync, key) &&
48f24c4d 3571 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
1da177e4
LT
3572 break;
3573 }
3574}
3575
3576/**
3577 * __wake_up - wake up threads blocked on a waitqueue.
3578 * @q: the waitqueue
3579 * @mode: which threads
3580 * @nr_exclusive: how many wake-one or wake-many threads to wake up
67be2dd1 3581 * @key: is directly passed to the wakeup function
1da177e4
LT
3582 */
3583void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
95cdf3b7 3584 int nr_exclusive, void *key)
1da177e4
LT
3585{
3586 unsigned long flags;
3587
3588 spin_lock_irqsave(&q->lock, flags);
3589 __wake_up_common(q, mode, nr_exclusive, 0, key);
3590 spin_unlock_irqrestore(&q->lock, flags);
3591}
1da177e4
LT
3592EXPORT_SYMBOL(__wake_up);
3593
3594/*
3595 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3596 */
3597void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3598{
3599 __wake_up_common(q, mode, 1, 0, NULL);
3600}
3601
3602/**
67be2dd1 3603 * __wake_up_sync - wake up threads blocked on a waitqueue.
1da177e4
LT
3604 * @q: the waitqueue
3605 * @mode: which threads
3606 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3607 *
3608 * The sync wakeup differs that the waker knows that it will schedule
3609 * away soon, so while the target thread will be woken up, it will not
3610 * be migrated to another CPU - ie. the two threads are 'synchronized'
3611 * with each other. This can prevent needless bouncing between CPUs.
3612 *
3613 * On UP it can prevent extra preemption.
3614 */
95cdf3b7
IM
3615void fastcall
3616__wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
1da177e4
LT
3617{
3618 unsigned long flags;
3619 int sync = 1;
3620
3621 if (unlikely(!q))
3622 return;
3623
3624 if (unlikely(!nr_exclusive))
3625 sync = 0;
3626
3627 spin_lock_irqsave(&q->lock, flags);
3628 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3629 spin_unlock_irqrestore(&q->lock, flags);
3630}
3631EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3632
3633void fastcall complete(struct completion *x)
3634{
3635 unsigned long flags;
3636
3637 spin_lock_irqsave(&x->wait.lock, flags);
3638 x->done++;
3639 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3640 1, 0, NULL);
3641 spin_unlock_irqrestore(&x->wait.lock, flags);
3642}
3643EXPORT_SYMBOL(complete);
3644
3645void fastcall complete_all(struct completion *x)
3646{
3647 unsigned long flags;
3648
3649 spin_lock_irqsave(&x->wait.lock, flags);
3650 x->done += UINT_MAX/2;
3651 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3652 0, 0, NULL);
3653 spin_unlock_irqrestore(&x->wait.lock, flags);
3654}
3655EXPORT_SYMBOL(complete_all);
3656
3657void fastcall __sched wait_for_completion(struct completion *x)
3658{
3659 might_sleep();
48f24c4d 3660
1da177e4
LT
3661 spin_lock_irq(&x->wait.lock);
3662 if (!x->done) {
3663 DECLARE_WAITQUEUE(wait, current);
3664
3665 wait.flags |= WQ_FLAG_EXCLUSIVE;
3666 __add_wait_queue_tail(&x->wait, &wait);
3667 do {
3668 __set_current_state(TASK_UNINTERRUPTIBLE);
3669 spin_unlock_irq(&x->wait.lock);
3670 schedule();
3671 spin_lock_irq(&x->wait.lock);
3672 } while (!x->done);
3673 __remove_wait_queue(&x->wait, &wait);
3674 }
3675 x->done--;
3676 spin_unlock_irq(&x->wait.lock);
3677}
3678EXPORT_SYMBOL(wait_for_completion);
3679
3680unsigned long fastcall __sched
3681wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3682{
3683 might_sleep();
3684
3685 spin_lock_irq(&x->wait.lock);
3686 if (!x->done) {
3687 DECLARE_WAITQUEUE(wait, current);
3688
3689 wait.flags |= WQ_FLAG_EXCLUSIVE;
3690 __add_wait_queue_tail(&x->wait, &wait);
3691 do {
3692 __set_current_state(TASK_UNINTERRUPTIBLE);
3693 spin_unlock_irq(&x->wait.lock);
3694 timeout = schedule_timeout(timeout);
3695 spin_lock_irq(&x->wait.lock);
3696 if (!timeout) {
3697 __remove_wait_queue(&x->wait, &wait);
3698 goto out;
3699 }
3700 } while (!x->done);
3701 __remove_wait_queue(&x->wait, &wait);
3702 }
3703 x->done--;
3704out:
3705 spin_unlock_irq(&x->wait.lock);
3706 return timeout;
3707}
3708EXPORT_SYMBOL(wait_for_completion_timeout);
3709
3710int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3711{
3712 int ret = 0;
3713
3714 might_sleep();
3715
3716 spin_lock_irq(&x->wait.lock);
3717 if (!x->done) {
3718 DECLARE_WAITQUEUE(wait, current);
3719
3720 wait.flags |= WQ_FLAG_EXCLUSIVE;
3721 __add_wait_queue_tail(&x->wait, &wait);
3722 do {
3723 if (signal_pending(current)) {
3724 ret = -ERESTARTSYS;
3725 __remove_wait_queue(&x->wait, &wait);
3726 goto out;
3727 }
3728 __set_current_state(TASK_INTERRUPTIBLE);
3729 spin_unlock_irq(&x->wait.lock);
3730 schedule();
3731 spin_lock_irq(&x->wait.lock);
3732 } while (!x->done);
3733 __remove_wait_queue(&x->wait, &wait);
3734 }
3735 x->done--;
3736out:
3737 spin_unlock_irq(&x->wait.lock);
3738
3739 return ret;
3740}
3741EXPORT_SYMBOL(wait_for_completion_interruptible);
3742
3743unsigned long fastcall __sched
3744wait_for_completion_interruptible_timeout(struct completion *x,
3745 unsigned long timeout)
3746{
3747 might_sleep();
3748
3749 spin_lock_irq(&x->wait.lock);
3750 if (!x->done) {
3751 DECLARE_WAITQUEUE(wait, current);
3752
3753 wait.flags |= WQ_FLAG_EXCLUSIVE;
3754 __add_wait_queue_tail(&x->wait, &wait);
3755 do {
3756 if (signal_pending(current)) {
3757 timeout = -ERESTARTSYS;
3758 __remove_wait_queue(&x->wait, &wait);
3759 goto out;
3760 }
3761 __set_current_state(TASK_INTERRUPTIBLE);
3762 spin_unlock_irq(&x->wait.lock);
3763 timeout = schedule_timeout(timeout);
3764 spin_lock_irq(&x->wait.lock);
3765 if (!timeout) {
3766 __remove_wait_queue(&x->wait, &wait);
3767 goto out;
3768 }
3769 } while (!x->done);
3770 __remove_wait_queue(&x->wait, &wait);
3771 }
3772 x->done--;
3773out:
3774 spin_unlock_irq(&x->wait.lock);
3775 return timeout;
3776}
3777EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3778
0fec171c
IM
3779static inline void
3780sleep_on_head(wait_queue_head_t *q, wait_queue_t *wait, unsigned long *flags)
3781{
3782 spin_lock_irqsave(&q->lock, *flags);
3783 __add_wait_queue(q, wait);
1da177e4 3784 spin_unlock(&q->lock);
0fec171c 3785}
1da177e4 3786
0fec171c
IM
3787static inline void
3788sleep_on_tail(wait_queue_head_t *q, wait_queue_t *wait, unsigned long *flags)
3789{
3790 spin_lock_irq(&q->lock);
3791 __remove_wait_queue(q, wait);
3792 spin_unlock_irqrestore(&q->lock, *flags);
3793}
1da177e4 3794
0fec171c 3795void __sched interruptible_sleep_on(wait_queue_head_t *q)
1da177e4 3796{
0fec171c
IM
3797 unsigned long flags;
3798 wait_queue_t wait;
3799
3800 init_waitqueue_entry(&wait, current);
1da177e4
LT
3801
3802 current->state = TASK_INTERRUPTIBLE;
3803
0fec171c 3804 sleep_on_head(q, &wait, &flags);
1da177e4 3805 schedule();
0fec171c 3806 sleep_on_tail(q, &wait, &flags);
1da177e4 3807}
1da177e4
LT
3808EXPORT_SYMBOL(interruptible_sleep_on);
3809
0fec171c 3810long __sched
95cdf3b7 3811interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
1da177e4 3812{
0fec171c
IM
3813 unsigned long flags;
3814 wait_queue_t wait;
3815
3816 init_waitqueue_entry(&wait, current);
1da177e4
LT
3817
3818 current->state = TASK_INTERRUPTIBLE;
3819
0fec171c 3820 sleep_on_head(q, &wait, &flags);
1da177e4 3821 timeout = schedule_timeout(timeout);
0fec171c 3822 sleep_on_tail(q, &wait, &flags);
1da177e4
LT
3823
3824 return timeout;
3825}
1da177e4
LT
3826EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3827
0fec171c 3828void __sched sleep_on(wait_queue_head_t *q)
1da177e4 3829{
0fec171c
IM
3830 unsigned long flags;
3831 wait_queue_t wait;
3832
3833 init_waitqueue_entry(&wait, current);
1da177e4
LT
3834
3835 current->state = TASK_UNINTERRUPTIBLE;
3836
0fec171c 3837 sleep_on_head(q, &wait, &flags);
1da177e4 3838 schedule();
0fec171c 3839 sleep_on_tail(q, &wait, &flags);
1da177e4 3840}
1da177e4
LT
3841EXPORT_SYMBOL(sleep_on);
3842
0fec171c 3843long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
1da177e4 3844{
0fec171c
IM
3845 unsigned long flags;
3846 wait_queue_t wait;
3847
3848 init_waitqueue_entry(&wait, current);
1da177e4
LT
3849
3850 current->state = TASK_UNINTERRUPTIBLE;
3851
0fec171c 3852 sleep_on_head(q, &wait, &flags);
1da177e4 3853 timeout = schedule_timeout(timeout);
0fec171c 3854 sleep_on_tail(q, &wait, &flags);
1da177e4
LT
3855
3856 return timeout;
3857}
1da177e4
LT
3858EXPORT_SYMBOL(sleep_on_timeout);
3859
b29739f9
IM
3860#ifdef CONFIG_RT_MUTEXES
3861
3862/*
3863 * rt_mutex_setprio - set the current priority of a task
3864 * @p: task
3865 * @prio: prio value (kernel-internal form)
3866 *
3867 * This function changes the 'effective' priority of a task. It does
3868 * not touch ->normal_prio like __setscheduler().
3869 *
3870 * Used by the rt_mutex code to implement priority inheritance logic.
3871 */
36c8b586 3872void rt_mutex_setprio(struct task_struct *p, int prio)
b29739f9
IM
3873{
3874 unsigned long flags;
dd41f596 3875 int oldprio, on_rq;
70b97a7f 3876 struct rq *rq;
b29739f9
IM
3877
3878 BUG_ON(prio < 0 || prio > MAX_PRIO);
3879
3880 rq = task_rq_lock(p, &flags);
a8e504d2 3881 update_rq_clock(rq);
b29739f9 3882
d5f9f942 3883 oldprio = p->prio;
dd41f596
IM
3884 on_rq = p->se.on_rq;
3885 if (on_rq)
69be72c1 3886 dequeue_task(rq, p, 0);
dd41f596
IM
3887
3888 if (rt_prio(prio))
3889 p->sched_class = &rt_sched_class;
3890 else
3891 p->sched_class = &fair_sched_class;
3892
b29739f9
IM
3893 p->prio = prio;
3894
dd41f596 3895 if (on_rq) {
8159f87e 3896 enqueue_task(rq, p, 0);
b29739f9
IM
3897 /*
3898 * Reschedule if we are currently running on this runqueue and
d5f9f942
AM
3899 * our priority decreased, or if we are not currently running on
3900 * this runqueue and our priority is higher than the current's
b29739f9 3901 */
d5f9f942
AM
3902 if (task_running(rq, p)) {
3903 if (p->prio > oldprio)
3904 resched_task(rq->curr);
dd41f596
IM
3905 } else {
3906 check_preempt_curr(rq, p);
3907 }
b29739f9
IM
3908 }
3909 task_rq_unlock(rq, &flags);
3910}
3911
3912#endif
3913
36c8b586 3914void set_user_nice(struct task_struct *p, long nice)
1da177e4 3915{
dd41f596 3916 int old_prio, delta, on_rq;
1da177e4 3917 unsigned long flags;
70b97a7f 3918 struct rq *rq;
1da177e4
LT
3919
3920 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3921 return;
3922 /*
3923 * We have to be careful, if called from sys_setpriority(),
3924 * the task might be in the middle of scheduling on another CPU.
3925 */
3926 rq = task_rq_lock(p, &flags);
a8e504d2 3927 update_rq_clock(rq);
1da177e4
LT
3928 /*
3929 * The RT priorities are set via sched_setscheduler(), but we still
3930 * allow the 'normal' nice value to be set - but as expected
3931 * it wont have any effect on scheduling until the task is
dd41f596 3932 * SCHED_FIFO/SCHED_RR:
1da177e4 3933 */
e05606d3 3934 if (task_has_rt_policy(p)) {
1da177e4
LT
3935 p->static_prio = NICE_TO_PRIO(nice);
3936 goto out_unlock;
3937 }
dd41f596
IM
3938 on_rq = p->se.on_rq;
3939 if (on_rq) {
69be72c1 3940 dequeue_task(rq, p, 0);
79b5dddf 3941 dec_load(rq, p);
2dd73a4f 3942 }
1da177e4 3943
1da177e4 3944 p->static_prio = NICE_TO_PRIO(nice);
2dd73a4f 3945 set_load_weight(p);
b29739f9
IM
3946 old_prio = p->prio;
3947 p->prio = effective_prio(p);
3948 delta = p->prio - old_prio;
1da177e4 3949
dd41f596 3950 if (on_rq) {
8159f87e 3951 enqueue_task(rq, p, 0);
29b4b623 3952 inc_load(rq, p);
1da177e4 3953 /*
d5f9f942
AM
3954 * If the task increased its priority or is running and
3955 * lowered its priority, then reschedule its CPU:
1da177e4 3956 */
d5f9f942 3957 if (delta < 0 || (delta > 0 && task_running(rq, p)))
1da177e4
LT
3958 resched_task(rq->curr);
3959 }
3960out_unlock:
3961 task_rq_unlock(rq, &flags);
3962}
1da177e4
LT
3963EXPORT_SYMBOL(set_user_nice);
3964
e43379f1
MM
3965/*
3966 * can_nice - check if a task can reduce its nice value
3967 * @p: task
3968 * @nice: nice value
3969 */
36c8b586 3970int can_nice(const struct task_struct *p, const int nice)
e43379f1 3971{
024f4747
MM
3972 /* convert nice value [19,-20] to rlimit style value [1,40] */
3973 int nice_rlim = 20 - nice;
48f24c4d 3974
e43379f1
MM
3975 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
3976 capable(CAP_SYS_NICE));
3977}
3978
1da177e4
LT
3979#ifdef __ARCH_WANT_SYS_NICE
3980
3981/*
3982 * sys_nice - change the priority of the current process.
3983 * @increment: priority increment
3984 *
3985 * sys_setpriority is a more generic, but much slower function that
3986 * does similar things.
3987 */
3988asmlinkage long sys_nice(int increment)
3989{
48f24c4d 3990 long nice, retval;
1da177e4
LT
3991
3992 /*
3993 * Setpriority might change our priority at the same moment.
3994 * We don't have to worry. Conceptually one call occurs first
3995 * and we have a single winner.
3996 */
e43379f1
MM
3997 if (increment < -40)
3998 increment = -40;
1da177e4
LT
3999 if (increment > 40)
4000 increment = 40;
4001
4002 nice = PRIO_TO_NICE(current->static_prio) + increment;
4003 if (nice < -20)
4004 nice = -20;
4005 if (nice > 19)
4006 nice = 19;
4007
e43379f1
MM
4008 if (increment < 0 && !can_nice(current, nice))
4009 return -EPERM;
4010
1da177e4
LT
4011 retval = security_task_setnice(current, nice);
4012 if (retval)
4013 return retval;
4014
4015 set_user_nice(current, nice);
4016 return 0;
4017}
4018
4019#endif
4020
4021/**
4022 * task_prio - return the priority value of a given task.
4023 * @p: the task in question.
4024 *
4025 * This is the priority value as seen by users in /proc.
4026 * RT tasks are offset by -200. Normal tasks are centered
4027 * around 0, value goes from -16 to +15.
4028 */
36c8b586 4029int task_prio(const struct task_struct *p)
1da177e4
LT
4030{
4031 return p->prio - MAX_RT_PRIO;
4032}
4033
4034/**
4035 * task_nice - return the nice value of a given task.
4036 * @p: the task in question.
4037 */
36c8b586 4038int task_nice(const struct task_struct *p)
1da177e4
LT
4039{
4040 return TASK_NICE(p);
4041}
1da177e4 4042EXPORT_SYMBOL_GPL(task_nice);
1da177e4
LT
4043
4044/**
4045 * idle_cpu - is a given cpu idle currently?
4046 * @cpu: the processor in question.
4047 */
4048int idle_cpu(int cpu)
4049{
4050 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
4051}
4052
1da177e4
LT
4053/**
4054 * idle_task - return the idle task for a given cpu.
4055 * @cpu: the processor in question.
4056 */
36c8b586 4057struct task_struct *idle_task(int cpu)
1da177e4
LT
4058{
4059 return cpu_rq(cpu)->idle;
4060}
4061
4062/**
4063 * find_process_by_pid - find a process with a matching PID value.
4064 * @pid: the pid in question.
4065 */
36c8b586 4066static inline struct task_struct *find_process_by_pid(pid_t pid)
1da177e4
LT
4067{
4068 return pid ? find_task_by_pid(pid) : current;
4069}
4070
4071/* Actually do priority change: must hold rq lock. */
dd41f596
IM
4072static void
4073__setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
1da177e4 4074{
dd41f596 4075 BUG_ON(p->se.on_rq);
48f24c4d 4076
1da177e4 4077 p->policy = policy;
dd41f596
IM
4078 switch (p->policy) {
4079 case SCHED_NORMAL:
4080 case SCHED_BATCH:
4081 case SCHED_IDLE:
4082 p->sched_class = &fair_sched_class;
4083 break;
4084 case SCHED_FIFO:
4085 case SCHED_RR:
4086 p->sched_class = &rt_sched_class;
4087 break;
4088 }
4089
1da177e4 4090 p->rt_priority = prio;
b29739f9
IM
4091 p->normal_prio = normal_prio(p);
4092 /* we are holding p->pi_lock already */
4093 p->prio = rt_mutex_getprio(p);
2dd73a4f 4094 set_load_weight(p);
1da177e4
LT
4095}
4096
4097/**
72fd4a35 4098 * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
1da177e4
LT
4099 * @p: the task in question.
4100 * @policy: new policy.
4101 * @param: structure containing the new RT priority.
5fe1d75f 4102 *
72fd4a35 4103 * NOTE that the task may be already dead.
1da177e4 4104 */
95cdf3b7
IM
4105int sched_setscheduler(struct task_struct *p, int policy,
4106 struct sched_param *param)
1da177e4 4107{
dd41f596 4108 int retval, oldprio, oldpolicy = -1, on_rq;
1da177e4 4109 unsigned long flags;
70b97a7f 4110 struct rq *rq;
1da177e4 4111
66e5393a
SR
4112 /* may grab non-irq protected spin_locks */
4113 BUG_ON(in_interrupt());
1da177e4
LT
4114recheck:
4115 /* double check policy once rq lock held */
4116 if (policy < 0)
4117 policy = oldpolicy = p->policy;
4118 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
dd41f596
IM
4119 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
4120 policy != SCHED_IDLE)
b0a9499c 4121 return -EINVAL;
1da177e4
LT
4122 /*
4123 * Valid priorities for SCHED_FIFO and SCHED_RR are
dd41f596
IM
4124 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4125 * SCHED_BATCH and SCHED_IDLE is 0.
1da177e4
LT
4126 */
4127 if (param->sched_priority < 0 ||
95cdf3b7 4128 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
d46523ea 4129 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
1da177e4 4130 return -EINVAL;
e05606d3 4131 if (rt_policy(policy) != (param->sched_priority != 0))
1da177e4
LT
4132 return -EINVAL;
4133
37e4ab3f
OC
4134 /*
4135 * Allow unprivileged RT tasks to decrease priority:
4136 */
4137 if (!capable(CAP_SYS_NICE)) {
e05606d3 4138 if (rt_policy(policy)) {
8dc3e909 4139 unsigned long rlim_rtprio;
8dc3e909
ON
4140
4141 if (!lock_task_sighand(p, &flags))
4142 return -ESRCH;
4143 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
4144 unlock_task_sighand(p, &flags);
4145
4146 /* can't set/change the rt policy */
4147 if (policy != p->policy && !rlim_rtprio)
4148 return -EPERM;
4149
4150 /* can't increase priority */
4151 if (param->sched_priority > p->rt_priority &&
4152 param->sched_priority > rlim_rtprio)
4153 return -EPERM;
4154 }
dd41f596
IM
4155 /*
4156 * Like positive nice levels, dont allow tasks to
4157 * move out of SCHED_IDLE either:
4158 */
4159 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
4160 return -EPERM;
5fe1d75f 4161
37e4ab3f
OC
4162 /* can't change other user's priorities */
4163 if ((current->euid != p->euid) &&
4164 (current->euid != p->uid))
4165 return -EPERM;
4166 }
1da177e4
LT
4167
4168 retval = security_task_setscheduler(p, policy, param);
4169 if (retval)
4170 return retval;
b29739f9
IM
4171 /*
4172 * make sure no PI-waiters arrive (or leave) while we are
4173 * changing the priority of the task:
4174 */
4175 spin_lock_irqsave(&p->pi_lock, flags);
1da177e4
LT
4176 /*
4177 * To be able to change p->policy safely, the apropriate
4178 * runqueue lock must be held.
4179 */
b29739f9 4180 rq = __task_rq_lock(p);
1da177e4
LT
4181 /* recheck policy now with rq lock held */
4182 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4183 policy = oldpolicy = -1;
b29739f9
IM
4184 __task_rq_unlock(rq);
4185 spin_unlock_irqrestore(&p->pi_lock, flags);
1da177e4
LT
4186 goto recheck;
4187 }
2daa3577 4188 update_rq_clock(rq);
dd41f596 4189 on_rq = p->se.on_rq;
2daa3577 4190 if (on_rq)
2e1cb74a 4191 deactivate_task(rq, p, 0);
1da177e4 4192 oldprio = p->prio;
dd41f596
IM
4193 __setscheduler(rq, p, policy, param->sched_priority);
4194 if (on_rq) {
4195 activate_task(rq, p, 0);
1da177e4
LT
4196 /*
4197 * Reschedule if we are currently running on this runqueue and
d5f9f942
AM
4198 * our priority decreased, or if we are not currently running on
4199 * this runqueue and our priority is higher than the current's
1da177e4 4200 */
d5f9f942
AM
4201 if (task_running(rq, p)) {
4202 if (p->prio > oldprio)
4203 resched_task(rq->curr);
dd41f596
IM
4204 } else {
4205 check_preempt_curr(rq, p);
4206 }
1da177e4 4207 }
b29739f9
IM
4208 __task_rq_unlock(rq);
4209 spin_unlock_irqrestore(&p->pi_lock, flags);
4210
95e02ca9
TG
4211 rt_mutex_adjust_pi(p);
4212
1da177e4
LT
4213 return 0;
4214}
4215EXPORT_SYMBOL_GPL(sched_setscheduler);
4216
95cdf3b7
IM
4217static int
4218do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
1da177e4 4219{
1da177e4
LT
4220 struct sched_param lparam;
4221 struct task_struct *p;
36c8b586 4222 int retval;
1da177e4
LT
4223
4224 if (!param || pid < 0)
4225 return -EINVAL;
4226 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4227 return -EFAULT;
5fe1d75f
ON
4228
4229 rcu_read_lock();
4230 retval = -ESRCH;
1da177e4 4231 p = find_process_by_pid(pid);
5fe1d75f
ON
4232 if (p != NULL)
4233 retval = sched_setscheduler(p, policy, &lparam);
4234 rcu_read_unlock();
36c8b586 4235
1da177e4
LT
4236 return retval;
4237}
4238
4239/**
4240 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4241 * @pid: the pid in question.
4242 * @policy: new policy.
4243 * @param: structure containing the new RT priority.
4244 */
4245asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
4246 struct sched_param __user *param)
4247{
c21761f1
JB
4248 /* negative values for policy are not valid */
4249 if (policy < 0)
4250 return -EINVAL;
4251
1da177e4
LT
4252 return do_sched_setscheduler(pid, policy, param);
4253}
4254
4255/**
4256 * sys_sched_setparam - set/change the RT priority of a thread
4257 * @pid: the pid in question.
4258 * @param: structure containing the new RT priority.
4259 */
4260asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
4261{
4262 return do_sched_setscheduler(pid, -1, param);
4263}
4264
4265/**
4266 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4267 * @pid: the pid in question.
4268 */
4269asmlinkage long sys_sched_getscheduler(pid_t pid)
4270{
36c8b586 4271 struct task_struct *p;
1da177e4 4272 int retval = -EINVAL;
1da177e4
LT
4273
4274 if (pid < 0)
4275 goto out_nounlock;
4276
4277 retval = -ESRCH;
4278 read_lock(&tasklist_lock);
4279 p = find_process_by_pid(pid);
4280 if (p) {
4281 retval = security_task_getscheduler(p);
4282 if (!retval)
4283 retval = p->policy;
4284 }
4285 read_unlock(&tasklist_lock);
4286
4287out_nounlock:
4288 return retval;
4289}
4290
4291/**
4292 * sys_sched_getscheduler - get the RT priority of a thread
4293 * @pid: the pid in question.
4294 * @param: structure containing the RT priority.
4295 */
4296asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
4297{
4298 struct sched_param lp;
36c8b586 4299 struct task_struct *p;
1da177e4 4300 int retval = -EINVAL;
1da177e4
LT
4301
4302 if (!param || pid < 0)
4303 goto out_nounlock;
4304
4305 read_lock(&tasklist_lock);
4306 p = find_process_by_pid(pid);
4307 retval = -ESRCH;
4308 if (!p)
4309 goto out_unlock;
4310
4311 retval = security_task_getscheduler(p);
4312 if (retval)
4313 goto out_unlock;
4314
4315 lp.sched_priority = p->rt_priority;
4316 read_unlock(&tasklist_lock);
4317
4318 /*
4319 * This one might sleep, we cannot do it with a spinlock held ...
4320 */
4321 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4322
4323out_nounlock:
4324 return retval;
4325
4326out_unlock:
4327 read_unlock(&tasklist_lock);
4328 return retval;
4329}
4330
4331long sched_setaffinity(pid_t pid, cpumask_t new_mask)
4332{
1da177e4 4333 cpumask_t cpus_allowed;
36c8b586
IM
4334 struct task_struct *p;
4335 int retval;
1da177e4 4336
5be9361c 4337 mutex_lock(&sched_hotcpu_mutex);
1da177e4
LT
4338 read_lock(&tasklist_lock);
4339
4340 p = find_process_by_pid(pid);
4341 if (!p) {
4342 read_unlock(&tasklist_lock);
5be9361c 4343 mutex_unlock(&sched_hotcpu_mutex);
1da177e4
LT
4344 return -ESRCH;
4345 }
4346
4347 /*
4348 * It is not safe to call set_cpus_allowed with the
4349 * tasklist_lock held. We will bump the task_struct's
4350 * usage count and then drop tasklist_lock.
4351 */
4352 get_task_struct(p);
4353 read_unlock(&tasklist_lock);
4354
4355 retval = -EPERM;
4356 if ((current->euid != p->euid) && (current->euid != p->uid) &&
4357 !capable(CAP_SYS_NICE))
4358 goto out_unlock;
4359
e7834f8f
DQ
4360 retval = security_task_setscheduler(p, 0, NULL);
4361 if (retval)
4362 goto out_unlock;
4363
1da177e4
LT
4364 cpus_allowed = cpuset_cpus_allowed(p);
4365 cpus_and(new_mask, new_mask, cpus_allowed);
4366 retval = set_cpus_allowed(p, new_mask);
4367
4368out_unlock:
4369 put_task_struct(p);
5be9361c 4370 mutex_unlock(&sched_hotcpu_mutex);
1da177e4
LT
4371 return retval;
4372}
4373
4374static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4375 cpumask_t *new_mask)
4376{
4377 if (len < sizeof(cpumask_t)) {
4378 memset(new_mask, 0, sizeof(cpumask_t));
4379 } else if (len > sizeof(cpumask_t)) {
4380 len = sizeof(cpumask_t);
4381 }
4382 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4383}
4384
4385/**
4386 * sys_sched_setaffinity - set the cpu affinity of a process
4387 * @pid: pid of the process
4388 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4389 * @user_mask_ptr: user-space pointer to the new cpu mask
4390 */
4391asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
4392 unsigned long __user *user_mask_ptr)
4393{
4394 cpumask_t new_mask;
4395 int retval;
4396
4397 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
4398 if (retval)
4399 return retval;
4400
4401 return sched_setaffinity(pid, new_mask);
4402}
4403
4404/*
4405 * Represents all cpu's present in the system
4406 * In systems capable of hotplug, this map could dynamically grow
4407 * as new cpu's are detected in the system via any platform specific
4408 * method, such as ACPI for e.g.
4409 */
4410
4cef0c61 4411cpumask_t cpu_present_map __read_mostly;
1da177e4
LT
4412EXPORT_SYMBOL(cpu_present_map);
4413
4414#ifndef CONFIG_SMP
4cef0c61 4415cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
e16b38f7
GB
4416EXPORT_SYMBOL(cpu_online_map);
4417
4cef0c61 4418cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
e16b38f7 4419EXPORT_SYMBOL(cpu_possible_map);
1da177e4
LT
4420#endif
4421
4422long sched_getaffinity(pid_t pid, cpumask_t *mask)
4423{
36c8b586 4424 struct task_struct *p;
1da177e4 4425 int retval;
1da177e4 4426
5be9361c 4427 mutex_lock(&sched_hotcpu_mutex);
1da177e4
LT
4428 read_lock(&tasklist_lock);
4429
4430 retval = -ESRCH;
4431 p = find_process_by_pid(pid);
4432 if (!p)
4433 goto out_unlock;
4434
e7834f8f
DQ
4435 retval = security_task_getscheduler(p);
4436 if (retval)
4437 goto out_unlock;
4438
2f7016d9 4439 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
1da177e4
LT
4440
4441out_unlock:
4442 read_unlock(&tasklist_lock);
5be9361c 4443 mutex_unlock(&sched_hotcpu_mutex);
1da177e4 4444
9531b62f 4445 return retval;
1da177e4
LT
4446}
4447
4448/**
4449 * sys_sched_getaffinity - get the cpu affinity of a process
4450 * @pid: pid of the process
4451 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4452 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4453 */
4454asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
4455 unsigned long __user *user_mask_ptr)
4456{
4457 int ret;
4458 cpumask_t mask;
4459
4460 if (len < sizeof(cpumask_t))
4461 return -EINVAL;
4462
4463 ret = sched_getaffinity(pid, &mask);
4464 if (ret < 0)
4465 return ret;
4466
4467 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
4468 return -EFAULT;
4469
4470 return sizeof(cpumask_t);
4471}
4472
4473/**
4474 * sys_sched_yield - yield the current processor to other threads.
4475 *
dd41f596
IM
4476 * This function yields the current CPU to other tasks. If there are no
4477 * other threads running on this CPU then this function will return.
1da177e4
LT
4478 */
4479asmlinkage long sys_sched_yield(void)
4480{
70b97a7f 4481 struct rq *rq = this_rq_lock();
1da177e4
LT
4482
4483 schedstat_inc(rq, yld_cnt);
1799e35d 4484 current->sched_class->yield_task(rq, current);
1da177e4
LT
4485
4486 /*
4487 * Since we are going to call schedule() anyway, there's
4488 * no need to preempt or enable interrupts:
4489 */
4490 __release(rq->lock);
8a25d5de 4491 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
1da177e4
LT
4492 _raw_spin_unlock(&rq->lock);
4493 preempt_enable_no_resched();
4494
4495 schedule();
4496
4497 return 0;
4498}
4499
e7b38404 4500static void __cond_resched(void)
1da177e4 4501{
8e0a43d8
IM
4502#ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4503 __might_sleep(__FILE__, __LINE__);
4504#endif
5bbcfd90
IM
4505 /*
4506 * The BKS might be reacquired before we have dropped
4507 * PREEMPT_ACTIVE, which could trigger a second
4508 * cond_resched() call.
4509 */
1da177e4
LT
4510 do {
4511 add_preempt_count(PREEMPT_ACTIVE);
4512 schedule();
4513 sub_preempt_count(PREEMPT_ACTIVE);
4514 } while (need_resched());
4515}
4516
4517int __sched cond_resched(void)
4518{
9414232f
IM
4519 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
4520 system_state == SYSTEM_RUNNING) {
1da177e4
LT
4521 __cond_resched();
4522 return 1;
4523 }
4524 return 0;
4525}
1da177e4
LT
4526EXPORT_SYMBOL(cond_resched);
4527
4528/*
4529 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4530 * call schedule, and on return reacquire the lock.
4531 *
4532 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4533 * operations here to prevent schedule() from being called twice (once via
4534 * spin_unlock(), once by hand).
4535 */
95cdf3b7 4536int cond_resched_lock(spinlock_t *lock)
1da177e4 4537{
6df3cecb
JK
4538 int ret = 0;
4539
1da177e4
LT
4540 if (need_lockbreak(lock)) {
4541 spin_unlock(lock);
4542 cpu_relax();
6df3cecb 4543 ret = 1;
1da177e4
LT
4544 spin_lock(lock);
4545 }
9414232f 4546 if (need_resched() && system_state == SYSTEM_RUNNING) {
8a25d5de 4547 spin_release(&lock->dep_map, 1, _THIS_IP_);
1da177e4
LT
4548 _raw_spin_unlock(lock);
4549 preempt_enable_no_resched();
4550 __cond_resched();
6df3cecb 4551 ret = 1;
1da177e4 4552 spin_lock(lock);
1da177e4 4553 }
6df3cecb 4554 return ret;
1da177e4 4555}
1da177e4
LT
4556EXPORT_SYMBOL(cond_resched_lock);
4557
4558int __sched cond_resched_softirq(void)
4559{
4560 BUG_ON(!in_softirq());
4561
9414232f 4562 if (need_resched() && system_state == SYSTEM_RUNNING) {
98d82567 4563 local_bh_enable();
1da177e4
LT
4564 __cond_resched();
4565 local_bh_disable();
4566 return 1;
4567 }
4568 return 0;
4569}
1da177e4
LT
4570EXPORT_SYMBOL(cond_resched_softirq);
4571
1da177e4
LT
4572/**
4573 * yield - yield the current processor to other threads.
4574 *
72fd4a35 4575 * This is a shortcut for kernel-space yielding - it marks the
1da177e4
LT
4576 * thread runnable and calls sys_sched_yield().
4577 */
4578void __sched yield(void)
4579{
4580 set_current_state(TASK_RUNNING);
4581 sys_sched_yield();
4582}
1da177e4
LT
4583EXPORT_SYMBOL(yield);
4584
4585/*
4586 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4587 * that process accounting knows that this is a task in IO wait state.
4588 *
4589 * But don't do that if it is a deliberate, throttling IO wait (this task
4590 * has set its backing_dev_info: the queue against which it should throttle)
4591 */
4592void __sched io_schedule(void)
4593{
70b97a7f 4594 struct rq *rq = &__raw_get_cpu_var(runqueues);
1da177e4 4595
0ff92245 4596 delayacct_blkio_start();
1da177e4
LT
4597 atomic_inc(&rq->nr_iowait);
4598 schedule();
4599 atomic_dec(&rq->nr_iowait);
0ff92245 4600 delayacct_blkio_end();
1da177e4 4601}
1da177e4
LT
4602EXPORT_SYMBOL(io_schedule);
4603
4604long __sched io_schedule_timeout(long timeout)
4605{
70b97a7f 4606 struct rq *rq = &__raw_get_cpu_var(runqueues);
1da177e4
LT
4607 long ret;
4608
0ff92245 4609 delayacct_blkio_start();
1da177e4
LT
4610 atomic_inc(&rq->nr_iowait);
4611 ret = schedule_timeout(timeout);
4612 atomic_dec(&rq->nr_iowait);
0ff92245 4613 delayacct_blkio_end();
1da177e4
LT
4614 return ret;
4615}
4616
4617/**
4618 * sys_sched_get_priority_max - return maximum RT priority.
4619 * @policy: scheduling class.
4620 *
4621 * this syscall returns the maximum rt_priority that can be used
4622 * by a given scheduling class.
4623 */
4624asmlinkage long sys_sched_get_priority_max(int policy)
4625{
4626 int ret = -EINVAL;
4627
4628 switch (policy) {
4629 case SCHED_FIFO:
4630 case SCHED_RR:
4631 ret = MAX_USER_RT_PRIO-1;
4632 break;
4633 case SCHED_NORMAL:
b0a9499c 4634 case SCHED_BATCH:
dd41f596 4635 case SCHED_IDLE:
1da177e4
LT
4636 ret = 0;
4637 break;
4638 }
4639 return ret;
4640}
4641
4642/**
4643 * sys_sched_get_priority_min - return minimum RT priority.
4644 * @policy: scheduling class.
4645 *
4646 * this syscall returns the minimum rt_priority that can be used
4647 * by a given scheduling class.
4648 */
4649asmlinkage long sys_sched_get_priority_min(int policy)
4650{
4651 int ret = -EINVAL;
4652
4653 switch (policy) {
4654 case SCHED_FIFO:
4655 case SCHED_RR:
4656 ret = 1;
4657 break;
4658 case SCHED_NORMAL:
b0a9499c 4659 case SCHED_BATCH:
dd41f596 4660 case SCHED_IDLE:
1da177e4
LT
4661 ret = 0;
4662 }
4663 return ret;
4664}
4665
4666/**
4667 * sys_sched_rr_get_interval - return the default timeslice of a process.
4668 * @pid: pid of the process.
4669 * @interval: userspace pointer to the timeslice value.
4670 *
4671 * this syscall writes the default timeslice value of a given process
4672 * into the user-space timespec buffer. A value of '0' means infinity.
4673 */
4674asmlinkage
4675long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4676{
36c8b586 4677 struct task_struct *p;
1da177e4
LT
4678 int retval = -EINVAL;
4679 struct timespec t;
1da177e4
LT
4680
4681 if (pid < 0)
4682 goto out_nounlock;
4683
4684 retval = -ESRCH;
4685 read_lock(&tasklist_lock);
4686 p = find_process_by_pid(pid);
4687 if (!p)
4688 goto out_unlock;
4689
4690 retval = security_task_getscheduler(p);
4691 if (retval)
4692 goto out_unlock;
4693
b78709cf 4694 jiffies_to_timespec(p->policy == SCHED_FIFO ?
dd41f596 4695 0 : static_prio_timeslice(p->static_prio), &t);
1da177e4
LT
4696 read_unlock(&tasklist_lock);
4697 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4698out_nounlock:
4699 return retval;
4700out_unlock:
4701 read_unlock(&tasklist_lock);
4702 return retval;
4703}
4704
2ed6e34f 4705static const char stat_nam[] = "RSDTtZX";
36c8b586
IM
4706
4707static void show_task(struct task_struct *p)
1da177e4 4708{
1da177e4 4709 unsigned long free = 0;
36c8b586 4710 unsigned state;
1da177e4 4711
1da177e4 4712 state = p->state ? __ffs(p->state) + 1 : 0;
2ed6e34f
AM
4713 printk("%-13.13s %c", p->comm,
4714 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
4bd77321 4715#if BITS_PER_LONG == 32
1da177e4 4716 if (state == TASK_RUNNING)
4bd77321 4717 printk(" running ");
1da177e4 4718 else
4bd77321 4719 printk(" %08lx ", thread_saved_pc(p));
1da177e4
LT
4720#else
4721 if (state == TASK_RUNNING)
4bd77321 4722 printk(" running task ");
1da177e4
LT
4723 else
4724 printk(" %016lx ", thread_saved_pc(p));
4725#endif
4726#ifdef CONFIG_DEBUG_STACK_USAGE
4727 {
10ebffde 4728 unsigned long *n = end_of_stack(p);
1da177e4
LT
4729 while (!*n)
4730 n++;
10ebffde 4731 free = (unsigned long)n - (unsigned long)end_of_stack(p);
1da177e4
LT
4732 }
4733#endif
4bd77321 4734 printk("%5lu %5d %6d\n", free, p->pid, p->parent->pid);
1da177e4
LT
4735
4736 if (state != TASK_RUNNING)
4737 show_stack(p, NULL);
4738}
4739
e59e2ae2 4740void show_state_filter(unsigned long state_filter)
1da177e4 4741{
36c8b586 4742 struct task_struct *g, *p;
1da177e4 4743
4bd77321
IM
4744#if BITS_PER_LONG == 32
4745 printk(KERN_INFO
4746 " task PC stack pid father\n");
1da177e4 4747#else
4bd77321
IM
4748 printk(KERN_INFO
4749 " task PC stack pid father\n");
1da177e4
LT
4750#endif
4751 read_lock(&tasklist_lock);
4752 do_each_thread(g, p) {
4753 /*
4754 * reset the NMI-timeout, listing all files on a slow
4755 * console might take alot of time:
4756 */
4757 touch_nmi_watchdog();
39bc89fd 4758 if (!state_filter || (p->state & state_filter))
e59e2ae2 4759 show_task(p);
1da177e4
LT
4760 } while_each_thread(g, p);
4761
04c9167f
JF
4762 touch_all_softlockup_watchdogs();
4763
dd41f596
IM
4764#ifdef CONFIG_SCHED_DEBUG
4765 sysrq_sched_debug_show();
4766#endif
1da177e4 4767 read_unlock(&tasklist_lock);
e59e2ae2
IM
4768 /*
4769 * Only show locks if all tasks are dumped:
4770 */
4771 if (state_filter == -1)
4772 debug_show_all_locks();
1da177e4
LT
4773}
4774
1df21055
IM
4775void __cpuinit init_idle_bootup_task(struct task_struct *idle)
4776{
dd41f596 4777 idle->sched_class = &idle_sched_class;
1df21055
IM
4778}
4779
f340c0d1
IM
4780/**
4781 * init_idle - set up an idle thread for a given CPU
4782 * @idle: task in question
4783 * @cpu: cpu the idle task belongs to
4784 *
4785 * NOTE: this function does not set the idle thread's NEED_RESCHED
4786 * flag, to make booting more robust.
4787 */
5c1e1767 4788void __cpuinit init_idle(struct task_struct *idle, int cpu)
1da177e4 4789{
70b97a7f 4790 struct rq *rq = cpu_rq(cpu);
1da177e4
LT
4791 unsigned long flags;
4792
dd41f596
IM
4793 __sched_fork(idle);
4794 idle->se.exec_start = sched_clock();
4795
b29739f9 4796 idle->prio = idle->normal_prio = MAX_PRIO;
1da177e4 4797 idle->cpus_allowed = cpumask_of_cpu(cpu);
dd41f596 4798 __set_task_cpu(idle, cpu);
1da177e4
LT
4799
4800 spin_lock_irqsave(&rq->lock, flags);
4801 rq->curr = rq->idle = idle;
4866cde0
NP
4802#if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
4803 idle->oncpu = 1;
4804#endif
1da177e4
LT
4805 spin_unlock_irqrestore(&rq->lock, flags);
4806
4807 /* Set the preempt count _outside_ the spinlocks! */
4808#if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
a1261f54 4809 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
1da177e4 4810#else
a1261f54 4811 task_thread_info(idle)->preempt_count = 0;
1da177e4 4812#endif
dd41f596
IM
4813 /*
4814 * The idle tasks have their own, simple scheduling class:
4815 */
4816 idle->sched_class = &idle_sched_class;
1da177e4
LT
4817}
4818
4819/*
4820 * In a system that switches off the HZ timer nohz_cpu_mask
4821 * indicates which cpus entered this state. This is used
4822 * in the rcu update to wait only for active cpus. For system
4823 * which do not switch off the HZ timer nohz_cpu_mask should
4824 * always be CPU_MASK_NONE.
4825 */
4826cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4827
4828#ifdef CONFIG_SMP
4829/*
4830 * This is how migration works:
4831 *
70b97a7f 4832 * 1) we queue a struct migration_req structure in the source CPU's
1da177e4
LT
4833 * runqueue and wake up that CPU's migration thread.
4834 * 2) we down() the locked semaphore => thread blocks.
4835 * 3) migration thread wakes up (implicitly it forces the migrated
4836 * thread off the CPU)
4837 * 4) it gets the migration request and checks whether the migrated
4838 * task is still in the wrong runqueue.
4839 * 5) if it's in the wrong runqueue then the migration thread removes
4840 * it and puts it into the right queue.
4841 * 6) migration thread up()s the semaphore.
4842 * 7) we wake up and the migration is done.
4843 */
4844
4845/*
4846 * Change a given task's CPU affinity. Migrate the thread to a
4847 * proper CPU and schedule it away if the CPU it's executing on
4848 * is removed from the allowed bitmask.
4849 *
4850 * NOTE: the caller must have a valid reference to the task, the
4851 * task must not exit() & deallocate itself prematurely. The
4852 * call is not atomic; no spinlocks may be held.
4853 */
36c8b586 4854int set_cpus_allowed(struct task_struct *p, cpumask_t new_mask)
1da177e4 4855{
70b97a7f 4856 struct migration_req req;
1da177e4 4857 unsigned long flags;
70b97a7f 4858 struct rq *rq;
48f24c4d 4859 int ret = 0;
1da177e4
LT
4860
4861 rq = task_rq_lock(p, &flags);
4862 if (!cpus_intersects(new_mask, cpu_online_map)) {
4863 ret = -EINVAL;
4864 goto out;
4865 }
4866
4867 p->cpus_allowed = new_mask;
4868 /* Can the task run on the task's current CPU? If so, we're done */
4869 if (cpu_isset(task_cpu(p), new_mask))
4870 goto out;
4871
4872 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4873 /* Need help from migration thread: drop lock and wait. */
4874 task_rq_unlock(rq, &flags);
4875 wake_up_process(rq->migration_thread);
4876 wait_for_completion(&req.done);
4877 tlb_migrate_finish(p->mm);
4878 return 0;
4879 }
4880out:
4881 task_rq_unlock(rq, &flags);
48f24c4d 4882
1da177e4
LT
4883 return ret;
4884}
1da177e4
LT
4885EXPORT_SYMBOL_GPL(set_cpus_allowed);
4886
4887/*
4888 * Move (not current) task off this cpu, onto dest cpu. We're doing
4889 * this because either it can't run here any more (set_cpus_allowed()
4890 * away from this CPU, or CPU going down), or because we're
4891 * attempting to rebalance this task on exec (sched_exec).
4892 *
4893 * So we race with normal scheduler movements, but that's OK, as long
4894 * as the task is no longer on this CPU.
efc30814
KK
4895 *
4896 * Returns non-zero if task was successfully migrated.
1da177e4 4897 */
efc30814 4898static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
1da177e4 4899{
70b97a7f 4900 struct rq *rq_dest, *rq_src;
dd41f596 4901 int ret = 0, on_rq;
1da177e4
LT
4902
4903 if (unlikely(cpu_is_offline(dest_cpu)))
efc30814 4904 return ret;
1da177e4
LT
4905
4906 rq_src = cpu_rq(src_cpu);
4907 rq_dest = cpu_rq(dest_cpu);
4908
4909 double_rq_lock(rq_src, rq_dest);
4910 /* Already moved. */
4911 if (task_cpu(p) != src_cpu)
4912 goto out;
4913 /* Affinity changed (again). */
4914 if (!cpu_isset(dest_cpu, p->cpus_allowed))
4915 goto out;
4916
dd41f596 4917 on_rq = p->se.on_rq;
6e82a3be 4918 if (on_rq)
2e1cb74a 4919 deactivate_task(rq_src, p, 0);
6e82a3be 4920
1da177e4 4921 set_task_cpu(p, dest_cpu);
dd41f596
IM
4922 if (on_rq) {
4923 activate_task(rq_dest, p, 0);
4924 check_preempt_curr(rq_dest, p);
1da177e4 4925 }
efc30814 4926 ret = 1;
1da177e4
LT
4927out:
4928 double_rq_unlock(rq_src, rq_dest);
efc30814 4929 return ret;
1da177e4
LT
4930}
4931
4932/*
4933 * migration_thread - this is a highprio system thread that performs
4934 * thread migration by bumping thread off CPU then 'pushing' onto
4935 * another runqueue.
4936 */
95cdf3b7 4937static int migration_thread(void *data)
1da177e4 4938{
1da177e4 4939 int cpu = (long)data;
70b97a7f 4940 struct rq *rq;
1da177e4
LT
4941
4942 rq = cpu_rq(cpu);
4943 BUG_ON(rq->migration_thread != current);
4944
4945 set_current_state(TASK_INTERRUPTIBLE);
4946 while (!kthread_should_stop()) {
70b97a7f 4947 struct migration_req *req;
1da177e4 4948 struct list_head *head;
1da177e4 4949
1da177e4
LT
4950 spin_lock_irq(&rq->lock);
4951
4952 if (cpu_is_offline(cpu)) {
4953 spin_unlock_irq(&rq->lock);
4954 goto wait_to_die;
4955 }
4956
4957 if (rq->active_balance) {
4958 active_load_balance(rq, cpu);
4959 rq->active_balance = 0;
4960 }
4961
4962 head = &rq->migration_queue;
4963
4964 if (list_empty(head)) {
4965 spin_unlock_irq(&rq->lock);
4966 schedule();
4967 set_current_state(TASK_INTERRUPTIBLE);
4968 continue;
4969 }
70b97a7f 4970 req = list_entry(head->next, struct migration_req, list);
1da177e4
LT
4971 list_del_init(head->next);
4972
674311d5
NP
4973 spin_unlock(&rq->lock);
4974 __migrate_task(req->task, cpu, req->dest_cpu);
4975 local_irq_enable();
1da177e4
LT
4976
4977 complete(&req->done);
4978 }
4979 __set_current_state(TASK_RUNNING);
4980 return 0;
4981
4982wait_to_die:
4983 /* Wait for kthread_stop */
4984 set_current_state(TASK_INTERRUPTIBLE);
4985 while (!kthread_should_stop()) {
4986 schedule();
4987 set_current_state(TASK_INTERRUPTIBLE);
4988 }
4989 __set_current_state(TASK_RUNNING);
4990 return 0;
4991}
4992
4993#ifdef CONFIG_HOTPLUG_CPU
054b9108
KK
4994/*
4995 * Figure out where task on dead CPU should go, use force if neccessary.
4996 * NOTE: interrupts should be disabled by the caller
4997 */
48f24c4d 4998static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
1da177e4 4999{
efc30814 5000 unsigned long flags;
1da177e4 5001 cpumask_t mask;
70b97a7f
IM
5002 struct rq *rq;
5003 int dest_cpu;
1da177e4 5004
efc30814 5005restart:
1da177e4
LT
5006 /* On same node? */
5007 mask = node_to_cpumask(cpu_to_node(dead_cpu));
48f24c4d 5008 cpus_and(mask, mask, p->cpus_allowed);
1da177e4
LT
5009 dest_cpu = any_online_cpu(mask);
5010
5011 /* On any allowed CPU? */
5012 if (dest_cpu == NR_CPUS)
48f24c4d 5013 dest_cpu = any_online_cpu(p->cpus_allowed);
1da177e4
LT
5014
5015 /* No more Mr. Nice Guy. */
5016 if (dest_cpu == NR_CPUS) {
48f24c4d
IM
5017 rq = task_rq_lock(p, &flags);
5018 cpus_setall(p->cpus_allowed);
5019 dest_cpu = any_online_cpu(p->cpus_allowed);
efc30814 5020 task_rq_unlock(rq, &flags);
1da177e4
LT
5021
5022 /*
5023 * Don't tell them about moving exiting tasks or
5024 * kernel threads (both mm NULL), since they never
5025 * leave kernel.
5026 */
48f24c4d 5027 if (p->mm && printk_ratelimit())
1da177e4
LT
5028 printk(KERN_INFO "process %d (%s) no "
5029 "longer affine to cpu%d\n",
48f24c4d 5030 p->pid, p->comm, dead_cpu);
1da177e4 5031 }
48f24c4d 5032 if (!__migrate_task(p, dead_cpu, dest_cpu))
efc30814 5033 goto restart;
1da177e4
LT
5034}
5035
5036/*
5037 * While a dead CPU has no uninterruptible tasks queued at this point,
5038 * it might still have a nonzero ->nr_uninterruptible counter, because
5039 * for performance reasons the counter is not stricly tracking tasks to
5040 * their home CPUs. So we just add the counter to another CPU's counter,
5041 * to keep the global sum constant after CPU-down:
5042 */
70b97a7f 5043static void migrate_nr_uninterruptible(struct rq *rq_src)
1da177e4 5044{
70b97a7f 5045 struct rq *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
1da177e4
LT
5046 unsigned long flags;
5047
5048 local_irq_save(flags);
5049 double_rq_lock(rq_src, rq_dest);
5050 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5051 rq_src->nr_uninterruptible = 0;
5052 double_rq_unlock(rq_src, rq_dest);
5053 local_irq_restore(flags);
5054}
5055
5056/* Run through task list and migrate tasks from the dead cpu. */
5057static void migrate_live_tasks(int src_cpu)
5058{
48f24c4d 5059 struct task_struct *p, *t;
1da177e4
LT
5060
5061 write_lock_irq(&tasklist_lock);
5062
48f24c4d
IM
5063 do_each_thread(t, p) {
5064 if (p == current)
1da177e4
LT
5065 continue;
5066
48f24c4d
IM
5067 if (task_cpu(p) == src_cpu)
5068 move_task_off_dead_cpu(src_cpu, p);
5069 } while_each_thread(t, p);
1da177e4
LT
5070
5071 write_unlock_irq(&tasklist_lock);
5072}
5073
dd41f596
IM
5074/*
5075 * Schedules idle task to be the next runnable task on current CPU.
1da177e4 5076 * It does so by boosting its priority to highest possible and adding it to
48f24c4d 5077 * the _front_ of the runqueue. Used by CPU offline code.
1da177e4
LT
5078 */
5079void sched_idle_next(void)
5080{
48f24c4d 5081 int this_cpu = smp_processor_id();
70b97a7f 5082 struct rq *rq = cpu_rq(this_cpu);
1da177e4
LT
5083 struct task_struct *p = rq->idle;
5084 unsigned long flags;
5085
5086 /* cpu has to be offline */
48f24c4d 5087 BUG_ON(cpu_online(this_cpu));
1da177e4 5088
48f24c4d
IM
5089 /*
5090 * Strictly not necessary since rest of the CPUs are stopped by now
5091 * and interrupts disabled on the current cpu.
1da177e4
LT
5092 */
5093 spin_lock_irqsave(&rq->lock, flags);
5094
dd41f596 5095 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
48f24c4d
IM
5096
5097 /* Add idle task to the _front_ of its priority queue: */
dd41f596 5098 activate_idle_task(p, rq);
1da177e4
LT
5099
5100 spin_unlock_irqrestore(&rq->lock, flags);
5101}
5102
48f24c4d
IM
5103/*
5104 * Ensures that the idle task is using init_mm right before its cpu goes
1da177e4
LT
5105 * offline.
5106 */
5107void idle_task_exit(void)
5108{
5109 struct mm_struct *mm = current->active_mm;
5110
5111 BUG_ON(cpu_online(smp_processor_id()));
5112
5113 if (mm != &init_mm)
5114 switch_mm(mm, &init_mm, current);
5115 mmdrop(mm);
5116}
5117
054b9108 5118/* called under rq->lock with disabled interrupts */
36c8b586 5119static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
1da177e4 5120{
70b97a7f 5121 struct rq *rq = cpu_rq(dead_cpu);
1da177e4
LT
5122
5123 /* Must be exiting, otherwise would be on tasklist. */
48f24c4d 5124 BUG_ON(p->exit_state != EXIT_ZOMBIE && p->exit_state != EXIT_DEAD);
1da177e4
LT
5125
5126 /* Cannot have done final schedule yet: would have vanished. */
c394cc9f 5127 BUG_ON(p->state == TASK_DEAD);
1da177e4 5128
48f24c4d 5129 get_task_struct(p);
1da177e4
LT
5130
5131 /*
5132 * Drop lock around migration; if someone else moves it,
5133 * that's OK. No task can be added to this CPU, so iteration is
5134 * fine.
054b9108 5135 * NOTE: interrupts should be left disabled --dev@
1da177e4 5136 */
054b9108 5137 spin_unlock(&rq->lock);
48f24c4d 5138 move_task_off_dead_cpu(dead_cpu, p);
054b9108 5139 spin_lock(&rq->lock);
1da177e4 5140
48f24c4d 5141 put_task_struct(p);
1da177e4
LT
5142}
5143
5144/* release_task() removes task from tasklist, so we won't find dead tasks. */
5145static void migrate_dead_tasks(unsigned int dead_cpu)
5146{
70b97a7f 5147 struct rq *rq = cpu_rq(dead_cpu);
dd41f596 5148 struct task_struct *next;
48f24c4d 5149
dd41f596
IM
5150 for ( ; ; ) {
5151 if (!rq->nr_running)
5152 break;
a8e504d2 5153 update_rq_clock(rq);
ff95f3df 5154 next = pick_next_task(rq, rq->curr);
dd41f596
IM
5155 if (!next)
5156 break;
5157 migrate_dead(dead_cpu, next);
e692ab53 5158
1da177e4
LT
5159 }
5160}
5161#endif /* CONFIG_HOTPLUG_CPU */
5162
e692ab53
NP
5163#if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5164
5165static struct ctl_table sd_ctl_dir[] = {
e0361851
AD
5166 {
5167 .procname = "sched_domain",
c57baf1e 5168 .mode = 0555,
e0361851 5169 },
e692ab53
NP
5170 {0,},
5171};
5172
5173static struct ctl_table sd_ctl_root[] = {
e0361851 5174 {
c57baf1e 5175 .ctl_name = CTL_KERN,
e0361851 5176 .procname = "kernel",
c57baf1e 5177 .mode = 0555,
e0361851
AD
5178 .child = sd_ctl_dir,
5179 },
e692ab53
NP
5180 {0,},
5181};
5182
5183static struct ctl_table *sd_alloc_ctl_entry(int n)
5184{
5185 struct ctl_table *entry =
5186 kmalloc(n * sizeof(struct ctl_table), GFP_KERNEL);
5187
5188 BUG_ON(!entry);
5189 memset(entry, 0, n * sizeof(struct ctl_table));
5190
5191 return entry;
5192}
5193
5194static void
e0361851 5195set_table_entry(struct ctl_table *entry,
e692ab53
NP
5196 const char *procname, void *data, int maxlen,
5197 mode_t mode, proc_handler *proc_handler)
5198{
e692ab53
NP
5199 entry->procname = procname;
5200 entry->data = data;
5201 entry->maxlen = maxlen;
5202 entry->mode = mode;
5203 entry->proc_handler = proc_handler;
5204}
5205
5206static struct ctl_table *
5207sd_alloc_ctl_domain_table(struct sched_domain *sd)
5208{
5209 struct ctl_table *table = sd_alloc_ctl_entry(14);
5210
e0361851 5211 set_table_entry(&table[0], "min_interval", &sd->min_interval,
e692ab53 5212 sizeof(long), 0644, proc_doulongvec_minmax);
e0361851 5213 set_table_entry(&table[1], "max_interval", &sd->max_interval,
e692ab53 5214 sizeof(long), 0644, proc_doulongvec_minmax);
e0361851 5215 set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
e692ab53 5216 sizeof(int), 0644, proc_dointvec_minmax);
e0361851 5217 set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
e692ab53 5218 sizeof(int), 0644, proc_dointvec_minmax);
e0361851 5219 set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
e692ab53 5220 sizeof(int), 0644, proc_dointvec_minmax);
e0361851 5221 set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
e692ab53 5222 sizeof(int), 0644, proc_dointvec_minmax);
e0361851 5223 set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
e692ab53 5224 sizeof(int), 0644, proc_dointvec_minmax);
e0361851 5225 set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
e692ab53 5226 sizeof(int), 0644, proc_dointvec_minmax);
e0361851 5227 set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
e692ab53 5228 sizeof(int), 0644, proc_dointvec_minmax);
e0361851 5229 set_table_entry(&table[10], "cache_nice_tries",
e692ab53
NP
5230 &sd->cache_nice_tries,
5231 sizeof(int), 0644, proc_dointvec_minmax);
e0361851 5232 set_table_entry(&table[12], "flags", &sd->flags,
e692ab53
NP
5233 sizeof(int), 0644, proc_dointvec_minmax);
5234
5235 return table;
5236}
5237
5238static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
5239{
5240 struct ctl_table *entry, *table;
5241 struct sched_domain *sd;
5242 int domain_num = 0, i;
5243 char buf[32];
5244
5245 for_each_domain(cpu, sd)
5246 domain_num++;
5247 entry = table = sd_alloc_ctl_entry(domain_num + 1);
5248
5249 i = 0;
5250 for_each_domain(cpu, sd) {
5251 snprintf(buf, 32, "domain%d", i);
e692ab53 5252 entry->procname = kstrdup(buf, GFP_KERNEL);
c57baf1e 5253 entry->mode = 0555;
e692ab53
NP
5254 entry->child = sd_alloc_ctl_domain_table(sd);
5255 entry++;
5256 i++;
5257 }
5258 return table;
5259}
5260
5261static struct ctl_table_header *sd_sysctl_header;
5262static void init_sched_domain_sysctl(void)
5263{
5264 int i, cpu_num = num_online_cpus();
5265 struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5266 char buf[32];
5267
5268 sd_ctl_dir[0].child = entry;
5269
5270 for (i = 0; i < cpu_num; i++, entry++) {
5271 snprintf(buf, 32, "cpu%d", i);
e692ab53 5272 entry->procname = kstrdup(buf, GFP_KERNEL);
c57baf1e 5273 entry->mode = 0555;
e692ab53
NP
5274 entry->child = sd_alloc_ctl_cpu_table(i);
5275 }
5276 sd_sysctl_header = register_sysctl_table(sd_ctl_root);
5277}
5278#else
5279static void init_sched_domain_sysctl(void)
5280{
5281}
5282#endif
5283
1da177e4
LT
5284/*
5285 * migration_call - callback that gets triggered when a CPU is added.
5286 * Here we can start up the necessary migration thread for the new CPU.
5287 */
48f24c4d
IM
5288static int __cpuinit
5289migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
1da177e4 5290{
1da177e4 5291 struct task_struct *p;
48f24c4d 5292 int cpu = (long)hcpu;
1da177e4 5293 unsigned long flags;
70b97a7f 5294 struct rq *rq;
1da177e4
LT
5295
5296 switch (action) {
5be9361c
GS
5297 case CPU_LOCK_ACQUIRE:
5298 mutex_lock(&sched_hotcpu_mutex);
5299 break;
5300
1da177e4 5301 case CPU_UP_PREPARE:
8bb78442 5302 case CPU_UP_PREPARE_FROZEN:
dd41f596 5303 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
1da177e4
LT
5304 if (IS_ERR(p))
5305 return NOTIFY_BAD;
1da177e4
LT
5306 kthread_bind(p, cpu);
5307 /* Must be high prio: stop_machine expects to yield to it. */
5308 rq = task_rq_lock(p, &flags);
dd41f596 5309 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
1da177e4
LT
5310 task_rq_unlock(rq, &flags);
5311 cpu_rq(cpu)->migration_thread = p;
5312 break;
48f24c4d 5313
1da177e4 5314 case CPU_ONLINE:
8bb78442 5315 case CPU_ONLINE_FROZEN:
1da177e4
LT
5316 /* Strictly unneccessary, as first user will wake it. */
5317 wake_up_process(cpu_rq(cpu)->migration_thread);
5318 break;
48f24c4d 5319
1da177e4
LT
5320#ifdef CONFIG_HOTPLUG_CPU
5321 case CPU_UP_CANCELED:
8bb78442 5322 case CPU_UP_CANCELED_FROZEN:
fc75cdfa
HC
5323 if (!cpu_rq(cpu)->migration_thread)
5324 break;
1da177e4 5325 /* Unbind it from offline cpu so it can run. Fall thru. */
a4c4af7c
HC
5326 kthread_bind(cpu_rq(cpu)->migration_thread,
5327 any_online_cpu(cpu_online_map));
1da177e4
LT
5328 kthread_stop(cpu_rq(cpu)->migration_thread);
5329 cpu_rq(cpu)->migration_thread = NULL;
5330 break;
48f24c4d 5331
1da177e4 5332 case CPU_DEAD:
8bb78442 5333 case CPU_DEAD_FROZEN:
1da177e4
LT
5334 migrate_live_tasks(cpu);
5335 rq = cpu_rq(cpu);
5336 kthread_stop(rq->migration_thread);
5337 rq->migration_thread = NULL;
5338 /* Idle task back to normal (off runqueue, low prio) */
5339 rq = task_rq_lock(rq->idle, &flags);
a8e504d2 5340 update_rq_clock(rq);
2e1cb74a 5341 deactivate_task(rq, rq->idle, 0);
1da177e4 5342 rq->idle->static_prio = MAX_PRIO;
dd41f596
IM
5343 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
5344 rq->idle->sched_class = &idle_sched_class;
1da177e4
LT
5345 migrate_dead_tasks(cpu);
5346 task_rq_unlock(rq, &flags);
5347 migrate_nr_uninterruptible(rq);
5348 BUG_ON(rq->nr_running != 0);
5349
5350 /* No need to migrate the tasks: it was best-effort if
5be9361c 5351 * they didn't take sched_hotcpu_mutex. Just wake up
1da177e4
LT
5352 * the requestors. */
5353 spin_lock_irq(&rq->lock);
5354 while (!list_empty(&rq->migration_queue)) {
70b97a7f
IM
5355 struct migration_req *req;
5356
1da177e4 5357 req = list_entry(rq->migration_queue.next,
70b97a7f 5358 struct migration_req, list);
1da177e4
LT
5359 list_del_init(&req->list);
5360 complete(&req->done);
5361 }
5362 spin_unlock_irq(&rq->lock);
5363 break;
5364#endif
5be9361c
GS
5365 case CPU_LOCK_RELEASE:
5366 mutex_unlock(&sched_hotcpu_mutex);
5367 break;
1da177e4
LT
5368 }
5369 return NOTIFY_OK;
5370}
5371
5372/* Register at highest priority so that task migration (migrate_all_tasks)
5373 * happens before everything else.
5374 */
26c2143b 5375static struct notifier_block __cpuinitdata migration_notifier = {
1da177e4
LT
5376 .notifier_call = migration_call,
5377 .priority = 10
5378};
5379
5380int __init migration_init(void)
5381{
5382 void *cpu = (void *)(long)smp_processor_id();
07dccf33 5383 int err;
48f24c4d
IM
5384
5385 /* Start one for the boot CPU: */
07dccf33
AM
5386 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5387 BUG_ON(err == NOTIFY_BAD);
1da177e4
LT
5388 migration_call(&migration_notifier, CPU_ONLINE, cpu);
5389 register_cpu_notifier(&migration_notifier);
48f24c4d 5390
1da177e4
LT
5391 return 0;
5392}
5393#endif
5394
5395#ifdef CONFIG_SMP
476f3534
CL
5396
5397/* Number of possible processor ids */
5398int nr_cpu_ids __read_mostly = NR_CPUS;
5399EXPORT_SYMBOL(nr_cpu_ids);
5400
1a20ff27 5401#undef SCHED_DOMAIN_DEBUG
1da177e4
LT
5402#ifdef SCHED_DOMAIN_DEBUG
5403static void sched_domain_debug(struct sched_domain *sd, int cpu)
5404{
5405 int level = 0;
5406
41c7ce9a
NP
5407 if (!sd) {
5408 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5409 return;
5410 }
5411
1da177e4
LT
5412 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5413
5414 do {
5415 int i;
5416 char str[NR_CPUS];
5417 struct sched_group *group = sd->groups;
5418 cpumask_t groupmask;
5419
5420 cpumask_scnprintf(str, NR_CPUS, sd->span);
5421 cpus_clear(groupmask);
5422
5423 printk(KERN_DEBUG);
5424 for (i = 0; i < level + 1; i++)
5425 printk(" ");
5426 printk("domain %d: ", level);
5427
5428 if (!(sd->flags & SD_LOAD_BALANCE)) {
5429 printk("does not load-balance\n");
5430 if (sd->parent)
33859f7f
MOS
5431 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
5432 " has parent");
1da177e4
LT
5433 break;
5434 }
5435
5436 printk("span %s\n", str);
5437
5438 if (!cpu_isset(cpu, sd->span))
33859f7f
MOS
5439 printk(KERN_ERR "ERROR: domain->span does not contain "
5440 "CPU%d\n", cpu);
1da177e4 5441 if (!cpu_isset(cpu, group->cpumask))
33859f7f
MOS
5442 printk(KERN_ERR "ERROR: domain->groups does not contain"
5443 " CPU%d\n", cpu);
1da177e4
LT
5444
5445 printk(KERN_DEBUG);
5446 for (i = 0; i < level + 2; i++)
5447 printk(" ");
5448 printk("groups:");
5449 do {
5450 if (!group) {
5451 printk("\n");
5452 printk(KERN_ERR "ERROR: group is NULL\n");
5453 break;
5454 }
5455
5517d86b 5456 if (!group->__cpu_power) {
1da177e4 5457 printk("\n");
33859f7f
MOS
5458 printk(KERN_ERR "ERROR: domain->cpu_power not "
5459 "set\n");
1da177e4
LT
5460 }
5461
5462 if (!cpus_weight(group->cpumask)) {
5463 printk("\n");
5464 printk(KERN_ERR "ERROR: empty group\n");
5465 }
5466
5467 if (cpus_intersects(groupmask, group->cpumask)) {
5468 printk("\n");
5469 printk(KERN_ERR "ERROR: repeated CPUs\n");
5470 }
5471
5472 cpus_or(groupmask, groupmask, group->cpumask);
5473
5474 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
5475 printk(" %s", str);
5476
5477 group = group->next;
5478 } while (group != sd->groups);
5479 printk("\n");
5480
5481 if (!cpus_equal(sd->span, groupmask))
33859f7f
MOS
5482 printk(KERN_ERR "ERROR: groups don't span "
5483 "domain->span\n");
1da177e4
LT
5484
5485 level++;
5486 sd = sd->parent;
33859f7f
MOS
5487 if (!sd)
5488 continue;
1da177e4 5489
33859f7f
MOS
5490 if (!cpus_subset(groupmask, sd->span))
5491 printk(KERN_ERR "ERROR: parent span is not a superset "
5492 "of domain->span\n");
1da177e4
LT
5493
5494 } while (sd);
5495}
5496#else
48f24c4d 5497# define sched_domain_debug(sd, cpu) do { } while (0)
1da177e4
LT
5498#endif
5499
1a20ff27 5500static int sd_degenerate(struct sched_domain *sd)
245af2c7
SS
5501{
5502 if (cpus_weight(sd->span) == 1)
5503 return 1;
5504
5505 /* Following flags need at least 2 groups */
5506 if (sd->flags & (SD_LOAD_BALANCE |
5507 SD_BALANCE_NEWIDLE |
5508 SD_BALANCE_FORK |
89c4710e
SS
5509 SD_BALANCE_EXEC |
5510 SD_SHARE_CPUPOWER |
5511 SD_SHARE_PKG_RESOURCES)) {
245af2c7
SS
5512 if (sd->groups != sd->groups->next)
5513 return 0;
5514 }
5515
5516 /* Following flags don't use groups */
5517 if (sd->flags & (SD_WAKE_IDLE |
5518 SD_WAKE_AFFINE |
5519 SD_WAKE_BALANCE))
5520 return 0;
5521
5522 return 1;
5523}
5524
48f24c4d
IM
5525static int
5526sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
245af2c7
SS
5527{
5528 unsigned long cflags = sd->flags, pflags = parent->flags;
5529
5530 if (sd_degenerate(parent))
5531 return 1;
5532
5533 if (!cpus_equal(sd->span, parent->span))
5534 return 0;
5535
5536 /* Does parent contain flags not in child? */
5537 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
5538 if (cflags & SD_WAKE_AFFINE)
5539 pflags &= ~SD_WAKE_BALANCE;
5540 /* Flags needing groups don't count if only 1 group in parent */
5541 if (parent->groups == parent->groups->next) {
5542 pflags &= ~(SD_LOAD_BALANCE |
5543 SD_BALANCE_NEWIDLE |
5544 SD_BALANCE_FORK |
89c4710e
SS
5545 SD_BALANCE_EXEC |
5546 SD_SHARE_CPUPOWER |
5547 SD_SHARE_PKG_RESOURCES);
245af2c7
SS
5548 }
5549 if (~cflags & pflags)
5550 return 0;
5551
5552 return 1;
5553}
5554
1da177e4
LT
5555/*
5556 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
5557 * hold the hotplug lock.
5558 */
9c1cfda2 5559static void cpu_attach_domain(struct sched_domain *sd, int cpu)
1da177e4 5560{
70b97a7f 5561 struct rq *rq = cpu_rq(cpu);
245af2c7
SS
5562 struct sched_domain *tmp;
5563
5564 /* Remove the sched domains which do not contribute to scheduling. */
5565 for (tmp = sd; tmp; tmp = tmp->parent) {
5566 struct sched_domain *parent = tmp->parent;
5567 if (!parent)
5568 break;
1a848870 5569 if (sd_parent_degenerate(tmp, parent)) {
245af2c7 5570 tmp->parent = parent->parent;
1a848870
SS
5571 if (parent->parent)
5572 parent->parent->child = tmp;
5573 }
245af2c7
SS
5574 }
5575
1a848870 5576 if (sd && sd_degenerate(sd)) {
245af2c7 5577 sd = sd->parent;
1a848870
SS
5578 if (sd)
5579 sd->child = NULL;
5580 }
1da177e4
LT
5581
5582 sched_domain_debug(sd, cpu);
5583
674311d5 5584 rcu_assign_pointer(rq->sd, sd);
1da177e4
LT
5585}
5586
5587/* cpus with isolated domains */
67af63a6 5588static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
1da177e4
LT
5589
5590/* Setup the mask of cpus configured for isolated domains */
5591static int __init isolated_cpu_setup(char *str)
5592{
5593 int ints[NR_CPUS], i;
5594
5595 str = get_options(str, ARRAY_SIZE(ints), ints);
5596 cpus_clear(cpu_isolated_map);
5597 for (i = 1; i <= ints[0]; i++)
5598 if (ints[i] < NR_CPUS)
5599 cpu_set(ints[i], cpu_isolated_map);
5600 return 1;
5601}
5602
5603__setup ("isolcpus=", isolated_cpu_setup);
5604
5605/*
6711cab4
SS
5606 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
5607 * to a function which identifies what group(along with sched group) a CPU
5608 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
5609 * (due to the fact that we keep track of groups covered with a cpumask_t).
1da177e4
LT
5610 *
5611 * init_sched_build_groups will build a circular linked list of the groups
5612 * covered by the given span, and will set each group's ->cpumask correctly,
5613 * and ->cpu_power to 0.
5614 */
a616058b 5615static void
6711cab4
SS
5616init_sched_build_groups(cpumask_t span, const cpumask_t *cpu_map,
5617 int (*group_fn)(int cpu, const cpumask_t *cpu_map,
5618 struct sched_group **sg))
1da177e4
LT
5619{
5620 struct sched_group *first = NULL, *last = NULL;
5621 cpumask_t covered = CPU_MASK_NONE;
5622 int i;
5623
5624 for_each_cpu_mask(i, span) {
6711cab4
SS
5625 struct sched_group *sg;
5626 int group = group_fn(i, cpu_map, &sg);
1da177e4
LT
5627 int j;
5628
5629 if (cpu_isset(i, covered))
5630 continue;
5631
5632 sg->cpumask = CPU_MASK_NONE;
5517d86b 5633 sg->__cpu_power = 0;
1da177e4
LT
5634
5635 for_each_cpu_mask(j, span) {
6711cab4 5636 if (group_fn(j, cpu_map, NULL) != group)
1da177e4
LT
5637 continue;
5638
5639 cpu_set(j, covered);
5640 cpu_set(j, sg->cpumask);
5641 }
5642 if (!first)
5643 first = sg;
5644 if (last)
5645 last->next = sg;
5646 last = sg;
5647 }
5648 last->next = first;
5649}
5650
9c1cfda2 5651#define SD_NODES_PER_DOMAIN 16
1da177e4 5652
9c1cfda2 5653#ifdef CONFIG_NUMA
198e2f18 5654
9c1cfda2
JH
5655/**
5656 * find_next_best_node - find the next node to include in a sched_domain
5657 * @node: node whose sched_domain we're building
5658 * @used_nodes: nodes already in the sched_domain
5659 *
5660 * Find the next node to include in a given scheduling domain. Simply
5661 * finds the closest node not already in the @used_nodes map.
5662 *
5663 * Should use nodemask_t.
5664 */
5665static int find_next_best_node(int node, unsigned long *used_nodes)
5666{
5667 int i, n, val, min_val, best_node = 0;
5668
5669 min_val = INT_MAX;
5670
5671 for (i = 0; i < MAX_NUMNODES; i++) {
5672 /* Start at @node */
5673 n = (node + i) % MAX_NUMNODES;
5674
5675 if (!nr_cpus_node(n))
5676 continue;
5677
5678 /* Skip already used nodes */
5679 if (test_bit(n, used_nodes))
5680 continue;
5681
5682 /* Simple min distance search */
5683 val = node_distance(node, n);
5684
5685 if (val < min_val) {
5686 min_val = val;
5687 best_node = n;
5688 }
5689 }
5690
5691 set_bit(best_node, used_nodes);
5692 return best_node;
5693}
5694
5695/**
5696 * sched_domain_node_span - get a cpumask for a node's sched_domain
5697 * @node: node whose cpumask we're constructing
5698 * @size: number of nodes to include in this span
5699 *
5700 * Given a node, construct a good cpumask for its sched_domain to span. It
5701 * should be one that prevents unnecessary balancing, but also spreads tasks
5702 * out optimally.
5703 */
5704static cpumask_t sched_domain_node_span(int node)
5705{
9c1cfda2 5706 DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
48f24c4d
IM
5707 cpumask_t span, nodemask;
5708 int i;
9c1cfda2
JH
5709
5710 cpus_clear(span);
5711 bitmap_zero(used_nodes, MAX_NUMNODES);
5712
5713 nodemask = node_to_cpumask(node);
5714 cpus_or(span, span, nodemask);
5715 set_bit(node, used_nodes);
5716
5717 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
5718 int next_node = find_next_best_node(node, used_nodes);
48f24c4d 5719
9c1cfda2
JH
5720 nodemask = node_to_cpumask(next_node);
5721 cpus_or(span, span, nodemask);
5722 }
5723
5724 return span;
5725}
5726#endif
5727
5c45bf27 5728int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
48f24c4d 5729
9c1cfda2 5730/*
48f24c4d 5731 * SMT sched-domains:
9c1cfda2 5732 */
1da177e4
LT
5733#ifdef CONFIG_SCHED_SMT
5734static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
6711cab4 5735static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
48f24c4d 5736
6711cab4
SS
5737static int cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map,
5738 struct sched_group **sg)
1da177e4 5739{
6711cab4
SS
5740 if (sg)
5741 *sg = &per_cpu(sched_group_cpus, cpu);
1da177e4
LT
5742 return cpu;
5743}
5744#endif
5745
48f24c4d
IM
5746/*
5747 * multi-core sched-domains:
5748 */
1e9f28fa
SS
5749#ifdef CONFIG_SCHED_MC
5750static DEFINE_PER_CPU(struct sched_domain, core_domains);
6711cab4 5751static DEFINE_PER_CPU(struct sched_group, sched_group_core);
1e9f28fa
SS
5752#endif
5753
5754#if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6711cab4
SS
5755static int cpu_to_core_group(int cpu, const cpumask_t *cpu_map,
5756 struct sched_group **sg)
1e9f28fa 5757{
6711cab4 5758 int group;
a616058b
SS
5759 cpumask_t mask = cpu_sibling_map[cpu];
5760 cpus_and(mask, mask, *cpu_map);
6711cab4
SS
5761 group = first_cpu(mask);
5762 if (sg)
5763 *sg = &per_cpu(sched_group_core, group);
5764 return group;
1e9f28fa
SS
5765}
5766#elif defined(CONFIG_SCHED_MC)
6711cab4
SS
5767static int cpu_to_core_group(int cpu, const cpumask_t *cpu_map,
5768 struct sched_group **sg)
1e9f28fa 5769{
6711cab4
SS
5770 if (sg)
5771 *sg = &per_cpu(sched_group_core, cpu);
1e9f28fa
SS
5772 return cpu;
5773}
5774#endif
5775
1da177e4 5776static DEFINE_PER_CPU(struct sched_domain, phys_domains);
6711cab4 5777static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
48f24c4d 5778
6711cab4
SS
5779static int cpu_to_phys_group(int cpu, const cpumask_t *cpu_map,
5780 struct sched_group **sg)
1da177e4 5781{
6711cab4 5782 int group;
48f24c4d 5783#ifdef CONFIG_SCHED_MC
1e9f28fa 5784 cpumask_t mask = cpu_coregroup_map(cpu);
a616058b 5785 cpus_and(mask, mask, *cpu_map);
6711cab4 5786 group = first_cpu(mask);
1e9f28fa 5787#elif defined(CONFIG_SCHED_SMT)
a616058b
SS
5788 cpumask_t mask = cpu_sibling_map[cpu];
5789 cpus_and(mask, mask, *cpu_map);
6711cab4 5790 group = first_cpu(mask);
1da177e4 5791#else
6711cab4 5792 group = cpu;
1da177e4 5793#endif
6711cab4
SS
5794 if (sg)
5795 *sg = &per_cpu(sched_group_phys, group);
5796 return group;
1da177e4
LT
5797}
5798
5799#ifdef CONFIG_NUMA
1da177e4 5800/*
9c1cfda2
JH
5801 * The init_sched_build_groups can't handle what we want to do with node
5802 * groups, so roll our own. Now each node has its own list of groups which
5803 * gets dynamically allocated.
1da177e4 5804 */
9c1cfda2 5805static DEFINE_PER_CPU(struct sched_domain, node_domains);
d1b55138 5806static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
1da177e4 5807
9c1cfda2 5808static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
6711cab4 5809static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
9c1cfda2 5810
6711cab4
SS
5811static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
5812 struct sched_group **sg)
9c1cfda2 5813{
6711cab4
SS
5814 cpumask_t nodemask = node_to_cpumask(cpu_to_node(cpu));
5815 int group;
5816
5817 cpus_and(nodemask, nodemask, *cpu_map);
5818 group = first_cpu(nodemask);
5819
5820 if (sg)
5821 *sg = &per_cpu(sched_group_allnodes, group);
5822 return group;
1da177e4 5823}
6711cab4 5824
08069033
SS
5825static void init_numa_sched_groups_power(struct sched_group *group_head)
5826{
5827 struct sched_group *sg = group_head;
5828 int j;
5829
5830 if (!sg)
5831 return;
5832next_sg:
5833 for_each_cpu_mask(j, sg->cpumask) {
5834 struct sched_domain *sd;
5835
5836 sd = &per_cpu(phys_domains, j);
5837 if (j != first_cpu(sd->groups->cpumask)) {
5838 /*
5839 * Only add "power" once for each
5840 * physical package.
5841 */
5842 continue;
5843 }
5844
5517d86b 5845 sg_inc_cpu_power(sg, sd->groups->__cpu_power);
08069033
SS
5846 }
5847 sg = sg->next;
5848 if (sg != group_head)
5849 goto next_sg;
5850}
1da177e4
LT
5851#endif
5852
a616058b 5853#ifdef CONFIG_NUMA
51888ca2
SV
5854/* Free memory allocated for various sched_group structures */
5855static void free_sched_groups(const cpumask_t *cpu_map)
5856{
a616058b 5857 int cpu, i;
51888ca2
SV
5858
5859 for_each_cpu_mask(cpu, *cpu_map) {
51888ca2
SV
5860 struct sched_group **sched_group_nodes
5861 = sched_group_nodes_bycpu[cpu];
5862
51888ca2
SV
5863 if (!sched_group_nodes)
5864 continue;
5865
5866 for (i = 0; i < MAX_NUMNODES; i++) {
5867 cpumask_t nodemask = node_to_cpumask(i);
5868 struct sched_group *oldsg, *sg = sched_group_nodes[i];
5869
5870 cpus_and(nodemask, nodemask, *cpu_map);
5871 if (cpus_empty(nodemask))
5872 continue;
5873
5874 if (sg == NULL)
5875 continue;
5876 sg = sg->next;
5877next_sg:
5878 oldsg = sg;
5879 sg = sg->next;
5880 kfree(oldsg);
5881 if (oldsg != sched_group_nodes[i])
5882 goto next_sg;
5883 }
5884 kfree(sched_group_nodes);
5885 sched_group_nodes_bycpu[cpu] = NULL;
5886 }
51888ca2 5887}
a616058b
SS
5888#else
5889static void free_sched_groups(const cpumask_t *cpu_map)
5890{
5891}
5892#endif
51888ca2 5893
89c4710e
SS
5894/*
5895 * Initialize sched groups cpu_power.
5896 *
5897 * cpu_power indicates the capacity of sched group, which is used while
5898 * distributing the load between different sched groups in a sched domain.
5899 * Typically cpu_power for all the groups in a sched domain will be same unless
5900 * there are asymmetries in the topology. If there are asymmetries, group
5901 * having more cpu_power will pickup more load compared to the group having
5902 * less cpu_power.
5903 *
5904 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
5905 * the maximum number of tasks a group can handle in the presence of other idle
5906 * or lightly loaded groups in the same sched domain.
5907 */
5908static void init_sched_groups_power(int cpu, struct sched_domain *sd)
5909{
5910 struct sched_domain *child;
5911 struct sched_group *group;
5912
5913 WARN_ON(!sd || !sd->groups);
5914
5915 if (cpu != first_cpu(sd->groups->cpumask))
5916 return;
5917
5918 child = sd->child;
5919
5517d86b
ED
5920 sd->groups->__cpu_power = 0;
5921
89c4710e
SS
5922 /*
5923 * For perf policy, if the groups in child domain share resources
5924 * (for example cores sharing some portions of the cache hierarchy
5925 * or SMT), then set this domain groups cpu_power such that each group
5926 * can handle only one task, when there are other idle groups in the
5927 * same sched domain.
5928 */
5929 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
5930 (child->flags &
5931 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
5517d86b 5932 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
89c4710e
SS
5933 return;
5934 }
5935
89c4710e
SS
5936 /*
5937 * add cpu_power of each child group to this groups cpu_power
5938 */
5939 group = child->groups;
5940 do {
5517d86b 5941 sg_inc_cpu_power(sd->groups, group->__cpu_power);
89c4710e
SS
5942 group = group->next;
5943 } while (group != child->groups);
5944}
5945
1da177e4 5946/*
1a20ff27
DG
5947 * Build sched domains for a given set of cpus and attach the sched domains
5948 * to the individual cpus
1da177e4 5949 */
51888ca2 5950static int build_sched_domains(const cpumask_t *cpu_map)
1da177e4
LT
5951{
5952 int i;
d1b55138
JH
5953#ifdef CONFIG_NUMA
5954 struct sched_group **sched_group_nodes = NULL;
6711cab4 5955 int sd_allnodes = 0;
d1b55138
JH
5956
5957 /*
5958 * Allocate the per-node list of sched groups
5959 */
dd41f596 5960 sched_group_nodes = kzalloc(sizeof(struct sched_group *)*MAX_NUMNODES,
d3a5aa98 5961 GFP_KERNEL);
d1b55138
JH
5962 if (!sched_group_nodes) {
5963 printk(KERN_WARNING "Can not alloc sched group node list\n");
51888ca2 5964 return -ENOMEM;
d1b55138
JH
5965 }
5966 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
5967#endif
1da177e4
LT
5968
5969 /*
1a20ff27 5970 * Set up domains for cpus specified by the cpu_map.
1da177e4 5971 */
1a20ff27 5972 for_each_cpu_mask(i, *cpu_map) {
1da177e4
LT
5973 struct sched_domain *sd = NULL, *p;
5974 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
5975
1a20ff27 5976 cpus_and(nodemask, nodemask, *cpu_map);
1da177e4
LT
5977
5978#ifdef CONFIG_NUMA
dd41f596
IM
5979 if (cpus_weight(*cpu_map) >
5980 SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
9c1cfda2
JH
5981 sd = &per_cpu(allnodes_domains, i);
5982 *sd = SD_ALLNODES_INIT;
5983 sd->span = *cpu_map;
6711cab4 5984 cpu_to_allnodes_group(i, cpu_map, &sd->groups);
9c1cfda2 5985 p = sd;
6711cab4 5986 sd_allnodes = 1;
9c1cfda2
JH
5987 } else
5988 p = NULL;
5989
1da177e4 5990 sd = &per_cpu(node_domains, i);
1da177e4 5991 *sd = SD_NODE_INIT;
9c1cfda2
JH
5992 sd->span = sched_domain_node_span(cpu_to_node(i));
5993 sd->parent = p;
1a848870
SS
5994 if (p)
5995 p->child = sd;
9c1cfda2 5996 cpus_and(sd->span, sd->span, *cpu_map);
1da177e4
LT
5997#endif
5998
5999 p = sd;
6000 sd = &per_cpu(phys_domains, i);
1da177e4
LT
6001 *sd = SD_CPU_INIT;
6002 sd->span = nodemask;
6003 sd->parent = p;
1a848870
SS
6004 if (p)
6005 p->child = sd;
6711cab4 6006 cpu_to_phys_group(i, cpu_map, &sd->groups);
1da177e4 6007
1e9f28fa
SS
6008#ifdef CONFIG_SCHED_MC
6009 p = sd;
6010 sd = &per_cpu(core_domains, i);
1e9f28fa
SS
6011 *sd = SD_MC_INIT;
6012 sd->span = cpu_coregroup_map(i);
6013 cpus_and(sd->span, sd->span, *cpu_map);
6014 sd->parent = p;
1a848870 6015 p->child = sd;
6711cab4 6016 cpu_to_core_group(i, cpu_map, &sd->groups);
1e9f28fa
SS
6017#endif
6018
1da177e4
LT
6019#ifdef CONFIG_SCHED_SMT
6020 p = sd;
6021 sd = &per_cpu(cpu_domains, i);
1da177e4
LT
6022 *sd = SD_SIBLING_INIT;
6023 sd->span = cpu_sibling_map[i];
1a20ff27 6024 cpus_and(sd->span, sd->span, *cpu_map);
1da177e4 6025 sd->parent = p;
1a848870 6026 p->child = sd;
6711cab4 6027 cpu_to_cpu_group(i, cpu_map, &sd->groups);
1da177e4
LT
6028#endif
6029 }
6030
6031#ifdef CONFIG_SCHED_SMT
6032 /* Set up CPU (sibling) groups */
9c1cfda2 6033 for_each_cpu_mask(i, *cpu_map) {
1da177e4 6034 cpumask_t this_sibling_map = cpu_sibling_map[i];
1a20ff27 6035 cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
1da177e4
LT
6036 if (i != first_cpu(this_sibling_map))
6037 continue;
6038
dd41f596
IM
6039 init_sched_build_groups(this_sibling_map, cpu_map,
6040 &cpu_to_cpu_group);
1da177e4
LT
6041 }
6042#endif
6043
1e9f28fa
SS
6044#ifdef CONFIG_SCHED_MC
6045 /* Set up multi-core groups */
6046 for_each_cpu_mask(i, *cpu_map) {
6047 cpumask_t this_core_map = cpu_coregroup_map(i);
6048 cpus_and(this_core_map, this_core_map, *cpu_map);
6049 if (i != first_cpu(this_core_map))
6050 continue;
dd41f596
IM
6051 init_sched_build_groups(this_core_map, cpu_map,
6052 &cpu_to_core_group);
1e9f28fa
SS
6053 }
6054#endif
6055
1da177e4
LT
6056 /* Set up physical groups */
6057 for (i = 0; i < MAX_NUMNODES; i++) {
6058 cpumask_t nodemask = node_to_cpumask(i);
6059
1a20ff27 6060 cpus_and(nodemask, nodemask, *cpu_map);
1da177e4
LT
6061 if (cpus_empty(nodemask))
6062 continue;
6063
6711cab4 6064 init_sched_build_groups(nodemask, cpu_map, &cpu_to_phys_group);
1da177e4
LT
6065 }
6066
6067#ifdef CONFIG_NUMA
6068 /* Set up node groups */
6711cab4 6069 if (sd_allnodes)
dd41f596
IM
6070 init_sched_build_groups(*cpu_map, cpu_map,
6071 &cpu_to_allnodes_group);
9c1cfda2
JH
6072
6073 for (i = 0; i < MAX_NUMNODES; i++) {
6074 /* Set up node groups */
6075 struct sched_group *sg, *prev;
6076 cpumask_t nodemask = node_to_cpumask(i);
6077 cpumask_t domainspan;
6078 cpumask_t covered = CPU_MASK_NONE;
6079 int j;
6080
6081 cpus_and(nodemask, nodemask, *cpu_map);
d1b55138
JH
6082 if (cpus_empty(nodemask)) {
6083 sched_group_nodes[i] = NULL;
9c1cfda2 6084 continue;
d1b55138 6085 }
9c1cfda2
JH
6086
6087 domainspan = sched_domain_node_span(i);
6088 cpus_and(domainspan, domainspan, *cpu_map);
6089
15f0b676 6090 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
51888ca2
SV
6091 if (!sg) {
6092 printk(KERN_WARNING "Can not alloc domain group for "
6093 "node %d\n", i);
6094 goto error;
6095 }
9c1cfda2
JH
6096 sched_group_nodes[i] = sg;
6097 for_each_cpu_mask(j, nodemask) {
6098 struct sched_domain *sd;
9761eea8 6099
9c1cfda2
JH
6100 sd = &per_cpu(node_domains, j);
6101 sd->groups = sg;
9c1cfda2 6102 }
5517d86b 6103 sg->__cpu_power = 0;
9c1cfda2 6104 sg->cpumask = nodemask;
51888ca2 6105 sg->next = sg;
9c1cfda2
JH
6106 cpus_or(covered, covered, nodemask);
6107 prev = sg;
6108
6109 for (j = 0; j < MAX_NUMNODES; j++) {
6110 cpumask_t tmp, notcovered;
6111 int n = (i + j) % MAX_NUMNODES;
6112
6113 cpus_complement(notcovered, covered);
6114 cpus_and(tmp, notcovered, *cpu_map);
6115 cpus_and(tmp, tmp, domainspan);
6116 if (cpus_empty(tmp))
6117 break;
6118
6119 nodemask = node_to_cpumask(n);
6120 cpus_and(tmp, tmp, nodemask);
6121 if (cpus_empty(tmp))
6122 continue;
6123
15f0b676
SV
6124 sg = kmalloc_node(sizeof(struct sched_group),
6125 GFP_KERNEL, i);
9c1cfda2
JH
6126 if (!sg) {
6127 printk(KERN_WARNING
6128 "Can not alloc domain group for node %d\n", j);
51888ca2 6129 goto error;
9c1cfda2 6130 }
5517d86b 6131 sg->__cpu_power = 0;
9c1cfda2 6132 sg->cpumask = tmp;
51888ca2 6133 sg->next = prev->next;
9c1cfda2
JH
6134 cpus_or(covered, covered, tmp);
6135 prev->next = sg;
6136 prev = sg;
6137 }
9c1cfda2 6138 }
1da177e4
LT
6139#endif
6140
6141 /* Calculate CPU power for physical packages and nodes */
5c45bf27 6142#ifdef CONFIG_SCHED_SMT
1a20ff27 6143 for_each_cpu_mask(i, *cpu_map) {
dd41f596
IM
6144 struct sched_domain *sd = &per_cpu(cpu_domains, i);
6145
89c4710e 6146 init_sched_groups_power(i, sd);
5c45bf27 6147 }
1da177e4 6148#endif
1e9f28fa 6149#ifdef CONFIG_SCHED_MC
5c45bf27 6150 for_each_cpu_mask(i, *cpu_map) {
dd41f596
IM
6151 struct sched_domain *sd = &per_cpu(core_domains, i);
6152
89c4710e 6153 init_sched_groups_power(i, sd);
5c45bf27
SS
6154 }
6155#endif
1e9f28fa 6156
5c45bf27 6157 for_each_cpu_mask(i, *cpu_map) {
dd41f596
IM
6158 struct sched_domain *sd = &per_cpu(phys_domains, i);
6159
89c4710e 6160 init_sched_groups_power(i, sd);
1da177e4
LT
6161 }
6162
9c1cfda2 6163#ifdef CONFIG_NUMA
08069033
SS
6164 for (i = 0; i < MAX_NUMNODES; i++)
6165 init_numa_sched_groups_power(sched_group_nodes[i]);
9c1cfda2 6166
6711cab4
SS
6167 if (sd_allnodes) {
6168 struct sched_group *sg;
f712c0c7 6169
6711cab4 6170 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg);
f712c0c7
SS
6171 init_numa_sched_groups_power(sg);
6172 }
9c1cfda2
JH
6173#endif
6174
1da177e4 6175 /* Attach the domains */
1a20ff27 6176 for_each_cpu_mask(i, *cpu_map) {
1da177e4
LT
6177 struct sched_domain *sd;
6178#ifdef CONFIG_SCHED_SMT
6179 sd = &per_cpu(cpu_domains, i);
1e9f28fa
SS
6180#elif defined(CONFIG_SCHED_MC)
6181 sd = &per_cpu(core_domains, i);
1da177e4
LT
6182#else
6183 sd = &per_cpu(phys_domains, i);
6184#endif
6185 cpu_attach_domain(sd, i);
6186 }
51888ca2
SV
6187
6188 return 0;
6189
a616058b 6190#ifdef CONFIG_NUMA
51888ca2
SV
6191error:
6192 free_sched_groups(cpu_map);
6193 return -ENOMEM;
a616058b 6194#endif
1da177e4 6195}
1a20ff27
DG
6196/*
6197 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6198 */
51888ca2 6199static int arch_init_sched_domains(const cpumask_t *cpu_map)
1a20ff27
DG
6200{
6201 cpumask_t cpu_default_map;
51888ca2 6202 int err;
1da177e4 6203
1a20ff27
DG
6204 /*
6205 * Setup mask for cpus without special case scheduling requirements.
6206 * For now this just excludes isolated cpus, but could be used to
6207 * exclude other special cases in the future.
6208 */
6209 cpus_andnot(cpu_default_map, *cpu_map, cpu_isolated_map);
6210
51888ca2
SV
6211 err = build_sched_domains(&cpu_default_map);
6212
6213 return err;
1a20ff27
DG
6214}
6215
6216static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
1da177e4 6217{
51888ca2 6218 free_sched_groups(cpu_map);
9c1cfda2 6219}
1da177e4 6220
1a20ff27
DG
6221/*
6222 * Detach sched domains from a group of cpus specified in cpu_map
6223 * These cpus will now be attached to the NULL domain
6224 */
858119e1 6225static void detach_destroy_domains(const cpumask_t *cpu_map)
1a20ff27
DG
6226{
6227 int i;
6228
6229 for_each_cpu_mask(i, *cpu_map)
6230 cpu_attach_domain(NULL, i);
6231 synchronize_sched();
6232 arch_destroy_sched_domains(cpu_map);
6233}
6234
6235/*
6236 * Partition sched domains as specified by the cpumasks below.
6237 * This attaches all cpus from the cpumasks to the NULL domain,
6238 * waits for a RCU quiescent period, recalculates sched
6239 * domain information and then attaches them back to the
6240 * correct sched domains
6241 * Call with hotplug lock held
6242 */
51888ca2 6243int partition_sched_domains(cpumask_t *partition1, cpumask_t *partition2)
1a20ff27
DG
6244{
6245 cpumask_t change_map;
51888ca2 6246 int err = 0;
1a20ff27
DG
6247
6248 cpus_and(*partition1, *partition1, cpu_online_map);
6249 cpus_and(*partition2, *partition2, cpu_online_map);
6250 cpus_or(change_map, *partition1, *partition2);
6251
6252 /* Detach sched domains from all of the affected cpus */
6253 detach_destroy_domains(&change_map);
6254 if (!cpus_empty(*partition1))
51888ca2
SV
6255 err = build_sched_domains(partition1);
6256 if (!err && !cpus_empty(*partition2))
6257 err = build_sched_domains(partition2);
6258
6259 return err;
1a20ff27
DG
6260}
6261
5c45bf27 6262#if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
6707de00 6263static int arch_reinit_sched_domains(void)
5c45bf27
SS
6264{
6265 int err;
6266
5be9361c 6267 mutex_lock(&sched_hotcpu_mutex);
5c45bf27
SS
6268 detach_destroy_domains(&cpu_online_map);
6269 err = arch_init_sched_domains(&cpu_online_map);
5be9361c 6270 mutex_unlock(&sched_hotcpu_mutex);
5c45bf27
SS
6271
6272 return err;
6273}
6274
6275static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
6276{
6277 int ret;
6278
6279 if (buf[0] != '0' && buf[0] != '1')
6280 return -EINVAL;
6281
6282 if (smt)
6283 sched_smt_power_savings = (buf[0] == '1');
6284 else
6285 sched_mc_power_savings = (buf[0] == '1');
6286
6287 ret = arch_reinit_sched_domains();
6288
6289 return ret ? ret : count;
6290}
6291
5c45bf27
SS
6292#ifdef CONFIG_SCHED_MC
6293static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
6294{
6295 return sprintf(page, "%u\n", sched_mc_power_savings);
6296}
48f24c4d
IM
6297static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
6298 const char *buf, size_t count)
5c45bf27
SS
6299{
6300 return sched_power_savings_store(buf, count, 0);
6301}
6707de00
AB
6302static SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
6303 sched_mc_power_savings_store);
5c45bf27
SS
6304#endif
6305
6306#ifdef CONFIG_SCHED_SMT
6307static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
6308{
6309 return sprintf(page, "%u\n", sched_smt_power_savings);
6310}
48f24c4d
IM
6311static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
6312 const char *buf, size_t count)
5c45bf27
SS
6313{
6314 return sched_power_savings_store(buf, count, 1);
6315}
6707de00
AB
6316static SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
6317 sched_smt_power_savings_store);
6318#endif
6319
6320int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
6321{
6322 int err = 0;
6323
6324#ifdef CONFIG_SCHED_SMT
6325 if (smt_capable())
6326 err = sysfs_create_file(&cls->kset.kobj,
6327 &attr_sched_smt_power_savings.attr);
6328#endif
6329#ifdef CONFIG_SCHED_MC
6330 if (!err && mc_capable())
6331 err = sysfs_create_file(&cls->kset.kobj,
6332 &attr_sched_mc_power_savings.attr);
6333#endif
6334 return err;
6335}
5c45bf27
SS
6336#endif
6337
1da177e4
LT
6338/*
6339 * Force a reinitialization of the sched domains hierarchy. The domains
6340 * and groups cannot be updated in place without racing with the balancing
41c7ce9a 6341 * code, so we temporarily attach all running cpus to the NULL domain
1da177e4
LT
6342 * which will prevent rebalancing while the sched domains are recalculated.
6343 */
6344static int update_sched_domains(struct notifier_block *nfb,
6345 unsigned long action, void *hcpu)
6346{
1da177e4
LT
6347 switch (action) {
6348 case CPU_UP_PREPARE:
8bb78442 6349 case CPU_UP_PREPARE_FROZEN:
1da177e4 6350 case CPU_DOWN_PREPARE:
8bb78442 6351 case CPU_DOWN_PREPARE_FROZEN:
1a20ff27 6352 detach_destroy_domains(&cpu_online_map);
1da177e4
LT
6353 return NOTIFY_OK;
6354
6355 case CPU_UP_CANCELED:
8bb78442 6356 case CPU_UP_CANCELED_FROZEN:
1da177e4 6357 case CPU_DOWN_FAILED:
8bb78442 6358 case CPU_DOWN_FAILED_FROZEN:
1da177e4 6359 case CPU_ONLINE:
8bb78442 6360 case CPU_ONLINE_FROZEN:
1da177e4 6361 case CPU_DEAD:
8bb78442 6362 case CPU_DEAD_FROZEN:
1da177e4
LT
6363 /*
6364 * Fall through and re-initialise the domains.
6365 */
6366 break;
6367 default:
6368 return NOTIFY_DONE;
6369 }
6370
6371 /* The hotplug lock is already held by cpu_up/cpu_down */
1a20ff27 6372 arch_init_sched_domains(&cpu_online_map);
1da177e4
LT
6373
6374 return NOTIFY_OK;
6375}
1da177e4
LT
6376
6377void __init sched_init_smp(void)
6378{
5c1e1767
NP
6379 cpumask_t non_isolated_cpus;
6380
5be9361c 6381 mutex_lock(&sched_hotcpu_mutex);
1a20ff27 6382 arch_init_sched_domains(&cpu_online_map);
e5e5673f 6383 cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
5c1e1767
NP
6384 if (cpus_empty(non_isolated_cpus))
6385 cpu_set(smp_processor_id(), non_isolated_cpus);
5be9361c 6386 mutex_unlock(&sched_hotcpu_mutex);
1da177e4
LT
6387 /* XXX: Theoretical race here - CPU may be hotplugged now */
6388 hotcpu_notifier(update_sched_domains, 0);
5c1e1767 6389
e692ab53
NP
6390 init_sched_domain_sysctl();
6391
5c1e1767
NP
6392 /* Move init over to a non-isolated CPU */
6393 if (set_cpus_allowed(current, non_isolated_cpus) < 0)
6394 BUG();
1da177e4
LT
6395}
6396#else
6397void __init sched_init_smp(void)
6398{
6399}
6400#endif /* CONFIG_SMP */
6401
6402int in_sched_functions(unsigned long addr)
6403{
6404 /* Linker adds these: start and end of __sched functions */
6405 extern char __sched_text_start[], __sched_text_end[];
48f24c4d 6406
1da177e4
LT
6407 return in_lock_functions(addr) ||
6408 (addr >= (unsigned long)__sched_text_start
6409 && addr < (unsigned long)__sched_text_end);
6410}
6411
dd41f596
IM
6412static inline void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
6413{
6414 cfs_rq->tasks_timeline = RB_ROOT;
dd41f596
IM
6415#ifdef CONFIG_FAIR_GROUP_SCHED
6416 cfs_rq->rq = rq;
6417#endif
6418}
6419
1da177e4
LT
6420void __init sched_init(void)
6421{
476f3534 6422 int highest_cpu = 0;
dd41f596
IM
6423 int i, j;
6424
6425 /*
6426 * Link up the scheduling class hierarchy:
6427 */
6428 rt_sched_class.next = &fair_sched_class;
6429 fair_sched_class.next = &idle_sched_class;
6430 idle_sched_class.next = NULL;
1da177e4 6431
0a945022 6432 for_each_possible_cpu(i) {
dd41f596 6433 struct rt_prio_array *array;
70b97a7f 6434 struct rq *rq;
1da177e4
LT
6435
6436 rq = cpu_rq(i);
6437 spin_lock_init(&rq->lock);
fcb99371 6438 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
7897986b 6439 rq->nr_running = 0;
dd41f596
IM
6440 rq->clock = 1;
6441 init_cfs_rq(&rq->cfs, rq);
6442#ifdef CONFIG_FAIR_GROUP_SCHED
6443 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
6444 list_add(&rq->cfs.leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
6445#endif
1da177e4 6446
dd41f596
IM
6447 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
6448 rq->cpu_load[j] = 0;
1da177e4 6449#ifdef CONFIG_SMP
41c7ce9a 6450 rq->sd = NULL;
1da177e4 6451 rq->active_balance = 0;
dd41f596 6452 rq->next_balance = jiffies;
1da177e4 6453 rq->push_cpu = 0;
0a2966b4 6454 rq->cpu = i;
1da177e4
LT
6455 rq->migration_thread = NULL;
6456 INIT_LIST_HEAD(&rq->migration_queue);
6457#endif
6458 atomic_set(&rq->nr_iowait, 0);
6459
dd41f596
IM
6460 array = &rq->rt.active;
6461 for (j = 0; j < MAX_RT_PRIO; j++) {
6462 INIT_LIST_HEAD(array->queue + j);
6463 __clear_bit(j, array->bitmap);
1da177e4 6464 }
476f3534 6465 highest_cpu = i;
dd41f596
IM
6466 /* delimiter for bitsearch: */
6467 __set_bit(MAX_RT_PRIO, array->bitmap);
1da177e4
LT
6468 }
6469
2dd73a4f 6470 set_load_weight(&init_task);
b50f60ce 6471
e107be36
AK
6472#ifdef CONFIG_PREEMPT_NOTIFIERS
6473 INIT_HLIST_HEAD(&init_task.preempt_notifiers);
6474#endif
6475
c9819f45 6476#ifdef CONFIG_SMP
476f3534 6477 nr_cpu_ids = highest_cpu + 1;
c9819f45
CL
6478 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
6479#endif
6480
b50f60ce
HC
6481#ifdef CONFIG_RT_MUTEXES
6482 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
6483#endif
6484
1da177e4
LT
6485 /*
6486 * The boot idle thread does lazy MMU switching as well:
6487 */
6488 atomic_inc(&init_mm.mm_count);
6489 enter_lazy_tlb(&init_mm, current);
6490
6491 /*
6492 * Make us the idle thread. Technically, schedule() should not be
6493 * called from this thread, however somewhere below it might be,
6494 * but because we are the idle thread, we just pick up running again
6495 * when this runqueue becomes "idle".
6496 */
6497 init_idle(current, smp_processor_id());
dd41f596
IM
6498 /*
6499 * During early bootup we pretend to be a normal task:
6500 */
6501 current->sched_class = &fair_sched_class;
1da177e4
LT
6502}
6503
6504#ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
6505void __might_sleep(char *file, int line)
6506{
48f24c4d 6507#ifdef in_atomic
1da177e4
LT
6508 static unsigned long prev_jiffy; /* ratelimiting */
6509
6510 if ((in_atomic() || irqs_disabled()) &&
6511 system_state == SYSTEM_RUNNING && !oops_in_progress) {
6512 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6513 return;
6514 prev_jiffy = jiffies;
91368d73 6515 printk(KERN_ERR "BUG: sleeping function called from invalid"
1da177e4
LT
6516 " context at %s:%d\n", file, line);
6517 printk("in_atomic():%d, irqs_disabled():%d\n",
6518 in_atomic(), irqs_disabled());
a4c410f0 6519 debug_show_held_locks(current);
3117df04
IM
6520 if (irqs_disabled())
6521 print_irqtrace_events(current);
1da177e4
LT
6522 dump_stack();
6523 }
6524#endif
6525}
6526EXPORT_SYMBOL(__might_sleep);
6527#endif
6528
6529#ifdef CONFIG_MAGIC_SYSRQ
6530void normalize_rt_tasks(void)
6531{
a0f98a1c 6532 struct task_struct *g, *p;
1da177e4 6533 unsigned long flags;
70b97a7f 6534 struct rq *rq;
dd41f596 6535 int on_rq;
1da177e4
LT
6536
6537 read_lock_irq(&tasklist_lock);
a0f98a1c 6538 do_each_thread(g, p) {
dd41f596 6539 p->se.fair_key = 0;
6cfb0d5d 6540 p->se.exec_start = 0;
6cfb0d5d 6541#ifdef CONFIG_SCHEDSTATS
dd41f596 6542 p->se.wait_start = 0;
dd41f596 6543 p->se.sleep_start = 0;
dd41f596 6544 p->se.block_start = 0;
6cfb0d5d 6545#endif
dd41f596
IM
6546 task_rq(p)->clock = 0;
6547
6548 if (!rt_task(p)) {
6549 /*
6550 * Renice negative nice level userspace
6551 * tasks back to 0:
6552 */
6553 if (TASK_NICE(p) < 0 && p->mm)
6554 set_user_nice(p, 0);
1da177e4 6555 continue;
dd41f596 6556 }
1da177e4 6557
b29739f9
IM
6558 spin_lock_irqsave(&p->pi_lock, flags);
6559 rq = __task_rq_lock(p);
dd41f596
IM
6560#ifdef CONFIG_SMP
6561 /*
6562 * Do not touch the migration thread:
6563 */
6564 if (p == rq->migration_thread)
6565 goto out_unlock;
6566#endif
1da177e4 6567
2daa3577 6568 update_rq_clock(rq);
dd41f596 6569 on_rq = p->se.on_rq;
2daa3577
IM
6570 if (on_rq)
6571 deactivate_task(rq, p, 0);
dd41f596
IM
6572 __setscheduler(rq, p, SCHED_NORMAL, 0);
6573 if (on_rq) {
2daa3577 6574 activate_task(rq, p, 0);
1da177e4
LT
6575 resched_task(rq->curr);
6576 }
dd41f596
IM
6577#ifdef CONFIG_SMP
6578 out_unlock:
6579#endif
b29739f9
IM
6580 __task_rq_unlock(rq);
6581 spin_unlock_irqrestore(&p->pi_lock, flags);
a0f98a1c
IM
6582 } while_each_thread(g, p);
6583
1da177e4
LT
6584 read_unlock_irq(&tasklist_lock);
6585}
6586
6587#endif /* CONFIG_MAGIC_SYSRQ */
1df5c10a
LT
6588
6589#ifdef CONFIG_IA64
6590/*
6591 * These functions are only useful for the IA64 MCA handling.
6592 *
6593 * They can only be called when the whole system has been
6594 * stopped - every CPU needs to be quiescent, and no scheduling
6595 * activity can take place. Using them for anything else would
6596 * be a serious bug, and as a result, they aren't even visible
6597 * under any other configuration.
6598 */
6599
6600/**
6601 * curr_task - return the current task for a given cpu.
6602 * @cpu: the processor in question.
6603 *
6604 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6605 */
36c8b586 6606struct task_struct *curr_task(int cpu)
1df5c10a
LT
6607{
6608 return cpu_curr(cpu);
6609}
6610
6611/**
6612 * set_curr_task - set the current task for a given cpu.
6613 * @cpu: the processor in question.
6614 * @p: the task pointer to set.
6615 *
6616 * Description: This function must only be used when non-maskable interrupts
6617 * are serviced on a separate stack. It allows the architecture to switch the
6618 * notion of the current task on a cpu in a non-blocking manner. This function
6619 * must be called with all CPU's synchronized, and interrupts disabled, the
6620 * and caller must save the original value of the current task (see
6621 * curr_task() above) and restore that value before reenabling interrupts and
6622 * re-starting the system.
6623 *
6624 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6625 */
36c8b586 6626void set_curr_task(int cpu, struct task_struct *p)
1df5c10a
LT
6627{
6628 cpu_curr(cpu) = p;
6629}
6630
6631#endif