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