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