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