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