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