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