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