]> www.pilppa.org Git - linux-2.6-omap-h63xx.git/blob - kernel/sched.c
9d42cbfc4f8ba2e3899cde4f1740db52dd555bab
[linux-2.6-omap-h63xx.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/capability.h>
31 #include <linux/completion.h>
32 #include <linux/kernel_stat.h>
33 #include <linux/debug_locks.h>
34 #include <linux/security.h>
35 #include <linux/notifier.h>
36 #include <linux/profile.h>
37 #include <linux/suspend.h>
38 #include <linux/vmalloc.h>
39 #include <linux/blkdev.h>
40 #include <linux/delay.h>
41 #include <linux/smp.h>
42 #include <linux/threads.h>
43 #include <linux/timer.h>
44 #include <linux/rcupdate.h>
45 #include <linux/cpu.h>
46 #include <linux/cpuset.h>
47 #include <linux/percpu.h>
48 #include <linux/kthread.h>
49 #include <linux/seq_file.h>
50 #include <linux/syscalls.h>
51 #include <linux/times.h>
52 #include <linux/acct.h>
53 #include <linux/kprobes.h>
54 #include <linux/delayacct.h>
55 #include <asm/tlb.h>
56
57 #include <asm/unistd.h>
58
59 /*
60  * Convert user-nice values [ -20 ... 0 ... 19 ]
61  * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
62  * and back.
63  */
64 #define NICE_TO_PRIO(nice)      (MAX_RT_PRIO + (nice) + 20)
65 #define PRIO_TO_NICE(prio)      ((prio) - MAX_RT_PRIO - 20)
66 #define TASK_NICE(p)            PRIO_TO_NICE((p)->static_prio)
67
68 /*
69  * 'User priority' is the nice value converted to something we
70  * can work with better when scaling various scheduler parameters,
71  * it's a [ 0 ... 39 ] range.
72  */
73 #define USER_PRIO(p)            ((p)-MAX_RT_PRIO)
74 #define TASK_USER_PRIO(p)       USER_PRIO((p)->static_prio)
75 #define MAX_USER_PRIO           (USER_PRIO(MAX_PRIO))
76
77 /*
78  * Some helpers for converting nanosecond timing to jiffy resolution
79  */
80 #define NS_TO_JIFFIES(TIME)     ((TIME) / (1000000000 / HZ))
81 #define JIFFIES_TO_NS(TIME)     ((TIME) * (1000000000 / HZ))
82
83 /*
84  * These are the 'tuning knobs' of the scheduler:
85  *
86  * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
87  * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
88  * Timeslices get refilled after they expire.
89  */
90 #define MIN_TIMESLICE           max(5 * HZ / 1000, 1)
91 #define DEF_TIMESLICE           (100 * HZ / 1000)
92 #define ON_RUNQUEUE_WEIGHT       30
93 #define CHILD_PENALTY            95
94 #define PARENT_PENALTY          100
95 #define EXIT_WEIGHT               3
96 #define PRIO_BONUS_RATIO         25
97 #define MAX_BONUS               (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
98 #define INTERACTIVE_DELTA         2
99 #define MAX_SLEEP_AVG           (DEF_TIMESLICE * MAX_BONUS)
100 #define STARVATION_LIMIT        (MAX_SLEEP_AVG)
101 #define NS_MAX_SLEEP_AVG        (JIFFIES_TO_NS(MAX_SLEEP_AVG))
102
103 /*
104  * If a task is 'interactive' then we reinsert it in the active
105  * array after it has expired its current timeslice. (it will not
106  * continue to run immediately, it will still roundrobin with
107  * other interactive tasks.)
108  *
109  * This part scales the interactivity limit depending on niceness.
110  *
111  * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
112  * Here are a few examples of different nice levels:
113  *
114  *  TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
115  *  TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
116  *  TASK_INTERACTIVE(  0): [1,1,1,1,0,0,0,0,0,0,0]
117  *  TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
118  *  TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
119  *
120  * (the X axis represents the possible -5 ... 0 ... +5 dynamic
121  *  priority range a task can explore, a value of '1' means the
122  *  task is rated interactive.)
123  *
124  * Ie. nice +19 tasks can never get 'interactive' enough to be
125  * reinserted into the active array. And only heavily CPU-hog nice -20
126  * tasks will be expired. Default nice 0 tasks are somewhere between,
127  * it takes some effort for them to get interactive, but it's not
128  * too hard.
129  */
130
131 #define CURRENT_BONUS(p) \
132         (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
133                 MAX_SLEEP_AVG)
134
135 #define GRANULARITY     (10 * HZ / 1000 ? : 1)
136
137 #ifdef CONFIG_SMP
138 #define TIMESLICE_GRANULARITY(p)        (GRANULARITY * \
139                 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
140                         num_online_cpus())
141 #else
142 #define TIMESLICE_GRANULARITY(p)        (GRANULARITY * \
143                 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
144 #endif
145
146 #define SCALE(v1,v1_max,v2_max) \
147         (v1) * (v2_max) / (v1_max)
148
149 #define DELTA(p) \
150         (SCALE(TASK_NICE(p) + 20, 40, MAX_BONUS) - 20 * MAX_BONUS / 40 + \
151                 INTERACTIVE_DELTA)
152
153 #define TASK_INTERACTIVE(p) \
154         ((p)->prio <= (p)->static_prio - DELTA(p))
155
156 #define INTERACTIVE_SLEEP(p) \
157         (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
158                 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
159
160 #define TASK_PREEMPTS_CURR(p, rq) \
161         ((p)->prio < (rq)->curr->prio)
162
163 /*
164  * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
165  * to time slice values: [800ms ... 100ms ... 5ms]
166  *
167  * The higher a thread's priority, the bigger timeslices
168  * it gets during one round of execution. But even the lowest
169  * priority thread gets MIN_TIMESLICE worth of execution time.
170  */
171
172 #define SCALE_PRIO(x, prio) \
173         max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO / 2), MIN_TIMESLICE)
174
175 static unsigned int static_prio_timeslice(int static_prio)
176 {
177         if (static_prio < NICE_TO_PRIO(0))
178                 return SCALE_PRIO(DEF_TIMESLICE * 4, static_prio);
179         else
180                 return SCALE_PRIO(DEF_TIMESLICE, static_prio);
181 }
182
183 static inline unsigned int task_timeslice(struct task_struct *p)
184 {
185         return static_prio_timeslice(p->static_prio);
186 }
187
188 /*
189  * These are the runqueue data structures:
190  */
191
192 struct prio_array {
193         unsigned int nr_active;
194         DECLARE_BITMAP(bitmap, MAX_PRIO+1); /* include 1 bit for delimiter */
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 rq {
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         unsigned long raw_weighted_load;
214 #ifdef CONFIG_SMP
215         unsigned long cpu_load[3];
216 #endif
217         unsigned long long nr_switches;
218
219         /*
220          * This is part of a global counter where only the total sum
221          * over all CPUs matters. A task can increase this counter on
222          * one CPU and if it got migrated afterwards it may decrease
223          * it on another CPU. Always updated under the runqueue lock:
224          */
225         unsigned long nr_uninterruptible;
226
227         unsigned long expired_timestamp;
228         unsigned long long timestamp_last_tick;
229         struct task_struct *curr, *idle;
230         struct mm_struct *prev_mm;
231         struct prio_array *active, *expired, arrays[2];
232         int best_expired_prio;
233         atomic_t nr_iowait;
234
235 #ifdef CONFIG_SMP
236         struct sched_domain *sd;
237
238         /* For active balancing */
239         int active_balance;
240         int push_cpu;
241
242         struct task_struct *migration_thread;
243         struct list_head migration_queue;
244 #endif
245
246 #ifdef CONFIG_SCHEDSTATS
247         /* latency stats */
248         struct sched_info rq_sched_info;
249
250         /* sys_sched_yield() stats */
251         unsigned long yld_exp_empty;
252         unsigned long yld_act_empty;
253         unsigned long yld_both_empty;
254         unsigned long yld_cnt;
255
256         /* schedule() stats */
257         unsigned long sched_switch;
258         unsigned long sched_cnt;
259         unsigned long sched_goidle;
260
261         /* try_to_wake_up() stats */
262         unsigned long ttwu_cnt;
263         unsigned long ttwu_local;
264 #endif
265         struct lock_class_key rq_lock_key;
266 };
267
268 static DEFINE_PER_CPU(struct rq, runqueues);
269
270 /*
271  * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
272  * See detach_destroy_domains: synchronize_sched for details.
273  *
274  * The domain tree of any CPU may only be accessed from within
275  * preempt-disabled sections.
276  */
277 #define for_each_domain(cpu, __sd) \
278         for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
279
280 #define cpu_rq(cpu)             (&per_cpu(runqueues, (cpu)))
281 #define this_rq()               (&__get_cpu_var(runqueues))
282 #define task_rq(p)              cpu_rq(task_cpu(p))
283 #define cpu_curr(cpu)           (cpu_rq(cpu)->curr)
284
285 #ifndef prepare_arch_switch
286 # define prepare_arch_switch(next)      do { } while (0)
287 #endif
288 #ifndef finish_arch_switch
289 # define finish_arch_switch(prev)       do { } while (0)
290 #endif
291
292 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
293 static inline int task_running(struct rq *rq, struct task_struct *p)
294 {
295         return rq->curr == p;
296 }
297
298 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
299 {
300 }
301
302 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
303 {
304 #ifdef CONFIG_DEBUG_SPINLOCK
305         /* this is a valid case when another task releases the spinlock */
306         rq->lock.owner = current;
307 #endif
308         /*
309          * If we are tracking spinlock dependencies then we have to
310          * fix up the runqueue lock - which gets 'carried over' from
311          * prev into current:
312          */
313         spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
314
315         spin_unlock_irq(&rq->lock);
316 }
317
318 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
319 static inline int task_running(struct rq *rq, struct task_struct *p)
320 {
321 #ifdef CONFIG_SMP
322         return p->oncpu;
323 #else
324         return rq->curr == p;
325 #endif
326 }
327
328 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
329 {
330 #ifdef CONFIG_SMP
331         /*
332          * We can optimise this out completely for !SMP, because the
333          * SMP rebalancing from interrupt is the only thing that cares
334          * here.
335          */
336         next->oncpu = 1;
337 #endif
338 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
339         spin_unlock_irq(&rq->lock);
340 #else
341         spin_unlock(&rq->lock);
342 #endif
343 }
344
345 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
346 {
347 #ifdef CONFIG_SMP
348         /*
349          * After ->oncpu is cleared, the task can be moved to a different CPU.
350          * We must ensure this doesn't happen until the switch is completely
351          * finished.
352          */
353         smp_wmb();
354         prev->oncpu = 0;
355 #endif
356 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
357         local_irq_enable();
358 #endif
359 }
360 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
361
362 /*
363  * __task_rq_lock - lock the runqueue a given task resides on.
364  * Must be called interrupts disabled.
365  */
366 static inline struct rq *__task_rq_lock(struct task_struct *p)
367         __acquires(rq->lock)
368 {
369         struct rq *rq;
370
371 repeat_lock_task:
372         rq = task_rq(p);
373         spin_lock(&rq->lock);
374         if (unlikely(rq != task_rq(p))) {
375                 spin_unlock(&rq->lock);
376                 goto repeat_lock_task;
377         }
378         return rq;
379 }
380
381 /*
382  * task_rq_lock - lock the runqueue a given task resides on and disable
383  * interrupts.  Note the ordering: we can safely lookup the task_rq without
384  * explicitly disabling preemption.
385  */
386 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
387         __acquires(rq->lock)
388 {
389         struct rq *rq;
390
391 repeat_lock_task:
392         local_irq_save(*flags);
393         rq = task_rq(p);
394         spin_lock(&rq->lock);
395         if (unlikely(rq != task_rq(p))) {
396                 spin_unlock_irqrestore(&rq->lock, *flags);
397                 goto repeat_lock_task;
398         }
399         return rq;
400 }
401
402 static inline void __task_rq_unlock(struct rq *rq)
403         __releases(rq->lock)
404 {
405         spin_unlock(&rq->lock);
406 }
407
408 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
409         __releases(rq->lock)
410 {
411         spin_unlock_irqrestore(&rq->lock, *flags);
412 }
413
414 #ifdef CONFIG_SCHEDSTATS
415 /*
416  * bump this up when changing the output format or the meaning of an existing
417  * format, so that tools can adapt (or abort)
418  */
419 #define SCHEDSTAT_VERSION 12
420
421 static int show_schedstat(struct seq_file *seq, void *v)
422 {
423         int cpu;
424
425         seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
426         seq_printf(seq, "timestamp %lu\n", jiffies);
427         for_each_online_cpu(cpu) {
428                 struct rq *rq = cpu_rq(cpu);
429 #ifdef CONFIG_SMP
430                 struct sched_domain *sd;
431                 int dcnt = 0;
432 #endif
433
434                 /* runqueue-specific stats */
435                 seq_printf(seq,
436                     "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
437                     cpu, rq->yld_both_empty,
438                     rq->yld_act_empty, rq->yld_exp_empty, rq->yld_cnt,
439                     rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
440                     rq->ttwu_cnt, rq->ttwu_local,
441                     rq->rq_sched_info.cpu_time,
442                     rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
443
444                 seq_printf(seq, "\n");
445
446 #ifdef CONFIG_SMP
447                 /* domain-specific stats */
448                 preempt_disable();
449                 for_each_domain(cpu, sd) {
450                         enum idle_type itype;
451                         char mask_str[NR_CPUS];
452
453                         cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
454                         seq_printf(seq, "domain%d %s", dcnt++, mask_str);
455                         for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
456                                         itype++) {
457                                 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu",
458                                     sd->lb_cnt[itype],
459                                     sd->lb_balanced[itype],
460                                     sd->lb_failed[itype],
461                                     sd->lb_imbalance[itype],
462                                     sd->lb_gained[itype],
463                                     sd->lb_hot_gained[itype],
464                                     sd->lb_nobusyq[itype],
465                                     sd->lb_nobusyg[itype]);
466                         }
467                         seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
468                             sd->alb_cnt, sd->alb_failed, sd->alb_pushed,
469                             sd->sbe_cnt, sd->sbe_balanced, sd->sbe_pushed,
470                             sd->sbf_cnt, sd->sbf_balanced, sd->sbf_pushed,
471                             sd->ttwu_wake_remote, sd->ttwu_move_affine, sd->ttwu_move_balance);
472                 }
473                 preempt_enable();
474 #endif
475         }
476         return 0;
477 }
478
479 static int schedstat_open(struct inode *inode, struct file *file)
480 {
481         unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
482         char *buf = kmalloc(size, GFP_KERNEL);
483         struct seq_file *m;
484         int res;
485
486         if (!buf)
487                 return -ENOMEM;
488         res = single_open(file, show_schedstat, NULL);
489         if (!res) {
490                 m = file->private_data;
491                 m->buf = buf;
492                 m->size = size;
493         } else
494                 kfree(buf);
495         return res;
496 }
497
498 struct file_operations proc_schedstat_operations = {
499         .open    = schedstat_open,
500         .read    = seq_read,
501         .llseek  = seq_lseek,
502         .release = single_release,
503 };
504
505 # define schedstat_inc(rq, field)       do { (rq)->field++; } while (0)
506 # define schedstat_add(rq, field, amt)  do { (rq)->field += (amt); } while (0)
507 #else /* !CONFIG_SCHEDSTATS */
508 # define schedstat_inc(rq, field)       do { } while (0)
509 # define schedstat_add(rq, field, amt)  do { } while (0)
510 #endif
511
512 /*
513  * rq_lock - lock a given runqueue and disable interrupts.
514  */
515 static inline struct rq *this_rq_lock(void)
516         __acquires(rq->lock)
517 {
518         struct rq *rq;
519
520         local_irq_disable();
521         rq = this_rq();
522         spin_lock(&rq->lock);
523
524         return rq;
525 }
526
527 #ifdef CONFIG_SCHEDSTATS
528 /*
529  * Called when a process is dequeued from the active array and given
530  * the cpu.  We should note that with the exception of interactive
531  * tasks, the expired queue will become the active queue after the active
532  * queue is empty, without explicitly dequeuing and requeuing tasks in the
533  * expired queue.  (Interactive tasks may be requeued directly to the
534  * active queue, thus delaying tasks in the expired queue from running;
535  * see scheduler_tick()).
536  *
537  * This function is only called from sched_info_arrive(), rather than
538  * dequeue_task(). Even though a task may be queued and dequeued multiple
539  * times as it is shuffled about, we're really interested in knowing how
540  * long it was from the *first* time it was queued to the time that it
541  * finally hit a cpu.
542  */
543 static inline void sched_info_dequeued(struct task_struct *t)
544 {
545         t->sched_info.last_queued = 0;
546 }
547
548 /*
549  * Called when a task finally hits the cpu.  We can now calculate how
550  * long it was waiting to run.  We also note when it began so that we
551  * can keep stats on how long its timeslice is.
552  */
553 static void sched_info_arrive(struct task_struct *t)
554 {
555         unsigned long now = jiffies, diff = 0;
556         struct rq *rq = task_rq(t);
557
558         if (t->sched_info.last_queued)
559                 diff = now - t->sched_info.last_queued;
560         sched_info_dequeued(t);
561         t->sched_info.run_delay += diff;
562         t->sched_info.last_arrival = now;
563         t->sched_info.pcnt++;
564
565         if (!rq)
566                 return;
567
568         rq->rq_sched_info.run_delay += diff;
569         rq->rq_sched_info.pcnt++;
570 }
571
572 /*
573  * Called when a process is queued into either the active or expired
574  * array.  The time is noted and later used to determine how long we
575  * had to wait for us to reach the cpu.  Since the expired queue will
576  * become the active queue after active queue is empty, without dequeuing
577  * and requeuing any tasks, we are interested in queuing to either. It
578  * is unusual but not impossible for tasks to be dequeued and immediately
579  * requeued in the same or another array: this can happen in sched_yield(),
580  * set_user_nice(), and even load_balance() as it moves tasks from runqueue
581  * to runqueue.
582  *
583  * This function is only called from enqueue_task(), but also only updates
584  * the timestamp if it is already not set.  It's assumed that
585  * sched_info_dequeued() will clear that stamp when appropriate.
586  */
587 static inline void sched_info_queued(struct task_struct *t)
588 {
589         if (!t->sched_info.last_queued)
590                 t->sched_info.last_queued = jiffies;
591 }
592
593 /*
594  * Called when a process ceases being the active-running process, either
595  * voluntarily or involuntarily.  Now we can calculate how long we ran.
596  */
597 static inline void sched_info_depart(struct task_struct *t)
598 {
599         struct rq *rq = task_rq(t);
600         unsigned long diff = jiffies - t->sched_info.last_arrival;
601
602         t->sched_info.cpu_time += diff;
603
604         if (rq)
605                 rq->rq_sched_info.cpu_time += diff;
606 }
607
608 /*
609  * Called when tasks are switched involuntarily due, typically, to expiring
610  * their time slice.  (This may also be called when switching to or from
611  * the idle task.)  We are only called when prev != next.
612  */
613 static inline void
614 sched_info_switch(struct task_struct *prev, struct task_struct *next)
615 {
616         struct rq *rq = task_rq(prev);
617
618         /*
619          * prev now departs the cpu.  It's not interesting to record
620          * stats about how efficient we were at scheduling the idle
621          * process, however.
622          */
623         if (prev != rq->idle)
624                 sched_info_depart(prev);
625
626         if (next != rq->idle)
627                 sched_info_arrive(next);
628 }
629 #else
630 #define sched_info_queued(t)            do { } while (0)
631 #define sched_info_switch(t, next)      do { } while (0)
632 #endif /* CONFIG_SCHEDSTATS */
633
634 /*
635  * Adding/removing a task to/from a priority array:
636  */
637 static void dequeue_task(struct task_struct *p, struct prio_array *array)
638 {
639         array->nr_active--;
640         list_del(&p->run_list);
641         if (list_empty(array->queue + p->prio))
642                 __clear_bit(p->prio, array->bitmap);
643 }
644
645 static void enqueue_task(struct task_struct *p, struct prio_array *array)
646 {
647         sched_info_queued(p);
648         list_add_tail(&p->run_list, array->queue + p->prio);
649         __set_bit(p->prio, array->bitmap);
650         array->nr_active++;
651         p->array = array;
652 }
653
654 /*
655  * Put task to the end of the run list without the overhead of dequeue
656  * followed by enqueue.
657  */
658 static void requeue_task(struct task_struct *p, struct prio_array *array)
659 {
660         list_move_tail(&p->run_list, array->queue + p->prio);
661 }
662
663 static inline void
664 enqueue_task_head(struct task_struct *p, struct prio_array *array)
665 {
666         list_add(&p->run_list, array->queue + p->prio);
667         __set_bit(p->prio, array->bitmap);
668         array->nr_active++;
669         p->array = array;
670 }
671
672 /*
673  * __normal_prio - return the priority that is based on the static
674  * priority but is modified by bonuses/penalties.
675  *
676  * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
677  * into the -5 ... 0 ... +5 bonus/penalty range.
678  *
679  * We use 25% of the full 0...39 priority range so that:
680  *
681  * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
682  * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
683  *
684  * Both properties are important to certain workloads.
685  */
686
687 static inline int __normal_prio(struct task_struct *p)
688 {
689         int bonus, prio;
690
691         bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
692
693         prio = p->static_prio - bonus;
694         if (prio < MAX_RT_PRIO)
695                 prio = MAX_RT_PRIO;
696         if (prio > MAX_PRIO-1)
697                 prio = MAX_PRIO-1;
698         return prio;
699 }
700
701 /*
702  * To aid in avoiding the subversion of "niceness" due to uneven distribution
703  * of tasks with abnormal "nice" values across CPUs the contribution that
704  * each task makes to its run queue's load is weighted according to its
705  * scheduling class and "nice" value.  For SCHED_NORMAL tasks this is just a
706  * scaled version of the new time slice allocation that they receive on time
707  * slice expiry etc.
708  */
709
710 /*
711  * Assume: static_prio_timeslice(NICE_TO_PRIO(0)) == DEF_TIMESLICE
712  * If static_prio_timeslice() is ever changed to break this assumption then
713  * this code will need modification
714  */
715 #define TIME_SLICE_NICE_ZERO DEF_TIMESLICE
716 #define LOAD_WEIGHT(lp) \
717         (((lp) * SCHED_LOAD_SCALE) / TIME_SLICE_NICE_ZERO)
718 #define PRIO_TO_LOAD_WEIGHT(prio) \
719         LOAD_WEIGHT(static_prio_timeslice(prio))
720 #define RTPRIO_TO_LOAD_WEIGHT(rp) \
721         (PRIO_TO_LOAD_WEIGHT(MAX_RT_PRIO) + LOAD_WEIGHT(rp))
722
723 static void set_load_weight(struct task_struct *p)
724 {
725         if (has_rt_policy(p)) {
726 #ifdef CONFIG_SMP
727                 if (p == task_rq(p)->migration_thread)
728                         /*
729                          * The migration thread does the actual balancing.
730                          * Giving its load any weight will skew balancing
731                          * adversely.
732                          */
733                         p->load_weight = 0;
734                 else
735 #endif
736                         p->load_weight = RTPRIO_TO_LOAD_WEIGHT(p->rt_priority);
737         } else
738                 p->load_weight = PRIO_TO_LOAD_WEIGHT(p->static_prio);
739 }
740
741 static inline void
742 inc_raw_weighted_load(struct rq *rq, const struct task_struct *p)
743 {
744         rq->raw_weighted_load += p->load_weight;
745 }
746
747 static inline void
748 dec_raw_weighted_load(struct rq *rq, const struct task_struct *p)
749 {
750         rq->raw_weighted_load -= p->load_weight;
751 }
752
753 static inline void inc_nr_running(struct task_struct *p, struct rq *rq)
754 {
755         rq->nr_running++;
756         inc_raw_weighted_load(rq, p);
757 }
758
759 static inline void dec_nr_running(struct task_struct *p, struct rq *rq)
760 {
761         rq->nr_running--;
762         dec_raw_weighted_load(rq, p);
763 }
764
765 /*
766  * Calculate the expected normal priority: i.e. priority
767  * without taking RT-inheritance into account. Might be
768  * boosted by interactivity modifiers. Changes upon fork,
769  * setprio syscalls, and whenever the interactivity
770  * estimator recalculates.
771  */
772 static inline int normal_prio(struct task_struct *p)
773 {
774         int prio;
775
776         if (has_rt_policy(p))
777                 prio = MAX_RT_PRIO-1 - p->rt_priority;
778         else
779                 prio = __normal_prio(p);
780         return prio;
781 }
782
783 /*
784  * Calculate the current priority, i.e. the priority
785  * taken into account by the scheduler. This value might
786  * be boosted by RT tasks, or might be boosted by
787  * interactivity modifiers. Will be RT if the task got
788  * RT-boosted. If not then it returns p->normal_prio.
789  */
790 static int effective_prio(struct task_struct *p)
791 {
792         p->normal_prio = normal_prio(p);
793         /*
794          * If we are RT tasks or we were boosted to RT priority,
795          * keep the priority unchanged. Otherwise, update priority
796          * to the normal priority:
797          */
798         if (!rt_prio(p->prio))
799                 return p->normal_prio;
800         return p->prio;
801 }
802
803 /*
804  * __activate_task - move a task to the runqueue.
805  */
806 static void __activate_task(struct task_struct *p, struct rq *rq)
807 {
808         struct prio_array *target = rq->active;
809
810         if (batch_task(p))
811                 target = rq->expired;
812         enqueue_task(p, target);
813         inc_nr_running(p, rq);
814 }
815
816 /*
817  * __activate_idle_task - move idle task to the _front_ of runqueue.
818  */
819 static inline void __activate_idle_task(struct task_struct *p, struct rq *rq)
820 {
821         enqueue_task_head(p, rq->active);
822         inc_nr_running(p, rq);
823 }
824
825 /*
826  * Recalculate p->normal_prio and p->prio after having slept,
827  * updating the sleep-average too:
828  */
829 static int recalc_task_prio(struct task_struct *p, unsigned long long now)
830 {
831         /* Caller must always ensure 'now >= p->timestamp' */
832         unsigned long sleep_time = now - p->timestamp;
833
834         if (batch_task(p))
835                 sleep_time = 0;
836
837         if (likely(sleep_time > 0)) {
838                 /*
839                  * This ceiling is set to the lowest priority that would allow
840                  * a task to be reinserted into the active array on timeslice
841                  * completion.
842                  */
843                 unsigned long ceiling = INTERACTIVE_SLEEP(p);
844
845                 if (p->mm && sleep_time > ceiling && p->sleep_avg < ceiling) {
846                         /*
847                          * Prevents user tasks from achieving best priority
848                          * with one single large enough sleep.
849                          */
850                         p->sleep_avg = ceiling;
851                         /*
852                          * Using INTERACTIVE_SLEEP() as a ceiling places a
853                          * nice(0) task 1ms sleep away from promotion, and
854                          * gives it 700ms to round-robin with no chance of
855                          * being demoted.  This is more than generous, so
856                          * mark this sleep as non-interactive to prevent the
857                          * on-runqueue bonus logic from intervening should
858                          * this task not receive cpu immediately.
859                          */
860                         p->sleep_type = SLEEP_NONINTERACTIVE;
861                 } else {
862                         /*
863                          * Tasks waking from uninterruptible sleep are
864                          * limited in their sleep_avg rise as they
865                          * are likely to be waiting on I/O
866                          */
867                         if (p->sleep_type == SLEEP_NONINTERACTIVE && p->mm) {
868                                 if (p->sleep_avg >= ceiling)
869                                         sleep_time = 0;
870                                 else if (p->sleep_avg + sleep_time >=
871                                          ceiling) {
872                                                 p->sleep_avg = ceiling;
873                                                 sleep_time = 0;
874                                 }
875                         }
876
877                         /*
878                          * This code gives a bonus to interactive tasks.
879                          *
880                          * The boost works by updating the 'average sleep time'
881                          * value here, based on ->timestamp. The more time a
882                          * task spends sleeping, the higher the average gets -
883                          * and the higher the priority boost gets as well.
884                          */
885                         p->sleep_avg += sleep_time;
886
887                 }
888                 if (p->sleep_avg > NS_MAX_SLEEP_AVG)
889                         p->sleep_avg = NS_MAX_SLEEP_AVG;
890         }
891
892         return effective_prio(p);
893 }
894
895 /*
896  * activate_task - move a task to the runqueue and do priority recalculation
897  *
898  * Update all the scheduling statistics stuff. (sleep average
899  * calculation, priority modifiers, etc.)
900  */
901 static void activate_task(struct task_struct *p, struct rq *rq, int local)
902 {
903         unsigned long long now;
904
905         now = sched_clock();
906 #ifdef CONFIG_SMP
907         if (!local) {
908                 /* Compensate for drifting sched_clock */
909                 struct rq *this_rq = this_rq();
910                 now = (now - this_rq->timestamp_last_tick)
911                         + rq->timestamp_last_tick;
912         }
913 #endif
914
915         if (!rt_task(p))
916                 p->prio = recalc_task_prio(p, now);
917
918         /*
919          * This checks to make sure it's not an uninterruptible task
920          * that is now waking up.
921          */
922         if (p->sleep_type == SLEEP_NORMAL) {
923                 /*
924                  * Tasks which were woken up by interrupts (ie. hw events)
925                  * are most likely of interactive nature. So we give them
926                  * the credit of extending their sleep time to the period
927                  * of time they spend on the runqueue, waiting for execution
928                  * on a CPU, first time around:
929                  */
930                 if (in_interrupt())
931                         p->sleep_type = SLEEP_INTERRUPTED;
932                 else {
933                         /*
934                          * Normal first-time wakeups get a credit too for
935                          * on-runqueue time, but it will be weighted down:
936                          */
937                         p->sleep_type = SLEEP_INTERACTIVE;
938                 }
939         }
940         p->timestamp = now;
941
942         __activate_task(p, rq);
943 }
944
945 /*
946  * deactivate_task - remove a task from the runqueue.
947  */
948 static void deactivate_task(struct task_struct *p, struct rq *rq)
949 {
950         dec_nr_running(p, rq);
951         dequeue_task(p, p->array);
952         p->array = NULL;
953 }
954
955 /*
956  * resched_task - mark a task 'to be rescheduled now'.
957  *
958  * On UP this means the setting of the need_resched flag, on SMP it
959  * might also involve a cross-CPU call to trigger the scheduler on
960  * the target CPU.
961  */
962 #ifdef CONFIG_SMP
963
964 #ifndef tsk_is_polling
965 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
966 #endif
967
968 static void resched_task(struct task_struct *p)
969 {
970         int cpu;
971
972         assert_spin_locked(&task_rq(p)->lock);
973
974         if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
975                 return;
976
977         set_tsk_thread_flag(p, TIF_NEED_RESCHED);
978
979         cpu = task_cpu(p);
980         if (cpu == smp_processor_id())
981                 return;
982
983         /* NEED_RESCHED must be visible before we test polling */
984         smp_mb();
985         if (!tsk_is_polling(p))
986                 smp_send_reschedule(cpu);
987 }
988 #else
989 static inline void resched_task(struct task_struct *p)
990 {
991         assert_spin_locked(&task_rq(p)->lock);
992         set_tsk_need_resched(p);
993 }
994 #endif
995
996 /**
997  * task_curr - is this task currently executing on a CPU?
998  * @p: the task in question.
999  */
1000 inline int task_curr(const struct task_struct *p)
1001 {
1002         return cpu_curr(task_cpu(p)) == p;
1003 }
1004
1005 /* Used instead of source_load when we know the type == 0 */
1006 unsigned long weighted_cpuload(const int cpu)
1007 {
1008         return cpu_rq(cpu)->raw_weighted_load;
1009 }
1010
1011 #ifdef CONFIG_SMP
1012 struct migration_req {
1013         struct list_head list;
1014
1015         struct task_struct *task;
1016         int dest_cpu;
1017
1018         struct completion done;
1019 };
1020
1021 /*
1022  * The task's runqueue lock must be held.
1023  * Returns true if you have to wait for migration thread.
1024  */
1025 static int
1026 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1027 {
1028         struct rq *rq = task_rq(p);
1029
1030         /*
1031          * If the task is not on a runqueue (and not running), then
1032          * it is sufficient to simply update the task's cpu field.
1033          */
1034         if (!p->array && !task_running(rq, p)) {
1035                 set_task_cpu(p, dest_cpu);
1036                 return 0;
1037         }
1038
1039         init_completion(&req->done);
1040         req->task = p;
1041         req->dest_cpu = dest_cpu;
1042         list_add(&req->list, &rq->migration_queue);
1043
1044         return 1;
1045 }
1046
1047 /*
1048  * wait_task_inactive - wait for a thread to unschedule.
1049  *
1050  * The caller must ensure that the task *will* unschedule sometime soon,
1051  * else this function might spin for a *long* time. This function can't
1052  * be called with interrupts off, or it may introduce deadlock with
1053  * smp_call_function() if an IPI is sent by the same process we are
1054  * waiting to become inactive.
1055  */
1056 void wait_task_inactive(struct task_struct *p)
1057 {
1058         unsigned long flags;
1059         struct rq *rq;
1060         int preempted;
1061
1062 repeat:
1063         rq = task_rq_lock(p, &flags);
1064         /* Must be off runqueue entirely, not preempted. */
1065         if (unlikely(p->array || task_running(rq, p))) {
1066                 /* If it's preempted, we yield.  It could be a while. */
1067                 preempted = !task_running(rq, p);
1068                 task_rq_unlock(rq, &flags);
1069                 cpu_relax();
1070                 if (preempted)
1071                         yield();
1072                 goto repeat;
1073         }
1074         task_rq_unlock(rq, &flags);
1075 }
1076
1077 /***
1078  * kick_process - kick a running thread to enter/exit the kernel
1079  * @p: the to-be-kicked thread
1080  *
1081  * Cause a process which is running on another CPU to enter
1082  * kernel-mode, without any delay. (to get signals handled.)
1083  *
1084  * NOTE: this function doesnt have to take the runqueue lock,
1085  * because all it wants to ensure is that the remote task enters
1086  * the kernel. If the IPI races and the task has been migrated
1087  * to another CPU then no harm is done and the purpose has been
1088  * achieved as well.
1089  */
1090 void kick_process(struct task_struct *p)
1091 {
1092         int cpu;
1093
1094         preempt_disable();
1095         cpu = task_cpu(p);
1096         if ((cpu != smp_processor_id()) && task_curr(p))
1097                 smp_send_reschedule(cpu);
1098         preempt_enable();
1099 }
1100
1101 /*
1102  * Return a low guess at the load of a migration-source cpu weighted
1103  * according to the scheduling class and "nice" value.
1104  *
1105  * We want to under-estimate the load of migration sources, to
1106  * balance conservatively.
1107  */
1108 static inline unsigned long source_load(int cpu, int type)
1109 {
1110         struct rq *rq = cpu_rq(cpu);
1111
1112         if (type == 0)
1113                 return rq->raw_weighted_load;
1114
1115         return min(rq->cpu_load[type-1], rq->raw_weighted_load);
1116 }
1117
1118 /*
1119  * Return a high guess at the load of a migration-target cpu weighted
1120  * according to the scheduling class and "nice" value.
1121  */
1122 static inline unsigned long target_load(int cpu, int type)
1123 {
1124         struct rq *rq = cpu_rq(cpu);
1125
1126         if (type == 0)
1127                 return rq->raw_weighted_load;
1128
1129         return max(rq->cpu_load[type-1], rq->raw_weighted_load);
1130 }
1131
1132 /*
1133  * Return the average load per task on the cpu's run queue
1134  */
1135 static inline unsigned long cpu_avg_load_per_task(int cpu)
1136 {
1137         struct rq *rq = cpu_rq(cpu);
1138         unsigned long n = rq->nr_running;
1139
1140         return n ? rq->raw_weighted_load / n : SCHED_LOAD_SCALE;
1141 }
1142
1143 /*
1144  * find_idlest_group finds and returns the least busy CPU group within the
1145  * domain.
1146  */
1147 static struct sched_group *
1148 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1149 {
1150         struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1151         unsigned long min_load = ULONG_MAX, this_load = 0;
1152         int load_idx = sd->forkexec_idx;
1153         int imbalance = 100 + (sd->imbalance_pct-100)/2;
1154
1155         do {
1156                 unsigned long load, avg_load;
1157                 int local_group;
1158                 int i;
1159
1160                 /* Skip over this group if it has no CPUs allowed */
1161                 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
1162                         goto nextgroup;
1163
1164                 local_group = cpu_isset(this_cpu, group->cpumask);
1165
1166                 /* Tally up the load of all CPUs in the group */
1167                 avg_load = 0;
1168
1169                 for_each_cpu_mask(i, group->cpumask) {
1170                         /* Bias balancing toward cpus of our domain */
1171                         if (local_group)
1172                                 load = source_load(i, load_idx);
1173                         else
1174                                 load = target_load(i, load_idx);
1175
1176                         avg_load += load;
1177                 }
1178
1179                 /* Adjust by relative CPU power of the group */
1180                 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1181
1182                 if (local_group) {
1183                         this_load = avg_load;
1184                         this = group;
1185                 } else if (avg_load < min_load) {
1186                         min_load = avg_load;
1187                         idlest = group;
1188                 }
1189 nextgroup:
1190                 group = group->next;
1191         } while (group != sd->groups);
1192
1193         if (!idlest || 100*this_load < imbalance*min_load)
1194                 return NULL;
1195         return idlest;
1196 }
1197
1198 /*
1199  * find_idlest_queue - find the idlest runqueue among the cpus in group.
1200  */
1201 static int
1202 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
1203 {
1204         cpumask_t tmp;
1205         unsigned long load, min_load = ULONG_MAX;
1206         int idlest = -1;
1207         int i;
1208
1209         /* Traverse only the allowed CPUs */
1210         cpus_and(tmp, group->cpumask, p->cpus_allowed);
1211
1212         for_each_cpu_mask(i, tmp) {
1213                 load = weighted_cpuload(i);
1214
1215                 if (load < min_load || (load == min_load && i == this_cpu)) {
1216                         min_load = load;
1217                         idlest = i;
1218                 }
1219         }
1220
1221         return idlest;
1222 }
1223
1224 /*
1225  * sched_balance_self: balance the current task (running on cpu) in domains
1226  * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1227  * SD_BALANCE_EXEC.
1228  *
1229  * Balance, ie. select the least loaded group.
1230  *
1231  * Returns the target CPU number, or the same CPU if no balancing is needed.
1232  *
1233  * preempt must be disabled.
1234  */
1235 static int sched_balance_self(int cpu, int flag)
1236 {
1237         struct task_struct *t = current;
1238         struct sched_domain *tmp, *sd = NULL;
1239
1240         for_each_domain(cpu, tmp) {
1241                 /*
1242                  * If power savings logic is enabled for a domain, stop there.
1243                  */
1244                 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
1245                         break;
1246                 if (tmp->flags & flag)
1247                         sd = tmp;
1248         }
1249
1250         while (sd) {
1251                 cpumask_t span;
1252                 struct sched_group *group;
1253                 int new_cpu;
1254                 int weight;
1255
1256                 span = sd->span;
1257                 group = find_idlest_group(sd, t, cpu);
1258                 if (!group)
1259                         goto nextlevel;
1260
1261                 new_cpu = find_idlest_cpu(group, t, cpu);
1262                 if (new_cpu == -1 || new_cpu == cpu)
1263                         goto nextlevel;
1264
1265                 /* Now try balancing at a lower domain level */
1266                 cpu = new_cpu;
1267 nextlevel:
1268                 sd = NULL;
1269                 weight = cpus_weight(span);
1270                 for_each_domain(cpu, tmp) {
1271                         if (weight <= cpus_weight(tmp->span))
1272                                 break;
1273                         if (tmp->flags & flag)
1274                                 sd = tmp;
1275                 }
1276                 /* while loop will break here if sd == NULL */
1277         }
1278
1279         return cpu;
1280 }
1281
1282 #endif /* CONFIG_SMP */
1283
1284 /*
1285  * wake_idle() will wake a task on an idle cpu if task->cpu is
1286  * not idle and an idle cpu is available.  The span of cpus to
1287  * search starts with cpus closest then further out as needed,
1288  * so we always favor a closer, idle cpu.
1289  *
1290  * Returns the CPU we should wake onto.
1291  */
1292 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1293 static int wake_idle(int cpu, struct task_struct *p)
1294 {
1295         cpumask_t tmp;
1296         struct sched_domain *sd;
1297         int i;
1298
1299         if (idle_cpu(cpu))
1300                 return cpu;
1301
1302         for_each_domain(cpu, sd) {
1303                 if (sd->flags & SD_WAKE_IDLE) {
1304                         cpus_and(tmp, sd->span, p->cpus_allowed);
1305                         for_each_cpu_mask(i, tmp) {
1306                                 if (idle_cpu(i))
1307                                         return i;
1308                         }
1309                 }
1310                 else
1311                         break;
1312         }
1313         return cpu;
1314 }
1315 #else
1316 static inline int wake_idle(int cpu, struct task_struct *p)
1317 {
1318         return cpu;
1319 }
1320 #endif
1321
1322 /***
1323  * try_to_wake_up - wake up a thread
1324  * @p: the to-be-woken-up thread
1325  * @state: the mask of task states that can be woken
1326  * @sync: do a synchronous wakeup?
1327  *
1328  * Put it on the run-queue if it's not already there. The "current"
1329  * thread is always on the run-queue (except when the actual
1330  * re-schedule is in progress), and as such you're allowed to do
1331  * the simpler "current->state = TASK_RUNNING" to mark yourself
1332  * runnable without the overhead of this.
1333  *
1334  * returns failure only if the task is already active.
1335  */
1336 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
1337 {
1338         int cpu, this_cpu, success = 0;
1339         unsigned long flags;
1340         long old_state;
1341         struct rq *rq;
1342 #ifdef CONFIG_SMP
1343         struct sched_domain *sd, *this_sd = NULL;
1344         unsigned long load, this_load;
1345         int new_cpu;
1346 #endif
1347
1348         rq = task_rq_lock(p, &flags);
1349         old_state = p->state;
1350         if (!(old_state & state))
1351                 goto out;
1352
1353         if (p->array)
1354                 goto out_running;
1355
1356         cpu = task_cpu(p);
1357         this_cpu = smp_processor_id();
1358
1359 #ifdef CONFIG_SMP
1360         if (unlikely(task_running(rq, p)))
1361                 goto out_activate;
1362
1363         new_cpu = cpu;
1364
1365         schedstat_inc(rq, ttwu_cnt);
1366         if (cpu == this_cpu) {
1367                 schedstat_inc(rq, ttwu_local);
1368                 goto out_set_cpu;
1369         }
1370
1371         for_each_domain(this_cpu, sd) {
1372                 if (cpu_isset(cpu, sd->span)) {
1373                         schedstat_inc(sd, ttwu_wake_remote);
1374                         this_sd = sd;
1375                         break;
1376                 }
1377         }
1378
1379         if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1380                 goto out_set_cpu;
1381
1382         /*
1383          * Check for affine wakeup and passive balancing possibilities.
1384          */
1385         if (this_sd) {
1386                 int idx = this_sd->wake_idx;
1387                 unsigned int imbalance;
1388
1389                 imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
1390
1391                 load = source_load(cpu, idx);
1392                 this_load = target_load(this_cpu, idx);
1393
1394                 new_cpu = this_cpu; /* Wake to this CPU if we can */
1395
1396                 if (this_sd->flags & SD_WAKE_AFFINE) {
1397                         unsigned long tl = this_load;
1398                         unsigned long tl_per_task = cpu_avg_load_per_task(this_cpu);
1399
1400                         /*
1401                          * If sync wakeup then subtract the (maximum possible)
1402                          * effect of the currently running task from the load
1403                          * of the current CPU:
1404                          */
1405                         if (sync)
1406                                 tl -= current->load_weight;
1407
1408                         if ((tl <= load &&
1409                                 tl + target_load(cpu, idx) <= tl_per_task) ||
1410                                 100*(tl + p->load_weight) <= imbalance*load) {
1411                                 /*
1412                                  * This domain has SD_WAKE_AFFINE and
1413                                  * p is cache cold in this domain, and
1414                                  * there is no bad imbalance.
1415                                  */
1416                                 schedstat_inc(this_sd, ttwu_move_affine);
1417                                 goto out_set_cpu;
1418                         }
1419                 }
1420
1421                 /*
1422                  * Start passive balancing when half the imbalance_pct
1423                  * limit is reached.
1424                  */
1425                 if (this_sd->flags & SD_WAKE_BALANCE) {
1426                         if (imbalance*this_load <= 100*load) {
1427                                 schedstat_inc(this_sd, ttwu_move_balance);
1428                                 goto out_set_cpu;
1429                         }
1430                 }
1431         }
1432
1433         new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1434 out_set_cpu:
1435         new_cpu = wake_idle(new_cpu, p);
1436         if (new_cpu != cpu) {
1437                 set_task_cpu(p, new_cpu);
1438                 task_rq_unlock(rq, &flags);
1439                 /* might preempt at this point */
1440                 rq = task_rq_lock(p, &flags);
1441                 old_state = p->state;
1442                 if (!(old_state & state))
1443                         goto out;
1444                 if (p->array)
1445                         goto out_running;
1446
1447                 this_cpu = smp_processor_id();
1448                 cpu = task_cpu(p);
1449         }
1450
1451 out_activate:
1452 #endif /* CONFIG_SMP */
1453         if (old_state == TASK_UNINTERRUPTIBLE) {
1454                 rq->nr_uninterruptible--;
1455                 /*
1456                  * Tasks on involuntary sleep don't earn
1457                  * sleep_avg beyond just interactive state.
1458                  */
1459                 p->sleep_type = SLEEP_NONINTERACTIVE;
1460         } else
1461
1462         /*
1463          * Tasks that have marked their sleep as noninteractive get
1464          * woken up with their sleep average not weighted in an
1465          * interactive way.
1466          */
1467                 if (old_state & TASK_NONINTERACTIVE)
1468                         p->sleep_type = SLEEP_NONINTERACTIVE;
1469
1470
1471         activate_task(p, rq, cpu == this_cpu);
1472         /*
1473          * Sync wakeups (i.e. those types of wakeups where the waker
1474          * has indicated that it will leave the CPU in short order)
1475          * don't trigger a preemption, if the woken up task will run on
1476          * this cpu. (in this case the 'I will reschedule' promise of
1477          * the waker guarantees that the freshly woken up task is going
1478          * to be considered on this CPU.)
1479          */
1480         if (!sync || cpu != this_cpu) {
1481                 if (TASK_PREEMPTS_CURR(p, rq))
1482                         resched_task(rq->curr);
1483         }
1484         success = 1;
1485
1486 out_running:
1487         p->state = TASK_RUNNING;
1488 out:
1489         task_rq_unlock(rq, &flags);
1490
1491         return success;
1492 }
1493
1494 int fastcall wake_up_process(struct task_struct *p)
1495 {
1496         return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1497                                  TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1498 }
1499 EXPORT_SYMBOL(wake_up_process);
1500
1501 int fastcall wake_up_state(struct task_struct *p, unsigned int state)
1502 {
1503         return try_to_wake_up(p, state, 0);
1504 }
1505
1506 /*
1507  * Perform scheduler related setup for a newly forked process p.
1508  * p is forked by current.
1509  */
1510 void fastcall sched_fork(struct task_struct *p, int clone_flags)
1511 {
1512         int cpu = get_cpu();
1513
1514 #ifdef CONFIG_SMP
1515         cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
1516 #endif
1517         set_task_cpu(p, cpu);
1518
1519         /*
1520          * We mark the process as running here, but have not actually
1521          * inserted it onto the runqueue yet. This guarantees that
1522          * nobody will actually run it, and a signal or other external
1523          * event cannot wake it up and insert it on the runqueue either.
1524          */
1525         p->state = TASK_RUNNING;
1526
1527         /*
1528          * Make sure we do not leak PI boosting priority to the child:
1529          */
1530         p->prio = current->normal_prio;
1531
1532         INIT_LIST_HEAD(&p->run_list);
1533         p->array = NULL;
1534 #ifdef CONFIG_SCHEDSTATS
1535         memset(&p->sched_info, 0, sizeof(p->sched_info));
1536 #endif
1537 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
1538         p->oncpu = 0;
1539 #endif
1540 #ifdef CONFIG_PREEMPT
1541         /* Want to start with kernel preemption disabled. */
1542         task_thread_info(p)->preempt_count = 1;
1543 #endif
1544         /*
1545          * Share the timeslice between parent and child, thus the
1546          * total amount of pending timeslices in the system doesn't change,
1547          * resulting in more scheduling fairness.
1548          */
1549         local_irq_disable();
1550         p->time_slice = (current->time_slice + 1) >> 1;
1551         /*
1552          * The remainder of the first timeslice might be recovered by
1553          * the parent if the child exits early enough.
1554          */
1555         p->first_time_slice = 1;
1556         current->time_slice >>= 1;
1557         p->timestamp = sched_clock();
1558         if (unlikely(!current->time_slice)) {
1559                 /*
1560                  * This case is rare, it happens when the parent has only
1561                  * a single jiffy left from its timeslice. Taking the
1562                  * runqueue lock is not a problem.
1563                  */
1564                 current->time_slice = 1;
1565                 scheduler_tick();
1566         }
1567         local_irq_enable();
1568         put_cpu();
1569 }
1570
1571 /*
1572  * wake_up_new_task - wake up a newly created task for the first time.
1573  *
1574  * This function will do some initial scheduler statistics housekeeping
1575  * that must be done for every newly created context, then puts the task
1576  * on the runqueue and wakes it.
1577  */
1578 void fastcall wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
1579 {
1580         struct rq *rq, *this_rq;
1581         unsigned long flags;
1582         int this_cpu, cpu;
1583
1584         rq = task_rq_lock(p, &flags);
1585         BUG_ON(p->state != TASK_RUNNING);
1586         this_cpu = smp_processor_id();
1587         cpu = task_cpu(p);
1588
1589         /*
1590          * We decrease the sleep average of forking parents
1591          * and children as well, to keep max-interactive tasks
1592          * from forking tasks that are max-interactive. The parent
1593          * (current) is done further down, under its lock.
1594          */
1595         p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1596                 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1597
1598         p->prio = effective_prio(p);
1599
1600         if (likely(cpu == this_cpu)) {
1601                 if (!(clone_flags & CLONE_VM)) {
1602                         /*
1603                          * The VM isn't cloned, so we're in a good position to
1604                          * do child-runs-first in anticipation of an exec. This
1605                          * usually avoids a lot of COW overhead.
1606                          */
1607                         if (unlikely(!current->array))
1608                                 __activate_task(p, rq);
1609                         else {
1610                                 p->prio = current->prio;
1611                                 p->normal_prio = current->normal_prio;
1612                                 list_add_tail(&p->run_list, &current->run_list);
1613                                 p->array = current->array;
1614                                 p->array->nr_active++;
1615                                 inc_nr_running(p, rq);
1616                         }
1617                         set_need_resched();
1618                 } else
1619                         /* Run child last */
1620                         __activate_task(p, rq);
1621                 /*
1622                  * We skip the following code due to cpu == this_cpu
1623                  *
1624                  *   task_rq_unlock(rq, &flags);
1625                  *   this_rq = task_rq_lock(current, &flags);
1626                  */
1627                 this_rq = rq;
1628         } else {
1629                 this_rq = cpu_rq(this_cpu);
1630
1631                 /*
1632                  * Not the local CPU - must adjust timestamp. This should
1633                  * get optimised away in the !CONFIG_SMP case.
1634                  */
1635                 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1636                                         + rq->timestamp_last_tick;
1637                 __activate_task(p, rq);
1638                 if (TASK_PREEMPTS_CURR(p, rq))
1639                         resched_task(rq->curr);
1640
1641                 /*
1642                  * Parent and child are on different CPUs, now get the
1643                  * parent runqueue to update the parent's ->sleep_avg:
1644                  */
1645                 task_rq_unlock(rq, &flags);
1646                 this_rq = task_rq_lock(current, &flags);
1647         }
1648         current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1649                 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1650         task_rq_unlock(this_rq, &flags);
1651 }
1652
1653 /*
1654  * Potentially available exiting-child timeslices are
1655  * retrieved here - this way the parent does not get
1656  * penalized for creating too many threads.
1657  *
1658  * (this cannot be used to 'generate' timeslices
1659  * artificially, because any timeslice recovered here
1660  * was given away by the parent in the first place.)
1661  */
1662 void fastcall sched_exit(struct task_struct *p)
1663 {
1664         unsigned long flags;
1665         struct rq *rq;
1666
1667         /*
1668          * If the child was a (relative-) CPU hog then decrease
1669          * the sleep_avg of the parent as well.
1670          */
1671         rq = task_rq_lock(p->parent, &flags);
1672         if (p->first_time_slice && task_cpu(p) == task_cpu(p->parent)) {
1673                 p->parent->time_slice += p->time_slice;
1674                 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1675                         p->parent->time_slice = task_timeslice(p);
1676         }
1677         if (p->sleep_avg < p->parent->sleep_avg)
1678                 p->parent->sleep_avg = p->parent->sleep_avg /
1679                 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1680                 (EXIT_WEIGHT + 1);
1681         task_rq_unlock(rq, &flags);
1682 }
1683
1684 /**
1685  * prepare_task_switch - prepare to switch tasks
1686  * @rq: the runqueue preparing to switch
1687  * @next: the task we are going to switch to.
1688  *
1689  * This is called with the rq lock held and interrupts off. It must
1690  * be paired with a subsequent finish_task_switch after the context
1691  * switch.
1692  *
1693  * prepare_task_switch sets up locking and calls architecture specific
1694  * hooks.
1695  */
1696 static inline void prepare_task_switch(struct rq *rq, struct task_struct *next)
1697 {
1698         prepare_lock_switch(rq, next);
1699         prepare_arch_switch(next);
1700 }
1701
1702 /**
1703  * finish_task_switch - clean up after a task-switch
1704  * @rq: runqueue associated with task-switch
1705  * @prev: the thread we just switched away from.
1706  *
1707  * finish_task_switch must be called after the context switch, paired
1708  * with a prepare_task_switch call before the context switch.
1709  * finish_task_switch will reconcile locking set up by prepare_task_switch,
1710  * and do any other architecture-specific cleanup actions.
1711  *
1712  * Note that we may have delayed dropping an mm in context_switch(). If
1713  * so, we finish that here outside of the runqueue lock.  (Doing it
1714  * with the lock held can cause deadlocks; see schedule() for
1715  * details.)
1716  */
1717 static inline void finish_task_switch(struct rq *rq, struct task_struct *prev)
1718         __releases(rq->lock)
1719 {
1720         struct mm_struct *mm = rq->prev_mm;
1721         unsigned long prev_task_flags;
1722
1723         rq->prev_mm = NULL;
1724
1725         /*
1726          * A task struct has one reference for the use as "current".
1727          * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1728          * calls schedule one last time. The schedule call will never return,
1729          * and the scheduled task must drop that reference.
1730          * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1731          * still held, otherwise prev could be scheduled on another cpu, die
1732          * there before we look at prev->state, and then the reference would
1733          * be dropped twice.
1734          *              Manfred Spraul <manfred@colorfullife.com>
1735          */
1736         prev_task_flags = prev->flags;
1737         finish_arch_switch(prev);
1738         finish_lock_switch(rq, prev);
1739         if (mm)
1740                 mmdrop(mm);
1741         if (unlikely(prev_task_flags & PF_DEAD)) {
1742                 /*
1743                  * Remove function-return probe instances associated with this
1744                  * task and put them back on the free list.
1745                  */
1746                 kprobe_flush_task(prev);
1747                 put_task_struct(prev);
1748         }
1749 }
1750
1751 /**
1752  * schedule_tail - first thing a freshly forked thread must call.
1753  * @prev: the thread we just switched away from.
1754  */
1755 asmlinkage void schedule_tail(struct task_struct *prev)
1756         __releases(rq->lock)
1757 {
1758         struct rq *rq = this_rq();
1759
1760         finish_task_switch(rq, prev);
1761 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
1762         /* In this case, finish_task_switch does not reenable preemption */
1763         preempt_enable();
1764 #endif
1765         if (current->set_child_tid)
1766                 put_user(current->pid, current->set_child_tid);
1767 }
1768
1769 /*
1770  * context_switch - switch to the new MM and the new
1771  * thread's register state.
1772  */
1773 static inline struct task_struct *
1774 context_switch(struct rq *rq, struct task_struct *prev,
1775                struct task_struct *next)
1776 {
1777         struct mm_struct *mm = next->mm;
1778         struct mm_struct *oldmm = prev->active_mm;
1779
1780         if (unlikely(!mm)) {
1781                 next->active_mm = oldmm;
1782                 atomic_inc(&oldmm->mm_count);
1783                 enter_lazy_tlb(oldmm, next);
1784         } else
1785                 switch_mm(oldmm, mm, next);
1786
1787         if (unlikely(!prev->mm)) {
1788                 prev->active_mm = NULL;
1789                 WARN_ON(rq->prev_mm);
1790                 rq->prev_mm = oldmm;
1791         }
1792         /*
1793          * Since the runqueue lock will be released by the next
1794          * task (which is an invalid locking op but in the case
1795          * of the scheduler it's an obvious special-case), so we
1796          * do an early lockdep release here:
1797          */
1798 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
1799         spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
1800 #endif
1801
1802         /* Here we just switch the register state and the stack. */
1803         switch_to(prev, next, prev);
1804
1805         return prev;
1806 }
1807
1808 /*
1809  * nr_running, nr_uninterruptible and nr_context_switches:
1810  *
1811  * externally visible scheduler statistics: current number of runnable
1812  * threads, current number of uninterruptible-sleeping threads, total
1813  * number of context switches performed since bootup.
1814  */
1815 unsigned long nr_running(void)
1816 {
1817         unsigned long i, sum = 0;
1818
1819         for_each_online_cpu(i)
1820                 sum += cpu_rq(i)->nr_running;
1821
1822         return sum;
1823 }
1824
1825 unsigned long nr_uninterruptible(void)
1826 {
1827         unsigned long i, sum = 0;
1828
1829         for_each_possible_cpu(i)
1830                 sum += cpu_rq(i)->nr_uninterruptible;
1831
1832         /*
1833          * Since we read the counters lockless, it might be slightly
1834          * inaccurate. Do not allow it to go below zero though:
1835          */
1836         if (unlikely((long)sum < 0))
1837                 sum = 0;
1838
1839         return sum;
1840 }
1841
1842 unsigned long long nr_context_switches(void)
1843 {
1844         int i;
1845         unsigned long long sum = 0;
1846
1847         for_each_possible_cpu(i)
1848                 sum += cpu_rq(i)->nr_switches;
1849
1850         return sum;
1851 }
1852
1853 unsigned long nr_iowait(void)
1854 {
1855         unsigned long i, sum = 0;
1856
1857         for_each_possible_cpu(i)
1858                 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1859
1860         return sum;
1861 }
1862
1863 unsigned long nr_active(void)
1864 {
1865         unsigned long i, running = 0, uninterruptible = 0;
1866
1867         for_each_online_cpu(i) {
1868                 running += cpu_rq(i)->nr_running;
1869                 uninterruptible += cpu_rq(i)->nr_uninterruptible;
1870         }
1871
1872         if (unlikely((long)uninterruptible < 0))
1873                 uninterruptible = 0;
1874
1875         return running + uninterruptible;
1876 }
1877
1878 #ifdef CONFIG_SMP
1879
1880 /*
1881  * Is this task likely cache-hot:
1882  */
1883 static inline int
1884 task_hot(struct task_struct *p, unsigned long long now, struct sched_domain *sd)
1885 {
1886         return (long long)(now - p->last_ran) < (long long)sd->cache_hot_time;
1887 }
1888
1889 /*
1890  * double_rq_lock - safely lock two runqueues
1891  *
1892  * Note this does not disable interrupts like task_rq_lock,
1893  * you need to do so manually before calling.
1894  */
1895 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
1896         __acquires(rq1->lock)
1897         __acquires(rq2->lock)
1898 {
1899         if (rq1 == rq2) {
1900                 spin_lock(&rq1->lock);
1901                 __acquire(rq2->lock);   /* Fake it out ;) */
1902         } else {
1903                 if (rq1 < rq2) {
1904                         spin_lock(&rq1->lock);
1905                         spin_lock(&rq2->lock);
1906                 } else {
1907                         spin_lock(&rq2->lock);
1908                         spin_lock(&rq1->lock);
1909                 }
1910         }
1911 }
1912
1913 /*
1914  * double_rq_unlock - safely unlock two runqueues
1915  *
1916  * Note this does not restore interrupts like task_rq_unlock,
1917  * you need to do so manually after calling.
1918  */
1919 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
1920         __releases(rq1->lock)
1921         __releases(rq2->lock)
1922 {
1923         spin_unlock(&rq1->lock);
1924         if (rq1 != rq2)
1925                 spin_unlock(&rq2->lock);
1926         else
1927                 __release(rq2->lock);
1928 }
1929
1930 /*
1931  * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1932  */
1933 static void double_lock_balance(struct rq *this_rq, struct rq *busiest)
1934         __releases(this_rq->lock)
1935         __acquires(busiest->lock)
1936         __acquires(this_rq->lock)
1937 {
1938         if (unlikely(!spin_trylock(&busiest->lock))) {
1939                 if (busiest < this_rq) {
1940                         spin_unlock(&this_rq->lock);
1941                         spin_lock(&busiest->lock);
1942                         spin_lock(&this_rq->lock);
1943                 } else
1944                         spin_lock(&busiest->lock);
1945         }
1946 }
1947
1948 /*
1949  * If dest_cpu is allowed for this process, migrate the task to it.
1950  * This is accomplished by forcing the cpu_allowed mask to only
1951  * allow dest_cpu, which will force the cpu onto dest_cpu.  Then
1952  * the cpu_allowed mask is restored.
1953  */
1954 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
1955 {
1956         struct migration_req req;
1957         unsigned long flags;
1958         struct rq *rq;
1959
1960         rq = task_rq_lock(p, &flags);
1961         if (!cpu_isset(dest_cpu, p->cpus_allowed)
1962             || unlikely(cpu_is_offline(dest_cpu)))
1963                 goto out;
1964
1965         /* force the process onto the specified CPU */
1966         if (migrate_task(p, dest_cpu, &req)) {
1967                 /* Need to wait for migration thread (might exit: take ref). */
1968                 struct task_struct *mt = rq->migration_thread;
1969
1970                 get_task_struct(mt);
1971                 task_rq_unlock(rq, &flags);
1972                 wake_up_process(mt);
1973                 put_task_struct(mt);
1974                 wait_for_completion(&req.done);
1975
1976                 return;
1977         }
1978 out:
1979         task_rq_unlock(rq, &flags);
1980 }
1981
1982 /*
1983  * sched_exec - execve() is a valuable balancing opportunity, because at
1984  * this point the task has the smallest effective memory and cache footprint.
1985  */
1986 void sched_exec(void)
1987 {
1988         int new_cpu, this_cpu = get_cpu();
1989         new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
1990         put_cpu();
1991         if (new_cpu != this_cpu)
1992                 sched_migrate_task(current, new_cpu);
1993 }
1994
1995 /*
1996  * pull_task - move a task from a remote runqueue to the local runqueue.
1997  * Both runqueues must be locked.
1998  */
1999 static void pull_task(struct rq *src_rq, struct prio_array *src_array,
2000                       struct task_struct *p, struct rq *this_rq,
2001                       struct prio_array *this_array, int this_cpu)
2002 {
2003         dequeue_task(p, src_array);
2004         dec_nr_running(p, src_rq);
2005         set_task_cpu(p, this_cpu);
2006         inc_nr_running(p, this_rq);
2007         enqueue_task(p, this_array);
2008         p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
2009                                 + this_rq->timestamp_last_tick;
2010         /*
2011          * Note that idle threads have a prio of MAX_PRIO, for this test
2012          * to be always true for them.
2013          */
2014         if (TASK_PREEMPTS_CURR(p, this_rq))
2015                 resched_task(this_rq->curr);
2016 }
2017
2018 /*
2019  * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2020  */
2021 static
2022 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
2023                      struct sched_domain *sd, enum idle_type idle,
2024                      int *all_pinned)
2025 {
2026         /*
2027          * We do not migrate tasks that are:
2028          * 1) running (obviously), or
2029          * 2) cannot be migrated to this CPU due to cpus_allowed, or
2030          * 3) are cache-hot on their current CPU.
2031          */
2032         if (!cpu_isset(this_cpu, p->cpus_allowed))
2033                 return 0;
2034         *all_pinned = 0;
2035
2036         if (task_running(rq, p))
2037                 return 0;
2038
2039         /*
2040          * Aggressive migration if:
2041          * 1) task is cache cold, or
2042          * 2) too many balance attempts have failed.
2043          */
2044
2045         if (sd->nr_balance_failed > sd->cache_nice_tries)
2046                 return 1;
2047
2048         if (task_hot(p, rq->timestamp_last_tick, sd))
2049                 return 0;
2050         return 1;
2051 }
2052
2053 #define rq_best_prio(rq) min((rq)->curr->prio, (rq)->best_expired_prio)
2054
2055 /*
2056  * move_tasks tries to move up to max_nr_move tasks and max_load_move weighted
2057  * load from busiest to this_rq, as part of a balancing operation within
2058  * "domain". Returns the number of tasks moved.
2059  *
2060  * Called with both runqueues locked.
2061  */
2062 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2063                       unsigned long max_nr_move, unsigned long max_load_move,
2064                       struct sched_domain *sd, enum idle_type idle,
2065                       int *all_pinned)
2066 {
2067         int idx, pulled = 0, pinned = 0, this_best_prio, best_prio,
2068             best_prio_seen, skip_for_load;
2069         struct prio_array *array, *dst_array;
2070         struct list_head *head, *curr;
2071         struct task_struct *tmp;
2072         long rem_load_move;
2073
2074         if (max_nr_move == 0 || max_load_move == 0)
2075                 goto out;
2076
2077         rem_load_move = max_load_move;
2078         pinned = 1;
2079         this_best_prio = rq_best_prio(this_rq);
2080         best_prio = rq_best_prio(busiest);
2081         /*
2082          * Enable handling of the case where there is more than one task
2083          * with the best priority.   If the current running task is one
2084          * of those with prio==best_prio we know it won't be moved
2085          * and therefore it's safe to override the skip (based on load) of
2086          * any task we find with that prio.
2087          */
2088         best_prio_seen = best_prio == busiest->curr->prio;
2089
2090         /*
2091          * We first consider expired tasks. Those will likely not be
2092          * executed in the near future, and they are most likely to
2093          * be cache-cold, thus switching CPUs has the least effect
2094          * on them.
2095          */
2096         if (busiest->expired->nr_active) {
2097                 array = busiest->expired;
2098                 dst_array = this_rq->expired;
2099         } else {
2100                 array = busiest->active;
2101                 dst_array = this_rq->active;
2102         }
2103
2104 new_array:
2105         /* Start searching at priority 0: */
2106         idx = 0;
2107 skip_bitmap:
2108         if (!idx)
2109                 idx = sched_find_first_bit(array->bitmap);
2110         else
2111                 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
2112         if (idx >= MAX_PRIO) {
2113                 if (array == busiest->expired && busiest->active->nr_active) {
2114                         array = busiest->active;
2115                         dst_array = this_rq->active;
2116                         goto new_array;
2117                 }
2118                 goto out;
2119         }
2120
2121         head = array->queue + idx;
2122         curr = head->prev;
2123 skip_queue:
2124         tmp = list_entry(curr, struct task_struct, run_list);
2125
2126         curr = curr->prev;
2127
2128         /*
2129          * To help distribute high priority tasks accross CPUs we don't
2130          * skip a task if it will be the highest priority task (i.e. smallest
2131          * prio value) on its new queue regardless of its load weight
2132          */
2133         skip_for_load = tmp->load_weight > rem_load_move;
2134         if (skip_for_load && idx < this_best_prio)
2135                 skip_for_load = !best_prio_seen && idx == best_prio;
2136         if (skip_for_load ||
2137             !can_migrate_task(tmp, busiest, this_cpu, sd, idle, &pinned)) {
2138
2139                 best_prio_seen |= idx == best_prio;
2140                 if (curr != head)
2141                         goto skip_queue;
2142                 idx++;
2143                 goto skip_bitmap;
2144         }
2145
2146 #ifdef CONFIG_SCHEDSTATS
2147         if (task_hot(tmp, busiest->timestamp_last_tick, sd))
2148                 schedstat_inc(sd, lb_hot_gained[idle]);
2149 #endif
2150
2151         pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
2152         pulled++;
2153         rem_load_move -= tmp->load_weight;
2154
2155         /*
2156          * We only want to steal up to the prescribed number of tasks
2157          * and the prescribed amount of weighted load.
2158          */
2159         if (pulled < max_nr_move && rem_load_move > 0) {
2160                 if (idx < this_best_prio)
2161                         this_best_prio = idx;
2162                 if (curr != head)
2163                         goto skip_queue;
2164                 idx++;
2165                 goto skip_bitmap;
2166         }
2167 out:
2168         /*
2169          * Right now, this is the only place pull_task() is called,
2170          * so we can safely collect pull_task() stats here rather than
2171          * inside pull_task().
2172          */
2173         schedstat_add(sd, lb_gained[idle], pulled);
2174
2175         if (all_pinned)
2176                 *all_pinned = pinned;
2177         return pulled;
2178 }
2179
2180 /*
2181  * find_busiest_group finds and returns the busiest CPU group within the
2182  * domain. It calculates and returns the amount of weighted load which
2183  * should be moved to restore balance via the imbalance parameter.
2184  */
2185 static struct sched_group *
2186 find_busiest_group(struct sched_domain *sd, int this_cpu,
2187                    unsigned long *imbalance, enum idle_type idle, int *sd_idle)
2188 {
2189         struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2190         unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2191         unsigned long max_pull;
2192         unsigned long busiest_load_per_task, busiest_nr_running;
2193         unsigned long this_load_per_task, this_nr_running;
2194         int load_idx;
2195 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2196         int power_savings_balance = 1;
2197         unsigned long leader_nr_running = 0, min_load_per_task = 0;
2198         unsigned long min_nr_running = ULONG_MAX;
2199         struct sched_group *group_min = NULL, *group_leader = NULL;
2200 #endif
2201
2202         max_load = this_load = total_load = total_pwr = 0;
2203         busiest_load_per_task = busiest_nr_running = 0;
2204         this_load_per_task = this_nr_running = 0;
2205         if (idle == NOT_IDLE)
2206                 load_idx = sd->busy_idx;
2207         else if (idle == NEWLY_IDLE)
2208                 load_idx = sd->newidle_idx;
2209         else
2210                 load_idx = sd->idle_idx;
2211
2212         do {
2213                 unsigned long load, group_capacity;
2214                 int local_group;
2215                 int i;
2216                 unsigned long sum_nr_running, sum_weighted_load;
2217
2218                 local_group = cpu_isset(this_cpu, group->cpumask);
2219
2220                 /* Tally up the load of all CPUs in the group */
2221                 sum_weighted_load = sum_nr_running = avg_load = 0;
2222
2223                 for_each_cpu_mask(i, group->cpumask) {
2224                         struct rq *rq = cpu_rq(i);
2225
2226                         if (*sd_idle && !idle_cpu(i))
2227                                 *sd_idle = 0;
2228
2229                         /* Bias balancing toward cpus of our domain */
2230                         if (local_group)
2231                                 load = target_load(i, load_idx);
2232                         else
2233                                 load = source_load(i, load_idx);
2234
2235                         avg_load += load;
2236                         sum_nr_running += rq->nr_running;
2237                         sum_weighted_load += rq->raw_weighted_load;
2238                 }
2239
2240                 total_load += avg_load;
2241                 total_pwr += group->cpu_power;
2242
2243                 /* Adjust by relative CPU power of the group */
2244                 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
2245
2246                 group_capacity = group->cpu_power / SCHED_LOAD_SCALE;
2247
2248                 if (local_group) {
2249                         this_load = avg_load;
2250                         this = group;
2251                         this_nr_running = sum_nr_running;
2252                         this_load_per_task = sum_weighted_load;
2253                 } else if (avg_load > max_load &&
2254                            sum_nr_running > group_capacity) {
2255                         max_load = avg_load;
2256                         busiest = group;
2257                         busiest_nr_running = sum_nr_running;
2258                         busiest_load_per_task = sum_weighted_load;
2259                 }
2260
2261 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2262                 /*
2263                  * Busy processors will not participate in power savings
2264                  * balance.
2265                  */
2266                 if (idle == NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
2267                         goto group_next;
2268
2269                 /*
2270                  * If the local group is idle or completely loaded
2271                  * no need to do power savings balance at this domain
2272                  */
2273                 if (local_group && (this_nr_running >= group_capacity ||
2274                                     !this_nr_running))
2275                         power_savings_balance = 0;
2276
2277                 /*
2278                  * If a group is already running at full capacity or idle,
2279                  * don't include that group in power savings calculations
2280                  */
2281                 if (!power_savings_balance || sum_nr_running >= group_capacity
2282                     || !sum_nr_running)
2283                         goto group_next;
2284
2285                 /*
2286                  * Calculate the group which has the least non-idle load.
2287                  * This is the group from where we need to pick up the load
2288                  * for saving power
2289                  */
2290                 if ((sum_nr_running < min_nr_running) ||
2291                     (sum_nr_running == min_nr_running &&
2292                      first_cpu(group->cpumask) <
2293                      first_cpu(group_min->cpumask))) {
2294                         group_min = group;
2295                         min_nr_running = sum_nr_running;
2296                         min_load_per_task = sum_weighted_load /
2297                                                 sum_nr_running;
2298                 }
2299
2300                 /*
2301                  * Calculate the group which is almost near its
2302                  * capacity but still has some space to pick up some load
2303                  * from other group and save more power
2304                  */
2305                 if (sum_nr_running <= group_capacity - 1) {
2306                         if (sum_nr_running > leader_nr_running ||
2307                             (sum_nr_running == leader_nr_running &&
2308                              first_cpu(group->cpumask) >
2309                               first_cpu(group_leader->cpumask))) {
2310                                 group_leader = group;
2311                                 leader_nr_running = sum_nr_running;
2312                         }
2313                 }
2314 group_next:
2315 #endif
2316                 group = group->next;
2317         } while (group != sd->groups);
2318
2319         if (!busiest || this_load >= max_load || busiest_nr_running == 0)
2320                 goto out_balanced;
2321
2322         avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2323
2324         if (this_load >= avg_load ||
2325                         100*max_load <= sd->imbalance_pct*this_load)
2326                 goto out_balanced;
2327
2328         busiest_load_per_task /= busiest_nr_running;
2329         /*
2330          * We're trying to get all the cpus to the average_load, so we don't
2331          * want to push ourselves above the average load, nor do we wish to
2332          * reduce the max loaded cpu below the average load, as either of these
2333          * actions would just result in more rebalancing later, and ping-pong
2334          * tasks around. Thus we look for the minimum possible imbalance.
2335          * Negative imbalances (*we* are more loaded than anyone else) will
2336          * be counted as no imbalance for these purposes -- we can't fix that
2337          * by pulling tasks to us.  Be careful of negative numbers as they'll
2338          * appear as very large values with unsigned longs.
2339          */
2340         if (max_load <= busiest_load_per_task)
2341                 goto out_balanced;
2342
2343         /*
2344          * In the presence of smp nice balancing, certain scenarios can have
2345          * max load less than avg load(as we skip the groups at or below
2346          * its cpu_power, while calculating max_load..)
2347          */
2348         if (max_load < avg_load) {
2349                 *imbalance = 0;
2350                 goto small_imbalance;
2351         }
2352
2353         /* Don't want to pull so many tasks that a group would go idle */
2354         max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
2355
2356         /* How much load to actually move to equalise the imbalance */
2357         *imbalance = min(max_pull * busiest->cpu_power,
2358                                 (avg_load - this_load) * this->cpu_power)
2359                         / SCHED_LOAD_SCALE;
2360
2361         /*
2362          * if *imbalance is less than the average load per runnable task
2363          * there is no gaurantee that any tasks will be moved so we'll have
2364          * a think about bumping its value to force at least one task to be
2365          * moved
2366          */
2367         if (*imbalance < busiest_load_per_task) {
2368                 unsigned long tmp, pwr_now, pwr_move;
2369                 unsigned int imbn;
2370
2371 small_imbalance:
2372                 pwr_move = pwr_now = 0;
2373                 imbn = 2;
2374                 if (this_nr_running) {
2375                         this_load_per_task /= this_nr_running;
2376                         if (busiest_load_per_task > this_load_per_task)
2377                                 imbn = 1;
2378                 } else
2379                         this_load_per_task = SCHED_LOAD_SCALE;
2380
2381                 if (max_load - this_load >= busiest_load_per_task * imbn) {
2382                         *imbalance = busiest_load_per_task;
2383                         return busiest;
2384                 }
2385
2386                 /*
2387                  * OK, we don't have enough imbalance to justify moving tasks,
2388                  * however we may be able to increase total CPU power used by
2389                  * moving them.
2390                  */
2391
2392                 pwr_now += busiest->cpu_power *
2393                         min(busiest_load_per_task, max_load);
2394                 pwr_now += this->cpu_power *
2395                         min(this_load_per_task, this_load);
2396                 pwr_now /= SCHED_LOAD_SCALE;
2397
2398                 /* Amount of load we'd subtract */
2399                 tmp = busiest_load_per_task*SCHED_LOAD_SCALE/busiest->cpu_power;
2400                 if (max_load > tmp)
2401                         pwr_move += busiest->cpu_power *
2402                                 min(busiest_load_per_task, max_load - tmp);
2403
2404                 /* Amount of load we'd add */
2405                 if (max_load*busiest->cpu_power <
2406                                 busiest_load_per_task*SCHED_LOAD_SCALE)
2407                         tmp = max_load*busiest->cpu_power/this->cpu_power;
2408                 else
2409                         tmp = busiest_load_per_task*SCHED_LOAD_SCALE/this->cpu_power;
2410                 pwr_move += this->cpu_power*min(this_load_per_task, this_load + tmp);
2411                 pwr_move /= SCHED_LOAD_SCALE;
2412
2413                 /* Move if we gain throughput */
2414                 if (pwr_move <= pwr_now)
2415                         goto out_balanced;
2416
2417                 *imbalance = busiest_load_per_task;
2418         }
2419
2420         return busiest;
2421
2422 out_balanced:
2423 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2424         if (idle == NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
2425                 goto ret;
2426
2427         if (this == group_leader && group_leader != group_min) {
2428                 *imbalance = min_load_per_task;
2429                 return group_min;
2430         }
2431 ret:
2432 #endif
2433         *imbalance = 0;
2434         return NULL;
2435 }
2436
2437 /*
2438  * find_busiest_queue - find the busiest runqueue among the cpus in group.
2439  */
2440 static struct rq *
2441 find_busiest_queue(struct sched_group *group, enum idle_type idle,
2442                    unsigned long imbalance)
2443 {
2444         struct rq *busiest = NULL, *rq;
2445         unsigned long max_load = 0;
2446         int i;
2447
2448         for_each_cpu_mask(i, group->cpumask) {
2449                 rq = cpu_rq(i);
2450
2451                 if (rq->nr_running == 1 && rq->raw_weighted_load > imbalance)
2452                         continue;
2453
2454                 if (rq->raw_weighted_load > max_load) {
2455                         max_load = rq->raw_weighted_load;
2456                         busiest = rq;
2457                 }
2458         }
2459
2460         return busiest;
2461 }
2462
2463 /*
2464  * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2465  * so long as it is large enough.
2466  */
2467 #define MAX_PINNED_INTERVAL     512
2468
2469 static inline unsigned long minus_1_or_zero(unsigned long n)
2470 {
2471         return n > 0 ? n - 1 : 0;
2472 }
2473
2474 /*
2475  * Check this_cpu to ensure it is balanced within domain. Attempt to move
2476  * tasks if there is an imbalance.
2477  *
2478  * Called with this_rq unlocked.
2479  */
2480 static int load_balance(int this_cpu, struct rq *this_rq,
2481                         struct sched_domain *sd, enum idle_type idle)
2482 {
2483         int nr_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
2484         struct sched_group *group;
2485         unsigned long imbalance;
2486         struct rq *busiest;
2487
2488         if (idle != NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
2489             !sched_smt_power_savings)
2490                 sd_idle = 1;
2491
2492         schedstat_inc(sd, lb_cnt[idle]);
2493
2494         group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle);
2495         if (!group) {
2496                 schedstat_inc(sd, lb_nobusyg[idle]);
2497                 goto out_balanced;
2498         }
2499
2500         busiest = find_busiest_queue(group, idle, imbalance);
2501         if (!busiest) {
2502                 schedstat_inc(sd, lb_nobusyq[idle]);
2503                 goto out_balanced;
2504         }
2505
2506         BUG_ON(busiest == this_rq);
2507
2508         schedstat_add(sd, lb_imbalance[idle], imbalance);
2509
2510         nr_moved = 0;
2511         if (busiest->nr_running > 1) {
2512                 /*
2513                  * Attempt to move tasks. If find_busiest_group has found
2514                  * an imbalance but busiest->nr_running <= 1, the group is
2515                  * still unbalanced. nr_moved simply stays zero, so it is
2516                  * correctly treated as an imbalance.
2517                  */
2518                 double_rq_lock(this_rq, busiest);
2519                 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2520                                       minus_1_or_zero(busiest->nr_running),
2521                                       imbalance, sd, idle, &all_pinned);
2522                 double_rq_unlock(this_rq, busiest);
2523
2524                 /* All tasks on this runqueue were pinned by CPU affinity */
2525                 if (unlikely(all_pinned))
2526                         goto out_balanced;
2527         }
2528
2529         if (!nr_moved) {
2530                 schedstat_inc(sd, lb_failed[idle]);
2531                 sd->nr_balance_failed++;
2532
2533                 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2534
2535                         spin_lock(&busiest->lock);
2536
2537                         /* don't kick the migration_thread, if the curr
2538                          * task on busiest cpu can't be moved to this_cpu
2539                          */
2540                         if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
2541                                 spin_unlock(&busiest->lock);
2542                                 all_pinned = 1;
2543                                 goto out_one_pinned;
2544                         }
2545
2546                         if (!busiest->active_balance) {
2547                                 busiest->active_balance = 1;
2548                                 busiest->push_cpu = this_cpu;
2549                                 active_balance = 1;
2550                         }
2551                         spin_unlock(&busiest->lock);
2552                         if (active_balance)
2553                                 wake_up_process(busiest->migration_thread);
2554
2555                         /*
2556                          * We've kicked active balancing, reset the failure
2557                          * counter.
2558                          */
2559                         sd->nr_balance_failed = sd->cache_nice_tries+1;
2560                 }
2561         } else
2562                 sd->nr_balance_failed = 0;
2563
2564         if (likely(!active_balance)) {
2565                 /* We were unbalanced, so reset the balancing interval */
2566                 sd->balance_interval = sd->min_interval;
2567         } else {
2568                 /*
2569                  * If we've begun active balancing, start to back off. This
2570                  * case may not be covered by the all_pinned logic if there
2571                  * is only 1 task on the busy runqueue (because we don't call
2572                  * move_tasks).
2573                  */
2574                 if (sd->balance_interval < sd->max_interval)
2575                         sd->balance_interval *= 2;
2576         }
2577
2578         if (!nr_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2579             !sched_smt_power_savings)
2580                 return -1;
2581         return nr_moved;
2582
2583 out_balanced:
2584         schedstat_inc(sd, lb_balanced[idle]);
2585
2586         sd->nr_balance_failed = 0;
2587
2588 out_one_pinned:
2589         /* tune up the balancing interval */
2590         if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
2591                         (sd->balance_interval < sd->max_interval))
2592                 sd->balance_interval *= 2;
2593
2594         if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2595                         !sched_smt_power_savings)
2596                 return -1;
2597         return 0;
2598 }
2599
2600 /*
2601  * Check this_cpu to ensure it is balanced within domain. Attempt to move
2602  * tasks if there is an imbalance.
2603  *
2604  * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2605  * this_rq is locked.
2606  */
2607 static int
2608 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
2609 {
2610         struct sched_group *group;
2611         struct rq *busiest = NULL;
2612         unsigned long imbalance;
2613         int nr_moved = 0;
2614         int sd_idle = 0;
2615
2616         if (sd->flags & SD_SHARE_CPUPOWER && !sched_smt_power_savings)
2617                 sd_idle = 1;
2618
2619         schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2620         group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE, &sd_idle);
2621         if (!group) {
2622                 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2623                 goto out_balanced;
2624         }
2625
2626         busiest = find_busiest_queue(group, NEWLY_IDLE, imbalance);
2627         if (!busiest) {
2628                 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2629                 goto out_balanced;
2630         }
2631
2632         BUG_ON(busiest == this_rq);
2633
2634         schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2635
2636         nr_moved = 0;
2637         if (busiest->nr_running > 1) {
2638                 /* Attempt to move tasks */
2639                 double_lock_balance(this_rq, busiest);
2640                 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2641                                         minus_1_or_zero(busiest->nr_running),
2642                                         imbalance, sd, NEWLY_IDLE, NULL);
2643                 spin_unlock(&busiest->lock);
2644         }
2645
2646         if (!nr_moved) {
2647                 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2648                 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2649                         return -1;
2650         } else
2651                 sd->nr_balance_failed = 0;
2652
2653         return nr_moved;
2654
2655 out_balanced:
2656         schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
2657         if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2658                                         !sched_smt_power_savings)
2659                 return -1;
2660         sd->nr_balance_failed = 0;
2661
2662         return 0;
2663 }
2664
2665 /*
2666  * idle_balance is called by schedule() if this_cpu is about to become
2667  * idle. Attempts to pull tasks from other CPUs.
2668  */
2669 static void idle_balance(int this_cpu, struct rq *this_rq)
2670 {
2671         struct sched_domain *sd;
2672
2673         for_each_domain(this_cpu, sd) {
2674                 if (sd->flags & SD_BALANCE_NEWIDLE) {
2675                         /* If we've pulled tasks over stop searching: */
2676                         if (load_balance_newidle(this_cpu, this_rq, sd))
2677                                 break;
2678                 }
2679         }
2680 }
2681
2682 /*
2683  * active_load_balance is run by migration threads. It pushes running tasks
2684  * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2685  * running on each physical CPU where possible, and avoids physical /
2686  * logical imbalances.
2687  *
2688  * Called with busiest_rq locked.
2689  */
2690 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
2691 {
2692         int target_cpu = busiest_rq->push_cpu;
2693         struct sched_domain *sd;
2694         struct rq *target_rq;
2695
2696         /* Is there any task to move? */
2697         if (busiest_rq->nr_running <= 1)
2698                 return;
2699
2700         target_rq = cpu_rq(target_cpu);
2701
2702         /*
2703          * This condition is "impossible", if it occurs
2704          * we need to fix it.  Originally reported by
2705          * Bjorn Helgaas on a 128-cpu setup.
2706          */
2707         BUG_ON(busiest_rq == target_rq);
2708
2709         /* move a task from busiest_rq to target_rq */
2710         double_lock_balance(busiest_rq, target_rq);
2711
2712         /* Search for an sd spanning us and the target CPU. */
2713         for_each_domain(target_cpu, sd) {
2714                 if ((sd->flags & SD_LOAD_BALANCE) &&
2715                     cpu_isset(busiest_cpu, sd->span))
2716                                 break;
2717         }
2718
2719         if (likely(sd)) {
2720                 schedstat_inc(sd, alb_cnt);
2721
2722                 if (move_tasks(target_rq, target_cpu, busiest_rq, 1,
2723                                RTPRIO_TO_LOAD_WEIGHT(100), sd, SCHED_IDLE,
2724                                NULL))
2725                         schedstat_inc(sd, alb_pushed);
2726                 else
2727                         schedstat_inc(sd, alb_failed);
2728         }
2729         spin_unlock(&target_rq->lock);
2730 }
2731
2732 /*
2733  * rebalance_tick will get called every timer tick, on every CPU.
2734  *
2735  * It checks each scheduling domain to see if it is due to be balanced,
2736  * and initiates a balancing operation if so.
2737  *
2738  * Balancing parameters are set up in arch_init_sched_domains.
2739  */
2740
2741 /* Don't have all balancing operations going off at once: */
2742 static inline unsigned long cpu_offset(int cpu)
2743 {
2744         return jiffies + cpu * HZ / NR_CPUS;
2745 }
2746
2747 static void
2748 rebalance_tick(int this_cpu, struct rq *this_rq, enum idle_type idle)
2749 {
2750         unsigned long this_load, interval, j = cpu_offset(this_cpu);
2751         struct sched_domain *sd;
2752         int i, scale;
2753
2754         this_load = this_rq->raw_weighted_load;
2755
2756         /* Update our load: */
2757         for (i = 0, scale = 1; i < 3; i++, scale <<= 1) {
2758                 unsigned long old_load, new_load;
2759
2760                 old_load = this_rq->cpu_load[i];
2761                 new_load = this_load;
2762                 /*
2763                  * Round up the averaging division if load is increasing. This
2764                  * prevents us from getting stuck on 9 if the load is 10, for
2765                  * example.
2766                  */
2767                 if (new_load > old_load)
2768                         new_load += scale-1;
2769                 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) / scale;
2770         }
2771
2772         for_each_domain(this_cpu, sd) {
2773                 if (!(sd->flags & SD_LOAD_BALANCE))
2774                         continue;
2775
2776                 interval = sd->balance_interval;
2777                 if (idle != SCHED_IDLE)
2778                         interval *= sd->busy_factor;
2779
2780                 /* scale ms to jiffies */
2781                 interval = msecs_to_jiffies(interval);
2782                 if (unlikely(!interval))
2783                         interval = 1;
2784
2785                 if (j - sd->last_balance >= interval) {
2786                         if (load_balance(this_cpu, this_rq, sd, idle)) {
2787                                 /*
2788                                  * We've pulled tasks over so either we're no
2789                                  * longer idle, or one of our SMT siblings is
2790                                  * not idle.
2791                                  */
2792                                 idle = NOT_IDLE;
2793                         }
2794                         sd->last_balance += interval;
2795                 }
2796         }
2797 }
2798 #else
2799 /*
2800  * on UP we do not need to balance between CPUs:
2801  */
2802 static inline void rebalance_tick(int cpu, struct rq *rq, enum idle_type idle)
2803 {
2804 }
2805 static inline void idle_balance(int cpu, struct rq *rq)
2806 {
2807 }
2808 #endif
2809
2810 static inline int wake_priority_sleeper(struct rq *rq)
2811 {
2812         int ret = 0;
2813
2814 #ifdef CONFIG_SCHED_SMT
2815         spin_lock(&rq->lock);
2816         /*
2817          * If an SMT sibling task has been put to sleep for priority
2818          * reasons reschedule the idle task to see if it can now run.
2819          */
2820         if (rq->nr_running) {
2821                 resched_task(rq->idle);
2822                 ret = 1;
2823         }
2824         spin_unlock(&rq->lock);
2825 #endif
2826         return ret;
2827 }
2828
2829 DEFINE_PER_CPU(struct kernel_stat, kstat);
2830
2831 EXPORT_PER_CPU_SYMBOL(kstat);
2832
2833 /*
2834  * This is called on clock ticks and on context switches.
2835  * Bank in p->sched_time the ns elapsed since the last tick or switch.
2836  */
2837 static inline void
2838 update_cpu_clock(struct task_struct *p, struct rq *rq, unsigned long long now)
2839 {
2840         p->sched_time += now - max(p->timestamp, rq->timestamp_last_tick);
2841 }
2842
2843 /*
2844  * Return current->sched_time plus any more ns on the sched_clock
2845  * that have not yet been banked.
2846  */
2847 unsigned long long current_sched_time(const struct task_struct *p)
2848 {
2849         unsigned long long ns;
2850         unsigned long flags;
2851
2852         local_irq_save(flags);
2853         ns = max(p->timestamp, task_rq(p)->timestamp_last_tick);
2854         ns = p->sched_time + sched_clock() - ns;
2855         local_irq_restore(flags);
2856
2857         return ns;
2858 }
2859
2860 /*
2861  * We place interactive tasks back into the active array, if possible.
2862  *
2863  * To guarantee that this does not starve expired tasks we ignore the
2864  * interactivity of a task if the first expired task had to wait more
2865  * than a 'reasonable' amount of time. This deadline timeout is
2866  * load-dependent, as the frequency of array switched decreases with
2867  * increasing number of running tasks. We also ignore the interactivity
2868  * if a better static_prio task has expired:
2869  */
2870 static inline int expired_starving(struct rq *rq)
2871 {
2872         if (rq->curr->static_prio > rq->best_expired_prio)
2873                 return 1;
2874         if (!STARVATION_LIMIT || !rq->expired_timestamp)
2875                 return 0;
2876         if (jiffies - rq->expired_timestamp > STARVATION_LIMIT * rq->nr_running)
2877                 return 1;
2878         return 0;
2879 }
2880
2881 /*
2882  * Account user cpu time to a process.
2883  * @p: the process that the cpu time gets accounted to
2884  * @hardirq_offset: the offset to subtract from hardirq_count()
2885  * @cputime: the cpu time spent in user space since the last update
2886  */
2887 void account_user_time(struct task_struct *p, cputime_t cputime)
2888 {
2889         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2890         cputime64_t tmp;
2891
2892         p->utime = cputime_add(p->utime, cputime);
2893
2894         /* Add user time to cpustat. */
2895         tmp = cputime_to_cputime64(cputime);
2896         if (TASK_NICE(p) > 0)
2897                 cpustat->nice = cputime64_add(cpustat->nice, tmp);
2898         else
2899                 cpustat->user = cputime64_add(cpustat->user, tmp);
2900 }
2901
2902 /*
2903  * Account system cpu time to a process.
2904  * @p: the process that the cpu time gets accounted to
2905  * @hardirq_offset: the offset to subtract from hardirq_count()
2906  * @cputime: the cpu time spent in kernel space since the last update
2907  */
2908 void account_system_time(struct task_struct *p, int hardirq_offset,
2909                          cputime_t cputime)
2910 {
2911         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2912         struct rq *rq = this_rq();
2913         cputime64_t tmp;
2914
2915         p->stime = cputime_add(p->stime, cputime);
2916
2917         /* Add system time to cpustat. */
2918         tmp = cputime_to_cputime64(cputime);
2919         if (hardirq_count() - hardirq_offset)
2920                 cpustat->irq = cputime64_add(cpustat->irq, tmp);
2921         else if (softirq_count())
2922                 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
2923         else if (p != rq->idle)
2924                 cpustat->system = cputime64_add(cpustat->system, tmp);
2925         else if (atomic_read(&rq->nr_iowait) > 0)
2926                 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2927         else
2928                 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2929         /* Account for system time used */
2930         acct_update_integrals(p);
2931 }
2932
2933 /*
2934  * Account for involuntary wait time.
2935  * @p: the process from which the cpu time has been stolen
2936  * @steal: the cpu time spent in involuntary wait
2937  */
2938 void account_steal_time(struct task_struct *p, cputime_t steal)
2939 {
2940         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2941         cputime64_t tmp = cputime_to_cputime64(steal);
2942         struct rq *rq = this_rq();
2943
2944         if (p == rq->idle) {
2945                 p->stime = cputime_add(p->stime, steal);
2946                 if (atomic_read(&rq->nr_iowait) > 0)
2947                         cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2948                 else
2949                         cpustat->idle = cputime64_add(cpustat->idle, tmp);
2950         } else
2951                 cpustat->steal = cputime64_add(cpustat->steal, tmp);
2952 }
2953
2954 /*
2955  * This function gets called by the timer code, with HZ frequency.
2956  * We call it with interrupts disabled.
2957  *
2958  * It also gets called by the fork code, when changing the parent's
2959  * timeslices.
2960  */
2961 void scheduler_tick(void)
2962 {
2963         unsigned long long now = sched_clock();
2964         struct task_struct *p = current;
2965         int cpu = smp_processor_id();
2966         struct rq *rq = cpu_rq(cpu);
2967
2968         update_cpu_clock(p, rq, now);
2969
2970         rq->timestamp_last_tick = now;
2971
2972         if (p == rq->idle) {
2973                 if (wake_priority_sleeper(rq))
2974                         goto out;
2975                 rebalance_tick(cpu, rq, SCHED_IDLE);
2976                 return;
2977         }
2978
2979         /* Task might have expired already, but not scheduled off yet */
2980         if (p->array != rq->active) {
2981                 set_tsk_need_resched(p);
2982                 goto out;
2983         }
2984         spin_lock(&rq->lock);
2985         /*
2986          * The task was running during this tick - update the
2987          * time slice counter. Note: we do not update a thread's
2988          * priority until it either goes to sleep or uses up its
2989          * timeslice. This makes it possible for interactive tasks
2990          * to use up their timeslices at their highest priority levels.
2991          */
2992         if (rt_task(p)) {
2993                 /*
2994                  * RR tasks need a special form of timeslice management.
2995                  * FIFO tasks have no timeslices.
2996                  */
2997                 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2998                         p->time_slice = task_timeslice(p);
2999                         p->first_time_slice = 0;
3000                         set_tsk_need_resched(p);
3001
3002                         /* put it at the end of the queue: */
3003                         requeue_task(p, rq->active);
3004                 }
3005                 goto out_unlock;
3006         }
3007         if (!--p->time_slice) {
3008                 dequeue_task(p, rq->active);
3009                 set_tsk_need_resched(p);
3010                 p->prio = effective_prio(p);
3011                 p->time_slice = task_timeslice(p);
3012                 p->first_time_slice = 0;
3013
3014                 if (!rq->expired_timestamp)
3015                         rq->expired_timestamp = jiffies;
3016                 if (!TASK_INTERACTIVE(p) || expired_starving(rq)) {
3017                         enqueue_task(p, rq->expired);
3018                         if (p->static_prio < rq->best_expired_prio)
3019                                 rq->best_expired_prio = p->static_prio;
3020                 } else
3021                         enqueue_task(p, rq->active);
3022         } else {
3023                 /*
3024                  * Prevent a too long timeslice allowing a task to monopolize
3025                  * the CPU. We do this by splitting up the timeslice into
3026                  * smaller pieces.
3027                  *
3028                  * Note: this does not mean the task's timeslices expire or
3029                  * get lost in any way, they just might be preempted by
3030                  * another task of equal priority. (one with higher
3031                  * priority would have preempted this task already.) We
3032                  * requeue this task to the end of the list on this priority
3033                  * level, which is in essence a round-robin of tasks with
3034                  * equal priority.
3035                  *
3036                  * This only applies to tasks in the interactive
3037                  * delta range with at least TIMESLICE_GRANULARITY to requeue.
3038                  */
3039                 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
3040                         p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
3041                         (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
3042                         (p->array == rq->active)) {
3043
3044                         requeue_task(p, rq->active);
3045                         set_tsk_need_resched(p);
3046                 }
3047         }
3048 out_unlock:
3049         spin_unlock(&rq->lock);
3050 out:
3051         rebalance_tick(cpu, rq, NOT_IDLE);
3052 }
3053
3054 #ifdef CONFIG_SCHED_SMT
3055 static inline void wakeup_busy_runqueue(struct rq *rq)
3056 {
3057         /* If an SMT runqueue is sleeping due to priority reasons wake it up */
3058         if (rq->curr == rq->idle && rq->nr_running)
3059                 resched_task(rq->idle);
3060 }
3061
3062 /*
3063  * Called with interrupt disabled and this_rq's runqueue locked.
3064  */
3065 static void wake_sleeping_dependent(int this_cpu)
3066 {
3067         struct sched_domain *tmp, *sd = NULL;
3068         int i;
3069
3070         for_each_domain(this_cpu, tmp) {
3071                 if (tmp->flags & SD_SHARE_CPUPOWER) {
3072                         sd = tmp;
3073                         break;
3074                 }
3075         }
3076
3077         if (!sd)
3078                 return;
3079
3080         for_each_cpu_mask(i, sd->span) {
3081                 struct rq *smt_rq = cpu_rq(i);
3082
3083                 if (i == this_cpu)
3084                         continue;
3085                 if (unlikely(!spin_trylock(&smt_rq->lock)))
3086                         continue;
3087
3088                 wakeup_busy_runqueue(smt_rq);
3089                 spin_unlock(&smt_rq->lock);
3090         }
3091 }
3092
3093 /*
3094  * number of 'lost' timeslices this task wont be able to fully
3095  * utilize, if another task runs on a sibling. This models the
3096  * slowdown effect of other tasks running on siblings:
3097  */
3098 static inline unsigned long
3099 smt_slice(struct task_struct *p, struct sched_domain *sd)
3100 {
3101         return p->time_slice * (100 - sd->per_cpu_gain) / 100;
3102 }
3103
3104 /*
3105  * To minimise lock contention and not have to drop this_rq's runlock we only
3106  * trylock the sibling runqueues and bypass those runqueues if we fail to
3107  * acquire their lock. As we only trylock the normal locking order does not
3108  * need to be obeyed.
3109  */
3110 static int
3111 dependent_sleeper(int this_cpu, struct rq *this_rq, struct task_struct *p)
3112 {
3113         struct sched_domain *tmp, *sd = NULL;
3114         int ret = 0, i;
3115
3116         /* kernel/rt threads do not participate in dependent sleeping */
3117         if (!p->mm || rt_task(p))
3118                 return 0;
3119
3120         for_each_domain(this_cpu, tmp) {
3121                 if (tmp->flags & SD_SHARE_CPUPOWER) {
3122                         sd = tmp;
3123                         break;
3124                 }
3125         }
3126
3127         if (!sd)
3128                 return 0;
3129
3130         for_each_cpu_mask(i, sd->span) {
3131                 struct task_struct *smt_curr;
3132                 struct rq *smt_rq;
3133
3134                 if (i == this_cpu)
3135                         continue;
3136
3137                 smt_rq = cpu_rq(i);
3138                 if (unlikely(!spin_trylock(&smt_rq->lock)))
3139                         continue;
3140
3141                 smt_curr = smt_rq->curr;
3142
3143                 if (!smt_curr->mm)
3144                         goto unlock;
3145
3146                 /*
3147                  * If a user task with lower static priority than the
3148                  * running task on the SMT sibling is trying to schedule,
3149                  * delay it till there is proportionately less timeslice
3150                  * left of the sibling task to prevent a lower priority
3151                  * task from using an unfair proportion of the
3152                  * physical cpu's resources. -ck
3153                  */
3154                 if (rt_task(smt_curr)) {
3155                         /*
3156                          * With real time tasks we run non-rt tasks only
3157                          * per_cpu_gain% of the time.
3158                          */
3159                         if ((jiffies % DEF_TIMESLICE) >
3160                                 (sd->per_cpu_gain * DEF_TIMESLICE / 100))
3161                                         ret = 1;
3162                 } else {
3163                         if (smt_curr->static_prio < p->static_prio &&
3164                                 !TASK_PREEMPTS_CURR(p, smt_rq) &&
3165                                 smt_slice(smt_curr, sd) > task_timeslice(p))
3166                                         ret = 1;
3167                 }
3168 unlock:
3169                 spin_unlock(&smt_rq->lock);
3170         }
3171         return ret;
3172 }
3173 #else
3174 static inline void wake_sleeping_dependent(int this_cpu)
3175 {
3176 }
3177 static inline int
3178 dependent_sleeper(int this_cpu, struct rq *this_rq, struct task_struct *p)
3179 {
3180         return 0;
3181 }
3182 #endif
3183
3184 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3185
3186 void fastcall add_preempt_count(int val)
3187 {
3188         /*
3189          * Underflow?
3190          */
3191         if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3192                 return;
3193         preempt_count() += val;
3194         /*
3195          * Spinlock count overflowing soon?
3196          */
3197         DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
3198 }
3199 EXPORT_SYMBOL(add_preempt_count);
3200
3201 void fastcall sub_preempt_count(int val)
3202 {
3203         /*
3204          * Underflow?
3205          */
3206         if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3207                 return;
3208         /*
3209          * Is the spinlock portion underflowing?
3210          */
3211         if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3212                         !(preempt_count() & PREEMPT_MASK)))
3213                 return;
3214
3215         preempt_count() -= val;
3216 }
3217 EXPORT_SYMBOL(sub_preempt_count);
3218
3219 #endif
3220
3221 static inline int interactive_sleep(enum sleep_type sleep_type)
3222 {
3223         return (sleep_type == SLEEP_INTERACTIVE ||
3224                 sleep_type == SLEEP_INTERRUPTED);
3225 }
3226
3227 /*
3228  * schedule() is the main scheduler function.
3229  */
3230 asmlinkage void __sched schedule(void)
3231 {
3232         struct task_struct *prev, *next;
3233         struct prio_array *array;
3234         struct list_head *queue;
3235         unsigned long long now;
3236         unsigned long run_time;
3237         int cpu, idx, new_prio;
3238         long *switch_count;
3239         struct rq *rq;
3240
3241         /*
3242          * Test if we are atomic.  Since do_exit() needs to call into
3243          * schedule() atomically, we ignore that path for now.
3244          * Otherwise, whine if we are scheduling when we should not be.
3245          */
3246         if (unlikely(in_atomic() && !current->exit_state)) {
3247                 printk(KERN_ERR "BUG: scheduling while atomic: "
3248                         "%s/0x%08x/%d\n",
3249                         current->comm, preempt_count(), current->pid);
3250                 dump_stack();
3251         }
3252         profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3253
3254 need_resched:
3255         preempt_disable();
3256         prev = current;
3257         release_kernel_lock(prev);
3258 need_resched_nonpreemptible:
3259         rq = this_rq();
3260
3261         /*
3262          * The idle thread is not allowed to schedule!
3263          * Remove this check after it has been exercised a bit.
3264          */
3265         if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
3266                 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
3267                 dump_stack();
3268         }
3269
3270         schedstat_inc(rq, sched_cnt);
3271         now = sched_clock();
3272         if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
3273                 run_time = now - prev->timestamp;
3274                 if (unlikely((long long)(now - prev->timestamp) < 0))
3275                         run_time = 0;
3276         } else
3277                 run_time = NS_MAX_SLEEP_AVG;
3278
3279         /*
3280          * Tasks charged proportionately less run_time at high sleep_avg to
3281          * delay them losing their interactive status
3282          */
3283         run_time /= (CURRENT_BONUS(prev) ? : 1);
3284
3285         spin_lock_irq(&rq->lock);
3286
3287         if (unlikely(prev->flags & PF_DEAD))
3288                 prev->state = EXIT_DEAD;
3289
3290         switch_count = &prev->nivcsw;
3291         if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3292                 switch_count = &prev->nvcsw;
3293                 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
3294                                 unlikely(signal_pending(prev))))
3295                         prev->state = TASK_RUNNING;
3296                 else {
3297                         if (prev->state == TASK_UNINTERRUPTIBLE)
3298                                 rq->nr_uninterruptible++;
3299                         deactivate_task(prev, rq);
3300                 }
3301         }
3302
3303         cpu = smp_processor_id();
3304         if (unlikely(!rq->nr_running)) {
3305                 idle_balance(cpu, rq);
3306                 if (!rq->nr_running) {
3307                         next = rq->idle;
3308                         rq->expired_timestamp = 0;
3309                         wake_sleeping_dependent(cpu);
3310                         goto switch_tasks;
3311                 }
3312         }
3313
3314         array = rq->active;
3315         if (unlikely(!array->nr_active)) {
3316                 /*
3317                  * Switch the active and expired arrays.
3318                  */
3319                 schedstat_inc(rq, sched_switch);
3320                 rq->active = rq->expired;
3321                 rq->expired = array;
3322                 array = rq->active;
3323                 rq->expired_timestamp = 0;
3324                 rq->best_expired_prio = MAX_PRIO;
3325         }
3326
3327         idx = sched_find_first_bit(array->bitmap);
3328         queue = array->queue + idx;
3329         next = list_entry(queue->next, struct task_struct, run_list);
3330
3331         if (!rt_task(next) && interactive_sleep(next->sleep_type)) {
3332                 unsigned long long delta = now - next->timestamp;
3333                 if (unlikely((long long)(now - next->timestamp) < 0))
3334                         delta = 0;
3335
3336                 if (next->sleep_type == SLEEP_INTERACTIVE)
3337                         delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
3338
3339                 array = next->array;
3340                 new_prio = recalc_task_prio(next, next->timestamp + delta);
3341
3342                 if (unlikely(next->prio != new_prio)) {
3343                         dequeue_task(next, array);
3344                         next->prio = new_prio;
3345                         enqueue_task(next, array);
3346                 }
3347         }
3348         next->sleep_type = SLEEP_NORMAL;
3349         if (dependent_sleeper(cpu, rq, next))
3350                 next = rq->idle;
3351 switch_tasks:
3352         if (next == rq->idle)
3353                 schedstat_inc(rq, sched_goidle);
3354         prefetch(next);
3355         prefetch_stack(next);
3356         clear_tsk_need_resched(prev);
3357         rcu_qsctr_inc(task_cpu(prev));
3358
3359         update_cpu_clock(prev, rq, now);
3360
3361         prev->sleep_avg -= run_time;
3362         if ((long)prev->sleep_avg <= 0)
3363                 prev->sleep_avg = 0;
3364         prev->timestamp = prev->last_ran = now;
3365
3366         sched_info_switch(prev, next);
3367         if (likely(prev != next)) {
3368                 next->timestamp = now;
3369                 rq->nr_switches++;
3370                 rq->curr = next;
3371                 ++*switch_count;
3372
3373                 prepare_task_switch(rq, next);
3374                 prev = context_switch(rq, prev, next);
3375                 barrier();
3376                 /*
3377                  * this_rq must be evaluated again because prev may have moved
3378                  * CPUs since it called schedule(), thus the 'rq' on its stack
3379                  * frame will be invalid.
3380                  */
3381                 finish_task_switch(this_rq(), prev);
3382         } else
3383                 spin_unlock_irq(&rq->lock);
3384
3385         prev = current;
3386         if (unlikely(reacquire_kernel_lock(prev) < 0))
3387                 goto need_resched_nonpreemptible;
3388         preempt_enable_no_resched();
3389         if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3390                 goto need_resched;
3391 }
3392 EXPORT_SYMBOL(schedule);
3393
3394 #ifdef CONFIG_PREEMPT
3395 /*
3396  * this is the entry point to schedule() from in-kernel preemption
3397  * off of preempt_enable.  Kernel preemptions off return from interrupt
3398  * occur there and call schedule directly.
3399  */
3400 asmlinkage void __sched preempt_schedule(void)
3401 {
3402         struct thread_info *ti = current_thread_info();
3403 #ifdef CONFIG_PREEMPT_BKL
3404         struct task_struct *task = current;
3405         int saved_lock_depth;
3406 #endif
3407         /*
3408          * If there is a non-zero preempt_count or interrupts are disabled,
3409          * we do not want to preempt the current task.  Just return..
3410          */
3411         if (unlikely(ti->preempt_count || irqs_disabled()))
3412                 return;
3413
3414 need_resched:
3415         add_preempt_count(PREEMPT_ACTIVE);
3416         /*
3417          * We keep the big kernel semaphore locked, but we
3418          * clear ->lock_depth so that schedule() doesnt
3419          * auto-release the semaphore:
3420          */
3421 #ifdef CONFIG_PREEMPT_BKL
3422         saved_lock_depth = task->lock_depth;
3423         task->lock_depth = -1;
3424 #endif
3425         schedule();
3426 #ifdef CONFIG_PREEMPT_BKL
3427         task->lock_depth = saved_lock_depth;
3428 #endif
3429         sub_preempt_count(PREEMPT_ACTIVE);
3430
3431         /* we could miss a preemption opportunity between schedule and now */
3432         barrier();
3433         if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3434                 goto need_resched;
3435 }
3436 EXPORT_SYMBOL(preempt_schedule);
3437
3438 /*
3439  * this is the entry point to schedule() from kernel preemption
3440  * off of irq context.
3441  * Note, that this is called and return with irqs disabled. This will
3442  * protect us against recursive calling from irq.
3443  */
3444 asmlinkage void __sched preempt_schedule_irq(void)
3445 {
3446         struct thread_info *ti = current_thread_info();
3447 #ifdef CONFIG_PREEMPT_BKL
3448         struct task_struct *task = current;
3449         int saved_lock_depth;
3450 #endif
3451         /* Catch callers which need to be fixed */
3452         BUG_ON(ti->preempt_count || !irqs_disabled());
3453
3454 need_resched:
3455         add_preempt_count(PREEMPT_ACTIVE);
3456         /*
3457          * We keep the big kernel semaphore locked, but we
3458          * clear ->lock_depth so that schedule() doesnt
3459          * auto-release the semaphore:
3460          */
3461 #ifdef CONFIG_PREEMPT_BKL
3462         saved_lock_depth = task->lock_depth;
3463         task->lock_depth = -1;
3464 #endif
3465         local_irq_enable();
3466         schedule();
3467         local_irq_disable();
3468 #ifdef CONFIG_PREEMPT_BKL
3469         task->lock_depth = saved_lock_depth;
3470 #endif
3471         sub_preempt_count(PREEMPT_ACTIVE);
3472
3473         /* we could miss a preemption opportunity between schedule and now */
3474         barrier();
3475         if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3476                 goto need_resched;
3477 }
3478
3479 #endif /* CONFIG_PREEMPT */
3480
3481 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
3482                           void *key)
3483 {
3484         return try_to_wake_up(curr->private, mode, sync);
3485 }
3486 EXPORT_SYMBOL(default_wake_function);
3487
3488 /*
3489  * The core wakeup function.  Non-exclusive wakeups (nr_exclusive == 0) just
3490  * wake everything up.  If it's an exclusive wakeup (nr_exclusive == small +ve
3491  * number) then we wake all the non-exclusive tasks and one exclusive task.
3492  *
3493  * There are circumstances in which we can try to wake a task which has already
3494  * started to run but is not in state TASK_RUNNING.  try_to_wake_up() returns
3495  * zero in this (rare) case, and we handle it by continuing to scan the queue.
3496  */
3497 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3498                              int nr_exclusive, int sync, void *key)
3499 {
3500         struct list_head *tmp, *next;
3501
3502         list_for_each_safe(tmp, next, &q->task_list) {
3503                 wait_queue_t *curr = list_entry(tmp, wait_queue_t, task_list);
3504                 unsigned flags = curr->flags;
3505
3506                 if (curr->func(curr, mode, sync, key) &&
3507                                 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
3508                         break;
3509         }
3510 }
3511
3512 /**
3513  * __wake_up - wake up threads blocked on a waitqueue.
3514  * @q: the waitqueue
3515  * @mode: which threads
3516  * @nr_exclusive: how many wake-one or wake-many threads to wake up
3517  * @key: is directly passed to the wakeup function
3518  */
3519 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3520                         int nr_exclusive, void *key)
3521 {
3522         unsigned long flags;
3523
3524         spin_lock_irqsave(&q->lock, flags);
3525         __wake_up_common(q, mode, nr_exclusive, 0, key);
3526         spin_unlock_irqrestore(&q->lock, flags);
3527 }
3528 EXPORT_SYMBOL(__wake_up);
3529
3530 /*
3531  * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3532  */
3533 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3534 {
3535         __wake_up_common(q, mode, 1, 0, NULL);
3536 }
3537
3538 /**
3539  * __wake_up_sync - wake up threads blocked on a waitqueue.
3540  * @q: the waitqueue
3541  * @mode: which threads
3542  * @nr_exclusive: how many wake-one or wake-many threads to wake up
3543  *
3544  * The sync wakeup differs that the waker knows that it will schedule
3545  * away soon, so while the target thread will be woken up, it will not
3546  * be migrated to another CPU - ie. the two threads are 'synchronized'
3547  * with each other. This can prevent needless bouncing between CPUs.
3548  *
3549  * On UP it can prevent extra preemption.
3550  */
3551 void fastcall
3552 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3553 {
3554         unsigned long flags;
3555         int sync = 1;
3556
3557         if (unlikely(!q))
3558                 return;
3559
3560         if (unlikely(!nr_exclusive))
3561                 sync = 0;
3562
3563         spin_lock_irqsave(&q->lock, flags);
3564         __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3565         spin_unlock_irqrestore(&q->lock, flags);
3566 }
3567 EXPORT_SYMBOL_GPL(__wake_up_sync);      /* For internal use only */
3568
3569 void fastcall complete(struct completion *x)
3570 {
3571         unsigned long flags;
3572
3573         spin_lock_irqsave(&x->wait.lock, flags);
3574         x->done++;
3575         __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3576                          1, 0, NULL);
3577         spin_unlock_irqrestore(&x->wait.lock, flags);
3578 }
3579 EXPORT_SYMBOL(complete);
3580
3581 void fastcall complete_all(struct completion *x)
3582 {
3583         unsigned long flags;
3584
3585         spin_lock_irqsave(&x->wait.lock, flags);
3586         x->done += UINT_MAX/2;
3587         __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3588                          0, 0, NULL);
3589         spin_unlock_irqrestore(&x->wait.lock, flags);
3590 }
3591 EXPORT_SYMBOL(complete_all);
3592
3593 void fastcall __sched wait_for_completion(struct completion *x)
3594 {
3595         might_sleep();
3596
3597         spin_lock_irq(&x->wait.lock);
3598         if (!x->done) {
3599                 DECLARE_WAITQUEUE(wait, current);
3600
3601                 wait.flags |= WQ_FLAG_EXCLUSIVE;
3602                 __add_wait_queue_tail(&x->wait, &wait);
3603                 do {
3604                         __set_current_state(TASK_UNINTERRUPTIBLE);
3605                         spin_unlock_irq(&x->wait.lock);
3606                         schedule();
3607                         spin_lock_irq(&x->wait.lock);
3608                 } while (!x->done);
3609                 __remove_wait_queue(&x->wait, &wait);
3610         }
3611         x->done--;
3612         spin_unlock_irq(&x->wait.lock);
3613 }
3614 EXPORT_SYMBOL(wait_for_completion);
3615
3616 unsigned long fastcall __sched
3617 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3618 {
3619         might_sleep();
3620
3621         spin_lock_irq(&x->wait.lock);
3622         if (!x->done) {
3623                 DECLARE_WAITQUEUE(wait, current);
3624
3625                 wait.flags |= WQ_FLAG_EXCLUSIVE;
3626                 __add_wait_queue_tail(&x->wait, &wait);
3627                 do {
3628                         __set_current_state(TASK_UNINTERRUPTIBLE);
3629                         spin_unlock_irq(&x->wait.lock);
3630                         timeout = schedule_timeout(timeout);
3631                         spin_lock_irq(&x->wait.lock);
3632                         if (!timeout) {
3633                                 __remove_wait_queue(&x->wait, &wait);
3634                                 goto out;
3635                         }
3636                 } while (!x->done);
3637                 __remove_wait_queue(&x->wait, &wait);
3638         }
3639         x->done--;
3640 out:
3641         spin_unlock_irq(&x->wait.lock);
3642         return timeout;
3643 }
3644 EXPORT_SYMBOL(wait_for_completion_timeout);
3645
3646 int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3647 {
3648         int ret = 0;
3649
3650         might_sleep();
3651
3652         spin_lock_irq(&x->wait.lock);
3653         if (!x->done) {
3654                 DECLARE_WAITQUEUE(wait, current);
3655
3656                 wait.flags |= WQ_FLAG_EXCLUSIVE;
3657                 __add_wait_queue_tail(&x->wait, &wait);
3658                 do {
3659                         if (signal_pending(current)) {
3660                                 ret = -ERESTARTSYS;
3661                                 __remove_wait_queue(&x->wait, &wait);
3662                                 goto out;
3663                         }
3664                         __set_current_state(TASK_INTERRUPTIBLE);
3665                         spin_unlock_irq(&x->wait.lock);
3666                         schedule();
3667                         spin_lock_irq(&x->wait.lock);
3668                 } while (!x->done);
3669                 __remove_wait_queue(&x->wait, &wait);
3670         }
3671         x->done--;
3672 out:
3673         spin_unlock_irq(&x->wait.lock);
3674
3675         return ret;
3676 }
3677 EXPORT_SYMBOL(wait_for_completion_interruptible);
3678
3679 unsigned long fastcall __sched
3680 wait_for_completion_interruptible_timeout(struct completion *x,
3681                                           unsigned long timeout)
3682 {
3683         might_sleep();
3684
3685         spin_lock_irq(&x->wait.lock);
3686         if (!x->done) {
3687                 DECLARE_WAITQUEUE(wait, current);
3688
3689                 wait.flags |= WQ_FLAG_EXCLUSIVE;
3690                 __add_wait_queue_tail(&x->wait, &wait);
3691                 do {
3692                         if (signal_pending(current)) {
3693                                 timeout = -ERESTARTSYS;
3694                                 __remove_wait_queue(&x->wait, &wait);
3695                                 goto out;
3696                         }
3697                         __set_current_state(TASK_INTERRUPTIBLE);
3698                         spin_unlock_irq(&x->wait.lock);
3699                         timeout = schedule_timeout(timeout);
3700                         spin_lock_irq(&x->wait.lock);
3701                         if (!timeout) {
3702                                 __remove_wait_queue(&x->wait, &wait);
3703                                 goto out;
3704                         }
3705                 } while (!x->done);
3706                 __remove_wait_queue(&x->wait, &wait);
3707         }
3708         x->done--;
3709 out:
3710         spin_unlock_irq(&x->wait.lock);
3711         return timeout;
3712 }
3713 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3714
3715
3716 #define SLEEP_ON_VAR                                    \
3717         unsigned long flags;                            \
3718         wait_queue_t wait;                              \
3719         init_waitqueue_entry(&wait, current);
3720
3721 #define SLEEP_ON_HEAD                                   \
3722         spin_lock_irqsave(&q->lock,flags);              \
3723         __add_wait_queue(q, &wait);                     \
3724         spin_unlock(&q->lock);
3725
3726 #define SLEEP_ON_TAIL                                   \
3727         spin_lock_irq(&q->lock);                        \
3728         __remove_wait_queue(q, &wait);                  \
3729         spin_unlock_irqrestore(&q->lock, flags);
3730
3731 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3732 {
3733         SLEEP_ON_VAR
3734
3735         current->state = TASK_INTERRUPTIBLE;
3736
3737         SLEEP_ON_HEAD
3738         schedule();
3739         SLEEP_ON_TAIL
3740 }
3741 EXPORT_SYMBOL(interruptible_sleep_on);
3742
3743 long fastcall __sched
3744 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3745 {
3746         SLEEP_ON_VAR
3747
3748         current->state = TASK_INTERRUPTIBLE;
3749
3750         SLEEP_ON_HEAD
3751         timeout = schedule_timeout(timeout);
3752         SLEEP_ON_TAIL
3753
3754         return timeout;
3755 }
3756 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3757
3758 void fastcall __sched sleep_on(wait_queue_head_t *q)
3759 {
3760         SLEEP_ON_VAR
3761
3762         current->state = TASK_UNINTERRUPTIBLE;
3763
3764         SLEEP_ON_HEAD
3765         schedule();
3766         SLEEP_ON_TAIL
3767 }
3768 EXPORT_SYMBOL(sleep_on);
3769
3770 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3771 {
3772         SLEEP_ON_VAR
3773
3774         current->state = TASK_UNINTERRUPTIBLE;
3775
3776         SLEEP_ON_HEAD
3777         timeout = schedule_timeout(timeout);
3778         SLEEP_ON_TAIL
3779
3780         return timeout;
3781 }
3782
3783 EXPORT_SYMBOL(sleep_on_timeout);
3784
3785 #ifdef CONFIG_RT_MUTEXES
3786
3787 /*
3788  * rt_mutex_setprio - set the current priority of a task
3789  * @p: task
3790  * @prio: prio value (kernel-internal form)
3791  *
3792  * This function changes the 'effective' priority of a task. It does
3793  * not touch ->normal_prio like __setscheduler().
3794  *
3795  * Used by the rt_mutex code to implement priority inheritance logic.
3796  */
3797 void rt_mutex_setprio(struct task_struct *p, int prio)
3798 {
3799         struct prio_array *array;
3800         unsigned long flags;
3801         struct rq *rq;
3802         int oldprio;
3803
3804         BUG_ON(prio < 0 || prio > MAX_PRIO);
3805
3806         rq = task_rq_lock(p, &flags);
3807
3808         oldprio = p->prio;
3809         array = p->array;
3810         if (array)
3811                 dequeue_task(p, array);
3812         p->prio = prio;
3813
3814         if (array) {
3815                 /*
3816                  * If changing to an RT priority then queue it
3817                  * in the active array!
3818                  */
3819                 if (rt_task(p))
3820                         array = rq->active;
3821                 enqueue_task(p, array);
3822                 /*
3823                  * Reschedule if we are currently running on this runqueue and
3824                  * our priority decreased, or if we are not currently running on
3825                  * this runqueue and our priority is higher than the current's
3826                  */
3827                 if (task_running(rq, p)) {
3828                         if (p->prio > oldprio)
3829                                 resched_task(rq->curr);
3830                 } else if (TASK_PREEMPTS_CURR(p, rq))
3831                         resched_task(rq->curr);
3832         }
3833         task_rq_unlock(rq, &flags);
3834 }
3835
3836 #endif
3837
3838 void set_user_nice(struct task_struct *p, long nice)
3839 {
3840         struct prio_array *array;
3841         int old_prio, delta;
3842         unsigned long flags;
3843         struct rq *rq;
3844
3845         if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3846                 return;
3847         /*
3848          * We have to be careful, if called from sys_setpriority(),
3849          * the task might be in the middle of scheduling on another CPU.
3850          */
3851         rq = task_rq_lock(p, &flags);
3852         /*
3853          * The RT priorities are set via sched_setscheduler(), but we still
3854          * allow the 'normal' nice value to be set - but as expected
3855          * it wont have any effect on scheduling until the task is
3856          * not SCHED_NORMAL/SCHED_BATCH:
3857          */
3858         if (has_rt_policy(p)) {
3859                 p->static_prio = NICE_TO_PRIO(nice);
3860                 goto out_unlock;
3861         }
3862         array = p->array;
3863         if (array) {
3864                 dequeue_task(p, array);
3865                 dec_raw_weighted_load(rq, p);
3866         }
3867
3868         p->static_prio = NICE_TO_PRIO(nice);
3869         set_load_weight(p);
3870         old_prio = p->prio;
3871         p->prio = effective_prio(p);
3872         delta = p->prio - old_prio;
3873
3874         if (array) {
3875                 enqueue_task(p, array);
3876                 inc_raw_weighted_load(rq, p);
3877                 /*
3878                  * If the task increased its priority or is running and
3879                  * lowered its priority, then reschedule its CPU:
3880                  */
3881                 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3882                         resched_task(rq->curr);
3883         }
3884 out_unlock:
3885         task_rq_unlock(rq, &flags);
3886 }
3887 EXPORT_SYMBOL(set_user_nice);
3888
3889 /*
3890  * can_nice - check if a task can reduce its nice value
3891  * @p: task
3892  * @nice: nice value
3893  */
3894 int can_nice(const struct task_struct *p, const int nice)
3895 {
3896         /* convert nice value [19,-20] to rlimit style value [1,40] */
3897         int nice_rlim = 20 - nice;
3898
3899         return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
3900                 capable(CAP_SYS_NICE));
3901 }
3902
3903 #ifdef __ARCH_WANT_SYS_NICE
3904
3905 /*
3906  * sys_nice - change the priority of the current process.
3907  * @increment: priority increment
3908  *
3909  * sys_setpriority is a more generic, but much slower function that
3910  * does similar things.
3911  */
3912 asmlinkage long sys_nice(int increment)
3913 {
3914         long nice, retval;
3915
3916         /*
3917          * Setpriority might change our priority at the same moment.
3918          * We don't have to worry. Conceptually one call occurs first
3919          * and we have a single winner.
3920          */
3921         if (increment < -40)
3922                 increment = -40;
3923         if (increment > 40)
3924                 increment = 40;
3925
3926         nice = PRIO_TO_NICE(current->static_prio) + increment;
3927         if (nice < -20)
3928                 nice = -20;
3929         if (nice > 19)
3930                 nice = 19;
3931
3932         if (increment < 0 && !can_nice(current, nice))
3933                 return -EPERM;
3934
3935         retval = security_task_setnice(current, nice);
3936         if (retval)
3937                 return retval;
3938
3939         set_user_nice(current, nice);
3940         return 0;
3941 }
3942
3943 #endif
3944
3945 /**
3946  * task_prio - return the priority value of a given task.
3947  * @p: the task in question.
3948  *
3949  * This is the priority value as seen by users in /proc.
3950  * RT tasks are offset by -200. Normal tasks are centered
3951  * around 0, value goes from -16 to +15.
3952  */
3953 int task_prio(const struct task_struct *p)
3954 {
3955         return p->prio - MAX_RT_PRIO;
3956 }
3957
3958 /**
3959  * task_nice - return the nice value of a given task.
3960  * @p: the task in question.
3961  */
3962 int task_nice(const struct task_struct *p)
3963 {
3964         return TASK_NICE(p);
3965 }
3966 EXPORT_SYMBOL_GPL(task_nice);
3967
3968 /**
3969  * idle_cpu - is a given cpu idle currently?
3970  * @cpu: the processor in question.
3971  */
3972 int idle_cpu(int cpu)
3973 {
3974         return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3975 }
3976
3977 /**
3978  * idle_task - return the idle task for a given cpu.
3979  * @cpu: the processor in question.
3980  */
3981 struct task_struct *idle_task(int cpu)
3982 {
3983         return cpu_rq(cpu)->idle;
3984 }
3985
3986 /**
3987  * find_process_by_pid - find a process with a matching PID value.
3988  * @pid: the pid in question.
3989  */
3990 static inline struct task_struct *find_process_by_pid(pid_t pid)
3991 {
3992         return pid ? find_task_by_pid(pid) : current;
3993 }
3994
3995 /* Actually do priority change: must hold rq lock. */
3996 static void __setscheduler(struct task_struct *p, int policy, int prio)
3997 {
3998         BUG_ON(p->array);
3999
4000         p->policy = policy;
4001         p->rt_priority = prio;
4002         p->normal_prio = normal_prio(p);
4003         /* we are holding p->pi_lock already */
4004         p->prio = rt_mutex_getprio(p);
4005         /*
4006          * SCHED_BATCH tasks are treated as perpetual CPU hogs:
4007          */
4008         if (policy == SCHED_BATCH)
4009                 p->sleep_avg = 0;
4010         set_load_weight(p);
4011 }
4012
4013 /**
4014  * sched_setscheduler - change the scheduling policy and/or RT priority of
4015  * a thread.
4016  * @p: the task in question.
4017  * @policy: new policy.
4018  * @param: structure containing the new RT priority.
4019  */
4020 int sched_setscheduler(struct task_struct *p, int policy,
4021                        struct sched_param *param)
4022 {
4023         int retval, oldprio, oldpolicy = -1;
4024         struct prio_array *array;
4025         unsigned long flags;
4026         struct rq *rq;
4027
4028         /* may grab non-irq protected spin_locks */
4029         BUG_ON(in_interrupt());
4030 recheck:
4031         /* double check policy once rq lock held */
4032         if (policy < 0)
4033                 policy = oldpolicy = p->policy;
4034         else if (policy != SCHED_FIFO && policy != SCHED_RR &&
4035                         policy != SCHED_NORMAL && policy != SCHED_BATCH)
4036                 return -EINVAL;
4037         /*
4038          * Valid priorities for SCHED_FIFO and SCHED_RR are
4039          * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL and
4040          * SCHED_BATCH is 0.
4041          */
4042         if (param->sched_priority < 0 ||
4043             (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
4044             (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
4045                 return -EINVAL;
4046         if ((policy == SCHED_NORMAL || policy == SCHED_BATCH)
4047                                         != (param->sched_priority == 0))
4048                 return -EINVAL;
4049
4050         /*
4051          * Allow unprivileged RT tasks to decrease priority:
4052          */
4053         if (!capable(CAP_SYS_NICE)) {
4054                 /*
4055                  * can't change policy, except between SCHED_NORMAL
4056                  * and SCHED_BATCH:
4057                  */
4058                 if (((policy != SCHED_NORMAL && p->policy != SCHED_BATCH) &&
4059                         (policy != SCHED_BATCH && p->policy != SCHED_NORMAL)) &&
4060                                 !p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
4061                         return -EPERM;
4062                 /* can't increase priority */
4063                 if ((policy != SCHED_NORMAL && policy != SCHED_BATCH) &&
4064                     param->sched_priority > p->rt_priority &&
4065                     param->sched_priority >
4066                                 p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
4067                         return -EPERM;
4068                 /* can't change other user's priorities */
4069                 if ((current->euid != p->euid) &&
4070                     (current->euid != p->uid))
4071                         return -EPERM;
4072         }
4073
4074         retval = security_task_setscheduler(p, policy, param);
4075         if (retval)
4076                 return retval;
4077         /*
4078          * make sure no PI-waiters arrive (or leave) while we are
4079          * changing the priority of the task:
4080          */
4081         spin_lock_irqsave(&p->pi_lock, flags);
4082         /*
4083          * To be able to change p->policy safely, the apropriate
4084          * runqueue lock must be held.
4085          */
4086         rq = __task_rq_lock(p);
4087         /* recheck policy now with rq lock held */
4088         if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4089                 policy = oldpolicy = -1;
4090                 __task_rq_unlock(rq);
4091                 spin_unlock_irqrestore(&p->pi_lock, flags);
4092                 goto recheck;
4093         }
4094         array = p->array;
4095         if (array)
4096                 deactivate_task(p, rq);
4097         oldprio = p->prio;
4098         __setscheduler(p, policy, param->sched_priority);
4099         if (array) {
4100                 __activate_task(p, rq);
4101                 /*
4102                  * Reschedule if we are currently running on this runqueue and
4103                  * our priority decreased, or if we are not currently running on
4104                  * this runqueue and our priority is higher than the current's
4105                  */
4106                 if (task_running(rq, p)) {
4107                         if (p->prio > oldprio)
4108                                 resched_task(rq->curr);
4109                 } else if (TASK_PREEMPTS_CURR(p, rq))
4110                         resched_task(rq->curr);
4111         }
4112         __task_rq_unlock(rq);
4113         spin_unlock_irqrestore(&p->pi_lock, flags);
4114
4115         rt_mutex_adjust_pi(p);
4116
4117         return 0;
4118 }
4119 EXPORT_SYMBOL_GPL(sched_setscheduler);
4120
4121 static int
4122 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4123 {
4124         struct sched_param lparam;
4125         struct task_struct *p;
4126         int retval;
4127
4128         if (!param || pid < 0)
4129                 return -EINVAL;
4130         if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4131                 return -EFAULT;
4132         read_lock_irq(&tasklist_lock);
4133         p = find_process_by_pid(pid);
4134         if (!p) {
4135                 read_unlock_irq(&tasklist_lock);
4136                 return -ESRCH;
4137         }
4138         get_task_struct(p);
4139         read_unlock_irq(&tasklist_lock);
4140         retval = sched_setscheduler(p, policy, &lparam);
4141         put_task_struct(p);
4142
4143         return retval;
4144 }
4145
4146 /**
4147  * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4148  * @pid: the pid in question.
4149  * @policy: new policy.
4150  * @param: structure containing the new RT priority.
4151  */
4152 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
4153                                        struct sched_param __user *param)
4154 {
4155         /* negative values for policy are not valid */
4156         if (policy < 0)
4157                 return -EINVAL;
4158
4159         return do_sched_setscheduler(pid, policy, param);
4160 }
4161
4162 /**
4163  * sys_sched_setparam - set/change the RT priority of a thread
4164  * @pid: the pid in question.
4165  * @param: structure containing the new RT priority.
4166  */
4167 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
4168 {
4169         return do_sched_setscheduler(pid, -1, param);
4170 }
4171
4172 /**
4173  * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4174  * @pid: the pid in question.
4175  */
4176 asmlinkage long sys_sched_getscheduler(pid_t pid)
4177 {
4178         struct task_struct *p;
4179         int retval = -EINVAL;
4180
4181         if (pid < 0)
4182                 goto out_nounlock;
4183
4184         retval = -ESRCH;
4185         read_lock(&tasklist_lock);
4186         p = find_process_by_pid(pid);
4187         if (p) {
4188                 retval = security_task_getscheduler(p);
4189                 if (!retval)
4190                         retval = p->policy;
4191         }
4192         read_unlock(&tasklist_lock);
4193
4194 out_nounlock:
4195         return retval;
4196 }
4197
4198 /**
4199  * sys_sched_getscheduler - get the RT priority of a thread
4200  * @pid: the pid in question.
4201  * @param: structure containing the RT priority.
4202  */
4203 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
4204 {
4205         struct sched_param lp;
4206         struct task_struct *p;
4207         int retval = -EINVAL;
4208
4209         if (!param || pid < 0)
4210                 goto out_nounlock;
4211
4212         read_lock(&tasklist_lock);
4213         p = find_process_by_pid(pid);
4214         retval = -ESRCH;
4215         if (!p)
4216                 goto out_unlock;
4217
4218         retval = security_task_getscheduler(p);
4219         if (retval)
4220                 goto out_unlock;
4221
4222         lp.sched_priority = p->rt_priority;
4223         read_unlock(&tasklist_lock);
4224
4225         /*
4226          * This one might sleep, we cannot do it with a spinlock held ...
4227          */
4228         retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4229
4230 out_nounlock:
4231         return retval;
4232
4233 out_unlock:
4234         read_unlock(&tasklist_lock);
4235         return retval;
4236 }
4237
4238 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
4239 {
4240         cpumask_t cpus_allowed;
4241         struct task_struct *p;
4242         int retval;
4243
4244         lock_cpu_hotplug();
4245         read_lock(&tasklist_lock);
4246
4247         p = find_process_by_pid(pid);
4248         if (!p) {
4249                 read_unlock(&tasklist_lock);
4250                 unlock_cpu_hotplug();
4251                 return -ESRCH;
4252         }
4253
4254         /*
4255          * It is not safe to call set_cpus_allowed with the
4256          * tasklist_lock held.  We will bump the task_struct's
4257          * usage count and then drop tasklist_lock.
4258          */
4259         get_task_struct(p);
4260         read_unlock(&tasklist_lock);
4261
4262         retval = -EPERM;
4263         if ((current->euid != p->euid) && (current->euid != p->uid) &&
4264                         !capable(CAP_SYS_NICE))
4265                 goto out_unlock;
4266
4267         retval = security_task_setscheduler(p, 0, NULL);
4268         if (retval)
4269                 goto out_unlock;
4270
4271         cpus_allowed = cpuset_cpus_allowed(p);
4272         cpus_and(new_mask, new_mask, cpus_allowed);
4273         retval = set_cpus_allowed(p, new_mask);
4274
4275 out_unlock:
4276         put_task_struct(p);
4277         unlock_cpu_hotplug();
4278         return retval;
4279 }
4280
4281 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4282                              cpumask_t *new_mask)
4283 {
4284         if (len < sizeof(cpumask_t)) {
4285                 memset(new_mask, 0, sizeof(cpumask_t));
4286         } else if (len > sizeof(cpumask_t)) {
4287                 len = sizeof(cpumask_t);
4288         }
4289         return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4290 }
4291
4292 /**
4293  * sys_sched_setaffinity - set the cpu affinity of a process
4294  * @pid: pid of the process
4295  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4296  * @user_mask_ptr: user-space pointer to the new cpu mask
4297  */
4298 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
4299                                       unsigned long __user *user_mask_ptr)
4300 {
4301         cpumask_t new_mask;
4302         int retval;
4303
4304         retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
4305         if (retval)
4306                 return retval;
4307
4308         return sched_setaffinity(pid, new_mask);
4309 }
4310
4311 /*
4312  * Represents all cpu's present in the system
4313  * In systems capable of hotplug, this map could dynamically grow
4314  * as new cpu's are detected in the system via any platform specific
4315  * method, such as ACPI for e.g.
4316  */
4317
4318 cpumask_t cpu_present_map __read_mostly;
4319 EXPORT_SYMBOL(cpu_present_map);
4320
4321 #ifndef CONFIG_SMP
4322 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
4323 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
4324 #endif
4325
4326 long sched_getaffinity(pid_t pid, cpumask_t *mask)
4327 {
4328         struct task_struct *p;
4329         int retval;
4330
4331         lock_cpu_hotplug();
4332         read_lock(&tasklist_lock);
4333
4334         retval = -ESRCH;
4335         p = find_process_by_pid(pid);
4336         if (!p)
4337                 goto out_unlock;
4338
4339         retval = security_task_getscheduler(p);
4340         if (retval)
4341                 goto out_unlock;
4342
4343         cpus_and(*mask, p->cpus_allowed, cpu_online_map);
4344
4345 out_unlock:
4346         read_unlock(&tasklist_lock);
4347         unlock_cpu_hotplug();
4348         if (retval)
4349                 return retval;
4350
4351         return 0;
4352 }
4353
4354 /**
4355  * sys_sched_getaffinity - get the cpu affinity of a process
4356  * @pid: pid of the process
4357  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4358  * @user_mask_ptr: user-space pointer to hold the current cpu mask
4359  */
4360 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
4361                                       unsigned long __user *user_mask_ptr)
4362 {
4363         int ret;
4364         cpumask_t mask;
4365
4366         if (len < sizeof(cpumask_t))
4367                 return -EINVAL;
4368
4369         ret = sched_getaffinity(pid, &mask);
4370         if (ret < 0)
4371                 return ret;
4372
4373         if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
4374                 return -EFAULT;
4375
4376         return sizeof(cpumask_t);
4377 }
4378
4379 /**
4380  * sys_sched_yield - yield the current processor to other threads.
4381  *
4382  * this function yields the current CPU by moving the calling thread
4383  * to the expired array. If there are no other threads running on this
4384  * CPU then this function will return.
4385  */
4386 asmlinkage long sys_sched_yield(void)
4387 {
4388         struct rq *rq = this_rq_lock();
4389         struct prio_array *array = current->array, *target = rq->expired;
4390
4391         schedstat_inc(rq, yld_cnt);
4392         /*
4393          * We implement yielding by moving the task into the expired
4394          * queue.
4395          *
4396          * (special rule: RT tasks will just roundrobin in the active
4397          *  array.)
4398          */
4399         if (rt_task(current))
4400                 target = rq->active;
4401
4402         if (array->nr_active == 1) {
4403                 schedstat_inc(rq, yld_act_empty);
4404                 if (!rq->expired->nr_active)
4405                         schedstat_inc(rq, yld_both_empty);
4406         } else if (!rq->expired->nr_active)
4407                 schedstat_inc(rq, yld_exp_empty);
4408
4409         if (array != target) {
4410                 dequeue_task(current, array);
4411                 enqueue_task(current, target);
4412         } else
4413                 /*
4414                  * requeue_task is cheaper so perform that if possible.
4415                  */
4416                 requeue_task(current, array);
4417
4418         /*
4419          * Since we are going to call schedule() anyway, there's
4420          * no need to preempt or enable interrupts:
4421          */
4422         __release(rq->lock);
4423         spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
4424         _raw_spin_unlock(&rq->lock);
4425         preempt_enable_no_resched();
4426
4427         schedule();
4428
4429         return 0;
4430 }
4431
4432 static inline int __resched_legal(void)
4433 {
4434         if (unlikely(preempt_count()))
4435                 return 0;
4436         if (unlikely(system_state != SYSTEM_RUNNING))
4437                 return 0;
4438         return 1;
4439 }
4440
4441 static void __cond_resched(void)
4442 {
4443 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4444         __might_sleep(__FILE__, __LINE__);
4445 #endif
4446         /*
4447          * The BKS might be reacquired before we have dropped
4448          * PREEMPT_ACTIVE, which could trigger a second
4449          * cond_resched() call.
4450          */
4451         do {
4452                 add_preempt_count(PREEMPT_ACTIVE);
4453                 schedule();
4454                 sub_preempt_count(PREEMPT_ACTIVE);
4455         } while (need_resched());
4456 }
4457
4458 int __sched cond_resched(void)
4459 {
4460         if (need_resched() && __resched_legal()) {
4461                 __cond_resched();
4462                 return 1;
4463         }
4464         return 0;
4465 }
4466 EXPORT_SYMBOL(cond_resched);
4467
4468 /*
4469  * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4470  * call schedule, and on return reacquire the lock.
4471  *
4472  * This works OK both with and without CONFIG_PREEMPT.  We do strange low-level
4473  * operations here to prevent schedule() from being called twice (once via
4474  * spin_unlock(), once by hand).
4475  */
4476 int cond_resched_lock(spinlock_t *lock)
4477 {
4478         int ret = 0;
4479
4480         if (need_lockbreak(lock)) {
4481                 spin_unlock(lock);
4482                 cpu_relax();
4483                 ret = 1;
4484                 spin_lock(lock);
4485         }
4486         if (need_resched() && __resched_legal()) {
4487                 spin_release(&lock->dep_map, 1, _THIS_IP_);
4488                 _raw_spin_unlock(lock);
4489                 preempt_enable_no_resched();
4490                 __cond_resched();
4491                 ret = 1;
4492                 spin_lock(lock);
4493         }
4494         return ret;
4495 }
4496 EXPORT_SYMBOL(cond_resched_lock);
4497
4498 int __sched cond_resched_softirq(void)
4499 {
4500         BUG_ON(!in_softirq());
4501
4502         if (need_resched() && __resched_legal()) {
4503                 raw_local_irq_disable();
4504                 _local_bh_enable();
4505                 raw_local_irq_enable();
4506                 __cond_resched();
4507                 local_bh_disable();
4508                 return 1;
4509         }
4510         return 0;
4511 }
4512 EXPORT_SYMBOL(cond_resched_softirq);
4513
4514 /**
4515  * yield - yield the current processor to other threads.
4516  *
4517  * this is a shortcut for kernel-space yielding - it marks the
4518  * thread runnable and calls sys_sched_yield().
4519  */
4520 void __sched yield(void)
4521 {
4522         set_current_state(TASK_RUNNING);
4523         sys_sched_yield();
4524 }
4525 EXPORT_SYMBOL(yield);
4526
4527 /*
4528  * This task is about to go to sleep on IO.  Increment rq->nr_iowait so
4529  * that process accounting knows that this is a task in IO wait state.
4530  *
4531  * But don't do that if it is a deliberate, throttling IO wait (this task
4532  * has set its backing_dev_info: the queue against which it should throttle)
4533  */
4534 void __sched io_schedule(void)
4535 {
4536         struct rq *rq = &__raw_get_cpu_var(runqueues);
4537
4538         delayacct_blkio_start();
4539         atomic_inc(&rq->nr_iowait);
4540         schedule();
4541         atomic_dec(&rq->nr_iowait);
4542         delayacct_blkio_end();
4543 }
4544 EXPORT_SYMBOL(io_schedule);
4545
4546 long __sched io_schedule_timeout(long timeout)
4547 {
4548         struct rq *rq = &__raw_get_cpu_var(runqueues);
4549         long ret;
4550
4551         delayacct_blkio_start();
4552         atomic_inc(&rq->nr_iowait);
4553         ret = schedule_timeout(timeout);
4554         atomic_dec(&rq->nr_iowait);
4555         delayacct_blkio_end();
4556         return ret;
4557 }
4558
4559 /**
4560  * sys_sched_get_priority_max - return maximum RT priority.
4561  * @policy: scheduling class.
4562  *
4563  * this syscall returns the maximum rt_priority that can be used
4564  * by a given scheduling class.
4565  */
4566 asmlinkage long sys_sched_get_priority_max(int policy)
4567 {
4568         int ret = -EINVAL;
4569
4570         switch (policy) {
4571         case SCHED_FIFO:
4572         case SCHED_RR:
4573                 ret = MAX_USER_RT_PRIO-1;
4574                 break;
4575         case SCHED_NORMAL:
4576         case SCHED_BATCH:
4577                 ret = 0;
4578                 break;
4579         }
4580         return ret;
4581 }
4582
4583 /**
4584  * sys_sched_get_priority_min - return minimum RT priority.
4585  * @policy: scheduling class.
4586  *
4587  * this syscall returns the minimum rt_priority that can be used
4588  * by a given scheduling class.
4589  */
4590 asmlinkage long sys_sched_get_priority_min(int policy)
4591 {
4592         int ret = -EINVAL;
4593
4594         switch (policy) {
4595         case SCHED_FIFO:
4596         case SCHED_RR:
4597                 ret = 1;
4598                 break;
4599         case SCHED_NORMAL:
4600         case SCHED_BATCH:
4601                 ret = 0;
4602         }
4603         return ret;
4604 }
4605
4606 /**
4607  * sys_sched_rr_get_interval - return the default timeslice of a process.
4608  * @pid: pid of the process.
4609  * @interval: userspace pointer to the timeslice value.
4610  *
4611  * this syscall writes the default timeslice value of a given process
4612  * into the user-space timespec buffer. A value of '0' means infinity.
4613  */
4614 asmlinkage
4615 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4616 {
4617         struct task_struct *p;
4618         int retval = -EINVAL;
4619         struct timespec t;
4620
4621         if (pid < 0)
4622                 goto out_nounlock;
4623
4624         retval = -ESRCH;
4625         read_lock(&tasklist_lock);
4626         p = find_process_by_pid(pid);
4627         if (!p)
4628                 goto out_unlock;
4629
4630         retval = security_task_getscheduler(p);
4631         if (retval)
4632                 goto out_unlock;
4633
4634         jiffies_to_timespec(p->policy == SCHED_FIFO ?
4635                                 0 : task_timeslice(p), &t);
4636         read_unlock(&tasklist_lock);
4637         retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4638 out_nounlock:
4639         return retval;
4640 out_unlock:
4641         read_unlock(&tasklist_lock);
4642         return retval;
4643 }
4644
4645 static inline struct task_struct *eldest_child(struct task_struct *p)
4646 {
4647         if (list_empty(&p->children))
4648                 return NULL;
4649         return list_entry(p->children.next,struct task_struct,sibling);
4650 }
4651
4652 static inline struct task_struct *older_sibling(struct task_struct *p)
4653 {
4654         if (p->sibling.prev==&p->parent->children)
4655                 return NULL;
4656         return list_entry(p->sibling.prev,struct task_struct,sibling);
4657 }
4658
4659 static inline struct task_struct *younger_sibling(struct task_struct *p)
4660 {
4661         if (p->sibling.next==&p->parent->children)
4662                 return NULL;
4663         return list_entry(p->sibling.next,struct task_struct,sibling);
4664 }
4665
4666 static const char stat_nam[] = "RSDTtZX";
4667
4668 static void show_task(struct task_struct *p)
4669 {
4670         struct task_struct *relative;
4671         unsigned long free = 0;
4672         unsigned state;
4673
4674         state = p->state ? __ffs(p->state) + 1 : 0;
4675         printk("%-13.13s %c", p->comm,
4676                 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
4677 #if (BITS_PER_LONG == 32)
4678         if (state == TASK_RUNNING)
4679                 printk(" running ");
4680         else
4681                 printk(" %08lX ", thread_saved_pc(p));
4682 #else
4683         if (state == TASK_RUNNING)
4684                 printk("  running task   ");
4685         else
4686                 printk(" %016lx ", thread_saved_pc(p));
4687 #endif
4688 #ifdef CONFIG_DEBUG_STACK_USAGE
4689         {
4690                 unsigned long *n = end_of_stack(p);
4691                 while (!*n)
4692                         n++;
4693                 free = (unsigned long)n - (unsigned long)end_of_stack(p);
4694         }
4695 #endif
4696         printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
4697         if ((relative = eldest_child(p)))
4698                 printk("%5d ", relative->pid);
4699         else
4700                 printk("      ");
4701         if ((relative = younger_sibling(p)))
4702                 printk("%7d", relative->pid);
4703         else
4704                 printk("       ");
4705         if ((relative = older_sibling(p)))
4706                 printk(" %5d", relative->pid);
4707         else
4708                 printk("      ");
4709         if (!p->mm)
4710                 printk(" (L-TLB)\n");
4711         else
4712                 printk(" (NOTLB)\n");
4713
4714         if (state != TASK_RUNNING)
4715                 show_stack(p, NULL);
4716 }
4717
4718 void show_state(void)
4719 {
4720         struct task_struct *g, *p;
4721
4722 #if (BITS_PER_LONG == 32)
4723         printk("\n"
4724                "                                               sibling\n");
4725         printk("  task             PC      pid father child younger older\n");
4726 #else
4727         printk("\n"
4728                "                                                       sibling\n");
4729         printk("  task                 PC          pid father child younger older\n");
4730 #endif
4731         read_lock(&tasklist_lock);
4732         do_each_thread(g, p) {
4733                 /*
4734                  * reset the NMI-timeout, listing all files on a slow
4735                  * console might take alot of time:
4736                  */
4737                 touch_nmi_watchdog();
4738                 show_task(p);
4739         } while_each_thread(g, p);
4740
4741         read_unlock(&tasklist_lock);
4742         debug_show_all_locks();
4743 }
4744
4745 /**
4746  * init_idle - set up an idle thread for a given CPU
4747  * @idle: task in question
4748  * @cpu: cpu the idle task belongs to
4749  *
4750  * NOTE: this function does not set the idle thread's NEED_RESCHED
4751  * flag, to make booting more robust.
4752  */
4753 void __devinit init_idle(struct task_struct *idle, int cpu)
4754 {
4755         struct rq *rq = cpu_rq(cpu);
4756         unsigned long flags;
4757
4758         idle->timestamp = sched_clock();
4759         idle->sleep_avg = 0;
4760         idle->array = NULL;
4761         idle->prio = idle->normal_prio = MAX_PRIO;
4762         idle->state = TASK_RUNNING;
4763         idle->cpus_allowed = cpumask_of_cpu(cpu);
4764         set_task_cpu(idle, cpu);
4765
4766         spin_lock_irqsave(&rq->lock, flags);
4767         rq->curr = rq->idle = idle;
4768 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
4769         idle->oncpu = 1;
4770 #endif
4771         spin_unlock_irqrestore(&rq->lock, flags);
4772
4773         /* Set the preempt count _outside_ the spinlocks! */
4774 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4775         task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
4776 #else
4777         task_thread_info(idle)->preempt_count = 0;
4778 #endif
4779 }
4780
4781 /*
4782  * In a system that switches off the HZ timer nohz_cpu_mask
4783  * indicates which cpus entered this state. This is used
4784  * in the rcu update to wait only for active cpus. For system
4785  * which do not switch off the HZ timer nohz_cpu_mask should
4786  * always be CPU_MASK_NONE.
4787  */
4788 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4789
4790 #ifdef CONFIG_SMP
4791 /*
4792  * This is how migration works:
4793  *
4794  * 1) we queue a struct migration_req structure in the source CPU's
4795  *    runqueue and wake up that CPU's migration thread.
4796  * 2) we down() the locked semaphore => thread blocks.
4797  * 3) migration thread wakes up (implicitly it forces the migrated
4798  *    thread off the CPU)
4799  * 4) it gets the migration request and checks whether the migrated
4800  *    task is still in the wrong runqueue.
4801  * 5) if it's in the wrong runqueue then the migration thread removes
4802  *    it and puts it into the right queue.
4803  * 6) migration thread up()s the semaphore.
4804  * 7) we wake up and the migration is done.
4805  */
4806
4807 /*
4808  * Change a given task's CPU affinity. Migrate the thread to a
4809  * proper CPU and schedule it away if the CPU it's executing on
4810  * is removed from the allowed bitmask.
4811  *
4812  * NOTE: the caller must have a valid reference to the task, the
4813  * task must not exit() & deallocate itself prematurely.  The
4814  * call is not atomic; no spinlocks may be held.
4815  */
4816 int set_cpus_allowed(struct task_struct *p, cpumask_t new_mask)
4817 {
4818         struct migration_req req;
4819         unsigned long flags;
4820         struct rq *rq;
4821         int ret = 0;
4822
4823         rq = task_rq_lock(p, &flags);
4824         if (!cpus_intersects(new_mask, cpu_online_map)) {
4825                 ret = -EINVAL;
4826                 goto out;
4827         }
4828
4829         p->cpus_allowed = new_mask;
4830         /* Can the task run on the task's current CPU? If so, we're done */
4831         if (cpu_isset(task_cpu(p), new_mask))
4832                 goto out;
4833
4834         if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4835                 /* Need help from migration thread: drop lock and wait. */
4836                 task_rq_unlock(rq, &flags);
4837                 wake_up_process(rq->migration_thread);
4838                 wait_for_completion(&req.done);
4839                 tlb_migrate_finish(p->mm);
4840                 return 0;
4841         }
4842 out:
4843         task_rq_unlock(rq, &flags);
4844
4845         return ret;
4846 }
4847 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4848
4849 /*
4850  * Move (not current) task off this cpu, onto dest cpu.  We're doing
4851  * this because either it can't run here any more (set_cpus_allowed()
4852  * away from this CPU, or CPU going down), or because we're
4853  * attempting to rebalance this task on exec (sched_exec).
4854  *
4855  * So we race with normal scheduler movements, but that's OK, as long
4856  * as the task is no longer on this CPU.
4857  *
4858  * Returns non-zero if task was successfully migrated.
4859  */
4860 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4861 {
4862         struct rq *rq_dest, *rq_src;
4863         int ret = 0;
4864
4865         if (unlikely(cpu_is_offline(dest_cpu)))
4866                 return ret;
4867
4868         rq_src = cpu_rq(src_cpu);
4869         rq_dest = cpu_rq(dest_cpu);
4870
4871         double_rq_lock(rq_src, rq_dest);
4872         /* Already moved. */
4873         if (task_cpu(p) != src_cpu)
4874                 goto out;
4875         /* Affinity changed (again). */
4876         if (!cpu_isset(dest_cpu, p->cpus_allowed))
4877                 goto out;
4878
4879         set_task_cpu(p, dest_cpu);
4880         if (p->array) {
4881                 /*
4882                  * Sync timestamp with rq_dest's before activating.
4883                  * The same thing could be achieved by doing this step
4884                  * afterwards, and pretending it was a local activate.
4885                  * This way is cleaner and logically correct.
4886                  */
4887                 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4888                                 + rq_dest->timestamp_last_tick;
4889                 deactivate_task(p, rq_src);
4890                 __activate_task(p, rq_dest);
4891                 if (TASK_PREEMPTS_CURR(p, rq_dest))
4892                         resched_task(rq_dest->curr);
4893         }
4894         ret = 1;
4895 out:
4896         double_rq_unlock(rq_src, rq_dest);
4897         return ret;
4898 }
4899
4900 /*
4901  * migration_thread - this is a highprio system thread that performs
4902  * thread migration by bumping thread off CPU then 'pushing' onto
4903  * another runqueue.
4904  */
4905 static int migration_thread(void *data)
4906 {
4907         int cpu = (long)data;
4908         struct rq *rq;
4909
4910         rq = cpu_rq(cpu);
4911         BUG_ON(rq->migration_thread != current);
4912
4913         set_current_state(TASK_INTERRUPTIBLE);
4914         while (!kthread_should_stop()) {
4915                 struct migration_req *req;
4916                 struct list_head *head;
4917
4918                 try_to_freeze();
4919
4920                 spin_lock_irq(&rq->lock);
4921
4922                 if (cpu_is_offline(cpu)) {
4923                         spin_unlock_irq(&rq->lock);
4924                         goto wait_to_die;
4925                 }
4926
4927                 if (rq->active_balance) {
4928                         active_load_balance(rq, cpu);
4929                         rq->active_balance = 0;
4930                 }
4931
4932                 head = &rq->migration_queue;
4933
4934                 if (list_empty(head)) {
4935                         spin_unlock_irq(&rq->lock);
4936                         schedule();
4937                         set_current_state(TASK_INTERRUPTIBLE);
4938                         continue;
4939                 }
4940                 req = list_entry(head->next, struct migration_req, list);
4941                 list_del_init(head->next);
4942
4943                 spin_unlock(&rq->lock);
4944                 __migrate_task(req->task, cpu, req->dest_cpu);
4945                 local_irq_enable();
4946
4947                 complete(&req->done);
4948         }
4949         __set_current_state(TASK_RUNNING);
4950         return 0;
4951
4952 wait_to_die:
4953         /* Wait for kthread_stop */
4954         set_current_state(TASK_INTERRUPTIBLE);
4955         while (!kthread_should_stop()) {
4956                 schedule();
4957                 set_current_state(TASK_INTERRUPTIBLE);
4958         }
4959         __set_current_state(TASK_RUNNING);
4960         return 0;
4961 }
4962
4963 #ifdef CONFIG_HOTPLUG_CPU
4964 /* Figure out where task on dead CPU should go, use force if neccessary. */
4965 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
4966 {
4967         unsigned long flags;
4968         cpumask_t mask;
4969         struct rq *rq;
4970         int dest_cpu;
4971
4972 restart:
4973         /* On same node? */
4974         mask = node_to_cpumask(cpu_to_node(dead_cpu));
4975         cpus_and(mask, mask, p->cpus_allowed);
4976         dest_cpu = any_online_cpu(mask);
4977
4978         /* On any allowed CPU? */
4979         if (dest_cpu == NR_CPUS)
4980                 dest_cpu = any_online_cpu(p->cpus_allowed);
4981
4982         /* No more Mr. Nice Guy. */
4983         if (dest_cpu == NR_CPUS) {
4984                 rq = task_rq_lock(p, &flags);
4985                 cpus_setall(p->cpus_allowed);
4986                 dest_cpu = any_online_cpu(p->cpus_allowed);
4987                 task_rq_unlock(rq, &flags);
4988
4989                 /*
4990                  * Don't tell them about moving exiting tasks or
4991                  * kernel threads (both mm NULL), since they never
4992                  * leave kernel.
4993                  */
4994                 if (p->mm && printk_ratelimit())
4995                         printk(KERN_INFO "process %d (%s) no "
4996                                "longer affine to cpu%d\n",
4997                                p->pid, p->comm, dead_cpu);
4998         }
4999         if (!__migrate_task(p, dead_cpu, dest_cpu))
5000                 goto restart;
5001 }
5002
5003 /*
5004  * While a dead CPU has no uninterruptible tasks queued at this point,
5005  * it might still have a nonzero ->nr_uninterruptible counter, because
5006  * for performance reasons the counter is not stricly tracking tasks to
5007  * their home CPUs. So we just add the counter to another CPU's counter,
5008  * to keep the global sum constant after CPU-down:
5009  */
5010 static void migrate_nr_uninterruptible(struct rq *rq_src)
5011 {
5012         struct rq *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
5013         unsigned long flags;
5014
5015         local_irq_save(flags);
5016         double_rq_lock(rq_src, rq_dest);
5017         rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5018         rq_src->nr_uninterruptible = 0;
5019         double_rq_unlock(rq_src, rq_dest);
5020         local_irq_restore(flags);
5021 }
5022
5023 /* Run through task list and migrate tasks from the dead cpu. */
5024 static void migrate_live_tasks(int src_cpu)
5025 {
5026         struct task_struct *p, *t;
5027
5028         write_lock_irq(&tasklist_lock);
5029
5030         do_each_thread(t, p) {
5031                 if (p == current)
5032                         continue;
5033
5034                 if (task_cpu(p) == src_cpu)
5035                         move_task_off_dead_cpu(src_cpu, p);
5036         } while_each_thread(t, p);
5037
5038         write_unlock_irq(&tasklist_lock);
5039 }
5040
5041 /* Schedules idle task to be the next runnable task on current CPU.
5042  * It does so by boosting its priority to highest possible and adding it to
5043  * the _front_ of the runqueue. Used by CPU offline code.
5044  */
5045 void sched_idle_next(void)
5046 {
5047         int this_cpu = smp_processor_id();
5048         struct rq *rq = cpu_rq(this_cpu);
5049         struct task_struct *p = rq->idle;
5050         unsigned long flags;
5051
5052         /* cpu has to be offline */
5053         BUG_ON(cpu_online(this_cpu));
5054
5055         /*
5056          * Strictly not necessary since rest of the CPUs are stopped by now
5057          * and interrupts disabled on the current cpu.
5058          */
5059         spin_lock_irqsave(&rq->lock, flags);
5060
5061         __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
5062
5063         /* Add idle task to the _front_ of its priority queue: */
5064         __activate_idle_task(p, rq);
5065
5066         spin_unlock_irqrestore(&rq->lock, flags);
5067 }
5068
5069 /*
5070  * Ensures that the idle task is using init_mm right before its cpu goes
5071  * offline.
5072  */
5073 void idle_task_exit(void)
5074 {
5075         struct mm_struct *mm = current->active_mm;
5076
5077         BUG_ON(cpu_online(smp_processor_id()));
5078
5079         if (mm != &init_mm)
5080                 switch_mm(mm, &init_mm, current);
5081         mmdrop(mm);
5082 }
5083
5084 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
5085 {
5086         struct rq *rq = cpu_rq(dead_cpu);
5087
5088         /* Must be exiting, otherwise would be on tasklist. */
5089         BUG_ON(p->exit_state != EXIT_ZOMBIE && p->exit_state != EXIT_DEAD);
5090
5091         /* Cannot have done final schedule yet: would have vanished. */
5092         BUG_ON(p->flags & PF_DEAD);
5093
5094         get_task_struct(p);
5095
5096         /*
5097          * Drop lock around migration; if someone else moves it,
5098          * that's OK.  No task can be added to this CPU, so iteration is
5099          * fine.
5100          */
5101         spin_unlock_irq(&rq->lock);
5102         move_task_off_dead_cpu(dead_cpu, p);
5103         spin_lock_irq(&rq->lock);
5104
5105         put_task_struct(p);
5106 }
5107
5108 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5109 static void migrate_dead_tasks(unsigned int dead_cpu)
5110 {
5111         struct rq *rq = cpu_rq(dead_cpu);
5112         unsigned int arr, i;
5113
5114         for (arr = 0; arr < 2; arr++) {
5115                 for (i = 0; i < MAX_PRIO; i++) {
5116                         struct list_head *list = &rq->arrays[arr].queue[i];
5117
5118                         while (!list_empty(list))
5119                                 migrate_dead(dead_cpu, list_entry(list->next,
5120                                              struct task_struct, run_list));
5121                 }
5122         }
5123 }
5124 #endif /* CONFIG_HOTPLUG_CPU */
5125
5126 /*
5127  * migration_call - callback that gets triggered when a CPU is added.
5128  * Here we can start up the necessary migration thread for the new CPU.
5129  */
5130 static int __cpuinit
5131 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
5132 {
5133         struct task_struct *p;
5134         int cpu = (long)hcpu;
5135         unsigned long flags;
5136         struct rq *rq;
5137
5138         switch (action) {
5139         case CPU_UP_PREPARE:
5140                 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
5141                 if (IS_ERR(p))
5142                         return NOTIFY_BAD;
5143                 p->flags |= PF_NOFREEZE;
5144                 kthread_bind(p, cpu);
5145                 /* Must be high prio: stop_machine expects to yield to it. */
5146                 rq = task_rq_lock(p, &flags);
5147                 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
5148                 task_rq_unlock(rq, &flags);
5149                 cpu_rq(cpu)->migration_thread = p;
5150                 break;
5151
5152         case CPU_ONLINE:
5153                 /* Strictly unneccessary, as first user will wake it. */
5154                 wake_up_process(cpu_rq(cpu)->migration_thread);
5155                 break;
5156
5157 #ifdef CONFIG_HOTPLUG_CPU
5158         case CPU_UP_CANCELED:
5159                 if (!cpu_rq(cpu)->migration_thread)
5160                         break;
5161                 /* Unbind it from offline cpu so it can run.  Fall thru. */
5162                 kthread_bind(cpu_rq(cpu)->migration_thread,
5163                              any_online_cpu(cpu_online_map));
5164                 kthread_stop(cpu_rq(cpu)->migration_thread);
5165                 cpu_rq(cpu)->migration_thread = NULL;
5166                 break;
5167
5168         case CPU_DEAD:
5169                 migrate_live_tasks(cpu);
5170                 rq = cpu_rq(cpu);
5171                 kthread_stop(rq->migration_thread);
5172                 rq->migration_thread = NULL;
5173                 /* Idle task back to normal (off runqueue, low prio) */
5174                 rq = task_rq_lock(rq->idle, &flags);
5175                 deactivate_task(rq->idle, rq);
5176                 rq->idle->static_prio = MAX_PRIO;
5177                 __setscheduler(rq->idle, SCHED_NORMAL, 0);
5178                 migrate_dead_tasks(cpu);
5179                 task_rq_unlock(rq, &flags);
5180                 migrate_nr_uninterruptible(rq);
5181                 BUG_ON(rq->nr_running != 0);
5182
5183                 /* No need to migrate the tasks: it was best-effort if
5184                  * they didn't do lock_cpu_hotplug().  Just wake up
5185                  * the requestors. */
5186                 spin_lock_irq(&rq->lock);
5187                 while (!list_empty(&rq->migration_queue)) {
5188                         struct migration_req *req;
5189
5190                         req = list_entry(rq->migration_queue.next,
5191                                          struct migration_req, list);
5192                         list_del_init(&req->list);
5193                         complete(&req->done);
5194                 }
5195                 spin_unlock_irq(&rq->lock);
5196                 break;
5197 #endif
5198         }
5199         return NOTIFY_OK;
5200 }
5201
5202 /* Register at highest priority so that task migration (migrate_all_tasks)
5203  * happens before everything else.
5204  */
5205 static struct notifier_block __cpuinitdata migration_notifier = {
5206         .notifier_call = migration_call,
5207         .priority = 10
5208 };
5209
5210 int __init migration_init(void)
5211 {
5212         void *cpu = (void *)(long)smp_processor_id();
5213
5214         /* Start one for the boot CPU: */
5215         migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5216         migration_call(&migration_notifier, CPU_ONLINE, cpu);
5217         register_cpu_notifier(&migration_notifier);
5218
5219         return 0;
5220 }
5221 #endif
5222
5223 #ifdef CONFIG_SMP
5224 #undef SCHED_DOMAIN_DEBUG
5225 #ifdef SCHED_DOMAIN_DEBUG
5226 static void sched_domain_debug(struct sched_domain *sd, int cpu)
5227 {
5228         int level = 0;
5229
5230         if (!sd) {
5231                 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5232                 return;
5233         }
5234
5235         printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5236
5237         do {
5238                 int i;
5239                 char str[NR_CPUS];
5240                 struct sched_group *group = sd->groups;
5241                 cpumask_t groupmask;
5242
5243                 cpumask_scnprintf(str, NR_CPUS, sd->span);
5244                 cpus_clear(groupmask);
5245
5246                 printk(KERN_DEBUG);
5247                 for (i = 0; i < level + 1; i++)
5248                         printk(" ");
5249                 printk("domain %d: ", level);
5250
5251                 if (!(sd->flags & SD_LOAD_BALANCE)) {
5252                         printk("does not load-balance\n");
5253                         if (sd->parent)
5254                                 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
5255                         break;
5256                 }
5257
5258                 printk("span %s\n", str);
5259
5260                 if (!cpu_isset(cpu, sd->span))
5261                         printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
5262                 if (!cpu_isset(cpu, group->cpumask))
5263                         printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
5264
5265                 printk(KERN_DEBUG);
5266                 for (i = 0; i < level + 2; i++)
5267                         printk(" ");
5268                 printk("groups:");
5269                 do {
5270                         if (!group) {
5271                                 printk("\n");
5272                                 printk(KERN_ERR "ERROR: group is NULL\n");
5273                                 break;
5274                         }
5275
5276                         if (!group->cpu_power) {
5277                                 printk("\n");
5278                                 printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
5279                         }
5280
5281                         if (!cpus_weight(group->cpumask)) {
5282                                 printk("\n");
5283                                 printk(KERN_ERR "ERROR: empty group\n");
5284                         }
5285
5286                         if (cpus_intersects(groupmask, group->cpumask)) {
5287                                 printk("\n");
5288                                 printk(KERN_ERR "ERROR: repeated CPUs\n");
5289                         }
5290
5291                         cpus_or(groupmask, groupmask, group->cpumask);
5292
5293                         cpumask_scnprintf(str, NR_CPUS, group->cpumask);
5294                         printk(" %s", str);
5295
5296                         group = group->next;
5297                 } while (group != sd->groups);
5298                 printk("\n");
5299
5300                 if (!cpus_equal(sd->span, groupmask))
5301                         printk(KERN_ERR "ERROR: groups don't span domain->span\n");
5302
5303                 level++;
5304                 sd = sd->parent;
5305
5306                 if (sd) {
5307                         if (!cpus_subset(groupmask, sd->span))
5308                                 printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
5309                 }
5310
5311         } while (sd);
5312 }
5313 #else
5314 # define sched_domain_debug(sd, cpu) do { } while (0)
5315 #endif
5316
5317 static int sd_degenerate(struct sched_domain *sd)
5318 {
5319         if (cpus_weight(sd->span) == 1)
5320                 return 1;
5321
5322         /* Following flags need at least 2 groups */
5323         if (sd->flags & (SD_LOAD_BALANCE |
5324                          SD_BALANCE_NEWIDLE |
5325                          SD_BALANCE_FORK |
5326                          SD_BALANCE_EXEC)) {
5327                 if (sd->groups != sd->groups->next)
5328                         return 0;
5329         }
5330
5331         /* Following flags don't use groups */
5332         if (sd->flags & (SD_WAKE_IDLE |
5333                          SD_WAKE_AFFINE |
5334                          SD_WAKE_BALANCE))
5335                 return 0;
5336
5337         return 1;
5338 }
5339
5340 static int
5341 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
5342 {
5343         unsigned long cflags = sd->flags, pflags = parent->flags;
5344
5345         if (sd_degenerate(parent))
5346                 return 1;
5347
5348         if (!cpus_equal(sd->span, parent->span))
5349                 return 0;
5350
5351         /* Does parent contain flags not in child? */
5352         /* WAKE_BALANCE is a subset of WAKE_AFFINE */
5353         if (cflags & SD_WAKE_AFFINE)
5354                 pflags &= ~SD_WAKE_BALANCE;
5355         /* Flags needing groups don't count if only 1 group in parent */
5356         if (parent->groups == parent->groups->next) {
5357                 pflags &= ~(SD_LOAD_BALANCE |
5358                                 SD_BALANCE_NEWIDLE |
5359                                 SD_BALANCE_FORK |
5360                                 SD_BALANCE_EXEC);
5361         }
5362         if (~cflags & pflags)
5363                 return 0;
5364
5365         return 1;
5366 }
5367
5368 /*
5369  * Attach the domain 'sd' to 'cpu' as its base domain.  Callers must
5370  * hold the hotplug lock.
5371  */
5372 static void cpu_attach_domain(struct sched_domain *sd, int cpu)
5373 {
5374         struct rq *rq = cpu_rq(cpu);
5375         struct sched_domain *tmp;
5376
5377         /* Remove the sched domains which do not contribute to scheduling. */
5378         for (tmp = sd; tmp; tmp = tmp->parent) {
5379                 struct sched_domain *parent = tmp->parent;
5380                 if (!parent)
5381                         break;
5382                 if (sd_parent_degenerate(tmp, parent))
5383                         tmp->parent = parent->parent;
5384         }
5385
5386         if (sd && sd_degenerate(sd))
5387                 sd = sd->parent;
5388
5389         sched_domain_debug(sd, cpu);
5390
5391         rcu_assign_pointer(rq->sd, sd);
5392 }
5393
5394 /* cpus with isolated domains */
5395 static cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
5396
5397 /* Setup the mask of cpus configured for isolated domains */
5398 static int __init isolated_cpu_setup(char *str)
5399 {
5400         int ints[NR_CPUS], i;
5401
5402         str = get_options(str, ARRAY_SIZE(ints), ints);
5403         cpus_clear(cpu_isolated_map);
5404         for (i = 1; i <= ints[0]; i++)
5405                 if (ints[i] < NR_CPUS)
5406                         cpu_set(ints[i], cpu_isolated_map);
5407         return 1;
5408 }
5409
5410 __setup ("isolcpus=", isolated_cpu_setup);
5411
5412 /*
5413  * init_sched_build_groups takes an array of groups, the cpumask we wish
5414  * to span, and a pointer to a function which identifies what group a CPU
5415  * belongs to. The return value of group_fn must be a valid index into the
5416  * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
5417  * keep track of groups covered with a cpumask_t).
5418  *
5419  * init_sched_build_groups will build a circular linked list of the groups
5420  * covered by the given span, and will set each group's ->cpumask correctly,
5421  * and ->cpu_power to 0.
5422  */
5423 static void init_sched_build_groups(struct sched_group groups[], cpumask_t span,
5424                                     int (*group_fn)(int cpu))
5425 {
5426         struct sched_group *first = NULL, *last = NULL;
5427         cpumask_t covered = CPU_MASK_NONE;
5428         int i;
5429
5430         for_each_cpu_mask(i, span) {
5431                 int group = group_fn(i);
5432                 struct sched_group *sg = &groups[group];
5433                 int j;
5434
5435                 if (cpu_isset(i, covered))
5436                         continue;
5437
5438                 sg->cpumask = CPU_MASK_NONE;
5439                 sg->cpu_power = 0;
5440
5441                 for_each_cpu_mask(j, span) {
5442                         if (group_fn(j) != group)
5443                                 continue;
5444
5445                         cpu_set(j, covered);
5446                         cpu_set(j, sg->cpumask);
5447                 }
5448                 if (!first)
5449                         first = sg;
5450                 if (last)
5451                         last->next = sg;
5452                 last = sg;
5453         }
5454         last->next = first;
5455 }
5456
5457 #define SD_NODES_PER_DOMAIN 16
5458
5459 /*
5460  * Self-tuning task migration cost measurement between source and target CPUs.
5461  *
5462  * This is done by measuring the cost of manipulating buffers of varying
5463  * sizes. For a given buffer-size here are the steps that are taken:
5464  *
5465  * 1) the source CPU reads+dirties a shared buffer
5466  * 2) the target CPU reads+dirties the same shared buffer
5467  *
5468  * We measure how long they take, in the following 4 scenarios:
5469  *
5470  *  - source: CPU1, target: CPU2 | cost1
5471  *  - source: CPU2, target: CPU1 | cost2
5472  *  - source: CPU1, target: CPU1 | cost3
5473  *  - source: CPU2, target: CPU2 | cost4
5474  *
5475  * We then calculate the cost3+cost4-cost1-cost2 difference - this is
5476  * the cost of migration.
5477  *
5478  * We then start off from a small buffer-size and iterate up to larger
5479  * buffer sizes, in 5% steps - measuring each buffer-size separately, and
5480  * doing a maximum search for the cost. (The maximum cost for a migration
5481  * normally occurs when the working set size is around the effective cache
5482  * size.)
5483  */
5484 #define SEARCH_SCOPE            2
5485 #define MIN_CACHE_SIZE          (64*1024U)
5486 #define DEFAULT_CACHE_SIZE      (5*1024*1024U)
5487 #define ITERATIONS              1
5488 #define SIZE_THRESH             130
5489 #define COST_THRESH             130
5490
5491 /*
5492  * The migration cost is a function of 'domain distance'. Domain
5493  * distance is the number of steps a CPU has to iterate down its
5494  * domain tree to share a domain with the other CPU. The farther
5495  * two CPUs are from each other, the larger the distance gets.
5496  *
5497  * Note that we use the distance only to cache measurement results,
5498  * the distance value is not used numerically otherwise. When two
5499  * CPUs have the same distance it is assumed that the migration
5500  * cost is the same. (this is a simplification but quite practical)
5501  */
5502 #define MAX_DOMAIN_DISTANCE 32
5503
5504 static unsigned long long migration_cost[MAX_DOMAIN_DISTANCE] =
5505                 { [ 0 ... MAX_DOMAIN_DISTANCE-1 ] =
5506 /*
5507  * Architectures may override the migration cost and thus avoid
5508  * boot-time calibration. Unit is nanoseconds. Mostly useful for
5509  * virtualized hardware:
5510  */
5511 #ifdef CONFIG_DEFAULT_MIGRATION_COST
5512                         CONFIG_DEFAULT_MIGRATION_COST
5513 #else
5514                         -1LL
5515 #endif
5516 };
5517
5518 /*
5519  * Allow override of migration cost - in units of microseconds.
5520  * E.g. migration_cost=1000,2000,3000 will set up a level-1 cost
5521  * of 1 msec, level-2 cost of 2 msecs and level3 cost of 3 msecs:
5522  */
5523 static int __init migration_cost_setup(char *str)
5524 {
5525         int ints[MAX_DOMAIN_DISTANCE+1], i;
5526
5527         str = get_options(str, ARRAY_SIZE(ints), ints);
5528
5529         printk("#ints: %d\n", ints[0]);
5530         for (i = 1; i <= ints[0]; i++) {
5531                 migration_cost[i-1] = (unsigned long long)ints[i]*1000;
5532                 printk("migration_cost[%d]: %Ld\n", i-1, migration_cost[i-1]);
5533         }
5534         return 1;
5535 }
5536
5537 __setup ("migration_cost=", migration_cost_setup);
5538
5539 /*
5540  * Global multiplier (divisor) for migration-cutoff values,
5541  * in percentiles. E.g. use a value of 150 to get 1.5 times
5542  * longer cache-hot cutoff times.
5543  *
5544  * (We scale it from 100 to 128 to long long handling easier.)
5545  */
5546
5547 #define MIGRATION_FACTOR_SCALE 128
5548
5549 static unsigned int migration_factor = MIGRATION_FACTOR_SCALE;
5550
5551 static int __init setup_migration_factor(char *str)
5552 {
5553         get_option(&str, &migration_factor);
5554         migration_factor = migration_factor * MIGRATION_FACTOR_SCALE / 100;
5555         return 1;
5556 }
5557
5558 __setup("migration_factor=", setup_migration_factor);
5559
5560 /*
5561  * Estimated distance of two CPUs, measured via the number of domains
5562  * we have to pass for the two CPUs to be in the same span:
5563  */
5564 static unsigned long domain_distance(int cpu1, int cpu2)
5565 {
5566         unsigned long distance = 0;
5567         struct sched_domain *sd;
5568
5569         for_each_domain(cpu1, sd) {
5570                 WARN_ON(!cpu_isset(cpu1, sd->span));
5571                 if (cpu_isset(cpu2, sd->span))
5572                         return distance;
5573                 distance++;
5574         }
5575         if (distance >= MAX_DOMAIN_DISTANCE) {
5576                 WARN_ON(1);
5577                 distance = MAX_DOMAIN_DISTANCE-1;
5578         }
5579
5580         return distance;
5581 }
5582
5583 static unsigned int migration_debug;
5584
5585 static int __init setup_migration_debug(char *str)
5586 {
5587         get_option(&str, &migration_debug);
5588         return 1;
5589 }
5590
5591 __setup("migration_debug=", setup_migration_debug);
5592
5593 /*
5594  * Maximum cache-size that the scheduler should try to measure.
5595  * Architectures with larger caches should tune this up during
5596  * bootup. Gets used in the domain-setup code (i.e. during SMP
5597  * bootup).
5598  */
5599 unsigned int max_cache_size;
5600
5601 static int __init setup_max_cache_size(char *str)
5602 {
5603         get_option(&str, &max_cache_size);
5604         return 1;
5605 }
5606
5607 __setup("max_cache_size=", setup_max_cache_size);
5608
5609 /*
5610  * Dirty a big buffer in a hard-to-predict (for the L2 cache) way. This
5611  * is the operation that is timed, so we try to generate unpredictable
5612  * cachemisses that still end up filling the L2 cache:
5613  */
5614 static void touch_cache(void *__cache, unsigned long __size)
5615 {
5616         unsigned long size = __size/sizeof(long), chunk1 = size/3,
5617                         chunk2 = 2*size/3;
5618         unsigned long *cache = __cache;
5619         int i;
5620
5621         for (i = 0; i < size/6; i += 8) {
5622                 switch (i % 6) {
5623                         case 0: cache[i]++;
5624                         case 1: cache[size-1-i]++;
5625                         case 2: cache[chunk1-i]++;
5626                         case 3: cache[chunk1+i]++;
5627                         case 4: cache[chunk2-i]++;
5628                         case 5: cache[chunk2+i]++;
5629                 }
5630         }
5631 }
5632
5633 /*
5634  * Measure the cache-cost of one task migration. Returns in units of nsec.
5635  */
5636 static unsigned long long
5637 measure_one(void *cache, unsigned long size, int source, int target)
5638 {
5639         cpumask_t mask, saved_mask;
5640         unsigned long long t0, t1, t2, t3, cost;
5641
5642         saved_mask = current->cpus_allowed;
5643
5644         /*
5645          * Flush source caches to RAM and invalidate them:
5646          */
5647         sched_cacheflush();
5648
5649         /*
5650          * Migrate to the source CPU:
5651          */
5652         mask = cpumask_of_cpu(source);
5653         set_cpus_allowed(current, mask);
5654         WARN_ON(smp_processor_id() != source);
5655
5656         /*
5657          * Dirty the working set:
5658          */
5659         t0 = sched_clock();
5660         touch_cache(cache, size);
5661         t1 = sched_clock();
5662
5663         /*
5664          * Migrate to the target CPU, dirty the L2 cache and access
5665          * the shared buffer. (which represents the working set
5666          * of a migrated task.)
5667          */
5668         mask = cpumask_of_cpu(target);
5669         set_cpus_allowed(current, mask);
5670         WARN_ON(smp_processor_id() != target);
5671
5672         t2 = sched_clock();
5673         touch_cache(cache, size);
5674         t3 = sched_clock();
5675
5676         cost = t1-t0 + t3-t2;
5677
5678         if (migration_debug >= 2)
5679                 printk("[%d->%d]: %8Ld %8Ld %8Ld => %10Ld.\n",
5680                         source, target, t1-t0, t1-t0, t3-t2, cost);
5681         /*
5682          * Flush target caches to RAM and invalidate them:
5683          */
5684         sched_cacheflush();
5685
5686         set_cpus_allowed(current, saved_mask);
5687
5688         return cost;
5689 }
5690
5691 /*
5692  * Measure a series of task migrations and return the average
5693  * result. Since this code runs early during bootup the system
5694  * is 'undisturbed' and the average latency makes sense.
5695  *
5696  * The algorithm in essence auto-detects the relevant cache-size,
5697  * so it will properly detect different cachesizes for different
5698  * cache-hierarchies, depending on how the CPUs are connected.
5699  *
5700  * Architectures can prime the upper limit of the search range via
5701  * max_cache_size, otherwise the search range defaults to 20MB...64K.
5702  */
5703 static unsigned long long
5704 measure_cost(int cpu1, int cpu2, void *cache, unsigned int size)
5705 {
5706         unsigned long long cost1, cost2;
5707         int i;
5708
5709         /*
5710          * Measure the migration cost of 'size' bytes, over an
5711          * average of 10 runs:
5712          *
5713          * (We perturb the cache size by a small (0..4k)
5714          *  value to compensate size/alignment related artifacts.
5715          *  We also subtract the cost of the operation done on
5716          *  the same CPU.)
5717          */
5718         cost1 = 0;
5719
5720         /*
5721          * dry run, to make sure we start off cache-cold on cpu1,
5722          * and to get any vmalloc pagefaults in advance:
5723          */
5724         measure_one(cache, size, cpu1, cpu2);
5725         for (i = 0; i < ITERATIONS; i++)
5726                 cost1 += measure_one(cache, size - i*1024, cpu1, cpu2);
5727
5728         measure_one(cache, size, cpu2, cpu1);
5729         for (i = 0; i < ITERATIONS; i++)
5730                 cost1 += measure_one(cache, size - i*1024, cpu2, cpu1);
5731
5732         /*
5733          * (We measure the non-migrating [cached] cost on both
5734          *  cpu1 and cpu2, to handle CPUs with different speeds)
5735          */
5736         cost2 = 0;
5737
5738         measure_one(cache, size, cpu1, cpu1);
5739         for (i = 0; i < ITERATIONS; i++)
5740                 cost2 += measure_one(cache, size - i*1024, cpu1, cpu1);
5741
5742         measure_one(cache, size, cpu2, cpu2);
5743         for (i = 0; i < ITERATIONS; i++)
5744                 cost2 += measure_one(cache, size - i*1024, cpu2, cpu2);
5745
5746         /*
5747          * Get the per-iteration migration cost:
5748          */
5749         do_div(cost1, 2*ITERATIONS);
5750         do_div(cost2, 2*ITERATIONS);
5751
5752         return cost1 - cost2;
5753 }
5754
5755 static unsigned long long measure_migration_cost(int cpu1, int cpu2)
5756 {
5757         unsigned long long max_cost = 0, fluct = 0, avg_fluct = 0;
5758         unsigned int max_size, size, size_found = 0;
5759         long long cost = 0, prev_cost;
5760         void *cache;
5761
5762         /*
5763          * Search from max_cache_size*5 down to 64K - the real relevant
5764          * cachesize has to lie somewhere inbetween.
5765          */
5766         if (max_cache_size) {
5767                 max_size = max(max_cache_size * SEARCH_SCOPE, MIN_CACHE_SIZE);
5768                 size = max(max_cache_size / SEARCH_SCOPE, MIN_CACHE_SIZE);
5769         } else {
5770                 /*
5771                  * Since we have no estimation about the relevant
5772                  * search range
5773                  */
5774                 max_size = DEFAULT_CACHE_SIZE * SEARCH_SCOPE;
5775                 size = MIN_CACHE_SIZE;
5776         }
5777
5778         if (!cpu_online(cpu1) || !cpu_online(cpu2)) {
5779                 printk("cpu %d and %d not both online!\n", cpu1, cpu2);
5780                 return 0;
5781         }
5782
5783         /*
5784          * Allocate the working set:
5785          */
5786         cache = vmalloc(max_size);
5787         if (!cache) {
5788                 printk("could not vmalloc %d bytes for cache!\n", 2*max_size);
5789                 return 1000000; /* return 1 msec on very small boxen */
5790         }
5791
5792         while (size <= max_size) {
5793                 prev_cost = cost;
5794                 cost = measure_cost(cpu1, cpu2, cache, size);
5795
5796                 /*
5797                  * Update the max:
5798                  */
5799                 if (cost > 0) {
5800                         if (max_cost < cost) {
5801                                 max_cost = cost;
5802                                 size_found = size;
5803                         }
5804                 }
5805                 /*
5806                  * Calculate average fluctuation, we use this to prevent
5807                  * noise from triggering an early break out of the loop:
5808                  */
5809                 fluct = abs(cost - prev_cost);
5810                 avg_fluct = (avg_fluct + fluct)/2;
5811
5812                 if (migration_debug)
5813                         printk("-> [%d][%d][%7d] %3ld.%ld [%3ld.%ld] (%ld): (%8Ld %8Ld)\n",
5814                                 cpu1, cpu2, size,
5815                                 (long)cost / 1000000,
5816                                 ((long)cost / 100000) % 10,
5817                                 (long)max_cost / 1000000,
5818                                 ((long)max_cost / 100000) % 10,
5819                                 domain_distance(cpu1, cpu2),
5820                                 cost, avg_fluct);
5821
5822                 /*
5823                  * If we iterated at least 20% past the previous maximum,
5824                  * and the cost has dropped by more than 20% already,
5825                  * (taking fluctuations into account) then we assume to
5826                  * have found the maximum and break out of the loop early:
5827                  */
5828                 if (size_found && (size*100 > size_found*SIZE_THRESH))
5829                         if (cost+avg_fluct <= 0 ||
5830                                 max_cost*100 > (cost+avg_fluct)*COST_THRESH) {
5831
5832                                 if (migration_debug)
5833                                         printk("-> found max.\n");
5834                                 break;
5835                         }
5836                 /*
5837                  * Increase the cachesize in 10% steps:
5838                  */
5839                 size = size * 10 / 9;
5840         }
5841
5842         if (migration_debug)
5843                 printk("[%d][%d] working set size found: %d, cost: %Ld\n",
5844                         cpu1, cpu2, size_found, max_cost);
5845
5846         vfree(cache);
5847
5848         /*
5849          * A task is considered 'cache cold' if at least 2 times
5850          * the worst-case cost of migration has passed.
5851          *
5852          * (this limit is only listened to if the load-balancing
5853          * situation is 'nice' - if there is a large imbalance we
5854          * ignore it for the sake of CPU utilization and
5855          * processing fairness.)
5856          */
5857         return 2 * max_cost * migration_factor / MIGRATION_FACTOR_SCALE;
5858 }
5859
5860 static void calibrate_migration_costs(const cpumask_t *cpu_map)
5861 {
5862         int cpu1 = -1, cpu2 = -1, cpu, orig_cpu = raw_smp_processor_id();
5863         unsigned long j0, j1, distance, max_distance = 0;
5864         struct sched_domain *sd;
5865
5866         j0 = jiffies;
5867
5868         /*
5869          * First pass - calculate the cacheflush times:
5870          */
5871         for_each_cpu_mask(cpu1, *cpu_map) {
5872                 for_each_cpu_mask(cpu2, *cpu_map) {
5873                         if (cpu1 == cpu2)
5874                                 continue;
5875                         distance = domain_distance(cpu1, cpu2);
5876                         max_distance = max(max_distance, distance);
5877                         /*
5878                          * No result cached yet?
5879                          */
5880                         if (migration_cost[distance] == -1LL)
5881                                 migration_cost[distance] =
5882                                         measure_migration_cost(cpu1, cpu2);
5883                 }
5884         }
5885         /*
5886          * Second pass - update the sched domain hierarchy with
5887          * the new cache-hot-time estimations:
5888          */
5889         for_each_cpu_mask(cpu, *cpu_map) {
5890                 distance = 0;
5891                 for_each_domain(cpu, sd) {
5892                         sd->cache_hot_time = migration_cost[distance];
5893                         distance++;
5894                 }
5895         }
5896         /*
5897          * Print the matrix:
5898          */
5899         if (migration_debug)
5900                 printk("migration: max_cache_size: %d, cpu: %d MHz:\n",
5901                         max_cache_size,
5902 #ifdef CONFIG_X86
5903                         cpu_khz/1000
5904 #else
5905                         -1
5906 #endif
5907                 );
5908         if (system_state == SYSTEM_BOOTING) {
5909                 printk("migration_cost=");
5910                 for (distance = 0; distance <= max_distance; distance++) {
5911                         if (distance)
5912                                 printk(",");
5913                         printk("%ld", (long)migration_cost[distance] / 1000);
5914                 }
5915                 printk("\n");
5916         }
5917         j1 = jiffies;
5918         if (migration_debug)
5919                 printk("migration: %ld seconds\n", (j1-j0)/HZ);
5920
5921         /*
5922          * Move back to the original CPU. NUMA-Q gets confused
5923          * if we migrate to another quad during bootup.
5924          */
5925         if (raw_smp_processor_id() != orig_cpu) {
5926                 cpumask_t mask = cpumask_of_cpu(orig_cpu),
5927                         saved_mask = current->cpus_allowed;
5928
5929                 set_cpus_allowed(current, mask);
5930                 set_cpus_allowed(current, saved_mask);
5931         }
5932 }
5933
5934 #ifdef CONFIG_NUMA
5935
5936 /**
5937  * find_next_best_node - find the next node to include in a sched_domain
5938  * @node: node whose sched_domain we're building
5939  * @used_nodes: nodes already in the sched_domain
5940  *
5941  * Find the next node to include in a given scheduling domain.  Simply
5942  * finds the closest node not already in the @used_nodes map.
5943  *
5944  * Should use nodemask_t.
5945  */
5946 static int find_next_best_node(int node, unsigned long *used_nodes)
5947 {
5948         int i, n, val, min_val, best_node = 0;
5949
5950         min_val = INT_MAX;
5951
5952         for (i = 0; i < MAX_NUMNODES; i++) {
5953                 /* Start at @node */
5954                 n = (node + i) % MAX_NUMNODES;
5955
5956                 if (!nr_cpus_node(n))
5957                         continue;
5958
5959                 /* Skip already used nodes */
5960                 if (test_bit(n, used_nodes))
5961                         continue;
5962
5963                 /* Simple min distance search */
5964                 val = node_distance(node, n);
5965
5966                 if (val < min_val) {
5967                         min_val = val;
5968                         best_node = n;
5969                 }
5970         }
5971
5972         set_bit(best_node, used_nodes);
5973         return best_node;
5974 }
5975
5976 /**
5977  * sched_domain_node_span - get a cpumask for a node's sched_domain
5978  * @node: node whose cpumask we're constructing
5979  * @size: number of nodes to include in this span
5980  *
5981  * Given a node, construct a good cpumask for its sched_domain to span.  It
5982  * should be one that prevents unnecessary balancing, but also spreads tasks
5983  * out optimally.
5984  */
5985 static cpumask_t sched_domain_node_span(int node)
5986 {
5987         DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
5988         cpumask_t span, nodemask;
5989         int i;
5990
5991         cpus_clear(span);
5992         bitmap_zero(used_nodes, MAX_NUMNODES);
5993
5994         nodemask = node_to_cpumask(node);
5995         cpus_or(span, span, nodemask);
5996         set_bit(node, used_nodes);
5997
5998         for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
5999                 int next_node = find_next_best_node(node, used_nodes);
6000
6001                 nodemask = node_to_cpumask(next_node);
6002                 cpus_or(span, span, nodemask);
6003         }
6004
6005         return span;
6006 }
6007 #endif
6008
6009 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6010
6011 /*
6012  * SMT sched-domains:
6013  */
6014 #ifdef CONFIG_SCHED_SMT
6015 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
6016 static struct sched_group sched_group_cpus[NR_CPUS];
6017
6018 static int cpu_to_cpu_group(int cpu)
6019 {
6020         return cpu;
6021 }
6022 #endif
6023
6024 /*
6025  * multi-core sched-domains:
6026  */
6027 #ifdef CONFIG_SCHED_MC
6028 static DEFINE_PER_CPU(struct sched_domain, core_domains);
6029 static struct sched_group *sched_group_core_bycpu[NR_CPUS];
6030 #endif
6031
6032 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6033 static int cpu_to_core_group(int cpu)
6034 {
6035         return first_cpu(cpu_sibling_map[cpu]);
6036 }
6037 #elif defined(CONFIG_SCHED_MC)
6038 static int cpu_to_core_group(int cpu)
6039 {
6040         return cpu;
6041 }
6042 #endif
6043
6044 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
6045 static struct sched_group *sched_group_phys_bycpu[NR_CPUS];
6046
6047 static int cpu_to_phys_group(int cpu)
6048 {
6049 #ifdef CONFIG_SCHED_MC
6050         cpumask_t mask = cpu_coregroup_map(cpu);
6051         return first_cpu(mask);
6052 #elif defined(CONFIG_SCHED_SMT)
6053         return first_cpu(cpu_sibling_map[cpu]);
6054 #else
6055         return cpu;
6056 #endif
6057 }
6058
6059 #ifdef CONFIG_NUMA
6060 /*
6061  * The init_sched_build_groups can't handle what we want to do with node
6062  * groups, so roll our own. Now each node has its own list of groups which
6063  * gets dynamically allocated.
6064  */
6065 static DEFINE_PER_CPU(struct sched_domain, node_domains);
6066 static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
6067
6068 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
6069 static struct sched_group *sched_group_allnodes_bycpu[NR_CPUS];
6070
6071 static int cpu_to_allnodes_group(int cpu)
6072 {
6073         return cpu_to_node(cpu);
6074 }
6075 static void init_numa_sched_groups_power(struct sched_group *group_head)
6076 {
6077         struct sched_group *sg = group_head;
6078         int j;
6079
6080         if (!sg)
6081                 return;
6082 next_sg:
6083         for_each_cpu_mask(j, sg->cpumask) {
6084                 struct sched_domain *sd;
6085
6086                 sd = &per_cpu(phys_domains, j);
6087                 if (j != first_cpu(sd->groups->cpumask)) {
6088                         /*
6089                          * Only add "power" once for each
6090                          * physical package.
6091                          */
6092                         continue;
6093                 }
6094
6095                 sg->cpu_power += sd->groups->cpu_power;
6096         }
6097         sg = sg->next;
6098         if (sg != group_head)
6099                 goto next_sg;
6100 }
6101 #endif
6102
6103 /* Free memory allocated for various sched_group structures */
6104 static void free_sched_groups(const cpumask_t *cpu_map)
6105 {
6106         int cpu;
6107 #ifdef CONFIG_NUMA
6108         int i;
6109
6110         for_each_cpu_mask(cpu, *cpu_map) {
6111                 struct sched_group *sched_group_allnodes
6112                         = sched_group_allnodes_bycpu[cpu];
6113                 struct sched_group **sched_group_nodes
6114                         = sched_group_nodes_bycpu[cpu];
6115
6116                 if (sched_group_allnodes) {
6117                         kfree(sched_group_allnodes);
6118                         sched_group_allnodes_bycpu[cpu] = NULL;
6119                 }
6120
6121                 if (!sched_group_nodes)
6122                         continue;
6123
6124                 for (i = 0; i < MAX_NUMNODES; i++) {
6125                         cpumask_t nodemask = node_to_cpumask(i);
6126                         struct sched_group *oldsg, *sg = sched_group_nodes[i];
6127
6128                         cpus_and(nodemask, nodemask, *cpu_map);
6129                         if (cpus_empty(nodemask))
6130                                 continue;
6131
6132                         if (sg == NULL)
6133                                 continue;
6134                         sg = sg->next;
6135 next_sg:
6136                         oldsg = sg;
6137                         sg = sg->next;
6138                         kfree(oldsg);
6139                         if (oldsg != sched_group_nodes[i])
6140                                 goto next_sg;
6141                 }
6142                 kfree(sched_group_nodes);
6143                 sched_group_nodes_bycpu[cpu] = NULL;
6144         }
6145 #endif
6146         for_each_cpu_mask(cpu, *cpu_map) {
6147                 if (sched_group_phys_bycpu[cpu]) {
6148                         kfree(sched_group_phys_bycpu[cpu]);
6149                         sched_group_phys_bycpu[cpu] = NULL;
6150                 }
6151 #ifdef CONFIG_SCHED_MC
6152                 if (sched_group_core_bycpu[cpu]) {
6153                         kfree(sched_group_core_bycpu[cpu]);
6154                         sched_group_core_bycpu[cpu] = NULL;
6155                 }
6156 #endif
6157         }
6158 }
6159
6160 /*
6161  * Build sched domains for a given set of cpus and attach the sched domains
6162  * to the individual cpus
6163  */
6164 static int build_sched_domains(const cpumask_t *cpu_map)
6165 {
6166         int i;
6167         struct sched_group *sched_group_phys = NULL;
6168 #ifdef CONFIG_SCHED_MC
6169         struct sched_group *sched_group_core = NULL;
6170 #endif
6171 #ifdef CONFIG_NUMA
6172         struct sched_group **sched_group_nodes = NULL;
6173         struct sched_group *sched_group_allnodes = NULL;
6174
6175         /*
6176          * Allocate the per-node list of sched groups
6177          */
6178         sched_group_nodes = kzalloc(sizeof(struct sched_group*)*MAX_NUMNODES,
6179                                            GFP_KERNEL);
6180         if (!sched_group_nodes) {
6181                 printk(KERN_WARNING "Can not alloc sched group node list\n");
6182                 return -ENOMEM;
6183         }
6184         sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
6185 #endif
6186
6187         /*
6188          * Set up domains for cpus specified by the cpu_map.
6189          */
6190         for_each_cpu_mask(i, *cpu_map) {
6191                 int group;
6192                 struct sched_domain *sd = NULL, *p;
6193                 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
6194
6195                 cpus_and(nodemask, nodemask, *cpu_map);
6196
6197 #ifdef CONFIG_NUMA
6198                 if (cpus_weight(*cpu_map)
6199                                 > SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
6200                         if (!sched_group_allnodes) {
6201                                 sched_group_allnodes
6202                                         = kmalloc(sizeof(struct sched_group)
6203                                                         * MAX_NUMNODES,
6204                                                   GFP_KERNEL);
6205                                 if (!sched_group_allnodes) {
6206                                         printk(KERN_WARNING
6207                                         "Can not alloc allnodes sched group\n");
6208                                         goto error;
6209                                 }
6210                                 sched_group_allnodes_bycpu[i]
6211                                                 = sched_group_allnodes;
6212                         }
6213                         sd = &per_cpu(allnodes_domains, i);
6214                         *sd = SD_ALLNODES_INIT;
6215                         sd->span = *cpu_map;
6216                         group = cpu_to_allnodes_group(i);
6217                         sd->groups = &sched_group_allnodes[group];
6218                         p = sd;
6219                 } else
6220                         p = NULL;
6221
6222                 sd = &per_cpu(node_domains, i);
6223                 *sd = SD_NODE_INIT;
6224                 sd->span = sched_domain_node_span(cpu_to_node(i));
6225                 sd->parent = p;
6226                 cpus_and(sd->span, sd->span, *cpu_map);
6227 #endif
6228
6229                 if (!sched_group_phys) {
6230                         sched_group_phys
6231                                 = kmalloc(sizeof(struct sched_group) * NR_CPUS,
6232                                           GFP_KERNEL);
6233                         if (!sched_group_phys) {
6234                                 printk (KERN_WARNING "Can not alloc phys sched"
6235                                                      "group\n");
6236                                 goto error;
6237                         }
6238                         sched_group_phys_bycpu[i] = sched_group_phys;
6239                 }
6240
6241                 p = sd;
6242                 sd = &per_cpu(phys_domains, i);
6243                 group = cpu_to_phys_group(i);
6244                 *sd = SD_CPU_INIT;
6245                 sd->span = nodemask;
6246                 sd->parent = p;
6247                 sd->groups = &sched_group_phys[group];
6248
6249 #ifdef CONFIG_SCHED_MC
6250                 if (!sched_group_core) {
6251                         sched_group_core
6252                                 = kmalloc(sizeof(struct sched_group) * NR_CPUS,
6253                                           GFP_KERNEL);
6254                         if (!sched_group_core) {
6255                                 printk (KERN_WARNING "Can not alloc core sched"
6256                                                      "group\n");
6257                                 goto error;
6258                         }
6259                         sched_group_core_bycpu[i] = sched_group_core;
6260                 }
6261
6262                 p = sd;
6263                 sd = &per_cpu(core_domains, i);
6264                 group = cpu_to_core_group(i);
6265                 *sd = SD_MC_INIT;
6266                 sd->span = cpu_coregroup_map(i);
6267                 cpus_and(sd->span, sd->span, *cpu_map);
6268                 sd->parent = p;
6269                 sd->groups = &sched_group_core[group];
6270 #endif
6271
6272 #ifdef CONFIG_SCHED_SMT
6273                 p = sd;
6274                 sd = &per_cpu(cpu_domains, i);
6275                 group = cpu_to_cpu_group(i);
6276                 *sd = SD_SIBLING_INIT;
6277                 sd->span = cpu_sibling_map[i];
6278                 cpus_and(sd->span, sd->span, *cpu_map);
6279                 sd->parent = p;
6280                 sd->groups = &sched_group_cpus[group];
6281 #endif
6282         }
6283
6284 #ifdef CONFIG_SCHED_SMT
6285         /* Set up CPU (sibling) groups */
6286         for_each_cpu_mask(i, *cpu_map) {
6287                 cpumask_t this_sibling_map = cpu_sibling_map[i];
6288                 cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
6289                 if (i != first_cpu(this_sibling_map))
6290                         continue;
6291
6292                 init_sched_build_groups(sched_group_cpus, this_sibling_map,
6293                                                 &cpu_to_cpu_group);
6294         }
6295 #endif
6296
6297 #ifdef CONFIG_SCHED_MC
6298         /* Set up multi-core groups */
6299         for_each_cpu_mask(i, *cpu_map) {
6300                 cpumask_t this_core_map = cpu_coregroup_map(i);
6301                 cpus_and(this_core_map, this_core_map, *cpu_map);
6302                 if (i != first_cpu(this_core_map))
6303                         continue;
6304                 init_sched_build_groups(sched_group_core, this_core_map,
6305                                         &cpu_to_core_group);
6306         }
6307 #endif
6308
6309
6310         /* Set up physical groups */
6311         for (i = 0; i < MAX_NUMNODES; i++) {
6312                 cpumask_t nodemask = node_to_cpumask(i);
6313
6314                 cpus_and(nodemask, nodemask, *cpu_map);
6315                 if (cpus_empty(nodemask))
6316                         continue;
6317
6318                 init_sched_build_groups(sched_group_phys, nodemask,
6319                                                 &cpu_to_phys_group);
6320         }
6321
6322 #ifdef CONFIG_NUMA
6323         /* Set up node groups */
6324         if (sched_group_allnodes)
6325                 init_sched_build_groups(sched_group_allnodes, *cpu_map,
6326                                         &cpu_to_allnodes_group);
6327
6328         for (i = 0; i < MAX_NUMNODES; i++) {
6329                 /* Set up node groups */
6330                 struct sched_group *sg, *prev;
6331                 cpumask_t nodemask = node_to_cpumask(i);
6332                 cpumask_t domainspan;
6333                 cpumask_t covered = CPU_MASK_NONE;
6334                 int j;
6335
6336                 cpus_and(nodemask, nodemask, *cpu_map);
6337                 if (cpus_empty(nodemask)) {
6338                         sched_group_nodes[i] = NULL;
6339                         continue;
6340                 }
6341
6342                 domainspan = sched_domain_node_span(i);
6343                 cpus_and(domainspan, domainspan, *cpu_map);
6344
6345                 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
6346                 if (!sg) {
6347                         printk(KERN_WARNING "Can not alloc domain group for "
6348                                 "node %d\n", i);
6349                         goto error;
6350                 }
6351                 sched_group_nodes[i] = sg;
6352                 for_each_cpu_mask(j, nodemask) {
6353                         struct sched_domain *sd;
6354                         sd = &per_cpu(node_domains, j);
6355                         sd->groups = sg;
6356                 }
6357                 sg->cpu_power = 0;
6358                 sg->cpumask = nodemask;
6359                 sg->next = sg;
6360                 cpus_or(covered, covered, nodemask);
6361                 prev = sg;
6362
6363                 for (j = 0; j < MAX_NUMNODES; j++) {
6364                         cpumask_t tmp, notcovered;
6365                         int n = (i + j) % MAX_NUMNODES;
6366
6367                         cpus_complement(notcovered, covered);
6368                         cpus_and(tmp, notcovered, *cpu_map);
6369                         cpus_and(tmp, tmp, domainspan);
6370                         if (cpus_empty(tmp))
6371                                 break;
6372
6373                         nodemask = node_to_cpumask(n);
6374                         cpus_and(tmp, tmp, nodemask);
6375                         if (cpus_empty(tmp))
6376                                 continue;
6377
6378                         sg = kmalloc_node(sizeof(struct sched_group),
6379                                           GFP_KERNEL, i);
6380                         if (!sg) {
6381                                 printk(KERN_WARNING
6382                                 "Can not alloc domain group for node %d\n", j);
6383                                 goto error;
6384                         }
6385                         sg->cpu_power = 0;
6386                         sg->cpumask = tmp;
6387                         sg->next = prev->next;
6388                         cpus_or(covered, covered, tmp);
6389                         prev->next = sg;
6390                         prev = sg;
6391                 }
6392         }
6393 #endif
6394
6395         /* Calculate CPU power for physical packages and nodes */
6396 #ifdef CONFIG_SCHED_SMT
6397         for_each_cpu_mask(i, *cpu_map) {
6398                 struct sched_domain *sd;
6399                 sd = &per_cpu(cpu_domains, i);
6400                 sd->groups->cpu_power = SCHED_LOAD_SCALE;
6401         }
6402 #endif
6403 #ifdef CONFIG_SCHED_MC
6404         for_each_cpu_mask(i, *cpu_map) {
6405                 int power;
6406                 struct sched_domain *sd;
6407                 sd = &per_cpu(core_domains, i);
6408                 if (sched_smt_power_savings)
6409                         power = SCHED_LOAD_SCALE * cpus_weight(sd->groups->cpumask);
6410                 else
6411                         power = SCHED_LOAD_SCALE + (cpus_weight(sd->groups->cpumask)-1)
6412                                             * SCHED_LOAD_SCALE / 10;
6413                 sd->groups->cpu_power = power;
6414         }
6415 #endif
6416
6417         for_each_cpu_mask(i, *cpu_map) {
6418                 struct sched_domain *sd;
6419 #ifdef CONFIG_SCHED_MC
6420                 sd = &per_cpu(phys_domains, i);
6421                 if (i != first_cpu(sd->groups->cpumask))
6422                         continue;
6423
6424                 sd->groups->cpu_power = 0;
6425                 if (sched_mc_power_savings || sched_smt_power_savings) {
6426                         int j;
6427
6428                         for_each_cpu_mask(j, sd->groups->cpumask) {
6429                                 struct sched_domain *sd1;
6430                                 sd1 = &per_cpu(core_domains, j);
6431                                 /*
6432                                  * for each core we will add once
6433                                  * to the group in physical domain
6434                                  */
6435                                 if (j != first_cpu(sd1->groups->cpumask))
6436                                         continue;
6437
6438                                 if (sched_smt_power_savings)
6439                                         sd->groups->cpu_power += sd1->groups->cpu_power;
6440                                 else
6441                                         sd->groups->cpu_power += SCHED_LOAD_SCALE;
6442                         }
6443                 } else
6444                         /*
6445                          * This has to be < 2 * SCHED_LOAD_SCALE
6446                          * Lets keep it SCHED_LOAD_SCALE, so that
6447                          * while calculating NUMA group's cpu_power
6448                          * we can simply do
6449                          *  numa_group->cpu_power += phys_group->cpu_power;
6450                          *
6451                          * See "only add power once for each physical pkg"
6452                          * comment below
6453                          */
6454                         sd->groups->cpu_power = SCHED_LOAD_SCALE;
6455 #else
6456                 int power;
6457                 sd = &per_cpu(phys_domains, i);
6458                 if (sched_smt_power_savings)
6459                         power = SCHED_LOAD_SCALE * cpus_weight(sd->groups->cpumask);
6460                 else
6461                         power = SCHED_LOAD_SCALE;
6462                 sd->groups->cpu_power = power;
6463 #endif
6464         }
6465
6466 #ifdef CONFIG_NUMA
6467         for (i = 0; i < MAX_NUMNODES; i++)
6468                 init_numa_sched_groups_power(sched_group_nodes[i]);
6469
6470         init_numa_sched_groups_power(sched_group_allnodes);
6471 #endif
6472
6473         /* Attach the domains */
6474         for_each_cpu_mask(i, *cpu_map) {
6475                 struct sched_domain *sd;
6476 #ifdef CONFIG_SCHED_SMT
6477                 sd = &per_cpu(cpu_domains, i);
6478 #elif defined(CONFIG_SCHED_MC)
6479                 sd = &per_cpu(core_domains, i);
6480 #else
6481                 sd = &per_cpu(phys_domains, i);
6482 #endif
6483                 cpu_attach_domain(sd, i);
6484         }
6485         /*
6486          * Tune cache-hot values:
6487          */
6488         calibrate_migration_costs(cpu_map);
6489
6490         return 0;
6491
6492 error:
6493         free_sched_groups(cpu_map);
6494         return -ENOMEM;
6495 }
6496 /*
6497  * Set up scheduler domains and groups.  Callers must hold the hotplug lock.
6498  */
6499 static int arch_init_sched_domains(const cpumask_t *cpu_map)
6500 {
6501         cpumask_t cpu_default_map;
6502         int err;
6503
6504         /*
6505          * Setup mask for cpus without special case scheduling requirements.
6506          * For now this just excludes isolated cpus, but could be used to
6507          * exclude other special cases in the future.
6508          */
6509         cpus_andnot(cpu_default_map, *cpu_map, cpu_isolated_map);
6510
6511         err = build_sched_domains(&cpu_default_map);
6512
6513         return err;
6514 }
6515
6516 static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
6517 {
6518         free_sched_groups(cpu_map);
6519 }
6520
6521 /*
6522  * Detach sched domains from a group of cpus specified in cpu_map
6523  * These cpus will now be attached to the NULL domain
6524  */
6525 static void detach_destroy_domains(const cpumask_t *cpu_map)
6526 {
6527         int i;
6528
6529         for_each_cpu_mask(i, *cpu_map)
6530                 cpu_attach_domain(NULL, i);
6531         synchronize_sched();
6532         arch_destroy_sched_domains(cpu_map);
6533 }
6534
6535 /*
6536  * Partition sched domains as specified by the cpumasks below.
6537  * This attaches all cpus from the cpumasks to the NULL domain,
6538  * waits for a RCU quiescent period, recalculates sched
6539  * domain information and then attaches them back to the
6540  * correct sched domains
6541  * Call with hotplug lock held
6542  */
6543 int partition_sched_domains(cpumask_t *partition1, cpumask_t *partition2)
6544 {
6545         cpumask_t change_map;
6546         int err = 0;
6547
6548         cpus_and(*partition1, *partition1, cpu_online_map);
6549         cpus_and(*partition2, *partition2, cpu_online_map);
6550         cpus_or(change_map, *partition1, *partition2);
6551
6552         /* Detach sched domains from all of the affected cpus */
6553         detach_destroy_domains(&change_map);
6554         if (!cpus_empty(*partition1))
6555                 err = build_sched_domains(partition1);
6556         if (!err && !cpus_empty(*partition2))
6557                 err = build_sched_domains(partition2);
6558
6559         return err;
6560 }
6561
6562 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
6563 int arch_reinit_sched_domains(void)
6564 {
6565         int err;
6566
6567         lock_cpu_hotplug();
6568         detach_destroy_domains(&cpu_online_map);
6569         err = arch_init_sched_domains(&cpu_online_map);
6570         unlock_cpu_hotplug();
6571
6572         return err;
6573 }
6574
6575 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
6576 {
6577         int ret;
6578
6579         if (buf[0] != '0' && buf[0] != '1')
6580                 return -EINVAL;
6581
6582         if (smt)
6583                 sched_smt_power_savings = (buf[0] == '1');
6584         else
6585                 sched_mc_power_savings = (buf[0] == '1');
6586
6587         ret = arch_reinit_sched_domains();
6588
6589         return ret ? ret : count;
6590 }
6591
6592 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
6593 {
6594         int err = 0;
6595
6596 #ifdef CONFIG_SCHED_SMT
6597         if (smt_capable())
6598                 err = sysfs_create_file(&cls->kset.kobj,
6599                                         &attr_sched_smt_power_savings.attr);
6600 #endif
6601 #ifdef CONFIG_SCHED_MC
6602         if (!err && mc_capable())
6603                 err = sysfs_create_file(&cls->kset.kobj,
6604                                         &attr_sched_mc_power_savings.attr);
6605 #endif
6606         return err;
6607 }
6608 #endif
6609
6610 #ifdef CONFIG_SCHED_MC
6611 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
6612 {
6613         return sprintf(page, "%u\n", sched_mc_power_savings);
6614 }
6615 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
6616                                             const char *buf, size_t count)
6617 {
6618         return sched_power_savings_store(buf, count, 0);
6619 }
6620 SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
6621             sched_mc_power_savings_store);
6622 #endif
6623
6624 #ifdef CONFIG_SCHED_SMT
6625 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
6626 {
6627         return sprintf(page, "%u\n", sched_smt_power_savings);
6628 }
6629 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
6630                                              const char *buf, size_t count)
6631 {
6632         return sched_power_savings_store(buf, count, 1);
6633 }
6634 SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
6635             sched_smt_power_savings_store);
6636 #endif
6637
6638
6639 #ifdef CONFIG_HOTPLUG_CPU
6640 /*
6641  * Force a reinitialization of the sched domains hierarchy.  The domains
6642  * and groups cannot be updated in place without racing with the balancing
6643  * code, so we temporarily attach all running cpus to the NULL domain
6644  * which will prevent rebalancing while the sched domains are recalculated.
6645  */
6646 static int update_sched_domains(struct notifier_block *nfb,
6647                                 unsigned long action, void *hcpu)
6648 {
6649         switch (action) {
6650         case CPU_UP_PREPARE:
6651         case CPU_DOWN_PREPARE:
6652                 detach_destroy_domains(&cpu_online_map);
6653                 return NOTIFY_OK;
6654
6655         case CPU_UP_CANCELED:
6656         case CPU_DOWN_FAILED:
6657         case CPU_ONLINE:
6658         case CPU_DEAD:
6659                 /*
6660                  * Fall through and re-initialise the domains.
6661                  */
6662                 break;
6663         default:
6664                 return NOTIFY_DONE;
6665         }
6666
6667         /* The hotplug lock is already held by cpu_up/cpu_down */
6668         arch_init_sched_domains(&cpu_online_map);
6669
6670         return NOTIFY_OK;
6671 }
6672 #endif
6673
6674 void __init sched_init_smp(void)
6675 {
6676         lock_cpu_hotplug();
6677         arch_init_sched_domains(&cpu_online_map);
6678         unlock_cpu_hotplug();
6679         /* XXX: Theoretical race here - CPU may be hotplugged now */
6680         hotcpu_notifier(update_sched_domains, 0);
6681 }
6682 #else
6683 void __init sched_init_smp(void)
6684 {
6685 }
6686 #endif /* CONFIG_SMP */
6687
6688 int in_sched_functions(unsigned long addr)
6689 {
6690         /* Linker adds these: start and end of __sched functions */
6691         extern char __sched_text_start[], __sched_text_end[];
6692
6693         return in_lock_functions(addr) ||
6694                 (addr >= (unsigned long)__sched_text_start
6695                 && addr < (unsigned long)__sched_text_end);
6696 }
6697
6698 void __init sched_init(void)
6699 {
6700         int i, j, k;
6701
6702         for_each_possible_cpu(i) {
6703                 struct prio_array *array;
6704                 struct rq *rq;
6705
6706                 rq = cpu_rq(i);
6707                 spin_lock_init(&rq->lock);
6708                 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
6709                 rq->nr_running = 0;
6710                 rq->active = rq->arrays;
6711                 rq->expired = rq->arrays + 1;
6712                 rq->best_expired_prio = MAX_PRIO;
6713
6714 #ifdef CONFIG_SMP
6715                 rq->sd = NULL;
6716                 for (j = 1; j < 3; j++)
6717                         rq->cpu_load[j] = 0;
6718                 rq->active_balance = 0;
6719                 rq->push_cpu = 0;
6720                 rq->migration_thread = NULL;
6721                 INIT_LIST_HEAD(&rq->migration_queue);
6722 #endif
6723                 atomic_set(&rq->nr_iowait, 0);
6724
6725                 for (j = 0; j < 2; j++) {
6726                         array = rq->arrays + j;
6727                         for (k = 0; k < MAX_PRIO; k++) {
6728                                 INIT_LIST_HEAD(array->queue + k);
6729                                 __clear_bit(k, array->bitmap);
6730                         }
6731                         // delimiter for bitsearch
6732                         __set_bit(MAX_PRIO, array->bitmap);
6733                 }
6734         }
6735
6736         set_load_weight(&init_task);
6737         /*
6738          * The boot idle thread does lazy MMU switching as well:
6739          */
6740         atomic_inc(&init_mm.mm_count);
6741         enter_lazy_tlb(&init_mm, current);
6742
6743         /*
6744          * Make us the idle thread. Technically, schedule() should not be
6745          * called from this thread, however somewhere below it might be,
6746          * but because we are the idle thread, we just pick up running again
6747          * when this runqueue becomes "idle".
6748          */
6749         init_idle(current, smp_processor_id());
6750 }
6751
6752 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
6753 void __might_sleep(char *file, int line)
6754 {
6755 #ifdef in_atomic
6756         static unsigned long prev_jiffy;        /* ratelimiting */
6757
6758         if ((in_atomic() || irqs_disabled()) &&
6759             system_state == SYSTEM_RUNNING && !oops_in_progress) {
6760                 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6761                         return;
6762                 prev_jiffy = jiffies;
6763                 printk(KERN_ERR "BUG: sleeping function called from invalid"
6764                                 " context at %s:%d\n", file, line);
6765                 printk("in_atomic():%d, irqs_disabled():%d\n",
6766                         in_atomic(), irqs_disabled());
6767                 dump_stack();
6768         }
6769 #endif
6770 }
6771 EXPORT_SYMBOL(__might_sleep);
6772 #endif
6773
6774 #ifdef CONFIG_MAGIC_SYSRQ
6775 void normalize_rt_tasks(void)
6776 {
6777         struct prio_array *array;
6778         struct task_struct *p;
6779         unsigned long flags;
6780         struct rq *rq;
6781
6782         read_lock_irq(&tasklist_lock);
6783         for_each_process(p) {
6784                 if (!rt_task(p))
6785                         continue;
6786
6787                 spin_lock_irqsave(&p->pi_lock, flags);
6788                 rq = __task_rq_lock(p);
6789
6790                 array = p->array;
6791                 if (array)
6792                         deactivate_task(p, task_rq(p));
6793                 __setscheduler(p, SCHED_NORMAL, 0);
6794                 if (array) {
6795                         __activate_task(p, task_rq(p));
6796                         resched_task(rq->curr);
6797                 }
6798
6799                 __task_rq_unlock(rq);
6800                 spin_unlock_irqrestore(&p->pi_lock, flags);
6801         }
6802         read_unlock_irq(&tasklist_lock);
6803 }
6804
6805 #endif /* CONFIG_MAGIC_SYSRQ */
6806
6807 #ifdef CONFIG_IA64
6808 /*
6809  * These functions are only useful for the IA64 MCA handling.
6810  *
6811  * They can only be called when the whole system has been
6812  * stopped - every CPU needs to be quiescent, and no scheduling
6813  * activity can take place. Using them for anything else would
6814  * be a serious bug, and as a result, they aren't even visible
6815  * under any other configuration.
6816  */
6817
6818 /**
6819  * curr_task - return the current task for a given cpu.
6820  * @cpu: the processor in question.
6821  *
6822  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6823  */
6824 struct task_struct *curr_task(int cpu)
6825 {
6826         return cpu_curr(cpu);
6827 }
6828
6829 /**
6830  * set_curr_task - set the current task for a given cpu.
6831  * @cpu: the processor in question.
6832  * @p: the task pointer to set.
6833  *
6834  * Description: This function must only be used when non-maskable interrupts
6835  * are serviced on a separate stack.  It allows the architecture to switch the
6836  * notion of the current task on a cpu in a non-blocking manner.  This function
6837  * must be called with all CPU's synchronized, and interrupts disabled, the
6838  * and caller must save the original value of the current task (see
6839  * curr_task() above) and restore that value before reenabling interrupts and
6840  * re-starting the system.
6841  *
6842  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6843  */
6844 void set_curr_task(int cpu, struct task_struct *p)
6845 {
6846         cpu_curr(cpu) = p;
6847 }
6848
6849 #endif