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