mutexes, sched: Introduce arch_mutex_cpu_relax()
[pandora-kernel.git] / kernel / sched.c
1 /*
2  *  kernel/sched.c
3  *
4  *  Kernel scheduler and related syscalls
5  *
6  *  Copyright (C) 1991-2002  Linus Torvalds
7  *
8  *  1996-12-23  Modified by Dave Grothe to fix bugs in semaphores and
9  *              make semaphores SMP safe
10  *  1998-11-19  Implemented schedule_timeout() and related stuff
11  *              by Andrea Arcangeli
12  *  2002-01-04  New ultra-scalable O(1) scheduler by Ingo Molnar:
13  *              hybrid priority-list and round-robin design with
14  *              an array-switch method of distributing timeslices
15  *              and per-CPU runqueues.  Cleanups and useful suggestions
16  *              by Davide Libenzi, preemptible kernel bits by Robert Love.
17  *  2003-09-03  Interactivity tuning by Con Kolivas.
18  *  2004-04-02  Scheduler domains code by Nick Piggin
19  *  2007-04-15  Work begun on replacing all interactivity tuning with a
20  *              fair scheduling design by Con Kolivas.
21  *  2007-05-05  Load balancing (smp-nice) and other improvements
22  *              by Peter Williams
23  *  2007-05-06  Interactivity improvements to CFS by Mike Galbraith
24  *  2007-07-01  Group scheduling enhancements by Srivatsa Vaddagiri
25  *  2007-11-29  RT balancing improvements by Steven Rostedt, Gregory Haskins,
26  *              Thomas Gleixner, Mike Kravetz
27  */
28
29 #include <linux/mm.h>
30 #include <linux/module.h>
31 #include <linux/nmi.h>
32 #include <linux/init.h>
33 #include <linux/uaccess.h>
34 #include <linux/highmem.h>
35 #include <linux/smp_lock.h>
36 #include <asm/mmu_context.h>
37 #include <linux/interrupt.h>
38 #include <linux/capability.h>
39 #include <linux/completion.h>
40 #include <linux/kernel_stat.h>
41 #include <linux/debug_locks.h>
42 #include <linux/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, int dest_cpu)
2065 {
2066         struct rq *rq = task_rq(p);
2067
2068         /*
2069          * If the task is not on a runqueue (and not running), then
2070          * the next wake-up will properly place the task.
2071          */
2072         return p->se.on_rq || task_running(rq, p);
2073 }
2074
2075 /*
2076  * wait_task_inactive - wait for a thread to unschedule.
2077  *
2078  * If @match_state is nonzero, it's the @p->state value just checked and
2079  * not expected to change.  If it changes, i.e. @p might have woken up,
2080  * then return zero.  When we succeed in waiting for @p to be off its CPU,
2081  * we return a positive number (its total switch count).  If a second call
2082  * a short while later returns the same number, the caller can be sure that
2083  * @p has remained unscheduled the whole time.
2084  *
2085  * The caller must ensure that the task *will* unschedule sometime soon,
2086  * else this function might spin for a *long* time. This function can't
2087  * be called with interrupts off, or it may introduce deadlock with
2088  * smp_call_function() if an IPI is sent by the same process we are
2089  * waiting to become inactive.
2090  */
2091 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
2092 {
2093         unsigned long flags;
2094         int running, on_rq;
2095         unsigned long ncsw;
2096         struct rq *rq;
2097
2098         for (;;) {
2099                 /*
2100                  * We do the initial early heuristics without holding
2101                  * any task-queue locks at all. We'll only try to get
2102                  * the runqueue lock when things look like they will
2103                  * work out!
2104                  */
2105                 rq = task_rq(p);
2106
2107                 /*
2108                  * If the task is actively running on another CPU
2109                  * still, just relax and busy-wait without holding
2110                  * any locks.
2111                  *
2112                  * NOTE! Since we don't hold any locks, it's not
2113                  * even sure that "rq" stays as the right runqueue!
2114                  * But we don't care, since "task_running()" will
2115                  * return false if the runqueue has changed and p
2116                  * is actually now running somewhere else!
2117                  */
2118                 while (task_running(rq, p)) {
2119                         if (match_state && unlikely(p->state != match_state))
2120                                 return 0;
2121                         cpu_relax();
2122                 }
2123
2124                 /*
2125                  * Ok, time to look more closely! We need the rq
2126                  * lock now, to be *sure*. If we're wrong, we'll
2127                  * just go back and repeat.
2128                  */
2129                 rq = task_rq_lock(p, &flags);
2130                 trace_sched_wait_task(p);
2131                 running = task_running(rq, p);
2132                 on_rq = p->se.on_rq;
2133                 ncsw = 0;
2134                 if (!match_state || p->state == match_state)
2135                         ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
2136                 task_rq_unlock(rq, &flags);
2137
2138                 /*
2139                  * If it changed from the expected state, bail out now.
2140                  */
2141                 if (unlikely(!ncsw))
2142                         break;
2143
2144                 /*
2145                  * Was it really running after all now that we
2146                  * checked with the proper locks actually held?
2147                  *
2148                  * Oops. Go back and try again..
2149                  */
2150                 if (unlikely(running)) {
2151                         cpu_relax();
2152                         continue;
2153                 }
2154
2155                 /*
2156                  * It's not enough that it's not actively running,
2157                  * it must be off the runqueue _entirely_, and not
2158                  * preempted!
2159                  *
2160                  * So if it was still runnable (but just not actively
2161                  * running right now), it's preempted, and we should
2162                  * yield - it could be a while.
2163                  */
2164                 if (unlikely(on_rq)) {
2165                         schedule_timeout_uninterruptible(1);
2166                         continue;
2167                 }
2168
2169                 /*
2170                  * Ahh, all good. It wasn't running, and it wasn't
2171                  * runnable, which means that it will never become
2172                  * running in the future either. We're all done!
2173                  */
2174                 break;
2175         }
2176
2177         return ncsw;
2178 }
2179
2180 /***
2181  * kick_process - kick a running thread to enter/exit the kernel
2182  * @p: the to-be-kicked thread
2183  *
2184  * Cause a process which is running on another CPU to enter
2185  * kernel-mode, without any delay. (to get signals handled.)
2186  *
2187  * NOTE: this function doesnt have to take the runqueue lock,
2188  * because all it wants to ensure is that the remote task enters
2189  * the kernel. If the IPI races and the task has been migrated
2190  * to another CPU then no harm is done and the purpose has been
2191  * achieved as well.
2192  */
2193 void kick_process(struct task_struct *p)
2194 {
2195         int cpu;
2196
2197         preempt_disable();
2198         cpu = task_cpu(p);
2199         if ((cpu != smp_processor_id()) && task_curr(p))
2200                 smp_send_reschedule(cpu);
2201         preempt_enable();
2202 }
2203 EXPORT_SYMBOL_GPL(kick_process);
2204 #endif /* CONFIG_SMP */
2205
2206 /**
2207  * task_oncpu_function_call - call a function on the cpu on which a task runs
2208  * @p:          the task to evaluate
2209  * @func:       the function to be called
2210  * @info:       the function call argument
2211  *
2212  * Calls the function @func when the task is currently running. This might
2213  * be on the current CPU, which just calls the function directly
2214  */
2215 void task_oncpu_function_call(struct task_struct *p,
2216                               void (*func) (void *info), void *info)
2217 {
2218         int cpu;
2219
2220         preempt_disable();
2221         cpu = task_cpu(p);
2222         if (task_curr(p))
2223                 smp_call_function_single(cpu, func, info, 1);
2224         preempt_enable();
2225 }
2226
2227 #ifdef CONFIG_SMP
2228 /*
2229  * ->cpus_allowed is protected by either TASK_WAKING or rq->lock held.
2230  */
2231 static int select_fallback_rq(int cpu, struct task_struct *p)
2232 {
2233         int dest_cpu;
2234         const struct cpumask *nodemask = cpumask_of_node(cpu_to_node(cpu));
2235
2236         /* Look for allowed, online CPU in same node. */
2237         for_each_cpu_and(dest_cpu, nodemask, cpu_active_mask)
2238                 if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
2239                         return dest_cpu;
2240
2241         /* Any allowed, online CPU? */
2242         dest_cpu = cpumask_any_and(&p->cpus_allowed, cpu_active_mask);
2243         if (dest_cpu < nr_cpu_ids)
2244                 return dest_cpu;
2245
2246         /* No more Mr. Nice Guy. */
2247         dest_cpu = cpuset_cpus_allowed_fallback(p);
2248         /*
2249          * Don't tell them about moving exiting tasks or
2250          * kernel threads (both mm NULL), since they never
2251          * leave kernel.
2252          */
2253         if (p->mm && printk_ratelimit()) {
2254                 printk(KERN_INFO "process %d (%s) no longer affine to cpu%d\n",
2255                                 task_pid_nr(p), p->comm, cpu);
2256         }
2257
2258         return dest_cpu;
2259 }
2260
2261 /*
2262  * The caller (fork, wakeup) owns TASK_WAKING, ->cpus_allowed is stable.
2263  */
2264 static inline
2265 int select_task_rq(struct rq *rq, struct task_struct *p, int sd_flags, int wake_flags)
2266 {
2267         int cpu = p->sched_class->select_task_rq(rq, p, sd_flags, wake_flags);
2268
2269         /*
2270          * In order not to call set_task_cpu() on a blocking task we need
2271          * to rely on ttwu() to place the task on a valid ->cpus_allowed
2272          * cpu.
2273          *
2274          * Since this is common to all placement strategies, this lives here.
2275          *
2276          * [ this allows ->select_task() to simply return task_cpu(p) and
2277          *   not worry about this generic constraint ]
2278          */
2279         if (unlikely(!cpumask_test_cpu(cpu, &p->cpus_allowed) ||
2280                      !cpu_online(cpu)))
2281                 cpu = select_fallback_rq(task_cpu(p), p);
2282
2283         return cpu;
2284 }
2285
2286 static void update_avg(u64 *avg, u64 sample)
2287 {
2288         s64 diff = sample - *avg;
2289         *avg += diff >> 3;
2290 }
2291 #endif
2292
2293 static inline void ttwu_activate(struct task_struct *p, struct rq *rq,
2294                                  bool is_sync, bool is_migrate, bool is_local,
2295                                  unsigned long en_flags)
2296 {
2297         schedstat_inc(p, se.statistics.nr_wakeups);
2298         if (is_sync)
2299                 schedstat_inc(p, se.statistics.nr_wakeups_sync);
2300         if (is_migrate)
2301                 schedstat_inc(p, se.statistics.nr_wakeups_migrate);
2302         if (is_local)
2303                 schedstat_inc(p, se.statistics.nr_wakeups_local);
2304         else
2305                 schedstat_inc(p, se.statistics.nr_wakeups_remote);
2306
2307         activate_task(rq, p, en_flags);
2308 }
2309
2310 static inline void ttwu_post_activation(struct task_struct *p, struct rq *rq,
2311                                         int wake_flags, bool success)
2312 {
2313         trace_sched_wakeup(p, success);
2314         check_preempt_curr(rq, p, wake_flags);
2315
2316         p->state = TASK_RUNNING;
2317 #ifdef CONFIG_SMP
2318         if (p->sched_class->task_woken)
2319                 p->sched_class->task_woken(rq, p);
2320
2321         if (unlikely(rq->idle_stamp)) {
2322                 u64 delta = rq->clock - rq->idle_stamp;
2323                 u64 max = 2*sysctl_sched_migration_cost;
2324
2325                 if (delta > max)
2326                         rq->avg_idle = max;
2327                 else
2328                         update_avg(&rq->avg_idle, delta);
2329                 rq->idle_stamp = 0;
2330         }
2331 #endif
2332         /* if a worker is waking up, notify workqueue */
2333         if ((p->flags & PF_WQ_WORKER) && success)
2334                 wq_worker_waking_up(p, cpu_of(rq));
2335 }
2336
2337 /**
2338  * try_to_wake_up - wake up a thread
2339  * @p: the thread to be awakened
2340  * @state: the mask of task states that can be woken
2341  * @wake_flags: wake modifier flags (WF_*)
2342  *
2343  * Put it on the run-queue if it's not already there. The "current"
2344  * thread is always on the run-queue (except when the actual
2345  * re-schedule is in progress), and as such you're allowed to do
2346  * the simpler "current->state = TASK_RUNNING" to mark yourself
2347  * runnable without the overhead of this.
2348  *
2349  * Returns %true if @p was woken up, %false if it was already running
2350  * or @state didn't match @p's state.
2351  */
2352 static int try_to_wake_up(struct task_struct *p, unsigned int state,
2353                           int wake_flags)
2354 {
2355         int cpu, orig_cpu, this_cpu, success = 0;
2356         unsigned long flags;
2357         unsigned long en_flags = ENQUEUE_WAKEUP;
2358         struct rq *rq;
2359
2360         this_cpu = get_cpu();
2361
2362         smp_wmb();
2363         rq = task_rq_lock(p, &flags);
2364         if (!(p->state & state))
2365                 goto out;
2366
2367         if (p->se.on_rq)
2368                 goto out_running;
2369
2370         cpu = task_cpu(p);
2371         orig_cpu = cpu;
2372
2373 #ifdef CONFIG_SMP
2374         if (unlikely(task_running(rq, p)))
2375                 goto out_activate;
2376
2377         /*
2378          * In order to handle concurrent wakeups and release the rq->lock
2379          * we put the task in TASK_WAKING state.
2380          *
2381          * First fix up the nr_uninterruptible count:
2382          */
2383         if (task_contributes_to_load(p)) {
2384                 if (likely(cpu_online(orig_cpu)))
2385                         rq->nr_uninterruptible--;
2386                 else
2387                         this_rq()->nr_uninterruptible--;
2388         }
2389         p->state = TASK_WAKING;
2390
2391         if (p->sched_class->task_waking) {
2392                 p->sched_class->task_waking(rq, p);
2393                 en_flags |= ENQUEUE_WAKING;
2394         }
2395
2396         cpu = select_task_rq(rq, p, SD_BALANCE_WAKE, wake_flags);
2397         if (cpu != orig_cpu)
2398                 set_task_cpu(p, cpu);
2399         __task_rq_unlock(rq);
2400
2401         rq = cpu_rq(cpu);
2402         raw_spin_lock(&rq->lock);
2403
2404         /*
2405          * We migrated the task without holding either rq->lock, however
2406          * since the task is not on the task list itself, nobody else
2407          * will try and migrate the task, hence the rq should match the
2408          * cpu we just moved it to.
2409          */
2410         WARN_ON(task_cpu(p) != cpu);
2411         WARN_ON(p->state != TASK_WAKING);
2412
2413 #ifdef CONFIG_SCHEDSTATS
2414         schedstat_inc(rq, ttwu_count);
2415         if (cpu == this_cpu)
2416                 schedstat_inc(rq, ttwu_local);
2417         else {
2418                 struct sched_domain *sd;
2419                 for_each_domain(this_cpu, sd) {
2420                         if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2421                                 schedstat_inc(sd, ttwu_wake_remote);
2422                                 break;
2423                         }
2424                 }
2425         }
2426 #endif /* CONFIG_SCHEDSTATS */
2427
2428 out_activate:
2429 #endif /* CONFIG_SMP */
2430         ttwu_activate(p, rq, wake_flags & WF_SYNC, orig_cpu != cpu,
2431                       cpu == this_cpu, en_flags);
2432         success = 1;
2433 out_running:
2434         ttwu_post_activation(p, rq, wake_flags, success);
2435 out:
2436         task_rq_unlock(rq, &flags);
2437         put_cpu();
2438
2439         return success;
2440 }
2441
2442 /**
2443  * try_to_wake_up_local - try to wake up a local task with rq lock held
2444  * @p: the thread to be awakened
2445  *
2446  * Put @p on the run-queue if it's not alredy there.  The caller must
2447  * ensure that this_rq() is locked, @p is bound to this_rq() and not
2448  * the current task.  this_rq() stays locked over invocation.
2449  */
2450 static void try_to_wake_up_local(struct task_struct *p)
2451 {
2452         struct rq *rq = task_rq(p);
2453         bool success = false;
2454
2455         BUG_ON(rq != this_rq());
2456         BUG_ON(p == current);
2457         lockdep_assert_held(&rq->lock);
2458
2459         if (!(p->state & TASK_NORMAL))
2460                 return;
2461
2462         if (!p->se.on_rq) {
2463                 if (likely(!task_running(rq, p))) {
2464                         schedstat_inc(rq, ttwu_count);
2465                         schedstat_inc(rq, ttwu_local);
2466                 }
2467                 ttwu_activate(p, rq, false, false, true, ENQUEUE_WAKEUP);
2468                 success = true;
2469         }
2470         ttwu_post_activation(p, rq, 0, success);
2471 }
2472
2473 /**
2474  * wake_up_process - Wake up a specific process
2475  * @p: The process to be woken up.
2476  *
2477  * Attempt to wake up the nominated process and move it to the set of runnable
2478  * processes.  Returns 1 if the process was woken up, 0 if it was already
2479  * running.
2480  *
2481  * It may be assumed that this function implies a write memory barrier before
2482  * changing the task state if and only if any tasks are woken up.
2483  */
2484 int wake_up_process(struct task_struct *p)
2485 {
2486         return try_to_wake_up(p, TASK_ALL, 0);
2487 }
2488 EXPORT_SYMBOL(wake_up_process);
2489
2490 int wake_up_state(struct task_struct *p, unsigned int state)
2491 {
2492         return try_to_wake_up(p, state, 0);
2493 }
2494
2495 /*
2496  * Perform scheduler related setup for a newly forked process p.
2497  * p is forked by current.
2498  *
2499  * __sched_fork() is basic setup used by init_idle() too:
2500  */
2501 static void __sched_fork(struct task_struct *p)
2502 {
2503         p->se.exec_start                = 0;
2504         p->se.sum_exec_runtime          = 0;
2505         p->se.prev_sum_exec_runtime     = 0;
2506         p->se.nr_migrations             = 0;
2507
2508 #ifdef CONFIG_SCHEDSTATS
2509         memset(&p->se.statistics, 0, sizeof(p->se.statistics));
2510 #endif
2511
2512         INIT_LIST_HEAD(&p->rt.run_list);
2513         p->se.on_rq = 0;
2514         INIT_LIST_HEAD(&p->se.group_node);
2515
2516 #ifdef CONFIG_PREEMPT_NOTIFIERS
2517         INIT_HLIST_HEAD(&p->preempt_notifiers);
2518 #endif
2519 }
2520
2521 /*
2522  * fork()/clone()-time setup:
2523  */
2524 void sched_fork(struct task_struct *p, int clone_flags)
2525 {
2526         int cpu = get_cpu();
2527
2528         __sched_fork(p);
2529         /*
2530          * We mark the process as running here. This guarantees that
2531          * nobody will actually run it, and a signal or other external
2532          * event cannot wake it up and insert it on the runqueue either.
2533          */
2534         p->state = TASK_RUNNING;
2535
2536         /*
2537          * Revert to default priority/policy on fork if requested.
2538          */
2539         if (unlikely(p->sched_reset_on_fork)) {
2540                 if (p->policy == SCHED_FIFO || p->policy == SCHED_RR) {
2541                         p->policy = SCHED_NORMAL;
2542                         p->normal_prio = p->static_prio;
2543                 }
2544
2545                 if (PRIO_TO_NICE(p->static_prio) < 0) {
2546                         p->static_prio = NICE_TO_PRIO(0);
2547                         p->normal_prio = p->static_prio;
2548                         set_load_weight(p);
2549                 }
2550
2551                 /*
2552                  * We don't need the reset flag anymore after the fork. It has
2553                  * fulfilled its duty:
2554                  */
2555                 p->sched_reset_on_fork = 0;
2556         }
2557
2558         /*
2559          * Make sure we do not leak PI boosting priority to the child.
2560          */
2561         p->prio = current->normal_prio;
2562
2563         if (!rt_prio(p->prio))
2564                 p->sched_class = &fair_sched_class;
2565
2566         if (p->sched_class->task_fork)
2567                 p->sched_class->task_fork(p);
2568
2569         /*
2570          * The child is not yet in the pid-hash so no cgroup attach races,
2571          * and the cgroup is pinned to this child due to cgroup_fork()
2572          * is ran before sched_fork().
2573          *
2574          * Silence PROVE_RCU.
2575          */
2576         rcu_read_lock();
2577         set_task_cpu(p, cpu);
2578         rcu_read_unlock();
2579
2580 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
2581         if (likely(sched_info_on()))
2582                 memset(&p->sched_info, 0, sizeof(p->sched_info));
2583 #endif
2584 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
2585         p->oncpu = 0;
2586 #endif
2587 #ifdef CONFIG_PREEMPT
2588         /* Want to start with kernel preemption disabled. */
2589         task_thread_info(p)->preempt_count = 1;
2590 #endif
2591         plist_node_init(&p->pushable_tasks, MAX_PRIO);
2592
2593         put_cpu();
2594 }
2595
2596 /*
2597  * wake_up_new_task - wake up a newly created task for the first time.
2598  *
2599  * This function will do some initial scheduler statistics housekeeping
2600  * that must be done for every newly created context, then puts the task
2601  * on the runqueue and wakes it.
2602  */
2603 void wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
2604 {
2605         unsigned long flags;
2606         struct rq *rq;
2607         int cpu __maybe_unused = get_cpu();
2608
2609 #ifdef CONFIG_SMP
2610         rq = task_rq_lock(p, &flags);
2611         p->state = TASK_WAKING;
2612
2613         /*
2614          * Fork balancing, do it here and not earlier because:
2615          *  - cpus_allowed can change in the fork path
2616          *  - any previously selected cpu might disappear through hotplug
2617          *
2618          * We set TASK_WAKING so that select_task_rq() can drop rq->lock
2619          * without people poking at ->cpus_allowed.
2620          */
2621         cpu = select_task_rq(rq, p, SD_BALANCE_FORK, 0);
2622         set_task_cpu(p, cpu);
2623
2624         p->state = TASK_RUNNING;
2625         task_rq_unlock(rq, &flags);
2626 #endif
2627
2628         rq = task_rq_lock(p, &flags);
2629         activate_task(rq, p, 0);
2630         trace_sched_wakeup_new(p, 1);
2631         check_preempt_curr(rq, p, WF_FORK);
2632 #ifdef CONFIG_SMP
2633         if (p->sched_class->task_woken)
2634                 p->sched_class->task_woken(rq, p);
2635 #endif
2636         task_rq_unlock(rq, &flags);
2637         put_cpu();
2638 }
2639
2640 #ifdef CONFIG_PREEMPT_NOTIFIERS
2641
2642 /**
2643  * preempt_notifier_register - tell me when current is being preempted & rescheduled
2644  * @notifier: notifier struct to register
2645  */
2646 void preempt_notifier_register(struct preempt_notifier *notifier)
2647 {
2648         hlist_add_head(&notifier->link, &current->preempt_notifiers);
2649 }
2650 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2651
2652 /**
2653  * preempt_notifier_unregister - no longer interested in preemption notifications
2654  * @notifier: notifier struct to unregister
2655  *
2656  * This is safe to call from within a preemption notifier.
2657  */
2658 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2659 {
2660         hlist_del(&notifier->link);
2661 }
2662 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2663
2664 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2665 {
2666         struct preempt_notifier *notifier;
2667         struct hlist_node *node;
2668
2669         hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2670                 notifier->ops->sched_in(notifier, raw_smp_processor_id());
2671 }
2672
2673 static void
2674 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2675                                  struct task_struct *next)
2676 {
2677         struct preempt_notifier *notifier;
2678         struct hlist_node *node;
2679
2680         hlist_for_each_entry(notifier, node, &curr->preempt_notifiers, link)
2681                 notifier->ops->sched_out(notifier, next);
2682 }
2683
2684 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2685
2686 static void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2687 {
2688 }
2689
2690 static void
2691 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2692                                  struct task_struct *next)
2693 {
2694 }
2695
2696 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2697
2698 /**
2699  * prepare_task_switch - prepare to switch tasks
2700  * @rq: the runqueue preparing to switch
2701  * @prev: the current task that is being switched out
2702  * @next: the task we are going to switch to.
2703  *
2704  * This is called with the rq lock held and interrupts off. It must
2705  * be paired with a subsequent finish_task_switch after the context
2706  * switch.
2707  *
2708  * prepare_task_switch sets up locking and calls architecture specific
2709  * hooks.
2710  */
2711 static inline void
2712 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2713                     struct task_struct *next)
2714 {
2715         fire_sched_out_preempt_notifiers(prev, next);
2716         prepare_lock_switch(rq, next);
2717         prepare_arch_switch(next);
2718 }
2719
2720 /**
2721  * finish_task_switch - clean up after a task-switch
2722  * @rq: runqueue associated with task-switch
2723  * @prev: the thread we just switched away from.
2724  *
2725  * finish_task_switch must be called after the context switch, paired
2726  * with a prepare_task_switch call before the context switch.
2727  * finish_task_switch will reconcile locking set up by prepare_task_switch,
2728  * and do any other architecture-specific cleanup actions.
2729  *
2730  * Note that we may have delayed dropping an mm in context_switch(). If
2731  * so, we finish that here outside of the runqueue lock. (Doing it
2732  * with the lock held can cause deadlocks; see schedule() for
2733  * details.)
2734  */
2735 static void finish_task_switch(struct rq *rq, struct task_struct *prev)
2736         __releases(rq->lock)
2737 {
2738         struct mm_struct *mm = rq->prev_mm;
2739         long prev_state;
2740
2741         rq->prev_mm = NULL;
2742
2743         /*
2744          * A task struct has one reference for the use as "current".
2745          * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2746          * schedule one last time. The schedule call will never return, and
2747          * the scheduled task must drop that reference.
2748          * The test for TASK_DEAD must occur while the runqueue locks are
2749          * still held, otherwise prev could be scheduled on another cpu, die
2750          * there before we look at prev->state, and then the reference would
2751          * be dropped twice.
2752          *              Manfred Spraul <manfred@colorfullife.com>
2753          */
2754         prev_state = prev->state;
2755         finish_arch_switch(prev);
2756 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
2757         local_irq_disable();
2758 #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */
2759         perf_event_task_sched_in(current);
2760 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
2761         local_irq_enable();
2762 #endif /* __ARCH_WANT_INTERRUPTS_ON_CTXSW */
2763         finish_lock_switch(rq, prev);
2764
2765         fire_sched_in_preempt_notifiers(current);
2766         if (mm)
2767                 mmdrop(mm);
2768         if (unlikely(prev_state == TASK_DEAD)) {
2769                 /*
2770                  * Remove function-return probe instances associated with this
2771                  * task and put them back on the free list.
2772                  */
2773                 kprobe_flush_task(prev);
2774                 put_task_struct(prev);
2775         }
2776 }
2777
2778 #ifdef CONFIG_SMP
2779
2780 /* assumes rq->lock is held */
2781 static inline void pre_schedule(struct rq *rq, struct task_struct *prev)
2782 {
2783         if (prev->sched_class->pre_schedule)
2784                 prev->sched_class->pre_schedule(rq, prev);
2785 }
2786
2787 /* rq->lock is NOT held, but preemption is disabled */
2788 static inline void post_schedule(struct rq *rq)
2789 {
2790         if (rq->post_schedule) {
2791                 unsigned long flags;
2792
2793                 raw_spin_lock_irqsave(&rq->lock, flags);
2794                 if (rq->curr->sched_class->post_schedule)
2795                         rq->curr->sched_class->post_schedule(rq);
2796                 raw_spin_unlock_irqrestore(&rq->lock, flags);
2797
2798                 rq->post_schedule = 0;
2799         }
2800 }
2801
2802 #else
2803
2804 static inline void pre_schedule(struct rq *rq, struct task_struct *p)
2805 {
2806 }
2807
2808 static inline void post_schedule(struct rq *rq)
2809 {
2810 }
2811
2812 #endif
2813
2814 /**
2815  * schedule_tail - first thing a freshly forked thread must call.
2816  * @prev: the thread we just switched away from.
2817  */
2818 asmlinkage void schedule_tail(struct task_struct *prev)
2819         __releases(rq->lock)
2820 {
2821         struct rq *rq = this_rq();
2822
2823         finish_task_switch(rq, prev);
2824
2825         /*
2826          * FIXME: do we need to worry about rq being invalidated by the
2827          * task_switch?
2828          */
2829         post_schedule(rq);
2830
2831 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
2832         /* In this case, finish_task_switch does not reenable preemption */
2833         preempt_enable();
2834 #endif
2835         if (current->set_child_tid)
2836                 put_user(task_pid_vnr(current), current->set_child_tid);
2837 }
2838
2839 /*
2840  * context_switch - switch to the new MM and the new
2841  * thread's register state.
2842  */
2843 static inline void
2844 context_switch(struct rq *rq, struct task_struct *prev,
2845                struct task_struct *next)
2846 {
2847         struct mm_struct *mm, *oldmm;
2848
2849         prepare_task_switch(rq, prev, next);
2850         trace_sched_switch(prev, next);
2851         mm = next->mm;
2852         oldmm = prev->active_mm;
2853         /*
2854          * For paravirt, this is coupled with an exit in switch_to to
2855          * combine the page table reload and the switch backend into
2856          * one hypercall.
2857          */
2858         arch_start_context_switch(prev);
2859
2860         if (!mm) {
2861                 next->active_mm = oldmm;
2862                 atomic_inc(&oldmm->mm_count);
2863                 enter_lazy_tlb(oldmm, next);
2864         } else
2865                 switch_mm(oldmm, mm, next);
2866
2867         if (!prev->mm) {
2868                 prev->active_mm = NULL;
2869                 rq->prev_mm = oldmm;
2870         }
2871         /*
2872          * Since the runqueue lock will be released by the next
2873          * task (which is an invalid locking op but in the case
2874          * of the scheduler it's an obvious special-case), so we
2875          * do an early lockdep release here:
2876          */
2877 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
2878         spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2879 #endif
2880
2881         /* Here we just switch the register state and the stack. */
2882         switch_to(prev, next, prev);
2883
2884         barrier();
2885         /*
2886          * this_rq must be evaluated again because prev may have moved
2887          * CPUs since it called schedule(), thus the 'rq' on its stack
2888          * frame will be invalid.
2889          */
2890         finish_task_switch(this_rq(), prev);
2891 }
2892
2893 /*
2894  * nr_running, nr_uninterruptible and nr_context_switches:
2895  *
2896  * externally visible scheduler statistics: current number of runnable
2897  * threads, current number of uninterruptible-sleeping threads, total
2898  * number of context switches performed since bootup.
2899  */
2900 unsigned long nr_running(void)
2901 {
2902         unsigned long i, sum = 0;
2903
2904         for_each_online_cpu(i)
2905                 sum += cpu_rq(i)->nr_running;
2906
2907         return sum;
2908 }
2909
2910 unsigned long nr_uninterruptible(void)
2911 {
2912         unsigned long i, sum = 0;
2913
2914         for_each_possible_cpu(i)
2915                 sum += cpu_rq(i)->nr_uninterruptible;
2916
2917         /*
2918          * Since we read the counters lockless, it might be slightly
2919          * inaccurate. Do not allow it to go below zero though:
2920          */
2921         if (unlikely((long)sum < 0))
2922                 sum = 0;
2923
2924         return sum;
2925 }
2926
2927 unsigned long long nr_context_switches(void)
2928 {
2929         int i;
2930         unsigned long long sum = 0;
2931
2932         for_each_possible_cpu(i)
2933                 sum += cpu_rq(i)->nr_switches;
2934
2935         return sum;
2936 }
2937
2938 unsigned long nr_iowait(void)
2939 {
2940         unsigned long i, sum = 0;
2941
2942         for_each_possible_cpu(i)
2943                 sum += atomic_read(&cpu_rq(i)->nr_iowait);
2944
2945         return sum;
2946 }
2947
2948 unsigned long nr_iowait_cpu(int cpu)
2949 {
2950         struct rq *this = cpu_rq(cpu);
2951         return atomic_read(&this->nr_iowait);
2952 }
2953
2954 unsigned long this_cpu_load(void)
2955 {
2956         struct rq *this = this_rq();
2957         return this->cpu_load[0];
2958 }
2959
2960
2961 /* Variables and functions for calc_load */
2962 static atomic_long_t calc_load_tasks;
2963 static unsigned long calc_load_update;
2964 unsigned long avenrun[3];
2965 EXPORT_SYMBOL(avenrun);
2966
2967 static long calc_load_fold_active(struct rq *this_rq)
2968 {
2969         long nr_active, delta = 0;
2970
2971         nr_active = this_rq->nr_running;
2972         nr_active += (long) this_rq->nr_uninterruptible;
2973
2974         if (nr_active != this_rq->calc_load_active) {
2975                 delta = nr_active - this_rq->calc_load_active;
2976                 this_rq->calc_load_active = nr_active;
2977         }
2978
2979         return delta;
2980 }
2981
2982 #ifdef CONFIG_NO_HZ
2983 /*
2984  * For NO_HZ we delay the active fold to the next LOAD_FREQ update.
2985  *
2986  * When making the ILB scale, we should try to pull this in as well.
2987  */
2988 static atomic_long_t calc_load_tasks_idle;
2989
2990 static void calc_load_account_idle(struct rq *this_rq)
2991 {
2992         long delta;
2993
2994         delta = calc_load_fold_active(this_rq);
2995         if (delta)
2996                 atomic_long_add(delta, &calc_load_tasks_idle);
2997 }
2998
2999 static long calc_load_fold_idle(void)
3000 {
3001         long delta = 0;
3002
3003         /*
3004          * Its got a race, we don't care...
3005          */
3006         if (atomic_long_read(&calc_load_tasks_idle))
3007                 delta = atomic_long_xchg(&calc_load_tasks_idle, 0);
3008
3009         return delta;
3010 }
3011 #else
3012 static void calc_load_account_idle(struct rq *this_rq)
3013 {
3014 }
3015
3016 static inline long calc_load_fold_idle(void)
3017 {
3018         return 0;
3019 }
3020 #endif
3021
3022 /**
3023  * get_avenrun - get the load average array
3024  * @loads:      pointer to dest load array
3025  * @offset:     offset to add
3026  * @shift:      shift count to shift the result left
3027  *
3028  * These values are estimates at best, so no need for locking.
3029  */
3030 void get_avenrun(unsigned long *loads, unsigned long offset, int shift)
3031 {
3032         loads[0] = (avenrun[0] + offset) << shift;
3033         loads[1] = (avenrun[1] + offset) << shift;
3034         loads[2] = (avenrun[2] + offset) << shift;
3035 }
3036
3037 static unsigned long
3038 calc_load(unsigned long load, unsigned long exp, unsigned long active)
3039 {
3040         load *= exp;
3041         load += active * (FIXED_1 - exp);
3042         return load >> FSHIFT;
3043 }
3044
3045 /*
3046  * calc_load - update the avenrun load estimates 10 ticks after the
3047  * CPUs have updated calc_load_tasks.
3048  */
3049 void calc_global_load(void)
3050 {
3051         unsigned long upd = calc_load_update + 10;
3052         long active;
3053
3054         if (time_before(jiffies, upd))
3055                 return;
3056
3057         active = atomic_long_read(&calc_load_tasks);
3058         active = active > 0 ? active * FIXED_1 : 0;
3059
3060         avenrun[0] = calc_load(avenrun[0], EXP_1, active);
3061         avenrun[1] = calc_load(avenrun[1], EXP_5, active);
3062         avenrun[2] = calc_load(avenrun[2], EXP_15, active);
3063
3064         calc_load_update += LOAD_FREQ;
3065 }
3066
3067 /*
3068  * Called from update_cpu_load() to periodically update this CPU's
3069  * active count.
3070  */
3071 static void calc_load_account_active(struct rq *this_rq)
3072 {
3073         long delta;
3074
3075         if (time_before(jiffies, this_rq->calc_load_update))
3076                 return;
3077
3078         delta  = calc_load_fold_active(this_rq);
3079         delta += calc_load_fold_idle();
3080         if (delta)
3081                 atomic_long_add(delta, &calc_load_tasks);
3082
3083         this_rq->calc_load_update += LOAD_FREQ;
3084 }
3085
3086 /*
3087  * The exact cpuload at various idx values, calculated at every tick would be
3088  * load = (2^idx - 1) / 2^idx * load + 1 / 2^idx * cur_load
3089  *
3090  * If a cpu misses updates for n-1 ticks (as it was idle) and update gets called
3091  * on nth tick when cpu may be busy, then we have:
3092  * load = ((2^idx - 1) / 2^idx)^(n-1) * load
3093  * load = (2^idx - 1) / 2^idx) * load + 1 / 2^idx * cur_load
3094  *
3095  * decay_load_missed() below does efficient calculation of
3096  * load = ((2^idx - 1) / 2^idx)^(n-1) * load
3097  * avoiding 0..n-1 loop doing load = ((2^idx - 1) / 2^idx) * load
3098  *
3099  * The calculation is approximated on a 128 point scale.
3100  * degrade_zero_ticks is the number of ticks after which load at any
3101  * particular idx is approximated to be zero.
3102  * degrade_factor is a precomputed table, a row for each load idx.
3103  * Each column corresponds to degradation factor for a power of two ticks,
3104  * based on 128 point scale.
3105  * Example:
3106  * row 2, col 3 (=12) says that the degradation at load idx 2 after
3107  * 8 ticks is 12/128 (which is an approximation of exact factor 3^8/4^8).
3108  *
3109  * With this power of 2 load factors, we can degrade the load n times
3110  * by looking at 1 bits in n and doing as many mult/shift instead of
3111  * n mult/shifts needed by the exact degradation.
3112  */
3113 #define DEGRADE_SHIFT           7
3114 static const unsigned char
3115                 degrade_zero_ticks[CPU_LOAD_IDX_MAX] = {0, 8, 32, 64, 128};
3116 static const unsigned char
3117                 degrade_factor[CPU_LOAD_IDX_MAX][DEGRADE_SHIFT + 1] = {
3118                                         {0, 0, 0, 0, 0, 0, 0, 0},
3119                                         {64, 32, 8, 0, 0, 0, 0, 0},
3120                                         {96, 72, 40, 12, 1, 0, 0},
3121                                         {112, 98, 75, 43, 15, 1, 0},
3122                                         {120, 112, 98, 76, 45, 16, 2} };
3123
3124 /*
3125  * Update cpu_load for any missed ticks, due to tickless idle. The backlog
3126  * would be when CPU is idle and so we just decay the old load without
3127  * adding any new load.
3128  */
3129 static unsigned long
3130 decay_load_missed(unsigned long load, unsigned long missed_updates, int idx)
3131 {
3132         int j = 0;
3133
3134         if (!missed_updates)
3135                 return load;
3136
3137         if (missed_updates >= degrade_zero_ticks[idx])
3138                 return 0;
3139
3140         if (idx == 1)
3141                 return load >> missed_updates;
3142
3143         while (missed_updates) {
3144                 if (missed_updates % 2)
3145                         load = (load * degrade_factor[idx][j]) >> DEGRADE_SHIFT;
3146
3147                 missed_updates >>= 1;
3148                 j++;
3149         }
3150         return load;
3151 }
3152
3153 /*
3154  * Update rq->cpu_load[] statistics. This function is usually called every
3155  * scheduler tick (TICK_NSEC). With tickless idle this will not be called
3156  * every tick. We fix it up based on jiffies.
3157  */
3158 static void update_cpu_load(struct rq *this_rq)
3159 {
3160         unsigned long this_load = this_rq->load.weight;
3161         unsigned long curr_jiffies = jiffies;
3162         unsigned long pending_updates;
3163         int i, scale;
3164
3165         this_rq->nr_load_updates++;
3166
3167         /* Avoid repeated calls on same jiffy, when moving in and out of idle */
3168         if (curr_jiffies == this_rq->last_load_update_tick)
3169                 return;
3170
3171         pending_updates = curr_jiffies - this_rq->last_load_update_tick;
3172         this_rq->last_load_update_tick = curr_jiffies;
3173
3174         /* Update our load: */
3175         this_rq->cpu_load[0] = this_load; /* Fasttrack for idx 0 */
3176         for (i = 1, scale = 2; i < CPU_LOAD_IDX_MAX; i++, scale += scale) {
3177                 unsigned long old_load, new_load;
3178
3179                 /* scale is effectively 1 << i now, and >> i divides by scale */
3180
3181                 old_load = this_rq->cpu_load[i];
3182                 old_load = decay_load_missed(old_load, pending_updates - 1, i);
3183                 new_load = this_load;
3184                 /*
3185                  * Round up the averaging division if load is increasing. This
3186                  * prevents us from getting stuck on 9 if the load is 10, for
3187                  * example.
3188                  */
3189                 if (new_load > old_load)
3190                         new_load += scale - 1;
3191
3192                 this_rq->cpu_load[i] = (old_load * (scale - 1) + new_load) >> i;
3193         }
3194
3195         sched_avg_update(this_rq);
3196 }
3197
3198 static void update_cpu_load_active(struct rq *this_rq)
3199 {
3200         update_cpu_load(this_rq);
3201
3202         calc_load_account_active(this_rq);
3203 }
3204
3205 #ifdef CONFIG_SMP
3206
3207 /*
3208  * sched_exec - execve() is a valuable balancing opportunity, because at
3209  * this point the task has the smallest effective memory and cache footprint.
3210  */
3211 void sched_exec(void)
3212 {
3213         struct task_struct *p = current;
3214         unsigned long flags;
3215         struct rq *rq;
3216         int dest_cpu;
3217
3218         rq = task_rq_lock(p, &flags);
3219         dest_cpu = p->sched_class->select_task_rq(rq, p, SD_BALANCE_EXEC, 0);
3220         if (dest_cpu == smp_processor_id())
3221                 goto unlock;
3222
3223         /*
3224          * select_task_rq() can race against ->cpus_allowed
3225          */
3226         if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed) &&
3227             likely(cpu_active(dest_cpu)) && migrate_task(p, dest_cpu)) {
3228                 struct migration_arg arg = { p, dest_cpu };
3229
3230                 task_rq_unlock(rq, &flags);
3231                 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
3232                 return;
3233         }
3234 unlock:
3235         task_rq_unlock(rq, &flags);
3236 }
3237
3238 #endif
3239
3240 DEFINE_PER_CPU(struct kernel_stat, kstat);
3241
3242 EXPORT_PER_CPU_SYMBOL(kstat);
3243
3244 /*
3245  * Return any ns on the sched_clock that have not yet been accounted in
3246  * @p in case that task is currently running.
3247  *
3248  * Called with task_rq_lock() held on @rq.
3249  */
3250 static u64 do_task_delta_exec(struct task_struct *p, struct rq *rq)
3251 {
3252         u64 ns = 0;
3253
3254         if (task_current(rq, p)) {
3255                 update_rq_clock(rq);
3256                 ns = rq->clock_task - p->se.exec_start;
3257                 if ((s64)ns < 0)
3258                         ns = 0;
3259         }
3260
3261         return ns;
3262 }
3263
3264 unsigned long long task_delta_exec(struct task_struct *p)
3265 {
3266         unsigned long flags;
3267         struct rq *rq;
3268         u64 ns = 0;
3269
3270         rq = task_rq_lock(p, &flags);
3271         ns = do_task_delta_exec(p, rq);
3272         task_rq_unlock(rq, &flags);
3273
3274         return ns;
3275 }
3276
3277 /*
3278  * Return accounted runtime for the task.
3279  * In case the task is currently running, return the runtime plus current's
3280  * pending runtime that have not been accounted yet.
3281  */
3282 unsigned long long task_sched_runtime(struct task_struct *p)
3283 {
3284         unsigned long flags;
3285         struct rq *rq;
3286         u64 ns = 0;
3287
3288         rq = task_rq_lock(p, &flags);
3289         ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq);
3290         task_rq_unlock(rq, &flags);
3291
3292         return ns;
3293 }
3294
3295 /*
3296  * Return sum_exec_runtime for the thread group.
3297  * In case the task is currently running, return the sum plus current's
3298  * pending runtime that have not been accounted yet.
3299  *
3300  * Note that the thread group might have other running tasks as well,
3301  * so the return value not includes other pending runtime that other
3302  * running tasks might have.
3303  */
3304 unsigned long long thread_group_sched_runtime(struct task_struct *p)
3305 {
3306         struct task_cputime totals;
3307         unsigned long flags;
3308         struct rq *rq;
3309         u64 ns;
3310
3311         rq = task_rq_lock(p, &flags);
3312         thread_group_cputime(p, &totals);
3313         ns = totals.sum_exec_runtime + do_task_delta_exec(p, rq);
3314         task_rq_unlock(rq, &flags);
3315
3316         return ns;
3317 }
3318
3319 /*
3320  * Account user cpu time to a process.
3321  * @p: the process that the cpu time gets accounted to
3322  * @cputime: the cpu time spent in user space since the last update
3323  * @cputime_scaled: cputime scaled by cpu frequency
3324  */
3325 void account_user_time(struct task_struct *p, cputime_t cputime,
3326                        cputime_t cputime_scaled)
3327 {
3328         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3329         cputime64_t tmp;
3330
3331         /* Add user time to process. */
3332         p->utime = cputime_add(p->utime, cputime);
3333         p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
3334         account_group_user_time(p, cputime);
3335
3336         /* Add user time to cpustat. */
3337         tmp = cputime_to_cputime64(cputime);
3338         if (TASK_NICE(p) > 0)
3339                 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3340         else
3341                 cpustat->user = cputime64_add(cpustat->user, tmp);
3342
3343         cpuacct_update_stats(p, CPUACCT_STAT_USER, cputime);
3344         /* Account for user time used */
3345         acct_update_integrals(p);
3346 }
3347
3348 /*
3349  * Account guest cpu time to a process.
3350  * @p: the process that the cpu time gets accounted to
3351  * @cputime: the cpu time spent in virtual machine since the last update
3352  * @cputime_scaled: cputime scaled by cpu frequency
3353  */
3354 static void account_guest_time(struct task_struct *p, cputime_t cputime,
3355                                cputime_t cputime_scaled)
3356 {
3357         cputime64_t tmp;
3358         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3359
3360         tmp = cputime_to_cputime64(cputime);
3361
3362         /* Add guest time to process. */
3363         p->utime = cputime_add(p->utime, cputime);
3364         p->utimescaled = cputime_add(p->utimescaled, cputime_scaled);
3365         account_group_user_time(p, cputime);
3366         p->gtime = cputime_add(p->gtime, cputime);
3367
3368         /* Add guest time to cpustat. */
3369         if (TASK_NICE(p) > 0) {
3370                 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3371                 cpustat->guest_nice = cputime64_add(cpustat->guest_nice, tmp);
3372         } else {
3373                 cpustat->user = cputime64_add(cpustat->user, tmp);
3374                 cpustat->guest = cputime64_add(cpustat->guest, tmp);
3375         }
3376 }
3377
3378 /*
3379  * Account system cpu time to a process.
3380  * @p: the process that the cpu time gets accounted to
3381  * @hardirq_offset: the offset to subtract from hardirq_count()
3382  * @cputime: the cpu time spent in kernel space since the last update
3383  * @cputime_scaled: cputime scaled by cpu frequency
3384  */
3385 void account_system_time(struct task_struct *p, int hardirq_offset,
3386                          cputime_t cputime, cputime_t cputime_scaled)
3387 {
3388         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3389         cputime64_t tmp;
3390
3391         if ((p->flags & PF_VCPU) && (irq_count() - hardirq_offset == 0)) {
3392                 account_guest_time(p, cputime, cputime_scaled);
3393                 return;
3394         }
3395
3396         /* Add system time to process. */
3397         p->stime = cputime_add(p->stime, cputime);
3398         p->stimescaled = cputime_add(p->stimescaled, cputime_scaled);
3399         account_group_system_time(p, cputime);
3400
3401         /* Add system time to cpustat. */
3402         tmp = cputime_to_cputime64(cputime);
3403         if (hardirq_count() - hardirq_offset)
3404                 cpustat->irq = cputime64_add(cpustat->irq, tmp);
3405         else if (in_serving_softirq())
3406                 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
3407         else
3408                 cpustat->system = cputime64_add(cpustat->system, tmp);
3409
3410         cpuacct_update_stats(p, CPUACCT_STAT_SYSTEM, cputime);
3411
3412         /* Account for system time used */
3413         acct_update_integrals(p);
3414 }
3415
3416 /*
3417  * Account for involuntary wait time.
3418  * @steal: the cpu time spent in involuntary wait
3419  */
3420 void account_steal_time(cputime_t cputime)
3421 {
3422         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3423         cputime64_t cputime64 = cputime_to_cputime64(cputime);
3424
3425         cpustat->steal = cputime64_add(cpustat->steal, cputime64);
3426 }
3427
3428 /*
3429  * Account for idle time.
3430  * @cputime: the cpu time spent in idle wait
3431  */
3432 void account_idle_time(cputime_t cputime)
3433 {
3434         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3435         cputime64_t cputime64 = cputime_to_cputime64(cputime);
3436         struct rq *rq = this_rq();
3437
3438         if (atomic_read(&rq->nr_iowait) > 0)
3439                 cpustat->iowait = cputime64_add(cpustat->iowait, cputime64);
3440         else
3441                 cpustat->idle = cputime64_add(cpustat->idle, cputime64);
3442 }
3443
3444 #ifndef CONFIG_VIRT_CPU_ACCOUNTING
3445
3446 /*
3447  * Account a single tick of cpu time.
3448  * @p: the process that the cpu time gets accounted to
3449  * @user_tick: indicates if the tick is a user or a system tick
3450  */
3451 void account_process_tick(struct task_struct *p, int user_tick)
3452 {
3453         cputime_t one_jiffy_scaled = cputime_to_scaled(cputime_one_jiffy);
3454         struct rq *rq = this_rq();
3455
3456         if (user_tick)
3457                 account_user_time(p, cputime_one_jiffy, one_jiffy_scaled);
3458         else if ((p != rq->idle) || (irq_count() != HARDIRQ_OFFSET))
3459                 account_system_time(p, HARDIRQ_OFFSET, cputime_one_jiffy,
3460                                     one_jiffy_scaled);
3461         else
3462                 account_idle_time(cputime_one_jiffy);
3463 }
3464
3465 /*
3466  * Account multiple ticks of steal time.
3467  * @p: the process from which the cpu time has been stolen
3468  * @ticks: number of stolen ticks
3469  */
3470 void account_steal_ticks(unsigned long ticks)
3471 {
3472         account_steal_time(jiffies_to_cputime(ticks));
3473 }
3474
3475 /*
3476  * Account multiple ticks of idle time.
3477  * @ticks: number of stolen ticks
3478  */
3479 void account_idle_ticks(unsigned long ticks)
3480 {
3481         account_idle_time(jiffies_to_cputime(ticks));
3482 }
3483
3484 #endif
3485
3486 /*
3487  * Use precise platform statistics if available:
3488  */
3489 #ifdef CONFIG_VIRT_CPU_ACCOUNTING
3490 void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
3491 {
3492         *ut = p->utime;
3493         *st = p->stime;
3494 }
3495
3496 void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
3497 {
3498         struct task_cputime cputime;
3499
3500         thread_group_cputime(p, &cputime);
3501
3502         *ut = cputime.utime;
3503         *st = cputime.stime;
3504 }
3505 #else
3506
3507 #ifndef nsecs_to_cputime
3508 # define nsecs_to_cputime(__nsecs)      nsecs_to_jiffies(__nsecs)
3509 #endif
3510
3511 void task_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
3512 {
3513         cputime_t rtime, utime = p->utime, total = cputime_add(utime, p->stime);
3514
3515         /*
3516          * Use CFS's precise accounting:
3517          */
3518         rtime = nsecs_to_cputime(p->se.sum_exec_runtime);
3519
3520         if (total) {
3521                 u64 temp = rtime;
3522
3523                 temp *= utime;
3524                 do_div(temp, total);
3525                 utime = (cputime_t)temp;
3526         } else
3527                 utime = rtime;
3528
3529         /*
3530          * Compare with previous values, to keep monotonicity:
3531          */
3532         p->prev_utime = max(p->prev_utime, utime);
3533         p->prev_stime = max(p->prev_stime, cputime_sub(rtime, p->prev_utime));
3534
3535         *ut = p->prev_utime;
3536         *st = p->prev_stime;
3537 }
3538
3539 /*
3540  * Must be called with siglock held.
3541  */
3542 void thread_group_times(struct task_struct *p, cputime_t *ut, cputime_t *st)
3543 {
3544         struct signal_struct *sig = p->signal;
3545         struct task_cputime cputime;
3546         cputime_t rtime, utime, total;
3547
3548         thread_group_cputime(p, &cputime);
3549
3550         total = cputime_add(cputime.utime, cputime.stime);
3551         rtime = nsecs_to_cputime(cputime.sum_exec_runtime);
3552
3553         if (total) {
3554                 u64 temp = rtime;
3555
3556                 temp *= cputime.utime;
3557                 do_div(temp, total);
3558                 utime = (cputime_t)temp;
3559         } else
3560                 utime = rtime;
3561
3562         sig->prev_utime = max(sig->prev_utime, utime);
3563         sig->prev_stime = max(sig->prev_stime,
3564                               cputime_sub(rtime, sig->prev_utime));
3565
3566         *ut = sig->prev_utime;
3567         *st = sig->prev_stime;
3568 }
3569 #endif
3570
3571 /*
3572  * This function gets called by the timer code, with HZ frequency.
3573  * We call it with interrupts disabled.
3574  *
3575  * It also gets called by the fork code, when changing the parent's
3576  * timeslices.
3577  */
3578 void scheduler_tick(void)
3579 {
3580         int cpu = smp_processor_id();
3581         struct rq *rq = cpu_rq(cpu);
3582         struct task_struct *curr = rq->curr;
3583
3584         sched_clock_tick();
3585
3586         raw_spin_lock(&rq->lock);
3587         update_rq_clock(rq);
3588         update_cpu_load_active(rq);
3589         curr->sched_class->task_tick(rq, curr, 0);
3590         raw_spin_unlock(&rq->lock);
3591
3592         perf_event_task_tick();
3593
3594 #ifdef CONFIG_SMP
3595         rq->idle_at_tick = idle_cpu(cpu);
3596         trigger_load_balance(rq, cpu);
3597 #endif
3598 }
3599
3600 notrace unsigned long get_parent_ip(unsigned long addr)
3601 {
3602         if (in_lock_functions(addr)) {
3603                 addr = CALLER_ADDR2;
3604                 if (in_lock_functions(addr))
3605                         addr = CALLER_ADDR3;
3606         }
3607         return addr;
3608 }
3609
3610 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
3611                                 defined(CONFIG_PREEMPT_TRACER))
3612
3613 void __kprobes add_preempt_count(int val)
3614 {
3615 #ifdef CONFIG_DEBUG_PREEMPT
3616         /*
3617          * Underflow?
3618          */
3619         if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3620                 return;
3621 #endif
3622         preempt_count() += val;
3623 #ifdef CONFIG_DEBUG_PREEMPT
3624         /*
3625          * Spinlock count overflowing soon?
3626          */
3627         DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3628                                 PREEMPT_MASK - 10);
3629 #endif
3630         if (preempt_count() == val)
3631                 trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
3632 }
3633 EXPORT_SYMBOL(add_preempt_count);
3634
3635 void __kprobes sub_preempt_count(int val)
3636 {
3637 #ifdef CONFIG_DEBUG_PREEMPT
3638         /*
3639          * Underflow?
3640          */
3641         if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3642                 return;
3643         /*
3644          * Is the spinlock portion underflowing?
3645          */
3646         if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3647                         !(preempt_count() & PREEMPT_MASK)))
3648                 return;
3649 #endif
3650
3651         if (preempt_count() == val)
3652                 trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1));
3653         preempt_count() -= val;
3654 }
3655 EXPORT_SYMBOL(sub_preempt_count);
3656
3657 #endif
3658
3659 /*
3660  * Print scheduling while atomic bug:
3661  */
3662 static noinline void __schedule_bug(struct task_struct *prev)
3663 {
3664         struct pt_regs *regs = get_irq_regs();
3665
3666         printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3667                 prev->comm, prev->pid, preempt_count());
3668
3669         debug_show_held_locks(prev);
3670         print_modules();
3671         if (irqs_disabled())
3672                 print_irqtrace_events(prev);
3673
3674         if (regs)
3675                 show_regs(regs);
3676         else
3677                 dump_stack();
3678 }
3679
3680 /*
3681  * Various schedule()-time debugging checks and statistics:
3682  */
3683 static inline void schedule_debug(struct task_struct *prev)
3684 {
3685         /*
3686          * Test if we are atomic. Since do_exit() needs to call into
3687          * schedule() atomically, we ignore that path for now.
3688          * Otherwise, whine if we are scheduling when we should not be.
3689          */
3690         if (unlikely(in_atomic_preempt_off() && !prev->exit_state))
3691                 __schedule_bug(prev);
3692
3693         profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3694
3695         schedstat_inc(this_rq(), sched_count);
3696 #ifdef CONFIG_SCHEDSTATS
3697         if (unlikely(prev->lock_depth >= 0)) {
3698                 schedstat_inc(this_rq(), bkl_count);
3699                 schedstat_inc(prev, sched_info.bkl_count);
3700         }
3701 #endif
3702 }
3703
3704 static void put_prev_task(struct rq *rq, struct task_struct *prev)
3705 {
3706         if (prev->se.on_rq)
3707                 update_rq_clock(rq);
3708         rq->skip_clock_update = 0;
3709         prev->sched_class->put_prev_task(rq, prev);
3710 }
3711
3712 /*
3713  * Pick up the highest-prio task:
3714  */
3715 static inline struct task_struct *
3716 pick_next_task(struct rq *rq)
3717 {
3718         const struct sched_class *class;
3719         struct task_struct *p;
3720
3721         /*
3722          * Optimization: we know that if all tasks are in
3723          * the fair class we can call that function directly:
3724          */
3725         if (likely(rq->nr_running == rq->cfs.nr_running)) {
3726                 p = fair_sched_class.pick_next_task(rq);
3727                 if (likely(p))
3728                         return p;
3729         }
3730
3731         for_each_class(class) {
3732                 p = class->pick_next_task(rq);
3733                 if (p)
3734                         return p;
3735         }
3736
3737         BUG(); /* the idle class will always have a runnable task */
3738 }
3739
3740 /*
3741  * schedule() is the main scheduler function.
3742  */
3743 asmlinkage void __sched schedule(void)
3744 {
3745         struct task_struct *prev, *next;
3746         unsigned long *switch_count;
3747         struct rq *rq;
3748         int cpu;
3749
3750 need_resched:
3751         preempt_disable();
3752         cpu = smp_processor_id();
3753         rq = cpu_rq(cpu);
3754         rcu_note_context_switch(cpu);
3755         prev = rq->curr;
3756
3757         release_kernel_lock(prev);
3758 need_resched_nonpreemptible:
3759
3760         schedule_debug(prev);
3761
3762         if (sched_feat(HRTICK))
3763                 hrtick_clear(rq);
3764
3765         raw_spin_lock_irq(&rq->lock);
3766         clear_tsk_need_resched(prev);
3767
3768         switch_count = &prev->nivcsw;
3769         if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3770                 if (unlikely(signal_pending_state(prev->state, prev))) {
3771                         prev->state = TASK_RUNNING;
3772                 } else {
3773                         /*
3774                          * If a worker is going to sleep, notify and
3775                          * ask workqueue whether it wants to wake up a
3776                          * task to maintain concurrency.  If so, wake
3777                          * up the task.
3778                          */
3779                         if (prev->flags & PF_WQ_WORKER) {
3780                                 struct task_struct *to_wakeup;
3781
3782                                 to_wakeup = wq_worker_sleeping(prev, cpu);
3783                                 if (to_wakeup)
3784                                         try_to_wake_up_local(to_wakeup);
3785                         }
3786                         deactivate_task(rq, prev, DEQUEUE_SLEEP);
3787                 }
3788                 switch_count = &prev->nvcsw;
3789         }
3790
3791         pre_schedule(rq, prev);
3792
3793         if (unlikely(!rq->nr_running))
3794                 idle_balance(cpu, rq);
3795
3796         put_prev_task(rq, prev);
3797         next = pick_next_task(rq);
3798
3799         if (likely(prev != next)) {
3800                 sched_info_switch(prev, next);
3801                 perf_event_task_sched_out(prev, next);
3802
3803                 rq->nr_switches++;
3804                 rq->curr = next;
3805                 ++*switch_count;
3806
3807                 context_switch(rq, prev, next); /* unlocks the rq */
3808                 /*
3809                  * The context switch have flipped the stack from under us
3810                  * and restored the local variables which were saved when
3811                  * this task called schedule() in the past. prev == current
3812                  * is still correct, but it can be moved to another cpu/rq.
3813                  */
3814                 cpu = smp_processor_id();
3815                 rq = cpu_rq(cpu);
3816         } else
3817                 raw_spin_unlock_irq(&rq->lock);
3818
3819         post_schedule(rq);
3820
3821         if (unlikely(reacquire_kernel_lock(prev)))
3822                 goto need_resched_nonpreemptible;
3823
3824         preempt_enable_no_resched();
3825         if (need_resched())
3826                 goto need_resched;
3827 }
3828 EXPORT_SYMBOL(schedule);
3829
3830 #ifdef CONFIG_MUTEX_SPIN_ON_OWNER
3831 /*
3832  * Look out! "owner" is an entirely speculative pointer
3833  * access and not reliable.
3834  */
3835 int mutex_spin_on_owner(struct mutex *lock, struct thread_info *owner)
3836 {
3837         unsigned int cpu;
3838         struct rq *rq;
3839
3840         if (!sched_feat(OWNER_SPIN))
3841                 return 0;
3842
3843 #ifdef CONFIG_DEBUG_PAGEALLOC
3844         /*
3845          * Need to access the cpu field knowing that
3846          * DEBUG_PAGEALLOC could have unmapped it if
3847          * the mutex owner just released it and exited.
3848          */
3849         if (probe_kernel_address(&owner->cpu, cpu))
3850                 return 0;
3851 #else
3852         cpu = owner->cpu;
3853 #endif
3854
3855         /*
3856          * Even if the access succeeded (likely case),
3857          * the cpu field may no longer be valid.
3858          */
3859         if (cpu >= nr_cpumask_bits)
3860                 return 0;
3861
3862         /*
3863          * We need to validate that we can do a
3864          * get_cpu() and that we have the percpu area.
3865          */
3866         if (!cpu_online(cpu))
3867                 return 0;
3868
3869         rq = cpu_rq(cpu);
3870
3871         for (;;) {
3872                 /*
3873                  * Owner changed, break to re-assess state.
3874                  */
3875                 if (lock->owner != owner) {
3876                         /*
3877                          * If the lock has switched to a different owner,
3878                          * we likely have heavy contention. Return 0 to quit
3879                          * optimistic spinning and not contend further:
3880                          */
3881                         if (lock->owner)
3882                                 return 0;
3883                         break;
3884                 }
3885
3886                 /*
3887                  * Is that owner really running on that cpu?
3888                  */
3889                 if (task_thread_info(rq->curr) != owner || need_resched())
3890                         return 0;
3891
3892                 arch_mutex_cpu_relax();
3893         }
3894
3895         return 1;
3896 }
3897 #endif
3898
3899 #ifdef CONFIG_PREEMPT
3900 /*
3901  * this is the entry point to schedule() from in-kernel preemption
3902  * off of preempt_enable. Kernel preemptions off return from interrupt
3903  * occur there and call schedule directly.
3904  */
3905 asmlinkage void __sched notrace preempt_schedule(void)
3906 {
3907         struct thread_info *ti = current_thread_info();
3908
3909         /*
3910          * If there is a non-zero preempt_count or interrupts are disabled,
3911          * we do not want to preempt the current task. Just return..
3912          */
3913         if (likely(ti->preempt_count || irqs_disabled()))
3914                 return;
3915
3916         do {
3917                 add_preempt_count_notrace(PREEMPT_ACTIVE);
3918                 schedule();
3919                 sub_preempt_count_notrace(PREEMPT_ACTIVE);
3920
3921                 /*
3922                  * Check again in case we missed a preemption opportunity
3923                  * between schedule and now.
3924                  */
3925                 barrier();
3926         } while (need_resched());
3927 }
3928 EXPORT_SYMBOL(preempt_schedule);
3929
3930 /*
3931  * this is the entry point to schedule() from kernel preemption
3932  * off of irq context.
3933  * Note, that this is called and return with irqs disabled. This will
3934  * protect us against recursive calling from irq.
3935  */
3936 asmlinkage void __sched preempt_schedule_irq(void)
3937 {
3938         struct thread_info *ti = current_thread_info();
3939
3940         /* Catch callers which need to be fixed */
3941         BUG_ON(ti->preempt_count || !irqs_disabled());
3942
3943         do {
3944                 add_preempt_count(PREEMPT_ACTIVE);
3945                 local_irq_enable();
3946                 schedule();
3947                 local_irq_disable();
3948                 sub_preempt_count(PREEMPT_ACTIVE);
3949
3950                 /*
3951                  * Check again in case we missed a preemption opportunity
3952                  * between schedule and now.
3953                  */
3954                 barrier();
3955         } while (need_resched());
3956 }
3957
3958 #endif /* CONFIG_PREEMPT */
3959
3960 int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags,
3961                           void *key)
3962 {
3963         return try_to_wake_up(curr->private, mode, wake_flags);
3964 }
3965 EXPORT_SYMBOL(default_wake_function);
3966
3967 /*
3968  * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3969  * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3970  * number) then we wake all the non-exclusive tasks and one exclusive task.
3971  *
3972  * There are circumstances in which we can try to wake a task which has already
3973  * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3974  * zero in this (rare) case, and we handle it by continuing to scan the queue.
3975  */
3976 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3977                         int nr_exclusive, int wake_flags, void *key)
3978 {
3979         wait_queue_t *curr, *next;
3980
3981         list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
3982                 unsigned flags = curr->flags;
3983
3984                 if (curr->func(curr, mode, wake_flags, key) &&
3985                                 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
3986                         break;
3987         }
3988 }
3989
3990 /**
3991  * __wake_up - wake up threads blocked on a waitqueue.
3992  * @q: the waitqueue
3993  * @mode: which threads
3994  * @nr_exclusive: how many wake-one or wake-many threads to wake up
3995  * @key: is directly passed to the wakeup function
3996  *
3997  * It may be assumed that this function implies a write memory barrier before
3998  * changing the task state if and only if any tasks are woken up.
3999  */
4000 void __wake_up(wait_queue_head_t *q, unsigned int mode,
4001                         int nr_exclusive, void *key)
4002 {
4003         unsigned long flags;
4004
4005         spin_lock_irqsave(&q->lock, flags);
4006         __wake_up_common(q, mode, nr_exclusive, 0, key);
4007         spin_unlock_irqrestore(&q->lock, flags);
4008 }
4009 EXPORT_SYMBOL(__wake_up);
4010
4011 /*
4012  * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4013  */
4014 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4015 {
4016         __wake_up_common(q, mode, 1, 0, NULL);
4017 }
4018 EXPORT_SYMBOL_GPL(__wake_up_locked);
4019
4020 void __wake_up_locked_key(wait_queue_head_t *q, unsigned int mode, void *key)
4021 {
4022         __wake_up_common(q, mode, 1, 0, key);
4023 }
4024
4025 /**
4026  * __wake_up_sync_key - wake up threads blocked on a waitqueue.
4027  * @q: the waitqueue
4028  * @mode: which threads
4029  * @nr_exclusive: how many wake-one or wake-many threads to wake up
4030  * @key: opaque value to be passed to wakeup targets
4031  *
4032  * The sync wakeup differs that the waker knows that it will schedule
4033  * away soon, so while the target thread will be woken up, it will not
4034  * be migrated to another CPU - ie. the two threads are 'synchronized'
4035  * with each other. This can prevent needless bouncing between CPUs.
4036  *
4037  * On UP it can prevent extra preemption.
4038  *
4039  * It may be assumed that this function implies a write memory barrier before
4040  * changing the task state if and only if any tasks are woken up.
4041  */
4042 void __wake_up_sync_key(wait_queue_head_t *q, unsigned int mode,
4043                         int nr_exclusive, void *key)
4044 {
4045         unsigned long flags;
4046         int wake_flags = WF_SYNC;
4047
4048         if (unlikely(!q))
4049                 return;
4050
4051         if (unlikely(!nr_exclusive))
4052                 wake_flags = 0;
4053
4054         spin_lock_irqsave(&q->lock, flags);
4055         __wake_up_common(q, mode, nr_exclusive, wake_flags, key);
4056         spin_unlock_irqrestore(&q->lock, flags);
4057 }
4058 EXPORT_SYMBOL_GPL(__wake_up_sync_key);
4059
4060 /*
4061  * __wake_up_sync - see __wake_up_sync_key()
4062  */
4063 void __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4064 {
4065         __wake_up_sync_key(q, mode, nr_exclusive, NULL);
4066 }
4067 EXPORT_SYMBOL_GPL(__wake_up_sync);      /* For internal use only */
4068
4069 /**
4070  * complete: - signals a single thread waiting on this completion
4071  * @x:  holds the state of this particular completion
4072  *
4073  * This will wake up a single thread waiting on this completion. Threads will be
4074  * awakened in the same order in which they were queued.
4075  *
4076  * See also complete_all(), wait_for_completion() and related routines.
4077  *
4078  * It may be assumed that this function implies a write memory barrier before
4079  * changing the task state if and only if any tasks are woken up.
4080  */
4081 void complete(struct completion *x)
4082 {
4083         unsigned long flags;
4084
4085         spin_lock_irqsave(&x->wait.lock, flags);
4086         x->done++;
4087         __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4088         spin_unlock_irqrestore(&x->wait.lock, flags);
4089 }
4090 EXPORT_SYMBOL(complete);
4091
4092 /**
4093  * complete_all: - signals all threads waiting on this completion
4094  * @x:  holds the state of this particular completion
4095  *
4096  * This will wake up all threads waiting on this particular completion event.
4097  *
4098  * It may be assumed that this function implies a write memory barrier before
4099  * changing the task state if and only if any tasks are woken up.
4100  */
4101 void complete_all(struct completion *x)
4102 {
4103         unsigned long flags;
4104
4105         spin_lock_irqsave(&x->wait.lock, flags);
4106         x->done += UINT_MAX/2;
4107         __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4108         spin_unlock_irqrestore(&x->wait.lock, flags);
4109 }
4110 EXPORT_SYMBOL(complete_all);
4111
4112 static inline long __sched
4113 do_wait_for_common(struct completion *x, long timeout, int state)
4114 {
4115         if (!x->done) {
4116                 DECLARE_WAITQUEUE(wait, current);
4117
4118                 __add_wait_queue_tail_exclusive(&x->wait, &wait);
4119                 do {
4120                         if (signal_pending_state(state, current)) {
4121                                 timeout = -ERESTARTSYS;
4122                                 break;
4123                         }
4124                         __set_current_state(state);
4125                         spin_unlock_irq(&x->wait.lock);
4126                         timeout = schedule_timeout(timeout);
4127                         spin_lock_irq(&x->wait.lock);
4128                 } while (!x->done && timeout);
4129                 __remove_wait_queue(&x->wait, &wait);
4130                 if (!x->done)
4131                         return timeout;
4132         }
4133         x->done--;
4134         return timeout ?: 1;
4135 }
4136
4137 static long __sched
4138 wait_for_common(struct completion *x, long timeout, int state)
4139 {
4140         might_sleep();
4141
4142         spin_lock_irq(&x->wait.lock);
4143         timeout = do_wait_for_common(x, timeout, state);
4144         spin_unlock_irq(&x->wait.lock);
4145         return timeout;
4146 }
4147
4148 /**
4149  * wait_for_completion: - waits for completion of a task
4150  * @x:  holds the state of this particular completion
4151  *
4152  * This waits to be signaled for completion of a specific task. It is NOT
4153  * interruptible and there is no timeout.
4154  *
4155  * See also similar routines (i.e. wait_for_completion_timeout()) with timeout
4156  * and interrupt capability. Also see complete().
4157  */
4158 void __sched wait_for_completion(struct completion *x)
4159 {
4160         wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4161 }
4162 EXPORT_SYMBOL(wait_for_completion);
4163
4164 /**
4165  * wait_for_completion_timeout: - waits for completion of a task (w/timeout)
4166  * @x:  holds the state of this particular completion
4167  * @timeout:  timeout value in jiffies
4168  *
4169  * This waits for either a completion of a specific task to be signaled or for a
4170  * specified timeout to expire. The timeout is in jiffies. It is not
4171  * interruptible.
4172  */
4173 unsigned long __sched
4174 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4175 {
4176         return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4177 }
4178 EXPORT_SYMBOL(wait_for_completion_timeout);
4179
4180 /**
4181  * wait_for_completion_interruptible: - waits for completion of a task (w/intr)
4182  * @x:  holds the state of this particular completion
4183  *
4184  * This waits for completion of a specific task to be signaled. It is
4185  * interruptible.
4186  */
4187 int __sched wait_for_completion_interruptible(struct completion *x)
4188 {
4189         long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4190         if (t == -ERESTARTSYS)
4191                 return t;
4192         return 0;
4193 }
4194 EXPORT_SYMBOL(wait_for_completion_interruptible);
4195
4196 /**
4197  * wait_for_completion_interruptible_timeout: - waits for completion (w/(to,intr))
4198  * @x:  holds the state of this particular completion
4199  * @timeout:  timeout value in jiffies
4200  *
4201  * This waits for either a completion of a specific task to be signaled or for a
4202  * specified timeout to expire. It is interruptible. The timeout is in jiffies.
4203  */
4204 unsigned long __sched
4205 wait_for_completion_interruptible_timeout(struct completion *x,
4206                                           unsigned long timeout)
4207 {
4208         return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4209 }
4210 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4211
4212 /**
4213  * wait_for_completion_killable: - waits for completion of a task (killable)
4214  * @x:  holds the state of this particular completion
4215  *
4216  * This waits to be signaled for completion of a specific task. It can be
4217  * interrupted by a kill signal.
4218  */
4219 int __sched wait_for_completion_killable(struct completion *x)
4220 {
4221         long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4222         if (t == -ERESTARTSYS)
4223                 return t;
4224         return 0;
4225 }
4226 EXPORT_SYMBOL(wait_for_completion_killable);
4227
4228 /**
4229  * wait_for_completion_killable_timeout: - waits for completion of a task (w/(to,killable))
4230  * @x:  holds the state of this particular completion
4231  * @timeout:  timeout value in jiffies
4232  *
4233  * This waits for either a completion of a specific task to be
4234  * signaled or for a specified timeout to expire. It can be
4235  * interrupted by a kill signal. The timeout is in jiffies.
4236  */
4237 unsigned long __sched
4238 wait_for_completion_killable_timeout(struct completion *x,
4239                                      unsigned long timeout)
4240 {
4241         return wait_for_common(x, timeout, TASK_KILLABLE);
4242 }
4243 EXPORT_SYMBOL(wait_for_completion_killable_timeout);
4244
4245 /**
4246  *      try_wait_for_completion - try to decrement a completion without blocking
4247  *      @x:     completion structure
4248  *
4249  *      Returns: 0 if a decrement cannot be done without blocking
4250  *               1 if a decrement succeeded.
4251  *
4252  *      If a completion is being used as a counting completion,
4253  *      attempt to decrement the counter without blocking. This
4254  *      enables us to avoid waiting if the resource the completion
4255  *      is protecting is not available.
4256  */
4257 bool try_wait_for_completion(struct completion *x)
4258 {
4259         unsigned long flags;
4260         int ret = 1;
4261
4262         spin_lock_irqsave(&x->wait.lock, flags);
4263         if (!x->done)
4264                 ret = 0;
4265         else
4266                 x->done--;
4267         spin_unlock_irqrestore(&x->wait.lock, flags);
4268         return ret;
4269 }
4270 EXPORT_SYMBOL(try_wait_for_completion);
4271
4272 /**
4273  *      completion_done - Test to see if a completion has any waiters
4274  *      @x:     completion structure
4275  *
4276  *      Returns: 0 if there are waiters (wait_for_completion() in progress)
4277  *               1 if there are no waiters.
4278  *
4279  */
4280 bool completion_done(struct completion *x)
4281 {
4282         unsigned long flags;
4283         int ret = 1;
4284
4285         spin_lock_irqsave(&x->wait.lock, flags);
4286         if (!x->done)
4287                 ret = 0;
4288         spin_unlock_irqrestore(&x->wait.lock, flags);
4289         return ret;
4290 }
4291 EXPORT_SYMBOL(completion_done);
4292
4293 static long __sched
4294 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4295 {
4296         unsigned long flags;
4297         wait_queue_t wait;
4298
4299         init_waitqueue_entry(&wait, current);
4300
4301         __set_current_state(state);
4302
4303         spin_lock_irqsave(&q->lock, flags);
4304         __add_wait_queue(q, &wait);
4305         spin_unlock(&q->lock);
4306         timeout = schedule_timeout(timeout);
4307         spin_lock_irq(&q->lock);
4308         __remove_wait_queue(q, &wait);
4309         spin_unlock_irqrestore(&q->lock, flags);
4310
4311         return timeout;
4312 }
4313
4314 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4315 {
4316         sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4317 }
4318 EXPORT_SYMBOL(interruptible_sleep_on);
4319
4320 long __sched
4321 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4322 {
4323         return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4324 }
4325 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4326
4327 void __sched sleep_on(wait_queue_head_t *q)
4328 {
4329         sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4330 }
4331 EXPORT_SYMBOL(sleep_on);
4332
4333 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4334 {
4335         return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
4336 }
4337 EXPORT_SYMBOL(sleep_on_timeout);
4338
4339 #ifdef CONFIG_RT_MUTEXES
4340
4341 /*
4342  * rt_mutex_setprio - set the current priority of a task
4343  * @p: task
4344  * @prio: prio value (kernel-internal form)
4345  *
4346  * This function changes the 'effective' priority of a task. It does
4347  * not touch ->normal_prio like __setscheduler().
4348  *
4349  * Used by the rt_mutex code to implement priority inheritance logic.
4350  */
4351 void rt_mutex_setprio(struct task_struct *p, int prio)
4352 {
4353         unsigned long flags;
4354         int oldprio, on_rq, running;
4355         struct rq *rq;
4356         const struct sched_class *prev_class;
4357
4358         BUG_ON(prio < 0 || prio > MAX_PRIO);
4359
4360         rq = task_rq_lock(p, &flags);
4361
4362         trace_sched_pi_setprio(p, prio);
4363         oldprio = p->prio;
4364         prev_class = p->sched_class;
4365         on_rq = p->se.on_rq;
4366         running = task_current(rq, p);
4367         if (on_rq)
4368                 dequeue_task(rq, p, 0);
4369         if (running)
4370                 p->sched_class->put_prev_task(rq, p);
4371
4372         if (rt_prio(prio))
4373                 p->sched_class = &rt_sched_class;
4374         else
4375                 p->sched_class = &fair_sched_class;
4376
4377         p->prio = prio;
4378
4379         if (running)
4380                 p->sched_class->set_curr_task(rq);
4381         if (on_rq) {
4382                 enqueue_task(rq, p, oldprio < prio ? ENQUEUE_HEAD : 0);
4383
4384                 check_class_changed(rq, p, prev_class, oldprio, running);
4385         }
4386         task_rq_unlock(rq, &flags);
4387 }
4388
4389 #endif
4390
4391 void set_user_nice(struct task_struct *p, long nice)
4392 {
4393         int old_prio, delta, on_rq;
4394         unsigned long flags;
4395         struct rq *rq;
4396
4397         if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4398                 return;
4399         /*
4400          * We have to be careful, if called from sys_setpriority(),
4401          * the task might be in the middle of scheduling on another CPU.
4402          */
4403         rq = task_rq_lock(p, &flags);
4404         /*
4405          * The RT priorities are set via sched_setscheduler(), but we still
4406          * allow the 'normal' nice value to be set - but as expected
4407          * it wont have any effect on scheduling until the task is
4408          * SCHED_FIFO/SCHED_RR:
4409          */
4410         if (task_has_rt_policy(p)) {
4411                 p->static_prio = NICE_TO_PRIO(nice);
4412                 goto out_unlock;
4413         }
4414         on_rq = p->se.on_rq;
4415         if (on_rq)
4416                 dequeue_task(rq, p, 0);
4417
4418         p->static_prio = NICE_TO_PRIO(nice);
4419         set_load_weight(p);
4420         old_prio = p->prio;
4421         p->prio = effective_prio(p);
4422         delta = p->prio - old_prio;
4423
4424         if (on_rq) {
4425                 enqueue_task(rq, p, 0);
4426                 /*
4427                  * If the task increased its priority or is running and
4428                  * lowered its priority, then reschedule its CPU:
4429                  */
4430                 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4431                         resched_task(rq->curr);
4432         }
4433 out_unlock:
4434         task_rq_unlock(rq, &flags);
4435 }
4436 EXPORT_SYMBOL(set_user_nice);
4437
4438 /*
4439  * can_nice - check if a task can reduce its nice value
4440  * @p: task
4441  * @nice: nice value
4442  */
4443 int can_nice(const struct task_struct *p, const int nice)
4444 {
4445         /* convert nice value [19,-20] to rlimit style value [1,40] */
4446         int nice_rlim = 20 - nice;
4447
4448         return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
4449                 capable(CAP_SYS_NICE));
4450 }
4451
4452 #ifdef __ARCH_WANT_SYS_NICE
4453
4454 /*
4455  * sys_nice - change the priority of the current process.
4456  * @increment: priority increment
4457  *
4458  * sys_setpriority is a more generic, but much slower function that
4459  * does similar things.
4460  */
4461 SYSCALL_DEFINE1(nice, int, increment)
4462 {
4463         long nice, retval;
4464
4465         /*
4466          * Setpriority might change our priority at the same moment.
4467          * We don't have to worry. Conceptually one call occurs first
4468          * and we have a single winner.
4469          */
4470         if (increment < -40)
4471                 increment = -40;
4472         if (increment > 40)
4473                 increment = 40;
4474
4475         nice = TASK_NICE(current) + increment;
4476         if (nice < -20)
4477                 nice = -20;
4478         if (nice > 19)
4479                 nice = 19;
4480
4481         if (increment < 0 && !can_nice(current, nice))
4482                 return -EPERM;
4483
4484         retval = security_task_setnice(current, nice);
4485         if (retval)
4486                 return retval;
4487
4488         set_user_nice(current, nice);
4489         return 0;
4490 }
4491
4492 #endif
4493
4494 /**
4495  * task_prio - return the priority value of a given task.
4496  * @p: the task in question.
4497  *
4498  * This is the priority value as seen by users in /proc.
4499  * RT tasks are offset by -200. Normal tasks are centered
4500  * around 0, value goes from -16 to +15.
4501  */
4502 int task_prio(const struct task_struct *p)
4503 {
4504         return p->prio - MAX_RT_PRIO;
4505 }
4506
4507 /**
4508  * task_nice - return the nice value of a given task.
4509  * @p: the task in question.
4510  */
4511 int task_nice(const struct task_struct *p)
4512 {
4513         return TASK_NICE(p);
4514 }
4515 EXPORT_SYMBOL(task_nice);
4516
4517 /**
4518  * idle_cpu - is a given cpu idle currently?
4519  * @cpu: the processor in question.
4520  */
4521 int idle_cpu(int cpu)
4522 {
4523         return cpu_curr(cpu) == cpu_rq(cpu)->idle;
4524 }
4525
4526 /**
4527  * idle_task - return the idle task for a given cpu.
4528  * @cpu: the processor in question.
4529  */
4530 struct task_struct *idle_task(int cpu)
4531 {
4532         return cpu_rq(cpu)->idle;
4533 }
4534
4535 /**
4536  * find_process_by_pid - find a process with a matching PID value.
4537  * @pid: the pid in question.
4538  */
4539 static struct task_struct *find_process_by_pid(pid_t pid)
4540 {
4541         return pid ? find_task_by_vpid(pid) : current;
4542 }
4543
4544 /* Actually do priority change: must hold rq lock. */
4545 static void
4546 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
4547 {
4548         BUG_ON(p->se.on_rq);
4549
4550         p->policy = policy;
4551         p->rt_priority = prio;
4552         p->normal_prio = normal_prio(p);
4553         /* we are holding p->pi_lock already */
4554         p->prio = rt_mutex_getprio(p);
4555         if (rt_prio(p->prio))
4556                 p->sched_class = &rt_sched_class;
4557         else
4558                 p->sched_class = &fair_sched_class;
4559         set_load_weight(p);
4560 }
4561
4562 /*
4563  * check the target process has a UID that matches the current process's
4564  */
4565 static bool check_same_owner(struct task_struct *p)
4566 {
4567         const struct cred *cred = current_cred(), *pcred;
4568         bool match;
4569
4570         rcu_read_lock();
4571         pcred = __task_cred(p);
4572         match = (cred->euid == pcred->euid ||
4573                  cred->euid == pcred->uid);
4574         rcu_read_unlock();
4575         return match;
4576 }
4577
4578 static int __sched_setscheduler(struct task_struct *p, int policy,
4579                                 const struct sched_param *param, bool user)
4580 {
4581         int retval, oldprio, oldpolicy = -1, on_rq, running;
4582         unsigned long flags;
4583         const struct sched_class *prev_class;
4584         struct rq *rq;
4585         int reset_on_fork;
4586
4587         /* may grab non-irq protected spin_locks */
4588         BUG_ON(in_interrupt());
4589 recheck:
4590         /* double check policy once rq lock held */
4591         if (policy < 0) {
4592                 reset_on_fork = p->sched_reset_on_fork;
4593                 policy = oldpolicy = p->policy;
4594         } else {
4595                 reset_on_fork = !!(policy & SCHED_RESET_ON_FORK);
4596                 policy &= ~SCHED_RESET_ON_FORK;
4597
4598                 if (policy != SCHED_FIFO && policy != SCHED_RR &&
4599                                 policy != SCHED_NORMAL && policy != SCHED_BATCH &&
4600                                 policy != SCHED_IDLE)
4601                         return -EINVAL;
4602         }
4603
4604         /*
4605          * Valid priorities for SCHED_FIFO and SCHED_RR are
4606          * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4607          * SCHED_BATCH and SCHED_IDLE is 0.
4608          */
4609         if (param->sched_priority < 0 ||
4610             (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
4611             (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
4612                 return -EINVAL;
4613         if (rt_policy(policy) != (param->sched_priority != 0))
4614                 return -EINVAL;
4615
4616         /*
4617          * Allow unprivileged RT tasks to decrease priority:
4618          */
4619         if (user && !capable(CAP_SYS_NICE)) {
4620                 if (rt_policy(policy)) {
4621                         unsigned long rlim_rtprio =
4622                                         task_rlimit(p, RLIMIT_RTPRIO);
4623
4624                         /* can't set/change the rt policy */
4625                         if (policy != p->policy && !rlim_rtprio)
4626                                 return -EPERM;
4627
4628                         /* can't increase priority */
4629                         if (param->sched_priority > p->rt_priority &&
4630                             param->sched_priority > rlim_rtprio)
4631                                 return -EPERM;
4632                 }
4633                 /*
4634                  * Like positive nice levels, dont allow tasks to
4635                  * move out of SCHED_IDLE either:
4636                  */
4637                 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
4638                         return -EPERM;
4639
4640                 /* can't change other user's priorities */
4641                 if (!check_same_owner(p))
4642                         return -EPERM;
4643
4644                 /* Normal users shall not reset the sched_reset_on_fork flag */
4645                 if (p->sched_reset_on_fork && !reset_on_fork)
4646                         return -EPERM;
4647         }
4648
4649         if (user) {
4650                 retval = security_task_setscheduler(p);
4651                 if (retval)
4652                         return retval;
4653         }
4654
4655         /*
4656          * make sure no PI-waiters arrive (or leave) while we are
4657          * changing the priority of the task:
4658          */
4659         raw_spin_lock_irqsave(&p->pi_lock, flags);
4660         /*
4661          * To be able to change p->policy safely, the apropriate
4662          * runqueue lock must be held.
4663          */
4664         rq = __task_rq_lock(p);
4665
4666         /*
4667          * Changing the policy of the stop threads its a very bad idea
4668          */
4669         if (p == rq->stop) {
4670                 __task_rq_unlock(rq);
4671                 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4672                 return -EINVAL;
4673         }
4674
4675 #ifdef CONFIG_RT_GROUP_SCHED
4676         if (user) {
4677                 /*
4678                  * Do not allow realtime tasks into groups that have no runtime
4679                  * assigned.
4680                  */
4681                 if (rt_bandwidth_enabled() && rt_policy(policy) &&
4682                                 task_group(p)->rt_bandwidth.rt_runtime == 0) {
4683                         __task_rq_unlock(rq);
4684                         raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4685                         return -EPERM;
4686                 }
4687         }
4688 #endif
4689
4690         /* recheck policy now with rq lock held */
4691         if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4692                 policy = oldpolicy = -1;
4693                 __task_rq_unlock(rq);
4694                 raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4695                 goto recheck;
4696         }
4697         on_rq = p->se.on_rq;
4698         running = task_current(rq, p);
4699         if (on_rq)
4700                 deactivate_task(rq, p, 0);
4701         if (running)
4702                 p->sched_class->put_prev_task(rq, p);
4703
4704         p->sched_reset_on_fork = reset_on_fork;
4705
4706         oldprio = p->prio;
4707         prev_class = p->sched_class;
4708         __setscheduler(rq, p, policy, param->sched_priority);
4709
4710         if (running)
4711                 p->sched_class->set_curr_task(rq);
4712         if (on_rq) {
4713                 activate_task(rq, p, 0);
4714
4715                 check_class_changed(rq, p, prev_class, oldprio, running);
4716         }
4717         __task_rq_unlock(rq);
4718         raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4719
4720         rt_mutex_adjust_pi(p);
4721
4722         return 0;
4723 }
4724
4725 /**
4726  * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4727  * @p: the task in question.
4728  * @policy: new policy.
4729  * @param: structure containing the new RT priority.
4730  *
4731  * NOTE that the task may be already dead.
4732  */
4733 int sched_setscheduler(struct task_struct *p, int policy,
4734                        const struct sched_param *param)
4735 {
4736         return __sched_setscheduler(p, policy, param, true);
4737 }
4738 EXPORT_SYMBOL_GPL(sched_setscheduler);
4739
4740 /**
4741  * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4742  * @p: the task in question.
4743  * @policy: new policy.
4744  * @param: structure containing the new RT priority.
4745  *
4746  * Just like sched_setscheduler, only don't bother checking if the
4747  * current context has permission.  For example, this is needed in
4748  * stop_machine(): we create temporary high priority worker threads,
4749  * but our caller might not have that capability.
4750  */
4751 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
4752                                const struct sched_param *param)
4753 {
4754         return __sched_setscheduler(p, policy, param, false);
4755 }
4756
4757 static int
4758 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4759 {
4760         struct sched_param lparam;
4761         struct task_struct *p;
4762         int retval;
4763
4764         if (!param || pid < 0)
4765                 return -EINVAL;
4766         if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4767                 return -EFAULT;
4768
4769         rcu_read_lock();
4770         retval = -ESRCH;
4771         p = find_process_by_pid(pid);
4772         if (p != NULL)
4773                 retval = sched_setscheduler(p, policy, &lparam);
4774         rcu_read_unlock();
4775
4776         return retval;
4777 }
4778
4779 /**
4780  * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4781  * @pid: the pid in question.
4782  * @policy: new policy.
4783  * @param: structure containing the new RT priority.
4784  */
4785 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy,
4786                 struct sched_param __user *, param)
4787 {
4788         /* negative values for policy are not valid */
4789         if (policy < 0)
4790                 return -EINVAL;
4791
4792         return do_sched_setscheduler(pid, policy, param);
4793 }
4794
4795 /**
4796  * sys_sched_setparam - set/change the RT priority of a thread
4797  * @pid: the pid in question.
4798  * @param: structure containing the new RT priority.
4799  */
4800 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
4801 {
4802         return do_sched_setscheduler(pid, -1, param);
4803 }
4804
4805 /**
4806  * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4807  * @pid: the pid in question.
4808  */
4809 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
4810 {
4811         struct task_struct *p;
4812         int retval;
4813
4814         if (pid < 0)
4815                 return -EINVAL;
4816
4817         retval = -ESRCH;
4818         rcu_read_lock();
4819         p = find_process_by_pid(pid);
4820         if (p) {
4821                 retval = security_task_getscheduler(p);
4822                 if (!retval)
4823                         retval = p->policy
4824                                 | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
4825         }
4826         rcu_read_unlock();
4827         return retval;
4828 }
4829
4830 /**
4831  * sys_sched_getparam - get the RT priority of a thread
4832  * @pid: the pid in question.
4833  * @param: structure containing the RT priority.
4834  */
4835 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
4836 {
4837         struct sched_param lp;
4838         struct task_struct *p;
4839         int retval;
4840
4841         if (!param || pid < 0)
4842                 return -EINVAL;
4843
4844         rcu_read_lock();
4845         p = find_process_by_pid(pid);
4846         retval = -ESRCH;
4847         if (!p)
4848                 goto out_unlock;
4849
4850         retval = security_task_getscheduler(p);
4851         if (retval)
4852                 goto out_unlock;
4853
4854         lp.sched_priority = p->rt_priority;
4855         rcu_read_unlock();
4856
4857         /*
4858          * This one might sleep, we cannot do it with a spinlock held ...
4859          */
4860         retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4861
4862         return retval;
4863
4864 out_unlock:
4865         rcu_read_unlock();
4866         return retval;
4867 }
4868
4869 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
4870 {
4871         cpumask_var_t cpus_allowed, new_mask;
4872         struct task_struct *p;
4873         int retval;
4874
4875         get_online_cpus();
4876         rcu_read_lock();
4877
4878         p = find_process_by_pid(pid);
4879         if (!p) {
4880                 rcu_read_unlock();
4881                 put_online_cpus();
4882                 return -ESRCH;
4883         }
4884
4885         /* Prevent p going away */
4886         get_task_struct(p);
4887         rcu_read_unlock();
4888
4889         if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4890                 retval = -ENOMEM;
4891                 goto out_put_task;
4892         }
4893         if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4894                 retval = -ENOMEM;
4895                 goto out_free_cpus_allowed;
4896         }
4897         retval = -EPERM;
4898         if (!check_same_owner(p) && !capable(CAP_SYS_NICE))
4899                 goto out_unlock;
4900
4901         retval = security_task_setscheduler(p);
4902         if (retval)
4903                 goto out_unlock;
4904
4905         cpuset_cpus_allowed(p, cpus_allowed);
4906         cpumask_and(new_mask, in_mask, cpus_allowed);
4907 again:
4908         retval = set_cpus_allowed_ptr(p, new_mask);
4909
4910         if (!retval) {
4911                 cpuset_cpus_allowed(p, cpus_allowed);
4912                 if (!cpumask_subset(new_mask, cpus_allowed)) {
4913                         /*
4914                          * We must have raced with a concurrent cpuset
4915                          * update. Just reset the cpus_allowed to the
4916                          * cpuset's cpus_allowed
4917                          */
4918                         cpumask_copy(new_mask, cpus_allowed);
4919                         goto again;
4920                 }
4921         }
4922 out_unlock:
4923         free_cpumask_var(new_mask);
4924 out_free_cpus_allowed:
4925         free_cpumask_var(cpus_allowed);
4926 out_put_task:
4927         put_task_struct(p);
4928         put_online_cpus();
4929         return retval;
4930 }
4931
4932 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4933                              struct cpumask *new_mask)
4934 {
4935         if (len < cpumask_size())
4936                 cpumask_clear(new_mask);
4937         else if (len > cpumask_size())
4938                 len = cpumask_size();
4939
4940         return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4941 }
4942
4943 /**
4944  * sys_sched_setaffinity - set the cpu affinity of a process
4945  * @pid: pid of the process
4946  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4947  * @user_mask_ptr: user-space pointer to the new cpu mask
4948  */
4949 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4950                 unsigned long __user *, user_mask_ptr)
4951 {
4952         cpumask_var_t new_mask;
4953         int retval;
4954
4955         if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4956                 return -ENOMEM;
4957
4958         retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4959         if (retval == 0)
4960                 retval = sched_setaffinity(pid, new_mask);
4961         free_cpumask_var(new_mask);
4962         return retval;
4963 }
4964
4965 long sched_getaffinity(pid_t pid, struct cpumask *mask)
4966 {
4967         struct task_struct *p;
4968         unsigned long flags;
4969         struct rq *rq;
4970         int retval;
4971
4972         get_online_cpus();
4973         rcu_read_lock();
4974
4975         retval = -ESRCH;
4976         p = find_process_by_pid(pid);
4977         if (!p)
4978                 goto out_unlock;
4979
4980         retval = security_task_getscheduler(p);
4981         if (retval)
4982                 goto out_unlock;
4983
4984         rq = task_rq_lock(p, &flags);
4985         cpumask_and(mask, &p->cpus_allowed, cpu_online_mask);
4986         task_rq_unlock(rq, &flags);
4987
4988 out_unlock:
4989         rcu_read_unlock();
4990         put_online_cpus();
4991
4992         return retval;
4993 }
4994
4995 /**
4996  * sys_sched_getaffinity - get the cpu affinity of a process
4997  * @pid: pid of the process
4998  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4999  * @user_mask_ptr: user-space pointer to hold the current cpu mask
5000  */
5001 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
5002                 unsigned long __user *, user_mask_ptr)
5003 {
5004         int ret;
5005         cpumask_var_t mask;
5006
5007         if ((len * BITS_PER_BYTE) < nr_cpu_ids)
5008                 return -EINVAL;
5009         if (len & (sizeof(unsigned long)-1))
5010                 return -EINVAL;
5011
5012         if (!alloc_cpumask_var(&mask, GFP_KERNEL))
5013                 return -ENOMEM;
5014
5015         ret = sched_getaffinity(pid, mask);
5016         if (ret == 0) {
5017                 size_t retlen = min_t(size_t, len, cpumask_size());
5018
5019                 if (copy_to_user(user_mask_ptr, mask, retlen))
5020                         ret = -EFAULT;
5021                 else
5022                         ret = retlen;
5023         }
5024         free_cpumask_var(mask);
5025
5026         return ret;
5027 }
5028
5029 /**
5030  * sys_sched_yield - yield the current processor to other threads.
5031  *
5032  * This function yields the current CPU to other tasks. If there are no
5033  * other threads running on this CPU then this function will return.
5034  */
5035 SYSCALL_DEFINE0(sched_yield)
5036 {
5037         struct rq *rq = this_rq_lock();
5038
5039         schedstat_inc(rq, yld_count);
5040         current->sched_class->yield_task(rq);
5041
5042         /*
5043          * Since we are going to call schedule() anyway, there's
5044          * no need to preempt or enable interrupts:
5045          */
5046         __release(rq->lock);
5047         spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5048         do_raw_spin_unlock(&rq->lock);
5049         preempt_enable_no_resched();
5050
5051         schedule();
5052
5053         return 0;
5054 }
5055
5056 static inline int should_resched(void)
5057 {
5058         return need_resched() && !(preempt_count() & PREEMPT_ACTIVE);
5059 }
5060
5061 static void __cond_resched(void)
5062 {
5063         add_preempt_count(PREEMPT_ACTIVE);
5064         schedule();
5065         sub_preempt_count(PREEMPT_ACTIVE);
5066 }
5067
5068 int __sched _cond_resched(void)
5069 {
5070         if (should_resched()) {
5071                 __cond_resched();
5072                 return 1;
5073         }
5074         return 0;
5075 }
5076 EXPORT_SYMBOL(_cond_resched);
5077
5078 /*
5079  * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
5080  * call schedule, and on return reacquire the lock.
5081  *
5082  * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5083  * operations here to prevent schedule() from being called twice (once via
5084  * spin_unlock(), once by hand).
5085  */
5086 int __cond_resched_lock(spinlock_t *lock)
5087 {
5088         int resched = should_resched();
5089         int ret = 0;
5090
5091         lockdep_assert_held(lock);
5092
5093         if (spin_needbreak(lock) || resched) {
5094                 spin_unlock(lock);
5095                 if (resched)
5096                         __cond_resched();
5097                 else
5098                         cpu_relax();
5099                 ret = 1;
5100                 spin_lock(lock);
5101         }
5102         return ret;
5103 }
5104 EXPORT_SYMBOL(__cond_resched_lock);
5105
5106 int __sched __cond_resched_softirq(void)
5107 {
5108         BUG_ON(!in_softirq());
5109
5110         if (should_resched()) {
5111                 local_bh_enable();
5112                 __cond_resched();
5113                 local_bh_disable();
5114                 return 1;
5115         }
5116         return 0;
5117 }
5118 EXPORT_SYMBOL(__cond_resched_softirq);
5119
5120 /**
5121  * yield - yield the current processor to other threads.
5122  *
5123  * This is a shortcut for kernel-space yielding - it marks the
5124  * thread runnable and calls sys_sched_yield().
5125  */
5126 void __sched yield(void)
5127 {
5128         set_current_state(TASK_RUNNING);
5129         sys_sched_yield();
5130 }
5131 EXPORT_SYMBOL(yield);
5132
5133 /*
5134  * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5135  * that process accounting knows that this is a task in IO wait state.
5136  */
5137 void __sched io_schedule(void)
5138 {
5139         struct rq *rq = raw_rq();
5140
5141         delayacct_blkio_start();
5142         atomic_inc(&rq->nr_iowait);
5143         current->in_iowait = 1;
5144         schedule();
5145         current->in_iowait = 0;
5146         atomic_dec(&rq->nr_iowait);
5147         delayacct_blkio_end();
5148 }
5149 EXPORT_SYMBOL(io_schedule);
5150
5151 long __sched io_schedule_timeout(long timeout)
5152 {
5153         struct rq *rq = raw_rq();
5154         long ret;
5155
5156         delayacct_blkio_start();
5157         atomic_inc(&rq->nr_iowait);
5158         current->in_iowait = 1;
5159         ret = schedule_timeout(timeout);
5160         current->in_iowait = 0;
5161         atomic_dec(&rq->nr_iowait);
5162         delayacct_blkio_end();
5163         return ret;
5164 }
5165
5166 /**
5167  * sys_sched_get_priority_max - return maximum RT priority.
5168  * @policy: scheduling class.
5169  *
5170  * this syscall returns the maximum rt_priority that can be used
5171  * by a given scheduling class.
5172  */
5173 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
5174 {
5175         int ret = -EINVAL;
5176
5177         switch (policy) {
5178         case SCHED_FIFO:
5179         case SCHED_RR:
5180                 ret = MAX_USER_RT_PRIO-1;
5181                 break;
5182         case SCHED_NORMAL:
5183         case SCHED_BATCH:
5184         case SCHED_IDLE:
5185                 ret = 0;
5186                 break;
5187         }
5188         return ret;
5189 }
5190
5191 /**
5192  * sys_sched_get_priority_min - return minimum RT priority.
5193  * @policy: scheduling class.
5194  *
5195  * this syscall returns the minimum rt_priority that can be used
5196  * by a given scheduling class.
5197  */
5198 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
5199 {
5200         int ret = -EINVAL;
5201
5202         switch (policy) {
5203         case SCHED_FIFO:
5204         case SCHED_RR:
5205                 ret = 1;
5206                 break;
5207         case SCHED_NORMAL:
5208         case SCHED_BATCH:
5209         case SCHED_IDLE:
5210                 ret = 0;
5211         }
5212         return ret;
5213 }
5214
5215 /**
5216  * sys_sched_rr_get_interval - return the default timeslice of a process.
5217  * @pid: pid of the process.
5218  * @interval: userspace pointer to the timeslice value.
5219  *
5220  * this syscall writes the default timeslice value of a given process
5221  * into the user-space timespec buffer. A value of '0' means infinity.
5222  */
5223 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
5224                 struct timespec __user *, interval)
5225 {
5226         struct task_struct *p;
5227         unsigned int time_slice;
5228         unsigned long flags;
5229         struct rq *rq;
5230         int retval;
5231         struct timespec t;
5232
5233         if (pid < 0)
5234                 return -EINVAL;
5235
5236         retval = -ESRCH;
5237         rcu_read_lock();
5238         p = find_process_by_pid(pid);
5239         if (!p)
5240                 goto out_unlock;
5241
5242         retval = security_task_getscheduler(p);
5243         if (retval)
5244                 goto out_unlock;
5245
5246         rq = task_rq_lock(p, &flags);
5247         time_slice = p->sched_class->get_rr_interval(rq, p);
5248         task_rq_unlock(rq, &flags);
5249
5250         rcu_read_unlock();
5251         jiffies_to_timespec(time_slice, &t);
5252         retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5253         return retval;
5254
5255 out_unlock:
5256         rcu_read_unlock();
5257         return retval;
5258 }
5259
5260 static const char stat_nam[] = TASK_STATE_TO_CHAR_STR;
5261
5262 void sched_show_task(struct task_struct *p)
5263 {
5264         unsigned long free = 0;
5265         unsigned state;
5266
5267         state = p->state ? __ffs(p->state) + 1 : 0;
5268         printk(KERN_INFO "%-15.15s %c", p->comm,
5269                 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5270 #if BITS_PER_LONG == 32
5271         if (state == TASK_RUNNING)
5272                 printk(KERN_CONT " running  ");
5273         else
5274                 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5275 #else
5276         if (state == TASK_RUNNING)
5277                 printk(KERN_CONT "  running task    ");
5278         else
5279                 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5280 #endif
5281 #ifdef CONFIG_DEBUG_STACK_USAGE
5282         free = stack_not_used(p);
5283 #endif
5284         printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
5285                 task_pid_nr(p), task_pid_nr(p->real_parent),
5286                 (unsigned long)task_thread_info(p)->flags);
5287
5288         show_stack(p, NULL);
5289 }
5290
5291 void show_state_filter(unsigned long state_filter)
5292 {
5293         struct task_struct *g, *p;
5294
5295 #if BITS_PER_LONG == 32
5296         printk(KERN_INFO
5297                 "  task                PC stack   pid father\n");
5298 #else
5299         printk(KERN_INFO
5300                 "  task                        PC stack   pid father\n");
5301 #endif
5302         read_lock(&tasklist_lock);
5303         do_each_thread(g, p) {
5304                 /*
5305                  * reset the NMI-timeout, listing all files on a slow
5306                  * console might take alot of time:
5307                  */
5308                 touch_nmi_watchdog();
5309                 if (!state_filter || (p->state & state_filter))
5310                         sched_show_task(p);
5311         } while_each_thread(g, p);
5312
5313         touch_all_softlockup_watchdogs();
5314
5315 #ifdef CONFIG_SCHED_DEBUG
5316         sysrq_sched_debug_show();
5317 #endif
5318         read_unlock(&tasklist_lock);
5319         /*
5320          * Only show locks if all tasks are dumped:
5321          */
5322         if (!state_filter)
5323                 debug_show_all_locks();
5324 }
5325
5326 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5327 {
5328         idle->sched_class = &idle_sched_class;
5329 }
5330
5331 /**
5332  * init_idle - set up an idle thread for a given CPU
5333  * @idle: task in question
5334  * @cpu: cpu the idle task belongs to
5335  *
5336  * NOTE: this function does not set the idle thread's NEED_RESCHED
5337  * flag, to make booting more robust.
5338  */
5339 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5340 {
5341         struct rq *rq = cpu_rq(cpu);
5342         unsigned long flags;
5343
5344         raw_spin_lock_irqsave(&rq->lock, flags);
5345
5346         __sched_fork(idle);
5347         idle->state = TASK_RUNNING;
5348         idle->se.exec_start = sched_clock();
5349
5350         cpumask_copy(&idle->cpus_allowed, cpumask_of(cpu));
5351         /*
5352          * We're having a chicken and egg problem, even though we are
5353          * holding rq->lock, the cpu isn't yet set to this cpu so the
5354          * lockdep check in task_group() will fail.
5355          *
5356          * Similar case to sched_fork(). / Alternatively we could
5357          * use task_rq_lock() here and obtain the other rq->lock.
5358          *
5359          * Silence PROVE_RCU
5360          */
5361         rcu_read_lock();
5362         __set_task_cpu(idle, cpu);
5363         rcu_read_unlock();
5364
5365         rq->curr = rq->idle = idle;
5366 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5367         idle->oncpu = 1;
5368 #endif
5369         raw_spin_unlock_irqrestore(&rq->lock, flags);
5370
5371         /* Set the preempt count _outside_ the spinlocks! */
5372 #if defined(CONFIG_PREEMPT)
5373         task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
5374 #else
5375         task_thread_info(idle)->preempt_count = 0;
5376 #endif
5377         /*
5378          * The idle tasks have their own, simple scheduling class:
5379          */
5380         idle->sched_class = &idle_sched_class;
5381         ftrace_graph_init_task(idle);
5382 }
5383
5384 /*
5385  * In a system that switches off the HZ timer nohz_cpu_mask
5386  * indicates which cpus entered this state. This is used
5387  * in the rcu update to wait only for active cpus. For system
5388  * which do not switch off the HZ timer nohz_cpu_mask should
5389  * always be CPU_BITS_NONE.
5390  */
5391 cpumask_var_t nohz_cpu_mask;
5392
5393 /*
5394  * Increase the granularity value when there are more CPUs,
5395  * because with more CPUs the 'effective latency' as visible
5396  * to users decreases. But the relationship is not linear,
5397  * so pick a second-best guess by going with the log2 of the
5398  * number of CPUs.
5399  *
5400  * This idea comes from the SD scheduler of Con Kolivas:
5401  */
5402 static int get_update_sysctl_factor(void)
5403 {
5404         unsigned int cpus = min_t(int, num_online_cpus(), 8);
5405         unsigned int factor;
5406
5407         switch (sysctl_sched_tunable_scaling) {
5408         case SCHED_TUNABLESCALING_NONE:
5409                 factor = 1;
5410                 break;
5411         case SCHED_TUNABLESCALING_LINEAR:
5412                 factor = cpus;
5413                 break;
5414         case SCHED_TUNABLESCALING_LOG:
5415         default:
5416                 factor = 1 + ilog2(cpus);
5417                 break;
5418         }
5419
5420         return factor;
5421 }
5422
5423 static void update_sysctl(void)
5424 {
5425         unsigned int factor = get_update_sysctl_factor();
5426
5427 #define SET_SYSCTL(name) \
5428         (sysctl_##name = (factor) * normalized_sysctl_##name)
5429         SET_SYSCTL(sched_min_granularity);
5430         SET_SYSCTL(sched_latency);
5431         SET_SYSCTL(sched_wakeup_granularity);
5432 #undef SET_SYSCTL
5433 }
5434
5435 static inline void sched_init_granularity(void)
5436 {
5437         update_sysctl();
5438 }
5439
5440 #ifdef CONFIG_SMP
5441 /*
5442  * This is how migration works:
5443  *
5444  * 1) we invoke migration_cpu_stop() on the target CPU using
5445  *    stop_one_cpu().
5446  * 2) stopper starts to run (implicitly forcing the migrated thread
5447  *    off the CPU)
5448  * 3) it checks whether the migrated task is still in the wrong runqueue.
5449  * 4) if it's in the wrong runqueue then the migration thread removes
5450  *    it and puts it into the right queue.
5451  * 5) stopper completes and stop_one_cpu() returns and the migration
5452  *    is done.
5453  */
5454
5455 /*
5456  * Change a given task's CPU affinity. Migrate the thread to a
5457  * proper CPU and schedule it away if the CPU it's executing on
5458  * is removed from the allowed bitmask.
5459  *
5460  * NOTE: the caller must have a valid reference to the task, the
5461  * task must not exit() & deallocate itself prematurely. The
5462  * call is not atomic; no spinlocks may be held.
5463  */
5464 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
5465 {
5466         unsigned long flags;
5467         struct rq *rq;
5468         unsigned int dest_cpu;
5469         int ret = 0;
5470
5471         /*
5472          * Serialize against TASK_WAKING so that ttwu() and wunt() can
5473          * drop the rq->lock and still rely on ->cpus_allowed.
5474          */
5475 again:
5476         while (task_is_waking(p))
5477                 cpu_relax();
5478         rq = task_rq_lock(p, &flags);
5479         if (task_is_waking(p)) {
5480                 task_rq_unlock(rq, &flags);
5481                 goto again;
5482         }
5483
5484         if (!cpumask_intersects(new_mask, cpu_active_mask)) {
5485                 ret = -EINVAL;
5486                 goto out;
5487         }
5488
5489         if (unlikely((p->flags & PF_THREAD_BOUND) && p != current &&
5490                      !cpumask_equal(&p->cpus_allowed, new_mask))) {
5491                 ret = -EINVAL;
5492                 goto out;
5493         }
5494
5495         if (p->sched_class->set_cpus_allowed)
5496                 p->sched_class->set_cpus_allowed(p, new_mask);
5497         else {
5498                 cpumask_copy(&p->cpus_allowed, new_mask);
5499                 p->rt.nr_cpus_allowed = cpumask_weight(new_mask);
5500         }
5501
5502         /* Can the task run on the task's current CPU? If so, we're done */
5503         if (cpumask_test_cpu(task_cpu(p), new_mask))
5504                 goto out;
5505
5506         dest_cpu = cpumask_any_and(cpu_active_mask, new_mask);
5507         if (migrate_task(p, dest_cpu)) {
5508                 struct migration_arg arg = { p, dest_cpu };
5509                 /* Need help from migration thread: drop lock and wait. */
5510                 task_rq_unlock(rq, &flags);
5511                 stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
5512                 tlb_migrate_finish(p->mm);
5513                 return 0;
5514         }
5515 out:
5516         task_rq_unlock(rq, &flags);
5517
5518         return ret;
5519 }
5520 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
5521
5522 /*
5523  * Move (not current) task off this cpu, onto dest cpu. We're doing
5524  * this because either it can't run here any more (set_cpus_allowed()
5525  * away from this CPU, or CPU going down), or because we're
5526  * attempting to rebalance this task on exec (sched_exec).
5527  *
5528  * So we race with normal scheduler movements, but that's OK, as long
5529  * as the task is no longer on this CPU.
5530  *
5531  * Returns non-zero if task was successfully migrated.
5532  */
5533 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
5534 {
5535         struct rq *rq_dest, *rq_src;
5536         int ret = 0;
5537
5538         if (unlikely(!cpu_active(dest_cpu)))
5539                 return ret;
5540
5541         rq_src = cpu_rq(src_cpu);
5542         rq_dest = cpu_rq(dest_cpu);
5543
5544         double_rq_lock(rq_src, rq_dest);
5545         /* Already moved. */
5546         if (task_cpu(p) != src_cpu)
5547                 goto done;
5548         /* Affinity changed (again). */
5549         if (!cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
5550                 goto fail;
5551
5552         /*
5553          * If we're not on a rq, the next wake-up will ensure we're
5554          * placed properly.
5555          */
5556         if (p->se.on_rq) {
5557                 deactivate_task(rq_src, p, 0);
5558                 set_task_cpu(p, dest_cpu);
5559                 activate_task(rq_dest, p, 0);
5560                 check_preempt_curr(rq_dest, p, 0);
5561         }
5562 done:
5563         ret = 1;
5564 fail:
5565         double_rq_unlock(rq_src, rq_dest);
5566         return ret;
5567 }
5568
5569 /*
5570  * migration_cpu_stop - this will be executed by a highprio stopper thread
5571  * and performs thread migration by bumping thread off CPU then
5572  * 'pushing' onto another runqueue.
5573  */
5574 static int migration_cpu_stop(void *data)
5575 {
5576         struct migration_arg *arg = data;
5577
5578         /*
5579          * The original target cpu might have gone down and we might
5580          * be on another cpu but it doesn't matter.
5581          */
5582         local_irq_disable();
5583         __migrate_task(arg->task, raw_smp_processor_id(), arg->dest_cpu);
5584         local_irq_enable();
5585         return 0;
5586 }
5587
5588 #ifdef CONFIG_HOTPLUG_CPU
5589
5590 /*
5591  * Ensures that the idle task is using init_mm right before its cpu goes
5592  * offline.
5593  */
5594 void idle_task_exit(void)
5595 {
5596         struct mm_struct *mm = current->active_mm;
5597
5598         BUG_ON(cpu_online(smp_processor_id()));
5599
5600         if (mm != &init_mm)
5601                 switch_mm(mm, &init_mm, current);
5602         mmdrop(mm);
5603 }
5604
5605 /*
5606  * While a dead CPU has no uninterruptible tasks queued at this point,
5607  * it might still have a nonzero ->nr_uninterruptible counter, because
5608  * for performance reasons the counter is not stricly tracking tasks to
5609  * their home CPUs. So we just add the counter to another CPU's counter,
5610  * to keep the global sum constant after CPU-down:
5611  */
5612 static void migrate_nr_uninterruptible(struct rq *rq_src)
5613 {
5614         struct rq *rq_dest = cpu_rq(cpumask_any(cpu_active_mask));
5615
5616         rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5617         rq_src->nr_uninterruptible = 0;
5618 }
5619
5620 /*
5621  * remove the tasks which were accounted by rq from calc_load_tasks.
5622  */
5623 static void calc_global_load_remove(struct rq *rq)
5624 {
5625         atomic_long_sub(rq->calc_load_active, &calc_load_tasks);
5626         rq->calc_load_active = 0;
5627 }
5628
5629 /*
5630  * Migrate all tasks from the rq, sleeping tasks will be migrated by
5631  * try_to_wake_up()->select_task_rq().
5632  *
5633  * Called with rq->lock held even though we'er in stop_machine() and
5634  * there's no concurrency possible, we hold the required locks anyway
5635  * because of lock validation efforts.
5636  */
5637 static void migrate_tasks(unsigned int dead_cpu)
5638 {
5639         struct rq *rq = cpu_rq(dead_cpu);
5640         struct task_struct *next, *stop = rq->stop;
5641         int dest_cpu;
5642
5643         /*
5644          * Fudge the rq selection such that the below task selection loop
5645          * doesn't get stuck on the currently eligible stop task.
5646          *
5647          * We're currently inside stop_machine() and the rq is either stuck
5648          * in the stop_machine_cpu_stop() loop, or we're executing this code,
5649          * either way we should never end up calling schedule() until we're
5650          * done here.
5651          */
5652         rq->stop = NULL;
5653
5654         for ( ; ; ) {
5655                 /*
5656                  * There's this thread running, bail when that's the only
5657                  * remaining thread.
5658                  */
5659                 if (rq->nr_running == 1)
5660                         break;
5661
5662                 next = pick_next_task(rq);
5663                 BUG_ON(!next);
5664                 next->sched_class->put_prev_task(rq, next);
5665
5666                 /* Find suitable destination for @next, with force if needed. */
5667                 dest_cpu = select_fallback_rq(dead_cpu, next);
5668                 raw_spin_unlock(&rq->lock);
5669
5670                 __migrate_task(next, dead_cpu, dest_cpu);
5671
5672                 raw_spin_lock(&rq->lock);
5673         }
5674
5675         rq->stop = stop;
5676 }
5677
5678 #endif /* CONFIG_HOTPLUG_CPU */
5679
5680 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5681
5682 static struct ctl_table sd_ctl_dir[] = {
5683         {
5684                 .procname       = "sched_domain",
5685                 .mode           = 0555,
5686         },
5687         {}
5688 };
5689
5690 static struct ctl_table sd_ctl_root[] = {
5691         {
5692                 .procname       = "kernel",
5693                 .mode           = 0555,
5694                 .child          = sd_ctl_dir,
5695         },
5696         {}
5697 };
5698
5699 static struct ctl_table *sd_alloc_ctl_entry(int n)
5700 {
5701         struct ctl_table *entry =
5702                 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
5703
5704         return entry;
5705 }
5706
5707 static void sd_free_ctl_entry(struct ctl_table **tablep)
5708 {
5709         struct ctl_table *entry;
5710
5711         /*
5712          * In the intermediate directories, both the child directory and
5713          * procname are dynamically allocated and could fail but the mode
5714          * will always be set. In the lowest directory the names are
5715          * static strings and all have proc handlers.
5716          */
5717         for (entry = *tablep; entry->mode; entry++) {
5718                 if (entry->child)
5719                         sd_free_ctl_entry(&entry->child);
5720                 if (entry->proc_handler == NULL)
5721                         kfree(entry->procname);
5722         }
5723
5724         kfree(*tablep);
5725         *tablep = NULL;
5726 }
5727
5728 static void
5729 set_table_entry(struct ctl_table *entry,
5730                 const char *procname, void *data, int maxlen,
5731                 mode_t mode, proc_handler *proc_handler)
5732 {
5733         entry->procname = procname;
5734         entry->data = data;
5735         entry->maxlen = maxlen;
5736         entry->mode = mode;
5737         entry->proc_handler = proc_handler;
5738 }
5739
5740 static struct ctl_table *
5741 sd_alloc_ctl_domain_table(struct sched_domain *sd)
5742 {
5743         struct ctl_table *table = sd_alloc_ctl_entry(13);
5744
5745         if (table == NULL)
5746                 return NULL;
5747
5748         set_table_entry(&table[0], "min_interval", &sd->min_interval,
5749                 sizeof(long), 0644, proc_doulongvec_minmax);
5750         set_table_entry(&table[1], "max_interval", &sd->max_interval,
5751                 sizeof(long), 0644, proc_doulongvec_minmax);
5752         set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
5753                 sizeof(int), 0644, proc_dointvec_minmax);
5754         set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
5755                 sizeof(int), 0644, proc_dointvec_minmax);
5756         set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
5757                 sizeof(int), 0644, proc_dointvec_minmax);
5758         set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
5759                 sizeof(int), 0644, proc_dointvec_minmax);
5760         set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
5761                 sizeof(int), 0644, proc_dointvec_minmax);
5762         set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
5763                 sizeof(int), 0644, proc_dointvec_minmax);
5764         set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
5765                 sizeof(int), 0644, proc_dointvec_minmax);
5766         set_table_entry(&table[9], "cache_nice_tries",
5767                 &sd->cache_nice_tries,
5768                 sizeof(int), 0644, proc_dointvec_minmax);
5769         set_table_entry(&table[10], "flags", &sd->flags,
5770                 sizeof(int), 0644, proc_dointvec_minmax);
5771         set_table_entry(&table[11], "name", sd->name,
5772                 CORENAME_MAX_SIZE, 0444, proc_dostring);
5773         /* &table[12] is terminator */
5774
5775         return table;
5776 }
5777
5778 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
5779 {
5780         struct ctl_table *entry, *table;
5781         struct sched_domain *sd;
5782         int domain_num = 0, i;
5783         char buf[32];
5784
5785         for_each_domain(cpu, sd)
5786                 domain_num++;
5787         entry = table = sd_alloc_ctl_entry(domain_num + 1);
5788         if (table == NULL)
5789                 return NULL;
5790
5791         i = 0;
5792         for_each_domain(cpu, sd) {
5793                 snprintf(buf, 32, "domain%d", i);
5794                 entry->procname = kstrdup(buf, GFP_KERNEL);
5795                 entry->mode = 0555;
5796                 entry->child = sd_alloc_ctl_domain_table(sd);
5797                 entry++;
5798                 i++;
5799         }
5800         return table;
5801 }
5802
5803 static struct ctl_table_header *sd_sysctl_header;
5804 static void register_sched_domain_sysctl(void)
5805 {
5806         int i, cpu_num = num_possible_cpus();
5807         struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
5808         char buf[32];
5809
5810         WARN_ON(sd_ctl_dir[0].child);
5811         sd_ctl_dir[0].child = entry;
5812
5813         if (entry == NULL)
5814                 return;
5815
5816         for_each_possible_cpu(i) {
5817                 snprintf(buf, 32, "cpu%d", i);
5818                 entry->procname = kstrdup(buf, GFP_KERNEL);
5819                 entry->mode = 0555;
5820                 entry->child = sd_alloc_ctl_cpu_table(i);
5821                 entry++;
5822         }
5823
5824         WARN_ON(sd_sysctl_header);
5825         sd_sysctl_header = register_sysctl_table(sd_ctl_root);
5826 }
5827
5828 /* may be called multiple times per register */
5829 static void unregister_sched_domain_sysctl(void)
5830 {
5831         if (sd_sysctl_header)
5832                 unregister_sysctl_table(sd_sysctl_header);
5833         sd_sysctl_header = NULL;
5834         if (sd_ctl_dir[0].child)
5835                 sd_free_ctl_entry(&sd_ctl_dir[0].child);
5836 }
5837 #else
5838 static void register_sched_domain_sysctl(void)
5839 {
5840 }
5841 static void unregister_sched_domain_sysctl(void)
5842 {
5843 }
5844 #endif
5845
5846 static void set_rq_online(struct rq *rq)
5847 {
5848         if (!rq->online) {
5849                 const struct sched_class *class;
5850
5851                 cpumask_set_cpu(rq->cpu, rq->rd->online);
5852                 rq->online = 1;
5853
5854                 for_each_class(class) {
5855                         if (class->rq_online)
5856                                 class->rq_online(rq);
5857                 }
5858         }
5859 }
5860
5861 static void set_rq_offline(struct rq *rq)
5862 {
5863         if (rq->online) {
5864                 const struct sched_class *class;
5865
5866                 for_each_class(class) {
5867                         if (class->rq_offline)
5868                                 class->rq_offline(rq);
5869                 }
5870
5871                 cpumask_clear_cpu(rq->cpu, rq->rd->online);
5872                 rq->online = 0;
5873         }
5874 }
5875
5876 /*
5877  * migration_call - callback that gets triggered when a CPU is added.
5878  * Here we can start up the necessary migration thread for the new CPU.
5879  */
5880 static int __cpuinit
5881 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
5882 {
5883         int cpu = (long)hcpu;
5884         unsigned long flags;
5885         struct rq *rq = cpu_rq(cpu);
5886
5887         switch (action & ~CPU_TASKS_FROZEN) {
5888
5889         case CPU_UP_PREPARE:
5890                 rq->calc_load_update = calc_load_update;
5891                 break;
5892
5893         case CPU_ONLINE:
5894                 /* Update our root-domain */
5895                 raw_spin_lock_irqsave(&rq->lock, flags);
5896                 if (rq->rd) {
5897                         BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5898
5899                         set_rq_online(rq);
5900                 }
5901                 raw_spin_unlock_irqrestore(&rq->lock, flags);
5902                 break;
5903
5904 #ifdef CONFIG_HOTPLUG_CPU
5905         case CPU_DYING:
5906                 /* Update our root-domain */
5907                 raw_spin_lock_irqsave(&rq->lock, flags);
5908                 if (rq->rd) {
5909                         BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5910                         set_rq_offline(rq);
5911                 }
5912                 migrate_tasks(cpu);
5913                 BUG_ON(rq->nr_running != 1); /* the migration thread */
5914                 raw_spin_unlock_irqrestore(&rq->lock, flags);
5915
5916                 migrate_nr_uninterruptible(rq);
5917                 calc_global_load_remove(rq);
5918                 break;
5919 #endif
5920         }
5921         return NOTIFY_OK;
5922 }
5923
5924 /*
5925  * Register at high priority so that task migration (migrate_all_tasks)
5926  * happens before everything else.  This has to be lower priority than
5927  * the notifier in the perf_event subsystem, though.
5928  */
5929 static struct notifier_block __cpuinitdata migration_notifier = {
5930         .notifier_call = migration_call,
5931         .priority = CPU_PRI_MIGRATION,
5932 };
5933
5934 static int __cpuinit sched_cpu_active(struct notifier_block *nfb,
5935                                       unsigned long action, void *hcpu)
5936 {
5937         switch (action & ~CPU_TASKS_FROZEN) {
5938         case CPU_ONLINE:
5939         case CPU_DOWN_FAILED:
5940                 set_cpu_active((long)hcpu, true);
5941                 return NOTIFY_OK;
5942         default:
5943                 return NOTIFY_DONE;
5944         }
5945 }
5946
5947 static int __cpuinit sched_cpu_inactive(struct notifier_block *nfb,
5948                                         unsigned long action, void *hcpu)
5949 {
5950         switch (action & ~CPU_TASKS_FROZEN) {
5951         case CPU_DOWN_PREPARE:
5952                 set_cpu_active((long)hcpu, false);
5953                 return NOTIFY_OK;
5954         default:
5955                 return NOTIFY_DONE;
5956         }
5957 }
5958
5959 static int __init migration_init(void)
5960 {
5961         void *cpu = (void *)(long)smp_processor_id();
5962         int err;
5963
5964         /* Initialize migration for the boot CPU */
5965         err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5966         BUG_ON(err == NOTIFY_BAD);
5967         migration_call(&migration_notifier, CPU_ONLINE, cpu);
5968         register_cpu_notifier(&migration_notifier);
5969
5970         /* Register cpu active notifiers */
5971         cpu_notifier(sched_cpu_active, CPU_PRI_SCHED_ACTIVE);
5972         cpu_notifier(sched_cpu_inactive, CPU_PRI_SCHED_INACTIVE);
5973
5974         return 0;
5975 }
5976 early_initcall(migration_init);
5977 #endif
5978
5979 #ifdef CONFIG_SMP
5980
5981 #ifdef CONFIG_SCHED_DEBUG
5982
5983 static __read_mostly int sched_domain_debug_enabled;
5984
5985 static int __init sched_domain_debug_setup(char *str)
5986 {
5987         sched_domain_debug_enabled = 1;
5988
5989         return 0;
5990 }
5991 early_param("sched_debug", sched_domain_debug_setup);
5992
5993 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
5994                                   struct cpumask *groupmask)
5995 {
5996         struct sched_group *group = sd->groups;
5997         char str[256];
5998
5999         cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd));
6000         cpumask_clear(groupmask);
6001
6002         printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6003
6004         if (!(sd->flags & SD_LOAD_BALANCE)) {
6005                 printk("does not load-balance\n");
6006                 if (sd->parent)
6007                         printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6008                                         " has parent");
6009                 return -1;
6010         }
6011
6012         printk(KERN_CONT "span %s level %s\n", str, sd->name);
6013
6014         if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) {
6015                 printk(KERN_ERR "ERROR: domain->span does not contain "
6016                                 "CPU%d\n", cpu);
6017         }
6018         if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) {
6019                 printk(KERN_ERR "ERROR: domain->groups does not contain"
6020                                 " CPU%d\n", cpu);
6021         }
6022
6023         printk(KERN_DEBUG "%*s groups:", level + 1, "");
6024         do {
6025                 if (!group) {
6026                         printk("\n");
6027                         printk(KERN_ERR "ERROR: group is NULL\n");
6028                         break;
6029                 }
6030
6031                 if (!group->cpu_power) {
6032                         printk(KERN_CONT "\n");
6033                         printk(KERN_ERR "ERROR: domain->cpu_power not "
6034                                         "set\n");
6035                         break;
6036                 }
6037
6038                 if (!cpumask_weight(sched_group_cpus(group))) {
6039                         printk(KERN_CONT "\n");
6040                         printk(KERN_ERR "ERROR: empty group\n");
6041                         break;
6042                 }
6043
6044                 if (cpumask_intersects(groupmask, sched_group_cpus(group))) {
6045                         printk(KERN_CONT "\n");
6046                         printk(KERN_ERR "ERROR: repeated CPUs\n");
6047                         break;
6048                 }
6049
6050                 cpumask_or(groupmask, groupmask, sched_group_cpus(group));
6051
6052                 cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group));
6053
6054                 printk(KERN_CONT " %s", str);
6055                 if (group->cpu_power != SCHED_LOAD_SCALE) {
6056                         printk(KERN_CONT " (cpu_power = %d)",
6057                                 group->cpu_power);
6058                 }
6059
6060                 group = group->next;
6061         } while (group != sd->groups);
6062         printk(KERN_CONT "\n");
6063
6064         if (!cpumask_equal(sched_domain_span(sd), groupmask))
6065                 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6066
6067         if (sd->parent &&
6068             !cpumask_subset(groupmask, sched_domain_span(sd->parent)))
6069                 printk(KERN_ERR "ERROR: parent span is not a superset "
6070                         "of domain->span\n");
6071         return 0;
6072 }
6073
6074 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6075 {
6076         cpumask_var_t groupmask;
6077         int level = 0;
6078
6079         if (!sched_domain_debug_enabled)
6080                 return;
6081
6082         if (!sd) {
6083                 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6084                 return;
6085         }
6086
6087         printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6088
6089         if (!alloc_cpumask_var(&groupmask, GFP_KERNEL)) {
6090                 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
6091                 return;
6092         }
6093
6094         for (;;) {
6095                 if (sched_domain_debug_one(sd, cpu, level, groupmask))
6096                         break;
6097                 level++;
6098                 sd = sd->parent;
6099                 if (!sd)
6100                         break;
6101         }
6102         free_cpumask_var(groupmask);
6103 }
6104 #else /* !CONFIG_SCHED_DEBUG */
6105 # define sched_domain_debug(sd, cpu) do { } while (0)
6106 #endif /* CONFIG_SCHED_DEBUG */
6107
6108 static int sd_degenerate(struct sched_domain *sd)
6109 {
6110         if (cpumask_weight(sched_domain_span(sd)) == 1)
6111                 return 1;
6112
6113         /* Following flags need at least 2 groups */
6114         if (sd->flags & (SD_LOAD_BALANCE |
6115                          SD_BALANCE_NEWIDLE |
6116                          SD_BALANCE_FORK |
6117                          SD_BALANCE_EXEC |
6118                          SD_SHARE_CPUPOWER |
6119                          SD_SHARE_PKG_RESOURCES)) {
6120                 if (sd->groups != sd->groups->next)
6121                         return 0;
6122         }
6123
6124         /* Following flags don't use groups */
6125         if (sd->flags & (SD_WAKE_AFFINE))
6126                 return 0;
6127
6128         return 1;
6129 }
6130
6131 static int
6132 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6133 {
6134         unsigned long cflags = sd->flags, pflags = parent->flags;
6135
6136         if (sd_degenerate(parent))
6137                 return 1;
6138
6139         if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent)))
6140                 return 0;
6141
6142         /* Flags needing groups don't count if only 1 group in parent */
6143         if (parent->groups == parent->groups->next) {
6144                 pflags &= ~(SD_LOAD_BALANCE |
6145                                 SD_BALANCE_NEWIDLE |
6146                                 SD_BALANCE_FORK |
6147                                 SD_BALANCE_EXEC |
6148                                 SD_SHARE_CPUPOWER |
6149                                 SD_SHARE_PKG_RESOURCES);
6150                 if (nr_node_ids == 1)
6151                         pflags &= ~SD_SERIALIZE;
6152         }
6153         if (~cflags & pflags)
6154                 return 0;
6155
6156         return 1;
6157 }
6158
6159 static void free_rootdomain(struct root_domain *rd)
6160 {
6161         synchronize_sched();
6162
6163         cpupri_cleanup(&rd->cpupri);
6164
6165         free_cpumask_var(rd->rto_mask);
6166         free_cpumask_var(rd->online);
6167         free_cpumask_var(rd->span);
6168         kfree(rd);
6169 }
6170
6171 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6172 {
6173         struct root_domain *old_rd = NULL;
6174         unsigned long flags;
6175
6176         raw_spin_lock_irqsave(&rq->lock, flags);
6177
6178         if (rq->rd) {
6179                 old_rd = rq->rd;
6180
6181                 if (cpumask_test_cpu(rq->cpu, old_rd->online))
6182                         set_rq_offline(rq);
6183
6184                 cpumask_clear_cpu(rq->cpu, old_rd->span);
6185
6186                 /*
6187                  * If we dont want to free the old_rt yet then
6188                  * set old_rd to NULL to skip the freeing later
6189                  * in this function:
6190                  */
6191                 if (!atomic_dec_and_test(&old_rd->refcount))
6192                         old_rd = NULL;
6193         }
6194
6195         atomic_inc(&rd->refcount);
6196         rq->rd = rd;
6197
6198         cpumask_set_cpu(rq->cpu, rd->span);
6199         if (cpumask_test_cpu(rq->cpu, cpu_active_mask))
6200                 set_rq_online(rq);
6201
6202         raw_spin_unlock_irqrestore(&rq->lock, flags);
6203
6204         if (old_rd)
6205                 free_rootdomain(old_rd);
6206 }
6207
6208 static int init_rootdomain(struct root_domain *rd)
6209 {
6210         memset(rd, 0, sizeof(*rd));
6211
6212         if (!alloc_cpumask_var(&rd->span, GFP_KERNEL))
6213                 goto out;
6214         if (!alloc_cpumask_var(&rd->online, GFP_KERNEL))
6215                 goto free_span;
6216         if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL))
6217                 goto free_online;
6218
6219         if (cpupri_init(&rd->cpupri) != 0)
6220                 goto free_rto_mask;
6221         return 0;
6222
6223 free_rto_mask:
6224         free_cpumask_var(rd->rto_mask);
6225 free_online:
6226         free_cpumask_var(rd->online);
6227 free_span:
6228         free_cpumask_var(rd->span);
6229 out:
6230         return -ENOMEM;
6231 }
6232
6233 static void init_defrootdomain(void)
6234 {
6235         init_rootdomain(&def_root_domain);
6236
6237         atomic_set(&def_root_domain.refcount, 1);
6238 }
6239
6240 static struct root_domain *alloc_rootdomain(void)
6241 {
6242         struct root_domain *rd;
6243
6244         rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6245         if (!rd)
6246                 return NULL;
6247
6248         if (init_rootdomain(rd) != 0) {
6249                 kfree(rd);
6250                 return NULL;
6251         }
6252
6253         return rd;
6254 }
6255
6256 /*
6257  * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6258  * hold the hotplug lock.
6259  */
6260 static void
6261 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6262 {
6263         struct rq *rq = cpu_rq(cpu);
6264         struct sched_domain *tmp;
6265
6266         for (tmp = sd; tmp; tmp = tmp->parent)
6267                 tmp->span_weight = cpumask_weight(sched_domain_span(tmp));
6268
6269         /* Remove the sched domains which do not contribute to scheduling. */
6270         for (tmp = sd; tmp; ) {
6271                 struct sched_domain *parent = tmp->parent;
6272                 if (!parent)
6273                         break;
6274
6275                 if (sd_parent_degenerate(tmp, parent)) {
6276                         tmp->parent = parent->parent;
6277                         if (parent->parent)
6278                                 parent->parent->child = tmp;
6279                 } else
6280                         tmp = tmp->parent;
6281         }
6282
6283         if (sd && sd_degenerate(sd)) {
6284                 sd = sd->parent;
6285                 if (sd)
6286                         sd->child = NULL;
6287         }
6288
6289         sched_domain_debug(sd, cpu);
6290
6291         rq_attach_root(rq, rd);
6292         rcu_assign_pointer(rq->sd, sd);
6293 }
6294
6295 /* cpus with isolated domains */
6296 static cpumask_var_t cpu_isolated_map;
6297
6298 /* Setup the mask of cpus configured for isolated domains */
6299 static int __init isolated_cpu_setup(char *str)
6300 {
6301         alloc_bootmem_cpumask_var(&cpu_isolated_map);
6302         cpulist_parse(str, cpu_isolated_map);
6303         return 1;
6304 }
6305
6306 __setup("isolcpus=", isolated_cpu_setup);
6307
6308 /*
6309  * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6310  * to a function which identifies what group(along with sched group) a CPU
6311  * belongs to. The return value of group_fn must be a >= 0 and < nr_cpu_ids
6312  * (due to the fact that we keep track of groups covered with a struct cpumask).
6313  *
6314  * init_sched_build_groups will build a circular linked list of the groups
6315  * covered by the given span, and will set each group's ->cpumask correctly,
6316  * and ->cpu_power to 0.
6317  */
6318 static void
6319 init_sched_build_groups(const struct cpumask *span,
6320                         const struct cpumask *cpu_map,
6321                         int (*group_fn)(int cpu, const struct cpumask *cpu_map,
6322                                         struct sched_group **sg,
6323                                         struct cpumask *tmpmask),
6324                         struct cpumask *covered, struct cpumask *tmpmask)
6325 {
6326         struct sched_group *first = NULL, *last = NULL;
6327         int i;
6328
6329         cpumask_clear(covered);
6330
6331         for_each_cpu(i, span) {
6332                 struct sched_group *sg;
6333                 int group = group_fn(i, cpu_map, &sg, tmpmask);
6334                 int j;
6335
6336                 if (cpumask_test_cpu(i, covered))
6337                         continue;
6338
6339                 cpumask_clear(sched_group_cpus(sg));
6340                 sg->cpu_power = 0;
6341
6342                 for_each_cpu(j, span) {
6343                         if (group_fn(j, cpu_map, NULL, tmpmask) != group)
6344                                 continue;
6345
6346                         cpumask_set_cpu(j, covered);
6347                         cpumask_set_cpu(j, sched_group_cpus(sg));
6348                 }
6349                 if (!first)
6350                         first = sg;
6351                 if (last)
6352                         last->next = sg;
6353                 last = sg;
6354         }
6355         last->next = first;
6356 }
6357
6358 #define SD_NODES_PER_DOMAIN 16
6359
6360 #ifdef CONFIG_NUMA
6361
6362 /**
6363  * find_next_best_node - find the next node to include in a sched_domain
6364  * @node: node whose sched_domain we're building
6365  * @used_nodes: nodes already in the sched_domain
6366  *
6367  * Find the next node to include in a given scheduling domain. Simply
6368  * finds the closest node not already in the @used_nodes map.
6369  *
6370  * Should use nodemask_t.
6371  */
6372 static int find_next_best_node(int node, nodemask_t *used_nodes)
6373 {
6374         int i, n, val, min_val, best_node = 0;
6375
6376         min_val = INT_MAX;
6377
6378         for (i = 0; i < nr_node_ids; i++) {
6379                 /* Start at @node */
6380                 n = (node + i) % nr_node_ids;
6381
6382                 if (!nr_cpus_node(n))
6383                         continue;
6384
6385                 /* Skip already used nodes */
6386                 if (node_isset(n, *used_nodes))
6387                         continue;
6388
6389                 /* Simple min distance search */
6390                 val = node_distance(node, n);
6391
6392                 if (val < min_val) {
6393                         min_val = val;
6394                         best_node = n;
6395                 }
6396         }
6397
6398         node_set(best_node, *used_nodes);
6399         return best_node;
6400 }
6401
6402 /**
6403  * sched_domain_node_span - get a cpumask for a node's sched_domain
6404  * @node: node whose cpumask we're constructing
6405  * @span: resulting cpumask
6406  *
6407  * Given a node, construct a good cpumask for its sched_domain to span. It
6408  * should be one that prevents unnecessary balancing, but also spreads tasks
6409  * out optimally.
6410  */
6411 static void sched_domain_node_span(int node, struct cpumask *span)
6412 {
6413         nodemask_t used_nodes;
6414         int i;
6415
6416         cpumask_clear(span);
6417         nodes_clear(used_nodes);
6418
6419         cpumask_or(span, span, cpumask_of_node(node));
6420         node_set(node, used_nodes);
6421
6422         for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
6423                 int next_node = find_next_best_node(node, &used_nodes);
6424
6425                 cpumask_or(span, span, cpumask_of_node(next_node));
6426         }
6427 }
6428 #endif /* CONFIG_NUMA */
6429
6430 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6431
6432 /*
6433  * The cpus mask in sched_group and sched_domain hangs off the end.
6434  *
6435  * ( See the the comments in include/linux/sched.h:struct sched_group
6436  *   and struct sched_domain. )
6437  */
6438 struct static_sched_group {
6439         struct sched_group sg;
6440         DECLARE_BITMAP(cpus, CONFIG_NR_CPUS);
6441 };
6442
6443 struct static_sched_domain {
6444         struct sched_domain sd;
6445         DECLARE_BITMAP(span, CONFIG_NR_CPUS);
6446 };
6447
6448 struct s_data {
6449 #ifdef CONFIG_NUMA
6450         int                     sd_allnodes;
6451         cpumask_var_t           domainspan;
6452         cpumask_var_t           covered;
6453         cpumask_var_t           notcovered;
6454 #endif
6455         cpumask_var_t           nodemask;
6456         cpumask_var_t           this_sibling_map;
6457         cpumask_var_t           this_core_map;
6458         cpumask_var_t           this_book_map;
6459         cpumask_var_t           send_covered;
6460         cpumask_var_t           tmpmask;
6461         struct sched_group      **sched_group_nodes;
6462         struct root_domain      *rd;
6463 };
6464
6465 enum s_alloc {
6466         sa_sched_groups = 0,
6467         sa_rootdomain,
6468         sa_tmpmask,
6469         sa_send_covered,
6470         sa_this_book_map,
6471         sa_this_core_map,
6472         sa_this_sibling_map,
6473         sa_nodemask,
6474         sa_sched_group_nodes,
6475 #ifdef CONFIG_NUMA
6476         sa_notcovered,
6477         sa_covered,
6478         sa_domainspan,
6479 #endif
6480         sa_none,
6481 };
6482
6483 /*
6484  * SMT sched-domains:
6485  */
6486 #ifdef CONFIG_SCHED_SMT
6487 static DEFINE_PER_CPU(struct static_sched_domain, cpu_domains);
6488 static DEFINE_PER_CPU(struct static_sched_group, sched_groups);
6489
6490 static int
6491 cpu_to_cpu_group(int cpu, const struct cpumask *cpu_map,
6492                  struct sched_group **sg, struct cpumask *unused)
6493 {
6494         if (sg)
6495                 *sg = &per_cpu(sched_groups, cpu).sg;
6496         return cpu;
6497 }
6498 #endif /* CONFIG_SCHED_SMT */
6499
6500 /*
6501  * multi-core sched-domains:
6502  */
6503 #ifdef CONFIG_SCHED_MC
6504 static DEFINE_PER_CPU(struct static_sched_domain, core_domains);
6505 static DEFINE_PER_CPU(struct static_sched_group, sched_group_core);
6506
6507 static int
6508 cpu_to_core_group(int cpu, const struct cpumask *cpu_map,
6509                   struct sched_group **sg, struct cpumask *mask)
6510 {
6511         int group;
6512 #ifdef CONFIG_SCHED_SMT
6513         cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
6514         group = cpumask_first(mask);
6515 #else
6516         group = cpu;
6517 #endif
6518         if (sg)
6519                 *sg = &per_cpu(sched_group_core, group).sg;
6520         return group;
6521 }
6522 #endif /* CONFIG_SCHED_MC */
6523
6524 /*
6525  * book sched-domains:
6526  */
6527 #ifdef CONFIG_SCHED_BOOK
6528 static DEFINE_PER_CPU(struct static_sched_domain, book_domains);
6529 static DEFINE_PER_CPU(struct static_sched_group, sched_group_book);
6530
6531 static int
6532 cpu_to_book_group(int cpu, const struct cpumask *cpu_map,
6533                   struct sched_group **sg, struct cpumask *mask)
6534 {
6535         int group = cpu;
6536 #ifdef CONFIG_SCHED_MC
6537         cpumask_and(mask, cpu_coregroup_mask(cpu), cpu_map);
6538         group = cpumask_first(mask);
6539 #elif defined(CONFIG_SCHED_SMT)
6540         cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
6541         group = cpumask_first(mask);
6542 #endif
6543         if (sg)
6544                 *sg = &per_cpu(sched_group_book, group).sg;
6545         return group;
6546 }
6547 #endif /* CONFIG_SCHED_BOOK */
6548
6549 static DEFINE_PER_CPU(struct static_sched_domain, phys_domains);
6550 static DEFINE_PER_CPU(struct static_sched_group, sched_group_phys);
6551
6552 static int
6553 cpu_to_phys_group(int cpu, const struct cpumask *cpu_map,
6554                   struct sched_group **sg, struct cpumask *mask)
6555 {
6556         int group;
6557 #ifdef CONFIG_SCHED_BOOK
6558         cpumask_and(mask, cpu_book_mask(cpu), cpu_map);
6559         group = cpumask_first(mask);
6560 #elif defined(CONFIG_SCHED_MC)
6561         cpumask_and(mask, cpu_coregroup_mask(cpu), cpu_map);
6562         group = cpumask_first(mask);
6563 #elif defined(CONFIG_SCHED_SMT)
6564         cpumask_and(mask, topology_thread_cpumask(cpu), cpu_map);
6565         group = cpumask_first(mask);
6566 #else
6567         group = cpu;
6568 #endif
6569         if (sg)
6570                 *sg = &per_cpu(sched_group_phys, group).sg;
6571         return group;
6572 }
6573
6574 #ifdef CONFIG_NUMA
6575 /*
6576  * The init_sched_build_groups can't handle what we want to do with node
6577  * groups, so roll our own. Now each node has its own list of groups which
6578  * gets dynamically allocated.
6579  */
6580 static DEFINE_PER_CPU(struct static_sched_domain, node_domains);
6581 static struct sched_group ***sched_group_nodes_bycpu;
6582
6583 static DEFINE_PER_CPU(struct static_sched_domain, allnodes_domains);
6584 static DEFINE_PER_CPU(struct static_sched_group, sched_group_allnodes);
6585
6586 static int cpu_to_allnodes_group(int cpu, const struct cpumask *cpu_map,
6587                                  struct sched_group **sg,
6588                                  struct cpumask *nodemask)
6589 {
6590         int group;
6591
6592         cpumask_and(nodemask, cpumask_of_node(cpu_to_node(cpu)), cpu_map);
6593         group = cpumask_first(nodemask);
6594
6595         if (sg)
6596                 *sg = &per_cpu(sched_group_allnodes, group).sg;
6597         return group;
6598 }
6599
6600 static void init_numa_sched_groups_power(struct sched_group *group_head)
6601 {
6602         struct sched_group *sg = group_head;
6603         int j;
6604
6605         if (!sg)
6606                 return;
6607         do {
6608                 for_each_cpu(j, sched_group_cpus(sg)) {
6609                         struct sched_domain *sd;
6610
6611                         sd = &per_cpu(phys_domains, j).sd;
6612                         if (j != group_first_cpu(sd->groups)) {
6613                                 /*
6614                                  * Only add "power" once for each
6615                                  * physical package.
6616                                  */
6617                                 continue;
6618                         }
6619
6620                         sg->cpu_power += sd->groups->cpu_power;
6621                 }
6622                 sg = sg->next;
6623         } while (sg != group_head);
6624 }
6625
6626 static int build_numa_sched_groups(struct s_data *d,
6627                                    const struct cpumask *cpu_map, int num)
6628 {
6629         struct sched_domain *sd;
6630         struct sched_group *sg, *prev;
6631         int n, j;
6632
6633         cpumask_clear(d->covered);
6634         cpumask_and(d->nodemask, cpumask_of_node(num), cpu_map);
6635         if (cpumask_empty(d->nodemask)) {
6636                 d->sched_group_nodes[num] = NULL;
6637                 goto out;
6638         }
6639
6640         sched_domain_node_span(num, d->domainspan);
6641         cpumask_and(d->domainspan, d->domainspan, cpu_map);
6642
6643         sg = kmalloc_node(sizeof(struct sched_group) + cpumask_size(),
6644                           GFP_KERNEL, num);
6645         if (!sg) {
6646                 printk(KERN_WARNING "Can not alloc domain group for node %d\n",
6647                        num);
6648                 return -ENOMEM;
6649         }
6650         d->sched_group_nodes[num] = sg;
6651
6652         for_each_cpu(j, d->nodemask) {
6653                 sd = &per_cpu(node_domains, j).sd;
6654                 sd->groups = sg;
6655         }
6656
6657         sg->cpu_power = 0;
6658         cpumask_copy(sched_group_cpus(sg), d->nodemask);
6659         sg->next = sg;
6660         cpumask_or(d->covered, d->covered, d->nodemask);
6661
6662         prev = sg;
6663         for (j = 0; j < nr_node_ids; j++) {
6664                 n = (num + j) % nr_node_ids;
6665                 cpumask_complement(d->notcovered, d->covered);
6666                 cpumask_and(d->tmpmask, d->notcovered, cpu_map);
6667                 cpumask_and(d->tmpmask, d->tmpmask, d->domainspan);
6668                 if (cpumask_empty(d->tmpmask))
6669                         break;
6670                 cpumask_and(d->tmpmask, d->tmpmask, cpumask_of_node(n));
6671                 if (cpumask_empty(d->tmpmask))
6672                         continue;
6673                 sg = kmalloc_node(sizeof(struct sched_group) + cpumask_size(),
6674                                   GFP_KERNEL, num);
6675                 if (!sg) {
6676                         printk(KERN_WARNING
6677                                "Can not alloc domain group for node %d\n", j);
6678                         return -ENOMEM;
6679                 }
6680                 sg->cpu_power = 0;
6681                 cpumask_copy(sched_group_cpus(sg), d->tmpmask);
6682                 sg->next = prev->next;
6683                 cpumask_or(d->covered, d->covered, d->tmpmask);
6684                 prev->next = sg;
6685                 prev = sg;
6686         }
6687 out:
6688         return 0;
6689 }
6690 #endif /* CONFIG_NUMA */
6691
6692 #ifdef CONFIG_NUMA
6693 /* Free memory allocated for various sched_group structures */
6694 static void free_sched_groups(const struct cpumask *cpu_map,
6695                               struct cpumask *nodemask)
6696 {
6697         int cpu, i;
6698
6699         for_each_cpu(cpu, cpu_map) {
6700                 struct sched_group **sched_group_nodes
6701                         = sched_group_nodes_bycpu[cpu];
6702
6703                 if (!sched_group_nodes)
6704                         continue;
6705
6706                 for (i = 0; i < nr_node_ids; i++) {
6707                         struct sched_group *oldsg, *sg = sched_group_nodes[i];
6708
6709                         cpumask_and(nodemask, cpumask_of_node(i), cpu_map);
6710                         if (cpumask_empty(nodemask))
6711                                 continue;
6712
6713                         if (sg == NULL)
6714                                 continue;
6715                         sg = sg->next;
6716 next_sg:
6717                         oldsg = sg;
6718                         sg = sg->next;
6719                         kfree(oldsg);
6720                         if (oldsg != sched_group_nodes[i])
6721                                 goto next_sg;
6722                 }
6723                 kfree(sched_group_nodes);
6724                 sched_group_nodes_bycpu[cpu] = NULL;
6725         }
6726 }
6727 #else /* !CONFIG_NUMA */
6728 static void free_sched_groups(const struct cpumask *cpu_map,
6729                               struct cpumask *nodemask)
6730 {
6731 }
6732 #endif /* CONFIG_NUMA */
6733
6734 /*
6735  * Initialize sched groups cpu_power.
6736  *
6737  * cpu_power indicates the capacity of sched group, which is used while
6738  * distributing the load between different sched groups in a sched domain.
6739  * Typically cpu_power for all the groups in a sched domain will be same unless
6740  * there are asymmetries in the topology. If there are asymmetries, group
6741  * having more cpu_power will pickup more load compared to the group having
6742  * less cpu_power.
6743  */
6744 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
6745 {
6746         struct sched_domain *child;
6747         struct sched_group *group;
6748         long power;
6749         int weight;
6750
6751         WARN_ON(!sd || !sd->groups);
6752
6753         if (cpu != group_first_cpu(sd->groups))
6754                 return;
6755
6756         sd->groups->group_weight = cpumask_weight(sched_group_cpus(sd->groups));
6757
6758         child = sd->child;
6759
6760         sd->groups->cpu_power = 0;
6761
6762         if (!child) {
6763                 power = SCHED_LOAD_SCALE;
6764                 weight = cpumask_weight(sched_domain_span(sd));
6765                 /*
6766                  * SMT siblings share the power of a single core.
6767                  * Usually multiple threads get a better yield out of
6768                  * that one core than a single thread would have,
6769                  * reflect that in sd->smt_gain.
6770                  */
6771                 if ((sd->flags & SD_SHARE_CPUPOWER) && weight > 1) {
6772                         power *= sd->smt_gain;
6773                         power /= weight;
6774                         power >>= SCHED_LOAD_SHIFT;
6775                 }
6776                 sd->groups->cpu_power += power;
6777                 return;
6778         }
6779
6780         /*
6781          * Add cpu_power of each child group to this groups cpu_power.
6782          */
6783         group = child->groups;
6784         do {
6785                 sd->groups->cpu_power += group->cpu_power;
6786                 group = group->next;
6787         } while (group != child->groups);
6788 }
6789
6790 /*
6791  * Initializers for schedule domains
6792  * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
6793  */
6794
6795 #ifdef CONFIG_SCHED_DEBUG
6796 # define SD_INIT_NAME(sd, type)         sd->name = #type
6797 #else
6798 # define SD_INIT_NAME(sd, type)         do { } while (0)
6799 #endif
6800
6801 #define SD_INIT(sd, type)       sd_init_##type(sd)
6802
6803 #define SD_INIT_FUNC(type)      \
6804 static noinline void sd_init_##type(struct sched_domain *sd)    \
6805 {                                                               \
6806         memset(sd, 0, sizeof(*sd));                             \
6807         *sd = SD_##type##_INIT;                                 \
6808         sd->level = SD_LV_##type;                               \
6809         SD_INIT_NAME(sd, type);                                 \
6810 }
6811
6812 SD_INIT_FUNC(CPU)
6813 #ifdef CONFIG_NUMA
6814  SD_INIT_FUNC(ALLNODES)
6815  SD_INIT_FUNC(NODE)
6816 #endif
6817 #ifdef CONFIG_SCHED_SMT
6818  SD_INIT_FUNC(SIBLING)
6819 #endif
6820 #ifdef CONFIG_SCHED_MC
6821  SD_INIT_FUNC(MC)
6822 #endif
6823 #ifdef CONFIG_SCHED_BOOK
6824  SD_INIT_FUNC(BOOK)
6825 #endif
6826
6827 static int default_relax_domain_level = -1;
6828
6829 static int __init setup_relax_domain_level(char *str)
6830 {
6831         unsigned long val;
6832
6833         val = simple_strtoul(str, NULL, 0);
6834         if (val < SD_LV_MAX)
6835                 default_relax_domain_level = val;
6836
6837         return 1;
6838 }
6839 __setup("relax_domain_level=", setup_relax_domain_level);
6840
6841 static void set_domain_attribute(struct sched_domain *sd,
6842                                  struct sched_domain_attr *attr)
6843 {
6844         int request;
6845
6846         if (!attr || attr->relax_domain_level < 0) {
6847                 if (default_relax_domain_level < 0)
6848                         return;
6849                 else
6850                         request = default_relax_domain_level;
6851         } else
6852                 request = attr->relax_domain_level;
6853         if (request < sd->level) {
6854                 /* turn off idle balance on this domain */
6855                 sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6856         } else {
6857                 /* turn on idle balance on this domain */
6858                 sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE);
6859         }
6860 }
6861
6862 static void __free_domain_allocs(struct s_data *d, enum s_alloc what,
6863                                  const struct cpumask *cpu_map)
6864 {
6865         switch (what) {
6866         case sa_sched_groups:
6867                 free_sched_groups(cpu_map, d->tmpmask); /* fall through */
6868                 d->sched_group_nodes = NULL;
6869         case sa_rootdomain:
6870                 free_rootdomain(d->rd); /* fall through */
6871         case sa_tmpmask:
6872                 free_cpumask_var(d->tmpmask); /* fall through */
6873         case sa_send_covered:
6874                 free_cpumask_var(d->send_covered); /* fall through */
6875         case sa_this_book_map:
6876                 free_cpumask_var(d->this_book_map); /* fall through */
6877         case sa_this_core_map:
6878                 free_cpumask_var(d->this_core_map); /* fall through */
6879         case sa_this_sibling_map:
6880                 free_cpumask_var(d->this_sibling_map); /* fall through */
6881         case sa_nodemask:
6882                 free_cpumask_var(d->nodemask); /* fall through */
6883         case sa_sched_group_nodes:
6884 #ifdef CONFIG_NUMA
6885                 kfree(d->sched_group_nodes); /* fall through */
6886         case sa_notcovered:
6887                 free_cpumask_var(d->notcovered); /* fall through */
6888         case sa_covered:
6889                 free_cpumask_var(d->covered); /* fall through */
6890         case sa_domainspan:
6891                 free_cpumask_var(d->domainspan); /* fall through */
6892 #endif
6893         case sa_none:
6894                 break;
6895         }
6896 }
6897
6898 static enum s_alloc __visit_domain_allocation_hell(struct s_data *d,
6899                                                    const struct cpumask *cpu_map)
6900 {
6901 #ifdef CONFIG_NUMA
6902         if (!alloc_cpumask_var(&d->domainspan, GFP_KERNEL))
6903                 return sa_none;
6904         if (!alloc_cpumask_var(&d->covered, GFP_KERNEL))
6905                 return sa_domainspan;
6906         if (!alloc_cpumask_var(&d->notcovered, GFP_KERNEL))
6907                 return sa_covered;
6908         /* Allocate the per-node list of sched groups */
6909         d->sched_group_nodes = kcalloc(nr_node_ids,
6910                                       sizeof(struct sched_group *), GFP_KERNEL);
6911         if (!d->sched_group_nodes) {
6912                 printk(KERN_WARNING "Can not alloc sched group node list\n");
6913                 return sa_notcovered;
6914         }
6915         sched_group_nodes_bycpu[cpumask_first(cpu_map)] = d->sched_group_nodes;
6916 #endif
6917         if (!alloc_cpumask_var(&d->nodemask, GFP_KERNEL))
6918                 return sa_sched_group_nodes;
6919         if (!alloc_cpumask_var(&d->this_sibling_map, GFP_KERNEL))
6920                 return sa_nodemask;
6921         if (!alloc_cpumask_var(&d->this_core_map, GFP_KERNEL))
6922                 return sa_this_sibling_map;
6923         if (!alloc_cpumask_var(&d->this_book_map, GFP_KERNEL))
6924                 return sa_this_core_map;
6925         if (!alloc_cpumask_var(&d->send_covered, GFP_KERNEL))
6926                 return sa_this_book_map;
6927         if (!alloc_cpumask_var(&d->tmpmask, GFP_KERNEL))
6928                 return sa_send_covered;
6929         d->rd = alloc_rootdomain();
6930         if (!d->rd) {
6931                 printk(KERN_WARNING "Cannot alloc root domain\n");
6932                 return sa_tmpmask;
6933         }
6934         return sa_rootdomain;
6935 }
6936
6937 static struct sched_domain *__build_numa_sched_domains(struct s_data *d,
6938         const struct cpumask *cpu_map, struct sched_domain_attr *attr, int i)
6939 {
6940         struct sched_domain *sd = NULL;
6941 #ifdef CONFIG_NUMA
6942         struct sched_domain *parent;
6943
6944         d->sd_allnodes = 0;
6945         if (cpumask_weight(cpu_map) >
6946             SD_NODES_PER_DOMAIN * cpumask_weight(d->nodemask)) {
6947                 sd = &per_cpu(allnodes_domains, i).sd;
6948                 SD_INIT(sd, ALLNODES);
6949                 set_domain_attribute(sd, attr);
6950                 cpumask_copy(sched_domain_span(sd), cpu_map);
6951                 cpu_to_allnodes_group(i, cpu_map, &sd->groups, d->tmpmask);
6952                 d->sd_allnodes = 1;
6953         }
6954         parent = sd;
6955
6956         sd = &per_cpu(node_domains, i).sd;
6957         SD_INIT(sd, NODE);
6958         set_domain_attribute(sd, attr);
6959         sched_domain_node_span(cpu_to_node(i), sched_domain_span(sd));
6960         sd->parent = parent;
6961         if (parent)
6962                 parent->child = sd;
6963         cpumask_and(sched_domain_span(sd), sched_domain_span(sd), cpu_map);
6964 #endif
6965         return sd;
6966 }
6967
6968 static struct sched_domain *__build_cpu_sched_domain(struct s_data *d,
6969         const struct cpumask *cpu_map, struct sched_domain_attr *attr,
6970         struct sched_domain *parent, int i)
6971 {
6972         struct sched_domain *sd;
6973         sd = &per_cpu(phys_domains, i).sd;
6974         SD_INIT(sd, CPU);
6975         set_domain_attribute(sd, attr);
6976         cpumask_copy(sched_domain_span(sd), d->nodemask);
6977         sd->parent = parent;
6978         if (parent)
6979                 parent->child = sd;
6980         cpu_to_phys_group(i, cpu_map, &sd->groups, d->tmpmask);
6981         return sd;
6982 }
6983
6984 static struct sched_domain *__build_book_sched_domain(struct s_data *d,
6985         const struct cpumask *cpu_map, struct sched_domain_attr *attr,
6986         struct sched_domain *parent, int i)
6987 {
6988         struct sched_domain *sd = parent;
6989 #ifdef CONFIG_SCHED_BOOK
6990         sd = &per_cpu(book_domains, i).sd;
6991         SD_INIT(sd, BOOK);
6992         set_domain_attribute(sd, attr);
6993         cpumask_and(sched_domain_span(sd), cpu_map, cpu_book_mask(i));
6994         sd->parent = parent;
6995         parent->child = sd;
6996         cpu_to_book_group(i, cpu_map, &sd->groups, d->tmpmask);
6997 #endif
6998         return sd;
6999 }
7000
7001 static struct sched_domain *__build_mc_sched_domain(struct s_data *d,
7002         const struct cpumask *cpu_map, struct sched_domain_attr *attr,
7003         struct sched_domain *parent, int i)
7004 {
7005         struct sched_domain *sd = parent;
7006 #ifdef CONFIG_SCHED_MC
7007         sd = &per_cpu(core_domains, i).sd;
7008         SD_INIT(sd, MC);
7009         set_domain_attribute(sd, attr);
7010         cpumask_and(sched_domain_span(sd), cpu_map, cpu_coregroup_mask(i));
7011         sd->parent = parent;
7012         parent->child = sd;
7013         cpu_to_core_group(i, cpu_map, &sd->groups, d->tmpmask);
7014 #endif
7015         return sd;
7016 }
7017
7018 static struct sched_domain *__build_smt_sched_domain(struct s_data *d,
7019         const struct cpumask *cpu_map, struct sched_domain_attr *attr,
7020         struct sched_domain *parent, int i)
7021 {
7022         struct sched_domain *sd = parent;
7023 #ifdef CONFIG_SCHED_SMT
7024         sd = &per_cpu(cpu_domains, i).sd;
7025         SD_INIT(sd, SIBLING);
7026         set_domain_attribute(sd, attr);
7027         cpumask_and(sched_domain_span(sd), cpu_map, topology_thread_cpumask(i));
7028         sd->parent = parent;
7029         parent->child = sd;
7030         cpu_to_cpu_group(i, cpu_map, &sd->groups, d->tmpmask);
7031 #endif
7032         return sd;
7033 }
7034
7035 static void build_sched_groups(struct s_data *d, enum sched_domain_level l,
7036                                const struct cpumask *cpu_map, int cpu)
7037 {
7038         switch (l) {
7039 #ifdef CONFIG_SCHED_SMT
7040         case SD_LV_SIBLING: /* set up CPU (sibling) groups */
7041                 cpumask_and(d->this_sibling_map, cpu_map,
7042                             topology_thread_cpumask(cpu));
7043                 if (cpu == cpumask_first(d->this_sibling_map))
7044                         init_sched_build_groups(d->this_sibling_map, cpu_map,
7045                                                 &cpu_to_cpu_group,
7046                                                 d->send_covered, d->tmpmask);
7047                 break;
7048 #endif
7049 #ifdef CONFIG_SCHED_MC
7050         case SD_LV_MC: /* set up multi-core groups */
7051                 cpumask_and(d->this_core_map, cpu_map, cpu_coregroup_mask(cpu));
7052                 if (cpu == cpumask_first(d->this_core_map))
7053                         init_sched_build_groups(d->this_core_map, cpu_map,
7054                                                 &cpu_to_core_group,
7055                                                 d->send_covered, d->tmpmask);
7056                 break;
7057 #endif
7058 #ifdef CONFIG_SCHED_BOOK
7059         case SD_LV_BOOK: /* set up book groups */
7060                 cpumask_and(d->this_book_map, cpu_map, cpu_book_mask(cpu));
7061                 if (cpu == cpumask_first(d->this_book_map))
7062                         init_sched_build_groups(d->this_book_map, cpu_map,
7063                                                 &cpu_to_book_group,
7064                                                 d->send_covered, d->tmpmask);
7065                 break;
7066 #endif
7067         case SD_LV_CPU: /* set up physical groups */
7068                 cpumask_and(d->nodemask, cpumask_of_node(cpu), cpu_map);
7069                 if (!cpumask_empty(d->nodemask))
7070                         init_sched_build_groups(d->nodemask, cpu_map,
7071                                                 &cpu_to_phys_group,
7072                                                 d->send_covered, d->tmpmask);
7073                 break;
7074 #ifdef CONFIG_NUMA
7075         case SD_LV_ALLNODES:
7076                 init_sched_build_groups(cpu_map, cpu_map, &cpu_to_allnodes_group,
7077                                         d->send_covered, d->tmpmask);
7078                 break;
7079 #endif
7080         default:
7081                 break;
7082         }
7083 }
7084
7085 /*
7086  * Build sched domains for a given set of cpus and attach the sched domains
7087  * to the individual cpus
7088  */
7089 static int __build_sched_domains(const struct cpumask *cpu_map,
7090                                  struct sched_domain_attr *attr)
7091 {
7092         enum s_alloc alloc_state = sa_none;
7093         struct s_data d;
7094         struct sched_domain *sd;
7095         int i;
7096 #ifdef CONFIG_NUMA
7097         d.sd_allnodes = 0;
7098 #endif
7099
7100         alloc_state = __visit_domain_allocation_hell(&d, cpu_map);
7101         if (alloc_state != sa_rootdomain)
7102                 goto error;
7103         alloc_state = sa_sched_groups;
7104
7105         /*
7106          * Set up domains for cpus specified by the cpu_map.
7107          */
7108         for_each_cpu(i, cpu_map) {
7109                 cpumask_and(d.nodemask, cpumask_of_node(cpu_to_node(i)),
7110                             cpu_map);
7111
7112                 sd = __build_numa_sched_domains(&d, cpu_map, attr, i);
7113                 sd = __build_cpu_sched_domain(&d, cpu_map, attr, sd, i);
7114                 sd = __build_book_sched_domain(&d, cpu_map, attr, sd, i);
7115                 sd = __build_mc_sched_domain(&d, cpu_map, attr, sd, i);
7116                 sd = __build_smt_sched_domain(&d, cpu_map, attr, sd, i);
7117         }
7118
7119         for_each_cpu(i, cpu_map) {
7120                 build_sched_groups(&d, SD_LV_SIBLING, cpu_map, i);
7121                 build_sched_groups(&d, SD_LV_BOOK, cpu_map, i);
7122                 build_sched_groups(&d, SD_LV_MC, cpu_map, i);
7123         }
7124
7125         /* Set up physical groups */
7126         for (i = 0; i < nr_node_ids; i++)
7127                 build_sched_groups(&d, SD_LV_CPU, cpu_map, i);
7128
7129 #ifdef CONFIG_NUMA
7130         /* Set up node groups */
7131         if (d.sd_allnodes)
7132                 build_sched_groups(&d, SD_LV_ALLNODES, cpu_map, 0);
7133
7134         for (i = 0; i < nr_node_ids; i++)
7135                 if (build_numa_sched_groups(&d, cpu_map, i))
7136                         goto error;
7137 #endif
7138
7139         /* Calculate CPU power for physical packages and nodes */
7140 #ifdef CONFIG_SCHED_SMT
7141         for_each_cpu(i, cpu_map) {
7142                 sd = &per_cpu(cpu_domains, i).sd;
7143                 init_sched_groups_power(i, sd);
7144         }
7145 #endif
7146 #ifdef CONFIG_SCHED_MC
7147         for_each_cpu(i, cpu_map) {
7148                 sd = &per_cpu(core_domains, i).sd;
7149                 init_sched_groups_power(i, sd);
7150         }
7151 #endif
7152 #ifdef CONFIG_SCHED_BOOK
7153         for_each_cpu(i, cpu_map) {
7154                 sd = &per_cpu(book_domains, i).sd;
7155                 init_sched_groups_power(i, sd);
7156         }
7157 #endif
7158
7159         for_each_cpu(i, cpu_map) {
7160                 sd = &per_cpu(phys_domains, i).sd;
7161                 init_sched_groups_power(i, sd);
7162         }
7163
7164 #ifdef CONFIG_NUMA
7165         for (i = 0; i < nr_node_ids; i++)
7166                 init_numa_sched_groups_power(d.sched_group_nodes[i]);
7167
7168         if (d.sd_allnodes) {
7169                 struct sched_group *sg;
7170
7171                 cpu_to_allnodes_group(cpumask_first(cpu_map), cpu_map, &sg,
7172                                                                 d.tmpmask);
7173                 init_numa_sched_groups_power(sg);
7174         }
7175 #endif
7176
7177         /* Attach the domains */
7178         for_each_cpu(i, cpu_map) {
7179 #ifdef CONFIG_SCHED_SMT
7180                 sd = &per_cpu(cpu_domains, i).sd;
7181 #elif defined(CONFIG_SCHED_MC)
7182                 sd = &per_cpu(core_domains, i).sd;
7183 #elif defined(CONFIG_SCHED_BOOK)
7184                 sd = &per_cpu(book_domains, i).sd;
7185 #else
7186                 sd = &per_cpu(phys_domains, i).sd;
7187 #endif
7188                 cpu_attach_domain(sd, d.rd, i);
7189         }
7190
7191         d.sched_group_nodes = NULL; /* don't free this we still need it */
7192         __free_domain_allocs(&d, sa_tmpmask, cpu_map);
7193         return 0;
7194
7195 error:
7196         __free_domain_allocs(&d, alloc_state, cpu_map);
7197         return -ENOMEM;
7198 }
7199
7200 static int build_sched_domains(const struct cpumask *cpu_map)
7201 {
7202         return __build_sched_domains(cpu_map, NULL);
7203 }
7204
7205 static cpumask_var_t *doms_cur; /* current sched domains */
7206 static int ndoms_cur;           /* number of sched domains in 'doms_cur' */
7207 static struct sched_domain_attr *dattr_cur;
7208                                 /* attribues of custom domains in 'doms_cur' */
7209
7210 /*
7211  * Special case: If a kmalloc of a doms_cur partition (array of
7212  * cpumask) fails, then fallback to a single sched domain,
7213  * as determined by the single cpumask fallback_doms.
7214  */
7215 static cpumask_var_t fallback_doms;
7216
7217 /*
7218  * arch_update_cpu_topology lets virtualized architectures update the
7219  * cpu core maps. It is supposed to return 1 if the topology changed
7220  * or 0 if it stayed the same.
7221  */
7222 int __attribute__((weak)) arch_update_cpu_topology(void)
7223 {
7224         return 0;
7225 }
7226
7227 cpumask_var_t *alloc_sched_domains(unsigned int ndoms)
7228 {
7229         int i;
7230         cpumask_var_t *doms;
7231
7232         doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL);
7233         if (!doms)
7234                 return NULL;
7235         for (i = 0; i < ndoms; i++) {
7236                 if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) {
7237                         free_sched_domains(doms, i);
7238                         return NULL;
7239                 }
7240         }
7241         return doms;
7242 }
7243
7244 void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms)
7245 {
7246         unsigned int i;
7247         for (i = 0; i < ndoms; i++)
7248                 free_cpumask_var(doms[i]);
7249         kfree(doms);
7250 }
7251
7252 /*
7253  * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7254  * For now this just excludes isolated cpus, but could be used to
7255  * exclude other special cases in the future.
7256  */
7257 static int arch_init_sched_domains(const struct cpumask *cpu_map)
7258 {
7259         int err;
7260
7261         arch_update_cpu_topology();
7262         ndoms_cur = 1;
7263         doms_cur = alloc_sched_domains(ndoms_cur);
7264         if (!doms_cur)
7265                 doms_cur = &fallback_doms;
7266         cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map);
7267         dattr_cur = NULL;
7268         err = build_sched_domains(doms_cur[0]);
7269         register_sched_domain_sysctl();
7270
7271         return err;
7272 }
7273
7274 static void arch_destroy_sched_domains(const struct cpumask *cpu_map,
7275                                        struct cpumask *tmpmask)
7276 {
7277         free_sched_groups(cpu_map, tmpmask);
7278 }
7279
7280 /*
7281  * Detach sched domains from a group of cpus specified in cpu_map
7282  * These cpus will now be attached to the NULL domain
7283  */
7284 static void detach_destroy_domains(const struct cpumask *cpu_map)
7285 {
7286         /* Save because hotplug lock held. */
7287         static DECLARE_BITMAP(tmpmask, CONFIG_NR_CPUS);
7288         int i;
7289
7290         for_each_cpu(i, cpu_map)
7291                 cpu_attach_domain(NULL, &def_root_domain, i);
7292         synchronize_sched();
7293         arch_destroy_sched_domains(cpu_map, to_cpumask(tmpmask));
7294 }
7295
7296 /* handle null as "default" */
7297 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7298                         struct sched_domain_attr *new, int idx_new)
7299 {
7300         struct sched_domain_attr tmp;
7301
7302         /* fast path */
7303         if (!new && !cur)
7304                 return 1;
7305
7306         tmp = SD_ATTR_INIT;
7307         return !memcmp(cur ? (cur + idx_cur) : &tmp,
7308                         new ? (new + idx_new) : &tmp,
7309                         sizeof(struct sched_domain_attr));
7310 }
7311
7312 /*
7313  * Partition sched domains as specified by the 'ndoms_new'
7314  * cpumasks in the array doms_new[] of cpumasks. This compares
7315  * doms_new[] to the current sched domain partitioning, doms_cur[].
7316  * It destroys each deleted domain and builds each new domain.
7317  *
7318  * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'.
7319  * The masks don't intersect (don't overlap.) We should setup one
7320  * sched domain for each mask. CPUs not in any of the cpumasks will
7321  * not be load balanced. If the same cpumask appears both in the
7322  * current 'doms_cur' domains and in the new 'doms_new', we can leave
7323  * it as it is.
7324  *
7325  * The passed in 'doms_new' should be allocated using
7326  * alloc_sched_domains.  This routine takes ownership of it and will
7327  * free_sched_domains it when done with it. If the caller failed the
7328  * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1,
7329  * and partition_sched_domains() will fallback to the single partition
7330  * 'fallback_doms', it also forces the domains to be rebuilt.
7331  *
7332  * If doms_new == NULL it will be replaced with cpu_online_mask.
7333  * ndoms_new == 0 is a special case for destroying existing domains,
7334  * and it will not create the default domain.
7335  *
7336  * Call with hotplug lock held
7337  */
7338 void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
7339                              struct sched_domain_attr *dattr_new)
7340 {
7341         int i, j, n;
7342         int new_topology;
7343
7344         mutex_lock(&sched_domains_mutex);
7345
7346         /* always unregister in case we don't destroy any domains */
7347         unregister_sched_domain_sysctl();
7348
7349         /* Let architecture update cpu core mappings. */
7350         new_topology = arch_update_cpu_topology();
7351
7352         n = doms_new ? ndoms_new : 0;
7353
7354         /* Destroy deleted domains */
7355         for (i = 0; i < ndoms_cur; i++) {
7356                 for (j = 0; j < n && !new_topology; j++) {
7357                         if (cpumask_equal(doms_cur[i], doms_new[j])
7358                             && dattrs_equal(dattr_cur, i, dattr_new, j))
7359                                 goto match1;
7360                 }
7361                 /* no match - a current sched domain not in new doms_new[] */
7362                 detach_destroy_domains(doms_cur[i]);
7363 match1:
7364                 ;
7365         }
7366
7367         if (doms_new == NULL) {
7368                 ndoms_cur = 0;
7369                 doms_new = &fallback_doms;
7370                 cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map);
7371                 WARN_ON_ONCE(dattr_new);
7372         }
7373
7374         /* Build new domains */
7375         for (i = 0; i < ndoms_new; i++) {
7376                 for (j = 0; j < ndoms_cur && !new_topology; j++) {
7377                         if (cpumask_equal(doms_new[i], doms_cur[j])
7378                             && dattrs_equal(dattr_new, i, dattr_cur, j))
7379                                 goto match2;
7380                 }
7381                 /* no match - add a new doms_new */
7382                 __build_sched_domains(doms_new[i],
7383                                         dattr_new ? dattr_new + i : NULL);
7384 match2:
7385                 ;
7386         }
7387
7388         /* Remember the new sched domains */
7389         if (doms_cur != &fallback_doms)
7390                 free_sched_domains(doms_cur, ndoms_cur);
7391         kfree(dattr_cur);       /* kfree(NULL) is safe */
7392         doms_cur = doms_new;
7393         dattr_cur = dattr_new;
7394         ndoms_cur = ndoms_new;
7395
7396         register_sched_domain_sysctl();
7397
7398         mutex_unlock(&sched_domains_mutex);
7399 }
7400
7401 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7402 static void arch_reinit_sched_domains(void)
7403 {
7404         get_online_cpus();
7405
7406         /* Destroy domains first to force the rebuild */
7407         partition_sched_domains(0, NULL, NULL);
7408
7409         rebuild_sched_domains();
7410         put_online_cpus();
7411 }
7412
7413 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7414 {
7415         unsigned int level = 0;
7416
7417         if (sscanf(buf, "%u", &level) != 1)
7418                 return -EINVAL;
7419
7420         /*
7421          * level is always be positive so don't check for
7422          * level < POWERSAVINGS_BALANCE_NONE which is 0
7423          * What happens on 0 or 1 byte write,
7424          * need to check for count as well?
7425          */
7426
7427         if (level >= MAX_POWERSAVINGS_BALANCE_LEVELS)
7428                 return -EINVAL;
7429
7430         if (smt)
7431                 sched_smt_power_savings = level;
7432         else
7433                 sched_mc_power_savings = level;
7434
7435         arch_reinit_sched_domains();
7436
7437         return count;
7438 }
7439
7440 #ifdef CONFIG_SCHED_MC
7441 static ssize_t sched_mc_power_savings_show(struct sysdev_class *class,
7442                                            struct sysdev_class_attribute *attr,
7443                                            char *page)
7444 {
7445         return sprintf(page, "%u\n", sched_mc_power_savings);
7446 }
7447 static ssize_t sched_mc_power_savings_store(struct sysdev_class *class,
7448                                             struct sysdev_class_attribute *attr,
7449                                             const char *buf, size_t count)
7450 {
7451         return sched_power_savings_store(buf, count, 0);
7452 }
7453 static SYSDEV_CLASS_ATTR(sched_mc_power_savings, 0644,
7454                          sched_mc_power_savings_show,
7455                          sched_mc_power_savings_store);
7456 #endif
7457
7458 #ifdef CONFIG_SCHED_SMT
7459 static ssize_t sched_smt_power_savings_show(struct sysdev_class *dev,
7460                                             struct sysdev_class_attribute *attr,
7461                                             char *page)
7462 {
7463         return sprintf(page, "%u\n", sched_smt_power_savings);
7464 }
7465 static ssize_t sched_smt_power_savings_store(struct sysdev_class *dev,
7466                                              struct sysdev_class_attribute *attr,
7467                                              const char *buf, size_t count)
7468 {
7469         return sched_power_savings_store(buf, count, 1);
7470 }
7471 static SYSDEV_CLASS_ATTR(sched_smt_power_savings, 0644,
7472                    sched_smt_power_savings_show,
7473                    sched_smt_power_savings_store);
7474 #endif
7475
7476 int __init sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7477 {
7478         int err = 0;
7479
7480 #ifdef CONFIG_SCHED_SMT
7481         if (smt_capable())
7482                 err = sysfs_create_file(&cls->kset.kobj,
7483                                         &attr_sched_smt_power_savings.attr);
7484 #endif
7485 #ifdef CONFIG_SCHED_MC
7486         if (!err && mc_capable())
7487                 err = sysfs_create_file(&cls->kset.kobj,
7488                                         &attr_sched_mc_power_savings.attr);
7489 #endif
7490         return err;
7491 }
7492 #endif /* CONFIG_SCHED_MC || CONFIG_SCHED_SMT */
7493
7494 /*
7495  * Update cpusets according to cpu_active mask.  If cpusets are
7496  * disabled, cpuset_update_active_cpus() becomes a simple wrapper
7497  * around partition_sched_domains().
7498  */
7499 static int cpuset_cpu_active(struct notifier_block *nfb, unsigned long action,
7500                              void *hcpu)
7501 {
7502         switch (action & ~CPU_TASKS_FROZEN) {
7503         case CPU_ONLINE:
7504         case CPU_DOWN_FAILED:
7505                 cpuset_update_active_cpus();
7506                 return NOTIFY_OK;
7507         default:
7508                 return NOTIFY_DONE;
7509         }
7510 }
7511
7512 static int cpuset_cpu_inactive(struct notifier_block *nfb, unsigned long action,
7513                                void *hcpu)
7514 {
7515         switch (action & ~CPU_TASKS_FROZEN) {
7516         case CPU_DOWN_PREPARE:
7517                 cpuset_update_active_cpus();
7518                 return NOTIFY_OK;
7519         default:
7520                 return NOTIFY_DONE;
7521         }
7522 }
7523
7524 static int update_runtime(struct notifier_block *nfb,
7525                                 unsigned long action, void *hcpu)
7526 {
7527         int cpu = (int)(long)hcpu;
7528
7529         switch (action) {
7530         case CPU_DOWN_PREPARE:
7531         case CPU_DOWN_PREPARE_FROZEN:
7532                 disable_runtime(cpu_rq(cpu));
7533                 return NOTIFY_OK;
7534
7535         case CPU_DOWN_FAILED:
7536         case CPU_DOWN_FAILED_FROZEN:
7537         case CPU_ONLINE:
7538         case CPU_ONLINE_FROZEN:
7539                 enable_runtime(cpu_rq(cpu));
7540                 return NOTIFY_OK;
7541
7542         default:
7543                 return NOTIFY_DONE;
7544         }
7545 }
7546
7547 void __init sched_init_smp(void)
7548 {
7549         cpumask_var_t non_isolated_cpus;
7550
7551         alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL);
7552         alloc_cpumask_var(&fallback_doms, GFP_KERNEL);
7553
7554 #if defined(CONFIG_NUMA)
7555         sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
7556                                                                 GFP_KERNEL);
7557         BUG_ON(sched_group_nodes_bycpu == NULL);
7558 #endif
7559         get_online_cpus();
7560         mutex_lock(&sched_domains_mutex);
7561         arch_init_sched_domains(cpu_active_mask);
7562         cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map);
7563         if (cpumask_empty(non_isolated_cpus))
7564                 cpumask_set_cpu(smp_processor_id(), non_isolated_cpus);
7565         mutex_unlock(&sched_domains_mutex);
7566         put_online_cpus();
7567
7568         hotcpu_notifier(cpuset_cpu_active, CPU_PRI_CPUSET_ACTIVE);
7569         hotcpu_notifier(cpuset_cpu_inactive, CPU_PRI_CPUSET_INACTIVE);
7570
7571         /* RT runtime code needs to handle some hotplug events */
7572         hotcpu_notifier(update_runtime, 0);
7573
7574         init_hrtick();
7575
7576         /* Move init over to a non-isolated CPU */
7577         if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0)
7578                 BUG();
7579         sched_init_granularity();
7580         free_cpumask_var(non_isolated_cpus);
7581
7582         init_sched_rt_class();
7583 }
7584 #else
7585 void __init sched_init_smp(void)
7586 {
7587         sched_init_granularity();
7588 }
7589 #endif /* CONFIG_SMP */
7590
7591 const_debug unsigned int sysctl_timer_migration = 1;
7592
7593 int in_sched_functions(unsigned long addr)
7594 {
7595         return in_lock_functions(addr) ||
7596                 (addr >= (unsigned long)__sched_text_start
7597                 && addr < (unsigned long)__sched_text_end);
7598 }
7599
7600 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
7601 {
7602         cfs_rq->tasks_timeline = RB_ROOT;
7603         INIT_LIST_HEAD(&cfs_rq->tasks);
7604 #ifdef CONFIG_FAIR_GROUP_SCHED
7605         cfs_rq->rq = rq;
7606 #endif
7607         cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7608 }
7609
7610 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
7611 {
7612         struct rt_prio_array *array;
7613         int i;
7614
7615         array = &rt_rq->active;
7616         for (i = 0; i < MAX_RT_PRIO; i++) {
7617                 INIT_LIST_HEAD(array->queue + i);
7618                 __clear_bit(i, array->bitmap);
7619         }
7620         /* delimiter for bitsearch: */
7621         __set_bit(MAX_RT_PRIO, array->bitmap);
7622
7623 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
7624         rt_rq->highest_prio.curr = MAX_RT_PRIO;
7625 #ifdef CONFIG_SMP
7626         rt_rq->highest_prio.next = MAX_RT_PRIO;
7627 #endif
7628 #endif
7629 #ifdef CONFIG_SMP
7630         rt_rq->rt_nr_migratory = 0;
7631         rt_rq->overloaded = 0;
7632         plist_head_init_raw(&rt_rq->pushable_tasks, &rq->lock);
7633 #endif
7634
7635         rt_rq->rt_time = 0;
7636         rt_rq->rt_throttled = 0;
7637         rt_rq->rt_runtime = 0;
7638         raw_spin_lock_init(&rt_rq->rt_runtime_lock);
7639
7640 #ifdef CONFIG_RT_GROUP_SCHED
7641         rt_rq->rt_nr_boosted = 0;
7642         rt_rq->rq = rq;
7643 #endif
7644 }
7645
7646 #ifdef CONFIG_FAIR_GROUP_SCHED
7647 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
7648                                 struct sched_entity *se, int cpu,
7649                                 struct sched_entity *parent)
7650 {
7651         struct rq *rq = cpu_rq(cpu);
7652         tg->cfs_rq[cpu] = cfs_rq;
7653         init_cfs_rq(cfs_rq, rq);
7654         cfs_rq->tg = tg;
7655
7656         tg->se[cpu] = se;
7657         /* se could be NULL for init_task_group */
7658         if (!se)
7659                 return;
7660
7661         if (!parent)
7662                 se->cfs_rq = &rq->cfs;
7663         else
7664                 se->cfs_rq = parent->my_q;
7665
7666         se->my_q = cfs_rq;
7667         update_load_set(&se->load, 0);
7668         se->parent = parent;
7669 }
7670 #endif
7671
7672 #ifdef CONFIG_RT_GROUP_SCHED
7673 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
7674                 struct sched_rt_entity *rt_se, int cpu,
7675                 struct sched_rt_entity *parent)
7676 {
7677         struct rq *rq = cpu_rq(cpu);
7678
7679         tg->rt_rq[cpu] = rt_rq;
7680         init_rt_rq(rt_rq, rq);
7681         rt_rq->tg = tg;
7682         rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
7683
7684         tg->rt_se[cpu] = rt_se;
7685         if (!rt_se)
7686                 return;
7687
7688         if (!parent)
7689                 rt_se->rt_rq = &rq->rt;
7690         else
7691                 rt_se->rt_rq = parent->my_q;
7692
7693         rt_se->my_q = rt_rq;
7694         rt_se->parent = parent;
7695         INIT_LIST_HEAD(&rt_se->run_list);
7696 }
7697 #endif
7698
7699 void __init sched_init(void)
7700 {
7701         int i, j;
7702         unsigned long alloc_size = 0, ptr;
7703
7704 #ifdef CONFIG_FAIR_GROUP_SCHED
7705         alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7706 #endif
7707 #ifdef CONFIG_RT_GROUP_SCHED
7708         alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7709 #endif
7710 #ifdef CONFIG_CPUMASK_OFFSTACK
7711         alloc_size += num_possible_cpus() * cpumask_size();
7712 #endif
7713         if (alloc_size) {
7714                 ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
7715
7716 #ifdef CONFIG_FAIR_GROUP_SCHED
7717                 init_task_group.se = (struct sched_entity **)ptr;
7718                 ptr += nr_cpu_ids * sizeof(void **);
7719
7720                 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
7721                 ptr += nr_cpu_ids * sizeof(void **);
7722
7723 #endif /* CONFIG_FAIR_GROUP_SCHED */
7724 #ifdef CONFIG_RT_GROUP_SCHED
7725                 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
7726                 ptr += nr_cpu_ids * sizeof(void **);
7727
7728                 init_task_group.rt_rq = (struct rt_rq **)ptr;
7729                 ptr += nr_cpu_ids * sizeof(void **);
7730
7731 #endif /* CONFIG_RT_GROUP_SCHED */
7732 #ifdef CONFIG_CPUMASK_OFFSTACK
7733                 for_each_possible_cpu(i) {
7734                         per_cpu(load_balance_tmpmask, i) = (void *)ptr;
7735                         ptr += cpumask_size();
7736                 }
7737 #endif /* CONFIG_CPUMASK_OFFSTACK */
7738         }
7739
7740 #ifdef CONFIG_SMP
7741         init_defrootdomain();
7742 #endif
7743
7744         init_rt_bandwidth(&def_rt_bandwidth,
7745                         global_rt_period(), global_rt_runtime());
7746
7747 #ifdef CONFIG_RT_GROUP_SCHED
7748         init_rt_bandwidth(&init_task_group.rt_bandwidth,
7749                         global_rt_period(), global_rt_runtime());
7750 #endif /* CONFIG_RT_GROUP_SCHED */
7751
7752 #ifdef CONFIG_CGROUP_SCHED
7753         list_add(&init_task_group.list, &task_groups);
7754         INIT_LIST_HEAD(&init_task_group.children);
7755
7756 #endif /* CONFIG_CGROUP_SCHED */
7757
7758         for_each_possible_cpu(i) {
7759                 struct rq *rq;
7760
7761                 rq = cpu_rq(i);
7762                 raw_spin_lock_init(&rq->lock);
7763                 rq->nr_running = 0;
7764                 rq->calc_load_active = 0;
7765                 rq->calc_load_update = jiffies + LOAD_FREQ;
7766                 init_cfs_rq(&rq->cfs, rq);
7767                 init_rt_rq(&rq->rt, rq);
7768 #ifdef CONFIG_FAIR_GROUP_SCHED
7769                 init_task_group.shares = init_task_group_load;
7770                 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7771 #ifdef CONFIG_CGROUP_SCHED
7772                 /*
7773                  * How much cpu bandwidth does init_task_group get?
7774                  *
7775                  * In case of task-groups formed thr' the cgroup filesystem, it
7776                  * gets 100% of the cpu resources in the system. This overall
7777                  * system cpu resource is divided among the tasks of
7778                  * init_task_group and its child task-groups in a fair manner,
7779                  * based on each entity's (task or task-group's) weight
7780                  * (se->load.weight).
7781                  *
7782                  * In other words, if init_task_group has 10 tasks of weight
7783                  * 1024) and two child groups A0 and A1 (of weight 1024 each),
7784                  * then A0's share of the cpu resource is:
7785                  *
7786                  *      A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
7787                  *
7788                  * We achieve this by letting init_task_group's tasks sit
7789                  * directly in rq->cfs (i.e init_task_group->se[] = NULL).
7790                  */
7791                 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, NULL);
7792 #endif
7793 #endif /* CONFIG_FAIR_GROUP_SCHED */
7794
7795                 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
7796 #ifdef CONFIG_RT_GROUP_SCHED
7797                 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
7798 #ifdef CONFIG_CGROUP_SCHED
7799                 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, NULL);
7800 #endif
7801 #endif
7802
7803                 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7804                         rq->cpu_load[j] = 0;
7805
7806                 rq->last_load_update_tick = jiffies;
7807
7808 #ifdef CONFIG_SMP
7809                 rq->sd = NULL;
7810                 rq->rd = NULL;
7811                 rq->cpu_power = SCHED_LOAD_SCALE;
7812                 rq->post_schedule = 0;
7813                 rq->active_balance = 0;
7814                 rq->next_balance = jiffies;
7815                 rq->push_cpu = 0;
7816                 rq->cpu = i;
7817                 rq->online = 0;
7818                 rq->idle_stamp = 0;
7819                 rq->avg_idle = 2*sysctl_sched_migration_cost;
7820                 rq_attach_root(rq, &def_root_domain);
7821 #ifdef CONFIG_NO_HZ
7822                 rq->nohz_balance_kick = 0;
7823                 init_sched_softirq_csd(&per_cpu(remote_sched_softirq_cb, i));
7824 #endif
7825 #endif
7826                 init_rq_hrtick(rq);
7827                 atomic_set(&rq->nr_iowait, 0);
7828         }
7829
7830         set_load_weight(&init_task);
7831
7832 #ifdef CONFIG_PREEMPT_NOTIFIERS
7833         INIT_HLIST_HEAD(&init_task.preempt_notifiers);
7834 #endif
7835
7836 #ifdef CONFIG_SMP
7837         open_softirq(SCHED_SOFTIRQ, run_rebalance_domains);
7838 #endif
7839
7840 #ifdef CONFIG_RT_MUTEXES
7841         plist_head_init_raw(&init_task.pi_waiters, &init_task.pi_lock);
7842 #endif
7843
7844         /*
7845          * The boot idle thread does lazy MMU switching as well:
7846          */
7847         atomic_inc(&init_mm.mm_count);
7848         enter_lazy_tlb(&init_mm, current);
7849
7850         /*
7851          * Make us the idle thread. Technically, schedule() should not be
7852          * called from this thread, however somewhere below it might be,
7853          * but because we are the idle thread, we just pick up running again
7854          * when this runqueue becomes "idle".
7855          */
7856         init_idle(current, smp_processor_id());
7857
7858         calc_load_update = jiffies + LOAD_FREQ;
7859
7860         /*
7861          * During early bootup we pretend to be a normal task:
7862          */
7863         current->sched_class = &fair_sched_class;
7864
7865         /* Allocate the nohz_cpu_mask if CONFIG_CPUMASK_OFFSTACK */
7866         zalloc_cpumask_var(&nohz_cpu_mask, GFP_NOWAIT);
7867 #ifdef CONFIG_SMP
7868 #ifdef CONFIG_NO_HZ
7869         zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT);
7870         alloc_cpumask_var(&nohz.grp_idle_mask, GFP_NOWAIT);
7871         atomic_set(&nohz.load_balancer, nr_cpu_ids);
7872         atomic_set(&nohz.first_pick_cpu, nr_cpu_ids);
7873         atomic_set(&nohz.second_pick_cpu, nr_cpu_ids);
7874 #endif
7875         /* May be allocated at isolcpus cmdline parse time */
7876         if (cpu_isolated_map == NULL)
7877                 zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT);
7878 #endif /* SMP */
7879
7880         perf_event_init();
7881
7882         scheduler_running = 1;
7883 }
7884
7885 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
7886 static inline int preempt_count_equals(int preempt_offset)
7887 {
7888         int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth();
7889
7890         return (nested == PREEMPT_INATOMIC_BASE + preempt_offset);
7891 }
7892
7893 void __might_sleep(const char *file, int line, int preempt_offset)
7894 {
7895 #ifdef in_atomic
7896         static unsigned long prev_jiffy;        /* ratelimiting */
7897
7898         if ((preempt_count_equals(preempt_offset) && !irqs_disabled()) ||
7899             system_state != SYSTEM_RUNNING || oops_in_progress)
7900                 return;
7901         if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7902                 return;
7903         prev_jiffy = jiffies;
7904
7905         printk(KERN_ERR
7906                 "BUG: sleeping function called from invalid context at %s:%d\n",
7907                         file, line);
7908         printk(KERN_ERR
7909                 "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
7910                         in_atomic(), irqs_disabled(),
7911                         current->pid, current->comm);
7912
7913         debug_show_held_locks(current);
7914         if (irqs_disabled())
7915                 print_irqtrace_events(current);
7916         dump_stack();
7917 #endif
7918 }
7919 EXPORT_SYMBOL(__might_sleep);
7920 #endif
7921
7922 #ifdef CONFIG_MAGIC_SYSRQ
7923 static void normalize_task(struct rq *rq, struct task_struct *p)
7924 {
7925         int on_rq;
7926
7927         on_rq = p->se.on_rq;
7928         if (on_rq)
7929                 deactivate_task(rq, p, 0);
7930         __setscheduler(rq, p, SCHED_NORMAL, 0);
7931         if (on_rq) {
7932                 activate_task(rq, p, 0);
7933                 resched_task(rq->curr);
7934         }
7935 }
7936
7937 void normalize_rt_tasks(void)
7938 {
7939         struct task_struct *g, *p;
7940         unsigned long flags;
7941         struct rq *rq;
7942
7943         read_lock_irqsave(&tasklist_lock, flags);
7944         do_each_thread(g, p) {
7945                 /*
7946                  * Only normalize user tasks:
7947                  */
7948                 if (!p->mm)
7949                         continue;
7950
7951                 p->se.exec_start                = 0;
7952 #ifdef CONFIG_SCHEDSTATS
7953                 p->se.statistics.wait_start     = 0;
7954                 p->se.statistics.sleep_start    = 0;
7955                 p->se.statistics.block_start    = 0;
7956 #endif
7957
7958                 if (!rt_task(p)) {
7959                         /*
7960                          * Renice negative nice level userspace
7961                          * tasks back to 0:
7962                          */
7963                         if (TASK_NICE(p) < 0 && p->mm)
7964                                 set_user_nice(p, 0);
7965                         continue;
7966                 }
7967
7968                 raw_spin_lock(&p->pi_lock);
7969                 rq = __task_rq_lock(p);
7970
7971                 normalize_task(rq, p);
7972
7973                 __task_rq_unlock(rq);
7974                 raw_spin_unlock(&p->pi_lock);
7975         } while_each_thread(g, p);
7976
7977         read_unlock_irqrestore(&tasklist_lock, flags);
7978 }
7979
7980 #endif /* CONFIG_MAGIC_SYSRQ */
7981
7982 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
7983 /*
7984  * These functions are only useful for the IA64 MCA handling, or kdb.
7985  *
7986  * They can only be called when the whole system has been
7987  * stopped - every CPU needs to be quiescent, and no scheduling
7988  * activity can take place. Using them for anything else would
7989  * be a serious bug, and as a result, they aren't even visible
7990  * under any other configuration.
7991  */
7992
7993 /**
7994  * curr_task - return the current task for a given cpu.
7995  * @cpu: the processor in question.
7996  *
7997  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7998  */
7999 struct task_struct *curr_task(int cpu)
8000 {
8001         return cpu_curr(cpu);
8002 }
8003
8004 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
8005
8006 #ifdef CONFIG_IA64
8007 /**
8008  * set_curr_task - set the current task for a given cpu.
8009  * @cpu: the processor in question.
8010  * @p: the task pointer to set.
8011  *
8012  * Description: This function must only be used when non-maskable interrupts
8013  * are serviced on a separate stack. It allows the architecture to switch the
8014  * notion of the current task on a cpu in a non-blocking manner. This function
8015  * must be called with all CPU's synchronized, and interrupts disabled, the
8016  * and caller must save the original value of the current task (see
8017  * curr_task() above) and restore that value before reenabling interrupts and
8018  * re-starting the system.
8019  *
8020  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8021  */
8022 void set_curr_task(int cpu, struct task_struct *p)
8023 {
8024         cpu_curr(cpu) = p;
8025 }
8026
8027 #endif
8028
8029 #ifdef CONFIG_FAIR_GROUP_SCHED
8030 static void free_fair_sched_group(struct task_group *tg)
8031 {
8032         int i;
8033
8034         for_each_possible_cpu(i) {
8035                 if (tg->cfs_rq)
8036                         kfree(tg->cfs_rq[i]);
8037                 if (tg->se)
8038                         kfree(tg->se[i]);
8039         }
8040
8041         kfree(tg->cfs_rq);
8042         kfree(tg->se);
8043 }
8044
8045 static
8046 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8047 {
8048         struct cfs_rq *cfs_rq;
8049         struct sched_entity *se;
8050         struct rq *rq;
8051         int i;
8052
8053         tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
8054         if (!tg->cfs_rq)
8055                 goto err;
8056         tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
8057         if (!tg->se)
8058                 goto err;
8059
8060         tg->shares = NICE_0_LOAD;
8061
8062         for_each_possible_cpu(i) {
8063                 rq = cpu_rq(i);
8064
8065                 cfs_rq = kzalloc_node(sizeof(struct cfs_rq),
8066                                       GFP_KERNEL, cpu_to_node(i));
8067                 if (!cfs_rq)
8068                         goto err;
8069
8070                 se = kzalloc_node(sizeof(struct sched_entity),
8071                                   GFP_KERNEL, cpu_to_node(i));
8072                 if (!se)
8073                         goto err_free_rq;
8074
8075                 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]);
8076         }
8077
8078         return 1;
8079
8080 err_free_rq:
8081         kfree(cfs_rq);
8082 err:
8083         return 0;
8084 }
8085
8086 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8087 {
8088         struct rq *rq = cpu_rq(cpu);
8089         unsigned long flags;
8090         int i;
8091
8092         /*
8093         * Only empty task groups can be destroyed; so we can speculatively
8094         * check on_list without danger of it being re-added.
8095         */
8096         if (!tg->cfs_rq[cpu]->on_list)
8097                 return;
8098
8099         raw_spin_lock_irqsave(&rq->lock, flags);
8100         list_del_leaf_cfs_rq(tg->cfs_rq[i]);
8101         raw_spin_unlock_irqrestore(&rq->lock, flags);
8102 }
8103 #else /* !CONFG_FAIR_GROUP_SCHED */
8104 static inline void free_fair_sched_group(struct task_group *tg)
8105 {
8106 }
8107
8108 static inline
8109 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8110 {
8111         return 1;
8112 }
8113
8114 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8115 {
8116 }
8117 #endif /* CONFIG_FAIR_GROUP_SCHED */
8118
8119 #ifdef CONFIG_RT_GROUP_SCHED
8120 static void free_rt_sched_group(struct task_group *tg)
8121 {
8122         int i;
8123
8124         destroy_rt_bandwidth(&tg->rt_bandwidth);
8125
8126         for_each_possible_cpu(i) {
8127                 if (tg->rt_rq)
8128                         kfree(tg->rt_rq[i]);
8129                 if (tg->rt_se)
8130                         kfree(tg->rt_se[i]);
8131         }
8132
8133         kfree(tg->rt_rq);
8134         kfree(tg->rt_se);
8135 }
8136
8137 static
8138 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8139 {
8140         struct rt_rq *rt_rq;
8141         struct sched_rt_entity *rt_se;
8142         struct rq *rq;
8143         int i;
8144
8145         tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
8146         if (!tg->rt_rq)
8147                 goto err;
8148         tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
8149         if (!tg->rt_se)
8150                 goto err;
8151
8152         init_rt_bandwidth(&tg->rt_bandwidth,
8153                         ktime_to_ns(def_rt_bandwidth.rt_period), 0);
8154
8155         for_each_possible_cpu(i) {
8156                 rq = cpu_rq(i);
8157
8158                 rt_rq = kzalloc_node(sizeof(struct rt_rq),
8159                                      GFP_KERNEL, cpu_to_node(i));
8160                 if (!rt_rq)
8161                         goto err;
8162
8163                 rt_se = kzalloc_node(sizeof(struct sched_rt_entity),
8164                                      GFP_KERNEL, cpu_to_node(i));
8165                 if (!rt_se)
8166                         goto err_free_rq;
8167
8168                 init_tg_rt_entry(tg, rt_rq, rt_se, i, parent->rt_se[i]);
8169         }
8170
8171         return 1;
8172
8173 err_free_rq:
8174         kfree(rt_rq);
8175 err:
8176         return 0;
8177 }
8178 #else /* !CONFIG_RT_GROUP_SCHED */
8179 static inline void free_rt_sched_group(struct task_group *tg)
8180 {
8181 }
8182
8183 static inline
8184 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8185 {
8186         return 1;
8187 }
8188 #endif /* CONFIG_RT_GROUP_SCHED */
8189
8190 #ifdef CONFIG_CGROUP_SCHED
8191 static void free_sched_group(struct task_group *tg)
8192 {
8193         free_fair_sched_group(tg);
8194         free_rt_sched_group(tg);
8195         kfree(tg);
8196 }
8197
8198 /* allocate runqueue etc for a new task group */
8199 struct task_group *sched_create_group(struct task_group *parent)
8200 {
8201         struct task_group *tg;
8202         unsigned long flags;
8203
8204         tg = kzalloc(sizeof(*tg), GFP_KERNEL);
8205         if (!tg)
8206                 return ERR_PTR(-ENOMEM);
8207
8208         if (!alloc_fair_sched_group(tg, parent))
8209                 goto err;
8210
8211         if (!alloc_rt_sched_group(tg, parent))
8212                 goto err;
8213
8214         spin_lock_irqsave(&task_group_lock, flags);
8215         list_add_rcu(&tg->list, &task_groups);
8216
8217         WARN_ON(!parent); /* root should already exist */
8218
8219         tg->parent = parent;
8220         INIT_LIST_HEAD(&tg->children);
8221         list_add_rcu(&tg->siblings, &parent->children);
8222         spin_unlock_irqrestore(&task_group_lock, flags);
8223
8224         return tg;
8225
8226 err:
8227         free_sched_group(tg);
8228         return ERR_PTR(-ENOMEM);
8229 }
8230
8231 /* rcu callback to free various structures associated with a task group */
8232 static void free_sched_group_rcu(struct rcu_head *rhp)
8233 {
8234         /* now it should be safe to free those cfs_rqs */
8235         free_sched_group(container_of(rhp, struct task_group, rcu));
8236 }
8237
8238 /* Destroy runqueue etc associated with a task group */
8239 void sched_destroy_group(struct task_group *tg)
8240 {
8241         unsigned long flags;
8242         int i;
8243
8244         /* end participation in shares distribution */
8245         for_each_possible_cpu(i)
8246                 unregister_fair_sched_group(tg, i);
8247
8248         spin_lock_irqsave(&task_group_lock, flags);
8249         list_del_rcu(&tg->list);
8250         list_del_rcu(&tg->siblings);
8251         spin_unlock_irqrestore(&task_group_lock, flags);
8252
8253         /* wait for possible concurrent references to cfs_rqs complete */
8254         call_rcu(&tg->rcu, free_sched_group_rcu);
8255 }
8256
8257 /* change task's runqueue when it moves between groups.
8258  *      The caller of this function should have put the task in its new group
8259  *      by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8260  *      reflect its new group.
8261  */
8262 void sched_move_task(struct task_struct *tsk)
8263 {
8264         int on_rq, running;
8265         unsigned long flags;
8266         struct rq *rq;
8267
8268         rq = task_rq_lock(tsk, &flags);
8269
8270         running = task_current(rq, tsk);
8271         on_rq = tsk->se.on_rq;
8272
8273         if (on_rq)
8274                 dequeue_task(rq, tsk, 0);
8275         if (unlikely(running))
8276                 tsk->sched_class->put_prev_task(rq, tsk);
8277
8278 #ifdef CONFIG_FAIR_GROUP_SCHED
8279         if (tsk->sched_class->task_move_group)
8280                 tsk->sched_class->task_move_group(tsk, on_rq);
8281         else
8282 #endif
8283                 set_task_rq(tsk, task_cpu(tsk));
8284
8285         if (unlikely(running))
8286                 tsk->sched_class->set_curr_task(rq);
8287         if (on_rq)
8288                 enqueue_task(rq, tsk, 0);
8289
8290         task_rq_unlock(rq, &flags);
8291 }
8292 #endif /* CONFIG_CGROUP_SCHED */
8293
8294 #ifdef CONFIG_FAIR_GROUP_SCHED
8295 static DEFINE_MUTEX(shares_mutex);
8296
8297 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8298 {
8299         int i;
8300         unsigned long flags;
8301
8302         /*
8303          * We can't change the weight of the root cgroup.
8304          */
8305         if (!tg->se[0])
8306                 return -EINVAL;
8307
8308         if (shares < MIN_SHARES)
8309                 shares = MIN_SHARES;
8310         else if (shares > MAX_SHARES)
8311                 shares = MAX_SHARES;
8312
8313         mutex_lock(&shares_mutex);
8314         if (tg->shares == shares)
8315                 goto done;
8316
8317         tg->shares = shares;
8318         for_each_possible_cpu(i) {
8319                 struct rq *rq = cpu_rq(i);
8320                 struct sched_entity *se;
8321
8322                 se = tg->se[i];
8323                 /* Propagate contribution to hierarchy */
8324                 raw_spin_lock_irqsave(&rq->lock, flags);
8325                 for_each_sched_entity(se)
8326                         update_cfs_shares(group_cfs_rq(se), 0);
8327                 raw_spin_unlock_irqrestore(&rq->lock, flags);
8328         }
8329
8330 done:
8331         mutex_unlock(&shares_mutex);
8332         return 0;
8333 }
8334
8335 unsigned long sched_group_shares(struct task_group *tg)
8336 {
8337         return tg->shares;
8338 }
8339 #endif
8340
8341 #ifdef CONFIG_RT_GROUP_SCHED
8342 /*
8343  * Ensure that the real time constraints are schedulable.
8344  */
8345 static DEFINE_MUTEX(rt_constraints_mutex);
8346
8347 static unsigned long to_ratio(u64 period, u64 runtime)
8348 {
8349         if (runtime == RUNTIME_INF)
8350                 return 1ULL << 20;
8351
8352         return div64_u64(runtime << 20, period);
8353 }
8354
8355 /* Must be called with tasklist_lock held */
8356 static inline int tg_has_rt_tasks(struct task_group *tg)
8357 {
8358         struct task_struct *g, *p;
8359
8360         do_each_thread(g, p) {
8361                 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
8362                         return 1;
8363         } while_each_thread(g, p);
8364
8365         return 0;
8366 }
8367
8368 struct rt_schedulable_data {
8369         struct task_group *tg;
8370         u64 rt_period;
8371         u64 rt_runtime;
8372 };
8373
8374 static int tg_schedulable(struct task_group *tg, void *data)
8375 {
8376         struct rt_schedulable_data *d = data;
8377         struct task_group *child;
8378         unsigned long total, sum = 0;
8379         u64 period, runtime;
8380
8381         period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8382         runtime = tg->rt_bandwidth.rt_runtime;
8383
8384         if (tg == d->tg) {
8385                 period = d->rt_period;
8386                 runtime = d->rt_runtime;
8387         }
8388
8389         /*
8390          * Cannot have more runtime than the period.
8391          */
8392         if (runtime > period && runtime != RUNTIME_INF)
8393                 return -EINVAL;
8394
8395         /*
8396          * Ensure we don't starve existing RT tasks.
8397          */
8398         if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg))
8399                 return -EBUSY;
8400
8401         total = to_ratio(period, runtime);
8402
8403         /*
8404          * Nobody can have more than the global setting allows.
8405          */
8406         if (total > to_ratio(global_rt_period(), global_rt_runtime()))
8407                 return -EINVAL;
8408
8409         /*
8410          * The sum of our children's runtime should not exceed our own.
8411          */
8412         list_for_each_entry_rcu(child, &tg->children, siblings) {
8413                 period = ktime_to_ns(child->rt_bandwidth.rt_period);
8414                 runtime = child->rt_bandwidth.rt_runtime;
8415
8416                 if (child == d->tg) {
8417                         period = d->rt_period;
8418                         runtime = d->rt_runtime;
8419                 }
8420
8421                 sum += to_ratio(period, runtime);
8422         }
8423
8424         if (sum > total)
8425                 return -EINVAL;
8426
8427         return 0;
8428 }
8429
8430 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8431 {
8432         struct rt_schedulable_data data = {
8433                 .tg = tg,
8434                 .rt_period = period,
8435                 .rt_runtime = runtime,
8436         };
8437
8438         return walk_tg_tree(tg_schedulable, tg_nop, &data);
8439 }
8440
8441 static int tg_set_bandwidth(struct task_group *tg,
8442                 u64 rt_period, u64 rt_runtime)
8443 {
8444         int i, err = 0;
8445
8446         mutex_lock(&rt_constraints_mutex);
8447         read_lock(&tasklist_lock);
8448         err = __rt_schedulable(tg, rt_period, rt_runtime);
8449         if (err)
8450                 goto unlock;
8451
8452         raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8453         tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8454         tg->rt_bandwidth.rt_runtime = rt_runtime;
8455
8456         for_each_possible_cpu(i) {
8457                 struct rt_rq *rt_rq = tg->rt_rq[i];
8458
8459                 raw_spin_lock(&rt_rq->rt_runtime_lock);
8460                 rt_rq->rt_runtime = rt_runtime;
8461                 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8462         }
8463         raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8464 unlock:
8465         read_unlock(&tasklist_lock);
8466         mutex_unlock(&rt_constraints_mutex);
8467
8468         return err;
8469 }
8470
8471 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8472 {
8473         u64 rt_runtime, rt_period;
8474
8475         rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8476         rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8477         if (rt_runtime_us < 0)
8478                 rt_runtime = RUNTIME_INF;
8479
8480         return tg_set_bandwidth(tg, rt_period, rt_runtime);
8481 }
8482
8483 long sched_group_rt_runtime(struct task_group *tg)
8484 {
8485         u64 rt_runtime_us;
8486
8487         if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8488                 return -1;
8489
8490         rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8491         do_div(rt_runtime_us, NSEC_PER_USEC);
8492         return rt_runtime_us;
8493 }
8494
8495 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
8496 {
8497         u64 rt_runtime, rt_period;
8498
8499         rt_period = (u64)rt_period_us * NSEC_PER_USEC;
8500         rt_runtime = tg->rt_bandwidth.rt_runtime;
8501
8502         if (rt_period == 0)
8503                 return -EINVAL;
8504
8505         return tg_set_bandwidth(tg, rt_period, rt_runtime);
8506 }
8507
8508 long sched_group_rt_period(struct task_group *tg)
8509 {
8510         u64 rt_period_us;
8511
8512         rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8513         do_div(rt_period_us, NSEC_PER_USEC);
8514         return rt_period_us;
8515 }
8516
8517 static int sched_rt_global_constraints(void)
8518 {
8519         u64 runtime, period;
8520         int ret = 0;
8521
8522         if (sysctl_sched_rt_period <= 0)
8523                 return -EINVAL;
8524
8525         runtime = global_rt_runtime();
8526         period = global_rt_period();
8527
8528         /*
8529          * Sanity check on the sysctl variables.
8530          */
8531         if (runtime > period && runtime != RUNTIME_INF)
8532                 return -EINVAL;
8533
8534         mutex_lock(&rt_constraints_mutex);
8535         read_lock(&tasklist_lock);
8536         ret = __rt_schedulable(NULL, 0, 0);
8537         read_unlock(&tasklist_lock);
8538         mutex_unlock(&rt_constraints_mutex);
8539
8540         return ret;
8541 }
8542
8543 int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk)
8544 {
8545         /* Don't accept realtime tasks when there is no way for them to run */
8546         if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0)
8547                 return 0;
8548
8549         return 1;
8550 }
8551
8552 #else /* !CONFIG_RT_GROUP_SCHED */
8553 static int sched_rt_global_constraints(void)
8554 {
8555         unsigned long flags;
8556         int i;
8557
8558         if (sysctl_sched_rt_period <= 0)
8559                 return -EINVAL;
8560
8561         /*
8562          * There's always some RT tasks in the root group
8563          * -- migration, kstopmachine etc..
8564          */
8565         if (sysctl_sched_rt_runtime == 0)
8566                 return -EBUSY;
8567
8568         raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
8569         for_each_possible_cpu(i) {
8570                 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
8571
8572                 raw_spin_lock(&rt_rq->rt_runtime_lock);
8573                 rt_rq->rt_runtime = global_rt_runtime();
8574                 raw_spin_unlock(&rt_rq->rt_runtime_lock);
8575         }
8576         raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
8577
8578         return 0;
8579 }
8580 #endif /* CONFIG_RT_GROUP_SCHED */
8581
8582 int sched_rt_handler(struct ctl_table *table, int write,
8583                 void __user *buffer, size_t *lenp,
8584                 loff_t *ppos)
8585 {
8586         int ret;
8587         int old_period, old_runtime;
8588         static DEFINE_MUTEX(mutex);
8589
8590         mutex_lock(&mutex);
8591         old_period = sysctl_sched_rt_period;
8592         old_runtime = sysctl_sched_rt_runtime;
8593
8594         ret = proc_dointvec(table, write, buffer, lenp, ppos);
8595
8596         if (!ret && write) {
8597                 ret = sched_rt_global_constraints();
8598                 if (ret) {
8599                         sysctl_sched_rt_period = old_period;
8600                         sysctl_sched_rt_runtime = old_runtime;
8601                 } else {
8602                         def_rt_bandwidth.rt_runtime = global_rt_runtime();
8603                         def_rt_bandwidth.rt_period =
8604                                 ns_to_ktime(global_rt_period());
8605                 }
8606         }
8607         mutex_unlock(&mutex);
8608
8609         return ret;
8610 }
8611
8612 #ifdef CONFIG_CGROUP_SCHED
8613
8614 /* return corresponding task_group object of a cgroup */
8615 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
8616 {
8617         return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
8618                             struct task_group, css);
8619 }
8620
8621 static struct cgroup_subsys_state *
8622 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
8623 {
8624         struct task_group *tg, *parent;
8625
8626         if (!cgrp->parent) {
8627                 /* This is early initialization for the top cgroup */
8628                 return &init_task_group.css;
8629         }
8630
8631         parent = cgroup_tg(cgrp->parent);
8632         tg = sched_create_group(parent);
8633         if (IS_ERR(tg))
8634                 return ERR_PTR(-ENOMEM);
8635
8636         return &tg->css;
8637 }
8638
8639 static void
8640 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
8641 {
8642         struct task_group *tg = cgroup_tg(cgrp);
8643
8644         sched_destroy_group(tg);
8645 }
8646
8647 static int
8648 cpu_cgroup_can_attach_task(struct cgroup *cgrp, struct task_struct *tsk)
8649 {
8650 #ifdef CONFIG_RT_GROUP_SCHED
8651         if (!sched_rt_can_attach(cgroup_tg(cgrp), tsk))
8652                 return -EINVAL;
8653 #else
8654         /* We don't support RT-tasks being in separate groups */
8655         if (tsk->sched_class != &fair_sched_class)
8656                 return -EINVAL;
8657 #endif
8658         return 0;
8659 }
8660
8661 static int
8662 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8663                       struct task_struct *tsk, bool threadgroup)
8664 {
8665         int retval = cpu_cgroup_can_attach_task(cgrp, tsk);
8666         if (retval)
8667                 return retval;
8668         if (threadgroup) {
8669                 struct task_struct *c;
8670                 rcu_read_lock();
8671                 list_for_each_entry_rcu(c, &tsk->thread_group, thread_group) {
8672                         retval = cpu_cgroup_can_attach_task(cgrp, c);
8673                         if (retval) {
8674                                 rcu_read_unlock();
8675                                 return retval;
8676                         }
8677                 }
8678                 rcu_read_unlock();
8679         }
8680         return 0;
8681 }
8682
8683 static void
8684 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8685                   struct cgroup *old_cont, struct task_struct *tsk,
8686                   bool threadgroup)
8687 {
8688         sched_move_task(tsk);
8689         if (threadgroup) {
8690                 struct task_struct *c;
8691                 rcu_read_lock();
8692                 list_for_each_entry_rcu(c, &tsk->thread_group, thread_group) {
8693                         sched_move_task(c);
8694                 }
8695                 rcu_read_unlock();
8696         }
8697 }
8698
8699 #ifdef CONFIG_FAIR_GROUP_SCHED
8700 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
8701                                 u64 shareval)
8702 {
8703         return sched_group_set_shares(cgroup_tg(cgrp), shareval);
8704 }
8705
8706 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
8707 {
8708         struct task_group *tg = cgroup_tg(cgrp);
8709
8710         return (u64) tg->shares;
8711 }
8712 #endif /* CONFIG_FAIR_GROUP_SCHED */
8713
8714 #ifdef CONFIG_RT_GROUP_SCHED
8715 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
8716                                 s64 val)
8717 {
8718         return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
8719 }
8720
8721 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
8722 {
8723         return sched_group_rt_runtime(cgroup_tg(cgrp));
8724 }
8725
8726 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
8727                 u64 rt_period_us)
8728 {
8729         return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
8730 }
8731
8732 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
8733 {
8734         return sched_group_rt_period(cgroup_tg(cgrp));
8735 }
8736 #endif /* CONFIG_RT_GROUP_SCHED */
8737
8738 static struct cftype cpu_files[] = {
8739 #ifdef CONFIG_FAIR_GROUP_SCHED
8740         {
8741                 .name = "shares",
8742                 .read_u64 = cpu_shares_read_u64,
8743                 .write_u64 = cpu_shares_write_u64,
8744         },
8745 #endif
8746 #ifdef CONFIG_RT_GROUP_SCHED
8747         {
8748                 .name = "rt_runtime_us",
8749                 .read_s64 = cpu_rt_runtime_read,
8750                 .write_s64 = cpu_rt_runtime_write,
8751         },
8752         {
8753                 .name = "rt_period_us",
8754                 .read_u64 = cpu_rt_period_read_uint,
8755                 .write_u64 = cpu_rt_period_write_uint,
8756         },
8757 #endif
8758 };
8759
8760 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
8761 {
8762         return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
8763 }
8764
8765 struct cgroup_subsys cpu_cgroup_subsys = {
8766         .name           = "cpu",
8767         .create         = cpu_cgroup_create,
8768         .destroy        = cpu_cgroup_destroy,
8769         .can_attach     = cpu_cgroup_can_attach,
8770         .attach         = cpu_cgroup_attach,
8771         .populate       = cpu_cgroup_populate,
8772         .subsys_id      = cpu_cgroup_subsys_id,
8773         .early_init     = 1,
8774 };
8775
8776 #endif  /* CONFIG_CGROUP_SCHED */
8777
8778 #ifdef CONFIG_CGROUP_CPUACCT
8779
8780 /*
8781  * CPU accounting code for task groups.
8782  *
8783  * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
8784  * (balbir@in.ibm.com).
8785  */
8786
8787 /* track cpu usage of a group of tasks and its child groups */
8788 struct cpuacct {
8789         struct cgroup_subsys_state css;
8790         /* cpuusage holds pointer to a u64-type object on every cpu */
8791         u64 __percpu *cpuusage;
8792         struct percpu_counter cpustat[CPUACCT_STAT_NSTATS];
8793         struct cpuacct *parent;
8794 };
8795
8796 struct cgroup_subsys cpuacct_subsys;
8797
8798 /* return cpu accounting group corresponding to this container */
8799 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
8800 {
8801         return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
8802                             struct cpuacct, css);
8803 }
8804
8805 /* return cpu accounting group to which this task belongs */
8806 static inline struct cpuacct *task_ca(struct task_struct *tsk)
8807 {
8808         return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
8809                             struct cpuacct, css);
8810 }
8811
8812 /* create a new cpu accounting group */
8813 static struct cgroup_subsys_state *cpuacct_create(
8814         struct cgroup_subsys *ss, struct cgroup *cgrp)
8815 {
8816         struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
8817         int i;
8818
8819         if (!ca)
8820                 goto out;
8821
8822         ca->cpuusage = alloc_percpu(u64);
8823         if (!ca->cpuusage)
8824                 goto out_free_ca;
8825
8826         for (i = 0; i < CPUACCT_STAT_NSTATS; i++)
8827                 if (percpu_counter_init(&ca->cpustat[i], 0))
8828                         goto out_free_counters;
8829
8830         if (cgrp->parent)
8831                 ca->parent = cgroup_ca(cgrp->parent);
8832
8833         return &ca->css;
8834
8835 out_free_counters:
8836         while (--i >= 0)
8837                 percpu_counter_destroy(&ca->cpustat[i]);
8838         free_percpu(ca->cpuusage);
8839 out_free_ca:
8840         kfree(ca);
8841 out:
8842         return ERR_PTR(-ENOMEM);
8843 }
8844
8845 /* destroy an existing cpu accounting group */
8846 static void
8847 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
8848 {
8849         struct cpuacct *ca = cgroup_ca(cgrp);
8850         int i;
8851
8852         for (i = 0; i < CPUACCT_STAT_NSTATS; i++)
8853                 percpu_counter_destroy(&ca->cpustat[i]);
8854         free_percpu(ca->cpuusage);
8855         kfree(ca);
8856 }
8857
8858 static u64 cpuacct_cpuusage_read(struct cpuacct *ca, int cpu)
8859 {
8860         u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
8861         u64 data;
8862
8863 #ifndef CONFIG_64BIT
8864         /*
8865          * Take rq->lock to make 64-bit read safe on 32-bit platforms.
8866          */
8867         raw_spin_lock_irq(&cpu_rq(cpu)->lock);
8868         data = *cpuusage;
8869         raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
8870 #else
8871         data = *cpuusage;
8872 #endif
8873
8874         return data;
8875 }
8876
8877 static void cpuacct_cpuusage_write(struct cpuacct *ca, int cpu, u64 val)
8878 {
8879         u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
8880
8881 #ifndef CONFIG_64BIT
8882         /*
8883          * Take rq->lock to make 64-bit write safe on 32-bit platforms.
8884          */
8885         raw_spin_lock_irq(&cpu_rq(cpu)->lock);
8886         *cpuusage = val;
8887         raw_spin_unlock_irq(&cpu_rq(cpu)->lock);
8888 #else
8889         *cpuusage = val;
8890 #endif
8891 }
8892
8893 /* return total cpu usage (in nanoseconds) of a group */
8894 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
8895 {
8896         struct cpuacct *ca = cgroup_ca(cgrp);
8897         u64 totalcpuusage = 0;
8898         int i;
8899
8900         for_each_present_cpu(i)
8901                 totalcpuusage += cpuacct_cpuusage_read(ca, i);
8902
8903         return totalcpuusage;
8904 }
8905
8906 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
8907                                                                 u64 reset)
8908 {
8909         struct cpuacct *ca = cgroup_ca(cgrp);
8910         int err = 0;
8911         int i;
8912
8913         if (reset) {
8914                 err = -EINVAL;
8915                 goto out;
8916         }
8917
8918         for_each_present_cpu(i)
8919                 cpuacct_cpuusage_write(ca, i, 0);
8920
8921 out:
8922         return err;
8923 }
8924
8925 static int cpuacct_percpu_seq_read(struct cgroup *cgroup, struct cftype *cft,
8926                                    struct seq_file *m)
8927 {
8928         struct cpuacct *ca = cgroup_ca(cgroup);
8929         u64 percpu;
8930         int i;
8931
8932         for_each_present_cpu(i) {
8933                 percpu = cpuacct_cpuusage_read(ca, i);
8934                 seq_printf(m, "%llu ", (unsigned long long) percpu);
8935         }
8936         seq_printf(m, "\n");
8937         return 0;
8938 }
8939
8940 static const char *cpuacct_stat_desc[] = {
8941         [CPUACCT_STAT_USER] = "user",
8942         [CPUACCT_STAT_SYSTEM] = "system",
8943 };
8944
8945 static int cpuacct_stats_show(struct cgroup *cgrp, struct cftype *cft,
8946                 struct cgroup_map_cb *cb)
8947 {
8948         struct cpuacct *ca = cgroup_ca(cgrp);
8949         int i;
8950
8951         for (i = 0; i < CPUACCT_STAT_NSTATS; i++) {
8952                 s64 val = percpu_counter_read(&ca->cpustat[i]);
8953                 val = cputime64_to_clock_t(val);
8954                 cb->fill(cb, cpuacct_stat_desc[i], val);
8955         }
8956         return 0;
8957 }
8958
8959 static struct cftype files[] = {
8960         {
8961                 .name = "usage",
8962                 .read_u64 = cpuusage_read,
8963                 .write_u64 = cpuusage_write,
8964         },
8965         {
8966                 .name = "usage_percpu",
8967                 .read_seq_string = cpuacct_percpu_seq_read,
8968         },
8969         {
8970                 .name = "stat",
8971                 .read_map = cpuacct_stats_show,
8972         },
8973 };
8974
8975 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
8976 {
8977         return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
8978 }
8979
8980 /*
8981  * charge this task's execution time to its accounting group.
8982  *
8983  * called with rq->lock held.
8984  */
8985 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
8986 {
8987         struct cpuacct *ca;
8988         int cpu;
8989
8990         if (unlikely(!cpuacct_subsys.active))
8991                 return;
8992
8993         cpu = task_cpu(tsk);
8994
8995         rcu_read_lock();
8996
8997         ca = task_ca(tsk);
8998
8999         for (; ca; ca = ca->parent) {
9000                 u64 *cpuusage = per_cpu_ptr(ca->cpuusage, cpu);
9001                 *cpuusage += cputime;
9002         }
9003
9004         rcu_read_unlock();
9005 }
9006
9007 /*
9008  * When CONFIG_VIRT_CPU_ACCOUNTING is enabled one jiffy can be very large
9009  * in cputime_t units. As a result, cpuacct_update_stats calls
9010  * percpu_counter_add with values large enough to always overflow the
9011  * per cpu batch limit causing bad SMP scalability.
9012  *
9013  * To fix this we scale percpu_counter_batch by cputime_one_jiffy so we
9014  * batch the same amount of time with CONFIG_VIRT_CPU_ACCOUNTING disabled
9015  * and enabled. We cap it at INT_MAX which is the largest allowed batch value.
9016  */
9017 #ifdef CONFIG_SMP
9018 #define CPUACCT_BATCH   \
9019         min_t(long, percpu_counter_batch * cputime_one_jiffy, INT_MAX)
9020 #else
9021 #define CPUACCT_BATCH   0
9022 #endif
9023
9024 /*
9025  * Charge the system/user time to the task's accounting group.
9026  */
9027 static void cpuacct_update_stats(struct task_struct *tsk,
9028                 enum cpuacct_stat_index idx, cputime_t val)
9029 {
9030         struct cpuacct *ca;
9031         int batch = CPUACCT_BATCH;
9032
9033         if (unlikely(!cpuacct_subsys.active))
9034                 return;
9035
9036         rcu_read_lock();
9037         ca = task_ca(tsk);
9038
9039         do {
9040                 __percpu_counter_add(&ca->cpustat[idx], val, batch);
9041                 ca = ca->parent;
9042         } while (ca);
9043         rcu_read_unlock();
9044 }
9045
9046 struct cgroup_subsys cpuacct_subsys = {
9047         .name = "cpuacct",
9048         .create = cpuacct_create,
9049         .destroy = cpuacct_destroy,
9050         .populate = cpuacct_populate,
9051         .subsys_id = cpuacct_subsys_id,
9052 };
9053 #endif  /* CONFIG_CGROUP_CPUACCT */
9054
9055 #ifndef CONFIG_SMP
9056
9057 void synchronize_sched_expedited(void)
9058 {
9059         barrier();
9060 }
9061 EXPORT_SYMBOL_GPL(synchronize_sched_expedited);
9062
9063 #else /* #ifndef CONFIG_SMP */
9064
9065 static atomic_t synchronize_sched_expedited_count = ATOMIC_INIT(0);
9066
9067 static int synchronize_sched_expedited_cpu_stop(void *data)
9068 {
9069         /*
9070          * There must be a full memory barrier on each affected CPU
9071          * between the time that try_stop_cpus() is called and the
9072          * time that it returns.
9073          *
9074          * In the current initial implementation of cpu_stop, the
9075          * above condition is already met when the control reaches
9076          * this point and the following smp_mb() is not strictly
9077          * necessary.  Do smp_mb() anyway for documentation and
9078          * robustness against future implementation changes.
9079          */
9080         smp_mb(); /* See above comment block. */
9081         return 0;
9082 }
9083
9084 /*
9085  * Wait for an rcu-sched grace period to elapse, but use "big hammer"
9086  * approach to force grace period to end quickly.  This consumes
9087  * significant time on all CPUs, and is thus not recommended for
9088  * any sort of common-case code.
9089  *
9090  * Note that it is illegal to call this function while holding any
9091  * lock that is acquired by a CPU-hotplug notifier.  Failing to
9092  * observe this restriction will result in deadlock.
9093  */
9094 void synchronize_sched_expedited(void)
9095 {
9096         int snap, trycount = 0;
9097
9098         smp_mb();  /* ensure prior mod happens before capturing snap. */
9099         snap = atomic_read(&synchronize_sched_expedited_count) + 1;
9100         get_online_cpus();
9101         while (try_stop_cpus(cpu_online_mask,
9102                              synchronize_sched_expedited_cpu_stop,
9103                              NULL) == -EAGAIN) {
9104                 put_online_cpus();
9105                 if (trycount++ < 10)
9106                         udelay(trycount * num_online_cpus());
9107                 else {
9108                         synchronize_sched();
9109                         return;
9110                 }
9111                 if (atomic_read(&synchronize_sched_expedited_count) - snap > 0) {
9112                         smp_mb(); /* ensure test happens before caller kfree */
9113                         return;
9114                 }
9115                 get_online_cpus();
9116         }
9117         atomic_inc(&synchronize_sched_expedited_count);
9118         smp_mb__after_atomic_inc(); /* ensure post-GP actions seen after GP. */
9119         put_online_cpus();
9120 }
9121 EXPORT_SYMBOL_GPL(synchronize_sched_expedited);
9122
9123 #endif /* #else #ifndef CONFIG_SMP */