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