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