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