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