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