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