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 <asm/mmu_context.h>
28 #include <linux/interrupt.h>
29 #include <linux/completion.h>
30 #include <linux/kernel_stat.h>
31 #include <linux/security.h>
32 #include <linux/notifier.h>
33 #include <linux/suspend.h>
34 #include <linux/blkdev.h>
35 #include <linux/delay.h>
36 #include <linux/smp.h>
37 #include <linux/timer.h>
38 #include <linux/rcupdate.h>
39 #include <linux/cpu.h>
40 #include <linux/percpu.h>
41 #include <linux/kthread.h>
43 #include <asm/unistd.h>
46 #define cpu_to_node_mask(cpu) node_to_cpumask(cpu_to_node(cpu))
48 #define cpu_to_node_mask(cpu) (cpu_online_map)
52 * Convert user-nice values [ -20 ... 0 ... 19 ]
53 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
56 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
57 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
58 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
61 * 'User priority' is the nice value converted to something we
62 * can work with better when scaling various scheduler parameters,
63 * it's a [ 0 ... 39 ] range.
65 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
66 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
67 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
68 #define AVG_TIMESLICE (MIN_TIMESLICE + ((MAX_TIMESLICE - MIN_TIMESLICE) *\
69 (MAX_PRIO-1-NICE_TO_PRIO(0))/(MAX_USER_PRIO - 1)))
72 * Some helpers for converting nanosecond timing to jiffy resolution
74 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
75 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
78 * These are the 'tuning knobs' of the scheduler:
80 * Minimum timeslice is 10 msecs, default timeslice is 100 msecs,
81 * maximum timeslice is 200 msecs. Timeslices get refilled after
84 #define MIN_TIMESLICE ( 10 * HZ / 1000)
85 #define MAX_TIMESLICE (200 * HZ / 1000)
86 #define ON_RUNQUEUE_WEIGHT 30
87 #define CHILD_PENALTY 95
88 #define PARENT_PENALTY 100
90 #define PRIO_BONUS_RATIO 25
91 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
92 #define INTERACTIVE_DELTA 2
93 #define MAX_SLEEP_AVG (AVG_TIMESLICE * MAX_BONUS)
94 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
95 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
96 #define CREDIT_LIMIT 100
99 * If a task is 'interactive' then we reinsert it in the active
100 * array after it has expired its current timeslice. (it will not
101 * continue to run immediately, it will still roundrobin with
102 * other interactive tasks.)
104 * This part scales the interactivity limit depending on niceness.
106 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
107 * Here are a few examples of different nice levels:
109 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
110 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
111 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
112 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
113 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
115 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
116 * priority range a task can explore, a value of '1' means the
117 * task is rated interactive.)
119 * Ie. nice +19 tasks can never get 'interactive' enough to be
120 * reinserted into the active array. And only heavily CPU-hog nice -20
121 * tasks will be expired. Default nice 0 tasks are somewhere between,
122 * it takes some effort for them to get interactive, but it's not
126 #define CURRENT_BONUS(p) \
127 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
131 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
132 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
135 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
136 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
139 #define SCALE(v1,v1_max,v2_max) \
140 (v1) * (v2_max) / (v1_max)
143 (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
145 #define TASK_INTERACTIVE(p) \
146 ((p)->prio <= (p)->static_prio - DELTA(p))
148 #define INTERACTIVE_SLEEP(p) \
149 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
150 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
152 #define HIGH_CREDIT(p) \
153 ((p)->interactive_credit > CREDIT_LIMIT)
155 #define LOW_CREDIT(p) \
156 ((p)->interactive_credit < -CREDIT_LIMIT)
159 * BASE_TIMESLICE scales user-nice values [ -20 ... 19 ]
160 * to time slice values.
162 * The higher a thread's priority, the bigger timeslices
163 * it gets during one round of execution. But even the lowest
164 * priority thread gets MIN_TIMESLICE worth of execution time.
166 * task_timeslice() is the interface that is used by the scheduler.
169 #define BASE_TIMESLICE(p) (MIN_TIMESLICE + \
170 ((MAX_TIMESLICE - MIN_TIMESLICE) * \
171 (MAX_PRIO-1 - (p)->static_prio) / (MAX_USER_PRIO-1)))
173 static unsigned int task_timeslice(task_t *p)
175 return BASE_TIMESLICE(p);
178 #define task_hot(p, now, sd) ((now) - (p)->timestamp < (sd)->cache_hot_time)
181 * These are the runqueue data structures:
183 typedef struct runqueue runqueue_t;
185 #ifdef CONFIG_CKRM_CPU_SCHEDULE
186 #include <linux/ckrm_classqueue.h>
189 #ifdef CONFIG_CKRM_CPU_SCHEDULE
192 * if belong to different class, compare class priority
193 * otherwise compare task priority
195 #define TASK_PREEMPTS_CURR(p, rq) \
196 (((p)->cpu_class != (rq)->curr->cpu_class) && ((rq)->curr != (rq)->idle))? class_preempts_curr((p),(rq)->curr) : ((p)->prio < (rq)->curr->prio)
198 #define TASK_PREEMPTS_CURR(p, rq) \
199 ((p)->prio < (rq)->curr->prio)
203 * This is the main, per-CPU runqueue data structure.
205 * Locking rule: those places that want to lock multiple runqueues
206 * (such as the load balancing or the thread migration code), lock
207 * acquire operations must be ordered by ascending &runqueue.
213 * nr_running and cpu_load should be in the same cacheline because
214 * remote CPUs use both these fields when doing load calculation.
216 unsigned long nr_running;
217 #if defined(CONFIG_SMP)
218 unsigned long cpu_load;
220 unsigned long long nr_switches;
221 unsigned long expired_timestamp, nr_uninterruptible;
222 unsigned long long timestamp_last_tick;
224 struct mm_struct *prev_mm;
225 #ifdef CONFIG_CKRM_CPU_SCHEDULE
226 unsigned long ckrm_cpu_load;
227 struct classqueue_struct classqueue;
229 prio_array_t *active, *expired, arrays[2];
231 int best_expired_prio;
235 struct sched_domain *sd;
237 /* For active balancing */
241 task_t *migration_thread;
242 struct list_head migration_queue;
246 static DEFINE_PER_CPU(struct runqueue, runqueues);
248 #define for_each_domain(cpu, domain) \
249 for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
251 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
252 #define this_rq() (&__get_cpu_var(runqueues))
253 #define task_rq(p) cpu_rq(task_cpu(p))
254 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
257 * Default context-switch locking:
259 #ifndef prepare_arch_switch
260 # define prepare_arch_switch(rq, next) do { } while (0)
261 # define finish_arch_switch(rq, next) spin_unlock_irq(&(rq)->lock)
262 # define task_running(rq, p) ((rq)->curr == (p))
265 #ifdef CONFIG_CKRM_CPU_SCHEDULE
266 #include <linux/ckrm_sched.h>
267 spinlock_t cvt_lock = SPIN_LOCK_UNLOCKED;
268 rwlock_t class_list_lock = RW_LOCK_UNLOCKED;
269 LIST_HEAD(active_cpu_classes); // list of active cpu classes; anchor
270 struct ckrm_cpu_class default_cpu_class_obj;
273 * the minimum CVT allowed is the base_cvt
274 * otherwise, it will starve others
276 CVT_t get_min_cvt(int cpu)
279 struct ckrm_local_runqueue * lrq;
282 node = classqueue_get_head(bpt_queue(cpu));
283 lrq = (node) ? class_list_entry(node) : NULL;
286 min_cvt = lrq->local_cvt;
294 * update the classueue base for all the runqueues
295 * TODO: we can only update half of the min_base to solve the movebackward issue
297 static inline void check_update_class_base(int this_cpu) {
298 unsigned long min_base = 0xFFFFFFFF;
302 if (! cpu_online(this_cpu)) return;
305 * find the min_base across all the processors
307 for_each_online_cpu(i) {
309 * I should change it to directly use bpt->base
311 node = classqueue_get_head(bpt_queue(i));
312 if (node && node->prio < min_base) {
313 min_base = node->prio;
316 if (min_base != 0xFFFFFFFF)
317 classqueue_update_base(bpt_queue(this_cpu),min_base);
320 static inline void ckrm_rebalance_tick(int j,int this_cpu)
322 #ifdef CONFIG_CKRM_CPU_SCHEDULE
323 read_lock(&class_list_lock);
324 if (!(j % CVT_UPDATE_TICK))
325 update_global_cvts(this_cpu);
327 #define CKRM_BASE_UPDATE_RATE 400
328 if (! (jiffies % CKRM_BASE_UPDATE_RATE))
329 check_update_class_base(this_cpu);
331 read_unlock(&class_list_lock);
335 static inline struct ckrm_local_runqueue *rq_get_next_class(struct runqueue *rq)
337 cq_node_t *node = classqueue_get_head(&rq->classqueue);
338 return ((node) ? class_list_entry(node) : NULL);
341 static inline struct task_struct * rq_get_next_task(struct runqueue* rq)
344 struct task_struct *next;
345 struct ckrm_local_runqueue *queue;
346 int cpu = smp_processor_id();
350 if ((queue = rq_get_next_class(rq))) {
351 array = queue->active;
352 //check switch active/expired queue
353 if (unlikely(!queue->active->nr_active)) {
356 array = queue->active;
357 queue->active = queue->expired;
358 queue->expired = array;
359 queue->expired_timestamp = 0;
361 if (queue->active->nr_active)
362 set_top_priority(queue,
363 find_first_bit(queue->active->bitmap, MAX_PRIO));
365 classqueue_dequeue(queue->classqueue,
366 &queue->classqueue_linkobj);
367 cpu_demand_event(get_rq_local_stat(queue,cpu),CPU_DEMAND_DEQUEUE,0);
370 goto retry_next_class;
372 BUG_ON(!queue->active->nr_active);
373 next = task_list_entry(array->queue[queue->top_priority].next);
378 static inline void rq_load_inc(runqueue_t *rq, struct task_struct *p) { rq->ckrm_cpu_load += cpu_class_weight(p->cpu_class); }
379 static inline void rq_load_dec(runqueue_t *rq, struct task_struct *p) { rq->ckrm_cpu_load -= cpu_class_weight(p->cpu_class); }
381 #else /*CONFIG_CKRM_CPU_SCHEDULE*/
383 static inline struct task_struct * rq_get_next_task(struct runqueue* rq)
386 struct list_head *queue;
390 if (unlikely(!array->nr_active)) {
392 * Switch the active and expired arrays.
394 rq->active = rq->expired;
397 rq->expired_timestamp = 0;
400 idx = sched_find_first_bit(array->bitmap);
401 queue = array->queue + idx;
402 return list_entry(queue->next, task_t, run_list);
405 static inline void class_enqueue_task(struct task_struct* p, prio_array_t *array) { }
406 static inline void class_dequeue_task(struct task_struct* p, prio_array_t *array) { }
407 static inline void init_cpu_classes(void) { }
408 static inline void rq_load_inc(runqueue_t *rq, struct task_struct *p) { }
409 static inline void rq_load_dec(runqueue_t *rq, struct task_struct *p) { }
410 #endif /* CONFIG_CKRM_CPU_SCHEDULE */
414 * task_rq_lock - lock the runqueue a given task resides on and disable
415 * interrupts. Note the ordering: we can safely lookup the task_rq without
416 * explicitly disabling preemption.
418 runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
423 local_irq_save(*flags);
425 spin_lock(&rq->lock);
426 if (unlikely(rq != task_rq(p))) {
427 spin_unlock_irqrestore(&rq->lock, *flags);
428 goto repeat_lock_task;
433 void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
435 spin_unlock_irqrestore(&rq->lock, *flags);
439 * rq_lock - lock a given runqueue and disable interrupts.
441 static runqueue_t *this_rq_lock(void)
447 spin_lock(&rq->lock);
452 static inline void rq_unlock(runqueue_t *rq)
454 spin_unlock_irq(&rq->lock);
458 * Adding/removing a task to/from a priority array:
460 void dequeue_task(struct task_struct *p, prio_array_t *array)
464 list_del(&p->run_list);
465 if (list_empty(array->queue + p->prio))
466 __clear_bit(p->prio, array->bitmap);
467 class_dequeue_task(p,array);
470 void enqueue_task(struct task_struct *p, prio_array_t *array)
472 list_add_tail(&p->run_list, array->queue + p->prio);
473 __set_bit(p->prio, array->bitmap);
476 class_enqueue_task(p,array);
480 * Used by the migration code - we pull tasks from the head of the
481 * remote queue so we want these tasks to show up at the head of the
484 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
486 list_add(&p->run_list, array->queue + p->prio);
487 __set_bit(p->prio, array->bitmap);
490 class_enqueue_task(p,array);
494 * effective_prio - return the priority that is based on the static
495 * priority but is modified by bonuses/penalties.
497 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
498 * into the -5 ... 0 ... +5 bonus/penalty range.
500 * We use 25% of the full 0...39 priority range so that:
502 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
503 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
505 * Both properties are important to certain workloads.
507 static int effective_prio(task_t *p)
514 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
516 prio = p->static_prio - bonus;
517 if (prio < MAX_RT_PRIO)
519 if (prio > MAX_PRIO-1)
525 * __activate_task - move a task to the runqueue.
527 static inline void __activate_task(task_t *p, runqueue_t *rq)
529 enqueue_task(p, rq_active(p,rq));
535 * __activate_idle_task - move idle task to the _front_ of runqueue.
537 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
539 enqueue_task_head(p, rq_active(p,rq));
544 static void recalc_task_prio(task_t *p, unsigned long long now)
546 unsigned long long __sleep_time = now - p->timestamp;
547 unsigned long sleep_time;
549 if (__sleep_time > NS_MAX_SLEEP_AVG)
550 sleep_time = NS_MAX_SLEEP_AVG;
552 sleep_time = (unsigned long)__sleep_time;
554 if (likely(sleep_time > 0)) {
556 * User tasks that sleep a long time are categorised as
557 * idle and will get just interactive status to stay active &
558 * prevent them suddenly becoming cpu hogs and starving
561 if (p->mm && p->activated != -1 &&
562 sleep_time > INTERACTIVE_SLEEP(p)) {
563 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
566 p->interactive_credit++;
569 * The lower the sleep avg a task has the more
570 * rapidly it will rise with sleep time.
572 sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
575 * Tasks with low interactive_credit are limited to
576 * one timeslice worth of sleep avg bonus.
579 sleep_time > JIFFIES_TO_NS(task_timeslice(p)))
580 sleep_time = JIFFIES_TO_NS(task_timeslice(p));
583 * Non high_credit tasks waking from uninterruptible
584 * sleep are limited in their sleep_avg rise as they
585 * are likely to be cpu hogs waiting on I/O
587 if (p->activated == -1 && !HIGH_CREDIT(p) && p->mm) {
588 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
590 else if (p->sleep_avg + sleep_time >=
591 INTERACTIVE_SLEEP(p)) {
592 p->sleep_avg = INTERACTIVE_SLEEP(p);
598 * This code gives a bonus to interactive tasks.
600 * The boost works by updating the 'average sleep time'
601 * value here, based on ->timestamp. The more time a
602 * task spends sleeping, the higher the average gets -
603 * and the higher the priority boost gets as well.
605 p->sleep_avg += sleep_time;
607 if (p->sleep_avg > NS_MAX_SLEEP_AVG) {
608 p->sleep_avg = NS_MAX_SLEEP_AVG;
610 p->interactive_credit++;
615 p->prio = effective_prio(p);
619 * activate_task - move a task to the runqueue and do priority recalculation
621 * Update all the scheduling statistics stuff. (sleep average
622 * calculation, priority modifiers, etc.)
624 static void activate_task(task_t *p, runqueue_t *rq, int local)
626 unsigned long long now;
631 /* Compensate for drifting sched_clock */
632 runqueue_t *this_rq = this_rq();
633 now = (now - this_rq->timestamp_last_tick)
634 + rq->timestamp_last_tick;
638 recalc_task_prio(p, now);
641 * This checks to make sure it's not an uninterruptible task
642 * that is now waking up.
646 * Tasks which were woken up by interrupts (ie. hw events)
647 * are most likely of interactive nature. So we give them
648 * the credit of extending their sleep time to the period
649 * of time they spend on the runqueue, waiting for execution
650 * on a CPU, first time around:
656 * Normal first-time wakeups get a credit too for
657 * on-runqueue time, but it will be weighted down:
664 __activate_task(p, rq);
668 * deactivate_task - remove a task from the runqueue.
670 static void deactivate_task(struct task_struct *p, runqueue_t *rq)
674 if (p->state == TASK_UNINTERRUPTIBLE)
675 rq->nr_uninterruptible++;
676 dequeue_task(p, p->array);
681 * resched_task - mark a task 'to be rescheduled now'.
683 * On UP this means the setting of the need_resched flag, on SMP it
684 * might also involve a cross-CPU call to trigger the scheduler on
688 static void resched_task(task_t *p)
690 int need_resched, nrpolling;
693 /* minimise the chance of sending an interrupt to poll_idle() */
694 nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
695 need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
696 nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
698 if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
699 smp_send_reschedule(task_cpu(p));
703 static inline void resched_task(task_t *p)
705 set_tsk_need_resched(p);
710 * task_curr - is this task currently executing on a CPU?
711 * @p: the task in question.
713 inline int task_curr(task_t *p)
715 return cpu_curr(task_cpu(p)) == p;
725 struct list_head list;
726 enum request_type type;
728 /* For REQ_MOVE_TASK */
732 /* For REQ_SET_DOMAIN */
733 struct sched_domain *sd;
735 struct completion done;
739 * The task's runqueue lock must be held.
740 * Returns true if you have to wait for migration thread.
742 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
744 runqueue_t *rq = task_rq(p);
747 * If the task is not on a runqueue (and not running), then
748 * it is sufficient to simply update the task's cpu field.
750 if (!p->array && !task_running(rq, p)) {
751 set_task_cpu(p, dest_cpu);
755 init_completion(&req->done);
756 req->type = REQ_MOVE_TASK;
758 req->dest_cpu = dest_cpu;
759 list_add(&req->list, &rq->migration_queue);
764 * wait_task_inactive - wait for a thread to unschedule.
766 * The caller must ensure that the task *will* unschedule sometime soon,
767 * else this function might spin for a *long* time. This function can't
768 * be called with interrupts off, or it may introduce deadlock with
769 * smp_call_function() if an IPI is sent by the same process we are
770 * waiting to become inactive.
772 void wait_task_inactive(task_t * p)
779 rq = task_rq_lock(p, &flags);
780 /* Must be off runqueue entirely, not preempted. */
781 if (unlikely(p->array)) {
782 /* If it's preempted, we yield. It could be a while. */
783 preempted = !task_running(rq, p);
784 task_rq_unlock(rq, &flags);
790 task_rq_unlock(rq, &flags);
794 * kick_process - kick a running thread to enter/exit the kernel
795 * @p: the to-be-kicked thread
797 * Cause a process which is running on another CPU to enter
798 * kernel-mode, without any delay. (to get signals handled.)
800 void kick_process(task_t *p)
806 if ((cpu != smp_processor_id()) && task_curr(p))
807 smp_send_reschedule(cpu);
811 EXPORT_SYMBOL_GPL(kick_process);
814 * Return a low guess at the load of a migration-source cpu.
816 * We want to under-estimate the load of migration sources, to
817 * balance conservatively.
819 static inline unsigned long source_load(int cpu)
821 runqueue_t *rq = cpu_rq(cpu);
822 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
824 return min(rq->cpu_load, load_now);
828 * Return a high guess at the load of a migration-target cpu
830 static inline unsigned long target_load(int cpu)
832 runqueue_t *rq = cpu_rq(cpu);
833 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
835 return max(rq->cpu_load, load_now);
841 * wake_idle() is useful especially on SMT architectures to wake a
842 * task onto an idle sibling if we would otherwise wake it onto a
845 * Returns the CPU we should wake onto.
847 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
848 static int wake_idle(int cpu, task_t *p)
851 runqueue_t *rq = cpu_rq(cpu);
852 struct sched_domain *sd;
859 if (!(sd->flags & SD_WAKE_IDLE))
862 cpus_and(tmp, sd->span, cpu_online_map);
863 for_each_cpu_mask(i, tmp) {
864 if (!cpu_isset(i, p->cpus_allowed))
874 static inline int wake_idle(int cpu, task_t *p)
881 * try_to_wake_up - wake up a thread
882 * @p: the to-be-woken-up thread
883 * @state: the mask of task states that can be woken
884 * @sync: do a synchronous wakeup?
886 * Put it on the run-queue if it's not already there. The "current"
887 * thread is always on the run-queue (except when the actual
888 * re-schedule is in progress), and as such you're allowed to do
889 * the simpler "current->state = TASK_RUNNING" to mark yourself
890 * runnable without the overhead of this.
892 * returns failure only if the task is already active.
894 static int try_to_wake_up(task_t * p, unsigned int state, int sync)
896 int cpu, this_cpu, success = 0;
901 unsigned long load, this_load;
902 struct sched_domain *sd;
906 rq = task_rq_lock(p, &flags);
907 old_state = p->state;
908 if (!(old_state & state))
915 this_cpu = smp_processor_id();
918 if (unlikely(task_running(rq, p)))
923 if (cpu == this_cpu || unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
926 load = source_load(cpu);
927 this_load = target_load(this_cpu);
930 * If sync wakeup then subtract the (maximum possible) effect of
931 * the currently running task from the load of the current CPU:
934 this_load -= SCHED_LOAD_SCALE;
936 /* Don't pull the task off an idle CPU to a busy one */
937 if (load < SCHED_LOAD_SCALE/2 && this_load > SCHED_LOAD_SCALE/2)
940 new_cpu = this_cpu; /* Wake to this CPU if we can */
943 * Scan domains for affine wakeup and passive balancing
946 for_each_domain(this_cpu, sd) {
947 unsigned int imbalance;
949 * Start passive balancing when half the imbalance_pct
952 imbalance = sd->imbalance_pct + (sd->imbalance_pct - 100) / 2;
954 if ( ((sd->flags & SD_WAKE_AFFINE) &&
955 !task_hot(p, rq->timestamp_last_tick, sd))
956 || ((sd->flags & SD_WAKE_BALANCE) &&
957 imbalance*this_load <= 100*load) ) {
959 * Now sd has SD_WAKE_AFFINE and p is cache cold in sd
960 * or sd has SD_WAKE_BALANCE and there is an imbalance
962 if (cpu_isset(cpu, sd->span))
967 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
969 new_cpu = wake_idle(new_cpu, p);
970 if (new_cpu != cpu && cpu_isset(new_cpu, p->cpus_allowed)) {
971 set_task_cpu(p, new_cpu);
972 task_rq_unlock(rq, &flags);
973 /* might preempt at this point */
974 rq = task_rq_lock(p, &flags);
975 old_state = p->state;
976 if (!(old_state & state))
981 this_cpu = smp_processor_id();
986 #endif /* CONFIG_SMP */
987 if (old_state == TASK_UNINTERRUPTIBLE) {
988 rq->nr_uninterruptible--;
990 * Tasks on involuntary sleep don't earn
991 * sleep_avg beyond just interactive state.
997 * Sync wakeups (i.e. those types of wakeups where the waker
998 * has indicated that it will leave the CPU in short order)
999 * don't trigger a preemption, if the woken up task will run on
1000 * this cpu. (in this case the 'I will reschedule' promise of
1001 * the waker guarantees that the freshly woken up task is going
1002 * to be considered on this CPU.)
1004 activate_task(p, rq, cpu == this_cpu);
1005 if (!sync || cpu != this_cpu) {
1006 if (TASK_PREEMPTS_CURR(p, rq))
1007 resched_task(rq->curr);
1012 p->state = TASK_RUNNING;
1014 task_rq_unlock(rq, &flags);
1019 int fastcall wake_up_process(task_t * p)
1021 return try_to_wake_up(p, TASK_STOPPED |
1022 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1025 EXPORT_SYMBOL(wake_up_process);
1027 int fastcall wake_up_state(task_t *p, unsigned int state)
1029 return try_to_wake_up(p, state, 0);
1033 * Perform scheduler related setup for a newly forked process p.
1034 * p is forked by current.
1036 void fastcall sched_fork(task_t *p)
1039 * We mark the process as running here, but have not actually
1040 * inserted it onto the runqueue yet. This guarantees that
1041 * nobody will actually run it, and a signal or other external
1042 * event cannot wake it up and insert it on the runqueue either.
1044 p->state = TASK_RUNNING;
1045 INIT_LIST_HEAD(&p->run_list);
1047 spin_lock_init(&p->switch_lock);
1048 #ifdef CONFIG_PREEMPT
1050 * During context-switch we hold precisely one spinlock, which
1051 * schedule_tail drops. (in the common case it's this_rq()->lock,
1052 * but it also can be p->switch_lock.) So we compensate with a count
1053 * of 1. Also, we want to start with kernel preemption disabled.
1055 p->thread_info->preempt_count = 1;
1058 * Share the timeslice between parent and child, thus the
1059 * total amount of pending timeslices in the system doesn't change,
1060 * resulting in more scheduling fairness.
1062 local_irq_disable();
1063 p->time_slice = (current->time_slice + 1) >> 1;
1065 * The remainder of the first timeslice might be recovered by
1066 * the parent if the child exits early enough.
1068 p->first_time_slice = 1;
1069 current->time_slice >>= 1;
1070 p->timestamp = sched_clock();
1071 if (!current->time_slice) {
1073 * This case is rare, it happens when the parent has only
1074 * a single jiffy left from its timeslice. Taking the
1075 * runqueue lock is not a problem.
1077 current->time_slice = 1;
1079 scheduler_tick(0, 0);
1087 * wake_up_forked_process - wake up a freshly forked process.
1089 * This function will do some initial scheduler statistics housekeeping
1090 * that must be done for every newly created process.
1092 void fastcall wake_up_forked_process(task_t * p)
1094 unsigned long flags;
1095 runqueue_t *rq = task_rq_lock(current, &flags);
1097 BUG_ON(p->state != TASK_RUNNING);
1100 * We decrease the sleep average of forking parents
1101 * and children as well, to keep max-interactive tasks
1102 * from forking tasks that are max-interactive.
1104 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1105 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1107 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1108 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1110 p->interactive_credit = 0;
1112 p->prio = effective_prio(p);
1113 set_task_cpu(p, smp_processor_id());
1115 if (unlikely(!current->array))
1116 __activate_task(p, rq);
1118 p->prio = current->prio;
1119 list_add_tail(&p->run_list, ¤t->run_list);
1120 p->array = current->array;
1121 p->array->nr_active++;
1125 task_rq_unlock(rq, &flags);
1129 * Potentially available exiting-child timeslices are
1130 * retrieved here - this way the parent does not get
1131 * penalized for creating too many threads.
1133 * (this cannot be used to 'generate' timeslices
1134 * artificially, because any timeslice recovered here
1135 * was given away by the parent in the first place.)
1137 void fastcall sched_exit(task_t * p)
1139 unsigned long flags;
1142 local_irq_save(flags);
1143 if (p->first_time_slice) {
1144 p->parent->time_slice += p->time_slice;
1145 if (unlikely(p->parent->time_slice > MAX_TIMESLICE))
1146 p->parent->time_slice = MAX_TIMESLICE;
1148 local_irq_restore(flags);
1150 * If the child was a (relative-) CPU hog then decrease
1151 * the sleep_avg of the parent as well.
1153 rq = task_rq_lock(p->parent, &flags);
1154 if (p->sleep_avg < p->parent->sleep_avg)
1155 p->parent->sleep_avg = p->parent->sleep_avg /
1156 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1158 task_rq_unlock(rq, &flags);
1162 * finish_task_switch - clean up after a task-switch
1163 * @prev: the thread we just switched away from.
1165 * We enter this with the runqueue still locked, and finish_arch_switch()
1166 * will unlock it along with doing any other architecture-specific cleanup
1169 * Note that we may have delayed dropping an mm in context_switch(). If
1170 * so, we finish that here outside of the runqueue lock. (Doing it
1171 * with the lock held can cause deadlocks; see schedule() for
1174 static void finish_task_switch(task_t *prev)
1176 runqueue_t *rq = this_rq();
1177 struct mm_struct *mm = rq->prev_mm;
1178 unsigned long prev_task_flags;
1183 * A task struct has one reference for the use as "current".
1184 * If a task dies, then it sets TASK_ZOMBIE in tsk->state and calls
1185 * schedule one last time. The schedule call will never return,
1186 * and the scheduled task must drop that reference.
1187 * The test for TASK_ZOMBIE must occur while the runqueue locks are
1188 * still held, otherwise prev could be scheduled on another cpu, die
1189 * there before we look at prev->state, and then the reference would
1191 * Manfred Spraul <manfred@colorfullife.com>
1193 prev_task_flags = prev->flags;
1194 finish_arch_switch(rq, prev);
1197 if (unlikely(prev_task_flags & PF_DEAD))
1198 put_task_struct(prev);
1202 * schedule_tail - first thing a freshly forked thread must call.
1203 * @prev: the thread we just switched away from.
1205 asmlinkage void schedule_tail(task_t *prev)
1207 finish_task_switch(prev);
1209 if (current->set_child_tid)
1210 put_user(current->pid, current->set_child_tid);
1214 * context_switch - switch to the new MM and the new
1215 * thread's register state.
1218 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1220 struct mm_struct *mm = next->mm;
1221 struct mm_struct *oldmm = prev->active_mm;
1223 if (unlikely(!mm)) {
1224 next->active_mm = oldmm;
1225 atomic_inc(&oldmm->mm_count);
1226 enter_lazy_tlb(oldmm, next);
1228 switch_mm(oldmm, mm, next);
1230 if (unlikely(!prev->mm)) {
1231 prev->active_mm = NULL;
1232 WARN_ON(rq->prev_mm);
1233 rq->prev_mm = oldmm;
1236 /* Here we just switch the register state and the stack. */
1237 switch_to(prev, next, prev);
1243 * nr_running, nr_uninterruptible and nr_context_switches:
1245 * externally visible scheduler statistics: current number of runnable
1246 * threads, current number of uninterruptible-sleeping threads, total
1247 * number of context switches performed since bootup.
1249 unsigned long nr_running(void)
1251 unsigned long i, sum = 0;
1254 sum += cpu_rq(i)->nr_running;
1259 unsigned long nr_uninterruptible(void)
1261 unsigned long i, sum = 0;
1263 for_each_online_cpu(i)
1264 sum += cpu_rq(i)->nr_uninterruptible;
1269 unsigned long long nr_context_switches(void)
1271 unsigned long long i, sum = 0;
1273 for_each_online_cpu(i)
1274 sum += cpu_rq(i)->nr_switches;
1279 unsigned long nr_iowait(void)
1281 unsigned long i, sum = 0;
1283 for_each_online_cpu(i)
1284 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1290 * double_rq_lock - safely lock two runqueues
1292 * Note this does not disable interrupts like task_rq_lock,
1293 * you need to do so manually before calling.
1295 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1298 spin_lock(&rq1->lock);
1301 spin_lock(&rq1->lock);
1302 spin_lock(&rq2->lock);
1304 spin_lock(&rq2->lock);
1305 spin_lock(&rq1->lock);
1311 * double_rq_unlock - safely unlock two runqueues
1313 * Note this does not restore interrupts like task_rq_unlock,
1314 * you need to do so manually after calling.
1316 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1318 spin_unlock(&rq1->lock);
1320 spin_unlock(&rq2->lock);
1333 * find_idlest_cpu - find the least busy runqueue.
1335 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1336 struct sched_domain *sd)
1338 unsigned long load, min_load, this_load;
1343 min_load = ULONG_MAX;
1345 cpus_and(mask, sd->span, cpu_online_map);
1346 cpus_and(mask, mask, p->cpus_allowed);
1348 for_each_cpu_mask(i, mask) {
1349 load = target_load(i);
1351 if (load < min_load) {
1355 /* break out early on an idle CPU: */
1361 /* add +1 to account for the new task */
1362 this_load = source_load(this_cpu) + SCHED_LOAD_SCALE;
1365 * Would with the addition of the new task to the
1366 * current CPU there be an imbalance between this
1367 * CPU and the idlest CPU?
1369 * Use half of the balancing threshold - new-context is
1370 * a good opportunity to balance.
1372 if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1379 * wake_up_forked_thread - wake up a freshly forked thread.
1381 * This function will do some initial scheduler statistics housekeeping
1382 * that must be done for every newly created context, and it also does
1383 * runqueue balancing.
1385 void fastcall wake_up_forked_thread(task_t * p)
1387 unsigned long flags;
1388 int this_cpu = get_cpu(), cpu;
1389 struct sched_domain *tmp, *sd = NULL;
1390 runqueue_t *this_rq = cpu_rq(this_cpu), *rq;
1393 * Find the largest domain that this CPU is part of that
1394 * is willing to balance on clone:
1396 for_each_domain(this_cpu, tmp)
1397 if (tmp->flags & SD_BALANCE_CLONE)
1400 cpu = find_idlest_cpu(p, this_cpu, sd);
1404 local_irq_save(flags);
1407 double_rq_lock(this_rq, rq);
1409 BUG_ON(p->state != TASK_RUNNING);
1412 * We did find_idlest_cpu() unlocked, so in theory
1413 * the mask could have changed - just dont migrate
1416 if (unlikely(!cpu_isset(cpu, p->cpus_allowed))) {
1418 double_rq_unlock(this_rq, rq);
1422 * We decrease the sleep average of forking parents
1423 * and children as well, to keep max-interactive tasks
1424 * from forking tasks that are max-interactive.
1426 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1427 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1429 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1430 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1432 p->interactive_credit = 0;
1434 p->prio = effective_prio(p);
1435 set_task_cpu(p, cpu);
1437 if (cpu == this_cpu) {
1438 if (unlikely(!current->array))
1439 __activate_task(p, rq);
1441 p->prio = current->prio;
1442 list_add_tail(&p->run_list, ¤t->run_list);
1443 p->array = current->array;
1444 p->array->nr_active++;
1449 /* Not the local CPU - must adjust timestamp */
1450 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1451 + rq->timestamp_last_tick;
1452 __activate_task(p, rq);
1453 if (TASK_PREEMPTS_CURR(p, rq))
1454 resched_task(rq->curr);
1457 double_rq_unlock(this_rq, rq);
1458 local_irq_restore(flags);
1463 * If dest_cpu is allowed for this process, migrate the task to it.
1464 * This is accomplished by forcing the cpu_allowed mask to only
1465 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1466 * the cpu_allowed mask is restored.
1468 static void sched_migrate_task(task_t *p, int dest_cpu)
1470 migration_req_t req;
1472 unsigned long flags;
1474 rq = task_rq_lock(p, &flags);
1475 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1476 || unlikely(cpu_is_offline(dest_cpu)))
1479 /* force the process onto the specified CPU */
1480 if (migrate_task(p, dest_cpu, &req)) {
1481 /* Need to wait for migration thread (might exit: take ref). */
1482 struct task_struct *mt = rq->migration_thread;
1483 get_task_struct(mt);
1484 task_rq_unlock(rq, &flags);
1485 wake_up_process(mt);
1486 put_task_struct(mt);
1487 wait_for_completion(&req.done);
1491 task_rq_unlock(rq, &flags);
1495 * sched_balance_exec(): find the highest-level, exec-balance-capable
1496 * domain and try to migrate the task to the least loaded CPU.
1498 * execve() is a valuable balancing opportunity, because at this point
1499 * the task has the smallest effective memory and cache footprint.
1501 void sched_balance_exec(void)
1503 struct sched_domain *tmp, *sd = NULL;
1504 int new_cpu, this_cpu = get_cpu();
1506 /* Prefer the current CPU if there's only this task running */
1507 if (this_rq()->nr_running <= 1)
1510 for_each_domain(this_cpu, tmp)
1511 if (tmp->flags & SD_BALANCE_EXEC)
1515 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1516 if (new_cpu != this_cpu) {
1518 sched_migrate_task(current, new_cpu);
1527 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1529 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1531 if (unlikely(!spin_trylock(&busiest->lock))) {
1532 if (busiest < this_rq) {
1533 spin_unlock(&this_rq->lock);
1534 spin_lock(&busiest->lock);
1535 spin_lock(&this_rq->lock);
1537 spin_lock(&busiest->lock);
1542 * pull_task - move a task from a remote runqueue to the local runqueue.
1543 * Both runqueues must be locked.
1546 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1547 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1549 dequeue_task(p, src_array);
1550 src_rq->nr_running--;
1551 rq_load_dec(src_rq,p);
1553 set_task_cpu(p, this_cpu);
1554 this_rq->nr_running++;
1555 rq_load_inc(this_rq,p);
1556 enqueue_task(p, this_array);
1558 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1559 + this_rq->timestamp_last_tick;
1561 * Note that idle threads have a prio of MAX_PRIO, for this test
1562 * to be always true for them.
1564 if (TASK_PREEMPTS_CURR(p, this_rq))
1565 resched_task(this_rq->curr);
1569 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1572 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1573 struct sched_domain *sd, enum idle_type idle)
1576 * We do not migrate tasks that are:
1577 * 1) running (obviously), or
1578 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1579 * 3) are cache-hot on their current CPU.
1581 if (task_running(rq, p))
1583 if (!cpu_isset(this_cpu, p->cpus_allowed))
1586 /* Aggressive migration if we've failed balancing */
1587 if (idle == NEWLY_IDLE ||
1588 sd->nr_balance_failed < sd->cache_nice_tries) {
1589 if (task_hot(p, rq->timestamp_last_tick, sd))
1596 #ifdef CONFIG_CKRM_CPU_SCHEDULE
1598 struct ckrm_cpu_class *find_unbalanced_class(int busiest_cpu, int this_cpu, unsigned long *cls_imbalance)
1600 struct ckrm_cpu_class *most_unbalanced_class = NULL;
1601 struct ckrm_cpu_class *clsptr;
1602 int max_unbalance = 0;
1604 list_for_each_entry(clsptr,&active_cpu_classes,links) {
1605 struct ckrm_local_runqueue *this_lrq = get_ckrm_local_runqueue(clsptr,this_cpu);
1606 struct ckrm_local_runqueue *busiest_lrq = get_ckrm_local_runqueue(clsptr,busiest_cpu);
1607 int unbalance_degree;
1609 unbalance_degree = (local_queue_nr_running(busiest_lrq) - local_queue_nr_running(this_lrq)) * cpu_class_weight(clsptr);
1610 if (unbalance_degree >= *cls_imbalance)
1611 continue; // already looked at this class
1613 if (unbalance_degree > max_unbalance) {
1614 max_unbalance = unbalance_degree;
1615 most_unbalanced_class = clsptr;
1618 *cls_imbalance = max_unbalance;
1619 return most_unbalanced_class;
1624 * find_busiest_queue - find the busiest runqueue among the cpus in cpumask.
1626 static int find_busiest_cpu(runqueue_t *this_rq, int this_cpu, int idle,
1629 int cpu_load, load, max_load, i, busiest_cpu;
1630 runqueue_t *busiest, *rq_src;
1633 /*Hubertus ... the concept of nr_running is replace with cpu_load */
1634 cpu_load = this_rq->ckrm_cpu_load;
1640 for_each_online_cpu(i) {
1642 load = rq_src->ckrm_cpu_load;
1644 if ((load > max_load) && (rq_src != this_rq)) {
1651 if (likely(!busiest))
1654 *imbalance = max_load - cpu_load;
1656 /* It needs an at least ~25% imbalance to trigger balancing. */
1657 if (!idle && ((*imbalance)*4 < max_load)) {
1662 double_lock_balance(this_rq, busiest);
1664 * Make sure nothing changed since we checked the
1667 if (busiest->ckrm_cpu_load <= cpu_load) {
1668 spin_unlock(&busiest->lock);
1672 return (busiest ? busiest_cpu : -1);
1675 static int load_balance(int this_cpu, runqueue_t *this_rq,
1676 struct sched_domain *sd, enum idle_type idle)
1680 runqueue_t *busiest;
1681 prio_array_t *array;
1682 struct list_head *head, *curr;
1684 struct ckrm_local_runqueue * busiest_local_queue;
1685 struct ckrm_cpu_class *clsptr;
1687 unsigned long cls_imbalance; // so we can retry other classes
1689 // need to update global CVT based on local accumulated CVTs
1690 read_lock(&class_list_lock);
1691 busiest_cpu = find_busiest_cpu(this_rq, this_cpu, idle, &imbalance);
1692 if (busiest_cpu == -1)
1695 busiest = cpu_rq(busiest_cpu);
1698 * We only want to steal a number of tasks equal to 1/2 the imbalance,
1699 * otherwise we'll just shift the imbalance to the new queue:
1703 /* now find class on that runqueue with largest inbalance */
1704 cls_imbalance = 0xFFFFFFFF;
1707 clsptr = find_unbalanced_class(busiest_cpu, this_cpu, &cls_imbalance);
1711 busiest_local_queue = get_ckrm_local_runqueue(clsptr,busiest_cpu);
1712 weight = cpu_class_weight(clsptr);
1715 * We first consider expired tasks. Those will likely not be
1716 * executed in the near future, and they are most likely to
1717 * be cache-cold, thus switching CPUs has the least effect
1720 if (busiest_local_queue->expired->nr_active)
1721 array = busiest_local_queue->expired;
1723 array = busiest_local_queue->active;
1726 /* Start searching at priority 0: */
1730 idx = sched_find_first_bit(array->bitmap);
1732 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1733 if (idx >= MAX_PRIO) {
1734 if (array == busiest_local_queue->expired && busiest_local_queue->active->nr_active) {
1735 array = busiest_local_queue->active;
1738 goto retry_other_class;
1741 head = array->queue + idx;
1744 tmp = list_entry(curr, task_t, run_list);
1748 if (!can_migrate_task(tmp, busiest, this_cpu, sd,idle)) {
1754 pull_task(busiest, array, tmp, this_rq, rq_active(tmp,this_rq),this_cpu);
1756 * tmp BUG FIX: hzheng
1757 * load balancing can make the busiest local queue empty
1758 * thus it should be removed from bpt
1760 if (! local_queue_nr_running(busiest_local_queue)) {
1761 classqueue_dequeue(busiest_local_queue->classqueue,&busiest_local_queue->classqueue_linkobj);
1762 cpu_demand_event(get_rq_local_stat(busiest_local_queue,busiest_cpu),CPU_DEMAND_DEQUEUE,0);
1765 imbalance -= weight;
1766 if (!idle && (imbalance>0)) {
1773 spin_unlock(&busiest->lock);
1775 read_unlock(&class_list_lock);
1780 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
1783 #else /* CONFIG_CKRM_CPU_SCHEDULE */
1785 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1786 * as part of a balancing operation within "domain". Returns the number of
1789 * Called with both runqueues locked.
1791 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1792 unsigned long max_nr_move, struct sched_domain *sd,
1793 enum idle_type idle)
1795 prio_array_t *array, *dst_array;
1796 struct list_head *head, *curr;
1797 int idx, pulled = 0;
1800 if (max_nr_move <= 0 || busiest->nr_running <= 1)
1804 * We first consider expired tasks. Those will likely not be
1805 * executed in the near future, and they are most likely to
1806 * be cache-cold, thus switching CPUs has the least effect
1809 if (busiest->expired->nr_active) {
1810 array = busiest->expired;
1811 dst_array = this_rq->expired;
1813 array = busiest->active;
1814 dst_array = this_rq->active;
1818 /* Start searching at priority 0: */
1822 idx = sched_find_first_bit(array->bitmap);
1824 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1825 if (idx >= MAX_PRIO) {
1826 if (array == busiest->expired && busiest->active->nr_active) {
1827 array = busiest->active;
1828 dst_array = this_rq->active;
1834 head = array->queue + idx;
1837 tmp = list_entry(curr, task_t, run_list);
1841 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
1847 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
1850 /* We only want to steal up to the prescribed number of tasks. */
1851 if (pulled < max_nr_move) {
1862 * find_busiest_group finds and returns the busiest CPU group within the
1863 * domain. It calculates and returns the number of tasks which should be
1864 * moved to restore balance via the imbalance parameter.
1866 static struct sched_group *
1867 find_busiest_group(struct sched_domain *sd, int this_cpu,
1868 unsigned long *imbalance, enum idle_type idle)
1870 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
1871 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
1873 max_load = this_load = total_load = total_pwr = 0;
1881 local_group = cpu_isset(this_cpu, group->cpumask);
1883 /* Tally up the load of all CPUs in the group */
1885 cpus_and(tmp, group->cpumask, cpu_online_map);
1886 if (unlikely(cpus_empty(tmp)))
1889 for_each_cpu_mask(i, tmp) {
1890 /* Bias balancing toward cpus of our domain */
1892 load = target_load(i);
1894 load = source_load(i);
1903 total_load += avg_load;
1904 total_pwr += group->cpu_power;
1906 /* Adjust by relative CPU power of the group */
1907 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1910 this_load = avg_load;
1913 } else if (avg_load > max_load) {
1914 max_load = avg_load;
1918 group = group->next;
1919 } while (group != sd->groups);
1921 if (!busiest || this_load >= max_load)
1924 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
1926 if (this_load >= avg_load ||
1927 100*max_load <= sd->imbalance_pct*this_load)
1931 * We're trying to get all the cpus to the average_load, so we don't
1932 * want to push ourselves above the average load, nor do we wish to
1933 * reduce the max loaded cpu below the average load, as either of these
1934 * actions would just result in more rebalancing later, and ping-pong
1935 * tasks around. Thus we look for the minimum possible imbalance.
1936 * Negative imbalances (*we* are more loaded than anyone else) will
1937 * be counted as no imbalance for these purposes -- we can't fix that
1938 * by pulling tasks to us. Be careful of negative numbers as they'll
1939 * appear as very large values with unsigned longs.
1941 *imbalance = min(max_load - avg_load, avg_load - this_load);
1943 /* How much load to actually move to equalise the imbalance */
1944 *imbalance = (*imbalance * min(busiest->cpu_power, this->cpu_power))
1947 if (*imbalance < SCHED_LOAD_SCALE - 1) {
1948 unsigned long pwr_now = 0, pwr_move = 0;
1951 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
1957 * OK, we don't have enough imbalance to justify moving tasks,
1958 * however we may be able to increase total CPU power used by
1962 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
1963 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
1964 pwr_now /= SCHED_LOAD_SCALE;
1966 /* Amount of load we'd subtract */
1967 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
1969 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
1972 /* Amount of load we'd add */
1973 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
1976 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
1977 pwr_move /= SCHED_LOAD_SCALE;
1979 /* Move if we gain another 8th of a CPU worth of throughput */
1980 if (pwr_move < pwr_now + SCHED_LOAD_SCALE / 8)
1987 /* Get rid of the scaling factor, rounding down as we divide */
1988 *imbalance = (*imbalance + 1) / SCHED_LOAD_SCALE;
1993 if (busiest && (idle == NEWLY_IDLE ||
1994 (idle == IDLE && max_load > SCHED_LOAD_SCALE)) ) {
2004 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2006 static runqueue_t *find_busiest_queue(struct sched_group *group)
2009 unsigned long load, max_load = 0;
2010 runqueue_t *busiest = NULL;
2013 cpus_and(tmp, group->cpumask, cpu_online_map);
2014 for_each_cpu_mask(i, tmp) {
2015 load = source_load(i);
2017 if (load > max_load) {
2019 busiest = cpu_rq(i);
2027 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2028 * tasks if there is an imbalance.
2030 * Called with this_rq unlocked.
2032 static int load_balance(int this_cpu, runqueue_t *this_rq,
2033 struct sched_domain *sd, enum idle_type idle)
2035 struct sched_group *group;
2036 runqueue_t *busiest;
2037 unsigned long imbalance;
2040 spin_lock(&this_rq->lock);
2042 group = find_busiest_group(sd, this_cpu, &imbalance, idle);
2046 busiest = find_busiest_queue(group);
2050 * This should be "impossible", but since load
2051 * balancing is inherently racy and statistical,
2052 * it could happen in theory.
2054 if (unlikely(busiest == this_rq)) {
2060 if (busiest->nr_running > 1) {
2062 * Attempt to move tasks. If find_busiest_group has found
2063 * an imbalance but busiest->nr_running <= 1, the group is
2064 * still unbalanced. nr_moved simply stays zero, so it is
2065 * correctly treated as an imbalance.
2067 double_lock_balance(this_rq, busiest);
2068 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2069 imbalance, sd, idle);
2070 spin_unlock(&busiest->lock);
2072 spin_unlock(&this_rq->lock);
2075 sd->nr_balance_failed++;
2077 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2080 spin_lock(&busiest->lock);
2081 if (!busiest->active_balance) {
2082 busiest->active_balance = 1;
2083 busiest->push_cpu = this_cpu;
2086 spin_unlock(&busiest->lock);
2088 wake_up_process(busiest->migration_thread);
2091 * We've kicked active balancing, reset the failure
2094 sd->nr_balance_failed = sd->cache_nice_tries;
2097 sd->nr_balance_failed = 0;
2099 /* We were unbalanced, so reset the balancing interval */
2100 sd->balance_interval = sd->min_interval;
2105 spin_unlock(&this_rq->lock);
2107 /* tune up the balancing interval */
2108 if (sd->balance_interval < sd->max_interval)
2109 sd->balance_interval *= 2;
2115 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2116 * tasks if there is an imbalance.
2118 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2119 * this_rq is locked.
2121 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2122 struct sched_domain *sd)
2124 struct sched_group *group;
2125 runqueue_t *busiest = NULL;
2126 unsigned long imbalance;
2129 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
2133 busiest = find_busiest_queue(group);
2134 if (!busiest || busiest == this_rq)
2137 /* Attempt to move tasks */
2138 double_lock_balance(this_rq, busiest);
2140 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2141 imbalance, sd, NEWLY_IDLE);
2143 spin_unlock(&busiest->lock);
2150 * idle_balance is called by schedule() if this_cpu is about to become
2151 * idle. Attempts to pull tasks from other CPUs.
2153 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
2155 struct sched_domain *sd;
2157 for_each_domain(this_cpu, sd) {
2158 if (sd->flags & SD_BALANCE_NEWIDLE) {
2159 if (load_balance_newidle(this_cpu, this_rq, sd)) {
2160 /* We've pulled tasks over so stop searching */
2168 * active_load_balance is run by migration threads. It pushes a running
2169 * task off the cpu. It can be required to correctly have at least 1 task
2170 * running on each physical CPU where possible, and not have a physical /
2171 * logical imbalance.
2173 * Called with busiest locked.
2175 static void active_load_balance(runqueue_t *busiest, int busiest_cpu)
2177 struct sched_domain *sd;
2178 struct sched_group *group, *busy_group;
2181 if (busiest->nr_running <= 1)
2184 for_each_domain(busiest_cpu, sd)
2185 if (cpu_isset(busiest->push_cpu, sd->span))
2193 while (!cpu_isset(busiest_cpu, group->cpumask))
2194 group = group->next;
2203 if (group == busy_group)
2206 cpus_and(tmp, group->cpumask, cpu_online_map);
2207 if (!cpus_weight(tmp))
2210 for_each_cpu_mask(i, tmp) {
2216 rq = cpu_rq(push_cpu);
2219 * This condition is "impossible", but since load
2220 * balancing is inherently a bit racy and statistical,
2221 * it can trigger.. Reported by Bjorn Helgaas on a
2224 if (unlikely(busiest == rq))
2226 double_lock_balance(busiest, rq);
2227 move_tasks(rq, push_cpu, busiest, 1, sd, IDLE);
2228 spin_unlock(&rq->lock);
2230 group = group->next;
2231 } while (group != sd->groups);
2233 #endif /* CONFIG_CKRM_CPU_SCHEDULE*/
2236 * rebalance_tick will get called every timer tick, on every CPU.
2238 * It checks each scheduling domain to see if it is due to be balanced,
2239 * and initiates a balancing operation if so.
2241 * Balancing parameters are set up in arch_init_sched_domains.
2244 /* Don't have all balancing operations going off at once */
2245 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2247 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2248 enum idle_type idle)
2250 unsigned long old_load, this_load;
2251 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2252 struct sched_domain *sd;
2254 ckrm_rebalance_tick(j,this_cpu);
2256 /* Update our load */
2257 old_load = this_rq->cpu_load;
2258 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
2260 * Round up the averaging division if load is increasing. This
2261 * prevents us from getting stuck on 9 if the load is 10, for
2264 if (this_load > old_load)
2266 this_rq->cpu_load = (old_load + this_load) / 2;
2268 for_each_domain(this_cpu, sd) {
2269 unsigned long interval = sd->balance_interval;
2272 interval *= sd->busy_factor;
2274 /* scale ms to jiffies */
2275 interval = msecs_to_jiffies(interval);
2276 if (unlikely(!interval))
2279 if (j - sd->last_balance >= interval) {
2280 if (load_balance(this_cpu, this_rq, sd, idle)) {
2281 /* We've pulled tasks over so no longer idle */
2284 sd->last_balance += interval;
2290 * on UP we do not need to balance between CPUs:
2292 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2294 ckrm_rebalance_tick(jiffies,cpu);
2297 static inline void idle_balance(int cpu, runqueue_t *rq)
2302 static inline int wake_priority_sleeper(runqueue_t *rq)
2304 #ifdef CONFIG_SCHED_SMT
2306 * If an SMT sibling task has been put to sleep for priority
2307 * reasons reschedule the idle task to see if it can now run.
2309 if (rq->nr_running) {
2310 resched_task(rq->idle);
2317 DEFINE_PER_CPU(struct kernel_stat, kstat) = { { 0 } };
2319 EXPORT_PER_CPU_SYMBOL(kstat);
2322 * We place interactive tasks back into the active array, if possible.
2324 * To guarantee that this does not starve expired tasks we ignore the
2325 * interactivity of a task if the first expired task had to wait more
2326 * than a 'reasonable' amount of time. This deadline timeout is
2327 * load-dependent, as the frequency of array switched decreases with
2328 * increasing number of running tasks. We also ignore the interactivity
2329 * if a better static_prio task has expired:
2332 #ifndef CONFIG_CKRM_CPU_SCHEDULE
2333 #define EXPIRED_STARVING(rq) \
2334 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2335 (jiffies - (rq)->expired_timestamp >= \
2336 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2337 ((rq)->curr->static_prio > (rq)->best_expired_prio))
2339 #define EXPIRED_STARVING(rq) \
2340 (STARVATION_LIMIT && ((rq)->expired_timestamp && \
2341 (jiffies - (rq)->expired_timestamp >= \
2342 STARVATION_LIMIT * (local_queue_nr_running(rq)) + 1)))
2346 * This function gets called by the timer code, with HZ frequency.
2347 * We call it with interrupts disabled.
2349 * It also gets called by the fork code, when changing the parent's
2352 void scheduler_tick(int user_ticks, int sys_ticks)
2354 int cpu = smp_processor_id();
2355 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2356 runqueue_t *rq = this_rq();
2357 task_t *p = current;
2359 rq->timestamp_last_tick = sched_clock();
2361 if (rcu_pending(cpu))
2362 rcu_check_callbacks(cpu, user_ticks);
2364 /* note: this timer irq context must be accounted for as well */
2365 if (hardirq_count() - HARDIRQ_OFFSET) {
2366 cpustat->irq += sys_ticks;
2368 } else if (softirq_count()) {
2369 cpustat->softirq += sys_ticks;
2373 if (p == rq->idle) {
2374 if (atomic_read(&rq->nr_iowait) > 0)
2375 cpustat->iowait += sys_ticks;
2377 cpustat->idle += sys_ticks;
2378 if (wake_priority_sleeper(rq))
2380 rebalance_tick(cpu, rq, IDLE);
2383 if (TASK_NICE(p) > 0)
2384 cpustat->nice += user_ticks;
2386 cpustat->user += user_ticks;
2387 cpustat->system += sys_ticks;
2389 /* Task might have expired already, but not scheduled off yet */
2390 if (p->array != rq_active(p,rq)) {
2391 set_tsk_need_resched(p);
2394 spin_lock(&rq->lock);
2396 * The task was running during this tick - update the
2397 * time slice counter. Note: we do not update a thread's
2398 * priority until it either goes to sleep or uses up its
2399 * timeslice. This makes it possible for interactive tasks
2400 * to use up their timeslices at their highest priority levels.
2402 if (unlikely(rt_task(p))) {
2404 * RR tasks need a special form of timeslice management.
2405 * FIFO tasks have no timeslices.
2407 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2408 p->time_slice = task_timeslice(p);
2409 p->first_time_slice = 0;
2410 set_tsk_need_resched(p);
2412 /* put it at the end of the queue: */
2413 dequeue_task(p, rq_active(p,rq));
2414 enqueue_task(p, rq_active(p,rq));
2418 if (!--p->time_slice) {
2419 #ifdef CONFIG_CKRM_CPU_SCHEDULE
2420 /* Hubertus ... we can abstract this out */
2421 struct ckrm_local_runqueue* rq = get_task_class_queue(p);
2423 dequeue_task(p, rq->active);
2424 set_tsk_need_resched(p);
2425 p->prio = effective_prio(p);
2426 p->time_slice = task_timeslice(p);
2427 p->first_time_slice = 0;
2429 if (!rq->expired_timestamp)
2430 rq->expired_timestamp = jiffies;
2431 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2432 enqueue_task(p, rq->expired);
2433 if (p->static_prio < this_rq()->best_expired_prio)
2434 this_rq()->best_expired_prio = p->static_prio;
2436 enqueue_task(p, rq->active);
2439 * Prevent a too long timeslice allowing a task to monopolize
2440 * the CPU. We do this by splitting up the timeslice into
2443 * Note: this does not mean the task's timeslices expire or
2444 * get lost in any way, they just might be preempted by
2445 * another task of equal priority. (one with higher
2446 * priority would have preempted this task already.) We
2447 * requeue this task to the end of the list on this priority
2448 * level, which is in essence a round-robin of tasks with
2451 * This only applies to tasks in the interactive
2452 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2454 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2455 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2456 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2457 (p->array == rq_active(p,rq))) {
2459 dequeue_task(p, rq_active(p,rq));
2460 set_tsk_need_resched(p);
2461 p->prio = effective_prio(p);
2462 enqueue_task(p, rq_active(p,rq));
2466 spin_unlock(&rq->lock);
2468 rebalance_tick(cpu, rq, NOT_IDLE);
2471 #ifdef CONFIG_SCHED_SMT
2472 static inline void wake_sleeping_dependent(int cpu, runqueue_t *rq)
2475 struct sched_domain *sd = rq->sd;
2476 cpumask_t sibling_map;
2478 if (!(sd->flags & SD_SHARE_CPUPOWER))
2481 cpus_and(sibling_map, sd->span, cpu_online_map);
2482 for_each_cpu_mask(i, sibling_map) {
2491 * If an SMT sibling task is sleeping due to priority
2492 * reasons wake it up now.
2494 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
2495 resched_task(smt_rq->idle);
2499 static inline int dependent_sleeper(int cpu, runqueue_t *rq, task_t *p)
2501 struct sched_domain *sd = rq->sd;
2502 cpumask_t sibling_map;
2505 if (!(sd->flags & SD_SHARE_CPUPOWER))
2508 cpus_and(sibling_map, sd->span, cpu_online_map);
2509 for_each_cpu_mask(i, sibling_map) {
2517 smt_curr = smt_rq->curr;
2520 * If a user task with lower static priority than the
2521 * running task on the SMT sibling is trying to schedule,
2522 * delay it till there is proportionately less timeslice
2523 * left of the sibling task to prevent a lower priority
2524 * task from using an unfair proportion of the
2525 * physical cpu's resources. -ck
2527 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
2528 task_timeslice(p) || rt_task(smt_curr)) &&
2529 p->mm && smt_curr->mm && !rt_task(p))
2533 * Reschedule a lower priority task on the SMT sibling,
2534 * or wake it up if it has been put to sleep for priority
2537 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
2538 task_timeslice(smt_curr) || rt_task(p)) &&
2539 smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
2540 (smt_curr == smt_rq->idle && smt_rq->nr_running))
2541 resched_task(smt_curr);
2546 static inline void wake_sleeping_dependent(int cpu, runqueue_t *rq)
2550 static inline int dependent_sleeper(int cpu, runqueue_t *rq, task_t *p)
2557 * schedule() is the main scheduler function.
2559 asmlinkage void __sched schedule(void)
2562 task_t *prev, *next;
2564 prio_array_t *array;
2565 unsigned long long now;
2566 unsigned long run_time;
2570 * Test if we are atomic. Since do_exit() needs to call into
2571 * schedule() atomically, we ignore that path for now.
2572 * Otherwise, whine if we are scheduling when we should not be.
2574 if (likely(!(current->state & (TASK_DEAD | TASK_ZOMBIE)))) {
2575 if (unlikely(in_atomic())) {
2576 printk(KERN_ERR "bad: scheduling while atomic!\n");
2586 release_kernel_lock(prev);
2587 now = sched_clock();
2588 if (likely(now - prev->timestamp < NS_MAX_SLEEP_AVG))
2589 run_time = now - prev->timestamp;
2591 run_time = NS_MAX_SLEEP_AVG;
2594 * Tasks with interactive credits get charged less run_time
2595 * at high sleep_avg to delay them losing their interactive
2598 if (HIGH_CREDIT(prev))
2599 run_time /= (CURRENT_BONUS(prev) ? : 1);
2601 spin_lock_irq(&rq->lock);
2604 * if entering off of a kernel preemption go straight
2605 * to picking the next task.
2607 switch_count = &prev->nivcsw;
2608 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2609 switch_count = &prev->nvcsw;
2610 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2611 unlikely(signal_pending(prev))))
2612 prev->state = TASK_RUNNING;
2614 deactivate_task(prev, rq);
2617 cpu = smp_processor_id();
2618 if (unlikely(!rq->nr_running)) {
2619 idle_balance(cpu, rq);
2620 if (!rq->nr_running) {
2622 rq->expired_timestamp = 0;
2623 wake_sleeping_dependent(cpu, rq);
2628 next = rq_get_next_task(rq);
2629 if (next == rq->idle)
2632 if (dependent_sleeper(cpu, rq, next)) {
2637 if (!rt_task(next) && next->activated > 0) {
2638 unsigned long long delta = now - next->timestamp;
2640 if (next->activated == 1)
2641 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
2643 array = next->array;
2644 dequeue_task(next, array);
2645 recalc_task_prio(next, next->timestamp + delta);
2646 enqueue_task(next, array);
2648 next->activated = 0;
2651 clear_tsk_need_resched(prev);
2652 RCU_qsctr(task_cpu(prev))++;
2654 #ifdef CONFIG_CKRM_CPU_SCHEDULE
2655 if (prev != rq->idle) {
2656 unsigned long long run = now - prev->timestamp;
2657 cpu_demand_event(get_task_local_stat(prev),CPU_DEMAND_DESCHEDULE,run);
2658 update_local_cvt(prev, run);
2662 prev->sleep_avg -= run_time;
2663 if ((long)prev->sleep_avg <= 0) {
2664 prev->sleep_avg = 0;
2665 if (!(HIGH_CREDIT(prev) || LOW_CREDIT(prev)))
2666 prev->interactive_credit--;
2668 add_delay_ts(prev,runcpu_total,prev->timestamp,now);
2669 prev->timestamp = now;
2671 if (likely(prev != next)) {
2672 add_delay_ts(next,waitcpu_total,next->timestamp,now);
2673 inc_delay(next,runs);
2674 next->timestamp = now;
2679 prepare_arch_switch(rq, next);
2680 prev = context_switch(rq, prev, next);
2683 finish_task_switch(prev);
2685 spin_unlock_irq(&rq->lock);
2687 reacquire_kernel_lock(current);
2688 preempt_enable_no_resched();
2689 if (test_thread_flag(TIF_NEED_RESCHED))
2693 EXPORT_SYMBOL(schedule);
2695 #ifdef CONFIG_PREEMPT
2697 * this is is the entry point to schedule() from in-kernel preemption
2698 * off of preempt_enable. Kernel preemptions off return from interrupt
2699 * occur there and call schedule directly.
2701 asmlinkage void __sched preempt_schedule(void)
2703 struct thread_info *ti = current_thread_info();
2706 * If there is a non-zero preempt_count or interrupts are disabled,
2707 * we do not want to preempt the current task. Just return..
2709 if (unlikely(ti->preempt_count || irqs_disabled()))
2713 ti->preempt_count = PREEMPT_ACTIVE;
2715 ti->preempt_count = 0;
2717 /* we could miss a preemption opportunity between schedule and now */
2719 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2723 EXPORT_SYMBOL(preempt_schedule);
2724 #endif /* CONFIG_PREEMPT */
2726 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
2728 task_t *p = curr->task;
2729 return try_to_wake_up(p, mode, sync);
2732 EXPORT_SYMBOL(default_wake_function);
2735 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
2736 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
2737 * number) then we wake all the non-exclusive tasks and one exclusive task.
2739 * There are circumstances in which we can try to wake a task which has already
2740 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
2741 * zero in this (rare) case, and we handle it by continuing to scan the queue.
2743 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
2744 int nr_exclusive, int sync, void *key)
2746 struct list_head *tmp, *next;
2748 list_for_each_safe(tmp, next, &q->task_list) {
2751 curr = list_entry(tmp, wait_queue_t, task_list);
2752 flags = curr->flags;
2753 if (curr->func(curr, mode, sync, key) &&
2754 (flags & WQ_FLAG_EXCLUSIVE) &&
2761 * __wake_up - wake up threads blocked on a waitqueue.
2763 * @mode: which threads
2764 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2766 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
2767 int nr_exclusive, void *key)
2769 unsigned long flags;
2771 spin_lock_irqsave(&q->lock, flags);
2772 __wake_up_common(q, mode, nr_exclusive, 0, key);
2773 spin_unlock_irqrestore(&q->lock, flags);
2776 EXPORT_SYMBOL(__wake_up);
2779 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
2781 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
2783 __wake_up_common(q, mode, 1, 0, NULL);
2787 * __wake_up - sync- wake up threads blocked on a waitqueue.
2789 * @mode: which threads
2790 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2792 * The sync wakeup differs that the waker knows that it will schedule
2793 * away soon, so while the target thread will be woken up, it will not
2794 * be migrated to another CPU - ie. the two threads are 'synchronized'
2795 * with each other. This can prevent needless bouncing between CPUs.
2797 * On UP it can prevent extra preemption.
2799 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
2801 unsigned long flags;
2807 if (unlikely(!nr_exclusive))
2810 spin_lock_irqsave(&q->lock, flags);
2811 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
2812 spin_unlock_irqrestore(&q->lock, flags);
2814 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
2816 void fastcall complete(struct completion *x)
2818 unsigned long flags;
2820 spin_lock_irqsave(&x->wait.lock, flags);
2822 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2824 spin_unlock_irqrestore(&x->wait.lock, flags);
2826 EXPORT_SYMBOL(complete);
2828 void fastcall complete_all(struct completion *x)
2830 unsigned long flags;
2832 spin_lock_irqsave(&x->wait.lock, flags);
2833 x->done += UINT_MAX/2;
2834 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2836 spin_unlock_irqrestore(&x->wait.lock, flags);
2838 EXPORT_SYMBOL(complete_all);
2840 void fastcall __sched wait_for_completion(struct completion *x)
2843 spin_lock_irq(&x->wait.lock);
2845 DECLARE_WAITQUEUE(wait, current);
2847 wait.flags |= WQ_FLAG_EXCLUSIVE;
2848 __add_wait_queue_tail(&x->wait, &wait);
2850 __set_current_state(TASK_UNINTERRUPTIBLE);
2851 spin_unlock_irq(&x->wait.lock);
2853 spin_lock_irq(&x->wait.lock);
2855 __remove_wait_queue(&x->wait, &wait);
2858 spin_unlock_irq(&x->wait.lock);
2860 EXPORT_SYMBOL(wait_for_completion);
2862 #define SLEEP_ON_VAR \
2863 unsigned long flags; \
2864 wait_queue_t wait; \
2865 init_waitqueue_entry(&wait, current);
2867 #define SLEEP_ON_HEAD \
2868 spin_lock_irqsave(&q->lock,flags); \
2869 __add_wait_queue(q, &wait); \
2870 spin_unlock(&q->lock);
2872 #define SLEEP_ON_TAIL \
2873 spin_lock_irq(&q->lock); \
2874 __remove_wait_queue(q, &wait); \
2875 spin_unlock_irqrestore(&q->lock, flags);
2877 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
2881 current->state = TASK_INTERRUPTIBLE;
2888 EXPORT_SYMBOL(interruptible_sleep_on);
2890 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
2894 current->state = TASK_INTERRUPTIBLE;
2897 timeout = schedule_timeout(timeout);
2903 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
2905 void fastcall __sched sleep_on(wait_queue_head_t *q)
2909 current->state = TASK_UNINTERRUPTIBLE;
2916 EXPORT_SYMBOL(sleep_on);
2918 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
2922 current->state = TASK_UNINTERRUPTIBLE;
2925 timeout = schedule_timeout(timeout);
2931 EXPORT_SYMBOL(sleep_on_timeout);
2933 void set_user_nice(task_t *p, long nice)
2935 unsigned long flags;
2936 prio_array_t *array;
2938 int old_prio, new_prio, delta;
2940 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
2943 * We have to be careful, if called from sys_setpriority(),
2944 * the task might be in the middle of scheduling on another CPU.
2946 rq = task_rq_lock(p, &flags);
2948 * The RT priorities are set via setscheduler(), but we still
2949 * allow the 'normal' nice value to be set - but as expected
2950 * it wont have any effect on scheduling until the task is
2954 p->static_prio = NICE_TO_PRIO(nice);
2959 dequeue_task(p, array);
2962 new_prio = NICE_TO_PRIO(nice);
2963 delta = new_prio - old_prio;
2964 p->static_prio = NICE_TO_PRIO(nice);
2968 enqueue_task(p, array);
2970 * If the task increased its priority or is running and
2971 * lowered its priority, then reschedule its CPU:
2973 if (delta < 0 || (delta > 0 && task_running(rq, p)))
2974 resched_task(rq->curr);
2977 task_rq_unlock(rq, &flags);
2980 EXPORT_SYMBOL(set_user_nice);
2982 #ifdef __ARCH_WANT_SYS_NICE
2985 * sys_nice - change the priority of the current process.
2986 * @increment: priority increment
2988 * sys_setpriority is a more generic, but much slower function that
2989 * does similar things.
2991 asmlinkage long sys_nice(int increment)
2997 * Setpriority might change our priority at the same moment.
2998 * We don't have to worry. Conceptually one call occurs first
2999 * and we have a single winner.
3001 if (increment < 0) {
3002 if (!capable(CAP_SYS_NICE))
3004 if (increment < -40)
3010 nice = PRIO_TO_NICE(current->static_prio) + increment;
3016 retval = security_task_setnice(current, nice);
3020 set_user_nice(current, nice);
3027 * task_prio - return the priority value of a given task.
3028 * @p: the task in question.
3030 * This is the priority value as seen by users in /proc.
3031 * RT tasks are offset by -200. Normal tasks are centered
3032 * around 0, value goes from -16 to +15.
3034 int task_prio(task_t *p)
3036 return p->prio - MAX_RT_PRIO;
3040 * task_nice - return the nice value of a given task.
3041 * @p: the task in question.
3043 int task_nice(task_t *p)
3045 return TASK_NICE(p);
3048 EXPORT_SYMBOL(task_nice);
3051 * idle_cpu - is a given cpu idle currently?
3052 * @cpu: the processor in question.
3054 int idle_cpu(int cpu)
3056 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3059 EXPORT_SYMBOL_GPL(idle_cpu);
3062 * find_process_by_pid - find a process with a matching PID value.
3063 * @pid: the pid in question.
3065 static inline task_t *find_process_by_pid(pid_t pid)
3067 return pid ? find_task_by_pid(pid) : current;
3070 /* Actually do priority change: must hold rq lock. */
3071 static void __setscheduler(struct task_struct *p, int policy, int prio)
3075 p->rt_priority = prio;
3076 if (policy != SCHED_NORMAL)
3077 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
3079 p->prio = p->static_prio;
3083 * setscheduler - change the scheduling policy and/or RT priority of a thread.
3085 static int setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3087 struct sched_param lp;
3088 int retval = -EINVAL;
3090 prio_array_t *array;
3091 unsigned long flags;
3095 if (!param || pid < 0)
3099 if (copy_from_user(&lp, param, sizeof(struct sched_param)))
3103 * We play safe to avoid deadlocks.
3105 read_lock_irq(&tasklist_lock);
3107 p = find_process_by_pid(pid);
3111 goto out_unlock_tasklist;
3114 * To be able to change p->policy safely, the apropriate
3115 * runqueue lock must be held.
3117 rq = task_rq_lock(p, &flags);
3123 if (policy != SCHED_FIFO && policy != SCHED_RR &&
3124 policy != SCHED_NORMAL)
3129 * Valid priorities for SCHED_FIFO and SCHED_RR are
3130 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
3133 if (lp.sched_priority < 0 || lp.sched_priority > MAX_USER_RT_PRIO-1)
3135 if ((policy == SCHED_NORMAL) != (lp.sched_priority == 0))
3139 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
3140 !capable(CAP_SYS_NICE))
3142 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3143 !capable(CAP_SYS_NICE))
3146 retval = security_task_setscheduler(p, policy, &lp);
3152 deactivate_task(p, task_rq(p));
3155 __setscheduler(p, policy, lp.sched_priority);
3157 __activate_task(p, task_rq(p));
3159 * Reschedule if we are currently running on this runqueue and
3160 * our priority decreased, or if we are not currently running on
3161 * this runqueue and our priority is higher than the current's
3163 if (task_running(rq, p)) {
3164 if (p->prio > oldprio)
3165 resched_task(rq->curr);
3166 } else if (TASK_PREEMPTS_CURR(p, rq))
3167 resched_task(rq->curr);
3171 task_rq_unlock(rq, &flags);
3172 out_unlock_tasklist:
3173 read_unlock_irq(&tasklist_lock);
3180 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3181 * @pid: the pid in question.
3182 * @policy: new policy
3183 * @param: structure containing the new RT priority.
3185 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3186 struct sched_param __user *param)
3188 return setscheduler(pid, policy, param);
3192 * sys_sched_setparam - set/change the RT priority of a thread
3193 * @pid: the pid in question.
3194 * @param: structure containing the new RT priority.
3196 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3198 return setscheduler(pid, -1, param);
3202 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3203 * @pid: the pid in question.
3205 asmlinkage long sys_sched_getscheduler(pid_t pid)
3207 int retval = -EINVAL;
3214 read_lock(&tasklist_lock);
3215 p = find_process_by_pid(pid);
3217 retval = security_task_getscheduler(p);
3221 read_unlock(&tasklist_lock);
3228 * sys_sched_getscheduler - get the RT priority of a thread
3229 * @pid: the pid in question.
3230 * @param: structure containing the RT priority.
3232 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3234 struct sched_param lp;
3235 int retval = -EINVAL;
3238 if (!param || pid < 0)
3241 read_lock(&tasklist_lock);
3242 p = find_process_by_pid(pid);
3247 retval = security_task_getscheduler(p);
3251 lp.sched_priority = p->rt_priority;
3252 read_unlock(&tasklist_lock);
3255 * This one might sleep, we cannot do it with a spinlock held ...
3257 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3263 read_unlock(&tasklist_lock);
3268 * sys_sched_setaffinity - set the cpu affinity of a process
3269 * @pid: pid of the process
3270 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3271 * @user_mask_ptr: user-space pointer to the new cpu mask
3273 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
3274 unsigned long __user *user_mask_ptr)
3280 if (len < sizeof(new_mask))
3283 if (copy_from_user(&new_mask, user_mask_ptr, sizeof(new_mask)))
3287 read_lock(&tasklist_lock);
3289 p = find_process_by_pid(pid);
3291 read_unlock(&tasklist_lock);
3292 unlock_cpu_hotplug();
3297 * It is not safe to call set_cpus_allowed with the
3298 * tasklist_lock held. We will bump the task_struct's
3299 * usage count and then drop tasklist_lock.
3302 read_unlock(&tasklist_lock);
3305 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3306 !capable(CAP_SYS_NICE))
3309 retval = set_cpus_allowed(p, new_mask);
3313 unlock_cpu_hotplug();
3318 * sys_sched_getaffinity - get the cpu affinity of a process
3319 * @pid: pid of the process
3320 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3321 * @user_mask_ptr: user-space pointer to hold the current cpu mask
3323 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
3324 unsigned long __user *user_mask_ptr)
3326 unsigned int real_len;
3331 real_len = sizeof(mask);
3336 read_lock(&tasklist_lock);
3339 p = find_process_by_pid(pid);
3344 cpus_and(mask, p->cpus_allowed, cpu_possible_map);
3347 read_unlock(&tasklist_lock);
3348 unlock_cpu_hotplug();
3351 if (copy_to_user(user_mask_ptr, &mask, real_len))
3357 * sys_sched_yield - yield the current processor to other threads.
3359 * this function yields the current CPU by moving the calling thread
3360 * to the expired array. If there are no other threads running on this
3361 * CPU then this function will return.
3363 asmlinkage long sys_sched_yield(void)
3365 runqueue_t *rq = this_rq_lock();
3366 prio_array_t *array = current->array;
3367 prio_array_t *target = rq_expired(current,rq);
3370 * We implement yielding by moving the task into the expired
3373 * (special rule: RT tasks will just roundrobin in the active
3376 if (unlikely(rt_task(current)))
3377 target = rq_active(current,rq);
3379 dequeue_task(current, array);
3380 enqueue_task(current, target);
3383 * Since we are going to call schedule() anyway, there's
3384 * no need to preempt or enable interrupts:
3386 _raw_spin_unlock(&rq->lock);
3387 preempt_enable_no_resched();
3394 void __sched __cond_resched(void)
3396 set_current_state(TASK_RUNNING);
3400 EXPORT_SYMBOL(__cond_resched);
3403 * yield - yield the current processor to other threads.
3405 * this is a shortcut for kernel-space yielding - it marks the
3406 * thread runnable and calls sys_sched_yield().
3408 void __sched yield(void)
3410 set_current_state(TASK_RUNNING);
3414 EXPORT_SYMBOL(yield);
3417 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
3418 * that process accounting knows that this is a task in IO wait state.
3420 * But don't do that if it is a deliberate, throttling IO wait (this task
3421 * has set its backing_dev_info: the queue against which it should throttle)
3423 void __sched io_schedule(void)
3425 struct runqueue *rq = this_rq();
3426 def_delay_var(dstart);
3428 start_delay_set(dstart,PF_IOWAIT);
3429 atomic_inc(&rq->nr_iowait);
3431 atomic_dec(&rq->nr_iowait);
3432 add_io_delay(dstart);
3435 EXPORT_SYMBOL(io_schedule);
3437 long __sched io_schedule_timeout(long timeout)
3439 struct runqueue *rq = this_rq();
3441 def_delay_var(dstart);
3443 start_delay_set(dstart,PF_IOWAIT);
3444 atomic_inc(&rq->nr_iowait);
3445 ret = schedule_timeout(timeout);
3446 atomic_dec(&rq->nr_iowait);
3447 add_io_delay(dstart);
3452 * sys_sched_get_priority_max - return maximum RT priority.
3453 * @policy: scheduling class.
3455 * this syscall returns the maximum rt_priority that can be used
3456 * by a given scheduling class.
3458 asmlinkage long sys_sched_get_priority_max(int policy)
3465 ret = MAX_USER_RT_PRIO-1;
3475 * sys_sched_get_priority_min - return minimum RT priority.
3476 * @policy: scheduling class.
3478 * this syscall returns the minimum rt_priority that can be used
3479 * by a given scheduling class.
3481 asmlinkage long sys_sched_get_priority_min(int policy)
3497 * sys_sched_rr_get_interval - return the default timeslice of a process.
3498 * @pid: pid of the process.
3499 * @interval: userspace pointer to the timeslice value.
3501 * this syscall writes the default timeslice value of a given process
3502 * into the user-space timespec buffer. A value of '0' means infinity.
3505 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
3507 int retval = -EINVAL;
3515 read_lock(&tasklist_lock);
3516 p = find_process_by_pid(pid);
3520 retval = security_task_getscheduler(p);
3524 jiffies_to_timespec(p->policy & SCHED_FIFO ?
3525 0 : task_timeslice(p), &t);
3526 read_unlock(&tasklist_lock);
3527 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
3531 read_unlock(&tasklist_lock);
3535 static inline struct task_struct *eldest_child(struct task_struct *p)
3537 if (list_empty(&p->children)) return NULL;
3538 return list_entry(p->children.next,struct task_struct,sibling);
3541 static inline struct task_struct *older_sibling(struct task_struct *p)
3543 if (p->sibling.prev==&p->parent->children) return NULL;
3544 return list_entry(p->sibling.prev,struct task_struct,sibling);
3547 static inline struct task_struct *younger_sibling(struct task_struct *p)
3549 if (p->sibling.next==&p->parent->children) return NULL;
3550 return list_entry(p->sibling.next,struct task_struct,sibling);
3553 static void show_task(task_t * p)
3557 unsigned long free = 0;
3558 static const char *stat_nam[] = { "R", "S", "D", "T", "Z", "W" };
3560 printk("%-13.13s ", p->comm);
3561 state = p->state ? __ffs(p->state) + 1 : 0;
3562 if (state < ARRAY_SIZE(stat_nam))
3563 printk(stat_nam[state]);
3566 #if (BITS_PER_LONG == 32)
3567 if (state == TASK_RUNNING)
3568 printk(" running ");
3570 printk(" %08lX ", thread_saved_pc(p));
3572 if (state == TASK_RUNNING)
3573 printk(" running task ");
3575 printk(" %016lx ", thread_saved_pc(p));
3577 #ifdef CONFIG_DEBUG_STACK_USAGE
3579 unsigned long * n = (unsigned long *) (p->thread_info+1);
3582 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
3585 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
3586 if ((relative = eldest_child(p)))
3587 printk("%5d ", relative->pid);
3590 if ((relative = younger_sibling(p)))
3591 printk("%7d", relative->pid);
3594 if ((relative = older_sibling(p)))
3595 printk(" %5d", relative->pid);
3599 printk(" (L-TLB)\n");
3601 printk(" (NOTLB)\n");
3603 if (state != TASK_RUNNING)
3604 show_stack(p, NULL);
3607 void show_state(void)
3611 #if (BITS_PER_LONG == 32)
3614 printk(" task PC pid father child younger older\n");
3618 printk(" task PC pid father child younger older\n");
3620 read_lock(&tasklist_lock);
3621 do_each_thread(g, p) {
3623 * reset the NMI-timeout, listing all files on a slow
3624 * console might take alot of time:
3626 touch_nmi_watchdog();
3628 } while_each_thread(g, p);
3630 read_unlock(&tasklist_lock);
3633 void __devinit init_idle(task_t *idle, int cpu)
3635 runqueue_t *idle_rq = cpu_rq(cpu), *rq = cpu_rq(task_cpu(idle));
3636 unsigned long flags;
3638 local_irq_save(flags);
3639 double_rq_lock(idle_rq, rq);
3641 idle_rq->curr = idle_rq->idle = idle;
3642 deactivate_task(idle, rq);
3644 idle->prio = MAX_PRIO;
3645 idle->state = TASK_RUNNING;
3646 set_task_cpu(idle, cpu);
3647 double_rq_unlock(idle_rq, rq);
3648 set_tsk_need_resched(idle);
3649 local_irq_restore(flags);
3651 /* Set the preempt count _outside_ the spinlocks! */
3652 #ifdef CONFIG_PREEMPT
3653 idle->thread_info->preempt_count = (idle->lock_depth >= 0);
3655 idle->thread_info->preempt_count = 0;
3660 * In a system that switches off the HZ timer nohz_cpu_mask
3661 * indicates which cpus entered this state. This is used
3662 * in the rcu update to wait only for active cpus. For system
3663 * which do not switch off the HZ timer nohz_cpu_mask should
3664 * always be CPU_MASK_NONE.
3666 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
3670 * This is how migration works:
3672 * 1) we queue a migration_req_t structure in the source CPU's
3673 * runqueue and wake up that CPU's migration thread.
3674 * 2) we down() the locked semaphore => thread blocks.
3675 * 3) migration thread wakes up (implicitly it forces the migrated
3676 * thread off the CPU)
3677 * 4) it gets the migration request and checks whether the migrated
3678 * task is still in the wrong runqueue.
3679 * 5) if it's in the wrong runqueue then the migration thread removes
3680 * it and puts it into the right queue.
3681 * 6) migration thread up()s the semaphore.
3682 * 7) we wake up and the migration is done.
3686 * Change a given task's CPU affinity. Migrate the thread to a
3687 * proper CPU and schedule it away if the CPU it's executing on
3688 * is removed from the allowed bitmask.
3690 * NOTE: the caller must have a valid reference to the task, the
3691 * task must not exit() & deallocate itself prematurely. The
3692 * call is not atomic; no spinlocks may be held.
3694 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
3696 unsigned long flags;
3698 migration_req_t req;
3701 rq = task_rq_lock(p, &flags);
3702 if (any_online_cpu(new_mask) == NR_CPUS) {
3707 p->cpus_allowed = new_mask;
3708 /* Can the task run on the task's current CPU? If so, we're done */
3709 if (cpu_isset(task_cpu(p), new_mask))
3712 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
3713 /* Need help from migration thread: drop lock and wait. */
3714 task_rq_unlock(rq, &flags);
3715 wake_up_process(rq->migration_thread);
3716 wait_for_completion(&req.done);
3720 task_rq_unlock(rq, &flags);
3724 EXPORT_SYMBOL_GPL(set_cpus_allowed);
3727 * Move (not current) task off this cpu, onto dest cpu. We're doing
3728 * this because either it can't run here any more (set_cpus_allowed()
3729 * away from this CPU, or CPU going down), or because we're
3730 * attempting to rebalance this task on exec (sched_balance_exec).
3732 * So we race with normal scheduler movements, but that's OK, as long
3733 * as the task is no longer on this CPU.
3735 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
3737 runqueue_t *rq_dest, *rq_src;
3739 if (unlikely(cpu_is_offline(dest_cpu)))
3742 rq_src = cpu_rq(src_cpu);
3743 rq_dest = cpu_rq(dest_cpu);
3745 double_rq_lock(rq_src, rq_dest);
3746 /* Already moved. */
3747 if (task_cpu(p) != src_cpu)
3749 /* Affinity changed (again). */
3750 if (!cpu_isset(dest_cpu, p->cpus_allowed))
3753 set_task_cpu(p, dest_cpu);
3756 * Sync timestamp with rq_dest's before activating.
3757 * The same thing could be achieved by doing this step
3758 * afterwards, and pretending it was a local activate.
3759 * This way is cleaner and logically correct.
3761 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
3762 + rq_dest->timestamp_last_tick;
3763 deactivate_task(p, rq_src);
3764 activate_task(p, rq_dest, 0);
3765 if (TASK_PREEMPTS_CURR(p, rq_dest))
3766 resched_task(rq_dest->curr);
3770 double_rq_unlock(rq_src, rq_dest);
3774 * migration_thread - this is a highprio system thread that performs
3775 * thread migration by bumping thread off CPU then 'pushing' onto
3778 static int migration_thread(void * data)
3781 int cpu = (long)data;
3784 BUG_ON(rq->migration_thread != current);
3786 set_current_state(TASK_INTERRUPTIBLE);
3787 while (!kthread_should_stop()) {
3788 struct list_head *head;
3789 migration_req_t *req;
3791 if (current->flags & PF_FREEZE)
3792 refrigerator(PF_FREEZE);
3794 spin_lock_irq(&rq->lock);
3796 if (cpu_is_offline(cpu)) {
3797 spin_unlock_irq(&rq->lock);
3801 if (rq->active_balance) {
3802 #ifndef CONFIG_CKRM_CPU_SCHEDULE
3803 active_load_balance(rq, cpu);
3805 rq->active_balance = 0;
3808 head = &rq->migration_queue;
3810 if (list_empty(head)) {
3811 spin_unlock_irq(&rq->lock);
3813 set_current_state(TASK_INTERRUPTIBLE);
3816 req = list_entry(head->next, migration_req_t, list);
3817 list_del_init(head->next);
3819 if (req->type == REQ_MOVE_TASK) {
3820 spin_unlock(&rq->lock);
3821 __migrate_task(req->task, smp_processor_id(),
3824 } else if (req->type == REQ_SET_DOMAIN) {
3826 spin_unlock_irq(&rq->lock);
3828 spin_unlock_irq(&rq->lock);
3832 complete(&req->done);
3834 __set_current_state(TASK_RUNNING);
3838 /* Wait for kthread_stop */
3839 set_current_state(TASK_INTERRUPTIBLE);
3840 while (!kthread_should_stop()) {
3842 set_current_state(TASK_INTERRUPTIBLE);
3844 __set_current_state(TASK_RUNNING);
3848 #ifdef CONFIG_HOTPLUG_CPU
3849 /* migrate_all_tasks - function to migrate all tasks from the dead cpu. */
3850 static void migrate_all_tasks(int src_cpu)
3852 struct task_struct *tsk, *t;
3856 write_lock_irq(&tasklist_lock);
3858 /* watch out for per node tasks, let's stay on this node */
3859 node = cpu_to_node(src_cpu);
3861 do_each_thread(t, tsk) {
3866 if (task_cpu(tsk) != src_cpu)
3869 /* Figure out where this task should go (attempting to
3870 * keep it on-node), and check if it can be migrated
3871 * as-is. NOTE that kernel threads bound to more than
3872 * one online cpu will be migrated. */
3873 mask = node_to_cpumask(node);
3874 cpus_and(mask, mask, tsk->cpus_allowed);
3875 dest_cpu = any_online_cpu(mask);
3876 if (dest_cpu == NR_CPUS)
3877 dest_cpu = any_online_cpu(tsk->cpus_allowed);
3878 if (dest_cpu == NR_CPUS) {
3879 cpus_clear(tsk->cpus_allowed);
3880 cpus_complement(tsk->cpus_allowed);
3881 dest_cpu = any_online_cpu(tsk->cpus_allowed);
3883 /* Don't tell them about moving exiting tasks
3884 or kernel threads (both mm NULL), since
3885 they never leave kernel. */
3886 if (tsk->mm && printk_ratelimit())
3887 printk(KERN_INFO "process %d (%s) no "
3888 "longer affine to cpu%d\n",
3889 tsk->pid, tsk->comm, src_cpu);
3892 __migrate_task(tsk, src_cpu, dest_cpu);
3893 } while_each_thread(t, tsk);
3895 write_unlock_irq(&tasklist_lock);
3898 /* Schedules idle task to be the next runnable task on current CPU.
3899 * It does so by boosting its priority to highest possible and adding it to
3900 * the _front_ of runqueue. Used by CPU offline code.
3902 void sched_idle_next(void)
3904 int cpu = smp_processor_id();
3905 runqueue_t *rq = this_rq();
3906 struct task_struct *p = rq->idle;
3907 unsigned long flags;
3909 /* cpu has to be offline */
3910 BUG_ON(cpu_online(cpu));
3912 /* Strictly not necessary since rest of the CPUs are stopped by now
3913 * and interrupts disabled on current cpu.
3915 spin_lock_irqsave(&rq->lock, flags);
3917 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
3918 /* Add idle task to _front_ of it's priority queue */
3919 __activate_idle_task(p, rq);
3921 spin_unlock_irqrestore(&rq->lock, flags);
3923 #endif /* CONFIG_HOTPLUG_CPU */
3926 * migration_call - callback that gets triggered when a CPU is added.
3927 * Here we can start up the necessary migration thread for the new CPU.
3929 static int migration_call(struct notifier_block *nfb, unsigned long action,
3932 int cpu = (long)hcpu;
3933 struct task_struct *p;
3934 struct runqueue *rq;
3935 unsigned long flags;
3938 case CPU_UP_PREPARE:
3939 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
3942 kthread_bind(p, cpu);
3943 /* Must be high prio: stop_machine expects to yield to it. */
3944 rq = task_rq_lock(p, &flags);
3945 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
3946 task_rq_unlock(rq, &flags);
3947 cpu_rq(cpu)->migration_thread = p;
3950 /* Strictly unneccessary, as first user will wake it. */
3951 wake_up_process(cpu_rq(cpu)->migration_thread);
3953 #ifdef CONFIG_HOTPLUG_CPU
3954 case CPU_UP_CANCELED:
3955 /* Unbind it from offline cpu so it can run. Fall thru. */
3956 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
3957 kthread_stop(cpu_rq(cpu)->migration_thread);
3958 cpu_rq(cpu)->migration_thread = NULL;
3961 migrate_all_tasks(cpu);
3963 kthread_stop(rq->migration_thread);
3964 rq->migration_thread = NULL;
3965 /* Idle task back to normal (off runqueue, low prio) */
3966 rq = task_rq_lock(rq->idle, &flags);
3967 deactivate_task(rq->idle, rq);
3968 rq->idle->static_prio = MAX_PRIO;
3969 __setscheduler(rq->idle, SCHED_NORMAL, 0);
3970 task_rq_unlock(rq, &flags);
3971 BUG_ON(rq->nr_running != 0);
3973 /* No need to migrate the tasks: it was best-effort if
3974 * they didn't do lock_cpu_hotplug(). Just wake up
3975 * the requestors. */
3976 spin_lock_irq(&rq->lock);
3977 while (!list_empty(&rq->migration_queue)) {
3978 migration_req_t *req;
3979 req = list_entry(rq->migration_queue.next,
3980 migration_req_t, list);
3981 BUG_ON(req->type != REQ_MOVE_TASK);
3982 list_del_init(&req->list);
3983 complete(&req->done);
3985 spin_unlock_irq(&rq->lock);
3992 /* Register at highest priority so that task migration (migrate_all_tasks)
3993 * happens before everything else.
3995 static struct notifier_block __devinitdata migration_notifier = {
3996 .notifier_call = migration_call,
4000 int __init migration_init(void)
4002 void *cpu = (void *)(long)smp_processor_id();
4003 /* Start one for boot CPU. */
4004 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4005 migration_call(&migration_notifier, CPU_ONLINE, cpu);
4006 register_cpu_notifier(&migration_notifier);
4012 * The 'big kernel lock'
4014 * This spinlock is taken and released recursively by lock_kernel()
4015 * and unlock_kernel(). It is transparently dropped and reaquired
4016 * over schedule(). It is used to protect legacy code that hasn't
4017 * been migrated to a proper locking design yet.
4019 * Don't use in new code.
4021 * Note: spinlock debugging needs this even on !CONFIG_SMP.
4023 spinlock_t kernel_flag __cacheline_aligned_in_smp = SPIN_LOCK_UNLOCKED;
4024 EXPORT_SYMBOL(kernel_flag);
4027 /* Attach the domain 'sd' to 'cpu' as its base domain */
4028 void cpu_attach_domain(struct sched_domain *sd, int cpu)
4030 migration_req_t req;
4031 unsigned long flags;
4032 runqueue_t *rq = cpu_rq(cpu);
4037 spin_lock_irqsave(&rq->lock, flags);
4039 if (cpu == smp_processor_id() || !cpu_online(cpu)) {
4042 init_completion(&req.done);
4043 req.type = REQ_SET_DOMAIN;
4045 list_add(&req.list, &rq->migration_queue);
4049 spin_unlock_irqrestore(&rq->lock, flags);
4052 wake_up_process(rq->migration_thread);
4053 wait_for_completion(&req.done);
4056 unlock_cpu_hotplug();
4059 #ifdef ARCH_HAS_SCHED_DOMAIN
4060 extern void __init arch_init_sched_domains(void);
4062 static struct sched_group sched_group_cpus[NR_CPUS];
4063 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
4065 static struct sched_group sched_group_nodes[MAX_NUMNODES];
4066 static DEFINE_PER_CPU(struct sched_domain, node_domains);
4067 static void __init arch_init_sched_domains(void)
4070 struct sched_group *first_node = NULL, *last_node = NULL;
4072 /* Set up domains */
4074 int node = cpu_to_node(i);
4075 cpumask_t nodemask = node_to_cpumask(node);
4076 struct sched_domain *node_sd = &per_cpu(node_domains, i);
4077 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
4079 *node_sd = SD_NODE_INIT;
4080 node_sd->span = cpu_possible_map;
4081 node_sd->groups = &sched_group_nodes[cpu_to_node(i)];
4083 *cpu_sd = SD_CPU_INIT;
4084 cpus_and(cpu_sd->span, nodemask, cpu_possible_map);
4085 cpu_sd->groups = &sched_group_cpus[i];
4086 cpu_sd->parent = node_sd;
4090 for (i = 0; i < MAX_NUMNODES; i++) {
4091 cpumask_t tmp = node_to_cpumask(i);
4093 struct sched_group *first_cpu = NULL, *last_cpu = NULL;
4094 struct sched_group *node = &sched_group_nodes[i];
4097 cpus_and(nodemask, tmp, cpu_possible_map);
4099 if (cpus_empty(nodemask))
4102 node->cpumask = nodemask;
4103 node->cpu_power = SCHED_LOAD_SCALE * cpus_weight(node->cpumask);
4105 for_each_cpu_mask(j, node->cpumask) {
4106 struct sched_group *cpu = &sched_group_cpus[j];
4108 cpus_clear(cpu->cpumask);
4109 cpu_set(j, cpu->cpumask);
4110 cpu->cpu_power = SCHED_LOAD_SCALE;
4115 last_cpu->next = cpu;
4118 last_cpu->next = first_cpu;
4123 last_node->next = node;
4126 last_node->next = first_node;
4130 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
4131 cpu_attach_domain(cpu_sd, i);
4135 #else /* !CONFIG_NUMA */
4136 static void __init arch_init_sched_domains(void)
4139 struct sched_group *first_cpu = NULL, *last_cpu = NULL;
4141 /* Set up domains */
4143 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
4145 *cpu_sd = SD_CPU_INIT;
4146 cpu_sd->span = cpu_possible_map;
4147 cpu_sd->groups = &sched_group_cpus[i];
4150 /* Set up CPU groups */
4151 for_each_cpu_mask(i, cpu_possible_map) {
4152 struct sched_group *cpu = &sched_group_cpus[i];
4154 cpus_clear(cpu->cpumask);
4155 cpu_set(i, cpu->cpumask);
4156 cpu->cpu_power = SCHED_LOAD_SCALE;
4161 last_cpu->next = cpu;
4164 last_cpu->next = first_cpu;
4166 mb(); /* domains were modified outside the lock */
4168 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
4169 cpu_attach_domain(cpu_sd, i);
4173 #endif /* CONFIG_NUMA */
4174 #endif /* ARCH_HAS_SCHED_DOMAIN */
4176 #define SCHED_DOMAIN_DEBUG
4177 #ifdef SCHED_DOMAIN_DEBUG
4178 void sched_domain_debug(void)
4183 runqueue_t *rq = cpu_rq(i);
4184 struct sched_domain *sd;
4189 printk(KERN_DEBUG "CPU%d: %s\n",
4190 i, (cpu_online(i) ? " online" : "offline"));
4195 struct sched_group *group = sd->groups;
4196 cpumask_t groupmask, tmp;
4198 cpumask_scnprintf(str, NR_CPUS, sd->span);
4199 cpus_clear(groupmask);
4202 for (j = 0; j < level + 1; j++)
4204 printk("domain %d: span %s\n", level, str);
4206 if (!cpu_isset(i, sd->span))
4207 printk(KERN_DEBUG "ERROR domain->span does not contain CPU%d\n", i);
4208 if (!cpu_isset(i, group->cpumask))
4209 printk(KERN_DEBUG "ERROR domain->groups does not contain CPU%d\n", i);
4210 if (!group->cpu_power)
4211 printk(KERN_DEBUG "ERROR domain->cpu_power not set\n");
4214 for (j = 0; j < level + 2; j++)
4219 printk(" ERROR: NULL");
4223 if (!cpus_weight(group->cpumask))
4224 printk(" ERROR empty group:");
4226 cpus_and(tmp, groupmask, group->cpumask);
4227 if (cpus_weight(tmp) > 0)
4228 printk(" ERROR repeated CPUs:");
4230 cpus_or(groupmask, groupmask, group->cpumask);
4232 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
4235 group = group->next;
4236 } while (group != sd->groups);
4239 if (!cpus_equal(sd->span, groupmask))
4240 printk(KERN_DEBUG "ERROR groups don't span domain->span\n");
4246 cpus_and(tmp, groupmask, sd->span);
4247 if (!cpus_equal(tmp, groupmask))
4248 printk(KERN_DEBUG "ERROR parent span is not a superset of domain->span\n");
4255 #define sched_domain_debug() {}
4258 void __init sched_init_smp(void)
4260 arch_init_sched_domains();
4261 sched_domain_debug();
4264 void __init sched_init_smp(void)
4267 #endif /* CONFIG_SMP */
4269 int in_sched_functions(unsigned long addr)
4271 /* Linker adds these: start and end of __sched functions */
4272 extern char __sched_text_start[], __sched_text_end[];
4273 return addr >= (unsigned long)__sched_text_start
4274 && addr < (unsigned long)__sched_text_end;
4277 void __init sched_init(void)
4281 #ifndef CONFIG_CKRM_CPU_SCHEDULE
4286 /* Set up an initial dummy domain for early boot */
4287 static struct sched_domain sched_domain_init;
4288 static struct sched_group sched_group_init;
4289 cpumask_t cpu_mask_all = CPU_MASK_ALL;
4291 memset(&sched_domain_init, 0, sizeof(struct sched_domain));
4292 sched_domain_init.span = cpu_mask_all;
4293 sched_domain_init.groups = &sched_group_init;
4294 sched_domain_init.last_balance = jiffies;
4295 sched_domain_init.balance_interval = INT_MAX; /* Don't balance */
4297 memset(&sched_group_init, 0, sizeof(struct sched_group));
4298 sched_group_init.cpumask = cpu_mask_all;
4299 sched_group_init.next = &sched_group_init;
4300 sched_group_init.cpu_power = SCHED_LOAD_SCALE;
4305 for (i = 0; i < NR_CPUS; i++) {
4306 #ifndef CONFIG_CKRM_CPU_SCHEDULE
4307 prio_array_t *array;
4310 spin_lock_init(&rq->lock);
4312 #ifndef CONFIG_CKRM_CPU_SCHEDULE
4313 rq->active = rq->arrays;
4314 rq->expired = rq->arrays + 1;
4316 rq->ckrm_cpu_load = 0;
4318 rq->best_expired_prio = MAX_PRIO;
4321 rq->sd = &sched_domain_init;
4323 rq->active_balance = 0;
4325 rq->migration_thread = NULL;
4326 INIT_LIST_HEAD(&rq->migration_queue);
4328 atomic_set(&rq->nr_iowait, 0);
4330 #ifndef CONFIG_CKRM_CPU_SCHEDULE
4331 for (j = 0; j < 2; j++) {
4332 array = rq->arrays + j;
4333 for (k = 0; k < MAX_PRIO; k++) {
4334 INIT_LIST_HEAD(array->queue + k);
4335 __clear_bit(k, array->bitmap);
4337 // delimiter for bitsearch
4338 __set_bit(MAX_PRIO, array->bitmap);
4344 * We have to do a little magic to get the first
4345 * thread right in SMP mode.
4350 set_task_cpu(current, smp_processor_id());
4351 #ifdef CONFIG_CKRM_CPU_SCHEDULE
4352 current->cpu_class = default_cpu_class;
4353 current->array = NULL;
4355 wake_up_forked_process(current);
4358 * The boot idle thread does lazy MMU switching as well:
4360 atomic_inc(&init_mm.mm_count);
4361 enter_lazy_tlb(&init_mm, current);
4364 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4365 void __might_sleep(char *file, int line)
4367 #if defined(in_atomic)
4368 static unsigned long prev_jiffy; /* ratelimiting */
4370 if ((in_atomic() || irqs_disabled()) &&
4371 system_state == SYSTEM_RUNNING) {
4372 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
4374 prev_jiffy = jiffies;
4375 printk(KERN_ERR "Debug: sleeping function called from invalid"
4376 " context at %s:%d\n", file, line);
4377 printk("in_atomic():%d, irqs_disabled():%d\n",
4378 in_atomic(), irqs_disabled());
4383 EXPORT_SYMBOL(__might_sleep);
4387 #if defined(CONFIG_SMP) && defined(CONFIG_PREEMPT)
4389 * This could be a long-held lock. If another CPU holds it for a long time,
4390 * and that CPU is not asked to reschedule then *this* CPU will spin on the
4391 * lock for a long time, even if *this* CPU is asked to reschedule.
4393 * So what we do here, in the slow (contended) path is to spin on the lock by
4394 * hand while permitting preemption.
4396 * Called inside preempt_disable().
4398 void __sched __preempt_spin_lock(spinlock_t *lock)
4400 if (preempt_count() > 1) {
4401 _raw_spin_lock(lock);
4406 while (spin_is_locked(lock))
4409 } while (!_raw_spin_trylock(lock));
4412 EXPORT_SYMBOL(__preempt_spin_lock);
4414 void __sched __preempt_write_lock(rwlock_t *lock)
4416 if (preempt_count() > 1) {
4417 _raw_write_lock(lock);
4423 while (rwlock_is_locked(lock))
4426 } while (!_raw_write_trylock(lock));
4429 EXPORT_SYMBOL(__preempt_write_lock);
4430 #endif /* defined(CONFIG_SMP) && defined(CONFIG_PREEMPT) */
4432 #ifdef CONFIG_DELAY_ACCT
4433 int task_running_sys(struct task_struct *p)
4435 return task_running(task_rq(p),p);
4437 EXPORT_SYMBOL(task_running_sys);
4440 #ifdef CONFIG_CKRM_CPU_SCHEDULE
4442 * return the classqueue object of a certain processor
4443 * Note: not supposed to be used in performance sensitive functions
4445 struct classqueue_struct * get_cpu_classqueue(int cpu)
4447 return (& (cpu_rq(cpu)->classqueue) );