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