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