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