4 * Kernel scheduler and related syscalls
6 * Copyright (C) 1991-2002 Linus Torvalds
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
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
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>
46 #include <asm/unistd.h>
48 #include <asm/unistd.h>
51 #define cpu_to_node_mask(cpu) node_to_cpumask(cpu_to_node(cpu))
53 #define cpu_to_node_mask(cpu) (cpu_online_map)
57 * Convert user-nice values [ -20 ... 0 ... 19 ]
58 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
61 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
62 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
63 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
66 * 'User priority' is the nice value converted to something we
67 * can work with better when scaling various scheduler parameters,
68 * it's a [ 0 ... 39 ] range.
70 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
71 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
72 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
73 #define AVG_TIMESLICE (MIN_TIMESLICE + ((MAX_TIMESLICE - MIN_TIMESLICE) *\
74 (MAX_PRIO-1-NICE_TO_PRIO(0))/(MAX_USER_PRIO - 1)))
77 * Some helpers for converting nanosecond timing to jiffy resolution
79 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
80 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
83 * These are the 'tuning knobs' of the scheduler:
85 * Minimum timeslice is 10 msecs, default timeslice is 100 msecs,
86 * maximum timeslice is 200 msecs. Timeslices get refilled after
89 #define MIN_TIMESLICE ( 10 * HZ / 1000)
90 #define MAX_TIMESLICE (200 * HZ / 1000)
91 #define ON_RUNQUEUE_WEIGHT 30
92 #define CHILD_PENALTY 95
93 #define PARENT_PENALTY 100
95 #define PRIO_BONUS_RATIO 25
96 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
97 #define INTERACTIVE_DELTA 2
98 #define MAX_SLEEP_AVG (AVG_TIMESLICE * MAX_BONUS)
99 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
100 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
101 #define CREDIT_LIMIT 100
104 * If a task is 'interactive' then we reinsert it in the active
105 * array after it has expired its current timeslice. (it will not
106 * continue to run immediately, it will still roundrobin with
107 * other interactive tasks.)
109 * This part scales the interactivity limit depending on niceness.
111 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
112 * Here are a few examples of different nice levels:
114 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
115 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
116 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
117 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
118 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
120 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
121 * priority range a task can explore, a value of '1' means the
122 * task is rated interactive.)
124 * Ie. nice +19 tasks can never get 'interactive' enough to be
125 * reinserted into the active array. And only heavily CPU-hog nice -20
126 * tasks will be expired. Default nice 0 tasks are somewhere between,
127 * it takes some effort for them to get interactive, but it's not
131 #define CURRENT_BONUS(p) \
132 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
136 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
137 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
140 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
141 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
144 #define SCALE(v1,v1_max,v2_max) \
145 (v1) * (v2_max) / (v1_max)
148 (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
150 #define TASK_INTERACTIVE(p) \
151 ((p)->prio <= (p)->static_prio - DELTA(p))
153 #define INTERACTIVE_SLEEP(p) \
154 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
155 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
157 #define HIGH_CREDIT(p) \
158 ((p)->interactive_credit > CREDIT_LIMIT)
160 #define LOW_CREDIT(p) \
161 ((p)->interactive_credit < -CREDIT_LIMIT)
164 * BASE_TIMESLICE scales user-nice values [ -20 ... 19 ]
165 * to time slice values.
167 * The higher a thread's priority, the bigger timeslices
168 * it gets during one round of execution. But even the lowest
169 * priority thread gets MIN_TIMESLICE worth of execution time.
171 * task_timeslice() is the interface that is used by the scheduler.
174 #define BASE_TIMESLICE(p) (MIN_TIMESLICE + \
175 ((MAX_TIMESLICE - MIN_TIMESLICE) * \
176 (MAX_PRIO-1 - (p)->static_prio) / (MAX_USER_PRIO-1)))
178 static unsigned int task_timeslice(task_t *p)
180 return BASE_TIMESLICE(p);
183 #define task_hot(p, now, sd) ((now) - (p)->timestamp < (sd)->cache_hot_time)
186 * These are the runqueue data structures:
188 typedef struct runqueue runqueue_t;
190 #ifdef CONFIG_CKRM_CPU_SCHEDULE
191 #include <linux/ckrm_classqueue.h>
194 #ifdef CONFIG_CKRM_CPU_SCHEDULE
197 * if belong to different class, compare class priority
198 * otherwise compare task priority
200 #define TASK_PREEMPTS_CURR(p, rq) \
201 (((p)->cpu_class != (rq)->curr->cpu_class) && ((rq)->curr != (rq)->idle))? class_preempts_curr((p),(rq)->curr) : ((p)->prio < (rq)->curr->prio)
203 #define TASK_PREEMPTS_CURR(p, rq) \
204 ((p)->prio < (rq)->curr->prio)
208 * This is the main, per-CPU runqueue data structure.
210 * Locking rule: those places that want to lock multiple runqueues
211 * (such as the load balancing or the thread migration code), lock
212 * acquire operations must be ordered by ascending &runqueue.
218 * nr_running and cpu_load should be in the same cacheline because
219 * remote CPUs use both these fields when doing load calculation.
221 unsigned long nr_running;
222 #if defined(CONFIG_SMP)
223 unsigned long cpu_load;
225 unsigned long long nr_switches;
226 unsigned long expired_timestamp, nr_uninterruptible;
227 unsigned long long timestamp_last_tick;
229 struct mm_struct *prev_mm;
230 #ifdef CONFIG_CKRM_CPU_SCHEDULE
231 unsigned long ckrm_cpu_load;
232 struct classqueue_struct classqueue;
234 prio_array_t *active, *expired, arrays[2];
236 int best_expired_prio;
240 struct sched_domain *sd;
242 /* For active balancing */
246 task_t *migration_thread;
247 struct list_head migration_queue;
249 struct list_head hold_queue;
253 static DEFINE_PER_CPU(struct runqueue, runqueues);
255 #define for_each_domain(cpu, domain) \
256 for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
258 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
259 #define this_rq() (&__get_cpu_var(runqueues))
260 #define task_rq(p) cpu_rq(task_cpu(p))
261 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
264 * Default context-switch locking:
266 #ifndef prepare_arch_switch
267 # define prepare_arch_switch(rq, next) do { } while (0)
268 # define finish_arch_switch(rq, next) spin_unlock_irq(&(rq)->lock)
269 # define task_running(rq, p) ((rq)->curr == (p))
272 #ifdef CONFIG_CKRM_CPU_SCHEDULE
273 #include <linux/ckrm_sched.h>
274 spinlock_t cvt_lock = SPIN_LOCK_UNLOCKED;
275 rwlock_t class_list_lock = RW_LOCK_UNLOCKED;
276 LIST_HEAD(active_cpu_classes); // list of active cpu classes; anchor
277 struct ckrm_cpu_class default_cpu_class_obj;
280 * the minimum CVT allowed is the base_cvt
281 * otherwise, it will starve others
283 CVT_t get_min_cvt(int cpu)
286 struct ckrm_local_runqueue * lrq;
289 node = classqueue_get_head(bpt_queue(cpu));
290 lrq = (node) ? class_list_entry(node) : NULL;
293 min_cvt = lrq->local_cvt;
301 * update the classueue base for all the runqueues
302 * TODO: we can only update half of the min_base to solve the movebackward issue
304 static inline void check_update_class_base(int this_cpu) {
305 unsigned long min_base = 0xFFFFFFFF;
309 if (! cpu_online(this_cpu)) return;
312 * find the min_base across all the processors
314 for_each_online_cpu(i) {
316 * I should change it to directly use bpt->base
318 node = classqueue_get_head(bpt_queue(i));
319 if (node && node->prio < min_base) {
320 min_base = node->prio;
323 if (min_base != 0xFFFFFFFF)
324 classqueue_update_base(bpt_queue(this_cpu),min_base);
327 static inline void ckrm_rebalance_tick(int j,int this_cpu)
329 #ifdef CONFIG_CKRM_CPU_SCHEDULE
330 read_lock(&class_list_lock);
331 if (!(j % CVT_UPDATE_TICK))
332 update_global_cvts(this_cpu);
334 #define CKRM_BASE_UPDATE_RATE 400
335 if (! (jiffies % CKRM_BASE_UPDATE_RATE))
336 check_update_class_base(this_cpu);
338 read_unlock(&class_list_lock);
342 static inline struct ckrm_local_runqueue *rq_get_next_class(struct runqueue *rq)
344 cq_node_t *node = classqueue_get_head(&rq->classqueue);
345 return ((node) ? class_list_entry(node) : NULL);
348 static inline struct task_struct * rq_get_next_task(struct runqueue* rq)
351 struct task_struct *next;
352 struct ckrm_local_runqueue *queue;
353 int cpu = smp_processor_id();
357 if ((queue = rq_get_next_class(rq))) {
358 array = queue->active;
359 //check switch active/expired queue
360 if (unlikely(!queue->active->nr_active)) {
361 queue->active = queue->expired;
362 queue->expired = array;
363 queue->expired_timestamp = 0;
365 if (queue->active->nr_active)
366 set_top_priority(queue,
367 find_first_bit(queue->active->bitmap, MAX_PRIO));
369 classqueue_dequeue(queue->classqueue,
370 &queue->classqueue_linkobj);
371 cpu_demand_event(get_rq_local_stat(queue,cpu),CPU_DEMAND_DEQUEUE,0);
374 goto retry_next_class;
376 BUG_ON(!queue->active->nr_active);
377 next = task_list_entry(array->queue[queue->top_priority].next);
382 static inline void rq_load_inc(runqueue_t *rq, struct task_struct *p) { rq->ckrm_cpu_load += cpu_class_weight(p->cpu_class); }
383 static inline void rq_load_dec(runqueue_t *rq, struct task_struct *p) { rq->ckrm_cpu_load -= cpu_class_weight(p->cpu_class); }
385 #else /*CONFIG_CKRM_CPU_SCHEDULE*/
387 static inline struct task_struct * rq_get_next_task(struct runqueue* rq)
390 struct list_head *queue;
394 if (unlikely(!array->nr_active)) {
396 * Switch the active and expired arrays.
398 rq->active = rq->expired;
401 rq->expired_timestamp = 0;
402 rq->best_expired_prio = MAX_PRIO;
405 idx = sched_find_first_bit(array->bitmap);
406 queue = array->queue + idx;
407 return list_entry(queue->next, task_t, run_list);
410 static inline void class_enqueue_task(struct task_struct* p, prio_array_t *array) { }
411 static inline void class_dequeue_task(struct task_struct* p, prio_array_t *array) { }
412 static inline void init_cpu_classes(void) { }
413 static inline void rq_load_inc(runqueue_t *rq, struct task_struct *p) { }
414 static inline void rq_load_dec(runqueue_t *rq, struct task_struct *p) { }
415 #endif /* CONFIG_CKRM_CPU_SCHEDULE */
419 * task_rq_lock - lock the runqueue a given task resides on and disable
420 * interrupts. Note the ordering: we can safely lookup the task_rq without
421 * explicitly disabling preemption.
423 runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
428 local_irq_save(*flags);
430 spin_lock(&rq->lock);
431 if (unlikely(rq != task_rq(p))) {
432 spin_unlock_irqrestore(&rq->lock, *flags);
433 goto repeat_lock_task;
438 void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
440 spin_unlock_irqrestore(&rq->lock, *flags);
444 * rq_lock - lock a given runqueue and disable interrupts.
446 static runqueue_t *this_rq_lock(void)
452 spin_lock(&rq->lock);
457 static inline void rq_unlock(runqueue_t *rq)
459 spin_unlock_irq(&rq->lock);
463 * Adding/removing a task to/from a priority array:
465 void dequeue_task(struct task_struct *p, prio_array_t *array)
469 list_del(&p->run_list);
470 if (list_empty(array->queue + p->prio))
471 __clear_bit(p->prio, array->bitmap);
472 class_dequeue_task(p,array);
475 void enqueue_task(struct task_struct *p, prio_array_t *array)
477 list_add_tail(&p->run_list, array->queue + p->prio);
478 __set_bit(p->prio, array->bitmap);
481 class_enqueue_task(p,array);
485 * Used by the migration code - we pull tasks from the head of the
486 * remote queue so we want these tasks to show up at the head of the
489 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
491 list_add(&p->run_list, array->queue + p->prio);
492 __set_bit(p->prio, array->bitmap);
495 class_enqueue_task(p,array);
499 * effective_prio - return the priority that is based on the static
500 * priority but is modified by bonuses/penalties.
502 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
503 * into the -5 ... 0 ... +5 bonus/penalty range.
505 * We use 25% of the full 0...39 priority range so that:
507 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
508 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
510 * Both properties are important to certain workloads.
512 static int effective_prio(task_t *p)
519 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
521 prio = p->static_prio - bonus;
522 if (__vx_task_flags(p, VXF_SCHED_PRIO, 0))
523 prio += effective_vavavoom(p, MAX_USER_PRIO);
525 if (prio < MAX_RT_PRIO)
527 if (prio > MAX_PRIO-1)
533 * __activate_task - move a task to the runqueue.
535 static inline void __activate_task(task_t *p, runqueue_t *rq)
537 enqueue_task(p, rq_active(p,rq));
543 * __activate_idle_task - move idle task to the _front_ of runqueue.
545 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
547 enqueue_task_head(p, rq_active(p,rq));
552 static void recalc_task_prio(task_t *p, unsigned long long now)
554 unsigned long long __sleep_time = now - p->timestamp;
555 unsigned long sleep_time;
557 if (__sleep_time > NS_MAX_SLEEP_AVG)
558 sleep_time = NS_MAX_SLEEP_AVG;
560 sleep_time = (unsigned long)__sleep_time;
562 if (likely(sleep_time > 0)) {
564 * User tasks that sleep a long time are categorised as
565 * idle and will get just interactive status to stay active &
566 * prevent them suddenly becoming cpu hogs and starving
569 if (p->mm && p->activated != -1 &&
570 sleep_time > INTERACTIVE_SLEEP(p)) {
571 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
574 p->interactive_credit++;
577 * The lower the sleep avg a task has the more
578 * rapidly it will rise with sleep time.
580 sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
583 * Tasks with low interactive_credit are limited to
584 * one timeslice worth of sleep avg bonus.
587 sleep_time > JIFFIES_TO_NS(task_timeslice(p)))
588 sleep_time = JIFFIES_TO_NS(task_timeslice(p));
591 * Non high_credit tasks waking from uninterruptible
592 * sleep are limited in their sleep_avg rise as they
593 * are likely to be cpu hogs waiting on I/O
595 if (p->activated == -1 && !HIGH_CREDIT(p) && p->mm) {
596 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
598 else if (p->sleep_avg + sleep_time >=
599 INTERACTIVE_SLEEP(p)) {
600 p->sleep_avg = INTERACTIVE_SLEEP(p);
606 * This code gives a bonus to interactive tasks.
608 * The boost works by updating the 'average sleep time'
609 * value here, based on ->timestamp. The more time a
610 * task spends sleeping, the higher the average gets -
611 * and the higher the priority boost gets as well.
613 p->sleep_avg += sleep_time;
615 if (p->sleep_avg > NS_MAX_SLEEP_AVG) {
616 p->sleep_avg = NS_MAX_SLEEP_AVG;
618 p->interactive_credit++;
623 p->prio = effective_prio(p);
627 * activate_task - move a task to the runqueue and do priority recalculation
629 * Update all the scheduling statistics stuff. (sleep average
630 * calculation, priority modifiers, etc.)
632 static void activate_task(task_t *p, runqueue_t *rq, int local)
634 unsigned long long now;
639 /* Compensate for drifting sched_clock */
640 runqueue_t *this_rq = this_rq();
641 now = (now - this_rq->timestamp_last_tick)
642 + rq->timestamp_last_tick;
646 recalc_task_prio(p, now);
649 * This checks to make sure it's not an uninterruptible task
650 * that is now waking up.
654 * Tasks which were woken up by interrupts (ie. hw events)
655 * are most likely of interactive nature. So we give them
656 * the credit of extending their sleep time to the period
657 * of time they spend on the runqueue, waiting for execution
658 * on a CPU, first time around:
664 * Normal first-time wakeups get a credit too for
665 * on-runqueue time, but it will be weighted down:
672 __activate_task(p, rq);
676 * deactivate_task - remove a task from the runqueue.
678 static void deactivate_task(struct task_struct *p, runqueue_t *rq)
682 if (p->state == TASK_UNINTERRUPTIBLE)
683 rq->nr_uninterruptible++;
684 dequeue_task(p, p->array);
689 * resched_task - mark a task 'to be rescheduled now'.
691 * On UP this means the setting of the need_resched flag, on SMP it
692 * might also involve a cross-CPU call to trigger the scheduler on
696 static void resched_task(task_t *p)
698 int need_resched, nrpolling;
701 /* minimise the chance of sending an interrupt to poll_idle() */
702 nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
703 need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
704 nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
706 if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
707 smp_send_reschedule(task_cpu(p));
711 static inline void resched_task(task_t *p)
713 set_tsk_need_resched(p);
718 * task_curr - is this task currently executing on a CPU?
719 * @p: the task in question.
721 inline int task_curr(const task_t *p)
723 return cpu_curr(task_cpu(p)) == p;
733 struct list_head list;
734 enum request_type type;
736 /* For REQ_MOVE_TASK */
740 /* For REQ_SET_DOMAIN */
741 struct sched_domain *sd;
743 struct completion done;
747 * The task's runqueue lock must be held.
748 * Returns true if you have to wait for migration thread.
750 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
752 runqueue_t *rq = task_rq(p);
755 * If the task is not on a runqueue (and not running), then
756 * it is sufficient to simply update the task's cpu field.
758 if (!p->array && !task_running(rq, p)) {
759 set_task_cpu(p, dest_cpu);
763 init_completion(&req->done);
764 req->type = REQ_MOVE_TASK;
766 req->dest_cpu = dest_cpu;
767 list_add(&req->list, &rq->migration_queue);
772 * wait_task_inactive - wait for a thread to unschedule.
774 * The caller must ensure that the task *will* unschedule sometime soon,
775 * else this function might spin for a *long* time. This function can't
776 * be called with interrupts off, or it may introduce deadlock with
777 * smp_call_function() if an IPI is sent by the same process we are
778 * waiting to become inactive.
780 void wait_task_inactive(task_t * p)
787 rq = task_rq_lock(p, &flags);
788 /* Must be off runqueue entirely, not preempted. */
789 if (unlikely(p->array)) {
790 /* If it's preempted, we yield. It could be a while. */
791 preempted = !task_running(rq, p);
792 task_rq_unlock(rq, &flags);
798 task_rq_unlock(rq, &flags);
802 * kick_process - kick a running thread to enter/exit the kernel
803 * @p: the to-be-kicked thread
805 * Cause a process which is running on another CPU to enter
806 * kernel-mode, without any delay. (to get signals handled.)
808 void kick_process(task_t *p)
814 if ((cpu != smp_processor_id()) && task_curr(p))
815 smp_send_reschedule(cpu);
819 EXPORT_SYMBOL_GPL(kick_process);
822 * Return a low guess at the load of a migration-source cpu.
824 * We want to under-estimate the load of migration sources, to
825 * balance conservatively.
827 static inline unsigned long source_load(int cpu)
829 runqueue_t *rq = cpu_rq(cpu);
830 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
832 return min(rq->cpu_load, load_now);
836 * Return a high guess at the load of a migration-target cpu
838 static inline unsigned long target_load(int cpu)
840 runqueue_t *rq = cpu_rq(cpu);
841 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
843 return max(rq->cpu_load, load_now);
849 * wake_idle() is useful especially on SMT architectures to wake a
850 * task onto an idle sibling if we would otherwise wake it onto a
853 * Returns the CPU we should wake onto.
855 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
856 static int wake_idle(int cpu, task_t *p)
859 runqueue_t *rq = cpu_rq(cpu);
860 struct sched_domain *sd;
867 if (!(sd->flags & SD_WAKE_IDLE))
870 cpus_and(tmp, sd->span, cpu_online_map);
871 for_each_cpu_mask(i, tmp) {
872 if (!cpu_isset(i, p->cpus_allowed))
882 static inline int wake_idle(int cpu, task_t *p)
889 * try_to_wake_up - wake up a thread
890 * @p: the to-be-woken-up thread
891 * @state: the mask of task states that can be woken
892 * @sync: do a synchronous wakeup?
894 * Put it on the run-queue if it's not already there. The "current"
895 * thread is always on the run-queue (except when the actual
896 * re-schedule is in progress), and as such you're allowed to do
897 * the simpler "current->state = TASK_RUNNING" to mark yourself
898 * runnable without the overhead of this.
900 * returns failure only if the task is already active.
902 static int try_to_wake_up(task_t * p, unsigned int state, int sync)
904 int cpu, this_cpu, success = 0;
909 unsigned long load, this_load;
910 struct sched_domain *sd;
914 rq = task_rq_lock(p, &flags);
915 old_state = p->state;
916 if (!(old_state & state))
923 this_cpu = smp_processor_id();
926 if (unlikely(task_running(rq, p)))
931 if (cpu == this_cpu || unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
934 load = source_load(cpu);
935 this_load = target_load(this_cpu);
938 * If sync wakeup then subtract the (maximum possible) effect of
939 * the currently running task from the load of the current CPU:
942 this_load -= SCHED_LOAD_SCALE;
944 /* Don't pull the task off an idle CPU to a busy one */
945 if (load < SCHED_LOAD_SCALE/2 && this_load > SCHED_LOAD_SCALE/2)
948 new_cpu = this_cpu; /* Wake to this CPU if we can */
951 * Scan domains for affine wakeup and passive balancing
954 for_each_domain(this_cpu, sd) {
955 unsigned int imbalance;
957 * Start passive balancing when half the imbalance_pct
960 imbalance = sd->imbalance_pct + (sd->imbalance_pct - 100) / 2;
962 if ( ((sd->flags & SD_WAKE_AFFINE) &&
963 !task_hot(p, rq->timestamp_last_tick, sd))
964 || ((sd->flags & SD_WAKE_BALANCE) &&
965 imbalance*this_load <= 100*load) ) {
967 * Now sd has SD_WAKE_AFFINE and p is cache cold in sd
968 * or sd has SD_WAKE_BALANCE and there is an imbalance
970 if (cpu_isset(cpu, sd->span))
975 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
977 new_cpu = wake_idle(new_cpu, p);
978 if (new_cpu != cpu && cpu_isset(new_cpu, p->cpus_allowed)) {
979 set_task_cpu(p, new_cpu);
980 task_rq_unlock(rq, &flags);
981 /* might preempt at this point */
982 rq = task_rq_lock(p, &flags);
983 old_state = p->state;
984 if (!(old_state & state))
989 this_cpu = smp_processor_id();
994 #endif /* CONFIG_SMP */
995 if (old_state == TASK_UNINTERRUPTIBLE) {
996 rq->nr_uninterruptible--;
998 * Tasks on involuntary sleep don't earn
999 * sleep_avg beyond just interactive state.
1005 * Sync wakeups (i.e. those types of wakeups where the waker
1006 * has indicated that it will leave the CPU in short order)
1007 * don't trigger a preemption, if the woken up task will run on
1008 * this cpu. (in this case the 'I will reschedule' promise of
1009 * the waker guarantees that the freshly woken up task is going
1010 * to be considered on this CPU.)
1012 activate_task(p, rq, cpu == this_cpu);
1013 if (!sync || cpu != this_cpu) {
1014 if (TASK_PREEMPTS_CURR(p, rq))
1015 resched_task(rq->curr);
1020 p->state = TASK_RUNNING;
1022 task_rq_unlock(rq, &flags);
1027 int fastcall wake_up_process(task_t * p)
1029 return try_to_wake_up(p, TASK_STOPPED |
1030 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1033 EXPORT_SYMBOL(wake_up_process);
1035 int fastcall wake_up_state(task_t *p, unsigned int state)
1037 return try_to_wake_up(p, state, 0);
1041 * Perform scheduler related setup for a newly forked process p.
1042 * p is forked by current.
1044 void fastcall sched_fork(task_t *p)
1047 * We mark the process as running here, but have not actually
1048 * inserted it onto the runqueue yet. This guarantees that
1049 * nobody will actually run it, and a signal or other external
1050 * event cannot wake it up and insert it on the runqueue either.
1052 p->state = TASK_RUNNING;
1053 INIT_LIST_HEAD(&p->run_list);
1055 spin_lock_init(&p->switch_lock);
1056 #ifdef CONFIG_PREEMPT
1058 * During context-switch we hold precisely one spinlock, which
1059 * schedule_tail drops. (in the common case it's this_rq()->lock,
1060 * but it also can be p->switch_lock.) So we compensate with a count
1061 * of 1. Also, we want to start with kernel preemption disabled.
1063 p->thread_info->preempt_count = 1;
1066 * Share the timeslice between parent and child, thus the
1067 * total amount of pending timeslices in the system doesn't change,
1068 * resulting in more scheduling fairness.
1070 local_irq_disable();
1071 p->time_slice = (current->time_slice + 1) >> 1;
1073 * The remainder of the first timeslice might be recovered by
1074 * the parent if the child exits early enough.
1076 p->first_time_slice = 1;
1077 current->time_slice >>= 1;
1078 p->timestamp = sched_clock();
1079 if (!current->time_slice) {
1081 * This case is rare, it happens when the parent has only
1082 * a single jiffy left from its timeslice. Taking the
1083 * runqueue lock is not a problem.
1085 current->time_slice = 1;
1087 scheduler_tick(0, 0);
1095 * wake_up_forked_process - wake up a freshly forked process.
1097 * This function will do some initial scheduler statistics housekeeping
1098 * that must be done for every newly created process.
1100 void fastcall wake_up_forked_process(task_t * p)
1102 unsigned long flags;
1103 runqueue_t *rq = task_rq_lock(current, &flags);
1105 BUG_ON(p->state != TASK_RUNNING);
1108 * We decrease the sleep average of forking parents
1109 * and children as well, to keep max-interactive tasks
1110 * from forking tasks that are max-interactive.
1112 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1113 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1115 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1116 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1118 p->interactive_credit = 0;
1120 p->prio = effective_prio(p);
1121 set_task_cpu(p, smp_processor_id());
1123 if (unlikely(!current->array))
1124 __activate_task(p, rq);
1126 p->prio = current->prio;
1127 list_add_tail(&p->run_list, ¤t->run_list);
1128 p->array = current->array;
1129 p->array->nr_active++;
1133 task_rq_unlock(rq, &flags);
1137 * Potentially available exiting-child timeslices are
1138 * retrieved here - this way the parent does not get
1139 * penalized for creating too many threads.
1141 * (this cannot be used to 'generate' timeslices
1142 * artificially, because any timeslice recovered here
1143 * was given away by the parent in the first place.)
1145 void fastcall sched_exit(task_t * p)
1147 unsigned long flags;
1150 local_irq_save(flags);
1151 if (p->first_time_slice) {
1152 p->parent->time_slice += p->time_slice;
1153 if (unlikely(p->parent->time_slice > MAX_TIMESLICE))
1154 p->parent->time_slice = MAX_TIMESLICE;
1156 local_irq_restore(flags);
1158 * If the child was a (relative-) CPU hog then decrease
1159 * the sleep_avg of the parent as well.
1161 rq = task_rq_lock(p->parent, &flags);
1162 if (p->sleep_avg < p->parent->sleep_avg)
1163 p->parent->sleep_avg = p->parent->sleep_avg /
1164 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1166 task_rq_unlock(rq, &flags);
1170 * finish_task_switch - clean up after a task-switch
1171 * @prev: the thread we just switched away from.
1173 * We enter this with the runqueue still locked, and finish_arch_switch()
1174 * will unlock it along with doing any other architecture-specific cleanup
1177 * Note that we may have delayed dropping an mm in context_switch(). If
1178 * so, we finish that here outside of the runqueue lock. (Doing it
1179 * with the lock held can cause deadlocks; see schedule() for
1182 static void finish_task_switch(task_t *prev)
1184 runqueue_t *rq = this_rq();
1185 struct mm_struct *mm = rq->prev_mm;
1186 unsigned long prev_task_flags;
1191 * A task struct has one reference for the use as "current".
1192 * If a task dies, then it sets TASK_ZOMBIE in tsk->state and calls
1193 * schedule one last time. The schedule call will never return,
1194 * and the scheduled task must drop that reference.
1195 * The test for TASK_ZOMBIE must occur while the runqueue locks are
1196 * still held, otherwise prev could be scheduled on another cpu, die
1197 * there before we look at prev->state, and then the reference would
1199 * Manfred Spraul <manfred@colorfullife.com>
1201 prev_task_flags = prev->flags;
1202 finish_arch_switch(rq, prev);
1205 if (unlikely(prev_task_flags & PF_DEAD))
1206 put_task_struct(prev);
1210 * schedule_tail - first thing a freshly forked thread must call.
1211 * @prev: the thread we just switched away from.
1213 asmlinkage void schedule_tail(task_t *prev)
1215 finish_task_switch(prev);
1217 if (current->set_child_tid)
1218 put_user(current->pid, current->set_child_tid);
1222 * context_switch - switch to the new MM and the new
1223 * thread's register state.
1226 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1228 struct mm_struct *mm = next->mm;
1229 struct mm_struct *oldmm = prev->active_mm;
1231 if (unlikely(!mm)) {
1232 next->active_mm = oldmm;
1233 atomic_inc(&oldmm->mm_count);
1234 enter_lazy_tlb(oldmm, next);
1236 switch_mm(oldmm, mm, next);
1238 if (unlikely(!prev->mm)) {
1239 prev->active_mm = NULL;
1240 WARN_ON(rq->prev_mm);
1241 rq->prev_mm = oldmm;
1244 /* Here we just switch the register state and the stack. */
1245 switch_to(prev, next, prev);
1251 * nr_running, nr_uninterruptible and nr_context_switches:
1253 * externally visible scheduler statistics: current number of runnable
1254 * threads, current number of uninterruptible-sleeping threads, total
1255 * number of context switches performed since bootup.
1257 unsigned long nr_running(void)
1259 unsigned long i, sum = 0;
1262 sum += cpu_rq(i)->nr_running;
1267 unsigned long nr_uninterruptible(void)
1269 unsigned long i, sum = 0;
1271 for_each_online_cpu(i)
1272 sum += cpu_rq(i)->nr_uninterruptible;
1277 unsigned long long nr_context_switches(void)
1279 unsigned long long i, sum = 0;
1281 for_each_online_cpu(i)
1282 sum += cpu_rq(i)->nr_switches;
1287 unsigned long nr_iowait(void)
1289 unsigned long i, sum = 0;
1291 for_each_online_cpu(i)
1292 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1298 * double_rq_lock - safely lock two runqueues
1300 * Note this does not disable interrupts like task_rq_lock,
1301 * you need to do so manually before calling.
1303 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1306 spin_lock(&rq1->lock);
1309 spin_lock(&rq1->lock);
1310 spin_lock(&rq2->lock);
1312 spin_lock(&rq2->lock);
1313 spin_lock(&rq1->lock);
1319 * double_rq_unlock - safely unlock two runqueues
1321 * Note this does not restore interrupts like task_rq_unlock,
1322 * you need to do so manually after calling.
1324 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1326 spin_unlock(&rq1->lock);
1328 spin_unlock(&rq2->lock);
1341 * find_idlest_cpu - find the least busy runqueue.
1343 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1344 struct sched_domain *sd)
1346 unsigned long load, min_load, this_load;
1351 min_load = ULONG_MAX;
1353 cpus_and(mask, sd->span, cpu_online_map);
1354 cpus_and(mask, mask, p->cpus_allowed);
1356 for_each_cpu_mask(i, mask) {
1357 load = target_load(i);
1359 if (load < min_load) {
1363 /* break out early on an idle CPU: */
1369 /* add +1 to account for the new task */
1370 this_load = source_load(this_cpu) + SCHED_LOAD_SCALE;
1373 * Would with the addition of the new task to the
1374 * current CPU there be an imbalance between this
1375 * CPU and the idlest CPU?
1377 * Use half of the balancing threshold - new-context is
1378 * a good opportunity to balance.
1380 if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1387 * wake_up_forked_thread - wake up a freshly forked thread.
1389 * This function will do some initial scheduler statistics housekeeping
1390 * that must be done for every newly created context, and it also does
1391 * runqueue balancing.
1393 void fastcall wake_up_forked_thread(task_t * p)
1395 unsigned long flags;
1396 int this_cpu = get_cpu(), cpu;
1397 struct sched_domain *tmp, *sd = NULL;
1398 runqueue_t *this_rq = cpu_rq(this_cpu), *rq;
1401 * Find the largest domain that this CPU is part of that
1402 * is willing to balance on clone:
1404 for_each_domain(this_cpu, tmp)
1405 if (tmp->flags & SD_BALANCE_CLONE)
1408 cpu = find_idlest_cpu(p, this_cpu, sd);
1412 local_irq_save(flags);
1415 double_rq_lock(this_rq, rq);
1417 BUG_ON(p->state != TASK_RUNNING);
1420 * We did find_idlest_cpu() unlocked, so in theory
1421 * the mask could have changed - just dont migrate
1424 if (unlikely(!cpu_isset(cpu, p->cpus_allowed))) {
1426 double_rq_unlock(this_rq, rq);
1430 * We decrease the sleep average of forking parents
1431 * and children as well, to keep max-interactive tasks
1432 * from forking tasks that are max-interactive.
1434 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1435 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1437 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1438 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1440 p->interactive_credit = 0;
1442 p->prio = effective_prio(p);
1443 set_task_cpu(p, cpu);
1445 if (cpu == this_cpu) {
1446 if (unlikely(!current->array))
1447 __activate_task(p, rq);
1449 p->prio = current->prio;
1450 list_add_tail(&p->run_list, ¤t->run_list);
1451 p->array = current->array;
1452 p->array->nr_active++;
1457 /* Not the local CPU - must adjust timestamp */
1458 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1459 + rq->timestamp_last_tick;
1460 __activate_task(p, rq);
1461 if (TASK_PREEMPTS_CURR(p, rq))
1462 resched_task(rq->curr);
1465 double_rq_unlock(this_rq, rq);
1466 local_irq_restore(flags);
1471 * If dest_cpu is allowed for this process, migrate the task to it.
1472 * This is accomplished by forcing the cpu_allowed mask to only
1473 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1474 * the cpu_allowed mask is restored.
1476 static void sched_migrate_task(task_t *p, int dest_cpu)
1478 migration_req_t req;
1480 unsigned long flags;
1482 rq = task_rq_lock(p, &flags);
1483 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1484 || unlikely(cpu_is_offline(dest_cpu)))
1487 /* force the process onto the specified CPU */
1488 if (migrate_task(p, dest_cpu, &req)) {
1489 /* Need to wait for migration thread (might exit: take ref). */
1490 struct task_struct *mt = rq->migration_thread;
1491 get_task_struct(mt);
1492 task_rq_unlock(rq, &flags);
1493 wake_up_process(mt);
1494 put_task_struct(mt);
1495 wait_for_completion(&req.done);
1499 task_rq_unlock(rq, &flags);
1503 * sched_balance_exec(): find the highest-level, exec-balance-capable
1504 * domain and try to migrate the task to the least loaded CPU.
1506 * execve() is a valuable balancing opportunity, because at this point
1507 * the task has the smallest effective memory and cache footprint.
1509 void sched_balance_exec(void)
1511 struct sched_domain *tmp, *sd = NULL;
1512 int new_cpu, this_cpu = get_cpu();
1514 /* Prefer the current CPU if there's only this task running */
1515 if (this_rq()->nr_running <= 1)
1518 for_each_domain(this_cpu, tmp)
1519 if (tmp->flags & SD_BALANCE_EXEC)
1523 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1524 if (new_cpu != this_cpu) {
1526 sched_migrate_task(current, new_cpu);
1535 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1537 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1539 if (unlikely(!spin_trylock(&busiest->lock))) {
1540 if (busiest < this_rq) {
1541 spin_unlock(&this_rq->lock);
1542 spin_lock(&busiest->lock);
1543 spin_lock(&this_rq->lock);
1545 spin_lock(&busiest->lock);
1550 * pull_task - move a task from a remote runqueue to the local runqueue.
1551 * Both runqueues must be locked.
1554 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1555 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1557 dequeue_task(p, src_array);
1558 src_rq->nr_running--;
1559 rq_load_dec(src_rq,p);
1561 set_task_cpu(p, this_cpu);
1562 this_rq->nr_running++;
1563 rq_load_inc(this_rq,p);
1564 enqueue_task(p, this_array);
1566 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1567 + this_rq->timestamp_last_tick;
1569 * Note that idle threads have a prio of MAX_PRIO, for this test
1570 * to be always true for them.
1572 if (TASK_PREEMPTS_CURR(p, this_rq))
1573 resched_task(this_rq->curr);
1577 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1580 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1581 struct sched_domain *sd, enum idle_type idle)
1584 * We do not migrate tasks that are:
1585 * 1) running (obviously), or
1586 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1587 * 3) are cache-hot on their current CPU.
1589 if (task_running(rq, p))
1591 if (!cpu_isset(this_cpu, p->cpus_allowed))
1594 /* Aggressive migration if we've failed balancing */
1595 if (idle == NEWLY_IDLE ||
1596 sd->nr_balance_failed < sd->cache_nice_tries) {
1597 if (task_hot(p, rq->timestamp_last_tick, sd))
1604 #ifdef CONFIG_CKRM_CPU_SCHEDULE
1606 struct ckrm_cpu_class *find_unbalanced_class(int busiest_cpu, int this_cpu, unsigned long *cls_imbalance)
1608 struct ckrm_cpu_class *most_unbalanced_class = NULL;
1609 struct ckrm_cpu_class *clsptr;
1610 int max_unbalance = 0;
1612 list_for_each_entry(clsptr,&active_cpu_classes,links) {
1613 struct ckrm_local_runqueue *this_lrq = get_ckrm_local_runqueue(clsptr,this_cpu);
1614 struct ckrm_local_runqueue *busiest_lrq = get_ckrm_local_runqueue(clsptr,busiest_cpu);
1615 int unbalance_degree;
1617 unbalance_degree = (local_queue_nr_running(busiest_lrq) - local_queue_nr_running(this_lrq)) * cpu_class_weight(clsptr);
1618 if (unbalance_degree >= *cls_imbalance)
1619 continue; // already looked at this class
1621 if (unbalance_degree > max_unbalance) {
1622 max_unbalance = unbalance_degree;
1623 most_unbalanced_class = clsptr;
1626 *cls_imbalance = max_unbalance;
1627 return most_unbalanced_class;
1632 * find_busiest_queue - find the busiest runqueue among the cpus in cpumask.
1634 static int find_busiest_cpu(runqueue_t *this_rq, int this_cpu, int idle,
1637 int cpu_load, load, max_load, i, busiest_cpu;
1638 runqueue_t *busiest, *rq_src;
1641 /*Hubertus ... the concept of nr_running is replace with cpu_load */
1642 cpu_load = this_rq->ckrm_cpu_load;
1648 for_each_online_cpu(i) {
1650 load = rq_src->ckrm_cpu_load;
1652 if ((load > max_load) && (rq_src != this_rq)) {
1659 if (likely(!busiest))
1662 *imbalance = max_load - cpu_load;
1664 /* It needs an at least ~25% imbalance to trigger balancing. */
1665 if (!idle && ((*imbalance)*4 < max_load)) {
1670 double_lock_balance(this_rq, busiest);
1672 * Make sure nothing changed since we checked the
1675 if (busiest->ckrm_cpu_load <= cpu_load) {
1676 spin_unlock(&busiest->lock);
1680 return (busiest ? busiest_cpu : -1);
1683 static int load_balance(int this_cpu, runqueue_t *this_rq,
1684 struct sched_domain *sd, enum idle_type idle)
1688 runqueue_t *busiest;
1689 prio_array_t *array;
1690 struct list_head *head, *curr;
1692 struct ckrm_local_runqueue * busiest_local_queue;
1693 struct ckrm_cpu_class *clsptr;
1695 unsigned long cls_imbalance; // so we can retry other classes
1697 // need to update global CVT based on local accumulated CVTs
1698 read_lock(&class_list_lock);
1699 busiest_cpu = find_busiest_cpu(this_rq, this_cpu, idle, &imbalance);
1700 if (busiest_cpu == -1)
1703 busiest = cpu_rq(busiest_cpu);
1706 * We only want to steal a number of tasks equal to 1/2 the imbalance,
1707 * otherwise we'll just shift the imbalance to the new queue:
1711 /* now find class on that runqueue with largest inbalance */
1712 cls_imbalance = 0xFFFFFFFF;
1715 clsptr = find_unbalanced_class(busiest_cpu, this_cpu, &cls_imbalance);
1719 busiest_local_queue = get_ckrm_local_runqueue(clsptr,busiest_cpu);
1720 weight = cpu_class_weight(clsptr);
1723 * We first consider expired tasks. Those will likely not be
1724 * executed in the near future, and they are most likely to
1725 * be cache-cold, thus switching CPUs has the least effect
1728 if (busiest_local_queue->expired->nr_active)
1729 array = busiest_local_queue->expired;
1731 array = busiest_local_queue->active;
1734 /* Start searching at priority 0: */
1738 idx = sched_find_first_bit(array->bitmap);
1740 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1741 if (idx >= MAX_PRIO) {
1742 if (array == busiest_local_queue->expired && busiest_local_queue->active->nr_active) {
1743 array = busiest_local_queue->active;
1746 goto retry_other_class;
1749 head = array->queue + idx;
1752 tmp = list_entry(curr, task_t, run_list);
1756 if (!can_migrate_task(tmp, busiest, this_cpu, sd,idle)) {
1762 pull_task(busiest, array, tmp, this_rq, rq_active(tmp,this_rq),this_cpu);
1764 * tmp BUG FIX: hzheng
1765 * load balancing can make the busiest local queue empty
1766 * thus it should be removed from bpt
1768 if (! local_queue_nr_running(busiest_local_queue)) {
1769 classqueue_dequeue(busiest_local_queue->classqueue,&busiest_local_queue->classqueue_linkobj);
1770 cpu_demand_event(get_rq_local_stat(busiest_local_queue,busiest_cpu),CPU_DEMAND_DEQUEUE,0);
1773 imbalance -= weight;
1774 if (!idle && (imbalance>0)) {
1781 spin_unlock(&busiest->lock);
1783 read_unlock(&class_list_lock);
1788 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
1791 #else /* CONFIG_CKRM_CPU_SCHEDULE */
1793 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1794 * as part of a balancing operation within "domain". Returns the number of
1797 * Called with both runqueues locked.
1799 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1800 unsigned long max_nr_move, struct sched_domain *sd,
1801 enum idle_type idle)
1803 prio_array_t *array, *dst_array;
1804 struct list_head *head, *curr;
1805 int idx, pulled = 0;
1808 if (max_nr_move <= 0 || busiest->nr_running <= 1)
1812 * We first consider expired tasks. Those will likely not be
1813 * executed in the near future, and they are most likely to
1814 * be cache-cold, thus switching CPUs has the least effect
1817 if (busiest->expired->nr_active) {
1818 array = busiest->expired;
1819 dst_array = this_rq->expired;
1821 array = busiest->active;
1822 dst_array = this_rq->active;
1826 /* Start searching at priority 0: */
1830 idx = sched_find_first_bit(array->bitmap);
1832 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1833 if (idx >= MAX_PRIO) {
1834 if (array == busiest->expired && busiest->active->nr_active) {
1835 array = busiest->active;
1836 dst_array = this_rq->active;
1842 head = array->queue + idx;
1845 tmp = list_entry(curr, task_t, run_list);
1849 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
1855 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
1858 /* We only want to steal up to the prescribed number of tasks. */
1859 if (pulled < max_nr_move) {
1870 * find_busiest_group finds and returns the busiest CPU group within the
1871 * domain. It calculates and returns the number of tasks which should be
1872 * moved to restore balance via the imbalance parameter.
1874 static struct sched_group *
1875 find_busiest_group(struct sched_domain *sd, int this_cpu,
1876 unsigned long *imbalance, enum idle_type idle)
1878 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
1879 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
1881 max_load = this_load = total_load = total_pwr = 0;
1889 local_group = cpu_isset(this_cpu, group->cpumask);
1891 /* Tally up the load of all CPUs in the group */
1893 cpus_and(tmp, group->cpumask, cpu_online_map);
1894 if (unlikely(cpus_empty(tmp)))
1897 for_each_cpu_mask(i, tmp) {
1898 /* Bias balancing toward cpus of our domain */
1900 load = target_load(i);
1902 load = source_load(i);
1911 total_load += avg_load;
1912 total_pwr += group->cpu_power;
1914 /* Adjust by relative CPU power of the group */
1915 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1918 this_load = avg_load;
1921 } else if (avg_load > max_load) {
1922 max_load = avg_load;
1926 group = group->next;
1927 } while (group != sd->groups);
1929 if (!busiest || this_load >= max_load)
1932 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
1934 if (this_load >= avg_load ||
1935 100*max_load <= sd->imbalance_pct*this_load)
1939 * We're trying to get all the cpus to the average_load, so we don't
1940 * want to push ourselves above the average load, nor do we wish to
1941 * reduce the max loaded cpu below the average load, as either of these
1942 * actions would just result in more rebalancing later, and ping-pong
1943 * tasks around. Thus we look for the minimum possible imbalance.
1944 * Negative imbalances (*we* are more loaded than anyone else) will
1945 * be counted as no imbalance for these purposes -- we can't fix that
1946 * by pulling tasks to us. Be careful of negative numbers as they'll
1947 * appear as very large values with unsigned longs.
1949 *imbalance = min(max_load - avg_load, avg_load - this_load);
1951 /* How much load to actually move to equalise the imbalance */
1952 *imbalance = (*imbalance * min(busiest->cpu_power, this->cpu_power))
1955 if (*imbalance < SCHED_LOAD_SCALE - 1) {
1956 unsigned long pwr_now = 0, pwr_move = 0;
1959 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
1965 * OK, we don't have enough imbalance to justify moving tasks,
1966 * however we may be able to increase total CPU power used by
1970 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
1971 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
1972 pwr_now /= SCHED_LOAD_SCALE;
1974 /* Amount of load we'd subtract */
1975 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
1977 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
1980 /* Amount of load we'd add */
1981 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
1984 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
1985 pwr_move /= SCHED_LOAD_SCALE;
1987 /* Move if we gain another 8th of a CPU worth of throughput */
1988 if (pwr_move < pwr_now + SCHED_LOAD_SCALE / 8)
1995 /* Get rid of the scaling factor, rounding down as we divide */
1996 *imbalance = (*imbalance + 1) / SCHED_LOAD_SCALE;
2001 if (busiest && (idle == NEWLY_IDLE ||
2002 (idle == IDLE && max_load > SCHED_LOAD_SCALE)) ) {
2012 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2014 static runqueue_t *find_busiest_queue(struct sched_group *group)
2017 unsigned long load, max_load = 0;
2018 runqueue_t *busiest = NULL;
2021 cpus_and(tmp, group->cpumask, cpu_online_map);
2022 for_each_cpu_mask(i, tmp) {
2023 load = source_load(i);
2025 if (load > max_load) {
2027 busiest = cpu_rq(i);
2035 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2036 * tasks if there is an imbalance.
2038 * Called with this_rq unlocked.
2040 static int load_balance(int this_cpu, runqueue_t *this_rq,
2041 struct sched_domain *sd, enum idle_type idle)
2043 struct sched_group *group;
2044 runqueue_t *busiest;
2045 unsigned long imbalance;
2048 spin_lock(&this_rq->lock);
2050 group = find_busiest_group(sd, this_cpu, &imbalance, idle);
2054 busiest = find_busiest_queue(group);
2058 * This should be "impossible", but since load
2059 * balancing is inherently racy and statistical,
2060 * it could happen in theory.
2062 if (unlikely(busiest == this_rq)) {
2068 if (busiest->nr_running > 1) {
2070 * Attempt to move tasks. If find_busiest_group has found
2071 * an imbalance but busiest->nr_running <= 1, the group is
2072 * still unbalanced. nr_moved simply stays zero, so it is
2073 * correctly treated as an imbalance.
2075 double_lock_balance(this_rq, busiest);
2076 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2077 imbalance, sd, idle);
2078 spin_unlock(&busiest->lock);
2080 spin_unlock(&this_rq->lock);
2083 sd->nr_balance_failed++;
2085 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2088 spin_lock(&busiest->lock);
2089 if (!busiest->active_balance) {
2090 busiest->active_balance = 1;
2091 busiest->push_cpu = this_cpu;
2094 spin_unlock(&busiest->lock);
2096 wake_up_process(busiest->migration_thread);
2099 * We've kicked active balancing, reset the failure
2102 sd->nr_balance_failed = sd->cache_nice_tries;
2105 sd->nr_balance_failed = 0;
2107 /* We were unbalanced, so reset the balancing interval */
2108 sd->balance_interval = sd->min_interval;
2113 spin_unlock(&this_rq->lock);
2115 /* tune up the balancing interval */
2116 if (sd->balance_interval < sd->max_interval)
2117 sd->balance_interval *= 2;
2123 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2124 * tasks if there is an imbalance.
2126 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2127 * this_rq is locked.
2129 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2130 struct sched_domain *sd)
2132 struct sched_group *group;
2133 runqueue_t *busiest = NULL;
2134 unsigned long imbalance;
2137 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
2141 busiest = find_busiest_queue(group);
2142 if (!busiest || busiest == this_rq)
2145 /* Attempt to move tasks */
2146 double_lock_balance(this_rq, busiest);
2148 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2149 imbalance, sd, NEWLY_IDLE);
2151 spin_unlock(&busiest->lock);
2158 * idle_balance is called by schedule() if this_cpu is about to become
2159 * idle. Attempts to pull tasks from other CPUs.
2161 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
2163 struct sched_domain *sd;
2165 for_each_domain(this_cpu, sd) {
2166 if (sd->flags & SD_BALANCE_NEWIDLE) {
2167 if (load_balance_newidle(this_cpu, this_rq, sd)) {
2168 /* We've pulled tasks over so stop searching */
2176 * active_load_balance is run by migration threads. It pushes a running
2177 * task off the cpu. It can be required to correctly have at least 1 task
2178 * running on each physical CPU where possible, and not have a physical /
2179 * logical imbalance.
2181 * Called with busiest locked.
2183 static void active_load_balance(runqueue_t *busiest, int busiest_cpu)
2185 struct sched_domain *sd;
2186 struct sched_group *group, *busy_group;
2189 if (busiest->nr_running <= 1)
2192 for_each_domain(busiest_cpu, sd)
2193 if (cpu_isset(busiest->push_cpu, sd->span))
2201 while (!cpu_isset(busiest_cpu, group->cpumask))
2202 group = group->next;
2211 if (group == busy_group)
2214 cpus_and(tmp, group->cpumask, cpu_online_map);
2215 if (!cpus_weight(tmp))
2218 for_each_cpu_mask(i, tmp) {
2224 rq = cpu_rq(push_cpu);
2227 * This condition is "impossible", but since load
2228 * balancing is inherently a bit racy and statistical,
2229 * it can trigger.. Reported by Bjorn Helgaas on a
2232 if (unlikely(busiest == rq))
2234 double_lock_balance(busiest, rq);
2235 move_tasks(rq, push_cpu, busiest, 1, sd, IDLE);
2236 spin_unlock(&rq->lock);
2238 group = group->next;
2239 } while (group != sd->groups);
2242 #endif /* CONFIG_CKRM_CPU_SCHEDULE*/
2245 * rebalance_tick will get called every timer tick, on every CPU.
2247 * It checks each scheduling domain to see if it is due to be balanced,
2248 * and initiates a balancing operation if so.
2250 * Balancing parameters are set up in arch_init_sched_domains.
2253 /* Don't have all balancing operations going off at once */
2254 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2256 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2257 enum idle_type idle)
2259 unsigned long old_load, this_load;
2260 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2261 struct sched_domain *sd;
2263 ckrm_rebalance_tick(j,this_cpu);
2265 /* Update our load */
2266 old_load = this_rq->cpu_load;
2267 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
2269 * Round up the averaging division if load is increasing. This
2270 * prevents us from getting stuck on 9 if the load is 10, for
2273 if (this_load > old_load)
2275 this_rq->cpu_load = (old_load + this_load) / 2;
2277 for_each_domain(this_cpu, sd) {
2278 unsigned long interval = sd->balance_interval;
2281 interval *= sd->busy_factor;
2283 /* scale ms to jiffies */
2284 interval = msecs_to_jiffies(interval);
2285 if (unlikely(!interval))
2288 if (j - sd->last_balance >= interval) {
2289 if (load_balance(this_cpu, this_rq, sd, idle)) {
2290 /* We've pulled tasks over so no longer idle */
2293 sd->last_balance += interval;
2299 * on UP we do not need to balance between CPUs:
2301 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2303 ckrm_rebalance_tick(jiffies,cpu);
2306 static inline void idle_balance(int cpu, runqueue_t *rq)
2311 static inline int wake_priority_sleeper(runqueue_t *rq)
2313 #ifdef CONFIG_SCHED_SMT
2315 * If an SMT sibling task has been put to sleep for priority
2316 * reasons reschedule the idle task to see if it can now run.
2318 if (rq->nr_running) {
2319 resched_task(rq->idle);
2326 DEFINE_PER_CPU(struct kernel_stat, kstat) = { { 0 } };
2328 EXPORT_PER_CPU_SYMBOL(kstat);
2331 * We place interactive tasks back into the active array, if possible.
2333 * To guarantee that this does not starve expired tasks we ignore the
2334 * interactivity of a task if the first expired task had to wait more
2335 * than a 'reasonable' amount of time. This deadline timeout is
2336 * load-dependent, as the frequency of array switched decreases with
2337 * increasing number of running tasks. We also ignore the interactivity
2338 * if a better static_prio task has expired:
2341 #ifndef CONFIG_CKRM_CPU_SCHEDULE
2342 #define EXPIRED_STARVING(rq) \
2343 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2344 (jiffies - (rq)->expired_timestamp >= \
2345 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2346 ((rq)->curr->static_prio > (rq)->best_expired_prio))
2348 #define EXPIRED_STARVING(rq) \
2349 (STARVATION_LIMIT && ((rq)->expired_timestamp && \
2350 (jiffies - (rq)->expired_timestamp >= \
2351 STARVATION_LIMIT * (local_queue_nr_running(rq)) + 1)))
2355 * This function gets called by the timer code, with HZ frequency.
2356 * We call it with interrupts disabled.
2358 * It also gets called by the fork code, when changing the parent's
2361 void scheduler_tick(int user_ticks, int sys_ticks)
2363 int cpu = smp_processor_id();
2364 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2365 runqueue_t *rq = this_rq();
2366 task_t *p = current;
2368 rq->timestamp_last_tick = sched_clock();
2370 if (rcu_pending(cpu))
2371 rcu_check_callbacks(cpu, user_ticks);
2373 /* note: this timer irq context must be accounted for as well */
2374 if (hardirq_count() - HARDIRQ_OFFSET) {
2375 cpustat->irq += sys_ticks;
2377 } else if (softirq_count()) {
2378 cpustat->softirq += sys_ticks;
2382 if (p == rq->idle) {
2383 if (!--rq->idle_tokens && !list_empty(&rq->hold_queue))
2386 if (atomic_read(&rq->nr_iowait) > 0)
2387 cpustat->iowait += sys_ticks;
2389 cpustat->idle += sys_ticks;
2390 if (wake_priority_sleeper(rq))
2392 rebalance_tick(cpu, rq, IDLE);
2395 if (TASK_NICE(p) > 0)
2396 cpustat->nice += user_ticks;
2398 cpustat->user += user_ticks;
2399 cpustat->system += sys_ticks;
2401 /* Task might have expired already, but not scheduled off yet */
2402 if (p->array != rq_active(p,rq)) {
2403 set_tsk_need_resched(p);
2406 spin_lock(&rq->lock);
2408 * The task was running during this tick - update the
2409 * time slice counter. Note: we do not update a thread's
2410 * priority until it either goes to sleep or uses up its
2411 * timeslice. This makes it possible for interactive tasks
2412 * to use up their timeslices at their highest priority levels.
2414 if (unlikely(rt_task(p))) {
2416 * RR tasks need a special form of timeslice management.
2417 * FIFO tasks have no timeslices.
2419 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2420 p->time_slice = task_timeslice(p);
2421 p->first_time_slice = 0;
2422 set_tsk_need_resched(p);
2424 /* put it at the end of the queue: */
2425 dequeue_task(p, rq_active(p,rq));
2426 enqueue_task(p, rq_active(p,rq));
2430 #warning MEF PLANETLAB: "if (vx_need_resched(p)) was if (!--p->time_slice) */"
2431 if (vx_need_resched(p)) {
2432 #ifdef CONFIG_CKRM_CPU_SCHEDULE
2433 /* Hubertus ... we can abstract this out */
2434 struct ckrm_local_runqueue* rq = get_task_class_queue(p);
2436 dequeue_task(p, rq->active);
2437 set_tsk_need_resched(p);
2438 p->prio = effective_prio(p);
2439 p->time_slice = task_timeslice(p);
2440 p->first_time_slice = 0;
2442 if (!rq->expired_timestamp)
2443 rq->expired_timestamp = jiffies;
2444 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2445 enqueue_task(p, rq->expired);
2446 if (p->static_prio < this_rq()->best_expired_prio)
2447 this_rq()->best_expired_prio = p->static_prio;
2449 enqueue_task(p, rq->active);
2452 * Prevent a too long timeslice allowing a task to monopolize
2453 * the CPU. We do this by splitting up the timeslice into
2456 * Note: this does not mean the task's timeslices expire or
2457 * get lost in any way, they just might be preempted by
2458 * another task of equal priority. (one with higher
2459 * priority would have preempted this task already.) We
2460 * requeue this task to the end of the list on this priority
2461 * level, which is in essence a round-robin of tasks with
2464 * This only applies to tasks in the interactive
2465 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2467 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2468 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2469 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2470 (p->array == rq_active(p,rq))) {
2472 dequeue_task(p, rq_active(p,rq));
2473 set_tsk_need_resched(p);
2474 p->prio = effective_prio(p);
2475 enqueue_task(p, rq_active(p,rq));
2479 spin_unlock(&rq->lock);
2481 rebalance_tick(cpu, rq, NOT_IDLE);
2484 #ifdef CONFIG_SCHED_SMT
2485 static inline void wake_sleeping_dependent(int cpu, runqueue_t *rq)
2488 struct sched_domain *sd = rq->sd;
2489 cpumask_t sibling_map;
2491 if (!(sd->flags & SD_SHARE_CPUPOWER))
2494 cpus_and(sibling_map, sd->span, cpu_online_map);
2495 for_each_cpu_mask(i, sibling_map) {
2504 * If an SMT sibling task is sleeping due to priority
2505 * reasons wake it up now.
2507 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
2508 resched_task(smt_rq->idle);
2512 static inline int dependent_sleeper(int cpu, runqueue_t *rq, task_t *p)
2514 struct sched_domain *sd = rq->sd;
2515 cpumask_t sibling_map;
2518 if (!(sd->flags & SD_SHARE_CPUPOWER))
2521 cpus_and(sibling_map, sd->span, cpu_online_map);
2522 for_each_cpu_mask(i, sibling_map) {
2530 smt_curr = smt_rq->curr;
2533 * If a user task with lower static priority than the
2534 * running task on the SMT sibling is trying to schedule,
2535 * delay it till there is proportionately less timeslice
2536 * left of the sibling task to prevent a lower priority
2537 * task from using an unfair proportion of the
2538 * physical cpu's resources. -ck
2540 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
2541 task_timeslice(p) || rt_task(smt_curr)) &&
2542 p->mm && smt_curr->mm && !rt_task(p))
2546 * Reschedule a lower priority task on the SMT sibling,
2547 * or wake it up if it has been put to sleep for priority
2550 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
2551 task_timeslice(smt_curr) || rt_task(p)) &&
2552 smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
2553 (smt_curr == smt_rq->idle && smt_rq->nr_running))
2554 resched_task(smt_curr);
2559 static inline void wake_sleeping_dependent(int cpu, runqueue_t *rq)
2563 static inline int dependent_sleeper(int cpu, runqueue_t *rq, task_t *p)
2570 * schedule() is the main scheduler function.
2572 asmlinkage void __sched schedule(void)
2575 task_t *prev, *next;
2577 prio_array_t *array;
2578 unsigned long long now;
2579 unsigned long run_time;
2581 #ifdef CONFIG_VSERVER_HARDCPU
2582 struct vx_info *vxi;
2587 * Test if we are atomic. Since do_exit() needs to call into
2588 * schedule() atomically, we ignore that path for now.
2589 * Otherwise, whine if we are scheduling when we should not be.
2591 if (likely(!(current->state & (TASK_DEAD | TASK_ZOMBIE)))) {
2592 if (unlikely(in_atomic())) {
2593 printk(KERN_ERR "bad: scheduling while atomic!\n");
2603 release_kernel_lock(prev);
2604 now = sched_clock();
2605 if (likely(now - prev->timestamp < NS_MAX_SLEEP_AVG))
2606 run_time = now - prev->timestamp;
2608 run_time = NS_MAX_SLEEP_AVG;
2611 * Tasks with interactive credits get charged less run_time
2612 * at high sleep_avg to delay them losing their interactive
2615 if (HIGH_CREDIT(prev))
2616 run_time /= (CURRENT_BONUS(prev) ? : 1);
2618 spin_lock_irq(&rq->lock);
2621 * if entering off of a kernel preemption go straight
2622 * to picking the next task.
2624 switch_count = &prev->nivcsw;
2625 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2626 switch_count = &prev->nvcsw;
2627 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2628 unlikely(signal_pending(prev))))
2629 prev->state = TASK_RUNNING;
2631 deactivate_task(prev, rq);
2634 cpu = smp_processor_id();
2635 #ifdef CONFIG_VSERVER_HARDCPU
2636 if (!list_empty(&rq->hold_queue)) {
2637 struct list_head *l, *n;
2641 list_for_each_safe(l, n, &rq->hold_queue) {
2642 next = list_entry(l, task_t, run_list);
2643 if (vxi == next->vx_info)
2646 vxi = next->vx_info;
2647 ret = vx_tokens_recalc(vxi);
2648 // tokens = vx_tokens_avail(next);
2651 list_del(&next->run_list);
2652 next->state &= ~TASK_ONHOLD;
2653 recalc_task_prio(next, now);
2654 __activate_task(next, rq);
2655 // printk("··· unhold %p\n", next);
2658 if ((ret < 0) && (maxidle < ret))
2662 rq->idle_tokens = -maxidle;
2666 if (unlikely(!rq->nr_running)) {
2667 idle_balance(cpu, rq);
2668 if (!rq->nr_running) {
2670 rq->expired_timestamp = 0;
2671 wake_sleeping_dependent(cpu, rq);
2676 next = rq_get_next_task(rq);
2677 if (next == rq->idle)
2680 if (dependent_sleeper(cpu, rq, next)) {
2685 #ifdef CONFIG_VSERVER_HARDCPU
2686 vxi = next->vx_info;
2687 if (vxi && __vx_flags(vxi->vx_flags,
2688 VXF_SCHED_PAUSE|VXF_SCHED_HARD, 0)) {
2689 int ret = vx_tokens_recalc(vxi);
2691 if (unlikely(ret <= 0)) {
2692 if (ret && (rq->idle_tokens > -ret))
2693 rq->idle_tokens = -ret;
2694 deactivate_task(next, rq);
2695 list_add_tail(&next->run_list, &rq->hold_queue);
2696 next->state |= TASK_ONHOLD;
2702 if (!rt_task(next) && next->activated > 0) {
2703 unsigned long long delta = now - next->timestamp;
2705 if (next->activated == 1)
2706 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
2708 array = next->array;
2709 dequeue_task(next, array);
2710 recalc_task_prio(next, next->timestamp + delta);
2711 enqueue_task(next, array);
2713 next->activated = 0;
2716 clear_tsk_need_resched(prev);
2717 RCU_qsctr(task_cpu(prev))++;
2719 #ifdef CONFIG_CKRM_CPU_SCHEDULE
2720 if (prev != rq->idle) {
2721 unsigned long long run = now - prev->timestamp;
2722 cpu_demand_event(get_task_local_stat(prev),CPU_DEMAND_DESCHEDULE,run);
2723 update_local_cvt(prev, run);
2727 prev->sleep_avg -= run_time;
2728 if ((long)prev->sleep_avg <= 0) {
2729 prev->sleep_avg = 0;
2730 if (!(HIGH_CREDIT(prev) || LOW_CREDIT(prev)))
2731 prev->interactive_credit--;
2733 add_delay_ts(prev,runcpu_total,prev->timestamp,now);
2734 prev->timestamp = now;
2736 if (likely(prev != next)) {
2737 add_delay_ts(next,waitcpu_total,next->timestamp,now);
2738 inc_delay(next,runs);
2739 next->timestamp = now;
2744 prepare_arch_switch(rq, next);
2745 prev = context_switch(rq, prev, next);
2748 finish_task_switch(prev);
2750 spin_unlock_irq(&rq->lock);
2752 reacquire_kernel_lock(current);
2753 preempt_enable_no_resched();
2754 if (test_thread_flag(TIF_NEED_RESCHED))
2758 EXPORT_SYMBOL(schedule);
2760 #ifdef CONFIG_PREEMPT
2762 * this is is the entry point to schedule() from in-kernel preemption
2763 * off of preempt_enable. Kernel preemptions off return from interrupt
2764 * occur there and call schedule directly.
2766 asmlinkage void __sched preempt_schedule(void)
2768 struct thread_info *ti = current_thread_info();
2771 * If there is a non-zero preempt_count or interrupts are disabled,
2772 * we do not want to preempt the current task. Just return..
2774 if (unlikely(ti->preempt_count || irqs_disabled()))
2778 ti->preempt_count = PREEMPT_ACTIVE;
2780 ti->preempt_count = 0;
2782 /* we could miss a preemption opportunity between schedule and now */
2784 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2788 EXPORT_SYMBOL(preempt_schedule);
2789 #endif /* CONFIG_PREEMPT */
2791 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
2793 task_t *p = curr->task;
2794 return try_to_wake_up(p, mode, sync);
2797 EXPORT_SYMBOL(default_wake_function);
2800 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
2801 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
2802 * number) then we wake all the non-exclusive tasks and one exclusive task.
2804 * There are circumstances in which we can try to wake a task which has already
2805 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
2806 * zero in this (rare) case, and we handle it by continuing to scan the queue.
2808 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
2809 int nr_exclusive, int sync, void *key)
2811 struct list_head *tmp, *next;
2813 list_for_each_safe(tmp, next, &q->task_list) {
2816 curr = list_entry(tmp, wait_queue_t, task_list);
2817 flags = curr->flags;
2818 if (curr->func(curr, mode, sync, key) &&
2819 (flags & WQ_FLAG_EXCLUSIVE) &&
2826 * __wake_up - wake up threads blocked on a waitqueue.
2828 * @mode: which threads
2829 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2831 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
2832 int nr_exclusive, void *key)
2834 unsigned long flags;
2836 spin_lock_irqsave(&q->lock, flags);
2837 __wake_up_common(q, mode, nr_exclusive, 0, key);
2838 spin_unlock_irqrestore(&q->lock, flags);
2841 EXPORT_SYMBOL(__wake_up);
2844 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
2846 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
2848 __wake_up_common(q, mode, 1, 0, NULL);
2852 * __wake_up - sync- wake up threads blocked on a waitqueue.
2854 * @mode: which threads
2855 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2857 * The sync wakeup differs that the waker knows that it will schedule
2858 * away soon, so while the target thread will be woken up, it will not
2859 * be migrated to another CPU - ie. the two threads are 'synchronized'
2860 * with each other. This can prevent needless bouncing between CPUs.
2862 * On UP it can prevent extra preemption.
2864 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
2866 unsigned long flags;
2872 if (unlikely(!nr_exclusive))
2875 spin_lock_irqsave(&q->lock, flags);
2876 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
2877 spin_unlock_irqrestore(&q->lock, flags);
2879 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
2881 void fastcall complete(struct completion *x)
2883 unsigned long flags;
2885 spin_lock_irqsave(&x->wait.lock, flags);
2887 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2889 spin_unlock_irqrestore(&x->wait.lock, flags);
2891 EXPORT_SYMBOL(complete);
2893 void fastcall complete_all(struct completion *x)
2895 unsigned long flags;
2897 spin_lock_irqsave(&x->wait.lock, flags);
2898 x->done += UINT_MAX/2;
2899 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2901 spin_unlock_irqrestore(&x->wait.lock, flags);
2903 EXPORT_SYMBOL(complete_all);
2905 void fastcall __sched wait_for_completion(struct completion *x)
2908 spin_lock_irq(&x->wait.lock);
2910 DECLARE_WAITQUEUE(wait, current);
2912 wait.flags |= WQ_FLAG_EXCLUSIVE;
2913 __add_wait_queue_tail(&x->wait, &wait);
2915 __set_current_state(TASK_UNINTERRUPTIBLE);
2916 spin_unlock_irq(&x->wait.lock);
2918 spin_lock_irq(&x->wait.lock);
2920 __remove_wait_queue(&x->wait, &wait);
2923 spin_unlock_irq(&x->wait.lock);
2925 EXPORT_SYMBOL(wait_for_completion);
2927 #define SLEEP_ON_VAR \
2928 unsigned long flags; \
2929 wait_queue_t wait; \
2930 init_waitqueue_entry(&wait, current);
2932 #define SLEEP_ON_HEAD \
2933 spin_lock_irqsave(&q->lock,flags); \
2934 __add_wait_queue(q, &wait); \
2935 spin_unlock(&q->lock);
2937 #define SLEEP_ON_TAIL \
2938 spin_lock_irq(&q->lock); \
2939 __remove_wait_queue(q, &wait); \
2940 spin_unlock_irqrestore(&q->lock, flags);
2942 #define SLEEP_ON_BKLCHECK \
2943 if (unlikely(!kernel_locked()) && \
2944 sleep_on_bkl_warnings < 10) { \
2945 sleep_on_bkl_warnings++; \
2949 static int sleep_on_bkl_warnings;
2951 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
2957 current->state = TASK_INTERRUPTIBLE;
2964 EXPORT_SYMBOL(interruptible_sleep_on);
2966 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
2972 current->state = TASK_INTERRUPTIBLE;
2975 timeout = schedule_timeout(timeout);
2981 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
2983 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
2989 current->state = TASK_UNINTERRUPTIBLE;
2992 timeout = schedule_timeout(timeout);
2998 EXPORT_SYMBOL(sleep_on_timeout);
3000 void set_user_nice(task_t *p, long nice)
3002 unsigned long flags;
3003 prio_array_t *array;
3005 int old_prio, new_prio, delta;
3007 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3010 * We have to be careful, if called from sys_setpriority(),
3011 * the task might be in the middle of scheduling on another CPU.
3013 rq = task_rq_lock(p, &flags);
3015 * The RT priorities are set via setscheduler(), but we still
3016 * allow the 'normal' nice value to be set - but as expected
3017 * it wont have any effect on scheduling until the task is
3021 p->static_prio = NICE_TO_PRIO(nice);
3026 dequeue_task(p, array);
3029 new_prio = NICE_TO_PRIO(nice);
3030 delta = new_prio - old_prio;
3031 p->static_prio = NICE_TO_PRIO(nice);
3035 enqueue_task(p, array);
3037 * If the task increased its priority or is running and
3038 * lowered its priority, then reschedule its CPU:
3040 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3041 resched_task(rq->curr);
3044 task_rq_unlock(rq, &flags);
3047 EXPORT_SYMBOL(set_user_nice);
3049 #ifdef __ARCH_WANT_SYS_NICE
3052 * sys_nice - change the priority of the current process.
3053 * @increment: priority increment
3055 * sys_setpriority is a more generic, but much slower function that
3056 * does similar things.
3058 asmlinkage long sys_nice(int increment)
3064 * Setpriority might change our priority at the same moment.
3065 * We don't have to worry. Conceptually one call occurs first
3066 * and we have a single winner.
3068 if (increment < 0) {
3069 if (!capable(CAP_SYS_NICE))
3071 if (increment < -40)
3077 nice = PRIO_TO_NICE(current->static_prio) + increment;
3083 retval = security_task_setnice(current, nice);
3087 set_user_nice(current, nice);
3094 * task_prio - return the priority value of a given task.
3095 * @p: the task in question.
3097 * This is the priority value as seen by users in /proc.
3098 * RT tasks are offset by -200. Normal tasks are centered
3099 * around 0, value goes from -16 to +15.
3101 int task_prio(const task_t *p)
3103 return p->prio - MAX_RT_PRIO;
3107 * task_nice - return the nice value of a given task.
3108 * @p: the task in question.
3110 int task_nice(const task_t *p)
3112 return TASK_NICE(p);
3115 EXPORT_SYMBOL(task_nice);
3118 * idle_cpu - is a given cpu idle currently?
3119 * @cpu: the processor in question.
3121 int idle_cpu(int cpu)
3123 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3126 EXPORT_SYMBOL_GPL(idle_cpu);
3129 * find_process_by_pid - find a process with a matching PID value.
3130 * @pid: the pid in question.
3132 static inline task_t *find_process_by_pid(pid_t pid)
3134 return pid ? find_task_by_pid(pid) : current;
3137 /* Actually do priority change: must hold rq lock. */
3138 static void __setscheduler(struct task_struct *p, int policy, int prio)
3142 p->rt_priority = prio;
3143 if (policy != SCHED_NORMAL)
3144 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
3146 p->prio = p->static_prio;
3150 * setscheduler - change the scheduling policy and/or RT priority of a thread.
3152 static int setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3154 struct sched_param lp;
3155 int retval = -EINVAL;
3157 prio_array_t *array;
3158 unsigned long flags;
3162 if (!param || pid < 0)
3166 if (copy_from_user(&lp, param, sizeof(struct sched_param)))
3170 * We play safe to avoid deadlocks.
3172 read_lock_irq(&tasklist_lock);
3174 p = find_process_by_pid(pid);
3178 goto out_unlock_tasklist;
3181 * To be able to change p->policy safely, the apropriate
3182 * runqueue lock must be held.
3184 rq = task_rq_lock(p, &flags);
3190 if (policy != SCHED_FIFO && policy != SCHED_RR &&
3191 policy != SCHED_NORMAL)
3196 * Valid priorities for SCHED_FIFO and SCHED_RR are
3197 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
3200 if (lp.sched_priority < 0 || lp.sched_priority > MAX_USER_RT_PRIO-1)
3202 if ((policy == SCHED_NORMAL) != (lp.sched_priority == 0))
3206 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
3207 !capable(CAP_SYS_NICE))
3209 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3210 !capable(CAP_SYS_NICE))
3213 retval = security_task_setscheduler(p, policy, &lp);
3219 deactivate_task(p, task_rq(p));
3222 __setscheduler(p, policy, lp.sched_priority);
3224 __activate_task(p, task_rq(p));
3226 * Reschedule if we are currently running on this runqueue and
3227 * our priority decreased, or if we are not currently running on
3228 * this runqueue and our priority is higher than the current's
3230 if (task_running(rq, p)) {
3231 if (p->prio > oldprio)
3232 resched_task(rq->curr);
3233 } else if (TASK_PREEMPTS_CURR(p, rq))
3234 resched_task(rq->curr);
3238 task_rq_unlock(rq, &flags);
3239 out_unlock_tasklist:
3240 read_unlock_irq(&tasklist_lock);
3247 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3248 * @pid: the pid in question.
3249 * @policy: new policy
3250 * @param: structure containing the new RT priority.
3252 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3253 struct sched_param __user *param)
3255 return setscheduler(pid, policy, param);
3259 * sys_sched_setparam - set/change the RT priority of a thread
3260 * @pid: the pid in question.
3261 * @param: structure containing the new RT priority.
3263 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3265 return setscheduler(pid, -1, param);
3269 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3270 * @pid: the pid in question.
3272 asmlinkage long sys_sched_getscheduler(pid_t pid)
3274 int retval = -EINVAL;
3281 read_lock(&tasklist_lock);
3282 p = find_process_by_pid(pid);
3284 retval = security_task_getscheduler(p);
3288 read_unlock(&tasklist_lock);
3295 * sys_sched_getscheduler - get the RT priority of a thread
3296 * @pid: the pid in question.
3297 * @param: structure containing the RT priority.
3299 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3301 struct sched_param lp;
3302 int retval = -EINVAL;
3305 if (!param || pid < 0)
3308 read_lock(&tasklist_lock);
3309 p = find_process_by_pid(pid);
3314 retval = security_task_getscheduler(p);
3318 lp.sched_priority = p->rt_priority;
3319 read_unlock(&tasklist_lock);
3322 * This one might sleep, we cannot do it with a spinlock held ...
3324 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3330 read_unlock(&tasklist_lock);
3335 * sys_sched_setaffinity - set the cpu affinity of a process
3336 * @pid: pid of the process
3337 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3338 * @user_mask_ptr: user-space pointer to the new cpu mask
3340 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
3341 unsigned long __user *user_mask_ptr)
3347 if (len < sizeof(new_mask))
3350 if (copy_from_user(&new_mask, user_mask_ptr, sizeof(new_mask)))
3354 read_lock(&tasklist_lock);
3356 p = find_process_by_pid(pid);
3358 read_unlock(&tasklist_lock);
3359 unlock_cpu_hotplug();
3364 * It is not safe to call set_cpus_allowed with the
3365 * tasklist_lock held. We will bump the task_struct's
3366 * usage count and then drop tasklist_lock.
3369 read_unlock(&tasklist_lock);
3372 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3373 !capable(CAP_SYS_NICE))
3376 retval = set_cpus_allowed(p, new_mask);
3380 unlock_cpu_hotplug();
3385 * sys_sched_getaffinity - get the cpu affinity of a process
3386 * @pid: pid of the process
3387 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3388 * @user_mask_ptr: user-space pointer to hold the current cpu mask
3390 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
3391 unsigned long __user *user_mask_ptr)
3393 unsigned int real_len;
3398 real_len = sizeof(mask);
3403 read_lock(&tasklist_lock);
3406 p = find_process_by_pid(pid);
3411 cpus_and(mask, p->cpus_allowed, cpu_possible_map);
3414 read_unlock(&tasklist_lock);
3415 unlock_cpu_hotplug();
3418 if (copy_to_user(user_mask_ptr, &mask, real_len))
3424 * sys_sched_yield - yield the current processor to other threads.
3426 * this function yields the current CPU by moving the calling thread
3427 * to the expired array. If there are no other threads running on this
3428 * CPU then this function will return.
3430 asmlinkage long sys_sched_yield(void)
3432 runqueue_t *rq = this_rq_lock();
3433 prio_array_t *array = current->array;
3434 prio_array_t *target = rq_expired(current,rq);
3437 * We implement yielding by moving the task into the expired
3440 * (special rule: RT tasks will just roundrobin in the active
3443 if (unlikely(rt_task(current)))
3444 target = rq_active(current,rq);
3446 dequeue_task(current, array);
3447 enqueue_task(current, target);
3450 * Since we are going to call schedule() anyway, there's
3451 * no need to preempt or enable interrupts:
3453 _raw_spin_unlock(&rq->lock);
3454 preempt_enable_no_resched();
3461 void __sched __cond_resched(void)
3463 set_current_state(TASK_RUNNING);
3467 EXPORT_SYMBOL(__cond_resched);
3470 * yield - yield the current processor to other threads.
3472 * this is a shortcut for kernel-space yielding - it marks the
3473 * thread runnable and calls sys_sched_yield().
3475 void __sched yield(void)
3477 set_current_state(TASK_RUNNING);
3481 EXPORT_SYMBOL(yield);
3484 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
3485 * that process accounting knows that this is a task in IO wait state.
3487 * But don't do that if it is a deliberate, throttling IO wait (this task
3488 * has set its backing_dev_info: the queue against which it should throttle)
3490 void __sched io_schedule(void)
3492 struct runqueue *rq = this_rq();
3493 def_delay_var(dstart);
3495 start_delay_set(dstart,PF_IOWAIT);
3496 atomic_inc(&rq->nr_iowait);
3498 atomic_dec(&rq->nr_iowait);
3499 add_io_delay(dstart);
3502 EXPORT_SYMBOL(io_schedule);
3504 long __sched io_schedule_timeout(long timeout)
3506 struct runqueue *rq = this_rq();
3508 def_delay_var(dstart);
3510 start_delay_set(dstart,PF_IOWAIT);
3511 atomic_inc(&rq->nr_iowait);
3512 ret = schedule_timeout(timeout);
3513 atomic_dec(&rq->nr_iowait);
3514 add_io_delay(dstart);
3519 * sys_sched_get_priority_max - return maximum RT priority.
3520 * @policy: scheduling class.
3522 * this syscall returns the maximum rt_priority that can be used
3523 * by a given scheduling class.
3525 asmlinkage long sys_sched_get_priority_max(int policy)
3532 ret = MAX_USER_RT_PRIO-1;
3542 * sys_sched_get_priority_min - return minimum RT priority.
3543 * @policy: scheduling class.
3545 * this syscall returns the minimum rt_priority that can be used
3546 * by a given scheduling class.
3548 asmlinkage long sys_sched_get_priority_min(int policy)
3564 * sys_sched_rr_get_interval - return the default timeslice of a process.
3565 * @pid: pid of the process.
3566 * @interval: userspace pointer to the timeslice value.
3568 * this syscall writes the default timeslice value of a given process
3569 * into the user-space timespec buffer. A value of '0' means infinity.
3572 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
3574 int retval = -EINVAL;
3582 read_lock(&tasklist_lock);
3583 p = find_process_by_pid(pid);
3587 retval = security_task_getscheduler(p);
3591 jiffies_to_timespec(p->policy & SCHED_FIFO ?
3592 0 : task_timeslice(p), &t);
3593 read_unlock(&tasklist_lock);
3594 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
3598 read_unlock(&tasklist_lock);
3602 static inline struct task_struct *eldest_child(struct task_struct *p)
3604 if (list_empty(&p->children)) return NULL;
3605 return list_entry(p->children.next,struct task_struct,sibling);
3608 static inline struct task_struct *older_sibling(struct task_struct *p)
3610 if (p->sibling.prev==&p->parent->children) return NULL;
3611 return list_entry(p->sibling.prev,struct task_struct,sibling);
3614 static inline struct task_struct *younger_sibling(struct task_struct *p)
3616 if (p->sibling.next==&p->parent->children) return NULL;
3617 return list_entry(p->sibling.next,struct task_struct,sibling);
3620 static void show_task(task_t * p)
3624 unsigned long free = 0;
3625 static const char *stat_nam[] = { "R", "S", "D", "T", "Z", "W" };
3627 printk("%-13.13s ", p->comm);
3628 state = p->state ? __ffs(p->state) + 1 : 0;
3629 if (state < ARRAY_SIZE(stat_nam))
3630 printk(stat_nam[state]);
3633 #if (BITS_PER_LONG == 32)
3634 if (state == TASK_RUNNING)
3635 printk(" running ");
3637 printk(" %08lX ", thread_saved_pc(p));
3639 if (state == TASK_RUNNING)
3640 printk(" running task ");
3642 printk(" %016lx ", thread_saved_pc(p));
3644 #ifdef CONFIG_DEBUG_STACK_USAGE
3646 unsigned long * n = (unsigned long *) (p->thread_info+1);
3649 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
3652 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
3653 if ((relative = eldest_child(p)))
3654 printk("%5d ", relative->pid);
3657 if ((relative = younger_sibling(p)))
3658 printk("%7d", relative->pid);
3661 if ((relative = older_sibling(p)))
3662 printk(" %5d", relative->pid);
3666 printk(" (L-TLB)\n");
3668 printk(" (NOTLB)\n");
3670 if (state != TASK_RUNNING)
3671 show_stack(p, NULL);
3674 void show_state(void)
3678 #if (BITS_PER_LONG == 32)
3681 printk(" task PC pid father child younger older\n");
3685 printk(" task PC pid father child younger older\n");
3687 read_lock(&tasklist_lock);
3688 do_each_thread(g, p) {
3690 * reset the NMI-timeout, listing all files on a slow
3691 * console might take alot of time:
3693 touch_nmi_watchdog();
3695 } while_each_thread(g, p);
3697 read_unlock(&tasklist_lock);
3700 void __devinit init_idle(task_t *idle, int cpu)
3702 runqueue_t *idle_rq = cpu_rq(cpu), *rq = cpu_rq(task_cpu(idle));
3703 unsigned long flags;
3705 local_irq_save(flags);
3706 double_rq_lock(idle_rq, rq);
3708 idle_rq->curr = idle_rq->idle = idle;
3709 deactivate_task(idle, rq);
3711 idle->prio = MAX_PRIO;
3712 idle->state = TASK_RUNNING;
3713 set_task_cpu(idle, cpu);
3714 double_rq_unlock(idle_rq, rq);
3715 set_tsk_need_resched(idle);
3716 local_irq_restore(flags);
3718 /* Set the preempt count _outside_ the spinlocks! */
3719 #ifdef CONFIG_PREEMPT
3720 idle->thread_info->preempt_count = (idle->lock_depth >= 0);
3722 idle->thread_info->preempt_count = 0;
3727 * In a system that switches off the HZ timer nohz_cpu_mask
3728 * indicates which cpus entered this state. This is used
3729 * in the rcu update to wait only for active cpus. For system
3730 * which do not switch off the HZ timer nohz_cpu_mask should
3731 * always be CPU_MASK_NONE.
3733 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
3737 * This is how migration works:
3739 * 1) we queue a migration_req_t structure in the source CPU's
3740 * runqueue and wake up that CPU's migration thread.
3741 * 2) we down() the locked semaphore => thread blocks.
3742 * 3) migration thread wakes up (implicitly it forces the migrated
3743 * thread off the CPU)
3744 * 4) it gets the migration request and checks whether the migrated
3745 * task is still in the wrong runqueue.
3746 * 5) if it's in the wrong runqueue then the migration thread removes
3747 * it and puts it into the right queue.
3748 * 6) migration thread up()s the semaphore.
3749 * 7) we wake up and the migration is done.
3753 * Change a given task's CPU affinity. Migrate the thread to a
3754 * proper CPU and schedule it away if the CPU it's executing on
3755 * is removed from the allowed bitmask.
3757 * NOTE: the caller must have a valid reference to the task, the
3758 * task must not exit() & deallocate itself prematurely. The
3759 * call is not atomic; no spinlocks may be held.
3761 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
3763 unsigned long flags;
3765 migration_req_t req;
3768 rq = task_rq_lock(p, &flags);
3769 if (any_online_cpu(new_mask) == NR_CPUS) {
3774 p->cpus_allowed = new_mask;
3775 /* Can the task run on the task's current CPU? If so, we're done */
3776 if (cpu_isset(task_cpu(p), new_mask))
3779 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
3780 /* Need help from migration thread: drop lock and wait. */
3781 task_rq_unlock(rq, &flags);
3782 wake_up_process(rq->migration_thread);
3783 wait_for_completion(&req.done);
3787 task_rq_unlock(rq, &flags);
3791 EXPORT_SYMBOL_GPL(set_cpus_allowed);
3794 * Move (not current) task off this cpu, onto dest cpu. We're doing
3795 * this because either it can't run here any more (set_cpus_allowed()
3796 * away from this CPU, or CPU going down), or because we're
3797 * attempting to rebalance this task on exec (sched_balance_exec).
3799 * So we race with normal scheduler movements, but that's OK, as long
3800 * as the task is no longer on this CPU.
3802 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
3804 runqueue_t *rq_dest, *rq_src;
3806 if (unlikely(cpu_is_offline(dest_cpu)))
3809 rq_src = cpu_rq(src_cpu);
3810 rq_dest = cpu_rq(dest_cpu);
3812 double_rq_lock(rq_src, rq_dest);
3813 /* Already moved. */
3814 if (task_cpu(p) != src_cpu)
3816 /* Affinity changed (again). */
3817 if (!cpu_isset(dest_cpu, p->cpus_allowed))
3820 set_task_cpu(p, dest_cpu);
3823 * Sync timestamp with rq_dest's before activating.
3824 * The same thing could be achieved by doing this step
3825 * afterwards, and pretending it was a local activate.
3826 * This way is cleaner and logically correct.
3828 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
3829 + rq_dest->timestamp_last_tick;
3830 deactivate_task(p, rq_src);
3831 activate_task(p, rq_dest, 0);
3832 if (TASK_PREEMPTS_CURR(p, rq_dest))
3833 resched_task(rq_dest->curr);
3837 double_rq_unlock(rq_src, rq_dest);
3841 * migration_thread - this is a highprio system thread that performs
3842 * thread migration by bumping thread off CPU then 'pushing' onto
3845 static int migration_thread(void * data)
3848 int cpu = (long)data;
3851 BUG_ON(rq->migration_thread != current);
3853 set_current_state(TASK_INTERRUPTIBLE);
3854 while (!kthread_should_stop()) {
3855 struct list_head *head;
3856 migration_req_t *req;
3858 if (current->flags & PF_FREEZE)
3859 refrigerator(PF_FREEZE);
3861 spin_lock_irq(&rq->lock);
3863 if (cpu_is_offline(cpu)) {
3864 spin_unlock_irq(&rq->lock);
3868 if (rq->active_balance) {
3869 #ifndef CONFIG_CKRM_CPU_SCHEDULE
3870 active_load_balance(rq, cpu);
3872 rq->active_balance = 0;
3875 head = &rq->migration_queue;
3877 if (list_empty(head)) {
3878 spin_unlock_irq(&rq->lock);
3880 set_current_state(TASK_INTERRUPTIBLE);
3883 req = list_entry(head->next, migration_req_t, list);
3884 list_del_init(head->next);
3886 if (req->type == REQ_MOVE_TASK) {
3887 spin_unlock(&rq->lock);
3888 __migrate_task(req->task, smp_processor_id(),
3891 } else if (req->type == REQ_SET_DOMAIN) {
3893 spin_unlock_irq(&rq->lock);
3895 spin_unlock_irq(&rq->lock);
3899 complete(&req->done);
3901 __set_current_state(TASK_RUNNING);
3905 /* Wait for kthread_stop */
3906 set_current_state(TASK_INTERRUPTIBLE);
3907 while (!kthread_should_stop()) {
3909 set_current_state(TASK_INTERRUPTIBLE);
3911 __set_current_state(TASK_RUNNING);
3915 #ifdef CONFIG_HOTPLUG_CPU
3916 /* migrate_all_tasks - function to migrate all tasks from the dead cpu. */
3917 static void migrate_all_tasks(int src_cpu)
3919 struct task_struct *tsk, *t;
3923 write_lock_irq(&tasklist_lock);
3925 /* watch out for per node tasks, let's stay on this node */
3926 node = cpu_to_node(src_cpu);
3928 do_each_thread(t, tsk) {
3933 if (task_cpu(tsk) != src_cpu)
3936 /* Figure out where this task should go (attempting to
3937 * keep it on-node), and check if it can be migrated
3938 * as-is. NOTE that kernel threads bound to more than
3939 * one online cpu will be migrated. */
3940 mask = node_to_cpumask(node);
3941 cpus_and(mask, mask, tsk->cpus_allowed);
3942 dest_cpu = any_online_cpu(mask);
3943 if (dest_cpu == NR_CPUS)
3944 dest_cpu = any_online_cpu(tsk->cpus_allowed);
3945 if (dest_cpu == NR_CPUS) {
3946 cpus_clear(tsk->cpus_allowed);
3947 cpus_complement(tsk->cpus_allowed);
3948 dest_cpu = any_online_cpu(tsk->cpus_allowed);
3950 /* Don't tell them about moving exiting tasks
3951 or kernel threads (both mm NULL), since
3952 they never leave kernel. */
3953 if (tsk->mm && printk_ratelimit())
3954 printk(KERN_INFO "process %d (%s) no "
3955 "longer affine to cpu%d\n",
3956 tsk->pid, tsk->comm, src_cpu);
3959 __migrate_task(tsk, src_cpu, dest_cpu);
3960 } while_each_thread(t, tsk);
3962 write_unlock_irq(&tasklist_lock);
3965 /* Schedules idle task to be the next runnable task on current CPU.
3966 * It does so by boosting its priority to highest possible and adding it to
3967 * the _front_ of runqueue. Used by CPU offline code.
3969 void sched_idle_next(void)
3971 int cpu = smp_processor_id();
3972 runqueue_t *rq = this_rq();
3973 struct task_struct *p = rq->idle;
3974 unsigned long flags;
3976 /* cpu has to be offline */
3977 BUG_ON(cpu_online(cpu));
3979 /* Strictly not necessary since rest of the CPUs are stopped by now
3980 * and interrupts disabled on current cpu.
3982 spin_lock_irqsave(&rq->lock, flags);
3984 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
3985 /* Add idle task to _front_ of it's priority queue */
3986 __activate_idle_task(p, rq);
3988 spin_unlock_irqrestore(&rq->lock, flags);
3990 #endif /* CONFIG_HOTPLUG_CPU */
3993 * migration_call - callback that gets triggered when a CPU is added.
3994 * Here we can start up the necessary migration thread for the new CPU.
3996 static int migration_call(struct notifier_block *nfb, unsigned long action,
3999 int cpu = (long)hcpu;
4000 struct task_struct *p;
4001 struct runqueue *rq;
4002 unsigned long flags;
4005 case CPU_UP_PREPARE:
4006 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4009 kthread_bind(p, cpu);
4010 /* Must be high prio: stop_machine expects to yield to it. */
4011 rq = task_rq_lock(p, &flags);
4012 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4013 task_rq_unlock(rq, &flags);
4014 cpu_rq(cpu)->migration_thread = p;
4017 /* Strictly unneccessary, as first user will wake it. */
4018 wake_up_process(cpu_rq(cpu)->migration_thread);
4020 #ifdef CONFIG_HOTPLUG_CPU
4021 case CPU_UP_CANCELED:
4022 /* Unbind it from offline cpu so it can run. Fall thru. */
4023 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
4024 kthread_stop(cpu_rq(cpu)->migration_thread);
4025 cpu_rq(cpu)->migration_thread = NULL;
4028 migrate_all_tasks(cpu);
4030 kthread_stop(rq->migration_thread);
4031 rq->migration_thread = NULL;
4032 /* Idle task back to normal (off runqueue, low prio) */
4033 rq = task_rq_lock(rq->idle, &flags);
4034 deactivate_task(rq->idle, rq);
4035 rq->idle->static_prio = MAX_PRIO;
4036 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4037 task_rq_unlock(rq, &flags);
4038 BUG_ON(rq->nr_running != 0);
4040 /* No need to migrate the tasks: it was best-effort if
4041 * they didn't do lock_cpu_hotplug(). Just wake up
4042 * the requestors. */
4043 spin_lock_irq(&rq->lock);
4044 while (!list_empty(&rq->migration_queue)) {
4045 migration_req_t *req;
4046 req = list_entry(rq->migration_queue.next,
4047 migration_req_t, list);
4048 BUG_ON(req->type != REQ_MOVE_TASK);
4049 list_del_init(&req->list);
4050 complete(&req->done);
4052 spin_unlock_irq(&rq->lock);
4059 /* Register at highest priority so that task migration (migrate_all_tasks)
4060 * happens before everything else.
4062 static struct notifier_block __devinitdata migration_notifier = {
4063 .notifier_call = migration_call,
4067 int __init migration_init(void)
4069 void *cpu = (void *)(long)smp_processor_id();
4070 /* Start one for boot CPU. */
4071 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4072 migration_call(&migration_notifier, CPU_ONLINE, cpu);
4073 register_cpu_notifier(&migration_notifier);
4079 * The 'big kernel lock'
4081 * This spinlock is taken and released recursively by lock_kernel()
4082 * and unlock_kernel(). It is transparently dropped and reaquired
4083 * over schedule(). It is used to protect legacy code that hasn't
4084 * been migrated to a proper locking design yet.
4086 * Don't use in new code.
4088 * Note: spinlock debugging needs this even on !CONFIG_SMP.
4090 spinlock_t kernel_flag __cacheline_aligned_in_smp = SPIN_LOCK_UNLOCKED;
4091 EXPORT_SYMBOL(kernel_flag);
4094 /* Attach the domain 'sd' to 'cpu' as its base domain */
4095 void cpu_attach_domain(struct sched_domain *sd, int cpu)
4097 migration_req_t req;
4098 unsigned long flags;
4099 runqueue_t *rq = cpu_rq(cpu);
4104 spin_lock_irqsave(&rq->lock, flags);
4106 if (cpu == smp_processor_id() || !cpu_online(cpu)) {
4109 init_completion(&req.done);
4110 req.type = REQ_SET_DOMAIN;
4112 list_add(&req.list, &rq->migration_queue);
4116 spin_unlock_irqrestore(&rq->lock, flags);
4119 wake_up_process(rq->migration_thread);
4120 wait_for_completion(&req.done);
4123 unlock_cpu_hotplug();
4126 #ifdef ARCH_HAS_SCHED_DOMAIN
4127 extern void __init arch_init_sched_domains(void);
4129 static struct sched_group sched_group_cpus[NR_CPUS];
4130 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
4132 static struct sched_group sched_group_nodes[MAX_NUMNODES];
4133 static DEFINE_PER_CPU(struct sched_domain, node_domains);
4134 static void __init arch_init_sched_domains(void)
4137 struct sched_group *first_node = NULL, *last_node = NULL;
4139 /* Set up domains */
4141 int node = cpu_to_node(i);
4142 cpumask_t nodemask = node_to_cpumask(node);
4143 struct sched_domain *node_sd = &per_cpu(node_domains, i);
4144 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
4146 *node_sd = SD_NODE_INIT;
4147 node_sd->span = cpu_possible_map;
4148 node_sd->groups = &sched_group_nodes[cpu_to_node(i)];
4150 *cpu_sd = SD_CPU_INIT;
4151 cpus_and(cpu_sd->span, nodemask, cpu_possible_map);
4152 cpu_sd->groups = &sched_group_cpus[i];
4153 cpu_sd->parent = node_sd;
4157 for (i = 0; i < MAX_NUMNODES; i++) {
4158 cpumask_t tmp = node_to_cpumask(i);
4160 struct sched_group *first_cpu = NULL, *last_cpu = NULL;
4161 struct sched_group *node = &sched_group_nodes[i];
4164 cpus_and(nodemask, tmp, cpu_possible_map);
4166 if (cpus_empty(nodemask))
4169 node->cpumask = nodemask;
4170 node->cpu_power = SCHED_LOAD_SCALE * cpus_weight(node->cpumask);
4172 for_each_cpu_mask(j, node->cpumask) {
4173 struct sched_group *cpu = &sched_group_cpus[j];
4175 cpus_clear(cpu->cpumask);
4176 cpu_set(j, cpu->cpumask);
4177 cpu->cpu_power = SCHED_LOAD_SCALE;
4182 last_cpu->next = cpu;
4185 last_cpu->next = first_cpu;
4190 last_node->next = node;
4193 last_node->next = first_node;
4197 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
4198 cpu_attach_domain(cpu_sd, i);
4202 #else /* !CONFIG_NUMA */
4203 static void __init arch_init_sched_domains(void)
4206 struct sched_group *first_cpu = NULL, *last_cpu = NULL;
4208 /* Set up domains */
4210 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
4212 *cpu_sd = SD_CPU_INIT;
4213 cpu_sd->span = cpu_possible_map;
4214 cpu_sd->groups = &sched_group_cpus[i];
4217 /* Set up CPU groups */
4218 for_each_cpu_mask(i, cpu_possible_map) {
4219 struct sched_group *cpu = &sched_group_cpus[i];
4221 cpus_clear(cpu->cpumask);
4222 cpu_set(i, cpu->cpumask);
4223 cpu->cpu_power = SCHED_LOAD_SCALE;
4228 last_cpu->next = cpu;
4231 last_cpu->next = first_cpu;
4233 mb(); /* domains were modified outside the lock */
4235 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
4236 cpu_attach_domain(cpu_sd, i);
4240 #endif /* CONFIG_NUMA */
4241 #endif /* ARCH_HAS_SCHED_DOMAIN */
4243 #define SCHED_DOMAIN_DEBUG
4244 #ifdef SCHED_DOMAIN_DEBUG
4245 void sched_domain_debug(void)
4250 runqueue_t *rq = cpu_rq(i);
4251 struct sched_domain *sd;
4256 printk(KERN_WARNING "CPU%d: %s\n",
4257 i, (cpu_online(i) ? " online" : "offline"));
4262 struct sched_group *group = sd->groups;
4263 cpumask_t groupmask, tmp;
4265 cpumask_scnprintf(str, NR_CPUS, sd->span);
4266 cpus_clear(groupmask);
4269 for (j = 0; j < level + 1; j++)
4271 printk("domain %d: span %s\n", level, str);
4273 if (!cpu_isset(i, sd->span))
4274 printk(KERN_WARNING "ERROR domain->span does not contain CPU%d\n", i);
4275 if (!cpu_isset(i, group->cpumask))
4276 printk(KERN_WARNING "ERROR domain->groups does not contain CPU%d\n", i);
4277 if (!group->cpu_power)
4278 printk(KERN_WARNING "ERROR domain->cpu_power not set\n");
4280 printk(KERN_WARNING);
4281 for (j = 0; j < level + 2; j++)
4286 printk(" ERROR: NULL");
4290 if (!cpus_weight(group->cpumask))
4291 printk(" ERROR empty group:");
4293 cpus_and(tmp, groupmask, group->cpumask);
4294 if (cpus_weight(tmp) > 0)
4295 printk(" ERROR repeated CPUs:");
4297 cpus_or(groupmask, groupmask, group->cpumask);
4299 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
4302 group = group->next;
4303 } while (group != sd->groups);
4306 if (!cpus_equal(sd->span, groupmask))
4307 printk(KERN_DEBUG "ERROR groups don't span domain->span\n");
4313 cpus_and(tmp, groupmask, sd->span);
4314 if (!cpus_equal(tmp, groupmask))
4315 printk(KERN_WARNING "ERROR parent span is not a superset of domain->span\n");
4322 #define sched_domain_debug() {}
4325 void __init sched_init_smp(void)
4327 arch_init_sched_domains();
4328 sched_domain_debug();
4331 void __init sched_init_smp(void)
4334 #endif /* CONFIG_SMP */
4336 int in_sched_functions(unsigned long addr)
4338 /* Linker adds these: start and end of __sched functions */
4339 extern char __sched_text_start[], __sched_text_end[];
4340 return addr >= (unsigned long)__sched_text_start
4341 && addr < (unsigned long)__sched_text_end;
4344 void __init sched_init(void)
4348 #ifndef CONFIG_CKRM_CPU_SCHEDULE
4353 /* Set up an initial dummy domain for early boot */
4354 static struct sched_domain sched_domain_init;
4355 static struct sched_group sched_group_init;
4356 cpumask_t cpu_mask_all = CPU_MASK_ALL;
4358 memset(&sched_domain_init, 0, sizeof(struct sched_domain));
4359 sched_domain_init.span = cpu_mask_all;
4360 sched_domain_init.groups = &sched_group_init;
4361 sched_domain_init.last_balance = jiffies;
4362 sched_domain_init.balance_interval = INT_MAX; /* Don't balance */
4364 memset(&sched_group_init, 0, sizeof(struct sched_group));
4365 sched_group_init.cpumask = cpu_mask_all;
4366 sched_group_init.next = &sched_group_init;
4367 sched_group_init.cpu_power = SCHED_LOAD_SCALE;
4372 for (i = 0; i < NR_CPUS; i++) {
4373 #ifndef CONFIG_CKRM_CPU_SCHEDULE
4374 prio_array_t *array;
4377 spin_lock_init(&rq->lock);
4379 #ifndef CONFIG_CKRM_CPU_SCHEDULE
4380 rq->active = rq->arrays;
4381 rq->expired = rq->arrays + 1;
4383 rq->ckrm_cpu_load = 0;
4385 rq->best_expired_prio = MAX_PRIO;
4388 rq->sd = &sched_domain_init;
4390 rq->active_balance = 0;
4392 rq->migration_thread = NULL;
4393 INIT_LIST_HEAD(&rq->migration_queue);
4395 INIT_LIST_HEAD(&rq->hold_queue);
4396 atomic_set(&rq->nr_iowait, 0);
4398 #ifndef CONFIG_CKRM_CPU_SCHEDULE
4399 for (j = 0; j < 2; j++) {
4400 array = rq->arrays + j;
4401 for (k = 0; k < MAX_PRIO; k++) {
4402 INIT_LIST_HEAD(array->queue + k);
4403 __clear_bit(k, array->bitmap);
4405 // delimiter for bitsearch
4406 __set_bit(MAX_PRIO, array->bitmap);
4412 * We have to do a little magic to get the first
4413 * thread right in SMP mode.
4418 set_task_cpu(current, smp_processor_id());
4419 #ifdef CONFIG_CKRM_CPU_SCHEDULE
4420 current->cpu_class = default_cpu_class;
4421 current->array = NULL;
4423 wake_up_forked_process(current);
4426 * The boot idle thread does lazy MMU switching as well:
4428 atomic_inc(&init_mm.mm_count);
4429 enter_lazy_tlb(&init_mm, current);
4432 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4433 void __might_sleep(char *file, int line)
4435 #if defined(in_atomic)
4436 static unsigned long prev_jiffy; /* ratelimiting */
4438 if ((in_atomic() || irqs_disabled()) &&
4439 system_state == SYSTEM_RUNNING) {
4440 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
4442 prev_jiffy = jiffies;
4443 printk(KERN_ERR "Debug: sleeping function called from invalid"
4444 " context at %s:%d\n", file, line);
4445 printk("in_atomic():%d, irqs_disabled():%d\n",
4446 in_atomic(), irqs_disabled());
4451 EXPORT_SYMBOL(__might_sleep);
4455 #if defined(CONFIG_SMP) && defined(CONFIG_PREEMPT)
4457 * This could be a long-held lock. If another CPU holds it for a long time,
4458 * and that CPU is not asked to reschedule then *this* CPU will spin on the
4459 * lock for a long time, even if *this* CPU is asked to reschedule.
4461 * So what we do here, in the slow (contended) path is to spin on the lock by
4462 * hand while permitting preemption.
4464 * Called inside preempt_disable().
4466 void __sched __preempt_spin_lock(spinlock_t *lock)
4468 if (preempt_count() > 1) {
4469 _raw_spin_lock(lock);
4474 while (spin_is_locked(lock))
4477 } while (!_raw_spin_trylock(lock));
4480 EXPORT_SYMBOL(__preempt_spin_lock);
4482 void __sched __preempt_write_lock(rwlock_t *lock)
4484 if (preempt_count() > 1) {
4485 _raw_write_lock(lock);
4491 while (rwlock_is_locked(lock))
4494 } while (!_raw_write_trylock(lock));
4497 EXPORT_SYMBOL(__preempt_write_lock);
4498 #endif /* defined(CONFIG_SMP) && defined(CONFIG_PREEMPT) */
4500 #ifdef CONFIG_DELAY_ACCT
4501 int task_running_sys(struct task_struct *p)
4503 return task_running(task_rq(p),p);
4505 EXPORT_SYMBOL(task_running_sys);
4508 #ifdef CONFIG_CKRM_CPU_SCHEDULE
4510 * return the classqueue object of a certain processor
4511 * Note: not supposed to be used in performance sensitive functions
4513 struct classqueue_struct * get_cpu_classqueue(int cpu)
4515 return (& (cpu_rq(cpu)->classqueue) );