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