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