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)
166 #ifdef CONFIG_CKRM_CPU_SCHEDULE
168 * if belong to different class, compare class priority
169 * otherwise compare task priority
171 #define TASK_PREEMPTS_CURR(p, rq) \
172 ( ((p)->cpu_class != (rq)->curr->cpu_class) \
173 && ((rq)->curr != (rq)->idle) && ((p) != (rq)->idle )) \
174 ? class_preempts_curr((p),(rq)->curr) \
175 : ((p)->prio < (rq)->curr->prio)
177 #define TASK_PREEMPTS_CURR(p, rq) \
178 ((p)->prio < (rq)->curr->prio)
182 * BASE_TIMESLICE scales user-nice values [ -20 ... 19 ]
183 * to time slice values.
185 * The higher a thread's priority, the bigger timeslices
186 * it gets during one round of execution. But even the lowest
187 * priority thread gets MIN_TIMESLICE worth of execution time.
189 * task_timeslice() is the interface that is used by the scheduler.
192 #define BASE_TIMESLICE(p) (MIN_TIMESLICE + \
193 ((MAX_TIMESLICE - MIN_TIMESLICE) * \
194 (MAX_PRIO-1 - (p)->static_prio) / (MAX_USER_PRIO-1)))
196 unsigned int task_timeslice(task_t *p)
198 return BASE_TIMESLICE(p);
201 #define task_hot(p, now, sd) ((now) - (p)->timestamp < (sd)->cache_hot_time)
204 * These are the runqueue data structures:
207 typedef struct runqueue runqueue_t;
208 #include <linux/ckrm_classqueue.h>
209 #include <linux/ckrm_sched.h>
212 * This is the main, per-CPU runqueue data structure.
214 * Locking rule: those places that want to lock multiple runqueues
215 * (such as the load balancing or the thread migration code), lock
216 * acquire operations must be ordered by ascending &runqueue.
222 * nr_running and cpu_load should be in the same cacheline because
223 * remote CPUs use both these fields when doing load calculation.
225 unsigned long nr_running;
226 #if defined(CONFIG_SMP)
227 unsigned long cpu_load;
229 unsigned long long nr_switches, nr_preempt;
230 unsigned long expired_timestamp, nr_uninterruptible;
231 unsigned long long timestamp_last_tick;
233 struct mm_struct *prev_mm;
234 #ifdef CONFIG_CKRM_CPU_SCHEDULE
235 struct classqueue_struct classqueue;
236 ckrm_load_t ckrm_load;
238 prio_array_t *active, *expired, arrays[2];
240 int best_expired_prio;
244 struct sched_domain *sd;
246 /* For active balancing */
250 task_t *migration_thread;
251 struct list_head migration_queue;
254 #ifdef CONFIG_VSERVER_HARDCPU
255 struct list_head hold_queue;
260 static DEFINE_PER_CPU(struct runqueue, runqueues);
262 #define for_each_domain(cpu, domain) \
263 for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
265 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
266 #define this_rq() (&__get_cpu_var(runqueues))
267 #define task_rq(p) cpu_rq(task_cpu(p))
268 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
271 * Default context-switch locking:
273 #ifndef prepare_arch_switch
274 # define prepare_arch_switch(rq, next) do { } while (0)
275 # define finish_arch_switch(rq, next) spin_unlock_irq(&(rq)->lock)
276 # define task_running(rq, p) ((rq)->curr == (p))
280 * task_rq_lock - lock the runqueue a given task resides on and disable
281 * interrupts. Note the ordering: we can safely lookup the task_rq without
282 * explicitly disabling preemption.
284 static runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
289 local_irq_save(*flags);
291 spin_lock(&rq->lock);
292 if (unlikely(rq != task_rq(p))) {
293 spin_unlock_irqrestore(&rq->lock, *flags);
294 goto repeat_lock_task;
299 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
301 spin_unlock_irqrestore(&rq->lock, *flags);
305 * rq_lock - lock a given runqueue and disable interrupts.
307 static runqueue_t *this_rq_lock(void)
313 spin_lock(&rq->lock);
318 static inline void rq_unlock(runqueue_t *rq)
320 spin_unlock_irq(&rq->lock);
323 #ifdef CONFIG_CKRM_CPU_SCHEDULE
324 static inline ckrm_lrq_t *rq_get_next_class(struct runqueue *rq)
326 cq_node_t *node = classqueue_get_head(&rq->classqueue);
327 return ((node) ? class_list_entry(node) : NULL);
331 * return the cvt of the current running class
332 * if no current running class, return 0
333 * assume cpu is valid (cpu_online(cpu) == 1)
335 CVT_t get_local_cur_cvt(int cpu)
337 ckrm_lrq_t * lrq = rq_get_next_class(cpu_rq(cpu));
340 return lrq->local_cvt;
345 static inline struct task_struct * rq_get_next_task(struct runqueue* rq)
348 struct task_struct *next;
351 int cpu = smp_processor_id();
355 if ((queue = rq_get_next_class(rq))) {
356 //check switch active/expired queue
357 array = queue->active;
358 if (unlikely(!array->nr_active)) {
359 queue->active = queue->expired;
360 queue->expired = array;
361 queue->expired_timestamp = 0;
363 if (queue->active->nr_active)
364 set_top_priority(queue,
365 find_first_bit(queue->active->bitmap, MAX_PRIO));
367 classqueue_dequeue(queue->classqueue,
368 &queue->classqueue_linkobj);
369 cpu_demand_event(get_rq_local_stat(queue,cpu),CPU_DEMAND_DEQUEUE,0);
371 goto retry_next_class;
373 BUG_ON(!array->nr_active);
375 idx = queue->top_priority;
376 if (queue->top_priority == MAX_PRIO) {
380 next = task_list_entry(array->queue[idx].next);
384 #else /*! CONFIG_CKRM_CPU_SCHEDULE*/
385 static inline struct task_struct * rq_get_next_task(struct runqueue* rq)
388 struct list_head *queue;
392 if (unlikely(!array->nr_active)) {
394 * Switch the active and expired arrays.
396 rq->active = rq->expired;
399 rq->expired_timestamp = 0;
400 rq->best_expired_prio = MAX_PRIO;
403 idx = sched_find_first_bit(array->bitmap);
404 queue = array->queue + idx;
405 return list_entry(queue->next, task_t, run_list);
408 static inline void class_enqueue_task(struct task_struct* p, prio_array_t *array) { }
409 static inline void class_dequeue_task(struct task_struct* p, prio_array_t *array) { }
410 static inline void init_cpu_classes(void) { }
411 #define rq_ckrm_load(rq) NULL
412 static inline void ckrm_sched_tick(int j,int this_cpu,void* name) {}
413 #endif /* CONFIG_CKRM_CPU_SCHEDULE */
416 * Adding/removing a task to/from a priority array:
418 static void dequeue_task(struct task_struct *p, prio_array_t *array)
422 list_del(&p->run_list);
423 if (list_empty(array->queue + p->prio))
424 __clear_bit(p->prio, array->bitmap);
425 class_dequeue_task(p,array);
428 static void enqueue_task(struct task_struct *p, prio_array_t *array)
430 list_add_tail(&p->run_list, array->queue + p->prio);
431 __set_bit(p->prio, array->bitmap);
434 class_enqueue_task(p,array);
438 * Used by the migration code - we pull tasks from the head of the
439 * remote queue so we want these tasks to show up at the head of the
442 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
444 list_add(&p->run_list, array->queue + p->prio);
445 __set_bit(p->prio, array->bitmap);
448 class_enqueue_task(p,array);
452 * effective_prio - return the priority that is based on the static
453 * priority but is modified by bonuses/penalties.
455 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
456 * into the -5 ... 0 ... +5 bonus/penalty range.
458 * We use 25% of the full 0...39 priority range so that:
460 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
461 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
463 * Both properties are important to certain workloads.
465 static int effective_prio(task_t *p)
472 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
474 prio = p->static_prio - bonus;
475 if (__vx_task_flags(p, VXF_SCHED_PRIO, 0))
476 prio += effective_vavavoom(p, MAX_USER_PRIO);
478 if (prio < MAX_RT_PRIO)
480 if (prio > MAX_PRIO-1)
486 * __activate_task - move a task to the runqueue.
488 static inline void __activate_task(task_t *p, runqueue_t *rq)
490 enqueue_task(p, rq_active(p,rq));
495 * __activate_idle_task - move idle task to the _front_ of runqueue.
497 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
499 enqueue_task_head(p, rq_active(p,rq));
503 static void recalc_task_prio(task_t *p, unsigned long long now)
505 unsigned long long __sleep_time = now - p->timestamp;
506 unsigned long sleep_time;
508 if (__sleep_time > NS_MAX_SLEEP_AVG)
509 sleep_time = NS_MAX_SLEEP_AVG;
511 sleep_time = (unsigned long)__sleep_time;
513 if (likely(sleep_time > 0)) {
515 * User tasks that sleep a long time are categorised as
516 * idle and will get just interactive status to stay active &
517 * prevent them suddenly becoming cpu hogs and starving
520 if (p->mm && p->activated != -1 &&
521 sleep_time > INTERACTIVE_SLEEP(p)) {
522 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
525 p->interactive_credit++;
528 * The lower the sleep avg a task has the more
529 * rapidly it will rise with sleep time.
531 sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
534 * Tasks with low interactive_credit are limited to
535 * one timeslice worth of sleep avg bonus.
538 sleep_time > JIFFIES_TO_NS(task_timeslice(p)))
539 sleep_time = JIFFIES_TO_NS(task_timeslice(p));
542 * Non high_credit tasks waking from uninterruptible
543 * sleep are limited in their sleep_avg rise as they
544 * are likely to be cpu hogs waiting on I/O
546 if (p->activated == -1 && !HIGH_CREDIT(p) && p->mm) {
547 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
549 else if (p->sleep_avg + sleep_time >=
550 INTERACTIVE_SLEEP(p)) {
551 p->sleep_avg = INTERACTIVE_SLEEP(p);
557 * This code gives a bonus to interactive tasks.
559 * The boost works by updating the 'average sleep time'
560 * value here, based on ->timestamp. The more time a
561 * task spends sleeping, the higher the average gets -
562 * and the higher the priority boost gets as well.
564 p->sleep_avg += sleep_time;
566 if (p->sleep_avg > NS_MAX_SLEEP_AVG) {
567 p->sleep_avg = NS_MAX_SLEEP_AVG;
569 p->interactive_credit++;
574 p->prio = effective_prio(p);
578 * activate_task - move a task to the runqueue and do priority recalculation
580 * Update all the scheduling statistics stuff. (sleep average
581 * calculation, priority modifiers, etc.)
583 static void activate_task(task_t *p, runqueue_t *rq, int local)
585 unsigned long long now;
590 /* Compensate for drifting sched_clock */
591 runqueue_t *this_rq = this_rq();
592 now = (now - this_rq->timestamp_last_tick)
593 + rq->timestamp_last_tick;
597 recalc_task_prio(p, now);
600 * This checks to make sure it's not an uninterruptible task
601 * that is now waking up.
605 * Tasks which were woken up by interrupts (ie. hw events)
606 * are most likely of interactive nature. So we give them
607 * the credit of extending their sleep time to the period
608 * of time they spend on the runqueue, waiting for execution
609 * on a CPU, first time around:
615 * Normal first-time wakeups get a credit too for
616 * on-runqueue time, but it will be weighted down:
623 __activate_task(p, rq);
627 * deactivate_task - remove a task from the runqueue.
629 static void deactivate_task(struct task_struct *p, runqueue_t *rq)
632 if (p->state == TASK_UNINTERRUPTIBLE)
633 rq->nr_uninterruptible++;
634 dequeue_task(p, p->array);
639 * resched_task - mark a task 'to be rescheduled now'.
641 * On UP this means the setting of the need_resched flag, on SMP it
642 * might also involve a cross-CPU call to trigger the scheduler on
646 static void resched_task(task_t *p)
648 int need_resched, nrpolling;
651 /* minimise the chance of sending an interrupt to poll_idle() */
652 nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
653 need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
654 nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
656 if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
657 smp_send_reschedule(task_cpu(p));
661 static inline void resched_task(task_t *p)
663 set_tsk_need_resched(p);
668 * task_curr - is this task currently executing on a CPU?
669 * @p: the task in question.
671 inline int task_curr(const task_t *p)
673 return cpu_curr(task_cpu(p)) == p;
683 struct list_head list;
684 enum request_type type;
686 /* For REQ_MOVE_TASK */
690 /* For REQ_SET_DOMAIN */
691 struct sched_domain *sd;
693 struct completion done;
697 * The task's runqueue lock must be held.
698 * Returns true if you have to wait for migration thread.
700 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
702 runqueue_t *rq = task_rq(p);
705 * If the task is not on a runqueue (and not running), then
706 * it is sufficient to simply update the task's cpu field.
708 if (!p->array && !task_running(rq, p)) {
709 set_task_cpu(p, dest_cpu);
713 init_completion(&req->done);
714 req->type = REQ_MOVE_TASK;
716 req->dest_cpu = dest_cpu;
717 list_add(&req->list, &rq->migration_queue);
722 * wait_task_inactive - wait for a thread to unschedule.
724 * The caller must ensure that the task *will* unschedule sometime soon,
725 * else this function might spin for a *long* time. This function can't
726 * be called with interrupts off, or it may introduce deadlock with
727 * smp_call_function() if an IPI is sent by the same process we are
728 * waiting to become inactive.
730 void wait_task_inactive(task_t * p)
737 rq = task_rq_lock(p, &flags);
738 /* Must be off runqueue entirely, not preempted. */
739 if (unlikely(p->array)) {
740 /* If it's preempted, we yield. It could be a while. */
741 preempted = !task_running(rq, p);
742 task_rq_unlock(rq, &flags);
748 task_rq_unlock(rq, &flags);
752 * kick_process - kick a running thread to enter/exit the kernel
753 * @p: the to-be-kicked thread
755 * Cause a process which is running on another CPU to enter
756 * kernel-mode, without any delay. (to get signals handled.)
758 void kick_process(task_t *p)
764 if ((cpu != smp_processor_id()) && task_curr(p))
765 smp_send_reschedule(cpu);
769 EXPORT_SYMBOL_GPL(kick_process);
772 * Return a low guess at the load of a migration-source cpu.
774 * We want to under-estimate the load of migration sources, to
775 * balance conservatively.
777 static inline unsigned long source_load(int cpu)
779 runqueue_t *rq = cpu_rq(cpu);
780 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
782 return min(rq->cpu_load, load_now);
786 * Return a high guess at the load of a migration-target cpu
788 static inline unsigned long target_load(int cpu)
790 runqueue_t *rq = cpu_rq(cpu);
791 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
793 return max(rq->cpu_load, load_now);
799 * wake_idle() is useful especially on SMT architectures to wake a
800 * task onto an idle sibling if we would otherwise wake it onto a
803 * Returns the CPU we should wake onto.
805 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
806 static int wake_idle(int cpu, task_t *p)
809 runqueue_t *rq = cpu_rq(cpu);
810 struct sched_domain *sd;
817 if (!(sd->flags & SD_WAKE_IDLE))
820 cpus_and(tmp, sd->span, cpu_online_map);
821 cpus_and(tmp, tmp, p->cpus_allowed);
823 for_each_cpu_mask(i, tmp) {
831 static inline int wake_idle(int cpu, task_t *p)
838 * try_to_wake_up - wake up a thread
839 * @p: the to-be-woken-up thread
840 * @state: the mask of task states that can be woken
841 * @sync: do a synchronous wakeup?
843 * Put it on the run-queue if it's not already there. The "current"
844 * thread is always on the run-queue (except when the actual
845 * re-schedule is in progress), and as such you're allowed to do
846 * the simpler "current->state = TASK_RUNNING" to mark yourself
847 * runnable without the overhead of this.
849 * returns failure only if the task is already active.
851 static int try_to_wake_up(task_t * p, unsigned int state, int sync)
853 int cpu, this_cpu, success = 0;
858 unsigned long load, this_load;
859 struct sched_domain *sd;
863 rq = task_rq_lock(p, &flags);
864 old_state = p->state;
865 if (!(old_state & state))
872 this_cpu = smp_processor_id();
875 if (unlikely(task_running(rq, p)))
880 if (cpu == this_cpu || unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
883 load = source_load(cpu);
884 this_load = target_load(this_cpu);
887 * If sync wakeup then subtract the (maximum possible) effect of
888 * the currently running task from the load of the current CPU:
891 this_load -= SCHED_LOAD_SCALE;
893 /* Don't pull the task off an idle CPU to a busy one */
894 if (load < SCHED_LOAD_SCALE/2 && this_load > SCHED_LOAD_SCALE/2)
897 new_cpu = this_cpu; /* Wake to this CPU if we can */
900 * Scan domains for affine wakeup and passive balancing
903 for_each_domain(this_cpu, sd) {
904 unsigned int imbalance;
906 * Start passive balancing when half the imbalance_pct
909 imbalance = sd->imbalance_pct + (sd->imbalance_pct - 100) / 2;
911 if ( ((sd->flags & SD_WAKE_AFFINE) &&
912 !task_hot(p, rq->timestamp_last_tick, sd))
913 || ((sd->flags & SD_WAKE_BALANCE) &&
914 imbalance*this_load <= 100*load) ) {
916 * Now sd has SD_WAKE_AFFINE and p is cache cold in sd
917 * or sd has SD_WAKE_BALANCE and there is an imbalance
919 if (cpu_isset(cpu, sd->span))
924 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
926 new_cpu = wake_idle(new_cpu, p);
927 if (new_cpu != cpu && cpu_isset(new_cpu, p->cpus_allowed)) {
928 set_task_cpu(p, new_cpu);
929 task_rq_unlock(rq, &flags);
930 /* might preempt at this point */
931 rq = task_rq_lock(p, &flags);
932 old_state = p->state;
933 if (!(old_state & state))
938 this_cpu = smp_processor_id();
943 #endif /* CONFIG_SMP */
944 if (old_state == TASK_UNINTERRUPTIBLE) {
945 rq->nr_uninterruptible--;
947 * Tasks on involuntary sleep don't earn
948 * sleep_avg beyond just interactive state.
954 * Sync wakeups (i.e. those types of wakeups where the waker
955 * has indicated that it will leave the CPU in short order)
956 * don't trigger a preemption, if the woken up task will run on
957 * this cpu. (in this case the 'I will reschedule' promise of
958 * the waker guarantees that the freshly woken up task is going
959 * to be considered on this CPU.)
961 activate_task(p, rq, cpu == this_cpu);
962 if (!sync || cpu != this_cpu) {
963 if (TASK_PREEMPTS_CURR(p, rq))
964 resched_task(rq->curr);
969 p->state = TASK_RUNNING;
971 task_rq_unlock(rq, &flags);
976 int fastcall wake_up_process(task_t * p)
978 return try_to_wake_up(p, TASK_STOPPED |
979 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
982 EXPORT_SYMBOL(wake_up_process);
984 int fastcall wake_up_state(task_t *p, unsigned int state)
986 return try_to_wake_up(p, state, 0);
990 * Perform scheduler related setup for a newly forked process p.
991 * p is forked by current.
993 void fastcall sched_fork(task_t *p)
996 * We mark the process as running here, but have not actually
997 * inserted it onto the runqueue yet. This guarantees that
998 * nobody will actually run it, and a signal or other external
999 * event cannot wake it up and insert it on the runqueue either.
1001 p->state = TASK_RUNNING;
1002 INIT_LIST_HEAD(&p->run_list);
1004 spin_lock_init(&p->switch_lock);
1005 #ifdef CONFIG_CKRM_CPU_SCHEDULE
1006 cpu_demand_event(&p->demand_stat,CPU_DEMAND_INIT,0);
1009 #ifdef CONFIG_PREEMPT
1011 * During context-switch we hold precisely one spinlock, which
1012 * schedule_tail drops. (in the common case it's this_rq()->lock,
1013 * but it also can be p->switch_lock.) So we compensate with a count
1014 * of 1. Also, we want to start with kernel preemption disabled.
1016 p->thread_info->preempt_count = 1;
1019 * Share the timeslice between parent and child, thus the
1020 * total amount of pending timeslices in the system doesn't change,
1021 * resulting in more scheduling fairness.
1023 local_irq_disable();
1024 p->time_slice = (current->time_slice + 1) >> 1;
1026 * The remainder of the first timeslice might be recovered by
1027 * the parent if the child exits early enough.
1029 p->first_time_slice = 1;
1030 current->time_slice >>= 1;
1031 p->timestamp = sched_clock();
1032 if (!current->time_slice) {
1034 * This case is rare, it happens when the parent has only
1035 * a single jiffy left from its timeslice. Taking the
1036 * runqueue lock is not a problem.
1038 current->time_slice = 1;
1040 scheduler_tick(0, 0);
1048 * wake_up_forked_process - wake up a freshly forked process.
1050 * This function will do some initial scheduler statistics housekeeping
1051 * that must be done for every newly created process.
1053 void fastcall wake_up_forked_process(task_t * p)
1055 unsigned long flags;
1056 runqueue_t *rq = task_rq_lock(current, &flags);
1058 BUG_ON(p->state != TASK_RUNNING);
1061 * We decrease the sleep average of forking parents
1062 * and children as well, to keep max-interactive tasks
1063 * from forking tasks that are max-interactive.
1065 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1066 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1068 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1069 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1071 p->interactive_credit = 0;
1073 p->prio = effective_prio(p);
1074 set_task_cpu(p, smp_processor_id());
1076 if (unlikely(!current->array))
1077 __activate_task(p, rq);
1079 p->prio = current->prio;
1080 list_add_tail(&p->run_list, ¤t->run_list);
1081 p->array = current->array;
1082 p->array->nr_active++;
1084 class_enqueue_task(p,p->array);
1086 task_rq_unlock(rq, &flags);
1090 * Potentially available exiting-child timeslices are
1091 * retrieved here - this way the parent does not get
1092 * penalized for creating too many threads.
1094 * (this cannot be used to 'generate' timeslices
1095 * artificially, because any timeslice recovered here
1096 * was given away by the parent in the first place.)
1098 void fastcall sched_exit(task_t * p)
1100 unsigned long flags;
1103 local_irq_save(flags);
1104 if (p->first_time_slice) {
1105 p->parent->time_slice += p->time_slice;
1106 if (unlikely(p->parent->time_slice > MAX_TIMESLICE))
1107 p->parent->time_slice = MAX_TIMESLICE;
1109 local_irq_restore(flags);
1111 * If the child was a (relative-) CPU hog then decrease
1112 * the sleep_avg of the parent as well.
1114 rq = task_rq_lock(p->parent, &flags);
1115 if (p->sleep_avg < p->parent->sleep_avg)
1116 p->parent->sleep_avg = p->parent->sleep_avg /
1117 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1119 task_rq_unlock(rq, &flags);
1123 * finish_task_switch - clean up after a task-switch
1124 * @prev: the thread we just switched away from.
1126 * We enter this with the runqueue still locked, and finish_arch_switch()
1127 * will unlock it along with doing any other architecture-specific cleanup
1130 * Note that we may have delayed dropping an mm in context_switch(). If
1131 * so, we finish that here outside of the runqueue lock. (Doing it
1132 * with the lock held can cause deadlocks; see schedule() for
1135 static void finish_task_switch(task_t *prev)
1137 runqueue_t *rq = this_rq();
1138 struct mm_struct *mm = rq->prev_mm;
1139 unsigned long prev_task_flags;
1144 * A task struct has one reference for the use as "current".
1145 * If a task dies, then it sets TASK_ZOMBIE in tsk->state and calls
1146 * schedule one last time. The schedule call will never return,
1147 * and the scheduled task must drop that reference.
1148 * The test for TASK_ZOMBIE must occur while the runqueue locks are
1149 * still held, otherwise prev could be scheduled on another cpu, die
1150 * there before we look at prev->state, and then the reference would
1152 * Manfred Spraul <manfred@colorfullife.com>
1154 prev_task_flags = prev->flags;
1155 finish_arch_switch(rq, prev);
1158 if (unlikely(prev_task_flags & PF_DEAD))
1159 put_task_struct(prev);
1163 * schedule_tail - first thing a freshly forked thread must call.
1164 * @prev: the thread we just switched away from.
1166 asmlinkage void schedule_tail(task_t *prev)
1168 finish_task_switch(prev);
1170 if (current->set_child_tid)
1171 put_user(current->pid, current->set_child_tid);
1175 * context_switch - switch to the new MM and the new
1176 * thread's register state.
1179 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1181 struct mm_struct *mm = next->mm;
1182 struct mm_struct *oldmm = prev->active_mm;
1184 if (unlikely(!mm)) {
1185 next->active_mm = oldmm;
1186 atomic_inc(&oldmm->mm_count);
1187 enter_lazy_tlb(oldmm, next);
1189 switch_mm(oldmm, mm, next);
1191 if (unlikely(!prev->mm)) {
1192 prev->active_mm = NULL;
1193 WARN_ON(rq->prev_mm);
1194 rq->prev_mm = oldmm;
1197 /* Here we just switch the register state and the stack. */
1198 switch_to(prev, next, prev);
1204 * nr_running, nr_uninterruptible and nr_context_switches:
1206 * externally visible scheduler statistics: current number of runnable
1207 * threads, current number of uninterruptible-sleeping threads, total
1208 * number of context switches performed since bootup.
1210 unsigned long nr_running(void)
1212 unsigned long i, sum = 0;
1215 sum += cpu_rq(i)->nr_running;
1220 unsigned long nr_uninterruptible(void)
1222 unsigned long i, sum = 0;
1225 sum += cpu_rq(i)->nr_uninterruptible;
1230 unsigned long long nr_context_switches(void)
1232 unsigned long long i, sum = 0;
1235 sum += cpu_rq(i)->nr_switches;
1240 unsigned long nr_iowait(void)
1242 unsigned long i, sum = 0;
1245 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1251 * double_rq_lock - safely lock two runqueues
1253 * Note this does not disable interrupts like task_rq_lock,
1254 * you need to do so manually before calling.
1256 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1259 spin_lock(&rq1->lock);
1262 spin_lock(&rq1->lock);
1263 spin_lock(&rq2->lock);
1265 spin_lock(&rq2->lock);
1266 spin_lock(&rq1->lock);
1272 * double_rq_unlock - safely unlock two runqueues
1274 * Note this does not restore interrupts like task_rq_unlock,
1275 * you need to do so manually after calling.
1277 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1279 spin_unlock(&rq1->lock);
1281 spin_unlock(&rq2->lock);
1284 unsigned long long nr_preempt(void)
1286 unsigned long long i, sum = 0;
1288 for_each_online_cpu(i)
1289 sum += cpu_rq(i)->nr_preempt;
1304 * find_idlest_cpu - find the least busy runqueue.
1306 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1307 struct sched_domain *sd)
1309 unsigned long load, min_load, this_load;
1314 min_load = ULONG_MAX;
1316 cpus_and(mask, sd->span, cpu_online_map);
1317 cpus_and(mask, mask, p->cpus_allowed);
1319 for_each_cpu_mask(i, mask) {
1320 load = target_load(i);
1322 if (load < min_load) {
1326 /* break out early on an idle CPU: */
1332 /* add +1 to account for the new task */
1333 this_load = source_load(this_cpu) + SCHED_LOAD_SCALE;
1336 * Would with the addition of the new task to the
1337 * current CPU there be an imbalance between this
1338 * CPU and the idlest CPU?
1340 * Use half of the balancing threshold - new-context is
1341 * a good opportunity to balance.
1343 if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1350 * wake_up_forked_thread - wake up a freshly forked thread.
1352 * This function will do some initial scheduler statistics housekeeping
1353 * that must be done for every newly created context, and it also does
1354 * runqueue balancing.
1356 void fastcall wake_up_forked_thread(task_t * p)
1358 unsigned long flags;
1359 int this_cpu = get_cpu(), cpu;
1360 struct sched_domain *tmp, *sd = NULL;
1361 runqueue_t *this_rq = cpu_rq(this_cpu), *rq;
1364 * Find the largest domain that this CPU is part of that
1365 * is willing to balance on clone:
1367 for_each_domain(this_cpu, tmp)
1368 if (tmp->flags & SD_BALANCE_CLONE)
1371 cpu = find_idlest_cpu(p, this_cpu, sd);
1375 local_irq_save(flags);
1378 double_rq_lock(this_rq, rq);
1380 BUG_ON(p->state != TASK_RUNNING);
1383 * We did find_idlest_cpu() unlocked, so in theory
1384 * the mask could have changed - just dont migrate
1387 if (unlikely(!cpu_isset(cpu, p->cpus_allowed))) {
1389 double_rq_unlock(this_rq, rq);
1393 * We decrease the sleep average of forking parents
1394 * and children as well, to keep max-interactive tasks
1395 * from forking tasks that are max-interactive.
1397 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1398 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1400 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1401 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1403 p->interactive_credit = 0;
1405 p->prio = effective_prio(p);
1406 set_task_cpu(p, cpu);
1408 if (cpu == this_cpu) {
1409 if (unlikely(!current->array))
1410 __activate_task(p, rq);
1412 p->prio = current->prio;
1413 list_add_tail(&p->run_list, ¤t->run_list);
1414 p->array = current->array;
1415 p->array->nr_active++;
1417 class_enqueue_task(p,p->array);
1420 /* Not the local CPU - must adjust timestamp */
1421 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1422 + rq->timestamp_last_tick;
1423 __activate_task(p, rq);
1424 if (TASK_PREEMPTS_CURR(p, rq))
1425 resched_task(rq->curr);
1428 double_rq_unlock(this_rq, rq);
1429 local_irq_restore(flags);
1434 * If dest_cpu is allowed for this process, migrate the task to it.
1435 * This is accomplished by forcing the cpu_allowed mask to only
1436 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1437 * the cpu_allowed mask is restored.
1439 static void sched_migrate_task(task_t *p, int dest_cpu)
1441 migration_req_t req;
1443 unsigned long flags;
1445 rq = task_rq_lock(p, &flags);
1446 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1447 || unlikely(cpu_is_offline(dest_cpu)))
1450 /* force the process onto the specified CPU */
1451 if (migrate_task(p, dest_cpu, &req)) {
1452 /* Need to wait for migration thread (might exit: take ref). */
1453 struct task_struct *mt = rq->migration_thread;
1454 get_task_struct(mt);
1455 task_rq_unlock(rq, &flags);
1456 wake_up_process(mt);
1457 put_task_struct(mt);
1458 wait_for_completion(&req.done);
1462 task_rq_unlock(rq, &flags);
1466 * sched_balance_exec(): find the highest-level, exec-balance-capable
1467 * domain and try to migrate the task to the least loaded CPU.
1469 * execve() is a valuable balancing opportunity, because at this point
1470 * the task has the smallest effective memory and cache footprint.
1472 void sched_balance_exec(void)
1474 struct sched_domain *tmp, *sd = NULL;
1475 int new_cpu, this_cpu = get_cpu();
1477 /* Prefer the current CPU if there's only this task running */
1478 if (this_rq()->nr_running <= 1)
1481 for_each_domain(this_cpu, tmp)
1482 if (tmp->flags & SD_BALANCE_EXEC)
1486 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1487 if (new_cpu != this_cpu) {
1489 sched_migrate_task(current, new_cpu);
1498 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1500 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1502 if (unlikely(!spin_trylock(&busiest->lock))) {
1503 if (busiest < this_rq) {
1504 spin_unlock(&this_rq->lock);
1505 spin_lock(&busiest->lock);
1506 spin_lock(&this_rq->lock);
1508 spin_lock(&busiest->lock);
1513 * pull_task - move a task from a remote runqueue to the local runqueue.
1514 * Both runqueues must be locked.
1517 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1518 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1520 dequeue_task(p, src_array);
1521 src_rq->nr_running--;
1522 set_task_cpu(p, this_cpu);
1523 this_rq->nr_running++;
1524 enqueue_task(p, this_array);
1525 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1526 + this_rq->timestamp_last_tick;
1528 * Note that idle threads have a prio of MAX_PRIO, for this test
1529 * to be always true for them.
1531 if (TASK_PREEMPTS_CURR(p, this_rq))
1532 resched_task(this_rq->curr);
1536 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1539 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1540 struct sched_domain *sd, enum idle_type idle)
1543 * We do not migrate tasks that are:
1544 * 1) running (obviously), or
1545 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1546 * 3) are cache-hot on their current CPU.
1548 if (task_running(rq, p))
1550 if (!cpu_isset(this_cpu, p->cpus_allowed))
1553 /* Aggressive migration if we've failed balancing */
1554 if (idle == NEWLY_IDLE ||
1555 sd->nr_balance_failed < sd->cache_nice_tries) {
1556 if (task_hot(p, rq->timestamp_last_tick, sd))
1563 #ifdef CONFIG_CKRM_CPU_SCHEDULE
1564 static inline int ckrm_preferred_task(task_t *tmp,long min, long max,
1565 int phase, enum idle_type idle)
1567 long pressure = task_load(tmp);
1572 if ((idle == NOT_IDLE) && ! phase && (pressure <= min))
1578 * move tasks for a specic local class
1579 * return number of tasks pulled
1581 static inline int ckrm_cls_move_tasks(ckrm_lrq_t* src_lrq,ckrm_lrq_t*dst_lrq,
1582 runqueue_t *this_rq,
1583 runqueue_t *busiest,
1584 struct sched_domain *sd,
1586 enum idle_type idle,
1587 long* pressure_imbalance)
1589 prio_array_t *array, *dst_array;
1590 struct list_head *head, *curr;
1595 long pressure_min, pressure_max;
1596 /*hzheng: magic : 90% balance is enough*/
1597 long balance_min = *pressure_imbalance / 10;
1599 * we don't want to migrate tasks that will reverse the balance
1600 * or the tasks that make too small difference
1602 #define CKRM_BALANCE_MAX_RATIO 100
1603 #define CKRM_BALANCE_MIN_RATIO 1
1607 * We first consider expired tasks. Those will likely not be
1608 * executed in the near future, and they are most likely to
1609 * be cache-cold, thus switching CPUs has the least effect
1612 if (src_lrq->expired->nr_active) {
1613 array = src_lrq->expired;
1614 dst_array = dst_lrq->expired;
1616 array = src_lrq->active;
1617 dst_array = dst_lrq->active;
1621 /* Start searching at priority 0: */
1625 idx = sched_find_first_bit(array->bitmap);
1627 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1628 if (idx >= MAX_PRIO) {
1629 if (array == src_lrq->expired && src_lrq->active->nr_active) {
1630 array = src_lrq->active;
1631 dst_array = dst_lrq->active;
1634 if ((! phase) && (! pulled) && (idle != IDLE))
1635 goto start; //try again
1637 goto out; //finished search for this lrq
1640 head = array->queue + idx;
1643 tmp = list_entry(curr, task_t, run_list);
1647 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
1654 pressure_min = *pressure_imbalance * CKRM_BALANCE_MIN_RATIO/100;
1655 pressure_max = *pressure_imbalance * CKRM_BALANCE_MAX_RATIO/100;
1657 * skip the tasks that will reverse the balance too much
1659 if (ckrm_preferred_task(tmp,pressure_min,pressure_max,phase,idle)) {
1660 *pressure_imbalance -= task_load(tmp);
1661 pull_task(busiest, array, tmp,
1662 this_rq, dst_array, this_cpu);
1665 if (*pressure_imbalance <= balance_min)
1677 static inline long ckrm_rq_imbalance(runqueue_t *this_rq,runqueue_t *dst_rq)
1681 * make sure after balance, imbalance' > - imbalance/2
1682 * we don't want the imbalance be reversed too much
1684 imbalance = pid_get_pressure(rq_ckrm_load(dst_rq),0)
1685 - pid_get_pressure(rq_ckrm_load(this_rq),1);
1691 * try to balance the two runqueues
1693 * Called with both runqueues locked.
1694 * if move_tasks is called, it will try to move at least one task over
1696 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1697 unsigned long max_nr_move, struct sched_domain *sd,
1698 enum idle_type idle)
1700 struct ckrm_cpu_class *clsptr,*vip_cls = NULL;
1701 ckrm_lrq_t* src_lrq,*dst_lrq;
1702 long pressure_imbalance, pressure_imbalance_old;
1703 int src_cpu = task_cpu(busiest->curr);
1704 struct list_head *list;
1708 imbalance = ckrm_rq_imbalance(this_rq,busiest);
1710 if ((idle == NOT_IDLE && imbalance <= 0) || busiest->nr_running <= 1)
1713 //try to find the vip class
1714 list_for_each_entry(clsptr,&active_cpu_classes,links) {
1715 src_lrq = get_ckrm_lrq(clsptr,src_cpu);
1717 if (! lrq_nr_running(src_lrq))
1720 if (! vip_cls || cpu_class_weight(vip_cls) < cpu_class_weight(clsptr) )
1727 * do search from the most significant class
1728 * hopefully, less tasks will be migrated this way
1737 src_lrq = get_ckrm_lrq(clsptr,src_cpu);
1738 if (! lrq_nr_running(src_lrq))
1741 dst_lrq = get_ckrm_lrq(clsptr,this_cpu);
1743 //how much pressure for this class should be transferred
1744 pressure_imbalance = src_lrq->lrq_load * imbalance/src_lrq->local_weight;
1745 if (pulled && ! pressure_imbalance)
1748 pressure_imbalance_old = pressure_imbalance;
1752 ckrm_cls_move_tasks(src_lrq,dst_lrq,
1756 &pressure_imbalance);
1759 * hzheng: 2 is another magic number
1760 * stop balancing if the imbalance is less than 25% of the orig
1762 if (pressure_imbalance <= (pressure_imbalance_old >> 2))
1766 imbalance *= pressure_imbalance / pressure_imbalance_old;
1769 list = clsptr->links.next;
1770 if (list == &active_cpu_classes)
1772 clsptr = list_entry(list, typeof(*clsptr), links);
1773 if (clsptr != vip_cls)
1780 * ckrm_check_balance - is load balancing necessary?
1781 * return 0 if load balancing is not necessary
1782 * otherwise return the average load of the system
1783 * also, update nr_group
1786 * no load balancing if it's load is over average
1787 * no load balancing if it's load is far more than the min
1789 * read the status of all the runqueues
1791 static unsigned long ckrm_check_balance(struct sched_domain *sd, int this_cpu,
1792 enum idle_type idle, int* nr_group)
1794 struct sched_group *group = sd->groups;
1795 unsigned long min_load, max_load, avg_load;
1796 unsigned long total_load, this_load, total_pwr;
1798 max_load = this_load = total_load = total_pwr = 0;
1799 min_load = 0xFFFFFFFF;
1808 /* Tally up the load of all CPUs in the group */
1809 cpus_and(tmp, group->cpumask, cpu_online_map);
1810 if (unlikely(cpus_empty(tmp)))
1814 local_group = cpu_isset(this_cpu, group->cpumask);
1816 for_each_cpu_mask(i, tmp) {
1817 load = pid_get_pressure(rq_ckrm_load(cpu_rq(i)),local_group);
1825 total_load += avg_load;
1826 total_pwr += group->cpu_power;
1828 /* Adjust by relative CPU power of the group */
1829 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1832 this_load = avg_load;
1834 } else if (avg_load > max_load) {
1835 max_load = avg_load;
1837 if (avg_load < min_load) {
1838 min_load = avg_load;
1841 group = group->next;
1842 *nr_group = *nr_group + 1;
1843 } while (group != sd->groups);
1845 if (!max_load || this_load >= max_load)
1848 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
1850 /* hzheng: debugging: 105 is a magic number
1851 * 100*max_load <= sd->imbalance_pct*this_load)
1852 * should use imbalance_pct instead
1854 if (this_load > avg_load
1855 || 100*max_load < 105*this_load
1856 || 100*min_load < 70*this_load
1866 * any group that has above average load is considered busy
1867 * find the busiest queue from any of busy group
1870 ckrm_find_busy_queue(struct sched_domain *sd, int this_cpu,
1871 unsigned long avg_load, enum idle_type idle,
1874 struct sched_group *group;
1875 runqueue_t * busiest=NULL;
1879 rand = get_ckrm_rand(nr_group);
1883 unsigned long load,total_load,max_load;
1886 runqueue_t * grp_busiest;
1888 cpus_and(tmp, group->cpumask, cpu_online_map);
1889 if (unlikely(cpus_empty(tmp)))
1890 goto find_nextgroup;
1895 for_each_cpu_mask(i, tmp) {
1896 load = pid_get_pressure(rq_ckrm_load(cpu_rq(i)),0);
1898 if (load > max_load) {
1900 grp_busiest = cpu_rq(i);
1904 total_load = (total_load * SCHED_LOAD_SCALE) / group->cpu_power;
1905 if (total_load > avg_load) {
1906 busiest = grp_busiest;
1907 if (nr_group >= rand)
1911 group = group->next;
1913 } while (group != sd->groups);
1919 * load_balance - pressure based load balancing algorithm used by ckrm
1921 static int ckrm_load_balance(int this_cpu, runqueue_t *this_rq,
1922 struct sched_domain *sd, enum idle_type idle)
1924 runqueue_t *busiest;
1925 unsigned long avg_load;
1926 int nr_moved,nr_group;
1928 avg_load = ckrm_check_balance(sd, this_cpu, idle, &nr_group);
1932 busiest = ckrm_find_busy_queue(sd,this_cpu,avg_load,idle,nr_group);
1936 * This should be "impossible", but since load
1937 * balancing is inherently racy and statistical,
1938 * it could happen in theory.
1940 if (unlikely(busiest == this_rq)) {
1946 if (busiest->nr_running > 1) {
1948 * Attempt to move tasks. If find_busiest_group has found
1949 * an imbalance but busiest->nr_running <= 1, the group is
1950 * still unbalanced. nr_moved simply stays zero, so it is
1951 * correctly treated as an imbalance.
1953 double_lock_balance(this_rq, busiest);
1954 nr_moved = move_tasks(this_rq, this_cpu, busiest,
1956 spin_unlock(&busiest->lock);
1958 adjust_local_weight();
1963 sd->nr_balance_failed ++;
1965 sd->nr_balance_failed = 0;
1967 /* We were unbalanced, so reset the balancing interval */
1968 sd->balance_interval = sd->min_interval;
1973 /* tune up the balancing interval */
1974 if (sd->balance_interval < sd->max_interval)
1975 sd->balance_interval *= 2;
1981 * this_rq->lock is already held
1983 static inline int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
1984 struct sched_domain *sd)
1987 read_lock(&class_list_lock);
1988 ret = ckrm_load_balance(this_cpu,this_rq,sd,NEWLY_IDLE);
1989 read_unlock(&class_list_lock);
1993 static inline int load_balance(int this_cpu, runqueue_t *this_rq,
1994 struct sched_domain *sd, enum idle_type idle)
1998 spin_lock(&this_rq->lock);
1999 read_lock(&class_list_lock);
2000 ret= ckrm_load_balance(this_cpu,this_rq,sd,NEWLY_IDLE);
2001 read_unlock(&class_list_lock);
2002 spin_unlock(&this_rq->lock);
2005 #else /*! CONFIG_CKRM_CPU_SCHEDULE */
2007 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
2008 * as part of a balancing operation within "domain". Returns the number of
2011 * Called with both runqueues locked.
2013 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
2014 unsigned long max_nr_move, struct sched_domain *sd,
2015 enum idle_type idle)
2017 prio_array_t *array, *dst_array;
2018 struct list_head *head, *curr;
2019 int idx, pulled = 0;
2022 if (max_nr_move <= 0 || busiest->nr_running <= 1)
2026 * We first consider expired tasks. Those will likely not be
2027 * executed in the near future, and they are most likely to
2028 * be cache-cold, thus switching CPUs has the least effect
2031 if (busiest->expired->nr_active) {
2032 array = busiest->expired;
2033 dst_array = this_rq->expired;
2035 array = busiest->active;
2036 dst_array = this_rq->active;
2040 /* Start searching at priority 0: */
2044 idx = sched_find_first_bit(array->bitmap);
2046 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
2047 if (idx >= MAX_PRIO) {
2048 if (array == busiest->expired && busiest->active->nr_active) {
2049 array = busiest->active;
2050 dst_array = this_rq->active;
2056 head = array->queue + idx;
2059 tmp = list_entry(curr, task_t, run_list);
2063 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
2069 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
2072 /* We only want to steal up to the prescribed number of tasks. */
2073 if (pulled < max_nr_move) {
2084 * find_busiest_group finds and returns the busiest CPU group within the
2085 * domain. It calculates and returns the number of tasks which should be
2086 * moved to restore balance via the imbalance parameter.
2088 static struct sched_group *
2089 find_busiest_group(struct sched_domain *sd, int this_cpu,
2090 unsigned long *imbalance, enum idle_type idle)
2092 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2093 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2095 max_load = this_load = total_load = total_pwr = 0;
2103 local_group = cpu_isset(this_cpu, group->cpumask);
2105 /* Tally up the load of all CPUs in the group */
2107 cpus_and(tmp, group->cpumask, cpu_online_map);
2108 if (unlikely(cpus_empty(tmp)))
2111 for_each_cpu_mask(i, tmp) {
2112 /* Bias balancing toward cpus of our domain */
2114 load = target_load(i);
2116 load = source_load(i);
2125 total_load += avg_load;
2126 total_pwr += group->cpu_power;
2128 /* Adjust by relative CPU power of the group */
2129 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
2132 this_load = avg_load;
2135 } else if (avg_load > max_load) {
2136 max_load = avg_load;
2140 group = group->next;
2141 } while (group != sd->groups);
2143 if (!busiest || this_load >= max_load)
2146 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2148 if (this_load >= avg_load ||
2149 100*max_load <= sd->imbalance_pct*this_load)
2153 * We're trying to get all the cpus to the average_load, so we don't
2154 * want to push ourselves above the average load, nor do we wish to
2155 * reduce the max loaded cpu below the average load, as either of these
2156 * actions would just result in more rebalancing later, and ping-pong
2157 * tasks around. Thus we look for the minimum possible imbalance.
2158 * Negative imbalances (*we* are more loaded than anyone else) will
2159 * be counted as no imbalance for these purposes -- we can't fix that
2160 * by pulling tasks to us. Be careful of negative numbers as they'll
2161 * appear as very large values with unsigned longs.
2163 *imbalance = min(max_load - avg_load, avg_load - this_load);
2165 /* How much load to actually move to equalise the imbalance */
2166 *imbalance = (*imbalance * min(busiest->cpu_power, this->cpu_power))
2169 if (*imbalance < SCHED_LOAD_SCALE - 1) {
2170 unsigned long pwr_now = 0, pwr_move = 0;
2173 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
2179 * OK, we don't have enough imbalance to justify moving tasks,
2180 * however we may be able to increase total CPU power used by
2184 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
2185 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
2186 pwr_now /= SCHED_LOAD_SCALE;
2188 /* Amount of load we'd subtract */
2189 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
2191 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
2194 /* Amount of load we'd add */
2195 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
2198 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
2199 pwr_move /= SCHED_LOAD_SCALE;
2201 /* Move if we gain another 8th of a CPU worth of throughput */
2202 if (pwr_move < pwr_now + SCHED_LOAD_SCALE / 8)
2209 /* Get rid of the scaling factor, rounding down as we divide */
2210 *imbalance = (*imbalance + 1) / SCHED_LOAD_SCALE;
2215 if (busiest && (idle == NEWLY_IDLE ||
2216 (idle == IDLE && max_load > SCHED_LOAD_SCALE)) ) {
2226 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2228 static runqueue_t *find_busiest_queue(struct sched_group *group)
2231 unsigned long load, max_load = 0;
2232 runqueue_t *busiest = NULL;
2235 cpus_and(tmp, group->cpumask, cpu_online_map);
2236 for_each_cpu_mask(i, tmp) {
2237 load = source_load(i);
2239 if (load > max_load) {
2241 busiest = cpu_rq(i);
2249 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2250 * tasks if there is an imbalance.
2252 * Called with this_rq unlocked.
2254 static int load_balance(int this_cpu, runqueue_t *this_rq,
2255 struct sched_domain *sd, enum idle_type idle)
2257 struct sched_group *group;
2258 runqueue_t *busiest;
2259 unsigned long imbalance;
2262 spin_lock(&this_rq->lock);
2264 group = find_busiest_group(sd, this_cpu, &imbalance, idle);
2268 busiest = find_busiest_queue(group);
2272 * This should be "impossible", but since load
2273 * balancing is inherently racy and statistical,
2274 * it could happen in theory.
2276 if (unlikely(busiest == this_rq)) {
2282 if (busiest->nr_running > 1) {
2284 * Attempt to move tasks. If find_busiest_group has found
2285 * an imbalance but busiest->nr_running <= 1, the group is
2286 * still unbalanced. nr_moved simply stays zero, so it is
2287 * correctly treated as an imbalance.
2289 double_lock_balance(this_rq, busiest);
2290 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2291 imbalance, sd, idle);
2292 spin_unlock(&busiest->lock);
2294 spin_unlock(&this_rq->lock);
2297 sd->nr_balance_failed++;
2299 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2302 spin_lock(&busiest->lock);
2303 if (!busiest->active_balance) {
2304 busiest->active_balance = 1;
2305 busiest->push_cpu = this_cpu;
2308 spin_unlock(&busiest->lock);
2310 wake_up_process(busiest->migration_thread);
2313 * We've kicked active balancing, reset the failure
2316 sd->nr_balance_failed = sd->cache_nice_tries;
2319 sd->nr_balance_failed = 0;
2321 /* We were unbalanced, so reset the balancing interval */
2322 sd->balance_interval = sd->min_interval;
2327 spin_unlock(&this_rq->lock);
2329 /* tune up the balancing interval */
2330 if (sd->balance_interval < sd->max_interval)
2331 sd->balance_interval *= 2;
2337 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2338 * tasks if there is an imbalance.
2340 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2341 * this_rq is locked.
2343 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2344 struct sched_domain *sd)
2346 struct sched_group *group;
2347 runqueue_t *busiest = NULL;
2348 unsigned long imbalance;
2351 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
2355 busiest = find_busiest_queue(group);
2356 if (!busiest || busiest == this_rq)
2359 /* Attempt to move tasks */
2360 double_lock_balance(this_rq, busiest);
2362 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2363 imbalance, sd, NEWLY_IDLE);
2365 spin_unlock(&busiest->lock);
2370 #endif /* CONFIG_CKRM_CPU_SCHEDULE*/
2374 * idle_balance is called by schedule() if this_cpu is about to become
2375 * idle. Attempts to pull tasks from other CPUs.
2377 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
2379 struct sched_domain *sd;
2381 for_each_domain(this_cpu, sd) {
2382 if (sd->flags & SD_BALANCE_NEWIDLE) {
2383 if (load_balance_newidle(this_cpu, this_rq, sd)) {
2384 /* We've pulled tasks over so stop searching */
2392 * active_load_balance is run by migration threads. It pushes a running
2393 * task off the cpu. It can be required to correctly have at least 1 task
2394 * running on each physical CPU where possible, and not have a physical /
2395 * logical imbalance.
2397 * Called with busiest locked.
2399 static void active_load_balance(runqueue_t *busiest, int busiest_cpu)
2401 struct sched_domain *sd;
2402 struct sched_group *group, *busy_group;
2405 if (busiest->nr_running <= 1)
2408 for_each_domain(busiest_cpu, sd)
2409 if (cpu_isset(busiest->push_cpu, sd->span))
2417 while (!cpu_isset(busiest_cpu, group->cpumask))
2418 group = group->next;
2427 if (group == busy_group)
2430 cpus_and(tmp, group->cpumask, cpu_online_map);
2431 if (!cpus_weight(tmp))
2434 for_each_cpu_mask(i, tmp) {
2440 rq = cpu_rq(push_cpu);
2443 * This condition is "impossible", but since load
2444 * balancing is inherently a bit racy and statistical,
2445 * it can trigger.. Reported by Bjorn Helgaas on a
2448 if (unlikely(busiest == rq))
2450 double_lock_balance(busiest, rq);
2451 move_tasks(rq, push_cpu, busiest, 1, sd, IDLE);
2452 spin_unlock(&rq->lock);
2454 group = group->next;
2455 } while (group != sd->groups);
2459 * rebalance_tick will get called every timer tick, on every CPU.
2461 * It checks each scheduling domain to see if it is due to be balanced,
2462 * and initiates a balancing operation if so.
2464 * Balancing parameters are set up in arch_init_sched_domains.
2467 /* Don't have all balancing operations going off at once */
2468 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2470 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2471 enum idle_type idle)
2473 unsigned long old_load, this_load;
2474 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2475 struct sched_domain *sd;
2477 /* Update our load */
2478 old_load = this_rq->cpu_load;
2479 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
2481 * Round up the averaging division if load is increasing. This
2482 * prevents us from getting stuck on 9 if the load is 10, for
2485 if (this_load > old_load)
2487 this_rq->cpu_load = (old_load + this_load) / 2;
2489 for_each_domain(this_cpu, sd) {
2490 unsigned long interval = sd->balance_interval;
2493 interval *= sd->busy_factor;
2495 /* scale ms to jiffies */
2496 interval = msecs_to_jiffies(interval);
2497 if (unlikely(!interval))
2500 if (j - sd->last_balance >= interval) {
2501 if (load_balance(this_cpu, this_rq, sd, idle)) {
2502 /* We've pulled tasks over so no longer idle */
2505 sd->last_balance += interval;
2511 * on UP we do not need to balance between CPUs:
2513 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2516 static inline void idle_balance(int cpu, runqueue_t *rq)
2521 static inline int wake_priority_sleeper(runqueue_t *rq)
2523 #ifdef CONFIG_SCHED_SMT
2525 * If an SMT sibling task has been put to sleep for priority
2526 * reasons reschedule the idle task to see if it can now run.
2528 if (rq->nr_running) {
2529 resched_task(rq->idle);
2536 DEFINE_PER_CPU(struct kernel_stat, kstat) = { { 0 } };
2537 EXPORT_PER_CPU_SYMBOL(kstat);
2540 * We place interactive tasks back into the active array, if possible.
2542 * To guarantee that this does not starve expired tasks we ignore the
2543 * interactivity of a task if the first expired task had to wait more
2544 * than a 'reasonable' amount of time. This deadline timeout is
2545 * load-dependent, as the frequency of array switched decreases with
2546 * increasing number of running tasks. We also ignore the interactivity
2547 * if a better static_prio task has expired:
2550 #ifndef CONFIG_CKRM_CPU_SCHEDULE
2551 #define EXPIRED_STARVING(rq) \
2552 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2553 (jiffies - (rq)->expired_timestamp >= \
2554 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2555 ((rq)->curr->static_prio > (rq)->best_expired_prio))
2557 #define EXPIRED_STARVING(rq) \
2558 (STARVATION_LIMIT && ((rq)->expired_timestamp && \
2559 (jiffies - (rq)->expired_timestamp >= \
2560 STARVATION_LIMIT * (lrq_nr_running(rq)) + 1)))
2564 * This function gets called by the timer code, with HZ frequency.
2565 * We call it with interrupts disabled.
2567 * It also gets called by the fork code, when changing the parent's
2570 void scheduler_tick(int user_ticks, int sys_ticks)
2572 int cpu = smp_processor_id();
2573 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2574 runqueue_t *rq = this_rq();
2575 task_t *p = current;
2577 rq->timestamp_last_tick = sched_clock();
2579 if (rcu_pending(cpu))
2580 rcu_check_callbacks(cpu, user_ticks);
2582 /* note: this timer irq context must be accounted for as well */
2583 if (hardirq_count() - HARDIRQ_OFFSET) {
2584 cpustat->irq += sys_ticks;
2586 } else if (softirq_count()) {
2587 cpustat->softirq += sys_ticks;
2591 if (p == rq->idle) {
2592 #ifdef CONFIG_VSERVER_HARDCPU
2593 if (!--rq->idle_tokens && !list_empty(&rq->hold_queue))
2597 if (atomic_read(&rq->nr_iowait) > 0)
2598 cpustat->iowait += sys_ticks;
2600 cpustat->idle += sys_ticks;
2601 if (wake_priority_sleeper(rq))
2603 ckrm_sched_tick(jiffies,cpu,rq_ckrm_load(rq));
2604 rebalance_tick(cpu, rq, IDLE);
2607 if (TASK_NICE(p) > 0)
2608 cpustat->nice += user_ticks;
2610 cpustat->user += user_ticks;
2611 cpustat->system += sys_ticks;
2613 /* Task might have expired already, but not scheduled off yet */
2614 if (p->array != rq_active(p,rq)) {
2615 set_tsk_need_resched(p);
2618 spin_lock(&rq->lock);
2620 * The task was running during this tick - update the
2621 * time slice counter. Note: we do not update a thread's
2622 * priority until it either goes to sleep or uses up its
2623 * timeslice. This makes it possible for interactive tasks
2624 * to use up their timeslices at their highest priority levels.
2626 if (unlikely(rt_task(p))) {
2628 * RR tasks need a special form of timeslice management.
2629 * FIFO tasks have no timeslices.
2631 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2632 p->time_slice = task_timeslice(p);
2633 p->first_time_slice = 0;
2634 set_tsk_need_resched(p);
2636 /* put it at the end of the queue: */
2637 dequeue_task(p, rq_active(p,rq));
2638 enqueue_task(p, rq_active(p,rq));
2642 if (vx_need_resched(p)) {
2643 #ifdef CONFIG_CKRM_CPU_SCHEDULE
2644 /* Hubertus ... we can abstract this out */
2645 ckrm_lrq_t* rq = get_task_lrq(p);
2647 dequeue_task(p, rq->active);
2648 set_tsk_need_resched(p);
2649 p->prio = effective_prio(p);
2650 p->time_slice = task_timeslice(p);
2651 p->first_time_slice = 0;
2653 if (!rq->expired_timestamp)
2654 rq->expired_timestamp = jiffies;
2655 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2656 enqueue_task(p, rq->expired);
2657 if (p->static_prio < this_rq()->best_expired_prio)
2658 this_rq()->best_expired_prio = p->static_prio;
2660 enqueue_task(p, rq->active);
2663 * Prevent a too long timeslice allowing a task to monopolize
2664 * the CPU. We do this by splitting up the timeslice into
2667 * Note: this does not mean the task's timeslices expire or
2668 * get lost in any way, they just might be preempted by
2669 * another task of equal priority. (one with higher
2670 * priority would have preempted this task already.) We
2671 * requeue this task to the end of the list on this priority
2672 * level, which is in essence a round-robin of tasks with
2675 * This only applies to tasks in the interactive
2676 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2678 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2679 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2680 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2681 (p->array == rq_active(p,rq))) {
2683 dequeue_task(p, rq_active(p,rq));
2684 set_tsk_need_resched(p);
2685 p->prio = effective_prio(p);
2686 enqueue_task(p, rq_active(p,rq));
2690 spin_unlock(&rq->lock);
2692 ckrm_sched_tick(jiffies,cpu,rq_ckrm_load(rq));
2693 rebalance_tick(cpu, rq, NOT_IDLE);
2696 #ifdef CONFIG_SCHED_SMT
2697 static inline void wake_sleeping_dependent(int cpu, runqueue_t *rq)
2700 struct sched_domain *sd = rq->sd;
2701 cpumask_t sibling_map;
2703 if (!(sd->flags & SD_SHARE_CPUPOWER))
2706 cpus_and(sibling_map, sd->span, cpu_online_map);
2707 for_each_cpu_mask(i, sibling_map) {
2716 * If an SMT sibling task is sleeping due to priority
2717 * reasons wake it up now.
2719 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
2720 resched_task(smt_rq->idle);
2724 static inline int dependent_sleeper(int cpu, runqueue_t *rq, task_t *p)
2726 struct sched_domain *sd = rq->sd;
2727 cpumask_t sibling_map;
2730 if (!(sd->flags & SD_SHARE_CPUPOWER))
2733 cpus_and(sibling_map, sd->span, cpu_online_map);
2734 for_each_cpu_mask(i, sibling_map) {
2742 smt_curr = smt_rq->curr;
2745 * If a user task with lower static priority than the
2746 * running task on the SMT sibling is trying to schedule,
2747 * delay it till there is proportionately less timeslice
2748 * left of the sibling task to prevent a lower priority
2749 * task from using an unfair proportion of the
2750 * physical cpu's resources. -ck
2752 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
2753 task_timeslice(p) || rt_task(smt_curr)) &&
2754 p->mm && smt_curr->mm && !rt_task(p))
2758 * Reschedule a lower priority task on the SMT sibling,
2759 * or wake it up if it has been put to sleep for priority
2762 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
2763 task_timeslice(smt_curr) || rt_task(p)) &&
2764 smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
2765 (smt_curr == smt_rq->idle && smt_rq->nr_running))
2766 resched_task(smt_curr);
2771 static inline void wake_sleeping_dependent(int cpu, runqueue_t *rq)
2775 static inline int dependent_sleeper(int cpu, runqueue_t *rq, task_t *p)
2782 * schedule() is the main scheduler function.
2784 asmlinkage void __sched schedule(void)
2787 task_t *prev, *next;
2789 prio_array_t *array;
2790 unsigned long long now;
2791 unsigned long run_time;
2793 #ifdef CONFIG_VSERVER_HARDCPU
2794 struct vx_info *vxi;
2799 * If crash dump is in progress, this other cpu's
2800 * need to wait until it completes.
2801 * NB: this code is optimized away for kernels without
2804 if (unlikely(dump_oncpu))
2805 goto dump_scheduling_disabled;
2807 //WARN_ON(system_state == SYSTEM_BOOTING);
2809 * Test if we are atomic. Since do_exit() needs to call into
2810 * schedule() atomically, we ignore that path for now.
2811 * Otherwise, whine if we are scheduling when we should not be.
2813 if (likely(!(current->state & (TASK_DEAD | TASK_ZOMBIE)))) {
2814 if (unlikely(in_atomic())) {
2815 printk(KERN_ERR "bad: scheduling while atomic!\n");
2825 release_kernel_lock(prev);
2826 now = sched_clock();
2827 if (likely(now - prev->timestamp < NS_MAX_SLEEP_AVG))
2828 run_time = now - prev->timestamp;
2830 run_time = NS_MAX_SLEEP_AVG;
2833 * Tasks with interactive credits get charged less run_time
2834 * at high sleep_avg to delay them losing their interactive
2837 if (HIGH_CREDIT(prev))
2838 run_time /= (CURRENT_BONUS(prev) ? : 1);
2840 spin_lock_irq(&rq->lock);
2842 #ifdef CONFIG_CKRM_CPU_SCHEDULE
2843 if (prev != rq->idle) {
2844 unsigned long long run = now - prev->timestamp;
2845 ckrm_lrq_t * lrq = get_task_lrq(prev);
2847 lrq->lrq_load -= task_load(prev);
2848 cpu_demand_event(&prev->demand_stat,CPU_DEMAND_DESCHEDULE,run);
2849 lrq->lrq_load += task_load(prev);
2851 cpu_demand_event(get_task_lrq_stat(prev),CPU_DEMAND_DESCHEDULE,run);
2852 update_local_cvt(prev, run);
2856 * if entering off of a kernel preemption go straight
2857 * to picking the next task.
2859 switch_count = &prev->nivcsw;
2860 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2861 switch_count = &prev->nvcsw;
2862 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2863 unlikely(signal_pending(prev))))
2864 prev->state = TASK_RUNNING;
2866 deactivate_task(prev, rq);
2869 cpu = smp_processor_id();
2870 #ifdef CONFIG_VSERVER_HARDCPU
2871 if (!list_empty(&rq->hold_queue)) {
2872 struct list_head *l, *n;
2876 list_for_each_safe(l, n, &rq->hold_queue) {
2877 next = list_entry(l, task_t, run_list);
2878 if (vxi == next->vx_info)
2881 vxi = next->vx_info;
2882 ret = vx_tokens_recalc(vxi);
2883 // tokens = vx_tokens_avail(next);
2886 list_del(&next->run_list);
2887 next->state &= ~TASK_ONHOLD;
2888 recalc_task_prio(next, now);
2889 __activate_task(next, rq);
2890 // printk("··· unhold %p\n", next);
2893 if ((ret < 0) && (maxidle < ret))
2897 rq->idle_tokens = -maxidle;
2901 if (unlikely(!rq->nr_running)) {
2902 idle_balance(cpu, rq);
2905 next = rq_get_next_task(rq);
2906 if (next == rq->idle) {
2907 rq->expired_timestamp = 0;
2908 wake_sleeping_dependent(cpu, rq);
2912 if (dependent_sleeper(cpu, rq, next)) {
2917 #ifdef CONFIG_VSERVER_HARDCPU
2918 vxi = next->vx_info;
2919 if (vxi && __vx_flags(vxi->vx_flags,
2920 VXF_SCHED_PAUSE|VXF_SCHED_HARD, 0)) {
2921 int ret = vx_tokens_recalc(vxi);
2923 if (unlikely(ret <= 0)) {
2924 if (ret && (rq->idle_tokens > -ret))
2925 rq->idle_tokens = -ret;
2926 deactivate_task(next, rq);
2927 list_add_tail(&next->run_list, &rq->hold_queue);
2928 next->state |= TASK_ONHOLD;
2934 if (!rt_task(next) && next->activated > 0) {
2935 unsigned long long delta = now - next->timestamp;
2937 if (next->activated == 1)
2938 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
2940 array = next->array;
2941 dequeue_task(next, array);
2942 recalc_task_prio(next, next->timestamp + delta);
2943 enqueue_task(next, array);
2945 next->activated = 0;
2948 if (test_and_clear_tsk_thread_flag(prev,TIF_NEED_RESCHED))
2950 RCU_qsctr(task_cpu(prev))++;
2952 prev->sleep_avg -= run_time;
2953 if ((long)prev->sleep_avg <= 0) {
2954 prev->sleep_avg = 0;
2955 if (!(HIGH_CREDIT(prev) || LOW_CREDIT(prev)))
2956 prev->interactive_credit--;
2958 add_delay_ts(prev,runcpu_total,prev->timestamp,now);
2959 prev->timestamp = now;
2961 if (likely(prev != next)) {
2962 add_delay_ts(next,waitcpu_total,next->timestamp,now);
2963 inc_delay(next,runs);
2964 next->timestamp = now;
2969 prepare_arch_switch(rq, next);
2970 prev = context_switch(rq, prev, next);
2973 finish_task_switch(prev);
2975 spin_unlock_irq(&rq->lock);
2977 reacquire_kernel_lock(current);
2978 preempt_enable_no_resched();
2979 if (test_thread_flag(TIF_NEED_RESCHED))
2984 dump_scheduling_disabled:
2985 /* allow scheduling only if this is the dumping cpu */
2986 if (dump_oncpu != smp_processor_id()+1) {
2993 EXPORT_SYMBOL(schedule);
2994 #ifdef CONFIG_PREEMPT
2996 * this is is the entry point to schedule() from in-kernel preemption
2997 * off of preempt_enable. Kernel preemptions off return from interrupt
2998 * occur there and call schedule directly.
3000 asmlinkage void __sched preempt_schedule(void)
3002 struct thread_info *ti = current_thread_info();
3005 * If there is a non-zero preempt_count or interrupts are disabled,
3006 * we do not want to preempt the current task. Just return..
3008 if (unlikely(ti->preempt_count || irqs_disabled()))
3012 ti->preempt_count = PREEMPT_ACTIVE;
3014 ti->preempt_count = 0;
3016 /* we could miss a preemption opportunity between schedule and now */
3018 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3022 EXPORT_SYMBOL(preempt_schedule);
3023 #endif /* CONFIG_PREEMPT */
3025 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
3027 task_t *p = curr->task;
3028 return try_to_wake_up(p, mode, sync);
3031 EXPORT_SYMBOL(default_wake_function);
3034 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3035 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3036 * number) then we wake all the non-exclusive tasks and one exclusive task.
3038 * There are circumstances in which we can try to wake a task which has already
3039 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3040 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3042 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3043 int nr_exclusive, int sync, void *key)
3045 struct list_head *tmp, *next;
3047 list_for_each_safe(tmp, next, &q->task_list) {
3050 curr = list_entry(tmp, wait_queue_t, task_list);
3051 flags = curr->flags;
3052 if (curr->func(curr, mode, sync, key) &&
3053 (flags & WQ_FLAG_EXCLUSIVE) &&
3060 * __wake_up - wake up threads blocked on a waitqueue.
3062 * @mode: which threads
3063 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3065 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3066 int nr_exclusive, void *key)
3068 unsigned long flags;
3070 spin_lock_irqsave(&q->lock, flags);
3071 __wake_up_common(q, mode, nr_exclusive, 0, key);
3072 spin_unlock_irqrestore(&q->lock, flags);
3075 EXPORT_SYMBOL(__wake_up);
3078 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3080 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3082 __wake_up_common(q, mode, 1, 0, NULL);
3086 * __wake_up - sync- wake up threads blocked on a waitqueue.
3088 * @mode: which threads
3089 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3091 * The sync wakeup differs that the waker knows that it will schedule
3092 * away soon, so while the target thread will be woken up, it will not
3093 * be migrated to another CPU - ie. the two threads are 'synchronized'
3094 * with each other. This can prevent needless bouncing between CPUs.
3096 * On UP it can prevent extra preemption.
3098 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3100 unsigned long flags;
3106 if (unlikely(!nr_exclusive))
3109 spin_lock_irqsave(&q->lock, flags);
3110 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3111 spin_unlock_irqrestore(&q->lock, flags);
3113 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3115 void fastcall complete(struct completion *x)
3117 unsigned long flags;
3119 spin_lock_irqsave(&x->wait.lock, flags);
3121 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3123 spin_unlock_irqrestore(&x->wait.lock, flags);
3125 EXPORT_SYMBOL(complete);
3127 void fastcall complete_all(struct completion *x)
3129 unsigned long flags;
3131 spin_lock_irqsave(&x->wait.lock, flags);
3132 x->done += UINT_MAX/2;
3133 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3135 spin_unlock_irqrestore(&x->wait.lock, flags);
3137 EXPORT_SYMBOL(complete_all);
3139 void fastcall __sched wait_for_completion(struct completion *x)
3142 spin_lock_irq(&x->wait.lock);
3144 DECLARE_WAITQUEUE(wait, current);
3146 wait.flags |= WQ_FLAG_EXCLUSIVE;
3147 __add_wait_queue_tail(&x->wait, &wait);
3149 __set_current_state(TASK_UNINTERRUPTIBLE);
3150 spin_unlock_irq(&x->wait.lock);
3152 spin_lock_irq(&x->wait.lock);
3154 __remove_wait_queue(&x->wait, &wait);
3157 spin_unlock_irq(&x->wait.lock);
3159 EXPORT_SYMBOL(wait_for_completion);
3161 #define SLEEP_ON_VAR \
3162 unsigned long flags; \
3163 wait_queue_t wait; \
3164 init_waitqueue_entry(&wait, current);
3166 #define SLEEP_ON_HEAD \
3167 spin_lock_irqsave(&q->lock,flags); \
3168 __add_wait_queue(q, &wait); \
3169 spin_unlock(&q->lock);
3171 #define SLEEP_ON_TAIL \
3172 spin_lock_irq(&q->lock); \
3173 __remove_wait_queue(q, &wait); \
3174 spin_unlock_irqrestore(&q->lock, flags);
3176 #define SLEEP_ON_BKLCHECK \
3177 if (unlikely(!kernel_locked()) && \
3178 sleep_on_bkl_warnings < 10) { \
3179 sleep_on_bkl_warnings++; \
3183 static int sleep_on_bkl_warnings;
3185 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3191 current->state = TASK_INTERRUPTIBLE;
3198 EXPORT_SYMBOL(interruptible_sleep_on);
3200 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3206 current->state = TASK_INTERRUPTIBLE;
3209 timeout = schedule_timeout(timeout);
3215 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3217 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3223 current->state = TASK_UNINTERRUPTIBLE;
3226 timeout = schedule_timeout(timeout);
3232 EXPORT_SYMBOL(sleep_on_timeout);
3234 void set_user_nice(task_t *p, long nice)
3236 unsigned long flags;
3237 prio_array_t *array;
3239 int old_prio, new_prio, delta;
3241 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3244 * We have to be careful, if called from sys_setpriority(),
3245 * the task might be in the middle of scheduling on another CPU.
3247 rq = task_rq_lock(p, &flags);
3249 * The RT priorities are set via setscheduler(), but we still
3250 * allow the 'normal' nice value to be set - but as expected
3251 * it wont have any effect on scheduling until the task is
3255 p->static_prio = NICE_TO_PRIO(nice);
3260 dequeue_task(p, array);
3263 new_prio = NICE_TO_PRIO(nice);
3264 delta = new_prio - old_prio;
3265 p->static_prio = NICE_TO_PRIO(nice);
3269 enqueue_task(p, array);
3271 * If the task increased its priority or is running and
3272 * lowered its priority, then reschedule its CPU:
3274 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3275 resched_task(rq->curr);
3278 task_rq_unlock(rq, &flags);
3281 EXPORT_SYMBOL(set_user_nice);
3283 #ifdef __ARCH_WANT_SYS_NICE
3286 * sys_nice - change the priority of the current process.
3287 * @increment: priority increment
3289 * sys_setpriority is a more generic, but much slower function that
3290 * does similar things.
3292 asmlinkage long sys_nice(int increment)
3298 * Setpriority might change our priority at the same moment.
3299 * We don't have to worry. Conceptually one call occurs first
3300 * and we have a single winner.
3302 if (increment < 0) {
3303 if (!capable(CAP_SYS_NICE))
3305 if (increment < -40)
3311 nice = PRIO_TO_NICE(current->static_prio) + increment;
3317 retval = security_task_setnice(current, nice);
3321 set_user_nice(current, nice);
3328 * task_prio - return the priority value of a given task.
3329 * @p: the task in question.
3331 * This is the priority value as seen by users in /proc.
3332 * RT tasks are offset by -200. Normal tasks are centered
3333 * around 0, value goes from -16 to +15.
3335 int task_prio(const task_t *p)
3337 return p->prio - MAX_RT_PRIO;
3341 * task_nice - return the nice value of a given task.
3342 * @p: the task in question.
3344 int task_nice(const task_t *p)
3346 return TASK_NICE(p);
3349 EXPORT_SYMBOL(task_nice);
3352 * idle_cpu - is a given cpu idle currently?
3353 * @cpu: the processor in question.
3355 int idle_cpu(int cpu)
3357 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3360 EXPORT_SYMBOL_GPL(idle_cpu);
3363 * find_process_by_pid - find a process with a matching PID value.
3364 * @pid: the pid in question.
3366 static inline task_t *find_process_by_pid(pid_t pid)
3368 return pid ? find_task_by_pid(pid) : current;
3371 /* Actually do priority change: must hold rq lock. */
3372 static void __setscheduler(struct task_struct *p, int policy, int prio)
3376 p->rt_priority = prio;
3377 if (policy != SCHED_NORMAL)
3378 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
3380 p->prio = p->static_prio;
3384 * setscheduler - change the scheduling policy and/or RT priority of a thread.
3386 static int setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3388 struct sched_param lp;
3389 int retval = -EINVAL;
3391 prio_array_t *array;
3392 unsigned long flags;
3396 if (!param || pid < 0)
3400 if (copy_from_user(&lp, param, sizeof(struct sched_param)))
3404 * We play safe to avoid deadlocks.
3406 read_lock_irq(&tasklist_lock);
3408 p = find_process_by_pid(pid);
3412 goto out_unlock_tasklist;
3415 * To be able to change p->policy safely, the apropriate
3416 * runqueue lock must be held.
3418 rq = task_rq_lock(p, &flags);
3424 if (policy != SCHED_FIFO && policy != SCHED_RR &&
3425 policy != SCHED_NORMAL)
3430 * Valid priorities for SCHED_FIFO and SCHED_RR are
3431 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
3434 if (lp.sched_priority < 0 || lp.sched_priority > MAX_USER_RT_PRIO-1)
3436 if ((policy == SCHED_NORMAL) != (lp.sched_priority == 0))
3440 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
3441 !capable(CAP_SYS_NICE))
3443 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3444 !capable(CAP_SYS_NICE))
3447 retval = security_task_setscheduler(p, policy, &lp);
3453 deactivate_task(p, task_rq(p));
3456 __setscheduler(p, policy, lp.sched_priority);
3458 __activate_task(p, task_rq(p));
3460 * Reschedule if we are currently running on this runqueue and
3461 * our priority decreased, or if we are not currently running on
3462 * this runqueue and our priority is higher than the current's
3464 if (task_running(rq, p)) {
3465 if (p->prio > oldprio)
3466 resched_task(rq->curr);
3467 } else if (TASK_PREEMPTS_CURR(p, rq))
3468 resched_task(rq->curr);
3472 task_rq_unlock(rq, &flags);
3473 out_unlock_tasklist:
3474 read_unlock_irq(&tasklist_lock);
3481 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3482 * @pid: the pid in question.
3483 * @policy: new policy
3484 * @param: structure containing the new RT priority.
3486 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3487 struct sched_param __user *param)
3489 return setscheduler(pid, policy, param);
3493 * sys_sched_setparam - set/change the RT priority of a thread
3494 * @pid: the pid in question.
3495 * @param: structure containing the new RT priority.
3497 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3499 return setscheduler(pid, -1, param);
3503 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3504 * @pid: the pid in question.
3506 asmlinkage long sys_sched_getscheduler(pid_t pid)
3508 int retval = -EINVAL;
3515 read_lock(&tasklist_lock);
3516 p = find_process_by_pid(pid);
3518 retval = security_task_getscheduler(p);
3522 read_unlock(&tasklist_lock);
3529 * sys_sched_getscheduler - get the RT priority of a thread
3530 * @pid: the pid in question.
3531 * @param: structure containing the RT priority.
3533 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3535 struct sched_param lp;
3536 int retval = -EINVAL;
3539 if (!param || pid < 0)
3542 read_lock(&tasklist_lock);
3543 p = find_process_by_pid(pid);
3548 retval = security_task_getscheduler(p);
3552 lp.sched_priority = p->rt_priority;
3553 read_unlock(&tasklist_lock);
3556 * This one might sleep, we cannot do it with a spinlock held ...
3558 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3564 read_unlock(&tasklist_lock);
3569 * sys_sched_setaffinity - set the cpu affinity of a process
3570 * @pid: pid of the process
3571 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3572 * @user_mask_ptr: user-space pointer to the new cpu mask
3574 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
3575 unsigned long __user *user_mask_ptr)
3581 if (len < sizeof(new_mask))
3584 if (copy_from_user(&new_mask, user_mask_ptr, sizeof(new_mask)))
3588 read_lock(&tasklist_lock);
3590 p = find_process_by_pid(pid);
3592 read_unlock(&tasklist_lock);
3593 unlock_cpu_hotplug();
3598 * It is not safe to call set_cpus_allowed with the
3599 * tasklist_lock held. We will bump the task_struct's
3600 * usage count and then drop tasklist_lock.
3603 read_unlock(&tasklist_lock);
3606 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3607 !capable(CAP_SYS_NICE))
3610 retval = set_cpus_allowed(p, new_mask);
3614 unlock_cpu_hotplug();
3619 * Represents all cpu's present in the system
3620 * In systems capable of hotplug, this map could dynamically grow
3621 * as new cpu's are detected in the system via any platform specific
3622 * method, such as ACPI for e.g.
3625 cpumask_t cpu_present_map;
3626 EXPORT_SYMBOL(cpu_present_map);
3629 cpumask_t cpu_online_map = CPU_MASK_ALL;
3630 cpumask_t cpu_possible_map = CPU_MASK_ALL;
3634 * sys_sched_getaffinity - get the cpu affinity of a process
3635 * @pid: pid of the process
3636 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3637 * @user_mask_ptr: user-space pointer to hold the current cpu mask
3639 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
3640 unsigned long __user *user_mask_ptr)
3642 unsigned int real_len;
3647 real_len = sizeof(mask);
3652 read_lock(&tasklist_lock);
3655 p = find_process_by_pid(pid);
3660 cpus_and(mask, p->cpus_allowed, cpu_possible_map);
3663 read_unlock(&tasklist_lock);
3664 unlock_cpu_hotplug();
3667 if (copy_to_user(user_mask_ptr, &mask, real_len))
3673 * sys_sched_yield - yield the current processor to other threads.
3675 * this function yields the current CPU by moving the calling thread
3676 * to the expired array. If there are no other threads running on this
3677 * CPU then this function will return.
3679 asmlinkage long sys_sched_yield(void)
3681 runqueue_t *rq = this_rq_lock();
3682 prio_array_t *array = current->array;
3683 prio_array_t *target = rq_expired(current,rq);
3686 * We implement yielding by moving the task into the expired
3689 * (special rule: RT tasks will just roundrobin in the active
3692 if (unlikely(rt_task(current)))
3693 target = rq_active(current,rq);
3695 dequeue_task(current, array);
3696 enqueue_task(current, target);
3699 * Since we are going to call schedule() anyway, there's
3700 * no need to preempt or enable interrupts:
3702 _raw_spin_unlock(&rq->lock);
3703 preempt_enable_no_resched();
3710 void __sched __cond_resched(void)
3712 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
3713 __might_sleep(__FILE__, __LINE__, 0);
3716 * The system_state check is somewhat ugly but we might be
3717 * called during early boot when we are not yet ready to reschedule.
3719 if (need_resched() && system_state >= SYSTEM_BOOTING_SCHEDULER_OK) {
3720 set_current_state(TASK_RUNNING);
3725 EXPORT_SYMBOL(__cond_resched);
3727 void __sched __cond_resched_lock(spinlock_t * lock)
3729 if (need_resched()) {
3730 _raw_spin_unlock(lock);
3731 preempt_enable_no_resched();
3732 set_current_state(TASK_RUNNING);
3738 EXPORT_SYMBOL(__cond_resched_lock);
3741 * yield - yield the current processor to other threads.
3743 * this is a shortcut for kernel-space yielding - it marks the
3744 * thread runnable and calls sys_sched_yield().
3746 void __sched yield(void)
3748 set_current_state(TASK_RUNNING);
3752 EXPORT_SYMBOL(yield);
3755 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
3756 * that process accounting knows that this is a task in IO wait state.
3758 * But don't do that if it is a deliberate, throttling IO wait (this task
3759 * has set its backing_dev_info: the queue against which it should throttle)
3761 void __sched io_schedule(void)
3763 struct runqueue *rq = this_rq();
3764 def_delay_var(dstart);
3766 start_delay_set(dstart,PF_IOWAIT);
3767 atomic_inc(&rq->nr_iowait);
3769 atomic_dec(&rq->nr_iowait);
3770 add_io_delay(dstart);
3773 EXPORT_SYMBOL(io_schedule);
3775 long __sched io_schedule_timeout(long timeout)
3777 struct runqueue *rq = this_rq();
3779 def_delay_var(dstart);
3781 start_delay_set(dstart,PF_IOWAIT);
3782 atomic_inc(&rq->nr_iowait);
3783 ret = schedule_timeout(timeout);
3784 atomic_dec(&rq->nr_iowait);
3785 add_io_delay(dstart);
3790 * sys_sched_get_priority_max - return maximum RT priority.
3791 * @policy: scheduling class.
3793 * this syscall returns the maximum rt_priority that can be used
3794 * by a given scheduling class.
3796 asmlinkage long sys_sched_get_priority_max(int policy)
3803 ret = MAX_USER_RT_PRIO-1;
3813 * sys_sched_get_priority_min - return minimum RT priority.
3814 * @policy: scheduling class.
3816 * this syscall returns the minimum rt_priority that can be used
3817 * by a given scheduling class.
3819 asmlinkage long sys_sched_get_priority_min(int policy)
3835 * sys_sched_rr_get_interval - return the default timeslice of a process.
3836 * @pid: pid of the process.
3837 * @interval: userspace pointer to the timeslice value.
3839 * this syscall writes the default timeslice value of a given process
3840 * into the user-space timespec buffer. A value of '0' means infinity.
3843 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
3845 int retval = -EINVAL;
3853 read_lock(&tasklist_lock);
3854 p = find_process_by_pid(pid);
3858 retval = security_task_getscheduler(p);
3862 jiffies_to_timespec(p->policy & SCHED_FIFO ?
3863 0 : task_timeslice(p), &t);
3864 read_unlock(&tasklist_lock);
3865 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
3869 read_unlock(&tasklist_lock);
3873 static inline struct task_struct *eldest_child(struct task_struct *p)
3875 if (list_empty(&p->children)) return NULL;
3876 return list_entry(p->children.next,struct task_struct,sibling);
3879 static inline struct task_struct *older_sibling(struct task_struct *p)
3881 if (p->sibling.prev==&p->parent->children) return NULL;
3882 return list_entry(p->sibling.prev,struct task_struct,sibling);
3885 static inline struct task_struct *younger_sibling(struct task_struct *p)
3887 if (p->sibling.next==&p->parent->children) return NULL;
3888 return list_entry(p->sibling.next,struct task_struct,sibling);
3891 static void show_task(task_t * p)
3895 unsigned long free = 0;
3896 static const char *stat_nam[] = { "R", "S", "D", "T", "Z", "W" };
3898 printk("%-13.13s ", p->comm);
3899 state = p->state ? __ffs(p->state) + 1 : 0;
3900 if (state < ARRAY_SIZE(stat_nam))
3901 printk(stat_nam[state]);
3904 #if (BITS_PER_LONG == 32)
3905 if (state == TASK_RUNNING)
3906 printk(" running ");
3908 printk(" %08lX ", thread_saved_pc(p));
3910 if (state == TASK_RUNNING)
3911 printk(" running task ");
3913 printk(" %016lx ", thread_saved_pc(p));
3915 #ifdef CONFIG_DEBUG_STACK_USAGE
3917 unsigned long * n = (unsigned long *) (p->thread_info+1);
3920 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
3923 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
3924 if ((relative = eldest_child(p)))
3925 printk("%5d ", relative->pid);
3928 if ((relative = younger_sibling(p)))
3929 printk("%7d", relative->pid);
3932 if ((relative = older_sibling(p)))
3933 printk(" %5d", relative->pid);
3937 printk(" (L-TLB)\n");
3939 printk(" (NOTLB)\n");
3941 if (state != TASK_RUNNING)
3942 show_stack(p, NULL);
3945 void show_state(void)
3949 #if (BITS_PER_LONG == 32)
3952 printk(" task PC pid father child younger older\n");
3956 printk(" task PC pid father child younger older\n");
3958 read_lock(&tasklist_lock);
3959 do_each_thread(g, p) {
3961 * reset the NMI-timeout, listing all files on a slow
3962 * console might take alot of time:
3964 touch_nmi_watchdog();
3966 } while_each_thread(g, p);
3968 read_unlock(&tasklist_lock);
3971 EXPORT_SYMBOL_GPL(show_state);
3973 void __devinit init_idle(task_t *idle, int cpu)
3975 runqueue_t *idle_rq = cpu_rq(cpu), *rq = cpu_rq(task_cpu(idle));
3976 unsigned long flags;
3978 local_irq_save(flags);
3979 double_rq_lock(idle_rq, rq);
3981 idle_rq->curr = idle_rq->idle = idle;
3982 deactivate_task(idle, rq);
3984 idle->prio = MAX_PRIO;
3985 idle->state = TASK_RUNNING;
3986 set_task_cpu(idle, cpu);
3987 double_rq_unlock(idle_rq, rq);
3988 set_tsk_need_resched(idle);
3989 local_irq_restore(flags);
3991 /* Set the preempt count _outside_ the spinlocks! */
3992 #ifdef CONFIG_PREEMPT
3993 idle->thread_info->preempt_count = (idle->lock_depth >= 0);
3995 idle->thread_info->preempt_count = 0;
4000 * In a system that switches off the HZ timer nohz_cpu_mask
4001 * indicates which cpus entered this state. This is used
4002 * in the rcu update to wait only for active cpus. For system
4003 * which do not switch off the HZ timer nohz_cpu_mask should
4004 * always be CPU_MASK_NONE.
4006 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4010 * This is how migration works:
4012 * 1) we queue a migration_req_t structure in the source CPU's
4013 * runqueue and wake up that CPU's migration thread.
4014 * 2) we down() the locked semaphore => thread blocks.
4015 * 3) migration thread wakes up (implicitly it forces the migrated
4016 * thread off the CPU)
4017 * 4) it gets the migration request and checks whether the migrated
4018 * task is still in the wrong runqueue.
4019 * 5) if it's in the wrong runqueue then the migration thread removes
4020 * it and puts it into the right queue.
4021 * 6) migration thread up()s the semaphore.
4022 * 7) we wake up and the migration is done.
4026 * Change a given task's CPU affinity. Migrate the thread to a
4027 * proper CPU and schedule it away if the CPU it's executing on
4028 * is removed from the allowed bitmask.
4030 * NOTE: the caller must have a valid reference to the task, the
4031 * task must not exit() & deallocate itself prematurely. The
4032 * call is not atomic; no spinlocks may be held.
4034 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
4036 unsigned long flags;
4038 migration_req_t req;
4041 rq = task_rq_lock(p, &flags);
4042 if (!cpus_intersects(new_mask, cpu_online_map)) {
4047 p->cpus_allowed = new_mask;
4048 /* Can the task run on the task's current CPU? If so, we're done */
4049 if (cpu_isset(task_cpu(p), new_mask))
4052 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4053 /* Need help from migration thread: drop lock and wait. */
4054 task_rq_unlock(rq, &flags);
4055 wake_up_process(rq->migration_thread);
4056 wait_for_completion(&req.done);
4057 tlb_migrate_finish(p->mm);
4061 task_rq_unlock(rq, &flags);
4065 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4068 * Move (not current) task off this cpu, onto dest cpu. We're doing
4069 * this because either it can't run here any more (set_cpus_allowed()
4070 * away from this CPU, or CPU going down), or because we're
4071 * attempting to rebalance this task on exec (sched_balance_exec).
4073 * So we race with normal scheduler movements, but that's OK, as long
4074 * as the task is no longer on this CPU.
4076 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4078 runqueue_t *rq_dest, *rq_src;
4080 if (unlikely(cpu_is_offline(dest_cpu)))
4083 rq_src = cpu_rq(src_cpu);
4084 rq_dest = cpu_rq(dest_cpu);
4086 double_rq_lock(rq_src, rq_dest);
4087 /* Already moved. */
4088 if (task_cpu(p) != src_cpu)
4090 /* Affinity changed (again). */
4091 if (!cpu_isset(dest_cpu, p->cpus_allowed))
4096 * Sync timestamp with rq_dest's before activating.
4097 * The same thing could be achieved by doing this step
4098 * afterwards, and pretending it was a local activate.
4099 * This way is cleaner and logically correct.
4101 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4102 + rq_dest->timestamp_last_tick;
4103 deactivate_task(p, rq_src);
4104 set_task_cpu(p, dest_cpu);
4105 activate_task(p, rq_dest, 0);
4106 if (TASK_PREEMPTS_CURR(p, rq_dest))
4107 resched_task(rq_dest->curr);
4109 set_task_cpu(p, dest_cpu);
4112 double_rq_unlock(rq_src, rq_dest);
4116 * migration_thread - this is a highprio system thread that performs
4117 * thread migration by bumping thread off CPU then 'pushing' onto
4120 static int migration_thread(void * data)
4123 int cpu = (long)data;
4126 BUG_ON(rq->migration_thread != current);
4128 set_current_state(TASK_INTERRUPTIBLE);
4129 while (!kthread_should_stop()) {
4130 struct list_head *head;
4131 migration_req_t *req;
4133 if (current->flags & PF_FREEZE)
4134 refrigerator(PF_FREEZE);
4136 spin_lock_irq(&rq->lock);
4138 if (cpu_is_offline(cpu)) {
4139 spin_unlock_irq(&rq->lock);
4143 if (rq->active_balance) {
4144 active_load_balance(rq, cpu);
4145 rq->active_balance = 0;
4148 head = &rq->migration_queue;
4150 if (list_empty(head)) {
4151 spin_unlock_irq(&rq->lock);
4153 set_current_state(TASK_INTERRUPTIBLE);
4156 req = list_entry(head->next, migration_req_t, list);
4157 list_del_init(head->next);
4159 if (req->type == REQ_MOVE_TASK) {
4160 spin_unlock(&rq->lock);
4161 __migrate_task(req->task, smp_processor_id(),
4164 } else if (req->type == REQ_SET_DOMAIN) {
4166 spin_unlock_irq(&rq->lock);
4168 spin_unlock_irq(&rq->lock);
4172 complete(&req->done);
4174 __set_current_state(TASK_RUNNING);
4178 /* Wait for kthread_stop */
4179 set_current_state(TASK_INTERRUPTIBLE);
4180 while (!kthread_should_stop()) {
4182 set_current_state(TASK_INTERRUPTIBLE);
4184 __set_current_state(TASK_RUNNING);
4188 #ifdef CONFIG_HOTPLUG_CPU
4189 /* migrate_all_tasks - function to migrate all tasks from the dead cpu. */
4190 static void migrate_all_tasks(int src_cpu)
4192 struct task_struct *tsk, *t;
4196 write_lock_irq(&tasklist_lock);
4198 /* watch out for per node tasks, let's stay on this node */
4199 node = cpu_to_node(src_cpu);
4201 do_each_thread(t, tsk) {
4206 if (task_cpu(tsk) != src_cpu)
4209 /* Figure out where this task should go (attempting to
4210 * keep it on-node), and check if it can be migrated
4211 * as-is. NOTE that kernel threads bound to more than
4212 * one online cpu will be migrated. */
4213 mask = node_to_cpumask(node);
4214 cpus_and(mask, mask, tsk->cpus_allowed);
4215 dest_cpu = any_online_cpu(mask);
4216 if (dest_cpu == NR_CPUS)
4217 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4218 if (dest_cpu == NR_CPUS) {
4219 cpus_setall(tsk->cpus_allowed);
4220 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4222 /* Don't tell them about moving exiting tasks
4223 or kernel threads (both mm NULL), since
4224 they never leave kernel. */
4225 if (tsk->mm && printk_ratelimit())
4226 printk(KERN_INFO "process %d (%s) no "
4227 "longer affine to cpu%d\n",
4228 tsk->pid, tsk->comm, src_cpu);
4231 __migrate_task(tsk, src_cpu, dest_cpu);
4232 } while_each_thread(t, tsk);
4234 write_unlock_irq(&tasklist_lock);
4237 /* Schedules idle task to be the next runnable task on current CPU.
4238 * It does so by boosting its priority to highest possible and adding it to
4239 * the _front_ of runqueue. Used by CPU offline code.
4241 void sched_idle_next(void)
4243 int cpu = smp_processor_id();
4244 runqueue_t *rq = this_rq();
4245 struct task_struct *p = rq->idle;
4246 unsigned long flags;
4248 /* cpu has to be offline */
4249 BUG_ON(cpu_online(cpu));
4251 /* Strictly not necessary since rest of the CPUs are stopped by now
4252 * and interrupts disabled on current cpu.
4254 spin_lock_irqsave(&rq->lock, flags);
4256 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4257 /* Add idle task to _front_ of it's priority queue */
4258 __activate_idle_task(p, rq);
4260 spin_unlock_irqrestore(&rq->lock, flags);
4262 #endif /* CONFIG_HOTPLUG_CPU */
4265 * migration_call - callback that gets triggered when a CPU is added.
4266 * Here we can start up the necessary migration thread for the new CPU.
4268 static int migration_call(struct notifier_block *nfb, unsigned long action,
4271 int cpu = (long)hcpu;
4272 struct task_struct *p;
4273 struct runqueue *rq;
4274 unsigned long flags;
4277 case CPU_UP_PREPARE:
4278 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4281 p->flags |= PF_NOFREEZE;
4282 kthread_bind(p, cpu);
4283 /* Must be high prio: stop_machine expects to yield to it. */
4284 rq = task_rq_lock(p, &flags);
4285 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4286 task_rq_unlock(rq, &flags);
4287 cpu_rq(cpu)->migration_thread = p;
4290 /* Strictly unneccessary, as first user will wake it. */
4291 wake_up_process(cpu_rq(cpu)->migration_thread);
4293 #ifdef CONFIG_HOTPLUG_CPU
4294 case CPU_UP_CANCELED:
4295 /* Unbind it from offline cpu so it can run. Fall thru. */
4296 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
4297 kthread_stop(cpu_rq(cpu)->migration_thread);
4298 cpu_rq(cpu)->migration_thread = NULL;
4301 migrate_all_tasks(cpu);
4303 kthread_stop(rq->migration_thread);
4304 rq->migration_thread = NULL;
4305 /* Idle task back to normal (off runqueue, low prio) */
4306 rq = task_rq_lock(rq->idle, &flags);
4307 deactivate_task(rq->idle, rq);
4308 rq->idle->static_prio = MAX_PRIO;
4309 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4310 task_rq_unlock(rq, &flags);
4311 BUG_ON(rq->nr_running != 0);
4313 /* No need to migrate the tasks: it was best-effort if
4314 * they didn't do lock_cpu_hotplug(). Just wake up
4315 * the requestors. */
4316 spin_lock_irq(&rq->lock);
4317 while (!list_empty(&rq->migration_queue)) {
4318 migration_req_t *req;
4319 req = list_entry(rq->migration_queue.next,
4320 migration_req_t, list);
4321 BUG_ON(req->type != REQ_MOVE_TASK);
4322 list_del_init(&req->list);
4323 complete(&req->done);
4325 spin_unlock_irq(&rq->lock);
4332 /* Register at highest priority so that task migration (migrate_all_tasks)
4333 * happens before everything else.
4335 static struct notifier_block __devinitdata migration_notifier = {
4336 .notifier_call = migration_call,
4340 int __init migration_init(void)
4342 void *cpu = (void *)(long)smp_processor_id();
4343 /* Start one for boot CPU. */
4344 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4345 migration_call(&migration_notifier, CPU_ONLINE, cpu);
4346 register_cpu_notifier(&migration_notifier);
4352 * The 'big kernel lock'
4354 * This spinlock is taken and released recursively by lock_kernel()
4355 * and unlock_kernel(). It is transparently dropped and reaquired
4356 * over schedule(). It is used to protect legacy code that hasn't
4357 * been migrated to a proper locking design yet.
4359 * Don't use in new code.
4361 * Note: spinlock debugging needs this even on !CONFIG_SMP.
4363 spinlock_t kernel_flag __cacheline_aligned_in_smp = SPIN_LOCK_UNLOCKED;
4364 EXPORT_SYMBOL(kernel_flag);
4367 /* Attach the domain 'sd' to 'cpu' as its base domain */
4368 void cpu_attach_domain(struct sched_domain *sd, int cpu)
4370 migration_req_t req;
4371 unsigned long flags;
4372 runqueue_t *rq = cpu_rq(cpu);
4377 spin_lock_irqsave(&rq->lock, flags);
4379 if (cpu == smp_processor_id() || !cpu_online(cpu)) {
4382 init_completion(&req.done);
4383 req.type = REQ_SET_DOMAIN;
4385 list_add(&req.list, &rq->migration_queue);
4389 spin_unlock_irqrestore(&rq->lock, flags);
4392 wake_up_process(rq->migration_thread);
4393 wait_for_completion(&req.done);
4396 unlock_cpu_hotplug();
4399 #ifdef ARCH_HAS_SCHED_DOMAIN
4400 extern void __init arch_init_sched_domains(void);
4402 static struct sched_group sched_group_cpus[NR_CPUS];
4403 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
4405 static struct sched_group sched_group_nodes[MAX_NUMNODES];
4406 static DEFINE_PER_CPU(struct sched_domain, node_domains);
4407 static void __init arch_init_sched_domains(void)
4410 struct sched_group *first_node = NULL, *last_node = NULL;
4412 /* Set up domains */
4414 int node = cpu_to_node(i);
4415 cpumask_t nodemask = node_to_cpumask(node);
4416 struct sched_domain *node_sd = &per_cpu(node_domains, i);
4417 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
4419 *node_sd = SD_NODE_INIT;
4420 node_sd->span = cpu_possible_map;
4421 node_sd->groups = &sched_group_nodes[cpu_to_node(i)];
4423 *cpu_sd = SD_CPU_INIT;
4424 cpus_and(cpu_sd->span, nodemask, cpu_possible_map);
4425 cpu_sd->groups = &sched_group_cpus[i];
4426 cpu_sd->parent = node_sd;
4430 for (i = 0; i < MAX_NUMNODES; i++) {
4431 cpumask_t tmp = node_to_cpumask(i);
4433 struct sched_group *first_cpu = NULL, *last_cpu = NULL;
4434 struct sched_group *node = &sched_group_nodes[i];
4437 cpus_and(nodemask, tmp, cpu_possible_map);
4439 if (cpus_empty(nodemask))
4442 node->cpumask = nodemask;
4443 node->cpu_power = SCHED_LOAD_SCALE * cpus_weight(node->cpumask);
4445 for_each_cpu_mask(j, node->cpumask) {
4446 struct sched_group *cpu = &sched_group_cpus[j];
4448 cpus_clear(cpu->cpumask);
4449 cpu_set(j, cpu->cpumask);
4450 cpu->cpu_power = SCHED_LOAD_SCALE;
4455 last_cpu->next = cpu;
4458 last_cpu->next = first_cpu;
4463 last_node->next = node;
4466 last_node->next = first_node;
4470 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
4471 cpu_attach_domain(cpu_sd, i);
4475 #else /* !CONFIG_NUMA */
4476 static void __init arch_init_sched_domains(void)
4479 struct sched_group *first_cpu = NULL, *last_cpu = NULL;
4481 /* Set up domains */
4483 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
4485 *cpu_sd = SD_CPU_INIT;
4486 cpu_sd->span = cpu_possible_map;
4487 cpu_sd->groups = &sched_group_cpus[i];
4490 /* Set up CPU groups */
4491 for_each_cpu_mask(i, cpu_possible_map) {
4492 struct sched_group *cpu = &sched_group_cpus[i];
4494 cpus_clear(cpu->cpumask);
4495 cpu_set(i, cpu->cpumask);
4496 cpu->cpu_power = SCHED_LOAD_SCALE;
4501 last_cpu->next = cpu;
4504 last_cpu->next = first_cpu;
4506 mb(); /* domains were modified outside the lock */
4508 struct sched_domain *cpu_sd = &per_cpu(cpu_domains, i);
4509 cpu_attach_domain(cpu_sd, i);
4513 #endif /* CONFIG_NUMA */
4514 #endif /* ARCH_HAS_SCHED_DOMAIN */
4516 #define SCHED_DOMAIN_DEBUG
4517 #ifdef SCHED_DOMAIN_DEBUG
4518 void sched_domain_debug(void)
4523 runqueue_t *rq = cpu_rq(i);
4524 struct sched_domain *sd;
4529 printk(KERN_DEBUG "CPU%d: %s\n",
4530 i, (cpu_online(i) ? " online" : "offline"));
4535 struct sched_group *group = sd->groups;
4536 cpumask_t groupmask;
4538 cpumask_scnprintf(str, NR_CPUS, sd->span);
4539 cpus_clear(groupmask);
4542 for (j = 0; j < level + 1; j++)
4544 printk("domain %d: span %s\n", level, str);
4546 if (!cpu_isset(i, sd->span))
4547 printk(KERN_DEBUG "ERROR domain->span does not contain CPU%d\n", i);
4548 if (!cpu_isset(i, group->cpumask))
4549 printk(KERN_DEBUG "ERROR domain->groups does not contain CPU%d\n", i);
4550 if (!group->cpu_power)
4551 printk(KERN_DEBUG "ERROR domain->cpu_power not set\n");
4554 for (j = 0; j < level + 2; j++)
4559 printk(" ERROR: NULL");
4563 if (!cpus_weight(group->cpumask))
4564 printk(" ERROR empty group:");
4566 if (cpus_intersects(groupmask, group->cpumask))
4567 printk(" ERROR repeated CPUs:");
4569 cpus_or(groupmask, groupmask, group->cpumask);
4571 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
4574 group = group->next;
4575 } while (group != sd->groups);
4578 if (!cpus_equal(sd->span, groupmask))
4579 printk(KERN_DEBUG "ERROR groups don't span domain->span\n");
4585 if (!cpus_subset(groupmask, sd->span))
4586 printk(KERN_DEBUG "ERROR parent span is not a superset of domain->span\n");
4593 #define sched_domain_debug() {}
4596 void __init sched_init_smp(void)
4598 arch_init_sched_domains();
4599 sched_domain_debug();
4602 void __init sched_init_smp(void)
4605 #endif /* CONFIG_SMP */
4607 int in_sched_functions(unsigned long addr)
4609 /* Linker adds these: start and end of __sched functions */
4610 extern char __sched_text_start[], __sched_text_end[];
4611 return addr >= (unsigned long)__sched_text_start
4612 && addr < (unsigned long)__sched_text_end;
4615 void __init sched_init(void)
4621 /* Set up an initial dummy domain for early boot */
4622 static struct sched_domain sched_domain_init;
4623 static struct sched_group sched_group_init;
4625 memset(&sched_domain_init, 0, sizeof(struct sched_domain));
4626 sched_domain_init.span = CPU_MASK_ALL;
4627 sched_domain_init.groups = &sched_group_init;
4628 sched_domain_init.last_balance = jiffies;
4629 sched_domain_init.balance_interval = INT_MAX; /* Don't balance */
4630 sched_domain_init.busy_factor = 1;
4632 memset(&sched_group_init, 0, sizeof(struct sched_group));
4633 sched_group_init.cpumask = CPU_MASK_ALL;
4634 sched_group_init.next = &sched_group_init;
4635 sched_group_init.cpu_power = SCHED_LOAD_SCALE;
4639 for (i = 0; i < NR_CPUS; i++) {
4640 #ifndef CONFIG_CKRM_CPU_SCHEDULE
4642 prio_array_t *array;
4645 spin_lock_init(&rq->lock);
4647 for (j = 0; j < 2; j++) {
4648 array = rq->arrays + j;
4649 for (k = 0; k < MAX_PRIO; k++) {
4650 INIT_LIST_HEAD(array->queue + k);
4651 __clear_bit(k, array->bitmap);
4653 // delimiter for bitsearch
4654 __set_bit(MAX_PRIO, array->bitmap);
4657 rq->active = rq->arrays;
4658 rq->expired = rq->arrays + 1;
4661 spin_lock_init(&rq->lock);
4664 rq->best_expired_prio = MAX_PRIO;
4667 rq->sd = &sched_domain_init;
4669 #ifdef CONFIG_CKRM_CPU_SCHEDULE
4670 ckrm_load_init(rq_ckrm_load(rq));
4672 rq->active_balance = 0;
4674 rq->migration_thread = NULL;
4675 INIT_LIST_HEAD(&rq->migration_queue);
4677 #ifdef CONFIG_VSERVER_HARDCPU
4678 INIT_LIST_HEAD(&rq->hold_queue);
4680 atomic_set(&rq->nr_iowait, 0);
4684 * We have to do a little magic to get the first
4685 * thread right in SMP mode.
4690 set_task_cpu(current, smp_processor_id());
4691 #ifdef CONFIG_CKRM_CPU_SCHEDULE
4692 cpu_demand_event(&(current)->demand_stat,CPU_DEMAND_INIT,0);
4693 current->cpu_class = get_default_cpu_class();
4694 current->array = NULL;
4696 wake_up_forked_process(current);
4699 * The boot idle thread does lazy MMU switching as well:
4701 atomic_inc(&init_mm.mm_count);
4702 enter_lazy_tlb(&init_mm, current);
4705 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4706 void __might_sleep(char *file, int line, int atomic_depth)
4708 #if defined(in_atomic)
4709 static unsigned long prev_jiffy; /* ratelimiting */
4711 #ifndef CONFIG_PREEMPT
4714 if (((in_atomic() != atomic_depth) || irqs_disabled()) &&
4715 system_state == SYSTEM_RUNNING) {
4716 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
4718 prev_jiffy = jiffies;
4719 printk(KERN_ERR "Debug: sleeping function called from invalid"
4720 " context at %s:%d\n", file, line);
4721 printk("in_atomic():%d[expected: %d], irqs_disabled():%d\n",
4722 in_atomic(), atomic_depth, irqs_disabled());
4727 EXPORT_SYMBOL(__might_sleep);
4731 #if defined(CONFIG_SMP) && defined(CONFIG_PREEMPT)
4733 * This could be a long-held lock. If another CPU holds it for a long time,
4734 * and that CPU is not asked to reschedule then *this* CPU will spin on the
4735 * lock for a long time, even if *this* CPU is asked to reschedule.
4737 * So what we do here, in the slow (contended) path is to spin on the lock by
4738 * hand while permitting preemption.
4740 * Called inside preempt_disable().
4742 void __sched __preempt_spin_lock(spinlock_t *lock)
4744 if (preempt_count() > 1) {
4745 _raw_spin_lock(lock);
4750 while (spin_is_locked(lock))
4753 } while (!_raw_spin_trylock(lock));
4756 EXPORT_SYMBOL(__preempt_spin_lock);
4758 void __sched __preempt_write_lock(rwlock_t *lock)
4760 if (preempt_count() > 1) {
4761 _raw_write_lock(lock);
4767 while (rwlock_is_locked(lock))
4770 } while (!_raw_write_trylock(lock));
4773 EXPORT_SYMBOL(__preempt_write_lock);
4774 #endif /* defined(CONFIG_SMP) && defined(CONFIG_PREEMPT) */
4776 #ifdef CONFIG_DELAY_ACCT
4777 int task_running_sys(struct task_struct *p)
4779 return task_running(task_rq(p),p);
4781 EXPORT_SYMBOL(task_running_sys);
4784 #ifdef CONFIG_CKRM_CPU_SCHEDULE
4786 * return the classqueue object of a certain processor
4788 struct classqueue_struct * get_cpu_classqueue(int cpu)
4790 return (& (cpu_rq(cpu)->classqueue) );
4794 * _ckrm_cpu_change_class - change the class of a task
4796 void _ckrm_cpu_change_class(task_t *tsk, struct ckrm_cpu_class *newcls)
4798 prio_array_t *array;
4799 struct runqueue *rq;
4800 unsigned long flags;
4802 rq = task_rq_lock(tsk,&flags);
4805 dequeue_task(tsk,array);
4806 tsk->cpu_class = newcls;
4807 enqueue_task(tsk,rq_active(tsk,rq));
4809 tsk->cpu_class = newcls;
4811 task_rq_unlock(rq,&flags);