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