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
22 #include <linux/module.h>
23 #include <linux/nmi.h>
24 #include <linux/init.h>
25 #include <asm/uaccess.h>
26 #include <linux/highmem.h>
27 #include <linux/smp_lock.h>
28 #include <asm/mmu_context.h>
29 #include <linux/interrupt.h>
30 #include <linux/completion.h>
31 #include <linux/kernel_stat.h>
32 #include <linux/security.h>
33 #include <linux/notifier.h>
34 #include <linux/profile.h>
35 #include <linux/suspend.h>
36 #include <linux/blkdev.h>
37 #include <linux/delay.h>
38 #include <linux/smp.h>
39 #include <linux/timer.h>
40 #include <linux/rcupdate.h>
41 #include <linux/cpu.h>
42 #include <linux/percpu.h>
43 #include <linux/kthread.h>
44 #include <linux/seq_file.h>
45 #include <linux/times.h>
48 #include <asm/unistd.h>
51 #define cpu_to_node_mask(cpu) node_to_cpumask(cpu_to_node(cpu))
53 #define cpu_to_node_mask(cpu) (cpu_online_map)
57 * Convert user-nice values [ -20 ... 0 ... 19 ]
58 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
61 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
62 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
63 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
66 * 'User priority' is the nice value converted to something we
67 * can work with better when scaling various scheduler parameters,
68 * it's a [ 0 ... 39 ] range.
70 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
71 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
72 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
75 * Some helpers for converting nanosecond timing to jiffy resolution
77 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
78 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
81 * These are the 'tuning knobs' of the scheduler:
83 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
84 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
85 * Timeslices get refilled after they expire.
87 #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
88 #define DEF_TIMESLICE (100 * HZ / 1000)
89 #define ON_RUNQUEUE_WEIGHT 30
90 #define CHILD_PENALTY 95
91 #define PARENT_PENALTY 100
93 #define PRIO_BONUS_RATIO 25
94 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
95 #define INTERACTIVE_DELTA 2
96 #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
97 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
98 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
99 #define CREDIT_LIMIT 100
102 * If a task is 'interactive' then we reinsert it in the active
103 * array after it has expired its current timeslice. (it will not
104 * continue to run immediately, it will still roundrobin with
105 * other interactive tasks.)
107 * This part scales the interactivity limit depending on niceness.
109 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
110 * Here are a few examples of different nice levels:
112 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
113 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
114 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
115 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
116 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
118 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
119 * priority range a task can explore, a value of '1' means the
120 * task is rated interactive.)
122 * Ie. nice +19 tasks can never get 'interactive' enough to be
123 * reinserted into the active array. And only heavily CPU-hog nice -20
124 * tasks will be expired. Default nice 0 tasks are somewhere between,
125 * it takes some effort for them to get interactive, but it's not
129 #define CURRENT_BONUS(p) \
130 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
134 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
135 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
138 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
139 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
142 #define SCALE(v1,v1_max,v2_max) \
143 (v1) * (v2_max) / (v1_max)
146 (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
148 #define TASK_INTERACTIVE(p) \
149 ((p)->prio <= (p)->static_prio - DELTA(p))
151 #define INTERACTIVE_SLEEP(p) \
152 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
153 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
155 #define HIGH_CREDIT(p) \
156 ((p)->interactive_credit > CREDIT_LIMIT)
158 #define LOW_CREDIT(p) \
159 ((p)->interactive_credit < -CREDIT_LIMIT)
161 #define TASK_PREEMPTS_CURR(p, rq) \
162 ((p)->prio < (rq)->curr->prio)
165 * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
166 * to time slice values: [800ms ... 100ms ... 5ms]
168 * The higher a thread's priority, the bigger timeslices
169 * it gets during one round of execution. But even the lowest
170 * priority thread gets MIN_TIMESLICE worth of execution time.
173 #define SCALE_PRIO(x, prio) \
174 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO/2), MIN_TIMESLICE)
176 static unsigned int task_timeslice(task_t *p)
178 if (p->static_prio < NICE_TO_PRIO(0))
179 return SCALE_PRIO(DEF_TIMESLICE*4, p->static_prio);
181 return SCALE_PRIO(DEF_TIMESLICE, p->static_prio);
183 #define task_hot(p, now, sd) ((long long) ((now) - (p)->last_ran) \
184 < (long long) (sd)->cache_hot_time)
197 * These are the runqueue data structures:
200 #define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
202 typedef struct runqueue runqueue_t;
205 unsigned int nr_active;
206 unsigned long bitmap[BITMAP_SIZE];
207 struct list_head queue[MAX_PRIO];
211 * This is the main, per-CPU runqueue data structure.
213 * Locking rule: those places that want to lock multiple runqueues
214 * (such as the load balancing or the thread migration code), lock
215 * acquire operations must be ordered by ascending &runqueue.
221 * nr_running and cpu_load should be in the same cacheline because
222 * remote CPUs use both these fields when doing load calculation.
224 unsigned long nr_running;
226 unsigned long cpu_load;
228 unsigned long long nr_switches;
229 unsigned long expired_timestamp, nr_uninterruptible;
230 unsigned long long timestamp_last_tick;
232 struct mm_struct *prev_mm;
233 prio_array_t *active, *expired, arrays[2];
234 int best_expired_prio;
238 struct sched_domain *sd;
240 /* For active balancing */
244 task_t *migration_thread;
245 struct list_head migration_queue;
248 #ifdef CONFIG_SCHEDSTATS
250 struct sched_info rq_sched_info;
252 /* sys_sched_yield() stats */
253 unsigned long yld_exp_empty;
254 unsigned long yld_act_empty;
255 unsigned long yld_both_empty;
256 unsigned long yld_cnt;
258 /* schedule() stats */
259 unsigned long sched_noswitch;
260 unsigned long sched_switch;
261 unsigned long sched_cnt;
262 unsigned long sched_goidle;
264 /* pull_task() stats */
265 unsigned long pt_gained[MAX_IDLE_TYPES];
266 unsigned long pt_lost[MAX_IDLE_TYPES];
268 /* active_load_balance() stats */
269 unsigned long alb_cnt;
270 unsigned long alb_lost;
271 unsigned long alb_gained;
272 unsigned long alb_failed;
274 /* try_to_wake_up() stats */
275 unsigned long ttwu_cnt;
276 unsigned long ttwu_attempts;
277 unsigned long ttwu_moved;
279 /* wake_up_new_task() stats */
280 unsigned long wunt_cnt;
281 unsigned long wunt_moved;
283 /* sched_migrate_task() stats */
284 unsigned long smt_cnt;
286 /* sched_balance_exec() stats */
287 unsigned long sbe_cnt;
291 static DEFINE_PER_CPU(struct runqueue, runqueues);
294 * sched-domains (multiprocessor balancing) declarations:
297 #define SCHED_LOAD_SCALE 128UL /* increase resolution of load */
299 #define SD_BALANCE_NEWIDLE 1 /* Balance when about to become idle */
300 #define SD_BALANCE_EXEC 2 /* Balance on exec */
301 #define SD_WAKE_IDLE 4 /* Wake to idle CPU on task wakeup */
302 #define SD_WAKE_AFFINE 8 /* Wake task to waking CPU */
303 #define SD_WAKE_BALANCE 16 /* Perform balancing at task wakeup */
304 #define SD_SHARE_CPUPOWER 32 /* Domain members share cpu power */
307 struct sched_group *next; /* Must be a circular list */
311 * CPU power of this group, SCHED_LOAD_SCALE being max power for a
312 * single CPU. This should be read only (except for setup). Although
313 * it will need to be written to at cpu hot(un)plug time, perhaps the
314 * cpucontrol semaphore will provide enough exclusion?
316 unsigned long cpu_power;
319 struct sched_domain {
320 /* These fields must be setup */
321 struct sched_domain *parent; /* top domain must be null terminated */
322 struct sched_group *groups; /* the balancing groups of the domain */
323 cpumask_t span; /* span of all CPUs in this domain */
324 unsigned long min_interval; /* Minimum balance interval ms */
325 unsigned long max_interval; /* Maximum balance interval ms */
326 unsigned int busy_factor; /* less balancing by factor if busy */
327 unsigned int imbalance_pct; /* No balance until over watermark */
328 unsigned long long cache_hot_time; /* Task considered cache hot (ns) */
329 unsigned int cache_nice_tries; /* Leave cache hot tasks for # tries */
330 unsigned int per_cpu_gain; /* CPU % gained by adding domain cpus */
331 int flags; /* See SD_* */
333 /* Runtime fields. */
334 unsigned long last_balance; /* init to jiffies. units in jiffies */
335 unsigned int balance_interval; /* initialise to 1. units in ms. */
336 unsigned int nr_balance_failed; /* initialise to 0 */
338 #ifdef CONFIG_SCHEDSTATS
339 /* load_balance() stats */
340 unsigned long lb_cnt[MAX_IDLE_TYPES];
341 unsigned long lb_failed[MAX_IDLE_TYPES];
342 unsigned long lb_imbalance[MAX_IDLE_TYPES];
343 unsigned long lb_nobusyg[MAX_IDLE_TYPES];
344 unsigned long lb_nobusyq[MAX_IDLE_TYPES];
346 /* sched_balance_exec() stats */
347 unsigned long sbe_attempts;
348 unsigned long sbe_pushed;
350 /* try_to_wake_up() stats */
351 unsigned long ttwu_wake_affine;
352 unsigned long ttwu_wake_balance;
356 #ifndef ARCH_HAS_SCHED_TUNE
357 #ifdef CONFIG_SCHED_SMT
358 #define ARCH_HAS_SCHED_WAKE_IDLE
359 /* Common values for SMT siblings */
360 #define SD_SIBLING_INIT (struct sched_domain) { \
361 .span = CPU_MASK_NONE, \
367 .imbalance_pct = 110, \
368 .cache_hot_time = 0, \
369 .cache_nice_tries = 0, \
370 .per_cpu_gain = 25, \
371 .flags = SD_BALANCE_NEWIDLE \
375 | SD_SHARE_CPUPOWER, \
376 .last_balance = jiffies, \
377 .balance_interval = 1, \
378 .nr_balance_failed = 0, \
382 /* Common values for CPUs */
383 #define SD_CPU_INIT (struct sched_domain) { \
384 .span = CPU_MASK_NONE, \
390 .imbalance_pct = 125, \
391 .cache_hot_time = cache_decay_ticks*1000000 ? : (5*1000000/2),\
392 .cache_nice_tries = 1, \
393 .per_cpu_gain = 100, \
394 .flags = SD_BALANCE_NEWIDLE \
398 .last_balance = jiffies, \
399 .balance_interval = 1, \
400 .nr_balance_failed = 0, \
403 /* Arch can override this macro in processor.h */
404 #if defined(CONFIG_NUMA) && !defined(SD_NODE_INIT)
405 #define SD_NODE_INIT (struct sched_domain) { \
406 .span = CPU_MASK_NONE, \
410 .max_interval = 32, \
412 .imbalance_pct = 125, \
413 .cache_hot_time = (10*1000000), \
414 .cache_nice_tries = 1, \
415 .per_cpu_gain = 100, \
416 .flags = SD_BALANCE_EXEC \
418 .last_balance = jiffies, \
419 .balance_interval = 1, \
420 .nr_balance_failed = 0, \
423 #endif /* ARCH_HAS_SCHED_TUNE */
427 #define for_each_domain(cpu, domain) \
428 for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
430 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
431 #define this_rq() (&__get_cpu_var(runqueues))
432 #define task_rq(p) cpu_rq(task_cpu(p))
433 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
436 * Default context-switch locking:
438 #ifndef prepare_arch_switch
439 # define prepare_arch_switch(rq, next) do { } while (0)
440 # define finish_arch_switch(rq, next) spin_unlock_irq(&(rq)->lock)
441 # define task_running(rq, p) ((rq)->curr == (p))
445 * task_rq_lock - lock the runqueue a given task resides on and disable
446 * interrupts. Note the ordering: we can safely lookup the task_rq without
447 * explicitly disabling preemption.
449 static runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
454 local_irq_save(*flags);
456 spin_lock(&rq->lock);
457 if (unlikely(rq != task_rq(p))) {
458 spin_unlock_irqrestore(&rq->lock, *flags);
459 goto repeat_lock_task;
464 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
466 spin_unlock_irqrestore(&rq->lock, *flags);
469 #ifdef CONFIG_SCHEDSTATS
471 * bump this up when changing the output format or the meaning of an existing
472 * format, so that tools can adapt (or abort)
474 #define SCHEDSTAT_VERSION 10
476 static int show_schedstat(struct seq_file *seq, void *v)
479 enum idle_type itype;
481 seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
482 seq_printf(seq, "timestamp %lu\n", jiffies);
483 for_each_online_cpu(cpu) {
484 runqueue_t *rq = cpu_rq(cpu);
486 struct sched_domain *sd;
490 /* runqueue-specific stats */
492 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu "
493 "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
494 cpu, rq->yld_both_empty,
495 rq->yld_act_empty, rq->yld_exp_empty,
496 rq->yld_cnt, rq->sched_noswitch,
497 rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
498 rq->alb_cnt, rq->alb_gained, rq->alb_lost,
500 rq->ttwu_cnt, rq->ttwu_moved, rq->ttwu_attempts,
501 rq->wunt_cnt, rq->wunt_moved,
502 rq->smt_cnt, rq->sbe_cnt, rq->rq_sched_info.cpu_time,
503 rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
505 for (itype = IDLE; itype < MAX_IDLE_TYPES; itype++)
506 seq_printf(seq, " %lu %lu", rq->pt_gained[itype],
508 seq_printf(seq, "\n");
511 /* domain-specific stats */
512 for_each_domain(cpu, sd) {
513 char mask_str[NR_CPUS];
515 cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
516 seq_printf(seq, "domain%d %s", dcnt++, mask_str);
517 for (itype = IDLE; itype < MAX_IDLE_TYPES; itype++) {
518 seq_printf(seq, " %lu %lu %lu %lu %lu",
520 sd->lb_failed[itype],
521 sd->lb_imbalance[itype],
522 sd->lb_nobusyq[itype],
523 sd->lb_nobusyg[itype]);
525 seq_printf(seq, " %lu %lu %lu %lu\n",
526 sd->sbe_pushed, sd->sbe_attempts,
527 sd->ttwu_wake_affine, sd->ttwu_wake_balance);
534 static int schedstat_open(struct inode *inode, struct file *file)
536 unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
537 char *buf = kmalloc(size, GFP_KERNEL);
543 res = single_open(file, show_schedstat, NULL);
545 m = file->private_data;
553 struct file_operations proc_schedstat_operations = {
554 .open = schedstat_open,
557 .release = single_release,
560 # define schedstat_inc(rq, field) rq->field++;
561 # define schedstat_add(rq, field, amt) rq->field += amt;
562 #else /* !CONFIG_SCHEDSTATS */
563 # define schedstat_inc(rq, field) do { } while (0);
564 # define schedstat_add(rq, field, amt) do { } while (0);
568 * rq_lock - lock a given runqueue and disable interrupts.
570 static runqueue_t *this_rq_lock(void)
576 spin_lock(&rq->lock);
581 static inline void rq_unlock(runqueue_t *rq)
583 spin_unlock_irq(&rq->lock);
586 #ifdef CONFIG_SCHEDSTATS
588 * Called when a process is dequeued from the active array and given
589 * the cpu. We should note that with the exception of interactive
590 * tasks, the expired queue will become the active queue after the active
591 * queue is empty, without explicitly dequeuing and requeuing tasks in the
592 * expired queue. (Interactive tasks may be requeued directly to the
593 * active queue, thus delaying tasks in the expired queue from running;
594 * see scheduler_tick()).
596 * This function is only called from sched_info_arrive(), rather than
597 * dequeue_task(). Even though a task may be queued and dequeued multiple
598 * times as it is shuffled about, we're really interested in knowing how
599 * long it was from the *first* time it was queued to the time that it
602 static inline void sched_info_dequeued(task_t *t)
604 t->sched_info.last_queued = 0;
608 * Called when a task finally hits the cpu. We can now calculate how
609 * long it was waiting to run. We also note when it began so that we
610 * can keep stats on how long its timeslice is.
612 static inline void sched_info_arrive(task_t *t)
614 unsigned long now = jiffies, diff = 0;
615 struct runqueue *rq = task_rq(t);
617 if (t->sched_info.last_queued)
618 diff = now - t->sched_info.last_queued;
619 sched_info_dequeued(t);
620 t->sched_info.run_delay += diff;
621 t->sched_info.last_arrival = now;
622 t->sched_info.pcnt++;
627 rq->rq_sched_info.run_delay += diff;
628 rq->rq_sched_info.pcnt++;
632 * Called when a process is queued into either the active or expired
633 * array. The time is noted and later used to determine how long we
634 * had to wait for us to reach the cpu. Since the expired queue will
635 * become the active queue after active queue is empty, without dequeuing
636 * and requeuing any tasks, we are interested in queuing to either. It
637 * is unusual but not impossible for tasks to be dequeued and immediately
638 * requeued in the same or another array: this can happen in sched_yield(),
639 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
642 * This function is only called from enqueue_task(), but also only updates
643 * the timestamp if it is already not set. It's assumed that
644 * sched_info_dequeued() will clear that stamp when appropriate.
646 static inline void sched_info_queued(task_t *t)
648 if (!t->sched_info.last_queued)
649 t->sched_info.last_queued = jiffies;
653 * Called when a process ceases being the active-running process, either
654 * voluntarily or involuntarily. Now we can calculate how long we ran.
656 static inline void sched_info_depart(task_t *t)
658 struct runqueue *rq = task_rq(t);
659 unsigned long diff = jiffies - t->sched_info.last_arrival;
661 t->sched_info.cpu_time += diff;
664 rq->rq_sched_info.cpu_time += diff;
668 * Called when tasks are switched involuntarily due, typically, to expiring
669 * their time slice. (This may also be called when switching to or from
670 * the idle task.) We are only called when prev != next.
672 static inline void sched_info_switch(task_t *prev, task_t *next)
674 struct runqueue *rq = task_rq(prev);
677 * prev now departs the cpu. It's not interesting to record
678 * stats about how efficient we were at scheduling the idle
681 if (prev != rq->idle)
682 sched_info_depart(prev);
684 if (next != rq->idle)
685 sched_info_arrive(next);
688 #define sched_info_queued(t) do { } while (0)
689 #define sched_info_switch(t, next) do { } while (0)
690 #endif /* CONFIG_SCHEDSTATS */
693 * Adding/removing a task to/from a priority array:
695 static void dequeue_task(struct task_struct *p, prio_array_t *array)
698 list_del(&p->run_list);
699 if (list_empty(array->queue + p->prio))
700 __clear_bit(p->prio, array->bitmap);
703 static void enqueue_task(struct task_struct *p, prio_array_t *array)
705 sched_info_queued(p);
706 list_add_tail(&p->run_list, array->queue + p->prio);
707 __set_bit(p->prio, array->bitmap);
713 * Used by the migration code - we pull tasks from the head of the
714 * remote queue so we want these tasks to show up at the head of the
717 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
719 list_add(&p->run_list, array->queue + p->prio);
720 __set_bit(p->prio, array->bitmap);
726 * effective_prio - return the priority that is based on the static
727 * priority but is modified by bonuses/penalties.
729 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
730 * into the -5 ... 0 ... +5 bonus/penalty range.
732 * We use 25% of the full 0...39 priority range so that:
734 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
735 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
737 * Both properties are important to certain workloads.
739 static int effective_prio(task_t *p)
746 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
748 prio = p->static_prio - bonus;
749 if (prio < MAX_RT_PRIO)
751 if (prio > MAX_PRIO-1)
757 * __activate_task - move a task to the runqueue.
759 static inline void __activate_task(task_t *p, runqueue_t *rq)
761 enqueue_task(p, rq->active);
766 * __activate_idle_task - move idle task to the _front_ of runqueue.
768 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
770 enqueue_task_head(p, rq->active);
774 static void recalc_task_prio(task_t *p, unsigned long long now)
776 unsigned long long __sleep_time = now - p->timestamp;
777 unsigned long sleep_time;
779 if (__sleep_time > NS_MAX_SLEEP_AVG)
780 sleep_time = NS_MAX_SLEEP_AVG;
782 sleep_time = (unsigned long)__sleep_time;
784 if (likely(sleep_time > 0)) {
786 * User tasks that sleep a long time are categorised as
787 * idle and will get just interactive status to stay active &
788 * prevent them suddenly becoming cpu hogs and starving
791 if (p->mm && p->activated != -1 &&
792 sleep_time > INTERACTIVE_SLEEP(p)) {
793 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
796 p->interactive_credit++;
799 * The lower the sleep avg a task has the more
800 * rapidly it will rise with sleep time.
802 sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
805 * Tasks with low interactive_credit are limited to
806 * one timeslice worth of sleep avg bonus.
809 sleep_time > JIFFIES_TO_NS(task_timeslice(p)))
810 sleep_time = JIFFIES_TO_NS(task_timeslice(p));
813 * Non high_credit tasks waking from uninterruptible
814 * sleep are limited in their sleep_avg rise as they
815 * are likely to be cpu hogs waiting on I/O
817 if (p->activated == -1 && !HIGH_CREDIT(p) && p->mm) {
818 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
820 else if (p->sleep_avg + sleep_time >=
821 INTERACTIVE_SLEEP(p)) {
822 p->sleep_avg = INTERACTIVE_SLEEP(p);
828 * This code gives a bonus to interactive tasks.
830 * The boost works by updating the 'average sleep time'
831 * value here, based on ->timestamp. The more time a
832 * task spends sleeping, the higher the average gets -
833 * and the higher the priority boost gets as well.
835 p->sleep_avg += sleep_time;
837 if (p->sleep_avg > NS_MAX_SLEEP_AVG) {
838 p->sleep_avg = NS_MAX_SLEEP_AVG;
840 p->interactive_credit++;
845 p->prio = effective_prio(p);
849 * activate_task - move a task to the runqueue and do priority recalculation
851 * Update all the scheduling statistics stuff. (sleep average
852 * calculation, priority modifiers, etc.)
854 static void activate_task(task_t *p, runqueue_t *rq, int local)
856 unsigned long long now;
861 /* Compensate for drifting sched_clock */
862 runqueue_t *this_rq = this_rq();
863 now = (now - this_rq->timestamp_last_tick)
864 + rq->timestamp_last_tick;
868 recalc_task_prio(p, now);
871 * This checks to make sure it's not an uninterruptible task
872 * that is now waking up.
876 * Tasks which were woken up by interrupts (ie. hw events)
877 * are most likely of interactive nature. So we give them
878 * the credit of extending their sleep time to the period
879 * of time they spend on the runqueue, waiting for execution
880 * on a CPU, first time around:
886 * Normal first-time wakeups get a credit too for
887 * on-runqueue time, but it will be weighted down:
894 __activate_task(p, rq);
898 * deactivate_task - remove a task from the runqueue.
900 static void deactivate_task(struct task_struct *p, runqueue_t *rq)
903 if (p->state == TASK_UNINTERRUPTIBLE)
904 rq->nr_uninterruptible++;
905 dequeue_task(p, p->array);
910 * resched_task - mark a task 'to be rescheduled now'.
912 * On UP this means the setting of the need_resched flag, on SMP it
913 * might also involve a cross-CPU call to trigger the scheduler on
917 static void resched_task(task_t *p)
919 int need_resched, nrpolling;
921 BUG_ON(!spin_is_locked(&task_rq(p)->lock));
923 /* minimise the chance of sending an interrupt to poll_idle() */
924 nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
925 need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
926 nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
928 if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
929 smp_send_reschedule(task_cpu(p));
932 static inline void resched_task(task_t *p)
934 set_tsk_need_resched(p);
939 * task_curr - is this task currently executing on a CPU?
940 * @p: the task in question.
942 inline int task_curr(const task_t *p)
944 return cpu_curr(task_cpu(p)) == p;
954 struct list_head list;
955 enum request_type type;
957 /* For REQ_MOVE_TASK */
961 /* For REQ_SET_DOMAIN */
962 struct sched_domain *sd;
964 struct completion done;
968 * The task's runqueue lock must be held.
969 * Returns true if you have to wait for migration thread.
971 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
973 runqueue_t *rq = task_rq(p);
976 * If the task is not on a runqueue (and not running), then
977 * it is sufficient to simply update the task's cpu field.
979 if (!p->array && !task_running(rq, p)) {
980 set_task_cpu(p, dest_cpu);
984 init_completion(&req->done);
985 req->type = REQ_MOVE_TASK;
987 req->dest_cpu = dest_cpu;
988 list_add(&req->list, &rq->migration_queue);
993 * wait_task_inactive - wait for a thread to unschedule.
995 * The caller must ensure that the task *will* unschedule sometime soon,
996 * else this function might spin for a *long* time. This function can't
997 * be called with interrupts off, or it may introduce deadlock with
998 * smp_call_function() if an IPI is sent by the same process we are
999 * waiting to become inactive.
1001 void wait_task_inactive(task_t * p)
1003 unsigned long flags;
1008 rq = task_rq_lock(p, &flags);
1009 /* Must be off runqueue entirely, not preempted. */
1010 if (unlikely(p->array)) {
1011 /* If it's preempted, we yield. It could be a while. */
1012 preempted = !task_running(rq, p);
1013 task_rq_unlock(rq, &flags);
1019 task_rq_unlock(rq, &flags);
1023 * kick_process - kick a running thread to enter/exit the kernel
1024 * @p: the to-be-kicked thread
1026 * Cause a process which is running on another CPU to enter
1027 * kernel-mode, without any delay. (to get signals handled.)
1029 void kick_process(task_t *p)
1035 if ((cpu != smp_processor_id()) && task_curr(p))
1036 smp_send_reschedule(cpu);
1040 EXPORT_SYMBOL_GPL(kick_process);
1043 * Return a low guess at the load of a migration-source cpu.
1045 * We want to under-estimate the load of migration sources, to
1046 * balance conservatively.
1048 static inline unsigned long source_load(int cpu)
1050 runqueue_t *rq = cpu_rq(cpu);
1051 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
1053 return min(rq->cpu_load, load_now);
1057 * Return a high guess at the load of a migration-target cpu
1059 static inline unsigned long target_load(int cpu)
1061 runqueue_t *rq = cpu_rq(cpu);
1062 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
1064 return max(rq->cpu_load, load_now);
1070 * wake_idle() is useful especially on SMT architectures to wake a
1071 * task onto an idle sibling if we would otherwise wake it onto a
1074 * Returns the CPU we should wake onto.
1076 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1077 static int wake_idle(int cpu, task_t *p)
1080 runqueue_t *rq = cpu_rq(cpu);
1081 struct sched_domain *sd;
1088 if (!(sd->flags & SD_WAKE_IDLE))
1091 cpus_and(tmp, sd->span, cpu_online_map);
1092 cpus_and(tmp, tmp, p->cpus_allowed);
1094 for_each_cpu_mask(i, tmp) {
1102 static inline int wake_idle(int cpu, task_t *p)
1109 * try_to_wake_up - wake up a thread
1110 * @p: the to-be-woken-up thread
1111 * @state: the mask of task states that can be woken
1112 * @sync: do a synchronous wakeup?
1114 * Put it on the run-queue if it's not already there. The "current"
1115 * thread is always on the run-queue (except when the actual
1116 * re-schedule is in progress), and as such you're allowed to do
1117 * the simpler "current->state = TASK_RUNNING" to mark yourself
1118 * runnable without the overhead of this.
1120 * returns failure only if the task is already active.
1122 static int try_to_wake_up(task_t * p, unsigned int state, int sync)
1124 int cpu, this_cpu, success = 0;
1125 unsigned long flags;
1129 unsigned long load, this_load;
1130 struct sched_domain *sd;
1134 rq = task_rq_lock(p, &flags);
1135 schedstat_inc(rq, ttwu_cnt);
1136 old_state = p->state;
1137 if (!(old_state & state))
1144 this_cpu = smp_processor_id();
1147 if (unlikely(task_running(rq, p)))
1152 if (cpu == this_cpu || unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1155 load = source_load(cpu);
1156 this_load = target_load(this_cpu);
1159 * If sync wakeup then subtract the (maximum possible) effect of
1160 * the currently running task from the load of the current CPU:
1163 this_load -= SCHED_LOAD_SCALE;
1165 /* Don't pull the task off an idle CPU to a busy one */
1166 if (load < SCHED_LOAD_SCALE/2 && this_load > SCHED_LOAD_SCALE/2)
1169 new_cpu = this_cpu; /* Wake to this CPU if we can */
1172 * Scan domains for affine wakeup and passive balancing
1175 for_each_domain(this_cpu, sd) {
1176 unsigned int imbalance;
1178 * Start passive balancing when half the imbalance_pct
1181 imbalance = sd->imbalance_pct + (sd->imbalance_pct - 100) / 2;
1183 if ((sd->flags & SD_WAKE_AFFINE) &&
1184 !task_hot(p, rq->timestamp_last_tick, sd)) {
1186 * This domain has SD_WAKE_AFFINE and p is cache cold
1189 if (cpu_isset(cpu, sd->span)) {
1190 schedstat_inc(sd, ttwu_wake_affine);
1193 } else if ((sd->flags & SD_WAKE_BALANCE) &&
1194 imbalance*this_load <= 100*load) {
1196 * This domain has SD_WAKE_BALANCE and there is
1199 if (cpu_isset(cpu, sd->span)) {
1200 schedstat_inc(sd, ttwu_wake_balance);
1206 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1208 schedstat_inc(rq, ttwu_attempts);
1209 new_cpu = wake_idle(new_cpu, p);
1210 if (new_cpu != cpu && cpu_isset(new_cpu, p->cpus_allowed)) {
1211 schedstat_inc(rq, ttwu_moved);
1212 set_task_cpu(p, new_cpu);
1213 task_rq_unlock(rq, &flags);
1214 /* might preempt at this point */
1215 rq = task_rq_lock(p, &flags);
1216 old_state = p->state;
1217 if (!(old_state & state))
1222 this_cpu = smp_processor_id();
1227 #endif /* CONFIG_SMP */
1228 if (old_state == TASK_UNINTERRUPTIBLE) {
1229 rq->nr_uninterruptible--;
1231 * Tasks on involuntary sleep don't earn
1232 * sleep_avg beyond just interactive state.
1238 * Sync wakeups (i.e. those types of wakeups where the waker
1239 * has indicated that it will leave the CPU in short order)
1240 * don't trigger a preemption, if the woken up task will run on
1241 * this cpu. (in this case the 'I will reschedule' promise of
1242 * the waker guarantees that the freshly woken up task is going
1243 * to be considered on this CPU.)
1245 activate_task(p, rq, cpu == this_cpu);
1246 if (!sync || cpu != this_cpu) {
1247 if (TASK_PREEMPTS_CURR(p, rq))
1248 resched_task(rq->curr);
1253 p->state = TASK_RUNNING;
1255 task_rq_unlock(rq, &flags);
1260 int fastcall wake_up_process(task_t * p)
1262 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1263 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1266 EXPORT_SYMBOL(wake_up_process);
1268 int fastcall wake_up_state(task_t *p, unsigned int state)
1270 return try_to_wake_up(p, state, 0);
1274 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1275 struct sched_domain *sd);
1279 * Perform scheduler related setup for a newly forked process p.
1280 * p is forked by current.
1282 void fastcall sched_fork(task_t *p)
1285 * We mark the process as running here, but have not actually
1286 * inserted it onto the runqueue yet. This guarantees that
1287 * nobody will actually run it, and a signal or other external
1288 * event cannot wake it up and insert it on the runqueue either.
1290 p->state = TASK_RUNNING;
1291 INIT_LIST_HEAD(&p->run_list);
1293 spin_lock_init(&p->switch_lock);
1294 #ifdef CONFIG_SCHEDSTATS
1295 memset(&p->sched_info, 0, sizeof(p->sched_info));
1297 #ifdef CONFIG_PREEMPT
1299 * During context-switch we hold precisely one spinlock, which
1300 * schedule_tail drops. (in the common case it's this_rq()->lock,
1301 * but it also can be p->switch_lock.) So we compensate with a count
1302 * of 1. Also, we want to start with kernel preemption disabled.
1304 p->thread_info->preempt_count = 1;
1307 * Share the timeslice between parent and child, thus the
1308 * total amount of pending timeslices in the system doesn't change,
1309 * resulting in more scheduling fairness.
1311 local_irq_disable();
1312 p->time_slice = (current->time_slice + 1) >> 1;
1314 * The remainder of the first timeslice might be recovered by
1315 * the parent if the child exits early enough.
1317 p->first_time_slice = 1;
1318 current->time_slice >>= 1;
1319 p->timestamp = sched_clock();
1320 if (unlikely(!current->time_slice)) {
1322 * This case is rare, it happens when the parent has only
1323 * a single jiffy left from its timeslice. Taking the
1324 * runqueue lock is not a problem.
1326 current->time_slice = 1;
1328 scheduler_tick(0, 0);
1336 * wake_up_new_task - wake up a newly created task for the first time.
1338 * This function will do some initial scheduler statistics housekeeping
1339 * that must be done for every newly created context, then puts the task
1340 * on the runqueue and wakes it.
1342 void fastcall wake_up_new_task(task_t * p, unsigned long clone_flags)
1344 unsigned long flags;
1346 runqueue_t *rq, *this_rq;
1348 rq = task_rq_lock(p, &flags);
1350 this_cpu = smp_processor_id();
1352 BUG_ON(p->state != TASK_RUNNING);
1354 schedstat_inc(rq, wunt_cnt);
1356 * We decrease the sleep average of forking parents
1357 * and children as well, to keep max-interactive tasks
1358 * from forking tasks that are max-interactive. The parent
1359 * (current) is done further down, under its lock.
1361 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1362 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1364 p->interactive_credit = 0;
1366 p->prio = effective_prio(p);
1368 if (likely(cpu == this_cpu)) {
1369 if (!(clone_flags & CLONE_VM)) {
1371 * The VM isn't cloned, so we're in a good position to
1372 * do child-runs-first in anticipation of an exec. This
1373 * usually avoids a lot of COW overhead.
1375 if (unlikely(!current->array))
1376 __activate_task(p, rq);
1378 p->prio = current->prio;
1379 list_add_tail(&p->run_list, ¤t->run_list);
1380 p->array = current->array;
1381 p->array->nr_active++;
1386 /* Run child last */
1387 __activate_task(p, rq);
1389 * We skip the following code due to cpu == this_cpu
1391 * task_rq_unlock(rq, &flags);
1392 * this_rq = task_rq_lock(current, &flags);
1396 this_rq = cpu_rq(this_cpu);
1399 * Not the local CPU - must adjust timestamp. This should
1400 * get optimised away in the !CONFIG_SMP case.
1402 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1403 + rq->timestamp_last_tick;
1404 __activate_task(p, rq);
1405 if (TASK_PREEMPTS_CURR(p, rq))
1406 resched_task(rq->curr);
1408 schedstat_inc(rq, wunt_moved);
1410 * Parent and child are on different CPUs, now get the
1411 * parent runqueue to update the parent's ->sleep_avg:
1413 task_rq_unlock(rq, &flags);
1414 this_rq = task_rq_lock(current, &flags);
1416 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1417 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1418 task_rq_unlock(this_rq, &flags);
1422 * Potentially available exiting-child timeslices are
1423 * retrieved here - this way the parent does not get
1424 * penalized for creating too many threads.
1426 * (this cannot be used to 'generate' timeslices
1427 * artificially, because any timeslice recovered here
1428 * was given away by the parent in the first place.)
1430 void fastcall sched_exit(task_t * p)
1432 unsigned long flags;
1436 * If the child was a (relative-) CPU hog then decrease
1437 * the sleep_avg of the parent as well.
1439 rq = task_rq_lock(p->parent, &flags);
1440 if (p->first_time_slice) {
1441 p->parent->time_slice += p->time_slice;
1442 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1443 p->parent->time_slice = task_timeslice(p);
1445 if (p->sleep_avg < p->parent->sleep_avg)
1446 p->parent->sleep_avg = p->parent->sleep_avg /
1447 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1449 task_rq_unlock(rq, &flags);
1453 * finish_task_switch - clean up after a task-switch
1454 * @prev: the thread we just switched away from.
1456 * We enter this with the runqueue still locked, and finish_arch_switch()
1457 * will unlock it along with doing any other architecture-specific cleanup
1460 * Note that we may have delayed dropping an mm in context_switch(). If
1461 * so, we finish that here outside of the runqueue lock. (Doing it
1462 * with the lock held can cause deadlocks; see schedule() for
1465 static void finish_task_switch(task_t *prev)
1467 runqueue_t *rq = this_rq();
1468 struct mm_struct *mm = rq->prev_mm;
1469 unsigned long prev_task_flags;
1474 * A task struct has one reference for the use as "current".
1475 * If a task dies, then it sets TASK_ZOMBIE in tsk->state and calls
1476 * schedule one last time. The schedule call will never return,
1477 * and the scheduled task must drop that reference.
1478 * The test for TASK_ZOMBIE must occur while the runqueue locks are
1479 * still held, otherwise prev could be scheduled on another cpu, die
1480 * there before we look at prev->state, and then the reference would
1482 * Manfred Spraul <manfred@colorfullife.com>
1484 prev_task_flags = prev->flags;
1485 finish_arch_switch(rq, prev);
1488 if (unlikely(prev_task_flags & PF_DEAD))
1489 put_task_struct(prev);
1493 * schedule_tail - first thing a freshly forked thread must call.
1494 * @prev: the thread we just switched away from.
1496 asmlinkage void schedule_tail(task_t *prev)
1498 finish_task_switch(prev);
1500 if (current->set_child_tid)
1501 put_user(current->pid, current->set_child_tid);
1505 * context_switch - switch to the new MM and the new
1506 * thread's register state.
1509 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1511 struct mm_struct *mm = next->mm;
1512 struct mm_struct *oldmm = prev->active_mm;
1514 if (unlikely(!mm)) {
1515 next->active_mm = oldmm;
1516 atomic_inc(&oldmm->mm_count);
1517 enter_lazy_tlb(oldmm, next);
1519 switch_mm(oldmm, mm, next);
1521 if (unlikely(!prev->mm)) {
1522 prev->active_mm = NULL;
1523 WARN_ON(rq->prev_mm);
1524 rq->prev_mm = oldmm;
1527 /* Here we just switch the register state and the stack. */
1528 switch_to(prev, next, prev);
1534 * nr_running, nr_uninterruptible and nr_context_switches:
1536 * externally visible scheduler statistics: current number of runnable
1537 * threads, current number of uninterruptible-sleeping threads, total
1538 * number of context switches performed since bootup.
1540 unsigned long nr_running(void)
1542 unsigned long i, sum = 0;
1544 for_each_online_cpu(i)
1545 sum += cpu_rq(i)->nr_running;
1550 unsigned long nr_uninterruptible(void)
1552 unsigned long i, sum = 0;
1555 sum += cpu_rq(i)->nr_uninterruptible;
1560 unsigned long long nr_context_switches(void)
1562 unsigned long long i, sum = 0;
1565 sum += cpu_rq(i)->nr_switches;
1570 unsigned long nr_iowait(void)
1572 unsigned long i, sum = 0;
1575 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1583 * double_rq_lock - safely lock two runqueues
1585 * Note this does not disable interrupts like task_rq_lock,
1586 * you need to do so manually before calling.
1588 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1591 spin_lock(&rq1->lock);
1594 spin_lock(&rq1->lock);
1595 spin_lock(&rq2->lock);
1597 spin_lock(&rq2->lock);
1598 spin_lock(&rq1->lock);
1604 * double_rq_unlock - safely unlock two runqueues
1606 * Note this does not restore interrupts like task_rq_unlock,
1607 * you need to do so manually after calling.
1609 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1611 spin_unlock(&rq1->lock);
1613 spin_unlock(&rq2->lock);
1617 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1619 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1621 if (unlikely(!spin_trylock(&busiest->lock))) {
1622 if (busiest < this_rq) {
1623 spin_unlock(&this_rq->lock);
1624 spin_lock(&busiest->lock);
1625 spin_lock(&this_rq->lock);
1627 spin_lock(&busiest->lock);
1632 * find_idlest_cpu - find the least busy runqueue.
1634 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1635 struct sched_domain *sd)
1637 unsigned long load, min_load, this_load;
1642 min_load = ULONG_MAX;
1644 cpus_and(mask, sd->span, cpu_online_map);
1645 cpus_and(mask, mask, p->cpus_allowed);
1647 for_each_cpu_mask(i, mask) {
1648 load = target_load(i);
1650 if (load < min_load) {
1654 /* break out early on an idle CPU: */
1660 /* add +1 to account for the new task */
1661 this_load = source_load(this_cpu) + SCHED_LOAD_SCALE;
1664 * Would with the addition of the new task to the
1665 * current CPU there be an imbalance between this
1666 * CPU and the idlest CPU?
1668 * Use half of the balancing threshold - new-context is
1669 * a good opportunity to balance.
1671 if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1678 * If dest_cpu is allowed for this process, migrate the task to it.
1679 * This is accomplished by forcing the cpu_allowed mask to only
1680 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1681 * the cpu_allowed mask is restored.
1683 static void sched_migrate_task(task_t *p, int dest_cpu)
1685 migration_req_t req;
1687 unsigned long flags;
1689 rq = task_rq_lock(p, &flags);
1690 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1691 || unlikely(cpu_is_offline(dest_cpu)))
1694 schedstat_inc(rq, smt_cnt);
1695 /* force the process onto the specified CPU */
1696 if (migrate_task(p, dest_cpu, &req)) {
1697 /* Need to wait for migration thread (might exit: take ref). */
1698 struct task_struct *mt = rq->migration_thread;
1699 get_task_struct(mt);
1700 task_rq_unlock(rq, &flags);
1701 wake_up_process(mt);
1702 put_task_struct(mt);
1703 wait_for_completion(&req.done);
1707 task_rq_unlock(rq, &flags);
1711 * sched_exec(): find the highest-level, exec-balance-capable
1712 * domain and try to migrate the task to the least loaded CPU.
1714 * execve() is a valuable balancing opportunity, because at this point
1715 * the task has the smallest effective memory and cache footprint.
1717 void sched_exec(void)
1719 struct sched_domain *tmp, *sd = NULL;
1720 int new_cpu, this_cpu = get_cpu();
1722 schedstat_inc(this_rq(), sbe_cnt);
1723 /* Prefer the current CPU if there's only this task running */
1724 if (this_rq()->nr_running <= 1)
1727 for_each_domain(this_cpu, tmp)
1728 if (tmp->flags & SD_BALANCE_EXEC)
1732 schedstat_inc(sd, sbe_attempts);
1733 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1734 if (new_cpu != this_cpu) {
1735 schedstat_inc(sd, sbe_pushed);
1737 sched_migrate_task(current, new_cpu);
1746 * pull_task - move a task from a remote runqueue to the local runqueue.
1747 * Both runqueues must be locked.
1750 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1751 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1753 dequeue_task(p, src_array);
1754 src_rq->nr_running--;
1755 set_task_cpu(p, this_cpu);
1756 this_rq->nr_running++;
1757 enqueue_task(p, this_array);
1758 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1759 + this_rq->timestamp_last_tick;
1761 * Note that idle threads have a prio of MAX_PRIO, for this test
1762 * to be always true for them.
1764 if (TASK_PREEMPTS_CURR(p, this_rq))
1765 resched_task(this_rq->curr);
1769 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1772 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1773 struct sched_domain *sd, enum idle_type idle)
1776 * We do not migrate tasks that are:
1777 * 1) running (obviously), or
1778 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1779 * 3) are cache-hot on their current CPU.
1781 if (task_running(rq, p))
1783 if (!cpu_isset(this_cpu, p->cpus_allowed))
1786 /* Aggressive migration if we've failed balancing */
1787 if (idle == NEWLY_IDLE ||
1788 sd->nr_balance_failed < sd->cache_nice_tries) {
1789 if (task_hot(p, rq->timestamp_last_tick, sd))
1797 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1798 * as part of a balancing operation within "domain". Returns the number of
1801 * Called with both runqueues locked.
1803 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1804 unsigned long max_nr_move, struct sched_domain *sd,
1805 enum idle_type idle)
1807 prio_array_t *array, *dst_array;
1808 struct list_head *head, *curr;
1809 int idx, pulled = 0;
1812 if (max_nr_move <= 0 || busiest->nr_running <= 1)
1816 * We first consider expired tasks. Those will likely not be
1817 * executed in the near future, and they are most likely to
1818 * be cache-cold, thus switching CPUs has the least effect
1821 if (busiest->expired->nr_active) {
1822 array = busiest->expired;
1823 dst_array = this_rq->expired;
1825 array = busiest->active;
1826 dst_array = this_rq->active;
1830 /* Start searching at priority 0: */
1834 idx = sched_find_first_bit(array->bitmap);
1836 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1837 if (idx >= MAX_PRIO) {
1838 if (array == busiest->expired && busiest->active->nr_active) {
1839 array = busiest->active;
1840 dst_array = this_rq->active;
1846 head = array->queue + idx;
1849 tmp = list_entry(curr, task_t, run_list);
1853 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
1861 * Right now, this is the only place pull_task() is called,
1862 * so we can safely collect pull_task() stats here rather than
1863 * inside pull_task().
1865 schedstat_inc(this_rq, pt_gained[idle]);
1866 schedstat_inc(busiest, pt_lost[idle]);
1868 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
1871 /* We only want to steal up to the prescribed number of tasks. */
1872 if (pulled < max_nr_move) {
1883 * find_busiest_group finds and returns the busiest CPU group within the
1884 * domain. It calculates and returns the number of tasks which should be
1885 * moved to restore balance via the imbalance parameter.
1887 static struct sched_group *
1888 find_busiest_group(struct sched_domain *sd, int this_cpu,
1889 unsigned long *imbalance, enum idle_type idle)
1891 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
1892 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
1894 max_load = this_load = total_load = total_pwr = 0;
1902 local_group = cpu_isset(this_cpu, group->cpumask);
1904 /* Tally up the load of all CPUs in the group */
1906 cpus_and(tmp, group->cpumask, cpu_online_map);
1907 if (unlikely(cpus_empty(tmp)))
1910 for_each_cpu_mask(i, tmp) {
1911 /* Bias balancing toward cpus of our domain */
1913 load = target_load(i);
1915 load = source_load(i);
1924 total_load += avg_load;
1925 total_pwr += group->cpu_power;
1927 /* Adjust by relative CPU power of the group */
1928 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1931 this_load = avg_load;
1934 } else if (avg_load > max_load) {
1935 max_load = avg_load;
1939 group = group->next;
1940 } while (group != sd->groups);
1942 if (!busiest || this_load >= max_load)
1945 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
1947 if (this_load >= avg_load ||
1948 100*max_load <= sd->imbalance_pct*this_load)
1952 * We're trying to get all the cpus to the average_load, so we don't
1953 * want to push ourselves above the average load, nor do we wish to
1954 * reduce the max loaded cpu below the average load, as either of these
1955 * actions would just result in more rebalancing later, and ping-pong
1956 * tasks around. Thus we look for the minimum possible imbalance.
1957 * Negative imbalances (*we* are more loaded than anyone else) will
1958 * be counted as no imbalance for these purposes -- we can't fix that
1959 * by pulling tasks to us. Be careful of negative numbers as they'll
1960 * appear as very large values with unsigned longs.
1962 *imbalance = min(max_load - avg_load, avg_load - this_load);
1964 /* How much load to actually move to equalise the imbalance */
1965 *imbalance = (*imbalance * min(busiest->cpu_power, this->cpu_power))
1968 if (*imbalance < SCHED_LOAD_SCALE - 1) {
1969 unsigned long pwr_now = 0, pwr_move = 0;
1972 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
1978 * OK, we don't have enough imbalance to justify moving tasks,
1979 * however we may be able to increase total CPU power used by
1983 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
1984 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
1985 pwr_now /= SCHED_LOAD_SCALE;
1987 /* Amount of load we'd subtract */
1988 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
1990 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
1993 /* Amount of load we'd add */
1994 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
1997 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
1998 pwr_move /= SCHED_LOAD_SCALE;
2000 /* Move if we gain another 8th of a CPU worth of throughput */
2001 if (pwr_move < pwr_now + SCHED_LOAD_SCALE / 8)
2008 /* Get rid of the scaling factor, rounding down as we divide */
2009 *imbalance = (*imbalance + 1) / SCHED_LOAD_SCALE;
2014 if (busiest && (idle == NEWLY_IDLE ||
2015 (idle == IDLE && max_load > SCHED_LOAD_SCALE)) ) {
2025 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2027 static runqueue_t *find_busiest_queue(struct sched_group *group)
2030 unsigned long load, max_load = 0;
2031 runqueue_t *busiest = NULL;
2034 cpus_and(tmp, group->cpumask, cpu_online_map);
2035 for_each_cpu_mask(i, tmp) {
2036 load = source_load(i);
2038 if (load > max_load) {
2040 busiest = cpu_rq(i);
2048 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2049 * tasks if there is an imbalance.
2051 * Called with this_rq unlocked.
2053 static int load_balance(int this_cpu, runqueue_t *this_rq,
2054 struct sched_domain *sd, enum idle_type idle)
2056 struct sched_group *group;
2057 runqueue_t *busiest;
2058 unsigned long imbalance;
2061 spin_lock(&this_rq->lock);
2062 schedstat_inc(sd, lb_cnt[idle]);
2064 group = find_busiest_group(sd, this_cpu, &imbalance, idle);
2066 schedstat_inc(sd, lb_nobusyg[idle]);
2070 busiest = find_busiest_queue(group);
2072 schedstat_inc(sd, lb_nobusyq[idle]);
2077 * This should be "impossible", but since load
2078 * balancing is inherently racy and statistical,
2079 * it could happen in theory.
2081 if (unlikely(busiest == this_rq)) {
2086 schedstat_add(sd, lb_imbalance[idle], imbalance);
2089 if (busiest->nr_running > 1) {
2091 * Attempt to move tasks. If find_busiest_group has found
2092 * an imbalance but busiest->nr_running <= 1, the group is
2093 * still unbalanced. nr_moved simply stays zero, so it is
2094 * correctly treated as an imbalance.
2096 double_lock_balance(this_rq, busiest);
2097 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2098 imbalance, sd, idle);
2099 spin_unlock(&busiest->lock);
2101 spin_unlock(&this_rq->lock);
2104 schedstat_inc(sd, lb_failed[idle]);
2105 sd->nr_balance_failed++;
2107 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2110 spin_lock(&busiest->lock);
2111 if (!busiest->active_balance) {
2112 busiest->active_balance = 1;
2113 busiest->push_cpu = this_cpu;
2116 spin_unlock(&busiest->lock);
2118 wake_up_process(busiest->migration_thread);
2121 * We've kicked active balancing, reset the failure
2124 sd->nr_balance_failed = sd->cache_nice_tries;
2127 sd->nr_balance_failed = 0;
2129 /* We were unbalanced, so reset the balancing interval */
2130 sd->balance_interval = sd->min_interval;
2135 spin_unlock(&this_rq->lock);
2137 /* tune up the balancing interval */
2138 if (sd->balance_interval < sd->max_interval)
2139 sd->balance_interval *= 2;
2145 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2146 * tasks if there is an imbalance.
2148 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2149 * this_rq is locked.
2151 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2152 struct sched_domain *sd)
2154 struct sched_group *group;
2155 runqueue_t *busiest = NULL;
2156 unsigned long imbalance;
2159 schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2160 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
2162 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2166 busiest = find_busiest_queue(group);
2167 if (!busiest || busiest == this_rq) {
2168 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2172 /* Attempt to move tasks */
2173 double_lock_balance(this_rq, busiest);
2175 schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2176 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2177 imbalance, sd, NEWLY_IDLE);
2179 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2181 spin_unlock(&busiest->lock);
2188 * idle_balance is called by schedule() if this_cpu is about to become
2189 * idle. Attempts to pull tasks from other CPUs.
2191 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
2193 struct sched_domain *sd;
2195 for_each_domain(this_cpu, sd) {
2196 if (sd->flags & SD_BALANCE_NEWIDLE) {
2197 if (load_balance_newidle(this_cpu, this_rq, sd)) {
2198 /* We've pulled tasks over so stop searching */
2206 * active_load_balance is run by migration threads. It pushes a running
2207 * task off the cpu. It can be required to correctly have at least 1 task
2208 * running on each physical CPU where possible, and not have a physical /
2209 * logical imbalance.
2211 * Called with busiest locked.
2213 static void active_load_balance(runqueue_t *busiest, int busiest_cpu)
2215 struct sched_domain *sd;
2216 struct sched_group *group, *busy_group;
2219 schedstat_inc(busiest, alb_cnt);
2220 if (busiest->nr_running <= 1)
2223 for_each_domain(busiest_cpu, sd)
2224 if (cpu_isset(busiest->push_cpu, sd->span))
2230 while (!cpu_isset(busiest_cpu, group->cpumask))
2231 group = group->next;
2240 if (group == busy_group)
2243 cpus_and(tmp, group->cpumask, cpu_online_map);
2244 if (!cpus_weight(tmp))
2247 for_each_cpu_mask(i, tmp) {
2253 rq = cpu_rq(push_cpu);
2256 * This condition is "impossible", but since load
2257 * balancing is inherently a bit racy and statistical,
2258 * it can trigger.. Reported by Bjorn Helgaas on a
2261 if (unlikely(busiest == rq))
2263 double_lock_balance(busiest, rq);
2264 if (move_tasks(rq, push_cpu, busiest, 1, sd, IDLE)) {
2265 schedstat_inc(busiest, alb_lost);
2266 schedstat_inc(rq, alb_gained);
2268 schedstat_inc(busiest, alb_failed);
2270 spin_unlock(&rq->lock);
2272 group = group->next;
2273 } while (group != sd->groups);
2277 * rebalance_tick will get called every timer tick, on every CPU.
2279 * It checks each scheduling domain to see if it is due to be balanced,
2280 * and initiates a balancing operation if so.
2282 * Balancing parameters are set up in arch_init_sched_domains.
2285 /* Don't have all balancing operations going off at once */
2286 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2288 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2289 enum idle_type idle)
2291 unsigned long old_load, this_load;
2292 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2293 struct sched_domain *sd;
2295 /* Update our load */
2296 old_load = this_rq->cpu_load;
2297 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
2299 * Round up the averaging division if load is increasing. This
2300 * prevents us from getting stuck on 9 if the load is 10, for
2303 if (this_load > old_load)
2305 this_rq->cpu_load = (old_load + this_load) / 2;
2307 for_each_domain(this_cpu, sd) {
2308 unsigned long interval = sd->balance_interval;
2311 interval *= sd->busy_factor;
2313 /* scale ms to jiffies */
2314 interval = msecs_to_jiffies(interval);
2315 if (unlikely(!interval))
2318 if (j - sd->last_balance >= interval) {
2319 if (load_balance(this_cpu, this_rq, sd, idle)) {
2320 /* We've pulled tasks over so no longer idle */
2323 sd->last_balance += interval;
2329 * on UP we do not need to balance between CPUs:
2331 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2334 static inline void idle_balance(int cpu, runqueue_t *rq)
2339 static inline int wake_priority_sleeper(runqueue_t *rq)
2342 #ifdef CONFIG_SCHED_SMT
2343 spin_lock(&rq->lock);
2345 * If an SMT sibling task has been put to sleep for priority
2346 * reasons reschedule the idle task to see if it can now run.
2348 if (rq->nr_running) {
2349 resched_task(rq->idle);
2352 spin_unlock(&rq->lock);
2357 DEFINE_PER_CPU(struct kernel_stat, kstat);
2359 EXPORT_PER_CPU_SYMBOL(kstat);
2362 * We place interactive tasks back into the active array, if possible.
2364 * To guarantee that this does not starve expired tasks we ignore the
2365 * interactivity of a task if the first expired task had to wait more
2366 * than a 'reasonable' amount of time. This deadline timeout is
2367 * load-dependent, as the frequency of array switched decreases with
2368 * increasing number of running tasks. We also ignore the interactivity
2369 * if a better static_prio task has expired:
2371 #define EXPIRED_STARVING(rq) \
2372 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2373 (jiffies - (rq)->expired_timestamp >= \
2374 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2375 ((rq)->curr->static_prio > (rq)->best_expired_prio))
2378 * This function gets called by the timer code, with HZ frequency.
2379 * We call it with interrupts disabled.
2381 * It also gets called by the fork code, when changing the parent's
2384 void scheduler_tick(int user_ticks, int sys_ticks)
2386 int cpu = smp_processor_id();
2387 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2388 runqueue_t *rq = this_rq();
2389 task_t *p = current;
2391 rq->timestamp_last_tick = sched_clock();
2393 if (rcu_pending(cpu))
2394 rcu_check_callbacks(cpu, user_ticks);
2396 /* note: this timer irq context must be accounted for as well */
2397 if (hardirq_count() - HARDIRQ_OFFSET) {
2398 cpustat->irq += sys_ticks;
2400 } else if (softirq_count()) {
2401 cpustat->softirq += sys_ticks;
2405 if (p == rq->idle) {
2406 if (atomic_read(&rq->nr_iowait) > 0)
2407 cpustat->iowait += sys_ticks;
2409 cpustat->idle += sys_ticks;
2410 if (wake_priority_sleeper(rq))
2412 rebalance_tick(cpu, rq, IDLE);
2415 if (TASK_NICE(p) > 0)
2416 cpustat->nice += user_ticks;
2418 cpustat->user += user_ticks;
2419 cpustat->system += sys_ticks;
2421 /* Task might have expired already, but not scheduled off yet */
2422 if (p->array != rq->active) {
2423 set_tsk_need_resched(p);
2426 spin_lock(&rq->lock);
2428 * The task was running during this tick - update the
2429 * time slice counter. Note: we do not update a thread's
2430 * priority until it either goes to sleep or uses up its
2431 * timeslice. This makes it possible for interactive tasks
2432 * to use up their timeslices at their highest priority levels.
2436 * RR tasks need a special form of timeslice management.
2437 * FIFO tasks have no timeslices.
2439 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2440 p->time_slice = task_timeslice(p);
2441 p->first_time_slice = 0;
2442 set_tsk_need_resched(p);
2444 /* put it at the end of the queue: */
2445 dequeue_task(p, rq->active);
2446 enqueue_task(p, rq->active);
2450 if (!--p->time_slice) {
2451 dequeue_task(p, rq->active);
2452 set_tsk_need_resched(p);
2453 p->prio = effective_prio(p);
2454 p->time_slice = task_timeslice(p);
2455 p->first_time_slice = 0;
2457 if (!rq->expired_timestamp)
2458 rq->expired_timestamp = jiffies;
2459 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2460 enqueue_task(p, rq->expired);
2461 if (p->static_prio < rq->best_expired_prio)
2462 rq->best_expired_prio = p->static_prio;
2464 enqueue_task(p, rq->active);
2467 * Prevent a too long timeslice allowing a task to monopolize
2468 * the CPU. We do this by splitting up the timeslice into
2471 * Note: this does not mean the task's timeslices expire or
2472 * get lost in any way, they just might be preempted by
2473 * another task of equal priority. (one with higher
2474 * priority would have preempted this task already.) We
2475 * requeue this task to the end of the list on this priority
2476 * level, which is in essence a round-robin of tasks with
2479 * This only applies to tasks in the interactive
2480 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2482 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2483 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2484 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2485 (p->array == rq->active)) {
2487 dequeue_task(p, rq->active);
2488 set_tsk_need_resched(p);
2489 p->prio = effective_prio(p);
2490 enqueue_task(p, rq->active);
2494 spin_unlock(&rq->lock);
2496 rebalance_tick(cpu, rq, NOT_IDLE);
2499 #ifdef CONFIG_SCHED_SMT
2500 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2502 struct sched_domain *sd = this_rq->sd;
2503 cpumask_t sibling_map;
2506 if (!(sd->flags & SD_SHARE_CPUPOWER))
2510 * Unlock the current runqueue because we have to lock in
2511 * CPU order to avoid deadlocks. Caller knows that we might
2512 * unlock. We keep IRQs disabled.
2514 spin_unlock(&this_rq->lock);
2516 cpus_and(sibling_map, sd->span, cpu_online_map);
2518 for_each_cpu_mask(i, sibling_map)
2519 spin_lock(&cpu_rq(i)->lock);
2521 * We clear this CPU from the mask. This both simplifies the
2522 * inner loop and keps this_rq locked when we exit:
2524 cpu_clear(this_cpu, sibling_map);
2526 for_each_cpu_mask(i, sibling_map) {
2527 runqueue_t *smt_rq = cpu_rq(i);
2530 * If an SMT sibling task is sleeping due to priority
2531 * reasons wake it up now.
2533 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
2534 resched_task(smt_rq->idle);
2537 for_each_cpu_mask(i, sibling_map)
2538 spin_unlock(&cpu_rq(i)->lock);
2540 * We exit with this_cpu's rq still held and IRQs
2545 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2547 struct sched_domain *sd = this_rq->sd;
2548 cpumask_t sibling_map;
2549 prio_array_t *array;
2553 if (!(sd->flags & SD_SHARE_CPUPOWER))
2557 * The same locking rules and details apply as for
2558 * wake_sleeping_dependent():
2560 spin_unlock(&this_rq->lock);
2561 cpus_and(sibling_map, sd->span, cpu_online_map);
2562 for_each_cpu_mask(i, sibling_map)
2563 spin_lock(&cpu_rq(i)->lock);
2564 cpu_clear(this_cpu, sibling_map);
2567 * Establish next task to be run - it might have gone away because
2568 * we released the runqueue lock above:
2570 if (!this_rq->nr_running)
2572 array = this_rq->active;
2573 if (!array->nr_active)
2574 array = this_rq->expired;
2575 BUG_ON(!array->nr_active);
2577 p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
2580 for_each_cpu_mask(i, sibling_map) {
2581 runqueue_t *smt_rq = cpu_rq(i);
2582 task_t *smt_curr = smt_rq->curr;
2585 * If a user task with lower static priority than the
2586 * running task on the SMT sibling is trying to schedule,
2587 * delay it till there is proportionately less timeslice
2588 * left of the sibling task to prevent a lower priority
2589 * task from using an unfair proportion of the
2590 * physical cpu's resources. -ck
2592 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
2593 task_timeslice(p) || rt_task(smt_curr)) &&
2594 p->mm && smt_curr->mm && !rt_task(p))
2598 * Reschedule a lower priority task on the SMT sibling,
2599 * or wake it up if it has been put to sleep for priority
2602 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
2603 task_timeslice(smt_curr) || rt_task(p)) &&
2604 smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
2605 (smt_curr == smt_rq->idle && smt_rq->nr_running))
2606 resched_task(smt_curr);
2609 for_each_cpu_mask(i, sibling_map)
2610 spin_unlock(&cpu_rq(i)->lock);
2614 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2618 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2625 * schedule() is the main scheduler function.
2627 asmlinkage void __sched schedule(void)
2630 task_t *prev, *next;
2632 prio_array_t *array;
2633 struct list_head *queue;
2634 unsigned long long now;
2635 unsigned long run_time;
2639 * Test if we are atomic. Since do_exit() needs to call into
2640 * schedule() atomically, we ignore that path for now.
2641 * Otherwise, whine if we are scheduling when we should not be.
2643 if (likely(!(current->state & (TASK_DEAD | TASK_ZOMBIE)))) {
2644 if (unlikely(in_atomic())) {
2645 printk(KERN_ERR "bad: scheduling while atomic!\n");
2656 * The idle thread is not allowed to schedule!
2657 * Remove this check after it has been exercised a bit.
2659 if (unlikely(current == rq->idle) && current->state != TASK_RUNNING) {
2660 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
2664 release_kernel_lock(prev);
2665 schedstat_inc(rq, sched_cnt);
2666 now = sched_clock();
2667 if (likely(now - prev->timestamp < NS_MAX_SLEEP_AVG))
2668 run_time = now - prev->timestamp;
2670 run_time = NS_MAX_SLEEP_AVG;
2673 * Tasks with interactive credits get charged less run_time
2674 * at high sleep_avg to delay them losing their interactive
2677 if (HIGH_CREDIT(prev))
2678 run_time /= (CURRENT_BONUS(prev) ? : 1);
2680 spin_lock_irq(&rq->lock);
2683 * if entering off of a kernel preemption go straight
2684 * to picking the next task.
2686 switch_count = &prev->nivcsw;
2687 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2688 switch_count = &prev->nvcsw;
2689 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2690 unlikely(signal_pending(prev))))
2691 prev->state = TASK_RUNNING;
2693 deactivate_task(prev, rq);
2696 cpu = smp_processor_id();
2697 if (unlikely(!rq->nr_running)) {
2699 idle_balance(cpu, rq);
2700 if (!rq->nr_running) {
2702 rq->expired_timestamp = 0;
2703 wake_sleeping_dependent(cpu, rq);
2705 * wake_sleeping_dependent() might have released
2706 * the runqueue, so break out if we got new
2709 if (!rq->nr_running)
2713 if (dependent_sleeper(cpu, rq)) {
2714 schedstat_inc(rq, sched_goidle);
2719 * dependent_sleeper() releases and reacquires the runqueue
2720 * lock, hence go into the idle loop if the rq went
2723 if (unlikely(!rq->nr_running))
2728 if (unlikely(!array->nr_active)) {
2730 * Switch the active and expired arrays.
2732 schedstat_inc(rq, sched_switch);
2733 rq->active = rq->expired;
2734 rq->expired = array;
2736 rq->expired_timestamp = 0;
2737 rq->best_expired_prio = MAX_PRIO;
2739 schedstat_inc(rq, sched_noswitch);
2741 idx = sched_find_first_bit(array->bitmap);
2742 queue = array->queue + idx;
2743 next = list_entry(queue->next, task_t, run_list);
2745 if (!rt_task(next) && next->activated > 0) {
2746 unsigned long long delta = now - next->timestamp;
2748 if (next->activated == 1)
2749 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
2751 array = next->array;
2752 dequeue_task(next, array);
2753 recalc_task_prio(next, next->timestamp + delta);
2754 enqueue_task(next, array);
2756 next->activated = 0;
2759 clear_tsk_need_resched(prev);
2760 rcu_qsctr_inc(task_cpu(prev));
2762 prev->sleep_avg -= run_time;
2763 if ((long)prev->sleep_avg <= 0) {
2764 prev->sleep_avg = 0;
2765 if (!(HIGH_CREDIT(prev) || LOW_CREDIT(prev)))
2766 prev->interactive_credit--;
2768 prev->timestamp = prev->last_ran = now;
2770 sched_info_switch(prev, next);
2771 if (likely(prev != next)) {
2772 next->timestamp = now;
2777 prepare_arch_switch(rq, next);
2778 prev = context_switch(rq, prev, next);
2781 finish_task_switch(prev);
2783 spin_unlock_irq(&rq->lock);
2785 reacquire_kernel_lock(current);
2786 preempt_enable_no_resched();
2787 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2791 EXPORT_SYMBOL(schedule);
2793 #ifdef CONFIG_PREEMPT
2795 * this is is the entry point to schedule() from in-kernel preemption
2796 * off of preempt_enable. Kernel preemptions off return from interrupt
2797 * occur there and call schedule directly.
2799 asmlinkage void __sched preempt_schedule(void)
2801 struct thread_info *ti = current_thread_info();
2804 * If there is a non-zero preempt_count or interrupts are disabled,
2805 * we do not want to preempt the current task. Just return..
2807 if (unlikely(ti->preempt_count || irqs_disabled()))
2811 ti->preempt_count = PREEMPT_ACTIVE;
2813 ti->preempt_count = 0;
2815 /* we could miss a preemption opportunity between schedule and now */
2817 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2821 EXPORT_SYMBOL(preempt_schedule);
2822 #endif /* CONFIG_PREEMPT */
2824 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
2826 task_t *p = curr->task;
2827 return try_to_wake_up(p, mode, sync);
2830 EXPORT_SYMBOL(default_wake_function);
2833 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
2834 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
2835 * number) then we wake all the non-exclusive tasks and one exclusive task.
2837 * There are circumstances in which we can try to wake a task which has already
2838 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
2839 * zero in this (rare) case, and we handle it by continuing to scan the queue.
2841 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
2842 int nr_exclusive, int sync, void *key)
2844 struct list_head *tmp, *next;
2846 list_for_each_safe(tmp, next, &q->task_list) {
2849 curr = list_entry(tmp, wait_queue_t, task_list);
2850 flags = curr->flags;
2851 if (curr->func(curr, mode, sync, key) &&
2852 (flags & WQ_FLAG_EXCLUSIVE) &&
2859 * __wake_up - wake up threads blocked on a waitqueue.
2861 * @mode: which threads
2862 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2864 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
2865 int nr_exclusive, void *key)
2867 unsigned long flags;
2869 spin_lock_irqsave(&q->lock, flags);
2870 __wake_up_common(q, mode, nr_exclusive, 0, key);
2871 spin_unlock_irqrestore(&q->lock, flags);
2874 EXPORT_SYMBOL(__wake_up);
2877 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
2879 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
2881 __wake_up_common(q, mode, 1, 0, NULL);
2885 * __wake_up - sync- wake up threads blocked on a waitqueue.
2887 * @mode: which threads
2888 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2890 * The sync wakeup differs that the waker knows that it will schedule
2891 * away soon, so while the target thread will be woken up, it will not
2892 * be migrated to another CPU - ie. the two threads are 'synchronized'
2893 * with each other. This can prevent needless bouncing between CPUs.
2895 * On UP it can prevent extra preemption.
2897 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
2899 unsigned long flags;
2905 if (unlikely(!nr_exclusive))
2908 spin_lock_irqsave(&q->lock, flags);
2909 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
2910 spin_unlock_irqrestore(&q->lock, flags);
2912 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
2914 void fastcall complete(struct completion *x)
2916 unsigned long flags;
2918 spin_lock_irqsave(&x->wait.lock, flags);
2920 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2922 spin_unlock_irqrestore(&x->wait.lock, flags);
2924 EXPORT_SYMBOL(complete);
2926 void fastcall complete_all(struct completion *x)
2928 unsigned long flags;
2930 spin_lock_irqsave(&x->wait.lock, flags);
2931 x->done += UINT_MAX/2;
2932 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2934 spin_unlock_irqrestore(&x->wait.lock, flags);
2936 EXPORT_SYMBOL(complete_all);
2938 void fastcall __sched wait_for_completion(struct completion *x)
2941 spin_lock_irq(&x->wait.lock);
2943 DECLARE_WAITQUEUE(wait, current);
2945 wait.flags |= WQ_FLAG_EXCLUSIVE;
2946 __add_wait_queue_tail(&x->wait, &wait);
2948 __set_current_state(TASK_UNINTERRUPTIBLE);
2949 spin_unlock_irq(&x->wait.lock);
2951 spin_lock_irq(&x->wait.lock);
2953 __remove_wait_queue(&x->wait, &wait);
2956 spin_unlock_irq(&x->wait.lock);
2958 EXPORT_SYMBOL(wait_for_completion);
2960 #define SLEEP_ON_VAR \
2961 unsigned long flags; \
2962 wait_queue_t wait; \
2963 init_waitqueue_entry(&wait, current);
2965 #define SLEEP_ON_HEAD \
2966 spin_lock_irqsave(&q->lock,flags); \
2967 __add_wait_queue(q, &wait); \
2968 spin_unlock(&q->lock);
2970 #define SLEEP_ON_TAIL \
2971 spin_lock_irq(&q->lock); \
2972 __remove_wait_queue(q, &wait); \
2973 spin_unlock_irqrestore(&q->lock, flags);
2975 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
2979 current->state = TASK_INTERRUPTIBLE;
2986 EXPORT_SYMBOL(interruptible_sleep_on);
2988 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
2992 current->state = TASK_INTERRUPTIBLE;
2995 timeout = schedule_timeout(timeout);
3001 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3003 void fastcall __sched sleep_on(wait_queue_head_t *q)
3007 current->state = TASK_UNINTERRUPTIBLE;
3014 EXPORT_SYMBOL(sleep_on);
3016 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3020 current->state = TASK_UNINTERRUPTIBLE;
3023 timeout = schedule_timeout(timeout);
3029 EXPORT_SYMBOL(sleep_on_timeout);
3031 void set_user_nice(task_t *p, long nice)
3033 unsigned long flags;
3034 prio_array_t *array;
3036 int old_prio, new_prio, delta;
3038 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3041 * We have to be careful, if called from sys_setpriority(),
3042 * the task might be in the middle of scheduling on another CPU.
3044 rq = task_rq_lock(p, &flags);
3046 * The RT priorities are set via setscheduler(), but we still
3047 * allow the 'normal' nice value to be set - but as expected
3048 * it wont have any effect on scheduling until the task is
3052 p->static_prio = NICE_TO_PRIO(nice);
3057 dequeue_task(p, array);
3060 new_prio = NICE_TO_PRIO(nice);
3061 delta = new_prio - old_prio;
3062 p->static_prio = NICE_TO_PRIO(nice);
3066 enqueue_task(p, array);
3068 * If the task increased its priority or is running and
3069 * lowered its priority, then reschedule its CPU:
3071 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3072 resched_task(rq->curr);
3075 task_rq_unlock(rq, &flags);
3078 EXPORT_SYMBOL(set_user_nice);
3080 #ifdef __ARCH_WANT_SYS_NICE
3083 * sys_nice - change the priority of the current process.
3084 * @increment: priority increment
3086 * sys_setpriority is a more generic, but much slower function that
3087 * does similar things.
3089 asmlinkage long sys_nice(int increment)
3095 * Setpriority might change our priority at the same moment.
3096 * We don't have to worry. Conceptually one call occurs first
3097 * and we have a single winner.
3099 if (increment < 0) {
3100 if (!capable(CAP_SYS_NICE))
3102 if (increment < -40)
3108 nice = PRIO_TO_NICE(current->static_prio) + increment;
3114 retval = security_task_setnice(current, nice);
3118 set_user_nice(current, nice);
3125 * task_prio - return the priority value of a given task.
3126 * @p: the task in question.
3128 * This is the priority value as seen by users in /proc.
3129 * RT tasks are offset by -200. Normal tasks are centered
3130 * around 0, value goes from -16 to +15.
3132 int task_prio(const task_t *p)
3134 return p->prio - MAX_RT_PRIO;
3138 * task_nice - return the nice value of a given task.
3139 * @p: the task in question.
3141 int task_nice(const task_t *p)
3143 return TASK_NICE(p);
3146 EXPORT_SYMBOL(task_nice);
3149 * idle_cpu - is a given cpu idle currently?
3150 * @cpu: the processor in question.
3152 int idle_cpu(int cpu)
3154 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3157 EXPORT_SYMBOL_GPL(idle_cpu);
3160 * find_process_by_pid - find a process with a matching PID value.
3161 * @pid: the pid in question.
3163 static inline task_t *find_process_by_pid(pid_t pid)
3165 return pid ? find_task_by_pid(pid) : current;
3168 /* Actually do priority change: must hold rq lock. */
3169 static void __setscheduler(struct task_struct *p, int policy, int prio)
3173 p->rt_priority = prio;
3174 if (policy != SCHED_NORMAL)
3175 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
3177 p->prio = p->static_prio;
3181 * setscheduler - change the scheduling policy and/or RT priority of a thread.
3183 static int setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3185 struct sched_param lp;
3186 int retval = -EINVAL;
3188 prio_array_t *array;
3189 unsigned long flags;
3193 if (!param || pid < 0)
3197 if (copy_from_user(&lp, param, sizeof(struct sched_param)))
3201 * We play safe to avoid deadlocks.
3203 read_lock_irq(&tasklist_lock);
3205 p = find_process_by_pid(pid);
3209 goto out_unlock_tasklist;
3212 * To be able to change p->policy safely, the apropriate
3213 * runqueue lock must be held.
3215 rq = task_rq_lock(p, &flags);
3221 if (policy != SCHED_FIFO && policy != SCHED_RR &&
3222 policy != SCHED_NORMAL)
3225 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3228 * Valid priorities for SCHED_FIFO and SCHED_RR are
3229 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
3232 if (lp.sched_priority < 0 || lp.sched_priority > MAX_USER_RT_PRIO-1)
3234 if ((policy == SCHED_NORMAL) != (lp.sched_priority == 0))
3238 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
3239 !capable(CAP_SYS_NICE))
3241 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3242 !capable(CAP_SYS_NICE))
3245 retval = security_task_setscheduler(p, policy, &lp);
3251 deactivate_task(p, task_rq(p));
3254 __setscheduler(p, policy, lp.sched_priority);
3256 __activate_task(p, task_rq(p));
3258 * Reschedule if we are currently running on this runqueue and
3259 * our priority decreased, or if we are not currently running on
3260 * this runqueue and our priority is higher than the current's
3262 if (task_running(rq, p)) {
3263 if (p->prio > oldprio)
3264 resched_task(rq->curr);
3265 } else if (TASK_PREEMPTS_CURR(p, rq))
3266 resched_task(rq->curr);
3270 task_rq_unlock(rq, &flags);
3271 out_unlock_tasklist:
3272 read_unlock_irq(&tasklist_lock);
3279 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3280 * @pid: the pid in question.
3281 * @policy: new policy
3282 * @param: structure containing the new RT priority.
3284 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3285 struct sched_param __user *param)
3287 return setscheduler(pid, policy, param);
3291 * sys_sched_setparam - set/change the RT priority of a thread
3292 * @pid: the pid in question.
3293 * @param: structure containing the new RT priority.
3295 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3297 return setscheduler(pid, -1, param);
3301 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3302 * @pid: the pid in question.
3304 asmlinkage long sys_sched_getscheduler(pid_t pid)
3306 int retval = -EINVAL;
3313 read_lock(&tasklist_lock);
3314 p = find_process_by_pid(pid);
3316 retval = security_task_getscheduler(p);
3320 read_unlock(&tasklist_lock);
3327 * sys_sched_getscheduler - get the RT priority of a thread
3328 * @pid: the pid in question.
3329 * @param: structure containing the RT priority.
3331 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3333 struct sched_param lp;
3334 int retval = -EINVAL;
3337 if (!param || pid < 0)
3340 read_lock(&tasklist_lock);
3341 p = find_process_by_pid(pid);
3346 retval = security_task_getscheduler(p);
3350 lp.sched_priority = p->rt_priority;
3351 read_unlock(&tasklist_lock);
3354 * This one might sleep, we cannot do it with a spinlock held ...
3356 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3362 read_unlock(&tasklist_lock);
3366 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
3372 read_lock(&tasklist_lock);
3374 p = find_process_by_pid(pid);
3376 read_unlock(&tasklist_lock);
3377 unlock_cpu_hotplug();
3382 * It is not safe to call set_cpus_allowed with the
3383 * tasklist_lock held. We will bump the task_struct's
3384 * usage count and then drop tasklist_lock.
3387 read_unlock(&tasklist_lock);
3390 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3391 !capable(CAP_SYS_NICE))
3394 retval = set_cpus_allowed(p, new_mask);
3398 unlock_cpu_hotplug();
3402 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
3403 cpumask_t *new_mask)
3405 if (len < sizeof(cpumask_t)) {
3406 memset(new_mask, 0, sizeof(cpumask_t));
3407 } else if (len > sizeof(cpumask_t)) {
3408 len = sizeof(cpumask_t);
3410 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
3414 * sys_sched_setaffinity - set the cpu affinity of a process
3415 * @pid: pid of the process
3416 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3417 * @user_mask_ptr: user-space pointer to the new cpu mask
3419 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
3420 unsigned long __user *user_mask_ptr)
3425 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
3429 return sched_setaffinity(pid, new_mask);
3433 * Represents all cpu's present in the system
3434 * In systems capable of hotplug, this map could dynamically grow
3435 * as new cpu's are detected in the system via any platform specific
3436 * method, such as ACPI for e.g.
3439 cpumask_t cpu_present_map;
3440 EXPORT_SYMBOL(cpu_present_map);
3443 cpumask_t cpu_online_map = CPU_MASK_ALL;
3444 cpumask_t cpu_possible_map = CPU_MASK_ALL;
3447 long sched_getaffinity(pid_t pid, cpumask_t *mask)
3453 read_lock(&tasklist_lock);
3456 p = find_process_by_pid(pid);
3461 cpus_and(*mask, p->cpus_allowed, cpu_possible_map);
3464 read_unlock(&tasklist_lock);
3465 unlock_cpu_hotplug();
3473 * sys_sched_getaffinity - get the cpu affinity of a process
3474 * @pid: pid of the process
3475 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3476 * @user_mask_ptr: user-space pointer to hold the current cpu mask
3478 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
3479 unsigned long __user *user_mask_ptr)
3484 if (len < sizeof(cpumask_t))
3487 ret = sched_getaffinity(pid, &mask);
3491 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
3494 return sizeof(cpumask_t);
3498 * sys_sched_yield - yield the current processor to other threads.
3500 * this function yields the current CPU by moving the calling thread
3501 * to the expired array. If there are no other threads running on this
3502 * CPU then this function will return.
3504 asmlinkage long sys_sched_yield(void)
3506 runqueue_t *rq = this_rq_lock();
3507 prio_array_t *array = current->array;
3508 prio_array_t *target = rq->expired;
3510 schedstat_inc(rq, yld_cnt);
3512 * We implement yielding by moving the task into the expired
3515 * (special rule: RT tasks will just roundrobin in the active
3518 if (rt_task(current))
3519 target = rq->active;
3521 if (current->array->nr_active == 1) {
3522 schedstat_inc(rq, yld_act_empty);
3523 if (!rq->expired->nr_active)
3524 schedstat_inc(rq, yld_both_empty);
3525 } else if (!rq->expired->nr_active)
3526 schedstat_inc(rq, yld_exp_empty);
3528 dequeue_task(current, array);
3529 enqueue_task(current, target);
3532 * Since we are going to call schedule() anyway, there's
3533 * no need to preempt or enable interrupts:
3535 _raw_spin_unlock(&rq->lock);
3536 preempt_enable_no_resched();
3543 void __sched __cond_resched(void)
3545 set_current_state(TASK_RUNNING);
3549 EXPORT_SYMBOL(__cond_resched);
3552 * yield - yield the current processor to other threads.
3554 * this is a shortcut for kernel-space yielding - it marks the
3555 * thread runnable and calls sys_sched_yield().
3557 void __sched yield(void)
3559 set_current_state(TASK_RUNNING);
3563 EXPORT_SYMBOL(yield);
3566 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
3567 * that process accounting knows that this is a task in IO wait state.
3569 * But don't do that if it is a deliberate, throttling IO wait (this task
3570 * has set its backing_dev_info: the queue against which it should throttle)
3572 void __sched io_schedule(void)
3574 struct runqueue *rq = this_rq();
3576 atomic_inc(&rq->nr_iowait);
3578 atomic_dec(&rq->nr_iowait);
3581 EXPORT_SYMBOL(io_schedule);
3583 long __sched io_schedule_timeout(long timeout)
3585 struct runqueue *rq = this_rq();
3588 atomic_inc(&rq->nr_iowait);
3589 ret = schedule_timeout(timeout);
3590 atomic_dec(&rq->nr_iowait);
3595 * sys_sched_get_priority_max - return maximum RT priority.
3596 * @policy: scheduling class.
3598 * this syscall returns the maximum rt_priority that can be used
3599 * by a given scheduling class.
3601 asmlinkage long sys_sched_get_priority_max(int policy)
3608 ret = MAX_USER_RT_PRIO-1;
3618 * sys_sched_get_priority_min - return minimum RT priority.
3619 * @policy: scheduling class.
3621 * this syscall returns the minimum rt_priority that can be used
3622 * by a given scheduling class.
3624 asmlinkage long sys_sched_get_priority_min(int policy)
3640 * sys_sched_rr_get_interval - return the default timeslice of a process.
3641 * @pid: pid of the process.
3642 * @interval: userspace pointer to the timeslice value.
3644 * this syscall writes the default timeslice value of a given process
3645 * into the user-space timespec buffer. A value of '0' means infinity.
3648 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
3650 int retval = -EINVAL;
3658 read_lock(&tasklist_lock);
3659 p = find_process_by_pid(pid);
3663 retval = security_task_getscheduler(p);
3667 jiffies_to_timespec(p->policy & SCHED_FIFO ?
3668 0 : task_timeslice(p), &t);
3669 read_unlock(&tasklist_lock);
3670 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
3674 read_unlock(&tasklist_lock);
3678 static inline struct task_struct *eldest_child(struct task_struct *p)
3680 if (list_empty(&p->children)) return NULL;
3681 return list_entry(p->children.next,struct task_struct,sibling);
3684 static inline struct task_struct *older_sibling(struct task_struct *p)
3686 if (p->sibling.prev==&p->parent->children) return NULL;
3687 return list_entry(p->sibling.prev,struct task_struct,sibling);
3690 static inline struct task_struct *younger_sibling(struct task_struct *p)
3692 if (p->sibling.next==&p->parent->children) return NULL;
3693 return list_entry(p->sibling.next,struct task_struct,sibling);
3696 static void show_task(task_t * p)
3700 unsigned long free = 0;
3701 static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
3703 printk("%-13.13s ", p->comm);
3704 state = p->state ? __ffs(p->state) + 1 : 0;
3705 if (state < ARRAY_SIZE(stat_nam))
3706 printk(stat_nam[state]);
3709 #if (BITS_PER_LONG == 32)
3710 if (state == TASK_RUNNING)
3711 printk(" running ");
3713 printk(" %08lX ", thread_saved_pc(p));
3715 if (state == TASK_RUNNING)
3716 printk(" running task ");
3718 printk(" %016lx ", thread_saved_pc(p));
3720 #ifdef CONFIG_DEBUG_STACK_USAGE
3722 unsigned long * n = (unsigned long *) (p->thread_info+1);
3725 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
3728 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
3729 if ((relative = eldest_child(p)))
3730 printk("%5d ", relative->pid);
3733 if ((relative = younger_sibling(p)))
3734 printk("%7d", relative->pid);
3737 if ((relative = older_sibling(p)))
3738 printk(" %5d", relative->pid);
3742 printk(" (L-TLB)\n");
3744 printk(" (NOTLB)\n");
3746 if (state != TASK_RUNNING)
3747 show_stack(p, NULL);
3750 void show_state(void)
3754 #if (BITS_PER_LONG == 32)
3757 printk(" task PC pid father child younger older\n");
3761 printk(" task PC pid father child younger older\n");
3763 read_lock(&tasklist_lock);
3764 do_each_thread(g, p) {
3766 * reset the NMI-timeout, listing all files on a slow
3767 * console might take alot of time:
3769 touch_nmi_watchdog();
3771 } while_each_thread(g, p);
3773 read_unlock(&tasklist_lock);
3776 void __devinit init_idle(task_t *idle, int cpu)
3778 runqueue_t *rq = cpu_rq(cpu);
3779 unsigned long flags;
3781 idle->sleep_avg = 0;
3782 idle->interactive_credit = 0;
3784 idle->prio = MAX_PRIO;
3785 idle->state = TASK_RUNNING;
3786 set_task_cpu(idle, cpu);
3788 spin_lock_irqsave(&rq->lock, flags);
3789 rq->curr = rq->idle = idle;
3790 set_tsk_need_resched(idle);
3791 spin_unlock_irqrestore(&rq->lock, flags);
3793 /* Set the preempt count _outside_ the spinlocks! */
3794 #ifdef CONFIG_PREEMPT
3795 idle->thread_info->preempt_count = (idle->lock_depth >= 0);
3797 idle->thread_info->preempt_count = 0;
3802 * In a system that switches off the HZ timer nohz_cpu_mask
3803 * indicates which cpus entered this state. This is used
3804 * in the rcu update to wait only for active cpus. For system
3805 * which do not switch off the HZ timer nohz_cpu_mask should
3806 * always be CPU_MASK_NONE.
3808 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
3812 * This is how migration works:
3814 * 1) we queue a migration_req_t structure in the source CPU's
3815 * runqueue and wake up that CPU's migration thread.
3816 * 2) we down() the locked semaphore => thread blocks.
3817 * 3) migration thread wakes up (implicitly it forces the migrated
3818 * thread off the CPU)
3819 * 4) it gets the migration request and checks whether the migrated
3820 * task is still in the wrong runqueue.
3821 * 5) if it's in the wrong runqueue then the migration thread removes
3822 * it and puts it into the right queue.
3823 * 6) migration thread up()s the semaphore.
3824 * 7) we wake up and the migration is done.
3828 * Change a given task's CPU affinity. Migrate the thread to a
3829 * proper CPU and schedule it away if the CPU it's executing on
3830 * is removed from the allowed bitmask.
3832 * NOTE: the caller must have a valid reference to the task, the
3833 * task must not exit() & deallocate itself prematurely. The
3834 * call is not atomic; no spinlocks may be held.
3836 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
3838 unsigned long flags;
3840 migration_req_t req;
3843 rq = task_rq_lock(p, &flags);
3844 if (!cpus_intersects(new_mask, cpu_online_map)) {
3849 p->cpus_allowed = new_mask;
3850 /* Can the task run on the task's current CPU? If so, we're done */
3851 if (cpu_isset(task_cpu(p), new_mask))
3854 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
3855 /* Need help from migration thread: drop lock and wait. */
3856 task_rq_unlock(rq, &flags);
3857 wake_up_process(rq->migration_thread);
3858 wait_for_completion(&req.done);
3859 tlb_migrate_finish(p->mm);
3863 task_rq_unlock(rq, &flags);
3867 EXPORT_SYMBOL_GPL(set_cpus_allowed);
3870 * Move (not current) task off this cpu, onto dest cpu. We're doing
3871 * this because either it can't run here any more (set_cpus_allowed()
3872 * away from this CPU, or CPU going down), or because we're
3873 * attempting to rebalance this task on exec (sched_exec).
3875 * So we race with normal scheduler movements, but that's OK, as long
3876 * as the task is no longer on this CPU.
3878 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
3880 runqueue_t *rq_dest, *rq_src;
3882 if (unlikely(cpu_is_offline(dest_cpu)))
3885 rq_src = cpu_rq(src_cpu);
3886 rq_dest = cpu_rq(dest_cpu);
3888 double_rq_lock(rq_src, rq_dest);
3889 /* Already moved. */
3890 if (task_cpu(p) != src_cpu)
3892 /* Affinity changed (again). */
3893 if (!cpu_isset(dest_cpu, p->cpus_allowed))
3896 set_task_cpu(p, dest_cpu);
3899 * Sync timestamp with rq_dest's before activating.
3900 * The same thing could be achieved by doing this step
3901 * afterwards, and pretending it was a local activate.
3902 * This way is cleaner and logically correct.
3904 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
3905 + rq_dest->timestamp_last_tick;
3906 deactivate_task(p, rq_src);
3907 activate_task(p, rq_dest, 0);
3908 if (TASK_PREEMPTS_CURR(p, rq_dest))
3909 resched_task(rq_dest->curr);
3913 double_rq_unlock(rq_src, rq_dest);
3917 * migration_thread - this is a highprio system thread that performs
3918 * thread migration by bumping thread off CPU then 'pushing' onto
3921 static int migration_thread(void * data)
3924 int cpu = (long)data;
3927 BUG_ON(rq->migration_thread != current);
3929 set_current_state(TASK_INTERRUPTIBLE);
3930 while (!kthread_should_stop()) {
3931 struct list_head *head;
3932 migration_req_t *req;
3934 if (current->flags & PF_FREEZE)
3935 refrigerator(PF_FREEZE);
3937 spin_lock_irq(&rq->lock);
3939 if (cpu_is_offline(cpu)) {
3940 spin_unlock_irq(&rq->lock);
3944 if (rq->active_balance) {
3945 active_load_balance(rq, cpu);
3946 rq->active_balance = 0;
3949 head = &rq->migration_queue;
3951 if (list_empty(head)) {
3952 spin_unlock_irq(&rq->lock);
3954 set_current_state(TASK_INTERRUPTIBLE);
3957 req = list_entry(head->next, migration_req_t, list);
3958 list_del_init(head->next);
3960 if (req->type == REQ_MOVE_TASK) {
3961 spin_unlock(&rq->lock);
3962 __migrate_task(req->task, smp_processor_id(),
3965 } else if (req->type == REQ_SET_DOMAIN) {
3967 spin_unlock_irq(&rq->lock);
3969 spin_unlock_irq(&rq->lock);
3973 complete(&req->done);
3975 __set_current_state(TASK_RUNNING);
3979 /* Wait for kthread_stop */
3980 set_current_state(TASK_INTERRUPTIBLE);
3981 while (!kthread_should_stop()) {
3983 set_current_state(TASK_INTERRUPTIBLE);
3985 __set_current_state(TASK_RUNNING);
3989 #ifdef CONFIG_HOTPLUG_CPU
3990 /* Figure out where task on dead CPU should go, use force if neccessary. */
3991 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
3997 mask = node_to_cpumask(cpu_to_node(dead_cpu));
3998 cpus_and(mask, mask, tsk->cpus_allowed);
3999 dest_cpu = any_online_cpu(mask);
4001 /* On any allowed CPU? */
4002 if (dest_cpu == NR_CPUS)
4003 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4005 /* No more Mr. Nice Guy. */
4006 if (dest_cpu == NR_CPUS) {
4007 cpus_setall(tsk->cpus_allowed);
4008 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4011 * Don't tell them about moving exiting tasks or
4012 * kernel threads (both mm NULL), since they never
4015 if (tsk->mm && printk_ratelimit())
4016 printk(KERN_INFO "process %d (%s) no "
4017 "longer affine to cpu%d\n",
4018 tsk->pid, tsk->comm, dead_cpu);
4020 __migrate_task(tsk, dead_cpu, dest_cpu);
4023 /* Run through task list and migrate tasks from the dead cpu. */
4024 static void migrate_live_tasks(int src_cpu)
4026 struct task_struct *tsk, *t;
4028 write_lock_irq(&tasklist_lock);
4030 do_each_thread(t, tsk) {
4034 if (task_cpu(tsk) == src_cpu)
4035 move_task_off_dead_cpu(src_cpu, tsk);
4036 } while_each_thread(t, tsk);
4038 write_unlock_irq(&tasklist_lock);
4041 /* Schedules idle task to be the next runnable task on current CPU.
4042 * It does so by boosting its priority to highest possible and adding it to
4043 * the _front_ of runqueue. Used by CPU offline code.
4045 void sched_idle_next(void)
4047 int cpu = smp_processor_id();
4048 runqueue_t *rq = this_rq();
4049 struct task_struct *p = rq->idle;
4050 unsigned long flags;
4052 /* cpu has to be offline */
4053 BUG_ON(cpu_online(cpu));
4055 /* Strictly not necessary since rest of the CPUs are stopped by now
4056 * and interrupts disabled on current cpu.
4058 spin_lock_irqsave(&rq->lock, flags);
4060 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4061 /* Add idle task to _front_ of it's priority queue */
4062 __activate_idle_task(p, rq);
4064 spin_unlock_irqrestore(&rq->lock, flags);
4067 static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
4069 struct runqueue *rq = cpu_rq(dead_cpu);
4071 /* Must be exiting, otherwise would be on tasklist. */
4072 BUG_ON(tsk->state != TASK_ZOMBIE && tsk->state != TASK_DEAD);
4074 /* Cannot have done final schedule yet: would have vanished. */
4075 BUG_ON(tsk->flags & PF_DEAD);
4077 get_task_struct(tsk);
4080 * Drop lock around migration; if someone else moves it,
4081 * that's OK. No task can be added to this CPU, so iteration is
4084 spin_unlock_irq(&rq->lock);
4085 move_task_off_dead_cpu(dead_cpu, tsk);
4086 spin_lock_irq(&rq->lock);
4088 put_task_struct(tsk);
4091 /* release_task() removes task from tasklist, so we won't find dead tasks. */
4092 static void migrate_dead_tasks(unsigned int dead_cpu)
4095 struct runqueue *rq = cpu_rq(dead_cpu);
4097 for (arr = 0; arr < 2; arr++) {
4098 for (i = 0; i < MAX_PRIO; i++) {
4099 struct list_head *list = &rq->arrays[arr].queue[i];
4100 while (!list_empty(list))
4101 migrate_dead(dead_cpu,
4102 list_entry(list->next, task_t,
4107 #endif /* CONFIG_HOTPLUG_CPU */
4110 * migration_call - callback that gets triggered when a CPU is added.
4111 * Here we can start up the necessary migration thread for the new CPU.
4113 static int migration_call(struct notifier_block *nfb, unsigned long action,
4116 int cpu = (long)hcpu;
4117 struct task_struct *p;
4118 struct runqueue *rq;
4119 unsigned long flags;
4122 case CPU_UP_PREPARE:
4123 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4126 p->flags |= PF_NOFREEZE;
4127 kthread_bind(p, cpu);
4128 /* Must be high prio: stop_machine expects to yield to it. */
4129 rq = task_rq_lock(p, &flags);
4130 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4131 task_rq_unlock(rq, &flags);
4132 cpu_rq(cpu)->migration_thread = p;
4135 /* Strictly unneccessary, as first user will wake it. */
4136 wake_up_process(cpu_rq(cpu)->migration_thread);
4138 #ifdef CONFIG_HOTPLUG_CPU
4139 case CPU_UP_CANCELED:
4140 /* Unbind it from offline cpu so it can run. Fall thru. */
4141 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
4142 kthread_stop(cpu_rq(cpu)->migration_thread);
4143 cpu_rq(cpu)->migration_thread = NULL;
4146 migrate_live_tasks(cpu);
4148 kthread_stop(rq->migration_thread);
4149 rq->migration_thread = NULL;
4150 /* Idle task back to normal (off runqueue, low prio) */
4151 rq = task_rq_lock(rq->idle, &flags);
4152 deactivate_task(rq->idle, rq);
4153 rq->idle->static_prio = MAX_PRIO;
4154 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4155 migrate_dead_tasks(cpu);
4156 task_rq_unlock(rq, &flags);
4157 BUG_ON(rq->nr_running != 0);
4159 /* No need to migrate the tasks: it was best-effort if
4160 * they didn't do lock_cpu_hotplug(). Just wake up
4161 * the requestors. */
4162 spin_lock_irq(&rq->lock);
4163 while (!list_empty(&rq->migration_queue)) {
4164 migration_req_t *req;
4165 req = list_entry(rq->migration_queue.next,
4166 migration_req_t, list);
4167 BUG_ON(req->type != REQ_MOVE_TASK);
4168 list_del_init(&req->list);
4169 complete(&req->done);
4171 spin_unlock_irq(&rq->lock);
4178 /* Register at highest priority so that task migration (migrate_all_tasks)
4179 * happens before everything else.
4181 static struct notifier_block __devinitdata migration_notifier = {
4182 .notifier_call = migration_call,
4186 int __init migration_init(void)
4188 void *cpu = (void *)(long)smp_processor_id();
4189 /* Start one for boot CPU. */
4190 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4191 migration_call(&migration_notifier, CPU_ONLINE, cpu);
4192 register_cpu_notifier(&migration_notifier);
4198 * The 'big kernel lock'
4200 * This spinlock is taken and released recursively by lock_kernel()
4201 * and unlock_kernel(). It is transparently dropped and reaquired
4202 * over schedule(). It is used to protect legacy code that hasn't
4203 * been migrated to a proper locking design yet.
4205 * Don't use in new code.
4207 * Note: spinlock debugging needs this even on !CONFIG_SMP.
4209 spinlock_t kernel_flag __cacheline_aligned_in_smp = SPIN_LOCK_UNLOCKED;
4210 EXPORT_SYMBOL(kernel_flag);
4213 /* Attach the domain 'sd' to 'cpu' as its base domain */
4214 static void cpu_attach_domain(struct sched_domain *sd, int cpu)
4216 migration_req_t req;
4217 unsigned long flags;
4218 runqueue_t *rq = cpu_rq(cpu);
4223 spin_lock_irqsave(&rq->lock, flags);
4225 if (cpu == smp_processor_id() || !cpu_online(cpu)) {
4228 init_completion(&req.done);
4229 req.type = REQ_SET_DOMAIN;
4231 list_add(&req.list, &rq->migration_queue);
4235 spin_unlock_irqrestore(&rq->lock, flags);
4238 wake_up_process(rq->migration_thread);
4239 wait_for_completion(&req.done);
4242 unlock_cpu_hotplug();
4246 * To enable disjoint top-level NUMA domains, define SD_NODES_PER_DOMAIN
4247 * in arch code. That defines the number of nearby nodes in a node's top
4248 * level scheduling domain.
4250 #if defined(CONFIG_NUMA) && defined(SD_NODES_PER_DOMAIN)
4252 * find_next_best_node - find the next node to include in a sched_domain
4253 * @node: node whose sched_domain we're building
4254 * @used_nodes: nodes already in the sched_domain
4256 * Find the next node to include in a given scheduling domain. Simply
4257 * finds the closest node not already in the @used_nodes map.
4259 * Should use nodemask_t.
4261 static int __init find_next_best_node(int node, unsigned long *used_nodes)
4263 int i, n, val, min_val, best_node = 0;
4267 for (i = 0; i < numnodes; i++) {
4268 /* Start at @node */
4269 n = (node + i) % numnodes;
4271 /* Skip already used nodes */
4272 if (test_bit(n, used_nodes))
4275 /* Simple min distance search */
4276 val = node_distance(node, i);
4278 if (val < min_val) {
4284 set_bit(best_node, used_nodes);
4289 * sched_domain_node_span - get a cpumask for a node's sched_domain
4290 * @node: node whose cpumask we're constructing
4291 * @size: number of nodes to include in this span
4293 * Given a node, construct a good cpumask for its sched_domain to span. It
4294 * should be one that prevents unnecessary balancing, but also spreads tasks
4297 cpumask_t __init sched_domain_node_span(int node)
4301 DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
4304 bitmap_zero(used_nodes, MAX_NUMNODES);
4306 for (i = 0; i < SD_NODES_PER_DOMAIN; i++) {
4307 int next_node = find_next_best_node(node, used_nodes);
4310 nodemask = node_to_cpumask(next_node);
4311 cpus_or(span, span, nodemask);
4316 #else /* CONFIG_NUMA && SD_NODES_PER_DOMAIN */
4317 cpumask_t __init sched_domain_node_span(int node)
4319 return cpu_possible_map;
4321 #endif /* CONFIG_NUMA && SD_NODES_PER_DOMAIN */
4323 #ifdef CONFIG_SCHED_SMT
4324 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
4325 static struct sched_group sched_group_cpus[NR_CPUS];
4326 __init static int cpu_to_cpu_group(int cpu)
4332 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
4333 static struct sched_group sched_group_phys[NR_CPUS];
4334 __init static int cpu_to_phys_group(int cpu)
4336 #ifdef CONFIG_SCHED_SMT
4337 return first_cpu(cpu_sibling_map[cpu]);
4345 static DEFINE_PER_CPU(struct sched_domain, node_domains);
4346 static struct sched_group sched_group_nodes[MAX_NUMNODES];
4347 __init static int cpu_to_node_group(int cpu)
4349 return cpu_to_node(cpu);
4353 /* Groups for isolated scheduling domains */
4354 static struct sched_group sched_group_isolated[NR_CPUS];
4356 /* cpus with isolated domains */
4357 cpumask_t __initdata cpu_isolated_map = CPU_MASK_NONE;
4359 __init static int cpu_to_isolated_group(int cpu)
4364 /* Setup the mask of cpus configured for isolated domains */
4365 static int __init isolated_cpu_setup(char *str)
4367 int ints[NR_CPUS], i;
4369 str = get_options(str, ARRAY_SIZE(ints), ints);
4370 cpus_clear(cpu_isolated_map);
4371 for (i = 1; i <= ints[0]; i++)
4372 cpu_set(ints[i], cpu_isolated_map);
4376 __setup ("isolcpus=", isolated_cpu_setup);
4379 * init_sched_build_groups takes an array of groups, the cpumask we wish
4380 * to span, and a pointer to a function which identifies what group a CPU
4381 * belongs to. The return value of group_fn must be a valid index into the
4382 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
4383 * keep track of groups covered with a cpumask_t).
4385 * init_sched_build_groups will build a circular linked list of the groups
4386 * covered by the given span, and will set each group's ->cpumask correctly,
4387 * and ->cpu_power to 0.
4389 __init static void init_sched_build_groups(struct sched_group groups[],
4390 cpumask_t span, int (*group_fn)(int cpu))
4392 struct sched_group *first = NULL, *last = NULL;
4393 cpumask_t covered = CPU_MASK_NONE;
4396 for_each_cpu_mask(i, span) {
4397 int group = group_fn(i);
4398 struct sched_group *sg = &groups[group];
4401 if (cpu_isset(i, covered))
4404 sg->cpumask = CPU_MASK_NONE;
4407 for_each_cpu_mask(j, span) {
4408 if (group_fn(j) != group)
4411 cpu_set(j, covered);
4412 cpu_set(j, sg->cpumask);
4423 __init static void arch_init_sched_domains(void)
4426 cpumask_t cpu_default_map;
4429 * Setup mask for cpus without special case scheduling requirements.
4430 * For now this just excludes isolated cpus, but could be used to
4431 * exclude other special cases in the future.
4433 cpus_complement(cpu_default_map, cpu_isolated_map);
4434 cpus_and(cpu_default_map, cpu_default_map, cpu_possible_map);
4436 /* Set up domains */
4439 struct sched_domain *sd = NULL, *p;
4440 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
4442 cpus_and(nodemask, nodemask, cpu_default_map);
4445 * Set up isolated domains.
4446 * Unlike those of other cpus, the domains and groups are
4447 * single level, and span a single cpu.
4449 if (cpu_isset(i, cpu_isolated_map)) {
4450 #ifdef CONFIG_SCHED_SMT
4451 sd = &per_cpu(cpu_domains, i);
4453 sd = &per_cpu(phys_domains, i);
4455 group = cpu_to_isolated_group(i);
4457 cpu_set(i, sd->span);
4458 sd->balance_interval = INT_MAX; /* Don't balance */
4459 sd->flags = 0; /* Avoid WAKE_ */
4460 sd->groups = &sched_group_isolated[group];
4461 printk(KERN_INFO "Setting up cpu %d isolated.\n", i);
4462 /* Single level, so continue with next cpu */
4467 sd = &per_cpu(node_domains, i);
4468 group = cpu_to_node_group(i);
4470 /* FIXME: should be multilevel, in arch code */
4471 sd->span = sched_domain_node_span(i);
4472 cpus_and(sd->span, sd->span, cpu_default_map);
4473 sd->groups = &sched_group_nodes[group];
4477 sd = &per_cpu(phys_domains, i);
4478 group = cpu_to_phys_group(i);
4481 sd->span = nodemask;
4483 sd->span = cpu_possible_map;
4486 sd->groups = &sched_group_phys[group];
4488 #ifdef CONFIG_SCHED_SMT
4490 sd = &per_cpu(cpu_domains, i);
4491 group = cpu_to_cpu_group(i);
4492 *sd = SD_SIBLING_INIT;
4493 sd->span = cpu_sibling_map[i];
4494 cpus_and(sd->span, sd->span, cpu_default_map);
4496 sd->groups = &sched_group_cpus[group];
4500 #ifdef CONFIG_SCHED_SMT
4501 /* Set up CPU (sibling) groups */
4503 cpumask_t this_sibling_map = cpu_sibling_map[i];
4504 cpus_and(this_sibling_map, this_sibling_map, cpu_default_map);
4505 if (i != first_cpu(this_sibling_map))
4508 init_sched_build_groups(sched_group_cpus, this_sibling_map,
4513 /* Set up isolated groups */
4514 for_each_cpu_mask(i, cpu_isolated_map) {
4518 init_sched_build_groups(sched_group_isolated, mask,
4519 &cpu_to_isolated_group);
4523 /* Set up physical groups */
4524 for (i = 0; i < MAX_NUMNODES; i++) {
4525 cpumask_t nodemask = node_to_cpumask(i);
4527 cpus_and(nodemask, nodemask, cpu_default_map);
4528 if (cpus_empty(nodemask))
4531 init_sched_build_groups(sched_group_phys, nodemask,
4532 &cpu_to_phys_group);
4535 init_sched_build_groups(sched_group_phys, cpu_possible_map,
4536 &cpu_to_phys_group);
4540 /* Set up node groups */
4541 init_sched_build_groups(sched_group_nodes, cpu_default_map,
4542 &cpu_to_node_group);
4545 /* Calculate CPU power for physical packages and nodes */
4546 for_each_cpu_mask(i, cpu_default_map) {
4548 struct sched_domain *sd;
4549 #ifdef CONFIG_SCHED_SMT
4550 sd = &per_cpu(cpu_domains, i);
4551 power = SCHED_LOAD_SCALE;
4552 sd->groups->cpu_power = power;
4555 sd = &per_cpu(phys_domains, i);
4556 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
4557 (cpus_weight(sd->groups->cpumask)-1) / 10;
4558 sd->groups->cpu_power = power;
4561 if (i == first_cpu(sd->groups->cpumask)) {
4562 /* Only add "power" once for each physical package. */
4563 sd = &per_cpu(node_domains, i);
4564 sd->groups->cpu_power += power;
4569 /* Attach the domains */
4571 struct sched_domain *sd;
4572 #ifdef CONFIG_SCHED_SMT
4573 sd = &per_cpu(cpu_domains, i);
4575 sd = &per_cpu(phys_domains, i);
4577 cpu_attach_domain(sd, i);
4581 #undef SCHED_DOMAIN_DEBUG
4582 #ifdef SCHED_DOMAIN_DEBUG
4583 void sched_domain_debug(void)
4588 runqueue_t *rq = cpu_rq(i);
4589 struct sched_domain *sd;
4594 printk(KERN_DEBUG "CPU%d: %s\n",
4595 i, (cpu_online(i) ? " online" : "offline"));
4600 struct sched_group *group = sd->groups;
4601 cpumask_t groupmask;
4603 cpumask_scnprintf(str, NR_CPUS, sd->span);
4604 cpus_clear(groupmask);
4607 for (j = 0; j < level + 1; j++)
4609 printk("domain %d: span %s\n", level, str);
4611 if (!cpu_isset(i, sd->span))
4612 printk(KERN_DEBUG "ERROR domain->span does not contain CPU%d\n", i);
4613 if (!cpu_isset(i, group->cpumask))
4614 printk(KERN_DEBUG "ERROR domain->groups does not contain CPU%d\n", i);
4615 if (!group->cpu_power)
4616 printk(KERN_DEBUG "ERROR domain->cpu_power not set\n");
4619 for (j = 0; j < level + 2; j++)
4624 printk(" ERROR: NULL");
4628 if (!cpus_weight(group->cpumask))
4629 printk(" ERROR empty group:");
4631 if (cpus_intersects(groupmask, group->cpumask))
4632 printk(" ERROR repeated CPUs:");
4634 cpus_or(groupmask, groupmask, group->cpumask);
4636 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
4639 group = group->next;
4640 } while (group != sd->groups);
4643 if (!cpus_equal(sd->span, groupmask))
4644 printk(KERN_DEBUG "ERROR groups don't span domain->span\n");
4650 if (!cpus_subset(groupmask, sd->span))
4651 printk(KERN_DEBUG "ERROR parent span is not a superset of domain->span\n");
4658 #define sched_domain_debug() {}
4661 void __init sched_init_smp(void)
4663 arch_init_sched_domains();
4664 sched_domain_debug();
4667 void __init sched_init_smp(void)
4670 #endif /* CONFIG_SMP */
4672 int in_sched_functions(unsigned long addr)
4674 /* Linker adds these: start and end of __sched functions */
4675 extern char __sched_text_start[], __sched_text_end[];
4676 return in_lock_functions(addr) ||
4677 (addr >= (unsigned long)__sched_text_start
4678 && addr < (unsigned long)__sched_text_end);
4681 void __init sched_init(void)
4687 /* Set up an initial dummy domain for early boot */
4688 static struct sched_domain sched_domain_init;
4689 static struct sched_group sched_group_init;
4691 memset(&sched_domain_init, 0, sizeof(struct sched_domain));
4692 sched_domain_init.span = CPU_MASK_ALL;
4693 sched_domain_init.groups = &sched_group_init;
4694 sched_domain_init.last_balance = jiffies;
4695 sched_domain_init.balance_interval = INT_MAX; /* Don't balance */
4696 sched_domain_init.busy_factor = 1;
4698 memset(&sched_group_init, 0, sizeof(struct sched_group));
4699 sched_group_init.cpumask = CPU_MASK_ALL;
4700 sched_group_init.next = &sched_group_init;
4701 sched_group_init.cpu_power = SCHED_LOAD_SCALE;
4704 for (i = 0; i < NR_CPUS; i++) {
4705 prio_array_t *array;
4708 spin_lock_init(&rq->lock);
4709 rq->active = rq->arrays;
4710 rq->expired = rq->arrays + 1;
4711 rq->best_expired_prio = MAX_PRIO;
4714 rq->sd = &sched_domain_init;
4716 rq->active_balance = 0;
4718 rq->migration_thread = NULL;
4719 INIT_LIST_HEAD(&rq->migration_queue);
4721 atomic_set(&rq->nr_iowait, 0);
4723 for (j = 0; j < 2; j++) {
4724 array = rq->arrays + j;
4725 for (k = 0; k < MAX_PRIO; k++) {
4726 INIT_LIST_HEAD(array->queue + k);
4727 __clear_bit(k, array->bitmap);
4729 // delimiter for bitsearch
4730 __set_bit(MAX_PRIO, array->bitmap);
4735 * The boot idle thread does lazy MMU switching as well:
4737 atomic_inc(&init_mm.mm_count);
4738 enter_lazy_tlb(&init_mm, current);
4741 * Make us the idle thread. Technically, schedule() should not be
4742 * called from this thread, however somewhere below it might be,
4743 * but because we are the idle thread, we just pick up running again
4744 * when this runqueue becomes "idle".
4746 init_idle(current, smp_processor_id());
4749 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4750 void __might_sleep(char *file, int line)
4752 #if defined(in_atomic)
4753 static unsigned long prev_jiffy; /* ratelimiting */
4755 if ((in_atomic() || irqs_disabled()) &&
4756 system_state == SYSTEM_RUNNING) {
4757 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
4759 prev_jiffy = jiffies;
4760 printk(KERN_ERR "Debug: sleeping function called from invalid"
4761 " context at %s:%d\n", file, line);
4762 printk("in_atomic():%d, irqs_disabled():%d\n",
4763 in_atomic(), irqs_disabled());
4768 EXPORT_SYMBOL(__might_sleep);