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