OSDN Git Service

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