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