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