4e10dc63aa7489d5b76391fe577a843d33a644fb
[linux-2.6.git] / kernel / sched.c
1 /*
2  *  kernel/sched.c
3  *
4  *  Kernel scheduler and related syscalls
5  *
6  *  Copyright (C) 1991-2002  Linus Torvalds
7  *
8  *  1996-12-23  Modified by Dave Grothe to fix bugs in semaphores and
9  *              make semaphores SMP safe
10  *  1998-11-19  Implemented schedule_timeout() and related stuff
11  *              by Andrea Arcangeli
12  *  2002-01-04  New ultra-scalable O(1) scheduler by Ingo Molnar:
13  *              hybrid priority-list and round-robin design with
14  *              an array-switch method of distributing timeslices
15  *              and per-CPU runqueues.  Cleanups and useful suggestions
16  *              by Davide Libenzi, preemptible kernel bits by Robert Love.
17  *  2003-09-03  Interactivity tuning by Con Kolivas.
18  *  2004-04-02  Scheduler domains code by Nick Piggin
19  */
20
21 #include <linux/mm.h>
22 #include <linux/module.h>
23 #include <linux/nmi.h>
24 #include <linux/init.h>
25 #include <asm/uaccess.h>
26 #include <linux/highmem.h>
27 #include <linux/smp_lock.h>
28 #include <asm/mmu_context.h>
29 #include <linux/interrupt.h>
30 #include <linux/completion.h>
31 #include <linux/kernel_stat.h>
32 #include <linux/security.h>
33 #include <linux/notifier.h>
34 #include <linux/profile.h>
35 #include <linux/suspend.h>
36 #include <linux/blkdev.h>
37 #include <linux/delay.h>
38 #include <linux/smp.h>
39 #include <linux/threads.h>
40 #include <linux/timer.h>
41 #include <linux/rcupdate.h>
42 #include <linux/cpu.h>
43 #include <linux/cpuset.h>
44 #include <linux/percpu.h>
45 #include <linux/kthread.h>
46 #include <linux/seq_file.h>
47 #include <linux/syscalls.h>
48 #include <linux/times.h>
49 #include <linux/acct.h>
50 #include <asm/tlb.h>
51
52 #include <asm/unistd.h>
53 #include <linux/vs_context.h>
54 #include <linux/vs_cvirt.h>
55 #include <linux/vs_sched.h>
56
57 /*
58  * Convert user-nice values [ -20 ... 0 ... 19 ]
59  * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
60  * and back.
61  */
62 #define NICE_TO_PRIO(nice)      (MAX_RT_PRIO + (nice) + 20)
63 #define PRIO_TO_NICE(prio)      ((prio) - MAX_RT_PRIO - 20)
64 #define TASK_NICE(p)            PRIO_TO_NICE((p)->static_prio)
65
66 /*
67  * 'User priority' is the nice value converted to something we
68  * can work with better when scaling various scheduler parameters,
69  * it's a [ 0 ... 39 ] range.
70  */
71 #define USER_PRIO(p)            ((p)-MAX_RT_PRIO)
72 #define TASK_USER_PRIO(p)       USER_PRIO((p)->static_prio)
73 #define MAX_USER_PRIO           (USER_PRIO(MAX_PRIO))
74
75 /*
76  * Some helpers for converting nanosecond timing to jiffy resolution
77  */
78 #define NS_TO_JIFFIES(TIME)     ((TIME) / (1000000000 / HZ))
79 #define JIFFIES_TO_NS(TIME)     ((TIME) * (1000000000 / HZ))
80
81 /*
82  * These are the 'tuning knobs' of the scheduler:
83  *
84  * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
85  * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
86  * Timeslices get refilled after they expire.
87  */
88 #define MIN_TIMESLICE           max(5 * HZ / 1000, 1)
89 #define DEF_TIMESLICE           (100 * HZ / 1000)
90 #define ON_RUNQUEUE_WEIGHT       30
91 #define CHILD_PENALTY            95
92 #define PARENT_PENALTY          100
93 #define EXIT_WEIGHT               3
94 #define PRIO_BONUS_RATIO         25
95 #define MAX_BONUS               (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
96 #define INTERACTIVE_DELTA         2
97 #define MAX_SLEEP_AVG           (DEF_TIMESLICE * MAX_BONUS)
98 #define STARVATION_LIMIT        (MAX_SLEEP_AVG)
99 #define NS_MAX_SLEEP_AVG        (JIFFIES_TO_NS(MAX_SLEEP_AVG))
100
101 /*
102  * If a task is 'interactive' then we reinsert it in the active
103  * array after it has expired its current timeslice. (it will not
104  * continue to run immediately, it will still roundrobin with
105  * other interactive tasks.)
106  *
107  * This part scales the interactivity limit depending on niceness.
108  *
109  * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
110  * Here are a few examples of different nice levels:
111  *
112  *  TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
113  *  TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
114  *  TASK_INTERACTIVE(  0): [1,1,1,1,0,0,0,0,0,0,0]
115  *  TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
116  *  TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
117  *
118  * (the X axis represents the possible -5 ... 0 ... +5 dynamic
119  *  priority range a task can explore, a value of '1' means the
120  *  task is rated interactive.)
121  *
122  * Ie. nice +19 tasks can never get 'interactive' enough to be
123  * reinserted into the active array. And only heavily CPU-hog nice -20
124  * tasks will be expired. Default nice 0 tasks are somewhere between,
125  * it takes some effort for them to get interactive, but it's not
126  * too hard.
127  */
128
129 #define CURRENT_BONUS(p) \
130         (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
131                 MAX_SLEEP_AVG)
132
133 #define GRANULARITY     (10 * HZ / 1000 ? : 1)
134
135 #ifdef CONFIG_SMP
136 #define TIMESLICE_GRANULARITY(p)        (GRANULARITY * \
137                 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
138                         num_online_cpus())
139 #else
140 #define TIMESLICE_GRANULARITY(p)        (GRANULARITY * \
141                 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
142 #endif
143
144 #define SCALE(v1,v1_max,v2_max) \
145         (v1) * (v2_max) / (v1_max)
146
147 #define DELTA(p) \
148         (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
149
150 #define TASK_INTERACTIVE(p) \
151         ((p)->prio <= (p)->static_prio - DELTA(p))
152
153 #define INTERACTIVE_SLEEP(p) \
154         (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
155                 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
156
157 #define TASK_PREEMPTS_CURR(p, rq) \
158         ((p)->prio < (rq)->curr->prio)
159
160 /*
161  * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
162  * to time slice values: [800ms ... 100ms ... 5ms]
163  *
164  * The higher a thread's priority, the bigger timeslices
165  * it gets during one round of execution. But even the lowest
166  * priority thread gets MIN_TIMESLICE worth of execution time.
167  */
168
169 #define SCALE_PRIO(x, prio) \
170         max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO/2), MIN_TIMESLICE)
171
172 static inline unsigned int task_timeslice(task_t *p)
173 {
174         if (p->static_prio < NICE_TO_PRIO(0))
175                 return SCALE_PRIO(DEF_TIMESLICE*4, p->static_prio);
176         else
177                 return SCALE_PRIO(DEF_TIMESLICE, p->static_prio);
178 }
179 #define task_hot(p, now, sd) ((long long) ((now) - (p)->last_ran)       \
180                                 < (long long) (sd)->cache_hot_time)
181
182 /*
183  * These are the runqueue data structures:
184  */
185
186 #define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
187
188 typedef struct runqueue runqueue_t;
189
190 struct prio_array {
191         unsigned int nr_active;
192         unsigned long bitmap[BITMAP_SIZE];
193         struct list_head queue[MAX_PRIO];
194 };
195
196 /*
197  * This is the main, per-CPU runqueue data structure.
198  *
199  * Locking rule: those places that want to lock multiple runqueues
200  * (such as the load balancing or the thread migration code), lock
201  * acquire operations must be ordered by ascending &runqueue.
202  */
203 struct runqueue {
204         spinlock_t lock;
205
206         /*
207          * nr_running and cpu_load should be in the same cacheline because
208          * remote CPUs use both these fields when doing load calculation.
209          */
210         unsigned long nr_running;
211 #ifdef CONFIG_SMP
212         unsigned long cpu_load;
213 #endif
214         unsigned long long nr_switches;
215
216         /*
217          * This is part of a global counter where only the total sum
218          * over all CPUs matters. A task can increase this counter on
219          * one CPU and if it got migrated afterwards it may decrease
220          * it on another CPU. Always updated under the runqueue lock:
221          */
222         unsigned long nr_uninterruptible;
223
224         unsigned long expired_timestamp;
225         unsigned long long timestamp_last_tick;
226         task_t *curr, *idle;
227         struct mm_struct *prev_mm;
228         prio_array_t *active, *expired, arrays[2];
229         int best_expired_prio;
230         atomic_t nr_iowait;
231
232 #ifdef CONFIG_SMP
233         struct sched_domain *sd;
234
235         /* For active balancing */
236         int active_balance;
237         int push_cpu;
238
239         task_t *migration_thread;
240         struct list_head migration_queue;
241 #endif
242 #ifdef CONFIG_VSERVER_HARDCPU
243         struct list_head hold_queue;
244         int idle_tokens;
245 #endif
246
247 #ifdef CONFIG_SCHEDSTATS
248         /* latency stats */
249         struct sched_info rq_sched_info;
250
251         /* sys_sched_yield() stats */
252         unsigned long yld_exp_empty;
253         unsigned long yld_act_empty;
254         unsigned long yld_both_empty;
255         unsigned long yld_cnt;
256
257         /* schedule() stats */
258         unsigned long sched_switch;
259         unsigned long sched_cnt;
260         unsigned long sched_goidle;
261
262         /* try_to_wake_up() stats */
263         unsigned long ttwu_cnt;
264         unsigned long ttwu_local;
265 #endif
266 };
267
268 static DEFINE_PER_CPU(struct runqueue, runqueues);
269
270 #define for_each_domain(cpu, domain) \
271         for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
272
273 #define cpu_rq(cpu)             (&per_cpu(runqueues, (cpu)))
274 #define this_rq()               (&__get_cpu_var(runqueues))
275 #define task_rq(p)              cpu_rq(task_cpu(p))
276 #define cpu_curr(cpu)           (cpu_rq(cpu)->curr)
277
278 /*
279  * Default context-switch locking:
280  */
281 #ifndef prepare_arch_switch
282 # define prepare_arch_switch(rq, next)  do { } while (0)
283 # define finish_arch_switch(rq, next)   spin_unlock_irq(&(rq)->lock)
284 # define task_running(rq, p)            ((rq)->curr == (p))
285 #endif
286
287 /*
288  * task_rq_lock - lock the runqueue a given task resides on and disable
289  * interrupts.  Note the ordering: we can safely lookup the task_rq without
290  * explicitly disabling preemption.
291  */
292 static inline runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
293         __acquires(rq->lock)
294 {
295         struct runqueue *rq;
296
297 repeat_lock_task:
298         local_irq_save(*flags);
299         rq = task_rq(p);
300         spin_lock(&rq->lock);
301         if (unlikely(rq != task_rq(p))) {
302                 spin_unlock_irqrestore(&rq->lock, *flags);
303                 goto repeat_lock_task;
304         }
305         return rq;
306 }
307
308 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
309         __releases(rq->lock)
310 {
311         spin_unlock_irqrestore(&rq->lock, *flags);
312 }
313
314 #ifdef CONFIG_SCHEDSTATS
315 /*
316  * bump this up when changing the output format or the meaning of an existing
317  * format, so that tools can adapt (or abort)
318  */
319 #define SCHEDSTAT_VERSION 11
320
321 static int show_schedstat(struct seq_file *seq, void *v)
322 {
323         int cpu;
324
325         seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
326         seq_printf(seq, "timestamp %lu\n", jiffies);
327         for_each_online_cpu(cpu) {
328                 runqueue_t *rq = cpu_rq(cpu);
329 #ifdef CONFIG_SMP
330                 struct sched_domain *sd;
331                 int dcnt = 0;
332 #endif
333
334                 /* runqueue-specific stats */
335                 seq_printf(seq,
336                     "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
337                     cpu, rq->yld_both_empty,
338                     rq->yld_act_empty, rq->yld_exp_empty, rq->yld_cnt,
339                     rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
340                     rq->ttwu_cnt, rq->ttwu_local,
341                     rq->rq_sched_info.cpu_time,
342                     rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
343
344                 seq_printf(seq, "\n");
345
346 #ifdef CONFIG_SMP
347                 /* domain-specific stats */
348                 for_each_domain(cpu, sd) {
349                         enum idle_type itype;
350                         char mask_str[NR_CPUS];
351
352                         cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
353                         seq_printf(seq, "domain%d %s", dcnt++, mask_str);
354                         for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
355                                         itype++) {
356                                 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu",
357                                     sd->lb_cnt[itype],
358                                     sd->lb_balanced[itype],
359                                     sd->lb_failed[itype],
360                                     sd->lb_imbalance[itype],
361                                     sd->lb_gained[itype],
362                                     sd->lb_hot_gained[itype],
363                                     sd->lb_nobusyq[itype],
364                                     sd->lb_nobusyg[itype]);
365                         }
366                         seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu\n",
367                             sd->alb_cnt, sd->alb_failed, sd->alb_pushed,
368                             sd->sbe_pushed, sd->sbe_attempts,
369                             sd->ttwu_wake_remote, sd->ttwu_move_affine, sd->ttwu_move_balance);
370                 }
371 #endif
372         }
373         return 0;
374 }
375
376 static int schedstat_open(struct inode *inode, struct file *file)
377 {
378         unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
379         char *buf = kmalloc(size, GFP_KERNEL);
380         struct seq_file *m;
381         int res;
382
383         if (!buf)
384                 return -ENOMEM;
385         res = single_open(file, show_schedstat, NULL);
386         if (!res) {
387                 m = file->private_data;
388                 m->buf = buf;
389                 m->size = size;
390         } else
391                 kfree(buf);
392         return res;
393 }
394
395 struct file_operations proc_schedstat_operations = {
396         .open    = schedstat_open,
397         .read    = seq_read,
398         .llseek  = seq_lseek,
399         .release = single_release,
400 };
401
402 # define schedstat_inc(rq, field)       do { (rq)->field++; } while (0)
403 # define schedstat_add(rq, field, amt)  do { (rq)->field += (amt); } while (0)
404 #else /* !CONFIG_SCHEDSTATS */
405 # define schedstat_inc(rq, field)       do { } while (0)
406 # define schedstat_add(rq, field, amt)  do { } while (0)
407 #endif
408
409 /*
410  * rq_lock - lock a given runqueue and disable interrupts.
411  */
412 static inline runqueue_t *this_rq_lock(void)
413         __acquires(rq->lock)
414 {
415         runqueue_t *rq;
416
417         local_irq_disable();
418         rq = this_rq();
419         spin_lock(&rq->lock);
420
421         return rq;
422 }
423
424 #ifdef CONFIG_SCHED_SMT
425 static int cpu_and_siblings_are_idle(int cpu)
426 {
427         int sib;
428         for_each_cpu_mask(sib, cpu_sibling_map[cpu]) {
429                 if (idle_cpu(sib))
430                         continue;
431                 return 0;
432         }
433
434         return 1;
435 }
436 #else
437 #define cpu_and_siblings_are_idle(A) idle_cpu(A)
438 #endif
439
440 #ifdef CONFIG_SCHEDSTATS
441 /*
442  * Called when a process is dequeued from the active array and given
443  * the cpu.  We should note that with the exception of interactive
444  * tasks, the expired queue will become the active queue after the active
445  * queue is empty, without explicitly dequeuing and requeuing tasks in the
446  * expired queue.  (Interactive tasks may be requeued directly to the
447  * active queue, thus delaying tasks in the expired queue from running;
448  * see scheduler_tick()).
449  *
450  * This function is only called from sched_info_arrive(), rather than
451  * dequeue_task(). Even though a task may be queued and dequeued multiple
452  * times as it is shuffled about, we're really interested in knowing how
453  * long it was from the *first* time it was queued to the time that it
454  * finally hit a cpu.
455  */
456 static inline void sched_info_dequeued(task_t *t)
457 {
458         t->sched_info.last_queued = 0;
459 }
460
461 /*
462  * Called when a task finally hits the cpu.  We can now calculate how
463  * long it was waiting to run.  We also note when it began so that we
464  * can keep stats on how long its timeslice is.
465  */
466 static inline void sched_info_arrive(task_t *t)
467 {
468         unsigned long now = jiffies, diff = 0;
469         struct runqueue *rq = task_rq(t);
470
471         if (t->sched_info.last_queued)
472                 diff = now - t->sched_info.last_queued;
473         sched_info_dequeued(t);
474         t->sched_info.run_delay += diff;
475         t->sched_info.last_arrival = now;
476         t->sched_info.pcnt++;
477
478         if (!rq)
479                 return;
480
481         rq->rq_sched_info.run_delay += diff;
482         rq->rq_sched_info.pcnt++;
483 }
484
485 /*
486  * Called when a process is queued into either the active or expired
487  * array.  The time is noted and later used to determine how long we
488  * had to wait for us to reach the cpu.  Since the expired queue will
489  * become the active queue after active queue is empty, without dequeuing
490  * and requeuing any tasks, we are interested in queuing to either. It
491  * is unusual but not impossible for tasks to be dequeued and immediately
492  * requeued in the same or another array: this can happen in sched_yield(),
493  * set_user_nice(), and even load_balance() as it moves tasks from runqueue
494  * to runqueue.
495  *
496  * This function is only called from enqueue_task(), but also only updates
497  * the timestamp if it is already not set.  It's assumed that
498  * sched_info_dequeued() will clear that stamp when appropriate.
499  */
500 static inline void sched_info_queued(task_t *t)
501 {
502         if (!t->sched_info.last_queued)
503                 t->sched_info.last_queued = jiffies;
504 }
505
506 /*
507  * Called when a process ceases being the active-running process, either
508  * voluntarily or involuntarily.  Now we can calculate how long we ran.
509  */
510 static inline void sched_info_depart(task_t *t)
511 {
512         struct runqueue *rq = task_rq(t);
513         unsigned long diff = jiffies - t->sched_info.last_arrival;
514
515         t->sched_info.cpu_time += diff;
516
517         if (rq)
518                 rq->rq_sched_info.cpu_time += diff;
519 }
520
521 /*
522  * Called when tasks are switched involuntarily due, typically, to expiring
523  * their time slice.  (This may also be called when switching to or from
524  * the idle task.)  We are only called when prev != next.
525  */
526 static inline void sched_info_switch(task_t *prev, task_t *next)
527 {
528         struct runqueue *rq = task_rq(prev);
529
530         /*
531          * prev now departs the cpu.  It's not interesting to record
532          * stats about how efficient we were at scheduling the idle
533          * process, however.
534          */
535         if (prev != rq->idle)
536                 sched_info_depart(prev);
537
538         if (next != rq->idle)
539                 sched_info_arrive(next);
540 }
541 #else
542 #define sched_info_queued(t)            do { } while (0)
543 #define sched_info_switch(t, next)      do { } while (0)
544 #endif /* CONFIG_SCHEDSTATS */
545
546 /*
547  * Adding/removing a task to/from a priority array:
548  */
549 static void dequeue_task(struct task_struct *p, prio_array_t *array)
550 {
551         BUG_ON(p->state & TASK_ONHOLD);
552         array->nr_active--;
553         list_del(&p->run_list);
554         if (list_empty(array->queue + p->prio))
555                 __clear_bit(p->prio, array->bitmap);
556 }
557
558 static void enqueue_task(struct task_struct *p, prio_array_t *array)
559 {
560         BUG_ON(p->state & TASK_ONHOLD);
561         sched_info_queued(p);
562         list_add_tail(&p->run_list, array->queue + p->prio);
563         __set_bit(p->prio, array->bitmap);
564         array->nr_active++;
565         p->array = array;
566 }
567
568 /*
569  * Put task to the end of the run list without the overhead of dequeue
570  * followed by enqueue.
571  */
572 static void requeue_task(struct task_struct *p, prio_array_t *array)
573 {
574         BUG_ON(p->state & TASK_ONHOLD);
575         list_move_tail(&p->run_list, array->queue + p->prio);
576 }
577
578 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
579 {
580         BUG_ON(p->state & TASK_ONHOLD);
581         list_add(&p->run_list, array->queue + p->prio);
582         __set_bit(p->prio, array->bitmap);
583         array->nr_active++;
584         p->array = array;
585 }
586
587 /*
588  * effective_prio - return the priority that is based on the static
589  * priority but is modified by bonuses/penalties.
590  *
591  * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
592  * into the -5 ... 0 ... +5 bonus/penalty range.
593  *
594  * We use 25% of the full 0...39 priority range so that:
595  *
596  * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
597  * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
598  *
599  * Both properties are important to certain workloads.
600  */
601 static int effective_prio(task_t *p)
602 {
603         int bonus, prio;
604         struct vx_info *vxi;
605
606         if (rt_task(p))
607                 return p->prio;
608
609         bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
610
611         prio = p->static_prio - bonus;
612
613         if ((vxi = p->vx_info) &&
614                 vx_info_flags(vxi, VXF_SCHED_PRIO, 0))
615                 prio += vx_effective_vavavoom(vxi, MAX_USER_PRIO);
616
617         if (prio < MAX_RT_PRIO)
618                 prio = MAX_RT_PRIO;
619         if (prio > MAX_PRIO-1)
620                 prio = MAX_PRIO-1;
621         return prio;
622 }
623
624 /*
625  * __activate_task - move a task to the runqueue.
626  */
627 static inline void __activate_task(task_t *p, runqueue_t *rq)
628 {
629         enqueue_task(p, rq->active);
630         rq->nr_running++;
631 }
632
633 /*
634  * __activate_idle_task - move idle task to the _front_ of runqueue.
635  */
636 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
637 {
638         enqueue_task_head(p, rq->active);
639         rq->nr_running++;
640 }
641
642 static void recalc_task_prio(task_t *p, unsigned long long now)
643 {
644         /* Caller must always ensure 'now >= p->timestamp' */
645         unsigned long long __sleep_time = now - p->timestamp;
646         unsigned long sleep_time;
647
648         if (__sleep_time > NS_MAX_SLEEP_AVG)
649                 sleep_time = NS_MAX_SLEEP_AVG;
650         else
651                 sleep_time = (unsigned long)__sleep_time;
652
653         if (likely(sleep_time > 0)) {
654                 /*
655                  * User tasks that sleep a long time are categorised as
656                  * idle and will get just interactive status to stay active &
657                  * prevent them suddenly becoming cpu hogs and starving
658                  * other processes.
659                  */
660                 if (p->mm && p->activated != -1 &&
661                         sleep_time > INTERACTIVE_SLEEP(p)) {
662                                 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
663                                                 DEF_TIMESLICE);
664                 } else {
665                         /*
666                          * The lower the sleep avg a task has the more
667                          * rapidly it will rise with sleep time.
668                          */
669                         sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
670
671                         /*
672                          * Tasks waking from uninterruptible sleep are
673                          * limited in their sleep_avg rise as they
674                          * are likely to be waiting on I/O
675                          */
676                         if (p->activated == -1 && p->mm) {
677                                 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
678                                         sleep_time = 0;
679                                 else if (p->sleep_avg + sleep_time >=
680                                                 INTERACTIVE_SLEEP(p)) {
681                                         p->sleep_avg = INTERACTIVE_SLEEP(p);
682                                         sleep_time = 0;
683                                 }
684                         }
685
686                         /*
687                          * This code gives a bonus to interactive tasks.
688                          *
689                          * The boost works by updating the 'average sleep time'
690                          * value here, based on ->timestamp. The more time a
691                          * task spends sleeping, the higher the average gets -
692                          * and the higher the priority boost gets as well.
693                          */
694                         p->sleep_avg += sleep_time;
695
696                         if (p->sleep_avg > NS_MAX_SLEEP_AVG)
697                                 p->sleep_avg = NS_MAX_SLEEP_AVG;
698                 }
699         }
700
701         p->prio = effective_prio(p);
702 }
703
704 /*
705  * activate_task - move a task to the runqueue and do priority recalculation
706  *
707  * Update all the scheduling statistics stuff. (sleep average
708  * calculation, priority modifiers, etc.)
709  */
710 static void activate_task(task_t *p, runqueue_t *rq, int local)
711 {
712         unsigned long long now;
713
714         now = sched_clock();
715 #ifdef CONFIG_SMP
716         if (!local) {
717                 /* Compensate for drifting sched_clock */
718                 runqueue_t *this_rq = this_rq();
719                 now = (now - this_rq->timestamp_last_tick)
720                         + rq->timestamp_last_tick;
721         }
722 #endif
723
724         recalc_task_prio(p, now);
725
726         /*
727          * This checks to make sure it's not an uninterruptible task
728          * that is now waking up.
729          */
730         if (!p->activated) {
731                 /*
732                  * Tasks which were woken up by interrupts (ie. hw events)
733                  * are most likely of interactive nature. So we give them
734                  * the credit of extending their sleep time to the period
735                  * of time they spend on the runqueue, waiting for execution
736                  * on a CPU, first time around:
737                  */
738                 if (in_interrupt())
739                         p->activated = 2;
740                 else {
741                         /*
742                          * Normal first-time wakeups get a credit too for
743                          * on-runqueue time, but it will be weighted down:
744                          */
745                         p->activated = 1;
746                 }
747         }
748         p->timestamp = now;
749
750         vx_activate_task(p);
751         __activate_task(p, rq);
752 }
753
754 /*
755  * deactivate_task - remove a task from the runqueue.
756  */
757 static void __deactivate_task(struct task_struct *p, runqueue_t *rq)
758 {
759         rq->nr_running--;
760         dequeue_task(p, p->array);
761         p->array = NULL;
762 }
763
764 static inline
765 void deactivate_task(struct task_struct *p, runqueue_t *rq)
766 {
767         vx_deactivate_task(p);
768         __deactivate_task(p, rq);
769 }
770
771
772 #ifdef  CONFIG_VSERVER_HARDCPU
773 /*
774  * vx_hold_task - put a task on the hold queue
775  */
776 static inline
777 void vx_hold_task(struct vx_info *vxi,
778         struct task_struct *p, runqueue_t *rq)
779 {
780         __deactivate_task(p, rq);
781         p->state |= TASK_ONHOLD;
782         /* a new one on hold */
783         vx_onhold_inc(vxi);
784         list_add_tail(&p->run_list, &rq->hold_queue);
785 }
786
787 /*
788  * vx_unhold_task - put a task back to the runqueue
789  */
790 static inline
791 void vx_unhold_task(struct vx_info *vxi,
792         struct task_struct *p, runqueue_t *rq)
793 {
794         list_del(&p->run_list);
795         /* one less waiting */
796         vx_onhold_dec(vxi);
797         p->state &= ~TASK_ONHOLD;
798         enqueue_task(p, rq->expired);
799         rq->nr_running++;
800
801         if (p->static_prio < rq->best_expired_prio)
802                 rq->best_expired_prio = p->static_prio;
803 }
804 #else
805 static inline
806 void vx_hold_task(struct vx_info *vxi,
807         struct task_struct *p, runqueue_t *rq)
808 {
809         return;
810 }
811
812 static inline
813 void vx_unhold_task(struct vx_info *vxi,
814         struct task_struct *p, runqueue_t *rq)
815 {
816         return;
817 }
818 #endif /* CONFIG_VSERVER_HARDCPU */
819
820
821 /*
822  * resched_task - mark a task 'to be rescheduled now'.
823  *
824  * On UP this means the setting of the need_resched flag, on SMP it
825  * might also involve a cross-CPU call to trigger the scheduler on
826  * the target CPU.
827  */
828 #ifdef CONFIG_SMP
829 static void resched_task(task_t *p)
830 {
831         int need_resched, nrpolling;
832
833         assert_spin_locked(&task_rq(p)->lock);
834
835         /* minimise the chance of sending an interrupt to poll_idle() */
836         nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
837         need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
838         nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
839
840         if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
841                 smp_send_reschedule(task_cpu(p));
842 }
843 #else
844 static inline void resched_task(task_t *p)
845 {
846         set_tsk_need_resched(p);
847 }
848 #endif
849
850 /**
851  * task_curr - is this task currently executing on a CPU?
852  * @p: the task in question.
853  */
854 inline int task_curr(const task_t *p)
855 {
856         return cpu_curr(task_cpu(p)) == p;
857 }
858
859 #ifdef CONFIG_SMP
860 enum request_type {
861         REQ_MOVE_TASK,
862         REQ_SET_DOMAIN,
863 };
864
865 typedef struct {
866         struct list_head list;
867         enum request_type type;
868
869         /* For REQ_MOVE_TASK */
870         task_t *task;
871         int dest_cpu;
872
873         /* For REQ_SET_DOMAIN */
874         struct sched_domain *sd;
875
876         struct completion done;
877 } migration_req_t;
878
879 /*
880  * The task's runqueue lock must be held.
881  * Returns true if you have to wait for migration thread.
882  */
883 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
884 {
885         runqueue_t *rq = task_rq(p);
886
887         /*
888          * If the task is not on a runqueue (and not running), then
889          * it is sufficient to simply update the task's cpu field.
890          */
891         if (!p->array && !task_running(rq, p)) {
892                 set_task_cpu(p, dest_cpu);
893                 return 0;
894         }
895
896         init_completion(&req->done);
897         req->type = REQ_MOVE_TASK;
898         req->task = p;
899         req->dest_cpu = dest_cpu;
900         list_add(&req->list, &rq->migration_queue);
901         return 1;
902 }
903
904 /*
905  * wait_task_inactive - wait for a thread to unschedule.
906  *
907  * The caller must ensure that the task *will* unschedule sometime soon,
908  * else this function might spin for a *long* time. This function can't
909  * be called with interrupts off, or it may introduce deadlock with
910  * smp_call_function() if an IPI is sent by the same process we are
911  * waiting to become inactive.
912  */
913 void wait_task_inactive(task_t * p)
914 {
915         unsigned long flags;
916         runqueue_t *rq;
917         int preempted;
918
919 repeat:
920         rq = task_rq_lock(p, &flags);
921         /* Must be off runqueue entirely, not preempted. */
922         if (unlikely(p->array || task_running(rq, p))) {
923                 /* If it's preempted, we yield.  It could be a while. */
924                 preempted = !task_running(rq, p);
925                 task_rq_unlock(rq, &flags);
926                 cpu_relax();
927                 if (preempted)
928                         yield();
929                 goto repeat;
930         }
931         task_rq_unlock(rq, &flags);
932 }
933
934 /***
935  * kick_process - kick a running thread to enter/exit the kernel
936  * @p: the to-be-kicked thread
937  *
938  * Cause a process which is running on another CPU to enter
939  * kernel-mode, without any delay. (to get signals handled.)
940  *
941  * NOTE: this function doesnt have to take the runqueue lock,
942  * because all it wants to ensure is that the remote task enters
943  * the kernel. If the IPI races and the task has been migrated
944  * to another CPU then no harm is done and the purpose has been
945  * achieved as well.
946  */
947 void kick_process(task_t *p)
948 {
949         int cpu;
950
951         preempt_disable();
952         cpu = task_cpu(p);
953         if ((cpu != smp_processor_id()) && task_curr(p))
954                 smp_send_reschedule(cpu);
955         preempt_enable();
956 }
957
958 /*
959  * Return a low guess at the load of a migration-source cpu.
960  *
961  * We want to under-estimate the load of migration sources, to
962  * balance conservatively.
963  */
964 static inline unsigned long source_load(int cpu)
965 {
966         runqueue_t *rq = cpu_rq(cpu);
967         unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
968
969         return min(rq->cpu_load, load_now);
970 }
971
972 /*
973  * Return a high guess at the load of a migration-target cpu
974  */
975 static inline unsigned long target_load(int cpu)
976 {
977         runqueue_t *rq = cpu_rq(cpu);
978         unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
979
980         return max(rq->cpu_load, load_now);
981 }
982
983 #endif
984
985 /*
986  * wake_idle() will wake a task on an idle cpu if task->cpu is
987  * not idle and an idle cpu is available.  The span of cpus to
988  * search starts with cpus closest then further out as needed,
989  * so we always favor a closer, idle cpu.
990  *
991  * Returns the CPU we should wake onto.
992  */
993 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
994 static int wake_idle(int cpu, task_t *p)
995 {
996         cpumask_t tmp;
997         struct sched_domain *sd;
998         int i;
999
1000         if (idle_cpu(cpu))
1001                 return cpu;
1002
1003         for_each_domain(cpu, sd) {
1004                 if (sd->flags & SD_WAKE_IDLE) {
1005                         cpus_and(tmp, sd->span, cpu_online_map);
1006                         cpus_and(tmp, tmp, p->cpus_allowed);
1007                         for_each_cpu_mask(i, tmp) {
1008                                 if (idle_cpu(i))
1009                                         return i;
1010                         }
1011                 }
1012                 else break;
1013         }
1014         return cpu;
1015 }
1016 #else
1017 static inline int wake_idle(int cpu, task_t *p)
1018 {
1019         return cpu;
1020 }
1021 #endif
1022
1023 /***
1024  * try_to_wake_up - wake up a thread
1025  * @p: the to-be-woken-up thread
1026  * @state: the mask of task states that can be woken
1027  * @sync: do a synchronous wakeup?
1028  *
1029  * Put it on the run-queue if it's not already there. The "current"
1030  * thread is always on the run-queue (except when the actual
1031  * re-schedule is in progress), and as such you're allowed to do
1032  * the simpler "current->state = TASK_RUNNING" to mark yourself
1033  * runnable without the overhead of this.
1034  *
1035  * returns failure only if the task is already active.
1036  */
1037 static int try_to_wake_up(task_t * p, unsigned int state, int sync)
1038 {
1039         int cpu, this_cpu, success = 0;
1040         unsigned long flags;
1041         long old_state;
1042         runqueue_t *rq;
1043 #ifdef CONFIG_SMP
1044         unsigned long load, this_load;
1045         struct sched_domain *sd;
1046         int new_cpu;
1047 #endif
1048
1049         rq = task_rq_lock(p, &flags);
1050         old_state = p->state;
1051
1052         /* we need to unhold suspended tasks */
1053         if (old_state & TASK_ONHOLD) {
1054                 vx_unhold_task(p->vx_info, p, rq);
1055                 old_state = p->state;
1056         }
1057         if (!(old_state & state))
1058                 goto out;
1059
1060         if (p->array)
1061                 goto out_running;
1062
1063         cpu = task_cpu(p);
1064         this_cpu = smp_processor_id();
1065
1066 #ifdef CONFIG_SMP
1067         if (unlikely(task_running(rq, p)))
1068                 goto out_activate;
1069
1070 #ifdef CONFIG_SCHEDSTATS
1071         schedstat_inc(rq, ttwu_cnt);
1072         if (cpu == this_cpu) {
1073                 schedstat_inc(rq, ttwu_local);
1074         } else {
1075                 for_each_domain(this_cpu, sd) {
1076                         if (cpu_isset(cpu, sd->span)) {
1077                                 schedstat_inc(sd, ttwu_wake_remote);
1078                                 break;
1079                         }
1080                 }
1081         }
1082 #endif
1083
1084         new_cpu = cpu;
1085         if (cpu == this_cpu || unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1086                 goto out_set_cpu;
1087
1088         load = source_load(cpu);
1089         this_load = target_load(this_cpu);
1090
1091         /*
1092          * If sync wakeup then subtract the (maximum possible) effect of
1093          * the currently running task from the load of the current CPU:
1094          */
1095         if (sync)
1096                 this_load -= SCHED_LOAD_SCALE;
1097
1098         /* Don't pull the task off an idle CPU to a busy one */
1099         if (load < SCHED_LOAD_SCALE/2 && this_load > SCHED_LOAD_SCALE/2)
1100                 goto out_set_cpu;
1101
1102         new_cpu = this_cpu; /* Wake to this CPU if we can */
1103
1104         /*
1105          * Scan domains for affine wakeup and passive balancing
1106          * possibilities.
1107          */
1108         for_each_domain(this_cpu, sd) {
1109                 unsigned int imbalance;
1110                 /*
1111                  * Start passive balancing when half the imbalance_pct
1112                  * limit is reached.
1113                  */
1114                 imbalance = sd->imbalance_pct + (sd->imbalance_pct - 100) / 2;
1115
1116                 if ((sd->flags & SD_WAKE_AFFINE) &&
1117                                 !task_hot(p, rq->timestamp_last_tick, sd)) {
1118                         /*
1119                          * This domain has SD_WAKE_AFFINE and p is cache cold
1120                          * in this domain.
1121                          */
1122                         if (cpu_isset(cpu, sd->span)) {
1123                                 schedstat_inc(sd, ttwu_move_affine);
1124                                 goto out_set_cpu;
1125                         }
1126                 } else if ((sd->flags & SD_WAKE_BALANCE) &&
1127                                 imbalance*this_load <= 100*load) {
1128                         /*
1129                          * This domain has SD_WAKE_BALANCE and there is
1130                          * an imbalance.
1131                          */
1132                         if (cpu_isset(cpu, sd->span)) {
1133                                 schedstat_inc(sd, ttwu_move_balance);
1134                                 goto out_set_cpu;
1135                         }
1136                 }
1137         }
1138
1139         new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1140 out_set_cpu:
1141         new_cpu = wake_idle(new_cpu, p);
1142         if (new_cpu != cpu) {
1143                 set_task_cpu(p, new_cpu);
1144                 task_rq_unlock(rq, &flags);
1145                 /* might preempt at this point */
1146                 rq = task_rq_lock(p, &flags);
1147                 old_state = p->state;
1148                 if (!(old_state & state))
1149                         goto out;
1150                 if (p->array)
1151                         goto out_running;
1152
1153                 this_cpu = smp_processor_id();
1154                 cpu = task_cpu(p);
1155         }
1156
1157 out_activate:
1158 #endif /* CONFIG_SMP */
1159         if (old_state == TASK_UNINTERRUPTIBLE) {
1160                 rq->nr_uninterruptible--;
1161                 /*
1162                  * Tasks on involuntary sleep don't earn
1163                  * sleep_avg beyond just interactive state.
1164                  */
1165                 p->activated = -1;
1166         }
1167
1168         /*
1169          * Sync wakeups (i.e. those types of wakeups where the waker
1170          * has indicated that it will leave the CPU in short order)
1171          * don't trigger a preemption, if the woken up task will run on
1172          * this cpu. (in this case the 'I will reschedule' promise of
1173          * the waker guarantees that the freshly woken up task is going
1174          * to be considered on this CPU.)
1175          */
1176         activate_task(p, rq, cpu == this_cpu);
1177         /* this is to get the accounting behind the load update */
1178         if (old_state == TASK_UNINTERRUPTIBLE)
1179                 vx_uninterruptible_dec(p);
1180         if (!sync || cpu != this_cpu) {
1181                 if (TASK_PREEMPTS_CURR(p, rq))
1182                         resched_task(rq->curr);
1183         }
1184         success = 1;
1185
1186 out_running:
1187         p->state = TASK_RUNNING;
1188 out:
1189         task_rq_unlock(rq, &flags);
1190
1191         return success;
1192 }
1193
1194 int fastcall wake_up_process(task_t * p)
1195 {
1196         return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1197                                  TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1198 }
1199
1200 EXPORT_SYMBOL(wake_up_process);
1201
1202 int fastcall wake_up_state(task_t *p, unsigned int state)
1203 {
1204         return try_to_wake_up(p, state, 0);
1205 }
1206
1207 #ifdef CONFIG_SMP
1208 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1209                            struct sched_domain *sd);
1210 #endif
1211
1212 /*
1213  * Perform scheduler related setup for a newly forked process p.
1214  * p is forked by current.
1215  */
1216 void fastcall sched_fork(task_t *p)
1217 {
1218         /*
1219          * We mark the process as running here, but have not actually
1220          * inserted it onto the runqueue yet. This guarantees that
1221          * nobody will actually run it, and a signal or other external
1222          * event cannot wake it up and insert it on the runqueue either.
1223          */
1224         p->state = TASK_RUNNING;
1225         INIT_LIST_HEAD(&p->run_list);
1226         p->array = NULL;
1227         spin_lock_init(&p->switch_lock);
1228 #ifdef CONFIG_SCHEDSTATS
1229         memset(&p->sched_info, 0, sizeof(p->sched_info));
1230 #endif
1231 #ifdef CONFIG_PREEMPT
1232         /*
1233          * During context-switch we hold precisely one spinlock, which
1234          * schedule_tail drops. (in the common case it's this_rq()->lock,
1235          * but it also can be p->switch_lock.) So we compensate with a count
1236          * of 1. Also, we want to start with kernel preemption disabled.
1237          */
1238         p->thread_info->preempt_count = 1;
1239 #endif
1240         /*
1241          * Share the timeslice between parent and child, thus the
1242          * total amount of pending timeslices in the system doesn't change,
1243          * resulting in more scheduling fairness.
1244          */
1245         local_irq_disable();
1246         p->time_slice = (current->time_slice + 1) >> 1;
1247         /*
1248          * The remainder of the first timeslice might be recovered by
1249          * the parent if the child exits early enough.
1250          */
1251         p->first_time_slice = 1;
1252         current->time_slice >>= 1;
1253         p->timestamp = sched_clock();
1254         if (unlikely(!current->time_slice)) {
1255                 /*
1256                  * This case is rare, it happens when the parent has only
1257                  * a single jiffy left from its timeslice. Taking the
1258                  * runqueue lock is not a problem.
1259                  */
1260                 current->time_slice = 1;
1261                 preempt_disable();
1262                 scheduler_tick();
1263                 local_irq_enable();
1264                 preempt_enable();
1265         } else
1266                 local_irq_enable();
1267 }
1268
1269 /*
1270  * wake_up_new_task - wake up a newly created task for the first time.
1271  *
1272  * This function will do some initial scheduler statistics housekeeping
1273  * that must be done for every newly created context, then puts the task
1274  * on the runqueue and wakes it.
1275  */
1276 void fastcall wake_up_new_task(task_t * p, unsigned long clone_flags)
1277 {
1278         unsigned long flags;
1279         int this_cpu, cpu;
1280         runqueue_t *rq, *this_rq;
1281
1282         rq = task_rq_lock(p, &flags);
1283         cpu = task_cpu(p);
1284         this_cpu = smp_processor_id();
1285
1286         BUG_ON(p->state != TASK_RUNNING);
1287
1288         /*
1289          * We decrease the sleep average of forking parents
1290          * and children as well, to keep max-interactive tasks
1291          * from forking tasks that are max-interactive. The parent
1292          * (current) is done further down, under its lock.
1293          */
1294         p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1295                 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1296
1297         p->prio = effective_prio(p);
1298
1299         vx_activate_task(p);
1300         if (likely(cpu == this_cpu)) {
1301                 if (!(clone_flags & CLONE_VM)) {
1302                         /*
1303                          * The VM isn't cloned, so we're in a good position to
1304                          * do child-runs-first in anticipation of an exec. This
1305                          * usually avoids a lot of COW overhead.
1306                          */
1307                         if (unlikely(!current->array))
1308                                 __activate_task(p, rq);
1309                         else {
1310                                 p->prio = current->prio;
1311                                 BUG_ON(p->state & TASK_ONHOLD);
1312                                 list_add_tail(&p->run_list, &current->run_list);
1313                                 p->array = current->array;
1314                                 p->array->nr_active++;
1315                                 rq->nr_running++;
1316                         }
1317                         set_need_resched();
1318                 } else
1319                         /* Run child last */
1320                         __activate_task(p, rq);
1321                 /*
1322                  * We skip the following code due to cpu == this_cpu
1323                  *
1324                  *   task_rq_unlock(rq, &flags);
1325                  *   this_rq = task_rq_lock(current, &flags);
1326                  */
1327                 this_rq = rq;
1328         } else {
1329                 this_rq = cpu_rq(this_cpu);
1330
1331                 /*
1332                  * Not the local CPU - must adjust timestamp. This should
1333                  * get optimised away in the !CONFIG_SMP case.
1334                  */
1335                 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1336                                         + rq->timestamp_last_tick;
1337                 __activate_task(p, rq);
1338                 if (TASK_PREEMPTS_CURR(p, rq))
1339                         resched_task(rq->curr);
1340
1341                 /*
1342                  * Parent and child are on different CPUs, now get the
1343                  * parent runqueue to update the parent's ->sleep_avg:
1344                  */
1345                 task_rq_unlock(rq, &flags);
1346                 this_rq = task_rq_lock(current, &flags);
1347         }
1348         current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1349                 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1350         task_rq_unlock(this_rq, &flags);
1351 }
1352
1353 /*
1354  * Potentially available exiting-child timeslices are
1355  * retrieved here - this way the parent does not get
1356  * penalized for creating too many threads.
1357  *
1358  * (this cannot be used to 'generate' timeslices
1359  * artificially, because any timeslice recovered here
1360  * was given away by the parent in the first place.)
1361  */
1362 void fastcall sched_exit(task_t * p)
1363 {
1364         unsigned long flags;
1365         runqueue_t *rq;
1366
1367         /*
1368          * If the child was a (relative-) CPU hog then decrease
1369          * the sleep_avg of the parent as well.
1370          */
1371         rq = task_rq_lock(p->parent, &flags);
1372         if (p->first_time_slice) {
1373                 p->parent->time_slice += p->time_slice;
1374                 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1375                         p->parent->time_slice = task_timeslice(p);
1376         }
1377         if (p->sleep_avg < p->parent->sleep_avg)
1378                 p->parent->sleep_avg = p->parent->sleep_avg /
1379                 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1380                 (EXIT_WEIGHT + 1);
1381         task_rq_unlock(rq, &flags);
1382 }
1383
1384 /**
1385  * finish_task_switch - clean up after a task-switch
1386  * @prev: the thread we just switched away from.
1387  *
1388  * We enter this with the runqueue still locked, and finish_arch_switch()
1389  * will unlock it along with doing any other architecture-specific cleanup
1390  * actions.
1391  *
1392  * Note that we may have delayed dropping an mm in context_switch(). If
1393  * so, we finish that here outside of the runqueue lock.  (Doing it
1394  * with the lock held can cause deadlocks; see schedule() for
1395  * details.)
1396  */
1397 static inline void finish_task_switch(task_t *prev)
1398         __releases(rq->lock)
1399 {
1400         runqueue_t *rq = this_rq();
1401         struct mm_struct *mm = rq->prev_mm;
1402         unsigned long prev_task_flags;
1403
1404         rq->prev_mm = NULL;
1405
1406         /*
1407          * A task struct has one reference for the use as "current".
1408          * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1409          * calls schedule one last time. The schedule call will never return,
1410          * and the scheduled task must drop that reference.
1411          * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1412          * still held, otherwise prev could be scheduled on another cpu, die
1413          * there before we look at prev->state, and then the reference would
1414          * be dropped twice.
1415          *              Manfred Spraul <manfred@colorfullife.com>
1416          */
1417         prev_task_flags = prev->flags;
1418         finish_arch_switch(rq, prev);
1419         if (mm)
1420                 mmdrop(mm);
1421         if (unlikely(prev_task_flags & PF_DEAD))
1422                 put_task_struct(prev);
1423 }
1424
1425 /**
1426  * schedule_tail - first thing a freshly forked thread must call.
1427  * @prev: the thread we just switched away from.
1428  */
1429 asmlinkage void schedule_tail(task_t *prev)
1430         __releases(rq->lock)
1431 {
1432         finish_task_switch(prev);
1433
1434         if (current->set_child_tid)
1435                 put_user(current->pid, current->set_child_tid);
1436 }
1437
1438 /*
1439  * context_switch - switch to the new MM and the new
1440  * thread's register state.
1441  */
1442 static inline
1443 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1444 {
1445         struct mm_struct *mm = next->mm;
1446         struct mm_struct *oldmm = prev->active_mm;
1447
1448         if (unlikely(!mm)) {
1449                 next->active_mm = oldmm;
1450                 atomic_inc(&oldmm->mm_count);
1451                 enter_lazy_tlb(oldmm, next);
1452         } else
1453                 switch_mm(oldmm, mm, next);
1454
1455         if (unlikely(!prev->mm)) {
1456                 prev->active_mm = NULL;
1457                 WARN_ON(rq->prev_mm);
1458                 rq->prev_mm = oldmm;
1459         }
1460
1461         /* Here we just switch the register state and the stack. */
1462         switch_to(prev, next, prev);
1463
1464         return prev;
1465 }
1466
1467 /*
1468  * nr_running, nr_uninterruptible and nr_context_switches:
1469  *
1470  * externally visible scheduler statistics: current number of runnable
1471  * threads, current number of uninterruptible-sleeping threads, total
1472  * number of context switches performed since bootup.
1473  */
1474 unsigned long nr_running(void)
1475 {
1476         unsigned long i, sum = 0;
1477
1478         for_each_online_cpu(i)
1479                 sum += cpu_rq(i)->nr_running;
1480
1481         return sum;
1482 }
1483
1484 unsigned long nr_uninterruptible(void)
1485 {
1486         unsigned long i, sum = 0;
1487
1488         for_each_cpu(i)
1489                 sum += cpu_rq(i)->nr_uninterruptible;
1490
1491         /*
1492          * Since we read the counters lockless, it might be slightly
1493          * inaccurate. Do not allow it to go below zero though:
1494          */
1495         if (unlikely((long)sum < 0))
1496                 sum = 0;
1497
1498         return sum;
1499 }
1500
1501 unsigned long long nr_context_switches(void)
1502 {
1503         unsigned long long i, sum = 0;
1504
1505         for_each_cpu(i)
1506                 sum += cpu_rq(i)->nr_switches;
1507
1508         return sum;
1509 }
1510
1511 unsigned long nr_iowait(void)
1512 {
1513         unsigned long i, sum = 0;
1514
1515         for_each_cpu(i)
1516                 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1517
1518         return sum;
1519 }
1520
1521 #ifdef CONFIG_SMP
1522
1523 /*
1524  * double_rq_lock - safely lock two runqueues
1525  *
1526  * Note this does not disable interrupts like task_rq_lock,
1527  * you need to do so manually before calling.
1528  */
1529 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1530         __acquires(rq1->lock)
1531         __acquires(rq2->lock)
1532 {
1533         if (rq1 == rq2) {
1534                 spin_lock(&rq1->lock);
1535                 __acquire(rq2->lock);   /* Fake it out ;) */
1536         } else {
1537                 if (rq1 < rq2) {
1538                         spin_lock(&rq1->lock);
1539                         spin_lock(&rq2->lock);
1540                 } else {
1541                         spin_lock(&rq2->lock);
1542                         spin_lock(&rq1->lock);
1543                 }
1544         }
1545 }
1546
1547 /*
1548  * double_rq_unlock - safely unlock two runqueues
1549  *
1550  * Note this does not restore interrupts like task_rq_unlock,
1551  * you need to do so manually after calling.
1552  */
1553 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1554         __releases(rq1->lock)
1555         __releases(rq2->lock)
1556 {
1557         spin_unlock(&rq1->lock);
1558         if (rq1 != rq2)
1559                 spin_unlock(&rq2->lock);
1560         else
1561                 __release(rq2->lock);
1562 }
1563
1564 /*
1565  * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1566  */
1567 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1568         __releases(this_rq->lock)
1569         __acquires(busiest->lock)
1570         __acquires(this_rq->lock)
1571 {
1572         if (unlikely(!spin_trylock(&busiest->lock))) {
1573                 if (busiest < this_rq) {
1574                         spin_unlock(&this_rq->lock);
1575                         spin_lock(&busiest->lock);
1576                         spin_lock(&this_rq->lock);
1577                 } else
1578                         spin_lock(&busiest->lock);
1579         }
1580 }
1581
1582 /*
1583  * find_idlest_cpu - find the least busy runqueue.
1584  */
1585 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1586                            struct sched_domain *sd)
1587 {
1588         unsigned long load, min_load, this_load;
1589         int i, min_cpu;
1590         cpumask_t mask;
1591
1592         min_cpu = UINT_MAX;
1593         min_load = ULONG_MAX;
1594
1595         cpus_and(mask, sd->span, p->cpus_allowed);
1596
1597         for_each_cpu_mask(i, mask) {
1598                 load = target_load(i);
1599
1600                 if (load < min_load) {
1601                         min_cpu = i;
1602                         min_load = load;
1603
1604                         /* break out early on an idle CPU: */
1605                         if (!min_load)
1606                                 break;
1607                 }
1608         }
1609
1610         /* add +1 to account for the new task */
1611         this_load = source_load(this_cpu) + SCHED_LOAD_SCALE;
1612
1613         /*
1614          * Would with the addition of the new task to the
1615          * current CPU there be an imbalance between this
1616          * CPU and the idlest CPU?
1617          *
1618          * Use half of the balancing threshold - new-context is
1619          * a good opportunity to balance.
1620          */
1621         if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1622                 return min_cpu;
1623
1624         return this_cpu;
1625 }
1626
1627 /*
1628  * If dest_cpu is allowed for this process, migrate the task to it.
1629  * This is accomplished by forcing the cpu_allowed mask to only
1630  * allow dest_cpu, which will force the cpu onto dest_cpu.  Then
1631  * the cpu_allowed mask is restored.
1632  */
1633 static void sched_migrate_task(task_t *p, int dest_cpu)
1634 {
1635         migration_req_t req;
1636         runqueue_t *rq;
1637         unsigned long flags;
1638
1639         rq = task_rq_lock(p, &flags);
1640         if (!cpu_isset(dest_cpu, p->cpus_allowed)
1641             || unlikely(cpu_is_offline(dest_cpu)))
1642                 goto out;
1643
1644         /* force the process onto the specified CPU */
1645         if (migrate_task(p, dest_cpu, &req)) {
1646                 /* Need to wait for migration thread (might exit: take ref). */
1647                 struct task_struct *mt = rq->migration_thread;
1648                 get_task_struct(mt);
1649                 task_rq_unlock(rq, &flags);
1650                 wake_up_process(mt);
1651                 put_task_struct(mt);
1652                 wait_for_completion(&req.done);
1653                 return;
1654         }
1655 out:
1656         task_rq_unlock(rq, &flags);
1657 }
1658
1659 /*
1660  * sched_exec(): find the highest-level, exec-balance-capable
1661  * domain and try to migrate the task to the least loaded CPU.
1662  *
1663  * execve() is a valuable balancing opportunity, because at this point
1664  * the task has the smallest effective memory and cache footprint.
1665  */
1666 void sched_exec(void)
1667 {
1668         struct sched_domain *tmp, *sd = NULL;
1669         int new_cpu, this_cpu = get_cpu();
1670
1671         /* Prefer the current CPU if there's only this task running */
1672         if (this_rq()->nr_running <= 1)
1673                 goto out;
1674
1675         for_each_domain(this_cpu, tmp)
1676                 if (tmp->flags & SD_BALANCE_EXEC)
1677                         sd = tmp;
1678
1679         if (sd) {
1680                 schedstat_inc(sd, sbe_attempts);
1681                 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1682                 if (new_cpu != this_cpu) {
1683                         schedstat_inc(sd, sbe_pushed);
1684                         put_cpu();
1685                         sched_migrate_task(current, new_cpu);
1686                         return;
1687                 }
1688         }
1689 out:
1690         put_cpu();
1691 }
1692
1693 /*
1694  * pull_task - move a task from a remote runqueue to the local runqueue.
1695  * Both runqueues must be locked.
1696  */
1697 static inline
1698 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1699                runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1700 {
1701         dequeue_task(p, src_array);
1702         src_rq->nr_running--;
1703         set_task_cpu(p, this_cpu);
1704         this_rq->nr_running++;
1705         enqueue_task(p, this_array);
1706         p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1707                                 + this_rq->timestamp_last_tick;
1708         /*
1709          * Note that idle threads have a prio of MAX_PRIO, for this test
1710          * to be always true for them.
1711          */
1712         if (TASK_PREEMPTS_CURR(p, this_rq))
1713                 resched_task(this_rq->curr);
1714 }
1715
1716 /*
1717  * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1718  */
1719 static inline
1720 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1721                      struct sched_domain *sd, enum idle_type idle)
1722 {
1723         /*
1724          * We do not migrate tasks that are:
1725          * 1) running (obviously), or
1726          * 2) cannot be migrated to this CPU due to cpus_allowed, or
1727          * 3) are cache-hot on their current CPU.
1728          */
1729         if (task_running(rq, p))
1730                 return 0;
1731         if (!cpu_isset(this_cpu, p->cpus_allowed))
1732                 return 0;
1733
1734         /*
1735          * Aggressive migration if:
1736          * 1) the [whole] cpu is idle, or
1737          * 2) too many balance attempts have failed.
1738          */
1739
1740         if (cpu_and_siblings_are_idle(this_cpu) || \
1741                         sd->nr_balance_failed > sd->cache_nice_tries)
1742                 return 1;
1743
1744         if (task_hot(p, rq->timestamp_last_tick, sd))
1745                         return 0;
1746         return 1;
1747 }
1748
1749 /*
1750  * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1751  * as part of a balancing operation within "domain". Returns the number of
1752  * tasks moved.
1753  *
1754  * Called with both runqueues locked.
1755  */
1756 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1757                       unsigned long max_nr_move, struct sched_domain *sd,
1758                       enum idle_type idle)
1759 {
1760         prio_array_t *array, *dst_array;
1761         struct list_head *head, *curr;
1762         int idx, pulled = 0;
1763         task_t *tmp;
1764
1765         if (max_nr_move <= 0 || busiest->nr_running <= 1)
1766                 goto out;
1767
1768         /*
1769          * We first consider expired tasks. Those will likely not be
1770          * executed in the near future, and they are most likely to
1771          * be cache-cold, thus switching CPUs has the least effect
1772          * on them.
1773          */
1774         if (busiest->expired->nr_active) {
1775                 array = busiest->expired;
1776                 dst_array = this_rq->expired;
1777         } else {
1778                 array = busiest->active;
1779                 dst_array = this_rq->active;
1780         }
1781
1782 new_array:
1783         /* Start searching at priority 0: */
1784         idx = 0;
1785 skip_bitmap:
1786         if (!idx)
1787                 idx = sched_find_first_bit(array->bitmap);
1788         else
1789                 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1790         if (idx >= MAX_PRIO) {
1791                 if (array == busiest->expired && busiest->active->nr_active) {
1792                         array = busiest->active;
1793                         dst_array = this_rq->active;
1794                         goto new_array;
1795                 }
1796                 goto out;
1797         }
1798
1799         head = array->queue + idx;
1800         curr = head->prev;
1801 skip_queue:
1802         tmp = list_entry(curr, task_t, run_list);
1803
1804         curr = curr->prev;
1805
1806         if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
1807                 if (curr != head)
1808                         goto skip_queue;
1809                 idx++;
1810                 goto skip_bitmap;
1811         }
1812
1813 #ifdef CONFIG_SCHEDSTATS
1814         if (task_hot(tmp, busiest->timestamp_last_tick, sd))
1815                 schedstat_inc(sd, lb_hot_gained[idle]);
1816 #endif
1817
1818         pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
1819         pulled++;
1820
1821         /* We only want to steal up to the prescribed number of tasks. */
1822         if (pulled < max_nr_move) {
1823                 if (curr != head)
1824                         goto skip_queue;
1825                 idx++;
1826                 goto skip_bitmap;
1827         }
1828 out:
1829         /*
1830          * Right now, this is the only place pull_task() is called,
1831          * so we can safely collect pull_task() stats here rather than
1832          * inside pull_task().
1833          */
1834         schedstat_add(sd, lb_gained[idle], pulled);
1835         return pulled;
1836 }
1837
1838 /*
1839  * find_busiest_group finds and returns the busiest CPU group within the
1840  * domain. It calculates and returns the number of tasks which should be
1841  * moved to restore balance via the imbalance parameter.
1842  */
1843 static struct sched_group *
1844 find_busiest_group(struct sched_domain *sd, int this_cpu,
1845                    unsigned long *imbalance, enum idle_type idle)
1846 {
1847         struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
1848         unsigned long max_load, avg_load, total_load, this_load, total_pwr;
1849
1850         max_load = this_load = total_load = total_pwr = 0;
1851
1852         do {
1853                 unsigned long load;
1854                 int local_group;
1855                 int i;
1856
1857                 local_group = cpu_isset(this_cpu, group->cpumask);
1858
1859                 /* Tally up the load of all CPUs in the group */
1860                 avg_load = 0;
1861
1862                 for_each_cpu_mask(i, group->cpumask) {
1863                         /* Bias balancing toward cpus of our domain */
1864                         if (local_group)
1865                                 load = target_load(i);
1866                         else
1867                                 load = source_load(i);
1868
1869                         avg_load += load;
1870                 }
1871
1872                 total_load += avg_load;
1873                 total_pwr += group->cpu_power;
1874
1875                 /* Adjust by relative CPU power of the group */
1876                 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1877
1878                 if (local_group) {
1879                         this_load = avg_load;
1880                         this = group;
1881                         goto nextgroup;
1882                 } else if (avg_load > max_load) {
1883                         max_load = avg_load;
1884                         busiest = group;
1885                 }
1886 nextgroup:
1887                 group = group->next;
1888         } while (group != sd->groups);
1889
1890         if (!busiest || this_load >= max_load)
1891                 goto out_balanced;
1892
1893         avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
1894
1895         if (this_load >= avg_load ||
1896                         100*max_load <= sd->imbalance_pct*this_load)
1897                 goto out_balanced;
1898
1899         /*
1900          * We're trying to get all the cpus to the average_load, so we don't
1901          * want to push ourselves above the average load, nor do we wish to
1902          * reduce the max loaded cpu below the average load, as either of these
1903          * actions would just result in more rebalancing later, and ping-pong
1904          * tasks around. Thus we look for the minimum possible imbalance.
1905          * Negative imbalances (*we* are more loaded than anyone else) will
1906          * be counted as no imbalance for these purposes -- we can't fix that
1907          * by pulling tasks to us.  Be careful of negative numbers as they'll
1908          * appear as very large values with unsigned longs.
1909          */
1910         /* How much load to actually move to equalise the imbalance */
1911         *imbalance = min((max_load - avg_load) * busiest->cpu_power,
1912                                 (avg_load - this_load) * this->cpu_power)
1913                         / SCHED_LOAD_SCALE;
1914
1915         if (*imbalance < SCHED_LOAD_SCALE) {
1916                 unsigned long pwr_now = 0, pwr_move = 0;
1917                 unsigned long tmp;
1918
1919                 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
1920                         *imbalance = 1;
1921                         return busiest;
1922                 }
1923
1924                 /*
1925                  * OK, we don't have enough imbalance to justify moving tasks,
1926                  * however we may be able to increase total CPU power used by
1927                  * moving them.
1928                  */
1929
1930                 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
1931                 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
1932                 pwr_now /= SCHED_LOAD_SCALE;
1933
1934                 /* Amount of load we'd subtract */
1935                 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
1936                 if (max_load > tmp)
1937                         pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
1938                                                         max_load - tmp);
1939
1940                 /* Amount of load we'd add */
1941                 if (max_load*busiest->cpu_power <
1942                                 SCHED_LOAD_SCALE*SCHED_LOAD_SCALE)
1943                         tmp = max_load*busiest->cpu_power/this->cpu_power;
1944                 else
1945                         tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
1946                 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
1947                 pwr_move /= SCHED_LOAD_SCALE;
1948
1949                 /* Move if we gain throughput */
1950                 if (pwr_move <= pwr_now)
1951                         goto out_balanced;
1952
1953                 *imbalance = 1;
1954                 return busiest;
1955         }
1956
1957         /* Get rid of the scaling factor, rounding down as we divide */
1958         *imbalance = *imbalance / SCHED_LOAD_SCALE;
1959
1960         return busiest;
1961
1962 out_balanced:
1963         if (busiest && (idle == NEWLY_IDLE ||
1964                         (idle == SCHED_IDLE && max_load > SCHED_LOAD_SCALE)) ) {
1965                 *imbalance = 1;
1966                 return busiest;
1967         }
1968
1969         *imbalance = 0;
1970         return NULL;
1971 }
1972
1973 /*
1974  * find_busiest_queue - find the busiest runqueue among the cpus in group.
1975  */
1976 static runqueue_t *find_busiest_queue(struct sched_group *group)
1977 {
1978         unsigned long load, max_load = 0;
1979         runqueue_t *busiest = NULL;
1980         int i;
1981
1982         for_each_cpu_mask(i, group->cpumask) {
1983                 load = source_load(i);
1984
1985                 if (load > max_load) {
1986                         max_load = load;
1987                         busiest = cpu_rq(i);
1988                 }
1989         }
1990
1991         return busiest;
1992 }
1993
1994 /*
1995  * Check this_cpu to ensure it is balanced within domain. Attempt to move
1996  * tasks if there is an imbalance.
1997  *
1998  * Called with this_rq unlocked.
1999  */
2000 static int load_balance(int this_cpu, runqueue_t *this_rq,
2001                         struct sched_domain *sd, enum idle_type idle)
2002 {
2003         struct sched_group *group;
2004         runqueue_t *busiest;
2005         unsigned long imbalance;
2006         int nr_moved;
2007
2008         spin_lock(&this_rq->lock);
2009         schedstat_inc(sd, lb_cnt[idle]);
2010
2011         group = find_busiest_group(sd, this_cpu, &imbalance, idle);
2012         if (!group) {
2013                 schedstat_inc(sd, lb_nobusyg[idle]);
2014                 goto out_balanced;
2015         }
2016
2017         busiest = find_busiest_queue(group);
2018         if (!busiest) {
2019                 schedstat_inc(sd, lb_nobusyq[idle]);
2020                 goto out_balanced;
2021         }
2022
2023         /*
2024          * This should be "impossible", but since load
2025          * balancing is inherently racy and statistical,
2026          * it could happen in theory.
2027          */
2028         if (unlikely(busiest == this_rq)) {
2029                 WARN_ON(1);
2030                 goto out_balanced;
2031         }
2032
2033         schedstat_add(sd, lb_imbalance[idle], imbalance);
2034
2035         nr_moved = 0;
2036         if (busiest->nr_running > 1) {
2037                 /*
2038                  * Attempt to move tasks. If find_busiest_group has found
2039                  * an imbalance but busiest->nr_running <= 1, the group is
2040                  * still unbalanced. nr_moved simply stays zero, so it is
2041                  * correctly treated as an imbalance.
2042                  */
2043                 double_lock_balance(this_rq, busiest);
2044                 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2045                                                 imbalance, sd, idle);
2046                 spin_unlock(&busiest->lock);
2047         }
2048         spin_unlock(&this_rq->lock);
2049
2050         if (!nr_moved) {
2051                 schedstat_inc(sd, lb_failed[idle]);
2052                 sd->nr_balance_failed++;
2053
2054                 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2055                         int wake = 0;
2056
2057                         spin_lock(&busiest->lock);
2058                         if (!busiest->active_balance) {
2059                                 busiest->active_balance = 1;
2060                                 busiest->push_cpu = this_cpu;
2061                                 wake = 1;
2062                         }
2063                         spin_unlock(&busiest->lock);
2064                         if (wake)
2065                                 wake_up_process(busiest->migration_thread);
2066
2067                         /*
2068                          * We've kicked active balancing, reset the failure
2069                          * counter.
2070                          */
2071                         sd->nr_balance_failed = sd->cache_nice_tries;
2072                 }
2073
2074                 /*
2075                  * We were unbalanced, but unsuccessful in move_tasks(),
2076                  * so bump the balance_interval to lessen the lock contention.
2077                  */
2078                 if (sd->balance_interval < sd->max_interval)
2079                         sd->balance_interval++;
2080         } else {
2081                 sd->nr_balance_failed = 0;
2082
2083                 /* We were unbalanced, so reset the balancing interval */
2084                 sd->balance_interval = sd->min_interval;
2085         }
2086
2087         return nr_moved;
2088
2089 out_balanced:
2090         spin_unlock(&this_rq->lock);
2091
2092         schedstat_inc(sd, lb_balanced[idle]);
2093
2094         /* tune up the balancing interval */
2095         if (sd->balance_interval < sd->max_interval)
2096                 sd->balance_interval *= 2;
2097
2098         return 0;
2099 }
2100
2101 /*
2102  * Check this_cpu to ensure it is balanced within domain. Attempt to move
2103  * tasks if there is an imbalance.
2104  *
2105  * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2106  * this_rq is locked.
2107  */
2108 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2109                                 struct sched_domain *sd)
2110 {
2111         struct sched_group *group;
2112         runqueue_t *busiest = NULL;
2113         unsigned long imbalance;
2114         int nr_moved = 0;
2115
2116         schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2117         group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
2118         if (!group) {
2119                 schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
2120                 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2121                 goto out;
2122         }
2123
2124         busiest = find_busiest_queue(group);
2125         if (!busiest || busiest == this_rq) {
2126                 schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
2127                 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2128                 goto out;
2129         }
2130
2131         /* Attempt to move tasks */
2132         double_lock_balance(this_rq, busiest);
2133
2134         schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2135         nr_moved = move_tasks(this_rq, this_cpu, busiest,
2136                                         imbalance, sd, NEWLY_IDLE);
2137         if (!nr_moved)
2138                 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2139
2140         spin_unlock(&busiest->lock);
2141
2142 out:
2143         return nr_moved;
2144 }
2145
2146 /*
2147  * idle_balance is called by schedule() if this_cpu is about to become
2148  * idle. Attempts to pull tasks from other CPUs.
2149  */
2150 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
2151 {
2152         struct sched_domain *sd;
2153
2154         for_each_domain(this_cpu, sd) {
2155                 if (sd->flags & SD_BALANCE_NEWIDLE) {
2156                         if (load_balance_newidle(this_cpu, this_rq, sd)) {
2157                                 /* We've pulled tasks over so stop searching */
2158                                 break;
2159                         }
2160                 }
2161         }
2162 }
2163
2164 /*
2165  * active_load_balance is run by migration threads. It pushes running tasks
2166  * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2167  * running on each physical CPU where possible, and avoids physical /
2168  * logical imbalances.
2169  *
2170  * Called with busiest_rq locked.
2171  */
2172 static void active_load_balance(runqueue_t *busiest_rq, int busiest_cpu)
2173 {
2174         struct sched_domain *sd;
2175         struct sched_group *cpu_group;
2176         runqueue_t *target_rq;
2177         cpumask_t visited_cpus;
2178         int cpu;
2179
2180         /*
2181          * Search for suitable CPUs to push tasks to in successively higher
2182          * domains with SD_LOAD_BALANCE set.
2183          */
2184         visited_cpus = CPU_MASK_NONE;
2185         for_each_domain(busiest_cpu, sd) {
2186                 if (!(sd->flags & SD_LOAD_BALANCE))
2187                         /* no more domains to search */
2188                         break;
2189
2190                 schedstat_inc(sd, alb_cnt);
2191
2192                 cpu_group = sd->groups;
2193                 do {
2194                         for_each_cpu_mask(cpu, cpu_group->cpumask) {
2195                                 if (busiest_rq->nr_running <= 1)
2196                                         /* no more tasks left to move */
2197                                         return;
2198                                 if (cpu_isset(cpu, visited_cpus))
2199                                         continue;
2200                                 cpu_set(cpu, visited_cpus);
2201                                 if (!cpu_and_siblings_are_idle(cpu) || cpu == busiest_cpu)
2202                                         continue;
2203
2204                                 target_rq = cpu_rq(cpu);
2205                                 /*
2206                                  * This condition is "impossible", if it occurs
2207                                  * we need to fix it.  Originally reported by
2208                                  * Bjorn Helgaas on a 128-cpu setup.
2209                                  */
2210                                 BUG_ON(busiest_rq == target_rq);
2211
2212                                 /* move a task from busiest_rq to target_rq */
2213                                 double_lock_balance(busiest_rq, target_rq);
2214                                 if (move_tasks(target_rq, cpu, busiest_rq,
2215                                                 1, sd, SCHED_IDLE)) {
2216                                         schedstat_inc(sd, alb_pushed);
2217                                 } else {
2218                                         schedstat_inc(sd, alb_failed);
2219                                 }
2220                                 spin_unlock(&target_rq->lock);
2221                         }
2222                         cpu_group = cpu_group->next;
2223                 } while (cpu_group != sd->groups);
2224         }
2225 }
2226
2227 /*
2228  * rebalance_tick will get called every timer tick, on every CPU.
2229  *
2230  * It checks each scheduling domain to see if it is due to be balanced,
2231  * and initiates a balancing operation if so.
2232  *
2233  * Balancing parameters are set up in arch_init_sched_domains.
2234  */
2235
2236 /* Don't have all balancing operations going off at once */
2237 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2238
2239 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2240                            enum idle_type idle)
2241 {
2242         unsigned long old_load, this_load;
2243         unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2244         struct sched_domain *sd;
2245
2246         /* Update our load */
2247         old_load = this_rq->cpu_load;
2248         this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
2249         /*
2250          * Round up the averaging division if load is increasing. This
2251          * prevents us from getting stuck on 9 if the load is 10, for
2252          * example.
2253          */
2254         if (this_load > old_load)
2255                 old_load++;
2256         this_rq->cpu_load = (old_load + this_load) / 2;
2257
2258         for_each_domain(this_cpu, sd) {
2259                 unsigned long interval;
2260
2261                 if (!(sd->flags & SD_LOAD_BALANCE))
2262                         continue;
2263
2264                 interval = sd->balance_interval;
2265                 if (idle != SCHED_IDLE)
2266                         interval *= sd->busy_factor;
2267
2268                 /* scale ms to jiffies */
2269                 interval = msecs_to_jiffies(interval);
2270                 if (unlikely(!interval))
2271                         interval = 1;
2272
2273                 if (j - sd->last_balance >= interval) {
2274                         if (load_balance(this_cpu, this_rq, sd, idle)) {
2275                                 /* We've pulled tasks over so no longer idle */
2276                                 idle = NOT_IDLE;
2277                         }
2278                         sd->last_balance += interval;
2279                 }
2280         }
2281 }
2282 #else
2283 /*
2284  * on UP we do not need to balance between CPUs:
2285  */
2286 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2287 {
2288 }
2289 static inline void idle_balance(int cpu, runqueue_t *rq)
2290 {
2291 }
2292 #endif
2293
2294 static inline int wake_priority_sleeper(runqueue_t *rq)
2295 {
2296         int ret = 0;
2297 #ifdef CONFIG_SCHED_SMT
2298         spin_lock(&rq->lock);
2299         /*
2300          * If an SMT sibling task has been put to sleep for priority
2301          * reasons reschedule the idle task to see if it can now run.
2302          */
2303         if (rq->nr_running) {
2304                 resched_task(rq->idle);
2305                 ret = 1;
2306         }
2307         spin_unlock(&rq->lock);
2308 #endif
2309         return ret;
2310 }
2311
2312 DEFINE_PER_CPU(struct kernel_stat, kstat);
2313
2314 EXPORT_PER_CPU_SYMBOL(kstat);
2315
2316 /*
2317  * This is called on clock ticks and on context switches.
2318  * Bank in p->sched_time the ns elapsed since the last tick or switch.
2319  */
2320 static inline void update_cpu_clock(task_t *p, runqueue_t *rq,
2321                                     unsigned long long now)
2322 {
2323         unsigned long long last = max(p->timestamp, rq->timestamp_last_tick);
2324         p->sched_time += now - last;
2325 }
2326
2327 /*
2328  * Return current->sched_time plus any more ns on the sched_clock
2329  * that have not yet been banked.
2330  */
2331 unsigned long long current_sched_time(const task_t *tsk)
2332 {
2333         unsigned long long ns;
2334         unsigned long flags;
2335         local_irq_save(flags);
2336         ns = max(tsk->timestamp, task_rq(tsk)->timestamp_last_tick);
2337         ns = tsk->sched_time + (sched_clock() - ns);
2338         local_irq_restore(flags);
2339         return ns;
2340 }
2341
2342 /*
2343  * We place interactive tasks back into the active array, if possible.
2344  *
2345  * To guarantee that this does not starve expired tasks we ignore the
2346  * interactivity of a task if the first expired task had to wait more
2347  * than a 'reasonable' amount of time. This deadline timeout is
2348  * load-dependent, as the frequency of array switched decreases with
2349  * increasing number of running tasks. We also ignore the interactivity
2350  * if a better static_prio task has expired:
2351  */
2352 #define EXPIRED_STARVING(rq) \
2353         ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2354                 (jiffies - (rq)->expired_timestamp >= \
2355                         STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2356                         ((rq)->curr->static_prio > (rq)->best_expired_prio))
2357
2358 /*
2359  * Account user cpu time to a process.
2360  * @p: the process that the cpu time gets accounted to
2361  * @hardirq_offset: the offset to subtract from hardirq_count()
2362  * @cputime: the cpu time spent in user space since the last update
2363  */
2364 void account_user_time(struct task_struct *p, cputime_t cputime)
2365 {
2366         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2367         struct vx_info *vxi = p->vx_info;  /* p is _always_ current */
2368         cputime64_t tmp;
2369         int nice = (TASK_NICE(p) > 0);
2370
2371         p->utime = cputime_add(p->utime, cputime);
2372         vx_account_user(vxi, cputime, nice);
2373
2374         /* Add user time to cpustat. */
2375         tmp = cputime_to_cputime64(cputime);
2376         if (nice)
2377                 cpustat->nice = cputime64_add(cpustat->nice, tmp);
2378         else
2379                 cpustat->user = cputime64_add(cpustat->user, tmp);
2380 }
2381
2382 /*
2383  * Account system cpu time to a process.
2384  * @p: the process that the cpu time gets accounted to
2385  * @hardirq_offset: the offset to subtract from hardirq_count()
2386  * @cputime: the cpu time spent in kernel space since the last update
2387  */
2388 void account_system_time(struct task_struct *p, int hardirq_offset,
2389                          cputime_t cputime)
2390 {
2391         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2392         struct vx_info *vxi = p->vx_info;  /* p is _always_ current */
2393         runqueue_t *rq = this_rq();
2394         cputime64_t tmp;
2395
2396         p->stime = cputime_add(p->stime, cputime);
2397         vx_account_system(vxi, cputime, (p == rq->idle));
2398
2399         /* Add system time to cpustat. */
2400         tmp = cputime_to_cputime64(cputime);
2401         if (hardirq_count() - hardirq_offset)
2402                 cpustat->irq = cputime64_add(cpustat->irq, tmp);
2403         else if (softirq_count())
2404                 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
2405         else if (p != rq->idle)
2406                 cpustat->system = cputime64_add(cpustat->system, tmp);
2407         else if (atomic_read(&rq->nr_iowait) > 0)
2408                 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2409         else
2410                 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2411         /* Account for system time used */
2412         acct_update_integrals(p);
2413         /* Update rss highwater mark */
2414         update_mem_hiwater(p);
2415 }
2416
2417 /*
2418  * Account for involuntary wait time.
2419  * @p: the process from which the cpu time has been stolen
2420  * @steal: the cpu time spent in involuntary wait
2421  */
2422 void account_steal_time(struct task_struct *p, cputime_t steal)
2423 {
2424         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2425         cputime64_t tmp = cputime_to_cputime64(steal);
2426         runqueue_t *rq = this_rq();
2427
2428         if (p == rq->idle) {
2429                 p->stime = cputime_add(p->stime, steal);
2430                 if (atomic_read(&rq->nr_iowait) > 0)
2431                         cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2432                 else
2433                         cpustat->idle = cputime64_add(cpustat->idle, tmp);
2434         } else
2435                 cpustat->steal = cputime64_add(cpustat->steal, tmp);
2436 }
2437
2438 /*
2439  * This function gets called by the timer code, with HZ frequency.
2440  * We call it with interrupts disabled.
2441  *
2442  * It also gets called by the fork code, when changing the parent's
2443  * timeslices.
2444  */
2445 void scheduler_tick(void)
2446 {
2447         int cpu = smp_processor_id();
2448         runqueue_t *rq = this_rq();
2449         task_t *p = current;
2450         unsigned long long now = sched_clock();
2451
2452         update_cpu_clock(p, rq, now);
2453
2454         rq->timestamp_last_tick = now;
2455
2456 #if defined(CONFIG_VSERVER_HARDCPU) && defined(CONFIG_VSERVER_ACB_SCHED) 
2457         vx_scheduler_tick();
2458 #endif
2459
2460         if (p == rq->idle) {
2461                 if (wake_priority_sleeper(rq))
2462                         goto out;
2463 #ifdef CONFIG_VSERVER_HARDCPU_IDLE
2464                 if (!--rq->idle_tokens && !list_empty(&rq->hold_queue))
2465                         set_need_resched();
2466 #endif
2467                 rebalance_tick(cpu, rq, SCHED_IDLE);
2468                 return;
2469         }
2470
2471         /* Task might have expired already, but not scheduled off yet */
2472         if (p->array != rq->active) {
2473                 set_tsk_need_resched(p);
2474                 goto out;
2475         }
2476         spin_lock(&rq->lock);
2477         /*
2478          * The task was running during this tick - update the
2479          * time slice counter. Note: we do not update a thread's
2480          * priority until it either goes to sleep or uses up its
2481          * timeslice. This makes it possible for interactive tasks
2482          * to use up their timeslices at their highest priority levels.
2483          */
2484         if (rt_task(p)) {
2485                 /*
2486                  * RR tasks need a special form of timeslice management.
2487                  * FIFO tasks have no timeslices.
2488                  */
2489                 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2490                         p->time_slice = task_timeslice(p);
2491                         p->first_time_slice = 0;
2492                         set_tsk_need_resched(p);
2493
2494                         /* put it at the end of the queue: */
2495                         requeue_task(p, rq->active);
2496                 }
2497                 goto out_unlock;
2498         }
2499         if (vx_need_resched(p)) {
2500                 dequeue_task(p, rq->active);
2501                 set_tsk_need_resched(p);
2502                 p->prio = effective_prio(p);
2503                 p->time_slice = task_timeslice(p);
2504                 p->first_time_slice = 0;
2505
2506                 if (!rq->expired_timestamp)
2507                         rq->expired_timestamp = jiffies;
2508                 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2509                         enqueue_task(p, rq->expired);
2510                         if (p->static_prio < rq->best_expired_prio)
2511                                 rq->best_expired_prio = p->static_prio;
2512                 } else
2513                         enqueue_task(p, rq->active);
2514         } else {
2515                 /*
2516                  * Prevent a too long timeslice allowing a task to monopolize
2517                  * the CPU. We do this by splitting up the timeslice into
2518                  * smaller pieces.
2519                  *
2520                  * Note: this does not mean the task's timeslices expire or
2521                  * get lost in any way, they just might be preempted by
2522                  * another task of equal priority. (one with higher
2523                  * priority would have preempted this task already.) We
2524                  * requeue this task to the end of the list on this priority
2525                  * level, which is in essence a round-robin of tasks with
2526                  * equal priority.
2527                  *
2528                  * This only applies to tasks in the interactive
2529                  * delta range with at least TIMESLICE_GRANULARITY to requeue.
2530                  */
2531                 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2532                         p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2533                         (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2534                         (p->array == rq->active)) {
2535
2536                         requeue_task(p, rq->active);
2537                         set_tsk_need_resched(p);
2538                 }
2539         }
2540 out_unlock:
2541         spin_unlock(&rq->lock);
2542 out:
2543         rebalance_tick(cpu, rq, NOT_IDLE);
2544 }
2545
2546 #ifdef CONFIG_SCHED_SMT
2547 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2548 {
2549         struct sched_domain *sd = this_rq->sd;
2550         cpumask_t sibling_map;
2551         int i;
2552
2553         if (!(sd->flags & SD_SHARE_CPUPOWER))
2554                 return;
2555
2556         /*
2557          * Unlock the current runqueue because we have to lock in
2558          * CPU order to avoid deadlocks. Caller knows that we might
2559          * unlock. We keep IRQs disabled.
2560          */
2561         spin_unlock(&this_rq->lock);
2562
2563         sibling_map = sd->span;
2564
2565         for_each_cpu_mask(i, sibling_map)
2566                 spin_lock(&cpu_rq(i)->lock);
2567         /*
2568          * We clear this CPU from the mask. This both simplifies the
2569          * inner loop and keps this_rq locked when we exit:
2570          */
2571         cpu_clear(this_cpu, sibling_map);
2572
2573         for_each_cpu_mask(i, sibling_map) {
2574                 runqueue_t *smt_rq = cpu_rq(i);
2575
2576                 /*
2577                  * If an SMT sibling task is sleeping due to priority
2578                  * reasons wake it up now.
2579                  */
2580                 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
2581                         resched_task(smt_rq->idle);
2582         }
2583
2584         for_each_cpu_mask(i, sibling_map)
2585                 spin_unlock(&cpu_rq(i)->lock);
2586         /*
2587          * We exit with this_cpu's rq still held and IRQs
2588          * still disabled:
2589          */
2590 }
2591
2592 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2593 {
2594         struct sched_domain *sd = this_rq->sd;
2595         cpumask_t sibling_map;
2596         prio_array_t *array;
2597         int ret = 0, i;
2598         task_t *p;
2599
2600         if (!(sd->flags & SD_SHARE_CPUPOWER))
2601                 return 0;
2602
2603         /*
2604          * The same locking rules and details apply as for
2605          * wake_sleeping_dependent():
2606          */
2607         spin_unlock(&this_rq->lock);
2608         sibling_map = sd->span;
2609         for_each_cpu_mask(i, sibling_map)
2610                 spin_lock(&cpu_rq(i)->lock);
2611         cpu_clear(this_cpu, sibling_map);
2612
2613         /*
2614          * Establish next task to be run - it might have gone away because
2615          * we released the runqueue lock above:
2616          */
2617         if (!this_rq->nr_running)
2618                 goto out_unlock;
2619         array = this_rq->active;
2620         if (!array->nr_active)
2621                 array = this_rq->expired;
2622         BUG_ON(!array->nr_active);
2623
2624         p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
2625                 task_t, run_list);
2626
2627         for_each_cpu_mask(i, sibling_map) {
2628                 runqueue_t *smt_rq = cpu_rq(i);
2629                 task_t *smt_curr = smt_rq->curr;
2630
2631                 /*
2632                  * If a user task with lower static priority than the
2633                  * running task on the SMT sibling is trying to schedule,
2634                  * delay it till there is proportionately less timeslice
2635                  * left of the sibling task to prevent a lower priority
2636                  * task from using an unfair proportion of the
2637                  * physical cpu's resources. -ck
2638                  */
2639                 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
2640                         task_timeslice(p) || rt_task(smt_curr)) &&
2641                         p->mm && smt_curr->mm && !rt_task(p))
2642                                 ret = 1;
2643
2644                 /*
2645                  * Reschedule a lower priority task on the SMT sibling,
2646                  * or wake it up if it has been put to sleep for priority
2647                  * reasons.
2648                  */
2649                 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
2650                         task_timeslice(smt_curr) || rt_task(p)) &&
2651                         smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
2652                         (smt_curr == smt_rq->idle && smt_rq->nr_running))
2653                                 resched_task(smt_curr);
2654         }
2655 out_unlock:
2656         for_each_cpu_mask(i, sibling_map)
2657                 spin_unlock(&cpu_rq(i)->lock);
2658         return ret;
2659 }
2660 #else
2661 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2662 {
2663 }
2664
2665 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2666 {
2667         return 0;
2668 }
2669 #endif
2670
2671 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
2672
2673 void fastcall add_preempt_count(int val)
2674 {
2675         /*
2676          * Underflow?
2677          */
2678         BUG_ON(((int)preempt_count() < 0));
2679         preempt_count() += val;
2680         /*
2681          * Spinlock count overflowing soon?
2682          */
2683         BUG_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
2684 }
2685 EXPORT_SYMBOL(add_preempt_count);
2686
2687 void fastcall sub_preempt_count(int val)
2688 {
2689         /*
2690          * Underflow?
2691          */
2692         BUG_ON(val > preempt_count());
2693         /*
2694          * Is the spinlock portion underflowing?
2695          */
2696         BUG_ON((val < PREEMPT_MASK) && !(preempt_count() & PREEMPT_MASK));
2697         preempt_count() -= val;
2698 }
2699 EXPORT_SYMBOL(sub_preempt_count);
2700
2701 #endif
2702
2703 /*
2704  * schedule() is the main scheduler function.
2705  */
2706 asmlinkage void __sched schedule(void)
2707 {
2708         long *switch_count;
2709         task_t *prev, *next;
2710         runqueue_t *rq;
2711         prio_array_t *array;
2712         struct list_head *queue;
2713         unsigned long long now;
2714         unsigned long run_time;
2715         struct vx_info *vxi;
2716 #ifdef  CONFIG_VSERVER_HARDCPU
2717         int maxidle = -HZ;
2718 # ifdef CONFIG_VSERVER_ACB_SCHED
2719         int min_guarantee_ticks = VX_INVALID_TICKS;
2720         int min_best_effort_ticks = VX_INVALID_TICKS;
2721 # endif
2722 #endif
2723         int cpu, idx;
2724
2725         /*
2726          * Test if we are atomic.  Since do_exit() needs to call into
2727          * schedule() atomically, we ignore that path for now.
2728          * Otherwise, whine if we are scheduling when we should not be.
2729          */
2730         if (likely(!current->exit_state)) {
2731                 if (unlikely(in_atomic())) {
2732                         printk(KERN_ERR "scheduling while atomic: "
2733                                 "%s/0x%08x/%d\n",
2734                                 current->comm, preempt_count(), current->pid);
2735                         dump_stack();
2736                 }
2737         }
2738         profile_hit(SCHED_PROFILING, __builtin_return_address(0));
2739
2740 need_resched:
2741         preempt_disable();
2742         prev = current;
2743         release_kernel_lock(prev);
2744 need_resched_nonpreemptible:
2745         rq = this_rq();
2746
2747         /*
2748          * The idle thread is not allowed to schedule!
2749          * Remove this check after it has been exercised a bit.
2750          */
2751         if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
2752                 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
2753                 dump_stack();
2754         }
2755
2756         schedstat_inc(rq, sched_cnt);
2757         now = sched_clock();
2758         if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
2759                 run_time = now - prev->timestamp;
2760                 if (unlikely((long long)(now - prev->timestamp) < 0))
2761                         run_time = 0;
2762         } else
2763                 run_time = NS_MAX_SLEEP_AVG;
2764
2765         /*
2766          * Tasks charged proportionately less run_time at high sleep_avg to
2767          * delay them losing their interactive status
2768          */
2769         run_time /= (CURRENT_BONUS(prev) ? : 1);
2770
2771         spin_lock_irq(&rq->lock);
2772
2773         if (unlikely(prev->flags & PF_DEAD))
2774                 prev->state = EXIT_DEAD;
2775
2776         switch_count = &prev->nivcsw;
2777         if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2778                 switch_count = &prev->nvcsw;
2779                 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2780                                 unlikely(signal_pending(prev))))
2781                         prev->state = TASK_RUNNING;
2782                 else {
2783                         if (prev->state == TASK_UNINTERRUPTIBLE) {
2784                                 rq->nr_uninterruptible++;
2785                                 vx_uninterruptible_inc(prev);
2786                         }
2787                         deactivate_task(prev, rq);
2788                 }
2789         }
2790
2791 #ifdef CONFIG_VSERVER_HARDCPU
2792 # ifdef CONFIG_VSERVER_ACB_SCHED
2793 drain_hold_queue:
2794 # endif 
2795         if (!list_empty(&rq->hold_queue)) {
2796                 struct list_head *l, *n;
2797                 int ret;
2798
2799                 vxi = NULL;
2800                 list_for_each_safe(l, n, &rq->hold_queue) {
2801                         next = list_entry(l, task_t, run_list);
2802                         if (vxi == next->vx_info)
2803                                 continue;
2804
2805                         vxi = next->vx_info;
2806                         ret = vx_tokens_recalc(vxi);
2807
2808                         if (ret > 0) {
2809                                 vx_unhold_task(vxi, next, rq);
2810                                 break;
2811                         }
2812                         if ((ret < 0) && (maxidle < ret))
2813                                 maxidle = ret;
2814 # ifdef CONFIG_VSERVER_ACB_SCHED
2815                         if (ret < 0) {
2816                                 if (IS_BEST_EFFORT(vxi)) {
2817                                         if (min_best_effort_ticks < ret) 
2818                                                 min_best_effort_ticks = ret;
2819                                 } else {
2820                                         if (min_guarantee_ticks < ret)
2821                                                 min_guarantee_ticks = ret;
2822                                 }
2823                         }
2824 # endif
2825                 }
2826         }
2827         rq->idle_tokens = -maxidle;
2828
2829 pick_next:
2830 #endif
2831
2832         cpu = smp_processor_id();
2833         if (unlikely(!rq->nr_running)) {
2834 go_idle:
2835                 idle_balance(cpu, rq);
2836                 if (!rq->nr_running) {
2837                         next = rq->idle;
2838                         rq->expired_timestamp = 0;
2839                         wake_sleeping_dependent(cpu, rq);
2840                         /*
2841                          * wake_sleeping_dependent() might have released
2842                          * the runqueue, so break out if we got new
2843                          * tasks meanwhile:
2844                          */
2845                         if (!rq->nr_running)
2846                                 goto switch_tasks;
2847                 }
2848         } else {
2849                 if (dependent_sleeper(cpu, rq)) {
2850                         next = rq->idle;
2851                         goto switch_tasks;
2852                 }
2853                 /*
2854                  * dependent_sleeper() releases and reacquires the runqueue
2855                  * lock, hence go into the idle loop if the rq went
2856                  * empty meanwhile:
2857                  */
2858                 if (unlikely(!rq->nr_running))
2859                         goto go_idle;
2860         }
2861
2862         array = rq->active;
2863         if (unlikely(!array->nr_active)) {
2864                 /*
2865                  * Switch the active and expired arrays.
2866                  */
2867                 schedstat_inc(rq, sched_switch);
2868                 rq->active = rq->expired;
2869                 rq->expired = array;
2870                 array = rq->active;
2871                 rq->expired_timestamp = 0;
2872                 rq->best_expired_prio = MAX_PRIO;
2873         }
2874
2875         idx = sched_find_first_bit(array->bitmap);
2876         queue = array->queue + idx;
2877         next = list_entry(queue->next, task_t, run_list);
2878
2879         vxi = next->vx_info;
2880 #ifdef  CONFIG_VSERVER_HARDCPU
2881         if (vx_info_flags(vxi, VXF_SCHED_PAUSE|VXF_SCHED_HARD, 0)) {
2882                 int ret = vx_tokens_recalc(vxi);
2883
2884                 if (unlikely(ret <= 0)) {
2885                         if (ret) {
2886                                 if ((rq->idle_tokens > -ret))
2887                                         rq->idle_tokens = -ret;
2888 # ifdef CONFIG_VSERVER_ACB_SCHED
2889                                 if (IS_BEST_EFFORT(vxi)) {
2890                                         if (min_best_effort_ticks < ret) 
2891                                                 min_best_effort_ticks = ret;
2892                                 } else {
2893                                         if (min_guarantee_ticks < ret)
2894                                                 min_guarantee_ticks = ret;
2895                                 }
2896 # endif
2897                         }
2898                         vx_hold_task(vxi, next, rq);
2899                         goto pick_next;
2900                 }
2901         } else  /* well, looks ugly but not as ugly as the ifdef-ed version */
2902 #endif
2903         if (vx_info_flags(vxi, VXF_SCHED_PRIO, 0))
2904                 vx_tokens_recalc(vxi);
2905
2906         if (!rt_task(next) && next->activated > 0) {
2907                 unsigned long long delta = now - next->timestamp;
2908                 if (unlikely((long long)(now - next->timestamp) < 0))
2909                         delta = 0;
2910
2911                 if (next->activated == 1)
2912                         delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
2913
2914                 array = next->array;
2915                 dequeue_task(next, array);
2916                 recalc_task_prio(next, next->timestamp + delta);
2917                 enqueue_task(next, array);
2918         }
2919         next->activated = 0;
2920 switch_tasks:
2921 #if defined(CONFIG_VSERVER_HARDCPU) && defined(CONFIG_VSERVER_ACB_SCHED)
2922         if (next == rq->idle && !list_empty(&rq->hold_queue)) {
2923                 if (min_best_effort_ticks != VX_INVALID_TICKS) {
2924                         vx_advance_best_effort_ticks(-min_best_effort_ticks);
2925                         goto drain_hold_queue;
2926                 } 
2927                 if (min_guarantee_ticks != VX_INVALID_TICKS) {
2928                         vx_advance_guaranteed_ticks(-min_guarantee_ticks);
2929                         goto drain_hold_queue;
2930                 }
2931         }
2932 #endif
2933         if (next == rq->idle)
2934                 schedstat_inc(rq, sched_goidle);
2935         prefetch(next);
2936         clear_tsk_need_resched(prev);
2937         rcu_qsctr_inc(task_cpu(prev));
2938
2939         update_cpu_clock(prev, rq, now);
2940
2941         prev->sleep_avg -= run_time;
2942         if ((long)prev->sleep_avg <= 0)
2943                 prev->sleep_avg = 0;
2944         prev->timestamp = prev->last_ran = now;
2945
2946         sched_info_switch(prev, next);
2947         if (likely(prev != next)) {
2948                 next->timestamp = now;
2949                 rq->nr_switches++;
2950                 rq->curr = next;
2951                 ++*switch_count;
2952
2953                 prepare_arch_switch(rq, next);
2954                 prev = context_switch(rq, prev, next);
2955                 barrier();
2956
2957                 finish_task_switch(prev);
2958         } else
2959                 spin_unlock_irq(&rq->lock);
2960
2961         prev = current;
2962         if (unlikely(reacquire_kernel_lock(prev) < 0))
2963                 goto need_resched_nonpreemptible;
2964         preempt_enable_no_resched();
2965         if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2966                 goto need_resched;
2967 }
2968
2969 EXPORT_SYMBOL(schedule);
2970
2971 #ifdef CONFIG_PREEMPT
2972 /*
2973  * this is is the entry point to schedule() from in-kernel preemption
2974  * off of preempt_enable.  Kernel preemptions off return from interrupt
2975  * occur there and call schedule directly.
2976  */
2977 asmlinkage void __sched preempt_schedule(void)
2978 {
2979         struct thread_info *ti = current_thread_info();
2980 #ifdef CONFIG_PREEMPT_BKL
2981         struct task_struct *task = current;
2982         int saved_lock_depth;
2983 #endif
2984         /*
2985          * If there is a non-zero preempt_count or interrupts are disabled,
2986          * we do not want to preempt the current task.  Just return..
2987          */
2988         if (unlikely(ti->preempt_count || irqs_disabled()))
2989                 return;
2990
2991 need_resched:
2992         add_preempt_count(PREEMPT_ACTIVE);
2993         /*
2994          * We keep the big kernel semaphore locked, but we
2995          * clear ->lock_depth so that schedule() doesnt
2996          * auto-release the semaphore:
2997          */
2998 #ifdef CONFIG_PREEMPT_BKL
2999         saved_lock_depth = task->lock_depth;
3000         task->lock_depth = -1;
3001 #endif
3002         schedule();
3003 #ifdef CONFIG_PREEMPT_BKL
3004         task->lock_depth = saved_lock_depth;
3005 #endif
3006         sub_preempt_count(PREEMPT_ACTIVE);
3007
3008         /* we could miss a preemption opportunity between schedule and now */
3009         barrier();
3010         if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3011                 goto need_resched;
3012 }
3013
3014 EXPORT_SYMBOL(preempt_schedule);
3015
3016 /*
3017  * this is is the entry point to schedule() from kernel preemption
3018  * off of irq context.
3019  * Note, that this is called and return with irqs disabled. This will
3020  * protect us against recursive calling from irq.
3021  */
3022 asmlinkage void __sched preempt_schedule_irq(void)
3023 {
3024         struct thread_info *ti = current_thread_info();
3025 #ifdef CONFIG_PREEMPT_BKL
3026         struct task_struct *task = current;
3027         int saved_lock_depth;
3028 #endif
3029         /* Catch callers which need to be fixed*/
3030         BUG_ON(ti->preempt_count || !irqs_disabled());
3031
3032 need_resched:
3033         add_preempt_count(PREEMPT_ACTIVE);
3034         /*
3035          * We keep the big kernel semaphore locked, but we
3036          * clear ->lock_depth so that schedule() doesnt
3037          * auto-release the semaphore:
3038          */
3039 #ifdef CONFIG_PREEMPT_BKL
3040         saved_lock_depth = task->lock_depth;
3041         task->lock_depth = -1;
3042 #endif
3043         local_irq_enable();
3044         schedule();
3045         local_irq_disable();
3046 #ifdef CONFIG_PREEMPT_BKL
3047         task->lock_depth = saved_lock_depth;
3048 #endif
3049         sub_preempt_count(PREEMPT_ACTIVE);
3050
3051         /* we could miss a preemption opportunity between schedule and now */
3052         barrier();
3053         if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3054                 goto need_resched;
3055 }
3056
3057 #endif /* CONFIG_PREEMPT */
3058
3059 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
3060 {
3061         task_t *p = curr->task;
3062         return try_to_wake_up(p, mode, sync);
3063 }
3064
3065 EXPORT_SYMBOL(default_wake_function);
3066
3067 /*
3068  * The core wakeup function.  Non-exclusive wakeups (nr_exclusive == 0) just
3069  * wake everything up.  If it's an exclusive wakeup (nr_exclusive == small +ve
3070  * number) then we wake all the non-exclusive tasks and one exclusive task.
3071  *
3072  * There are circumstances in which we can try to wake a task which has already
3073  * started to run but is not in state TASK_RUNNING.  try_to_wake_up() returns
3074  * zero in this (rare) case, and we handle it by continuing to scan the queue.
3075  */
3076 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3077                              int nr_exclusive, int sync, void *key)
3078 {
3079         struct list_head *tmp, *next;
3080
3081         list_for_each_safe(tmp, next, &q->task_list) {
3082                 wait_queue_t *curr;
3083                 unsigned flags;
3084                 curr = list_entry(tmp, wait_queue_t, task_list);
3085                 flags = curr->flags;
3086                 if (curr->func(curr, mode, sync, key) &&
3087                     (flags & WQ_FLAG_EXCLUSIVE) &&
3088                     !--nr_exclusive)
3089                         break;
3090         }
3091 }
3092
3093 /**
3094  * __wake_up - wake up threads blocked on a waitqueue.
3095  * @q: the waitqueue
3096  * @mode: which threads
3097  * @nr_exclusive: how many wake-one or wake-many threads to wake up
3098  * @key: is directly passed to the wakeup function
3099  */
3100 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3101                                 int nr_exclusive, void *key)
3102 {
3103         unsigned long flags;
3104
3105         spin_lock_irqsave(&q->lock, flags);
3106         __wake_up_common(q, mode, nr_exclusive, 0, key);
3107         spin_unlock_irqrestore(&q->lock, flags);
3108 }
3109
3110 EXPORT_SYMBOL(__wake_up);
3111
3112 /*
3113  * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3114  */
3115 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3116 {
3117         __wake_up_common(q, mode, 1, 0, NULL);
3118 }
3119
3120 /**
3121  * __wake_up_sync - wake up threads blocked on a waitqueue.
3122  * @q: the waitqueue
3123  * @mode: which threads
3124  * @nr_exclusive: how many wake-one or wake-many threads to wake up
3125  *
3126  * The sync wakeup differs that the waker knows that it will schedule
3127  * away soon, so while the target thread will be woken up, it will not
3128  * be migrated to another CPU - ie. the two threads are 'synchronized'
3129  * with each other. This can prevent needless bouncing between CPUs.
3130  *
3131  * On UP it can prevent extra preemption.
3132  */
3133 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3134 {
3135         unsigned long flags;
3136         int sync = 1;
3137
3138         if (unlikely(!q))
3139                 return;
3140
3141         if (unlikely(!nr_exclusive))
3142                 sync = 0;
3143
3144         spin_lock_irqsave(&q->lock, flags);
3145         __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3146         spin_unlock_irqrestore(&q->lock, flags);
3147 }
3148 EXPORT_SYMBOL_GPL(__wake_up_sync);      /* For internal use only */
3149
3150 void fastcall complete(struct completion *x)
3151 {
3152         unsigned long flags;
3153
3154         spin_lock_irqsave(&x->wait.lock, flags);
3155         x->done++;
3156         __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3157                          1, 0, NULL);
3158         spin_unlock_irqrestore(&x->wait.lock, flags);
3159 }
3160 EXPORT_SYMBOL(complete);
3161
3162 void fastcall complete_all(struct completion *x)
3163 {
3164         unsigned long flags;
3165
3166         spin_lock_irqsave(&x->wait.lock, flags);
3167         x->done += UINT_MAX/2;
3168         __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3169                          0, 0, NULL);
3170         spin_unlock_irqrestore(&x->wait.lock, flags);
3171 }
3172 EXPORT_SYMBOL(complete_all);
3173
3174 void fastcall __sched wait_for_completion(struct completion *x)
3175 {
3176         might_sleep();
3177         spin_lock_irq(&x->wait.lock);
3178         if (!x->done) {
3179                 DECLARE_WAITQUEUE(wait, current);
3180
3181                 wait.flags |= WQ_FLAG_EXCLUSIVE;
3182                 __add_wait_queue_tail(&x->wait, &wait);
3183                 do {
3184                         __set_current_state(TASK_UNINTERRUPTIBLE);
3185                         spin_unlock_irq(&x->wait.lock);
3186                         schedule();
3187                         spin_lock_irq(&x->wait.lock);
3188                 } while (!x->done);
3189                 __remove_wait_queue(&x->wait, &wait);
3190         }
3191         x->done--;
3192         spin_unlock_irq(&x->wait.lock);
3193 }
3194 EXPORT_SYMBOL(wait_for_completion);
3195
3196 unsigned long fastcall __sched
3197 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3198 {
3199         might_sleep();
3200
3201         spin_lock_irq(&x->wait.lock);
3202         if (!x->done) {
3203                 DECLARE_WAITQUEUE(wait, current);
3204
3205                 wait.flags |= WQ_FLAG_EXCLUSIVE;
3206                 __add_wait_queue_tail(&x->wait, &wait);
3207                 do {
3208                         __set_current_state(TASK_UNINTERRUPTIBLE);
3209                         spin_unlock_irq(&x->wait.lock);
3210                         timeout = schedule_timeout(timeout);
3211                         spin_lock_irq(&x->wait.lock);
3212                         if (!timeout) {
3213                                 __remove_wait_queue(&x->wait, &wait);
3214                                 goto out;
3215                         }
3216                 } while (!x->done);
3217                 __remove_wait_queue(&x->wait, &wait);
3218         }
3219         x->done--;
3220 out:
3221         spin_unlock_irq(&x->wait.lock);
3222         return timeout;
3223 }
3224 EXPORT_SYMBOL(wait_for_completion_timeout);
3225
3226 int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3227 {
3228         int ret = 0;
3229
3230         might_sleep();
3231
3232         spin_lock_irq(&x->wait.lock);
3233         if (!x->done) {
3234                 DECLARE_WAITQUEUE(wait, current);
3235
3236                 wait.flags |= WQ_FLAG_EXCLUSIVE;
3237                 __add_wait_queue_tail(&x->wait, &wait);
3238                 do {
3239                         if (signal_pending(current)) {
3240                                 ret = -ERESTARTSYS;
3241                                 __remove_wait_queue(&x->wait, &wait);
3242                                 goto out;
3243                         }
3244                         __set_current_state(TASK_INTERRUPTIBLE);
3245                         spin_unlock_irq(&x->wait.lock);
3246                         schedule();
3247                         spin_lock_irq(&x->wait.lock);
3248                 } while (!x->done);
3249                 __remove_wait_queue(&x->wait, &wait);
3250         }
3251         x->done--;
3252 out:
3253         spin_unlock_irq(&x->wait.lock);
3254
3255         return ret;
3256 }
3257 EXPORT_SYMBOL(wait_for_completion_interruptible);
3258
3259 unsigned long fastcall __sched
3260 wait_for_completion_interruptible_timeout(struct completion *x,
3261                                           unsigned long timeout)
3262 {
3263         might_sleep();
3264
3265         spin_lock_irq(&x->wait.lock);
3266         if (!x->done) {
3267                 DECLARE_WAITQUEUE(wait, current);
3268
3269                 wait.flags |= WQ_FLAG_EXCLUSIVE;
3270                 __add_wait_queue_tail(&x->wait, &wait);
3271                 do {
3272                         if (signal_pending(current)) {
3273                                 timeout = -ERESTARTSYS;
3274                                 __remove_wait_queue(&x->wait, &wait);
3275                                 goto out;
3276                         }
3277                         __set_current_state(TASK_INTERRUPTIBLE);
3278                         spin_unlock_irq(&x->wait.lock);
3279                         timeout = schedule_timeout(timeout);
3280                         spin_lock_irq(&x->wait.lock);
3281                         if (!timeout) {
3282                                 __remove_wait_queue(&x->wait, &wait);
3283                                 goto out;
3284                         }
3285                 } while (!x->done);
3286                 __remove_wait_queue(&x->wait, &wait);
3287         }
3288         x->done--;
3289 out:
3290         spin_unlock_irq(&x->wait.lock);
3291         return timeout;
3292 }
3293 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3294
3295
3296 #define SLEEP_ON_VAR                                    \
3297         unsigned long flags;                            \
3298         wait_queue_t wait;                              \
3299         init_waitqueue_entry(&wait, current);
3300
3301 #define SLEEP_ON_HEAD                                   \
3302         spin_lock_irqsave(&q->lock,flags);              \
3303         __add_wait_queue(q, &wait);                     \
3304         spin_unlock(&q->lock);
3305
3306 #define SLEEP_ON_TAIL                                   \
3307         spin_lock_irq(&q->lock);                        \
3308         __remove_wait_queue(q, &wait);                  \
3309         spin_unlock_irqrestore(&q->lock, flags);
3310
3311 #define SLEEP_ON_BKLCHECK                               \
3312         if (unlikely(!kernel_locked()) &&               \
3313             sleep_on_bkl_warnings < 10) {               \
3314                 sleep_on_bkl_warnings++;                \
3315                 WARN_ON(1);                             \
3316         }
3317
3318 static int sleep_on_bkl_warnings;
3319
3320 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3321 {
3322         SLEEP_ON_VAR
3323
3324         SLEEP_ON_BKLCHECK
3325
3326         current->state = TASK_INTERRUPTIBLE;
3327
3328         SLEEP_ON_HEAD
3329         schedule();
3330         SLEEP_ON_TAIL
3331 }
3332
3333 EXPORT_SYMBOL(interruptible_sleep_on);
3334
3335 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3336 {
3337         SLEEP_ON_VAR
3338
3339         SLEEP_ON_BKLCHECK
3340
3341         current->state = TASK_INTERRUPTIBLE;
3342
3343         SLEEP_ON_HEAD
3344         timeout = schedule_timeout(timeout);
3345         SLEEP_ON_TAIL
3346
3347         return timeout;
3348 }
3349
3350 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3351
3352 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3353 {
3354         SLEEP_ON_VAR
3355
3356         SLEEP_ON_BKLCHECK
3357
3358         current->state = TASK_UNINTERRUPTIBLE;
3359
3360         SLEEP_ON_HEAD
3361         timeout = schedule_timeout(timeout);
3362         SLEEP_ON_TAIL
3363
3364         return timeout;
3365 }
3366
3367 EXPORT_SYMBOL(sleep_on_timeout);
3368
3369 void set_user_nice(task_t *p, long nice)
3370 {
3371         unsigned long flags;
3372         prio_array_t *array;
3373         runqueue_t *rq;
3374         int old_prio, new_prio, delta;
3375
3376         if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3377                 return;
3378         /*
3379          * We have to be careful, if called from sys_setpriority(),
3380          * the task might be in the middle of scheduling on another CPU.
3381          */
3382         rq = task_rq_lock(p, &flags);
3383         /*
3384          * The RT priorities are set via sched_setscheduler(), but we still
3385          * allow the 'normal' nice value to be set - but as expected
3386          * it wont have any effect on scheduling until the task is
3387          * not SCHED_NORMAL:
3388          */
3389         if (rt_task(p)) {
3390                 p->static_prio = NICE_TO_PRIO(nice);
3391                 goto out_unlock;
3392         }
3393         array = p->array;
3394         if (array)
3395                 dequeue_task(p, array);
3396
3397         old_prio = p->prio;
3398         new_prio = NICE_TO_PRIO(nice);
3399         delta = new_prio - old_prio;
3400         p->static_prio = NICE_TO_PRIO(nice);
3401         p->prio += delta;
3402
3403         if (array) {
3404                 enqueue_task(p, array);
3405                 /*
3406                  * If the task increased its priority or is running and
3407                  * lowered its priority, then reschedule its CPU:
3408                  */
3409                 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3410                         resched_task(rq->curr);
3411         }
3412 out_unlock:
3413         task_rq_unlock(rq, &flags);
3414 }
3415
3416 EXPORT_SYMBOL(set_user_nice);
3417
3418 /*
3419  * can_nice - check if a task can reduce its nice value
3420  * @p: task
3421  * @nice: nice value
3422  */
3423 int can_nice(const task_t *p, const int nice)
3424 {
3425         /* convert nice value [19,-20] to rlimit style value [0,39] */
3426         int nice_rlim = 19 - nice;
3427         return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
3428                 capable(CAP_SYS_NICE));
3429 }
3430
3431 #ifdef __ARCH_WANT_SYS_NICE
3432
3433 /*
3434  * sys_nice - change the priority of the current process.
3435  * @increment: priority increment
3436  *
3437  * sys_setpriority is a more generic, but much slower function that
3438  * does similar things.
3439  */
3440 asmlinkage long sys_nice(int increment)
3441 {
3442         int retval;
3443         long nice;
3444
3445         /*
3446          * Setpriority might change our priority at the same moment.
3447          * We don't have to worry. Conceptually one call occurs first
3448          * and we have a single winner.
3449          */
3450         if (increment < -40)
3451                 increment = -40;
3452         if (increment > 40)
3453                 increment = 40;
3454
3455         nice = PRIO_TO_NICE(current->static_prio) + increment;
3456         if (nice < -20)
3457                 nice = -20;
3458         if (nice > 19)
3459                 nice = 19;
3460
3461         if (increment < 0 && !can_nice(current, nice))
3462                 return vx_flags(VXF_IGNEG_NICE, 0) ? 0 : -EPERM;
3463
3464         retval = security_task_setnice(current, nice);
3465         if (retval)
3466                 return retval;
3467
3468         set_user_nice(current, nice);
3469         return 0;
3470 }
3471
3472 #endif
3473
3474 /**
3475  * task_prio - return the priority value of a given task.
3476  * @p: the task in question.
3477  *
3478  * This is the priority value as seen by users in /proc.
3479  * RT tasks are offset by -200. Normal tasks are centered
3480  * around 0, value goes from -16 to +15.
3481  */
3482 int task_prio(const task_t *p)
3483 {
3484         return p->prio - MAX_RT_PRIO;
3485 }
3486
3487 /**
3488  * task_nice - return the nice value of a given task.
3489  * @p: the task in question.
3490  */
3491 int task_nice(const task_t *p)
3492 {
3493         return TASK_NICE(p);
3494 }
3495
3496 /*
3497  * The only users of task_nice are binfmt_elf and binfmt_elf32.
3498  * binfmt_elf is no longer modular, but binfmt_elf32 still is.
3499  * Therefore, task_nice is needed if there is a compat_mode.
3500  */
3501 #ifdef CONFIG_COMPAT
3502 EXPORT_SYMBOL_GPL(task_nice);
3503 #endif
3504
3505 /**
3506  * idle_cpu - is a given cpu idle currently?
3507  * @cpu: the processor in question.
3508  */
3509 int idle_cpu(int cpu)
3510 {
3511         return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3512 }
3513
3514 EXPORT_SYMBOL_GPL(idle_cpu);
3515
3516 /**
3517  * idle_task - return the idle task for a given cpu.
3518  * @cpu: the processor in question.
3519  */
3520 task_t *idle_task(int cpu)
3521 {
3522         return cpu_rq(cpu)->idle;
3523 }
3524
3525 /**
3526  * find_process_by_pid - find a process with a matching PID value.
3527  * @pid: the pid in question.
3528  */
3529 static inline task_t *find_process_by_pid(pid_t pid)
3530 {
3531         return pid ? find_task_by_pid(pid) : current;
3532 }
3533
3534 /* Actually do priority change: must hold rq lock. */
3535 static void __setscheduler(struct task_struct *p, int policy, int prio)
3536 {
3537         BUG_ON(p->array);
3538         p->policy = policy;
3539         p->rt_priority = prio;
3540         if (policy != SCHED_NORMAL)
3541                 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
3542         else
3543                 p->prio = p->static_prio;
3544 }
3545
3546 /**
3547  * sched_setscheduler - change the scheduling policy and/or RT priority of
3548  * a thread.
3549  * @p: the task in question.
3550  * @policy: new policy.
3551  * @param: structure containing the new RT priority.
3552  */
3553 int sched_setscheduler(struct task_struct *p, int policy, struct sched_param *param)
3554 {
3555         int retval;
3556         int oldprio, oldpolicy = -1;
3557         prio_array_t *array;
3558         unsigned long flags;
3559         runqueue_t *rq;
3560
3561 recheck:
3562         /* double check policy once rq lock held */
3563         if (policy < 0)
3564                 policy = oldpolicy = p->policy;
3565         else if (policy != SCHED_FIFO && policy != SCHED_RR &&
3566                                 policy != SCHED_NORMAL)
3567                         return -EINVAL;
3568         /*
3569          * Valid priorities for SCHED_FIFO and SCHED_RR are
3570          * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
3571          */
3572         if (param->sched_priority < 0 ||
3573             param->sched_priority > MAX_USER_RT_PRIO-1)
3574                 return -EINVAL;
3575         if ((policy == SCHED_NORMAL) != (param->sched_priority == 0))
3576                 return -EINVAL;
3577
3578         if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
3579             param->sched_priority > p->signal->rlim[RLIMIT_RTPRIO].rlim_cur &&
3580             !capable(CAP_SYS_NICE))
3581                 return -EPERM;
3582         if ((current->euid != p->euid) && (current->euid != p->uid) &&
3583             !capable(CAP_SYS_NICE))
3584                 return -EPERM;
3585
3586         retval = security_task_setscheduler(p, policy, param);
3587         if (retval)
3588                 return retval;
3589         /*
3590          * To be able to change p->policy safely, the apropriate
3591          * runqueue lock must be held.
3592          */
3593         rq = task_rq_lock(p, &flags);
3594         /* recheck policy now with rq lock held */
3595         if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3596                 policy = oldpolicy = -1;
3597                 task_rq_unlock(rq, &flags);
3598                 goto recheck;
3599         }
3600         array = p->array;
3601         if (array)
3602                 deactivate_task(p, rq);
3603         oldprio = p->prio;
3604         __setscheduler(p, policy, param->sched_priority);
3605         if (array) {
3606                 vx_activate_task(p);
3607                 __activate_task(p, rq);
3608                 /*
3609                  * Reschedule if we are currently running on this runqueue and
3610                  * our priority decreased, or if we are not currently running on
3611                  * this runqueue and our priority is higher than the current's
3612                  */
3613                 if (task_running(rq, p)) {
3614                         if (p->prio > oldprio)
3615                                 resched_task(rq->curr);
3616                 } else if (TASK_PREEMPTS_CURR(p, rq))
3617                         resched_task(rq->curr);
3618         }
3619         task_rq_unlock(rq, &flags);
3620         return 0;
3621 }
3622 EXPORT_SYMBOL_GPL(sched_setscheduler);
3623
3624 static int do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3625 {
3626         int retval;
3627         struct sched_param lparam;
3628         struct task_struct *p;
3629
3630         if (!param || pid < 0)
3631                 return -EINVAL;
3632         if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
3633                 return -EFAULT;
3634         read_lock_irq(&tasklist_lock);
3635         p = find_process_by_pid(pid);
3636         if (!p) {
3637                 read_unlock_irq(&tasklist_lock);
3638                 return -ESRCH;
3639         }
3640         retval = sched_setscheduler(p, policy, &lparam);
3641         read_unlock_irq(&tasklist_lock);
3642         return retval;
3643 }
3644
3645 /**
3646  * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3647  * @pid: the pid in question.
3648  * @policy: new policy.
3649  * @param: structure containing the new RT priority.
3650  */
3651 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3652                                        struct sched_param __user *param)
3653 {
3654         return do_sched_setscheduler(pid, policy, param);
3655 }
3656
3657 /**
3658  * sys_sched_setparam - set/change the RT priority of a thread
3659  * @pid: the pid in question.
3660  * @param: structure containing the new RT priority.
3661  */
3662 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3663 {
3664         return do_sched_setscheduler(pid, -1, param);
3665 }
3666
3667 /**
3668  * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3669  * @pid: the pid in question.
3670  */
3671 asmlinkage long sys_sched_getscheduler(pid_t pid)
3672 {
3673         int retval = -EINVAL;
3674         task_t *p;
3675
3676         if (pid < 0)
3677                 goto out_nounlock;
3678
3679         retval = -ESRCH;
3680         read_lock(&tasklist_lock);
3681         p = find_process_by_pid(pid);
3682         if (p) {
3683                 retval = security_task_getscheduler(p);
3684                 if (!retval)
3685                         retval = p->policy;
3686         }
3687         read_unlock(&tasklist_lock);
3688
3689 out_nounlock:
3690         return retval;
3691 }
3692
3693 /**
3694  * sys_sched_getscheduler - get the RT priority of a thread
3695  * @pid: the pid in question.
3696  * @param: structure containing the RT priority.
3697  */
3698 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3699 {
3700         struct sched_param lp;
3701         int retval = -EINVAL;
3702         task_t *p;
3703
3704         if (!param || pid < 0)
3705                 goto out_nounlock;
3706
3707         read_lock(&tasklist_lock);
3708         p = find_process_by_pid(pid);
3709         retval = -ESRCH;
3710         if (!p)
3711                 goto out_unlock;
3712
3713         retval = security_task_getscheduler(p);
3714         if (retval)
3715                 goto out_unlock;
3716
3717         lp.sched_priority = p->rt_priority;
3718         read_unlock(&tasklist_lock);
3719
3720         /*
3721          * This one might sleep, we cannot do it with a spinlock held ...
3722          */
3723         retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3724
3725 out_nounlock:
3726         return retval;
3727
3728 out_unlock:
3729         read_unlock(&tasklist_lock);
3730         return retval;
3731 }
3732
3733 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
3734 {
3735         task_t *p;
3736         int retval;
3737         cpumask_t cpus_allowed;
3738
3739         lock_cpu_hotplug();
3740         read_lock(&tasklist_lock);
3741
3742         p = find_process_by_pid(pid);
3743         if (!p) {
3744                 read_unlock(&tasklist_lock);
3745                 unlock_cpu_hotplug();
3746                 return -ESRCH;
3747         }
3748
3749         /*
3750          * It is not safe to call set_cpus_allowed with the
3751          * tasklist_lock held.  We will bump the task_struct's
3752          * usage count and then drop tasklist_lock.
3753          */
3754         get_task_struct(p);
3755         read_unlock(&tasklist_lock);
3756
3757         retval = -EPERM;
3758         if ((current->euid != p->euid) && (current->euid != p->uid) &&
3759                         !capable(CAP_SYS_NICE))
3760                 goto out_unlock;
3761
3762         cpus_allowed = cpuset_cpus_allowed(p);
3763         cpus_and(new_mask, new_mask, cpus_allowed);
3764         retval = set_cpus_allowed(p, new_mask);
3765
3766 out_unlock:
3767         put_task_struct(p);
3768         unlock_cpu_hotplug();
3769         return retval;
3770 }
3771
3772 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
3773                              cpumask_t *new_mask)
3774 {
3775         if (len < sizeof(cpumask_t)) {
3776                 memset(new_mask, 0, sizeof(cpumask_t));
3777         } else if (len > sizeof(cpumask_t)) {
3778                 len = sizeof(cpumask_t);
3779         }
3780         return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
3781 }
3782
3783 /**
3784  * sys_sched_setaffinity - set the cpu affinity of a process
3785  * @pid: pid of the process
3786  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3787  * @user_mask_ptr: user-space pointer to the new cpu mask
3788  */
3789 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
3790                                       unsigned long __user *user_mask_ptr)
3791 {
3792         cpumask_t new_mask;
3793         int retval;
3794
3795         retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
3796         if (retval)
3797                 return retval;
3798
3799         return sched_setaffinity(pid, new_mask);
3800 }
3801
3802 /*
3803  * Represents all cpu's present in the system
3804  * In systems capable of hotplug, this map could dynamically grow
3805  * as new cpu's are detected in the system via any platform specific
3806  * method, such as ACPI for e.g.
3807  */
3808
3809 cpumask_t cpu_present_map;
3810 EXPORT_SYMBOL(cpu_present_map);
3811
3812 #ifndef CONFIG_SMP
3813 cpumask_t cpu_online_map = CPU_MASK_ALL;
3814 cpumask_t cpu_possible_map = CPU_MASK_ALL;
3815 #endif
3816
3817 long sched_getaffinity(pid_t pid, cpumask_t *mask)
3818 {
3819         int retval;
3820         task_t *p;
3821
3822         lock_cpu_hotplug();
3823         read_lock(&tasklist_lock);
3824
3825         retval = -ESRCH;
3826         p = find_process_by_pid(pid);
3827         if (!p)
3828                 goto out_unlock;
3829
3830         retval = 0;
3831         cpus_and(*mask, p->cpus_allowed, cpu_possible_map);
3832
3833 out_unlock:
3834         read_unlock(&tasklist_lock);
3835         unlock_cpu_hotplug();
3836         if (retval)
3837                 return retval;
3838
3839         return 0;
3840 }
3841
3842 /**
3843  * sys_sched_getaffinity - get the cpu affinity of a process
3844  * @pid: pid of the process
3845  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3846  * @user_mask_ptr: user-space pointer to hold the current cpu mask
3847  */
3848 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
3849                                       unsigned long __user *user_mask_ptr)
3850 {
3851         int ret;
3852         cpumask_t mask;
3853
3854         if (len < sizeof(cpumask_t))
3855                 return -EINVAL;
3856
3857         ret = sched_getaffinity(pid, &mask);
3858         if (ret < 0)
3859                 return ret;
3860
3861         if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
3862                 return -EFAULT;
3863
3864         return sizeof(cpumask_t);
3865 }
3866
3867 /**
3868  * sys_sched_yield - yield the current processor to other threads.
3869  *
3870  * this function yields the current CPU by moving the calling thread
3871  * to the expired array. If there are no other threads running on this
3872  * CPU then this function will return.
3873  */
3874 asmlinkage long sys_sched_yield(void)
3875 {
3876         runqueue_t *rq = this_rq_lock();
3877         prio_array_t *array = current->array;
3878         prio_array_t *target = rq->expired;
3879
3880         schedstat_inc(rq, yld_cnt);
3881         /*
3882          * We implement yielding by moving the task into the expired
3883          * queue.
3884          *
3885          * (special rule: RT tasks will just roundrobin in the active
3886          *  array.)
3887          */
3888         if (rt_task(current))
3889                 target = rq->active;
3890
3891         if (current->array->nr_active == 1) {
3892                 schedstat_inc(rq, yld_act_empty);
3893                 if (!rq->expired->nr_active)
3894                         schedstat_inc(rq, yld_both_empty);
3895         } else if (!rq->expired->nr_active)
3896                 schedstat_inc(rq, yld_exp_empty);
3897
3898         if (array != target) {
3899                 dequeue_task(current, array);
3900                 enqueue_task(current, target);
3901         } else
3902                 /*
3903                  * requeue_task is cheaper so perform that if possible.
3904                  */
3905                 requeue_task(current, array);
3906
3907         /*
3908          * Since we are going to call schedule() anyway, there's
3909          * no need to preempt or enable interrupts:
3910          */
3911         __release(rq->lock);
3912         _raw_spin_unlock(&rq->lock);
3913         preempt_enable_no_resched();
3914
3915         schedule();
3916
3917         return 0;
3918 }
3919
3920 static inline void __cond_resched(void)
3921 {
3922         do {
3923                 add_preempt_count(PREEMPT_ACTIVE);
3924                 schedule();
3925                 sub_preempt_count(PREEMPT_ACTIVE);
3926         } while (need_resched());
3927 }
3928
3929 int __sched cond_resched(void)
3930 {
3931         if (need_resched()) {
3932                 __cond_resched();
3933                 return 1;
3934         }
3935         return 0;
3936 }
3937
3938 EXPORT_SYMBOL(cond_resched);
3939
3940 /*
3941  * cond_resched_lock() - if a reschedule is pending, drop the given lock,
3942  * call schedule, and on return reacquire the lock.
3943  *
3944  * This works OK both with and without CONFIG_PREEMPT.  We do strange low-level
3945  * operations here to prevent schedule() from being called twice (once via
3946  * spin_unlock(), once by hand).
3947  */
3948 int cond_resched_lock(spinlock_t * lock)
3949 {
3950         int ret = 0;
3951
3952         if (need_lockbreak(lock)) {
3953                 spin_unlock(lock);
3954                 cpu_relax();
3955                 ret = 1;
3956                 spin_lock(lock);
3957         }
3958         if (need_resched()) {
3959                 _raw_spin_unlock(lock);
3960                 preempt_enable_no_resched();
3961                 __cond_resched();
3962                 ret = 1;
3963                 spin_lock(lock);
3964         }
3965         return ret;
3966 }
3967
3968 EXPORT_SYMBOL(cond_resched_lock);
3969
3970 int __sched cond_resched_softirq(void)
3971 {
3972         BUG_ON(!in_softirq());
3973
3974         if (need_resched()) {
3975                 __local_bh_enable();
3976                 __cond_resched();
3977                 local_bh_disable();
3978                 return 1;
3979         }
3980         return 0;
3981 }
3982
3983 EXPORT_SYMBOL(cond_resched_softirq);
3984
3985
3986 /**
3987  * yield - yield the current processor to other threads.
3988  *
3989  * this is a shortcut for kernel-space yielding - it marks the
3990  * thread runnable and calls sys_sched_yield().
3991  */
3992 void __sched yield(void)
3993 {
3994         set_current_state(TASK_RUNNING);
3995         sys_sched_yield();
3996 }
3997
3998 EXPORT_SYMBOL(yield);
3999
4000 /*
4001  * This task is about to go to sleep on IO.  Increment rq->nr_iowait so
4002  * that process accounting knows that this is a task in IO wait state.
4003  *
4004  * But don't do that if it is a deliberate, throttling IO wait (this task
4005  * has set its backing_dev_info: the queue against which it should throttle)
4006  */
4007 void __sched io_schedule(void)
4008 {
4009         struct runqueue *rq = &per_cpu(runqueues, _smp_processor_id());
4010
4011         atomic_inc(&rq->nr_iowait);
4012         schedule();
4013         atomic_dec(&rq->nr_iowait);
4014 }
4015
4016 EXPORT_SYMBOL(io_schedule);
4017
4018 long __sched io_schedule_timeout(long timeout)
4019 {
4020         struct runqueue *rq = &per_cpu(runqueues, _smp_processor_id());
4021         long ret;
4022
4023         atomic_inc(&rq->nr_iowait);
4024         ret = schedule_timeout(timeout);
4025         atomic_dec(&rq->nr_iowait);
4026         return ret;
4027 }
4028
4029 /**
4030  * sys_sched_get_priority_max - return maximum RT priority.
4031  * @policy: scheduling class.
4032  *
4033  * this syscall returns the maximum rt_priority that can be used
4034  * by a given scheduling class.
4035  */
4036 asmlinkage long sys_sched_get_priority_max(int policy)
4037 {
4038         int ret = -EINVAL;
4039
4040         switch (policy) {
4041         case SCHED_FIFO:
4042         case SCHED_RR:
4043                 ret = MAX_USER_RT_PRIO-1;
4044                 break;
4045         case SCHED_NORMAL:
4046                 ret = 0;
4047                 break;
4048         }
4049         return ret;
4050 }
4051
4052 /**
4053  * sys_sched_get_priority_min - return minimum RT priority.
4054  * @policy: scheduling class.
4055  *
4056  * this syscall returns the minimum rt_priority that can be used
4057  * by a given scheduling class.
4058  */
4059 asmlinkage long sys_sched_get_priority_min(int policy)
4060 {
4061         int ret = -EINVAL;
4062
4063         switch (policy) {
4064         case SCHED_FIFO:
4065         case SCHED_RR:
4066                 ret = 1;
4067                 break;
4068         case SCHED_NORMAL:
4069                 ret = 0;
4070         }
4071         return ret;
4072 }
4073
4074 /**
4075  * sys_sched_rr_get_interval - return the default timeslice of a process.
4076  * @pid: pid of the process.
4077  * @interval: userspace pointer to the timeslice value.
4078  *
4079  * this syscall writes the default timeslice value of a given process
4080  * into the user-space timespec buffer. A value of '0' means infinity.
4081  */
4082 asmlinkage
4083 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4084 {
4085         int retval = -EINVAL;
4086         struct timespec t;
4087         task_t *p;
4088
4089         if (pid < 0)
4090                 goto out_nounlock;
4091
4092         retval = -ESRCH;
4093         read_lock(&tasklist_lock);
4094         p = find_process_by_pid(pid);
4095         if (!p)
4096                 goto out_unlock;
4097
4098         retval = security_task_getscheduler(p);
4099         if (retval)
4100                 goto out_unlock;
4101
4102         jiffies_to_timespec(p->policy & SCHED_FIFO ?
4103                                 0 : task_timeslice(p), &t);
4104         read_unlock(&tasklist_lock);
4105         retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4106 out_nounlock:
4107         return retval;
4108 out_unlock:
4109         read_unlock(&tasklist_lock);
4110         return retval;
4111 }
4112
4113 static inline struct task_struct *eldest_child(struct task_struct *p)
4114 {
4115         if (list_empty(&p->children)) return NULL;
4116         return list_entry(p->children.next,struct task_struct,sibling);
4117 }
4118
4119 static inline struct task_struct *older_sibling(struct task_struct *p)
4120 {
4121         if (p->sibling.prev==&p->parent->children) return NULL;
4122         return list_entry(p->sibling.prev,struct task_struct,sibling);
4123 }
4124
4125 static inline struct task_struct *younger_sibling(struct task_struct *p)
4126 {
4127         if (p->sibling.next==&p->parent->children) return NULL;
4128         return list_entry(p->sibling.next,struct task_struct,sibling);
4129 }
4130
4131 static void show_task(task_t * p)
4132 {
4133         task_t *relative;
4134         unsigned state;
4135         unsigned long free = 0;
4136         static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
4137
4138         printk("%-13.13s ", p->comm);
4139         state = p->state ? __ffs(p->state) + 1 : 0;
4140         if (state < ARRAY_SIZE(stat_nam))
4141                 printk(stat_nam[state]);
4142         else
4143                 printk("?");
4144 #if (BITS_PER_LONG == 32)
4145         if (state == TASK_RUNNING)
4146                 printk(" running ");
4147         else
4148                 printk(" %08lX ", thread_saved_pc(p));
4149 #else
4150         if (state == TASK_RUNNING)
4151                 printk("  running task   ");
4152         else
4153                 printk(" %016lx ", thread_saved_pc(p));
4154 #endif
4155 #ifdef CONFIG_DEBUG_STACK_USAGE
4156         {
4157                 unsigned long * n = (unsigned long *) (p->thread_info+1);
4158                 while (!*n)
4159                         n++;
4160                 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
4161         }
4162 #endif
4163         printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
4164         if ((relative = eldest_child(p)))
4165                 printk("%5d ", relative->pid);
4166         else
4167                 printk("      ");
4168         if ((relative = younger_sibling(p)))
4169                 printk("%7d", relative->pid);
4170         else
4171                 printk("       ");
4172         if ((relative = older_sibling(p)))
4173                 printk(" %5d", relative->pid);
4174         else
4175                 printk("      ");
4176         if (!p->mm)
4177                 printk(" (L-TLB)\n");
4178         else
4179                 printk(" (NOTLB)\n");
4180
4181         if (state != TASK_RUNNING)
4182                 show_stack(p, NULL);
4183 }
4184
4185 void show_state(void)
4186 {
4187         task_t *g, *p;
4188
4189 #if (BITS_PER_LONG == 32)
4190         printk("\n"
4191                "                                               sibling\n");
4192         printk("  task             PC      pid father child younger older\n");
4193 #else
4194         printk("\n"
4195                "                                                       sibling\n");
4196         printk("  task                 PC          pid father child younger older\n");
4197 #endif
4198         read_lock(&tasklist_lock);
4199         do_each_thread(g, p) {
4200                 /*
4201                  * reset the NMI-timeout, listing all files on a slow
4202                  * console might take alot of time:
4203                  */
4204                 touch_nmi_watchdog();
4205                 show_task(p);
4206         } while_each_thread(g, p);
4207
4208         read_unlock(&tasklist_lock);
4209 }
4210
4211 EXPORT_SYMBOL_GPL(show_state);
4212
4213 void __devinit init_idle(task_t *idle, int cpu)
4214 {
4215         runqueue_t *rq = cpu_rq(cpu);
4216         unsigned long flags;
4217
4218         idle->sleep_avg = 0;
4219         idle->array = NULL;
4220         idle->prio = MAX_PRIO;
4221         idle->state = TASK_RUNNING;
4222         idle->cpus_allowed = cpumask_of_cpu(cpu);
4223         set_task_cpu(idle, cpu);
4224
4225         spin_lock_irqsave(&rq->lock, flags);
4226         rq->curr = rq->idle = idle;
4227         set_tsk_need_resched(idle);
4228         spin_unlock_irqrestore(&rq->lock, flags);
4229
4230         /* Set the preempt count _outside_ the spinlocks! */
4231 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4232         idle->thread_info->preempt_count = (idle->lock_depth >= 0);
4233 #else
4234         idle->thread_info->preempt_count = 0;
4235 #endif
4236 }
4237
4238 /*
4239  * In a system that switches off the HZ timer nohz_cpu_mask
4240  * indicates which cpus entered this state. This is used
4241  * in the rcu update to wait only for active cpus. For system
4242  * which do not switch off the HZ timer nohz_cpu_mask should
4243  * always be CPU_MASK_NONE.
4244  */
4245 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4246
4247 #ifdef CONFIG_SMP
4248 /*
4249  * This is how migration works:
4250  *
4251  * 1) we queue a migration_req_t structure in the source CPU's
4252  *    runqueue and wake up that CPU's migration thread.
4253  * 2) we down() the locked semaphore => thread blocks.
4254  * 3) migration thread wakes up (implicitly it forces the migrated
4255  *    thread off the CPU)
4256  * 4) it gets the migration request and checks whether the migrated
4257  *    task is still in the wrong runqueue.
4258  * 5) if it's in the wrong runqueue then the migration thread removes
4259  *    it and puts it into the right queue.
4260  * 6) migration thread up()s the semaphore.
4261  * 7) we wake up and the migration is done.
4262  */
4263
4264 /*
4265  * Change a given task's CPU affinity. Migrate the thread to a
4266  * proper CPU and schedule it away if the CPU it's executing on
4267  * is removed from the allowed bitmask.
4268  *
4269  * NOTE: the caller must have a valid reference to the task, the
4270  * task must not exit() & deallocate itself prematurely.  The
4271  * call is not atomic; no spinlocks may be held.
4272  */
4273 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
4274 {
4275         unsigned long flags;
4276         int ret = 0;
4277         migration_req_t req;
4278         runqueue_t *rq;
4279
4280         rq = task_rq_lock(p, &flags);
4281         if (!cpus_intersects(new_mask, cpu_online_map)) {
4282                 ret = -EINVAL;
4283                 goto out;
4284         }
4285
4286         p->cpus_allowed = new_mask;
4287         /* Can the task run on the task's current CPU? If so, we're done */
4288         if (cpu_isset(task_cpu(p), new_mask))
4289                 goto out;
4290
4291         if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4292                 /* Need help from migration thread: drop lock and wait. */
4293                 task_rq_unlock(rq, &flags);
4294                 wake_up_process(rq->migration_thread);
4295                 wait_for_completion(&req.done);
4296                 tlb_migrate_finish(p->mm);
4297                 return 0;
4298         }
4299 out:
4300         task_rq_unlock(rq, &flags);
4301         return ret;
4302 }
4303
4304 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4305
4306 /*
4307  * Move (not current) task off this cpu, onto dest cpu.  We're doing
4308  * this because either it can't run here any more (set_cpus_allowed()
4309  * away from this CPU, or CPU going down), or because we're
4310  * attempting to rebalance this task on exec (sched_exec).
4311  *
4312  * So we race with normal scheduler movements, but that's OK, as long
4313  * as the task is no longer on this CPU.
4314  */
4315 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4316 {
4317         runqueue_t *rq_dest, *rq_src;
4318
4319         if (unlikely(cpu_is_offline(dest_cpu)))
4320                 return;
4321
4322         rq_src = cpu_rq(src_cpu);
4323         rq_dest = cpu_rq(dest_cpu);
4324
4325         double_rq_lock(rq_src, rq_dest);
4326         /* Already moved. */
4327         if (task_cpu(p) != src_cpu)
4328                 goto out;
4329         /* Affinity changed (again). */
4330         if (!cpu_isset(dest_cpu, p->cpus_allowed))
4331                 goto out;
4332
4333         set_task_cpu(p, dest_cpu);
4334         if (p->array) {
4335                 /*
4336                  * Sync timestamp with rq_dest's before activating.
4337                  * The same thing could be achieved by doing this step
4338                  * afterwards, and pretending it was a local activate.
4339                  * This way is cleaner and logically correct.
4340                  */
4341                 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4342                                 + rq_dest->timestamp_last_tick;
4343                 deactivate_task(p, rq_src);
4344                 activate_task(p, rq_dest, 0);
4345                 if (TASK_PREEMPTS_CURR(p, rq_dest))
4346                         resched_task(rq_dest->curr);
4347         }
4348
4349 out:
4350         double_rq_unlock(rq_src, rq_dest);
4351 }
4352
4353 /*
4354  * migration_thread - this is a highprio system thread that performs
4355  * thread migration by bumping thread off CPU then 'pushing' onto
4356  * another runqueue.
4357  */
4358 static int migration_thread(void * data)
4359 {
4360         runqueue_t *rq;
4361         int cpu = (long)data;
4362
4363         rq = cpu_rq(cpu);
4364         BUG_ON(rq->migration_thread != current);
4365
4366         set_current_state(TASK_INTERRUPTIBLE);
4367         while (!kthread_should_stop()) {
4368                 struct list_head *head;
4369                 migration_req_t *req;
4370
4371                 if (current->flags & PF_FREEZE)
4372                         refrigerator(PF_FREEZE);
4373
4374                 spin_lock_irq(&rq->lock);
4375
4376                 if (cpu_is_offline(cpu)) {
4377                         spin_unlock_irq(&rq->lock);
4378                         goto wait_to_die;
4379                 }
4380
4381                 if (rq->active_balance) {
4382                         active_load_balance(rq, cpu);
4383                         rq->active_balance = 0;
4384                 }
4385
4386                 head = &rq->migration_queue;
4387
4388                 if (list_empty(head)) {
4389                         spin_unlock_irq(&rq->lock);
4390                         schedule();
4391                         set_current_state(TASK_INTERRUPTIBLE);
4392                         continue;
4393                 }
4394                 req = list_entry(head->next, migration_req_t, list);
4395                 list_del_init(head->next);
4396
4397                 if (req->type == REQ_MOVE_TASK) {
4398                         spin_unlock(&rq->lock);
4399                         __migrate_task(req->task, cpu, req->dest_cpu);
4400                         local_irq_enable();
4401                 } else if (req->type == REQ_SET_DOMAIN) {
4402                         rq->sd = req->sd;
4403                         spin_unlock_irq(&rq->lock);
4404                 } else {
4405                         spin_unlock_irq(&rq->lock);
4406                         WARN_ON(1);
4407                 }
4408
4409                 complete(&req->done);
4410         }
4411         __set_current_state(TASK_RUNNING);
4412         return 0;
4413
4414 wait_to_die:
4415         /* Wait for kthread_stop */
4416         set_current_state(TASK_INTERRUPTIBLE);
4417         while (!kthread_should_stop()) {
4418                 schedule();
4419                 set_current_state(TASK_INTERRUPTIBLE);
4420         }
4421         __set_current_state(TASK_RUNNING);
4422         return 0;
4423 }
4424
4425 #ifdef CONFIG_HOTPLUG_CPU
4426 /* Figure out where task on dead CPU should go, use force if neccessary. */
4427 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
4428 {
4429         int dest_cpu;
4430         cpumask_t mask;
4431
4432         /* On same node? */
4433         mask = node_to_cpumask(cpu_to_node(dead_cpu));
4434         cpus_and(mask, mask, tsk->cpus_allowed);
4435         dest_cpu = any_online_cpu(mask);
4436
4437         /* On any allowed CPU? */
4438         if (dest_cpu == NR_CPUS)
4439                 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4440
4441         /* No more Mr. Nice Guy. */
4442         if (dest_cpu == NR_CPUS) {
4443                 cpus_setall(tsk->cpus_allowed);
4444                 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4445
4446                 /*
4447                  * Don't tell them about moving exiting tasks or
4448                  * kernel threads (both mm NULL), since they never
4449                  * leave kernel.
4450                  */
4451                 if (tsk->mm && printk_ratelimit())
4452                         printk(KERN_INFO "process %d (%s) no "
4453                                "longer affine to cpu%d\n",
4454                                tsk->pid, tsk->comm, dead_cpu);
4455         }
4456         __migrate_task(tsk, dead_cpu, dest_cpu);
4457 }
4458
4459 /*
4460  * While a dead CPU has no uninterruptible tasks queued at this point,
4461  * it might still have a nonzero ->nr_uninterruptible counter, because
4462  * for performance reasons the counter is not stricly tracking tasks to
4463  * their home CPUs. So we just add the counter to another CPU's counter,
4464  * to keep the global sum constant after CPU-down:
4465  */
4466 static void migrate_nr_uninterruptible(runqueue_t *rq_src)
4467 {
4468         runqueue_t *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
4469         unsigned long flags;
4470
4471         local_irq_save(flags);
4472         double_rq_lock(rq_src, rq_dest);
4473         rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
4474         rq_src->nr_uninterruptible = 0;
4475         double_rq_unlock(rq_src, rq_dest);
4476         local_irq_restore(flags);
4477 }
4478
4479 /* Run through task list and migrate tasks from the dead cpu. */
4480 static void migrate_live_tasks(int src_cpu)
4481 {
4482         struct task_struct *tsk, *t;
4483
4484         write_lock_irq(&tasklist_lock);
4485
4486         do_each_thread(t, tsk) {
4487                 if (tsk == current)
4488                         continue;
4489
4490                 if (task_cpu(tsk) == src_cpu)
4491                         move_task_off_dead_cpu(src_cpu, tsk);
4492         } while_each_thread(t, tsk);
4493
4494         write_unlock_irq(&tasklist_lock);
4495 }
4496
4497 /* Schedules idle task to be the next runnable task on current CPU.
4498  * It does so by boosting its priority to highest possible and adding it to
4499  * the _front_ of runqueue. Used by CPU offline code.
4500  */
4501 void sched_idle_next(void)
4502 {
4503         int cpu = smp_processor_id();
4504         runqueue_t *rq = this_rq();
4505         struct task_struct *p = rq->idle;
4506         unsigned long flags;
4507
4508         /* cpu has to be offline */
4509         BUG_ON(cpu_online(cpu));
4510
4511         /* Strictly not necessary since rest of the CPUs are stopped by now
4512          * and interrupts disabled on current cpu.
4513          */
4514         spin_lock_irqsave(&rq->lock, flags);
4515
4516         __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4517         /* Add idle task to _front_ of it's priority queue */
4518         __activate_idle_task(p, rq);
4519
4520         spin_unlock_irqrestore(&rq->lock, flags);
4521 }
4522
4523 /* Ensures that the idle task is using init_mm right before its cpu goes
4524  * offline.
4525  */
4526 void idle_task_exit(void)
4527 {
4528         struct mm_struct *mm = current->active_mm;
4529
4530         BUG_ON(cpu_online(smp_processor_id()));
4531
4532         if (mm != &init_mm)
4533                 switch_mm(mm, &init_mm, current);
4534         mmdrop(mm);
4535 }
4536
4537 static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
4538 {
4539         struct runqueue *rq = cpu_rq(dead_cpu);
4540
4541         /* Must be exiting, otherwise would be on tasklist. */
4542         BUG_ON(tsk->exit_state != EXIT_ZOMBIE && tsk->exit_state != EXIT_DEAD);
4543
4544         /* Cannot have done final schedule yet: would have vanished. */
4545         BUG_ON(tsk->flags & PF_DEAD);
4546
4547         get_task_struct(tsk);
4548
4549         /*
4550          * Drop lock around migration; if someone else moves it,
4551          * that's OK.  No task can be added to this CPU, so iteration is
4552          * fine.
4553          */
4554         spin_unlock_irq(&rq->lock);
4555         move_task_off_dead_cpu(dead_cpu, tsk);
4556         spin_lock_irq(&rq->lock);
4557
4558         put_task_struct(tsk);
4559 }
4560
4561 /* release_task() removes task from tasklist, so we won't find dead tasks. */
4562 static void migrate_dead_tasks(unsigned int dead_cpu)
4563 {
4564         unsigned arr, i;
4565         struct runqueue *rq = cpu_rq(dead_cpu);
4566
4567         for (arr = 0; arr < 2; arr++) {
4568                 for (i = 0; i < MAX_PRIO; i++) {
4569                         struct list_head *list = &rq->arrays[arr].queue[i];
4570                         while (!list_empty(list))
4571                                 migrate_dead(dead_cpu,
4572                                              list_entry(list->next, task_t,
4573                                                         run_list));
4574                 }
4575         }
4576 }
4577 #endif /* CONFIG_HOTPLUG_CPU */
4578
4579 /*
4580  * migration_call - callback that gets triggered when a CPU is added.
4581  * Here we can start up the necessary migration thread for the new CPU.
4582  */
4583 static int migration_call(struct notifier_block *nfb, unsigned long action,
4584                           void *hcpu)
4585 {
4586         int cpu = (long)hcpu;
4587         struct task_struct *p;
4588         struct runqueue *rq;
4589         unsigned long flags;
4590
4591         switch (action) {
4592         case CPU_UP_PREPARE:
4593                 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4594                 if (IS_ERR(p))
4595                         return NOTIFY_BAD;
4596                 p->flags |= PF_NOFREEZE;
4597                 kthread_bind(p, cpu);
4598                 /* Must be high prio: stop_machine expects to yield to it. */
4599                 rq = task_rq_lock(p, &flags);
4600                 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4601                 task_rq_unlock(rq, &flags);
4602                 cpu_rq(cpu)->migration_thread = p;
4603                 break;
4604         case CPU_ONLINE:
4605                 /* Strictly unneccessary, as first user will wake it. */
4606                 wake_up_process(cpu_rq(cpu)->migration_thread);
4607                 break;
4608 #ifdef CONFIG_HOTPLUG_CPU
4609         case CPU_UP_CANCELED:
4610                 /* Unbind it from offline cpu so it can run.  Fall thru. */
4611                 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
4612                 kthread_stop(cpu_rq(cpu)->migration_thread);
4613                 cpu_rq(cpu)->migration_thread = NULL;
4614                 break;
4615         case CPU_DEAD:
4616                 migrate_live_tasks(cpu);
4617                 rq = cpu_rq(cpu);
4618                 kthread_stop(rq->migration_thread);
4619                 rq->migration_thread = NULL;
4620                 /* Idle task back to normal (off runqueue, low prio) */
4621                 rq = task_rq_lock(rq->idle, &flags);
4622                 deactivate_task(rq->idle, rq);
4623                 rq->idle->static_prio = MAX_PRIO;
4624                 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4625                 migrate_dead_tasks(cpu);
4626                 task_rq_unlock(rq, &flags);
4627                 migrate_nr_uninterruptible(rq);
4628                 BUG_ON(rq->nr_running != 0);
4629
4630                 /* No need to migrate the tasks: it was best-effort if
4631                  * they didn't do lock_cpu_hotplug().  Just wake up
4632                  * the requestors. */
4633                 spin_lock_irq(&rq->lock);
4634                 while (!list_empty(&rq->migration_queue)) {
4635                         migration_req_t *req;
4636                         req = list_entry(rq->migration_queue.next,
4637                                          migration_req_t, list);
4638                         BUG_ON(req->type != REQ_MOVE_TASK);
4639                         list_del_init(&req->list);
4640                         complete(&req->done);
4641                 }
4642                 spin_unlock_irq(&rq->lock);
4643                 break;
4644 #endif
4645         }
4646         return NOTIFY_OK;
4647 }
4648
4649 /* Register at highest priority so that task migration (migrate_all_tasks)
4650  * happens before everything else.
4651  */
4652 static struct notifier_block __devinitdata migration_notifier = {
4653         .notifier_call = migration_call,
4654         .priority = 10
4655 };
4656
4657 int __init migration_init(void)
4658 {
4659         void *cpu = (void *)(long)smp_processor_id();
4660         /* Start one for boot CPU. */
4661         migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4662         migration_call(&migration_notifier, CPU_ONLINE, cpu);
4663         register_cpu_notifier(&migration_notifier);
4664         return 0;
4665 }
4666 #endif
4667
4668 #ifdef CONFIG_SMP
4669 #define SCHED_DOMAIN_DEBUG
4670 #ifdef SCHED_DOMAIN_DEBUG
4671 static void sched_domain_debug(struct sched_domain *sd, int cpu)
4672 {
4673         int level = 0;
4674
4675         printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
4676
4677         do {
4678                 int i;
4679                 char str[NR_CPUS];
4680                 struct sched_group *group = sd->groups;
4681                 cpumask_t groupmask;
4682
4683                 cpumask_scnprintf(str, NR_CPUS, sd->span);
4684                 cpus_clear(groupmask);
4685
4686                 printk(KERN_DEBUG);
4687                 for (i = 0; i < level + 1; i++)
4688                         printk(" ");
4689                 printk("domain %d: ", level);
4690
4691                 if (!(sd->flags & SD_LOAD_BALANCE)) {
4692                         printk("does not load-balance\n");
4693                         if (sd->parent)
4694                                 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
4695                         break;
4696                 }
4697
4698                 printk("span %s\n", str);
4699
4700                 if (!cpu_isset(cpu, sd->span))
4701                         printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
4702                 if (!cpu_isset(cpu, group->cpumask))
4703                         printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
4704
4705                 printk(KERN_DEBUG);
4706                 for (i = 0; i < level + 2; i++)
4707                         printk(" ");
4708                 printk("groups:");
4709                 do {
4710                         if (!group) {
4711                                 printk("\n");
4712                                 printk(KERN_ERR "ERROR: group is NULL\n");
4713                                 break;
4714                         }
4715
4716                         if (!group->cpu_power) {
4717                                 printk("\n");
4718                                 printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
4719                         }
4720
4721                         if (!cpus_weight(group->cpumask)) {
4722                                 printk("\n");
4723                                 printk(KERN_ERR "ERROR: empty group\n");
4724                         }
4725
4726                         if (cpus_intersects(groupmask, group->cpumask)) {
4727                                 printk("\n");
4728                                 printk(KERN_ERR "ERROR: repeated CPUs\n");
4729                         }
4730
4731                         cpus_or(groupmask, groupmask, group->cpumask);
4732
4733                         cpumask_scnprintf(str, NR_CPUS, group->cpumask);
4734                         printk(" %s", str);
4735
4736                         group = group->next;
4737                 } while (group != sd->groups);
4738                 printk("\n");
4739
4740                 if (!cpus_equal(sd->span, groupmask))
4741                         printk(KERN_ERR "ERROR: groups don't span domain->span\n");
4742
4743                 level++;
4744                 sd = sd->parent;
4745
4746                 if (sd) {
4747                         if (!cpus_subset(groupmask, sd->span))
4748                                 printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
4749                 }
4750
4751         } while (sd);
4752 }
4753 #else
4754 #define sched_domain_debug(sd, cpu) {}
4755 #endif
4756
4757 /*
4758  * Attach the domain 'sd' to 'cpu' as its base domain.  Callers must
4759  * hold the hotplug lock.
4760  */
4761 void __devinit cpu_attach_domain(struct sched_domain *sd, int cpu)
4762 {
4763         migration_req_t req;
4764         unsigned long flags;
4765         runqueue_t *rq = cpu_rq(cpu);
4766         int local = 1;
4767
4768         sched_domain_debug(sd, cpu);
4769
4770         spin_lock_irqsave(&rq->lock, flags);
4771
4772         if (cpu == smp_processor_id() || !cpu_online(cpu)) {
4773                 rq->sd = sd;
4774         } else {
4775                 init_completion(&req.done);
4776                 req.type = REQ_SET_DOMAIN;
4777                 req.sd = sd;
4778                 list_add(&req.list, &rq->migration_queue);
4779                 local = 0;
4780         }
4781
4782         spin_unlock_irqrestore(&rq->lock, flags);
4783
4784         if (!local) {
4785                 wake_up_process(rq->migration_thread);
4786                 wait_for_completion(&req.done);
4787         }
4788 }
4789
4790 /* cpus with isolated domains */
4791 cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
4792
4793 /* Setup the mask of cpus configured for isolated domains */
4794 static int __init isolated_cpu_setup(char *str)
4795 {
4796         int ints[NR_CPUS], i;
4797
4798         str = get_options(str, ARRAY_SIZE(ints), ints);
4799         cpus_clear(cpu_isolated_map);
4800         for (i = 1; i <= ints[0]; i++)
4801                 if (ints[i] < NR_CPUS)
4802                         cpu_set(ints[i], cpu_isolated_map);
4803         return 1;
4804 }
4805
4806 __setup ("isolcpus=", isolated_cpu_setup);
4807
4808 /*
4809  * init_sched_build_groups takes an array of groups, the cpumask we wish
4810  * to span, and a pointer to a function which identifies what group a CPU
4811  * belongs to. The return value of group_fn must be a valid index into the
4812  * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
4813  * keep track of groups covered with a cpumask_t).
4814  *
4815  * init_sched_build_groups will build a circular linked list of the groups
4816  * covered by the given span, and will set each group's ->cpumask correctly,
4817  * and ->cpu_power to 0.
4818  */
4819 void __devinit init_sched_build_groups(struct sched_group groups[],
4820                         cpumask_t span, int (*group_fn)(int cpu))
4821 {
4822         struct sched_group *first = NULL, *last = NULL;
4823         cpumask_t covered = CPU_MASK_NONE;
4824         int i;
4825
4826         for_each_cpu_mask(i, span) {
4827                 int group = group_fn(i);
4828                 struct sched_group *sg = &groups[group];
4829                 int j;
4830
4831                 if (cpu_isset(i, covered))
4832                         continue;
4833
4834                 sg->cpumask = CPU_MASK_NONE;
4835                 sg->cpu_power = 0;
4836
4837                 for_each_cpu_mask(j, span) {
4838                         if (group_fn(j) != group)
4839                                 continue;
4840
4841                         cpu_set(j, covered);
4842                         cpu_set(j, sg->cpumask);
4843                 }
4844                 if (!first)
4845                         first = sg;
4846                 if (last)
4847                         last->next = sg;
4848                 last = sg;
4849         }
4850         last->next = first;
4851 }
4852
4853
4854 #ifdef ARCH_HAS_SCHED_DOMAIN
4855 extern void __devinit arch_init_sched_domains(void);
4856 extern void __devinit arch_destroy_sched_domains(void);
4857 #else
4858 #ifdef CONFIG_SCHED_SMT
4859 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
4860 static struct sched_group sched_group_cpus[NR_CPUS];
4861 static int __devinit cpu_to_cpu_group(int cpu)
4862 {
4863         return cpu;
4864 }
4865 #endif
4866
4867 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
4868 static struct sched_group sched_group_phys[NR_CPUS];
4869 static int __devinit cpu_to_phys_group(int cpu)
4870 {
4871 #ifdef CONFIG_SCHED_SMT
4872         return first_cpu(cpu_sibling_map[cpu]);
4873 #else
4874         return cpu;
4875 #endif
4876 }
4877
4878 #ifdef CONFIG_NUMA
4879
4880 static DEFINE_PER_CPU(struct sched_domain, node_domains);
4881 static struct sched_group sched_group_nodes[MAX_NUMNODES];
4882 static int __devinit cpu_to_node_group(int cpu)
4883 {
4884         return cpu_to_node(cpu);
4885 }
4886 #endif
4887
4888 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
4889 /*
4890  * The domains setup code relies on siblings not spanning
4891  * multiple nodes. Make sure the architecture has a proper
4892  * siblings map:
4893  */
4894 static void check_sibling_maps(void)
4895 {
4896         int i, j;
4897
4898         for_each_online_cpu(i) {
4899                 for_each_cpu_mask(j, cpu_sibling_map[i]) {
4900                         if (cpu_to_node(i) != cpu_to_node(j)) {
4901                                 printk(KERN_INFO "warning: CPU %d siblings map "
4902                                         "to different node - isolating "
4903                                         "them.\n", i);
4904                                 cpu_sibling_map[i] = cpumask_of_cpu(i);
4905                                 break;
4906                         }
4907                 }
4908         }
4909 }
4910 #endif
4911
4912 /*
4913  * Set up scheduler domains and groups.  Callers must hold the hotplug lock.
4914  */
4915 static void __devinit arch_init_sched_domains(void)
4916 {
4917         int i;
4918         cpumask_t cpu_default_map;
4919
4920 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
4921         check_sibling_maps();
4922 #endif
4923         /*
4924          * Setup mask for cpus without special case scheduling requirements.
4925          * For now this just excludes isolated cpus, but could be used to
4926          * exclude other special cases in the future.
4927          */
4928         cpus_complement(cpu_default_map, cpu_isolated_map);
4929         cpus_and(cpu_default_map, cpu_default_map, cpu_online_map);
4930
4931         /*
4932          * Set up domains. Isolated domains just stay on the dummy domain.
4933          */
4934         for_each_cpu_mask(i, cpu_default_map) {
4935                 int group;
4936                 struct sched_domain *sd = NULL, *p;
4937                 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
4938
4939                 cpus_and(nodemask, nodemask, cpu_default_map);
4940
4941 #ifdef CONFIG_NUMA
4942                 sd = &per_cpu(node_domains, i);
4943                 group = cpu_to_node_group(i);
4944                 *sd = SD_NODE_INIT;
4945                 sd->span = cpu_default_map;
4946                 sd->groups = &sched_group_nodes[group];
4947 #endif
4948
4949                 p = sd;
4950                 sd = &per_cpu(phys_domains, i);
4951                 group = cpu_to_phys_group(i);
4952                 *sd = SD_CPU_INIT;
4953                 sd->span = nodemask;
4954                 sd->parent = p;
4955                 sd->groups = &sched_group_phys[group];
4956
4957 #ifdef CONFIG_SCHED_SMT
4958                 p = sd;
4959                 sd = &per_cpu(cpu_domains, i);
4960                 group = cpu_to_cpu_group(i);
4961                 *sd = SD_SIBLING_INIT;
4962                 sd->span = cpu_sibling_map[i];
4963                 cpus_and(sd->span, sd->span, cpu_default_map);
4964                 sd->parent = p;
4965                 sd->groups = &sched_group_cpus[group];
4966 #endif
4967         }
4968
4969 #ifdef CONFIG_SCHED_SMT
4970         /* Set up CPU (sibling) groups */
4971         for_each_online_cpu(i) {
4972                 cpumask_t this_sibling_map = cpu_sibling_map[i];
4973                 cpus_and(this_sibling_map, this_sibling_map, cpu_default_map);
4974                 if (i != first_cpu(this_sibling_map))
4975                         continue;
4976
4977                 init_sched_build_groups(sched_group_cpus, this_sibling_map,
4978                                                 &cpu_to_cpu_group);
4979         }
4980 #endif
4981
4982         /* Set up physical groups */
4983         for (i = 0; i < MAX_NUMNODES; i++) {
4984                 cpumask_t nodemask = node_to_cpumask(i);
4985
4986                 cpus_and(nodemask, nodemask, cpu_default_map);
4987                 if (cpus_empty(nodemask))
4988                         continue;
4989
4990                 init_sched_build_groups(sched_group_phys, nodemask,
4991                                                 &cpu_to_phys_group);
4992         }
4993
4994 #ifdef CONFIG_NUMA
4995         /* Set up node groups */
4996         init_sched_build_groups(sched_group_nodes, cpu_default_map,
4997                                         &cpu_to_node_group);
4998 #endif
4999
5000         /* Calculate CPU power for physical packages and nodes */
5001         for_each_cpu_mask(i, cpu_default_map) {
5002                 int power;
5003                 struct sched_domain *sd;
5004 #ifdef CONFIG_SCHED_SMT
5005                 sd = &per_cpu(cpu_domains, i);
5006                 power = SCHED_LOAD_SCALE;
5007                 sd->groups->cpu_power = power;
5008 #endif
5009
5010                 sd = &per_cpu(phys_domains, i);
5011                 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
5012                                 (cpus_weight(sd->groups->cpumask)-1) / 10;
5013                 sd->groups->cpu_power = power;
5014
5015 #ifdef CONFIG_NUMA
5016                 if (i == first_cpu(sd->groups->cpumask)) {
5017                         /* Only add "power" once for each physical package. */
5018                         sd = &per_cpu(node_domains, i);
5019                         sd->groups->cpu_power += power;
5020                 }
5021 #endif
5022         }
5023
5024         /* Attach the domains */
5025         for_each_online_cpu(i) {
5026                 struct sched_domain *sd;
5027 #ifdef CONFIG_SCHED_SMT
5028                 sd = &per_cpu(cpu_domains, i);
5029 #else
5030                 sd = &per_cpu(phys_domains, i);
5031 #endif
5032                 cpu_attach_domain(sd, i);
5033         }
5034 }
5035
5036 #ifdef CONFIG_HOTPLUG_CPU
5037 static void __devinit arch_destroy_sched_domains(void)
5038 {
5039         /* Do nothing: everything is statically allocated. */
5040 }
5041 #endif
5042
5043 #endif /* ARCH_HAS_SCHED_DOMAIN */
5044
5045 /*
5046  * Initial dummy domain for early boot and for hotplug cpu. Being static,
5047  * it is initialized to zero, so all balancing flags are cleared which is
5048  * what we want.
5049  */
5050 static struct sched_domain sched_domain_dummy;
5051
5052 #ifdef CONFIG_HOTPLUG_CPU
5053 /*
5054  * Force a reinitialization of the sched domains hierarchy.  The domains
5055  * and groups cannot be updated in place without racing with the balancing
5056  * code, so we temporarily attach all running cpus to a "dummy" domain
5057  * which will prevent rebalancing while the sched domains are recalculated.
5058  */
5059 static int update_sched_domains(struct notifier_block *nfb,
5060                                 unsigned long action, void *hcpu)
5061 {
5062         int i;
5063
5064         switch (action) {
5065         case CPU_UP_PREPARE:
5066         case CPU_DOWN_PREPARE:
5067                 for_each_online_cpu(i)
5068                         cpu_attach_domain(&sched_domain_dummy, i);
5069                 arch_destroy_sched_domains();
5070                 return NOTIFY_OK;
5071
5072         case CPU_UP_CANCELED:
5073         case CPU_DOWN_FAILED:
5074         case CPU_ONLINE:
5075         case CPU_DEAD:
5076                 /*
5077                  * Fall through and re-initialise the domains.
5078                  */
5079                 break;
5080         default:
5081                 return NOTIFY_DONE;
5082         }
5083
5084         /* The hotplug lock is already held by cpu_up/cpu_down */
5085         arch_init_sched_domains();
5086
5087         return NOTIFY_OK;
5088 }
5089 #endif
5090
5091 void __init sched_init_smp(void)
5092 {
5093         lock_cpu_hotplug();
5094         arch_init_sched_domains();
5095         unlock_cpu_hotplug();
5096         /* XXX: Theoretical race here - CPU may be hotplugged now */
5097         hotcpu_notifier(update_sched_domains, 0);
5098 }
5099 #else
5100 void __init sched_init_smp(void)
5101 {
5102 }
5103 #endif /* CONFIG_SMP */
5104
5105 int in_sched_functions(unsigned long addr)
5106 {
5107         /* Linker adds these: start and end of __sched functions */
5108         extern char __sched_text_start[], __sched_text_end[];
5109         return in_lock_functions(addr) ||
5110                 (addr >= (unsigned long)__sched_text_start
5111                 && addr < (unsigned long)__sched_text_end);
5112 }
5113
5114 void __init sched_init(void)
5115 {
5116         runqueue_t *rq;
5117         int i, j, k;
5118
5119         for (i = 0; i < NR_CPUS; i++) {
5120                 prio_array_t *array;
5121
5122                 rq = cpu_rq(i);
5123                 spin_lock_init(&rq->lock);
5124                 rq->active = rq->arrays;
5125                 rq->expired = rq->arrays + 1;
5126                 rq->best_expired_prio = MAX_PRIO;
5127
5128 #ifdef CONFIG_SMP
5129                 rq->sd = &sched_domain_dummy;
5130                 rq->cpu_load = 0;
5131                 rq->active_balance = 0;
5132                 rq->push_cpu = 0;
5133                 rq->migration_thread = NULL;
5134                 INIT_LIST_HEAD(&rq->migration_queue);
5135 #endif
5136 #ifdef CONFIG_VSERVER_HARDCPU
5137                 INIT_LIST_HEAD(&rq->hold_queue);
5138 #endif
5139                 atomic_set(&rq->nr_iowait, 0);
5140 #ifdef CONFIG_VSERVER_HARDCPU
5141                 INIT_LIST_HEAD(&rq->hold_queue);
5142 #endif
5143
5144                 for (j = 0; j < 2; j++) {
5145                         array = rq->arrays + j;
5146                         for (k = 0; k < MAX_PRIO; k++) {
5147                                 INIT_LIST_HEAD(array->queue + k);
5148                                 __clear_bit(k, array->bitmap);
5149                         }
5150                         // delimiter for bitsearch
5151                         __set_bit(MAX_PRIO, array->bitmap);
5152                 }
5153         }
5154
5155         /*
5156          * The boot idle thread does lazy MMU switching as well:
5157          */
5158         atomic_inc(&init_mm.mm_count);
5159         enter_lazy_tlb(&init_mm, current);
5160
5161         /*
5162          * Make us the idle thread. Technically, schedule() should not be
5163          * called from this thread, however somewhere below it might be,
5164          * but because we are the idle thread, we just pick up running again
5165          * when this runqueue becomes "idle".
5166          */
5167         init_idle(current, smp_processor_id());
5168 }
5169
5170 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5171 void __might_sleep(char *file, int line)
5172 {
5173 #if defined(in_atomic)
5174         static unsigned long prev_jiffy;        /* ratelimiting */
5175
5176         if ((in_atomic() || irqs_disabled()) &&
5177             system_state == SYSTEM_RUNNING && !oops_in_progress) {
5178                 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
5179                         return;
5180                 prev_jiffy = jiffies;
5181                 printk(KERN_ERR "Debug: sleeping function called from invalid"
5182                                 " context at %s:%d\n", file, line);
5183                 printk("in_atomic():%d, irqs_disabled():%d\n",
5184                         in_atomic(), irqs_disabled());
5185                 dump_stack();
5186         }
5187 #endif
5188 }
5189 EXPORT_SYMBOL(__might_sleep);
5190 #endif
5191
5192 #ifdef CONFIG_MAGIC_SYSRQ
5193 void normalize_rt_tasks(void)
5194 {
5195         struct task_struct *p;
5196         prio_array_t *array;
5197         unsigned long flags;
5198         runqueue_t *rq;
5199
5200         read_lock_irq(&tasklist_lock);
5201         for_each_process (p) {
5202                 if (!rt_task(p))
5203                         continue;
5204
5205                 rq = task_rq_lock(p, &flags);
5206
5207                 array = p->array;
5208                 if (array)
5209                         deactivate_task(p, task_rq(p));
5210                 __setscheduler(p, SCHED_NORMAL, 0);
5211                 if (array) {
5212                         vx_activate_task(p);
5213                         __activate_task(p, task_rq(p));
5214                         resched_task(rq->curr);
5215                 }
5216
5217                 task_rq_unlock(rq, &flags);
5218         }
5219         read_unlock_irq(&tasklist_lock);
5220 }
5221
5222 #endif /* CONFIG_MAGIC_SYSRQ */