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