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