4 * Kernel scheduler and related syscalls
6 * Copyright (C) 1991-2002 Linus Torvalds
8 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
9 * make semaphores SMP safe
10 * 1998-11-19 Implemented schedule_timeout() and related stuff
12 * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
13 * hybrid priority-list and round-robin design with
14 * an array-switch method of distributing timeslices
15 * and per-CPU runqueues. Cleanups and useful suggestions
16 * by Davide Libenzi, preemptible kernel bits by Robert Love.
17 * 2003-09-03 Interactivity tuning by Con Kolivas.
18 * 2004-04-02 Scheduler domains code by Nick Piggin
21 #include <linux/module.h>
22 #include <linux/nmi.h>
23 #include <linux/init.h>
24 #include <asm/uaccess.h>
25 #include <linux/highmem.h>
26 #include <linux/smp_lock.h>
27 #include <asm/mmu_context.h>
28 #include <linux/interrupt.h>
29 #include <linux/completion.h>
30 #include <linux/kernel_stat.h>
31 #include <linux/security.h>
32 #include <linux/notifier.h>
33 #include <linux/profile.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/seq_file.h>
44 #include <linux/syscalls.h>
45 #include <linux/times.h>
46 #include <linux/vserver/sched.h>
47 #include <linux/vs_base.h>
48 #include <linux/vs_context.h>
49 #include <linux/vs_cvirt.h>
52 #include <asm/unistd.h>
55 #define cpu_to_node_mask(cpu) node_to_cpumask(cpu_to_node(cpu))
57 #define cpu_to_node_mask(cpu) (cpu_online_map)
60 /* used to soft spin in sched while dump is in progress */
61 unsigned long dump_oncpu;
62 EXPORT_SYMBOL(dump_oncpu);
65 * Convert user-nice values [ -20 ... 0 ... 19 ]
66 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
69 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
70 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
71 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
74 * 'User priority' is the nice value converted to something we
75 * can work with better when scaling various scheduler parameters,
76 * it's a [ 0 ... 39 ] range.
78 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
79 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
80 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
83 * Some helpers for converting nanosecond timing to jiffy resolution
85 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
86 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
89 * These are the 'tuning knobs' of the scheduler:
91 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
92 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
93 * Timeslices get refilled after they expire.
95 #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
96 #define DEF_TIMESLICE (100 * HZ / 1000)
97 #define ON_RUNQUEUE_WEIGHT 30
98 #define CHILD_PENALTY 95
99 #define PARENT_PENALTY 100
100 #define EXIT_WEIGHT 3
101 #define PRIO_BONUS_RATIO 25
102 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
103 #define INTERACTIVE_DELTA 2
104 #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
105 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
106 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
107 #define CREDIT_LIMIT 100
110 * If a task is 'interactive' then we reinsert it in the active
111 * array after it has expired its current timeslice. (it will not
112 * continue to run immediately, it will still roundrobin with
113 * other interactive tasks.)
115 * This part scales the interactivity limit depending on niceness.
117 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
118 * Here are a few examples of different nice levels:
120 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
121 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
122 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
123 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
124 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
126 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
127 * priority range a task can explore, a value of '1' means the
128 * task is rated interactive.)
130 * Ie. nice +19 tasks can never get 'interactive' enough to be
131 * reinserted into the active array. And only heavily CPU-hog nice -20
132 * tasks will be expired. Default nice 0 tasks are somewhere between,
133 * it takes some effort for them to get interactive, but it's not
137 #define CURRENT_BONUS(p) \
138 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
142 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
143 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
146 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
147 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
150 #define SCALE(v1,v1_max,v2_max) \
151 (v1) * (v2_max) / (v1_max)
154 (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
156 #define TASK_INTERACTIVE(p) \
157 ((p)->prio <= (p)->static_prio - DELTA(p))
159 #define INTERACTIVE_SLEEP(p) \
160 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
161 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
163 #define HIGH_CREDIT(p) \
164 ((p)->interactive_credit > CREDIT_LIMIT)
166 #define LOW_CREDIT(p) \
167 ((p)->interactive_credit < -CREDIT_LIMIT)
169 #ifdef CONFIG_CKRM_CPU_SCHEDULE
171 * if belong to different class, compare class priority
172 * otherwise compare task priority
174 #define TASK_PREEMPTS_CURR(p, rq) \
175 ( ((p)->cpu_class != (rq)->curr->cpu_class) \
176 && ((rq)->curr != (rq)->idle) && ((p) != (rq)->idle )) \
177 ? class_preempts_curr((p),(rq)->curr) \
178 : ((p)->prio < (rq)->curr->prio)
180 #define TASK_PREEMPTS_CURR(p, rq) \
181 ((p)->prio < (rq)->curr->prio)
185 * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
186 * to time slice values: [800ms ... 100ms ... 5ms]
188 * The higher a thread's priority, the bigger timeslices
189 * it gets during one round of execution. But even the lowest
190 * priority thread gets MIN_TIMESLICE worth of execution time.
193 #define SCALE_PRIO(x, prio) \
194 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO/2), MIN_TIMESLICE)
196 unsigned int task_timeslice(task_t *p)
198 if (p->static_prio < NICE_TO_PRIO(0))
199 return SCALE_PRIO(DEF_TIMESLICE*4, p->static_prio);
201 return SCALE_PRIO(DEF_TIMESLICE, p->static_prio);
203 #define task_hot(p, now, sd) ((long long) ((now) - (p)->last_ran) \
204 < (long long) (sd)->cache_hot_time)
207 * These are the runqueue data structures:
210 typedef struct runqueue runqueue_t;
211 #include <linux/ckrm_classqueue.h>
212 #include <linux/ckrm_sched.h>
215 * This is the main, per-CPU runqueue data structure.
217 * Locking rule: those places that want to lock multiple runqueues
218 * (such as the load balancing or the thread migration code), lock
219 * acquire operations must be ordered by ascending &runqueue.
225 * nr_running and cpu_load should be in the same cacheline because
226 * remote CPUs use both these fields when doing load calculation.
228 unsigned long nr_running;
230 unsigned long cpu_load;
232 unsigned long long nr_switches;
235 * This is part of a global counter where only the total sum
236 * over all CPUs matters. A task can increase this counter on
237 * one CPU and if it got migrated afterwards it may decrease
238 * it on another CPU. Always updated under the runqueue lock:
240 unsigned long nr_uninterruptible;
242 unsigned long expired_timestamp;
243 unsigned long long timestamp_last_tick;
245 struct mm_struct *prev_mm;
246 #ifdef CONFIG_CKRM_CPU_SCHEDULE
247 struct classqueue_struct classqueue;
248 ckrm_load_t ckrm_load;
250 prio_array_t *active, *expired, arrays[2];
252 int best_expired_prio;
256 struct sched_domain *sd;
258 /* For active balancing */
262 task_t *migration_thread;
263 struct list_head migration_queue;
266 #ifdef CONFIG_VSERVER_HARDCPU
267 struct list_head hold_queue;
271 #ifdef CONFIG_SCHEDSTATS
273 struct sched_info rq_sched_info;
275 /* sys_sched_yield() stats */
276 unsigned long yld_exp_empty;
277 unsigned long yld_act_empty;
278 unsigned long yld_both_empty;
279 unsigned long yld_cnt;
281 /* schedule() stats */
282 unsigned long sched_noswitch;
283 unsigned long sched_switch;
284 unsigned long sched_cnt;
285 unsigned long sched_goidle;
287 /* pull_task() stats */
288 unsigned long pt_gained[MAX_IDLE_TYPES];
289 unsigned long pt_lost[MAX_IDLE_TYPES];
291 /* active_load_balance() stats */
292 unsigned long alb_cnt;
293 unsigned long alb_lost;
294 unsigned long alb_gained;
295 unsigned long alb_failed;
297 /* try_to_wake_up() stats */
298 unsigned long ttwu_cnt;
299 unsigned long ttwu_attempts;
300 unsigned long ttwu_moved;
302 /* wake_up_new_task() stats */
303 unsigned long wunt_cnt;
304 unsigned long wunt_moved;
306 /* sched_migrate_task() stats */
307 unsigned long smt_cnt;
309 /* sched_balance_exec() stats */
310 unsigned long sbe_cnt;
314 static DEFINE_PER_CPU(struct runqueue, runqueues);
316 #define for_each_domain(cpu, domain) \
317 for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
319 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
320 #define this_rq() (&__get_cpu_var(runqueues))
321 #define task_rq(p) cpu_rq(task_cpu(p))
322 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
325 * Default context-switch locking:
327 #ifndef prepare_arch_switch
328 # define prepare_arch_switch(rq, next) do { } while (0)
329 # define finish_arch_switch(rq, next) spin_unlock_irq(&(rq)->lock)
330 # define task_running(rq, p) ((rq)->curr == (p))
334 * task_rq_lock - lock the runqueue a given task resides on and disable
335 * interrupts. Note the ordering: we can safely lookup the task_rq without
336 * explicitly disabling preemption.
338 static runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
344 local_irq_save(*flags);
346 spin_lock(&rq->lock);
347 if (unlikely(rq != task_rq(p))) {
348 spin_unlock_irqrestore(&rq->lock, *flags);
349 goto repeat_lock_task;
354 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
357 spin_unlock_irqrestore(&rq->lock, *flags);
360 #ifdef CONFIG_SCHEDSTATS
362 * bump this up when changing the output format or the meaning of an existing
363 * format, so that tools can adapt (or abort)
365 #define SCHEDSTAT_VERSION 10
367 static int show_schedstat(struct seq_file *seq, void *v)
370 enum idle_type itype;
372 seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
373 seq_printf(seq, "timestamp %lu\n", jiffies);
374 for_each_online_cpu(cpu) {
375 runqueue_t *rq = cpu_rq(cpu);
377 struct sched_domain *sd;
381 /* runqueue-specific stats */
383 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu "
384 "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
385 cpu, rq->yld_both_empty,
386 rq->yld_act_empty, rq->yld_exp_empty,
387 rq->yld_cnt, rq->sched_noswitch,
388 rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
389 rq->alb_cnt, rq->alb_gained, rq->alb_lost,
391 rq->ttwu_cnt, rq->ttwu_moved, rq->ttwu_attempts,
392 rq->wunt_cnt, rq->wunt_moved,
393 rq->smt_cnt, rq->sbe_cnt, rq->rq_sched_info.cpu_time,
394 rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
396 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES; itype++)
397 seq_printf(seq, " %lu %lu", rq->pt_gained[itype],
399 seq_printf(seq, "\n");
402 /* domain-specific stats */
403 for_each_domain(cpu, sd) {
404 char mask_str[NR_CPUS];
406 cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
407 seq_printf(seq, "domain%d %s", dcnt++, mask_str);
408 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
410 seq_printf(seq, " %lu %lu %lu %lu %lu",
412 sd->lb_failed[itype],
413 sd->lb_imbalance[itype],
414 sd->lb_nobusyq[itype],
415 sd->lb_nobusyg[itype]);
417 seq_printf(seq, " %lu %lu %lu %lu\n",
418 sd->sbe_pushed, sd->sbe_attempts,
419 sd->ttwu_wake_affine, sd->ttwu_wake_balance);
426 static int schedstat_open(struct inode *inode, struct file *file)
428 unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
429 char *buf = kmalloc(size, GFP_KERNEL);
435 res = single_open(file, show_schedstat, NULL);
437 m = file->private_data;
445 struct file_operations proc_schedstat_operations = {
446 .open = schedstat_open,
449 .release = single_release,
452 # define schedstat_inc(rq, field) rq->field++;
453 # define schedstat_add(rq, field, amt) rq->field += amt;
454 #else /* !CONFIG_SCHEDSTATS */
455 # define schedstat_inc(rq, field) do { } while (0);
456 # define schedstat_add(rq, field, amt) do { } while (0);
460 * rq_lock - lock a given runqueue and disable interrupts.
462 static runqueue_t *this_rq_lock(void)
469 spin_lock(&rq->lock);
474 static inline void rq_unlock(runqueue_t *rq)
477 spin_unlock_irq(&rq->lock);
480 #ifdef CONFIG_SCHEDSTATS
482 * Called when a process is dequeued from the active array and given
483 * the cpu. We should note that with the exception of interactive
484 * tasks, the expired queue will become the active queue after the active
485 * queue is empty, without explicitly dequeuing and requeuing tasks in the
486 * expired queue. (Interactive tasks may be requeued directly to the
487 * active queue, thus delaying tasks in the expired queue from running;
488 * see scheduler_tick()).
490 * This function is only called from sched_info_arrive(), rather than
491 * dequeue_task(). Even though a task may be queued and dequeued multiple
492 * times as it is shuffled about, we're really interested in knowing how
493 * long it was from the *first* time it was queued to the time that it
496 static inline void sched_info_dequeued(task_t *t)
498 t->sched_info.last_queued = 0;
502 * Called when a task finally hits the cpu. We can now calculate how
503 * long it was waiting to run. We also note when it began so that we
504 * can keep stats on how long its timeslice is.
506 static inline void sched_info_arrive(task_t *t)
508 unsigned long now = jiffies, diff = 0;
509 struct runqueue *rq = task_rq(t);
511 if (t->sched_info.last_queued)
512 diff = now - t->sched_info.last_queued;
513 sched_info_dequeued(t);
514 t->sched_info.run_delay += diff;
515 t->sched_info.last_arrival = now;
516 t->sched_info.pcnt++;
521 rq->rq_sched_info.run_delay += diff;
522 rq->rq_sched_info.pcnt++;
526 * Called when a process is queued into either the active or expired
527 * array. The time is noted and later used to determine how long we
528 * had to wait for us to reach the cpu. Since the expired queue will
529 * become the active queue after active queue is empty, without dequeuing
530 * and requeuing any tasks, we are interested in queuing to either. It
531 * is unusual but not impossible for tasks to be dequeued and immediately
532 * requeued in the same or another array: this can happen in sched_yield(),
533 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
536 * This function is only called from enqueue_task(), but also only updates
537 * the timestamp if it is already not set. It's assumed that
538 * sched_info_dequeued() will clear that stamp when appropriate.
540 static inline void sched_info_queued(task_t *t)
542 if (!t->sched_info.last_queued)
543 t->sched_info.last_queued = jiffies;
547 * Called when a process ceases being the active-running process, either
548 * voluntarily or involuntarily. Now we can calculate how long we ran.
550 static inline void sched_info_depart(task_t *t)
552 struct runqueue *rq = task_rq(t);
553 unsigned long diff = jiffies - t->sched_info.last_arrival;
555 t->sched_info.cpu_time += diff;
558 rq->rq_sched_info.cpu_time += diff;
562 * Called when tasks are switched involuntarily due, typically, to expiring
563 * their time slice. (This may also be called when switching to or from
564 * the idle task.) We are only called when prev != next.
566 static inline void sched_info_switch(task_t *prev, task_t *next)
568 struct runqueue *rq = task_rq(prev);
571 * prev now departs the cpu. It's not interesting to record
572 * stats about how efficient we were at scheduling the idle
575 if (prev != rq->idle)
576 sched_info_depart(prev);
578 if (next != rq->idle)
579 sched_info_arrive(next);
582 #define sched_info_queued(t) do { } while (0)
583 #define sched_info_switch(t, next) do { } while (0)
584 #endif /* CONFIG_SCHEDSTATS */
586 #ifdef CONFIG_CKRM_CPU_SCHEDULE
587 static inline ckrm_lrq_t *rq_get_next_class(struct runqueue *rq)
589 cq_node_t *node = classqueue_get_head(&rq->classqueue);
590 return ((node) ? class_list_entry(node) : NULL);
594 * return the cvt of the current running class
595 * if no current running class, return 0
596 * assume cpu is valid (cpu_online(cpu) == 1)
598 CVT_t get_local_cur_cvt(int cpu)
600 ckrm_lrq_t * lrq = rq_get_next_class(cpu_rq(cpu));
603 return lrq->local_cvt;
608 static inline struct task_struct * rq_get_next_task(struct runqueue* rq)
611 struct task_struct *next;
614 int cpu = smp_processor_id();
616 // it is guaranteed be the ( rq->nr_running > 0 ) check in
617 // schedule that a task will be found.
620 queue = rq_get_next_class(rq);
623 array = queue->active;
624 if (unlikely(!array->nr_active)) {
625 queue->active = queue->expired;
626 queue->expired = array;
627 queue->expired_timestamp = 0;
629 schedstat_inc(rq, sched_switch);
630 if (queue->active->nr_active)
631 set_top_priority(queue,
632 find_first_bit(queue->active->bitmap, MAX_PRIO));
634 classqueue_dequeue(queue->classqueue,
635 &queue->classqueue_linkobj);
636 cpu_demand_event(get_rq_local_stat(queue,cpu),CPU_DEMAND_DEQUEUE,0);
638 goto retry_next_class;
640 schedstat_inc(rq, sched_noswitch);
641 // BUG_ON(!array->nr_active);
643 idx = queue->top_priority;
644 // BUG_ON (idx == MAX_PRIO);
645 next = task_list_entry(array->queue[idx].next);
648 #else /*! CONFIG_CKRM_CPU_SCHEDULE*/
649 static inline struct task_struct * rq_get_next_task(struct runqueue* rq)
652 struct list_head *queue;
656 if (unlikely(!array->nr_active)) {
658 * Switch the active and expired arrays.
660 schedstat_inc(rq, sched_switch);
661 rq->active = rq->expired;
664 rq->expired_timestamp = 0;
665 rq->best_expired_prio = MAX_PRIO;
667 schedstat_inc(rq, sched_noswitch);
669 idx = sched_find_first_bit(array->bitmap);
670 queue = array->queue + idx;
671 return list_entry(queue->next, task_t, run_list);
674 static inline void class_enqueue_task(struct task_struct* p, prio_array_t *array) { }
675 static inline void class_dequeue_task(struct task_struct* p, prio_array_t *array) { }
676 static inline void init_cpu_classes(void) { }
677 #define rq_ckrm_load(rq) NULL
678 static inline void ckrm_sched_tick(int j,int this_cpu,void* name) {}
679 #endif /* CONFIG_CKRM_CPU_SCHEDULE */
682 * Adding/removing a task to/from a priority array:
684 static void dequeue_task(struct task_struct *p, prio_array_t *array)
687 list_del(&p->run_list);
688 if (list_empty(array->queue + p->prio))
689 __clear_bit(p->prio, array->bitmap);
690 class_dequeue_task(p,array);
693 static void enqueue_task(struct task_struct *p, prio_array_t *array)
695 sched_info_queued(p);
696 list_add_tail(&p->run_list, array->queue + p->prio);
697 __set_bit(p->prio, array->bitmap);
700 class_enqueue_task(p,array);
704 * Used by the migration code - we pull tasks from the head of the
705 * remote queue so we want these tasks to show up at the head of the
708 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
710 list_add(&p->run_list, array->queue + p->prio);
711 __set_bit(p->prio, array->bitmap);
714 class_enqueue_task(p,array);
718 * effective_prio - return the priority that is based on the static
719 * priority but is modified by bonuses/penalties.
721 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
722 * into the -5 ... 0 ... +5 bonus/penalty range.
724 * We use 25% of the full 0...39 priority range so that:
726 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
727 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
729 * Both properties are important to certain workloads.
731 static int effective_prio(task_t *p)
738 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
740 prio = p->static_prio - bonus;
742 #ifdef CONFIG_VSERVER_HARDCPU
743 if (task_vx_flags(p, VXF_SCHED_PRIO, 0))
744 prio += effective_vavavoom(p, MAX_USER_PRIO);
747 if (prio < MAX_RT_PRIO)
749 if (prio > MAX_PRIO-1)
755 * __activate_task - move a task to the runqueue.
757 static inline void __activate_task(task_t *p, runqueue_t *rq)
759 enqueue_task(p, rq_active(p,rq));
764 * __activate_idle_task - move idle task to the _front_ of runqueue.
766 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
768 enqueue_task_head(p, rq_active(p,rq));
772 static void recalc_task_prio(task_t *p, unsigned long long now)
774 unsigned long long __sleep_time = now - p->timestamp;
775 unsigned long sleep_time;
777 if (__sleep_time > NS_MAX_SLEEP_AVG)
778 sleep_time = NS_MAX_SLEEP_AVG;
780 sleep_time = (unsigned long)__sleep_time;
782 if (likely(sleep_time > 0)) {
784 * User tasks that sleep a long time are categorised as
785 * idle and will get just interactive status to stay active &
786 * prevent them suddenly becoming cpu hogs and starving
789 if (p->mm && p->activated != -1 &&
790 sleep_time > INTERACTIVE_SLEEP(p)) {
791 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
794 p->interactive_credit++;
797 * The lower the sleep avg a task has the more
798 * rapidly it will rise with sleep time.
800 sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
803 * Tasks with low interactive_credit are limited to
804 * one timeslice worth of sleep avg bonus.
807 sleep_time > JIFFIES_TO_NS(task_timeslice(p)))
808 sleep_time = JIFFIES_TO_NS(task_timeslice(p));
811 * Non high_credit tasks waking from uninterruptible
812 * sleep are limited in their sleep_avg rise as they
813 * are likely to be cpu hogs waiting on I/O
815 if (p->activated == -1 && !HIGH_CREDIT(p) && p->mm) {
816 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
818 else if (p->sleep_avg + sleep_time >=
819 INTERACTIVE_SLEEP(p)) {
820 p->sleep_avg = INTERACTIVE_SLEEP(p);
826 * This code gives a bonus to interactive tasks.
828 * The boost works by updating the 'average sleep time'
829 * value here, based on ->timestamp. The more time a
830 * task spends sleeping, the higher the average gets -
831 * and the higher the priority boost gets as well.
833 p->sleep_avg += sleep_time;
835 if (p->sleep_avg > NS_MAX_SLEEP_AVG) {
836 p->sleep_avg = NS_MAX_SLEEP_AVG;
838 p->interactive_credit++;
843 p->prio = effective_prio(p);
847 * activate_task - move a task to the runqueue and do priority recalculation
849 * Update all the scheduling statistics stuff. (sleep average
850 * calculation, priority modifiers, etc.)
852 static void activate_task(task_t *p, runqueue_t *rq, int local)
854 unsigned long long now;
859 /* Compensate for drifting sched_clock */
860 runqueue_t *this_rq = this_rq();
861 now = (now - this_rq->timestamp_last_tick)
862 + rq->timestamp_last_tick;
866 recalc_task_prio(p, now);
869 * This checks to make sure it's not an uninterruptible task
870 * that is now waking up.
874 * Tasks which were woken up by interrupts (ie. hw events)
875 * are most likely of interactive nature. So we give them
876 * the credit of extending their sleep time to the period
877 * of time they spend on the runqueue, waiting for execution
878 * on a CPU, first time around:
884 * Normal first-time wakeups get a credit too for
885 * on-runqueue time, but it will be weighted down:
893 __activate_task(p, rq);
897 * deactivate_task - remove a task from the runqueue.
899 static void __deactivate_task(struct task_struct *p, runqueue_t *rq)
902 dequeue_task(p, p->array);
907 static void deactivate_task(struct task_struct *p, runqueue_t *rq)
909 __deactivate_task(p, rq);
910 vx_deactivate_task(p);
914 * resched_task - mark a task 'to be rescheduled now'.
916 * On UP this means the setting of the need_resched flag, on SMP it
917 * might also involve a cross-CPU call to trigger the scheduler on
921 static void resched_task(task_t *p)
923 int need_resched, nrpolling;
925 BUG_ON(!spin_is_locked(&task_rq(p)->lock));
927 /* minimise the chance of sending an interrupt to poll_idle() */
928 nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
929 need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
930 nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
932 if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
933 smp_send_reschedule(task_cpu(p));
936 static inline void resched_task(task_t *p)
938 set_tsk_need_resched(p);
943 * task_curr - is this task currently executing on a CPU?
944 * @p: the task in question.
946 inline int task_curr(const task_t *p)
948 return cpu_curr(task_cpu(p)) == p;
958 struct list_head list;
959 enum request_type type;
961 /* For REQ_MOVE_TASK */
965 /* For REQ_SET_DOMAIN */
966 struct sched_domain *sd;
968 struct completion done;
972 * The task's runqueue lock must be held.
973 * Returns true if you have to wait for migration thread.
975 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
977 runqueue_t *rq = task_rq(p);
980 * If the task is not on a runqueue (and not running), then
981 * it is sufficient to simply update the task's cpu field.
983 if (!p->array && !task_running(rq, p)) {
984 set_task_cpu(p, dest_cpu);
988 init_completion(&req->done);
989 req->type = REQ_MOVE_TASK;
991 req->dest_cpu = dest_cpu;
992 list_add(&req->list, &rq->migration_queue);
997 * wait_task_inactive - wait for a thread to unschedule.
999 * The caller must ensure that the task *will* unschedule sometime soon,
1000 * else this function might spin for a *long* time. This function can't
1001 * be called with interrupts off, or it may introduce deadlock with
1002 * smp_call_function() if an IPI is sent by the same process we are
1003 * waiting to become inactive.
1005 void wait_task_inactive(task_t * p)
1007 unsigned long flags;
1012 rq = task_rq_lock(p, &flags);
1013 /* Must be off runqueue entirely, not preempted. */
1014 if (unlikely(p->array)) {
1015 /* If it's preempted, we yield. It could be a while. */
1016 preempted = !task_running(rq, p);
1017 task_rq_unlock(rq, &flags);
1023 task_rq_unlock(rq, &flags);
1027 * kick_process - kick a running thread to enter/exit the kernel
1028 * @p: the to-be-kicked thread
1030 * Cause a process which is running on another CPU to enter
1031 * kernel-mode, without any delay. (to get signals handled.)
1033 void kick_process(task_t *p)
1039 if ((cpu != smp_processor_id()) && task_curr(p))
1040 smp_send_reschedule(cpu);
1045 * Return a low guess at the load of a migration-source cpu.
1047 * We want to under-estimate the load of migration sources, to
1048 * balance conservatively.
1050 static inline unsigned long source_load(int cpu)
1052 runqueue_t *rq = cpu_rq(cpu);
1053 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
1055 return min(rq->cpu_load, load_now);
1059 * Return a high guess at the load of a migration-target cpu
1061 static inline unsigned long target_load(int cpu)
1063 runqueue_t *rq = cpu_rq(cpu);
1064 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
1066 return max(rq->cpu_load, load_now);
1072 * wake_idle() is useful especially on SMT architectures to wake a
1073 * task onto an idle sibling if we would otherwise wake it onto a
1076 * Returns the CPU we should wake onto.
1078 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1079 static int wake_idle(int cpu, task_t *p)
1082 runqueue_t *rq = cpu_rq(cpu);
1083 struct sched_domain *sd;
1090 if (!(sd->flags & SD_WAKE_IDLE))
1093 cpus_and(tmp, sd->span, p->cpus_allowed);
1095 for_each_cpu_mask(i, tmp) {
1103 static inline int wake_idle(int cpu, task_t *p)
1110 * try_to_wake_up - wake up a thread
1111 * @p: the to-be-woken-up thread
1112 * @state: the mask of task states that can be woken
1113 * @sync: do a synchronous wakeup?
1115 * Put it on the run-queue if it's not already there. The "current"
1116 * thread is always on the run-queue (except when the actual
1117 * re-schedule is in progress), and as such you're allowed to do
1118 * the simpler "current->state = TASK_RUNNING" to mark yourself
1119 * runnable without the overhead of this.
1121 * returns failure only if the task is already active.
1123 static int try_to_wake_up(task_t * p, unsigned int state, int sync)
1125 int cpu, this_cpu, success = 0;
1126 unsigned long flags;
1130 unsigned long load, this_load;
1131 struct sched_domain *sd;
1135 rq = task_rq_lock(p, &flags);
1136 schedstat_inc(rq, ttwu_cnt);
1137 old_state = p->state;
1138 if (!(old_state & state))
1145 this_cpu = smp_processor_id();
1148 if (unlikely(task_running(rq, p)))
1153 if (cpu == this_cpu || unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1156 load = source_load(cpu);
1157 this_load = target_load(this_cpu);
1160 * If sync wakeup then subtract the (maximum possible) effect of
1161 * the currently running task from the load of the current CPU:
1164 this_load -= SCHED_LOAD_SCALE;
1166 /* Don't pull the task off an idle CPU to a busy one */
1167 if (load < SCHED_LOAD_SCALE/2 && this_load > SCHED_LOAD_SCALE/2)
1170 new_cpu = this_cpu; /* Wake to this CPU if we can */
1173 * Scan domains for affine wakeup and passive balancing
1176 for_each_domain(this_cpu, sd) {
1177 unsigned int imbalance;
1179 * Start passive balancing when half the imbalance_pct
1182 imbalance = sd->imbalance_pct + (sd->imbalance_pct - 100) / 2;
1184 if ((sd->flags & SD_WAKE_AFFINE) &&
1185 !task_hot(p, rq->timestamp_last_tick, sd)) {
1187 * This domain has SD_WAKE_AFFINE and p is cache cold
1190 if (cpu_isset(cpu, sd->span)) {
1191 schedstat_inc(sd, ttwu_wake_affine);
1194 } else if ((sd->flags & SD_WAKE_BALANCE) &&
1195 imbalance*this_load <= 100*load) {
1197 * This domain has SD_WAKE_BALANCE and there is
1200 if (cpu_isset(cpu, sd->span)) {
1201 schedstat_inc(sd, ttwu_wake_balance);
1207 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1209 schedstat_inc(rq, ttwu_attempts);
1210 new_cpu = wake_idle(new_cpu, p);
1211 if (new_cpu != cpu && cpu_isset(new_cpu, p->cpus_allowed)) {
1212 schedstat_inc(rq, ttwu_moved);
1213 set_task_cpu(p, new_cpu);
1214 task_rq_unlock(rq, &flags);
1215 /* might preempt at this point */
1216 rq = task_rq_lock(p, &flags);
1217 old_state = p->state;
1218 if (!(old_state & state))
1223 this_cpu = smp_processor_id();
1228 #endif /* CONFIG_SMP */
1229 if (old_state == TASK_UNINTERRUPTIBLE) {
1230 rq->nr_uninterruptible--;
1232 * Tasks on involuntary sleep don't earn
1233 * sleep_avg beyond just interactive state.
1239 * Sync wakeups (i.e. those types of wakeups where the waker
1240 * has indicated that it will leave the CPU in short order)
1241 * don't trigger a preemption, if the woken up task will run on
1242 * this cpu. (in this case the 'I will reschedule' promise of
1243 * the waker guarantees that the freshly woken up task is going
1244 * to be considered on this CPU.)
1246 activate_task(p, rq, cpu == this_cpu);
1247 if (!sync || cpu != this_cpu) {
1248 if (TASK_PREEMPTS_CURR(p, rq))
1249 resched_task(rq->curr);
1254 p->state = TASK_RUNNING;
1256 task_rq_unlock(rq, &flags);
1261 int fastcall wake_up_process(task_t * p)
1263 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1264 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1267 EXPORT_SYMBOL(wake_up_process);
1269 int fastcall wake_up_state(task_t *p, unsigned int state)
1271 return try_to_wake_up(p, state, 0);
1275 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1276 struct sched_domain *sd);
1280 * Perform scheduler related setup for a newly forked process p.
1281 * p is forked by current.
1283 void fastcall sched_fork(task_t *p)
1286 * We mark the process as running here, but have not actually
1287 * inserted it onto the runqueue yet. This guarantees that
1288 * nobody will actually run it, and a signal or other external
1289 * event cannot wake it up and insert it on the runqueue either.
1291 p->state = TASK_RUNNING;
1292 INIT_LIST_HEAD(&p->run_list);
1294 spin_lock_init(&p->switch_lock);
1295 #ifdef CONFIG_SCHEDSTATS
1296 memset(&p->sched_info, 0, sizeof(p->sched_info));
1298 #ifdef CONFIG_CKRM_CPU_SCHEDULE
1299 cpu_demand_event(&p->demand_stat,CPU_DEMAND_INIT,0);
1301 #ifdef CONFIG_PREEMPT
1303 * During context-switch we hold precisely one spinlock, which
1304 * schedule_tail drops. (in the common case it's this_rq()->lock,
1305 * but it also can be p->switch_lock.) So we compensate with a count
1306 * of 1. Also, we want to start with kernel preemption disabled.
1308 p->thread_info->preempt_count = 1;
1311 * Share the timeslice between parent and child, thus the
1312 * total amount of pending timeslices in the system doesn't change,
1313 * resulting in more scheduling fairness.
1315 local_irq_disable();
1316 p->time_slice = (current->time_slice + 1) >> 1;
1318 * The remainder of the first timeslice might be recovered by
1319 * the parent if the child exits early enough.
1321 p->first_time_slice = 1;
1322 current->time_slice >>= 1;
1323 p->timestamp = sched_clock();
1324 if (unlikely(!current->time_slice)) {
1326 * This case is rare, it happens when the parent has only
1327 * a single jiffy left from its timeslice. Taking the
1328 * runqueue lock is not a problem.
1330 current->time_slice = 1;
1332 scheduler_tick(0, 0);
1340 * wake_up_new_task - wake up a newly created task for the first time.
1342 * This function will do some initial scheduler statistics housekeeping
1343 * that must be done for every newly created context, then puts the task
1344 * on the runqueue and wakes it.
1346 void fastcall wake_up_new_task(task_t * p, unsigned long clone_flags)
1348 unsigned long flags;
1350 runqueue_t *rq, *this_rq;
1352 rq = task_rq_lock(p, &flags);
1354 this_cpu = smp_processor_id();
1356 BUG_ON(p->state != TASK_RUNNING);
1358 schedstat_inc(rq, wunt_cnt);
1360 * We decrease the sleep average of forking parents
1361 * and children as well, to keep max-interactive tasks
1362 * from forking tasks that are max-interactive. The parent
1363 * (current) is done further down, under its lock.
1365 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1366 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1368 p->interactive_credit = 0;
1370 p->prio = effective_prio(p);
1372 vx_activate_task(p);
1373 if (likely(cpu == this_cpu)) {
1374 if (!(clone_flags & CLONE_VM)) {
1376 * The VM isn't cloned, so we're in a good position to
1377 * do child-runs-first in anticipation of an exec. This
1378 * usually avoids a lot of COW overhead.
1380 if (unlikely(!current->array))
1381 __activate_task(p, rq);
1383 p->prio = current->prio;
1384 list_add_tail(&p->run_list, ¤t->run_list);
1385 p->array = current->array;
1386 p->array->nr_active++;
1388 class_enqueue_task(p,p->array);
1392 /* Run child last */
1393 __activate_task(p, rq);
1395 * We skip the following code due to cpu == this_cpu
1397 * task_rq_unlock(rq, &flags);
1398 * this_rq = task_rq_lock(current, &flags);
1402 this_rq = cpu_rq(this_cpu);
1405 * Not the local CPU - must adjust timestamp. This should
1406 * get optimised away in the !CONFIG_SMP case.
1408 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1409 + rq->timestamp_last_tick;
1410 __activate_task(p, rq);
1411 if (TASK_PREEMPTS_CURR(p, rq))
1412 resched_task(rq->curr);
1414 schedstat_inc(rq, wunt_moved);
1416 * Parent and child are on different CPUs, now get the
1417 * parent runqueue to update the parent's ->sleep_avg:
1419 task_rq_unlock(rq, &flags);
1420 this_rq = task_rq_lock(current, &flags);
1422 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1423 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1424 task_rq_unlock(this_rq, &flags);
1428 * Potentially available exiting-child timeslices are
1429 * retrieved here - this way the parent does not get
1430 * penalized for creating too many threads.
1432 * (this cannot be used to 'generate' timeslices
1433 * artificially, because any timeslice recovered here
1434 * was given away by the parent in the first place.)
1436 void fastcall sched_exit(task_t * p)
1438 unsigned long flags;
1442 * If the child was a (relative-) CPU hog then decrease
1443 * the sleep_avg of the parent as well.
1445 rq = task_rq_lock(p->parent, &flags);
1446 if (p->first_time_slice) {
1447 p->parent->time_slice += p->time_slice;
1448 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1449 p->parent->time_slice = task_timeslice(p);
1451 if (p->sleep_avg < p->parent->sleep_avg)
1452 p->parent->sleep_avg = p->parent->sleep_avg /
1453 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1455 task_rq_unlock(rq, &flags);
1459 * finish_task_switch - clean up after a task-switch
1460 * @prev: the thread we just switched away from.
1462 * We enter this with the runqueue still locked, and finish_arch_switch()
1463 * will unlock it along with doing any other architecture-specific cleanup
1466 * Note that we may have delayed dropping an mm in context_switch(). If
1467 * so, we finish that here outside of the runqueue lock. (Doing it
1468 * with the lock held can cause deadlocks; see schedule() for
1471 static void finish_task_switch(task_t *prev)
1472 __releases(rq->lock)
1474 runqueue_t *rq = this_rq();
1475 struct mm_struct *mm = rq->prev_mm;
1476 unsigned long prev_task_flags;
1481 * A task struct has one reference for the use as "current".
1482 * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1483 * calls schedule one last time. The schedule call will never return,
1484 * and the scheduled task must drop that reference.
1485 * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1486 * still held, otherwise prev could be scheduled on another cpu, die
1487 * there before we look at prev->state, and then the reference would
1489 * Manfred Spraul <manfred@colorfullife.com>
1491 prev_task_flags = prev->flags;
1492 finish_arch_switch(rq, prev);
1495 if (unlikely(prev_task_flags & PF_DEAD))
1496 put_task_struct(prev);
1500 * schedule_tail - first thing a freshly forked thread must call.
1501 * @prev: the thread we just switched away from.
1503 asmlinkage void schedule_tail(task_t *prev)
1504 __releases(rq->lock)
1506 finish_task_switch(prev);
1508 if (current->set_child_tid)
1509 put_user(current->pid, current->set_child_tid);
1513 * context_switch - switch to the new MM and the new
1514 * thread's register state.
1517 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1519 struct mm_struct *mm = next->mm;
1520 struct mm_struct *oldmm = prev->active_mm;
1522 if (unlikely(!mm)) {
1523 next->active_mm = oldmm;
1524 atomic_inc(&oldmm->mm_count);
1525 enter_lazy_tlb(oldmm, next);
1527 switch_mm(oldmm, mm, next);
1529 if (unlikely(!prev->mm)) {
1530 prev->active_mm = NULL;
1531 WARN_ON(rq->prev_mm);
1532 rq->prev_mm = oldmm;
1535 /* Here we just switch the register state and the stack. */
1536 switch_to(prev, next, prev);
1542 * nr_running, nr_uninterruptible and nr_context_switches:
1544 * externally visible scheduler statistics: current number of runnable
1545 * threads, current number of uninterruptible-sleeping threads, total
1546 * number of context switches performed since bootup.
1548 unsigned long nr_running(void)
1550 unsigned long i, sum = 0;
1552 for_each_online_cpu(i)
1553 sum += cpu_rq(i)->nr_running;
1558 unsigned long nr_uninterruptible(void)
1560 unsigned long i, sum = 0;
1563 sum += cpu_rq(i)->nr_uninterruptible;
1566 * Since we read the counters lockless, it might be slightly
1567 * inaccurate. Do not allow it to go below zero though:
1569 if (unlikely((long)sum < 0))
1575 unsigned long long nr_context_switches(void)
1577 unsigned long long i, sum = 0;
1580 sum += cpu_rq(i)->nr_switches;
1585 unsigned long nr_iowait(void)
1587 unsigned long i, sum = 0;
1590 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1598 * double_rq_lock - safely lock two runqueues
1600 * Note this does not disable interrupts like task_rq_lock,
1601 * you need to do so manually before calling.
1603 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1604 __acquires(rq1->lock)
1605 __acquires(rq2->lock)
1608 spin_lock(&rq1->lock);
1609 __acquire(rq2->lock); /* Fake it out ;) */
1612 spin_lock(&rq1->lock);
1613 spin_lock(&rq2->lock);
1615 spin_lock(&rq2->lock);
1616 spin_lock(&rq1->lock);
1622 * double_rq_unlock - safely unlock two runqueues
1624 * Note this does not restore interrupts like task_rq_unlock,
1625 * you need to do so manually after calling.
1627 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1628 __releases(rq1->lock)
1629 __releases(rq2->lock)
1631 spin_unlock(&rq1->lock);
1633 spin_unlock(&rq2->lock);
1635 __release(rq2->lock);
1639 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1641 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1642 __releases(this_rq->lock)
1643 __acquires(busiest->lock)
1644 __acquires(this_rq->lock)
1646 if (unlikely(!spin_trylock(&busiest->lock))) {
1647 if (busiest < this_rq) {
1648 spin_unlock(&this_rq->lock);
1649 spin_lock(&busiest->lock);
1650 spin_lock(&this_rq->lock);
1652 spin_lock(&busiest->lock);
1657 * find_idlest_cpu - find the least busy runqueue.
1659 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1660 struct sched_domain *sd)
1662 unsigned long load, min_load, this_load;
1667 min_load = ULONG_MAX;
1669 cpus_and(mask, sd->span, p->cpus_allowed);
1671 for_each_cpu_mask(i, mask) {
1672 load = target_load(i);
1674 if (load < min_load) {
1678 /* break out early on an idle CPU: */
1684 /* add +1 to account for the new task */
1685 this_load = source_load(this_cpu) + SCHED_LOAD_SCALE;
1688 * Would with the addition of the new task to the
1689 * current CPU there be an imbalance between this
1690 * CPU and the idlest CPU?
1692 * Use half of the balancing threshold - new-context is
1693 * a good opportunity to balance.
1695 if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1702 * If dest_cpu is allowed for this process, migrate the task to it.
1703 * This is accomplished by forcing the cpu_allowed mask to only
1704 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1705 * the cpu_allowed mask is restored.
1707 static void sched_migrate_task(task_t *p, int dest_cpu)
1709 migration_req_t req;
1711 unsigned long flags;
1713 rq = task_rq_lock(p, &flags);
1714 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1715 || unlikely(cpu_is_offline(dest_cpu)))
1718 schedstat_inc(rq, smt_cnt);
1719 /* force the process onto the specified CPU */
1720 if (migrate_task(p, dest_cpu, &req)) {
1721 /* Need to wait for migration thread (might exit: take ref). */
1722 struct task_struct *mt = rq->migration_thread;
1723 get_task_struct(mt);
1724 task_rq_unlock(rq, &flags);
1725 wake_up_process(mt);
1726 put_task_struct(mt);
1727 wait_for_completion(&req.done);
1731 task_rq_unlock(rq, &flags);
1735 * sched_exec(): find the highest-level, exec-balance-capable
1736 * domain and try to migrate the task to the least loaded CPU.
1738 * execve() is a valuable balancing opportunity, because at this point
1739 * the task has the smallest effective memory and cache footprint.
1741 void sched_exec(void)
1743 struct sched_domain *tmp, *sd = NULL;
1744 int new_cpu, this_cpu = get_cpu();
1746 schedstat_inc(this_rq(), sbe_cnt);
1747 /* Prefer the current CPU if there's only this task running */
1748 if (this_rq()->nr_running <= 1)
1751 for_each_domain(this_cpu, tmp)
1752 if (tmp->flags & SD_BALANCE_EXEC)
1756 schedstat_inc(sd, sbe_attempts);
1757 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1758 if (new_cpu != this_cpu) {
1759 schedstat_inc(sd, sbe_pushed);
1761 sched_migrate_task(current, new_cpu);
1770 * pull_task - move a task from a remote runqueue to the local runqueue.
1771 * Both runqueues must be locked.
1774 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1775 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1777 dequeue_task(p, src_array);
1778 src_rq->nr_running--;
1779 set_task_cpu(p, this_cpu);
1780 this_rq->nr_running++;
1781 enqueue_task(p, this_array);
1782 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1783 + this_rq->timestamp_last_tick;
1785 * Note that idle threads have a prio of MAX_PRIO, for this test
1786 * to be always true for them.
1788 if (TASK_PREEMPTS_CURR(p, this_rq))
1789 resched_task(this_rq->curr);
1793 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1796 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1797 struct sched_domain *sd, enum idle_type idle)
1800 * We do not migrate tasks that are:
1801 * 1) running (obviously), or
1802 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1803 * 3) are cache-hot on their current CPU.
1805 if (task_running(rq, p))
1807 if (!cpu_isset(this_cpu, p->cpus_allowed))
1810 /* Aggressive migration if we've failed balancing */
1811 if (idle == NEWLY_IDLE ||
1812 sd->nr_balance_failed < sd->cache_nice_tries) {
1813 if (task_hot(p, rq->timestamp_last_tick, sd))
1820 #ifdef CONFIG_CKRM_CPU_SCHEDULE
1821 static inline int ckrm_preferred_task(task_t *tmp,long min, long max,
1822 int phase, enum idle_type idle)
1824 long pressure = task_load(tmp);
1829 if ((idle == NOT_IDLE) && ! phase && (pressure <= min))
1835 * move tasks for a specic local class
1836 * return number of tasks pulled
1838 static inline int ckrm_cls_move_tasks(ckrm_lrq_t* src_lrq,ckrm_lrq_t*dst_lrq,
1839 runqueue_t *this_rq,
1840 runqueue_t *busiest,
1841 struct sched_domain *sd,
1843 enum idle_type idle,
1844 long* pressure_imbalance)
1846 prio_array_t *array, *dst_array;
1847 struct list_head *head, *curr;
1852 long pressure_min, pressure_max;
1853 /*hzheng: magic : 90% balance is enough*/
1854 long balance_min = *pressure_imbalance / 10;
1856 * we don't want to migrate tasks that will reverse the balance
1857 * or the tasks that make too small difference
1859 #define CKRM_BALANCE_MAX_RATIO 100
1860 #define CKRM_BALANCE_MIN_RATIO 1
1864 * We first consider expired tasks. Those will likely not be
1865 * executed in the near future, and they are most likely to
1866 * be cache-cold, thus switching CPUs has the least effect
1869 if (src_lrq->expired->nr_active) {
1870 array = src_lrq->expired;
1871 dst_array = dst_lrq->expired;
1873 array = src_lrq->active;
1874 dst_array = dst_lrq->active;
1878 /* Start searching at priority 0: */
1882 idx = sched_find_first_bit(array->bitmap);
1884 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1885 if (idx >= MAX_PRIO) {
1886 if (array == src_lrq->expired && src_lrq->active->nr_active) {
1887 array = src_lrq->active;
1888 dst_array = dst_lrq->active;
1891 if ((! phase) && (! pulled) && (idle != IDLE))
1892 goto start; //try again
1894 goto out; //finished search for this lrq
1897 head = array->queue + idx;
1900 tmp = list_entry(curr, task_t, run_list);
1904 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
1911 pressure_min = *pressure_imbalance * CKRM_BALANCE_MIN_RATIO/100;
1912 pressure_max = *pressure_imbalance * CKRM_BALANCE_MAX_RATIO/100;
1914 * skip the tasks that will reverse the balance too much
1916 if (ckrm_preferred_task(tmp,pressure_min,pressure_max,phase,idle)) {
1917 *pressure_imbalance -= task_load(tmp);
1918 pull_task(busiest, array, tmp,
1919 this_rq, dst_array, this_cpu);
1922 if (*pressure_imbalance <= balance_min)
1934 static inline long ckrm_rq_imbalance(runqueue_t *this_rq,runqueue_t *dst_rq)
1938 * make sure after balance, imbalance' > - imbalance/2
1939 * we don't want the imbalance be reversed too much
1941 imbalance = pid_get_pressure(rq_ckrm_load(dst_rq),0)
1942 - pid_get_pressure(rq_ckrm_load(this_rq),1);
1948 * try to balance the two runqueues
1950 * Called with both runqueues locked.
1951 * if move_tasks is called, it will try to move at least one task over
1953 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1954 unsigned long max_nr_move, struct sched_domain *sd,
1955 enum idle_type idle)
1957 struct ckrm_cpu_class *clsptr,*vip_cls = NULL;
1958 ckrm_lrq_t* src_lrq,*dst_lrq;
1959 long pressure_imbalance, pressure_imbalance_old;
1960 int src_cpu = task_cpu(busiest->curr);
1961 struct list_head *list;
1965 imbalance = ckrm_rq_imbalance(this_rq,busiest);
1967 if ((idle == NOT_IDLE && imbalance <= 0) || busiest->nr_running <= 1)
1970 //try to find the vip class
1971 list_for_each_entry(clsptr,&active_cpu_classes,links) {
1972 src_lrq = get_ckrm_lrq(clsptr,src_cpu);
1974 if (! lrq_nr_running(src_lrq))
1977 if (! vip_cls || cpu_class_weight(vip_cls) < cpu_class_weight(clsptr) )
1984 * do search from the most significant class
1985 * hopefully, less tasks will be migrated this way
1994 src_lrq = get_ckrm_lrq(clsptr,src_cpu);
1995 if (! lrq_nr_running(src_lrq))
1998 dst_lrq = get_ckrm_lrq(clsptr,this_cpu);
2000 //how much pressure for this class should be transferred
2001 pressure_imbalance = src_lrq->lrq_load * imbalance/src_lrq->local_weight;
2002 if (pulled && ! pressure_imbalance)
2005 pressure_imbalance_old = pressure_imbalance;
2009 ckrm_cls_move_tasks(src_lrq,dst_lrq,
2013 &pressure_imbalance);
2016 * hzheng: 2 is another magic number
2017 * stop balancing if the imbalance is less than 25% of the orig
2019 if (pressure_imbalance <= (pressure_imbalance_old >> 2))
2023 imbalance *= pressure_imbalance / pressure_imbalance_old;
2026 list = clsptr->links.next;
2027 if (list == &active_cpu_classes)
2029 clsptr = list_entry(list, typeof(*clsptr), links);
2030 if (clsptr != vip_cls)
2037 * ckrm_check_balance - is load balancing necessary?
2038 * return 0 if load balancing is not necessary
2039 * otherwise return the average load of the system
2040 * also, update nr_group
2043 * no load balancing if it's load is over average
2044 * no load balancing if it's load is far more than the min
2046 * read the status of all the runqueues
2048 static unsigned long ckrm_check_balance(struct sched_domain *sd, int this_cpu,
2049 enum idle_type idle, int* nr_group)
2051 struct sched_group *group = sd->groups;
2052 unsigned long min_load, max_load, avg_load;
2053 unsigned long total_load, this_load, total_pwr;
2055 max_load = this_load = total_load = total_pwr = 0;
2056 min_load = 0xFFFFFFFF;
2065 /* Tally up the load of all CPUs in the group */
2066 cpus_and(tmp, group->cpumask, cpu_online_map);
2067 if (unlikely(cpus_empty(tmp)))
2071 local_group = cpu_isset(this_cpu, group->cpumask);
2073 for_each_cpu_mask(i, tmp) {
2074 load = pid_get_pressure(rq_ckrm_load(cpu_rq(i)),local_group);
2082 total_load += avg_load;
2083 total_pwr += group->cpu_power;
2085 /* Adjust by relative CPU power of the group */
2086 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
2089 this_load = avg_load;
2091 } else if (avg_load > max_load) {
2092 max_load = avg_load;
2094 if (avg_load < min_load) {
2095 min_load = avg_load;
2098 group = group->next;
2099 *nr_group = *nr_group + 1;
2100 } while (group != sd->groups);
2102 if (!max_load || this_load >= max_load)
2105 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2107 /* hzheng: debugging: 105 is a magic number
2108 * 100*max_load <= sd->imbalance_pct*this_load)
2109 * should use imbalance_pct instead
2111 if (this_load > avg_load
2112 || 100*max_load < 105*this_load
2113 || 100*min_load < 70*this_load
2123 * any group that has above average load is considered busy
2124 * find the busiest queue from any of busy group
2127 ckrm_find_busy_queue(struct sched_domain *sd, int this_cpu,
2128 unsigned long avg_load, enum idle_type idle,
2131 struct sched_group *group;
2132 runqueue_t * busiest=NULL;
2136 rand = get_ckrm_rand(nr_group);
2140 unsigned long load,total_load,max_load;
2143 runqueue_t * grp_busiest;
2145 cpus_and(tmp, group->cpumask, cpu_online_map);
2146 if (unlikely(cpus_empty(tmp)))
2147 goto find_nextgroup;
2152 for_each_cpu_mask(i, tmp) {
2153 load = pid_get_pressure(rq_ckrm_load(cpu_rq(i)),0);
2155 if (load > max_load) {
2157 grp_busiest = cpu_rq(i);
2161 total_load = (total_load * SCHED_LOAD_SCALE) / group->cpu_power;
2162 if (total_load > avg_load) {
2163 busiest = grp_busiest;
2164 if (nr_group >= rand)
2168 group = group->next;
2170 } while (group != sd->groups);
2176 * load_balance - pressure based load balancing algorithm used by ckrm
2178 static int ckrm_load_balance(int this_cpu, runqueue_t *this_rq,
2179 struct sched_domain *sd, enum idle_type idle)
2181 runqueue_t *busiest;
2182 unsigned long avg_load;
2183 int nr_moved,nr_group;
2185 avg_load = ckrm_check_balance(sd, this_cpu, idle, &nr_group);
2189 busiest = ckrm_find_busy_queue(sd,this_cpu,avg_load,idle,nr_group);
2193 * This should be "impossible", but since load
2194 * balancing is inherently racy and statistical,
2195 * it could happen in theory.
2197 if (unlikely(busiest == this_rq)) {
2203 if (busiest->nr_running > 1) {
2205 * Attempt to move tasks. If find_busiest_group has found
2206 * an imbalance but busiest->nr_running <= 1, the group is
2207 * still unbalanced. nr_moved simply stays zero, so it is
2208 * correctly treated as an imbalance.
2210 double_lock_balance(this_rq, busiest);
2211 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2213 spin_unlock(&busiest->lock);
2215 adjust_local_weight();
2220 sd->nr_balance_failed ++;
2222 sd->nr_balance_failed = 0;
2224 /* We were unbalanced, so reset the balancing interval */
2225 sd->balance_interval = sd->min_interval;
2230 /* tune up the balancing interval */
2231 if (sd->balance_interval < sd->max_interval)
2232 sd->balance_interval *= 2;
2238 * this_rq->lock is already held
2240 static inline int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2241 struct sched_domain *sd)
2244 read_lock(&class_list_lock);
2245 ret = ckrm_load_balance(this_cpu,this_rq,sd,NEWLY_IDLE);
2246 read_unlock(&class_list_lock);
2250 static inline int load_balance(int this_cpu, runqueue_t *this_rq,
2251 struct sched_domain *sd, enum idle_type idle)
2255 spin_lock(&this_rq->lock);
2256 read_lock(&class_list_lock);
2257 ret= ckrm_load_balance(this_cpu,this_rq,sd,NEWLY_IDLE);
2258 read_unlock(&class_list_lock);
2259 spin_unlock(&this_rq->lock);
2262 #else /*! CONFIG_CKRM_CPU_SCHEDULE */
2264 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
2265 * as part of a balancing operation within "domain". Returns the number of
2268 * Called with both runqueues locked.
2270 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
2271 unsigned long max_nr_move, struct sched_domain *sd,
2272 enum idle_type idle)
2274 prio_array_t *array, *dst_array;
2275 struct list_head *head, *curr;
2276 int idx, pulled = 0;
2279 if (max_nr_move <= 0 || busiest->nr_running <= 1)
2283 * We first consider expired tasks. Those will likely not be
2284 * executed in the near future, and they are most likely to
2285 * be cache-cold, thus switching CPUs has the least effect
2288 if (busiest->expired->nr_active) {
2289 array = busiest->expired;
2290 dst_array = this_rq->expired;
2292 array = busiest->active;
2293 dst_array = this_rq->active;
2297 /* Start searching at priority 0: */
2301 idx = sched_find_first_bit(array->bitmap);
2303 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
2304 if (idx >= MAX_PRIO) {
2305 if (array == busiest->expired && busiest->active->nr_active) {
2306 array = busiest->active;
2307 dst_array = this_rq->active;
2313 head = array->queue + idx;
2316 tmp = list_entry(curr, task_t, run_list);
2320 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
2328 * Right now, this is the only place pull_task() is called,
2329 * so we can safely collect pull_task() stats here rather than
2330 * inside pull_task().
2332 schedstat_inc(this_rq, pt_gained[idle]);
2333 schedstat_inc(busiest, pt_lost[idle]);
2335 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
2338 /* We only want to steal up to the prescribed number of tasks. */
2339 if (pulled < max_nr_move) {
2350 * find_busiest_group finds and returns the busiest CPU group within the
2351 * domain. It calculates and returns the number of tasks which should be
2352 * moved to restore balance via the imbalance parameter.
2354 static struct sched_group *
2355 find_busiest_group(struct sched_domain *sd, int this_cpu,
2356 unsigned long *imbalance, enum idle_type idle)
2358 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2359 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2361 max_load = this_load = total_load = total_pwr = 0;
2368 local_group = cpu_isset(this_cpu, group->cpumask);
2370 /* Tally up the load of all CPUs in the group */
2373 for_each_cpu_mask(i, group->cpumask) {
2374 /* Bias balancing toward cpus of our domain */
2376 load = target_load(i);
2378 load = source_load(i);
2387 total_load += avg_load;
2388 total_pwr += group->cpu_power;
2390 /* Adjust by relative CPU power of the group */
2391 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
2394 this_load = avg_load;
2397 } else if (avg_load > max_load) {
2398 max_load = avg_load;
2402 group = group->next;
2403 } while (group != sd->groups);
2405 if (!busiest || this_load >= max_load)
2408 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2410 if (this_load >= avg_load ||
2411 100*max_load <= sd->imbalance_pct*this_load)
2415 * We're trying to get all the cpus to the average_load, so we don't
2416 * want to push ourselves above the average load, nor do we wish to
2417 * reduce the max loaded cpu below the average load, as either of these
2418 * actions would just result in more rebalancing later, and ping-pong
2419 * tasks around. Thus we look for the minimum possible imbalance.
2420 * Negative imbalances (*we* are more loaded than anyone else) will
2421 * be counted as no imbalance for these purposes -- we can't fix that
2422 * by pulling tasks to us. Be careful of negative numbers as they'll
2423 * appear as very large values with unsigned longs.
2425 *imbalance = min(max_load - avg_load, avg_load - this_load);
2427 /* How much load to actually move to equalise the imbalance */
2428 *imbalance = (*imbalance * min(busiest->cpu_power, this->cpu_power))
2431 if (*imbalance < SCHED_LOAD_SCALE - 1) {
2432 unsigned long pwr_now = 0, pwr_move = 0;
2435 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
2441 * OK, we don't have enough imbalance to justify moving tasks,
2442 * however we may be able to increase total CPU power used by
2446 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
2447 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
2448 pwr_now /= SCHED_LOAD_SCALE;
2450 /* Amount of load we'd subtract */
2451 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
2453 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
2456 /* Amount of load we'd add */
2457 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
2460 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
2461 pwr_move /= SCHED_LOAD_SCALE;
2463 /* Move if we gain another 8th of a CPU worth of throughput */
2464 if (pwr_move < pwr_now + SCHED_LOAD_SCALE / 8)
2471 /* Get rid of the scaling factor, rounding down as we divide */
2472 *imbalance = (*imbalance + 1) / SCHED_LOAD_SCALE;
2477 if (busiest && (idle == NEWLY_IDLE ||
2478 (idle == SCHED_IDLE && max_load > SCHED_LOAD_SCALE)) ) {
2488 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2490 static runqueue_t *find_busiest_queue(struct sched_group *group)
2492 unsigned long load, max_load = 0;
2493 runqueue_t *busiest = NULL;
2496 for_each_cpu_mask(i, group->cpumask) {
2497 load = source_load(i);
2499 if (load > max_load) {
2501 busiest = cpu_rq(i);
2509 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2510 * tasks if there is an imbalance.
2512 * Called with this_rq unlocked.
2514 static int load_balance(int this_cpu, runqueue_t *this_rq,
2515 struct sched_domain *sd, enum idle_type idle)
2517 struct sched_group *group;
2518 runqueue_t *busiest;
2519 unsigned long imbalance;
2522 spin_lock(&this_rq->lock);
2523 schedstat_inc(sd, lb_cnt[idle]);
2525 group = find_busiest_group(sd, this_cpu, &imbalance, idle);
2527 schedstat_inc(sd, lb_nobusyg[idle]);
2531 busiest = find_busiest_queue(group);
2533 schedstat_inc(sd, lb_nobusyq[idle]);
2538 * This should be "impossible", but since load
2539 * balancing is inherently racy and statistical,
2540 * it could happen in theory.
2542 if (unlikely(busiest == this_rq)) {
2547 schedstat_add(sd, lb_imbalance[idle], imbalance);
2550 if (busiest->nr_running > 1) {
2552 * Attempt to move tasks. If find_busiest_group has found
2553 * an imbalance but busiest->nr_running <= 1, the group is
2554 * still unbalanced. nr_moved simply stays zero, so it is
2555 * correctly treated as an imbalance.
2557 double_lock_balance(this_rq, busiest);
2558 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2559 imbalance, sd, idle);
2560 spin_unlock(&busiest->lock);
2562 spin_unlock(&this_rq->lock);
2565 schedstat_inc(sd, lb_failed[idle]);
2566 sd->nr_balance_failed++;
2568 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2571 spin_lock(&busiest->lock);
2572 if (!busiest->active_balance) {
2573 busiest->active_balance = 1;
2574 busiest->push_cpu = this_cpu;
2577 spin_unlock(&busiest->lock);
2579 wake_up_process(busiest->migration_thread);
2582 * We've kicked active balancing, reset the failure
2585 sd->nr_balance_failed = sd->cache_nice_tries;
2589 * We were unbalanced, but unsuccessful in move_tasks(),
2590 * so bump the balance_interval to lessen the lock contention.
2592 if (sd->balance_interval < sd->max_interval)
2593 sd->balance_interval++;
2595 sd->nr_balance_failed = 0;
2597 /* We were unbalanced, so reset the balancing interval */
2598 sd->balance_interval = sd->min_interval;
2604 spin_unlock(&this_rq->lock);
2606 /* tune up the balancing interval */
2607 if (sd->balance_interval < sd->max_interval)
2608 sd->balance_interval *= 2;
2614 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2615 * tasks if there is an imbalance.
2617 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2618 * this_rq is locked.
2620 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2621 struct sched_domain *sd)
2623 struct sched_group *group;
2624 runqueue_t *busiest = NULL;
2625 unsigned long imbalance;
2628 schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2629 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
2631 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2635 busiest = find_busiest_queue(group);
2636 if (!busiest || busiest == this_rq) {
2637 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2641 /* Attempt to move tasks */
2642 double_lock_balance(this_rq, busiest);
2644 schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2645 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2646 imbalance, sd, NEWLY_IDLE);
2648 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2650 spin_unlock(&busiest->lock);
2655 #endif /* CONFIG_CKRM_CPU_SCHEDULE*/
2659 * idle_balance is called by schedule() if this_cpu is about to become
2660 * idle. Attempts to pull tasks from other CPUs.
2662 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
2664 struct sched_domain *sd;
2666 for_each_domain(this_cpu, sd) {
2667 if (sd->flags & SD_BALANCE_NEWIDLE) {
2668 if (load_balance_newidle(this_cpu, this_rq, sd)) {
2669 /* We've pulled tasks over so stop searching */
2676 #ifdef CONFIG_SCHED_SMT
2677 static int cpu_and_siblings_are_idle(int cpu)
2680 for_each_cpu_mask(sib, cpu_sibling_map[cpu]) {
2689 #define cpu_and_siblings_are_idle(A) idle_cpu(A)
2694 * active_load_balance is run by migration threads. It pushes running tasks
2695 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2696 * running on each physical CPU where possible, and avoids physical /
2697 * logical imbalances.
2699 * Called with busiest_rq locked.
2701 static void active_load_balance(runqueue_t *busiest_rq, int busiest_cpu)
2703 struct sched_domain *sd;
2704 struct sched_group *cpu_group;
2705 cpumask_t visited_cpus;
2707 schedstat_inc(busiest_rq, alb_cnt);
2709 * Search for suitable CPUs to push tasks to in successively higher
2710 * domains with SD_LOAD_BALANCE set.
2712 visited_cpus = CPU_MASK_NONE;
2713 for_each_domain(busiest_cpu, sd) {
2714 if (!(sd->flags & SD_LOAD_BALANCE) || busiest_rq->nr_running <= 1)
2715 break; /* no more domains to search or no more tasks to move */
2717 cpu_group = sd->groups;
2718 do { /* sched_groups should either use list_heads or be merged into the domains structure */
2719 int cpu, target_cpu = -1;
2720 runqueue_t *target_rq;
2722 for_each_cpu_mask(cpu, cpu_group->cpumask) {
2723 if (cpu_isset(cpu, visited_cpus) || cpu == busiest_cpu ||
2724 !cpu_and_siblings_are_idle(cpu)) {
2725 cpu_set(cpu, visited_cpus);
2731 if (target_cpu == -1)
2732 goto next_group; /* failed to find a suitable target cpu in this domain */
2734 target_rq = cpu_rq(target_cpu);
2737 * This condition is "impossible", if it occurs we need to fix it
2738 * Reported by Bjorn Helgaas on a 128-cpu setup.
2740 BUG_ON(busiest_rq == target_rq);
2742 /* move a task from busiest_rq to target_rq */
2743 double_lock_balance(busiest_rq, target_rq);
2744 if (move_tasks(target_rq, target_cpu, busiest_rq, 1, sd, SCHED_IDLE)) {
2745 schedstat_inc(busiest_rq, alb_lost);
2746 schedstat_inc(target_rq, alb_gained);
2748 schedstat_inc(busiest_rq, alb_failed);
2750 spin_unlock(&target_rq->lock);
2752 cpu_group = cpu_group->next;
2753 } while (cpu_group != sd->groups && busiest_rq->nr_running > 1);
2758 * rebalance_tick will get called every timer tick, on every CPU.
2760 * It checks each scheduling domain to see if it is due to be balanced,
2761 * and initiates a balancing operation if so.
2763 * Balancing parameters are set up in arch_init_sched_domains.
2766 /* Don't have all balancing operations going off at once */
2767 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2769 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2770 enum idle_type idle)
2772 unsigned long old_load, this_load;
2773 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2774 struct sched_domain *sd;
2776 /* Update our load */
2777 old_load = this_rq->cpu_load;
2778 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
2780 * Round up the averaging division if load is increasing. This
2781 * prevents us from getting stuck on 9 if the load is 10, for
2784 if (this_load > old_load)
2786 this_rq->cpu_load = (old_load + this_load) / 2;
2788 for_each_domain(this_cpu, sd) {
2789 unsigned long interval;
2791 if (!(sd->flags & SD_LOAD_BALANCE))
2794 interval = sd->balance_interval;
2795 if (idle != SCHED_IDLE)
2796 interval *= sd->busy_factor;
2798 /* scale ms to jiffies */
2799 interval = msecs_to_jiffies(interval);
2800 if (unlikely(!interval))
2803 if (j - sd->last_balance >= interval) {
2804 if (load_balance(this_cpu, this_rq, sd, idle)) {
2805 /* We've pulled tasks over so no longer idle */
2808 sd->last_balance += interval;
2814 * on UP we do not need to balance between CPUs:
2816 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2819 static inline void idle_balance(int cpu, runqueue_t *rq)
2824 static inline int wake_priority_sleeper(runqueue_t *rq)
2827 #ifdef CONFIG_SCHED_SMT
2828 spin_lock(&rq->lock);
2830 * If an SMT sibling task has been put to sleep for priority
2831 * reasons reschedule the idle task to see if it can now run.
2833 if (rq->nr_running) {
2834 resched_task(rq->idle);
2837 spin_unlock(&rq->lock);
2842 DEFINE_PER_CPU(struct kernel_stat, kstat);
2843 EXPORT_PER_CPU_SYMBOL(kstat);
2846 * We place interactive tasks back into the active array, if possible.
2848 * To guarantee that this does not starve expired tasks we ignore the
2849 * interactivity of a task if the first expired task had to wait more
2850 * than a 'reasonable' amount of time. This deadline timeout is
2851 * load-dependent, as the frequency of array switched decreases with
2852 * increasing number of running tasks. We also ignore the interactivity
2853 * if a better static_prio task has expired:
2856 #ifndef CONFIG_CKRM_CPU_SCHEDULE
2857 #define EXPIRED_STARVING(rq) \
2858 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2859 (jiffies - (rq)->expired_timestamp >= \
2860 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2861 ((rq)->curr->static_prio > (rq)->best_expired_prio))
2863 #define EXPIRED_STARVING(rq) \
2864 (STARVATION_LIMIT && ((rq)->expired_timestamp && \
2865 (jiffies - (rq)->expired_timestamp >= \
2866 STARVATION_LIMIT * (lrq_nr_running(rq)) + 1)))
2870 * This function gets called by the timer code, with HZ frequency.
2871 * We call it with interrupts disabled.
2873 * It also gets called by the fork code, when changing the parent's
2876 void scheduler_tick(int user_ticks, int sys_ticks)
2878 int cpu = smp_processor_id();
2879 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2880 runqueue_t *rq = this_rq();
2881 task_t *p = current;
2882 struct vx_info *vxi = p->vx_info;
2884 rq->timestamp_last_tick = sched_clock();
2886 if (rcu_pending(cpu))
2887 rcu_check_callbacks(cpu, user_ticks);
2891 vxi->sched.cpu[cpu].user_ticks += user_ticks;
2892 vxi->sched.cpu[cpu].sys_ticks += sys_ticks;
2895 /* note: this timer irq context must be accounted for as well */
2896 if (hardirq_count() - HARDIRQ_OFFSET) {
2897 cpustat->irq += sys_ticks;
2899 } else if (softirq_count()) {
2900 cpustat->softirq += sys_ticks;
2904 if (p == rq->idle) {
2905 if (atomic_read(&rq->nr_iowait) > 0)
2906 cpustat->iowait += sys_ticks;
2907 // vx_cpustat_acc(vxi, iowait, cpu, cpustat, sys_ticks);
2909 cpustat->idle += sys_ticks;
2910 // vx_cpustat_acc(vxi, idle, cpu, cpustat, sys_ticks);
2912 if (wake_priority_sleeper(rq))
2914 ckrm_sched_tick(jiffies,cpu,rq_ckrm_load(rq));
2916 #ifdef CONFIG_VSERVER_HARDCPU_IDLE
2917 if (!--rq->idle_tokens && !list_empty(&rq->hold_queue))
2920 rebalance_tick(cpu, rq, SCHED_IDLE);
2923 if (TASK_NICE(p) > 0)
2924 cpustat->nice += user_ticks;
2926 cpustat->user += user_ticks;
2927 cpustat->system += sys_ticks;
2929 /* Task might have expired already, but not scheduled off yet */
2930 if (p->array != rq_active(p,rq)) {
2931 set_tsk_need_resched(p);
2934 spin_lock(&rq->lock);
2936 * The task was running during this tick - update the
2937 * time slice counter. Note: we do not update a thread's
2938 * priority until it either goes to sleep or uses up its
2939 * timeslice. This makes it possible for interactive tasks
2940 * to use up their timeslices at their highest priority levels.
2944 * RR tasks need a special form of timeslice management.
2945 * FIFO tasks have no timeslices.
2947 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2948 p->time_slice = task_timeslice(p);
2949 p->first_time_slice = 0;
2950 set_tsk_need_resched(p);
2952 /* put it at the end of the queue: */
2953 dequeue_task(p, rq_active(p,rq));
2954 enqueue_task(p, rq_active(p,rq));
2958 if (vx_need_resched(p)) {
2959 #ifdef CONFIG_CKRM_CPU_SCHEDULE
2960 /* Hubertus ... we can abstract this out */
2961 ckrm_lrq_t* rq = get_task_lrq(p);
2963 dequeue_task(p, rq->active);
2964 set_tsk_need_resched(p);
2965 p->prio = effective_prio(p);
2966 p->time_slice = task_timeslice(p);
2967 p->first_time_slice = 0;
2969 if (!rq->expired_timestamp)
2970 rq->expired_timestamp = jiffies;
2971 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2972 enqueue_task(p, rq->expired);
2973 if (p->static_prio < this_rq()->best_expired_prio)
2974 this_rq()->best_expired_prio = p->static_prio;
2976 enqueue_task(p, rq->active);
2979 * Prevent a too long timeslice allowing a task to monopolize
2980 * the CPU. We do this by splitting up the timeslice into
2983 * Note: this does not mean the task's timeslices expire or
2984 * get lost in any way, they just might be preempted by
2985 * another task of equal priority. (one with higher
2986 * priority would have preempted this task already.) We
2987 * requeue this task to the end of the list on this priority
2988 * level, which is in essence a round-robin of tasks with
2991 * This only applies to tasks in the interactive
2992 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2994 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2995 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2996 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2997 (p->array == rq_active(p,rq))) {
2999 dequeue_task(p, rq_active(p,rq));
3000 set_tsk_need_resched(p);
3001 p->prio = effective_prio(p);
3002 enqueue_task(p, rq_active(p,rq));
3006 spin_unlock(&rq->lock);
3008 ckrm_sched_tick(jiffies,cpu,rq_ckrm_load(rq));
3009 rebalance_tick(cpu, rq, NOT_IDLE);
3012 #ifdef CONFIG_SCHED_SMT
3013 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
3015 struct sched_domain *sd = this_rq->sd;
3016 cpumask_t sibling_map;
3019 if (!(sd->flags & SD_SHARE_CPUPOWER))
3022 #ifdef CONFIG_CKRM_CPU_SCHEDULE
3023 if (prev != rq->idle) {
3024 unsigned long long run = now - prev->timestamp;
3025 ckrm_lrq_t * lrq = get_task_lrq(prev);
3027 lrq->lrq_load -= task_load(prev);
3028 cpu_demand_event(&prev->demand_stat,CPU_DEMAND_DESCHEDULE,run);
3029 lrq->lrq_load += task_load(prev);
3031 cpu_demand_event(get_task_lrq_stat(prev),CPU_DEMAND_DESCHEDULE,run);
3032 update_local_cvt(prev, run);
3036 * Unlock the current runqueue because we have to lock in
3037 * CPU order to avoid deadlocks. Caller knows that we might
3038 * unlock. We keep IRQs disabled.
3040 spin_unlock(&this_rq->lock);
3042 sibling_map = sd->span;
3044 for_each_cpu_mask(i, sibling_map)
3045 spin_lock(&cpu_rq(i)->lock);
3047 * We clear this CPU from the mask. This both simplifies the
3048 * inner loop and keps this_rq locked when we exit:
3050 cpu_clear(this_cpu, sibling_map);
3052 for_each_cpu_mask(i, sibling_map) {
3053 runqueue_t *smt_rq = cpu_rq(i);
3056 * If an SMT sibling task is sleeping due to priority
3057 * reasons wake it up now.
3059 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
3060 resched_task(smt_rq->idle);
3063 for_each_cpu_mask(i, sibling_map)
3064 spin_unlock(&cpu_rq(i)->lock);
3066 * We exit with this_cpu's rq still held and IRQs
3071 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
3073 struct sched_domain *sd = this_rq->sd;
3074 cpumask_t sibling_map;
3075 prio_array_t *array;
3079 if (!(sd->flags & SD_SHARE_CPUPOWER))
3083 * The same locking rules and details apply as for
3084 * wake_sleeping_dependent():
3086 spin_unlock(&this_rq->lock);
3087 sibling_map = sd->span;
3088 for_each_cpu_mask(i, sibling_map)
3089 spin_lock(&cpu_rq(i)->lock);
3090 cpu_clear(this_cpu, sibling_map);
3093 * Establish next task to be run - it might have gone away because
3094 * we released the runqueue lock above:
3096 if (!this_rq->nr_running)
3098 array = this_rq->active;
3099 if (!array->nr_active)
3100 array = this_rq->expired;
3101 BUG_ON(!array->nr_active);
3103 p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
3106 for_each_cpu_mask(i, sibling_map) {
3107 runqueue_t *smt_rq = cpu_rq(i);
3108 task_t *smt_curr = smt_rq->curr;
3111 * If a user task with lower static priority than the
3112 * running task on the SMT sibling is trying to schedule,
3113 * delay it till there is proportionately less timeslice
3114 * left of the sibling task to prevent a lower priority
3115 * task from using an unfair proportion of the
3116 * physical cpu's resources. -ck
3118 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
3119 task_timeslice(p) || rt_task(smt_curr)) &&
3120 p->mm && smt_curr->mm && !rt_task(p))
3124 * Reschedule a lower priority task on the SMT sibling,
3125 * or wake it up if it has been put to sleep for priority
3128 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
3129 task_timeslice(smt_curr) || rt_task(p)) &&
3130 smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
3131 (smt_curr == smt_rq->idle && smt_rq->nr_running))
3132 resched_task(smt_curr);
3135 for_each_cpu_mask(i, sibling_map)
3136 spin_unlock(&cpu_rq(i)->lock);
3140 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
3144 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
3151 * schedule() is the main scheduler function.
3153 asmlinkage void __sched schedule(void)
3156 task_t *prev, *next;
3158 prio_array_t *array;
3159 unsigned long long now;
3160 unsigned long run_time;
3162 #ifdef CONFIG_VSERVER_HARDCPU
3163 struct vx_info *vxi;
3168 * If crash dump is in progress, this other cpu's
3169 * need to wait until it completes.
3170 * NB: this code is optimized away for kernels without
3173 if (unlikely(dump_oncpu))
3174 goto dump_scheduling_disabled;
3178 * Test if we are atomic. Since do_exit() needs to call into
3179 * schedule() atomically, we ignore that path for now.
3180 * Otherwise, whine if we are scheduling when we should not be.
3182 if (likely(!(current->exit_state & (EXIT_DEAD | EXIT_ZOMBIE)))) {
3183 if (unlikely(in_atomic())) {
3184 printk(KERN_ERR "scheduling while atomic: "
3186 current->comm, preempt_count(), current->pid);
3190 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3195 release_kernel_lock(prev);
3196 need_resched_nonpreemptible:
3200 * The idle thread is not allowed to schedule!
3201 * Remove this check after it has been exercised a bit.
3203 if (unlikely(current == rq->idle) && current->state != TASK_RUNNING) {
3204 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
3208 schedstat_inc(rq, sched_cnt);
3209 now = sched_clock();
3210 if (likely(now - prev->timestamp < NS_MAX_SLEEP_AVG))
3211 run_time = now - prev->timestamp;
3213 run_time = NS_MAX_SLEEP_AVG;
3216 * Tasks with interactive credits get charged less run_time
3217 * at high sleep_avg to delay them losing their interactive
3220 if (HIGH_CREDIT(prev))
3221 run_time /= (CURRENT_BONUS(prev) ? : 1);
3223 spin_lock_irq(&rq->lock);
3225 #ifdef CONFIG_CKRM_CPU_SCHEDULE
3226 if (prev != rq->idle) {
3227 unsigned long long run = now - prev->timestamp;
3228 ckrm_lrq_t * lrq = get_task_lrq(prev);
3230 lrq->lrq_load -= task_load(prev);
3231 cpu_demand_event(&prev->demand_stat,CPU_DEMAND_DESCHEDULE,run);
3232 lrq->lrq_load += task_load(prev);
3234 cpu_demand_event(get_task_lrq_stat(prev),CPU_DEMAND_DESCHEDULE,run);
3235 update_local_cvt(prev, run);
3239 if (unlikely(current->flags & PF_DEAD))
3240 current->state = EXIT_DEAD;
3242 * if entering off of a kernel preemption go straight
3243 * to picking the next task.
3245 switch_count = &prev->nivcsw;
3246 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3247 switch_count = &prev->nvcsw;
3248 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
3249 unlikely(signal_pending(prev))))
3250 prev->state = TASK_RUNNING;
3252 if (prev->state == TASK_UNINTERRUPTIBLE)
3253 rq->nr_uninterruptible++;
3254 deactivate_task(prev, rq);
3258 #ifdef CONFIG_VSERVER_HARDCPU
3259 if (!list_empty(&rq->hold_queue)) {
3260 struct list_head *l, *n;
3264 list_for_each_safe(l, n, &rq->hold_queue) {
3265 next = list_entry(l, task_t, run_list);
3266 if (vxi == next->vx_info)
3269 vxi = next->vx_info;
3270 ret = vx_tokens_recalc(vxi);
3271 // tokens = vx_tokens_avail(next);
3274 list_del(&next->run_list);
3275 next->state &= ~TASK_ONHOLD;
3278 array = rq->expired;
3279 next->prio = MAX_PRIO-1;
3280 enqueue_task(next, array);
3282 if (next->static_prio < rq->best_expired_prio)
3283 rq->best_expired_prio = next->static_prio;
3285 // printk("··· %8lu unhold %p [%d]\n", jiffies, next, next->prio);
3288 if ((ret < 0) && (maxidle < ret))
3292 rq->idle_tokens = -maxidle;
3297 cpu = smp_processor_id();
3298 if (unlikely(!rq->nr_running)) {
3300 idle_balance(cpu, rq);
3301 if (!rq->nr_running) {
3303 rq->expired_timestamp = 0;
3304 wake_sleeping_dependent(cpu, rq);
3306 * wake_sleeping_dependent() might have released
3307 * the runqueue, so break out if we got new
3310 if (!rq->nr_running)
3314 if (dependent_sleeper(cpu, rq)) {
3319 * dependent_sleeper() releases and reacquires the runqueue
3320 * lock, hence go into the idle loop if the rq went
3323 if (unlikely(!rq->nr_running))
3327 /* MEF: CKRM refactored code into rq_get_next_task(); make
3328 * sure that when upgrading changes are reflected into both
3329 * versions of the code.
3331 next = rq_get_next_task(rq);
3333 #ifdef CONFIG_VSERVER_HARDCPU
3334 vxi = next->vx_info;
3335 if (vx_info_flags(vxi, VXF_SCHED_PAUSE|VXF_SCHED_HARD, 0)) {
3336 int ret = vx_tokens_recalc(vxi);
3338 if (unlikely(ret <= 0)) {
3339 if (ret && (rq->idle_tokens > -ret))
3340 rq->idle_tokens = -ret;
3341 __deactivate_task(next, rq);
3342 recalc_task_prio(next, now);
3343 // a new one on hold
3345 next->state |= TASK_ONHOLD;
3346 list_add_tail(&next->run_list, &rq->hold_queue);
3347 //printk("··· %8lu hold %p [%d]\n", jiffies, next, next->prio);
3353 if (!rt_task(next) && next->activated > 0) {
3354 unsigned long long delta = now - next->timestamp;
3356 if (next->activated == 1)
3357 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
3359 array = next->array;
3360 dequeue_task(next, array);
3361 recalc_task_prio(next, next->timestamp + delta);
3362 enqueue_task(next, array);
3364 next->activated = 0;
3366 if (next == rq->idle)
3367 schedstat_inc(rq, sched_goidle);
3369 clear_tsk_need_resched(prev);
3370 rcu_qsctr_inc(task_cpu(prev));
3372 prev->sleep_avg -= run_time;
3373 if ((long)prev->sleep_avg <= 0) {
3374 prev->sleep_avg = 0;
3375 if (!(HIGH_CREDIT(prev) || LOW_CREDIT(prev)))
3376 prev->interactive_credit--;
3378 prev->timestamp = prev->last_ran = now;
3380 sched_info_switch(prev, next);
3381 if (likely(prev != next)) {
3382 next->timestamp = now;
3387 prepare_arch_switch(rq, next);
3388 prev = context_switch(rq, prev, next);
3391 finish_task_switch(prev);
3393 spin_unlock_irq(&rq->lock);
3396 if (unlikely(reacquire_kernel_lock(prev) < 0))
3397 goto need_resched_nonpreemptible;
3398 preempt_enable_no_resched();
3399 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3404 dump_scheduling_disabled:
3405 /* allow scheduling only if this is the dumping cpu */
3406 if (dump_oncpu != smp_processor_id()+1) {
3413 EXPORT_SYMBOL(schedule);
3414 #ifdef CONFIG_PREEMPT
3416 * this is is the entry point to schedule() from in-kernel preemption
3417 * off of preempt_enable. Kernel preemptions off return from interrupt
3418 * occur there and call schedule directly.
3420 asmlinkage void __sched preempt_schedule(void)
3422 struct thread_info *ti = current_thread_info();
3425 * If there is a non-zero preempt_count or interrupts are disabled,
3426 * we do not want to preempt the current task. Just return..
3428 if (unlikely(ti->preempt_count || irqs_disabled()))
3432 ti->preempt_count = PREEMPT_ACTIVE;
3434 ti->preempt_count = 0;
3436 /* we could miss a preemption opportunity between schedule and now */
3438 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3442 EXPORT_SYMBOL(preempt_schedule);
3443 #endif /* CONFIG_PREEMPT */
3445 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
3447 task_t *p = curr->task;
3448 return try_to_wake_up(p, mode, sync);
3451 EXPORT_SYMBOL(default_wake_function);
3454 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3455 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3456 * number) then we wake all the non-exclusive tasks and one exclusive task.
3458 * There are circumstances in which we can try to wake a task which has already
3459 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3460 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3462 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3463 int nr_exclusive, int sync, void *key)
3465 struct list_head *tmp, *next;
3467 list_for_each_safe(tmp, next, &q->task_list) {
3470 curr = list_entry(tmp, wait_queue_t, task_list);
3471 flags = curr->flags;
3472 if (curr->func(curr, mode, sync, key) &&
3473 (flags & WQ_FLAG_EXCLUSIVE) &&
3480 * __wake_up - wake up threads blocked on a waitqueue.
3482 * @mode: which threads
3483 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3485 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3486 int nr_exclusive, void *key)
3488 unsigned long flags;
3490 spin_lock_irqsave(&q->lock, flags);
3491 __wake_up_common(q, mode, nr_exclusive, 0, key);
3492 spin_unlock_irqrestore(&q->lock, flags);
3495 EXPORT_SYMBOL(__wake_up);
3498 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3500 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3502 __wake_up_common(q, mode, 1, 0, NULL);
3506 * __wake_up - sync- wake up threads blocked on a waitqueue.
3508 * @mode: which threads
3509 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3511 * The sync wakeup differs that the waker knows that it will schedule
3512 * away soon, so while the target thread will be woken up, it will not
3513 * be migrated to another CPU - ie. the two threads are 'synchronized'
3514 * with each other. This can prevent needless bouncing between CPUs.
3516 * On UP it can prevent extra preemption.
3518 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3520 unsigned long flags;
3526 if (unlikely(!nr_exclusive))
3529 spin_lock_irqsave(&q->lock, flags);
3530 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3531 spin_unlock_irqrestore(&q->lock, flags);
3533 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3535 void fastcall complete(struct completion *x)
3537 unsigned long flags;
3539 spin_lock_irqsave(&x->wait.lock, flags);
3541 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3543 spin_unlock_irqrestore(&x->wait.lock, flags);
3545 EXPORT_SYMBOL(complete);
3547 void fastcall complete_all(struct completion *x)
3549 unsigned long flags;
3551 spin_lock_irqsave(&x->wait.lock, flags);
3552 x->done += UINT_MAX/2;
3553 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3555 spin_unlock_irqrestore(&x->wait.lock, flags);
3557 EXPORT_SYMBOL(complete_all);
3559 void fastcall __sched wait_for_completion(struct completion *x)
3562 spin_lock_irq(&x->wait.lock);
3564 DECLARE_WAITQUEUE(wait, current);
3566 wait.flags |= WQ_FLAG_EXCLUSIVE;
3567 __add_wait_queue_tail(&x->wait, &wait);
3569 __set_current_state(TASK_UNINTERRUPTIBLE);
3570 spin_unlock_irq(&x->wait.lock);
3572 spin_lock_irq(&x->wait.lock);
3574 __remove_wait_queue(&x->wait, &wait);
3577 spin_unlock_irq(&x->wait.lock);
3579 EXPORT_SYMBOL(wait_for_completion);
3581 #define SLEEP_ON_VAR \
3582 unsigned long flags; \
3583 wait_queue_t wait; \
3584 init_waitqueue_entry(&wait, current);
3586 #define SLEEP_ON_HEAD \
3587 spin_lock_irqsave(&q->lock,flags); \
3588 __add_wait_queue(q, &wait); \
3589 spin_unlock(&q->lock);
3591 #define SLEEP_ON_TAIL \
3592 spin_lock_irq(&q->lock); \
3593 __remove_wait_queue(q, &wait); \
3594 spin_unlock_irqrestore(&q->lock, flags);
3596 #define SLEEP_ON_BKLCHECK \
3597 if (unlikely(!kernel_locked()) && \
3598 sleep_on_bkl_warnings < 10) { \
3599 sleep_on_bkl_warnings++; \
3603 static int sleep_on_bkl_warnings;
3605 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3611 current->state = TASK_INTERRUPTIBLE;
3618 EXPORT_SYMBOL(interruptible_sleep_on);
3620 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3626 current->state = TASK_INTERRUPTIBLE;
3629 timeout = schedule_timeout(timeout);
3635 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3637 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3643 current->state = TASK_UNINTERRUPTIBLE;
3646 timeout = schedule_timeout(timeout);
3652 EXPORT_SYMBOL(sleep_on_timeout);
3654 void set_user_nice(task_t *p, long nice)
3656 unsigned long flags;
3657 prio_array_t *array;
3659 int old_prio, new_prio, delta;
3661 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3664 * We have to be careful, if called from sys_setpriority(),
3665 * the task might be in the middle of scheduling on another CPU.
3667 rq = task_rq_lock(p, &flags);
3669 * The RT priorities are set via setscheduler(), but we still
3670 * allow the 'normal' nice value to be set - but as expected
3671 * it wont have any effect on scheduling until the task is
3675 p->static_prio = NICE_TO_PRIO(nice);
3680 dequeue_task(p, array);
3683 new_prio = NICE_TO_PRIO(nice);
3684 delta = new_prio - old_prio;
3685 p->static_prio = NICE_TO_PRIO(nice);
3689 enqueue_task(p, array);
3691 * If the task increased its priority or is running and
3692 * lowered its priority, then reschedule its CPU:
3694 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3695 resched_task(rq->curr);
3698 task_rq_unlock(rq, &flags);
3701 EXPORT_SYMBOL(set_user_nice);
3703 #ifdef __ARCH_WANT_SYS_NICE
3706 * sys_nice - change the priority of the current process.
3707 * @increment: priority increment
3709 * sys_setpriority is a more generic, but much slower function that
3710 * does similar things.
3712 asmlinkage long sys_nice(int increment)
3718 * Setpriority might change our priority at the same moment.
3719 * We don't have to worry. Conceptually one call occurs first
3720 * and we have a single winner.
3722 if (increment < 0) {
3723 if (vx_flags(VXF_IGNEG_NICE, 0))
3725 if (!capable(CAP_SYS_NICE))
3727 if (increment < -40)
3733 nice = PRIO_TO_NICE(current->static_prio) + increment;
3739 retval = security_task_setnice(current, nice);
3743 set_user_nice(current, nice);
3750 * task_prio - return the priority value of a given task.
3751 * @p: the task in question.
3753 * This is the priority value as seen by users in /proc.
3754 * RT tasks are offset by -200. Normal tasks are centered
3755 * around 0, value goes from -16 to +15.
3757 int task_prio(const task_t *p)
3759 return p->prio - MAX_RT_PRIO;
3763 * task_nice - return the nice value of a given task.
3764 * @p: the task in question.
3766 int task_nice(const task_t *p)
3768 return TASK_NICE(p);
3772 * idle_cpu - is a given cpu idle currently?
3773 * @cpu: the processor in question.
3775 int idle_cpu(int cpu)
3777 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3780 EXPORT_SYMBOL_GPL(idle_cpu);
3783 * find_process_by_pid - find a process with a matching PID value.
3784 * @pid: the pid in question.
3786 static inline task_t *find_process_by_pid(pid_t pid)
3788 return pid ? find_task_by_pid(pid) : current;
3791 /* Actually do priority change: must hold rq lock. */
3792 static void __setscheduler(struct task_struct *p, int policy, int prio)
3796 p->rt_priority = prio;
3797 if (policy != SCHED_NORMAL)
3798 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
3800 p->prio = p->static_prio;
3804 * setscheduler - change the scheduling policy and/or RT priority of a thread.
3806 static int setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3808 struct sched_param lp;
3809 int retval = -EINVAL;
3810 int oldprio, oldpolicy = -1;
3811 prio_array_t *array;
3812 unsigned long flags;
3816 if (!param || pid < 0)
3820 if (copy_from_user(&lp, param, sizeof(struct sched_param)))
3824 * We play safe to avoid deadlocks.
3826 read_lock_irq(&tasklist_lock);
3828 p = find_process_by_pid(pid);
3834 /* double check policy once rq lock held */
3836 policy = oldpolicy = p->policy;
3839 if (policy != SCHED_FIFO && policy != SCHED_RR &&
3840 policy != SCHED_NORMAL)
3844 * Valid priorities for SCHED_FIFO and SCHED_RR are
3845 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
3848 if (lp.sched_priority < 0 || lp.sched_priority > MAX_USER_RT_PRIO-1)
3850 if ((policy == SCHED_NORMAL) != (lp.sched_priority == 0))
3854 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
3855 !capable(CAP_SYS_NICE))
3857 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3858 !capable(CAP_SYS_NICE))
3861 retval = security_task_setscheduler(p, policy, &lp);
3865 * To be able to change p->policy safely, the apropriate
3866 * runqueue lock must be held.
3868 rq = task_rq_lock(p, &flags);
3869 /* recheck policy now with rq lock held */
3870 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3871 policy = oldpolicy = -1;
3872 task_rq_unlock(rq, &flags);
3877 deactivate_task(p, task_rq(p));
3880 __setscheduler(p, policy, lp.sched_priority);
3882 vx_activate_task(p);
3883 __activate_task(p, task_rq(p));
3885 * Reschedule if we are currently running on this runqueue and
3886 * our priority decreased, or if we are not currently running on
3887 * this runqueue and our priority is higher than the current's
3889 if (task_running(rq, p)) {
3890 if (p->prio > oldprio)
3891 resched_task(rq->curr);
3892 } else if (TASK_PREEMPTS_CURR(p, rq))
3893 resched_task(rq->curr);
3895 task_rq_unlock(rq, &flags);
3897 read_unlock_irq(&tasklist_lock);
3903 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3904 * @pid: the pid in question.
3905 * @policy: new policy
3906 * @param: structure containing the new RT priority.
3908 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3909 struct sched_param __user *param)
3911 return setscheduler(pid, policy, param);
3915 * sys_sched_setparam - set/change the RT priority of a thread
3916 * @pid: the pid in question.
3917 * @param: structure containing the new RT priority.
3919 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3921 return setscheduler(pid, -1, param);
3925 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3926 * @pid: the pid in question.
3928 asmlinkage long sys_sched_getscheduler(pid_t pid)
3930 int retval = -EINVAL;
3937 read_lock(&tasklist_lock);
3938 p = find_process_by_pid(pid);
3940 retval = security_task_getscheduler(p);
3944 read_unlock(&tasklist_lock);
3951 * sys_sched_getscheduler - get the RT priority of a thread
3952 * @pid: the pid in question.
3953 * @param: structure containing the RT priority.
3955 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3957 struct sched_param lp;
3958 int retval = -EINVAL;
3961 if (!param || pid < 0)
3964 read_lock(&tasklist_lock);
3965 p = find_process_by_pid(pid);
3970 retval = security_task_getscheduler(p);
3974 lp.sched_priority = p->rt_priority;
3975 read_unlock(&tasklist_lock);
3978 * This one might sleep, we cannot do it with a spinlock held ...
3980 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3986 read_unlock(&tasklist_lock);
3990 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
3996 read_lock(&tasklist_lock);
3998 p = find_process_by_pid(pid);
4000 read_unlock(&tasklist_lock);
4001 unlock_cpu_hotplug();
4006 * It is not safe to call set_cpus_allowed with the
4007 * tasklist_lock held. We will bump the task_struct's
4008 * usage count and then drop tasklist_lock.
4011 read_unlock(&tasklist_lock);
4014 if ((current->euid != p->euid) && (current->euid != p->uid) &&
4015 !capable(CAP_SYS_NICE))
4018 retval = set_cpus_allowed(p, new_mask);
4022 unlock_cpu_hotplug();
4026 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4027 cpumask_t *new_mask)
4029 if (len < sizeof(cpumask_t)) {
4030 memset(new_mask, 0, sizeof(cpumask_t));
4031 } else if (len > sizeof(cpumask_t)) {
4032 len = sizeof(cpumask_t);
4034 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4038 * sys_sched_setaffinity - set the cpu affinity of a process
4039 * @pid: pid of the process
4040 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4041 * @user_mask_ptr: user-space pointer to the new cpu mask
4043 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
4044 unsigned long __user *user_mask_ptr)
4049 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
4053 return sched_setaffinity(pid, new_mask);
4057 * Represents all cpu's present in the system
4058 * In systems capable of hotplug, this map could dynamically grow
4059 * as new cpu's are detected in the system via any platform specific
4060 * method, such as ACPI for e.g.
4063 cpumask_t cpu_present_map;
4064 EXPORT_SYMBOL(cpu_present_map);
4067 cpumask_t cpu_online_map = CPU_MASK_ALL;
4068 cpumask_t cpu_possible_map = CPU_MASK_ALL;
4071 long sched_getaffinity(pid_t pid, cpumask_t *mask)
4077 read_lock(&tasklist_lock);
4080 p = find_process_by_pid(pid);
4085 cpus_and(*mask, p->cpus_allowed, cpu_possible_map);
4088 read_unlock(&tasklist_lock);
4089 unlock_cpu_hotplug();
4097 * sys_sched_getaffinity - get the cpu affinity of a process
4098 * @pid: pid of the process
4099 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4100 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4102 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
4103 unsigned long __user *user_mask_ptr)
4108 if (len < sizeof(cpumask_t))
4111 ret = sched_getaffinity(pid, &mask);
4115 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
4118 return sizeof(cpumask_t);
4122 * sys_sched_yield - yield the current processor to other threads.
4124 * this function yields the current CPU by moving the calling thread
4125 * to the expired array. If there are no other threads running on this
4126 * CPU then this function will return.
4128 asmlinkage long sys_sched_yield(void)
4130 runqueue_t *rq = this_rq_lock();
4131 prio_array_t *array = current->array;
4132 prio_array_t *target = rq_expired(current,rq);
4134 schedstat_inc(rq, yld_cnt);
4136 * We implement yielding by moving the task into the expired
4139 * (special rule: RT tasks will just roundrobin in the active
4142 if (rt_task(current))
4143 target = rq_active(current,rq);
4145 #warning MEF need to fix up SCHEDSTATS code, but I hope this is fixed by the 2.6.10 CKRM patch
4146 #ifdef CONFIG_SCHEDSTATS
4147 if (current->array->nr_active == 1) {
4148 schedstat_inc(rq, yld_act_empty);
4149 if (!rq->expired->nr_active)
4150 schedstat_inc(rq, yld_both_empty);
4151 } else if (!rq->expired->nr_active)
4152 schedstat_inc(rq, yld_exp_empty);
4155 dequeue_task(current, array);
4156 enqueue_task(current, target);
4159 * Since we are going to call schedule() anyway, there's
4160 * no need to preempt or enable interrupts:
4162 __release(rq->lock);
4163 _raw_spin_unlock(&rq->lock);
4164 preempt_enable_no_resched();
4171 void __sched __cond_resched(void)
4173 set_current_state(TASK_RUNNING);
4177 EXPORT_SYMBOL(__cond_resched);
4180 * yield - yield the current processor to other threads.
4182 * this is a shortcut for kernel-space yielding - it marks the
4183 * thread runnable and calls sys_sched_yield().
4185 void __sched yield(void)
4187 set_current_state(TASK_RUNNING);
4191 EXPORT_SYMBOL(yield);
4194 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4195 * that process accounting knows that this is a task in IO wait state.
4197 * But don't do that if it is a deliberate, throttling IO wait (this task
4198 * has set its backing_dev_info: the queue against which it should throttle)
4200 void __sched io_schedule(void)
4202 struct runqueue *rq = this_rq();
4204 atomic_inc(&rq->nr_iowait);
4206 atomic_dec(&rq->nr_iowait);
4209 EXPORT_SYMBOL(io_schedule);
4211 long __sched io_schedule_timeout(long timeout)
4213 struct runqueue *rq = this_rq();
4216 atomic_inc(&rq->nr_iowait);
4217 ret = schedule_timeout(timeout);
4218 atomic_dec(&rq->nr_iowait);
4223 * sys_sched_get_priority_max - return maximum RT priority.
4224 * @policy: scheduling class.
4226 * this syscall returns the maximum rt_priority that can be used
4227 * by a given scheduling class.
4229 asmlinkage long sys_sched_get_priority_max(int policy)
4236 ret = MAX_USER_RT_PRIO-1;
4246 * sys_sched_get_priority_min - return minimum RT priority.
4247 * @policy: scheduling class.
4249 * this syscall returns the minimum rt_priority that can be used
4250 * by a given scheduling class.
4252 asmlinkage long sys_sched_get_priority_min(int policy)
4268 * sys_sched_rr_get_interval - return the default timeslice of a process.
4269 * @pid: pid of the process.
4270 * @interval: userspace pointer to the timeslice value.
4272 * this syscall writes the default timeslice value of a given process
4273 * into the user-space timespec buffer. A value of '0' means infinity.
4276 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4278 int retval = -EINVAL;
4286 read_lock(&tasklist_lock);
4287 p = find_process_by_pid(pid);
4291 retval = security_task_getscheduler(p);
4295 jiffies_to_timespec(p->policy & SCHED_FIFO ?
4296 0 : task_timeslice(p), &t);
4297 read_unlock(&tasklist_lock);
4298 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4302 read_unlock(&tasklist_lock);
4306 static inline struct task_struct *eldest_child(struct task_struct *p)
4308 if (list_empty(&p->children)) return NULL;
4309 return list_entry(p->children.next,struct task_struct,sibling);
4312 static inline struct task_struct *older_sibling(struct task_struct *p)
4314 if (p->sibling.prev==&p->parent->children) return NULL;
4315 return list_entry(p->sibling.prev,struct task_struct,sibling);
4318 static inline struct task_struct *younger_sibling(struct task_struct *p)
4320 if (p->sibling.next==&p->parent->children) return NULL;
4321 return list_entry(p->sibling.next,struct task_struct,sibling);
4324 static void show_task(task_t * p)
4328 unsigned long free = 0;
4329 static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
4331 printk("%-13.13s ", p->comm);
4332 state = p->state ? __ffs(p->state) + 1 : 0;
4333 if (state < ARRAY_SIZE(stat_nam))
4334 printk(stat_nam[state]);
4337 #if (BITS_PER_LONG == 32)
4338 if (state == TASK_RUNNING)
4339 printk(" running ");
4341 printk(" %08lX ", thread_saved_pc(p));
4343 if (state == TASK_RUNNING)
4344 printk(" running task ");
4346 printk(" %016lx ", thread_saved_pc(p));
4348 #ifdef CONFIG_DEBUG_STACK_USAGE
4350 unsigned long * n = (unsigned long *) (p->thread_info+1);
4353 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
4356 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
4357 if ((relative = eldest_child(p)))
4358 printk("%5d ", relative->pid);
4361 if ((relative = younger_sibling(p)))
4362 printk("%7d", relative->pid);
4365 if ((relative = older_sibling(p)))
4366 printk(" %5d", relative->pid);
4370 printk(" (L-TLB)\n");
4372 printk(" (NOTLB)\n");
4374 if (state != TASK_RUNNING)
4375 show_stack(p, NULL);
4378 void show_state(void)
4382 #if (BITS_PER_LONG == 32)
4385 printk(" task PC pid father child younger older\n");
4389 printk(" task PC pid father child younger older\n");
4391 read_lock(&tasklist_lock);
4392 do_each_thread(g, p) {
4394 * reset the NMI-timeout, listing all files on a slow
4395 * console might take alot of time:
4397 touch_nmi_watchdog();
4399 } while_each_thread(g, p);
4401 read_unlock(&tasklist_lock);
4404 EXPORT_SYMBOL_GPL(show_state);
4406 void __devinit init_idle(task_t *idle, int cpu)
4408 runqueue_t *rq = cpu_rq(cpu);
4409 unsigned long flags;
4411 idle->sleep_avg = 0;
4412 idle->interactive_credit = 0;
4414 idle->prio = MAX_PRIO;
4415 idle->state = TASK_RUNNING;
4416 set_task_cpu(idle, cpu);
4418 #ifdef CONFIG_CKRM_CPU_SCHEDULE
4419 cpu_demand_event(&(idle->demand_stat),CPU_DEMAND_INIT,0);
4420 idle->cpu_class = get_default_cpu_class();
4424 spin_lock_irqsave(&rq->lock, flags);
4425 rq->curr = rq->idle = idle;
4426 set_tsk_need_resched(idle);
4427 spin_unlock_irqrestore(&rq->lock, flags);
4429 /* Set the preempt count _outside_ the spinlocks! */
4430 #ifdef CONFIG_PREEMPT
4431 idle->thread_info->preempt_count = (idle->lock_depth >= 0);
4433 idle->thread_info->preempt_count = 0;
4438 * In a system that switches off the HZ timer nohz_cpu_mask
4439 * indicates which cpus entered this state. This is used
4440 * in the rcu update to wait only for active cpus. For system
4441 * which do not switch off the HZ timer nohz_cpu_mask should
4442 * always be CPU_MASK_NONE.
4444 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4448 * This is how migration works:
4450 * 1) we queue a migration_req_t structure in the source CPU's
4451 * runqueue and wake up that CPU's migration thread.
4452 * 2) we down() the locked semaphore => thread blocks.
4453 * 3) migration thread wakes up (implicitly it forces the migrated
4454 * thread off the CPU)
4455 * 4) it gets the migration request and checks whether the migrated
4456 * task is still in the wrong runqueue.
4457 * 5) if it's in the wrong runqueue then the migration thread removes
4458 * it and puts it into the right queue.
4459 * 6) migration thread up()s the semaphore.
4460 * 7) we wake up and the migration is done.
4464 * Change a given task's CPU affinity. Migrate the thread to a
4465 * proper CPU and schedule it away if the CPU it's executing on
4466 * is removed from the allowed bitmask.
4468 * NOTE: the caller must have a valid reference to the task, the
4469 * task must not exit() & deallocate itself prematurely. The
4470 * call is not atomic; no spinlocks may be held.
4472 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
4474 unsigned long flags;
4476 migration_req_t req;
4479 rq = task_rq_lock(p, &flags);
4480 if (!cpus_intersects(new_mask, cpu_online_map)) {
4485 p->cpus_allowed = new_mask;
4486 /* Can the task run on the task's current CPU? If so, we're done */
4487 if (cpu_isset(task_cpu(p), new_mask))
4490 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4491 /* Need help from migration thread: drop lock and wait. */
4492 task_rq_unlock(rq, &flags);
4493 wake_up_process(rq->migration_thread);
4494 wait_for_completion(&req.done);
4495 tlb_migrate_finish(p->mm);
4499 task_rq_unlock(rq, &flags);
4503 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4506 * Move (not current) task off this cpu, onto dest cpu. We're doing
4507 * this because either it can't run here any more (set_cpus_allowed()
4508 * away from this CPU, or CPU going down), or because we're
4509 * attempting to rebalance this task on exec (sched_exec).
4511 * So we race with normal scheduler movements, but that's OK, as long
4512 * as the task is no longer on this CPU.
4514 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4516 runqueue_t *rq_dest, *rq_src;
4518 if (unlikely(cpu_is_offline(dest_cpu)))
4521 rq_src = cpu_rq(src_cpu);
4522 rq_dest = cpu_rq(dest_cpu);
4524 double_rq_lock(rq_src, rq_dest);
4525 /* Already moved. */
4526 if (task_cpu(p) != src_cpu)
4528 /* Affinity changed (again). */
4529 if (!cpu_isset(dest_cpu, p->cpus_allowed))
4534 * Sync timestamp with rq_dest's before activating.
4535 * The same thing could be achieved by doing this step
4536 * afterwards, and pretending it was a local activate.
4537 * This way is cleaner and logically correct.
4539 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4540 + rq_dest->timestamp_last_tick;
4541 deactivate_task(p, rq_src);
4542 set_task_cpu(p, dest_cpu);
4543 activate_task(p, rq_dest, 0);
4544 if (TASK_PREEMPTS_CURR(p, rq_dest))
4545 resched_task(rq_dest->curr);
4547 set_task_cpu(p, dest_cpu);
4550 double_rq_unlock(rq_src, rq_dest);
4554 * migration_thread - this is a highprio system thread that performs
4555 * thread migration by bumping thread off CPU then 'pushing' onto
4558 static int migration_thread(void * data)
4561 int cpu = (long)data;
4564 BUG_ON(rq->migration_thread != current);
4566 set_current_state(TASK_INTERRUPTIBLE);
4567 while (!kthread_should_stop()) {
4568 struct list_head *head;
4569 migration_req_t *req;
4571 if (current->flags & PF_FREEZE)
4572 refrigerator(PF_FREEZE);
4574 spin_lock_irq(&rq->lock);
4576 if (cpu_is_offline(cpu)) {
4577 spin_unlock_irq(&rq->lock);
4581 if (rq->active_balance) {
4582 active_load_balance(rq, cpu);
4583 rq->active_balance = 0;
4586 head = &rq->migration_queue;
4588 if (list_empty(head)) {
4589 spin_unlock_irq(&rq->lock);
4591 set_current_state(TASK_INTERRUPTIBLE);
4594 req = list_entry(head->next, migration_req_t, list);
4595 list_del_init(head->next);
4597 if (req->type == REQ_MOVE_TASK) {
4598 spin_unlock(&rq->lock);
4599 __migrate_task(req->task, smp_processor_id(),
4602 } else if (req->type == REQ_SET_DOMAIN) {
4604 spin_unlock_irq(&rq->lock);
4606 spin_unlock_irq(&rq->lock);
4610 complete(&req->done);
4612 __set_current_state(TASK_RUNNING);
4616 /* Wait for kthread_stop */
4617 set_current_state(TASK_INTERRUPTIBLE);
4618 while (!kthread_should_stop()) {
4620 set_current_state(TASK_INTERRUPTIBLE);
4622 __set_current_state(TASK_RUNNING);
4626 #ifdef CONFIG_HOTPLUG_CPU
4627 /* Figure out where task on dead CPU should go, use force if neccessary. */
4628 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
4634 mask = node_to_cpumask(cpu_to_node(dead_cpu));
4635 cpus_and(mask, mask, tsk->cpus_allowed);
4636 dest_cpu = any_online_cpu(mask);
4638 /* On any allowed CPU? */
4639 if (dest_cpu == NR_CPUS)
4640 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4642 /* No more Mr. Nice Guy. */
4643 if (dest_cpu == NR_CPUS) {
4644 cpus_setall(tsk->cpus_allowed);
4645 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4648 * Don't tell them about moving exiting tasks or
4649 * kernel threads (both mm NULL), since they never
4652 if (tsk->mm && printk_ratelimit())
4653 printk(KERN_INFO "process %d (%s) no "
4654 "longer affine to cpu%d\n",
4655 tsk->pid, tsk->comm, dead_cpu);
4657 __migrate_task(tsk, dead_cpu, dest_cpu);
4661 * While a dead CPU has no uninterruptible tasks queued at this point,
4662 * it might still have a nonzero ->nr_uninterruptible counter, because
4663 * for performance reasons the counter is not stricly tracking tasks to
4664 * their home CPUs. So we just add the counter to another CPU's counter,
4665 * to keep the global sum constant after CPU-down:
4667 static void migrate_nr_uninterruptible(runqueue_t *rq_src)
4669 runqueue_t *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
4670 unsigned long flags;
4672 local_irq_save(flags);
4673 double_rq_lock(rq_src, rq_dest);
4674 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
4675 rq_src->nr_uninterruptible = 0;
4676 double_rq_unlock(rq_src, rq_dest);
4677 local_irq_restore(flags);
4680 /* Run through task list and migrate tasks from the dead cpu. */
4681 static void migrate_live_tasks(int src_cpu)
4683 struct task_struct *tsk, *t;
4685 write_lock_irq(&tasklist_lock);
4687 do_each_thread(t, tsk) {
4691 if (task_cpu(tsk) == src_cpu)
4692 move_task_off_dead_cpu(src_cpu, tsk);
4693 } while_each_thread(t, tsk);
4695 write_unlock_irq(&tasklist_lock);
4698 /* Schedules idle task to be the next runnable task on current CPU.
4699 * It does so by boosting its priority to highest possible and adding it to
4700 * the _front_ of runqueue. Used by CPU offline code.
4702 void sched_idle_next(void)
4704 int cpu = smp_processor_id();
4705 runqueue_t *rq = this_rq();
4706 struct task_struct *p = rq->idle;
4707 unsigned long flags;
4709 /* cpu has to be offline */
4710 BUG_ON(cpu_online(cpu));
4712 /* Strictly not necessary since rest of the CPUs are stopped by now
4713 * and interrupts disabled on current cpu.
4715 spin_lock_irqsave(&rq->lock, flags);
4717 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4718 /* Add idle task to _front_ of it's priority queue */
4719 __activate_idle_task(p, rq);
4721 spin_unlock_irqrestore(&rq->lock, flags);
4724 static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
4726 struct runqueue *rq = cpu_rq(dead_cpu);
4728 /* Must be exiting, otherwise would be on tasklist. */
4729 BUG_ON(tsk->exit_state != EXIT_ZOMBIE && tsk->exit_state != EXIT_DEAD);
4731 /* Cannot have done final schedule yet: would have vanished. */
4732 BUG_ON(tsk->flags & PF_DEAD);
4734 get_task_struct(tsk);
4737 * Drop lock around migration; if someone else moves it,
4738 * that's OK. No task can be added to this CPU, so iteration is
4741 spin_unlock_irq(&rq->lock);
4742 move_task_off_dead_cpu(dead_cpu, tsk);
4743 spin_lock_irq(&rq->lock);
4745 put_task_struct(tsk);
4748 /* release_task() removes task from tasklist, so we won't find dead tasks. */
4749 static void migrate_dead_tasks(unsigned int dead_cpu)
4752 struct runqueue *rq = cpu_rq(dead_cpu);
4754 for (arr = 0; arr < 2; arr++) {
4755 for (i = 0; i < MAX_PRIO; i++) {
4756 struct list_head *list = &rq->arrays[arr].queue[i];
4757 while (!list_empty(list))
4758 migrate_dead(dead_cpu,
4759 list_entry(list->next, task_t,
4764 #endif /* CONFIG_HOTPLUG_CPU */
4767 * migration_call - callback that gets triggered when a CPU is added.
4768 * Here we can start up the necessary migration thread for the new CPU.
4770 static int migration_call(struct notifier_block *nfb, unsigned long action,
4773 int cpu = (long)hcpu;
4774 struct task_struct *p;
4775 struct runqueue *rq;
4776 unsigned long flags;
4779 case CPU_UP_PREPARE:
4780 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4783 p->flags |= PF_NOFREEZE;
4784 kthread_bind(p, cpu);
4785 /* Must be high prio: stop_machine expects to yield to it. */
4786 rq = task_rq_lock(p, &flags);
4787 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4788 task_rq_unlock(rq, &flags);
4789 cpu_rq(cpu)->migration_thread = p;
4792 /* Strictly unneccessary, as first user will wake it. */
4793 wake_up_process(cpu_rq(cpu)->migration_thread);
4795 #ifdef CONFIG_HOTPLUG_CPU
4796 case CPU_UP_CANCELED:
4797 /* Unbind it from offline cpu so it can run. Fall thru. */
4798 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
4799 kthread_stop(cpu_rq(cpu)->migration_thread);
4800 cpu_rq(cpu)->migration_thread = NULL;
4803 migrate_live_tasks(cpu);
4805 kthread_stop(rq->migration_thread);
4806 rq->migration_thread = NULL;
4807 /* Idle task back to normal (off runqueue, low prio) */
4808 rq = task_rq_lock(rq->idle, &flags);
4809 deactivate_task(rq->idle, rq);
4810 rq->idle->static_prio = MAX_PRIO;
4811 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4812 migrate_dead_tasks(cpu);
4813 task_rq_unlock(rq, &flags);
4814 migrate_nr_uninterruptible(rq);
4815 BUG_ON(rq->nr_running != 0);
4817 /* No need to migrate the tasks: it was best-effort if
4818 * they didn't do lock_cpu_hotplug(). Just wake up
4819 * the requestors. */
4820 spin_lock_irq(&rq->lock);
4821 while (!list_empty(&rq->migration_queue)) {
4822 migration_req_t *req;
4823 req = list_entry(rq->migration_queue.next,
4824 migration_req_t, list);
4825 BUG_ON(req->type != REQ_MOVE_TASK);
4826 list_del_init(&req->list);
4827 complete(&req->done);
4829 spin_unlock_irq(&rq->lock);
4836 /* Register at highest priority so that task migration (migrate_all_tasks)
4837 * happens before everything else.
4839 static struct notifier_block __devinitdata migration_notifier = {
4840 .notifier_call = migration_call,
4844 int __init migration_init(void)
4846 void *cpu = (void *)(long)smp_processor_id();
4847 /* Start one for boot CPU. */
4848 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4849 migration_call(&migration_notifier, CPU_ONLINE, cpu);
4850 register_cpu_notifier(&migration_notifier);
4857 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
4858 * hold the hotplug lock.
4860 void __devinit cpu_attach_domain(struct sched_domain *sd, int cpu)
4862 migration_req_t req;
4863 unsigned long flags;
4864 runqueue_t *rq = cpu_rq(cpu);
4867 spin_lock_irqsave(&rq->lock, flags);
4869 if (cpu == smp_processor_id() || !cpu_online(cpu)) {
4872 init_completion(&req.done);
4873 req.type = REQ_SET_DOMAIN;
4875 list_add(&req.list, &rq->migration_queue);
4879 spin_unlock_irqrestore(&rq->lock, flags);
4882 wake_up_process(rq->migration_thread);
4883 wait_for_completion(&req.done);
4887 /* cpus with isolated domains */
4888 cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
4890 /* Setup the mask of cpus configured for isolated domains */
4891 static int __init isolated_cpu_setup(char *str)
4893 int ints[NR_CPUS], i;
4895 str = get_options(str, ARRAY_SIZE(ints), ints);
4896 cpus_clear(cpu_isolated_map);
4897 for (i = 1; i <= ints[0]; i++)
4898 cpu_set(ints[i], cpu_isolated_map);
4902 __setup ("isolcpus=", isolated_cpu_setup);
4905 * init_sched_build_groups takes an array of groups, the cpumask we wish
4906 * to span, and a pointer to a function which identifies what group a CPU
4907 * belongs to. The return value of group_fn must be a valid index into the
4908 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
4909 * keep track of groups covered with a cpumask_t).
4911 * init_sched_build_groups will build a circular linked list of the groups
4912 * covered by the given span, and will set each group's ->cpumask correctly,
4913 * and ->cpu_power to 0.
4915 void __devinit init_sched_build_groups(struct sched_group groups[],
4916 cpumask_t span, int (*group_fn)(int cpu))
4918 struct sched_group *first = NULL, *last = NULL;
4919 cpumask_t covered = CPU_MASK_NONE;
4922 for_each_cpu_mask(i, span) {
4923 int group = group_fn(i);
4924 struct sched_group *sg = &groups[group];
4927 if (cpu_isset(i, covered))
4930 sg->cpumask = CPU_MASK_NONE;
4933 for_each_cpu_mask(j, span) {
4934 if (group_fn(j) != group)
4937 cpu_set(j, covered);
4938 cpu_set(j, sg->cpumask);
4950 #ifdef ARCH_HAS_SCHED_DOMAIN
4951 extern void __devinit arch_init_sched_domains(void);
4952 extern void __devinit arch_destroy_sched_domains(void);
4954 #ifdef CONFIG_SCHED_SMT
4955 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
4956 static struct sched_group sched_group_cpus[NR_CPUS];
4957 static int __devinit cpu_to_cpu_group(int cpu)
4963 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
4964 static struct sched_group sched_group_phys[NR_CPUS];
4965 static int __devinit cpu_to_phys_group(int cpu)
4967 #ifdef CONFIG_SCHED_SMT
4968 return first_cpu(cpu_sibling_map[cpu]);
4976 static DEFINE_PER_CPU(struct sched_domain, node_domains);
4977 static struct sched_group sched_group_nodes[MAX_NUMNODES];
4978 static int __devinit cpu_to_node_group(int cpu)
4980 return cpu_to_node(cpu);
4984 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
4986 * The domains setup code relies on siblings not spanning
4987 * multiple nodes. Make sure the architecture has a proper
4990 static void check_sibling_maps(void)
4994 for_each_online_cpu(i) {
4995 for_each_cpu_mask(j, cpu_sibling_map[i]) {
4996 if (cpu_to_node(i) != cpu_to_node(j)) {
4997 printk(KERN_INFO "warning: CPU %d siblings map "
4998 "to different node - isolating "
5000 cpu_sibling_map[i] = cpumask_of_cpu(i);
5009 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
5011 static void __devinit arch_init_sched_domains(void)
5014 cpumask_t cpu_default_map;
5016 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
5017 check_sibling_maps();
5020 * Setup mask for cpus without special case scheduling requirements.
5021 * For now this just excludes isolated cpus, but could be used to
5022 * exclude other special cases in the future.
5024 cpus_complement(cpu_default_map, cpu_isolated_map);
5025 cpus_and(cpu_default_map, cpu_default_map, cpu_online_map);
5028 * Set up domains. Isolated domains just stay on the dummy domain.
5030 for_each_cpu_mask(i, cpu_default_map) {
5032 struct sched_domain *sd = NULL, *p;
5033 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
5035 cpus_and(nodemask, nodemask, cpu_default_map);
5038 sd = &per_cpu(node_domains, i);
5039 group = cpu_to_node_group(i);
5041 sd->span = cpu_default_map;
5042 sd->groups = &sched_group_nodes[group];
5046 sd = &per_cpu(phys_domains, i);
5047 group = cpu_to_phys_group(i);
5049 sd->span = nodemask;
5051 sd->groups = &sched_group_phys[group];
5053 #ifdef CONFIG_SCHED_SMT
5055 sd = &per_cpu(cpu_domains, i);
5056 group = cpu_to_cpu_group(i);
5057 *sd = SD_SIBLING_INIT;
5058 sd->span = cpu_sibling_map[i];
5059 cpus_and(sd->span, sd->span, cpu_default_map);
5061 sd->groups = &sched_group_cpus[group];
5065 #ifdef CONFIG_SCHED_SMT
5066 /* Set up CPU (sibling) groups */
5067 for_each_online_cpu(i) {
5068 cpumask_t this_sibling_map = cpu_sibling_map[i];
5069 cpus_and(this_sibling_map, this_sibling_map, cpu_default_map);
5070 if (i != first_cpu(this_sibling_map))
5073 init_sched_build_groups(sched_group_cpus, this_sibling_map,
5078 /* Set up physical groups */
5079 for (i = 0; i < MAX_NUMNODES; i++) {
5080 cpumask_t nodemask = node_to_cpumask(i);
5082 cpus_and(nodemask, nodemask, cpu_default_map);
5083 if (cpus_empty(nodemask))
5086 init_sched_build_groups(sched_group_phys, nodemask,
5087 &cpu_to_phys_group);
5092 /* Set up node groups */
5093 init_sched_build_groups(sched_group_nodes, cpu_default_map,
5094 &cpu_to_node_group);
5098 /* Calculate CPU power for physical packages and nodes */
5099 for_each_cpu_mask(i, cpu_default_map) {
5101 struct sched_domain *sd;
5102 #ifdef CONFIG_SCHED_SMT
5103 sd = &per_cpu(cpu_domains, i);
5104 power = SCHED_LOAD_SCALE;
5105 sd->groups->cpu_power = power;
5108 sd = &per_cpu(phys_domains, i);
5109 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
5110 (cpus_weight(sd->groups->cpumask)-1) / 10;
5111 sd->groups->cpu_power = power;
5115 if (i == first_cpu(sd->groups->cpumask)) {
5116 /* Only add "power" once for each physical package. */
5117 sd = &per_cpu(node_domains, i);
5118 sd->groups->cpu_power += power;
5123 /* Attach the domains */
5124 for_each_online_cpu(i) {
5125 struct sched_domain *sd;
5126 #ifdef CONFIG_SCHED_SMT
5127 sd = &per_cpu(cpu_domains, i);
5129 sd = &per_cpu(phys_domains, i);
5131 cpu_attach_domain(sd, i);
5136 #ifdef CONFIG_HOTPLUG_CPU
5137 static void __devinit arch_destroy_sched_domains(void)
5139 /* Do nothing: everything is statically allocated. */
5143 #endif /* ARCH_HAS_SCHED_DOMAIN */
5145 #define SCHED_DOMAIN_DEBUG
5146 #ifdef SCHED_DOMAIN_DEBUG
5147 static void sched_domain_debug(void)
5151 for_each_online_cpu(i) {
5152 runqueue_t *rq = cpu_rq(i);
5153 struct sched_domain *sd;
5158 printk(KERN_DEBUG "CPU%d:\n", i);
5163 struct sched_group *group = sd->groups;
5164 cpumask_t groupmask;
5166 cpumask_scnprintf(str, NR_CPUS, sd->span);
5167 cpus_clear(groupmask);
5170 for (j = 0; j < level + 1; j++)
5172 printk("domain %d: ", level);
5174 if (!(sd->flags & SD_LOAD_BALANCE)) {
5175 printk("does not load-balance");
5177 printk(" ERROR !SD_LOAD_BALANCE domain has parent");
5182 printk("span %s\n", str);
5184 if (!cpu_isset(i, sd->span))
5185 printk(KERN_DEBUG "ERROR domain->span does not contain CPU%d\n", i);
5186 if (!cpu_isset(i, group->cpumask))
5187 printk(KERN_DEBUG "ERROR domain->groups does not contain CPU%d\n", i);
5190 for (j = 0; j < level + 2; j++)
5195 printk(" ERROR: NULL");
5199 if (!group->cpu_power)
5200 printk(KERN_DEBUG "ERROR group->cpu_power not set\n");
5202 if (!cpus_weight(group->cpumask))
5203 printk(" ERROR empty group:");
5205 if (cpus_intersects(groupmask, group->cpumask))
5206 printk(" ERROR repeated CPUs:");
5208 cpus_or(groupmask, groupmask, group->cpumask);
5210 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
5213 group = group->next;
5214 } while (group != sd->groups);
5217 if (!cpus_equal(sd->span, groupmask))
5218 printk(KERN_DEBUG "ERROR groups don't span domain->span\n");
5224 if (!cpus_subset(groupmask, sd->span))
5225 printk(KERN_DEBUG "ERROR parent span is not a superset of domain->span\n");
5232 #define sched_domain_debug() {}
5236 * Initial dummy domain for early boot and for hotplug cpu. Being static,
5237 * it is initialized to zero, so all balancing flags are cleared which is
5240 static struct sched_domain sched_domain_dummy;
5242 #ifdef CONFIG_HOTPLUG_CPU
5244 * Force a reinitialization of the sched domains hierarchy. The domains
5245 * and groups cannot be updated in place without racing with the balancing
5246 * code, so we temporarily attach all running cpus to a "dummy" domain
5247 * which will prevent rebalancing while the sched domains are recalculated.
5249 static int update_sched_domains(struct notifier_block *nfb,
5250 unsigned long action, void *hcpu)
5255 case CPU_UP_PREPARE:
5256 case CPU_DOWN_PREPARE:
5257 for_each_online_cpu(i)
5258 cpu_attach_domain(&sched_domain_dummy, i);
5259 arch_destroy_sched_domains();
5262 case CPU_UP_CANCELED:
5263 case CPU_DOWN_FAILED:
5267 * Fall through and re-initialise the domains.
5274 /* The hotplug lock is already held by cpu_up/cpu_down */
5275 arch_init_sched_domains();
5277 sched_domain_debug();
5283 void __init sched_init_smp(void)
5286 arch_init_sched_domains();
5287 sched_domain_debug();
5288 unlock_cpu_hotplug();
5289 /* XXX: Theoretical race here - CPU may be hotplugged now */
5290 hotcpu_notifier(update_sched_domains, 0);
5293 void __init sched_init_smp(void)
5296 #endif /* CONFIG_SMP */
5298 int in_sched_functions(unsigned long addr)
5300 /* Linker adds these: start and end of __sched functions */
5301 extern char __sched_text_start[], __sched_text_end[];
5302 return in_lock_functions(addr) ||
5303 (addr >= (unsigned long)__sched_text_start
5304 && addr < (unsigned long)__sched_text_end);
5307 void __init sched_init(void)
5314 for (i = 0; i < NR_CPUS; i++) {
5315 #ifndef CONFIG_CKRM_CPU_SCHEDULE
5317 prio_array_t *array;
5320 spin_lock_init(&rq->lock);
5322 for (j = 0; j < 2; j++) {
5323 array = rq->arrays + j;
5324 for (k = 0; k < MAX_PRIO; k++) {
5325 INIT_LIST_HEAD(array->queue + k);
5326 __clear_bit(k, array->bitmap);
5328 // delimiter for bitsearch
5329 __set_bit(MAX_PRIO, array->bitmap);
5332 rq->active = rq->arrays;
5333 rq->expired = rq->arrays + 1;
5334 rq->best_expired_prio = MAX_PRIO;
5338 spin_lock_init(&rq->lock);
5342 rq->sd = &sched_domain_dummy;
5344 #ifdef CONFIG_CKRM_CPU_SCHEDULE
5345 ckrm_load_init(rq_ckrm_load(rq));
5347 rq->active_balance = 0;
5349 rq->migration_thread = NULL;
5350 INIT_LIST_HEAD(&rq->migration_queue);
5352 #ifdef CONFIG_VSERVER_HARDCPU
5353 INIT_LIST_HEAD(&rq->hold_queue);
5355 atomic_set(&rq->nr_iowait, 0);
5360 * The boot idle thread does lazy MMU switching as well:
5362 atomic_inc(&init_mm.mm_count);
5363 enter_lazy_tlb(&init_mm, current);
5366 * Make us the idle thread. Technically, schedule() should not be
5367 * called from this thread, however somewhere below it might be,
5368 * but because we are the idle thread, we just pick up running again
5369 * when this runqueue becomes "idle".
5371 init_idle(current, smp_processor_id());
5374 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5375 void __might_sleep(char *file, int line)
5377 #if defined(in_atomic)
5378 static unsigned long prev_jiffy; /* ratelimiting */
5380 if ((in_atomic() || irqs_disabled()) &&
5381 system_state == SYSTEM_RUNNING) {
5382 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
5384 prev_jiffy = jiffies;
5385 printk(KERN_ERR "Debug: sleeping function called from invalid"
5386 " context at %s:%d\n", file, line);
5387 printk("in_atomic():%d, irqs_disabled():%d\n",
5388 in_atomic(), irqs_disabled());
5393 EXPORT_SYMBOL(__might_sleep);
5396 #ifdef CONFIG_CKRM_CPU_SCHEDULE
5398 * return the classqueue object of a certain processor
5400 struct classqueue_struct * get_cpu_classqueue(int cpu)
5402 return (& (cpu_rq(cpu)->classqueue) );
5406 * _ckrm_cpu_change_class - change the class of a task
5408 void _ckrm_cpu_change_class(task_t *tsk, struct ckrm_cpu_class *newcls)
5410 prio_array_t *array;
5411 struct runqueue *rq;
5412 unsigned long flags;
5414 rq = task_rq_lock(tsk,&flags);
5417 dequeue_task(tsk,array);
5418 tsk->cpu_class = newcls;
5419 enqueue_task(tsk,rq_active(tsk,rq));
5421 tsk->cpu_class = newcls;
5423 task_rq_unlock(rq,&flags);
5427 #ifdef CONFIG_MAGIC_SYSRQ
5428 void normalize_rt_tasks(void)
5430 struct task_struct *p;
5431 prio_array_t *array;
5432 unsigned long flags;
5435 read_lock_irq(&tasklist_lock);
5436 for_each_process (p) {
5440 rq = task_rq_lock(p, &flags);
5444 deactivate_task(p, task_rq(p));
5445 __setscheduler(p, SCHED_NORMAL, 0);
5447 __activate_task(p, task_rq(p));
5448 resched_task(rq->curr);
5451 task_rq_unlock(rq, &flags);
5453 read_unlock_irq(&tasklist_lock);
5456 #endif /* CONFIG_MAGIC_SYSRQ */