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