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