This commit was manufactured by cvs2svn to create tag
[linux-2.6.git] / kernel / sched.c
1 /*
2  *  kernel/sched.c
3  *
4  *  Kernel scheduler and related syscalls
5  *
6  *  Copyright (C) 1991-2002  Linus Torvalds
7  *
8  *  1996-12-23  Modified by Dave Grothe to fix bugs in semaphores and
9  *              make semaphores SMP safe
10  *  1998-11-19  Implemented schedule_timeout() and related stuff
11  *              by Andrea Arcangeli
12  *  2002-01-04  New ultra-scalable O(1) scheduler by Ingo Molnar:
13  *              hybrid priority-list and round-robin design with
14  *              an array-switch method of distributing timeslices
15  *              and per-CPU runqueues.  Cleanups and useful suggestions
16  *              by Davide Libenzi, preemptible kernel bits by Robert Love.
17  *  2003-09-03  Interactivity tuning by Con Kolivas.
18  *  2004-04-02  Scheduler domains code by Nick Piggin
19  */
20
21 #include <linux/mm.h>
22 #include <linux/module.h>
23 #include <linux/nmi.h>
24 #include <linux/init.h>
25 #include <asm/uaccess.h>
26 #include <linux/highmem.h>
27 #include <linux/smp_lock.h>
28 #include <linux/pagemap.h>
29 #include <asm/mmu_context.h>
30 #include <linux/interrupt.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/suspend.h>
36 #include <linux/blkdev.h>
37 #include <linux/delay.h>
38 #include <linux/smp.h>
39 #include <linux/timer.h>
40 #include <linux/rcupdate.h>
41 #include <linux/cpu.h>
42 #include <linux/percpu.h>
43 #include <linux/kthread.h>
44 #include <linux/vserver/sched.h>
45 #include <linux/vinline.h>
46
47 #include <asm/unistd.h>
48
49 #ifdef CONFIG_NUMA
50 #define cpu_to_node_mask(cpu) node_to_cpumask(cpu_to_node(cpu))
51 #else
52 #define cpu_to_node_mask(cpu) (cpu_online_map)
53 #endif
54
55 /*
56  * Convert user-nice values [ -20 ... 0 ... 19 ]
57  * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
58  * and back.
59  */
60 #define NICE_TO_PRIO(nice)      (MAX_RT_PRIO + (nice) + 20)
61 #define PRIO_TO_NICE(prio)      ((prio) - MAX_RT_PRIO - 20)
62 #define TASK_NICE(p)            PRIO_TO_NICE((p)->static_prio)
63
64 /*
65  * 'User priority' is the nice value converted to something we
66  * can work with better when scaling various scheduler parameters,
67  * it's a [ 0 ... 39 ] range.
68  */
69 #define USER_PRIO(p)            ((p)-MAX_RT_PRIO)
70 #define TASK_USER_PRIO(p)       USER_PRIO((p)->static_prio)
71 #define MAX_USER_PRIO           (USER_PRIO(MAX_PRIO))
72 #define AVG_TIMESLICE   (MIN_TIMESLICE + ((MAX_TIMESLICE - MIN_TIMESLICE) *\
73                         (MAX_PRIO-1-NICE_TO_PRIO(0))/(MAX_USER_PRIO - 1)))
74
75 /*
76  * Some helpers for converting nanosecond timing to jiffy resolution
77  */
78 #define NS_TO_JIFFIES(TIME)     ((TIME) / (1000000000 / HZ))
79 #define JIFFIES_TO_NS(TIME)     ((TIME) * (1000000000 / HZ))
80
81 /*
82  * These are the 'tuning knobs' of the scheduler:
83  *
84  * Minimum timeslice is 10 msecs, default timeslice is 100 msecs,
85  * maximum timeslice is 200 msecs. Timeslices get refilled after
86  * they expire.
87  */
88 #define MIN_TIMESLICE           ( 10 * HZ / 1000)
89 #define MAX_TIMESLICE           (200 * HZ / 1000)
90 #define ON_RUNQUEUE_WEIGHT       30
91 #define CHILD_PENALTY            95
92 #define PARENT_PENALTY          100
93 #define EXIT_WEIGHT               3
94 #define PRIO_BONUS_RATIO         25
95 #define MAX_BONUS               (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
96 #define INTERACTIVE_DELTA         2
97 #define MAX_SLEEP_AVG           (AVG_TIMESLICE * MAX_BONUS)
98 #define STARVATION_LIMIT        (MAX_SLEEP_AVG)
99 #define NS_MAX_SLEEP_AVG        (JIFFIES_TO_NS(MAX_SLEEP_AVG))
100 #define CREDIT_LIMIT            100
101
102 /*
103  * If a task is 'interactive' then we reinsert it in the active
104  * array after it has expired its current timeslice. (it will not
105  * continue to run immediately, it will still roundrobin with
106  * other interactive tasks.)
107  *
108  * This part scales the interactivity limit depending on niceness.
109  *
110  * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
111  * Here are a few examples of different nice levels:
112  *
113  *  TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
114  *  TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
115  *  TASK_INTERACTIVE(  0): [1,1,1,1,0,0,0,0,0,0,0]
116  *  TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
117  *  TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
118  *
119  * (the X axis represents the possible -5 ... 0 ... +5 dynamic
120  *  priority range a task can explore, a value of '1' means the
121  *  task is rated interactive.)
122  *
123  * Ie. nice +19 tasks can never get 'interactive' enough to be
124  * reinserted into the active array. And only heavily CPU-hog nice -20
125  * tasks will be expired. Default nice 0 tasks are somewhere between,
126  * it takes some effort for them to get interactive, but it's not
127  * too hard.
128  */
129
130 #define CURRENT_BONUS(p) \
131         (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
132                 MAX_SLEEP_AVG)
133
134 #ifdef CONFIG_SMP
135 #define TIMESLICE_GRANULARITY(p)        (MIN_TIMESLICE * \
136                 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
137                         num_online_cpus())
138 #else
139 #define TIMESLICE_GRANULARITY(p)        (MIN_TIMESLICE * \
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 HIGH_CREDIT(p) \
157         ((p)->interactive_credit > CREDIT_LIMIT)
158
159 #define LOW_CREDIT(p) \
160         ((p)->interactive_credit < -CREDIT_LIMIT)
161
162 #define TASK_PREEMPTS_CURR(p, rq) \
163         ((p)->prio < (rq)->curr->prio)
164
165 /*
166  * BASE_TIMESLICE scales user-nice values [ -20 ... 19 ]
167  * to time slice values.
168  *
169  * The higher a thread's priority, the bigger timeslices
170  * it gets during one round of execution. But even the lowest
171  * priority thread gets MIN_TIMESLICE worth of execution time.
172  *
173  * task_timeslice() is the interface that is used by the scheduler.
174  */
175
176 #define BASE_TIMESLICE(p) (MIN_TIMESLICE + \
177                 ((MAX_TIMESLICE - MIN_TIMESLICE) * \
178                         (MAX_PRIO-1 - (p)->static_prio) / (MAX_USER_PRIO-1)))
179
180 static unsigned int task_timeslice(task_t *p)
181 {
182         return BASE_TIMESLICE(p);
183 }
184
185 #define task_hot(p, now, sd) ((now) - (p)->timestamp < (sd)->cache_hot_time)
186
187 /*
188  * These are the runqueue data structures:
189  */
190
191 #define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
192
193 typedef struct runqueue runqueue_t;
194
195 struct prio_array {
196         unsigned int nr_active;
197         unsigned long bitmap[BITMAP_SIZE];
198         struct list_head queue[MAX_PRIO];
199 };
200
201 /*
202  * This is the main, per-CPU runqueue data structure.
203  *
204  * Locking rule: those places that want to lock multiple runqueues
205  * (such as the load balancing or the thread migration code), lock
206  * acquire operations must be ordered by ascending &runqueue.
207  */
208 struct runqueue {
209         spinlock_t lock;
210
211         /*
212          * nr_running and cpu_load should be in the same cacheline because
213          * remote CPUs use both these fields when doing load calculation.
214          */
215         unsigned long nr_running;
216 #ifdef CONFIG_SMP
217         unsigned long cpu_load;
218 #endif
219         unsigned long long nr_switches;
220         unsigned long expired_timestamp, nr_uninterruptible;
221         unsigned long long timestamp_last_tick;
222         task_t *curr, *idle;
223         struct mm_struct *prev_mm;
224         prio_array_t *active, *expired, arrays[2];
225         int best_expired_prio;
226         atomic_t nr_iowait;
227
228 #ifdef CONFIG_SMP
229         struct sched_domain *sd;
230
231         /* For active balancing */
232         int active_balance;
233         int push_cpu;
234
235         task_t *migration_thread;
236         struct list_head migration_queue;
237 #endif
238         struct list_head hold_queue;
239         int idle_tokens;
240 };
241
242 static DEFINE_PER_CPU(struct runqueue, runqueues);
243
244 #define for_each_domain(cpu, domain) \
245         for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
246
247 #define cpu_rq(cpu)             (&per_cpu(runqueues, (cpu)))
248 #define this_rq()               (&__get_cpu_var(runqueues))
249 #define task_rq(p)              cpu_rq(task_cpu(p))
250 #define cpu_curr(cpu)           (cpu_rq(cpu)->curr)
251
252 /*
253  * Default context-switch locking:
254  */
255 #ifndef prepare_arch_switch
256 # define prepare_arch_switch(rq, next)  do { } while (0)
257 # define finish_arch_switch(rq, next)   spin_unlock_irq(&(rq)->lock)
258 # define task_running(rq, p)            ((rq)->curr == (p))
259 #endif
260
261 /*
262  * task_rq_lock - lock the runqueue a given task resides on and disable
263  * interrupts.  Note the ordering: we can safely lookup the task_rq without
264  * explicitly disabling preemption.
265  */
266 static runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
267 {
268         struct runqueue *rq;
269
270 repeat_lock_task:
271         local_irq_save(*flags);
272         rq = task_rq(p);
273         spin_lock(&rq->lock);
274         if (unlikely(rq != task_rq(p))) {
275                 spin_unlock_irqrestore(&rq->lock, *flags);
276                 goto repeat_lock_task;
277         }
278         return rq;
279 }
280
281 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
282 {
283         spin_unlock_irqrestore(&rq->lock, *flags);
284 }
285
286 /*
287  * rq_lock - lock a given runqueue and disable interrupts.
288  */
289 static runqueue_t *this_rq_lock(void)
290 {
291         runqueue_t *rq;
292
293         local_irq_disable();
294         rq = this_rq();
295         spin_lock(&rq->lock);
296
297         return rq;
298 }
299
300 static inline void rq_unlock(runqueue_t *rq)
301 {
302         spin_unlock_irq(&rq->lock);
303 }
304
305 /*
306  * Adding/removing a task to/from a priority array:
307  */
308 static void dequeue_task(struct task_struct *p, prio_array_t *array)
309 {
310         array->nr_active--;
311         list_del(&p->run_list);
312         if (list_empty(array->queue + p->prio))
313                 __clear_bit(p->prio, array->bitmap);
314 }
315
316 static void enqueue_task(struct task_struct *p, prio_array_t *array)
317 {
318         list_add_tail(&p->run_list, array->queue + p->prio);
319         __set_bit(p->prio, array->bitmap);
320         array->nr_active++;
321         p->array = array;
322 }
323
324 /*
325  * Used by the migration code - we pull tasks from the head of the
326  * remote queue so we want these tasks to show up at the head of the
327  * local queue:
328  */
329 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
330 {
331         list_add(&p->run_list, array->queue + p->prio);
332         __set_bit(p->prio, array->bitmap);
333         array->nr_active++;
334         p->array = array;
335 }
336
337 /*
338  * effective_prio - return the priority that is based on the static
339  * priority but is modified by bonuses/penalties.
340  *
341  * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
342  * into the -5 ... 0 ... +5 bonus/penalty range.
343  *
344  * We use 25% of the full 0...39 priority range so that:
345  *
346  * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
347  * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
348  *
349  * Both properties are important to certain workloads.
350  */
351 static int effective_prio(task_t *p)
352 {
353         int bonus, prio;
354
355         if (rt_task(p))
356                 return p->prio;
357
358         bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
359
360         prio = p->static_prio - bonus;
361         if (__vx_task_flags(p, VXF_SCHED_PRIO, 0))
362                 prio += effective_vavavoom(p, MAX_USER_PRIO);
363
364         if (prio < MAX_RT_PRIO)
365                 prio = MAX_RT_PRIO;
366         if (prio > MAX_PRIO-1)
367                 prio = MAX_PRIO-1;
368         return prio;
369 }
370
371 /*
372  * __activate_task - move a task to the runqueue.
373  */
374 static inline void __activate_task(task_t *p, runqueue_t *rq)
375 {
376         enqueue_task(p, rq->active);
377         rq->nr_running++;
378 }
379
380 /*
381  * __activate_idle_task - move idle task to the _front_ of runqueue.
382  */
383 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
384 {
385         enqueue_task_head(p, rq->active);
386         rq->nr_running++;
387 }
388
389 static void recalc_task_prio(task_t *p, unsigned long long now)
390 {
391         unsigned long long __sleep_time = now - p->timestamp;
392         unsigned long sleep_time;
393
394         if (__sleep_time > NS_MAX_SLEEP_AVG)
395                 sleep_time = NS_MAX_SLEEP_AVG;
396         else
397                 sleep_time = (unsigned long)__sleep_time;
398
399         if (likely(sleep_time > 0)) {
400                 /*
401                  * User tasks that sleep a long time are categorised as
402                  * idle and will get just interactive status to stay active &
403                  * prevent them suddenly becoming cpu hogs and starving
404                  * other processes.
405                  */
406                 if (p->mm && p->activated != -1 &&
407                         sleep_time > INTERACTIVE_SLEEP(p)) {
408                                 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
409                                                 AVG_TIMESLICE);
410                                 if (!HIGH_CREDIT(p))
411                                         p->interactive_credit++;
412                 } else {
413                         /*
414                          * The lower the sleep avg a task has the more
415                          * rapidly it will rise with sleep time.
416                          */
417                         sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
418
419                         /*
420                          * Tasks with low interactive_credit are limited to
421                          * one timeslice worth of sleep avg bonus.
422                          */
423                         if (LOW_CREDIT(p) &&
424                             sleep_time > JIFFIES_TO_NS(task_timeslice(p)))
425                                 sleep_time = JIFFIES_TO_NS(task_timeslice(p));
426
427                         /*
428                          * Non high_credit tasks waking from uninterruptible
429                          * sleep are limited in their sleep_avg rise as they
430                          * are likely to be cpu hogs waiting on I/O
431                          */
432                         if (p->activated == -1 && !HIGH_CREDIT(p) && p->mm) {
433                                 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
434                                         sleep_time = 0;
435                                 else if (p->sleep_avg + sleep_time >=
436                                                 INTERACTIVE_SLEEP(p)) {
437                                         p->sleep_avg = INTERACTIVE_SLEEP(p);
438                                         sleep_time = 0;
439                                 }
440                         }
441
442                         /*
443                          * This code gives a bonus to interactive tasks.
444                          *
445                          * The boost works by updating the 'average sleep time'
446                          * value here, based on ->timestamp. The more time a
447                          * task spends sleeping, the higher the average gets -
448                          * and the higher the priority boost gets as well.
449                          */
450                         p->sleep_avg += sleep_time;
451
452                         if (p->sleep_avg > NS_MAX_SLEEP_AVG) {
453                                 p->sleep_avg = NS_MAX_SLEEP_AVG;
454                                 if (!HIGH_CREDIT(p))
455                                         p->interactive_credit++;
456                         }
457                 }
458         }
459
460         p->prio = effective_prio(p);
461 }
462
463 /*
464  * activate_task - move a task to the runqueue and do priority recalculation
465  *
466  * Update all the scheduling statistics stuff. (sleep average
467  * calculation, priority modifiers, etc.)
468  */
469 static void activate_task(task_t *p, runqueue_t *rq, int local)
470 {
471         unsigned long long now;
472
473         now = sched_clock();
474 #ifdef CONFIG_SMP
475         if (!local) {
476                 /* Compensate for drifting sched_clock */
477                 runqueue_t *this_rq = this_rq();
478                 now = (now - this_rq->timestamp_last_tick)
479                         + rq->timestamp_last_tick;
480         }
481 #endif
482
483         recalc_task_prio(p, now);
484
485         /*
486          * This checks to make sure it's not an uninterruptible task
487          * that is now waking up.
488          */
489         if (!p->activated) {
490                 /*
491                  * Tasks which were woken up by interrupts (ie. hw events)
492                  * are most likely of interactive nature. So we give them
493                  * the credit of extending their sleep time to the period
494                  * of time they spend on the runqueue, waiting for execution
495                  * on a CPU, first time around:
496                  */
497                 if (in_interrupt())
498                         p->activated = 2;
499                 else {
500                         /*
501                          * Normal first-time wakeups get a credit too for
502                          * on-runqueue time, but it will be weighted down:
503                          */
504                         p->activated = 1;
505                 }
506         }
507         p->timestamp = now;
508
509         __activate_task(p, rq);
510 }
511
512 /*
513  * deactivate_task - remove a task from the runqueue.
514  */
515 static void deactivate_task(struct task_struct *p, runqueue_t *rq)
516 {
517         rq->nr_running--;
518         if (p->state == TASK_UNINTERRUPTIBLE)
519                 rq->nr_uninterruptible++;
520         dequeue_task(p, p->array);
521         p->array = NULL;
522 }
523
524 /*
525  * resched_task - mark a task 'to be rescheduled now'.
526  *
527  * On UP this means the setting of the need_resched flag, on SMP it
528  * might also involve a cross-CPU call to trigger the scheduler on
529  * the target CPU.
530  */
531 #ifdef CONFIG_SMP
532 static void resched_task(task_t *p)
533 {
534         int need_resched, nrpolling;
535
536         preempt_disable();
537         /* minimise the chance of sending an interrupt to poll_idle() */
538         nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
539         need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
540         nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
541
542         if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
543                 smp_send_reschedule(task_cpu(p));
544         preempt_enable();
545 }
546 #else
547 static inline void resched_task(task_t *p)
548 {
549         set_tsk_need_resched(p);
550 }
551 #endif
552
553 /**
554  * task_curr - is this task currently executing on a CPU?
555  * @p: the task in question.
556  */
557 inline int task_curr(task_t *p)
558 {
559         return cpu_curr(task_cpu(p)) == p;
560 }
561
562 #ifdef CONFIG_SMP
563 enum request_type {
564         REQ_MOVE_TASK,
565         REQ_SET_DOMAIN,
566 };
567
568 typedef struct {
569         struct list_head list;
570         enum request_type type;
571
572         /* For REQ_MOVE_TASK */
573         task_t *task;
574         int dest_cpu;
575
576         /* For REQ_SET_DOMAIN */
577         struct sched_domain *sd;
578
579         struct completion done;
580 } migration_req_t;
581
582 /*
583  * The task's runqueue lock must be held.
584  * Returns true if you have to wait for migration thread.
585  */
586 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
587 {
588         runqueue_t *rq = task_rq(p);
589
590         /*
591          * If the task is not on a runqueue (and not running), then
592          * it is sufficient to simply update the task's cpu field.
593          */
594         if (!p->array && !task_running(rq, p)) {
595                 set_task_cpu(p, dest_cpu);
596                 return 0;
597         }
598
599         init_completion(&req->done);
600         req->type = REQ_MOVE_TASK;
601         req->task = p;
602         req->dest_cpu = dest_cpu;
603         list_add(&req->list, &rq->migration_queue);
604         return 1;
605 }
606
607 /*
608  * wait_task_inactive - wait for a thread to unschedule.
609  *
610  * The caller must ensure that the task *will* unschedule sometime soon,
611  * else this function might spin for a *long* time. This function can't
612  * be called with interrupts off, or it may introduce deadlock with
613  * smp_call_function() if an IPI is sent by the same process we are
614  * waiting to become inactive.
615  */
616 void wait_task_inactive(task_t * p)
617 {
618         unsigned long flags;
619         runqueue_t *rq;
620         int preempted;
621
622 repeat:
623         rq = task_rq_lock(p, &flags);
624         /* Must be off runqueue entirely, not preempted. */
625         if (unlikely(p->array)) {
626                 /* If it's preempted, we yield.  It could be a while. */
627                 preempted = !task_running(rq, p);
628                 task_rq_unlock(rq, &flags);
629                 cpu_relax();
630                 if (preempted)
631                         yield();
632                 goto repeat;
633         }
634         task_rq_unlock(rq, &flags);
635 }
636
637 /***
638  * kick_process - kick a running thread to enter/exit the kernel
639  * @p: the to-be-kicked thread
640  *
641  * Cause a process which is running on another CPU to enter
642  * kernel-mode, without any delay. (to get signals handled.)
643  */
644 void kick_process(task_t *p)
645 {
646         int cpu;
647
648         preempt_disable();
649         cpu = task_cpu(p);
650         if ((cpu != smp_processor_id()) && task_curr(p))
651                 smp_send_reschedule(cpu);
652         preempt_enable();
653 }
654
655 EXPORT_SYMBOL_GPL(kick_process);
656
657 /*
658  * Return a low guess at the load of a migration-source cpu.
659  *
660  * We want to under-estimate the load of migration sources, to
661  * balance conservatively.
662  */
663 static inline unsigned long source_load(int cpu)
664 {
665         runqueue_t *rq = cpu_rq(cpu);
666         unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
667
668         return min(rq->cpu_load, load_now);
669 }
670
671 /*
672  * Return a high guess at the load of a migration-target cpu
673  */
674 static inline unsigned long target_load(int cpu)
675 {
676         runqueue_t *rq = cpu_rq(cpu);
677         unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
678
679         return max(rq->cpu_load, load_now);
680 }
681
682 #endif
683
684 /*
685  * wake_idle() is useful especially on SMT architectures to wake a
686  * task onto an idle sibling if we would otherwise wake it onto a
687  * busy sibling.
688  *
689  * Returns the CPU we should wake onto.
690  */
691 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
692 static int wake_idle(int cpu, task_t *p)
693 {
694         cpumask_t tmp;
695         runqueue_t *rq = cpu_rq(cpu);
696         struct sched_domain *sd;
697         int i;
698
699         if (idle_cpu(cpu))
700                 return cpu;
701
702         sd = rq->sd;
703         if (!(sd->flags & SD_WAKE_IDLE))
704                 return cpu;
705
706         cpus_and(tmp, sd->span, cpu_online_map);
707         for_each_cpu_mask(i, tmp) {
708                 if (!cpu_isset(i, p->cpus_allowed))
709                         continue;
710
711                 if (idle_cpu(i))
712                         return i;
713         }
714
715         return cpu;
716 }
717 #else
718 static inline int wake_idle(int cpu, task_t *p)
719 {
720         return cpu;
721 }
722 #endif
723
724 /***
725  * try_to_wake_up - wake up a thread
726  * @p: the to-be-woken-up thread
727  * @state: the mask of task states that can be woken
728  * @sync: do a synchronous wakeup?
729  *
730  * Put it on the run-queue if it's not already there. The "current"
731  * thread is always on the run-queue (except when the actual
732  * re-schedule is in progress), and as such you're allowed to do
733  * the simpler "current->state = TASK_RUNNING" to mark yourself
734  * runnable without the overhead of this.
735  *
736  * returns failure only if the task is already active.
737  */
738 static int try_to_wake_up(task_t * p, unsigned int state, int sync)
739 {
740         int cpu, this_cpu, success = 0;
741         unsigned long flags;
742         long old_state;
743         runqueue_t *rq;
744 #ifdef CONFIG_SMP
745         unsigned long load, this_load;
746         struct sched_domain *sd;
747         int new_cpu;
748 #endif
749
750         rq = task_rq_lock(p, &flags);
751         old_state = p->state;
752         if (!(old_state & state))
753                 goto out;
754
755         if (p->array)
756                 goto out_running;
757
758         cpu = task_cpu(p);
759         this_cpu = smp_processor_id();
760
761 #ifdef CONFIG_SMP
762         if (unlikely(task_running(rq, p)))
763                 goto out_activate;
764
765         new_cpu = cpu;
766
767         if (cpu == this_cpu || unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
768                 goto out_set_cpu;
769
770         load = source_load(cpu);
771         this_load = target_load(this_cpu);
772
773         /* Don't pull the task off an idle CPU to a busy one */
774         if (load < SCHED_LOAD_SCALE/2 && this_load > SCHED_LOAD_SCALE/2)
775                 goto out_set_cpu;
776
777         new_cpu = this_cpu; /* Wake to this CPU if we can */
778
779         /*
780          * Scan domains for affine wakeup and passive balancing
781          * possibilities.
782          */
783         for_each_domain(this_cpu, sd) {
784                 unsigned int imbalance;
785                 /*
786                  * Start passive balancing when half the imbalance_pct
787                  * limit is reached.
788                  */
789                 imbalance = sd->imbalance_pct + (sd->imbalance_pct - 100) / 2;
790
791                 if ( ((sd->flags & SD_WAKE_AFFINE) &&
792                                 !task_hot(p, rq->timestamp_last_tick, sd))
793                         || ((sd->flags & SD_WAKE_BALANCE) &&
794                                 imbalance*this_load <= 100*load) ) {
795                         /*
796                          * Now sd has SD_WAKE_AFFINE and p is cache cold in sd
797                          * or sd has SD_WAKE_BALANCE and there is an imbalance
798                          */
799                         if (cpu_isset(cpu, sd->span))
800                                 goto out_set_cpu;
801                 }
802         }
803
804         new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
805 out_set_cpu:
806         new_cpu = wake_idle(new_cpu, p);
807         if (new_cpu != cpu && cpu_isset(new_cpu, p->cpus_allowed)) {
808                 set_task_cpu(p, new_cpu);
809                 task_rq_unlock(rq, &flags);
810                 /* might preempt at this point */
811                 rq = task_rq_lock(p, &flags);
812                 old_state = p->state;
813                 if (!(old_state & state))
814                         goto out;
815                 if (p->array)
816                         goto out_running;
817
818                 this_cpu = smp_processor_id();
819                 cpu = task_cpu(p);
820         }
821
822 out_activate:
823 #endif /* CONFIG_SMP */
824         if (old_state == TASK_UNINTERRUPTIBLE) {
825                 rq->nr_uninterruptible--;
826                 /*
827                  * Tasks on involuntary sleep don't earn
828                  * sleep_avg beyond just interactive state.
829                  */
830                 p->activated = -1;
831         }
832
833         /*
834          * Sync wakeups (i.e. those types of wakeups where the waker
835          * has indicated that it will leave the CPU in short order)
836          * don't trigger a preemption, if the woken up task will run on
837          * this cpu. (in this case the 'I will reschedule' promise of
838          * the waker guarantees that the freshly woken up task is going
839          * to be considered on this CPU.)
840          */
841         activate_task(p, rq, cpu == this_cpu);
842         if (!sync || cpu != this_cpu) {
843                 if (TASK_PREEMPTS_CURR(p, rq))
844                         resched_task(rq->curr);
845         }
846         success = 1;
847
848 out_running:
849         p->state = TASK_RUNNING;
850 out:
851         task_rq_unlock(rq, &flags);
852
853         return success;
854 }
855
856 int fastcall wake_up_process(task_t * p)
857 {
858         return try_to_wake_up(p, TASK_STOPPED |
859                                  TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
860 }
861
862 EXPORT_SYMBOL(wake_up_process);
863
864 int fastcall wake_up_state(task_t *p, unsigned int state)
865 {
866         return try_to_wake_up(p, state, 0);
867 }
868
869 /*
870  * Perform scheduler related setup for a newly forked process p.
871  * p is forked by current.
872  */
873 void fastcall sched_fork(task_t *p)
874 {
875         /*
876          * We mark the process as running here, but have not actually
877          * inserted it onto the runqueue yet. This guarantees that
878          * nobody will actually run it, and a signal or other external
879          * event cannot wake it up and insert it on the runqueue either.
880          */
881         p->state = TASK_RUNNING;
882         INIT_LIST_HEAD(&p->run_list);
883         p->array = NULL;
884         spin_lock_init(&p->switch_lock);
885 #ifdef CONFIG_PREEMPT
886         /*
887          * During context-switch we hold precisely one spinlock, which
888          * schedule_tail drops. (in the common case it's this_rq()->lock,
889          * but it also can be p->switch_lock.) So we compensate with a count
890          * of 1. Also, we want to start with kernel preemption disabled.
891          */
892         p->thread_info->preempt_count = 1;
893 #endif
894         /*
895          * Share the timeslice between parent and child, thus the
896          * total amount of pending timeslices in the system doesn't change,
897          * resulting in more scheduling fairness.
898          */
899         local_irq_disable();
900         p->time_slice = (current->time_slice + 1) >> 1;
901         /*
902          * The remainder of the first timeslice might be recovered by
903          * the parent if the child exits early enough.
904          */
905         p->first_time_slice = 1;
906         current->time_slice >>= 1;
907         p->timestamp = sched_clock();
908         if (!current->time_slice) {
909                 /*
910                  * This case is rare, it happens when the parent has only
911                  * a single jiffy left from its timeslice. Taking the
912                  * runqueue lock is not a problem.
913                  */
914                 current->time_slice = 1;
915                 preempt_disable();
916                 scheduler_tick(0, 0);
917                 local_irq_enable();
918                 preempt_enable();
919         } else
920                 local_irq_enable();
921 }
922
923 /*
924  * wake_up_forked_process - wake up a freshly forked process.
925  *
926  * This function will do some initial scheduler statistics housekeeping
927  * that must be done for every newly created process.
928  */
929 void fastcall wake_up_forked_process(task_t * p)
930 {
931         unsigned long flags;
932         runqueue_t *rq = task_rq_lock(current, &flags);
933
934         BUG_ON(p->state != TASK_RUNNING);
935
936         /*
937          * We decrease the sleep average of forking parents
938          * and children as well, to keep max-interactive tasks
939          * from forking tasks that are max-interactive.
940          */
941         current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
942                 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
943
944         p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
945                 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
946
947         p->interactive_credit = 0;
948
949         p->prio = effective_prio(p);
950         set_task_cpu(p, smp_processor_id());
951
952         if (unlikely(!current->array))
953                 __activate_task(p, rq);
954         else {
955                 p->prio = current->prio;
956                 list_add_tail(&p->run_list, &current->run_list);
957                 p->array = current->array;
958                 p->array->nr_active++;
959                 rq->nr_running++;
960         }
961         task_rq_unlock(rq, &flags);
962 }
963
964 /*
965  * Potentially available exiting-child timeslices are
966  * retrieved here - this way the parent does not get
967  * penalized for creating too many threads.
968  *
969  * (this cannot be used to 'generate' timeslices
970  * artificially, because any timeslice recovered here
971  * was given away by the parent in the first place.)
972  */
973 void fastcall sched_exit(task_t * p)
974 {
975         unsigned long flags;
976         runqueue_t *rq;
977
978         local_irq_save(flags);
979         if (p->first_time_slice) {
980                 p->parent->time_slice += p->time_slice;
981                 if (unlikely(p->parent->time_slice > MAX_TIMESLICE))
982                         p->parent->time_slice = MAX_TIMESLICE;
983         }
984         local_irq_restore(flags);
985         /*
986          * If the child was a (relative-) CPU hog then decrease
987          * the sleep_avg of the parent as well.
988          */
989         rq = task_rq_lock(p->parent, &flags);
990         if (p->sleep_avg < p->parent->sleep_avg)
991                 p->parent->sleep_avg = p->parent->sleep_avg /
992                 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
993                 (EXIT_WEIGHT + 1);
994         task_rq_unlock(rq, &flags);
995 }
996
997 /**
998  * finish_task_switch - clean up after a task-switch
999  * @prev: the thread we just switched away from.
1000  *
1001  * We enter this with the runqueue still locked, and finish_arch_switch()
1002  * will unlock it along with doing any other architecture-specific cleanup
1003  * actions.
1004  *
1005  * Note that we may have delayed dropping an mm in context_switch(). If
1006  * so, we finish that here outside of the runqueue lock.  (Doing it
1007  * with the lock held can cause deadlocks; see schedule() for
1008  * details.)
1009  */
1010 static void finish_task_switch(task_t *prev)
1011 {
1012         runqueue_t *rq = this_rq();
1013         struct mm_struct *mm = rq->prev_mm;
1014         unsigned long prev_task_flags;
1015
1016         rq->prev_mm = NULL;
1017
1018         /*
1019          * A task struct has one reference for the use as "current".
1020          * If a task dies, then it sets TASK_ZOMBIE in tsk->state and calls
1021          * schedule one last time. The schedule call will never return,
1022          * and the scheduled task must drop that reference.
1023          * The test for TASK_ZOMBIE must occur while the runqueue locks are
1024          * still held, otherwise prev could be scheduled on another cpu, die
1025          * there before we look at prev->state, and then the reference would
1026          * be dropped twice.
1027          *              Manfred Spraul <manfred@colorfullife.com>
1028          */
1029         prev_task_flags = prev->flags;
1030         finish_arch_switch(rq, prev);
1031         if (mm)
1032                 mmdrop(mm);
1033         if (unlikely(prev_task_flags & PF_DEAD))
1034                 put_task_struct(prev);
1035 }
1036
1037 /**
1038  * schedule_tail - first thing a freshly forked thread must call.
1039  * @prev: the thread we just switched away from.
1040  */
1041 asmlinkage void schedule_tail(task_t *prev)
1042 {
1043         finish_task_switch(prev);
1044
1045         if (current->set_child_tid)
1046                 put_user(current->pid, current->set_child_tid);
1047 }
1048
1049 /*
1050  * context_switch - switch to the new MM and the new
1051  * thread's register state.
1052  */
1053 static inline
1054 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1055 {
1056         struct mm_struct *mm = next->mm;
1057         struct mm_struct *oldmm = prev->active_mm;
1058
1059         if (unlikely(!mm)) {
1060                 next->active_mm = oldmm;
1061                 atomic_inc(&oldmm->mm_count);
1062                 enter_lazy_tlb(oldmm, next);
1063         } else
1064                 switch_mm(oldmm, mm, next);
1065
1066         if (unlikely(!prev->mm)) {
1067                 prev->active_mm = NULL;
1068                 WARN_ON(rq->prev_mm);
1069                 rq->prev_mm = oldmm;
1070         }
1071
1072         /* Here we just switch the register state and the stack. */
1073         switch_to(prev, next, prev);
1074
1075         return prev;
1076 }
1077
1078 /*
1079  * nr_running, nr_uninterruptible and nr_context_switches:
1080  *
1081  * externally visible scheduler statistics: current number of runnable
1082  * threads, current number of uninterruptible-sleeping threads, total
1083  * number of context switches performed since bootup.
1084  */
1085 unsigned long nr_running(void)
1086 {
1087         unsigned long i, sum = 0;
1088
1089         for_each_cpu(i)
1090                 sum += cpu_rq(i)->nr_running;
1091
1092         return sum;
1093 }
1094
1095 unsigned long nr_uninterruptible(void)
1096 {
1097         unsigned long i, sum = 0;
1098
1099         for_each_online_cpu(i)
1100                 sum += cpu_rq(i)->nr_uninterruptible;
1101
1102         return sum;
1103 }
1104
1105 unsigned long long nr_context_switches(void)
1106 {
1107         unsigned long long i, sum = 0;
1108
1109         for_each_online_cpu(i)
1110                 sum += cpu_rq(i)->nr_switches;
1111
1112         return sum;
1113 }
1114
1115 unsigned long nr_iowait(void)
1116 {
1117         unsigned long i, sum = 0;
1118
1119         for_each_online_cpu(i)
1120                 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1121
1122         return sum;
1123 }
1124
1125 /*
1126  * double_rq_lock - safely lock two runqueues
1127  *
1128  * Note this does not disable interrupts like task_rq_lock,
1129  * you need to do so manually before calling.
1130  */
1131 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1132 {
1133         if (rq1 == rq2)
1134                 spin_lock(&rq1->lock);
1135         else {
1136                 if (rq1 < rq2) {
1137                         spin_lock(&rq1->lock);
1138                         spin_lock(&rq2->lock);
1139                 } else {
1140                         spin_lock(&rq2->lock);
1141                         spin_lock(&rq1->lock);
1142                 }
1143         }
1144 }
1145
1146 /*
1147  * double_rq_unlock - safely unlock two runqueues
1148  *
1149  * Note this does not restore interrupts like task_rq_unlock,
1150  * you need to do so manually after calling.
1151  */
1152 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1153 {
1154         spin_unlock(&rq1->lock);
1155         if (rq1 != rq2)
1156                 spin_unlock(&rq2->lock);
1157 }
1158
1159 enum idle_type
1160 {
1161         IDLE,
1162         NOT_IDLE,
1163         NEWLY_IDLE,
1164 };
1165
1166 #ifdef CONFIG_SMP
1167
1168 /*
1169  * find_idlest_cpu - find the least busy runqueue.
1170  */
1171 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1172                            struct sched_domain *sd)
1173 {
1174         unsigned long load, min_load, this_load;
1175         int i, min_cpu;
1176         cpumask_t mask;
1177
1178         min_cpu = UINT_MAX;
1179         min_load = ULONG_MAX;
1180
1181         cpus_and(mask, sd->span, cpu_online_map);
1182         cpus_and(mask, mask, p->cpus_allowed);
1183
1184         for_each_cpu_mask(i, mask) {
1185                 load = target_load(i);
1186
1187                 if (load < min_load) {
1188                         min_cpu = i;
1189                         min_load = load;
1190
1191                         /* break out early on an idle CPU: */
1192                         if (!min_load)
1193                                 break;
1194                 }
1195         }
1196
1197         /* add +1 to account for the new task */
1198         this_load = source_load(this_cpu) + SCHED_LOAD_SCALE;
1199
1200         /*
1201          * Would with the addition of the new task to the
1202          * current CPU there be an imbalance between this
1203          * CPU and the idlest CPU?
1204          *
1205          * Use half of the balancing threshold - new-context is
1206          * a good opportunity to balance.
1207          */
1208         if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1209                 return min_cpu;
1210
1211         return this_cpu;
1212 }
1213
1214 /*
1215  * wake_up_forked_thread - wake up a freshly forked thread.
1216  *
1217  * This function will do some initial scheduler statistics housekeeping
1218  * that must be done for every newly created context, and it also does
1219  * runqueue balancing.
1220  */
1221 void fastcall wake_up_forked_thread(task_t * p)
1222 {
1223         unsigned long flags;
1224         int this_cpu = get_cpu(), cpu;
1225         struct sched_domain *tmp, *sd = NULL;
1226         runqueue_t *this_rq = cpu_rq(this_cpu), *rq;
1227
1228         /*
1229          * Find the largest domain that this CPU is part of that
1230          * is willing to balance on clone:
1231          */
1232         for_each_domain(this_cpu, tmp)
1233                 if (tmp->flags & SD_BALANCE_CLONE)
1234                         sd = tmp;
1235         if (sd)
1236                 cpu = find_idlest_cpu(p, this_cpu, sd);
1237         else
1238                 cpu = this_cpu;
1239
1240         local_irq_save(flags);
1241 lock_again:
1242         rq = cpu_rq(cpu);
1243         double_rq_lock(this_rq, rq);
1244
1245         BUG_ON(p->state != TASK_RUNNING);
1246
1247         /*
1248          * We did find_idlest_cpu() unlocked, so in theory
1249          * the mask could have changed - just dont migrate
1250          * in this case:
1251          */
1252         if (unlikely(!cpu_isset(cpu, p->cpus_allowed))) {
1253                 cpu = this_cpu;
1254                 double_rq_unlock(this_rq, rq);
1255                 goto lock_again;
1256         }
1257         /*
1258          * We decrease the sleep average of forking parents
1259          * and children as well, to keep max-interactive tasks
1260          * from forking tasks that are max-interactive.
1261          */
1262         current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1263                 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1264
1265         p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1266                 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1267
1268         p->interactive_credit = 0;
1269
1270         p->prio = effective_prio(p);
1271         set_task_cpu(p, cpu);
1272
1273         if (cpu == this_cpu) {
1274                 if (unlikely(!current->array))
1275                         __activate_task(p, rq);
1276                 else {
1277                         p->prio = current->prio;
1278                         list_add_tail(&p->run_list, &current->run_list);
1279                         p->array = current->array;
1280                         p->array->nr_active++;
1281                         rq->nr_running++;
1282                 }
1283         } else {
1284                 /* Not the local CPU - must adjust timestamp */
1285                 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1286                                         + rq->timestamp_last_tick;
1287                 __activate_task(p, rq);
1288                 if (TASK_PREEMPTS_CURR(p, rq))
1289                         resched_task(rq->curr);
1290         }
1291
1292         double_rq_unlock(this_rq, rq);
1293         local_irq_restore(flags);
1294         put_cpu();
1295 }
1296
1297 /*
1298  * If dest_cpu is allowed for this process, migrate the task to it.
1299  * This is accomplished by forcing the cpu_allowed mask to only
1300  * allow dest_cpu, which will force the cpu onto dest_cpu.  Then
1301  * the cpu_allowed mask is restored.
1302  */
1303 static void sched_migrate_task(task_t *p, int dest_cpu)
1304 {
1305         migration_req_t req;
1306         runqueue_t *rq;
1307         unsigned long flags;
1308
1309         rq = task_rq_lock(p, &flags);
1310         if (!cpu_isset(dest_cpu, p->cpus_allowed)
1311             || unlikely(cpu_is_offline(dest_cpu)))
1312                 goto out;
1313
1314         /* force the process onto the specified CPU */
1315         if (migrate_task(p, dest_cpu, &req)) {
1316                 /* Need to wait for migration thread (might exit: take ref). */
1317                 struct task_struct *mt = rq->migration_thread;
1318                 get_task_struct(mt);
1319                 task_rq_unlock(rq, &flags);
1320                 wake_up_process(mt);
1321                 put_task_struct(mt);
1322                 wait_for_completion(&req.done);
1323                 return;
1324         }
1325 out:
1326         task_rq_unlock(rq, &flags);
1327 }
1328
1329 /*
1330  * sched_balance_exec(): find the highest-level, exec-balance-capable
1331  * domain and try to migrate the task to the least loaded CPU.
1332  *
1333  * execve() is a valuable balancing opportunity, because at this point
1334  * the task has the smallest effective memory and cache footprint.
1335  */
1336 void sched_balance_exec(void)
1337 {
1338         struct sched_domain *tmp, *sd = NULL;
1339         int new_cpu, this_cpu = get_cpu();
1340
1341         /* Prefer the current CPU if there's only this task running */
1342         if (this_rq()->nr_running <= 1)
1343                 goto out;
1344
1345         for_each_domain(this_cpu, tmp)
1346                 if (tmp->flags & SD_BALANCE_EXEC)
1347                         sd = tmp;
1348
1349         if (sd) {
1350                 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1351                 if (new_cpu != this_cpu) {
1352                         put_cpu();
1353                         sched_migrate_task(current, new_cpu);
1354                         return;
1355                 }
1356         }
1357 out:
1358         put_cpu();
1359 }
1360
1361 /*
1362  * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1363  */
1364 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1365 {
1366         if (unlikely(!spin_trylock(&busiest->lock))) {
1367                 if (busiest < this_rq) {
1368                         spin_unlock(&this_rq->lock);
1369                         spin_lock(&busiest->lock);
1370                         spin_lock(&this_rq->lock);
1371                 } else
1372                         spin_lock(&busiest->lock);
1373         }
1374 }
1375
1376 /*
1377  * pull_task - move a task from a remote runqueue to the local runqueue.
1378  * Both runqueues must be locked.
1379  */
1380 static inline
1381 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1382                runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1383 {
1384         dequeue_task(p, src_array);
1385         src_rq->nr_running--;
1386         set_task_cpu(p, this_cpu);
1387         this_rq->nr_running++;
1388         enqueue_task(p, this_array);
1389         p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1390                                 + this_rq->timestamp_last_tick;
1391         /*
1392          * Note that idle threads have a prio of MAX_PRIO, for this test
1393          * to be always true for them.
1394          */
1395         if (TASK_PREEMPTS_CURR(p, this_rq))
1396                 resched_task(this_rq->curr);
1397 }
1398
1399 /*
1400  * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1401  */
1402 static inline
1403 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1404                      struct sched_domain *sd, enum idle_type idle)
1405 {
1406         /*
1407          * We do not migrate tasks that are:
1408          * 1) running (obviously), or
1409          * 2) cannot be migrated to this CPU due to cpus_allowed, or
1410          * 3) are cache-hot on their current CPU.
1411          */
1412         if (task_running(rq, p))
1413                 return 0;
1414         if (!cpu_isset(this_cpu, p->cpus_allowed))
1415                 return 0;
1416
1417         /* Aggressive migration if we've failed balancing */
1418         if (idle == NEWLY_IDLE ||
1419                         sd->nr_balance_failed < sd->cache_nice_tries) {
1420                 if (task_hot(p, rq->timestamp_last_tick, sd))
1421                         return 0;
1422         }
1423
1424         return 1;
1425 }
1426
1427 /*
1428  * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1429  * as part of a balancing operation within "domain". Returns the number of
1430  * tasks moved.
1431  *
1432  * Called with both runqueues locked.
1433  */
1434 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1435                       unsigned long max_nr_move, struct sched_domain *sd,
1436                       enum idle_type idle)
1437 {
1438         prio_array_t *array, *dst_array;
1439         struct list_head *head, *curr;
1440         int idx, pulled = 0;
1441         task_t *tmp;
1442
1443         if (max_nr_move <= 0 || busiest->nr_running <= 1)
1444                 goto out;
1445
1446         /*
1447          * We first consider expired tasks. Those will likely not be
1448          * executed in the near future, and they are most likely to
1449          * be cache-cold, thus switching CPUs has the least effect
1450          * on them.
1451          */
1452         if (busiest->expired->nr_active) {
1453                 array = busiest->expired;
1454                 dst_array = this_rq->expired;
1455         } else {
1456                 array = busiest->active;
1457                 dst_array = this_rq->active;
1458         }
1459
1460 new_array:
1461         /* Start searching at priority 0: */
1462         idx = 0;
1463 skip_bitmap:
1464         if (!idx)
1465                 idx = sched_find_first_bit(array->bitmap);
1466         else
1467                 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1468         if (idx >= MAX_PRIO) {
1469                 if (array == busiest->expired && busiest->active->nr_active) {
1470                         array = busiest->active;
1471                         dst_array = this_rq->active;
1472                         goto new_array;
1473                 }
1474                 goto out;
1475         }
1476
1477         head = array->queue + idx;
1478         curr = head->prev;
1479 skip_queue:
1480         tmp = list_entry(curr, task_t, run_list);
1481
1482         curr = curr->prev;
1483
1484         if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
1485                 if (curr != head)
1486                         goto skip_queue;
1487                 idx++;
1488                 goto skip_bitmap;
1489         }
1490         pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
1491         pulled++;
1492
1493         /* We only want to steal up to the prescribed number of tasks. */
1494         if (pulled < max_nr_move) {
1495                 if (curr != head)
1496                         goto skip_queue;
1497                 idx++;
1498                 goto skip_bitmap;
1499         }
1500 out:
1501         return pulled;
1502 }
1503
1504 /*
1505  * find_busiest_group finds and returns the busiest CPU group within the
1506  * domain. It calculates and returns the number of tasks which should be
1507  * moved to restore balance via the imbalance parameter.
1508  */
1509 static struct sched_group *
1510 find_busiest_group(struct sched_domain *sd, int this_cpu,
1511                    unsigned long *imbalance, enum idle_type idle)
1512 {
1513         struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
1514         unsigned long max_load, avg_load, total_load, this_load, total_pwr;
1515
1516         max_load = this_load = total_load = total_pwr = 0;
1517
1518         do {
1519                 cpumask_t tmp;
1520                 unsigned long load;
1521                 int local_group;
1522                 int i, nr_cpus = 0;
1523
1524                 local_group = cpu_isset(this_cpu, group->cpumask);
1525
1526                 /* Tally up the load of all CPUs in the group */
1527                 avg_load = 0;
1528                 cpus_and(tmp, group->cpumask, cpu_online_map);
1529                 if (unlikely(cpus_empty(tmp)))
1530                         goto nextgroup;
1531
1532                 for_each_cpu_mask(i, tmp) {
1533                         /* Bias balancing toward cpus of our domain */
1534                         if (local_group)
1535                                 load = target_load(i);
1536                         else
1537                                 load = source_load(i);
1538
1539                         nr_cpus++;
1540                         avg_load += load;
1541                 }
1542
1543                 if (!nr_cpus)
1544                         goto nextgroup;
1545
1546                 total_load += avg_load;
1547                 total_pwr += group->cpu_power;
1548
1549                 /* Adjust by relative CPU power of the group */
1550                 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1551
1552                 if (local_group) {
1553                         this_load = avg_load;
1554                         this = group;
1555                         goto nextgroup;
1556                 } else if (avg_load > max_load) {
1557                         max_load = avg_load;
1558                         busiest = group;
1559                 }
1560 nextgroup:
1561                 group = group->next;
1562         } while (group != sd->groups);
1563
1564         if (!busiest || this_load >= max_load)
1565                 goto out_balanced;
1566
1567         avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
1568
1569         if (this_load >= avg_load ||
1570                         100*max_load <= sd->imbalance_pct*this_load)
1571                 goto out_balanced;
1572
1573         /*
1574          * We're trying to get all the cpus to the average_load, so we don't
1575          * want to push ourselves above the average load, nor do we wish to
1576          * reduce the max loaded cpu below the average load, as either of these
1577          * actions would just result in more rebalancing later, and ping-pong
1578          * tasks around. Thus we look for the minimum possible imbalance.
1579          * Negative imbalances (*we* are more loaded than anyone else) will
1580          * be counted as no imbalance for these purposes -- we can't fix that
1581          * by pulling tasks to us.  Be careful of negative numbers as they'll
1582          * appear as very large values with unsigned longs.
1583          */
1584         *imbalance = min(max_load - avg_load, avg_load - this_load);
1585
1586         /* How much load to actually move to equalise the imbalance */
1587         *imbalance = (*imbalance * min(busiest->cpu_power, this->cpu_power))
1588                                 / SCHED_LOAD_SCALE;
1589
1590         if (*imbalance < SCHED_LOAD_SCALE - 1) {
1591                 unsigned long pwr_now = 0, pwr_move = 0;
1592                 unsigned long tmp;
1593
1594                 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
1595                         *imbalance = 1;
1596                         return busiest;
1597                 }
1598
1599                 /*
1600                  * OK, we don't have enough imbalance to justify moving tasks,
1601                  * however we may be able to increase total CPU power used by
1602                  * moving them.
1603                  */
1604
1605                 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
1606                 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
1607                 pwr_now /= SCHED_LOAD_SCALE;
1608
1609                 /* Amount of load we'd subtract */
1610                 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
1611                 if (max_load > tmp)
1612                         pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
1613                                                         max_load - tmp);
1614
1615                 /* Amount of load we'd add */
1616                 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
1617                 if (max_load < tmp)
1618                         tmp = max_load;
1619                 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
1620                 pwr_move /= SCHED_LOAD_SCALE;
1621
1622                 /* Move if we gain another 8th of a CPU worth of throughput */
1623                 if (pwr_move < pwr_now + SCHED_LOAD_SCALE / 8)
1624                         goto out_balanced;
1625
1626                 *imbalance = 1;
1627                 return busiest;
1628         }
1629
1630         /* Get rid of the scaling factor, rounding down as we divide */
1631         *imbalance = (*imbalance + 1) / SCHED_LOAD_SCALE;
1632
1633         return busiest;
1634
1635 out_balanced:
1636         if (busiest && (idle == NEWLY_IDLE ||
1637                         (idle == IDLE && max_load > SCHED_LOAD_SCALE)) ) {
1638                 *imbalance = 1;
1639                 return busiest;
1640         }
1641
1642         *imbalance = 0;
1643         return NULL;
1644 }
1645
1646 /*
1647  * find_busiest_queue - find the busiest runqueue among the cpus in group.
1648  */
1649 static runqueue_t *find_busiest_queue(struct sched_group *group)
1650 {
1651         cpumask_t tmp;
1652         unsigned long load, max_load = 0;
1653         runqueue_t *busiest = NULL;
1654         int i;
1655
1656         cpus_and(tmp, group->cpumask, cpu_online_map);
1657         for_each_cpu_mask(i, tmp) {
1658                 load = source_load(i);
1659
1660                 if (load > max_load) {
1661                         max_load = load;
1662                         busiest = cpu_rq(i);
1663                 }
1664         }
1665
1666         return busiest;
1667 }
1668
1669 /*
1670  * Check this_cpu to ensure it is balanced within domain. Attempt to move
1671  * tasks if there is an imbalance.
1672  *
1673  * Called with this_rq unlocked.
1674  *
1675  * This function is marked noinline to work around a compiler
1676  * bug with gcc 3.3.3-hammer on x86-64.
1677  */
1678 static int noinline load_balance(int this_cpu, runqueue_t *this_rq,
1679                         struct sched_domain *sd, enum idle_type idle)
1680 {
1681         struct sched_group *group;
1682         runqueue_t *busiest;
1683         unsigned long imbalance;
1684         int nr_moved;
1685
1686         spin_lock(&this_rq->lock);
1687
1688         group = find_busiest_group(sd, this_cpu, &imbalance, idle);
1689         if (!group)
1690                 goto out_balanced;
1691
1692         busiest = find_busiest_queue(group);
1693         if (!busiest)
1694                 goto out_balanced;
1695         if (unlikely(busiest == this_rq)) {
1696                 WARN_ON(1);
1697                 goto out_balanced;
1698         }
1699
1700         nr_moved = 0;
1701         if (busiest->nr_running > 1) {
1702                 /*
1703                  * Attempt to move tasks. If find_busiest_group has found
1704                  * an imbalance but busiest->nr_running <= 1, the group is
1705                  * still unbalanced. nr_moved simply stays zero, so it is
1706                  * correctly treated as an imbalance.
1707                  */
1708                 double_lock_balance(this_rq, busiest);
1709                 nr_moved = move_tasks(this_rq, this_cpu, busiest,
1710                                                 imbalance, sd, idle);
1711                 spin_unlock(&busiest->lock);
1712         }
1713         spin_unlock(&this_rq->lock);
1714
1715         if (!nr_moved) {
1716                 sd->nr_balance_failed++;
1717
1718                 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
1719                         int wake = 0;
1720
1721                         spin_lock(&busiest->lock);
1722                         if (!busiest->active_balance) {
1723                                 busiest->active_balance = 1;
1724                                 busiest->push_cpu = this_cpu;
1725                                 wake = 1;
1726                         }
1727                         spin_unlock(&busiest->lock);
1728                         if (wake)
1729                                 wake_up_process(busiest->migration_thread);
1730
1731                         /*
1732                          * We've kicked active balancing, reset the failure
1733                          * counter.
1734                          */
1735                         sd->nr_balance_failed = sd->cache_nice_tries;
1736                 }
1737         } else
1738                 sd->nr_balance_failed = 0;
1739
1740         /* We were unbalanced, so reset the balancing interval */
1741         sd->balance_interval = sd->min_interval;
1742
1743         return nr_moved;
1744
1745 out_balanced:
1746         spin_unlock(&this_rq->lock);
1747
1748         /* tune up the balancing interval */
1749         if (sd->balance_interval < sd->max_interval)
1750                 sd->balance_interval *= 2;
1751
1752         return 0;
1753 }
1754
1755 /*
1756  * Check this_cpu to ensure it is balanced within domain. Attempt to move
1757  * tasks if there is an imbalance.
1758  *
1759  * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
1760  * this_rq is locked.
1761  */
1762 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
1763                                 struct sched_domain *sd)
1764 {
1765         struct sched_group *group;
1766         runqueue_t *busiest = NULL;
1767         unsigned long imbalance;
1768         int nr_moved = 0;
1769
1770         group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
1771         if (!group)
1772                 goto out;
1773
1774         busiest = find_busiest_queue(group);
1775         if (!busiest || busiest == this_rq)
1776                 goto out;
1777
1778         /* Attempt to move tasks */
1779         double_lock_balance(this_rq, busiest);
1780
1781         nr_moved = move_tasks(this_rq, this_cpu, busiest,
1782                                         imbalance, sd, NEWLY_IDLE);
1783
1784         spin_unlock(&busiest->lock);
1785
1786 out:
1787         return nr_moved;
1788 }
1789
1790 /*
1791  * idle_balance is called by schedule() if this_cpu is about to become
1792  * idle. Attempts to pull tasks from other CPUs.
1793  */
1794 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
1795 {
1796         struct sched_domain *sd;
1797
1798         for_each_domain(this_cpu, sd) {
1799                 if (sd->flags & SD_BALANCE_NEWIDLE) {
1800                         if (load_balance_newidle(this_cpu, this_rq, sd)) {
1801                                 /* We've pulled tasks over so stop searching */
1802                                 break;
1803                         }
1804                 }
1805         }
1806 }
1807
1808 /*
1809  * active_load_balance is run by migration threads. It pushes a running
1810  * task off the cpu. It can be required to correctly have at least 1 task
1811  * running on each physical CPU where possible, and not have a physical /
1812  * logical imbalance.
1813  *
1814  * Called with busiest locked.
1815  */
1816 static void active_load_balance(runqueue_t *busiest, int busiest_cpu)
1817 {
1818         struct sched_domain *sd;
1819         struct sched_group *group, *busy_group;
1820         int i;
1821
1822         if (busiest->nr_running <= 1)
1823                 return;
1824
1825         for_each_domain(busiest_cpu, sd)
1826                 if (cpu_isset(busiest->push_cpu, sd->span))
1827                         break;
1828         if (!sd) {
1829                 WARN_ON(1);
1830                 return;
1831         }
1832
1833         group = sd->groups;
1834         while (!cpu_isset(busiest_cpu, group->cpumask))
1835                 group = group->next;
1836         busy_group = group;
1837
1838         group = sd->groups;
1839         do {
1840                 cpumask_t tmp;
1841                 runqueue_t *rq;
1842                 int push_cpu = 0;
1843
1844                 if (group == busy_group)
1845                         goto next_group;
1846
1847                 cpus_and(tmp, group->cpumask, cpu_online_map);
1848                 if (!cpus_weight(tmp))
1849                         goto next_group;
1850
1851                 for_each_cpu_mask(i, tmp) {
1852                         if (!idle_cpu(i))
1853                                 goto next_group;
1854                         push_cpu = i;
1855                 }
1856
1857                 rq = cpu_rq(push_cpu);
1858                 double_lock_balance(busiest, rq);
1859                 move_tasks(rq, push_cpu, busiest, 1, sd, IDLE);
1860                 spin_unlock(&rq->lock);
1861 next_group:
1862                 group = group->next;
1863         } while (group != sd->groups);
1864 }
1865
1866 /*
1867  * rebalance_tick will get called every timer tick, on every CPU.
1868  *
1869  * It checks each scheduling domain to see if it is due to be balanced,
1870  * and initiates a balancing operation if so.
1871  *
1872  * Balancing parameters are set up in arch_init_sched_domains.
1873  */
1874
1875 /* Don't have all balancing operations going off at once */
1876 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
1877
1878 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
1879                            enum idle_type idle)
1880 {
1881         unsigned long old_load, this_load;
1882         unsigned long j = jiffies + CPU_OFFSET(this_cpu);
1883         struct sched_domain *sd;
1884
1885         /* Update our load */
1886         old_load = this_rq->cpu_load;
1887         this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
1888         /*
1889          * Round up the averaging division if load is increasing. This
1890          * prevents us from getting stuck on 9 if the load is 10, for
1891          * example.
1892          */
1893         if (this_load > old_load)
1894                 old_load++;
1895         this_rq->cpu_load = (old_load + this_load) / 2;
1896
1897         for_each_domain(this_cpu, sd) {
1898                 unsigned long interval = sd->balance_interval;
1899
1900                 if (idle != IDLE)
1901                         interval *= sd->busy_factor;
1902
1903                 /* scale ms to jiffies */
1904                 interval = msecs_to_jiffies(interval);
1905                 if (unlikely(!interval))
1906                         interval = 1;
1907
1908                 if (j - sd->last_balance >= interval) {
1909                         if (load_balance(this_cpu, this_rq, sd, idle)) {
1910                                 /* We've pulled tasks over so no longer idle */
1911                                 idle = NOT_IDLE;
1912                         }
1913                         sd->last_balance += interval;
1914                 }
1915         }
1916 }
1917 #else
1918 /*
1919  * on UP we do not need to balance between CPUs:
1920  */
1921 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
1922 {
1923 }
1924 static inline void idle_balance(int cpu, runqueue_t *rq)
1925 {
1926 }
1927 #endif
1928
1929 static inline int wake_priority_sleeper(runqueue_t *rq)
1930 {
1931 #ifdef CONFIG_SCHED_SMT
1932         /*
1933          * If an SMT sibling task has been put to sleep for priority
1934          * reasons reschedule the idle task to see if it can now run.
1935          */
1936         if (rq->nr_running) {
1937                 resched_task(rq->idle);
1938                 return 1;
1939         }
1940 #endif
1941         return 0;
1942 }
1943
1944 DEFINE_PER_CPU(struct kernel_stat, kstat);
1945
1946 EXPORT_PER_CPU_SYMBOL(kstat);
1947
1948 /*
1949  * We place interactive tasks back into the active array, if possible.
1950  *
1951  * To guarantee that this does not starve expired tasks we ignore the
1952  * interactivity of a task if the first expired task had to wait more
1953  * than a 'reasonable' amount of time. This deadline timeout is
1954  * load-dependent, as the frequency of array switched decreases with
1955  * increasing number of running tasks. We also ignore the interactivity
1956  * if a better static_prio task has expired:
1957  */
1958 #define EXPIRED_STARVING(rq) \
1959         ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
1960                 (jiffies - (rq)->expired_timestamp >= \
1961                         STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
1962                         ((rq)->curr->static_prio > (rq)->best_expired_prio))
1963
1964 /*
1965  * This function gets called by the timer code, with HZ frequency.
1966  * We call it with interrupts disabled.
1967  *
1968  * It also gets called by the fork code, when changing the parent's
1969  * timeslices.
1970  */
1971 void scheduler_tick(int user_ticks, int sys_ticks)
1972 {
1973         int cpu = smp_processor_id();
1974         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
1975         runqueue_t *rq = this_rq();
1976         task_t *p = current;
1977
1978         rq->timestamp_last_tick = sched_clock();
1979
1980         if (rcu_pending(cpu))
1981                 rcu_check_callbacks(cpu, user_ticks);
1982
1983         /* note: this timer irq context must be accounted for as well */
1984         if (hardirq_count() - HARDIRQ_OFFSET) {
1985                 cpustat->irq += sys_ticks;
1986                 sys_ticks = 0;
1987         } else if (softirq_count()) {
1988                 cpustat->softirq += sys_ticks;
1989                 sys_ticks = 0;
1990         }
1991
1992         if (p == rq->idle) {
1993                 if (!--rq->idle_tokens && !list_empty(&rq->hold_queue))
1994                         set_need_resched();     
1995
1996                 if (atomic_read(&rq->nr_iowait) > 0)
1997                         cpustat->iowait += sys_ticks;
1998                 else
1999                         cpustat->idle += sys_ticks;
2000                 if (wake_priority_sleeper(rq))
2001                         goto out;
2002                 rebalance_tick(cpu, rq, IDLE);
2003                 return;
2004         }
2005         if (TASK_NICE(p) > 0)
2006                 cpustat->nice += user_ticks;
2007         else
2008                 cpustat->user += user_ticks;
2009         cpustat->system += sys_ticks;
2010
2011         /* Task might have expired already, but not scheduled off yet */
2012         if (p->array != rq->active) {
2013                 set_tsk_need_resched(p);
2014                 goto out;
2015         }
2016         spin_lock(&rq->lock);
2017         /*
2018          * The task was running during this tick - update the
2019          * time slice counter. Note: we do not update a thread's
2020          * priority until it either goes to sleep or uses up its
2021          * timeslice. This makes it possible for interactive tasks
2022          * to use up their timeslices at their highest priority levels.
2023          */
2024         if (unlikely(rt_task(p))) {
2025                 /*
2026                  * RR tasks need a special form of timeslice management.
2027                  * FIFO tasks have no timeslices.
2028                  */
2029                 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2030                         p->time_slice = task_timeslice(p);
2031                         p->first_time_slice = 0;
2032                         set_tsk_need_resched(p);
2033
2034                         /* put it at the end of the queue: */
2035                         dequeue_task(p, rq->active);
2036                         enqueue_task(p, rq->active);
2037                 }
2038                 goto out_unlock;
2039         }
2040         if (vx_need_resched(p)) {
2041                 dequeue_task(p, rq->active);
2042                 set_tsk_need_resched(p);
2043                 p->prio = effective_prio(p);
2044                 p->time_slice = task_timeslice(p);
2045                 p->first_time_slice = 0;
2046
2047                 if (!rq->expired_timestamp)
2048                         rq->expired_timestamp = jiffies;
2049                 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2050                         enqueue_task(p, rq->expired);
2051                         if (p->static_prio < rq->best_expired_prio)
2052                                 rq->best_expired_prio = p->static_prio;
2053                 } else
2054                         enqueue_task(p, rq->active);
2055         } else {
2056                 /*
2057                  * Prevent a too long timeslice allowing a task to monopolize
2058                  * the CPU. We do this by splitting up the timeslice into
2059                  * smaller pieces.
2060                  *
2061                  * Note: this does not mean the task's timeslices expire or
2062                  * get lost in any way, they just might be preempted by
2063                  * another task of equal priority. (one with higher
2064                  * priority would have preempted this task already.) We
2065                  * requeue this task to the end of the list on this priority
2066                  * level, which is in essence a round-robin of tasks with
2067                  * equal priority.
2068                  *
2069                  * This only applies to tasks in the interactive
2070                  * delta range with at least TIMESLICE_GRANULARITY to requeue.
2071                  */
2072                 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2073                         p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2074                         (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2075                         (p->array == rq->active)) {
2076
2077                         dequeue_task(p, rq->active);
2078                         set_tsk_need_resched(p);
2079                         p->prio = effective_prio(p);
2080                         enqueue_task(p, rq->active);
2081                 }
2082         }
2083 out_unlock:
2084         spin_unlock(&rq->lock);
2085 out:
2086         rebalance_tick(cpu, rq, NOT_IDLE);
2087 }
2088
2089 #ifdef CONFIG_SCHED_SMT
2090 static inline void wake_sleeping_dependent(int cpu, runqueue_t *rq)
2091 {
2092         int i;
2093         struct sched_domain *sd = rq->sd;
2094         cpumask_t sibling_map;
2095
2096         if (!(sd->flags & SD_SHARE_CPUPOWER))
2097                 return;
2098
2099         cpus_and(sibling_map, sd->span, cpu_online_map);
2100         for_each_cpu_mask(i, sibling_map) {
2101                 runqueue_t *smt_rq;
2102
2103                 if (i == cpu)
2104                         continue;
2105
2106                 smt_rq = cpu_rq(i);
2107
2108                 /*
2109                  * If an SMT sibling task is sleeping due to priority
2110                  * reasons wake it up now.
2111                  */
2112                 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
2113                         resched_task(smt_rq->idle);
2114         }
2115 }
2116
2117 static inline int dependent_sleeper(int cpu, runqueue_t *rq, task_t *p)
2118 {
2119         struct sched_domain *sd = rq->sd;
2120         cpumask_t sibling_map;
2121         int ret = 0, i;
2122
2123         if (!(sd->flags & SD_SHARE_CPUPOWER))
2124                 return 0;
2125
2126         cpus_and(sibling_map, sd->span, cpu_online_map);
2127         for_each_cpu_mask(i, sibling_map) {
2128                 runqueue_t *smt_rq;
2129                 task_t *smt_curr;
2130
2131                 if (i == cpu)
2132                         continue;
2133
2134                 smt_rq = cpu_rq(i);
2135                 smt_curr = smt_rq->curr;
2136
2137                 /*
2138                  * If a user task with lower static priority than the
2139                  * running task on the SMT sibling is trying to schedule,
2140                  * delay it till there is proportionately less timeslice
2141                  * left of the sibling task to prevent a lower priority
2142                  * task from using an unfair proportion of the
2143                  * physical cpu's resources. -ck
2144                  */
2145                 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
2146                         task_timeslice(p) || rt_task(smt_curr)) &&
2147                         p->mm && smt_curr->mm && !rt_task(p))
2148                                 ret = 1;
2149
2150                 /*
2151                  * Reschedule a lower priority task on the SMT sibling,
2152                  * or wake it up if it has been put to sleep for priority
2153                  * reasons.
2154                  */
2155                 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
2156                         task_timeslice(smt_curr) || rt_task(p)) &&
2157                         smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
2158                         (smt_curr == smt_rq->idle && smt_rq->nr_running))
2159                                 resched_task(smt_curr);
2160         }
2161         return ret;
2162 }
2163 #else
2164 static inline void wake_sleeping_dependent(int cpu, runqueue_t *rq)
2165 {
2166 }
2167
2168 static inline int dependent_sleeper(int cpu, runqueue_t *rq, task_t *p)
2169 {
2170         return 0;
2171 }
2172 #endif
2173
2174 /*
2175  * schedule() is the main scheduler function.
2176  */
2177 asmlinkage void __sched schedule(void)
2178 {
2179         long *switch_count;
2180         task_t *prev, *next;
2181         runqueue_t *rq;
2182         prio_array_t *array;
2183         struct list_head *queue;
2184         unsigned long long now;
2185         unsigned long run_time;
2186         int cpu, idx;
2187 #ifdef  CONFIG_VSERVER_HARDCPU          
2188         struct vx_info *vxi;
2189         int maxidle = -HZ;
2190 #endif
2191
2192         /*
2193          * Test if we are atomic.  Since do_exit() needs to call into
2194          * schedule() atomically, we ignore that path for now.
2195          * Otherwise, whine if we are scheduling when we should not be.
2196          */
2197         if (likely(!(current->state & (TASK_DEAD | TASK_ZOMBIE)))) {
2198                 if (unlikely(in_atomic())) {
2199                         printk(KERN_ERR "bad: scheduling while atomic!\n");
2200                         dump_stack();
2201                 }
2202         }
2203
2204 need_resched:
2205         preempt_disable();
2206         prev = current;
2207         rq = this_rq();
2208
2209         release_kernel_lock(prev);
2210         now = sched_clock();
2211         if (likely(now - prev->timestamp < NS_MAX_SLEEP_AVG))
2212                 run_time = now - prev->timestamp;
2213         else
2214                 run_time = NS_MAX_SLEEP_AVG;
2215
2216         /*
2217          * Tasks with interactive credits get charged less run_time
2218          * at high sleep_avg to delay them losing their interactive
2219          * status
2220          */
2221         if (HIGH_CREDIT(prev))
2222                 run_time /= (CURRENT_BONUS(prev) ? : 1);
2223
2224         spin_lock_irq(&rq->lock);
2225
2226         /*
2227          * if entering off of a kernel preemption go straight
2228          * to picking the next task.
2229          */
2230         switch_count = &prev->nivcsw;
2231         if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2232                 switch_count = &prev->nvcsw;
2233                 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2234                                 unlikely(signal_pending(prev))))
2235                         prev->state = TASK_RUNNING;
2236                 else
2237                         deactivate_task(prev, rq);
2238         }
2239
2240         cpu = smp_processor_id();
2241 #ifdef  CONFIG_VSERVER_HARDCPU          
2242         if (!list_empty(&rq->hold_queue)) {
2243                 struct list_head *l, *n;
2244                 int ret;
2245
2246                 vxi = NULL;
2247                 list_for_each_safe(l, n, &rq->hold_queue) {
2248                         next = list_entry(l, task_t, run_list);
2249                         if (vxi == next->vx_info)
2250                                 continue;
2251
2252                         vxi = next->vx_info;
2253                         ret = vx_tokens_recalc(vxi);
2254                         // tokens = vx_tokens_avail(next);
2255
2256                         if (ret > 0) {
2257                                 list_del(&next->run_list);
2258                                 next->state &= ~TASK_ONHOLD;
2259                                 recalc_task_prio(next, now);
2260                                 __activate_task(next, rq);
2261                                 // printk("··· unhold %p\n", next);
2262                                 break;
2263                         }
2264                         if ((ret < 0) && (maxidle < ret))
2265                                 maxidle = ret;
2266                 }       
2267         }
2268         rq->idle_tokens = -maxidle;
2269
2270 pick_next:
2271 #endif
2272         if (unlikely(!rq->nr_running)) {
2273                 idle_balance(cpu, rq);
2274                 if (!rq->nr_running) {
2275                         next = rq->idle;
2276                         rq->expired_timestamp = 0;
2277                         wake_sleeping_dependent(cpu, rq);
2278                         goto switch_tasks;
2279                 }
2280         }
2281
2282         array = rq->active;
2283         if (unlikely(!array->nr_active)) {
2284                 /*
2285                  * Switch the active and expired arrays.
2286                  */
2287                 rq->active = rq->expired;
2288                 rq->expired = array;
2289                 array = rq->active;
2290                 rq->expired_timestamp = 0;
2291                 rq->best_expired_prio = MAX_PRIO;
2292         }
2293
2294         idx = sched_find_first_bit(array->bitmap);
2295         queue = array->queue + idx;
2296         next = list_entry(queue->next, task_t, run_list);
2297
2298         if (dependent_sleeper(cpu, rq, next)) {
2299                 next = rq->idle;
2300                 goto switch_tasks;
2301         }
2302
2303 #ifdef  CONFIG_VSERVER_HARDCPU          
2304         vxi = next->vx_info;
2305         if (vxi && __vx_flags(vxi->vx_flags,
2306                 VXF_SCHED_PAUSE|VXF_SCHED_HARD, 0)) {
2307                 int ret = vx_tokens_recalc(vxi);
2308
2309                 if (unlikely(ret <= 0)) {
2310                         if (ret && (rq->idle_tokens > -ret))
2311                                 rq->idle_tokens = -ret;
2312                         deactivate_task(next, rq);
2313                         list_add_tail(&next->run_list, &rq->hold_queue);
2314                         next->state |= TASK_ONHOLD;                     
2315                         goto pick_next;
2316                 }
2317         }
2318 #endif
2319
2320         if (!rt_task(next) && next->activated > 0) {
2321                 unsigned long long delta = now - next->timestamp;
2322
2323                 if (next->activated == 1)
2324                         delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
2325
2326                 array = next->array;
2327                 dequeue_task(next, array);
2328                 recalc_task_prio(next, next->timestamp + delta);
2329                 enqueue_task(next, array);
2330         }
2331         next->activated = 0;
2332 switch_tasks:
2333         prefetch(next);
2334         clear_tsk_need_resched(prev);
2335         RCU_qsctr(task_cpu(prev))++;
2336
2337         prev->sleep_avg -= run_time;
2338         if ((long)prev->sleep_avg <= 0) {
2339                 prev->sleep_avg = 0;
2340                 if (!(HIGH_CREDIT(prev) || LOW_CREDIT(prev)))
2341                         prev->interactive_credit--;
2342         }
2343         prev->timestamp = now;
2344
2345         if (likely(prev != next)) {
2346                 next->timestamp = now;
2347                 rq->nr_switches++;
2348                 rq->curr = next;
2349                 ++*switch_count;
2350
2351                 prepare_arch_switch(rq, next);
2352                 prev = context_switch(rq, prev, next);
2353                 barrier();
2354
2355                 finish_task_switch(prev);
2356         } else
2357                 spin_unlock_irq(&rq->lock);
2358
2359         reacquire_kernel_lock(current);
2360         preempt_enable_no_resched();
2361         if (test_thread_flag(TIF_NEED_RESCHED))
2362                 goto need_resched;
2363 }
2364
2365 EXPORT_SYMBOL(schedule);
2366
2367 #ifdef CONFIG_PREEMPT
2368 /*
2369  * this is is the entry point to schedule() from in-kernel preemption
2370  * off of preempt_enable.  Kernel preemptions off return from interrupt
2371  * occur there and call schedule directly.
2372  */
2373 asmlinkage void __sched preempt_schedule(void)
2374 {
2375         struct thread_info *ti = current_thread_info();
2376
2377         /*
2378          * If there is a non-zero preempt_count or interrupts are disabled,
2379          * we do not want to preempt the current task.  Just return..
2380          */
2381         if (unlikely(ti->preempt_count || irqs_disabled()))
2382                 return;
2383
2384 need_resched:
2385         ti->preempt_count = PREEMPT_ACTIVE;
2386         schedule();
2387         ti->preempt_count = 0;
2388
2389         /* we could miss a preemption opportunity between schedule and now */
2390         barrier();
2391         if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2392                 goto need_resched;
2393 }
2394
2395 EXPORT_SYMBOL(preempt_schedule);
2396 #endif /* CONFIG_PREEMPT */
2397
2398 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
2399 {
2400         task_t *p = curr->task;
2401         return try_to_wake_up(p, mode, sync);
2402 }
2403
2404 EXPORT_SYMBOL(default_wake_function);
2405
2406 /*
2407  * The core wakeup function.  Non-exclusive wakeups (nr_exclusive == 0) just
2408  * wake everything up.  If it's an exclusive wakeup (nr_exclusive == small +ve
2409  * number) then we wake all the non-exclusive tasks and one exclusive task.
2410  *
2411  * There are circumstances in which we can try to wake a task which has already
2412  * started to run but is not in state TASK_RUNNING.  try_to_wake_up() returns
2413  * zero in this (rare) case, and we handle it by continuing to scan the queue.
2414  */
2415 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
2416                              int nr_exclusive, int sync, void *key)
2417 {
2418         struct list_head *tmp, *next;
2419
2420         list_for_each_safe(tmp, next, &q->task_list) {
2421                 wait_queue_t *curr;
2422                 unsigned flags;
2423                 curr = list_entry(tmp, wait_queue_t, task_list);
2424                 flags = curr->flags;
2425                 if (curr->func(curr, mode, sync, key) &&
2426                     (flags & WQ_FLAG_EXCLUSIVE) &&
2427                     !--nr_exclusive)
2428                         break;
2429         }
2430 }
2431
2432 /**
2433  * __wake_up - wake up threads blocked on a waitqueue.
2434  * @q: the waitqueue
2435  * @mode: which threads
2436  * @nr_exclusive: how many wake-one or wake-many threads to wake up
2437  */
2438 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
2439                                 int nr_exclusive, void *key)
2440 {
2441         unsigned long flags;
2442
2443         spin_lock_irqsave(&q->lock, flags);
2444         __wake_up_common(q, mode, nr_exclusive, 0, key);
2445         spin_unlock_irqrestore(&q->lock, flags);
2446 }
2447
2448 EXPORT_SYMBOL(__wake_up);
2449
2450 /*
2451  * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
2452  */
2453 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
2454 {
2455         __wake_up_common(q, mode, 1, 0, NULL);
2456 }
2457
2458 /**
2459  * __wake_up - sync- wake up threads blocked on a waitqueue.
2460  * @q: the waitqueue
2461  * @mode: which threads
2462  * @nr_exclusive: how many wake-one or wake-many threads to wake up
2463  *
2464  * The sync wakeup differs that the waker knows that it will schedule
2465  * away soon, so while the target thread will be woken up, it will not
2466  * be migrated to another CPU - ie. the two threads are 'synchronized'
2467  * with each other. This can prevent needless bouncing between CPUs.
2468  *
2469  * On UP it can prevent extra preemption.
2470  */
2471 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
2472 {
2473         unsigned long flags;
2474         int sync = 1;
2475
2476         if (unlikely(!q))
2477                 return;
2478
2479         if (unlikely(!nr_exclusive))
2480                 sync = 0;
2481
2482         spin_lock_irqsave(&q->lock, flags);
2483         __wake_up_common(q, mode, nr_exclusive, sync, NULL);
2484         spin_unlock_irqrestore(&q->lock, flags);
2485 }
2486 EXPORT_SYMBOL_GPL(__wake_up_sync);      /* For internal use only */
2487
2488 void fastcall complete(struct completion *x)
2489 {
2490         unsigned long flags;
2491
2492         spin_lock_irqsave(&x->wait.lock, flags);
2493         x->done++;
2494         __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2495                          1, 0, NULL);
2496         spin_unlock_irqrestore(&x->wait.lock, flags);
2497 }
2498 EXPORT_SYMBOL(complete);
2499
2500 void fastcall complete_all(struct completion *x)
2501 {
2502         unsigned long flags;
2503
2504         spin_lock_irqsave(&x->wait.lock, flags);
2505         x->done += UINT_MAX/2;
2506         __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2507                          0, 0, NULL);
2508         spin_unlock_irqrestore(&x->wait.lock, flags);
2509 }
2510 EXPORT_SYMBOL(complete_all);
2511
2512 void fastcall __sched wait_for_completion(struct completion *x)
2513 {
2514         might_sleep();
2515         spin_lock_irq(&x->wait.lock);
2516         if (!x->done) {
2517                 DECLARE_WAITQUEUE(wait, current);
2518
2519                 wait.flags |= WQ_FLAG_EXCLUSIVE;
2520                 __add_wait_queue_tail(&x->wait, &wait);
2521                 do {
2522                         __set_current_state(TASK_UNINTERRUPTIBLE);
2523                         spin_unlock_irq(&x->wait.lock);
2524                         schedule();
2525                         spin_lock_irq(&x->wait.lock);
2526                 } while (!x->done);
2527                 __remove_wait_queue(&x->wait, &wait);
2528         }
2529         x->done--;
2530         spin_unlock_irq(&x->wait.lock);
2531 }
2532 EXPORT_SYMBOL(wait_for_completion);
2533
2534 #define SLEEP_ON_VAR                                    \
2535         unsigned long flags;                            \
2536         wait_queue_t wait;                              \
2537         init_waitqueue_entry(&wait, current);
2538
2539 #define SLEEP_ON_HEAD                                   \
2540         spin_lock_irqsave(&q->lock,flags);              \
2541         __add_wait_queue(q, &wait);                     \
2542         spin_unlock(&q->lock);
2543
2544 #define SLEEP_ON_TAIL                                   \
2545         spin_lock_irq(&q->lock);                        \
2546         __remove_wait_queue(q, &wait);                  \
2547         spin_unlock_irqrestore(&q->lock, flags);
2548
2549 #define SLEEP_ON_BKLCHECK                               \
2550         if (unlikely(!kernel_locked()) &&               \
2551             sleep_on_bkl_warnings < 10) {               \
2552                 sleep_on_bkl_warnings++;                \
2553                 WARN_ON(1);                             \
2554         }
2555
2556 static int sleep_on_bkl_warnings;
2557
2558 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
2559 {
2560         SLEEP_ON_VAR
2561
2562         SLEEP_ON_BKLCHECK
2563
2564         current->state = TASK_INTERRUPTIBLE;
2565
2566         SLEEP_ON_HEAD
2567         schedule();
2568         SLEEP_ON_TAIL
2569 }
2570
2571 EXPORT_SYMBOL(interruptible_sleep_on);
2572
2573 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
2574 {
2575         SLEEP_ON_VAR
2576
2577         SLEEP_ON_BKLCHECK
2578
2579         current->state = TASK_INTERRUPTIBLE;
2580
2581         SLEEP_ON_HEAD
2582         timeout = schedule_timeout(timeout);
2583         SLEEP_ON_TAIL
2584
2585         return timeout;
2586 }
2587
2588 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
2589
2590 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
2591 {
2592         SLEEP_ON_VAR
2593
2594         SLEEP_ON_BKLCHECK
2595
2596         current->state = TASK_UNINTERRUPTIBLE;
2597
2598         SLEEP_ON_HEAD
2599         timeout = schedule_timeout(timeout);
2600         SLEEP_ON_TAIL
2601
2602         return timeout;
2603 }
2604
2605 EXPORT_SYMBOL(sleep_on_timeout);
2606
2607 void set_user_nice(task_t *p, long nice)
2608 {
2609         unsigned long flags;
2610         prio_array_t *array;
2611         runqueue_t *rq;
2612         int old_prio, new_prio, delta;
2613
2614         if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
2615                 return;
2616         /*
2617          * We have to be careful, if called from sys_setpriority(),
2618          * the task might be in the middle of scheduling on another CPU.
2619          */
2620         rq = task_rq_lock(p, &flags);
2621         /*
2622          * The RT priorities are set via setscheduler(), but we still
2623          * allow the 'normal' nice value to be set - but as expected
2624          * it wont have any effect on scheduling until the task is
2625          * not SCHED_NORMAL:
2626          */
2627         if (rt_task(p)) {
2628                 p->static_prio = NICE_TO_PRIO(nice);
2629                 goto out_unlock;
2630         }
2631         array = p->array;
2632         if (array)
2633                 dequeue_task(p, array);
2634
2635         old_prio = p->prio;
2636         new_prio = NICE_TO_PRIO(nice);
2637         delta = new_prio - old_prio;
2638         p->static_prio = NICE_TO_PRIO(nice);
2639         p->prio += delta;
2640
2641         if (array) {
2642                 enqueue_task(p, array);
2643                 /*
2644                  * If the task increased its priority or is running and
2645                  * lowered its priority, then reschedule its CPU:
2646                  */
2647                 if (delta < 0 || (delta > 0 && task_running(rq, p)))
2648                         resched_task(rq->curr);
2649         }
2650 out_unlock:
2651         task_rq_unlock(rq, &flags);
2652 }
2653
2654 EXPORT_SYMBOL(set_user_nice);
2655
2656 #ifdef __ARCH_WANT_SYS_NICE
2657
2658 /*
2659  * sys_nice - change the priority of the current process.
2660  * @increment: priority increment
2661  *
2662  * sys_setpriority is a more generic, but much slower function that
2663  * does similar things.
2664  */
2665 asmlinkage long sys_nice(int increment)
2666 {
2667         int retval;
2668         long nice;
2669
2670         /*
2671          * Setpriority might change our priority at the same moment.
2672          * We don't have to worry. Conceptually one call occurs first
2673          * and we have a single winner.
2674          */
2675         if (increment < 0) {
2676                 if (!capable(CAP_SYS_NICE))
2677                         return -EPERM;
2678                 if (increment < -40)
2679                         increment = -40;
2680         }
2681         if (increment > 40)
2682                 increment = 40;
2683
2684         nice = PRIO_TO_NICE(current->static_prio) + increment;
2685         if (nice < -20)
2686                 nice = -20;
2687         if (nice > 19)
2688                 nice = 19;
2689
2690         retval = security_task_setnice(current, nice);
2691         if (retval)
2692                 return retval;
2693
2694         set_user_nice(current, nice);
2695         return 0;
2696 }
2697
2698 #endif
2699
2700 /**
2701  * task_prio - return the priority value of a given task.
2702  * @p: the task in question.
2703  *
2704  * This is the priority value as seen by users in /proc.
2705  * RT tasks are offset by -200. Normal tasks are centered
2706  * around 0, value goes from -16 to +15.
2707  */
2708 int task_prio(task_t *p)
2709 {
2710         return p->prio - MAX_RT_PRIO;
2711 }
2712
2713 /**
2714  * task_nice - return the nice value of a given task.
2715  * @p: the task in question.
2716  */
2717 int task_nice(task_t *p)
2718 {
2719         return TASK_NICE(p);
2720 }
2721
2722 EXPORT_SYMBOL(task_nice);
2723
2724 /**
2725  * idle_cpu - is a given cpu idle currently?
2726  * @cpu: the processor in question.
2727  */
2728 int idle_cpu(int cpu)
2729 {
2730         return cpu_curr(cpu) == cpu_rq(cpu)->idle;
2731 }
2732
2733 EXPORT_SYMBOL_GPL(idle_cpu);
2734
2735 /**
2736  * find_process_by_pid - find a process with a matching PID value.
2737  * @pid: the pid in question.
2738  */
2739 static inline task_t *find_process_by_pid(pid_t pid)
2740 {
2741         return pid ? find_task_by_pid(pid) : current;
2742 }
2743
2744 /* Actually do priority change: must hold rq lock. */
2745 static void __setscheduler(struct task_struct *p, int policy, int prio)
2746 {
2747         BUG_ON(p->array);
2748         p->policy = policy;
2749         p->rt_priority = prio;
2750         if (policy != SCHED_NORMAL)
2751                 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
2752         else
2753                 p->prio = p->static_prio;
2754 }
2755
2756 /*
2757  * setscheduler - change the scheduling policy and/or RT priority of a thread.
2758  */
2759 static int setscheduler(pid_t pid, int policy, struct sched_param __user *param)
2760 {
2761         struct sched_param lp;
2762         int retval = -EINVAL;
2763         int oldprio;
2764         prio_array_t *array;
2765         unsigned long flags;
2766         runqueue_t *rq;
2767         task_t *p;
2768
2769         if (!param || pid < 0)
2770                 goto out_nounlock;
2771
2772         retval = -EFAULT;
2773         if (copy_from_user(&lp, param, sizeof(struct sched_param)))
2774                 goto out_nounlock;
2775
2776         /*
2777          * We play safe to avoid deadlocks.
2778          */
2779         read_lock_irq(&tasklist_lock);
2780
2781         p = find_process_by_pid(pid);
2782
2783         retval = -ESRCH;
2784         if (!p)
2785                 goto out_unlock_tasklist;
2786
2787         /*
2788          * To be able to change p->policy safely, the apropriate
2789          * runqueue lock must be held.
2790          */
2791         rq = task_rq_lock(p, &flags);
2792
2793         if (policy < 0)
2794                 policy = p->policy;
2795         else {
2796                 retval = -EINVAL;
2797                 if (policy != SCHED_FIFO && policy != SCHED_RR &&
2798                                 policy != SCHED_NORMAL)
2799                         goto out_unlock;
2800         }
2801
2802         /*
2803          * Valid priorities for SCHED_FIFO and SCHED_RR are
2804          * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
2805          */
2806         retval = -EINVAL;
2807         if (lp.sched_priority < 0 || lp.sched_priority > MAX_USER_RT_PRIO-1)
2808                 goto out_unlock;
2809         if ((policy == SCHED_NORMAL) != (lp.sched_priority == 0))
2810                 goto out_unlock;
2811
2812         retval = -EPERM;
2813         if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
2814             !capable(CAP_SYS_NICE))
2815                 goto out_unlock;
2816         if ((current->euid != p->euid) && (current->euid != p->uid) &&
2817             !capable(CAP_SYS_NICE))
2818                 goto out_unlock;
2819
2820         retval = security_task_setscheduler(p, policy, &lp);
2821         if (retval)
2822                 goto out_unlock;
2823
2824         array = p->array;
2825         if (array)
2826                 deactivate_task(p, task_rq(p));
2827         retval = 0;
2828         oldprio = p->prio;
2829         __setscheduler(p, policy, lp.sched_priority);
2830         if (array) {
2831                 __activate_task(p, task_rq(p));
2832                 /*
2833                  * Reschedule if we are currently running on this runqueue and
2834                  * our priority decreased, or if we are not currently running on
2835                  * this runqueue and our priority is higher than the current's
2836                  */
2837                 if (task_running(rq, p)) {
2838                         if (p->prio > oldprio)
2839                                 resched_task(rq->curr);
2840                 } else if (TASK_PREEMPTS_CURR(p, rq))
2841                         resched_task(rq->curr);
2842         }
2843
2844 out_unlock:
2845         task_rq_unlock(rq, &flags);
2846 out_unlock_tasklist:
2847         read_unlock_irq(&tasklist_lock);
2848
2849 out_nounlock:
2850         return retval;
2851 }
2852
2853 /**
2854  * sys_sched_setscheduler - set/change the scheduler policy and RT priority
2855  * @pid: the pid in question.
2856  * @policy: new policy
2857  * @param: structure containing the new RT priority.
2858  */
2859 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
2860                                        struct sched_param __user *param)
2861 {
2862         return setscheduler(pid, policy, param);
2863 }
2864
2865 /**
2866  * sys_sched_setparam - set/change the RT priority of a thread
2867  * @pid: the pid in question.
2868  * @param: structure containing the new RT priority.
2869  */
2870 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
2871 {
2872         return setscheduler(pid, -1, param);
2873 }
2874
2875 /**
2876  * sys_sched_getscheduler - get the policy (scheduling class) of a thread
2877  * @pid: the pid in question.
2878  */
2879 asmlinkage long sys_sched_getscheduler(pid_t pid)
2880 {
2881         int retval = -EINVAL;
2882         task_t *p;
2883
2884         if (pid < 0)
2885                 goto out_nounlock;
2886
2887         retval = -ESRCH;
2888         read_lock(&tasklist_lock);
2889         p = find_process_by_pid(pid);
2890         if (p) {
2891                 retval = security_task_getscheduler(p);
2892                 if (!retval)
2893                         retval = p->policy;
2894         }
2895         read_unlock(&tasklist_lock);
2896
2897 out_nounlock:
2898         return retval;
2899 }
2900
2901 /**
2902  * sys_sched_getscheduler - get the RT priority of a thread
2903  * @pid: the pid in question.
2904  * @param: structure containing the RT priority.
2905  */
2906 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
2907 {
2908         struct sched_param lp;
2909         int retval = -EINVAL;
2910         task_t *p;
2911
2912         if (!param || pid < 0)
2913                 goto out_nounlock;
2914
2915         read_lock(&tasklist_lock);
2916         p = find_process_by_pid(pid);
2917         retval = -ESRCH;
2918         if (!p)
2919                 goto out_unlock;
2920
2921         retval = security_task_getscheduler(p);
2922         if (retval)
2923                 goto out_unlock;
2924
2925         lp.sched_priority = p->rt_priority;
2926         read_unlock(&tasklist_lock);
2927
2928         /*
2929          * This one might sleep, we cannot do it with a spinlock held ...
2930          */
2931         retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
2932
2933 out_nounlock:
2934         return retval;
2935
2936 out_unlock:
2937         read_unlock(&tasklist_lock);
2938         return retval;
2939 }
2940
2941 /**
2942  * sys_sched_setaffinity - set the cpu affinity of a process
2943  * @pid: pid of the process
2944  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
2945  * @user_mask_ptr: user-space pointer to the new cpu mask
2946  */
2947 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
2948                                       unsigned long __user *user_mask_ptr)
2949 {
2950         cpumask_t new_mask;
2951         int retval;
2952         task_t *p;
2953
2954         if (len < sizeof(new_mask))
2955                 return -EINVAL;
2956
2957         if (copy_from_user(&new_mask, user_mask_ptr, sizeof(new_mask)))
2958                 return -EFAULT;
2959
2960         lock_cpu_hotplug();
2961         read_lock(&tasklist_lock);
2962
2963         p = find_process_by_pid(pid);
2964         if (!p) {
2965                 read_unlock(&tasklist_lock);
2966                 unlock_cpu_hotplug();
2967                 return -ESRCH;
2968         }
2969
2970         /*
2971          * It is not safe to call set_cpus_allowed with the
2972          * tasklist_lock held.  We will bump the task_struct's
2973          * usage count and then drop tasklist_lock.
2974          */
2975         get_task_struct(p);
2976         read_unlock(&tasklist_lock);
2977
2978         retval = -EPERM;
2979         if ((current->euid != p->euid) && (current->euid != p->uid) &&
2980                         !capable(CAP_SYS_NICE))
2981                 goto out_unlock;
2982
2983         retval = set_cpus_allowed(p, new_mask);
2984
2985 out_unlock:
2986         put_task_struct(p);
2987         unlock_cpu_hotplug();
2988         return retval;
2989 }
2990
2991 /**
2992  * sys_sched_getaffinity - get the cpu affinity of a process
2993  * @pid: pid of the process
2994  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
2995  * @user_mask_ptr: user-space pointer to hold the current cpu mask
2996  */
2997 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
2998                                       unsigned long __user *user_mask_ptr)
2999 {
3000         unsigned int real_len;
3001         cpumask_t mask;
3002         int retval;
3003         task_t *p;
3004
3005         real_len = sizeof(mask);
3006         if (len < real_len)
3007                 return -EINVAL;
3008
3009         lock_cpu_hotplug();
3010         read_lock(&tasklist_lock);
3011
3012         retval = -ESRCH;
3013         p = find_process_by_pid(pid);
3014         if (!p)
3015                 goto out_unlock;
3016
3017         retval = 0;
3018         cpus_and(mask, p->cpus_allowed, cpu_possible_map);
3019
3020 out_unlock:
3021         read_unlock(&tasklist_lock);
3022         unlock_cpu_hotplug();
3023         if (retval)
3024                 return retval;
3025         if (copy_to_user(user_mask_ptr, &mask, real_len))
3026                 return -EFAULT;
3027         return real_len;
3028 }
3029
3030 /**
3031  * sys_sched_yield - yield the current processor to other threads.
3032  *
3033  * this function yields the current CPU by moving the calling thread
3034  * to the expired array. If there are no other threads running on this
3035  * CPU then this function will return.
3036  */
3037 asmlinkage long sys_sched_yield(void)
3038 {
3039         runqueue_t *rq = this_rq_lock();
3040         prio_array_t *array = current->array;
3041         prio_array_t *target = rq->expired;
3042
3043         /*
3044          * We implement yielding by moving the task into the expired
3045          * queue.
3046          *
3047          * (special rule: RT tasks will just roundrobin in the active
3048          *  array.)
3049          */
3050         if (unlikely(rt_task(current)))
3051                 target = rq->active;
3052
3053         dequeue_task(current, array);
3054         enqueue_task(current, target);
3055
3056         /*
3057          * Since we are going to call schedule() anyway, there's
3058          * no need to preempt or enable interrupts:
3059          */
3060         _raw_spin_unlock(&rq->lock);
3061         preempt_enable_no_resched();
3062
3063         schedule();
3064
3065         return 0;
3066 }
3067
3068 void __sched __cond_resched(void)
3069 {
3070         set_current_state(TASK_RUNNING);
3071         schedule();
3072 }
3073
3074 EXPORT_SYMBOL(__cond_resched);
3075
3076 /**
3077  * yield - yield the current processor to other threads.
3078  *
3079  * this is a shortcut for kernel-space yielding - it marks the
3080  * thread runnable and calls sys_sched_yield().
3081  */
3082 void __sched yield(void)
3083 {
3084         set_current_state(TASK_RUNNING);
3085         sys_sched_yield();
3086 }
3087
3088 EXPORT_SYMBOL(yield);
3089
3090 /*
3091  * This task is about to go to sleep on IO.  Increment rq->nr_iowait so
3092  * that process accounting knows that this is a task in IO wait state.
3093  *
3094  * But don't do that if it is a deliberate, throttling IO wait (this task
3095  * has set its backing_dev_info: the queue against which it should throttle)
3096  */
3097 void __sched io_schedule(void)
3098 {
3099         struct runqueue *rq = this_rq();
3100
3101         atomic_inc(&rq->nr_iowait);
3102         schedule();
3103         atomic_dec(&rq->nr_iowait);
3104 }
3105
3106 EXPORT_SYMBOL(io_schedule);
3107
3108 long __sched io_schedule_timeout(long timeout)
3109 {
3110         struct runqueue *rq = this_rq();
3111         long ret;
3112
3113         atomic_inc(&rq->nr_iowait);
3114         ret = schedule_timeout(timeout);
3115         atomic_dec(&rq->nr_iowait);
3116         return ret;
3117 }
3118
3119 /**
3120  * sys_sched_get_priority_max - return maximum RT priority.
3121  * @policy: scheduling class.
3122  *
3123  * this syscall returns the maximum rt_priority that can be used
3124  * by a given scheduling class.
3125  */
3126 asmlinkage long sys_sched_get_priority_max(int policy)
3127 {
3128         int ret = -EINVAL;
3129
3130         switch (policy) {
3131         case SCHED_FIFO:
3132         case SCHED_RR:
3133                 ret = MAX_USER_RT_PRIO-1;
3134                 break;
3135         case SCHED_NORMAL:
3136                 ret = 0;
3137                 break;
3138         }
3139         return ret;
3140 }
3141
3142 /**
3143  * sys_sched_get_priority_min - return minimum RT priority.
3144  * @policy: scheduling class.
3145  *
3146  * this syscall returns the minimum rt_priority that can be used
3147  * by a given scheduling class.
3148  */
3149 asmlinkage long sys_sched_get_priority_min(int policy)
3150 {
3151         int ret = -EINVAL;
3152
3153         switch (policy) {
3154         case SCHED_FIFO:
3155         case SCHED_RR:
3156                 ret = 1;
3157                 break;
3158         case SCHED_NORMAL:
3159                 ret = 0;
3160         }
3161         return ret;
3162 }
3163
3164 /**
3165  * sys_sched_rr_get_interval - return the default timeslice of a process.
3166  * @pid: pid of the process.
3167  * @interval: userspace pointer to the timeslice value.
3168  *
3169  * this syscall writes the default timeslice value of a given process
3170  * into the user-space timespec buffer. A value of '0' means infinity.
3171  */
3172 asmlinkage
3173 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
3174 {
3175         int retval = -EINVAL;
3176         struct timespec t;
3177         task_t *p;
3178
3179         if (pid < 0)
3180                 goto out_nounlock;
3181
3182         retval = -ESRCH;
3183         read_lock(&tasklist_lock);
3184         p = find_process_by_pid(pid);
3185         if (!p)
3186                 goto out_unlock;
3187
3188         retval = security_task_getscheduler(p);
3189         if (retval)
3190                 goto out_unlock;
3191
3192         jiffies_to_timespec(p->policy & SCHED_FIFO ?
3193                                 0 : task_timeslice(p), &t);
3194         read_unlock(&tasklist_lock);
3195         retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
3196 out_nounlock:
3197         return retval;
3198 out_unlock:
3199         read_unlock(&tasklist_lock);
3200         return retval;
3201 }
3202
3203 static inline struct task_struct *eldest_child(struct task_struct *p)
3204 {
3205         if (list_empty(&p->children)) return NULL;
3206         return list_entry(p->children.next,struct task_struct,sibling);
3207 }
3208
3209 static inline struct task_struct *older_sibling(struct task_struct *p)
3210 {
3211         if (p->sibling.prev==&p->parent->children) return NULL;
3212         return list_entry(p->sibling.prev,struct task_struct,sibling);
3213 }
3214
3215 static inline struct task_struct *younger_sibling(struct task_struct *p)
3216 {
3217         if (p->sibling.next==&p->parent->children) return NULL;
3218         return list_entry(p->sibling.next,struct task_struct,sibling);
3219 }
3220
3221 static void show_task(task_t * p)
3222 {
3223         task_t *relative;
3224         unsigned state;
3225         unsigned long free = 0;
3226         static const char *stat_nam[] = { "R", "S", "D", "T", "Z", "W" };
3227
3228         printk("%-13.13s ", p->comm);
3229         state = p->state ? __ffs(p->state) + 1 : 0;
3230         if (state < ARRAY_SIZE(stat_nam))
3231                 printk(stat_nam[state]);
3232         else
3233                 printk("?");
3234 #if (BITS_PER_LONG == 32)
3235         if (state == TASK_RUNNING)
3236                 printk(" running ");
3237         else
3238                 printk(" %08lX ", thread_saved_pc(p));
3239 #else
3240         if (state == TASK_RUNNING)
3241                 printk("  running task   ");
3242         else
3243                 printk(" %016lx ", thread_saved_pc(p));
3244 #endif
3245 #ifdef CONFIG_DEBUG_STACK_USAGE
3246         {
3247                 unsigned long * n = (unsigned long *) (p->thread_info+1);
3248                 while (!*n)
3249                         n++;
3250                 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
3251         }
3252 #endif
3253         printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
3254         if ((relative = eldest_child(p)))
3255                 printk("%5d ", relative->pid);
3256         else
3257                 printk("      ");
3258         if ((relative = younger_sibling(p)))
3259                 printk("%7d", relative->pid);
3260         else
3261                 printk("       ");
3262         if ((relative = older_sibling(p)))
3263                 printk(" %5d", relative->pid);
3264         else
3265                 printk("      ");
3266         if (!p->mm)
3267                 printk(" (L-TLB)\n");
3268         else
3269                 printk(" (NOTLB)\n");
3270
3271         if (state != TASK_RUNNING)
3272                 show_stack(p, NULL);
3273 }
3274
3275 void show_state(void)
3276 {
3277         task_t *g, *p;
3278
3279 #if (BITS_PER_LONG == 32)
3280         printk("\n"
3281                "                                               sibling\n");
3282         printk("  task             PC      pid father child younger older\n");
3283 #else
3284         printk("\n"
3285                "                                                       sibling\n");
3286         printk("  task                 PC          pid father child younger older\n");
3287 #endif
3288         read_lock(&tasklist_lock);
3289         do_each_thread(g, p) {
3290                 /*
3291                  * reset the NMI-timeout, listing all files on a slow
3292                  * console might take alot of time:
3293                  */
3294                 touch_nmi_watchdog();
3295                 show_task(p);
3296         } while_each_thread(g, p);
3297
3298         read_unlock(&tasklist_lock);
3299 }
3300
3301 void __devinit init_idle(task_t *idle, int cpu)
3302 {
3303         runqueue_t *idle_rq = cpu_rq(cpu), *rq = cpu_rq(task_cpu(idle));
3304         unsigned long flags;
3305
3306         local_irq_save(flags);
3307         double_rq_lock(idle_rq, rq);
3308
3309         idle_rq->curr = idle_rq->idle = idle;
3310         deactivate_task(idle, rq);
3311         idle->array = NULL;
3312         idle->prio = MAX_PRIO;
3313         idle->state = TASK_RUNNING;
3314         set_task_cpu(idle, cpu);
3315         double_rq_unlock(idle_rq, rq);
3316         set_tsk_need_resched(idle);
3317         local_irq_restore(flags);
3318
3319         /* Set the preempt count _outside_ the spinlocks! */
3320 #ifdef CONFIG_PREEMPT
3321         idle->thread_info->preempt_count = (idle->lock_depth >= 0);
3322 #else
3323         idle->thread_info->preempt_count = 0;
3324 #endif
3325 }
3326
3327 /*
3328  * In a system that switches off the HZ timer nohz_cpu_mask
3329  * indicates which cpus entered this state. This is used
3330  * in the rcu update to wait only for active cpus. For system
3331  * which do not switch off the HZ timer nohz_cpu_mask should
3332  * always be CPU_MASK_NONE.
3333  */
3334 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
3335
3336 #ifdef CONFIG_SMP
3337 /*
3338  * This is how migration works:
3339  *
3340  * 1) we queue a migration_req_t structure in the source CPU's
3341  *    runqueue and wake up that CPU's migration thread.
3342  * 2) we down() the locked semaphore => thread blocks.
3343  * 3) migration thread wakes up (implicitly it forces the migrated
3344  *    thread off the CPU)
3345  * 4) it gets the migration request and checks whether the migrated
3346  *    task is still in the wrong runqueue.
3347  * 5) if it's in the wrong runqueue then the migration thread removes
3348  *    it and puts it into the right queue.
3349  * 6) migration thread up()s the semaphore.
3350  * 7) we wake up and the migration is done.
3351  */
3352
3353 /*
3354  * Change a given task's CPU affinity. Migrate the thread to a
3355  * proper CPU and schedule it away if the CPU it's executing on
3356  * is removed from the allowed bitmask.
3357  *
3358  * NOTE: the caller must have a valid reference to the task, the
3359  * task must not exit() & deallocate itself prematurely.  The
3360  * call is not atomic; no spinlocks may be held.
3361  */
3362 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
3363 {
3364         unsigned long flags;
3365         int ret = 0;
3366         migration_req_t req;
3367         runqueue_t *rq;
3368
3369         rq = task_rq_lock(p, &flags);
3370         if (any_online_cpu(new_mask) == NR_CPUS) {
3371                 ret = -EINVAL;
3372                 goto out;
3373         }
3374
3375         p->cpus_allowed = new_mask;
3376         /* Can the task run on the task's current CPU? If so, we're done */
3377         if (cpu_isset(task_cpu(p), new_mask))
3378                 goto out;
3379
3380         if (migrate_task(p, any_online_cpu(new_mask), &req)) {
3381                 /* Need help from migration thread: drop lock and wait. */
3382                 task_rq_unlock(rq, &flags);
3383                 wake_up_process(rq->migration_thread);
3384                 wait_for_completion(&req.done);
3385                 return 0;
3386         }
3387 out:
3388         task_rq_unlock(rq, &flags);
3389         return ret;
3390 }
3391
3392 EXPORT_SYMBOL_GPL(set_cpus_allowed);
3393
3394 /*
3395  * Move (not current) task off this cpu, onto dest cpu.  We're doing
3396  * this because either it can't run here any more (set_cpus_allowed()
3397  * away from this CPU, or CPU going down), or because we're
3398  * attempting to rebalance this task on exec (sched_balance_exec).
3399  *
3400  * So we race with normal scheduler movements, but that's OK, as long
3401  * as the task is no longer on this CPU.
3402  */
3403 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
3404 {
3405         runqueue_t *rq_dest, *rq_src;
3406
3407         if (unlikely(cpu_is_offline(dest_cpu)))
3408                 return;
3409
3410         rq_src  = cpu_rq(src_cpu);
3411         rq_dest = cpu_rq(dest_cpu);
3412
3413         double_rq_lock(rq_src, rq_dest);
3414         /* Already moved. */
3415         if (task_cpu(p) != src_cpu)
3416                 goto out;
3417         /* Affinity changed (again). */
3418         if (!cpu_isset(dest_cpu, p->cpus_allowed))
3419                 goto out;
3420
3421         set_task_cpu(p, dest_cpu);
3422         if (p->array) {
3423                 /*
3424                  * Sync timestamp with rq_dest's before activating.
3425                  * The same thing could be achieved by doing this step
3426                  * afterwards, and pretending it was a local activate.
3427                  * This way is cleaner and logically correct.
3428                  */
3429                 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
3430                                 + rq_dest->timestamp_last_tick;
3431                 deactivate_task(p, rq_src);
3432                 activate_task(p, rq_dest, 0);
3433                 if (TASK_PREEMPTS_CURR(p, rq_dest))
3434                         resched_task(rq_dest->curr);
3435         }
3436
3437 out:
3438         double_rq_unlock(rq_src, rq_dest);
3439 }
3440
3441 /*
3442  * migration_thread - this is a highprio system thread that performs
3443  * thread migration by bumping thread off CPU then 'pushing' onto
3444  * another runqueue.
3445  */
3446 static int migration_thread(void * data)
3447 {
3448         runqueue_t *rq;
3449         int cpu = (long)data;
3450
3451         rq = cpu_rq(cpu);
3452         BUG_ON(rq->migration_thread != current);
3453
3454         set_current_state(TASK_INTERRUPTIBLE);
3455         while (!kthread_should_stop()) {
3456                 struct list_head *head;
3457                 migration_req_t *req;
3458
3459                 if (current->flags & PF_FREEZE)
3460                         refrigerator(PF_FREEZE);
3461
3462                 spin_lock_irq(&rq->lock);
3463
3464                 if (cpu_is_offline(cpu)) {
3465                         spin_unlock_irq(&rq->lock);
3466                         goto wait_to_die;
3467                 }
3468
3469                 if (rq->active_balance) {
3470                         active_load_balance(rq, cpu);
3471                         rq->active_balance = 0;
3472                 }
3473
3474                 head = &rq->migration_queue;
3475
3476                 if (list_empty(head)) {
3477                         spin_unlock_irq(&rq->lock);
3478                         schedule();
3479                         set_current_state(TASK_INTERRUPTIBLE);
3480                         continue;
3481                 }
3482                 req = list_entry(head->next, migration_req_t, list);
3483                 list_del_init(head->next);
3484
3485                 if (req->type == REQ_MOVE_TASK) {
3486                         spin_unlock(&rq->lock);
3487                         __migrate_task(req->task, smp_processor_id(),
3488                                         req->dest_cpu);
3489                         local_irq_enable();
3490                 } else if (req->type == REQ_SET_DOMAIN) {
3491                         rq->sd = req->sd;
3492                         spin_unlock_irq(&rq->lock);
3493                 } else {
3494                         spin_unlock_irq(&rq->lock);
3495                         WARN_ON(1);
3496                 }
3497
3498                 complete(&req->done);
3499         }
3500         __set_current_state(TASK_RUNNING);
3501         return 0;
3502
3503 wait_to_die:
3504         /* Wait for kthread_stop */
3505         set_current_state(TASK_INTERRUPTIBLE);
3506         while (!kthread_should_stop()) {
3507                 schedule();
3508                 set_current_state(TASK_INTERRUPTIBLE);
3509         }
3510         __set_current_state(TASK_RUNNING);
3511         return 0;
3512 }
3513
3514 #ifdef CONFIG_HOTPLUG_CPU
3515 /* migrate_all_tasks - function to migrate all tasks from the dead cpu.  */
3516 static void migrate_all_tasks(int src_cpu)
3517 {
3518         struct task_struct *tsk, *t;
3519         int dest_cpu;
3520         unsigned int node;
3521
3522         write_lock_irq(&tasklist_lock);
3523
3524         /* watch out for per node tasks, let's stay on this node */
3525         node = cpu_to_node(src_cpu);
3526
3527         do_each_thread(t, tsk) {
3528                 cpumask_t mask;
3529                 if (tsk == current)
3530                         continue;
3531
3532                 if (task_cpu(tsk) != src_cpu)
3533                         continue;
3534
3535                 /* Figure out where this task should go (attempting to
3536                  * keep it on-node), and check if it can be migrated
3537                  * as-is.  NOTE that kernel threads bound to more than
3538                  * one online cpu will be migrated. */
3539                 mask = node_to_cpumask(node);
3540                 cpus_and(mask, mask, tsk->cpus_allowed);
3541                 dest_cpu = any_online_cpu(mask);
3542                 if (dest_cpu == NR_CPUS)
3543                         dest_cpu = any_online_cpu(tsk->cpus_allowed);
3544                 if (dest_cpu == NR_CPUS) {
3545                         cpus_clear(tsk->cpus_allowed);
3546                         cpus_complement(tsk->cpus_allowed);
3547                         dest_cpu = any_online_cpu(tsk->cpus_allowed);
3548
3549                         /* Don't tell them about moving exiting tasks
3550                            or kernel threads (both mm NULL), since
3551                            they never leave kernel. */
3552                         if (tsk->mm && printk_ratelimit())
3553                                 printk(KERN_INFO "process %d (%s) no "
3554                                        "longer affine to cpu%d\n",
3555                                        tsk->pid, tsk->comm, src_cpu);
3556                 }
3557
3558                 __migrate_task(tsk, src_cpu, dest_cpu);
3559         } while_each_thread(t, tsk);
3560
3561         write_unlock_irq(&tasklist_lock);
3562 }
3563
3564 /* Schedules idle task to be the next runnable task on current CPU.
3565  * It does so by boosting its priority to highest possible and adding it to
3566  * the _front_ of runqueue. Used by CPU offline code.
3567  */
3568 void sched_idle_next(void)
3569 {
3570         int cpu = smp_processor_id();
3571         runqueue_t *rq = this_rq();
3572         struct task_struct *p = rq->idle;
3573         unsigned long flags;
3574
3575         /* cpu has to be offline */
3576         BUG_ON(cpu_online(cpu));
3577
3578         /* Strictly not necessary since rest of the CPUs are stopped by now
3579          * and interrupts disabled on current cpu.
3580          */
3581         spin_lock_irqsave(&rq->lock, flags);
3582
3583         __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
3584         /* Add idle task to _front_ of it's priority queue */
3585         __activate_idle_task(p, rq);
3586
3587         spin_unlock_irqrestore(&rq->lock, flags);
3588 }
3589 #endif /* CONFIG_HOTPLUG_CPU */
3590
3591 /*
3592  * migration_call - callback that gets triggered when a CPU is added.
3593  * Here we can start up the necessary migration thread for the new CPU.
3594  */
3595 static int migration_call(struct notifier_block *nfb, unsigned long action,
3596                           void *hcpu)
3597 {
3598         int cpu = (long)hcpu;
3599         struct task_struct *p;
3600         struct runqueue *rq;
3601         unsigned long flags;
3602
3603         switch (action) {
3604         case CPU_UP_PREPARE:
3605                 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
3606                 if (IS_ERR(p))
3607                         return NOTIFY_BAD;
3608                 kthread_bind(p, cpu);
3609                 /* Must be high prio: stop_machine expects to yield to it. */
3610                 rq = task_rq_lock(p, &flags);
3611                 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
3612                 task_rq_unlock(rq, &flags);
3613                 cpu_rq(cpu)->migration_thread = p;
3614                 break;
3615         case CPU_ONLINE:
3616                 /* Strictly unneccessary, as first user will wake it. */
3617                 wake_up_process(cpu_rq(cpu)->migration_thread);
3618                 break;
3619 #ifdef CONFIG_HOTPLUG_CPU
3620         case CPU_UP_CANCELED:
3621                 /* Unbind it from offline cpu so it can run.  Fall thru. */
3622                 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
3623                 kthread_stop(cpu_rq(cpu)->migration_thread);
3624                 cpu_rq(cpu)->migration_thread = NULL;
3625                 break;
3626         case CPU_DEAD:
3627                 migrate_all_tasks(cpu);
3628                 rq = cpu_rq(cpu);
3629                 kthread_stop(rq->migration_thread);
3630                 rq->migration_thread = NULL;
3631                 /* Idle task back to normal (off runqueue, low prio) */
3632                 rq = task_rq_lock(rq->idle, &flags);
3633                 deactivate_task(rq->idle, rq);
3634                 rq->idle->static_prio = MAX_PRIO;
3635                 __setscheduler(rq->idle, SCHED_NORMAL, 0);
3636                 task_rq_unlock(rq, &flags);
3637                 BUG_ON(rq->nr_running != 0);
3638
3639                 /* No need to migrate the tasks: it was best-effort if
3640                  * they didn't do lock_cpu_hotplug().  Just wake up
3641                  * the requestors. */
3642                 spin_lock_irq(&rq->lock);
3643                 while (!list_empty(&rq->migration_queue)) {
3644                         migration_req_t *req;
3645                         req = list_entry(rq->migration_queue.next,
3646                                          migration_req_t, list);
3647                         BUG_ON(req->type != REQ_MOVE_TASK);
3648                         list_del_init(&req->list);
3649                         complete(&req->done);
3650                 }
3651                 spin_unlock_irq(&rq->lock);
3652                 break;
3653 #endif
3654         }
3655         return NOTIFY_OK;
3656 }
3657
3658 /* Register at highest priority so that task migration (migrate_all_tasks)
3659  * happens before everything else.
3660  */
3661 static struct notifier_block __devinitdata migration_notifier = {
3662         .notifier_call = migration_call,
3663         .priority = 10
3664 };
3665
3666 int __init migration_init(void)
3667 {
3668         void *cpu = (void *)(long)smp_processor_id();
3669         /* Start one for boot CPU. */
3670         migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
3671         migration_call(&migration_notifier, CPU_ONLINE, cpu);
3672         register_cpu_notifier(&migration_notifier);
3673         return 0;
3674 }
3675 #endif
3676
3677 /*
3678  * The 'big kernel lock'
3679  *
3680  * This spinlock is taken and released recursively by lock_kernel()
3681  * and unlock_kernel().  It is transparently dropped and reaquired
3682  * over schedule().  It is used to protect legacy code that hasn't
3683  * been migrated to a proper locking design yet.
3684  *
3685  * Don't use in new code.
3686  *
3687  * Note: spinlock debugging needs this even on !CONFIG_SMP.
3688  */
3689 spinlock_t kernel_flag __cacheline_aligned_in_smp = SPIN_LOCK_UNLOCKED;
3690 EXPORT_SYMBOL(kernel_flag);
3691
3692 #ifdef CONFIG_SMP
3693 /* Attach the domain 'sd' to 'cpu' as its base domain */
3694 void cpu_attach_domain(struct sched_domain *sd, int cpu)
3695 {
3696         migration_req_t req;
3697         unsigned long flags;
3698         runqueue_t *rq = cpu_rq(cpu);
3699         int local = 1;
3700
3701         lock_cpu_hotplug();
3702
3703         spin_lock_irqsave(&rq->lock, flags);
3704
3705         if (cpu == smp_processor_id() || !cpu_online(cpu)) {
3706                 rq->sd = sd;
3707         } else {
3708                 init_completion(&req.done);
3709                 req.type = REQ_SET_DOMAIN;
3710                 req.sd = sd;
3711                 list_add(&req.list, &rq->migration_queue);
3712                 local = 0;
3713         }
3714
3715         spin_unlock_irqrestore(&rq->lock, flags);
3716
3717         if (!local) {
3718                 wake_up_process(rq->migration_thread);
3719                 wait_for_completion(&req.done);
3720         }
3721
3722         unlock_cpu_hotplug();
3723 }
3724
3725 #ifdef ARCH_HAS_SCHED_DOMAIN
3726 extern void __init arch_init_sched_domains(void);
3727 #else
3728 static struct sched_group sched_group_cpus[NR_CPUS];
3729 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
3730 #ifdef CONFIG_NUMA
3731 static struct sched_group sched_group_nodes[MAX_NUMNODES];
3732 static DEFINE_PER_CPU(struct sched_domain, node_domains);
3733 static void __init arch_init_sched_domains(void)
3734 {
3735         int i;
3736         struct sched_group *first_node = NULL, *last_node = NULL;
3737
3738         /* Set up domains */
3739         for_each_cpu(i) {
3740                 int node = cpu_to_node(i);
3741                 cpumask_t nodemask = node_to_cpumask(node);
3742                 struct sched_domain *node_sd = &per_cpu(node_domains, i);
3743                 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3744
3745                 *node_sd = SD_NODE_INIT;
3746                 node_sd->span = cpu_possible_map;
3747                 node_sd->groups = &sched_group_nodes[cpu_to_node(i)];
3748
3749                 *cpu_sd = SD_CPU_INIT;
3750                 cpus_and(cpu_sd->span, nodemask, cpu_possible_map);
3751                 cpu_sd->groups = &sched_group_cpus[i];
3752                 cpu_sd->parent = node_sd;
3753         }
3754
3755         /* Set up groups */
3756         for (i = 0; i < MAX_NUMNODES; i++) {
3757                 cpumask_t tmp = node_to_cpumask(i);
3758                 cpumask_t nodemask;
3759                 struct sched_group *first_cpu = NULL, *last_cpu = NULL;
3760                 struct sched_group *node = &sched_group_nodes[i];
3761                 int j;
3762
3763                 cpus_and(nodemask, tmp, cpu_possible_map);
3764
3765                 if (cpus_empty(nodemask))
3766                         continue;
3767
3768                 node->cpumask = nodemask;
3769                 node->cpu_power = SCHED_LOAD_SCALE * cpus_weight(node->cpumask);
3770
3771                 for_each_cpu_mask(j, node->cpumask) {
3772                         struct sched_group *cpu = &sched_group_cpus[j];
3773
3774                         cpus_clear(cpu->cpumask);
3775                         cpu_set(j, cpu->cpumask);
3776                         cpu->cpu_power = SCHED_LOAD_SCALE;
3777
3778                         if (!first_cpu)
3779                                 first_cpu = cpu;
3780                         if (last_cpu)
3781                                 last_cpu->next = cpu;
3782                         last_cpu = cpu;
3783                 }
3784                 last_cpu->next = first_cpu;
3785
3786                 if (!first_node)
3787                         first_node = node;
3788                 if (last_node)
3789                         last_node->next = node;
3790                 last_node = node;
3791         }
3792         last_node->next = first_node;
3793
3794         mb();
3795         for_each_cpu(i) {
3796                 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3797                 cpu_attach_domain(cpu_sd, i);
3798         }
3799 }
3800
3801 #else /* !CONFIG_NUMA */
3802 static void __init arch_init_sched_domains(void)
3803 {
3804         int i;
3805         struct sched_group *first_cpu = NULL, *last_cpu = NULL;
3806
3807         /* Set up domains */
3808         for_each_cpu(i) {
3809                 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3810
3811                 *cpu_sd = SD_CPU_INIT;
3812                 cpu_sd->span = cpu_possible_map;
3813                 cpu_sd->groups = &sched_group_cpus[i];
3814         }
3815
3816         /* Set up CPU groups */
3817         for_each_cpu_mask(i, cpu_possible_map) {
3818                 struct sched_group *cpu = &sched_group_cpus[i];
3819
3820                 cpus_clear(cpu->cpumask);
3821                 cpu_set(i, cpu->cpumask);
3822                 cpu->cpu_power = SCHED_LOAD_SCALE;
3823
3824                 if (!first_cpu)
3825                         first_cpu = cpu;
3826                 if (last_cpu)
3827                         last_cpu->next = cpu;
3828                 last_cpu = cpu;
3829         }
3830         last_cpu->next = first_cpu;
3831
3832         mb(); /* domains were modified outside the lock */
3833         for_each_cpu(i) {
3834                 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3835                 cpu_attach_domain(cpu_sd, i);
3836         }
3837 }
3838
3839 #endif /* CONFIG_NUMA */
3840 #endif /* ARCH_HAS_SCHED_DOMAIN */
3841
3842 #define SCHED_DOMAIN_DEBUG
3843 #ifdef SCHED_DOMAIN_DEBUG
3844 void sched_domain_debug(void)
3845 {
3846         int i;
3847
3848         for_each_cpu(i) {
3849                 runqueue_t *rq = cpu_rq(i);
3850                 struct sched_domain *sd;
3851                 int level = 0;
3852
3853                 sd = rq->sd;
3854
3855                 printk(KERN_DEBUG "CPU%d: %s\n",
3856                                 i, (cpu_online(i) ? " online" : "offline"));
3857
3858                 do {
3859                         int j;
3860                         char str[NR_CPUS];
3861                         struct sched_group *group = sd->groups;
3862                         cpumask_t groupmask, tmp;
3863
3864                         cpumask_scnprintf(str, NR_CPUS, sd->span);
3865                         cpus_clear(groupmask);
3866
3867                         printk(KERN_DEBUG);
3868                         for (j = 0; j < level + 1; j++)
3869                                 printk(" ");
3870                         printk("domain %d: span %s\n", level, str);
3871
3872                         if (!cpu_isset(i, sd->span))
3873                                 printk(KERN_DEBUG "ERROR domain->span does not contain CPU%d\n", i);
3874                         if (!cpu_isset(i, group->cpumask))
3875                                 printk(KERN_DEBUG "ERROR domain->groups does not contain CPU%d\n", i);
3876                         if (!group->cpu_power)
3877                                 printk(KERN_DEBUG "ERROR domain->cpu_power not set\n");
3878
3879                         printk(KERN_DEBUG);
3880                         for (j = 0; j < level + 2; j++)
3881                                 printk(" ");
3882                         printk("groups:");
3883                         do {
3884                                 if (!group) {
3885                                         printk(" ERROR: NULL");
3886                                         break;
3887                                 }
3888
3889                                 if (!cpus_weight(group->cpumask))
3890                                         printk(" ERROR empty group:");
3891
3892                                 cpus_and(tmp, groupmask, group->cpumask);
3893                                 if (cpus_weight(tmp) > 0)
3894                                         printk(" ERROR repeated CPUs:");
3895
3896                                 cpus_or(groupmask, groupmask, group->cpumask);
3897
3898                                 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
3899                                 printk(" %s", str);
3900
3901                                 group = group->next;
3902                         } while (group != sd->groups);
3903                         printk("\n");
3904
3905                         if (!cpus_equal(sd->span, groupmask))
3906                                 printk(KERN_DEBUG "ERROR groups don't span domain->span\n");
3907
3908                         level++;
3909                         sd = sd->parent;
3910
3911                         if (sd) {
3912                                 cpus_and(tmp, groupmask, sd->span);
3913                                 if (!cpus_equal(tmp, groupmask))
3914                                         printk(KERN_DEBUG "ERROR parent span is not a superset of domain->span\n");
3915                         }
3916
3917                 } while (sd);
3918         }
3919 }
3920 #else
3921 #define sched_domain_debug() {}
3922 #endif
3923
3924 void __init sched_init_smp(void)
3925 {
3926         arch_init_sched_domains();
3927         sched_domain_debug();
3928 }
3929 #else
3930 void __init sched_init_smp(void)
3931 {
3932 }
3933 #endif /* CONFIG_SMP */
3934
3935 int in_sched_functions(unsigned long addr)
3936 {
3937         /* Linker adds these: start and end of __sched functions */
3938         extern char __sched_text_start[], __sched_text_end[];
3939         return addr >= (unsigned long)__sched_text_start
3940                 && addr < (unsigned long)__sched_text_end;
3941 }
3942
3943 void __init sched_init(void)
3944 {
3945         runqueue_t *rq;
3946         int i, j, k;
3947
3948 #ifdef CONFIG_SMP
3949         /* Set up an initial dummy domain for early boot */
3950         static struct sched_domain sched_domain_init;
3951         static struct sched_group sched_group_init;
3952         cpumask_t cpu_mask_all = CPU_MASK_ALL;
3953
3954         memset(&sched_domain_init, 0, sizeof(struct sched_domain));
3955         sched_domain_init.span = cpu_mask_all;
3956         sched_domain_init.groups = &sched_group_init;
3957         sched_domain_init.last_balance = jiffies;
3958         sched_domain_init.balance_interval = INT_MAX; /* Don't balance */
3959
3960         memset(&sched_group_init, 0, sizeof(struct sched_group));
3961         sched_group_init.cpumask = cpu_mask_all;
3962         sched_group_init.next = &sched_group_init;
3963         sched_group_init.cpu_power = SCHED_LOAD_SCALE;
3964 #endif
3965
3966         for (i = 0; i < NR_CPUS; i++) {
3967                 prio_array_t *array;
3968
3969                 rq = cpu_rq(i);
3970                 spin_lock_init(&rq->lock);
3971                 rq->active = rq->arrays;
3972                 rq->expired = rq->arrays + 1;
3973                 rq->best_expired_prio = MAX_PRIO;
3974
3975 #ifdef CONFIG_SMP
3976                 rq->sd = &sched_domain_init;
3977                 rq->cpu_load = 0;
3978                 rq->active_balance = 0;
3979                 rq->push_cpu = 0;
3980                 rq->migration_thread = NULL;
3981                 INIT_LIST_HEAD(&rq->migration_queue);
3982 #endif
3983                 INIT_LIST_HEAD(&rq->hold_queue);
3984                 atomic_set(&rq->nr_iowait, 0);
3985
3986                 for (j = 0; j < 2; j++) {
3987                         array = rq->arrays + j;
3988                         for (k = 0; k < MAX_PRIO; k++) {
3989                                 INIT_LIST_HEAD(array->queue + k);
3990                                 __clear_bit(k, array->bitmap);
3991                         }
3992                         // delimiter for bitsearch
3993                         __set_bit(MAX_PRIO, array->bitmap);
3994                 }
3995         }
3996         /*
3997          * We have to do a little magic to get the first
3998          * thread right in SMP mode.
3999          */
4000         rq = this_rq();
4001         rq->curr = current;
4002         rq->idle = current;
4003         set_task_cpu(current, smp_processor_id());
4004         wake_up_forked_process(current);
4005
4006         /*
4007          * The boot idle thread does lazy MMU switching as well:
4008          */
4009         atomic_inc(&init_mm.mm_count);
4010         enter_lazy_tlb(&init_mm, current);
4011 }
4012
4013 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4014 void __might_sleep(char *file, int line)
4015 {
4016 #if defined(in_atomic)
4017         static unsigned long prev_jiffy;        /* ratelimiting */
4018
4019         if ((in_atomic() || irqs_disabled()) &&
4020             system_state == SYSTEM_RUNNING) {
4021                 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
4022                         return;
4023                 prev_jiffy = jiffies;
4024                 printk(KERN_ERR "Debug: sleeping function called from invalid"
4025                                 " context at %s:%d\n", file, line);
4026                 printk("in_atomic():%d, irqs_disabled():%d\n",
4027                         in_atomic(), irqs_disabled());
4028                 dump_stack();
4029         }
4030 #endif
4031 }
4032 EXPORT_SYMBOL(__might_sleep);
4033 #endif
4034
4035
4036 #if defined(CONFIG_SMP) && defined(CONFIG_PREEMPT)
4037 /*
4038  * This could be a long-held lock.  If another CPU holds it for a long time,
4039  * and that CPU is not asked to reschedule then *this* CPU will spin on the
4040  * lock for a long time, even if *this* CPU is asked to reschedule.
4041  *
4042  * So what we do here, in the slow (contended) path is to spin on the lock by
4043  * hand while permitting preemption.
4044  *
4045  * Called inside preempt_disable().
4046  */
4047 void __sched __preempt_spin_lock(spinlock_t *lock)
4048 {
4049         if (preempt_count() > 1) {
4050                 _raw_spin_lock(lock);
4051                 return;
4052         }
4053         do {
4054                 preempt_enable();
4055                 while (spin_is_locked(lock))
4056                         cpu_relax();
4057                 preempt_disable();
4058         } while (!_raw_spin_trylock(lock));
4059 }
4060
4061 EXPORT_SYMBOL(__preempt_spin_lock);
4062
4063 void __sched __preempt_write_lock(rwlock_t *lock)
4064 {
4065         if (preempt_count() > 1) {
4066                 _raw_write_lock(lock);
4067                 return;
4068         }
4069
4070         do {
4071                 preempt_enable();
4072                 while (rwlock_is_locked(lock))
4073                         cpu_relax();
4074                 preempt_disable();
4075         } while (!_raw_write_trylock(lock));
4076 }
4077
4078 EXPORT_SYMBOL(__preempt_write_lock);
4079 #endif /* defined(CONFIG_SMP) && defined(CONFIG_PREEMPT) */