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