]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - kernel/sched.c
7178b8c2351ce5f12289bfe858f52f636fd493a9
[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;
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         hrtick_clear(rq);
4153
4154         /*
4155          * Do the rq-clock update outside the rq lock:
4156          */
4157         local_irq_disable();
4158         update_rq_clock(rq);
4159         spin_lock(&rq->lock);
4160         clear_tsk_need_resched(prev);
4161
4162         if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
4163                 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
4164                                 signal_pending(prev))) {
4165                         prev->state = TASK_RUNNING;
4166                 } else {
4167                         deactivate_task(rq, prev, 1);
4168                 }
4169                 switch_count = &prev->nvcsw;
4170         }
4171
4172 #ifdef CONFIG_SMP
4173         if (prev->sched_class->pre_schedule)
4174                 prev->sched_class->pre_schedule(rq, prev);
4175 #endif
4176
4177         if (unlikely(!rq->nr_running))
4178                 idle_balance(cpu, rq);
4179
4180         prev->sched_class->put_prev_task(rq, prev);
4181         next = pick_next_task(rq, prev);
4182
4183         if (likely(prev != next)) {
4184                 sched_info_switch(prev, next);
4185
4186                 rq->nr_switches++;
4187                 rq->curr = next;
4188                 ++*switch_count;
4189
4190                 context_switch(rq, prev, next); /* unlocks the rq */
4191                 /*
4192                  * the context switch might have flipped the stack from under
4193                  * us, hence refresh the local variables.
4194                  */
4195                 cpu = smp_processor_id();
4196                 rq = cpu_rq(cpu);
4197         } else
4198                 spin_unlock_irq(&rq->lock);
4199
4200         hrtick_set(rq);
4201
4202         if (unlikely(reacquire_kernel_lock(current) < 0))
4203                 goto need_resched_nonpreemptible;
4204
4205         preempt_enable_no_resched();
4206         if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
4207                 goto need_resched;
4208 }
4209 EXPORT_SYMBOL(schedule);
4210
4211 #ifdef CONFIG_PREEMPT
4212 /*
4213  * this is the entry point to schedule() from in-kernel preemption
4214  * off of preempt_enable. Kernel preemptions off return from interrupt
4215  * occur there and call schedule directly.
4216  */
4217 asmlinkage void __sched preempt_schedule(void)
4218 {
4219         struct thread_info *ti = current_thread_info();
4220
4221         /*
4222          * If there is a non-zero preempt_count or interrupts are disabled,
4223          * we do not want to preempt the current task. Just return..
4224          */
4225         if (likely(ti->preempt_count || irqs_disabled()))
4226                 return;
4227
4228         do {
4229                 add_preempt_count(PREEMPT_ACTIVE);
4230                 schedule();
4231                 sub_preempt_count(PREEMPT_ACTIVE);
4232
4233                 /*
4234                  * Check again in case we missed a preemption opportunity
4235                  * between schedule and now.
4236                  */
4237                 barrier();
4238         } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4239 }
4240 EXPORT_SYMBOL(preempt_schedule);
4241
4242 /*
4243  * this is the entry point to schedule() from kernel preemption
4244  * off of irq context.
4245  * Note, that this is called and return with irqs disabled. This will
4246  * protect us against recursive calling from irq.
4247  */
4248 asmlinkage void __sched preempt_schedule_irq(void)
4249 {
4250         struct thread_info *ti = current_thread_info();
4251
4252         /* Catch callers which need to be fixed */
4253         BUG_ON(ti->preempt_count || !irqs_disabled());
4254
4255         do {
4256                 add_preempt_count(PREEMPT_ACTIVE);
4257                 local_irq_enable();
4258                 schedule();
4259                 local_irq_disable();
4260                 sub_preempt_count(PREEMPT_ACTIVE);
4261
4262                 /*
4263                  * Check again in case we missed a preemption opportunity
4264                  * between schedule and now.
4265                  */
4266                 barrier();
4267         } while (unlikely(test_thread_flag(TIF_NEED_RESCHED)));
4268 }
4269
4270 #endif /* CONFIG_PREEMPT */
4271
4272 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
4273                           void *key)
4274 {
4275         return try_to_wake_up(curr->private, mode, sync);
4276 }
4277 EXPORT_SYMBOL(default_wake_function);
4278
4279 /*
4280  * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
4281  * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
4282  * number) then we wake all the non-exclusive tasks and one exclusive task.
4283  *
4284  * There are circumstances in which we can try to wake a task which has already
4285  * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
4286  * zero in this (rare) case, and we handle it by continuing to scan the queue.
4287  */
4288 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
4289                              int nr_exclusive, int sync, void *key)
4290 {
4291         wait_queue_t *curr, *next;
4292
4293         list_for_each_entry_safe(curr, next, &q->task_list, task_list) {
4294                 unsigned flags = curr->flags;
4295
4296                 if (curr->func(curr, mode, sync, key) &&
4297                                 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
4298                         break;
4299         }
4300 }
4301
4302 /**
4303  * __wake_up - wake up threads blocked on a waitqueue.
4304  * @q: the waitqueue
4305  * @mode: which threads
4306  * @nr_exclusive: how many wake-one or wake-many threads to wake up
4307  * @key: is directly passed to the wakeup function
4308  */
4309 void __wake_up(wait_queue_head_t *q, unsigned int mode,
4310                         int nr_exclusive, void *key)
4311 {
4312         unsigned long flags;
4313
4314         spin_lock_irqsave(&q->lock, flags);
4315         __wake_up_common(q, mode, nr_exclusive, 0, key);
4316         spin_unlock_irqrestore(&q->lock, flags);
4317 }
4318 EXPORT_SYMBOL(__wake_up);
4319
4320 /*
4321  * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
4322  */
4323 void __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
4324 {
4325         __wake_up_common(q, mode, 1, 0, NULL);
4326 }
4327
4328 /**
4329  * __wake_up_sync - wake up threads blocked on a waitqueue.
4330  * @q: the waitqueue
4331  * @mode: which threads
4332  * @nr_exclusive: how many wake-one or wake-many threads to wake up
4333  *
4334  * The sync wakeup differs that the waker knows that it will schedule
4335  * away soon, so while the target thread will be woken up, it will not
4336  * be migrated to another CPU - ie. the two threads are 'synchronized'
4337  * with each other. This can prevent needless bouncing between CPUs.
4338  *
4339  * On UP it can prevent extra preemption.
4340  */
4341 void
4342 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
4343 {
4344         unsigned long flags;
4345         int sync = 1;
4346
4347         if (unlikely(!q))
4348                 return;
4349
4350         if (unlikely(!nr_exclusive))
4351                 sync = 0;
4352
4353         spin_lock_irqsave(&q->lock, flags);
4354         __wake_up_common(q, mode, nr_exclusive, sync, NULL);
4355         spin_unlock_irqrestore(&q->lock, flags);
4356 }
4357 EXPORT_SYMBOL_GPL(__wake_up_sync);      /* For internal use only */
4358
4359 void complete(struct completion *x)
4360 {
4361         unsigned long flags;
4362
4363         spin_lock_irqsave(&x->wait.lock, flags);
4364         x->done++;
4365         __wake_up_common(&x->wait, TASK_NORMAL, 1, 0, NULL);
4366         spin_unlock_irqrestore(&x->wait.lock, flags);
4367 }
4368 EXPORT_SYMBOL(complete);
4369
4370 void complete_all(struct completion *x)
4371 {
4372         unsigned long flags;
4373
4374         spin_lock_irqsave(&x->wait.lock, flags);
4375         x->done += UINT_MAX/2;
4376         __wake_up_common(&x->wait, TASK_NORMAL, 0, 0, NULL);
4377         spin_unlock_irqrestore(&x->wait.lock, flags);
4378 }
4379 EXPORT_SYMBOL(complete_all);
4380
4381 static inline long __sched
4382 do_wait_for_common(struct completion *x, long timeout, int state)
4383 {
4384         if (!x->done) {
4385                 DECLARE_WAITQUEUE(wait, current);
4386
4387                 wait.flags |= WQ_FLAG_EXCLUSIVE;
4388                 __add_wait_queue_tail(&x->wait, &wait);
4389                 do {
4390                         if ((state == TASK_INTERRUPTIBLE &&
4391                              signal_pending(current)) ||
4392                             (state == TASK_KILLABLE &&
4393                              fatal_signal_pending(current))) {
4394                                 __remove_wait_queue(&x->wait, &wait);
4395                                 return -ERESTARTSYS;
4396                         }
4397                         __set_current_state(state);
4398                         spin_unlock_irq(&x->wait.lock);
4399                         timeout = schedule_timeout(timeout);
4400                         spin_lock_irq(&x->wait.lock);
4401                         if (!timeout) {
4402                                 __remove_wait_queue(&x->wait, &wait);
4403                                 return timeout;
4404                         }
4405                 } while (!x->done);
4406                 __remove_wait_queue(&x->wait, &wait);
4407         }
4408         x->done--;
4409         return timeout;
4410 }
4411
4412 static long __sched
4413 wait_for_common(struct completion *x, long timeout, int state)
4414 {
4415         might_sleep();
4416
4417         spin_lock_irq(&x->wait.lock);
4418         timeout = do_wait_for_common(x, timeout, state);
4419         spin_unlock_irq(&x->wait.lock);
4420         return timeout;
4421 }
4422
4423 void __sched wait_for_completion(struct completion *x)
4424 {
4425         wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_UNINTERRUPTIBLE);
4426 }
4427 EXPORT_SYMBOL(wait_for_completion);
4428
4429 unsigned long __sched
4430 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
4431 {
4432         return wait_for_common(x, timeout, TASK_UNINTERRUPTIBLE);
4433 }
4434 EXPORT_SYMBOL(wait_for_completion_timeout);
4435
4436 int __sched wait_for_completion_interruptible(struct completion *x)
4437 {
4438         long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_INTERRUPTIBLE);
4439         if (t == -ERESTARTSYS)
4440                 return t;
4441         return 0;
4442 }
4443 EXPORT_SYMBOL(wait_for_completion_interruptible);
4444
4445 unsigned long __sched
4446 wait_for_completion_interruptible_timeout(struct completion *x,
4447                                           unsigned long timeout)
4448 {
4449         return wait_for_common(x, timeout, TASK_INTERRUPTIBLE);
4450 }
4451 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
4452
4453 int __sched wait_for_completion_killable(struct completion *x)
4454 {
4455         long t = wait_for_common(x, MAX_SCHEDULE_TIMEOUT, TASK_KILLABLE);
4456         if (t == -ERESTARTSYS)
4457                 return t;
4458         return 0;
4459 }
4460 EXPORT_SYMBOL(wait_for_completion_killable);
4461
4462 static long __sched
4463 sleep_on_common(wait_queue_head_t *q, int state, long timeout)
4464 {
4465         unsigned long flags;
4466         wait_queue_t wait;
4467
4468         init_waitqueue_entry(&wait, current);
4469
4470         __set_current_state(state);
4471
4472         spin_lock_irqsave(&q->lock, flags);
4473         __add_wait_queue(q, &wait);
4474         spin_unlock(&q->lock);
4475         timeout = schedule_timeout(timeout);
4476         spin_lock_irq(&q->lock);
4477         __remove_wait_queue(q, &wait);
4478         spin_unlock_irqrestore(&q->lock, flags);
4479
4480         return timeout;
4481 }
4482
4483 void __sched interruptible_sleep_on(wait_queue_head_t *q)
4484 {
4485         sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4486 }
4487 EXPORT_SYMBOL(interruptible_sleep_on);
4488
4489 long __sched
4490 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4491 {
4492         return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout);
4493 }
4494 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4495
4496 void __sched sleep_on(wait_queue_head_t *q)
4497 {
4498         sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT);
4499 }
4500 EXPORT_SYMBOL(sleep_on);
4501
4502 long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4503 {
4504         return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout);
4505 }
4506 EXPORT_SYMBOL(sleep_on_timeout);
4507
4508 #ifdef CONFIG_RT_MUTEXES
4509
4510 /*
4511  * rt_mutex_setprio - set the current priority of a task
4512  * @p: task
4513  * @prio: prio value (kernel-internal form)
4514  *
4515  * This function changes the 'effective' priority of a task. It does
4516  * not touch ->normal_prio like __setscheduler().
4517  *
4518  * Used by the rt_mutex code to implement priority inheritance logic.
4519  */
4520 void rt_mutex_setprio(struct task_struct *p, int prio)
4521 {
4522         unsigned long flags;
4523         int oldprio, on_rq, running;
4524         struct rq *rq;
4525         const struct sched_class *prev_class = p->sched_class;
4526
4527         BUG_ON(prio < 0 || prio > MAX_PRIO);
4528
4529         rq = task_rq_lock(p, &flags);
4530         update_rq_clock(rq);
4531
4532         oldprio = p->prio;
4533         on_rq = p->se.on_rq;
4534         running = task_current(rq, p);
4535         if (on_rq)
4536                 dequeue_task(rq, p, 0);
4537         if (running)
4538                 p->sched_class->put_prev_task(rq, p);
4539
4540         if (rt_prio(prio))
4541                 p->sched_class = &rt_sched_class;
4542         else
4543                 p->sched_class = &fair_sched_class;
4544
4545         p->prio = prio;
4546
4547         if (running)
4548                 p->sched_class->set_curr_task(rq);
4549         if (on_rq) {
4550                 enqueue_task(rq, p, 0);
4551
4552                 check_class_changed(rq, p, prev_class, oldprio, running);
4553         }
4554         task_rq_unlock(rq, &flags);
4555 }
4556
4557 #endif
4558
4559 void set_user_nice(struct task_struct *p, long nice)
4560 {
4561         int old_prio, delta, on_rq;
4562         unsigned long flags;
4563         struct rq *rq;
4564
4565         if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4566                 return;
4567         /*
4568          * We have to be careful, if called from sys_setpriority(),
4569          * the task might be in the middle of scheduling on another CPU.
4570          */
4571         rq = task_rq_lock(p, &flags);
4572         update_rq_clock(rq);
4573         /*
4574          * The RT priorities are set via sched_setscheduler(), but we still
4575          * allow the 'normal' nice value to be set - but as expected
4576          * it wont have any effect on scheduling until the task is
4577          * SCHED_FIFO/SCHED_RR:
4578          */
4579         if (task_has_rt_policy(p)) {
4580                 p->static_prio = NICE_TO_PRIO(nice);
4581                 goto out_unlock;
4582         }
4583         on_rq = p->se.on_rq;
4584         if (on_rq) {
4585                 dequeue_task(rq, p, 0);
4586                 dec_load(rq, p);
4587         }
4588
4589         p->static_prio = NICE_TO_PRIO(nice);
4590         set_load_weight(p);
4591         old_prio = p->prio;
4592         p->prio = effective_prio(p);
4593         delta = p->prio - old_prio;
4594
4595         if (on_rq) {
4596                 enqueue_task(rq, p, 0);
4597                 inc_load(rq, p);
4598                 /*
4599                  * If the task increased its priority or is running and
4600                  * lowered its priority, then reschedule its CPU:
4601                  */
4602                 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4603                         resched_task(rq->curr);
4604         }
4605 out_unlock:
4606         task_rq_unlock(rq, &flags);
4607 }
4608 EXPORT_SYMBOL(set_user_nice);
4609
4610 /*
4611  * can_nice - check if a task can reduce its nice value
4612  * @p: task
4613  * @nice: nice value
4614  */
4615 int can_nice(const struct task_struct *p, const int nice)
4616 {
4617         /* convert nice value [19,-20] to rlimit style value [1,40] */
4618         int nice_rlim = 20 - nice;
4619
4620         return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
4621                 capable(CAP_SYS_NICE));
4622 }
4623
4624 #ifdef __ARCH_WANT_SYS_NICE
4625
4626 /*
4627  * sys_nice - change the priority of the current process.
4628  * @increment: priority increment
4629  *
4630  * sys_setpriority is a more generic, but much slower function that
4631  * does similar things.
4632  */
4633 asmlinkage long sys_nice(int increment)
4634 {
4635         long nice, retval;
4636
4637         /*
4638          * Setpriority might change our priority at the same moment.
4639          * We don't have to worry. Conceptually one call occurs first
4640          * and we have a single winner.
4641          */
4642         if (increment < -40)
4643                 increment = -40;
4644         if (increment > 40)
4645                 increment = 40;
4646
4647         nice = PRIO_TO_NICE(current->static_prio) + increment;
4648         if (nice < -20)
4649                 nice = -20;
4650         if (nice > 19)
4651                 nice = 19;
4652
4653         if (increment < 0 && !can_nice(current, nice))
4654                 return -EPERM;
4655
4656         retval = security_task_setnice(current, nice);
4657         if (retval)
4658                 return retval;
4659
4660         set_user_nice(current, nice);
4661         return 0;
4662 }
4663
4664 #endif
4665
4666 /**
4667  * task_prio - return the priority value of a given task.
4668  * @p: the task in question.
4669  *
4670  * This is the priority value as seen by users in /proc.
4671  * RT tasks are offset by -200. Normal tasks are centered
4672  * around 0, value goes from -16 to +15.
4673  */
4674 int task_prio(const struct task_struct *p)
4675 {
4676         return p->prio - MAX_RT_PRIO;
4677 }
4678
4679 /**
4680  * task_nice - return the nice value of a given task.
4681  * @p: the task in question.
4682  */
4683 int task_nice(const struct task_struct *p)
4684 {
4685         return TASK_NICE(p);
4686 }
4687 EXPORT_SYMBOL(task_nice);
4688
4689 /**
4690  * idle_cpu - is a given cpu idle currently?
4691  * @cpu: the processor in question.
4692  */
4693 int idle_cpu(int cpu)
4694 {
4695         return cpu_curr(cpu) == cpu_rq(cpu)->idle;
4696 }
4697
4698 /**
4699  * idle_task - return the idle task for a given cpu.
4700  * @cpu: the processor in question.
4701  */
4702 struct task_struct *idle_task(int cpu)
4703 {
4704         return cpu_rq(cpu)->idle;
4705 }
4706
4707 /**
4708  * find_process_by_pid - find a process with a matching PID value.
4709  * @pid: the pid in question.
4710  */
4711 static struct task_struct *find_process_by_pid(pid_t pid)
4712 {
4713         return pid ? find_task_by_vpid(pid) : current;
4714 }
4715
4716 /* Actually do priority change: must hold rq lock. */
4717 static void
4718 __setscheduler(struct rq *rq, struct task_struct *p, int policy, int prio)
4719 {
4720         BUG_ON(p->se.on_rq);
4721
4722         p->policy = policy;
4723         switch (p->policy) {
4724         case SCHED_NORMAL:
4725         case SCHED_BATCH:
4726         case SCHED_IDLE:
4727                 p->sched_class = &fair_sched_class;
4728                 break;
4729         case SCHED_FIFO:
4730         case SCHED_RR:
4731                 p->sched_class = &rt_sched_class;
4732                 break;
4733         }
4734
4735         p->rt_priority = prio;
4736         p->normal_prio = normal_prio(p);
4737         /* we are holding p->pi_lock already */
4738         p->prio = rt_mutex_getprio(p);
4739         set_load_weight(p);
4740 }
4741
4742 /**
4743  * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4744  * @p: the task in question.
4745  * @policy: new policy.
4746  * @param: structure containing the new RT priority.
4747  *
4748  * NOTE that the task may be already dead.
4749  */
4750 int sched_setscheduler(struct task_struct *p, int policy,
4751                        struct sched_param *param)
4752 {
4753         int retval, oldprio, oldpolicy = -1, on_rq, running;
4754         unsigned long flags;
4755         const struct sched_class *prev_class = p->sched_class;
4756         struct rq *rq;
4757
4758         /* may grab non-irq protected spin_locks */
4759         BUG_ON(in_interrupt());
4760 recheck:
4761         /* double check policy once rq lock held */
4762         if (policy < 0)
4763                 policy = oldpolicy = p->policy;
4764         else if (policy != SCHED_FIFO && policy != SCHED_RR &&
4765                         policy != SCHED_NORMAL && policy != SCHED_BATCH &&
4766                         policy != SCHED_IDLE)
4767                 return -EINVAL;
4768         /*
4769          * Valid priorities for SCHED_FIFO and SCHED_RR are
4770          * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4771          * SCHED_BATCH and SCHED_IDLE is 0.
4772          */
4773         if (param->sched_priority < 0 ||
4774             (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
4775             (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
4776                 return -EINVAL;
4777         if (rt_policy(policy) != (param->sched_priority != 0))
4778                 return -EINVAL;
4779
4780         /*
4781          * Allow unprivileged RT tasks to decrease priority:
4782          */
4783         if (!capable(CAP_SYS_NICE)) {
4784                 if (rt_policy(policy)) {
4785                         unsigned long rlim_rtprio;
4786
4787                         if (!lock_task_sighand(p, &flags))
4788                                 return -ESRCH;
4789                         rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
4790                         unlock_task_sighand(p, &flags);
4791
4792                         /* can't set/change the rt policy */
4793                         if (policy != p->policy && !rlim_rtprio)
4794                                 return -EPERM;
4795
4796                         /* can't increase priority */
4797                         if (param->sched_priority > p->rt_priority &&
4798                             param->sched_priority > rlim_rtprio)
4799                                 return -EPERM;
4800                 }
4801                 /*
4802                  * Like positive nice levels, dont allow tasks to
4803                  * move out of SCHED_IDLE either:
4804                  */
4805                 if (p->policy == SCHED_IDLE && policy != SCHED_IDLE)
4806                         return -EPERM;
4807
4808                 /* can't change other user's priorities */
4809                 if ((current->euid != p->euid) &&
4810                     (current->euid != p->uid))
4811                         return -EPERM;
4812         }
4813
4814 #ifdef CONFIG_RT_GROUP_SCHED
4815         /*
4816          * Do not allow realtime tasks into groups that have no runtime
4817          * assigned.
4818          */
4819         if (rt_policy(policy) && task_group(p)->rt_bandwidth.rt_runtime == 0)
4820                 return -EPERM;
4821 #endif
4822
4823         retval = security_task_setscheduler(p, policy, param);
4824         if (retval)
4825                 return retval;
4826         /*
4827          * make sure no PI-waiters arrive (or leave) while we are
4828          * changing the priority of the task:
4829          */
4830         spin_lock_irqsave(&p->pi_lock, flags);
4831         /*
4832          * To be able to change p->policy safely, the apropriate
4833          * runqueue lock must be held.
4834          */
4835         rq = __task_rq_lock(p);
4836         /* recheck policy now with rq lock held */
4837         if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4838                 policy = oldpolicy = -1;
4839                 __task_rq_unlock(rq);
4840                 spin_unlock_irqrestore(&p->pi_lock, flags);
4841                 goto recheck;
4842         }
4843         update_rq_clock(rq);
4844         on_rq = p->se.on_rq;
4845         running = task_current(rq, p);
4846         if (on_rq)
4847                 deactivate_task(rq, p, 0);
4848         if (running)
4849                 p->sched_class->put_prev_task(rq, p);
4850
4851         oldprio = p->prio;
4852         __setscheduler(rq, p, policy, param->sched_priority);
4853
4854         if (running)
4855                 p->sched_class->set_curr_task(rq);
4856         if (on_rq) {
4857                 activate_task(rq, p, 0);
4858
4859                 check_class_changed(rq, p, prev_class, oldprio, running);
4860         }
4861         __task_rq_unlock(rq);
4862         spin_unlock_irqrestore(&p->pi_lock, flags);
4863
4864         rt_mutex_adjust_pi(p);
4865
4866         return 0;
4867 }
4868 EXPORT_SYMBOL_GPL(sched_setscheduler);
4869
4870 static int
4871 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4872 {
4873         struct sched_param lparam;
4874         struct task_struct *p;
4875         int retval;
4876
4877         if (!param || pid < 0)
4878                 return -EINVAL;
4879         if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4880                 return -EFAULT;
4881
4882         rcu_read_lock();
4883         retval = -ESRCH;
4884         p = find_process_by_pid(pid);
4885         if (p != NULL)
4886                 retval = sched_setscheduler(p, policy, &lparam);
4887         rcu_read_unlock();
4888
4889         return retval;
4890 }
4891
4892 /**
4893  * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4894  * @pid: the pid in question.
4895  * @policy: new policy.
4896  * @param: structure containing the new RT priority.
4897  */
4898 asmlinkage long
4899 sys_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4900 {
4901         /* negative values for policy are not valid */
4902         if (policy < 0)
4903                 return -EINVAL;
4904
4905         return do_sched_setscheduler(pid, policy, param);
4906 }
4907
4908 /**
4909  * sys_sched_setparam - set/change the RT priority of a thread
4910  * @pid: the pid in question.
4911  * @param: structure containing the new RT priority.
4912  */
4913 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
4914 {
4915         return do_sched_setscheduler(pid, -1, param);
4916 }
4917
4918 /**
4919  * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4920  * @pid: the pid in question.
4921  */
4922 asmlinkage long sys_sched_getscheduler(pid_t pid)
4923 {
4924         struct task_struct *p;
4925         int retval;
4926
4927         if (pid < 0)
4928                 return -EINVAL;
4929
4930         retval = -ESRCH;
4931         read_lock(&tasklist_lock);
4932         p = find_process_by_pid(pid);
4933         if (p) {
4934                 retval = security_task_getscheduler(p);
4935                 if (!retval)
4936                         retval = p->policy;
4937         }
4938         read_unlock(&tasklist_lock);
4939         return retval;
4940 }
4941
4942 /**
4943  * sys_sched_getscheduler - get the RT priority of a thread
4944  * @pid: the pid in question.
4945  * @param: structure containing the RT priority.
4946  */
4947 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
4948 {
4949         struct sched_param lp;
4950         struct task_struct *p;
4951         int retval;
4952
4953         if (!param || pid < 0)
4954                 return -EINVAL;
4955
4956         read_lock(&tasklist_lock);
4957         p = find_process_by_pid(pid);
4958         retval = -ESRCH;
4959         if (!p)
4960                 goto out_unlock;
4961
4962         retval = security_task_getscheduler(p);
4963         if (retval)
4964                 goto out_unlock;
4965
4966         lp.sched_priority = p->rt_priority;
4967         read_unlock(&tasklist_lock);
4968
4969         /*
4970          * This one might sleep, we cannot do it with a spinlock held ...
4971          */
4972         retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4973
4974         return retval;
4975
4976 out_unlock:
4977         read_unlock(&tasklist_lock);
4978         return retval;
4979 }
4980
4981 long sched_setaffinity(pid_t pid, const cpumask_t *in_mask)
4982 {
4983         cpumask_t cpus_allowed;
4984         cpumask_t new_mask = *in_mask;
4985         struct task_struct *p;
4986         int retval;
4987
4988         get_online_cpus();
4989         read_lock(&tasklist_lock);
4990
4991         p = find_process_by_pid(pid);
4992         if (!p) {
4993                 read_unlock(&tasklist_lock);
4994                 put_online_cpus();
4995                 return -ESRCH;
4996         }
4997
4998         /*
4999          * It is not safe to call set_cpus_allowed with the
5000          * tasklist_lock held. We will bump the task_struct's
5001          * usage count and then drop tasklist_lock.
5002          */
5003         get_task_struct(p);
5004         read_unlock(&tasklist_lock);
5005
5006         retval = -EPERM;
5007         if ((current->euid != p->euid) && (current->euid != p->uid) &&
5008                         !capable(CAP_SYS_NICE))
5009                 goto out_unlock;
5010
5011         retval = security_task_setscheduler(p, 0, NULL);
5012         if (retval)
5013                 goto out_unlock;
5014
5015         cpuset_cpus_allowed(p, &cpus_allowed);
5016         cpus_and(new_mask, new_mask, cpus_allowed);
5017  again:
5018         retval = set_cpus_allowed_ptr(p, &new_mask);
5019
5020         if (!retval) {
5021                 cpuset_cpus_allowed(p, &cpus_allowed);
5022                 if (!cpus_subset(new_mask, cpus_allowed)) {
5023                         /*
5024                          * We must have raced with a concurrent cpuset
5025                          * update. Just reset the cpus_allowed to the
5026                          * cpuset's cpus_allowed
5027                          */
5028                         new_mask = cpus_allowed;
5029                         goto again;
5030                 }
5031         }
5032 out_unlock:
5033         put_task_struct(p);
5034         put_online_cpus();
5035         return retval;
5036 }
5037
5038 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
5039                              cpumask_t *new_mask)
5040 {
5041         if (len < sizeof(cpumask_t)) {
5042                 memset(new_mask, 0, sizeof(cpumask_t));
5043         } else if (len > sizeof(cpumask_t)) {
5044                 len = sizeof(cpumask_t);
5045         }
5046         return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
5047 }
5048
5049 /**
5050  * sys_sched_setaffinity - set the cpu affinity of a process
5051  * @pid: pid of the process
5052  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5053  * @user_mask_ptr: user-space pointer to the new cpu mask
5054  */
5055 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
5056                                       unsigned long __user *user_mask_ptr)
5057 {
5058         cpumask_t new_mask;
5059         int retval;
5060
5061         retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
5062         if (retval)
5063                 return retval;
5064
5065         return sched_setaffinity(pid, &new_mask);
5066 }
5067
5068 /*
5069  * Represents all cpu's present in the system
5070  * In systems capable of hotplug, this map could dynamically grow
5071  * as new cpu's are detected in the system via any platform specific
5072  * method, such as ACPI for e.g.
5073  */
5074
5075 cpumask_t cpu_present_map __read_mostly;
5076 EXPORT_SYMBOL(cpu_present_map);
5077
5078 #ifndef CONFIG_SMP
5079 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
5080 EXPORT_SYMBOL(cpu_online_map);
5081
5082 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
5083 EXPORT_SYMBOL(cpu_possible_map);
5084 #endif
5085
5086 long sched_getaffinity(pid_t pid, cpumask_t *mask)
5087 {
5088         struct task_struct *p;
5089         int retval;
5090
5091         get_online_cpus();
5092         read_lock(&tasklist_lock);
5093
5094         retval = -ESRCH;
5095         p = find_process_by_pid(pid);
5096         if (!p)
5097                 goto out_unlock;
5098
5099         retval = security_task_getscheduler(p);
5100         if (retval)
5101                 goto out_unlock;
5102
5103         cpus_and(*mask, p->cpus_allowed, cpu_online_map);
5104
5105 out_unlock:
5106         read_unlock(&tasklist_lock);
5107         put_online_cpus();
5108
5109         return retval;
5110 }
5111
5112 /**
5113  * sys_sched_getaffinity - get the cpu affinity of a process
5114  * @pid: pid of the process
5115  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
5116  * @user_mask_ptr: user-space pointer to hold the current cpu mask
5117  */
5118 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
5119                                       unsigned long __user *user_mask_ptr)
5120 {
5121         int ret;
5122         cpumask_t mask;
5123
5124         if (len < sizeof(cpumask_t))
5125                 return -EINVAL;
5126
5127         ret = sched_getaffinity(pid, &mask);
5128         if (ret < 0)
5129                 return ret;
5130
5131         if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
5132                 return -EFAULT;
5133
5134         return sizeof(cpumask_t);
5135 }
5136
5137 /**
5138  * sys_sched_yield - yield the current processor to other threads.
5139  *
5140  * This function yields the current CPU to other tasks. If there are no
5141  * other threads running on this CPU then this function will return.
5142  */
5143 asmlinkage long sys_sched_yield(void)
5144 {
5145         struct rq *rq = this_rq_lock();
5146
5147         schedstat_inc(rq, yld_count);
5148         current->sched_class->yield_task(rq);
5149
5150         /*
5151          * Since we are going to call schedule() anyway, there's
5152          * no need to preempt or enable interrupts:
5153          */
5154         __release(rq->lock);
5155         spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
5156         _raw_spin_unlock(&rq->lock);
5157         preempt_enable_no_resched();
5158
5159         schedule();
5160
5161         return 0;
5162 }
5163
5164 static void __cond_resched(void)
5165 {
5166 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5167         __might_sleep(__FILE__, __LINE__);
5168 #endif
5169         /*
5170          * The BKS might be reacquired before we have dropped
5171          * PREEMPT_ACTIVE, which could trigger a second
5172          * cond_resched() call.
5173          */
5174         do {
5175                 add_preempt_count(PREEMPT_ACTIVE);
5176                 schedule();
5177                 sub_preempt_count(PREEMPT_ACTIVE);
5178         } while (need_resched());
5179 }
5180
5181 int __sched _cond_resched(void)
5182 {
5183         if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
5184                                         system_state == SYSTEM_RUNNING) {
5185                 __cond_resched();
5186                 return 1;
5187         }
5188         return 0;
5189 }
5190 EXPORT_SYMBOL(_cond_resched);
5191
5192 /*
5193  * cond_resched_lock() - if a reschedule is pending, drop the given lock,
5194  * call schedule, and on return reacquire the lock.
5195  *
5196  * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5197  * operations here to prevent schedule() from being called twice (once via
5198  * spin_unlock(), once by hand).
5199  */
5200 int cond_resched_lock(spinlock_t *lock)
5201 {
5202         int resched = need_resched() && system_state == SYSTEM_RUNNING;
5203         int ret = 0;
5204
5205         if (spin_needbreak(lock) || resched) {
5206                 spin_unlock(lock);
5207                 if (resched && need_resched())
5208                         __cond_resched();
5209                 else
5210                         cpu_relax();
5211                 ret = 1;
5212                 spin_lock(lock);
5213         }
5214         return ret;
5215 }
5216 EXPORT_SYMBOL(cond_resched_lock);
5217
5218 int __sched cond_resched_softirq(void)
5219 {
5220         BUG_ON(!in_softirq());
5221
5222         if (need_resched() && system_state == SYSTEM_RUNNING) {
5223                 local_bh_enable();
5224                 __cond_resched();
5225                 local_bh_disable();
5226                 return 1;
5227         }
5228         return 0;
5229 }
5230 EXPORT_SYMBOL(cond_resched_softirq);
5231
5232 /**
5233  * yield - yield the current processor to other threads.
5234  *
5235  * This is a shortcut for kernel-space yielding - it marks the
5236  * thread runnable and calls sys_sched_yield().
5237  */
5238 void __sched yield(void)
5239 {
5240         set_current_state(TASK_RUNNING);
5241         sys_sched_yield();
5242 }
5243 EXPORT_SYMBOL(yield);
5244
5245 /*
5246  * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5247  * that process accounting knows that this is a task in IO wait state.
5248  *
5249  * But don't do that if it is a deliberate, throttling IO wait (this task
5250  * has set its backing_dev_info: the queue against which it should throttle)
5251  */
5252 void __sched io_schedule(void)
5253 {
5254         struct rq *rq = &__raw_get_cpu_var(runqueues);
5255
5256         delayacct_blkio_start();
5257         atomic_inc(&rq->nr_iowait);
5258         schedule();
5259         atomic_dec(&rq->nr_iowait);
5260         delayacct_blkio_end();
5261 }
5262 EXPORT_SYMBOL(io_schedule);
5263
5264 long __sched io_schedule_timeout(long timeout)
5265 {
5266         struct rq *rq = &__raw_get_cpu_var(runqueues);
5267         long ret;
5268
5269         delayacct_blkio_start();
5270         atomic_inc(&rq->nr_iowait);
5271         ret = schedule_timeout(timeout);
5272         atomic_dec(&rq->nr_iowait);
5273         delayacct_blkio_end();
5274         return ret;
5275 }
5276
5277 /**
5278  * sys_sched_get_priority_max - return maximum RT priority.
5279  * @policy: scheduling class.
5280  *
5281  * this syscall returns the maximum rt_priority that can be used
5282  * by a given scheduling class.
5283  */
5284 asmlinkage long sys_sched_get_priority_max(int policy)
5285 {
5286         int ret = -EINVAL;
5287
5288         switch (policy) {
5289         case SCHED_FIFO:
5290         case SCHED_RR:
5291                 ret = MAX_USER_RT_PRIO-1;
5292                 break;
5293         case SCHED_NORMAL:
5294         case SCHED_BATCH:
5295         case SCHED_IDLE:
5296                 ret = 0;
5297                 break;
5298         }
5299         return ret;
5300 }
5301
5302 /**
5303  * sys_sched_get_priority_min - return minimum RT priority.
5304  * @policy: scheduling class.
5305  *
5306  * this syscall returns the minimum rt_priority that can be used
5307  * by a given scheduling class.
5308  */
5309 asmlinkage long sys_sched_get_priority_min(int policy)
5310 {
5311         int ret = -EINVAL;
5312
5313         switch (policy) {
5314         case SCHED_FIFO:
5315         case SCHED_RR:
5316                 ret = 1;
5317                 break;
5318         case SCHED_NORMAL:
5319         case SCHED_BATCH:
5320         case SCHED_IDLE:
5321                 ret = 0;
5322         }
5323         return ret;
5324 }
5325
5326 /**
5327  * sys_sched_rr_get_interval - return the default timeslice of a process.
5328  * @pid: pid of the process.
5329  * @interval: userspace pointer to the timeslice value.
5330  *
5331  * this syscall writes the default timeslice value of a given process
5332  * into the user-space timespec buffer. A value of '0' means infinity.
5333  */
5334 asmlinkage
5335 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
5336 {
5337         struct task_struct *p;
5338         unsigned int time_slice;
5339         int retval;
5340         struct timespec t;
5341
5342         if (pid < 0)
5343                 return -EINVAL;
5344
5345         retval = -ESRCH;
5346         read_lock(&tasklist_lock);
5347         p = find_process_by_pid(pid);
5348         if (!p)
5349                 goto out_unlock;
5350
5351         retval = security_task_getscheduler(p);
5352         if (retval)
5353                 goto out_unlock;
5354
5355         /*
5356          * Time slice is 0 for SCHED_FIFO tasks and for SCHED_OTHER
5357          * tasks that are on an otherwise idle runqueue:
5358          */
5359         time_slice = 0;
5360         if (p->policy == SCHED_RR) {
5361                 time_slice = DEF_TIMESLICE;
5362         } else if (p->policy != SCHED_FIFO) {
5363                 struct sched_entity *se = &p->se;
5364                 unsigned long flags;
5365                 struct rq *rq;
5366
5367                 rq = task_rq_lock(p, &flags);
5368                 if (rq->cfs.load.weight)
5369                         time_slice = NS_TO_JIFFIES(sched_slice(&rq->cfs, se));
5370                 task_rq_unlock(rq, &flags);
5371         }
5372         read_unlock(&tasklist_lock);
5373         jiffies_to_timespec(time_slice, &t);
5374         retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
5375         return retval;
5376
5377 out_unlock:
5378         read_unlock(&tasklist_lock);
5379         return retval;
5380 }
5381
5382 static const char stat_nam[] = "RSDTtZX";
5383
5384 void sched_show_task(struct task_struct *p)
5385 {
5386         unsigned long free = 0;
5387         unsigned state;
5388
5389         state = p->state ? __ffs(p->state) + 1 : 0;
5390         printk(KERN_INFO "%-13.13s %c", p->comm,
5391                 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
5392 #if BITS_PER_LONG == 32
5393         if (state == TASK_RUNNING)
5394                 printk(KERN_CONT " running  ");
5395         else
5396                 printk(KERN_CONT " %08lx ", thread_saved_pc(p));
5397 #else
5398         if (state == TASK_RUNNING)
5399                 printk(KERN_CONT "  running task    ");
5400         else
5401                 printk(KERN_CONT " %016lx ", thread_saved_pc(p));
5402 #endif
5403 #ifdef CONFIG_DEBUG_STACK_USAGE
5404         {
5405                 unsigned long *n = end_of_stack(p);
5406                 while (!*n)
5407                         n++;
5408                 free = (unsigned long)n - (unsigned long)end_of_stack(p);
5409         }
5410 #endif
5411         printk(KERN_CONT "%5lu %5d %6d\n", free,
5412                 task_pid_nr(p), task_pid_nr(p->real_parent));
5413
5414         show_stack(p, NULL);
5415 }
5416
5417 void show_state_filter(unsigned long state_filter)
5418 {
5419         struct task_struct *g, *p;
5420
5421 #if BITS_PER_LONG == 32
5422         printk(KERN_INFO
5423                 "  task                PC stack   pid father\n");
5424 #else
5425         printk(KERN_INFO
5426                 "  task                        PC stack   pid father\n");
5427 #endif
5428         read_lock(&tasklist_lock);
5429         do_each_thread(g, p) {
5430                 /*
5431                  * reset the NMI-timeout, listing all files on a slow
5432                  * console might take alot of time:
5433                  */
5434                 touch_nmi_watchdog();
5435                 if (!state_filter || (p->state & state_filter))
5436                         sched_show_task(p);
5437         } while_each_thread(g, p);
5438
5439         touch_all_softlockup_watchdogs();
5440
5441 #ifdef CONFIG_SCHED_DEBUG
5442         sysrq_sched_debug_show();
5443 #endif
5444         read_unlock(&tasklist_lock);
5445         /*
5446          * Only show locks if all tasks are dumped:
5447          */
5448         if (state_filter == -1)
5449                 debug_show_all_locks();
5450 }
5451
5452 void __cpuinit init_idle_bootup_task(struct task_struct *idle)
5453 {
5454         idle->sched_class = &idle_sched_class;
5455 }
5456
5457 /**
5458  * init_idle - set up an idle thread for a given CPU
5459  * @idle: task in question
5460  * @cpu: cpu the idle task belongs to
5461  *
5462  * NOTE: this function does not set the idle thread's NEED_RESCHED
5463  * flag, to make booting more robust.
5464  */
5465 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5466 {
5467         struct rq *rq = cpu_rq(cpu);
5468         unsigned long flags;
5469
5470         __sched_fork(idle);
5471         idle->se.exec_start = sched_clock();
5472
5473         idle->prio = idle->normal_prio = MAX_PRIO;
5474         idle->cpus_allowed = cpumask_of_cpu(cpu);
5475         __set_task_cpu(idle, cpu);
5476
5477         spin_lock_irqsave(&rq->lock, flags);
5478         rq->curr = rq->idle = idle;
5479 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5480         idle->oncpu = 1;
5481 #endif
5482         spin_unlock_irqrestore(&rq->lock, flags);
5483
5484         /* Set the preempt count _outside_ the spinlocks! */
5485 #if defined(CONFIG_PREEMPT)
5486         task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
5487 #else
5488         task_thread_info(idle)->preempt_count = 0;
5489 #endif
5490         /*
5491          * The idle tasks have their own, simple scheduling class:
5492          */
5493         idle->sched_class = &idle_sched_class;
5494 }
5495
5496 /*
5497  * In a system that switches off the HZ timer nohz_cpu_mask
5498  * indicates which cpus entered this state. This is used
5499  * in the rcu update to wait only for active cpus. For system
5500  * which do not switch off the HZ timer nohz_cpu_mask should
5501  * always be CPU_MASK_NONE.
5502  */
5503 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
5504
5505 /*
5506  * Increase the granularity value when there are more CPUs,
5507  * because with more CPUs the 'effective latency' as visible
5508  * to users decreases. But the relationship is not linear,
5509  * so pick a second-best guess by going with the log2 of the
5510  * number of CPUs.
5511  *
5512  * This idea comes from the SD scheduler of Con Kolivas:
5513  */
5514 static inline void sched_init_granularity(void)
5515 {
5516         unsigned int factor = 1 + ilog2(num_online_cpus());
5517         const unsigned long limit = 200000000;
5518
5519         sysctl_sched_min_granularity *= factor;
5520         if (sysctl_sched_min_granularity > limit)
5521                 sysctl_sched_min_granularity = limit;
5522
5523         sysctl_sched_latency *= factor;
5524         if (sysctl_sched_latency > limit)
5525                 sysctl_sched_latency = limit;
5526
5527         sysctl_sched_wakeup_granularity *= factor;
5528 }
5529
5530 #ifdef CONFIG_SMP
5531 /*
5532  * This is how migration works:
5533  *
5534  * 1) we queue a struct migration_req structure in the source CPU's
5535  *    runqueue and wake up that CPU's migration thread.
5536  * 2) we down() the locked semaphore => thread blocks.
5537  * 3) migration thread wakes up (implicitly it forces the migrated
5538  *    thread off the CPU)
5539  * 4) it gets the migration request and checks whether the migrated
5540  *    task is still in the wrong runqueue.
5541  * 5) if it's in the wrong runqueue then the migration thread removes
5542  *    it and puts it into the right queue.
5543  * 6) migration thread up()s the semaphore.
5544  * 7) we wake up and the migration is done.
5545  */
5546
5547 /*
5548  * Change a given task's CPU affinity. Migrate the thread to a
5549  * proper CPU and schedule it away if the CPU it's executing on
5550  * is removed from the allowed bitmask.
5551  *
5552  * NOTE: the caller must have a valid reference to the task, the
5553  * task must not exit() & deallocate itself prematurely. The
5554  * call is not atomic; no spinlocks may be held.
5555  */
5556 int set_cpus_allowed_ptr(struct task_struct *p, const cpumask_t *new_mask)
5557 {
5558         struct migration_req req;
5559         unsigned long flags;
5560         struct rq *rq;
5561         int ret = 0;
5562
5563         rq = task_rq_lock(p, &flags);
5564         if (!cpus_intersects(*new_mask, cpu_online_map)) {
5565                 ret = -EINVAL;
5566                 goto out;
5567         }
5568
5569         if (p->sched_class->set_cpus_allowed)
5570                 p->sched_class->set_cpus_allowed(p, new_mask);
5571         else {
5572                 p->cpus_allowed = *new_mask;
5573                 p->rt.nr_cpus_allowed = cpus_weight(*new_mask);
5574         }
5575
5576         /* Can the task run on the task's current CPU? If so, we're done */
5577         if (cpu_isset(task_cpu(p), *new_mask))
5578                 goto out;
5579
5580         if (migrate_task(p, any_online_cpu(*new_mask), &req)) {
5581                 /* Need help from migration thread: drop lock and wait. */
5582                 task_rq_unlock(rq, &flags);
5583                 wake_up_process(rq->migration_thread);
5584                 wait_for_completion(&req.done);
5585                 tlb_migrate_finish(p->mm);
5586                 return 0;
5587         }
5588 out:
5589         task_rq_unlock(rq, &flags);
5590
5591         return ret;
5592 }
5593 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
5594
5595 /*
5596  * Move (not current) task off this cpu, onto dest cpu. We're doing
5597  * this because either it can't run here any more (set_cpus_allowed()
5598  * away from this CPU, or CPU going down), or because we're
5599  * attempting to rebalance this task on exec (sched_exec).
5600  *
5601  * So we race with normal scheduler movements, but that's OK, as long
5602  * as the task is no longer on this CPU.
5603  *
5604  * Returns non-zero if task was successfully migrated.
5605  */
5606 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
5607 {
5608         struct rq *rq_dest, *rq_src;
5609         int ret = 0, on_rq;
5610
5611         if (unlikely(cpu_is_offline(dest_cpu)))
5612                 return ret;
5613
5614         rq_src = cpu_rq(src_cpu);
5615         rq_dest = cpu_rq(dest_cpu);
5616
5617         double_rq_lock(rq_src, rq_dest);
5618         /* Already moved. */
5619         if (task_cpu(p) != src_cpu)
5620                 goto out;
5621         /* Affinity changed (again). */
5622         if (!cpu_isset(dest_cpu, p->cpus_allowed))
5623                 goto out;
5624
5625         on_rq = p->se.on_rq;
5626         if (on_rq)
5627                 deactivate_task(rq_src, p, 0);
5628
5629         set_task_cpu(p, dest_cpu);
5630         if (on_rq) {
5631                 activate_task(rq_dest, p, 0);
5632                 check_preempt_curr(rq_dest, p);
5633         }
5634         ret = 1;
5635 out:
5636         double_rq_unlock(rq_src, rq_dest);
5637         return ret;
5638 }
5639
5640 /*
5641  * migration_thread - this is a highprio system thread that performs
5642  * thread migration by bumping thread off CPU then 'pushing' onto
5643  * another runqueue.
5644  */
5645 static int migration_thread(void *data)
5646 {
5647         int cpu = (long)data;
5648         struct rq *rq;
5649
5650         rq = cpu_rq(cpu);
5651         BUG_ON(rq->migration_thread != current);
5652
5653         set_current_state(TASK_INTERRUPTIBLE);
5654         while (!kthread_should_stop()) {
5655                 struct migration_req *req;
5656                 struct list_head *head;
5657
5658                 spin_lock_irq(&rq->lock);
5659
5660                 if (cpu_is_offline(cpu)) {
5661                         spin_unlock_irq(&rq->lock);
5662                         goto wait_to_die;
5663                 }
5664
5665                 if (rq->active_balance) {
5666                         active_load_balance(rq, cpu);
5667                         rq->active_balance = 0;
5668                 }
5669
5670                 head = &rq->migration_queue;
5671
5672                 if (list_empty(head)) {
5673                         spin_unlock_irq(&rq->lock);
5674                         schedule();
5675                         set_current_state(TASK_INTERRUPTIBLE);
5676                         continue;
5677                 }
5678                 req = list_entry(head->next, struct migration_req, list);
5679                 list_del_init(head->next);
5680
5681                 spin_unlock(&rq->lock);
5682                 __migrate_task(req->task, cpu, req->dest_cpu);
5683                 local_irq_enable();
5684
5685                 complete(&req->done);
5686         }
5687         __set_current_state(TASK_RUNNING);
5688         return 0;
5689
5690 wait_to_die:
5691         /* Wait for kthread_stop */
5692         set_current_state(TASK_INTERRUPTIBLE);
5693         while (!kthread_should_stop()) {
5694                 schedule();
5695                 set_current_state(TASK_INTERRUPTIBLE);
5696         }
5697         __set_current_state(TASK_RUNNING);
5698         return 0;
5699 }
5700
5701 #ifdef CONFIG_HOTPLUG_CPU
5702
5703 static int __migrate_task_irq(struct task_struct *p, int src_cpu, int dest_cpu)
5704 {
5705         int ret;
5706
5707         local_irq_disable();
5708         ret = __migrate_task(p, src_cpu, dest_cpu);
5709         local_irq_enable();
5710         return ret;
5711 }
5712
5713 /*
5714  * Figure out where task on dead CPU should go, use force if necessary.
5715  * NOTE: interrupts should be disabled by the caller
5716  */
5717 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
5718 {
5719         unsigned long flags;
5720         cpumask_t mask;
5721         struct rq *rq;
5722         int dest_cpu;
5723
5724         do {
5725                 /* On same node? */
5726                 mask = node_to_cpumask(cpu_to_node(dead_cpu));
5727                 cpus_and(mask, mask, p->cpus_allowed);
5728                 dest_cpu = any_online_cpu(mask);
5729
5730                 /* On any allowed CPU? */
5731                 if (dest_cpu >= nr_cpu_ids)
5732                         dest_cpu = any_online_cpu(p->cpus_allowed);
5733
5734                 /* No more Mr. Nice Guy. */
5735                 if (dest_cpu >= nr_cpu_ids) {
5736                         cpumask_t cpus_allowed;
5737
5738                         cpuset_cpus_allowed_locked(p, &cpus_allowed);
5739                         /*
5740                          * Try to stay on the same cpuset, where the
5741                          * current cpuset may be a subset of all cpus.
5742                          * The cpuset_cpus_allowed_locked() variant of
5743                          * cpuset_cpus_allowed() will not block. It must be
5744                          * called within calls to cpuset_lock/cpuset_unlock.
5745                          */
5746                         rq = task_rq_lock(p, &flags);
5747                         p->cpus_allowed = cpus_allowed;
5748                         dest_cpu = any_online_cpu(p->cpus_allowed);
5749                         task_rq_unlock(rq, &flags);
5750
5751                         /*
5752                          * Don't tell them about moving exiting tasks or
5753                          * kernel threads (both mm NULL), since they never
5754                          * leave kernel.
5755                          */
5756                         if (p->mm && printk_ratelimit()) {
5757                                 printk(KERN_INFO "process %d (%s) no "
5758                                        "longer affine to cpu%d\n",
5759                                         task_pid_nr(p), p->comm, dead_cpu);
5760                         }
5761                 }
5762         } while (!__migrate_task_irq(p, dead_cpu, dest_cpu));
5763 }
5764
5765 /*
5766  * While a dead CPU has no uninterruptible tasks queued at this point,
5767  * it might still have a nonzero ->nr_uninterruptible counter, because
5768  * for performance reasons the counter is not stricly tracking tasks to
5769  * their home CPUs. So we just add the counter to another CPU's counter,
5770  * to keep the global sum constant after CPU-down:
5771  */
5772 static void migrate_nr_uninterruptible(struct rq *rq_src)
5773 {
5774         struct rq *rq_dest = cpu_rq(any_online_cpu(*CPU_MASK_ALL_PTR));
5775         unsigned long flags;
5776
5777         local_irq_save(flags);
5778         double_rq_lock(rq_src, rq_dest);
5779         rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5780         rq_src->nr_uninterruptible = 0;
5781         double_rq_unlock(rq_src, rq_dest);
5782         local_irq_restore(flags);
5783 }
5784
5785 /* Run through task list and migrate tasks from the dead cpu. */
5786 static void migrate_live_tasks(int src_cpu)
5787 {
5788         struct task_struct *p, *t;
5789
5790         read_lock(&tasklist_lock);
5791
5792         do_each_thread(t, p) {
5793                 if (p == current)
5794                         continue;
5795
5796                 if (task_cpu(p) == src_cpu)
5797                         move_task_off_dead_cpu(src_cpu, p);
5798         } while_each_thread(t, p);
5799
5800         read_unlock(&tasklist_lock);
5801 }
5802
5803 /*
5804  * Schedules idle task to be the next runnable task on current CPU.
5805  * It does so by boosting its priority to highest possible.
5806  * Used by CPU offline code.
5807  */
5808 void sched_idle_next(void)
5809 {
5810         int this_cpu = smp_processor_id();
5811         struct rq *rq = cpu_rq(this_cpu);
5812         struct task_struct *p = rq->idle;
5813         unsigned long flags;
5814
5815         /* cpu has to be offline */
5816         BUG_ON(cpu_online(this_cpu));
5817
5818         /*
5819          * Strictly not necessary since rest of the CPUs are stopped by now
5820          * and interrupts disabled on the current cpu.
5821          */
5822         spin_lock_irqsave(&rq->lock, flags);
5823
5824         __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
5825
5826         update_rq_clock(rq);
5827         activate_task(rq, p, 0);
5828
5829         spin_unlock_irqrestore(&rq->lock, flags);
5830 }
5831
5832 /*
5833  * Ensures that the idle task is using init_mm right before its cpu goes
5834  * offline.
5835  */
5836 void idle_task_exit(void)
5837 {
5838         struct mm_struct *mm = current->active_mm;
5839
5840         BUG_ON(cpu_online(smp_processor_id()));
5841
5842         if (mm != &init_mm)
5843                 switch_mm(mm, &init_mm, current);
5844         mmdrop(mm);
5845 }
5846
5847 /* called under rq->lock with disabled interrupts */
5848 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
5849 {
5850         struct rq *rq = cpu_rq(dead_cpu);
5851
5852         /* Must be exiting, otherwise would be on tasklist. */
5853         BUG_ON(!p->exit_state);
5854
5855         /* Cannot have done final schedule yet: would have vanished. */
5856         BUG_ON(p->state == TASK_DEAD);
5857
5858         get_task_struct(p);
5859
5860         /*
5861          * Drop lock around migration; if someone else moves it,
5862          * that's OK. No task can be added to this CPU, so iteration is
5863          * fine.
5864          */
5865         spin_unlock_irq(&rq->lock);
5866         move_task_off_dead_cpu(dead_cpu, p);
5867         spin_lock_irq(&rq->lock);
5868
5869         put_task_struct(p);
5870 }
5871
5872 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5873 static void migrate_dead_tasks(unsigned int dead_cpu)
5874 {
5875         struct rq *rq = cpu_rq(dead_cpu);
5876         struct task_struct *next;
5877
5878         for ( ; ; ) {
5879                 if (!rq->nr_running)
5880                         break;
5881                 update_rq_clock(rq);
5882                 next = pick_next_task(rq, rq->curr);
5883                 if (!next)
5884                         break;
5885                 migrate_dead(dead_cpu, next);
5886
5887         }
5888 }
5889 #endif /* CONFIG_HOTPLUG_CPU */
5890
5891 #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL)
5892
5893 static struct ctl_table sd_ctl_dir[] = {
5894         {
5895                 .procname       = "sched_domain",
5896                 .mode           = 0555,
5897         },
5898         {0, },
5899 };
5900
5901 static struct ctl_table sd_ctl_root[] = {
5902         {
5903                 .ctl_name       = CTL_KERN,
5904                 .procname       = "kernel",
5905                 .mode           = 0555,
5906                 .child          = sd_ctl_dir,
5907         },
5908         {0, },
5909 };
5910
5911 static struct ctl_table *sd_alloc_ctl_entry(int n)
5912 {
5913         struct ctl_table *entry =
5914                 kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL);
5915
5916         return entry;
5917 }
5918
5919 static void sd_free_ctl_entry(struct ctl_table **tablep)
5920 {
5921         struct ctl_table *entry;
5922
5923         /*
5924          * In the intermediate directories, both the child directory and
5925          * procname are dynamically allocated and could fail but the mode
5926          * will always be set. In the lowest directory the names are
5927          * static strings and all have proc handlers.
5928          */
5929         for (entry = *tablep; entry->mode; entry++) {
5930                 if (entry->child)
5931                         sd_free_ctl_entry(&entry->child);
5932                 if (entry->proc_handler == NULL)
5933                         kfree(entry->procname);
5934         }
5935
5936         kfree(*tablep);
5937         *tablep = NULL;
5938 }
5939
5940 static void
5941 set_table_entry(struct ctl_table *entry,
5942                 const char *procname, void *data, int maxlen,
5943                 mode_t mode, proc_handler *proc_handler)
5944 {
5945         entry->procname = procname;
5946         entry->data = data;
5947         entry->maxlen = maxlen;
5948         entry->mode = mode;
5949         entry->proc_handler = proc_handler;
5950 }
5951
5952 static struct ctl_table *
5953 sd_alloc_ctl_domain_table(struct sched_domain *sd)
5954 {
5955         struct ctl_table *table = sd_alloc_ctl_entry(12);
5956
5957         if (table == NULL)
5958                 return NULL;
5959
5960         set_table_entry(&table[0], "min_interval", &sd->min_interval,
5961                 sizeof(long), 0644, proc_doulongvec_minmax);
5962         set_table_entry(&table[1], "max_interval", &sd->max_interval,
5963                 sizeof(long), 0644, proc_doulongvec_minmax);
5964         set_table_entry(&table[2], "busy_idx", &sd->busy_idx,
5965                 sizeof(int), 0644, proc_dointvec_minmax);
5966         set_table_entry(&table[3], "idle_idx", &sd->idle_idx,
5967                 sizeof(int), 0644, proc_dointvec_minmax);
5968         set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx,
5969                 sizeof(int), 0644, proc_dointvec_minmax);
5970         set_table_entry(&table[5], "wake_idx", &sd->wake_idx,
5971                 sizeof(int), 0644, proc_dointvec_minmax);
5972         set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx,
5973                 sizeof(int), 0644, proc_dointvec_minmax);
5974         set_table_entry(&table[7], "busy_factor", &sd->busy_factor,
5975                 sizeof(int), 0644, proc_dointvec_minmax);
5976         set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct,
5977                 sizeof(int), 0644, proc_dointvec_minmax);
5978         set_table_entry(&table[9], "cache_nice_tries",
5979                 &sd->cache_nice_tries,
5980                 sizeof(int), 0644, proc_dointvec_minmax);
5981         set_table_entry(&table[10], "flags", &sd->flags,
5982                 sizeof(int), 0644, proc_dointvec_minmax);
5983         /* &table[11] is terminator */
5984
5985         return table;
5986 }
5987
5988 static ctl_table *sd_alloc_ctl_cpu_table(int cpu)
5989 {
5990         struct ctl_table *entry, *table;
5991         struct sched_domain *sd;
5992         int domain_num = 0, i;
5993         char buf[32];
5994
5995         for_each_domain(cpu, sd)
5996                 domain_num++;
5997         entry = table = sd_alloc_ctl_entry(domain_num + 1);
5998         if (table == NULL)
5999                 return NULL;
6000
6001         i = 0;
6002         for_each_domain(cpu, sd) {
6003                 snprintf(buf, 32, "domain%d", i);
6004                 entry->procname = kstrdup(buf, GFP_KERNEL);
6005                 entry->mode = 0555;
6006                 entry->child = sd_alloc_ctl_domain_table(sd);
6007                 entry++;
6008                 i++;
6009         }
6010         return table;
6011 }
6012
6013 static struct ctl_table_header *sd_sysctl_header;
6014 static void register_sched_domain_sysctl(void)
6015 {
6016         int i, cpu_num = num_online_cpus();
6017         struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1);
6018         char buf[32];
6019
6020         WARN_ON(sd_ctl_dir[0].child);
6021         sd_ctl_dir[0].child = entry;
6022
6023         if (entry == NULL)
6024                 return;
6025
6026         for_each_online_cpu(i) {
6027                 snprintf(buf, 32, "cpu%d", i);
6028                 entry->procname = kstrdup(buf, GFP_KERNEL);
6029                 entry->mode = 0555;
6030                 entry->child = sd_alloc_ctl_cpu_table(i);
6031                 entry++;
6032         }
6033
6034         WARN_ON(sd_sysctl_header);
6035         sd_sysctl_header = register_sysctl_table(sd_ctl_root);
6036 }
6037
6038 /* may be called multiple times per register */
6039 static void unregister_sched_domain_sysctl(void)
6040 {
6041         if (sd_sysctl_header)
6042                 unregister_sysctl_table(sd_sysctl_header);
6043         sd_sysctl_header = NULL;
6044         if (sd_ctl_dir[0].child)
6045                 sd_free_ctl_entry(&sd_ctl_dir[0].child);
6046 }
6047 #else
6048 static void register_sched_domain_sysctl(void)
6049 {
6050 }
6051 static void unregister_sched_domain_sysctl(void)
6052 {
6053 }
6054 #endif
6055
6056 /*
6057  * migration_call - callback that gets triggered when a CPU is added.
6058  * Here we can start up the necessary migration thread for the new CPU.
6059  */
6060 static int __cpuinit
6061 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
6062 {
6063         struct task_struct *p;
6064         int cpu = (long)hcpu;
6065         unsigned long flags;
6066         struct rq *rq;
6067
6068         switch (action) {
6069
6070         case CPU_UP_PREPARE:
6071         case CPU_UP_PREPARE_FROZEN:
6072                 p = kthread_create(migration_thread, hcpu, "migration/%d", cpu);
6073                 if (IS_ERR(p))
6074                         return NOTIFY_BAD;
6075                 kthread_bind(p, cpu);
6076                 /* Must be high prio: stop_machine expects to yield to it. */
6077                 rq = task_rq_lock(p, &flags);
6078                 __setscheduler(rq, p, SCHED_FIFO, MAX_RT_PRIO-1);
6079                 task_rq_unlock(rq, &flags);
6080                 cpu_rq(cpu)->migration_thread = p;
6081                 break;
6082
6083         case CPU_ONLINE:
6084         case CPU_ONLINE_FROZEN:
6085                 /* Strictly unnecessary, as first user will wake it. */
6086                 wake_up_process(cpu_rq(cpu)->migration_thread);
6087
6088                 /* Update our root-domain */
6089                 rq = cpu_rq(cpu);
6090                 spin_lock_irqsave(&rq->lock, flags);
6091                 if (rq->rd) {
6092                         BUG_ON(!cpu_isset(cpu, rq->rd->span));
6093                         cpu_set(cpu, rq->rd->online);
6094                 }
6095                 spin_unlock_irqrestore(&rq->lock, flags);
6096                 break;
6097
6098 #ifdef CONFIG_HOTPLUG_CPU
6099         case CPU_UP_CANCELED:
6100         case CPU_UP_CANCELED_FROZEN:
6101                 if (!cpu_rq(cpu)->migration_thread)
6102                         break;
6103                 /* Unbind it from offline cpu so it can run. Fall thru. */
6104                 kthread_bind(cpu_rq(cpu)->migration_thread,
6105                              any_online_cpu(cpu_online_map));
6106                 kthread_stop(cpu_rq(cpu)->migration_thread);
6107                 cpu_rq(cpu)->migration_thread = NULL;
6108                 break;
6109
6110         case CPU_DEAD:
6111         case CPU_DEAD_FROZEN:
6112                 cpuset_lock(); /* around calls to cpuset_cpus_allowed_lock() */
6113                 migrate_live_tasks(cpu);
6114                 rq = cpu_rq(cpu);
6115                 kthread_stop(rq->migration_thread);
6116                 rq->migration_thread = NULL;
6117                 /* Idle task back to normal (off runqueue, low prio) */
6118                 spin_lock_irq(&rq->lock);
6119                 update_rq_clock(rq);
6120                 deactivate_task(rq, rq->idle, 0);
6121                 rq->idle->static_prio = MAX_PRIO;
6122                 __setscheduler(rq, rq->idle, SCHED_NORMAL, 0);
6123                 rq->idle->sched_class = &idle_sched_class;
6124                 migrate_dead_tasks(cpu);
6125                 spin_unlock_irq(&rq->lock);
6126                 cpuset_unlock();
6127                 migrate_nr_uninterruptible(rq);
6128                 BUG_ON(rq->nr_running != 0);
6129
6130                 /*
6131                  * No need to migrate the tasks: it was best-effort if
6132                  * they didn't take sched_hotcpu_mutex. Just wake up
6133                  * the requestors.
6134                  */
6135                 spin_lock_irq(&rq->lock);
6136                 while (!list_empty(&rq->migration_queue)) {
6137                         struct migration_req *req;
6138
6139                         req = list_entry(rq->migration_queue.next,
6140                                          struct migration_req, list);
6141                         list_del_init(&req->list);
6142                         complete(&req->done);
6143                 }
6144                 spin_unlock_irq(&rq->lock);
6145                 break;
6146
6147         case CPU_DYING:
6148         case CPU_DYING_FROZEN:
6149                 /* Update our root-domain */
6150                 rq = cpu_rq(cpu);
6151                 spin_lock_irqsave(&rq->lock, flags);
6152                 if (rq->rd) {
6153                         BUG_ON(!cpu_isset(cpu, rq->rd->span));
6154                         cpu_clear(cpu, rq->rd->online);
6155                 }
6156                 spin_unlock_irqrestore(&rq->lock, flags);
6157                 break;
6158 #endif
6159         }
6160         return NOTIFY_OK;
6161 }
6162
6163 /* Register at highest priority so that task migration (migrate_all_tasks)
6164  * happens before everything else.
6165  */
6166 static struct notifier_block __cpuinitdata migration_notifier = {
6167         .notifier_call = migration_call,
6168         .priority = 10
6169 };
6170
6171 void __init migration_init(void)
6172 {
6173         void *cpu = (void *)(long)smp_processor_id();
6174         int err;
6175
6176         /* Start one for the boot CPU: */
6177         err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
6178         BUG_ON(err == NOTIFY_BAD);
6179         migration_call(&migration_notifier, CPU_ONLINE, cpu);
6180         register_cpu_notifier(&migration_notifier);
6181 }
6182 #endif
6183
6184 #ifdef CONFIG_SMP
6185
6186 #ifdef CONFIG_SCHED_DEBUG
6187
6188 static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level,
6189                                   cpumask_t *groupmask)
6190 {
6191         struct sched_group *group = sd->groups;
6192         char str[256];
6193
6194         cpulist_scnprintf(str, sizeof(str), sd->span);
6195         cpus_clear(*groupmask);
6196
6197         printk(KERN_DEBUG "%*s domain %d: ", level, "", level);
6198
6199         if (!(sd->flags & SD_LOAD_BALANCE)) {
6200                 printk("does not load-balance\n");
6201                 if (sd->parent)
6202                         printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
6203                                         " has parent");
6204                 return -1;
6205         }
6206
6207         printk(KERN_CONT "span %s\n", str);
6208
6209         if (!cpu_isset(cpu, sd->span)) {
6210                 printk(KERN_ERR "ERROR: domain->span does not contain "
6211                                 "CPU%d\n", cpu);
6212         }
6213         if (!cpu_isset(cpu, group->cpumask)) {
6214                 printk(KERN_ERR "ERROR: domain->groups does not contain"
6215                                 " CPU%d\n", cpu);
6216         }
6217
6218         printk(KERN_DEBUG "%*s groups:", level + 1, "");
6219         do {
6220                 if (!group) {
6221                         printk("\n");
6222                         printk(KERN_ERR "ERROR: group is NULL\n");
6223                         break;
6224                 }
6225
6226                 if (!group->__cpu_power) {
6227                         printk(KERN_CONT "\n");
6228                         printk(KERN_ERR "ERROR: domain->cpu_power not "
6229                                         "set\n");
6230                         break;
6231                 }
6232
6233                 if (!cpus_weight(group->cpumask)) {
6234                         printk(KERN_CONT "\n");
6235                         printk(KERN_ERR "ERROR: empty group\n");
6236                         break;
6237                 }
6238
6239                 if (cpus_intersects(*groupmask, group->cpumask)) {
6240                         printk(KERN_CONT "\n");
6241                         printk(KERN_ERR "ERROR: repeated CPUs\n");
6242                         break;
6243                 }
6244
6245                 cpus_or(*groupmask, *groupmask, group->cpumask);
6246
6247                 cpulist_scnprintf(str, sizeof(str), group->cpumask);
6248                 printk(KERN_CONT " %s", str);
6249
6250                 group = group->next;
6251         } while (group != sd->groups);
6252         printk(KERN_CONT "\n");
6253
6254         if (!cpus_equal(sd->span, *groupmask))
6255                 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
6256
6257         if (sd->parent && !cpus_subset(*groupmask, sd->parent->span))
6258                 printk(KERN_ERR "ERROR: parent span is not a superset "
6259                         "of domain->span\n");
6260         return 0;
6261 }
6262
6263 static void sched_domain_debug(struct sched_domain *sd, int cpu)
6264 {
6265         cpumask_t *groupmask;
6266         int level = 0;
6267
6268         if (!sd) {
6269                 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
6270                 return;
6271         }
6272
6273         printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
6274
6275         groupmask = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
6276         if (!groupmask) {
6277                 printk(KERN_DEBUG "Cannot load-balance (out of memory)\n");
6278                 return;
6279         }
6280
6281         for (;;) {
6282                 if (sched_domain_debug_one(sd, cpu, level, groupmask))
6283                         break;
6284                 level++;
6285                 sd = sd->parent;
6286                 if (!sd)
6287                         break;
6288         }
6289         kfree(groupmask);
6290 }
6291 #else
6292 # define sched_domain_debug(sd, cpu) do { } while (0)
6293 #endif
6294
6295 static int sd_degenerate(struct sched_domain *sd)
6296 {
6297         if (cpus_weight(sd->span) == 1)
6298                 return 1;
6299
6300         /* Following flags need at least 2 groups */
6301         if (sd->flags & (SD_LOAD_BALANCE |
6302                          SD_BALANCE_NEWIDLE |
6303                          SD_BALANCE_FORK |
6304                          SD_BALANCE_EXEC |
6305                          SD_SHARE_CPUPOWER |
6306                          SD_SHARE_PKG_RESOURCES)) {
6307                 if (sd->groups != sd->groups->next)
6308                         return 0;
6309         }
6310
6311         /* Following flags don't use groups */
6312         if (sd->flags & (SD_WAKE_IDLE |
6313                          SD_WAKE_AFFINE |
6314                          SD_WAKE_BALANCE))
6315                 return 0;
6316
6317         return 1;
6318 }
6319
6320 static int
6321 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
6322 {
6323         unsigned long cflags = sd->flags, pflags = parent->flags;
6324
6325         if (sd_degenerate(parent))
6326                 return 1;
6327
6328         if (!cpus_equal(sd->span, parent->span))
6329                 return 0;
6330
6331         /* Does parent contain flags not in child? */
6332         /* WAKE_BALANCE is a subset of WAKE_AFFINE */
6333         if (cflags & SD_WAKE_AFFINE)
6334                 pflags &= ~SD_WAKE_BALANCE;
6335         /* Flags needing groups don't count if only 1 group in parent */
6336         if (parent->groups == parent->groups->next) {
6337                 pflags &= ~(SD_LOAD_BALANCE |
6338                                 SD_BALANCE_NEWIDLE |
6339                                 SD_BALANCE_FORK |
6340                                 SD_BALANCE_EXEC |
6341                                 SD_SHARE_CPUPOWER |
6342                                 SD_SHARE_PKG_RESOURCES);
6343         }
6344         if (~cflags & pflags)
6345                 return 0;
6346
6347         return 1;
6348 }
6349
6350 static void rq_attach_root(struct rq *rq, struct root_domain *rd)
6351 {
6352         unsigned long flags;
6353         const struct sched_class *class;
6354
6355         spin_lock_irqsave(&rq->lock, flags);
6356
6357         if (rq->rd) {
6358                 struct root_domain *old_rd = rq->rd;
6359
6360                 for (class = sched_class_highest; class; class = class->next) {
6361                         if (class->leave_domain)
6362                                 class->leave_domain(rq);
6363                 }
6364
6365                 cpu_clear(rq->cpu, old_rd->span);
6366                 cpu_clear(rq->cpu, old_rd->online);
6367
6368                 if (atomic_dec_and_test(&old_rd->refcount))
6369                         kfree(old_rd);
6370         }
6371
6372         atomic_inc(&rd->refcount);
6373         rq->rd = rd;
6374
6375         cpu_set(rq->cpu, rd->span);
6376         if (cpu_isset(rq->cpu, cpu_online_map))
6377                 cpu_set(rq->cpu, rd->online);
6378
6379         for (class = sched_class_highest; class; class = class->next) {
6380                 if (class->join_domain)
6381                         class->join_domain(rq);
6382         }
6383
6384         spin_unlock_irqrestore(&rq->lock, flags);
6385 }
6386
6387 static void init_rootdomain(struct root_domain *rd)
6388 {
6389         memset(rd, 0, sizeof(*rd));
6390
6391         cpus_clear(rd->span);
6392         cpus_clear(rd->online);
6393 }
6394
6395 static void init_defrootdomain(void)
6396 {
6397         init_rootdomain(&def_root_domain);
6398         atomic_set(&def_root_domain.refcount, 1);
6399 }
6400
6401 static struct root_domain *alloc_rootdomain(void)
6402 {
6403         struct root_domain *rd;
6404
6405         rd = kmalloc(sizeof(*rd), GFP_KERNEL);
6406         if (!rd)
6407                 return NULL;
6408
6409         init_rootdomain(rd);
6410
6411         return rd;
6412 }
6413
6414 /*
6415  * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
6416  * hold the hotplug lock.
6417  */
6418 static void
6419 cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu)
6420 {
6421         struct rq *rq = cpu_rq(cpu);
6422         struct sched_domain *tmp;
6423
6424         /* Remove the sched domains which do not contribute to scheduling. */
6425         for (tmp = sd; tmp; tmp = tmp->parent) {
6426                 struct sched_domain *parent = tmp->parent;
6427                 if (!parent)
6428                         break;
6429                 if (sd_parent_degenerate(tmp, parent)) {
6430                         tmp->parent = parent->parent;
6431                         if (parent->parent)
6432                                 parent->parent->child = tmp;
6433                 }
6434         }
6435
6436         if (sd && sd_degenerate(sd)) {
6437                 sd = sd->parent;
6438                 if (sd)
6439                         sd->child = NULL;
6440         }
6441
6442         sched_domain_debug(sd, cpu);
6443
6444         rq_attach_root(rq, rd);
6445         rcu_assign_pointer(rq->sd, sd);
6446 }
6447
6448 /* cpus with isolated domains */
6449 static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
6450
6451 /* Setup the mask of cpus configured for isolated domains */
6452 static int __init isolated_cpu_setup(char *str)
6453 {
6454         int ints[NR_CPUS], i;
6455
6456         str = get_options(str, ARRAY_SIZE(ints), ints);
6457         cpus_clear(cpu_isolated_map);
6458         for (i = 1; i <= ints[0]; i++)
6459                 if (ints[i] < NR_CPUS)
6460                         cpu_set(ints[i], cpu_isolated_map);
6461         return 1;
6462 }
6463
6464 __setup("isolcpus=", isolated_cpu_setup);
6465
6466 /*
6467  * init_sched_build_groups takes the cpumask we wish to span, and a pointer
6468  * to a function which identifies what group(along with sched group) a CPU
6469  * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
6470  * (due to the fact that we keep track of groups covered with a cpumask_t).
6471  *
6472  * init_sched_build_groups will build a circular linked list of the groups
6473  * covered by the given span, and will set each group's ->cpumask correctly,
6474  * and ->cpu_power to 0.
6475  */
6476 static void
6477 init_sched_build_groups(const cpumask_t *span, const cpumask_t *cpu_map,
6478                         int (*group_fn)(int cpu, const cpumask_t *cpu_map,
6479                                         struct sched_group **sg,
6480                                         cpumask_t *tmpmask),
6481                         cpumask_t *covered, cpumask_t *tmpmask)
6482 {
6483         struct sched_group *first = NULL, *last = NULL;
6484         int i;
6485
6486         cpus_clear(*covered);
6487
6488         for_each_cpu_mask(i, *span) {
6489                 struct sched_group *sg;
6490                 int group = group_fn(i, cpu_map, &sg, tmpmask);
6491                 int j;
6492
6493                 if (cpu_isset(i, *covered))
6494                         continue;
6495
6496                 cpus_clear(sg->cpumask);
6497                 sg->__cpu_power = 0;
6498
6499                 for_each_cpu_mask(j, *span) {
6500                         if (group_fn(j, cpu_map, NULL, tmpmask) != group)
6501                                 continue;
6502
6503                         cpu_set(j, *covered);
6504                         cpu_set(j, sg->cpumask);
6505                 }
6506                 if (!first)
6507                         first = sg;
6508                 if (last)
6509                         last->next = sg;
6510                 last = sg;
6511         }
6512         last->next = first;
6513 }
6514
6515 #define SD_NODES_PER_DOMAIN 16
6516
6517 #ifdef CONFIG_NUMA
6518
6519 /**
6520  * find_next_best_node - find the next node to include in a sched_domain
6521  * @node: node whose sched_domain we're building
6522  * @used_nodes: nodes already in the sched_domain
6523  *
6524  * Find the next node to include in a given scheduling domain. Simply
6525  * finds the closest node not already in the @used_nodes map.
6526  *
6527  * Should use nodemask_t.
6528  */
6529 static int find_next_best_node(int node, nodemask_t *used_nodes)
6530 {
6531         int i, n, val, min_val, best_node = 0;
6532
6533         min_val = INT_MAX;
6534
6535         for (i = 0; i < MAX_NUMNODES; i++) {
6536                 /* Start at @node */
6537                 n = (node + i) % MAX_NUMNODES;
6538
6539                 if (!nr_cpus_node(n))
6540                         continue;
6541
6542                 /* Skip already used nodes */
6543                 if (node_isset(n, *used_nodes))
6544                         continue;
6545
6546                 /* Simple min distance search */
6547                 val = node_distance(node, n);
6548
6549                 if (val < min_val) {
6550                         min_val = val;
6551                         best_node = n;
6552                 }
6553         }
6554
6555         node_set(best_node, *used_nodes);
6556         return best_node;
6557 }
6558
6559 /**
6560  * sched_domain_node_span - get a cpumask for a node's sched_domain
6561  * @node: node whose cpumask we're constructing
6562  * @span: resulting cpumask
6563  *
6564  * Given a node, construct a good cpumask for its sched_domain to span. It
6565  * should be one that prevents unnecessary balancing, but also spreads tasks
6566  * out optimally.
6567  */
6568 static void sched_domain_node_span(int node, cpumask_t *span)
6569 {
6570         nodemask_t used_nodes;
6571         node_to_cpumask_ptr(nodemask, node);
6572         int i;
6573
6574         cpus_clear(*span);
6575         nodes_clear(used_nodes);
6576
6577         cpus_or(*span, *span, *nodemask);
6578         node_set(node, used_nodes);
6579
6580         for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
6581                 int next_node = find_next_best_node(node, &used_nodes);
6582
6583                 node_to_cpumask_ptr_next(nodemask, next_node);
6584                 cpus_or(*span, *span, *nodemask);
6585         }
6586 }
6587 #endif
6588
6589 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6590
6591 /*
6592  * SMT sched-domains:
6593  */
6594 #ifdef CONFIG_SCHED_SMT
6595 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
6596 static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
6597
6598 static int
6599 cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
6600                  cpumask_t *unused)
6601 {
6602         if (sg)
6603                 *sg = &per_cpu(sched_group_cpus, cpu);
6604         return cpu;
6605 }
6606 #endif
6607
6608 /*
6609  * multi-core sched-domains:
6610  */
6611 #ifdef CONFIG_SCHED_MC
6612 static DEFINE_PER_CPU(struct sched_domain, core_domains);
6613 static DEFINE_PER_CPU(struct sched_group, sched_group_core);
6614 #endif
6615
6616 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6617 static int
6618 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
6619                   cpumask_t *mask)
6620 {
6621         int group;
6622
6623         *mask = per_cpu(cpu_sibling_map, cpu);
6624         cpus_and(*mask, *mask, *cpu_map);
6625         group = first_cpu(*mask);
6626         if (sg)
6627                 *sg = &per_cpu(sched_group_core, group);
6628         return group;
6629 }
6630 #elif defined(CONFIG_SCHED_MC)
6631 static int
6632 cpu_to_core_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
6633                   cpumask_t *unused)
6634 {
6635         if (sg)
6636                 *sg = &per_cpu(sched_group_core, cpu);
6637         return cpu;
6638 }
6639 #endif
6640
6641 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
6642 static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
6643
6644 static int
6645 cpu_to_phys_group(int cpu, const cpumask_t *cpu_map, struct sched_group **sg,
6646                   cpumask_t *mask)
6647 {
6648         int group;
6649 #ifdef CONFIG_SCHED_MC
6650         *mask = cpu_coregroup_map(cpu);
6651         cpus_and(*mask, *mask, *cpu_map);
6652         group = first_cpu(*mask);
6653 #elif defined(CONFIG_SCHED_SMT)
6654         *mask = per_cpu(cpu_sibling_map, cpu);
6655         cpus_and(*mask, *mask, *cpu_map);
6656         group = first_cpu(*mask);
6657 #else
6658         group = cpu;
6659 #endif
6660         if (sg)
6661                 *sg = &per_cpu(sched_group_phys, group);
6662         return group;
6663 }
6664
6665 #ifdef CONFIG_NUMA
6666 /*
6667  * The init_sched_build_groups can't handle what we want to do with node
6668  * groups, so roll our own. Now each node has its own list of groups which
6669  * gets dynamically allocated.
6670  */
6671 static DEFINE_PER_CPU(struct sched_domain, node_domains);
6672 static struct sched_group ***sched_group_nodes_bycpu;
6673
6674 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
6675 static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
6676
6677 static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
6678                                  struct sched_group **sg, cpumask_t *nodemask)
6679 {
6680         int group;
6681
6682         *nodemask = node_to_cpumask(cpu_to_node(cpu));
6683         cpus_and(*nodemask, *nodemask, *cpu_map);
6684         group = first_cpu(*nodemask);
6685
6686         if (sg)
6687                 *sg = &per_cpu(sched_group_allnodes, group);
6688         return group;
6689 }
6690
6691 static void init_numa_sched_groups_power(struct sched_group *group_head)
6692 {
6693         struct sched_group *sg = group_head;
6694         int j;
6695
6696         if (!sg)
6697                 return;
6698         do {
6699                 for_each_cpu_mask(j, sg->cpumask) {
6700                         struct sched_domain *sd;
6701
6702                         sd = &per_cpu(phys_domains, j);
6703                         if (j != first_cpu(sd->groups->cpumask)) {
6704                                 /*
6705                                  * Only add "power" once for each
6706                                  * physical package.
6707                                  */
6708                                 continue;
6709                         }
6710
6711                         sg_inc_cpu_power(sg, sd->groups->__cpu_power);
6712                 }
6713                 sg = sg->next;
6714         } while (sg != group_head);
6715 }
6716 #endif
6717
6718 #ifdef CONFIG_NUMA
6719 /* Free memory allocated for various sched_group structures */
6720 static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
6721 {
6722         int cpu, i;
6723
6724         for_each_cpu_mask(cpu, *cpu_map) {
6725                 struct sched_group **sched_group_nodes
6726                         = sched_group_nodes_bycpu[cpu];
6727
6728                 if (!sched_group_nodes)
6729                         continue;
6730
6731                 for (i = 0; i < MAX_NUMNODES; i++) {
6732                         struct sched_group *oldsg, *sg = sched_group_nodes[i];
6733
6734                         *nodemask = node_to_cpumask(i);
6735                         cpus_and(*nodemask, *nodemask, *cpu_map);
6736                         if (cpus_empty(*nodemask))
6737                                 continue;
6738
6739                         if (sg == NULL)
6740                                 continue;
6741                         sg = sg->next;
6742 next_sg:
6743                         oldsg = sg;
6744                         sg = sg->next;
6745                         kfree(oldsg);
6746                         if (oldsg != sched_group_nodes[i])
6747                                 goto next_sg;
6748                 }
6749                 kfree(sched_group_nodes);
6750                 sched_group_nodes_bycpu[cpu] = NULL;
6751         }
6752 }
6753 #else
6754 static void free_sched_groups(const cpumask_t *cpu_map, cpumask_t *nodemask)
6755 {
6756 }
6757 #endif
6758
6759 /*
6760  * Initialize sched groups cpu_power.
6761  *
6762  * cpu_power indicates the capacity of sched group, which is used while
6763  * distributing the load between different sched groups in a sched domain.
6764  * Typically cpu_power for all the groups in a sched domain will be same unless
6765  * there are asymmetries in the topology. If there are asymmetries, group
6766  * having more cpu_power will pickup more load compared to the group having
6767  * less cpu_power.
6768  *
6769  * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
6770  * the maximum number of tasks a group can handle in the presence of other idle
6771  * or lightly loaded groups in the same sched domain.
6772  */
6773 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
6774 {
6775         struct sched_domain *child;
6776         struct sched_group *group;
6777
6778         WARN_ON(!sd || !sd->groups);
6779
6780         if (cpu != first_cpu(sd->groups->cpumask))
6781                 return;
6782
6783         child = sd->child;
6784
6785         sd->groups->__cpu_power = 0;
6786
6787         /*
6788          * For perf policy, if the groups in child domain share resources
6789          * (for example cores sharing some portions of the cache hierarchy
6790          * or SMT), then set this domain groups cpu_power such that each group
6791          * can handle only one task, when there are other idle groups in the
6792          * same sched domain.
6793          */
6794         if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
6795                        (child->flags &
6796                         (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
6797                 sg_inc_cpu_power(sd->groups, SCHED_LOAD_SCALE);
6798                 return;
6799         }
6800
6801         /*
6802          * add cpu_power of each child group to this groups cpu_power
6803          */
6804         group = child->groups;
6805         do {
6806                 sg_inc_cpu_power(sd->groups, group->__cpu_power);
6807                 group = group->next;
6808         } while (group != child->groups);
6809 }
6810
6811 /*
6812  * Initializers for schedule domains
6813  * Non-inlined to reduce accumulated stack pressure in build_sched_domains()
6814  */
6815
6816 #define SD_INIT(sd, type)       sd_init_##type(sd)
6817 #define SD_INIT_FUNC(type)      \
6818 static noinline void sd_init_##type(struct sched_domain *sd)    \
6819 {                                                               \
6820         memset(sd, 0, sizeof(*sd));                             \
6821         *sd = SD_##type##_INIT;                                 \
6822         sd->level = SD_LV_##type;                               \
6823 }
6824
6825 SD_INIT_FUNC(CPU)
6826 #ifdef CONFIG_NUMA
6827  SD_INIT_FUNC(ALLNODES)
6828  SD_INIT_FUNC(NODE)
6829 #endif
6830 #ifdef CONFIG_SCHED_SMT
6831  SD_INIT_FUNC(SIBLING)
6832 #endif
6833 #ifdef CONFIG_SCHED_MC
6834  SD_INIT_FUNC(MC)
6835 #endif
6836
6837 /*
6838  * To minimize stack usage kmalloc room for cpumasks and share the
6839  * space as the usage in build_sched_domains() dictates.  Used only
6840  * if the amount of space is significant.
6841  */
6842 struct allmasks {
6843         cpumask_t tmpmask;                      /* make this one first */
6844         union {
6845                 cpumask_t nodemask;
6846                 cpumask_t this_sibling_map;
6847                 cpumask_t this_core_map;
6848         };
6849         cpumask_t send_covered;
6850
6851 #ifdef CONFIG_NUMA
6852         cpumask_t domainspan;
6853         cpumask_t covered;
6854         cpumask_t notcovered;
6855 #endif
6856 };
6857
6858 #if     NR_CPUS > 128
6859 #define SCHED_CPUMASK_ALLOC             1
6860 #define SCHED_CPUMASK_FREE(v)           kfree(v)
6861 #define SCHED_CPUMASK_DECLARE(v)        struct allmasks *v
6862 #else
6863 #define SCHED_CPUMASK_ALLOC             0
6864 #define SCHED_CPUMASK_FREE(v)
6865 #define SCHED_CPUMASK_DECLARE(v)        struct allmasks _v, *v = &_v
6866 #endif
6867
6868 #define SCHED_CPUMASK_VAR(v, a)         cpumask_t *v = (cpumask_t *) \
6869                         ((unsigned long)(a) + offsetof(struct allmasks, v))
6870
6871 static int default_relax_domain_level = -1;
6872
6873 static int __init setup_relax_domain_level(char *str)
6874 {
6875         default_relax_domain_level = simple_strtoul(str, NULL, 0);
6876         return 1;
6877 }
6878 __setup("relax_domain_level=", setup_relax_domain_level);
6879
6880 static void set_domain_attribute(struct sched_domain *sd,
6881                                  struct sched_domain_attr *attr)
6882 {
6883         int request;
6884
6885         if (!attr || attr->relax_domain_level < 0) {
6886                 if (default_relax_domain_level < 0)
6887                         return;
6888                 else
6889                         request = default_relax_domain_level;
6890         } else
6891                 request = attr->relax_domain_level;
6892         if (request < sd->level) {
6893                 /* turn off idle balance on this domain */
6894                 sd->flags &= ~(SD_WAKE_IDLE|SD_BALANCE_NEWIDLE);
6895         } else {
6896                 /* turn on idle balance on this domain */
6897                 sd->flags |= (SD_WAKE_IDLE_FAR|SD_BALANCE_NEWIDLE);
6898         }
6899 }
6900
6901 /*
6902  * Build sched domains for a given set of cpus and attach the sched domains
6903  * to the individual cpus
6904  */
6905 static int __build_sched_domains(const cpumask_t *cpu_map,
6906                                  struct sched_domain_attr *attr)
6907 {
6908         int i;
6909         struct root_domain *rd;
6910         SCHED_CPUMASK_DECLARE(allmasks);
6911         cpumask_t *tmpmask;
6912 #ifdef CONFIG_NUMA
6913         struct sched_group **sched_group_nodes = NULL;
6914         int sd_allnodes = 0;
6915
6916         /*
6917          * Allocate the per-node list of sched groups
6918          */
6919         sched_group_nodes = kcalloc(MAX_NUMNODES, sizeof(struct sched_group *),
6920                                     GFP_KERNEL);
6921         if (!sched_group_nodes) {
6922                 printk(KERN_WARNING "Can not alloc sched group node list\n");
6923                 return -ENOMEM;
6924         }
6925 #endif
6926
6927         rd = alloc_rootdomain();
6928         if (!rd) {
6929                 printk(KERN_WARNING "Cannot alloc root domain\n");
6930 #ifdef CONFIG_NUMA
6931                 kfree(sched_group_nodes);
6932 #endif
6933                 return -ENOMEM;
6934         }
6935
6936 #if SCHED_CPUMASK_ALLOC
6937         /* get space for all scratch cpumask variables */
6938         allmasks = kmalloc(sizeof(*allmasks), GFP_KERNEL);
6939         if (!allmasks) {
6940                 printk(KERN_WARNING "Cannot alloc cpumask array\n");
6941                 kfree(rd);
6942 #ifdef CONFIG_NUMA
6943                 kfree(sched_group_nodes);
6944 #endif
6945                 return -ENOMEM;
6946         }
6947 #endif
6948         tmpmask = (cpumask_t *)allmasks;
6949
6950
6951 #ifdef CONFIG_NUMA
6952         sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
6953 #endif
6954
6955         /*
6956          * Set up domains for cpus specified by the cpu_map.
6957          */
6958         for_each_cpu_mask(i, *cpu_map) {
6959                 struct sched_domain *sd = NULL, *p;
6960                 SCHED_CPUMASK_VAR(nodemask, allmasks);
6961
6962                 *nodemask = node_to_cpumask(cpu_to_node(i));
6963                 cpus_and(*nodemask, *nodemask, *cpu_map);
6964
6965 #ifdef CONFIG_NUMA
6966                 if (cpus_weight(*cpu_map) >
6967                                 SD_NODES_PER_DOMAIN*cpus_weight(*nodemask)) {
6968                         sd = &per_cpu(allnodes_domains, i);
6969                         SD_INIT(sd, ALLNODES);
6970                         set_domain_attribute(sd, attr);
6971                         sd->span = *cpu_map;
6972                         cpu_to_allnodes_group(i, cpu_map, &sd->groups, tmpmask);
6973                         p = sd;
6974                         sd_allnodes = 1;
6975                 } else
6976                         p = NULL;
6977
6978                 sd = &per_cpu(node_domains, i);
6979                 SD_INIT(sd, NODE);
6980                 set_domain_attribute(sd, attr);
6981                 sched_domain_node_span(cpu_to_node(i), &sd->span);
6982                 sd->parent = p;
6983                 if (p)
6984                         p->child = sd;
6985                 cpus_and(sd->span, sd->span, *cpu_map);
6986 #endif
6987
6988                 p = sd;
6989                 sd = &per_cpu(phys_domains, i);
6990                 SD_INIT(sd, CPU);
6991                 set_domain_attribute(sd, attr);
6992                 sd->span = *nodemask;
6993                 sd->parent = p;
6994                 if (p)
6995                         p->child = sd;
6996                 cpu_to_phys_group(i, cpu_map, &sd->groups, tmpmask);
6997
6998 #ifdef CONFIG_SCHED_MC
6999                 p = sd;
7000                 sd = &per_cpu(core_domains, i);
7001                 SD_INIT(sd, MC);
7002                 set_domain_attribute(sd, attr);
7003                 sd->span = cpu_coregroup_map(i);
7004                 cpus_and(sd->span, sd->span, *cpu_map);
7005                 sd->parent = p;
7006                 p->child = sd;
7007                 cpu_to_core_group(i, cpu_map, &sd->groups, tmpmask);
7008 #endif
7009
7010 #ifdef CONFIG_SCHED_SMT
7011                 p = sd;
7012                 sd = &per_cpu(cpu_domains, i);
7013                 SD_INIT(sd, SIBLING);
7014                 set_domain_attribute(sd, attr);
7015                 sd->span = per_cpu(cpu_sibling_map, i);
7016                 cpus_and(sd->span, sd->span, *cpu_map);
7017                 sd->parent = p;
7018                 p->child = sd;
7019                 cpu_to_cpu_group(i, cpu_map, &sd->groups, tmpmask);
7020 #endif
7021         }
7022
7023 #ifdef CONFIG_SCHED_SMT
7024         /* Set up CPU (sibling) groups */
7025         for_each_cpu_mask(i, *cpu_map) {
7026                 SCHED_CPUMASK_VAR(this_sibling_map, allmasks);
7027                 SCHED_CPUMASK_VAR(send_covered, allmasks);
7028
7029                 *this_sibling_map = per_cpu(cpu_sibling_map, i);
7030                 cpus_and(*this_sibling_map, *this_sibling_map, *cpu_map);
7031                 if (i != first_cpu(*this_sibling_map))
7032                         continue;
7033
7034                 init_sched_build_groups(this_sibling_map, cpu_map,
7035                                         &cpu_to_cpu_group,
7036                                         send_covered, tmpmask);
7037         }
7038 #endif
7039
7040 #ifdef CONFIG_SCHED_MC
7041         /* Set up multi-core groups */
7042         for_each_cpu_mask(i, *cpu_map) {
7043                 SCHED_CPUMASK_VAR(this_core_map, allmasks);
7044                 SCHED_CPUMASK_VAR(send_covered, allmasks);
7045
7046                 *this_core_map = cpu_coregroup_map(i);
7047                 cpus_and(*this_core_map, *this_core_map, *cpu_map);
7048                 if (i != first_cpu(*this_core_map))
7049                         continue;
7050
7051                 init_sched_build_groups(this_core_map, cpu_map,
7052                                         &cpu_to_core_group,
7053                                         send_covered, tmpmask);
7054         }
7055 #endif
7056
7057         /* Set up physical groups */
7058         for (i = 0; i < MAX_NUMNODES; i++) {
7059                 SCHED_CPUMASK_VAR(nodemask, allmasks);
7060                 SCHED_CPUMASK_VAR(send_covered, allmasks);
7061
7062                 *nodemask = node_to_cpumask(i);
7063                 cpus_and(*nodemask, *nodemask, *cpu_map);
7064                 if (cpus_empty(*nodemask))
7065                         continue;
7066
7067                 init_sched_build_groups(nodemask, cpu_map,
7068                                         &cpu_to_phys_group,
7069                                         send_covered, tmpmask);
7070         }
7071
7072 #ifdef CONFIG_NUMA
7073         /* Set up node groups */
7074         if (sd_allnodes) {
7075                 SCHED_CPUMASK_VAR(send_covered, allmasks);
7076
7077                 init_sched_build_groups(cpu_map, cpu_map,
7078                                         &cpu_to_allnodes_group,
7079                                         send_covered, tmpmask);
7080         }
7081
7082         for (i = 0; i < MAX_NUMNODES; i++) {
7083                 /* Set up node groups */
7084                 struct sched_group *sg, *prev;
7085                 SCHED_CPUMASK_VAR(nodemask, allmasks);
7086                 SCHED_CPUMASK_VAR(domainspan, allmasks);
7087                 SCHED_CPUMASK_VAR(covered, allmasks);
7088                 int j;
7089
7090                 *nodemask = node_to_cpumask(i);
7091                 cpus_clear(*covered);
7092
7093                 cpus_and(*nodemask, *nodemask, *cpu_map);
7094                 if (cpus_empty(*nodemask)) {
7095                         sched_group_nodes[i] = NULL;
7096                         continue;
7097                 }
7098
7099                 sched_domain_node_span(i, domainspan);
7100                 cpus_and(*domainspan, *domainspan, *cpu_map);
7101
7102                 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
7103                 if (!sg) {
7104                         printk(KERN_WARNING "Can not alloc domain group for "
7105                                 "node %d\n", i);
7106                         goto error;
7107                 }
7108                 sched_group_nodes[i] = sg;
7109                 for_each_cpu_mask(j, *nodemask) {
7110                         struct sched_domain *sd;
7111
7112                         sd = &per_cpu(node_domains, j);
7113                         sd->groups = sg;
7114                 }
7115                 sg->__cpu_power = 0;
7116                 sg->cpumask = *nodemask;
7117                 sg->next = sg;
7118                 cpus_or(*covered, *covered, *nodemask);
7119                 prev = sg;
7120
7121                 for (j = 0; j < MAX_NUMNODES; j++) {
7122                         SCHED_CPUMASK_VAR(notcovered, allmasks);
7123                         int n = (i + j) % MAX_NUMNODES;
7124                         node_to_cpumask_ptr(pnodemask, n);
7125
7126                         cpus_complement(*notcovered, *covered);
7127                         cpus_and(*tmpmask, *notcovered, *cpu_map);
7128                         cpus_and(*tmpmask, *tmpmask, *domainspan);
7129                         if (cpus_empty(*tmpmask))
7130                                 break;
7131
7132                         cpus_and(*tmpmask, *tmpmask, *pnodemask);
7133                         if (cpus_empty(*tmpmask))
7134                                 continue;
7135
7136                         sg = kmalloc_node(sizeof(struct sched_group),
7137                                           GFP_KERNEL, i);
7138                         if (!sg) {
7139                                 printk(KERN_WARNING
7140                                 "Can not alloc domain group for node %d\n", j);
7141                                 goto error;
7142                         }
7143                         sg->__cpu_power = 0;
7144                         sg->cpumask = *tmpmask;
7145                         sg->next = prev->next;
7146                         cpus_or(*covered, *covered, *tmpmask);
7147                         prev->next = sg;
7148                         prev = sg;
7149                 }
7150         }
7151 #endif
7152
7153         /* Calculate CPU power for physical packages and nodes */
7154 #ifdef CONFIG_SCHED_SMT
7155         for_each_cpu_mask(i, *cpu_map) {
7156                 struct sched_domain *sd = &per_cpu(cpu_domains, i);
7157
7158                 init_sched_groups_power(i, sd);
7159         }
7160 #endif
7161 #ifdef CONFIG_SCHED_MC
7162         for_each_cpu_mask(i, *cpu_map) {
7163                 struct sched_domain *sd = &per_cpu(core_domains, i);
7164
7165                 init_sched_groups_power(i, sd);
7166         }
7167 #endif
7168
7169         for_each_cpu_mask(i, *cpu_map) {
7170                 struct sched_domain *sd = &per_cpu(phys_domains, i);
7171
7172                 init_sched_groups_power(i, sd);
7173         }
7174
7175 #ifdef CONFIG_NUMA
7176         for (i = 0; i < MAX_NUMNODES; i++)
7177                 init_numa_sched_groups_power(sched_group_nodes[i]);
7178
7179         if (sd_allnodes) {
7180                 struct sched_group *sg;
7181
7182                 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg,
7183                                                                 tmpmask);
7184                 init_numa_sched_groups_power(sg);
7185         }
7186 #endif
7187
7188         /* Attach the domains */
7189         for_each_cpu_mask(i, *cpu_map) {
7190                 struct sched_domain *sd;
7191 #ifdef CONFIG_SCHED_SMT
7192                 sd = &per_cpu(cpu_domains, i);
7193 #elif defined(CONFIG_SCHED_MC)
7194                 sd = &per_cpu(core_domains, i);
7195 #else
7196                 sd = &per_cpu(phys_domains, i);
7197 #endif
7198                 cpu_attach_domain(sd, rd, i);
7199         }
7200
7201         SCHED_CPUMASK_FREE((void *)allmasks);
7202         return 0;
7203
7204 #ifdef CONFIG_NUMA
7205 error:
7206         free_sched_groups(cpu_map, tmpmask);
7207         SCHED_CPUMASK_FREE((void *)allmasks);
7208         return -ENOMEM;
7209 #endif
7210 }
7211
7212 static int build_sched_domains(const cpumask_t *cpu_map)
7213 {
7214         return __build_sched_domains(cpu_map, NULL);
7215 }
7216
7217 static cpumask_t *doms_cur;     /* current sched domains */
7218 static int ndoms_cur;           /* number of sched domains in 'doms_cur' */
7219 static struct sched_domain_attr *dattr_cur;
7220                                 /* attribues of custom domains in 'doms_cur' */
7221
7222 /*
7223  * Special case: If a kmalloc of a doms_cur partition (array of
7224  * cpumask_t) fails, then fallback to a single sched domain,
7225  * as determined by the single cpumask_t fallback_doms.
7226  */
7227 static cpumask_t fallback_doms;
7228
7229 void __attribute__((weak)) arch_update_cpu_topology(void)
7230 {
7231 }
7232
7233 /*
7234  * Set up scheduler domains and groups. Callers must hold the hotplug lock.
7235  * For now this just excludes isolated cpus, but could be used to
7236  * exclude other special cases in the future.
7237  */
7238 static int arch_init_sched_domains(const cpumask_t *cpu_map)
7239 {
7240         int err;
7241
7242         arch_update_cpu_topology();
7243         ndoms_cur = 1;
7244         doms_cur = kmalloc(sizeof(cpumask_t), GFP_KERNEL);
7245         if (!doms_cur)
7246                 doms_cur = &fallback_doms;
7247         cpus_andnot(*doms_cur, *cpu_map, cpu_isolated_map);
7248         dattr_cur = NULL;
7249         err = build_sched_domains(doms_cur);
7250         register_sched_domain_sysctl();
7251
7252         return err;
7253 }
7254
7255 static void arch_destroy_sched_domains(const cpumask_t *cpu_map,
7256                                        cpumask_t *tmpmask)
7257 {
7258         free_sched_groups(cpu_map, tmpmask);
7259 }
7260
7261 /*
7262  * Detach sched domains from a group of cpus specified in cpu_map
7263  * These cpus will now be attached to the NULL domain
7264  */
7265 static void detach_destroy_domains(const cpumask_t *cpu_map)
7266 {
7267         cpumask_t tmpmask;
7268         int i;
7269
7270         unregister_sched_domain_sysctl();
7271
7272         for_each_cpu_mask(i, *cpu_map)
7273                 cpu_attach_domain(NULL, &def_root_domain, i);
7274         synchronize_sched();
7275         arch_destroy_sched_domains(cpu_map, &tmpmask);
7276 }
7277
7278 /* handle null as "default" */
7279 static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur,
7280                         struct sched_domain_attr *new, int idx_new)
7281 {
7282         struct sched_domain_attr tmp;
7283
7284         /* fast path */
7285         if (!new && !cur)
7286                 return 1;
7287
7288         tmp = SD_ATTR_INIT;
7289         return !memcmp(cur ? (cur + idx_cur) : &tmp,
7290                         new ? (new + idx_new) : &tmp,
7291                         sizeof(struct sched_domain_attr));
7292 }
7293
7294 /*
7295  * Partition sched domains as specified by the 'ndoms_new'
7296  * cpumasks in the array doms_new[] of cpumasks. This compares
7297  * doms_new[] to the current sched domain partitioning, doms_cur[].
7298  * It destroys each deleted domain and builds each new domain.
7299  *
7300  * 'doms_new' is an array of cpumask_t's of length 'ndoms_new'.
7301  * The masks don't intersect (don't overlap.) We should setup one
7302  * sched domain for each mask. CPUs not in any of the cpumasks will
7303  * not be load balanced. If the same cpumask appears both in the
7304  * current 'doms_cur' domains and in the new 'doms_new', we can leave
7305  * it as it is.
7306  *
7307  * The passed in 'doms_new' should be kmalloc'd. This routine takes
7308  * ownership of it and will kfree it when done with it. If the caller
7309  * failed the kmalloc call, then it can pass in doms_new == NULL,
7310  * and partition_sched_domains() will fallback to the single partition
7311  * 'fallback_doms'.
7312  *
7313  * Call with hotplug lock held
7314  */
7315 void partition_sched_domains(int ndoms_new, cpumask_t *doms_new,
7316                              struct sched_domain_attr *dattr_new)
7317 {
7318         int i, j;
7319
7320         mutex_lock(&sched_domains_mutex);
7321
7322         /* always unregister in case we don't destroy any domains */
7323         unregister_sched_domain_sysctl();
7324
7325         if (doms_new == NULL) {
7326                 ndoms_new = 1;
7327                 doms_new = &fallback_doms;
7328                 cpus_andnot(doms_new[0], cpu_online_map, cpu_isolated_map);
7329                 dattr_new = NULL;
7330         }
7331
7332         /* Destroy deleted domains */
7333         for (i = 0; i < ndoms_cur; i++) {
7334                 for (j = 0; j < ndoms_new; j++) {
7335                         if (cpus_equal(doms_cur[i], doms_new[j])
7336                             && dattrs_equal(dattr_cur, i, dattr_new, j))
7337                                 goto match1;
7338                 }
7339                 /* no match - a current sched domain not in new doms_new[] */
7340                 detach_destroy_domains(doms_cur + i);
7341 match1:
7342                 ;
7343         }
7344
7345         /* Build new domains */
7346         for (i = 0; i < ndoms_new; i++) {
7347                 for (j = 0; j < ndoms_cur; j++) {
7348                         if (cpus_equal(doms_new[i], doms_cur[j])
7349                             && dattrs_equal(dattr_new, i, dattr_cur, j))
7350                                 goto match2;
7351                 }
7352                 /* no match - add a new doms_new */
7353                 __build_sched_domains(doms_new + i,
7354                                         dattr_new ? dattr_new + i : NULL);
7355 match2:
7356                 ;
7357         }
7358
7359         /* Remember the new sched domains */
7360         if (doms_cur != &fallback_doms)
7361                 kfree(doms_cur);
7362         kfree(dattr_cur);       /* kfree(NULL) is safe */
7363         doms_cur = doms_new;
7364         dattr_cur = dattr_new;
7365         ndoms_cur = ndoms_new;
7366
7367         register_sched_domain_sysctl();
7368
7369         mutex_unlock(&sched_domains_mutex);
7370 }
7371
7372 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
7373 int arch_reinit_sched_domains(void)
7374 {
7375         int err;
7376
7377         get_online_cpus();
7378         mutex_lock(&sched_domains_mutex);
7379         detach_destroy_domains(&cpu_online_map);
7380         err = arch_init_sched_domains(&cpu_online_map);
7381         mutex_unlock(&sched_domains_mutex);
7382         put_online_cpus();
7383
7384         return err;
7385 }
7386
7387 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
7388 {
7389         int ret;
7390
7391         if (buf[0] != '0' && buf[0] != '1')
7392                 return -EINVAL;
7393
7394         if (smt)
7395                 sched_smt_power_savings = (buf[0] == '1');
7396         else
7397                 sched_mc_power_savings = (buf[0] == '1');
7398
7399         ret = arch_reinit_sched_domains();
7400
7401         return ret ? ret : count;
7402 }
7403
7404 #ifdef CONFIG_SCHED_MC
7405 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
7406 {
7407         return sprintf(page, "%u\n", sched_mc_power_savings);
7408 }
7409 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
7410                                             const char *buf, size_t count)
7411 {
7412         return sched_power_savings_store(buf, count, 0);
7413 }
7414 static SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
7415                    sched_mc_power_savings_store);
7416 #endif
7417
7418 #ifdef CONFIG_SCHED_SMT
7419 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
7420 {
7421         return sprintf(page, "%u\n", sched_smt_power_savings);
7422 }
7423 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
7424                                              const char *buf, size_t count)
7425 {
7426         return sched_power_savings_store(buf, count, 1);
7427 }
7428 static SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
7429                    sched_smt_power_savings_store);
7430 #endif
7431
7432 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
7433 {
7434         int err = 0;
7435
7436 #ifdef CONFIG_SCHED_SMT
7437         if (smt_capable())
7438                 err = sysfs_create_file(&cls->kset.kobj,
7439                                         &attr_sched_smt_power_savings.attr);
7440 #endif
7441 #ifdef CONFIG_SCHED_MC
7442         if (!err && mc_capable())
7443                 err = sysfs_create_file(&cls->kset.kobj,
7444                                         &attr_sched_mc_power_savings.attr);
7445 #endif
7446         return err;
7447 }
7448 #endif
7449
7450 /*
7451  * Force a reinitialization of the sched domains hierarchy. The domains
7452  * and groups cannot be updated in place without racing with the balancing
7453  * code, so we temporarily attach all running cpus to the NULL domain
7454  * which will prevent rebalancing while the sched domains are recalculated.
7455  */
7456 static int update_sched_domains(struct notifier_block *nfb,
7457                                 unsigned long action, void *hcpu)
7458 {
7459         switch (action) {
7460         case CPU_UP_PREPARE:
7461         case CPU_UP_PREPARE_FROZEN:
7462         case CPU_DOWN_PREPARE:
7463         case CPU_DOWN_PREPARE_FROZEN:
7464                 detach_destroy_domains(&cpu_online_map);
7465                 return NOTIFY_OK;
7466
7467         case CPU_UP_CANCELED:
7468         case CPU_UP_CANCELED_FROZEN:
7469         case CPU_DOWN_FAILED:
7470         case CPU_DOWN_FAILED_FROZEN:
7471         case CPU_ONLINE:
7472         case CPU_ONLINE_FROZEN:
7473         case CPU_DEAD:
7474         case CPU_DEAD_FROZEN:
7475                 /*
7476                  * Fall through and re-initialise the domains.
7477                  */
7478                 break;
7479         default:
7480                 return NOTIFY_DONE;
7481         }
7482
7483         /* The hotplug lock is already held by cpu_up/cpu_down */
7484         arch_init_sched_domains(&cpu_online_map);
7485
7486         return NOTIFY_OK;
7487 }
7488
7489 void __init sched_init_smp(void)
7490 {
7491         cpumask_t non_isolated_cpus;
7492
7493 #if defined(CONFIG_NUMA)
7494         sched_group_nodes_bycpu = kzalloc(nr_cpu_ids * sizeof(void **),
7495                                                                 GFP_KERNEL);
7496         BUG_ON(sched_group_nodes_bycpu == NULL);
7497 #endif
7498         get_online_cpus();
7499         mutex_lock(&sched_domains_mutex);
7500         arch_init_sched_domains(&cpu_online_map);
7501         cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
7502         if (cpus_empty(non_isolated_cpus))
7503                 cpu_set(smp_processor_id(), non_isolated_cpus);
7504         mutex_unlock(&sched_domains_mutex);
7505         put_online_cpus();
7506         /* XXX: Theoretical race here - CPU may be hotplugged now */
7507         hotcpu_notifier(update_sched_domains, 0);
7508         init_hrtick();
7509
7510         /* Move init over to a non-isolated CPU */
7511         if (set_cpus_allowed_ptr(current, &non_isolated_cpus) < 0)
7512                 BUG();
7513         sched_init_granularity();
7514 }
7515 #else
7516 void __init sched_init_smp(void)
7517 {
7518         sched_init_granularity();
7519 }
7520 #endif /* CONFIG_SMP */
7521
7522 int in_sched_functions(unsigned long addr)
7523 {
7524         return in_lock_functions(addr) ||
7525                 (addr >= (unsigned long)__sched_text_start
7526                 && addr < (unsigned long)__sched_text_end);
7527 }
7528
7529 static void init_cfs_rq(struct cfs_rq *cfs_rq, struct rq *rq)
7530 {
7531         cfs_rq->tasks_timeline = RB_ROOT;
7532         INIT_LIST_HEAD(&cfs_rq->tasks);
7533 #ifdef CONFIG_FAIR_GROUP_SCHED
7534         cfs_rq->rq = rq;
7535 #endif
7536         cfs_rq->min_vruntime = (u64)(-(1LL << 20));
7537 }
7538
7539 static void init_rt_rq(struct rt_rq *rt_rq, struct rq *rq)
7540 {
7541         struct rt_prio_array *array;
7542         int i;
7543
7544         array = &rt_rq->active;
7545         for (i = 0; i < MAX_RT_PRIO; i++) {
7546                 INIT_LIST_HEAD(array->xqueue + i);
7547                 INIT_LIST_HEAD(array->squeue + i);
7548                 __clear_bit(i, array->bitmap);
7549         }
7550         /* delimiter for bitsearch: */
7551         __set_bit(MAX_RT_PRIO, array->bitmap);
7552
7553 #if defined CONFIG_SMP || defined CONFIG_RT_GROUP_SCHED
7554         rt_rq->highest_prio = MAX_RT_PRIO;
7555 #endif
7556 #ifdef CONFIG_SMP
7557         rt_rq->rt_nr_migratory = 0;
7558         rt_rq->overloaded = 0;
7559 #endif
7560
7561         rt_rq->rt_time = 0;
7562         rt_rq->rt_throttled = 0;
7563         rt_rq->rt_runtime = 0;
7564         spin_lock_init(&rt_rq->rt_runtime_lock);
7565
7566 #ifdef CONFIG_RT_GROUP_SCHED
7567         rt_rq->rt_nr_boosted = 0;
7568         rt_rq->rq = rq;
7569 #endif
7570 }
7571
7572 #ifdef CONFIG_FAIR_GROUP_SCHED
7573 static void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq,
7574                                 struct sched_entity *se, int cpu, int add,
7575                                 struct sched_entity *parent)
7576 {
7577         struct rq *rq = cpu_rq(cpu);
7578         tg->cfs_rq[cpu] = cfs_rq;
7579         init_cfs_rq(cfs_rq, rq);
7580         cfs_rq->tg = tg;
7581         if (add)
7582                 list_add(&cfs_rq->leaf_cfs_rq_list, &rq->leaf_cfs_rq_list);
7583
7584         tg->se[cpu] = se;
7585         /* se could be NULL for init_task_group */
7586         if (!se)
7587                 return;
7588
7589         if (!parent)
7590                 se->cfs_rq = &rq->cfs;
7591         else
7592                 se->cfs_rq = parent->my_q;
7593
7594         se->my_q = cfs_rq;
7595         se->load.weight = tg->shares;
7596         se->load.inv_weight = 0;
7597         se->parent = parent;
7598 }
7599 #endif
7600
7601 #ifdef CONFIG_RT_GROUP_SCHED
7602 static void init_tg_rt_entry(struct task_group *tg, struct rt_rq *rt_rq,
7603                 struct sched_rt_entity *rt_se, int cpu, int add,
7604                 struct sched_rt_entity *parent)
7605 {
7606         struct rq *rq = cpu_rq(cpu);
7607
7608         tg->rt_rq[cpu] = rt_rq;
7609         init_rt_rq(rt_rq, rq);
7610         rt_rq->tg = tg;
7611         rt_rq->rt_se = rt_se;
7612         rt_rq->rt_runtime = tg->rt_bandwidth.rt_runtime;
7613         if (add)
7614                 list_add(&rt_rq->leaf_rt_rq_list, &rq->leaf_rt_rq_list);
7615
7616         tg->rt_se[cpu] = rt_se;
7617         if (!rt_se)
7618                 return;
7619
7620         if (!parent)
7621                 rt_se->rt_rq = &rq->rt;
7622         else
7623                 rt_se->rt_rq = parent->my_q;
7624
7625         rt_se->rt_rq = &rq->rt;
7626         rt_se->my_q = rt_rq;
7627         rt_se->parent = parent;
7628         INIT_LIST_HEAD(&rt_se->run_list);
7629 }
7630 #endif
7631
7632 void __init sched_init(void)
7633 {
7634         int i, j;
7635         unsigned long alloc_size = 0, ptr;
7636
7637 #ifdef CONFIG_FAIR_GROUP_SCHED
7638         alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7639 #endif
7640 #ifdef CONFIG_RT_GROUP_SCHED
7641         alloc_size += 2 * nr_cpu_ids * sizeof(void **);
7642 #endif
7643 #ifdef CONFIG_USER_SCHED
7644         alloc_size *= 2;
7645 #endif
7646         /*
7647          * As sched_init() is called before page_alloc is setup,
7648          * we use alloc_bootmem().
7649          */
7650         if (alloc_size) {
7651                 ptr = (unsigned long)alloc_bootmem(alloc_size);
7652
7653 #ifdef CONFIG_FAIR_GROUP_SCHED
7654                 init_task_group.se = (struct sched_entity **)ptr;
7655                 ptr += nr_cpu_ids * sizeof(void **);
7656
7657                 init_task_group.cfs_rq = (struct cfs_rq **)ptr;
7658                 ptr += nr_cpu_ids * sizeof(void **);
7659
7660 #ifdef CONFIG_USER_SCHED
7661                 root_task_group.se = (struct sched_entity **)ptr;
7662                 ptr += nr_cpu_ids * sizeof(void **);
7663
7664                 root_task_group.cfs_rq = (struct cfs_rq **)ptr;
7665                 ptr += nr_cpu_ids * sizeof(void **);
7666 #endif
7667 #endif
7668 #ifdef CONFIG_RT_GROUP_SCHED
7669                 init_task_group.rt_se = (struct sched_rt_entity **)ptr;
7670                 ptr += nr_cpu_ids * sizeof(void **);
7671
7672                 init_task_group.rt_rq = (struct rt_rq **)ptr;
7673                 ptr += nr_cpu_ids * sizeof(void **);
7674
7675 #ifdef CONFIG_USER_SCHED
7676                 root_task_group.rt_se = (struct sched_rt_entity **)ptr;
7677                 ptr += nr_cpu_ids * sizeof(void **);
7678
7679                 root_task_group.rt_rq = (struct rt_rq **)ptr;
7680                 ptr += nr_cpu_ids * sizeof(void **);
7681 #endif
7682 #endif
7683         }
7684
7685 #ifdef CONFIG_SMP
7686         init_defrootdomain();
7687 #endif
7688
7689         init_rt_bandwidth(&def_rt_bandwidth,
7690                         global_rt_period(), global_rt_runtime());
7691
7692 #ifdef CONFIG_RT_GROUP_SCHED
7693         init_rt_bandwidth(&init_task_group.rt_bandwidth,
7694                         global_rt_period(), global_rt_runtime());
7695 #ifdef CONFIG_USER_SCHED
7696         init_rt_bandwidth(&root_task_group.rt_bandwidth,
7697                         global_rt_period(), RUNTIME_INF);
7698 #endif
7699 #endif
7700
7701 #ifdef CONFIG_GROUP_SCHED
7702         list_add(&init_task_group.list, &task_groups);
7703         INIT_LIST_HEAD(&init_task_group.children);
7704
7705 #ifdef CONFIG_USER_SCHED
7706         INIT_LIST_HEAD(&root_task_group.children);
7707         init_task_group.parent = &root_task_group;
7708         list_add(&init_task_group.siblings, &root_task_group.children);
7709 #endif
7710 #endif
7711
7712         for_each_possible_cpu(i) {
7713                 struct rq *rq;
7714
7715                 rq = cpu_rq(i);
7716                 spin_lock_init(&rq->lock);
7717                 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
7718                 rq->nr_running = 0;
7719                 init_cfs_rq(&rq->cfs, rq);
7720                 init_rt_rq(&rq->rt, rq);
7721 #ifdef CONFIG_FAIR_GROUP_SCHED
7722                 init_task_group.shares = init_task_group_load;
7723                 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7724 #ifdef CONFIG_CGROUP_SCHED
7725                 /*
7726                  * How much cpu bandwidth does init_task_group get?
7727                  *
7728                  * In case of task-groups formed thr' the cgroup filesystem, it
7729                  * gets 100% of the cpu resources in the system. This overall
7730                  * system cpu resource is divided among the tasks of
7731                  * init_task_group and its child task-groups in a fair manner,
7732                  * based on each entity's (task or task-group's) weight
7733                  * (se->load.weight).
7734                  *
7735                  * In other words, if init_task_group has 10 tasks of weight
7736                  * 1024) and two child groups A0 and A1 (of weight 1024 each),
7737                  * then A0's share of the cpu resource is:
7738                  *
7739                  *      A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
7740                  *
7741                  * We achieve this by letting init_task_group's tasks sit
7742                  * directly in rq->cfs (i.e init_task_group->se[] = NULL).
7743                  */
7744                 init_tg_cfs_entry(&init_task_group, &rq->cfs, NULL, i, 1, NULL);
7745 #elif defined CONFIG_USER_SCHED
7746                 root_task_group.shares = NICE_0_LOAD;
7747                 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, 0, NULL);
7748                 /*
7749                  * In case of task-groups formed thr' the user id of tasks,
7750                  * init_task_group represents tasks belonging to root user.
7751                  * Hence it forms a sibling of all subsequent groups formed.
7752                  * In this case, init_task_group gets only a fraction of overall
7753                  * system cpu resource, based on the weight assigned to root
7754                  * user's cpu share (INIT_TASK_GROUP_LOAD). This is accomplished
7755                  * by letting tasks of init_task_group sit in a separate cfs_rq
7756                  * (init_cfs_rq) and having one entity represent this group of
7757                  * tasks in rq->cfs (i.e init_task_group->se[] != NULL).
7758                  */
7759                 init_tg_cfs_entry(&init_task_group,
7760                                 &per_cpu(init_cfs_rq, i),
7761                                 &per_cpu(init_sched_entity, i), i, 1,
7762                                 root_task_group.se[i]);
7763
7764 #endif
7765 #endif /* CONFIG_FAIR_GROUP_SCHED */
7766
7767                 rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
7768 #ifdef CONFIG_RT_GROUP_SCHED
7769                 INIT_LIST_HEAD(&rq->leaf_rt_rq_list);
7770 #ifdef CONFIG_CGROUP_SCHED
7771                 init_tg_rt_entry(&init_task_group, &rq->rt, NULL, i, 1, NULL);
7772 #elif defined CONFIG_USER_SCHED
7773                 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, 0, NULL);
7774                 init_tg_rt_entry(&init_task_group,
7775                                 &per_cpu(init_rt_rq, i),
7776                                 &per_cpu(init_sched_rt_entity, i), i, 1,
7777                                 root_task_group.rt_se[i]);
7778 #endif
7779 #endif
7780
7781                 for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
7782                         rq->cpu_load[j] = 0;
7783 #ifdef CONFIG_SMP
7784                 rq->sd = NULL;
7785                 rq->rd = NULL;
7786                 rq->active_balance = 0;
7787                 rq->next_balance = jiffies;
7788                 rq->push_cpu = 0;
7789                 rq->cpu = i;
7790                 rq->migration_thread = NULL;
7791                 INIT_LIST_HEAD(&rq->migration_queue);
7792                 rq_attach_root(rq, &def_root_domain);
7793 #endif
7794                 init_rq_hrtick(rq);
7795                 atomic_set(&rq->nr_iowait, 0);
7796         }
7797
7798         set_load_weight(&init_task);
7799
7800 #ifdef CONFIG_PREEMPT_NOTIFIERS
7801         INIT_HLIST_HEAD(&init_task.preempt_notifiers);
7802 #endif
7803
7804 #ifdef CONFIG_SMP
7805         open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
7806 #endif
7807
7808 #ifdef CONFIG_RT_MUTEXES
7809         plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
7810 #endif
7811
7812         /*
7813          * The boot idle thread does lazy MMU switching as well:
7814          */
7815         atomic_inc(&init_mm.mm_count);
7816         enter_lazy_tlb(&init_mm, current);
7817
7818         /*
7819          * Make us the idle thread. Technically, schedule() should not be
7820          * called from this thread, however somewhere below it might be,
7821          * but because we are the idle thread, we just pick up running again
7822          * when this runqueue becomes "idle".
7823          */
7824         init_idle(current, smp_processor_id());
7825         /*
7826          * During early bootup we pretend to be a normal task:
7827          */
7828         current->sched_class = &fair_sched_class;
7829
7830         scheduler_running = 1;
7831 }
7832
7833 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
7834 void __might_sleep(char *file, int line)
7835 {
7836 #ifdef in_atomic
7837         static unsigned long prev_jiffy;        /* ratelimiting */
7838
7839         if ((in_atomic() || irqs_disabled()) &&
7840             system_state == SYSTEM_RUNNING && !oops_in_progress) {
7841                 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7842                         return;
7843                 prev_jiffy = jiffies;
7844                 printk(KERN_ERR "BUG: sleeping function called from invalid"
7845                                 " context at %s:%d\n", file, line);
7846                 printk("in_atomic():%d, irqs_disabled():%d\n",
7847                         in_atomic(), irqs_disabled());
7848                 debug_show_held_locks(current);
7849                 if (irqs_disabled())
7850                         print_irqtrace_events(current);
7851                 dump_stack();
7852         }
7853 #endif
7854 }
7855 EXPORT_SYMBOL(__might_sleep);
7856 #endif
7857
7858 #ifdef CONFIG_MAGIC_SYSRQ
7859 static void normalize_task(struct rq *rq, struct task_struct *p)
7860 {
7861         int on_rq;
7862
7863         update_rq_clock(rq);
7864         on_rq = p->se.on_rq;
7865         if (on_rq)
7866                 deactivate_task(rq, p, 0);
7867         __setscheduler(rq, p, SCHED_NORMAL, 0);
7868         if (on_rq) {
7869                 activate_task(rq, p, 0);
7870                 resched_task(rq->curr);
7871         }
7872 }
7873
7874 void normalize_rt_tasks(void)
7875 {
7876         struct task_struct *g, *p;
7877         unsigned long flags;
7878         struct rq *rq;
7879
7880         read_lock_irqsave(&tasklist_lock, flags);
7881         do_each_thread(g, p) {
7882                 /*
7883                  * Only normalize user tasks:
7884                  */
7885                 if (!p->mm)
7886                         continue;
7887
7888                 p->se.exec_start                = 0;
7889 #ifdef CONFIG_SCHEDSTATS
7890                 p->se.wait_start                = 0;
7891                 p->se.sleep_start               = 0;
7892                 p->se.block_start               = 0;
7893 #endif
7894
7895                 if (!rt_task(p)) {
7896                         /*
7897                          * Renice negative nice level userspace
7898                          * tasks back to 0:
7899                          */
7900                         if (TASK_NICE(p) < 0 && p->mm)
7901                                 set_user_nice(p, 0);
7902                         continue;
7903                 }
7904
7905                 spin_lock(&p->pi_lock);
7906                 rq = __task_rq_lock(p);
7907
7908                 normalize_task(rq, p);
7909
7910                 __task_rq_unlock(rq);
7911                 spin_unlock(&p->pi_lock);
7912         } while_each_thread(g, p);
7913
7914         read_unlock_irqrestore(&tasklist_lock, flags);
7915 }
7916
7917 #endif /* CONFIG_MAGIC_SYSRQ */
7918
7919 #ifdef CONFIG_IA64
7920 /*
7921  * These functions are only useful for the IA64 MCA handling.
7922  *
7923  * They can only be called when the whole system has been
7924  * stopped - every CPU needs to be quiescent, and no scheduling
7925  * activity can take place. Using them for anything else would
7926  * be a serious bug, and as a result, they aren't even visible
7927  * under any other configuration.
7928  */
7929
7930 /**
7931  * curr_task - return the current task for a given cpu.
7932  * @cpu: the processor in question.
7933  *
7934  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7935  */
7936 struct task_struct *curr_task(int cpu)
7937 {
7938         return cpu_curr(cpu);
7939 }
7940
7941 /**
7942  * set_curr_task - set the current task for a given cpu.
7943  * @cpu: the processor in question.
7944  * @p: the task pointer to set.
7945  *
7946  * Description: This function must only be used when non-maskable interrupts
7947  * are serviced on a separate stack. It allows the architecture to switch the
7948  * notion of the current task on a cpu in a non-blocking manner. This function
7949  * must be called with all CPU's synchronized, and interrupts disabled, the
7950  * and caller must save the original value of the current task (see
7951  * curr_task() above) and restore that value before reenabling interrupts and
7952  * re-starting the system.
7953  *
7954  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7955  */
7956 void set_curr_task(int cpu, struct task_struct *p)
7957 {
7958         cpu_curr(cpu) = p;
7959 }
7960
7961 #endif
7962
7963 #ifdef CONFIG_FAIR_GROUP_SCHED
7964 static void free_fair_sched_group(struct task_group *tg)
7965 {
7966         int i;
7967
7968         for_each_possible_cpu(i) {
7969                 if (tg->cfs_rq)
7970                         kfree(tg->cfs_rq[i]);
7971                 if (tg->se)
7972                         kfree(tg->se[i]);
7973         }
7974
7975         kfree(tg->cfs_rq);
7976         kfree(tg->se);
7977 }
7978
7979 static
7980 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
7981 {
7982         struct cfs_rq *cfs_rq;
7983         struct sched_entity *se, *parent_se;
7984         struct rq *rq;
7985         int i;
7986
7987         tg->cfs_rq = kzalloc(sizeof(cfs_rq) * nr_cpu_ids, GFP_KERNEL);
7988         if (!tg->cfs_rq)
7989                 goto err;
7990         tg->se = kzalloc(sizeof(se) * nr_cpu_ids, GFP_KERNEL);
7991         if (!tg->se)
7992                 goto err;
7993
7994         tg->shares = NICE_0_LOAD;
7995
7996         for_each_possible_cpu(i) {
7997                 rq = cpu_rq(i);
7998
7999                 cfs_rq = kmalloc_node(sizeof(struct cfs_rq),
8000                                 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8001                 if (!cfs_rq)
8002                         goto err;
8003
8004                 se = kmalloc_node(sizeof(struct sched_entity),
8005                                 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8006                 if (!se)
8007                         goto err;
8008
8009                 parent_se = parent ? parent->se[i] : NULL;
8010                 init_tg_cfs_entry(tg, cfs_rq, se, i, 0, parent_se);
8011         }
8012
8013         return 1;
8014
8015  err:
8016         return 0;
8017 }
8018
8019 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8020 {
8021         list_add_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list,
8022                         &cpu_rq(cpu)->leaf_cfs_rq_list);
8023 }
8024
8025 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8026 {
8027         list_del_rcu(&tg->cfs_rq[cpu]->leaf_cfs_rq_list);
8028 }
8029 #else
8030 static inline void free_fair_sched_group(struct task_group *tg)
8031 {
8032 }
8033
8034 static inline
8035 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent)
8036 {
8037         return 1;
8038 }
8039
8040 static inline void register_fair_sched_group(struct task_group *tg, int cpu)
8041 {
8042 }
8043
8044 static inline void unregister_fair_sched_group(struct task_group *tg, int cpu)
8045 {
8046 }
8047 #endif
8048
8049 #ifdef CONFIG_RT_GROUP_SCHED
8050 static void free_rt_sched_group(struct task_group *tg)
8051 {
8052         int i;
8053
8054         destroy_rt_bandwidth(&tg->rt_bandwidth);
8055
8056         for_each_possible_cpu(i) {
8057                 if (tg->rt_rq)
8058                         kfree(tg->rt_rq[i]);
8059                 if (tg->rt_se)
8060                         kfree(tg->rt_se[i]);
8061         }
8062
8063         kfree(tg->rt_rq);
8064         kfree(tg->rt_se);
8065 }
8066
8067 static
8068 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8069 {
8070         struct rt_rq *rt_rq;
8071         struct sched_rt_entity *rt_se, *parent_se;
8072         struct rq *rq;
8073         int i;
8074
8075         tg->rt_rq = kzalloc(sizeof(rt_rq) * nr_cpu_ids, GFP_KERNEL);
8076         if (!tg->rt_rq)
8077                 goto err;
8078         tg->rt_se = kzalloc(sizeof(rt_se) * nr_cpu_ids, GFP_KERNEL);
8079         if (!tg->rt_se)
8080                 goto err;
8081
8082         init_rt_bandwidth(&tg->rt_bandwidth,
8083                         ktime_to_ns(def_rt_bandwidth.rt_period), 0);
8084
8085         for_each_possible_cpu(i) {
8086                 rq = cpu_rq(i);
8087
8088                 rt_rq = kmalloc_node(sizeof(struct rt_rq),
8089                                 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8090                 if (!rt_rq)
8091                         goto err;
8092
8093                 rt_se = kmalloc_node(sizeof(struct sched_rt_entity),
8094                                 GFP_KERNEL|__GFP_ZERO, cpu_to_node(i));
8095                 if (!rt_se)
8096                         goto err;
8097
8098                 parent_se = parent ? parent->rt_se[i] : NULL;
8099                 init_tg_rt_entry(tg, rt_rq, rt_se, i, 0, parent_se);
8100         }
8101
8102         return 1;
8103
8104  err:
8105         return 0;
8106 }
8107
8108 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8109 {
8110         list_add_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list,
8111                         &cpu_rq(cpu)->leaf_rt_rq_list);
8112 }
8113
8114 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8115 {
8116         list_del_rcu(&tg->rt_rq[cpu]->leaf_rt_rq_list);
8117 }
8118 #else
8119 static inline void free_rt_sched_group(struct task_group *tg)
8120 {
8121 }
8122
8123 static inline
8124 int alloc_rt_sched_group(struct task_group *tg, struct task_group *parent)
8125 {
8126         return 1;
8127 }
8128
8129 static inline void register_rt_sched_group(struct task_group *tg, int cpu)
8130 {
8131 }
8132
8133 static inline void unregister_rt_sched_group(struct task_group *tg, int cpu)
8134 {
8135 }
8136 #endif
8137
8138 #ifdef CONFIG_GROUP_SCHED
8139 static void free_sched_group(struct task_group *tg)
8140 {
8141         free_fair_sched_group(tg);
8142         free_rt_sched_group(tg);
8143         kfree(tg);
8144 }
8145
8146 /* allocate runqueue etc for a new task group */
8147 struct task_group *sched_create_group(struct task_group *parent)
8148 {
8149         struct task_group *tg;
8150         unsigned long flags;
8151         int i;
8152
8153         tg = kzalloc(sizeof(*tg), GFP_KERNEL);
8154         if (!tg)
8155                 return ERR_PTR(-ENOMEM);
8156
8157         if (!alloc_fair_sched_group(tg, parent))
8158                 goto err;
8159
8160         if (!alloc_rt_sched_group(tg, parent))
8161                 goto err;
8162
8163         spin_lock_irqsave(&task_group_lock, flags);
8164         for_each_possible_cpu(i) {
8165                 register_fair_sched_group(tg, i);
8166                 register_rt_sched_group(tg, i);
8167         }
8168         list_add_rcu(&tg->list, &task_groups);
8169
8170         WARN_ON(!parent); /* root should already exist */
8171
8172         tg->parent = parent;
8173         list_add_rcu(&tg->siblings, &parent->children);
8174         INIT_LIST_HEAD(&tg->children);
8175         spin_unlock_irqrestore(&task_group_lock, flags);
8176
8177         return tg;
8178
8179 err:
8180         free_sched_group(tg);
8181         return ERR_PTR(-ENOMEM);
8182 }
8183
8184 /* rcu callback to free various structures associated with a task group */
8185 static void free_sched_group_rcu(struct rcu_head *rhp)
8186 {
8187         /* now it should be safe to free those cfs_rqs */
8188         free_sched_group(container_of(rhp, struct task_group, rcu));
8189 }
8190
8191 /* Destroy runqueue etc associated with a task group */
8192 void sched_destroy_group(struct task_group *tg)
8193 {
8194         unsigned long flags;
8195         int i;
8196
8197         spin_lock_irqsave(&task_group_lock, flags);
8198         for_each_possible_cpu(i) {
8199                 unregister_fair_sched_group(tg, i);
8200                 unregister_rt_sched_group(tg, i);
8201         }
8202         list_del_rcu(&tg->list);
8203         list_del_rcu(&tg->siblings);
8204         spin_unlock_irqrestore(&task_group_lock, flags);
8205
8206         /* wait for possible concurrent references to cfs_rqs complete */
8207         call_rcu(&tg->rcu, free_sched_group_rcu);
8208 }
8209
8210 /* change task's runqueue when it moves between groups.
8211  *      The caller of this function should have put the task in its new group
8212  *      by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to
8213  *      reflect its new group.
8214  */
8215 void sched_move_task(struct task_struct *tsk)
8216 {
8217         int on_rq, running;
8218         unsigned long flags;
8219         struct rq *rq;
8220
8221         rq = task_rq_lock(tsk, &flags);
8222
8223         update_rq_clock(rq);
8224
8225         running = task_current(rq, tsk);
8226         on_rq = tsk->se.on_rq;
8227
8228         if (on_rq)
8229                 dequeue_task(rq, tsk, 0);
8230         if (unlikely(running))
8231                 tsk->sched_class->put_prev_task(rq, tsk);
8232
8233         set_task_rq(tsk, task_cpu(tsk));
8234
8235 #ifdef CONFIG_FAIR_GROUP_SCHED
8236         if (tsk->sched_class->moved_group)
8237                 tsk->sched_class->moved_group(tsk);
8238 #endif
8239
8240         if (unlikely(running))
8241                 tsk->sched_class->set_curr_task(rq);
8242         if (on_rq)
8243                 enqueue_task(rq, tsk, 0);
8244
8245         task_rq_unlock(rq, &flags);
8246 }
8247 #endif
8248
8249 #ifdef CONFIG_FAIR_GROUP_SCHED
8250 static void set_se_shares(struct sched_entity *se, unsigned long shares)
8251 {
8252         struct cfs_rq *cfs_rq = se->cfs_rq;
8253         struct rq *rq = cfs_rq->rq;
8254         int on_rq;
8255
8256         spin_lock_irq(&rq->lock);
8257
8258         on_rq = se->on_rq;
8259         if (on_rq)
8260                 dequeue_entity(cfs_rq, se, 0);
8261
8262         se->load.weight = shares;
8263         se->load.inv_weight = 0;
8264
8265         if (on_rq)
8266                 enqueue_entity(cfs_rq, se, 0);
8267
8268         spin_unlock_irq(&rq->lock);
8269 }
8270
8271 static DEFINE_MUTEX(shares_mutex);
8272
8273 int sched_group_set_shares(struct task_group *tg, unsigned long shares)
8274 {
8275         int i;
8276         unsigned long flags;
8277
8278         /*
8279          * We can't change the weight of the root cgroup.
8280          */
8281         if (!tg->se[0])
8282                 return -EINVAL;
8283
8284         if (shares < MIN_SHARES)
8285                 shares = MIN_SHARES;
8286         else if (shares > MAX_SHARES)
8287                 shares = MAX_SHARES;
8288
8289         mutex_lock(&shares_mutex);
8290         if (tg->shares == shares)
8291                 goto done;
8292
8293         spin_lock_irqsave(&task_group_lock, flags);
8294         for_each_possible_cpu(i)
8295                 unregister_fair_sched_group(tg, i);
8296         list_del_rcu(&tg->siblings);
8297         spin_unlock_irqrestore(&task_group_lock, flags);
8298
8299         /* wait for any ongoing reference to this group to finish */
8300         synchronize_sched();
8301
8302         /*
8303          * Now we are free to modify the group's share on each cpu
8304          * w/o tripping rebalance_share or load_balance_fair.
8305          */
8306         tg->shares = shares;
8307         for_each_possible_cpu(i)
8308                 set_se_shares(tg->se[i], shares);
8309
8310         /*
8311          * Enable load balance activity on this group, by inserting it back on
8312          * each cpu's rq->leaf_cfs_rq_list.
8313          */
8314         spin_lock_irqsave(&task_group_lock, flags);
8315         for_each_possible_cpu(i)
8316                 register_fair_sched_group(tg, i);
8317         list_add_rcu(&tg->siblings, &tg->parent->children);
8318         spin_unlock_irqrestore(&task_group_lock, flags);
8319 done:
8320         mutex_unlock(&shares_mutex);
8321         return 0;
8322 }
8323
8324 unsigned long sched_group_shares(struct task_group *tg)
8325 {
8326         return tg->shares;
8327 }
8328 #endif
8329
8330 #ifdef CONFIG_RT_GROUP_SCHED
8331 /*
8332  * Ensure that the real time constraints are schedulable.
8333  */
8334 static DEFINE_MUTEX(rt_constraints_mutex);
8335
8336 static unsigned long to_ratio(u64 period, u64 runtime)
8337 {
8338         if (runtime == RUNTIME_INF)
8339                 return 1ULL << 16;
8340
8341         return div64_u64(runtime << 16, period);
8342 }
8343
8344 #ifdef CONFIG_CGROUP_SCHED
8345 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8346 {
8347         struct task_group *tgi, *parent = tg->parent;
8348         unsigned long total = 0;
8349
8350         if (!parent) {
8351                 if (global_rt_period() < period)
8352                         return 0;
8353
8354                 return to_ratio(period, runtime) <
8355                         to_ratio(global_rt_period(), global_rt_runtime());
8356         }
8357
8358         if (ktime_to_ns(parent->rt_bandwidth.rt_period) < period)
8359                 return 0;
8360
8361         rcu_read_lock();
8362         list_for_each_entry_rcu(tgi, &parent->children, siblings) {
8363                 if (tgi == tg)
8364                         continue;
8365
8366                 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
8367                                 tgi->rt_bandwidth.rt_runtime);
8368         }
8369         rcu_read_unlock();
8370
8371         return total + to_ratio(period, runtime) <
8372                 to_ratio(ktime_to_ns(parent->rt_bandwidth.rt_period),
8373                                 parent->rt_bandwidth.rt_runtime);
8374 }
8375 #elif defined CONFIG_USER_SCHED
8376 static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime)
8377 {
8378         struct task_group *tgi;
8379         unsigned long total = 0;
8380         unsigned long global_ratio =
8381                 to_ratio(global_rt_period(), global_rt_runtime());
8382
8383         rcu_read_lock();
8384         list_for_each_entry_rcu(tgi, &task_groups, list) {
8385                 if (tgi == tg)
8386                         continue;
8387
8388                 total += to_ratio(ktime_to_ns(tgi->rt_bandwidth.rt_period),
8389                                 tgi->rt_bandwidth.rt_runtime);
8390         }
8391         rcu_read_unlock();
8392
8393         return total + to_ratio(period, runtime) < global_ratio;
8394 }
8395 #endif
8396
8397 /* Must be called with tasklist_lock held */
8398 static inline int tg_has_rt_tasks(struct task_group *tg)
8399 {
8400         struct task_struct *g, *p;
8401         do_each_thread(g, p) {
8402                 if (rt_task(p) && rt_rq_of_se(&p->rt)->tg == tg)
8403                         return 1;
8404         } while_each_thread(g, p);
8405         return 0;
8406 }
8407
8408 static int tg_set_bandwidth(struct task_group *tg,
8409                 u64 rt_period, u64 rt_runtime)
8410 {
8411         int i, err = 0;
8412
8413         mutex_lock(&rt_constraints_mutex);
8414         read_lock(&tasklist_lock);
8415         if (rt_runtime == 0 && tg_has_rt_tasks(tg)) {
8416                 err = -EBUSY;
8417                 goto unlock;
8418         }
8419         if (!__rt_schedulable(tg, rt_period, rt_runtime)) {
8420                 err = -EINVAL;
8421                 goto unlock;
8422         }
8423
8424         spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8425         tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period);
8426         tg->rt_bandwidth.rt_runtime = rt_runtime;
8427
8428         for_each_possible_cpu(i) {
8429                 struct rt_rq *rt_rq = tg->rt_rq[i];
8430
8431                 spin_lock(&rt_rq->rt_runtime_lock);
8432                 rt_rq->rt_runtime = rt_runtime;
8433                 spin_unlock(&rt_rq->rt_runtime_lock);
8434         }
8435         spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock);
8436  unlock:
8437         read_unlock(&tasklist_lock);
8438         mutex_unlock(&rt_constraints_mutex);
8439
8440         return err;
8441 }
8442
8443 int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us)
8444 {
8445         u64 rt_runtime, rt_period;
8446
8447         rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period);
8448         rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC;
8449         if (rt_runtime_us < 0)
8450                 rt_runtime = RUNTIME_INF;
8451
8452         return tg_set_bandwidth(tg, rt_period, rt_runtime);
8453 }
8454
8455 long sched_group_rt_runtime(struct task_group *tg)
8456 {
8457         u64 rt_runtime_us;
8458
8459         if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF)
8460                 return -1;
8461
8462         rt_runtime_us = tg->rt_bandwidth.rt_runtime;
8463         do_div(rt_runtime_us, NSEC_PER_USEC);
8464         return rt_runtime_us;
8465 }
8466
8467 int sched_group_set_rt_period(struct task_group *tg, long rt_period_us)
8468 {
8469         u64 rt_runtime, rt_period;
8470
8471         rt_period = (u64)rt_period_us * NSEC_PER_USEC;
8472         rt_runtime = tg->rt_bandwidth.rt_runtime;
8473
8474         return tg_set_bandwidth(tg, rt_period, rt_runtime);
8475 }
8476
8477 long sched_group_rt_period(struct task_group *tg)
8478 {
8479         u64 rt_period_us;
8480
8481         rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period);
8482         do_div(rt_period_us, NSEC_PER_USEC);
8483         return rt_period_us;
8484 }
8485
8486 static int sched_rt_global_constraints(void)
8487 {
8488         int ret = 0;
8489
8490         mutex_lock(&rt_constraints_mutex);
8491         if (!__rt_schedulable(NULL, 1, 0))
8492                 ret = -EINVAL;
8493         mutex_unlock(&rt_constraints_mutex);
8494
8495         return ret;
8496 }
8497 #else
8498 static int sched_rt_global_constraints(void)
8499 {
8500         unsigned long flags;
8501         int i;
8502
8503         spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags);
8504         for_each_possible_cpu(i) {
8505                 struct rt_rq *rt_rq = &cpu_rq(i)->rt;
8506
8507                 spin_lock(&rt_rq->rt_runtime_lock);
8508                 rt_rq->rt_runtime = global_rt_runtime();
8509                 spin_unlock(&rt_rq->rt_runtime_lock);
8510         }
8511         spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags);
8512
8513         return 0;
8514 }
8515 #endif
8516
8517 int sched_rt_handler(struct ctl_table *table, int write,
8518                 struct file *filp, void __user *buffer, size_t *lenp,
8519                 loff_t *ppos)
8520 {
8521         int ret;
8522         int old_period, old_runtime;
8523         static DEFINE_MUTEX(mutex);
8524
8525         mutex_lock(&mutex);
8526         old_period = sysctl_sched_rt_period;
8527         old_runtime = sysctl_sched_rt_runtime;
8528
8529         ret = proc_dointvec(table, write, filp, buffer, lenp, ppos);
8530
8531         if (!ret && write) {
8532                 ret = sched_rt_global_constraints();
8533                 if (ret) {
8534                         sysctl_sched_rt_period = old_period;
8535                         sysctl_sched_rt_runtime = old_runtime;
8536                 } else {
8537                         def_rt_bandwidth.rt_runtime = global_rt_runtime();
8538                         def_rt_bandwidth.rt_period =
8539                                 ns_to_ktime(global_rt_period());
8540                 }
8541         }
8542         mutex_unlock(&mutex);
8543
8544         return ret;
8545 }
8546
8547 #ifdef CONFIG_CGROUP_SCHED
8548
8549 /* return corresponding task_group object of a cgroup */
8550 static inline struct task_group *cgroup_tg(struct cgroup *cgrp)
8551 {
8552         return container_of(cgroup_subsys_state(cgrp, cpu_cgroup_subsys_id),
8553                             struct task_group, css);
8554 }
8555
8556 static struct cgroup_subsys_state *
8557 cpu_cgroup_create(struct cgroup_subsys *ss, struct cgroup *cgrp)
8558 {
8559         struct task_group *tg, *parent;
8560
8561         if (!cgrp->parent) {
8562                 /* This is early initialization for the top cgroup */
8563                 init_task_group.css.cgroup = cgrp;
8564                 return &init_task_group.css;
8565         }
8566
8567         parent = cgroup_tg(cgrp->parent);
8568         tg = sched_create_group(parent);
8569         if (IS_ERR(tg))
8570                 return ERR_PTR(-ENOMEM);
8571
8572         /* Bind the cgroup to task_group object we just created */
8573         tg->css.cgroup = cgrp;
8574
8575         return &tg->css;
8576 }
8577
8578 static void
8579 cpu_cgroup_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
8580 {
8581         struct task_group *tg = cgroup_tg(cgrp);
8582
8583         sched_destroy_group(tg);
8584 }
8585
8586 static int
8587 cpu_cgroup_can_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8588                       struct task_struct *tsk)
8589 {
8590 #ifdef CONFIG_RT_GROUP_SCHED
8591         /* Don't accept realtime tasks when there is no way for them to run */
8592         if (rt_task(tsk) && cgroup_tg(cgrp)->rt_bandwidth.rt_runtime == 0)
8593                 return -EINVAL;
8594 #else
8595         /* We don't support RT-tasks being in separate groups */
8596         if (tsk->sched_class != &fair_sched_class)
8597                 return -EINVAL;
8598 #endif
8599
8600         return 0;
8601 }
8602
8603 static void
8604 cpu_cgroup_attach(struct cgroup_subsys *ss, struct cgroup *cgrp,
8605                         struct cgroup *old_cont, struct task_struct *tsk)
8606 {
8607         sched_move_task(tsk);
8608 }
8609
8610 #ifdef CONFIG_FAIR_GROUP_SCHED
8611 static int cpu_shares_write_u64(struct cgroup *cgrp, struct cftype *cftype,
8612                                 u64 shareval)
8613 {
8614         return sched_group_set_shares(cgroup_tg(cgrp), shareval);
8615 }
8616
8617 static u64 cpu_shares_read_u64(struct cgroup *cgrp, struct cftype *cft)
8618 {
8619         struct task_group *tg = cgroup_tg(cgrp);
8620
8621         return (u64) tg->shares;
8622 }
8623 #endif
8624
8625 #ifdef CONFIG_RT_GROUP_SCHED
8626 static int cpu_rt_runtime_write(struct cgroup *cgrp, struct cftype *cft,
8627                                 s64 val)
8628 {
8629         return sched_group_set_rt_runtime(cgroup_tg(cgrp), val);
8630 }
8631
8632 static s64 cpu_rt_runtime_read(struct cgroup *cgrp, struct cftype *cft)
8633 {
8634         return sched_group_rt_runtime(cgroup_tg(cgrp));
8635 }
8636
8637 static int cpu_rt_period_write_uint(struct cgroup *cgrp, struct cftype *cftype,
8638                 u64 rt_period_us)
8639 {
8640         return sched_group_set_rt_period(cgroup_tg(cgrp), rt_period_us);
8641 }
8642
8643 static u64 cpu_rt_period_read_uint(struct cgroup *cgrp, struct cftype *cft)
8644 {
8645         return sched_group_rt_period(cgroup_tg(cgrp));
8646 }
8647 #endif
8648
8649 static struct cftype cpu_files[] = {
8650 #ifdef CONFIG_FAIR_GROUP_SCHED
8651         {
8652                 .name = "shares",
8653                 .read_u64 = cpu_shares_read_u64,
8654                 .write_u64 = cpu_shares_write_u64,
8655         },
8656 #endif
8657 #ifdef CONFIG_RT_GROUP_SCHED
8658         {
8659                 .name = "rt_runtime_us",
8660                 .read_s64 = cpu_rt_runtime_read,
8661                 .write_s64 = cpu_rt_runtime_write,
8662         },
8663         {
8664                 .name = "rt_period_us",
8665                 .read_u64 = cpu_rt_period_read_uint,
8666                 .write_u64 = cpu_rt_period_write_uint,
8667         },
8668 #endif
8669 };
8670
8671 static int cpu_cgroup_populate(struct cgroup_subsys *ss, struct cgroup *cont)
8672 {
8673         return cgroup_add_files(cont, ss, cpu_files, ARRAY_SIZE(cpu_files));
8674 }
8675
8676 struct cgroup_subsys cpu_cgroup_subsys = {
8677         .name           = "cpu",
8678         .create         = cpu_cgroup_create,
8679         .destroy        = cpu_cgroup_destroy,
8680         .can_attach     = cpu_cgroup_can_attach,
8681         .attach         = cpu_cgroup_attach,
8682         .populate       = cpu_cgroup_populate,
8683         .subsys_id      = cpu_cgroup_subsys_id,
8684         .early_init     = 1,
8685 };
8686
8687 #endif  /* CONFIG_CGROUP_SCHED */
8688
8689 #ifdef CONFIG_CGROUP_CPUACCT
8690
8691 /*
8692  * CPU accounting code for task groups.
8693  *
8694  * Based on the work by Paul Menage (menage@google.com) and Balbir Singh
8695  * (balbir@in.ibm.com).
8696  */
8697
8698 /* track cpu usage of a group of tasks */
8699 struct cpuacct {
8700         struct cgroup_subsys_state css;
8701         /* cpuusage holds pointer to a u64-type object on every cpu */
8702         u64 *cpuusage;
8703 };
8704
8705 struct cgroup_subsys cpuacct_subsys;
8706
8707 /* return cpu accounting group corresponding to this container */
8708 static inline struct cpuacct *cgroup_ca(struct cgroup *cgrp)
8709 {
8710         return container_of(cgroup_subsys_state(cgrp, cpuacct_subsys_id),
8711                             struct cpuacct, css);
8712 }
8713
8714 /* return cpu accounting group to which this task belongs */
8715 static inline struct cpuacct *task_ca(struct task_struct *tsk)
8716 {
8717         return container_of(task_subsys_state(tsk, cpuacct_subsys_id),
8718                             struct cpuacct, css);
8719 }
8720
8721 /* create a new cpu accounting group */
8722 static struct cgroup_subsys_state *cpuacct_create(
8723         struct cgroup_subsys *ss, struct cgroup *cgrp)
8724 {
8725         struct cpuacct *ca = kzalloc(sizeof(*ca), GFP_KERNEL);
8726
8727         if (!ca)
8728                 return ERR_PTR(-ENOMEM);
8729
8730         ca->cpuusage = alloc_percpu(u64);
8731         if (!ca->cpuusage) {
8732                 kfree(ca);
8733                 return ERR_PTR(-ENOMEM);
8734         }
8735
8736         return &ca->css;
8737 }
8738
8739 /* destroy an existing cpu accounting group */
8740 static void
8741 cpuacct_destroy(struct cgroup_subsys *ss, struct cgroup *cgrp)
8742 {
8743         struct cpuacct *ca = cgroup_ca(cgrp);
8744
8745         free_percpu(ca->cpuusage);
8746         kfree(ca);
8747 }
8748
8749 /* return total cpu usage (in nanoseconds) of a group */
8750 static u64 cpuusage_read(struct cgroup *cgrp, struct cftype *cft)
8751 {
8752         struct cpuacct *ca = cgroup_ca(cgrp);
8753         u64 totalcpuusage = 0;
8754         int i;
8755
8756         for_each_possible_cpu(i) {
8757                 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
8758
8759                 /*
8760                  * Take rq->lock to make 64-bit addition safe on 32-bit
8761                  * platforms.
8762                  */
8763                 spin_lock_irq(&cpu_rq(i)->lock);
8764                 totalcpuusage += *cpuusage;
8765                 spin_unlock_irq(&cpu_rq(i)->lock);
8766         }
8767
8768         return totalcpuusage;
8769 }
8770
8771 static int cpuusage_write(struct cgroup *cgrp, struct cftype *cftype,
8772                                                                 u64 reset)
8773 {
8774         struct cpuacct *ca = cgroup_ca(cgrp);
8775         int err = 0;
8776         int i;
8777
8778         if (reset) {
8779                 err = -EINVAL;
8780                 goto out;
8781         }
8782
8783         for_each_possible_cpu(i) {
8784                 u64 *cpuusage = percpu_ptr(ca->cpuusage, i);
8785
8786                 spin_lock_irq(&cpu_rq(i)->lock);
8787                 *cpuusage = 0;
8788                 spin_unlock_irq(&cpu_rq(i)->lock);
8789         }
8790 out:
8791         return err;
8792 }
8793
8794 static struct cftype files[] = {
8795         {
8796                 .name = "usage",
8797                 .read_u64 = cpuusage_read,
8798                 .write_u64 = cpuusage_write,
8799         },
8800 };
8801
8802 static int cpuacct_populate(struct cgroup_subsys *ss, struct cgroup *cgrp)
8803 {
8804         return cgroup_add_files(cgrp, ss, files, ARRAY_SIZE(files));
8805 }
8806
8807 /*
8808  * charge this task's execution time to its accounting group.
8809  *
8810  * called with rq->lock held.
8811  */
8812 static void cpuacct_charge(struct task_struct *tsk, u64 cputime)
8813 {
8814         struct cpuacct *ca;
8815
8816         if (!cpuacct_subsys.active)
8817                 return;
8818
8819         ca = task_ca(tsk);
8820         if (ca) {
8821                 u64 *cpuusage = percpu_ptr(ca->cpuusage, task_cpu(tsk));
8822
8823                 *cpuusage += cputime;
8824         }
8825 }
8826
8827 struct cgroup_subsys cpuacct_subsys = {
8828         .name = "cpuacct",
8829         .create = cpuacct_create,
8830         .destroy = cpuacct_destroy,
8831         .populate = cpuacct_populate,
8832         .subsys_id = cpuacct_subsys_id,
8833 };
8834 #endif  /* CONFIG_CGROUP_CPUACCT */