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