sched: high-res preemption tick
[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  *  2007-04-15  Work begun on replacing all interactivity tuning with a
20  *              fair scheduling design by Con Kolivas.
21  *  2007-05-05  Load balancing (smp-nice) and other improvements
22  *              by Peter Williams
23  *  2007-05-06  Interactivity improvements to CFS by Mike Galbraith
24  *  2007-07-01  Group scheduling enhancements by Srivatsa Vaddagiri
25  *  2007-11-29  RT balancing improvements by Steven Rostedt, Gregory Haskins,
26  *              Thomas Gleixner, Mike Kravetz
27  */
28
29 #include <linux/mm.h>
30 #include <linux/module.h>
31 #include <linux/nmi.h>
32 #include <linux/init.h>
33 #include <linux/uaccess.h>
34 #include <linux/highmem.h>
35 #include <linux/smp_lock.h>
36 #include <asm/mmu_context.h>
37 #include <linux/interrupt.h>
38 #include <linux/capability.h>
39 #include <linux/completion.h>
40 #include <linux/kernel_stat.h>
41 #include <linux/debug_locks.h>
42 #include <linux/security.h>
43 #include <linux/notifier.h>
44 #include <linux/profile.h>
45 #include <linux/freezer.h>
46 #include <linux/vmalloc.h>
47 #include <linux/blkdev.h>
48 #include <linux/delay.h>
49 #include <linux/pid_namespace.h>
50 #include <linux/smp.h>
51 #include <linux/threads.h>
52 #include <linux/timer.h>
53 #include <linux/rcupdate.h>
54 #include <linux/cpu.h>
55 #include <linux/cpuset.h>
56 #include <linux/percpu.h>
57 #include <linux/kthread.h>
58 #include <linux/seq_file.h>
59 #include <linux/sysctl.h>
60 #include <linux/syscalls.h>
61 #include <linux/times.h>
62 #include <linux/tsacct_kern.h>
63 #include <linux/kprobes.h>
64 #include <linux/delayacct.h>
65 #include <linux/reciprocal_div.h>
66 #include <linux/unistd.h>
67 #include <linux/pagemap.h>
68 #include <linux/hrtimer.h>
69
70 #include <asm/tlb.h>
71 #include <asm/irq_regs.h>
72
73 /*
74  * Scheduler clock - returns current time in nanosec units.
75  * This is default implementation.
76  * Architectures and sub-architectures can override this.
77  */
78 unsigned long long __attribute__((weak)) sched_clock(void)
79 {
80         return (unsigned long long)jiffies * (NSEC_PER_SEC / HZ);
81 }
82
83 /*
84  * Convert user-nice values [ -20 ... 0 ... 19 ]
85  * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
86  * and back.
87  */
88 #define NICE_TO_PRIO(nice)      (MAX_RT_PRIO + (nice) + 20)
89 #define PRIO_TO_NICE(prio)      ((prio) - MAX_RT_PRIO - 20)
90 #define TASK_NICE(p)            PRIO_TO_NICE((p)->static_prio)
91
92 /*
93  * 'User priority' is the nice value converted to something we
94  * can work with better when scaling various scheduler parameters,
95  * it's a [ 0 ... 39 ] range.
96  */
97 #define USER_PRIO(p)            ((p)-MAX_RT_PRIO)
98 #define TASK_USER_PRIO(p)       USER_PRIO((p)->static_prio)
99 #define MAX_USER_PRIO           (USER_PRIO(MAX_PRIO))
100
101 /*
102  * Helpers for converting nanosecond timing to jiffy resolution
103  */
104 #define NS_TO_JIFFIES(TIME)     ((unsigned long)(TIME) / (NSEC_PER_SEC / HZ))
105
106 #define NICE_0_LOAD             SCHED_LOAD_SCALE
107 #define NICE_0_SHIFT            SCHED_LOAD_SHIFT
108
109 /*
110  * These are the 'tuning knobs' of the scheduler:
111  *
112  * default timeslice is 100 msecs (used only for SCHED_RR tasks).
113  * Timeslices get refilled after they expire.
114  */
115 #define DEF_TIMESLICE           (100 * HZ / 1000)
116
117 #ifdef CONFIG_SMP
118 /*
119  * Divide a load by a sched group cpu_power : (load / sg->__cpu_power)
120  * Since cpu_power is a 'constant', we can use a reciprocal divide.
121  */
122 static inline u32 sg_div_cpu_power(const struct sched_group *sg, u32 load)
123 {
124         return reciprocal_divide(load, sg->reciprocal_cpu_power);
125 }
126
127 /*
128  * Each time a sched group cpu_power is changed,
129  * we must compute its reciprocal value
130  */
131 static inline void sg_inc_cpu_power(struct sched_group *sg, u32 val)
132 {
133         sg->__cpu_power += val;
134         sg->reciprocal_cpu_power = reciprocal_value(sg->__cpu_power);
135 }
136 #endif
137
138 static inline int rt_policy(int policy)
139 {
140         if (unlikely(policy == SCHED_FIFO) || unlikely(policy == SCHED_RR))
141                 return 1;
142         return 0;
143 }
144
145 static inline int task_has_rt_policy(struct task_struct *p)
146 {
147         return rt_policy(p->policy);
148 }
149
150 /*
151  * This is the priority-queue data structure of the RT scheduling class:
152  */
153 struct rt_prio_array {
154         DECLARE_BITMAP(bitmap, MAX_RT_PRIO+1); /* include 1 bit for delimiter */
155         struct list_head queue[MAX_RT_PRIO];
156 };
157
158 #ifdef CONFIG_FAIR_GROUP_SCHED
159
160 #include <linux/cgroup.h>
161
162 struct cfs_rq;
163
164 /* task group related information */
165 struct task_group {
166 #ifdef CONFIG_FAIR_CGROUP_SCHED
167         struct cgroup_subsys_state css;
168 #endif
169         /* schedulable entities of this group on each cpu */
170         struct sched_entity **se;
171         /* runqueue "owned" by this group on each cpu */
172         struct cfs_rq **cfs_rq;
173
174         /*
175          * shares assigned to a task group governs how much of cpu bandwidth
176          * is allocated to the group. The more shares a group has, the more is
177          * the cpu bandwidth allocated to it.
178          *
179          * For ex, lets say that there are three task groups, A, B and C which
180          * have been assigned shares 1000, 2000 and 3000 respectively. Then,
181          * cpu bandwidth allocated by the scheduler to task groups A, B and C
182          * should be:
183          *
184          *      Bw(A) = 1000/(1000+2000+3000) * 100 = 16.66%
185          *      Bw(B) = 2000/(1000+2000+3000) * 100 = 33.33%
186          *      Bw(C) = 3000/(1000+2000+3000) * 100 = 50%
187          *
188          * The weight assigned to a task group's schedulable entities on every
189          * cpu (task_group.se[a_cpu]->load.weight) is derived from the task
190          * group's shares. For ex: lets say that task group A has been
191          * assigned shares of 1000 and there are two CPUs in a system. Then,
192          *
193          *  tg_A->se[0]->load.weight = tg_A->se[1]->load.weight = 1000;
194          *
195          * Note: It's not necessary that each of a task's group schedulable
196          *       entity have the same weight on all CPUs. If the group
197          *       has 2 of its tasks on CPU0 and 1 task on CPU1, then a
198          *       better distribution of weight could be:
199          *
200          *      tg_A->se[0]->load.weight = 2/3 * 2000 = 1333
201          *      tg_A->se[1]->load.weight = 1/2 * 2000 =  667
202          *
203          * rebalance_shares() is responsible for distributing the shares of a
204          * task groups like this among the group's schedulable entities across
205          * cpus.
206          *
207          */
208         unsigned long shares;
209
210         struct rcu_head rcu;
211 };
212
213 /* Default task group's sched entity on each cpu */
214 static DEFINE_PER_CPU(struct sched_entity, init_sched_entity);
215 /* Default task group's cfs_rq on each cpu */
216 static DEFINE_PER_CPU(struct cfs_rq, init_cfs_rq) ____cacheline_aligned_in_smp;
217
218 static struct sched_entity *init_sched_entity_p[NR_CPUS];
219 static struct cfs_rq *init_cfs_rq_p[NR_CPUS];
220
221 /* task_group_mutex serializes add/remove of task groups and also changes to
222  * a task group's cpu shares.
223  */
224 static DEFINE_MUTEX(task_group_mutex);
225
226 /* doms_cur_mutex serializes access to doms_cur[] array */
227 static DEFINE_MUTEX(doms_cur_mutex);
228
229 #ifdef CONFIG_SMP
230 /* kernel thread that runs rebalance_shares() periodically */
231 static struct task_struct *lb_monitor_task;
232 static int load_balance_monitor(void *unused);
233 #endif
234
235 static void set_se_shares(struct sched_entity *se, unsigned long shares);
236
237 /* Default task group.
238  *      Every task in system belong to this group at bootup.
239  */
240 struct task_group init_task_group = {
241         .se     = init_sched_entity_p,
242         .cfs_rq = init_cfs_rq_p,
243 };
244
245 #ifdef CONFIG_FAIR_USER_SCHED
246 # define INIT_TASK_GROUP_LOAD   (2*NICE_0_LOAD)
247 #else
248 # define INIT_TASK_GROUP_LOAD   NICE_0_LOAD
249 #endif
250
251 #define MIN_GROUP_SHARES        2
252
253 static int init_task_group_load = INIT_TASK_GROUP_LOAD;
254
255 /* return group to which a task belongs */
256 static inline struct task_group *task_group(struct task_struct *p)
257 {
258         struct task_group *tg;
259
260 #ifdef CONFIG_FAIR_USER_SCHED
261         tg = p->user->tg;
262 #elif defined(CONFIG_FAIR_CGROUP_SCHED)
263         tg = container_of(task_subsys_state(p, cpu_cgroup_subsys_id),
264                                 struct task_group, css);
265 #else
266         tg = &init_task_group;
267 #endif
268         return tg;
269 }
270
271 /* Change a task's cfs_rq and parent entity if it moves across CPUs/groups */
272 static inline void set_task_cfs_rq(struct task_struct *p, unsigned int cpu)
273 {
274         p->se.cfs_rq = task_group(p)->cfs_rq[cpu];
275         p->se.parent = task_group(p)->se[cpu];
276 }
277
278 static inline void lock_task_group_list(void)
279 {
280         mutex_lock(&task_group_mutex);
281 }
282
283 static inline void unlock_task_group_list(void)
284 {
285         mutex_unlock(&task_group_mutex);
286 }
287
288 static inline void lock_doms_cur(void)
289 {
290         mutex_lock(&doms_cur_mutex);
291 }
292
293 static inline void unlock_doms_cur(void)
294 {
295         mutex_unlock(&doms_cur_mutex);
296 }
297
298 #else
299
300 static inline void set_task_cfs_rq(struct task_struct *p, unsigned int cpu) { }
301 static inline void lock_task_group_list(void) { }
302 static inline void unlock_task_group_list(void) { }
303 static inline void lock_doms_cur(void) { }
304 static inline void unlock_doms_cur(void) { }
305
306 #endif  /* CONFIG_FAIR_GROUP_SCHED */
307
308 /* CFS-related fields in a runqueue */
309 struct cfs_rq {
310         struct load_weight load;
311         unsigned long nr_running;
312
313         u64 exec_clock;
314         u64 min_vruntime;
315
316         struct rb_root tasks_timeline;
317         struct rb_node *rb_leftmost;
318         struct rb_node *rb_load_balance_curr;
319         /* 'curr' points to currently running entity on this cfs_rq.
320          * It is set to NULL otherwise (i.e when none are currently running).
321          */
322         struct sched_entity *curr;
323
324         unsigned long nr_spread_over;
325
326 #ifdef CONFIG_FAIR_GROUP_SCHED
327         struct rq *rq;  /* cpu runqueue to which this cfs_rq is attached */
328
329         /*
330          * leaf cfs_rqs are those that hold tasks (lowest schedulable entity in
331          * a hierarchy). Non-leaf lrqs hold other higher schedulable entities
332          * (like users, containers etc.)
333          *
334          * leaf_cfs_rq_list ties together list of leaf cfs_rq's in a cpu. This
335          * list is used during load balance.
336          */
337         struct list_head leaf_cfs_rq_list;
338         struct task_group *tg;  /* group that "owns" this runqueue */
339 #endif
340 };
341
342 /* Real-Time classes' related field in a runqueue: */
343 struct rt_rq {
344         struct rt_prio_array active;
345         int rt_load_balance_idx;
346         struct list_head *rt_load_balance_head, *rt_load_balance_curr;
347         unsigned long rt_nr_running;
348         unsigned long rt_nr_migratory;
349         /* highest queued rt task prio */
350         int highest_prio;
351         int overloaded;
352 };
353
354 #ifdef CONFIG_SMP
355
356 /*
357  * We add the notion of a root-domain which will be used to define per-domain
358  * variables. Each exclusive cpuset essentially defines an island domain by
359  * fully partitioning the member cpus from any other cpuset. Whenever a new
360  * exclusive cpuset is created, we also create and attach a new root-domain
361  * object.
362  *
363  */
364 struct root_domain {
365         atomic_t refcount;
366         cpumask_t span;
367         cpumask_t online;
368
369         /*
370          * The "RT overload" flag: it gets set if a CPU has more than
371          * one runnable RT task.
372          */
373         cpumask_t rto_mask;
374         atomic_t rto_count;
375 };
376
377 /*
378  * By default the system creates a single root-domain with all cpus as
379  * members (mimicking the global state we have today).
380  */
381 static struct root_domain def_root_domain;
382
383 #endif
384
385 /*
386  * This is the main, per-CPU runqueue data structure.
387  *
388  * Locking rule: those places that want to lock multiple runqueues
389  * (such as the load balancing or the thread migration code), lock
390  * acquire operations must be ordered by ascending &runqueue.
391  */
392 struct rq {
393         /* runqueue lock: */
394         spinlock_t lock;
395
396         /*
397          * nr_running and cpu_load should be in the same cacheline because
398          * remote CPUs use both these fields when doing load calculation.
399          */
400         unsigned long nr_running;
401         #define CPU_LOAD_IDX_MAX 5
402         unsigned long cpu_load[CPU_LOAD_IDX_MAX];
403         unsigned char idle_at_tick;
404 #ifdef CONFIG_NO_HZ
405         unsigned char in_nohz_recently;
406 #endif
407         /* capture load from *all* tasks on this cpu: */
408         struct load_weight load;
409         unsigned long nr_load_updates;
410         u64 nr_switches;
411
412         struct cfs_rq cfs;
413 #ifdef CONFIG_FAIR_GROUP_SCHED
414         /* list of leaf cfs_rq on this cpu: */
415         struct list_head leaf_cfs_rq_list;
416 #endif
417         struct rt_rq rt;
418
419         /*
420          * This is part of a global counter where only the total sum
421          * over all CPUs matters. A task can increase this counter on
422          * one CPU and if it got migrated afterwards it may decrease
423          * it on another CPU. Always updated under the runqueue lock:
424          */
425         unsigned long nr_uninterruptible;
426
427         struct task_struct *curr, *idle;
428         unsigned long next_balance;
429         struct mm_struct *prev_mm;
430
431         u64 clock, prev_clock_raw;
432         s64 clock_max_delta;
433
434         unsigned int clock_warps, clock_overflows;
435         u64 idle_clock;
436         unsigned int clock_deep_idle_events;
437         u64 tick_timestamp;
438
439         atomic_t nr_iowait;
440
441 #ifdef CONFIG_SMP
442         struct root_domain *rd;
443         struct sched_domain *sd;
444
445         /* For active balancing */
446         int active_balance;
447         int push_cpu;
448         /* cpu of this runqueue: */
449         int cpu;
450
451         struct task_struct *migration_thread;
452         struct list_head migration_queue;
453 #endif
454
455 #ifdef CONFIG_SCHED_HRTICK
456         unsigned long hrtick_flags;
457         ktime_t hrtick_expire;
458         struct hrtimer hrtick_timer;
459 #endif
460
461 #ifdef CONFIG_SCHEDSTATS
462         /* latency stats */
463         struct sched_info rq_sched_info;
464
465         /* sys_sched_yield() stats */
466         unsigned int yld_exp_empty;
467         unsigned int yld_act_empty;
468         unsigned int yld_both_empty;
469         unsigned int yld_count;
470
471         /* schedule() stats */
472         unsigned int sched_switch;
473         unsigned int sched_count;
474         unsigned int sched_goidle;
475
476         /* try_to_wake_up() stats */
477         unsigned int ttwu_count;
478         unsigned int ttwu_local;
479
480         /* BKL stats */
481         unsigned int bkl_count;
482 #endif
483         struct lock_class_key rq_lock_key;
484 };
485
486 static DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
487
488 static inline void check_preempt_curr(struct rq *rq, struct task_struct *p)
489 {
490         rq->curr->sched_class->check_preempt_curr(rq, p);
491 }
492
493 static inline int cpu_of(struct rq *rq)
494 {
495 #ifdef CONFIG_SMP
496         return rq->cpu;
497 #else
498         return 0;
499 #endif
500 }
501
502 /*
503  * Update the per-runqueue clock, as finegrained as the platform can give
504  * us, but without assuming monotonicity, etc.:
505  */
506 static void __update_rq_clock(struct rq *rq)
507 {
508         u64 prev_raw = rq->prev_clock_raw;
509         u64 now = sched_clock();
510         s64 delta = now - prev_raw;
511         u64 clock = rq->clock;
512
513 #ifdef CONFIG_SCHED_DEBUG
514         WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
515 #endif
516         /*
517          * Protect against sched_clock() occasionally going backwards:
518          */
519         if (unlikely(delta < 0)) {
520                 clock++;
521                 rq->clock_warps++;
522         } else {
523                 /*
524                  * Catch too large forward jumps too:
525                  */
526                 if (unlikely(clock + delta > rq->tick_timestamp + TICK_NSEC)) {
527                         if (clock < rq->tick_timestamp + TICK_NSEC)
528                                 clock = rq->tick_timestamp + TICK_NSEC;
529                         else
530                                 clock++;
531                         rq->clock_overflows++;
532                 } else {
533                         if (unlikely(delta > rq->clock_max_delta))
534                                 rq->clock_max_delta = delta;
535                         clock += delta;
536                 }
537         }
538
539         rq->prev_clock_raw = now;
540         rq->clock = clock;
541 }
542
543 static void update_rq_clock(struct rq *rq)
544 {
545         if (likely(smp_processor_id() == cpu_of(rq)))
546                 __update_rq_clock(rq);
547 }
548
549 /*
550  * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
551  * See detach_destroy_domains: synchronize_sched for details.
552  *
553  * The domain tree of any CPU may only be accessed from within
554  * preempt-disabled sections.
555  */
556 #define for_each_domain(cpu, __sd) \
557         for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
558
559 #define cpu_rq(cpu)             (&per_cpu(runqueues, (cpu)))
560 #define this_rq()               (&__get_cpu_var(runqueues))
561 #define task_rq(p)              cpu_rq(task_cpu(p))
562 #define cpu_curr(cpu)           (cpu_rq(cpu)->curr)
563
564 /*
565  * Tunables that become constants when CONFIG_SCHED_DEBUG is off:
566  */
567 #ifdef CONFIG_SCHED_DEBUG
568 # define const_debug __read_mostly
569 #else
570 # define const_debug static const
571 #endif
572
573 /*
574  * Debugging: various feature bits
575  */
576 enum {
577         SCHED_FEAT_NEW_FAIR_SLEEPERS    = 1,
578         SCHED_FEAT_WAKEUP_PREEMPT       = 2,
579         SCHED_FEAT_START_DEBIT          = 4,
580         SCHED_FEAT_TREE_AVG             = 8,
581         SCHED_FEAT_APPROX_AVG           = 16,
582         SCHED_FEAT_HRTICK               = 32,
583         SCHED_FEAT_DOUBLE_TICK          = 64,
584 };
585
586 const_debug unsigned int sysctl_sched_features =
587                 SCHED_FEAT_NEW_FAIR_SLEEPERS    * 1 |
588                 SCHED_FEAT_WAKEUP_PREEMPT       * 1 |
589                 SCHED_FEAT_START_DEBIT          * 1 |
590                 SCHED_FEAT_TREE_AVG             * 0 |
591                 SCHED_FEAT_APPROX_AVG           * 0 |
592                 SCHED_FEAT_HRTICK               * 1 |
593                 SCHED_FEAT_DOUBLE_TICK          * 0;
594
595 #define sched_feat(x) (sysctl_sched_features & SCHED_FEAT_##x)
596
597 /*
598  * Number of tasks to iterate in a single balance run.
599  * Limited because this is done with IRQs disabled.
600  */
601 const_debug unsigned int sysctl_sched_nr_migrate = 32;
602
603 /*
604  * For kernel-internal use: high-speed (but slightly incorrect) per-cpu
605  * clock constructed from sched_clock():
606  */
607 unsigned long long cpu_clock(int cpu)
608 {
609         unsigned long long now;
610         unsigned long flags;
611         struct rq *rq;
612
613         local_irq_save(flags);
614         rq = cpu_rq(cpu);
615         /*
616          * Only call sched_clock() if the scheduler has already been
617          * initialized (some code might call cpu_clock() very early):
618          */
619         if (rq->idle)
620                 update_rq_clock(rq);
621         now = rq->clock;
622         local_irq_restore(flags);
623
624         return now;
625 }
626 EXPORT_SYMBOL_GPL(cpu_clock);
627
628 #ifndef prepare_arch_switch
629 # define prepare_arch_switch(next)      do { } while (0)
630 #endif
631 #ifndef finish_arch_switch
632 # define finish_arch_switch(prev)       do { } while (0)
633 #endif
634
635 static inline int task_current(struct rq *rq, struct task_struct *p)
636 {
637         return rq->curr == p;
638 }
639
640 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
641 static inline int task_running(struct rq *rq, struct task_struct *p)
642 {
643         return task_current(rq, p);
644 }
645
646 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
647 {
648 }
649
650 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
651 {
652 #ifdef CONFIG_DEBUG_SPINLOCK
653         /* this is a valid case when another task releases the spinlock */
654         rq->lock.owner = current;
655 #endif
656         /*
657          * If we are tracking spinlock dependencies then we have to
658          * fix up the runqueue lock - which gets 'carried over' from
659          * prev into current:
660          */
661         spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
662
663         spin_unlock_irq(&rq->lock);
664 }
665
666 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
667 static inline int task_running(struct rq *rq, struct task_struct *p)
668 {
669 #ifdef CONFIG_SMP
670         return p->oncpu;
671 #else
672         return task_current(rq, p);
673 #endif
674 }
675
676 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
677 {
678 #ifdef CONFIG_SMP
679         /*
680          * We can optimise this out completely for !SMP, because the
681          * SMP rebalancing from interrupt is the only thing that cares
682          * here.
683          */
684         next->oncpu = 1;
685 #endif
686 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
687         spin_unlock_irq(&rq->lock);
688 #else
689         spin_unlock(&rq->lock);
690 #endif
691 }
692
693 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
694 {
695 #ifdef CONFIG_SMP
696         /*
697          * After ->oncpu is cleared, the task can be moved to a different CPU.
698          * We must ensure this doesn't happen until the switch is completely
699          * finished.
700          */
701         smp_wmb();
702         prev->oncpu = 0;
703 #endif
704 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
705         local_irq_enable();
706 #endif
707 }
708 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
709
710 /*
711  * __task_rq_lock - lock the runqueue a given task resides on.
712  * Must be called interrupts disabled.
713  */
714 static inline struct rq *__task_rq_lock(struct task_struct *p)
715         __acquires(rq->lock)
716 {
717         for (;;) {
718                 struct rq *rq = task_rq(p);
719                 spin_lock(&rq->lock);
720                 if (likely(rq == task_rq(p)))
721                         return rq;
722                 spin_unlock(&rq->lock);
723         }
724 }
725
726 /*
727  * task_rq_lock - lock the runqueue a given task resides on and disable
728  * interrupts. Note the ordering: we can safely lookup the task_rq without
729  * explicitly disabling preemption.
730  */
731 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
732         __acquires(rq->lock)
733 {
734         struct rq *rq;
735
736         for (;;) {
737                 local_irq_save(*flags);
738                 rq = task_rq(p);
739                 spin_lock(&rq->lock);
740                 if (likely(rq == task_rq(p)))
741                         return rq;
742                 spin_unlock_irqrestore(&rq->lock, *flags);
743         }
744 }
745
746 static void __task_rq_unlock(struct rq *rq)
747         __releases(rq->lock)
748 {
749         spin_unlock(&rq->lock);
750 }
751
752 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
753         __releases(rq->lock)
754 {
755         spin_unlock_irqrestore(&rq->lock, *flags);
756 }
757
758 /*
759  * this_rq_lock - lock this runqueue and disable interrupts.
760  */
761 static struct rq *this_rq_lock(void)
762         __acquires(rq->lock)
763 {
764         struct rq *rq;
765
766         local_irq_disable();
767         rq = this_rq();
768         spin_lock(&rq->lock);
769
770         return rq;
771 }
772
773 /*
774  * We are going deep-idle (irqs are disabled):
775  */
776 void sched_clock_idle_sleep_event(void)
777 {
778         struct rq *rq = cpu_rq(smp_processor_id());
779
780         spin_lock(&rq->lock);
781         __update_rq_clock(rq);
782         spin_unlock(&rq->lock);
783         rq->clock_deep_idle_events++;
784 }
785 EXPORT_SYMBOL_GPL(sched_clock_idle_sleep_event);
786
787 /*
788  * We just idled delta nanoseconds (called with irqs disabled):
789  */
790 void sched_clock_idle_wakeup_event(u64 delta_ns)
791 {
792         struct rq *rq = cpu_rq(smp_processor_id());
793         u64 now = sched_clock();
794
795         touch_softlockup_watchdog();
796         rq->idle_clock += delta_ns;
797         /*
798          * Override the previous timestamp and ignore all
799          * sched_clock() deltas that occured while we idled,
800          * and use the PM-provided delta_ns to advance the
801          * rq clock:
802          */
803         spin_lock(&rq->lock);
804         rq->prev_clock_raw = now;
805         rq->clock += delta_ns;
806         spin_unlock(&rq->lock);
807 }
808 EXPORT_SYMBOL_GPL(sched_clock_idle_wakeup_event);
809
810 static void __resched_task(struct task_struct *p, int tif_bit);
811
812 static inline void resched_task(struct task_struct *p)
813 {
814         __resched_task(p, TIF_NEED_RESCHED);
815 }
816
817 #ifdef CONFIG_SCHED_HRTICK
818 /*
819  * Use HR-timers to deliver accurate preemption points.
820  *
821  * Its all a bit involved since we cannot program an hrt while holding the
822  * rq->lock. So what we do is store a state in in rq->hrtick_* and ask for a
823  * reschedule event.
824  *
825  * When we get rescheduled we reprogram the hrtick_timer outside of the
826  * rq->lock.
827  */
828 static inline void resched_hrt(struct task_struct *p)
829 {
830         __resched_task(p, TIF_HRTICK_RESCHED);
831 }
832
833 static inline void resched_rq(struct rq *rq)
834 {
835         unsigned long flags;
836
837         spin_lock_irqsave(&rq->lock, flags);
838         resched_task(rq->curr);
839         spin_unlock_irqrestore(&rq->lock, flags);
840 }
841
842 enum {
843         HRTICK_SET,             /* re-programm hrtick_timer */
844         HRTICK_RESET,           /* not a new slice */
845 };
846
847 /*
848  * Use hrtick when:
849  *  - enabled by features
850  *  - hrtimer is actually high res
851  */
852 static inline int hrtick_enabled(struct rq *rq)
853 {
854         if (!sched_feat(HRTICK))
855                 return 0;
856         return hrtimer_is_hres_active(&rq->hrtick_timer);
857 }
858
859 /*
860  * Called to set the hrtick timer state.
861  *
862  * called with rq->lock held and irqs disabled
863  */
864 static void hrtick_start(struct rq *rq, u64 delay, int reset)
865 {
866         assert_spin_locked(&rq->lock);
867
868         /*
869          * preempt at: now + delay
870          */
871         rq->hrtick_expire =
872                 ktime_add_ns(rq->hrtick_timer.base->get_time(), delay);
873         /*
874          * indicate we need to program the timer
875          */
876         __set_bit(HRTICK_SET, &rq->hrtick_flags);
877         if (reset)
878                 __set_bit(HRTICK_RESET, &rq->hrtick_flags);
879
880         /*
881          * New slices are called from the schedule path and don't need a
882          * forced reschedule.
883          */
884         if (reset)
885                 resched_hrt(rq->curr);
886 }
887
888 static void hrtick_clear(struct rq *rq)
889 {
890         if (hrtimer_active(&rq->hrtick_timer))
891                 hrtimer_cancel(&rq->hrtick_timer);
892 }
893
894 /*
895  * Update the timer from the possible pending state.
896  */
897 static void hrtick_set(struct rq *rq)
898 {
899         ktime_t time;
900         int set, reset;
901         unsigned long flags;
902
903         WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
904
905         spin_lock_irqsave(&rq->lock, flags);
906         set = __test_and_clear_bit(HRTICK_SET, &rq->hrtick_flags);
907         reset = __test_and_clear_bit(HRTICK_RESET, &rq->hrtick_flags);
908         time = rq->hrtick_expire;
909         clear_thread_flag(TIF_HRTICK_RESCHED);
910         spin_unlock_irqrestore(&rq->lock, flags);
911
912         if (set) {
913                 hrtimer_start(&rq->hrtick_timer, time, HRTIMER_MODE_ABS);
914                 if (reset && !hrtimer_active(&rq->hrtick_timer))
915                         resched_rq(rq);
916         } else
917                 hrtick_clear(rq);
918 }
919
920 /*
921  * High-resolution timer tick.
922  * Runs from hardirq context with interrupts disabled.
923  */
924 static enum hrtimer_restart hrtick(struct hrtimer *timer)
925 {
926         struct rq *rq = container_of(timer, struct rq, hrtick_timer);
927
928         WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
929
930         spin_lock(&rq->lock);
931         __update_rq_clock(rq);
932         rq->curr->sched_class->task_tick(rq, rq->curr, 1);
933         spin_unlock(&rq->lock);
934
935         return HRTIMER_NORESTART;
936 }
937
938 static inline void init_rq_hrtick(struct rq *rq)
939 {
940         rq->hrtick_flags = 0;
941         hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
942         rq->hrtick_timer.function = hrtick;
943         rq->hrtick_timer.cb_mode = HRTIMER_CB_IRQSAFE_NO_SOFTIRQ;
944 }
945
946 void hrtick_resched(void)
947 {
948         struct rq *rq;
949         unsigned long flags;
950
951         if (!test_thread_flag(TIF_HRTICK_RESCHED))
952                 return;
953
954         local_irq_save(flags);
955         rq = cpu_rq(smp_processor_id());
956         hrtick_set(rq);
957         local_irq_restore(flags);
958 }
959 #else
960 static inline void hrtick_clear(struct rq *rq)
961 {
962 }
963
964 static inline void hrtick_set(struct rq *rq)
965 {
966 }
967
968 static inline void init_rq_hrtick(struct rq *rq)
969 {
970 }
971
972 void hrtick_resched(void)
973 {
974 }
975 #endif
976
977 /*
978  * resched_task - mark a task 'to be rescheduled now'.
979  *
980  * On UP this means the setting of the need_resched flag, on SMP it
981  * might also involve a cross-CPU call to trigger the scheduler on
982  * the target CPU.
983  */
984 #ifdef CONFIG_SMP
985
986 #ifndef tsk_is_polling
987 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
988 #endif
989
990 static void __resched_task(struct task_struct *p, int tif_bit)
991 {
992         int cpu;
993
994         assert_spin_locked(&task_rq(p)->lock);
995
996         if (unlikely(test_tsk_thread_flag(p, tif_bit)))
997                 return;
998
999         set_tsk_thread_flag(p, tif_bit);
1000
1001         cpu = task_cpu(p);
1002         if (cpu == smp_processor_id())
1003                 return;
1004
1005         /* NEED_RESCHED must be visible before we test polling */
1006         smp_mb();
1007         if (!tsk_is_polling(p))
1008                 smp_send_reschedule(cpu);
1009 }
1010
1011 static void resched_cpu(int cpu)
1012 {
1013         struct rq *rq = cpu_rq(cpu);
1014         unsigned long flags;
1015
1016         if (!spin_trylock_irqsave(&rq->lock, flags))
1017                 return;
1018         resched_task(cpu_curr(cpu));
1019         spin_unlock_irqrestore(&rq->lock, flags);
1020 }
1021 #else
1022 static void __resched_task(struct task_struct *p, int tif_bit)
1023 {
1024         assert_spin_locked(&task_rq(p)->lock);
1025         set_tsk_thread_flag(p, tif_bit);
1026 }
1027 #endif
1028
1029 #if BITS_PER_LONG == 32
1030 # define WMULT_CONST    (~0UL)
1031 #else
1032 # define WMULT_CONST    (1UL << 32)
1033 #endif
1034
1035 #define WMULT_SHIFT     32
1036
1037 /*
1038  * Shift right and round:
1039  */
1040 #define SRR(x, y) (((x) + (1UL << ((y) - 1))) >> (y))
1041
1042 static unsigned long
1043 calc_delta_mine(unsigned long delta_exec, unsigned long weight,
1044                 struct load_weight *lw)
1045 {
1046         u64 tmp;
1047
1048         if (unlikely(!lw->inv_weight))
1049                 lw->inv_weight = (WMULT_CONST - lw->weight/2) / lw->weight + 1;
1050
1051         tmp = (u64)delta_exec * weight;
1052         /*
1053          * Check whether we'd overflow the 64-bit multiplication:
1054          */
1055         if (unlikely(tmp > WMULT_CONST))
1056                 tmp = SRR(SRR(tmp, WMULT_SHIFT/2) * lw->inv_weight,
1057                         WMULT_SHIFT/2);
1058         else
1059                 tmp = SRR(tmp * lw->inv_weight, WMULT_SHIFT);
1060
1061         return (unsigned long)min(tmp, (u64)(unsigned long)LONG_MAX);
1062 }
1063
1064 static inline unsigned long
1065 calc_delta_fair(unsigned long delta_exec, struct load_weight *lw)
1066 {
1067         return calc_delta_mine(delta_exec, NICE_0_LOAD, lw);
1068 }
1069
1070 static inline void update_load_add(struct load_weight *lw, unsigned long inc)
1071 {
1072         lw->weight += inc;
1073 }
1074
1075 static inline void update_load_sub(struct load_weight *lw, unsigned long dec)
1076 {
1077         lw->weight -= dec;
1078 }
1079
1080 /*
1081  * To aid in avoiding the subversion of "niceness" due to uneven distribution
1082  * of tasks with abnormal "nice" values across CPUs the contribution that
1083  * each task makes to its run queue's load is weighted according to its
1084  * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
1085  * scaled version of the new time slice allocation that they receive on time
1086  * slice expiry etc.
1087  */
1088
1089 #define WEIGHT_IDLEPRIO         2
1090 #define WMULT_IDLEPRIO          (1 << 31)
1091
1092 /*
1093  * Nice levels are multiplicative, with a gentle 10% change for every
1094  * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
1095  * nice 1, it will get ~10% less CPU time than another CPU-bound task
1096  * that remained on nice 0.
1097  *
1098  * The "10% effect" is relative and cumulative: from _any_ nice level,
1099  * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
1100  * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
1101  * If a task goes up by ~10% and another task goes down by ~10% then
1102  * the relative distance between them is ~25%.)
1103  */
1104 static const int prio_to_weight[40] = {
1105  /* -20 */     88761,     71755,     56483,     46273,     36291,
1106  /* -15 */     29154,     23254,     18705,     14949,     11916,
1107  /* -10 */      9548,      7620,      6100,      4904,      3906,
1108  /*  -5 */      3121,      2501,      1991,      1586,      1277,
1109  /*   0 */      1024,       820,       655,       526,       423,
1110  /*   5 */       335,       272,       215,       172,       137,
1111  /*  10 */       110,        87,        70,        56,        45,
1112  /*  15 */        36,        29,        23,        18,        15,
1113 };
1114
1115 /*
1116  * Inverse (2^32/x) values of the prio_to_weight[] array, precalculated.
1117  *
1118  * In cases where the weight does not change often, we can use the
1119  * precalculated inverse to speed up arithmetics by turning divisions
1120  * into multiplications:
1121  */
1122 static const u32 prio_to_wmult[40] = {
1123  /* -20 */     48388,     59856,     76040,     92818,    118348,
1124  /* -15 */    147320,    184698,    229616,    287308,    360437,
1125  /* -10 */    449829,    563644,    704093,    875809,   1099582,
1126  /*  -5 */   1376151,   1717300,   2157191,   2708050,   3363326,
1127  /*   0 */   4194304,   5237765,   6557202,   8165337,  10153587,
1128  /*   5 */  12820798,  15790321,  19976592,  24970740,  31350126,
1129  /*  10 */  39045157,  49367440,  61356676,  76695844,  95443717,
1130  /*  15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
1131 };
1132
1133 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup);
1134
1135 /*
1136  * runqueue iterator, to support SMP load-balancing between different
1137  * scheduling classes, without having to expose their internal data
1138  * structures to the load-balancing proper:
1139  */
1140 struct rq_iterator {
1141         void *arg;
1142         struct task_struct *(*start)(void *);
1143         struct task_struct *(*next)(void *);
1144 };
1145
1146 #ifdef CONFIG_SMP
1147 static unsigned long
1148 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
1149               unsigned long max_load_move, struct sched_domain *sd,
1150               enum cpu_idle_type idle, int *all_pinned,
1151               int *this_best_prio, struct rq_iterator *iterator);
1152
1153 static int
1154 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
1155                    struct sched_domain *sd, enum cpu_idle_type idle,
1156                    struct rq_iterator *iterator);
1157 #endif
1158
1159 #ifdef CONFIG_CGROUP_CPUACCT
1160 static void cpuacct_charge(struct task_struct *tsk, u64 cputime);
1161 #else
1162 static inline void cpuacct_charge(struct task_struct *tsk, u64 cputime) {}
1163 #endif
1164
1165 static inline void inc_cpu_load(struct rq *rq, unsigned long load)
1166 {
1167         update_load_add(&rq->load, load);
1168 }
1169
1170 static inline void dec_cpu_load(struct rq *rq, unsigned long load)
1171 {
1172         update_load_sub(&rq->load, load);
1173 }
1174
1175 #ifdef CONFIG_SMP
1176 static unsigned long source_load(int cpu, int type);
1177 static unsigned long target_load(int cpu, int type);
1178 static unsigned long cpu_avg_load_per_task(int cpu);
1179 static int task_hot(struct task_struct *p, u64 now, struct sched_domain *sd);
1180 #endif /* CONFIG_SMP */
1181
1182 #include "sched_stats.h"
1183 #include "sched_idletask.c"
1184 #include "sched_fair.c"
1185 #include "sched_rt.c"
1186 #ifdef CONFIG_SCHED_DEBUG
1187 # include "sched_debug.c"
1188 #endif
1189
1190 #define sched_class_highest (&rt_sched_class)
1191
1192 static void inc_nr_running(struct task_struct *p, struct rq *rq)
1193 {
1194         rq->nr_running++;
1195 }
1196
1197 static void dec_nr_running(struct task_struct *p, struct rq *rq)
1198 {
1199         rq->nr_running--;
1200 }
1201
1202 static void set_load_weight(struct task_struct *p)
1203 {
1204         if (task_has_rt_policy(p)) {
1205                 p->se.load.weight = prio_to_weight[0] * 2;
1206                 p->se.load.inv_weight = prio_to_wmult[0] >> 1;
1207                 return;
1208         }
1209
1210         /*
1211          * SCHED_IDLE tasks get minimal weight:
1212          */
1213         if (p->policy == SCHED_IDLE) {
1214                 p->se.load.weight = WEIGHT_IDLEPRIO;
1215                 p->se.load.inv_weight = WMULT_IDLEPRIO;
1216                 return;
1217         }
1218
1219         p->se.load.weight = prio_to_weight[p->static_prio - MAX_RT_PRIO];
1220         p->se.load.inv_weight = prio_to_wmult[p->static_prio - MAX_RT_PRIO];
1221 }
1222
1223 static void enqueue_task(struct rq *rq, struct task_struct *p, int wakeup)
1224 {
1225         sched_info_queued(p);
1226         p->sched_class->enqueue_task(rq, p, wakeup);
1227         p->se.on_rq = 1;
1228 }
1229
1230 static void dequeue_task(struct rq *rq, struct task_struct *p, int sleep)
1231 {
1232         p->sched_class->dequeue_task(rq, p, sleep);
1233         p->se.on_rq = 0;
1234 }
1235
1236 /*
1237  * __normal_prio - return the priority that is based on the static prio
1238  */
1239 static inline int __normal_prio(struct task_struct *p)
1240 {
1241         return p->static_prio;
1242 }
1243
1244 /*
1245  * Calculate the expected normal priority: i.e. priority
1246  * without taking RT-inheritance into account. Might be
1247  * boosted by interactivity modifiers. Changes upon fork,
1248  * setprio syscalls, and whenever the interactivity
1249  * estimator recalculates.
1250  */
1251 static inline int normal_prio(struct task_struct *p)
1252 {
1253         int prio;
1254
1255         if (task_has_rt_policy(p))
1256                 prio = MAX_RT_PRIO-1 - p->rt_priority;
1257         else
1258                 prio = __normal_prio(p);
1259         return prio;
1260 }
1261
1262 /*
1263  * Calculate the current priority, i.e. the priority
1264  * taken into account by the scheduler. This value might
1265  * be boosted by RT tasks, or might be boosted by
1266  * interactivity modifiers. Will be RT if the task got
1267  * RT-boosted. If not then it returns p->normal_prio.
1268  */
1269 static int effective_prio(struct task_struct *p)
1270 {
1271         p->normal_prio = normal_prio(p);
1272         /*
1273          * If we are RT tasks or we were boosted to RT priority,
1274          * keep the priority unchanged. Otherwise, update priority
1275          * to the normal priority:
1276          */
1277         if (!rt_prio(p->prio))
1278                 return p->normal_prio;
1279         return p->prio;
1280 }
1281
1282 /*
1283  * activate_task - move a task to the runqueue.
1284  */
1285 static void activate_task(struct rq *rq, struct task_struct *p, int wakeup)
1286 {
1287         if (p->state == TASK_UNINTERRUPTIBLE)
1288                 rq->nr_uninterruptible--;
1289
1290         enqueue_task(rq, p, wakeup);
1291         inc_nr_running(p, rq);
1292 }
1293
1294 /*
1295  * deactivate_task - remove a task from the runqueue.
1296  */
1297 static void deactivate_task(struct rq *rq, struct task_struct *p, int sleep)
1298 {
1299         if (p->state == TASK_UNINTERRUPTIBLE)
1300                 rq->nr_uninterruptible++;
1301
1302         dequeue_task(rq, p, sleep);
1303         dec_nr_running(p, rq);
1304 }
1305
1306 /**
1307  * task_curr - is this task currently executing on a CPU?
1308  * @p: the task in question.
1309  */
1310 inline int task_curr(const struct task_struct *p)
1311 {
1312         return cpu_curr(task_cpu(p)) == p;
1313 }
1314
1315 /* Used instead of source_load when we know the type == 0 */
1316 unsigned long weighted_cpuload(const int cpu)
1317 {
1318         return cpu_rq(cpu)->load.weight;
1319 }
1320
1321 static inline void __set_task_cpu(struct task_struct *p, unsigned int cpu)
1322 {
1323         set_task_cfs_rq(p, cpu);
1324 #ifdef CONFIG_SMP
1325         /*
1326          * After ->cpu is set up to a new value, task_rq_lock(p, ...) can be
1327          * successfuly executed on another CPU. We must ensure that updates of
1328          * per-task data have been completed by this moment.
1329          */
1330         smp_wmb();
1331         task_thread_info(p)->cpu = cpu;
1332 #endif
1333 }
1334
1335 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1336                                        const struct sched_class *prev_class,
1337                                        int oldprio, int running)
1338 {
1339         if (prev_class != p->sched_class) {
1340                 if (prev_class->switched_from)
1341                         prev_class->switched_from(rq, p, running);
1342                 p->sched_class->switched_to(rq, p, running);
1343         } else
1344                 p->sched_class->prio_changed(rq, p, oldprio, running);
1345 }
1346
1347 #ifdef CONFIG_SMP
1348
1349 /*
1350  * Is this task likely cache-hot:
1351  */
1352 static int
1353 task_hot(struct task_struct *p, u64 now, struct sched_domain *sd)
1354 {
1355         s64 delta;
1356
1357         if (p->sched_class != &fair_sched_class)
1358                 return 0;
1359
1360         if (sysctl_sched_migration_cost == -1)
1361                 return 1;
1362         if (sysctl_sched_migration_cost == 0)
1363                 return 0;
1364
1365         delta = now - p->se.exec_start;
1366
1367         return delta < (s64)sysctl_sched_migration_cost;
1368 }
1369
1370
1371 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1372 {
1373         int old_cpu = task_cpu(p);
1374         struct rq *old_rq = cpu_rq(old_cpu), *new_rq = cpu_rq(new_cpu);
1375         struct cfs_rq *old_cfsrq = task_cfs_rq(p),
1376                       *new_cfsrq = cpu_cfs_rq(old_cfsrq, new_cpu);
1377         u64 clock_offset;
1378
1379         clock_offset = old_rq->clock - new_rq->clock;
1380
1381 #ifdef CONFIG_SCHEDSTATS
1382         if (p->se.wait_start)
1383                 p->se.wait_start -= clock_offset;
1384         if (p->se.sleep_start)
1385                 p->se.sleep_start -= clock_offset;
1386         if (p->se.block_start)
1387                 p->se.block_start -= clock_offset;
1388         if (old_cpu != new_cpu) {
1389                 schedstat_inc(p, se.nr_migrations);
1390                 if (task_hot(p, old_rq->clock, NULL))
1391                         schedstat_inc(p, se.nr_forced2_migrations);
1392         }
1393 #endif
1394         p->se.vruntime -= old_cfsrq->min_vruntime -
1395                                          new_cfsrq->min_vruntime;
1396
1397         __set_task_cpu(p, new_cpu);
1398 }
1399
1400 struct migration_req {
1401         struct list_head list;
1402
1403         struct task_struct *task;
1404         int dest_cpu;
1405
1406         struct completion done;
1407 };
1408
1409 /*
1410  * The task's runqueue lock must be held.
1411  * Returns true if you have to wait for migration thread.
1412  */
1413 static int
1414 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1415 {
1416         struct rq *rq = task_rq(p);
1417
1418         /*
1419          * If the task is not on a runqueue (and not running), then
1420          * it is sufficient to simply update the task's cpu field.
1421          */
1422         if (!p->se.on_rq && !task_running(rq, p)) {
1423                 set_task_cpu(p, dest_cpu);
1424                 return 0;
1425         }
1426
1427         init_completion(&req->done);
1428         req->task = p;
1429         req->dest_cpu = dest_cpu;
1430         list_add(&req->list, &rq->migration_queue);
1431
1432         return 1;
1433 }
1434
1435 /*
1436  * wait_task_inactive - wait for a thread to unschedule.
1437  *
1438  * The caller must ensure that the task *will* unschedule sometime soon,
1439  * else this function might spin for a *long* time. This function can't
1440  * be called with interrupts off, or it may introduce deadlock with
1441  * smp_call_function() if an IPI is sent by the same process we are
1442  * waiting to become inactive.
1443  */
1444 void wait_task_inactive(struct task_struct *p)
1445 {
1446         unsigned long flags;
1447         int running, on_rq;
1448         struct rq *rq;
1449
1450         for (;;) {
1451                 /*
1452                  * We do the initial early heuristics without holding
1453                  * any task-queue locks at all. We'll only try to get
1454                  * the runqueue lock when things look like they will
1455                  * work out!
1456                  */
1457                 rq = task_rq(p);
1458
1459                 /*
1460                  * If the task is actively running on another CPU
1461                  * still, just relax and busy-wait without holding
1462                  * any locks.
1463                  *
1464                  * NOTE! Since we don't hold any locks, it's not
1465                  * even sure that "rq" stays as the right runqueue!
1466                  * But we don't care, since "task_running()" will
1467                  * return false if the runqueue has changed and p
1468                  * is actually now running somewhere else!
1469                  */
1470                 while (task_running(rq, p))
1471                         cpu_relax();
1472
1473                 /*
1474                  * Ok, time to look more closely! We need the rq
1475                  * lock now, to be *sure*. If we're wrong, we'll
1476                  * just go back and repeat.
1477                  */
1478                 rq = task_rq_lock(p, &flags);
1479                 running = task_running(rq, p);
1480                 on_rq = p->se.on_rq;
1481                 task_rq_unlock(rq, &flags);
1482
1483                 /*
1484                  * Was it really running after all now that we
1485                  * checked with the proper locks actually held?
1486                  *
1487                  * Oops. Go back and try again..
1488                  */
1489                 if (unlikely(running)) {
1490                         cpu_relax();
1491                         continue;
1492                 }
1493
1494                 /*
1495                  * It's not enough that it's not actively running,
1496                  * it must be off the runqueue _entirely_, and not
1497                  * preempted!
1498                  *
1499                  * So if it wa still runnable (but just not actively
1500                  * running right now), it's preempted, and we should
1501                  * yield - it could be a while.
1502                  */
1503                 if (unlikely(on_rq)) {
1504                         schedule_timeout_uninterruptible(1);
1505                         continue;
1506                 }
1507
1508                 /*
1509                  * Ahh, all good. It wasn't running, and it wasn't
1510                  * runnable, which means that it will never become
1511                  * running in the future either. We're all done!
1512                  */
1513                 break;
1514         }
1515 }
1516
1517 /***
1518  * kick_process - kick a running thread to enter/exit the kernel
1519  * @p: the to-be-kicked thread
1520  *
1521  * Cause a process which is running on another CPU to enter
1522  * kernel-mode, without any delay. (to get signals handled.)
1523  *
1524  * NOTE: this function doesnt have to take the runqueue lock,
1525  * because all it wants to ensure is that the remote task enters
1526  * the kernel. If the IPI races and the task has been migrated
1527  * to another CPU then no harm is done and the purpose has been
1528  * achieved as well.
1529  */
1530 void kick_process(struct task_struct *p)
1531 {
1532         int cpu;
1533
1534         preempt_disable();
1535         cpu = task_cpu(p);
1536         if ((cpu != smp_processor_id()) && task_curr(p))
1537                 smp_send_reschedule(cpu);
1538         preempt_enable();
1539 }
1540
1541 /*
1542  * Return a low guess at the load of a migration-source cpu weighted
1543  * according to the scheduling class and "nice" value.
1544  *
1545  * We want to under-estimate the load of migration sources, to
1546  * balance conservatively.
1547  */
1548 static unsigned long source_load(int cpu, int type)
1549 {
1550         struct rq *rq = cpu_rq(cpu);
1551         unsigned long total = weighted_cpuload(cpu);
1552
1553         if (type == 0)
1554                 return total;
1555
1556         return min(rq->cpu_load[type-1], total);
1557 }
1558
1559 /*
1560  * Return a high guess at the load of a migration-target cpu weighted
1561  * according to the scheduling class and "nice" value.
1562  */
1563 static unsigned long target_load(int cpu, int type)
1564 {
1565         struct rq *rq = cpu_rq(cpu);
1566         unsigned long total = weighted_cpuload(cpu);
1567
1568         if (type == 0)
1569                 return total;
1570
1571         return max(rq->cpu_load[type-1], total);
1572 }
1573
1574 /*
1575  * Return the average load per task on the cpu's run queue
1576  */
1577 static unsigned long cpu_avg_load_per_task(int cpu)
1578 {
1579         struct rq *rq = cpu_rq(cpu);
1580         unsigned long total = weighted_cpuload(cpu);
1581         unsigned long n = rq->nr_running;
1582
1583         return n ? total / n : SCHED_LOAD_SCALE;
1584 }
1585
1586 /*
1587  * find_idlest_group finds and returns the least busy CPU group within the
1588  * domain.
1589  */
1590 static struct sched_group *
1591 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1592 {
1593         struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1594         unsigned long min_load = ULONG_MAX, this_load = 0;
1595         int load_idx = sd->forkexec_idx;
1596         int imbalance = 100 + (sd->imbalance_pct-100)/2;
1597
1598         do {
1599                 unsigned long load, avg_load;
1600                 int local_group;
1601                 int i;
1602
1603                 /* Skip over this group if it has no CPUs allowed */
1604                 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
1605                         continue;
1606
1607                 local_group = cpu_isset(this_cpu, group->cpumask);
1608
1609                 /* Tally up the load of all CPUs in the group */
1610                 avg_load = 0;
1611
1612                 for_each_cpu_mask(i, group->cpumask) {
1613                         /* Bias balancing toward cpus of our domain */
1614                         if (local_group)
1615                                 load = source_load(i, load_idx);
1616                         else
1617                                 load = target_load(i, load_idx);
1618
1619                         avg_load += load;
1620                 }
1621
1622                 /* Adjust by relative CPU power of the group */
1623                 avg_load = sg_div_cpu_power(group,
1624                                 avg_load * SCHED_LOAD_SCALE);
1625
1626                 if (local_group) {
1627                         this_load = avg_load;
1628                         this = group;
1629                 } else if (avg_load < min_load) {
1630                         min_load = avg_load;
1631                         idlest = group;
1632                 }
1633         } while (group = group->next, group != sd->groups);
1634
1635         if (!idlest || 100*this_load < imbalance*min_load)
1636                 return NULL;
1637         return idlest;
1638 }
1639
1640 /*
1641  * find_idlest_cpu - find the idlest cpu among the cpus in group.
1642  */
1643 static int
1644 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
1645 {
1646         cpumask_t tmp;
1647         unsigned long load, min_load = ULONG_MAX;
1648         int idlest = -1;
1649         int i;
1650
1651         /* Traverse only the allowed CPUs */
1652         cpus_and(tmp, group->cpumask, p->cpus_allowed);
1653
1654         for_each_cpu_mask(i, tmp) {
1655                 load = weighted_cpuload(i);
1656
1657                 if (load < min_load || (load == min_load && i == this_cpu)) {
1658                         min_load = load;
1659                         idlest = i;
1660                 }
1661         }
1662
1663         return idlest;
1664 }
1665
1666 /*
1667  * sched_balance_self: balance the current task (running on cpu) in domains
1668  * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1669  * SD_BALANCE_EXEC.
1670  *
1671  * Balance, ie. select the least loaded group.
1672  *
1673  * Returns the target CPU number, or the same CPU if no balancing is needed.
1674  *
1675  * preempt must be disabled.
1676  */
1677 static int sched_balance_self(int cpu, int flag)
1678 {
1679         struct task_struct *t = current;
1680         struct sched_domain *tmp, *sd = NULL;
1681
1682         for_each_domain(cpu, tmp) {
1683                 /*
1684                  * If power savings logic is enabled for a domain, stop there.
1685                  */
1686                 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
1687                         break;
1688                 if (tmp->flags & flag)
1689                         sd = tmp;
1690         }
1691
1692         while (sd) {
1693                 cpumask_t span;
1694                 struct sched_group *group;
1695                 int new_cpu, weight;
1696
1697                 if (!(sd->flags & flag)) {
1698                         sd = sd->child;
1699                         continue;
1700                 }
1701
1702                 span = sd->span;
1703                 group = find_idlest_group(sd, t, cpu);
1704                 if (!group) {
1705                         sd = sd->child;
1706                         continue;
1707                 }
1708
1709                 new_cpu = find_idlest_cpu(group, t, cpu);
1710                 if (new_cpu == -1 || new_cpu == cpu) {
1711                         /* Now try balancing at a lower domain level of cpu */
1712                         sd = sd->child;
1713                         continue;
1714                 }
1715
1716                 /* Now try balancing at a lower domain level of new_cpu */
1717                 cpu = new_cpu;
1718                 sd = NULL;
1719                 weight = cpus_weight(span);
1720                 for_each_domain(cpu, tmp) {
1721                         if (weight <= cpus_weight(tmp->span))
1722                                 break;
1723                         if (tmp->flags & flag)
1724                                 sd = tmp;
1725                 }
1726                 /* while loop will break here if sd == NULL */
1727         }
1728
1729         return cpu;
1730 }
1731
1732 #endif /* CONFIG_SMP */
1733
1734 /***
1735  * try_to_wake_up - wake up a thread
1736  * @p: the to-be-woken-up thread
1737  * @state: the mask of task states that can be woken
1738  * @sync: do a synchronous wakeup?
1739  *
1740  * Put it on the run-queue if it's not already there. The "current"
1741  * thread is always on the run-queue (except when the actual
1742  * re-schedule is in progress), and as such you're allowed to do
1743  * the simpler "current->state = TASK_RUNNING" to mark yourself
1744  * runnable without the overhead of this.
1745  *
1746  * returns failure only if the task is already active.
1747  */
1748 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
1749 {
1750         int cpu, orig_cpu, this_cpu, success = 0;
1751         unsigned long flags;
1752         long old_state;
1753         struct rq *rq;
1754
1755         rq = task_rq_lock(p, &flags);
1756         old_state = p->state;
1757         if (!(old_state & state))
1758                 goto out;
1759
1760         if (p->se.on_rq)
1761                 goto out_running;
1762
1763         cpu = task_cpu(p);
1764         orig_cpu = cpu;
1765         this_cpu = smp_processor_id();
1766
1767 #ifdef CONFIG_SMP
1768         if (unlikely(task_running(rq, p)))
1769                 goto out_activate;
1770
1771         cpu = p->sched_class->select_task_rq(p, sync);
1772         if (cpu != orig_cpu) {
1773                 set_task_cpu(p, cpu);
1774                 task_rq_unlock(rq, &flags);
1775                 /* might preempt at this point */
1776                 rq = task_rq_lock(p, &flags);
1777                 old_state = p->state;
1778                 if (!(old_state & state))
1779                         goto out;
1780                 if (p->se.on_rq)
1781                         goto out_running;
1782
1783                 this_cpu = smp_processor_id();
1784                 cpu = task_cpu(p);
1785         }
1786
1787 #ifdef CONFIG_SCHEDSTATS
1788         schedstat_inc(rq, ttwu_count);
1789         if (cpu == this_cpu)
1790                 schedstat_inc(rq, ttwu_local);
1791         else {
1792                 struct sched_domain *sd;
1793                 for_each_domain(this_cpu, sd) {
1794                         if (cpu_isset(cpu, sd->span)) {
1795                                 schedstat_inc(sd, ttwu_wake_remote);
1796                                 break;
1797                         }
1798                 }
1799         }
1800 #endif
1801
1802 out_activate:
1803 #endif /* CONFIG_SMP */
1804         schedstat_inc(p, se.nr_wakeups);
1805         if (sync)
1806                 schedstat_inc(p, se.nr_wakeups_sync);
1807         if (orig_cpu != cpu)
1808                 schedstat_inc(p, se.nr_wakeups_migrate);
1809         if (cpu == this_cpu)
1810                 schedstat_inc(p, se.nr_wakeups_local);
1811         else
1812                 schedstat_inc(p, se.nr_wakeups_remote);
1813         update_rq_clock(rq);
1814         activate_task(rq, p, 1);
1815         check_preempt_curr(rq, p);
1816         success = 1;
1817
1818 out_running:
1819         p->state = TASK_RUNNING;
1820 #ifdef CONFIG_SMP
1821         if (p->sched_class->task_wake_up)
1822                 p->sched_class->task_wake_up(rq, p);
1823 #endif
1824 out:
1825         task_rq_unlock(rq, &flags);
1826
1827         return success;
1828 }
1829
1830 int fastcall wake_up_process(struct task_struct *p)
1831 {
1832         return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1833                                  TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1834 }
1835 EXPORT_SYMBOL(wake_up_process);
1836
1837 int fastcall wake_up_state(struct task_struct *p, unsigned int state)
1838 {
1839         return try_to_wake_up(p, state, 0);
1840 }
1841
1842 /*
1843  * Perform scheduler related setup for a newly forked process p.
1844  * p is forked by current.
1845  *
1846  * __sched_fork() is basic setup used by init_idle() too:
1847  */
1848 static void __sched_fork(struct task_struct *p)
1849 {
1850         p->se.exec_start                = 0;
1851         p->se.sum_exec_runtime          = 0;
1852         p->se.prev_sum_exec_runtime     = 0;
1853
1854 #ifdef CONFIG_SCHEDSTATS
1855         p->se.wait_start                = 0;
1856         p->se.sum_sleep_runtime         = 0;
1857         p->se.sleep_start               = 0;
1858         p->se.block_start               = 0;
1859         p->se.sleep_max                 = 0;
1860         p->se.block_max                 = 0;
1861         p->se.exec_max                  = 0;
1862         p->se.slice_max                 = 0;
1863         p->se.wait_max                  = 0;
1864 #endif
1865
1866         INIT_LIST_HEAD(&p->rt.run_list);
1867         p->se.on_rq = 0;
1868
1869 #ifdef CONFIG_PREEMPT_NOTIFIERS
1870         INIT_HLIST_HEAD(&p->preempt_notifiers);
1871 #endif
1872
1873         /*
1874          * We mark the process as running here, but have not actually
1875          * inserted it onto the runqueue yet. This guarantees that
1876          * nobody will actually run it, and a signal or other external
1877          * event cannot wake it up and insert it on the runqueue either.
1878          */
1879         p->state = TASK_RUNNING;
1880 }
1881
1882 /*
1883  * fork()/clone()-time setup:
1884  */
1885 void sched_fork(struct task_struct *p, int clone_flags)
1886 {
1887         int cpu = get_cpu();
1888
1889         __sched_fork(p);
1890
1891 #ifdef CONFIG_SMP
1892         cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
1893 #endif
1894         set_task_cpu(p, cpu);
1895
1896         /*
1897          * Make sure we do not leak PI boosting priority to the child:
1898          */
1899         p->prio = current->normal_prio;
1900         if (!rt_prio(p->prio))
1901                 p->sched_class = &fair_sched_class;
1902
1903 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
1904         if (likely(sched_info_on()))
1905                 memset(&p->sched_info, 0, sizeof(p->sched_info));
1906 #endif
1907 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
1908         p->oncpu = 0;
1909 #endif
1910 #ifdef CONFIG_PREEMPT
1911         /* Want to start with kernel preemption disabled. */
1912         task_thread_info(p)->preempt_count = 1;
1913 #endif
1914         put_cpu();
1915 }
1916
1917 /*
1918  * wake_up_new_task - wake up a newly created task for the first time.
1919  *
1920  * This function will do some initial scheduler statistics housekeeping
1921  * that must be done for every newly created context, then puts the task
1922  * on the runqueue and wakes it.
1923  */
1924 void fastcall wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
1925 {
1926         unsigned long flags;
1927         struct rq *rq;
1928
1929         rq = task_rq_lock(p, &flags);
1930         BUG_ON(p->state != TASK_RUNNING);
1931         update_rq_clock(rq);
1932
1933         p->prio = effective_prio(p);
1934
1935         if (!p->sched_class->task_new || !current->se.on_rq) {
1936                 activate_task(rq, p, 0);
1937         } else {
1938                 /*
1939                  * Let the scheduling class do new task startup
1940                  * management (if any):
1941                  */
1942                 p->sched_class->task_new(rq, p);
1943                 inc_nr_running(p, rq);
1944         }
1945         check_preempt_curr(rq, p);
1946 #ifdef CONFIG_SMP
1947         if (p->sched_class->task_wake_up)
1948                 p->sched_class->task_wake_up(rq, p);
1949 #endif
1950         task_rq_unlock(rq, &flags);
1951 }
1952
1953 #ifdef CONFIG_PREEMPT_NOTIFIERS
1954
1955 /**
1956  * preempt_notifier_register - tell me when current is being being preempted & rescheduled
1957  * @notifier: notifier struct to register
1958  */
1959 void preempt_notifier_register(struct preempt_notifier *notifier)
1960 {
1961         hlist_add_head(&notifier->link, &current->preempt_notifiers);
1962 }
1963 EXPORT_SYMBOL_GPL(preempt_notifier_register);
1964
1965 /**
1966  * preempt_notifier_unregister - no longer interested in preemption notifications
1967  * @notifier: notifier struct to unregister
1968  *
1969  * This is safe to call from within a preemption notifier.
1970  */
1971 void preempt_notifier_unregister(struct preempt_notifier *notifier)
1972 {
1973         hlist_del(&notifier->link);
1974 }
1975 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
1976
1977 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
1978 {
1979         struct preempt_notifier *notifier;
1980         struct hlist_node *node;
1981
1982         hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
1983                 notifier->ops->sched_in(notifier, raw_smp_processor_id());
1984 }
1985
1986 static void
1987 fire_sched_out_preempt_notifiers(struct task_struct *curr,
1988                                  struct task_struct *next)
1989 {
1990         struct preempt_notifier *notifier;
1991         struct hlist_node *node;
1992
1993         hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
1994                 notifier->ops->sched_out(notifier, next);
1995 }
1996
1997 #else
1998
1999 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2000 {
2001 }
2002
2003 static void
2004 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2005                                  struct task_struct *next)
2006 {
2007 }
2008
2009 #endif
2010
2011 /**
2012  * prepare_task_switch - prepare to switch tasks
2013  * @rq: the runqueue preparing to switch
2014  * @prev: the current task that is being switched out
2015  * @next: the task we are going to switch to.
2016  *
2017  * This is called with the rq lock held and interrupts off. It must
2018  * be paired with a subsequent finish_task_switch after the context
2019  * switch.
2020  *
2021  * prepare_task_switch sets up locking and calls architecture specific
2022  * hooks.
2023  */
2024 static inline void
2025 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2026                     struct task_struct *next)
2027 {
2028         fire_sched_out_preempt_notifiers(prev, next);
2029         prepare_lock_switch(rq, next);
2030         prepare_arch_switch(next);
2031 }
2032
2033 /**
2034  * finish_task_switch - clean up after a task-switch
2035  * @rq: runqueue associated with task-switch
2036  * @prev: the thread we just switched away from.
2037  *
2038  * finish_task_switch must be called after the context switch, paired
2039  * with a prepare_task_switch call before the context switch.
2040  * finish_task_switch will reconcile locking set up by prepare_task_switch,
2041  * and do any other architecture-specific cleanup actions.
2042  *
2043  * Note that we may have delayed dropping an mm in context_switch(). If
2044  * so, we finish that here outside of the runqueue lock. (Doing it
2045  * with the lock held can cause deadlocks; see schedule() for
2046  * details.)
2047  */
2048 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2049         __releases(rq->lock)
2050 {
2051         struct mm_struct *mm = rq->prev_mm;
2052         long prev_state;
2053
2054         rq->prev_mm = NULL;
2055
2056         /*
2057          * A task struct has one reference for the use as "current".
2058          * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2059          * schedule one last time. The schedule call will never return, and
2060          * the scheduled task must drop that reference.
2061          * The test for TASK_DEAD must occur while the runqueue locks are
2062          * still held, otherwise prev could be scheduled on another cpu, die
2063          * there before we look at prev->state, and then the reference would
2064          * be dropped twice.
2065          *              Manfred Spraul <manfred@colorfullife.com>
2066          */
2067         prev_state = prev->state;
2068         finish_arch_switch(prev);
2069         finish_lock_switch(rq, prev);
2070 #ifdef CONFIG_SMP
2071         if (current->sched_class->post_schedule)
2072                 current->sched_class->post_schedule(rq);
2073 #endif
2074
2075         fire_sched_in_preempt_notifiers(current);
2076         if (mm)
2077                 mmdrop(mm);
2078         if (unlikely(prev_state == TASK_DEAD)) {
2079                 /*
2080                  * Remove function-return probe instances associated with this
2081                  * task and put them back on the free list.
2082                  */
2083                 kprobe_flush_task(prev);
2084                 put_task_struct(prev);
2085         }
2086 }
2087
2088 /**
2089  * schedule_tail - first thing a freshly forked thread must call.
2090  * @prev: the thread we just switched away from.
2091  */
2092 asmlinkage void schedule_tail(struct task_struct *prev)
2093         __releases(rq->lock)
2094 {
2095         struct rq *rq = this_rq();
2096
2097         finish_task_switch(rq, prev);
2098 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2099         /* In this case, finish_task_switch does not reenable preemption */
2100         preempt_enable();
2101 #endif
2102         if (current->set_child_tid)
2103                 put_user(task_pid_vnr(current), current->set_child_tid);
2104 }
2105
2106 /*
2107  * context_switch - switch to the new MM and the new
2108  * thread's register state.
2109  */
2110 static inline void
2111 context_switch(struct rq *rq, struct task_struct *prev,
2112                struct task_struct *next)
2113 {
2114         struct mm_struct *mm, *oldmm;
2115
2116         prepare_task_switch(rq, prev, next);
2117         mm = next->mm;
2118         oldmm = prev->active_mm;
2119         /*
2120          * For paravirt, this is coupled with an exit in switch_to to
2121          * combine the page table reload and the switch backend into
2122          * one hypercall.
2123          */
2124         arch_enter_lazy_cpu_mode();
2125
2126         if (unlikely(!mm)) {
2127                 next->active_mm = oldmm;
2128                 atomic_inc(&oldmm->mm_count);
2129                 enter_lazy_tlb(oldmm, next);
2130         } else
2131                 switch_mm(oldmm, mm, next);
2132
2133         if (unlikely(!prev->mm)) {
2134                 prev->active_mm = NULL;
2135                 rq->prev_mm = oldmm;
2136         }
2137         /*
2138          * Since the runqueue lock will be released by the next
2139          * task (which is an invalid locking op but in the case
2140          * of the scheduler it's an obvious special-case), so we
2141          * do an early lockdep release here:
2142          */
2143 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2144         spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2145 #endif
2146
2147         /* Here we just switch the register state and the stack. */
2148         switch_to(prev, next, prev);
2149
2150         barrier();
2151         /*
2152          * this_rq must be evaluated again because prev may have moved
2153          * CPUs since it called schedule(), thus the 'rq' on its stack
2154          * frame will be invalid.
2155          */
2156         finish_task_switch(this_rq(), prev);
2157 }
2158
2159 /*
2160  * nr_running, nr_uninterruptible and nr_context_switches:
2161  *
2162  * externally visible scheduler statistics: current number of runnable
2163  * threads, current number of uninterruptible-sleeping threads, total
2164  * number of context switches performed since bootup.
2165  */
2166 unsigned long nr_running(void)
2167 {
2168         unsigned long i, sum = 0;
2169
2170         for_each_online_cpu(i)
2171                 sum += cpu_rq(i)->nr_running;
2172
2173         return sum;
2174 }
2175
2176 unsigned long nr_uninterruptible(void)
2177 {
2178         unsigned long i, sum = 0;
2179
2180         for_each_possible_cpu(i)
2181                 sum += cpu_rq(i)->nr_uninterruptible;
2182
2183         /*
2184          * Since we read the counters lockless, it might be slightly
2185          * inaccurate. Do not allow it to go below zero though:
2186          */
2187         if (unlikely((long)sum < 0))
2188                 sum = 0;
2189
2190         return sum;
2191 }
2192
2193 unsigned long long nr_context_switches(void)
2194 {
2195         int i;
2196         unsigned long long sum = 0;
2197
2198         for_each_possible_cpu(i)
2199                 sum += cpu_rq(i)->nr_switches;
2200
2201         return sum;
2202 }
2203
2204 unsigned long nr_iowait(void)
2205 {
2206         unsigned long i, sum = 0;
2207
2208         for_each_possible_cpu(i)
2209                 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2210
2211         return sum;
2212 }
2213
2214 unsigned long nr_active(void)
2215 {
2216         unsigned long i, running = 0, uninterruptible = 0;
2217
2218         for_each_online_cpu(i) {
2219                 running += cpu_rq(i)->nr_running;
2220                 uninterruptible += cpu_rq(i)->nr_uninterruptible;
2221         }
2222
2223         if (unlikely((long)uninterruptible < 0))
2224                 uninterruptible = 0;
2225
2226         return running + uninterruptible;
2227 }
2228
2229 /*
2230  * Update rq->cpu_load[] statistics. This function is usually called every
2231  * scheduler tick (TICK_NSEC).
2232  */
2233 static void update_cpu_load(struct rq *this_rq)
2234 {
2235         unsigned long this_load = this_rq->load.weight;
2236         int i, scale;
2237
2238         this_rq->nr_load_updates++;
2239
2240         /* Update our load: */
2241         for (i = 0, scale = 1; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
2242                 unsigned long old_load, new_load;
2243
2244                 /* scale is effectively 1 << i now, and >> i divides by scale */
2245
2246                 old_load = this_rq->cpu_load[i];
2247                 new_load = this_load;
2248                 /*
2249                  * Round up the averaging division if load is increasing. This
2250                  * prevents us from getting stuck on 9 if the load is 10, for
2251                  * example.
2252                  */
2253                 if (new_load > old_load)
2254                         new_load += scale-1;
2255                 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) >> i;
2256         }
2257 }
2258
2259 #ifdef CONFIG_SMP
2260
2261 /*
2262  * double_rq_lock - safely lock two runqueues
2263  *
2264  * Note this does not disable interrupts like task_rq_lock,
2265  * you need to do so manually before calling.
2266  */
2267 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
2268         __acquires(rq1->lock)
2269         __acquires(rq2->lock)
2270 {
2271         BUG_ON(!irqs_disabled());
2272         if (rq1 == rq2) {
2273                 spin_lock(&rq1->lock);
2274                 __acquire(rq2->lock);   /* Fake it out ;) */
2275         } else {
2276                 if (rq1 < rq2) {
2277                         spin_lock(&rq1->lock);
2278                         spin_lock(&rq2->lock);
2279                 } else {
2280                         spin_lock(&rq2->lock);
2281                         spin_lock(&rq1->lock);
2282                 }
2283         }
2284         update_rq_clock(rq1);
2285         update_rq_clock(rq2);
2286 }
2287
2288 /*
2289  * double_rq_unlock - safely unlock two runqueues
2290  *
2291  * Note this does not restore interrupts like task_rq_unlock,
2292  * you need to do so manually after calling.
2293  */
2294 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
2295         __releases(rq1->lock)
2296         __releases(rq2->lock)
2297 {
2298         spin_unlock(&rq1->lock);
2299         if (rq1 != rq2)
2300                 spin_unlock(&rq2->lock);
2301         else
2302                 __release(rq2->lock);
2303 }
2304
2305 /*
2306  * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2307  */
2308 static int double_lock_balance(struct rq *this_rq, struct rq *busiest)
2309         __releases(this_rq->lock)
2310         __acquires(busiest->lock)
2311         __acquires(this_rq->lock)
2312 {
2313         int ret = 0;
2314
2315         if (unlikely(!irqs_disabled())) {
2316                 /* printk() doesn't work good under rq->lock */
2317                 spin_unlock(&this_rq->lock);
2318                 BUG_ON(1);
2319         }
2320         if (unlikely(!spin_trylock(&busiest->lock))) {
2321                 if (busiest < this_rq) {
2322                         spin_unlock(&this_rq->lock);
2323                         spin_lock(&busiest->lock);
2324                         spin_lock(&this_rq->lock);
2325                         ret = 1;
2326                 } else
2327                         spin_lock(&busiest->lock);
2328         }
2329         return ret;
2330 }
2331
2332 /*
2333  * If dest_cpu is allowed for this process, migrate the task to it.
2334  * This is accomplished by forcing the cpu_allowed mask to only
2335  * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2336  * the cpu_allowed mask is restored.
2337  */
2338 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
2339 {
2340         struct migration_req req;
2341         unsigned long flags;
2342         struct rq *rq;
2343
2344         rq = task_rq_lock(p, &flags);
2345         if (!cpu_isset(dest_cpu, p->cpus_allowed)
2346             || unlikely(cpu_is_offline(dest_cpu)))
2347                 goto out;
2348
2349         /* force the process onto the specified CPU */
2350         if (migrate_task(p, dest_cpu, &req)) {
2351                 /* Need to wait for migration thread (might exit: take ref). */
2352                 struct task_struct *mt = rq->migration_thread;
2353
2354                 get_task_struct(mt);
2355                 task_rq_unlock(rq, &flags);
2356                 wake_up_process(mt);
2357                 put_task_struct(mt);
2358                 wait_for_completion(&req.done);
2359
2360                 return;
2361         }
2362 out:
2363         task_rq_unlock(rq, &flags);
2364 }
2365
2366 /*
2367  * sched_exec - execve() is a valuable balancing opportunity, because at
2368  * this point the task has the smallest effective memory and cache footprint.
2369  */
2370 void sched_exec(void)
2371 {
2372         int new_cpu, this_cpu = get_cpu();
2373         new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
2374         put_cpu();
2375         if (new_cpu != this_cpu)
2376                 sched_migrate_task(current, new_cpu);
2377 }
2378
2379 /*
2380  * pull_task - move a task from a remote runqueue to the local runqueue.
2381  * Both runqueues must be locked.
2382  */
2383 static void pull_task(struct rq *src_rq, struct task_struct *p,
2384                       struct rq *this_rq, int this_cpu)
2385 {
2386         deactivate_task(src_rq, p, 0);
2387         set_task_cpu(p, this_cpu);
2388         activate_task(this_rq, p, 0);
2389         /*
2390          * Note that idle threads have a prio of MAX_PRIO, for this test
2391          * to be always true for them.
2392          */
2393         check_preempt_curr(this_rq, p);
2394 }
2395
2396 /*
2397  * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2398  */
2399 static
2400 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
2401                      struct sched_domain *sd, enum cpu_idle_type idle,
2402                      int *all_pinned)
2403 {
2404         /*
2405          * We do not migrate tasks that are:
2406          * 1) running (obviously), or
2407          * 2) cannot be migrated to this CPU due to cpus_allowed, or
2408          * 3) are cache-hot on their current CPU.
2409          */
2410         if (!cpu_isset(this_cpu, p->cpus_allowed)) {
2411                 schedstat_inc(p, se.nr_failed_migrations_affine);
2412                 return 0;
2413         }
2414         *all_pinned = 0;
2415
2416         if (task_running(rq, p)) {
2417                 schedstat_inc(p, se.nr_failed_migrations_running);
2418                 return 0;
2419         }
2420
2421         /*
2422          * Aggressive migration if:
2423          * 1) task is cache cold, or
2424          * 2) too many balance attempts have failed.
2425          */
2426
2427         if (!task_hot(p, rq->clock, sd) ||
2428                         sd->nr_balance_failed > sd->cache_nice_tries) {
2429 #ifdef CONFIG_SCHEDSTATS
2430                 if (task_hot(p, rq->clock, sd)) {
2431                         schedstat_inc(sd, lb_hot_gained[idle]);
2432                         schedstat_inc(p, se.nr_forced_migrations);
2433                 }
2434 #endif
2435                 return 1;
2436         }
2437
2438         if (task_hot(p, rq->clock, sd)) {
2439                 schedstat_inc(p, se.nr_failed_migrations_hot);
2440                 return 0;
2441         }
2442         return 1;
2443 }
2444
2445 static unsigned long
2446 balance_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2447               unsigned long max_load_move, struct sched_domain *sd,
2448               enum cpu_idle_type idle, int *all_pinned,
2449               int *this_best_prio, struct rq_iterator *iterator)
2450 {
2451         int loops = 0, pulled = 0, pinned = 0, skip_for_load;
2452         struct task_struct *p;
2453         long rem_load_move = max_load_move;
2454
2455         if (max_load_move == 0)
2456                 goto out;
2457
2458         pinned = 1;
2459
2460         /*
2461          * Start the load-balancing iterator:
2462          */
2463         p = iterator->start(iterator->arg);
2464 next:
2465         if (!p || loops++ > sysctl_sched_nr_migrate)
2466                 goto out;
2467         /*
2468          * To help distribute high priority tasks across CPUs we don't
2469          * skip a task if it will be the highest priority task (i.e. smallest
2470          * prio value) on its new queue regardless of its load weight
2471          */
2472         skip_for_load = (p->se.load.weight >> 1) > rem_load_move +
2473                                                          SCHED_LOAD_SCALE_FUZZ;
2474         if ((skip_for_load && p->prio >= *this_best_prio) ||
2475             !can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
2476                 p = iterator->next(iterator->arg);
2477                 goto next;
2478         }
2479
2480         pull_task(busiest, p, this_rq, this_cpu);
2481         pulled++;
2482         rem_load_move -= p->se.load.weight;
2483
2484         /*
2485          * We only want to steal up to the prescribed amount of weighted load.
2486          */
2487         if (rem_load_move > 0) {
2488                 if (p->prio < *this_best_prio)
2489                         *this_best_prio = p->prio;
2490                 p = iterator->next(iterator->arg);
2491                 goto next;
2492         }
2493 out:
2494         /*
2495          * Right now, this is one of only two places pull_task() is called,
2496          * so we can safely collect pull_task() stats here rather than
2497          * inside pull_task().
2498          */
2499         schedstat_add(sd, lb_gained[idle], pulled);
2500
2501         if (all_pinned)
2502                 *all_pinned = pinned;
2503
2504         return max_load_move - rem_load_move;
2505 }
2506
2507 /*
2508  * move_tasks tries to move up to max_load_move weighted load from busiest to
2509  * this_rq, as part of a balancing operation within domain "sd".
2510  * Returns 1 if successful and 0 otherwise.
2511  *
2512  * Called with both runqueues locked.
2513  */
2514 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2515                       unsigned long max_load_move,
2516                       struct sched_domain *sd, enum cpu_idle_type idle,
2517                       int *all_pinned)
2518 {
2519         const struct sched_class *class = sched_class_highest;
2520         unsigned long total_load_moved = 0;
2521         int this_best_prio = this_rq->curr->prio;
2522
2523         do {
2524                 total_load_moved +=
2525                         class->load_balance(this_rq, this_cpu, busiest,
2526                                 max_load_move - total_load_moved,
2527                                 sd, idle, all_pinned, &this_best_prio);
2528                 class = class->next;
2529         } while (class && max_load_move > total_load_moved);
2530
2531         return total_load_moved > 0;
2532 }
2533
2534 static int
2535 iter_move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
2536                    struct sched_domain *sd, enum cpu_idle_type idle,
2537                    struct rq_iterator *iterator)
2538 {
2539         struct task_struct *p = iterator->start(iterator->arg);
2540         int pinned = 0;
2541
2542         while (p) {
2543                 if (can_migrate_task(p, busiest, this_cpu, sd, idle, &pinned)) {
2544                         pull_task(busiest, p, this_rq, this_cpu);
2545                         /*
2546                          * Right now, this is only the second place pull_task()
2547                          * is called, so we can safely collect pull_task()
2548                          * stats here rather than inside pull_task().
2549                          */
2550                         schedstat_inc(sd, lb_gained[idle]);
2551
2552                         return 1;
2553                 }
2554                 p = iterator->next(iterator->arg);
2555         }
2556
2557         return 0;
2558 }
2559
2560 /*
2561  * move_one_task tries to move exactly one task from busiest to this_rq, as
2562  * part of active balancing operations within "domain".
2563  * Returns 1 if successful and 0 otherwise.
2564  *
2565  * Called with both runqueues locked.
2566  */
2567 static int move_one_task(struct rq *this_rq, int this_cpu, struct rq *busiest,
2568                          struct sched_domain *sd, enum cpu_idle_type idle)
2569 {
2570         const struct sched_class *class;
2571
2572         for (class = sched_class_highest; class; class = class->next)
2573                 if (class->move_one_task(this_rq, this_cpu, busiest, sd, idle))
2574                         return 1;
2575
2576         return 0;
2577 }
2578
2579 /*
2580  * find_busiest_group finds and returns the busiest CPU group within the
2581  * domain. It calculates and returns the amount of weighted load which
2582  * should be moved to restore balance via the imbalance parameter.
2583  */
2584 static struct sched_group *
2585 find_busiest_group(struct sched_domain *sd, int this_cpu,
2586                    unsigned long *imbalance, enum cpu_idle_type idle,
2587                    int *sd_idle, cpumask_t *cpus, int *balance)
2588 {
2589         struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2590         unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2591         unsigned long max_pull;
2592         unsigned long busiest_load_per_task, busiest_nr_running;
2593         unsigned long this_load_per_task, this_nr_running;
2594         int load_idx, group_imb = 0;
2595 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2596         int power_savings_balance = 1;
2597         unsigned long leader_nr_running = 0, min_load_per_task = 0;
2598         unsigned long min_nr_running = ULONG_MAX;
2599         struct sched_group *group_min = NULL, *group_leader = NULL;
2600 #endif
2601
2602         max_load = this_load = total_load = total_pwr = 0;
2603         busiest_load_per_task = busiest_nr_running = 0;
2604         this_load_per_task = this_nr_running = 0;
2605         if (idle == CPU_NOT_IDLE)
2606                 load_idx = sd->busy_idx;
2607         else if (idle == CPU_NEWLY_IDLE)
2608                 load_idx = sd->newidle_idx;
2609         else
2610                 load_idx = sd->idle_idx;
2611
2612         do {
2613                 unsigned long load, group_capacity, max_cpu_load, min_cpu_load;
2614                 int local_group;
2615                 int i;
2616                 int __group_imb = 0;
2617                 unsigned int balance_cpu = -1, first_idle_cpu = 0;
2618                 unsigned long sum_nr_running, sum_weighted_load;
2619
2620                 local_group = cpu_isset(this_cpu, group->cpumask);
2621
2622                 if (local_group)
2623                         balance_cpu = first_cpu(group->cpumask);
2624
2625                 /* Tally up the load of all CPUs in the group */
2626                 sum_weighted_load = sum_nr_running = avg_load = 0;
2627                 max_cpu_load = 0;
2628                 min_cpu_load = ~0UL;
2629
2630                 for_each_cpu_mask(i, group->cpumask) {
2631                         struct rq *rq;
2632
2633                         if (!cpu_isset(i, *cpus))
2634                                 continue;
2635
2636                         rq = cpu_rq(i);
2637
2638                         if (*sd_idle && rq->nr_running)
2639                                 *sd_idle = 0;
2640
2641                         /* Bias balancing toward cpus of our domain */
2642                         if (local_group) {
2643                                 if (idle_cpu(i) && !first_idle_cpu) {
2644                                         first_idle_cpu = 1;
2645                                         balance_cpu = i;
2646                                 }
2647
2648                                 load = target_load(i, load_idx);
2649                         } else {
2650                                 load = source_load(i, load_idx);
2651                                 if (load > max_cpu_load)
2652                                         max_cpu_load = load;
2653                                 if (min_cpu_load > load)
2654                                         min_cpu_load = load;
2655                         }
2656
2657                         avg_load += load;
2658                         sum_nr_running += rq->nr_running;
2659                         sum_weighted_load += weighted_cpuload(i);
2660                 }
2661
2662                 /*
2663                  * First idle cpu or the first cpu(busiest) in this sched group
2664                  * is eligible for doing load balancing at this and above
2665                  * domains. In the newly idle case, we will allow all the cpu's
2666                  * to do the newly idle load balance.
2667                  */
2668                 if (idle != CPU_NEWLY_IDLE && local_group &&
2669                     balance_cpu != this_cpu && balance) {
2670                         *balance = 0;
2671                         goto ret;
2672                 }
2673
2674                 total_load += avg_load;
2675                 total_pwr += group->__cpu_power;
2676
2677                 /* Adjust by relative CPU power of the group */
2678                 avg_load = sg_div_cpu_power(group,
2679                                 avg_load * SCHED_LOAD_SCALE);
2680
2681                 if ((max_cpu_load - min_cpu_load) > SCHED_LOAD_SCALE)
2682                         __group_imb = 1;
2683
2684                 group_capacity = group->__cpu_power / SCHED_LOAD_SCALE;
2685
2686                 if (local_group) {
2687                         this_load = avg_load;
2688                         this = group;
2689                         this_nr_running = sum_nr_running;
2690                         this_load_per_task = sum_weighted_load;
2691                 } else if (avg_load > max_load &&
2692                            (sum_nr_running > group_capacity || __group_imb)) {
2693                         max_load = avg_load;
2694                         busiest = group;
2695                         busiest_nr_running = sum_nr_running;
2696                         busiest_load_per_task = sum_weighted_load;
2697                         group_imb = __group_imb;
2698                 }
2699
2700 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2701                 /*
2702                  * Busy processors will not participate in power savings
2703                  * balance.
2704                  */
2705                 if (idle == CPU_NOT_IDLE ||
2706                                 !(sd->flags & SD_POWERSAVINGS_BALANCE))
2707                         goto group_next;
2708
2709                 /*
2710                  * If the local group is idle or completely loaded
2711                  * no need to do power savings balance at this domain
2712                  */
2713                 if (local_group && (this_nr_running >= group_capacity ||
2714                                     !this_nr_running))
2715                         power_savings_balance = 0;
2716
2717                 /*
2718                  * If a group is already running at full capacity or idle,
2719                  * don't include that group in power savings calculations
2720                  */
2721                 if (!power_savings_balance || sum_nr_running >= group_capacity
2722                     || !sum_nr_running)
2723                         goto group_next;
2724
2725                 /*
2726                  * Calculate the group which has the least non-idle load.
2727                  * This is the group from where we need to pick up the load
2728                  * for saving power
2729                  */
2730                 if ((sum_nr_running < min_nr_running) ||
2731                     (sum_nr_running == min_nr_running &&
2732                      first_cpu(group->cpumask) <
2733                      first_cpu(group_min->cpumask))) {
2734                         group_min = group;
2735                         min_nr_running = sum_nr_running;
2736                         min_load_per_task = sum_weighted_load /
2737                                                 sum_nr_running;
2738                 }
2739
2740                 /*
2741                  * Calculate the group which is almost near its
2742                  * capacity but still has some space to pick up some load
2743                  * from other group and save more power
2744                  */
2745                 if (sum_nr_running <= group_capacity - 1) {
2746                         if (sum_nr_running > leader_nr_running ||
2747                             (sum_nr_running == leader_nr_running &&
2748                              first_cpu(group->cpumask) >
2749                               first_cpu(group_leader->cpumask))) {
2750                                 group_leader = group;
2751                                 leader_nr_running = sum_nr_running;
2752                         }
2753                 }
2754 group_next:
2755 #endif
2756                 group = group->next;
2757         } while (group != sd->groups);
2758
2759         if (!busiest || this_load >= max_load || busiest_nr_running == 0)
2760                 goto out_balanced;
2761
2762         avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2763
2764         if (this_load >= avg_load ||
2765                         100*max_load <= sd->imbalance_pct*this_load)
2766                 goto out_balanced;
2767
2768         busiest_load_per_task /= busiest_nr_running;
2769         if (group_imb)
2770                 busiest_load_per_task = min(busiest_load_per_task, avg_load);
2771
2772         /*
2773          * We're trying to get all the cpus to the average_load, so we don't
2774          * want to push ourselves above the average load, nor do we wish to
2775          * reduce the max loaded cpu below the average load, as either of these
2776          * actions would just result in more rebalancing later, and ping-pong
2777          * tasks around. Thus we look for the minimum possible imbalance.
2778          * Negative imbalances (*we* are more loaded than anyone else) will
2779          * be counted as no imbalance for these purposes -- we can't fix that
2780          * by pulling tasks to us. Be careful of negative numbers as they'll
2781          * appear as very large values with unsigned longs.
2782          */
2783         if (max_load <= busiest_load_per_task)
2784                 goto out_balanced;
2785
2786         /*
2787          * In the presence of smp nice balancing, certain scenarios can have
2788          * max load less than avg load(as we skip the groups at or below
2789          * its cpu_power, while calculating max_load..)
2790          */
2791         if (max_load < avg_load) {
2792                 *imbalance = 0;
2793                 goto small_imbalance;
2794         }
2795
2796         /* Don't want to pull so many tasks that a group would go idle */
2797         max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
2798
2799         /* How much load to actually move to equalise the imbalance */
2800         *imbalance = min(max_pull * busiest->__cpu_power,
2801                                 (avg_load - this_load) * this->__cpu_power)
2802                         / SCHED_LOAD_SCALE;
2803
2804         /*
2805          * if *imbalance is less than the average load per runnable task
2806          * there is no gaurantee that any tasks will be moved so we'll have
2807          * a think about bumping its value to force at least one task to be
2808          * moved
2809          */
2810         if (*imbalance < busiest_load_per_task) {
2811                 unsigned long tmp, pwr_now, pwr_move;
2812                 unsigned int imbn;
2813
2814 small_imbalance:
2815                 pwr_move = pwr_now = 0;
2816                 imbn = 2;
2817                 if (this_nr_running) {
2818                         this_load_per_task /= this_nr_running;
2819                         if (busiest_load_per_task > this_load_per_task)
2820                                 imbn = 1;
2821                 } else
2822                         this_load_per_task = SCHED_LOAD_SCALE;
2823
2824                 if (max_load - this_load + SCHED_LOAD_SCALE_FUZZ >=
2825                                         busiest_load_per_task * imbn) {
2826                         *imbalance = busiest_load_per_task;
2827                         return busiest;
2828                 }
2829
2830                 /*
2831                  * OK, we don't have enough imbalance to justify moving tasks,
2832                  * however we may be able to increase total CPU power used by
2833                  * moving them.
2834                  */
2835
2836                 pwr_now += busiest->__cpu_power *
2837                                 min(busiest_load_per_task, max_load);
2838                 pwr_now += this->__cpu_power *
2839                                 min(this_load_per_task, this_load);
2840                 pwr_now /= SCHED_LOAD_SCALE;
2841
2842                 /* Amount of load we'd subtract */
2843                 tmp = sg_div_cpu_power(busiest,
2844                                 busiest_load_per_task * SCHED_LOAD_SCALE);
2845                 if (max_load > tmp)
2846                         pwr_move += busiest->__cpu_power *
2847                                 min(busiest_load_per_task, max_load - tmp);
2848
2849                 /* Amount of load we'd add */
2850                 if (max_load * busiest->__cpu_power <
2851                                 busiest_load_per_task * SCHED_LOAD_SCALE)
2852                         tmp = sg_div_cpu_power(this,
2853                                         max_load * busiest->__cpu_power);
2854                 else
2855                         tmp = sg_div_cpu_power(this,
2856                                 busiest_load_per_task * SCHED_LOAD_SCALE);
2857                 pwr_move += this->__cpu_power *
2858                                 min(this_load_per_task, this_load + tmp);
2859                 pwr_move /= SCHED_LOAD_SCALE;
2860
2861                 /* Move if we gain throughput */
2862                 if (pwr_move > pwr_now)
2863                         *imbalance = busiest_load_per_task;
2864         }
2865
2866         return busiest;
2867
2868 out_balanced:
2869 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2870         if (idle == CPU_NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
2871                 goto ret;
2872
2873         if (this == group_leader && group_leader != group_min) {
2874                 *imbalance = min_load_per_task;
2875                 return group_min;
2876         }
2877 #endif
2878 ret:
2879         *imbalance = 0;
2880         return NULL;
2881 }
2882
2883 /*
2884  * find_busiest_queue - find the busiest runqueue among the cpus in group.
2885  */
2886 static struct rq *
2887 find_busiest_queue(struct sched_group *group, enum cpu_idle_type idle,
2888                    unsigned long imbalance, cpumask_t *cpus)
2889 {
2890         struct rq *busiest = NULL, *rq;
2891         unsigned long max_load = 0;
2892         int i;
2893
2894         for_each_cpu_mask(i, group->cpumask) {
2895                 unsigned long wl;
2896
2897                 if (!cpu_isset(i, *cpus))
2898                         continue;
2899
2900                 rq = cpu_rq(i);
2901                 wl = weighted_cpuload(i);
2902
2903                 if (rq->nr_running == 1 && wl > imbalance)
2904                         continue;
2905
2906                 if (wl > max_load) {
2907                         max_load = wl;
2908                         busiest = rq;
2909                 }
2910         }
2911
2912         return busiest;
2913 }
2914
2915 /*
2916  * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2917  * so long as it is large enough.
2918  */
2919 #define MAX_PINNED_INTERVAL     512
2920
2921 /*
2922  * Check this_cpu to ensure it is balanced within domain. Attempt to move
2923  * tasks if there is an imbalance.
2924  */
2925 static int load_balance(int this_cpu, struct rq *this_rq,
2926                         struct sched_domain *sd, enum cpu_idle_type idle,
2927                         int *balance)
2928 {
2929         int ld_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
2930         struct sched_group *group;
2931         unsigned long imbalance;
2932         struct rq *busiest;
2933         cpumask_t cpus = CPU_MASK_ALL;
2934         unsigned long flags;
2935
2936         /*
2937          * When power savings policy is enabled for the parent domain, idle
2938          * sibling can pick up load irrespective of busy siblings. In this case,
2939          * let the state of idle sibling percolate up as CPU_IDLE, instead of
2940          * portraying it as CPU_NOT_IDLE.
2941          */
2942         if (idle != CPU_NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
2943             !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2944                 sd_idle = 1;
2945
2946         schedstat_inc(sd, lb_count[idle]);
2947
2948 redo:
2949         group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
2950                                    &cpus, balance);
2951
2952         if (*balance == 0)
2953                 goto out_balanced;
2954
2955         if (!group) {
2956                 schedstat_inc(sd, lb_nobusyg[idle]);
2957                 goto out_balanced;
2958         }
2959
2960         busiest = find_busiest_queue(group, idle, imbalance, &cpus);
2961         if (!busiest) {
2962                 schedstat_inc(sd, lb_nobusyq[idle]);
2963                 goto out_balanced;
2964         }
2965
2966         BUG_ON(busiest == this_rq);
2967
2968         schedstat_add(sd, lb_imbalance[idle], imbalance);
2969
2970         ld_moved = 0;
2971         if (busiest->nr_running > 1) {
2972                 /*
2973                  * Attempt to move tasks. If find_busiest_group has found
2974                  * an imbalance but busiest->nr_running <= 1, the group is
2975                  * still unbalanced. ld_moved simply stays zero, so it is
2976                  * correctly treated as an imbalance.
2977                  */
2978                 local_irq_save(flags);
2979                 double_rq_lock(this_rq, busiest);
2980                 ld_moved = move_tasks(this_rq, this_cpu, busiest,
2981                                       imbalance, sd, idle, &all_pinned);
2982                 double_rq_unlock(this_rq, busiest);
2983                 local_irq_restore(flags);
2984
2985                 /*
2986                  * some other cpu did the load balance for us.
2987                  */
2988                 if (ld_moved && this_cpu != smp_processor_id())
2989                         resched_cpu(this_cpu);
2990
2991                 /* All tasks on this runqueue were pinned by CPU affinity */
2992                 if (unlikely(all_pinned)) {
2993                         cpu_clear(cpu_of(busiest), cpus);
2994                         if (!cpus_empty(cpus))
2995                                 goto redo;
2996                         goto out_balanced;
2997                 }
2998         }
2999
3000         if (!ld_moved) {
3001                 schedstat_inc(sd, lb_failed[idle]);
3002                 sd->nr_balance_failed++;
3003
3004                 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
3005
3006                         spin_lock_irqsave(&busiest->lock, flags);
3007
3008                         /* don't kick the migration_thread, if the curr
3009                          * task on busiest cpu can't be moved to this_cpu
3010                          */
3011                         if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
3012                                 spin_unlock_irqrestore(&busiest->lock, flags);
3013                                 all_pinned = 1;
3014                                 goto out_one_pinned;
3015                         }
3016
3017                         if (!busiest->active_balance) {
3018                                 busiest->active_balance = 1;
3019                                 busiest->push_cpu = this_cpu;
3020                                 active_balance = 1;
3021                         }
3022                         spin_unlock_irqrestore(&busiest->lock, flags);
3023                         if (active_balance)
3024                                 wake_up_process(busiest->migration_thread);
3025
3026                         /*
3027                          * We've kicked active balancing, reset the failure
3028                          * counter.
3029                          */
3030                         sd->nr_balance_failed = sd->cache_nice_tries+1;
3031                 }
3032         } else
3033                 sd->nr_balance_failed = 0;
3034
3035         if (likely(!active_balance)) {
3036                 /* We were unbalanced, so reset the balancing interval */
3037                 sd->balance_interval = sd->min_interval;
3038         } else {
3039                 /*
3040                  * If we've begun active balancing, start to back off. This
3041                  * case may not be covered by the all_pinned logic if there
3042                  * is only 1 task on the busy runqueue (because we don't call
3043                  * move_tasks).
3044                  */
3045                 if (sd->balance_interval < sd->max_interval)
3046                         sd->balance_interval *= 2;
3047         }
3048
3049         if (!ld_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3050             !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3051                 return -1;
3052         return ld_moved;
3053
3054 out_balanced:
3055         schedstat_inc(sd, lb_balanced[idle]);
3056
3057         sd->nr_balance_failed = 0;
3058
3059 out_one_pinned:
3060         /* tune up the balancing interval */
3061         if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
3062                         (sd->balance_interval < sd->max_interval))
3063                 sd->balance_interval *= 2;
3064
3065         if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3066             !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3067                 return -1;
3068         return 0;
3069 }
3070
3071 /*
3072  * Check this_cpu to ensure it is balanced within domain. Attempt to move
3073  * tasks if there is an imbalance.
3074  *
3075  * Called from schedule when this_rq is about to become idle (CPU_NEWLY_IDLE).
3076  * this_rq is locked.
3077  */
3078 static int
3079 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
3080 {
3081         struct sched_group *group;
3082         struct rq *busiest = NULL;
3083         unsigned long imbalance;
3084         int ld_moved = 0;
3085         int sd_idle = 0;
3086         int all_pinned = 0;
3087         cpumask_t cpus = CPU_MASK_ALL;
3088
3089         /*
3090          * When power savings policy is enabled for the parent domain, idle
3091          * sibling can pick up load irrespective of busy siblings. In this case,
3092          * let the state of idle sibling percolate up as IDLE, instead of
3093          * portraying it as CPU_NOT_IDLE.
3094          */
3095         if (sd->flags & SD_SHARE_CPUPOWER &&
3096             !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3097                 sd_idle = 1;
3098
3099         schedstat_inc(sd, lb_count[CPU_NEWLY_IDLE]);
3100 redo:
3101         group = find_busiest_group(sd, this_cpu, &imbalance, CPU_NEWLY_IDLE,
3102                                    &sd_idle, &cpus, NULL);
3103         if (!group) {
3104                 schedstat_inc(sd, lb_nobusyg[CPU_NEWLY_IDLE]);
3105                 goto out_balanced;
3106         }
3107
3108         busiest = find_busiest_queue(group, CPU_NEWLY_IDLE, imbalance,
3109                                 &cpus);
3110         if (!busiest) {
3111                 schedstat_inc(sd, lb_nobusyq[CPU_NEWLY_IDLE]);
3112                 goto out_balanced;
3113         }
3114
3115         BUG_ON(busiest == this_rq);
3116
3117         schedstat_add(sd, lb_imbalance[CPU_NEWLY_IDLE], imbalance);
3118
3119         ld_moved = 0;
3120         if (busiest->nr_running > 1) {
3121                 /* Attempt to move tasks */
3122                 double_lock_balance(this_rq, busiest);
3123                 /* this_rq->clock is already updated */
3124                 update_rq_clock(busiest);
3125                 ld_moved = move_tasks(this_rq, this_cpu, busiest,
3126                                         imbalance, sd, CPU_NEWLY_IDLE,
3127                                         &all_pinned);
3128                 spin_unlock(&busiest->lock);
3129
3130                 if (unlikely(all_pinned)) {
3131                         cpu_clear(cpu_of(busiest), cpus);
3132                         if (!cpus_empty(cpus))
3133                                 goto redo;
3134                 }
3135         }
3136
3137         if (!ld_moved) {
3138                 schedstat_inc(sd, lb_failed[CPU_NEWLY_IDLE]);
3139                 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3140                     !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3141                         return -1;
3142         } else
3143                 sd->nr_balance_failed = 0;
3144
3145         return ld_moved;
3146
3147 out_balanced:
3148         schedstat_inc(sd, lb_balanced[CPU_NEWLY_IDLE]);
3149         if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
3150             !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
3151                 return -1;
3152         sd->nr_balance_failed = 0;
3153
3154         return 0;
3155 }
3156
3157 /*
3158  * idle_balance is called by schedule() if this_cpu is about to become
3159  * idle. Attempts to pull tasks from other CPUs.
3160  */
3161 static void idle_balance(int this_cpu, struct rq *this_rq)
3162 {
3163         struct sched_domain *sd;
3164         int pulled_task = -1;
3165         unsigned long next_balance = jiffies + HZ;
3166
3167         for_each_domain(this_cpu, sd) {
3168                 unsigned long interval;
3169
3170                 if (!(sd->flags & SD_LOAD_BALANCE))
3171                         continue;
3172
3173                 if (sd->flags & SD_BALANCE_NEWIDLE)
3174                         /* If we've pulled tasks over stop searching: */
3175                         pulled_task = load_balance_newidle(this_cpu,
3176                                                                 this_rq, sd);
3177
3178                 interval = msecs_to_jiffies(sd->balance_interval);
3179                 if (time_after(next_balance, sd->last_balance + interval))
3180                         next_balance = sd->last_balance + interval;
3181                 if (pulled_task)
3182                         break;
3183         }
3184         if (pulled_task || time_after(jiffies, this_rq->next_balance)) {
3185                 /*
3186                  * We are going idle. next_balance may be set based on
3187                  * a busy processor. So reset next_balance.
3188                  */
3189                 this_rq->next_balance = next_balance;
3190         }
3191 }
3192
3193 /*
3194  * active_load_balance is run by migration threads. It pushes running tasks
3195  * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
3196  * running on each physical CPU where possible, and avoids physical /
3197  * logical imbalances.
3198  *
3199  * Called with busiest_rq locked.
3200  */
3201 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
3202 {
3203         int target_cpu = busiest_rq->push_cpu;
3204         struct sched_domain *sd;
3205         struct rq *target_rq;
3206
3207         /* Is there any task to move? */
3208         if (busiest_rq->nr_running <= 1)
3209                 return;
3210
3211         target_rq = cpu_rq(target_cpu);
3212
3213         /*
3214          * This condition is "impossible", if it occurs
3215          * we need to fix it. Originally reported by
3216          * Bjorn Helgaas on a 128-cpu setup.
3217          */
3218         BUG_ON(busiest_rq == target_rq);
3219
3220         /* move a task from busiest_rq to target_rq */
3221         double_lock_balance(busiest_rq, target_rq);
3222         update_rq_clock(busiest_rq);
3223         update_rq_clock(target_rq);
3224
3225         /* Search for an sd spanning us and the target CPU. */
3226         for_each_domain(target_cpu, sd) {
3227                 if ((sd->flags & SD_LOAD_BALANCE) &&
3228                     cpu_isset(busiest_cpu, sd->span))
3229                                 break;
3230         }
3231
3232         if (likely(sd)) {
3233                 schedstat_inc(sd, alb_count);
3234
3235                 if (move_one_task(target_rq, target_cpu, busiest_rq,
3236                                   sd, CPU_IDLE))
3237                         schedstat_inc(sd, alb_pushed);
3238                 else
3239                         schedstat_inc(sd, alb_failed);
3240         }
3241         spin_unlock(&target_rq->lock);
3242 }
3243
3244 #ifdef CONFIG_NO_HZ
3245 static struct {
3246         atomic_t load_balancer;
3247         cpumask_t cpu_mask;
3248 } nohz ____cacheline_aligned = {
3249         .load_balancer = ATOMIC_INIT(-1),
3250         .cpu_mask = CPU_MASK_NONE,
3251 };
3252
3253 /*
3254  * This routine will try to nominate the ilb (idle load balancing)
3255  * owner among the cpus whose ticks are stopped. ilb owner will do the idle
3256  * load balancing on behalf of all those cpus. If all the cpus in the system
3257  * go into this tickless mode, then there will be no ilb owner (as there is
3258  * no need for one) and all the cpus will sleep till the next wakeup event
3259  * arrives...
3260  *
3261  * For the ilb owner, tick is not stopped. And this tick will be used
3262  * for idle load balancing. ilb owner will still be part of
3263  * nohz.cpu_mask..
3264  *
3265  * While stopping the tick, this cpu will become the ilb owner if there
3266  * is no other owner. And will be the owner till that cpu becomes busy
3267  * or if all cpus in the system stop their ticks at which point
3268  * there is no need for ilb owner.
3269  *
3270  * When the ilb owner becomes busy, it nominates another owner, during the
3271  * next busy scheduler_tick()
3272  */
3273 int select_nohz_load_balancer(int stop_tick)
3274 {
3275         int cpu = smp_processor_id();
3276
3277         if (stop_tick) {
3278                 cpu_set(cpu, nohz.cpu_mask);
3279                 cpu_rq(cpu)->in_nohz_recently = 1;
3280
3281                 /*
3282                  * If we are going offline and still the leader, give up!
3283                  */
3284                 if (cpu_is_offline(cpu) &&
3285                     atomic_read(&nohz.load_balancer) == cpu) {
3286                         if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3287                                 BUG();
3288                         return 0;
3289                 }
3290
3291                 /* time for ilb owner also to sleep */
3292                 if (cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3293                         if (atomic_read(&nohz.load_balancer) == cpu)
3294                                 atomic_set(&nohz.load_balancer, -1);
3295                         return 0;
3296                 }
3297
3298                 if (atomic_read(&nohz.load_balancer) == -1) {
3299                         /* make me the ilb owner */
3300                         if (atomic_cmpxchg(&nohz.load_balancer, -1, cpu) == -1)
3301                                 return 1;
3302                 } else if (atomic_read(&nohz.load_balancer) == cpu)
3303                         return 1;
3304         } else {
3305                 if (!cpu_isset(cpu, nohz.cpu_mask))
3306                         return 0;
3307
3308                 cpu_clear(cpu, nohz.cpu_mask);
3309
3310                 if (atomic_read(&nohz.load_balancer) == cpu)
3311                         if (atomic_cmpxchg(&nohz.load_balancer, cpu, -1) != cpu)
3312                                 BUG();
3313         }
3314         return 0;
3315 }
3316 #endif
3317
3318 static DEFINE_SPINLOCK(balancing);
3319
3320 /*
3321  * It checks each scheduling domain to see if it is due to be balanced,
3322  * and initiates a balancing operation if so.
3323  *
3324  * Balancing parameters are set up in arch_init_sched_domains.
3325  */
3326 static void rebalance_domains(int cpu, enum cpu_idle_type idle)
3327 {
3328         int balance = 1;
3329         struct rq *rq = cpu_rq(cpu);
3330         unsigned long interval;
3331         struct sched_domain *sd;
3332         /* Earliest time when we have to do rebalance again */
3333         unsigned long next_balance = jiffies + 60*HZ;
3334         int update_next_balance = 0;
3335
3336         for_each_domain(cpu, sd) {
3337                 if (!(sd->flags & SD_LOAD_BALANCE))
3338                         continue;
3339
3340                 interval = sd->balance_interval;
3341                 if (idle != CPU_IDLE)
3342                         interval *= sd->busy_factor;
3343
3344                 /* scale ms to jiffies */
3345                 interval = msecs_to_jiffies(interval);
3346                 if (unlikely(!interval))
3347                         interval = 1;
3348                 if (interval > HZ*NR_CPUS/10)
3349                         interval = HZ*NR_CPUS/10;
3350
3351
3352                 if (sd->flags & SD_SERIALIZE) {
3353                         if (!spin_trylock(&balancing))
3354                                 goto out;
3355                 }
3356
3357                 if (time_after_eq(jiffies, sd->last_balance + interval)) {
3358                         if (load_balance(cpu, rq, sd, idle, &balance)) {
3359                                 /*
3360                                  * We've pulled tasks over so either we're no
3361                                  * longer idle, or one of our SMT siblings is
3362                                  * not idle.
3363                                  */
3364                                 idle = CPU_NOT_IDLE;
3365                         }
3366                         sd->last_balance = jiffies;
3367                 }
3368                 if (sd->flags & SD_SERIALIZE)
3369                         spin_unlock(&balancing);
3370 out:
3371                 if (time_after(next_balance, sd->last_balance + interval)) {
3372                         next_balance = sd->last_balance + interval;
3373                         update_next_balance = 1;
3374                 }
3375
3376                 /*
3377                  * Stop the load balance at this level. There is another
3378                  * CPU in our sched group which is doing load balancing more
3379                  * actively.
3380                  */
3381                 if (!balance)
3382                         break;
3383         }
3384
3385         /*
3386          * next_balance will be updated only when there is a need.
3387          * When the cpu is attached to null domain for ex, it will not be
3388          * updated.
3389          */
3390         if (likely(update_next_balance))
3391                 rq->next_balance = next_balance;
3392 }
3393
3394 /*
3395  * run_rebalance_domains is triggered when needed from the scheduler tick.
3396  * In CONFIG_NO_HZ case, the idle load balance owner will do the
3397  * rebalancing for all the cpus for whom scheduler ticks are stopped.
3398  */
3399 static void run_rebalance_domains(struct softirq_action *h)
3400 {
3401         int this_cpu = smp_processor_id();
3402         struct rq *this_rq = cpu_rq(this_cpu);
3403         enum cpu_idle_type idle = this_rq->idle_at_tick ?
3404                                                 CPU_IDLE : CPU_NOT_IDLE;
3405
3406         rebalance_domains(this_cpu, idle);
3407
3408 #ifdef CONFIG_NO_HZ
3409         /*
3410          * If this cpu is the owner for idle load balancing, then do the
3411          * balancing on behalf of the other idle cpus whose ticks are
3412          * stopped.
3413          */
3414         if (this_rq->idle_at_tick &&
3415             atomic_read(&nohz.load_balancer) == this_cpu) {
3416                 cpumask_t cpus = nohz.cpu_mask;
3417                 struct rq *rq;
3418                 int balance_cpu;
3419
3420                 cpu_clear(this_cpu, cpus);
3421                 for_each_cpu_mask(balance_cpu, cpus) {
3422                         /*
3423                          * If this cpu gets work to do, stop the load balancing
3424                          * work being done for other cpus. Next load
3425                          * balancing owner will pick it up.
3426                          */
3427                         if (need_resched())
3428                                 break;
3429
3430                         rebalance_domains(balance_cpu, CPU_IDLE);
3431
3432                         rq = cpu_rq(balance_cpu);
3433                         if (time_after(this_rq->next_balance, rq->next_balance))
3434                                 this_rq->next_balance = rq->next_balance;
3435                 }
3436         }
3437 #endif
3438 }
3439
3440 /*
3441  * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing.
3442  *
3443  * In case of CONFIG_NO_HZ, this is the place where we nominate a new
3444  * idle load balancing owner or decide to stop the periodic load balancing,
3445  * if the whole system is idle.
3446  */
3447 static inline void trigger_load_balance(struct rq *rq, int cpu)
3448 {
3449 #ifdef CONFIG_NO_HZ
3450         /*
3451          * If we were in the nohz mode recently and busy at the current
3452          * scheduler tick, then check if we need to nominate new idle
3453          * load balancer.
3454          */
3455         if (rq->in_nohz_recently && !rq->idle_at_tick) {
3456                 rq->in_nohz_recently = 0;
3457
3458                 if (atomic_read(&nohz.load_balancer) == cpu) {
3459                         cpu_clear(cpu, nohz.cpu_mask);
3460                         atomic_set(&nohz.load_balancer, -1);
3461                 }
3462
3463                 if (atomic_read(&nohz.load_balancer) == -1) {
3464                         /*
3465                          * simple selection for now: Nominate the
3466                          * first cpu in the nohz list to be the next
3467                          * ilb owner.
3468                          *
3469                          * TBD: Traverse the sched domains and nominate
3470                          * the nearest cpu in the nohz.cpu_mask.
3471                          */
3472                         int ilb = first_cpu(nohz.cpu_mask);
3473
3474                         if (ilb != NR_CPUS)
3475                                 resched_cpu(ilb);
3476                 }
3477         }
3478
3479         /*
3480          * If this cpu is idle and doing idle load balancing for all the
3481          * cpus with ticks stopped, is it time for that to stop?
3482          */
3483         if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) == cpu &&
3484             cpus_weight(nohz.cpu_mask) == num_online_cpus()) {
3485                 resched_cpu(cpu);
3486                 return;
3487         }
3488
3489         /*
3490          * If this cpu is idle and the idle load balancing is done by
3491          * someone else, then no need raise the SCHED_SOFTIRQ
3492          */
3493         if (rq->idle_at_tick && atomic_read(&nohz.load_balancer) != cpu &&
3494             cpu_isset(cpu, nohz.cpu_mask))
3495                 return;
3496 #endif
3497         if (time_after_eq(jiffies, rq->next_balance))
3498                 raise_softirq(SCHED_SOFTIRQ);
3499 }
3500
3501 #else   /* CONFIG_SMP */
3502
3503 /*
3504  * on UP we do not need to balance between CPUs:
3505  */
3506 static inline void idle_balance(int cpu, struct rq *rq)
3507 {
3508 }
3509
3510 #endif
3511
3512 DEFINE_PER_CPU(struct kernel_stat, kstat);
3513
3514 EXPORT_PER_CPU_SYMBOL(kstat);
3515
3516 /*
3517  * Return p->sum_exec_runtime plus any more ns on the sched_clock
3518  * that have not yet been banked in case the task is currently running.
3519  */
3520 unsigned long long task_sched_runtime(struct task_struct *p)
3521 {
3522         unsigned long flags;
3523         u64 ns, delta_exec;
3524         struct rq *rq;
3525
3526         rq = task_rq_lock(p, &flags);
3527         ns = p->se.sum_exec_runtime;
3528         if (task_current(rq, p)) {
3529                 update_rq_clock(rq);
3530                 delta_exec = rq->clock - p->se.exec_start;
3531                 if ((s64)delta_exec > 0)
3532                         ns += delta_exec;
3533         }
3534         task_rq_unlock(rq, &flags);
3535
3536         return ns;
3537 }
3538
3539 /*
3540  * Account user cpu time to a process.
3541  * @p: the process that the cpu time gets accounted to
3542  * @cputime: the cpu time spent in user space since the last update
3543  */
3544 void account_user_time(struct task_struct *p, cputime_t cputime)
3545 {
3546         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3547         cputime64_t tmp;
3548
3549         p->utime = cputime_add(p->utime, cputime);
3550
3551         /* Add user time to cpustat. */
3552         tmp = cputime_to_cputime64(cputime);
3553         if (TASK_NICE(p) > 0)
3554                 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3555         else
3556                 cpustat->user = cputime64_add(cpustat->user, tmp);
3557 }
3558
3559 /*
3560  * Account guest cpu time to a process.
3561  * @p: the process that the cpu time gets accounted to
3562  * @cputime: the cpu time spent in virtual machine since the last update
3563  */
3564 static void account_guest_time(struct task_struct *p, cputime_t cputime)
3565 {
3566         cputime64_t tmp;
3567         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3568
3569         tmp = cputime_to_cputime64(cputime);
3570
3571         p->utime = cputime_add(p->utime, cputime);
3572         p->gtime = cputime_add(p->gtime, cputime);
3573
3574         cpustat->user = cputime64_add(cpustat->user, tmp);
3575         cpustat->guest = cputime64_add(cpustat->guest, tmp);
3576 }
3577
3578 /*
3579  * Account scaled user cpu time to a process.
3580  * @p: the process that the cpu time gets accounted to
3581  * @cputime: the cpu time spent in user space since the last update
3582  */
3583 void account_user_time_scaled(struct task_struct *p, cputime_t cputime)
3584 {
3585         p->utimescaled = cputime_add(p->utimescaled, cputime);
3586 }
3587
3588 /*
3589  * Account system cpu time to a process.
3590  * @p: the process that the cpu time gets accounted to
3591  * @hardirq_offset: the offset to subtract from hardirq_count()
3592  * @cputime: the cpu time spent in kernel space since the last update
3593  */
3594 void account_system_time(struct task_struct *p, int hardirq_offset,
3595                          cputime_t cputime)
3596 {
3597         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3598         struct rq *rq = this_rq();
3599         cputime64_t tmp;
3600
3601         if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0))
3602                 return account_guest_time(p, cputime);
3603
3604         p->stime = cputime_add(p->stime, cputime);
3605
3606         /* Add system time to cpustat. */
3607         tmp = cputime_to_cputime64(cputime);
3608         if (hardirq_count() - hardirq_offset)
3609                 cpustat->irq = cputime64_add(cpustat->irq, tmp);
3610         else if (softirq_count())
3611                 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
3612         else if (p != rq->idle)
3613                 cpustat->system = cputime64_add(cpustat->system, tmp);
3614         else if (atomic_read(&rq->nr_iowait) > 0)
3615                 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3616         else
3617                 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3618         /* Account for system time used */
3619         acct_update_integrals(p);
3620 }
3621
3622 /*
3623  * Account scaled system cpu time to a process.
3624  * @p: the process that the cpu time gets accounted to
3625  * @hardirq_offset: the offset to subtract from hardirq_count()
3626  * @cputime: the cpu time spent in kernel space since the last update
3627  */
3628 void account_system_time_scaled(struct task_struct *p, cputime_t cputime)
3629 {
3630         p->stimescaled = cputime_add(p->stimescaled, cputime);
3631 }
3632
3633 /*
3634  * Account for involuntary wait time.
3635  * @p: the process from which the cpu time has been stolen
3636  * @steal: the cpu time spent in involuntary wait
3637  */
3638 void account_steal_time(struct task_struct *p, cputime_t steal)
3639 {
3640         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3641         cputime64_t tmp = cputime_to_cputime64(steal);
3642         struct rq *rq = this_rq();
3643
3644         if (p == rq->idle) {
3645                 p->stime = cputime_add(p->stime, steal);
3646                 if (atomic_read(&rq->nr_iowait) > 0)
3647                         cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3648                 else
3649                         cpustat->idle = cputime64_add(cpustat->idle, tmp);
3650         } else
3651                 cpustat->steal = cputime64_add(cpustat->steal, tmp);
3652 }
3653
3654 /*
3655  * This function gets called by the timer code, with HZ frequency.
3656  * We call it with interrupts disabled.
3657  *
3658  * It also gets called by the fork code, when changing the parent's
3659  * timeslices.
3660  */
3661 void scheduler_tick(void)
3662 {
3663         int cpu = smp_processor_id();
3664         struct rq *rq = cpu_rq(cpu);
3665         struct task_struct *curr = rq->curr;
3666         u64 next_tick = rq->tick_timestamp + TICK_NSEC;
3667
3668         spin_lock(&rq->lock);
3669         __update_rq_clock(rq);
3670         /*
3671          * Let rq->clock advance by at least TICK_NSEC:
3672          */
3673         if (unlikely(rq->clock < next_tick))
3674                 rq->clock = next_tick;
3675         rq->tick_timestamp = rq->clock;
3676         update_cpu_load(rq);
3677         if (curr != rq->idle) /* FIXME: needed? */
3678                 curr->sched_class->task_tick(rq, curr, 0);
3679         spin_unlock(&rq->lock);
3680
3681 #ifdef CONFIG_SMP
3682         rq->idle_at_tick = idle_cpu(cpu);
3683         trigger_load_balance(rq, cpu);
3684 #endif
3685 }
3686
3687 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3688
3689 void fastcall add_preempt_count(int val)
3690 {
3691         /*
3692          * Underflow?
3693          */
3694         if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3695                 return;
3696         preempt_count() += val;
3697         /*
3698          * Spinlock count overflowing soon?
3699          */
3700         DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3701                                 PREEMPT_MASK - 10);
3702 }
3703 EXPORT_SYMBOL(add_preempt_count);
3704
3705 void fastcall sub_preempt_count(int val)
3706 {
3707         /*
3708          * Underflow?
3709          */
3710         if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3711                 return;
3712         /*
3713          * Is the spinlock portion underflowing?
3714          */
3715         if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3716                         !(preempt_count() & PREEMPT_MASK)))
3717                 return;
3718
3719         preempt_count() -= val;
3720 }
3721 EXPORT_SYMBOL(sub_preempt_count);
3722
3723 #endif
3724
3725 /*
3726  * Print scheduling while atomic bug:
3727  */
3728 static noinline void __schedule_bug(struct task_struct *prev)
3729 {
3730         struct pt_regs *regs = get_irq_regs();
3731
3732         printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3733                 prev->comm, prev->pid, preempt_count());
3734
3735         debug_show_held_locks(prev);
3736         if (irqs_disabled())
3737                 print_irqtrace_events(prev);
3738
3739         if (regs)
3740                 show_regs(regs);
3741         else
3742                 dump_stack();
3743 }
3744
3745 /*
3746  * Various schedule()-time debugging checks and statistics:
3747  */
3748 static inline void schedule_debug(struct task_struct *prev)
3749 {
3750         /*
3751          * Test if we are atomic. Since do_exit() needs to call into
3752          * schedule() atomically, we ignore that path for now.
3753          * Otherwise, whine if we are scheduling when we should not be.
3754          */
3755         if (unlikely(in_atomic_preempt_off()) && unlikely(!prev->exit_state))
3756                 __schedule_bug(prev);
3757
3758         profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3759
3760         schedstat_inc(this_rq(), sched_count);
3761 #ifdef CONFIG_SCHEDSTATS
3762         if (unlikely(prev->lock_depth >= 0)) {
3763                 schedstat_inc(this_rq(), bkl_count);
3764                 schedstat_inc(prev, sched_info.bkl_count);
3765         }
3766 #endif
3767 }
3768
3769 /*
3770  * Pick up the highest-prio task:
3771  */
3772 static inline struct task_struct *
3773 pick_next_task(struct rq *rq, struct task_struct *prev)
3774 {
3775         const struct sched_class *class;
3776         struct task_struct *p;
3777
3778         /*
3779          * Optimization: we know that if all tasks are in
3780          * the fair class we can call that function directly:
3781          */
3782         if (likely(rq->nr_running == rq->cfs.nr_running)) {
3783                 p = fair_sched_class.pick_next_task(rq);
3784                 if (likely(p))
3785                         return p;
3786         }
3787
3788         class = sched_class_highest;
3789         for ( ; ; ) {
3790                 p = class->pick_next_task(rq);
3791                 if (p)
3792                         return p;
3793                 /*
3794                  * Will never be NULL as the idle class always
3795                  * returns a non-NULL p:
3796                  */
3797                 class = class->next;
3798         }
3799 }
3800
3801 /*
3802  * schedule() is the main scheduler function.
3803  */
3804 asmlinkage void __sched schedule(void)
3805 {
3806         struct task_struct *prev, *next;
3807         long *switch_count;
3808         struct rq *rq;
3809         int cpu;
3810
3811 need_resched:
3812         preempt_disable();
3813         cpu = smp_processor_id();
3814         rq = cpu_rq(cpu);
3815         rcu_qsctr_inc(cpu);
3816         prev = rq->curr;
3817         switch_count = &prev->nivcsw;
3818
3819         release_kernel_lock(prev);
3820 need_resched_nonpreemptible:
3821
3822         schedule_debug(prev);
3823
3824         hrtick_clear(rq);
3825
3826         /*
3827          * Do the rq-clock update outside the rq lock:
3828          */
3829         local_irq_disable();
3830         __update_rq_clock(rq);
3831         spin_lock(&rq->lock);
3832         clear_tsk_need_resched(prev);
3833
3834         if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3835                 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
3836                                 unlikely(signal_pending(prev)))) {
3837                         prev->state = TASK_RUNNING;
3838                 } else {
3839                         deactivate_task(rq, prev, 1);
3840                 }
3841                 switch_count = &prev->nvcsw;
3842         }
3843
3844 #ifdef CONFIG_SMP
3845         if (prev->sched_class->pre_schedule)
3846                 prev->sched_class->pre_schedule(rq, prev);
3847 #endif
3848
3849         if (unlikely(!rq->nr_running))
3850                 idle_balance(cpu, rq);
3851
3852         prev->sched_class->put_prev_task(rq, prev);
3853         next = pick_next_task(rq, prev);
3854
3855         sched_info_switch(prev, next);
3856
3857         if (likely(prev != next)) {
3858                 rq->nr_switches++;
3859                 rq->curr = next;
3860                 ++*switch_count;
3861
3862                 context_switch(rq, prev, next); /* unlocks the rq */
3863                 /*
3864                  * the context switch might have flipped the stack from under
3865                  * us, hence refresh the local variables.
3866                  */
3867                 cpu = smp_processor_id();
3868                 rq = cpu_rq(cpu);
3869         } else
3870                 spin_unlock_irq(&rq->lock);
3871
3872         hrtick_set(rq);
3873
3874         if (unlikely(reacquire_kernel_lock(current) < 0))
3875                 goto need_resched_nonpreemptible;
3876
3877         preempt_enable_no_resched();
3878         if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3879                 goto need_resched;
3880 }
3881 EXPORT_SYMBOL(schedule);
3882
3883 #ifdef CONFIG_PREEMPT
3884 /*
3885  * this is the entry point to schedule() from in-kernel preemption
3886  * off of preempt_enable. Kernel preemptions off return from interrupt
3887  * occur there and call schedule directly.
3888  */
3889 asmlinkage void __sched preempt_schedule(void)
3890 {
3891         struct thread_info *ti = current_thread_info();
3892 #ifdef CONFIG_PREEMPT_BKL
3893         struct task_struct *task = current;
3894         int saved_lock_depth;
3895 #endif
3896         /*
3897          * If there is a non-zero preempt_count or interrupts are disabled,
3898          * we do not want to preempt the current task. Just return..
3899          */
3900         if (likely(ti->preempt_count || irqs_disabled()))
3901                 return;
3902
3903         do {
3904                 add_preempt_count(PREEMPT_ACTIVE);
3905
3906                 /*
3907                  * We keep the big kernel semaphore locked, but we
3908                  * clear ->lock_depth so that schedule() doesnt
3909                  * auto-release the semaphore:
3910                  */
3911 #ifdef CONFIG_PREEMPT_BKL
3912                 saved_lock_depth = task->lock_depth;
3913                 task->lock_depth = -1;
3914 #endif
3915                 schedule();
3916 #ifdef CONFIG_PREEMPT_BKL
3917                 task->lock_depth = saved_lock_depth;
3918 #endif
3919                 sub_preempt_count(PREEMPT_ACTIVE);
3920
3921                 /*
3922                  * Check again in case we missed a preemption opportunity
3923                  * between schedule and now.
3924                  */
3925                 barrier();
3926         } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
3927 }
3928 EXPORT_SYMBOL(preempt_schedule);
3929
3930 /*
3931  * this is the entry point to schedule() from kernel preemption
3932  * off of irq context.
3933  * Note, that this is called and return with irqs disabled. This will
3934  * protect us against recursive calling from irq.
3935  */
3936 asmlinkage void __sched preempt_schedule_irq(void)
3937 {
3938         struct thread_info *ti = current_thread_info();
3939 #ifdef CONFIG_PREEMPT_BKL
3940         struct task_struct *task = current;
3941         int saved_lock_depth;
3942 #endif
3943         /* Catch callers which need to be fixed */
3944         BUG_ON(ti->preempt_count || !irqs_disabled());
3945
3946         do {
3947                 add_preempt_count(PREEMPT_ACTIVE);
3948
3949                 /*
3950                  * We keep the big kernel semaphore locked, but we
3951                  * clear ->lock_depth so that schedule() doesnt
3952                  * auto-release the semaphore:
3953                  */
3954 #ifdef CONFIG_PREEMPT_BKL
3955                 saved_lock_depth = task->lock_depth;
3956                 task->lock_depth = -1;
3957 #endif
3958                 local_irq_enable();
3959                 schedule();
3960                 local_irq_disable();
3961 #ifdef CONFIG_PREEMPT_BKL
3962                 task->lock_depth = saved_lock_depth;
3963 #endif
3964                 sub_preempt_count(PREEMPT_ACTIVE);
3965
3966                 /*
3967                  * Check again in case we missed a preemption opportunity
3968                  * between schedule and now.
3969                  */
3970                 barrier();
3971         } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
3972 }
3973
3974 #endif /* CONFIG_PREEMPT */
3975
3976 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
3977                           void *key)
3978 {
3979         return try_to_wake_up(curr->private, mode, sync);
3980 }
3981 EXPORT_SYMBOL(default_wake_function);
3982
3983 /*
3984  * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3985  * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3986  * number) then we wake all the non-exclusive tasks and one exclusive task.
3987  *
3988  * There are circumstances in which we can try to wake a task which has already
3989  * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3990  * zero in this (rare) case, and we handle it by continuing to scan the queue.
3991  */
3992 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3993                              int nr_exclusive, int sync, void *key)
3994 {
3995         wait_queue_t *curr, *next;
3996
3997         list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
3998                 unsigned flags = curr->flags;
3999
4000                 if (curr->func(curr, mode, sync, key) &&
4001                                 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
4002                         break;
4003         }
4004 }
4005
4006 /**
4007  * __wake_up - wake up threads blocked on a waitqueue.
4008  * @q: the waitqueue
4009  * @mode: which threads
4010  * @nr_exclusive: how many wake-one or wake-many threads to wake up
4011  * @key: is directly passed to the wakeup function
4012  */
4013 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
4014                         int nr_exclusive, void *key)
4015 {
4016         unsigned long flags;
4017
4018         spin_lock_irqsave(&q->lock, flags);
4019         __wake_up_common(q, mode, nr_exclusive, 0, key);
4020         spin_unlock_irqrestore(&q->lock, flags);
4021 }
4022 EXPORT_SYMBOL(__wake_up);
4023
4024 /*
4025  * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4026  */
4027 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4028 {
4029         __wake_up_common(q, mode, 1, 0, NULL);
4030 }
4031
4032 /**
4033  * __wake_up_sync - wake up threads blocked on a waitqueue.
4034  * @q: the waitqueue
4035  * @mode: which threads
4036  * @nr_exclusive: how many wake-one or wake-many threads to wake up
4037  *
4038  * The sync wakeup differs that the waker knows that it will schedule
4039  * away soon, so while the target thread will be woken up, it will not
4040  * be migrated to another CPU - ie. the two threads are 'synchronized'
4041  * with each other. This can prevent needless bouncing between CPUs.
4042  *
4043  * On UP it can prevent extra preemption.
4044  */
4045 void fastcall
4046 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4047 {
4048         unsigned long flags;
4049         int sync = 1;
4050
4051         if (unlikely(!q))
4052                 return;
4053
4054         if (unlikely(!nr_exclusive))
4055                 sync = 0;
4056
4057         spin_lock_irqsave(&q->lock, flags);
4058         __wake_up_common(q, mode, nr_exclusive, sync, NULL);
4059         spin_unlock_irqrestore(&q->lock, flags);
4060 }
4061 EXPORT_SYMBOL_GPL(__wake_up_sync);      /* For internal use only */
4062
4063 void complete(struct completion *x)
4064 {
4065         unsigned long flags;
4066
4067         spin_lock_irqsave(&x->wait.lock, flags);
4068         x->done++;
4069         __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
4070                          1, 0, NULL);
4071         spin_unlock_irqrestore(&x->wait.lock, flags);
4072 }
4073 EXPORT_SYMBOL(complete);
4074
4075 void complete_all(struct completion *x)
4076 {
4077         unsigned long flags;
4078
4079         spin_lock_irqsave(&x->wait.lock, flags);
4080         x->done += UINT_MAX/2;
4081         __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
4082                          0, 0, NULL);
4083         spin_unlock_irqrestore(&x->wait.lock, flags);
4084 }
4085 EXPORT_SYMBOL(complete_all);
4086
4087 static inline long __sched
4088 do_wait_for_common(struct completion *x, long timeout, int state)
4089 {
4090         if (!x->done) {
4091                 DECLARE_WAITQUEUE(wait, current);
4092
4093                 wait.flags |= WQ_FLAG_EXCLUSIVE;
4094                 __add_wait_queue_tail(&x->wait, &wait);
4095                 do {
4096                         if (state == TASK_INTERRUPTIBLE &&
4097                             signal_pending(current)) {
4098                                 __remove_wait_queue(&x->wait, &wait);
4099                                 return -ERESTARTSYS;
4100                         }
4101                         __set_current_state(state);
4102                         spin_unlock_irq(&x->wait.lock);
4103                         timeout = schedule_timeout(timeout);
4104                         spin_lock_irq(&x->wait.lock);
4105                         if (!timeout) {
4106                                 __remove_wait_queue(&x->wait, &wait);
4107                                 return timeout;
4108                         }
4109                 } while (!x->done);
4110                 __remove_wait_queue(&x->wait, &wait);
4111         }
4112         x->done--;
4113         return timeout;
4114 }
4115
4116 static long __sched
4117 wait_for_common(struct completion *x, long timeout, int state)
4118 {
4119         might_sleep();
4120
4121         spin_lock_irq(&x->wait.lock);
4122         timeout = do_wait_for_common(x, timeout, state);
4123         spin_unlock_irq(&x->wait.lock);
4124         return timeout;
4125 }
4126
4127 void __sched wait_for_completion(struct completion *x)
4128 {
4129         wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4130 }
4131 EXPORT_SYMBOL(wait_for_completion);
4132
4133 unsigned long __sched
4134 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4135 {
4136         return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4137 }
4138 EXPORT_SYMBOL(wait_for_completion_timeout);
4139
4140 int __sched wait_for_completion_interruptible(struct completion *x)
4141 {
4142         long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4143         if (t == -ERESTARTSYS)
4144                 return t;
4145         return 0;
4146 }
4147 EXPORT_SYMBOL(wait_for_completion_interruptible);
4148
4149 unsigned long __sched
4150 wait_for_completion_interruptible_timeout(struct completion *x,
4151                                           unsigned long timeout)
4152 {
4153         return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4154 }
4155 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4156
4157 static long __sched
4158 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4159 {
4160         unsigned long flags;
4161         wait_queue_t wait;
4162
4163         init_waitqueue_entry(&wait, current);
4164
4165         __set_current_state(state);
4166
4167         spin_lock_irqsave(&q->lock, flags);
4168         __add_wait_queue(q, &wait);
4169         spin_unlock(&q->lock);
4170         timeout = schedule_timeout(timeout);
4171         spin_lock_irq(&q->lock);
4172         __remove_wait_queue(q, &wait);
4173         spin_unlock_irqrestore(&q->lock, flags);
4174
4175         return timeout;
4176 }
4177
4178 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4179 {
4180         sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4181 }
4182 EXPORT_SYMBOL(interruptible_sleep_on);
4183
4184 long __sched
4185 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4186 {
4187         return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4188 }
4189 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4190
4191 void __sched sleep_on(wait_queue_head_t *q)
4192 {
4193         sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4194 }
4195 EXPORT_SYMBOL(sleep_on);
4196
4197 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4198 {
4199         return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
4200 }
4201 EXPORT_SYMBOL(sleep_on_timeout);
4202
4203 #ifdef CONFIG_RT_MUTEXES
4204
4205 /*
4206  * rt_mutex_setprio - set the current priority of a task
4207  * @p: task
4208  * @prio: prio value (kernel-internal form)
4209  *
4210  * This function changes the 'effective' priority of a task. It does
4211  * not touch ->normal_prio like __setscheduler().
4212  *
4213  * Used by the rt_mutex code to implement priority inheritance logic.
4214  */
4215 void rt_mutex_setprio(struct task_struct *p, int prio)
4216 {
4217         unsigned long flags;
4218         int oldprio, on_rq, running;
4219         struct rq *rq;
4220         const struct sched_class *prev_class = p->sched_class;
4221
4222         BUG_ON(prio < 0 || prio > MAX_PRIO);
4223
4224         rq = task_rq_lock(p, &flags);
4225         update_rq_clock(rq);
4226
4227         oldprio = p->prio;
4228         on_rq = p->se.on_rq;
4229         running = task_current(rq, p);
4230         if (on_rq) {
4231                 dequeue_task(rq, p, 0);
4232                 if (running)
4233                         p->sched_class->put_prev_task(rq, p);
4234         }
4235
4236         if (rt_prio(prio))
4237                 p->sched_class = &rt_sched_class;
4238         else
4239                 p->sched_class = &fair_sched_class;
4240
4241         p->prio = prio;
4242
4243         if (on_rq) {
4244                 if (running)
4245                         p->sched_class->set_curr_task(rq);
4246
4247                 enqueue_task(rq, p, 0);
4248
4249                 check_class_changed(rq, p, prev_class, oldprio, running);
4250         }
4251         task_rq_unlock(rq, &flags);
4252 }
4253
4254 #endif
4255
4256 void set_user_nice(struct task_struct *p, long nice)
4257 {
4258         int old_prio, delta, on_rq;
4259         unsigned long flags;
4260         struct rq *rq;
4261
4262         if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4263                 return;
4264         /*
4265          * We have to be careful, if called from sys_setpriority(),
4266          * the task might be in the middle of scheduling on another CPU.
4267          */
4268         rq = task_rq_lock(p, &flags);
4269         update_rq_clock(rq);
4270         /*
4271          * The RT priorities are set via sched_setscheduler(), but we still
4272          * allow the 'normal' nice value to be set - but as expected
4273          * it wont have any effect on scheduling until the task is
4274          * SCHED_FIFO/SCHED_RR:
4275          */
4276         if (task_has_rt_policy(p)) {
4277                 p->static_prio = NICE_TO_PRIO(nice);
4278                 goto out_unlock;
4279         }
4280         on_rq = p->se.on_rq;
4281         if (on_rq)
4282                 dequeue_task(rq, p, 0);
4283
4284         p->static_prio = NICE_TO_PRIO(nice);
4285         set_load_weight(p);
4286         old_prio = p->prio;
4287         p->prio = effective_prio(p);
4288         delta = p->prio - old_prio;
4289
4290         if (on_rq) {
4291                 enqueue_task(rq, p, 0);
4292                 /*
4293                  * If the task increased its priority or is running and
4294                  * lowered its priority, then reschedule its CPU:
4295                  */
4296                 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4297                         resched_task(rq->curr);
4298         }
4299 out_unlock:
4300         task_rq_unlock(rq, &flags);
4301 }
4302 EXPORT_SYMBOL(set_user_nice);
4303
4304 /*
4305  * can_nice - check if a task can reduce its nice value
4306  * @p: task
4307  * @nice: nice value
4308  */
4309 int can_nice(const struct task_struct *p, const int nice)
4310 {
4311         /* convert nice value [19,-20] to rlimit style value [1,40] */
4312         int nice_rlim = 20 - nice;
4313
4314         return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
4315                 capable(CAP_SYS_NICE));
4316 }
4317
4318 #ifdef __ARCH_WANT_SYS_NICE
4319
4320 /*
4321  * sys_nice - change the priority of the current process.
4322  * @increment: priority increment
4323  *
4324  * sys_setpriority is a more generic, but much slower function that
4325  * does similar things.
4326  */
4327 asmlinkage long sys_nice(int increment)
4328 {
4329         long nice, retval;
4330
4331         /*
4332          * Setpriority might change our priority at the same moment.
4333          * We don't have to worry. Conceptually one call occurs first
4334          * and we have a single winner.
4335          */
4336         if (increment < -40)
4337                 increment = -40;
4338         if (increment > 40)
4339                 increment = 40;
4340
4341         nice = PRIO_TO_NICE(current->static_prio) + increment;
4342         if (nice < -20)
4343                 nice = -20;
4344         if (nice > 19)
4345                 nice = 19;
4346
4347         if (increment < 0 && !can_nice(current, nice))
4348                 return -EPERM;
4349
4350         retval = security_task_setnice(current, nice);
4351         if (retval)
4352                 return retval;
4353
4354         set_user_nice(current, nice);
4355         return 0;
4356 }
4357
4358 #endif
4359
4360 /**
4361  * task_prio - return the priority value of a given task.
4362  * @p: the task in question.
4363  *
4364  * This is the priority value as seen by users in /proc.
4365  * RT tasks are offset by -200. Normal tasks are centered
4366  * around 0, value goes from -16 to +15.
4367  */
4368 int task_prio(const struct task_struct *p)
4369 {
4370         return p->prio - MAX_RT_PRIO;
4371 }
4372
4373 /**
4374  * task_nice - return the nice value of a given task.
4375  * @p: the task in question.
4376  */
4377 int task_nice(const struct task_struct *p)
4378 {
4379         return TASK_NICE(p);
4380 }
4381 EXPORT_SYMBOL_GPL(task_nice);
4382
4383 /**
4384  * idle_cpu - is a given cpu idle currently?
4385  * @cpu: the processor in question.
4386  */
4387 int idle_cpu(int cpu)
4388 {
4389         return cpu_curr(cpu) == cpu_rq(cpu)->idle;
4390 }
4391
4392 /**
4393  * idle_task - return the idle task for a given cpu.
4394  * @cpu: the processor in question.
4395  */
4396 struct task_struct *idle_task(int cpu)
4397 {
4398         return cpu_rq(cpu)->idle;
4399 }
4400
4401 /**
4402  * find_process_by_pid - find a process with a matching PID value.
4403  * @pid: the pid in question.
4404  */
4405 static struct task_struct *find_process_by_pid(pid_t pid)
4406 {
4407         return pid ? find_task_by_vpid(pid) : current;
4408 }
4409
4410 /* Actually do priority change: must hold rq lock. */
4411 static void
4412 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
4413 {
4414         BUG_ON(p->se.on_rq);
4415
4416         p->policy = policy;
4417         switch (p->policy) {
4418         case SCHED_NORMAL:
4419         case SCHED_BATCH:
4420         case SCHED_IDLE:
4421                 p->sched_class = &fair_sched_class;
4422                 break;
4423         case SCHED_FIFO:
4424         case SCHED_RR:
4425                 p->sched_class = &rt_sched_class;
4426                 break;
4427         }
4428
4429         p->rt_priority = prio;
4430         p->normal_prio = normal_prio(p);
4431         /* we are holding p->pi_lock already */
4432         p->prio = rt_mutex_getprio(p);
4433         set_load_weight(p);
4434 }
4435
4436 /**
4437  * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4438  * @p: the task in question.
4439  * @policy: new policy.
4440  * @param: structure containing the new RT priority.
4441  *
4442  * NOTE that the task may be already dead.
4443  */
4444 int sched_setscheduler(struct task_struct *p, int policy,
4445                        struct sched_param *param)
4446 {
4447         int retval, oldprio, oldpolicy = -1, on_rq, running;
4448         unsigned long flags;
4449         const struct sched_class *prev_class = p->sched_class;
4450         struct rq *rq;
4451
4452         /* may grab non-irq protected spin_locks */
4453         BUG_ON(in_interrupt());
4454 recheck:
4455         /* double check policy once rq lock held */
4456         if (policy < 0)
4457                 policy = oldpolicy = p->policy;
4458         else if (policy != SCHED_FIFO && policy != SCHED_RR &&
4459                         policy != SCHED_NORMAL && policy != SCHED_BATCH &&
4460                         policy != SCHED_IDLE)
4461                 return -EINVAL;
4462         /*
4463          * Valid priorities for SCHED_FIFO and SCHED_RR are
4464          * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4465          * SCHED_BATCH and SCHED_IDLE is 0.
4466          */
4467         if (param->sched_priority < 0 ||
4468             (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
4469             (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
4470                 return -EINVAL;
4471         if (rt_policy(policy) != (param->sched_priority != 0))
4472                 return -EINVAL;
4473
4474         /*
4475          * Allow unprivileged RT tasks to decrease priority:
4476          */
4477         if (!capable(CAP_SYS_NICE)) {
4478                 if (rt_policy(policy)) {
4479                         unsigned long rlim_rtprio;
4480
4481                         if (!lock_task_sighand(p, &flags))
4482                                 return -ESRCH;
4483                         rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
4484                         unlock_task_sighand(p, &flags);
4485
4486                         /* can't set/change the rt policy */
4487                         if (policy != p->policy && !rlim_rtprio)
4488                                 return -EPERM;
4489
4490                         /* can't increase priority */
4491                         if (param->sched_priority > p->rt_priority &&
4492                             param->sched_priority > rlim_rtprio)
4493                                 return -EPERM;
4494                 }
4495                 /*
4496                  * Like positive nice levels, dont allow tasks to
4497                  * move out of SCHED_IDLE either:
4498                  */
4499                 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
4500                         return -EPERM;
4501
4502                 /* can't change other user's priorities */
4503                 if ((current->euid != p->euid) &&
4504                     (current->euid != p->uid))
4505                         return -EPERM;
4506         }
4507
4508         retval = security_task_setscheduler(p, policy, param);
4509         if (retval)
4510                 return retval;
4511         /*
4512          * make sure no PI-waiters arrive (or leave) while we are
4513          * changing the priority of the task:
4514          */
4515         spin_lock_irqsave(&p->pi_lock, flags);
4516         /*
4517          * To be able to change p->policy safely, the apropriate
4518          * runqueue lock must be held.
4519          */
4520         rq = __task_rq_lock(p);
4521         /* recheck policy now with rq lock held */
4522         if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4523                 policy = oldpolicy = -1;
4524                 __task_rq_unlock(rq);
4525                 spin_unlock_irqrestore(&p->pi_lock, flags);
4526                 goto recheck;
4527         }
4528         update_rq_clock(rq);
4529         on_rq = p->se.on_rq;
4530         running = task_current(rq, p);
4531         if (on_rq) {
4532                 deactivate_task(rq, p, 0);
4533                 if (running)
4534                         p->sched_class->put_prev_task(rq, p);
4535         }
4536
4537         oldprio = p->prio;
4538         __setscheduler(rq, p, policy, param->sched_priority);
4539
4540         if (on_rq) {
4541                 if (running)
4542                         p->sched_class->set_curr_task(rq);
4543
4544                 activate_task(rq, p, 0);
4545
4546                 check_class_changed(rq, p, prev_class, oldprio, running);
4547         }
4548         __task_rq_unlock(rq);
4549         spin_unlock_irqrestore(&p->pi_lock, flags);
4550
4551         rt_mutex_adjust_pi(p);
4552
4553         return 0;
4554 }
4555 EXPORT_SYMBOL_GPL(sched_setscheduler);
4556
4557 static int
4558 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4559 {
4560         struct sched_param lparam;
4561         struct task_struct *p;
4562         int retval;
4563
4564         if (!param || pid < 0)
4565                 return -EINVAL;
4566         if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4567                 return -EFAULT;
4568
4569         rcu_read_lock();
4570         retval = -ESRCH;
4571         p = find_process_by_pid(pid);
4572         if (p != NULL)
4573                 retval = sched_setscheduler(p, policy, &lparam);
4574         rcu_read_unlock();
4575
4576         return retval;
4577 }
4578
4579 /**
4580  * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4581  * @pid: the pid in question.
4582  * @policy: new policy.
4583  * @param: structure containing the new RT priority.
4584  */
4585 asmlinkage long
4586 sys_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4587 {
4588         /* negative values for policy are not valid */
4589         if (policy < 0)
4590                 return -EINVAL;
4591
4592         return do_sched_setscheduler(pid, policy, param);
4593 }
4594
4595 /**
4596  * sys_sched_setparam - set/change the RT priority of a thread
4597  * @pid: the pid in question.
4598  * @param: structure containing the new RT priority.
4599  */
4600 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
4601 {
4602         return do_sched_setscheduler(pid, -1, param);
4603 }
4604
4605 /**
4606  * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4607  * @pid: the pid in question.
4608  */
4609 asmlinkage long sys_sched_getscheduler(pid_t pid)
4610 {
4611         struct task_struct *p;
4612         int retval;
4613
4614         if (pid < 0)
4615                 return -EINVAL;
4616
4617         retval = -ESRCH;
4618         read_lock(&tasklist_lock);
4619         p = find_process_by_pid(pid);
4620         if (p) {
4621                 retval = security_task_getscheduler(p);
4622                 if (!retval)
4623                         retval = p->policy;
4624         }
4625         read_unlock(&tasklist_lock);
4626         return retval;
4627 }
4628
4629 /**
4630  * sys_sched_getscheduler - get the RT priority of a thread
4631  * @pid: the pid in question.
4632  * @param: structure containing the RT priority.
4633  */
4634 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
4635 {
4636         struct sched_param lp;
4637         struct task_struct *p;
4638         int retval;
4639
4640         if (!param || pid < 0)
4641                 return -EINVAL;
4642
4643         read_lock(&tasklist_lock);
4644         p = find_process_by_pid(pid);
4645         retval = -ESRCH;
4646         if (!p)
4647                 goto out_unlock;
4648
4649         retval = security_task_getscheduler(p);
4650         if (retval)
4651                 goto out_unlock;
4652
4653         lp.sched_priority = p->rt_priority;
4654         read_unlock(&tasklist_lock);
4655
4656         /*
4657          * This one might sleep, we cannot do it with a spinlock held ...
4658          */
4659         retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4660
4661         return retval;
4662
4663 out_unlock:
4664         read_unlock(&tasklist_lock);
4665         return retval;
4666 }
4667
4668 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
4669 {
4670         cpumask_t cpus_allowed;
4671         struct task_struct *p;
4672         int retval;
4673
4674         get_online_cpus();
4675         read_lock(&tasklist_lock);
4676
4677         p = find_process_by_pid(pid);
4678         if (!p) {
4679                 read_unlock(&tasklist_lock);
4680                 put_online_cpus();
4681                 return -ESRCH;
4682         }
4683
4684         /*
4685          * It is not safe to call set_cpus_allowed with the
4686          * tasklist_lock held. We will bump the task_struct's
4687          * usage count and then drop tasklist_lock.
4688          */
4689         get_task_struct(p);
4690         read_unlock(&tasklist_lock);
4691
4692         retval = -EPERM;
4693         if ((current->euid != p->euid) && (current->euid != p->uid) &&
4694                         !capable(CAP_SYS_NICE))
4695                 goto out_unlock;
4696
4697         retval = security_task_setscheduler(p, 0, NULL);
4698         if (retval)
4699                 goto out_unlock;
4700
4701         cpus_allowed = cpuset_cpus_allowed(p);
4702         cpus_and(new_mask, new_mask, cpus_allowed);
4703  again:
4704         retval = set_cpus_allowed(p, new_mask);
4705
4706         if (!retval) {
4707                 cpus_allowed = cpuset_cpus_allowed(p);
4708                 if (!cpus_subset(new_mask, cpus_allowed)) {
4709                         /*
4710                          * We must have raced with a concurrent cpuset
4711                          * update. Just reset the cpus_allowed to the
4712                          * cpuset's cpus_allowed
4713                          */
4714                         new_mask = cpus_allowed;
4715                         goto again;
4716                 }
4717         }
4718 out_unlock:
4719         put_task_struct(p);
4720         put_online_cpus();
4721         return retval;
4722 }
4723
4724 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4725                              cpumask_t *new_mask)
4726 {
4727         if (len < sizeof(cpumask_t)) {
4728                 memset(new_mask, 0, sizeof(cpumask_t));
4729         } else if (len > sizeof(cpumask_t)) {
4730                 len = sizeof(cpumask_t);
4731         }
4732         return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4733 }
4734
4735 /**
4736  * sys_sched_setaffinity - set the cpu affinity of a process
4737  * @pid: pid of the process
4738  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4739  * @user_mask_ptr: user-space pointer to the new cpu mask
4740  */
4741 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
4742                                       unsigned long __user *user_mask_ptr)
4743 {
4744         cpumask_t new_mask;
4745         int retval;
4746
4747         retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
4748         if (retval)
4749                 return retval;
4750
4751         return sched_setaffinity(pid, new_mask);
4752 }
4753
4754 /*
4755  * Represents all cpu's present in the system
4756  * In systems capable of hotplug, this map could dynamically grow
4757  * as new cpu's are detected in the system via any platform specific
4758  * method, such as ACPI for e.g.
4759  */
4760
4761 cpumask_t cpu_present_map __read_mostly;
4762 EXPORT_SYMBOL(cpu_present_map);
4763
4764 #ifndef CONFIG_SMP
4765 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
4766 EXPORT_SYMBOL(cpu_online_map);
4767
4768 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
4769 EXPORT_SYMBOL(cpu_possible_map);
4770 #endif
4771
4772 long sched_getaffinity(pid_t pid, cpumask_t *mask)
4773 {
4774         struct task_struct *p;
4775         int retval;
4776
4777         get_online_cpus();
4778         read_lock(&tasklist_lock);
4779
4780         retval = -ESRCH;
4781         p = find_process_by_pid(pid);
4782         if (!p)
4783                 goto out_unlock;
4784
4785         retval = security_task_getscheduler(p);
4786         if (retval)
4787                 goto out_unlock;
4788
4789         cpus_and(*mask, p->cpus_allowed, cpu_online_map);
4790
4791 out_unlock:
4792         read_unlock(&tasklist_lock);
4793         put_online_cpus();
4794
4795         return retval;
4796 }
4797
4798 /**
4799  * sys_sched_getaffinity - get the cpu affinity of a process
4800  * @pid: pid of the process
4801  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4802  * @user_mask_ptr: user-space pointer to hold the current cpu mask
4803  */
4804 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
4805                                       unsigned long __user *user_mask_ptr)
4806 {
4807         int ret;
4808         cpumask_t mask;
4809
4810         if (len < sizeof(cpumask_t))
4811                 return -EINVAL;
4812
4813         ret = sched_getaffinity(pid, &mask);
4814         if (ret < 0)
4815                 return ret;
4816
4817         if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
4818                 return -EFAULT;
4819
4820         return sizeof(cpumask_t);
4821 }
4822
4823 /**
4824  * sys_sched_yield - yield the current processor to other threads.
4825  *
4826  * This function yields the current CPU to other tasks. If there are no
4827  * other threads running on this CPU then this function will return.
4828  */
4829 asmlinkage long sys_sched_yield(void)
4830 {
4831         struct rq *rq = this_rq_lock();
4832
4833         schedstat_inc(rq, yld_count);
4834         current->sched_class->yield_task(rq);
4835
4836         /*
4837          * Since we are going to call schedule() anyway, there's
4838          * no need to preempt or enable interrupts:
4839          */
4840         __release(rq->lock);
4841         spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
4842         _raw_spin_unlock(&rq->lock);
4843         preempt_enable_no_resched();
4844
4845         schedule();
4846
4847         return 0;
4848 }
4849
4850 static void __cond_resched(void)
4851 {
4852 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4853         __might_sleep(__FILE__, __LINE__);
4854 #endif
4855         /*
4856          * The BKS might be reacquired before we have dropped
4857          * PREEMPT_ACTIVE, which could trigger a second
4858          * cond_resched() call.
4859          */
4860         do {
4861                 add_preempt_count(PREEMPT_ACTIVE);
4862                 schedule();
4863                 sub_preempt_count(PREEMPT_ACTIVE);
4864         } while (need_resched());
4865 }
4866
4867 #if !defined(CONFIG_PREEMPT) || defined(CONFIG_PREEMPT_VOLUNTARY)
4868 int __sched _cond_resched(void)
4869 {
4870         if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
4871                                         system_state == SYSTEM_RUNNING) {
4872                 __cond_resched();
4873                 return 1;
4874         }
4875         return 0;
4876 }
4877 EXPORT_SYMBOL(_cond_resched);
4878 #endif
4879
4880 /*
4881  * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4882  * call schedule, and on return reacquire the lock.
4883  *
4884  * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4885  * operations here to prevent schedule() from being called twice (once via
4886  * spin_unlock(), once by hand).
4887  */
4888 int cond_resched_lock(spinlock_t *lock)
4889 {
4890         int ret = 0;
4891
4892         if (need_lockbreak(lock)) {
4893                 spin_unlock(lock);
4894                 cpu_relax();
4895                 ret = 1;
4896                 spin_lock(lock);
4897         }
4898         if (need_resched() && system_state == SYSTEM_RUNNING) {
4899                 spin_release(&lock->dep_map, 1, _THIS_IP_);
4900                 _raw_spin_unlock(lock);
4901                 preempt_enable_no_resched();
4902                 __cond_resched();
4903                 ret = 1;
4904                 spin_lock(lock);
4905         }
4906         return ret;
4907 }
4908 EXPORT_SYMBOL(cond_resched_lock);
4909
4910 int __sched cond_resched_softirq(void)
4911 {
4912         BUG_ON(!in_softirq());
4913
4914         if (need_resched() && system_state == SYSTEM_RUNNING) {
4915                 local_bh_enable();
4916                 __cond_resched();
4917                 local_bh_disable();
4918                 return 1;
4919         }
4920         return 0;
4921 }
4922 EXPORT_SYMBOL(cond_resched_softirq);
4923
4924 /**
4925  * yield - yield the current processor to other threads.
4926  *
4927  * This is a shortcut for kernel-space yielding - it marks the
4928  * thread runnable and calls sys_sched_yield().
4929  */
4930 void __sched yield(void)
4931 {
4932         set_current_state(TASK_RUNNING);
4933         sys_sched_yield();
4934 }
4935 EXPORT_SYMBOL(yield);
4936
4937 /*
4938  * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4939  * that process accounting knows that this is a task in IO wait state.
4940  *
4941  * But don't do that if it is a deliberate, throttling IO wait (this task
4942  * has set its backing_dev_info: the queue against which it should throttle)
4943  */
4944 void __sched io_schedule(void)
4945 {
4946         struct rq *rq = &__raw_get_cpu_var(runqueues);
4947
4948         delayacct_blkio_start();
4949         atomic_inc(&rq->nr_iowait);
4950         schedule();
4951         atomic_dec(&rq->nr_iowait);
4952         delayacct_blkio_end();
4953 }
4954 EXPORT_SYMBOL(io_schedule);
4955
4956 long __sched io_schedule_timeout(long timeout)
4957 {
4958         struct rq *rq = &__raw_get_cpu_var(runqueues);
4959         long ret;
4960
4961         delayacct_blkio_start();
4962         atomic_inc(&rq->nr_iowait);
4963         ret = schedule_timeout(timeout);
4964         atomic_dec(&rq->nr_iowait);
4965         delayacct_blkio_end();
4966         return ret;
4967 }
4968
4969 /**
4970  * sys_sched_get_priority_max - return maximum RT priority.
4971  * @policy: scheduling class.
4972  *
4973  * this syscall returns the maximum rt_priority that can be used
4974  * by a given scheduling class.
4975  */
4976 asmlinkage long sys_sched_get_priority_max(int policy)
4977 {
4978         int ret = -EINVAL;
4979
4980         switch (policy) {
4981         case SCHED_FIFO:
4982         case SCHED_RR:
4983                 ret = MAX_USER_RT_PRIO-1;
4984                 break;
4985         case SCHED_NORMAL:
4986         case SCHED_BATCH:
4987         case SCHED_IDLE:
4988                 ret = 0;
4989                 break;
4990         }
4991         return ret;
4992 }
4993
4994 /**
4995  * sys_sched_get_priority_min - return minimum RT priority.
4996  * @policy: scheduling class.
4997  *
4998  * this syscall returns the minimum rt_priority that can be used
4999  * by a given scheduling class.
5000  */
5001 asmlinkage long sys_sched_get_priority_min(int policy)
5002 {
5003         int ret = -EINVAL;
5004
5005         switch (policy) {
5006         case SCHED_FIFO:
5007         case SCHED_RR:
5008                 ret = 1;
5009                 break;
5010         case SCHED_NORMAL:
5011         case SCHED_BATCH:
5012         case SCHED_IDLE:
5013                 ret = 0;
5014         }
5015         return ret;
5016 }
5017
5018 /**
5019  * sys_sched_rr_get_interval - return the default timeslice of a process.
5020  * @pid: pid of the process.
5021  * @interval: userspace pointer to the timeslice value.
5022  *
5023  * this syscall writes the default timeslice value of a given process
5024  * into the user-space timespec buffer. A value of '0' means infinity.
5025  */
5026 asmlinkage
5027 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
5028 {
5029         struct task_struct *p;
5030         unsigned int time_slice;
5031         int retval;
5032         struct timespec t;
5033
5034         if (pid < 0)
5035                 return -EINVAL;
5036
5037         retval = -ESRCH;
5038         read_lock(&tasklist_lock);
5039         p = find_process_by_pid(pid);
5040         if (!p)
5041                 goto out_unlock;
5042
5043         retval = security_task_getscheduler(p);
5044         if (retval)
5045                 goto out_unlock;
5046
5047         /*
5048          * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5049          * tasks that are on an otherwise idle runqueue:
5050          */
5051         time_slice = 0;
5052         if (p->policy == SCHED_RR) {
5053                 time_slice = DEF_TIMESLICE;
5054         } else {
5055                 struct sched_entity *se = &p->se;
5056                 unsigned long flags;
5057                 struct rq *rq;
5058
5059                 rq = task_rq_lock(p, &flags);
5060                 if (rq->cfs.load.weight)
5061                         time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
5062                 task_rq_unlock(rq, &flags);
5063         }
5064         read_unlock(&tasklist_lock);
5065         jiffies_to_timespec(time_slice, &t);
5066         retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5067         return retval;
5068
5069 out_unlock:
5070         read_unlock(&tasklist_lock);
5071         return retval;
5072 }
5073
5074 static const char stat_nam[] = "RSDTtZX";
5075
5076 void sched_show_task(struct task_struct *p)
5077 {
5078         unsigned long free = 0;
5079         unsigned state;
5080
5081         state = p->state ? __ffs(p->state) + 1 : 0;
5082         printk(KERN_INFO "%-13.13s %c", p->comm,
5083                 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5084 #if BITS_PER_LONG == 32
5085         if (state == TASK_RUNNING)
5086                 printk(KERN_CONT " running  ");
5087         else
5088                 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5089 #else
5090         if (state == TASK_RUNNING)
5091                 printk(KERN_CONT "  running task    ");
5092         else
5093                 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5094 #endif
5095 #ifdef CONFIG_DEBUG_STACK_USAGE
5096         {
5097                 unsigned long *n = end_of_stack(p);
5098                 while (!*n)
5099                         n++;
5100                 free = (unsigned long)n - (unsigned long)end_of_stack(p);
5101         }
5102 #endif
5103         printk(KERN_CONT "%5lu %5d %6d\n", free,
5104                 task_pid_nr(p), task_pid_nr(p->real_parent));
5105
5106         if (state != TASK_RUNNING)
5107                 show_stack(p, NULL);
5108 }
5109
5110 void show_state_filter(unsigned long state_filter)
5111 {
5112         struct task_struct *g, *p;
5113
5114 #if BITS_PER_LONG == 32
5115         printk(KERN_INFO
5116                 "  task                PC stack   pid father\n");
5117 #else
5118         printk(KERN_INFO
5119                 "  task                        PC stack   pid father\n");
5120 #endif
5121         read_lock(&tasklist_lock);
5122         do_each_thread(g, p) {
5123                 /*
5124                  * reset the NMI-timeout, listing all files on a slow
5125                  * console might take alot of time:
5126                  */
5127                 touch_nmi_watchdog();
5128                 if (!state_filter || (p->state & state_filter))
5129                         sched_show_task(p);
5130         } while_each_thread(g, p);
5131
5132         touch_all_softlockup_watchdogs();
5133
5134 #ifdef CONFIG_SCHED_DEBUG
5135         sysrq_sched_debug_show();
5136 #endif
5137         read_unlock(&tasklist_lock);
5138         /*
5139          * Only show locks if all tasks are dumped:
5140          */
5141         if (state_filter == -1)
5142                 debug_show_all_locks();
5143 }
5144
5145 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5146 {
5147         idle->sched_class = &idle_sched_class;
5148 }
5149
5150 /**
5151  * init_idle - set up an idle thread for a given CPU
5152  * @idle: task in question
5153  * @cpu: cpu the idle task belongs to
5154  *
5155  * NOTE: this function does not set the idle thread's NEED_RESCHED
5156  * flag, to make booting more robust.
5157  */
5158 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5159 {
5160         struct rq *rq = cpu_rq(cpu);
5161         unsigned long flags;
5162
5163         __sched_fork(idle);
5164         idle->se.exec_start = sched_clock();
5165
5166         idle->prio = idle->normal_prio = MAX_PRIO;
5167         idle->cpus_allowed = cpumask_of_cpu(cpu);
5168         __set_task_cpu(idle, cpu);
5169
5170         spin_lock_irqsave(&rq->lock, flags);
5171         rq->curr = rq->idle = idle;
5172 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5173         idle->oncpu = 1;
5174 #endif
5175         spin_unlock_irqrestore(&rq->lock, flags);
5176
5177         /* Set the preempt count _outside_ the spinlocks! */
5178 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
5179         task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
5180 #else
5181         task_thread_info(idle)->preempt_count = 0;
5182 #endif
5183         /*
5184          * The idle tasks have their own, simple scheduling class:
5185          */
5186         idle->sched_class = &idle_sched_class;
5187 }
5188
5189 /*
5190  * In a system that switches off the HZ timer nohz_cpu_mask
5191  * indicates which cpus entered this state. This is used
5192  * in the rcu update to wait only for active cpus. For system
5193  * which do not switch off the HZ timer nohz_cpu_mask should
5194  * always be CPU_MASK_NONE.
5195  */
5196 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
5197
5198 /*
5199  * Increase the granularity value when there are more CPUs,
5200  * because with more CPUs the 'effective latency' as visible
5201  * to users decreases. But the relationship is not linear,
5202  * so pick a second-best guess by going with the log2 of the
5203  * number of CPUs.
5204  *
5205  * This idea comes from the SD scheduler of Con Kolivas:
5206  */
5207 static inline void sched_init_granularity(void)
5208 {
5209         unsigned int factor = 1 + ilog2(num_online_cpus());
5210         const unsigned long limit = 200000000;
5211
5212         sysctl_sched_min_granularity *= factor;
5213         if (sysctl_sched_min_granularity > limit)
5214                 sysctl_sched_min_granularity = limit;
5215
5216         sysctl_sched_latency *= factor;
5217         if (sysctl_sched_latency > limit)
5218                 sysctl_sched_latency = limit;
5219
5220         sysctl_sched_wakeup_granularity *= factor;
5221         sysctl_sched_batch_wakeup_granularity *= factor;
5222 }
5223
5224 #ifdef CONFIG_SMP
5225 /*
5226  * This is how migration works:
5227  *
5228  * 1) we queue a struct migration_req structure in the source CPU's
5229  *    runqueue and wake up that CPU's migration thread.
5230  * 2) we down() the locked semaphore => thread blocks.
5231  * 3) migration thread wakes up (implicitly it forces the migrated
5232  *    thread off the CPU)
5233  * 4) it gets the migration request and checks whether the migrated
5234  *    task is still in the wrong runqueue.
5235  * 5) if it's in the wrong runqueue then the migration thread removes
5236  *    it and puts it into the right queue.
5237  * 6) migration thread up()s the semaphore.
5238  * 7) we wake up and the migration is done.
5239  */
5240
5241 /*
5242  * Change a given task's CPU affinity. Migrate the thread to a
5243  * proper CPU and schedule it away if the CPU it's executing on
5244  * is removed from the allowed bitmask.
5245  *
5246  * NOTE: the caller must have a valid reference to the task, the
5247  * task must not exit() & deallocate itself prematurely. The
5248  * call is not atomic; no spinlocks may be held.
5249  */
5250 int set_cpus_allowed(struct task_struct *p, cpumask_t new_mask)
5251 {
5252         struct migration_req req;
5253         unsigned long flags;
5254         struct rq *rq;
5255         int ret = 0;
5256
5257         rq = task_rq_lock(p, &flags);
5258         if (!cpus_intersects(new_mask, cpu_online_map)) {
5259                 ret = -EINVAL;
5260                 goto out;
5261         }
5262
5263         if (p->sched_class->set_cpus_allowed)
5264                 p->sched_class->set_cpus_allowed(p, &new_mask);
5265         else {
5266                 p->cpus_allowed = new_mask;
5267                 p->nr_cpus_allowed = cpus_weight(new_mask);
5268         }
5269
5270         /* Can the task run on the task's current CPU? If so, we're done */
5271         if (cpu_isset(task_cpu(p), new_mask))
5272                 goto out;
5273
5274         if (migrate_task(p, any_online_cpu(new_mask), &req)) {
5275                 /* Need help from migration thread: drop lock and wait. */
5276                 task_rq_unlock(rq, &flags);
5277                 wake_up_process(rq->migration_thread);
5278                 wait_for_completion(&req.done);
5279                 tlb_migrate_finish(p->mm);
5280                 return 0;
5281         }
5282 out:
5283         task_rq_unlock(rq, &flags);
5284
5285         return ret;
5286 }
5287 EXPORT_SYMBOL_GPL(set_cpus_allowed);
5288
5289 /*
5290  * Move (not current) task off this cpu, onto dest cpu. We're doing
5291  * this because either it can't run here any more (set_cpus_allowed()
5292  * away from this CPU, or CPU going down), or because we're
5293  * attempting to rebalance this task on exec (sched_exec).
5294  *
5295  * So we race with normal scheduler movements, but that's OK, as long
5296  * as the task is no longer on this CPU.
5297  *
5298  * Returns non-zero if task was successfully migrated.
5299  */
5300 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
5301 {
5302         struct rq *rq_dest, *rq_src;
5303         int ret = 0, on_rq;
5304
5305         if (unlikely(cpu_is_offline(dest_cpu)))
5306                 return ret;
5307
5308         rq_src = cpu_rq(src_cpu);
5309         rq_dest = cpu_rq(dest_cpu);
5310
5311         double_rq_lock(rq_src, rq_dest);
5312         /* Already moved. */
5313         if (task_cpu(p) != src_cpu)
5314                 goto out;
5315         /* Affinity changed (again). */
5316         if (!cpu_isset(dest_cpu, p->cpus_allowed))
5317                 goto out;
5318
5319         on_rq = p->se.on_rq;
5320         if (on_rq)
5321                 deactivate_task(rq_src, p, 0);
5322
5323         set_task_cpu(p, dest_cpu);
5324         if (on_rq) {
5325                 activate_task(rq_dest, p, 0);
5326                 check_preempt_curr(rq_dest, p);
5327         }
5328         ret = 1;
5329 out:
5330         double_rq_unlock(rq_src, rq_dest);
5331         return ret;
5332 }
5333
5334 /*
5335  * migration_thread - this is a highprio system thread that performs
5336  * thread migration by bumping thread off CPU then 'pushing' onto
5337  * another runqueue.
5338  */
5339 static int migration_thread(void *data)
5340 {
5341         int cpu = (long)data;
5342         struct rq *rq;
5343
5344         rq = cpu_rq(cpu);
5345         BUG_ON(rq->migration_thread != current);
5346
5347         set_current_state(TASK_INTERRUPTIBLE);
5348         while (!kthread_should_stop()) {
5349                 struct migration_req *req;
5350                 struct list_head *head;
5351
5352                 spin_lock_irq(&rq->lock);
5353
5354                 if (cpu_is_offline(cpu)) {
5355                         spin_unlock_irq(&rq->lock);
5356                         goto wait_to_die;
5357                 }
5358
5359                 if (rq->active_balance) {
5360                         active_load_balance(rq, cpu);
5361                         rq->active_balance = 0;
5362                 }
5363
5364                 head = &rq->migration_queue;
5365
5366                 if (list_empty(head)) {
5367                         spin_unlock_irq(&rq->lock);
5368                         schedule();
5369                         set_current_state(TASK_INTERRUPTIBLE);
5370                         continue;
5371                 }
5372                 req = list_entry(head->next, struct migration_req, list);
5373                 list_del_init(head->next);
5374
5375                 spin_unlock(&rq->lock);
5376                 __migrate_task(req->task, cpu, req->dest_cpu);
5377                 local_irq_enable();
5378
5379                 complete(&req->done);
5380         }
5381         __set_current_state(TASK_RUNNING);
5382         return 0;
5383
5384 wait_to_die:
5385         /* Wait for kthread_stop */
5386         set_current_state(TASK_INTERRUPTIBLE);
5387         while (!kthread_should_stop()) {
5388                 schedule();
5389                 set_current_state(TASK_INTERRUPTIBLE);
5390         }
5391         __set_current_state(TASK_RUNNING);
5392         return 0;
5393 }
5394
5395 #ifdef CONFIG_HOTPLUG_CPU
5396
5397 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
5398 {
5399         int ret;
5400
5401         local_irq_disable();
5402         ret = __migrate_task(p, src_cpu, dest_cpu);
5403         local_irq_enable();
5404         return ret;
5405 }
5406
5407 /*
5408  * Figure out where task on dead CPU should go, use force if necessary.
5409  * NOTE: interrupts should be disabled by the caller
5410  */
5411 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
5412 {
5413         unsigned long flags;
5414         cpumask_t mask;
5415         struct rq *rq;
5416         int dest_cpu;
5417
5418         do {
5419                 /* On same node? */
5420                 mask = node_to_cpumask(cpu_to_node(dead_cpu));
5421                 cpus_and(mask, mask, p->cpus_allowed);
5422                 dest_cpu = any_online_cpu(mask);
5423
5424                 /* On any allowed CPU? */
5425                 if (dest_cpu == NR_CPUS)
5426                         dest_cpu = any_online_cpu(p->cpus_allowed);
5427
5428                 /* No more Mr. Nice Guy. */
5429                 if (dest_cpu == NR_CPUS) {
5430                         cpumask_t cpus_allowed = cpuset_cpus_allowed_locked(p);
5431                         /*
5432                          * Try to stay on the same cpuset, where the
5433                          * current cpuset may be a subset of all cpus.
5434                          * The cpuset_cpus_allowed_locked() variant of
5435                          * cpuset_cpus_allowed() will not block. It must be
5436                          * called within calls to cpuset_lock/cpuset_unlock.
5437                          */
5438                         rq = task_rq_lock(p, &flags);
5439                         p->cpus_allowed = cpus_allowed;
5440                         dest_cpu = any_online_cpu(p->cpus_allowed);
5441                         task_rq_unlock(rq, &flags);
5442
5443                         /*
5444                          * Don't tell them about moving exiting tasks or
5445                          * kernel threads (both mm NULL), since they never
5446                          * leave kernel.
5447                          */
5448                         if (p->mm && printk_ratelimit()) {
5449                                 printk(KERN_INFO "process %d (%s) no "
5450                                        "longer affine to cpu%d\n",
5451                                         task_pid_nr(p), p->comm, dead_cpu);
5452                         }
5453                 }
5454         } while (!__migrate_task_irq(p, dead_cpu, dest_cpu));
5455 }
5456
5457 /*
5458  * While a dead CPU has no uninterruptible tasks queued at this point,
5459  * it might still have a nonzero ->nr_uninterruptible counter, because
5460  * for performance reasons the counter is not stricly tracking tasks to
5461  * their home CPUs. So we just add the counter to another CPU's counter,
5462  * to keep the global sum constant after CPU-down:
5463  */
5464 static void migrate_nr_uninterruptible(struct rq *rq_src)
5465 {
5466         struct rq *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
5467         unsigned long flags;
5468
5469         local_irq_save(flags);
5470         double_rq_lock(rq_src, rq_dest);
5471         rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5472         rq_src->nr_uninterruptible = 0;
5473         double_rq_unlock(rq_src, rq_dest);
5474         local_irq_restore(flags);
5475 }
5476
5477 /* Run through task list and migrate tasks from the dead cpu. */
5478 static void migrate_live_tasks(int src_cpu)
5479 {
5480         struct task_struct *p, *t;
5481
5482         read_lock(&tasklist_lock);
5483
5484         do_each_thread(t, p) {
5485                 if (p == current)
5486                         continue;
5487
5488                 if (task_cpu(p) == src_cpu)
5489                         move_task_off_dead_cpu(src_cpu, p);
5490         } while_each_thread(t, p);
5491
5492         read_unlock(&tasklist_lock);
5493 }
5494
5495 /*
5496  * Schedules idle task to be the next runnable task on current CPU.
5497  * It does so by boosting its priority to highest possible.
5498  * Used by CPU offline code.
5499  */
5500 void sched_idle_next(void)
5501 {
5502         int this_cpu = smp_processor_id();
5503         struct rq *rq = cpu_rq(this_cpu);
5504         struct task_struct *p = rq->idle;
5505         unsigned long flags;
5506
5507         /* cpu has to be offline */
5508         BUG_ON(cpu_online(this_cpu));
5509
5510         /*
5511          * Strictly not necessary since rest of the CPUs are stopped by now
5512          * and interrupts disabled on the current cpu.
5513          */
5514         spin_lock_irqsave(&rq->lock, flags);
5515
5516         __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
5517
5518         update_rq_clock(rq);
5519         activate_task(rq, p, 0);
5520
5521         spin_unlock_irqrestore(&rq->lock, flags);
5522 }
5523
5524 /*
5525  * Ensures that the idle task is using init_mm right before its cpu goes
5526  * offline.
5527  */
5528 void idle_task_exit(void)
5529 {
5530         struct mm_struct *mm = current->active_mm;
5531
5532         BUG_ON(cpu_online(smp_processor_id()));
5533
5534         if (mm != &init_mm)
5535                 switch_mm(mm, &init_mm, current);
5536         mmdrop(mm);
5537 }
5538
5539 /* called under rq->lock with disabled interrupts */
5540 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
5541 {
5542         struct rq *rq = cpu_rq(dead_cpu);
5543
5544         /* Must be exiting, otherwise would be on tasklist. */
5545         BUG_ON(!p->exit_state);
5546
5547         /* Cannot have done final schedule yet: would have vanished. */
5548         BUG_ON(p->state == TASK_DEAD);
5549
5550         get_task_struct(p);
5551
5552         /*
5553          * Drop lock around migration; if someone else moves it,
5554          * that's OK. No task can be added to this CPU, so iteration is
5555          * fine.
5556          */
5557         spin_unlock_irq(&rq->lock);
5558         move_task_off_dead_cpu(dead_cpu, p);
5559         spin_lock_irq(&rq->lock);
5560
5561         put_task_struct(p);
5562 }
5563
5564 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5565 static void migrate_dead_tasks(unsigned int dead_cpu)
5566 {
5567         struct rq *rq = cpu_rq(dead_cpu);
5568         struct task_struct *next;
5569
5570         for ( ; ; ) {
5571                 if (!rq->nr_running)
5572                         break;
5573                 update_rq_clock(rq);
5574                 next = pick_next_task(rq, rq->curr);
5575                 if (!next)
5576                         break;
5577                 migrate_dead(dead_cpu, next);
5578
5579         }
5580 }
5581 #endif /* CONFIG_HOTPLUG_CPU */
5582
5583 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5584
5585 static struct ctl_table sd_ctl_dir[] = {
5586         {
5587                 .procname       = "sched_domain",
5588                 .mode           = 0555,
5589         },
5590         {0, },
5591 };
5592
5593 static struct ctl_table sd_ctl_root[] = {
5594         {
5595                 .ctl_name       = CTL_KERN,
5596                 .procname       = "kernel",
5597                 .mode           = 0555,
5598                 .child          = sd_ctl_dir,
5599         },
5600         {0, },
5601 };
5602
5603 static struct ctl_table *sd_alloc_ctl_entry(int n)
5604 {
5605         struct ctl_table *entry =
5606                 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
5607
5608         return entry;
5609 }
5610
5611 static void sd_free_ctl_entry(struct ctl_table **tablep)
5612 {
5613         struct ctl_table *entry;
5614
5615         /*
5616          * In the intermediate directories, both the child directory and
5617          * procname are dynamically allocated and could fail but the mode
5618          * will always be set. In the lowest directory the names are
5619          * static strings and all have proc handlers.
5620          */
5621         for (entry = *tablep; entry->mode; entry++) {
5622                 if (entry->child)
5623                         sd_free_ctl_entry(&entry->child);
5624                 if (entry->proc_handler == NULL)
5625                         kfree(entry->procname);
5626         }
5627
5628         kfree(*tablep);
5629         *tablep = NULL;
5630 }
5631
5632 static void
5633 set_table_entry(struct ctl_table *entry,
5634                 const char *procname, void *data, int maxlen,
5635                 mode_t mode, proc_handler *proc_handler)
5636 {
5637         entry->procname = procname;
5638         entry->data = data;
5639         entry->maxlen = maxlen;
5640         entry->mode = mode;
5641         entry->proc_handler = proc_handler;
5642 }
5643
5644 static struct ctl_table *
5645 sd_alloc_ctl_domain_table(struct sched_domain *sd)
5646 {
5647         struct ctl_table *table = sd_alloc_ctl_entry(12);
5648
5649         if (table == NULL)
5650                 return NULL;
5651
5652         set_table_entry(&table[0], "min_interval", &sd->min_interval,
5653                 sizeof(long), 0644, proc_doulongvec_minmax);
5654         set_table_entry(&table[1], "max_interval", &sd->max_interval,
5655                 sizeof(long), 0644, proc_doulongvec_minmax);
5656         set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
5657                 sizeof(int), 0644, proc_dointvec_minmax);
5658         set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
5659                 sizeof(int), 0644, proc_dointvec_minmax);
5660         set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
5661                 sizeof(int), 0644, proc_dointvec_minmax);
5662         set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
5663                 sizeof(int), 0644, proc_dointvec_minmax);
5664         set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
5665                 sizeof(int), 0644, proc_dointvec_minmax);
5666         set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
5667                 sizeof(int), 0644, proc_dointvec_minmax);
5668         set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
5669                 sizeof(int), 0644, proc_dointvec_minmax);
5670         set_table_entry(&table[9], "cache_nice_tries",
5671                 &sd->cache_nice_tries,
5672                 sizeof(int), 0644, proc_dointvec_minmax);
5673         set_table_entry(&table[10], "flags", &sd->flags,
5674                 sizeof(int), 0644, proc_dointvec_minmax);
5675         /* &table[11] is terminator */
5676
5677         return table;
5678 }
5679
5680 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
5681 {
5682         struct ctl_table *entry, *table;
5683         struct sched_domain *sd;
5684         int domain_num = 0, i;
5685         char buf[32];
5686
5687         for_each_domain(cpu, sd)
5688                 domain_num++;
5689         entry = table = sd_alloc_ctl_entry(domain_num + 1);
5690         if (table == NULL)
5691                 return NULL;
5692
5693         i = 0;
5694         for_each_domain(cpu, sd) {
5695                 snprintf(buf, 32, "domain%d", i);
5696                 entry->procname = kstrdup(buf, GFP_KERNEL);
5697                 entry->mode = 0555;
5698                 entry->child = sd_alloc_ctl_domain_table(sd);
5699                 entry++;
5700                 i++;
5701         }
5702         return table;
5703 }
5704
5705 static struct ctl_table_header *sd_sysctl_header;
5706 static void register_sched_domain_sysctl(void)
5707 {
5708         int i, cpu_num = num_online_cpus();
5709         struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5710         char buf[32];
5711
5712         WARN_ON(sd_ctl_dir[0].child);
5713         sd_ctl_dir[0].child = entry;
5714
5715         if (entry == NULL)
5716                 return;
5717
5718         for_each_online_cpu(i) {
5719                 snprintf(buf, 32, "cpu%d", i);
5720                 entry->procname = kstrdup(buf, GFP_KERNEL);
5721                 entry->mode = 0555;
5722                 entry->child = sd_alloc_ctl_cpu_table(i);
5723                 entry++;
5724         }
5725
5726         WARN_ON(sd_sysctl_header);
5727         sd_sysctl_header = register_sysctl_table(sd_ctl_root);
5728 }
5729
5730 /* may be called multiple times per register */
5731 static void unregister_sched_domain_sysctl(void)
5732 {
5733         if (sd_sysctl_header)
5734                 unregister_sysctl_table(sd_sysctl_header);
5735         sd_sysctl_header = NULL;
5736         if (sd_ctl_dir[0].child)
5737                 sd_free_ctl_entry(&sd_ctl_dir[0].child);
5738 }
5739 #else
5740 static void register_sched_domain_sysctl(void)
5741 {
5742 }
5743 static void unregister_sched_domain_sysctl(void)
5744 {
5745 }
5746 #endif
5747
5748 /*
5749  * migration_call - callback that gets triggered when a CPU is added.
5750  * Here we can start up the necessary migration thread for the new CPU.
5751  */
5752 static int __cpuinit
5753 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
5754 {
5755         struct task_struct *p;
5756         int cpu = (long)hcpu;
5757         unsigned long flags;
5758         struct rq *rq;
5759
5760         switch (action) {
5761
5762         case CPU_UP_PREPARE:
5763         case CPU_UP_PREPARE_FROZEN:
5764                 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
5765                 if (IS_ERR(p))
5766                         return NOTIFY_BAD;
5767                 kthread_bind(p, cpu);
5768                 /* Must be high prio: stop_machine expects to yield to it. */
5769                 rq = task_rq_lock(p, &flags);
5770                 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
5771                 task_rq_unlock(rq, &flags);
5772                 cpu_rq(cpu)->migration_thread = p;
5773                 break;
5774
5775         case CPU_ONLINE:
5776         case CPU_ONLINE_FROZEN:
5777                 /* Strictly unnecessary, as first user will wake it. */
5778                 wake_up_process(cpu_rq(cpu)->migration_thread);
5779
5780                 /* Update our root-domain */
5781                 rq = cpu_rq(cpu);
5782                 spin_lock_irqsave(&rq->lock, flags);
5783                 if (rq->rd) {
5784                         BUG_ON(!cpu_isset(cpu, rq->rd->span));
5785                         cpu_set(cpu, rq->rd->online);
5786                 }
5787                 spin_unlock_irqrestore(&rq->lock, flags);
5788                 break;
5789
5790 #ifdef CONFIG_HOTPLUG_CPU
5791         case CPU_UP_CANCELED:
5792         case CPU_UP_CANCELED_FROZEN:
5793                 if (!cpu_rq(cpu)->migration_thread)
5794                         break;
5795                 /* Unbind it from offline cpu so it can run. Fall thru. */
5796                 kthread_bind(cpu_rq(cpu)->migration_thread,
5797                              any_online_cpu(cpu_online_map));
5798                 kthread_stop(cpu_rq(cpu)->migration_thread);
5799                 cpu_rq(cpu)->migration_thread = NULL;
5800                 break;
5801
5802         case CPU_DEAD:
5803         case CPU_DEAD_FROZEN:
5804                 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
5805                 migrate_live_tasks(cpu);
5806                 rq = cpu_rq(cpu);
5807                 kthread_stop(rq->migration_thread);
5808                 rq->migration_thread = NULL;
5809                 /* Idle task back to normal (off runqueue, low prio) */
5810                 spin_lock_irq(&rq->lock);
5811                 update_rq_clock(rq);
5812                 deactivate_task(rq, rq->idle, 0);
5813                 rq->idle->static_prio = MAX_PRIO;
5814                 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
5815                 rq->idle->sched_class = &idle_sched_class;
5816                 migrate_dead_tasks(cpu);
5817                 spin_unlock_irq(&rq->lock);
5818                 cpuset_unlock();
5819                 migrate_nr_uninterruptible(rq);
5820                 BUG_ON(rq->nr_running != 0);
5821
5822                 /*
5823                  * No need to migrate the tasks: it was best-effort if
5824                  * they didn't take sched_hotcpu_mutex. Just wake up
5825                  * the requestors.
5826                  */
5827                 spin_lock_irq(&rq->lock);
5828                 while (!list_empty(&rq->migration_queue)) {
5829                         struct migration_req *req;
5830
5831                         req = list_entry(rq->migration_queue.next,
5832                                          struct migration_req, list);
5833                         list_del_init(&req->list);
5834                         complete(&req->done);
5835                 }
5836                 spin_unlock_irq(&rq->lock);
5837                 break;
5838
5839         case CPU_DOWN_PREPARE:
5840                 /* Update our root-domain */
5841                 rq = cpu_rq(cpu);
5842                 spin_lock_irqsave(&rq->lock, flags);
5843                 if (rq->rd) {
5844                         BUG_ON(!cpu_isset(cpu, rq->rd->span));
5845                         cpu_clear(cpu, rq->rd->online);
5846                 }
5847                 spin_unlock_irqrestore(&rq->lock, flags);
5848                 break;
5849 #endif
5850         }
5851         return NOTIFY_OK;
5852 }
5853
5854 /* Register at highest priority so that task migration (migrate_all_tasks)
5855  * happens before everything else.
5856  */
5857 static struct notifier_block __cpuinitdata migration_notifier = {
5858         .notifier_call = migration_call,
5859         .priority = 10
5860 };
5861
5862 void __init migration_init(void)
5863 {
5864         void *cpu = (void *)(long)smp_processor_id();
5865         int err;
5866
5867         /* Start one for the boot CPU: */
5868         err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5869         BUG_ON(err == NOTIFY_BAD);
5870         migration_call(&migration_notifier, CPU_ONLINE, cpu);
5871         register_cpu_notifier(&migration_notifier);
5872 }
5873 #endif
5874
5875 #ifdef CONFIG_SMP
5876
5877 /* Number of possible processor ids */
5878 int nr_cpu_ids __read_mostly = NR_CPUS;
5879 EXPORT_SYMBOL(nr_cpu_ids);
5880
5881 #ifdef CONFIG_SCHED_DEBUG
5882
5883 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level)
5884 {
5885         struct sched_group *group = sd->groups;
5886         cpumask_t groupmask;
5887         char str[NR_CPUS];
5888
5889         cpumask_scnprintf(str, NR_CPUS, sd->span);
5890         cpus_clear(groupmask);
5891
5892         printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
5893
5894         if (!(sd->flags & SD_LOAD_BALANCE)) {
5895                 printk("does not load-balance\n");
5896                 if (sd->parent)
5897                         printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
5898                                         " has parent");
5899                 return -1;
5900         }
5901
5902         printk(KERN_CONT "span %s\n", str);
5903
5904         if (!cpu_isset(cpu, sd->span)) {
5905                 printk(KERN_ERR "ERROR: domain->span does not contain "
5906                                 "CPU%d\n", cpu);
5907         }
5908         if (!cpu_isset(cpu, group->cpumask)) {
5909                 printk(KERN_ERR "ERROR: domain->groups does not contain"
5910                                 " CPU%d\n", cpu);
5911         }
5912
5913         printk(KERN_DEBUG "%*s groups:", level + 1, "");
5914         do {
5915                 if (!group) {
5916                         printk("\n");
5917                         printk(KERN_ERR "ERROR: group is NULL\n");
5918                         break;
5919                 }
5920
5921                 if (!group->__cpu_power) {
5922                         printk(KERN_CONT "\n");
5923                         printk(KERN_ERR "ERROR: domain->cpu_power not "
5924                                         "set\n");
5925                         break;
5926                 }
5927
5928                 if (!cpus_weight(group->cpumask)) {
5929                         printk(KERN_CONT "\n");
5930                         printk(KERN_ERR "ERROR: empty group\n");
5931                         break;
5932                 }
5933
5934                 if (cpus_intersects(groupmask, group->cpumask)) {
5935                         printk(KERN_CONT "\n");
5936                         printk(KERN_ERR "ERROR: repeated CPUs\n");
5937                         break;
5938                 }
5939
5940                 cpus_or(groupmask, groupmask, group->cpumask);
5941
5942                 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
5943                 printk(KERN_CONT " %s", str);
5944
5945                 group = group->next;
5946         } while (group != sd->groups);
5947         printk(KERN_CONT "\n");
5948
5949         if (!cpus_equal(sd->span, groupmask))
5950                 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
5951
5952         if (sd->parent && !cpus_subset(groupmask, sd->parent->span))
5953                 printk(KERN_ERR "ERROR: parent span is not a superset "
5954                         "of domain->span\n");
5955         return 0;
5956 }
5957
5958 static void sched_domain_debug(struct sched_domain *sd, int cpu)
5959 {
5960         int level = 0;
5961
5962         if (!sd) {
5963                 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5964                 return;
5965         }
5966
5967         printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5968
5969         for (;;) {
5970                 if (sched_domain_debug_one(sd, cpu, level))
5971                         break;
5972                 level++;
5973                 sd = sd->parent;
5974                 if (!sd)
5975                         break;
5976         }
5977 }
5978 #else
5979 # define sched_domain_debug(sd, cpu) do { } while (0)
5980 #endif
5981
5982 static int sd_degenerate(struct sched_domain *sd)
5983 {
5984         if (cpus_weight(sd->span) == 1)
5985                 return 1;
5986
5987         /* Following flags need at least 2 groups */
5988         if (sd->flags & (SD_LOAD_BALANCE |
5989                          SD_BALANCE_NEWIDLE |
5990                          SD_BALANCE_FORK |
5991                          SD_BALANCE_EXEC |
5992                          SD_SHARE_CPUPOWER |
5993                          SD_SHARE_PKG_RESOURCES)) {
5994                 if (sd->groups != sd->groups->next)
5995                         return 0;
5996         }
5997
5998         /* Following flags don't use groups */
5999         if (sd->flags & (SD_WAKE_IDLE |
6000                          SD_WAKE_AFFINE |
6001                          SD_WAKE_BALANCE))
6002                 return 0;
6003
6004         return 1;
6005 }
6006
6007 static int
6008 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6009 {
6010         unsigned long cflags = sd->flags, pflags = parent->flags;
6011
6012         if (sd_degenerate(parent))
6013                 return 1;
6014
6015         if (!cpus_equal(sd->span, parent->span))
6016                 return 0;
6017
6018         /* Does parent contain flags not in child? */
6019         /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6020         if (cflags & SD_WAKE_AFFINE)
6021                 pflags &= ~SD_WAKE_BALANCE;
6022         /* Flags needing groups don't count if only 1 group in parent */
6023         if (parent->groups == parent->groups->next) {
6024                 pflags &= ~(SD_LOAD_BALANCE |
6025                                 SD_BALANCE_NEWIDLE |
6026                                 SD_BALANCE_FORK |
6027                                 SD_BALANCE_EXEC |
6028                                 SD_SHARE_CPUPOWER |
6029                                 SD_SHARE_PKG_RESOURCES);
6030         }
6031         if (~cflags & pflags)
6032                 return 0;
6033
6034         return 1;
6035 }
6036
6037 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6038 {
6039         unsigned long flags;
6040         const struct sched_class *class;
6041
6042         spin_lock_irqsave(&rq->lock, flags);
6043
6044         if (rq->rd) {
6045                 struct root_domain *old_rd = rq->rd;
6046
6047                 for (class = sched_class_highest; class; class = class->next) {
6048                         if (class->leave_domain)
6049                                 class->leave_domain(rq);
6050                 }
6051
6052                 cpu_clear(rq->cpu, old_rd->span);
6053                 cpu_clear(rq->cpu, old_rd->online);
6054
6055                 if (atomic_dec_and_test(&old_rd->refcount))
6056                         kfree(old_rd);
6057         }
6058
6059         atomic_inc(&rd->refcount);
6060         rq->rd = rd;
6061
6062         cpu_set(rq->cpu, rd->span);
6063         if (cpu_isset(rq->cpu, cpu_online_map))
6064                 cpu_set(rq->cpu, rd->online);
6065
6066         for (class = sched_class_highest; class; class = class->next) {
6067                 if (class->join_domain)
6068                         class->join_domain(rq);
6069         }
6070
6071         spin_unlock_irqrestore(&rq->lock, flags);
6072 }
6073
6074 static void init_rootdomain(struct root_domain *rd)
6075 {
6076         memset(rd, 0, sizeof(*rd));
6077
6078         cpus_clear(rd->span);
6079         cpus_clear(rd->online);
6080 }
6081
6082 static void init_defrootdomain(void)
6083 {
6084         init_rootdomain(&def_root_domain);
6085         atomic_set(&def_root_domain.refcount, 1);
6086 }
6087
6088 static struct root_domain *alloc_rootdomain(void)
6089 {
6090         struct root_domain *rd;
6091
6092         rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6093         if (!rd)
6094                 return NULL;
6095
6096         init_rootdomain(rd);
6097
6098         return rd;
6099 }
6100
6101 /*
6102  * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6103  * hold the hotplug lock.
6104  */
6105 static void
6106 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6107 {
6108         struct rq *rq = cpu_rq(cpu);
6109         struct sched_domain *tmp;
6110
6111         /* Remove the sched domains which do not contribute to scheduling. */
6112         for (tmp = sd; tmp; tmp = tmp->parent) {
6113                 struct sched_domain *parent = tmp->parent;
6114                 if (!parent)
6115                         break;
6116                 if (sd_parent_degenerate(tmp, parent)) {
6117                         tmp->parent = parent->parent;
6118                         if (parent->parent)
6119                                 parent->parent->child = tmp;
6120                 }
6121         }
6122
6123         if (sd && sd_degenerate(sd)) {
6124                 sd = sd->parent;
6125                 if (sd)
6126                         sd->child = NULL;
6127         }
6128
6129         sched_domain_debug(sd, cpu);
6130
6131         rq_attach_root(rq, rd);
6132         rcu_assign_pointer(rq->sd, sd);
6133 }
6134
6135 /* cpus with isolated domains */
6136 static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
6137
6138 /* Setup the mask of cpus configured for isolated domains */
6139 static int __init isolated_cpu_setup(char *str)
6140 {
6141         int ints[NR_CPUS], i;
6142
6143         str = get_options(str, ARRAY_SIZE(ints), ints);
6144         cpus_clear(cpu_isolated_map);
6145         for (i = 1; i <= ints[0]; i++)
6146                 if (ints[i] < NR_CPUS)
6147                         cpu_set(ints[i], cpu_isolated_map);
6148         return 1;
6149 }
6150
6151 __setup("isolcpus=", isolated_cpu_setup);
6152
6153 /*
6154  * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6155  * to a function which identifies what group(along with sched group) a CPU
6156  * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6157  * (due to the fact that we keep track of groups covered with a cpumask_t).
6158  *
6159  * init_sched_build_groups will build a circular linked list of the groups
6160  * covered by the given span, and will set each group's ->cpumask correctly,
6161  * and ->cpu_power to 0.
6162  */
6163 static void
6164 init_sched_build_groups(cpumask_t span, const cpumask_t *cpu_map,
6165                         int (*group_fn)(int cpu, const cpumask_t *cpu_map,
6166                                         struct sched_group **sg))
6167 {
6168         struct sched_group *first = NULL, *last = NULL;
6169         cpumask_t covered = CPU_MASK_NONE;
6170         int i;
6171
6172         for_each_cpu_mask(i, span) {
6173                 struct sched_group *sg;
6174                 int group = group_fn(i, cpu_map, &sg);
6175                 int j;
6176
6177                 if (cpu_isset(i, covered))
6178                         continue;
6179
6180                 sg->cpumask = CPU_MASK_NONE;
6181                 sg->__cpu_power = 0;
6182
6183                 for_each_cpu_mask(j, span) {
6184                         if (group_fn(j, cpu_map, NULL) != group)
6185                                 continue;
6186
6187                         cpu_set(j, covered);
6188                         cpu_set(j, sg->cpumask);
6189                 }
6190                 if (!first)
6191                         first = sg;
6192                 if (last)
6193                         last->next = sg;
6194                 last = sg;
6195         }
6196         last->next = first;
6197 }
6198
6199 #define SD_NODES_PER_DOMAIN 16
6200
6201 #ifdef CONFIG_NUMA
6202
6203 /**
6204  * find_next_best_node - find the next node to include in a sched_domain
6205  * @node: node whose sched_domain we're building
6206  * @used_nodes: nodes already in the sched_domain
6207  *
6208  * Find the next node to include in a given scheduling domain. Simply
6209  * finds the closest node not already in the @used_nodes map.
6210  *
6211  * Should use nodemask_t.
6212  */
6213 static int find_next_best_node(int node, unsigned long *used_nodes)
6214 {
6215         int i, n, val, min_val, best_node = 0;
6216
6217         min_val = INT_MAX;
6218
6219         for (i = 0; i < MAX_NUMNODES; i++) {
6220                 /* Start at @node */
6221                 n = (node + i) % MAX_NUMNODES;
6222
6223                 if (!nr_cpus_node(n))
6224                         continue;
6225
6226                 /* Skip already used nodes */
6227                 if (test_bit(n, used_nodes))
6228                         continue;
6229
6230                 /* Simple min distance search */
6231                 val = node_distance(node, n);
6232
6233                 if (val < min_val) {
6234                         min_val = val;
6235                         best_node = n;
6236                 }
6237         }
6238
6239         set_bit(best_node, used_nodes);
6240         return best_node;
6241 }
6242
6243 /**
6244  * sched_domain_node_span - get a cpumask for a node's sched_domain
6245  * @node: node whose cpumask we're constructing
6246  * @size: number of nodes to include in this span
6247  *
6248  * Given a node, construct a good cpumask for its sched_domain to span. It
6249  * should be one that prevents unnecessary balancing, but also spreads tasks
6250  * out optimally.
6251  */
6252 static cpumask_t sched_domain_node_span(int node)
6253 {
6254         DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
6255         cpumask_t span, nodemask;
6256         int i;
6257
6258         cpus_clear(span);
6259         bitmap_zero(used_nodes, MAX_NUMNODES);
6260
6261         nodemask = node_to_cpumask(node);
6262         cpus_or(span, span, nodemask);
6263         set_bit(node, used_nodes);
6264
6265         for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
6266                 int next_node = find_next_best_node(node, used_nodes);
6267
6268                 nodemask = node_to_cpumask(next_node);
6269                 cpus_or(span, span, nodemask);
6270         }
6271
6272         return span;
6273 }
6274 #endif
6275
6276 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6277
6278 /*
6279  * SMT sched-domains:
6280  */
6281 #ifdef CONFIG_SCHED_SMT
6282 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
6283 static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
6284
6285 static int
6286 cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6287 {
6288         if (sg)
6289                 *sg = &per_cpu(sched_group_cpus, cpu);
6290         return cpu;
6291 }
6292 #endif
6293
6294 /*
6295  * multi-core sched-domains:
6296  */
6297 #ifdef CONFIG_SCHED_MC
6298 static DEFINE_PER_CPU(struct sched_domain, core_domains);
6299 static DEFINE_PER_CPU(struct sched_group, sched_group_core);
6300 #endif
6301
6302 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6303 static int
6304 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6305 {
6306         int group;
6307         cpumask_t mask = per_cpu(cpu_sibling_map, cpu);
6308         cpus_and(mask, mask, *cpu_map);
6309         group = first_cpu(mask);
6310         if (sg)
6311                 *sg = &per_cpu(sched_group_core, group);
6312         return group;
6313 }
6314 #elif defined(CONFIG_SCHED_MC)
6315 static int
6316 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6317 {
6318         if (sg)
6319                 *sg = &per_cpu(sched_group_core, cpu);
6320         return cpu;
6321 }
6322 #endif
6323
6324 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
6325 static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
6326
6327 static int
6328 cpu_to_phys_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg)
6329 {
6330         int group;
6331 #ifdef CONFIG_SCHED_MC
6332         cpumask_t mask = cpu_coregroup_map(cpu);
6333         cpus_and(mask, mask, *cpu_map);
6334         group = first_cpu(mask);
6335 #elif defined(CONFIG_SCHED_SMT)
6336         cpumask_t mask = per_cpu(cpu_sibling_map, cpu);
6337         cpus_and(mask, mask, *cpu_map);
6338         group = first_cpu(mask);
6339 #else
6340         group = cpu;
6341 #endif
6342         if (sg)
6343                 *sg = &per_cpu(sched_group_phys, group);
6344         return group;
6345 }
6346
6347 #ifdef CONFIG_NUMA
6348 /*
6349  * The init_sched_build_groups can't handle what we want to do with node
6350  * groups, so roll our own. Now each node has its own list of groups which
6351  * gets dynamically allocated.
6352  */
6353 static DEFINE_PER_CPU(struct sched_domain, node_domains);
6354 static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
6355
6356 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
6357 static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
6358
6359 static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
6360                                  struct sched_group **sg)
6361 {
6362         cpumask_t nodemask = node_to_cpumask(cpu_to_node(cpu));
6363         int group;
6364
6365         cpus_and(nodemask, nodemask, *cpu_map);
6366         group = first_cpu(nodemask);
6367
6368         if (sg)
6369                 *sg = &per_cpu(sched_group_allnodes, group);
6370         return group;
6371 }
6372
6373 static void init_numa_sched_groups_power(struct sched_group *group_head)
6374 {
6375         struct sched_group *sg = group_head;
6376         int j;
6377
6378         if (!sg)
6379                 return;
6380         do {
6381                 for_each_cpu_mask(j, sg->cpumask) {
6382                         struct sched_domain *sd;
6383
6384                         sd = &per_cpu(phys_domains, j);
6385                         if (j != first_cpu(sd->groups->cpumask)) {
6386                                 /*
6387                                  * Only add "power" once for each
6388                                  * physical package.
6389                                  */
6390                                 continue;
6391                         }
6392
6393                         sg_inc_cpu_power(sg, sd->groups->__cpu_power);
6394                 }
6395                 sg = sg->next;
6396         } while (sg != group_head);
6397 }
6398 #endif
6399
6400 #ifdef CONFIG_NUMA
6401 /* Free memory allocated for various sched_group structures */
6402 static void free_sched_groups(const cpumask_t *cpu_map)
6403 {
6404         int cpu, i;
6405
6406         for_each_cpu_mask(cpu, *cpu_map) {
6407                 struct sched_group **sched_group_nodes
6408                         = sched_group_nodes_bycpu[cpu];
6409
6410                 if (!sched_group_nodes)
6411                         continue;
6412
6413                 for (i = 0; i < MAX_NUMNODES; i++) {
6414                         cpumask_t nodemask = node_to_cpumask(i);
6415                         struct sched_group *oldsg, *sg = sched_group_nodes[i];
6416
6417                         cpus_and(nodemask, nodemask, *cpu_map);
6418                         if (cpus_empty(nodemask))
6419                                 continue;
6420
6421                         if (sg == NULL)
6422                                 continue;
6423                         sg = sg->next;
6424 next_sg:
6425                         oldsg = sg;
6426                         sg = sg->next;
6427                         kfree(oldsg);
6428                         if (oldsg != sched_group_nodes[i])
6429                                 goto next_sg;
6430                 }
6431                 kfree(sched_group_nodes);
6432                 sched_group_nodes_bycpu[cpu] = NULL;
6433         }
6434 }
6435 #else
6436 static void free_sched_groups(const cpumask_t *cpu_map)
6437 {
6438 }
6439 #endif
6440
6441 /*
6442  * Initialize sched groups cpu_power.
6443  *
6444  * cpu_power indicates the capacity of sched group, which is used while
6445  * distributing the load between different sched groups in a sched domain.
6446  * Typically cpu_power for all the groups in a sched domain will be same unless
6447  * there are asymmetries in the topology. If there are asymmetries, group
6448  * having more cpu_power will pickup more load compared to the group having
6449  * less cpu_power.
6450  *
6451  * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
6452  * the maximum number of tasks a group can handle in the presence of other idle
6453  * or lightly loaded groups in the same sched domain.
6454  */
6455 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
6456 {
6457         struct sched_domain *child;
6458         struct sched_group *group;
6459
6460         WARN_ON(!sd || !sd->groups);
6461
6462         if (cpu != first_cpu(sd->groups->cpumask))
6463                 return;
6464
6465         child = sd->child;
6466
6467         sd->groups->__cpu_power = 0;
6468
6469         /*
6470          * For perf policy, if the groups in child domain share resources
6471          * (for example cores sharing some portions of the cache hierarchy
6472          * or SMT), then set this domain groups cpu_power such that each group
6473          * can handle only one task, when there are other idle groups in the
6474          * same sched domain.
6475          */
6476         if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
6477                        (child->flags &
6478                         (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
6479                 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
6480                 return;
6481         }
6482
6483         /*
6484          * add cpu_power of each child group to this groups cpu_power
6485          */
6486         group = child->groups;
6487         do {
6488                 sg_inc_cpu_power(sd->groups, group->__cpu_power);
6489                 group = group->next;
6490         } while (group != child->groups);
6491 }
6492
6493 /*
6494  * Build sched domains for a given set of cpus and attach the sched domains
6495  * to the individual cpus
6496  */
6497 static int build_sched_domains(const cpumask_t *cpu_map)
6498 {
6499         int i;
6500         struct root_domain *rd;
6501 #ifdef CONFIG_NUMA
6502         struct sched_group **sched_group_nodes = NULL;
6503         int sd_allnodes = 0;
6504
6505         /*
6506          * Allocate the per-node list of sched groups
6507          */
6508         sched_group_nodes = kcalloc(MAX_NUMNODES, sizeof(struct sched_group *),
6509                                     GFP_KERNEL);
6510         if (!sched_group_nodes) {
6511                 printk(KERN_WARNING "Can not alloc sched group node list\n");
6512                 return -ENOMEM;
6513         }
6514         sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
6515 #endif
6516
6517         rd = alloc_rootdomain();
6518         if (!rd) {
6519                 printk(KERN_WARNING "Cannot alloc root domain\n");
6520                 return -ENOMEM;
6521         }
6522
6523         /*
6524          * Set up domains for cpus specified by the cpu_map.
6525          */
6526         for_each_cpu_mask(i, *cpu_map) {
6527                 struct sched_domain *sd = NULL, *p;
6528                 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
6529
6530                 cpus_and(nodemask, nodemask, *cpu_map);
6531
6532 #ifdef CONFIG_NUMA
6533                 if (cpus_weight(*cpu_map) >
6534                                 SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
6535                         sd = &per_cpu(allnodes_domains, i);
6536                         *sd = SD_ALLNODES_INIT;
6537                         sd->span = *cpu_map;
6538                         cpu_to_allnodes_group(i, cpu_map, &sd->groups);
6539                         p = sd;
6540                         sd_allnodes = 1;
6541                 } else
6542                         p = NULL;
6543
6544                 sd = &per_cpu(node_domains, i);
6545                 *sd = SD_NODE_INIT;
6546                 sd->span = sched_domain_node_span(cpu_to_node(i));
6547                 sd->parent = p;
6548                 if (p)
6549                         p->child = sd;
6550                 cpus_and(sd->span, sd->span, *cpu_map);
6551 #endif
6552
6553                 p = sd;
6554                 sd = &per_cpu(phys_domains, i);
6555                 *sd = SD_CPU_INIT;
6556                 sd->span = nodemask;
6557                 sd->parent = p;
6558                 if (p)
6559                         p->child = sd;
6560                 cpu_to_phys_group(i, cpu_map, &sd->groups);
6561
6562 #ifdef CONFIG_SCHED_MC
6563                 p = sd;
6564                 sd = &per_cpu(core_domains, i);
6565                 *sd = SD_MC_INIT;
6566                 sd->span = cpu_coregroup_map(i);
6567                 cpus_and(sd->span, sd->span, *cpu_map);
6568                 sd->parent = p;
6569                 p->child = sd;
6570                 cpu_to_core_group(i, cpu_map, &sd->groups);
6571 #endif
6572
6573 #ifdef CONFIG_SCHED_SMT
6574                 p = sd;
6575                 sd = &per_cpu(cpu_domains, i);
6576                 *sd = SD_SIBLING_INIT;
6577                 sd->span = per_cpu(cpu_sibling_map, i);
6578                 cpus_and(sd->span, sd->span, *cpu_map);
6579                 sd->parent = p;
6580                 p->child = sd;
6581                 cpu_to_cpu_group(i, cpu_map, &sd->groups);
6582 #endif
6583         }
6584
6585 #ifdef CONFIG_SCHED_SMT
6586         /* Set up CPU (sibling) groups */
6587         for_each_cpu_mask(i, *cpu_map) {
6588                 cpumask_t this_sibling_map = per_cpu(cpu_sibling_map, i);
6589                 cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
6590                 if (i != first_cpu(this_sibling_map))
6591                         continue;
6592
6593                 init_sched_build_groups(this_sibling_map, cpu_map,
6594                                         &cpu_to_cpu_group);
6595         }
6596 #endif
6597
6598 #ifdef CONFIG_SCHED_MC
6599         /* Set up multi-core groups */
6600         for_each_cpu_mask(i, *cpu_map) {
6601                 cpumask_t this_core_map = cpu_coregroup_map(i);
6602                 cpus_and(this_core_map, this_core_map, *cpu_map);
6603                 if (i != first_cpu(this_core_map))
6604                         continue;
6605                 init_sched_build_groups(this_core_map, cpu_map,
6606                                         &cpu_to_core_group);
6607         }
6608 #endif
6609
6610         /* Set up physical groups */
6611         for (i = 0; i < MAX_NUMNODES; i++) {
6612                 cpumask_t nodemask = node_to_cpumask(i);
6613
6614                 cpus_and(nodemask, nodemask, *cpu_map);
6615                 if (cpus_empty(nodemask))
6616                         continue;
6617
6618                 init_sched_build_groups(nodemask, cpu_map, &cpu_to_phys_group);
6619         }
6620
6621 #ifdef CONFIG_NUMA
6622         /* Set up node groups */
6623         if (sd_allnodes)
6624                 init_sched_build_groups(*cpu_map, cpu_map,
6625                                         &cpu_to_allnodes_group);
6626
6627         for (i = 0; i < MAX_NUMNODES; i++) {
6628                 /* Set up node groups */
6629                 struct sched_group *sg, *prev;
6630                 cpumask_t nodemask = node_to_cpumask(i);
6631                 cpumask_t domainspan;
6632                 cpumask_t covered = CPU_MASK_NONE;
6633                 int j;
6634
6635                 cpus_and(nodemask, nodemask, *cpu_map);
6636                 if (cpus_empty(nodemask)) {
6637                         sched_group_nodes[i] = NULL;
6638                         continue;
6639                 }
6640
6641                 domainspan = sched_domain_node_span(i);
6642                 cpus_and(domainspan, domainspan, *cpu_map);
6643
6644                 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
6645                 if (!sg) {
6646                         printk(KERN_WARNING "Can not alloc domain group for "
6647                                 "node %d\n", i);
6648                         goto error;
6649                 }
6650                 sched_group_nodes[i] = sg;
6651                 for_each_cpu_mask(j, nodemask) {
6652                         struct sched_domain *sd;
6653
6654                         sd = &per_cpu(node_domains, j);
6655                         sd->groups = sg;
6656                 }
6657                 sg->__cpu_power = 0;
6658                 sg->cpumask = nodemask;
6659                 sg->next = sg;
6660                 cpus_or(covered, covered, nodemask);
6661                 prev = sg;
6662
6663                 for (j = 0; j < MAX_NUMNODES; j++) {
6664                         cpumask_t tmp, notcovered;
6665                         int n = (i + j) % MAX_NUMNODES;
6666
6667                         cpus_complement(notcovered, covered);
6668                         cpus_and(tmp, notcovered, *cpu_map);
6669                         cpus_and(tmp, tmp, domainspan);
6670                         if (cpus_empty(tmp))
6671                                 break;
6672
6673                         nodemask = node_to_cpumask(n);
6674                         cpus_and(tmp, tmp, nodemask);
6675                         if (cpus_empty(tmp))
6676                                 continue;
6677
6678                         sg = kmalloc_node(sizeof(struct sched_group),
6679                                           GFP_KERNEL, i);
6680                         if (!sg) {
6681                                 printk(KERN_WARNING
6682                                 "Can not alloc domain group for node %d\n", j);
6683                                 goto error;
6684                         }
6685                         sg->__cpu_power = 0;
6686                         sg->cpumask = tmp;
6687                         sg->next = prev->next;
6688                         cpus_or(covered, covered, tmp);
6689                         prev->next = sg;
6690                         prev = sg;
6691                 }
6692         }
6693 #endif
6694
6695         /* Calculate CPU power for physical packages and nodes */
6696 #ifdef CONFIG_SCHED_SMT
6697         for_each_cpu_mask(i, *cpu_map) {
6698                 struct sched_domain *sd = &per_cpu(cpu_domains, i);
6699
6700                 init_sched_groups_power(i, sd);
6701         }
6702 #endif
6703 #ifdef CONFIG_SCHED_MC
6704         for_each_cpu_mask(i, *cpu_map) {
6705                 struct sched_domain *sd = &per_cpu(core_domains, i);
6706
6707                 init_sched_groups_power(i, sd);
6708         }
6709 #endif
6710
6711         for_each_cpu_mask(i, *cpu_map) {
6712                 struct sched_domain *sd = &per_cpu(phys_domains, i);
6713
6714                 init_sched_groups_power(i, sd);
6715         }
6716
6717 #ifdef CONFIG_NUMA
6718         for (i = 0; i < MAX_NUMNODES; i++)
6719                 init_numa_sched_groups_power(sched_group_nodes[i]);
6720
6721         if (sd_allnodes) {
6722                 struct sched_group *sg;
6723
6724                 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg);
6725                 init_numa_sched_groups_power(sg);
6726         }
6727 #endif
6728
6729         /* Attach the domains */
6730         for_each_cpu_mask(i, *cpu_map) {
6731                 struct sched_domain *sd;
6732 #ifdef CONFIG_SCHED_SMT
6733                 sd = &per_cpu(cpu_domains, i);
6734 #elif defined(CONFIG_SCHED_MC)
6735                 sd = &per_cpu(core_domains, i);
6736 #else
6737                 sd = &per_cpu(phys_domains, i);
6738 #endif
6739                 cpu_attach_domain(sd, rd, i);
6740         }
6741
6742         return 0;
6743
6744 #ifdef CONFIG_NUMA
6745 error:
6746         free_sched_groups(cpu_map);
6747         return -ENOMEM;
6748 #endif
6749 }
6750
6751 static cpumask_t *doms_cur;     /* current sched domains */
6752 static int ndoms_cur;           /* number of sched domains in 'doms_cur' */
6753
6754 /*
6755  * Special case: If a kmalloc of a doms_cur partition (array of
6756  * cpumask_t) fails, then fallback to a single sched domain,
6757  * as determined by the single cpumask_t fallback_doms.
6758  */
6759 static cpumask_t fallback_doms;
6760
6761 /*
6762  * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6763  * For now this just excludes isolated cpus, but could be used to
6764  * exclude other special cases in the future.
6765  */
6766 static int arch_init_sched_domains(const cpumask_t *cpu_map)
6767 {
6768         int err;
6769
6770         ndoms_cur = 1;
6771         doms_cur = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
6772         if (!doms_cur)
6773                 doms_cur = &fallback_doms;
6774         cpus_andnot(*doms_cur, *cpu_map, cpu_isolated_map);
6775         err = build_sched_domains(doms_cur);
6776         register_sched_domain_sysctl();
6777
6778         return err;
6779 }
6780
6781 static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
6782 {
6783         free_sched_groups(cpu_map);
6784 }
6785
6786 /*
6787  * Detach sched domains from a group of cpus specified in cpu_map
6788  * These cpus will now be attached to the NULL domain
6789  */
6790 static void detach_destroy_domains(const cpumask_t *cpu_map)
6791 {
6792         int i;
6793
6794         unregister_sched_domain_sysctl();
6795
6796         for_each_cpu_mask(i, *cpu_map)
6797                 cpu_attach_domain(NULL, &def_root_domain, i);
6798         synchronize_sched();
6799         arch_destroy_sched_domains(cpu_map);
6800 }
6801
6802 /*
6803  * Partition sched domains as specified by the 'ndoms_new'
6804  * cpumasks in the array doms_new[] of cpumasks. This compares
6805  * doms_new[] to the current sched domain partitioning, doms_cur[].
6806  * It destroys each deleted domain and builds each new domain.
6807  *
6808  * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
6809  * The masks don't intersect (don't overlap.) We should setup one
6810  * sched domain for each mask. CPUs not in any of the cpumasks will
6811  * not be load balanced. If the same cpumask appears both in the
6812  * current 'doms_cur' domains and in the new 'doms_new', we can leave
6813  * it as it is.
6814  *
6815  * The passed in 'doms_new' should be kmalloc'd. This routine takes
6816  * ownership of it and will kfree it when done with it. If the caller
6817  * failed the kmalloc call, then it can pass in doms_new == NULL,
6818  * and partition_sched_domains() will fallback to the single partition
6819  * 'fallback_doms'.
6820  *
6821  * Call with hotplug lock held
6822  */
6823 void partition_sched_domains(int ndoms_new, cpumask_t *doms_new)
6824 {
6825         int i, j;
6826
6827         lock_doms_cur();
6828
6829         /* always unregister in case we don't destroy any domains */
6830         unregister_sched_domain_sysctl();
6831
6832         if (doms_new == NULL) {
6833                 ndoms_new = 1;
6834                 doms_new = &fallback_doms;
6835                 cpus_andnot(doms_new[0], cpu_online_map, cpu_isolated_map);
6836         }
6837
6838         /* Destroy deleted domains */
6839         for (i = 0; i < ndoms_cur; i++) {
6840                 for (j = 0; j < ndoms_new; j++) {
6841                         if (cpus_equal(doms_cur[i], doms_new[j]))
6842                                 goto match1;
6843                 }
6844                 /* no match - a current sched domain not in new doms_new[] */
6845                 detach_destroy_domains(doms_cur + i);
6846 match1:
6847                 ;
6848         }
6849
6850         /* Build new domains */
6851         for (i = 0; i < ndoms_new; i++) {
6852                 for (j = 0; j < ndoms_cur; j++) {
6853                         if (cpus_equal(doms_new[i], doms_cur[j]))
6854                                 goto match2;
6855                 }
6856                 /* no match - add a new doms_new */
6857                 build_sched_domains(doms_new + i);
6858 match2:
6859                 ;
6860         }
6861
6862         /* Remember the new sched domains */
6863         if (doms_cur != &fallback_doms)
6864                 kfree(doms_cur);
6865         doms_cur = doms_new;
6866         ndoms_cur = ndoms_new;
6867
6868         register_sched_domain_sysctl();
6869
6870         unlock_doms_cur();
6871 }
6872
6873 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
6874 static int arch_reinit_sched_domains(void)
6875 {
6876         int err;
6877
6878         get_online_cpus();
6879         detach_destroy_domains(&cpu_online_map);
6880         err = arch_init_sched_domains(&cpu_online_map);
6881         put_online_cpus();
6882
6883         return err;
6884 }
6885
6886 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
6887 {
6888         int ret;
6889
6890         if (buf[0] != '0' && buf[0] != '1')
6891                 return -EINVAL;
6892
6893         if (smt)
6894                 sched_smt_power_savings = (buf[0] == '1');
6895         else
6896                 sched_mc_power_savings = (buf[0] == '1');
6897
6898         ret = arch_reinit_sched_domains();
6899
6900         return ret ? ret : count;
6901 }
6902
6903 #ifdef CONFIG_SCHED_MC
6904 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
6905 {
6906         return sprintf(page, "%u\n", sched_mc_power_savings);
6907 }
6908 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
6909                                             const char *buf, size_t count)
6910 {
6911         return sched_power_savings_store(buf, count, 0);
6912 }
6913 static SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
6914                    sched_mc_power_savings_store);
6915 #endif
6916
6917 #ifdef CONFIG_SCHED_SMT
6918 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
6919 {
6920         return sprintf(page, "%u\n", sched_smt_power_savings);
6921 }
6922 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
6923                                              const char *buf, size_t count)
6924 {
6925         return sched_power_savings_store(buf, count, 1);
6926 }
6927 static SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
6928                    sched_smt_power_savings_store);
6929 #endif
6930
6931 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
6932 {
6933         int err = 0;
6934
6935 #ifdef CONFIG_SCHED_SMT
6936         if (smt_capable())
6937                 err = sysfs_create_file(&cls->kset.kobj,
6938                                         &attr_sched_smt_power_savings.attr);
6939 #endif
6940 #ifdef CONFIG_SCHED_MC
6941         if (!err && mc_capable())
6942                 err = sysfs_create_file(&cls->kset.kobj,
6943                                         &attr_sched_mc_power_savings.attr);
6944 #endif
6945         return err;
6946 }
6947 #endif
6948
6949 /*
6950  * Force a reinitialization of the sched domains hierarchy. The domains
6951  * and groups cannot be updated in place without racing with the balancing
6952  * code, so we temporarily attach all running cpus to the NULL domain
6953  * which will prevent rebalancing while the sched domains are recalculated.
6954  */
6955 static int update_sched_domains(struct notifier_block *nfb,
6956                                 unsigned long action, void *hcpu)
6957 {
6958         switch (action) {
6959         case CPU_UP_PREPARE:
6960         case CPU_UP_PREPARE_FROZEN:
6961         case CPU_DOWN_PREPARE:
6962         case CPU_DOWN_PREPARE_FROZEN:
6963                 detach_destroy_domains(&cpu_online_map);
6964                 return NOTIFY_OK;
6965
6966         case CPU_UP_CANCELED:
6967         case CPU_UP_CANCELED_FROZEN:
6968         case CPU_DOWN_FAILED:
6969         case CPU_DOWN_FAILED_FROZEN:
6970         case CPU_ONLINE:
6971         case CPU_ONLINE_FROZEN:
6972         case CPU_DEAD:
6973         case CPU_DEAD_FROZEN:
6974                 /*
6975                  * Fall through and re-initialise the domains.
6976                  */
6977                 break;
6978         default:
6979                 return NOTIFY_DONE;
6980         }
6981
6982         /* The hotplug lock is already held by cpu_up/cpu_down */
6983         arch_init_sched_domains(&cpu_online_map);
6984
6985         return NOTIFY_OK;
6986 }
6987
6988 void __init sched_init_smp(void)
6989 {
6990         cpumask_t non_isolated_cpus;
6991
6992         get_online_cpus();
6993         arch_init_sched_domains(&cpu_online_map);
6994         cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
6995         if (cpus_empty(non_isolated_cpus))
6996                 cpu_set(smp_processor_id(), non_isolated_cpus);
6997         put_online_cpus();
6998         /* XXX: Theoretical race here - CPU may be hotplugged now */
6999         hotcpu_notifier(update_sched_domains, 0);
7000
7001         /* Move init over to a non-isolated CPU */
7002         if (set_cpus_allowed(current, non_isolated_cpus) < 0)
7003                 BUG();
7004         sched_init_granularity();
7005
7006 #ifdef CONFIG_FAIR_GROUP_SCHED
7007         if (nr_cpu_ids == 1)
7008                 return;
7009
7010         lb_monitor_task = kthread_create(load_balance_monitor, NULL,
7011                                          "group_balance");
7012         if (!IS_ERR(lb_monitor_task)) {
7013                 lb_monitor_task->flags |= PF_NOFREEZE;
7014                 wake_up_process(lb_monitor_task);
7015         } else {
7016                 printk(KERN_ERR "Could not create load balance monitor thread"
7017                         "(error = %ld) \n", PTR_ERR(lb_monitor_task));
7018         }
7019 #endif
7020 }
7021 #else
7022 void __init sched_init_smp(void)
7023 {
7024         sched_init_granularity();
7025 }
7026 #endif /* CONFIG_SMP */
7027
7028 int in_sched_functions(unsigned long addr)
7029 {
7030         return in_lock_functions(addr) ||
7031                 (addr >= (unsigned long)__sched_text_start
7032                 && addr < (unsigned long)__sched_text_end);
7033 }
7034
7035 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
7036 {
7037         cfs_rq->tasks_timeline = RB_ROOT;
7038 #ifdef CONFIG_FAIR_GROUP_SCHED
7039         cfs_rq->rq = rq;
7040 #endif
7041         cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7042 }
7043
7044 void __init sched_init(void)
7045 {
7046         int highest_cpu = 0;
7047         int i, j;
7048
7049 #ifdef CONFIG_SMP
7050         init_defrootdomain();
7051 #endif
7052
7053         for_each_possible_cpu(i) {
7054                 struct rt_prio_array *array;
7055                 struct rq *rq;
7056
7057                 rq = cpu_rq(i);
7058                 spin_lock_init(&rq->lock);
7059                 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
7060                 rq->nr_running = 0;
7061                 rq->clock = 1;
7062                 init_cfs_rq(&rq->cfs, rq);
7063 #ifdef CONFIG_FAIR_GROUP_SCHED
7064                 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7065                 {
7066                         struct cfs_rq *cfs_rq = &per_cpu(init_cfs_rq, i);
7067                         struct sched_entity *se =
7068                                          &per_cpu(init_sched_entity, i);
7069
7070                         init_cfs_rq_p[i] = cfs_rq;
7071                         init_cfs_rq(cfs_rq, rq);
7072                         cfs_rq->tg = &init_task_group;
7073                         list_add(&cfs_rq->leaf_cfs_rq_list,
7074                                                          &rq->leaf_cfs_rq_list);
7075
7076                         init_sched_entity_p[i] = se;
7077                         se->cfs_rq = &rq->cfs;
7078                         se->my_q = cfs_rq;
7079                         se->load.weight = init_task_group_load;
7080                         se->load.inv_weight =
7081                                  div64_64(1ULL<<32, init_task_group_load);
7082                         se->parent = NULL;
7083                 }
7084                 init_task_group.shares = init_task_group_load;
7085 #endif
7086
7087                 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7088                         rq->cpu_load[j] = 0;
7089 #ifdef CONFIG_SMP
7090                 rq->sd = NULL;
7091                 rq->rd = NULL;
7092                 rq->active_balance = 0;
7093                 rq->next_balance = jiffies;
7094                 rq->push_cpu = 0;
7095                 rq->cpu = i;
7096                 rq->migration_thread = NULL;
7097                 INIT_LIST_HEAD(&rq->migration_queue);
7098                 rq->rt.highest_prio = MAX_RT_PRIO;
7099                 rq->rt.overloaded = 0;
7100                 rq_attach_root(rq, &def_root_domain);
7101 #endif
7102                 init_rq_hrtick(rq);
7103
7104                 atomic_set(&rq->nr_iowait, 0);
7105
7106                 array = &rq->rt.active;
7107                 for (j = 0; j < MAX_RT_PRIO; j++) {
7108                         INIT_LIST_HEAD(array->queue + j);
7109                         __clear_bit(j, array->bitmap);
7110                 }
7111                 highest_cpu = i;
7112                 /* delimiter for bitsearch: */
7113                 __set_bit(MAX_RT_PRIO, array->bitmap);
7114         }
7115
7116         set_load_weight(&init_task);
7117
7118 #ifdef CONFIG_PREEMPT_NOTIFIERS
7119         INIT_HLIST_HEAD(&init_task.preempt_notifiers);
7120 #endif
7121
7122 #ifdef CONFIG_SMP
7123         nr_cpu_ids = highest_cpu + 1;
7124         open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
7125 #endif
7126
7127 #ifdef CONFIG_RT_MUTEXES
7128         plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
7129 #endif
7130
7131         /*
7132          * The boot idle thread does lazy MMU switching as well:
7133          */
7134         atomic_inc(&init_mm.mm_count);
7135         enter_lazy_tlb(&init_mm, current);
7136
7137         /*
7138          * Make us the idle thread. Technically, schedule() should not be
7139          * called from this thread, however somewhere below it might be,
7140          * but because we are the idle thread, we just pick up running again
7141          * when this runqueue becomes "idle".
7142          */
7143         init_idle(current, smp_processor_id());
7144         /*
7145          * During early bootup we pretend to be a normal task:
7146          */
7147         current->sched_class = &fair_sched_class;
7148 }
7149
7150 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
7151 void __might_sleep(char *file, int line)
7152 {
7153 #ifdef in_atomic
7154         static unsigned long prev_jiffy;        /* ratelimiting */
7155
7156         if ((in_atomic() || irqs_disabled()) &&
7157             system_state == SYSTEM_RUNNING && !oops_in_progress) {
7158                 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7159                         return;
7160                 prev_jiffy = jiffies;
7161                 printk(KERN_ERR "BUG: sleeping function called from invalid"
7162                                 " context at %s:%d\n", file, line);
7163                 printk("in_atomic():%d, irqs_disabled():%d\n",
7164                         in_atomic(), irqs_disabled());
7165                 debug_show_held_locks(current);
7166                 if (irqs_disabled())
7167                         print_irqtrace_events(current);
7168                 dump_stack();
7169         }
7170 #endif
7171 }
7172 EXPORT_SYMBOL(__might_sleep);
7173 #endif
7174
7175 #ifdef CONFIG_MAGIC_SYSRQ
7176 static void normalize_task(struct rq *rq, struct task_struct *p)
7177 {
7178         int on_rq;
7179         update_rq_clock(rq);
7180         on_rq = p->se.on_rq;
7181         if (on_rq)
7182                 deactivate_task(rq, p, 0);
7183         __setscheduler(rq, p, SCHED_NORMAL, 0);
7184         if (on_rq) {
7185                 activate_task(rq, p, 0);
7186                 resched_task(rq->curr);
7187         }
7188 }
7189
7190 void normalize_rt_tasks(void)
7191 {
7192         struct task_struct *g, *p;
7193         unsigned long flags;
7194         struct rq *rq;
7195
7196         read_lock_irq(&tasklist_lock);
7197         do_each_thread(g, p) {
7198                 /*
7199                  * Only normalize user tasks:
7200                  */
7201                 if (!p->mm)
7202                         continue;
7203
7204                 p->se.exec_start                = 0;
7205 #ifdef CONFIG_SCHEDSTATS
7206                 p->se.wait_start                = 0;
7207                 p->se.sleep_start               = 0;
7208                 p->se.block_start               = 0;
7209 #endif
7210                 task_rq(p)->clock               = 0;
7211
7212                 if (!rt_task(p)) {
7213                         /*
7214                          * Renice negative nice level userspace
7215                          * tasks back to 0:
7216                          */
7217                         if (TASK_NICE(p) < 0 && p->mm)
7218                                 set_user_nice(p, 0);
7219                         continue;
7220                 }
7221
7222                 spin_lock_irqsave(&p->pi_lock, flags);
7223                 rq = __task_rq_lock(p);
7224
7225                 normalize_task(rq, p);
7226
7227                 __task_rq_unlock(rq);
7228                 spin_unlock_irqrestore(&p->pi_lock, flags);
7229         } while_each_thread(g, p);
7230
7231         read_unlock_irq(&tasklist_lock);
7232 }
7233
7234 #endif /* CONFIG_MAGIC_SYSRQ */
7235
7236 #ifdef CONFIG_IA64
7237 /*
7238  * These functions are only useful for the IA64 MCA handling.
7239  *
7240  * They can only be called when the whole system has been
7241  * stopped - every CPU needs to be quiescent, and no scheduling
7242  * activity can take place. Using them for anything else would
7243  * be a serious bug, and as a result, they aren't even visible
7244  * under any other configuration.
7245  */
7246
7247 /**
7248  * curr_task - return the current task for a given cpu.
7249  * @cpu: the processor in question.
7250  *
7251  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7252  */
7253 struct task_struct *curr_task(int cpu)
7254 {
7255         return cpu_curr(cpu);
7256 }
7257
7258 /**
7259  * set_curr_task - set the current task for a given cpu.
7260  * @cpu: the processor in question.
7261  * @p: the task pointer to set.
7262  *
7263  * Description: This function must only be used when non-maskable interrupts
7264  * are serviced on a separate stack. It allows the architecture to switch the
7265  * notion of the current task on a cpu in a non-blocking manner. This function
7266  * must be called with all CPU's synchronized, and interrupts disabled, the
7267  * and caller must save the original value of the current task (see
7268  * curr_task() above) and restore that value before reenabling interrupts and
7269  * re-starting the system.
7270  *
7271  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7272  */
7273 void set_curr_task(int cpu, struct task_struct *p)
7274 {
7275         cpu_curr(cpu) = p;
7276 }
7277
7278 #endif
7279
7280 #ifdef CONFIG_FAIR_GROUP_SCHED
7281
7282 #ifdef CONFIG_SMP
7283 /*
7284  * distribute shares of all task groups among their schedulable entities,
7285  * to reflect load distrbution across cpus.
7286  */
7287 static int rebalance_shares(struct sched_domain *sd, int this_cpu)
7288 {
7289         struct cfs_rq *cfs_rq;
7290         struct rq *rq = cpu_rq(this_cpu);
7291         cpumask_t sdspan = sd->span;
7292         int balanced = 1;
7293
7294         /* Walk thr' all the task groups that we have */
7295         for_each_leaf_cfs_rq(rq, cfs_rq) {
7296                 int i;
7297                 unsigned long total_load = 0, total_shares;
7298                 struct task_group *tg = cfs_rq->tg;
7299
7300                 /* Gather total task load of this group across cpus */
7301                 for_each_cpu_mask(i, sdspan)
7302                         total_load += tg->cfs_rq[i]->load.weight;
7303
7304                 /* Nothing to do if this group has no load */
7305                 if (!total_load)
7306                         continue;
7307
7308                 /*
7309                  * tg->shares represents the number of cpu shares the task group
7310                  * is eligible to hold on a single cpu. On N cpus, it is
7311                  * eligible to hold (N * tg->shares) number of cpu shares.
7312                  */
7313                 total_shares = tg->shares * cpus_weight(sdspan);
7314
7315                 /*
7316                  * redistribute total_shares across cpus as per the task load
7317                  * distribution.
7318                  */
7319                 for_each_cpu_mask(i, sdspan) {
7320                         unsigned long local_load, local_shares;
7321
7322                         local_load = tg->cfs_rq[i]->load.weight;
7323                         local_shares = (local_load * total_shares) / total_load;
7324                         if (!local_shares)
7325                                 local_shares = MIN_GROUP_SHARES;
7326                         if (local_shares == tg->se[i]->load.weight)
7327                                 continue;
7328
7329                         spin_lock_irq(&cpu_rq(i)->lock);
7330                         set_se_shares(tg->se[i], local_shares);
7331                         spin_unlock_irq(&cpu_rq(i)->lock);
7332                         balanced = 0;
7333                 }
7334         }
7335
7336         return balanced;
7337 }
7338
7339 /*
7340  * How frequently should we rebalance_shares() across cpus?
7341  *
7342  * The more frequently we rebalance shares, the more accurate is the fairness
7343  * of cpu bandwidth distribution between task groups. However higher frequency
7344  * also implies increased scheduling overhead.
7345  *
7346  * sysctl_sched_min_bal_int_shares represents the minimum interval between
7347  * consecutive calls to rebalance_shares() in the same sched domain.
7348  *
7349  * sysctl_sched_max_bal_int_shares represents the maximum interval between
7350  * consecutive calls to rebalance_shares() in the same sched domain.
7351  *
7352  * These settings allows for the appropriate tradeoff between accuracy of
7353  * fairness and the associated overhead.
7354  *
7355  */
7356
7357 /* default: 8ms, units: milliseconds */
7358 const_debug unsigned int sysctl_sched_min_bal_int_shares = 8;
7359
7360 /* default: 128ms, units: milliseconds */
7361 const_debug unsigned int sysctl_sched_max_bal_int_shares = 128;
7362
7363 /* kernel thread that runs rebalance_shares() periodically */
7364 static int load_balance_monitor(void *unused)
7365 {
7366         unsigned int timeout = sysctl_sched_min_bal_int_shares;
7367         struct sched_param schedparm;
7368         int ret;
7369
7370         /*
7371          * We don't want this thread's execution to be limited by the shares
7372          * assigned to default group (init_task_group). Hence make it run
7373          * as a SCHED_RR RT task at the lowest priority.
7374          */
7375         schedparm.sched_priority = 1;
7376         ret = sched_setscheduler(current, SCHED_RR, &schedparm);
7377         if (ret)
7378                 printk(KERN_ERR "Couldn't set SCHED_RR policy for load balance"
7379                                 " monitor thread (error = %d) \n", ret);
7380
7381         while (!kthread_should_stop()) {
7382                 int i, cpu, balanced = 1;
7383
7384                 /* Prevent cpus going down or coming up */
7385                 get_online_cpus();
7386                 /* lockout changes to doms_cur[] array */
7387                 lock_doms_cur();
7388                 /*
7389                  * Enter a rcu read-side critical section to safely walk rq->sd
7390                  * chain on various cpus and to walk task group list
7391                  * (rq->leaf_cfs_rq_list) in rebalance_shares().
7392                  */
7393                 rcu_read_lock();
7394
7395                 for (i = 0; i < ndoms_cur; i++) {
7396                         cpumask_t cpumap = doms_cur[i];
7397                         struct sched_domain *sd = NULL, *sd_prev = NULL;
7398
7399                         cpu = first_cpu(cpumap);
7400
7401                         /* Find the highest domain at which to balance shares */
7402                         for_each_domain(cpu, sd) {
7403                                 if (!(sd->flags & SD_LOAD_BALANCE))
7404                                         continue;
7405                                 sd_prev = sd;
7406                         }
7407
7408                         sd = sd_prev;
7409                         /* sd == NULL? No load balance reqd in this domain */
7410                         if (!sd)
7411                                 continue;
7412
7413                         balanced &= rebalance_shares(sd, cpu);
7414                 }
7415
7416                 rcu_read_unlock();
7417
7418                 unlock_doms_cur();
7419                 put_online_cpus();
7420
7421                 if (!balanced)
7422                         timeout = sysctl_sched_min_bal_int_shares;
7423                 else if (timeout < sysctl_sched_max_bal_int_shares)
7424                         timeout *= 2;
7425
7426                 msleep_interruptible(timeout);
7427         }
7428
7429         return 0;
7430 }
7431 #endif  /* CONFIG_SMP */
7432
7433 /* allocate runqueue etc for a new task group */
7434 struct task_group *sched_create_group(void)
7435 {
7436         struct task_group *tg;
7437         struct cfs_rq *cfs_rq;
7438         struct sched_entity *se;
7439         struct rq *rq;
7440         int i;
7441
7442         tg = kzalloc(sizeof(*tg), GFP_KERNEL);
7443         if (!tg)
7444                 return ERR_PTR(-ENOMEM);
7445
7446         tg->cfs_rq = kzalloc(sizeof(cfs_rq) * NR_CPUS, GFP_KERNEL);
7447         if (!tg->cfs_rq)
7448                 goto err;
7449         tg->se = kzalloc(sizeof(se) * NR_CPUS, GFP_KERNEL);
7450         if (!tg->se)
7451                 goto err;
7452
7453         for_each_possible_cpu(i) {
7454                 rq = cpu_rq(i);
7455
7456                 cfs_rq = kmalloc_node(sizeof(struct cfs_rq), GFP_KERNEL,
7457                                                          cpu_to_node(i));
7458                 if (!cfs_rq)
7459                         goto err;
7460
7461                 se = kmalloc_node(sizeof(struct sched_entity), GFP_KERNEL,
7462                                                         cpu_to_node(i));
7463                 if (!se)
7464                         goto err;
7465
7466                 memset(cfs_rq, 0, sizeof(struct cfs_rq));
7467                 memset(se, 0, sizeof(struct sched_entity));
7468
7469                 tg->cfs_rq[i] = cfs_rq;
7470                 init_cfs_rq(cfs_rq, rq);
7471                 cfs_rq->tg = tg;
7472
7473                 tg->se[i] = se;
7474                 se->cfs_rq = &rq->cfs;
7475                 se->my_q = cfs_rq;
7476                 se->load.weight = NICE_0_LOAD;
7477                 se->load.inv_weight = div64_64(1ULL<<32, NICE_0_LOAD);
7478                 se->parent = NULL;
7479         }
7480
7481         tg->shares = NICE_0_LOAD;
7482
7483         lock_task_group_list();
7484         for_each_possible_cpu(i) {
7485                 rq = cpu_rq(i);
7486                 cfs_rq = tg->cfs_rq[i];
7487                 list_add_rcu(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
7488         }
7489         unlock_task_group_list();
7490
7491         return tg;
7492
7493 err:
7494         for_each_possible_cpu(i) {
7495                 if (tg->cfs_rq)
7496                         kfree(tg->cfs_rq[i]);
7497                 if (tg->se)
7498                         kfree(tg->se[i]);
7499         }
7500         kfree(tg->cfs_rq);
7501         kfree(tg->se);
7502         kfree(tg);
7503
7504         return ERR_PTR(-ENOMEM);
7505 }
7506
7507 /* rcu callback to free various structures associated with a task group */
7508 static void free_sched_group(struct rcu_head *rhp)
7509 {
7510         struct task_group *tg = container_of(rhp, struct task_group, rcu);
7511         struct cfs_rq *cfs_rq;
7512         struct sched_entity *se;
7513         int i;
7514
7515         /* now it should be safe to free those cfs_rqs */
7516         for_each_possible_cpu(i) {
7517                 cfs_rq = tg->cfs_rq[i];
7518                 kfree(cfs_rq);
7519
7520                 se = tg->se[i];
7521                 kfree(se);
7522         }
7523
7524         kfree(tg->cfs_rq);
7525         kfree(tg->se);
7526         kfree(tg);
7527 }
7528
7529 /* Destroy runqueue etc associated with a task group */
7530 void sched_destroy_group(struct task_group *tg)
7531 {
7532         struct cfs_rq *cfs_rq = NULL;
7533         int i;
7534
7535         lock_task_group_list();
7536         for_each_possible_cpu(i) {
7537                 cfs_rq = tg->cfs_rq[i];
7538                 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
7539         }
7540         unlock_task_group_list();
7541
7542         BUG_ON(!cfs_rq);
7543
7544         /* wait for possible concurrent references to cfs_rqs complete */
7545         call_rcu(&tg->rcu, free_sched_group);
7546 }
7547
7548 /* change task's runqueue when it moves between groups.
7549  *      The caller of this function should have put the task in its new group
7550  *      by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
7551  *      reflect its new group.
7552  */
7553 void sched_move_task(struct task_struct *tsk)
7554 {
7555         int on_rq, running;
7556         unsigned long flags;
7557         struct rq *rq;
7558
7559         rq = task_rq_lock(tsk, &flags);
7560
7561         if (tsk->sched_class != &fair_sched_class) {
7562                 set_task_cfs_rq(tsk, task_cpu(tsk));
7563                 goto done;
7564         }
7565
7566         update_rq_clock(rq);
7567
7568         running = task_current(rq, tsk);
7569         on_rq = tsk->se.on_rq;
7570
7571         if (on_rq) {
7572                 dequeue_task(rq, tsk, 0);
7573                 if (unlikely(running))
7574                         tsk->sched_class->put_prev_task(rq, tsk);
7575         }
7576
7577         set_task_cfs_rq(tsk, task_cpu(tsk));
7578
7579         if (on_rq) {
7580                 if (unlikely(running))
7581                         tsk->sched_class->set_curr_task(rq);
7582                 enqueue_task(rq, tsk, 0);
7583         }
7584
7585 done:
7586         task_rq_unlock(rq, &flags);
7587 }
7588
7589 /* rq->lock to be locked by caller */
7590 static void set_se_shares(struct sched_entity *se, unsigned long shares)
7591 {
7592         struct cfs_rq *cfs_rq = se->cfs_rq;
7593         struct rq *rq = cfs_rq->rq;
7594         int on_rq;
7595
7596         if (!shares)
7597                 shares = MIN_GROUP_SHARES;
7598
7599         on_rq = se->on_rq;
7600         if (on_rq) {
7601                 dequeue_entity(cfs_rq, se, 0);
7602                 dec_cpu_load(rq, se->load.weight);
7603         }
7604
7605         se->load.weight = shares;
7606         se->load.inv_weight = div64_64((1ULL<<32), shares);
7607
7608         if (on_rq) {
7609                 enqueue_entity(cfs_rq, se, 0);
7610                 inc_cpu_load(rq, se->load.weight);
7611         }
7612 }
7613
7614 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
7615 {
7616         int i;
7617         struct cfs_rq *cfs_rq;
7618         struct rq *rq;
7619
7620         lock_task_group_list();
7621         if (tg->shares == shares)
7622                 goto done;
7623
7624         if (shares < MIN_GROUP_SHARES)
7625                 shares = MIN_GROUP_SHARES;
7626
7627         /*
7628          * Prevent any load balance activity (rebalance_shares,
7629          * load_balance_fair) from referring to this group first,
7630          * by taking it off the rq->leaf_cfs_rq_list on each cpu.
7631          */
7632         for_each_possible_cpu(i) {
7633                 cfs_rq = tg->cfs_rq[i];
7634                 list_del_rcu(&cfs_rq->leaf_cfs_rq_list);
7635         }
7636
7637         /* wait for any ongoing reference to this group to finish */
7638         synchronize_sched();
7639
7640         /*
7641          * Now we are free to modify the group's share on each cpu
7642          * w/o tripping rebalance_share or load_balance_fair.
7643          */
7644         tg->shares = shares;
7645         for_each_possible_cpu(i) {
7646                 spin_lock_irq(&cpu_rq(i)->lock);
7647                 set_se_shares(tg->se[i], shares);
7648                 spin_unlock_irq(&cpu_rq(i)->lock);
7649         }
7650
7651         /*
7652          * Enable load balance activity on this group, by inserting it back on
7653          * each cpu's rq->leaf_cfs_rq_list.
7654          */
7655         for_each_possible_cpu(i) {
7656                 rq = cpu_rq(i);
7657                 cfs_rq = tg->cfs_rq[i];
7658                 list_add_rcu(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
7659         }
7660 done:
7661         unlock_task_group_list();
7662         return 0;
7663 }
7664
7665 unsigned long sched_group_shares(struct task_group *tg)
7666 {
7667         return tg->shares;
7668 }
7669
7670 #endif  /* CONFIG_FAIR_GROUP_SCHED */
7671
7672 #ifdef CONFIG_FAIR_CGROUP_SCHED
7673
7674 /* return corresponding task_group object of a cgroup */
7675 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
7676 {
7677         return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
7678                             struct task_group, css);
7679 }
7680
7681 static struct cgroup_subsys_state *
7682 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
7683 {
7684         struct task_group *tg;
7685
7686         if (!cgrp->parent) {
7687                 /* This is early initialization for the top cgroup */
7688                 init_task_group.css.cgroup = cgrp;
7689                 return &init_task_group.css;
7690         }
7691
7692         /* we support only 1-level deep hierarchical scheduler atm */
7693         if (cgrp->parent->parent)
7694                 return ERR_PTR(-EINVAL);
7695
7696         tg = sched_create_group();
7697         if (IS_ERR(tg))
7698                 return ERR_PTR(-ENOMEM);
7699
7700         /* Bind the cgroup to task_group object we just created */
7701         tg->css.cgroup = cgrp;
7702
7703         return &tg->css;
7704 }
7705
7706 static void
7707 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
7708 {
7709         struct task_group *tg = cgroup_tg(cgrp);
7710
7711         sched_destroy_group(tg);
7712 }
7713
7714 static int
7715 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
7716                       struct task_struct *tsk)
7717 {
7718         /* We don't support RT-tasks being in separate groups */
7719         if (tsk->sched_class != &fair_sched_class)
7720                 return -EINVAL;
7721
7722         return 0;
7723 }
7724
7725 static void
7726 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
7727                         struct cgroup *old_cont, struct task_struct *tsk)
7728 {
7729         sched_move_task(tsk);
7730 }
7731
7732 static int cpu_shares_write_uint(struct cgroup *cgrp, struct cftype *cftype,
7733                                 u64 shareval)
7734 {
7735         return sched_group_set_shares(cgroup_tg(cgrp), shareval);
7736 }
7737
7738 static u64 cpu_shares_read_uint(struct cgroup *cgrp, struct cftype *cft)
7739 {
7740         struct task_group *tg = cgroup_tg(cgrp);
7741
7742         return (u64) tg->shares;
7743 }
7744
7745 static struct cftype cpu_files[] = {
7746         {
7747                 .name = "shares",
7748                 .read_uint = cpu_shares_read_uint,
7749                 .write_uint = cpu_shares_write_uint,
7750         },
7751 };
7752
7753 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
7754 {
7755         return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
7756 }
7757
7758 struct cgroup_subsys cpu_cgroup_subsys = {
7759         .name           = "cpu",
7760         .create         = cpu_cgroup_create,
7761         .destroy        = cpu_cgroup_destroy,
7762         .can_attach     = cpu_cgroup_can_attach,
7763         .attach         = cpu_cgroup_attach,
7764         .populate       = cpu_cgroup_populate,
7765         .subsys_id      = cpu_cgroup_subsys_id,
7766         .early_init     = 1,
7767 };
7768
7769 #endif  /* CONFIG_FAIR_CGROUP_SCHED */
7770
7771 #ifdef CONFIG_CGROUP_CPUACCT
7772
7773 /*
7774  * CPU accounting code for task groups.
7775  *
7776  * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
7777  * (balbir@in.ibm.com).
7778  */
7779
7780 /* track cpu usage of a group of tasks */
7781 struct cpuacct {
7782         struct cgroup_subsys_state css;
7783         /* cpuusage holds pointer to a u64-type object on every cpu */
7784         u64 *cpuusage;
7785 };
7786
7787 struct cgroup_subsys cpuacct_subsys;
7788
7789 /* return cpu accounting group corresponding to this container */
7790 static inline struct cpuacct *cgroup_ca(struct cgroup *cont)
7791 {
7792         return container_of(cgroup_subsys_state(cont, cpuacct_subsys_id),
7793                             struct cpuacct, css);
7794 }
7795
7796 /* return cpu accounting group to which this task belongs */
7797 static inline struct cpuacct *task_ca(struct task_struct *tsk)
7798 {
7799         return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
7800                             struct cpuacct, css);
7801 }
7802
7803 /* create a new cpu accounting group */
7804 static struct cgroup_subsys_state *cpuacct_create(
7805         struct cgroup_subsys *ss, struct cgroup *cont)
7806 {
7807         struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
7808
7809         if (!ca)
7810                 return ERR_PTR(-ENOMEM);
7811
7812         ca->cpuusage = alloc_percpu(u64);
7813         if (!ca->cpuusage) {
7814                 kfree(ca);
7815                 return ERR_PTR(-ENOMEM);
7816         }
7817
7818         return &ca->css;
7819 }
7820
7821 /* destroy an existing cpu accounting group */
7822 static void
7823 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cont)
7824 {
7825         struct cpuacct *ca = cgroup_ca(cont);
7826
7827         free_percpu(ca->cpuusage);
7828         kfree(ca);
7829 }
7830
7831 /* return total cpu usage (in nanoseconds) of a group */
7832 static u64 cpuusage_read(struct cgroup *cont, struct cftype *cft)
7833 {
7834         struct cpuacct *ca = cgroup_ca(cont);
7835         u64 totalcpuusage = 0;
7836         int i;
7837
7838         for_each_possible_cpu(i) {
7839                 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
7840
7841                 /*
7842                  * Take rq->lock to make 64-bit addition safe on 32-bit
7843                  * platforms.
7844                  */
7845                 spin_lock_irq(&cpu_rq(i)->lock);
7846                 totalcpuusage += *cpuusage;
7847                 spin_unlock_irq(&cpu_rq(i)->lock);
7848         }
7849
7850         return totalcpuusage;
7851 }
7852
7853 static struct cftype files[] = {
7854         {
7855                 .name = "usage",
7856                 .read_uint = cpuusage_read,
7857         },
7858 };
7859
7860 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cont)
7861 {
7862         return cgroup_add_files(cont, ss, files, ARRAY_SIZE(files));
7863 }
7864
7865 /*
7866  * charge this task's execution time to its accounting group.
7867  *
7868  * called with rq->lock held.
7869  */
7870 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
7871 {
7872         struct cpuacct *ca;
7873
7874         if (!cpuacct_subsys.active)
7875                 return;
7876
7877         ca = task_ca(tsk);
7878         if (ca) {
7879                 u64 *cpuusage = percpu_ptr(ca->cpuusage, task_cpu(tsk));
7880
7881                 *cpuusage += cputime;
7882         }
7883 }
7884
7885 struct cgroup_subsys cpuacct_subsys = {
7886         .name = "cpuacct",
7887         .create = cpuacct_create,
7888         .destroy = cpuacct_destroy,
7889         .populate = cpuacct_populate,
7890         .subsys_id = cpuacct_subsys_id,
7891 };
7892 #endif  /* CONFIG_CGROUP_CPUACCT */