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