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