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