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