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