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