vserver 2.0 rc7
[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 (p == rq->idle) {
2457                 if (wake_priority_sleeper(rq))
2458                         goto out;
2459 #ifdef CONFIG_VSERVER_HARDCPU_IDLE
2460                 if (!--rq->idle_tokens && !list_empty(&rq->hold_queue))
2461                         set_need_resched();
2462 #endif
2463                 rebalance_tick(cpu, rq, SCHED_IDLE);
2464                 return;
2465         }
2466
2467         /* Task might have expired already, but not scheduled off yet */
2468         if (p->array != rq->active) {
2469                 set_tsk_need_resched(p);
2470                 goto out;
2471         }
2472         spin_lock(&rq->lock);
2473         /*
2474          * The task was running during this tick - update the
2475          * time slice counter. Note: we do not update a thread's
2476          * priority until it either goes to sleep or uses up its
2477          * timeslice. This makes it possible for interactive tasks
2478          * to use up their timeslices at their highest priority levels.
2479          */
2480         if (rt_task(p)) {
2481                 /*
2482                  * RR tasks need a special form of timeslice management.
2483                  * FIFO tasks have no timeslices.
2484                  */
2485                 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2486                         p->time_slice = task_timeslice(p);
2487                         p->first_time_slice = 0;
2488                         set_tsk_need_resched(p);
2489
2490                         /* put it at the end of the queue: */
2491                         requeue_task(p, rq->active);
2492                 }
2493                 goto out_unlock;
2494         }
2495         if (vx_need_resched(p)) {
2496                 dequeue_task(p, rq->active);
2497                 set_tsk_need_resched(p);
2498                 p->prio = effective_prio(p);
2499                 p->time_slice = task_timeslice(p);
2500                 p->first_time_slice = 0;
2501
2502                 if (!rq->expired_timestamp)
2503                         rq->expired_timestamp = jiffies;
2504                 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2505                         enqueue_task(p, rq->expired);
2506                         if (p->static_prio < rq->best_expired_prio)
2507                                 rq->best_expired_prio = p->static_prio;
2508                 } else
2509                         enqueue_task(p, rq->active);
2510         } else {
2511                 /*
2512                  * Prevent a too long timeslice allowing a task to monopolize
2513                  * the CPU. We do this by splitting up the timeslice into
2514                  * smaller pieces.
2515                  *
2516                  * Note: this does not mean the task's timeslices expire or
2517                  * get lost in any way, they just might be preempted by
2518                  * another task of equal priority. (one with higher
2519                  * priority would have preempted this task already.) We
2520                  * requeue this task to the end of the list on this priority
2521                  * level, which is in essence a round-robin of tasks with
2522                  * equal priority.
2523                  *
2524                  * This only applies to tasks in the interactive
2525                  * delta range with at least TIMESLICE_GRANULARITY to requeue.
2526                  */
2527                 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2528                         p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2529                         (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2530                         (p->array == rq->active)) {
2531
2532                         requeue_task(p, rq->active);
2533                         set_tsk_need_resched(p);
2534                 }
2535         }
2536 out_unlock:
2537         spin_unlock(&rq->lock);
2538 out:
2539         rebalance_tick(cpu, rq, NOT_IDLE);
2540 }
2541
2542 #ifdef CONFIG_SCHED_SMT
2543 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2544 {
2545         struct sched_domain *sd = this_rq->sd;
2546         cpumask_t sibling_map;
2547         int i;
2548
2549         if (!(sd->flags & SD_SHARE_CPUPOWER))
2550                 return;
2551
2552         /*
2553          * Unlock the current runqueue because we have to lock in
2554          * CPU order to avoid deadlocks. Caller knows that we might
2555          * unlock. We keep IRQs disabled.
2556          */
2557         spin_unlock(&this_rq->lock);
2558
2559         sibling_map = sd->span;
2560
2561         for_each_cpu_mask(i, sibling_map)
2562                 spin_lock(&cpu_rq(i)->lock);
2563         /*
2564          * We clear this CPU from the mask. This both simplifies the
2565          * inner loop and keps this_rq locked when we exit:
2566          */
2567         cpu_clear(this_cpu, sibling_map);
2568
2569         for_each_cpu_mask(i, sibling_map) {
2570                 runqueue_t *smt_rq = cpu_rq(i);
2571
2572                 /*
2573                  * If an SMT sibling task is sleeping due to priority
2574                  * reasons wake it up now.
2575                  */
2576                 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
2577                         resched_task(smt_rq->idle);
2578         }
2579
2580         for_each_cpu_mask(i, sibling_map)
2581                 spin_unlock(&cpu_rq(i)->lock);
2582         /*
2583          * We exit with this_cpu's rq still held and IRQs
2584          * still disabled:
2585          */
2586 }
2587
2588 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2589 {
2590         struct sched_domain *sd = this_rq->sd;
2591         cpumask_t sibling_map;
2592         prio_array_t *array;
2593         int ret = 0, i;
2594         task_t *p;
2595
2596         if (!(sd->flags & SD_SHARE_CPUPOWER))
2597                 return 0;
2598
2599         /*
2600          * The same locking rules and details apply as for
2601          * wake_sleeping_dependent():
2602          */
2603         spin_unlock(&this_rq->lock);
2604         sibling_map = sd->span;
2605         for_each_cpu_mask(i, sibling_map)
2606                 spin_lock(&cpu_rq(i)->lock);
2607         cpu_clear(this_cpu, sibling_map);
2608
2609         /*
2610          * Establish next task to be run - it might have gone away because
2611          * we released the runqueue lock above:
2612          */
2613         if (!this_rq->nr_running)
2614                 goto out_unlock;
2615         array = this_rq->active;
2616         if (!array->nr_active)
2617                 array = this_rq->expired;
2618         BUG_ON(!array->nr_active);
2619
2620         p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
2621                 task_t, run_list);
2622
2623         for_each_cpu_mask(i, sibling_map) {
2624                 runqueue_t *smt_rq = cpu_rq(i);
2625                 task_t *smt_curr = smt_rq->curr;
2626
2627                 /*
2628                  * If a user task with lower static priority than the
2629                  * running task on the SMT sibling is trying to schedule,
2630                  * delay it till there is proportionately less timeslice
2631                  * left of the sibling task to prevent a lower priority
2632                  * task from using an unfair proportion of the
2633                  * physical cpu's resources. -ck
2634                  */
2635                 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
2636                         task_timeslice(p) || rt_task(smt_curr)) &&
2637                         p->mm && smt_curr->mm && !rt_task(p))
2638                                 ret = 1;
2639
2640                 /*
2641                  * Reschedule a lower priority task on the SMT sibling,
2642                  * or wake it up if it has been put to sleep for priority
2643                  * reasons.
2644                  */
2645                 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
2646                         task_timeslice(smt_curr) || rt_task(p)) &&
2647                         smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
2648                         (smt_curr == smt_rq->idle && smt_rq->nr_running))
2649                                 resched_task(smt_curr);
2650         }
2651 out_unlock:
2652         for_each_cpu_mask(i, sibling_map)
2653                 spin_unlock(&cpu_rq(i)->lock);
2654         return ret;
2655 }
2656 #else
2657 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2658 {
2659 }
2660
2661 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2662 {
2663         return 0;
2664 }
2665 #endif
2666
2667 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
2668
2669 void fastcall add_preempt_count(int val)
2670 {
2671         /*
2672          * Underflow?
2673          */
2674         BUG_ON(((int)preempt_count() < 0));
2675         preempt_count() += val;
2676         /*
2677          * Spinlock count overflowing soon?
2678          */
2679         BUG_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
2680 }
2681 EXPORT_SYMBOL(add_preempt_count);
2682
2683 void fastcall sub_preempt_count(int val)
2684 {
2685         /*
2686          * Underflow?
2687          */
2688         BUG_ON(val > preempt_count());
2689         /*
2690          * Is the spinlock portion underflowing?
2691          */
2692         BUG_ON((val < PREEMPT_MASK) && !(preempt_count() & PREEMPT_MASK));
2693         preempt_count() -= val;
2694 }
2695 EXPORT_SYMBOL(sub_preempt_count);
2696
2697 #endif
2698
2699 /*
2700  * schedule() is the main scheduler function.
2701  */
2702 asmlinkage void __sched schedule(void)
2703 {
2704         long *switch_count;
2705         task_t *prev, *next;
2706         runqueue_t *rq;
2707         prio_array_t *array;
2708         struct list_head *queue;
2709         unsigned long long now;
2710         unsigned long run_time;
2711         struct vx_info *vxi;
2712 #ifdef  CONFIG_VSERVER_HARDCPU
2713         int maxidle = -HZ;
2714 #endif
2715         int cpu, idx;
2716
2717         /*
2718          * Test if we are atomic.  Since do_exit() needs to call into
2719          * schedule() atomically, we ignore that path for now.
2720          * Otherwise, whine if we are scheduling when we should not be.
2721          */
2722         if (likely(!current->exit_state)) {
2723                 if (unlikely(in_atomic())) {
2724                         printk(KERN_ERR "scheduling while atomic: "
2725                                 "%s/0x%08x/%d\n",
2726                                 current->comm, preempt_count(), current->pid);
2727                         dump_stack();
2728                 }
2729         }
2730         profile_hit(SCHED_PROFILING, __builtin_return_address(0));
2731
2732 need_resched:
2733         preempt_disable();
2734         prev = current;
2735         release_kernel_lock(prev);
2736 need_resched_nonpreemptible:
2737         rq = this_rq();
2738
2739         /*
2740          * The idle thread is not allowed to schedule!
2741          * Remove this check after it has been exercised a bit.
2742          */
2743         if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
2744                 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
2745                 dump_stack();
2746         }
2747
2748         schedstat_inc(rq, sched_cnt);
2749         now = sched_clock();
2750         if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
2751                 run_time = now - prev->timestamp;
2752                 if (unlikely((long long)(now - prev->timestamp) < 0))
2753                         run_time = 0;
2754         } else
2755                 run_time = NS_MAX_SLEEP_AVG;
2756
2757         /*
2758          * Tasks charged proportionately less run_time at high sleep_avg to
2759          * delay them losing their interactive status
2760          */
2761         run_time /= (CURRENT_BONUS(prev) ? : 1);
2762
2763         spin_lock_irq(&rq->lock);
2764
2765         if (unlikely(prev->flags & PF_DEAD))
2766                 prev->state = EXIT_DEAD;
2767
2768         switch_count = &prev->nivcsw;
2769         if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2770                 switch_count = &prev->nvcsw;
2771                 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2772                                 unlikely(signal_pending(prev))))
2773                         prev->state = TASK_RUNNING;
2774                 else {
2775                         if (prev->state == TASK_UNINTERRUPTIBLE) {
2776                                 rq->nr_uninterruptible++;
2777                                 vx_uninterruptible_inc(prev);
2778                         }
2779                         deactivate_task(prev, rq);
2780                 }
2781         }
2782
2783 #ifdef CONFIG_VSERVER_HARDCPU
2784         if (!list_empty(&rq->hold_queue)) {
2785                 struct list_head *l, *n;
2786                 int ret;
2787
2788                 vxi = NULL;
2789                 list_for_each_safe(l, n, &rq->hold_queue) {
2790                         next = list_entry(l, task_t, run_list);
2791                         if (vxi == next->vx_info)
2792                                 continue;
2793
2794                         vxi = next->vx_info;
2795                         ret = vx_tokens_recalc(vxi);
2796
2797                         if (ret > 0) {
2798                                 vx_unhold_task(vxi, next, rq);
2799                                 break;
2800                         }
2801                         if ((ret < 0) && (maxidle < ret))
2802                                 maxidle = ret;
2803                 }
2804         }
2805         rq->idle_tokens = -maxidle;
2806
2807 pick_next:
2808 #endif
2809
2810         cpu = smp_processor_id();
2811         if (unlikely(!rq->nr_running)) {
2812 go_idle:
2813                 idle_balance(cpu, rq);
2814                 if (!rq->nr_running) {
2815                         next = rq->idle;
2816                         rq->expired_timestamp = 0;
2817                         wake_sleeping_dependent(cpu, rq);
2818                         /*
2819                          * wake_sleeping_dependent() might have released
2820                          * the runqueue, so break out if we got new
2821                          * tasks meanwhile:
2822                          */
2823                         if (!rq->nr_running)
2824                                 goto switch_tasks;
2825                 }
2826         } else {
2827                 if (dependent_sleeper(cpu, rq)) {
2828                         next = rq->idle;
2829                         goto switch_tasks;
2830                 }
2831                 /*
2832                  * dependent_sleeper() releases and reacquires the runqueue
2833                  * lock, hence go into the idle loop if the rq went
2834                  * empty meanwhile:
2835                  */
2836                 if (unlikely(!rq->nr_running))
2837                         goto go_idle;
2838         }
2839
2840         array = rq->active;
2841         if (unlikely(!array->nr_active)) {
2842                 /*
2843                  * Switch the active and expired arrays.
2844                  */
2845                 schedstat_inc(rq, sched_switch);
2846                 rq->active = rq->expired;
2847                 rq->expired = array;
2848                 array = rq->active;
2849                 rq->expired_timestamp = 0;
2850                 rq->best_expired_prio = MAX_PRIO;
2851         }
2852
2853         idx = sched_find_first_bit(array->bitmap);
2854         queue = array->queue + idx;
2855         next = list_entry(queue->next, task_t, run_list);
2856
2857         vxi = next->vx_info;
2858 #ifdef  CONFIG_VSERVER_HARDCPU
2859         if (vx_info_flags(vxi, VXF_SCHED_PAUSE|VXF_SCHED_HARD, 0)) {
2860                 int ret = vx_tokens_recalc(vxi);
2861
2862                 if (unlikely(ret <= 0)) {
2863                         if (ret && (rq->idle_tokens > -ret))
2864                                 rq->idle_tokens = -ret;
2865                         vx_hold_task(vxi, next, rq);
2866                         goto pick_next;
2867                 }
2868         } else  /* well, looks ugly but not as ugly as the ifdef-ed version */
2869 #endif
2870         if (vx_info_flags(vxi, VXF_SCHED_PRIO, 0))
2871                 vx_tokens_recalc(vxi);
2872
2873         if (!rt_task(next) && next->activated > 0) {
2874                 unsigned long long delta = now - next->timestamp;
2875                 if (unlikely((long long)(now - next->timestamp) < 0))
2876                         delta = 0;
2877
2878                 if (next->activated == 1)
2879                         delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
2880
2881                 array = next->array;
2882                 dequeue_task(next, array);
2883                 recalc_task_prio(next, next->timestamp + delta);
2884                 enqueue_task(next, array);
2885         }
2886         next->activated = 0;
2887 switch_tasks:
2888         if (next == rq->idle)
2889                 schedstat_inc(rq, sched_goidle);
2890         prefetch(next);
2891         clear_tsk_need_resched(prev);
2892         rcu_qsctr_inc(task_cpu(prev));
2893
2894         update_cpu_clock(prev, rq, now);
2895
2896         prev->sleep_avg -= run_time;
2897         if ((long)prev->sleep_avg <= 0)
2898                 prev->sleep_avg = 0;
2899         prev->timestamp = prev->last_ran = now;
2900
2901         sched_info_switch(prev, next);
2902         if (likely(prev != next)) {
2903                 next->timestamp = now;
2904                 rq->nr_switches++;
2905                 rq->curr = next;
2906                 ++*switch_count;
2907
2908                 prepare_arch_switch(rq, next);
2909                 prev = context_switch(rq, prev, next);
2910                 barrier();
2911
2912                 finish_task_switch(prev);
2913         } else
2914                 spin_unlock_irq(&rq->lock);
2915
2916         prev = current;
2917         if (unlikely(reacquire_kernel_lock(prev) < 0))
2918                 goto need_resched_nonpreemptible;
2919         preempt_enable_no_resched();
2920         if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2921                 goto need_resched;
2922 }
2923
2924 EXPORT_SYMBOL(schedule);
2925
2926 #ifdef CONFIG_PREEMPT
2927 /*
2928  * this is is the entry point to schedule() from in-kernel preemption
2929  * off of preempt_enable.  Kernel preemptions off return from interrupt
2930  * occur there and call schedule directly.
2931  */
2932 asmlinkage void __sched preempt_schedule(void)
2933 {
2934         struct thread_info *ti = current_thread_info();
2935 #ifdef CONFIG_PREEMPT_BKL
2936         struct task_struct *task = current;
2937         int saved_lock_depth;
2938 #endif
2939         /*
2940          * If there is a non-zero preempt_count or interrupts are disabled,
2941          * we do not want to preempt the current task.  Just return..
2942          */
2943         if (unlikely(ti->preempt_count || irqs_disabled()))
2944                 return;
2945
2946 need_resched:
2947         add_preempt_count(PREEMPT_ACTIVE);
2948         /*
2949          * We keep the big kernel semaphore locked, but we
2950          * clear ->lock_depth so that schedule() doesnt
2951          * auto-release the semaphore:
2952          */
2953 #ifdef CONFIG_PREEMPT_BKL
2954         saved_lock_depth = task->lock_depth;
2955         task->lock_depth = -1;
2956 #endif
2957         schedule();
2958 #ifdef CONFIG_PREEMPT_BKL
2959         task->lock_depth = saved_lock_depth;
2960 #endif
2961         sub_preempt_count(PREEMPT_ACTIVE);
2962
2963         /* we could miss a preemption opportunity between schedule and now */
2964         barrier();
2965         if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2966                 goto need_resched;
2967 }
2968
2969 EXPORT_SYMBOL(preempt_schedule);
2970
2971 /*
2972  * this is is the entry point to schedule() from kernel preemption
2973  * off of irq context.
2974  * Note, that this is called and return with irqs disabled. This will
2975  * protect us against recursive calling from irq.
2976  */
2977 asmlinkage void __sched preempt_schedule_irq(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         /* Catch callers which need to be fixed*/
2985         BUG_ON(ti->preempt_count || !irqs_disabled());
2986
2987 need_resched:
2988         add_preempt_count(PREEMPT_ACTIVE);
2989         /*
2990          * We keep the big kernel semaphore locked, but we
2991          * clear ->lock_depth so that schedule() doesnt
2992          * auto-release the semaphore:
2993          */
2994 #ifdef CONFIG_PREEMPT_BKL
2995         saved_lock_depth = task->lock_depth;
2996         task->lock_depth = -1;
2997 #endif
2998         local_irq_enable();
2999         schedule();
3000         local_irq_disable();
3001 #ifdef CONFIG_PREEMPT_BKL
3002         task->lock_depth = saved_lock_depth;
3003 #endif
3004         sub_preempt_count(PREEMPT_ACTIVE);
3005
3006         /* we could miss a preemption opportunity between schedule and now */
3007         barrier();
3008         if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3009                 goto need_resched;
3010 }
3011
3012 #endif /* CONFIG_PREEMPT */
3013
3014 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
3015 {
3016         task_t *p = curr->task;
3017         return try_to_wake_up(p, mode, sync);
3018 }
3019
3020 EXPORT_SYMBOL(default_wake_function);
3021
3022 /*
3023  * The core wakeup function.  Non-exclusive wakeups (nr_exclusive == 0) just
3024  * wake everything up.  If it's an exclusive wakeup (nr_exclusive == small +ve
3025  * number) then we wake all the non-exclusive tasks and one exclusive task.
3026  *
3027  * There are circumstances in which we can try to wake a task which has already
3028  * started to run but is not in state TASK_RUNNING.  try_to_wake_up() returns
3029  * zero in this (rare) case, and we handle it by continuing to scan the queue.
3030  */
3031 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3032                              int nr_exclusive, int sync, void *key)
3033 {
3034         struct list_head *tmp, *next;
3035
3036         list_for_each_safe(tmp, next, &q->task_list) {
3037                 wait_queue_t *curr;
3038                 unsigned flags;
3039                 curr = list_entry(tmp, wait_queue_t, task_list);
3040                 flags = curr->flags;
3041                 if (curr->func(curr, mode, sync, key) &&
3042                     (flags & WQ_FLAG_EXCLUSIVE) &&
3043                     !--nr_exclusive)
3044                         break;
3045         }
3046 }
3047
3048 /**
3049  * __wake_up - wake up threads blocked on a waitqueue.
3050  * @q: the waitqueue
3051  * @mode: which threads
3052  * @nr_exclusive: how many wake-one or wake-many threads to wake up
3053  * @key: is directly passed to the wakeup function
3054  */
3055 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3056                                 int nr_exclusive, void *key)
3057 {
3058         unsigned long flags;
3059
3060         spin_lock_irqsave(&q->lock, flags);
3061         __wake_up_common(q, mode, nr_exclusive, 0, key);
3062         spin_unlock_irqrestore(&q->lock, flags);
3063 }
3064
3065 EXPORT_SYMBOL(__wake_up);
3066
3067 /*
3068  * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3069  */
3070 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3071 {
3072         __wake_up_common(q, mode, 1, 0, NULL);
3073 }
3074
3075 /**
3076  * __wake_up_sync - wake up threads blocked on a waitqueue.
3077  * @q: the waitqueue
3078  * @mode: which threads
3079  * @nr_exclusive: how many wake-one or wake-many threads to wake up
3080  *
3081  * The sync wakeup differs that the waker knows that it will schedule
3082  * away soon, so while the target thread will be woken up, it will not
3083  * be migrated to another CPU - ie. the two threads are 'synchronized'
3084  * with each other. This can prevent needless bouncing between CPUs.
3085  *
3086  * On UP it can prevent extra preemption.
3087  */
3088 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3089 {
3090         unsigned long flags;
3091         int sync = 1;
3092
3093         if (unlikely(!q))
3094                 return;
3095
3096         if (unlikely(!nr_exclusive))
3097                 sync = 0;
3098
3099         spin_lock_irqsave(&q->lock, flags);
3100         __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3101         spin_unlock_irqrestore(&q->lock, flags);
3102 }
3103 EXPORT_SYMBOL_GPL(__wake_up_sync);      /* For internal use only */
3104
3105 void fastcall complete(struct completion *x)
3106 {
3107         unsigned long flags;
3108
3109         spin_lock_irqsave(&x->wait.lock, flags);
3110         x->done++;
3111         __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3112                          1, 0, NULL);
3113         spin_unlock_irqrestore(&x->wait.lock, flags);
3114 }
3115 EXPORT_SYMBOL(complete);
3116
3117 void fastcall complete_all(struct completion *x)
3118 {
3119         unsigned long flags;
3120
3121         spin_lock_irqsave(&x->wait.lock, flags);
3122         x->done += UINT_MAX/2;
3123         __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3124                          0, 0, NULL);
3125         spin_unlock_irqrestore(&x->wait.lock, flags);
3126 }
3127 EXPORT_SYMBOL(complete_all);
3128
3129 void fastcall __sched wait_for_completion(struct completion *x)
3130 {
3131         might_sleep();
3132         spin_lock_irq(&x->wait.lock);
3133         if (!x->done) {
3134                 DECLARE_WAITQUEUE(wait, current);
3135
3136                 wait.flags |= WQ_FLAG_EXCLUSIVE;
3137                 __add_wait_queue_tail(&x->wait, &wait);
3138                 do {
3139                         __set_current_state(TASK_UNINTERRUPTIBLE);
3140                         spin_unlock_irq(&x->wait.lock);
3141                         schedule();
3142                         spin_lock_irq(&x->wait.lock);
3143                 } while (!x->done);
3144                 __remove_wait_queue(&x->wait, &wait);
3145         }
3146         x->done--;
3147         spin_unlock_irq(&x->wait.lock);
3148 }
3149 EXPORT_SYMBOL(wait_for_completion);
3150
3151 unsigned long fastcall __sched
3152 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3153 {
3154         might_sleep();
3155
3156         spin_lock_irq(&x->wait.lock);
3157         if (!x->done) {
3158                 DECLARE_WAITQUEUE(wait, current);
3159
3160                 wait.flags |= WQ_FLAG_EXCLUSIVE;
3161                 __add_wait_queue_tail(&x->wait, &wait);
3162                 do {
3163                         __set_current_state(TASK_UNINTERRUPTIBLE);
3164                         spin_unlock_irq(&x->wait.lock);
3165                         timeout = schedule_timeout(timeout);
3166                         spin_lock_irq(&x->wait.lock);
3167                         if (!timeout) {
3168                                 __remove_wait_queue(&x->wait, &wait);
3169                                 goto out;
3170                         }
3171                 } while (!x->done);
3172                 __remove_wait_queue(&x->wait, &wait);
3173         }
3174         x->done--;
3175 out:
3176         spin_unlock_irq(&x->wait.lock);
3177         return timeout;
3178 }
3179 EXPORT_SYMBOL(wait_for_completion_timeout);
3180
3181 int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3182 {
3183         int ret = 0;
3184
3185         might_sleep();
3186
3187         spin_lock_irq(&x->wait.lock);
3188         if (!x->done) {
3189                 DECLARE_WAITQUEUE(wait, current);
3190
3191                 wait.flags |= WQ_FLAG_EXCLUSIVE;
3192                 __add_wait_queue_tail(&x->wait, &wait);
3193                 do {
3194                         if (signal_pending(current)) {
3195                                 ret = -ERESTARTSYS;
3196                                 __remove_wait_queue(&x->wait, &wait);
3197                                 goto out;
3198                         }
3199                         __set_current_state(TASK_INTERRUPTIBLE);
3200                         spin_unlock_irq(&x->wait.lock);
3201                         schedule();
3202                         spin_lock_irq(&x->wait.lock);
3203                 } while (!x->done);
3204                 __remove_wait_queue(&x->wait, &wait);
3205         }
3206         x->done--;
3207 out:
3208         spin_unlock_irq(&x->wait.lock);
3209
3210         return ret;
3211 }
3212 EXPORT_SYMBOL(wait_for_completion_interruptible);
3213
3214 unsigned long fastcall __sched
3215 wait_for_completion_interruptible_timeout(struct completion *x,
3216                                           unsigned long timeout)
3217 {
3218         might_sleep();
3219
3220         spin_lock_irq(&x->wait.lock);
3221         if (!x->done) {
3222                 DECLARE_WAITQUEUE(wait, current);
3223
3224                 wait.flags |= WQ_FLAG_EXCLUSIVE;
3225                 __add_wait_queue_tail(&x->wait, &wait);
3226                 do {
3227                         if (signal_pending(current)) {
3228                                 timeout = -ERESTARTSYS;
3229                                 __remove_wait_queue(&x->wait, &wait);
3230                                 goto out;
3231                         }
3232                         __set_current_state(TASK_INTERRUPTIBLE);
3233                         spin_unlock_irq(&x->wait.lock);
3234                         timeout = schedule_timeout(timeout);
3235                         spin_lock_irq(&x->wait.lock);
3236                         if (!timeout) {
3237                                 __remove_wait_queue(&x->wait, &wait);
3238                                 goto out;
3239                         }
3240                 } while (!x->done);
3241                 __remove_wait_queue(&x->wait, &wait);
3242         }
3243         x->done--;
3244 out:
3245         spin_unlock_irq(&x->wait.lock);
3246         return timeout;
3247 }
3248 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3249
3250
3251 #define SLEEP_ON_VAR                                    \
3252         unsigned long flags;                            \
3253         wait_queue_t wait;                              \
3254         init_waitqueue_entry(&wait, current);
3255
3256 #define SLEEP_ON_HEAD                                   \
3257         spin_lock_irqsave(&q->lock,flags);              \
3258         __add_wait_queue(q, &wait);                     \
3259         spin_unlock(&q->lock);
3260
3261 #define SLEEP_ON_TAIL                                   \
3262         spin_lock_irq(&q->lock);                        \
3263         __remove_wait_queue(q, &wait);                  \
3264         spin_unlock_irqrestore(&q->lock, flags);
3265
3266 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3267 {
3268         SLEEP_ON_VAR
3269
3270         current->state = TASK_INTERRUPTIBLE;
3271
3272         SLEEP_ON_HEAD
3273         schedule();
3274         SLEEP_ON_TAIL
3275 }
3276
3277 EXPORT_SYMBOL(interruptible_sleep_on);
3278
3279 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3280 {
3281         SLEEP_ON_VAR
3282
3283         current->state = TASK_INTERRUPTIBLE;
3284
3285         SLEEP_ON_HEAD
3286         timeout = schedule_timeout(timeout);
3287         SLEEP_ON_TAIL
3288
3289         return timeout;
3290 }
3291
3292 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3293
3294 void fastcall __sched sleep_on(wait_queue_head_t *q)
3295 {
3296         SLEEP_ON_VAR
3297
3298         current->state = TASK_UNINTERRUPTIBLE;
3299
3300         SLEEP_ON_HEAD
3301         schedule();
3302         SLEEP_ON_TAIL
3303 }
3304
3305 EXPORT_SYMBOL(sleep_on);
3306
3307 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3308 {
3309         SLEEP_ON_VAR
3310
3311         current->state = TASK_UNINTERRUPTIBLE;
3312
3313         SLEEP_ON_HEAD
3314         timeout = schedule_timeout(timeout);
3315         SLEEP_ON_TAIL
3316
3317         return timeout;
3318 }
3319
3320 EXPORT_SYMBOL(sleep_on_timeout);
3321
3322 void set_user_nice(task_t *p, long nice)
3323 {
3324         unsigned long flags;
3325         prio_array_t *array;
3326         runqueue_t *rq;
3327         int old_prio, new_prio, delta;
3328
3329         if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3330                 return;
3331         /*
3332          * We have to be careful, if called from sys_setpriority(),
3333          * the task might be in the middle of scheduling on another CPU.
3334          */
3335         rq = task_rq_lock(p, &flags);
3336         /*
3337          * The RT priorities are set via sched_setscheduler(), but we still
3338          * allow the 'normal' nice value to be set - but as expected
3339          * it wont have any effect on scheduling until the task is
3340          * not SCHED_NORMAL:
3341          */
3342         if (rt_task(p)) {
3343                 p->static_prio = NICE_TO_PRIO(nice);
3344                 goto out_unlock;
3345         }
3346         array = p->array;
3347         if (array)
3348                 dequeue_task(p, array);
3349
3350         old_prio = p->prio;
3351         new_prio = NICE_TO_PRIO(nice);
3352         delta = new_prio - old_prio;
3353         p->static_prio = NICE_TO_PRIO(nice);
3354         p->prio += delta;
3355
3356         if (array) {
3357                 enqueue_task(p, array);
3358                 /*
3359                  * If the task increased its priority or is running and
3360                  * lowered its priority, then reschedule its CPU:
3361                  */
3362                 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3363                         resched_task(rq->curr);
3364         }
3365 out_unlock:
3366         task_rq_unlock(rq, &flags);
3367 }
3368
3369 EXPORT_SYMBOL(set_user_nice);
3370
3371 /*
3372  * can_nice - check if a task can reduce its nice value
3373  * @p: task
3374  * @nice: nice value
3375  */
3376 int can_nice(const task_t *p, const int nice)
3377 {
3378         /* convert nice value [19,-20] to rlimit style value [0,39] */
3379         int nice_rlim = 19 - nice;
3380         return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
3381                 capable(CAP_SYS_NICE));
3382 }
3383
3384 #ifdef __ARCH_WANT_SYS_NICE
3385
3386 /*
3387  * sys_nice - change the priority of the current process.
3388  * @increment: priority increment
3389  *
3390  * sys_setpriority is a more generic, but much slower function that
3391  * does similar things.
3392  */
3393 asmlinkage long sys_nice(int increment)
3394 {
3395         int retval;
3396         long nice;
3397
3398         /*
3399          * Setpriority might change our priority at the same moment.
3400          * We don't have to worry. Conceptually one call occurs first
3401          * and we have a single winner.
3402          */
3403         if (increment < -40)
3404                 increment = -40;
3405         if (increment > 40)
3406                 increment = 40;
3407
3408         nice = PRIO_TO_NICE(current->static_prio) + increment;
3409         if (nice < -20)
3410                 nice = -20;
3411         if (nice > 19)
3412                 nice = 19;
3413
3414         if (increment < 0 && !can_nice(current, nice))
3415                 return vx_flags(VXF_IGNEG_NICE, 0) ? 0 : -EPERM;
3416
3417         retval = security_task_setnice(current, nice);
3418         if (retval)
3419                 return retval;
3420
3421         set_user_nice(current, nice);
3422         return 0;
3423 }
3424
3425 #endif
3426
3427 /**
3428  * task_prio - return the priority value of a given task.
3429  * @p: the task in question.
3430  *
3431  * This is the priority value as seen by users in /proc.
3432  * RT tasks are offset by -200. Normal tasks are centered
3433  * around 0, value goes from -16 to +15.
3434  */
3435 int task_prio(const task_t *p)
3436 {
3437         return p->prio - MAX_RT_PRIO;
3438 }
3439
3440 /**
3441  * task_nice - return the nice value of a given task.
3442  * @p: the task in question.
3443  */
3444 int task_nice(const task_t *p)
3445 {
3446         return TASK_NICE(p);
3447 }
3448
3449 /*
3450  * The only users of task_nice are binfmt_elf and binfmt_elf32.
3451  * binfmt_elf is no longer modular, but binfmt_elf32 still is.
3452  * Therefore, task_nice is needed if there is a compat_mode.
3453  */
3454 #ifdef CONFIG_COMPAT
3455 EXPORT_SYMBOL_GPL(task_nice);
3456 #endif
3457
3458 /**
3459  * idle_cpu - is a given cpu idle currently?
3460  * @cpu: the processor in question.
3461  */
3462 int idle_cpu(int cpu)
3463 {
3464         return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3465 }
3466
3467 EXPORT_SYMBOL_GPL(idle_cpu);
3468
3469 /**
3470  * idle_task - return the idle task for a given cpu.
3471  * @cpu: the processor in question.
3472  */
3473 task_t *idle_task(int cpu)
3474 {
3475         return cpu_rq(cpu)->idle;
3476 }
3477
3478 /**
3479  * find_process_by_pid - find a process with a matching PID value.
3480  * @pid: the pid in question.
3481  */
3482 static inline task_t *find_process_by_pid(pid_t pid)
3483 {
3484         return pid ? find_task_by_pid(pid) : current;
3485 }
3486
3487 /* Actually do priority change: must hold rq lock. */
3488 static void __setscheduler(struct task_struct *p, int policy, int prio)
3489 {
3490         BUG_ON(p->array);
3491         p->policy = policy;
3492         p->rt_priority = prio;
3493         if (policy != SCHED_NORMAL)
3494                 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
3495         else
3496                 p->prio = p->static_prio;
3497 }
3498
3499 /**
3500  * sched_setscheduler - change the scheduling policy and/or RT priority of
3501  * a thread.
3502  * @p: the task in question.
3503  * @policy: new policy.
3504  * @param: structure containing the new RT priority.
3505  */
3506 int sched_setscheduler(struct task_struct *p, int policy, struct sched_param *param)
3507 {
3508         int retval;
3509         int oldprio, oldpolicy = -1;
3510         prio_array_t *array;
3511         unsigned long flags;
3512         runqueue_t *rq;
3513
3514 recheck:
3515         /* double check policy once rq lock held */
3516         if (policy < 0)
3517                 policy = oldpolicy = p->policy;
3518         else if (policy != SCHED_FIFO && policy != SCHED_RR &&
3519                                 policy != SCHED_NORMAL)
3520                         return -EINVAL;
3521         /*
3522          * Valid priorities for SCHED_FIFO and SCHED_RR are
3523          * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
3524          */
3525         if (param->sched_priority < 0 ||
3526             param->sched_priority > MAX_USER_RT_PRIO-1)
3527                 return -EINVAL;
3528         if ((policy == SCHED_NORMAL) != (param->sched_priority == 0))
3529                 return -EINVAL;
3530
3531         if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
3532             param->sched_priority > p->signal->rlim[RLIMIT_RTPRIO].rlim_cur &&
3533             !capable(CAP_SYS_NICE))
3534                 return -EPERM;
3535         if ((current->euid != p->euid) && (current->euid != p->uid) &&
3536             !capable(CAP_SYS_NICE))
3537                 return -EPERM;
3538
3539         retval = security_task_setscheduler(p, policy, param);
3540         if (retval)
3541                 return retval;
3542         /*
3543          * To be able to change p->policy safely, the apropriate
3544          * runqueue lock must be held.
3545          */
3546         rq = task_rq_lock(p, &flags);
3547         /* recheck policy now with rq lock held */
3548         if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3549                 policy = oldpolicy = -1;
3550                 task_rq_unlock(rq, &flags);
3551                 goto recheck;
3552         }
3553         array = p->array;
3554         if (array)
3555                 deactivate_task(p, rq);
3556         oldprio = p->prio;
3557         __setscheduler(p, policy, param->sched_priority);
3558         if (array) {
3559                 vx_activate_task(p);
3560                 __activate_task(p, rq);
3561                 /*
3562                  * Reschedule if we are currently running on this runqueue and
3563                  * our priority decreased, or if we are not currently running on
3564                  * this runqueue and our priority is higher than the current's
3565                  */
3566                 if (task_running(rq, p)) {
3567                         if (p->prio > oldprio)
3568                                 resched_task(rq->curr);
3569                 } else if (TASK_PREEMPTS_CURR(p, rq))
3570                         resched_task(rq->curr);
3571         }
3572         task_rq_unlock(rq, &flags);
3573         return 0;
3574 }
3575 EXPORT_SYMBOL_GPL(sched_setscheduler);
3576
3577 static int do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3578 {
3579         int retval;
3580         struct sched_param lparam;
3581         struct task_struct *p;
3582
3583         if (!param || pid < 0)
3584                 return -EINVAL;
3585         if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
3586                 return -EFAULT;
3587         read_lock_irq(&tasklist_lock);
3588         p = find_process_by_pid(pid);
3589         if (!p) {
3590                 read_unlock_irq(&tasklist_lock);
3591                 return -ESRCH;
3592         }
3593         retval = sched_setscheduler(p, policy, &lparam);
3594         read_unlock_irq(&tasklist_lock);
3595         return retval;
3596 }
3597
3598 /**
3599  * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3600  * @pid: the pid in question.
3601  * @policy: new policy.
3602  * @param: structure containing the new RT priority.
3603  */
3604 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3605                                        struct sched_param __user *param)
3606 {
3607         return do_sched_setscheduler(pid, policy, param);
3608 }
3609
3610 /**
3611  * sys_sched_setparam - set/change the RT priority of a thread
3612  * @pid: the pid in question.
3613  * @param: structure containing the new RT priority.
3614  */
3615 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3616 {
3617         return do_sched_setscheduler(pid, -1, param);
3618 }
3619
3620 /**
3621  * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3622  * @pid: the pid in question.
3623  */
3624 asmlinkage long sys_sched_getscheduler(pid_t pid)
3625 {
3626         int retval = -EINVAL;
3627         task_t *p;
3628
3629         if (pid < 0)
3630                 goto out_nounlock;
3631
3632         retval = -ESRCH;
3633         read_lock(&tasklist_lock);
3634         p = find_process_by_pid(pid);
3635         if (p) {
3636                 retval = security_task_getscheduler(p);
3637                 if (!retval)
3638                         retval = p->policy;
3639         }
3640         read_unlock(&tasklist_lock);
3641
3642 out_nounlock:
3643         return retval;
3644 }
3645
3646 /**
3647  * sys_sched_getscheduler - get the RT priority of a thread
3648  * @pid: the pid in question.
3649  * @param: structure containing the RT priority.
3650  */
3651 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3652 {
3653         struct sched_param lp;
3654         int retval = -EINVAL;
3655         task_t *p;
3656
3657         if (!param || pid < 0)
3658                 goto out_nounlock;
3659
3660         read_lock(&tasklist_lock);
3661         p = find_process_by_pid(pid);
3662         retval = -ESRCH;
3663         if (!p)
3664                 goto out_unlock;
3665
3666         retval = security_task_getscheduler(p);
3667         if (retval)
3668                 goto out_unlock;
3669
3670         lp.sched_priority = p->rt_priority;
3671         read_unlock(&tasklist_lock);
3672
3673         /*
3674          * This one might sleep, we cannot do it with a spinlock held ...
3675          */
3676         retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3677
3678 out_nounlock:
3679         return retval;
3680
3681 out_unlock:
3682         read_unlock(&tasklist_lock);
3683         return retval;
3684 }
3685
3686 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
3687 {
3688         task_t *p;
3689         int retval;
3690         cpumask_t cpus_allowed;
3691
3692         lock_cpu_hotplug();
3693         read_lock(&tasklist_lock);
3694
3695         p = find_process_by_pid(pid);
3696         if (!p) {
3697                 read_unlock(&tasklist_lock);
3698                 unlock_cpu_hotplug();
3699                 return -ESRCH;
3700         }
3701
3702         /*
3703          * It is not safe to call set_cpus_allowed with the
3704          * tasklist_lock held.  We will bump the task_struct's
3705          * usage count and then drop tasklist_lock.
3706          */
3707         get_task_struct(p);
3708         read_unlock(&tasklist_lock);
3709
3710         retval = -EPERM;
3711         if ((current->euid != p->euid) && (current->euid != p->uid) &&
3712                         !capable(CAP_SYS_NICE))
3713                 goto out_unlock;
3714
3715         cpus_allowed = cpuset_cpus_allowed(p);
3716         cpus_and(new_mask, new_mask, cpus_allowed);
3717         retval = set_cpus_allowed(p, new_mask);
3718
3719 out_unlock:
3720         put_task_struct(p);
3721         unlock_cpu_hotplug();
3722         return retval;
3723 }
3724
3725 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
3726                              cpumask_t *new_mask)
3727 {
3728         if (len < sizeof(cpumask_t)) {
3729                 memset(new_mask, 0, sizeof(cpumask_t));
3730         } else if (len > sizeof(cpumask_t)) {
3731                 len = sizeof(cpumask_t);
3732         }
3733         return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
3734 }
3735
3736 /**
3737  * sys_sched_setaffinity - set the cpu affinity of a process
3738  * @pid: pid of the process
3739  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3740  * @user_mask_ptr: user-space pointer to the new cpu mask
3741  */
3742 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
3743                                       unsigned long __user *user_mask_ptr)
3744 {
3745         cpumask_t new_mask;
3746         int retval;
3747
3748         retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
3749         if (retval)
3750                 return retval;
3751
3752         return sched_setaffinity(pid, new_mask);
3753 }
3754
3755 /*
3756  * Represents all cpu's present in the system
3757  * In systems capable of hotplug, this map could dynamically grow
3758  * as new cpu's are detected in the system via any platform specific
3759  * method, such as ACPI for e.g.
3760  */
3761
3762 cpumask_t cpu_present_map;
3763 EXPORT_SYMBOL(cpu_present_map);
3764
3765 #ifndef CONFIG_SMP
3766 cpumask_t cpu_online_map = CPU_MASK_ALL;
3767 cpumask_t cpu_possible_map = CPU_MASK_ALL;
3768 #endif
3769
3770 long sched_getaffinity(pid_t pid, cpumask_t *mask)
3771 {
3772         int retval;
3773         task_t *p;
3774
3775         lock_cpu_hotplug();
3776         read_lock(&tasklist_lock);
3777
3778         retval = -ESRCH;
3779         p = find_process_by_pid(pid);
3780         if (!p)
3781                 goto out_unlock;
3782
3783         retval = 0;
3784         cpus_and(*mask, p->cpus_allowed, cpu_possible_map);
3785
3786 out_unlock:
3787         read_unlock(&tasklist_lock);
3788         unlock_cpu_hotplug();
3789         if (retval)
3790                 return retval;
3791
3792         return 0;
3793 }
3794
3795 /**
3796  * sys_sched_getaffinity - get the cpu affinity of a process
3797  * @pid: pid of the process
3798  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3799  * @user_mask_ptr: user-space pointer to hold the current cpu mask
3800  */
3801 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
3802                                       unsigned long __user *user_mask_ptr)
3803 {
3804         int ret;
3805         cpumask_t mask;
3806
3807         if (len < sizeof(cpumask_t))
3808                 return -EINVAL;
3809
3810         ret = sched_getaffinity(pid, &mask);
3811         if (ret < 0)
3812                 return ret;
3813
3814         if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
3815                 return -EFAULT;
3816
3817         return sizeof(cpumask_t);
3818 }
3819
3820 /**
3821  * sys_sched_yield - yield the current processor to other threads.
3822  *
3823  * this function yields the current CPU by moving the calling thread
3824  * to the expired array. If there are no other threads running on this
3825  * CPU then this function will return.
3826  */
3827 asmlinkage long sys_sched_yield(void)
3828 {
3829         runqueue_t *rq = this_rq_lock();
3830         prio_array_t *array = current->array;
3831         prio_array_t *target = rq->expired;
3832
3833         schedstat_inc(rq, yld_cnt);
3834         /*
3835          * We implement yielding by moving the task into the expired
3836          * queue.
3837          *
3838          * (special rule: RT tasks will just roundrobin in the active
3839          *  array.)
3840          */
3841         if (rt_task(current))
3842                 target = rq->active;
3843
3844         if (current->array->nr_active == 1) {
3845                 schedstat_inc(rq, yld_act_empty);
3846                 if (!rq->expired->nr_active)
3847                         schedstat_inc(rq, yld_both_empty);
3848         } else if (!rq->expired->nr_active)
3849                 schedstat_inc(rq, yld_exp_empty);
3850
3851         if (array != target) {
3852                 dequeue_task(current, array);
3853                 enqueue_task(current, target);
3854         } else
3855                 /*
3856                  * requeue_task is cheaper so perform that if possible.
3857                  */
3858                 requeue_task(current, array);
3859
3860         /*
3861          * Since we are going to call schedule() anyway, there's
3862          * no need to preempt or enable interrupts:
3863          */
3864         __release(rq->lock);
3865         _raw_spin_unlock(&rq->lock);
3866         preempt_enable_no_resched();
3867
3868         schedule();
3869
3870         return 0;
3871 }
3872
3873 static inline void __cond_resched(void)
3874 {
3875         do {
3876                 add_preempt_count(PREEMPT_ACTIVE);
3877                 schedule();
3878                 sub_preempt_count(PREEMPT_ACTIVE);
3879         } while (need_resched());
3880 }
3881
3882 int __sched cond_resched(void)
3883 {
3884         if (need_resched()) {
3885                 __cond_resched();
3886                 return 1;
3887         }
3888         return 0;
3889 }
3890
3891 EXPORT_SYMBOL(cond_resched);
3892
3893 /*
3894  * cond_resched_lock() - if a reschedule is pending, drop the given lock,
3895  * call schedule, and on return reacquire the lock.
3896  *
3897  * This works OK both with and without CONFIG_PREEMPT.  We do strange low-level
3898  * operations here to prevent schedule() from being called twice (once via
3899  * spin_unlock(), once by hand).
3900  */
3901 int cond_resched_lock(spinlock_t * lock)
3902 {
3903         int ret = 0;
3904
3905         if (need_lockbreak(lock)) {
3906                 spin_unlock(lock);
3907                 cpu_relax();
3908                 ret = 1;
3909                 spin_lock(lock);
3910         }
3911         if (need_resched()) {
3912                 _raw_spin_unlock(lock);
3913                 preempt_enable_no_resched();
3914                 __cond_resched();
3915                 ret = 1;
3916                 spin_lock(lock);
3917         }
3918         return ret;
3919 }
3920
3921 EXPORT_SYMBOL(cond_resched_lock);
3922
3923 int __sched cond_resched_softirq(void)
3924 {
3925         BUG_ON(!in_softirq());
3926
3927         if (need_resched()) {
3928                 __local_bh_enable();
3929                 __cond_resched();
3930                 local_bh_disable();
3931                 return 1;
3932         }
3933         return 0;
3934 }
3935
3936 EXPORT_SYMBOL(cond_resched_softirq);
3937
3938
3939 /**
3940  * yield - yield the current processor to other threads.
3941  *
3942  * this is a shortcut for kernel-space yielding - it marks the
3943  * thread runnable and calls sys_sched_yield().
3944  */
3945 void __sched yield(void)
3946 {
3947         set_current_state(TASK_RUNNING);
3948         sys_sched_yield();
3949 }
3950
3951 EXPORT_SYMBOL(yield);
3952
3953 /*
3954  * This task is about to go to sleep on IO.  Increment rq->nr_iowait so
3955  * that process accounting knows that this is a task in IO wait state.
3956  *
3957  * But don't do that if it is a deliberate, throttling IO wait (this task
3958  * has set its backing_dev_info: the queue against which it should throttle)
3959  */
3960 void __sched io_schedule(void)
3961 {
3962         struct runqueue *rq = &per_cpu(runqueues, _smp_processor_id());
3963
3964         atomic_inc(&rq->nr_iowait);
3965         schedule();
3966         atomic_dec(&rq->nr_iowait);
3967 }
3968
3969 EXPORT_SYMBOL(io_schedule);
3970
3971 long __sched io_schedule_timeout(long timeout)
3972 {
3973         struct runqueue *rq = &per_cpu(runqueues, _smp_processor_id());
3974         long ret;
3975
3976         atomic_inc(&rq->nr_iowait);
3977         ret = schedule_timeout(timeout);
3978         atomic_dec(&rq->nr_iowait);
3979         return ret;
3980 }
3981
3982 /**
3983  * sys_sched_get_priority_max - return maximum RT priority.
3984  * @policy: scheduling class.
3985  *
3986  * this syscall returns the maximum rt_priority that can be used
3987  * by a given scheduling class.
3988  */
3989 asmlinkage long sys_sched_get_priority_max(int policy)
3990 {
3991         int ret = -EINVAL;
3992
3993         switch (policy) {
3994         case SCHED_FIFO:
3995         case SCHED_RR:
3996                 ret = MAX_USER_RT_PRIO-1;
3997                 break;
3998         case SCHED_NORMAL:
3999                 ret = 0;
4000                 break;
4001         }
4002         return ret;
4003 }
4004
4005 /**
4006  * sys_sched_get_priority_min - return minimum RT priority.
4007  * @policy: scheduling class.
4008  *
4009  * this syscall returns the minimum rt_priority that can be used
4010  * by a given scheduling class.
4011  */
4012 asmlinkage long sys_sched_get_priority_min(int policy)
4013 {
4014         int ret = -EINVAL;
4015
4016         switch (policy) {
4017         case SCHED_FIFO:
4018         case SCHED_RR:
4019                 ret = 1;
4020                 break;
4021         case SCHED_NORMAL:
4022                 ret = 0;
4023         }
4024         return ret;
4025 }
4026
4027 /**
4028  * sys_sched_rr_get_interval - return the default timeslice of a process.
4029  * @pid: pid of the process.
4030  * @interval: userspace pointer to the timeslice value.
4031  *
4032  * this syscall writes the default timeslice value of a given process
4033  * into the user-space timespec buffer. A value of '0' means infinity.
4034  */
4035 asmlinkage
4036 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4037 {
4038         int retval = -EINVAL;
4039         struct timespec t;
4040         task_t *p;
4041
4042         if (pid < 0)
4043                 goto out_nounlock;
4044
4045         retval = -ESRCH;
4046         read_lock(&tasklist_lock);
4047         p = find_process_by_pid(pid);
4048         if (!p)
4049                 goto out_unlock;
4050
4051         retval = security_task_getscheduler(p);
4052         if (retval)
4053                 goto out_unlock;
4054
4055         jiffies_to_timespec(p->policy & SCHED_FIFO ?
4056                                 0 : task_timeslice(p), &t);
4057         read_unlock(&tasklist_lock);
4058         retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4059 out_nounlock:
4060         return retval;
4061 out_unlock:
4062         read_unlock(&tasklist_lock);
4063         return retval;
4064 }
4065
4066 static inline struct task_struct *eldest_child(struct task_struct *p)
4067 {
4068         if (list_empty(&p->children)) return NULL;
4069         return list_entry(p->children.next,struct task_struct,sibling);
4070 }
4071
4072 static inline struct task_struct *older_sibling(struct task_struct *p)
4073 {
4074         if (p->sibling.prev==&p->parent->children) return NULL;
4075         return list_entry(p->sibling.prev,struct task_struct,sibling);
4076 }
4077
4078 static inline struct task_struct *younger_sibling(struct task_struct *p)
4079 {
4080         if (p->sibling.next==&p->parent->children) return NULL;
4081         return list_entry(p->sibling.next,struct task_struct,sibling);
4082 }
4083
4084 static void show_task(task_t * p)
4085 {
4086         task_t *relative;
4087         unsigned state;
4088         unsigned long free = 0;
4089         static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
4090
4091         printk("%-13.13s ", p->comm);
4092         state = p->state ? __ffs(p->state) + 1 : 0;
4093         if (state < ARRAY_SIZE(stat_nam))
4094                 printk(stat_nam[state]);
4095         else
4096                 printk("?");
4097 #if (BITS_PER_LONG == 32)
4098         if (state == TASK_RUNNING)
4099                 printk(" running ");
4100         else
4101                 printk(" %08lX ", thread_saved_pc(p));
4102 #else
4103         if (state == TASK_RUNNING)
4104                 printk("  running task   ");
4105         else
4106                 printk(" %016lx ", thread_saved_pc(p));
4107 #endif
4108 #ifdef CONFIG_DEBUG_STACK_USAGE
4109         {
4110                 unsigned long * n = (unsigned long *) (p->thread_info+1);
4111                 while (!*n)
4112                         n++;
4113                 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
4114         }
4115 #endif
4116         printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
4117         if ((relative = eldest_child(p)))
4118                 printk("%5d ", relative->pid);
4119         else
4120                 printk("      ");
4121         if ((relative = younger_sibling(p)))
4122                 printk("%7d", relative->pid);
4123         else
4124                 printk("       ");
4125         if ((relative = older_sibling(p)))
4126                 printk(" %5d", relative->pid);
4127         else
4128                 printk("      ");
4129         if (!p->mm)
4130                 printk(" (L-TLB)\n");
4131         else
4132                 printk(" (NOTLB)\n");
4133
4134         if (state != TASK_RUNNING)
4135                 show_stack(p, NULL);
4136 }
4137
4138 void show_state(void)
4139 {
4140         task_t *g, *p;
4141
4142 #if (BITS_PER_LONG == 32)
4143         printk("\n"
4144                "                                               sibling\n");
4145         printk("  task             PC      pid father child younger older\n");
4146 #else
4147         printk("\n"
4148                "                                                       sibling\n");
4149         printk("  task                 PC          pid father child younger older\n");
4150 #endif
4151         read_lock(&tasklist_lock);
4152         do_each_thread(g, p) {
4153                 /*
4154                  * reset the NMI-timeout, listing all files on a slow
4155                  * console might take alot of time:
4156                  */
4157                 touch_nmi_watchdog();
4158                 show_task(p);
4159         } while_each_thread(g, p);
4160
4161         read_unlock(&tasklist_lock);
4162 }
4163
4164 void __devinit init_idle(task_t *idle, int cpu)
4165 {
4166         runqueue_t *rq = cpu_rq(cpu);
4167         unsigned long flags;
4168
4169         idle->sleep_avg = 0;
4170         idle->array = NULL;
4171         idle->prio = MAX_PRIO;
4172         idle->state = TASK_RUNNING;
4173         idle->cpus_allowed = cpumask_of_cpu(cpu);
4174         set_task_cpu(idle, cpu);
4175
4176         spin_lock_irqsave(&rq->lock, flags);
4177         rq->curr = rq->idle = idle;
4178         set_tsk_need_resched(idle);
4179         spin_unlock_irqrestore(&rq->lock, flags);
4180
4181         /* Set the preempt count _outside_ the spinlocks! */
4182 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4183         idle->thread_info->preempt_count = (idle->lock_depth >= 0);
4184 #else
4185         idle->thread_info->preempt_count = 0;
4186 #endif
4187 }
4188
4189 /*
4190  * In a system that switches off the HZ timer nohz_cpu_mask
4191  * indicates which cpus entered this state. This is used
4192  * in the rcu update to wait only for active cpus. For system
4193  * which do not switch off the HZ timer nohz_cpu_mask should
4194  * always be CPU_MASK_NONE.
4195  */
4196 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4197
4198 #ifdef CONFIG_SMP
4199 /*
4200  * This is how migration works:
4201  *
4202  * 1) we queue a migration_req_t structure in the source CPU's
4203  *    runqueue and wake up that CPU's migration thread.
4204  * 2) we down() the locked semaphore => thread blocks.
4205  * 3) migration thread wakes up (implicitly it forces the migrated
4206  *    thread off the CPU)
4207  * 4) it gets the migration request and checks whether the migrated
4208  *    task is still in the wrong runqueue.
4209  * 5) if it's in the wrong runqueue then the migration thread removes
4210  *    it and puts it into the right queue.
4211  * 6) migration thread up()s the semaphore.
4212  * 7) we wake up and the migration is done.
4213  */
4214
4215 /*
4216  * Change a given task's CPU affinity. Migrate the thread to a
4217  * proper CPU and schedule it away if the CPU it's executing on
4218  * is removed from the allowed bitmask.
4219  *
4220  * NOTE: the caller must have a valid reference to the task, the
4221  * task must not exit() & deallocate itself prematurely.  The
4222  * call is not atomic; no spinlocks may be held.
4223  */
4224 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
4225 {
4226         unsigned long flags;
4227         int ret = 0;
4228         migration_req_t req;
4229         runqueue_t *rq;
4230
4231         rq = task_rq_lock(p, &flags);
4232         if (!cpus_intersects(new_mask, cpu_online_map)) {
4233                 ret = -EINVAL;
4234                 goto out;
4235         }
4236
4237         p->cpus_allowed = new_mask;
4238         /* Can the task run on the task's current CPU? If so, we're done */
4239         if (cpu_isset(task_cpu(p), new_mask))
4240                 goto out;
4241
4242         if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4243                 /* Need help from migration thread: drop lock and wait. */
4244                 task_rq_unlock(rq, &flags);
4245                 wake_up_process(rq->migration_thread);
4246                 wait_for_completion(&req.done);
4247                 tlb_migrate_finish(p->mm);
4248                 return 0;
4249         }
4250 out:
4251         task_rq_unlock(rq, &flags);
4252         return ret;
4253 }
4254
4255 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4256
4257 /*
4258  * Move (not current) task off this cpu, onto dest cpu.  We're doing
4259  * this because either it can't run here any more (set_cpus_allowed()
4260  * away from this CPU, or CPU going down), or because we're
4261  * attempting to rebalance this task on exec (sched_exec).
4262  *
4263  * So we race with normal scheduler movements, but that's OK, as long
4264  * as the task is no longer on this CPU.
4265  */
4266 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4267 {
4268         runqueue_t *rq_dest, *rq_src;
4269
4270         if (unlikely(cpu_is_offline(dest_cpu)))
4271                 return;
4272
4273         rq_src = cpu_rq(src_cpu);
4274         rq_dest = cpu_rq(dest_cpu);
4275
4276         double_rq_lock(rq_src, rq_dest);
4277         /* Already moved. */
4278         if (task_cpu(p) != src_cpu)
4279                 goto out;
4280         /* Affinity changed (again). */
4281         if (!cpu_isset(dest_cpu, p->cpus_allowed))
4282                 goto out;
4283
4284         set_task_cpu(p, dest_cpu);
4285         if (p->array) {
4286                 /*
4287                  * Sync timestamp with rq_dest's before activating.
4288                  * The same thing could be achieved by doing this step
4289                  * afterwards, and pretending it was a local activate.
4290                  * This way is cleaner and logically correct.
4291                  */
4292                 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4293                                 + rq_dest->timestamp_last_tick;
4294                 deactivate_task(p, rq_src);
4295                 activate_task(p, rq_dest, 0);
4296                 if (TASK_PREEMPTS_CURR(p, rq_dest))
4297                         resched_task(rq_dest->curr);
4298         }
4299
4300 out:
4301         double_rq_unlock(rq_src, rq_dest);
4302 }
4303
4304 /*
4305  * migration_thread - this is a highprio system thread that performs
4306  * thread migration by bumping thread off CPU then 'pushing' onto
4307  * another runqueue.
4308  */
4309 static int migration_thread(void * data)
4310 {
4311         runqueue_t *rq;
4312         int cpu = (long)data;
4313
4314         rq = cpu_rq(cpu);
4315         BUG_ON(rq->migration_thread != current);
4316
4317         set_current_state(TASK_INTERRUPTIBLE);
4318         while (!kthread_should_stop()) {
4319                 struct list_head *head;
4320                 migration_req_t *req;
4321
4322                 if (current->flags & PF_FREEZE)
4323                         refrigerator(PF_FREEZE);
4324
4325                 spin_lock_irq(&rq->lock);
4326
4327                 if (cpu_is_offline(cpu)) {
4328                         spin_unlock_irq(&rq->lock);
4329                         goto wait_to_die;
4330                 }
4331
4332                 if (rq->active_balance) {
4333                         active_load_balance(rq, cpu);
4334                         rq->active_balance = 0;
4335                 }
4336
4337                 head = &rq->migration_queue;
4338
4339                 if (list_empty(head)) {
4340                         spin_unlock_irq(&rq->lock);
4341                         schedule();
4342                         set_current_state(TASK_INTERRUPTIBLE);
4343                         continue;
4344                 }
4345                 req = list_entry(head->next, migration_req_t, list);
4346                 list_del_init(head->next);
4347
4348                 if (req->type == REQ_MOVE_TASK) {
4349                         spin_unlock(&rq->lock);
4350                         __migrate_task(req->task, cpu, req->dest_cpu);
4351                         local_irq_enable();
4352                 } else if (req->type == REQ_SET_DOMAIN) {
4353                         rq->sd = req->sd;
4354                         spin_unlock_irq(&rq->lock);
4355                 } else {
4356                         spin_unlock_irq(&rq->lock);
4357                         WARN_ON(1);
4358                 }
4359
4360                 complete(&req->done);
4361         }
4362         __set_current_state(TASK_RUNNING);
4363         return 0;
4364
4365 wait_to_die:
4366         /* Wait for kthread_stop */
4367         set_current_state(TASK_INTERRUPTIBLE);
4368         while (!kthread_should_stop()) {
4369                 schedule();
4370                 set_current_state(TASK_INTERRUPTIBLE);
4371         }
4372         __set_current_state(TASK_RUNNING);
4373         return 0;
4374 }
4375
4376 #ifdef CONFIG_HOTPLUG_CPU
4377 /* Figure out where task on dead CPU should go, use force if neccessary. */
4378 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
4379 {
4380         int dest_cpu;
4381         cpumask_t mask;
4382
4383         /* On same node? */
4384         mask = node_to_cpumask(cpu_to_node(dead_cpu));
4385         cpus_and(mask, mask, tsk->cpus_allowed);
4386         dest_cpu = any_online_cpu(mask);
4387
4388         /* On any allowed CPU? */
4389         if (dest_cpu == NR_CPUS)
4390                 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4391
4392         /* No more Mr. Nice Guy. */
4393         if (dest_cpu == NR_CPUS) {
4394                 cpus_setall(tsk->cpus_allowed);
4395                 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4396
4397                 /*
4398                  * Don't tell them about moving exiting tasks or
4399                  * kernel threads (both mm NULL), since they never
4400                  * leave kernel.
4401                  */
4402                 if (tsk->mm && printk_ratelimit())
4403                         printk(KERN_INFO "process %d (%s) no "
4404                                "longer affine to cpu%d\n",
4405                                tsk->pid, tsk->comm, dead_cpu);
4406         }
4407         __migrate_task(tsk, dead_cpu, dest_cpu);
4408 }
4409
4410 /*
4411  * While a dead CPU has no uninterruptible tasks queued at this point,
4412  * it might still have a nonzero ->nr_uninterruptible counter, because
4413  * for performance reasons the counter is not stricly tracking tasks to
4414  * their home CPUs. So we just add the counter to another CPU's counter,
4415  * to keep the global sum constant after CPU-down:
4416  */
4417 static void migrate_nr_uninterruptible(runqueue_t *rq_src)
4418 {
4419         runqueue_t *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
4420         unsigned long flags;
4421
4422         local_irq_save(flags);
4423         double_rq_lock(rq_src, rq_dest);
4424         rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
4425         rq_src->nr_uninterruptible = 0;
4426         double_rq_unlock(rq_src, rq_dest);
4427         local_irq_restore(flags);
4428 }
4429
4430 /* Run through task list and migrate tasks from the dead cpu. */
4431 static void migrate_live_tasks(int src_cpu)
4432 {
4433         struct task_struct *tsk, *t;
4434
4435         write_lock_irq(&tasklist_lock);
4436
4437         do_each_thread(t, tsk) {
4438                 if (tsk == current)
4439                         continue;
4440
4441                 if (task_cpu(tsk) == src_cpu)
4442                         move_task_off_dead_cpu(src_cpu, tsk);
4443         } while_each_thread(t, tsk);
4444
4445         write_unlock_irq(&tasklist_lock);
4446 }
4447
4448 /* Schedules idle task to be the next runnable task on current CPU.
4449  * It does so by boosting its priority to highest possible and adding it to
4450  * the _front_ of runqueue. Used by CPU offline code.
4451  */
4452 void sched_idle_next(void)
4453 {
4454         int cpu = smp_processor_id();
4455         runqueue_t *rq = this_rq();
4456         struct task_struct *p = rq->idle;
4457         unsigned long flags;
4458
4459         /* cpu has to be offline */
4460         BUG_ON(cpu_online(cpu));
4461
4462         /* Strictly not necessary since rest of the CPUs are stopped by now
4463          * and interrupts disabled on current cpu.
4464          */
4465         spin_lock_irqsave(&rq->lock, flags);
4466
4467         __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4468         /* Add idle task to _front_ of it's priority queue */
4469         __activate_idle_task(p, rq);
4470
4471         spin_unlock_irqrestore(&rq->lock, flags);
4472 }
4473
4474 /* Ensures that the idle task is using init_mm right before its cpu goes
4475  * offline.
4476  */
4477 void idle_task_exit(void)
4478 {
4479         struct mm_struct *mm = current->active_mm;
4480
4481         BUG_ON(cpu_online(smp_processor_id()));
4482
4483         if (mm != &init_mm)
4484                 switch_mm(mm, &init_mm, current);
4485         mmdrop(mm);
4486 }
4487
4488 static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
4489 {
4490         struct runqueue *rq = cpu_rq(dead_cpu);
4491
4492         /* Must be exiting, otherwise would be on tasklist. */
4493         BUG_ON(tsk->exit_state != EXIT_ZOMBIE && tsk->exit_state != EXIT_DEAD);
4494
4495         /* Cannot have done final schedule yet: would have vanished. */
4496         BUG_ON(tsk->flags & PF_DEAD);
4497
4498         get_task_struct(tsk);
4499
4500         /*
4501          * Drop lock around migration; if someone else moves it,
4502          * that's OK.  No task can be added to this CPU, so iteration is
4503          * fine.
4504          */
4505         spin_unlock_irq(&rq->lock);
4506         move_task_off_dead_cpu(dead_cpu, tsk);
4507         spin_lock_irq(&rq->lock);
4508
4509         put_task_struct(tsk);
4510 }
4511
4512 /* release_task() removes task from tasklist, so we won't find dead tasks. */
4513 static void migrate_dead_tasks(unsigned int dead_cpu)
4514 {
4515         unsigned arr, i;
4516         struct runqueue *rq = cpu_rq(dead_cpu);
4517
4518         for (arr = 0; arr < 2; arr++) {
4519                 for (i = 0; i < MAX_PRIO; i++) {
4520                         struct list_head *list = &rq->arrays[arr].queue[i];
4521                         while (!list_empty(list))
4522                                 migrate_dead(dead_cpu,
4523                                              list_entry(list->next, task_t,
4524                                                         run_list));
4525                 }
4526         }
4527 }
4528 #endif /* CONFIG_HOTPLUG_CPU */
4529
4530 /*
4531  * migration_call - callback that gets triggered when a CPU is added.
4532  * Here we can start up the necessary migration thread for the new CPU.
4533  */
4534 static int migration_call(struct notifier_block *nfb, unsigned long action,
4535                           void *hcpu)
4536 {
4537         int cpu = (long)hcpu;
4538         struct task_struct *p;
4539         struct runqueue *rq;
4540         unsigned long flags;
4541
4542         switch (action) {
4543         case CPU_UP_PREPARE:
4544                 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4545                 if (IS_ERR(p))
4546                         return NOTIFY_BAD;
4547                 p->flags |= PF_NOFREEZE;
4548                 kthread_bind(p, cpu);
4549                 /* Must be high prio: stop_machine expects to yield to it. */
4550                 rq = task_rq_lock(p, &flags);
4551                 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4552                 task_rq_unlock(rq, &flags);
4553                 cpu_rq(cpu)->migration_thread = p;
4554                 break;
4555         case CPU_ONLINE:
4556                 /* Strictly unneccessary, as first user will wake it. */
4557                 wake_up_process(cpu_rq(cpu)->migration_thread);
4558                 break;
4559 #ifdef CONFIG_HOTPLUG_CPU
4560         case CPU_UP_CANCELED:
4561                 /* Unbind it from offline cpu so it can run.  Fall thru. */
4562                 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
4563                 kthread_stop(cpu_rq(cpu)->migration_thread);
4564                 cpu_rq(cpu)->migration_thread = NULL;
4565                 break;
4566         case CPU_DEAD:
4567                 migrate_live_tasks(cpu);
4568                 rq = cpu_rq(cpu);
4569                 kthread_stop(rq->migration_thread);
4570                 rq->migration_thread = NULL;
4571                 /* Idle task back to normal (off runqueue, low prio) */
4572                 rq = task_rq_lock(rq->idle, &flags);
4573                 deactivate_task(rq->idle, rq);
4574                 rq->idle->static_prio = MAX_PRIO;
4575                 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4576                 migrate_dead_tasks(cpu);
4577                 task_rq_unlock(rq, &flags);
4578                 migrate_nr_uninterruptible(rq);
4579                 BUG_ON(rq->nr_running != 0);
4580
4581                 /* No need to migrate the tasks: it was best-effort if
4582                  * they didn't do lock_cpu_hotplug().  Just wake up
4583                  * the requestors. */
4584                 spin_lock_irq(&rq->lock);
4585                 while (!list_empty(&rq->migration_queue)) {
4586                         migration_req_t *req;
4587                         req = list_entry(rq->migration_queue.next,
4588                                          migration_req_t, list);
4589                         BUG_ON(req->type != REQ_MOVE_TASK);
4590                         list_del_init(&req->list);
4591                         complete(&req->done);
4592                 }
4593                 spin_unlock_irq(&rq->lock);
4594                 break;
4595 #endif
4596         }
4597         return NOTIFY_OK;
4598 }
4599
4600 /* Register at highest priority so that task migration (migrate_all_tasks)
4601  * happens before everything else.
4602  */
4603 static struct notifier_block __devinitdata migration_notifier = {
4604         .notifier_call = migration_call,
4605         .priority = 10
4606 };
4607
4608 int __init migration_init(void)
4609 {
4610         void *cpu = (void *)(long)smp_processor_id();
4611         /* Start one for boot CPU. */
4612         migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4613         migration_call(&migration_notifier, CPU_ONLINE, cpu);
4614         register_cpu_notifier(&migration_notifier);
4615         return 0;
4616 }
4617 #endif
4618
4619 #ifdef CONFIG_SMP
4620 #define SCHED_DOMAIN_DEBUG
4621 #ifdef SCHED_DOMAIN_DEBUG
4622 static void sched_domain_debug(struct sched_domain *sd, int cpu)
4623 {
4624         int level = 0;
4625
4626         printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
4627
4628         do {
4629                 int i;
4630                 char str[NR_CPUS];
4631                 struct sched_group *group = sd->groups;
4632                 cpumask_t groupmask;
4633
4634                 cpumask_scnprintf(str, NR_CPUS, sd->span);
4635                 cpus_clear(groupmask);
4636
4637                 printk(KERN_DEBUG);
4638                 for (i = 0; i < level + 1; i++)
4639                         printk(" ");
4640                 printk("domain %d: ", level);
4641
4642                 if (!(sd->flags & SD_LOAD_BALANCE)) {
4643                         printk("does not load-balance\n");
4644                         if (sd->parent)
4645                                 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
4646                         break;
4647                 }
4648
4649                 printk("span %s\n", str);
4650
4651                 if (!cpu_isset(cpu, sd->span))
4652                         printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
4653                 if (!cpu_isset(cpu, group->cpumask))
4654                         printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
4655
4656                 printk(KERN_DEBUG);
4657                 for (i = 0; i < level + 2; i++)
4658                         printk(" ");
4659                 printk("groups:");
4660                 do {
4661                         if (!group) {
4662                                 printk("\n");
4663                                 printk(KERN_ERR "ERROR: group is NULL\n");
4664                                 break;
4665                         }
4666
4667                         if (!group->cpu_power) {
4668                                 printk("\n");
4669                                 printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
4670                         }
4671
4672                         if (!cpus_weight(group->cpumask)) {
4673                                 printk("\n");
4674                                 printk(KERN_ERR "ERROR: empty group\n");
4675                         }
4676
4677                         if (cpus_intersects(groupmask, group->cpumask)) {
4678                                 printk("\n");
4679                                 printk(KERN_ERR "ERROR: repeated CPUs\n");
4680                         }
4681
4682                         cpus_or(groupmask, groupmask, group->cpumask);
4683
4684                         cpumask_scnprintf(str, NR_CPUS, group->cpumask);
4685                         printk(" %s", str);
4686
4687                         group = group->next;
4688                 } while (group != sd->groups);
4689                 printk("\n");
4690
4691                 if (!cpus_equal(sd->span, groupmask))
4692                         printk(KERN_ERR "ERROR: groups don't span domain->span\n");
4693
4694                 level++;
4695                 sd = sd->parent;
4696
4697                 if (sd) {
4698                         if (!cpus_subset(groupmask, sd->span))
4699                                 printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
4700                 }
4701
4702         } while (sd);
4703 }
4704 #else
4705 #define sched_domain_debug(sd, cpu) {}
4706 #endif
4707
4708 /*
4709  * Attach the domain 'sd' to 'cpu' as its base domain.  Callers must
4710  * hold the hotplug lock.
4711  */
4712 void __devinit cpu_attach_domain(struct sched_domain *sd, int cpu)
4713 {
4714         migration_req_t req;
4715         unsigned long flags;
4716         runqueue_t *rq = cpu_rq(cpu);
4717         int local = 1;
4718
4719         sched_domain_debug(sd, cpu);
4720
4721         spin_lock_irqsave(&rq->lock, flags);
4722
4723         if (cpu == smp_processor_id() || !cpu_online(cpu)) {
4724                 rq->sd = sd;
4725         } else {
4726                 init_completion(&req.done);
4727                 req.type = REQ_SET_DOMAIN;
4728                 req.sd = sd;
4729                 list_add(&req.list, &rq->migration_queue);
4730                 local = 0;
4731         }
4732
4733         spin_unlock_irqrestore(&rq->lock, flags);
4734
4735         if (!local) {
4736                 wake_up_process(rq->migration_thread);
4737                 wait_for_completion(&req.done);
4738         }
4739 }
4740
4741 /* cpus with isolated domains */
4742 cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
4743
4744 /* Setup the mask of cpus configured for isolated domains */
4745 static int __init isolated_cpu_setup(char *str)
4746 {
4747         int ints[NR_CPUS], i;
4748
4749         str = get_options(str, ARRAY_SIZE(ints), ints);
4750         cpus_clear(cpu_isolated_map);
4751         for (i = 1; i <= ints[0]; i++)
4752                 if (ints[i] < NR_CPUS)
4753                         cpu_set(ints[i], cpu_isolated_map);
4754         return 1;
4755 }
4756
4757 __setup ("isolcpus=", isolated_cpu_setup);
4758
4759 /*
4760  * init_sched_build_groups takes an array of groups, the cpumask we wish
4761  * to span, and a pointer to a function which identifies what group a CPU
4762  * belongs to. The return value of group_fn must be a valid index into the
4763  * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
4764  * keep track of groups covered with a cpumask_t).
4765  *
4766  * init_sched_build_groups will build a circular linked list of the groups
4767  * covered by the given span, and will set each group's ->cpumask correctly,
4768  * and ->cpu_power to 0.
4769  */
4770 void __devinit init_sched_build_groups(struct sched_group groups[],
4771                         cpumask_t span, int (*group_fn)(int cpu))
4772 {
4773         struct sched_group *first = NULL, *last = NULL;
4774         cpumask_t covered = CPU_MASK_NONE;
4775         int i;
4776
4777         for_each_cpu_mask(i, span) {
4778                 int group = group_fn(i);
4779                 struct sched_group *sg = &groups[group];
4780                 int j;
4781
4782                 if (cpu_isset(i, covered))
4783                         continue;
4784
4785                 sg->cpumask = CPU_MASK_NONE;
4786                 sg->cpu_power = 0;
4787
4788                 for_each_cpu_mask(j, span) {
4789                         if (group_fn(j) != group)
4790                                 continue;
4791
4792                         cpu_set(j, covered);
4793                         cpu_set(j, sg->cpumask);
4794                 }
4795                 if (!first)
4796                         first = sg;
4797                 if (last)
4798                         last->next = sg;
4799                 last = sg;
4800         }
4801         last->next = first;
4802 }
4803
4804
4805 #ifdef ARCH_HAS_SCHED_DOMAIN
4806 extern void __devinit arch_init_sched_domains(void);
4807 extern void __devinit arch_destroy_sched_domains(void);
4808 #else
4809 #ifdef CONFIG_SCHED_SMT
4810 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
4811 static struct sched_group sched_group_cpus[NR_CPUS];
4812 static int __devinit cpu_to_cpu_group(int cpu)
4813 {
4814         return cpu;
4815 }
4816 #endif
4817
4818 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
4819 static struct sched_group sched_group_phys[NR_CPUS];
4820 static int __devinit cpu_to_phys_group(int cpu)
4821 {
4822 #ifdef CONFIG_SCHED_SMT
4823         return first_cpu(cpu_sibling_map[cpu]);
4824 #else
4825         return cpu;
4826 #endif
4827 }
4828
4829 #ifdef CONFIG_NUMA
4830
4831 static DEFINE_PER_CPU(struct sched_domain, node_domains);
4832 static struct sched_group sched_group_nodes[MAX_NUMNODES];
4833 static int __devinit cpu_to_node_group(int cpu)
4834 {
4835         return cpu_to_node(cpu);
4836 }
4837 #endif
4838
4839 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
4840 /*
4841  * The domains setup code relies on siblings not spanning
4842  * multiple nodes. Make sure the architecture has a proper
4843  * siblings map:
4844  */
4845 static void check_sibling_maps(void)
4846 {
4847         int i, j;
4848
4849         for_each_online_cpu(i) {
4850                 for_each_cpu_mask(j, cpu_sibling_map[i]) {
4851                         if (cpu_to_node(i) != cpu_to_node(j)) {
4852                                 printk(KERN_INFO "warning: CPU %d siblings map "
4853                                         "to different node - isolating "
4854                                         "them.\n", i);
4855                                 cpu_sibling_map[i] = cpumask_of_cpu(i);
4856                                 break;
4857                         }
4858                 }
4859         }
4860 }
4861 #endif
4862
4863 /*
4864  * Set up scheduler domains and groups.  Callers must hold the hotplug lock.
4865  */
4866 static void __devinit arch_init_sched_domains(void)
4867 {
4868         int i;
4869         cpumask_t cpu_default_map;
4870
4871 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
4872         check_sibling_maps();
4873 #endif
4874         /*
4875          * Setup mask for cpus without special case scheduling requirements.
4876          * For now this just excludes isolated cpus, but could be used to
4877          * exclude other special cases in the future.
4878          */
4879         cpus_complement(cpu_default_map, cpu_isolated_map);
4880         cpus_and(cpu_default_map, cpu_default_map, cpu_online_map);
4881
4882         /*
4883          * Set up domains. Isolated domains just stay on the dummy domain.
4884          */
4885         for_each_cpu_mask(i, cpu_default_map) {
4886                 int group;
4887                 struct sched_domain *sd = NULL, *p;
4888                 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
4889
4890                 cpus_and(nodemask, nodemask, cpu_default_map);
4891
4892 #ifdef CONFIG_NUMA
4893                 sd = &per_cpu(node_domains, i);
4894                 group = cpu_to_node_group(i);
4895                 *sd = SD_NODE_INIT;
4896                 sd->span = cpu_default_map;
4897                 sd->groups = &sched_group_nodes[group];
4898 #endif
4899
4900                 p = sd;
4901                 sd = &per_cpu(phys_domains, i);
4902                 group = cpu_to_phys_group(i);
4903                 *sd = SD_CPU_INIT;
4904                 sd->span = nodemask;
4905                 sd->parent = p;
4906                 sd->groups = &sched_group_phys[group];
4907
4908 #ifdef CONFIG_SCHED_SMT
4909                 p = sd;
4910                 sd = &per_cpu(cpu_domains, i);
4911                 group = cpu_to_cpu_group(i);
4912                 *sd = SD_SIBLING_INIT;
4913                 sd->span = cpu_sibling_map[i];
4914                 cpus_and(sd->span, sd->span, cpu_default_map);
4915                 sd->parent = p;
4916                 sd->groups = &sched_group_cpus[group];
4917 #endif
4918         }
4919
4920 #ifdef CONFIG_SCHED_SMT
4921         /* Set up CPU (sibling) groups */
4922         for_each_online_cpu(i) {
4923                 cpumask_t this_sibling_map = cpu_sibling_map[i];
4924                 cpus_and(this_sibling_map, this_sibling_map, cpu_default_map);
4925                 if (i != first_cpu(this_sibling_map))
4926                         continue;
4927
4928                 init_sched_build_groups(sched_group_cpus, this_sibling_map,
4929                                                 &cpu_to_cpu_group);
4930         }
4931 #endif
4932
4933         /* Set up physical groups */
4934         for (i = 0; i < MAX_NUMNODES; i++) {
4935                 cpumask_t nodemask = node_to_cpumask(i);
4936
4937                 cpus_and(nodemask, nodemask, cpu_default_map);
4938                 if (cpus_empty(nodemask))
4939                         continue;
4940
4941                 init_sched_build_groups(sched_group_phys, nodemask,
4942                                                 &cpu_to_phys_group);
4943         }
4944
4945 #ifdef CONFIG_NUMA
4946         /* Set up node groups */
4947         init_sched_build_groups(sched_group_nodes, cpu_default_map,
4948                                         &cpu_to_node_group);
4949 #endif
4950
4951         /* Calculate CPU power for physical packages and nodes */
4952         for_each_cpu_mask(i, cpu_default_map) {
4953                 int power;
4954                 struct sched_domain *sd;
4955 #ifdef CONFIG_SCHED_SMT
4956                 sd = &per_cpu(cpu_domains, i);
4957                 power = SCHED_LOAD_SCALE;
4958                 sd->groups->cpu_power = power;
4959 #endif
4960
4961                 sd = &per_cpu(phys_domains, i);
4962                 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
4963                                 (cpus_weight(sd->groups->cpumask)-1) / 10;
4964                 sd->groups->cpu_power = power;
4965
4966 #ifdef CONFIG_NUMA
4967                 if (i == first_cpu(sd->groups->cpumask)) {
4968                         /* Only add "power" once for each physical package. */
4969                         sd = &per_cpu(node_domains, i);
4970                         sd->groups->cpu_power += power;
4971                 }
4972 #endif
4973         }
4974
4975         /* Attach the domains */
4976         for_each_online_cpu(i) {
4977                 struct sched_domain *sd;
4978 #ifdef CONFIG_SCHED_SMT
4979                 sd = &per_cpu(cpu_domains, i);
4980 #else
4981                 sd = &per_cpu(phys_domains, i);
4982 #endif
4983                 cpu_attach_domain(sd, i);
4984         }
4985 }
4986
4987 #ifdef CONFIG_HOTPLUG_CPU
4988 static void __devinit arch_destroy_sched_domains(void)
4989 {
4990         /* Do nothing: everything is statically allocated. */
4991 }
4992 #endif
4993
4994 #endif /* ARCH_HAS_SCHED_DOMAIN */
4995
4996 /*
4997  * Initial dummy domain for early boot and for hotplug cpu. Being static,
4998  * it is initialized to zero, so all balancing flags are cleared which is
4999  * what we want.
5000  */
5001 static struct sched_domain sched_domain_dummy;
5002
5003 #ifdef CONFIG_HOTPLUG_CPU
5004 /*
5005  * Force a reinitialization of the sched domains hierarchy.  The domains
5006  * and groups cannot be updated in place without racing with the balancing
5007  * code, so we temporarily attach all running cpus to a "dummy" domain
5008  * which will prevent rebalancing while the sched domains are recalculated.
5009  */
5010 static int update_sched_domains(struct notifier_block *nfb,
5011                                 unsigned long action, void *hcpu)
5012 {
5013         int i;
5014
5015         switch (action) {
5016         case CPU_UP_PREPARE:
5017         case CPU_DOWN_PREPARE:
5018                 for_each_online_cpu(i)
5019                         cpu_attach_domain(&sched_domain_dummy, i);
5020                 arch_destroy_sched_domains();
5021                 return NOTIFY_OK;
5022
5023         case CPU_UP_CANCELED:
5024         case CPU_DOWN_FAILED:
5025         case CPU_ONLINE:
5026         case CPU_DEAD:
5027                 /*
5028                  * Fall through and re-initialise the domains.
5029                  */
5030                 break;
5031         default:
5032                 return NOTIFY_DONE;
5033         }
5034
5035         /* The hotplug lock is already held by cpu_up/cpu_down */
5036         arch_init_sched_domains();
5037
5038         return NOTIFY_OK;
5039 }
5040 #endif
5041
5042 void __init sched_init_smp(void)
5043 {
5044         lock_cpu_hotplug();
5045         arch_init_sched_domains();
5046         unlock_cpu_hotplug();
5047         /* XXX: Theoretical race here - CPU may be hotplugged now */
5048         hotcpu_notifier(update_sched_domains, 0);
5049 }
5050 #else
5051 void __init sched_init_smp(void)
5052 {
5053 }
5054 #endif /* CONFIG_SMP */
5055
5056 int in_sched_functions(unsigned long addr)
5057 {
5058         /* Linker adds these: start and end of __sched functions */
5059         extern char __sched_text_start[], __sched_text_end[];
5060         return in_lock_functions(addr) ||
5061                 (addr >= (unsigned long)__sched_text_start
5062                 && addr < (unsigned long)__sched_text_end);
5063 }
5064
5065 void __init sched_init(void)
5066 {
5067         runqueue_t *rq;
5068         int i, j, k;
5069
5070         for (i = 0; i < NR_CPUS; i++) {
5071                 prio_array_t *array;
5072
5073                 rq = cpu_rq(i);
5074                 spin_lock_init(&rq->lock);
5075                 rq->active = rq->arrays;
5076                 rq->expired = rq->arrays + 1;
5077                 rq->best_expired_prio = MAX_PRIO;
5078
5079 #ifdef CONFIG_SMP
5080                 rq->sd = &sched_domain_dummy;
5081                 rq->cpu_load = 0;
5082                 rq->active_balance = 0;
5083                 rq->push_cpu = 0;
5084                 rq->migration_thread = NULL;
5085                 INIT_LIST_HEAD(&rq->migration_queue);
5086 #endif
5087                 atomic_set(&rq->nr_iowait, 0);
5088 #ifdef CONFIG_VSERVER_HARDCPU
5089                 INIT_LIST_HEAD(&rq->hold_queue);
5090 #endif
5091
5092                 for (j = 0; j < 2; j++) {
5093                         array = rq->arrays + j;
5094                         for (k = 0; k < MAX_PRIO; k++) {
5095                                 INIT_LIST_HEAD(array->queue + k);
5096                                 __clear_bit(k, array->bitmap);
5097                         }
5098                         // delimiter for bitsearch
5099                         __set_bit(MAX_PRIO, array->bitmap);
5100                 }
5101         }
5102
5103         /*
5104          * The boot idle thread does lazy MMU switching as well:
5105          */
5106         atomic_inc(&init_mm.mm_count);
5107         enter_lazy_tlb(&init_mm, current);
5108
5109         /*
5110          * Make us the idle thread. Technically, schedule() should not be
5111          * called from this thread, however somewhere below it might be,
5112          * but because we are the idle thread, we just pick up running again
5113          * when this runqueue becomes "idle".
5114          */
5115         init_idle(current, smp_processor_id());
5116 }
5117
5118 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5119 void __might_sleep(char *file, int line)
5120 {
5121 #if defined(in_atomic)
5122         static unsigned long prev_jiffy;        /* ratelimiting */
5123
5124         if ((in_atomic() || irqs_disabled()) &&
5125             system_state == SYSTEM_RUNNING && !oops_in_progress) {
5126                 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
5127                         return;
5128                 prev_jiffy = jiffies;
5129                 printk(KERN_ERR "Debug: sleeping function called from invalid"
5130                                 " context at %s:%d\n", file, line);
5131                 printk("in_atomic():%d, irqs_disabled():%d\n",
5132                         in_atomic(), irqs_disabled());
5133                 dump_stack();
5134         }
5135 #endif
5136 }
5137 EXPORT_SYMBOL(__might_sleep);
5138 #endif
5139
5140 #ifdef CONFIG_MAGIC_SYSRQ
5141 void normalize_rt_tasks(void)
5142 {
5143         struct task_struct *p;
5144         prio_array_t *array;
5145         unsigned long flags;
5146         runqueue_t *rq;
5147
5148         read_lock_irq(&tasklist_lock);
5149         for_each_process (p) {
5150                 if (!rt_task(p))
5151                         continue;
5152
5153                 rq = task_rq_lock(p, &flags);
5154
5155                 array = p->array;
5156                 if (array)
5157                         deactivate_task(p, task_rq(p));
5158                 __setscheduler(p, SCHED_NORMAL, 0);
5159                 if (array) {
5160                         vx_activate_task(p);
5161                         __activate_task(p, task_rq(p));
5162                         resched_task(rq->curr);
5163                 }
5164
5165                 task_rq_unlock(rq, &flags);
5166         }
5167         read_unlock_irq(&tasklist_lock);
5168 }
5169
5170 #endif /* CONFIG_MAGIC_SYSRQ */