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