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