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