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