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