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