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