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