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