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