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