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