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