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