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