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