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>
46 #include <linux/vserver/sched.h>
47 #include <linux/vs_base.h>
48 #include <linux/vs_context.h>
49 #include <linux/vs_cvirt.h>
52 #include <asm/unistd.h>
55 #define cpu_to_node_mask(cpu) node_to_cpumask(cpu_to_node(cpu))
57 #define cpu_to_node_mask(cpu) (cpu_online_map)
61 * Convert user-nice values [ -20 ... 0 ... 19 ]
62 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
65 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
66 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
67 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
70 * 'User priority' is the nice value converted to something we
71 * can work with better when scaling various scheduler parameters,
72 * it's a [ 0 ... 39 ] range.
74 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
75 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
76 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
79 * Some helpers for converting nanosecond timing to jiffy resolution
81 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
82 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
85 * These are the 'tuning knobs' of the scheduler:
87 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
88 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
89 * Timeslices get refilled after they expire.
91 #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
92 #define DEF_TIMESLICE (100 * HZ / 1000)
93 #define ON_RUNQUEUE_WEIGHT 30
94 #define CHILD_PENALTY 95
95 #define PARENT_PENALTY 100
97 #define PRIO_BONUS_RATIO 25
98 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
99 #define INTERACTIVE_DELTA 2
100 #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
101 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
102 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
103 #define CREDIT_LIMIT 100
106 * If a task is 'interactive' then we reinsert it in the active
107 * array after it has expired its current timeslice. (it will not
108 * continue to run immediately, it will still roundrobin with
109 * other interactive tasks.)
111 * This part scales the interactivity limit depending on niceness.
113 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
114 * Here are a few examples of different nice levels:
116 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
117 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
118 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
119 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
120 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
122 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
123 * priority range a task can explore, a value of '1' means the
124 * task is rated interactive.)
126 * Ie. nice +19 tasks can never get 'interactive' enough to be
127 * reinserted into the active array. And only heavily CPU-hog nice -20
128 * tasks will be expired. Default nice 0 tasks are somewhere between,
129 * it takes some effort for them to get interactive, but it's not
133 #define CURRENT_BONUS(p) \
134 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
138 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
139 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
142 #define TIMESLICE_GRANULARITY(p) (MIN_TIMESLICE * \
143 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
146 #define SCALE(v1,v1_max,v2_max) \
147 (v1) * (v2_max) / (v1_max)
150 (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
152 #define TASK_INTERACTIVE(p) \
153 ((p)->prio <= (p)->static_prio - DELTA(p))
155 #define INTERACTIVE_SLEEP(p) \
156 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
157 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
159 #define HIGH_CREDIT(p) \
160 ((p)->interactive_credit > CREDIT_LIMIT)
162 #define LOW_CREDIT(p) \
163 ((p)->interactive_credit < -CREDIT_LIMIT)
165 #define TASK_PREEMPTS_CURR(p, rq) \
166 ((p)->prio < (rq)->curr->prio)
169 * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
170 * to time slice values: [800ms ... 100ms ... 5ms]
172 * The higher a thread's priority, the bigger timeslices
173 * it gets during one round of execution. But even the lowest
174 * priority thread gets MIN_TIMESLICE worth of execution time.
177 #define SCALE_PRIO(x, prio) \
178 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO/2), MIN_TIMESLICE)
180 static unsigned int task_timeslice(task_t *p)
182 if (p->static_prio < NICE_TO_PRIO(0))
183 return SCALE_PRIO(DEF_TIMESLICE*4, p->static_prio);
185 return SCALE_PRIO(DEF_TIMESLICE, p->static_prio);
187 #define task_hot(p, now, sd) ((long long) ((now) - (p)->last_ran) \
188 < (long long) (sd)->cache_hot_time)
201 * These are the runqueue data structures:
204 #define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
206 typedef struct runqueue runqueue_t;
209 unsigned int nr_active;
210 unsigned long bitmap[BITMAP_SIZE];
211 struct list_head queue[MAX_PRIO];
215 * This is the main, per-CPU runqueue data structure.
217 * Locking rule: those places that want to lock multiple runqueues
218 * (such as the load balancing or the thread migration code), lock
219 * acquire operations must be ordered by ascending &runqueue.
225 * nr_running and cpu_load should be in the same cacheline because
226 * remote CPUs use both these fields when doing load calculation.
228 unsigned long nr_running;
230 unsigned long cpu_load;
232 unsigned long long nr_switches;
233 unsigned long expired_timestamp, nr_uninterruptible;
234 unsigned long long timestamp_last_tick;
236 struct mm_struct *prev_mm;
237 prio_array_t *active, *expired, arrays[2];
238 int best_expired_prio;
242 struct sched_domain *sd;
244 /* For active balancing */
248 task_t *migration_thread;
249 struct list_head migration_queue;
251 #ifdef CONFIG_VSERVER_HARDCPU
252 struct list_head hold_queue;
256 #ifdef CONFIG_SCHEDSTATS
258 struct sched_info rq_sched_info;
260 /* sys_sched_yield() stats */
261 unsigned long yld_exp_empty;
262 unsigned long yld_act_empty;
263 unsigned long yld_both_empty;
264 unsigned long yld_cnt;
266 /* schedule() stats */
267 unsigned long sched_noswitch;
268 unsigned long sched_switch;
269 unsigned long sched_cnt;
270 unsigned long sched_goidle;
272 /* pull_task() stats */
273 unsigned long pt_gained[MAX_IDLE_TYPES];
274 unsigned long pt_lost[MAX_IDLE_TYPES];
276 /* active_load_balance() stats */
277 unsigned long alb_cnt;
278 unsigned long alb_lost;
279 unsigned long alb_gained;
280 unsigned long alb_failed;
282 /* try_to_wake_up() stats */
283 unsigned long ttwu_cnt;
284 unsigned long ttwu_attempts;
285 unsigned long ttwu_moved;
287 /* wake_up_new_task() stats */
288 unsigned long wunt_cnt;
289 unsigned long wunt_moved;
291 /* sched_migrate_task() stats */
292 unsigned long smt_cnt;
294 /* sched_balance_exec() stats */
295 unsigned long sbe_cnt;
299 static DEFINE_PER_CPU(struct runqueue, runqueues);
302 * sched-domains (multiprocessor balancing) declarations:
305 #define SCHED_LOAD_SCALE 128UL /* increase resolution of load */
307 #define SD_BALANCE_NEWIDLE 1 /* Balance when about to become idle */
308 #define SD_BALANCE_EXEC 2 /* Balance on exec */
309 #define SD_WAKE_IDLE 4 /* Wake to idle CPU on task wakeup */
310 #define SD_WAKE_AFFINE 8 /* Wake task to waking CPU */
311 #define SD_WAKE_BALANCE 16 /* Perform balancing at task wakeup */
312 #define SD_SHARE_CPUPOWER 32 /* Domain members share cpu power */
315 struct sched_group *next; /* Must be a circular list */
319 * CPU power of this group, SCHED_LOAD_SCALE being max power for a
320 * single CPU. This should be read only (except for setup). Although
321 * it will need to be written to at cpu hot(un)plug time, perhaps the
322 * cpucontrol semaphore will provide enough exclusion?
324 unsigned long cpu_power;
327 struct sched_domain {
328 /* These fields must be setup */
329 struct sched_domain *parent; /* top domain must be null terminated */
330 struct sched_group *groups; /* the balancing groups of the domain */
331 cpumask_t span; /* span of all CPUs in this domain */
332 unsigned long min_interval; /* Minimum balance interval ms */
333 unsigned long max_interval; /* Maximum balance interval ms */
334 unsigned int busy_factor; /* less balancing by factor if busy */
335 unsigned int imbalance_pct; /* No balance until over watermark */
336 unsigned long long cache_hot_time; /* Task considered cache hot (ns) */
337 unsigned int cache_nice_tries; /* Leave cache hot tasks for # tries */
338 unsigned int per_cpu_gain; /* CPU % gained by adding domain cpus */
339 int flags; /* See SD_* */
341 /* Runtime fields. */
342 unsigned long last_balance; /* init to jiffies. units in jiffies */
343 unsigned int balance_interval; /* initialise to 1. units in ms. */
344 unsigned int nr_balance_failed; /* initialise to 0 */
346 #ifdef CONFIG_SCHEDSTATS
347 /* load_balance() stats */
348 unsigned long lb_cnt[MAX_IDLE_TYPES];
349 unsigned long lb_failed[MAX_IDLE_TYPES];
350 unsigned long lb_imbalance[MAX_IDLE_TYPES];
351 unsigned long lb_nobusyg[MAX_IDLE_TYPES];
352 unsigned long lb_nobusyq[MAX_IDLE_TYPES];
354 /* sched_balance_exec() stats */
355 unsigned long sbe_attempts;
356 unsigned long sbe_pushed;
358 /* try_to_wake_up() stats */
359 unsigned long ttwu_wake_affine;
360 unsigned long ttwu_wake_balance;
364 #ifndef ARCH_HAS_SCHED_TUNE
365 #ifdef CONFIG_SCHED_SMT
366 #define ARCH_HAS_SCHED_WAKE_IDLE
367 /* Common values for SMT siblings */
368 #define SD_SIBLING_INIT (struct sched_domain) { \
369 .span = CPU_MASK_NONE, \
375 .imbalance_pct = 110, \
376 .cache_hot_time = 0, \
377 .cache_nice_tries = 0, \
378 .per_cpu_gain = 25, \
379 .flags = SD_BALANCE_NEWIDLE \
383 | SD_SHARE_CPUPOWER, \
384 .last_balance = jiffies, \
385 .balance_interval = 1, \
386 .nr_balance_failed = 0, \
390 /* Common values for CPUs */
391 #define SD_CPU_INIT (struct sched_domain) { \
392 .span = CPU_MASK_NONE, \
398 .imbalance_pct = 125, \
399 .cache_hot_time = cache_decay_ticks*1000000 ? : (5*1000000/2),\
400 .cache_nice_tries = 1, \
401 .per_cpu_gain = 100, \
402 .flags = SD_BALANCE_NEWIDLE \
406 .last_balance = jiffies, \
407 .balance_interval = 1, \
408 .nr_balance_failed = 0, \
411 /* Arch can override this macro in processor.h */
412 #if defined(CONFIG_NUMA) && !defined(SD_NODE_INIT)
413 #define SD_NODE_INIT (struct sched_domain) { \
414 .span = CPU_MASK_NONE, \
418 .max_interval = 32, \
420 .imbalance_pct = 125, \
421 .cache_hot_time = (10*1000000), \
422 .cache_nice_tries = 1, \
423 .per_cpu_gain = 100, \
424 .flags = SD_BALANCE_EXEC \
426 .last_balance = jiffies, \
427 .balance_interval = 1, \
428 .nr_balance_failed = 0, \
431 #endif /* ARCH_HAS_SCHED_TUNE */
435 #define for_each_domain(cpu, domain) \
436 for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
438 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
439 #define this_rq() (&__get_cpu_var(runqueues))
440 #define task_rq(p) cpu_rq(task_cpu(p))
441 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
444 * Default context-switch locking:
446 #ifndef prepare_arch_switch
447 # define prepare_arch_switch(rq, next) do { } while (0)
448 # define finish_arch_switch(rq, next) spin_unlock_irq(&(rq)->lock)
449 # define task_running(rq, p) ((rq)->curr == (p))
453 * task_rq_lock - lock the runqueue a given task resides on and disable
454 * interrupts. Note the ordering: we can safely lookup the task_rq without
455 * explicitly disabling preemption.
457 static runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
462 local_irq_save(*flags);
464 spin_lock(&rq->lock);
465 if (unlikely(rq != task_rq(p))) {
466 spin_unlock_irqrestore(&rq->lock, *flags);
467 goto repeat_lock_task;
472 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
474 spin_unlock_irqrestore(&rq->lock, *flags);
477 #ifdef CONFIG_SCHEDSTATS
479 * bump this up when changing the output format or the meaning of an existing
480 * format, so that tools can adapt (or abort)
482 #define SCHEDSTAT_VERSION 10
484 static int show_schedstat(struct seq_file *seq, void *v)
487 enum idle_type itype;
489 seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
490 seq_printf(seq, "timestamp %lu\n", jiffies);
491 for_each_online_cpu(cpu) {
492 runqueue_t *rq = cpu_rq(cpu);
494 struct sched_domain *sd;
498 /* runqueue-specific stats */
500 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu "
501 "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
502 cpu, rq->yld_both_empty,
503 rq->yld_act_empty, rq->yld_exp_empty,
504 rq->yld_cnt, rq->sched_noswitch,
505 rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
506 rq->alb_cnt, rq->alb_gained, rq->alb_lost,
508 rq->ttwu_cnt, rq->ttwu_moved, rq->ttwu_attempts,
509 rq->wunt_cnt, rq->wunt_moved,
510 rq->smt_cnt, rq->sbe_cnt, rq->rq_sched_info.cpu_time,
511 rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
513 for (itype = IDLE; itype < MAX_IDLE_TYPES; itype++)
514 seq_printf(seq, " %lu %lu", rq->pt_gained[itype],
516 seq_printf(seq, "\n");
519 /* domain-specific stats */
520 for_each_domain(cpu, sd) {
521 char mask_str[NR_CPUS];
523 cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
524 seq_printf(seq, "domain%d %s", dcnt++, mask_str);
525 for (itype = IDLE; itype < MAX_IDLE_TYPES; itype++) {
526 seq_printf(seq, " %lu %lu %lu %lu %lu",
528 sd->lb_failed[itype],
529 sd->lb_imbalance[itype],
530 sd->lb_nobusyq[itype],
531 sd->lb_nobusyg[itype]);
533 seq_printf(seq, " %lu %lu %lu %lu\n",
534 sd->sbe_pushed, sd->sbe_attempts,
535 sd->ttwu_wake_affine, sd->ttwu_wake_balance);
542 static int schedstat_open(struct inode *inode, struct file *file)
544 unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
545 char *buf = kmalloc(size, GFP_KERNEL);
551 res = single_open(file, show_schedstat, NULL);
553 m = file->private_data;
561 struct file_operations proc_schedstat_operations = {
562 .open = schedstat_open,
565 .release = single_release,
568 # define schedstat_inc(rq, field) rq->field++;
569 # define schedstat_add(rq, field, amt) rq->field += amt;
570 #else /* !CONFIG_SCHEDSTATS */
571 # define schedstat_inc(rq, field) do { } while (0);
572 # define schedstat_add(rq, field, amt) do { } while (0);
576 * rq_lock - lock a given runqueue and disable interrupts.
578 static runqueue_t *this_rq_lock(void)
584 spin_lock(&rq->lock);
589 static inline void rq_unlock(runqueue_t *rq)
591 spin_unlock_irq(&rq->lock);
594 #ifdef CONFIG_SCHEDSTATS
596 * Called when a process is dequeued from the active array and given
597 * the cpu. We should note that with the exception of interactive
598 * tasks, the expired queue will become the active queue after the active
599 * queue is empty, without explicitly dequeuing and requeuing tasks in the
600 * expired queue. (Interactive tasks may be requeued directly to the
601 * active queue, thus delaying tasks in the expired queue from running;
602 * see scheduler_tick()).
604 * This function is only called from sched_info_arrive(), rather than
605 * dequeue_task(). Even though a task may be queued and dequeued multiple
606 * times as it is shuffled about, we're really interested in knowing how
607 * long it was from the *first* time it was queued to the time that it
610 static inline void sched_info_dequeued(task_t *t)
612 t->sched_info.last_queued = 0;
616 * Called when a task finally hits the cpu. We can now calculate how
617 * long it was waiting to run. We also note when it began so that we
618 * can keep stats on how long its timeslice is.
620 static inline void sched_info_arrive(task_t *t)
622 unsigned long now = jiffies, diff = 0;
623 struct runqueue *rq = task_rq(t);
625 if (t->sched_info.last_queued)
626 diff = now - t->sched_info.last_queued;
627 sched_info_dequeued(t);
628 t->sched_info.run_delay += diff;
629 t->sched_info.last_arrival = now;
630 t->sched_info.pcnt++;
635 rq->rq_sched_info.run_delay += diff;
636 rq->rq_sched_info.pcnt++;
640 * Called when a process is queued into either the active or expired
641 * array. The time is noted and later used to determine how long we
642 * had to wait for us to reach the cpu. Since the expired queue will
643 * become the active queue after active queue is empty, without dequeuing
644 * and requeuing any tasks, we are interested in queuing to either. It
645 * is unusual but not impossible for tasks to be dequeued and immediately
646 * requeued in the same or another array: this can happen in sched_yield(),
647 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
650 * This function is only called from enqueue_task(), but also only updates
651 * the timestamp if it is already not set. It's assumed that
652 * sched_info_dequeued() will clear that stamp when appropriate.
654 static inline void sched_info_queued(task_t *t)
656 if (!t->sched_info.last_queued)
657 t->sched_info.last_queued = jiffies;
661 * Called when a process ceases being the active-running process, either
662 * voluntarily or involuntarily. Now we can calculate how long we ran.
664 static inline void sched_info_depart(task_t *t)
666 struct runqueue *rq = task_rq(t);
667 unsigned long diff = jiffies - t->sched_info.last_arrival;
669 t->sched_info.cpu_time += diff;
672 rq->rq_sched_info.cpu_time += diff;
676 * Called when tasks are switched involuntarily due, typically, to expiring
677 * their time slice. (This may also be called when switching to or from
678 * the idle task.) We are only called when prev != next.
680 static inline void sched_info_switch(task_t *prev, task_t *next)
682 struct runqueue *rq = task_rq(prev);
685 * prev now departs the cpu. It's not interesting to record
686 * stats about how efficient we were at scheduling the idle
689 if (prev != rq->idle)
690 sched_info_depart(prev);
692 if (next != rq->idle)
693 sched_info_arrive(next);
696 #define sched_info_queued(t) do { } while (0)
697 #define sched_info_switch(t, next) do { } while (0)
698 #endif /* CONFIG_SCHEDSTATS */
701 * Adding/removing a task to/from a priority array:
703 static void dequeue_task(struct task_struct *p, prio_array_t *array)
706 list_del(&p->run_list);
707 if (list_empty(array->queue + p->prio))
708 __clear_bit(p->prio, array->bitmap);
711 static void enqueue_task(struct task_struct *p, prio_array_t *array)
713 sched_info_queued(p);
714 list_add_tail(&p->run_list, array->queue + p->prio);
715 __set_bit(p->prio, array->bitmap);
721 * Used by the migration code - we pull tasks from the head of the
722 * remote queue so we want these tasks to show up at the head of the
725 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
727 list_add(&p->run_list, array->queue + p->prio);
728 __set_bit(p->prio, array->bitmap);
734 * effective_prio - return the priority that is based on the static
735 * priority but is modified by bonuses/penalties.
737 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
738 * into the -5 ... 0 ... +5 bonus/penalty range.
740 * We use 25% of the full 0...39 priority range so that:
742 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
743 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
745 * Both properties are important to certain workloads.
747 static int effective_prio(task_t *p)
754 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
756 prio = p->static_prio - bonus;
757 if (task_vx_flags(p, VXF_SCHED_PRIO, 0))
758 prio += effective_vavavoom(p, MAX_USER_PRIO);
760 if (prio < MAX_RT_PRIO)
762 if (prio > MAX_PRIO-1)
768 * __activate_task - move a task to the runqueue.
770 static inline void __activate_task(task_t *p, runqueue_t *rq)
772 enqueue_task(p, rq->active);
777 * __activate_idle_task - move idle task to the _front_ of runqueue.
779 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
781 enqueue_task_head(p, rq->active);
785 static void recalc_task_prio(task_t *p, unsigned long long now)
787 unsigned long long __sleep_time = now - p->timestamp;
788 unsigned long sleep_time;
790 if (__sleep_time > NS_MAX_SLEEP_AVG)
791 sleep_time = NS_MAX_SLEEP_AVG;
793 sleep_time = (unsigned long)__sleep_time;
795 if (likely(sleep_time > 0)) {
797 * User tasks that sleep a long time are categorised as
798 * idle and will get just interactive status to stay active &
799 * prevent them suddenly becoming cpu hogs and starving
802 if (p->mm && p->activated != -1 &&
803 sleep_time > INTERACTIVE_SLEEP(p)) {
804 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
807 p->interactive_credit++;
810 * The lower the sleep avg a task has the more
811 * rapidly it will rise with sleep time.
813 sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
816 * Tasks with low interactive_credit are limited to
817 * one timeslice worth of sleep avg bonus.
820 sleep_time > JIFFIES_TO_NS(task_timeslice(p)))
821 sleep_time = JIFFIES_TO_NS(task_timeslice(p));
824 * Non high_credit tasks waking from uninterruptible
825 * sleep are limited in their sleep_avg rise as they
826 * are likely to be cpu hogs waiting on I/O
828 if (p->activated == -1 && !HIGH_CREDIT(p) && p->mm) {
829 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
831 else if (p->sleep_avg + sleep_time >=
832 INTERACTIVE_SLEEP(p)) {
833 p->sleep_avg = INTERACTIVE_SLEEP(p);
839 * This code gives a bonus to interactive tasks.
841 * The boost works by updating the 'average sleep time'
842 * value here, based on ->timestamp. The more time a
843 * task spends sleeping, the higher the average gets -
844 * and the higher the priority boost gets as well.
846 p->sleep_avg += sleep_time;
848 if (p->sleep_avg > NS_MAX_SLEEP_AVG) {
849 p->sleep_avg = NS_MAX_SLEEP_AVG;
851 p->interactive_credit++;
856 p->prio = effective_prio(p);
860 * activate_task - move a task to the runqueue and do priority recalculation
862 * Update all the scheduling statistics stuff. (sleep average
863 * calculation, priority modifiers, etc.)
865 static void activate_task(task_t *p, runqueue_t *rq, int local)
867 unsigned long long now;
872 /* Compensate for drifting sched_clock */
873 runqueue_t *this_rq = this_rq();
874 now = (now - this_rq->timestamp_last_tick)
875 + rq->timestamp_last_tick;
879 recalc_task_prio(p, now);
882 * This checks to make sure it's not an uninterruptible task
883 * that is now waking up.
887 * Tasks which were woken up by interrupts (ie. hw events)
888 * are most likely of interactive nature. So we give them
889 * the credit of extending their sleep time to the period
890 * of time they spend on the runqueue, waiting for execution
891 * on a CPU, first time around:
897 * Normal first-time wakeups get a credit too for
898 * on-runqueue time, but it will be weighted down:
906 __activate_task(p, rq);
910 * deactivate_task - remove a task from the runqueue.
912 static void __deactivate_task(struct task_struct *p, runqueue_t *rq)
915 if (p->state == TASK_UNINTERRUPTIBLE)
916 rq->nr_uninterruptible++;
917 dequeue_task(p, p->array);
922 static void deactivate_task(struct task_struct *p, runqueue_t *rq)
924 __deactivate_task(p, rq);
925 vx_deactivate_task(p);
929 * resched_task - mark a task 'to be rescheduled now'.
931 * On UP this means the setting of the need_resched flag, on SMP it
932 * might also involve a cross-CPU call to trigger the scheduler on
936 static void resched_task(task_t *p)
938 int need_resched, nrpolling;
940 BUG_ON(!spin_is_locked(&task_rq(p)->lock));
942 /* minimise the chance of sending an interrupt to poll_idle() */
943 nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
944 need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
945 nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
947 if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
948 smp_send_reschedule(task_cpu(p));
951 static inline void resched_task(task_t *p)
953 set_tsk_need_resched(p);
958 * task_curr - is this task currently executing on a CPU?
959 * @p: the task in question.
961 inline int task_curr(const task_t *p)
963 return cpu_curr(task_cpu(p)) == p;
973 struct list_head list;
974 enum request_type type;
976 /* For REQ_MOVE_TASK */
980 /* For REQ_SET_DOMAIN */
981 struct sched_domain *sd;
983 struct completion done;
987 * The task's runqueue lock must be held.
988 * Returns true if you have to wait for migration thread.
990 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
992 runqueue_t *rq = task_rq(p);
995 * If the task is not on a runqueue (and not running), then
996 * it is sufficient to simply update the task's cpu field.
998 if (!p->array && !task_running(rq, p)) {
999 set_task_cpu(p, dest_cpu);
1003 init_completion(&req->done);
1004 req->type = REQ_MOVE_TASK;
1006 req->dest_cpu = dest_cpu;
1007 list_add(&req->list, &rq->migration_queue);
1012 * wait_task_inactive - wait for a thread to unschedule.
1014 * The caller must ensure that the task *will* unschedule sometime soon,
1015 * else this function might spin for a *long* time. This function can't
1016 * be called with interrupts off, or it may introduce deadlock with
1017 * smp_call_function() if an IPI is sent by the same process we are
1018 * waiting to become inactive.
1020 void wait_task_inactive(task_t * p)
1022 unsigned long flags;
1027 rq = task_rq_lock(p, &flags);
1028 /* Must be off runqueue entirely, not preempted. */
1029 if (unlikely(p->array)) {
1030 /* If it's preempted, we yield. It could be a while. */
1031 preempted = !task_running(rq, p);
1032 task_rq_unlock(rq, &flags);
1038 task_rq_unlock(rq, &flags);
1042 * kick_process - kick a running thread to enter/exit the kernel
1043 * @p: the to-be-kicked thread
1045 * Cause a process which is running on another CPU to enter
1046 * kernel-mode, without any delay. (to get signals handled.)
1048 void kick_process(task_t *p)
1054 if ((cpu != smp_processor_id()) && task_curr(p))
1055 smp_send_reschedule(cpu);
1059 EXPORT_SYMBOL_GPL(kick_process);
1062 * Return a low guess at the load of a migration-source cpu.
1064 * We want to under-estimate the load of migration sources, to
1065 * balance conservatively.
1067 static inline unsigned long source_load(int cpu)
1069 runqueue_t *rq = cpu_rq(cpu);
1070 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
1072 return min(rq->cpu_load, load_now);
1076 * Return a high guess at the load of a migration-target cpu
1078 static inline unsigned long target_load(int cpu)
1080 runqueue_t *rq = cpu_rq(cpu);
1081 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
1083 return max(rq->cpu_load, load_now);
1089 * wake_idle() is useful especially on SMT architectures to wake a
1090 * task onto an idle sibling if we would otherwise wake it onto a
1093 * Returns the CPU we should wake onto.
1095 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1096 static int wake_idle(int cpu, task_t *p)
1099 runqueue_t *rq = cpu_rq(cpu);
1100 struct sched_domain *sd;
1107 if (!(sd->flags & SD_WAKE_IDLE))
1110 cpus_and(tmp, sd->span, cpu_online_map);
1111 cpus_and(tmp, tmp, p->cpus_allowed);
1113 for_each_cpu_mask(i, tmp) {
1121 static inline int wake_idle(int cpu, task_t *p)
1128 * try_to_wake_up - wake up a thread
1129 * @p: the to-be-woken-up thread
1130 * @state: the mask of task states that can be woken
1131 * @sync: do a synchronous wakeup?
1133 * Put it on the run-queue if it's not already there. The "current"
1134 * thread is always on the run-queue (except when the actual
1135 * re-schedule is in progress), and as such you're allowed to do
1136 * the simpler "current->state = TASK_RUNNING" to mark yourself
1137 * runnable without the overhead of this.
1139 * returns failure only if the task is already active.
1141 static int try_to_wake_up(task_t * p, unsigned int state, int sync)
1143 int cpu, this_cpu, success = 0;
1144 unsigned long flags;
1148 unsigned long load, this_load;
1149 struct sched_domain *sd;
1153 rq = task_rq_lock(p, &flags);
1154 schedstat_inc(rq, ttwu_cnt);
1155 old_state = p->state;
1156 if (!(old_state & state))
1163 this_cpu = smp_processor_id();
1166 if (unlikely(task_running(rq, p)))
1171 if (cpu == this_cpu || unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1174 load = source_load(cpu);
1175 this_load = target_load(this_cpu);
1178 * If sync wakeup then subtract the (maximum possible) effect of
1179 * the currently running task from the load of the current CPU:
1182 this_load -= SCHED_LOAD_SCALE;
1184 /* Don't pull the task off an idle CPU to a busy one */
1185 if (load < SCHED_LOAD_SCALE/2 && this_load > SCHED_LOAD_SCALE/2)
1188 new_cpu = this_cpu; /* Wake to this CPU if we can */
1191 * Scan domains for affine wakeup and passive balancing
1194 for_each_domain(this_cpu, sd) {
1195 unsigned int imbalance;
1197 * Start passive balancing when half the imbalance_pct
1200 imbalance = sd->imbalance_pct + (sd->imbalance_pct - 100) / 2;
1202 if ((sd->flags & SD_WAKE_AFFINE) &&
1203 !task_hot(p, rq->timestamp_last_tick, sd)) {
1205 * This domain has SD_WAKE_AFFINE and p is cache cold
1208 if (cpu_isset(cpu, sd->span)) {
1209 schedstat_inc(sd, ttwu_wake_affine);
1212 } else if ((sd->flags & SD_WAKE_BALANCE) &&
1213 imbalance*this_load <= 100*load) {
1215 * This domain has SD_WAKE_BALANCE and there is
1218 if (cpu_isset(cpu, sd->span)) {
1219 schedstat_inc(sd, ttwu_wake_balance);
1225 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1227 schedstat_inc(rq, ttwu_attempts);
1228 new_cpu = wake_idle(new_cpu, p);
1229 if (new_cpu != cpu && cpu_isset(new_cpu, p->cpus_allowed)) {
1230 schedstat_inc(rq, ttwu_moved);
1231 set_task_cpu(p, new_cpu);
1232 task_rq_unlock(rq, &flags);
1233 /* might preempt at this point */
1234 rq = task_rq_lock(p, &flags);
1235 old_state = p->state;
1236 if (!(old_state & state))
1241 this_cpu = smp_processor_id();
1246 #endif /* CONFIG_SMP */
1247 if (old_state == TASK_UNINTERRUPTIBLE) {
1248 rq->nr_uninterruptible--;
1250 * Tasks on involuntary sleep don't earn
1251 * sleep_avg beyond just interactive state.
1257 * Sync wakeups (i.e. those types of wakeups where the waker
1258 * has indicated that it will leave the CPU in short order)
1259 * don't trigger a preemption, if the woken up task will run on
1260 * this cpu. (in this case the 'I will reschedule' promise of
1261 * the waker guarantees that the freshly woken up task is going
1262 * to be considered on this CPU.)
1264 activate_task(p, rq, cpu == this_cpu);
1265 if (!sync || cpu != this_cpu) {
1266 if (TASK_PREEMPTS_CURR(p, rq))
1267 resched_task(rq->curr);
1272 p->state = TASK_RUNNING;
1274 task_rq_unlock(rq, &flags);
1279 int fastcall wake_up_process(task_t * p)
1281 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1282 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1285 EXPORT_SYMBOL(wake_up_process);
1287 int fastcall wake_up_state(task_t *p, unsigned int state)
1289 return try_to_wake_up(p, state, 0);
1293 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1294 struct sched_domain *sd);
1298 * Perform scheduler related setup for a newly forked process p.
1299 * p is forked by current.
1301 void fastcall sched_fork(task_t *p)
1304 * We mark the process as running here, but have not actually
1305 * inserted it onto the runqueue yet. This guarantees that
1306 * nobody will actually run it, and a signal or other external
1307 * event cannot wake it up and insert it on the runqueue either.
1309 p->state = TASK_RUNNING;
1310 INIT_LIST_HEAD(&p->run_list);
1312 spin_lock_init(&p->switch_lock);
1313 #ifdef CONFIG_SCHEDSTATS
1314 memset(&p->sched_info, 0, sizeof(p->sched_info));
1316 #ifdef CONFIG_PREEMPT
1318 * During context-switch we hold precisely one spinlock, which
1319 * schedule_tail drops. (in the common case it's this_rq()->lock,
1320 * but it also can be p->switch_lock.) So we compensate with a count
1321 * of 1. Also, we want to start with kernel preemption disabled.
1323 p->thread_info->preempt_count = 1;
1326 * Share the timeslice between parent and child, thus the
1327 * total amount of pending timeslices in the system doesn't change,
1328 * resulting in more scheduling fairness.
1330 local_irq_disable();
1331 p->time_slice = (current->time_slice + 1) >> 1;
1333 * The remainder of the first timeslice might be recovered by
1334 * the parent if the child exits early enough.
1336 p->first_time_slice = 1;
1337 current->time_slice >>= 1;
1338 p->timestamp = sched_clock();
1339 if (unlikely(!current->time_slice)) {
1341 * This case is rare, it happens when the parent has only
1342 * a single jiffy left from its timeslice. Taking the
1343 * runqueue lock is not a problem.
1345 current->time_slice = 1;
1347 scheduler_tick(0, 0);
1355 * wake_up_new_task - wake up a newly created task for the first time.
1357 * This function will do some initial scheduler statistics housekeeping
1358 * that must be done for every newly created context, then puts the task
1359 * on the runqueue and wakes it.
1361 void fastcall wake_up_new_task(task_t * p, unsigned long clone_flags)
1363 unsigned long flags;
1365 runqueue_t *rq, *this_rq;
1367 rq = task_rq_lock(p, &flags);
1369 this_cpu = smp_processor_id();
1371 BUG_ON(p->state != TASK_RUNNING);
1373 schedstat_inc(rq, wunt_cnt);
1375 * We decrease the sleep average of forking parents
1376 * and children as well, to keep max-interactive tasks
1377 * from forking tasks that are max-interactive. The parent
1378 * (current) is done further down, under its lock.
1380 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1381 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1383 p->interactive_credit = 0;
1385 p->prio = effective_prio(p);
1387 vx_activate_task(p);
1388 if (likely(cpu == this_cpu)) {
1389 if (!(clone_flags & CLONE_VM)) {
1391 * The VM isn't cloned, so we're in a good position to
1392 * do child-runs-first in anticipation of an exec. This
1393 * usually avoids a lot of COW overhead.
1395 if (unlikely(!current->array))
1396 __activate_task(p, rq);
1398 p->prio = current->prio;
1399 list_add_tail(&p->run_list, ¤t->run_list);
1400 p->array = current->array;
1401 p->array->nr_active++;
1406 /* Run child last */
1407 __activate_task(p, rq);
1409 * We skip the following code due to cpu == this_cpu
1411 * task_rq_unlock(rq, &flags);
1412 * this_rq = task_rq_lock(current, &flags);
1416 this_rq = cpu_rq(this_cpu);
1419 * Not the local CPU - must adjust timestamp. This should
1420 * get optimised away in the !CONFIG_SMP case.
1422 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1423 + rq->timestamp_last_tick;
1424 __activate_task(p, rq);
1425 if (TASK_PREEMPTS_CURR(p, rq))
1426 resched_task(rq->curr);
1428 schedstat_inc(rq, wunt_moved);
1430 * Parent and child are on different CPUs, now get the
1431 * parent runqueue to update the parent's ->sleep_avg:
1433 task_rq_unlock(rq, &flags);
1434 this_rq = task_rq_lock(current, &flags);
1436 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1437 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1438 task_rq_unlock(this_rq, &flags);
1442 * Potentially available exiting-child timeslices are
1443 * retrieved here - this way the parent does not get
1444 * penalized for creating too many threads.
1446 * (this cannot be used to 'generate' timeslices
1447 * artificially, because any timeslice recovered here
1448 * was given away by the parent in the first place.)
1450 void fastcall sched_exit(task_t * p)
1452 unsigned long flags;
1456 * If the child was a (relative-) CPU hog then decrease
1457 * the sleep_avg of the parent as well.
1459 rq = task_rq_lock(p->parent, &flags);
1460 if (p->first_time_slice) {
1461 p->parent->time_slice += p->time_slice;
1462 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1463 p->parent->time_slice = task_timeslice(p);
1465 if (p->sleep_avg < p->parent->sleep_avg)
1466 p->parent->sleep_avg = p->parent->sleep_avg /
1467 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1469 task_rq_unlock(rq, &flags);
1473 * finish_task_switch - clean up after a task-switch
1474 * @prev: the thread we just switched away from.
1476 * We enter this with the runqueue still locked, and finish_arch_switch()
1477 * will unlock it along with doing any other architecture-specific cleanup
1480 * Note that we may have delayed dropping an mm in context_switch(). If
1481 * so, we finish that here outside of the runqueue lock. (Doing it
1482 * with the lock held can cause deadlocks; see schedule() for
1485 static void finish_task_switch(task_t *prev)
1487 runqueue_t *rq = this_rq();
1488 struct mm_struct *mm = rq->prev_mm;
1489 unsigned long prev_task_flags;
1494 * A task struct has one reference for the use as "current".
1495 * If a task dies, then it sets TASK_ZOMBIE in tsk->state and calls
1496 * schedule one last time. The schedule call will never return,
1497 * and the scheduled task must drop that reference.
1498 * The test for TASK_ZOMBIE must occur while the runqueue locks are
1499 * still held, otherwise prev could be scheduled on another cpu, die
1500 * there before we look at prev->state, and then the reference would
1502 * Manfred Spraul <manfred@colorfullife.com>
1504 prev_task_flags = prev->flags;
1505 finish_arch_switch(rq, prev);
1508 if (unlikely(prev_task_flags & PF_DEAD))
1509 put_task_struct(prev);
1513 * schedule_tail - first thing a freshly forked thread must call.
1514 * @prev: the thread we just switched away from.
1516 asmlinkage void schedule_tail(task_t *prev)
1518 finish_task_switch(prev);
1520 if (current->set_child_tid)
1521 put_user(current->pid, current->set_child_tid);
1525 * context_switch - switch to the new MM and the new
1526 * thread's register state.
1529 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1531 struct mm_struct *mm = next->mm;
1532 struct mm_struct *oldmm = prev->active_mm;
1534 if (unlikely(!mm)) {
1535 next->active_mm = oldmm;
1536 atomic_inc(&oldmm->mm_count);
1537 enter_lazy_tlb(oldmm, next);
1539 switch_mm(oldmm, mm, next);
1541 if (unlikely(!prev->mm)) {
1542 prev->active_mm = NULL;
1543 WARN_ON(rq->prev_mm);
1544 rq->prev_mm = oldmm;
1547 /* Here we just switch the register state and the stack. */
1548 switch_to(prev, next, prev);
1554 * nr_running, nr_uninterruptible and nr_context_switches:
1556 * externally visible scheduler statistics: current number of runnable
1557 * threads, current number of uninterruptible-sleeping threads, total
1558 * number of context switches performed since bootup.
1560 unsigned long nr_running(void)
1562 unsigned long i, sum = 0;
1564 for_each_online_cpu(i)
1565 sum += cpu_rq(i)->nr_running;
1570 unsigned long nr_uninterruptible(void)
1572 unsigned long i, sum = 0;
1575 sum += cpu_rq(i)->nr_uninterruptible;
1580 unsigned long long nr_context_switches(void)
1582 unsigned long long i, sum = 0;
1585 sum += cpu_rq(i)->nr_switches;
1590 unsigned long nr_iowait(void)
1592 unsigned long i, sum = 0;
1595 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1603 * double_rq_lock - safely lock two runqueues
1605 * Note this does not disable interrupts like task_rq_lock,
1606 * you need to do so manually before calling.
1608 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1611 spin_lock(&rq1->lock);
1614 spin_lock(&rq1->lock);
1615 spin_lock(&rq2->lock);
1617 spin_lock(&rq2->lock);
1618 spin_lock(&rq1->lock);
1624 * double_rq_unlock - safely unlock two runqueues
1626 * Note this does not restore interrupts like task_rq_unlock,
1627 * you need to do so manually after calling.
1629 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1631 spin_unlock(&rq1->lock);
1633 spin_unlock(&rq2->lock);
1637 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1639 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1641 if (unlikely(!spin_trylock(&busiest->lock))) {
1642 if (busiest < this_rq) {
1643 spin_unlock(&this_rq->lock);
1644 spin_lock(&busiest->lock);
1645 spin_lock(&this_rq->lock);
1647 spin_lock(&busiest->lock);
1652 * find_idlest_cpu - find the least busy runqueue.
1654 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1655 struct sched_domain *sd)
1657 unsigned long load, min_load, this_load;
1662 min_load = ULONG_MAX;
1664 cpus_and(mask, sd->span, cpu_online_map);
1665 cpus_and(mask, mask, p->cpus_allowed);
1667 for_each_cpu_mask(i, mask) {
1668 load = target_load(i);
1670 if (load < min_load) {
1674 /* break out early on an idle CPU: */
1680 /* add +1 to account for the new task */
1681 this_load = source_load(this_cpu) + SCHED_LOAD_SCALE;
1684 * Would with the addition of the new task to the
1685 * current CPU there be an imbalance between this
1686 * CPU and the idlest CPU?
1688 * Use half of the balancing threshold - new-context is
1689 * a good opportunity to balance.
1691 if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1698 * If dest_cpu is allowed for this process, migrate the task to it.
1699 * This is accomplished by forcing the cpu_allowed mask to only
1700 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1701 * the cpu_allowed mask is restored.
1703 static void sched_migrate_task(task_t *p, int dest_cpu)
1705 migration_req_t req;
1707 unsigned long flags;
1709 rq = task_rq_lock(p, &flags);
1710 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1711 || unlikely(cpu_is_offline(dest_cpu)))
1714 schedstat_inc(rq, smt_cnt);
1715 /* force the process onto the specified CPU */
1716 if (migrate_task(p, dest_cpu, &req)) {
1717 /* Need to wait for migration thread (might exit: take ref). */
1718 struct task_struct *mt = rq->migration_thread;
1719 get_task_struct(mt);
1720 task_rq_unlock(rq, &flags);
1721 wake_up_process(mt);
1722 put_task_struct(mt);
1723 wait_for_completion(&req.done);
1727 task_rq_unlock(rq, &flags);
1731 * sched_exec(): find the highest-level, exec-balance-capable
1732 * domain and try to migrate the task to the least loaded CPU.
1734 * execve() is a valuable balancing opportunity, because at this point
1735 * the task has the smallest effective memory and cache footprint.
1737 void sched_exec(void)
1739 struct sched_domain *tmp, *sd = NULL;
1740 int new_cpu, this_cpu = get_cpu();
1742 schedstat_inc(this_rq(), sbe_cnt);
1743 /* Prefer the current CPU if there's only this task running */
1744 if (this_rq()->nr_running <= 1)
1747 for_each_domain(this_cpu, tmp)
1748 if (tmp->flags & SD_BALANCE_EXEC)
1752 schedstat_inc(sd, sbe_attempts);
1753 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1754 if (new_cpu != this_cpu) {
1755 schedstat_inc(sd, sbe_pushed);
1757 sched_migrate_task(current, new_cpu);
1766 * pull_task - move a task from a remote runqueue to the local runqueue.
1767 * Both runqueues must be locked.
1770 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1771 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1773 dequeue_task(p, src_array);
1774 src_rq->nr_running--;
1775 set_task_cpu(p, this_cpu);
1776 this_rq->nr_running++;
1777 enqueue_task(p, this_array);
1778 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1779 + this_rq->timestamp_last_tick;
1781 * Note that idle threads have a prio of MAX_PRIO, for this test
1782 * to be always true for them.
1784 if (TASK_PREEMPTS_CURR(p, this_rq))
1785 resched_task(this_rq->curr);
1789 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1792 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1793 struct sched_domain *sd, enum idle_type idle)
1796 * We do not migrate tasks that are:
1797 * 1) running (obviously), or
1798 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1799 * 3) are cache-hot on their current CPU.
1801 if (task_running(rq, p))
1803 if (!cpu_isset(this_cpu, p->cpus_allowed))
1806 /* Aggressive migration if we've failed balancing */
1807 if (idle == NEWLY_IDLE ||
1808 sd->nr_balance_failed < sd->cache_nice_tries) {
1809 if (task_hot(p, rq->timestamp_last_tick, sd))
1817 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1818 * as part of a balancing operation within "domain". Returns the number of
1821 * Called with both runqueues locked.
1823 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1824 unsigned long max_nr_move, struct sched_domain *sd,
1825 enum idle_type idle)
1827 prio_array_t *array, *dst_array;
1828 struct list_head *head, *curr;
1829 int idx, pulled = 0;
1832 if (max_nr_move <= 0 || busiest->nr_running <= 1)
1836 * We first consider expired tasks. Those will likely not be
1837 * executed in the near future, and they are most likely to
1838 * be cache-cold, thus switching CPUs has the least effect
1841 if (busiest->expired->nr_active) {
1842 array = busiest->expired;
1843 dst_array = this_rq->expired;
1845 array = busiest->active;
1846 dst_array = this_rq->active;
1850 /* Start searching at priority 0: */
1854 idx = sched_find_first_bit(array->bitmap);
1856 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1857 if (idx >= MAX_PRIO) {
1858 if (array == busiest->expired && busiest->active->nr_active) {
1859 array = busiest->active;
1860 dst_array = this_rq->active;
1866 head = array->queue + idx;
1869 tmp = list_entry(curr, task_t, run_list);
1873 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
1881 * Right now, this is the only place pull_task() is called,
1882 * so we can safely collect pull_task() stats here rather than
1883 * inside pull_task().
1885 schedstat_inc(this_rq, pt_gained[idle]);
1886 schedstat_inc(busiest, pt_lost[idle]);
1888 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
1891 /* We only want to steal up to the prescribed number of tasks. */
1892 if (pulled < max_nr_move) {
1903 * find_busiest_group finds and returns the busiest CPU group within the
1904 * domain. It calculates and returns the number of tasks which should be
1905 * moved to restore balance via the imbalance parameter.
1907 static struct sched_group *
1908 find_busiest_group(struct sched_domain *sd, int this_cpu,
1909 unsigned long *imbalance, enum idle_type idle)
1911 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
1912 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
1914 max_load = this_load = total_load = total_pwr = 0;
1922 local_group = cpu_isset(this_cpu, group->cpumask);
1924 /* Tally up the load of all CPUs in the group */
1926 cpus_and(tmp, group->cpumask, cpu_online_map);
1927 if (unlikely(cpus_empty(tmp)))
1930 for_each_cpu_mask(i, tmp) {
1931 /* Bias balancing toward cpus of our domain */
1933 load = target_load(i);
1935 load = source_load(i);
1944 total_load += avg_load;
1945 total_pwr += group->cpu_power;
1947 /* Adjust by relative CPU power of the group */
1948 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1951 this_load = avg_load;
1954 } else if (avg_load > max_load) {
1955 max_load = avg_load;
1959 group = group->next;
1960 } while (group != sd->groups);
1962 if (!busiest || this_load >= max_load)
1965 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
1967 if (this_load >= avg_load ||
1968 100*max_load <= sd->imbalance_pct*this_load)
1972 * We're trying to get all the cpus to the average_load, so we don't
1973 * want to push ourselves above the average load, nor do we wish to
1974 * reduce the max loaded cpu below the average load, as either of these
1975 * actions would just result in more rebalancing later, and ping-pong
1976 * tasks around. Thus we look for the minimum possible imbalance.
1977 * Negative imbalances (*we* are more loaded than anyone else) will
1978 * be counted as no imbalance for these purposes -- we can't fix that
1979 * by pulling tasks to us. Be careful of negative numbers as they'll
1980 * appear as very large values with unsigned longs.
1982 *imbalance = min(max_load - avg_load, avg_load - this_load);
1984 /* How much load to actually move to equalise the imbalance */
1985 *imbalance = (*imbalance * min(busiest->cpu_power, this->cpu_power))
1988 if (*imbalance < SCHED_LOAD_SCALE - 1) {
1989 unsigned long pwr_now = 0, pwr_move = 0;
1992 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
1998 * OK, we don't have enough imbalance to justify moving tasks,
1999 * however we may be able to increase total CPU power used by
2003 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
2004 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
2005 pwr_now /= SCHED_LOAD_SCALE;
2007 /* Amount of load we'd subtract */
2008 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
2010 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
2013 /* Amount of load we'd add */
2014 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
2017 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
2018 pwr_move /= SCHED_LOAD_SCALE;
2020 /* Move if we gain another 8th of a CPU worth of throughput */
2021 if (pwr_move < pwr_now + SCHED_LOAD_SCALE / 8)
2028 /* Get rid of the scaling factor, rounding down as we divide */
2029 *imbalance = (*imbalance + 1) / SCHED_LOAD_SCALE;
2034 if (busiest && (idle == NEWLY_IDLE ||
2035 (idle == IDLE && max_load > SCHED_LOAD_SCALE)) ) {
2045 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2047 static runqueue_t *find_busiest_queue(struct sched_group *group)
2050 unsigned long load, max_load = 0;
2051 runqueue_t *busiest = NULL;
2054 cpus_and(tmp, group->cpumask, cpu_online_map);
2055 for_each_cpu_mask(i, tmp) {
2056 load = source_load(i);
2058 if (load > max_load) {
2060 busiest = cpu_rq(i);
2068 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2069 * tasks if there is an imbalance.
2071 * Called with this_rq unlocked.
2073 static int load_balance(int this_cpu, runqueue_t *this_rq,
2074 struct sched_domain *sd, enum idle_type idle)
2076 struct sched_group *group;
2077 runqueue_t *busiest;
2078 unsigned long imbalance;
2081 spin_lock(&this_rq->lock);
2082 schedstat_inc(sd, lb_cnt[idle]);
2084 group = find_busiest_group(sd, this_cpu, &imbalance, idle);
2086 schedstat_inc(sd, lb_nobusyg[idle]);
2090 busiest = find_busiest_queue(group);
2092 schedstat_inc(sd, lb_nobusyq[idle]);
2097 * This should be "impossible", but since load
2098 * balancing is inherently racy and statistical,
2099 * it could happen in theory.
2101 if (unlikely(busiest == this_rq)) {
2106 schedstat_add(sd, lb_imbalance[idle], imbalance);
2109 if (busiest->nr_running > 1) {
2111 * Attempt to move tasks. If find_busiest_group has found
2112 * an imbalance but busiest->nr_running <= 1, the group is
2113 * still unbalanced. nr_moved simply stays zero, so it is
2114 * correctly treated as an imbalance.
2116 double_lock_balance(this_rq, busiest);
2117 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2118 imbalance, sd, idle);
2119 spin_unlock(&busiest->lock);
2121 spin_unlock(&this_rq->lock);
2124 schedstat_inc(sd, lb_failed[idle]);
2125 sd->nr_balance_failed++;
2127 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2130 spin_lock(&busiest->lock);
2131 if (!busiest->active_balance) {
2132 busiest->active_balance = 1;
2133 busiest->push_cpu = this_cpu;
2136 spin_unlock(&busiest->lock);
2138 wake_up_process(busiest->migration_thread);
2141 * We've kicked active balancing, reset the failure
2144 sd->nr_balance_failed = sd->cache_nice_tries;
2147 sd->nr_balance_failed = 0;
2149 /* We were unbalanced, so reset the balancing interval */
2150 sd->balance_interval = sd->min_interval;
2155 spin_unlock(&this_rq->lock);
2157 /* tune up the balancing interval */
2158 if (sd->balance_interval < sd->max_interval)
2159 sd->balance_interval *= 2;
2165 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2166 * tasks if there is an imbalance.
2168 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2169 * this_rq is locked.
2171 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2172 struct sched_domain *sd)
2174 struct sched_group *group;
2175 runqueue_t *busiest = NULL;
2176 unsigned long imbalance;
2179 schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2180 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
2182 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2186 busiest = find_busiest_queue(group);
2187 if (!busiest || busiest == this_rq) {
2188 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2192 /* Attempt to move tasks */
2193 double_lock_balance(this_rq, busiest);
2195 schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2196 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2197 imbalance, sd, NEWLY_IDLE);
2199 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2201 spin_unlock(&busiest->lock);
2208 * idle_balance is called by schedule() if this_cpu is about to become
2209 * idle. Attempts to pull tasks from other CPUs.
2211 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
2213 struct sched_domain *sd;
2215 for_each_domain(this_cpu, sd) {
2216 if (sd->flags & SD_BALANCE_NEWIDLE) {
2217 if (load_balance_newidle(this_cpu, this_rq, sd)) {
2218 /* We've pulled tasks over so stop searching */
2226 * active_load_balance is run by migration threads. It pushes a running
2227 * task off the cpu. It can be required to correctly have at least 1 task
2228 * running on each physical CPU where possible, and not have a physical /
2229 * logical imbalance.
2231 * Called with busiest locked.
2233 static void active_load_balance(runqueue_t *busiest, int busiest_cpu)
2235 struct sched_domain *sd;
2236 struct sched_group *group, *busy_group;
2239 schedstat_inc(busiest, alb_cnt);
2240 if (busiest->nr_running <= 1)
2243 for_each_domain(busiest_cpu, sd)
2244 if (cpu_isset(busiest->push_cpu, sd->span))
2250 while (!cpu_isset(busiest_cpu, group->cpumask))
2251 group = group->next;
2260 if (group == busy_group)
2263 cpus_and(tmp, group->cpumask, cpu_online_map);
2264 if (!cpus_weight(tmp))
2267 for_each_cpu_mask(i, tmp) {
2273 rq = cpu_rq(push_cpu);
2276 * This condition is "impossible", but since load
2277 * balancing is inherently a bit racy and statistical,
2278 * it can trigger.. Reported by Bjorn Helgaas on a
2281 if (unlikely(busiest == rq))
2283 double_lock_balance(busiest, rq);
2284 if (move_tasks(rq, push_cpu, busiest, 1, sd, IDLE)) {
2285 schedstat_inc(busiest, alb_lost);
2286 schedstat_inc(rq, alb_gained);
2288 schedstat_inc(busiest, alb_failed);
2290 spin_unlock(&rq->lock);
2292 group = group->next;
2293 } while (group != sd->groups);
2297 * rebalance_tick will get called every timer tick, on every CPU.
2299 * It checks each scheduling domain to see if it is due to be balanced,
2300 * and initiates a balancing operation if so.
2302 * Balancing parameters are set up in arch_init_sched_domains.
2305 /* Don't have all balancing operations going off at once */
2306 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2308 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2309 enum idle_type idle)
2311 unsigned long old_load, this_load;
2312 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2313 struct sched_domain *sd;
2315 /* Update our load */
2316 old_load = this_rq->cpu_load;
2317 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
2319 * Round up the averaging division if load is increasing. This
2320 * prevents us from getting stuck on 9 if the load is 10, for
2323 if (this_load > old_load)
2325 this_rq->cpu_load = (old_load + this_load) / 2;
2327 for_each_domain(this_cpu, sd) {
2328 unsigned long interval = sd->balance_interval;
2331 interval *= sd->busy_factor;
2333 /* scale ms to jiffies */
2334 interval = msecs_to_jiffies(interval);
2335 if (unlikely(!interval))
2338 if (j - sd->last_balance >= interval) {
2339 if (load_balance(this_cpu, this_rq, sd, idle)) {
2340 /* We've pulled tasks over so no longer idle */
2343 sd->last_balance += interval;
2349 * on UP we do not need to balance between CPUs:
2351 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2354 static inline void idle_balance(int cpu, runqueue_t *rq)
2359 static inline int wake_priority_sleeper(runqueue_t *rq)
2362 #ifdef CONFIG_SCHED_SMT
2363 spin_lock(&rq->lock);
2365 * If an SMT sibling task has been put to sleep for priority
2366 * reasons reschedule the idle task to see if it can now run.
2368 if (rq->nr_running) {
2369 resched_task(rq->idle);
2372 spin_unlock(&rq->lock);
2377 DEFINE_PER_CPU(struct kernel_stat, kstat);
2379 EXPORT_PER_CPU_SYMBOL(kstat);
2382 * We place interactive tasks back into the active array, if possible.
2384 * To guarantee that this does not starve expired tasks we ignore the
2385 * interactivity of a task if the first expired task had to wait more
2386 * than a 'reasonable' amount of time. This deadline timeout is
2387 * load-dependent, as the frequency of array switched decreases with
2388 * increasing number of running tasks. We also ignore the interactivity
2389 * if a better static_prio task has expired:
2391 #define EXPIRED_STARVING(rq) \
2392 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2393 (jiffies - (rq)->expired_timestamp >= \
2394 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2395 ((rq)->curr->static_prio > (rq)->best_expired_prio))
2398 * This function gets called by the timer code, with HZ frequency.
2399 * We call it with interrupts disabled.
2401 * It also gets called by the fork code, when changing the parent's
2404 void scheduler_tick(int user_ticks, int sys_ticks)
2406 int cpu = smp_processor_id();
2407 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2408 runqueue_t *rq = this_rq();
2409 task_t *p = current;
2410 struct vx_info *vxi = p->vx_info;
2412 rq->timestamp_last_tick = sched_clock();
2414 if (rcu_pending(cpu))
2415 rcu_check_callbacks(cpu, user_ticks);
2418 vxi->sched.cpu[cpu].user_ticks += user_ticks;
2419 vxi->sched.cpu[cpu].sys_ticks += sys_ticks;
2422 /* note: this timer irq context must be accounted for as well */
2423 if (hardirq_count() - HARDIRQ_OFFSET) {
2424 cpustat->irq += sys_ticks;
2426 } else if (softirq_count()) {
2427 cpustat->softirq += sys_ticks;
2431 if (p == rq->idle) {
2432 if (atomic_read(&rq->nr_iowait) > 0)
2433 cpustat->iowait += sys_ticks;
2434 // vx_cpustat_acc(vxi, iowait, cpu, cpustat, sys_ticks);
2436 cpustat->idle += sys_ticks;
2437 // vx_cpustat_acc(vxi, idle, cpu, cpustat, sys_ticks);
2439 if (wake_priority_sleeper(rq))
2442 #ifdef CONFIG_VSERVER_HARDCPU_IDLE
2443 if (!--rq->idle_tokens && !list_empty(&rq->hold_queue))
2446 rebalance_tick(cpu, rq, IDLE);
2449 if (TASK_NICE(p) > 0)
2450 cpustat->nice += user_ticks;
2452 cpustat->user += user_ticks;
2453 cpustat->system += sys_ticks;
2455 /* Task might have expired already, but not scheduled off yet */
2456 if (p->array != rq->active) {
2457 set_tsk_need_resched(p);
2460 spin_lock(&rq->lock);
2462 * The task was running during this tick - update the
2463 * time slice counter. Note: we do not update a thread's
2464 * priority until it either goes to sleep or uses up its
2465 * timeslice. This makes it possible for interactive tasks
2466 * to use up their timeslices at their highest priority levels.
2470 * RR tasks need a special form of timeslice management.
2471 * FIFO tasks have no timeslices.
2473 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2474 p->time_slice = task_timeslice(p);
2475 p->first_time_slice = 0;
2476 set_tsk_need_resched(p);
2478 /* put it at the end of the queue: */
2479 dequeue_task(p, rq->active);
2480 enqueue_task(p, rq->active);
2484 if (vx_need_resched(p)) {
2485 dequeue_task(p, rq->active);
2486 set_tsk_need_resched(p);
2487 p->prio = effective_prio(p);
2488 p->time_slice = task_timeslice(p);
2489 p->first_time_slice = 0;
2491 if (!rq->expired_timestamp)
2492 rq->expired_timestamp = jiffies;
2493 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2494 enqueue_task(p, rq->expired);
2495 if (p->static_prio < rq->best_expired_prio)
2496 rq->best_expired_prio = p->static_prio;
2498 enqueue_task(p, rq->active);
2501 * Prevent a too long timeslice allowing a task to monopolize
2502 * the CPU. We do this by splitting up the timeslice into
2505 * Note: this does not mean the task's timeslices expire or
2506 * get lost in any way, they just might be preempted by
2507 * another task of equal priority. (one with higher
2508 * priority would have preempted this task already.) We
2509 * requeue this task to the end of the list on this priority
2510 * level, which is in essence a round-robin of tasks with
2513 * This only applies to tasks in the interactive
2514 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2516 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2517 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2518 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2519 (p->array == rq->active)) {
2521 dequeue_task(p, rq->active);
2522 set_tsk_need_resched(p);
2523 p->prio = effective_prio(p);
2524 enqueue_task(p, rq->active);
2528 spin_unlock(&rq->lock);
2530 rebalance_tick(cpu, rq, NOT_IDLE);
2533 #ifdef CONFIG_SCHED_SMT
2534 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2536 struct sched_domain *sd = this_rq->sd;
2537 cpumask_t sibling_map;
2540 if (!(sd->flags & SD_SHARE_CPUPOWER))
2544 * Unlock the current runqueue because we have to lock in
2545 * CPU order to avoid deadlocks. Caller knows that we might
2546 * unlock. We keep IRQs disabled.
2548 spin_unlock(&this_rq->lock);
2550 cpus_and(sibling_map, sd->span, cpu_online_map);
2552 for_each_cpu_mask(i, sibling_map)
2553 spin_lock(&cpu_rq(i)->lock);
2555 * We clear this CPU from the mask. This both simplifies the
2556 * inner loop and keps this_rq locked when we exit:
2558 cpu_clear(this_cpu, sibling_map);
2560 for_each_cpu_mask(i, sibling_map) {
2561 runqueue_t *smt_rq = cpu_rq(i);
2564 * If an SMT sibling task is sleeping due to priority
2565 * reasons wake it up now.
2567 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
2568 resched_task(smt_rq->idle);
2571 for_each_cpu_mask(i, sibling_map)
2572 spin_unlock(&cpu_rq(i)->lock);
2574 * We exit with this_cpu's rq still held and IRQs
2579 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2581 struct sched_domain *sd = this_rq->sd;
2582 cpumask_t sibling_map;
2583 prio_array_t *array;
2587 if (!(sd->flags & SD_SHARE_CPUPOWER))
2591 * The same locking rules and details apply as for
2592 * wake_sleeping_dependent():
2594 spin_unlock(&this_rq->lock);
2595 cpus_and(sibling_map, sd->span, cpu_online_map);
2596 for_each_cpu_mask(i, sibling_map)
2597 spin_lock(&cpu_rq(i)->lock);
2598 cpu_clear(this_cpu, sibling_map);
2601 * Establish next task to be run - it might have gone away because
2602 * we released the runqueue lock above:
2604 if (!this_rq->nr_running)
2606 array = this_rq->active;
2607 if (!array->nr_active)
2608 array = this_rq->expired;
2609 BUG_ON(!array->nr_active);
2611 p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
2614 for_each_cpu_mask(i, sibling_map) {
2615 runqueue_t *smt_rq = cpu_rq(i);
2616 task_t *smt_curr = smt_rq->curr;
2619 * If a user task with lower static priority than the
2620 * running task on the SMT sibling is trying to schedule,
2621 * delay it till there is proportionately less timeslice
2622 * left of the sibling task to prevent a lower priority
2623 * task from using an unfair proportion of the
2624 * physical cpu's resources. -ck
2626 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
2627 task_timeslice(p) || rt_task(smt_curr)) &&
2628 p->mm && smt_curr->mm && !rt_task(p))
2632 * Reschedule a lower priority task on the SMT sibling,
2633 * or wake it up if it has been put to sleep for priority
2636 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
2637 task_timeslice(smt_curr) || rt_task(p)) &&
2638 smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
2639 (smt_curr == smt_rq->idle && smt_rq->nr_running))
2640 resched_task(smt_curr);
2643 for_each_cpu_mask(i, sibling_map)
2644 spin_unlock(&cpu_rq(i)->lock);
2648 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2652 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2659 * schedule() is the main scheduler function.
2661 asmlinkage void __sched schedule(void)
2664 task_t *prev, *next;
2666 prio_array_t *array;
2667 struct list_head *queue;
2668 unsigned long long now;
2669 unsigned long run_time;
2670 #ifdef CONFIG_VSERVER_HARDCPU
2671 struct vx_info *vxi;
2677 * Test if we are atomic. Since do_exit() needs to call into
2678 * schedule() atomically, we ignore that path for now.
2679 * Otherwise, whine if we are scheduling when we should not be.
2681 if (likely(!(current->state & (TASK_DEAD | TASK_ZOMBIE)))) {
2682 if (unlikely(in_atomic())) {
2683 printk(KERN_ERR "bad: scheduling while atomic!\n");
2694 * The idle thread is not allowed to schedule!
2695 * Remove this check after it has been exercised a bit.
2697 if (unlikely(current == rq->idle) && current->state != TASK_RUNNING) {
2698 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
2702 release_kernel_lock(prev);
2703 schedstat_inc(rq, sched_cnt);
2704 now = sched_clock();
2705 if (likely(now - prev->timestamp < NS_MAX_SLEEP_AVG))
2706 run_time = now - prev->timestamp;
2708 run_time = NS_MAX_SLEEP_AVG;
2711 * Tasks with interactive credits get charged less run_time
2712 * at high sleep_avg to delay them losing their interactive
2715 if (HIGH_CREDIT(prev))
2716 run_time /= (CURRENT_BONUS(prev) ? : 1);
2718 spin_lock_irq(&rq->lock);
2721 * if entering off of a kernel preemption go straight
2722 * to picking the next task.
2724 switch_count = &prev->nivcsw;
2725 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2726 switch_count = &prev->nvcsw;
2727 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2728 unlikely(signal_pending(prev))))
2729 prev->state = TASK_RUNNING;
2731 deactivate_task(prev, rq);
2734 #ifdef CONFIG_VSERVER_HARDCPU
2735 if (!list_empty(&rq->hold_queue)) {
2736 struct list_head *l, *n;
2740 list_for_each_safe(l, n, &rq->hold_queue) {
2741 next = list_entry(l, task_t, run_list);
2742 if (vxi == next->vx_info)
2745 vxi = next->vx_info;
2746 ret = vx_tokens_recalc(vxi);
2747 // tokens = vx_tokens_avail(next);
2750 list_del(&next->run_list);
2751 next->state &= ~TASK_ONHOLD;
2754 array = rq->expired;
2755 next->prio = MAX_PRIO-1;
2756 enqueue_task(next, array);
2758 if (next->static_prio < rq->best_expired_prio)
2759 rq->best_expired_prio = next->static_prio;
2761 // printk("··· %8lu unhold %p [%d]\n", jiffies, next, next->prio);
2764 if ((ret < 0) && (maxidle < ret))
2768 rq->idle_tokens = -maxidle;
2773 cpu = smp_processor_id();
2774 if (unlikely(!rq->nr_running)) {
2776 idle_balance(cpu, rq);
2777 if (!rq->nr_running) {
2779 rq->expired_timestamp = 0;
2780 wake_sleeping_dependent(cpu, rq);
2782 * wake_sleeping_dependent() might have released
2783 * the runqueue, so break out if we got new
2786 if (!rq->nr_running)
2790 if (dependent_sleeper(cpu, rq)) {
2791 schedstat_inc(rq, sched_goidle);
2796 * dependent_sleeper() releases and reacquires the runqueue
2797 * lock, hence go into the idle loop if the rq went
2800 if (unlikely(!rq->nr_running))
2805 if (unlikely(!array->nr_active)) {
2807 * Switch the active and expired arrays.
2809 schedstat_inc(rq, sched_switch);
2810 rq->active = rq->expired;
2811 rq->expired = array;
2813 rq->expired_timestamp = 0;
2814 rq->best_expired_prio = MAX_PRIO;
2816 schedstat_inc(rq, sched_noswitch);
2818 idx = sched_find_first_bit(array->bitmap);
2819 queue = array->queue + idx;
2820 next = list_entry(queue->next, task_t, run_list);
2822 #ifdef CONFIG_VSERVER_HARDCPU
2823 vxi = next->vx_info;
2824 if (vx_info_flags(vxi, VXF_SCHED_PAUSE|VXF_SCHED_HARD, 0)) {
2825 int ret = vx_tokens_recalc(vxi);
2827 if (unlikely(ret <= 0)) {
2828 if (ret && (rq->idle_tokens > -ret))
2829 rq->idle_tokens = -ret;
2830 __deactivate_task(next, rq);
2831 recalc_task_prio(next, now);
2832 // a new one on hold
2834 next->state |= TASK_ONHOLD;
2835 list_add_tail(&next->run_list, &rq->hold_queue);
2836 //printk("··· %8lu hold %p [%d]\n", jiffies, next, next->prio);
2842 if (!rt_task(next) && next->activated > 0) {
2843 unsigned long long delta = now - next->timestamp;
2845 if (next->activated == 1)
2846 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
2848 array = next->array;
2849 dequeue_task(next, array);
2850 recalc_task_prio(next, next->timestamp + delta);
2851 enqueue_task(next, array);
2853 next->activated = 0;
2856 clear_tsk_need_resched(prev);
2857 rcu_qsctr_inc(task_cpu(prev));
2859 prev->sleep_avg -= run_time;
2860 if ((long)prev->sleep_avg <= 0) {
2861 prev->sleep_avg = 0;
2862 if (!(HIGH_CREDIT(prev) || LOW_CREDIT(prev)))
2863 prev->interactive_credit--;
2865 prev->timestamp = prev->last_ran = now;
2867 sched_info_switch(prev, next);
2868 if (likely(prev != next)) {
2869 next->timestamp = now;
2874 prepare_arch_switch(rq, next);
2875 prev = context_switch(rq, prev, next);
2878 finish_task_switch(prev);
2880 spin_unlock_irq(&rq->lock);
2882 reacquire_kernel_lock(current);
2883 preempt_enable_no_resched();
2884 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2888 EXPORT_SYMBOL(schedule);
2890 #ifdef CONFIG_PREEMPT
2892 * this is is the entry point to schedule() from in-kernel preemption
2893 * off of preempt_enable. Kernel preemptions off return from interrupt
2894 * occur there and call schedule directly.
2896 asmlinkage void __sched preempt_schedule(void)
2898 struct thread_info *ti = current_thread_info();
2901 * If there is a non-zero preempt_count or interrupts are disabled,
2902 * we do not want to preempt the current task. Just return..
2904 if (unlikely(ti->preempt_count || irqs_disabled()))
2908 ti->preempt_count = PREEMPT_ACTIVE;
2910 ti->preempt_count = 0;
2912 /* we could miss a preemption opportunity between schedule and now */
2914 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2918 EXPORT_SYMBOL(preempt_schedule);
2919 #endif /* CONFIG_PREEMPT */
2921 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
2923 task_t *p = curr->task;
2924 return try_to_wake_up(p, mode, sync);
2927 EXPORT_SYMBOL(default_wake_function);
2930 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
2931 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
2932 * number) then we wake all the non-exclusive tasks and one exclusive task.
2934 * There are circumstances in which we can try to wake a task which has already
2935 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
2936 * zero in this (rare) case, and we handle it by continuing to scan the queue.
2938 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
2939 int nr_exclusive, int sync, void *key)
2941 struct list_head *tmp, *next;
2943 list_for_each_safe(tmp, next, &q->task_list) {
2946 curr = list_entry(tmp, wait_queue_t, task_list);
2947 flags = curr->flags;
2948 if (curr->func(curr, mode, sync, key) &&
2949 (flags & WQ_FLAG_EXCLUSIVE) &&
2956 * __wake_up - wake up threads blocked on a waitqueue.
2958 * @mode: which threads
2959 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2961 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
2962 int nr_exclusive, void *key)
2964 unsigned long flags;
2966 spin_lock_irqsave(&q->lock, flags);
2967 __wake_up_common(q, mode, nr_exclusive, 0, key);
2968 spin_unlock_irqrestore(&q->lock, flags);
2971 EXPORT_SYMBOL(__wake_up);
2974 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
2976 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
2978 __wake_up_common(q, mode, 1, 0, NULL);
2982 * __wake_up - sync- wake up threads blocked on a waitqueue.
2984 * @mode: which threads
2985 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2987 * The sync wakeup differs that the waker knows that it will schedule
2988 * away soon, so while the target thread will be woken up, it will not
2989 * be migrated to another CPU - ie. the two threads are 'synchronized'
2990 * with each other. This can prevent needless bouncing between CPUs.
2992 * On UP it can prevent extra preemption.
2994 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
2996 unsigned long flags;
3002 if (unlikely(!nr_exclusive))
3005 spin_lock_irqsave(&q->lock, flags);
3006 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3007 spin_unlock_irqrestore(&q->lock, flags);
3009 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3011 void fastcall complete(struct completion *x)
3013 unsigned long flags;
3015 spin_lock_irqsave(&x->wait.lock, flags);
3017 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3019 spin_unlock_irqrestore(&x->wait.lock, flags);
3021 EXPORT_SYMBOL(complete);
3023 void fastcall complete_all(struct completion *x)
3025 unsigned long flags;
3027 spin_lock_irqsave(&x->wait.lock, flags);
3028 x->done += UINT_MAX/2;
3029 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3031 spin_unlock_irqrestore(&x->wait.lock, flags);
3033 EXPORT_SYMBOL(complete_all);
3035 void fastcall __sched wait_for_completion(struct completion *x)
3038 spin_lock_irq(&x->wait.lock);
3040 DECLARE_WAITQUEUE(wait, current);
3042 wait.flags |= WQ_FLAG_EXCLUSIVE;
3043 __add_wait_queue_tail(&x->wait, &wait);
3045 __set_current_state(TASK_UNINTERRUPTIBLE);
3046 spin_unlock_irq(&x->wait.lock);
3048 spin_lock_irq(&x->wait.lock);
3050 __remove_wait_queue(&x->wait, &wait);
3053 spin_unlock_irq(&x->wait.lock);
3055 EXPORT_SYMBOL(wait_for_completion);
3057 #define SLEEP_ON_VAR \
3058 unsigned long flags; \
3059 wait_queue_t wait; \
3060 init_waitqueue_entry(&wait, current);
3062 #define SLEEP_ON_HEAD \
3063 spin_lock_irqsave(&q->lock,flags); \
3064 __add_wait_queue(q, &wait); \
3065 spin_unlock(&q->lock);
3067 #define SLEEP_ON_TAIL \
3068 spin_lock_irq(&q->lock); \
3069 __remove_wait_queue(q, &wait); \
3070 spin_unlock_irqrestore(&q->lock, flags);
3072 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3076 current->state = TASK_INTERRUPTIBLE;
3083 EXPORT_SYMBOL(interruptible_sleep_on);
3085 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3089 current->state = TASK_INTERRUPTIBLE;
3092 timeout = schedule_timeout(timeout);
3098 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3100 void fastcall __sched sleep_on(wait_queue_head_t *q)
3104 current->state = TASK_UNINTERRUPTIBLE;
3111 EXPORT_SYMBOL(sleep_on);
3113 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3117 current->state = TASK_UNINTERRUPTIBLE;
3120 timeout = schedule_timeout(timeout);
3126 EXPORT_SYMBOL(sleep_on_timeout);
3128 void set_user_nice(task_t *p, long nice)
3130 unsigned long flags;
3131 prio_array_t *array;
3133 int old_prio, new_prio, delta;
3135 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3138 * We have to be careful, if called from sys_setpriority(),
3139 * the task might be in the middle of scheduling on another CPU.
3141 rq = task_rq_lock(p, &flags);
3143 * The RT priorities are set via setscheduler(), but we still
3144 * allow the 'normal' nice value to be set - but as expected
3145 * it wont have any effect on scheduling until the task is
3149 p->static_prio = NICE_TO_PRIO(nice);
3154 dequeue_task(p, array);
3157 new_prio = NICE_TO_PRIO(nice);
3158 delta = new_prio - old_prio;
3159 p->static_prio = NICE_TO_PRIO(nice);
3163 enqueue_task(p, array);
3165 * If the task increased its priority or is running and
3166 * lowered its priority, then reschedule its CPU:
3168 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3169 resched_task(rq->curr);
3172 task_rq_unlock(rq, &flags);
3175 EXPORT_SYMBOL(set_user_nice);
3177 #ifdef __ARCH_WANT_SYS_NICE
3180 * sys_nice - change the priority of the current process.
3181 * @increment: priority increment
3183 * sys_setpriority is a more generic, but much slower function that
3184 * does similar things.
3186 asmlinkage long sys_nice(int increment)
3192 * Setpriority might change our priority at the same moment.
3193 * We don't have to worry. Conceptually one call occurs first
3194 * and we have a single winner.
3196 if (increment < 0) {
3197 if (vx_flags(VXF_IGNEG_NICE, 0))
3199 if (!capable(CAP_SYS_NICE))
3201 if (increment < -40)
3207 nice = PRIO_TO_NICE(current->static_prio) + increment;
3213 retval = security_task_setnice(current, nice);
3217 set_user_nice(current, nice);
3224 * task_prio - return the priority value of a given task.
3225 * @p: the task in question.
3227 * This is the priority value as seen by users in /proc.
3228 * RT tasks are offset by -200. Normal tasks are centered
3229 * around 0, value goes from -16 to +15.
3231 int task_prio(const task_t *p)
3233 return p->prio - MAX_RT_PRIO;
3237 * task_nice - return the nice value of a given task.
3238 * @p: the task in question.
3240 int task_nice(const task_t *p)
3242 return TASK_NICE(p);
3245 EXPORT_SYMBOL(task_nice);
3248 * idle_cpu - is a given cpu idle currently?
3249 * @cpu: the processor in question.
3251 int idle_cpu(int cpu)
3253 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3256 EXPORT_SYMBOL_GPL(idle_cpu);
3259 * find_process_by_pid - find a process with a matching PID value.
3260 * @pid: the pid in question.
3262 static inline task_t *find_process_by_pid(pid_t pid)
3264 return pid ? find_task_by_pid(pid) : current;
3267 /* Actually do priority change: must hold rq lock. */
3268 static void __setscheduler(struct task_struct *p, int policy, int prio)
3272 p->rt_priority = prio;
3273 if (policy != SCHED_NORMAL)
3274 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
3276 p->prio = p->static_prio;
3280 * setscheduler - change the scheduling policy and/or RT priority of a thread.
3282 static int setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3284 struct sched_param lp;
3285 int retval = -EINVAL;
3287 prio_array_t *array;
3288 unsigned long flags;
3292 if (!param || pid < 0)
3296 if (copy_from_user(&lp, param, sizeof(struct sched_param)))
3300 * We play safe to avoid deadlocks.
3302 read_lock_irq(&tasklist_lock);
3304 p = find_process_by_pid(pid);
3308 goto out_unlock_tasklist;
3311 * To be able to change p->policy safely, the apropriate
3312 * runqueue lock must be held.
3314 rq = task_rq_lock(p, &flags);
3320 if (policy != SCHED_FIFO && policy != SCHED_RR &&
3321 policy != SCHED_NORMAL)
3324 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3327 * Valid priorities for SCHED_FIFO and SCHED_RR are
3328 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
3331 if (lp.sched_priority < 0 || lp.sched_priority > MAX_USER_RT_PRIO-1)
3333 if ((policy == SCHED_NORMAL) != (lp.sched_priority == 0))
3337 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
3338 !capable(CAP_SYS_NICE))
3340 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3341 !capable(CAP_SYS_NICE))
3344 retval = security_task_setscheduler(p, policy, &lp);
3350 deactivate_task(p, task_rq(p));
3353 __setscheduler(p, policy, lp.sched_priority);
3355 vx_activate_task(p);
3356 __activate_task(p, task_rq(p));
3358 * Reschedule if we are currently running on this runqueue and
3359 * our priority decreased, or if we are not currently running on
3360 * this runqueue and our priority is higher than the current's
3362 if (task_running(rq, p)) {
3363 if (p->prio > oldprio)
3364 resched_task(rq->curr);
3365 } else if (TASK_PREEMPTS_CURR(p, rq))
3366 resched_task(rq->curr);
3370 task_rq_unlock(rq, &flags);
3371 out_unlock_tasklist:
3372 read_unlock_irq(&tasklist_lock);
3379 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3380 * @pid: the pid in question.
3381 * @policy: new policy
3382 * @param: structure containing the new RT priority.
3384 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3385 struct sched_param __user *param)
3387 return setscheduler(pid, policy, param);
3391 * sys_sched_setparam - set/change the RT priority of a thread
3392 * @pid: the pid in question.
3393 * @param: structure containing the new RT priority.
3395 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3397 return setscheduler(pid, -1, param);
3401 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3402 * @pid: the pid in question.
3404 asmlinkage long sys_sched_getscheduler(pid_t pid)
3406 int retval = -EINVAL;
3413 read_lock(&tasklist_lock);
3414 p = find_process_by_pid(pid);
3416 retval = security_task_getscheduler(p);
3420 read_unlock(&tasklist_lock);
3427 * sys_sched_getscheduler - get the RT priority of a thread
3428 * @pid: the pid in question.
3429 * @param: structure containing the RT priority.
3431 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3433 struct sched_param lp;
3434 int retval = -EINVAL;
3437 if (!param || pid < 0)
3440 read_lock(&tasklist_lock);
3441 p = find_process_by_pid(pid);
3446 retval = security_task_getscheduler(p);
3450 lp.sched_priority = p->rt_priority;
3451 read_unlock(&tasklist_lock);
3454 * This one might sleep, we cannot do it with a spinlock held ...
3456 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3462 read_unlock(&tasklist_lock);
3466 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
3472 read_lock(&tasklist_lock);
3474 p = find_process_by_pid(pid);
3476 read_unlock(&tasklist_lock);
3477 unlock_cpu_hotplug();
3482 * It is not safe to call set_cpus_allowed with the
3483 * tasklist_lock held. We will bump the task_struct's
3484 * usage count and then drop tasklist_lock.
3487 read_unlock(&tasklist_lock);
3490 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3491 !capable(CAP_SYS_NICE))
3494 retval = set_cpus_allowed(p, new_mask);
3498 unlock_cpu_hotplug();
3502 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
3503 cpumask_t *new_mask)
3505 if (len < sizeof(cpumask_t)) {
3506 memset(new_mask, 0, sizeof(cpumask_t));
3507 } else if (len > sizeof(cpumask_t)) {
3508 len = sizeof(cpumask_t);
3510 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
3514 * sys_sched_setaffinity - set the cpu affinity of a process
3515 * @pid: pid of the process
3516 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3517 * @user_mask_ptr: user-space pointer to the new cpu mask
3519 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
3520 unsigned long __user *user_mask_ptr)
3525 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
3529 return sched_setaffinity(pid, new_mask);
3533 * Represents all cpu's present in the system
3534 * In systems capable of hotplug, this map could dynamically grow
3535 * as new cpu's are detected in the system via any platform specific
3536 * method, such as ACPI for e.g.
3539 cpumask_t cpu_present_map;
3540 EXPORT_SYMBOL(cpu_present_map);
3543 cpumask_t cpu_online_map = CPU_MASK_ALL;
3544 cpumask_t cpu_possible_map = CPU_MASK_ALL;
3547 long sched_getaffinity(pid_t pid, cpumask_t *mask)
3553 read_lock(&tasklist_lock);
3556 p = find_process_by_pid(pid);
3561 cpus_and(*mask, p->cpus_allowed, cpu_possible_map);
3564 read_unlock(&tasklist_lock);
3565 unlock_cpu_hotplug();
3573 * sys_sched_getaffinity - get the cpu affinity of a process
3574 * @pid: pid of the process
3575 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3576 * @user_mask_ptr: user-space pointer to hold the current cpu mask
3578 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
3579 unsigned long __user *user_mask_ptr)
3584 if (len < sizeof(cpumask_t))
3587 ret = sched_getaffinity(pid, &mask);
3591 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
3594 return sizeof(cpumask_t);
3598 * sys_sched_yield - yield the current processor to other threads.
3600 * this function yields the current CPU by moving the calling thread
3601 * to the expired array. If there are no other threads running on this
3602 * CPU then this function will return.
3604 asmlinkage long sys_sched_yield(void)
3606 runqueue_t *rq = this_rq_lock();
3607 prio_array_t *array = current->array;
3608 prio_array_t *target = rq->expired;
3610 schedstat_inc(rq, yld_cnt);
3612 * We implement yielding by moving the task into the expired
3615 * (special rule: RT tasks will just roundrobin in the active
3618 if (rt_task(current))
3619 target = rq->active;
3621 if (current->array->nr_active == 1) {
3622 schedstat_inc(rq, yld_act_empty);
3623 if (!rq->expired->nr_active)
3624 schedstat_inc(rq, yld_both_empty);
3625 } else if (!rq->expired->nr_active)
3626 schedstat_inc(rq, yld_exp_empty);
3628 dequeue_task(current, array);
3629 enqueue_task(current, target);
3632 * Since we are going to call schedule() anyway, there's
3633 * no need to preempt or enable interrupts:
3635 _raw_spin_unlock(&rq->lock);
3636 preempt_enable_no_resched();
3643 void __sched __cond_resched(void)
3645 set_current_state(TASK_RUNNING);
3649 EXPORT_SYMBOL(__cond_resched);
3652 * yield - yield the current processor to other threads.
3654 * this is a shortcut for kernel-space yielding - it marks the
3655 * thread runnable and calls sys_sched_yield().
3657 void __sched yield(void)
3659 set_current_state(TASK_RUNNING);
3663 EXPORT_SYMBOL(yield);
3666 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
3667 * that process accounting knows that this is a task in IO wait state.
3669 * But don't do that if it is a deliberate, throttling IO wait (this task
3670 * has set its backing_dev_info: the queue against which it should throttle)
3672 void __sched io_schedule(void)
3674 struct runqueue *rq = this_rq();
3676 atomic_inc(&rq->nr_iowait);
3678 atomic_dec(&rq->nr_iowait);
3681 EXPORT_SYMBOL(io_schedule);
3683 long __sched io_schedule_timeout(long timeout)
3685 struct runqueue *rq = this_rq();
3688 atomic_inc(&rq->nr_iowait);
3689 ret = schedule_timeout(timeout);
3690 atomic_dec(&rq->nr_iowait);
3695 * sys_sched_get_priority_max - return maximum RT priority.
3696 * @policy: scheduling class.
3698 * this syscall returns the maximum rt_priority that can be used
3699 * by a given scheduling class.
3701 asmlinkage long sys_sched_get_priority_max(int policy)
3708 ret = MAX_USER_RT_PRIO-1;
3718 * sys_sched_get_priority_min - return minimum RT priority.
3719 * @policy: scheduling class.
3721 * this syscall returns the minimum rt_priority that can be used
3722 * by a given scheduling class.
3724 asmlinkage long sys_sched_get_priority_min(int policy)
3740 * sys_sched_rr_get_interval - return the default timeslice of a process.
3741 * @pid: pid of the process.
3742 * @interval: userspace pointer to the timeslice value.
3744 * this syscall writes the default timeslice value of a given process
3745 * into the user-space timespec buffer. A value of '0' means infinity.
3748 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
3750 int retval = -EINVAL;
3758 read_lock(&tasklist_lock);
3759 p = find_process_by_pid(pid);
3763 retval = security_task_getscheduler(p);
3767 jiffies_to_timespec(p->policy & SCHED_FIFO ?
3768 0 : task_timeslice(p), &t);
3769 read_unlock(&tasklist_lock);
3770 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
3774 read_unlock(&tasklist_lock);
3778 static inline struct task_struct *eldest_child(struct task_struct *p)
3780 if (list_empty(&p->children)) return NULL;
3781 return list_entry(p->children.next,struct task_struct,sibling);
3784 static inline struct task_struct *older_sibling(struct task_struct *p)
3786 if (p->sibling.prev==&p->parent->children) return NULL;
3787 return list_entry(p->sibling.prev,struct task_struct,sibling);
3790 static inline struct task_struct *younger_sibling(struct task_struct *p)
3792 if (p->sibling.next==&p->parent->children) return NULL;
3793 return list_entry(p->sibling.next,struct task_struct,sibling);
3796 static void show_task(task_t * p)
3800 unsigned long free = 0;
3801 static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
3803 printk("%-13.13s ", p->comm);
3804 state = p->state ? __ffs(p->state) + 1 : 0;
3805 if (state < ARRAY_SIZE(stat_nam))
3806 printk(stat_nam[state]);
3809 #if (BITS_PER_LONG == 32)
3810 if (state == TASK_RUNNING)
3811 printk(" running ");
3813 printk(" %08lX ", thread_saved_pc(p));
3815 if (state == TASK_RUNNING)
3816 printk(" running task ");
3818 printk(" %016lx ", thread_saved_pc(p));
3820 #ifdef CONFIG_DEBUG_STACK_USAGE
3822 unsigned long * n = (unsigned long *) (p->thread_info+1);
3825 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
3828 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
3829 if ((relative = eldest_child(p)))
3830 printk("%5d ", relative->pid);
3833 if ((relative = younger_sibling(p)))
3834 printk("%7d", relative->pid);
3837 if ((relative = older_sibling(p)))
3838 printk(" %5d", relative->pid);
3842 printk(" (L-TLB)\n");
3844 printk(" (NOTLB)\n");
3846 if (state != TASK_RUNNING)
3847 show_stack(p, NULL);
3850 void show_state(void)
3854 #if (BITS_PER_LONG == 32)
3857 printk(" task PC pid father child younger older\n");
3861 printk(" task PC pid father child younger older\n");
3863 read_lock(&tasklist_lock);
3864 do_each_thread(g, p) {
3866 * reset the NMI-timeout, listing all files on a slow
3867 * console might take alot of time:
3869 touch_nmi_watchdog();
3871 } while_each_thread(g, p);
3873 read_unlock(&tasklist_lock);
3876 void __devinit init_idle(task_t *idle, int cpu)
3878 runqueue_t *rq = cpu_rq(cpu);
3879 unsigned long flags;
3881 idle->sleep_avg = 0;
3882 idle->interactive_credit = 0;
3884 idle->prio = MAX_PRIO;
3885 idle->state = TASK_RUNNING;
3886 set_task_cpu(idle, cpu);
3888 spin_lock_irqsave(&rq->lock, flags);
3889 rq->curr = rq->idle = idle;
3890 set_tsk_need_resched(idle);
3891 spin_unlock_irqrestore(&rq->lock, flags);
3893 /* Set the preempt count _outside_ the spinlocks! */
3894 #ifdef CONFIG_PREEMPT
3895 idle->thread_info->preempt_count = (idle->lock_depth >= 0);
3897 idle->thread_info->preempt_count = 0;
3902 * In a system that switches off the HZ timer nohz_cpu_mask
3903 * indicates which cpus entered this state. This is used
3904 * in the rcu update to wait only for active cpus. For system
3905 * which do not switch off the HZ timer nohz_cpu_mask should
3906 * always be CPU_MASK_NONE.
3908 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
3912 * This is how migration works:
3914 * 1) we queue a migration_req_t structure in the source CPU's
3915 * runqueue and wake up that CPU's migration thread.
3916 * 2) we down() the locked semaphore => thread blocks.
3917 * 3) migration thread wakes up (implicitly it forces the migrated
3918 * thread off the CPU)
3919 * 4) it gets the migration request and checks whether the migrated
3920 * task is still in the wrong runqueue.
3921 * 5) if it's in the wrong runqueue then the migration thread removes
3922 * it and puts it into the right queue.
3923 * 6) migration thread up()s the semaphore.
3924 * 7) we wake up and the migration is done.
3928 * Change a given task's CPU affinity. Migrate the thread to a
3929 * proper CPU and schedule it away if the CPU it's executing on
3930 * is removed from the allowed bitmask.
3932 * NOTE: the caller must have a valid reference to the task, the
3933 * task must not exit() & deallocate itself prematurely. The
3934 * call is not atomic; no spinlocks may be held.
3936 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
3938 unsigned long flags;
3940 migration_req_t req;
3943 rq = task_rq_lock(p, &flags);
3944 if (!cpus_intersects(new_mask, cpu_online_map)) {
3949 p->cpus_allowed = new_mask;
3950 /* Can the task run on the task's current CPU? If so, we're done */
3951 if (cpu_isset(task_cpu(p), new_mask))
3954 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
3955 /* Need help from migration thread: drop lock and wait. */
3956 task_rq_unlock(rq, &flags);
3957 wake_up_process(rq->migration_thread);
3958 wait_for_completion(&req.done);
3959 tlb_migrate_finish(p->mm);
3963 task_rq_unlock(rq, &flags);
3967 EXPORT_SYMBOL_GPL(set_cpus_allowed);
3970 * Move (not current) task off this cpu, onto dest cpu. We're doing
3971 * this because either it can't run here any more (set_cpus_allowed()
3972 * away from this CPU, or CPU going down), or because we're
3973 * attempting to rebalance this task on exec (sched_exec).
3975 * So we race with normal scheduler movements, but that's OK, as long
3976 * as the task is no longer on this CPU.
3978 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
3980 runqueue_t *rq_dest, *rq_src;
3982 if (unlikely(cpu_is_offline(dest_cpu)))
3985 rq_src = cpu_rq(src_cpu);
3986 rq_dest = cpu_rq(dest_cpu);
3988 double_rq_lock(rq_src, rq_dest);
3989 /* Already moved. */
3990 if (task_cpu(p) != src_cpu)
3992 /* Affinity changed (again). */
3993 if (!cpu_isset(dest_cpu, p->cpus_allowed))
3996 set_task_cpu(p, dest_cpu);
3999 * Sync timestamp with rq_dest's before activating.
4000 * The same thing could be achieved by doing this step
4001 * afterwards, and pretending it was a local activate.
4002 * This way is cleaner and logically correct.
4004 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4005 + rq_dest->timestamp_last_tick;
4006 deactivate_task(p, rq_src);
4007 activate_task(p, rq_dest, 0);
4008 if (TASK_PREEMPTS_CURR(p, rq_dest))
4009 resched_task(rq_dest->curr);
4013 double_rq_unlock(rq_src, rq_dest);
4017 * migration_thread - this is a highprio system thread that performs
4018 * thread migration by bumping thread off CPU then 'pushing' onto
4021 static int migration_thread(void * data)
4024 int cpu = (long)data;
4027 BUG_ON(rq->migration_thread != current);
4029 set_current_state(TASK_INTERRUPTIBLE);
4030 while (!kthread_should_stop()) {
4031 struct list_head *head;
4032 migration_req_t *req;
4034 if (current->flags & PF_FREEZE)
4035 refrigerator(PF_FREEZE);
4037 spin_lock_irq(&rq->lock);
4039 if (cpu_is_offline(cpu)) {
4040 spin_unlock_irq(&rq->lock);
4044 if (rq->active_balance) {
4045 active_load_balance(rq, cpu);
4046 rq->active_balance = 0;
4049 head = &rq->migration_queue;
4051 if (list_empty(head)) {
4052 spin_unlock_irq(&rq->lock);
4054 set_current_state(TASK_INTERRUPTIBLE);
4057 req = list_entry(head->next, migration_req_t, list);
4058 list_del_init(head->next);
4060 if (req->type == REQ_MOVE_TASK) {
4061 spin_unlock(&rq->lock);
4062 __migrate_task(req->task, smp_processor_id(),
4065 } else if (req->type == REQ_SET_DOMAIN) {
4067 spin_unlock_irq(&rq->lock);
4069 spin_unlock_irq(&rq->lock);
4073 complete(&req->done);
4075 __set_current_state(TASK_RUNNING);
4079 /* Wait for kthread_stop */
4080 set_current_state(TASK_INTERRUPTIBLE);
4081 while (!kthread_should_stop()) {
4083 set_current_state(TASK_INTERRUPTIBLE);
4085 __set_current_state(TASK_RUNNING);
4089 #ifdef CONFIG_HOTPLUG_CPU
4090 /* Figure out where task on dead CPU should go, use force if neccessary. */
4091 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
4097 mask = node_to_cpumask(cpu_to_node(dead_cpu));
4098 cpus_and(mask, mask, tsk->cpus_allowed);
4099 dest_cpu = any_online_cpu(mask);
4101 /* On any allowed CPU? */
4102 if (dest_cpu == NR_CPUS)
4103 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4105 /* No more Mr. Nice Guy. */
4106 if (dest_cpu == NR_CPUS) {
4107 cpus_setall(tsk->cpus_allowed);
4108 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4111 * Don't tell them about moving exiting tasks or
4112 * kernel threads (both mm NULL), since they never
4115 if (tsk->mm && printk_ratelimit())
4116 printk(KERN_INFO "process %d (%s) no "
4117 "longer affine to cpu%d\n",
4118 tsk->pid, tsk->comm, dead_cpu);
4120 __migrate_task(tsk, dead_cpu, dest_cpu);
4123 /* Run through task list and migrate tasks from the dead cpu. */
4124 static void migrate_live_tasks(int src_cpu)
4126 struct task_struct *tsk, *t;
4128 write_lock_irq(&tasklist_lock);
4130 do_each_thread(t, tsk) {
4134 if (task_cpu(tsk) == src_cpu)
4135 move_task_off_dead_cpu(src_cpu, tsk);
4136 } while_each_thread(t, tsk);
4138 write_unlock_irq(&tasklist_lock);
4141 /* Schedules idle task to be the next runnable task on current CPU.
4142 * It does so by boosting its priority to highest possible and adding it to
4143 * the _front_ of runqueue. Used by CPU offline code.
4145 void sched_idle_next(void)
4147 int cpu = smp_processor_id();
4148 runqueue_t *rq = this_rq();
4149 struct task_struct *p = rq->idle;
4150 unsigned long flags;
4152 /* cpu has to be offline */
4153 BUG_ON(cpu_online(cpu));
4155 /* Strictly not necessary since rest of the CPUs are stopped by now
4156 * and interrupts disabled on current cpu.
4158 spin_lock_irqsave(&rq->lock, flags);
4160 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4161 /* Add idle task to _front_ of it's priority queue */
4162 __activate_idle_task(p, rq);
4164 spin_unlock_irqrestore(&rq->lock, flags);
4167 static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
4169 struct runqueue *rq = cpu_rq(dead_cpu);
4171 /* Must be exiting, otherwise would be on tasklist. */
4172 BUG_ON(tsk->state != TASK_ZOMBIE && tsk->state != TASK_DEAD);
4174 /* Cannot have done final schedule yet: would have vanished. */
4175 BUG_ON(tsk->flags & PF_DEAD);
4177 get_task_struct(tsk);
4180 * Drop lock around migration; if someone else moves it,
4181 * that's OK. No task can be added to this CPU, so iteration is
4184 spin_unlock_irq(&rq->lock);
4185 move_task_off_dead_cpu(dead_cpu, tsk);
4186 spin_lock_irq(&rq->lock);
4188 put_task_struct(tsk);
4191 /* release_task() removes task from tasklist, so we won't find dead tasks. */
4192 static void migrate_dead_tasks(unsigned int dead_cpu)
4195 struct runqueue *rq = cpu_rq(dead_cpu);
4197 for (arr = 0; arr < 2; arr++) {
4198 for (i = 0; i < MAX_PRIO; i++) {
4199 struct list_head *list = &rq->arrays[arr].queue[i];
4200 while (!list_empty(list))
4201 migrate_dead(dead_cpu,
4202 list_entry(list->next, task_t,
4207 #endif /* CONFIG_HOTPLUG_CPU */
4210 * migration_call - callback that gets triggered when a CPU is added.
4211 * Here we can start up the necessary migration thread for the new CPU.
4213 static int migration_call(struct notifier_block *nfb, unsigned long action,
4216 int cpu = (long)hcpu;
4217 struct task_struct *p;
4218 struct runqueue *rq;
4219 unsigned long flags;
4222 case CPU_UP_PREPARE:
4223 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4226 p->flags |= PF_NOFREEZE;
4227 kthread_bind(p, cpu);
4228 /* Must be high prio: stop_machine expects to yield to it. */
4229 rq = task_rq_lock(p, &flags);
4230 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4231 task_rq_unlock(rq, &flags);
4232 cpu_rq(cpu)->migration_thread = p;
4235 /* Strictly unneccessary, as first user will wake it. */
4236 wake_up_process(cpu_rq(cpu)->migration_thread);
4238 #ifdef CONFIG_HOTPLUG_CPU
4239 case CPU_UP_CANCELED:
4240 /* Unbind it from offline cpu so it can run. Fall thru. */
4241 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
4242 kthread_stop(cpu_rq(cpu)->migration_thread);
4243 cpu_rq(cpu)->migration_thread = NULL;
4246 migrate_live_tasks(cpu);
4248 kthread_stop(rq->migration_thread);
4249 rq->migration_thread = NULL;
4250 /* Idle task back to normal (off runqueue, low prio) */
4251 rq = task_rq_lock(rq->idle, &flags);
4252 deactivate_task(rq->idle, rq);
4253 rq->idle->static_prio = MAX_PRIO;
4254 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4255 migrate_dead_tasks(cpu);
4256 task_rq_unlock(rq, &flags);
4257 BUG_ON(rq->nr_running != 0);
4259 /* No need to migrate the tasks: it was best-effort if
4260 * they didn't do lock_cpu_hotplug(). Just wake up
4261 * the requestors. */
4262 spin_lock_irq(&rq->lock);
4263 while (!list_empty(&rq->migration_queue)) {
4264 migration_req_t *req;
4265 req = list_entry(rq->migration_queue.next,
4266 migration_req_t, list);
4267 BUG_ON(req->type != REQ_MOVE_TASK);
4268 list_del_init(&req->list);
4269 complete(&req->done);
4271 spin_unlock_irq(&rq->lock);
4278 /* Register at highest priority so that task migration (migrate_all_tasks)
4279 * happens before everything else.
4281 static struct notifier_block __devinitdata migration_notifier = {
4282 .notifier_call = migration_call,
4286 int __init migration_init(void)
4288 void *cpu = (void *)(long)smp_processor_id();
4289 /* Start one for boot CPU. */
4290 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4291 migration_call(&migration_notifier, CPU_ONLINE, cpu);
4292 register_cpu_notifier(&migration_notifier);
4298 * The 'big kernel lock'
4300 * This spinlock is taken and released recursively by lock_kernel()
4301 * and unlock_kernel(). It is transparently dropped and reaquired
4302 * over schedule(). It is used to protect legacy code that hasn't
4303 * been migrated to a proper locking design yet.
4305 * Don't use in new code.
4307 * Note: spinlock debugging needs this even on !CONFIG_SMP.
4309 spinlock_t kernel_flag __cacheline_aligned_in_smp = SPIN_LOCK_UNLOCKED;
4310 EXPORT_SYMBOL(kernel_flag);
4313 /* Attach the domain 'sd' to 'cpu' as its base domain */
4314 static void cpu_attach_domain(struct sched_domain *sd, int cpu)
4316 migration_req_t req;
4317 unsigned long flags;
4318 runqueue_t *rq = cpu_rq(cpu);
4323 spin_lock_irqsave(&rq->lock, flags);
4325 if (cpu == smp_processor_id() || !cpu_online(cpu)) {
4328 init_completion(&req.done);
4329 req.type = REQ_SET_DOMAIN;
4331 list_add(&req.list, &rq->migration_queue);
4335 spin_unlock_irqrestore(&rq->lock, flags);
4338 wake_up_process(rq->migration_thread);
4339 wait_for_completion(&req.done);
4342 unlock_cpu_hotplug();
4346 * To enable disjoint top-level NUMA domains, define SD_NODES_PER_DOMAIN
4347 * in arch code. That defines the number of nearby nodes in a node's top
4348 * level scheduling domain.
4350 #if defined(CONFIG_NUMA) && defined(SD_NODES_PER_DOMAIN)
4352 * find_next_best_node - find the next node to include in a sched_domain
4353 * @node: node whose sched_domain we're building
4354 * @used_nodes: nodes already in the sched_domain
4356 * Find the next node to include in a given scheduling domain. Simply
4357 * finds the closest node not already in the @used_nodes map.
4359 * Should use nodemask_t.
4361 static int __init find_next_best_node(int node, unsigned long *used_nodes)
4363 int i, n, val, min_val, best_node = 0;
4367 for (i = 0; i < numnodes; i++) {
4368 /* Start at @node */
4369 n = (node + i) % numnodes;
4371 /* Skip already used nodes */
4372 if (test_bit(n, used_nodes))
4375 /* Simple min distance search */
4376 val = node_distance(node, i);
4378 if (val < min_val) {
4384 set_bit(best_node, used_nodes);
4389 * sched_domain_node_span - get a cpumask for a node's sched_domain
4390 * @node: node whose cpumask we're constructing
4391 * @size: number of nodes to include in this span
4393 * Given a node, construct a good cpumask for its sched_domain to span. It
4394 * should be one that prevents unnecessary balancing, but also spreads tasks
4397 cpumask_t __init sched_domain_node_span(int node)
4401 DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
4404 bitmap_zero(used_nodes, MAX_NUMNODES);
4406 for (i = 0; i < SD_NODES_PER_DOMAIN; i++) {
4407 int next_node = find_next_best_node(node, used_nodes);
4410 nodemask = node_to_cpumask(next_node);
4411 cpus_or(span, span, nodemask);
4416 #else /* CONFIG_NUMA && SD_NODES_PER_DOMAIN */
4417 cpumask_t __init sched_domain_node_span(int node)
4419 return cpu_possible_map;
4421 #endif /* CONFIG_NUMA && SD_NODES_PER_DOMAIN */
4423 #ifdef CONFIG_SCHED_SMT
4424 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
4425 static struct sched_group sched_group_cpus[NR_CPUS];
4426 __init static int cpu_to_cpu_group(int cpu)
4432 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
4433 static struct sched_group sched_group_phys[NR_CPUS];
4434 __init static int cpu_to_phys_group(int cpu)
4436 #ifdef CONFIG_SCHED_SMT
4437 return first_cpu(cpu_sibling_map[cpu]);
4445 static DEFINE_PER_CPU(struct sched_domain, node_domains);
4446 static struct sched_group sched_group_nodes[MAX_NUMNODES];
4447 __init static int cpu_to_node_group(int cpu)
4449 return cpu_to_node(cpu);
4453 /* Groups for isolated scheduling domains */
4454 static struct sched_group sched_group_isolated[NR_CPUS];
4456 /* cpus with isolated domains */
4457 cpumask_t __initdata cpu_isolated_map = CPU_MASK_NONE;
4459 __init static int cpu_to_isolated_group(int cpu)
4464 /* Setup the mask of cpus configured for isolated domains */
4465 static int __init isolated_cpu_setup(char *str)
4467 int ints[NR_CPUS], i;
4469 str = get_options(str, ARRAY_SIZE(ints), ints);
4470 cpus_clear(cpu_isolated_map);
4471 for (i = 1; i <= ints[0]; i++)
4472 cpu_set(ints[i], cpu_isolated_map);
4476 __setup ("isolcpus=", isolated_cpu_setup);
4479 * init_sched_build_groups takes an array of groups, the cpumask we wish
4480 * to span, and a pointer to a function which identifies what group a CPU
4481 * belongs to. The return value of group_fn must be a valid index into the
4482 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
4483 * keep track of groups covered with a cpumask_t).
4485 * init_sched_build_groups will build a circular linked list of the groups
4486 * covered by the given span, and will set each group's ->cpumask correctly,
4487 * and ->cpu_power to 0.
4489 __init static void init_sched_build_groups(struct sched_group groups[],
4490 cpumask_t span, int (*group_fn)(int cpu))
4492 struct sched_group *first = NULL, *last = NULL;
4493 cpumask_t covered = CPU_MASK_NONE;
4496 for_each_cpu_mask(i, span) {
4497 int group = group_fn(i);
4498 struct sched_group *sg = &groups[group];
4501 if (cpu_isset(i, covered))
4504 sg->cpumask = CPU_MASK_NONE;
4507 for_each_cpu_mask(j, span) {
4508 if (group_fn(j) != group)
4511 cpu_set(j, covered);
4512 cpu_set(j, sg->cpumask);
4523 __init static void arch_init_sched_domains(void)
4526 cpumask_t cpu_default_map;
4529 * Setup mask for cpus without special case scheduling requirements.
4530 * For now this just excludes isolated cpus, but could be used to
4531 * exclude other special cases in the future.
4533 cpus_complement(cpu_default_map, cpu_isolated_map);
4534 cpus_and(cpu_default_map, cpu_default_map, cpu_possible_map);
4536 /* Set up domains */
4539 struct sched_domain *sd = NULL, *p;
4540 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
4542 cpus_and(nodemask, nodemask, cpu_default_map);
4545 * Set up isolated domains.
4546 * Unlike those of other cpus, the domains and groups are
4547 * single level, and span a single cpu.
4549 if (cpu_isset(i, cpu_isolated_map)) {
4550 #ifdef CONFIG_SCHED_SMT
4551 sd = &per_cpu(cpu_domains, i);
4553 sd = &per_cpu(phys_domains, i);
4555 group = cpu_to_isolated_group(i);
4557 cpu_set(i, sd->span);
4558 sd->balance_interval = INT_MAX; /* Don't balance */
4559 sd->flags = 0; /* Avoid WAKE_ */
4560 sd->groups = &sched_group_isolated[group];
4561 printk(KERN_INFO "Setting up cpu %d isolated.\n", i);
4562 /* Single level, so continue with next cpu */
4567 sd = &per_cpu(node_domains, i);
4568 group = cpu_to_node_group(i);
4570 /* FIXME: should be multilevel, in arch code */
4571 sd->span = sched_domain_node_span(i);
4572 cpus_and(sd->span, sd->span, cpu_default_map);
4573 sd->groups = &sched_group_nodes[group];
4577 sd = &per_cpu(phys_domains, i);
4578 group = cpu_to_phys_group(i);
4581 sd->span = nodemask;
4583 sd->span = cpu_possible_map;
4586 sd->groups = &sched_group_phys[group];
4588 #ifdef CONFIG_SCHED_SMT
4590 sd = &per_cpu(cpu_domains, i);
4591 group = cpu_to_cpu_group(i);
4592 *sd = SD_SIBLING_INIT;
4593 sd->span = cpu_sibling_map[i];
4594 cpus_and(sd->span, sd->span, cpu_default_map);
4596 sd->groups = &sched_group_cpus[group];
4600 #ifdef CONFIG_SCHED_SMT
4601 /* Set up CPU (sibling) groups */
4603 cpumask_t this_sibling_map = cpu_sibling_map[i];
4604 cpus_and(this_sibling_map, this_sibling_map, cpu_default_map);
4605 if (i != first_cpu(this_sibling_map))
4608 init_sched_build_groups(sched_group_cpus, this_sibling_map,
4613 /* Set up isolated groups */
4614 for_each_cpu_mask(i, cpu_isolated_map) {
4618 init_sched_build_groups(sched_group_isolated, mask,
4619 &cpu_to_isolated_group);
4623 /* Set up physical groups */
4624 for (i = 0; i < MAX_NUMNODES; i++) {
4625 cpumask_t nodemask = node_to_cpumask(i);
4627 cpus_and(nodemask, nodemask, cpu_default_map);
4628 if (cpus_empty(nodemask))
4631 init_sched_build_groups(sched_group_phys, nodemask,
4632 &cpu_to_phys_group);
4635 init_sched_build_groups(sched_group_phys, cpu_possible_map,
4636 &cpu_to_phys_group);
4640 /* Set up node groups */
4641 init_sched_build_groups(sched_group_nodes, cpu_default_map,
4642 &cpu_to_node_group);
4645 /* Calculate CPU power for physical packages and nodes */
4646 for_each_cpu_mask(i, cpu_default_map) {
4648 struct sched_domain *sd;
4649 #ifdef CONFIG_SCHED_SMT
4650 sd = &per_cpu(cpu_domains, i);
4651 power = SCHED_LOAD_SCALE;
4652 sd->groups->cpu_power = power;
4655 sd = &per_cpu(phys_domains, i);
4656 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
4657 (cpus_weight(sd->groups->cpumask)-1) / 10;
4658 sd->groups->cpu_power = power;
4661 if (i == first_cpu(sd->groups->cpumask)) {
4662 /* Only add "power" once for each physical package. */
4663 sd = &per_cpu(node_domains, i);
4664 sd->groups->cpu_power += power;
4669 /* Attach the domains */
4671 struct sched_domain *sd;
4672 #ifdef CONFIG_SCHED_SMT
4673 sd = &per_cpu(cpu_domains, i);
4675 sd = &per_cpu(phys_domains, i);
4677 cpu_attach_domain(sd, i);
4681 #undef SCHED_DOMAIN_DEBUG
4682 #ifdef SCHED_DOMAIN_DEBUG
4683 void sched_domain_debug(void)
4688 runqueue_t *rq = cpu_rq(i);
4689 struct sched_domain *sd;
4694 printk(KERN_DEBUG "CPU%d: %s\n",
4695 i, (cpu_online(i) ? " online" : "offline"));
4700 struct sched_group *group = sd->groups;
4701 cpumask_t groupmask;
4703 cpumask_scnprintf(str, NR_CPUS, sd->span);
4704 cpus_clear(groupmask);
4707 for (j = 0; j < level + 1; j++)
4709 printk("domain %d: span %s\n", level, str);
4711 if (!cpu_isset(i, sd->span))
4712 printk(KERN_DEBUG "ERROR domain->span does not contain CPU%d\n", i);
4713 if (!cpu_isset(i, group->cpumask))
4714 printk(KERN_DEBUG "ERROR domain->groups does not contain CPU%d\n", i);
4715 if (!group->cpu_power)
4716 printk(KERN_DEBUG "ERROR domain->cpu_power not set\n");
4719 for (j = 0; j < level + 2; j++)
4724 printk(" ERROR: NULL");
4728 if (!cpus_weight(group->cpumask))
4729 printk(" ERROR empty group:");
4731 if (cpus_intersects(groupmask, group->cpumask))
4732 printk(" ERROR repeated CPUs:");
4734 cpus_or(groupmask, groupmask, group->cpumask);
4736 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
4739 group = group->next;
4740 } while (group != sd->groups);
4743 if (!cpus_equal(sd->span, groupmask))
4744 printk(KERN_DEBUG "ERROR groups don't span domain->span\n");
4750 if (!cpus_subset(groupmask, sd->span))
4751 printk(KERN_DEBUG "ERROR parent span is not a superset of domain->span\n");
4758 #define sched_domain_debug() {}
4761 void __init sched_init_smp(void)
4763 arch_init_sched_domains();
4764 sched_domain_debug();
4767 void __init sched_init_smp(void)
4770 #endif /* CONFIG_SMP */
4772 int in_sched_functions(unsigned long addr)
4774 /* Linker adds these: start and end of __sched functions */
4775 extern char __sched_text_start[], __sched_text_end[];
4776 return in_lock_functions(addr) ||
4777 (addr >= (unsigned long)__sched_text_start
4778 && addr < (unsigned long)__sched_text_end);
4781 void __init sched_init(void)
4787 /* Set up an initial dummy domain for early boot */
4788 static struct sched_domain sched_domain_init;
4789 static struct sched_group sched_group_init;
4791 memset(&sched_domain_init, 0, sizeof(struct sched_domain));
4792 sched_domain_init.span = CPU_MASK_ALL;
4793 sched_domain_init.groups = &sched_group_init;
4794 sched_domain_init.last_balance = jiffies;
4795 sched_domain_init.balance_interval = INT_MAX; /* Don't balance */
4796 sched_domain_init.busy_factor = 1;
4798 memset(&sched_group_init, 0, sizeof(struct sched_group));
4799 sched_group_init.cpumask = CPU_MASK_ALL;
4800 sched_group_init.next = &sched_group_init;
4801 sched_group_init.cpu_power = SCHED_LOAD_SCALE;
4804 for (i = 0; i < NR_CPUS; i++) {
4805 prio_array_t *array;
4808 spin_lock_init(&rq->lock);
4809 rq->active = rq->arrays;
4810 rq->expired = rq->arrays + 1;
4811 rq->best_expired_prio = MAX_PRIO;
4814 rq->sd = &sched_domain_init;
4816 rq->active_balance = 0;
4818 rq->migration_thread = NULL;
4819 INIT_LIST_HEAD(&rq->migration_queue);
4821 #ifdef CONFIG_VSERVER_HARDCPU
4822 INIT_LIST_HEAD(&rq->hold_queue);
4824 atomic_set(&rq->nr_iowait, 0);
4826 for (j = 0; j < 2; j++) {
4827 array = rq->arrays + j;
4828 for (k = 0; k < MAX_PRIO; k++) {
4829 INIT_LIST_HEAD(array->queue + k);
4830 __clear_bit(k, array->bitmap);
4832 // delimiter for bitsearch
4833 __set_bit(MAX_PRIO, array->bitmap);
4838 * The boot idle thread does lazy MMU switching as well:
4840 atomic_inc(&init_mm.mm_count);
4841 enter_lazy_tlb(&init_mm, current);
4844 * Make us the idle thread. Technically, schedule() should not be
4845 * called from this thread, however somewhere below it might be,
4846 * but because we are the idle thread, we just pick up running again
4847 * when this runqueue becomes "idle".
4849 init_idle(current, smp_processor_id());
4852 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4853 void __might_sleep(char *file, int line)
4855 #if defined(in_atomic)
4856 static unsigned long prev_jiffy; /* ratelimiting */
4858 if ((in_atomic() || irqs_disabled()) &&
4859 system_state == SYSTEM_RUNNING) {
4860 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
4862 prev_jiffy = jiffies;
4863 printk(KERN_ERR "Debug: sleeping function called from invalid"
4864 " context at %s:%d\n", file, line);
4865 printk("in_atomic():%d, irqs_disabled():%d\n",
4866 in_atomic(), irqs_disabled());
4871 EXPORT_SYMBOL(__might_sleep);