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