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