[PATCH] sched: tweak affine wakeups
[pandora-kernel.git] / kernel / sched.c
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>
30 #include <linux/completion.h>
31 #include <linux/kernel_stat.h>
32 #include <linux/security.h>
33 #include <linux/notifier.h>
34 #include <linux/profile.h>
35 #include <linux/suspend.h>
36 #include <linux/blkdev.h>
37 #include <linux/delay.h>
38 #include <linux/smp.h>
39 #include <linux/threads.h>
40 #include <linux/timer.h>
41 #include <linux/rcupdate.h>
42 #include <linux/cpu.h>
43 #include <linux/cpuset.h>
44 #include <linux/percpu.h>
45 #include <linux/kthread.h>
46 #include <linux/seq_file.h>
47 #include <linux/syscalls.h>
48 #include <linux/times.h>
49 #include <linux/acct.h>
50 #include <asm/tlb.h>
51
52 #include <asm/unistd.h>
53
54 /*
55  * Convert user-nice values [ -20 ... 0 ... 19 ]
56  * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
57  * and back.
58  */
59 #define NICE_TO_PRIO(nice)      (MAX_RT_PRIO + (nice) + 20)
60 #define PRIO_TO_NICE(prio)      ((prio) - MAX_RT_PRIO - 20)
61 #define TASK_NICE(p)            PRIO_TO_NICE((p)->static_prio)
62
63 /*
64  * 'User priority' is the nice value converted to something we
65  * can work with better when scaling various scheduler parameters,
66  * it's a [ 0 ... 39 ] range.
67  */
68 #define USER_PRIO(p)            ((p)-MAX_RT_PRIO)
69 #define TASK_USER_PRIO(p)       USER_PRIO((p)->static_prio)
70 #define MAX_USER_PRIO           (USER_PRIO(MAX_PRIO))
71
72 /*
73  * Some helpers for converting nanosecond timing to jiffy resolution
74  */
75 #define NS_TO_JIFFIES(TIME)     ((TIME) / (1000000000 / HZ))
76 #define JIFFIES_TO_NS(TIME)     ((TIME) * (1000000000 / HZ))
77
78 /*
79  * These are the 'tuning knobs' of the scheduler:
80  *
81  * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
82  * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
83  * Timeslices get refilled after they expire.
84  */
85 #define MIN_TIMESLICE           max(5 * HZ / 1000, 1)
86 #define DEF_TIMESLICE           (100 * HZ / 1000)
87 #define ON_RUNQUEUE_WEIGHT       30
88 #define CHILD_PENALTY            95
89 #define PARENT_PENALTY          100
90 #define EXIT_WEIGHT               3
91 #define PRIO_BONUS_RATIO         25
92 #define MAX_BONUS               (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
93 #define INTERACTIVE_DELTA         2
94 #define MAX_SLEEP_AVG           (DEF_TIMESLICE * MAX_BONUS)
95 #define STARVATION_LIMIT        (MAX_SLEEP_AVG)
96 #define NS_MAX_SLEEP_AVG        (JIFFIES_TO_NS(MAX_SLEEP_AVG))
97
98 /*
99  * If a task is 'interactive' then we reinsert it in the active
100  * array after it has expired its current timeslice. (it will not
101  * continue to run immediately, it will still roundrobin with
102  * other interactive tasks.)
103  *
104  * This part scales the interactivity limit depending on niceness.
105  *
106  * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
107  * Here are a few examples of different nice levels:
108  *
109  *  TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
110  *  TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
111  *  TASK_INTERACTIVE(  0): [1,1,1,1,0,0,0,0,0,0,0]
112  *  TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
113  *  TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
114  *
115  * (the X axis represents the possible -5 ... 0 ... +5 dynamic
116  *  priority range a task can explore, a value of '1' means the
117  *  task is rated interactive.)
118  *
119  * Ie. nice +19 tasks can never get 'interactive' enough to be
120  * reinserted into the active array. And only heavily CPU-hog nice -20
121  * tasks will be expired. Default nice 0 tasks are somewhere between,
122  * it takes some effort for them to get interactive, but it's not
123  * too hard.
124  */
125
126 #define CURRENT_BONUS(p) \
127         (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
128                 MAX_SLEEP_AVG)
129
130 #define GRANULARITY     (10 * HZ / 1000 ? : 1)
131
132 #ifdef CONFIG_SMP
133 #define TIMESLICE_GRANULARITY(p)        (GRANULARITY * \
134                 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
135                         num_online_cpus())
136 #else
137 #define TIMESLICE_GRANULARITY(p)        (GRANULARITY * \
138                 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
139 #endif
140
141 #define SCALE(v1,v1_max,v2_max) \
142         (v1) * (v2_max) / (v1_max)
143
144 #define DELTA(p) \
145         (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
146
147 #define TASK_INTERACTIVE(p) \
148         ((p)->prio <= (p)->static_prio - DELTA(p))
149
150 #define INTERACTIVE_SLEEP(p) \
151         (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
152                 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
153
154 #define TASK_PREEMPTS_CURR(p, rq) \
155         ((p)->prio < (rq)->curr->prio)
156
157 /*
158  * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
159  * to time slice values: [800ms ... 100ms ... 5ms]
160  *
161  * The higher a thread's priority, the bigger timeslices
162  * it gets during one round of execution. But even the lowest
163  * priority thread gets MIN_TIMESLICE worth of execution time.
164  */
165
166 #define SCALE_PRIO(x, prio) \
167         max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO/2), MIN_TIMESLICE)
168
169 static inline unsigned int task_timeslice(task_t *p)
170 {
171         if (p->static_prio < NICE_TO_PRIO(0))
172                 return SCALE_PRIO(DEF_TIMESLICE*4, p->static_prio);
173         else
174                 return SCALE_PRIO(DEF_TIMESLICE, p->static_prio);
175 }
176 #define task_hot(p, now, sd) ((long long) ((now) - (p)->last_ran)       \
177                                 < (long long) (sd)->cache_hot_time)
178
179 /*
180  * These are the runqueue data structures:
181  */
182
183 #define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
184
185 typedef struct runqueue runqueue_t;
186
187 struct prio_array {
188         unsigned int nr_active;
189         unsigned long bitmap[BITMAP_SIZE];
190         struct list_head queue[MAX_PRIO];
191 };
192
193 /*
194  * This is the main, per-CPU runqueue data structure.
195  *
196  * Locking rule: those places that want to lock multiple runqueues
197  * (such as the load balancing or the thread migration code), lock
198  * acquire operations must be ordered by ascending &runqueue.
199  */
200 struct runqueue {
201         spinlock_t lock;
202
203         /*
204          * nr_running and cpu_load should be in the same cacheline because
205          * remote CPUs use both these fields when doing load calculation.
206          */
207         unsigned long nr_running;
208 #ifdef CONFIG_SMP
209         unsigned long cpu_load[3];
210 #endif
211         unsigned long long nr_switches;
212
213         /*
214          * This is part of a global counter where only the total sum
215          * over all CPUs matters. A task can increase this counter on
216          * one CPU and if it got migrated afterwards it may decrease
217          * it on another CPU. Always updated under the runqueue lock:
218          */
219         unsigned long nr_uninterruptible;
220
221         unsigned long expired_timestamp;
222         unsigned long long timestamp_last_tick;
223         task_t *curr, *idle;
224         struct mm_struct *prev_mm;
225         prio_array_t *active, *expired, arrays[2];
226         int best_expired_prio;
227         atomic_t nr_iowait;
228
229 #ifdef CONFIG_SMP
230         struct sched_domain *sd;
231
232         /* For active balancing */
233         int active_balance;
234         int push_cpu;
235
236         task_t *migration_thread;
237         struct list_head migration_queue;
238 #endif
239
240 #ifdef CONFIG_SCHEDSTATS
241         /* latency stats */
242         struct sched_info rq_sched_info;
243
244         /* sys_sched_yield() stats */
245         unsigned long yld_exp_empty;
246         unsigned long yld_act_empty;
247         unsigned long yld_both_empty;
248         unsigned long yld_cnt;
249
250         /* schedule() stats */
251         unsigned long sched_switch;
252         unsigned long sched_cnt;
253         unsigned long sched_goidle;
254
255         /* try_to_wake_up() stats */
256         unsigned long ttwu_cnt;
257         unsigned long ttwu_local;
258 #endif
259 };
260
261 static DEFINE_PER_CPU(struct runqueue, runqueues);
262
263 #define for_each_domain(cpu, domain) \
264         for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
265
266 #define cpu_rq(cpu)             (&per_cpu(runqueues, (cpu)))
267 #define this_rq()               (&__get_cpu_var(runqueues))
268 #define task_rq(p)              cpu_rq(task_cpu(p))
269 #define cpu_curr(cpu)           (cpu_rq(cpu)->curr)
270
271 /*
272  * Default context-switch locking:
273  */
274 #ifndef prepare_arch_switch
275 # define prepare_arch_switch(rq, next)  do { } while (0)
276 # define finish_arch_switch(rq, next)   spin_unlock_irq(&(rq)->lock)
277 # define task_running(rq, p)            ((rq)->curr == (p))
278 #endif
279
280 /*
281  * task_rq_lock - lock the runqueue a given task resides on and disable
282  * interrupts.  Note the ordering: we can safely lookup the task_rq without
283  * explicitly disabling preemption.
284  */
285 static inline runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
286         __acquires(rq->lock)
287 {
288         struct runqueue *rq;
289
290 repeat_lock_task:
291         local_irq_save(*flags);
292         rq = task_rq(p);
293         spin_lock(&rq->lock);
294         if (unlikely(rq != task_rq(p))) {
295                 spin_unlock_irqrestore(&rq->lock, *flags);
296                 goto repeat_lock_task;
297         }
298         return rq;
299 }
300
301 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
302         __releases(rq->lock)
303 {
304         spin_unlock_irqrestore(&rq->lock, *flags);
305 }
306
307 #ifdef CONFIG_SCHEDSTATS
308 /*
309  * bump this up when changing the output format or the meaning of an existing
310  * format, so that tools can adapt (or abort)
311  */
312 #define SCHEDSTAT_VERSION 11
313
314 static int show_schedstat(struct seq_file *seq, void *v)
315 {
316         int cpu;
317
318         seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
319         seq_printf(seq, "timestamp %lu\n", jiffies);
320         for_each_online_cpu(cpu) {
321                 runqueue_t *rq = cpu_rq(cpu);
322 #ifdef CONFIG_SMP
323                 struct sched_domain *sd;
324                 int dcnt = 0;
325 #endif
326
327                 /* runqueue-specific stats */
328                 seq_printf(seq,
329                     "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
330                     cpu, rq->yld_both_empty,
331                     rq->yld_act_empty, rq->yld_exp_empty, rq->yld_cnt,
332                     rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
333                     rq->ttwu_cnt, rq->ttwu_local,
334                     rq->rq_sched_info.cpu_time,
335                     rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
336
337                 seq_printf(seq, "\n");
338
339 #ifdef CONFIG_SMP
340                 /* domain-specific stats */
341                 for_each_domain(cpu, sd) {
342                         enum idle_type itype;
343                         char mask_str[NR_CPUS];
344
345                         cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
346                         seq_printf(seq, "domain%d %s", dcnt++, mask_str);
347                         for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
348                                         itype++) {
349                                 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu",
350                                     sd->lb_cnt[itype],
351                                     sd->lb_balanced[itype],
352                                     sd->lb_failed[itype],
353                                     sd->lb_imbalance[itype],
354                                     sd->lb_gained[itype],
355                                     sd->lb_hot_gained[itype],
356                                     sd->lb_nobusyq[itype],
357                                     sd->lb_nobusyg[itype]);
358                         }
359                         seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu\n",
360                             sd->alb_cnt, sd->alb_failed, sd->alb_pushed,
361                             sd->sbe_pushed, sd->sbe_attempts,
362                             sd->ttwu_wake_remote, sd->ttwu_move_affine, sd->ttwu_move_balance);
363                 }
364 #endif
365         }
366         return 0;
367 }
368
369 static int schedstat_open(struct inode *inode, struct file *file)
370 {
371         unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
372         char *buf = kmalloc(size, GFP_KERNEL);
373         struct seq_file *m;
374         int res;
375
376         if (!buf)
377                 return -ENOMEM;
378         res = single_open(file, show_schedstat, NULL);
379         if (!res) {
380                 m = file->private_data;
381                 m->buf = buf;
382                 m->size = size;
383         } else
384                 kfree(buf);
385         return res;
386 }
387
388 struct file_operations proc_schedstat_operations = {
389         .open    = schedstat_open,
390         .read    = seq_read,
391         .llseek  = seq_lseek,
392         .release = single_release,
393 };
394
395 # define schedstat_inc(rq, field)       do { (rq)->field++; } while (0)
396 # define schedstat_add(rq, field, amt)  do { (rq)->field += (amt); } while (0)
397 #else /* !CONFIG_SCHEDSTATS */
398 # define schedstat_inc(rq, field)       do { } while (0)
399 # define schedstat_add(rq, field, amt)  do { } while (0)
400 #endif
401
402 /*
403  * rq_lock - lock a given runqueue and disable interrupts.
404  */
405 static inline runqueue_t *this_rq_lock(void)
406         __acquires(rq->lock)
407 {
408         runqueue_t *rq;
409
410         local_irq_disable();
411         rq = this_rq();
412         spin_lock(&rq->lock);
413
414         return rq;
415 }
416
417 #ifdef CONFIG_SCHED_SMT
418 static int cpu_and_siblings_are_idle(int cpu)
419 {
420         int sib;
421         for_each_cpu_mask(sib, cpu_sibling_map[cpu]) {
422                 if (idle_cpu(sib))
423                         continue;
424                 return 0;
425         }
426
427         return 1;
428 }
429 #else
430 #define cpu_and_siblings_are_idle(A) idle_cpu(A)
431 #endif
432
433 #ifdef CONFIG_SCHEDSTATS
434 /*
435  * Called when a process is dequeued from the active array and given
436  * the cpu.  We should note that with the exception of interactive
437  * tasks, the expired queue will become the active queue after the active
438  * queue is empty, without explicitly dequeuing and requeuing tasks in the
439  * expired queue.  (Interactive tasks may be requeued directly to the
440  * active queue, thus delaying tasks in the expired queue from running;
441  * see scheduler_tick()).
442  *
443  * This function is only called from sched_info_arrive(), rather than
444  * dequeue_task(). Even though a task may be queued and dequeued multiple
445  * times as it is shuffled about, we're really interested in knowing how
446  * long it was from the *first* time it was queued to the time that it
447  * finally hit a cpu.
448  */
449 static inline void sched_info_dequeued(task_t *t)
450 {
451         t->sched_info.last_queued = 0;
452 }
453
454 /*
455  * Called when a task finally hits the cpu.  We can now calculate how
456  * long it was waiting to run.  We also note when it began so that we
457  * can keep stats on how long its timeslice is.
458  */
459 static inline void sched_info_arrive(task_t *t)
460 {
461         unsigned long now = jiffies, diff = 0;
462         struct runqueue *rq = task_rq(t);
463
464         if (t->sched_info.last_queued)
465                 diff = now - t->sched_info.last_queued;
466         sched_info_dequeued(t);
467         t->sched_info.run_delay += diff;
468         t->sched_info.last_arrival = now;
469         t->sched_info.pcnt++;
470
471         if (!rq)
472                 return;
473
474         rq->rq_sched_info.run_delay += diff;
475         rq->rq_sched_info.pcnt++;
476 }
477
478 /*
479  * Called when a process is queued into either the active or expired
480  * array.  The time is noted and later used to determine how long we
481  * had to wait for us to reach the cpu.  Since the expired queue will
482  * become the active queue after active queue is empty, without dequeuing
483  * and requeuing any tasks, we are interested in queuing to either. It
484  * is unusual but not impossible for tasks to be dequeued and immediately
485  * requeued in the same or another array: this can happen in sched_yield(),
486  * set_user_nice(), and even load_balance() as it moves tasks from runqueue
487  * to runqueue.
488  *
489  * This function is only called from enqueue_task(), but also only updates
490  * the timestamp if it is already not set.  It's assumed that
491  * sched_info_dequeued() will clear that stamp when appropriate.
492  */
493 static inline void sched_info_queued(task_t *t)
494 {
495         if (!t->sched_info.last_queued)
496                 t->sched_info.last_queued = jiffies;
497 }
498
499 /*
500  * Called when a process ceases being the active-running process, either
501  * voluntarily or involuntarily.  Now we can calculate how long we ran.
502  */
503 static inline void sched_info_depart(task_t *t)
504 {
505         struct runqueue *rq = task_rq(t);
506         unsigned long diff = jiffies - t->sched_info.last_arrival;
507
508         t->sched_info.cpu_time += diff;
509
510         if (rq)
511                 rq->rq_sched_info.cpu_time += diff;
512 }
513
514 /*
515  * Called when tasks are switched involuntarily due, typically, to expiring
516  * their time slice.  (This may also be called when switching to or from
517  * the idle task.)  We are only called when prev != next.
518  */
519 static inline void sched_info_switch(task_t *prev, task_t *next)
520 {
521         struct runqueue *rq = task_rq(prev);
522
523         /*
524          * prev now departs the cpu.  It's not interesting to record
525          * stats about how efficient we were at scheduling the idle
526          * process, however.
527          */
528         if (prev != rq->idle)
529                 sched_info_depart(prev);
530
531         if (next != rq->idle)
532                 sched_info_arrive(next);
533 }
534 #else
535 #define sched_info_queued(t)            do { } while (0)
536 #define sched_info_switch(t, next)      do { } while (0)
537 #endif /* CONFIG_SCHEDSTATS */
538
539 /*
540  * Adding/removing a task to/from a priority array:
541  */
542 static void dequeue_task(struct task_struct *p, prio_array_t *array)
543 {
544         array->nr_active--;
545         list_del(&p->run_list);
546         if (list_empty(array->queue + p->prio))
547                 __clear_bit(p->prio, array->bitmap);
548 }
549
550 static void enqueue_task(struct task_struct *p, prio_array_t *array)
551 {
552         sched_info_queued(p);
553         list_add_tail(&p->run_list, array->queue + p->prio);
554         __set_bit(p->prio, array->bitmap);
555         array->nr_active++;
556         p->array = array;
557 }
558
559 /*
560  * Put task to the end of the run list without the overhead of dequeue
561  * followed by enqueue.
562  */
563 static void requeue_task(struct task_struct *p, prio_array_t *array)
564 {
565         list_move_tail(&p->run_list, array->queue + p->prio);
566 }
567
568 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
569 {
570         list_add(&p->run_list, array->queue + p->prio);
571         __set_bit(p->prio, array->bitmap);
572         array->nr_active++;
573         p->array = array;
574 }
575
576 /*
577  * effective_prio - return the priority that is based on the static
578  * priority but is modified by bonuses/penalties.
579  *
580  * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
581  * into the -5 ... 0 ... +5 bonus/penalty range.
582  *
583  * We use 25% of the full 0...39 priority range so that:
584  *
585  * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
586  * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
587  *
588  * Both properties are important to certain workloads.
589  */
590 static int effective_prio(task_t *p)
591 {
592         int bonus, prio;
593
594         if (rt_task(p))
595                 return p->prio;
596
597         bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
598
599         prio = p->static_prio - bonus;
600         if (prio < MAX_RT_PRIO)
601                 prio = MAX_RT_PRIO;
602         if (prio > MAX_PRIO-1)
603                 prio = MAX_PRIO-1;
604         return prio;
605 }
606
607 /*
608  * __activate_task - move a task to the runqueue.
609  */
610 static inline void __activate_task(task_t *p, runqueue_t *rq)
611 {
612         enqueue_task(p, rq->active);
613         rq->nr_running++;
614 }
615
616 /*
617  * __activate_idle_task - move idle task to the _front_ of runqueue.
618  */
619 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
620 {
621         enqueue_task_head(p, rq->active);
622         rq->nr_running++;
623 }
624
625 static void recalc_task_prio(task_t *p, unsigned long long now)
626 {
627         /* Caller must always ensure 'now >= p->timestamp' */
628         unsigned long long __sleep_time = now - p->timestamp;
629         unsigned long sleep_time;
630
631         if (__sleep_time > NS_MAX_SLEEP_AVG)
632                 sleep_time = NS_MAX_SLEEP_AVG;
633         else
634                 sleep_time = (unsigned long)__sleep_time;
635
636         if (likely(sleep_time > 0)) {
637                 /*
638                  * User tasks that sleep a long time are categorised as
639                  * idle and will get just interactive status to stay active &
640                  * prevent them suddenly becoming cpu hogs and starving
641                  * other processes.
642                  */
643                 if (p->mm && p->activated != -1 &&
644                         sleep_time > INTERACTIVE_SLEEP(p)) {
645                                 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
646                                                 DEF_TIMESLICE);
647                 } else {
648                         /*
649                          * The lower the sleep avg a task has the more
650                          * rapidly it will rise with sleep time.
651                          */
652                         sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
653
654                         /*
655                          * Tasks waking from uninterruptible sleep are
656                          * limited in their sleep_avg rise as they
657                          * are likely to be waiting on I/O
658                          */
659                         if (p->activated == -1 && p->mm) {
660                                 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
661                                         sleep_time = 0;
662                                 else if (p->sleep_avg + sleep_time >=
663                                                 INTERACTIVE_SLEEP(p)) {
664                                         p->sleep_avg = INTERACTIVE_SLEEP(p);
665                                         sleep_time = 0;
666                                 }
667                         }
668
669                         /*
670                          * This code gives a bonus to interactive tasks.
671                          *
672                          * The boost works by updating the 'average sleep time'
673                          * value here, based on ->timestamp. The more time a
674                          * task spends sleeping, the higher the average gets -
675                          * and the higher the priority boost gets as well.
676                          */
677                         p->sleep_avg += sleep_time;
678
679                         if (p->sleep_avg > NS_MAX_SLEEP_AVG)
680                                 p->sleep_avg = NS_MAX_SLEEP_AVG;
681                 }
682         }
683
684         p->prio = effective_prio(p);
685 }
686
687 /*
688  * activate_task - move a task to the runqueue and do priority recalculation
689  *
690  * Update all the scheduling statistics stuff. (sleep average
691  * calculation, priority modifiers, etc.)
692  */
693 static void activate_task(task_t *p, runqueue_t *rq, int local)
694 {
695         unsigned long long now;
696
697         now = sched_clock();
698 #ifdef CONFIG_SMP
699         if (!local) {
700                 /* Compensate for drifting sched_clock */
701                 runqueue_t *this_rq = this_rq();
702                 now = (now - this_rq->timestamp_last_tick)
703                         + rq->timestamp_last_tick;
704         }
705 #endif
706
707         recalc_task_prio(p, now);
708
709         /*
710          * This checks to make sure it's not an uninterruptible task
711          * that is now waking up.
712          */
713         if (!p->activated) {
714                 /*
715                  * Tasks which were woken up by interrupts (ie. hw events)
716                  * are most likely of interactive nature. So we give them
717                  * the credit of extending their sleep time to the period
718                  * of time they spend on the runqueue, waiting for execution
719                  * on a CPU, first time around:
720                  */
721                 if (in_interrupt())
722                         p->activated = 2;
723                 else {
724                         /*
725                          * Normal first-time wakeups get a credit too for
726                          * on-runqueue time, but it will be weighted down:
727                          */
728                         p->activated = 1;
729                 }
730         }
731         p->timestamp = now;
732
733         __activate_task(p, rq);
734 }
735
736 /*
737  * deactivate_task - remove a task from the runqueue.
738  */
739 static void deactivate_task(struct task_struct *p, runqueue_t *rq)
740 {
741         rq->nr_running--;
742         dequeue_task(p, p->array);
743         p->array = NULL;
744 }
745
746 /*
747  * resched_task - mark a task 'to be rescheduled now'.
748  *
749  * On UP this means the setting of the need_resched flag, on SMP it
750  * might also involve a cross-CPU call to trigger the scheduler on
751  * the target CPU.
752  */
753 #ifdef CONFIG_SMP
754 static void resched_task(task_t *p)
755 {
756         int need_resched, nrpolling;
757
758         assert_spin_locked(&task_rq(p)->lock);
759
760         /* minimise the chance of sending an interrupt to poll_idle() */
761         nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
762         need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
763         nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
764
765         if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
766                 smp_send_reschedule(task_cpu(p));
767 }
768 #else
769 static inline void resched_task(task_t *p)
770 {
771         set_tsk_need_resched(p);
772 }
773 #endif
774
775 /**
776  * task_curr - is this task currently executing on a CPU?
777  * @p: the task in question.
778  */
779 inline int task_curr(const task_t *p)
780 {
781         return cpu_curr(task_cpu(p)) == p;
782 }
783
784 #ifdef CONFIG_SMP
785 enum request_type {
786         REQ_MOVE_TASK,
787         REQ_SET_DOMAIN,
788 };
789
790 typedef struct {
791         struct list_head list;
792         enum request_type type;
793
794         /* For REQ_MOVE_TASK */
795         task_t *task;
796         int dest_cpu;
797
798         /* For REQ_SET_DOMAIN */
799         struct sched_domain *sd;
800
801         struct completion done;
802 } migration_req_t;
803
804 /*
805  * The task's runqueue lock must be held.
806  * Returns true if you have to wait for migration thread.
807  */
808 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
809 {
810         runqueue_t *rq = task_rq(p);
811
812         /*
813          * If the task is not on a runqueue (and not running), then
814          * it is sufficient to simply update the task's cpu field.
815          */
816         if (!p->array && !task_running(rq, p)) {
817                 set_task_cpu(p, dest_cpu);
818                 return 0;
819         }
820
821         init_completion(&req->done);
822         req->type = REQ_MOVE_TASK;
823         req->task = p;
824         req->dest_cpu = dest_cpu;
825         list_add(&req->list, &rq->migration_queue);
826         return 1;
827 }
828
829 /*
830  * wait_task_inactive - wait for a thread to unschedule.
831  *
832  * The caller must ensure that the task *will* unschedule sometime soon,
833  * else this function might spin for a *long* time. This function can't
834  * be called with interrupts off, or it may introduce deadlock with
835  * smp_call_function() if an IPI is sent by the same process we are
836  * waiting to become inactive.
837  */
838 void wait_task_inactive(task_t * p)
839 {
840         unsigned long flags;
841         runqueue_t *rq;
842         int preempted;
843
844 repeat:
845         rq = task_rq_lock(p, &flags);
846         /* Must be off runqueue entirely, not preempted. */
847         if (unlikely(p->array || task_running(rq, p))) {
848                 /* If it's preempted, we yield.  It could be a while. */
849                 preempted = !task_running(rq, p);
850                 task_rq_unlock(rq, &flags);
851                 cpu_relax();
852                 if (preempted)
853                         yield();
854                 goto repeat;
855         }
856         task_rq_unlock(rq, &flags);
857 }
858
859 /***
860  * kick_process - kick a running thread to enter/exit the kernel
861  * @p: the to-be-kicked thread
862  *
863  * Cause a process which is running on another CPU to enter
864  * kernel-mode, without any delay. (to get signals handled.)
865  *
866  * NOTE: this function doesnt have to take the runqueue lock,
867  * because all it wants to ensure is that the remote task enters
868  * the kernel. If the IPI races and the task has been migrated
869  * to another CPU then no harm is done and the purpose has been
870  * achieved as well.
871  */
872 void kick_process(task_t *p)
873 {
874         int cpu;
875
876         preempt_disable();
877         cpu = task_cpu(p);
878         if ((cpu != smp_processor_id()) && task_curr(p))
879                 smp_send_reschedule(cpu);
880         preempt_enable();
881 }
882
883 /*
884  * Return a low guess at the load of a migration-source cpu.
885  *
886  * We want to under-estimate the load of migration sources, to
887  * balance conservatively.
888  */
889 static inline unsigned long source_load(int cpu, int type)
890 {
891         runqueue_t *rq = cpu_rq(cpu);
892         unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
893         if (type == 0)
894                 return load_now;
895
896         return min(rq->cpu_load[type-1], load_now);
897 }
898
899 /*
900  * Return a high guess at the load of a migration-target cpu
901  */
902 static inline unsigned long target_load(int cpu, int type)
903 {
904         runqueue_t *rq = cpu_rq(cpu);
905         unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
906         if (type == 0)
907                 return load_now;
908
909         return max(rq->cpu_load[type-1], load_now);
910 }
911
912 #endif
913
914 /*
915  * wake_idle() will wake a task on an idle cpu if task->cpu is
916  * not idle and an idle cpu is available.  The span of cpus to
917  * search starts with cpus closest then further out as needed,
918  * so we always favor a closer, idle cpu.
919  *
920  * Returns the CPU we should wake onto.
921  */
922 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
923 static int wake_idle(int cpu, task_t *p)
924 {
925         cpumask_t tmp;
926         struct sched_domain *sd;
927         int i;
928
929         if (idle_cpu(cpu))
930                 return cpu;
931
932         for_each_domain(cpu, sd) {
933                 if (sd->flags & SD_WAKE_IDLE) {
934                         cpus_and(tmp, sd->span, p->cpus_allowed);
935                         for_each_cpu_mask(i, tmp) {
936                                 if (idle_cpu(i))
937                                         return i;
938                         }
939                 }
940                 else
941                         break;
942         }
943         return cpu;
944 }
945 #else
946 static inline int wake_idle(int cpu, task_t *p)
947 {
948         return cpu;
949 }
950 #endif
951
952 /***
953  * try_to_wake_up - wake up a thread
954  * @p: the to-be-woken-up thread
955  * @state: the mask of task states that can be woken
956  * @sync: do a synchronous wakeup?
957  *
958  * Put it on the run-queue if it's not already there. The "current"
959  * thread is always on the run-queue (except when the actual
960  * re-schedule is in progress), and as such you're allowed to do
961  * the simpler "current->state = TASK_RUNNING" to mark yourself
962  * runnable without the overhead of this.
963  *
964  * returns failure only if the task is already active.
965  */
966 static int try_to_wake_up(task_t * p, unsigned int state, int sync)
967 {
968         int cpu, this_cpu, success = 0;
969         unsigned long flags;
970         long old_state;
971         runqueue_t *rq;
972 #ifdef CONFIG_SMP
973         unsigned long load, this_load;
974         struct sched_domain *sd, *this_sd = NULL;
975         int new_cpu;
976 #endif
977
978         rq = task_rq_lock(p, &flags);
979         old_state = p->state;
980         if (!(old_state & state))
981                 goto out;
982
983         if (p->array)
984                 goto out_running;
985
986         cpu = task_cpu(p);
987         this_cpu = smp_processor_id();
988
989 #ifdef CONFIG_SMP
990         if (unlikely(task_running(rq, p)))
991                 goto out_activate;
992
993         new_cpu = cpu;
994
995         schedstat_inc(rq, ttwu_cnt);
996         if (cpu == this_cpu) {
997                 schedstat_inc(rq, ttwu_local);
998                 goto out_set_cpu;
999         }
1000
1001         for_each_domain(this_cpu, sd) {
1002                 if (cpu_isset(cpu, sd->span)) {
1003                         schedstat_inc(sd, ttwu_wake_remote);
1004                         this_sd = sd;
1005                         break;
1006                 }
1007         }
1008
1009         if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1010                 goto out_set_cpu;
1011
1012         /*
1013          * Check for affine wakeup and passive balancing possibilities.
1014          */
1015         if (this_sd) {
1016                 int idx = this_sd->wake_idx;
1017                 unsigned int imbalance;
1018
1019                 imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
1020
1021                 load = source_load(cpu, idx);
1022                 this_load = target_load(this_cpu, idx);
1023
1024                 new_cpu = this_cpu; /* Wake to this CPU if we can */
1025
1026                 if (this_sd->flags & SD_WAKE_AFFINE) {
1027                         unsigned long tl = this_load;
1028                         /*
1029                          * If sync wakeup then subtract the (maximum possible)
1030                          * effect of the currently running task from the load
1031                          * of the current CPU:
1032                          */
1033                         if (sync)
1034                                 tl -= SCHED_LOAD_SCALE;
1035
1036                         if ((tl <= load &&
1037                                 tl + target_load(cpu, idx) <= SCHED_LOAD_SCALE) ||
1038                                 100*(tl + SCHED_LOAD_SCALE) <= imbalance*load) {
1039                                 /*
1040                                  * This domain has SD_WAKE_AFFINE and
1041                                  * p is cache cold in this domain, and
1042                                  * there is no bad imbalance.
1043                                  */
1044                                 schedstat_inc(this_sd, ttwu_move_affine);
1045                                 goto out_set_cpu;
1046                         }
1047                 }
1048
1049                 /*
1050                  * Start passive balancing when half the imbalance_pct
1051                  * limit is reached.
1052                  */
1053                 if (this_sd->flags & SD_WAKE_BALANCE) {
1054                         if (imbalance*this_load <= 100*load) {
1055                                 schedstat_inc(this_sd, ttwu_move_balance);
1056                                 goto out_set_cpu;
1057                         }
1058                 }
1059         }
1060
1061         new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1062 out_set_cpu:
1063         new_cpu = wake_idle(new_cpu, p);
1064         if (new_cpu != cpu) {
1065                 set_task_cpu(p, new_cpu);
1066                 task_rq_unlock(rq, &flags);
1067                 /* might preempt at this point */
1068                 rq = task_rq_lock(p, &flags);
1069                 old_state = p->state;
1070                 if (!(old_state & state))
1071                         goto out;
1072                 if (p->array)
1073                         goto out_running;
1074
1075                 this_cpu = smp_processor_id();
1076                 cpu = task_cpu(p);
1077         }
1078
1079 out_activate:
1080 #endif /* CONFIG_SMP */
1081         if (old_state == TASK_UNINTERRUPTIBLE) {
1082                 rq->nr_uninterruptible--;
1083                 /*
1084                  * Tasks on involuntary sleep don't earn
1085                  * sleep_avg beyond just interactive state.
1086                  */
1087                 p->activated = -1;
1088         }
1089
1090         /*
1091          * Sync wakeups (i.e. those types of wakeups where the waker
1092          * has indicated that it will leave the CPU in short order)
1093          * don't trigger a preemption, if the woken up task will run on
1094          * this cpu. (in this case the 'I will reschedule' promise of
1095          * the waker guarantees that the freshly woken up task is going
1096          * to be considered on this CPU.)
1097          */
1098         activate_task(p, rq, cpu == this_cpu);
1099         if (!sync || cpu != this_cpu) {
1100                 if (TASK_PREEMPTS_CURR(p, rq))
1101                         resched_task(rq->curr);
1102         }
1103         success = 1;
1104
1105 out_running:
1106         p->state = TASK_RUNNING;
1107 out:
1108         task_rq_unlock(rq, &flags);
1109
1110         return success;
1111 }
1112
1113 int fastcall wake_up_process(task_t * p)
1114 {
1115         return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1116                                  TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1117 }
1118
1119 EXPORT_SYMBOL(wake_up_process);
1120
1121 int fastcall wake_up_state(task_t *p, unsigned int state)
1122 {
1123         return try_to_wake_up(p, state, 0);
1124 }
1125
1126 #ifdef CONFIG_SMP
1127 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1128                            struct sched_domain *sd);
1129 #endif
1130
1131 /*
1132  * Perform scheduler related setup for a newly forked process p.
1133  * p is forked by current.
1134  */
1135 void fastcall sched_fork(task_t *p)
1136 {
1137         /*
1138          * We mark the process as running here, but have not actually
1139          * inserted it onto the runqueue yet. This guarantees that
1140          * nobody will actually run it, and a signal or other external
1141          * event cannot wake it up and insert it on the runqueue either.
1142          */
1143         p->state = TASK_RUNNING;
1144         INIT_LIST_HEAD(&p->run_list);
1145         p->array = NULL;
1146         spin_lock_init(&p->switch_lock);
1147 #ifdef CONFIG_SCHEDSTATS
1148         memset(&p->sched_info, 0, sizeof(p->sched_info));
1149 #endif
1150 #ifdef CONFIG_PREEMPT
1151         /*
1152          * During context-switch we hold precisely one spinlock, which
1153          * schedule_tail drops. (in the common case it's this_rq()->lock,
1154          * but it also can be p->switch_lock.) So we compensate with a count
1155          * of 1. Also, we want to start with kernel preemption disabled.
1156          */
1157         p->thread_info->preempt_count = 1;
1158 #endif
1159         /*
1160          * Share the timeslice between parent and child, thus the
1161          * total amount of pending timeslices in the system doesn't change,
1162          * resulting in more scheduling fairness.
1163          */
1164         local_irq_disable();
1165         p->time_slice = (current->time_slice + 1) >> 1;
1166         /*
1167          * The remainder of the first timeslice might be recovered by
1168          * the parent if the child exits early enough.
1169          */
1170         p->first_time_slice = 1;
1171         current->time_slice >>= 1;
1172         p->timestamp = sched_clock();
1173         if (unlikely(!current->time_slice)) {
1174                 /*
1175                  * This case is rare, it happens when the parent has only
1176                  * a single jiffy left from its timeslice. Taking the
1177                  * runqueue lock is not a problem.
1178                  */
1179                 current->time_slice = 1;
1180                 preempt_disable();
1181                 scheduler_tick();
1182                 local_irq_enable();
1183                 preempt_enable();
1184         } else
1185                 local_irq_enable();
1186 }
1187
1188 /*
1189  * wake_up_new_task - wake up a newly created task for the first time.
1190  *
1191  * This function will do some initial scheduler statistics housekeeping
1192  * that must be done for every newly created context, then puts the task
1193  * on the runqueue and wakes it.
1194  */
1195 void fastcall wake_up_new_task(task_t * p, unsigned long clone_flags)
1196 {
1197         unsigned long flags;
1198         int this_cpu, cpu;
1199         runqueue_t *rq, *this_rq;
1200
1201         rq = task_rq_lock(p, &flags);
1202         cpu = task_cpu(p);
1203         this_cpu = smp_processor_id();
1204
1205         BUG_ON(p->state != TASK_RUNNING);
1206
1207         /*
1208          * We decrease the sleep average of forking parents
1209          * and children as well, to keep max-interactive tasks
1210          * from forking tasks that are max-interactive. The parent
1211          * (current) is done further down, under its lock.
1212          */
1213         p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1214                 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1215
1216         p->prio = effective_prio(p);
1217
1218         if (likely(cpu == this_cpu)) {
1219                 if (!(clone_flags & CLONE_VM)) {
1220                         /*
1221                          * The VM isn't cloned, so we're in a good position to
1222                          * do child-runs-first in anticipation of an exec. This
1223                          * usually avoids a lot of COW overhead.
1224                          */
1225                         if (unlikely(!current->array))
1226                                 __activate_task(p, rq);
1227                         else {
1228                                 p->prio = current->prio;
1229                                 list_add_tail(&p->run_list, &current->run_list);
1230                                 p->array = current->array;
1231                                 p->array->nr_active++;
1232                                 rq->nr_running++;
1233                         }
1234                         set_need_resched();
1235                 } else
1236                         /* Run child last */
1237                         __activate_task(p, rq);
1238                 /*
1239                  * We skip the following code due to cpu == this_cpu
1240                  *
1241                  *   task_rq_unlock(rq, &flags);
1242                  *   this_rq = task_rq_lock(current, &flags);
1243                  */
1244                 this_rq = rq;
1245         } else {
1246                 this_rq = cpu_rq(this_cpu);
1247
1248                 /*
1249                  * Not the local CPU - must adjust timestamp. This should
1250                  * get optimised away in the !CONFIG_SMP case.
1251                  */
1252                 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1253                                         + rq->timestamp_last_tick;
1254                 __activate_task(p, rq);
1255                 if (TASK_PREEMPTS_CURR(p, rq))
1256                         resched_task(rq->curr);
1257
1258                 /*
1259                  * Parent and child are on different CPUs, now get the
1260                  * parent runqueue to update the parent's ->sleep_avg:
1261                  */
1262                 task_rq_unlock(rq, &flags);
1263                 this_rq = task_rq_lock(current, &flags);
1264         }
1265         current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1266                 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1267         task_rq_unlock(this_rq, &flags);
1268 }
1269
1270 /*
1271  * Potentially available exiting-child timeslices are
1272  * retrieved here - this way the parent does not get
1273  * penalized for creating too many threads.
1274  *
1275  * (this cannot be used to 'generate' timeslices
1276  * artificially, because any timeslice recovered here
1277  * was given away by the parent in the first place.)
1278  */
1279 void fastcall sched_exit(task_t * p)
1280 {
1281         unsigned long flags;
1282         runqueue_t *rq;
1283
1284         /*
1285          * If the child was a (relative-) CPU hog then decrease
1286          * the sleep_avg of the parent as well.
1287          */
1288         rq = task_rq_lock(p->parent, &flags);
1289         if (p->first_time_slice) {
1290                 p->parent->time_slice += p->time_slice;
1291                 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1292                         p->parent->time_slice = task_timeslice(p);
1293         }
1294         if (p->sleep_avg < p->parent->sleep_avg)
1295                 p->parent->sleep_avg = p->parent->sleep_avg /
1296                 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1297                 (EXIT_WEIGHT + 1);
1298         task_rq_unlock(rq, &flags);
1299 }
1300
1301 /**
1302  * finish_task_switch - clean up after a task-switch
1303  * @prev: the thread we just switched away from.
1304  *
1305  * We enter this with the runqueue still locked, and finish_arch_switch()
1306  * will unlock it along with doing any other architecture-specific cleanup
1307  * actions.
1308  *
1309  * Note that we may have delayed dropping an mm in context_switch(). If
1310  * so, we finish that here outside of the runqueue lock.  (Doing it
1311  * with the lock held can cause deadlocks; see schedule() for
1312  * details.)
1313  */
1314 static inline void finish_task_switch(task_t *prev)
1315         __releases(rq->lock)
1316 {
1317         runqueue_t *rq = this_rq();
1318         struct mm_struct *mm = rq->prev_mm;
1319         unsigned long prev_task_flags;
1320
1321         rq->prev_mm = NULL;
1322
1323         /*
1324          * A task struct has one reference for the use as "current".
1325          * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1326          * calls schedule one last time. The schedule call will never return,
1327          * and the scheduled task must drop that reference.
1328          * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1329          * still held, otherwise prev could be scheduled on another cpu, die
1330          * there before we look at prev->state, and then the reference would
1331          * be dropped twice.
1332          *              Manfred Spraul <manfred@colorfullife.com>
1333          */
1334         prev_task_flags = prev->flags;
1335         finish_arch_switch(rq, prev);
1336         if (mm)
1337                 mmdrop(mm);
1338         if (unlikely(prev_task_flags & PF_DEAD))
1339                 put_task_struct(prev);
1340 }
1341
1342 /**
1343  * schedule_tail - first thing a freshly forked thread must call.
1344  * @prev: the thread we just switched away from.
1345  */
1346 asmlinkage void schedule_tail(task_t *prev)
1347         __releases(rq->lock)
1348 {
1349         finish_task_switch(prev);
1350
1351         if (current->set_child_tid)
1352                 put_user(current->pid, current->set_child_tid);
1353 }
1354
1355 /*
1356  * context_switch - switch to the new MM and the new
1357  * thread's register state.
1358  */
1359 static inline
1360 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1361 {
1362         struct mm_struct *mm = next->mm;
1363         struct mm_struct *oldmm = prev->active_mm;
1364
1365         if (unlikely(!mm)) {
1366                 next->active_mm = oldmm;
1367                 atomic_inc(&oldmm->mm_count);
1368                 enter_lazy_tlb(oldmm, next);
1369         } else
1370                 switch_mm(oldmm, mm, next);
1371
1372         if (unlikely(!prev->mm)) {
1373                 prev->active_mm = NULL;
1374                 WARN_ON(rq->prev_mm);
1375                 rq->prev_mm = oldmm;
1376         }
1377
1378         /* Here we just switch the register state and the stack. */
1379         switch_to(prev, next, prev);
1380
1381         return prev;
1382 }
1383
1384 /*
1385  * nr_running, nr_uninterruptible and nr_context_switches:
1386  *
1387  * externally visible scheduler statistics: current number of runnable
1388  * threads, current number of uninterruptible-sleeping threads, total
1389  * number of context switches performed since bootup.
1390  */
1391 unsigned long nr_running(void)
1392 {
1393         unsigned long i, sum = 0;
1394
1395         for_each_online_cpu(i)
1396                 sum += cpu_rq(i)->nr_running;
1397
1398         return sum;
1399 }
1400
1401 unsigned long nr_uninterruptible(void)
1402 {
1403         unsigned long i, sum = 0;
1404
1405         for_each_cpu(i)
1406                 sum += cpu_rq(i)->nr_uninterruptible;
1407
1408         /*
1409          * Since we read the counters lockless, it might be slightly
1410          * inaccurate. Do not allow it to go below zero though:
1411          */
1412         if (unlikely((long)sum < 0))
1413                 sum = 0;
1414
1415         return sum;
1416 }
1417
1418 unsigned long long nr_context_switches(void)
1419 {
1420         unsigned long long i, sum = 0;
1421
1422         for_each_cpu(i)
1423                 sum += cpu_rq(i)->nr_switches;
1424
1425         return sum;
1426 }
1427
1428 unsigned long nr_iowait(void)
1429 {
1430         unsigned long i, sum = 0;
1431
1432         for_each_cpu(i)
1433                 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1434
1435         return sum;
1436 }
1437
1438 #ifdef CONFIG_SMP
1439
1440 /*
1441  * double_rq_lock - safely lock two runqueues
1442  *
1443  * Note this does not disable interrupts like task_rq_lock,
1444  * you need to do so manually before calling.
1445  */
1446 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1447         __acquires(rq1->lock)
1448         __acquires(rq2->lock)
1449 {
1450         if (rq1 == rq2) {
1451                 spin_lock(&rq1->lock);
1452                 __acquire(rq2->lock);   /* Fake it out ;) */
1453         } else {
1454                 if (rq1 < rq2) {
1455                         spin_lock(&rq1->lock);
1456                         spin_lock(&rq2->lock);
1457                 } else {
1458                         spin_lock(&rq2->lock);
1459                         spin_lock(&rq1->lock);
1460                 }
1461         }
1462 }
1463
1464 /*
1465  * double_rq_unlock - safely unlock two runqueues
1466  *
1467  * Note this does not restore interrupts like task_rq_unlock,
1468  * you need to do so manually after calling.
1469  */
1470 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1471         __releases(rq1->lock)
1472         __releases(rq2->lock)
1473 {
1474         spin_unlock(&rq1->lock);
1475         if (rq1 != rq2)
1476                 spin_unlock(&rq2->lock);
1477         else
1478                 __release(rq2->lock);
1479 }
1480
1481 /*
1482  * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1483  */
1484 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1485         __releases(this_rq->lock)
1486         __acquires(busiest->lock)
1487         __acquires(this_rq->lock)
1488 {
1489         if (unlikely(!spin_trylock(&busiest->lock))) {
1490                 if (busiest < this_rq) {
1491                         spin_unlock(&this_rq->lock);
1492                         spin_lock(&busiest->lock);
1493                         spin_lock(&this_rq->lock);
1494                 } else
1495                         spin_lock(&busiest->lock);
1496         }
1497 }
1498
1499 /*
1500  * find_idlest_cpu - find the least busy runqueue.
1501  */
1502 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1503                            struct sched_domain *sd)
1504 {
1505         unsigned long load, min_load, this_load;
1506         int i, min_cpu;
1507         cpumask_t mask;
1508
1509         min_cpu = UINT_MAX;
1510         min_load = ULONG_MAX;
1511
1512         cpus_and(mask, sd->span, p->cpus_allowed);
1513
1514         for_each_cpu_mask(i, mask) {
1515                 load = target_load(i, sd->wake_idx);
1516
1517                 if (load < min_load) {
1518                         min_cpu = i;
1519                         min_load = load;
1520
1521                         /* break out early on an idle CPU: */
1522                         if (!min_load)
1523                                 break;
1524                 }
1525         }
1526
1527         /* add +1 to account for the new task */
1528         this_load = source_load(this_cpu, sd->wake_idx) + SCHED_LOAD_SCALE;
1529
1530         /*
1531          * Would with the addition of the new task to the
1532          * current CPU there be an imbalance between this
1533          * CPU and the idlest CPU?
1534          *
1535          * Use half of the balancing threshold - new-context is
1536          * a good opportunity to balance.
1537          */
1538         if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1539                 return min_cpu;
1540
1541         return this_cpu;
1542 }
1543
1544 /*
1545  * If dest_cpu is allowed for this process, migrate the task to it.
1546  * This is accomplished by forcing the cpu_allowed mask to only
1547  * allow dest_cpu, which will force the cpu onto dest_cpu.  Then
1548  * the cpu_allowed mask is restored.
1549  */
1550 static void sched_migrate_task(task_t *p, int dest_cpu)
1551 {
1552         migration_req_t req;
1553         runqueue_t *rq;
1554         unsigned long flags;
1555
1556         rq = task_rq_lock(p, &flags);
1557         if (!cpu_isset(dest_cpu, p->cpus_allowed)
1558             || unlikely(cpu_is_offline(dest_cpu)))
1559                 goto out;
1560
1561         /* force the process onto the specified CPU */
1562         if (migrate_task(p, dest_cpu, &req)) {
1563                 /* Need to wait for migration thread (might exit: take ref). */
1564                 struct task_struct *mt = rq->migration_thread;
1565                 get_task_struct(mt);
1566                 task_rq_unlock(rq, &flags);
1567                 wake_up_process(mt);
1568                 put_task_struct(mt);
1569                 wait_for_completion(&req.done);
1570                 return;
1571         }
1572 out:
1573         task_rq_unlock(rq, &flags);
1574 }
1575
1576 /*
1577  * sched_exec(): find the highest-level, exec-balance-capable
1578  * domain and try to migrate the task to the least loaded CPU.
1579  *
1580  * execve() is a valuable balancing opportunity, because at this point
1581  * the task has the smallest effective memory and cache footprint.
1582  */
1583 void sched_exec(void)
1584 {
1585         struct sched_domain *tmp, *sd = NULL;
1586         int new_cpu, this_cpu = get_cpu();
1587
1588         /* Prefer the current CPU if there's only this task running */
1589         if (this_rq()->nr_running <= 1)
1590                 goto out;
1591
1592         for_each_domain(this_cpu, tmp)
1593                 if (tmp->flags & SD_BALANCE_EXEC)
1594                         sd = tmp;
1595
1596         if (sd) {
1597                 schedstat_inc(sd, sbe_attempts);
1598                 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1599                 if (new_cpu != this_cpu) {
1600                         schedstat_inc(sd, sbe_pushed);
1601                         put_cpu();
1602                         sched_migrate_task(current, new_cpu);
1603                         return;
1604                 }
1605         }
1606 out:
1607         put_cpu();
1608 }
1609
1610 /*
1611  * pull_task - move a task from a remote runqueue to the local runqueue.
1612  * Both runqueues must be locked.
1613  */
1614 static inline
1615 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1616                runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1617 {
1618         dequeue_task(p, src_array);
1619         src_rq->nr_running--;
1620         set_task_cpu(p, this_cpu);
1621         this_rq->nr_running++;
1622         enqueue_task(p, this_array);
1623         p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1624                                 + this_rq->timestamp_last_tick;
1625         /*
1626          * Note that idle threads have a prio of MAX_PRIO, for this test
1627          * to be always true for them.
1628          */
1629         if (TASK_PREEMPTS_CURR(p, this_rq))
1630                 resched_task(this_rq->curr);
1631 }
1632
1633 /*
1634  * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1635  */
1636 static inline
1637 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1638              struct sched_domain *sd, enum idle_type idle, int *all_pinned)
1639 {
1640         /*
1641          * We do not migrate tasks that are:
1642          * 1) running (obviously), or
1643          * 2) cannot be migrated to this CPU due to cpus_allowed, or
1644          * 3) are cache-hot on their current CPU.
1645          */
1646         if (!cpu_isset(this_cpu, p->cpus_allowed))
1647                 return 0;
1648         *all_pinned = 0;
1649
1650         if (task_running(rq, p))
1651                 return 0;
1652
1653         /*
1654          * Aggressive migration if:
1655          * 1) the [whole] cpu is idle, or
1656          * 2) too many balance attempts have failed.
1657          */
1658
1659         if (cpu_and_siblings_are_idle(this_cpu) || \
1660                         sd->nr_balance_failed > sd->cache_nice_tries)
1661                 return 1;
1662
1663         if (task_hot(p, rq->timestamp_last_tick, sd))
1664                 return 0;
1665         return 1;
1666 }
1667
1668 /*
1669  * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1670  * as part of a balancing operation within "domain". Returns the number of
1671  * tasks moved.
1672  *
1673  * Called with both runqueues locked.
1674  */
1675 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1676                       unsigned long max_nr_move, struct sched_domain *sd,
1677                       enum idle_type idle, int *all_pinned)
1678 {
1679         prio_array_t *array, *dst_array;
1680         struct list_head *head, *curr;
1681         int idx, pulled = 0, pinned = 0;
1682         task_t *tmp;
1683
1684         if (max_nr_move == 0)
1685                 goto out;
1686
1687         pinned = 1;
1688
1689         /*
1690          * We first consider expired tasks. Those will likely not be
1691          * executed in the near future, and they are most likely to
1692          * be cache-cold, thus switching CPUs has the least effect
1693          * on them.
1694          */
1695         if (busiest->expired->nr_active) {
1696                 array = busiest->expired;
1697                 dst_array = this_rq->expired;
1698         } else {
1699                 array = busiest->active;
1700                 dst_array = this_rq->active;
1701         }
1702
1703 new_array:
1704         /* Start searching at priority 0: */
1705         idx = 0;
1706 skip_bitmap:
1707         if (!idx)
1708                 idx = sched_find_first_bit(array->bitmap);
1709         else
1710                 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1711         if (idx >= MAX_PRIO) {
1712                 if (array == busiest->expired && busiest->active->nr_active) {
1713                         array = busiest->active;
1714                         dst_array = this_rq->active;
1715                         goto new_array;
1716                 }
1717                 goto out;
1718         }
1719
1720         head = array->queue + idx;
1721         curr = head->prev;
1722 skip_queue:
1723         tmp = list_entry(curr, task_t, run_list);
1724
1725         curr = curr->prev;
1726
1727         if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle, &pinned)) {
1728                 if (curr != head)
1729                         goto skip_queue;
1730                 idx++;
1731                 goto skip_bitmap;
1732         }
1733
1734 #ifdef CONFIG_SCHEDSTATS
1735         if (task_hot(tmp, busiest->timestamp_last_tick, sd))
1736                 schedstat_inc(sd, lb_hot_gained[idle]);
1737 #endif
1738
1739         pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
1740         pulled++;
1741
1742         /* We only want to steal up to the prescribed number of tasks. */
1743         if (pulled < max_nr_move) {
1744                 if (curr != head)
1745                         goto skip_queue;
1746                 idx++;
1747                 goto skip_bitmap;
1748         }
1749 out:
1750         /*
1751          * Right now, this is the only place pull_task() is called,
1752          * so we can safely collect pull_task() stats here rather than
1753          * inside pull_task().
1754          */
1755         schedstat_add(sd, lb_gained[idle], pulled);
1756
1757         if (all_pinned)
1758                 *all_pinned = pinned;
1759         return pulled;
1760 }
1761
1762 /*
1763  * find_busiest_group finds and returns the busiest CPU group within the
1764  * domain. It calculates and returns the number of tasks which should be
1765  * moved to restore balance via the imbalance parameter.
1766  */
1767 static struct sched_group *
1768 find_busiest_group(struct sched_domain *sd, int this_cpu,
1769                    unsigned long *imbalance, enum idle_type idle)
1770 {
1771         struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
1772         unsigned long max_load, avg_load, total_load, this_load, total_pwr;
1773         int load_idx;
1774
1775         max_load = this_load = total_load = total_pwr = 0;
1776         if (idle == NOT_IDLE)
1777                 load_idx = sd->busy_idx;
1778         else if (idle == NEWLY_IDLE)
1779                 load_idx = sd->newidle_idx;
1780         else
1781                 load_idx = sd->idle_idx;
1782
1783         do {
1784                 unsigned long load;
1785                 int local_group;
1786                 int i;
1787
1788                 local_group = cpu_isset(this_cpu, group->cpumask);
1789
1790                 /* Tally up the load of all CPUs in the group */
1791                 avg_load = 0;
1792
1793                 for_each_cpu_mask(i, group->cpumask) {
1794                         /* Bias balancing toward cpus of our domain */
1795                         if (local_group)
1796                                 load = target_load(i, load_idx);
1797                         else
1798                                 load = source_load(i, load_idx);
1799
1800                         avg_load += load;
1801                 }
1802
1803                 total_load += avg_load;
1804                 total_pwr += group->cpu_power;
1805
1806                 /* Adjust by relative CPU power of the group */
1807                 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1808
1809                 if (local_group) {
1810                         this_load = avg_load;
1811                         this = group;
1812                         goto nextgroup;
1813                 } else if (avg_load > max_load) {
1814                         max_load = avg_load;
1815                         busiest = group;
1816                 }
1817 nextgroup:
1818                 group = group->next;
1819         } while (group != sd->groups);
1820
1821         if (!busiest || this_load >= max_load)
1822                 goto out_balanced;
1823
1824         avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
1825
1826         if (this_load >= avg_load ||
1827                         100*max_load <= sd->imbalance_pct*this_load)
1828                 goto out_balanced;
1829
1830         /*
1831          * We're trying to get all the cpus to the average_load, so we don't
1832          * want to push ourselves above the average load, nor do we wish to
1833          * reduce the max loaded cpu below the average load, as either of these
1834          * actions would just result in more rebalancing later, and ping-pong
1835          * tasks around. Thus we look for the minimum possible imbalance.
1836          * Negative imbalances (*we* are more loaded than anyone else) will
1837          * be counted as no imbalance for these purposes -- we can't fix that
1838          * by pulling tasks to us.  Be careful of negative numbers as they'll
1839          * appear as very large values with unsigned longs.
1840          */
1841         /* How much load to actually move to equalise the imbalance */
1842         *imbalance = min((max_load - avg_load) * busiest->cpu_power,
1843                                 (avg_load - this_load) * this->cpu_power)
1844                         / SCHED_LOAD_SCALE;
1845
1846         if (*imbalance < SCHED_LOAD_SCALE) {
1847                 unsigned long pwr_now = 0, pwr_move = 0;
1848                 unsigned long tmp;
1849
1850                 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
1851                         *imbalance = 1;
1852                         return busiest;
1853                 }
1854
1855                 /*
1856                  * OK, we don't have enough imbalance to justify moving tasks,
1857                  * however we may be able to increase total CPU power used by
1858                  * moving them.
1859                  */
1860
1861                 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
1862                 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
1863                 pwr_now /= SCHED_LOAD_SCALE;
1864
1865                 /* Amount of load we'd subtract */
1866                 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
1867                 if (max_load > tmp)
1868                         pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
1869                                                         max_load - tmp);
1870
1871                 /* Amount of load we'd add */
1872                 if (max_load*busiest->cpu_power <
1873                                 SCHED_LOAD_SCALE*SCHED_LOAD_SCALE)
1874                         tmp = max_load*busiest->cpu_power/this->cpu_power;
1875                 else
1876                         tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
1877                 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
1878                 pwr_move /= SCHED_LOAD_SCALE;
1879
1880                 /* Move if we gain throughput */
1881                 if (pwr_move <= pwr_now)
1882                         goto out_balanced;
1883
1884                 *imbalance = 1;
1885                 return busiest;
1886         }
1887
1888         /* Get rid of the scaling factor, rounding down as we divide */
1889         *imbalance = *imbalance / SCHED_LOAD_SCALE;
1890         return busiest;
1891
1892 out_balanced:
1893
1894         *imbalance = 0;
1895         return NULL;
1896 }
1897
1898 /*
1899  * find_busiest_queue - find the busiest runqueue among the cpus in group.
1900  */
1901 static runqueue_t *find_busiest_queue(struct sched_group *group)
1902 {
1903         unsigned long load, max_load = 0;
1904         runqueue_t *busiest = NULL;
1905         int i;
1906
1907         for_each_cpu_mask(i, group->cpumask) {
1908                 load = source_load(i, 0);
1909
1910                 if (load > max_load) {
1911                         max_load = load;
1912                         busiest = cpu_rq(i);
1913                 }
1914         }
1915
1916         return busiest;
1917 }
1918
1919 /*
1920  * Check this_cpu to ensure it is balanced within domain. Attempt to move
1921  * tasks if there is an imbalance.
1922  *
1923  * Called with this_rq unlocked.
1924  */
1925 static int load_balance(int this_cpu, runqueue_t *this_rq,
1926                         struct sched_domain *sd, enum idle_type idle)
1927 {
1928         struct sched_group *group;
1929         runqueue_t *busiest;
1930         unsigned long imbalance;
1931         int nr_moved, all_pinned;
1932         int active_balance = 0;
1933
1934         spin_lock(&this_rq->lock);
1935         schedstat_inc(sd, lb_cnt[idle]);
1936
1937         group = find_busiest_group(sd, this_cpu, &imbalance, idle);
1938         if (!group) {
1939                 schedstat_inc(sd, lb_nobusyg[idle]);
1940                 goto out_balanced;
1941         }
1942
1943         busiest = find_busiest_queue(group);
1944         if (!busiest) {
1945                 schedstat_inc(sd, lb_nobusyq[idle]);
1946                 goto out_balanced;
1947         }
1948
1949         BUG_ON(busiest == this_rq);
1950
1951         schedstat_add(sd, lb_imbalance[idle], imbalance);
1952
1953         nr_moved = 0;
1954         if (busiest->nr_running > 1) {
1955                 /*
1956                  * Attempt to move tasks. If find_busiest_group has found
1957                  * an imbalance but busiest->nr_running <= 1, the group is
1958                  * still unbalanced. nr_moved simply stays zero, so it is
1959                  * correctly treated as an imbalance.
1960                  */
1961                 double_lock_balance(this_rq, busiest);
1962                 nr_moved = move_tasks(this_rq, this_cpu, busiest,
1963                                                 imbalance, sd, idle,
1964                                                 &all_pinned);
1965                 spin_unlock(&busiest->lock);
1966
1967                 /* All tasks on this runqueue were pinned by CPU affinity */
1968                 if (unlikely(all_pinned))
1969                         goto out_balanced;
1970         }
1971
1972         spin_unlock(&this_rq->lock);
1973
1974         if (!nr_moved) {
1975                 schedstat_inc(sd, lb_failed[idle]);
1976                 sd->nr_balance_failed++;
1977
1978                 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
1979
1980                         spin_lock(&busiest->lock);
1981                         if (!busiest->active_balance) {
1982                                 busiest->active_balance = 1;
1983                                 busiest->push_cpu = this_cpu;
1984                                 active_balance = 1;
1985                         }
1986                         spin_unlock(&busiest->lock);
1987                         if (active_balance)
1988                                 wake_up_process(busiest->migration_thread);
1989
1990                         /*
1991                          * We've kicked active balancing, reset the failure
1992                          * counter.
1993                          */
1994                         sd->nr_balance_failed = sd->cache_nice_tries+1;
1995                 }
1996         } else
1997                 sd->nr_balance_failed = 0;
1998
1999         if (likely(!active_balance)) {
2000                 /* We were unbalanced, so reset the balancing interval */
2001                 sd->balance_interval = sd->min_interval;
2002         } else {
2003                 /*
2004                  * If we've begun active balancing, start to back off. This
2005                  * case may not be covered by the all_pinned logic if there
2006                  * is only 1 task on the busy runqueue (because we don't call
2007                  * move_tasks).
2008                  */
2009                 if (sd->balance_interval < sd->max_interval)
2010                         sd->balance_interval *= 2;
2011         }
2012
2013         return nr_moved;
2014
2015 out_balanced:
2016         spin_unlock(&this_rq->lock);
2017
2018         schedstat_inc(sd, lb_balanced[idle]);
2019
2020         sd->nr_balance_failed = 0;
2021         /* tune up the balancing interval */
2022         if (sd->balance_interval < sd->max_interval)
2023                 sd->balance_interval *= 2;
2024
2025         return 0;
2026 }
2027
2028 /*
2029  * Check this_cpu to ensure it is balanced within domain. Attempt to move
2030  * tasks if there is an imbalance.
2031  *
2032  * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2033  * this_rq is locked.
2034  */
2035 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2036                                 struct sched_domain *sd)
2037 {
2038         struct sched_group *group;
2039         runqueue_t *busiest = NULL;
2040         unsigned long imbalance;
2041         int nr_moved = 0;
2042
2043         schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2044         group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
2045         if (!group) {
2046                 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2047                 goto out_balanced;
2048         }
2049
2050         busiest = find_busiest_queue(group);
2051         if (!busiest) {
2052                 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2053                 goto out_balanced;
2054         }
2055
2056         BUG_ON(busiest == this_rq);
2057
2058         /* Attempt to move tasks */
2059         double_lock_balance(this_rq, busiest);
2060
2061         schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2062         nr_moved = move_tasks(this_rq, this_cpu, busiest,
2063                                         imbalance, sd, NEWLY_IDLE, NULL);
2064         if (!nr_moved)
2065                 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2066         else
2067                 sd->nr_balance_failed = 0;
2068
2069         spin_unlock(&busiest->lock);
2070         return nr_moved;
2071
2072 out_balanced:
2073         schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
2074         sd->nr_balance_failed = 0;
2075         return 0;
2076 }
2077
2078 /*
2079  * idle_balance is called by schedule() if this_cpu is about to become
2080  * idle. Attempts to pull tasks from other CPUs.
2081  */
2082 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
2083 {
2084         struct sched_domain *sd;
2085
2086         for_each_domain(this_cpu, sd) {
2087                 if (sd->flags & SD_BALANCE_NEWIDLE) {
2088                         if (load_balance_newidle(this_cpu, this_rq, sd)) {
2089                                 /* We've pulled tasks over so stop searching */
2090                                 break;
2091                         }
2092                 }
2093         }
2094 }
2095
2096 /*
2097  * active_load_balance is run by migration threads. It pushes running tasks
2098  * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2099  * running on each physical CPU where possible, and avoids physical /
2100  * logical imbalances.
2101  *
2102  * Called with busiest_rq locked.
2103  */
2104 static void active_load_balance(runqueue_t *busiest_rq, int busiest_cpu)
2105 {
2106         struct sched_domain *sd;
2107         runqueue_t *target_rq;
2108         int target_cpu = busiest_rq->push_cpu;
2109
2110         if (busiest_rq->nr_running <= 1)
2111                 /* no task to move */
2112                 return;
2113
2114         target_rq = cpu_rq(target_cpu);
2115
2116         /*
2117          * This condition is "impossible", if it occurs
2118          * we need to fix it.  Originally reported by
2119          * Bjorn Helgaas on a 128-cpu setup.
2120          */
2121         BUG_ON(busiest_rq == target_rq);
2122
2123         /* move a task from busiest_rq to target_rq */
2124         double_lock_balance(busiest_rq, target_rq);
2125
2126         /* Search for an sd spanning us and the target CPU. */
2127         for_each_domain(target_cpu, sd)
2128                 if ((sd->flags & SD_LOAD_BALANCE) &&
2129                         cpu_isset(busiest_cpu, sd->span))
2130                                 break;
2131
2132         if (unlikely(sd == NULL))
2133                 goto out;
2134
2135         schedstat_inc(sd, alb_cnt);
2136
2137         if (move_tasks(target_rq, target_cpu, busiest_rq, 1, sd, SCHED_IDLE, NULL))
2138                 schedstat_inc(sd, alb_pushed);
2139         else
2140                 schedstat_inc(sd, alb_failed);
2141 out:
2142         spin_unlock(&target_rq->lock);
2143 }
2144
2145 /*
2146  * rebalance_tick will get called every timer tick, on every CPU.
2147  *
2148  * It checks each scheduling domain to see if it is due to be balanced,
2149  * and initiates a balancing operation if so.
2150  *
2151  * Balancing parameters are set up in arch_init_sched_domains.
2152  */
2153
2154 /* Don't have all balancing operations going off at once */
2155 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2156
2157 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2158                            enum idle_type idle)
2159 {
2160         unsigned long old_load, this_load;
2161         unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2162         struct sched_domain *sd;
2163         int i;
2164
2165         this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
2166         /* Update our load */
2167         for (i = 0; i < 3; i++) {
2168                 unsigned long new_load = this_load;
2169                 int scale = 1 << i;
2170                 old_load = this_rq->cpu_load[i];
2171                 /*
2172                  * Round up the averaging division if load is increasing. This
2173                  * prevents us from getting stuck on 9 if the load is 10, for
2174                  * example.
2175                  */
2176                 if (new_load > old_load)
2177                         new_load += scale-1;
2178                 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) / scale;
2179         }
2180
2181         for_each_domain(this_cpu, sd) {
2182                 unsigned long interval;
2183
2184                 if (!(sd->flags & SD_LOAD_BALANCE))
2185                         continue;
2186
2187                 interval = sd->balance_interval;
2188                 if (idle != SCHED_IDLE)
2189                         interval *= sd->busy_factor;
2190
2191                 /* scale ms to jiffies */
2192                 interval = msecs_to_jiffies(interval);
2193                 if (unlikely(!interval))
2194                         interval = 1;
2195
2196                 if (j - sd->last_balance >= interval) {
2197                         if (load_balance(this_cpu, this_rq, sd, idle)) {
2198                                 /* We've pulled tasks over so no longer idle */
2199                                 idle = NOT_IDLE;
2200                         }
2201                         sd->last_balance += interval;
2202                 }
2203         }
2204 }
2205 #else
2206 /*
2207  * on UP we do not need to balance between CPUs:
2208  */
2209 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2210 {
2211 }
2212 static inline void idle_balance(int cpu, runqueue_t *rq)
2213 {
2214 }
2215 #endif
2216
2217 static inline int wake_priority_sleeper(runqueue_t *rq)
2218 {
2219         int ret = 0;
2220 #ifdef CONFIG_SCHED_SMT
2221         spin_lock(&rq->lock);
2222         /*
2223          * If an SMT sibling task has been put to sleep for priority
2224          * reasons reschedule the idle task to see if it can now run.
2225          */
2226         if (rq->nr_running) {
2227                 resched_task(rq->idle);
2228                 ret = 1;
2229         }
2230         spin_unlock(&rq->lock);
2231 #endif
2232         return ret;
2233 }
2234
2235 DEFINE_PER_CPU(struct kernel_stat, kstat);
2236
2237 EXPORT_PER_CPU_SYMBOL(kstat);
2238
2239 /*
2240  * This is called on clock ticks and on context switches.
2241  * Bank in p->sched_time the ns elapsed since the last tick or switch.
2242  */
2243 static inline void update_cpu_clock(task_t *p, runqueue_t *rq,
2244                                     unsigned long long now)
2245 {
2246         unsigned long long last = max(p->timestamp, rq->timestamp_last_tick);
2247         p->sched_time += now - last;
2248 }
2249
2250 /*
2251  * Return current->sched_time plus any more ns on the sched_clock
2252  * that have not yet been banked.
2253  */
2254 unsigned long long current_sched_time(const task_t *tsk)
2255 {
2256         unsigned long long ns;
2257         unsigned long flags;
2258         local_irq_save(flags);
2259         ns = max(tsk->timestamp, task_rq(tsk)->timestamp_last_tick);
2260         ns = tsk->sched_time + (sched_clock() - ns);
2261         local_irq_restore(flags);
2262         return ns;
2263 }
2264
2265 /*
2266  * We place interactive tasks back into the active array, if possible.
2267  *
2268  * To guarantee that this does not starve expired tasks we ignore the
2269  * interactivity of a task if the first expired task had to wait more
2270  * than a 'reasonable' amount of time. This deadline timeout is
2271  * load-dependent, as the frequency of array switched decreases with
2272  * increasing number of running tasks. We also ignore the interactivity
2273  * if a better static_prio task has expired:
2274  */
2275 #define EXPIRED_STARVING(rq) \
2276         ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2277                 (jiffies - (rq)->expired_timestamp >= \
2278                         STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2279                         ((rq)->curr->static_prio > (rq)->best_expired_prio))
2280
2281 /*
2282  * Account user cpu time to a process.
2283  * @p: the process that the cpu time gets accounted to
2284  * @hardirq_offset: the offset to subtract from hardirq_count()
2285  * @cputime: the cpu time spent in user space since the last update
2286  */
2287 void account_user_time(struct task_struct *p, cputime_t cputime)
2288 {
2289         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2290         cputime64_t tmp;
2291
2292         p->utime = cputime_add(p->utime, cputime);
2293
2294         /* Add user time to cpustat. */
2295         tmp = cputime_to_cputime64(cputime);
2296         if (TASK_NICE(p) > 0)
2297                 cpustat->nice = cputime64_add(cpustat->nice, tmp);
2298         else
2299                 cpustat->user = cputime64_add(cpustat->user, tmp);
2300 }
2301
2302 /*
2303  * Account system cpu time to a process.
2304  * @p: the process that the cpu time gets accounted to
2305  * @hardirq_offset: the offset to subtract from hardirq_count()
2306  * @cputime: the cpu time spent in kernel space since the last update
2307  */
2308 void account_system_time(struct task_struct *p, int hardirq_offset,
2309                          cputime_t cputime)
2310 {
2311         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2312         runqueue_t *rq = this_rq();
2313         cputime64_t tmp;
2314
2315         p->stime = cputime_add(p->stime, cputime);
2316
2317         /* Add system time to cpustat. */
2318         tmp = cputime_to_cputime64(cputime);
2319         if (hardirq_count() - hardirq_offset)
2320                 cpustat->irq = cputime64_add(cpustat->irq, tmp);
2321         else if (softirq_count())
2322                 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
2323         else if (p != rq->idle)
2324                 cpustat->system = cputime64_add(cpustat->system, tmp);
2325         else if (atomic_read(&rq->nr_iowait) > 0)
2326                 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2327         else
2328                 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2329         /* Account for system time used */
2330         acct_update_integrals(p);
2331         /* Update rss highwater mark */
2332         update_mem_hiwater(p);
2333 }
2334
2335 /*
2336  * Account for involuntary wait time.
2337  * @p: the process from which the cpu time has been stolen
2338  * @steal: the cpu time spent in involuntary wait
2339  */
2340 void account_steal_time(struct task_struct *p, cputime_t steal)
2341 {
2342         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2343         cputime64_t tmp = cputime_to_cputime64(steal);
2344         runqueue_t *rq = this_rq();
2345
2346         if (p == rq->idle) {
2347                 p->stime = cputime_add(p->stime, steal);
2348                 if (atomic_read(&rq->nr_iowait) > 0)
2349                         cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2350                 else
2351                         cpustat->idle = cputime64_add(cpustat->idle, tmp);
2352         } else
2353                 cpustat->steal = cputime64_add(cpustat->steal, tmp);
2354 }
2355
2356 /*
2357  * This function gets called by the timer code, with HZ frequency.
2358  * We call it with interrupts disabled.
2359  *
2360  * It also gets called by the fork code, when changing the parent's
2361  * timeslices.
2362  */
2363 void scheduler_tick(void)
2364 {
2365         int cpu = smp_processor_id();
2366         runqueue_t *rq = this_rq();
2367         task_t *p = current;
2368         unsigned long long now = sched_clock();
2369
2370         update_cpu_clock(p, rq, now);
2371
2372         rq->timestamp_last_tick = now;
2373
2374         if (p == rq->idle) {
2375                 if (wake_priority_sleeper(rq))
2376                         goto out;
2377                 rebalance_tick(cpu, rq, SCHED_IDLE);
2378                 return;
2379         }
2380
2381         /* Task might have expired already, but not scheduled off yet */
2382         if (p->array != rq->active) {
2383                 set_tsk_need_resched(p);
2384                 goto out;
2385         }
2386         spin_lock(&rq->lock);
2387         /*
2388          * The task was running during this tick - update the
2389          * time slice counter. Note: we do not update a thread's
2390          * priority until it either goes to sleep or uses up its
2391          * timeslice. This makes it possible for interactive tasks
2392          * to use up their timeslices at their highest priority levels.
2393          */
2394         if (rt_task(p)) {
2395                 /*
2396                  * RR tasks need a special form of timeslice management.
2397                  * FIFO tasks have no timeslices.
2398                  */
2399                 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2400                         p->time_slice = task_timeslice(p);
2401                         p->first_time_slice = 0;
2402                         set_tsk_need_resched(p);
2403
2404                         /* put it at the end of the queue: */
2405                         requeue_task(p, rq->active);
2406                 }
2407                 goto out_unlock;
2408         }
2409         if (!--p->time_slice) {
2410                 dequeue_task(p, rq->active);
2411                 set_tsk_need_resched(p);
2412                 p->prio = effective_prio(p);
2413                 p->time_slice = task_timeslice(p);
2414                 p->first_time_slice = 0;
2415
2416                 if (!rq->expired_timestamp)
2417                         rq->expired_timestamp = jiffies;
2418                 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2419                         enqueue_task(p, rq->expired);
2420                         if (p->static_prio < rq->best_expired_prio)
2421                                 rq->best_expired_prio = p->static_prio;
2422                 } else
2423                         enqueue_task(p, rq->active);
2424         } else {
2425                 /*
2426                  * Prevent a too long timeslice allowing a task to monopolize
2427                  * the CPU. We do this by splitting up the timeslice into
2428                  * smaller pieces.
2429                  *
2430                  * Note: this does not mean the task's timeslices expire or
2431                  * get lost in any way, they just might be preempted by
2432                  * another task of equal priority. (one with higher
2433                  * priority would have preempted this task already.) We
2434                  * requeue this task to the end of the list on this priority
2435                  * level, which is in essence a round-robin of tasks with
2436                  * equal priority.
2437                  *
2438                  * This only applies to tasks in the interactive
2439                  * delta range with at least TIMESLICE_GRANULARITY to requeue.
2440                  */
2441                 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2442                         p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2443                         (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2444                         (p->array == rq->active)) {
2445
2446                         requeue_task(p, rq->active);
2447                         set_tsk_need_resched(p);
2448                 }
2449         }
2450 out_unlock:
2451         spin_unlock(&rq->lock);
2452 out:
2453         rebalance_tick(cpu, rq, NOT_IDLE);
2454 }
2455
2456 #ifdef CONFIG_SCHED_SMT
2457 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2458 {
2459         struct sched_domain *sd = this_rq->sd;
2460         cpumask_t sibling_map;
2461         int i;
2462
2463         if (!(sd->flags & SD_SHARE_CPUPOWER))
2464                 return;
2465
2466         /*
2467          * Unlock the current runqueue because we have to lock in
2468          * CPU order to avoid deadlocks. Caller knows that we might
2469          * unlock. We keep IRQs disabled.
2470          */
2471         spin_unlock(&this_rq->lock);
2472
2473         sibling_map = sd->span;
2474
2475         for_each_cpu_mask(i, sibling_map)
2476                 spin_lock(&cpu_rq(i)->lock);
2477         /*
2478          * We clear this CPU from the mask. This both simplifies the
2479          * inner loop and keps this_rq locked when we exit:
2480          */
2481         cpu_clear(this_cpu, sibling_map);
2482
2483         for_each_cpu_mask(i, sibling_map) {
2484                 runqueue_t *smt_rq = cpu_rq(i);
2485
2486                 /*
2487                  * If an SMT sibling task is sleeping due to priority
2488                  * reasons wake it up now.
2489                  */
2490                 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
2491                         resched_task(smt_rq->idle);
2492         }
2493
2494         for_each_cpu_mask(i, sibling_map)
2495                 spin_unlock(&cpu_rq(i)->lock);
2496         /*
2497          * We exit with this_cpu's rq still held and IRQs
2498          * still disabled:
2499          */
2500 }
2501
2502 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2503 {
2504         struct sched_domain *sd = this_rq->sd;
2505         cpumask_t sibling_map;
2506         prio_array_t *array;
2507         int ret = 0, i;
2508         task_t *p;
2509
2510         if (!(sd->flags & SD_SHARE_CPUPOWER))
2511                 return 0;
2512
2513         /*
2514          * The same locking rules and details apply as for
2515          * wake_sleeping_dependent():
2516          */
2517         spin_unlock(&this_rq->lock);
2518         sibling_map = sd->span;
2519         for_each_cpu_mask(i, sibling_map)
2520                 spin_lock(&cpu_rq(i)->lock);
2521         cpu_clear(this_cpu, sibling_map);
2522
2523         /*
2524          * Establish next task to be run - it might have gone away because
2525          * we released the runqueue lock above:
2526          */
2527         if (!this_rq->nr_running)
2528                 goto out_unlock;
2529         array = this_rq->active;
2530         if (!array->nr_active)
2531                 array = this_rq->expired;
2532         BUG_ON(!array->nr_active);
2533
2534         p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
2535                 task_t, run_list);
2536
2537         for_each_cpu_mask(i, sibling_map) {
2538                 runqueue_t *smt_rq = cpu_rq(i);
2539                 task_t *smt_curr = smt_rq->curr;
2540
2541                 /*
2542                  * If a user task with lower static priority than the
2543                  * running task on the SMT sibling is trying to schedule,
2544                  * delay it till there is proportionately less timeslice
2545                  * left of the sibling task to prevent a lower priority
2546                  * task from using an unfair proportion of the
2547                  * physical cpu's resources. -ck
2548                  */
2549                 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
2550                         task_timeslice(p) || rt_task(smt_curr)) &&
2551                         p->mm && smt_curr->mm && !rt_task(p))
2552                                 ret = 1;
2553
2554                 /*
2555                  * Reschedule a lower priority task on the SMT sibling,
2556                  * or wake it up if it has been put to sleep for priority
2557                  * reasons.
2558                  */
2559                 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
2560                         task_timeslice(smt_curr) || rt_task(p)) &&
2561                         smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
2562                         (smt_curr == smt_rq->idle && smt_rq->nr_running))
2563                                 resched_task(smt_curr);
2564         }
2565 out_unlock:
2566         for_each_cpu_mask(i, sibling_map)
2567                 spin_unlock(&cpu_rq(i)->lock);
2568         return ret;
2569 }
2570 #else
2571 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2572 {
2573 }
2574
2575 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2576 {
2577         return 0;
2578 }
2579 #endif
2580
2581 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
2582
2583 void fastcall add_preempt_count(int val)
2584 {
2585         /*
2586          * Underflow?
2587          */
2588         BUG_ON((preempt_count() < 0));
2589         preempt_count() += val;
2590         /*
2591          * Spinlock count overflowing soon?
2592          */
2593         BUG_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
2594 }
2595 EXPORT_SYMBOL(add_preempt_count);
2596
2597 void fastcall sub_preempt_count(int val)
2598 {
2599         /*
2600          * Underflow?
2601          */
2602         BUG_ON(val > preempt_count());
2603         /*
2604          * Is the spinlock portion underflowing?
2605          */
2606         BUG_ON((val < PREEMPT_MASK) && !(preempt_count() & PREEMPT_MASK));
2607         preempt_count() -= val;
2608 }
2609 EXPORT_SYMBOL(sub_preempt_count);
2610
2611 #endif
2612
2613 /*
2614  * schedule() is the main scheduler function.
2615  */
2616 asmlinkage void __sched schedule(void)
2617 {
2618         long *switch_count;
2619         task_t *prev, *next;
2620         runqueue_t *rq;
2621         prio_array_t *array;
2622         struct list_head *queue;
2623         unsigned long long now;
2624         unsigned long run_time;
2625         int cpu, idx;
2626
2627         /*
2628          * Test if we are atomic.  Since do_exit() needs to call into
2629          * schedule() atomically, we ignore that path for now.
2630          * Otherwise, whine if we are scheduling when we should not be.
2631          */
2632         if (likely(!current->exit_state)) {
2633                 if (unlikely(in_atomic())) {
2634                         printk(KERN_ERR "scheduling while atomic: "
2635                                 "%s/0x%08x/%d\n",
2636                                 current->comm, preempt_count(), current->pid);
2637                         dump_stack();
2638                 }
2639         }
2640         profile_hit(SCHED_PROFILING, __builtin_return_address(0));
2641
2642 need_resched:
2643         preempt_disable();
2644         prev = current;
2645         release_kernel_lock(prev);
2646 need_resched_nonpreemptible:
2647         rq = this_rq();
2648
2649         /*
2650          * The idle thread is not allowed to schedule!
2651          * Remove this check after it has been exercised a bit.
2652          */
2653         if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
2654                 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
2655                 dump_stack();
2656         }
2657
2658         schedstat_inc(rq, sched_cnt);
2659         now = sched_clock();
2660         if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
2661                 run_time = now - prev->timestamp;
2662                 if (unlikely((long long)(now - prev->timestamp) < 0))
2663                         run_time = 0;
2664         } else
2665                 run_time = NS_MAX_SLEEP_AVG;
2666
2667         /*
2668          * Tasks charged proportionately less run_time at high sleep_avg to
2669          * delay them losing their interactive status
2670          */
2671         run_time /= (CURRENT_BONUS(prev) ? : 1);
2672
2673         spin_lock_irq(&rq->lock);
2674
2675         if (unlikely(prev->flags & PF_DEAD))
2676                 prev->state = EXIT_DEAD;
2677
2678         switch_count = &prev->nivcsw;
2679         if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2680                 switch_count = &prev->nvcsw;
2681                 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2682                                 unlikely(signal_pending(prev))))
2683                         prev->state = TASK_RUNNING;
2684                 else {
2685                         if (prev->state == TASK_UNINTERRUPTIBLE)
2686                                 rq->nr_uninterruptible++;
2687                         deactivate_task(prev, rq);
2688                 }
2689         }
2690
2691         cpu = smp_processor_id();
2692         if (unlikely(!rq->nr_running)) {
2693 go_idle:
2694                 idle_balance(cpu, rq);
2695                 if (!rq->nr_running) {
2696                         next = rq->idle;
2697                         rq->expired_timestamp = 0;
2698                         wake_sleeping_dependent(cpu, rq);
2699                         /*
2700                          * wake_sleeping_dependent() might have released
2701                          * the runqueue, so break out if we got new
2702                          * tasks meanwhile:
2703                          */
2704                         if (!rq->nr_running)
2705                                 goto switch_tasks;
2706                 }
2707         } else {
2708                 if (dependent_sleeper(cpu, rq)) {
2709                         next = rq->idle;
2710                         goto switch_tasks;
2711                 }
2712                 /*
2713                  * dependent_sleeper() releases and reacquires the runqueue
2714                  * lock, hence go into the idle loop if the rq went
2715                  * empty meanwhile:
2716                  */
2717                 if (unlikely(!rq->nr_running))
2718                         goto go_idle;
2719         }
2720
2721         array = rq->active;
2722         if (unlikely(!array->nr_active)) {
2723                 /*
2724                  * Switch the active and expired arrays.
2725                  */
2726                 schedstat_inc(rq, sched_switch);
2727                 rq->active = rq->expired;
2728                 rq->expired = array;
2729                 array = rq->active;
2730                 rq->expired_timestamp = 0;
2731                 rq->best_expired_prio = MAX_PRIO;
2732         }
2733
2734         idx = sched_find_first_bit(array->bitmap);
2735         queue = array->queue + idx;
2736         next = list_entry(queue->next, task_t, run_list);
2737
2738         if (!rt_task(next) && next->activated > 0) {
2739                 unsigned long long delta = now - next->timestamp;
2740                 if (unlikely((long long)(now - next->timestamp) < 0))
2741                         delta = 0;
2742
2743                 if (next->activated == 1)
2744                         delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
2745
2746                 array = next->array;
2747                 dequeue_task(next, array);
2748                 recalc_task_prio(next, next->timestamp + delta);
2749                 enqueue_task(next, array);
2750         }
2751         next->activated = 0;
2752 switch_tasks:
2753         if (next == rq->idle)
2754                 schedstat_inc(rq, sched_goidle);
2755         prefetch(next);
2756         clear_tsk_need_resched(prev);
2757         rcu_qsctr_inc(task_cpu(prev));
2758
2759         update_cpu_clock(prev, rq, now);
2760
2761         prev->sleep_avg -= run_time;
2762         if ((long)prev->sleep_avg <= 0)
2763                 prev->sleep_avg = 0;
2764         prev->timestamp = prev->last_ran = now;
2765
2766         sched_info_switch(prev, next);
2767         if (likely(prev != next)) {
2768                 next->timestamp = now;
2769                 rq->nr_switches++;
2770                 rq->curr = next;
2771                 ++*switch_count;
2772
2773                 prepare_arch_switch(rq, next);
2774                 prev = context_switch(rq, prev, next);
2775                 barrier();
2776
2777                 finish_task_switch(prev);
2778         } else
2779                 spin_unlock_irq(&rq->lock);
2780
2781         prev = current;
2782         if (unlikely(reacquire_kernel_lock(prev) < 0))
2783                 goto need_resched_nonpreemptible;
2784         preempt_enable_no_resched();
2785         if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2786                 goto need_resched;
2787 }
2788
2789 EXPORT_SYMBOL(schedule);
2790
2791 #ifdef CONFIG_PREEMPT
2792 /*
2793  * this is is the entry point to schedule() from in-kernel preemption
2794  * off of preempt_enable.  Kernel preemptions off return from interrupt
2795  * occur there and call schedule directly.
2796  */
2797 asmlinkage void __sched preempt_schedule(void)
2798 {
2799         struct thread_info *ti = current_thread_info();
2800 #ifdef CONFIG_PREEMPT_BKL
2801         struct task_struct *task = current;
2802         int saved_lock_depth;
2803 #endif
2804         /*
2805          * If there is a non-zero preempt_count or interrupts are disabled,
2806          * we do not want to preempt the current task.  Just return..
2807          */
2808         if (unlikely(ti->preempt_count || irqs_disabled()))
2809                 return;
2810
2811 need_resched:
2812         add_preempt_count(PREEMPT_ACTIVE);
2813         /*
2814          * We keep the big kernel semaphore locked, but we
2815          * clear ->lock_depth so that schedule() doesnt
2816          * auto-release the semaphore:
2817          */
2818 #ifdef CONFIG_PREEMPT_BKL
2819         saved_lock_depth = task->lock_depth;
2820         task->lock_depth = -1;
2821 #endif
2822         schedule();
2823 #ifdef CONFIG_PREEMPT_BKL
2824         task->lock_depth = saved_lock_depth;
2825 #endif
2826         sub_preempt_count(PREEMPT_ACTIVE);
2827
2828         /* we could miss a preemption opportunity between schedule and now */
2829         barrier();
2830         if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2831                 goto need_resched;
2832 }
2833
2834 EXPORT_SYMBOL(preempt_schedule);
2835
2836 /*
2837  * this is is the entry point to schedule() from kernel preemption
2838  * off of irq context.
2839  * Note, that this is called and return with irqs disabled. This will
2840  * protect us against recursive calling from irq.
2841  */
2842 asmlinkage void __sched preempt_schedule_irq(void)
2843 {
2844         struct thread_info *ti = current_thread_info();
2845 #ifdef CONFIG_PREEMPT_BKL
2846         struct task_struct *task = current;
2847         int saved_lock_depth;
2848 #endif
2849         /* Catch callers which need to be fixed*/
2850         BUG_ON(ti->preempt_count || !irqs_disabled());
2851
2852 need_resched:
2853         add_preempt_count(PREEMPT_ACTIVE);
2854         /*
2855          * We keep the big kernel semaphore locked, but we
2856          * clear ->lock_depth so that schedule() doesnt
2857          * auto-release the semaphore:
2858          */
2859 #ifdef CONFIG_PREEMPT_BKL
2860         saved_lock_depth = task->lock_depth;
2861         task->lock_depth = -1;
2862 #endif
2863         local_irq_enable();
2864         schedule();
2865         local_irq_disable();
2866 #ifdef CONFIG_PREEMPT_BKL
2867         task->lock_depth = saved_lock_depth;
2868 #endif
2869         sub_preempt_count(PREEMPT_ACTIVE);
2870
2871         /* we could miss a preemption opportunity between schedule and now */
2872         barrier();
2873         if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2874                 goto need_resched;
2875 }
2876
2877 #endif /* CONFIG_PREEMPT */
2878
2879 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
2880 {
2881         task_t *p = curr->private;
2882         return try_to_wake_up(p, mode, sync);
2883 }
2884
2885 EXPORT_SYMBOL(default_wake_function);
2886
2887 /*
2888  * The core wakeup function.  Non-exclusive wakeups (nr_exclusive == 0) just
2889  * wake everything up.  If it's an exclusive wakeup (nr_exclusive == small +ve
2890  * number) then we wake all the non-exclusive tasks and one exclusive task.
2891  *
2892  * There are circumstances in which we can try to wake a task which has already
2893  * started to run but is not in state TASK_RUNNING.  try_to_wake_up() returns
2894  * zero in this (rare) case, and we handle it by continuing to scan the queue.
2895  */
2896 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
2897                              int nr_exclusive, int sync, void *key)
2898 {
2899         struct list_head *tmp, *next;
2900
2901         list_for_each_safe(tmp, next, &q->task_list) {
2902                 wait_queue_t *curr;
2903                 unsigned flags;
2904                 curr = list_entry(tmp, wait_queue_t, task_list);
2905                 flags = curr->flags;
2906                 if (curr->func(curr, mode, sync, key) &&
2907                     (flags & WQ_FLAG_EXCLUSIVE) &&
2908                     !--nr_exclusive)
2909                         break;
2910         }
2911 }
2912
2913 /**
2914  * __wake_up - wake up threads blocked on a waitqueue.
2915  * @q: the waitqueue
2916  * @mode: which threads
2917  * @nr_exclusive: how many wake-one or wake-many threads to wake up
2918  * @key: is directly passed to the wakeup function
2919  */
2920 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
2921                                 int nr_exclusive, void *key)
2922 {
2923         unsigned long flags;
2924
2925         spin_lock_irqsave(&q->lock, flags);
2926         __wake_up_common(q, mode, nr_exclusive, 0, key);
2927         spin_unlock_irqrestore(&q->lock, flags);
2928 }
2929
2930 EXPORT_SYMBOL(__wake_up);
2931
2932 /*
2933  * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
2934  */
2935 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
2936 {
2937         __wake_up_common(q, mode, 1, 0, NULL);
2938 }
2939
2940 /**
2941  * __wake_up_sync - wake up threads blocked on a waitqueue.
2942  * @q: the waitqueue
2943  * @mode: which threads
2944  * @nr_exclusive: how many wake-one or wake-many threads to wake up
2945  *
2946  * The sync wakeup differs that the waker knows that it will schedule
2947  * away soon, so while the target thread will be woken up, it will not
2948  * be migrated to another CPU - ie. the two threads are 'synchronized'
2949  * with each other. This can prevent needless bouncing between CPUs.
2950  *
2951  * On UP it can prevent extra preemption.
2952  */
2953 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
2954 {
2955         unsigned long flags;
2956         int sync = 1;
2957
2958         if (unlikely(!q))
2959                 return;
2960
2961         if (unlikely(!nr_exclusive))
2962                 sync = 0;
2963
2964         spin_lock_irqsave(&q->lock, flags);
2965         __wake_up_common(q, mode, nr_exclusive, sync, NULL);
2966         spin_unlock_irqrestore(&q->lock, flags);
2967 }
2968 EXPORT_SYMBOL_GPL(__wake_up_sync);      /* For internal use only */
2969
2970 void fastcall complete(struct completion *x)
2971 {
2972         unsigned long flags;
2973
2974         spin_lock_irqsave(&x->wait.lock, flags);
2975         x->done++;
2976         __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2977                          1, 0, NULL);
2978         spin_unlock_irqrestore(&x->wait.lock, flags);
2979 }
2980 EXPORT_SYMBOL(complete);
2981
2982 void fastcall complete_all(struct completion *x)
2983 {
2984         unsigned long flags;
2985
2986         spin_lock_irqsave(&x->wait.lock, flags);
2987         x->done += UINT_MAX/2;
2988         __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2989                          0, 0, NULL);
2990         spin_unlock_irqrestore(&x->wait.lock, flags);
2991 }
2992 EXPORT_SYMBOL(complete_all);
2993
2994 void fastcall __sched wait_for_completion(struct completion *x)
2995 {
2996         might_sleep();
2997         spin_lock_irq(&x->wait.lock);
2998         if (!x->done) {
2999                 DECLARE_WAITQUEUE(wait, current);
3000
3001                 wait.flags |= WQ_FLAG_EXCLUSIVE;
3002                 __add_wait_queue_tail(&x->wait, &wait);
3003                 do {
3004                         __set_current_state(TASK_UNINTERRUPTIBLE);
3005                         spin_unlock_irq(&x->wait.lock);
3006                         schedule();
3007                         spin_lock_irq(&x->wait.lock);
3008                 } while (!x->done);
3009                 __remove_wait_queue(&x->wait, &wait);
3010         }
3011         x->done--;
3012         spin_unlock_irq(&x->wait.lock);
3013 }
3014 EXPORT_SYMBOL(wait_for_completion);
3015
3016 unsigned long fastcall __sched
3017 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3018 {
3019         might_sleep();
3020
3021         spin_lock_irq(&x->wait.lock);
3022         if (!x->done) {
3023                 DECLARE_WAITQUEUE(wait, current);
3024
3025                 wait.flags |= WQ_FLAG_EXCLUSIVE;
3026                 __add_wait_queue_tail(&x->wait, &wait);
3027                 do {
3028                         __set_current_state(TASK_UNINTERRUPTIBLE);
3029                         spin_unlock_irq(&x->wait.lock);
3030                         timeout = schedule_timeout(timeout);
3031                         spin_lock_irq(&x->wait.lock);
3032                         if (!timeout) {
3033                                 __remove_wait_queue(&x->wait, &wait);
3034                                 goto out;
3035                         }
3036                 } while (!x->done);
3037                 __remove_wait_queue(&x->wait, &wait);
3038         }
3039         x->done--;
3040 out:
3041         spin_unlock_irq(&x->wait.lock);
3042         return timeout;
3043 }
3044 EXPORT_SYMBOL(wait_for_completion_timeout);
3045
3046 int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3047 {
3048         int ret = 0;
3049
3050         might_sleep();
3051
3052         spin_lock_irq(&x->wait.lock);
3053         if (!x->done) {
3054                 DECLARE_WAITQUEUE(wait, current);
3055
3056                 wait.flags |= WQ_FLAG_EXCLUSIVE;
3057                 __add_wait_queue_tail(&x->wait, &wait);
3058                 do {
3059                         if (signal_pending(current)) {
3060                                 ret = -ERESTARTSYS;
3061                                 __remove_wait_queue(&x->wait, &wait);
3062                                 goto out;
3063                         }
3064                         __set_current_state(TASK_INTERRUPTIBLE);
3065                         spin_unlock_irq(&x->wait.lock);
3066                         schedule();
3067                         spin_lock_irq(&x->wait.lock);
3068                 } while (!x->done);
3069                 __remove_wait_queue(&x->wait, &wait);
3070         }
3071         x->done--;
3072 out:
3073         spin_unlock_irq(&x->wait.lock);
3074
3075         return ret;
3076 }
3077 EXPORT_SYMBOL(wait_for_completion_interruptible);
3078
3079 unsigned long fastcall __sched
3080 wait_for_completion_interruptible_timeout(struct completion *x,
3081                                           unsigned long timeout)
3082 {
3083         might_sleep();
3084
3085         spin_lock_irq(&x->wait.lock);
3086         if (!x->done) {
3087                 DECLARE_WAITQUEUE(wait, current);
3088
3089                 wait.flags |= WQ_FLAG_EXCLUSIVE;
3090                 __add_wait_queue_tail(&x->wait, &wait);
3091                 do {
3092                         if (signal_pending(current)) {
3093                                 timeout = -ERESTARTSYS;
3094                                 __remove_wait_queue(&x->wait, &wait);
3095                                 goto out;
3096                         }
3097                         __set_current_state(TASK_INTERRUPTIBLE);
3098                         spin_unlock_irq(&x->wait.lock);
3099                         timeout = schedule_timeout(timeout);
3100                         spin_lock_irq(&x->wait.lock);
3101                         if (!timeout) {
3102                                 __remove_wait_queue(&x->wait, &wait);
3103                                 goto out;
3104                         }
3105                 } while (!x->done);
3106                 __remove_wait_queue(&x->wait, &wait);
3107         }
3108         x->done--;
3109 out:
3110         spin_unlock_irq(&x->wait.lock);
3111         return timeout;
3112 }
3113 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3114
3115
3116 #define SLEEP_ON_VAR                                    \
3117         unsigned long flags;                            \
3118         wait_queue_t wait;                              \
3119         init_waitqueue_entry(&wait, current);
3120
3121 #define SLEEP_ON_HEAD                                   \
3122         spin_lock_irqsave(&q->lock,flags);              \
3123         __add_wait_queue(q, &wait);                     \
3124         spin_unlock(&q->lock);
3125
3126 #define SLEEP_ON_TAIL                                   \
3127         spin_lock_irq(&q->lock);                        \
3128         __remove_wait_queue(q, &wait);                  \
3129         spin_unlock_irqrestore(&q->lock, flags);
3130
3131 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3132 {
3133         SLEEP_ON_VAR
3134
3135         current->state = TASK_INTERRUPTIBLE;
3136
3137         SLEEP_ON_HEAD
3138         schedule();
3139         SLEEP_ON_TAIL
3140 }
3141
3142 EXPORT_SYMBOL(interruptible_sleep_on);
3143
3144 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3145 {
3146         SLEEP_ON_VAR
3147
3148         current->state = TASK_INTERRUPTIBLE;
3149
3150         SLEEP_ON_HEAD
3151         timeout = schedule_timeout(timeout);
3152         SLEEP_ON_TAIL
3153
3154         return timeout;
3155 }
3156
3157 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3158
3159 void fastcall __sched sleep_on(wait_queue_head_t *q)
3160 {
3161         SLEEP_ON_VAR
3162
3163         current->state = TASK_UNINTERRUPTIBLE;
3164
3165         SLEEP_ON_HEAD
3166         schedule();
3167         SLEEP_ON_TAIL
3168 }
3169
3170 EXPORT_SYMBOL(sleep_on);
3171
3172 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3173 {
3174         SLEEP_ON_VAR
3175
3176         current->state = TASK_UNINTERRUPTIBLE;
3177
3178         SLEEP_ON_HEAD
3179         timeout = schedule_timeout(timeout);
3180         SLEEP_ON_TAIL
3181
3182         return timeout;
3183 }
3184
3185 EXPORT_SYMBOL(sleep_on_timeout);
3186
3187 void set_user_nice(task_t *p, long nice)
3188 {
3189         unsigned long flags;
3190         prio_array_t *array;
3191         runqueue_t *rq;
3192         int old_prio, new_prio, delta;
3193
3194         if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3195                 return;
3196         /*
3197          * We have to be careful, if called from sys_setpriority(),
3198          * the task might be in the middle of scheduling on another CPU.
3199          */
3200         rq = task_rq_lock(p, &flags);
3201         /*
3202          * The RT priorities are set via sched_setscheduler(), but we still
3203          * allow the 'normal' nice value to be set - but as expected
3204          * it wont have any effect on scheduling until the task is
3205          * not SCHED_NORMAL:
3206          */
3207         if (rt_task(p)) {
3208                 p->static_prio = NICE_TO_PRIO(nice);
3209                 goto out_unlock;
3210         }
3211         array = p->array;
3212         if (array)
3213                 dequeue_task(p, array);
3214
3215         old_prio = p->prio;
3216         new_prio = NICE_TO_PRIO(nice);
3217         delta = new_prio - old_prio;
3218         p->static_prio = NICE_TO_PRIO(nice);
3219         p->prio += delta;
3220
3221         if (array) {
3222                 enqueue_task(p, array);
3223                 /*
3224                  * If the task increased its priority or is running and
3225                  * lowered its priority, then reschedule its CPU:
3226                  */
3227                 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3228                         resched_task(rq->curr);
3229         }
3230 out_unlock:
3231         task_rq_unlock(rq, &flags);
3232 }
3233
3234 EXPORT_SYMBOL(set_user_nice);
3235
3236 /*
3237  * can_nice - check if a task can reduce its nice value
3238  * @p: task
3239  * @nice: nice value
3240  */
3241 int can_nice(const task_t *p, const int nice)
3242 {
3243         /* convert nice value [19,-20] to rlimit style value [0,39] */
3244         int nice_rlim = 19 - nice;
3245         return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
3246                 capable(CAP_SYS_NICE));
3247 }
3248
3249 #ifdef __ARCH_WANT_SYS_NICE
3250
3251 /*
3252  * sys_nice - change the priority of the current process.
3253  * @increment: priority increment
3254  *
3255  * sys_setpriority is a more generic, but much slower function that
3256  * does similar things.
3257  */
3258 asmlinkage long sys_nice(int increment)
3259 {
3260         int retval;
3261         long nice;
3262
3263         /*
3264          * Setpriority might change our priority at the same moment.
3265          * We don't have to worry. Conceptually one call occurs first
3266          * and we have a single winner.
3267          */
3268         if (increment < -40)
3269                 increment = -40;
3270         if (increment > 40)
3271                 increment = 40;
3272
3273         nice = PRIO_TO_NICE(current->static_prio) + increment;
3274         if (nice < -20)
3275                 nice = -20;
3276         if (nice > 19)
3277                 nice = 19;
3278
3279         if (increment < 0 && !can_nice(current, nice))
3280                 return -EPERM;
3281
3282         retval = security_task_setnice(current, nice);
3283         if (retval)
3284                 return retval;
3285
3286         set_user_nice(current, nice);
3287         return 0;
3288 }
3289
3290 #endif
3291
3292 /**
3293  * task_prio - return the priority value of a given task.
3294  * @p: the task in question.
3295  *
3296  * This is the priority value as seen by users in /proc.
3297  * RT tasks are offset by -200. Normal tasks are centered
3298  * around 0, value goes from -16 to +15.
3299  */
3300 int task_prio(const task_t *p)
3301 {
3302         return p->prio - MAX_RT_PRIO;
3303 }
3304
3305 /**
3306  * task_nice - return the nice value of a given task.
3307  * @p: the task in question.
3308  */
3309 int task_nice(const task_t *p)
3310 {
3311         return TASK_NICE(p);
3312 }
3313
3314 /*
3315  * The only users of task_nice are binfmt_elf and binfmt_elf32.
3316  * binfmt_elf is no longer modular, but binfmt_elf32 still is.
3317  * Therefore, task_nice is needed if there is a compat_mode.
3318  */
3319 #ifdef CONFIG_COMPAT
3320 EXPORT_SYMBOL_GPL(task_nice);
3321 #endif
3322
3323 /**
3324  * idle_cpu - is a given cpu idle currently?
3325  * @cpu: the processor in question.
3326  */
3327 int idle_cpu(int cpu)
3328 {
3329         return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3330 }
3331
3332 EXPORT_SYMBOL_GPL(idle_cpu);
3333
3334 /**
3335  * idle_task - return the idle task for a given cpu.
3336  * @cpu: the processor in question.
3337  */
3338 task_t *idle_task(int cpu)
3339 {
3340         return cpu_rq(cpu)->idle;
3341 }
3342
3343 /**
3344  * find_process_by_pid - find a process with a matching PID value.
3345  * @pid: the pid in question.
3346  */
3347 static inline task_t *find_process_by_pid(pid_t pid)
3348 {
3349         return pid ? find_task_by_pid(pid) : current;
3350 }
3351
3352 /* Actually do priority change: must hold rq lock. */
3353 static void __setscheduler(struct task_struct *p, int policy, int prio)
3354 {
3355         BUG_ON(p->array);
3356         p->policy = policy;
3357         p->rt_priority = prio;
3358         if (policy != SCHED_NORMAL)
3359                 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
3360         else
3361                 p->prio = p->static_prio;
3362 }
3363
3364 /**
3365  * sched_setscheduler - change the scheduling policy and/or RT priority of
3366  * a thread.
3367  * @p: the task in question.
3368  * @policy: new policy.
3369  * @param: structure containing the new RT priority.
3370  */
3371 int sched_setscheduler(struct task_struct *p, int policy, struct sched_param *param)
3372 {
3373         int retval;
3374         int oldprio, oldpolicy = -1;
3375         prio_array_t *array;
3376         unsigned long flags;
3377         runqueue_t *rq;
3378
3379 recheck:
3380         /* double check policy once rq lock held */
3381         if (policy < 0)
3382                 policy = oldpolicy = p->policy;
3383         else if (policy != SCHED_FIFO && policy != SCHED_RR &&
3384                                 policy != SCHED_NORMAL)
3385                         return -EINVAL;
3386         /*
3387          * Valid priorities for SCHED_FIFO and SCHED_RR are
3388          * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
3389          */
3390         if (param->sched_priority < 0 ||
3391             param->sched_priority > MAX_USER_RT_PRIO-1)
3392                 return -EINVAL;
3393         if ((policy == SCHED_NORMAL) != (param->sched_priority == 0))
3394                 return -EINVAL;
3395
3396         if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
3397             param->sched_priority > p->signal->rlim[RLIMIT_RTPRIO].rlim_cur &&
3398             !capable(CAP_SYS_NICE))
3399                 return -EPERM;
3400         if ((current->euid != p->euid) && (current->euid != p->uid) &&
3401             !capable(CAP_SYS_NICE))
3402                 return -EPERM;
3403
3404         retval = security_task_setscheduler(p, policy, param);
3405         if (retval)
3406                 return retval;
3407         /*
3408          * To be able to change p->policy safely, the apropriate
3409          * runqueue lock must be held.
3410          */
3411         rq = task_rq_lock(p, &flags);
3412         /* recheck policy now with rq lock held */
3413         if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3414                 policy = oldpolicy = -1;
3415                 task_rq_unlock(rq, &flags);
3416                 goto recheck;
3417         }
3418         array = p->array;
3419         if (array)
3420                 deactivate_task(p, rq);
3421         oldprio = p->prio;
3422         __setscheduler(p, policy, param->sched_priority);
3423         if (array) {
3424                 __activate_task(p, rq);
3425                 /*
3426                  * Reschedule if we are currently running on this runqueue and
3427                  * our priority decreased, or if we are not currently running on
3428                  * this runqueue and our priority is higher than the current's
3429                  */
3430                 if (task_running(rq, p)) {
3431                         if (p->prio > oldprio)
3432                                 resched_task(rq->curr);
3433                 } else if (TASK_PREEMPTS_CURR(p, rq))
3434                         resched_task(rq->curr);
3435         }
3436         task_rq_unlock(rq, &flags);
3437         return 0;
3438 }
3439 EXPORT_SYMBOL_GPL(sched_setscheduler);
3440
3441 static int do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3442 {
3443         int retval;
3444         struct sched_param lparam;
3445         struct task_struct *p;
3446
3447         if (!param || pid < 0)
3448                 return -EINVAL;
3449         if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
3450                 return -EFAULT;
3451         read_lock_irq(&tasklist_lock);
3452         p = find_process_by_pid(pid);
3453         if (!p) {
3454                 read_unlock_irq(&tasklist_lock);
3455                 return -ESRCH;
3456         }
3457         retval = sched_setscheduler(p, policy, &lparam);
3458         read_unlock_irq(&tasklist_lock);
3459         return retval;
3460 }
3461
3462 /**
3463  * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3464  * @pid: the pid in question.
3465  * @policy: new policy.
3466  * @param: structure containing the new RT priority.
3467  */
3468 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3469                                        struct sched_param __user *param)
3470 {
3471         return do_sched_setscheduler(pid, policy, param);
3472 }
3473
3474 /**
3475  * sys_sched_setparam - set/change the RT priority of a thread
3476  * @pid: the pid in question.
3477  * @param: structure containing the new RT priority.
3478  */
3479 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3480 {
3481         return do_sched_setscheduler(pid, -1, param);
3482 }
3483
3484 /**
3485  * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3486  * @pid: the pid in question.
3487  */
3488 asmlinkage long sys_sched_getscheduler(pid_t pid)
3489 {
3490         int retval = -EINVAL;
3491         task_t *p;
3492
3493         if (pid < 0)
3494                 goto out_nounlock;
3495
3496         retval = -ESRCH;
3497         read_lock(&tasklist_lock);
3498         p = find_process_by_pid(pid);
3499         if (p) {
3500                 retval = security_task_getscheduler(p);
3501                 if (!retval)
3502                         retval = p->policy;
3503         }
3504         read_unlock(&tasklist_lock);
3505
3506 out_nounlock:
3507         return retval;
3508 }
3509
3510 /**
3511  * sys_sched_getscheduler - get the RT priority of a thread
3512  * @pid: the pid in question.
3513  * @param: structure containing the RT priority.
3514  */
3515 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3516 {
3517         struct sched_param lp;
3518         int retval = -EINVAL;
3519         task_t *p;
3520
3521         if (!param || pid < 0)
3522                 goto out_nounlock;
3523
3524         read_lock(&tasklist_lock);
3525         p = find_process_by_pid(pid);
3526         retval = -ESRCH;
3527         if (!p)
3528                 goto out_unlock;
3529
3530         retval = security_task_getscheduler(p);
3531         if (retval)
3532                 goto out_unlock;
3533
3534         lp.sched_priority = p->rt_priority;
3535         read_unlock(&tasklist_lock);
3536
3537         /*
3538          * This one might sleep, we cannot do it with a spinlock held ...
3539          */
3540         retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3541
3542 out_nounlock:
3543         return retval;
3544
3545 out_unlock:
3546         read_unlock(&tasklist_lock);
3547         return retval;
3548 }
3549
3550 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
3551 {
3552         task_t *p;
3553         int retval;
3554         cpumask_t cpus_allowed;
3555
3556         lock_cpu_hotplug();
3557         read_lock(&tasklist_lock);
3558
3559         p = find_process_by_pid(pid);
3560         if (!p) {
3561                 read_unlock(&tasklist_lock);
3562                 unlock_cpu_hotplug();
3563                 return -ESRCH;
3564         }
3565
3566         /*
3567          * It is not safe to call set_cpus_allowed with the
3568          * tasklist_lock held.  We will bump the task_struct's
3569          * usage count and then drop tasklist_lock.
3570          */
3571         get_task_struct(p);
3572         read_unlock(&tasklist_lock);
3573
3574         retval = -EPERM;
3575         if ((current->euid != p->euid) && (current->euid != p->uid) &&
3576                         !capable(CAP_SYS_NICE))
3577                 goto out_unlock;
3578
3579         cpus_allowed = cpuset_cpus_allowed(p);
3580         cpus_and(new_mask, new_mask, cpus_allowed);
3581         retval = set_cpus_allowed(p, new_mask);
3582
3583 out_unlock:
3584         put_task_struct(p);
3585         unlock_cpu_hotplug();
3586         return retval;
3587 }
3588
3589 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
3590                              cpumask_t *new_mask)
3591 {
3592         if (len < sizeof(cpumask_t)) {
3593                 memset(new_mask, 0, sizeof(cpumask_t));
3594         } else if (len > sizeof(cpumask_t)) {
3595                 len = sizeof(cpumask_t);
3596         }
3597         return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
3598 }
3599
3600 /**
3601  * sys_sched_setaffinity - set the cpu affinity of a process
3602  * @pid: pid of the process
3603  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3604  * @user_mask_ptr: user-space pointer to the new cpu mask
3605  */
3606 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
3607                                       unsigned long __user *user_mask_ptr)
3608 {
3609         cpumask_t new_mask;
3610         int retval;
3611
3612         retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
3613         if (retval)
3614                 return retval;
3615
3616         return sched_setaffinity(pid, new_mask);
3617 }
3618
3619 /*
3620  * Represents all cpu's present in the system
3621  * In systems capable of hotplug, this map could dynamically grow
3622  * as new cpu's are detected in the system via any platform specific
3623  * method, such as ACPI for e.g.
3624  */
3625
3626 cpumask_t cpu_present_map;
3627 EXPORT_SYMBOL(cpu_present_map);
3628
3629 #ifndef CONFIG_SMP
3630 cpumask_t cpu_online_map = CPU_MASK_ALL;
3631 cpumask_t cpu_possible_map = CPU_MASK_ALL;
3632 #endif
3633
3634 long sched_getaffinity(pid_t pid, cpumask_t *mask)
3635 {
3636         int retval;
3637         task_t *p;
3638
3639         lock_cpu_hotplug();
3640         read_lock(&tasklist_lock);
3641
3642         retval = -ESRCH;
3643         p = find_process_by_pid(pid);
3644         if (!p)
3645                 goto out_unlock;
3646
3647         retval = 0;
3648         cpus_and(*mask, p->cpus_allowed, cpu_possible_map);
3649
3650 out_unlock:
3651         read_unlock(&tasklist_lock);
3652         unlock_cpu_hotplug();
3653         if (retval)
3654                 return retval;
3655
3656         return 0;
3657 }
3658
3659 /**
3660  * sys_sched_getaffinity - get the cpu affinity of a process
3661  * @pid: pid of the process
3662  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3663  * @user_mask_ptr: user-space pointer to hold the current cpu mask
3664  */
3665 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
3666                                       unsigned long __user *user_mask_ptr)
3667 {
3668         int ret;
3669         cpumask_t mask;
3670
3671         if (len < sizeof(cpumask_t))
3672                 return -EINVAL;
3673
3674         ret = sched_getaffinity(pid, &mask);
3675         if (ret < 0)
3676                 return ret;
3677
3678         if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
3679                 return -EFAULT;
3680
3681         return sizeof(cpumask_t);
3682 }
3683
3684 /**
3685  * sys_sched_yield - yield the current processor to other threads.
3686  *
3687  * this function yields the current CPU by moving the calling thread
3688  * to the expired array. If there are no other threads running on this
3689  * CPU then this function will return.
3690  */
3691 asmlinkage long sys_sched_yield(void)
3692 {
3693         runqueue_t *rq = this_rq_lock();
3694         prio_array_t *array = current->array;
3695         prio_array_t *target = rq->expired;
3696
3697         schedstat_inc(rq, yld_cnt);
3698         /*
3699          * We implement yielding by moving the task into the expired
3700          * queue.
3701          *
3702          * (special rule: RT tasks will just roundrobin in the active
3703          *  array.)
3704          */
3705         if (rt_task(current))
3706                 target = rq->active;
3707
3708         if (current->array->nr_active == 1) {
3709                 schedstat_inc(rq, yld_act_empty);
3710                 if (!rq->expired->nr_active)
3711                         schedstat_inc(rq, yld_both_empty);
3712         } else if (!rq->expired->nr_active)
3713                 schedstat_inc(rq, yld_exp_empty);
3714
3715         if (array != target) {
3716                 dequeue_task(current, array);
3717                 enqueue_task(current, target);
3718         } else
3719                 /*
3720                  * requeue_task is cheaper so perform that if possible.
3721                  */
3722                 requeue_task(current, array);
3723
3724         /*
3725          * Since we are going to call schedule() anyway, there's
3726          * no need to preempt or enable interrupts:
3727          */
3728         __release(rq->lock);
3729         _raw_spin_unlock(&rq->lock);
3730         preempt_enable_no_resched();
3731
3732         schedule();
3733
3734         return 0;
3735 }
3736
3737 static inline void __cond_resched(void)
3738 {
3739         do {
3740                 add_preempt_count(PREEMPT_ACTIVE);
3741                 schedule();
3742                 sub_preempt_count(PREEMPT_ACTIVE);
3743         } while (need_resched());
3744 }
3745
3746 int __sched cond_resched(void)
3747 {
3748         if (need_resched()) {
3749                 __cond_resched();
3750                 return 1;
3751         }
3752         return 0;
3753 }
3754
3755 EXPORT_SYMBOL(cond_resched);
3756
3757 /*
3758  * cond_resched_lock() - if a reschedule is pending, drop the given lock,
3759  * call schedule, and on return reacquire the lock.
3760  *
3761  * This works OK both with and without CONFIG_PREEMPT.  We do strange low-level
3762  * operations here to prevent schedule() from being called twice (once via
3763  * spin_unlock(), once by hand).
3764  */
3765 int cond_resched_lock(spinlock_t * lock)
3766 {
3767         int ret = 0;
3768
3769         if (need_lockbreak(lock)) {
3770                 spin_unlock(lock);
3771                 cpu_relax();
3772                 ret = 1;
3773                 spin_lock(lock);
3774         }
3775         if (need_resched()) {
3776                 _raw_spin_unlock(lock);
3777                 preempt_enable_no_resched();
3778                 __cond_resched();
3779                 ret = 1;
3780                 spin_lock(lock);
3781         }
3782         return ret;
3783 }
3784
3785 EXPORT_SYMBOL(cond_resched_lock);
3786
3787 int __sched cond_resched_softirq(void)
3788 {
3789         BUG_ON(!in_softirq());
3790
3791         if (need_resched()) {
3792                 __local_bh_enable();
3793                 __cond_resched();
3794                 local_bh_disable();
3795                 return 1;
3796         }
3797         return 0;
3798 }
3799
3800 EXPORT_SYMBOL(cond_resched_softirq);
3801
3802
3803 /**
3804  * yield - yield the current processor to other threads.
3805  *
3806  * this is a shortcut for kernel-space yielding - it marks the
3807  * thread runnable and calls sys_sched_yield().
3808  */
3809 void __sched yield(void)
3810 {
3811         set_current_state(TASK_RUNNING);
3812         sys_sched_yield();
3813 }
3814
3815 EXPORT_SYMBOL(yield);
3816
3817 /*
3818  * This task is about to go to sleep on IO.  Increment rq->nr_iowait so
3819  * that process accounting knows that this is a task in IO wait state.
3820  *
3821  * But don't do that if it is a deliberate, throttling IO wait (this task
3822  * has set its backing_dev_info: the queue against which it should throttle)
3823  */
3824 void __sched io_schedule(void)
3825 {
3826         struct runqueue *rq = &per_cpu(runqueues, raw_smp_processor_id());
3827
3828         atomic_inc(&rq->nr_iowait);
3829         schedule();
3830         atomic_dec(&rq->nr_iowait);
3831 }
3832
3833 EXPORT_SYMBOL(io_schedule);
3834
3835 long __sched io_schedule_timeout(long timeout)
3836 {
3837         struct runqueue *rq = &per_cpu(runqueues, raw_smp_processor_id());
3838         long ret;
3839
3840         atomic_inc(&rq->nr_iowait);
3841         ret = schedule_timeout(timeout);
3842         atomic_dec(&rq->nr_iowait);
3843         return ret;
3844 }
3845
3846 /**
3847  * sys_sched_get_priority_max - return maximum RT priority.
3848  * @policy: scheduling class.
3849  *
3850  * this syscall returns the maximum rt_priority that can be used
3851  * by a given scheduling class.
3852  */
3853 asmlinkage long sys_sched_get_priority_max(int policy)
3854 {
3855         int ret = -EINVAL;
3856
3857         switch (policy) {
3858         case SCHED_FIFO:
3859         case SCHED_RR:
3860                 ret = MAX_USER_RT_PRIO-1;
3861                 break;
3862         case SCHED_NORMAL:
3863                 ret = 0;
3864                 break;
3865         }
3866         return ret;
3867 }
3868
3869 /**
3870  * sys_sched_get_priority_min - return minimum RT priority.
3871  * @policy: scheduling class.
3872  *
3873  * this syscall returns the minimum rt_priority that can be used
3874  * by a given scheduling class.
3875  */
3876 asmlinkage long sys_sched_get_priority_min(int policy)
3877 {
3878         int ret = -EINVAL;
3879
3880         switch (policy) {
3881         case SCHED_FIFO:
3882         case SCHED_RR:
3883                 ret = 1;
3884                 break;
3885         case SCHED_NORMAL:
3886                 ret = 0;
3887         }
3888         return ret;
3889 }
3890
3891 /**
3892  * sys_sched_rr_get_interval - return the default timeslice of a process.
3893  * @pid: pid of the process.
3894  * @interval: userspace pointer to the timeslice value.
3895  *
3896  * this syscall writes the default timeslice value of a given process
3897  * into the user-space timespec buffer. A value of '0' means infinity.
3898  */
3899 asmlinkage
3900 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
3901 {
3902         int retval = -EINVAL;
3903         struct timespec t;
3904         task_t *p;
3905
3906         if (pid < 0)
3907                 goto out_nounlock;
3908
3909         retval = -ESRCH;
3910         read_lock(&tasklist_lock);
3911         p = find_process_by_pid(pid);
3912         if (!p)
3913                 goto out_unlock;
3914
3915         retval = security_task_getscheduler(p);
3916         if (retval)
3917                 goto out_unlock;
3918
3919         jiffies_to_timespec(p->policy & SCHED_FIFO ?
3920                                 0 : task_timeslice(p), &t);
3921         read_unlock(&tasklist_lock);
3922         retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
3923 out_nounlock:
3924         return retval;
3925 out_unlock:
3926         read_unlock(&tasklist_lock);
3927         return retval;
3928 }
3929
3930 static inline struct task_struct *eldest_child(struct task_struct *p)
3931 {
3932         if (list_empty(&p->children)) return NULL;
3933         return list_entry(p->children.next,struct task_struct,sibling);
3934 }
3935
3936 static inline struct task_struct *older_sibling(struct task_struct *p)
3937 {
3938         if (p->sibling.prev==&p->parent->children) return NULL;
3939         return list_entry(p->sibling.prev,struct task_struct,sibling);
3940 }
3941
3942 static inline struct task_struct *younger_sibling(struct task_struct *p)
3943 {
3944         if (p->sibling.next==&p->parent->children) return NULL;
3945         return list_entry(p->sibling.next,struct task_struct,sibling);
3946 }
3947
3948 static void show_task(task_t * p)
3949 {
3950         task_t *relative;
3951         unsigned state;
3952         unsigned long free = 0;
3953         static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
3954
3955         printk("%-13.13s ", p->comm);
3956         state = p->state ? __ffs(p->state) + 1 : 0;
3957         if (state < ARRAY_SIZE(stat_nam))
3958                 printk(stat_nam[state]);
3959         else
3960                 printk("?");
3961 #if (BITS_PER_LONG == 32)
3962         if (state == TASK_RUNNING)
3963                 printk(" running ");
3964         else
3965                 printk(" %08lX ", thread_saved_pc(p));
3966 #else
3967         if (state == TASK_RUNNING)
3968                 printk("  running task   ");
3969         else
3970                 printk(" %016lx ", thread_saved_pc(p));
3971 #endif
3972 #ifdef CONFIG_DEBUG_STACK_USAGE
3973         {
3974                 unsigned long * n = (unsigned long *) (p->thread_info+1);
3975                 while (!*n)
3976                         n++;
3977                 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
3978         }
3979 #endif
3980         printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
3981         if ((relative = eldest_child(p)))
3982                 printk("%5d ", relative->pid);
3983         else
3984                 printk("      ");
3985         if ((relative = younger_sibling(p)))
3986                 printk("%7d", relative->pid);
3987         else
3988                 printk("       ");
3989         if ((relative = older_sibling(p)))
3990                 printk(" %5d", relative->pid);
3991         else
3992                 printk("      ");
3993         if (!p->mm)
3994                 printk(" (L-TLB)\n");
3995         else
3996                 printk(" (NOTLB)\n");
3997
3998         if (state != TASK_RUNNING)
3999                 show_stack(p, NULL);
4000 }
4001
4002 void show_state(void)
4003 {
4004         task_t *g, *p;
4005
4006 #if (BITS_PER_LONG == 32)
4007         printk("\n"
4008                "                                               sibling\n");
4009         printk("  task             PC      pid father child younger older\n");
4010 #else
4011         printk("\n"
4012                "                                                       sibling\n");
4013         printk("  task                 PC          pid father child younger older\n");
4014 #endif
4015         read_lock(&tasklist_lock);
4016         do_each_thread(g, p) {
4017                 /*
4018                  * reset the NMI-timeout, listing all files on a slow
4019                  * console might take alot of time:
4020                  */
4021                 touch_nmi_watchdog();
4022                 show_task(p);
4023         } while_each_thread(g, p);
4024
4025         read_unlock(&tasklist_lock);
4026 }
4027
4028 void __devinit init_idle(task_t *idle, int cpu)
4029 {
4030         runqueue_t *rq = cpu_rq(cpu);
4031         unsigned long flags;
4032
4033         idle->sleep_avg = 0;
4034         idle->array = NULL;
4035         idle->prio = MAX_PRIO;
4036         idle->state = TASK_RUNNING;
4037         idle->cpus_allowed = cpumask_of_cpu(cpu);
4038         set_task_cpu(idle, cpu);
4039
4040         spin_lock_irqsave(&rq->lock, flags);
4041         rq->curr = rq->idle = idle;
4042         set_tsk_need_resched(idle);
4043         spin_unlock_irqrestore(&rq->lock, flags);
4044
4045         /* Set the preempt count _outside_ the spinlocks! */
4046 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4047         idle->thread_info->preempt_count = (idle->lock_depth >= 0);
4048 #else
4049         idle->thread_info->preempt_count = 0;
4050 #endif
4051 }
4052
4053 /*
4054  * In a system that switches off the HZ timer nohz_cpu_mask
4055  * indicates which cpus entered this state. This is used
4056  * in the rcu update to wait only for active cpus. For system
4057  * which do not switch off the HZ timer nohz_cpu_mask should
4058  * always be CPU_MASK_NONE.
4059  */
4060 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4061
4062 #ifdef CONFIG_SMP
4063 /*
4064  * This is how migration works:
4065  *
4066  * 1) we queue a migration_req_t structure in the source CPU's
4067  *    runqueue and wake up that CPU's migration thread.
4068  * 2) we down() the locked semaphore => thread blocks.
4069  * 3) migration thread wakes up (implicitly it forces the migrated
4070  *    thread off the CPU)
4071  * 4) it gets the migration request and checks whether the migrated
4072  *    task is still in the wrong runqueue.
4073  * 5) if it's in the wrong runqueue then the migration thread removes
4074  *    it and puts it into the right queue.
4075  * 6) migration thread up()s the semaphore.
4076  * 7) we wake up and the migration is done.
4077  */
4078
4079 /*
4080  * Change a given task's CPU affinity. Migrate the thread to a
4081  * proper CPU and schedule it away if the CPU it's executing on
4082  * is removed from the allowed bitmask.
4083  *
4084  * NOTE: the caller must have a valid reference to the task, the
4085  * task must not exit() & deallocate itself prematurely.  The
4086  * call is not atomic; no spinlocks may be held.
4087  */
4088 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
4089 {
4090         unsigned long flags;
4091         int ret = 0;
4092         migration_req_t req;
4093         runqueue_t *rq;
4094
4095         rq = task_rq_lock(p, &flags);
4096         if (!cpus_intersects(new_mask, cpu_online_map)) {
4097                 ret = -EINVAL;
4098                 goto out;
4099         }
4100
4101         p->cpus_allowed = new_mask;
4102         /* Can the task run on the task's current CPU? If so, we're done */
4103         if (cpu_isset(task_cpu(p), new_mask))
4104                 goto out;
4105
4106         if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4107                 /* Need help from migration thread: drop lock and wait. */
4108                 task_rq_unlock(rq, &flags);
4109                 wake_up_process(rq->migration_thread);
4110                 wait_for_completion(&req.done);
4111                 tlb_migrate_finish(p->mm);
4112                 return 0;
4113         }
4114 out:
4115         task_rq_unlock(rq, &flags);
4116         return ret;
4117 }
4118
4119 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4120
4121 /*
4122  * Move (not current) task off this cpu, onto dest cpu.  We're doing
4123  * this because either it can't run here any more (set_cpus_allowed()
4124  * away from this CPU, or CPU going down), or because we're
4125  * attempting to rebalance this task on exec (sched_exec).
4126  *
4127  * So we race with normal scheduler movements, but that's OK, as long
4128  * as the task is no longer on this CPU.
4129  */
4130 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4131 {
4132         runqueue_t *rq_dest, *rq_src;
4133
4134         if (unlikely(cpu_is_offline(dest_cpu)))
4135                 return;
4136
4137         rq_src = cpu_rq(src_cpu);
4138         rq_dest = cpu_rq(dest_cpu);
4139
4140         double_rq_lock(rq_src, rq_dest);
4141         /* Already moved. */
4142         if (task_cpu(p) != src_cpu)
4143                 goto out;
4144         /* Affinity changed (again). */
4145         if (!cpu_isset(dest_cpu, p->cpus_allowed))
4146                 goto out;
4147
4148         set_task_cpu(p, dest_cpu);
4149         if (p->array) {
4150                 /*
4151                  * Sync timestamp with rq_dest's before activating.
4152                  * The same thing could be achieved by doing this step
4153                  * afterwards, and pretending it was a local activate.
4154                  * This way is cleaner and logically correct.
4155                  */
4156                 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4157                                 + rq_dest->timestamp_last_tick;
4158                 deactivate_task(p, rq_src);
4159                 activate_task(p, rq_dest, 0);
4160                 if (TASK_PREEMPTS_CURR(p, rq_dest))
4161                         resched_task(rq_dest->curr);
4162         }
4163
4164 out:
4165         double_rq_unlock(rq_src, rq_dest);
4166 }
4167
4168 /*
4169  * migration_thread - this is a highprio system thread that performs
4170  * thread migration by bumping thread off CPU then 'pushing' onto
4171  * another runqueue.
4172  */
4173 static int migration_thread(void * data)
4174 {
4175         runqueue_t *rq;
4176         int cpu = (long)data;
4177
4178         rq = cpu_rq(cpu);
4179         BUG_ON(rq->migration_thread != current);
4180
4181         set_current_state(TASK_INTERRUPTIBLE);
4182         while (!kthread_should_stop()) {
4183                 struct list_head *head;
4184                 migration_req_t *req;
4185
4186                 if (current->flags & PF_FREEZE)
4187                         refrigerator(PF_FREEZE);
4188
4189                 spin_lock_irq(&rq->lock);
4190
4191                 if (cpu_is_offline(cpu)) {
4192                         spin_unlock_irq(&rq->lock);
4193                         goto wait_to_die;
4194                 }
4195
4196                 if (rq->active_balance) {
4197                         active_load_balance(rq, cpu);
4198                         rq->active_balance = 0;
4199                 }
4200
4201                 head = &rq->migration_queue;
4202
4203                 if (list_empty(head)) {
4204                         spin_unlock_irq(&rq->lock);
4205                         schedule();
4206                         set_current_state(TASK_INTERRUPTIBLE);
4207                         continue;
4208                 }
4209                 req = list_entry(head->next, migration_req_t, list);
4210                 list_del_init(head->next);
4211
4212                 if (req->type == REQ_MOVE_TASK) {
4213                         spin_unlock(&rq->lock);
4214                         __migrate_task(req->task, cpu, req->dest_cpu);
4215                         local_irq_enable();
4216                 } else if (req->type == REQ_SET_DOMAIN) {
4217                         rq->sd = req->sd;
4218                         spin_unlock_irq(&rq->lock);
4219                 } else {
4220                         spin_unlock_irq(&rq->lock);
4221                         WARN_ON(1);
4222                 }
4223
4224                 complete(&req->done);
4225         }
4226         __set_current_state(TASK_RUNNING);
4227         return 0;
4228
4229 wait_to_die:
4230         /* Wait for kthread_stop */
4231         set_current_state(TASK_INTERRUPTIBLE);
4232         while (!kthread_should_stop()) {
4233                 schedule();
4234                 set_current_state(TASK_INTERRUPTIBLE);
4235         }
4236         __set_current_state(TASK_RUNNING);
4237         return 0;
4238 }
4239
4240 #ifdef CONFIG_HOTPLUG_CPU
4241 /* Figure out where task on dead CPU should go, use force if neccessary. */
4242 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
4243 {
4244         int dest_cpu;
4245         cpumask_t mask;
4246
4247         /* On same node? */
4248         mask = node_to_cpumask(cpu_to_node(dead_cpu));
4249         cpus_and(mask, mask, tsk->cpus_allowed);
4250         dest_cpu = any_online_cpu(mask);
4251
4252         /* On any allowed CPU? */
4253         if (dest_cpu == NR_CPUS)
4254                 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4255
4256         /* No more Mr. Nice Guy. */
4257         if (dest_cpu == NR_CPUS) {
4258                 cpus_setall(tsk->cpus_allowed);
4259                 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4260
4261                 /*
4262                  * Don't tell them about moving exiting tasks or
4263                  * kernel threads (both mm NULL), since they never
4264                  * leave kernel.
4265                  */
4266                 if (tsk->mm && printk_ratelimit())
4267                         printk(KERN_INFO "process %d (%s) no "
4268                                "longer affine to cpu%d\n",
4269                                tsk->pid, tsk->comm, dead_cpu);
4270         }
4271         __migrate_task(tsk, dead_cpu, dest_cpu);
4272 }
4273
4274 /*
4275  * While a dead CPU has no uninterruptible tasks queued at this point,
4276  * it might still have a nonzero ->nr_uninterruptible counter, because
4277  * for performance reasons the counter is not stricly tracking tasks to
4278  * their home CPUs. So we just add the counter to another CPU's counter,
4279  * to keep the global sum constant after CPU-down:
4280  */
4281 static void migrate_nr_uninterruptible(runqueue_t *rq_src)
4282 {
4283         runqueue_t *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
4284         unsigned long flags;
4285
4286         local_irq_save(flags);
4287         double_rq_lock(rq_src, rq_dest);
4288         rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
4289         rq_src->nr_uninterruptible = 0;
4290         double_rq_unlock(rq_src, rq_dest);
4291         local_irq_restore(flags);
4292 }
4293
4294 /* Run through task list and migrate tasks from the dead cpu. */
4295 static void migrate_live_tasks(int src_cpu)
4296 {
4297         struct task_struct *tsk, *t;
4298
4299         write_lock_irq(&tasklist_lock);
4300
4301         do_each_thread(t, tsk) {
4302                 if (tsk == current)
4303                         continue;
4304
4305                 if (task_cpu(tsk) == src_cpu)
4306                         move_task_off_dead_cpu(src_cpu, tsk);
4307         } while_each_thread(t, tsk);
4308
4309         write_unlock_irq(&tasklist_lock);
4310 }
4311
4312 /* Schedules idle task to be the next runnable task on current CPU.
4313  * It does so by boosting its priority to highest possible and adding it to
4314  * the _front_ of runqueue. Used by CPU offline code.
4315  */
4316 void sched_idle_next(void)
4317 {
4318         int cpu = smp_processor_id();
4319         runqueue_t *rq = this_rq();
4320         struct task_struct *p = rq->idle;
4321         unsigned long flags;
4322
4323         /* cpu has to be offline */
4324         BUG_ON(cpu_online(cpu));
4325
4326         /* Strictly not necessary since rest of the CPUs are stopped by now
4327          * and interrupts disabled on current cpu.
4328          */
4329         spin_lock_irqsave(&rq->lock, flags);
4330
4331         __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4332         /* Add idle task to _front_ of it's priority queue */
4333         __activate_idle_task(p, rq);
4334
4335         spin_unlock_irqrestore(&rq->lock, flags);
4336 }
4337
4338 /* Ensures that the idle task is using init_mm right before its cpu goes
4339  * offline.
4340  */
4341 void idle_task_exit(void)
4342 {
4343         struct mm_struct *mm = current->active_mm;
4344
4345         BUG_ON(cpu_online(smp_processor_id()));
4346
4347         if (mm != &init_mm)
4348                 switch_mm(mm, &init_mm, current);
4349         mmdrop(mm);
4350 }
4351
4352 static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
4353 {
4354         struct runqueue *rq = cpu_rq(dead_cpu);
4355
4356         /* Must be exiting, otherwise would be on tasklist. */
4357         BUG_ON(tsk->exit_state != EXIT_ZOMBIE && tsk->exit_state != EXIT_DEAD);
4358
4359         /* Cannot have done final schedule yet: would have vanished. */
4360         BUG_ON(tsk->flags & PF_DEAD);
4361
4362         get_task_struct(tsk);
4363
4364         /*
4365          * Drop lock around migration; if someone else moves it,
4366          * that's OK.  No task can be added to this CPU, so iteration is
4367          * fine.
4368          */
4369         spin_unlock_irq(&rq->lock);
4370         move_task_off_dead_cpu(dead_cpu, tsk);
4371         spin_lock_irq(&rq->lock);
4372
4373         put_task_struct(tsk);
4374 }
4375
4376 /* release_task() removes task from tasklist, so we won't find dead tasks. */
4377 static void migrate_dead_tasks(unsigned int dead_cpu)
4378 {
4379         unsigned arr, i;
4380         struct runqueue *rq = cpu_rq(dead_cpu);
4381
4382         for (arr = 0; arr < 2; arr++) {
4383                 for (i = 0; i < MAX_PRIO; i++) {
4384                         struct list_head *list = &rq->arrays[arr].queue[i];
4385                         while (!list_empty(list))
4386                                 migrate_dead(dead_cpu,
4387                                              list_entry(list->next, task_t,
4388                                                         run_list));
4389                 }
4390         }
4391 }
4392 #endif /* CONFIG_HOTPLUG_CPU */
4393
4394 /*
4395  * migration_call - callback that gets triggered when a CPU is added.
4396  * Here we can start up the necessary migration thread for the new CPU.
4397  */
4398 static int migration_call(struct notifier_block *nfb, unsigned long action,
4399                           void *hcpu)
4400 {
4401         int cpu = (long)hcpu;
4402         struct task_struct *p;
4403         struct runqueue *rq;
4404         unsigned long flags;
4405
4406         switch (action) {
4407         case CPU_UP_PREPARE:
4408                 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4409                 if (IS_ERR(p))
4410                         return NOTIFY_BAD;
4411                 p->flags |= PF_NOFREEZE;
4412                 kthread_bind(p, cpu);
4413                 /* Must be high prio: stop_machine expects to yield to it. */
4414                 rq = task_rq_lock(p, &flags);
4415                 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4416                 task_rq_unlock(rq, &flags);
4417                 cpu_rq(cpu)->migration_thread = p;
4418                 break;
4419         case CPU_ONLINE:
4420                 /* Strictly unneccessary, as first user will wake it. */
4421                 wake_up_process(cpu_rq(cpu)->migration_thread);
4422                 break;
4423 #ifdef CONFIG_HOTPLUG_CPU
4424         case CPU_UP_CANCELED:
4425                 /* Unbind it from offline cpu so it can run.  Fall thru. */
4426                 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
4427                 kthread_stop(cpu_rq(cpu)->migration_thread);
4428                 cpu_rq(cpu)->migration_thread = NULL;
4429                 break;
4430         case CPU_DEAD:
4431                 migrate_live_tasks(cpu);
4432                 rq = cpu_rq(cpu);
4433                 kthread_stop(rq->migration_thread);
4434                 rq->migration_thread = NULL;
4435                 /* Idle task back to normal (off runqueue, low prio) */
4436                 rq = task_rq_lock(rq->idle, &flags);
4437                 deactivate_task(rq->idle, rq);
4438                 rq->idle->static_prio = MAX_PRIO;
4439                 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4440                 migrate_dead_tasks(cpu);
4441                 task_rq_unlock(rq, &flags);
4442                 migrate_nr_uninterruptible(rq);
4443                 BUG_ON(rq->nr_running != 0);
4444
4445                 /* No need to migrate the tasks: it was best-effort if
4446                  * they didn't do lock_cpu_hotplug().  Just wake up
4447                  * the requestors. */
4448                 spin_lock_irq(&rq->lock);
4449                 while (!list_empty(&rq->migration_queue)) {
4450                         migration_req_t *req;
4451                         req = list_entry(rq->migration_queue.next,
4452                                          migration_req_t, list);
4453                         BUG_ON(req->type != REQ_MOVE_TASK);
4454                         list_del_init(&req->list);
4455                         complete(&req->done);
4456                 }
4457                 spin_unlock_irq(&rq->lock);
4458                 break;
4459 #endif
4460         }
4461         return NOTIFY_OK;
4462 }
4463
4464 /* Register at highest priority so that task migration (migrate_all_tasks)
4465  * happens before everything else.
4466  */
4467 static struct notifier_block __devinitdata migration_notifier = {
4468         .notifier_call = migration_call,
4469         .priority = 10
4470 };
4471
4472 int __init migration_init(void)
4473 {
4474         void *cpu = (void *)(long)smp_processor_id();
4475         /* Start one for boot CPU. */
4476         migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4477         migration_call(&migration_notifier, CPU_ONLINE, cpu);
4478         register_cpu_notifier(&migration_notifier);
4479         return 0;
4480 }
4481 #endif
4482
4483 #ifdef CONFIG_SMP
4484 #define SCHED_DOMAIN_DEBUG
4485 #ifdef SCHED_DOMAIN_DEBUG
4486 static void sched_domain_debug(struct sched_domain *sd, int cpu)
4487 {
4488         int level = 0;
4489
4490         printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
4491
4492         do {
4493                 int i;
4494                 char str[NR_CPUS];
4495                 struct sched_group *group = sd->groups;
4496                 cpumask_t groupmask;
4497
4498                 cpumask_scnprintf(str, NR_CPUS, sd->span);
4499                 cpus_clear(groupmask);
4500
4501                 printk(KERN_DEBUG);
4502                 for (i = 0; i < level + 1; i++)
4503                         printk(" ");
4504                 printk("domain %d: ", level);
4505
4506                 if (!(sd->flags & SD_LOAD_BALANCE)) {
4507                         printk("does not load-balance\n");
4508                         if (sd->parent)
4509                                 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
4510                         break;
4511                 }
4512
4513                 printk("span %s\n", str);
4514
4515                 if (!cpu_isset(cpu, sd->span))
4516                         printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
4517                 if (!cpu_isset(cpu, group->cpumask))
4518                         printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
4519
4520                 printk(KERN_DEBUG);
4521                 for (i = 0; i < level + 2; i++)
4522                         printk(" ");
4523                 printk("groups:");
4524                 do {
4525                         if (!group) {
4526                                 printk("\n");
4527                                 printk(KERN_ERR "ERROR: group is NULL\n");
4528                                 break;
4529                         }
4530
4531                         if (!group->cpu_power) {
4532                                 printk("\n");
4533                                 printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
4534                         }
4535
4536                         if (!cpus_weight(group->cpumask)) {
4537                                 printk("\n");
4538                                 printk(KERN_ERR "ERROR: empty group\n");
4539                         }
4540
4541                         if (cpus_intersects(groupmask, group->cpumask)) {
4542                                 printk("\n");
4543                                 printk(KERN_ERR "ERROR: repeated CPUs\n");
4544                         }
4545
4546                         cpus_or(groupmask, groupmask, group->cpumask);
4547
4548                         cpumask_scnprintf(str, NR_CPUS, group->cpumask);
4549                         printk(" %s", str);
4550
4551                         group = group->next;
4552                 } while (group != sd->groups);
4553                 printk("\n");
4554
4555                 if (!cpus_equal(sd->span, groupmask))
4556                         printk(KERN_ERR "ERROR: groups don't span domain->span\n");
4557
4558                 level++;
4559                 sd = sd->parent;
4560
4561                 if (sd) {
4562                         if (!cpus_subset(groupmask, sd->span))
4563                                 printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
4564                 }
4565
4566         } while (sd);
4567 }
4568 #else
4569 #define sched_domain_debug(sd, cpu) {}
4570 #endif
4571
4572 /*
4573  * Attach the domain 'sd' to 'cpu' as its base domain.  Callers must
4574  * hold the hotplug lock.
4575  */
4576 void __devinit cpu_attach_domain(struct sched_domain *sd, int cpu)
4577 {
4578         migration_req_t req;
4579         unsigned long flags;
4580         runqueue_t *rq = cpu_rq(cpu);
4581         int local = 1;
4582
4583         sched_domain_debug(sd, cpu);
4584
4585         spin_lock_irqsave(&rq->lock, flags);
4586
4587         if (cpu == smp_processor_id() || !cpu_online(cpu)) {
4588                 rq->sd = sd;
4589         } else {
4590                 init_completion(&req.done);
4591                 req.type = REQ_SET_DOMAIN;
4592                 req.sd = sd;
4593                 list_add(&req.list, &rq->migration_queue);
4594                 local = 0;
4595         }
4596
4597         spin_unlock_irqrestore(&rq->lock, flags);
4598
4599         if (!local) {
4600                 wake_up_process(rq->migration_thread);
4601                 wait_for_completion(&req.done);
4602         }
4603 }
4604
4605 /* cpus with isolated domains */
4606 cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
4607
4608 /* Setup the mask of cpus configured for isolated domains */
4609 static int __init isolated_cpu_setup(char *str)
4610 {
4611         int ints[NR_CPUS], i;
4612
4613         str = get_options(str, ARRAY_SIZE(ints), ints);
4614         cpus_clear(cpu_isolated_map);
4615         for (i = 1; i <= ints[0]; i++)
4616                 if (ints[i] < NR_CPUS)
4617                         cpu_set(ints[i], cpu_isolated_map);
4618         return 1;
4619 }
4620
4621 __setup ("isolcpus=", isolated_cpu_setup);
4622
4623 /*
4624  * init_sched_build_groups takes an array of groups, the cpumask we wish
4625  * to span, and a pointer to a function which identifies what group a CPU
4626  * belongs to. The return value of group_fn must be a valid index into the
4627  * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
4628  * keep track of groups covered with a cpumask_t).
4629  *
4630  * init_sched_build_groups will build a circular linked list of the groups
4631  * covered by the given span, and will set each group's ->cpumask correctly,
4632  * and ->cpu_power to 0.
4633  */
4634 void __devinit init_sched_build_groups(struct sched_group groups[],
4635                         cpumask_t span, int (*group_fn)(int cpu))
4636 {
4637         struct sched_group *first = NULL, *last = NULL;
4638         cpumask_t covered = CPU_MASK_NONE;
4639         int i;
4640
4641         for_each_cpu_mask(i, span) {
4642                 int group = group_fn(i);
4643                 struct sched_group *sg = &groups[group];
4644                 int j;
4645
4646                 if (cpu_isset(i, covered))
4647                         continue;
4648
4649                 sg->cpumask = CPU_MASK_NONE;
4650                 sg->cpu_power = 0;
4651
4652                 for_each_cpu_mask(j, span) {
4653                         if (group_fn(j) != group)
4654                                 continue;
4655
4656                         cpu_set(j, covered);
4657                         cpu_set(j, sg->cpumask);
4658                 }
4659                 if (!first)
4660                         first = sg;
4661                 if (last)
4662                         last->next = sg;
4663                 last = sg;
4664         }
4665         last->next = first;
4666 }
4667
4668
4669 #ifdef ARCH_HAS_SCHED_DOMAIN
4670 extern void __devinit arch_init_sched_domains(void);
4671 extern void __devinit arch_destroy_sched_domains(void);
4672 #else
4673 #ifdef CONFIG_SCHED_SMT
4674 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
4675 static struct sched_group sched_group_cpus[NR_CPUS];
4676 static int __devinit cpu_to_cpu_group(int cpu)
4677 {
4678         return cpu;
4679 }
4680 #endif
4681
4682 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
4683 static struct sched_group sched_group_phys[NR_CPUS];
4684 static int __devinit cpu_to_phys_group(int cpu)
4685 {
4686 #ifdef CONFIG_SCHED_SMT
4687         return first_cpu(cpu_sibling_map[cpu]);
4688 #else
4689         return cpu;
4690 #endif
4691 }
4692
4693 #ifdef CONFIG_NUMA
4694
4695 static DEFINE_PER_CPU(struct sched_domain, node_domains);
4696 static struct sched_group sched_group_nodes[MAX_NUMNODES];
4697 static int __devinit cpu_to_node_group(int cpu)
4698 {
4699         return cpu_to_node(cpu);
4700 }
4701 #endif
4702
4703 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
4704 /*
4705  * The domains setup code relies on siblings not spanning
4706  * multiple nodes. Make sure the architecture has a proper
4707  * siblings map:
4708  */
4709 static void check_sibling_maps(void)
4710 {
4711         int i, j;
4712
4713         for_each_online_cpu(i) {
4714                 for_each_cpu_mask(j, cpu_sibling_map[i]) {
4715                         if (cpu_to_node(i) != cpu_to_node(j)) {
4716                                 printk(KERN_INFO "warning: CPU %d siblings map "
4717                                         "to different node - isolating "
4718                                         "them.\n", i);
4719                                 cpu_sibling_map[i] = cpumask_of_cpu(i);
4720                                 break;
4721                         }
4722                 }
4723         }
4724 }
4725 #endif
4726
4727 /*
4728  * Set up scheduler domains and groups.  Callers must hold the hotplug lock.
4729  */
4730 static void __devinit arch_init_sched_domains(void)
4731 {
4732         int i;
4733         cpumask_t cpu_default_map;
4734
4735 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
4736         check_sibling_maps();
4737 #endif
4738         /*
4739          * Setup mask for cpus without special case scheduling requirements.
4740          * For now this just excludes isolated cpus, but could be used to
4741          * exclude other special cases in the future.
4742          */
4743         cpus_complement(cpu_default_map, cpu_isolated_map);
4744         cpus_and(cpu_default_map, cpu_default_map, cpu_online_map);
4745
4746         /*
4747          * Set up domains. Isolated domains just stay on the dummy domain.
4748          */
4749         for_each_cpu_mask(i, cpu_default_map) {
4750                 int group;
4751                 struct sched_domain *sd = NULL, *p;
4752                 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
4753
4754                 cpus_and(nodemask, nodemask, cpu_default_map);
4755
4756 #ifdef CONFIG_NUMA
4757                 sd = &per_cpu(node_domains, i);
4758                 group = cpu_to_node_group(i);
4759                 *sd = SD_NODE_INIT;
4760                 sd->span = cpu_default_map;
4761                 sd->groups = &sched_group_nodes[group];
4762 #endif
4763
4764                 p = sd;
4765                 sd = &per_cpu(phys_domains, i);
4766                 group = cpu_to_phys_group(i);
4767                 *sd = SD_CPU_INIT;
4768                 sd->span = nodemask;
4769                 sd->parent = p;
4770                 sd->groups = &sched_group_phys[group];
4771
4772 #ifdef CONFIG_SCHED_SMT
4773                 p = sd;
4774                 sd = &per_cpu(cpu_domains, i);
4775                 group = cpu_to_cpu_group(i);
4776                 *sd = SD_SIBLING_INIT;
4777                 sd->span = cpu_sibling_map[i];
4778                 cpus_and(sd->span, sd->span, cpu_default_map);
4779                 sd->parent = p;
4780                 sd->groups = &sched_group_cpus[group];
4781 #endif
4782         }
4783
4784 #ifdef CONFIG_SCHED_SMT
4785         /* Set up CPU (sibling) groups */
4786         for_each_online_cpu(i) {
4787                 cpumask_t this_sibling_map = cpu_sibling_map[i];
4788                 cpus_and(this_sibling_map, this_sibling_map, cpu_default_map);
4789                 if (i != first_cpu(this_sibling_map))
4790                         continue;
4791
4792                 init_sched_build_groups(sched_group_cpus, this_sibling_map,
4793                                                 &cpu_to_cpu_group);
4794         }
4795 #endif
4796
4797         /* Set up physical groups */
4798         for (i = 0; i < MAX_NUMNODES; i++) {
4799                 cpumask_t nodemask = node_to_cpumask(i);
4800
4801                 cpus_and(nodemask, nodemask, cpu_default_map);
4802                 if (cpus_empty(nodemask))
4803                         continue;
4804
4805                 init_sched_build_groups(sched_group_phys, nodemask,
4806                                                 &cpu_to_phys_group);
4807         }
4808
4809 #ifdef CONFIG_NUMA
4810         /* Set up node groups */
4811         init_sched_build_groups(sched_group_nodes, cpu_default_map,
4812                                         &cpu_to_node_group);
4813 #endif
4814
4815         /* Calculate CPU power for physical packages and nodes */
4816         for_each_cpu_mask(i, cpu_default_map) {
4817                 int power;
4818                 struct sched_domain *sd;
4819 #ifdef CONFIG_SCHED_SMT
4820                 sd = &per_cpu(cpu_domains, i);
4821                 power = SCHED_LOAD_SCALE;
4822                 sd->groups->cpu_power = power;
4823 #endif
4824
4825                 sd = &per_cpu(phys_domains, i);
4826                 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
4827                                 (cpus_weight(sd->groups->cpumask)-1) / 10;
4828                 sd->groups->cpu_power = power;
4829
4830 #ifdef CONFIG_NUMA
4831                 if (i == first_cpu(sd->groups->cpumask)) {
4832                         /* Only add "power" once for each physical package. */
4833                         sd = &per_cpu(node_domains, i);
4834                         sd->groups->cpu_power += power;
4835                 }
4836 #endif
4837         }
4838
4839         /* Attach the domains */
4840         for_each_online_cpu(i) {
4841                 struct sched_domain *sd;
4842 #ifdef CONFIG_SCHED_SMT
4843                 sd = &per_cpu(cpu_domains, i);
4844 #else
4845                 sd = &per_cpu(phys_domains, i);
4846 #endif
4847                 cpu_attach_domain(sd, i);
4848         }
4849 }
4850
4851 #ifdef CONFIG_HOTPLUG_CPU
4852 static void __devinit arch_destroy_sched_domains(void)
4853 {
4854         /* Do nothing: everything is statically allocated. */
4855 }
4856 #endif
4857
4858 #endif /* ARCH_HAS_SCHED_DOMAIN */
4859
4860 /*
4861  * Initial dummy domain for early boot and for hotplug cpu. Being static,
4862  * it is initialized to zero, so all balancing flags are cleared which is
4863  * what we want.
4864  */
4865 static struct sched_domain sched_domain_dummy;
4866
4867 #ifdef CONFIG_HOTPLUG_CPU
4868 /*
4869  * Force a reinitialization of the sched domains hierarchy.  The domains
4870  * and groups cannot be updated in place without racing with the balancing
4871  * code, so we temporarily attach all running cpus to a "dummy" domain
4872  * which will prevent rebalancing while the sched domains are recalculated.
4873  */
4874 static int update_sched_domains(struct notifier_block *nfb,
4875                                 unsigned long action, void *hcpu)
4876 {
4877         int i;
4878
4879         switch (action) {
4880         case CPU_UP_PREPARE:
4881         case CPU_DOWN_PREPARE:
4882                 for_each_online_cpu(i)
4883                         cpu_attach_domain(&sched_domain_dummy, i);
4884                 arch_destroy_sched_domains();
4885                 return NOTIFY_OK;
4886
4887         case CPU_UP_CANCELED:
4888         case CPU_DOWN_FAILED:
4889         case CPU_ONLINE:
4890         case CPU_DEAD:
4891                 /*
4892                  * Fall through and re-initialise the domains.
4893                  */
4894                 break;
4895         default:
4896                 return NOTIFY_DONE;
4897         }
4898
4899         /* The hotplug lock is already held by cpu_up/cpu_down */
4900         arch_init_sched_domains();
4901
4902         return NOTIFY_OK;
4903 }
4904 #endif
4905
4906 void __init sched_init_smp(void)
4907 {
4908         lock_cpu_hotplug();
4909         arch_init_sched_domains();
4910         unlock_cpu_hotplug();
4911         /* XXX: Theoretical race here - CPU may be hotplugged now */
4912         hotcpu_notifier(update_sched_domains, 0);
4913 }
4914 #else
4915 void __init sched_init_smp(void)
4916 {
4917 }
4918 #endif /* CONFIG_SMP */
4919
4920 int in_sched_functions(unsigned long addr)
4921 {
4922         /* Linker adds these: start and end of __sched functions */
4923         extern char __sched_text_start[], __sched_text_end[];
4924         return in_lock_functions(addr) ||
4925                 (addr >= (unsigned long)__sched_text_start
4926                 && addr < (unsigned long)__sched_text_end);
4927 }
4928
4929 void __init sched_init(void)
4930 {
4931         runqueue_t *rq;
4932         int i, j, k;
4933
4934         for (i = 0; i < NR_CPUS; i++) {
4935                 prio_array_t *array;
4936
4937                 rq = cpu_rq(i);
4938                 spin_lock_init(&rq->lock);
4939                 rq->nr_running = 0;
4940                 rq->active = rq->arrays;
4941                 rq->expired = rq->arrays + 1;
4942                 rq->best_expired_prio = MAX_PRIO;
4943
4944 #ifdef CONFIG_SMP
4945                 rq->sd = &sched_domain_dummy;
4946                 for (j = 1; j < 3; j++)
4947                         rq->cpu_load[j] = 0;
4948                 rq->active_balance = 0;
4949                 rq->push_cpu = 0;
4950                 rq->migration_thread = NULL;
4951                 INIT_LIST_HEAD(&rq->migration_queue);
4952 #endif
4953                 atomic_set(&rq->nr_iowait, 0);
4954
4955                 for (j = 0; j < 2; j++) {
4956                         array = rq->arrays + j;
4957                         for (k = 0; k < MAX_PRIO; k++) {
4958                                 INIT_LIST_HEAD(array->queue + k);
4959                                 __clear_bit(k, array->bitmap);
4960                         }
4961                         // delimiter for bitsearch
4962                         __set_bit(MAX_PRIO, array->bitmap);
4963                 }
4964         }
4965
4966         /*
4967          * The boot idle thread does lazy MMU switching as well:
4968          */
4969         atomic_inc(&init_mm.mm_count);
4970         enter_lazy_tlb(&init_mm, current);
4971
4972         /*
4973          * Make us the idle thread. Technically, schedule() should not be
4974          * called from this thread, however somewhere below it might be,
4975          * but because we are the idle thread, we just pick up running again
4976          * when this runqueue becomes "idle".
4977          */
4978         init_idle(current, smp_processor_id());
4979 }
4980
4981 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4982 void __might_sleep(char *file, int line)
4983 {
4984 #if defined(in_atomic)
4985         static unsigned long prev_jiffy;        /* ratelimiting */
4986
4987         if ((in_atomic() || irqs_disabled()) &&
4988             system_state == SYSTEM_RUNNING && !oops_in_progress) {
4989                 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
4990                         return;
4991                 prev_jiffy = jiffies;
4992                 printk(KERN_ERR "Debug: sleeping function called from invalid"
4993                                 " context at %s:%d\n", file, line);
4994                 printk("in_atomic():%d, irqs_disabled():%d\n",
4995                         in_atomic(), irqs_disabled());
4996                 dump_stack();
4997         }
4998 #endif
4999 }
5000 EXPORT_SYMBOL(__might_sleep);
5001 #endif
5002
5003 #ifdef CONFIG_MAGIC_SYSRQ
5004 void normalize_rt_tasks(void)
5005 {
5006         struct task_struct *p;
5007         prio_array_t *array;
5008         unsigned long flags;
5009         runqueue_t *rq;
5010
5011         read_lock_irq(&tasklist_lock);
5012         for_each_process (p) {
5013                 if (!rt_task(p))
5014                         continue;
5015
5016                 rq = task_rq_lock(p, &flags);
5017
5018                 array = p->array;
5019                 if (array)
5020                         deactivate_task(p, task_rq(p));
5021                 __setscheduler(p, SCHED_NORMAL, 0);
5022                 if (array) {
5023                         __activate_task(p, task_rq(p));
5024                         resched_task(rq->curr);
5025                 }
5026
5027                 task_rq_unlock(rq, &flags);
5028         }
5029         read_unlock_irq(&tasklist_lock);
5030 }
5031
5032 #endif /* CONFIG_MAGIC_SYSRQ */