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