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