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