Revert to Fedora kernel-2.6.17-1.2187_FC5 patched with vs2.0.2.1; there are too many...
[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/capability.h>
31 #include <linux/completion.h>
32 #include <linux/kernel_stat.h>
33 #include <linux/security.h>
34 #include <linux/notifier.h>
35 #include <linux/profile.h>
36 #include <linux/suspend.h>
37 #include <linux/vmalloc.h>
38 #include <linux/blkdev.h>
39 #include <linux/delay.h>
40 #include <linux/smp.h>
41 #include <linux/threads.h>
42 #include <linux/timer.h>
43 #include <linux/rcupdate.h>
44 #include <linux/cpu.h>
45 #include <linux/cpuset.h>
46 #include <linux/percpu.h>
47 #include <linux/kthread.h>
48 #include <linux/seq_file.h>
49 #include <linux/syscalls.h>
50 #include <linux/times.h>
51 #include <linux/acct.h>
52 #include <linux/kprobes.h>
53
54 #include <asm/tlb.h>
55 #include <asm/unistd.h>
56
57 #include <linux/vs_context.h>
58 #include <linux/vs_cvirt.h>
59 #include <linux/vs_sched.h>
60
61 /*
62  * Convert user-nice values [ -20 ... 0 ... 19 ]
63  * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
64  * and back.
65  */
66 #define NICE_TO_PRIO(nice)      (MAX_RT_PRIO + (nice) + 20)
67 #define PRIO_TO_NICE(prio)      ((prio) - MAX_RT_PRIO - 20)
68 #define TASK_NICE(p)            PRIO_TO_NICE((p)->static_prio)
69
70 /*
71  * 'User priority' is the nice value converted to something we
72  * can work with better when scaling various scheduler parameters,
73  * it's a [ 0 ... 39 ] range.
74  */
75 #define USER_PRIO(p)            ((p)-MAX_RT_PRIO)
76 #define TASK_USER_PRIO(p)       USER_PRIO((p)->static_prio)
77 #define MAX_USER_PRIO           (USER_PRIO(MAX_PRIO))
78
79 /*
80  * Some helpers for converting nanosecond timing to jiffy resolution
81  */
82 #define NS_TO_JIFFIES(TIME)     ((TIME) / (1000000000 / HZ))
83 #define JIFFIES_TO_NS(TIME)     ((TIME) * (1000000000 / HZ))
84
85 /*
86  * These are the 'tuning knobs' of the scheduler:
87  *
88  * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
89  * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
90  * Timeslices get refilled after they expire.
91  */
92 #define MIN_TIMESLICE           max(5 * HZ / 1000, 1)
93 #define DEF_TIMESLICE           (100 * HZ / 1000)
94 #define ON_RUNQUEUE_WEIGHT       30
95 #define CHILD_PENALTY            95
96 #define PARENT_PENALTY          100
97 #define EXIT_WEIGHT               3
98 #define PRIO_BONUS_RATIO         25
99 #define MAX_BONUS               (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
100 #define INTERACTIVE_DELTA         2
101 #define MAX_SLEEP_AVG           (DEF_TIMESLICE * MAX_BONUS)
102 #define STARVATION_LIMIT        (MAX_SLEEP_AVG)
103 #define NS_MAX_SLEEP_AVG        (JIFFIES_TO_NS(MAX_SLEEP_AVG))
104
105 /*
106  * If a task is 'interactive' then we reinsert it in the active
107  * array after it has expired its current timeslice. (it will not
108  * continue to run immediately, it will still roundrobin with
109  * other interactive tasks.)
110  *
111  * This part scales the interactivity limit depending on niceness.
112  *
113  * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
114  * Here are a few examples of different nice levels:
115  *
116  *  TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
117  *  TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
118  *  TASK_INTERACTIVE(  0): [1,1,1,1,0,0,0,0,0,0,0]
119  *  TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
120  *  TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
121  *
122  * (the X axis represents the possible -5 ... 0 ... +5 dynamic
123  *  priority range a task can explore, a value of '1' means the
124  *  task is rated interactive.)
125  *
126  * Ie. nice +19 tasks can never get 'interactive' enough to be
127  * reinserted into the active array. And only heavily CPU-hog nice -20
128  * tasks will be expired. Default nice 0 tasks are somewhere between,
129  * it takes some effort for them to get interactive, but it's not
130  * too hard.
131  */
132
133 #define CURRENT_BONUS(p) \
134         (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
135                 MAX_SLEEP_AVG)
136
137 #define GRANULARITY     (10 * HZ / 1000 ? : 1)
138
139 #ifdef CONFIG_SMP
140 #define TIMESLICE_GRANULARITY(p)        (GRANULARITY * \
141                 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
142                         num_online_cpus())
143 #else
144 #define TIMESLICE_GRANULARITY(p)        (GRANULARITY * \
145                 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
146 #endif
147
148 #define SCALE(v1,v1_max,v2_max) \
149         (v1) * (v2_max) / (v1_max)
150
151 #define DELTA(p) \
152         (SCALE(TASK_NICE(p) + 20, 40, MAX_BONUS) - 20 * MAX_BONUS / 40 + \
153                 INTERACTIVE_DELTA)
154
155 #define TASK_INTERACTIVE(p) \
156         ((p)->prio <= (p)->static_prio - DELTA(p))
157
158 #define INTERACTIVE_SLEEP(p) \
159         (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
160                 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
161
162 #define TASK_PREEMPTS_CURR(p, rq) \
163         ((p)->prio < (rq)->curr->prio)
164
165 /*
166  * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
167  * to time slice values: [800ms ... 100ms ... 5ms]
168  *
169  * The higher a thread's priority, the bigger timeslices
170  * it gets during one round of execution. But even the lowest
171  * priority thread gets MIN_TIMESLICE worth of execution time.
172  */
173
174 #define SCALE_PRIO(x, prio) \
175         max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO/2), MIN_TIMESLICE)
176
177 static unsigned int task_timeslice(task_t *p)
178 {
179         if (p->static_prio < NICE_TO_PRIO(0))
180                 return SCALE_PRIO(DEF_TIMESLICE*4, p->static_prio);
181         else
182                 return SCALE_PRIO(DEF_TIMESLICE, p->static_prio);
183 }
184 #define task_hot(p, now, sd) ((long long) ((now) - (p)->last_ran)       \
185                                 < (long long) (sd)->cache_hot_time)
186
187 /*
188  * These are the runqueue data structures:
189  */
190
191 #define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
192
193 typedef struct runqueue runqueue_t;
194
195 struct prio_array {
196         unsigned int nr_active;
197         unsigned long bitmap[BITMAP_SIZE];
198         struct list_head queue[MAX_PRIO];
199 };
200
201 /*
202  * This is the main, per-CPU runqueue data structure.
203  *
204  * Locking rule: those places that want to lock multiple runqueues
205  * (such as the load balancing or the thread migration code), lock
206  * acquire operations must be ordered by ascending &runqueue.
207  */
208 struct runqueue {
209         spinlock_t lock;
210
211         /*
212          * nr_running and cpu_load should be in the same cacheline because
213          * remote CPUs use both these fields when doing load calculation.
214          */
215         unsigned long nr_running;
216 #ifdef CONFIG_SMP
217         unsigned long cpu_load[3];
218 #endif
219         unsigned long long nr_switches;
220
221         /*
222          * This is part of a global counter where only the total sum
223          * over all CPUs matters. A task can increase this counter on
224          * one CPU and if it got migrated afterwards it may decrease
225          * it on another CPU. Always updated under the runqueue lock:
226          */
227         unsigned long nr_uninterruptible;
228
229         unsigned long expired_timestamp;
230         unsigned long long timestamp_last_tick;
231         task_t *curr, *idle;
232         struct mm_struct *prev_mm;
233         prio_array_t *active, *expired, arrays[2];
234         int best_expired_prio;
235         atomic_t nr_iowait;
236
237 #ifdef CONFIG_SMP
238         struct sched_domain *sd;
239
240         /* For active balancing */
241         int active_balance;
242         int push_cpu;
243
244         task_t *migration_thread;
245         struct list_head migration_queue;
246         int cpu;
247 #endif
248 #ifdef CONFIG_VSERVER_HARDCPU
249         struct list_head hold_queue;
250         int idle_tokens;
251 #endif
252
253 #ifdef CONFIG_SCHEDSTATS
254         /* latency stats */
255         struct sched_info rq_sched_info;
256
257         /* sys_sched_yield() stats */
258         unsigned long yld_exp_empty;
259         unsigned long yld_act_empty;
260         unsigned long yld_both_empty;
261         unsigned long yld_cnt;
262
263         /* schedule() stats */
264         unsigned long sched_switch;
265         unsigned long sched_cnt;
266         unsigned long sched_goidle;
267
268         /* try_to_wake_up() stats */
269         unsigned long ttwu_cnt;
270         unsigned long ttwu_local;
271 #endif
272 };
273
274 static DEFINE_PER_CPU(struct runqueue, runqueues);
275
276 /*
277  * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
278  * See detach_destroy_domains: synchronize_sched for details.
279  *
280  * The domain tree of any CPU may only be accessed from within
281  * preempt-disabled sections.
282  */
283 #define for_each_domain(cpu, domain) \
284 for (domain = rcu_dereference(cpu_rq(cpu)->sd); domain; domain = domain->parent)
285
286 #define cpu_rq(cpu)             (&per_cpu(runqueues, (cpu)))
287 #define this_rq()               (&__get_cpu_var(runqueues))
288 #define task_rq(p)              cpu_rq(task_cpu(p))
289 #define cpu_curr(cpu)           (cpu_rq(cpu)->curr)
290
291 #ifndef prepare_arch_switch
292 # define prepare_arch_switch(next)      do { } while (0)
293 #endif
294 #ifndef finish_arch_switch
295 # define finish_arch_switch(prev)       do { } while (0)
296 #endif
297
298 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
299 static inline int task_running(runqueue_t *rq, task_t *p)
300 {
301         return rq->curr == p;
302 }
303
304 static inline void prepare_lock_switch(runqueue_t *rq, task_t *next)
305 {
306 }
307
308 static inline void finish_lock_switch(runqueue_t *rq, task_t *prev)
309 {
310 #ifdef CONFIG_DEBUG_SPINLOCK
311         /* this is a valid case when another task releases the spinlock */
312         rq->lock.owner = current;
313 #endif
314         spin_unlock_irq(&rq->lock);
315 }
316
317 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
318 static inline int task_running(runqueue_t *rq, task_t *p)
319 {
320 #ifdef CONFIG_SMP
321         return p->oncpu;
322 #else
323         return rq->curr == p;
324 #endif
325 }
326
327 static inline void prepare_lock_switch(runqueue_t *rq, task_t *next)
328 {
329 #ifdef CONFIG_SMP
330         /*
331          * We can optimise this out completely for !SMP, because the
332          * SMP rebalancing from interrupt is the only thing that cares
333          * here.
334          */
335         next->oncpu = 1;
336 #endif
337 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
338         spin_unlock_irq(&rq->lock);
339 #else
340         spin_unlock(&rq->lock);
341 #endif
342 }
343
344 static inline void finish_lock_switch(runqueue_t *rq, task_t *prev)
345 {
346 #ifdef CONFIG_SMP
347         /*
348          * After ->oncpu is cleared, the task can be moved to a different CPU.
349          * We must ensure this doesn't happen until the switch is completely
350          * finished.
351          */
352         smp_wmb();
353         prev->oncpu = 0;
354 #endif
355 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
356         local_irq_enable();
357 #endif
358 }
359 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
360
361 /*
362  * task_rq_lock - lock the runqueue a given task resides on and disable
363  * interrupts.  Note the ordering: we can safely lookup the task_rq without
364  * explicitly disabling preemption.
365  */
366 static inline runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
367         __acquires(rq->lock)
368 {
369         struct runqueue *rq;
370
371 repeat_lock_task:
372         local_irq_save(*flags);
373         rq = task_rq(p);
374         spin_lock(&rq->lock);
375         if (unlikely(rq != task_rq(p))) {
376                 spin_unlock_irqrestore(&rq->lock, *flags);
377                 goto repeat_lock_task;
378         }
379         return rq;
380 }
381
382 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
383         __releases(rq->lock)
384 {
385         spin_unlock_irqrestore(&rq->lock, *flags);
386 }
387
388 #ifdef CONFIG_SCHEDSTATS
389 /*
390  * bump this up when changing the output format or the meaning of an existing
391  * format, so that tools can adapt (or abort)
392  */
393 #define SCHEDSTAT_VERSION 12
394
395 static int show_schedstat(struct seq_file *seq, void *v)
396 {
397         int cpu;
398
399         seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
400         seq_printf(seq, "timestamp %lu\n", jiffies);
401         for_each_online_cpu(cpu) {
402                 runqueue_t *rq = cpu_rq(cpu);
403 #ifdef CONFIG_SMP
404                 struct sched_domain *sd;
405                 int dcnt = 0;
406 #endif
407
408                 /* runqueue-specific stats */
409                 seq_printf(seq,
410                     "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
411                     cpu, rq->yld_both_empty,
412                     rq->yld_act_empty, rq->yld_exp_empty, rq->yld_cnt,
413                     rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
414                     rq->ttwu_cnt, rq->ttwu_local,
415                     rq->rq_sched_info.cpu_time,
416                     rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
417
418                 seq_printf(seq, "\n");
419
420 #ifdef CONFIG_SMP
421                 /* domain-specific stats */
422                 preempt_disable();
423                 for_each_domain(cpu, sd) {
424                         enum idle_type itype;
425                         char mask_str[NR_CPUS];
426
427                         cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
428                         seq_printf(seq, "domain%d %s", dcnt++, mask_str);
429                         for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
430                                         itype++) {
431                                 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu",
432                                     sd->lb_cnt[itype],
433                                     sd->lb_balanced[itype],
434                                     sd->lb_failed[itype],
435                                     sd->lb_imbalance[itype],
436                                     sd->lb_gained[itype],
437                                     sd->lb_hot_gained[itype],
438                                     sd->lb_nobusyq[itype],
439                                     sd->lb_nobusyg[itype]);
440                         }
441                         seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
442                             sd->alb_cnt, sd->alb_failed, sd->alb_pushed,
443                             sd->sbe_cnt, sd->sbe_balanced, sd->sbe_pushed,
444                             sd->sbf_cnt, sd->sbf_balanced, sd->sbf_pushed,
445                             sd->ttwu_wake_remote, sd->ttwu_move_affine, sd->ttwu_move_balance);
446                 }
447                 preempt_enable();
448 #endif
449         }
450         return 0;
451 }
452
453 static int schedstat_open(struct inode *inode, struct file *file)
454 {
455         unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
456         char *buf = kmalloc(size, GFP_KERNEL);
457         struct seq_file *m;
458         int res;
459
460         if (!buf)
461                 return -ENOMEM;
462         res = single_open(file, show_schedstat, NULL);
463         if (!res) {
464                 m = file->private_data;
465                 m->buf = buf;
466                 m->size = size;
467         } else
468                 kfree(buf);
469         return res;
470 }
471
472 struct file_operations proc_schedstat_operations = {
473         .open    = schedstat_open,
474         .read    = seq_read,
475         .llseek  = seq_lseek,
476         .release = single_release,
477 };
478
479 # define schedstat_inc(rq, field)       do { (rq)->field++; } while (0)
480 # define schedstat_add(rq, field, amt)  do { (rq)->field += (amt); } while (0)
481 #else /* !CONFIG_SCHEDSTATS */
482 # define schedstat_inc(rq, field)       do { } while (0)
483 # define schedstat_add(rq, field, amt)  do { } while (0)
484 #endif
485
486 /*
487  * rq_lock - lock a given runqueue and disable interrupts.
488  */
489 static inline runqueue_t *this_rq_lock(void)
490         __acquires(rq->lock)
491 {
492         runqueue_t *rq;
493
494         local_irq_disable();
495         rq = this_rq();
496         spin_lock(&rq->lock);
497
498         return rq;
499 }
500
501 #ifdef CONFIG_SCHEDSTATS
502 /*
503  * Called when a process is dequeued from the active array and given
504  * the cpu.  We should note that with the exception of interactive
505  * tasks, the expired queue will become the active queue after the active
506  * queue is empty, without explicitly dequeuing and requeuing tasks in the
507  * expired queue.  (Interactive tasks may be requeued directly to the
508  * active queue, thus delaying tasks in the expired queue from running;
509  * see scheduler_tick()).
510  *
511  * This function is only called from sched_info_arrive(), rather than
512  * dequeue_task(). Even though a task may be queued and dequeued multiple
513  * times as it is shuffled about, we're really interested in knowing how
514  * long it was from the *first* time it was queued to the time that it
515  * finally hit a cpu.
516  */
517 static inline void sched_info_dequeued(task_t *t)
518 {
519         t->sched_info.last_queued = 0;
520 }
521
522 /*
523  * Called when a task finally hits the cpu.  We can now calculate how
524  * long it was waiting to run.  We also note when it began so that we
525  * can keep stats on how long its timeslice is.
526  */
527 static void sched_info_arrive(task_t *t)
528 {
529         unsigned long now = jiffies, diff = 0;
530         struct runqueue *rq = task_rq(t);
531
532         if (t->sched_info.last_queued)
533                 diff = now - t->sched_info.last_queued;
534         sched_info_dequeued(t);
535         t->sched_info.run_delay += diff;
536         t->sched_info.last_arrival = now;
537         t->sched_info.pcnt++;
538
539         if (!rq)
540                 return;
541
542         rq->rq_sched_info.run_delay += diff;
543         rq->rq_sched_info.pcnt++;
544 }
545
546 /*
547  * Called when a process is queued into either the active or expired
548  * array.  The time is noted and later used to determine how long we
549  * had to wait for us to reach the cpu.  Since the expired queue will
550  * become the active queue after active queue is empty, without dequeuing
551  * and requeuing any tasks, we are interested in queuing to either. It
552  * is unusual but not impossible for tasks to be dequeued and immediately
553  * requeued in the same or another array: this can happen in sched_yield(),
554  * set_user_nice(), and even load_balance() as it moves tasks from runqueue
555  * to runqueue.
556  *
557  * This function is only called from enqueue_task(), but also only updates
558  * the timestamp if it is already not set.  It's assumed that
559  * sched_info_dequeued() will clear that stamp when appropriate.
560  */
561 static inline void sched_info_queued(task_t *t)
562 {
563         if (!t->sched_info.last_queued)
564                 t->sched_info.last_queued = jiffies;
565 }
566
567 /*
568  * Called when a process ceases being the active-running process, either
569  * voluntarily or involuntarily.  Now we can calculate how long we ran.
570  */
571 static inline void sched_info_depart(task_t *t)
572 {
573         struct runqueue *rq = task_rq(t);
574         unsigned long diff = jiffies - t->sched_info.last_arrival;
575
576         t->sched_info.cpu_time += diff;
577
578         if (rq)
579                 rq->rq_sched_info.cpu_time += diff;
580 }
581
582 /*
583  * Called when tasks are switched involuntarily due, typically, to expiring
584  * their time slice.  (This may also be called when switching to or from
585  * the idle task.)  We are only called when prev != next.
586  */
587 static inline void sched_info_switch(task_t *prev, task_t *next)
588 {
589         struct runqueue *rq = task_rq(prev);
590
591         /*
592          * prev now departs the cpu.  It's not interesting to record
593          * stats about how efficient we were at scheduling the idle
594          * process, however.
595          */
596         if (prev != rq->idle)
597                 sched_info_depart(prev);
598
599         if (next != rq->idle)
600                 sched_info_arrive(next);
601 }
602 #else
603 #define sched_info_queued(t)            do { } while (0)
604 #define sched_info_switch(t, next)      do { } while (0)
605 #endif /* CONFIG_SCHEDSTATS */
606
607 /*
608  * Adding/removing a task to/from a priority array:
609  */
610 static void dequeue_task(struct task_struct *p, prio_array_t *array)
611 {
612         BUG_ON(p->state & TASK_ONHOLD);
613         array->nr_active--;
614         list_del(&p->run_list);
615         if (list_empty(array->queue + p->prio))
616                 __clear_bit(p->prio, array->bitmap);
617 }
618
619 static void enqueue_task(struct task_struct *p, prio_array_t *array)
620 {
621         BUG_ON(p->state & TASK_ONHOLD);
622         sched_info_queued(p);
623         list_add_tail(&p->run_list, array->queue + p->prio);
624         __set_bit(p->prio, array->bitmap);
625         array->nr_active++;
626         p->array = array;
627 }
628
629 /*
630  * Put task to the end of the run list without the overhead of dequeue
631  * followed by enqueue.
632  */
633 static void requeue_task(struct task_struct *p, prio_array_t *array)
634 {
635         BUG_ON(p->state & TASK_ONHOLD);
636         list_move_tail(&p->run_list, array->queue + p->prio);
637 }
638
639 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
640 {
641         BUG_ON(p->state & TASK_ONHOLD);
642         list_add(&p->run_list, array->queue + p->prio);
643         __set_bit(p->prio, array->bitmap);
644         array->nr_active++;
645         p->array = array;
646 }
647
648 /*
649  * effective_prio - return the priority that is based on the static
650  * priority but is modified by bonuses/penalties.
651  *
652  * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
653  * into the -5 ... 0 ... +5 bonus/penalty range.
654  *
655  * We use 25% of the full 0...39 priority range so that:
656  *
657  * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
658  * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
659  *
660  * Both properties are important to certain workloads.
661  */
662 static int effective_prio(task_t *p)
663 {
664         int bonus, prio;
665         struct vx_info *vxi;
666
667         if (rt_task(p))
668                 return p->prio;
669
670         bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
671
672         prio = p->static_prio - bonus;
673
674         if ((vxi = p->vx_info) &&
675                 vx_info_flags(vxi, VXF_SCHED_PRIO, 0))
676                 prio += vx_effective_vavavoom(vxi, MAX_USER_PRIO);
677
678         if (prio < MAX_RT_PRIO)
679                 prio = MAX_RT_PRIO;
680         if (prio > MAX_PRIO-1)
681                 prio = MAX_PRIO-1;
682         return prio;
683 }
684
685 /*
686  * __activate_task - move a task to the runqueue.
687  */
688 static void __activate_task(task_t *p, runqueue_t *rq)
689 {
690         prio_array_t *target = rq->active;
691
692         if (batch_task(p))
693                 target = rq->expired;
694         enqueue_task(p, target);
695         rq->nr_running++;
696 }
697
698 /*
699  * __activate_idle_task - move idle task to the _front_ of runqueue.
700  */
701 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
702 {
703         enqueue_task_head(p, rq->active);
704         rq->nr_running++;
705 }
706
707 static int recalc_task_prio(task_t *p, unsigned long long now)
708 {
709         /* Caller must always ensure 'now >= p->timestamp' */
710         unsigned long long __sleep_time = now - p->timestamp;
711         unsigned long sleep_time;
712
713         if (batch_task(p))
714                 sleep_time = 0;
715         else {
716                 if (__sleep_time > NS_MAX_SLEEP_AVG)
717                         sleep_time = NS_MAX_SLEEP_AVG;
718                 else
719                         sleep_time = (unsigned long)__sleep_time;
720         }
721
722         if (likely(sleep_time > 0)) {
723                 /*
724                  * User tasks that sleep a long time are categorised as
725                  * idle. They will only have their sleep_avg increased to a
726                  * level that makes them just interactive priority to stay
727                  * active yet prevent them suddenly becoming cpu hogs and
728                  * starving other processes.
729                  */
730                 if (p->mm && sleep_time > INTERACTIVE_SLEEP(p)) {
731                                 unsigned long ceiling;
732
733                                 ceiling = JIFFIES_TO_NS(MAX_SLEEP_AVG -
734                                         DEF_TIMESLICE);
735                                 if (p->sleep_avg < ceiling)
736                                         p->sleep_avg = ceiling;
737                 } else {
738                         /*
739                          * Tasks waking from uninterruptible sleep are
740                          * limited in their sleep_avg rise as they
741                          * are likely to be waiting on I/O
742                          */
743                         if (p->sleep_type == SLEEP_NONINTERACTIVE && p->mm) {
744                                 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
745                                         sleep_time = 0;
746                                 else if (p->sleep_avg + sleep_time >=
747                                                 INTERACTIVE_SLEEP(p)) {
748                                         p->sleep_avg = INTERACTIVE_SLEEP(p);
749                                         sleep_time = 0;
750                                 }
751                         }
752
753                         /*
754                          * This code gives a bonus to interactive tasks.
755                          *
756                          * The boost works by updating the 'average sleep time'
757                          * value here, based on ->timestamp. The more time a
758                          * task spends sleeping, the higher the average gets -
759                          * and the higher the priority boost gets as well.
760                          */
761                         p->sleep_avg += sleep_time;
762
763                         if (p->sleep_avg > NS_MAX_SLEEP_AVG)
764                                 p->sleep_avg = NS_MAX_SLEEP_AVG;
765                 }
766         }
767
768         return effective_prio(p);
769 }
770
771 /*
772  * activate_task - move a task to the runqueue and do priority recalculation
773  *
774  * Update all the scheduling statistics stuff. (sleep average
775  * calculation, priority modifiers, etc.)
776  */
777 static void activate_task(task_t *p, runqueue_t *rq, int local)
778 {
779         unsigned long long now;
780
781         now = sched_clock();
782 #ifdef CONFIG_SMP
783         if (!local) {
784                 /* Compensate for drifting sched_clock */
785                 runqueue_t *this_rq = this_rq();
786                 now = (now - this_rq->timestamp_last_tick)
787                         + rq->timestamp_last_tick;
788         }
789 #endif
790
791         if (!rt_task(p))
792                 p->prio = recalc_task_prio(p, now);
793
794         /*
795          * This checks to make sure it's not an uninterruptible task
796          * that is now waking up.
797          */
798         if (p->sleep_type == SLEEP_NORMAL) {
799                 /*
800                  * Tasks which were woken up by interrupts (ie. hw events)
801                  * are most likely of interactive nature. So we give them
802                  * the credit of extending their sleep time to the period
803                  * of time they spend on the runqueue, waiting for execution
804                  * on a CPU, first time around:
805                  */
806                 if (in_interrupt())
807                         p->sleep_type = SLEEP_INTERRUPTED;
808                 else {
809                         /*
810                          * Normal first-time wakeups get a credit too for
811                          * on-runqueue time, but it will be weighted down:
812                          */
813                         p->sleep_type = SLEEP_INTERACTIVE;
814                 }
815         }
816         p->timestamp = now;
817
818         vx_activate_task(p);
819         __activate_task(p, rq);
820 }
821
822 /*
823  * deactivate_task - remove a task from the runqueue.
824  */
825 static void __deactivate_task(struct task_struct *p, runqueue_t *rq)
826 {
827         rq->nr_running--;
828         dequeue_task(p, p->array);
829         p->array = NULL;
830 }
831
832 static inline
833 void deactivate_task(struct task_struct *p, runqueue_t *rq)
834 {
835         vx_deactivate_task(p);
836         __deactivate_task(p, rq);
837 }
838
839
840 #ifdef  CONFIG_VSERVER_HARDCPU
841 /*
842  * vx_hold_task - put a task on the hold queue
843  */
844 static inline
845 void vx_hold_task(struct vx_info *vxi,
846         struct task_struct *p, runqueue_t *rq)
847 {
848         __deactivate_task(p, rq);
849         p->state |= TASK_ONHOLD;
850         /* a new one on hold */
851         vx_onhold_inc(vxi);
852         list_add_tail(&p->run_list, &rq->hold_queue);
853 }
854
855 /*
856  * vx_unhold_task - put a task back to the runqueue
857  */
858 static inline
859 void vx_unhold_task(struct vx_info *vxi,
860         struct task_struct *p, runqueue_t *rq)
861 {
862         list_del(&p->run_list);
863         /* one less waiting */
864         vx_onhold_dec(vxi);
865         p->state &= ~TASK_ONHOLD;
866         enqueue_task(p, rq->expired);
867         rq->nr_running++;
868
869         if (p->static_prio < rq->best_expired_prio)
870                 rq->best_expired_prio = p->static_prio;
871 }
872 #else
873 static inline
874 void vx_hold_task(struct vx_info *vxi,
875         struct task_struct *p, runqueue_t *rq)
876 {
877         return;
878 }
879
880 static inline
881 void vx_unhold_task(struct vx_info *vxi,
882         struct task_struct *p, runqueue_t *rq)
883 {
884         return;
885 }
886 #endif /* CONFIG_VSERVER_HARDCPU */
887
888
889 /*
890  * resched_task - mark a task 'to be rescheduled now'.
891  *
892  * On UP this means the setting of the need_resched flag, on SMP it
893  * might also involve a cross-CPU call to trigger the scheduler on
894  * the target CPU.
895  */
896 #ifdef CONFIG_SMP
897 static void resched_task(task_t *p)
898 {
899         int cpu;
900
901         assert_spin_locked(&task_rq(p)->lock);
902
903         if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
904                 return;
905
906         set_tsk_thread_flag(p, TIF_NEED_RESCHED);
907
908         cpu = task_cpu(p);
909         if (cpu == smp_processor_id())
910                 return;
911
912         /* NEED_RESCHED must be visible before we test POLLING_NRFLAG */
913         smp_mb();
914         if (!test_tsk_thread_flag(p, TIF_POLLING_NRFLAG))
915                 smp_send_reschedule(cpu);
916 }
917 #else
918 static inline void resched_task(task_t *p)
919 {
920         assert_spin_locked(&task_rq(p)->lock);
921         set_tsk_need_resched(p);
922 }
923 #endif
924
925 /**
926  * task_curr - is this task currently executing on a CPU?
927  * @p: the task in question.
928  */
929 inline int task_curr(const task_t *p)
930 {
931         return cpu_curr(task_cpu(p)) == p;
932 }
933
934 #ifdef CONFIG_SMP
935 typedef struct {
936         struct list_head list;
937
938         task_t *task;
939         int dest_cpu;
940
941         struct completion done;
942 } migration_req_t;
943
944 /*
945  * The task's runqueue lock must be held.
946  * Returns true if you have to wait for migration thread.
947  */
948 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
949 {
950         runqueue_t *rq = task_rq(p);
951
952         /*
953          * If the task is not on a runqueue (and not running), then
954          * it is sufficient to simply update the task's cpu field.
955          */
956         if (!p->array && !task_running(rq, p)) {
957                 set_task_cpu(p, dest_cpu);
958                 return 0;
959         }
960
961         init_completion(&req->done);
962         req->task = p;
963         req->dest_cpu = dest_cpu;
964         list_add(&req->list, &rq->migration_queue);
965         return 1;
966 }
967
968 /*
969  * wait_task_inactive - wait for a thread to unschedule.
970  *
971  * The caller must ensure that the task *will* unschedule sometime soon,
972  * else this function might spin for a *long* time. This function can't
973  * be called with interrupts off, or it may introduce deadlock with
974  * smp_call_function() if an IPI is sent by the same process we are
975  * waiting to become inactive.
976  */
977 void wait_task_inactive(task_t *p)
978 {
979         unsigned long flags;
980         runqueue_t *rq;
981         int preempted;
982
983 repeat:
984         rq = task_rq_lock(p, &flags);
985         /* Must be off runqueue entirely, not preempted. */
986         if (unlikely(p->array || task_running(rq, p))) {
987                 /* If it's preempted, we yield.  It could be a while. */
988                 preempted = !task_running(rq, p);
989                 task_rq_unlock(rq, &flags);
990                 cpu_relax();
991                 if (preempted)
992                         yield();
993                 goto repeat;
994         }
995         task_rq_unlock(rq, &flags);
996 }
997
998 /***
999  * kick_process - kick a running thread to enter/exit the kernel
1000  * @p: the to-be-kicked thread
1001  *
1002  * Cause a process which is running on another CPU to enter
1003  * kernel-mode, without any delay. (to get signals handled.)
1004  *
1005  * NOTE: this function doesnt have to take the runqueue lock,
1006  * because all it wants to ensure is that the remote task enters
1007  * the kernel. If the IPI races and the task has been migrated
1008  * to another CPU then no harm is done and the purpose has been
1009  * achieved as well.
1010  */
1011 void kick_process(task_t *p)
1012 {
1013         int cpu;
1014
1015         preempt_disable();
1016         cpu = task_cpu(p);
1017         if ((cpu != smp_processor_id()) && task_curr(p))
1018                 smp_send_reschedule(cpu);
1019         preempt_enable();
1020 }
1021
1022 /*
1023  * Return a low guess at the load of a migration-source cpu.
1024  *
1025  * We want to under-estimate the load of migration sources, to
1026  * balance conservatively.
1027  */
1028 static inline unsigned long source_load(int cpu, int type)
1029 {
1030         runqueue_t *rq = cpu_rq(cpu);
1031         unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
1032         if (type == 0)
1033                 return load_now;
1034
1035         return min(rq->cpu_load[type-1], load_now);
1036 }
1037
1038 /*
1039  * Return a high guess at the load of a migration-target cpu
1040  */
1041 static inline unsigned long target_load(int cpu, int type)
1042 {
1043         runqueue_t *rq = cpu_rq(cpu);
1044         unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
1045         if (type == 0)
1046                 return load_now;
1047
1048         return max(rq->cpu_load[type-1], load_now);
1049 }
1050
1051 /*
1052  * find_idlest_group finds and returns the least busy CPU group within the
1053  * domain.
1054  */
1055 static struct sched_group *
1056 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1057 {
1058         struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1059         unsigned long min_load = ULONG_MAX, this_load = 0;
1060         int load_idx = sd->forkexec_idx;
1061         int imbalance = 100 + (sd->imbalance_pct-100)/2;
1062
1063         do {
1064                 unsigned long load, avg_load;
1065                 int local_group;
1066                 int i;
1067
1068                 /* Skip over this group if it has no CPUs allowed */
1069                 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
1070                         goto nextgroup;
1071
1072                 local_group = cpu_isset(this_cpu, group->cpumask);
1073
1074                 /* Tally up the load of all CPUs in the group */
1075                 avg_load = 0;
1076
1077                 for_each_cpu_mask(i, group->cpumask) {
1078                         /* Bias balancing toward cpus of our domain */
1079                         if (local_group)
1080                                 load = source_load(i, load_idx);
1081                         else
1082                                 load = target_load(i, load_idx);
1083
1084                         avg_load += load;
1085                 }
1086
1087                 /* Adjust by relative CPU power of the group */
1088                 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1089
1090                 if (local_group) {
1091                         this_load = avg_load;
1092                         this = group;
1093                 } else if (avg_load < min_load) {
1094                         min_load = avg_load;
1095                         idlest = group;
1096                 }
1097 nextgroup:
1098                 group = group->next;
1099         } while (group != sd->groups);
1100
1101         if (!idlest || 100*this_load < imbalance*min_load)
1102                 return NULL;
1103         return idlest;
1104 }
1105
1106 /*
1107  * find_idlest_queue - find the idlest runqueue among the cpus in group.
1108  */
1109 static int
1110 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
1111 {
1112         cpumask_t tmp;
1113         unsigned long load, min_load = ULONG_MAX;
1114         int idlest = -1;
1115         int i;
1116
1117         /* Traverse only the allowed CPUs */
1118         cpus_and(tmp, group->cpumask, p->cpus_allowed);
1119
1120         for_each_cpu_mask(i, tmp) {
1121                 load = source_load(i, 0);
1122
1123                 if (load < min_load || (load == min_load && i == this_cpu)) {
1124                         min_load = load;
1125                         idlest = i;
1126                 }
1127         }
1128
1129         return idlest;
1130 }
1131
1132 /*
1133  * sched_balance_self: balance the current task (running on cpu) in domains
1134  * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1135  * SD_BALANCE_EXEC.
1136  *
1137  * Balance, ie. select the least loaded group.
1138  *
1139  * Returns the target CPU number, or the same CPU if no balancing is needed.
1140  *
1141  * preempt must be disabled.
1142  */
1143 static int sched_balance_self(int cpu, int flag)
1144 {
1145         struct task_struct *t = current;
1146         struct sched_domain *tmp, *sd = NULL;
1147
1148         for_each_domain(cpu, tmp)
1149                 if (tmp->flags & flag)
1150                         sd = tmp;
1151
1152         while (sd) {
1153                 cpumask_t span;
1154                 struct sched_group *group;
1155                 int new_cpu;
1156                 int weight;
1157
1158                 span = sd->span;
1159                 group = find_idlest_group(sd, t, cpu);
1160                 if (!group)
1161                         goto nextlevel;
1162
1163                 new_cpu = find_idlest_cpu(group, t, cpu);
1164                 if (new_cpu == -1 || new_cpu == cpu)
1165                         goto nextlevel;
1166
1167                 /* Now try balancing at a lower domain level */
1168                 cpu = new_cpu;
1169 nextlevel:
1170                 sd = NULL;
1171                 weight = cpus_weight(span);
1172                 for_each_domain(cpu, tmp) {
1173                         if (weight <= cpus_weight(tmp->span))
1174                                 break;
1175                         if (tmp->flags & flag)
1176                                 sd = tmp;
1177                 }
1178                 /* while loop will break here if sd == NULL */
1179         }
1180
1181         return cpu;
1182 }
1183
1184 #endif /* CONFIG_SMP */
1185
1186 /*
1187  * wake_idle() will wake a task on an idle cpu if task->cpu is
1188  * not idle and an idle cpu is available.  The span of cpus to
1189  * search starts with cpus closest then further out as needed,
1190  * so we always favor a closer, idle cpu.
1191  *
1192  * Returns the CPU we should wake onto.
1193  */
1194 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1195 static int wake_idle(int cpu, task_t *p)
1196 {
1197         cpumask_t tmp;
1198         struct sched_domain *sd;
1199         int i;
1200
1201         if (idle_cpu(cpu))
1202                 return cpu;
1203
1204         for_each_domain(cpu, sd) {
1205                 if (sd->flags & SD_WAKE_IDLE) {
1206                         cpus_and(tmp, sd->span, p->cpus_allowed);
1207                         for_each_cpu_mask(i, tmp) {
1208                                 if (idle_cpu(i))
1209                                         return i;
1210                         }
1211                 }
1212                 else
1213                         break;
1214         }
1215         return cpu;
1216 }
1217 #else
1218 static inline int wake_idle(int cpu, task_t *p)
1219 {
1220         return cpu;
1221 }
1222 #endif
1223
1224 /***
1225  * try_to_wake_up - wake up a thread
1226  * @p: the to-be-woken-up thread
1227  * @state: the mask of task states that can be woken
1228  * @sync: do a synchronous wakeup?
1229  *
1230  * Put it on the run-queue if it's not already there. The "current"
1231  * thread is always on the run-queue (except when the actual
1232  * re-schedule is in progress), and as such you're allowed to do
1233  * the simpler "current->state = TASK_RUNNING" to mark yourself
1234  * runnable without the overhead of this.
1235  *
1236  * returns failure only if the task is already active.
1237  */
1238 static int try_to_wake_up(task_t *p, unsigned int state, int sync)
1239 {
1240         int cpu, this_cpu, success = 0;
1241         unsigned long flags;
1242         long old_state;
1243         runqueue_t *rq;
1244 #ifdef CONFIG_SMP
1245         unsigned long load, this_load;
1246         struct sched_domain *sd, *this_sd = NULL;
1247         int new_cpu;
1248 #endif
1249
1250         rq = task_rq_lock(p, &flags);
1251         old_state = p->state;
1252
1253         /* we need to unhold suspended tasks */
1254         if (old_state & TASK_ONHOLD) {
1255                 vx_unhold_task(p->vx_info, p, rq);
1256                 old_state = p->state;
1257         }
1258         if (!(old_state & state))
1259                 goto out;
1260
1261         if (p->array)
1262                 goto out_running;
1263
1264         cpu = task_cpu(p);
1265         this_cpu = smp_processor_id();
1266
1267 #ifdef CONFIG_SMP
1268         if (unlikely(task_running(rq, p)))
1269                 goto out_activate;
1270
1271         new_cpu = cpu;
1272
1273         schedstat_inc(rq, ttwu_cnt);
1274         if (cpu == this_cpu) {
1275                 schedstat_inc(rq, ttwu_local);
1276                 goto out_set_cpu;
1277         }
1278
1279         for_each_domain(this_cpu, sd) {
1280                 if (cpu_isset(cpu, sd->span)) {
1281                         schedstat_inc(sd, ttwu_wake_remote);
1282                         this_sd = sd;
1283                         break;
1284                 }
1285         }
1286
1287         if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1288                 goto out_set_cpu;
1289
1290         /*
1291          * Check for affine wakeup and passive balancing possibilities.
1292          */
1293         if (this_sd) {
1294                 int idx = this_sd->wake_idx;
1295                 unsigned int imbalance;
1296
1297                 imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
1298
1299                 load = source_load(cpu, idx);
1300                 this_load = target_load(this_cpu, idx);
1301
1302                 new_cpu = this_cpu; /* Wake to this CPU if we can */
1303
1304                 if (this_sd->flags & SD_WAKE_AFFINE) {
1305                         unsigned long tl = this_load;
1306                         /*
1307                          * If sync wakeup then subtract the (maximum possible)
1308                          * effect of the currently running task from the load
1309                          * of the current CPU:
1310                          */
1311                         if (sync)
1312                                 tl -= SCHED_LOAD_SCALE;
1313
1314                         if ((tl <= load &&
1315                                 tl + target_load(cpu, idx) <= SCHED_LOAD_SCALE) ||
1316                                 100*(tl + SCHED_LOAD_SCALE) <= imbalance*load) {
1317                                 /*
1318                                  * This domain has SD_WAKE_AFFINE and
1319                                  * p is cache cold in this domain, and
1320                                  * there is no bad imbalance.
1321                                  */
1322                                 schedstat_inc(this_sd, ttwu_move_affine);
1323                                 goto out_set_cpu;
1324                         }
1325                 }
1326
1327                 /*
1328                  * Start passive balancing when half the imbalance_pct
1329                  * limit is reached.
1330                  */
1331                 if (this_sd->flags & SD_WAKE_BALANCE) {
1332                         if (imbalance*this_load <= 100*load) {
1333                                 schedstat_inc(this_sd, ttwu_move_balance);
1334                                 goto out_set_cpu;
1335                         }
1336                 }
1337         }
1338
1339         new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1340 out_set_cpu:
1341         new_cpu = wake_idle(new_cpu, p);
1342         if (new_cpu != cpu) {
1343                 set_task_cpu(p, new_cpu);
1344                 task_rq_unlock(rq, &flags);
1345                 /* might preempt at this point */
1346                 rq = task_rq_lock(p, &flags);
1347                 old_state = p->state;
1348                 if (!(old_state & state))
1349                         goto out;
1350                 if (p->array)
1351                         goto out_running;
1352
1353                 this_cpu = smp_processor_id();
1354                 cpu = task_cpu(p);
1355         }
1356
1357 out_activate:
1358 #endif /* CONFIG_SMP */
1359         if (old_state == TASK_UNINTERRUPTIBLE) {
1360                 rq->nr_uninterruptible--;
1361                 vx_uninterruptible_dec(p);
1362                 /*
1363                  * Tasks on involuntary sleep don't earn
1364                  * sleep_avg beyond just interactive state.
1365                  */
1366                 p->sleep_type = SLEEP_NONINTERACTIVE;
1367         } else
1368
1369         /*
1370          * Tasks that have marked their sleep as noninteractive get
1371          * woken up with their sleep average not weighted in an
1372          * interactive way.
1373          */
1374                 if (old_state & TASK_NONINTERACTIVE)
1375                         p->sleep_type = SLEEP_NONINTERACTIVE;
1376
1377
1378         activate_task(p, rq, cpu == this_cpu);
1379         /*
1380          * Sync wakeups (i.e. those types of wakeups where the waker
1381          * has indicated that it will leave the CPU in short order)
1382          * don't trigger a preemption, if the woken up task will run on
1383          * this cpu. (in this case the 'I will reschedule' promise of
1384          * the waker guarantees that the freshly woken up task is going
1385          * to be considered on this CPU.)
1386          */
1387         if (!sync || cpu != this_cpu) {
1388                 if (TASK_PREEMPTS_CURR(p, rq))
1389                         resched_task(rq->curr);
1390         }
1391         success = 1;
1392
1393 out_running:
1394         p->state = TASK_RUNNING;
1395 out:
1396         task_rq_unlock(rq, &flags);
1397
1398         return success;
1399 }
1400
1401 int fastcall wake_up_process(task_t *p)
1402 {
1403         return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1404                                  TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1405 }
1406
1407 EXPORT_SYMBOL(wake_up_process);
1408
1409 int fastcall wake_up_state(task_t *p, unsigned int state)
1410 {
1411         return try_to_wake_up(p, state, 0);
1412 }
1413
1414 /*
1415  * Perform scheduler related setup for a newly forked process p.
1416  * p is forked by current.
1417  */
1418 void fastcall sched_fork(task_t *p, int clone_flags)
1419 {
1420         int cpu = get_cpu();
1421
1422 #ifdef CONFIG_SMP
1423         cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
1424 #endif
1425         set_task_cpu(p, cpu);
1426
1427         /*
1428          * We mark the process as running here, but have not actually
1429          * inserted it onto the runqueue yet. This guarantees that
1430          * nobody will actually run it, and a signal or other external
1431          * event cannot wake it up and insert it on the runqueue either.
1432          */
1433         p->state = TASK_RUNNING;
1434         INIT_LIST_HEAD(&p->run_list);
1435         p->array = NULL;
1436 #ifdef CONFIG_SCHEDSTATS
1437         memset(&p->sched_info, 0, sizeof(p->sched_info));
1438 #endif
1439 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
1440         p->oncpu = 0;
1441 #endif
1442 #ifdef CONFIG_PREEMPT
1443         /* Want to start with kernel preemption disabled. */
1444         task_thread_info(p)->preempt_count = 1;
1445 #endif
1446         /*
1447          * Share the timeslice between parent and child, thus the
1448          * total amount of pending timeslices in the system doesn't change,
1449          * resulting in more scheduling fairness.
1450          */
1451         local_irq_disable();
1452         p->time_slice = (current->time_slice + 1) >> 1;
1453         /*
1454          * The remainder of the first timeslice might be recovered by
1455          * the parent if the child exits early enough.
1456          */
1457         p->first_time_slice = 1;
1458         current->time_slice >>= 1;
1459         p->timestamp = sched_clock();
1460         if (unlikely(!current->time_slice)) {
1461                 /*
1462                  * This case is rare, it happens when the parent has only
1463                  * a single jiffy left from its timeslice. Taking the
1464                  * runqueue lock is not a problem.
1465                  */
1466                 current->time_slice = 1;
1467                 scheduler_tick();
1468         }
1469         local_irq_enable();
1470         put_cpu();
1471 }
1472
1473 /*
1474  * wake_up_new_task - wake up a newly created task for the first time.
1475  *
1476  * This function will do some initial scheduler statistics housekeeping
1477  * that must be done for every newly created context, then puts the task
1478  * on the runqueue and wakes it.
1479  */
1480 void fastcall wake_up_new_task(task_t *p, unsigned long clone_flags)
1481 {
1482         unsigned long flags;
1483         int this_cpu, cpu;
1484         runqueue_t *rq, *this_rq;
1485
1486         rq = task_rq_lock(p, &flags);
1487         BUG_ON(p->state != TASK_RUNNING);
1488         this_cpu = smp_processor_id();
1489         cpu = task_cpu(p);
1490
1491         /*
1492          * We decrease the sleep average of forking parents
1493          * and children as well, to keep max-interactive tasks
1494          * from forking tasks that are max-interactive. The parent
1495          * (current) is done further down, under its lock.
1496          */
1497         p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1498                 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1499
1500         p->prio = effective_prio(p);
1501
1502         vx_activate_task(p);
1503         if (likely(cpu == this_cpu)) {
1504                 if (!(clone_flags & CLONE_VM)) {
1505                         /*
1506                          * The VM isn't cloned, so we're in a good position to
1507                          * do child-runs-first in anticipation of an exec. This
1508                          * usually avoids a lot of COW overhead.
1509                          */
1510                         if (unlikely(!current->array))
1511                                 __activate_task(p, rq);
1512                         else {
1513                                 p->prio = current->prio;
1514                                 BUG_ON(p->state & TASK_ONHOLD);
1515                                 list_add_tail(&p->run_list, &current->run_list);
1516                                 p->array = current->array;
1517                                 p->array->nr_active++;
1518                                 rq->nr_running++;
1519                         }
1520                         set_need_resched();
1521                 } else
1522                         /* Run child last */
1523                         __activate_task(p, rq);
1524                 /*
1525                  * We skip the following code due to cpu == this_cpu
1526                  *
1527                  *   task_rq_unlock(rq, &flags);
1528                  *   this_rq = task_rq_lock(current, &flags);
1529                  */
1530                 this_rq = rq;
1531         } else {
1532                 this_rq = cpu_rq(this_cpu);
1533
1534                 /*
1535                  * Not the local CPU - must adjust timestamp. This should
1536                  * get optimised away in the !CONFIG_SMP case.
1537                  */
1538                 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1539                                         + rq->timestamp_last_tick;
1540                 __activate_task(p, rq);
1541                 if (TASK_PREEMPTS_CURR(p, rq))
1542                         resched_task(rq->curr);
1543
1544                 /*
1545                  * Parent and child are on different CPUs, now get the
1546                  * parent runqueue to update the parent's ->sleep_avg:
1547                  */
1548                 task_rq_unlock(rq, &flags);
1549                 this_rq = task_rq_lock(current, &flags);
1550         }
1551         current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1552                 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1553         task_rq_unlock(this_rq, &flags);
1554 }
1555
1556 /*
1557  * Potentially available exiting-child timeslices are
1558  * retrieved here - this way the parent does not get
1559  * penalized for creating too many threads.
1560  *
1561  * (this cannot be used to 'generate' timeslices
1562  * artificially, because any timeslice recovered here
1563  * was given away by the parent in the first place.)
1564  */
1565 void fastcall sched_exit(task_t *p)
1566 {
1567         unsigned long flags;
1568         runqueue_t *rq;
1569
1570         /*
1571          * If the child was a (relative-) CPU hog then decrease
1572          * the sleep_avg of the parent as well.
1573          */
1574         rq = task_rq_lock(p->parent, &flags);
1575         if (p->first_time_slice && task_cpu(p) == task_cpu(p->parent)) {
1576                 p->parent->time_slice += p->time_slice;
1577                 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1578                         p->parent->time_slice = task_timeslice(p);
1579         }
1580         if (p->sleep_avg < p->parent->sleep_avg)
1581                 p->parent->sleep_avg = p->parent->sleep_avg /
1582                 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1583                 (EXIT_WEIGHT + 1);
1584         task_rq_unlock(rq, &flags);
1585 }
1586
1587 /**
1588  * prepare_task_switch - prepare to switch tasks
1589  * @rq: the runqueue preparing to switch
1590  * @next: the task we are going to switch to.
1591  *
1592  * This is called with the rq lock held and interrupts off. It must
1593  * be paired with a subsequent finish_task_switch after the context
1594  * switch.
1595  *
1596  * prepare_task_switch sets up locking and calls architecture specific
1597  * hooks.
1598  */
1599 static inline void prepare_task_switch(runqueue_t *rq, task_t *next)
1600 {
1601         prepare_lock_switch(rq, next);
1602         prepare_arch_switch(next);
1603 }
1604
1605 /**
1606  * finish_task_switch - clean up after a task-switch
1607  * @rq: runqueue associated with task-switch
1608  * @prev: the thread we just switched away from.
1609  *
1610  * finish_task_switch must be called after the context switch, paired
1611  * with a prepare_task_switch call before the context switch.
1612  * finish_task_switch will reconcile locking set up by prepare_task_switch,
1613  * and do any other architecture-specific cleanup actions.
1614  *
1615  * Note that we may have delayed dropping an mm in context_switch(). If
1616  * so, we finish that here outside of the runqueue lock.  (Doing it
1617  * with the lock held can cause deadlocks; see schedule() for
1618  * details.)
1619  */
1620 static inline void finish_task_switch(runqueue_t *rq, task_t *prev)
1621         __releases(rq->lock)
1622 {
1623         struct mm_struct *mm = rq->prev_mm;
1624         unsigned long prev_task_flags;
1625
1626         rq->prev_mm = NULL;
1627
1628         /*
1629          * A task struct has one reference for the use as "current".
1630          * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1631          * calls schedule one last time. The schedule call will never return,
1632          * and the scheduled task must drop that reference.
1633          * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1634          * still held, otherwise prev could be scheduled on another cpu, die
1635          * there before we look at prev->state, and then the reference would
1636          * be dropped twice.
1637          *              Manfred Spraul <manfred@colorfullife.com>
1638          */
1639         prev_task_flags = prev->flags;
1640         finish_arch_switch(prev);
1641         finish_lock_switch(rq, prev);
1642         if (mm)
1643                 mmdrop(mm);
1644         if (unlikely(prev_task_flags & PF_DEAD)) {
1645                 /*
1646                  * Remove function-return probe instances associated with this
1647                  * task and put them back on the free list.
1648                  */
1649                 kprobe_flush_task(prev);
1650                 put_task_struct(prev);
1651         }
1652 }
1653
1654 /**
1655  * schedule_tail - first thing a freshly forked thread must call.
1656  * @prev: the thread we just switched away from.
1657  */
1658 asmlinkage void schedule_tail(task_t *prev)
1659         __releases(rq->lock)
1660 {
1661         runqueue_t *rq = this_rq();
1662         finish_task_switch(rq, prev);
1663 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
1664         /* In this case, finish_task_switch does not reenable preemption */
1665         preempt_enable();
1666 #endif
1667         if (current->set_child_tid)
1668                 put_user(current->pid, current->set_child_tid);
1669 }
1670
1671 /*
1672  * context_switch - switch to the new MM and the new
1673  * thread's register state.
1674  */
1675 static inline
1676 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1677 {
1678         struct mm_struct *mm = next->mm;
1679         struct mm_struct *oldmm = prev->active_mm;
1680
1681         if (unlikely(!mm)) {
1682                 next->active_mm = oldmm;
1683                 atomic_inc(&oldmm->mm_count);
1684                 enter_lazy_tlb(oldmm, next);
1685         } else
1686                 switch_mm(oldmm, mm, next);
1687
1688         if (unlikely(!prev->mm)) {
1689                 prev->active_mm = NULL;
1690                 WARN_ON(rq->prev_mm);
1691                 rq->prev_mm = oldmm;
1692         }
1693
1694         /* Here we just switch the register state and the stack. */
1695         switch_to(prev, next, prev);
1696
1697         return prev;
1698 }
1699
1700 /*
1701  * nr_running, nr_uninterruptible and nr_context_switches:
1702  *
1703  * externally visible scheduler statistics: current number of runnable
1704  * threads, current number of uninterruptible-sleeping threads, total
1705  * number of context switches performed since bootup.
1706  */
1707 unsigned long nr_running(void)
1708 {
1709         unsigned long i, sum = 0;
1710
1711         for_each_online_cpu(i)
1712                 sum += cpu_rq(i)->nr_running;
1713
1714         return sum;
1715 }
1716
1717 unsigned long nr_uninterruptible(void)
1718 {
1719         unsigned long i, sum = 0;
1720
1721         for_each_possible_cpu(i)
1722                 sum += cpu_rq(i)->nr_uninterruptible;
1723
1724         /*
1725          * Since we read the counters lockless, it might be slightly
1726          * inaccurate. Do not allow it to go below zero though:
1727          */
1728         if (unlikely((long)sum < 0))
1729                 sum = 0;
1730
1731         return sum;
1732 }
1733
1734 unsigned long long nr_context_switches(void)
1735 {
1736         unsigned long long i, sum = 0;
1737
1738         for_each_possible_cpu(i)
1739                 sum += cpu_rq(i)->nr_switches;
1740
1741         return sum;
1742 }
1743
1744 unsigned long nr_iowait(void)
1745 {
1746         unsigned long i, sum = 0;
1747
1748         for_each_possible_cpu(i)
1749                 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1750
1751         return sum;
1752 }
1753
1754 unsigned long nr_active(void)
1755 {
1756         unsigned long i, running = 0, uninterruptible = 0;
1757
1758         for_each_online_cpu(i) {
1759                 running += cpu_rq(i)->nr_running;
1760                 uninterruptible += cpu_rq(i)->nr_uninterruptible;
1761         }
1762
1763         if (unlikely((long)uninterruptible < 0))
1764                 uninterruptible = 0;
1765
1766         return running + uninterruptible;
1767 }
1768
1769 #ifdef CONFIG_SMP
1770
1771 /*
1772  * double_rq_lock - safely lock two runqueues
1773  *
1774  * We must take them in cpu order to match code in
1775  * dependent_sleeper and wake_dependent_sleeper.
1776  *
1777  * Note this does not disable interrupts like task_rq_lock,
1778  * you need to do so manually before calling.
1779  */
1780 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1781         __acquires(rq1->lock)
1782         __acquires(rq2->lock)
1783 {
1784         if (rq1 == rq2) {
1785                 spin_lock(&rq1->lock);
1786                 __acquire(rq2->lock);   /* Fake it out ;) */
1787         } else {
1788                 if (rq1->cpu < rq2->cpu) {
1789                         spin_lock(&rq1->lock);
1790                         spin_lock(&rq2->lock);
1791                 } else {
1792                         spin_lock(&rq2->lock);
1793                         spin_lock(&rq1->lock);
1794                 }
1795         }
1796 }
1797
1798 /*
1799  * double_rq_unlock - safely unlock two runqueues
1800  *
1801  * Note this does not restore interrupts like task_rq_unlock,
1802  * you need to do so manually after calling.
1803  */
1804 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1805         __releases(rq1->lock)
1806         __releases(rq2->lock)
1807 {
1808         spin_unlock(&rq1->lock);
1809         if (rq1 != rq2)
1810                 spin_unlock(&rq2->lock);
1811         else
1812                 __release(rq2->lock);
1813 }
1814
1815 /*
1816  * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1817  */
1818 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1819         __releases(this_rq->lock)
1820         __acquires(busiest->lock)
1821         __acquires(this_rq->lock)
1822 {
1823         if (unlikely(!spin_trylock(&busiest->lock))) {
1824                 if (busiest->cpu < this_rq->cpu) {
1825                         spin_unlock(&this_rq->lock);
1826                         spin_lock(&busiest->lock);
1827                         spin_lock(&this_rq->lock);
1828                 } else
1829                         spin_lock(&busiest->lock);
1830         }
1831 }
1832
1833 /*
1834  * If dest_cpu is allowed for this process, migrate the task to it.
1835  * This is accomplished by forcing the cpu_allowed mask to only
1836  * allow dest_cpu, which will force the cpu onto dest_cpu.  Then
1837  * the cpu_allowed mask is restored.
1838  */
1839 static void sched_migrate_task(task_t *p, int dest_cpu)
1840 {
1841         migration_req_t req;
1842         runqueue_t *rq;
1843         unsigned long flags;
1844
1845         rq = task_rq_lock(p, &flags);
1846         if (!cpu_isset(dest_cpu, p->cpus_allowed)
1847             || unlikely(cpu_is_offline(dest_cpu)))
1848                 goto out;
1849
1850         /* force the process onto the specified CPU */
1851         if (migrate_task(p, dest_cpu, &req)) {
1852                 /* Need to wait for migration thread (might exit: take ref). */
1853                 struct task_struct *mt = rq->migration_thread;
1854                 get_task_struct(mt);
1855                 task_rq_unlock(rq, &flags);
1856                 wake_up_process(mt);
1857                 put_task_struct(mt);
1858                 wait_for_completion(&req.done);
1859                 return;
1860         }
1861 out:
1862         task_rq_unlock(rq, &flags);
1863 }
1864
1865 /*
1866  * sched_exec - execve() is a valuable balancing opportunity, because at
1867  * this point the task has the smallest effective memory and cache footprint.
1868  */
1869 void sched_exec(void)
1870 {
1871         int new_cpu, this_cpu = get_cpu();
1872         new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
1873         put_cpu();
1874         if (new_cpu != this_cpu)
1875                 sched_migrate_task(current, new_cpu);
1876 }
1877
1878 /*
1879  * pull_task - move a task from a remote runqueue to the local runqueue.
1880  * Both runqueues must be locked.
1881  */
1882 static
1883 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1884                runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1885 {
1886         dequeue_task(p, src_array);
1887         src_rq->nr_running--;
1888         set_task_cpu(p, this_cpu);
1889         this_rq->nr_running++;
1890         enqueue_task(p, this_array);
1891         p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1892                                 + this_rq->timestamp_last_tick;
1893         /*
1894          * Note that idle threads have a prio of MAX_PRIO, for this test
1895          * to be always true for them.
1896          */
1897         if (TASK_PREEMPTS_CURR(p, this_rq))
1898                 resched_task(this_rq->curr);
1899 }
1900
1901 /*
1902  * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1903  */
1904 static
1905 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1906                      struct sched_domain *sd, enum idle_type idle,
1907                      int *all_pinned)
1908 {
1909         /*
1910          * We do not migrate tasks that are:
1911          * 1) running (obviously), or
1912          * 2) cannot be migrated to this CPU due to cpus_allowed, or
1913          * 3) are cache-hot on their current CPU.
1914          */
1915         if (!cpu_isset(this_cpu, p->cpus_allowed))
1916                 return 0;
1917         *all_pinned = 0;
1918
1919         if (task_running(rq, p))
1920                 return 0;
1921
1922         /*
1923          * Aggressive migration if:
1924          * 1) task is cache cold, or
1925          * 2) too many balance attempts have failed.
1926          */
1927
1928         if (sd->nr_balance_failed > sd->cache_nice_tries)
1929                 return 1;
1930
1931         if (task_hot(p, rq->timestamp_last_tick, sd))
1932                 return 0;
1933         return 1;
1934 }
1935
1936 /*
1937  * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1938  * as part of a balancing operation within "domain". Returns the number of
1939  * tasks moved.
1940  *
1941  * Called with both runqueues locked.
1942  */
1943 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1944                       unsigned long max_nr_move, struct sched_domain *sd,
1945                       enum idle_type idle, int *all_pinned)
1946 {
1947         prio_array_t *array, *dst_array;
1948         struct list_head *head, *curr;
1949         int idx, pulled = 0, pinned = 0;
1950         task_t *tmp;
1951
1952         if (max_nr_move == 0)
1953                 goto out;
1954
1955         pinned = 1;
1956
1957         /*
1958          * We first consider expired tasks. Those will likely not be
1959          * executed in the near future, and they are most likely to
1960          * be cache-cold, thus switching CPUs has the least effect
1961          * on them.
1962          */
1963         if (busiest->expired->nr_active) {
1964                 array = busiest->expired;
1965                 dst_array = this_rq->expired;
1966         } else {
1967                 array = busiest->active;
1968                 dst_array = this_rq->active;
1969         }
1970
1971 new_array:
1972         /* Start searching at priority 0: */
1973         idx = 0;
1974 skip_bitmap:
1975         if (!idx)
1976                 idx = sched_find_first_bit(array->bitmap);
1977         else
1978                 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1979         if (idx >= MAX_PRIO) {
1980                 if (array == busiest->expired && busiest->active->nr_active) {
1981                         array = busiest->active;
1982                         dst_array = this_rq->active;
1983                         goto new_array;
1984                 }
1985                 goto out;
1986         }
1987
1988         head = array->queue + idx;
1989         curr = head->prev;
1990 skip_queue:
1991         tmp = list_entry(curr, task_t, run_list);
1992
1993         curr = curr->prev;
1994
1995         if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle, &pinned)) {
1996                 if (curr != head)
1997                         goto skip_queue;
1998                 idx++;
1999                 goto skip_bitmap;
2000         }
2001
2002 #ifdef CONFIG_SCHEDSTATS
2003         if (task_hot(tmp, busiest->timestamp_last_tick, sd))
2004                 schedstat_inc(sd, lb_hot_gained[idle]);
2005 #endif
2006
2007         pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
2008         pulled++;
2009
2010         /* We only want to steal up to the prescribed number of tasks. */
2011         if (pulled < max_nr_move) {
2012                 if (curr != head)
2013                         goto skip_queue;
2014                 idx++;
2015                 goto skip_bitmap;
2016         }
2017 out:
2018         /*
2019          * Right now, this is the only place pull_task() is called,
2020          * so we can safely collect pull_task() stats here rather than
2021          * inside pull_task().
2022          */
2023         schedstat_add(sd, lb_gained[idle], pulled);
2024
2025         if (all_pinned)
2026                 *all_pinned = pinned;
2027         return pulled;
2028 }
2029
2030 /*
2031  * find_busiest_group finds and returns the busiest CPU group within the
2032  * domain. It calculates and returns the number of tasks which should be
2033  * moved to restore balance via the imbalance parameter.
2034  */
2035 static struct sched_group *
2036 find_busiest_group(struct sched_domain *sd, int this_cpu,
2037                    unsigned long *imbalance, enum idle_type idle, int *sd_idle)
2038 {
2039         struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2040         unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2041         unsigned long max_pull;
2042         int load_idx;
2043
2044         max_load = this_load = total_load = total_pwr = 0;
2045         if (idle == NOT_IDLE)
2046                 load_idx = sd->busy_idx;
2047         else if (idle == NEWLY_IDLE)
2048                 load_idx = sd->newidle_idx;
2049         else
2050                 load_idx = sd->idle_idx;
2051
2052         do {
2053                 unsigned long load;
2054                 int local_group;
2055                 int i;
2056
2057                 local_group = cpu_isset(this_cpu, group->cpumask);
2058
2059                 /* Tally up the load of all CPUs in the group */
2060                 avg_load = 0;
2061
2062                 for_each_cpu_mask(i, group->cpumask) {
2063                         if (*sd_idle && !idle_cpu(i))
2064                                 *sd_idle = 0;
2065
2066                         /* Bias balancing toward cpus of our domain */
2067                         if (local_group)
2068                                 load = target_load(i, load_idx);
2069                         else
2070                                 load = source_load(i, load_idx);
2071
2072                         avg_load += load;
2073                 }
2074
2075                 total_load += avg_load;
2076                 total_pwr += group->cpu_power;
2077
2078                 /* Adjust by relative CPU power of the group */
2079                 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
2080
2081                 if (local_group) {
2082                         this_load = avg_load;
2083                         this = group;
2084                 } else if (avg_load > max_load) {
2085                         max_load = avg_load;
2086                         busiest = group;
2087                 }
2088                 group = group->next;
2089         } while (group != sd->groups);
2090
2091         if (!busiest || this_load >= max_load || max_load <= SCHED_LOAD_SCALE)
2092                 goto out_balanced;
2093
2094         avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2095
2096         if (this_load >= avg_load ||
2097                         100*max_load <= sd->imbalance_pct*this_load)
2098                 goto out_balanced;
2099
2100         /*
2101          * We're trying to get all the cpus to the average_load, so we don't
2102          * want to push ourselves above the average load, nor do we wish to
2103          * reduce the max loaded cpu below the average load, as either of these
2104          * actions would just result in more rebalancing later, and ping-pong
2105          * tasks around. Thus we look for the minimum possible imbalance.
2106          * Negative imbalances (*we* are more loaded than anyone else) will
2107          * be counted as no imbalance for these purposes -- we can't fix that
2108          * by pulling tasks to us.  Be careful of negative numbers as they'll
2109          * appear as very large values with unsigned longs.
2110          */
2111
2112         /* Don't want to pull so many tasks that a group would go idle */
2113         max_pull = min(max_load - avg_load, max_load - SCHED_LOAD_SCALE);
2114
2115         /* How much load to actually move to equalise the imbalance */
2116         *imbalance = min(max_pull * busiest->cpu_power,
2117                                 (avg_load - this_load) * this->cpu_power)
2118                         / SCHED_LOAD_SCALE;
2119
2120         if (*imbalance < SCHED_LOAD_SCALE) {
2121                 unsigned long pwr_now = 0, pwr_move = 0;
2122                 unsigned long tmp;
2123
2124                 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
2125                         *imbalance = 1;
2126                         return busiest;
2127                 }
2128
2129                 /*
2130                  * OK, we don't have enough imbalance to justify moving tasks,
2131                  * however we may be able to increase total CPU power used by
2132                  * moving them.
2133                  */
2134
2135                 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
2136                 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
2137                 pwr_now /= SCHED_LOAD_SCALE;
2138
2139                 /* Amount of load we'd subtract */
2140                 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
2141                 if (max_load > tmp)
2142                         pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
2143                                                         max_load - tmp);
2144
2145                 /* Amount of load we'd add */
2146                 if (max_load*busiest->cpu_power <
2147                                 SCHED_LOAD_SCALE*SCHED_LOAD_SCALE)
2148                         tmp = max_load*busiest->cpu_power/this->cpu_power;
2149                 else
2150                         tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
2151                 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
2152                 pwr_move /= SCHED_LOAD_SCALE;
2153
2154                 /* Move if we gain throughput */
2155                 if (pwr_move <= pwr_now)
2156                         goto out_balanced;
2157
2158                 *imbalance = 1;
2159                 return busiest;
2160         }
2161
2162         /* Get rid of the scaling factor, rounding down as we divide */
2163         *imbalance = *imbalance / SCHED_LOAD_SCALE;
2164         return busiest;
2165
2166 out_balanced:
2167
2168         *imbalance = 0;
2169         return NULL;
2170 }
2171
2172 /*
2173  * find_busiest_queue - find the busiest runqueue among the cpus in group.
2174  */
2175 static runqueue_t *find_busiest_queue(struct sched_group *group,
2176         enum idle_type idle)
2177 {
2178         unsigned long load, max_load = 0;
2179         runqueue_t *busiest = NULL;
2180         int i;
2181
2182         for_each_cpu_mask(i, group->cpumask) {
2183                 load = source_load(i, 0);
2184
2185                 if (load > max_load) {
2186                         max_load = load;
2187                         busiest = cpu_rq(i);
2188                 }
2189         }
2190
2191         return busiest;
2192 }
2193
2194 /*
2195  * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2196  * so long as it is large enough.
2197  */
2198 #define MAX_PINNED_INTERVAL     512
2199
2200 /*
2201  * Check this_cpu to ensure it is balanced within domain. Attempt to move
2202  * tasks if there is an imbalance.
2203  *
2204  * Called with this_rq unlocked.
2205  */
2206 static int load_balance(int this_cpu, runqueue_t *this_rq,
2207                         struct sched_domain *sd, enum idle_type idle)
2208 {
2209         struct sched_group *group;
2210         runqueue_t *busiest;
2211         unsigned long imbalance;
2212         int nr_moved, all_pinned = 0;
2213         int active_balance = 0;
2214         int sd_idle = 0;
2215
2216         if (idle != NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER)
2217                 sd_idle = 1;
2218
2219         schedstat_inc(sd, lb_cnt[idle]);
2220
2221         group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle);
2222         if (!group) {
2223                 schedstat_inc(sd, lb_nobusyg[idle]);
2224                 goto out_balanced;
2225         }
2226
2227         busiest = find_busiest_queue(group, idle);
2228         if (!busiest) {
2229                 schedstat_inc(sd, lb_nobusyq[idle]);
2230                 goto out_balanced;
2231         }
2232
2233         BUG_ON(busiest == this_rq);
2234
2235         schedstat_add(sd, lb_imbalance[idle], imbalance);
2236
2237         nr_moved = 0;
2238         if (busiest->nr_running > 1) {
2239                 /*
2240                  * Attempt to move tasks. If find_busiest_group has found
2241                  * an imbalance but busiest->nr_running <= 1, the group is
2242                  * still unbalanced. nr_moved simply stays zero, so it is
2243                  * correctly treated as an imbalance.
2244                  */
2245                 double_rq_lock(this_rq, busiest);
2246                 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2247                                         imbalance, sd, idle, &all_pinned);
2248                 double_rq_unlock(this_rq, busiest);
2249
2250                 /* All tasks on this runqueue were pinned by CPU affinity */
2251                 if (unlikely(all_pinned))
2252                         goto out_balanced;
2253         }
2254
2255         if (!nr_moved) {
2256                 schedstat_inc(sd, lb_failed[idle]);
2257                 sd->nr_balance_failed++;
2258
2259                 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2260
2261                         spin_lock(&busiest->lock);
2262
2263                         /* don't kick the migration_thread, if the curr
2264                          * task on busiest cpu can't be moved to this_cpu
2265                          */
2266                         if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
2267                                 spin_unlock(&busiest->lock);
2268                                 all_pinned = 1;
2269                                 goto out_one_pinned;
2270                         }
2271
2272                         if (!busiest->active_balance) {
2273                                 busiest->active_balance = 1;
2274                                 busiest->push_cpu = this_cpu;
2275                                 active_balance = 1;
2276                         }
2277                         spin_unlock(&busiest->lock);
2278                         if (active_balance)
2279                                 wake_up_process(busiest->migration_thread);
2280
2281                         /*
2282                          * We've kicked active balancing, reset the failure
2283                          * counter.
2284                          */
2285                         sd->nr_balance_failed = sd->cache_nice_tries+1;
2286                 }
2287         } else
2288                 sd->nr_balance_failed = 0;
2289
2290         if (likely(!active_balance)) {
2291                 /* We were unbalanced, so reset the balancing interval */
2292                 sd->balance_interval = sd->min_interval;
2293         } else {
2294                 /*
2295                  * If we've begun active balancing, start to back off. This
2296                  * case may not be covered by the all_pinned logic if there
2297                  * is only 1 task on the busy runqueue (because we don't call
2298                  * move_tasks).
2299                  */
2300                 if (sd->balance_interval < sd->max_interval)
2301                         sd->balance_interval *= 2;
2302         }
2303
2304         if (!nr_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2305                 return -1;
2306         return nr_moved;
2307
2308 out_balanced:
2309         schedstat_inc(sd, lb_balanced[idle]);
2310
2311         sd->nr_balance_failed = 0;
2312
2313 out_one_pinned:
2314         /* tune up the balancing interval */
2315         if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
2316                         (sd->balance_interval < sd->max_interval))
2317                 sd->balance_interval *= 2;
2318
2319         if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2320                 return -1;
2321         return 0;
2322 }
2323
2324 /*
2325  * Check this_cpu to ensure it is balanced within domain. Attempt to move
2326  * tasks if there is an imbalance.
2327  *
2328  * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2329  * this_rq is locked.
2330  */
2331 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2332                                 struct sched_domain *sd)
2333 {
2334         struct sched_group *group;
2335         runqueue_t *busiest = NULL;
2336         unsigned long imbalance;
2337         int nr_moved = 0;
2338         int sd_idle = 0;
2339
2340         if (sd->flags & SD_SHARE_CPUPOWER)
2341                 sd_idle = 1;
2342
2343         schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2344         group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE, &sd_idle);
2345         if (!group) {
2346                 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2347                 goto out_balanced;
2348         }
2349
2350         busiest = find_busiest_queue(group, NEWLY_IDLE);
2351         if (!busiest) {
2352                 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2353                 goto out_balanced;
2354         }
2355
2356         BUG_ON(busiest == this_rq);
2357
2358         schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2359
2360         nr_moved = 0;
2361         if (busiest->nr_running > 1) {
2362                 /* Attempt to move tasks */
2363                 double_lock_balance(this_rq, busiest);
2364                 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2365                                         imbalance, sd, NEWLY_IDLE, NULL);
2366                 spin_unlock(&busiest->lock);
2367         }
2368
2369         if (!nr_moved) {
2370                 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2371                 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2372                         return -1;
2373         } else
2374                 sd->nr_balance_failed = 0;
2375
2376         return nr_moved;
2377
2378 out_balanced:
2379         schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
2380         if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2381                 return -1;
2382         sd->nr_balance_failed = 0;
2383         return 0;
2384 }
2385
2386 /*
2387  * idle_balance is called by schedule() if this_cpu is about to become
2388  * idle. Attempts to pull tasks from other CPUs.
2389  */
2390 static void idle_balance(int this_cpu, runqueue_t *this_rq)
2391 {
2392         struct sched_domain *sd;
2393
2394         for_each_domain(this_cpu, sd) {
2395                 if (sd->flags & SD_BALANCE_NEWIDLE) {
2396                         if (load_balance_newidle(this_cpu, this_rq, sd)) {
2397                                 /* We've pulled tasks over so stop searching */
2398                                 break;
2399                         }
2400                 }
2401         }
2402 }
2403
2404 /*
2405  * active_load_balance is run by migration threads. It pushes running tasks
2406  * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2407  * running on each physical CPU where possible, and avoids physical /
2408  * logical imbalances.
2409  *
2410  * Called with busiest_rq locked.
2411  */
2412 static void active_load_balance(runqueue_t *busiest_rq, int busiest_cpu)
2413 {
2414         struct sched_domain *sd;
2415         runqueue_t *target_rq;
2416         int target_cpu = busiest_rq->push_cpu;
2417
2418         if (busiest_rq->nr_running <= 1)
2419                 /* no task to move */
2420                 return;
2421
2422         target_rq = cpu_rq(target_cpu);
2423
2424         /*
2425          * This condition is "impossible", if it occurs
2426          * we need to fix it.  Originally reported by
2427          * Bjorn Helgaas on a 128-cpu setup.
2428          */
2429         BUG_ON(busiest_rq == target_rq);
2430
2431         /* move a task from busiest_rq to target_rq */
2432         double_lock_balance(busiest_rq, target_rq);
2433
2434         /* Search for an sd spanning us and the target CPU. */
2435         for_each_domain(target_cpu, sd)
2436                 if ((sd->flags & SD_LOAD_BALANCE) &&
2437                         cpu_isset(busiest_cpu, sd->span))
2438                                 break;
2439
2440         if (unlikely(sd == NULL))
2441                 goto out;
2442
2443         schedstat_inc(sd, alb_cnt);
2444
2445         if (move_tasks(target_rq, target_cpu, busiest_rq, 1, sd, SCHED_IDLE, NULL))
2446                 schedstat_inc(sd, alb_pushed);
2447         else
2448                 schedstat_inc(sd, alb_failed);
2449 out:
2450         spin_unlock(&target_rq->lock);
2451 }
2452
2453 /*
2454  * rebalance_tick will get called every timer tick, on every CPU.
2455  *
2456  * It checks each scheduling domain to see if it is due to be balanced,
2457  * and initiates a balancing operation if so.
2458  *
2459  * Balancing parameters are set up in arch_init_sched_domains.
2460  */
2461
2462 /* Don't have all balancing operations going off at once */
2463 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2464
2465 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2466                            enum idle_type idle)
2467 {
2468         unsigned long old_load, this_load;
2469         unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2470         struct sched_domain *sd;
2471         int i;
2472
2473         this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
2474         /* Update our load */
2475         for (i = 0; i < 3; i++) {
2476                 unsigned long new_load = this_load;
2477                 int scale = 1 << i;
2478                 old_load = this_rq->cpu_load[i];
2479                 /*
2480                  * Round up the averaging division if load is increasing. This
2481                  * prevents us from getting stuck on 9 if the load is 10, for
2482                  * example.
2483                  */
2484                 if (new_load > old_load)
2485                         new_load += scale-1;
2486                 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) / scale;
2487         }
2488
2489         for_each_domain(this_cpu, sd) {
2490                 unsigned long interval;
2491
2492                 if (!(sd->flags & SD_LOAD_BALANCE))
2493                         continue;
2494
2495                 interval = sd->balance_interval;
2496                 if (idle != SCHED_IDLE)
2497                         interval *= sd->busy_factor;
2498
2499                 /* scale ms to jiffies */
2500                 interval = msecs_to_jiffies(interval);
2501                 if (unlikely(!interval))
2502                         interval = 1;
2503
2504                 if (j - sd->last_balance >= interval) {
2505                         if (load_balance(this_cpu, this_rq, sd, idle)) {
2506                                 /*
2507                                  * We've pulled tasks over so either we're no
2508                                  * longer idle, or one of our SMT siblings is
2509                                  * not idle.
2510                                  */
2511                                 idle = NOT_IDLE;
2512                         }
2513                         sd->last_balance += interval;
2514                 }
2515         }
2516 }
2517 #else
2518 /*
2519  * on UP we do not need to balance between CPUs:
2520  */
2521 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2522 {
2523 }
2524 static inline void idle_balance(int cpu, runqueue_t *rq)
2525 {
2526 }
2527 #endif
2528
2529 static inline int wake_priority_sleeper(runqueue_t *rq)
2530 {
2531         int ret = 0;
2532 #ifdef CONFIG_SCHED_SMT
2533         spin_lock(&rq->lock);
2534         /*
2535          * If an SMT sibling task has been put to sleep for priority
2536          * reasons reschedule the idle task to see if it can now run.
2537          */
2538         if (rq->nr_running) {
2539                 resched_task(rq->idle);
2540                 ret = 1;
2541         }
2542         spin_unlock(&rq->lock);
2543 #endif
2544         return ret;
2545 }
2546
2547 DEFINE_PER_CPU(struct kernel_stat, kstat);
2548
2549 EXPORT_PER_CPU_SYMBOL(kstat);
2550
2551 /*
2552  * This is called on clock ticks and on context switches.
2553  * Bank in p->sched_time the ns elapsed since the last tick or switch.
2554  */
2555 static inline void update_cpu_clock(task_t *p, runqueue_t *rq,
2556                                     unsigned long long now)
2557 {
2558         unsigned long long last = max(p->timestamp, rq->timestamp_last_tick);
2559         p->sched_time += now - last;
2560 }
2561
2562 /*
2563  * Return current->sched_time plus any more ns on the sched_clock
2564  * that have not yet been banked.
2565  */
2566 unsigned long long current_sched_time(const task_t *tsk)
2567 {
2568         unsigned long long ns;
2569         unsigned long flags;
2570         local_irq_save(flags);
2571         ns = max(tsk->timestamp, task_rq(tsk)->timestamp_last_tick);
2572         ns = tsk->sched_time + (sched_clock() - ns);
2573         local_irq_restore(flags);
2574         return ns;
2575 }
2576
2577 /*
2578  * We place interactive tasks back into the active array, if possible.
2579  *
2580  * To guarantee that this does not starve expired tasks we ignore the
2581  * interactivity of a task if the first expired task had to wait more
2582  * than a 'reasonable' amount of time. This deadline timeout is
2583  * load-dependent, as the frequency of array switched decreases with
2584  * increasing number of running tasks. We also ignore the interactivity
2585  * if a better static_prio task has expired:
2586  */
2587 #define EXPIRED_STARVING(rq) \
2588         ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2589                 (jiffies - (rq)->expired_timestamp >= \
2590                         STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2591                         ((rq)->curr->static_prio > (rq)->best_expired_prio))
2592
2593 /*
2594  * Account user cpu time to a process.
2595  * @p: the process that the cpu time gets accounted to
2596  * @hardirq_offset: the offset to subtract from hardirq_count()
2597  * @cputime: the cpu time spent in user space since the last update
2598  */
2599 void account_user_time(struct task_struct *p, cputime_t cputime)
2600 {
2601         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2602         struct vx_info *vxi = p->vx_info;  /* p is _always_ current */
2603         cputime64_t tmp;
2604         int nice = (TASK_NICE(p) > 0);
2605
2606         p->utime = cputime_add(p->utime, cputime);
2607         vx_account_user(vxi, cputime, nice);
2608
2609         /* Add user time to cpustat. */
2610         tmp = cputime_to_cputime64(cputime);
2611         if (nice)
2612                 cpustat->nice = cputime64_add(cpustat->nice, tmp);
2613         else
2614                 cpustat->user = cputime64_add(cpustat->user, tmp);
2615 }
2616
2617 /*
2618  * Account system cpu time to a process.
2619  * @p: the process that the cpu time gets accounted to
2620  * @hardirq_offset: the offset to subtract from hardirq_count()
2621  * @cputime: the cpu time spent in kernel space since the last update
2622  */
2623 void account_system_time(struct task_struct *p, int hardirq_offset,
2624                          cputime_t cputime)
2625 {
2626         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2627         struct vx_info *vxi = p->vx_info;  /* p is _always_ current */
2628         runqueue_t *rq = this_rq();
2629         cputime64_t tmp;
2630
2631         p->stime = cputime_add(p->stime, cputime);
2632         vx_account_system(vxi, cputime, (p == rq->idle));
2633
2634         /* Add system time to cpustat. */
2635         tmp = cputime_to_cputime64(cputime);
2636         if (hardirq_count() - hardirq_offset)
2637                 cpustat->irq = cputime64_add(cpustat->irq, tmp);
2638         else if (softirq_count())
2639                 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
2640         else if (p != rq->idle)
2641                 cpustat->system = cputime64_add(cpustat->system, tmp);
2642         else if (atomic_read(&rq->nr_iowait) > 0)
2643                 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2644         else
2645                 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2646         /* Account for system time used */
2647         acct_update_integrals(p);
2648 }
2649
2650 /*
2651  * Account for involuntary wait time.
2652  * @p: the process from which the cpu time has been stolen
2653  * @steal: the cpu time spent in involuntary wait
2654  */
2655 void account_steal_time(struct task_struct *p, cputime_t steal)
2656 {
2657         struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2658         cputime64_t tmp = cputime_to_cputime64(steal);
2659         runqueue_t *rq = this_rq();
2660
2661         if (p == rq->idle) {
2662                 p->stime = cputime_add(p->stime, steal);
2663                 if (atomic_read(&rq->nr_iowait) > 0)
2664                         cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2665                 else
2666                         cpustat->idle = cputime64_add(cpustat->idle, tmp);
2667         } else
2668                 cpustat->steal = cputime64_add(cpustat->steal, tmp);
2669 }
2670
2671 /*
2672  * This function gets called by the timer code, with HZ frequency.
2673  * We call it with interrupts disabled.
2674  *
2675  * It also gets called by the fork code, when changing the parent's
2676  * timeslices.
2677  */
2678 void scheduler_tick(void)
2679 {
2680         int cpu = smp_processor_id();
2681         runqueue_t *rq = this_rq();
2682         task_t *p = current;
2683         unsigned long long now = sched_clock();
2684
2685         update_cpu_clock(p, rq, now);
2686
2687         rq->timestamp_last_tick = now;
2688
2689 #if defined(CONFIG_VSERVER_HARDCPU) && defined(CONFIG_VSERVER_ACB_SCHED) 
2690         vx_scheduler_tick();
2691 #endif
2692
2693         if (p == rq->idle) {
2694                 if (wake_priority_sleeper(rq))
2695                         goto out;
2696 #ifdef CONFIG_VSERVER_HARDCPU_IDLE
2697                 if (!--rq->idle_tokens && !list_empty(&rq->hold_queue))
2698                         set_need_resched();
2699 #endif
2700                 rebalance_tick(cpu, rq, SCHED_IDLE);
2701                 return;
2702         }
2703
2704         /* Task might have expired already, but not scheduled off yet */
2705         if (p->array != rq->active) {
2706                 set_tsk_need_resched(p);
2707                 goto out;
2708         }
2709         spin_lock(&rq->lock);
2710         /*
2711          * The task was running during this tick - update the
2712          * time slice counter. Note: we do not update a thread's
2713          * priority until it either goes to sleep or uses up its
2714          * timeslice. This makes it possible for interactive tasks
2715          * to use up their timeslices at their highest priority levels.
2716          */
2717         if (rt_task(p)) {
2718                 /*
2719                  * RR tasks need a special form of timeslice management.
2720                  * FIFO tasks have no timeslices.
2721                  */
2722                 if ((p->policy == SCHED_RR) && vx_need_resched(p)) {
2723                         p->time_slice = task_timeslice(p);
2724                         p->first_time_slice = 0;
2725                         set_tsk_need_resched(p);
2726
2727                         /* put it at the end of the queue: */
2728                         requeue_task(p, rq->active);
2729                 }
2730                 goto out_unlock;
2731         }
2732         if (vx_need_resched(p)) {
2733                 dequeue_task(p, rq->active);
2734                 set_tsk_need_resched(p);
2735                 p->prio = effective_prio(p);
2736                 p->time_slice = task_timeslice(p);
2737                 p->first_time_slice = 0;
2738
2739                 if (!rq->expired_timestamp)
2740                         rq->expired_timestamp = jiffies;
2741                 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2742                         enqueue_task(p, rq->expired);
2743                         if (p->static_prio < rq->best_expired_prio)
2744                                 rq->best_expired_prio = p->static_prio;
2745                 } else
2746                         enqueue_task(p, rq->active);
2747         } else {
2748                 /*
2749                  * Prevent a too long timeslice allowing a task to monopolize
2750                  * the CPU. We do this by splitting up the timeslice into
2751                  * smaller pieces.
2752                  *
2753                  * Note: this does not mean the task's timeslices expire or
2754                  * get lost in any way, they just might be preempted by
2755                  * another task of equal priority. (one with higher
2756                  * priority would have preempted this task already.) We
2757                  * requeue this task to the end of the list on this priority
2758                  * level, which is in essence a round-robin of tasks with
2759                  * equal priority.
2760                  *
2761                  * This only applies to tasks in the interactive
2762                  * delta range with at least TIMESLICE_GRANULARITY to requeue.
2763                  */
2764                 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2765                         p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2766                         (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2767                         (p->array == rq->active)) {
2768
2769                         requeue_task(p, rq->active);
2770                         set_tsk_need_resched(p);
2771                 }
2772         }
2773 out_unlock:
2774         spin_unlock(&rq->lock);
2775 out:
2776         rebalance_tick(cpu, rq, NOT_IDLE);
2777 }
2778
2779 #ifdef CONFIG_SCHED_SMT
2780 static inline void wakeup_busy_runqueue(runqueue_t *rq)
2781 {
2782         /* If an SMT runqueue is sleeping due to priority reasons wake it up */
2783         if (rq->curr == rq->idle && rq->nr_running)
2784                 resched_task(rq->idle);
2785 }
2786
2787 static void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2788 {
2789         struct sched_domain *tmp, *sd = NULL;
2790         cpumask_t sibling_map;
2791         int i;
2792
2793         for_each_domain(this_cpu, tmp)
2794                 if (tmp->flags & SD_SHARE_CPUPOWER)
2795                         sd = tmp;
2796
2797         if (!sd)
2798                 return;
2799
2800         /*
2801          * Unlock the current runqueue because we have to lock in
2802          * CPU order to avoid deadlocks. Caller knows that we might
2803          * unlock. We keep IRQs disabled.
2804          */
2805         spin_unlock(&this_rq->lock);
2806
2807         sibling_map = sd->span;
2808
2809         for_each_cpu_mask(i, sibling_map)
2810                 spin_lock(&cpu_rq(i)->lock);
2811         /*
2812          * We clear this CPU from the mask. This both simplifies the
2813          * inner loop and keps this_rq locked when we exit:
2814          */
2815         cpu_clear(this_cpu, sibling_map);
2816
2817         for_each_cpu_mask(i, sibling_map) {
2818                 runqueue_t *smt_rq = cpu_rq(i);
2819
2820                 wakeup_busy_runqueue(smt_rq);
2821         }
2822
2823         for_each_cpu_mask(i, sibling_map)
2824                 spin_unlock(&cpu_rq(i)->lock);
2825         /*
2826          * We exit with this_cpu's rq still held and IRQs
2827          * still disabled:
2828          */
2829 }
2830
2831 /*
2832  * number of 'lost' timeslices this task wont be able to fully
2833  * utilize, if another task runs on a sibling. This models the
2834  * slowdown effect of other tasks running on siblings:
2835  */
2836 static inline unsigned long smt_slice(task_t *p, struct sched_domain *sd)
2837 {
2838         return p->time_slice * (100 - sd->per_cpu_gain) / 100;
2839 }
2840
2841 static int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2842 {
2843         struct sched_domain *tmp, *sd = NULL;
2844         cpumask_t sibling_map;
2845         prio_array_t *array;
2846         int ret = 0, i;
2847         task_t *p;
2848
2849         for_each_domain(this_cpu, tmp)
2850                 if (tmp->flags & SD_SHARE_CPUPOWER)
2851                         sd = tmp;
2852
2853         if (!sd)
2854                 return 0;
2855
2856         /*
2857          * The same locking rules and details apply as for
2858          * wake_sleeping_dependent():
2859          */
2860         spin_unlock(&this_rq->lock);
2861         sibling_map = sd->span;
2862         for_each_cpu_mask(i, sibling_map)
2863                 spin_lock(&cpu_rq(i)->lock);
2864         cpu_clear(this_cpu, sibling_map);
2865
2866         /*
2867          * Establish next task to be run - it might have gone away because
2868          * we released the runqueue lock above:
2869          */
2870         if (!this_rq->nr_running)
2871                 goto out_unlock;
2872         array = this_rq->active;
2873         if (!array->nr_active)
2874                 array = this_rq->expired;
2875         BUG_ON(!array->nr_active);
2876
2877         p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
2878                 task_t, run_list);
2879
2880         for_each_cpu_mask(i, sibling_map) {
2881                 runqueue_t *smt_rq = cpu_rq(i);
2882                 task_t *smt_curr = smt_rq->curr;
2883
2884                 /* Kernel threads do not participate in dependent sleeping */
2885                 if (!p->mm || !smt_curr->mm || rt_task(p))
2886                         goto check_smt_task;
2887
2888                 /*
2889                  * If a user task with lower static priority than the
2890                  * running task on the SMT sibling is trying to schedule,
2891                  * delay it till there is proportionately less timeslice
2892                  * left of the sibling task to prevent a lower priority
2893                  * task from using an unfair proportion of the
2894                  * physical cpu's resources. -ck
2895                  */
2896                 if (rt_task(smt_curr)) {
2897                         /*
2898                          * With real time tasks we run non-rt tasks only
2899                          * per_cpu_gain% of the time.
2900                          */
2901                         if ((jiffies % DEF_TIMESLICE) >
2902                                 (sd->per_cpu_gain * DEF_TIMESLICE / 100))
2903                                         ret = 1;
2904                 } else
2905                         if (smt_curr->static_prio < p->static_prio &&
2906                                 !TASK_PREEMPTS_CURR(p, smt_rq) &&
2907                                 smt_slice(smt_curr, sd) > task_timeslice(p))
2908                                         ret = 1;
2909
2910 check_smt_task:
2911                 if ((!smt_curr->mm && smt_curr != smt_rq->idle) ||
2912                         rt_task(smt_curr))
2913                                 continue;
2914                 if (!p->mm) {
2915                         wakeup_busy_runqueue(smt_rq);
2916                         continue;
2917                 }
2918
2919                 /*
2920                  * Reschedule a lower priority task on the SMT sibling for
2921                  * it to be put to sleep, or wake it up if it has been put to
2922                  * sleep for priority reasons to see if it should run now.
2923                  */
2924                 if (rt_task(p)) {
2925                         if ((jiffies % DEF_TIMESLICE) >
2926                                 (sd->per_cpu_gain * DEF_TIMESLICE / 100))
2927                                         resched_task(smt_curr);
2928                 } else {
2929                         if (TASK_PREEMPTS_CURR(p, smt_rq) &&
2930                                 smt_slice(p, sd) > task_timeslice(smt_curr))
2931                                         resched_task(smt_curr);
2932                         else
2933                                 wakeup_busy_runqueue(smt_rq);
2934                 }
2935         }
2936 out_unlock:
2937         for_each_cpu_mask(i, sibling_map)
2938                 spin_unlock(&cpu_rq(i)->lock);
2939         return ret;
2940 }
2941 #else
2942 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2943 {
2944 }
2945
2946 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2947 {
2948         return 0;
2949 }
2950 #endif
2951
2952 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
2953
2954 void fastcall add_preempt_count(int val)
2955 {
2956         /*
2957          * Underflow?
2958          */
2959         BUG_ON((preempt_count() < 0));
2960         preempt_count() += val;
2961         /*
2962          * Spinlock count overflowing soon?
2963          */
2964         BUG_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
2965 }
2966 EXPORT_SYMBOL(add_preempt_count);
2967
2968 void fastcall sub_preempt_count(int val)
2969 {
2970         /*
2971          * Underflow?
2972          */
2973         BUG_ON(val > preempt_count());
2974         /*
2975          * Is the spinlock portion underflowing?
2976          */
2977         BUG_ON((val < PREEMPT_MASK) && !(preempt_count() & PREEMPT_MASK));
2978         preempt_count() -= val;
2979 }
2980 EXPORT_SYMBOL(sub_preempt_count);
2981
2982 #endif
2983
2984 static inline int interactive_sleep(enum sleep_type sleep_type)
2985 {
2986         return (sleep_type == SLEEP_INTERACTIVE ||
2987                 sleep_type == SLEEP_INTERRUPTED);
2988 }
2989
2990 /*
2991  * schedule() is the main scheduler function.
2992  */
2993 asmlinkage void __sched schedule(void)
2994 {
2995         long *switch_count;
2996         task_t *prev, *next;
2997         runqueue_t *rq;
2998         prio_array_t *array;
2999         struct list_head *queue;
3000         unsigned long long now;
3001         unsigned long run_time;
3002         int cpu, idx, new_prio;
3003         struct vx_info *vxi;
3004 #ifdef  CONFIG_VSERVER_HARDCPU
3005         int maxidle = -HZ;
3006 # ifdef CONFIG_VSERVER_ACB_SCHED
3007         int min_guarantee_ticks = VX_INVALID_TICKS;
3008         int min_best_effort_ticks = VX_INVALID_TICKS;
3009 # endif
3010 #endif
3011
3012         /*
3013          * Test if we are atomic.  Since do_exit() needs to call into
3014          * schedule() atomically, we ignore that path for now.
3015          * Otherwise, whine if we are scheduling when we should not be.
3016          */
3017         if (unlikely(in_atomic() && !current->exit_state)) {
3018                 printk(KERN_ERR "BUG: scheduling while atomic: "
3019                         "%s/0x%08x/%d\n",
3020                         current->comm, preempt_count(), current->pid);
3021                 dump_stack();
3022         }
3023         profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3024
3025 need_resched:
3026         preempt_disable();
3027         prev = current;
3028         release_kernel_lock(prev);
3029 need_resched_nonpreemptible:
3030         rq = this_rq();
3031
3032         /*
3033          * The idle thread is not allowed to schedule!
3034          * Remove this check after it has been exercised a bit.
3035          */
3036         if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
3037                 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
3038                 dump_stack();
3039         }
3040
3041         schedstat_inc(rq, sched_cnt);
3042         now = sched_clock();
3043         if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
3044                 run_time = now - prev->timestamp;
3045                 if (unlikely((long long)(now - prev->timestamp) < 0))
3046                         run_time = 0;
3047         } else
3048                 run_time = NS_MAX_SLEEP_AVG;
3049
3050         /*
3051          * Tasks charged proportionately less run_time at high sleep_avg to
3052          * delay them losing their interactive status
3053          */
3054         run_time /= (CURRENT_BONUS(prev) ? : 1);
3055
3056         spin_lock_irq(&rq->lock);
3057
3058         if (unlikely(prev->flags & PF_DEAD))
3059                 prev->state = EXIT_DEAD;
3060
3061         switch_count = &prev->nivcsw;
3062         if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3063                 switch_count = &prev->nvcsw;
3064                 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
3065                                 unlikely(signal_pending(prev))))
3066                         prev->state = TASK_RUNNING;
3067                 else {
3068                         if (prev->state == TASK_UNINTERRUPTIBLE) {
3069                                 rq->nr_uninterruptible++;
3070                                 vx_uninterruptible_inc(prev);
3071                         }
3072                         deactivate_task(prev, rq);
3073                 }
3074         }
3075
3076 #ifdef CONFIG_VSERVER_HARDCPU
3077 # ifdef CONFIG_VSERVER_ACB_SCHED
3078 drain_hold_queue:
3079
3080         min_guarantee_ticks = VX_INVALID_TICKS;
3081         min_best_effort_ticks = VX_INVALID_TICKS;
3082
3083 # endif 
3084         if (!list_empty(&rq->hold_queue)) {
3085                 struct list_head *l, *n;
3086                 int ret;
3087
3088                 vxi = NULL;
3089                 list_for_each_safe(l, n, &rq->hold_queue) {
3090                         next = list_entry(l, task_t, run_list);
3091                         if (vxi == next->vx_info)
3092                                 continue;
3093
3094                         vxi = next->vx_info;
3095                         ret = vx_tokens_recalc(vxi);
3096
3097                         if (ret > 0) {
3098                                 vx_unhold_task(vxi, next, rq);
3099                                 break;
3100                         }
3101                         if ((ret < 0) && (maxidle < ret))
3102                                 maxidle = ret;
3103 # ifdef CONFIG_VSERVER_ACB_SCHED
3104                         if (ret < 0) {
3105                                 if (IS_BEST_EFFORT(vxi)) {
3106                                         if (min_best_effort_ticks < ret) 
3107                                                 min_best_effort_ticks = ret;
3108                                 } else {
3109                                         if (min_guarantee_ticks < ret)
3110                                                 min_guarantee_ticks = ret;
3111                                 }
3112                         }
3113 # endif
3114                 }
3115         }
3116         rq->idle_tokens = -maxidle;
3117
3118 pick_next:
3119 #endif
3120
3121         cpu = smp_processor_id();
3122         if (unlikely(!rq->nr_running)) {
3123 go_idle:
3124                 idle_balance(cpu, rq);
3125                 if (!rq->nr_running) {
3126                         next = rq->idle;
3127                         rq->expired_timestamp = 0;
3128                         wake_sleeping_dependent(cpu, rq);
3129                         /*
3130                          * wake_sleeping_dependent() might have released
3131                          * the runqueue, so break out if we got new
3132                          * tasks meanwhile:
3133                          */
3134                         if (!rq->nr_running)
3135                                 goto switch_tasks;
3136                 }
3137         } else {
3138                 if (dependent_sleeper(cpu, rq)) {
3139                         next = rq->idle;
3140                         goto switch_tasks;
3141                 }
3142                 /*
3143                  * dependent_sleeper() releases and reacquires the runqueue
3144                  * lock, hence go into the idle loop if the rq went
3145                  * empty meanwhile:
3146                  */
3147                 if (unlikely(!rq->nr_running))
3148                         goto go_idle;
3149         }
3150
3151         array = rq->active;
3152         if (unlikely(!array->nr_active)) {
3153                 /*
3154                  * Switch the active and expired arrays.
3155                  */
3156                 schedstat_inc(rq, sched_switch);
3157                 rq->active = rq->expired;
3158                 rq->expired = array;
3159                 array = rq->active;
3160                 rq->expired_timestamp = 0;
3161                 rq->best_expired_prio = MAX_PRIO;
3162         }
3163
3164         idx = sched_find_first_bit(array->bitmap);
3165         queue = array->queue + idx;
3166         next = list_entry(queue->next, task_t, run_list);
3167
3168         vxi = next->vx_info;
3169 #ifdef  CONFIG_VSERVER_HARDCPU
3170         if (vx_info_flags(vxi, VXF_SCHED_PAUSE|VXF_SCHED_HARD, 0)) {
3171                 int ret = vx_tokens_recalc(vxi);
3172
3173                 if (unlikely(ret <= 0)) {
3174                         if (ret) {
3175                                 if ((rq->idle_tokens > -ret))
3176                                         rq->idle_tokens = -ret;
3177 # ifdef CONFIG_VSERVER_ACB_SCHED
3178                                 if (IS_BEST_EFFORT(vxi)) {
3179                                         if (min_best_effort_ticks < ret) 
3180                                                 min_best_effort_ticks = ret;
3181                                 } else {
3182                                         if (min_guarantee_ticks < ret)
3183                                                 min_guarantee_ticks = ret;
3184                                 }
3185 # endif
3186                         }
3187                         vx_hold_task(vxi, next, rq);
3188                         goto pick_next;
3189                 }
3190         } else  /* well, looks ugly but not as ugly as the ifdef-ed version */
3191 #endif
3192         if (vx_info_flags(vxi, VXF_SCHED_PRIO, 0))
3193                 vx_tokens_recalc(vxi);
3194
3195         if (!rt_task(next) && interactive_sleep(next->sleep_type)) {
3196                 unsigned long long delta = now - next->timestamp;
3197                 if (unlikely((long long)(now - next->timestamp) < 0))
3198                         delta = 0;
3199
3200                 if (next->sleep_type == SLEEP_INTERACTIVE)
3201                         delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
3202
3203                 array = next->array;
3204                 new_prio = recalc_task_prio(next, next->timestamp + delta);
3205
3206                 if (unlikely(next->prio != new_prio)) {
3207                         dequeue_task(next, array);
3208                         next->prio = new_prio;
3209                         enqueue_task(next, array);
3210                 }
3211         }
3212         next->sleep_type = SLEEP_NORMAL;
3213 switch_tasks:
3214 #if defined(CONFIG_VSERVER_HARDCPU) && defined(CONFIG_VSERVER_ACB_SCHED)
3215         if (next == rq->idle && !list_empty(&rq->hold_queue)) {
3216                 if (min_best_effort_ticks != VX_INVALID_TICKS) {
3217                         vx_advance_best_effort_ticks(-min_best_effort_ticks);
3218                         goto drain_hold_queue;
3219                 } 
3220                 if (min_guarantee_ticks != VX_INVALID_TICKS) {
3221                         vx_advance_guaranteed_ticks(-min_guarantee_ticks);
3222                         goto drain_hold_queue;
3223                 }
3224         }
3225 #endif
3226         if (next == rq->idle)
3227                 schedstat_inc(rq, sched_goidle);
3228         prefetch(next);
3229         prefetch_stack(next);
3230         clear_tsk_need_resched(prev);
3231         rcu_qsctr_inc(task_cpu(prev));
3232
3233         update_cpu_clock(prev, rq, now);
3234
3235         prev->sleep_avg -= run_time;
3236         if ((long)prev->sleep_avg <= 0)
3237                 prev->sleep_avg = 0;
3238         prev->timestamp = prev->last_ran = now;
3239
3240         sched_info_switch(prev, next);
3241         if (likely(prev != next)) {
3242                 next->timestamp = now;
3243                 rq->nr_switches++;
3244                 rq->curr = next;
3245                 ++*switch_count;
3246
3247                 prepare_task_switch(rq, next);
3248                 prev = context_switch(rq, prev, next);
3249                 barrier();
3250                 /*
3251                  * this_rq must be evaluated again because prev may have moved
3252                  * CPUs since it called schedule(), thus the 'rq' on its stack
3253                  * frame will be invalid.
3254                  */
3255                 finish_task_switch(this_rq(), prev);
3256         } else
3257                 spin_unlock_irq(&rq->lock);
3258
3259         prev = current;
3260         if (unlikely(reacquire_kernel_lock(prev) < 0))
3261                 goto need_resched_nonpreemptible;
3262         preempt_enable_no_resched();
3263         if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3264                 goto need_resched;
3265 }
3266
3267 EXPORT_SYMBOL(schedule);
3268
3269 #ifdef CONFIG_PREEMPT
3270 /*
3271  * this is is the entry point to schedule() from in-kernel preemption
3272  * off of preempt_enable.  Kernel preemptions off return from interrupt
3273  * occur there and call schedule directly.
3274  */
3275 asmlinkage void __sched preempt_schedule(void)
3276 {
3277         struct thread_info *ti = current_thread_info();
3278 #ifdef CONFIG_PREEMPT_BKL
3279         struct task_struct *task = current;
3280         int saved_lock_depth;
3281 #endif
3282         /*
3283          * If there is a non-zero preempt_count or interrupts are disabled,
3284          * we do not want to preempt the current task.  Just return..
3285          */
3286         if (unlikely(ti->preempt_count || irqs_disabled()))
3287                 return;
3288
3289 need_resched:
3290         add_preempt_count(PREEMPT_ACTIVE);
3291         /*
3292          * We keep the big kernel semaphore locked, but we
3293          * clear ->lock_depth so that schedule() doesnt
3294          * auto-release the semaphore:
3295          */
3296 #ifdef CONFIG_PREEMPT_BKL
3297         saved_lock_depth = task->lock_depth;
3298         task->lock_depth = -1;
3299 #endif
3300         schedule();
3301 #ifdef CONFIG_PREEMPT_BKL
3302         task->lock_depth = saved_lock_depth;
3303 #endif
3304         sub_preempt_count(PREEMPT_ACTIVE);
3305
3306         /* we could miss a preemption opportunity between schedule and now */
3307         barrier();
3308         if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3309                 goto need_resched;
3310 }
3311
3312 EXPORT_SYMBOL(preempt_schedule);
3313
3314 /*
3315  * this is is the entry point to schedule() from kernel preemption
3316  * off of irq context.
3317  * Note, that this is called and return with irqs disabled. This will
3318  * protect us against recursive calling from irq.
3319  */
3320 asmlinkage void __sched preempt_schedule_irq(void)
3321 {
3322         struct thread_info *ti = current_thread_info();
3323 #ifdef CONFIG_PREEMPT_BKL
3324         struct task_struct *task = current;
3325         int saved_lock_depth;
3326 #endif
3327         /* Catch callers which need to be fixed*/
3328         BUG_ON(ti->preempt_count || !irqs_disabled());
3329
3330 need_resched:
3331         add_preempt_count(PREEMPT_ACTIVE);
3332         /*
3333          * We keep the big kernel semaphore locked, but we
3334          * clear ->lock_depth so that schedule() doesnt
3335          * auto-release the semaphore:
3336          */
3337 #ifdef CONFIG_PREEMPT_BKL
3338         saved_lock_depth = task->lock_depth;
3339         task->lock_depth = -1;
3340 #endif
3341         local_irq_enable();
3342         schedule();
3343         local_irq_disable();
3344 #ifdef CONFIG_PREEMPT_BKL
3345         task->lock_depth = saved_lock_depth;
3346 #endif
3347         sub_preempt_count(PREEMPT_ACTIVE);
3348
3349         /* we could miss a preemption opportunity between schedule and now */
3350         barrier();
3351         if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3352                 goto need_resched;
3353 }
3354
3355 #endif /* CONFIG_PREEMPT */
3356
3357 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
3358                           void *key)
3359 {
3360         task_t *p = curr->private;
3361         return try_to_wake_up(p, mode, sync);
3362 }
3363
3364 EXPORT_SYMBOL(default_wake_function);
3365
3366 /*
3367  * The core wakeup function.  Non-exclusive wakeups (nr_exclusive == 0) just
3368  * wake everything up.  If it's an exclusive wakeup (nr_exclusive == small +ve
3369  * number) then we wake all the non-exclusive tasks and one exclusive task.
3370  *
3371  * There are circumstances in which we can try to wake a task which has already
3372  * started to run but is not in state TASK_RUNNING.  try_to_wake_up() returns
3373  * zero in this (rare) case, and we handle it by continuing to scan the queue.
3374  */
3375 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3376                              int nr_exclusive, int sync, void *key)
3377 {
3378         struct list_head *tmp, *next;
3379
3380         list_for_each_safe(tmp, next, &q->task_list) {
3381                 wait_queue_t *curr;
3382                 unsigned flags;
3383                 curr = list_entry(tmp, wait_queue_t, task_list);
3384                 flags = curr->flags;
3385                 if (curr->func(curr, mode, sync, key) &&
3386                     (flags & WQ_FLAG_EXCLUSIVE) &&
3387                     !--nr_exclusive)
3388                         break;
3389         }
3390 }
3391
3392 /**
3393  * __wake_up - wake up threads blocked on a waitqueue.
3394  * @q: the waitqueue
3395  * @mode: which threads
3396  * @nr_exclusive: how many wake-one or wake-many threads to wake up
3397  * @key: is directly passed to the wakeup function
3398  */
3399 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3400                         int nr_exclusive, void *key)
3401 {
3402         unsigned long flags;
3403
3404         spin_lock_irqsave(&q->lock, flags);
3405         __wake_up_common(q, mode, nr_exclusive, 0, key);
3406         spin_unlock_irqrestore(&q->lock, flags);
3407 }
3408
3409 EXPORT_SYMBOL(__wake_up);
3410
3411 /*
3412  * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3413  */
3414 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3415 {
3416         __wake_up_common(q, mode, 1, 0, NULL);
3417 }
3418
3419 /**
3420  * __wake_up_sync - wake up threads blocked on a waitqueue.
3421  * @q: the waitqueue
3422  * @mode: which threads
3423  * @nr_exclusive: how many wake-one or wake-many threads to wake up
3424  *
3425  * The sync wakeup differs that the waker knows that it will schedule
3426  * away soon, so while the target thread will be woken up, it will not
3427  * be migrated to another CPU - ie. the two threads are 'synchronized'
3428  * with each other. This can prevent needless bouncing between CPUs.
3429  *
3430  * On UP it can prevent extra preemption.
3431  */
3432 void fastcall
3433 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3434 {
3435         unsigned long flags;
3436         int sync = 1;
3437
3438         if (unlikely(!q))
3439                 return;
3440
3441         if (unlikely(!nr_exclusive))
3442                 sync = 0;
3443
3444         spin_lock_irqsave(&q->lock, flags);
3445         __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3446         spin_unlock_irqrestore(&q->lock, flags);
3447 }
3448 EXPORT_SYMBOL_GPL(__wake_up_sync);      /* For internal use only */
3449
3450 void fastcall complete(struct completion *x)
3451 {
3452         unsigned long flags;
3453
3454         spin_lock_irqsave(&x->wait.lock, flags);
3455         x->done++;
3456         __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3457                          1, 0, NULL);
3458         spin_unlock_irqrestore(&x->wait.lock, flags);
3459 }
3460 EXPORT_SYMBOL(complete);
3461
3462 void fastcall complete_all(struct completion *x)
3463 {
3464         unsigned long flags;
3465
3466         spin_lock_irqsave(&x->wait.lock, flags);
3467         x->done += UINT_MAX/2;
3468         __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3469                          0, 0, NULL);
3470         spin_unlock_irqrestore(&x->wait.lock, flags);
3471 }
3472 EXPORT_SYMBOL(complete_all);
3473
3474 void fastcall __sched wait_for_completion(struct completion *x)
3475 {
3476         might_sleep();
3477         spin_lock_irq(&x->wait.lock);
3478         if (!x->done) {
3479                 DECLARE_WAITQUEUE(wait, current);
3480
3481                 wait.flags |= WQ_FLAG_EXCLUSIVE;
3482                 __add_wait_queue_tail(&x->wait, &wait);
3483                 do {
3484                         __set_current_state(TASK_UNINTERRUPTIBLE);
3485                         spin_unlock_irq(&x->wait.lock);
3486                         schedule();
3487                         spin_lock_irq(&x->wait.lock);
3488                 } while (!x->done);
3489                 __remove_wait_queue(&x->wait, &wait);
3490         }
3491         x->done--;
3492         spin_unlock_irq(&x->wait.lock);
3493 }
3494 EXPORT_SYMBOL(wait_for_completion);
3495
3496 unsigned long fastcall __sched
3497 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3498 {
3499         might_sleep();
3500
3501         spin_lock_irq(&x->wait.lock);
3502         if (!x->done) {
3503                 DECLARE_WAITQUEUE(wait, current);
3504
3505                 wait.flags |= WQ_FLAG_EXCLUSIVE;
3506                 __add_wait_queue_tail(&x->wait, &wait);
3507                 do {
3508                         __set_current_state(TASK_UNINTERRUPTIBLE);
3509                         spin_unlock_irq(&x->wait.lock);
3510                         timeout = schedule_timeout(timeout);
3511                         spin_lock_irq(&x->wait.lock);
3512                         if (!timeout) {
3513                                 __remove_wait_queue(&x->wait, &wait);
3514                                 goto out;
3515                         }
3516                 } while (!x->done);
3517                 __remove_wait_queue(&x->wait, &wait);
3518         }
3519         x->done--;
3520 out:
3521         spin_unlock_irq(&x->wait.lock);
3522         return timeout;
3523 }
3524 EXPORT_SYMBOL(wait_for_completion_timeout);
3525
3526 int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3527 {
3528         int ret = 0;
3529
3530         might_sleep();
3531
3532         spin_lock_irq(&x->wait.lock);
3533         if (!x->done) {
3534                 DECLARE_WAITQUEUE(wait, current);
3535
3536                 wait.flags |= WQ_FLAG_EXCLUSIVE;
3537                 __add_wait_queue_tail(&x->wait, &wait);
3538                 do {
3539                         if (signal_pending(current)) {
3540                                 ret = -ERESTARTSYS;
3541                                 __remove_wait_queue(&x->wait, &wait);
3542                                 goto out;
3543                         }
3544                         __set_current_state(TASK_INTERRUPTIBLE);
3545                         spin_unlock_irq(&x->wait.lock);
3546                         schedule();
3547                         spin_lock_irq(&x->wait.lock);
3548                 } while (!x->done);
3549                 __remove_wait_queue(&x->wait, &wait);
3550         }
3551         x->done--;
3552 out:
3553         spin_unlock_irq(&x->wait.lock);
3554
3555         return ret;
3556 }
3557 EXPORT_SYMBOL(wait_for_completion_interruptible);
3558
3559 unsigned long fastcall __sched
3560 wait_for_completion_interruptible_timeout(struct completion *x,
3561                                           unsigned long timeout)
3562 {
3563         might_sleep();
3564
3565         spin_lock_irq(&x->wait.lock);
3566         if (!x->done) {
3567                 DECLARE_WAITQUEUE(wait, current);
3568
3569                 wait.flags |= WQ_FLAG_EXCLUSIVE;
3570                 __add_wait_queue_tail(&x->wait, &wait);
3571                 do {
3572                         if (signal_pending(current)) {
3573                                 timeout = -ERESTARTSYS;
3574                                 __remove_wait_queue(&x->wait, &wait);
3575                                 goto out;
3576                         }
3577                         __set_current_state(TASK_INTERRUPTIBLE);
3578                         spin_unlock_irq(&x->wait.lock);
3579                         timeout = schedule_timeout(timeout);
3580                         spin_lock_irq(&x->wait.lock);
3581                         if (!timeout) {
3582                                 __remove_wait_queue(&x->wait, &wait);
3583                                 goto out;
3584                         }
3585                 } while (!x->done);
3586                 __remove_wait_queue(&x->wait, &wait);
3587         }
3588         x->done--;
3589 out:
3590         spin_unlock_irq(&x->wait.lock);
3591         return timeout;
3592 }
3593 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3594
3595
3596 #define SLEEP_ON_VAR                                    \
3597         unsigned long flags;                            \
3598         wait_queue_t wait;                              \
3599         init_waitqueue_entry(&wait, current);
3600
3601 #define SLEEP_ON_HEAD                                   \
3602         spin_lock_irqsave(&q->lock,flags);              \
3603         __add_wait_queue(q, &wait);                     \
3604         spin_unlock(&q->lock);
3605
3606 #define SLEEP_ON_TAIL                                   \
3607         spin_lock_irq(&q->lock);                        \
3608         __remove_wait_queue(q, &wait);                  \
3609         spin_unlock_irqrestore(&q->lock, flags);
3610
3611 #define SLEEP_ON_BKLCHECK                               \
3612         if (unlikely(!kernel_locked()) &&               \
3613             sleep_on_bkl_warnings < 10) {               \
3614                 sleep_on_bkl_warnings++;                \
3615                 WARN_ON(1);                             \
3616         }
3617
3618 static int sleep_on_bkl_warnings;
3619
3620 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3621 {
3622         SLEEP_ON_VAR
3623
3624         SLEEP_ON_BKLCHECK
3625
3626         current->state = TASK_INTERRUPTIBLE;
3627
3628         SLEEP_ON_HEAD
3629         schedule();
3630         SLEEP_ON_TAIL
3631 }
3632
3633 EXPORT_SYMBOL(interruptible_sleep_on);
3634
3635 long fastcall __sched
3636 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3637 {
3638         SLEEP_ON_VAR
3639
3640         SLEEP_ON_BKLCHECK
3641
3642         current->state = TASK_INTERRUPTIBLE;
3643
3644         SLEEP_ON_HEAD
3645         timeout = schedule_timeout(timeout);
3646         SLEEP_ON_TAIL
3647
3648         return timeout;
3649 }
3650
3651 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3652
3653 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3654 {
3655         SLEEP_ON_VAR
3656
3657         SLEEP_ON_BKLCHECK
3658
3659         current->state = TASK_UNINTERRUPTIBLE;
3660
3661         SLEEP_ON_HEAD
3662         timeout = schedule_timeout(timeout);
3663         SLEEP_ON_TAIL
3664
3665         return timeout;
3666 }
3667
3668 EXPORT_SYMBOL(sleep_on_timeout);
3669
3670 void set_user_nice(task_t *p, long nice)
3671 {
3672         unsigned long flags;
3673         prio_array_t *array;
3674         runqueue_t *rq;
3675         int old_prio, new_prio, delta;
3676
3677         if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3678                 return;
3679         /*
3680          * We have to be careful, if called from sys_setpriority(),
3681          * the task might be in the middle of scheduling on another CPU.
3682          */
3683         rq = task_rq_lock(p, &flags);
3684         /*
3685          * The RT priorities are set via sched_setscheduler(), but we still
3686          * allow the 'normal' nice value to be set - but as expected
3687          * it wont have any effect on scheduling until the task is
3688          * not SCHED_NORMAL/SCHED_BATCH:
3689          */
3690         if (rt_task(p)) {
3691                 p->static_prio = NICE_TO_PRIO(nice);
3692                 goto out_unlock;
3693         }
3694         array = p->array;
3695         if (array)
3696                 dequeue_task(p, array);
3697
3698         old_prio = p->prio;
3699         new_prio = NICE_TO_PRIO(nice);
3700         delta = new_prio - old_prio;
3701         p->static_prio = NICE_TO_PRIO(nice);
3702         p->prio += delta;
3703
3704         if (array) {
3705                 enqueue_task(p, array);
3706                 /*
3707                  * If the task increased its priority or is running and
3708                  * lowered its priority, then reschedule its CPU:
3709                  */
3710                 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3711                         resched_task(rq->curr);
3712         }
3713 out_unlock:
3714         task_rq_unlock(rq, &flags);
3715 }
3716
3717 EXPORT_SYMBOL(set_user_nice);
3718
3719 /*
3720  * can_nice - check if a task can reduce its nice value
3721  * @p: task
3722  * @nice: nice value
3723  */
3724 int can_nice(const task_t *p, const int nice)
3725 {
3726         /* convert nice value [19,-20] to rlimit style value [1,40] */
3727         int nice_rlim = 20 - nice;
3728         return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
3729                 capable(CAP_SYS_NICE));
3730 }
3731
3732 #ifdef __ARCH_WANT_SYS_NICE
3733
3734 /*
3735  * sys_nice - change the priority of the current process.
3736  * @increment: priority increment
3737  *
3738  * sys_setpriority is a more generic, but much slower function that
3739  * does similar things.
3740  */
3741 asmlinkage long sys_nice(int increment)
3742 {
3743         int retval;
3744         long nice;
3745
3746         /*
3747          * Setpriority might change our priority at the same moment.
3748          * We don't have to worry. Conceptually one call occurs first
3749          * and we have a single winner.
3750          */
3751         if (increment < -40)
3752                 increment = -40;
3753         if (increment > 40)
3754                 increment = 40;
3755
3756         nice = PRIO_TO_NICE(current->static_prio) + increment;
3757         if (nice < -20)
3758                 nice = -20;
3759         if (nice > 19)
3760                 nice = 19;
3761
3762         if (increment < 0 && !can_nice(current, nice))
3763                 return vx_flags(VXF_IGNEG_NICE, 0) ? 0 : -EPERM;
3764
3765         retval = security_task_setnice(current, nice);
3766         if (retval)
3767                 return retval;
3768
3769         set_user_nice(current, nice);
3770         return 0;
3771 }
3772
3773 #endif
3774
3775 /**
3776  * task_prio - return the priority value of a given task.
3777  * @p: the task in question.
3778  *
3779  * This is the priority value as seen by users in /proc.
3780  * RT tasks are offset by -200. Normal tasks are centered
3781  * around 0, value goes from -16 to +15.
3782  */
3783 int task_prio(const task_t *p)
3784 {
3785         return p->prio - MAX_RT_PRIO;
3786 }
3787
3788 /**
3789  * task_nice - return the nice value of a given task.
3790  * @p: the task in question.
3791  */
3792 int task_nice(const task_t *p)
3793 {
3794         return TASK_NICE(p);
3795 }
3796 EXPORT_SYMBOL_GPL(task_nice);
3797
3798 /**
3799  * idle_cpu - is a given cpu idle currently?
3800  * @cpu: the processor in question.
3801  */
3802 int idle_cpu(int cpu)
3803 {
3804         return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3805 }
3806
3807 /**
3808  * idle_task - return the idle task for a given cpu.
3809  * @cpu: the processor in question.
3810  */
3811 task_t *idle_task(int cpu)
3812 {
3813         return cpu_rq(cpu)->idle;
3814 }
3815
3816 /**
3817  * find_process_by_pid - find a process with a matching PID value.
3818  * @pid: the pid in question.
3819  */
3820 static inline task_t *find_process_by_pid(pid_t pid)
3821 {
3822         return pid ? find_task_by_pid(pid) : current;
3823 }
3824
3825 /* Actually do priority change: must hold rq lock. */
3826 static void __setscheduler(struct task_struct *p, int policy, int prio)
3827 {
3828         BUG_ON(p->array);
3829         p->policy = policy;
3830         p->rt_priority = prio;
3831         if (policy != SCHED_NORMAL && policy != SCHED_BATCH) {
3832                 p->prio = MAX_RT_PRIO-1 - p->rt_priority;
3833         } else {
3834                 p->prio = p->static_prio;
3835                 /*
3836                  * SCHED_BATCH tasks are treated as perpetual CPU hogs:
3837                  */
3838                 if (policy == SCHED_BATCH)
3839                         p->sleep_avg = 0;
3840         }
3841 }
3842
3843 /**
3844  * sched_setscheduler - change the scheduling policy and/or RT priority of
3845  * a thread.
3846  * @p: the task in question.
3847  * @policy: new policy.
3848  * @param: structure containing the new RT priority.
3849  */
3850 int sched_setscheduler(struct task_struct *p, int policy,
3851                        struct sched_param *param)
3852 {
3853         int retval;
3854         int oldprio, oldpolicy = -1;
3855         prio_array_t *array;
3856         unsigned long flags;
3857         runqueue_t *rq;
3858
3859 recheck:
3860         /* double check policy once rq lock held */
3861         if (policy < 0)
3862                 policy = oldpolicy = p->policy;
3863         else if (policy != SCHED_FIFO && policy != SCHED_RR &&
3864                         policy != SCHED_NORMAL && policy != SCHED_BATCH)
3865                 return -EINVAL;
3866         /*
3867          * Valid priorities for SCHED_FIFO and SCHED_RR are
3868          * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL and
3869          * SCHED_BATCH is 0.
3870          */
3871         if (param->sched_priority < 0 ||
3872             (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
3873             (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
3874                 return -EINVAL;
3875         if ((policy == SCHED_NORMAL || policy == SCHED_BATCH)
3876                                         != (param->sched_priority == 0))
3877                 return -EINVAL;
3878
3879         /*
3880          * Allow unprivileged RT tasks to decrease priority:
3881          */
3882         if (!capable(CAP_SYS_NICE)) {
3883                 /*
3884                  * can't change policy, except between SCHED_NORMAL
3885                  * and SCHED_BATCH:
3886                  */
3887                 if (((policy != SCHED_NORMAL && p->policy != SCHED_BATCH) &&
3888                         (policy != SCHED_BATCH && p->policy != SCHED_NORMAL)) &&
3889                                 !p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
3890                         return -EPERM;
3891                 /* can't increase priority */
3892                 if ((policy != SCHED_NORMAL && policy != SCHED_BATCH) &&
3893                     param->sched_priority > p->rt_priority &&
3894                     param->sched_priority >
3895                                 p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
3896                         return -EPERM;
3897                 /* can't change other user's priorities */
3898                 if ((current->euid != p->euid) &&
3899                     (current->euid != p->uid))
3900                         return -EPERM;
3901         }
3902
3903         retval = security_task_setscheduler(p, policy, param);
3904         if (retval)
3905                 return retval;
3906         /*
3907          * To be able to change p->policy safely, the apropriate
3908          * runqueue lock must be held.
3909          */
3910         rq = task_rq_lock(p, &flags);
3911         /* recheck policy now with rq lock held */
3912         if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3913                 policy = oldpolicy = -1;
3914                 task_rq_unlock(rq, &flags);
3915                 goto recheck;
3916         }
3917         array = p->array;
3918         if (array)
3919                 deactivate_task(p, rq);
3920         oldprio = p->prio;
3921         __setscheduler(p, policy, param->sched_priority);
3922         if (array) {
3923                 vx_activate_task(p);
3924                 __activate_task(p, rq);
3925                 /*
3926                  * Reschedule if we are currently running on this runqueue and
3927                  * our priority decreased, or if we are not currently running on
3928                  * this runqueue and our priority is higher than the current's
3929                  */
3930                 if (task_running(rq, p)) {
3931                         if (p->prio > oldprio)
3932                                 resched_task(rq->curr);
3933                 } else if (TASK_PREEMPTS_CURR(p, rq))
3934                         resched_task(rq->curr);
3935         }
3936         task_rq_unlock(rq, &flags);
3937         return 0;
3938 }
3939 EXPORT_SYMBOL_GPL(sched_setscheduler);
3940
3941 static int
3942 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3943 {
3944         int retval;
3945         struct sched_param lparam;
3946         struct task_struct *p;
3947
3948         if (!param || pid < 0)
3949                 return -EINVAL;
3950         if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
3951                 return -EFAULT;
3952         read_lock_irq(&tasklist_lock);
3953         p = find_process_by_pid(pid);
3954         if (!p) {
3955                 read_unlock_irq(&tasklist_lock);
3956                 return -ESRCH;
3957         }
3958         retval = sched_setscheduler(p, policy, &lparam);
3959         read_unlock_irq(&tasklist_lock);
3960         return retval;
3961 }
3962
3963 /**
3964  * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3965  * @pid: the pid in question.
3966  * @policy: new policy.
3967  * @param: structure containing the new RT priority.
3968  */
3969 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3970                                        struct sched_param __user *param)
3971 {
3972         /* negative values for policy are not valid */
3973         if (policy < 0)
3974                 return -EINVAL;
3975
3976         return do_sched_setscheduler(pid, policy, param);
3977 }
3978
3979 /**
3980  * sys_sched_setparam - set/change the RT priority of a thread
3981  * @pid: the pid in question.
3982  * @param: structure containing the new RT priority.
3983  */
3984 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3985 {
3986         return do_sched_setscheduler(pid, -1, param);
3987 }
3988
3989 /**
3990  * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3991  * @pid: the pid in question.
3992  */
3993 asmlinkage long sys_sched_getscheduler(pid_t pid)
3994 {
3995         int retval = -EINVAL;
3996         task_t *p;
3997
3998         if (pid < 0)
3999                 goto out_nounlock;
4000
4001         retval = -ESRCH;
4002         read_lock(&tasklist_lock);
4003         p = find_process_by_pid(pid);
4004         if (p) {
4005                 retval = security_task_getscheduler(p);
4006                 if (!retval)
4007                         retval = p->policy;
4008         }
4009         read_unlock(&tasklist_lock);
4010
4011 out_nounlock:
4012         return retval;
4013 }
4014
4015 /**
4016  * sys_sched_getscheduler - get the RT priority of a thread
4017  * @pid: the pid in question.
4018  * @param: structure containing the RT priority.
4019  */
4020 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
4021 {
4022         struct sched_param lp;
4023         int retval = -EINVAL;
4024         task_t *p;
4025
4026         if (!param || pid < 0)
4027                 goto out_nounlock;
4028
4029         read_lock(&tasklist_lock);
4030         p = find_process_by_pid(pid);
4031         retval = -ESRCH;
4032         if (!p)
4033                 goto out_unlock;
4034
4035         retval = security_task_getscheduler(p);
4036         if (retval)
4037                 goto out_unlock;
4038
4039         lp.sched_priority = p->rt_priority;
4040         read_unlock(&tasklist_lock);
4041
4042         /*
4043          * This one might sleep, we cannot do it with a spinlock held ...
4044          */
4045         retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4046
4047 out_nounlock:
4048         return retval;
4049
4050 out_unlock:
4051         read_unlock(&tasklist_lock);
4052         return retval;
4053 }
4054
4055 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
4056 {
4057         task_t *p;
4058         int retval;
4059         cpumask_t cpus_allowed;
4060
4061         lock_cpu_hotplug();
4062         read_lock(&tasklist_lock);
4063
4064         p = find_process_by_pid(pid);
4065         if (!p) {
4066                 read_unlock(&tasklist_lock);
4067                 unlock_cpu_hotplug();
4068                 return -ESRCH;
4069         }
4070
4071         /*
4072          * It is not safe to call set_cpus_allowed with the
4073          * tasklist_lock held.  We will bump the task_struct's
4074          * usage count and then drop tasklist_lock.
4075          */
4076         get_task_struct(p);
4077         read_unlock(&tasklist_lock);
4078
4079         retval = -EPERM;
4080         if ((current->euid != p->euid) && (current->euid != p->uid) &&
4081                         !capable(CAP_SYS_NICE))
4082                 goto out_unlock;
4083
4084         cpus_allowed = cpuset_cpus_allowed(p);
4085         cpus_and(new_mask, new_mask, cpus_allowed);
4086         retval = set_cpus_allowed(p, new_mask);
4087
4088 out_unlock:
4089         put_task_struct(p);
4090         unlock_cpu_hotplug();
4091         return retval;
4092 }
4093
4094 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4095                              cpumask_t *new_mask)
4096 {
4097         if (len < sizeof(cpumask_t)) {
4098                 memset(new_mask, 0, sizeof(cpumask_t));
4099         } else if (len > sizeof(cpumask_t)) {
4100                 len = sizeof(cpumask_t);
4101         }
4102         return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4103 }
4104
4105 /**
4106  * sys_sched_setaffinity - set the cpu affinity of a process
4107  * @pid: pid of the process
4108  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4109  * @user_mask_ptr: user-space pointer to the new cpu mask
4110  */
4111 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
4112                                       unsigned long __user *user_mask_ptr)
4113 {
4114         cpumask_t new_mask;
4115         int retval;
4116
4117         retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
4118         if (retval)
4119                 return retval;
4120
4121         return sched_setaffinity(pid, new_mask);
4122 }
4123
4124 /*
4125  * Represents all cpu's present in the system
4126  * In systems capable of hotplug, this map could dynamically grow
4127  * as new cpu's are detected in the system via any platform specific
4128  * method, such as ACPI for e.g.
4129  */
4130
4131 cpumask_t cpu_present_map __read_mostly;
4132 EXPORT_SYMBOL(cpu_present_map);
4133
4134 #ifndef CONFIG_SMP
4135 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
4136 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
4137 #endif
4138
4139 long sched_getaffinity(pid_t pid, cpumask_t *mask)
4140 {
4141         int retval;
4142         task_t *p;
4143
4144         lock_cpu_hotplug();
4145         read_lock(&tasklist_lock);
4146
4147         retval = -ESRCH;
4148         p = find_process_by_pid(pid);
4149         if (!p)
4150                 goto out_unlock;
4151
4152         retval = 0;
4153         cpus_and(*mask, p->cpus_allowed, cpu_online_map);
4154
4155 out_unlock:
4156         read_unlock(&tasklist_lock);
4157         unlock_cpu_hotplug();
4158         if (retval)
4159                 return retval;
4160
4161         return 0;
4162 }
4163
4164 /**
4165  * sys_sched_getaffinity - get the cpu affinity of a process
4166  * @pid: pid of the process
4167  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4168  * @user_mask_ptr: user-space pointer to hold the current cpu mask
4169  */
4170 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
4171                                       unsigned long __user *user_mask_ptr)
4172 {
4173         int ret;
4174         cpumask_t mask;
4175
4176         if (len < sizeof(cpumask_t))
4177                 return -EINVAL;
4178
4179         ret = sched_getaffinity(pid, &mask);
4180         if (ret < 0)
4181                 return ret;
4182
4183         if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
4184                 return -EFAULT;
4185
4186         return sizeof(cpumask_t);
4187 }
4188
4189 /**
4190  * sys_sched_yield - yield the current processor to other threads.
4191  *
4192  * this function yields the current CPU by moving the calling thread
4193  * to the expired array. If there are no other threads running on this
4194  * CPU then this function will return.
4195  */
4196 asmlinkage long sys_sched_yield(void)
4197 {
4198         runqueue_t *rq = this_rq_lock();
4199         prio_array_t *array = current->array;
4200         prio_array_t *target = rq->expired;
4201
4202         schedstat_inc(rq, yld_cnt);
4203         /*
4204          * We implement yielding by moving the task into the expired
4205          * queue.
4206          *
4207          * (special rule: RT tasks will just roundrobin in the active
4208          *  array.)
4209          */
4210         if (rt_task(current))
4211                 target = rq->active;
4212
4213         if (array->nr_active == 1) {
4214                 schedstat_inc(rq, yld_act_empty);
4215                 if (!rq->expired->nr_active)
4216                         schedstat_inc(rq, yld_both_empty);
4217         } else if (!rq->expired->nr_active)
4218                 schedstat_inc(rq, yld_exp_empty);
4219
4220         if (array != target) {
4221                 dequeue_task(current, array);
4222                 enqueue_task(current, target);
4223         } else
4224                 /*
4225                  * requeue_task is cheaper so perform that if possible.
4226                  */
4227                 requeue_task(current, array);
4228
4229         /*
4230          * Since we are going to call schedule() anyway, there's
4231          * no need to preempt or enable interrupts:
4232          */
4233         __release(rq->lock);
4234         _raw_spin_unlock(&rq->lock);
4235         preempt_enable_no_resched();
4236
4237         schedule();
4238
4239         return 0;
4240 }
4241
4242 static inline int __resched_legal(int expected_preempt_count)
4243 {
4244         if (unlikely(preempt_count() != expected_preempt_count))
4245                 return 0;
4246         if (unlikely(system_state != SYSTEM_RUNNING))
4247                 return 0;
4248         return 1;
4249 }
4250
4251 static void __cond_resched(void)
4252 {
4253         /*
4254          * The BKS might be reacquired before we have dropped
4255          * PREEMPT_ACTIVE, which could trigger a second
4256          * cond_resched() call.
4257          */
4258         do {
4259                 add_preempt_count(PREEMPT_ACTIVE);
4260                 schedule();
4261                 sub_preempt_count(PREEMPT_ACTIVE);
4262         } while (need_resched());
4263 }
4264
4265 int __sched cond_resched(void)
4266 {
4267         if (need_resched() && __resched_legal(0)) {
4268                 __cond_resched();
4269                 return 1;
4270         }
4271         return 0;
4272 }
4273 EXPORT_SYMBOL(cond_resched);
4274
4275 /*
4276  * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4277  * call schedule, and on return reacquire the lock.
4278  *
4279  * This works OK both with and without CONFIG_PREEMPT.  We do strange low-level
4280  * operations here to prevent schedule() from being called twice (once via
4281  * spin_unlock(), once by hand).
4282  */
4283 int cond_resched_lock(spinlock_t *lock)
4284 {
4285         int ret = 0;
4286
4287         if (need_lockbreak(lock)) {
4288                 spin_unlock(lock);
4289                 cpu_relax();
4290                 ret = 1;
4291                 spin_lock(lock);
4292         }
4293         if (need_resched() && __resched_legal(1)) {
4294                 _raw_spin_unlock(lock);
4295                 preempt_enable_no_resched();
4296                 __cond_resched();
4297                 ret = 1;
4298                 spin_lock(lock);
4299         }
4300         return ret;
4301 }
4302 EXPORT_SYMBOL(cond_resched_lock);
4303
4304 int __sched cond_resched_softirq(void)
4305 {
4306         BUG_ON(!in_softirq());
4307
4308         if (need_resched() && __resched_legal(0)) {
4309                 __local_bh_enable();
4310                 __cond_resched();
4311                 local_bh_disable();
4312                 return 1;
4313         }
4314         return 0;
4315 }
4316 EXPORT_SYMBOL(cond_resched_softirq);
4317
4318 /**
4319  * yield - yield the current processor to other threads.
4320  *
4321  * this is a shortcut for kernel-space yielding - it marks the
4322  * thread runnable and calls sys_sched_yield().
4323  */
4324 void __sched yield(void)
4325 {
4326         set_current_state(TASK_RUNNING);
4327         sys_sched_yield();
4328 }
4329
4330 EXPORT_SYMBOL(yield);
4331
4332 /*
4333  * This task is about to go to sleep on IO.  Increment rq->nr_iowait so
4334  * that process accounting knows that this is a task in IO wait state.
4335  *
4336  * But don't do that if it is a deliberate, throttling IO wait (this task
4337  * has set its backing_dev_info: the queue against which it should throttle)
4338  */
4339 void __sched io_schedule(void)
4340 {
4341         struct runqueue *rq = &per_cpu(runqueues, raw_smp_processor_id());
4342
4343         atomic_inc(&rq->nr_iowait);
4344         schedule();
4345         atomic_dec(&rq->nr_iowait);
4346 }
4347
4348 EXPORT_SYMBOL(io_schedule);
4349
4350 long __sched io_schedule_timeout(long timeout)
4351 {
4352         struct runqueue *rq = &per_cpu(runqueues, raw_smp_processor_id());
4353         long ret;
4354
4355         atomic_inc(&rq->nr_iowait);
4356         ret = schedule_timeout(timeout);
4357         atomic_dec(&rq->nr_iowait);
4358         return ret;
4359 }
4360
4361 /**
4362  * sys_sched_get_priority_max - return maximum RT priority.
4363  * @policy: scheduling class.
4364  *
4365  * this syscall returns the maximum rt_priority that can be used
4366  * by a given scheduling class.
4367  */
4368 asmlinkage long sys_sched_get_priority_max(int policy)
4369 {
4370         int ret = -EINVAL;
4371
4372         switch (policy) {
4373         case SCHED_FIFO:
4374         case SCHED_RR:
4375                 ret = MAX_USER_RT_PRIO-1;
4376                 break;
4377         case SCHED_NORMAL:
4378         case SCHED_BATCH:
4379                 ret = 0;
4380                 break;
4381         }
4382         return ret;
4383 }
4384
4385 /**
4386  * sys_sched_get_priority_min - return minimum RT priority.
4387  * @policy: scheduling class.
4388  *
4389  * this syscall returns the minimum rt_priority that can be used
4390  * by a given scheduling class.
4391  */
4392 asmlinkage long sys_sched_get_priority_min(int policy)
4393 {
4394         int ret = -EINVAL;
4395
4396         switch (policy) {
4397         case SCHED_FIFO:
4398         case SCHED_RR:
4399                 ret = 1;
4400                 break;
4401         case SCHED_NORMAL:
4402         case SCHED_BATCH:
4403                 ret = 0;
4404         }
4405         return ret;
4406 }
4407
4408 /**
4409  * sys_sched_rr_get_interval - return the default timeslice of a process.
4410  * @pid: pid of the process.
4411  * @interval: userspace pointer to the timeslice value.
4412  *
4413  * this syscall writes the default timeslice value of a given process
4414  * into the user-space timespec buffer. A value of '0' means infinity.
4415  */
4416 asmlinkage
4417 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4418 {
4419         int retval = -EINVAL;
4420         struct timespec t;
4421         task_t *p;
4422
4423         if (pid < 0)
4424                 goto out_nounlock;
4425
4426         retval = -ESRCH;
4427         read_lock(&tasklist_lock);
4428         p = find_process_by_pid(pid);
4429         if (!p)
4430                 goto out_unlock;
4431
4432         retval = security_task_getscheduler(p);
4433         if (retval)
4434                 goto out_unlock;
4435
4436         jiffies_to_timespec(p->policy & SCHED_FIFO ?
4437                                 0 : task_timeslice(p), &t);
4438         read_unlock(&tasklist_lock);
4439         retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4440 out_nounlock:
4441         return retval;
4442 out_unlock:
4443         read_unlock(&tasklist_lock);
4444         return retval;
4445 }
4446
4447 static inline struct task_struct *eldest_child(struct task_struct *p)
4448 {
4449         if (list_empty(&p->children)) return NULL;
4450         return list_entry(p->children.next,struct task_struct,sibling);
4451 }
4452
4453 static inline struct task_struct *older_sibling(struct task_struct *p)
4454 {
4455         if (p->sibling.prev==&p->parent->children) return NULL;
4456         return list_entry(p->sibling.prev,struct task_struct,sibling);
4457 }
4458
4459 static inline struct task_struct *younger_sibling(struct task_struct *p)
4460 {
4461         if (p->sibling.next==&p->parent->children) return NULL;
4462         return list_entry(p->sibling.next,struct task_struct,sibling);
4463 }
4464
4465 static void show_task(task_t *p)
4466 {
4467         task_t *relative;
4468         unsigned state;
4469         unsigned long free = 0;
4470         static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
4471
4472         printk("%-13.13s ", p->comm);
4473         state = p->state ? __ffs(p->state) + 1 : 0;
4474         if (state < ARRAY_SIZE(stat_nam))
4475                 printk(stat_nam[state]);
4476         else
4477                 printk("?");
4478 #if (BITS_PER_LONG == 32)
4479         if (state == TASK_RUNNING)
4480                 printk(" running ");
4481         else
4482                 printk(" %08lX ", thread_saved_pc(p));
4483 #else
4484         if (state == TASK_RUNNING)
4485                 printk("  running task   ");
4486         else
4487                 printk(" %016lx ", thread_saved_pc(p));
4488 #endif
4489 #ifdef CONFIG_DEBUG_STACK_USAGE
4490         {
4491                 unsigned long *n = end_of_stack(p);
4492                 while (!*n)
4493                         n++;
4494                 free = (unsigned long)n - (unsigned long)end_of_stack(p);
4495         }
4496 #endif
4497         printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
4498         if ((relative = eldest_child(p)))
4499                 printk("%5d ", relative->pid);
4500         else
4501                 printk("      ");
4502         if ((relative = younger_sibling(p)))
4503                 printk("%7d", relative->pid);
4504         else
4505                 printk("       ");
4506         if ((relative = older_sibling(p)))
4507                 printk(" %5d", relative->pid);
4508         else
4509                 printk("      ");
4510         if (!p->mm)
4511                 printk(" (L-TLB)\n");
4512         else
4513                 printk(" (NOTLB)\n");
4514
4515         if (state != TASK_RUNNING)
4516                 show_stack(p, NULL);
4517 }
4518
4519 void show_state(void)
4520 {
4521         task_t *g, *p;
4522
4523 #if (BITS_PER_LONG == 32)
4524         printk("\n"
4525                "                                               sibling\n");
4526         printk("  task             PC      pid father child younger older\n");
4527 #else
4528         printk("\n"
4529                "                                                       sibling\n");
4530         printk("  task                 PC          pid father child younger older\n");
4531 #endif
4532         read_lock(&tasklist_lock);
4533         do_each_thread(g, p) {
4534                 /*
4535                  * reset the NMI-timeout, listing all files on a slow
4536                  * console might take alot of time:
4537                  */
4538                 touch_nmi_watchdog();
4539                 show_task(p);
4540         } while_each_thread(g, p);
4541
4542         read_unlock(&tasklist_lock);
4543         mutex_debug_show_all_locks();
4544 }
4545
4546 /**
4547  * init_idle - set up an idle thread for a given CPU
4548  * @idle: task in question
4549  * @cpu: cpu the idle task belongs to
4550  *
4551  * NOTE: this function does not set the idle thread's NEED_RESCHED
4552  * flag, to make booting more robust.
4553  */
4554 void __devinit init_idle(task_t *idle, int cpu)
4555 {
4556         runqueue_t *rq = cpu_rq(cpu);
4557         unsigned long flags;
4558
4559         idle->timestamp = sched_clock();
4560         idle->sleep_avg = 0;
4561         idle->array = NULL;
4562         idle->prio = MAX_PRIO;
4563         idle->state = TASK_RUNNING;
4564         idle->cpus_allowed = cpumask_of_cpu(cpu);
4565         set_task_cpu(idle, cpu);
4566
4567         spin_lock_irqsave(&rq->lock, flags);
4568         rq->curr = rq->idle = idle;
4569 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
4570         idle->oncpu = 1;
4571 #endif
4572         spin_unlock_irqrestore(&rq->lock, flags);
4573
4574         /* Set the preempt count _outside_ the spinlocks! */
4575 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4576         task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
4577 #else
4578         task_thread_info(idle)->preempt_count = 0;
4579 #endif
4580 }
4581
4582 /*
4583  * In a system that switches off the HZ timer nohz_cpu_mask
4584  * indicates which cpus entered this state. This is used
4585  * in the rcu update to wait only for active cpus. For system
4586  * which do not switch off the HZ timer nohz_cpu_mask should
4587  * always be CPU_MASK_NONE.
4588  */
4589 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4590
4591 #ifdef CONFIG_SMP
4592 /*
4593  * This is how migration works:
4594  *
4595  * 1) we queue a migration_req_t structure in the source CPU's
4596  *    runqueue and wake up that CPU's migration thread.
4597  * 2) we down() the locked semaphore => thread blocks.
4598  * 3) migration thread wakes up (implicitly it forces the migrated
4599  *    thread off the CPU)
4600  * 4) it gets the migration request and checks whether the migrated
4601  *    task is still in the wrong runqueue.
4602  * 5) if it's in the wrong runqueue then the migration thread removes
4603  *    it and puts it into the right queue.
4604  * 6) migration thread up()s the semaphore.
4605  * 7) we wake up and the migration is done.
4606  */
4607
4608 /*
4609  * Change a given task's CPU affinity. Migrate the thread to a
4610  * proper CPU and schedule it away if the CPU it's executing on
4611  * is removed from the allowed bitmask.
4612  *
4613  * NOTE: the caller must have a valid reference to the task, the
4614  * task must not exit() & deallocate itself prematurely.  The
4615  * call is not atomic; no spinlocks may be held.
4616  */
4617 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
4618 {
4619         unsigned long flags;
4620         int ret = 0;
4621         migration_req_t req;
4622         runqueue_t *rq;
4623
4624         rq = task_rq_lock(p, &flags);
4625         if (!cpus_intersects(new_mask, cpu_online_map)) {
4626                 ret = -EINVAL;
4627                 goto out;
4628         }
4629
4630         p->cpus_allowed = new_mask;
4631         /* Can the task run on the task's current CPU? If so, we're done */
4632         if (cpu_isset(task_cpu(p), new_mask))
4633                 goto out;
4634
4635         if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4636                 /* Need help from migration thread: drop lock and wait. */
4637                 task_rq_unlock(rq, &flags);
4638                 wake_up_process(rq->migration_thread);
4639                 wait_for_completion(&req.done);
4640                 tlb_migrate_finish(p->mm);
4641                 return 0;
4642         }
4643 out:
4644         task_rq_unlock(rq, &flags);
4645         return ret;
4646 }
4647
4648 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4649
4650 /*
4651  * Move (not current) task off this cpu, onto dest cpu.  We're doing
4652  * this because either it can't run here any more (set_cpus_allowed()
4653  * away from this CPU, or CPU going down), or because we're
4654  * attempting to rebalance this task on exec (sched_exec).
4655  *
4656  * So we race with normal scheduler movements, but that's OK, as long
4657  * as the task is no longer on this CPU.
4658  */
4659 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4660 {
4661         runqueue_t *rq_dest, *rq_src;
4662
4663         if (unlikely(cpu_is_offline(dest_cpu)))
4664                 return;
4665
4666         rq_src = cpu_rq(src_cpu);
4667         rq_dest = cpu_rq(dest_cpu);
4668
4669         double_rq_lock(rq_src, rq_dest);
4670         /* Already moved. */
4671         if (task_cpu(p) != src_cpu)
4672                 goto out;
4673         /* Affinity changed (again). */
4674         if (!cpu_isset(dest_cpu, p->cpus_allowed))
4675                 goto out;
4676
4677         set_task_cpu(p, dest_cpu);
4678         if (p->array) {
4679                 /*
4680                  * Sync timestamp with rq_dest's before activating.
4681                  * The same thing could be achieved by doing this step
4682                  * afterwards, and pretending it was a local activate.
4683                  * This way is cleaner and logically correct.
4684                  */
4685                 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4686                                 + rq_dest->timestamp_last_tick;
4687                 deactivate_task(p, rq_src);
4688                 activate_task(p, rq_dest, 0);
4689                 if (TASK_PREEMPTS_CURR(p, rq_dest))
4690                         resched_task(rq_dest->curr);
4691         }
4692
4693 out:
4694         double_rq_unlock(rq_src, rq_dest);
4695 }
4696
4697 /*
4698  * migration_thread - this is a highprio system thread that performs
4699  * thread migration by bumping thread off CPU then 'pushing' onto
4700  * another runqueue.
4701  */
4702 static int migration_thread(void *data)
4703 {
4704         runqueue_t *rq;
4705         int cpu = (long)data;
4706
4707         rq = cpu_rq(cpu);
4708         BUG_ON(rq->migration_thread != current);
4709
4710         set_current_state(TASK_INTERRUPTIBLE);
4711         while (!kthread_should_stop()) {
4712                 struct list_head *head;
4713                 migration_req_t *req;
4714
4715                 try_to_freeze();
4716
4717                 spin_lock_irq(&rq->lock);
4718
4719                 if (cpu_is_offline(cpu)) {
4720                         spin_unlock_irq(&rq->lock);
4721                         goto wait_to_die;
4722                 }
4723
4724                 if (rq->active_balance) {
4725                         active_load_balance(rq, cpu);
4726                         rq->active_balance = 0;
4727                 }
4728
4729                 head = &rq->migration_queue;
4730
4731                 if (list_empty(head)) {
4732                         spin_unlock_irq(&rq->lock);
4733                         schedule();
4734                         set_current_state(TASK_INTERRUPTIBLE);
4735                         continue;
4736                 }
4737                 req = list_entry(head->next, migration_req_t, list);
4738                 list_del_init(head->next);
4739
4740                 spin_unlock(&rq->lock);
4741                 __migrate_task(req->task, cpu, req->dest_cpu);
4742                 local_irq_enable();
4743
4744                 complete(&req->done);
4745         }
4746         __set_current_state(TASK_RUNNING);
4747         return 0;
4748
4749 wait_to_die:
4750         /* Wait for kthread_stop */
4751         set_current_state(TASK_INTERRUPTIBLE);
4752         while (!kthread_should_stop()) {
4753                 schedule();
4754                 set_current_state(TASK_INTERRUPTIBLE);
4755         }
4756         __set_current_state(TASK_RUNNING);
4757         return 0;
4758 }
4759
4760 #ifdef CONFIG_HOTPLUG_CPU
4761 /* Figure out where task on dead CPU should go, use force if neccessary. */
4762 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
4763 {
4764         int dest_cpu;
4765         cpumask_t mask;
4766
4767         /* On same node? */
4768         mask = node_to_cpumask(cpu_to_node(dead_cpu));
4769         cpus_and(mask, mask, tsk->cpus_allowed);
4770         dest_cpu = any_online_cpu(mask);
4771
4772         /* On any allowed CPU? */
4773         if (dest_cpu == NR_CPUS)
4774                 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4775
4776         /* No more Mr. Nice Guy. */
4777         if (dest_cpu == NR_CPUS) {
4778                 cpus_setall(tsk->cpus_allowed);
4779                 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4780
4781                 /*
4782                  * Don't tell them about moving exiting tasks or
4783                  * kernel threads (both mm NULL), since they never
4784                  * leave kernel.
4785                  */
4786                 if (tsk->mm && printk_ratelimit())
4787                         printk(KERN_INFO "process %d (%s) no "
4788                                "longer affine to cpu%d\n",
4789                                tsk->pid, tsk->comm, dead_cpu);
4790         }
4791         __migrate_task(tsk, dead_cpu, dest_cpu);
4792 }
4793
4794 /*
4795  * While a dead CPU has no uninterruptible tasks queued at this point,
4796  * it might still have a nonzero ->nr_uninterruptible counter, because
4797  * for performance reasons the counter is not stricly tracking tasks to
4798  * their home CPUs. So we just add the counter to another CPU's counter,
4799  * to keep the global sum constant after CPU-down:
4800  */
4801 static void migrate_nr_uninterruptible(runqueue_t *rq_src)
4802 {
4803         runqueue_t *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
4804         unsigned long flags;
4805
4806         local_irq_save(flags);
4807         double_rq_lock(rq_src, rq_dest);
4808         rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
4809         rq_src->nr_uninterruptible = 0;
4810         double_rq_unlock(rq_src, rq_dest);
4811         local_irq_restore(flags);
4812 }
4813
4814 /* Run through task list and migrate tasks from the dead cpu. */
4815 static void migrate_live_tasks(int src_cpu)
4816 {
4817         struct task_struct *tsk, *t;
4818
4819         write_lock_irq(&tasklist_lock);
4820
4821         do_each_thread(t, tsk) {
4822                 if (tsk == current)
4823                         continue;
4824
4825                 if (task_cpu(tsk) == src_cpu)
4826                         move_task_off_dead_cpu(src_cpu, tsk);
4827         } while_each_thread(t, tsk);
4828
4829         write_unlock_irq(&tasklist_lock);
4830 }
4831
4832 /* Schedules idle task to be the next runnable task on current CPU.
4833  * It does so by boosting its priority to highest possible and adding it to
4834  * the _front_ of runqueue. Used by CPU offline code.
4835  */
4836 void sched_idle_next(void)
4837 {
4838         int cpu = smp_processor_id();
4839         runqueue_t *rq = this_rq();
4840         struct task_struct *p = rq->idle;
4841         unsigned long flags;
4842
4843         /* cpu has to be offline */
4844         BUG_ON(cpu_online(cpu));
4845
4846         /* Strictly not necessary since rest of the CPUs are stopped by now
4847          * and interrupts disabled on current cpu.
4848          */
4849         spin_lock_irqsave(&rq->lock, flags);
4850
4851         __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4852         /* Add idle task to _front_ of it's priority queue */
4853         __activate_idle_task(p, rq);
4854
4855         spin_unlock_irqrestore(&rq->lock, flags);
4856 }
4857
4858 /* Ensures that the idle task is using init_mm right before its cpu goes
4859  * offline.
4860  */
4861 void idle_task_exit(void)
4862 {
4863         struct mm_struct *mm = current->active_mm;
4864
4865         BUG_ON(cpu_online(smp_processor_id()));
4866
4867         if (mm != &init_mm)
4868                 switch_mm(mm, &init_mm, current);
4869         mmdrop(mm);
4870 }
4871
4872 static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
4873 {
4874         struct runqueue *rq = cpu_rq(dead_cpu);
4875
4876         /* Must be exiting, otherwise would be on tasklist. */
4877         BUG_ON(tsk->exit_state != EXIT_ZOMBIE && tsk->exit_state != EXIT_DEAD);
4878
4879         /* Cannot have done final schedule yet: would have vanished. */
4880         BUG_ON(tsk->flags & PF_DEAD);
4881
4882         get_task_struct(tsk);
4883
4884         /*
4885          * Drop lock around migration; if someone else moves it,
4886          * that's OK.  No task can be added to this CPU, so iteration is
4887          * fine.
4888          */
4889         spin_unlock_irq(&rq->lock);
4890         move_task_off_dead_cpu(dead_cpu, tsk);
4891         spin_lock_irq(&rq->lock);
4892
4893         put_task_struct(tsk);
4894 }
4895
4896 /* release_task() removes task from tasklist, so we won't find dead tasks. */
4897 static void migrate_dead_tasks(unsigned int dead_cpu)
4898 {
4899         unsigned arr, i;
4900         struct runqueue *rq = cpu_rq(dead_cpu);
4901
4902         for (arr = 0; arr < 2; arr++) {
4903                 for (i = 0; i < MAX_PRIO; i++) {
4904                         struct list_head *list = &rq->arrays[arr].queue[i];
4905                         while (!list_empty(list))
4906                                 migrate_dead(dead_cpu,
4907                                              list_entry(list->next, task_t,
4908                                                         run_list));
4909                 }
4910         }
4911 }
4912 #endif /* CONFIG_HOTPLUG_CPU */
4913
4914 /*
4915  * migration_call - callback that gets triggered when a CPU is added.
4916  * Here we can start up the necessary migration thread for the new CPU.
4917  */
4918 static int migration_call(struct notifier_block *nfb, unsigned long action,
4919                           void *hcpu)
4920 {
4921         int cpu = (long)hcpu;
4922         struct task_struct *p;
4923         struct runqueue *rq;
4924         unsigned long flags;
4925
4926         switch (action) {
4927         case CPU_UP_PREPARE:
4928                 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4929                 if (IS_ERR(p))
4930                         return NOTIFY_BAD;
4931                 p->flags |= PF_NOFREEZE;
4932                 kthread_bind(p, cpu);
4933                 /* Must be high prio: stop_machine expects to yield to it. */
4934                 rq = task_rq_lock(p, &flags);
4935                 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4936                 task_rq_unlock(rq, &flags);
4937                 cpu_rq(cpu)->migration_thread = p;
4938                 break;
4939         case CPU_ONLINE:
4940                 /* Strictly unneccessary, as first user will wake it. */
4941                 wake_up_process(cpu_rq(cpu)->migration_thread);
4942                 break;
4943 #ifdef CONFIG_HOTPLUG_CPU
4944         case CPU_UP_CANCELED:
4945                 /* Unbind it from offline cpu so it can run.  Fall thru. */
4946                 kthread_bind(cpu_rq(cpu)->migration_thread,
4947                              any_online_cpu(cpu_online_map));
4948                 kthread_stop(cpu_rq(cpu)->migration_thread);
4949                 cpu_rq(cpu)->migration_thread = NULL;
4950                 break;
4951         case CPU_DEAD:
4952                 migrate_live_tasks(cpu);
4953                 rq = cpu_rq(cpu);
4954                 kthread_stop(rq->migration_thread);
4955                 rq->migration_thread = NULL;
4956                 /* Idle task back to normal (off runqueue, low prio) */
4957                 rq = task_rq_lock(rq->idle, &flags);
4958                 deactivate_task(rq->idle, rq);
4959                 rq->idle->static_prio = MAX_PRIO;
4960                 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4961                 migrate_dead_tasks(cpu);
4962                 task_rq_unlock(rq, &flags);
4963                 migrate_nr_uninterruptible(rq);
4964                 BUG_ON(rq->nr_running != 0);
4965
4966                 /* No need to migrate the tasks: it was best-effort if
4967                  * they didn't do lock_cpu_hotplug().  Just wake up
4968                  * the requestors. */
4969                 spin_lock_irq(&rq->lock);
4970                 while (!list_empty(&rq->migration_queue)) {
4971                         migration_req_t *req;
4972                         req = list_entry(rq->migration_queue.next,
4973                                          migration_req_t, list);
4974                         list_del_init(&req->list);
4975                         complete(&req->done);
4976                 }
4977                 spin_unlock_irq(&rq->lock);
4978                 break;
4979 #endif
4980         }
4981         return NOTIFY_OK;
4982 }
4983
4984 /* Register at highest priority so that task migration (migrate_all_tasks)
4985  * happens before everything else.
4986  */
4987 static struct notifier_block migration_notifier = {
4988         .notifier_call = migration_call,
4989         .priority = 10
4990 };
4991
4992 int __init migration_init(void)
4993 {
4994         void *cpu = (void *)(long)smp_processor_id();
4995         /* Start one for boot CPU. */
4996         migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4997         migration_call(&migration_notifier, CPU_ONLINE, cpu);
4998         register_cpu_notifier(&migration_notifier);
4999         return 0;
5000 }
5001 #endif
5002
5003 #ifdef CONFIG_SMP
5004 #undef SCHED_DOMAIN_DEBUG
5005 #ifdef SCHED_DOMAIN_DEBUG
5006 static void sched_domain_debug(struct sched_domain *sd, int cpu)
5007 {
5008         int level = 0;
5009
5010         if (!sd) {
5011                 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5012                 return;
5013         }
5014
5015         printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5016
5017         do {
5018                 int i;
5019                 char str[NR_CPUS];
5020                 struct sched_group *group = sd->groups;
5021                 cpumask_t groupmask;
5022
5023                 cpumask_scnprintf(str, NR_CPUS, sd->span);
5024                 cpus_clear(groupmask);
5025
5026                 printk(KERN_DEBUG);
5027                 for (i = 0; i < level + 1; i++)
5028                         printk(" ");
5029                 printk("domain %d: ", level);
5030
5031                 if (!(sd->flags & SD_LOAD_BALANCE)) {
5032                         printk("does not load-balance\n");
5033                         if (sd->parent)
5034                                 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
5035                         break;
5036                 }
5037
5038                 printk("span %s\n", str);
5039
5040                 if (!cpu_isset(cpu, sd->span))
5041                         printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
5042                 if (!cpu_isset(cpu, group->cpumask))
5043                         printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
5044
5045                 printk(KERN_DEBUG);
5046                 for (i = 0; i < level + 2; i++)
5047                         printk(" ");
5048                 printk("groups:");
5049                 do {
5050                         if (!group) {
5051                                 printk("\n");
5052                                 printk(KERN_ERR "ERROR: group is NULL\n");
5053                                 break;
5054                         }
5055
5056                         if (!group->cpu_power) {
5057                                 printk("\n");
5058                                 printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
5059                         }
5060
5061                         if (!cpus_weight(group->cpumask)) {
5062                                 printk("\n");
5063                                 printk(KERN_ERR "ERROR: empty group\n");
5064                         }
5065
5066                         if (cpus_intersects(groupmask, group->cpumask)) {
5067                                 printk("\n");
5068                                 printk(KERN_ERR "ERROR: repeated CPUs\n");
5069                         }
5070
5071                         cpus_or(groupmask, groupmask, group->cpumask);
5072
5073                         cpumask_scnprintf(str, NR_CPUS, group->cpumask);
5074                         printk(" %s", str);
5075
5076                         group = group->next;
5077                 } while (group != sd->groups);
5078                 printk("\n");
5079
5080                 if (!cpus_equal(sd->span, groupmask))
5081                         printk(KERN_ERR "ERROR: groups don't span domain->span\n");
5082
5083                 level++;
5084                 sd = sd->parent;
5085
5086                 if (sd) {
5087                         if (!cpus_subset(groupmask, sd->span))
5088                                 printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
5089                 }
5090
5091         } while (sd);
5092 }
5093 #else
5094 #define sched_domain_debug(sd, cpu) {}
5095 #endif
5096
5097 static int sd_degenerate(struct sched_domain *sd)
5098 {
5099         if (cpus_weight(sd->span) == 1)
5100                 return 1;
5101
5102         /* Following flags need at least 2 groups */
5103         if (sd->flags & (SD_LOAD_BALANCE |
5104                          SD_BALANCE_NEWIDLE |
5105                          SD_BALANCE_FORK |
5106                          SD_BALANCE_EXEC)) {
5107                 if (sd->groups != sd->groups->next)
5108                         return 0;
5109         }
5110
5111         /* Following flags don't use groups */
5112         if (sd->flags & (SD_WAKE_IDLE |
5113                          SD_WAKE_AFFINE |
5114                          SD_WAKE_BALANCE))
5115                 return 0;
5116
5117         return 1;
5118 }
5119
5120 static int sd_parent_degenerate(struct sched_domain *sd,
5121                                                 struct sched_domain *parent)
5122 {
5123         unsigned long cflags = sd->flags, pflags = parent->flags;
5124
5125         if (sd_degenerate(parent))
5126                 return 1;
5127
5128         if (!cpus_equal(sd->span, parent->span))
5129                 return 0;
5130
5131         /* Does parent contain flags not in child? */
5132         /* WAKE_BALANCE is a subset of WAKE_AFFINE */
5133         if (cflags & SD_WAKE_AFFINE)
5134                 pflags &= ~SD_WAKE_BALANCE;
5135         /* Flags needing groups don't count if only 1 group in parent */
5136         if (parent->groups == parent->groups->next) {
5137                 pflags &= ~(SD_LOAD_BALANCE |
5138                                 SD_BALANCE_NEWIDLE |
5139                                 SD_BALANCE_FORK |
5140                                 SD_BALANCE_EXEC);
5141         }
5142         if (~cflags & pflags)
5143                 return 0;
5144
5145         return 1;
5146 }
5147
5148 /*
5149  * Attach the domain 'sd' to 'cpu' as its base domain.  Callers must
5150  * hold the hotplug lock.
5151  */
5152 static void cpu_attach_domain(struct sched_domain *sd, int cpu)
5153 {
5154         runqueue_t *rq = cpu_rq(cpu);
5155         struct sched_domain *tmp;
5156
5157         /* Remove the sched domains which do not contribute to scheduling. */
5158         for (tmp = sd; tmp; tmp = tmp->parent) {
5159                 struct sched_domain *parent = tmp->parent;
5160                 if (!parent)
5161                         break;
5162                 if (sd_parent_degenerate(tmp, parent))
5163                         tmp->parent = parent->parent;
5164         }
5165
5166         if (sd && sd_degenerate(sd))
5167                 sd = sd->parent;
5168
5169         sched_domain_debug(sd, cpu);
5170
5171         rcu_assign_pointer(rq->sd, sd);
5172 }
5173
5174 /* cpus with isolated domains */
5175 static cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
5176
5177 /* Setup the mask of cpus configured for isolated domains */
5178 static int __init isolated_cpu_setup(char *str)
5179 {
5180         int ints[NR_CPUS], i;
5181
5182         str = get_options(str, ARRAY_SIZE(ints), ints);
5183         cpus_clear(cpu_isolated_map);
5184         for (i = 1; i <= ints[0]; i++)
5185                 if (ints[i] < NR_CPUS)
5186                         cpu_set(ints[i], cpu_isolated_map);
5187         return 1;
5188 }
5189
5190 __setup ("isolcpus=", isolated_cpu_setup);
5191
5192 /*
5193  * init_sched_build_groups takes an array of groups, the cpumask we wish
5194  * to span, and a pointer to a function which identifies what group a CPU
5195  * belongs to. The return value of group_fn must be a valid index into the
5196  * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
5197  * keep track of groups covered with a cpumask_t).
5198  *
5199  * init_sched_build_groups will build a circular linked list of the groups
5200  * covered by the given span, and will set each group's ->cpumask correctly,
5201  * and ->cpu_power to 0.
5202  */
5203 static void init_sched_build_groups(struct sched_group groups[], cpumask_t span,
5204                                     int (*group_fn)(int cpu))
5205 {
5206         struct sched_group *first = NULL, *last = NULL;
5207         cpumask_t covered = CPU_MASK_NONE;
5208         int i;
5209
5210         for_each_cpu_mask(i, span) {
5211                 int group = group_fn(i);
5212                 struct sched_group *sg = &groups[group];
5213                 int j;
5214
5215                 if (cpu_isset(i, covered))
5216                         continue;
5217
5218                 sg->cpumask = CPU_MASK_NONE;
5219                 sg->cpu_power = 0;
5220
5221                 for_each_cpu_mask(j, span) {
5222                         if (group_fn(j) != group)
5223                                 continue;
5224
5225                         cpu_set(j, covered);
5226                         cpu_set(j, sg->cpumask);
5227                 }
5228                 if (!first)
5229                         first = sg;
5230                 if (last)
5231                         last->next = sg;
5232                 last = sg;
5233         }
5234         last->next = first;
5235 }
5236
5237 #define SD_NODES_PER_DOMAIN 16
5238
5239 /*
5240  * Self-tuning task migration cost measurement between source and target CPUs.
5241  *
5242  * This is done by measuring the cost of manipulating buffers of varying
5243  * sizes. For a given buffer-size here are the steps that are taken:
5244  *
5245  * 1) the source CPU reads+dirties a shared buffer
5246  * 2) the target CPU reads+dirties the same shared buffer
5247  *
5248  * We measure how long they take, in the following 4 scenarios:
5249  *
5250  *  - source: CPU1, target: CPU2 | cost1
5251  *  - source: CPU2, target: CPU1 | cost2
5252  *  - source: CPU1, target: CPU1 | cost3
5253  *  - source: CPU2, target: CPU2 | cost4
5254  *
5255  * We then calculate the cost3+cost4-cost1-cost2 difference - this is
5256  * the cost of migration.
5257  *
5258  * We then start off from a small buffer-size and iterate up to larger
5259  * buffer sizes, in 5% steps - measuring each buffer-size separately, and
5260  * doing a maximum search for the cost. (The maximum cost for a migration
5261  * normally occurs when the working set size is around the effective cache
5262  * size.)
5263  */
5264 #define SEARCH_SCOPE            2
5265 #define MIN_CACHE_SIZE          (64*1024U)
5266 #define DEFAULT_CACHE_SIZE      (5*1024*1024U)
5267 #define ITERATIONS              1
5268 #define SIZE_THRESH             130
5269 #define COST_THRESH             130
5270
5271 /*
5272  * The migration cost is a function of 'domain distance'. Domain
5273  * distance is the number of steps a CPU has to iterate down its
5274  * domain tree to share a domain with the other CPU. The farther
5275  * two CPUs are from each other, the larger the distance gets.
5276  *
5277  * Note that we use the distance only to cache measurement results,
5278  * the distance value is not used numerically otherwise. When two
5279  * CPUs have the same distance it is assumed that the migration
5280  * cost is the same. (this is a simplification but quite practical)
5281  */
5282 #define MAX_DOMAIN_DISTANCE 32
5283
5284 static unsigned long long migration_cost[MAX_DOMAIN_DISTANCE] =
5285                 { [ 0 ... MAX_DOMAIN_DISTANCE-1 ] =
5286 /*
5287  * Architectures may override the migration cost and thus avoid
5288  * boot-time calibration. Unit is nanoseconds. Mostly useful for
5289  * virtualized hardware:
5290  */
5291 #ifdef CONFIG_DEFAULT_MIGRATION_COST
5292                         CONFIG_DEFAULT_MIGRATION_COST
5293 #else
5294                         -1LL
5295 #endif
5296 };
5297
5298 /*
5299  * Allow override of migration cost - in units of microseconds.
5300  * E.g. migration_cost=1000,2000,3000 will set up a level-1 cost
5301  * of 1 msec, level-2 cost of 2 msecs and level3 cost of 3 msecs:
5302  */
5303 static int __init migration_cost_setup(char *str)
5304 {
5305         int ints[MAX_DOMAIN_DISTANCE+1], i;
5306
5307         str = get_options(str, ARRAY_SIZE(ints), ints);
5308
5309         printk("#ints: %d\n", ints[0]);
5310         for (i = 1; i <= ints[0]; i++) {
5311                 migration_cost[i-1] = (unsigned long long)ints[i]*1000;
5312                 printk("migration_cost[%d]: %Ld\n", i-1, migration_cost[i-1]);
5313         }
5314         return 1;
5315 }
5316
5317 __setup ("migration_cost=", migration_cost_setup);
5318
5319 /*
5320  * Global multiplier (divisor) for migration-cutoff values,
5321  * in percentiles. E.g. use a value of 150 to get 1.5 times
5322  * longer cache-hot cutoff times.
5323  *
5324  * (We scale it from 100 to 128 to long long handling easier.)
5325  */
5326
5327 #define MIGRATION_FACTOR_SCALE 128
5328
5329 static unsigned int migration_factor = MIGRATION_FACTOR_SCALE;
5330
5331 static int __init setup_migration_factor(char *str)
5332 {
5333         get_option(&str, &migration_factor);
5334         migration_factor = migration_factor * MIGRATION_FACTOR_SCALE / 100;
5335         return 1;
5336 }
5337
5338 __setup("migration_factor=", setup_migration_factor);
5339
5340 /*
5341  * Estimated distance of two CPUs, measured via the number of domains
5342  * we have to pass for the two CPUs to be in the same span:
5343  */
5344 static unsigned long domain_distance(int cpu1, int cpu2)
5345 {
5346         unsigned long distance = 0;
5347         struct sched_domain *sd;
5348
5349         for_each_domain(cpu1, sd) {
5350                 WARN_ON(!cpu_isset(cpu1, sd->span));
5351                 if (cpu_isset(cpu2, sd->span))
5352                         return distance;
5353                 distance++;
5354         }
5355         if (distance >= MAX_DOMAIN_DISTANCE) {
5356                 WARN_ON(1);
5357                 distance = MAX_DOMAIN_DISTANCE-1;
5358         }
5359
5360         return distance;
5361 }
5362
5363 static unsigned int migration_debug;
5364
5365 static int __init setup_migration_debug(char *str)
5366 {
5367         get_option(&str, &migration_debug);
5368         return 1;
5369 }
5370
5371 __setup("migration_debug=", setup_migration_debug);
5372
5373 /*
5374  * Maximum cache-size that the scheduler should try to measure.
5375  * Architectures with larger caches should tune this up during
5376  * bootup. Gets used in the domain-setup code (i.e. during SMP
5377  * bootup).
5378  */
5379 unsigned int max_cache_size;
5380
5381 static int __init setup_max_cache_size(char *str)
5382 {
5383         get_option(&str, &max_cache_size);
5384         return 1;
5385 }
5386
5387 __setup("max_cache_size=", setup_max_cache_size);
5388
5389 /*
5390  * Dirty a big buffer in a hard-to-predict (for the L2 cache) way. This
5391  * is the operation that is timed, so we try to generate unpredictable
5392  * cachemisses that still end up filling the L2 cache:
5393  */
5394 static void touch_cache(void *__cache, unsigned long __size)
5395 {
5396         unsigned long size = __size/sizeof(long), chunk1 = size/3,
5397                         chunk2 = 2*size/3;
5398         unsigned long *cache = __cache;
5399         int i;
5400
5401         for (i = 0; i < size/6; i += 8) {
5402                 switch (i % 6) {
5403                         case 0: cache[i]++;
5404                         case 1: cache[size-1-i]++;
5405                         case 2: cache[chunk1-i]++;
5406                         case 3: cache[chunk1+i]++;
5407                         case 4: cache[chunk2-i]++;
5408                         case 5: cache[chunk2+i]++;
5409                 }
5410         }
5411 }
5412
5413 /*
5414  * Measure the cache-cost of one task migration. Returns in units of nsec.
5415  */
5416 static unsigned long long measure_one(void *cache, unsigned long size,
5417                                       int source, int target)
5418 {
5419         cpumask_t mask, saved_mask;
5420         unsigned long long t0, t1, t2, t3, cost;
5421
5422         saved_mask = current->cpus_allowed;
5423
5424         /*
5425          * Flush source caches to RAM and invalidate them:
5426          */
5427         sched_cacheflush();
5428
5429         /*
5430          * Migrate to the source CPU:
5431          */
5432         mask = cpumask_of_cpu(source);
5433         set_cpus_allowed(current, mask);
5434         WARN_ON(smp_processor_id() != source);
5435
5436         /*
5437          * Dirty the working set:
5438          */
5439         t0 = sched_clock();
5440         touch_cache(cache, size);
5441         t1 = sched_clock();
5442
5443         /*
5444          * Migrate to the target CPU, dirty the L2 cache and access
5445          * the shared buffer. (which represents the working set
5446          * of a migrated task.)
5447          */
5448         mask = cpumask_of_cpu(target);
5449         set_cpus_allowed(current, mask);
5450         WARN_ON(smp_processor_id() != target);
5451
5452         t2 = sched_clock();
5453         touch_cache(cache, size);
5454         t3 = sched_clock();
5455
5456         cost = t1-t0 + t3-t2;
5457
5458         if (migration_debug >= 2)
5459                 printk("[%d->%d]: %8Ld %8Ld %8Ld => %10Ld.\n",
5460                         source, target, t1-t0, t1-t0, t3-t2, cost);
5461         /*
5462          * Flush target caches to RAM and invalidate them:
5463          */
5464         sched_cacheflush();
5465
5466         set_cpus_allowed(current, saved_mask);
5467
5468         return cost;
5469 }
5470
5471 /*
5472  * Measure a series of task migrations and return the average
5473  * result. Since this code runs early during bootup the system
5474  * is 'undisturbed' and the average latency makes sense.
5475  *
5476  * The algorithm in essence auto-detects the relevant cache-size,
5477  * so it will properly detect different cachesizes for different
5478  * cache-hierarchies, depending on how the CPUs are connected.
5479  *
5480  * Architectures can prime the upper limit of the search range via
5481  * max_cache_size, otherwise the search range defaults to 20MB...64K.
5482  */
5483 static unsigned long long
5484 measure_cost(int cpu1, int cpu2, void *cache, unsigned int size)
5485 {
5486         unsigned long long cost1, cost2;
5487         int i;
5488
5489         /*
5490          * Measure the migration cost of 'size' bytes, over an
5491          * average of 10 runs:
5492          *
5493          * (We perturb the cache size by a small (0..4k)
5494          *  value to compensate size/alignment related artifacts.
5495          *  We also subtract the cost of the operation done on
5496          *  the same CPU.)
5497          */
5498         cost1 = 0;
5499
5500         /*
5501          * dry run, to make sure we start off cache-cold on cpu1,
5502          * and to get any vmalloc pagefaults in advance:
5503          */
5504         measure_one(cache, size, cpu1, cpu2);
5505         for (i = 0; i < ITERATIONS; i++)
5506                 cost1 += measure_one(cache, size - i*1024, cpu1, cpu2);
5507
5508         measure_one(cache, size, cpu2, cpu1);
5509         for (i = 0; i < ITERATIONS; i++)
5510                 cost1 += measure_one(cache, size - i*1024, cpu2, cpu1);
5511
5512         /*
5513          * (We measure the non-migrating [cached] cost on both
5514          *  cpu1 and cpu2, to handle CPUs with different speeds)
5515          */
5516         cost2 = 0;
5517
5518         measure_one(cache, size, cpu1, cpu1);
5519         for (i = 0; i < ITERATIONS; i++)
5520                 cost2 += measure_one(cache, size - i*1024, cpu1, cpu1);
5521
5522         measure_one(cache, size, cpu2, cpu2);
5523         for (i = 0; i < ITERATIONS; i++)
5524                 cost2 += measure_one(cache, size - i*1024, cpu2, cpu2);
5525
5526         /*
5527          * Get the per-iteration migration cost:
5528          */
5529         do_div(cost1, 2*ITERATIONS);
5530         do_div(cost2, 2*ITERATIONS);
5531
5532         return cost1 - cost2;
5533 }
5534
5535 static unsigned long long measure_migration_cost(int cpu1, int cpu2)
5536 {
5537         unsigned long long max_cost = 0, fluct = 0, avg_fluct = 0;
5538         unsigned int max_size, size, size_found = 0;
5539         long long cost = 0, prev_cost;
5540         void *cache;
5541
5542         /*
5543          * Search from max_cache_size*5 down to 64K - the real relevant
5544          * cachesize has to lie somewhere inbetween.
5545          */
5546         if (max_cache_size) {
5547                 max_size = max(max_cache_size * SEARCH_SCOPE, MIN_CACHE_SIZE);
5548                 size = max(max_cache_size / SEARCH_SCOPE, MIN_CACHE_SIZE);
5549         } else {
5550                 /*
5551                  * Since we have no estimation about the relevant
5552                  * search range
5553                  */
5554                 max_size = DEFAULT_CACHE_SIZE * SEARCH_SCOPE;
5555                 size = MIN_CACHE_SIZE;
5556         }
5557
5558         if (!cpu_online(cpu1) || !cpu_online(cpu2)) {
5559                 printk("cpu %d and %d not both online!\n", cpu1, cpu2);
5560                 return 0;
5561         }
5562
5563         /*
5564          * Allocate the working set:
5565          */
5566         cache = vmalloc(max_size);
5567         if (!cache) {
5568                 printk("could not vmalloc %d bytes for cache!\n", 2*max_size);
5569                 return 1000000; // return 1 msec on very small boxen
5570         }
5571
5572         while (size <= max_size) {
5573                 prev_cost = cost;
5574                 cost = measure_cost(cpu1, cpu2, cache, size);
5575
5576                 /*
5577                  * Update the max:
5578                  */
5579                 if (cost > 0) {
5580                         if (max_cost < cost) {
5581                                 max_cost = cost;
5582                                 size_found = size;
5583                         }
5584                 }
5585                 /*
5586                  * Calculate average fluctuation, we use this to prevent
5587                  * noise from triggering an early break out of the loop:
5588                  */
5589                 fluct = abs(cost - prev_cost);
5590                 avg_fluct = (avg_fluct + fluct)/2;
5591
5592                 if (migration_debug)
5593                         printk("-> [%d][%d][%7d] %3ld.%ld [%3ld.%ld] (%ld): (%8Ld %8Ld)\n",
5594                                 cpu1, cpu2, size,
5595                                 (long)cost / 1000000,
5596                                 ((long)cost / 100000) % 10,
5597                                 (long)max_cost / 1000000,
5598                                 ((long)max_cost / 100000) % 10,
5599                                 domain_distance(cpu1, cpu2),
5600                                 cost, avg_fluct);
5601
5602                 /*
5603                  * If we iterated at least 20% past the previous maximum,
5604                  * and the cost has dropped by more than 20% already,
5605                  * (taking fluctuations into account) then we assume to
5606                  * have found the maximum and break out of the loop early:
5607                  */
5608                 if (size_found && (size*100 > size_found*SIZE_THRESH))
5609                         if (cost+avg_fluct <= 0 ||
5610                                 max_cost*100 > (cost+avg_fluct)*COST_THRESH) {
5611
5612                                 if (migration_debug)
5613                                         printk("-> found max.\n");
5614                                 break;
5615                         }
5616                 /*
5617                  * Increase the cachesize in 10% steps:
5618                  */
5619                 size = size * 10 / 9;
5620         }
5621
5622         if (migration_debug)
5623                 printk("[%d][%d] working set size found: %d, cost: %Ld\n",
5624                         cpu1, cpu2, size_found, max_cost);
5625
5626         vfree(cache);
5627
5628         /*
5629          * A task is considered 'cache cold' if at least 2 times
5630          * the worst-case cost of migration has passed.
5631          *
5632          * (this limit is only listened to if the load-balancing
5633          * situation is 'nice' - if there is a large imbalance we
5634          * ignore it for the sake of CPU utilization and
5635          * processing fairness.)
5636          */
5637         return 2 * max_cost * migration_factor / MIGRATION_FACTOR_SCALE;
5638 }
5639
5640 static void calibrate_migration_costs(const cpumask_t *cpu_map)
5641 {
5642         int cpu1 = -1, cpu2 = -1, cpu, orig_cpu = raw_smp_processor_id();
5643         unsigned long j0, j1, distance, max_distance = 0;
5644         struct sched_domain *sd;
5645
5646         j0 = jiffies;
5647
5648         /*
5649          * First pass - calculate the cacheflush times:
5650          */
5651         for_each_cpu_mask(cpu1, *cpu_map) {
5652                 for_each_cpu_mask(cpu2, *cpu_map) {
5653                         if (cpu1 == cpu2)
5654                                 continue;
5655                         distance = domain_distance(cpu1, cpu2);
5656                         max_distance = max(max_distance, distance);
5657                         /*
5658                          * No result cached yet?
5659                          */
5660                         if (migration_cost[distance] == -1LL)
5661                                 migration_cost[distance] =
5662                                         measure_migration_cost(cpu1, cpu2);
5663                 }
5664         }
5665         /*
5666          * Second pass - update the sched domain hierarchy with
5667          * the new cache-hot-time estimations:
5668          */
5669         for_each_cpu_mask(cpu, *cpu_map) {
5670                 distance = 0;
5671                 for_each_domain(cpu, sd) {
5672                         sd->cache_hot_time = migration_cost[distance];
5673                         distance++;
5674                 }
5675         }
5676         /*
5677          * Print the matrix:
5678          */
5679         if (migration_debug)
5680                 printk("migration: max_cache_size: %d, cpu: %d MHz:\n",
5681                         max_cache_size,
5682 #ifdef CONFIG_X86
5683                         cpu_khz/1000
5684 #else
5685                         -1
5686 #endif
5687                 );
5688         if (system_state == SYSTEM_BOOTING) {
5689                 if (num_online_cpus() > 1) {
5690                         printk("migration_cost=");
5691                         for (distance = 0; distance <= max_distance; distance++) {
5692                                 if (distance)
5693                                         printk(",");
5694                                 printk("%ld", (long)migration_cost[distance] / 1000);
5695                         }
5696                         printk("\n");
5697                 }
5698         }
5699         j1 = jiffies;
5700         if (migration_debug)
5701                 printk("migration: %ld seconds\n", (j1-j0)/HZ);
5702
5703         /*
5704          * Move back to the original CPU. NUMA-Q gets confused
5705          * if we migrate to another quad during bootup.
5706          */
5707         if (raw_smp_processor_id() != orig_cpu) {
5708                 cpumask_t mask = cpumask_of_cpu(orig_cpu),
5709                         saved_mask = current->cpus_allowed;
5710
5711                 set_cpus_allowed(current, mask);
5712                 set_cpus_allowed(current, saved_mask);
5713         }
5714 }
5715
5716 #ifdef CONFIG_NUMA
5717
5718 /**
5719  * find_next_best_node - find the next node to include in a sched_domain
5720  * @node: node whose sched_domain we're building
5721  * @used_nodes: nodes already in the sched_domain
5722  *
5723  * Find the next node to include in a given scheduling domain.  Simply
5724  * finds the closest node not already in the @used_nodes map.
5725  *
5726  * Should use nodemask_t.
5727  */
5728 static int find_next_best_node(int node, unsigned long *used_nodes)
5729 {
5730         int i, n, val, min_val, best_node = 0;
5731
5732         min_val = INT_MAX;
5733
5734         for (i = 0; i < MAX_NUMNODES; i++) {
5735                 /* Start at @node */
5736                 n = (node + i) % MAX_NUMNODES;
5737
5738                 if (!nr_cpus_node(n))
5739                         continue;
5740
5741                 /* Skip already used nodes */
5742                 if (test_bit(n, used_nodes))
5743                         continue;
5744
5745                 /* Simple min distance search */
5746                 val = node_distance(node, n);
5747
5748                 if (val < min_val) {
5749                         min_val = val;
5750                         best_node = n;
5751                 }
5752         }
5753
5754         set_bit(best_node, used_nodes);
5755         return best_node;
5756 }
5757
5758 /**
5759  * sched_domain_node_span - get a cpumask for a node's sched_domain
5760  * @node: node whose cpumask we're constructing
5761  * @size: number of nodes to include in this span
5762  *
5763  * Given a node, construct a good cpumask for its sched_domain to span.  It
5764  * should be one that prevents unnecessary balancing, but also spreads tasks
5765  * out optimally.
5766  */
5767 static cpumask_t sched_domain_node_span(int node)
5768 {
5769         int i;
5770         cpumask_t span, nodemask;
5771         DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
5772
5773         cpus_clear(span);
5774         bitmap_zero(used_nodes, MAX_NUMNODES);
5775
5776         nodemask = node_to_cpumask(node);
5777         cpus_or(span, span, nodemask);
5778         set_bit(node, used_nodes);
5779
5780         for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
5781                 int next_node = find_next_best_node(node, used_nodes);
5782                 nodemask = node_to_cpumask(next_node);
5783                 cpus_or(span, span, nodemask);
5784         }
5785
5786         return span;
5787 }
5788 #endif
5789
5790 /*
5791  * At the moment, CONFIG_SCHED_SMT is never defined, but leave it in so we
5792  * can switch it on easily if needed.
5793  */
5794 #ifdef CONFIG_SCHED_SMT
5795 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
5796 static struct sched_group sched_group_cpus[NR_CPUS];
5797 static int cpu_to_cpu_group(int cpu)
5798 {
5799         return cpu;
5800 }
5801 #endif
5802
5803 #ifdef CONFIG_SCHED_MC
5804 static DEFINE_PER_CPU(struct sched_domain, core_domains);
5805 static struct sched_group sched_group_core[NR_CPUS];
5806 #endif
5807
5808 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
5809 static int cpu_to_core_group(int cpu)
5810 {
5811         return first_cpu(cpu_sibling_map[cpu]);
5812 }
5813 #elif defined(CONFIG_SCHED_MC)
5814 static int cpu_to_core_group(int cpu)
5815 {
5816         return cpu;
5817 }
5818 #endif
5819
5820 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
5821 static struct sched_group sched_group_phys[NR_CPUS];
5822 static int cpu_to_phys_group(int cpu)
5823 {
5824 #if defined(CONFIG_SCHED_MC)
5825         cpumask_t mask = cpu_coregroup_map(cpu);
5826         return first_cpu(mask);
5827 #elif defined(CONFIG_SCHED_SMT)
5828         return first_cpu(cpu_sibling_map[cpu]);
5829 #else
5830         return cpu;
5831 #endif
5832 }
5833
5834 #ifdef CONFIG_NUMA
5835 /*
5836  * The init_sched_build_groups can't handle what we want to do with node
5837  * groups, so roll our own. Now each node has its own list of groups which
5838  * gets dynamically allocated.
5839  */
5840 static DEFINE_PER_CPU(struct sched_domain, node_domains);
5841 static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
5842
5843 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
5844 static struct sched_group *sched_group_allnodes_bycpu[NR_CPUS];
5845
5846 static int cpu_to_allnodes_group(int cpu)
5847 {
5848         return cpu_to_node(cpu);
5849 }
5850 static void init_numa_sched_groups_power(struct sched_group *group_head)
5851 {
5852         struct sched_group *sg = group_head;
5853         int j;
5854
5855         if (!sg)
5856                 return;
5857 next_sg:
5858         for_each_cpu_mask(j, sg->cpumask) {
5859                 struct sched_domain *sd;
5860
5861                 sd = &per_cpu(phys_domains, j);
5862                 if (j != first_cpu(sd->groups->cpumask)) {
5863                         /*
5864                          * Only add "power" once for each
5865                          * physical package.
5866                          */
5867                         continue;
5868                 }
5869
5870                 sg->cpu_power += sd->groups->cpu_power;
5871         }
5872         sg = sg->next;
5873         if (sg != group_head)
5874                 goto next_sg;
5875 }
5876 #endif
5877
5878 /*
5879  * Build sched domains for a given set of cpus and attach the sched domains
5880  * to the individual cpus
5881  */
5882 void build_sched_domains(const cpumask_t *cpu_map)
5883 {
5884         int i;
5885 #ifdef CONFIG_NUMA
5886         struct sched_group **sched_group_nodes = NULL;
5887         struct sched_group *sched_group_allnodes = NULL;
5888
5889         /*
5890          * Allocate the per-node list of sched groups
5891          */
5892         sched_group_nodes = kmalloc(sizeof(struct sched_group*)*MAX_NUMNODES,
5893                                            GFP_ATOMIC);
5894         if (!sched_group_nodes) {
5895                 printk(KERN_WARNING "Can not alloc sched group node list\n");
5896                 return;
5897         }
5898         sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
5899 #endif
5900
5901         /*
5902          * Set up domains for cpus specified by the cpu_map.
5903          */
5904         for_each_cpu_mask(i, *cpu_map) {
5905                 int group;
5906                 struct sched_domain *sd = NULL, *p;
5907                 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
5908
5909                 cpus_and(nodemask, nodemask, *cpu_map);
5910
5911 #ifdef CONFIG_NUMA
5912                 if (cpus_weight(*cpu_map)
5913                                 > SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
5914                         if (!sched_group_allnodes) {
5915                                 sched_group_allnodes
5916                                         = kmalloc(sizeof(struct sched_group)
5917                                                         * MAX_NUMNODES,
5918                                                   GFP_KERNEL);
5919                                 if (!sched_group_allnodes) {
5920                                         printk(KERN_WARNING
5921                                         "Can not alloc allnodes sched group\n");
5922                                         break;
5923                                 }
5924                                 sched_group_allnodes_bycpu[i]
5925                                                 = sched_group_allnodes;
5926                         }
5927                         sd = &per_cpu(allnodes_domains, i);
5928                         *sd = SD_ALLNODES_INIT;
5929                         sd->span = *cpu_map;
5930                         group = cpu_to_allnodes_group(i);
5931                         sd->groups = &sched_group_allnodes[group];
5932                         p = sd;
5933                 } else
5934                         p = NULL;
5935
5936                 sd = &per_cpu(node_domains, i);
5937                 *sd = SD_NODE_INIT;
5938                 sd->span = sched_domain_node_span(cpu_to_node(i));
5939                 sd->parent = p;
5940                 cpus_and(sd->span, sd->span, *cpu_map);
5941 #endif
5942
5943                 p = sd;
5944                 sd = &per_cpu(phys_domains, i);
5945                 group = cpu_to_phys_group(i);
5946                 *sd = SD_CPU_INIT;
5947                 sd->span = nodemask;
5948                 sd->parent = p;
5949                 sd->groups = &sched_group_phys[group];
5950
5951 #ifdef CONFIG_SCHED_MC
5952                 p = sd;
5953                 sd = &per_cpu(core_domains, i);
5954                 group = cpu_to_core_group(i);
5955                 *sd = SD_MC_INIT;
5956                 sd->span = cpu_coregroup_map(i);
5957                 cpus_and(sd->span, sd->span, *cpu_map);
5958                 sd->parent = p;
5959                 sd->groups = &sched_group_core[group];
5960 #endif
5961
5962 #ifdef CONFIG_SCHED_SMT
5963                 p = sd;
5964                 sd = &per_cpu(cpu_domains, i);
5965                 group = cpu_to_cpu_group(i);
5966                 *sd = SD_SIBLING_INIT;
5967                 sd->span = cpu_sibling_map[i];
5968                 cpus_and(sd->span, sd->span, *cpu_map);
5969                 sd->parent = p;
5970                 sd->groups = &sched_group_cpus[group];
5971 #endif
5972         }
5973
5974 #ifdef CONFIG_SCHED_SMT
5975         /* Set up CPU (sibling) groups */
5976         for_each_cpu_mask(i, *cpu_map) {
5977                 cpumask_t this_sibling_map = cpu_sibling_map[i];
5978                 cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
5979                 if (i != first_cpu(this_sibling_map))
5980                         continue;
5981
5982                 init_sched_build_groups(sched_group_cpus, this_sibling_map,
5983                                                 &cpu_to_cpu_group);
5984         }
5985 #endif
5986
5987 #ifdef CONFIG_SCHED_MC
5988         /* Set up multi-core groups */
5989         for_each_cpu_mask(i, *cpu_map) {
5990                 cpumask_t this_core_map = cpu_coregroup_map(i);
5991                 cpus_and(this_core_map, this_core_map, *cpu_map);
5992                 if (i != first_cpu(this_core_map))
5993                         continue;
5994                 init_sched_build_groups(sched_group_core, this_core_map,
5995                                         &cpu_to_core_group);
5996         }
5997 #endif
5998
5999
6000         /* Set up physical groups */
6001         for (i = 0; i < MAX_NUMNODES; i++) {
6002                 cpumask_t nodemask = node_to_cpumask(i);
6003
6004                 cpus_and(nodemask, nodemask, *cpu_map);
6005                 if (cpus_empty(nodemask))
6006                         continue;
6007
6008                 init_sched_build_groups(sched_group_phys, nodemask,
6009                                                 &cpu_to_phys_group);
6010         }
6011
6012 #ifdef CONFIG_NUMA
6013         /* Set up node groups */
6014         if (sched_group_allnodes)
6015                 init_sched_build_groups(sched_group_allnodes, *cpu_map,
6016                                         &cpu_to_allnodes_group);
6017
6018         for (i = 0; i < MAX_NUMNODES; i++) {
6019                 /* Set up node groups */
6020                 struct sched_group *sg, *prev;
6021                 cpumask_t nodemask = node_to_cpumask(i);
6022                 cpumask_t domainspan;
6023                 cpumask_t covered = CPU_MASK_NONE;
6024                 int j;
6025
6026                 cpus_and(nodemask, nodemask, *cpu_map);
6027                 if (cpus_empty(nodemask)) {
6028                         sched_group_nodes[i] = NULL;
6029                         continue;
6030                 }
6031
6032                 domainspan = sched_domain_node_span(i);
6033                 cpus_and(domainspan, domainspan, *cpu_map);
6034
6035                 sg = kmalloc(sizeof(struct sched_group), GFP_KERNEL);
6036                 sched_group_nodes[i] = sg;
6037                 for_each_cpu_mask(j, nodemask) {
6038                         struct sched_domain *sd;
6039                         sd = &per_cpu(node_domains, j);
6040                         sd->groups = sg;
6041                         if (sd->groups == NULL) {
6042                                 /* Turn off balancing if we have no groups */
6043                                 sd->flags = 0;
6044                         }
6045                 }
6046                 if (!sg) {
6047                         printk(KERN_WARNING
6048                         "Can not alloc domain group for node %d\n", i);
6049                         continue;
6050                 }
6051                 sg->cpu_power = 0;
6052                 sg->cpumask = nodemask;
6053                 cpus_or(covered, covered, nodemask);
6054                 prev = sg;
6055
6056                 for (j = 0; j < MAX_NUMNODES; j++) {
6057                         cpumask_t tmp, notcovered;
6058                         int n = (i + j) % MAX_NUMNODES;
6059
6060                         cpus_complement(notcovered, covered);
6061                         cpus_and(tmp, notcovered, *cpu_map);
6062                         cpus_and(tmp, tmp, domainspan);
6063                         if (cpus_empty(tmp))
6064                                 break;
6065
6066                         nodemask = node_to_cpumask(n);
6067                         cpus_and(tmp, tmp, nodemask);
6068                         if (cpus_empty(tmp))
6069                                 continue;
6070
6071                         sg = kmalloc(sizeof(struct sched_group), GFP_KERNEL);
6072                         if (!sg) {
6073                                 printk(KERN_WARNING
6074                                 "Can not alloc domain group for node %d\n", j);
6075                                 break;
6076                         }
6077                         sg->cpu_power = 0;
6078                         sg->cpumask = tmp;
6079                         cpus_or(covered, covered, tmp);
6080                         prev->next = sg;
6081                         prev = sg;
6082                 }
6083                 prev->next = sched_group_nodes[i];
6084         }
6085 #endif
6086
6087         /* Calculate CPU power for physical packages and nodes */
6088         for_each_cpu_mask(i, *cpu_map) {
6089                 int power;
6090                 struct sched_domain *sd;
6091 #ifdef CONFIG_SCHED_SMT
6092                 sd = &per_cpu(cpu_domains, i);
6093                 power = SCHED_LOAD_SCALE;
6094                 sd->groups->cpu_power = power;
6095 #endif
6096 #ifdef CONFIG_SCHED_MC
6097                 sd = &per_cpu(core_domains, i);
6098                 power = SCHED_LOAD_SCALE + (cpus_weight(sd->groups->cpumask)-1)
6099                                             * SCHED_LOAD_SCALE / 10;
6100                 sd->groups->cpu_power = power;
6101
6102                 sd = &per_cpu(phys_domains, i);
6103
6104                 /*
6105                  * This has to be < 2 * SCHED_LOAD_SCALE
6106                  * Lets keep it SCHED_LOAD_SCALE, so that
6107                  * while calculating NUMA group's cpu_power
6108                  * we can simply do
6109                  *  numa_group->cpu_power += phys_group->cpu_power;
6110                  *
6111                  * See "only add power once for each physical pkg"
6112                  * comment below
6113                  */
6114                 sd->groups->cpu_power = SCHED_LOAD_SCALE;
6115 #else
6116                 sd = &per_cpu(phys_domains, i);
6117                 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
6118                                 (cpus_weight(sd->groups->cpumask)-1) / 10;
6119                 sd->groups->cpu_power = power;
6120 #endif
6121         }
6122
6123 #ifdef CONFIG_NUMA
6124         for (i = 0; i < MAX_NUMNODES; i++)
6125                 init_numa_sched_groups_power(sched_group_nodes[i]);
6126
6127         init_numa_sched_groups_power(sched_group_allnodes);
6128 #endif
6129
6130         /* Attach the domains */
6131         for_each_cpu_mask(i, *cpu_map) {
6132                 struct sched_domain *sd;
6133 #ifdef CONFIG_SCHED_SMT
6134                 sd = &per_cpu(cpu_domains, i);
6135 #elif defined(CONFIG_SCHED_MC)
6136                 sd = &per_cpu(core_domains, i);
6137 #else
6138                 sd = &per_cpu(phys_domains, i);
6139 #endif
6140                 cpu_attach_domain(sd, i);
6141         }
6142         /*
6143          * Tune cache-hot values:
6144          */
6145         calibrate_migration_costs(cpu_map);
6146 }
6147 /*
6148  * Set up scheduler domains and groups.  Callers must hold the hotplug lock.
6149  */
6150 static void arch_init_sched_domains(const cpumask_t *cpu_map)
6151 {
6152         cpumask_t cpu_default_map;
6153
6154         /*
6155          * Setup mask for cpus without special case scheduling requirements.
6156          * For now this just excludes isolated cpus, but could be used to
6157          * exclude other special cases in the future.
6158          */
6159         cpus_andnot(cpu_default_map, *cpu_map, cpu_isolated_map);
6160
6161         build_sched_domains(&cpu_default_map);
6162 }
6163
6164 static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
6165 {
6166 #ifdef CONFIG_NUMA
6167         int i;
6168         int cpu;
6169
6170         for_each_cpu_mask(cpu, *cpu_map) {
6171                 struct sched_group *sched_group_allnodes
6172                         = sched_group_allnodes_bycpu[cpu];
6173                 struct sched_group **sched_group_nodes
6174                         = sched_group_nodes_bycpu[cpu];
6175
6176                 if (sched_group_allnodes) {
6177                         kfree(sched_group_allnodes);
6178                         sched_group_allnodes_bycpu[cpu] = NULL;
6179                 }
6180
6181                 if (!sched_group_nodes)
6182                         continue;
6183
6184                 for (i = 0; i < MAX_NUMNODES; i++) {
6185                         cpumask_t nodemask = node_to_cpumask(i);
6186                         struct sched_group *oldsg, *sg = sched_group_nodes[i];
6187
6188                         cpus_and(nodemask, nodemask, *cpu_map);
6189                         if (cpus_empty(nodemask))
6190                                 continue;
6191
6192                         if (sg == NULL)
6193                                 continue;
6194                         sg = sg->next;
6195 next_sg:
6196                         oldsg = sg;
6197                         sg = sg->next;
6198                         kfree(oldsg);
6199                         if (oldsg != sched_group_nodes[i])
6200                                 goto next_sg;
6201                 }
6202                 kfree(sched_group_nodes);
6203                 sched_group_nodes_bycpu[cpu] = NULL;
6204         }
6205 #endif
6206 }
6207
6208 /*
6209  * Detach sched domains from a group of cpus specified in cpu_map
6210  * These cpus will now be attached to the NULL domain
6211  */
6212 static void detach_destroy_domains(const cpumask_t *cpu_map)
6213 {
6214         int i;
6215
6216         for_each_cpu_mask(i, *cpu_map)
6217                 cpu_attach_domain(NULL, i);
6218         synchronize_sched();
6219         arch_destroy_sched_domains(cpu_map);
6220 }
6221
6222 /*
6223  * Partition sched domains as specified by the cpumasks below.
6224  * This attaches all cpus from the cpumasks to the NULL domain,
6225  * waits for a RCU quiescent period, recalculates sched
6226  * domain information and then attaches them back to the
6227  * correct sched domains
6228  * Call with hotplug lock held
6229  */
6230 void partition_sched_domains(cpumask_t *partition1, cpumask_t *partition2)
6231 {
6232         cpumask_t change_map;
6233
6234         cpus_and(*partition1, *partition1, cpu_online_map);
6235         cpus_and(*partition2, *partition2, cpu_online_map);
6236         cpus_or(change_map, *partition1, *partition2);
6237
6238         /* Detach sched domains from all of the affected cpus */
6239         detach_destroy_domains(&change_map);
6240         if (!cpus_empty(*partition1))
6241                 build_sched_domains(partition1);
6242         if (!cpus_empty(*partition2))
6243                 build_sched_domains(partition2);
6244 }
6245
6246 #ifdef CONFIG_HOTPLUG_CPU
6247 /*
6248  * Force a reinitialization of the sched domains hierarchy.  The domains
6249  * and groups cannot be updated in place without racing with the balancing
6250  * code, so we temporarily attach all running cpus to the NULL domain
6251  * which will prevent rebalancing while the sched domains are recalculated.
6252  */
6253 static int update_sched_domains(struct notifier_block *nfb,
6254                                 unsigned long action, void *hcpu)
6255 {
6256         switch (action) {
6257         case CPU_UP_PREPARE:
6258         case CPU_DOWN_PREPARE:
6259                 detach_destroy_domains(&cpu_online_map);
6260                 return NOTIFY_OK;
6261
6262         case CPU_UP_CANCELED:
6263         case CPU_DOWN_FAILED:
6264         case CPU_ONLINE:
6265         case CPU_DEAD:
6266                 /*
6267                  * Fall through and re-initialise the domains.
6268                  */
6269                 break;
6270         default:
6271                 return NOTIFY_DONE;
6272         }
6273
6274         /* The hotplug lock is already held by cpu_up/cpu_down */
6275         arch_init_sched_domains(&cpu_online_map);
6276
6277         return NOTIFY_OK;
6278 }
6279 #endif
6280
6281 void __init sched_init_smp(void)
6282 {
6283         lock_cpu_hotplug();
6284         arch_init_sched_domains(&cpu_online_map);
6285         unlock_cpu_hotplug();
6286         /* XXX: Theoretical race here - CPU may be hotplugged now */
6287         hotcpu_notifier(update_sched_domains, 0);
6288 }
6289 #else
6290 void __init sched_init_smp(void)
6291 {
6292 }
6293 #endif /* CONFIG_SMP */
6294
6295 int in_sched_functions(unsigned long addr)
6296 {
6297         /* Linker adds these: start and end of __sched functions */
6298         extern char __sched_text_start[], __sched_text_end[];
6299         return in_lock_functions(addr) ||
6300                 (addr >= (unsigned long)__sched_text_start
6301                 && addr < (unsigned long)__sched_text_end);
6302 }
6303
6304 void __init sched_init(void)
6305 {
6306         runqueue_t *rq;
6307         int i, j, k;
6308
6309         for_each_possible_cpu(i) {
6310                 prio_array_t *array;
6311
6312                 rq = cpu_rq(i);
6313                 spin_lock_init(&rq->lock);
6314                 rq->nr_running = 0;
6315                 rq->active = rq->arrays;
6316                 rq->expired = rq->arrays + 1;
6317                 rq->best_expired_prio = MAX_PRIO;
6318
6319 #ifdef CONFIG_SMP
6320                 rq->sd = NULL;
6321                 for (j = 1; j < 3; j++)
6322                         rq->cpu_load[j] = 0;
6323                 rq->active_balance = 0;
6324                 rq->push_cpu = 0;
6325                 rq->migration_thread = NULL;
6326                 INIT_LIST_HEAD(&rq->migration_queue);
6327                 rq->cpu = i;
6328 #endif
6329                 atomic_set(&rq->nr_iowait, 0);
6330 #ifdef CONFIG_VSERVER_HARDCPU
6331                 INIT_LIST_HEAD(&rq->hold_queue);
6332 #endif
6333
6334                 for (j = 0; j < 2; j++) {
6335                         array = rq->arrays + j;
6336                         for (k = 0; k < MAX_PRIO; k++) {
6337                                 INIT_LIST_HEAD(array->queue + k);
6338                                 __clear_bit(k, array->bitmap);
6339                         }
6340                         // delimiter for bitsearch
6341                         __set_bit(MAX_PRIO, array->bitmap);
6342                 }
6343         }
6344
6345         /*
6346          * The boot idle thread does lazy MMU switching as well:
6347          */
6348         atomic_inc(&init_mm.mm_count);
6349         enter_lazy_tlb(&init_mm, current);
6350
6351         /*
6352          * Make us the idle thread. Technically, schedule() should not be
6353          * called from this thread, however somewhere below it might be,
6354          * but because we are the idle thread, we just pick up running again
6355          * when this runqueue becomes "idle".
6356          */
6357         init_idle(current, smp_processor_id());
6358 }
6359
6360 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
6361 void __might_sleep(char *file, int line)
6362 {
6363 #if defined(in_atomic)
6364         static unsigned long prev_jiffy;        /* ratelimiting */
6365
6366         if ((in_atomic() || irqs_disabled()) &&
6367             system_state == SYSTEM_RUNNING && !oops_in_progress) {
6368                 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6369                         return;
6370                 prev_jiffy = jiffies;
6371                 printk(KERN_ERR "BUG: sleeping function called from invalid"
6372                                 " context at %s:%d\n", file, line);
6373                 printk("in_atomic():%d, irqs_disabled():%d\n",
6374                         in_atomic(), irqs_disabled());
6375                 dump_stack();
6376         }
6377 #endif
6378 }
6379 EXPORT_SYMBOL(__might_sleep);
6380 #endif
6381
6382 #ifdef CONFIG_MAGIC_SYSRQ
6383 void normalize_rt_tasks(void)
6384 {
6385         struct task_struct *p;
6386         prio_array_t *array;
6387         unsigned long flags;
6388         runqueue_t *rq;
6389
6390         read_lock_irq(&tasklist_lock);
6391         for_each_process (p) {
6392                 if (!rt_task(p))
6393                         continue;
6394
6395                 rq = task_rq_lock(p, &flags);
6396
6397                 array = p->array;
6398                 if (array)
6399                         deactivate_task(p, task_rq(p));
6400                 __setscheduler(p, SCHED_NORMAL, 0);
6401                 if (array) {
6402                         vx_activate_task(p);
6403                         __activate_task(p, task_rq(p));
6404                         resched_task(rq->curr);
6405                 }
6406
6407                 task_rq_unlock(rq, &flags);
6408         }
6409         read_unlock_irq(&tasklist_lock);
6410 }
6411
6412 #endif /* CONFIG_MAGIC_SYSRQ */
6413
6414 #ifdef CONFIG_IA64
6415 /*
6416  * These functions are only useful for the IA64 MCA handling.
6417  *
6418  * They can only be called when the whole system has been
6419  * stopped - every CPU needs to be quiescent, and no scheduling
6420  * activity can take place. Using them for anything else would
6421  * be a serious bug, and as a result, they aren't even visible
6422  * under any other configuration.
6423  */
6424
6425 /**
6426  * curr_task - return the current task for a given cpu.
6427  * @cpu: the processor in question.
6428  *
6429  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6430  */
6431 task_t *curr_task(int cpu)
6432 {
6433         return cpu_curr(cpu);
6434 }
6435
6436 /**
6437  * set_curr_task - set the current task for a given cpu.
6438  * @cpu: the processor in question.
6439  * @p: the task pointer to set.
6440  *
6441  * Description: This function must only be used when non-maskable interrupts
6442  * are serviced on a separate stack.  It allows the architecture to switch the
6443  * notion of the current task on a cpu in a non-blocking manner.  This function
6444  * must be called with all CPU's synchronized, and interrupts disabled, the
6445  * and caller must save the original value of the current task (see
6446  * curr_task() above) and restore that value before reenabling interrupts and
6447  * re-starting the system.
6448  *
6449  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6450  */
6451 void set_curr_task(int cpu, task_t *p)
6452 {
6453         cpu_curr(cpu) = p;
6454 }
6455
6456 #endif