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