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>
53 #include <linux/vs_context.h>
54 #include <linux/vs_cvirt.h>
55 #include <linux/vs_sched.h>
58 #define cpu_to_node_mask(cpu) node_to_cpumask(cpu_to_node(cpu))
60 #define cpu_to_node_mask(cpu) (cpu_online_map)
63 /* used to soft spin in sched while dump is in progress */
64 unsigned long dump_oncpu;
65 EXPORT_SYMBOL(dump_oncpu);
68 * Convert user-nice values [ -20 ... 0 ... 19 ]
69 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
72 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
73 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
74 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
77 * 'User priority' is the nice value converted to something we
78 * can work with better when scaling various scheduler parameters,
79 * it's a [ 0 ... 39 ] range.
81 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
82 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
83 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
86 * Some helpers for converting nanosecond timing to jiffy resolution
88 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
89 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
92 * These are the 'tuning knobs' of the scheduler:
94 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
95 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
96 * Timeslices get refilled after they expire.
98 #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
99 #define DEF_TIMESLICE (100 * HZ / 1000)
100 #define ON_RUNQUEUE_WEIGHT 30
101 #define CHILD_PENALTY 95
102 #define PARENT_PENALTY 100
103 #define EXIT_WEIGHT 3
104 #define PRIO_BONUS_RATIO 25
105 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
106 #define INTERACTIVE_DELTA 2
107 #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
108 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
109 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
110 #define CREDIT_LIMIT 100
113 * If a task is 'interactive' then we reinsert it in the active
114 * array after it has expired its current timeslice. (it will not
115 * continue to run immediately, it will still roundrobin with
116 * other interactive tasks.)
118 * This part scales the interactivity limit depending on niceness.
120 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
121 * Here are a few examples of different nice levels:
123 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
124 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
125 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
126 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
127 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
129 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
130 * priority range a task can explore, a value of '1' means the
131 * task is rated interactive.)
133 * Ie. nice +19 tasks can never get 'interactive' enough to be
134 * reinserted into the active array. And only heavily CPU-hog nice -20
135 * tasks will be expired. Default nice 0 tasks are somewhere between,
136 * it takes some effort for them to get interactive, but it's not
140 #define CURRENT_BONUS(p) \
141 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
145 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
146 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
149 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
150 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
153 #define SCALE(v1,v1_max,v2_max) \
154 (v1) * (v2_max) / (v1_max)
157 (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
159 #define TASK_INTERACTIVE(p) \
160 ((p)->prio <= (p)->static_prio - DELTA(p))
162 #define INTERACTIVE_SLEEP(p) \
163 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
164 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
166 #define HIGH_CREDIT(p) \
167 ((p)->interactive_credit > CREDIT_LIMIT)
169 #define LOW_CREDIT(p) \
170 ((p)->interactive_credit < -CREDIT_LIMIT)
172 #ifdef CONFIG_CKRM_CPU_SCHEDULE
174 * if belong to different class, compare class priority
175 * otherwise compare task priority
177 #define TASK_PREEMPTS_CURR(p, rq) \
178 ( ((p)->cpu_class != (rq)->curr->cpu_class) \
179 && ((rq)->curr != (rq)->idle) && ((p) != (rq)->idle )) \
180 ? class_preempts_curr((p),(rq)->curr) \
181 : ((p)->prio < (rq)->curr->prio)
183 #define TASK_PREEMPTS_CURR(p, rq) \
184 ((p)->prio < (rq)->curr->prio)
188 * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
189 * to time slice values: [800ms ... 100ms ... 5ms]
191 * The higher a thread's priority, the bigger timeslices
192 * it gets during one round of execution. But even the lowest
193 * priority thread gets MIN_TIMESLICE worth of execution time.
196 #define SCALE_PRIO(x, prio) \
197 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO/2), MIN_TIMESLICE)
199 unsigned int task_timeslice(task_t *p)
201 if (p->static_prio < NICE_TO_PRIO(0))
202 return SCALE_PRIO(DEF_TIMESLICE*4, p->static_prio);
204 return SCALE_PRIO(DEF_TIMESLICE, p->static_prio);
206 #define task_hot(p, now, sd) ((long long) ((now) - (p)->last_ran) \
207 < (long long) (sd)->cache_hot_time)
210 * These are the runqueue data structures:
213 typedef struct runqueue runqueue_t;
214 #include <linux/ckrm_classqueue.h>
215 #include <linux/ckrm_sched.h>
218 * This is the main, per-CPU runqueue data structure.
220 * Locking rule: those places that want to lock multiple runqueues
221 * (such as the load balancing or the thread migration code), lock
222 * acquire operations must be ordered by ascending &runqueue.
228 * nr_running and cpu_load should be in the same cacheline because
229 * remote CPUs use both these fields when doing load calculation.
231 unsigned long nr_running;
233 unsigned long cpu_load;
235 unsigned long long nr_switches;
238 * This is part of a global counter where only the total sum
239 * over all CPUs matters. A task can increase this counter on
240 * one CPU and if it got migrated afterwards it may decrease
241 * it on another CPU. Always updated under the runqueue lock:
243 unsigned long nr_uninterruptible;
245 unsigned long expired_timestamp;
246 unsigned long long timestamp_last_tick;
248 struct mm_struct *prev_mm;
249 #ifdef CONFIG_CKRM_CPU_SCHEDULE
250 struct classqueue_struct classqueue;
251 ckrm_load_t ckrm_load;
253 prio_array_t *active, *expired, arrays[2];
255 int best_expired_prio;
259 struct sched_domain *sd;
261 /* For active balancing */
265 task_t *migration_thread;
266 struct list_head migration_queue;
268 #ifdef CONFIG_VSERVER_HARDCPU
269 struct list_head hold_queue;
273 #ifdef CONFIG_VSERVER_HARDCPU
274 struct list_head hold_queue;
278 #ifdef CONFIG_SCHEDSTATS
280 struct sched_info rq_sched_info;
282 /* sys_sched_yield() stats */
283 unsigned long yld_exp_empty;
284 unsigned long yld_act_empty;
285 unsigned long yld_both_empty;
286 unsigned long yld_cnt;
288 /* schedule() stats */
289 unsigned long sched_noswitch;
290 unsigned long sched_switch;
291 unsigned long sched_cnt;
292 unsigned long sched_goidle;
294 /* pull_task() stats */
295 unsigned long pt_gained[MAX_IDLE_TYPES];
296 unsigned long pt_lost[MAX_IDLE_TYPES];
298 /* active_load_balance() stats */
299 unsigned long alb_cnt;
300 unsigned long alb_lost;
301 unsigned long alb_gained;
302 unsigned long alb_failed;
304 /* try_to_wake_up() stats */
305 unsigned long ttwu_cnt;
306 unsigned long ttwu_attempts;
307 unsigned long ttwu_moved;
309 /* wake_up_new_task() stats */
310 unsigned long wunt_cnt;
311 unsigned long wunt_moved;
313 /* sched_migrate_task() stats */
314 unsigned long smt_cnt;
316 /* sched_balance_exec() stats */
317 unsigned long sbe_cnt;
321 static DEFINE_PER_CPU(struct runqueue, runqueues);
323 #define for_each_domain(cpu, domain) \
324 for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
326 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
327 #define this_rq() (&__get_cpu_var(runqueues))
328 #define task_rq(p) cpu_rq(task_cpu(p))
329 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
332 * Default context-switch locking:
334 #ifndef prepare_arch_switch
335 # define prepare_arch_switch(rq, next) do { } while (0)
336 # define finish_arch_switch(rq, next) spin_unlock_irq(&(rq)->lock)
337 # define task_running(rq, p) ((rq)->curr == (p))
341 * task_rq_lock - lock the runqueue a given task resides on and disable
342 * interrupts. Note the ordering: we can safely lookup the task_rq without
343 * explicitly disabling preemption.
345 static runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
351 local_irq_save(*flags);
353 spin_lock(&rq->lock);
354 if (unlikely(rq != task_rq(p))) {
355 spin_unlock_irqrestore(&rq->lock, *flags);
356 goto repeat_lock_task;
361 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
364 spin_unlock_irqrestore(&rq->lock, *flags);
367 #ifdef CONFIG_SCHEDSTATS
369 * bump this up when changing the output format or the meaning of an existing
370 * format, so that tools can adapt (or abort)
372 #define SCHEDSTAT_VERSION 10
374 static int show_schedstat(struct seq_file *seq, void *v)
377 enum idle_type itype;
379 seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
380 seq_printf(seq, "timestamp %lu\n", jiffies);
381 for_each_online_cpu(cpu) {
382 runqueue_t *rq = cpu_rq(cpu);
384 struct sched_domain *sd;
388 /* runqueue-specific stats */
390 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu "
391 "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
392 cpu, rq->yld_both_empty,
393 rq->yld_act_empty, rq->yld_exp_empty,
394 rq->yld_cnt, rq->sched_noswitch,
395 rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
396 rq->alb_cnt, rq->alb_gained, rq->alb_lost,
398 rq->ttwu_cnt, rq->ttwu_moved, rq->ttwu_attempts,
399 rq->wunt_cnt, rq->wunt_moved,
400 rq->smt_cnt, rq->sbe_cnt, rq->rq_sched_info.cpu_time,
401 rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
403 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES; itype++)
404 seq_printf(seq, " %lu %lu", rq->pt_gained[itype],
406 seq_printf(seq, "\n");
409 /* domain-specific stats */
410 for_each_domain(cpu, sd) {
411 char mask_str[NR_CPUS];
413 cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
414 seq_printf(seq, "domain%d %s", dcnt++, mask_str);
415 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
417 seq_printf(seq, " %lu %lu %lu %lu %lu",
419 sd->lb_failed[itype],
420 sd->lb_imbalance[itype],
421 sd->lb_nobusyq[itype],
422 sd->lb_nobusyg[itype]);
424 seq_printf(seq, " %lu %lu %lu %lu\n",
425 sd->sbe_pushed, sd->sbe_attempts,
426 sd->ttwu_wake_affine, sd->ttwu_wake_balance);
433 static int schedstat_open(struct inode *inode, struct file *file)
435 unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
436 char *buf = kmalloc(size, GFP_KERNEL);
442 res = single_open(file, show_schedstat, NULL);
444 m = file->private_data;
452 struct file_operations proc_schedstat_operations = {
453 .open = schedstat_open,
456 .release = single_release,
459 # define schedstat_inc(rq, field) rq->field++;
460 # define schedstat_add(rq, field, amt) rq->field += amt;
461 #else /* !CONFIG_SCHEDSTATS */
462 # define schedstat_inc(rq, field) do { } while (0);
463 # define schedstat_add(rq, field, amt) do { } while (0);
467 * rq_lock - lock a given runqueue and disable interrupts.
469 static runqueue_t *this_rq_lock(void)
476 spin_lock(&rq->lock);
481 static inline void rq_unlock(runqueue_t *rq)
484 spin_unlock_irq(&rq->lock);
487 #ifdef CONFIG_SCHEDSTATS
489 * Called when a process is dequeued from the active array and given
490 * the cpu. We should note that with the exception of interactive
491 * tasks, the expired queue will become the active queue after the active
492 * queue is empty, without explicitly dequeuing and requeuing tasks in the
493 * expired queue. (Interactive tasks may be requeued directly to the
494 * active queue, thus delaying tasks in the expired queue from running;
495 * see scheduler_tick()).
497 * This function is only called from sched_info_arrive(), rather than
498 * dequeue_task(). Even though a task may be queued and dequeued multiple
499 * times as it is shuffled about, we're really interested in knowing how
500 * long it was from the *first* time it was queued to the time that it
503 static inline void sched_info_dequeued(task_t *t)
505 t->sched_info.last_queued = 0;
509 * Called when a task finally hits the cpu. We can now calculate how
510 * long it was waiting to run. We also note when it began so that we
511 * can keep stats on how long its timeslice is.
513 static inline void sched_info_arrive(task_t *t)
515 unsigned long now = jiffies, diff = 0;
516 struct runqueue *rq = task_rq(t);
518 if (t->sched_info.last_queued)
519 diff = now - t->sched_info.last_queued;
520 sched_info_dequeued(t);
521 t->sched_info.run_delay += diff;
522 t->sched_info.last_arrival = now;
523 t->sched_info.pcnt++;
528 rq->rq_sched_info.run_delay += diff;
529 rq->rq_sched_info.pcnt++;
533 * Called when a process is queued into either the active or expired
534 * array. The time is noted and later used to determine how long we
535 * had to wait for us to reach the cpu. Since the expired queue will
536 * become the active queue after active queue is empty, without dequeuing
537 * and requeuing any tasks, we are interested in queuing to either. It
538 * is unusual but not impossible for tasks to be dequeued and immediately
539 * requeued in the same or another array: this can happen in sched_yield(),
540 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
543 * This function is only called from enqueue_task(), but also only updates
544 * the timestamp if it is already not set. It's assumed that
545 * sched_info_dequeued() will clear that stamp when appropriate.
547 static inline void sched_info_queued(task_t *t)
549 if (!t->sched_info.last_queued)
550 t->sched_info.last_queued = jiffies;
554 * Called when a process ceases being the active-running process, either
555 * voluntarily or involuntarily. Now we can calculate how long we ran.
557 static inline void sched_info_depart(task_t *t)
559 struct runqueue *rq = task_rq(t);
560 unsigned long diff = jiffies - t->sched_info.last_arrival;
562 t->sched_info.cpu_time += diff;
565 rq->rq_sched_info.cpu_time += diff;
569 * Called when tasks are switched involuntarily due, typically, to expiring
570 * their time slice. (This may also be called when switching to or from
571 * the idle task.) We are only called when prev != next.
573 static inline void sched_info_switch(task_t *prev, task_t *next)
575 struct runqueue *rq = task_rq(prev);
578 * prev now departs the cpu. It's not interesting to record
579 * stats about how efficient we were at scheduling the idle
582 if (prev != rq->idle)
583 sched_info_depart(prev);
585 if (next != rq->idle)
586 sched_info_arrive(next);
589 #define sched_info_queued(t) do { } while (0)
590 #define sched_info_switch(t, next) do { } while (0)
591 #endif /* CONFIG_SCHEDSTATS */
593 #ifdef CONFIG_CKRM_CPU_SCHEDULE
594 static inline ckrm_lrq_t *rq_get_next_class(struct runqueue *rq)
596 cq_node_t *node = classqueue_get_head(&rq->classqueue);
597 return ((node) ? class_list_entry(node) : NULL);
601 * return the cvt of the current running class
602 * if no current running class, return 0
603 * assume cpu is valid (cpu_online(cpu) == 1)
605 CVT_t get_local_cur_cvt(int cpu)
607 ckrm_lrq_t * lrq = rq_get_next_class(cpu_rq(cpu));
610 return lrq->local_cvt;
615 static inline struct task_struct * rq_get_next_task(struct runqueue* rq)
618 struct task_struct *next;
621 int cpu = smp_processor_id();
623 // it is guaranteed be the ( rq->nr_running > 0 ) check in
624 // schedule that a task will be found.
627 queue = rq_get_next_class(rq);
630 array = queue->active;
631 if (unlikely(!array->nr_active)) {
632 queue->active = queue->expired;
633 queue->expired = array;
634 queue->expired_timestamp = 0;
636 schedstat_inc(rq, sched_switch);
637 if (queue->active->nr_active)
638 set_top_priority(queue,
639 find_first_bit(queue->active->bitmap, MAX_PRIO));
641 classqueue_dequeue(queue->classqueue,
642 &queue->classqueue_linkobj);
643 cpu_demand_event(get_rq_local_stat(queue,cpu),CPU_DEMAND_DEQUEUE,0);
645 goto retry_next_class;
647 schedstat_inc(rq, sched_noswitch);
648 // BUG_ON(!array->nr_active);
650 idx = queue->top_priority;
651 // BUG_ON (idx == MAX_PRIO);
652 next = task_list_entry(array->queue[idx].next);
655 #else /*! CONFIG_CKRM_CPU_SCHEDULE*/
656 static inline struct task_struct * rq_get_next_task(struct runqueue* rq)
659 struct list_head *queue;
663 if (unlikely(!array->nr_active)) {
665 * Switch the active and expired arrays.
667 schedstat_inc(rq, sched_switch);
668 rq->active = rq->expired;
671 rq->expired_timestamp = 0;
672 rq->best_expired_prio = MAX_PRIO;
674 schedstat_inc(rq, sched_noswitch);
676 idx = sched_find_first_bit(array->bitmap);
677 queue = array->queue + idx;
678 return list_entry(queue->next, task_t, run_list);
681 static inline void class_enqueue_task(struct task_struct* p, prio_array_t *array) { }
682 static inline void class_dequeue_task(struct task_struct* p, prio_array_t *array) { }
683 static inline void init_cpu_classes(void) { }
684 #define rq_ckrm_load(rq) NULL
685 static inline void ckrm_sched_tick(int j,int this_cpu,void* name) {}
686 #endif /* CONFIG_CKRM_CPU_SCHEDULE */
689 * Adding/removing a task to/from a priority array:
691 static void dequeue_task(struct task_struct *p, prio_array_t *array)
694 list_del(&p->run_list);
695 if (list_empty(array->queue + p->prio))
696 __clear_bit(p->prio, array->bitmap);
697 class_dequeue_task(p,array);
700 static void enqueue_task(struct task_struct *p, prio_array_t *array)
702 sched_info_queued(p);
703 list_add_tail(&p->run_list, array->queue + p->prio);
704 __set_bit(p->prio, array->bitmap);
707 class_enqueue_task(p,array);
711 * Used by the migration code - we pull tasks from the head of the
712 * remote queue so we want these tasks to show up at the head of the
715 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
717 list_add(&p->run_list, array->queue + p->prio);
718 __set_bit(p->prio, array->bitmap);
721 class_enqueue_task(p,array);
725 * effective_prio - return the priority that is based on the static
726 * priority but is modified by bonuses/penalties.
728 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
729 * into the -5 ... 0 ... +5 bonus/penalty range.
731 * We use 25% of the full 0...39 priority range so that:
733 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
734 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
736 * Both properties are important to certain workloads.
738 static int effective_prio(task_t *p)
745 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
747 prio = p->static_prio - bonus;
748 #ifdef CONFIG_VSERVER_HARDCPU
749 if (task_vx_flags(p, VXF_SCHED_PRIO, 0))
750 prio += effective_vavavoom(p, MAX_USER_PRIO);
752 if (prio < MAX_RT_PRIO)
754 if (prio > MAX_PRIO-1)
760 * __activate_task - move a task to the runqueue.
762 static inline void __activate_task(task_t *p, runqueue_t *rq)
764 enqueue_task(p, rq_active(p,rq));
769 * __activate_idle_task - move idle task to the _front_ of runqueue.
771 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
773 enqueue_task_head(p, rq_active(p,rq));
777 static void recalc_task_prio(task_t *p, unsigned long long now)
779 unsigned long long __sleep_time = now - p->timestamp;
780 unsigned long sleep_time;
782 if (__sleep_time > NS_MAX_SLEEP_AVG)
783 sleep_time = NS_MAX_SLEEP_AVG;
785 sleep_time = (unsigned long)__sleep_time;
787 if (likely(sleep_time > 0)) {
789 * User tasks that sleep a long time are categorised as
790 * idle and will get just interactive status to stay active &
791 * prevent them suddenly becoming cpu hogs and starving
794 if (p->mm && p->activated != -1 &&
795 sleep_time > INTERACTIVE_SLEEP(p)) {
796 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
799 p->interactive_credit++;
802 * The lower the sleep avg a task has the more
803 * rapidly it will rise with sleep time.
805 sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
808 * Tasks with low interactive_credit are limited to
809 * one timeslice worth of sleep avg bonus.
812 sleep_time > JIFFIES_TO_NS(task_timeslice(p)))
813 sleep_time = JIFFIES_TO_NS(task_timeslice(p));
816 * Non high_credit tasks waking from uninterruptible
817 * sleep are limited in their sleep_avg rise as they
818 * are likely to be cpu hogs waiting on I/O
820 if (p->activated == -1 && !HIGH_CREDIT(p) && p->mm) {
821 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
823 else if (p->sleep_avg + sleep_time >=
824 INTERACTIVE_SLEEP(p)) {
825 p->sleep_avg = INTERACTIVE_SLEEP(p);
831 * This code gives a bonus to interactive tasks.
833 * The boost works by updating the 'average sleep time'
834 * value here, based on ->timestamp. The more time a
835 * task spends sleeping, the higher the average gets -
836 * and the higher the priority boost gets as well.
838 p->sleep_avg += sleep_time;
840 if (p->sleep_avg > NS_MAX_SLEEP_AVG) {
841 p->sleep_avg = NS_MAX_SLEEP_AVG;
843 p->interactive_credit++;
848 p->prio = effective_prio(p);
852 * activate_task - move a task to the runqueue and do priority recalculation
854 * Update all the scheduling statistics stuff. (sleep average
855 * calculation, priority modifiers, etc.)
857 static void activate_task(task_t *p, runqueue_t *rq, int local)
859 unsigned long long now;
864 /* Compensate for drifting sched_clock */
865 runqueue_t *this_rq = this_rq();
866 now = (now - this_rq->timestamp_last_tick)
867 + rq->timestamp_last_tick;
871 recalc_task_prio(p, now);
874 * This checks to make sure it's not an uninterruptible task
875 * that is now waking up.
879 * Tasks which were woken up by interrupts (ie. hw events)
880 * are most likely of interactive nature. So we give them
881 * the credit of extending their sleep time to the period
882 * of time they spend on the runqueue, waiting for execution
883 * on a CPU, first time around:
889 * Normal first-time wakeups get a credit too for
890 * on-runqueue time, but it will be weighted down:
898 __activate_task(p, rq);
902 * deactivate_task - remove a task from the runqueue.
904 static void __deactivate_task(struct task_struct *p, runqueue_t *rq)
907 dequeue_task(p, p->array);
913 void deactivate_task(struct task_struct *p, runqueue_t *rq)
915 vx_deactivate_task(p);
916 __deactivate_task(p, rq);
920 * resched_task - mark a task 'to be rescheduled now'.
922 * On UP this means the setting of the need_resched flag, on SMP it
923 * might also involve a cross-CPU call to trigger the scheduler on
927 static void resched_task(task_t *p)
929 int need_resched, nrpolling;
931 BUG_ON(!spin_is_locked(&task_rq(p)->lock));
933 /* minimise the chance of sending an interrupt to poll_idle() */
934 nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
935 need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
936 nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
938 if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
939 smp_send_reschedule(task_cpu(p));
942 static inline void resched_task(task_t *p)
944 set_tsk_need_resched(p);
949 * task_curr - is this task currently executing on a CPU?
950 * @p: the task in question.
952 inline int task_curr(const task_t *p)
954 return cpu_curr(task_cpu(p)) == p;
964 struct list_head list;
965 enum request_type type;
967 /* For REQ_MOVE_TASK */
971 /* For REQ_SET_DOMAIN */
972 struct sched_domain *sd;
974 struct completion done;
978 * The task's runqueue lock must be held.
979 * Returns true if you have to wait for migration thread.
981 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
983 runqueue_t *rq = task_rq(p);
986 * If the task is not on a runqueue (and not running), then
987 * it is sufficient to simply update the task's cpu field.
989 if (!p->array && !task_running(rq, p)) {
990 set_task_cpu(p, dest_cpu);
994 init_completion(&req->done);
995 req->type = REQ_MOVE_TASK;
997 req->dest_cpu = dest_cpu;
998 list_add(&req->list, &rq->migration_queue);
1003 * wait_task_inactive - wait for a thread to unschedule.
1005 * The caller must ensure that the task *will* unschedule sometime soon,
1006 * else this function might spin for a *long* time. This function can't
1007 * be called with interrupts off, or it may introduce deadlock with
1008 * smp_call_function() if an IPI is sent by the same process we are
1009 * waiting to become inactive.
1011 void wait_task_inactive(task_t * p)
1013 unsigned long flags;
1018 rq = task_rq_lock(p, &flags);
1019 /* Must be off runqueue entirely, not preempted. */
1020 if (unlikely(p->array)) {
1021 /* If it's preempted, we yield. It could be a while. */
1022 preempted = !task_running(rq, p);
1023 task_rq_unlock(rq, &flags);
1029 task_rq_unlock(rq, &flags);
1033 * kick_process - kick a running thread to enter/exit the kernel
1034 * @p: the to-be-kicked thread
1036 * Cause a process which is running on another CPU to enter
1037 * kernel-mode, without any delay. (to get signals handled.)
1039 void kick_process(task_t *p)
1045 if ((cpu != smp_processor_id()) && task_curr(p))
1046 smp_send_reschedule(cpu);
1051 * Return a low guess at the load of a migration-source cpu.
1053 * We want to under-estimate the load of migration sources, to
1054 * balance conservatively.
1056 static inline unsigned long source_load(int cpu)
1058 runqueue_t *rq = cpu_rq(cpu);
1059 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
1061 return min(rq->cpu_load, load_now);
1065 * Return a high guess at the load of a migration-target cpu
1067 static inline unsigned long target_load(int cpu)
1069 runqueue_t *rq = cpu_rq(cpu);
1070 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
1072 return max(rq->cpu_load, load_now);
1078 * wake_idle() is useful especially on SMT architectures to wake a
1079 * task onto an idle sibling if we would otherwise wake it onto a
1082 * Returns the CPU we should wake onto.
1084 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1085 static int wake_idle(int cpu, task_t *p)
1088 runqueue_t *rq = cpu_rq(cpu);
1089 struct sched_domain *sd;
1096 if (!(sd->flags & SD_WAKE_IDLE))
1099 cpus_and(tmp, sd->span, p->cpus_allowed);
1101 for_each_cpu_mask(i, tmp) {
1109 static inline int wake_idle(int cpu, task_t *p)
1116 * try_to_wake_up - wake up a thread
1117 * @p: the to-be-woken-up thread
1118 * @state: the mask of task states that can be woken
1119 * @sync: do a synchronous wakeup?
1121 * Put it on the run-queue if it's not already there. The "current"
1122 * thread is always on the run-queue (except when the actual
1123 * re-schedule is in progress), and as such you're allowed to do
1124 * the simpler "current->state = TASK_RUNNING" to mark yourself
1125 * runnable without the overhead of this.
1127 * returns failure only if the task is already active.
1129 static int try_to_wake_up(task_t * p, unsigned int state, int sync)
1131 int cpu, this_cpu, success = 0;
1132 unsigned long flags;
1136 unsigned long load, this_load;
1137 struct sched_domain *sd;
1141 rq = task_rq_lock(p, &flags);
1142 schedstat_inc(rq, ttwu_cnt);
1143 old_state = p->state;
1144 if (!(old_state & state))
1151 this_cpu = smp_processor_id();
1154 if (unlikely(task_running(rq, p)))
1159 if (cpu == this_cpu || unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1162 load = source_load(cpu);
1163 this_load = target_load(this_cpu);
1166 * If sync wakeup then subtract the (maximum possible) effect of
1167 * the currently running task from the load of the current CPU:
1170 this_load -= SCHED_LOAD_SCALE;
1172 /* Don't pull the task off an idle CPU to a busy one */
1173 if (load < SCHED_LOAD_SCALE/2 && this_load > SCHED_LOAD_SCALE/2)
1176 new_cpu = this_cpu; /* Wake to this CPU if we can */
1179 * Scan domains for affine wakeup and passive balancing
1182 for_each_domain(this_cpu, sd) {
1183 unsigned int imbalance;
1185 * Start passive balancing when half the imbalance_pct
1188 imbalance = sd->imbalance_pct + (sd->imbalance_pct - 100) / 2;
1190 if ((sd->flags & SD_WAKE_AFFINE) &&
1191 !task_hot(p, rq->timestamp_last_tick, sd)) {
1193 * This domain has SD_WAKE_AFFINE and p is cache cold
1196 if (cpu_isset(cpu, sd->span)) {
1197 schedstat_inc(sd, ttwu_wake_affine);
1200 } else if ((sd->flags & SD_WAKE_BALANCE) &&
1201 imbalance*this_load <= 100*load) {
1203 * This domain has SD_WAKE_BALANCE and there is
1206 if (cpu_isset(cpu, sd->span)) {
1207 schedstat_inc(sd, ttwu_wake_balance);
1213 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1215 schedstat_inc(rq, ttwu_attempts);
1216 new_cpu = wake_idle(new_cpu, p);
1217 if (new_cpu != cpu && cpu_isset(new_cpu, p->cpus_allowed)) {
1218 schedstat_inc(rq, ttwu_moved);
1219 set_task_cpu(p, new_cpu);
1220 task_rq_unlock(rq, &flags);
1221 /* might preempt at this point */
1222 rq = task_rq_lock(p, &flags);
1223 old_state = p->state;
1224 if (!(old_state & state))
1229 this_cpu = smp_processor_id();
1234 #endif /* CONFIG_SMP */
1235 if (old_state == TASK_UNINTERRUPTIBLE) {
1236 rq->nr_uninterruptible--;
1238 * Tasks on involuntary sleep don't earn
1239 * sleep_avg beyond just interactive state.
1245 * Sync wakeups (i.e. those types of wakeups where the waker
1246 * has indicated that it will leave the CPU in short order)
1247 * don't trigger a preemption, if the woken up task will run on
1248 * this cpu. (in this case the 'I will reschedule' promise of
1249 * the waker guarantees that the freshly woken up task is going
1250 * to be considered on this CPU.)
1252 activate_task(p, rq, cpu == this_cpu);
1253 /* this is to get the accounting behind the load update */
1254 if (old_state == TASK_UNINTERRUPTIBLE)
1255 vx_uninterruptible_dec(p);
1256 if (!sync || cpu != this_cpu) {
1257 if (TASK_PREEMPTS_CURR(p, rq))
1258 resched_task(rq->curr);
1263 p->state = TASK_RUNNING;
1265 task_rq_unlock(rq, &flags);
1270 int fastcall wake_up_process(task_t * p)
1272 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1273 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1276 EXPORT_SYMBOL(wake_up_process);
1278 int fastcall wake_up_state(task_t *p, unsigned int state)
1280 return try_to_wake_up(p, state, 0);
1284 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1285 struct sched_domain *sd);
1289 * Perform scheduler related setup for a newly forked process p.
1290 * p is forked by current.
1292 void fastcall sched_fork(task_t *p)
1295 * We mark the process as running here, but have not actually
1296 * inserted it onto the runqueue yet. This guarantees that
1297 * nobody will actually run it, and a signal or other external
1298 * event cannot wake it up and insert it on the runqueue either.
1300 p->state = TASK_RUNNING;
1301 INIT_LIST_HEAD(&p->run_list);
1303 spin_lock_init(&p->switch_lock);
1304 #ifdef CONFIG_SCHEDSTATS
1305 memset(&p->sched_info, 0, sizeof(p->sched_info));
1307 #ifdef CONFIG_CKRM_CPU_SCHEDULE
1308 cpu_demand_event(&p->demand_stat,CPU_DEMAND_INIT,0);
1310 #ifdef CONFIG_PREEMPT
1312 * During context-switch we hold precisely one spinlock, which
1313 * schedule_tail drops. (in the common case it's this_rq()->lock,
1314 * but it also can be p->switch_lock.) So we compensate with a count
1315 * of 1. Also, we want to start with kernel preemption disabled.
1317 p->thread_info->preempt_count = 1;
1320 * Share the timeslice between parent and child, thus the
1321 * total amount of pending timeslices in the system doesn't change,
1322 * resulting in more scheduling fairness.
1324 local_irq_disable();
1325 p->time_slice = (current->time_slice + 1) >> 1;
1327 * The remainder of the first timeslice might be recovered by
1328 * the parent if the child exits early enough.
1330 p->first_time_slice = 1;
1331 current->time_slice >>= 1;
1332 p->timestamp = sched_clock();
1333 if (unlikely(!current->time_slice)) {
1335 * This case is rare, it happens when the parent has only
1336 * a single jiffy left from its timeslice. Taking the
1337 * runqueue lock is not a problem.
1339 current->time_slice = 1;
1341 scheduler_tick(0, 0);
1349 * wake_up_new_task - wake up a newly created task for the first time.
1351 * This function will do some initial scheduler statistics housekeeping
1352 * that must be done for every newly created context, then puts the task
1353 * on the runqueue and wakes it.
1355 void fastcall wake_up_new_task(task_t * p, unsigned long clone_flags)
1357 unsigned long flags;
1359 runqueue_t *rq, *this_rq;
1361 rq = task_rq_lock(p, &flags);
1363 this_cpu = smp_processor_id();
1365 BUG_ON(p->state != TASK_RUNNING);
1367 schedstat_inc(rq, wunt_cnt);
1369 * We decrease the sleep average of forking parents
1370 * and children as well, to keep max-interactive tasks
1371 * from forking tasks that are max-interactive. The parent
1372 * (current) is done further down, under its lock.
1374 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1375 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1377 p->interactive_credit = 0;
1379 p->prio = effective_prio(p);
1381 vx_activate_task(p);
1382 if (likely(cpu == this_cpu)) {
1383 if (!(clone_flags & CLONE_VM)) {
1385 * The VM isn't cloned, so we're in a good position to
1386 * do child-runs-first in anticipation of an exec. This
1387 * usually avoids a lot of COW overhead.
1389 if (unlikely(!current->array))
1390 __activate_task(p, rq);
1392 p->prio = current->prio;
1393 list_add_tail(&p->run_list, ¤t->run_list);
1394 p->array = current->array;
1395 p->array->nr_active++;
1397 class_enqueue_task(p,p->array);
1401 /* Run child last */
1402 __activate_task(p, rq);
1404 * We skip the following code due to cpu == this_cpu
1406 * task_rq_unlock(rq, &flags);
1407 * this_rq = task_rq_lock(current, &flags);
1411 this_rq = cpu_rq(this_cpu);
1414 * Not the local CPU - must adjust timestamp. This should
1415 * get optimised away in the !CONFIG_SMP case.
1417 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1418 + rq->timestamp_last_tick;
1419 __activate_task(p, rq);
1420 if (TASK_PREEMPTS_CURR(p, rq))
1421 resched_task(rq->curr);
1423 schedstat_inc(rq, wunt_moved);
1425 * Parent and child are on different CPUs, now get the
1426 * parent runqueue to update the parent's ->sleep_avg:
1428 task_rq_unlock(rq, &flags);
1429 this_rq = task_rq_lock(current, &flags);
1431 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1432 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1433 task_rq_unlock(this_rq, &flags);
1437 * Potentially available exiting-child timeslices are
1438 * retrieved here - this way the parent does not get
1439 * penalized for creating too many threads.
1441 * (this cannot be used to 'generate' timeslices
1442 * artificially, because any timeslice recovered here
1443 * was given away by the parent in the first place.)
1445 void fastcall sched_exit(task_t * p)
1447 unsigned long flags;
1451 * If the child was a (relative-) CPU hog then decrease
1452 * the sleep_avg of the parent as well.
1454 rq = task_rq_lock(p->parent, &flags);
1455 if (p->first_time_slice) {
1456 p->parent->time_slice += p->time_slice;
1457 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1458 p->parent->time_slice = task_timeslice(p);
1460 if (p->sleep_avg < p->parent->sleep_avg)
1461 p->parent->sleep_avg = p->parent->sleep_avg /
1462 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1464 task_rq_unlock(rq, &flags);
1468 * finish_task_switch - clean up after a task-switch
1469 * @prev: the thread we just switched away from.
1471 * We enter this with the runqueue still locked, and finish_arch_switch()
1472 * will unlock it along with doing any other architecture-specific cleanup
1475 * Note that we may have delayed dropping an mm in context_switch(). If
1476 * so, we finish that here outside of the runqueue lock. (Doing it
1477 * with the lock held can cause deadlocks; see schedule() for
1480 static void finish_task_switch(task_t *prev)
1481 __releases(rq->lock)
1483 runqueue_t *rq = this_rq();
1484 struct mm_struct *mm = rq->prev_mm;
1485 unsigned long prev_task_flags;
1490 * A task struct has one reference for the use as "current".
1491 * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1492 * calls schedule one last time. The schedule call will never return,
1493 * and the scheduled task must drop that reference.
1494 * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1495 * still held, otherwise prev could be scheduled on another cpu, die
1496 * there before we look at prev->state, and then the reference would
1498 * Manfred Spraul <manfred@colorfullife.com>
1500 prev_task_flags = prev->flags;
1501 finish_arch_switch(rq, prev);
1504 if (unlikely(prev_task_flags & PF_DEAD))
1505 put_task_struct(prev);
1509 * schedule_tail - first thing a freshly forked thread must call.
1510 * @prev: the thread we just switched away from.
1512 asmlinkage void schedule_tail(task_t *prev)
1513 __releases(rq->lock)
1515 finish_task_switch(prev);
1517 if (current->set_child_tid)
1518 put_user(current->pid, current->set_child_tid);
1522 * context_switch - switch to the new MM and the new
1523 * thread's register state.
1526 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1528 struct mm_struct *mm = next->mm;
1529 struct mm_struct *oldmm = prev->active_mm;
1531 if (unlikely(!mm)) {
1532 next->active_mm = oldmm;
1533 atomic_inc(&oldmm->mm_count);
1534 enter_lazy_tlb(oldmm, next);
1536 switch_mm(oldmm, mm, next);
1538 if (unlikely(!prev->mm)) {
1539 prev->active_mm = NULL;
1540 WARN_ON(rq->prev_mm);
1541 rq->prev_mm = oldmm;
1544 /* Here we just switch the register state and the stack. */
1545 switch_to(prev, next, prev);
1551 * nr_running, nr_uninterruptible and nr_context_switches:
1553 * externally visible scheduler statistics: current number of runnable
1554 * threads, current number of uninterruptible-sleeping threads, total
1555 * number of context switches performed since bootup.
1557 unsigned long nr_running(void)
1559 unsigned long i, sum = 0;
1561 for_each_online_cpu(i)
1562 sum += cpu_rq(i)->nr_running;
1567 unsigned long nr_uninterruptible(void)
1569 unsigned long i, sum = 0;
1572 sum += cpu_rq(i)->nr_uninterruptible;
1575 * Since we read the counters lockless, it might be slightly
1576 * inaccurate. Do not allow it to go below zero though:
1578 if (unlikely((long)sum < 0))
1584 unsigned long long nr_context_switches(void)
1586 unsigned long long i, sum = 0;
1589 sum += cpu_rq(i)->nr_switches;
1594 unsigned long nr_iowait(void)
1596 unsigned long i, sum = 0;
1599 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1607 * double_rq_lock - safely lock two runqueues
1609 * Note this does not disable interrupts like task_rq_lock,
1610 * you need to do so manually before calling.
1612 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1613 __acquires(rq1->lock)
1614 __acquires(rq2->lock)
1617 spin_lock(&rq1->lock);
1618 __acquire(rq2->lock); /* Fake it out ;) */
1621 spin_lock(&rq1->lock);
1622 spin_lock(&rq2->lock);
1624 spin_lock(&rq2->lock);
1625 spin_lock(&rq1->lock);
1631 * double_rq_unlock - safely unlock two runqueues
1633 * Note this does not restore interrupts like task_rq_unlock,
1634 * you need to do so manually after calling.
1636 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1637 __releases(rq1->lock)
1638 __releases(rq2->lock)
1640 spin_unlock(&rq1->lock);
1642 spin_unlock(&rq2->lock);
1644 __release(rq2->lock);
1648 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1650 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1651 __releases(this_rq->lock)
1652 __acquires(busiest->lock)
1653 __acquires(this_rq->lock)
1655 if (unlikely(!spin_trylock(&busiest->lock))) {
1656 if (busiest < this_rq) {
1657 spin_unlock(&this_rq->lock);
1658 spin_lock(&busiest->lock);
1659 spin_lock(&this_rq->lock);
1661 spin_lock(&busiest->lock);
1666 * find_idlest_cpu - find the least busy runqueue.
1668 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1669 struct sched_domain *sd)
1671 unsigned long load, min_load, this_load;
1676 min_load = ULONG_MAX;
1678 cpus_and(mask, sd->span, p->cpus_allowed);
1680 for_each_cpu_mask(i, mask) {
1681 load = target_load(i);
1683 if (load < min_load) {
1687 /* break out early on an idle CPU: */
1693 /* add +1 to account for the new task */
1694 this_load = source_load(this_cpu) + SCHED_LOAD_SCALE;
1697 * Would with the addition of the new task to the
1698 * current CPU there be an imbalance between this
1699 * CPU and the idlest CPU?
1701 * Use half of the balancing threshold - new-context is
1702 * a good opportunity to balance.
1704 if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1711 * If dest_cpu is allowed for this process, migrate the task to it.
1712 * This is accomplished by forcing the cpu_allowed mask to only
1713 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1714 * the cpu_allowed mask is restored.
1716 static void sched_migrate_task(task_t *p, int dest_cpu)
1718 migration_req_t req;
1720 unsigned long flags;
1722 rq = task_rq_lock(p, &flags);
1723 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1724 || unlikely(cpu_is_offline(dest_cpu)))
1727 schedstat_inc(rq, smt_cnt);
1728 /* force the process onto the specified CPU */
1729 if (migrate_task(p, dest_cpu, &req)) {
1730 /* Need to wait for migration thread (might exit: take ref). */
1731 struct task_struct *mt = rq->migration_thread;
1732 get_task_struct(mt);
1733 task_rq_unlock(rq, &flags);
1734 wake_up_process(mt);
1735 put_task_struct(mt);
1736 wait_for_completion(&req.done);
1740 task_rq_unlock(rq, &flags);
1744 * sched_exec(): find the highest-level, exec-balance-capable
1745 * domain and try to migrate the task to the least loaded CPU.
1747 * execve() is a valuable balancing opportunity, because at this point
1748 * the task has the smallest effective memory and cache footprint.
1750 void sched_exec(void)
1752 struct sched_domain *tmp, *sd = NULL;
1753 int new_cpu, this_cpu = get_cpu();
1755 schedstat_inc(this_rq(), sbe_cnt);
1756 /* Prefer the current CPU if there's only this task running */
1757 if (this_rq()->nr_running <= 1)
1760 for_each_domain(this_cpu, tmp)
1761 if (tmp->flags & SD_BALANCE_EXEC)
1765 schedstat_inc(sd, sbe_attempts);
1766 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1767 if (new_cpu != this_cpu) {
1768 schedstat_inc(sd, sbe_pushed);
1770 sched_migrate_task(current, new_cpu);
1779 * pull_task - move a task from a remote runqueue to the local runqueue.
1780 * Both runqueues must be locked.
1783 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1784 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1786 dequeue_task(p, src_array);
1787 src_rq->nr_running--;
1788 set_task_cpu(p, this_cpu);
1789 this_rq->nr_running++;
1790 enqueue_task(p, this_array);
1791 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1792 + this_rq->timestamp_last_tick;
1794 * Note that idle threads have a prio of MAX_PRIO, for this test
1795 * to be always true for them.
1797 if (TASK_PREEMPTS_CURR(p, this_rq))
1798 resched_task(this_rq->curr);
1802 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1805 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1806 struct sched_domain *sd, enum idle_type idle)
1809 * We do not migrate tasks that are:
1810 * 1) running (obviously), or
1811 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1812 * 3) are cache-hot on their current CPU.
1814 if (task_running(rq, p))
1816 if (!cpu_isset(this_cpu, p->cpus_allowed))
1819 /* Aggressive migration if we've failed balancing */
1820 if (idle == NEWLY_IDLE ||
1821 sd->nr_balance_failed < sd->cache_nice_tries) {
1822 if (task_hot(p, rq->timestamp_last_tick, sd))
1829 #ifdef CONFIG_CKRM_CPU_SCHEDULE
1830 static inline int ckrm_preferred_task(task_t *tmp,long min, long max,
1831 int phase, enum idle_type idle)
1833 long pressure = task_load(tmp);
1838 if ((idle == NOT_IDLE) && ! phase && (pressure <= min))
1844 * move tasks for a specic local class
1845 * return number of tasks pulled
1847 static inline int ckrm_cls_move_tasks(ckrm_lrq_t* src_lrq,ckrm_lrq_t*dst_lrq,
1848 runqueue_t *this_rq,
1849 runqueue_t *busiest,
1850 struct sched_domain *sd,
1852 enum idle_type idle,
1853 long* pressure_imbalance)
1855 prio_array_t *array, *dst_array;
1856 struct list_head *head, *curr;
1861 long pressure_min, pressure_max;
1862 /*hzheng: magic : 90% balance is enough*/
1863 long balance_min = *pressure_imbalance / 10;
1865 * we don't want to migrate tasks that will reverse the balance
1866 * or the tasks that make too small difference
1868 #define CKRM_BALANCE_MAX_RATIO 100
1869 #define CKRM_BALANCE_MIN_RATIO 1
1873 * We first consider expired tasks. Those will likely not be
1874 * executed in the near future, and they are most likely to
1875 * be cache-cold, thus switching CPUs has the least effect
1878 if (src_lrq->expired->nr_active) {
1879 array = src_lrq->expired;
1880 dst_array = dst_lrq->expired;
1882 array = src_lrq->active;
1883 dst_array = dst_lrq->active;
1887 /* Start searching at priority 0: */
1891 idx = sched_find_first_bit(array->bitmap);
1893 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1894 if (idx >= MAX_PRIO) {
1895 if (array == src_lrq->expired && src_lrq->active->nr_active) {
1896 array = src_lrq->active;
1897 dst_array = dst_lrq->active;
1900 if ((! phase) && (! pulled) && (idle != IDLE))
1901 goto start; //try again
1903 goto out; //finished search for this lrq
1906 head = array->queue + idx;
1909 tmp = list_entry(curr, task_t, run_list);
1913 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
1920 pressure_min = *pressure_imbalance * CKRM_BALANCE_MIN_RATIO/100;
1921 pressure_max = *pressure_imbalance * CKRM_BALANCE_MAX_RATIO/100;
1923 * skip the tasks that will reverse the balance too much
1925 if (ckrm_preferred_task(tmp,pressure_min,pressure_max,phase,idle)) {
1926 *pressure_imbalance -= task_load(tmp);
1927 pull_task(busiest, array, tmp,
1928 this_rq, dst_array, this_cpu);
1931 if (*pressure_imbalance <= balance_min)
1943 static inline long ckrm_rq_imbalance(runqueue_t *this_rq,runqueue_t *dst_rq)
1947 * make sure after balance, imbalance' > - imbalance/2
1948 * we don't want the imbalance be reversed too much
1950 imbalance = pid_get_pressure(rq_ckrm_load(dst_rq),0)
1951 - pid_get_pressure(rq_ckrm_load(this_rq),1);
1957 * try to balance the two runqueues
1959 * Called with both runqueues locked.
1960 * if move_tasks is called, it will try to move at least one task over
1962 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1963 unsigned long max_nr_move, struct sched_domain *sd,
1964 enum idle_type idle)
1966 struct ckrm_cpu_class *clsptr,*vip_cls = NULL;
1967 ckrm_lrq_t* src_lrq,*dst_lrq;
1968 long pressure_imbalance, pressure_imbalance_old;
1969 int src_cpu = task_cpu(busiest->curr);
1970 struct list_head *list;
1974 imbalance = ckrm_rq_imbalance(this_rq,busiest);
1976 if ((idle == NOT_IDLE && imbalance <= 0) || busiest->nr_running <= 1)
1979 //try to find the vip class
1980 list_for_each_entry(clsptr,&active_cpu_classes,links) {
1981 src_lrq = get_ckrm_lrq(clsptr,src_cpu);
1983 if (! lrq_nr_running(src_lrq))
1986 if (! vip_cls || cpu_class_weight(vip_cls) < cpu_class_weight(clsptr) )
1993 * do search from the most significant class
1994 * hopefully, less tasks will be migrated this way
2003 src_lrq = get_ckrm_lrq(clsptr,src_cpu);
2004 if (! lrq_nr_running(src_lrq))
2007 dst_lrq = get_ckrm_lrq(clsptr,this_cpu);
2009 //how much pressure for this class should be transferred
2010 pressure_imbalance = src_lrq->lrq_load * imbalance/src_lrq->local_weight;
2011 if (pulled && ! pressure_imbalance)
2014 pressure_imbalance_old = pressure_imbalance;
2018 ckrm_cls_move_tasks(src_lrq,dst_lrq,
2022 &pressure_imbalance);
2025 * hzheng: 2 is another magic number
2026 * stop balancing if the imbalance is less than 25% of the orig
2028 if (pressure_imbalance <= (pressure_imbalance_old >> 2))
2032 imbalance *= pressure_imbalance / pressure_imbalance_old;
2035 list = clsptr->links.next;
2036 if (list == &active_cpu_classes)
2038 clsptr = list_entry(list, typeof(*clsptr), links);
2039 if (clsptr != vip_cls)
2046 * ckrm_check_balance - is load balancing necessary?
2047 * return 0 if load balancing is not necessary
2048 * otherwise return the average load of the system
2049 * also, update nr_group
2052 * no load balancing if it's load is over average
2053 * no load balancing if it's load is far more than the min
2055 * read the status of all the runqueues
2057 static unsigned long ckrm_check_balance(struct sched_domain *sd, int this_cpu,
2058 enum idle_type idle, int* nr_group)
2060 struct sched_group *group = sd->groups;
2061 unsigned long min_load, max_load, avg_load;
2062 unsigned long total_load, this_load, total_pwr;
2064 max_load = this_load = total_load = total_pwr = 0;
2065 min_load = 0xFFFFFFFF;
2074 /* Tally up the load of all CPUs in the group */
2075 cpus_and(tmp, group->cpumask, cpu_online_map);
2076 if (unlikely(cpus_empty(tmp)))
2080 local_group = cpu_isset(this_cpu, group->cpumask);
2082 for_each_cpu_mask(i, tmp) {
2083 load = pid_get_pressure(rq_ckrm_load(cpu_rq(i)),local_group);
2091 total_load += avg_load;
2092 total_pwr += group->cpu_power;
2094 /* Adjust by relative CPU power of the group */
2095 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
2098 this_load = avg_load;
2100 } else if (avg_load > max_load) {
2101 max_load = avg_load;
2103 if (avg_load < min_load) {
2104 min_load = avg_load;
2107 group = group->next;
2108 *nr_group = *nr_group + 1;
2109 } while (group != sd->groups);
2111 if (!max_load || this_load >= max_load)
2114 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2116 /* hzheng: debugging: 105 is a magic number
2117 * 100*max_load <= sd->imbalance_pct*this_load)
2118 * should use imbalance_pct instead
2120 if (this_load > avg_load
2121 || 100*max_load < 105*this_load
2122 || 100*min_load < 70*this_load
2132 * any group that has above average load is considered busy
2133 * find the busiest queue from any of busy group
2136 ckrm_find_busy_queue(struct sched_domain *sd, int this_cpu,
2137 unsigned long avg_load, enum idle_type idle,
2140 struct sched_group *group;
2141 runqueue_t * busiest=NULL;
2145 rand = get_ckrm_rand(nr_group);
2149 unsigned long load,total_load,max_load;
2152 runqueue_t * grp_busiest;
2154 cpus_and(tmp, group->cpumask, cpu_online_map);
2155 if (unlikely(cpus_empty(tmp)))
2156 goto find_nextgroup;
2161 for_each_cpu_mask(i, tmp) {
2162 load = pid_get_pressure(rq_ckrm_load(cpu_rq(i)),0);
2164 if (load > max_load) {
2166 grp_busiest = cpu_rq(i);
2170 total_load = (total_load * SCHED_LOAD_SCALE) / group->cpu_power;
2171 if (total_load > avg_load) {
2172 busiest = grp_busiest;
2173 if (nr_group >= rand)
2177 group = group->next;
2179 } while (group != sd->groups);
2185 * load_balance - pressure based load balancing algorithm used by ckrm
2187 static int ckrm_load_balance(int this_cpu, runqueue_t *this_rq,
2188 struct sched_domain *sd, enum idle_type idle)
2190 runqueue_t *busiest;
2191 unsigned long avg_load;
2192 int nr_moved,nr_group;
2194 avg_load = ckrm_check_balance(sd, this_cpu, idle, &nr_group);
2198 busiest = ckrm_find_busy_queue(sd,this_cpu,avg_load,idle,nr_group);
2202 * This should be "impossible", but since load
2203 * balancing is inherently racy and statistical,
2204 * it could happen in theory.
2206 if (unlikely(busiest == this_rq)) {
2212 if (busiest->nr_running > 1) {
2214 * Attempt to move tasks. If find_busiest_group has found
2215 * an imbalance but busiest->nr_running <= 1, the group is
2216 * still unbalanced. nr_moved simply stays zero, so it is
2217 * correctly treated as an imbalance.
2219 double_lock_balance(this_rq, busiest);
2220 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2222 spin_unlock(&busiest->lock);
2224 adjust_local_weight();
2229 sd->nr_balance_failed ++;
2231 sd->nr_balance_failed = 0;
2233 /* We were unbalanced, so reset the balancing interval */
2234 sd->balance_interval = sd->min_interval;
2239 /* tune up the balancing interval */
2240 if (sd->balance_interval < sd->max_interval)
2241 sd->balance_interval *= 2;
2247 * this_rq->lock is already held
2249 static inline int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2250 struct sched_domain *sd)
2253 read_lock(&class_list_lock);
2254 ret = ckrm_load_balance(this_cpu,this_rq,sd,NEWLY_IDLE);
2255 read_unlock(&class_list_lock);
2259 static inline int load_balance(int this_cpu, runqueue_t *this_rq,
2260 struct sched_domain *sd, enum idle_type idle)
2264 spin_lock(&this_rq->lock);
2265 read_lock(&class_list_lock);
2266 ret= ckrm_load_balance(this_cpu,this_rq,sd,NEWLY_IDLE);
2267 read_unlock(&class_list_lock);
2268 spin_unlock(&this_rq->lock);
2271 #else /*! CONFIG_CKRM_CPU_SCHEDULE */
2273 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
2274 * as part of a balancing operation within "domain". Returns the number of
2277 * Called with both runqueues locked.
2279 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
2280 unsigned long max_nr_move, struct sched_domain *sd,
2281 enum idle_type idle)
2283 prio_array_t *array, *dst_array;
2284 struct list_head *head, *curr;
2285 int idx, pulled = 0;
2288 if (max_nr_move <= 0 || busiest->nr_running <= 1)
2292 * We first consider expired tasks. Those will likely not be
2293 * executed in the near future, and they are most likely to
2294 * be cache-cold, thus switching CPUs has the least effect
2297 if (busiest->expired->nr_active) {
2298 array = busiest->expired;
2299 dst_array = this_rq->expired;
2301 array = busiest->active;
2302 dst_array = this_rq->active;
2306 /* Start searching at priority 0: */
2310 idx = sched_find_first_bit(array->bitmap);
2312 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
2313 if (idx >= MAX_PRIO) {
2314 if (array == busiest->expired && busiest->active->nr_active) {
2315 array = busiest->active;
2316 dst_array = this_rq->active;
2322 head = array->queue + idx;
2325 tmp = list_entry(curr, task_t, run_list);
2329 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
2337 * Right now, this is the only place pull_task() is called,
2338 * so we can safely collect pull_task() stats here rather than
2339 * inside pull_task().
2341 schedstat_inc(this_rq, pt_gained[idle]);
2342 schedstat_inc(busiest, pt_lost[idle]);
2344 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
2347 /* We only want to steal up to the prescribed number of tasks. */
2348 if (pulled < max_nr_move) {
2359 * find_busiest_group finds and returns the busiest CPU group within the
2360 * domain. It calculates and returns the number of tasks which should be
2361 * moved to restore balance via the imbalance parameter.
2363 static struct sched_group *
2364 find_busiest_group(struct sched_domain *sd, int this_cpu,
2365 unsigned long *imbalance, enum idle_type idle)
2367 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2368 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2370 max_load = this_load = total_load = total_pwr = 0;
2377 local_group = cpu_isset(this_cpu, group->cpumask);
2379 /* Tally up the load of all CPUs in the group */
2382 for_each_cpu_mask(i, group->cpumask) {
2383 /* Bias balancing toward cpus of our domain */
2385 load = target_load(i);
2387 load = source_load(i);
2396 total_load += avg_load;
2397 total_pwr += group->cpu_power;
2399 /* Adjust by relative CPU power of the group */
2400 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
2403 this_load = avg_load;
2406 } else if (avg_load > max_load) {
2407 max_load = avg_load;
2411 group = group->next;
2412 } while (group != sd->groups);
2414 if (!busiest || this_load >= max_load)
2417 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2419 if (this_load >= avg_load ||
2420 100*max_load <= sd->imbalance_pct*this_load)
2424 * We're trying to get all the cpus to the average_load, so we don't
2425 * want to push ourselves above the average load, nor do we wish to
2426 * reduce the max loaded cpu below the average load, as either of these
2427 * actions would just result in more rebalancing later, and ping-pong
2428 * tasks around. Thus we look for the minimum possible imbalance.
2429 * Negative imbalances (*we* are more loaded than anyone else) will
2430 * be counted as no imbalance for these purposes -- we can't fix that
2431 * by pulling tasks to us. Be careful of negative numbers as they'll
2432 * appear as very large values with unsigned longs.
2434 *imbalance = min(max_load - avg_load, avg_load - this_load);
2436 /* How much load to actually move to equalise the imbalance */
2437 *imbalance = (*imbalance * min(busiest->cpu_power, this->cpu_power))
2440 if (*imbalance < SCHED_LOAD_SCALE - 1) {
2441 unsigned long pwr_now = 0, pwr_move = 0;
2444 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
2450 * OK, we don't have enough imbalance to justify moving tasks,
2451 * however we may be able to increase total CPU power used by
2455 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
2456 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
2457 pwr_now /= SCHED_LOAD_SCALE;
2459 /* Amount of load we'd subtract */
2460 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
2462 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
2465 /* Amount of load we'd add */
2466 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
2469 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
2470 pwr_move /= SCHED_LOAD_SCALE;
2472 /* Move if we gain another 8th of a CPU worth of throughput */
2473 if (pwr_move < pwr_now + SCHED_LOAD_SCALE / 8)
2480 /* Get rid of the scaling factor, rounding down as we divide */
2481 *imbalance = (*imbalance + 1) / SCHED_LOAD_SCALE;
2486 if (busiest && (idle == NEWLY_IDLE ||
2487 (idle == SCHED_IDLE && max_load > SCHED_LOAD_SCALE)) ) {
2497 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2499 static runqueue_t *find_busiest_queue(struct sched_group *group)
2501 unsigned long load, max_load = 0;
2502 runqueue_t *busiest = NULL;
2505 for_each_cpu_mask(i, group->cpumask) {
2506 load = source_load(i);
2508 if (load > max_load) {
2510 busiest = cpu_rq(i);
2518 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2519 * tasks if there is an imbalance.
2521 * Called with this_rq unlocked.
2523 static int load_balance(int this_cpu, runqueue_t *this_rq,
2524 struct sched_domain *sd, enum idle_type idle)
2526 struct sched_group *group;
2527 runqueue_t *busiest;
2528 unsigned long imbalance;
2531 spin_lock(&this_rq->lock);
2532 schedstat_inc(sd, lb_cnt[idle]);
2534 group = find_busiest_group(sd, this_cpu, &imbalance, idle);
2536 schedstat_inc(sd, lb_nobusyg[idle]);
2540 busiest = find_busiest_queue(group);
2542 schedstat_inc(sd, lb_nobusyq[idle]);
2547 * This should be "impossible", but since load
2548 * balancing is inherently racy and statistical,
2549 * it could happen in theory.
2551 if (unlikely(busiest == this_rq)) {
2556 schedstat_add(sd, lb_imbalance[idle], imbalance);
2559 if (busiest->nr_running > 1) {
2561 * Attempt to move tasks. If find_busiest_group has found
2562 * an imbalance but busiest->nr_running <= 1, the group is
2563 * still unbalanced. nr_moved simply stays zero, so it is
2564 * correctly treated as an imbalance.
2566 double_lock_balance(this_rq, busiest);
2567 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2568 imbalance, sd, idle);
2569 spin_unlock(&busiest->lock);
2571 spin_unlock(&this_rq->lock);
2574 schedstat_inc(sd, lb_failed[idle]);
2575 sd->nr_balance_failed++;
2577 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2580 spin_lock(&busiest->lock);
2581 if (!busiest->active_balance) {
2582 busiest->active_balance = 1;
2583 busiest->push_cpu = this_cpu;
2586 spin_unlock(&busiest->lock);
2588 wake_up_process(busiest->migration_thread);
2591 * We've kicked active balancing, reset the failure
2594 sd->nr_balance_failed = sd->cache_nice_tries;
2598 * We were unbalanced, but unsuccessful in move_tasks(),
2599 * so bump the balance_interval to lessen the lock contention.
2601 if (sd->balance_interval < sd->max_interval)
2602 sd->balance_interval++;
2604 sd->nr_balance_failed = 0;
2606 /* We were unbalanced, so reset the balancing interval */
2607 sd->balance_interval = sd->min_interval;
2613 spin_unlock(&this_rq->lock);
2615 /* tune up the balancing interval */
2616 if (sd->balance_interval < sd->max_interval)
2617 sd->balance_interval *= 2;
2623 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2624 * tasks if there is an imbalance.
2626 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2627 * this_rq is locked.
2629 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2630 struct sched_domain *sd)
2632 struct sched_group *group;
2633 runqueue_t *busiest = NULL;
2634 unsigned long imbalance;
2637 schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2638 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
2640 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2644 busiest = find_busiest_queue(group);
2645 if (!busiest || busiest == this_rq) {
2646 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2650 /* Attempt to move tasks */
2651 double_lock_balance(this_rq, busiest);
2653 schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2654 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2655 imbalance, sd, NEWLY_IDLE);
2657 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2659 spin_unlock(&busiest->lock);
2664 #endif /* CONFIG_CKRM_CPU_SCHEDULE*/
2668 * idle_balance is called by schedule() if this_cpu is about to become
2669 * idle. Attempts to pull tasks from other CPUs.
2671 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
2673 struct sched_domain *sd;
2675 for_each_domain(this_cpu, sd) {
2676 if (sd->flags & SD_BALANCE_NEWIDLE) {
2677 if (load_balance_newidle(this_cpu, this_rq, sd)) {
2678 /* We've pulled tasks over so stop searching */
2685 #ifdef CONFIG_SCHED_SMT
2686 static int cpu_and_siblings_are_idle(int cpu)
2689 for_each_cpu_mask(sib, cpu_sibling_map[cpu]) {
2698 #define cpu_and_siblings_are_idle(A) idle_cpu(A)
2703 * active_load_balance is run by migration threads. It pushes running tasks
2704 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2705 * running on each physical CPU where possible, and avoids physical /
2706 * logical imbalances.
2708 * Called with busiest_rq locked.
2710 static void active_load_balance(runqueue_t *busiest_rq, int busiest_cpu)
2712 struct sched_domain *sd;
2713 struct sched_group *cpu_group;
2714 cpumask_t visited_cpus;
2716 schedstat_inc(busiest_rq, alb_cnt);
2718 * Search for suitable CPUs to push tasks to in successively higher
2719 * domains with SD_LOAD_BALANCE set.
2721 visited_cpus = CPU_MASK_NONE;
2722 for_each_domain(busiest_cpu, sd) {
2723 if (!(sd->flags & SD_LOAD_BALANCE) || busiest_rq->nr_running <= 1)
2724 break; /* no more domains to search or no more tasks to move */
2726 cpu_group = sd->groups;
2727 do { /* sched_groups should either use list_heads or be merged into the domains structure */
2728 int cpu, target_cpu = -1;
2729 runqueue_t *target_rq;
2731 for_each_cpu_mask(cpu, cpu_group->cpumask) {
2732 if (cpu_isset(cpu, visited_cpus) || cpu == busiest_cpu ||
2733 !cpu_and_siblings_are_idle(cpu)) {
2734 cpu_set(cpu, visited_cpus);
2740 if (target_cpu == -1)
2741 goto next_group; /* failed to find a suitable target cpu in this domain */
2743 target_rq = cpu_rq(target_cpu);
2746 * This condition is "impossible", if it occurs we need to fix it
2747 * Reported by Bjorn Helgaas on a 128-cpu setup.
2749 BUG_ON(busiest_rq == target_rq);
2751 /* move a task from busiest_rq to target_rq */
2752 double_lock_balance(busiest_rq, target_rq);
2753 if (move_tasks(target_rq, target_cpu, busiest_rq, 1, sd, SCHED_IDLE)) {
2754 schedstat_inc(busiest_rq, alb_lost);
2755 schedstat_inc(target_rq, alb_gained);
2757 schedstat_inc(busiest_rq, alb_failed);
2759 spin_unlock(&target_rq->lock);
2761 cpu_group = cpu_group->next;
2762 } while (cpu_group != sd->groups && busiest_rq->nr_running > 1);
2767 * rebalance_tick will get called every timer tick, on every CPU.
2769 * It checks each scheduling domain to see if it is due to be balanced,
2770 * and initiates a balancing operation if so.
2772 * Balancing parameters are set up in arch_init_sched_domains.
2775 /* Don't have all balancing operations going off at once */
2776 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2778 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2779 enum idle_type idle)
2781 unsigned long old_load, this_load;
2782 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2783 struct sched_domain *sd;
2785 /* Update our load */
2786 old_load = this_rq->cpu_load;
2787 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
2789 * Round up the averaging division if load is increasing. This
2790 * prevents us from getting stuck on 9 if the load is 10, for
2793 if (this_load > old_load)
2795 this_rq->cpu_load = (old_load + this_load) / 2;
2797 for_each_domain(this_cpu, sd) {
2798 unsigned long interval;
2800 if (!(sd->flags & SD_LOAD_BALANCE))
2803 interval = sd->balance_interval;
2804 if (idle != SCHED_IDLE)
2805 interval *= sd->busy_factor;
2807 /* scale ms to jiffies */
2808 interval = msecs_to_jiffies(interval);
2809 if (unlikely(!interval))
2812 if (j - sd->last_balance >= interval) {
2813 if (load_balance(this_cpu, this_rq, sd, idle)) {
2814 /* We've pulled tasks over so no longer idle */
2817 sd->last_balance += interval;
2823 * on UP we do not need to balance between CPUs:
2825 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2828 static inline void idle_balance(int cpu, runqueue_t *rq)
2833 static inline int wake_priority_sleeper(runqueue_t *rq)
2836 #ifdef CONFIG_SCHED_SMT
2837 spin_lock(&rq->lock);
2839 * If an SMT sibling task has been put to sleep for priority
2840 * reasons reschedule the idle task to see if it can now run.
2842 if (rq->nr_running) {
2843 resched_task(rq->idle);
2846 spin_unlock(&rq->lock);
2851 DEFINE_PER_CPU(struct kernel_stat, kstat);
2852 EXPORT_PER_CPU_SYMBOL(kstat);
2855 * We place interactive tasks back into the active array, if possible.
2857 * To guarantee that this does not starve expired tasks we ignore the
2858 * interactivity of a task if the first expired task had to wait more
2859 * than a 'reasonable' amount of time. This deadline timeout is
2860 * load-dependent, as the frequency of array switched decreases with
2861 * increasing number of running tasks. We also ignore the interactivity
2862 * if a better static_prio task has expired:
2865 #ifndef CONFIG_CKRM_CPU_SCHEDULE
2866 #define EXPIRED_STARVING(rq) \
2867 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2868 (jiffies - (rq)->expired_timestamp >= \
2869 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2870 ((rq)->curr->static_prio > (rq)->best_expired_prio))
2872 #define EXPIRED_STARVING(rq) \
2873 (STARVATION_LIMIT && ((rq)->expired_timestamp && \
2874 (jiffies - (rq)->expired_timestamp >= \
2875 STARVATION_LIMIT * (lrq_nr_running(rq)) + 1)))
2879 * This function gets called by the timer code, with HZ frequency.
2880 * We call it with interrupts disabled.
2882 * It also gets called by the fork code, when changing the parent's
2885 void scheduler_tick(int user_ticks, int sys_ticks)
2887 int cpu = smp_processor_id();
2888 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2889 runqueue_t *rq = this_rq();
2890 task_t *p = current;
2891 struct vx_info *vxi = p->vx_info;
2893 rq->timestamp_last_tick = sched_clock();
2895 if (rcu_pending(cpu))
2896 rcu_check_callbacks(cpu, user_ticks);
2899 vxi->sched.cpu[cpu].user_ticks += user_ticks;
2900 vxi->sched.cpu[cpu].sys_ticks += sys_ticks;
2903 /* note: this timer irq context must be accounted for as well */
2904 if (hardirq_count() - HARDIRQ_OFFSET) {
2905 cpustat->irq += sys_ticks;
2907 } else if (softirq_count()) {
2908 cpustat->softirq += sys_ticks;
2912 if (p == rq->idle) {
2913 if (atomic_read(&rq->nr_iowait) > 0)
2914 cpustat->iowait += sys_ticks;
2915 // vx_cpustat_acc(vxi, iowait, cpu, cpustat, sys_ticks);
2917 cpustat->idle += sys_ticks;
2918 // vx_cpustat_acc(vxi, idle, cpu, cpustat, sys_ticks);
2920 if (wake_priority_sleeper(rq))
2923 ckrm_sched_tick(jiffies,cpu,rq_ckrm_load(rq));
2925 #ifdef CONFIG_VSERVER_HARDCPU_IDLE
2926 if (!--rq->idle_tokens && !list_empty(&rq->hold_queue))
2929 rebalance_tick(cpu, rq, SCHED_IDLE);
2932 if (TASK_NICE(p) > 0)
2933 cpustat->nice += user_ticks;
2935 cpustat->user += user_ticks;
2936 cpustat->system += sys_ticks;
2938 /* Task might have expired already, but not scheduled off yet */
2939 if (p->array != rq_active(p,rq)) {
2940 set_tsk_need_resched(p);
2943 spin_lock(&rq->lock);
2945 * The task was running during this tick - update the
2946 * time slice counter. Note: we do not update a thread's
2947 * priority until it either goes to sleep or uses up its
2948 * timeslice. This makes it possible for interactive tasks
2949 * to use up their timeslices at their highest priority levels.
2953 * RR tasks need a special form of timeslice management.
2954 * FIFO tasks have no timeslices.
2956 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2957 p->time_slice = task_timeslice(p);
2958 p->first_time_slice = 0;
2959 set_tsk_need_resched(p);
2961 /* put it at the end of the queue: */
2962 dequeue_task(p, rq_active(p,rq));
2963 enqueue_task(p, rq_active(p,rq));
2967 #warning MEF: vx_need_resched incorpates standard kernel code, which it should not.
2968 if (vx_need_resched(p)) {
2969 #ifdef CONFIG_CKRM_CPU_SCHEDULE
2970 /* Hubertus ... we can abstract this out */
2971 ckrm_lrq_t* rq = get_task_lrq(p);
2973 dequeue_task(p, rq->active);
2974 set_tsk_need_resched(p);
2975 p->prio = effective_prio(p);
2976 p->time_slice = task_timeslice(p);
2977 p->first_time_slice = 0;
2979 if (!rq->expired_timestamp)
2980 rq->expired_timestamp = jiffies;
2981 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2982 enqueue_task(p, rq->expired);
2983 if (p->static_prio < this_rq()->best_expired_prio)
2984 this_rq()->best_expired_prio = p->static_prio;
2986 enqueue_task(p, rq->active);
2989 * Prevent a too long timeslice allowing a task to monopolize
2990 * the CPU. We do this by splitting up the timeslice into
2993 * Note: this does not mean the task's timeslices expire or
2994 * get lost in any way, they just might be preempted by
2995 * another task of equal priority. (one with higher
2996 * priority would have preempted this task already.) We
2997 * requeue this task to the end of the list on this priority
2998 * level, which is in essence a round-robin of tasks with
3001 * This only applies to tasks in the interactive
3002 * delta range with at least TIMESLICE_GRANULARITY to requeue.
3004 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
3005 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
3006 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
3007 (p->array == rq_active(p,rq))) {
3009 dequeue_task(p, rq_active(p,rq));
3010 set_tsk_need_resched(p);
3011 p->prio = effective_prio(p);
3012 enqueue_task(p, rq_active(p,rq));
3016 spin_unlock(&rq->lock);
3018 ckrm_sched_tick(jiffies,cpu,rq_ckrm_load(rq));
3019 rebalance_tick(cpu, rq, NOT_IDLE);
3022 #ifdef CONFIG_SCHED_SMT
3023 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
3025 struct sched_domain *sd = this_rq->sd;
3026 cpumask_t sibling_map;
3029 if (!(sd->flags & SD_SHARE_CPUPOWER))
3032 #ifdef CONFIG_CKRM_CPU_SCHEDULE
3033 if (prev != rq->idle) {
3034 unsigned long long run = now - prev->timestamp;
3035 ckrm_lrq_t * lrq = get_task_lrq(prev);
3037 lrq->lrq_load -= task_load(prev);
3038 cpu_demand_event(&prev->demand_stat,CPU_DEMAND_DESCHEDULE,run);
3039 lrq->lrq_load += task_load(prev);
3041 cpu_demand_event(get_task_lrq_stat(prev),CPU_DEMAND_DESCHEDULE,run);
3042 update_local_cvt(prev, run);
3046 * Unlock the current runqueue because we have to lock in
3047 * CPU order to avoid deadlocks. Caller knows that we might
3048 * unlock. We keep IRQs disabled.
3050 spin_unlock(&this_rq->lock);
3052 sibling_map = sd->span;
3054 for_each_cpu_mask(i, sibling_map)
3055 spin_lock(&cpu_rq(i)->lock);
3057 * We clear this CPU from the mask. This both simplifies the
3058 * inner loop and keps this_rq locked when we exit:
3060 cpu_clear(this_cpu, sibling_map);
3062 for_each_cpu_mask(i, sibling_map) {
3063 runqueue_t *smt_rq = cpu_rq(i);
3066 * If an SMT sibling task is sleeping due to priority
3067 * reasons wake it up now.
3069 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
3070 resched_task(smt_rq->idle);
3073 for_each_cpu_mask(i, sibling_map)
3074 spin_unlock(&cpu_rq(i)->lock);
3076 * We exit with this_cpu's rq still held and IRQs
3081 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
3083 struct sched_domain *sd = this_rq->sd;
3084 cpumask_t sibling_map;
3085 prio_array_t *array;
3089 if (!(sd->flags & SD_SHARE_CPUPOWER))
3093 * The same locking rules and details apply as for
3094 * wake_sleeping_dependent():
3096 spin_unlock(&this_rq->lock);
3097 sibling_map = sd->span;
3098 for_each_cpu_mask(i, sibling_map)
3099 spin_lock(&cpu_rq(i)->lock);
3100 cpu_clear(this_cpu, sibling_map);
3103 * Establish next task to be run - it might have gone away because
3104 * we released the runqueue lock above:
3106 if (!this_rq->nr_running)
3108 array = this_rq->active;
3109 if (!array->nr_active)
3110 array = this_rq->expired;
3111 BUG_ON(!array->nr_active);
3113 p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
3116 for_each_cpu_mask(i, sibling_map) {
3117 runqueue_t *smt_rq = cpu_rq(i);
3118 task_t *smt_curr = smt_rq->curr;
3121 * If a user task with lower static priority than the
3122 * running task on the SMT sibling is trying to schedule,
3123 * delay it till there is proportionately less timeslice
3124 * left of the sibling task to prevent a lower priority
3125 * task from using an unfair proportion of the
3126 * physical cpu's resources. -ck
3128 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
3129 task_timeslice(p) || rt_task(smt_curr)) &&
3130 p->mm && smt_curr->mm && !rt_task(p))
3134 * Reschedule a lower priority task on the SMT sibling,
3135 * or wake it up if it has been put to sleep for priority
3138 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
3139 task_timeslice(smt_curr) || rt_task(p)) &&
3140 smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
3141 (smt_curr == smt_rq->idle && smt_rq->nr_running))
3142 resched_task(smt_curr);
3145 for_each_cpu_mask(i, sibling_map)
3146 spin_unlock(&cpu_rq(i)->lock);
3150 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
3154 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
3161 * schedule() is the main scheduler function.
3163 asmlinkage void __sched schedule(void)
3166 task_t *prev, *next;
3168 prio_array_t *array;
3169 unsigned long long now;
3170 unsigned long run_time;
3171 #ifdef CONFIG_VSERVER_HARDCPU
3172 struct vx_info *vxi;
3178 * If crash dump is in progress, this other cpu's
3179 * need to wait until it completes.
3180 * NB: this code is optimized away for kernels without
3183 if (unlikely(dump_oncpu))
3184 goto dump_scheduling_disabled;
3187 * Test if we are atomic. Since do_exit() needs to call into
3188 * schedule() atomically, we ignore that path for now.
3189 * Otherwise, whine if we are scheduling when we should not be.
3191 if (likely(!(current->exit_state & (EXIT_DEAD | EXIT_ZOMBIE)))) {
3192 if (unlikely(in_atomic())) {
3193 printk(KERN_ERR "scheduling while atomic: "
3195 current->comm, preempt_count(), current->pid);
3199 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3204 release_kernel_lock(prev);
3205 need_resched_nonpreemptible:
3209 * The idle thread is not allowed to schedule!
3210 * Remove this check after it has been exercised a bit.
3212 if (unlikely(current == rq->idle) && current->state != TASK_RUNNING) {
3213 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
3217 schedstat_inc(rq, sched_cnt);
3218 now = sched_clock();
3219 if (likely(now - prev->timestamp < NS_MAX_SLEEP_AVG))
3220 run_time = now - prev->timestamp;
3222 run_time = NS_MAX_SLEEP_AVG;
3225 * Tasks with interactive credits get charged less run_time
3226 * at high sleep_avg to delay them losing their interactive
3229 if (HIGH_CREDIT(prev))
3230 run_time /= (CURRENT_BONUS(prev) ? : 1);
3232 spin_lock_irq(&rq->lock);
3234 #ifdef CONFIG_CKRM_CPU_SCHEDULE
3235 if (prev != rq->idle) {
3236 unsigned long long run = now - prev->timestamp;
3237 ckrm_lrq_t * lrq = get_task_lrq(prev);
3239 lrq->lrq_load -= task_load(prev);
3240 cpu_demand_event(&prev->demand_stat,CPU_DEMAND_DESCHEDULE,run);
3241 lrq->lrq_load += task_load(prev);
3243 cpu_demand_event(get_task_lrq_stat(prev),CPU_DEMAND_DESCHEDULE,run);
3244 update_local_cvt(prev, run);
3248 if (unlikely(current->flags & PF_DEAD))
3249 current->state = EXIT_DEAD;
3251 * if entering off of a kernel preemption go straight
3252 * to picking the next task.
3254 switch_count = &prev->nivcsw;
3255 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3256 switch_count = &prev->nvcsw;
3257 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
3258 unlikely(signal_pending(prev))))
3259 prev->state = TASK_RUNNING;
3261 if (prev->state == TASK_UNINTERRUPTIBLE) {
3262 rq->nr_uninterruptible++;
3263 vx_uninterruptible_inc(prev);
3265 deactivate_task(prev, rq);
3269 #ifdef CONFIG_VSERVER_HARDCPU
3270 if (!list_empty(&rq->hold_queue)) {
3271 struct list_head *l, *n;
3275 list_for_each_safe(l, n, &rq->hold_queue) {
3276 next = list_entry(l, task_t, run_list);
3277 if (vxi == next->vx_info)
3280 vxi = next->vx_info;
3281 ret = vx_tokens_recalc(vxi);
3282 // tokens = vx_tokens_avail(next);
3285 list_del(&next->run_list);
3286 next->state &= ~TASK_ONHOLD;
3289 array = rq->expired;
3290 next->prio = MAX_PRIO-1;
3291 enqueue_task(next, array);
3293 if (next->static_prio < rq->best_expired_prio)
3294 rq->best_expired_prio = next->static_prio;
3296 // printk("··· %8lu unhold %p [%d]\n", jiffies, next, next->prio);
3299 if ((ret < 0) && (maxidle < ret))
3303 rq->idle_tokens = -maxidle;
3308 cpu = smp_processor_id();
3309 if (unlikely(!rq->nr_running)) {
3311 idle_balance(cpu, rq);
3312 if (!rq->nr_running) {
3314 rq->expired_timestamp = 0;
3315 wake_sleeping_dependent(cpu, rq);
3317 * wake_sleeping_dependent() might have released
3318 * the runqueue, so break out if we got new
3321 if (!rq->nr_running)
3325 if (dependent_sleeper(cpu, rq)) {
3330 * dependent_sleeper() releases and reacquires the runqueue
3331 * lock, hence go into the idle loop if the rq went
3334 if (unlikely(!rq->nr_running))
3338 /* MEF: CKRM refactored code into rq_get_next_task(); make
3339 * sure that when upgrading changes are reflected into both
3340 * versions of the code.
3342 next = rq_get_next_task(rq);
3344 #ifdef CONFIG_VSERVER_HARDCPU
3345 vxi = next->vx_info;
3346 if (vx_info_flags(vxi, VXF_SCHED_PAUSE|VXF_SCHED_HARD, 0)) {
3347 int ret = vx_tokens_recalc(vxi);
3349 if (unlikely(ret <= 0)) {
3350 if (ret && (rq->idle_tokens > -ret))
3351 rq->idle_tokens = -ret;
3352 __deactivate_task(next, rq);
3353 recalc_task_prio(next, now);
3354 // a new one on hold
3356 next->state |= TASK_ONHOLD;
3357 list_add_tail(&next->run_list, &rq->hold_queue);
3358 //printk("··· %8lu hold %p [%d]\n", jiffies, next, next->prio);
3364 #ifdef CONFIG_VSERVER_HARDCPU
3365 vxi = next->vx_info;
3366 if (vx_info_flags(vxi, VXF_SCHED_PAUSE|VXF_SCHED_HARD, 0)) {
3367 int ret = vx_tokens_recalc(vxi);
3369 if (unlikely(ret <= 0)) {
3370 if (ret && (rq->idle_tokens > -ret))
3371 rq->idle_tokens = -ret;
3372 __deactivate_task(next, rq);
3373 recalc_task_prio(next, now);
3374 // a new one on hold
3376 next->state |= TASK_ONHOLD;
3377 list_add_tail(&next->run_list, &rq->hold_queue);
3378 //printk("··· %8lu hold %p [%d]\n", jiffies, next, next->prio);
3384 if (!rt_task(next) && next->activated > 0) {
3385 unsigned long long delta = now - next->timestamp;
3387 if (next->activated == 1)
3388 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
3390 array = next->array;
3391 dequeue_task(next, array);
3392 recalc_task_prio(next, next->timestamp + delta);
3393 enqueue_task(next, array);
3395 next->activated = 0;
3397 if (next == rq->idle)
3398 schedstat_inc(rq, sched_goidle);
3400 clear_tsk_need_resched(prev);
3401 rcu_qsctr_inc(task_cpu(prev));
3403 prev->sleep_avg -= run_time;
3404 if ((long)prev->sleep_avg <= 0) {
3405 prev->sleep_avg = 0;
3406 if (!(HIGH_CREDIT(prev) || LOW_CREDIT(prev)))
3407 prev->interactive_credit--;
3409 prev->timestamp = prev->last_ran = now;
3411 sched_info_switch(prev, next);
3412 if (likely(prev != next)) {
3413 next->timestamp = now;
3418 prepare_arch_switch(rq, next);
3419 prev = context_switch(rq, prev, next);
3422 finish_task_switch(prev);
3424 spin_unlock_irq(&rq->lock);
3427 if (unlikely(reacquire_kernel_lock(prev) < 0))
3428 goto need_resched_nonpreemptible;
3429 preempt_enable_no_resched();
3430 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3435 dump_scheduling_disabled:
3436 /* allow scheduling only if this is the dumping cpu */
3437 if (dump_oncpu != smp_processor_id()+1) {
3444 EXPORT_SYMBOL(schedule);
3445 #ifdef CONFIG_PREEMPT
3447 * this is is the entry point to schedule() from in-kernel preemption
3448 * off of preempt_enable. Kernel preemptions off return from interrupt
3449 * occur there and call schedule directly.
3451 asmlinkage void __sched preempt_schedule(void)
3453 struct thread_info *ti = current_thread_info();
3456 * If there is a non-zero preempt_count or interrupts are disabled,
3457 * we do not want to preempt the current task. Just return..
3459 if (unlikely(ti->preempt_count || irqs_disabled()))
3463 ti->preempt_count = PREEMPT_ACTIVE;
3465 ti->preempt_count = 0;
3467 /* we could miss a preemption opportunity between schedule and now */
3469 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3473 EXPORT_SYMBOL(preempt_schedule);
3474 #endif /* CONFIG_PREEMPT */
3476 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
3478 task_t *p = curr->task;
3479 return try_to_wake_up(p, mode, sync);
3482 EXPORT_SYMBOL(default_wake_function);
3485 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3486 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3487 * number) then we wake all the non-exclusive tasks and one exclusive task.
3489 * There are circumstances in which we can try to wake a task which has already
3490 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3491 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3493 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3494 int nr_exclusive, int sync, void *key)
3496 struct list_head *tmp, *next;
3498 list_for_each_safe(tmp, next, &q->task_list) {
3501 curr = list_entry(tmp, wait_queue_t, task_list);
3502 flags = curr->flags;
3503 if (curr->func(curr, mode, sync, key) &&
3504 (flags & WQ_FLAG_EXCLUSIVE) &&
3511 * __wake_up - wake up threads blocked on a waitqueue.
3513 * @mode: which threads
3514 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3516 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3517 int nr_exclusive, void *key)
3519 unsigned long flags;
3521 spin_lock_irqsave(&q->lock, flags);
3522 __wake_up_common(q, mode, nr_exclusive, 0, key);
3523 spin_unlock_irqrestore(&q->lock, flags);
3526 EXPORT_SYMBOL(__wake_up);
3529 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3531 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3533 __wake_up_common(q, mode, 1, 0, NULL);
3537 * __wake_up - sync- wake up threads blocked on a waitqueue.
3539 * @mode: which threads
3540 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3542 * The sync wakeup differs that the waker knows that it will schedule
3543 * away soon, so while the target thread will be woken up, it will not
3544 * be migrated to another CPU - ie. the two threads are 'synchronized'
3545 * with each other. This can prevent needless bouncing between CPUs.
3547 * On UP it can prevent extra preemption.
3549 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3551 unsigned long flags;
3557 if (unlikely(!nr_exclusive))
3560 spin_lock_irqsave(&q->lock, flags);
3561 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3562 spin_unlock_irqrestore(&q->lock, flags);
3564 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3566 void fastcall complete(struct completion *x)
3568 unsigned long flags;
3570 spin_lock_irqsave(&x->wait.lock, flags);
3572 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3574 spin_unlock_irqrestore(&x->wait.lock, flags);
3576 EXPORT_SYMBOL(complete);
3578 void fastcall complete_all(struct completion *x)
3580 unsigned long flags;
3582 spin_lock_irqsave(&x->wait.lock, flags);
3583 x->done += UINT_MAX/2;
3584 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3586 spin_unlock_irqrestore(&x->wait.lock, flags);
3588 EXPORT_SYMBOL(complete_all);
3590 void fastcall __sched wait_for_completion(struct completion *x)
3593 spin_lock_irq(&x->wait.lock);
3595 DECLARE_WAITQUEUE(wait, current);
3597 wait.flags |= WQ_FLAG_EXCLUSIVE;
3598 __add_wait_queue_tail(&x->wait, &wait);
3600 __set_current_state(TASK_UNINTERRUPTIBLE);
3601 spin_unlock_irq(&x->wait.lock);
3603 spin_lock_irq(&x->wait.lock);
3605 __remove_wait_queue(&x->wait, &wait);
3608 spin_unlock_irq(&x->wait.lock);
3610 EXPORT_SYMBOL(wait_for_completion);
3612 #define SLEEP_ON_VAR \
3613 unsigned long flags; \
3614 wait_queue_t wait; \
3615 init_waitqueue_entry(&wait, current);
3617 #define SLEEP_ON_HEAD \
3618 spin_lock_irqsave(&q->lock,flags); \
3619 __add_wait_queue(q, &wait); \
3620 spin_unlock(&q->lock);
3622 #define SLEEP_ON_TAIL \
3623 spin_lock_irq(&q->lock); \
3624 __remove_wait_queue(q, &wait); \
3625 spin_unlock_irqrestore(&q->lock, flags);
3627 #define SLEEP_ON_BKLCHECK \
3628 if (unlikely(!kernel_locked()) && \
3629 sleep_on_bkl_warnings < 10) { \
3630 sleep_on_bkl_warnings++; \
3634 static int sleep_on_bkl_warnings;
3636 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3642 current->state = TASK_INTERRUPTIBLE;
3649 EXPORT_SYMBOL(interruptible_sleep_on);
3651 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3657 current->state = TASK_INTERRUPTIBLE;
3660 timeout = schedule_timeout(timeout);
3666 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3668 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3674 current->state = TASK_UNINTERRUPTIBLE;
3677 timeout = schedule_timeout(timeout);
3683 EXPORT_SYMBOL(sleep_on_timeout);
3685 void set_user_nice(task_t *p, long nice)
3687 unsigned long flags;
3688 prio_array_t *array;
3690 int old_prio, new_prio, delta;
3692 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3695 * We have to be careful, if called from sys_setpriority(),
3696 * the task might be in the middle of scheduling on another CPU.
3698 rq = task_rq_lock(p, &flags);
3700 * The RT priorities are set via setscheduler(), but we still
3701 * allow the 'normal' nice value to be set - but as expected
3702 * it wont have any effect on scheduling until the task is
3706 p->static_prio = NICE_TO_PRIO(nice);
3711 dequeue_task(p, array);
3714 new_prio = NICE_TO_PRIO(nice);
3715 delta = new_prio - old_prio;
3716 p->static_prio = NICE_TO_PRIO(nice);
3720 enqueue_task(p, array);
3722 * If the task increased its priority or is running and
3723 * lowered its priority, then reschedule its CPU:
3725 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3726 resched_task(rq->curr);
3729 task_rq_unlock(rq, &flags);
3732 EXPORT_SYMBOL(set_user_nice);
3734 #ifdef __ARCH_WANT_SYS_NICE
3737 * sys_nice - change the priority of the current process.
3738 * @increment: priority increment
3740 * sys_setpriority is a more generic, but much slower function that
3741 * does similar things.
3743 asmlinkage long sys_nice(int increment)
3749 * Setpriority might change our priority at the same moment.
3750 * We don't have to worry. Conceptually one call occurs first
3751 * and we have a single winner.
3753 if (increment < 0) {
3754 if (vx_flags(VXF_IGNEG_NICE, 0))
3756 if (!capable(CAP_SYS_NICE))
3758 if (increment < -40)
3764 nice = PRIO_TO_NICE(current->static_prio) + increment;
3770 retval = security_task_setnice(current, nice);
3774 set_user_nice(current, nice);
3781 * task_prio - return the priority value of a given task.
3782 * @p: the task in question.
3784 * This is the priority value as seen by users in /proc.
3785 * RT tasks are offset by -200. Normal tasks are centered
3786 * around 0, value goes from -16 to +15.
3788 int task_prio(const task_t *p)
3790 return p->prio - MAX_RT_PRIO;
3794 * task_nice - return the nice value of a given task.
3795 * @p: the task in question.
3797 int task_nice(const task_t *p)
3799 return TASK_NICE(p);
3803 * idle_cpu - is a given cpu idle currently?
3804 * @cpu: the processor in question.
3806 int idle_cpu(int cpu)
3808 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3811 EXPORT_SYMBOL_GPL(idle_cpu);
3814 * find_process_by_pid - find a process with a matching PID value.
3815 * @pid: the pid in question.
3817 static inline task_t *find_process_by_pid(pid_t pid)
3819 return pid ? find_task_by_pid(pid) : current;
3822 /* Actually do priority change: must hold rq lock. */
3823 static void __setscheduler(struct task_struct *p, int policy, int prio)
3827 p->rt_priority = prio;
3828 if (policy != SCHED_NORMAL)
3829 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
3831 p->prio = p->static_prio;
3835 * setscheduler - change the scheduling policy and/or RT priority of a thread.
3837 static int setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3839 struct sched_param lp;
3840 int retval = -EINVAL;
3841 int oldprio, oldpolicy = -1;
3842 prio_array_t *array;
3843 unsigned long flags;
3847 if (!param || pid < 0)
3851 if (copy_from_user(&lp, param, sizeof(struct sched_param)))
3855 * We play safe to avoid deadlocks.
3857 read_lock_irq(&tasklist_lock);
3859 p = find_process_by_pid(pid);
3865 /* double check policy once rq lock held */
3867 policy = oldpolicy = p->policy;
3870 if (policy != SCHED_FIFO && policy != SCHED_RR &&
3871 policy != SCHED_NORMAL)
3875 * Valid priorities for SCHED_FIFO and SCHED_RR are
3876 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
3879 if (lp.sched_priority < 0 || lp.sched_priority > MAX_USER_RT_PRIO-1)
3881 if ((policy == SCHED_NORMAL) != (lp.sched_priority == 0))
3885 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
3886 !capable(CAP_SYS_NICE))
3888 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3889 !capable(CAP_SYS_NICE))
3892 retval = security_task_setscheduler(p, policy, &lp);
3896 * To be able to change p->policy safely, the apropriate
3897 * runqueue lock must be held.
3899 rq = task_rq_lock(p, &flags);
3900 /* recheck policy now with rq lock held */
3901 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3902 policy = oldpolicy = -1;
3903 task_rq_unlock(rq, &flags);
3908 deactivate_task(p, task_rq(p));
3911 __setscheduler(p, policy, lp.sched_priority);
3913 vx_activate_task(p);
3914 __activate_task(p, task_rq(p));
3916 * Reschedule if we are currently running on this runqueue and
3917 * our priority decreased, or if we are not currently running on
3918 * this runqueue and our priority is higher than the current's
3920 if (task_running(rq, p)) {
3921 if (p->prio > oldprio)
3922 resched_task(rq->curr);
3923 } else if (TASK_PREEMPTS_CURR(p, rq))
3924 resched_task(rq->curr);
3926 task_rq_unlock(rq, &flags);
3928 read_unlock_irq(&tasklist_lock);
3934 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3935 * @pid: the pid in question.
3936 * @policy: new policy
3937 * @param: structure containing the new RT priority.
3939 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3940 struct sched_param __user *param)
3942 return setscheduler(pid, policy, param);
3946 * sys_sched_setparam - set/change the RT priority of a thread
3947 * @pid: the pid in question.
3948 * @param: structure containing the new RT priority.
3950 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3952 return setscheduler(pid, -1, param);
3956 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3957 * @pid: the pid in question.
3959 asmlinkage long sys_sched_getscheduler(pid_t pid)
3961 int retval = -EINVAL;
3968 read_lock(&tasklist_lock);
3969 p = find_process_by_pid(pid);
3971 retval = security_task_getscheduler(p);
3975 read_unlock(&tasklist_lock);
3982 * sys_sched_getscheduler - get the RT priority of a thread
3983 * @pid: the pid in question.
3984 * @param: structure containing the RT priority.
3986 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3988 struct sched_param lp;
3989 int retval = -EINVAL;
3992 if (!param || pid < 0)
3995 read_lock(&tasklist_lock);
3996 p = find_process_by_pid(pid);
4001 retval = security_task_getscheduler(p);
4005 lp.sched_priority = p->rt_priority;
4006 read_unlock(&tasklist_lock);
4009 * This one might sleep, we cannot do it with a spinlock held ...
4011 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4017 read_unlock(&tasklist_lock);
4021 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
4027 read_lock(&tasklist_lock);
4029 p = find_process_by_pid(pid);
4031 read_unlock(&tasklist_lock);
4032 unlock_cpu_hotplug();
4037 * It is not safe to call set_cpus_allowed with the
4038 * tasklist_lock held. We will bump the task_struct's
4039 * usage count and then drop tasklist_lock.
4042 read_unlock(&tasklist_lock);
4045 if ((current->euid != p->euid) && (current->euid != p->uid) &&
4046 !capable(CAP_SYS_NICE))
4049 retval = set_cpus_allowed(p, new_mask);
4053 unlock_cpu_hotplug();
4057 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4058 cpumask_t *new_mask)
4060 if (len < sizeof(cpumask_t)) {
4061 memset(new_mask, 0, sizeof(cpumask_t));
4062 } else if (len > sizeof(cpumask_t)) {
4063 len = sizeof(cpumask_t);
4065 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4069 * sys_sched_setaffinity - set the cpu affinity of a process
4070 * @pid: pid of the process
4071 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4072 * @user_mask_ptr: user-space pointer to the new cpu mask
4074 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
4075 unsigned long __user *user_mask_ptr)
4080 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
4084 return sched_setaffinity(pid, new_mask);
4088 * Represents all cpu's present in the system
4089 * In systems capable of hotplug, this map could dynamically grow
4090 * as new cpu's are detected in the system via any platform specific
4091 * method, such as ACPI for e.g.
4094 cpumask_t cpu_present_map;
4095 EXPORT_SYMBOL(cpu_present_map);
4098 cpumask_t cpu_online_map = CPU_MASK_ALL;
4099 cpumask_t cpu_possible_map = CPU_MASK_ALL;
4102 long sched_getaffinity(pid_t pid, cpumask_t *mask)
4108 read_lock(&tasklist_lock);
4111 p = find_process_by_pid(pid);
4116 cpus_and(*mask, p->cpus_allowed, cpu_possible_map);
4119 read_unlock(&tasklist_lock);
4120 unlock_cpu_hotplug();
4128 * sys_sched_getaffinity - get the cpu affinity of a process
4129 * @pid: pid of the process
4130 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4131 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4133 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
4134 unsigned long __user *user_mask_ptr)
4139 if (len < sizeof(cpumask_t))
4142 ret = sched_getaffinity(pid, &mask);
4146 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
4149 return sizeof(cpumask_t);
4153 * sys_sched_yield - yield the current processor to other threads.
4155 * this function yields the current CPU by moving the calling thread
4156 * to the expired array. If there are no other threads running on this
4157 * CPU then this function will return.
4159 asmlinkage long sys_sched_yield(void)
4161 runqueue_t *rq = this_rq_lock();
4162 prio_array_t *array = current->array;
4163 prio_array_t *target = rq_expired(current,rq);
4165 schedstat_inc(rq, yld_cnt);
4167 * We implement yielding by moving the task into the expired
4170 * (special rule: RT tasks will just roundrobin in the active
4173 if (rt_task(current))
4174 target = rq_active(current,rq);
4176 #warning MEF need to fix up SCHEDSTATS code, but I hope this is fixed by the 2.6.10 CKRM patch
4177 #ifdef CONFIG_SCHEDSTATS
4178 if (current->array->nr_active == 1) {
4179 schedstat_inc(rq, yld_act_empty);
4180 if (!rq->expired->nr_active)
4181 schedstat_inc(rq, yld_both_empty);
4182 } else if (!rq->expired->nr_active)
4183 schedstat_inc(rq, yld_exp_empty);
4186 dequeue_task(current, array);
4187 enqueue_task(current, target);
4190 * Since we are going to call schedule() anyway, there's
4191 * no need to preempt or enable interrupts:
4193 __release(rq->lock);
4194 _raw_spin_unlock(&rq->lock);
4195 preempt_enable_no_resched();
4202 void __sched __cond_resched(void)
4204 set_current_state(TASK_RUNNING);
4208 EXPORT_SYMBOL(__cond_resched);
4211 * yield - yield the current processor to other threads.
4213 * this is a shortcut for kernel-space yielding - it marks the
4214 * thread runnable and calls sys_sched_yield().
4216 void __sched yield(void)
4218 set_current_state(TASK_RUNNING);
4222 EXPORT_SYMBOL(yield);
4225 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4226 * that process accounting knows that this is a task in IO wait state.
4228 * But don't do that if it is a deliberate, throttling IO wait (this task
4229 * has set its backing_dev_info: the queue against which it should throttle)
4231 void __sched io_schedule(void)
4233 struct runqueue *rq = this_rq();
4235 atomic_inc(&rq->nr_iowait);
4237 atomic_dec(&rq->nr_iowait);
4240 EXPORT_SYMBOL(io_schedule);
4242 long __sched io_schedule_timeout(long timeout)
4244 struct runqueue *rq = this_rq();
4247 atomic_inc(&rq->nr_iowait);
4248 ret = schedule_timeout(timeout);
4249 atomic_dec(&rq->nr_iowait);
4254 * sys_sched_get_priority_max - return maximum RT priority.
4255 * @policy: scheduling class.
4257 * this syscall returns the maximum rt_priority that can be used
4258 * by a given scheduling class.
4260 asmlinkage long sys_sched_get_priority_max(int policy)
4267 ret = MAX_USER_RT_PRIO-1;
4277 * sys_sched_get_priority_min - return minimum RT priority.
4278 * @policy: scheduling class.
4280 * this syscall returns the minimum rt_priority that can be used
4281 * by a given scheduling class.
4283 asmlinkage long sys_sched_get_priority_min(int policy)
4299 * sys_sched_rr_get_interval - return the default timeslice of a process.
4300 * @pid: pid of the process.
4301 * @interval: userspace pointer to the timeslice value.
4303 * this syscall writes the default timeslice value of a given process
4304 * into the user-space timespec buffer. A value of '0' means infinity.
4307 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4309 int retval = -EINVAL;
4317 read_lock(&tasklist_lock);
4318 p = find_process_by_pid(pid);
4322 retval = security_task_getscheduler(p);
4326 jiffies_to_timespec(p->policy & SCHED_FIFO ?
4327 0 : task_timeslice(p), &t);
4328 read_unlock(&tasklist_lock);
4329 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4333 read_unlock(&tasklist_lock);
4337 static inline struct task_struct *eldest_child(struct task_struct *p)
4339 if (list_empty(&p->children)) return NULL;
4340 return list_entry(p->children.next,struct task_struct,sibling);
4343 static inline struct task_struct *older_sibling(struct task_struct *p)
4345 if (p->sibling.prev==&p->parent->children) return NULL;
4346 return list_entry(p->sibling.prev,struct task_struct,sibling);
4349 static inline struct task_struct *younger_sibling(struct task_struct *p)
4351 if (p->sibling.next==&p->parent->children) return NULL;
4352 return list_entry(p->sibling.next,struct task_struct,sibling);
4355 static void show_task(task_t * p)
4359 unsigned long free = 0;
4360 static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
4362 printk("%-13.13s ", p->comm);
4363 state = p->state ? __ffs(p->state) + 1 : 0;
4364 if (state < ARRAY_SIZE(stat_nam))
4365 printk(stat_nam[state]);
4368 #if (BITS_PER_LONG == 32)
4369 if (state == TASK_RUNNING)
4370 printk(" running ");
4372 printk(" %08lX ", thread_saved_pc(p));
4374 if (state == TASK_RUNNING)
4375 printk(" running task ");
4377 printk(" %016lx ", thread_saved_pc(p));
4379 #ifdef CONFIG_DEBUG_STACK_USAGE
4381 unsigned long * n = (unsigned long *) (p->thread_info+1);
4384 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
4387 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
4388 if ((relative = eldest_child(p)))
4389 printk("%5d ", relative->pid);
4392 if ((relative = younger_sibling(p)))
4393 printk("%7d", relative->pid);
4396 if ((relative = older_sibling(p)))
4397 printk(" %5d", relative->pid);
4401 printk(" (L-TLB)\n");
4403 printk(" (NOTLB)\n");
4405 if (state != TASK_RUNNING)
4406 show_stack(p, NULL);
4409 void show_state(void)
4413 #if (BITS_PER_LONG == 32)
4416 printk(" task PC pid father child younger older\n");
4420 printk(" task PC pid father child younger older\n");
4422 read_lock(&tasklist_lock);
4423 do_each_thread(g, p) {
4425 * reset the NMI-timeout, listing all files on a slow
4426 * console might take alot of time:
4428 touch_nmi_watchdog();
4430 } while_each_thread(g, p);
4432 read_unlock(&tasklist_lock);
4435 EXPORT_SYMBOL_GPL(show_state);
4437 void __devinit init_idle(task_t *idle, int cpu)
4439 runqueue_t *rq = cpu_rq(cpu);
4440 unsigned long flags;
4442 idle->sleep_avg = 0;
4443 idle->interactive_credit = 0;
4445 idle->prio = MAX_PRIO;
4446 idle->state = TASK_RUNNING;
4447 set_task_cpu(idle, cpu);
4449 #ifdef CONFIG_CKRM_CPU_SCHEDULE
4450 cpu_demand_event(&(idle->demand_stat),CPU_DEMAND_INIT,0);
4451 idle->cpu_class = get_default_cpu_class();
4455 spin_lock_irqsave(&rq->lock, flags);
4456 rq->curr = rq->idle = idle;
4457 set_tsk_need_resched(idle);
4458 spin_unlock_irqrestore(&rq->lock, flags);
4460 /* Set the preempt count _outside_ the spinlocks! */
4461 #ifdef CONFIG_PREEMPT
4462 idle->thread_info->preempt_count = (idle->lock_depth >= 0);
4464 idle->thread_info->preempt_count = 0;
4469 * In a system that switches off the HZ timer nohz_cpu_mask
4470 * indicates which cpus entered this state. This is used
4471 * in the rcu update to wait only for active cpus. For system
4472 * which do not switch off the HZ timer nohz_cpu_mask should
4473 * always be CPU_MASK_NONE.
4475 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4479 * This is how migration works:
4481 * 1) we queue a migration_req_t structure in the source CPU's
4482 * runqueue and wake up that CPU's migration thread.
4483 * 2) we down() the locked semaphore => thread blocks.
4484 * 3) migration thread wakes up (implicitly it forces the migrated
4485 * thread off the CPU)
4486 * 4) it gets the migration request and checks whether the migrated
4487 * task is still in the wrong runqueue.
4488 * 5) if it's in the wrong runqueue then the migration thread removes
4489 * it and puts it into the right queue.
4490 * 6) migration thread up()s the semaphore.
4491 * 7) we wake up and the migration is done.
4495 * Change a given task's CPU affinity. Migrate the thread to a
4496 * proper CPU and schedule it away if the CPU it's executing on
4497 * is removed from the allowed bitmask.
4499 * NOTE: the caller must have a valid reference to the task, the
4500 * task must not exit() & deallocate itself prematurely. The
4501 * call is not atomic; no spinlocks may be held.
4503 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
4505 unsigned long flags;
4507 migration_req_t req;
4510 rq = task_rq_lock(p, &flags);
4511 if (!cpus_intersects(new_mask, cpu_online_map)) {
4516 p->cpus_allowed = new_mask;
4517 /* Can the task run on the task's current CPU? If so, we're done */
4518 if (cpu_isset(task_cpu(p), new_mask))
4521 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4522 /* Need help from migration thread: drop lock and wait. */
4523 task_rq_unlock(rq, &flags);
4524 wake_up_process(rq->migration_thread);
4525 wait_for_completion(&req.done);
4526 tlb_migrate_finish(p->mm);
4530 task_rq_unlock(rq, &flags);
4534 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4537 * Move (not current) task off this cpu, onto dest cpu. We're doing
4538 * this because either it can't run here any more (set_cpus_allowed()
4539 * away from this CPU, or CPU going down), or because we're
4540 * attempting to rebalance this task on exec (sched_exec).
4542 * So we race with normal scheduler movements, but that's OK, as long
4543 * as the task is no longer on this CPU.
4545 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4547 runqueue_t *rq_dest, *rq_src;
4549 if (unlikely(cpu_is_offline(dest_cpu)))
4552 rq_src = cpu_rq(src_cpu);
4553 rq_dest = cpu_rq(dest_cpu);
4555 double_rq_lock(rq_src, rq_dest);
4556 /* Already moved. */
4557 if (task_cpu(p) != src_cpu)
4559 /* Affinity changed (again). */
4560 if (!cpu_isset(dest_cpu, p->cpus_allowed))
4565 * Sync timestamp with rq_dest's before activating.
4566 * The same thing could be achieved by doing this step
4567 * afterwards, and pretending it was a local activate.
4568 * This way is cleaner and logically correct.
4570 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4571 + rq_dest->timestamp_last_tick;
4572 deactivate_task(p, rq_src);
4573 set_task_cpu(p, dest_cpu);
4574 activate_task(p, rq_dest, 0);
4575 if (TASK_PREEMPTS_CURR(p, rq_dest))
4576 resched_task(rq_dest->curr);
4578 set_task_cpu(p, dest_cpu);
4581 double_rq_unlock(rq_src, rq_dest);
4585 * migration_thread - this is a highprio system thread that performs
4586 * thread migration by bumping thread off CPU then 'pushing' onto
4589 static int migration_thread(void * data)
4592 int cpu = (long)data;
4595 BUG_ON(rq->migration_thread != current);
4597 set_current_state(TASK_INTERRUPTIBLE);
4598 while (!kthread_should_stop()) {
4599 struct list_head *head;
4600 migration_req_t *req;
4602 if (current->flags & PF_FREEZE)
4603 refrigerator(PF_FREEZE);
4605 spin_lock_irq(&rq->lock);
4607 if (cpu_is_offline(cpu)) {
4608 spin_unlock_irq(&rq->lock);
4612 if (rq->active_balance) {
4613 active_load_balance(rq, cpu);
4614 rq->active_balance = 0;
4617 head = &rq->migration_queue;
4619 if (list_empty(head)) {
4620 spin_unlock_irq(&rq->lock);
4622 set_current_state(TASK_INTERRUPTIBLE);
4625 req = list_entry(head->next, migration_req_t, list);
4626 list_del_init(head->next);
4628 if (req->type == REQ_MOVE_TASK) {
4629 spin_unlock(&rq->lock);
4630 __migrate_task(req->task, smp_processor_id(),
4633 } else if (req->type == REQ_SET_DOMAIN) {
4635 spin_unlock_irq(&rq->lock);
4637 spin_unlock_irq(&rq->lock);
4641 complete(&req->done);
4643 __set_current_state(TASK_RUNNING);
4647 /* Wait for kthread_stop */
4648 set_current_state(TASK_INTERRUPTIBLE);
4649 while (!kthread_should_stop()) {
4651 set_current_state(TASK_INTERRUPTIBLE);
4653 __set_current_state(TASK_RUNNING);
4657 #ifdef CONFIG_HOTPLUG_CPU
4658 /* Figure out where task on dead CPU should go, use force if neccessary. */
4659 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
4665 mask = node_to_cpumask(cpu_to_node(dead_cpu));
4666 cpus_and(mask, mask, tsk->cpus_allowed);
4667 dest_cpu = any_online_cpu(mask);
4669 /* On any allowed CPU? */
4670 if (dest_cpu == NR_CPUS)
4671 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4673 /* No more Mr. Nice Guy. */
4674 if (dest_cpu == NR_CPUS) {
4675 cpus_setall(tsk->cpus_allowed);
4676 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4679 * Don't tell them about moving exiting tasks or
4680 * kernel threads (both mm NULL), since they never
4683 if (tsk->mm && printk_ratelimit())
4684 printk(KERN_INFO "process %d (%s) no "
4685 "longer affine to cpu%d\n",
4686 tsk->pid, tsk->comm, dead_cpu);
4688 __migrate_task(tsk, dead_cpu, dest_cpu);
4692 * While a dead CPU has no uninterruptible tasks queued at this point,
4693 * it might still have a nonzero ->nr_uninterruptible counter, because
4694 * for performance reasons the counter is not stricly tracking tasks to
4695 * their home CPUs. So we just add the counter to another CPU's counter,
4696 * to keep the global sum constant after CPU-down:
4698 static void migrate_nr_uninterruptible(runqueue_t *rq_src)
4700 runqueue_t *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
4701 unsigned long flags;
4703 local_irq_save(flags);
4704 double_rq_lock(rq_src, rq_dest);
4705 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
4706 rq_src->nr_uninterruptible = 0;
4707 double_rq_unlock(rq_src, rq_dest);
4708 local_irq_restore(flags);
4711 /* Run through task list and migrate tasks from the dead cpu. */
4712 static void migrate_live_tasks(int src_cpu)
4714 struct task_struct *tsk, *t;
4716 write_lock_irq(&tasklist_lock);
4718 do_each_thread(t, tsk) {
4722 if (task_cpu(tsk) == src_cpu)
4723 move_task_off_dead_cpu(src_cpu, tsk);
4724 } while_each_thread(t, tsk);
4726 write_unlock_irq(&tasklist_lock);
4729 /* Schedules idle task to be the next runnable task on current CPU.
4730 * It does so by boosting its priority to highest possible and adding it to
4731 * the _front_ of runqueue. Used by CPU offline code.
4733 void sched_idle_next(void)
4735 int cpu = smp_processor_id();
4736 runqueue_t *rq = this_rq();
4737 struct task_struct *p = rq->idle;
4738 unsigned long flags;
4740 /* cpu has to be offline */
4741 BUG_ON(cpu_online(cpu));
4743 /* Strictly not necessary since rest of the CPUs are stopped by now
4744 * and interrupts disabled on current cpu.
4746 spin_lock_irqsave(&rq->lock, flags);
4748 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4749 /* Add idle task to _front_ of it's priority queue */
4750 __activate_idle_task(p, rq);
4752 spin_unlock_irqrestore(&rq->lock, flags);
4755 static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
4757 struct runqueue *rq = cpu_rq(dead_cpu);
4759 /* Must be exiting, otherwise would be on tasklist. */
4760 BUG_ON(tsk->exit_state != EXIT_ZOMBIE && tsk->exit_state != EXIT_DEAD);
4762 /* Cannot have done final schedule yet: would have vanished. */
4763 BUG_ON(tsk->flags & PF_DEAD);
4765 get_task_struct(tsk);
4768 * Drop lock around migration; if someone else moves it,
4769 * that's OK. No task can be added to this CPU, so iteration is
4772 spin_unlock_irq(&rq->lock);
4773 move_task_off_dead_cpu(dead_cpu, tsk);
4774 spin_lock_irq(&rq->lock);
4776 put_task_struct(tsk);
4779 /* release_task() removes task from tasklist, so we won't find dead tasks. */
4780 static void migrate_dead_tasks(unsigned int dead_cpu)
4783 struct runqueue *rq = cpu_rq(dead_cpu);
4785 for (arr = 0; arr < 2; arr++) {
4786 for (i = 0; i < MAX_PRIO; i++) {
4787 struct list_head *list = &rq->arrays[arr].queue[i];
4788 while (!list_empty(list))
4789 migrate_dead(dead_cpu,
4790 list_entry(list->next, task_t,
4795 #endif /* CONFIG_HOTPLUG_CPU */
4798 * migration_call - callback that gets triggered when a CPU is added.
4799 * Here we can start up the necessary migration thread for the new CPU.
4801 static int migration_call(struct notifier_block *nfb, unsigned long action,
4804 int cpu = (long)hcpu;
4805 struct task_struct *p;
4806 struct runqueue *rq;
4807 unsigned long flags;
4810 case CPU_UP_PREPARE:
4811 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4814 p->flags |= PF_NOFREEZE;
4815 kthread_bind(p, cpu);
4816 /* Must be high prio: stop_machine expects to yield to it. */
4817 rq = task_rq_lock(p, &flags);
4818 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4819 task_rq_unlock(rq, &flags);
4820 cpu_rq(cpu)->migration_thread = p;
4823 /* Strictly unneccessary, as first user will wake it. */
4824 wake_up_process(cpu_rq(cpu)->migration_thread);
4826 #ifdef CONFIG_HOTPLUG_CPU
4827 case CPU_UP_CANCELED:
4828 /* Unbind it from offline cpu so it can run. Fall thru. */
4829 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
4830 kthread_stop(cpu_rq(cpu)->migration_thread);
4831 cpu_rq(cpu)->migration_thread = NULL;
4834 migrate_live_tasks(cpu);
4836 kthread_stop(rq->migration_thread);
4837 rq->migration_thread = NULL;
4838 /* Idle task back to normal (off runqueue, low prio) */
4839 rq = task_rq_lock(rq->idle, &flags);
4840 deactivate_task(rq->idle, rq);
4841 rq->idle->static_prio = MAX_PRIO;
4842 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4843 migrate_dead_tasks(cpu);
4844 task_rq_unlock(rq, &flags);
4845 migrate_nr_uninterruptible(rq);
4846 BUG_ON(rq->nr_running != 0);
4848 /* No need to migrate the tasks: it was best-effort if
4849 * they didn't do lock_cpu_hotplug(). Just wake up
4850 * the requestors. */
4851 spin_lock_irq(&rq->lock);
4852 while (!list_empty(&rq->migration_queue)) {
4853 migration_req_t *req;
4854 req = list_entry(rq->migration_queue.next,
4855 migration_req_t, list);
4856 BUG_ON(req->type != REQ_MOVE_TASK);
4857 list_del_init(&req->list);
4858 complete(&req->done);
4860 spin_unlock_irq(&rq->lock);
4867 /* Register at highest priority so that task migration (migrate_all_tasks)
4868 * happens before everything else.
4870 static struct notifier_block __devinitdata migration_notifier = {
4871 .notifier_call = migration_call,
4875 int __init migration_init(void)
4877 void *cpu = (void *)(long)smp_processor_id();
4878 /* Start one for boot CPU. */
4879 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4880 migration_call(&migration_notifier, CPU_ONLINE, cpu);
4881 register_cpu_notifier(&migration_notifier);
4888 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
4889 * hold the hotplug lock.
4891 void __devinit cpu_attach_domain(struct sched_domain *sd, int cpu)
4893 migration_req_t req;
4894 unsigned long flags;
4895 runqueue_t *rq = cpu_rq(cpu);
4898 spin_lock_irqsave(&rq->lock, flags);
4900 if (cpu == smp_processor_id() || !cpu_online(cpu)) {
4903 init_completion(&req.done);
4904 req.type = REQ_SET_DOMAIN;
4906 list_add(&req.list, &rq->migration_queue);
4910 spin_unlock_irqrestore(&rq->lock, flags);
4913 wake_up_process(rq->migration_thread);
4914 wait_for_completion(&req.done);
4918 /* cpus with isolated domains */
4919 cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
4921 /* Setup the mask of cpus configured for isolated domains */
4922 static int __init isolated_cpu_setup(char *str)
4924 int ints[NR_CPUS], i;
4926 str = get_options(str, ARRAY_SIZE(ints), ints);
4927 cpus_clear(cpu_isolated_map);
4928 for (i = 1; i <= ints[0]; i++)
4929 cpu_set(ints[i], cpu_isolated_map);
4933 __setup ("isolcpus=", isolated_cpu_setup);
4936 * init_sched_build_groups takes an array of groups, the cpumask we wish
4937 * to span, and a pointer to a function which identifies what group a CPU
4938 * belongs to. The return value of group_fn must be a valid index into the
4939 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
4940 * keep track of groups covered with a cpumask_t).
4942 * init_sched_build_groups will build a circular linked list of the groups
4943 * covered by the given span, and will set each group's ->cpumask correctly,
4944 * and ->cpu_power to 0.
4946 void __devinit init_sched_build_groups(struct sched_group groups[],
4947 cpumask_t span, int (*group_fn)(int cpu))
4949 struct sched_group *first = NULL, *last = NULL;
4950 cpumask_t covered = CPU_MASK_NONE;
4953 for_each_cpu_mask(i, span) {
4954 int group = group_fn(i);
4955 struct sched_group *sg = &groups[group];
4958 if (cpu_isset(i, covered))
4961 sg->cpumask = CPU_MASK_NONE;
4964 for_each_cpu_mask(j, span) {
4965 if (group_fn(j) != group)
4968 cpu_set(j, covered);
4969 cpu_set(j, sg->cpumask);
4981 #ifdef ARCH_HAS_SCHED_DOMAIN
4982 extern void __devinit arch_init_sched_domains(void);
4983 extern void __devinit arch_destroy_sched_domains(void);
4985 #ifdef CONFIG_SCHED_SMT
4986 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
4987 static struct sched_group sched_group_cpus[NR_CPUS];
4988 static int __devinit cpu_to_cpu_group(int cpu)
4994 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
4995 static struct sched_group sched_group_phys[NR_CPUS];
4996 static int __devinit cpu_to_phys_group(int cpu)
4998 #ifdef CONFIG_SCHED_SMT
4999 return first_cpu(cpu_sibling_map[cpu]);
5007 static DEFINE_PER_CPU(struct sched_domain, node_domains);
5008 static struct sched_group sched_group_nodes[MAX_NUMNODES];
5009 static int __devinit cpu_to_node_group(int cpu)
5011 return cpu_to_node(cpu);
5015 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
5017 * The domains setup code relies on siblings not spanning
5018 * multiple nodes. Make sure the architecture has a proper
5021 static void check_sibling_maps(void)
5025 for_each_online_cpu(i) {
5026 for_each_cpu_mask(j, cpu_sibling_map[i]) {
5027 if (cpu_to_node(i) != cpu_to_node(j)) {
5028 printk(KERN_INFO "warning: CPU %d siblings map "
5029 "to different node - isolating "
5031 cpu_sibling_map[i] = cpumask_of_cpu(i);
5040 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
5042 static void __devinit arch_init_sched_domains(void)
5045 cpumask_t cpu_default_map;
5047 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
5048 check_sibling_maps();
5051 * Setup mask for cpus without special case scheduling requirements.
5052 * For now this just excludes isolated cpus, but could be used to
5053 * exclude other special cases in the future.
5055 cpus_complement(cpu_default_map, cpu_isolated_map);
5056 cpus_and(cpu_default_map, cpu_default_map, cpu_online_map);
5059 * Set up domains. Isolated domains just stay on the dummy domain.
5061 for_each_cpu_mask(i, cpu_default_map) {
5063 struct sched_domain *sd = NULL, *p;
5064 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
5066 cpus_and(nodemask, nodemask, cpu_default_map);
5069 sd = &per_cpu(node_domains, i);
5070 group = cpu_to_node_group(i);
5072 sd->span = cpu_default_map;
5073 sd->groups = &sched_group_nodes[group];
5077 sd = &per_cpu(phys_domains, i);
5078 group = cpu_to_phys_group(i);
5080 sd->span = nodemask;
5082 sd->groups = &sched_group_phys[group];
5084 #ifdef CONFIG_SCHED_SMT
5086 sd = &per_cpu(cpu_domains, i);
5087 group = cpu_to_cpu_group(i);
5088 *sd = SD_SIBLING_INIT;
5089 sd->span = cpu_sibling_map[i];
5090 cpus_and(sd->span, sd->span, cpu_default_map);
5092 sd->groups = &sched_group_cpus[group];
5096 #ifdef CONFIG_SCHED_SMT
5097 /* Set up CPU (sibling) groups */
5098 for_each_online_cpu(i) {
5099 cpumask_t this_sibling_map = cpu_sibling_map[i];
5100 cpus_and(this_sibling_map, this_sibling_map, cpu_default_map);
5101 if (i != first_cpu(this_sibling_map))
5104 init_sched_build_groups(sched_group_cpus, this_sibling_map,
5109 /* Set up physical groups */
5110 for (i = 0; i < MAX_NUMNODES; i++) {
5111 cpumask_t nodemask = node_to_cpumask(i);
5113 cpus_and(nodemask, nodemask, cpu_default_map);
5114 if (cpus_empty(nodemask))
5117 init_sched_build_groups(sched_group_phys, nodemask,
5118 &cpu_to_phys_group);
5123 /* Set up node groups */
5124 init_sched_build_groups(sched_group_nodes, cpu_default_map,
5125 &cpu_to_node_group);
5129 /* Calculate CPU power for physical packages and nodes */
5130 for_each_cpu_mask(i, cpu_default_map) {
5132 struct sched_domain *sd;
5133 #ifdef CONFIG_SCHED_SMT
5134 sd = &per_cpu(cpu_domains, i);
5135 power = SCHED_LOAD_SCALE;
5136 sd->groups->cpu_power = power;
5139 sd = &per_cpu(phys_domains, i);
5140 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
5141 (cpus_weight(sd->groups->cpumask)-1) / 10;
5142 sd->groups->cpu_power = power;
5146 if (i == first_cpu(sd->groups->cpumask)) {
5147 /* Only add "power" once for each physical package. */
5148 sd = &per_cpu(node_domains, i);
5149 sd->groups->cpu_power += power;
5154 /* Attach the domains */
5155 for_each_online_cpu(i) {
5156 struct sched_domain *sd;
5157 #ifdef CONFIG_SCHED_SMT
5158 sd = &per_cpu(cpu_domains, i);
5160 sd = &per_cpu(phys_domains, i);
5162 cpu_attach_domain(sd, i);
5167 #ifdef CONFIG_HOTPLUG_CPU
5168 static void __devinit arch_destroy_sched_domains(void)
5170 /* Do nothing: everything is statically allocated. */
5174 #endif /* ARCH_HAS_SCHED_DOMAIN */
5176 #define SCHED_DOMAIN_DEBUG
5177 #ifdef SCHED_DOMAIN_DEBUG
5178 static void sched_domain_debug(void)
5182 for_each_online_cpu(i) {
5183 runqueue_t *rq = cpu_rq(i);
5184 struct sched_domain *sd;
5189 printk(KERN_DEBUG "CPU%d:\n", i);
5194 struct sched_group *group = sd->groups;
5195 cpumask_t groupmask;
5197 cpumask_scnprintf(str, NR_CPUS, sd->span);
5198 cpus_clear(groupmask);
5201 for (j = 0; j < level + 1; j++)
5203 printk("domain %d: ", level);
5205 if (!(sd->flags & SD_LOAD_BALANCE)) {
5206 printk("does not load-balance");
5208 printk(" ERROR !SD_LOAD_BALANCE domain has parent");
5213 printk("span %s\n", str);
5215 if (!cpu_isset(i, sd->span))
5216 printk(KERN_DEBUG "ERROR domain->span does not contain CPU%d\n", i);
5217 if (!cpu_isset(i, group->cpumask))
5218 printk(KERN_DEBUG "ERROR domain->groups does not contain CPU%d\n", i);
5221 for (j = 0; j < level + 2; j++)
5226 printk(" ERROR: NULL");
5230 if (!group->cpu_power)
5231 printk(KERN_DEBUG "ERROR group->cpu_power not set\n");
5233 if (!cpus_weight(group->cpumask))
5234 printk(" ERROR empty group:");
5236 if (cpus_intersects(groupmask, group->cpumask))
5237 printk(" ERROR repeated CPUs:");
5239 cpus_or(groupmask, groupmask, group->cpumask);
5241 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
5244 group = group->next;
5245 } while (group != sd->groups);
5248 if (!cpus_equal(sd->span, groupmask))
5249 printk(KERN_DEBUG "ERROR groups don't span domain->span\n");
5255 if (!cpus_subset(groupmask, sd->span))
5256 printk(KERN_DEBUG "ERROR parent span is not a superset of domain->span\n");
5263 #define sched_domain_debug() {}
5267 * Initial dummy domain for early boot and for hotplug cpu. Being static,
5268 * it is initialized to zero, so all balancing flags are cleared which is
5271 static struct sched_domain sched_domain_dummy;
5273 #ifdef CONFIG_HOTPLUG_CPU
5275 * Force a reinitialization of the sched domains hierarchy. The domains
5276 * and groups cannot be updated in place without racing with the balancing
5277 * code, so we temporarily attach all running cpus to a "dummy" domain
5278 * which will prevent rebalancing while the sched domains are recalculated.
5280 static int update_sched_domains(struct notifier_block *nfb,
5281 unsigned long action, void *hcpu)
5286 case CPU_UP_PREPARE:
5287 case CPU_DOWN_PREPARE:
5288 for_each_online_cpu(i)
5289 cpu_attach_domain(&sched_domain_dummy, i);
5290 arch_destroy_sched_domains();
5293 case CPU_UP_CANCELED:
5294 case CPU_DOWN_FAILED:
5298 * Fall through and re-initialise the domains.
5305 /* The hotplug lock is already held by cpu_up/cpu_down */
5306 arch_init_sched_domains();
5308 sched_domain_debug();
5314 void __init sched_init_smp(void)
5317 arch_init_sched_domains();
5318 sched_domain_debug();
5319 unlock_cpu_hotplug();
5320 /* XXX: Theoretical race here - CPU may be hotplugged now */
5321 hotcpu_notifier(update_sched_domains, 0);
5324 void __init sched_init_smp(void)
5327 #endif /* CONFIG_SMP */
5329 int in_sched_functions(unsigned long addr)
5331 /* Linker adds these: start and end of __sched functions */
5332 extern char __sched_text_start[], __sched_text_end[];
5333 return in_lock_functions(addr) ||
5334 (addr >= (unsigned long)__sched_text_start
5335 && addr < (unsigned long)__sched_text_end);
5338 void __init sched_init(void)
5345 for (i = 0; i < NR_CPUS; i++) {
5346 #ifndef CONFIG_CKRM_CPU_SCHEDULE
5348 prio_array_t *array;
5351 spin_lock_init(&rq->lock);
5353 for (j = 0; j < 2; j++) {
5354 array = rq->arrays + j;
5355 for (k = 0; k < MAX_PRIO; k++) {
5356 INIT_LIST_HEAD(array->queue + k);
5357 __clear_bit(k, array->bitmap);
5359 // delimiter for bitsearch
5360 __set_bit(MAX_PRIO, array->bitmap);
5363 rq->active = rq->arrays;
5364 rq->expired = rq->arrays + 1;
5365 rq->best_expired_prio = MAX_PRIO;
5369 spin_lock_init(&rq->lock);
5373 rq->sd = &sched_domain_dummy;
5375 #ifdef CONFIG_CKRM_CPU_SCHEDULE
5376 ckrm_load_init(rq_ckrm_load(rq));
5378 rq->active_balance = 0;
5380 rq->migration_thread = NULL;
5381 INIT_LIST_HEAD(&rq->migration_queue);
5383 #ifdef CONFIG_VSERVER_HARDCPU
5384 INIT_LIST_HEAD(&rq->hold_queue);
5386 atomic_set(&rq->nr_iowait, 0);
5391 * The boot idle thread does lazy MMU switching as well:
5393 atomic_inc(&init_mm.mm_count);
5394 enter_lazy_tlb(&init_mm, current);
5397 * Make us the idle thread. Technically, schedule() should not be
5398 * called from this thread, however somewhere below it might be,
5399 * but because we are the idle thread, we just pick up running again
5400 * when this runqueue becomes "idle".
5402 init_idle(current, smp_processor_id());
5405 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5406 void __might_sleep(char *file, int line)
5408 #if defined(in_atomic)
5409 static unsigned long prev_jiffy; /* ratelimiting */
5411 if ((in_atomic() || irqs_disabled()) &&
5412 system_state == SYSTEM_RUNNING) {
5413 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
5415 prev_jiffy = jiffies;
5416 printk(KERN_ERR "Debug: sleeping function called from invalid"
5417 " context at %s:%d\n", file, line);
5418 printk("in_atomic():%d, irqs_disabled():%d\n",
5419 in_atomic(), irqs_disabled());
5424 EXPORT_SYMBOL(__might_sleep);
5427 #ifdef CONFIG_CKRM_CPU_SCHEDULE
5429 * return the classqueue object of a certain processor
5431 struct classqueue_struct * get_cpu_classqueue(int cpu)
5433 return (& (cpu_rq(cpu)->classqueue) );
5437 * _ckrm_cpu_change_class - change the class of a task
5439 void _ckrm_cpu_change_class(task_t *tsk, struct ckrm_cpu_class *newcls)
5441 prio_array_t *array;
5442 struct runqueue *rq;
5443 unsigned long flags;
5445 rq = task_rq_lock(tsk,&flags);
5448 dequeue_task(tsk,array);
5449 tsk->cpu_class = newcls;
5450 enqueue_task(tsk,rq_active(tsk,rq));
5452 tsk->cpu_class = newcls;
5454 task_rq_unlock(rq,&flags);
5458 #ifdef CONFIG_MAGIC_SYSRQ
5459 void normalize_rt_tasks(void)
5461 struct task_struct *p;
5462 prio_array_t *array;
5463 unsigned long flags;
5466 read_lock_irq(&tasklist_lock);
5467 for_each_process (p) {
5471 rq = task_rq_lock(p, &flags);
5475 deactivate_task(p, task_rq(p));
5476 __setscheduler(p, SCHED_NORMAL, 0);
5478 __activate_task(p, task_rq(p));
5479 resched_task(rq->curr);
5482 task_rq_unlock(rq, &flags);
5484 read_unlock_irq(&tasklist_lock);
5487 #endif /* CONFIG_MAGIC_SYSRQ */