[PATCH] count_vm_events() fix
[GitHub/mt8127/android_kernel_alcatel_ttab.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
191struct prio_array {
192 unsigned int nr_active;
d444886e 193 DECLARE_BITMAP(bitmap, MAX_PRIO+1); /* include 1 bit for delimiter */
1da177e4
LT
194 struct list_head queue[MAX_PRIO];
195};
196
197/*
198 * This is the main, per-CPU runqueue data structure.
199 *
200 * Locking rule: those places that want to lock multiple runqueues
201 * (such as the load balancing or the thread migration code), lock
202 * acquire operations must be ordered by ascending &runqueue.
203 */
70b97a7f 204struct rq {
1da177e4
LT
205 spinlock_t lock;
206
207 /*
208 * nr_running and cpu_load should be in the same cacheline because
209 * remote CPUs use both these fields when doing load calculation.
210 */
211 unsigned long nr_running;
2dd73a4f 212 unsigned long raw_weighted_load;
1da177e4 213#ifdef CONFIG_SMP
7897986b 214 unsigned long cpu_load[3];
1da177e4
LT
215#endif
216 unsigned long long nr_switches;
217
218 /*
219 * This is part of a global counter where only the total sum
220 * over all CPUs matters. A task can increase this counter on
221 * one CPU and if it got migrated afterwards it may decrease
222 * it on another CPU. Always updated under the runqueue lock:
223 */
224 unsigned long nr_uninterruptible;
225
226 unsigned long expired_timestamp;
227 unsigned long long timestamp_last_tick;
36c8b586 228 struct task_struct *curr, *idle;
1da177e4 229 struct mm_struct *prev_mm;
70b97a7f 230 struct prio_array *active, *expired, arrays[2];
1da177e4
LT
231 int best_expired_prio;
232 atomic_t nr_iowait;
233
234#ifdef CONFIG_SMP
235 struct sched_domain *sd;
236
237 /* For active balancing */
238 int active_balance;
239 int push_cpu;
240
36c8b586 241 struct task_struct *migration_thread;
1da177e4
LT
242 struct list_head migration_queue;
243#endif
244
245#ifdef CONFIG_SCHEDSTATS
246 /* latency stats */
247 struct sched_info rq_sched_info;
248
249 /* sys_sched_yield() stats */
250 unsigned long yld_exp_empty;
251 unsigned long yld_act_empty;
252 unsigned long yld_both_empty;
253 unsigned long yld_cnt;
254
255 /* schedule() stats */
256 unsigned long sched_switch;
257 unsigned long sched_cnt;
258 unsigned long sched_goidle;
259
260 /* try_to_wake_up() stats */
261 unsigned long ttwu_cnt;
262 unsigned long ttwu_local;
263#endif
fcb99371 264 struct lock_class_key rq_lock_key;
1da177e4
LT
265};
266
70b97a7f 267static DEFINE_PER_CPU(struct rq, runqueues);
1da177e4 268
674311d5
NP
269/*
270 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
1a20ff27 271 * See detach_destroy_domains: synchronize_sched for details.
674311d5
NP
272 *
273 * The domain tree of any CPU may only be accessed from within
274 * preempt-disabled sections.
275 */
48f24c4d
IM
276#define for_each_domain(cpu, __sd) \
277 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
1da177e4
LT
278
279#define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
280#define this_rq() (&__get_cpu_var(runqueues))
281#define task_rq(p) cpu_rq(task_cpu(p))
282#define cpu_curr(cpu) (cpu_rq(cpu)->curr)
283
1da177e4 284#ifndef prepare_arch_switch
4866cde0
NP
285# define prepare_arch_switch(next) do { } while (0)
286#endif
287#ifndef finish_arch_switch
288# define finish_arch_switch(prev) do { } while (0)
289#endif
290
291#ifndef __ARCH_WANT_UNLOCKED_CTXSW
70b97a7f 292static inline int task_running(struct rq *rq, struct task_struct *p)
4866cde0
NP
293{
294 return rq->curr == p;
295}
296
70b97a7f 297static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
4866cde0
NP
298{
299}
300
70b97a7f 301static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
4866cde0 302{
da04c035
IM
303#ifdef CONFIG_DEBUG_SPINLOCK
304 /* this is a valid case when another task releases the spinlock */
305 rq->lock.owner = current;
306#endif
8a25d5de
IM
307 /*
308 * If we are tracking spinlock dependencies then we have to
309 * fix up the runqueue lock - which gets 'carried over' from
310 * prev into current:
311 */
312 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
313
4866cde0
NP
314 spin_unlock_irq(&rq->lock);
315}
316
317#else /* __ARCH_WANT_UNLOCKED_CTXSW */
70b97a7f 318static inline int task_running(struct rq *rq, struct task_struct *p)
4866cde0
NP
319{
320#ifdef CONFIG_SMP
321 return p->oncpu;
322#else
323 return rq->curr == p;
324#endif
325}
326
70b97a7f 327static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
4866cde0
NP
328{
329#ifdef CONFIG_SMP
330 /*
331 * We can optimise this out completely for !SMP, because the
332 * SMP rebalancing from interrupt is the only thing that cares
333 * here.
334 */
335 next->oncpu = 1;
336#endif
337#ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
338 spin_unlock_irq(&rq->lock);
339#else
340 spin_unlock(&rq->lock);
341#endif
342}
343
70b97a7f 344static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
4866cde0
NP
345{
346#ifdef CONFIG_SMP
347 /*
348 * After ->oncpu is cleared, the task can be moved to a different CPU.
349 * We must ensure this doesn't happen until the switch is completely
350 * finished.
351 */
352 smp_wmb();
353 prev->oncpu = 0;
354#endif
355#ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
356 local_irq_enable();
1da177e4 357#endif
4866cde0
NP
358}
359#endif /* __ARCH_WANT_UNLOCKED_CTXSW */
1da177e4 360
b29739f9
IM
361/*
362 * __task_rq_lock - lock the runqueue a given task resides on.
363 * Must be called interrupts disabled.
364 */
70b97a7f 365static inline struct rq *__task_rq_lock(struct task_struct *p)
b29739f9
IM
366 __acquires(rq->lock)
367{
70b97a7f 368 struct rq *rq;
b29739f9
IM
369
370repeat_lock_task:
371 rq = task_rq(p);
372 spin_lock(&rq->lock);
373 if (unlikely(rq != task_rq(p))) {
374 spin_unlock(&rq->lock);
375 goto repeat_lock_task;
376 }
377 return rq;
378}
379
1da177e4
LT
380/*
381 * task_rq_lock - lock the runqueue a given task resides on and disable
382 * interrupts. Note the ordering: we can safely lookup the task_rq without
383 * explicitly disabling preemption.
384 */
70b97a7f 385static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
1da177e4
LT
386 __acquires(rq->lock)
387{
70b97a7f 388 struct rq *rq;
1da177e4
LT
389
390repeat_lock_task:
391 local_irq_save(*flags);
392 rq = task_rq(p);
393 spin_lock(&rq->lock);
394 if (unlikely(rq != task_rq(p))) {
395 spin_unlock_irqrestore(&rq->lock, *flags);
396 goto repeat_lock_task;
397 }
398 return rq;
399}
400
70b97a7f 401static inline void __task_rq_unlock(struct rq *rq)
b29739f9
IM
402 __releases(rq->lock)
403{
404 spin_unlock(&rq->lock);
405}
406
70b97a7f 407static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
1da177e4
LT
408 __releases(rq->lock)
409{
410 spin_unlock_irqrestore(&rq->lock, *flags);
411}
412
413#ifdef CONFIG_SCHEDSTATS
414/*
415 * bump this up when changing the output format or the meaning of an existing
416 * format, so that tools can adapt (or abort)
417 */
68767a0a 418#define SCHEDSTAT_VERSION 12
1da177e4
LT
419
420static int show_schedstat(struct seq_file *seq, void *v)
421{
422 int cpu;
423
424 seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
425 seq_printf(seq, "timestamp %lu\n", jiffies);
426 for_each_online_cpu(cpu) {
70b97a7f 427 struct rq *rq = cpu_rq(cpu);
1da177e4
LT
428#ifdef CONFIG_SMP
429 struct sched_domain *sd;
430 int dcnt = 0;
431#endif
432
433 /* runqueue-specific stats */
434 seq_printf(seq,
435 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
436 cpu, rq->yld_both_empty,
437 rq->yld_act_empty, rq->yld_exp_empty, rq->yld_cnt,
438 rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
439 rq->ttwu_cnt, rq->ttwu_local,
440 rq->rq_sched_info.cpu_time,
441 rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
442
443 seq_printf(seq, "\n");
444
445#ifdef CONFIG_SMP
446 /* domain-specific stats */
674311d5 447 preempt_disable();
1da177e4
LT
448 for_each_domain(cpu, sd) {
449 enum idle_type itype;
450 char mask_str[NR_CPUS];
451
452 cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
453 seq_printf(seq, "domain%d %s", dcnt++, mask_str);
454 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
455 itype++) {
456 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu",
457 sd->lb_cnt[itype],
458 sd->lb_balanced[itype],
459 sd->lb_failed[itype],
460 sd->lb_imbalance[itype],
461 sd->lb_gained[itype],
462 sd->lb_hot_gained[itype],
463 sd->lb_nobusyq[itype],
464 sd->lb_nobusyg[itype]);
465 }
68767a0a 466 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
1da177e4 467 sd->alb_cnt, sd->alb_failed, sd->alb_pushed,
68767a0a
NP
468 sd->sbe_cnt, sd->sbe_balanced, sd->sbe_pushed,
469 sd->sbf_cnt, sd->sbf_balanced, sd->sbf_pushed,
1da177e4
LT
470 sd->ttwu_wake_remote, sd->ttwu_move_affine, sd->ttwu_move_balance);
471 }
674311d5 472 preempt_enable();
1da177e4
LT
473#endif
474 }
475 return 0;
476}
477
478static int schedstat_open(struct inode *inode, struct file *file)
479{
480 unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
481 char *buf = kmalloc(size, GFP_KERNEL);
482 struct seq_file *m;
483 int res;
484
485 if (!buf)
486 return -ENOMEM;
487 res = single_open(file, show_schedstat, NULL);
488 if (!res) {
489 m = file->private_data;
490 m->buf = buf;
491 m->size = size;
492 } else
493 kfree(buf);
494 return res;
495}
496
497struct file_operations proc_schedstat_operations = {
498 .open = schedstat_open,
499 .read = seq_read,
500 .llseek = seq_lseek,
501 .release = single_release,
502};
503
504# define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
505# define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
506#else /* !CONFIG_SCHEDSTATS */
507# define schedstat_inc(rq, field) do { } while (0)
508# define schedstat_add(rq, field, amt) do { } while (0)
509#endif
510
511/*
512 * rq_lock - lock a given runqueue and disable interrupts.
513 */
70b97a7f 514static inline struct rq *this_rq_lock(void)
1da177e4
LT
515 __acquires(rq->lock)
516{
70b97a7f 517 struct rq *rq;
1da177e4
LT
518
519 local_irq_disable();
520 rq = this_rq();
521 spin_lock(&rq->lock);
522
523 return rq;
524}
525
1da177e4
LT
526#ifdef CONFIG_SCHEDSTATS
527/*
528 * Called when a process is dequeued from the active array and given
529 * the cpu. We should note that with the exception of interactive
530 * tasks, the expired queue will become the active queue after the active
531 * queue is empty, without explicitly dequeuing and requeuing tasks in the
532 * expired queue. (Interactive tasks may be requeued directly to the
533 * active queue, thus delaying tasks in the expired queue from running;
534 * see scheduler_tick()).
535 *
536 * This function is only called from sched_info_arrive(), rather than
537 * dequeue_task(). Even though a task may be queued and dequeued multiple
538 * times as it is shuffled about, we're really interested in knowing how
539 * long it was from the *first* time it was queued to the time that it
540 * finally hit a cpu.
541 */
36c8b586 542static inline void sched_info_dequeued(struct task_struct *t)
1da177e4
LT
543{
544 t->sched_info.last_queued = 0;
545}
546
547/*
548 * Called when a task finally hits the cpu. We can now calculate how
549 * long it was waiting to run. We also note when it began so that we
550 * can keep stats on how long its timeslice is.
551 */
36c8b586 552static void sched_info_arrive(struct task_struct *t)
1da177e4
LT
553{
554 unsigned long now = jiffies, diff = 0;
70b97a7f 555 struct rq *rq = task_rq(t);
1da177e4
LT
556
557 if (t->sched_info.last_queued)
558 diff = now - t->sched_info.last_queued;
559 sched_info_dequeued(t);
560 t->sched_info.run_delay += diff;
561 t->sched_info.last_arrival = now;
562 t->sched_info.pcnt++;
563
564 if (!rq)
565 return;
566
567 rq->rq_sched_info.run_delay += diff;
568 rq->rq_sched_info.pcnt++;
569}
570
571/*
572 * Called when a process is queued into either the active or expired
573 * array. The time is noted and later used to determine how long we
574 * had to wait for us to reach the cpu. Since the expired queue will
575 * become the active queue after active queue is empty, without dequeuing
576 * and requeuing any tasks, we are interested in queuing to either. It
577 * is unusual but not impossible for tasks to be dequeued and immediately
578 * requeued in the same or another array: this can happen in sched_yield(),
579 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
580 * to runqueue.
581 *
582 * This function is only called from enqueue_task(), but also only updates
583 * the timestamp if it is already not set. It's assumed that
584 * sched_info_dequeued() will clear that stamp when appropriate.
585 */
36c8b586 586static inline void sched_info_queued(struct task_struct *t)
1da177e4
LT
587{
588 if (!t->sched_info.last_queued)
589 t->sched_info.last_queued = jiffies;
590}
591
592/*
593 * Called when a process ceases being the active-running process, either
594 * voluntarily or involuntarily. Now we can calculate how long we ran.
595 */
36c8b586 596static inline void sched_info_depart(struct task_struct *t)
1da177e4 597{
70b97a7f 598 struct rq *rq = task_rq(t);
1da177e4
LT
599 unsigned long diff = jiffies - t->sched_info.last_arrival;
600
601 t->sched_info.cpu_time += diff;
602
603 if (rq)
604 rq->rq_sched_info.cpu_time += diff;
605}
606
607/*
608 * Called when tasks are switched involuntarily due, typically, to expiring
609 * their time slice. (This may also be called when switching to or from
610 * the idle task.) We are only called when prev != next.
611 */
36c8b586
IM
612static inline void
613sched_info_switch(struct task_struct *prev, struct task_struct *next)
1da177e4 614{
70b97a7f 615 struct rq *rq = task_rq(prev);
1da177e4
LT
616
617 /*
618 * prev now departs the cpu. It's not interesting to record
619 * stats about how efficient we were at scheduling the idle
620 * process, however.
621 */
622 if (prev != rq->idle)
623 sched_info_depart(prev);
624
625 if (next != rq->idle)
626 sched_info_arrive(next);
627}
628#else
629#define sched_info_queued(t) do { } while (0)
630#define sched_info_switch(t, next) do { } while (0)
631#endif /* CONFIG_SCHEDSTATS */
632
633/*
634 * Adding/removing a task to/from a priority array:
635 */
70b97a7f 636static void dequeue_task(struct task_struct *p, struct prio_array *array)
1da177e4
LT
637{
638 array->nr_active--;
639 list_del(&p->run_list);
640 if (list_empty(array->queue + p->prio))
641 __clear_bit(p->prio, array->bitmap);
642}
643
70b97a7f 644static void enqueue_task(struct task_struct *p, struct prio_array *array)
1da177e4
LT
645{
646 sched_info_queued(p);
647 list_add_tail(&p->run_list, array->queue + p->prio);
648 __set_bit(p->prio, array->bitmap);
649 array->nr_active++;
650 p->array = array;
651}
652
653/*
654 * Put task to the end of the run list without the overhead of dequeue
655 * followed by enqueue.
656 */
70b97a7f 657static void requeue_task(struct task_struct *p, struct prio_array *array)
1da177e4
LT
658{
659 list_move_tail(&p->run_list, array->queue + p->prio);
660}
661
70b97a7f
IM
662static inline void
663enqueue_task_head(struct task_struct *p, struct prio_array *array)
1da177e4
LT
664{
665 list_add(&p->run_list, array->queue + p->prio);
666 __set_bit(p->prio, array->bitmap);
667 array->nr_active++;
668 p->array = array;
669}
670
671/*
b29739f9 672 * __normal_prio - return the priority that is based on the static
1da177e4
LT
673 * priority but is modified by bonuses/penalties.
674 *
675 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
676 * into the -5 ... 0 ... +5 bonus/penalty range.
677 *
678 * We use 25% of the full 0...39 priority range so that:
679 *
680 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
681 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
682 *
683 * Both properties are important to certain workloads.
684 */
b29739f9 685
36c8b586 686static inline int __normal_prio(struct task_struct *p)
1da177e4
LT
687{
688 int bonus, prio;
689
1da177e4
LT
690 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
691
692 prio = p->static_prio - bonus;
693 if (prio < MAX_RT_PRIO)
694 prio = MAX_RT_PRIO;
695 if (prio > MAX_PRIO-1)
696 prio = MAX_PRIO-1;
697 return prio;
698}
699
2dd73a4f
PW
700/*
701 * To aid in avoiding the subversion of "niceness" due to uneven distribution
702 * of tasks with abnormal "nice" values across CPUs the contribution that
703 * each task makes to its run queue's load is weighted according to its
704 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
705 * scaled version of the new time slice allocation that they receive on time
706 * slice expiry etc.
707 */
708
709/*
710 * Assume: static_prio_timeslice(NICE_TO_PRIO(0)) == DEF_TIMESLICE
711 * If static_prio_timeslice() is ever changed to break this assumption then
712 * this code will need modification
713 */
714#define TIME_SLICE_NICE_ZERO DEF_TIMESLICE
715#define LOAD_WEIGHT(lp) \
716 (((lp) * SCHED_LOAD_SCALE) / TIME_SLICE_NICE_ZERO)
717#define PRIO_TO_LOAD_WEIGHT(prio) \
718 LOAD_WEIGHT(static_prio_timeslice(prio))
719#define RTPRIO_TO_LOAD_WEIGHT(rp) \
720 (PRIO_TO_LOAD_WEIGHT(MAX_RT_PRIO) + LOAD_WEIGHT(rp))
721
36c8b586 722static void set_load_weight(struct task_struct *p)
2dd73a4f 723{
b29739f9 724 if (has_rt_policy(p)) {
2dd73a4f
PW
725#ifdef CONFIG_SMP
726 if (p == task_rq(p)->migration_thread)
727 /*
728 * The migration thread does the actual balancing.
729 * Giving its load any weight will skew balancing
730 * adversely.
731 */
732 p->load_weight = 0;
733 else
734#endif
735 p->load_weight = RTPRIO_TO_LOAD_WEIGHT(p->rt_priority);
736 } else
737 p->load_weight = PRIO_TO_LOAD_WEIGHT(p->static_prio);
738}
739
36c8b586 740static inline void
70b97a7f 741inc_raw_weighted_load(struct rq *rq, const struct task_struct *p)
2dd73a4f
PW
742{
743 rq->raw_weighted_load += p->load_weight;
744}
745
36c8b586 746static inline void
70b97a7f 747dec_raw_weighted_load(struct rq *rq, const struct task_struct *p)
2dd73a4f
PW
748{
749 rq->raw_weighted_load -= p->load_weight;
750}
751
70b97a7f 752static inline void inc_nr_running(struct task_struct *p, struct rq *rq)
2dd73a4f
PW
753{
754 rq->nr_running++;
755 inc_raw_weighted_load(rq, p);
756}
757
70b97a7f 758static inline void dec_nr_running(struct task_struct *p, struct rq *rq)
2dd73a4f
PW
759{
760 rq->nr_running--;
761 dec_raw_weighted_load(rq, p);
762}
763
b29739f9
IM
764/*
765 * Calculate the expected normal priority: i.e. priority
766 * without taking RT-inheritance into account. Might be
767 * boosted by interactivity modifiers. Changes upon fork,
768 * setprio syscalls, and whenever the interactivity
769 * estimator recalculates.
770 */
36c8b586 771static inline int normal_prio(struct task_struct *p)
b29739f9
IM
772{
773 int prio;
774
775 if (has_rt_policy(p))
776 prio = MAX_RT_PRIO-1 - p->rt_priority;
777 else
778 prio = __normal_prio(p);
779 return prio;
780}
781
782/*
783 * Calculate the current priority, i.e. the priority
784 * taken into account by the scheduler. This value might
785 * be boosted by RT tasks, or might be boosted by
786 * interactivity modifiers. Will be RT if the task got
787 * RT-boosted. If not then it returns p->normal_prio.
788 */
36c8b586 789static int effective_prio(struct task_struct *p)
b29739f9
IM
790{
791 p->normal_prio = normal_prio(p);
792 /*
793 * If we are RT tasks or we were boosted to RT priority,
794 * keep the priority unchanged. Otherwise, update priority
795 * to the normal priority:
796 */
797 if (!rt_prio(p->prio))
798 return p->normal_prio;
799 return p->prio;
800}
801
1da177e4
LT
802/*
803 * __activate_task - move a task to the runqueue.
804 */
70b97a7f 805static void __activate_task(struct task_struct *p, struct rq *rq)
1da177e4 806{
70b97a7f 807 struct prio_array *target = rq->active;
d425b274 808
f1adad78 809 if (batch_task(p))
d425b274
CK
810 target = rq->expired;
811 enqueue_task(p, target);
2dd73a4f 812 inc_nr_running(p, rq);
1da177e4
LT
813}
814
815/*
816 * __activate_idle_task - move idle task to the _front_ of runqueue.
817 */
70b97a7f 818static inline void __activate_idle_task(struct task_struct *p, struct rq *rq)
1da177e4
LT
819{
820 enqueue_task_head(p, rq->active);
2dd73a4f 821 inc_nr_running(p, rq);
1da177e4
LT
822}
823
b29739f9
IM
824/*
825 * Recalculate p->normal_prio and p->prio after having slept,
826 * updating the sleep-average too:
827 */
36c8b586 828static int recalc_task_prio(struct task_struct *p, unsigned long long now)
1da177e4
LT
829{
830 /* Caller must always ensure 'now >= p->timestamp' */
72d2854d 831 unsigned long sleep_time = now - p->timestamp;
1da177e4 832
d425b274 833 if (batch_task(p))
b0a9499c 834 sleep_time = 0;
1da177e4
LT
835
836 if (likely(sleep_time > 0)) {
837 /*
72d2854d
CK
838 * This ceiling is set to the lowest priority that would allow
839 * a task to be reinserted into the active array on timeslice
840 * completion.
1da177e4 841 */
72d2854d 842 unsigned long ceiling = INTERACTIVE_SLEEP(p);
e72ff0bb 843
72d2854d
CK
844 if (p->mm && sleep_time > ceiling && p->sleep_avg < ceiling) {
845 /*
846 * Prevents user tasks from achieving best priority
847 * with one single large enough sleep.
848 */
849 p->sleep_avg = ceiling;
850 /*
851 * Using INTERACTIVE_SLEEP() as a ceiling places a
852 * nice(0) task 1ms sleep away from promotion, and
853 * gives it 700ms to round-robin with no chance of
854 * being demoted. This is more than generous, so
855 * mark this sleep as non-interactive to prevent the
856 * on-runqueue bonus logic from intervening should
857 * this task not receive cpu immediately.
858 */
859 p->sleep_type = SLEEP_NONINTERACTIVE;
1da177e4 860 } else {
1da177e4
LT
861 /*
862 * Tasks waking from uninterruptible sleep are
863 * limited in their sleep_avg rise as they
864 * are likely to be waiting on I/O
865 */
3dee386e 866 if (p->sleep_type == SLEEP_NONINTERACTIVE && p->mm) {
72d2854d 867 if (p->sleep_avg >= ceiling)
1da177e4
LT
868 sleep_time = 0;
869 else if (p->sleep_avg + sleep_time >=
72d2854d
CK
870 ceiling) {
871 p->sleep_avg = ceiling;
872 sleep_time = 0;
1da177e4
LT
873 }
874 }
875
876 /*
877 * This code gives a bonus to interactive tasks.
878 *
879 * The boost works by updating the 'average sleep time'
880 * value here, based on ->timestamp. The more time a
881 * task spends sleeping, the higher the average gets -
882 * and the higher the priority boost gets as well.
883 */
884 p->sleep_avg += sleep_time;
885
1da177e4 886 }
72d2854d
CK
887 if (p->sleep_avg > NS_MAX_SLEEP_AVG)
888 p->sleep_avg = NS_MAX_SLEEP_AVG;
1da177e4
LT
889 }
890
a3464a10 891 return effective_prio(p);
1da177e4
LT
892}
893
894/*
895 * activate_task - move a task to the runqueue and do priority recalculation
896 *
897 * Update all the scheduling statistics stuff. (sleep average
898 * calculation, priority modifiers, etc.)
899 */
70b97a7f 900static void activate_task(struct task_struct *p, struct rq *rq, int local)
1da177e4
LT
901{
902 unsigned long long now;
903
904 now = sched_clock();
905#ifdef CONFIG_SMP
906 if (!local) {
907 /* Compensate for drifting sched_clock */
70b97a7f 908 struct rq *this_rq = this_rq();
1da177e4
LT
909 now = (now - this_rq->timestamp_last_tick)
910 + rq->timestamp_last_tick;
911 }
912#endif
913
a47ab937
KC
914 if (!rt_task(p))
915 p->prio = recalc_task_prio(p, now);
1da177e4
LT
916
917 /*
918 * This checks to make sure it's not an uninterruptible task
919 * that is now waking up.
920 */
3dee386e 921 if (p->sleep_type == SLEEP_NORMAL) {
1da177e4
LT
922 /*
923 * Tasks which were woken up by interrupts (ie. hw events)
924 * are most likely of interactive nature. So we give them
925 * the credit of extending their sleep time to the period
926 * of time they spend on the runqueue, waiting for execution
927 * on a CPU, first time around:
928 */
929 if (in_interrupt())
3dee386e 930 p->sleep_type = SLEEP_INTERRUPTED;
1da177e4
LT
931 else {
932 /*
933 * Normal first-time wakeups get a credit too for
934 * on-runqueue time, but it will be weighted down:
935 */
3dee386e 936 p->sleep_type = SLEEP_INTERACTIVE;
1da177e4
LT
937 }
938 }
939 p->timestamp = now;
940
941 __activate_task(p, rq);
942}
943
944/*
945 * deactivate_task - remove a task from the runqueue.
946 */
70b97a7f 947static void deactivate_task(struct task_struct *p, struct rq *rq)
1da177e4 948{
2dd73a4f 949 dec_nr_running(p, rq);
1da177e4
LT
950 dequeue_task(p, p->array);
951 p->array = NULL;
952}
953
954/*
955 * resched_task - mark a task 'to be rescheduled now'.
956 *
957 * On UP this means the setting of the need_resched flag, on SMP it
958 * might also involve a cross-CPU call to trigger the scheduler on
959 * the target CPU.
960 */
961#ifdef CONFIG_SMP
495ab9c0
AK
962
963#ifndef tsk_is_polling
964#define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
965#endif
966
36c8b586 967static void resched_task(struct task_struct *p)
1da177e4 968{
64c7c8f8 969 int cpu;
1da177e4
LT
970
971 assert_spin_locked(&task_rq(p)->lock);
972
64c7c8f8
NP
973 if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
974 return;
975
976 set_tsk_thread_flag(p, TIF_NEED_RESCHED);
1da177e4 977
64c7c8f8
NP
978 cpu = task_cpu(p);
979 if (cpu == smp_processor_id())
980 return;
981
495ab9c0 982 /* NEED_RESCHED must be visible before we test polling */
64c7c8f8 983 smp_mb();
495ab9c0 984 if (!tsk_is_polling(p))
64c7c8f8 985 smp_send_reschedule(cpu);
1da177e4
LT
986}
987#else
36c8b586 988static inline void resched_task(struct task_struct *p)
1da177e4 989{
64c7c8f8 990 assert_spin_locked(&task_rq(p)->lock);
1da177e4
LT
991 set_tsk_need_resched(p);
992}
993#endif
994
995/**
996 * task_curr - is this task currently executing on a CPU?
997 * @p: the task in question.
998 */
36c8b586 999inline int task_curr(const struct task_struct *p)
1da177e4
LT
1000{
1001 return cpu_curr(task_cpu(p)) == p;
1002}
1003
2dd73a4f
PW
1004/* Used instead of source_load when we know the type == 0 */
1005unsigned long weighted_cpuload(const int cpu)
1006{
1007 return cpu_rq(cpu)->raw_weighted_load;
1008}
1009
1da177e4 1010#ifdef CONFIG_SMP
70b97a7f 1011struct migration_req {
1da177e4 1012 struct list_head list;
1da177e4 1013
36c8b586 1014 struct task_struct *task;
1da177e4
LT
1015 int dest_cpu;
1016
1da177e4 1017 struct completion done;
70b97a7f 1018};
1da177e4
LT
1019
1020/*
1021 * The task's runqueue lock must be held.
1022 * Returns true if you have to wait for migration thread.
1023 */
36c8b586 1024static int
70b97a7f 1025migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1da177e4 1026{
70b97a7f 1027 struct rq *rq = task_rq(p);
1da177e4
LT
1028
1029 /*
1030 * If the task is not on a runqueue (and not running), then
1031 * it is sufficient to simply update the task's cpu field.
1032 */
1033 if (!p->array && !task_running(rq, p)) {
1034 set_task_cpu(p, dest_cpu);
1035 return 0;
1036 }
1037
1038 init_completion(&req->done);
1da177e4
LT
1039 req->task = p;
1040 req->dest_cpu = dest_cpu;
1041 list_add(&req->list, &rq->migration_queue);
48f24c4d 1042
1da177e4
LT
1043 return 1;
1044}
1045
1046/*
1047 * wait_task_inactive - wait for a thread to unschedule.
1048 *
1049 * The caller must ensure that the task *will* unschedule sometime soon,
1050 * else this function might spin for a *long* time. This function can't
1051 * be called with interrupts off, or it may introduce deadlock with
1052 * smp_call_function() if an IPI is sent by the same process we are
1053 * waiting to become inactive.
1054 */
36c8b586 1055void wait_task_inactive(struct task_struct *p)
1da177e4
LT
1056{
1057 unsigned long flags;
70b97a7f 1058 struct rq *rq;
1da177e4
LT
1059 int preempted;
1060
1061repeat:
1062 rq = task_rq_lock(p, &flags);
1063 /* Must be off runqueue entirely, not preempted. */
1064 if (unlikely(p->array || task_running(rq, p))) {
1065 /* If it's preempted, we yield. It could be a while. */
1066 preempted = !task_running(rq, p);
1067 task_rq_unlock(rq, &flags);
1068 cpu_relax();
1069 if (preempted)
1070 yield();
1071 goto repeat;
1072 }
1073 task_rq_unlock(rq, &flags);
1074}
1075
1076/***
1077 * kick_process - kick a running thread to enter/exit the kernel
1078 * @p: the to-be-kicked thread
1079 *
1080 * Cause a process which is running on another CPU to enter
1081 * kernel-mode, without any delay. (to get signals handled.)
1082 *
1083 * NOTE: this function doesnt have to take the runqueue lock,
1084 * because all it wants to ensure is that the remote task enters
1085 * the kernel. If the IPI races and the task has been migrated
1086 * to another CPU then no harm is done and the purpose has been
1087 * achieved as well.
1088 */
36c8b586 1089void kick_process(struct task_struct *p)
1da177e4
LT
1090{
1091 int cpu;
1092
1093 preempt_disable();
1094 cpu = task_cpu(p);
1095 if ((cpu != smp_processor_id()) && task_curr(p))
1096 smp_send_reschedule(cpu);
1097 preempt_enable();
1098}
1099
1100/*
2dd73a4f
PW
1101 * Return a low guess at the load of a migration-source cpu weighted
1102 * according to the scheduling class and "nice" value.
1da177e4
LT
1103 *
1104 * We want to under-estimate the load of migration sources, to
1105 * balance conservatively.
1106 */
a2000572 1107static inline unsigned long source_load(int cpu, int type)
1da177e4 1108{
70b97a7f 1109 struct rq *rq = cpu_rq(cpu);
2dd73a4f 1110
3b0bd9bc 1111 if (type == 0)
2dd73a4f 1112 return rq->raw_weighted_load;
b910472d 1113
2dd73a4f 1114 return min(rq->cpu_load[type-1], rq->raw_weighted_load);
1da177e4
LT
1115}
1116
1117/*
2dd73a4f
PW
1118 * Return a high guess at the load of a migration-target cpu weighted
1119 * according to the scheduling class and "nice" value.
1da177e4 1120 */
a2000572 1121static inline unsigned long target_load(int cpu, int type)
1da177e4 1122{
70b97a7f 1123 struct rq *rq = cpu_rq(cpu);
2dd73a4f 1124
7897986b 1125 if (type == 0)
2dd73a4f 1126 return rq->raw_weighted_load;
3b0bd9bc 1127
2dd73a4f
PW
1128 return max(rq->cpu_load[type-1], rq->raw_weighted_load);
1129}
1130
1131/*
1132 * Return the average load per task on the cpu's run queue
1133 */
1134static inline unsigned long cpu_avg_load_per_task(int cpu)
1135{
70b97a7f 1136 struct rq *rq = cpu_rq(cpu);
2dd73a4f
PW
1137 unsigned long n = rq->nr_running;
1138
48f24c4d 1139 return n ? rq->raw_weighted_load / n : SCHED_LOAD_SCALE;
1da177e4
LT
1140}
1141
147cbb4b
NP
1142/*
1143 * find_idlest_group finds and returns the least busy CPU group within the
1144 * domain.
1145 */
1146static struct sched_group *
1147find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1148{
1149 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1150 unsigned long min_load = ULONG_MAX, this_load = 0;
1151 int load_idx = sd->forkexec_idx;
1152 int imbalance = 100 + (sd->imbalance_pct-100)/2;
1153
1154 do {
1155 unsigned long load, avg_load;
1156 int local_group;
1157 int i;
1158
da5a5522
BD
1159 /* Skip over this group if it has no CPUs allowed */
1160 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
1161 goto nextgroup;
1162
147cbb4b 1163 local_group = cpu_isset(this_cpu, group->cpumask);
147cbb4b
NP
1164
1165 /* Tally up the load of all CPUs in the group */
1166 avg_load = 0;
1167
1168 for_each_cpu_mask(i, group->cpumask) {
1169 /* Bias balancing toward cpus of our domain */
1170 if (local_group)
1171 load = source_load(i, load_idx);
1172 else
1173 load = target_load(i, load_idx);
1174
1175 avg_load += load;
1176 }
1177
1178 /* Adjust by relative CPU power of the group */
1179 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1180
1181 if (local_group) {
1182 this_load = avg_load;
1183 this = group;
1184 } else if (avg_load < min_load) {
1185 min_load = avg_load;
1186 idlest = group;
1187 }
da5a5522 1188nextgroup:
147cbb4b
NP
1189 group = group->next;
1190 } while (group != sd->groups);
1191
1192 if (!idlest || 100*this_load < imbalance*min_load)
1193 return NULL;
1194 return idlest;
1195}
1196
1197/*
1198 * find_idlest_queue - find the idlest runqueue among the cpus in group.
1199 */
95cdf3b7
IM
1200static int
1201find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
147cbb4b 1202{
da5a5522 1203 cpumask_t tmp;
147cbb4b
NP
1204 unsigned long load, min_load = ULONG_MAX;
1205 int idlest = -1;
1206 int i;
1207
da5a5522
BD
1208 /* Traverse only the allowed CPUs */
1209 cpus_and(tmp, group->cpumask, p->cpus_allowed);
1210
1211 for_each_cpu_mask(i, tmp) {
2dd73a4f 1212 load = weighted_cpuload(i);
147cbb4b
NP
1213
1214 if (load < min_load || (load == min_load && i == this_cpu)) {
1215 min_load = load;
1216 idlest = i;
1217 }
1218 }
1219
1220 return idlest;
1221}
1222
476d139c
NP
1223/*
1224 * sched_balance_self: balance the current task (running on cpu) in domains
1225 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1226 * SD_BALANCE_EXEC.
1227 *
1228 * Balance, ie. select the least loaded group.
1229 *
1230 * Returns the target CPU number, or the same CPU if no balancing is needed.
1231 *
1232 * preempt must be disabled.
1233 */
1234static int sched_balance_self(int cpu, int flag)
1235{
1236 struct task_struct *t = current;
1237 struct sched_domain *tmp, *sd = NULL;
147cbb4b 1238
c96d145e 1239 for_each_domain(cpu, tmp) {
5c45bf27
SS
1240 /*
1241 * If power savings logic is enabled for a domain, stop there.
1242 */
1243 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
1244 break;
476d139c
NP
1245 if (tmp->flags & flag)
1246 sd = tmp;
c96d145e 1247 }
476d139c
NP
1248
1249 while (sd) {
1250 cpumask_t span;
1251 struct sched_group *group;
1252 int new_cpu;
1253 int weight;
1254
1255 span = sd->span;
1256 group = find_idlest_group(sd, t, cpu);
1257 if (!group)
1258 goto nextlevel;
1259
da5a5522 1260 new_cpu = find_idlest_cpu(group, t, cpu);
476d139c
NP
1261 if (new_cpu == -1 || new_cpu == cpu)
1262 goto nextlevel;
1263
1264 /* Now try balancing at a lower domain level */
1265 cpu = new_cpu;
1266nextlevel:
1267 sd = NULL;
1268 weight = cpus_weight(span);
1269 for_each_domain(cpu, tmp) {
1270 if (weight <= cpus_weight(tmp->span))
1271 break;
1272 if (tmp->flags & flag)
1273 sd = tmp;
1274 }
1275 /* while loop will break here if sd == NULL */
1276 }
1277
1278 return cpu;
1279}
1280
1281#endif /* CONFIG_SMP */
1da177e4
LT
1282
1283/*
1284 * wake_idle() will wake a task on an idle cpu if task->cpu is
1285 * not idle and an idle cpu is available. The span of cpus to
1286 * search starts with cpus closest then further out as needed,
1287 * so we always favor a closer, idle cpu.
1288 *
1289 * Returns the CPU we should wake onto.
1290 */
1291#if defined(ARCH_HAS_SCHED_WAKE_IDLE)
36c8b586 1292static int wake_idle(int cpu, struct task_struct *p)
1da177e4
LT
1293{
1294 cpumask_t tmp;
1295 struct sched_domain *sd;
1296 int i;
1297
1298 if (idle_cpu(cpu))
1299 return cpu;
1300
1301 for_each_domain(cpu, sd) {
1302 if (sd->flags & SD_WAKE_IDLE) {
e0f364f4 1303 cpus_and(tmp, sd->span, p->cpus_allowed);
1da177e4
LT
1304 for_each_cpu_mask(i, tmp) {
1305 if (idle_cpu(i))
1306 return i;
1307 }
1308 }
e0f364f4
NP
1309 else
1310 break;
1da177e4
LT
1311 }
1312 return cpu;
1313}
1314#else
36c8b586 1315static inline int wake_idle(int cpu, struct task_struct *p)
1da177e4
LT
1316{
1317 return cpu;
1318}
1319#endif
1320
1321/***
1322 * try_to_wake_up - wake up a thread
1323 * @p: the to-be-woken-up thread
1324 * @state: the mask of task states that can be woken
1325 * @sync: do a synchronous wakeup?
1326 *
1327 * Put it on the run-queue if it's not already there. The "current"
1328 * thread is always on the run-queue (except when the actual
1329 * re-schedule is in progress), and as such you're allowed to do
1330 * the simpler "current->state = TASK_RUNNING" to mark yourself
1331 * runnable without the overhead of this.
1332 *
1333 * returns failure only if the task is already active.
1334 */
36c8b586 1335static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
1da177e4
LT
1336{
1337 int cpu, this_cpu, success = 0;
1338 unsigned long flags;
1339 long old_state;
70b97a7f 1340 struct rq *rq;
1da177e4 1341#ifdef CONFIG_SMP
7897986b 1342 struct sched_domain *sd, *this_sd = NULL;
70b97a7f 1343 unsigned long load, this_load;
1da177e4
LT
1344 int new_cpu;
1345#endif
1346
1347 rq = task_rq_lock(p, &flags);
1348 old_state = p->state;
1349 if (!(old_state & state))
1350 goto out;
1351
1352 if (p->array)
1353 goto out_running;
1354
1355 cpu = task_cpu(p);
1356 this_cpu = smp_processor_id();
1357
1358#ifdef CONFIG_SMP
1359 if (unlikely(task_running(rq, p)))
1360 goto out_activate;
1361
7897986b
NP
1362 new_cpu = cpu;
1363
1da177e4
LT
1364 schedstat_inc(rq, ttwu_cnt);
1365 if (cpu == this_cpu) {
1366 schedstat_inc(rq, ttwu_local);
7897986b
NP
1367 goto out_set_cpu;
1368 }
1369
1370 for_each_domain(this_cpu, sd) {
1371 if (cpu_isset(cpu, sd->span)) {
1372 schedstat_inc(sd, ttwu_wake_remote);
1373 this_sd = sd;
1374 break;
1da177e4
LT
1375 }
1376 }
1da177e4 1377
7897986b 1378 if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1da177e4
LT
1379 goto out_set_cpu;
1380
1da177e4 1381 /*
7897986b 1382 * Check for affine wakeup and passive balancing possibilities.
1da177e4 1383 */
7897986b
NP
1384 if (this_sd) {
1385 int idx = this_sd->wake_idx;
1386 unsigned int imbalance;
1da177e4 1387
a3f21bce
NP
1388 imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
1389
7897986b
NP
1390 load = source_load(cpu, idx);
1391 this_load = target_load(this_cpu, idx);
1da177e4 1392
7897986b
NP
1393 new_cpu = this_cpu; /* Wake to this CPU if we can */
1394
a3f21bce
NP
1395 if (this_sd->flags & SD_WAKE_AFFINE) {
1396 unsigned long tl = this_load;
2dd73a4f
PW
1397 unsigned long tl_per_task = cpu_avg_load_per_task(this_cpu);
1398
1da177e4 1399 /*
a3f21bce
NP
1400 * If sync wakeup then subtract the (maximum possible)
1401 * effect of the currently running task from the load
1402 * of the current CPU:
1da177e4 1403 */
a3f21bce 1404 if (sync)
2dd73a4f 1405 tl -= current->load_weight;
a3f21bce
NP
1406
1407 if ((tl <= load &&
2dd73a4f
PW
1408 tl + target_load(cpu, idx) <= tl_per_task) ||
1409 100*(tl + p->load_weight) <= imbalance*load) {
a3f21bce
NP
1410 /*
1411 * This domain has SD_WAKE_AFFINE and
1412 * p is cache cold in this domain, and
1413 * there is no bad imbalance.
1414 */
1415 schedstat_inc(this_sd, ttwu_move_affine);
1416 goto out_set_cpu;
1417 }
1418 }
1419
1420 /*
1421 * Start passive balancing when half the imbalance_pct
1422 * limit is reached.
1423 */
1424 if (this_sd->flags & SD_WAKE_BALANCE) {
1425 if (imbalance*this_load <= 100*load) {
1426 schedstat_inc(this_sd, ttwu_move_balance);
1427 goto out_set_cpu;
1428 }
1da177e4
LT
1429 }
1430 }
1431
1432 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1433out_set_cpu:
1434 new_cpu = wake_idle(new_cpu, p);
1435 if (new_cpu != cpu) {
1436 set_task_cpu(p, new_cpu);
1437 task_rq_unlock(rq, &flags);
1438 /* might preempt at this point */
1439 rq = task_rq_lock(p, &flags);
1440 old_state = p->state;
1441 if (!(old_state & state))
1442 goto out;
1443 if (p->array)
1444 goto out_running;
1445
1446 this_cpu = smp_processor_id();
1447 cpu = task_cpu(p);
1448 }
1449
1450out_activate:
1451#endif /* CONFIG_SMP */
1452 if (old_state == TASK_UNINTERRUPTIBLE) {
1453 rq->nr_uninterruptible--;
1454 /*
1455 * Tasks on involuntary sleep don't earn
1456 * sleep_avg beyond just interactive state.
1457 */
3dee386e 1458 p->sleep_type = SLEEP_NONINTERACTIVE;
e7c38cb4 1459 } else
1da177e4 1460
d79fc0fc
IM
1461 /*
1462 * Tasks that have marked their sleep as noninteractive get
e7c38cb4
CK
1463 * woken up with their sleep average not weighted in an
1464 * interactive way.
d79fc0fc 1465 */
e7c38cb4
CK
1466 if (old_state & TASK_NONINTERACTIVE)
1467 p->sleep_type = SLEEP_NONINTERACTIVE;
1468
1469
1470 activate_task(p, rq, cpu == this_cpu);
1da177e4
LT
1471 /*
1472 * Sync wakeups (i.e. those types of wakeups where the waker
1473 * has indicated that it will leave the CPU in short order)
1474 * don't trigger a preemption, if the woken up task will run on
1475 * this cpu. (in this case the 'I will reschedule' promise of
1476 * the waker guarantees that the freshly woken up task is going
1477 * to be considered on this CPU.)
1478 */
1da177e4
LT
1479 if (!sync || cpu != this_cpu) {
1480 if (TASK_PREEMPTS_CURR(p, rq))
1481 resched_task(rq->curr);
1482 }
1483 success = 1;
1484
1485out_running:
1486 p->state = TASK_RUNNING;
1487out:
1488 task_rq_unlock(rq, &flags);
1489
1490 return success;
1491}
1492
36c8b586 1493int fastcall wake_up_process(struct task_struct *p)
1da177e4
LT
1494{
1495 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1496 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1497}
1da177e4
LT
1498EXPORT_SYMBOL(wake_up_process);
1499
36c8b586 1500int fastcall wake_up_state(struct task_struct *p, unsigned int state)
1da177e4
LT
1501{
1502 return try_to_wake_up(p, state, 0);
1503}
1504
1da177e4
LT
1505/*
1506 * Perform scheduler related setup for a newly forked process p.
1507 * p is forked by current.
1508 */
36c8b586 1509void fastcall sched_fork(struct task_struct *p, int clone_flags)
1da177e4 1510{
476d139c
NP
1511 int cpu = get_cpu();
1512
1513#ifdef CONFIG_SMP
1514 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
1515#endif
1516 set_task_cpu(p, cpu);
1517
1da177e4
LT
1518 /*
1519 * We mark the process as running here, but have not actually
1520 * inserted it onto the runqueue yet. This guarantees that
1521 * nobody will actually run it, and a signal or other external
1522 * event cannot wake it up and insert it on the runqueue either.
1523 */
1524 p->state = TASK_RUNNING;
b29739f9
IM
1525
1526 /*
1527 * Make sure we do not leak PI boosting priority to the child:
1528 */
1529 p->prio = current->normal_prio;
1530
1da177e4
LT
1531 INIT_LIST_HEAD(&p->run_list);
1532 p->array = NULL;
1da177e4
LT
1533#ifdef CONFIG_SCHEDSTATS
1534 memset(&p->sched_info, 0, sizeof(p->sched_info));
1535#endif
d6077cb8 1536#if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
4866cde0
NP
1537 p->oncpu = 0;
1538#endif
1da177e4 1539#ifdef CONFIG_PREEMPT
4866cde0 1540 /* Want to start with kernel preemption disabled. */
a1261f54 1541 task_thread_info(p)->preempt_count = 1;
1da177e4
LT
1542#endif
1543 /*
1544 * Share the timeslice between parent and child, thus the
1545 * total amount of pending timeslices in the system doesn't change,
1546 * resulting in more scheduling fairness.
1547 */
1548 local_irq_disable();
1549 p->time_slice = (current->time_slice + 1) >> 1;
1550 /*
1551 * The remainder of the first timeslice might be recovered by
1552 * the parent if the child exits early enough.
1553 */
1554 p->first_time_slice = 1;
1555 current->time_slice >>= 1;
1556 p->timestamp = sched_clock();
1557 if (unlikely(!current->time_slice)) {
1558 /*
1559 * This case is rare, it happens when the parent has only
1560 * a single jiffy left from its timeslice. Taking the
1561 * runqueue lock is not a problem.
1562 */
1563 current->time_slice = 1;
1da177e4 1564 scheduler_tick();
476d139c
NP
1565 }
1566 local_irq_enable();
1567 put_cpu();
1da177e4
LT
1568}
1569
1570/*
1571 * wake_up_new_task - wake up a newly created task for the first time.
1572 *
1573 * This function will do some initial scheduler statistics housekeeping
1574 * that must be done for every newly created context, then puts the task
1575 * on the runqueue and wakes it.
1576 */
36c8b586 1577void fastcall wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
1da177e4 1578{
70b97a7f 1579 struct rq *rq, *this_rq;
1da177e4
LT
1580 unsigned long flags;
1581 int this_cpu, cpu;
1da177e4
LT
1582
1583 rq = task_rq_lock(p, &flags);
147cbb4b 1584 BUG_ON(p->state != TASK_RUNNING);
1da177e4 1585 this_cpu = smp_processor_id();
147cbb4b 1586 cpu = task_cpu(p);
1da177e4 1587
1da177e4
LT
1588 /*
1589 * We decrease the sleep average of forking parents
1590 * and children as well, to keep max-interactive tasks
1591 * from forking tasks that are max-interactive. The parent
1592 * (current) is done further down, under its lock.
1593 */
1594 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1595 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1596
1597 p->prio = effective_prio(p);
1598
1599 if (likely(cpu == this_cpu)) {
1600 if (!(clone_flags & CLONE_VM)) {
1601 /*
1602 * The VM isn't cloned, so we're in a good position to
1603 * do child-runs-first in anticipation of an exec. This
1604 * usually avoids a lot of COW overhead.
1605 */
1606 if (unlikely(!current->array))
1607 __activate_task(p, rq);
1608 else {
1609 p->prio = current->prio;
b29739f9 1610 p->normal_prio = current->normal_prio;
1da177e4
LT
1611 list_add_tail(&p->run_list, &current->run_list);
1612 p->array = current->array;
1613 p->array->nr_active++;
2dd73a4f 1614 inc_nr_running(p, rq);
1da177e4
LT
1615 }
1616 set_need_resched();
1617 } else
1618 /* Run child last */
1619 __activate_task(p, rq);
1620 /*
1621 * We skip the following code due to cpu == this_cpu
1622 *
1623 * task_rq_unlock(rq, &flags);
1624 * this_rq = task_rq_lock(current, &flags);
1625 */
1626 this_rq = rq;
1627 } else {
1628 this_rq = cpu_rq(this_cpu);
1629
1630 /*
1631 * Not the local CPU - must adjust timestamp. This should
1632 * get optimised away in the !CONFIG_SMP case.
1633 */
1634 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1635 + rq->timestamp_last_tick;
1636 __activate_task(p, rq);
1637 if (TASK_PREEMPTS_CURR(p, rq))
1638 resched_task(rq->curr);
1639
1640 /*
1641 * Parent and child are on different CPUs, now get the
1642 * parent runqueue to update the parent's ->sleep_avg:
1643 */
1644 task_rq_unlock(rq, &flags);
1645 this_rq = task_rq_lock(current, &flags);
1646 }
1647 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1648 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1649 task_rq_unlock(this_rq, &flags);
1650}
1651
1652/*
1653 * Potentially available exiting-child timeslices are
1654 * retrieved here - this way the parent does not get
1655 * penalized for creating too many threads.
1656 *
1657 * (this cannot be used to 'generate' timeslices
1658 * artificially, because any timeslice recovered here
1659 * was given away by the parent in the first place.)
1660 */
36c8b586 1661void fastcall sched_exit(struct task_struct *p)
1da177e4
LT
1662{
1663 unsigned long flags;
70b97a7f 1664 struct rq *rq;
1da177e4
LT
1665
1666 /*
1667 * If the child was a (relative-) CPU hog then decrease
1668 * the sleep_avg of the parent as well.
1669 */
1670 rq = task_rq_lock(p->parent, &flags);
889dfafe 1671 if (p->first_time_slice && task_cpu(p) == task_cpu(p->parent)) {
1da177e4
LT
1672 p->parent->time_slice += p->time_slice;
1673 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1674 p->parent->time_slice = task_timeslice(p);
1675 }
1676 if (p->sleep_avg < p->parent->sleep_avg)
1677 p->parent->sleep_avg = p->parent->sleep_avg /
1678 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1679 (EXIT_WEIGHT + 1);
1680 task_rq_unlock(rq, &flags);
1681}
1682
4866cde0
NP
1683/**
1684 * prepare_task_switch - prepare to switch tasks
1685 * @rq: the runqueue preparing to switch
1686 * @next: the task we are going to switch to.
1687 *
1688 * This is called with the rq lock held and interrupts off. It must
1689 * be paired with a subsequent finish_task_switch after the context
1690 * switch.
1691 *
1692 * prepare_task_switch sets up locking and calls architecture specific
1693 * hooks.
1694 */
70b97a7f 1695static inline void prepare_task_switch(struct rq *rq, struct task_struct *next)
4866cde0
NP
1696{
1697 prepare_lock_switch(rq, next);
1698 prepare_arch_switch(next);
1699}
1700
1da177e4
LT
1701/**
1702 * finish_task_switch - clean up after a task-switch
344babaa 1703 * @rq: runqueue associated with task-switch
1da177e4
LT
1704 * @prev: the thread we just switched away from.
1705 *
4866cde0
NP
1706 * finish_task_switch must be called after the context switch, paired
1707 * with a prepare_task_switch call before the context switch.
1708 * finish_task_switch will reconcile locking set up by prepare_task_switch,
1709 * and do any other architecture-specific cleanup actions.
1da177e4
LT
1710 *
1711 * Note that we may have delayed dropping an mm in context_switch(). If
1712 * so, we finish that here outside of the runqueue lock. (Doing it
1713 * with the lock held can cause deadlocks; see schedule() for
1714 * details.)
1715 */
70b97a7f 1716static inline void finish_task_switch(struct rq *rq, struct task_struct *prev)
1da177e4
LT
1717 __releases(rq->lock)
1718{
1da177e4
LT
1719 struct mm_struct *mm = rq->prev_mm;
1720 unsigned long prev_task_flags;
1721
1722 rq->prev_mm = NULL;
1723
1724 /*
1725 * A task struct has one reference for the use as "current".
1726 * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1727 * calls schedule one last time. The schedule call will never return,
1728 * and the scheduled task must drop that reference.
1729 * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1730 * still held, otherwise prev could be scheduled on another cpu, die
1731 * there before we look at prev->state, and then the reference would
1732 * be dropped twice.
1733 * Manfred Spraul <manfred@colorfullife.com>
1734 */
1735 prev_task_flags = prev->flags;
4866cde0
NP
1736 finish_arch_switch(prev);
1737 finish_lock_switch(rq, prev);
1da177e4
LT
1738 if (mm)
1739 mmdrop(mm);
c6fd91f0 1740 if (unlikely(prev_task_flags & PF_DEAD)) {
1741 /*
1742 * Remove function-return probe instances associated with this
1743 * task and put them back on the free list.
1744 */
1745 kprobe_flush_task(prev);
1da177e4 1746 put_task_struct(prev);
c6fd91f0 1747 }
1da177e4
LT
1748}
1749
1750/**
1751 * schedule_tail - first thing a freshly forked thread must call.
1752 * @prev: the thread we just switched away from.
1753 */
36c8b586 1754asmlinkage void schedule_tail(struct task_struct *prev)
1da177e4
LT
1755 __releases(rq->lock)
1756{
70b97a7f
IM
1757 struct rq *rq = this_rq();
1758
4866cde0
NP
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 1772static inline struct task_struct *
70b97a7f 1773context_switch(struct rq *rq, struct task_struct *prev,
36c8b586 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 */
70b97a7f 1886static void double_rq_lock(struct rq *rq1, struct rq *rq2)
1da177e4
LT
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 */
70b97a7f 1910static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
1da177e4
LT
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 */
70b97a7f 1924static void double_lock_balance(struct rq *this_rq, struct rq *busiest)
1da177e4
LT
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 1946{
70b97a7f 1947 struct migration_req req;
1da177e4 1948 unsigned long flags;
70b97a7f 1949 struct rq *rq;
1da177e4
LT
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 */
70b97a7f
IM
1990static void pull_task(struct rq *src_rq, struct prio_array *src_array,
1991 struct task_struct *p, struct rq *this_rq,
1992 struct prio_array *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
70b97a7f 2013int can_migrate_task(struct task_struct *p, struct rq *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 */
70b97a7f 2053static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *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;
70b97a7f 2060 struct prio_array *array, *dst_array;
1da177e4 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) {
70b97a7f 2215 struct rq *rq = cpu_rq(i);
2dd73a4f 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 */
70b97a7f 2431static struct rq *
48f24c4d
IM
2432find_busiest_queue(struct sched_group *group, enum idle_type idle,
2433 unsigned long imbalance)
1da177e4 2434{
70b97a7f 2435 struct rq *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 */
70b97a7f 2471static int load_balance(int this_cpu, struct rq *this_rq,
1da177e4
LT
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;
70b97a7f 2477 struct rq *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 2598static int
70b97a7f 2599load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
1da177e4
LT
2600{
2601 struct sched_group *group;
70b97a7f 2602 struct rq *busiest = NULL;
1da177e4
LT
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 */
70b97a7f 2660static void idle_balance(int this_cpu, struct rq *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 */
70b97a7f 2681static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
1da177e4 2682{
39507451 2683 int target_cpu = busiest_rq->push_cpu;
70b97a7f
IM
2684 struct sched_domain *sd;
2685 struct rq *target_rq;
39507451 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 2738static void
70b97a7f 2739rebalance_tick(int this_cpu, struct rq *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 */
70b97a7f 2793static inline void rebalance_tick(int cpu, struct rq *rq, enum idle_type idle)
1da177e4
LT
2794{
2795}
70b97a7f 2796static inline void idle_balance(int cpu, struct rq *rq)
1da177e4
LT
2797{
2798}
2799#endif
2800
70b97a7f 2801static inline int wake_priority_sleeper(struct rq *rq)
1da177e4
LT
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
70b97a7f 2829update_cpu_clock(struct task_struct *p, struct rq *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 */
70b97a7f 2861static inline int expired_starving(struct rq *rq)
48f24c4d
IM
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;
70b97a7f 2903 struct rq *rq = this_rq();
1da177e4
LT
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);
70b97a7f 2933 struct rq *rq = this_rq();
1da177e4
LT
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 2956 int cpu = smp_processor_id();
70b97a7f 2957 struct rq *rq = cpu_rq(cpu);
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
70b97a7f 3046static inline void wakeup_busy_runqueue(struct rq *rq)
fc38ed75
CK
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) {
70b97a7f 3072 struct rq *smt_rq = cpu_rq(i);
1da177e4 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 3101static int
70b97a7f 3102dependent_sleeper(int this_cpu, struct rq *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;
70b97a7f 3123 struct rq *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
70b97a7f 3169dependent_sleeper(int this_cpu, struct rq *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;
70b97a7f 3224 struct prio_array *array;
1da177e4
LT
3225 struct list_head *queue;
3226 unsigned long long now;
3227 unsigned long run_time;
a3464a10 3228 int cpu, idx, new_prio;
48f24c4d 3229 long *switch_count;
70b97a7f 3230 struct rq *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 3789{
70b97a7f 3790 struct prio_array *array;
b29739f9 3791 unsigned long flags;
70b97a7f 3792 struct rq *rq;
b29739f9
IM
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{
70b97a7f 3831 struct prio_array *array;
48f24c4d 3832 int old_prio, delta;
1da177e4 3833 unsigned long flags;
70b97a7f 3834 struct rq *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;
70b97a7f 4015 struct prio_array *array;
1da177e4 4016 unsigned long flags;
70b97a7f 4017 struct rq *rq;
1da177e4 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{
70b97a7f
IM
4379 struct rq *rq = this_rq_lock();
4380 struct prio_array *array = current->array, *target = rq->expired;
1da177e4
LT
4381
4382 schedstat_inc(rq, yld_cnt);
4383 /*
4384 * We implement yielding by moving the task into the expired
4385 * queue.
4386 *
4387 * (special rule: RT tasks will just roundrobin in the active
4388 * array.)
4389 */
4390 if (rt_task(current))
4391 target = rq->active;
4392
5927ad78 4393 if (array->nr_active == 1) {
1da177e4
LT
4394 schedstat_inc(rq, yld_act_empty);
4395 if (!rq->expired->nr_active)
4396 schedstat_inc(rq, yld_both_empty);
4397 } else if (!rq->expired->nr_active)
4398 schedstat_inc(rq, yld_exp_empty);
4399
4400 if (array != target) {
4401 dequeue_task(current, array);
4402 enqueue_task(current, target);
4403 } else
4404 /*
4405 * requeue_task is cheaper so perform that if possible.
4406 */
4407 requeue_task(current, array);
4408
4409 /*
4410 * Since we are going to call schedule() anyway, there's
4411 * no need to preempt or enable interrupts:
4412 */
4413 __release(rq->lock);
8a25d5de 4414 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
1da177e4
LT
4415 _raw_spin_unlock(&rq->lock);
4416 preempt_enable_no_resched();
4417
4418 schedule();
4419
4420 return 0;
4421}
4422
e7b38404
AM
4423static inline int __resched_legal(void)
4424{
4425 if (unlikely(preempt_count()))
4426 return 0;
4427 if (unlikely(system_state != SYSTEM_RUNNING))
4428 return 0;
4429 return 1;
4430}
4431
4432static void __cond_resched(void)
1da177e4 4433{
8e0a43d8
IM
4434#ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4435 __might_sleep(__FILE__, __LINE__);
4436#endif
5bbcfd90
IM
4437 /*
4438 * The BKS might be reacquired before we have dropped
4439 * PREEMPT_ACTIVE, which could trigger a second
4440 * cond_resched() call.
4441 */
1da177e4
LT
4442 do {
4443 add_preempt_count(PREEMPT_ACTIVE);
4444 schedule();
4445 sub_preempt_count(PREEMPT_ACTIVE);
4446 } while (need_resched());
4447}
4448
4449int __sched cond_resched(void)
4450{
e7b38404 4451 if (need_resched() && __resched_legal()) {
1da177e4
LT
4452 __cond_resched();
4453 return 1;
4454 }
4455 return 0;
4456}
1da177e4
LT
4457EXPORT_SYMBOL(cond_resched);
4458
4459/*
4460 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4461 * call schedule, and on return reacquire the lock.
4462 *
4463 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4464 * operations here to prevent schedule() from being called twice (once via
4465 * spin_unlock(), once by hand).
4466 */
95cdf3b7 4467int cond_resched_lock(spinlock_t *lock)
1da177e4 4468{
6df3cecb
JK
4469 int ret = 0;
4470
1da177e4
LT
4471 if (need_lockbreak(lock)) {
4472 spin_unlock(lock);
4473 cpu_relax();
6df3cecb 4474 ret = 1;
1da177e4
LT
4475 spin_lock(lock);
4476 }
e7b38404 4477 if (need_resched() && __resched_legal()) {
8a25d5de 4478 spin_release(&lock->dep_map, 1, _THIS_IP_);
1da177e4
LT
4479 _raw_spin_unlock(lock);
4480 preempt_enable_no_resched();
4481 __cond_resched();
6df3cecb 4482 ret = 1;
1da177e4 4483 spin_lock(lock);
1da177e4 4484 }
6df3cecb 4485 return ret;
1da177e4 4486}
1da177e4
LT
4487EXPORT_SYMBOL(cond_resched_lock);
4488
4489int __sched cond_resched_softirq(void)
4490{
4491 BUG_ON(!in_softirq());
4492
e7b38404 4493 if (need_resched() && __resched_legal()) {
de30a2b3
IM
4494 raw_local_irq_disable();
4495 _local_bh_enable();
4496 raw_local_irq_enable();
1da177e4
LT
4497 __cond_resched();
4498 local_bh_disable();
4499 return 1;
4500 }
4501 return 0;
4502}
1da177e4
LT
4503EXPORT_SYMBOL(cond_resched_softirq);
4504
1da177e4
LT
4505/**
4506 * yield - yield the current processor to other threads.
4507 *
4508 * this is a shortcut for kernel-space yielding - it marks the
4509 * thread runnable and calls sys_sched_yield().
4510 */
4511void __sched yield(void)
4512{
4513 set_current_state(TASK_RUNNING);
4514 sys_sched_yield();
4515}
1da177e4
LT
4516EXPORT_SYMBOL(yield);
4517
4518/*
4519 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4520 * that process accounting knows that this is a task in IO wait state.
4521 *
4522 * But don't do that if it is a deliberate, throttling IO wait (this task
4523 * has set its backing_dev_info: the queue against which it should throttle)
4524 */
4525void __sched io_schedule(void)
4526{
70b97a7f 4527 struct rq *rq = &__raw_get_cpu_var(runqueues);
1da177e4
LT
4528
4529 atomic_inc(&rq->nr_iowait);
4530 schedule();
4531 atomic_dec(&rq->nr_iowait);
4532}
1da177e4
LT
4533EXPORT_SYMBOL(io_schedule);
4534
4535long __sched io_schedule_timeout(long timeout)
4536{
70b97a7f 4537 struct rq *rq = &__raw_get_cpu_var(runqueues);
1da177e4
LT
4538 long ret;
4539
4540 atomic_inc(&rq->nr_iowait);
4541 ret = schedule_timeout(timeout);
4542 atomic_dec(&rq->nr_iowait);
4543 return ret;
4544}
4545
4546/**
4547 * sys_sched_get_priority_max - return maximum RT priority.
4548 * @policy: scheduling class.
4549 *
4550 * this syscall returns the maximum rt_priority that can be used
4551 * by a given scheduling class.
4552 */
4553asmlinkage long sys_sched_get_priority_max(int policy)
4554{
4555 int ret = -EINVAL;
4556
4557 switch (policy) {
4558 case SCHED_FIFO:
4559 case SCHED_RR:
4560 ret = MAX_USER_RT_PRIO-1;
4561 break;
4562 case SCHED_NORMAL:
b0a9499c 4563 case SCHED_BATCH:
1da177e4
LT
4564 ret = 0;
4565 break;
4566 }
4567 return ret;
4568}
4569
4570/**
4571 * sys_sched_get_priority_min - return minimum RT priority.
4572 * @policy: scheduling class.
4573 *
4574 * this syscall returns the minimum rt_priority that can be used
4575 * by a given scheduling class.
4576 */
4577asmlinkage long sys_sched_get_priority_min(int policy)
4578{
4579 int ret = -EINVAL;
4580
4581 switch (policy) {
4582 case SCHED_FIFO:
4583 case SCHED_RR:
4584 ret = 1;
4585 break;
4586 case SCHED_NORMAL:
b0a9499c 4587 case SCHED_BATCH:
1da177e4
LT
4588 ret = 0;
4589 }
4590 return ret;
4591}
4592
4593/**
4594 * sys_sched_rr_get_interval - return the default timeslice of a process.
4595 * @pid: pid of the process.
4596 * @interval: userspace pointer to the timeslice value.
4597 *
4598 * this syscall writes the default timeslice value of a given process
4599 * into the user-space timespec buffer. A value of '0' means infinity.
4600 */
4601asmlinkage
4602long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4603{
36c8b586 4604 struct task_struct *p;
1da177e4
LT
4605 int retval = -EINVAL;
4606 struct timespec t;
1da177e4
LT
4607
4608 if (pid < 0)
4609 goto out_nounlock;
4610
4611 retval = -ESRCH;
4612 read_lock(&tasklist_lock);
4613 p = find_process_by_pid(pid);
4614 if (!p)
4615 goto out_unlock;
4616
4617 retval = security_task_getscheduler(p);
4618 if (retval)
4619 goto out_unlock;
4620
b78709cf 4621 jiffies_to_timespec(p->policy == SCHED_FIFO ?
1da177e4
LT
4622 0 : task_timeslice(p), &t);
4623 read_unlock(&tasklist_lock);
4624 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4625out_nounlock:
4626 return retval;
4627out_unlock:
4628 read_unlock(&tasklist_lock);
4629 return retval;
4630}
4631
4632static inline struct task_struct *eldest_child(struct task_struct *p)
4633{
48f24c4d
IM
4634 if (list_empty(&p->children))
4635 return NULL;
1da177e4
LT
4636 return list_entry(p->children.next,struct task_struct,sibling);
4637}
4638
4639static inline struct task_struct *older_sibling(struct task_struct *p)
4640{
48f24c4d
IM
4641 if (p->sibling.prev==&p->parent->children)
4642 return NULL;
1da177e4
LT
4643 return list_entry(p->sibling.prev,struct task_struct,sibling);
4644}
4645
4646static inline struct task_struct *younger_sibling(struct task_struct *p)
4647{
48f24c4d
IM
4648 if (p->sibling.next==&p->parent->children)
4649 return NULL;
1da177e4
LT
4650 return list_entry(p->sibling.next,struct task_struct,sibling);
4651}
4652
36c8b586
IM
4653static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
4654
4655static void show_task(struct task_struct *p)
1da177e4 4656{
36c8b586 4657 struct task_struct *relative;
1da177e4 4658 unsigned long free = 0;
36c8b586 4659 unsigned state;
1da177e4
LT
4660
4661 printk("%-13.13s ", p->comm);
4662 state = p->state ? __ffs(p->state) + 1 : 0;
4663 if (state < ARRAY_SIZE(stat_nam))
4664 printk(stat_nam[state]);
4665 else
4666 printk("?");
4667#if (BITS_PER_LONG == 32)
4668 if (state == TASK_RUNNING)
4669 printk(" running ");
4670 else
4671 printk(" %08lX ", thread_saved_pc(p));
4672#else
4673 if (state == TASK_RUNNING)
4674 printk(" running task ");
4675 else
4676 printk(" %016lx ", thread_saved_pc(p));
4677#endif
4678#ifdef CONFIG_DEBUG_STACK_USAGE
4679 {
10ebffde 4680 unsigned long *n = end_of_stack(p);
1da177e4
LT
4681 while (!*n)
4682 n++;
10ebffde 4683 free = (unsigned long)n - (unsigned long)end_of_stack(p);
1da177e4
LT
4684 }
4685#endif
4686 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
4687 if ((relative = eldest_child(p)))
4688 printk("%5d ", relative->pid);
4689 else
4690 printk(" ");
4691 if ((relative = younger_sibling(p)))
4692 printk("%7d", relative->pid);
4693 else
4694 printk(" ");
4695 if ((relative = older_sibling(p)))
4696 printk(" %5d", relative->pid);
4697 else
4698 printk(" ");
4699 if (!p->mm)
4700 printk(" (L-TLB)\n");
4701 else
4702 printk(" (NOTLB)\n");
4703
4704 if (state != TASK_RUNNING)
4705 show_stack(p, NULL);
4706}
4707
4708void show_state(void)
4709{
36c8b586 4710 struct task_struct *g, *p;
1da177e4
LT
4711
4712#if (BITS_PER_LONG == 32)
4713 printk("\n"
4714 " sibling\n");
4715 printk(" task PC pid father child younger older\n");
4716#else
4717 printk("\n"
4718 " sibling\n");
4719 printk(" task PC pid father child younger older\n");
4720#endif
4721 read_lock(&tasklist_lock);
4722 do_each_thread(g, p) {
4723 /*
4724 * reset the NMI-timeout, listing all files on a slow
4725 * console might take alot of time:
4726 */
4727 touch_nmi_watchdog();
4728 show_task(p);
4729 } while_each_thread(g, p);
4730
4731 read_unlock(&tasklist_lock);
9a11b49a 4732 debug_show_all_locks();
1da177e4
LT
4733}
4734
f340c0d1
IM
4735/**
4736 * init_idle - set up an idle thread for a given CPU
4737 * @idle: task in question
4738 * @cpu: cpu the idle task belongs to
4739 *
4740 * NOTE: this function does not set the idle thread's NEED_RESCHED
4741 * flag, to make booting more robust.
4742 */
36c8b586 4743void __devinit init_idle(struct task_struct *idle, int cpu)
1da177e4 4744{
70b97a7f 4745 struct rq *rq = cpu_rq(cpu);
1da177e4
LT
4746 unsigned long flags;
4747
81c29a85 4748 idle->timestamp = sched_clock();
1da177e4
LT
4749 idle->sleep_avg = 0;
4750 idle->array = NULL;
b29739f9 4751 idle->prio = idle->normal_prio = MAX_PRIO;
1da177e4
LT
4752 idle->state = TASK_RUNNING;
4753 idle->cpus_allowed = cpumask_of_cpu(cpu);
4754 set_task_cpu(idle, cpu);
4755
4756 spin_lock_irqsave(&rq->lock, flags);
4757 rq->curr = rq->idle = idle;
4866cde0
NP
4758#if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
4759 idle->oncpu = 1;
4760#endif
1da177e4
LT
4761 spin_unlock_irqrestore(&rq->lock, flags);
4762
4763 /* Set the preempt count _outside_ the spinlocks! */
4764#if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
a1261f54 4765 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
1da177e4 4766#else
a1261f54 4767 task_thread_info(idle)->preempt_count = 0;
1da177e4
LT
4768#endif
4769}
4770
4771/*
4772 * In a system that switches off the HZ timer nohz_cpu_mask
4773 * indicates which cpus entered this state. This is used
4774 * in the rcu update to wait only for active cpus. For system
4775 * which do not switch off the HZ timer nohz_cpu_mask should
4776 * always be CPU_MASK_NONE.
4777 */
4778cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4779
4780#ifdef CONFIG_SMP
4781/*
4782 * This is how migration works:
4783 *
70b97a7f 4784 * 1) we queue a struct migration_req structure in the source CPU's
1da177e4
LT
4785 * runqueue and wake up that CPU's migration thread.
4786 * 2) we down() the locked semaphore => thread blocks.
4787 * 3) migration thread wakes up (implicitly it forces the migrated
4788 * thread off the CPU)
4789 * 4) it gets the migration request and checks whether the migrated
4790 * task is still in the wrong runqueue.
4791 * 5) if it's in the wrong runqueue then the migration thread removes
4792 * it and puts it into the right queue.
4793 * 6) migration thread up()s the semaphore.
4794 * 7) we wake up and the migration is done.
4795 */
4796
4797/*
4798 * Change a given task's CPU affinity. Migrate the thread to a
4799 * proper CPU and schedule it away if the CPU it's executing on
4800 * is removed from the allowed bitmask.
4801 *
4802 * NOTE: the caller must have a valid reference to the task, the
4803 * task must not exit() & deallocate itself prematurely. The
4804 * call is not atomic; no spinlocks may be held.
4805 */
36c8b586 4806int set_cpus_allowed(struct task_struct *p, cpumask_t new_mask)
1da177e4 4807{
70b97a7f 4808 struct migration_req req;
1da177e4 4809 unsigned long flags;
70b97a7f 4810 struct rq *rq;
48f24c4d 4811 int ret = 0;
1da177e4
LT
4812
4813 rq = task_rq_lock(p, &flags);
4814 if (!cpus_intersects(new_mask, cpu_online_map)) {
4815 ret = -EINVAL;
4816 goto out;
4817 }
4818
4819 p->cpus_allowed = new_mask;
4820 /* Can the task run on the task's current CPU? If so, we're done */
4821 if (cpu_isset(task_cpu(p), new_mask))
4822 goto out;
4823
4824 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4825 /* Need help from migration thread: drop lock and wait. */
4826 task_rq_unlock(rq, &flags);
4827 wake_up_process(rq->migration_thread);
4828 wait_for_completion(&req.done);
4829 tlb_migrate_finish(p->mm);
4830 return 0;
4831 }
4832out:
4833 task_rq_unlock(rq, &flags);
48f24c4d 4834
1da177e4
LT
4835 return ret;
4836}
1da177e4
LT
4837EXPORT_SYMBOL_GPL(set_cpus_allowed);
4838
4839/*
4840 * Move (not current) task off this cpu, onto dest cpu. We're doing
4841 * this because either it can't run here any more (set_cpus_allowed()
4842 * away from this CPU, or CPU going down), or because we're
4843 * attempting to rebalance this task on exec (sched_exec).
4844 *
4845 * So we race with normal scheduler movements, but that's OK, as long
4846 * as the task is no longer on this CPU.
efc30814
KK
4847 *
4848 * Returns non-zero if task was successfully migrated.
1da177e4 4849 */
efc30814 4850static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
1da177e4 4851{
70b97a7f 4852 struct rq *rq_dest, *rq_src;
efc30814 4853 int ret = 0;
1da177e4
LT
4854
4855 if (unlikely(cpu_is_offline(dest_cpu)))
efc30814 4856 return ret;
1da177e4
LT
4857
4858 rq_src = cpu_rq(src_cpu);
4859 rq_dest = cpu_rq(dest_cpu);
4860
4861 double_rq_lock(rq_src, rq_dest);
4862 /* Already moved. */
4863 if (task_cpu(p) != src_cpu)
4864 goto out;
4865 /* Affinity changed (again). */
4866 if (!cpu_isset(dest_cpu, p->cpus_allowed))
4867 goto out;
4868
4869 set_task_cpu(p, dest_cpu);
4870 if (p->array) {
4871 /*
4872 * Sync timestamp with rq_dest's before activating.
4873 * The same thing could be achieved by doing this step
4874 * afterwards, and pretending it was a local activate.
4875 * This way is cleaner and logically correct.
4876 */
4877 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4878 + rq_dest->timestamp_last_tick;
4879 deactivate_task(p, rq_src);
4880 activate_task(p, rq_dest, 0);
4881 if (TASK_PREEMPTS_CURR(p, rq_dest))
4882 resched_task(rq_dest->curr);
4883 }
efc30814 4884 ret = 1;
1da177e4
LT
4885out:
4886 double_rq_unlock(rq_src, rq_dest);
efc30814 4887 return ret;
1da177e4
LT
4888}
4889
4890/*
4891 * migration_thread - this is a highprio system thread that performs
4892 * thread migration by bumping thread off CPU then 'pushing' onto
4893 * another runqueue.
4894 */
95cdf3b7 4895static int migration_thread(void *data)
1da177e4 4896{
1da177e4 4897 int cpu = (long)data;
70b97a7f 4898 struct rq *rq;
1da177e4
LT
4899
4900 rq = cpu_rq(cpu);
4901 BUG_ON(rq->migration_thread != current);
4902
4903 set_current_state(TASK_INTERRUPTIBLE);
4904 while (!kthread_should_stop()) {
70b97a7f 4905 struct migration_req *req;
1da177e4 4906 struct list_head *head;
1da177e4 4907
3e1d1d28 4908 try_to_freeze();
1da177e4
LT
4909
4910 spin_lock_irq(&rq->lock);
4911
4912 if (cpu_is_offline(cpu)) {
4913 spin_unlock_irq(&rq->lock);
4914 goto wait_to_die;
4915 }
4916
4917 if (rq->active_balance) {
4918 active_load_balance(rq, cpu);
4919 rq->active_balance = 0;
4920 }
4921
4922 head = &rq->migration_queue;
4923
4924 if (list_empty(head)) {
4925 spin_unlock_irq(&rq->lock);
4926 schedule();
4927 set_current_state(TASK_INTERRUPTIBLE);
4928 continue;
4929 }
70b97a7f 4930 req = list_entry(head->next, struct migration_req, list);
1da177e4
LT
4931 list_del_init(head->next);
4932
674311d5
NP
4933 spin_unlock(&rq->lock);
4934 __migrate_task(req->task, cpu, req->dest_cpu);
4935 local_irq_enable();
1da177e4
LT
4936
4937 complete(&req->done);
4938 }
4939 __set_current_state(TASK_RUNNING);
4940 return 0;
4941
4942wait_to_die:
4943 /* Wait for kthread_stop */
4944 set_current_state(TASK_INTERRUPTIBLE);
4945 while (!kthread_should_stop()) {
4946 schedule();
4947 set_current_state(TASK_INTERRUPTIBLE);
4948 }
4949 __set_current_state(TASK_RUNNING);
4950 return 0;
4951}
4952
4953#ifdef CONFIG_HOTPLUG_CPU
4954/* Figure out where task on dead CPU should go, use force if neccessary. */
48f24c4d 4955static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
1da177e4 4956{
efc30814 4957 unsigned long flags;
1da177e4 4958 cpumask_t mask;
70b97a7f
IM
4959 struct rq *rq;
4960 int dest_cpu;
1da177e4 4961
efc30814 4962restart:
1da177e4
LT
4963 /* On same node? */
4964 mask = node_to_cpumask(cpu_to_node(dead_cpu));
48f24c4d 4965 cpus_and(mask, mask, p->cpus_allowed);
1da177e4
LT
4966 dest_cpu = any_online_cpu(mask);
4967
4968 /* On any allowed CPU? */
4969 if (dest_cpu == NR_CPUS)
48f24c4d 4970 dest_cpu = any_online_cpu(p->cpus_allowed);
1da177e4
LT
4971
4972 /* No more Mr. Nice Guy. */
4973 if (dest_cpu == NR_CPUS) {
48f24c4d
IM
4974 rq = task_rq_lock(p, &flags);
4975 cpus_setall(p->cpus_allowed);
4976 dest_cpu = any_online_cpu(p->cpus_allowed);
efc30814 4977 task_rq_unlock(rq, &flags);
1da177e4
LT
4978
4979 /*
4980 * Don't tell them about moving exiting tasks or
4981 * kernel threads (both mm NULL), since they never
4982 * leave kernel.
4983 */
48f24c4d 4984 if (p->mm && printk_ratelimit())
1da177e4
LT
4985 printk(KERN_INFO "process %d (%s) no "
4986 "longer affine to cpu%d\n",
48f24c4d 4987 p->pid, p->comm, dead_cpu);
1da177e4 4988 }
48f24c4d 4989 if (!__migrate_task(p, dead_cpu, dest_cpu))
efc30814 4990 goto restart;
1da177e4
LT
4991}
4992
4993/*
4994 * While a dead CPU has no uninterruptible tasks queued at this point,
4995 * it might still have a nonzero ->nr_uninterruptible counter, because
4996 * for performance reasons the counter is not stricly tracking tasks to
4997 * their home CPUs. So we just add the counter to another CPU's counter,
4998 * to keep the global sum constant after CPU-down:
4999 */
70b97a7f 5000static void migrate_nr_uninterruptible(struct rq *rq_src)
1da177e4 5001{
70b97a7f 5002 struct rq *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
1da177e4
LT
5003 unsigned long flags;
5004
5005 local_irq_save(flags);
5006 double_rq_lock(rq_src, rq_dest);
5007 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5008 rq_src->nr_uninterruptible = 0;
5009 double_rq_unlock(rq_src, rq_dest);
5010 local_irq_restore(flags);
5011}
5012
5013/* Run through task list and migrate tasks from the dead cpu. */
5014static void migrate_live_tasks(int src_cpu)
5015{
48f24c4d 5016 struct task_struct *p, *t;
1da177e4
LT
5017
5018 write_lock_irq(&tasklist_lock);
5019
48f24c4d
IM
5020 do_each_thread(t, p) {
5021 if (p == current)
1da177e4
LT
5022 continue;
5023
48f24c4d
IM
5024 if (task_cpu(p) == src_cpu)
5025 move_task_off_dead_cpu(src_cpu, p);
5026 } while_each_thread(t, p);
1da177e4
LT
5027
5028 write_unlock_irq(&tasklist_lock);
5029}
5030
5031/* Schedules idle task to be the next runnable task on current CPU.
5032 * It does so by boosting its priority to highest possible and adding it to
48f24c4d 5033 * the _front_ of the runqueue. Used by CPU offline code.
1da177e4
LT
5034 */
5035void sched_idle_next(void)
5036{
48f24c4d 5037 int this_cpu = smp_processor_id();
70b97a7f 5038 struct rq *rq = cpu_rq(this_cpu);
1da177e4
LT
5039 struct task_struct *p = rq->idle;
5040 unsigned long flags;
5041
5042 /* cpu has to be offline */
48f24c4d 5043 BUG_ON(cpu_online(this_cpu));
1da177e4 5044
48f24c4d
IM
5045 /*
5046 * Strictly not necessary since rest of the CPUs are stopped by now
5047 * and interrupts disabled on the current cpu.
1da177e4
LT
5048 */
5049 spin_lock_irqsave(&rq->lock, flags);
5050
5051 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
48f24c4d
IM
5052
5053 /* Add idle task to the _front_ of its priority queue: */
1da177e4
LT
5054 __activate_idle_task(p, rq);
5055
5056 spin_unlock_irqrestore(&rq->lock, flags);
5057}
5058
48f24c4d
IM
5059/*
5060 * Ensures that the idle task is using init_mm right before its cpu goes
1da177e4
LT
5061 * offline.
5062 */
5063void idle_task_exit(void)
5064{
5065 struct mm_struct *mm = current->active_mm;
5066
5067 BUG_ON(cpu_online(smp_processor_id()));
5068
5069 if (mm != &init_mm)
5070 switch_mm(mm, &init_mm, current);
5071 mmdrop(mm);
5072}
5073
36c8b586 5074static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
1da177e4 5075{
70b97a7f 5076 struct rq *rq = cpu_rq(dead_cpu);
1da177e4
LT
5077
5078 /* Must be exiting, otherwise would be on tasklist. */
48f24c4d 5079 BUG_ON(p->exit_state != EXIT_ZOMBIE && p->exit_state != EXIT_DEAD);
1da177e4
LT
5080
5081 /* Cannot have done final schedule yet: would have vanished. */
48f24c4d 5082 BUG_ON(p->flags & PF_DEAD);
1da177e4 5083
48f24c4d 5084 get_task_struct(p);
1da177e4
LT
5085
5086 /*
5087 * Drop lock around migration; if someone else moves it,
5088 * that's OK. No task can be added to this CPU, so iteration is
5089 * fine.
5090 */
5091 spin_unlock_irq(&rq->lock);
48f24c4d 5092 move_task_off_dead_cpu(dead_cpu, p);
1da177e4
LT
5093 spin_lock_irq(&rq->lock);
5094
48f24c4d 5095 put_task_struct(p);
1da177e4
LT
5096}
5097
5098/* release_task() removes task from tasklist, so we won't find dead tasks. */
5099static void migrate_dead_tasks(unsigned int dead_cpu)
5100{
70b97a7f 5101 struct rq *rq = cpu_rq(dead_cpu);
48f24c4d 5102 unsigned int arr, i;
1da177e4
LT
5103
5104 for (arr = 0; arr < 2; arr++) {
5105 for (i = 0; i < MAX_PRIO; i++) {
5106 struct list_head *list = &rq->arrays[arr].queue[i];
48f24c4d 5107
1da177e4 5108 while (!list_empty(list))
36c8b586
IM
5109 migrate_dead(dead_cpu, list_entry(list->next,
5110 struct task_struct, run_list));
1da177e4
LT
5111 }
5112 }
5113}
5114#endif /* CONFIG_HOTPLUG_CPU */
5115
5116/*
5117 * migration_call - callback that gets triggered when a CPU is added.
5118 * Here we can start up the necessary migration thread for the new CPU.
5119 */
48f24c4d
IM
5120static int __cpuinit
5121migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
1da177e4 5122{
1da177e4 5123 struct task_struct *p;
48f24c4d 5124 int cpu = (long)hcpu;
1da177e4 5125 unsigned long flags;
70b97a7f 5126 struct rq *rq;
1da177e4
LT
5127
5128 switch (action) {
5129 case CPU_UP_PREPARE:
5130 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
5131 if (IS_ERR(p))
5132 return NOTIFY_BAD;
5133 p->flags |= PF_NOFREEZE;
5134 kthread_bind(p, cpu);
5135 /* Must be high prio: stop_machine expects to yield to it. */
5136 rq = task_rq_lock(p, &flags);
5137 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
5138 task_rq_unlock(rq, &flags);
5139 cpu_rq(cpu)->migration_thread = p;
5140 break;
48f24c4d 5141
1da177e4
LT
5142 case CPU_ONLINE:
5143 /* Strictly unneccessary, as first user will wake it. */
5144 wake_up_process(cpu_rq(cpu)->migration_thread);
5145 break;
48f24c4d 5146
1da177e4
LT
5147#ifdef CONFIG_HOTPLUG_CPU
5148 case CPU_UP_CANCELED:
fc75cdfa
HC
5149 if (!cpu_rq(cpu)->migration_thread)
5150 break;
1da177e4 5151 /* Unbind it from offline cpu so it can run. Fall thru. */
a4c4af7c
HC
5152 kthread_bind(cpu_rq(cpu)->migration_thread,
5153 any_online_cpu(cpu_online_map));
1da177e4
LT
5154 kthread_stop(cpu_rq(cpu)->migration_thread);
5155 cpu_rq(cpu)->migration_thread = NULL;
5156 break;
48f24c4d 5157
1da177e4
LT
5158 case CPU_DEAD:
5159 migrate_live_tasks(cpu);
5160 rq = cpu_rq(cpu);
5161 kthread_stop(rq->migration_thread);
5162 rq->migration_thread = NULL;
5163 /* Idle task back to normal (off runqueue, low prio) */
5164 rq = task_rq_lock(rq->idle, &flags);
5165 deactivate_task(rq->idle, rq);
5166 rq->idle->static_prio = MAX_PRIO;
5167 __setscheduler(rq->idle, SCHED_NORMAL, 0);
5168 migrate_dead_tasks(cpu);
5169 task_rq_unlock(rq, &flags);
5170 migrate_nr_uninterruptible(rq);
5171 BUG_ON(rq->nr_running != 0);
5172
5173 /* No need to migrate the tasks: it was best-effort if
5174 * they didn't do lock_cpu_hotplug(). Just wake up
5175 * the requestors. */
5176 spin_lock_irq(&rq->lock);
5177 while (!list_empty(&rq->migration_queue)) {
70b97a7f
IM
5178 struct migration_req *req;
5179
1da177e4 5180 req = list_entry(rq->migration_queue.next,
70b97a7f 5181 struct migration_req, 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{
70b97a7f 5364 struct rq *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
AM
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
AM
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
AM
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
AM
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
AM
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
AM
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
AM
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) {
70b97a7f
IM
6693 struct prio_array *array;
6694 struct rq *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{
70b97a7f 6767 struct prio_array *array;
1da177e4 6768 struct task_struct *p;
1da177e4 6769 unsigned long flags;
70b97a7f 6770 struct rq *rq;
1da177e4
LT
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