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