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