ckrm-E15 memory controller
[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         add_delay_ts(prev,runcpu_total,prev->timestamp,now);
2299         prev->timestamp = now;
2300
2301         if (likely(prev != next)) {
2302                 add_delay_ts(next,waitcpu_total,next->timestamp,now);
2303                 inc_delay(next,runs);
2304                 next->timestamp = now;
2305                 rq->nr_switches++;
2306                 rq->curr = next;
2307                 ++*switch_count;
2308
2309                 prepare_arch_switch(rq, next);
2310                 prev = context_switch(rq, prev, next);
2311                 barrier();
2312
2313                 finish_task_switch(prev);
2314         } else
2315                 spin_unlock_irq(&rq->lock);
2316
2317         reacquire_kernel_lock(current);
2318         preempt_enable_no_resched();
2319         if (test_thread_flag(TIF_NEED_RESCHED))
2320                 goto need_resched;
2321 }
2322
2323 EXPORT_SYMBOL(schedule);
2324
2325 #ifdef CONFIG_PREEMPT
2326 /*
2327  * this is is the entry point to schedule() from in-kernel preemption
2328  * off of preempt_enable.  Kernel preemptions off return from interrupt
2329  * occur there and call schedule directly.
2330  */
2331 asmlinkage void __sched preempt_schedule(void)
2332 {
2333         struct thread_info *ti = current_thread_info();
2334
2335         /*
2336          * If there is a non-zero preempt_count or interrupts are disabled,
2337          * we do not want to preempt the current task.  Just return..
2338          */
2339         if (unlikely(ti->preempt_count || irqs_disabled()))
2340                 return;
2341
2342 need_resched:
2343         ti->preempt_count = PREEMPT_ACTIVE;
2344         schedule();
2345         ti->preempt_count = 0;
2346
2347         /* we could miss a preemption opportunity between schedule and now */
2348         barrier();
2349         if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2350                 goto need_resched;
2351 }
2352
2353 EXPORT_SYMBOL(preempt_schedule);
2354 #endif /* CONFIG_PREEMPT */
2355
2356 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
2357 {
2358         task_t *p = curr->task;
2359         return try_to_wake_up(p, mode, sync);
2360 }
2361
2362 EXPORT_SYMBOL(default_wake_function);
2363
2364 /*
2365  * The core wakeup function.  Non-exclusive wakeups (nr_exclusive == 0) just
2366  * wake everything up.  If it's an exclusive wakeup (nr_exclusive == small +ve
2367  * number) then we wake all the non-exclusive tasks and one exclusive task.
2368  *
2369  * There are circumstances in which we can try to wake a task which has already
2370  * started to run but is not in state TASK_RUNNING.  try_to_wake_up() returns
2371  * zero in this (rare) case, and we handle it by continuing to scan the queue.
2372  */
2373 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
2374                              int nr_exclusive, int sync, void *key)
2375 {
2376         struct list_head *tmp, *next;
2377
2378         list_for_each_safe(tmp, next, &q->task_list) {
2379                 wait_queue_t *curr;
2380                 unsigned flags;
2381                 curr = list_entry(tmp, wait_queue_t, task_list);
2382                 flags = curr->flags;
2383                 if (curr->func(curr, mode, sync, key) &&
2384                     (flags & WQ_FLAG_EXCLUSIVE) &&
2385                     !--nr_exclusive)
2386                         break;
2387         }
2388 }
2389
2390 /**
2391  * __wake_up - wake up threads blocked on a waitqueue.
2392  * @q: the waitqueue
2393  * @mode: which threads
2394  * @nr_exclusive: how many wake-one or wake-many threads to wake up
2395  */
2396 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
2397                                 int nr_exclusive, void *key)
2398 {
2399         unsigned long flags;
2400
2401         spin_lock_irqsave(&q->lock, flags);
2402         __wake_up_common(q, mode, nr_exclusive, 0, key);
2403         spin_unlock_irqrestore(&q->lock, flags);
2404 }
2405
2406 EXPORT_SYMBOL(__wake_up);
2407
2408 /*
2409  * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
2410  */
2411 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
2412 {
2413         __wake_up_common(q, mode, 1, 0, NULL);
2414 }
2415
2416 /**
2417  * __wake_up - sync- wake up threads blocked on a waitqueue.
2418  * @q: the waitqueue
2419  * @mode: which threads
2420  * @nr_exclusive: how many wake-one or wake-many threads to wake up
2421  *
2422  * The sync wakeup differs that the waker knows that it will schedule
2423  * away soon, so while the target thread will be woken up, it will not
2424  * be migrated to another CPU - ie. the two threads are 'synchronized'
2425  * with each other. This can prevent needless bouncing between CPUs.
2426  *
2427  * On UP it can prevent extra preemption.
2428  */
2429 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
2430 {
2431         unsigned long flags;
2432         int sync = 1;
2433
2434         if (unlikely(!q))
2435                 return;
2436
2437         if (unlikely(!nr_exclusive))
2438                 sync = 0;
2439
2440         spin_lock_irqsave(&q->lock, flags);
2441         __wake_up_common(q, mode, nr_exclusive, sync, NULL);
2442         spin_unlock_irqrestore(&q->lock, flags);
2443 }
2444 EXPORT_SYMBOL_GPL(__wake_up_sync);      /* For internal use only */
2445
2446 void fastcall complete(struct completion *x)
2447 {
2448         unsigned long flags;
2449
2450         spin_lock_irqsave(&x->wait.lock, flags);
2451         x->done++;
2452         __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2453                          1, 0, NULL);
2454         spin_unlock_irqrestore(&x->wait.lock, flags);
2455 }
2456 EXPORT_SYMBOL(complete);
2457
2458 void fastcall complete_all(struct completion *x)
2459 {
2460         unsigned long flags;
2461
2462         spin_lock_irqsave(&x->wait.lock, flags);
2463         x->done += UINT_MAX/2;
2464         __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2465                          0, 0, NULL);
2466         spin_unlock_irqrestore(&x->wait.lock, flags);
2467 }
2468 EXPORT_SYMBOL(complete_all);
2469
2470 void fastcall __sched wait_for_completion(struct completion *x)
2471 {
2472         might_sleep();
2473         spin_lock_irq(&x->wait.lock);
2474         if (!x->done) {
2475                 DECLARE_WAITQUEUE(wait, current);
2476
2477                 wait.flags |= WQ_FLAG_EXCLUSIVE;
2478                 __add_wait_queue_tail(&x->wait, &wait);
2479                 do {
2480                         __set_current_state(TASK_UNINTERRUPTIBLE);
2481                         spin_unlock_irq(&x->wait.lock);
2482                         schedule();
2483                         spin_lock_irq(&x->wait.lock);
2484                 } while (!x->done);
2485                 __remove_wait_queue(&x->wait, &wait);
2486         }
2487         x->done--;
2488         spin_unlock_irq(&x->wait.lock);
2489 }
2490 EXPORT_SYMBOL(wait_for_completion);
2491
2492 #define SLEEP_ON_VAR                                    \
2493         unsigned long flags;                            \
2494         wait_queue_t wait;                              \
2495         init_waitqueue_entry(&wait, current);
2496
2497 #define SLEEP_ON_HEAD                                   \
2498         spin_lock_irqsave(&q->lock,flags);              \
2499         __add_wait_queue(q, &wait);                     \
2500         spin_unlock(&q->lock);
2501
2502 #define SLEEP_ON_TAIL                                   \
2503         spin_lock_irq(&q->lock);                        \
2504         __remove_wait_queue(q, &wait);                  \
2505         spin_unlock_irqrestore(&q->lock, flags);
2506
2507 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
2508 {
2509         SLEEP_ON_VAR
2510
2511         current->state = TASK_INTERRUPTIBLE;
2512
2513         SLEEP_ON_HEAD
2514         schedule();
2515         SLEEP_ON_TAIL
2516 }
2517
2518 EXPORT_SYMBOL(interruptible_sleep_on);
2519
2520 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
2521 {
2522         SLEEP_ON_VAR
2523
2524         current->state = TASK_INTERRUPTIBLE;
2525
2526         SLEEP_ON_HEAD
2527         timeout = schedule_timeout(timeout);
2528         SLEEP_ON_TAIL
2529
2530         return timeout;
2531 }
2532
2533 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
2534
2535 void fastcall __sched sleep_on(wait_queue_head_t *q)
2536 {
2537         SLEEP_ON_VAR
2538
2539         current->state = TASK_UNINTERRUPTIBLE;
2540
2541         SLEEP_ON_HEAD
2542         schedule();
2543         SLEEP_ON_TAIL
2544 }
2545
2546 EXPORT_SYMBOL(sleep_on);
2547
2548 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
2549 {
2550         SLEEP_ON_VAR
2551
2552         current->state = TASK_UNINTERRUPTIBLE;
2553
2554         SLEEP_ON_HEAD
2555         timeout = schedule_timeout(timeout);
2556         SLEEP_ON_TAIL
2557
2558         return timeout;
2559 }
2560
2561 EXPORT_SYMBOL(sleep_on_timeout);
2562
2563 void set_user_nice(task_t *p, long nice)
2564 {
2565         unsigned long flags;
2566         prio_array_t *array;
2567         runqueue_t *rq;
2568         int old_prio, new_prio, delta;
2569
2570         if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
2571                 return;
2572         /*
2573          * We have to be careful, if called from sys_setpriority(),
2574          * the task might be in the middle of scheduling on another CPU.
2575          */
2576         rq = task_rq_lock(p, &flags);
2577         /*
2578          * The RT priorities are set via setscheduler(), but we still
2579          * allow the 'normal' nice value to be set - but as expected
2580          * it wont have any effect on scheduling until the task is
2581          * not SCHED_NORMAL:
2582          */
2583         if (rt_task(p)) {
2584                 p->static_prio = NICE_TO_PRIO(nice);
2585                 goto out_unlock;
2586         }
2587         array = p->array;
2588         if (array)
2589                 dequeue_task(p, array);
2590
2591         old_prio = p->prio;
2592         new_prio = NICE_TO_PRIO(nice);
2593         delta = new_prio - old_prio;
2594         p->static_prio = NICE_TO_PRIO(nice);
2595         p->prio += delta;
2596
2597         if (array) {
2598                 enqueue_task(p, array);
2599                 /*
2600                  * If the task increased its priority or is running and
2601                  * lowered its priority, then reschedule its CPU:
2602                  */
2603                 if (delta < 0 || (delta > 0 && task_running(rq, p)))
2604                         resched_task(rq->curr);
2605         }
2606 out_unlock:
2607         task_rq_unlock(rq, &flags);
2608 }
2609
2610 EXPORT_SYMBOL(set_user_nice);
2611
2612 #ifdef __ARCH_WANT_SYS_NICE
2613
2614 /*
2615  * sys_nice - change the priority of the current process.
2616  * @increment: priority increment
2617  *
2618  * sys_setpriority is a more generic, but much slower function that
2619  * does similar things.
2620  */
2621 asmlinkage long sys_nice(int increment)
2622 {
2623         int retval;
2624         long nice;
2625
2626         /*
2627          * Setpriority might change our priority at the same moment.
2628          * We don't have to worry. Conceptually one call occurs first
2629          * and we have a single winner.
2630          */
2631         if (increment < 0) {
2632                 if (!capable(CAP_SYS_NICE))
2633                         return -EPERM;
2634                 if (increment < -40)
2635                         increment = -40;
2636         }
2637         if (increment > 40)
2638                 increment = 40;
2639
2640         nice = PRIO_TO_NICE(current->static_prio) + increment;
2641         if (nice < -20)
2642                 nice = -20;
2643         if (nice > 19)
2644                 nice = 19;
2645
2646         retval = security_task_setnice(current, nice);
2647         if (retval)
2648                 return retval;
2649
2650         set_user_nice(current, nice);
2651         return 0;
2652 }
2653
2654 #endif
2655
2656 /**
2657  * task_prio - return the priority value of a given task.
2658  * @p: the task in question.
2659  *
2660  * This is the priority value as seen by users in /proc.
2661  * RT tasks are offset by -200. Normal tasks are centered
2662  * around 0, value goes from -16 to +15.
2663  */
2664 int task_prio(task_t *p)
2665 {
2666         return p->prio - MAX_RT_PRIO;
2667 }
2668
2669 /**
2670  * task_nice - return the nice value of a given task.
2671  * @p: the task in question.
2672  */
2673 int task_nice(task_t *p)
2674 {
2675         return TASK_NICE(p);
2676 }
2677
2678 EXPORT_SYMBOL(task_nice);
2679
2680 /**
2681  * idle_cpu - is a given cpu idle currently?
2682  * @cpu: the processor in question.
2683  */
2684 int idle_cpu(int cpu)
2685 {
2686         return cpu_curr(cpu) == cpu_rq(cpu)->idle;
2687 }
2688
2689 EXPORT_SYMBOL_GPL(idle_cpu);
2690
2691 /**
2692  * find_process_by_pid - find a process with a matching PID value.
2693  * @pid: the pid in question.
2694  */
2695 static inline task_t *find_process_by_pid(pid_t pid)
2696 {
2697         return pid ? find_task_by_pid(pid) : current;
2698 }
2699
2700 /* Actually do priority change: must hold rq lock. */
2701 static void __setscheduler(struct task_struct *p, int policy, int prio)
2702 {
2703         BUG_ON(p->array);
2704         p->policy = policy;
2705         p->rt_priority = prio;
2706         if (policy != SCHED_NORMAL)
2707                 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
2708         else
2709                 p->prio = p->static_prio;
2710 }
2711
2712 /*
2713  * setscheduler - change the scheduling policy and/or RT priority of a thread.
2714  */
2715 static int setscheduler(pid_t pid, int policy, struct sched_param __user *param)
2716 {
2717         struct sched_param lp;
2718         int retval = -EINVAL;
2719         int oldprio;
2720         prio_array_t *array;
2721         unsigned long flags;
2722         runqueue_t *rq;
2723         task_t *p;
2724
2725         if (!param || pid < 0)
2726                 goto out_nounlock;
2727
2728         retval = -EFAULT;
2729         if (copy_from_user(&lp, param, sizeof(struct sched_param)))
2730                 goto out_nounlock;
2731
2732         /*
2733          * We play safe to avoid deadlocks.
2734          */
2735         read_lock_irq(&tasklist_lock);
2736
2737         p = find_process_by_pid(pid);
2738
2739         retval = -ESRCH;
2740         if (!p)
2741                 goto out_unlock_tasklist;
2742
2743         /*
2744          * To be able to change p->policy safely, the apropriate
2745          * runqueue lock must be held.
2746          */
2747         rq = task_rq_lock(p, &flags);
2748
2749         if (policy < 0)
2750                 policy = p->policy;
2751         else {
2752                 retval = -EINVAL;
2753                 if (policy != SCHED_FIFO && policy != SCHED_RR &&
2754                                 policy != SCHED_NORMAL)
2755                         goto out_unlock;
2756         }
2757
2758         /*
2759          * Valid priorities for SCHED_FIFO and SCHED_RR are
2760          * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
2761          */
2762         retval = -EINVAL;
2763         if (lp.sched_priority < 0 || lp.sched_priority > MAX_USER_RT_PRIO-1)
2764                 goto out_unlock;
2765         if ((policy == SCHED_NORMAL) != (lp.sched_priority == 0))
2766                 goto out_unlock;
2767
2768         retval = -EPERM;
2769         if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
2770             !capable(CAP_SYS_NICE))
2771                 goto out_unlock;
2772         if ((current->euid != p->euid) && (current->euid != p->uid) &&
2773             !capable(CAP_SYS_NICE))
2774                 goto out_unlock;
2775
2776         retval = security_task_setscheduler(p, policy, &lp);
2777         if (retval)
2778                 goto out_unlock;
2779
2780         array = p->array;
2781         if (array)
2782                 deactivate_task(p, task_rq(p));
2783         retval = 0;
2784         oldprio = p->prio;
2785         __setscheduler(p, policy, lp.sched_priority);
2786         if (array) {
2787                 __activate_task(p, task_rq(p));
2788                 /*
2789                  * Reschedule if we are currently running on this runqueue and
2790                  * our priority decreased, or if we are not currently running on
2791                  * this runqueue and our priority is higher than the current's
2792                  */
2793                 if (task_running(rq, p)) {
2794                         if (p->prio > oldprio)
2795                                 resched_task(rq->curr);
2796                 } else if (TASK_PREEMPTS_CURR(p, rq))
2797                         resched_task(rq->curr);
2798         }
2799
2800 out_unlock:
2801         task_rq_unlock(rq, &flags);
2802 out_unlock_tasklist:
2803         read_unlock_irq(&tasklist_lock);
2804
2805 out_nounlock:
2806         return retval;
2807 }
2808
2809 /**
2810  * sys_sched_setscheduler - set/change the scheduler policy and RT priority
2811  * @pid: the pid in question.
2812  * @policy: new policy
2813  * @param: structure containing the new RT priority.
2814  */
2815 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
2816                                        struct sched_param __user *param)
2817 {
2818         return setscheduler(pid, policy, param);
2819 }
2820
2821 /**
2822  * sys_sched_setparam - set/change the RT priority of a thread
2823  * @pid: the pid in question.
2824  * @param: structure containing the new RT priority.
2825  */
2826 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
2827 {
2828         return setscheduler(pid, -1, param);
2829 }
2830
2831 /**
2832  * sys_sched_getscheduler - get the policy (scheduling class) of a thread
2833  * @pid: the pid in question.
2834  */
2835 asmlinkage long sys_sched_getscheduler(pid_t pid)
2836 {
2837         int retval = -EINVAL;
2838         task_t *p;
2839
2840         if (pid < 0)
2841                 goto out_nounlock;
2842
2843         retval = -ESRCH;
2844         read_lock(&tasklist_lock);
2845         p = find_process_by_pid(pid);
2846         if (p) {
2847                 retval = security_task_getscheduler(p);
2848                 if (!retval)
2849                         retval = p->policy;
2850         }
2851         read_unlock(&tasklist_lock);
2852
2853 out_nounlock:
2854         return retval;
2855 }
2856
2857 /**
2858  * sys_sched_getscheduler - get the RT priority of a thread
2859  * @pid: the pid in question.
2860  * @param: structure containing the RT priority.
2861  */
2862 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
2863 {
2864         struct sched_param lp;
2865         int retval = -EINVAL;
2866         task_t *p;
2867
2868         if (!param || pid < 0)
2869                 goto out_nounlock;
2870
2871         read_lock(&tasklist_lock);
2872         p = find_process_by_pid(pid);
2873         retval = -ESRCH;
2874         if (!p)
2875                 goto out_unlock;
2876
2877         retval = security_task_getscheduler(p);
2878         if (retval)
2879                 goto out_unlock;
2880
2881         lp.sched_priority = p->rt_priority;
2882         read_unlock(&tasklist_lock);
2883
2884         /*
2885          * This one might sleep, we cannot do it with a spinlock held ...
2886          */
2887         retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
2888
2889 out_nounlock:
2890         return retval;
2891
2892 out_unlock:
2893         read_unlock(&tasklist_lock);
2894         return retval;
2895 }
2896
2897 /**
2898  * sys_sched_setaffinity - set the cpu affinity of a process
2899  * @pid: pid of the process
2900  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
2901  * @user_mask_ptr: user-space pointer to the new cpu mask
2902  */
2903 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
2904                                       unsigned long __user *user_mask_ptr)
2905 {
2906         cpumask_t new_mask;
2907         int retval;
2908         task_t *p;
2909
2910         if (len < sizeof(new_mask))
2911                 return -EINVAL;
2912
2913         if (copy_from_user(&new_mask, user_mask_ptr, sizeof(new_mask)))
2914                 return -EFAULT;
2915
2916         lock_cpu_hotplug();
2917         read_lock(&tasklist_lock);
2918
2919         p = find_process_by_pid(pid);
2920         if (!p) {
2921                 read_unlock(&tasklist_lock);
2922                 unlock_cpu_hotplug();
2923                 return -ESRCH;
2924         }
2925
2926         /*
2927          * It is not safe to call set_cpus_allowed with the
2928          * tasklist_lock held.  We will bump the task_struct's
2929          * usage count and then drop tasklist_lock.
2930          */
2931         get_task_struct(p);
2932         read_unlock(&tasklist_lock);
2933
2934         retval = -EPERM;
2935         if ((current->euid != p->euid) && (current->euid != p->uid) &&
2936                         !capable(CAP_SYS_NICE))
2937                 goto out_unlock;
2938
2939         retval = set_cpus_allowed(p, new_mask);
2940
2941 out_unlock:
2942         put_task_struct(p);
2943         unlock_cpu_hotplug();
2944         return retval;
2945 }
2946
2947 /**
2948  * sys_sched_getaffinity - get the cpu affinity of a process
2949  * @pid: pid of the process
2950  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
2951  * @user_mask_ptr: user-space pointer to hold the current cpu mask
2952  */
2953 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
2954                                       unsigned long __user *user_mask_ptr)
2955 {
2956         unsigned int real_len;
2957         cpumask_t mask;
2958         int retval;
2959         task_t *p;
2960
2961         real_len = sizeof(mask);
2962         if (len < real_len)
2963                 return -EINVAL;
2964
2965         lock_cpu_hotplug();
2966         read_lock(&tasklist_lock);
2967
2968         retval = -ESRCH;
2969         p = find_process_by_pid(pid);
2970         if (!p)
2971                 goto out_unlock;
2972
2973         retval = 0;
2974         cpus_and(mask, p->cpus_allowed, cpu_possible_map);
2975
2976 out_unlock:
2977         read_unlock(&tasklist_lock);
2978         unlock_cpu_hotplug();
2979         if (retval)
2980                 return retval;
2981         if (copy_to_user(user_mask_ptr, &mask, real_len))
2982                 return -EFAULT;
2983         return real_len;
2984 }
2985
2986 /**
2987  * sys_sched_yield - yield the current processor to other threads.
2988  *
2989  * this function yields the current CPU by moving the calling thread
2990  * to the expired array. If there are no other threads running on this
2991  * CPU then this function will return.
2992  */
2993 asmlinkage long sys_sched_yield(void)
2994 {
2995         runqueue_t *rq = this_rq_lock();
2996         prio_array_t *array = current->array;
2997         prio_array_t *target = rq->expired;
2998
2999         /*
3000          * We implement yielding by moving the task into the expired
3001          * queue.
3002          *
3003          * (special rule: RT tasks will just roundrobin in the active
3004          *  array.)
3005          */
3006         if (unlikely(rt_task(current)))
3007                 target = rq->active;
3008
3009         dequeue_task(current, array);
3010         enqueue_task(current, target);
3011
3012         /*
3013          * Since we are going to call schedule() anyway, there's
3014          * no need to preempt or enable interrupts:
3015          */
3016         _raw_spin_unlock(&rq->lock);
3017         preempt_enable_no_resched();
3018
3019         schedule();
3020
3021         return 0;
3022 }
3023
3024 void __sched __cond_resched(void)
3025 {
3026         set_current_state(TASK_RUNNING);
3027         schedule();
3028 }
3029
3030 EXPORT_SYMBOL(__cond_resched);
3031
3032 /**
3033  * yield - yield the current processor to other threads.
3034  *
3035  * this is a shortcut for kernel-space yielding - it marks the
3036  * thread runnable and calls sys_sched_yield().
3037  */
3038 void __sched yield(void)
3039 {
3040         set_current_state(TASK_RUNNING);
3041         sys_sched_yield();
3042 }
3043
3044 EXPORT_SYMBOL(yield);
3045
3046 /*
3047  * This task is about to go to sleep on IO.  Increment rq->nr_iowait so
3048  * that process accounting knows that this is a task in IO wait state.
3049  *
3050  * But don't do that if it is a deliberate, throttling IO wait (this task
3051  * has set its backing_dev_info: the queue against which it should throttle)
3052  */
3053 void __sched io_schedule(void)
3054 {
3055         struct runqueue *rq = this_rq();
3056         def_delay_var(dstart);
3057
3058         start_delay_set(dstart,PF_IOWAIT);
3059         atomic_inc(&rq->nr_iowait);
3060         schedule();
3061         atomic_dec(&rq->nr_iowait);
3062         add_io_delay(dstart);
3063 }
3064
3065 EXPORT_SYMBOL(io_schedule);
3066
3067 long __sched io_schedule_timeout(long timeout)
3068 {
3069         struct runqueue *rq = this_rq();
3070         long ret;
3071         def_delay_var(dstart);
3072
3073         start_delay_set(dstart,PF_IOWAIT);
3074         atomic_inc(&rq->nr_iowait);
3075         ret = schedule_timeout(timeout);
3076         atomic_dec(&rq->nr_iowait);
3077         add_io_delay(dstart);
3078         return ret;
3079 }
3080
3081 /**
3082  * sys_sched_get_priority_max - return maximum RT priority.
3083  * @policy: scheduling class.
3084  *
3085  * this syscall returns the maximum rt_priority that can be used
3086  * by a given scheduling class.
3087  */
3088 asmlinkage long sys_sched_get_priority_max(int policy)
3089 {
3090         int ret = -EINVAL;
3091
3092         switch (policy) {
3093         case SCHED_FIFO:
3094         case SCHED_RR:
3095                 ret = MAX_USER_RT_PRIO-1;
3096                 break;
3097         case SCHED_NORMAL:
3098                 ret = 0;
3099                 break;
3100         }
3101         return ret;
3102 }
3103
3104 /**
3105  * sys_sched_get_priority_min - return minimum RT priority.
3106  * @policy: scheduling class.
3107  *
3108  * this syscall returns the minimum rt_priority that can be used
3109  * by a given scheduling class.
3110  */
3111 asmlinkage long sys_sched_get_priority_min(int policy)
3112 {
3113         int ret = -EINVAL;
3114
3115         switch (policy) {
3116         case SCHED_FIFO:
3117         case SCHED_RR:
3118                 ret = 1;
3119                 break;
3120         case SCHED_NORMAL:
3121                 ret = 0;
3122         }
3123         return ret;
3124 }
3125
3126 /**
3127  * sys_sched_rr_get_interval - return the default timeslice of a process.
3128  * @pid: pid of the process.
3129  * @interval: userspace pointer to the timeslice value.
3130  *
3131  * this syscall writes the default timeslice value of a given process
3132  * into the user-space timespec buffer. A value of '0' means infinity.
3133  */
3134 asmlinkage
3135 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
3136 {
3137         int retval = -EINVAL;
3138         struct timespec t;
3139         task_t *p;
3140
3141         if (pid < 0)
3142                 goto out_nounlock;
3143
3144         retval = -ESRCH;
3145         read_lock(&tasklist_lock);
3146         p = find_process_by_pid(pid);
3147         if (!p)
3148                 goto out_unlock;
3149
3150         retval = security_task_getscheduler(p);
3151         if (retval)
3152                 goto out_unlock;
3153
3154         jiffies_to_timespec(p->policy & SCHED_FIFO ?
3155                                 0 : task_timeslice(p), &t);
3156         read_unlock(&tasklist_lock);
3157         retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
3158 out_nounlock:
3159         return retval;
3160 out_unlock:
3161         read_unlock(&tasklist_lock);
3162         return retval;
3163 }
3164
3165 static inline struct task_struct *eldest_child(struct task_struct *p)
3166 {
3167         if (list_empty(&p->children)) return NULL;
3168         return list_entry(p->children.next,struct task_struct,sibling);
3169 }
3170
3171 static inline struct task_struct *older_sibling(struct task_struct *p)
3172 {
3173         if (p->sibling.prev==&p->parent->children) return NULL;
3174         return list_entry(p->sibling.prev,struct task_struct,sibling);
3175 }
3176
3177 static inline struct task_struct *younger_sibling(struct task_struct *p)
3178 {
3179         if (p->sibling.next==&p->parent->children) return NULL;
3180         return list_entry(p->sibling.next,struct task_struct,sibling);
3181 }
3182
3183 static void show_task(task_t * p)
3184 {
3185         task_t *relative;
3186         unsigned state;
3187         unsigned long free = 0;
3188         static const char *stat_nam[] = { "R", "S", "D", "T", "Z", "W" };
3189
3190         printk("%-13.13s ", p->comm);
3191         state = p->state ? __ffs(p->state) + 1 : 0;
3192         if (state < ARRAY_SIZE(stat_nam))
3193                 printk(stat_nam[state]);
3194         else
3195                 printk("?");
3196 #if (BITS_PER_LONG == 32)
3197         if (state == TASK_RUNNING)
3198                 printk(" running ");
3199         else
3200                 printk(" %08lX ", thread_saved_pc(p));
3201 #else
3202         if (state == TASK_RUNNING)
3203                 printk("  running task   ");
3204         else
3205                 printk(" %016lx ", thread_saved_pc(p));
3206 #endif
3207 #ifdef CONFIG_DEBUG_STACK_USAGE
3208         {
3209                 unsigned long * n = (unsigned long *) (p->thread_info+1);
3210                 while (!*n)
3211                         n++;
3212                 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
3213         }
3214 #endif
3215         printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
3216         if ((relative = eldest_child(p)))
3217                 printk("%5d ", relative->pid);
3218         else
3219                 printk("      ");
3220         if ((relative = younger_sibling(p)))
3221                 printk("%7d", relative->pid);
3222         else
3223                 printk("       ");
3224         if ((relative = older_sibling(p)))
3225                 printk(" %5d", relative->pid);
3226         else
3227                 printk("      ");
3228         if (!p->mm)
3229                 printk(" (L-TLB)\n");
3230         else
3231                 printk(" (NOTLB)\n");
3232
3233         if (state != TASK_RUNNING)
3234                 show_stack(p, NULL);
3235 }
3236
3237 void show_state(void)
3238 {
3239         task_t *g, *p;
3240
3241 #if (BITS_PER_LONG == 32)
3242         printk("\n"
3243                "                                               sibling\n");
3244         printk("  task             PC      pid father child younger older\n");
3245 #else
3246         printk("\n"
3247                "                                                       sibling\n");
3248         printk("  task                 PC          pid father child younger older\n");
3249 #endif
3250         read_lock(&tasklist_lock);
3251         do_each_thread(g, p) {
3252                 /*
3253                  * reset the NMI-timeout, listing all files on a slow
3254                  * console might take alot of time:
3255                  */
3256                 touch_nmi_watchdog();
3257                 show_task(p);
3258         } while_each_thread(g, p);
3259
3260         read_unlock(&tasklist_lock);
3261 }
3262
3263 void __devinit init_idle(task_t *idle, int cpu)
3264 {
3265         runqueue_t *idle_rq = cpu_rq(cpu), *rq = cpu_rq(task_cpu(idle));
3266         unsigned long flags;
3267
3268         local_irq_save(flags);
3269         double_rq_lock(idle_rq, rq);
3270
3271         idle_rq->curr = idle_rq->idle = idle;
3272         deactivate_task(idle, rq);
3273         idle->array = NULL;
3274         idle->prio = MAX_PRIO;
3275         idle->state = TASK_RUNNING;
3276         set_task_cpu(idle, cpu);
3277         double_rq_unlock(idle_rq, rq);
3278         set_tsk_need_resched(idle);
3279         local_irq_restore(flags);
3280
3281         /* Set the preempt count _outside_ the spinlocks! */
3282 #ifdef CONFIG_PREEMPT
3283         idle->thread_info->preempt_count = (idle->lock_depth >= 0);
3284 #else
3285         idle->thread_info->preempt_count = 0;
3286 #endif
3287 }
3288
3289 /*
3290  * In a system that switches off the HZ timer nohz_cpu_mask
3291  * indicates which cpus entered this state. This is used
3292  * in the rcu update to wait only for active cpus. For system
3293  * which do not switch off the HZ timer nohz_cpu_mask should
3294  * always be CPU_MASK_NONE.
3295  */
3296 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
3297
3298 #ifdef CONFIG_SMP
3299 /*
3300  * This is how migration works:
3301  *
3302  * 1) we queue a migration_req_t structure in the source CPU's
3303  *    runqueue and wake up that CPU's migration thread.
3304  * 2) we down() the locked semaphore => thread blocks.
3305  * 3) migration thread wakes up (implicitly it forces the migrated
3306  *    thread off the CPU)
3307  * 4) it gets the migration request and checks whether the migrated
3308  *    task is still in the wrong runqueue.
3309  * 5) if it's in the wrong runqueue then the migration thread removes
3310  *    it and puts it into the right queue.
3311  * 6) migration thread up()s the semaphore.
3312  * 7) we wake up and the migration is done.
3313  */
3314
3315 /*
3316  * Change a given task's CPU affinity. Migrate the thread to a
3317  * proper CPU and schedule it away if the CPU it's executing on
3318  * is removed from the allowed bitmask.
3319  *
3320  * NOTE: the caller must have a valid reference to the task, the
3321  * task must not exit() & deallocate itself prematurely.  The
3322  * call is not atomic; no spinlocks may be held.
3323  */
3324 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
3325 {
3326         unsigned long flags;
3327         int ret = 0;
3328         migration_req_t req;
3329         runqueue_t *rq;
3330
3331         rq = task_rq_lock(p, &flags);
3332         if (any_online_cpu(new_mask) == NR_CPUS) {
3333                 ret = -EINVAL;
3334                 goto out;
3335         }
3336
3337         p->cpus_allowed = new_mask;
3338         /* Can the task run on the task's current CPU? If so, we're done */
3339         if (cpu_isset(task_cpu(p), new_mask))
3340                 goto out;
3341
3342         if (migrate_task(p, any_online_cpu(new_mask), &req)) {
3343                 /* Need help from migration thread: drop lock and wait. */
3344                 task_rq_unlock(rq, &flags);
3345                 wake_up_process(rq->migration_thread);
3346                 wait_for_completion(&req.done);
3347                 return 0;
3348         }
3349 out:
3350         task_rq_unlock(rq, &flags);
3351         return ret;
3352 }
3353
3354 EXPORT_SYMBOL_GPL(set_cpus_allowed);
3355
3356 /*
3357  * Move (not current) task off this cpu, onto dest cpu.  We're doing
3358  * this because either it can't run here any more (set_cpus_allowed()
3359  * away from this CPU, or CPU going down), or because we're
3360  * attempting to rebalance this task on exec (sched_balance_exec).
3361  *
3362  * So we race with normal scheduler movements, but that's OK, as long
3363  * as the task is no longer on this CPU.
3364  */
3365 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
3366 {
3367         runqueue_t *rq_dest, *rq_src;
3368
3369         if (unlikely(cpu_is_offline(dest_cpu)))
3370                 return;
3371
3372         rq_src  = cpu_rq(src_cpu);
3373         rq_dest = cpu_rq(dest_cpu);
3374
3375         double_rq_lock(rq_src, rq_dest);
3376         /* Already moved. */
3377         if (task_cpu(p) != src_cpu)
3378                 goto out;
3379         /* Affinity changed (again). */
3380         if (!cpu_isset(dest_cpu, p->cpus_allowed))
3381                 goto out;
3382
3383         set_task_cpu(p, dest_cpu);
3384         if (p->array) {
3385                 /*
3386                  * Sync timestamp with rq_dest's before activating.
3387                  * The same thing could be achieved by doing this step
3388                  * afterwards, and pretending it was a local activate.
3389                  * This way is cleaner and logically correct.
3390                  */
3391                 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
3392                                 + rq_dest->timestamp_last_tick;
3393                 deactivate_task(p, rq_src);
3394                 activate_task(p, rq_dest, 0);
3395                 if (TASK_PREEMPTS_CURR(p, rq_dest))
3396                         resched_task(rq_dest->curr);
3397         }
3398
3399 out:
3400         double_rq_unlock(rq_src, rq_dest);
3401 }
3402
3403 /*
3404  * migration_thread - this is a highprio system thread that performs
3405  * thread migration by bumping thread off CPU then 'pushing' onto
3406  * another runqueue.
3407  */
3408 static int migration_thread(void * data)
3409 {
3410         runqueue_t *rq;
3411         int cpu = (long)data;
3412
3413         rq = cpu_rq(cpu);
3414         BUG_ON(rq->migration_thread != current);
3415
3416         set_current_state(TASK_INTERRUPTIBLE);
3417         while (!kthread_should_stop()) {
3418                 struct list_head *head;
3419                 migration_req_t *req;
3420
3421                 if (current->flags & PF_FREEZE)
3422                         refrigerator(PF_FREEZE);
3423
3424                 spin_lock_irq(&rq->lock);
3425
3426                 if (cpu_is_offline(cpu)) {
3427                         spin_unlock_irq(&rq->lock);
3428                         goto wait_to_die;
3429                 }
3430
3431                 if (rq->active_balance) {
3432                         active_load_balance(rq, cpu);
3433                         rq->active_balance = 0;
3434                 }
3435
3436                 head = &rq->migration_queue;
3437
3438                 if (list_empty(head)) {
3439                         spin_unlock_irq(&rq->lock);
3440                         schedule();
3441                         set_current_state(TASK_INTERRUPTIBLE);
3442                         continue;
3443                 }
3444                 req = list_entry(head->next, migration_req_t, list);
3445                 list_del_init(head->next);
3446
3447                 if (req->type == REQ_MOVE_TASK) {
3448                         spin_unlock(&rq->lock);
3449                         __migrate_task(req->task, smp_processor_id(),
3450                                         req->dest_cpu);
3451                         local_irq_enable();
3452                 } else if (req->type == REQ_SET_DOMAIN) {
3453                         rq->sd = req->sd;
3454                         spin_unlock_irq(&rq->lock);
3455                 } else {
3456                         spin_unlock_irq(&rq->lock);
3457                         WARN_ON(1);
3458                 }
3459
3460                 complete(&req->done);
3461         }
3462         __set_current_state(TASK_RUNNING);
3463         return 0;
3464
3465 wait_to_die:
3466         /* Wait for kthread_stop */
3467         set_current_state(TASK_INTERRUPTIBLE);
3468         while (!kthread_should_stop()) {
3469                 schedule();
3470                 set_current_state(TASK_INTERRUPTIBLE);
3471         }
3472         __set_current_state(TASK_RUNNING);
3473         return 0;
3474 }
3475
3476 #ifdef CONFIG_HOTPLUG_CPU
3477 /* migrate_all_tasks - function to migrate all tasks from the dead cpu.  */
3478 static void migrate_all_tasks(int src_cpu)
3479 {
3480         struct task_struct *tsk, *t;
3481         int dest_cpu;
3482         unsigned int node;
3483
3484         write_lock_irq(&tasklist_lock);
3485
3486         /* watch out for per node tasks, let's stay on this node */
3487         node = cpu_to_node(src_cpu);
3488
3489         do_each_thread(t, tsk) {
3490                 cpumask_t mask;
3491                 if (tsk == current)
3492                         continue;
3493
3494                 if (task_cpu(tsk) != src_cpu)
3495                         continue;
3496
3497                 /* Figure out where this task should go (attempting to
3498                  * keep it on-node), and check if it can be migrated
3499                  * as-is.  NOTE that kernel threads bound to more than
3500                  * one online cpu will be migrated. */
3501                 mask = node_to_cpumask(node);
3502                 cpus_and(mask, mask, tsk->cpus_allowed);
3503                 dest_cpu = any_online_cpu(mask);
3504                 if (dest_cpu == NR_CPUS)
3505                         dest_cpu = any_online_cpu(tsk->cpus_allowed);
3506                 if (dest_cpu == NR_CPUS) {
3507                         cpus_clear(tsk->cpus_allowed);
3508                         cpus_complement(tsk->cpus_allowed);
3509                         dest_cpu = any_online_cpu(tsk->cpus_allowed);
3510
3511                         /* Don't tell them about moving exiting tasks
3512                            or kernel threads (both mm NULL), since
3513                            they never leave kernel. */
3514                         if (tsk->mm && printk_ratelimit())
3515                                 printk(KERN_INFO "process %d (%s) no "
3516                                        "longer affine to cpu%d\n",
3517                                        tsk->pid, tsk->comm, src_cpu);
3518                 }
3519
3520                 __migrate_task(tsk, src_cpu, dest_cpu);
3521         } while_each_thread(t, tsk);
3522
3523         write_unlock_irq(&tasklist_lock);
3524 }
3525
3526 /* Schedules idle task to be the next runnable task on current CPU.
3527  * It does so by boosting its priority to highest possible and adding it to
3528  * the _front_ of runqueue. Used by CPU offline code.
3529  */
3530 void sched_idle_next(void)
3531 {
3532         int cpu = smp_processor_id();
3533         runqueue_t *rq = this_rq();
3534         struct task_struct *p = rq->idle;
3535         unsigned long flags;
3536
3537         /* cpu has to be offline */
3538         BUG_ON(cpu_online(cpu));
3539
3540         /* Strictly not necessary since rest of the CPUs are stopped by now
3541          * and interrupts disabled on current cpu.
3542          */
3543         spin_lock_irqsave(&rq->lock, flags);
3544
3545         __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
3546         /* Add idle task to _front_ of it's priority queue */
3547         __activate_idle_task(p, rq);
3548
3549         spin_unlock_irqrestore(&rq->lock, flags);
3550 }
3551 #endif /* CONFIG_HOTPLUG_CPU */
3552
3553 /*
3554  * migration_call - callback that gets triggered when a CPU is added.
3555  * Here we can start up the necessary migration thread for the new CPU.
3556  */
3557 static int migration_call(struct notifier_block *nfb, unsigned long action,
3558                           void *hcpu)
3559 {
3560         int cpu = (long)hcpu;
3561         struct task_struct *p;
3562         struct runqueue *rq;
3563         unsigned long flags;
3564
3565         switch (action) {
3566         case CPU_UP_PREPARE:
3567                 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
3568                 if (IS_ERR(p))
3569                         return NOTIFY_BAD;
3570                 kthread_bind(p, cpu);
3571                 /* Must be high prio: stop_machine expects to yield to it. */
3572                 rq = task_rq_lock(p, &flags);
3573                 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
3574                 task_rq_unlock(rq, &flags);
3575                 cpu_rq(cpu)->migration_thread = p;
3576                 break;
3577         case CPU_ONLINE:
3578                 /* Strictly unneccessary, as first user will wake it. */
3579                 wake_up_process(cpu_rq(cpu)->migration_thread);
3580                 break;
3581 #ifdef CONFIG_HOTPLUG_CPU
3582         case CPU_UP_CANCELED:
3583                 /* Unbind it from offline cpu so it can run.  Fall thru. */
3584                 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
3585                 kthread_stop(cpu_rq(cpu)->migration_thread);
3586                 cpu_rq(cpu)->migration_thread = NULL;
3587                 break;
3588         case CPU_DEAD:
3589                 migrate_all_tasks(cpu);
3590                 rq = cpu_rq(cpu);
3591                 kthread_stop(rq->migration_thread);
3592                 rq->migration_thread = NULL;
3593                 /* Idle task back to normal (off runqueue, low prio) */
3594                 rq = task_rq_lock(rq->idle, &flags);
3595                 deactivate_task(rq->idle, rq);
3596                 rq->idle->static_prio = MAX_PRIO;
3597                 __setscheduler(rq->idle, SCHED_NORMAL, 0);
3598                 task_rq_unlock(rq, &flags);
3599                 BUG_ON(rq->nr_running != 0);
3600
3601                 /* No need to migrate the tasks: it was best-effort if
3602                  * they didn't do lock_cpu_hotplug().  Just wake up
3603                  * the requestors. */
3604                 spin_lock_irq(&rq->lock);
3605                 while (!list_empty(&rq->migration_queue)) {
3606                         migration_req_t *req;
3607                         req = list_entry(rq->migration_queue.next,
3608                                          migration_req_t, list);
3609                         BUG_ON(req->type != REQ_MOVE_TASK);
3610                         list_del_init(&req->list);
3611                         complete(&req->done);
3612                 }
3613                 spin_unlock_irq(&rq->lock);
3614                 break;
3615 #endif
3616         }
3617         return NOTIFY_OK;
3618 }
3619
3620 /* Register at highest priority so that task migration (migrate_all_tasks)
3621  * happens before everything else.
3622  */
3623 static struct notifier_block __devinitdata migration_notifier = {
3624         .notifier_call = migration_call,
3625         .priority = 10
3626 };
3627
3628 int __init migration_init(void)
3629 {
3630         void *cpu = (void *)(long)smp_processor_id();
3631         /* Start one for boot CPU. */
3632         migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
3633         migration_call(&migration_notifier, CPU_ONLINE, cpu);
3634         register_cpu_notifier(&migration_notifier);
3635         return 0;
3636 }
3637 #endif
3638
3639 /*
3640  * The 'big kernel lock'
3641  *
3642  * This spinlock is taken and released recursively by lock_kernel()
3643  * and unlock_kernel().  It is transparently dropped and reaquired
3644  * over schedule().  It is used to protect legacy code that hasn't
3645  * been migrated to a proper locking design yet.
3646  *
3647  * Don't use in new code.
3648  *
3649  * Note: spinlock debugging needs this even on !CONFIG_SMP.
3650  */
3651 spinlock_t kernel_flag __cacheline_aligned_in_smp = SPIN_LOCK_UNLOCKED;
3652 EXPORT_SYMBOL(kernel_flag);
3653
3654 #ifdef CONFIG_SMP
3655 /* Attach the domain 'sd' to 'cpu' as its base domain */
3656 void cpu_attach_domain(struct sched_domain *sd, int cpu)
3657 {
3658         migration_req_t req;
3659         unsigned long flags;
3660         runqueue_t *rq = cpu_rq(cpu);
3661         int local = 1;
3662
3663         lock_cpu_hotplug();
3664
3665         spin_lock_irqsave(&rq->lock, flags);
3666
3667         if (cpu == smp_processor_id() || !cpu_online(cpu)) {
3668                 rq->sd = sd;
3669         } else {
3670                 init_completion(&req.done);
3671                 req.type = REQ_SET_DOMAIN;
3672                 req.sd = sd;
3673                 list_add(&req.list, &rq->migration_queue);
3674                 local = 0;
3675         }
3676
3677         spin_unlock_irqrestore(&rq->lock, flags);
3678
3679         if (!local) {
3680                 wake_up_process(rq->migration_thread);
3681                 wait_for_completion(&req.done);
3682         }
3683
3684         unlock_cpu_hotplug();
3685 }
3686
3687 #ifdef ARCH_HAS_SCHED_DOMAIN
3688 extern void __init arch_init_sched_domains(void);
3689 #else
3690 static struct sched_group sched_group_cpus[NR_CPUS];
3691 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
3692 #ifdef CONFIG_NUMA
3693 static struct sched_group sched_group_nodes[MAX_NUMNODES];
3694 static DEFINE_PER_CPU(struct sched_domain, node_domains);
3695 static void __init arch_init_sched_domains(void)
3696 {
3697         int i;
3698         struct sched_group *first_node = NULL, *last_node = NULL;
3699
3700         /* Set up domains */
3701         for_each_cpu(i) {
3702                 int node = cpu_to_node(i);
3703                 cpumask_t nodemask = node_to_cpumask(node);
3704                 struct sched_domain *node_sd = &per_cpu(node_domains, i);
3705                 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3706
3707                 *node_sd = SD_NODE_INIT;
3708                 node_sd->span = cpu_possible_map;
3709                 node_sd->groups = &sched_group_nodes[cpu_to_node(i)];
3710
3711                 *cpu_sd = SD_CPU_INIT;
3712                 cpus_and(cpu_sd->span, nodemask, cpu_possible_map);
3713                 cpu_sd->groups = &sched_group_cpus[i];
3714                 cpu_sd->parent = node_sd;
3715         }
3716
3717         /* Set up groups */
3718         for (i = 0; i < MAX_NUMNODES; i++) {
3719                 cpumask_t tmp = node_to_cpumask(i);
3720                 cpumask_t nodemask;
3721                 struct sched_group *first_cpu = NULL, *last_cpu = NULL;
3722                 struct sched_group *node = &sched_group_nodes[i];
3723                 int j;
3724
3725                 cpus_and(nodemask, tmp, cpu_possible_map);
3726
3727                 if (cpus_empty(nodemask))
3728                         continue;
3729
3730                 node->cpumask = nodemask;
3731                 node->cpu_power = SCHED_LOAD_SCALE * cpus_weight(node->cpumask);
3732
3733                 for_each_cpu_mask(j, node->cpumask) {
3734                         struct sched_group *cpu = &sched_group_cpus[j];
3735
3736                         cpus_clear(cpu->cpumask);
3737                         cpu_set(j, cpu->cpumask);
3738                         cpu->cpu_power = SCHED_LOAD_SCALE;
3739
3740                         if (!first_cpu)
3741                                 first_cpu = cpu;
3742                         if (last_cpu)
3743                                 last_cpu->next = cpu;
3744                         last_cpu = cpu;
3745                 }
3746                 last_cpu->next = first_cpu;
3747
3748                 if (!first_node)
3749                         first_node = node;
3750                 if (last_node)
3751                         last_node->next = node;
3752                 last_node = node;
3753         }
3754         last_node->next = first_node;
3755
3756         mb();
3757         for_each_cpu(i) {
3758                 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3759                 cpu_attach_domain(cpu_sd, i);
3760         }
3761 }
3762
3763 #else /* !CONFIG_NUMA */
3764 static void __init arch_init_sched_domains(void)
3765 {
3766         int i;
3767         struct sched_group *first_cpu = NULL, *last_cpu = NULL;
3768
3769         /* Set up domains */
3770         for_each_cpu(i) {
3771                 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3772
3773                 *cpu_sd = SD_CPU_INIT;
3774                 cpu_sd->span = cpu_possible_map;
3775                 cpu_sd->groups = &sched_group_cpus[i];
3776         }
3777
3778         /* Set up CPU groups */
3779         for_each_cpu_mask(i, cpu_possible_map) {
3780                 struct sched_group *cpu = &sched_group_cpus[i];
3781
3782                 cpus_clear(cpu->cpumask);
3783                 cpu_set(i, cpu->cpumask);
3784                 cpu->cpu_power = SCHED_LOAD_SCALE;
3785
3786                 if (!first_cpu)
3787                         first_cpu = cpu;
3788                 if (last_cpu)
3789                         last_cpu->next = cpu;
3790                 last_cpu = cpu;
3791         }
3792         last_cpu->next = first_cpu;
3793
3794         mb(); /* domains were modified outside the lock */
3795         for_each_cpu(i) {
3796                 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
3797                 cpu_attach_domain(cpu_sd, i);
3798         }
3799 }
3800
3801 #endif /* CONFIG_NUMA */
3802 #endif /* ARCH_HAS_SCHED_DOMAIN */
3803
3804 #define SCHED_DOMAIN_DEBUG
3805 #ifdef SCHED_DOMAIN_DEBUG
3806 void sched_domain_debug(void)
3807 {
3808         int i;
3809
3810         for_each_cpu(i) {
3811                 runqueue_t *rq = cpu_rq(i);
3812                 struct sched_domain *sd;
3813                 int level = 0;
3814
3815                 sd = rq->sd;
3816
3817                 printk(KERN_DEBUG "CPU%d: %s\n",
3818                                 i, (cpu_online(i) ? " online" : "offline"));
3819
3820                 do {
3821                         int j;
3822                         char str[NR_CPUS];
3823                         struct sched_group *group = sd->groups;
3824                         cpumask_t groupmask, tmp;
3825
3826                         cpumask_scnprintf(str, NR_CPUS, sd->span);
3827                         cpus_clear(groupmask);
3828
3829                         printk(KERN_DEBUG);
3830                         for (j = 0; j < level + 1; j++)
3831                                 printk(" ");
3832                         printk("domain %d: span %s\n", level, str);
3833
3834                         if (!cpu_isset(i, sd->span))
3835                                 printk(KERN_DEBUG "ERROR domain->span does not contain CPU%d\n", i);
3836                         if (!cpu_isset(i, group->cpumask))
3837                                 printk(KERN_DEBUG "ERROR domain->groups does not contain CPU%d\n", i);
3838                         if (!group->cpu_power)
3839                                 printk(KERN_DEBUG "ERROR domain->cpu_power not set\n");
3840
3841                         printk(KERN_DEBUG);
3842                         for (j = 0; j < level + 2; j++)
3843                                 printk(" ");
3844                         printk("groups:");
3845                         do {
3846                                 if (!group) {
3847                                         printk(" ERROR: NULL");
3848                                         break;
3849                                 }
3850
3851                                 if (!cpus_weight(group->cpumask))
3852                                         printk(" ERROR empty group:");
3853
3854                                 cpus_and(tmp, groupmask, group->cpumask);
3855                                 if (cpus_weight(tmp) > 0)
3856                                         printk(" ERROR repeated CPUs:");
3857
3858                                 cpus_or(groupmask, groupmask, group->cpumask);
3859
3860                                 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
3861                                 printk(" %s", str);
3862
3863                                 group = group->next;
3864                         } while (group != sd->groups);
3865                         printk("\n");
3866
3867                         if (!cpus_equal(sd->span, groupmask))
3868                                 printk(KERN_DEBUG "ERROR groups don't span domain->span\n");
3869
3870                         level++;
3871                         sd = sd->parent;
3872
3873                         if (sd) {
3874                                 cpus_and(tmp, groupmask, sd->span);
3875                                 if (!cpus_equal(tmp, groupmask))
3876                                         printk(KERN_DEBUG "ERROR parent span is not a superset of domain->span\n");
3877                         }
3878
3879                 } while (sd);
3880         }
3881 }
3882 #else
3883 #define sched_domain_debug() {}
3884 #endif
3885
3886 void __init sched_init_smp(void)
3887 {
3888         arch_init_sched_domains();
3889         sched_domain_debug();
3890 }
3891 #else
3892 void __init sched_init_smp(void)
3893 {
3894 }
3895 #endif /* CONFIG_SMP */
3896
3897 int in_sched_functions(unsigned long addr)
3898 {
3899         /* Linker adds these: start and end of __sched functions */
3900         extern char __sched_text_start[], __sched_text_end[];
3901         return addr >= (unsigned long)__sched_text_start
3902                 && addr < (unsigned long)__sched_text_end;
3903 }
3904
3905 void __init sched_init(void)
3906 {
3907         runqueue_t *rq;
3908         int i, j, k;
3909
3910 #ifdef CONFIG_SMP
3911         /* Set up an initial dummy domain for early boot */
3912         static struct sched_domain sched_domain_init;
3913         static struct sched_group sched_group_init;
3914         cpumask_t cpu_mask_all = CPU_MASK_ALL;
3915
3916         memset(&sched_domain_init, 0, sizeof(struct sched_domain));
3917         sched_domain_init.span = cpu_mask_all;
3918         sched_domain_init.groups = &sched_group_init;
3919         sched_domain_init.last_balance = jiffies;
3920         sched_domain_init.balance_interval = INT_MAX; /* Don't balance */
3921
3922         memset(&sched_group_init, 0, sizeof(struct sched_group));
3923         sched_group_init.cpumask = cpu_mask_all;
3924         sched_group_init.next = &sched_group_init;
3925         sched_group_init.cpu_power = SCHED_LOAD_SCALE;
3926 #endif
3927
3928         for (i = 0; i < NR_CPUS; i++) {
3929                 prio_array_t *array;
3930
3931                 rq = cpu_rq(i);
3932                 spin_lock_init(&rq->lock);
3933                 rq->active = rq->arrays;
3934                 rq->expired = rq->arrays + 1;
3935                 rq->best_expired_prio = MAX_PRIO;
3936
3937 #ifdef CONFIG_SMP
3938                 rq->sd = &sched_domain_init;
3939                 rq->cpu_load = 0;
3940                 rq->active_balance = 0;
3941                 rq->push_cpu = 0;
3942                 rq->migration_thread = NULL;
3943                 INIT_LIST_HEAD(&rq->migration_queue);
3944 #endif
3945                 atomic_set(&rq->nr_iowait, 0);
3946
3947                 for (j = 0; j < 2; j++) {
3948                         array = rq->arrays + j;
3949                         for (k = 0; k < MAX_PRIO; k++) {
3950                                 INIT_LIST_HEAD(array->queue + k);
3951                                 __clear_bit(k, array->bitmap);
3952                         }
3953                         // delimiter for bitsearch
3954                         __set_bit(MAX_PRIO, array->bitmap);
3955                 }
3956         }
3957         /*
3958          * We have to do a little magic to get the first
3959          * thread right in SMP mode.
3960          */
3961         rq = this_rq();
3962         rq->curr = current;
3963         rq->idle = current;
3964         set_task_cpu(current, smp_processor_id());
3965         wake_up_forked_process(current);
3966
3967         /*
3968          * The boot idle thread does lazy MMU switching as well:
3969          */
3970         atomic_inc(&init_mm.mm_count);
3971         enter_lazy_tlb(&init_mm, current);
3972 }
3973
3974 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
3975 void __might_sleep(char *file, int line)
3976 {
3977 #if defined(in_atomic)
3978         static unsigned long prev_jiffy;        /* ratelimiting */
3979
3980         if ((in_atomic() || irqs_disabled()) &&
3981             system_state == SYSTEM_RUNNING) {
3982                 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
3983                         return;
3984                 prev_jiffy = jiffies;
3985                 printk(KERN_ERR "Debug: sleeping function called from invalid"
3986                                 " context at %s:%d\n", file, line);
3987                 printk("in_atomic():%d, irqs_disabled():%d\n",
3988                         in_atomic(), irqs_disabled());
3989                 dump_stack();
3990         }
3991 #endif
3992 }
3993 EXPORT_SYMBOL(__might_sleep);
3994 #endif
3995
3996
3997 #if defined(CONFIG_SMP) && defined(CONFIG_PREEMPT)
3998 /*
3999  * This could be a long-held lock.  If another CPU holds it for a long time,
4000  * and that CPU is not asked to reschedule then *this* CPU will spin on the
4001  * lock for a long time, even if *this* CPU is asked to reschedule.
4002  *
4003  * So what we do here, in the slow (contended) path is to spin on the lock by
4004  * hand while permitting preemption.
4005  *
4006  * Called inside preempt_disable().
4007  */
4008 void __sched __preempt_spin_lock(spinlock_t *lock)
4009 {
4010         if (preempt_count() > 1) {
4011                 _raw_spin_lock(lock);
4012                 return;
4013         }
4014         do {
4015                 preempt_enable();
4016                 while (spin_is_locked(lock))
4017                         cpu_relax();
4018                 preempt_disable();
4019         } while (!_raw_spin_trylock(lock));
4020 }
4021
4022 EXPORT_SYMBOL(__preempt_spin_lock);
4023
4024 void __sched __preempt_write_lock(rwlock_t *lock)
4025 {
4026         if (preempt_count() > 1) {
4027                 _raw_write_lock(lock);
4028                 return;
4029         }
4030
4031         do {
4032                 preempt_enable();
4033                 while (rwlock_is_locked(lock))
4034                         cpu_relax();
4035                 preempt_disable();
4036         } while (!_raw_write_trylock(lock));
4037 }
4038
4039 EXPORT_SYMBOL(__preempt_write_lock);
4040 #endif /* defined(CONFIG_SMP) && defined(CONFIG_PREEMPT) */
4041
4042 #ifdef CONFIG_DELAY_ACCT
4043 int task_running_sys(struct task_struct *p)
4044 {
4045        return task_running(task_rq(p),p);
4046 }
4047 EXPORT_SYMBOL(task_running_sys);
4048 #endif
4049