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