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