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