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