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