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