4 * Kernel scheduler and related syscalls
6 * Copyright (C) 1991-2002 Linus Torvalds
8 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
9 * make semaphores SMP safe
10 * 1998-11-19 Implemented schedule_timeout() and related stuff
12 * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
13 * hybrid priority-list and round-robin design with
14 * an array-switch method of distributing timeslices
15 * and per-CPU runqueues. Cleanups and useful suggestions
16 * by Davide Libenzi, preemptible kernel bits by Robert Love.
17 * 2003-09-03 Interactivity tuning by Con Kolivas.
18 * 2004-04-02 Scheduler domains code by Nick Piggin
21 #include <linux/module.h>
22 #include <linux/nmi.h>
23 #include <linux/init.h>
24 #include <asm/uaccess.h>
25 #include <linux/highmem.h>
26 #include <linux/smp_lock.h>
27 #include <linux/pagemap.h>
28 #include <asm/mmu_context.h>
29 #include <linux/interrupt.h>
30 #include <linux/completion.h>
31 #include <linux/kernel_stat.h>
32 #include <linux/security.h>
33 #include <linux/notifier.h>
34 #include <linux/suspend.h>
35 #include <linux/blkdev.h>
36 #include <linux/delay.h>
37 #include <linux/smp.h>
38 #include <linux/timer.h>
39 #include <linux/rcupdate.h>
40 #include <linux/cpu.h>
41 #include <linux/percpu.h>
42 #include <linux/kthread.h>
43 #include <linux/vserver/sched.h>
44 #include <linux/vs_base.h>
47 #include <asm/unistd.h>
50 #define cpu_to_node_mask(cpu) node_to_cpumask(cpu_to_node(cpu))
52 #define cpu_to_node_mask(cpu) (cpu_online_map)
55 /* used to soft spin in sched while dump is in progress */
56 unsigned long dump_oncpu;
57 EXPORT_SYMBOL(dump_oncpu);
60 * Convert user-nice values [ -20 ... 0 ... 19 ]
61 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
64 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
65 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
66 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
69 * 'User priority' is the nice value converted to something we
70 * can work with better when scaling various scheduler parameters,
71 * it's a [ 0 ... 39 ] range.
73 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
74 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
75 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
76 #define AVG_TIMESLICE (MIN_TIMESLICE + ((MAX_TIMESLICE - MIN_TIMESLICE) *\
77 (MAX_PRIO-1-NICE_TO_PRIO(0))/(MAX_USER_PRIO - 1)))
80 * Some helpers for converting nanosecond timing to jiffy resolution
82 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
83 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
86 * These are the 'tuning knobs' of the scheduler:
88 * Minimum timeslice is 10 msecs, default timeslice is 100 msecs,
89 * maximum timeslice is 200 msecs. Timeslices get refilled after
92 #define MIN_TIMESLICE ( 10 * HZ / 1000)
93 #define MAX_TIMESLICE (200 * HZ / 1000)
94 #define ON_RUNQUEUE_WEIGHT 30
95 #define CHILD_PENALTY 95
96 #define PARENT_PENALTY 100
98 #define PRIO_BONUS_RATIO 25
99 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
100 #define INTERACTIVE_DELTA 2
101 #define MAX_SLEEP_AVG (AVG_TIMESLICE * MAX_BONUS)
102 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
103 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
104 #define CREDIT_LIMIT 100
107 * If a task is 'interactive' then we reinsert it in the active
108 * array after it has expired its current timeslice. (it will not
109 * continue to run immediately, it will still roundrobin with
110 * other interactive tasks.)
112 * This part scales the interactivity limit depending on niceness.
114 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
115 * Here are a few examples of different nice levels:
117 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
118 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
119 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
120 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
121 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
123 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
124 * priority range a task can explore, a value of '1' means the
125 * task is rated interactive.)
127 * Ie. nice +19 tasks can never get 'interactive' enough to be
128 * reinserted into the active array. And only heavily CPU-hog nice -20
129 * tasks will be expired. Default nice 0 tasks are somewhere between,
130 * it takes some effort for them to get interactive, but it's not
134 #define CURRENT_BONUS(p) \
135 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
139 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
140 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
143 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
144 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
147 #define SCALE(v1,v1_max,v2_max) \
148 (v1) * (v2_max) / (v1_max)
151 (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
153 #define TASK_INTERACTIVE(p) \
154 ((p)->prio <= (p)->static_prio - DELTA(p))
156 #define INTERACTIVE_SLEEP(p) \
157 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
158 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
160 #define HIGH_CREDIT(p) \
161 ((p)->interactive_credit > CREDIT_LIMIT)
163 #define LOW_CREDIT(p) \
164 ((p)->interactive_credit < -CREDIT_LIMIT)
167 * BASE_TIMESLICE scales user-nice values [ -20 ... 19 ]
168 * to time slice values.
170 * The higher a thread's priority, the bigger timeslices
171 * it gets during one round of execution. But even the lowest
172 * priority thread gets MIN_TIMESLICE worth of execution time.
174 * task_timeslice() is the interface that is used by the scheduler.
177 #define BASE_TIMESLICE(p) (MIN_TIMESLICE + \
178 ((MAX_TIMESLICE - MIN_TIMESLICE) * \
179 (MAX_PRIO-1 - (p)->static_prio) / (MAX_USER_PRIO-1)))
181 static unsigned int task_timeslice(task_t *p)
183 return BASE_TIMESLICE(p);
186 #define task_hot(p, now, sd) ((now) - (p)->timestamp < (sd)->cache_hot_time)
188 DEFINE_PER_CPU(struct runqueue, runqueues);
190 #define for_each_domain(cpu, domain) \
191 for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
193 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
194 #define this_rq() (&__get_cpu_var(runqueues))
195 #define task_rq(p) cpu_rq(task_cpu(p))
196 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
199 * Default context-switch locking:
201 #ifndef prepare_arch_switch
202 # define prepare_arch_switch(rq, next) do { } while (0)
203 # define finish_arch_switch(rq, next) spin_unlock_irq(&(rq)->lock)
204 # define task_running(rq, p) ((rq)->curr == (p))
207 #ifdef CONFIG_CKRM_CPU_SCHEDULE
208 #include <linux/ckrm_sched.h>
209 spinlock_t cvt_lock = SPIN_LOCK_UNLOCKED;
210 rwlock_t class_list_lock = RW_LOCK_UNLOCKED;
211 LIST_HEAD(active_cpu_classes); // list of active cpu classes; anchor
212 struct ckrm_cpu_class default_cpu_class_obj;
215 * the minimum CVT allowed is the base_cvt
216 * otherwise, it will starve others
218 CVT_t get_min_cvt(int cpu)
221 struct ckrm_local_runqueue * lrq;
224 node = classqueue_get_head(bpt_queue(cpu));
225 lrq = (node) ? class_list_entry(node) : NULL;
228 min_cvt = lrq->local_cvt;
236 * update the classueue base for all the runqueues
237 * TODO: we can only update half of the min_base to solve the movebackward issue
239 static inline void check_update_class_base(int this_cpu) {
240 unsigned long min_base = 0xFFFFFFFF;
244 if (! cpu_online(this_cpu)) return;
247 * find the min_base across all the processors
249 for_each_online_cpu(i) {
251 * I should change it to directly use bpt->base
253 node = classqueue_get_head(bpt_queue(i));
254 if (node && node->prio < min_base) {
255 min_base = node->prio;
258 if (min_base != 0xFFFFFFFF)
259 classqueue_update_base(bpt_queue(this_cpu),min_base);
262 static inline void ckrm_rebalance_tick(int j,int this_cpu)
264 #ifdef CONFIG_CKRM_CPU_SCHEDULE
265 read_lock(&class_list_lock);
266 if (!(j % CVT_UPDATE_TICK))
267 update_global_cvts(this_cpu);
269 #define CKRM_BASE_UPDATE_RATE 400
270 if (! (jiffies % CKRM_BASE_UPDATE_RATE))
271 check_update_class_base(this_cpu);
273 read_unlock(&class_list_lock);
277 static inline struct ckrm_local_runqueue *rq_get_next_class(struct runqueue *rq)
279 cq_node_t *node = classqueue_get_head(&rq->classqueue);
280 return ((node) ? class_list_entry(node) : NULL);
283 static inline struct task_struct * rq_get_next_task(struct runqueue* rq)
286 struct task_struct *next;
287 struct ckrm_local_runqueue *queue;
288 int cpu = smp_processor_id();
292 if ((queue = rq_get_next_class(rq))) {
293 array = queue->active;
294 //check switch active/expired queue
295 if (unlikely(!queue->active->nr_active)) {
296 queue->active = queue->expired;
297 queue->expired = array;
298 queue->expired_timestamp = 0;
300 if (queue->active->nr_active)
301 set_top_priority(queue,
302 find_first_bit(queue->active->bitmap, MAX_PRIO));
304 classqueue_dequeue(queue->classqueue,
305 &queue->classqueue_linkobj);
306 cpu_demand_event(get_rq_local_stat(queue,cpu),CPU_DEMAND_DEQUEUE,0);
309 goto retry_next_class;
311 BUG_ON(!queue->active->nr_active);
312 next = task_list_entry(array->queue[queue->top_priority].next);
317 static inline void rq_load_inc(runqueue_t *rq, struct task_struct *p) { rq->ckrm_cpu_load += cpu_class_weight(p->cpu_class); }
318 static inline void rq_load_dec(runqueue_t *rq, struct task_struct *p) { rq->ckrm_cpu_load -= cpu_class_weight(p->cpu_class); }
320 #else /*CONFIG_CKRM_CPU_SCHEDULE*/
322 static inline struct task_struct * rq_get_next_task(struct runqueue* rq)
325 struct list_head *queue;
329 if (unlikely(!array->nr_active)) {
331 * Switch the active and expired arrays.
333 rq->active = rq->expired;
336 rq->expired_timestamp = 0;
337 rq->best_expired_prio = MAX_PRIO;
340 idx = sched_find_first_bit(array->bitmap);
341 queue = array->queue + idx;
342 return list_entry(queue->next, task_t, run_list);
345 static inline void class_enqueue_task(struct task_struct* p, prio_array_t *array) { }
346 static inline void class_dequeue_task(struct task_struct* p, prio_array_t *array) { }
347 static inline void init_cpu_classes(void) { }
348 static inline void rq_load_inc(runqueue_t *rq, struct task_struct *p) { }
349 static inline void rq_load_dec(runqueue_t *rq, struct task_struct *p) { }
350 #endif /* CONFIG_CKRM_CPU_SCHEDULE */
354 * task_rq_lock - lock the runqueue a given task resides on and disable
355 * interrupts. Note the ordering: we can safely lookup the task_rq without
356 * explicitly disabling preemption.
358 runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
363 local_irq_save(*flags);
365 spin_lock(&rq->lock);
366 if (unlikely(rq != task_rq(p))) {
367 spin_unlock_irqrestore(&rq->lock, *flags);
368 goto repeat_lock_task;
373 void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
375 spin_unlock_irqrestore(&rq->lock, *flags);
379 * rq_lock - lock a given runqueue and disable interrupts.
381 static runqueue_t *this_rq_lock(void)
387 spin_lock(&rq->lock);
392 static inline void rq_unlock(runqueue_t *rq)
394 spin_unlock_irq(&rq->lock);
398 * Adding/removing a task to/from a priority array:
400 void dequeue_task(struct task_struct *p, prio_array_t *array)
404 list_del(&p->run_list);
405 if (list_empty(array->queue + p->prio))
406 __clear_bit(p->prio, array->bitmap);
407 class_dequeue_task(p,array);
410 void enqueue_task(struct task_struct *p, prio_array_t *array)
412 list_add_tail(&p->run_list, array->queue + p->prio);
413 __set_bit(p->prio, array->bitmap);
416 class_enqueue_task(p,array);
420 * Used by the migration code - we pull tasks from the head of the
421 * remote queue so we want these tasks to show up at the head of the
424 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
426 list_add(&p->run_list, array->queue + p->prio);
427 __set_bit(p->prio, array->bitmap);
430 class_enqueue_task(p,array);
434 * effective_prio - return the priority that is based on the static
435 * priority but is modified by bonuses/penalties.
437 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
438 * into the -5 ... 0 ... +5 bonus/penalty range.
440 * We use 25% of the full 0...39 priority range so that:
442 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
443 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
445 * Both properties are important to certain workloads.
447 static int effective_prio(task_t *p)
454 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
456 prio = p->static_prio - bonus;
457 if (__vx_task_flags(p, VXF_SCHED_PRIO, 0))
458 prio += effective_vavavoom(p, MAX_USER_PRIO);
460 if (prio < MAX_RT_PRIO)
462 if (prio > MAX_PRIO-1)
468 * __activate_task - move a task to the runqueue.
470 static inline void __activate_task(task_t *p, runqueue_t *rq)
472 enqueue_task(p, rq_active(p,rq));
478 * __activate_idle_task - move idle task to the _front_ of runqueue.
480 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
482 enqueue_task_head(p, rq_active(p,rq));
487 static void recalc_task_prio(task_t *p, unsigned long long now)
489 unsigned long long __sleep_time = now - p->timestamp;
490 unsigned long sleep_time;
492 if (__sleep_time > NS_MAX_SLEEP_AVG)
493 sleep_time = NS_MAX_SLEEP_AVG;
495 sleep_time = (unsigned long)__sleep_time;
497 if (likely(sleep_time > 0)) {
499 * User tasks that sleep a long time are categorised as
500 * idle and will get just interactive status to stay active &
501 * prevent them suddenly becoming cpu hogs and starving
504 if (p->mm && p->activated != -1 &&
505 sleep_time > INTERACTIVE_SLEEP(p)) {
506 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
509 p->interactive_credit++;
512 * The lower the sleep avg a task has the more
513 * rapidly it will rise with sleep time.
515 sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
518 * Tasks with low interactive_credit are limited to
519 * one timeslice worth of sleep avg bonus.
522 sleep_time > JIFFIES_TO_NS(task_timeslice(p)))
523 sleep_time = JIFFIES_TO_NS(task_timeslice(p));
526 * Non high_credit tasks waking from uninterruptible
527 * sleep are limited in their sleep_avg rise as they
528 * are likely to be cpu hogs waiting on I/O
530 if (p->activated == -1 && !HIGH_CREDIT(p) && p->mm) {
531 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
533 else if (p->sleep_avg + sleep_time >=
534 INTERACTIVE_SLEEP(p)) {
535 p->sleep_avg = INTERACTIVE_SLEEP(p);
541 * This code gives a bonus to interactive tasks.
543 * The boost works by updating the 'average sleep time'
544 * value here, based on ->timestamp. The more time a
545 * task spends sleeping, the higher the average gets -
546 * and the higher the priority boost gets as well.
548 p->sleep_avg += sleep_time;
550 if (p->sleep_avg > NS_MAX_SLEEP_AVG) {
551 p->sleep_avg = NS_MAX_SLEEP_AVG;
553 p->interactive_credit++;
558 p->prio = effective_prio(p);
562 * activate_task - move a task to the runqueue and do priority recalculation
564 * Update all the scheduling statistics stuff. (sleep average
565 * calculation, priority modifiers, etc.)
567 static void activate_task(task_t *p, runqueue_t *rq, int local)
569 unsigned long long now;
574 /* Compensate for drifting sched_clock */
575 runqueue_t *this_rq = this_rq();
576 now = (now - this_rq->timestamp_last_tick)
577 + rq->timestamp_last_tick;
581 recalc_task_prio(p, now);
584 * This checks to make sure it's not an uninterruptible task
585 * that is now waking up.
589 * Tasks which were woken up by interrupts (ie. hw events)
590 * are most likely of interactive nature. So we give them
591 * the credit of extending their sleep time to the period
592 * of time they spend on the runqueue, waiting for execution
593 * on a CPU, first time around:
599 * Normal first-time wakeups get a credit too for
600 * on-runqueue time, but it will be weighted down:
607 __activate_task(p, rq);
611 * deactivate_task - remove a task from the runqueue.
613 static void deactivate_task(struct task_struct *p, runqueue_t *rq)
617 if (p->state == TASK_UNINTERRUPTIBLE)
618 rq->nr_uninterruptible++;
619 dequeue_task(p, p->array);
624 * resched_task - mark a task 'to be rescheduled now'.
626 * On UP this means the setting of the need_resched flag, on SMP it
627 * might also involve a cross-CPU call to trigger the scheduler on
631 static void resched_task(task_t *p)
633 int need_resched, nrpolling;
636 /* minimise the chance of sending an interrupt to poll_idle() */
637 nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
638 need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
639 nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
641 if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
642 smp_send_reschedule(task_cpu(p));
646 static inline void resched_task(task_t *p)
648 set_tsk_need_resched(p);
653 * task_curr - is this task currently executing on a CPU?
654 * @p: the task in question.
656 inline int task_curr(const task_t *p)
658 return cpu_curr(task_cpu(p)) == p;
668 struct list_head list;
669 enum request_type type;
671 /* For REQ_MOVE_TASK */
675 /* For REQ_SET_DOMAIN */
676 struct sched_domain *sd;
678 struct completion done;
682 * The task's runqueue lock must be held.
683 * Returns true if you have to wait for migration thread.
685 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
687 runqueue_t *rq = task_rq(p);
690 * If the task is not on a runqueue (and not running), then
691 * it is sufficient to simply update the task's cpu field.
693 if (!p->array && !task_running(rq, p)) {
694 set_task_cpu(p, dest_cpu);
698 init_completion(&req->done);
699 req->type = REQ_MOVE_TASK;
701 req->dest_cpu = dest_cpu;
702 list_add(&req->list, &rq->migration_queue);
707 * wait_task_inactive - wait for a thread to unschedule.
709 * The caller must ensure that the task *will* unschedule sometime soon,
710 * else this function might spin for a *long* time. This function can't
711 * be called with interrupts off, or it may introduce deadlock with
712 * smp_call_function() if an IPI is sent by the same process we are
713 * waiting to become inactive.
715 void wait_task_inactive(task_t * p)
722 rq = task_rq_lock(p, &flags);
723 /* Must be off runqueue entirely, not preempted. */
724 if (unlikely(p->array)) {
725 /* If it's preempted, we yield. It could be a while. */
726 preempted = !task_running(rq, p);
727 task_rq_unlock(rq, &flags);
733 task_rq_unlock(rq, &flags);
737 * kick_process - kick a running thread to enter/exit the kernel
738 * @p: the to-be-kicked thread
740 * Cause a process which is running on another CPU to enter
741 * kernel-mode, without any delay. (to get signals handled.)
743 void kick_process(task_t *p)
749 if ((cpu != smp_processor_id()) && task_curr(p))
750 smp_send_reschedule(cpu);
754 EXPORT_SYMBOL_GPL(kick_process);
757 * Return a low guess at the load of a migration-source cpu.
759 * We want to under-estimate the load of migration sources, to
760 * balance conservatively.
762 static inline unsigned long source_load(int cpu)
764 runqueue_t *rq = cpu_rq(cpu);
765 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
767 return min(rq->cpu_load, load_now);
771 * Return a high guess at the load of a migration-target cpu
773 static inline unsigned long target_load(int cpu)
775 runqueue_t *rq = cpu_rq(cpu);
776 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
778 return max(rq->cpu_load, load_now);
784 * wake_idle() is useful especially on SMT architectures to wake a
785 * task onto an idle sibling if we would otherwise wake it onto a
788 * Returns the CPU we should wake onto.
790 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
791 static int wake_idle(int cpu, task_t *p)
794 runqueue_t *rq = cpu_rq(cpu);
795 struct sched_domain *sd;
802 if (!(sd->flags & SD_WAKE_IDLE))
805 cpus_and(tmp, sd->span, cpu_online_map);
806 cpus_and(tmp, tmp, p->cpus_allowed);
808 for_each_cpu_mask(i, tmp) {
816 static inline int wake_idle(int cpu, task_t *p)
823 * try_to_wake_up - wake up a thread
824 * @p: the to-be-woken-up thread
825 * @state: the mask of task states that can be woken
826 * @sync: do a synchronous wakeup?
828 * Put it on the run-queue if it's not already there. The "current"
829 * thread is always on the run-queue (except when the actual
830 * re-schedule is in progress), and as such you're allowed to do
831 * the simpler "current->state = TASK_RUNNING" to mark yourself
832 * runnable without the overhead of this.
834 * returns failure only if the task is already active.
836 static int try_to_wake_up(task_t * p, unsigned int state, int sync)
838 int cpu, this_cpu, success = 0;
843 unsigned long load, this_load;
844 struct sched_domain *sd;
848 rq = task_rq_lock(p, &flags);
849 old_state = p->state;
850 if (!(old_state & state))
857 this_cpu = smp_processor_id();
860 if (unlikely(task_running(rq, p)))
865 if (cpu == this_cpu || unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
868 load = source_load(cpu);
869 this_load = target_load(this_cpu);
872 * If sync wakeup then subtract the (maximum possible) effect of
873 * the currently running task from the load of the current CPU:
876 this_load -= SCHED_LOAD_SCALE;
878 /* Don't pull the task off an idle CPU to a busy one */
879 if (load < SCHED_LOAD_SCALE/2 && this_load > SCHED_LOAD_SCALE/2)
882 new_cpu = this_cpu; /* Wake to this CPU if we can */
885 * Scan domains for affine wakeup and passive balancing
888 for_each_domain(this_cpu, sd) {
889 unsigned int imbalance;
891 * Start passive balancing when half the imbalance_pct
894 imbalance = sd->imbalance_pct + (sd->imbalance_pct - 100) / 2;
896 if ( ((sd->flags & SD_WAKE_AFFINE) &&
897 !task_hot(p, rq->timestamp_last_tick, sd))
898 || ((sd->flags & SD_WAKE_BALANCE) &&
899 imbalance*this_load <= 100*load) ) {
901 * Now sd has SD_WAKE_AFFINE and p is cache cold in sd
902 * or sd has SD_WAKE_BALANCE and there is an imbalance
904 if (cpu_isset(cpu, sd->span))
909 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
911 new_cpu = wake_idle(new_cpu, p);
912 if (new_cpu != cpu && cpu_isset(new_cpu, p->cpus_allowed)) {
913 set_task_cpu(p, new_cpu);
914 task_rq_unlock(rq, &flags);
915 /* might preempt at this point */
916 rq = task_rq_lock(p, &flags);
917 old_state = p->state;
918 if (!(old_state & state))
923 this_cpu = smp_processor_id();
928 #endif /* CONFIG_SMP */
929 if (old_state == TASK_UNINTERRUPTIBLE) {
930 rq->nr_uninterruptible--;
932 * Tasks on involuntary sleep don't earn
933 * sleep_avg beyond just interactive state.
939 * Sync wakeups (i.e. those types of wakeups where the waker
940 * has indicated that it will leave the CPU in short order)
941 * don't trigger a preemption, if the woken up task will run on
942 * this cpu. (in this case the 'I will reschedule' promise of
943 * the waker guarantees that the freshly woken up task is going
944 * to be considered on this CPU.)
946 activate_task(p, rq, cpu == this_cpu);
947 if (!sync || cpu != this_cpu) {
948 if (TASK_PREEMPTS_CURR(p, rq))
949 resched_task(rq->curr);
954 p->state = TASK_RUNNING;
956 task_rq_unlock(rq, &flags);
961 int fastcall wake_up_process(task_t * p)
963 return try_to_wake_up(p, TASK_STOPPED |
964 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
967 EXPORT_SYMBOL(wake_up_process);
969 int fastcall wake_up_state(task_t *p, unsigned int state)
971 return try_to_wake_up(p, state, 0);
975 * Perform scheduler related setup for a newly forked process p.
976 * p is forked by current.
978 void fastcall sched_fork(task_t *p)
981 * We mark the process as running here, but have not actually
982 * inserted it onto the runqueue yet. This guarantees that
983 * nobody will actually run it, and a signal or other external
984 * event cannot wake it up and insert it on the runqueue either.
986 p->state = TASK_RUNNING;
987 INIT_LIST_HEAD(&p->run_list);
989 spin_lock_init(&p->switch_lock);
990 #ifdef CONFIG_PREEMPT
992 * During context-switch we hold precisely one spinlock, which
993 * schedule_tail drops. (in the common case it's this_rq()->lock,
994 * but it also can be p->switch_lock.) So we compensate with a count
995 * of 1. Also, we want to start with kernel preemption disabled.
997 p->thread_info->preempt_count = 1;
1000 * Share the timeslice between parent and child, thus the
1001 * total amount of pending timeslices in the system doesn't change,
1002 * resulting in more scheduling fairness.
1004 local_irq_disable();
1005 p->time_slice = (current->time_slice + 1) >> 1;
1007 * The remainder of the first timeslice might be recovered by
1008 * the parent if the child exits early enough.
1010 p->first_time_slice = 1;
1011 current->time_slice >>= 1;
1012 p->timestamp = sched_clock();
1013 if (!current->time_slice) {
1015 * This case is rare, it happens when the parent has only
1016 * a single jiffy left from its timeslice. Taking the
1017 * runqueue lock is not a problem.
1019 current->time_slice = 1;
1021 scheduler_tick(0, 0);
1029 * wake_up_forked_process - wake up a freshly forked process.
1031 * This function will do some initial scheduler statistics housekeeping
1032 * that must be done for every newly created process.
1034 void fastcall wake_up_forked_process(task_t * p)
1036 unsigned long flags;
1037 runqueue_t *rq = task_rq_lock(current, &flags);
1039 BUG_ON(p->state != TASK_RUNNING);
1042 * We decrease the sleep average of forking parents
1043 * and children as well, to keep max-interactive tasks
1044 * from forking tasks that are max-interactive.
1046 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1047 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1049 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1050 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1052 p->interactive_credit = 0;
1054 p->prio = effective_prio(p);
1055 set_task_cpu(p, smp_processor_id());
1057 if (unlikely(!current->array))
1058 __activate_task(p, rq);
1060 p->prio = current->prio;
1061 list_add_tail(&p->run_list, ¤t->run_list);
1062 p->array = current->array;
1063 p->array->nr_active++;
1067 task_rq_unlock(rq, &flags);
1071 * Potentially available exiting-child timeslices are
1072 * retrieved here - this way the parent does not get
1073 * penalized for creating too many threads.
1075 * (this cannot be used to 'generate' timeslices
1076 * artificially, because any timeslice recovered here
1077 * was given away by the parent in the first place.)
1079 void fastcall sched_exit(task_t * p)
1081 unsigned long flags;
1084 local_irq_save(flags);
1085 if (p->first_time_slice) {
1086 p->parent->time_slice += p->time_slice;
1087 if (unlikely(p->parent->time_slice > MAX_TIMESLICE))
1088 p->parent->time_slice = MAX_TIMESLICE;
1090 local_irq_restore(flags);
1092 * If the child was a (relative-) CPU hog then decrease
1093 * the sleep_avg of the parent as well.
1095 rq = task_rq_lock(p->parent, &flags);
1096 if (p->sleep_avg < p->parent->sleep_avg)
1097 p->parent->sleep_avg = p->parent->sleep_avg /
1098 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1100 task_rq_unlock(rq, &flags);
1104 * finish_task_switch - clean up after a task-switch
1105 * @prev: the thread we just switched away from.
1107 * We enter this with the runqueue still locked, and finish_arch_switch()
1108 * will unlock it along with doing any other architecture-specific cleanup
1111 * Note that we may have delayed dropping an mm in context_switch(). If
1112 * so, we finish that here outside of the runqueue lock. (Doing it
1113 * with the lock held can cause deadlocks; see schedule() for
1116 static void finish_task_switch(task_t *prev)
1118 runqueue_t *rq = this_rq();
1119 struct mm_struct *mm = rq->prev_mm;
1120 unsigned long prev_task_flags;
1125 * A task struct has one reference for the use as "current".
1126 * If a task dies, then it sets TASK_ZOMBIE in tsk->state and calls
1127 * schedule one last time. The schedule call will never return,
1128 * and the scheduled task must drop that reference.
1129 * The test for TASK_ZOMBIE must occur while the runqueue locks are
1130 * still held, otherwise prev could be scheduled on another cpu, die
1131 * there before we look at prev->state, and then the reference would
1133 * Manfred Spraul <manfred@colorfullife.com>
1135 prev_task_flags = prev->flags;
1136 finish_arch_switch(rq, prev);
1139 if (unlikely(prev_task_flags & PF_DEAD))
1140 put_task_struct(prev);
1144 * schedule_tail - first thing a freshly forked thread must call.
1145 * @prev: the thread we just switched away from.
1147 asmlinkage void schedule_tail(task_t *prev)
1149 finish_task_switch(prev);
1151 if (current->set_child_tid)
1152 put_user(current->pid, current->set_child_tid);
1156 * context_switch - switch to the new MM and the new
1157 * thread's register state.
1160 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1162 struct mm_struct *mm = next->mm;
1163 struct mm_struct *oldmm = prev->active_mm;
1165 if (unlikely(!mm)) {
1166 next->active_mm = oldmm;
1167 atomic_inc(&oldmm->mm_count);
1168 enter_lazy_tlb(oldmm, next);
1170 switch_mm(oldmm, mm, next);
1172 if (unlikely(!prev->mm)) {
1173 prev->active_mm = NULL;
1174 WARN_ON(rq->prev_mm);
1175 rq->prev_mm = oldmm;
1178 /* Here we just switch the register state and the stack. */
1179 switch_to(prev, next, prev);
1185 * nr_running, nr_uninterruptible and nr_context_switches:
1187 * externally visible scheduler statistics: current number of runnable
1188 * threads, current number of uninterruptible-sleeping threads, total
1189 * number of context switches performed since bootup.
1191 unsigned long nr_running(void)
1193 unsigned long i, sum = 0;
1196 sum += cpu_rq(i)->nr_running;
1201 unsigned long nr_uninterruptible(void)
1203 unsigned long i, sum = 0;
1205 for_each_online_cpu(i)
1206 sum += cpu_rq(i)->nr_uninterruptible;
1211 unsigned long long nr_context_switches(void)
1213 unsigned long long i, sum = 0;
1215 for_each_online_cpu(i)
1216 sum += cpu_rq(i)->nr_switches;
1221 unsigned long nr_iowait(void)
1223 unsigned long i, sum = 0;
1225 for_each_online_cpu(i)
1226 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1232 * double_rq_lock - safely lock two runqueues
1234 * Note this does not disable interrupts like task_rq_lock,
1235 * you need to do so manually before calling.
1237 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1240 spin_lock(&rq1->lock);
1243 spin_lock(&rq1->lock);
1244 spin_lock(&rq2->lock);
1246 spin_lock(&rq2->lock);
1247 spin_lock(&rq1->lock);
1253 * double_rq_unlock - safely unlock two runqueues
1255 * Note this does not restore interrupts like task_rq_unlock,
1256 * you need to do so manually after calling.
1258 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1260 spin_unlock(&rq1->lock);
1262 spin_unlock(&rq2->lock);
1265 unsigned long long nr_preempt(void)
1267 unsigned long long i, sum = 0;
1269 for_each_online_cpu(i)
1270 sum += cpu_rq(i)->nr_preempt;
1285 * find_idlest_cpu - find the least busy runqueue.
1287 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1288 struct sched_domain *sd)
1290 unsigned long load, min_load, this_load;
1295 min_load = ULONG_MAX;
1297 cpus_and(mask, sd->span, cpu_online_map);
1298 cpus_and(mask, mask, p->cpus_allowed);
1300 for_each_cpu_mask(i, mask) {
1301 load = target_load(i);
1303 if (load < min_load) {
1307 /* break out early on an idle CPU: */
1313 /* add +1 to account for the new task */
1314 this_load = source_load(this_cpu) + SCHED_LOAD_SCALE;
1317 * Would with the addition of the new task to the
1318 * current CPU there be an imbalance between this
1319 * CPU and the idlest CPU?
1321 * Use half of the balancing threshold - new-context is
1322 * a good opportunity to balance.
1324 if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1331 * wake_up_forked_thread - wake up a freshly forked thread.
1333 * This function will do some initial scheduler statistics housekeeping
1334 * that must be done for every newly created context, and it also does
1335 * runqueue balancing.
1337 void fastcall wake_up_forked_thread(task_t * p)
1339 unsigned long flags;
1340 int this_cpu = get_cpu(), cpu;
1341 struct sched_domain *tmp, *sd = NULL;
1342 runqueue_t *this_rq = cpu_rq(this_cpu), *rq;
1345 * Find the largest domain that this CPU is part of that
1346 * is willing to balance on clone:
1348 for_each_domain(this_cpu, tmp)
1349 if (tmp->flags & SD_BALANCE_CLONE)
1352 cpu = find_idlest_cpu(p, this_cpu, sd);
1356 local_irq_save(flags);
1359 double_rq_lock(this_rq, rq);
1361 BUG_ON(p->state != TASK_RUNNING);
1364 * We did find_idlest_cpu() unlocked, so in theory
1365 * the mask could have changed - just dont migrate
1368 if (unlikely(!cpu_isset(cpu, p->cpus_allowed))) {
1370 double_rq_unlock(this_rq, rq);
1374 * We decrease the sleep average of forking parents
1375 * and children as well, to keep max-interactive tasks
1376 * from forking tasks that are max-interactive.
1378 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1379 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1381 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1382 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1384 p->interactive_credit = 0;
1386 p->prio = effective_prio(p);
1387 set_task_cpu(p, cpu);
1389 if (cpu == this_cpu) {
1390 if (unlikely(!current->array))
1391 __activate_task(p, rq);
1393 p->prio = current->prio;
1394 list_add_tail(&p->run_list, ¤t->run_list);
1395 p->array = current->array;
1396 p->array->nr_active++;
1401 /* Not the local CPU - must adjust timestamp */
1402 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1403 + rq->timestamp_last_tick;
1404 __activate_task(p, rq);
1405 if (TASK_PREEMPTS_CURR(p, rq))
1406 resched_task(rq->curr);
1409 double_rq_unlock(this_rq, rq);
1410 local_irq_restore(flags);
1415 * If dest_cpu is allowed for this process, migrate the task to it.
1416 * This is accomplished by forcing the cpu_allowed mask to only
1417 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1418 * the cpu_allowed mask is restored.
1420 static void sched_migrate_task(task_t *p, int dest_cpu)
1422 migration_req_t req;
1424 unsigned long flags;
1426 rq = task_rq_lock(p, &flags);
1427 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1428 || unlikely(cpu_is_offline(dest_cpu)))
1431 /* force the process onto the specified CPU */
1432 if (migrate_task(p, dest_cpu, &req)) {
1433 /* Need to wait for migration thread (might exit: take ref). */
1434 struct task_struct *mt = rq->migration_thread;
1435 get_task_struct(mt);
1436 task_rq_unlock(rq, &flags);
1437 wake_up_process(mt);
1438 put_task_struct(mt);
1439 wait_for_completion(&req.done);
1443 task_rq_unlock(rq, &flags);
1447 * sched_balance_exec(): find the highest-level, exec-balance-capable
1448 * domain and try to migrate the task to the least loaded CPU.
1450 * execve() is a valuable balancing opportunity, because at this point
1451 * the task has the smallest effective memory and cache footprint.
1453 void sched_balance_exec(void)
1455 struct sched_domain *tmp, *sd = NULL;
1456 int new_cpu, this_cpu = get_cpu();
1458 /* Prefer the current CPU if there's only this task running */
1459 if (this_rq()->nr_running <= 1)
1462 for_each_domain(this_cpu, tmp)
1463 if (tmp->flags & SD_BALANCE_EXEC)
1467 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1468 if (new_cpu != this_cpu) {
1470 sched_migrate_task(current, new_cpu);
1479 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1481 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1483 if (unlikely(!spin_trylock(&busiest->lock))) {
1484 if (busiest < this_rq) {
1485 spin_unlock(&this_rq->lock);
1486 spin_lock(&busiest->lock);
1487 spin_lock(&this_rq->lock);
1489 spin_lock(&busiest->lock);
1494 * pull_task - move a task from a remote runqueue to the local runqueue.
1495 * Both runqueues must be locked.
1498 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1499 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1501 dequeue_task(p, src_array);
1502 src_rq->nr_running--;
1503 rq_load_dec(src_rq,p);
1505 set_task_cpu(p, this_cpu);
1506 this_rq->nr_running++;
1507 rq_load_inc(this_rq,p);
1508 enqueue_task(p, this_array);
1510 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1511 + this_rq->timestamp_last_tick;
1513 * Note that idle threads have a prio of MAX_PRIO, for this test
1514 * to be always true for them.
1516 if (TASK_PREEMPTS_CURR(p, this_rq))
1517 resched_task(this_rq->curr);
1521 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1524 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1525 struct sched_domain *sd, enum idle_type idle)
1528 * We do not migrate tasks that are:
1529 * 1) running (obviously), or
1530 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1531 * 3) are cache-hot on their current CPU.
1533 if (task_running(rq, p))
1535 if (!cpu_isset(this_cpu, p->cpus_allowed))
1538 /* Aggressive migration if we've failed balancing */
1539 if (idle == NEWLY_IDLE ||
1540 sd->nr_balance_failed < sd->cache_nice_tries) {
1541 if (task_hot(p, rq->timestamp_last_tick, sd))
1548 #ifdef CONFIG_CKRM_CPU_SCHEDULE
1550 struct ckrm_cpu_class *find_unbalanced_class(int busiest_cpu, int this_cpu, unsigned long *cls_imbalance)
1552 struct ckrm_cpu_class *most_unbalanced_class = NULL;
1553 struct ckrm_cpu_class *clsptr;
1554 int max_unbalance = 0;
1556 list_for_each_entry(clsptr,&active_cpu_classes,links) {
1557 struct ckrm_local_runqueue *this_lrq = get_ckrm_local_runqueue(clsptr,this_cpu);
1558 struct ckrm_local_runqueue *busiest_lrq = get_ckrm_local_runqueue(clsptr,busiest_cpu);
1559 int unbalance_degree;
1561 unbalance_degree = (local_queue_nr_running(busiest_lrq) - local_queue_nr_running(this_lrq)) * cpu_class_weight(clsptr);
1562 if (unbalance_degree >= *cls_imbalance)
1563 continue; // already looked at this class
1565 if (unbalance_degree > max_unbalance) {
1566 max_unbalance = unbalance_degree;
1567 most_unbalanced_class = clsptr;
1570 *cls_imbalance = max_unbalance;
1571 return most_unbalanced_class;
1576 * find_busiest_queue - find the busiest runqueue among the cpus in cpumask.
1578 static int find_busiest_cpu(runqueue_t *this_rq, int this_cpu, int idle,
1581 int cpu_load, load, max_load, i, busiest_cpu;
1582 runqueue_t *busiest, *rq_src;
1585 /*Hubertus ... the concept of nr_running is replace with cpu_load */
1586 cpu_load = this_rq->ckrm_cpu_load;
1592 for_each_online_cpu(i) {
1594 load = rq_src->ckrm_cpu_load;
1596 if ((load > max_load) && (rq_src != this_rq)) {
1603 if (likely(!busiest))
1606 *imbalance = max_load - cpu_load;
1608 /* It needs an at least ~25% imbalance to trigger balancing. */
1609 if (!idle && ((*imbalance)*4 < max_load)) {
1614 double_lock_balance(this_rq, busiest);
1616 * Make sure nothing changed since we checked the
1619 if (busiest->ckrm_cpu_load <= cpu_load) {
1620 spin_unlock(&busiest->lock);
1624 return (busiest ? busiest_cpu : -1);
1627 static int load_balance(int this_cpu, runqueue_t *this_rq,
1628 struct sched_domain *sd, enum idle_type idle)
1632 runqueue_t *busiest;
1633 prio_array_t *array;
1634 struct list_head *head, *curr;
1636 struct ckrm_local_runqueue * busiest_local_queue;
1637 struct ckrm_cpu_class *clsptr;
1639 unsigned long cls_imbalance; // so we can retry other classes
1641 // need to update global CVT based on local accumulated CVTs
1642 read_lock(&class_list_lock);
1643 busiest_cpu = find_busiest_cpu(this_rq, this_cpu, idle, &imbalance);
1644 if (busiest_cpu == -1)
1647 busiest = cpu_rq(busiest_cpu);
1650 * We only want to steal a number of tasks equal to 1/2 the imbalance,
1651 * otherwise we'll just shift the imbalance to the new queue:
1655 /* now find class on that runqueue with largest inbalance */
1656 cls_imbalance = 0xFFFFFFFF;
1659 clsptr = find_unbalanced_class(busiest_cpu, this_cpu, &cls_imbalance);
1663 busiest_local_queue = get_ckrm_local_runqueue(clsptr,busiest_cpu);
1664 weight = cpu_class_weight(clsptr);
1667 * We first consider expired tasks. Those will likely not be
1668 * executed in the near future, and they are most likely to
1669 * be cache-cold, thus switching CPUs has the least effect
1672 if (busiest_local_queue->expired->nr_active)
1673 array = busiest_local_queue->expired;
1675 array = busiest_local_queue->active;
1678 /* Start searching at priority 0: */
1682 idx = sched_find_first_bit(array->bitmap);
1684 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1685 if (idx >= MAX_PRIO) {
1686 if (array == busiest_local_queue->expired && busiest_local_queue->active->nr_active) {
1687 array = busiest_local_queue->active;
1690 goto retry_other_class;
1693 head = array->queue + idx;
1696 tmp = list_entry(curr, task_t, run_list);
1700 if (!can_migrate_task(tmp, busiest, this_cpu, sd,idle)) {
1706 pull_task(busiest, array, tmp, this_rq, rq_active(tmp,this_rq),this_cpu);
1708 * tmp BUG FIX: hzheng
1709 * load balancing can make the busiest local queue empty
1710 * thus it should be removed from bpt
1712 if (! local_queue_nr_running(busiest_local_queue)) {
1713 classqueue_dequeue(busiest_local_queue->classqueue,&busiest_local_queue->classqueue_linkobj);
1714 cpu_demand_event(get_rq_local_stat(busiest_local_queue,busiest_cpu),CPU_DEMAND_DEQUEUE,0);
1717 imbalance -= weight;
1718 if (!idle && (imbalance>0)) {
1725 spin_unlock(&busiest->lock);
1727 read_unlock(&class_list_lock);
1732 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
1735 #else /* CONFIG_CKRM_CPU_SCHEDULE */
1737 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1738 * as part of a balancing operation within "domain". Returns the number of
1741 * Called with both runqueues locked.
1743 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1744 unsigned long max_nr_move, struct sched_domain *sd,
1745 enum idle_type idle)
1747 prio_array_t *array, *dst_array;
1748 struct list_head *head, *curr;
1749 int idx, pulled = 0;
1752 if (max_nr_move <= 0 || busiest->nr_running <= 1)
1756 * We first consider expired tasks. Those will likely not be
1757 * executed in the near future, and they are most likely to
1758 * be cache-cold, thus switching CPUs has the least effect
1761 if (busiest->expired->nr_active) {
1762 array = busiest->expired;
1763 dst_array = this_rq->expired;
1765 array = busiest->active;
1766 dst_array = this_rq->active;
1770 /* Start searching at priority 0: */
1774 idx = sched_find_first_bit(array->bitmap);
1776 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1777 if (idx >= MAX_PRIO) {
1778 if (array == busiest->expired && busiest->active->nr_active) {
1779 array = busiest->active;
1780 dst_array = this_rq->active;
1786 head = array->queue + idx;
1789 tmp = list_entry(curr, task_t, run_list);
1793 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
1799 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
1802 /* We only want to steal up to the prescribed number of tasks. */
1803 if (pulled < max_nr_move) {
1814 * find_busiest_group finds and returns the busiest CPU group within the
1815 * domain. It calculates and returns the number of tasks which should be
1816 * moved to restore balance via the imbalance parameter.
1818 static struct sched_group *
1819 find_busiest_group(struct sched_domain *sd, int this_cpu,
1820 unsigned long *imbalance, enum idle_type idle)
1822 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
1823 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
1825 max_load = this_load = total_load = total_pwr = 0;
1833 local_group = cpu_isset(this_cpu, group->cpumask);
1835 /* Tally up the load of all CPUs in the group */
1837 cpus_and(tmp, group->cpumask, cpu_online_map);
1838 if (unlikely(cpus_empty(tmp)))
1841 for_each_cpu_mask(i, tmp) {
1842 /* Bias balancing toward cpus of our domain */
1844 load = target_load(i);
1846 load = source_load(i);
1855 total_load += avg_load;
1856 total_pwr += group->cpu_power;
1858 /* Adjust by relative CPU power of the group */
1859 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1862 this_load = avg_load;
1865 } else if (avg_load > max_load) {
1866 max_load = avg_load;
1870 group = group->next;
1871 } while (group != sd->groups);
1873 if (!busiest || this_load >= max_load)
1876 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
1878 if (this_load >= avg_load ||
1879 100*max_load <= sd->imbalance_pct*this_load)
1883 * If crash dump is in progress, this other cpu's
1884 * need to wait until it completes.
1885 * NB: this code is optimized away for kernels without
1888 if (unlikely(dump_oncpu))
1889 goto dump_scheduling_disabled;
1892 * We're trying to get all the cpus to the average_load, so we don't
1893 * want to push ourselves above the average load, nor do we wish to
1894 * reduce the max loaded cpu below the average load, as either of these
1895 * actions would just result in more rebalancing later, and ping-pong
1896 * tasks around. Thus we look for the minimum possible imbalance.
1897 * Negative imbalances (*we* are more loaded than anyone else) will
1898 * be counted as no imbalance for these purposes -- we can't fix that
1899 * by pulling tasks to us. Be careful of negative numbers as they'll
1900 * appear as very large values with unsigned longs.
1902 *imbalance = min(max_load - avg_load, avg_load - this_load);
1904 /* How much load to actually move to equalise the imbalance */
1905 *imbalance = (*imbalance * min(busiest->cpu_power, this->cpu_power))
1908 if (*imbalance < SCHED_LOAD_SCALE - 1) {
1909 unsigned long pwr_now = 0, pwr_move = 0;
1912 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
1918 * OK, we don't have enough imbalance to justify moving tasks,
1919 * however we may be able to increase total CPU power used by
1923 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
1924 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
1925 pwr_now /= SCHED_LOAD_SCALE;
1927 /* Amount of load we'd subtract */
1928 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
1930 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
1933 /* Amount of load we'd add */
1934 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
1937 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
1938 pwr_move /= SCHED_LOAD_SCALE;
1940 /* Move if we gain another 8th of a CPU worth of throughput */
1941 if (pwr_move < pwr_now + SCHED_LOAD_SCALE / 8)
1948 /* Get rid of the scaling factor, rounding down as we divide */
1949 *imbalance = (*imbalance + 1) / SCHED_LOAD_SCALE;
1954 if (busiest && (idle == NEWLY_IDLE ||
1955 (idle == IDLE && max_load > SCHED_LOAD_SCALE)) ) {
1965 * find_busiest_queue - find the busiest runqueue among the cpus in group.
1967 static runqueue_t *find_busiest_queue(struct sched_group *group)
1970 unsigned long load, max_load = 0;
1971 runqueue_t *busiest = NULL;
1974 cpus_and(tmp, group->cpumask, cpu_online_map);
1975 for_each_cpu_mask(i, tmp) {
1976 load = source_load(i);
1978 if (load > max_load) {
1980 busiest = cpu_rq(i);
1988 * Check this_cpu to ensure it is balanced within domain. Attempt to move
1989 * tasks if there is an imbalance.
1991 * Called with this_rq unlocked.
1993 static int load_balance(int this_cpu, runqueue_t *this_rq,
1994 struct sched_domain *sd, enum idle_type idle)
1996 struct sched_group *group;
1997 runqueue_t *busiest;
1998 unsigned long imbalance;
2001 spin_lock(&this_rq->lock);
2003 group = find_busiest_group(sd, this_cpu, &imbalance, idle);
2007 busiest = find_busiest_queue(group);
2011 * This should be "impossible", but since load
2012 * balancing is inherently racy and statistical,
2013 * it could happen in theory.
2015 if (unlikely(busiest == this_rq)) {
2021 if (busiest->nr_running > 1) {
2023 * Attempt to move tasks. If find_busiest_group has found
2024 * an imbalance but busiest->nr_running <= 1, the group is
2025 * still unbalanced. nr_moved simply stays zero, so it is
2026 * correctly treated as an imbalance.
2028 double_lock_balance(this_rq, busiest);
2029 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2030 imbalance, sd, idle);
2031 spin_unlock(&busiest->lock);
2033 spin_unlock(&this_rq->lock);
2036 sd->nr_balance_failed++;
2038 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2041 spin_lock(&busiest->lock);
2042 if (!busiest->active_balance) {
2043 busiest->active_balance = 1;
2044 busiest->push_cpu = this_cpu;
2047 spin_unlock(&busiest->lock);
2049 wake_up_process(busiest->migration_thread);
2052 * We've kicked active balancing, reset the failure
2055 sd->nr_balance_failed = sd->cache_nice_tries;
2058 sd->nr_balance_failed = 0;
2060 /* We were unbalanced, so reset the balancing interval */
2061 sd->balance_interval = sd->min_interval;
2066 spin_unlock(&this_rq->lock);
2068 /* tune up the balancing interval */
2069 if (sd->balance_interval < sd->max_interval)
2070 sd->balance_interval *= 2;
2076 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2077 * tasks if there is an imbalance.
2079 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2080 * this_rq is locked.
2082 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2083 struct sched_domain *sd)
2085 struct sched_group *group;
2086 runqueue_t *busiest = NULL;
2087 unsigned long imbalance;
2090 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
2094 busiest = find_busiest_queue(group);
2095 if (!busiest || busiest == this_rq)
2098 /* Attempt to move tasks */
2099 double_lock_balance(this_rq, busiest);
2101 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2102 imbalance, sd, NEWLY_IDLE);
2104 spin_unlock(&busiest->lock);
2111 * idle_balance is called by schedule() if this_cpu is about to become
2112 * idle. Attempts to pull tasks from other CPUs.
2114 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
2116 struct sched_domain *sd;
2118 for_each_domain(this_cpu, sd) {
2119 if (sd->flags & SD_BALANCE_NEWIDLE) {
2120 if (load_balance_newidle(this_cpu, this_rq, sd)) {
2121 /* We've pulled tasks over so stop searching */
2129 * active_load_balance is run by migration threads. It pushes a running
2130 * task off the cpu. It can be required to correctly have at least 1 task
2131 * running on each physical CPU where possible, and not have a physical /
2132 * logical imbalance.
2134 * Called with busiest locked.
2136 static void active_load_balance(runqueue_t *busiest, int busiest_cpu)
2138 struct sched_domain *sd;
2139 struct sched_group *group, *busy_group;
2142 if (busiest->nr_running <= 1)
2145 for_each_domain(busiest_cpu, sd)
2146 if (cpu_isset(busiest->push_cpu, sd->span))
2154 while (!cpu_isset(busiest_cpu, group->cpumask))
2155 group = group->next;
2164 if (group == busy_group)
2167 cpus_and(tmp, group->cpumask, cpu_online_map);
2168 if (!cpus_weight(tmp))
2171 for_each_cpu_mask(i, tmp) {
2177 rq = cpu_rq(push_cpu);
2180 * This condition is "impossible", but since load
2181 * balancing is inherently a bit racy and statistical,
2182 * it can trigger.. Reported by Bjorn Helgaas on a
2185 if (unlikely(busiest == rq))
2187 double_lock_balance(busiest, rq);
2188 move_tasks(rq, push_cpu, busiest, 1, sd, IDLE);
2189 spin_unlock(&rq->lock);
2191 group = group->next;
2192 } while (group != sd->groups);
2194 #endif /* CONFIG_CKRM_CPU_SCHEDULE*/
2197 * rebalance_tick will get called every timer tick, on every CPU.
2199 * It checks each scheduling domain to see if it is due to be balanced,
2200 * and initiates a balancing operation if so.
2202 * Balancing parameters are set up in arch_init_sched_domains.
2205 /* Don't have all balancing operations going off at once */
2206 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2208 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2209 enum idle_type idle)
2211 unsigned long old_load, this_load;
2212 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2213 struct sched_domain *sd;
2215 ckrm_rebalance_tick(j,this_cpu);
2217 /* Update our load */
2218 old_load = this_rq->cpu_load;
2219 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
2221 * Round up the averaging division if load is increasing. This
2222 * prevents us from getting stuck on 9 if the load is 10, for
2225 if (this_load > old_load)
2227 this_rq->cpu_load = (old_load + this_load) / 2;
2229 for_each_domain(this_cpu, sd) {
2230 unsigned long interval = sd->balance_interval;
2233 interval *= sd->busy_factor;
2235 /* scale ms to jiffies */
2236 interval = msecs_to_jiffies(interval);
2237 if (unlikely(!interval))
2240 if (j - sd->last_balance >= interval) {
2241 if (load_balance(this_cpu, this_rq, sd, idle)) {
2242 /* We've pulled tasks over so no longer idle */
2245 sd->last_balance += interval;
2251 * on UP we do not need to balance between CPUs:
2253 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2255 ckrm_rebalance_tick(jiffies,cpu);
2258 static inline void idle_balance(int cpu, runqueue_t *rq)
2263 static inline int wake_priority_sleeper(runqueue_t *rq)
2265 #ifdef CONFIG_SCHED_SMT
2267 * If an SMT sibling task has been put to sleep for priority
2268 * reasons reschedule the idle task to see if it can now run.
2270 if (rq->nr_running) {
2271 resched_task(rq->idle);
2278 DEFINE_PER_CPU(struct kernel_stat, kstat) = { { 0 } };
2280 EXPORT_PER_CPU_SYMBOL(kstat);
2283 * We place interactive tasks back into the active array, if possible.
2285 * To guarantee that this does not starve expired tasks we ignore the
2286 * interactivity of a task if the first expired task had to wait more
2287 * than a 'reasonable' amount of time. This deadline timeout is
2288 * load-dependent, as the frequency of array switched decreases with
2289 * increasing number of running tasks. We also ignore the interactivity
2290 * if a better static_prio task has expired:
2293 #ifndef CONFIG_CKRM_CPU_SCHEDULE
2294 #define EXPIRED_STARVING(rq) \
2295 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2296 (jiffies - (rq)->expired_timestamp >= \
2297 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2298 ((rq)->curr->static_prio > (rq)->best_expired_prio))
2300 #define EXPIRED_STARVING(rq) \
2301 (STARVATION_LIMIT && ((rq)->expired_timestamp && \
2302 (jiffies - (rq)->expired_timestamp >= \
2303 STARVATION_LIMIT * (local_queue_nr_running(rq)) + 1)))
2307 * This function gets called by the timer code, with HZ frequency.
2308 * We call it with interrupts disabled.
2310 * It also gets called by the fork code, when changing the parent's
2313 void scheduler_tick(int user_ticks, int sys_ticks)
2315 int cpu = smp_processor_id();
2316 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2317 runqueue_t *rq = this_rq();
2318 task_t *p = current;
2320 rq->timestamp_last_tick = sched_clock();
2322 if (rcu_pending(cpu))
2323 rcu_check_callbacks(cpu, user_ticks);
2325 /* note: this timer irq context must be accounted for as well */
2326 if (hardirq_count() - HARDIRQ_OFFSET) {
2327 cpustat->irq += sys_ticks;
2329 } else if (softirq_count()) {
2330 cpustat->softirq += sys_ticks;
2334 if (p == rq->idle) {
2335 if (!--rq->idle_tokens && !list_empty(&rq->hold_queue))
2338 if (atomic_read(&rq->nr_iowait) > 0)
2339 cpustat->iowait += sys_ticks;
2341 cpustat->idle += sys_ticks;
2342 if (wake_priority_sleeper(rq))
2344 rebalance_tick(cpu, rq, IDLE);
2347 if (TASK_NICE(p) > 0)
2348 cpustat->nice += user_ticks;
2350 cpustat->user += user_ticks;
2351 cpustat->system += sys_ticks;
2353 /* Task might have expired already, but not scheduled off yet */
2354 if (p->array != rq_active(p,rq)) {
2355 set_tsk_need_resched(p);
2358 spin_lock(&rq->lock);
2360 * The task was running during this tick - update the
2361 * time slice counter. Note: we do not update a thread's
2362 * priority until it either goes to sleep or uses up its
2363 * timeslice. This makes it possible for interactive tasks
2364 * to use up their timeslices at their highest priority levels.
2366 if (unlikely(rt_task(p))) {
2368 * RR tasks need a special form of timeslice management.
2369 * FIFO tasks have no timeslices.
2371 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2372 p->time_slice = task_timeslice(p);
2373 p->first_time_slice = 0;
2374 set_tsk_need_resched(p);
2376 /* put it at the end of the queue: */
2377 dequeue_task(p, rq_active(p,rq));
2378 enqueue_task(p, rq_active(p,rq));
2382 #warning MEF PLANETLAB: "if (vx_need_resched(p)) was if (!--p->time_slice) */"
2383 if (vx_need_resched(p)) {
2384 #ifdef CONFIG_CKRM_CPU_SCHEDULE
2385 /* Hubertus ... we can abstract this out */
2386 struct ckrm_local_runqueue* rq = get_task_class_queue(p);
2388 dequeue_task(p, rq->active);
2389 set_tsk_need_resched(p);
2390 p->prio = effective_prio(p);
2391 p->time_slice = task_timeslice(p);
2392 p->first_time_slice = 0;
2394 if (!rq->expired_timestamp)
2395 rq->expired_timestamp = jiffies;
2396 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2397 enqueue_task(p, rq->expired);
2398 if (p->static_prio < this_rq()->best_expired_prio)
2399 this_rq()->best_expired_prio = p->static_prio;
2401 enqueue_task(p, rq->active);
2404 * Prevent a too long timeslice allowing a task to monopolize
2405 * the CPU. We do this by splitting up the timeslice into
2408 * Note: this does not mean the task's timeslices expire or
2409 * get lost in any way, they just might be preempted by
2410 * another task of equal priority. (one with higher
2411 * priority would have preempted this task already.) We
2412 * requeue this task to the end of the list on this priority
2413 * level, which is in essence a round-robin of tasks with
2416 * This only applies to tasks in the interactive
2417 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2419 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2420 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2421 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2422 (p->array == rq_active(p,rq))) {
2424 dequeue_task(p, rq_active(p,rq));
2425 set_tsk_need_resched(p);
2426 p->prio = effective_prio(p);
2427 enqueue_task(p, rq_active(p,rq));
2431 spin_unlock(&rq->lock);
2433 rebalance_tick(cpu, rq, NOT_IDLE);
2436 #ifdef CONFIG_SCHED_SMT
2437 static inline void wake_sleeping_dependent(int cpu, runqueue_t *rq)
2440 struct sched_domain *sd = rq->sd;
2441 cpumask_t sibling_map;
2443 if (!(sd->flags & SD_SHARE_CPUPOWER))
2446 cpus_and(sibling_map, sd->span, cpu_online_map);
2447 for_each_cpu_mask(i, sibling_map) {
2456 * If an SMT sibling task is sleeping due to priority
2457 * reasons wake it up now.
2459 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
2460 resched_task(smt_rq->idle);
2464 static inline int dependent_sleeper(int cpu, runqueue_t *rq, task_t *p)
2466 struct sched_domain *sd = rq->sd;
2467 cpumask_t sibling_map;
2470 if (!(sd->flags & SD_SHARE_CPUPOWER))
2473 cpus_and(sibling_map, sd->span, cpu_online_map);
2474 for_each_cpu_mask(i, sibling_map) {
2482 smt_curr = smt_rq->curr;
2485 * If a user task with lower static priority than the
2486 * running task on the SMT sibling is trying to schedule,
2487 * delay it till there is proportionately less timeslice
2488 * left of the sibling task to prevent a lower priority
2489 * task from using an unfair proportion of the
2490 * physical cpu's resources. -ck
2492 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
2493 task_timeslice(p) || rt_task(smt_curr)) &&
2494 p->mm && smt_curr->mm && !rt_task(p))
2498 * Reschedule a lower priority task on the SMT sibling,
2499 * or wake it up if it has been put to sleep for priority
2502 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
2503 task_timeslice(smt_curr) || rt_task(p)) &&
2504 smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
2505 (smt_curr == smt_rq->idle && smt_rq->nr_running))
2506 resched_task(smt_curr);
2511 static inline void wake_sleeping_dependent(int cpu, runqueue_t *rq)
2515 static inline int dependent_sleeper(int cpu, runqueue_t *rq, task_t *p)
2522 * schedule() is the main scheduler function.
2524 asmlinkage void __sched schedule(void)
2527 task_t *prev, *next;
2529 prio_array_t *array;
2530 unsigned long long now;
2531 unsigned long run_time;
2533 #ifdef CONFIG_VSERVER_HARDCPU
2534 struct vx_info *vxi;
2538 //WARN_ON(system_state == SYSTEM_BOOTING);
2540 * Test if we are atomic. Since do_exit() needs to call into
2541 * schedule() atomically, we ignore that path for now.
2542 * Otherwise, whine if we are scheduling when we should not be.
2544 if (likely(!(current->state & (TASK_DEAD | TASK_ZOMBIE)))) {
2545 if (unlikely(in_atomic())) {
2546 printk(KERN_ERR "bad: scheduling while atomic!\n");
2556 release_kernel_lock(prev);
2557 now = sched_clock();
2558 if (likely(now - prev->timestamp < NS_MAX_SLEEP_AVG))
2559 run_time = now - prev->timestamp;
2561 run_time = NS_MAX_SLEEP_AVG;
2564 * Tasks with interactive credits get charged less run_time
2565 * at high sleep_avg to delay them losing their interactive
2568 if (HIGH_CREDIT(prev))
2569 run_time /= (CURRENT_BONUS(prev) ? : 1);
2571 spin_lock_irq(&rq->lock);
2574 * if entering off of a kernel preemption go straight
2575 * to picking the next task.
2577 switch_count = &prev->nivcsw;
2578 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2579 switch_count = &prev->nvcsw;
2580 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2581 unlikely(signal_pending(prev))))
2582 prev->state = TASK_RUNNING;
2584 deactivate_task(prev, rq);
2587 cpu = smp_processor_id();
2588 #ifdef CONFIG_VSERVER_HARDCPU
2589 if (!list_empty(&rq->hold_queue)) {
2590 struct list_head *l, *n;
2594 list_for_each_safe(l, n, &rq->hold_queue) {
2595 next = list_entry(l, task_t, run_list);
2596 if (vxi == next->vx_info)
2599 vxi = next->vx_info;
2600 ret = vx_tokens_recalc(vxi);
2601 // tokens = vx_tokens_avail(next);
2604 list_del(&next->run_list);
2605 next->state &= ~TASK_ONHOLD;
2606 recalc_task_prio(next, now);
2607 __activate_task(next, rq);
2608 // printk("··· unhold %p\n", next);
2611 if ((ret < 0) && (maxidle < ret))
2615 rq->idle_tokens = -maxidle;
2619 if (unlikely(!rq->nr_running)) {
2620 idle_balance(cpu, rq);
2621 if (!rq->nr_running) {
2623 rq->expired_timestamp = 0;
2624 wake_sleeping_dependent(cpu, rq);
2629 next = rq_get_next_task(rq);
2630 if (next == rq->idle)
2633 if (dependent_sleeper(cpu, rq, next)) {
2638 #ifdef CONFIG_VSERVER_HARDCPU
2639 vxi = next->vx_info;
2640 if (vxi && __vx_flags(vxi->vx_flags,
2641 VXF_SCHED_PAUSE|VXF_SCHED_HARD, 0)) {
2642 int ret = vx_tokens_recalc(vxi);
2644 if (unlikely(ret <= 0)) {
2645 if (ret && (rq->idle_tokens > -ret))
2646 rq->idle_tokens = -ret;
2647 deactivate_task(next, rq);
2648 list_add_tail(&next->run_list, &rq->hold_queue);
2649 next->state |= TASK_ONHOLD;
2655 if (!rt_task(next) && next->activated > 0) {
2656 unsigned long long delta = now - next->timestamp;
2658 if (next->activated == 1)
2659 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
2661 array = next->array;
2662 dequeue_task(next, array);
2663 recalc_task_prio(next, next->timestamp + delta);
2664 enqueue_task(next, array);
2666 next->activated = 0;
2669 if (test_and_clear_tsk_thread_flag(prev,TIF_NEED_RESCHED))
2671 RCU_qsctr(task_cpu(prev))++;
2673 #ifdef CONFIG_CKRM_CPU_SCHEDULE
2674 if (prev != rq->idle) {
2675 unsigned long long run = now - prev->timestamp;
2676 cpu_demand_event(get_task_local_stat(prev),CPU_DEMAND_DESCHEDULE,run);
2677 update_local_cvt(prev, run);
2681 prev->sleep_avg -= run_time;
2682 if ((long)prev->sleep_avg <= 0) {
2683 prev->sleep_avg = 0;
2684 if (!(HIGH_CREDIT(prev) || LOW_CREDIT(prev)))
2685 prev->interactive_credit--;
2687 add_delay_ts(prev,runcpu_total,prev->timestamp,now);
2688 prev->timestamp = now;
2690 if (likely(prev != next)) {
2691 add_delay_ts(next,waitcpu_total,next->timestamp,now);
2692 inc_delay(next,runs);
2693 next->timestamp = now;
2698 prepare_arch_switch(rq, next);
2699 prev = context_switch(rq, prev, next);
2702 finish_task_switch(prev);
2704 spin_unlock_irq(&rq->lock);
2706 reacquire_kernel_lock(current);
2707 preempt_enable_no_resched();
2708 if (test_thread_flag(TIF_NEED_RESCHED))
2713 dump_scheduling_disabled:
2714 /* allow scheduling only if this is the dumping cpu */
2715 if (dump_oncpu != smp_processor_id()+1) {
2722 EXPORT_SYMBOL(schedule);
2724 #ifdef CONFIG_PREEMPT
2726 * this is is the entry point to schedule() from in-kernel preemption
2727 * off of preempt_enable. Kernel preemptions off return from interrupt
2728 * occur there and call schedule directly.
2730 asmlinkage void __sched preempt_schedule(void)
2732 struct thread_info *ti = current_thread_info();
2735 * If there is a non-zero preempt_count or interrupts are disabled,
2736 * we do not want to preempt the current task. Just return..
2738 if (unlikely(ti->preempt_count || irqs_disabled()))
2742 ti->preempt_count = PREEMPT_ACTIVE;
2744 ti->preempt_count = 0;
2746 /* we could miss a preemption opportunity between schedule and now */
2748 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2752 EXPORT_SYMBOL(preempt_schedule);
2753 #endif /* CONFIG_PREEMPT */
2755 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
2757 task_t *p = curr->task;
2758 return try_to_wake_up(p, mode, sync);
2761 EXPORT_SYMBOL(default_wake_function);
2764 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
2765 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
2766 * number) then we wake all the non-exclusive tasks and one exclusive task.
2768 * There are circumstances in which we can try to wake a task which has already
2769 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
2770 * zero in this (rare) case, and we handle it by continuing to scan the queue.
2772 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
2773 int nr_exclusive, int sync, void *key)
2775 struct list_head *tmp, *next;
2777 list_for_each_safe(tmp, next, &q->task_list) {
2780 curr = list_entry(tmp, wait_queue_t, task_list);
2781 flags = curr->flags;
2782 if (curr->func(curr, mode, sync, key) &&
2783 (flags & WQ_FLAG_EXCLUSIVE) &&
2790 * __wake_up - wake up threads blocked on a waitqueue.
2792 * @mode: which threads
2793 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2795 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
2796 int nr_exclusive, void *key)
2798 unsigned long flags;
2800 spin_lock_irqsave(&q->lock, flags);
2801 __wake_up_common(q, mode, nr_exclusive, 0, key);
2802 spin_unlock_irqrestore(&q->lock, flags);
2805 EXPORT_SYMBOL(__wake_up);
2808 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
2810 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
2812 __wake_up_common(q, mode, 1, 0, NULL);
2816 * __wake_up - sync- wake up threads blocked on a waitqueue.
2818 * @mode: which threads
2819 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2821 * The sync wakeup differs that the waker knows that it will schedule
2822 * away soon, so while the target thread will be woken up, it will not
2823 * be migrated to another CPU - ie. the two threads are 'synchronized'
2824 * with each other. This can prevent needless bouncing between CPUs.
2826 * On UP it can prevent extra preemption.
2828 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
2830 unsigned long flags;
2836 if (unlikely(!nr_exclusive))
2839 spin_lock_irqsave(&q->lock, flags);
2840 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
2841 spin_unlock_irqrestore(&q->lock, flags);
2843 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
2845 void fastcall complete(struct completion *x)
2847 unsigned long flags;
2849 spin_lock_irqsave(&x->wait.lock, flags);
2851 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2853 spin_unlock_irqrestore(&x->wait.lock, flags);
2855 EXPORT_SYMBOL(complete);
2857 void fastcall complete_all(struct completion *x)
2859 unsigned long flags;
2861 spin_lock_irqsave(&x->wait.lock, flags);
2862 x->done += UINT_MAX/2;
2863 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2865 spin_unlock_irqrestore(&x->wait.lock, flags);
2867 EXPORT_SYMBOL(complete_all);
2869 void fastcall __sched wait_for_completion(struct completion *x)
2872 spin_lock_irq(&x->wait.lock);
2874 DECLARE_WAITQUEUE(wait, current);
2876 wait.flags |= WQ_FLAG_EXCLUSIVE;
2877 __add_wait_queue_tail(&x->wait, &wait);
2879 __set_current_state(TASK_UNINTERRUPTIBLE);
2880 spin_unlock_irq(&x->wait.lock);
2882 spin_lock_irq(&x->wait.lock);
2884 __remove_wait_queue(&x->wait, &wait);
2887 spin_unlock_irq(&x->wait.lock);
2889 EXPORT_SYMBOL(wait_for_completion);
2891 #define SLEEP_ON_VAR \
2892 unsigned long flags; \
2893 wait_queue_t wait; \
2894 init_waitqueue_entry(&wait, current);
2896 #define SLEEP_ON_HEAD \
2897 spin_lock_irqsave(&q->lock,flags); \
2898 __add_wait_queue(q, &wait); \
2899 spin_unlock(&q->lock);
2901 #define SLEEP_ON_TAIL \
2902 spin_lock_irq(&q->lock); \
2903 __remove_wait_queue(q, &wait); \
2904 spin_unlock_irqrestore(&q->lock, flags);
2906 #define SLEEP_ON_BKLCHECK \
2907 if (unlikely(!kernel_locked()) && \
2908 sleep_on_bkl_warnings < 10) { \
2909 sleep_on_bkl_warnings++; \
2913 static int sleep_on_bkl_warnings;
2915 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
2921 current->state = TASK_INTERRUPTIBLE;
2928 EXPORT_SYMBOL(interruptible_sleep_on);
2930 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
2936 current->state = TASK_INTERRUPTIBLE;
2939 timeout = schedule_timeout(timeout);
2945 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
2947 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
2953 current->state = TASK_UNINTERRUPTIBLE;
2956 timeout = schedule_timeout(timeout);
2962 EXPORT_SYMBOL(sleep_on_timeout);
2964 void set_user_nice(task_t *p, long nice)
2966 unsigned long flags;
2967 prio_array_t *array;
2969 int old_prio, new_prio, delta;
2971 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
2974 * We have to be careful, if called from sys_setpriority(),
2975 * the task might be in the middle of scheduling on another CPU.
2977 rq = task_rq_lock(p, &flags);
2979 * The RT priorities are set via setscheduler(), but we still
2980 * allow the 'normal' nice value to be set - but as expected
2981 * it wont have any effect on scheduling until the task is
2985 p->static_prio = NICE_TO_PRIO(nice);
2990 dequeue_task(p, array);
2993 new_prio = NICE_TO_PRIO(nice);
2994 delta = new_prio - old_prio;
2995 p->static_prio = NICE_TO_PRIO(nice);
2999 enqueue_task(p, array);
3001 * If the task increased its priority or is running and
3002 * lowered its priority, then reschedule its CPU:
3004 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3005 resched_task(rq->curr);
3008 task_rq_unlock(rq, &flags);
3011 EXPORT_SYMBOL(set_user_nice);
3013 #ifdef __ARCH_WANT_SYS_NICE
3016 * sys_nice - change the priority of the current process.
3017 * @increment: priority increment
3019 * sys_setpriority is a more generic, but much slower function that
3020 * does similar things.
3022 asmlinkage long sys_nice(int increment)
3028 * Setpriority might change our priority at the same moment.
3029 * We don't have to worry. Conceptually one call occurs first
3030 * and we have a single winner.
3032 if (increment < 0) {
3033 if (!capable(CAP_SYS_NICE))
3035 if (increment < -40)
3041 nice = PRIO_TO_NICE(current->static_prio) + increment;
3047 retval = security_task_setnice(current, nice);
3051 set_user_nice(current, nice);
3058 * task_prio - return the priority value of a given task.
3059 * @p: the task in question.
3061 * This is the priority value as seen by users in /proc.
3062 * RT tasks are offset by -200. Normal tasks are centered
3063 * around 0, value goes from -16 to +15.
3065 int task_prio(const task_t *p)
3067 return p->prio - MAX_RT_PRIO;
3071 * task_nice - return the nice value of a given task.
3072 * @p: the task in question.
3074 int task_nice(const task_t *p)
3076 return TASK_NICE(p);
3079 EXPORT_SYMBOL(task_nice);
3082 * idle_cpu - is a given cpu idle currently?
3083 * @cpu: the processor in question.
3085 int idle_cpu(int cpu)
3087 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3090 EXPORT_SYMBOL_GPL(idle_cpu);
3093 * find_process_by_pid - find a process with a matching PID value.
3094 * @pid: the pid in question.
3096 static inline task_t *find_process_by_pid(pid_t pid)
3098 return pid ? find_task_by_pid(pid) : current;
3101 /* Actually do priority change: must hold rq lock. */
3102 static void __setscheduler(struct task_struct *p, int policy, int prio)
3106 p->rt_priority = prio;
3107 if (policy != SCHED_NORMAL)
3108 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
3110 p->prio = p->static_prio;
3114 * setscheduler - change the scheduling policy and/or RT priority of a thread.
3116 static int setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3118 struct sched_param lp;
3119 int retval = -EINVAL;
3121 prio_array_t *array;
3122 unsigned long flags;
3126 if (!param || pid < 0)
3130 if (copy_from_user(&lp, param, sizeof(struct sched_param)))
3134 * We play safe to avoid deadlocks.
3136 read_lock_irq(&tasklist_lock);
3138 p = find_process_by_pid(pid);
3142 goto out_unlock_tasklist;
3145 * To be able to change p->policy safely, the apropriate
3146 * runqueue lock must be held.
3148 rq = task_rq_lock(p, &flags);
3154 if (policy != SCHED_FIFO && policy != SCHED_RR &&
3155 policy != SCHED_NORMAL)
3160 * Valid priorities for SCHED_FIFO and SCHED_RR are
3161 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
3164 if (lp.sched_priority < 0 || lp.sched_priority > MAX_USER_RT_PRIO-1)
3166 if ((policy == SCHED_NORMAL) != (lp.sched_priority == 0))
3170 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
3171 !capable(CAP_SYS_NICE))
3173 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3174 !capable(CAP_SYS_NICE))
3177 retval = security_task_setscheduler(p, policy, &lp);
3183 deactivate_task(p, task_rq(p));
3186 __setscheduler(p, policy, lp.sched_priority);
3188 __activate_task(p, task_rq(p));
3190 * Reschedule if we are currently running on this runqueue and
3191 * our priority decreased, or if we are not currently running on
3192 * this runqueue and our priority is higher than the current's
3194 if (task_running(rq, p)) {
3195 if (p->prio > oldprio)
3196 resched_task(rq->curr);
3197 } else if (TASK_PREEMPTS_CURR(p, rq))
3198 resched_task(rq->curr);
3202 task_rq_unlock(rq, &flags);
3203 out_unlock_tasklist:
3204 read_unlock_irq(&tasklist_lock);
3211 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3212 * @pid: the pid in question.
3213 * @policy: new policy
3214 * @param: structure containing the new RT priority.
3216 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3217 struct sched_param __user *param)
3219 return setscheduler(pid, policy, param);
3223 * sys_sched_setparam - set/change the RT priority of a thread
3224 * @pid: the pid in question.
3225 * @param: structure containing the new RT priority.
3227 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3229 return setscheduler(pid, -1, param);
3233 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3234 * @pid: the pid in question.
3236 asmlinkage long sys_sched_getscheduler(pid_t pid)
3238 int retval = -EINVAL;
3245 read_lock(&tasklist_lock);
3246 p = find_process_by_pid(pid);
3248 retval = security_task_getscheduler(p);
3252 read_unlock(&tasklist_lock);
3259 * sys_sched_getscheduler - get the RT priority of a thread
3260 * @pid: the pid in question.
3261 * @param: structure containing the RT priority.
3263 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3265 struct sched_param lp;
3266 int retval = -EINVAL;
3269 if (!param || pid < 0)
3272 read_lock(&tasklist_lock);
3273 p = find_process_by_pid(pid);
3278 retval = security_task_getscheduler(p);
3282 lp.sched_priority = p->rt_priority;
3283 read_unlock(&tasklist_lock);
3286 * This one might sleep, we cannot do it with a spinlock held ...
3288 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3294 read_unlock(&tasklist_lock);
3299 * sys_sched_setaffinity - set the cpu affinity of a process
3300 * @pid: pid of the process
3301 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3302 * @user_mask_ptr: user-space pointer to the new cpu mask
3304 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
3305 unsigned long __user *user_mask_ptr)
3311 if (len < sizeof(new_mask))
3314 if (copy_from_user(&new_mask, user_mask_ptr, sizeof(new_mask)))
3318 read_lock(&tasklist_lock);
3320 p = find_process_by_pid(pid);
3322 read_unlock(&tasklist_lock);
3323 unlock_cpu_hotplug();
3328 * It is not safe to call set_cpus_allowed with the
3329 * tasklist_lock held. We will bump the task_struct's
3330 * usage count and then drop tasklist_lock.
3333 read_unlock(&tasklist_lock);
3336 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3337 !capable(CAP_SYS_NICE))
3340 retval = set_cpus_allowed(p, new_mask);
3344 unlock_cpu_hotplug();
3349 * Represents all cpu's present in the system
3350 * In systems capable of hotplug, this map could dynamically grow
3351 * as new cpu's are detected in the system via any platform specific
3352 * method, such as ACPI for e.g.
3355 cpumask_t cpu_present_map;
3356 EXPORT_SYMBOL(cpu_present_map);
3359 cpumask_t cpu_online_map = CPU_MASK_ALL;
3360 cpumask_t cpu_possible_map = CPU_MASK_ALL;
3364 * sys_sched_getaffinity - get the cpu affinity of a process
3365 * @pid: pid of the process
3366 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3367 * @user_mask_ptr: user-space pointer to hold the current cpu mask
3369 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
3370 unsigned long __user *user_mask_ptr)
3372 unsigned int real_len;
3377 real_len = sizeof(mask);
3382 read_lock(&tasklist_lock);
3385 p = find_process_by_pid(pid);
3390 cpus_and(mask, p->cpus_allowed, cpu_possible_map);
3393 read_unlock(&tasklist_lock);
3394 unlock_cpu_hotplug();
3397 if (copy_to_user(user_mask_ptr, &mask, real_len))
3403 * sys_sched_yield - yield the current processor to other threads.
3405 * this function yields the current CPU by moving the calling thread
3406 * to the expired array. If there are no other threads running on this
3407 * CPU then this function will return.
3409 asmlinkage long sys_sched_yield(void)
3411 runqueue_t *rq = this_rq_lock();
3412 prio_array_t *array = current->array;
3413 prio_array_t *target = rq_expired(current,rq);
3416 * We implement yielding by moving the task into the expired
3419 * (special rule: RT tasks will just roundrobin in the active
3422 if (unlikely(rt_task(current)))
3423 target = rq_active(current,rq);
3425 dequeue_task(current, array);
3426 enqueue_task(current, target);
3429 * Since we are going to call schedule() anyway, there's
3430 * no need to preempt or enable interrupts:
3432 _raw_spin_unlock(&rq->lock);
3433 preempt_enable_no_resched();
3440 void __sched __cond_resched(void)
3442 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
3443 __might_sleep(__FILE__, __LINE__, 0);
3446 * The system_state check is somewhat ugly but we might be
3447 * called during early boot when we are not yet ready to reschedule.
3449 if (need_resched() && system_state >= SYSTEM_BOOTING_SCHEDULER_OK) {
3450 set_current_state(TASK_RUNNING);
3455 EXPORT_SYMBOL(__cond_resched);
3457 void __sched __cond_resched_lock(spinlock_t * lock)
3459 if (need_resched()) {
3460 _raw_spin_unlock(lock);
3461 preempt_enable_no_resched();
3462 set_current_state(TASK_RUNNING);
3468 EXPORT_SYMBOL(__cond_resched_lock);
3471 * yield - yield the current processor to other threads.
3473 * this is a shortcut for kernel-space yielding - it marks the
3474 * thread runnable and calls sys_sched_yield().
3476 void __sched yield(void)
3478 set_current_state(TASK_RUNNING);
3482 EXPORT_SYMBOL(yield);
3485 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
3486 * that process accounting knows that this is a task in IO wait state.
3488 * But don't do that if it is a deliberate, throttling IO wait (this task
3489 * has set its backing_dev_info: the queue against which it should throttle)
3491 void __sched io_schedule(void)
3493 struct runqueue *rq = this_rq();
3494 def_delay_var(dstart);
3496 start_delay_set(dstart,PF_IOWAIT);
3497 atomic_inc(&rq->nr_iowait);
3499 atomic_dec(&rq->nr_iowait);
3500 add_io_delay(dstart);
3503 EXPORT_SYMBOL(io_schedule);
3505 long __sched io_schedule_timeout(long timeout)
3507 struct runqueue *rq = this_rq();
3509 def_delay_var(dstart);
3511 start_delay_set(dstart,PF_IOWAIT);
3512 atomic_inc(&rq->nr_iowait);
3513 ret = schedule_timeout(timeout);
3514 atomic_dec(&rq->nr_iowait);
3515 add_io_delay(dstart);
3520 * sys_sched_get_priority_max - return maximum RT priority.
3521 * @policy: scheduling class.
3523 * this syscall returns the maximum rt_priority that can be used
3524 * by a given scheduling class.
3526 asmlinkage long sys_sched_get_priority_max(int policy)
3533 ret = MAX_USER_RT_PRIO-1;
3543 * sys_sched_get_priority_min - return minimum RT priority.
3544 * @policy: scheduling class.
3546 * this syscall returns the minimum rt_priority that can be used
3547 * by a given scheduling class.
3549 asmlinkage long sys_sched_get_priority_min(int policy)
3565 * sys_sched_rr_get_interval - return the default timeslice of a process.
3566 * @pid: pid of the process.
3567 * @interval: userspace pointer to the timeslice value.
3569 * this syscall writes the default timeslice value of a given process
3570 * into the user-space timespec buffer. A value of '0' means infinity.
3573 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
3575 int retval = -EINVAL;
3583 read_lock(&tasklist_lock);
3584 p = find_process_by_pid(pid);
3588 retval = security_task_getscheduler(p);
3592 jiffies_to_timespec(p->policy & SCHED_FIFO ?
3593 0 : task_timeslice(p), &t);
3594 read_unlock(&tasklist_lock);
3595 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
3599 read_unlock(&tasklist_lock);
3603 static inline struct task_struct *eldest_child(struct task_struct *p)
3605 if (list_empty(&p->children)) return NULL;
3606 return list_entry(p->children.next,struct task_struct,sibling);
3609 static inline struct task_struct *older_sibling(struct task_struct *p)
3611 if (p->sibling.prev==&p->parent->children) return NULL;
3612 return list_entry(p->sibling.prev,struct task_struct,sibling);
3615 static inline struct task_struct *younger_sibling(struct task_struct *p)
3617 if (p->sibling.next==&p->parent->children) return NULL;
3618 return list_entry(p->sibling.next,struct task_struct,sibling);
3621 static void show_task(task_t * p)
3625 unsigned long free = 0;
3626 static const char *stat_nam[] = { "R", "S", "D", "T", "Z", "W" };
3628 printk("%-13.13s ", p->comm);
3629 state = p->state ? __ffs(p->state) + 1 : 0;
3630 if (state < ARRAY_SIZE(stat_nam))
3631 printk(stat_nam[state]);
3634 #if (BITS_PER_LONG == 32)
3635 if (state == TASK_RUNNING)
3636 printk(" running ");
3638 printk(" %08lX ", thread_saved_pc(p));
3640 if (state == TASK_RUNNING)
3641 printk(" running task ");
3643 printk(" %016lx ", thread_saved_pc(p));
3645 #ifdef CONFIG_DEBUG_STACK_USAGE
3647 unsigned long * n = (unsigned long *) (p->thread_info+1);
3650 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
3653 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
3654 if ((relative = eldest_child(p)))
3655 printk("%5d ", relative->pid);
3658 if ((relative = younger_sibling(p)))
3659 printk("%7d", relative->pid);
3662 if ((relative = older_sibling(p)))
3663 printk(" %5d", relative->pid);
3667 printk(" (L-TLB)\n");
3669 printk(" (NOTLB)\n");
3671 if (state != TASK_RUNNING)
3672 show_stack(p, NULL);
3675 void show_state(void)
3679 #if (BITS_PER_LONG == 32)
3682 printk(" task PC pid father child younger older\n");
3686 printk(" task PC pid father child younger older\n");
3688 read_lock(&tasklist_lock);
3689 do_each_thread(g, p) {
3691 * reset the NMI-timeout, listing all files on a slow
3692 * console might take alot of time:
3694 touch_nmi_watchdog();
3696 } while_each_thread(g, p);
3698 read_unlock(&tasklist_lock);
3701 EXPORT_SYMBOL_GPL(show_state);
3703 void __devinit init_idle(task_t *idle, int cpu)
3705 runqueue_t *idle_rq = cpu_rq(cpu), *rq = cpu_rq(task_cpu(idle));
3706 unsigned long flags;
3708 local_irq_save(flags);
3709 double_rq_lock(idle_rq, rq);
3711 idle_rq->curr = idle_rq->idle = idle;
3712 deactivate_task(idle, rq);
3714 idle->prio = MAX_PRIO;
3715 idle->state = TASK_RUNNING;
3716 set_task_cpu(idle, cpu);
3717 double_rq_unlock(idle_rq, rq);
3718 set_tsk_need_resched(idle);
3719 local_irq_restore(flags);
3721 /* Set the preempt count _outside_ the spinlocks! */
3722 #ifdef CONFIG_PREEMPT
3723 idle->thread_info->preempt_count = (idle->lock_depth >= 0);
3725 idle->thread_info->preempt_count = 0;
3730 * In a system that switches off the HZ timer nohz_cpu_mask
3731 * indicates which cpus entered this state. This is used
3732 * in the rcu update to wait only for active cpus. For system
3733 * which do not switch off the HZ timer nohz_cpu_mask should
3734 * always be CPU_MASK_NONE.
3736 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
3740 * This is how migration works:
3742 * 1) we queue a migration_req_t structure in the source CPU's
3743 * runqueue and wake up that CPU's migration thread.
3744 * 2) we down() the locked semaphore => thread blocks.
3745 * 3) migration thread wakes up (implicitly it forces the migrated
3746 * thread off the CPU)
3747 * 4) it gets the migration request and checks whether the migrated
3748 * task is still in the wrong runqueue.
3749 * 5) if it's in the wrong runqueue then the migration thread removes
3750 * it and puts it into the right queue.
3751 * 6) migration thread up()s the semaphore.
3752 * 7) we wake up and the migration is done.
3756 * Change a given task's CPU affinity. Migrate the thread to a
3757 * proper CPU and schedule it away if the CPU it's executing on
3758 * is removed from the allowed bitmask.
3760 * NOTE: the caller must have a valid reference to the task, the
3761 * task must not exit() & deallocate itself prematurely. The
3762 * call is not atomic; no spinlocks may be held.
3764 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
3766 unsigned long flags;
3768 migration_req_t req;
3771 rq = task_rq_lock(p, &flags);
3772 if (!cpus_intersects(new_mask, cpu_online_map)) {
3777 p->cpus_allowed = new_mask;
3778 /* Can the task run on the task's current CPU? If so, we're done */
3779 if (cpu_isset(task_cpu(p), new_mask))
3782 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
3783 /* Need help from migration thread: drop lock and wait. */
3784 task_rq_unlock(rq, &flags);
3785 wake_up_process(rq->migration_thread);
3786 wait_for_completion(&req.done);
3787 tlb_migrate_finish(p->mm);
3791 task_rq_unlock(rq, &flags);
3795 EXPORT_SYMBOL_GPL(set_cpus_allowed);
3798 * Move (not current) task off this cpu, onto dest cpu. We're doing
3799 * this because either it can't run here any more (set_cpus_allowed()
3800 * away from this CPU, or CPU going down), or because we're
3801 * attempting to rebalance this task on exec (sched_balance_exec).
3803 * So we race with normal scheduler movements, but that's OK, as long
3804 * as the task is no longer on this CPU.
3806 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
3808 runqueue_t *rq_dest, *rq_src;
3810 if (unlikely(cpu_is_offline(dest_cpu)))
3813 rq_src = cpu_rq(src_cpu);
3814 rq_dest = cpu_rq(dest_cpu);
3816 double_rq_lock(rq_src, rq_dest);
3817 /* Already moved. */
3818 if (task_cpu(p) != src_cpu)
3820 /* Affinity changed (again). */
3821 if (!cpu_isset(dest_cpu, p->cpus_allowed))
3824 set_task_cpu(p, dest_cpu);
3827 * Sync timestamp with rq_dest's before activating.
3828 * The same thing could be achieved by doing this step
3829 * afterwards, and pretending it was a local activate.
3830 * This way is cleaner and logically correct.
3832 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
3833 + rq_dest->timestamp_last_tick;
3834 deactivate_task(p, rq_src);
3835 activate_task(p, rq_dest, 0);
3836 if (TASK_PREEMPTS_CURR(p, rq_dest))
3837 resched_task(rq_dest->curr);
3841 double_rq_unlock(rq_src, rq_dest);
3845 * migration_thread - this is a highprio system thread that performs
3846 * thread migration by bumping thread off CPU then 'pushing' onto
3849 static int migration_thread(void * data)
3852 int cpu = (long)data;
3855 BUG_ON(rq->migration_thread != current);
3857 set_current_state(TASK_INTERRUPTIBLE);
3858 while (!kthread_should_stop()) {
3859 struct list_head *head;
3860 migration_req_t *req;
3862 if (current->flags & PF_FREEZE)
3863 refrigerator(PF_FREEZE);
3865 spin_lock_irq(&rq->lock);
3867 if (cpu_is_offline(cpu)) {
3868 spin_unlock_irq(&rq->lock);
3872 if (rq->active_balance) {
3873 #ifndef CONFIG_CKRM_CPU_SCHEDULE
3874 active_load_balance(rq, cpu);
3876 rq->active_balance = 0;
3879 head = &rq->migration_queue;
3881 if (list_empty(head)) {
3882 spin_unlock_irq(&rq->lock);
3884 set_current_state(TASK_INTERRUPTIBLE);
3887 req = list_entry(head->next, migration_req_t, list);
3888 list_del_init(head->next);
3890 if (req->type == REQ_MOVE_TASK) {
3891 spin_unlock(&rq->lock);
3892 __migrate_task(req->task, smp_processor_id(),
3895 } else if (req->type == REQ_SET_DOMAIN) {
3897 spin_unlock_irq(&rq->lock);
3899 spin_unlock_irq(&rq->lock);
3903 complete(&req->done);
3905 __set_current_state(TASK_RUNNING);
3909 /* Wait for kthread_stop */
3910 set_current_state(TASK_INTERRUPTIBLE);
3911 while (!kthread_should_stop()) {
3913 set_current_state(TASK_INTERRUPTIBLE);
3915 __set_current_state(TASK_RUNNING);
3919 #ifdef CONFIG_HOTPLUG_CPU
3920 /* migrate_all_tasks - function to migrate all tasks from the dead cpu. */
3921 static void migrate_all_tasks(int src_cpu)
3923 struct task_struct *tsk, *t;
3927 write_lock_irq(&tasklist_lock);
3929 /* watch out for per node tasks, let's stay on this node */
3930 node = cpu_to_node(src_cpu);
3932 do_each_thread(t, tsk) {
3937 if (task_cpu(tsk) != src_cpu)
3940 /* Figure out where this task should go (attempting to
3941 * keep it on-node), and check if it can be migrated
3942 * as-is. NOTE that kernel threads bound to more than
3943 * one online cpu will be migrated. */
3944 mask = node_to_cpumask(node);
3945 cpus_and(mask, mask, tsk->cpus_allowed);
3946 dest_cpu = any_online_cpu(mask);
3947 if (dest_cpu == NR_CPUS)
3948 dest_cpu = any_online_cpu(tsk->cpus_allowed);
3949 if (dest_cpu == NR_CPUS) {
3950 cpus_setall(tsk->cpus_allowed);
3951 dest_cpu = any_online_cpu(tsk->cpus_allowed);
3953 /* Don't tell them about moving exiting tasks
3954 or kernel threads (both mm NULL), since
3955 they never leave kernel. */
3956 if (tsk->mm && printk_ratelimit())
3957 printk(KERN_INFO "process %d (%s) no "
3958 "longer affine to cpu%d\n",
3959 tsk->pid, tsk->comm, src_cpu);
3962 __migrate_task(tsk, src_cpu, dest_cpu);
3963 } while_each_thread(t, tsk);
3965 write_unlock_irq(&tasklist_lock);
3968 /* Schedules idle task to be the next runnable task on current CPU.
3969 * It does so by boosting its priority to highest possible and adding it to
3970 * the _front_ of runqueue. Used by CPU offline code.
3972 void sched_idle_next(void)
3974 int cpu = smp_processor_id();
3975 runqueue_t *rq = this_rq();
3976 struct task_struct *p = rq->idle;
3977 unsigned long flags;
3979 /* cpu has to be offline */
3980 BUG_ON(cpu_online(cpu));
3982 /* Strictly not necessary since rest of the CPUs are stopped by now
3983 * and interrupts disabled on current cpu.
3985 spin_lock_irqsave(&rq->lock, flags);
3987 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
3988 /* Add idle task to _front_ of it's priority queue */
3989 __activate_idle_task(p, rq);
3991 spin_unlock_irqrestore(&rq->lock, flags);
3993 #endif /* CONFIG_HOTPLUG_CPU */
3996 * migration_call - callback that gets triggered when a CPU is added.
3997 * Here we can start up the necessary migration thread for the new CPU.
3999 static int migration_call(struct notifier_block *nfb, unsigned long action,
4002 int cpu = (long)hcpu;
4003 struct task_struct *p;
4004 struct runqueue *rq;
4005 unsigned long flags;
4008 case CPU_UP_PREPARE:
4009 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4012 p->flags |= PF_NOFREEZE;
4013 kthread_bind(p, cpu);
4014 /* Must be high prio: stop_machine expects to yield to it. */
4015 rq = task_rq_lock(p, &flags);
4016 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4017 task_rq_unlock(rq, &flags);
4018 cpu_rq(cpu)->migration_thread = p;
4021 /* Strictly unneccessary, as first user will wake it. */
4022 wake_up_process(cpu_rq(cpu)->migration_thread);
4024 #ifdef CONFIG_HOTPLUG_CPU
4025 case CPU_UP_CANCELED:
4026 /* Unbind it from offline cpu so it can run. Fall thru. */
4027 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
4028 kthread_stop(cpu_rq(cpu)->migration_thread);
4029 cpu_rq(cpu)->migration_thread = NULL;
4032 migrate_all_tasks(cpu);
4034 kthread_stop(rq->migration_thread);
4035 rq->migration_thread = NULL;
4036 /* Idle task back to normal (off runqueue, low prio) */
4037 rq = task_rq_lock(rq->idle, &flags);
4038 deactivate_task(rq->idle, rq);
4039 rq->idle->static_prio = MAX_PRIO;
4040 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4041 task_rq_unlock(rq, &flags);
4042 BUG_ON(rq->nr_running != 0);
4044 /* No need to migrate the tasks: it was best-effort if
4045 * they didn't do lock_cpu_hotplug(). Just wake up
4046 * the requestors. */
4047 spin_lock_irq(&rq->lock);
4048 while (!list_empty(&rq->migration_queue)) {
4049 migration_req_t *req;
4050 req = list_entry(rq->migration_queue.next,
4051 migration_req_t, list);
4052 BUG_ON(req->type != REQ_MOVE_TASK);
4053 list_del_init(&req->list);
4054 complete(&req->done);
4056 spin_unlock_irq(&rq->lock);
4063 /* Register at highest priority so that task migration (migrate_all_tasks)
4064 * happens before everything else.
4066 static struct notifier_block __devinitdata migration_notifier = {
4067 .notifier_call = migration_call,
4071 int __init migration_init(void)
4073 void *cpu = (void *)(long)smp_processor_id();
4074 /* Start one for boot CPU. */
4075 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4076 migration_call(&migration_notifier, CPU_ONLINE, cpu);
4077 register_cpu_notifier(&migration_notifier);
4083 * The 'big kernel lock'
4085 * This spinlock is taken and released recursively by lock_kernel()
4086 * and unlock_kernel(). It is transparently dropped and reaquired
4087 * over schedule(). It is used to protect legacy code that hasn't
4088 * been migrated to a proper locking design yet.
4090 * Don't use in new code.
4092 * Note: spinlock debugging needs this even on !CONFIG_SMP.
4094 spinlock_t kernel_flag __cacheline_aligned_in_smp = SPIN_LOCK_UNLOCKED;
4095 EXPORT_SYMBOL(kernel_flag);
4098 /* Attach the domain 'sd' to 'cpu' as its base domain */
4099 void cpu_attach_domain(struct sched_domain *sd, int cpu)
4101 migration_req_t req;
4102 unsigned long flags;
4103 runqueue_t *rq = cpu_rq(cpu);
4108 spin_lock_irqsave(&rq->lock, flags);
4110 if (cpu == smp_processor_id() || !cpu_online(cpu)) {
4113 init_completion(&req.done);
4114 req.type = REQ_SET_DOMAIN;
4116 list_add(&req.list, &rq->migration_queue);
4120 spin_unlock_irqrestore(&rq->lock, flags);
4123 wake_up_process(rq->migration_thread);
4124 wait_for_completion(&req.done);
4127 unlock_cpu_hotplug();
4130 #ifdef ARCH_HAS_SCHED_DOMAIN
4131 extern void __init arch_init_sched_domains(void);
4133 static struct sched_group sched_group_cpus[NR_CPUS];
4134 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
4136 static struct sched_group sched_group_nodes[MAX_NUMNODES];
4137 static DEFINE_PER_CPU(struct sched_domain, node_domains);
4138 static void __init arch_init_sched_domains(void)
4141 struct sched_group *first_node = NULL, *last_node = NULL;
4143 /* Set up domains */
4145 int node = cpu_to_node(i);
4146 cpumask_t nodemask = node_to_cpumask(node);
4147 struct sched_domain *node_sd = &per_cpu(node_domains, i);
4148 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
4150 *node_sd = SD_NODE_INIT;
4151 node_sd->span = cpu_possible_map;
4152 node_sd->groups = &sched_group_nodes[cpu_to_node(i)];
4154 *cpu_sd = SD_CPU_INIT;
4155 cpus_and(cpu_sd->span, nodemask, cpu_possible_map);
4156 cpu_sd->groups = &sched_group_cpus[i];
4157 cpu_sd->parent = node_sd;
4161 for (i = 0; i < MAX_NUMNODES; i++) {
4162 cpumask_t tmp = node_to_cpumask(i);
4164 struct sched_group *first_cpu = NULL, *last_cpu = NULL;
4165 struct sched_group *node = &sched_group_nodes[i];
4168 cpus_and(nodemask, tmp, cpu_possible_map);
4170 if (cpus_empty(nodemask))
4173 node->cpumask = nodemask;
4174 node->cpu_power = SCHED_LOAD_SCALE * cpus_weight(node->cpumask);
4176 for_each_cpu_mask(j, node->cpumask) {
4177 struct sched_group *cpu = &sched_group_cpus[j];
4179 cpus_clear(cpu->cpumask);
4180 cpu_set(j, cpu->cpumask);
4181 cpu->cpu_power = SCHED_LOAD_SCALE;
4186 last_cpu->next = cpu;
4189 last_cpu->next = first_cpu;
4194 last_node->next = node;
4197 last_node->next = first_node;
4201 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
4202 cpu_attach_domain(cpu_sd, i);
4206 #else /* !CONFIG_NUMA */
4207 static void __init arch_init_sched_domains(void)
4210 struct sched_group *first_cpu = NULL, *last_cpu = NULL;
4212 /* Set up domains */
4214 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
4216 *cpu_sd = SD_CPU_INIT;
4217 cpu_sd->span = cpu_possible_map;
4218 cpu_sd->groups = &sched_group_cpus[i];
4221 /* Set up CPU groups */
4222 for_each_cpu_mask(i, cpu_possible_map) {
4223 struct sched_group *cpu = &sched_group_cpus[i];
4225 cpus_clear(cpu->cpumask);
4226 cpu_set(i, cpu->cpumask);
4227 cpu->cpu_power = SCHED_LOAD_SCALE;
4232 last_cpu->next = cpu;
4235 last_cpu->next = first_cpu;
4237 mb(); /* domains were modified outside the lock */
4239 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
4240 cpu_attach_domain(cpu_sd, i);
4244 #endif /* CONFIG_NUMA */
4245 #endif /* ARCH_HAS_SCHED_DOMAIN */
4247 #define SCHED_DOMAIN_DEBUG
4248 #ifdef SCHED_DOMAIN_DEBUG
4249 void sched_domain_debug(void)
4254 runqueue_t *rq = cpu_rq(i);
4255 struct sched_domain *sd;
4260 printk(KERN_DEBUG "CPU%d: %s\n",
4261 i, (cpu_online(i) ? " online" : "offline"));
4266 struct sched_group *group = sd->groups;
4267 cpumask_t groupmask;
4269 cpumask_scnprintf(str, NR_CPUS, sd->span);
4270 cpus_clear(groupmask);
4273 for (j = 0; j < level + 1; j++)
4275 printk("domain %d: span %s\n", level, str);
4277 if (!cpu_isset(i, sd->span))
4278 printk(KERN_DEBUG "ERROR domain->span does not contain CPU%d\n", i);
4279 if (!cpu_isset(i, group->cpumask))
4280 printk(KERN_DEBUG "ERROR domain->groups does not contain CPU%d\n", i);
4281 if (!group->cpu_power)
4282 printk(KERN_DEBUG "ERROR domain->cpu_power not set\n");
4285 for (j = 0; j < level + 2; j++)
4290 printk(" ERROR: NULL");
4294 if (!cpus_weight(group->cpumask))
4295 printk(" ERROR empty group:");
4297 if (cpus_intersects(groupmask, group->cpumask))
4298 printk(" ERROR repeated CPUs:");
4300 cpus_or(groupmask, groupmask, group->cpumask);
4302 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
4305 group = group->next;
4306 } while (group != sd->groups);
4309 if (!cpus_equal(sd->span, groupmask))
4310 printk(KERN_DEBUG "ERROR groups don't span domain->span\n");
4316 if (!cpus_subset(groupmask, sd->span))
4317 printk(KERN_DEBUG "ERROR parent span is not a superset of domain->span\n");
4324 #define sched_domain_debug() {}
4327 void __init sched_init_smp(void)
4329 arch_init_sched_domains();
4330 sched_domain_debug();
4333 void __init sched_init_smp(void)
4336 #endif /* CONFIG_SMP */
4338 int in_sched_functions(unsigned long addr)
4340 /* Linker adds these: start and end of __sched functions */
4341 extern char __sched_text_start[], __sched_text_end[];
4342 return addr >= (unsigned long)__sched_text_start
4343 && addr < (unsigned long)__sched_text_end;
4346 void __init sched_init(void)
4350 #ifndef CONFIG_CKRM_CPU_SCHEDULE
4355 /* Set up an initial dummy domain for early boot */
4356 static struct sched_domain sched_domain_init;
4357 static struct sched_group sched_group_init;
4359 memset(&sched_domain_init, 0, sizeof(struct sched_domain));
4360 sched_domain_init.span = CPU_MASK_ALL;
4361 sched_domain_init.groups = &sched_group_init;
4362 sched_domain_init.last_balance = jiffies;
4363 sched_domain_init.balance_interval = INT_MAX; /* Don't balance */
4365 memset(&sched_group_init, 0, sizeof(struct sched_group));
4366 sched_group_init.cpumask = CPU_MASK_ALL;
4367 sched_group_init.next = &sched_group_init;
4368 sched_group_init.cpu_power = SCHED_LOAD_SCALE;
4373 for (i = 0; i < NR_CPUS; i++) {
4374 #ifndef CONFIG_CKRM_CPU_SCHEDULE
4375 prio_array_t *array;
4378 spin_lock_init(&rq->lock);
4380 #ifndef CONFIG_CKRM_CPU_SCHEDULE
4381 rq->active = rq->arrays;
4382 rq->expired = rq->arrays + 1;
4384 rq->ckrm_cpu_load = 0;
4386 rq->best_expired_prio = MAX_PRIO;
4389 rq->sd = &sched_domain_init;
4391 rq->active_balance = 0;
4393 rq->migration_thread = NULL;
4394 INIT_LIST_HEAD(&rq->migration_queue);
4396 INIT_LIST_HEAD(&rq->hold_queue);
4397 atomic_set(&rq->nr_iowait, 0);
4399 #ifndef CONFIG_CKRM_CPU_SCHEDULE
4400 for (j = 0; j < 2; j++) {
4401 array = rq->arrays + j;
4402 for (k = 0; k < MAX_PRIO; k++) {
4403 INIT_LIST_HEAD(array->queue + k);
4404 __clear_bit(k, array->bitmap);
4406 // delimiter for bitsearch
4407 __set_bit(MAX_PRIO, array->bitmap);
4413 * We have to do a little magic to get the first
4414 * thread right in SMP mode.
4419 set_task_cpu(current, smp_processor_id());
4420 #ifdef CONFIG_CKRM_CPU_SCHEDULE
4421 current->cpu_class = default_cpu_class;
4422 current->array = NULL;
4424 wake_up_forked_process(current);
4427 * The boot idle thread does lazy MMU switching as well:
4429 atomic_inc(&init_mm.mm_count);
4430 enter_lazy_tlb(&init_mm, current);
4433 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4434 void __might_sleep(char *file, int line, int atomic_depth)
4436 #if defined(in_atomic)
4437 static unsigned long prev_jiffy; /* ratelimiting */
4439 #ifndef CONFIG_PREEMPT
4442 if (((in_atomic() != atomic_depth) || irqs_disabled()) &&
4443 system_state == SYSTEM_RUNNING) {
4444 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
4446 prev_jiffy = jiffies;
4447 printk(KERN_ERR "Debug: sleeping function called from invalid"
4448 " context at %s:%d\n", file, line);
4449 printk("in_atomic():%d[expected: %d], irqs_disabled():%d\n",
4450 in_atomic(), atomic_depth, irqs_disabled());
4455 EXPORT_SYMBOL(__might_sleep);
4459 #if defined(CONFIG_SMP) && defined(CONFIG_PREEMPT)
4461 * This could be a long-held lock. If another CPU holds it for a long time,
4462 * and that CPU is not asked to reschedule then *this* CPU will spin on the
4463 * lock for a long time, even if *this* CPU is asked to reschedule.
4465 * So what we do here, in the slow (contended) path is to spin on the lock by
4466 * hand while permitting preemption.
4468 * Called inside preempt_disable().
4470 void __sched __preempt_spin_lock(spinlock_t *lock)
4472 if (preempt_count() > 1) {
4473 _raw_spin_lock(lock);
4478 while (spin_is_locked(lock))
4481 } while (!_raw_spin_trylock(lock));
4484 EXPORT_SYMBOL(__preempt_spin_lock);
4486 void __sched __preempt_write_lock(rwlock_t *lock)
4488 if (preempt_count() > 1) {
4489 _raw_write_lock(lock);
4495 while (rwlock_is_locked(lock))
4498 } while (!_raw_write_trylock(lock));
4501 EXPORT_SYMBOL(__preempt_write_lock);
4502 #endif /* defined(CONFIG_SMP) && defined(CONFIG_PREEMPT) */
4504 #ifdef CONFIG_DELAY_ACCT
4505 int task_running_sys(struct task_struct *p)
4507 return task_running(task_rq(p),p);
4509 EXPORT_SYMBOL(task_running_sys);
4512 #ifdef CONFIG_CKRM_CPU_SCHEDULE
4514 * return the classqueue object of a certain processor
4515 * Note: not supposed to be used in performance sensitive functions
4517 struct classqueue_struct * get_cpu_classqueue(int cpu)
4519 return (& (cpu_rq(cpu)->classqueue) );