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