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/capability.h>
31 #include <linux/completion.h>
32 #include <linux/kernel_stat.h>
33 #include <linux/debug_locks.h>
34 #include <linux/security.h>
35 #include <linux/notifier.h>
36 #include <linux/profile.h>
37 #include <linux/suspend.h>
38 #include <linux/vmalloc.h>
39 #include <linux/blkdev.h>
40 #include <linux/delay.h>
41 #include <linux/smp.h>
42 #include <linux/threads.h>
43 #include <linux/timer.h>
44 #include <linux/rcupdate.h>
45 #include <linux/cpu.h>
46 #include <linux/cpuset.h>
47 #include <linux/percpu.h>
48 #include <linux/kthread.h>
49 #include <linux/seq_file.h>
50 #include <linux/syscalls.h>
51 #include <linux/times.h>
52 #include <linux/acct.h>
53 #include <linux/kprobes.h>
54 #include <linux/delayacct.h>
57 #include <asm/unistd.h>
58 #include <linux/vs_context.h>
59 #include <linux/vs_cvirt.h>
60 #include <linux/vs_sched.h>
63 * Convert user-nice values [ -20 ... 0 ... 19 ]
64 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
67 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
68 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
69 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
72 * 'User priority' is the nice value converted to something we
73 * can work with better when scaling various scheduler parameters,
74 * it's a [ 0 ... 39 ] range.
76 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
77 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
78 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
81 * Some helpers for converting nanosecond timing to jiffy resolution
83 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
84 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
87 * These are the 'tuning knobs' of the scheduler:
89 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
90 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
91 * Timeslices get refilled after they expire.
93 #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
94 #define DEF_TIMESLICE (100 * HZ / 1000)
95 #define ON_RUNQUEUE_WEIGHT 30
96 #define CHILD_PENALTY 95
97 #define PARENT_PENALTY 100
99 #define PRIO_BONUS_RATIO 25
100 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
101 #define INTERACTIVE_DELTA 2
102 #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
103 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
104 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
107 * If a task is 'interactive' then we reinsert it in the active
108 * array after it has expired its current timeslice. (it will not
109 * continue to run immediately, it will still roundrobin with
110 * other interactive tasks.)
112 * This part scales the interactivity limit depending on niceness.
114 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
115 * Here are a few examples of different nice levels:
117 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
118 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
119 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
120 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
121 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
123 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
124 * priority range a task can explore, a value of '1' means the
125 * task is rated interactive.)
127 * Ie. nice +19 tasks can never get 'interactive' enough to be
128 * reinserted into the active array. And only heavily CPU-hog nice -20
129 * tasks will be expired. Default nice 0 tasks are somewhere between,
130 * it takes some effort for them to get interactive, but it's not
134 #define CURRENT_BONUS(p) \
135 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
138 #define GRANULARITY (10 * HZ / 1000 ? : 1)
141 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
142 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
145 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
146 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
149 #define SCALE(v1,v1_max,v2_max) \
150 (v1) * (v2_max) / (v1_max)
153 (SCALE(TASK_NICE(p) + 20, 40, MAX_BONUS) - 20 * MAX_BONUS / 40 + \
156 #define TASK_INTERACTIVE(p) \
157 ((p)->prio <= (p)->static_prio - DELTA(p))
159 #define INTERACTIVE_SLEEP(p) \
160 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
161 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
163 #define TASK_PREEMPTS_CURR(p, rq) \
164 ((p)->prio < (rq)->curr->prio)
167 * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
168 * to time slice values: [800ms ... 100ms ... 5ms]
170 * The higher a thread's priority, the bigger timeslices
171 * it gets during one round of execution. But even the lowest
172 * priority thread gets MIN_TIMESLICE worth of execution time.
175 #define SCALE_PRIO(x, prio) \
176 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO / 2), MIN_TIMESLICE)
178 static unsigned int static_prio_timeslice(int static_prio)
180 if (static_prio < NICE_TO_PRIO(0))
181 return SCALE_PRIO(DEF_TIMESLICE * 4, static_prio);
183 return SCALE_PRIO(DEF_TIMESLICE, static_prio);
186 static inline unsigned int task_timeslice(struct task_struct *p)
188 return static_prio_timeslice(p->static_prio);
192 * These are the runqueue data structures:
196 unsigned int nr_active;
197 DECLARE_BITMAP(bitmap, MAX_PRIO+1); /* include 1 bit for delimiter */
198 struct list_head queue[MAX_PRIO];
202 * This is the main, per-CPU runqueue data structure.
204 * Locking rule: those places that want to lock multiple runqueues
205 * (such as the load balancing or the thread migration code), lock
206 * acquire operations must be ordered by ascending &runqueue.
212 * nr_running and cpu_load should be in the same cacheline because
213 * remote CPUs use both these fields when doing load calculation.
215 unsigned long nr_running;
216 unsigned long raw_weighted_load;
218 unsigned long cpu_load[3];
220 unsigned long long nr_switches;
223 * This is part of a global counter where only the total sum
224 * over all CPUs matters. A task can increase this counter on
225 * one CPU and if it got migrated afterwards it may decrease
226 * it on another CPU. Always updated under the runqueue lock:
228 unsigned long nr_uninterruptible;
230 unsigned long expired_timestamp;
231 unsigned long long timestamp_last_tick;
232 struct task_struct *curr, *idle;
233 struct mm_struct *prev_mm;
234 struct prio_array *active, *expired, arrays[2];
235 int best_expired_prio;
239 struct sched_domain *sd;
241 /* For active balancing */
244 int cpu; /* cpu of this runqueue */
246 struct task_struct *migration_thread;
247 struct list_head migration_queue;
249 #ifdef CONFIG_VSERVER_HARDCPU
250 struct list_head hold_queue;
254 #ifdef CONFIG_SCHEDSTATS
256 struct sched_info rq_sched_info;
258 /* sys_sched_yield() stats */
259 unsigned long yld_exp_empty;
260 unsigned long yld_act_empty;
261 unsigned long yld_both_empty;
262 unsigned long yld_cnt;
264 /* schedule() stats */
265 unsigned long sched_switch;
266 unsigned long sched_cnt;
267 unsigned long sched_goidle;
269 /* try_to_wake_up() stats */
270 unsigned long ttwu_cnt;
271 unsigned long ttwu_local;
273 struct lock_class_key rq_lock_key;
276 static DEFINE_PER_CPU(struct rq, runqueues);
278 static inline int cpu_of(struct rq *rq)
288 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
289 * See detach_destroy_domains: synchronize_sched for details.
291 * The domain tree of any CPU may only be accessed from within
292 * preempt-disabled sections.
294 #define for_each_domain(cpu, __sd) \
295 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
297 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
298 #define this_rq() (&__get_cpu_var(runqueues))
299 #define task_rq(p) cpu_rq(task_cpu(p))
300 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
302 #ifndef prepare_arch_switch
303 # define prepare_arch_switch(next) do { } while (0)
305 #ifndef finish_arch_switch
306 # define finish_arch_switch(prev) do { } while (0)
309 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
310 static inline int task_running(struct rq *rq, struct task_struct *p)
312 return rq->curr == p;
315 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
319 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
321 #ifdef CONFIG_DEBUG_SPINLOCK
322 /* this is a valid case when another task releases the spinlock */
323 rq->lock.owner = current;
326 * If we are tracking spinlock dependencies then we have to
327 * fix up the runqueue lock - which gets 'carried over' from
330 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
332 spin_unlock_irq(&rq->lock);
335 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
336 static inline int task_running(struct rq *rq, struct task_struct *p)
341 return rq->curr == p;
345 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
349 * We can optimise this out completely for !SMP, because the
350 * SMP rebalancing from interrupt is the only thing that cares
355 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
356 spin_unlock_irq(&rq->lock);
358 spin_unlock(&rq->lock);
362 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
366 * After ->oncpu is cleared, the task can be moved to a different CPU.
367 * We must ensure this doesn't happen until the switch is completely
373 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
377 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
380 * __task_rq_lock - lock the runqueue a given task resides on.
381 * Must be called interrupts disabled.
383 static inline struct rq *__task_rq_lock(struct task_struct *p)
390 spin_lock(&rq->lock);
391 if (unlikely(rq != task_rq(p))) {
392 spin_unlock(&rq->lock);
393 goto repeat_lock_task;
399 * task_rq_lock - lock the runqueue a given task resides on and disable
400 * interrupts. Note the ordering: we can safely lookup the task_rq without
401 * explicitly disabling preemption.
403 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
409 local_irq_save(*flags);
411 spin_lock(&rq->lock);
412 if (unlikely(rq != task_rq(p))) {
413 spin_unlock_irqrestore(&rq->lock, *flags);
414 goto repeat_lock_task;
419 static inline void __task_rq_unlock(struct rq *rq)
422 spin_unlock(&rq->lock);
425 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
428 spin_unlock_irqrestore(&rq->lock, *flags);
431 #ifdef CONFIG_SCHEDSTATS
433 * bump this up when changing the output format or the meaning of an existing
434 * format, so that tools can adapt (or abort)
436 #define SCHEDSTAT_VERSION 12
438 static int show_schedstat(struct seq_file *seq, void *v)
442 seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
443 seq_printf(seq, "timestamp %lu\n", jiffies);
444 for_each_online_cpu(cpu) {
445 struct rq *rq = cpu_rq(cpu);
447 struct sched_domain *sd;
451 /* runqueue-specific stats */
453 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
454 cpu, rq->yld_both_empty,
455 rq->yld_act_empty, rq->yld_exp_empty, rq->yld_cnt,
456 rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
457 rq->ttwu_cnt, rq->ttwu_local,
458 rq->rq_sched_info.cpu_time,
459 rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
461 seq_printf(seq, "\n");
464 /* domain-specific stats */
466 for_each_domain(cpu, sd) {
467 enum idle_type itype;
468 char mask_str[NR_CPUS];
470 cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
471 seq_printf(seq, "domain%d %s", dcnt++, mask_str);
472 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
474 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu",
476 sd->lb_balanced[itype],
477 sd->lb_failed[itype],
478 sd->lb_imbalance[itype],
479 sd->lb_gained[itype],
480 sd->lb_hot_gained[itype],
481 sd->lb_nobusyq[itype],
482 sd->lb_nobusyg[itype]);
484 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
485 sd->alb_cnt, sd->alb_failed, sd->alb_pushed,
486 sd->sbe_cnt, sd->sbe_balanced, sd->sbe_pushed,
487 sd->sbf_cnt, sd->sbf_balanced, sd->sbf_pushed,
488 sd->ttwu_wake_remote, sd->ttwu_move_affine, sd->ttwu_move_balance);
496 static int schedstat_open(struct inode *inode, struct file *file)
498 unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
499 char *buf = kmalloc(size, GFP_KERNEL);
505 res = single_open(file, show_schedstat, NULL);
507 m = file->private_data;
515 struct file_operations proc_schedstat_operations = {
516 .open = schedstat_open,
519 .release = single_release,
523 * Expects runqueue lock to be held for atomicity of update
526 rq_sched_info_arrive(struct rq *rq, unsigned long delta_jiffies)
529 rq->rq_sched_info.run_delay += delta_jiffies;
530 rq->rq_sched_info.pcnt++;
535 * Expects runqueue lock to be held for atomicity of update
538 rq_sched_info_depart(struct rq *rq, unsigned long delta_jiffies)
541 rq->rq_sched_info.cpu_time += delta_jiffies;
543 # define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
544 # define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
545 #else /* !CONFIG_SCHEDSTATS */
547 rq_sched_info_arrive(struct rq *rq, unsigned long delta_jiffies)
550 rq_sched_info_depart(struct rq *rq, unsigned long delta_jiffies)
552 # define schedstat_inc(rq, field) do { } while (0)
553 # define schedstat_add(rq, field, amt) do { } while (0)
557 * rq_lock - lock a given runqueue and disable interrupts.
559 static inline struct rq *this_rq_lock(void)
566 spin_lock(&rq->lock);
571 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
573 * Called when a process is dequeued from the active array and given
574 * the cpu. We should note that with the exception of interactive
575 * tasks, the expired queue will become the active queue after the active
576 * queue is empty, without explicitly dequeuing and requeuing tasks in the
577 * expired queue. (Interactive tasks may be requeued directly to the
578 * active queue, thus delaying tasks in the expired queue from running;
579 * see scheduler_tick()).
581 * This function is only called from sched_info_arrive(), rather than
582 * dequeue_task(). Even though a task may be queued and dequeued multiple
583 * times as it is shuffled about, we're really interested in knowing how
584 * long it was from the *first* time it was queued to the time that it
587 static inline void sched_info_dequeued(struct task_struct *t)
589 t->sched_info.last_queued = 0;
593 * Called when a task finally hits the cpu. We can now calculate how
594 * long it was waiting to run. We also note when it began so that we
595 * can keep stats on how long its timeslice is.
597 static void sched_info_arrive(struct task_struct *t)
599 unsigned long now = jiffies, delta_jiffies = 0;
601 if (t->sched_info.last_queued)
602 delta_jiffies = now - t->sched_info.last_queued;
603 sched_info_dequeued(t);
604 t->sched_info.run_delay += delta_jiffies;
605 t->sched_info.last_arrival = now;
606 t->sched_info.pcnt++;
608 rq_sched_info_arrive(task_rq(t), delta_jiffies);
612 * Called when a process is queued into either the active or expired
613 * array. The time is noted and later used to determine how long we
614 * had to wait for us to reach the cpu. Since the expired queue will
615 * become the active queue after active queue is empty, without dequeuing
616 * and requeuing any tasks, we are interested in queuing to either. It
617 * is unusual but not impossible for tasks to be dequeued and immediately
618 * requeued in the same or another array: this can happen in sched_yield(),
619 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
622 * This function is only called from enqueue_task(), but also only updates
623 * the timestamp if it is already not set. It's assumed that
624 * sched_info_dequeued() will clear that stamp when appropriate.
626 static inline void sched_info_queued(struct task_struct *t)
628 if (unlikely(sched_info_on()))
629 if (!t->sched_info.last_queued)
630 t->sched_info.last_queued = jiffies;
634 * Called when a process ceases being the active-running process, either
635 * voluntarily or involuntarily. Now we can calculate how long we ran.
637 static inline void sched_info_depart(struct task_struct *t)
639 unsigned long delta_jiffies = jiffies - t->sched_info.last_arrival;
641 t->sched_info.cpu_time += delta_jiffies;
642 rq_sched_info_depart(task_rq(t), delta_jiffies);
646 * Called when tasks are switched involuntarily due, typically, to expiring
647 * their time slice. (This may also be called when switching to or from
648 * the idle task.) We are only called when prev != next.
651 __sched_info_switch(struct task_struct *prev, struct task_struct *next)
653 struct rq *rq = task_rq(prev);
656 * prev now departs the cpu. It's not interesting to record
657 * stats about how efficient we were at scheduling the idle
660 if (prev != rq->idle)
661 sched_info_depart(prev);
663 if (next != rq->idle)
664 sched_info_arrive(next);
667 sched_info_switch(struct task_struct *prev, struct task_struct *next)
669 if (unlikely(sched_info_on()))
670 __sched_info_switch(prev, next);
673 #define sched_info_queued(t) do { } while (0)
674 #define sched_info_switch(t, next) do { } while (0)
675 #endif /* CONFIG_SCHEDSTATS || CONFIG_TASK_DELAY_ACCT */
678 * Adding/removing a task to/from a priority array:
680 static void dequeue_task(struct task_struct *p, struct prio_array *array)
682 BUG_ON(p->state & TASK_ONHOLD);
684 list_del(&p->run_list);
685 if (list_empty(array->queue + p->prio))
686 __clear_bit(p->prio, array->bitmap);
689 static void enqueue_task(struct task_struct *p, struct prio_array *array)
691 BUG_ON(p->state & TASK_ONHOLD);
692 sched_info_queued(p);
693 list_add_tail(&p->run_list, array->queue + p->prio);
694 __set_bit(p->prio, array->bitmap);
700 * Put task to the end of the run list without the overhead of dequeue
701 * followed by enqueue.
703 static void requeue_task(struct task_struct *p, struct prio_array *array)
705 BUG_ON(p->state & TASK_ONHOLD);
706 list_move_tail(&p->run_list, array->queue + p->prio);
710 enqueue_task_head(struct task_struct *p, struct prio_array *array)
712 BUG_ON(p->state & TASK_ONHOLD);
713 list_add(&p->run_list, array->queue + p->prio);
714 __set_bit(p->prio, array->bitmap);
720 * __normal_prio - return the priority that is based on the static
721 * priority but is modified by bonuses/penalties.
723 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
724 * into the -5 ... 0 ... +5 bonus/penalty range.
726 * We use 25% of the full 0...39 priority range so that:
728 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
729 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
731 * Both properties are important to certain workloads.
734 static inline int __normal_prio(struct task_struct *p)
739 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
741 prio = p->static_prio - bonus;
743 if ((vxi = p->vx_info) &&
744 vx_info_flags(vxi, VXF_SCHED_PRIO, 0))
745 prio += vx_effective_vavavoom(vxi, MAX_USER_PRIO);
747 if (prio < MAX_RT_PRIO)
749 if (prio > MAX_PRIO-1)
755 * To aid in avoiding the subversion of "niceness" due to uneven distribution
756 * of tasks with abnormal "nice" values across CPUs the contribution that
757 * each task makes to its run queue's load is weighted according to its
758 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
759 * scaled version of the new time slice allocation that they receive on time
764 * Assume: static_prio_timeslice(NICE_TO_PRIO(0)) == DEF_TIMESLICE
765 * If static_prio_timeslice() is ever changed to break this assumption then
766 * this code will need modification
768 #define TIME_SLICE_NICE_ZERO DEF_TIMESLICE
769 #define LOAD_WEIGHT(lp) \
770 (((lp) * SCHED_LOAD_SCALE) / TIME_SLICE_NICE_ZERO)
771 #define PRIO_TO_LOAD_WEIGHT(prio) \
772 LOAD_WEIGHT(static_prio_timeslice(prio))
773 #define RTPRIO_TO_LOAD_WEIGHT(rp) \
774 (PRIO_TO_LOAD_WEIGHT(MAX_RT_PRIO) + LOAD_WEIGHT(rp))
776 static void set_load_weight(struct task_struct *p)
778 if (has_rt_policy(p)) {
780 if (p == task_rq(p)->migration_thread)
782 * The migration thread does the actual balancing.
783 * Giving its load any weight will skew balancing
789 p->load_weight = RTPRIO_TO_LOAD_WEIGHT(p->rt_priority);
791 p->load_weight = PRIO_TO_LOAD_WEIGHT(p->static_prio);
795 inc_raw_weighted_load(struct rq *rq, const struct task_struct *p)
797 rq->raw_weighted_load += p->load_weight;
801 dec_raw_weighted_load(struct rq *rq, const struct task_struct *p)
803 rq->raw_weighted_load -= p->load_weight;
806 static inline void inc_nr_running(struct task_struct *p, struct rq *rq)
809 inc_raw_weighted_load(rq, p);
812 static inline void dec_nr_running(struct task_struct *p, struct rq *rq)
815 dec_raw_weighted_load(rq, p);
819 * Calculate the expected normal priority: i.e. priority
820 * without taking RT-inheritance into account. Might be
821 * boosted by interactivity modifiers. Changes upon fork,
822 * setprio syscalls, and whenever the interactivity
823 * estimator recalculates.
825 static inline int normal_prio(struct task_struct *p)
829 if (has_rt_policy(p))
830 prio = MAX_RT_PRIO-1 - p->rt_priority;
832 prio = __normal_prio(p);
837 * Calculate the current priority, i.e. the priority
838 * taken into account by the scheduler. This value might
839 * be boosted by RT tasks, or might be boosted by
840 * interactivity modifiers. Will be RT if the task got
841 * RT-boosted. If not then it returns p->normal_prio.
843 static int effective_prio(struct task_struct *p)
845 p->normal_prio = normal_prio(p);
847 * If we are RT tasks or we were boosted to RT priority,
848 * keep the priority unchanged. Otherwise, update priority
849 * to the normal priority:
851 if (!rt_prio(p->prio))
852 return p->normal_prio;
857 * __activate_task - move a task to the runqueue.
859 static void __activate_task(struct task_struct *p, struct rq *rq)
861 struct prio_array *target = rq->active;
864 target = rq->expired;
865 enqueue_task(p, target);
866 inc_nr_running(p, rq);
870 * __activate_idle_task - move idle task to the _front_ of runqueue.
872 static inline void __activate_idle_task(struct task_struct *p, struct rq *rq)
874 enqueue_task_head(p, rq->active);
875 inc_nr_running(p, rq);
879 * Recalculate p->normal_prio and p->prio after having slept,
880 * updating the sleep-average too:
882 static int recalc_task_prio(struct task_struct *p, unsigned long long now)
884 /* Caller must always ensure 'now >= p->timestamp' */
885 unsigned long sleep_time = now - p->timestamp;
890 if (likely(sleep_time > 0)) {
892 * This ceiling is set to the lowest priority that would allow
893 * a task to be reinserted into the active array on timeslice
896 unsigned long ceiling = INTERACTIVE_SLEEP(p);
898 if (p->mm && sleep_time > ceiling && p->sleep_avg < ceiling) {
900 * Prevents user tasks from achieving best priority
901 * with one single large enough sleep.
903 p->sleep_avg = ceiling;
905 * Using INTERACTIVE_SLEEP() as a ceiling places a
906 * nice(0) task 1ms sleep away from promotion, and
907 * gives it 700ms to round-robin with no chance of
908 * being demoted. This is more than generous, so
909 * mark this sleep as non-interactive to prevent the
910 * on-runqueue bonus logic from intervening should
911 * this task not receive cpu immediately.
913 p->sleep_type = SLEEP_NONINTERACTIVE;
916 * Tasks waking from uninterruptible sleep are
917 * limited in their sleep_avg rise as they
918 * are likely to be waiting on I/O
920 if (p->sleep_type == SLEEP_NONINTERACTIVE && p->mm) {
921 if (p->sleep_avg >= ceiling)
923 else if (p->sleep_avg + sleep_time >=
925 p->sleep_avg = ceiling;
931 * This code gives a bonus to interactive tasks.
933 * The boost works by updating the 'average sleep time'
934 * value here, based on ->timestamp. The more time a
935 * task spends sleeping, the higher the average gets -
936 * and the higher the priority boost gets as well.
938 p->sleep_avg += sleep_time;
941 if (p->sleep_avg > NS_MAX_SLEEP_AVG)
942 p->sleep_avg = NS_MAX_SLEEP_AVG;
945 return effective_prio(p);
949 * activate_task - move a task to the runqueue and do priority recalculation
951 * Update all the scheduling statistics stuff. (sleep average
952 * calculation, priority modifiers, etc.)
954 static void activate_task(struct task_struct *p, struct rq *rq, int local)
956 unsigned long long now;
961 /* Compensate for drifting sched_clock */
962 struct rq *this_rq = this_rq();
963 now = (now - this_rq->timestamp_last_tick)
964 + rq->timestamp_last_tick;
969 p->prio = recalc_task_prio(p, now);
972 * This checks to make sure it's not an uninterruptible task
973 * that is now waking up.
975 if (p->sleep_type == SLEEP_NORMAL) {
977 * Tasks which were woken up by interrupts (ie. hw events)
978 * are most likely of interactive nature. So we give them
979 * the credit of extending their sleep time to the period
980 * of time they spend on the runqueue, waiting for execution
981 * on a CPU, first time around:
984 p->sleep_type = SLEEP_INTERRUPTED;
987 * Normal first-time wakeups get a credit too for
988 * on-runqueue time, but it will be weighted down:
990 p->sleep_type = SLEEP_INTERACTIVE;
996 __activate_task(p, rq);
1000 * deactivate_task - remove a task from the runqueue.
1002 static void __deactivate_task(struct task_struct *p, struct rq *rq)
1004 dec_nr_running(p, rq);
1005 dequeue_task(p, p->array);
1010 void deactivate_task(struct task_struct *p, struct rq *rq)
1012 vx_deactivate_task(p);
1013 __deactivate_task(p, rq);
1017 #ifdef CONFIG_VSERVER_HARDCPU
1019 * vx_hold_task - put a task on the hold queue
1022 void vx_hold_task(struct vx_info *vxi,
1023 struct task_struct *p, struct rq *rq)
1025 __deactivate_task(p, rq);
1026 p->state |= TASK_ONHOLD;
1027 /* a new one on hold */
1029 list_add_tail(&p->run_list, &rq->hold_queue);
1033 * vx_unhold_task - put a task back to the runqueue
1036 void vx_unhold_task(struct vx_info *vxi,
1037 struct task_struct *p, struct rq *rq)
1039 list_del(&p->run_list);
1040 /* one less waiting */
1042 p->state &= ~TASK_ONHOLD;
1043 enqueue_task(p, rq->expired);
1044 inc_nr_running(p, rq);
1046 if (p->static_prio < rq->best_expired_prio)
1047 rq->best_expired_prio = p->static_prio;
1051 void vx_hold_task(struct vx_info *vxi,
1052 struct task_struct *p, struct rq *rq)
1058 void vx_unhold_task(struct vx_info *vxi,
1059 struct task_struct *p, struct rq *rq)
1063 #endif /* CONFIG_VSERVER_HARDCPU */
1067 * resched_task - mark a task 'to be rescheduled now'.
1069 * On UP this means the setting of the need_resched flag, on SMP it
1070 * might also involve a cross-CPU call to trigger the scheduler on
1075 #ifndef tsk_is_polling
1076 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1079 static void resched_task(struct task_struct *p)
1083 assert_spin_locked(&task_rq(p)->lock);
1085 if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
1088 set_tsk_thread_flag(p, TIF_NEED_RESCHED);
1091 if (cpu == smp_processor_id())
1094 /* NEED_RESCHED must be visible before we test polling */
1096 if (!tsk_is_polling(p))
1097 smp_send_reschedule(cpu);
1100 static inline void resched_task(struct task_struct *p)
1102 assert_spin_locked(&task_rq(p)->lock);
1103 set_tsk_need_resched(p);
1108 * task_curr - is this task currently executing on a CPU?
1109 * @p: the task in question.
1111 inline int task_curr(const struct task_struct *p)
1113 return cpu_curr(task_cpu(p)) == p;
1116 /* Used instead of source_load when we know the type == 0 */
1117 unsigned long weighted_cpuload(const int cpu)
1119 return cpu_rq(cpu)->raw_weighted_load;
1123 struct migration_req {
1124 struct list_head list;
1126 struct task_struct *task;
1129 struct completion done;
1133 * The task's runqueue lock must be held.
1134 * Returns true if you have to wait for migration thread.
1137 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1139 struct rq *rq = task_rq(p);
1142 * If the task is not on a runqueue (and not running), then
1143 * it is sufficient to simply update the task's cpu field.
1145 if (!p->array && !task_running(rq, p)) {
1146 set_task_cpu(p, dest_cpu);
1150 init_completion(&req->done);
1152 req->dest_cpu = dest_cpu;
1153 list_add(&req->list, &rq->migration_queue);
1159 * wait_task_inactive - wait for a thread to unschedule.
1161 * The caller must ensure that the task *will* unschedule sometime soon,
1162 * else this function might spin for a *long* time. This function can't
1163 * be called with interrupts off, or it may introduce deadlock with
1164 * smp_call_function() if an IPI is sent by the same process we are
1165 * waiting to become inactive.
1167 void wait_task_inactive(struct task_struct *p)
1169 unsigned long flags;
1174 rq = task_rq_lock(p, &flags);
1175 /* Must be off runqueue entirely, not preempted. */
1176 if (unlikely(p->array || task_running(rq, p))) {
1177 /* If it's preempted, we yield. It could be a while. */
1178 preempted = !task_running(rq, p);
1179 task_rq_unlock(rq, &flags);
1185 task_rq_unlock(rq, &flags);
1189 * kick_process - kick a running thread to enter/exit the kernel
1190 * @p: the to-be-kicked thread
1192 * Cause a process which is running on another CPU to enter
1193 * kernel-mode, without any delay. (to get signals handled.)
1195 * NOTE: this function doesnt have to take the runqueue lock,
1196 * because all it wants to ensure is that the remote task enters
1197 * the kernel. If the IPI races and the task has been migrated
1198 * to another CPU then no harm is done and the purpose has been
1201 void kick_process(struct task_struct *p)
1207 if ((cpu != smp_processor_id()) && task_curr(p))
1208 smp_send_reschedule(cpu);
1213 * Return a low guess at the load of a migration-source cpu weighted
1214 * according to the scheduling class and "nice" value.
1216 * We want to under-estimate the load of migration sources, to
1217 * balance conservatively.
1219 static inline unsigned long source_load(int cpu, int type)
1221 struct rq *rq = cpu_rq(cpu);
1224 return rq->raw_weighted_load;
1226 return min(rq->cpu_load[type-1], rq->raw_weighted_load);
1230 * Return a high guess at the load of a migration-target cpu weighted
1231 * according to the scheduling class and "nice" value.
1233 static inline unsigned long target_load(int cpu, int type)
1235 struct rq *rq = cpu_rq(cpu);
1238 return rq->raw_weighted_load;
1240 return max(rq->cpu_load[type-1], rq->raw_weighted_load);
1244 * Return the average load per task on the cpu's run queue
1246 static inline unsigned long cpu_avg_load_per_task(int cpu)
1248 struct rq *rq = cpu_rq(cpu);
1249 unsigned long n = rq->nr_running;
1251 return n ? rq->raw_weighted_load / n : SCHED_LOAD_SCALE;
1255 * find_idlest_group finds and returns the least busy CPU group within the
1258 static struct sched_group *
1259 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1261 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1262 unsigned long min_load = ULONG_MAX, this_load = 0;
1263 int load_idx = sd->forkexec_idx;
1264 int imbalance = 100 + (sd->imbalance_pct-100)/2;
1267 unsigned long load, avg_load;
1271 /* Skip over this group if it has no CPUs allowed */
1272 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
1275 local_group = cpu_isset(this_cpu, group->cpumask);
1277 /* Tally up the load of all CPUs in the group */
1280 for_each_cpu_mask(i, group->cpumask) {
1281 /* Bias balancing toward cpus of our domain */
1283 load = source_load(i, load_idx);
1285 load = target_load(i, load_idx);
1290 /* Adjust by relative CPU power of the group */
1291 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1294 this_load = avg_load;
1296 } else if (avg_load < min_load) {
1297 min_load = avg_load;
1301 group = group->next;
1302 } while (group != sd->groups);
1304 if (!idlest || 100*this_load < imbalance*min_load)
1310 * find_idlest_queue - find the idlest runqueue among the cpus in group.
1313 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
1316 unsigned long load, min_load = ULONG_MAX;
1320 /* Traverse only the allowed CPUs */
1321 cpus_and(tmp, group->cpumask, p->cpus_allowed);
1323 for_each_cpu_mask(i, tmp) {
1324 load = weighted_cpuload(i);
1326 if (load < min_load || (load == min_load && i == this_cpu)) {
1336 * sched_balance_self: balance the current task (running on cpu) in domains
1337 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1340 * Balance, ie. select the least loaded group.
1342 * Returns the target CPU number, or the same CPU if no balancing is needed.
1344 * preempt must be disabled.
1346 static int sched_balance_self(int cpu, int flag)
1348 struct task_struct *t = current;
1349 struct sched_domain *tmp, *sd = NULL;
1351 for_each_domain(cpu, tmp) {
1353 * If power savings logic is enabled for a domain, stop there.
1355 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
1357 if (tmp->flags & flag)
1363 struct sched_group *group;
1368 group = find_idlest_group(sd, t, cpu);
1372 new_cpu = find_idlest_cpu(group, t, cpu);
1373 if (new_cpu == -1 || new_cpu == cpu)
1376 /* Now try balancing at a lower domain level */
1380 weight = cpus_weight(span);
1381 for_each_domain(cpu, tmp) {
1382 if (weight <= cpus_weight(tmp->span))
1384 if (tmp->flags & flag)
1387 /* while loop will break here if sd == NULL */
1393 #endif /* CONFIG_SMP */
1396 * wake_idle() will wake a task on an idle cpu if task->cpu is
1397 * not idle and an idle cpu is available. The span of cpus to
1398 * search starts with cpus closest then further out as needed,
1399 * so we always favor a closer, idle cpu.
1401 * Returns the CPU we should wake onto.
1403 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1404 static int wake_idle(int cpu, struct task_struct *p)
1407 struct sched_domain *sd;
1413 for_each_domain(cpu, sd) {
1414 if (sd->flags & SD_WAKE_IDLE) {
1415 cpus_and(tmp, sd->span, p->cpus_allowed);
1416 for_each_cpu_mask(i, tmp) {
1427 static inline int wake_idle(int cpu, struct task_struct *p)
1434 * try_to_wake_up - wake up a thread
1435 * @p: the to-be-woken-up thread
1436 * @state: the mask of task states that can be woken
1437 * @sync: do a synchronous wakeup?
1439 * Put it on the run-queue if it's not already there. The "current"
1440 * thread is always on the run-queue (except when the actual
1441 * re-schedule is in progress), and as such you're allowed to do
1442 * the simpler "current->state = TASK_RUNNING" to mark yourself
1443 * runnable without the overhead of this.
1445 * returns failure only if the task is already active.
1447 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
1449 int cpu, this_cpu, success = 0;
1450 unsigned long flags;
1454 struct sched_domain *sd, *this_sd = NULL;
1455 unsigned long load, this_load;
1459 rq = task_rq_lock(p, &flags);
1460 old_state = p->state;
1462 /* we need to unhold suspended tasks */
1463 if (old_state & TASK_ONHOLD) {
1464 vx_unhold_task(p->vx_info, p, rq);
1465 old_state = p->state;
1467 if (!(old_state & state))
1474 this_cpu = smp_processor_id();
1477 if (unlikely(task_running(rq, p)))
1482 schedstat_inc(rq, ttwu_cnt);
1483 if (cpu == this_cpu) {
1484 schedstat_inc(rq, ttwu_local);
1488 for_each_domain(this_cpu, sd) {
1489 if (cpu_isset(cpu, sd->span)) {
1490 schedstat_inc(sd, ttwu_wake_remote);
1496 if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1500 * Check for affine wakeup and passive balancing possibilities.
1503 int idx = this_sd->wake_idx;
1504 unsigned int imbalance;
1506 imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
1508 load = source_load(cpu, idx);
1509 this_load = target_load(this_cpu, idx);
1511 new_cpu = this_cpu; /* Wake to this CPU if we can */
1513 if (this_sd->flags & SD_WAKE_AFFINE) {
1514 unsigned long tl = this_load;
1515 unsigned long tl_per_task = cpu_avg_load_per_task(this_cpu);
1518 * If sync wakeup then subtract the (maximum possible)
1519 * effect of the currently running task from the load
1520 * of the current CPU:
1523 tl -= current->load_weight;
1526 tl + target_load(cpu, idx) <= tl_per_task) ||
1527 100*(tl + p->load_weight) <= imbalance*load) {
1529 * This domain has SD_WAKE_AFFINE and
1530 * p is cache cold in this domain, and
1531 * there is no bad imbalance.
1533 schedstat_inc(this_sd, ttwu_move_affine);
1539 * Start passive balancing when half the imbalance_pct
1542 if (this_sd->flags & SD_WAKE_BALANCE) {
1543 if (imbalance*this_load <= 100*load) {
1544 schedstat_inc(this_sd, ttwu_move_balance);
1550 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1552 new_cpu = wake_idle(new_cpu, p);
1553 if (new_cpu != cpu) {
1554 set_task_cpu(p, new_cpu);
1555 task_rq_unlock(rq, &flags);
1556 /* might preempt at this point */
1557 rq = task_rq_lock(p, &flags);
1558 old_state = p->state;
1559 if (!(old_state & state))
1564 this_cpu = smp_processor_id();
1569 #endif /* CONFIG_SMP */
1570 if (old_state == TASK_UNINTERRUPTIBLE) {
1571 rq->nr_uninterruptible--;
1572 vx_uninterruptible_dec(p);
1574 * Tasks on involuntary sleep don't earn
1575 * sleep_avg beyond just interactive state.
1577 p->sleep_type = SLEEP_NONINTERACTIVE;
1581 * Tasks that have marked their sleep as noninteractive get
1582 * woken up with their sleep average not weighted in an
1585 if (old_state & TASK_NONINTERACTIVE)
1586 p->sleep_type = SLEEP_NONINTERACTIVE;
1589 activate_task(p, rq, cpu == this_cpu);
1591 * Sync wakeups (i.e. those types of wakeups where the waker
1592 * has indicated that it will leave the CPU in short order)
1593 * don't trigger a preemption, if the woken up task will run on
1594 * this cpu. (in this case the 'I will reschedule' promise of
1595 * the waker guarantees that the freshly woken up task is going
1596 * to be considered on this CPU.)
1598 if (!sync || cpu != this_cpu) {
1599 if (TASK_PREEMPTS_CURR(p, rq))
1600 resched_task(rq->curr);
1605 p->state = TASK_RUNNING;
1607 task_rq_unlock(rq, &flags);
1612 int fastcall wake_up_process(struct task_struct *p)
1614 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1615 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1617 EXPORT_SYMBOL(wake_up_process);
1619 int fastcall wake_up_state(struct task_struct *p, unsigned int state)
1621 return try_to_wake_up(p, state, 0);
1625 * Perform scheduler related setup for a newly forked process p.
1626 * p is forked by current.
1628 void fastcall sched_fork(struct task_struct *p, int clone_flags)
1630 int cpu = get_cpu();
1633 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
1635 set_task_cpu(p, cpu);
1638 * We mark the process as running here, but have not actually
1639 * inserted it onto the runqueue yet. This guarantees that
1640 * nobody will actually run it, and a signal or other external
1641 * event cannot wake it up and insert it on the runqueue either.
1643 p->state = TASK_RUNNING;
1646 * Make sure we do not leak PI boosting priority to the child:
1648 p->prio = current->normal_prio;
1650 INIT_LIST_HEAD(&p->run_list);
1652 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
1653 if (unlikely(sched_info_on()))
1654 memset(&p->sched_info, 0, sizeof(p->sched_info));
1656 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
1659 #ifdef CONFIG_PREEMPT
1660 /* Want to start with kernel preemption disabled. */
1661 task_thread_info(p)->preempt_count = 1;
1664 * Share the timeslice between parent and child, thus the
1665 * total amount of pending timeslices in the system doesn't change,
1666 * resulting in more scheduling fairness.
1668 local_irq_disable();
1669 p->time_slice = (current->time_slice + 1) >> 1;
1671 * The remainder of the first timeslice might be recovered by
1672 * the parent if the child exits early enough.
1674 p->first_time_slice = 1;
1675 current->time_slice >>= 1;
1676 p->timestamp = sched_clock();
1677 if (unlikely(!current->time_slice)) {
1679 * This case is rare, it happens when the parent has only
1680 * a single jiffy left from its timeslice. Taking the
1681 * runqueue lock is not a problem.
1683 current->time_slice = 1;
1691 * wake_up_new_task - wake up a newly created task for the first time.
1693 * This function will do some initial scheduler statistics housekeeping
1694 * that must be done for every newly created context, then puts the task
1695 * on the runqueue and wakes it.
1697 void fastcall wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
1699 struct rq *rq, *this_rq;
1700 unsigned long flags;
1703 rq = task_rq_lock(p, &flags);
1704 BUG_ON(p->state != TASK_RUNNING);
1705 this_cpu = smp_processor_id();
1709 * We decrease the sleep average of forking parents
1710 * and children as well, to keep max-interactive tasks
1711 * from forking tasks that are max-interactive. The parent
1712 * (current) is done further down, under its lock.
1714 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1715 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1717 p->prio = effective_prio(p);
1719 vx_activate_task(p);
1720 if (likely(cpu == this_cpu)) {
1721 if (!(clone_flags & CLONE_VM)) {
1723 * The VM isn't cloned, so we're in a good position to
1724 * do child-runs-first in anticipation of an exec. This
1725 * usually avoids a lot of COW overhead.
1727 if (unlikely(!current->array))
1728 __activate_task(p, rq);
1730 p->prio = current->prio;
1731 BUG_ON(p->state & TASK_ONHOLD);
1732 p->normal_prio = current->normal_prio;
1733 list_add_tail(&p->run_list, ¤t->run_list);
1734 p->array = current->array;
1735 p->array->nr_active++;
1736 inc_nr_running(p, rq);
1740 /* Run child last */
1741 __activate_task(p, rq);
1743 * We skip the following code due to cpu == this_cpu
1745 * task_rq_unlock(rq, &flags);
1746 * this_rq = task_rq_lock(current, &flags);
1750 this_rq = cpu_rq(this_cpu);
1753 * Not the local CPU - must adjust timestamp. This should
1754 * get optimised away in the !CONFIG_SMP case.
1756 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1757 + rq->timestamp_last_tick;
1758 __activate_task(p, rq);
1759 if (TASK_PREEMPTS_CURR(p, rq))
1760 resched_task(rq->curr);
1763 * Parent and child are on different CPUs, now get the
1764 * parent runqueue to update the parent's ->sleep_avg:
1766 task_rq_unlock(rq, &flags);
1767 this_rq = task_rq_lock(current, &flags);
1769 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1770 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1771 task_rq_unlock(this_rq, &flags);
1775 * Potentially available exiting-child timeslices are
1776 * retrieved here - this way the parent does not get
1777 * penalized for creating too many threads.
1779 * (this cannot be used to 'generate' timeslices
1780 * artificially, because any timeslice recovered here
1781 * was given away by the parent in the first place.)
1783 void fastcall sched_exit(struct task_struct *p)
1785 unsigned long flags;
1789 * If the child was a (relative-) CPU hog then decrease
1790 * the sleep_avg of the parent as well.
1792 rq = task_rq_lock(p->parent, &flags);
1793 if (p->first_time_slice && task_cpu(p) == task_cpu(p->parent)) {
1794 p->parent->time_slice += p->time_slice;
1795 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1796 p->parent->time_slice = task_timeslice(p);
1798 if (p->sleep_avg < p->parent->sleep_avg)
1799 p->parent->sleep_avg = p->parent->sleep_avg /
1800 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1802 task_rq_unlock(rq, &flags);
1806 * prepare_task_switch - prepare to switch tasks
1807 * @rq: the runqueue preparing to switch
1808 * @next: the task we are going to switch to.
1810 * This is called with the rq lock held and interrupts off. It must
1811 * be paired with a subsequent finish_task_switch after the context
1814 * prepare_task_switch sets up locking and calls architecture specific
1817 static inline void prepare_task_switch(struct rq *rq, struct task_struct *next)
1819 prepare_lock_switch(rq, next);
1820 prepare_arch_switch(next);
1824 * finish_task_switch - clean up after a task-switch
1825 * @rq: runqueue associated with task-switch
1826 * @prev: the thread we just switched away from.
1828 * finish_task_switch must be called after the context switch, paired
1829 * with a prepare_task_switch call before the context switch.
1830 * finish_task_switch will reconcile locking set up by prepare_task_switch,
1831 * and do any other architecture-specific cleanup actions.
1833 * Note that we may have delayed dropping an mm in context_switch(). If
1834 * so, we finish that here outside of the runqueue lock. (Doing it
1835 * with the lock held can cause deadlocks; see schedule() for
1838 static inline void finish_task_switch(struct rq *rq, struct task_struct *prev)
1839 __releases(rq->lock)
1841 struct mm_struct *mm = rq->prev_mm;
1842 unsigned long prev_task_flags;
1847 * A task struct has one reference for the use as "current".
1848 * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1849 * calls schedule one last time. The schedule call will never return,
1850 * and the scheduled task must drop that reference.
1851 * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1852 * still held, otherwise prev could be scheduled on another cpu, die
1853 * there before we look at prev->state, and then the reference would
1855 * Manfred Spraul <manfred@colorfullife.com>
1857 prev_task_flags = prev->flags;
1858 finish_arch_switch(prev);
1859 finish_lock_switch(rq, prev);
1862 if (unlikely(prev_task_flags & PF_DEAD)) {
1864 * Remove function-return probe instances associated with this
1865 * task and put them back on the free list.
1867 kprobe_flush_task(prev);
1868 put_task_struct(prev);
1873 * schedule_tail - first thing a freshly forked thread must call.
1874 * @prev: the thread we just switched away from.
1876 asmlinkage void schedule_tail(struct task_struct *prev)
1877 __releases(rq->lock)
1879 struct rq *rq = this_rq();
1881 finish_task_switch(rq, prev);
1882 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
1883 /* In this case, finish_task_switch does not reenable preemption */
1886 if (current->set_child_tid)
1887 put_user(current->pid, current->set_child_tid);
1891 * context_switch - switch to the new MM and the new
1892 * thread's register state.
1894 static inline struct task_struct *
1895 context_switch(struct rq *rq, struct task_struct *prev,
1896 struct task_struct *next)
1898 struct mm_struct *mm = next->mm;
1899 struct mm_struct *oldmm = prev->active_mm;
1901 if (unlikely(!mm)) {
1902 next->active_mm = oldmm;
1903 atomic_inc(&oldmm->mm_count);
1904 enter_lazy_tlb(oldmm, next);
1906 switch_mm(oldmm, mm, next);
1908 if (unlikely(!prev->mm)) {
1909 prev->active_mm = NULL;
1910 WARN_ON(rq->prev_mm);
1911 rq->prev_mm = oldmm;
1914 * Since the runqueue lock will be released by the next
1915 * task (which is an invalid locking op but in the case
1916 * of the scheduler it's an obvious special-case), so we
1917 * do an early lockdep release here:
1919 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
1920 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
1923 /* Here we just switch the register state and the stack. */
1924 switch_to(prev, next, prev);
1930 * nr_running, nr_uninterruptible and nr_context_switches:
1932 * externally visible scheduler statistics: current number of runnable
1933 * threads, current number of uninterruptible-sleeping threads, total
1934 * number of context switches performed since bootup.
1936 unsigned long nr_running(void)
1938 unsigned long i, sum = 0;
1940 for_each_online_cpu(i)
1941 sum += cpu_rq(i)->nr_running;
1946 unsigned long nr_uninterruptible(void)
1948 unsigned long i, sum = 0;
1950 for_each_possible_cpu(i)
1951 sum += cpu_rq(i)->nr_uninterruptible;
1954 * Since we read the counters lockless, it might be slightly
1955 * inaccurate. Do not allow it to go below zero though:
1957 if (unlikely((long)sum < 0))
1963 unsigned long long nr_context_switches(void)
1966 unsigned long long sum = 0;
1968 for_each_possible_cpu(i)
1969 sum += cpu_rq(i)->nr_switches;
1974 unsigned long nr_iowait(void)
1976 unsigned long i, sum = 0;
1978 for_each_possible_cpu(i)
1979 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1984 unsigned long nr_active(void)
1986 unsigned long i, running = 0, uninterruptible = 0;
1988 for_each_online_cpu(i) {
1989 running += cpu_rq(i)->nr_running;
1990 uninterruptible += cpu_rq(i)->nr_uninterruptible;
1993 if (unlikely((long)uninterruptible < 0))
1994 uninterruptible = 0;
1996 return running + uninterruptible;
2002 * Is this task likely cache-hot:
2005 task_hot(struct task_struct *p, unsigned long long now, struct sched_domain *sd)
2007 return (long long)(now - p->last_ran) < (long long)sd->cache_hot_time;
2011 * double_rq_lock - safely lock two runqueues
2013 * Note this does not disable interrupts like task_rq_lock,
2014 * you need to do so manually before calling.
2016 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
2017 __acquires(rq1->lock)
2018 __acquires(rq2->lock)
2021 spin_lock(&rq1->lock);
2022 __acquire(rq2->lock); /* Fake it out ;) */
2025 spin_lock(&rq1->lock);
2026 spin_lock(&rq2->lock);
2028 spin_lock(&rq2->lock);
2029 spin_lock(&rq1->lock);
2035 * double_rq_unlock - safely unlock two runqueues
2037 * Note this does not restore interrupts like task_rq_unlock,
2038 * you need to do so manually after calling.
2040 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
2041 __releases(rq1->lock)
2042 __releases(rq2->lock)
2044 spin_unlock(&rq1->lock);
2046 spin_unlock(&rq2->lock);
2048 __release(rq2->lock);
2052 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2054 static void double_lock_balance(struct rq *this_rq, struct rq *busiest)
2055 __releases(this_rq->lock)
2056 __acquires(busiest->lock)
2057 __acquires(this_rq->lock)
2059 if (unlikely(!spin_trylock(&busiest->lock))) {
2060 if (busiest < this_rq) {
2061 spin_unlock(&this_rq->lock);
2062 spin_lock(&busiest->lock);
2063 spin_lock(&this_rq->lock);
2065 spin_lock(&busiest->lock);
2070 * If dest_cpu is allowed for this process, migrate the task to it.
2071 * This is accomplished by forcing the cpu_allowed mask to only
2072 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2073 * the cpu_allowed mask is restored.
2075 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
2077 struct migration_req req;
2078 unsigned long flags;
2081 rq = task_rq_lock(p, &flags);
2082 if (!cpu_isset(dest_cpu, p->cpus_allowed)
2083 || unlikely(cpu_is_offline(dest_cpu)))
2086 /* force the process onto the specified CPU */
2087 if (migrate_task(p, dest_cpu, &req)) {
2088 /* Need to wait for migration thread (might exit: take ref). */
2089 struct task_struct *mt = rq->migration_thread;
2091 get_task_struct(mt);
2092 task_rq_unlock(rq, &flags);
2093 wake_up_process(mt);
2094 put_task_struct(mt);
2095 wait_for_completion(&req.done);
2100 task_rq_unlock(rq, &flags);
2104 * sched_exec - execve() is a valuable balancing opportunity, because at
2105 * this point the task has the smallest effective memory and cache footprint.
2107 void sched_exec(void)
2109 int new_cpu, this_cpu = get_cpu();
2110 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
2112 if (new_cpu != this_cpu)
2113 sched_migrate_task(current, new_cpu);
2117 * pull_task - move a task from a remote runqueue to the local runqueue.
2118 * Both runqueues must be locked.
2120 static void pull_task(struct rq *src_rq, struct prio_array *src_array,
2121 struct task_struct *p, struct rq *this_rq,
2122 struct prio_array *this_array, int this_cpu)
2124 dequeue_task(p, src_array);
2125 dec_nr_running(p, src_rq);
2126 set_task_cpu(p, this_cpu);
2127 inc_nr_running(p, this_rq);
2128 enqueue_task(p, this_array);
2129 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
2130 + this_rq->timestamp_last_tick;
2132 * Note that idle threads have a prio of MAX_PRIO, for this test
2133 * to be always true for them.
2135 if (TASK_PREEMPTS_CURR(p, this_rq))
2136 resched_task(this_rq->curr);
2140 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2143 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
2144 struct sched_domain *sd, enum idle_type idle,
2148 * We do not migrate tasks that are:
2149 * 1) running (obviously), or
2150 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2151 * 3) are cache-hot on their current CPU.
2153 if (!cpu_isset(this_cpu, p->cpus_allowed))
2157 if (task_running(rq, p))
2161 * Aggressive migration if:
2162 * 1) task is cache cold, or
2163 * 2) too many balance attempts have failed.
2166 if (sd->nr_balance_failed > sd->cache_nice_tries)
2169 if (task_hot(p, rq->timestamp_last_tick, sd))
2174 #define rq_best_prio(rq) min((rq)->curr->prio, (rq)->best_expired_prio)
2177 * move_tasks tries to move up to max_nr_move tasks and max_load_move weighted
2178 * load from busiest to this_rq, as part of a balancing operation within
2179 * "domain". Returns the number of tasks moved.
2181 * Called with both runqueues locked.
2183 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2184 unsigned long max_nr_move, unsigned long max_load_move,
2185 struct sched_domain *sd, enum idle_type idle,
2188 int idx, pulled = 0, pinned = 0, this_best_prio, best_prio,
2189 best_prio_seen, skip_for_load;
2190 struct prio_array *array, *dst_array;
2191 struct list_head *head, *curr;
2192 struct task_struct *tmp;
2195 if (max_nr_move == 0 || max_load_move == 0)
2198 rem_load_move = max_load_move;
2200 this_best_prio = rq_best_prio(this_rq);
2201 best_prio = rq_best_prio(busiest);
2203 * Enable handling of the case where there is more than one task
2204 * with the best priority. If the current running task is one
2205 * of those with prio==best_prio we know it won't be moved
2206 * and therefore it's safe to override the skip (based on load) of
2207 * any task we find with that prio.
2209 best_prio_seen = best_prio == busiest->curr->prio;
2212 * We first consider expired tasks. Those will likely not be
2213 * executed in the near future, and they are most likely to
2214 * be cache-cold, thus switching CPUs has the least effect
2217 if (busiest->expired->nr_active) {
2218 array = busiest->expired;
2219 dst_array = this_rq->expired;
2221 array = busiest->active;
2222 dst_array = this_rq->active;
2226 /* Start searching at priority 0: */
2230 idx = sched_find_first_bit(array->bitmap);
2232 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
2233 if (idx >= MAX_PRIO) {
2234 if (array == busiest->expired && busiest->active->nr_active) {
2235 array = busiest->active;
2236 dst_array = this_rq->active;
2242 head = array->queue + idx;
2245 tmp = list_entry(curr, struct task_struct, run_list);
2250 * To help distribute high priority tasks accross CPUs we don't
2251 * skip a task if it will be the highest priority task (i.e. smallest
2252 * prio value) on its new queue regardless of its load weight
2254 skip_for_load = tmp->load_weight > rem_load_move;
2255 if (skip_for_load && idx < this_best_prio)
2256 skip_for_load = !best_prio_seen && idx == best_prio;
2257 if (skip_for_load ||
2258 !can_migrate_task(tmp, busiest, this_cpu, sd, idle, &pinned)) {
2260 best_prio_seen |= idx == best_prio;
2267 #ifdef CONFIG_SCHEDSTATS
2268 if (task_hot(tmp, busiest->timestamp_last_tick, sd))
2269 schedstat_inc(sd, lb_hot_gained[idle]);
2272 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
2274 rem_load_move -= tmp->load_weight;
2277 * We only want to steal up to the prescribed number of tasks
2278 * and the prescribed amount of weighted load.
2280 if (pulled < max_nr_move && rem_load_move > 0) {
2281 if (idx < this_best_prio)
2282 this_best_prio = idx;
2290 * Right now, this is the only place pull_task() is called,
2291 * so we can safely collect pull_task() stats here rather than
2292 * inside pull_task().
2294 schedstat_add(sd, lb_gained[idle], pulled);
2297 *all_pinned = pinned;
2302 * find_busiest_group finds and returns the busiest CPU group within the
2303 * domain. It calculates and returns the amount of weighted load which
2304 * should be moved to restore balance via the imbalance parameter.
2306 static struct sched_group *
2307 find_busiest_group(struct sched_domain *sd, int this_cpu,
2308 unsigned long *imbalance, enum idle_type idle, int *sd_idle,
2311 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2312 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2313 unsigned long max_pull;
2314 unsigned long busiest_load_per_task, busiest_nr_running;
2315 unsigned long this_load_per_task, this_nr_running;
2317 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2318 int power_savings_balance = 1;
2319 unsigned long leader_nr_running = 0, min_load_per_task = 0;
2320 unsigned long min_nr_running = ULONG_MAX;
2321 struct sched_group *group_min = NULL, *group_leader = NULL;
2324 max_load = this_load = total_load = total_pwr = 0;
2325 busiest_load_per_task = busiest_nr_running = 0;
2326 this_load_per_task = this_nr_running = 0;
2327 if (idle == NOT_IDLE)
2328 load_idx = sd->busy_idx;
2329 else if (idle == NEWLY_IDLE)
2330 load_idx = sd->newidle_idx;
2332 load_idx = sd->idle_idx;
2335 unsigned long load, group_capacity;
2338 unsigned long sum_nr_running, sum_weighted_load;
2340 local_group = cpu_isset(this_cpu, group->cpumask);
2342 /* Tally up the load of all CPUs in the group */
2343 sum_weighted_load = sum_nr_running = avg_load = 0;
2345 for_each_cpu_mask(i, group->cpumask) {
2348 if (!cpu_isset(i, *cpus))
2353 if (*sd_idle && !idle_cpu(i))
2356 /* Bias balancing toward cpus of our domain */
2358 load = target_load(i, load_idx);
2360 load = source_load(i, load_idx);
2363 sum_nr_running += rq->nr_running;
2364 sum_weighted_load += rq->raw_weighted_load;
2367 total_load += avg_load;
2368 total_pwr += group->cpu_power;
2370 /* Adjust by relative CPU power of the group */
2371 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
2373 group_capacity = group->cpu_power / SCHED_LOAD_SCALE;
2376 this_load = avg_load;
2378 this_nr_running = sum_nr_running;
2379 this_load_per_task = sum_weighted_load;
2380 } else if (avg_load > max_load &&
2381 sum_nr_running > group_capacity) {
2382 max_load = avg_load;
2384 busiest_nr_running = sum_nr_running;
2385 busiest_load_per_task = sum_weighted_load;
2388 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2390 * Busy processors will not participate in power savings
2393 if (idle == NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
2397 * If the local group is idle or completely loaded
2398 * no need to do power savings balance at this domain
2400 if (local_group && (this_nr_running >= group_capacity ||
2402 power_savings_balance = 0;
2405 * If a group is already running at full capacity or idle,
2406 * don't include that group in power savings calculations
2408 if (!power_savings_balance || sum_nr_running >= group_capacity
2413 * Calculate the group which has the least non-idle load.
2414 * This is the group from where we need to pick up the load
2417 if ((sum_nr_running < min_nr_running) ||
2418 (sum_nr_running == min_nr_running &&
2419 first_cpu(group->cpumask) <
2420 first_cpu(group_min->cpumask))) {
2422 min_nr_running = sum_nr_running;
2423 min_load_per_task = sum_weighted_load /
2428 * Calculate the group which is almost near its
2429 * capacity but still has some space to pick up some load
2430 * from other group and save more power
2432 if (sum_nr_running <= group_capacity - 1) {
2433 if (sum_nr_running > leader_nr_running ||
2434 (sum_nr_running == leader_nr_running &&
2435 first_cpu(group->cpumask) >
2436 first_cpu(group_leader->cpumask))) {
2437 group_leader = group;
2438 leader_nr_running = sum_nr_running;
2443 group = group->next;
2444 } while (group != sd->groups);
2446 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
2449 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2451 if (this_load >= avg_load ||
2452 100*max_load <= sd->imbalance_pct*this_load)
2455 busiest_load_per_task /= busiest_nr_running;
2457 * We're trying to get all the cpus to the average_load, so we don't
2458 * want to push ourselves above the average load, nor do we wish to
2459 * reduce the max loaded cpu below the average load, as either of these
2460 * actions would just result in more rebalancing later, and ping-pong
2461 * tasks around. Thus we look for the minimum possible imbalance.
2462 * Negative imbalances (*we* are more loaded than anyone else) will
2463 * be counted as no imbalance for these purposes -- we can't fix that
2464 * by pulling tasks to us. Be careful of negative numbers as they'll
2465 * appear as very large values with unsigned longs.
2467 if (max_load <= busiest_load_per_task)
2471 * In the presence of smp nice balancing, certain scenarios can have
2472 * max load less than avg load(as we skip the groups at or below
2473 * its cpu_power, while calculating max_load..)
2475 if (max_load < avg_load) {
2477 goto small_imbalance;
2480 /* Don't want to pull so many tasks that a group would go idle */
2481 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
2483 /* How much load to actually move to equalise the imbalance */
2484 *imbalance = min(max_pull * busiest->cpu_power,
2485 (avg_load - this_load) * this->cpu_power)
2489 * if *imbalance is less than the average load per runnable task
2490 * there is no gaurantee that any tasks will be moved so we'll have
2491 * a think about bumping its value to force at least one task to be
2494 if (*imbalance < busiest_load_per_task) {
2495 unsigned long tmp, pwr_now, pwr_move;
2499 pwr_move = pwr_now = 0;
2501 if (this_nr_running) {
2502 this_load_per_task /= this_nr_running;
2503 if (busiest_load_per_task > this_load_per_task)
2506 this_load_per_task = SCHED_LOAD_SCALE;
2508 if (max_load - this_load >= busiest_load_per_task * imbn) {
2509 *imbalance = busiest_load_per_task;
2514 * OK, we don't have enough imbalance to justify moving tasks,
2515 * however we may be able to increase total CPU power used by
2519 pwr_now += busiest->cpu_power *
2520 min(busiest_load_per_task, max_load);
2521 pwr_now += this->cpu_power *
2522 min(this_load_per_task, this_load);
2523 pwr_now /= SCHED_LOAD_SCALE;
2525 /* Amount of load we'd subtract */
2526 tmp = busiest_load_per_task*SCHED_LOAD_SCALE/busiest->cpu_power;
2528 pwr_move += busiest->cpu_power *
2529 min(busiest_load_per_task, max_load - tmp);
2531 /* Amount of load we'd add */
2532 if (max_load*busiest->cpu_power <
2533 busiest_load_per_task*SCHED_LOAD_SCALE)
2534 tmp = max_load*busiest->cpu_power/this->cpu_power;
2536 tmp = busiest_load_per_task*SCHED_LOAD_SCALE/this->cpu_power;
2537 pwr_move += this->cpu_power*min(this_load_per_task, this_load + tmp);
2538 pwr_move /= SCHED_LOAD_SCALE;
2540 /* Move if we gain throughput */
2541 if (pwr_move <= pwr_now)
2544 *imbalance = busiest_load_per_task;
2550 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2551 if (idle == NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
2554 if (this == group_leader && group_leader != group_min) {
2555 *imbalance = min_load_per_task;
2565 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2568 find_busiest_queue(struct sched_group *group, enum idle_type idle,
2569 unsigned long imbalance, cpumask_t *cpus)
2571 struct rq *busiest = NULL, *rq;
2572 unsigned long max_load = 0;
2575 for_each_cpu_mask(i, group->cpumask) {
2577 if (!cpu_isset(i, *cpus))
2582 if (rq->nr_running == 1 && rq->raw_weighted_load > imbalance)
2585 if (rq->raw_weighted_load > max_load) {
2586 max_load = rq->raw_weighted_load;
2595 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2596 * so long as it is large enough.
2598 #define MAX_PINNED_INTERVAL 512
2600 static inline unsigned long minus_1_or_zero(unsigned long n)
2602 return n > 0 ? n - 1 : 0;
2606 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2607 * tasks if there is an imbalance.
2609 * Called with this_rq unlocked.
2611 static int load_balance(int this_cpu, struct rq *this_rq,
2612 struct sched_domain *sd, enum idle_type idle)
2614 int nr_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
2615 struct sched_group *group;
2616 unsigned long imbalance;
2618 cpumask_t cpus = CPU_MASK_ALL;
2620 if (idle != NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
2621 !sched_smt_power_savings)
2624 schedstat_inc(sd, lb_cnt[idle]);
2627 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
2630 schedstat_inc(sd, lb_nobusyg[idle]);
2634 busiest = find_busiest_queue(group, idle, imbalance, &cpus);
2636 schedstat_inc(sd, lb_nobusyq[idle]);
2640 BUG_ON(busiest == this_rq);
2642 schedstat_add(sd, lb_imbalance[idle], imbalance);
2645 if (busiest->nr_running > 1) {
2647 * Attempt to move tasks. If find_busiest_group has found
2648 * an imbalance but busiest->nr_running <= 1, the group is
2649 * still unbalanced. nr_moved simply stays zero, so it is
2650 * correctly treated as an imbalance.
2652 double_rq_lock(this_rq, busiest);
2653 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2654 minus_1_or_zero(busiest->nr_running),
2655 imbalance, sd, idle, &all_pinned);
2656 double_rq_unlock(this_rq, busiest);
2658 /* All tasks on this runqueue were pinned by CPU affinity */
2659 if (unlikely(all_pinned)) {
2660 cpu_clear(cpu_of(busiest), cpus);
2661 if (!cpus_empty(cpus))
2668 schedstat_inc(sd, lb_failed[idle]);
2669 sd->nr_balance_failed++;
2671 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2673 spin_lock(&busiest->lock);
2675 /* don't kick the migration_thread, if the curr
2676 * task on busiest cpu can't be moved to this_cpu
2678 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
2679 spin_unlock(&busiest->lock);
2681 goto out_one_pinned;
2684 if (!busiest->active_balance) {
2685 busiest->active_balance = 1;
2686 busiest->push_cpu = this_cpu;
2689 spin_unlock(&busiest->lock);
2691 wake_up_process(busiest->migration_thread);
2694 * We've kicked active balancing, reset the failure
2697 sd->nr_balance_failed = sd->cache_nice_tries+1;
2700 sd->nr_balance_failed = 0;
2702 if (likely(!active_balance)) {
2703 /* We were unbalanced, so reset the balancing interval */
2704 sd->balance_interval = sd->min_interval;
2707 * If we've begun active balancing, start to back off. This
2708 * case may not be covered by the all_pinned logic if there
2709 * is only 1 task on the busy runqueue (because we don't call
2712 if (sd->balance_interval < sd->max_interval)
2713 sd->balance_interval *= 2;
2716 if (!nr_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2717 !sched_smt_power_savings)
2722 schedstat_inc(sd, lb_balanced[idle]);
2724 sd->nr_balance_failed = 0;
2727 /* tune up the balancing interval */
2728 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
2729 (sd->balance_interval < sd->max_interval))
2730 sd->balance_interval *= 2;
2732 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2733 !sched_smt_power_savings)
2739 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2740 * tasks if there is an imbalance.
2742 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2743 * this_rq is locked.
2746 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
2748 struct sched_group *group;
2749 struct rq *busiest = NULL;
2750 unsigned long imbalance;
2753 cpumask_t cpus = CPU_MASK_ALL;
2755 if (sd->flags & SD_SHARE_CPUPOWER && !sched_smt_power_savings)
2758 schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2760 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE,
2763 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2767 busiest = find_busiest_queue(group, NEWLY_IDLE, imbalance,
2770 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2774 BUG_ON(busiest == this_rq);
2776 schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2779 if (busiest->nr_running > 1) {
2780 /* Attempt to move tasks */
2781 double_lock_balance(this_rq, busiest);
2782 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2783 minus_1_or_zero(busiest->nr_running),
2784 imbalance, sd, NEWLY_IDLE, NULL);
2785 spin_unlock(&busiest->lock);
2788 cpu_clear(cpu_of(busiest), cpus);
2789 if (!cpus_empty(cpus))
2795 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2796 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2799 sd->nr_balance_failed = 0;
2804 schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
2805 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2806 !sched_smt_power_savings)
2808 sd->nr_balance_failed = 0;
2814 * idle_balance is called by schedule() if this_cpu is about to become
2815 * idle. Attempts to pull tasks from other CPUs.
2817 static void idle_balance(int this_cpu, struct rq *this_rq)
2819 struct sched_domain *sd;
2821 for_each_domain(this_cpu, sd) {
2822 if (sd->flags & SD_BALANCE_NEWIDLE) {
2823 /* If we've pulled tasks over stop searching: */
2824 if (load_balance_newidle(this_cpu, this_rq, sd))
2831 * active_load_balance is run by migration threads. It pushes running tasks
2832 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2833 * running on each physical CPU where possible, and avoids physical /
2834 * logical imbalances.
2836 * Called with busiest_rq locked.
2838 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
2840 int target_cpu = busiest_rq->push_cpu;
2841 struct sched_domain *sd;
2842 struct rq *target_rq;
2844 /* Is there any task to move? */
2845 if (busiest_rq->nr_running <= 1)
2848 target_rq = cpu_rq(target_cpu);
2851 * This condition is "impossible", if it occurs
2852 * we need to fix it. Originally reported by
2853 * Bjorn Helgaas on a 128-cpu setup.
2855 BUG_ON(busiest_rq == target_rq);
2857 /* move a task from busiest_rq to target_rq */
2858 double_lock_balance(busiest_rq, target_rq);
2860 /* Search for an sd spanning us and the target CPU. */
2861 for_each_domain(target_cpu, sd) {
2862 if ((sd->flags & SD_LOAD_BALANCE) &&
2863 cpu_isset(busiest_cpu, sd->span))
2868 schedstat_inc(sd, alb_cnt);
2870 if (move_tasks(target_rq, target_cpu, busiest_rq, 1,
2871 RTPRIO_TO_LOAD_WEIGHT(100), sd, SCHED_IDLE,
2873 schedstat_inc(sd, alb_pushed);
2875 schedstat_inc(sd, alb_failed);
2877 spin_unlock(&target_rq->lock);
2881 * rebalance_tick will get called every timer tick, on every CPU.
2883 * It checks each scheduling domain to see if it is due to be balanced,
2884 * and initiates a balancing operation if so.
2886 * Balancing parameters are set up in arch_init_sched_domains.
2889 /* Don't have all balancing operations going off at once: */
2890 static inline unsigned long cpu_offset(int cpu)
2892 return jiffies + cpu * HZ / NR_CPUS;
2896 rebalance_tick(int this_cpu, struct rq *this_rq, enum idle_type idle)
2898 unsigned long this_load, interval, j = cpu_offset(this_cpu);
2899 struct sched_domain *sd;
2902 this_load = this_rq->raw_weighted_load;
2904 /* Update our load: */
2905 for (i = 0, scale = 1; i < 3; i++, scale <<= 1) {
2906 unsigned long old_load, new_load;
2908 old_load = this_rq->cpu_load[i];
2909 new_load = this_load;
2911 * Round up the averaging division if load is increasing. This
2912 * prevents us from getting stuck on 9 if the load is 10, for
2915 if (new_load > old_load)
2916 new_load += scale-1;
2917 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) / scale;
2920 for_each_domain(this_cpu, sd) {
2921 if (!(sd->flags & SD_LOAD_BALANCE))
2924 interval = sd->balance_interval;
2925 if (idle != SCHED_IDLE)
2926 interval *= sd->busy_factor;
2928 /* scale ms to jiffies */
2929 interval = msecs_to_jiffies(interval);
2930 if (unlikely(!interval))
2933 if (j - sd->last_balance >= interval) {
2934 if (load_balance(this_cpu, this_rq, sd, idle)) {
2936 * We've pulled tasks over so either we're no
2937 * longer idle, or one of our SMT siblings is
2942 sd->last_balance += interval;
2948 * on UP we do not need to balance between CPUs:
2950 static inline void rebalance_tick(int cpu, struct rq *rq, enum idle_type idle)
2953 static inline void idle_balance(int cpu, struct rq *rq)
2958 static inline int wake_priority_sleeper(struct rq *rq)
2962 #ifdef CONFIG_SCHED_SMT
2963 spin_lock(&rq->lock);
2965 * If an SMT sibling task has been put to sleep for priority
2966 * reasons reschedule the idle task to see if it can now run.
2968 if (rq->nr_running) {
2969 resched_task(rq->idle);
2972 spin_unlock(&rq->lock);
2977 DEFINE_PER_CPU(struct kernel_stat, kstat);
2979 EXPORT_PER_CPU_SYMBOL(kstat);
2982 * This is called on clock ticks and on context switches.
2983 * Bank in p->sched_time the ns elapsed since the last tick or switch.
2986 update_cpu_clock(struct task_struct *p, struct rq *rq, unsigned long long now)
2988 p->sched_time += now - max(p->timestamp, rq->timestamp_last_tick);
2992 * Return current->sched_time plus any more ns on the sched_clock
2993 * that have not yet been banked.
2995 unsigned long long current_sched_time(const struct task_struct *p)
2997 unsigned long long ns;
2998 unsigned long flags;
3000 local_irq_save(flags);
3001 ns = max(p->timestamp, task_rq(p)->timestamp_last_tick);
3002 ns = p->sched_time + sched_clock() - ns;
3003 local_irq_restore(flags);
3009 * We place interactive tasks back into the active array, if possible.
3011 * To guarantee that this does not starve expired tasks we ignore the
3012 * interactivity of a task if the first expired task had to wait more
3013 * than a 'reasonable' amount of time. This deadline timeout is
3014 * load-dependent, as the frequency of array switched decreases with
3015 * increasing number of running tasks. We also ignore the interactivity
3016 * if a better static_prio task has expired:
3018 static inline int expired_starving(struct rq *rq)
3020 if (rq->curr->static_prio > rq->best_expired_prio)
3022 if (!STARVATION_LIMIT || !rq->expired_timestamp)
3024 if (jiffies - rq->expired_timestamp > STARVATION_LIMIT * rq->nr_running)
3030 * Account user cpu time to a process.
3031 * @p: the process that the cpu time gets accounted to
3032 * @hardirq_offset: the offset to subtract from hardirq_count()
3033 * @cputime: the cpu time spent in user space since the last update
3035 void account_user_time(struct task_struct *p, cputime_t cputime)
3037 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3038 struct vx_info *vxi = p->vx_info; /* p is _always_ current */
3040 int nice = (TASK_NICE(p) > 0);
3042 p->utime = cputime_add(p->utime, cputime);
3043 vx_account_user(vxi, cputime, nice);
3045 /* Add user time to cpustat. */
3046 tmp = cputime_to_cputime64(cputime);
3048 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3050 cpustat->user = cputime64_add(cpustat->user, tmp);
3054 * Account system cpu time to a process.
3055 * @p: the process that the cpu time gets accounted to
3056 * @hardirq_offset: the offset to subtract from hardirq_count()
3057 * @cputime: the cpu time spent in kernel space since the last update
3059 void account_system_time(struct task_struct *p, int hardirq_offset,
3062 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3063 struct vx_info *vxi = p->vx_info; /* p is _always_ current */
3064 struct rq *rq = this_rq();
3067 p->stime = cputime_add(p->stime, cputime);
3068 vx_account_system(vxi, cputime, (p == rq->idle));
3070 /* Add system time to cpustat. */
3071 tmp = cputime_to_cputime64(cputime);
3072 if (hardirq_count() - hardirq_offset)
3073 cpustat->irq = cputime64_add(cpustat->irq, tmp);
3074 else if (softirq_count())
3075 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
3076 else if (p != rq->idle)
3077 cpustat->system = cputime64_add(cpustat->system, tmp);
3078 else if (atomic_read(&rq->nr_iowait) > 0)
3079 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3081 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3082 /* Account for system time used */
3083 acct_update_integrals(p);
3087 * Account for involuntary wait time.
3088 * @p: the process from which the cpu time has been stolen
3089 * @steal: the cpu time spent in involuntary wait
3091 void account_steal_time(struct task_struct *p, cputime_t steal)
3093 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3094 cputime64_t tmp = cputime_to_cputime64(steal);
3095 struct rq *rq = this_rq();
3097 if (p == rq->idle) {
3098 p->stime = cputime_add(p->stime, steal);
3099 if (atomic_read(&rq->nr_iowait) > 0)
3100 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3102 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3104 cpustat->steal = cputime64_add(cpustat->steal, tmp);
3108 * This function gets called by the timer code, with HZ frequency.
3109 * We call it with interrupts disabled.
3111 * It also gets called by the fork code, when changing the parent's
3114 void scheduler_tick(void)
3116 unsigned long long now = sched_clock();
3117 struct task_struct *p = current;
3118 int cpu = smp_processor_id();
3119 struct rq *rq = cpu_rq(cpu);
3121 update_cpu_clock(p, rq, now);
3123 rq->timestamp_last_tick = now;
3125 if (p == rq->idle) {
3126 if (wake_priority_sleeper(rq))
3128 #ifdef CONFIG_VSERVER_HARDCPU_IDLE
3129 if (!--rq->idle_tokens && !list_empty(&rq->hold_queue))
3132 rebalance_tick(cpu, rq, SCHED_IDLE);
3136 /* Task might have expired already, but not scheduled off yet */
3137 if (p->array != rq->active) {
3138 set_tsk_need_resched(p);
3141 spin_lock(&rq->lock);
3143 * The task was running during this tick - update the
3144 * time slice counter. Note: we do not update a thread's
3145 * priority until it either goes to sleep or uses up its
3146 * timeslice. This makes it possible for interactive tasks
3147 * to use up their timeslices at their highest priority levels.
3151 * RR tasks need a special form of timeslice management.
3152 * FIFO tasks have no timeslices.
3154 if ((p->policy == SCHED_RR) && !--p->time_slice) {
3155 p->time_slice = task_timeslice(p);
3156 p->first_time_slice = 0;
3157 set_tsk_need_resched(p);
3159 /* put it at the end of the queue: */
3160 requeue_task(p, rq->active);
3164 if (vx_need_resched(p)) {
3165 dequeue_task(p, rq->active);
3166 set_tsk_need_resched(p);
3167 p->prio = effective_prio(p);
3168 p->time_slice = task_timeslice(p);
3169 p->first_time_slice = 0;
3171 if (!rq->expired_timestamp)
3172 rq->expired_timestamp = jiffies;
3173 if (!TASK_INTERACTIVE(p) || expired_starving(rq)) {
3174 enqueue_task(p, rq->expired);
3175 if (p->static_prio < rq->best_expired_prio)
3176 rq->best_expired_prio = p->static_prio;
3178 enqueue_task(p, rq->active);
3181 * Prevent a too long timeslice allowing a task to monopolize
3182 * the CPU. We do this by splitting up the timeslice into
3185 * Note: this does not mean the task's timeslices expire or
3186 * get lost in any way, they just might be preempted by
3187 * another task of equal priority. (one with higher
3188 * priority would have preempted this task already.) We
3189 * requeue this task to the end of the list on this priority
3190 * level, which is in essence a round-robin of tasks with
3193 * This only applies to tasks in the interactive
3194 * delta range with at least TIMESLICE_GRANULARITY to requeue.
3196 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
3197 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
3198 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
3199 (p->array == rq->active)) {
3201 requeue_task(p, rq->active);
3202 set_tsk_need_resched(p);
3206 spin_unlock(&rq->lock);
3208 rebalance_tick(cpu, rq, NOT_IDLE);
3211 #ifdef CONFIG_SCHED_SMT
3212 static inline void wakeup_busy_runqueue(struct rq *rq)
3214 /* If an SMT runqueue is sleeping due to priority reasons wake it up */
3215 if (rq->curr == rq->idle && rq->nr_running)
3216 resched_task(rq->idle);
3220 * Called with interrupt disabled and this_rq's runqueue locked.
3222 static void wake_sleeping_dependent(int this_cpu)
3224 struct sched_domain *tmp, *sd = NULL;
3227 for_each_domain(this_cpu, tmp) {
3228 if (tmp->flags & SD_SHARE_CPUPOWER) {
3237 for_each_cpu_mask(i, sd->span) {
3238 struct rq *smt_rq = cpu_rq(i);
3242 if (unlikely(!spin_trylock(&smt_rq->lock)))
3245 wakeup_busy_runqueue(smt_rq);
3246 spin_unlock(&smt_rq->lock);
3251 * number of 'lost' timeslices this task wont be able to fully
3252 * utilize, if another task runs on a sibling. This models the
3253 * slowdown effect of other tasks running on siblings:
3255 static inline unsigned long
3256 smt_slice(struct task_struct *p, struct sched_domain *sd)
3258 return p->time_slice * (100 - sd->per_cpu_gain) / 100;
3262 * To minimise lock contention and not have to drop this_rq's runlock we only
3263 * trylock the sibling runqueues and bypass those runqueues if we fail to
3264 * acquire their lock. As we only trylock the normal locking order does not
3265 * need to be obeyed.
3268 dependent_sleeper(int this_cpu, struct rq *this_rq, struct task_struct *p)
3270 struct sched_domain *tmp, *sd = NULL;
3273 /* kernel/rt threads do not participate in dependent sleeping */
3274 if (!p->mm || rt_task(p))
3277 for_each_domain(this_cpu, tmp) {
3278 if (tmp->flags & SD_SHARE_CPUPOWER) {
3287 for_each_cpu_mask(i, sd->span) {
3288 struct task_struct *smt_curr;
3295 if (unlikely(!spin_trylock(&smt_rq->lock)))
3298 smt_curr = smt_rq->curr;
3304 * If a user task with lower static priority than the
3305 * running task on the SMT sibling is trying to schedule,
3306 * delay it till there is proportionately less timeslice
3307 * left of the sibling task to prevent a lower priority
3308 * task from using an unfair proportion of the
3309 * physical cpu's resources. -ck
3311 if (rt_task(smt_curr)) {
3313 * With real time tasks we run non-rt tasks only
3314 * per_cpu_gain% of the time.
3316 if ((jiffies % DEF_TIMESLICE) >
3317 (sd->per_cpu_gain * DEF_TIMESLICE / 100))
3320 if (smt_curr->static_prio < p->static_prio &&
3321 !TASK_PREEMPTS_CURR(p, smt_rq) &&
3322 smt_slice(smt_curr, sd) > task_timeslice(p))
3326 spin_unlock(&smt_rq->lock);
3331 static inline void wake_sleeping_dependent(int this_cpu)
3335 dependent_sleeper(int this_cpu, struct rq *this_rq, struct task_struct *p)
3341 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3343 void fastcall add_preempt_count(int val)
3348 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3350 preempt_count() += val;
3352 * Spinlock count overflowing soon?
3354 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
3356 EXPORT_SYMBOL(add_preempt_count);
3358 void fastcall sub_preempt_count(int val)
3363 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3366 * Is the spinlock portion underflowing?
3368 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3369 !(preempt_count() & PREEMPT_MASK)))
3372 preempt_count() -= val;
3374 EXPORT_SYMBOL(sub_preempt_count);
3378 static inline int interactive_sleep(enum sleep_type sleep_type)
3380 return (sleep_type == SLEEP_INTERACTIVE ||
3381 sleep_type == SLEEP_INTERRUPTED);
3385 * schedule() is the main scheduler function.
3387 asmlinkage void __sched schedule(void)
3389 struct task_struct *prev, *next;
3390 struct prio_array *array;
3391 struct list_head *queue;
3392 unsigned long long now;
3393 unsigned long run_time;
3394 int cpu, idx, new_prio;
3397 struct vx_info *vxi;
3398 #ifdef CONFIG_VSERVER_HARDCPU
3403 * Test if we are atomic. Since do_exit() needs to call into
3404 * schedule() atomically, we ignore that path for now.
3405 * Otherwise, whine if we are scheduling when we should not be.
3407 if (unlikely(in_atomic() && !current->exit_state)) {
3408 printk(KERN_ERR "BUG: scheduling while atomic: "
3410 current->comm, preempt_count(), current->pid);
3413 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3418 release_kernel_lock(prev);
3419 need_resched_nonpreemptible:
3423 * The idle thread is not allowed to schedule!
3424 * Remove this check after it has been exercised a bit.
3426 if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
3427 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
3431 schedstat_inc(rq, sched_cnt);
3432 now = sched_clock();
3433 if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
3434 run_time = now - prev->timestamp;
3435 if (unlikely((long long)(now - prev->timestamp) < 0))
3438 run_time = NS_MAX_SLEEP_AVG;
3441 * Tasks charged proportionately less run_time at high sleep_avg to
3442 * delay them losing their interactive status
3444 run_time /= (CURRENT_BONUS(prev) ? : 1);
3446 spin_lock_irq(&rq->lock);
3448 if (unlikely(prev->flags & PF_DEAD))
3449 prev->state = EXIT_DEAD;
3451 switch_count = &prev->nivcsw;
3452 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3453 switch_count = &prev->nvcsw;
3454 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
3455 unlikely(signal_pending(prev))))
3456 prev->state = TASK_RUNNING;
3458 if (prev->state == TASK_UNINTERRUPTIBLE) {
3459 rq->nr_uninterruptible++;
3460 vx_uninterruptible_inc(prev);
3462 deactivate_task(prev, rq);
3466 #ifdef CONFIG_VSERVER_HARDCPU
3467 if (!list_empty(&rq->hold_queue)) {
3468 struct list_head *l, *n;
3472 list_for_each_safe(l, n, &rq->hold_queue) {
3473 next = list_entry(l, struct task_struct, run_list);
3474 if (vxi == next->vx_info)
3477 vxi = next->vx_info;
3478 ret = vx_tokens_recalc(vxi);
3481 vx_unhold_task(vxi, next, rq);
3484 if ((ret < 0) && (maxidle < ret))
3488 rq->idle_tokens = -maxidle;
3493 cpu = smp_processor_id();
3494 if (unlikely(!rq->nr_running)) {
3495 idle_balance(cpu, rq);
3496 if (!rq->nr_running) {
3498 rq->expired_timestamp = 0;
3499 wake_sleeping_dependent(cpu);
3505 if (unlikely(!array->nr_active)) {
3507 * Switch the active and expired arrays.
3509 schedstat_inc(rq, sched_switch);
3510 rq->active = rq->expired;
3511 rq->expired = array;
3513 rq->expired_timestamp = 0;
3514 rq->best_expired_prio = MAX_PRIO;
3517 idx = sched_find_first_bit(array->bitmap);
3518 queue = array->queue + idx;
3519 next = list_entry(queue->next, struct task_struct, run_list);
3521 vxi = next->vx_info;
3522 #ifdef CONFIG_VSERVER_HARDCPU
3523 if (vx_info_flags(vxi, VXF_SCHED_PAUSE|VXF_SCHED_HARD, 0)) {
3524 int ret = vx_tokens_recalc(vxi);
3526 if (unlikely(ret <= 0)) {
3527 if (ret && (rq->idle_tokens > -ret))
3528 rq->idle_tokens = -ret;
3529 vx_hold_task(vxi, next, rq);
3532 } else /* well, looks ugly but not as ugly as the ifdef-ed version */
3534 if (vx_info_flags(vxi, VXF_SCHED_PRIO, 0))
3535 vx_tokens_recalc(vxi);
3537 if (!rt_task(next) && interactive_sleep(next->sleep_type)) {
3538 unsigned long long delta = now - next->timestamp;
3539 if (unlikely((long long)(now - next->timestamp) < 0))
3542 if (next->sleep_type == SLEEP_INTERACTIVE)
3543 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
3545 array = next->array;
3546 new_prio = recalc_task_prio(next, next->timestamp + delta);
3548 if (unlikely(next->prio != new_prio)) {
3549 dequeue_task(next, array);
3550 next->prio = new_prio;
3551 enqueue_task(next, array);
3554 next->sleep_type = SLEEP_NORMAL;
3555 if (dependent_sleeper(cpu, rq, next))
3558 if (next == rq->idle)
3559 schedstat_inc(rq, sched_goidle);
3561 prefetch_stack(next);
3562 clear_tsk_need_resched(prev);
3563 rcu_qsctr_inc(task_cpu(prev));
3565 update_cpu_clock(prev, rq, now);
3567 prev->sleep_avg -= run_time;
3568 if ((long)prev->sleep_avg <= 0)
3569 prev->sleep_avg = 0;
3570 prev->timestamp = prev->last_ran = now;
3572 sched_info_switch(prev, next);
3573 if (likely(prev != next)) {
3574 next->timestamp = now;
3579 prepare_task_switch(rq, next);
3580 prev = context_switch(rq, prev, next);
3583 * this_rq must be evaluated again because prev may have moved
3584 * CPUs since it called schedule(), thus the 'rq' on its stack
3585 * frame will be invalid.
3587 finish_task_switch(this_rq(), prev);
3589 spin_unlock_irq(&rq->lock);
3592 if (unlikely(reacquire_kernel_lock(prev) < 0))
3593 goto need_resched_nonpreemptible;
3594 preempt_enable_no_resched();
3595 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3598 EXPORT_SYMBOL(schedule);
3600 #ifdef CONFIG_PREEMPT
3602 * this is the entry point to schedule() from in-kernel preemption
3603 * off of preempt_enable. Kernel preemptions off return from interrupt
3604 * occur there and call schedule directly.
3606 asmlinkage void __sched preempt_schedule(void)
3608 struct thread_info *ti = current_thread_info();
3609 #ifdef CONFIG_PREEMPT_BKL
3610 struct task_struct *task = current;
3611 int saved_lock_depth;
3614 * If there is a non-zero preempt_count or interrupts are disabled,
3615 * we do not want to preempt the current task. Just return..
3617 if (unlikely(ti->preempt_count || irqs_disabled()))
3621 add_preempt_count(PREEMPT_ACTIVE);
3623 * We keep the big kernel semaphore locked, but we
3624 * clear ->lock_depth so that schedule() doesnt
3625 * auto-release the semaphore:
3627 #ifdef CONFIG_PREEMPT_BKL
3628 saved_lock_depth = task->lock_depth;
3629 task->lock_depth = -1;
3632 #ifdef CONFIG_PREEMPT_BKL
3633 task->lock_depth = saved_lock_depth;
3635 sub_preempt_count(PREEMPT_ACTIVE);
3637 /* we could miss a preemption opportunity between schedule and now */
3639 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3642 EXPORT_SYMBOL(preempt_schedule);
3645 * this is the entry point to schedule() from kernel preemption
3646 * off of irq context.
3647 * Note, that this is called and return with irqs disabled. This will
3648 * protect us against recursive calling from irq.
3650 asmlinkage void __sched preempt_schedule_irq(void)
3652 struct thread_info *ti = current_thread_info();
3653 #ifdef CONFIG_PREEMPT_BKL
3654 struct task_struct *task = current;
3655 int saved_lock_depth;
3657 /* Catch callers which need to be fixed */
3658 BUG_ON(ti->preempt_count || !irqs_disabled());
3661 add_preempt_count(PREEMPT_ACTIVE);
3663 * We keep the big kernel semaphore locked, but we
3664 * clear ->lock_depth so that schedule() doesnt
3665 * auto-release the semaphore:
3667 #ifdef CONFIG_PREEMPT_BKL
3668 saved_lock_depth = task->lock_depth;
3669 task->lock_depth = -1;
3673 local_irq_disable();
3674 #ifdef CONFIG_PREEMPT_BKL
3675 task->lock_depth = saved_lock_depth;
3677 sub_preempt_count(PREEMPT_ACTIVE);
3679 /* we could miss a preemption opportunity between schedule and now */
3681 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3685 #endif /* CONFIG_PREEMPT */
3687 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
3690 return try_to_wake_up(curr->private, mode, sync);
3692 EXPORT_SYMBOL(default_wake_function);
3695 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3696 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3697 * number) then we wake all the non-exclusive tasks and one exclusive task.
3699 * There are circumstances in which we can try to wake a task which has already
3700 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3701 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3703 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3704 int nr_exclusive, int sync, void *key)
3706 struct list_head *tmp, *next;
3708 list_for_each_safe(tmp, next, &q->task_list) {
3709 wait_queue_t *curr = list_entry(tmp, wait_queue_t, task_list);
3710 unsigned flags = curr->flags;
3712 if (curr->func(curr, mode, sync, key) &&
3713 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
3719 * __wake_up - wake up threads blocked on a waitqueue.
3721 * @mode: which threads
3722 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3723 * @key: is directly passed to the wakeup function
3725 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3726 int nr_exclusive, void *key)
3728 unsigned long flags;
3730 spin_lock_irqsave(&q->lock, flags);
3731 __wake_up_common(q, mode, nr_exclusive, 0, key);
3732 spin_unlock_irqrestore(&q->lock, flags);
3734 EXPORT_SYMBOL(__wake_up);
3737 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3739 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3741 __wake_up_common(q, mode, 1, 0, NULL);
3745 * __wake_up_sync - wake up threads blocked on a waitqueue.
3747 * @mode: which threads
3748 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3750 * The sync wakeup differs that the waker knows that it will schedule
3751 * away soon, so while the target thread will be woken up, it will not
3752 * be migrated to another CPU - ie. the two threads are 'synchronized'
3753 * with each other. This can prevent needless bouncing between CPUs.
3755 * On UP it can prevent extra preemption.
3758 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3760 unsigned long flags;
3766 if (unlikely(!nr_exclusive))
3769 spin_lock_irqsave(&q->lock, flags);
3770 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3771 spin_unlock_irqrestore(&q->lock, flags);
3773 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3775 void fastcall complete(struct completion *x)
3777 unsigned long flags;
3779 spin_lock_irqsave(&x->wait.lock, flags);
3781 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3783 spin_unlock_irqrestore(&x->wait.lock, flags);
3785 EXPORT_SYMBOL(complete);
3787 void fastcall complete_all(struct completion *x)
3789 unsigned long flags;
3791 spin_lock_irqsave(&x->wait.lock, flags);
3792 x->done += UINT_MAX/2;
3793 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3795 spin_unlock_irqrestore(&x->wait.lock, flags);
3797 EXPORT_SYMBOL(complete_all);
3799 void fastcall __sched wait_for_completion(struct completion *x)
3803 spin_lock_irq(&x->wait.lock);
3805 DECLARE_WAITQUEUE(wait, current);
3807 wait.flags |= WQ_FLAG_EXCLUSIVE;
3808 __add_wait_queue_tail(&x->wait, &wait);
3810 __set_current_state(TASK_UNINTERRUPTIBLE);
3811 spin_unlock_irq(&x->wait.lock);
3813 spin_lock_irq(&x->wait.lock);
3815 __remove_wait_queue(&x->wait, &wait);
3818 spin_unlock_irq(&x->wait.lock);
3820 EXPORT_SYMBOL(wait_for_completion);
3822 unsigned long fastcall __sched
3823 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3827 spin_lock_irq(&x->wait.lock);
3829 DECLARE_WAITQUEUE(wait, current);
3831 wait.flags |= WQ_FLAG_EXCLUSIVE;
3832 __add_wait_queue_tail(&x->wait, &wait);
3834 __set_current_state(TASK_UNINTERRUPTIBLE);
3835 spin_unlock_irq(&x->wait.lock);
3836 timeout = schedule_timeout(timeout);
3837 spin_lock_irq(&x->wait.lock);
3839 __remove_wait_queue(&x->wait, &wait);
3843 __remove_wait_queue(&x->wait, &wait);
3847 spin_unlock_irq(&x->wait.lock);
3850 EXPORT_SYMBOL(wait_for_completion_timeout);
3852 int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3858 spin_lock_irq(&x->wait.lock);
3860 DECLARE_WAITQUEUE(wait, current);
3862 wait.flags |= WQ_FLAG_EXCLUSIVE;
3863 __add_wait_queue_tail(&x->wait, &wait);
3865 if (signal_pending(current)) {
3867 __remove_wait_queue(&x->wait, &wait);
3870 __set_current_state(TASK_INTERRUPTIBLE);
3871 spin_unlock_irq(&x->wait.lock);
3873 spin_lock_irq(&x->wait.lock);
3875 __remove_wait_queue(&x->wait, &wait);
3879 spin_unlock_irq(&x->wait.lock);
3883 EXPORT_SYMBOL(wait_for_completion_interruptible);
3885 unsigned long fastcall __sched
3886 wait_for_completion_interruptible_timeout(struct completion *x,
3887 unsigned long timeout)
3891 spin_lock_irq(&x->wait.lock);
3893 DECLARE_WAITQUEUE(wait, current);
3895 wait.flags |= WQ_FLAG_EXCLUSIVE;
3896 __add_wait_queue_tail(&x->wait, &wait);
3898 if (signal_pending(current)) {
3899 timeout = -ERESTARTSYS;
3900 __remove_wait_queue(&x->wait, &wait);
3903 __set_current_state(TASK_INTERRUPTIBLE);
3904 spin_unlock_irq(&x->wait.lock);
3905 timeout = schedule_timeout(timeout);
3906 spin_lock_irq(&x->wait.lock);
3908 __remove_wait_queue(&x->wait, &wait);
3912 __remove_wait_queue(&x->wait, &wait);
3916 spin_unlock_irq(&x->wait.lock);
3919 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3922 #define SLEEP_ON_VAR \
3923 unsigned long flags; \
3924 wait_queue_t wait; \
3925 init_waitqueue_entry(&wait, current);
3927 #define SLEEP_ON_HEAD \
3928 spin_lock_irqsave(&q->lock,flags); \
3929 __add_wait_queue(q, &wait); \
3930 spin_unlock(&q->lock);
3932 #define SLEEP_ON_TAIL \
3933 spin_lock_irq(&q->lock); \
3934 __remove_wait_queue(q, &wait); \
3935 spin_unlock_irqrestore(&q->lock, flags);
3937 #define SLEEP_ON_BKLCHECK \
3938 if (unlikely(!kernel_locked()) && \
3939 sleep_on_bkl_warnings < 10) { \
3940 sleep_on_bkl_warnings++; \
3944 static int sleep_on_bkl_warnings;
3946 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3952 current->state = TASK_INTERRUPTIBLE;
3958 EXPORT_SYMBOL(interruptible_sleep_on);
3960 long fastcall __sched
3961 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3967 current->state = TASK_INTERRUPTIBLE;
3970 timeout = schedule_timeout(timeout);
3975 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3977 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3983 current->state = TASK_UNINTERRUPTIBLE;
3986 timeout = schedule_timeout(timeout);
3992 EXPORT_SYMBOL(sleep_on_timeout);
3994 #ifdef CONFIG_RT_MUTEXES
3997 * rt_mutex_setprio - set the current priority of a task
3999 * @prio: prio value (kernel-internal form)
4001 * This function changes the 'effective' priority of a task. It does
4002 * not touch ->normal_prio like __setscheduler().
4004 * Used by the rt_mutex code to implement priority inheritance logic.
4006 void rt_mutex_setprio(struct task_struct *p, int prio)
4008 struct prio_array *array;
4009 unsigned long flags;
4013 BUG_ON(prio < 0 || prio > MAX_PRIO);
4015 rq = task_rq_lock(p, &flags);
4020 dequeue_task(p, array);
4025 * If changing to an RT priority then queue it
4026 * in the active array!
4030 enqueue_task(p, array);
4032 * Reschedule if we are currently running on this runqueue and
4033 * our priority decreased, or if we are not currently running on
4034 * this runqueue and our priority is higher than the current's
4036 if (task_running(rq, p)) {
4037 if (p->prio > oldprio)
4038 resched_task(rq->curr);
4039 } else if (TASK_PREEMPTS_CURR(p, rq))
4040 resched_task(rq->curr);
4042 task_rq_unlock(rq, &flags);
4047 void set_user_nice(struct task_struct *p, long nice)
4049 struct prio_array *array;
4050 int old_prio, delta;
4051 unsigned long flags;
4054 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4057 * We have to be careful, if called from sys_setpriority(),
4058 * the task might be in the middle of scheduling on another CPU.
4060 rq = task_rq_lock(p, &flags);
4062 * The RT priorities are set via sched_setscheduler(), but we still
4063 * allow the 'normal' nice value to be set - but as expected
4064 * it wont have any effect on scheduling until the task is
4065 * not SCHED_NORMAL/SCHED_BATCH:
4067 if (has_rt_policy(p)) {
4068 p->static_prio = NICE_TO_PRIO(nice);
4073 dequeue_task(p, array);
4074 dec_raw_weighted_load(rq, p);
4077 p->static_prio = NICE_TO_PRIO(nice);
4080 p->prio = effective_prio(p);
4081 delta = p->prio - old_prio;
4084 enqueue_task(p, array);
4085 inc_raw_weighted_load(rq, p);
4087 * If the task increased its priority or is running and
4088 * lowered its priority, then reschedule its CPU:
4090 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4091 resched_task(rq->curr);
4094 task_rq_unlock(rq, &flags);
4096 EXPORT_SYMBOL(set_user_nice);
4099 * can_nice - check if a task can reduce its nice value
4103 int can_nice(const struct task_struct *p, const int nice)
4105 /* convert nice value [19,-20] to rlimit style value [1,40] */
4106 int nice_rlim = 20 - nice;
4108 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
4109 capable(CAP_SYS_NICE));
4112 #ifdef __ARCH_WANT_SYS_NICE
4115 * sys_nice - change the priority of the current process.
4116 * @increment: priority increment
4118 * sys_setpriority is a more generic, but much slower function that
4119 * does similar things.
4121 asmlinkage long sys_nice(int increment)
4126 * Setpriority might change our priority at the same moment.
4127 * We don't have to worry. Conceptually one call occurs first
4128 * and we have a single winner.
4130 if (increment < -40)
4135 nice = PRIO_TO_NICE(current->static_prio) + increment;
4141 if (increment < 0 && !can_nice(current, nice))
4142 return vx_flags(VXF_IGNEG_NICE, 0) ? 0 : -EPERM;
4144 retval = security_task_setnice(current, nice);
4148 set_user_nice(current, nice);
4155 * task_prio - return the priority value of a given task.
4156 * @p: the task in question.
4158 * This is the priority value as seen by users in /proc.
4159 * RT tasks are offset by -200. Normal tasks are centered
4160 * around 0, value goes from -16 to +15.
4162 int task_prio(const struct task_struct *p)
4164 return p->prio - MAX_RT_PRIO;
4168 * task_nice - return the nice value of a given task.
4169 * @p: the task in question.
4171 int task_nice(const struct task_struct *p)
4173 return TASK_NICE(p);
4175 EXPORT_SYMBOL_GPL(task_nice);
4178 * idle_cpu - is a given cpu idle currently?
4179 * @cpu: the processor in question.
4181 int idle_cpu(int cpu)
4183 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
4187 * idle_task - return the idle task for a given cpu.
4188 * @cpu: the processor in question.
4190 struct task_struct *idle_task(int cpu)
4192 return cpu_rq(cpu)->idle;
4196 * find_process_by_pid - find a process with a matching PID value.
4197 * @pid: the pid in question.
4199 static inline struct task_struct *find_process_by_pid(pid_t pid)
4201 return pid ? find_task_by_pid(pid) : current;
4204 /* Actually do priority change: must hold rq lock. */
4205 static void __setscheduler(struct task_struct *p, int policy, int prio)
4210 p->rt_priority = prio;
4211 p->normal_prio = normal_prio(p);
4212 /* we are holding p->pi_lock already */
4213 p->prio = rt_mutex_getprio(p);
4215 * SCHED_BATCH tasks are treated as perpetual CPU hogs:
4217 if (policy == SCHED_BATCH)
4223 * sched_setscheduler - change the scheduling policy and/or RT priority of
4225 * @p: the task in question.
4226 * @policy: new policy.
4227 * @param: structure containing the new RT priority.
4229 int sched_setscheduler(struct task_struct *p, int policy,
4230 struct sched_param *param)
4232 int retval, oldprio, oldpolicy = -1;
4233 struct prio_array *array;
4234 unsigned long flags;
4237 /* may grab non-irq protected spin_locks */
4238 BUG_ON(in_interrupt());
4240 /* double check policy once rq lock held */
4242 policy = oldpolicy = p->policy;
4243 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
4244 policy != SCHED_NORMAL && policy != SCHED_BATCH)
4247 * Valid priorities for SCHED_FIFO and SCHED_RR are
4248 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL and
4251 if (param->sched_priority < 0 ||
4252 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
4253 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
4255 if ((policy == SCHED_NORMAL || policy == SCHED_BATCH)
4256 != (param->sched_priority == 0))
4260 * Allow unprivileged RT tasks to decrease priority:
4262 if (!capable(CAP_SYS_NICE)) {
4264 * can't change policy, except between SCHED_NORMAL
4267 if (((policy != SCHED_NORMAL && p->policy != SCHED_BATCH) &&
4268 (policy != SCHED_BATCH && p->policy != SCHED_NORMAL)) &&
4269 !p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
4271 /* can't increase priority */
4272 if ((policy != SCHED_NORMAL && policy != SCHED_BATCH) &&
4273 param->sched_priority > p->rt_priority &&
4274 param->sched_priority >
4275 p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
4277 /* can't change other user's priorities */
4278 if ((current->euid != p->euid) &&
4279 (current->euid != p->uid))
4283 retval = security_task_setscheduler(p, policy, param);
4287 * make sure no PI-waiters arrive (or leave) while we are
4288 * changing the priority of the task:
4290 spin_lock_irqsave(&p->pi_lock, flags);
4292 * To be able to change p->policy safely, the apropriate
4293 * runqueue lock must be held.
4295 rq = __task_rq_lock(p);
4296 /* recheck policy now with rq lock held */
4297 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4298 policy = oldpolicy = -1;
4299 __task_rq_unlock(rq);
4300 spin_unlock_irqrestore(&p->pi_lock, flags);
4305 deactivate_task(p, rq);
4307 __setscheduler(p, policy, param->sched_priority);
4309 vx_activate_task(p);
4310 __activate_task(p, rq);
4312 * Reschedule if we are currently running on this runqueue and
4313 * our priority decreased, or if we are not currently running on
4314 * this runqueue and our priority is higher than the current's
4316 if (task_running(rq, p)) {
4317 if (p->prio > oldprio)
4318 resched_task(rq->curr);
4319 } else if (TASK_PREEMPTS_CURR(p, rq))
4320 resched_task(rq->curr);
4322 __task_rq_unlock(rq);
4323 spin_unlock_irqrestore(&p->pi_lock, flags);
4325 rt_mutex_adjust_pi(p);
4329 EXPORT_SYMBOL_GPL(sched_setscheduler);
4332 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4334 struct sched_param lparam;
4335 struct task_struct *p;
4338 if (!param || pid < 0)
4340 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4342 read_lock_irq(&tasklist_lock);
4343 p = find_process_by_pid(pid);
4345 read_unlock_irq(&tasklist_lock);
4348 retval = sched_setscheduler(p, policy, &lparam);
4349 read_unlock_irq(&tasklist_lock);
4355 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4356 * @pid: the pid in question.
4357 * @policy: new policy.
4358 * @param: structure containing the new RT priority.
4360 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
4361 struct sched_param __user *param)
4363 /* negative values for policy are not valid */
4367 return do_sched_setscheduler(pid, policy, param);
4371 * sys_sched_setparam - set/change the RT priority of a thread
4372 * @pid: the pid in question.
4373 * @param: structure containing the new RT priority.
4375 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
4377 return do_sched_setscheduler(pid, -1, param);
4381 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4382 * @pid: the pid in question.
4384 asmlinkage long sys_sched_getscheduler(pid_t pid)
4386 struct task_struct *p;
4387 int retval = -EINVAL;
4393 read_lock(&tasklist_lock);
4394 p = find_process_by_pid(pid);
4396 retval = security_task_getscheduler(p);
4400 read_unlock(&tasklist_lock);
4407 * sys_sched_getscheduler - get the RT priority of a thread
4408 * @pid: the pid in question.
4409 * @param: structure containing the RT priority.
4411 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
4413 struct sched_param lp;
4414 struct task_struct *p;
4415 int retval = -EINVAL;
4417 if (!param || pid < 0)
4420 read_lock(&tasklist_lock);
4421 p = find_process_by_pid(pid);
4426 retval = security_task_getscheduler(p);
4430 lp.sched_priority = p->rt_priority;
4431 read_unlock(&tasklist_lock);
4434 * This one might sleep, we cannot do it with a spinlock held ...
4436 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4442 read_unlock(&tasklist_lock);
4446 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
4448 cpumask_t cpus_allowed;
4449 struct task_struct *p;
4453 read_lock(&tasklist_lock);
4455 p = find_process_by_pid(pid);
4457 read_unlock(&tasklist_lock);
4458 unlock_cpu_hotplug();
4463 * It is not safe to call set_cpus_allowed with the
4464 * tasklist_lock held. We will bump the task_struct's
4465 * usage count and then drop tasklist_lock.
4468 read_unlock(&tasklist_lock);
4471 if ((current->euid != p->euid) && (current->euid != p->uid) &&
4472 !capable(CAP_SYS_NICE))
4475 retval = security_task_setscheduler(p, 0, NULL);
4479 cpus_allowed = cpuset_cpus_allowed(p);
4480 cpus_and(new_mask, new_mask, cpus_allowed);
4481 retval = set_cpus_allowed(p, new_mask);
4485 unlock_cpu_hotplug();
4489 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4490 cpumask_t *new_mask)
4492 if (len < sizeof(cpumask_t)) {
4493 memset(new_mask, 0, sizeof(cpumask_t));
4494 } else if (len > sizeof(cpumask_t)) {
4495 len = sizeof(cpumask_t);
4497 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4501 * sys_sched_setaffinity - set the cpu affinity of a process
4502 * @pid: pid of the process
4503 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4504 * @user_mask_ptr: user-space pointer to the new cpu mask
4506 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
4507 unsigned long __user *user_mask_ptr)
4512 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
4516 return sched_setaffinity(pid, new_mask);
4520 * Represents all cpu's present in the system
4521 * In systems capable of hotplug, this map could dynamically grow
4522 * as new cpu's are detected in the system via any platform specific
4523 * method, such as ACPI for e.g.
4526 cpumask_t cpu_present_map __read_mostly;
4527 EXPORT_SYMBOL(cpu_present_map);
4530 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
4531 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
4534 long sched_getaffinity(pid_t pid, cpumask_t *mask)
4536 struct task_struct *p;
4540 read_lock(&tasklist_lock);
4543 p = find_process_by_pid(pid);
4547 retval = security_task_getscheduler(p);
4551 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
4554 read_unlock(&tasklist_lock);
4555 unlock_cpu_hotplug();
4563 * sys_sched_getaffinity - get the cpu affinity of a process
4564 * @pid: pid of the process
4565 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4566 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4568 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
4569 unsigned long __user *user_mask_ptr)
4574 if (len < sizeof(cpumask_t))
4577 ret = sched_getaffinity(pid, &mask);
4581 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
4584 return sizeof(cpumask_t);
4588 * sys_sched_yield - yield the current processor to other threads.
4590 * this function yields the current CPU by moving the calling thread
4591 * to the expired array. If there are no other threads running on this
4592 * CPU then this function will return.
4594 asmlinkage long sys_sched_yield(void)
4596 struct rq *rq = this_rq_lock();
4597 struct prio_array *array = current->array, *target = rq->expired;
4599 schedstat_inc(rq, yld_cnt);
4601 * We implement yielding by moving the task into the expired
4604 * (special rule: RT tasks will just roundrobin in the active
4607 if (rt_task(current))
4608 target = rq->active;
4610 if (array->nr_active == 1) {
4611 schedstat_inc(rq, yld_act_empty);
4612 if (!rq->expired->nr_active)
4613 schedstat_inc(rq, yld_both_empty);
4614 } else if (!rq->expired->nr_active)
4615 schedstat_inc(rq, yld_exp_empty);
4617 if (array != target) {
4618 dequeue_task(current, array);
4619 enqueue_task(current, target);
4622 * requeue_task is cheaper so perform that if possible.
4624 requeue_task(current, array);
4627 * Since we are going to call schedule() anyway, there's
4628 * no need to preempt or enable interrupts:
4630 __release(rq->lock);
4631 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
4632 _raw_spin_unlock(&rq->lock);
4633 preempt_enable_no_resched();
4640 static inline int __resched_legal(int expected_preempt_count)
4642 if (unlikely(preempt_count() != expected_preempt_count))
4644 if (unlikely(system_state != SYSTEM_RUNNING))
4649 static void __cond_resched(void)
4651 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4652 __might_sleep(__FILE__, __LINE__);
4655 * The BKS might be reacquired before we have dropped
4656 * PREEMPT_ACTIVE, which could trigger a second
4657 * cond_resched() call.
4660 add_preempt_count(PREEMPT_ACTIVE);
4662 sub_preempt_count(PREEMPT_ACTIVE);
4663 } while (need_resched());
4666 int __sched cond_resched(void)
4668 if (need_resched() && __resched_legal(0)) {
4674 EXPORT_SYMBOL(cond_resched);
4677 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4678 * call schedule, and on return reacquire the lock.
4680 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4681 * operations here to prevent schedule() from being called twice (once via
4682 * spin_unlock(), once by hand).
4684 int cond_resched_lock(spinlock_t *lock)
4688 if (need_lockbreak(lock)) {
4694 if (need_resched() && __resched_legal(1)) {
4695 spin_release(&lock->dep_map, 1, _THIS_IP_);
4696 _raw_spin_unlock(lock);
4697 preempt_enable_no_resched();
4704 EXPORT_SYMBOL(cond_resched_lock);
4706 int __sched cond_resched_softirq(void)
4708 BUG_ON(!in_softirq());
4710 if (need_resched() && __resched_legal(0)) {
4711 raw_local_irq_disable();
4713 raw_local_irq_enable();
4720 EXPORT_SYMBOL(cond_resched_softirq);
4723 * yield - yield the current processor to other threads.
4725 * this is a shortcut for kernel-space yielding - it marks the
4726 * thread runnable and calls sys_sched_yield().
4728 void __sched yield(void)
4730 set_current_state(TASK_RUNNING);
4733 EXPORT_SYMBOL(yield);
4736 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4737 * that process accounting knows that this is a task in IO wait state.
4739 * But don't do that if it is a deliberate, throttling IO wait (this task
4740 * has set its backing_dev_info: the queue against which it should throttle)
4742 void __sched io_schedule(void)
4744 struct rq *rq = &__raw_get_cpu_var(runqueues);
4746 delayacct_blkio_start();
4747 atomic_inc(&rq->nr_iowait);
4749 atomic_dec(&rq->nr_iowait);
4750 delayacct_blkio_end();
4752 EXPORT_SYMBOL(io_schedule);
4754 long __sched io_schedule_timeout(long timeout)
4756 struct rq *rq = &__raw_get_cpu_var(runqueues);
4759 delayacct_blkio_start();
4760 atomic_inc(&rq->nr_iowait);
4761 ret = schedule_timeout(timeout);
4762 atomic_dec(&rq->nr_iowait);
4763 delayacct_blkio_end();
4768 * sys_sched_get_priority_max - return maximum RT priority.
4769 * @policy: scheduling class.
4771 * this syscall returns the maximum rt_priority that can be used
4772 * by a given scheduling class.
4774 asmlinkage long sys_sched_get_priority_max(int policy)
4781 ret = MAX_USER_RT_PRIO-1;
4792 * sys_sched_get_priority_min - return minimum RT priority.
4793 * @policy: scheduling class.
4795 * this syscall returns the minimum rt_priority that can be used
4796 * by a given scheduling class.
4798 asmlinkage long sys_sched_get_priority_min(int policy)
4815 * sys_sched_rr_get_interval - return the default timeslice of a process.
4816 * @pid: pid of the process.
4817 * @interval: userspace pointer to the timeslice value.
4819 * this syscall writes the default timeslice value of a given process
4820 * into the user-space timespec buffer. A value of '0' means infinity.
4823 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4825 struct task_struct *p;
4826 int retval = -EINVAL;
4833 read_lock(&tasklist_lock);
4834 p = find_process_by_pid(pid);
4838 retval = security_task_getscheduler(p);
4842 jiffies_to_timespec(p->policy == SCHED_FIFO ?
4843 0 : task_timeslice(p), &t);
4844 read_unlock(&tasklist_lock);
4845 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4849 read_unlock(&tasklist_lock);
4853 static inline struct task_struct *eldest_child(struct task_struct *p)
4855 if (list_empty(&p->children))
4857 return list_entry(p->children.next,struct task_struct,sibling);
4860 static inline struct task_struct *older_sibling(struct task_struct *p)
4862 if (p->sibling.prev==&p->parent->children)
4864 return list_entry(p->sibling.prev,struct task_struct,sibling);
4867 static inline struct task_struct *younger_sibling(struct task_struct *p)
4869 if (p->sibling.next==&p->parent->children)
4871 return list_entry(p->sibling.next,struct task_struct,sibling);
4874 static const char stat_nam[] = "RSDTtZX";
4876 static void show_task(struct task_struct *p)
4878 struct task_struct *relative;
4879 unsigned long free = 0;
4882 state = p->state ? __ffs(p->state) + 1 : 0;
4883 printk("%-13.13s %c", p->comm,
4884 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
4885 #if (BITS_PER_LONG == 32)
4886 if (state == TASK_RUNNING)
4887 printk(" running ");
4889 printk(" %08lX ", thread_saved_pc(p));
4891 if (state == TASK_RUNNING)
4892 printk(" running task ");
4894 printk(" %016lx ", thread_saved_pc(p));
4896 #ifdef CONFIG_DEBUG_STACK_USAGE
4898 unsigned long *n = end_of_stack(p);
4901 free = (unsigned long)n - (unsigned long)end_of_stack(p);
4904 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
4905 if ((relative = eldest_child(p)))
4906 printk("%5d ", relative->pid);
4909 if ((relative = younger_sibling(p)))
4910 printk("%7d", relative->pid);
4913 if ((relative = older_sibling(p)))
4914 printk(" %5d", relative->pid);
4918 printk(" (L-TLB)\n");
4920 printk(" (NOTLB)\n");
4922 if (state != TASK_RUNNING)
4923 show_stack(p, NULL);
4926 void show_state(void)
4928 struct task_struct *g, *p;
4930 #if (BITS_PER_LONG == 32)
4933 printk(" task PC pid father child younger older\n");
4937 printk(" task PC pid father child younger older\n");
4939 read_lock(&tasklist_lock);
4940 do_each_thread(g, p) {
4942 * reset the NMI-timeout, listing all files on a slow
4943 * console might take alot of time:
4945 touch_nmi_watchdog();
4947 } while_each_thread(g, p);
4949 read_unlock(&tasklist_lock);
4950 debug_show_all_locks();
4954 * init_idle - set up an idle thread for a given CPU
4955 * @idle: task in question
4956 * @cpu: cpu the idle task belongs to
4958 * NOTE: this function does not set the idle thread's NEED_RESCHED
4959 * flag, to make booting more robust.
4961 void __devinit init_idle(struct task_struct *idle, int cpu)
4963 struct rq *rq = cpu_rq(cpu);
4964 unsigned long flags;
4966 idle->timestamp = sched_clock();
4967 idle->sleep_avg = 0;
4969 idle->prio = idle->normal_prio = MAX_PRIO;
4970 idle->state = TASK_RUNNING;
4971 idle->cpus_allowed = cpumask_of_cpu(cpu);
4972 set_task_cpu(idle, cpu);
4974 spin_lock_irqsave(&rq->lock, flags);
4975 rq->curr = rq->idle = idle;
4976 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
4979 spin_unlock_irqrestore(&rq->lock, flags);
4981 /* Set the preempt count _outside_ the spinlocks! */
4982 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4983 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
4985 task_thread_info(idle)->preempt_count = 0;
4990 * In a system that switches off the HZ timer nohz_cpu_mask
4991 * indicates which cpus entered this state. This is used
4992 * in the rcu update to wait only for active cpus. For system
4993 * which do not switch off the HZ timer nohz_cpu_mask should
4994 * always be CPU_MASK_NONE.
4996 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
5000 * This is how migration works:
5002 * 1) we queue a struct migration_req structure in the source CPU's
5003 * runqueue and wake up that CPU's migration thread.
5004 * 2) we down() the locked semaphore => thread blocks.
5005 * 3) migration thread wakes up (implicitly it forces the migrated
5006 * thread off the CPU)
5007 * 4) it gets the migration request and checks whether the migrated
5008 * task is still in the wrong runqueue.
5009 * 5) if it's in the wrong runqueue then the migration thread removes
5010 * it and puts it into the right queue.
5011 * 6) migration thread up()s the semaphore.
5012 * 7) we wake up and the migration is done.
5016 * Change a given task's CPU affinity. Migrate the thread to a
5017 * proper CPU and schedule it away if the CPU it's executing on
5018 * is removed from the allowed bitmask.
5020 * NOTE: the caller must have a valid reference to the task, the
5021 * task must not exit() & deallocate itself prematurely. The
5022 * call is not atomic; no spinlocks may be held.
5024 int set_cpus_allowed(struct task_struct *p, cpumask_t new_mask)
5026 struct migration_req req;
5027 unsigned long flags;
5031 rq = task_rq_lock(p, &flags);
5032 if (!cpus_intersects(new_mask, cpu_online_map)) {
5037 p->cpus_allowed = new_mask;
5038 /* Can the task run on the task's current CPU? If so, we're done */
5039 if (cpu_isset(task_cpu(p), new_mask))
5042 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
5043 /* Need help from migration thread: drop lock and wait. */
5044 task_rq_unlock(rq, &flags);
5045 wake_up_process(rq->migration_thread);
5046 wait_for_completion(&req.done);
5047 tlb_migrate_finish(p->mm);
5051 task_rq_unlock(rq, &flags);
5055 EXPORT_SYMBOL_GPL(set_cpus_allowed);
5058 * Move (not current) task off this cpu, onto dest cpu. We're doing
5059 * this because either it can't run here any more (set_cpus_allowed()
5060 * away from this CPU, or CPU going down), or because we're
5061 * attempting to rebalance this task on exec (sched_exec).
5063 * So we race with normal scheduler movements, but that's OK, as long
5064 * as the task is no longer on this CPU.
5066 * Returns non-zero if task was successfully migrated.
5068 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
5070 struct rq *rq_dest, *rq_src;
5073 if (unlikely(cpu_is_offline(dest_cpu)))
5076 rq_src = cpu_rq(src_cpu);
5077 rq_dest = cpu_rq(dest_cpu);
5079 double_rq_lock(rq_src, rq_dest);
5080 /* Already moved. */
5081 if (task_cpu(p) != src_cpu)
5083 /* Affinity changed (again). */
5084 if (!cpu_isset(dest_cpu, p->cpus_allowed))
5087 set_task_cpu(p, dest_cpu);
5090 * Sync timestamp with rq_dest's before activating.
5091 * The same thing could be achieved by doing this step
5092 * afterwards, and pretending it was a local activate.
5093 * This way is cleaner and logically correct.
5095 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
5096 + rq_dest->timestamp_last_tick;
5097 deactivate_task(p, rq_src);
5098 vx_activate_task(p);
5099 __activate_task(p, rq_dest);
5100 if (TASK_PREEMPTS_CURR(p, rq_dest))
5101 resched_task(rq_dest->curr);
5105 double_rq_unlock(rq_src, rq_dest);
5110 * migration_thread - this is a highprio system thread that performs
5111 * thread migration by bumping thread off CPU then 'pushing' onto
5114 static int migration_thread(void *data)
5116 int cpu = (long)data;
5120 BUG_ON(rq->migration_thread != current);
5122 set_current_state(TASK_INTERRUPTIBLE);
5123 while (!kthread_should_stop()) {
5124 struct migration_req *req;
5125 struct list_head *head;
5129 spin_lock_irq(&rq->lock);
5131 if (cpu_is_offline(cpu)) {
5132 spin_unlock_irq(&rq->lock);
5136 if (rq->active_balance) {
5137 active_load_balance(rq, cpu);
5138 rq->active_balance = 0;
5141 head = &rq->migration_queue;
5143 if (list_empty(head)) {
5144 spin_unlock_irq(&rq->lock);
5146 set_current_state(TASK_INTERRUPTIBLE);
5149 req = list_entry(head->next, struct migration_req, list);
5150 list_del_init(head->next);
5152 spin_unlock(&rq->lock);
5153 __migrate_task(req->task, cpu, req->dest_cpu);
5156 complete(&req->done);
5158 __set_current_state(TASK_RUNNING);
5162 /* Wait for kthread_stop */
5163 set_current_state(TASK_INTERRUPTIBLE);
5164 while (!kthread_should_stop()) {
5166 set_current_state(TASK_INTERRUPTIBLE);
5168 __set_current_state(TASK_RUNNING);
5172 #ifdef CONFIG_HOTPLUG_CPU
5173 /* Figure out where task on dead CPU should go, use force if neccessary. */
5174 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
5176 unsigned long flags;
5183 mask = node_to_cpumask(cpu_to_node(dead_cpu));
5184 cpus_and(mask, mask, p->cpus_allowed);
5185 dest_cpu = any_online_cpu(mask);
5187 /* On any allowed CPU? */
5188 if (dest_cpu == NR_CPUS)
5189 dest_cpu = any_online_cpu(p->cpus_allowed);
5191 /* No more Mr. Nice Guy. */
5192 if (dest_cpu == NR_CPUS) {
5193 rq = task_rq_lock(p, &flags);
5194 cpus_setall(p->cpus_allowed);
5195 dest_cpu = any_online_cpu(p->cpus_allowed);
5196 task_rq_unlock(rq, &flags);
5199 * Don't tell them about moving exiting tasks or
5200 * kernel threads (both mm NULL), since they never
5203 if (p->mm && printk_ratelimit())
5204 printk(KERN_INFO "process %d (%s) no "
5205 "longer affine to cpu%d\n",
5206 p->pid, p->comm, dead_cpu);
5208 if (!__migrate_task(p, dead_cpu, dest_cpu))
5213 * While a dead CPU has no uninterruptible tasks queued at this point,
5214 * it might still have a nonzero ->nr_uninterruptible counter, because
5215 * for performance reasons the counter is not stricly tracking tasks to
5216 * their home CPUs. So we just add the counter to another CPU's counter,
5217 * to keep the global sum constant after CPU-down:
5219 static void migrate_nr_uninterruptible(struct rq *rq_src)
5221 struct rq *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
5222 unsigned long flags;
5224 local_irq_save(flags);
5225 double_rq_lock(rq_src, rq_dest);
5226 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5227 rq_src->nr_uninterruptible = 0;
5228 double_rq_unlock(rq_src, rq_dest);
5229 local_irq_restore(flags);
5232 /* Run through task list and migrate tasks from the dead cpu. */
5233 static void migrate_live_tasks(int src_cpu)
5235 struct task_struct *p, *t;
5237 write_lock_irq(&tasklist_lock);
5239 do_each_thread(t, p) {
5243 if (task_cpu(p) == src_cpu)
5244 move_task_off_dead_cpu(src_cpu, p);
5245 } while_each_thread(t, p);
5247 write_unlock_irq(&tasklist_lock);
5250 /* Schedules idle task to be the next runnable task on current CPU.
5251 * It does so by boosting its priority to highest possible and adding it to
5252 * the _front_ of the runqueue. Used by CPU offline code.
5254 void sched_idle_next(void)
5256 int this_cpu = smp_processor_id();
5257 struct rq *rq = cpu_rq(this_cpu);
5258 struct task_struct *p = rq->idle;
5259 unsigned long flags;
5261 /* cpu has to be offline */
5262 BUG_ON(cpu_online(this_cpu));
5265 * Strictly not necessary since rest of the CPUs are stopped by now
5266 * and interrupts disabled on the current cpu.
5268 spin_lock_irqsave(&rq->lock, flags);
5270 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
5272 /* Add idle task to the _front_ of its priority queue: */
5273 __activate_idle_task(p, rq);
5275 spin_unlock_irqrestore(&rq->lock, flags);
5279 * Ensures that the idle task is using init_mm right before its cpu goes
5282 void idle_task_exit(void)
5284 struct mm_struct *mm = current->active_mm;
5286 BUG_ON(cpu_online(smp_processor_id()));
5289 switch_mm(mm, &init_mm, current);
5293 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
5295 struct rq *rq = cpu_rq(dead_cpu);
5297 /* Must be exiting, otherwise would be on tasklist. */
5298 BUG_ON(p->exit_state != EXIT_ZOMBIE && p->exit_state != EXIT_DEAD);
5300 /* Cannot have done final schedule yet: would have vanished. */
5301 BUG_ON(p->flags & PF_DEAD);
5306 * Drop lock around migration; if someone else moves it,
5307 * that's OK. No task can be added to this CPU, so iteration is
5310 spin_unlock_irq(&rq->lock);
5311 move_task_off_dead_cpu(dead_cpu, p);
5312 spin_lock_irq(&rq->lock);
5317 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5318 static void migrate_dead_tasks(unsigned int dead_cpu)
5320 struct rq *rq = cpu_rq(dead_cpu);
5321 unsigned int arr, i;
5323 for (arr = 0; arr < 2; arr++) {
5324 for (i = 0; i < MAX_PRIO; i++) {
5325 struct list_head *list = &rq->arrays[arr].queue[i];
5327 while (!list_empty(list))
5328 migrate_dead(dead_cpu, list_entry(list->next,
5329 struct task_struct, run_list));
5333 #endif /* CONFIG_HOTPLUG_CPU */
5336 * migration_call - callback that gets triggered when a CPU is added.
5337 * Here we can start up the necessary migration thread for the new CPU.
5339 static int __cpuinit
5340 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
5342 struct task_struct *p;
5343 int cpu = (long)hcpu;
5344 unsigned long flags;
5348 case CPU_UP_PREPARE:
5349 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
5352 p->flags |= PF_NOFREEZE;
5353 kthread_bind(p, cpu);
5354 /* Must be high prio: stop_machine expects to yield to it. */
5355 rq = task_rq_lock(p, &flags);
5356 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
5357 task_rq_unlock(rq, &flags);
5358 cpu_rq(cpu)->migration_thread = p;
5362 /* Strictly unneccessary, as first user will wake it. */
5363 wake_up_process(cpu_rq(cpu)->migration_thread);
5366 #ifdef CONFIG_HOTPLUG_CPU
5367 case CPU_UP_CANCELED:
5368 if (!cpu_rq(cpu)->migration_thread)
5370 /* Unbind it from offline cpu so it can run. Fall thru. */
5371 kthread_bind(cpu_rq(cpu)->migration_thread,
5372 any_online_cpu(cpu_online_map));
5373 kthread_stop(cpu_rq(cpu)->migration_thread);
5374 cpu_rq(cpu)->migration_thread = NULL;
5378 migrate_live_tasks(cpu);
5380 kthread_stop(rq->migration_thread);
5381 rq->migration_thread = NULL;
5382 /* Idle task back to normal (off runqueue, low prio) */
5383 rq = task_rq_lock(rq->idle, &flags);
5384 deactivate_task(rq->idle, rq);
5385 rq->idle->static_prio = MAX_PRIO;
5386 __setscheduler(rq->idle, SCHED_NORMAL, 0);
5387 migrate_dead_tasks(cpu);
5388 task_rq_unlock(rq, &flags);
5389 migrate_nr_uninterruptible(rq);
5390 BUG_ON(rq->nr_running != 0);
5392 /* No need to migrate the tasks: it was best-effort if
5393 * they didn't do lock_cpu_hotplug(). Just wake up
5394 * the requestors. */
5395 spin_lock_irq(&rq->lock);
5396 while (!list_empty(&rq->migration_queue)) {
5397 struct migration_req *req;
5399 req = list_entry(rq->migration_queue.next,
5400 struct migration_req, list);
5401 list_del_init(&req->list);
5402 complete(&req->done);
5404 spin_unlock_irq(&rq->lock);
5411 /* Register at highest priority so that task migration (migrate_all_tasks)
5412 * happens before everything else.
5414 static struct notifier_block __cpuinitdata migration_notifier = {
5415 .notifier_call = migration_call,
5419 int __init migration_init(void)
5421 void *cpu = (void *)(long)smp_processor_id();
5423 /* Start one for the boot CPU: */
5424 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5425 migration_call(&migration_notifier, CPU_ONLINE, cpu);
5426 register_cpu_notifier(&migration_notifier);
5433 #undef SCHED_DOMAIN_DEBUG
5434 #ifdef SCHED_DOMAIN_DEBUG
5435 static void sched_domain_debug(struct sched_domain *sd, int cpu)
5440 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5444 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5449 struct sched_group *group = sd->groups;
5450 cpumask_t groupmask;
5452 cpumask_scnprintf(str, NR_CPUS, sd->span);
5453 cpus_clear(groupmask);
5456 for (i = 0; i < level + 1; i++)
5458 printk("domain %d: ", level);
5460 if (!(sd->flags & SD_LOAD_BALANCE)) {
5461 printk("does not load-balance\n");
5463 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
5467 printk("span %s\n", str);
5469 if (!cpu_isset(cpu, sd->span))
5470 printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
5471 if (!cpu_isset(cpu, group->cpumask))
5472 printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
5475 for (i = 0; i < level + 2; i++)
5481 printk(KERN_ERR "ERROR: group is NULL\n");
5485 if (!group->cpu_power) {
5487 printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
5490 if (!cpus_weight(group->cpumask)) {
5492 printk(KERN_ERR "ERROR: empty group\n");
5495 if (cpus_intersects(groupmask, group->cpumask)) {
5497 printk(KERN_ERR "ERROR: repeated CPUs\n");
5500 cpus_or(groupmask, groupmask, group->cpumask);
5502 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
5505 group = group->next;
5506 } while (group != sd->groups);
5509 if (!cpus_equal(sd->span, groupmask))
5510 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
5516 if (!cpus_subset(groupmask, sd->span))
5517 printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
5523 # define sched_domain_debug(sd, cpu) do { } while (0)
5526 static int sd_degenerate(struct sched_domain *sd)
5528 if (cpus_weight(sd->span) == 1)
5531 /* Following flags need at least 2 groups */
5532 if (sd->flags & (SD_LOAD_BALANCE |
5533 SD_BALANCE_NEWIDLE |
5536 if (sd->groups != sd->groups->next)
5540 /* Following flags don't use groups */
5541 if (sd->flags & (SD_WAKE_IDLE |
5550 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
5552 unsigned long cflags = sd->flags, pflags = parent->flags;
5554 if (sd_degenerate(parent))
5557 if (!cpus_equal(sd->span, parent->span))
5560 /* Does parent contain flags not in child? */
5561 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
5562 if (cflags & SD_WAKE_AFFINE)
5563 pflags &= ~SD_WAKE_BALANCE;
5564 /* Flags needing groups don't count if only 1 group in parent */
5565 if (parent->groups == parent->groups->next) {
5566 pflags &= ~(SD_LOAD_BALANCE |
5567 SD_BALANCE_NEWIDLE |
5571 if (~cflags & pflags)
5578 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
5579 * hold the hotplug lock.
5581 static void cpu_attach_domain(struct sched_domain *sd, int cpu)
5583 struct rq *rq = cpu_rq(cpu);
5584 struct sched_domain *tmp;
5586 /* Remove the sched domains which do not contribute to scheduling. */
5587 for (tmp = sd; tmp; tmp = tmp->parent) {
5588 struct sched_domain *parent = tmp->parent;
5591 if (sd_parent_degenerate(tmp, parent))
5592 tmp->parent = parent->parent;
5595 if (sd && sd_degenerate(sd))
5598 sched_domain_debug(sd, cpu);
5600 rcu_assign_pointer(rq->sd, sd);
5603 /* cpus with isolated domains */
5604 static cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
5606 /* Setup the mask of cpus configured for isolated domains */
5607 static int __init isolated_cpu_setup(char *str)
5609 int ints[NR_CPUS], i;
5611 str = get_options(str, ARRAY_SIZE(ints), ints);
5612 cpus_clear(cpu_isolated_map);
5613 for (i = 1; i <= ints[0]; i++)
5614 if (ints[i] < NR_CPUS)
5615 cpu_set(ints[i], cpu_isolated_map);
5619 __setup ("isolcpus=", isolated_cpu_setup);
5622 * init_sched_build_groups takes an array of groups, the cpumask we wish
5623 * to span, and a pointer to a function which identifies what group a CPU
5624 * belongs to. The return value of group_fn must be a valid index into the
5625 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
5626 * keep track of groups covered with a cpumask_t).
5628 * init_sched_build_groups will build a circular linked list of the groups
5629 * covered by the given span, and will set each group's ->cpumask correctly,
5630 * and ->cpu_power to 0.
5632 static void init_sched_build_groups(struct sched_group groups[], cpumask_t span,
5633 int (*group_fn)(int cpu))
5635 struct sched_group *first = NULL, *last = NULL;
5636 cpumask_t covered = CPU_MASK_NONE;
5639 for_each_cpu_mask(i, span) {
5640 int group = group_fn(i);
5641 struct sched_group *sg = &groups[group];
5644 if (cpu_isset(i, covered))
5647 sg->cpumask = CPU_MASK_NONE;
5650 for_each_cpu_mask(j, span) {
5651 if (group_fn(j) != group)
5654 cpu_set(j, covered);
5655 cpu_set(j, sg->cpumask);
5666 #define SD_NODES_PER_DOMAIN 16
5669 * Self-tuning task migration cost measurement between source and target CPUs.
5671 * This is done by measuring the cost of manipulating buffers of varying
5672 * sizes. For a given buffer-size here are the steps that are taken:
5674 * 1) the source CPU reads+dirties a shared buffer
5675 * 2) the target CPU reads+dirties the same shared buffer
5677 * We measure how long they take, in the following 4 scenarios:
5679 * - source: CPU1, target: CPU2 | cost1
5680 * - source: CPU2, target: CPU1 | cost2
5681 * - source: CPU1, target: CPU1 | cost3
5682 * - source: CPU2, target: CPU2 | cost4
5684 * We then calculate the cost3+cost4-cost1-cost2 difference - this is
5685 * the cost of migration.
5687 * We then start off from a small buffer-size and iterate up to larger
5688 * buffer sizes, in 5% steps - measuring each buffer-size separately, and
5689 * doing a maximum search for the cost. (The maximum cost for a migration
5690 * normally occurs when the working set size is around the effective cache
5693 #define SEARCH_SCOPE 2
5694 #define MIN_CACHE_SIZE (64*1024U)
5695 #define DEFAULT_CACHE_SIZE (5*1024*1024U)
5696 #define ITERATIONS 1
5697 #define SIZE_THRESH 130
5698 #define COST_THRESH 130
5701 * The migration cost is a function of 'domain distance'. Domain
5702 * distance is the number of steps a CPU has to iterate down its
5703 * domain tree to share a domain with the other CPU. The farther
5704 * two CPUs are from each other, the larger the distance gets.
5706 * Note that we use the distance only to cache measurement results,
5707 * the distance value is not used numerically otherwise. When two
5708 * CPUs have the same distance it is assumed that the migration
5709 * cost is the same. (this is a simplification but quite practical)
5711 #define MAX_DOMAIN_DISTANCE 32
5713 static unsigned long long migration_cost[MAX_DOMAIN_DISTANCE] =
5714 { [ 0 ... MAX_DOMAIN_DISTANCE-1 ] =
5716 * Architectures may override the migration cost and thus avoid
5717 * boot-time calibration. Unit is nanoseconds. Mostly useful for
5718 * virtualized hardware:
5720 #ifdef CONFIG_DEFAULT_MIGRATION_COST
5721 CONFIG_DEFAULT_MIGRATION_COST
5728 * Allow override of migration cost - in units of microseconds.
5729 * E.g. migration_cost=1000,2000,3000 will set up a level-1 cost
5730 * of 1 msec, level-2 cost of 2 msecs and level3 cost of 3 msecs:
5732 static int __init migration_cost_setup(char *str)
5734 int ints[MAX_DOMAIN_DISTANCE+1], i;
5736 str = get_options(str, ARRAY_SIZE(ints), ints);
5738 printk("#ints: %d\n", ints[0]);
5739 for (i = 1; i <= ints[0]; i++) {
5740 migration_cost[i-1] = (unsigned long long)ints[i]*1000;
5741 printk("migration_cost[%d]: %Ld\n", i-1, migration_cost[i-1]);
5746 __setup ("migration_cost=", migration_cost_setup);
5749 * Global multiplier (divisor) for migration-cutoff values,
5750 * in percentiles. E.g. use a value of 150 to get 1.5 times
5751 * longer cache-hot cutoff times.
5753 * (We scale it from 100 to 128 to long long handling easier.)
5756 #define MIGRATION_FACTOR_SCALE 128
5758 static unsigned int migration_factor = MIGRATION_FACTOR_SCALE;
5760 static int __init setup_migration_factor(char *str)
5762 get_option(&str, &migration_factor);
5763 migration_factor = migration_factor * MIGRATION_FACTOR_SCALE / 100;
5767 __setup("migration_factor=", setup_migration_factor);
5770 * Estimated distance of two CPUs, measured via the number of domains
5771 * we have to pass for the two CPUs to be in the same span:
5773 static unsigned long domain_distance(int cpu1, int cpu2)
5775 unsigned long distance = 0;
5776 struct sched_domain *sd;
5778 for_each_domain(cpu1, sd) {
5779 WARN_ON(!cpu_isset(cpu1, sd->span));
5780 if (cpu_isset(cpu2, sd->span))
5784 if (distance >= MAX_DOMAIN_DISTANCE) {
5786 distance = MAX_DOMAIN_DISTANCE-1;
5792 static unsigned int migration_debug;
5794 static int __init setup_migration_debug(char *str)
5796 get_option(&str, &migration_debug);
5800 __setup("migration_debug=", setup_migration_debug);
5803 * Maximum cache-size that the scheduler should try to measure.
5804 * Architectures with larger caches should tune this up during
5805 * bootup. Gets used in the domain-setup code (i.e. during SMP
5808 unsigned int max_cache_size;
5810 static int __init setup_max_cache_size(char *str)
5812 get_option(&str, &max_cache_size);
5816 __setup("max_cache_size=", setup_max_cache_size);
5819 * Dirty a big buffer in a hard-to-predict (for the L2 cache) way. This
5820 * is the operation that is timed, so we try to generate unpredictable
5821 * cachemisses that still end up filling the L2 cache:
5823 static void touch_cache(void *__cache, unsigned long __size)
5825 unsigned long size = __size/sizeof(long), chunk1 = size/3,
5827 unsigned long *cache = __cache;
5830 for (i = 0; i < size/6; i += 8) {
5833 case 1: cache[size-1-i]++;
5834 case 2: cache[chunk1-i]++;
5835 case 3: cache[chunk1+i]++;
5836 case 4: cache[chunk2-i]++;
5837 case 5: cache[chunk2+i]++;
5843 * Measure the cache-cost of one task migration. Returns in units of nsec.
5845 static unsigned long long
5846 measure_one(void *cache, unsigned long size, int source, int target)
5848 cpumask_t mask, saved_mask;
5849 unsigned long long t0, t1, t2, t3, cost;
5851 saved_mask = current->cpus_allowed;
5854 * Flush source caches to RAM and invalidate them:
5859 * Migrate to the source CPU:
5861 mask = cpumask_of_cpu(source);
5862 set_cpus_allowed(current, mask);
5863 WARN_ON(smp_processor_id() != source);
5866 * Dirty the working set:
5869 touch_cache(cache, size);
5873 * Migrate to the target CPU, dirty the L2 cache and access
5874 * the shared buffer. (which represents the working set
5875 * of a migrated task.)
5877 mask = cpumask_of_cpu(target);
5878 set_cpus_allowed(current, mask);
5879 WARN_ON(smp_processor_id() != target);
5882 touch_cache(cache, size);
5885 cost = t1-t0 + t3-t2;
5887 if (migration_debug >= 2)
5888 printk("[%d->%d]: %8Ld %8Ld %8Ld => %10Ld.\n",
5889 source, target, t1-t0, t1-t0, t3-t2, cost);
5891 * Flush target caches to RAM and invalidate them:
5895 set_cpus_allowed(current, saved_mask);
5901 * Measure a series of task migrations and return the average
5902 * result. Since this code runs early during bootup the system
5903 * is 'undisturbed' and the average latency makes sense.
5905 * The algorithm in essence auto-detects the relevant cache-size,
5906 * so it will properly detect different cachesizes for different
5907 * cache-hierarchies, depending on how the CPUs are connected.
5909 * Architectures can prime the upper limit of the search range via
5910 * max_cache_size, otherwise the search range defaults to 20MB...64K.
5912 static unsigned long long
5913 measure_cost(int cpu1, int cpu2, void *cache, unsigned int size)
5915 unsigned long long cost1, cost2;
5919 * Measure the migration cost of 'size' bytes, over an
5920 * average of 10 runs:
5922 * (We perturb the cache size by a small (0..4k)
5923 * value to compensate size/alignment related artifacts.
5924 * We also subtract the cost of the operation done on
5930 * dry run, to make sure we start off cache-cold on cpu1,
5931 * and to get any vmalloc pagefaults in advance:
5933 measure_one(cache, size, cpu1, cpu2);
5934 for (i = 0; i < ITERATIONS; i++)
5935 cost1 += measure_one(cache, size - i*1024, cpu1, cpu2);
5937 measure_one(cache, size, cpu2, cpu1);
5938 for (i = 0; i < ITERATIONS; i++)
5939 cost1 += measure_one(cache, size - i*1024, cpu2, cpu1);
5942 * (We measure the non-migrating [cached] cost on both
5943 * cpu1 and cpu2, to handle CPUs with different speeds)
5947 measure_one(cache, size, cpu1, cpu1);
5948 for (i = 0; i < ITERATIONS; i++)
5949 cost2 += measure_one(cache, size - i*1024, cpu1, cpu1);
5951 measure_one(cache, size, cpu2, cpu2);
5952 for (i = 0; i < ITERATIONS; i++)
5953 cost2 += measure_one(cache, size - i*1024, cpu2, cpu2);
5956 * Get the per-iteration migration cost:
5958 do_div(cost1, 2*ITERATIONS);
5959 do_div(cost2, 2*ITERATIONS);
5961 return cost1 - cost2;
5964 static unsigned long long measure_migration_cost(int cpu1, int cpu2)
5966 unsigned long long max_cost = 0, fluct = 0, avg_fluct = 0;
5967 unsigned int max_size, size, size_found = 0;
5968 long long cost = 0, prev_cost;
5972 * Search from max_cache_size*5 down to 64K - the real relevant
5973 * cachesize has to lie somewhere inbetween.
5975 if (max_cache_size) {
5976 max_size = max(max_cache_size * SEARCH_SCOPE, MIN_CACHE_SIZE);
5977 size = max(max_cache_size / SEARCH_SCOPE, MIN_CACHE_SIZE);
5980 * Since we have no estimation about the relevant
5983 max_size = DEFAULT_CACHE_SIZE * SEARCH_SCOPE;
5984 size = MIN_CACHE_SIZE;
5987 if (!cpu_online(cpu1) || !cpu_online(cpu2)) {
5988 printk("cpu %d and %d not both online!\n", cpu1, cpu2);
5993 * Allocate the working set:
5995 cache = vmalloc(max_size);
5997 printk("could not vmalloc %d bytes for cache!\n", 2*max_size);
5998 return 1000000; /* return 1 msec on very small boxen */
6001 while (size <= max_size) {
6003 cost = measure_cost(cpu1, cpu2, cache, size);
6009 if (max_cost < cost) {
6015 * Calculate average fluctuation, we use this to prevent
6016 * noise from triggering an early break out of the loop:
6018 fluct = abs(cost - prev_cost);
6019 avg_fluct = (avg_fluct + fluct)/2;
6021 if (migration_debug)
6022 printk("-> [%d][%d][%7d] %3ld.%ld [%3ld.%ld] (%ld): (%8Ld %8Ld)\n",
6024 (long)cost / 1000000,
6025 ((long)cost / 100000) % 10,
6026 (long)max_cost / 1000000,
6027 ((long)max_cost / 100000) % 10,
6028 domain_distance(cpu1, cpu2),
6032 * If we iterated at least 20% past the previous maximum,
6033 * and the cost has dropped by more than 20% already,
6034 * (taking fluctuations into account) then we assume to
6035 * have found the maximum and break out of the loop early:
6037 if (size_found && (size*100 > size_found*SIZE_THRESH))
6038 if (cost+avg_fluct <= 0 ||
6039 max_cost*100 > (cost+avg_fluct)*COST_THRESH) {
6041 if (migration_debug)
6042 printk("-> found max.\n");
6046 * Increase the cachesize in 10% steps:
6048 size = size * 10 / 9;
6051 if (migration_debug)
6052 printk("[%d][%d] working set size found: %d, cost: %Ld\n",
6053 cpu1, cpu2, size_found, max_cost);
6058 * A task is considered 'cache cold' if at least 2 times
6059 * the worst-case cost of migration has passed.
6061 * (this limit is only listened to if the load-balancing
6062 * situation is 'nice' - if there is a large imbalance we
6063 * ignore it for the sake of CPU utilization and
6064 * processing fairness.)
6066 return 2 * max_cost * migration_factor / MIGRATION_FACTOR_SCALE;
6069 static void calibrate_migration_costs(const cpumask_t *cpu_map)
6071 int cpu1 = -1, cpu2 = -1, cpu, orig_cpu = raw_smp_processor_id();
6072 unsigned long j0, j1, distance, max_distance = 0;
6073 struct sched_domain *sd;
6078 * First pass - calculate the cacheflush times:
6080 for_each_cpu_mask(cpu1, *cpu_map) {
6081 for_each_cpu_mask(cpu2, *cpu_map) {
6084 distance = domain_distance(cpu1, cpu2);
6085 max_distance = max(max_distance, distance);
6087 * No result cached yet?
6089 if (migration_cost[distance] == -1LL)
6090 migration_cost[distance] =
6091 measure_migration_cost(cpu1, cpu2);
6095 * Second pass - update the sched domain hierarchy with
6096 * the new cache-hot-time estimations:
6098 for_each_cpu_mask(cpu, *cpu_map) {
6100 for_each_domain(cpu, sd) {
6101 sd->cache_hot_time = migration_cost[distance];
6108 if (migration_debug)
6109 printk("migration: max_cache_size: %d, cpu: %d MHz:\n",
6117 if (system_state == SYSTEM_BOOTING) {
6118 if (num_online_cpus() > 1) {
6119 printk("migration_cost=");
6120 for (distance = 0; distance <= max_distance; distance++) {
6123 printk("%ld", (long)migration_cost[distance] / 1000);
6129 if (migration_debug)
6130 printk("migration: %ld seconds\n", (j1-j0)/HZ);
6133 * Move back to the original CPU. NUMA-Q gets confused
6134 * if we migrate to another quad during bootup.
6136 if (raw_smp_processor_id() != orig_cpu) {
6137 cpumask_t mask = cpumask_of_cpu(orig_cpu),
6138 saved_mask = current->cpus_allowed;
6140 set_cpus_allowed(current, mask);
6141 set_cpus_allowed(current, saved_mask);
6148 * find_next_best_node - find the next node to include in a sched_domain
6149 * @node: node whose sched_domain we're building
6150 * @used_nodes: nodes already in the sched_domain
6152 * Find the next node to include in a given scheduling domain. Simply
6153 * finds the closest node not already in the @used_nodes map.
6155 * Should use nodemask_t.
6157 static int find_next_best_node(int node, unsigned long *used_nodes)
6159 int i, n, val, min_val, best_node = 0;
6163 for (i = 0; i < MAX_NUMNODES; i++) {
6164 /* Start at @node */
6165 n = (node + i) % MAX_NUMNODES;
6167 if (!nr_cpus_node(n))
6170 /* Skip already used nodes */
6171 if (test_bit(n, used_nodes))
6174 /* Simple min distance search */
6175 val = node_distance(node, n);
6177 if (val < min_val) {
6183 set_bit(best_node, used_nodes);
6188 * sched_domain_node_span - get a cpumask for a node's sched_domain
6189 * @node: node whose cpumask we're constructing
6190 * @size: number of nodes to include in this span
6192 * Given a node, construct a good cpumask for its sched_domain to span. It
6193 * should be one that prevents unnecessary balancing, but also spreads tasks
6196 static cpumask_t sched_domain_node_span(int node)
6198 DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
6199 cpumask_t span, nodemask;
6203 bitmap_zero(used_nodes, MAX_NUMNODES);
6205 nodemask = node_to_cpumask(node);
6206 cpus_or(span, span, nodemask);
6207 set_bit(node, used_nodes);
6209 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
6210 int next_node = find_next_best_node(node, used_nodes);
6212 nodemask = node_to_cpumask(next_node);
6213 cpus_or(span, span, nodemask);
6220 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6223 * SMT sched-domains:
6225 #ifdef CONFIG_SCHED_SMT
6226 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
6227 static struct sched_group sched_group_cpus[NR_CPUS];
6229 static int cpu_to_cpu_group(int cpu)
6236 * multi-core sched-domains:
6238 #ifdef CONFIG_SCHED_MC
6239 static DEFINE_PER_CPU(struct sched_domain, core_domains);
6240 static struct sched_group *sched_group_core_bycpu[NR_CPUS];
6243 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6244 static int cpu_to_core_group(int cpu)
6246 return first_cpu(cpu_sibling_map[cpu]);
6248 #elif defined(CONFIG_SCHED_MC)
6249 static int cpu_to_core_group(int cpu)
6255 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
6256 static struct sched_group *sched_group_phys_bycpu[NR_CPUS];
6258 static int cpu_to_phys_group(int cpu)
6260 #ifdef CONFIG_SCHED_MC
6261 cpumask_t mask = cpu_coregroup_map(cpu);
6262 return first_cpu(mask);
6263 #elif defined(CONFIG_SCHED_SMT)
6264 return first_cpu(cpu_sibling_map[cpu]);
6272 * The init_sched_build_groups can't handle what we want to do with node
6273 * groups, so roll our own. Now each node has its own list of groups which
6274 * gets dynamically allocated.
6276 static DEFINE_PER_CPU(struct sched_domain, node_domains);
6277 static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
6279 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
6280 static struct sched_group *sched_group_allnodes_bycpu[NR_CPUS];
6282 static int cpu_to_allnodes_group(int cpu)
6284 return cpu_to_node(cpu);
6286 static void init_numa_sched_groups_power(struct sched_group *group_head)
6288 struct sched_group *sg = group_head;
6294 for_each_cpu_mask(j, sg->cpumask) {
6295 struct sched_domain *sd;
6297 sd = &per_cpu(phys_domains, j);
6298 if (j != first_cpu(sd->groups->cpumask)) {
6300 * Only add "power" once for each
6306 sg->cpu_power += sd->groups->cpu_power;
6309 if (sg != group_head)
6314 /* Free memory allocated for various sched_group structures */
6315 static void free_sched_groups(const cpumask_t *cpu_map)
6321 for_each_cpu_mask(cpu, *cpu_map) {
6322 struct sched_group *sched_group_allnodes
6323 = sched_group_allnodes_bycpu[cpu];
6324 struct sched_group **sched_group_nodes
6325 = sched_group_nodes_bycpu[cpu];
6327 if (sched_group_allnodes) {
6328 kfree(sched_group_allnodes);
6329 sched_group_allnodes_bycpu[cpu] = NULL;
6332 if (!sched_group_nodes)
6335 for (i = 0; i < MAX_NUMNODES; i++) {
6336 cpumask_t nodemask = node_to_cpumask(i);
6337 struct sched_group *oldsg, *sg = sched_group_nodes[i];
6339 cpus_and(nodemask, nodemask, *cpu_map);
6340 if (cpus_empty(nodemask))
6350 if (oldsg != sched_group_nodes[i])
6353 kfree(sched_group_nodes);
6354 sched_group_nodes_bycpu[cpu] = NULL;
6357 for_each_cpu_mask(cpu, *cpu_map) {
6358 if (sched_group_phys_bycpu[cpu]) {
6359 kfree(sched_group_phys_bycpu[cpu]);
6360 sched_group_phys_bycpu[cpu] = NULL;
6362 #ifdef CONFIG_SCHED_MC
6363 if (sched_group_core_bycpu[cpu]) {
6364 kfree(sched_group_core_bycpu[cpu]);
6365 sched_group_core_bycpu[cpu] = NULL;
6372 * Build sched domains for a given set of cpus and attach the sched domains
6373 * to the individual cpus
6375 static int build_sched_domains(const cpumask_t *cpu_map)
6378 struct sched_group *sched_group_phys = NULL;
6379 #ifdef CONFIG_SCHED_MC
6380 struct sched_group *sched_group_core = NULL;
6383 struct sched_group **sched_group_nodes = NULL;
6384 struct sched_group *sched_group_allnodes = NULL;
6387 * Allocate the per-node list of sched groups
6389 sched_group_nodes = kzalloc(sizeof(struct sched_group*)*MAX_NUMNODES,
6391 if (!sched_group_nodes) {
6392 printk(KERN_WARNING "Can not alloc sched group node list\n");
6395 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
6399 * Set up domains for cpus specified by the cpu_map.
6401 for_each_cpu_mask(i, *cpu_map) {
6403 struct sched_domain *sd = NULL, *p;
6404 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
6406 cpus_and(nodemask, nodemask, *cpu_map);
6409 if (cpus_weight(*cpu_map)
6410 > SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
6411 if (!sched_group_allnodes) {
6412 sched_group_allnodes
6413 = kmalloc(sizeof(struct sched_group)
6416 if (!sched_group_allnodes) {
6418 "Can not alloc allnodes sched group\n");
6421 sched_group_allnodes_bycpu[i]
6422 = sched_group_allnodes;
6424 sd = &per_cpu(allnodes_domains, i);
6425 *sd = SD_ALLNODES_INIT;
6426 sd->span = *cpu_map;
6427 group = cpu_to_allnodes_group(i);
6428 sd->groups = &sched_group_allnodes[group];
6433 sd = &per_cpu(node_domains, i);
6435 sd->span = sched_domain_node_span(cpu_to_node(i));
6437 cpus_and(sd->span, sd->span, *cpu_map);
6440 if (!sched_group_phys) {
6442 = kmalloc(sizeof(struct sched_group) * NR_CPUS,
6444 if (!sched_group_phys) {
6445 printk (KERN_WARNING "Can not alloc phys sched"
6449 sched_group_phys_bycpu[i] = sched_group_phys;
6453 sd = &per_cpu(phys_domains, i);
6454 group = cpu_to_phys_group(i);
6456 sd->span = nodemask;
6458 sd->groups = &sched_group_phys[group];
6460 #ifdef CONFIG_SCHED_MC
6461 if (!sched_group_core) {
6463 = kmalloc(sizeof(struct sched_group) * NR_CPUS,
6465 if (!sched_group_core) {
6466 printk (KERN_WARNING "Can not alloc core sched"
6470 sched_group_core_bycpu[i] = sched_group_core;
6474 sd = &per_cpu(core_domains, i);
6475 group = cpu_to_core_group(i);
6477 sd->span = cpu_coregroup_map(i);
6478 cpus_and(sd->span, sd->span, *cpu_map);
6480 sd->groups = &sched_group_core[group];
6483 #ifdef CONFIG_SCHED_SMT
6485 sd = &per_cpu(cpu_domains, i);
6486 group = cpu_to_cpu_group(i);
6487 *sd = SD_SIBLING_INIT;
6488 sd->span = cpu_sibling_map[i];
6489 cpus_and(sd->span, sd->span, *cpu_map);
6491 sd->groups = &sched_group_cpus[group];
6495 #ifdef CONFIG_SCHED_SMT
6496 /* Set up CPU (sibling) groups */
6497 for_each_cpu_mask(i, *cpu_map) {
6498 cpumask_t this_sibling_map = cpu_sibling_map[i];
6499 cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
6500 if (i != first_cpu(this_sibling_map))
6503 init_sched_build_groups(sched_group_cpus, this_sibling_map,
6508 #ifdef CONFIG_SCHED_MC
6509 /* Set up multi-core groups */
6510 for_each_cpu_mask(i, *cpu_map) {
6511 cpumask_t this_core_map = cpu_coregroup_map(i);
6512 cpus_and(this_core_map, this_core_map, *cpu_map);
6513 if (i != first_cpu(this_core_map))
6515 init_sched_build_groups(sched_group_core, this_core_map,
6516 &cpu_to_core_group);
6521 /* Set up physical groups */
6522 for (i = 0; i < MAX_NUMNODES; i++) {
6523 cpumask_t nodemask = node_to_cpumask(i);
6525 cpus_and(nodemask, nodemask, *cpu_map);
6526 if (cpus_empty(nodemask))
6529 init_sched_build_groups(sched_group_phys, nodemask,
6530 &cpu_to_phys_group);
6534 /* Set up node groups */
6535 if (sched_group_allnodes)
6536 init_sched_build_groups(sched_group_allnodes, *cpu_map,
6537 &cpu_to_allnodes_group);
6539 for (i = 0; i < MAX_NUMNODES; i++) {
6540 /* Set up node groups */
6541 struct sched_group *sg, *prev;
6542 cpumask_t nodemask = node_to_cpumask(i);
6543 cpumask_t domainspan;
6544 cpumask_t covered = CPU_MASK_NONE;
6547 cpus_and(nodemask, nodemask, *cpu_map);
6548 if (cpus_empty(nodemask)) {
6549 sched_group_nodes[i] = NULL;
6553 domainspan = sched_domain_node_span(i);
6554 cpus_and(domainspan, domainspan, *cpu_map);
6556 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
6558 printk(KERN_WARNING "Can not alloc domain group for "
6562 sched_group_nodes[i] = sg;
6563 for_each_cpu_mask(j, nodemask) {
6564 struct sched_domain *sd;
6565 sd = &per_cpu(node_domains, j);
6569 sg->cpumask = nodemask;
6571 cpus_or(covered, covered, nodemask);
6574 for (j = 0; j < MAX_NUMNODES; j++) {
6575 cpumask_t tmp, notcovered;
6576 int n = (i + j) % MAX_NUMNODES;
6578 cpus_complement(notcovered, covered);
6579 cpus_and(tmp, notcovered, *cpu_map);
6580 cpus_and(tmp, tmp, domainspan);
6581 if (cpus_empty(tmp))
6584 nodemask = node_to_cpumask(n);
6585 cpus_and(tmp, tmp, nodemask);
6586 if (cpus_empty(tmp))
6589 sg = kmalloc_node(sizeof(struct sched_group),
6593 "Can not alloc domain group for node %d\n", j);
6598 sg->next = prev->next;
6599 cpus_or(covered, covered, tmp);
6606 /* Calculate CPU power for physical packages and nodes */
6607 #ifdef CONFIG_SCHED_SMT
6608 for_each_cpu_mask(i, *cpu_map) {
6609 struct sched_domain *sd;
6610 sd = &per_cpu(cpu_domains, i);
6611 sd->groups->cpu_power = SCHED_LOAD_SCALE;
6614 #ifdef CONFIG_SCHED_MC
6615 for_each_cpu_mask(i, *cpu_map) {
6617 struct sched_domain *sd;
6618 sd = &per_cpu(core_domains, i);
6619 if (sched_smt_power_savings)
6620 power = SCHED_LOAD_SCALE * cpus_weight(sd->groups->cpumask);
6622 power = SCHED_LOAD_SCALE + (cpus_weight(sd->groups->cpumask)-1)
6623 * SCHED_LOAD_SCALE / 10;
6624 sd->groups->cpu_power = power;
6628 for_each_cpu_mask(i, *cpu_map) {
6629 struct sched_domain *sd;
6630 #ifdef CONFIG_SCHED_MC
6631 sd = &per_cpu(phys_domains, i);
6632 if (i != first_cpu(sd->groups->cpumask))
6635 sd->groups->cpu_power = 0;
6636 if (sched_mc_power_savings || sched_smt_power_savings) {
6639 for_each_cpu_mask(j, sd->groups->cpumask) {
6640 struct sched_domain *sd1;
6641 sd1 = &per_cpu(core_domains, j);
6643 * for each core we will add once
6644 * to the group in physical domain
6646 if (j != first_cpu(sd1->groups->cpumask))
6649 if (sched_smt_power_savings)
6650 sd->groups->cpu_power += sd1->groups->cpu_power;
6652 sd->groups->cpu_power += SCHED_LOAD_SCALE;
6656 * This has to be < 2 * SCHED_LOAD_SCALE
6657 * Lets keep it SCHED_LOAD_SCALE, so that
6658 * while calculating NUMA group's cpu_power
6660 * numa_group->cpu_power += phys_group->cpu_power;
6662 * See "only add power once for each physical pkg"
6665 sd->groups->cpu_power = SCHED_LOAD_SCALE;
6668 sd = &per_cpu(phys_domains, i);
6669 if (sched_smt_power_savings)
6670 power = SCHED_LOAD_SCALE * cpus_weight(sd->groups->cpumask);
6672 power = SCHED_LOAD_SCALE;
6673 sd->groups->cpu_power = power;
6678 for (i = 0; i < MAX_NUMNODES; i++)
6679 init_numa_sched_groups_power(sched_group_nodes[i]);
6681 if (sched_group_allnodes) {
6682 int group = cpu_to_allnodes_group(first_cpu(*cpu_map));
6683 struct sched_group *sg = &sched_group_allnodes[group];
6685 init_numa_sched_groups_power(sg);
6689 /* Attach the domains */
6690 for_each_cpu_mask(i, *cpu_map) {
6691 struct sched_domain *sd;
6692 #ifdef CONFIG_SCHED_SMT
6693 sd = &per_cpu(cpu_domains, i);
6694 #elif defined(CONFIG_SCHED_MC)
6695 sd = &per_cpu(core_domains, i);
6697 sd = &per_cpu(phys_domains, i);
6699 cpu_attach_domain(sd, i);
6702 * Tune cache-hot values:
6704 calibrate_migration_costs(cpu_map);
6709 free_sched_groups(cpu_map);
6713 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6715 static int arch_init_sched_domains(const cpumask_t *cpu_map)
6717 cpumask_t cpu_default_map;
6721 * Setup mask for cpus without special case scheduling requirements.
6722 * For now this just excludes isolated cpus, but could be used to
6723 * exclude other special cases in the future.
6725 cpus_andnot(cpu_default_map, *cpu_map, cpu_isolated_map);
6727 err = build_sched_domains(&cpu_default_map);
6732 static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
6734 free_sched_groups(cpu_map);
6738 * Detach sched domains from a group of cpus specified in cpu_map
6739 * These cpus will now be attached to the NULL domain
6741 static void detach_destroy_domains(const cpumask_t *cpu_map)
6745 for_each_cpu_mask(i, *cpu_map)
6746 cpu_attach_domain(NULL, i);
6747 synchronize_sched();
6748 arch_destroy_sched_domains(cpu_map);
6752 * Partition sched domains as specified by the cpumasks below.
6753 * This attaches all cpus from the cpumasks to the NULL domain,
6754 * waits for a RCU quiescent period, recalculates sched
6755 * domain information and then attaches them back to the
6756 * correct sched domains
6757 * Call with hotplug lock held
6759 int partition_sched_domains(cpumask_t *partition1, cpumask_t *partition2)
6761 cpumask_t change_map;
6764 cpus_and(*partition1, *partition1, cpu_online_map);
6765 cpus_and(*partition2, *partition2, cpu_online_map);
6766 cpus_or(change_map, *partition1, *partition2);
6768 /* Detach sched domains from all of the affected cpus */
6769 detach_destroy_domains(&change_map);
6770 if (!cpus_empty(*partition1))
6771 err = build_sched_domains(partition1);
6772 if (!err && !cpus_empty(*partition2))
6773 err = build_sched_domains(partition2);
6778 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
6779 int arch_reinit_sched_domains(void)
6784 detach_destroy_domains(&cpu_online_map);
6785 err = arch_init_sched_domains(&cpu_online_map);
6786 unlock_cpu_hotplug();
6791 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
6795 if (buf[0] != '0' && buf[0] != '1')
6799 sched_smt_power_savings = (buf[0] == '1');
6801 sched_mc_power_savings = (buf[0] == '1');
6803 ret = arch_reinit_sched_domains();
6805 return ret ? ret : count;
6808 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
6812 #ifdef CONFIG_SCHED_SMT
6814 err = sysfs_create_file(&cls->kset.kobj,
6815 &attr_sched_smt_power_savings.attr);
6817 #ifdef CONFIG_SCHED_MC
6818 if (!err && mc_capable())
6819 err = sysfs_create_file(&cls->kset.kobj,
6820 &attr_sched_mc_power_savings.attr);
6826 #ifdef CONFIG_SCHED_MC
6827 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
6829 return sprintf(page, "%u\n", sched_mc_power_savings);
6831 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
6832 const char *buf, size_t count)
6834 return sched_power_savings_store(buf, count, 0);
6836 SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
6837 sched_mc_power_savings_store);
6840 #ifdef CONFIG_SCHED_SMT
6841 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
6843 return sprintf(page, "%u\n", sched_smt_power_savings);
6845 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
6846 const char *buf, size_t count)
6848 return sched_power_savings_store(buf, count, 1);
6850 SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
6851 sched_smt_power_savings_store);
6855 #ifdef CONFIG_HOTPLUG_CPU
6857 * Force a reinitialization of the sched domains hierarchy. The domains
6858 * and groups cannot be updated in place without racing with the balancing
6859 * code, so we temporarily attach all running cpus to the NULL domain
6860 * which will prevent rebalancing while the sched domains are recalculated.
6862 static int update_sched_domains(struct notifier_block *nfb,
6863 unsigned long action, void *hcpu)
6866 case CPU_UP_PREPARE:
6867 case CPU_DOWN_PREPARE:
6868 detach_destroy_domains(&cpu_online_map);
6871 case CPU_UP_CANCELED:
6872 case CPU_DOWN_FAILED:
6876 * Fall through and re-initialise the domains.
6883 /* The hotplug lock is already held by cpu_up/cpu_down */
6884 arch_init_sched_domains(&cpu_online_map);
6890 void __init sched_init_smp(void)
6893 arch_init_sched_domains(&cpu_online_map);
6894 unlock_cpu_hotplug();
6895 /* XXX: Theoretical race here - CPU may be hotplugged now */
6896 hotcpu_notifier(update_sched_domains, 0);
6899 void __init sched_init_smp(void)
6902 #endif /* CONFIG_SMP */
6904 int in_sched_functions(unsigned long addr)
6906 /* Linker adds these: start and end of __sched functions */
6907 extern char __sched_text_start[], __sched_text_end[];
6909 return in_lock_functions(addr) ||
6910 (addr >= (unsigned long)__sched_text_start
6911 && addr < (unsigned long)__sched_text_end);
6914 void __init sched_init(void)
6918 for_each_possible_cpu(i) {
6919 struct prio_array *array;
6923 spin_lock_init(&rq->lock);
6924 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
6926 rq->active = rq->arrays;
6927 rq->expired = rq->arrays + 1;
6928 rq->best_expired_prio = MAX_PRIO;
6932 for (j = 1; j < 3; j++)
6933 rq->cpu_load[j] = 0;
6934 rq->active_balance = 0;
6937 rq->migration_thread = NULL;
6938 INIT_LIST_HEAD(&rq->migration_queue);
6940 atomic_set(&rq->nr_iowait, 0);
6941 #ifdef CONFIG_VSERVER_HARDCPU
6942 INIT_LIST_HEAD(&rq->hold_queue);
6945 for (j = 0; j < 2; j++) {
6946 array = rq->arrays + j;
6947 for (k = 0; k < MAX_PRIO; k++) {
6948 INIT_LIST_HEAD(array->queue + k);
6949 __clear_bit(k, array->bitmap);
6951 // delimiter for bitsearch
6952 __set_bit(MAX_PRIO, array->bitmap);
6956 set_load_weight(&init_task);
6958 #ifdef CONFIG_RT_MUTEXES
6959 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
6963 * The boot idle thread does lazy MMU switching as well:
6965 atomic_inc(&init_mm.mm_count);
6966 enter_lazy_tlb(&init_mm, current);
6969 * Make us the idle thread. Technically, schedule() should not be
6970 * called from this thread, however somewhere below it might be,
6971 * but because we are the idle thread, we just pick up running again
6972 * when this runqueue becomes "idle".
6974 init_idle(current, smp_processor_id());
6977 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
6978 void __might_sleep(char *file, int line)
6981 static unsigned long prev_jiffy; /* ratelimiting */
6983 if ((in_atomic() || irqs_disabled()) &&
6984 system_state == SYSTEM_RUNNING && !oops_in_progress) {
6985 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6987 prev_jiffy = jiffies;
6988 printk(KERN_ERR "BUG: sleeping function called from invalid"
6989 " context at %s:%d\n", file, line);
6990 printk("in_atomic():%d, irqs_disabled():%d\n",
6991 in_atomic(), irqs_disabled());
6996 EXPORT_SYMBOL(__might_sleep);
6999 #ifdef CONFIG_MAGIC_SYSRQ
7000 void normalize_rt_tasks(void)
7002 struct prio_array *array;
7003 struct task_struct *p;
7004 unsigned long flags;
7007 read_lock_irq(&tasklist_lock);
7008 for_each_process(p) {
7012 spin_lock_irqsave(&p->pi_lock, flags);
7013 rq = __task_rq_lock(p);
7017 deactivate_task(p, task_rq(p));
7018 __setscheduler(p, SCHED_NORMAL, 0);
7020 vx_activate_task(p);
7021 __activate_task(p, task_rq(p));
7022 resched_task(rq->curr);
7025 __task_rq_unlock(rq);
7026 spin_unlock_irqrestore(&p->pi_lock, flags);
7028 read_unlock_irq(&tasklist_lock);
7031 #endif /* CONFIG_MAGIC_SYSRQ */
7035 * These functions are only useful for the IA64 MCA handling.
7037 * They can only be called when the whole system has been
7038 * stopped - every CPU needs to be quiescent, and no scheduling
7039 * activity can take place. Using them for anything else would
7040 * be a serious bug, and as a result, they aren't even visible
7041 * under any other configuration.
7045 * curr_task - return the current task for a given cpu.
7046 * @cpu: the processor in question.
7048 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7050 struct task_struct *curr_task(int cpu)
7052 return cpu_curr(cpu);
7056 * set_curr_task - set the current task for a given cpu.
7057 * @cpu: the processor in question.
7058 * @p: the task pointer to set.
7060 * Description: This function must only be used when non-maskable interrupts
7061 * are serviced on a separate stack. It allows the architecture to switch the
7062 * notion of the current task on a cpu in a non-blocking manner. This function
7063 * must be called with all CPU's synchronized, and interrupts disabled, the
7064 * and caller must save the original value of the current task (see
7065 * curr_task() above) and restore that value before reenabling interrupts and
7066 * re-starting the system.
7068 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7070 void set_curr_task(int cpu, struct task_struct *p)