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/freezer.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/tsacct_kern.h>
53 #include <linux/kprobes.h>
54 #include <linux/delayacct.h>
57 #include <asm/unistd.h>
58 #include <linux/vs_sched.h>
59 #include <linux/vs_cvirt.h>
62 * Convert user-nice values [ -20 ... 0 ... 19 ]
63 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
66 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
67 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
68 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
71 * 'User priority' is the nice value converted to something we
72 * can work with better when scaling various scheduler parameters,
73 * it's a [ 0 ... 39 ] range.
75 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
76 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
77 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
80 * Some helpers for converting nanosecond timing to jiffy resolution
82 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
83 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
86 * These are the 'tuning knobs' of the scheduler:
88 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
89 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
90 * Timeslices get refilled after they expire.
92 #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
93 #define DEF_TIMESLICE (100 * HZ / 1000)
94 #define ON_RUNQUEUE_WEIGHT 30
95 #define CHILD_PENALTY 95
96 #define PARENT_PENALTY 100
98 #define PRIO_BONUS_RATIO 25
99 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
100 #define INTERACTIVE_DELTA 2
101 #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
102 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
103 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
106 * If a task is 'interactive' then we reinsert it in the active
107 * array after it has expired its current timeslice. (it will not
108 * continue to run immediately, it will still roundrobin with
109 * other interactive tasks.)
111 * This part scales the interactivity limit depending on niceness.
113 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
114 * Here are a few examples of different nice levels:
116 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
117 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
118 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
119 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
120 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
122 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
123 * priority range a task can explore, a value of '1' means the
124 * task is rated interactive.)
126 * Ie. nice +19 tasks can never get 'interactive' enough to be
127 * reinserted into the active array. And only heavily CPU-hog nice -20
128 * tasks will be expired. Default nice 0 tasks are somewhere between,
129 * it takes some effort for them to get interactive, but it's not
133 #define CURRENT_BONUS(p) \
134 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
137 #define GRANULARITY (10 * HZ / 1000 ? : 1)
140 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
141 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
144 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
145 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
148 #define SCALE(v1,v1_max,v2_max) \
149 (v1) * (v2_max) / (v1_max)
152 (SCALE(TASK_NICE(p) + 20, 40, MAX_BONUS) - 20 * MAX_BONUS / 40 + \
155 #define TASK_INTERACTIVE(p) \
156 ((p)->prio <= (p)->static_prio - DELTA(p))
158 #define INTERACTIVE_SLEEP(p) \
159 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
160 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
162 #define TASK_PREEMPTS_CURR(p, rq) \
163 ((p)->prio < (rq)->curr->prio)
165 #define SCALE_PRIO(x, prio) \
166 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO / 2), MIN_TIMESLICE)
168 static unsigned int static_prio_timeslice(int static_prio)
170 if (static_prio < NICE_TO_PRIO(0))
171 return SCALE_PRIO(DEF_TIMESLICE * 4, static_prio);
173 return SCALE_PRIO(DEF_TIMESLICE, static_prio);
177 * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
178 * to time slice values: [800ms ... 100ms ... 5ms]
180 * The higher a thread's priority, the bigger timeslices
181 * it gets during one round of execution. But even the lowest
182 * priority thread gets MIN_TIMESLICE worth of execution time.
185 static inline unsigned int task_timeslice(struct task_struct *p)
187 return static_prio_timeslice(p->static_prio);
191 * These are the runqueue data structures:
195 unsigned int nr_active;
196 DECLARE_BITMAP(bitmap, MAX_PRIO+1); /* include 1 bit for delimiter */
197 struct list_head queue[MAX_PRIO];
201 * This is the main, per-CPU runqueue data structure.
203 * Locking rule: those places that want to lock multiple runqueues
204 * (such as the load balancing or the thread migration code), lock
205 * acquire operations must be ordered by ascending &runqueue.
211 * nr_running and cpu_load should be in the same cacheline because
212 * remote CPUs use both these fields when doing load calculation.
214 unsigned long nr_running;
215 unsigned long raw_weighted_load;
217 unsigned long cpu_load[3];
219 unsigned long long nr_switches;
222 * This is part of a global counter where only the total sum
223 * over all CPUs matters. A task can increase this counter on
224 * one CPU and if it got migrated afterwards it may decrease
225 * it on another CPU. Always updated under the runqueue lock:
227 unsigned long nr_uninterruptible;
229 unsigned long expired_timestamp;
230 /* Cached timestamp set by update_cpu_clock() */
231 unsigned long long most_recent_timestamp;
232 struct task_struct *curr, *idle;
233 unsigned long next_balance;
234 struct mm_struct *prev_mm;
235 struct prio_array *active, *expired, arrays[2];
236 int best_expired_prio;
240 struct sched_domain *sd;
242 /* For active balancing */
245 int cpu; /* cpu of this runqueue */
247 struct task_struct *migration_thread;
248 struct list_head migration_queue;
250 unsigned long norm_time;
251 unsigned long idle_time;
252 #ifdef CONFIG_VSERVER_IDLETIME
255 #ifdef CONFIG_VSERVER_HARDCPU
256 struct list_head hold_queue;
257 unsigned long nr_onhold;
261 #ifdef CONFIG_SCHEDSTATS
263 struct sched_info rq_sched_info;
265 /* sys_sched_yield() stats */
266 unsigned long yld_exp_empty;
267 unsigned long yld_act_empty;
268 unsigned long yld_both_empty;
269 unsigned long yld_cnt;
271 /* schedule() stats */
272 unsigned long sched_switch;
273 unsigned long sched_cnt;
274 unsigned long sched_goidle;
276 /* try_to_wake_up() stats */
277 unsigned long ttwu_cnt;
278 unsigned long ttwu_local;
280 struct lock_class_key rq_lock_key;
283 static DEFINE_PER_CPU(struct rq, runqueues) ____cacheline_aligned_in_smp;
285 static inline int cpu_of(struct rq *rq)
295 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
296 * See detach_destroy_domains: synchronize_sched for details.
298 * The domain tree of any CPU may only be accessed from within
299 * preempt-disabled sections.
301 #define for_each_domain(cpu, __sd) \
302 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
304 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
305 #define this_rq() (&__get_cpu_var(runqueues))
306 #define task_rq(p) cpu_rq(task_cpu(p))
307 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
309 #ifndef prepare_arch_switch
310 # define prepare_arch_switch(next) do { } while (0)
312 #ifndef finish_arch_switch
313 # define finish_arch_switch(prev) do { } while (0)
316 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
317 static inline int task_running(struct rq *rq, struct task_struct *p)
319 return rq->curr == p;
322 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
326 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
328 #ifdef CONFIG_DEBUG_SPINLOCK
329 /* this is a valid case when another task releases the spinlock */
330 rq->lock.owner = current;
333 * If we are tracking spinlock dependencies then we have to
334 * fix up the runqueue lock - which gets 'carried over' from
337 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
339 spin_unlock_irq(&rq->lock);
342 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
343 static inline int task_running(struct rq *rq, struct task_struct *p)
348 return rq->curr == p;
352 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
356 * We can optimise this out completely for !SMP, because the
357 * SMP rebalancing from interrupt is the only thing that cares
362 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
363 spin_unlock_irq(&rq->lock);
365 spin_unlock(&rq->lock);
369 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
373 * After ->oncpu is cleared, the task can be moved to a different CPU.
374 * We must ensure this doesn't happen until the switch is completely
380 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
384 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
387 * __task_rq_lock - lock the runqueue a given task resides on.
388 * Must be called interrupts disabled.
390 static inline struct rq *__task_rq_lock(struct task_struct *p)
397 spin_lock(&rq->lock);
398 if (unlikely(rq != task_rq(p))) {
399 spin_unlock(&rq->lock);
400 goto repeat_lock_task;
406 * task_rq_lock - lock the runqueue a given task resides on and disable
407 * interrupts. Note the ordering: we can safely lookup the task_rq without
408 * explicitly disabling preemption.
410 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
416 local_irq_save(*flags);
418 spin_lock(&rq->lock);
419 if (unlikely(rq != task_rq(p))) {
420 spin_unlock_irqrestore(&rq->lock, *flags);
421 goto repeat_lock_task;
426 static inline void __task_rq_unlock(struct rq *rq)
429 spin_unlock(&rq->lock);
432 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
435 spin_unlock_irqrestore(&rq->lock, *flags);
438 #ifdef CONFIG_SCHEDSTATS
440 * bump this up when changing the output format or the meaning of an existing
441 * format, so that tools can adapt (or abort)
443 #define SCHEDSTAT_VERSION 14
445 static int show_schedstat(struct seq_file *seq, void *v)
449 seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
450 seq_printf(seq, "timestamp %lu\n", jiffies);
451 for_each_online_cpu(cpu) {
452 struct rq *rq = cpu_rq(cpu);
454 struct sched_domain *sd;
458 /* runqueue-specific stats */
460 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
461 cpu, rq->yld_both_empty,
462 rq->yld_act_empty, rq->yld_exp_empty, rq->yld_cnt,
463 rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
464 rq->ttwu_cnt, rq->ttwu_local,
465 rq->rq_sched_info.cpu_time,
466 rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
468 seq_printf(seq, "\n");
471 /* domain-specific stats */
473 for_each_domain(cpu, sd) {
474 enum idle_type itype;
475 char mask_str[NR_CPUS];
477 cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
478 seq_printf(seq, "domain%d %s", dcnt++, mask_str);
479 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
481 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu "
484 sd->lb_balanced[itype],
485 sd->lb_failed[itype],
486 sd->lb_imbalance[itype],
487 sd->lb_gained[itype],
488 sd->lb_hot_gained[itype],
489 sd->lb_nobusyq[itype],
490 sd->lb_nobusyg[itype]);
492 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu %lu"
494 sd->alb_cnt, sd->alb_failed, sd->alb_pushed,
495 sd->sbe_cnt, sd->sbe_balanced, sd->sbe_pushed,
496 sd->sbf_cnt, sd->sbf_balanced, sd->sbf_pushed,
497 sd->ttwu_wake_remote, sd->ttwu_move_affine,
498 sd->ttwu_move_balance);
506 static int schedstat_open(struct inode *inode, struct file *file)
508 unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
509 char *buf = kmalloc(size, GFP_KERNEL);
515 res = single_open(file, show_schedstat, NULL);
517 m = file->private_data;
525 const struct file_operations proc_schedstat_operations = {
526 .open = schedstat_open,
529 .release = single_release,
533 * Expects runqueue lock to be held for atomicity of update
536 rq_sched_info_arrive(struct rq *rq, unsigned long delta_jiffies)
539 rq->rq_sched_info.run_delay += delta_jiffies;
540 rq->rq_sched_info.pcnt++;
545 * Expects runqueue lock to be held for atomicity of update
548 rq_sched_info_depart(struct rq *rq, unsigned long delta_jiffies)
551 rq->rq_sched_info.cpu_time += delta_jiffies;
553 # define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
554 # define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
555 #else /* !CONFIG_SCHEDSTATS */
557 rq_sched_info_arrive(struct rq *rq, unsigned long delta_jiffies)
560 rq_sched_info_depart(struct rq *rq, unsigned long delta_jiffies)
562 # define schedstat_inc(rq, field) do { } while (0)
563 # define schedstat_add(rq, field, amt) do { } while (0)
567 * this_rq_lock - lock this runqueue and disable interrupts.
569 static inline struct rq *this_rq_lock(void)
576 spin_lock(&rq->lock);
581 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
583 * Called when a process is dequeued from the active array and given
584 * the cpu. We should note that with the exception of interactive
585 * tasks, the expired queue will become the active queue after the active
586 * queue is empty, without explicitly dequeuing and requeuing tasks in the
587 * expired queue. (Interactive tasks may be requeued directly to the
588 * active queue, thus delaying tasks in the expired queue from running;
589 * see scheduler_tick()).
591 * This function is only called from sched_info_arrive(), rather than
592 * dequeue_task(). Even though a task may be queued and dequeued multiple
593 * times as it is shuffled about, we're really interested in knowing how
594 * long it was from the *first* time it was queued to the time that it
597 static inline void sched_info_dequeued(struct task_struct *t)
599 t->sched_info.last_queued = 0;
603 * Called when a task finally hits the cpu. We can now calculate how
604 * long it was waiting to run. We also note when it began so that we
605 * can keep stats on how long its timeslice is.
607 static void sched_info_arrive(struct task_struct *t)
609 unsigned long now = jiffies, delta_jiffies = 0;
611 if (t->sched_info.last_queued)
612 delta_jiffies = now - t->sched_info.last_queued;
613 sched_info_dequeued(t);
614 t->sched_info.run_delay += delta_jiffies;
615 t->sched_info.last_arrival = now;
616 t->sched_info.pcnt++;
618 rq_sched_info_arrive(task_rq(t), delta_jiffies);
622 * Called when a process is queued into either the active or expired
623 * array. The time is noted and later used to determine how long we
624 * had to wait for us to reach the cpu. Since the expired queue will
625 * become the active queue after active queue is empty, without dequeuing
626 * and requeuing any tasks, we are interested in queuing to either. It
627 * is unusual but not impossible for tasks to be dequeued and immediately
628 * requeued in the same or another array: this can happen in sched_yield(),
629 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
632 * This function is only called from enqueue_task(), but also only updates
633 * the timestamp if it is already not set. It's assumed that
634 * sched_info_dequeued() will clear that stamp when appropriate.
636 static inline void sched_info_queued(struct task_struct *t)
638 if (unlikely(sched_info_on()))
639 if (!t->sched_info.last_queued)
640 t->sched_info.last_queued = jiffies;
644 * Called when a process ceases being the active-running process, either
645 * voluntarily or involuntarily. Now we can calculate how long we ran.
647 static inline void sched_info_depart(struct task_struct *t)
649 unsigned long delta_jiffies = jiffies - t->sched_info.last_arrival;
651 t->sched_info.cpu_time += delta_jiffies;
652 rq_sched_info_depart(task_rq(t), delta_jiffies);
656 * Called when tasks are switched involuntarily due, typically, to expiring
657 * their time slice. (This may also be called when switching to or from
658 * the idle task.) We are only called when prev != next.
661 __sched_info_switch(struct task_struct *prev, struct task_struct *next)
663 struct rq *rq = task_rq(prev);
666 * prev now departs the cpu. It's not interesting to record
667 * stats about how efficient we were at scheduling the idle
670 if (prev != rq->idle)
671 sched_info_depart(prev);
673 if (next != rq->idle)
674 sched_info_arrive(next);
677 sched_info_switch(struct task_struct *prev, struct task_struct *next)
679 if (unlikely(sched_info_on()))
680 __sched_info_switch(prev, next);
683 #define sched_info_queued(t) do { } while (0)
684 #define sched_info_switch(t, next) do { } while (0)
685 #endif /* CONFIG_SCHEDSTATS || CONFIG_TASK_DELAY_ACCT */
688 * Adding/removing a task to/from a priority array:
690 static void dequeue_task(struct task_struct *p, struct prio_array *array)
692 BUG_ON(p->state & TASK_ONHOLD);
694 list_del(&p->run_list);
695 if (list_empty(array->queue + p->prio))
696 __clear_bit(p->prio, array->bitmap);
699 static void enqueue_task(struct task_struct *p, struct prio_array *array)
701 BUG_ON(p->state & TASK_ONHOLD);
702 sched_info_queued(p);
703 list_add_tail(&p->run_list, array->queue + p->prio);
704 __set_bit(p->prio, array->bitmap);
710 * Put task to the end of the run list without the overhead of dequeue
711 * followed by enqueue.
713 static void requeue_task(struct task_struct *p, struct prio_array *array)
715 BUG_ON(p->state & TASK_ONHOLD);
716 list_move_tail(&p->run_list, array->queue + p->prio);
720 enqueue_task_head(struct task_struct *p, struct prio_array *array)
722 BUG_ON(p->state & TASK_ONHOLD);
723 list_add(&p->run_list, array->queue + p->prio);
724 __set_bit(p->prio, array->bitmap);
730 * __normal_prio - return the priority that is based on the static
731 * priority but is modified by bonuses/penalties.
733 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
734 * into the -5 ... 0 ... +5 bonus/penalty range.
736 * We use 25% of the full 0...39 priority range so that:
738 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
739 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
741 * Both properties are important to certain workloads.
744 static inline int __normal_prio(struct task_struct *p)
748 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
750 prio = p->static_prio - bonus;
752 /* adjust effective priority */
753 prio = vx_adjust_prio(p, prio, MAX_USER_PRIO);
755 if (prio < MAX_RT_PRIO)
757 if (prio > MAX_PRIO-1)
763 * To aid in avoiding the subversion of "niceness" due to uneven distribution
764 * of tasks with abnormal "nice" values across CPUs the contribution that
765 * each task makes to its run queue's load is weighted according to its
766 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
767 * scaled version of the new time slice allocation that they receive on time
772 * Assume: static_prio_timeslice(NICE_TO_PRIO(0)) == DEF_TIMESLICE
773 * If static_prio_timeslice() is ever changed to break this assumption then
774 * this code will need modification
776 #define TIME_SLICE_NICE_ZERO DEF_TIMESLICE
777 #define LOAD_WEIGHT(lp) \
778 (((lp) * SCHED_LOAD_SCALE) / TIME_SLICE_NICE_ZERO)
779 #define PRIO_TO_LOAD_WEIGHT(prio) \
780 LOAD_WEIGHT(static_prio_timeslice(prio))
781 #define RTPRIO_TO_LOAD_WEIGHT(rp) \
782 (PRIO_TO_LOAD_WEIGHT(MAX_RT_PRIO) + LOAD_WEIGHT(rp))
784 static void set_load_weight(struct task_struct *p)
786 if (has_rt_policy(p)) {
788 if (p == task_rq(p)->migration_thread)
790 * The migration thread does the actual balancing.
791 * Giving its load any weight will skew balancing
797 p->load_weight = RTPRIO_TO_LOAD_WEIGHT(p->rt_priority);
799 p->load_weight = PRIO_TO_LOAD_WEIGHT(p->static_prio);
803 inc_raw_weighted_load(struct rq *rq, const struct task_struct *p)
805 rq->raw_weighted_load += p->load_weight;
809 dec_raw_weighted_load(struct rq *rq, const struct task_struct *p)
811 rq->raw_weighted_load -= p->load_weight;
814 static inline void inc_nr_running(struct task_struct *p, struct rq *rq)
817 inc_raw_weighted_load(rq, p);
820 static inline void dec_nr_running(struct task_struct *p, struct rq *rq)
823 dec_raw_weighted_load(rq, p);
827 * Calculate the expected normal priority: i.e. priority
828 * without taking RT-inheritance into account. Might be
829 * boosted by interactivity modifiers. Changes upon fork,
830 * setprio syscalls, and whenever the interactivity
831 * estimator recalculates.
833 static inline int normal_prio(struct task_struct *p)
837 if (has_rt_policy(p))
838 prio = MAX_RT_PRIO-1 - p->rt_priority;
840 prio = __normal_prio(p);
845 * Calculate the current priority, i.e. the priority
846 * taken into account by the scheduler. This value might
847 * be boosted by RT tasks, or might be boosted by
848 * interactivity modifiers. Will be RT if the task got
849 * RT-boosted. If not then it returns p->normal_prio.
851 static int effective_prio(struct task_struct *p)
853 p->normal_prio = normal_prio(p);
855 * If we are RT tasks or we were boosted to RT priority,
856 * keep the priority unchanged. Otherwise, update priority
857 * to the normal priority:
859 if (!rt_prio(p->prio))
860 return p->normal_prio;
864 #include "sched_mon.h"
868 * __activate_task - move a task to the runqueue.
870 static void __activate_task(struct task_struct *p, struct rq *rq)
872 struct prio_array *target = rq->active;
875 target = rq->expired;
876 vxm_activate_task(p, rq);
877 enqueue_task(p, target);
878 inc_nr_running(p, rq);
882 * __activate_idle_task - move idle task to the _front_ of runqueue.
884 static inline void __activate_idle_task(struct task_struct *p, struct rq *rq)
886 vxm_activate_idle(p, rq);
887 enqueue_task_head(p, rq->active);
888 inc_nr_running(p, rq);
892 * Recalculate p->normal_prio and p->prio after having slept,
893 * updating the sleep-average too:
895 static int recalc_task_prio(struct task_struct *p, unsigned long long now)
897 /* Caller must always ensure 'now >= p->timestamp' */
898 unsigned long sleep_time = now - p->timestamp;
903 if (likely(sleep_time > 0)) {
905 * This ceiling is set to the lowest priority that would allow
906 * a task to be reinserted into the active array on timeslice
909 unsigned long ceiling = INTERACTIVE_SLEEP(p);
911 if (p->mm && sleep_time > ceiling && p->sleep_avg < ceiling) {
913 * Prevents user tasks from achieving best priority
914 * with one single large enough sleep.
916 p->sleep_avg = ceiling;
918 * Using INTERACTIVE_SLEEP() as a ceiling places a
919 * nice(0) task 1ms sleep away from promotion, and
920 * gives it 700ms to round-robin with no chance of
921 * being demoted. This is more than generous, so
922 * mark this sleep as non-interactive to prevent the
923 * on-runqueue bonus logic from intervening should
924 * this task not receive cpu immediately.
926 p->sleep_type = SLEEP_NONINTERACTIVE;
929 * Tasks waking from uninterruptible sleep are
930 * limited in their sleep_avg rise as they
931 * are likely to be waiting on I/O
933 if (p->sleep_type == SLEEP_NONINTERACTIVE && p->mm) {
934 if (p->sleep_avg >= ceiling)
936 else if (p->sleep_avg + sleep_time >=
938 p->sleep_avg = ceiling;
944 * This code gives a bonus to interactive tasks.
946 * The boost works by updating the 'average sleep time'
947 * value here, based on ->timestamp. The more time a
948 * task spends sleeping, the higher the average gets -
949 * and the higher the priority boost gets as well.
951 p->sleep_avg += sleep_time;
954 if (p->sleep_avg > NS_MAX_SLEEP_AVG)
955 p->sleep_avg = NS_MAX_SLEEP_AVG;
958 return effective_prio(p);
962 * activate_task - move a task to the runqueue and do priority recalculation
964 * Update all the scheduling statistics stuff. (sleep average
965 * calculation, priority modifiers, etc.)
967 static void activate_task(struct task_struct *p, struct rq *rq, int local)
969 unsigned long long now;
977 /* Compensate for drifting sched_clock */
978 struct rq *this_rq = this_rq();
979 now = (now - this_rq->most_recent_timestamp)
980 + rq->most_recent_timestamp;
985 * Sleep time is in units of nanosecs, so shift by 20 to get a
986 * milliseconds-range estimation of the amount of time that the task
989 if (unlikely(prof_on == SLEEP_PROFILING)) {
990 if (p->state == TASK_UNINTERRUPTIBLE)
991 profile_hits(SLEEP_PROFILING, (void *)get_wchan(p),
992 (now - p->timestamp) >> 20);
995 p->prio = recalc_task_prio(p, now);
998 * This checks to make sure it's not an uninterruptible task
999 * that is now waking up.
1001 if (p->sleep_type == SLEEP_NORMAL) {
1003 * Tasks which were woken up by interrupts (ie. hw events)
1004 * are most likely of interactive nature. So we give them
1005 * the credit of extending their sleep time to the period
1006 * of time they spend on the runqueue, waiting for execution
1007 * on a CPU, first time around:
1010 p->sleep_type = SLEEP_INTERRUPTED;
1013 * Normal first-time wakeups get a credit too for
1014 * on-runqueue time, but it will be weighted down:
1016 p->sleep_type = SLEEP_INTERACTIVE;
1021 vx_activate_task(p);
1022 __activate_task(p, rq);
1026 * __deactivate_task - remove a task from the runqueue.
1028 static void __deactivate_task(struct task_struct *p, struct rq *rq)
1030 dec_nr_running(p, rq);
1031 dequeue_task(p, p->array);
1032 vxm_deactivate_task(p, rq);
1037 void deactivate_task(struct task_struct *p, struct rq *rq)
1039 vx_deactivate_task(p);
1040 __deactivate_task(p, rq);
1043 #include "sched_hard.h"
1046 * resched_task - mark a task 'to be rescheduled now'.
1048 * On UP this means the setting of the need_resched flag, on SMP it
1049 * might also involve a cross-CPU call to trigger the scheduler on
1054 #ifndef tsk_is_polling
1055 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
1058 static void resched_task(struct task_struct *p)
1062 assert_spin_locked(&task_rq(p)->lock);
1064 if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
1067 set_tsk_thread_flag(p, TIF_NEED_RESCHED);
1070 if (cpu == smp_processor_id())
1073 /* NEED_RESCHED must be visible before we test polling */
1075 if (!tsk_is_polling(p))
1076 smp_send_reschedule(cpu);
1079 static inline void resched_task(struct task_struct *p)
1081 assert_spin_locked(&task_rq(p)->lock);
1082 set_tsk_need_resched(p);
1087 * task_curr - is this task currently executing on a CPU?
1088 * @p: the task in question.
1090 inline int task_curr(const struct task_struct *p)
1092 return cpu_curr(task_cpu(p)) == p;
1095 /* Used instead of source_load when we know the type == 0 */
1096 unsigned long weighted_cpuload(const int cpu)
1098 return cpu_rq(cpu)->raw_weighted_load;
1102 struct migration_req {
1103 struct list_head list;
1105 struct task_struct *task;
1108 struct completion done;
1112 * The task's runqueue lock must be held.
1113 * Returns true if you have to wait for migration thread.
1116 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1118 struct rq *rq = task_rq(p);
1120 vxm_migrate_task(p, rq, dest_cpu);
1122 * If the task is not on a runqueue (and not running), then
1123 * it is sufficient to simply update the task's cpu field.
1125 if (!p->array && !task_running(rq, p)) {
1126 set_task_cpu(p, dest_cpu);
1130 init_completion(&req->done);
1132 req->dest_cpu = dest_cpu;
1133 list_add(&req->list, &rq->migration_queue);
1139 * wait_task_inactive - wait for a thread to unschedule.
1141 * The caller must ensure that the task *will* unschedule sometime soon,
1142 * else this function might spin for a *long* time. This function can't
1143 * be called with interrupts off, or it may introduce deadlock with
1144 * smp_call_function() if an IPI is sent by the same process we are
1145 * waiting to become inactive.
1147 void wait_task_inactive(struct task_struct *p)
1149 unsigned long flags;
1154 rq = task_rq_lock(p, &flags);
1155 /* Must be off runqueue entirely, not preempted. */
1156 if (unlikely(p->array || task_running(rq, p))) {
1157 /* If it's preempted, we yield. It could be a while. */
1158 preempted = !task_running(rq, p);
1159 task_rq_unlock(rq, &flags);
1165 task_rq_unlock(rq, &flags);
1169 * kick_process - kick a running thread to enter/exit the kernel
1170 * @p: the to-be-kicked thread
1172 * Cause a process which is running on another CPU to enter
1173 * kernel-mode, without any delay. (to get signals handled.)
1175 * NOTE: this function doesnt have to take the runqueue lock,
1176 * because all it wants to ensure is that the remote task enters
1177 * the kernel. If the IPI races and the task has been migrated
1178 * to another CPU then no harm is done and the purpose has been
1181 void kick_process(struct task_struct *p)
1187 if ((cpu != smp_processor_id()) && task_curr(p))
1188 smp_send_reschedule(cpu);
1193 * Return a low guess at the load of a migration-source cpu weighted
1194 * according to the scheduling class and "nice" value.
1196 * We want to under-estimate the load of migration sources, to
1197 * balance conservatively.
1199 static inline unsigned long source_load(int cpu, int type)
1201 struct rq *rq = cpu_rq(cpu);
1204 return rq->raw_weighted_load;
1206 return min(rq->cpu_load[type-1], rq->raw_weighted_load);
1210 * Return a high guess at the load of a migration-target cpu weighted
1211 * according to the scheduling class and "nice" value.
1213 static inline unsigned long target_load(int cpu, int type)
1215 struct rq *rq = cpu_rq(cpu);
1218 return rq->raw_weighted_load;
1220 return max(rq->cpu_load[type-1], rq->raw_weighted_load);
1224 * Return the average load per task on the cpu's run queue
1226 static inline unsigned long cpu_avg_load_per_task(int cpu)
1228 struct rq *rq = cpu_rq(cpu);
1229 unsigned long n = rq->nr_running;
1231 return n ? rq->raw_weighted_load / n : SCHED_LOAD_SCALE;
1235 * find_idlest_group finds and returns the least busy CPU group within the
1238 static struct sched_group *
1239 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1241 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1242 unsigned long min_load = ULONG_MAX, this_load = 0;
1243 int load_idx = sd->forkexec_idx;
1244 int imbalance = 100 + (sd->imbalance_pct-100)/2;
1247 unsigned long load, avg_load;
1251 /* Skip over this group if it has no CPUs allowed */
1252 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
1255 local_group = cpu_isset(this_cpu, group->cpumask);
1257 /* Tally up the load of all CPUs in the group */
1260 for_each_cpu_mask(i, group->cpumask) {
1261 /* Bias balancing toward cpus of our domain */
1263 load = source_load(i, load_idx);
1265 load = target_load(i, load_idx);
1270 /* Adjust by relative CPU power of the group */
1271 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1274 this_load = avg_load;
1276 } else if (avg_load < min_load) {
1277 min_load = avg_load;
1281 group = group->next;
1282 } while (group != sd->groups);
1284 if (!idlest || 100*this_load < imbalance*min_load)
1290 * find_idlest_cpu - find the idlest cpu among the cpus in group.
1293 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
1296 unsigned long load, min_load = ULONG_MAX;
1300 /* Traverse only the allowed CPUs */
1301 cpus_and(tmp, group->cpumask, p->cpus_allowed);
1303 for_each_cpu_mask(i, tmp) {
1304 load = weighted_cpuload(i);
1306 if (load < min_load || (load == min_load && i == this_cpu)) {
1316 * sched_balance_self: balance the current task (running on cpu) in domains
1317 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1320 * Balance, ie. select the least loaded group.
1322 * Returns the target CPU number, or the same CPU if no balancing is needed.
1324 * preempt must be disabled.
1326 static int sched_balance_self(int cpu, int flag)
1328 struct task_struct *t = current;
1329 struct sched_domain *tmp, *sd = NULL;
1331 for_each_domain(cpu, tmp) {
1333 * If power savings logic is enabled for a domain, stop there.
1335 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
1337 if (tmp->flags & flag)
1343 struct sched_group *group;
1344 int new_cpu, weight;
1346 if (!(sd->flags & flag)) {
1352 group = find_idlest_group(sd, t, cpu);
1358 new_cpu = find_idlest_cpu(group, t, cpu);
1359 if (new_cpu == -1 || new_cpu == cpu) {
1360 /* Now try balancing at a lower domain level of cpu */
1365 /* Now try balancing at a lower domain level of new_cpu */
1368 weight = cpus_weight(span);
1369 for_each_domain(cpu, tmp) {
1370 if (weight <= cpus_weight(tmp->span))
1372 if (tmp->flags & flag)
1375 /* while loop will break here if sd == NULL */
1381 #endif /* CONFIG_SMP */
1384 * wake_idle() will wake a task on an idle cpu if task->cpu is
1385 * not idle and an idle cpu is available. The span of cpus to
1386 * search starts with cpus closest then further out as needed,
1387 * so we always favor a closer, idle cpu.
1389 * Returns the CPU we should wake onto.
1391 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1392 static int wake_idle(int cpu, struct task_struct *p)
1395 struct sched_domain *sd;
1401 for_each_domain(cpu, sd) {
1402 if (sd->flags & SD_WAKE_IDLE) {
1403 cpus_and(tmp, sd->span, p->cpus_allowed);
1404 for_each_cpu_mask(i, tmp) {
1415 static inline int wake_idle(int cpu, struct task_struct *p)
1422 * try_to_wake_up - wake up a thread
1423 * @p: the to-be-woken-up thread
1424 * @state: the mask of task states that can be woken
1425 * @sync: do a synchronous wakeup?
1427 * Put it on the run-queue if it's not already there. The "current"
1428 * thread is always on the run-queue (except when the actual
1429 * re-schedule is in progress), and as such you're allowed to do
1430 * the simpler "current->state = TASK_RUNNING" to mark yourself
1431 * runnable without the overhead of this.
1433 * returns failure only if the task is already active.
1435 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
1437 int cpu, this_cpu, success = 0;
1438 unsigned long flags;
1442 struct sched_domain *sd, *this_sd = NULL;
1443 unsigned long load, this_load;
1447 rq = task_rq_lock(p, &flags);
1448 old_state = p->state;
1450 /* we need to unhold suspended tasks */
1451 if (old_state & TASK_ONHOLD) {
1452 vx_unhold_task(p, rq);
1453 old_state = p->state;
1455 if (!(old_state & state))
1462 this_cpu = smp_processor_id();
1465 if (unlikely(task_running(rq, p)))
1470 schedstat_inc(rq, ttwu_cnt);
1471 if (cpu == this_cpu) {
1472 schedstat_inc(rq, ttwu_local);
1476 for_each_domain(this_cpu, sd) {
1477 if (cpu_isset(cpu, sd->span)) {
1478 schedstat_inc(sd, ttwu_wake_remote);
1484 if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1488 * Check for affine wakeup and passive balancing possibilities.
1491 int idx = this_sd->wake_idx;
1492 unsigned int imbalance;
1494 imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
1496 load = source_load(cpu, idx);
1497 this_load = target_load(this_cpu, idx);
1499 new_cpu = this_cpu; /* Wake to this CPU if we can */
1501 if (this_sd->flags & SD_WAKE_AFFINE) {
1502 unsigned long tl = this_load;
1503 unsigned long tl_per_task;
1505 tl_per_task = cpu_avg_load_per_task(this_cpu);
1508 * If sync wakeup then subtract the (maximum possible)
1509 * effect of the currently running task from the load
1510 * of the current CPU:
1513 tl -= current->load_weight;
1516 tl + target_load(cpu, idx) <= tl_per_task) ||
1517 100*(tl + p->load_weight) <= imbalance*load) {
1519 * This domain has SD_WAKE_AFFINE and
1520 * p is cache cold in this domain, and
1521 * there is no bad imbalance.
1523 schedstat_inc(this_sd, ttwu_move_affine);
1529 * Start passive balancing when half the imbalance_pct
1532 if (this_sd->flags & SD_WAKE_BALANCE) {
1533 if (imbalance*this_load <= 100*load) {
1534 schedstat_inc(this_sd, ttwu_move_balance);
1540 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1542 new_cpu = wake_idle(new_cpu, p);
1543 if (new_cpu != cpu) {
1544 set_task_cpu(p, new_cpu);
1545 task_rq_unlock(rq, &flags);
1546 /* might preempt at this point */
1547 rq = task_rq_lock(p, &flags);
1548 old_state = p->state;
1549 if (!(old_state & state))
1554 this_cpu = smp_processor_id();
1559 #endif /* CONFIG_SMP */
1560 if (old_state == TASK_UNINTERRUPTIBLE) {
1561 rq->nr_uninterruptible--;
1562 vx_uninterruptible_dec(p);
1564 * Tasks on involuntary sleep don't earn
1565 * sleep_avg beyond just interactive state.
1567 p->sleep_type = SLEEP_NONINTERACTIVE;
1571 * Tasks that have marked their sleep as noninteractive get
1572 * woken up with their sleep average not weighted in an
1575 if (old_state & TASK_NONINTERACTIVE)
1576 p->sleep_type = SLEEP_NONINTERACTIVE;
1579 activate_task(p, rq, cpu == this_cpu);
1581 * Sync wakeups (i.e. those types of wakeups where the waker
1582 * has indicated that it will leave the CPU in short order)
1583 * don't trigger a preemption, if the woken up task will run on
1584 * this cpu. (in this case the 'I will reschedule' promise of
1585 * the waker guarantees that the freshly woken up task is going
1586 * to be considered on this CPU.)
1588 if (!sync || cpu != this_cpu) {
1589 if (TASK_PREEMPTS_CURR(p, rq))
1590 resched_task(rq->curr);
1595 p->state = TASK_RUNNING;
1597 task_rq_unlock(rq, &flags);
1602 int fastcall wake_up_process(struct task_struct *p)
1604 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1605 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1607 EXPORT_SYMBOL(wake_up_process);
1609 int fastcall wake_up_state(struct task_struct *p, unsigned int state)
1611 return try_to_wake_up(p, state, 0);
1614 static void task_running_tick(struct rq *rq, struct task_struct *p, int cpu);
1616 * Perform scheduler related setup for a newly forked process p.
1617 * p is forked by current.
1619 void fastcall sched_fork(struct task_struct *p, int clone_flags)
1621 int cpu = get_cpu();
1624 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
1626 set_task_cpu(p, cpu);
1629 * We mark the process as running here, but have not actually
1630 * inserted it onto the runqueue yet. This guarantees that
1631 * nobody will actually run it, and a signal or other external
1632 * event cannot wake it up and insert it on the runqueue either.
1634 p->state = TASK_RUNNING;
1637 * Make sure we do not leak PI boosting priority to the child:
1639 p->prio = current->normal_prio;
1641 INIT_LIST_HEAD(&p->run_list);
1643 #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
1644 if (unlikely(sched_info_on()))
1645 memset(&p->sched_info, 0, sizeof(p->sched_info));
1647 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
1650 #ifdef CONFIG_PREEMPT
1651 /* Want to start with kernel preemption disabled. */
1652 task_thread_info(p)->preempt_count = 1;
1655 * Share the timeslice between parent and child, thus the
1656 * total amount of pending timeslices in the system doesn't change,
1657 * resulting in more scheduling fairness.
1659 local_irq_disable();
1660 p->time_slice = (current->time_slice + 1) >> 1;
1662 * The remainder of the first timeslice might be recovered by
1663 * the parent if the child exits early enough.
1665 p->first_time_slice = 1;
1666 current->time_slice >>= 1;
1667 p->timestamp = sched_clock();
1668 if (unlikely(!current->time_slice)) {
1670 * This case is rare, it happens when the parent has only
1671 * a single jiffy left from its timeslice. Taking the
1672 * runqueue lock is not a problem.
1674 current->time_slice = 1;
1675 task_running_tick(cpu_rq(cpu), current, cpu);
1682 * wake_up_new_task - wake up a newly created task for the first time.
1684 * This function will do some initial scheduler statistics housekeeping
1685 * that must be done for every newly created context, then puts the task
1686 * on the runqueue and wakes it.
1688 void fastcall wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
1690 struct rq *rq, *this_rq;
1691 unsigned long flags;
1694 rq = task_rq_lock(p, &flags);
1695 BUG_ON(p->state != TASK_RUNNING);
1696 this_cpu = smp_processor_id();
1700 * We decrease the sleep average of forking parents
1701 * and children as well, to keep max-interactive tasks
1702 * from forking tasks that are max-interactive. The parent
1703 * (current) is done further down, under its lock.
1705 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1706 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1708 p->prio = effective_prio(p);
1710 vx_activate_task(p);
1711 if (likely(cpu == this_cpu)) {
1712 if (!(clone_flags & CLONE_VM)) {
1714 * The VM isn't cloned, so we're in a good position to
1715 * do child-runs-first in anticipation of an exec. This
1716 * usually avoids a lot of COW overhead.
1718 if (unlikely(!current->array))
1719 __activate_task(p, rq);
1721 p->prio = current->prio;
1722 BUG_ON(p->state & TASK_ONHOLD);
1723 p->normal_prio = current->normal_prio;
1724 list_add_tail(&p->run_list, ¤t->run_list);
1725 p->array = current->array;
1726 p->array->nr_active++;
1727 inc_nr_running(p, rq);
1731 /* Run child last */
1732 __activate_task(p, rq);
1734 * We skip the following code due to cpu == this_cpu
1736 * task_rq_unlock(rq, &flags);
1737 * this_rq = task_rq_lock(current, &flags);
1741 this_rq = cpu_rq(this_cpu);
1744 * Not the local CPU - must adjust timestamp. This should
1745 * get optimised away in the !CONFIG_SMP case.
1747 p->timestamp = (p->timestamp - this_rq->most_recent_timestamp)
1748 + rq->most_recent_timestamp;
1749 __activate_task(p, rq);
1750 if (TASK_PREEMPTS_CURR(p, rq))
1751 resched_task(rq->curr);
1754 * Parent and child are on different CPUs, now get the
1755 * parent runqueue to update the parent's ->sleep_avg:
1757 task_rq_unlock(rq, &flags);
1758 this_rq = task_rq_lock(current, &flags);
1760 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1761 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1762 task_rq_unlock(this_rq, &flags);
1766 * Potentially available exiting-child timeslices are
1767 * retrieved here - this way the parent does not get
1768 * penalized for creating too many threads.
1770 * (this cannot be used to 'generate' timeslices
1771 * artificially, because any timeslice recovered here
1772 * was given away by the parent in the first place.)
1774 void fastcall sched_exit(struct task_struct *p)
1776 unsigned long flags;
1780 * If the child was a (relative-) CPU hog then decrease
1781 * the sleep_avg of the parent as well.
1783 rq = task_rq_lock(p->parent, &flags);
1784 if (p->first_time_slice && task_cpu(p) == task_cpu(p->parent)) {
1785 p->parent->time_slice += p->time_slice;
1786 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1787 p->parent->time_slice = task_timeslice(p);
1789 if (p->sleep_avg < p->parent->sleep_avg)
1790 p->parent->sleep_avg = p->parent->sleep_avg /
1791 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1793 task_rq_unlock(rq, &flags);
1797 * prepare_task_switch - prepare to switch tasks
1798 * @rq: the runqueue preparing to switch
1799 * @next: the task we are going to switch to.
1801 * This is called with the rq lock held and interrupts off. It must
1802 * be paired with a subsequent finish_task_switch after the context
1805 * prepare_task_switch sets up locking and calls architecture specific
1808 static inline void prepare_task_switch(struct rq *rq, struct task_struct *next)
1810 prepare_lock_switch(rq, next);
1811 prepare_arch_switch(next);
1815 * finish_task_switch - clean up after a task-switch
1816 * @rq: runqueue associated with task-switch
1817 * @prev: the thread we just switched away from.
1819 * finish_task_switch must be called after the context switch, paired
1820 * with a prepare_task_switch call before the context switch.
1821 * finish_task_switch will reconcile locking set up by prepare_task_switch,
1822 * and do any other architecture-specific cleanup actions.
1824 * Note that we may have delayed dropping an mm in context_switch(). If
1825 * so, we finish that here outside of the runqueue lock. (Doing it
1826 * with the lock held can cause deadlocks; see schedule() for
1829 static inline void finish_task_switch(struct rq *rq, struct task_struct *prev)
1830 __releases(rq->lock)
1832 struct mm_struct *mm = rq->prev_mm;
1838 * A task struct has one reference for the use as "current".
1839 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
1840 * schedule one last time. The schedule call will never return, and
1841 * the scheduled task must drop that reference.
1842 * The test for TASK_DEAD must occur while the runqueue locks are
1843 * still held, otherwise prev could be scheduled on another cpu, die
1844 * there before we look at prev->state, and then the reference would
1846 * Manfred Spraul <manfred@colorfullife.com>
1848 prev_state = prev->state;
1849 finish_arch_switch(prev);
1850 finish_lock_switch(rq, prev);
1853 if (unlikely(prev_state == TASK_DEAD)) {
1855 * Remove function-return probe instances associated with this
1856 * task and put them back on the free list.
1858 kprobe_flush_task(prev);
1859 put_task_struct(prev);
1864 * schedule_tail - first thing a freshly forked thread must call.
1865 * @prev: the thread we just switched away from.
1867 asmlinkage void schedule_tail(struct task_struct *prev)
1868 __releases(rq->lock)
1870 struct rq *rq = this_rq();
1872 finish_task_switch(rq, prev);
1873 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
1874 /* In this case, finish_task_switch does not reenable preemption */
1877 if (current->set_child_tid)
1878 put_user(current->pid, current->set_child_tid);
1882 * context_switch - switch to the new MM and the new
1883 * thread's register state.
1885 static inline struct task_struct *
1886 context_switch(struct rq *rq, struct task_struct *prev,
1887 struct task_struct *next)
1889 struct mm_struct *mm = next->mm;
1890 struct mm_struct *oldmm = prev->active_mm;
1893 next->active_mm = oldmm;
1894 atomic_inc(&oldmm->mm_count);
1895 enter_lazy_tlb(oldmm, next);
1897 switch_mm(oldmm, mm, next);
1900 prev->active_mm = NULL;
1901 WARN_ON(rq->prev_mm);
1902 rq->prev_mm = oldmm;
1905 * Since the runqueue lock will be released by the next
1906 * task (which is an invalid locking op but in the case
1907 * of the scheduler it's an obvious special-case), so we
1908 * do an early lockdep release here:
1910 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
1911 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
1914 /* Here we just switch the register state and the stack. */
1915 switch_to(prev, next, prev);
1921 * nr_running, nr_uninterruptible and nr_context_switches:
1923 * externally visible scheduler statistics: current number of runnable
1924 * threads, current number of uninterruptible-sleeping threads, total
1925 * number of context switches performed since bootup.
1927 unsigned long nr_running(void)
1929 unsigned long i, sum = 0;
1931 for_each_online_cpu(i)
1932 sum += cpu_rq(i)->nr_running;
1937 unsigned long nr_uninterruptible(void)
1939 unsigned long i, sum = 0;
1941 for_each_possible_cpu(i)
1942 sum += cpu_rq(i)->nr_uninterruptible;
1945 * Since we read the counters lockless, it might be slightly
1946 * inaccurate. Do not allow it to go below zero though:
1948 if (unlikely((long)sum < 0))
1954 unsigned long long nr_context_switches(void)
1957 unsigned long long sum = 0;
1959 for_each_possible_cpu(i)
1960 sum += cpu_rq(i)->nr_switches;
1965 unsigned long nr_iowait(void)
1967 unsigned long i, sum = 0;
1969 for_each_possible_cpu(i)
1970 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1975 unsigned long nr_active(void)
1977 unsigned long i, running = 0, uninterruptible = 0;
1979 for_each_online_cpu(i) {
1980 running += cpu_rq(i)->nr_running;
1981 uninterruptible += cpu_rq(i)->nr_uninterruptible;
1984 if (unlikely((long)uninterruptible < 0))
1985 uninterruptible = 0;
1987 return running + uninterruptible;
1993 * Is this task likely cache-hot:
1996 task_hot(struct task_struct *p, unsigned long long now, struct sched_domain *sd)
1998 return (long long)(now - p->last_ran) < (long long)sd->cache_hot_time;
2002 * double_rq_lock - safely lock two runqueues
2004 * Note this does not disable interrupts like task_rq_lock,
2005 * you need to do so manually before calling.
2007 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
2008 __acquires(rq1->lock)
2009 __acquires(rq2->lock)
2011 BUG_ON(!irqs_disabled());
2013 spin_lock(&rq1->lock);
2014 __acquire(rq2->lock); /* Fake it out ;) */
2017 spin_lock(&rq1->lock);
2018 spin_lock(&rq2->lock);
2020 spin_lock(&rq2->lock);
2021 spin_lock(&rq1->lock);
2027 * double_rq_unlock - safely unlock two runqueues
2029 * Note this does not restore interrupts like task_rq_unlock,
2030 * you need to do so manually after calling.
2032 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
2033 __releases(rq1->lock)
2034 __releases(rq2->lock)
2036 spin_unlock(&rq1->lock);
2038 spin_unlock(&rq2->lock);
2040 __release(rq2->lock);
2044 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
2046 static void double_lock_balance(struct rq *this_rq, struct rq *busiest)
2047 __releases(this_rq->lock)
2048 __acquires(busiest->lock)
2049 __acquires(this_rq->lock)
2051 if (unlikely(!irqs_disabled())) {
2052 /* printk() doesn't work good under rq->lock */
2053 spin_unlock(&this_rq->lock);
2056 if (unlikely(!spin_trylock(&busiest->lock))) {
2057 if (busiest < this_rq) {
2058 spin_unlock(&this_rq->lock);
2059 spin_lock(&busiest->lock);
2060 spin_lock(&this_rq->lock);
2062 spin_lock(&busiest->lock);
2067 * If dest_cpu is allowed for this process, migrate the task to it.
2068 * This is accomplished by forcing the cpu_allowed mask to only
2069 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
2070 * the cpu_allowed mask is restored.
2072 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
2074 struct migration_req req;
2075 unsigned long flags;
2078 rq = task_rq_lock(p, &flags);
2079 if (!cpu_isset(dest_cpu, p->cpus_allowed)
2080 || unlikely(cpu_is_offline(dest_cpu)))
2083 /* force the process onto the specified CPU */
2084 if (migrate_task(p, dest_cpu, &req)) {
2085 /* Need to wait for migration thread (might exit: take ref). */
2086 struct task_struct *mt = rq->migration_thread;
2088 get_task_struct(mt);
2089 task_rq_unlock(rq, &flags);
2090 wake_up_process(mt);
2091 put_task_struct(mt);
2092 wait_for_completion(&req.done);
2097 task_rq_unlock(rq, &flags);
2101 * sched_exec - execve() is a valuable balancing opportunity, because at
2102 * this point the task has the smallest effective memory and cache footprint.
2104 void sched_exec(void)
2106 int new_cpu, this_cpu = get_cpu();
2107 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
2109 if (new_cpu != this_cpu)
2110 sched_migrate_task(current, new_cpu);
2114 * pull_task - move a task from a remote runqueue to the local runqueue.
2115 * Both runqueues must be locked.
2117 static void pull_task(struct rq *src_rq, struct prio_array *src_array,
2118 struct task_struct *p, struct rq *this_rq,
2119 struct prio_array *this_array, int this_cpu)
2121 dequeue_task(p, src_array);
2122 dec_nr_running(p, src_rq);
2123 set_task_cpu(p, this_cpu);
2124 inc_nr_running(p, this_rq);
2125 enqueue_task(p, this_array);
2126 p->timestamp = (p->timestamp - src_rq->most_recent_timestamp)
2127 + this_rq->most_recent_timestamp;
2129 * Note that idle threads have a prio of MAX_PRIO, for this test
2130 * to be always true for them.
2132 if (TASK_PREEMPTS_CURR(p, this_rq))
2133 resched_task(this_rq->curr);
2137 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2140 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
2141 struct sched_domain *sd, enum idle_type idle,
2145 * We do not migrate tasks that are:
2146 * 1) running (obviously), or
2147 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2148 * 3) are cache-hot on their current CPU.
2150 if (!cpu_isset(this_cpu, p->cpus_allowed))
2154 if (task_running(rq, p))
2158 * Aggressive migration if:
2159 * 1) task is cache cold, or
2160 * 2) too many balance attempts have failed.
2163 if (sd->nr_balance_failed > sd->cache_nice_tries) {
2164 #ifdef CONFIG_SCHEDSTATS
2165 if (task_hot(p, rq->most_recent_timestamp, sd))
2166 schedstat_inc(sd, lb_hot_gained[idle]);
2171 if (task_hot(p, rq->most_recent_timestamp, sd))
2176 #define rq_best_prio(rq) min((rq)->curr->prio, (rq)->best_expired_prio)
2179 * move_tasks tries to move up to max_nr_move tasks and max_load_move weighted
2180 * load from busiest to this_rq, as part of a balancing operation within
2181 * "domain". Returns the number of tasks moved.
2183 * Called with both runqueues locked.
2185 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2186 unsigned long max_nr_move, unsigned long max_load_move,
2187 struct sched_domain *sd, enum idle_type idle,
2190 int idx, pulled = 0, pinned = 0, this_best_prio, best_prio,
2191 best_prio_seen, skip_for_load;
2192 struct prio_array *array, *dst_array;
2193 struct list_head *head, *curr;
2194 struct task_struct *tmp;
2197 if (max_nr_move == 0 || max_load_move == 0)
2200 rem_load_move = max_load_move;
2202 this_best_prio = rq_best_prio(this_rq);
2203 best_prio = rq_best_prio(busiest);
2205 * Enable handling of the case where there is more than one task
2206 * with the best priority. If the current running task is one
2207 * of those with prio==best_prio we know it won't be moved
2208 * and therefore it's safe to override the skip (based on load) of
2209 * any task we find with that prio.
2211 best_prio_seen = best_prio == busiest->curr->prio;
2214 * We first consider expired tasks. Those will likely not be
2215 * executed in the near future, and they are most likely to
2216 * be cache-cold, thus switching CPUs has the least effect
2219 if (busiest->expired->nr_active) {
2220 array = busiest->expired;
2221 dst_array = this_rq->expired;
2223 array = busiest->active;
2224 dst_array = this_rq->active;
2228 /* Start searching at priority 0: */
2232 idx = sched_find_first_bit(array->bitmap);
2234 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
2235 if (idx >= MAX_PRIO) {
2236 if (array == busiest->expired && busiest->active->nr_active) {
2237 array = busiest->active;
2238 dst_array = this_rq->active;
2244 head = array->queue + idx;
2247 tmp = list_entry(curr, struct task_struct, run_list);
2252 * To help distribute high priority tasks accross CPUs we don't
2253 * skip a task if it will be the highest priority task (i.e. smallest
2254 * prio value) on its new queue regardless of its load weight
2256 skip_for_load = tmp->load_weight > rem_load_move;
2257 if (skip_for_load && idx < this_best_prio)
2258 skip_for_load = !best_prio_seen && idx == best_prio;
2259 if (skip_for_load ||
2260 !can_migrate_task(tmp, busiest, this_cpu, sd, idle, &pinned)) {
2262 best_prio_seen |= idx == best_prio;
2269 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
2271 rem_load_move -= tmp->load_weight;
2274 * We only want to steal up to the prescribed number of tasks
2275 * and the prescribed amount of weighted load.
2277 if (pulled < max_nr_move && rem_load_move > 0) {
2278 if (idx < this_best_prio)
2279 this_best_prio = idx;
2287 * Right now, this is the only place pull_task() is called,
2288 * so we can safely collect pull_task() stats here rather than
2289 * inside pull_task().
2291 schedstat_add(sd, lb_gained[idle], pulled);
2294 *all_pinned = pinned;
2299 * find_busiest_group finds and returns the busiest CPU group within the
2300 * domain. It calculates and returns the amount of weighted load which
2301 * should be moved to restore balance via the imbalance parameter.
2303 static struct sched_group *
2304 find_busiest_group(struct sched_domain *sd, int this_cpu,
2305 unsigned long *imbalance, enum idle_type idle, int *sd_idle,
2306 cpumask_t *cpus, int *balance)
2308 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2309 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2310 unsigned long max_pull;
2311 unsigned long busiest_load_per_task, busiest_nr_running;
2312 unsigned long this_load_per_task, this_nr_running;
2314 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2315 int power_savings_balance = 1;
2316 unsigned long leader_nr_running = 0, min_load_per_task = 0;
2317 unsigned long min_nr_running = ULONG_MAX;
2318 struct sched_group *group_min = NULL, *group_leader = NULL;
2321 max_load = this_load = total_load = total_pwr = 0;
2322 busiest_load_per_task = busiest_nr_running = 0;
2323 this_load_per_task = this_nr_running = 0;
2324 if (idle == NOT_IDLE)
2325 load_idx = sd->busy_idx;
2326 else if (idle == NEWLY_IDLE)
2327 load_idx = sd->newidle_idx;
2329 load_idx = sd->idle_idx;
2332 unsigned long load, group_capacity;
2335 unsigned int balance_cpu = -1, first_idle_cpu = 0;
2336 unsigned long sum_nr_running, sum_weighted_load;
2338 local_group = cpu_isset(this_cpu, group->cpumask);
2341 balance_cpu = first_cpu(group->cpumask);
2343 /* Tally up the load of all CPUs in the group */
2344 sum_weighted_load = sum_nr_running = avg_load = 0;
2346 for_each_cpu_mask(i, group->cpumask) {
2349 if (!cpu_isset(i, *cpus))
2354 if (*sd_idle && !idle_cpu(i))
2357 /* Bias balancing toward cpus of our domain */
2359 if (idle_cpu(i) && !first_idle_cpu) {
2364 load = target_load(i, load_idx);
2366 load = source_load(i, load_idx);
2369 sum_nr_running += rq->nr_running;
2370 sum_weighted_load += rq->raw_weighted_load;
2374 * First idle cpu or the first cpu(busiest) in this sched group
2375 * is eligible for doing load balancing at this and above
2378 if (local_group && balance_cpu != this_cpu && balance) {
2383 total_load += avg_load;
2384 total_pwr += group->cpu_power;
2386 /* Adjust by relative CPU power of the group */
2387 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
2389 group_capacity = group->cpu_power / SCHED_LOAD_SCALE;
2392 this_load = avg_load;
2394 this_nr_running = sum_nr_running;
2395 this_load_per_task = sum_weighted_load;
2396 } else if (avg_load > max_load &&
2397 sum_nr_running > group_capacity) {
2398 max_load = avg_load;
2400 busiest_nr_running = sum_nr_running;
2401 busiest_load_per_task = sum_weighted_load;
2404 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2406 * Busy processors will not participate in power savings
2409 if (idle == NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
2413 * If the local group is idle or completely loaded
2414 * no need to do power savings balance at this domain
2416 if (local_group && (this_nr_running >= group_capacity ||
2418 power_savings_balance = 0;
2421 * If a group is already running at full capacity or idle,
2422 * don't include that group in power savings calculations
2424 if (!power_savings_balance || sum_nr_running >= group_capacity
2429 * Calculate the group which has the least non-idle load.
2430 * This is the group from where we need to pick up the load
2433 if ((sum_nr_running < min_nr_running) ||
2434 (sum_nr_running == min_nr_running &&
2435 first_cpu(group->cpumask) <
2436 first_cpu(group_min->cpumask))) {
2438 min_nr_running = sum_nr_running;
2439 min_load_per_task = sum_weighted_load /
2444 * Calculate the group which is almost near its
2445 * capacity but still has some space to pick up some load
2446 * from other group and save more power
2448 if (sum_nr_running <= group_capacity - 1) {
2449 if (sum_nr_running > leader_nr_running ||
2450 (sum_nr_running == leader_nr_running &&
2451 first_cpu(group->cpumask) >
2452 first_cpu(group_leader->cpumask))) {
2453 group_leader = group;
2454 leader_nr_running = sum_nr_running;
2459 group = group->next;
2460 } while (group != sd->groups);
2462 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
2465 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2467 if (this_load >= avg_load ||
2468 100*max_load <= sd->imbalance_pct*this_load)
2471 busiest_load_per_task /= busiest_nr_running;
2473 * We're trying to get all the cpus to the average_load, so we don't
2474 * want to push ourselves above the average load, nor do we wish to
2475 * reduce the max loaded cpu below the average load, as either of these
2476 * actions would just result in more rebalancing later, and ping-pong
2477 * tasks around. Thus we look for the minimum possible imbalance.
2478 * Negative imbalances (*we* are more loaded than anyone else) will
2479 * be counted as no imbalance for these purposes -- we can't fix that
2480 * by pulling tasks to us. Be careful of negative numbers as they'll
2481 * appear as very large values with unsigned longs.
2483 if (max_load <= busiest_load_per_task)
2487 * In the presence of smp nice balancing, certain scenarios can have
2488 * max load less than avg load(as we skip the groups at or below
2489 * its cpu_power, while calculating max_load..)
2491 if (max_load < avg_load) {
2493 goto small_imbalance;
2496 /* Don't want to pull so many tasks that a group would go idle */
2497 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
2499 /* How much load to actually move to equalise the imbalance */
2500 *imbalance = min(max_pull * busiest->cpu_power,
2501 (avg_load - this_load) * this->cpu_power)
2505 * if *imbalance is less than the average load per runnable task
2506 * there is no gaurantee that any tasks will be moved so we'll have
2507 * a think about bumping its value to force at least one task to be
2510 if (*imbalance < busiest_load_per_task) {
2511 unsigned long tmp, pwr_now, pwr_move;
2515 pwr_move = pwr_now = 0;
2517 if (this_nr_running) {
2518 this_load_per_task /= this_nr_running;
2519 if (busiest_load_per_task > this_load_per_task)
2522 this_load_per_task = SCHED_LOAD_SCALE;
2524 if (max_load - this_load >= busiest_load_per_task * imbn) {
2525 *imbalance = busiest_load_per_task;
2530 * OK, we don't have enough imbalance to justify moving tasks,
2531 * however we may be able to increase total CPU power used by
2535 pwr_now += busiest->cpu_power *
2536 min(busiest_load_per_task, max_load);
2537 pwr_now += this->cpu_power *
2538 min(this_load_per_task, this_load);
2539 pwr_now /= SCHED_LOAD_SCALE;
2541 /* Amount of load we'd subtract */
2542 tmp = busiest_load_per_task * SCHED_LOAD_SCALE /
2545 pwr_move += busiest->cpu_power *
2546 min(busiest_load_per_task, max_load - tmp);
2548 /* Amount of load we'd add */
2549 if (max_load * busiest->cpu_power <
2550 busiest_load_per_task * SCHED_LOAD_SCALE)
2551 tmp = max_load * busiest->cpu_power / this->cpu_power;
2553 tmp = busiest_load_per_task * SCHED_LOAD_SCALE /
2555 pwr_move += this->cpu_power *
2556 min(this_load_per_task, this_load + tmp);
2557 pwr_move /= SCHED_LOAD_SCALE;
2559 /* Move if we gain throughput */
2560 if (pwr_move <= pwr_now)
2563 *imbalance = busiest_load_per_task;
2569 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2570 if (idle == NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
2573 if (this == group_leader && group_leader != group_min) {
2574 *imbalance = min_load_per_task;
2584 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2587 find_busiest_queue(struct sched_group *group, enum idle_type idle,
2588 unsigned long imbalance, cpumask_t *cpus)
2590 struct rq *busiest = NULL, *rq;
2591 unsigned long max_load = 0;
2594 for_each_cpu_mask(i, group->cpumask) {
2596 if (!cpu_isset(i, *cpus))
2601 if (rq->nr_running == 1 && rq->raw_weighted_load > imbalance)
2604 if (rq->raw_weighted_load > max_load) {
2605 max_load = rq->raw_weighted_load;
2614 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2615 * so long as it is large enough.
2617 #define MAX_PINNED_INTERVAL 512
2619 static inline unsigned long minus_1_or_zero(unsigned long n)
2621 return n > 0 ? n - 1 : 0;
2625 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2626 * tasks if there is an imbalance.
2628 static int load_balance(int this_cpu, struct rq *this_rq,
2629 struct sched_domain *sd, enum idle_type idle,
2632 int nr_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
2633 struct sched_group *group;
2634 unsigned long imbalance;
2636 cpumask_t cpus = CPU_MASK_ALL;
2637 unsigned long flags;
2640 * When power savings policy is enabled for the parent domain, idle
2641 * sibling can pick up load irrespective of busy siblings. In this case,
2642 * let the state of idle sibling percolate up as IDLE, instead of
2643 * portraying it as NOT_IDLE.
2645 if (idle != NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
2646 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2649 schedstat_inc(sd, lb_cnt[idle]);
2652 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle,
2659 schedstat_inc(sd, lb_nobusyg[idle]);
2663 busiest = find_busiest_queue(group, idle, imbalance, &cpus);
2665 schedstat_inc(sd, lb_nobusyq[idle]);
2669 BUG_ON(busiest == this_rq);
2671 schedstat_add(sd, lb_imbalance[idle], imbalance);
2674 if (busiest->nr_running > 1) {
2676 * Attempt to move tasks. If find_busiest_group has found
2677 * an imbalance but busiest->nr_running <= 1, the group is
2678 * still unbalanced. nr_moved simply stays zero, so it is
2679 * correctly treated as an imbalance.
2681 local_irq_save(flags);
2682 double_rq_lock(this_rq, busiest);
2683 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2684 minus_1_or_zero(busiest->nr_running),
2685 imbalance, sd, idle, &all_pinned);
2686 double_rq_unlock(this_rq, busiest);
2687 local_irq_restore(flags);
2689 /* All tasks on this runqueue were pinned by CPU affinity */
2690 if (unlikely(all_pinned)) {
2691 cpu_clear(cpu_of(busiest), cpus);
2692 if (!cpus_empty(cpus))
2699 schedstat_inc(sd, lb_failed[idle]);
2700 sd->nr_balance_failed++;
2702 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2704 spin_lock_irqsave(&busiest->lock, flags);
2706 /* don't kick the migration_thread, if the curr
2707 * task on busiest cpu can't be moved to this_cpu
2709 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
2710 spin_unlock_irqrestore(&busiest->lock, flags);
2712 goto out_one_pinned;
2715 if (!busiest->active_balance) {
2716 busiest->active_balance = 1;
2717 busiest->push_cpu = this_cpu;
2720 spin_unlock_irqrestore(&busiest->lock, flags);
2722 wake_up_process(busiest->migration_thread);
2725 * We've kicked active balancing, reset the failure
2728 sd->nr_balance_failed = sd->cache_nice_tries+1;
2731 sd->nr_balance_failed = 0;
2733 if (likely(!active_balance)) {
2734 /* We were unbalanced, so reset the balancing interval */
2735 sd->balance_interval = sd->min_interval;
2738 * If we've begun active balancing, start to back off. This
2739 * case may not be covered by the all_pinned logic if there
2740 * is only 1 task on the busy runqueue (because we don't call
2743 if (sd->balance_interval < sd->max_interval)
2744 sd->balance_interval *= 2;
2747 if (!nr_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2748 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2753 schedstat_inc(sd, lb_balanced[idle]);
2755 sd->nr_balance_failed = 0;
2758 /* tune up the balancing interval */
2759 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
2760 (sd->balance_interval < sd->max_interval))
2761 sd->balance_interval *= 2;
2763 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2764 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2770 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2771 * tasks if there is an imbalance.
2773 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2774 * this_rq is locked.
2777 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
2779 struct sched_group *group;
2780 struct rq *busiest = NULL;
2781 unsigned long imbalance;
2784 cpumask_t cpus = CPU_MASK_ALL;
2787 * When power savings policy is enabled for the parent domain, idle
2788 * sibling can pick up load irrespective of busy siblings. In this case,
2789 * let the state of idle sibling percolate up as IDLE, instead of
2790 * portraying it as NOT_IDLE.
2792 if (sd->flags & SD_SHARE_CPUPOWER &&
2793 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2796 schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2798 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE,
2799 &sd_idle, &cpus, NULL);
2801 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2805 busiest = find_busiest_queue(group, NEWLY_IDLE, imbalance,
2808 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2812 BUG_ON(busiest == this_rq);
2814 schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2817 if (busiest->nr_running > 1) {
2818 /* Attempt to move tasks */
2819 double_lock_balance(this_rq, busiest);
2820 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2821 minus_1_or_zero(busiest->nr_running),
2822 imbalance, sd, NEWLY_IDLE, NULL);
2823 spin_unlock(&busiest->lock);
2826 cpu_clear(cpu_of(busiest), cpus);
2827 if (!cpus_empty(cpus))
2833 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2834 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2835 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2838 sd->nr_balance_failed = 0;
2843 schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
2844 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2845 !test_sd_parent(sd, SD_POWERSAVINGS_BALANCE))
2847 sd->nr_balance_failed = 0;
2853 * idle_balance is called by schedule() if this_cpu is about to become
2854 * idle. Attempts to pull tasks from other CPUs.
2856 static void idle_balance(int this_cpu, struct rq *this_rq)
2858 struct sched_domain *sd;
2859 int pulled_task = 0;
2860 unsigned long next_balance = jiffies + 60 * HZ;
2862 for_each_domain(this_cpu, sd) {
2863 if (sd->flags & SD_BALANCE_NEWIDLE) {
2864 /* If we've pulled tasks over stop searching: */
2865 pulled_task = load_balance_newidle(this_cpu,
2867 if (time_after(next_balance,
2868 sd->last_balance + sd->balance_interval))
2869 next_balance = sd->last_balance
2870 + sd->balance_interval;
2877 * We are going idle. next_balance may be set based on
2878 * a busy processor. So reset next_balance.
2880 this_rq->next_balance = next_balance;
2884 * active_load_balance is run by migration threads. It pushes running tasks
2885 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2886 * running on each physical CPU where possible, and avoids physical /
2887 * logical imbalances.
2889 * Called with busiest_rq locked.
2891 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
2893 int target_cpu = busiest_rq->push_cpu;
2894 struct sched_domain *sd;
2895 struct rq *target_rq;
2897 /* Is there any task to move? */
2898 if (busiest_rq->nr_running <= 1)
2901 target_rq = cpu_rq(target_cpu);
2904 * This condition is "impossible", if it occurs
2905 * we need to fix it. Originally reported by
2906 * Bjorn Helgaas on a 128-cpu setup.
2908 BUG_ON(busiest_rq == target_rq);
2910 /* move a task from busiest_rq to target_rq */
2911 double_lock_balance(busiest_rq, target_rq);
2913 /* Search for an sd spanning us and the target CPU. */
2914 for_each_domain(target_cpu, sd) {
2915 if ((sd->flags & SD_LOAD_BALANCE) &&
2916 cpu_isset(busiest_cpu, sd->span))
2921 schedstat_inc(sd, alb_cnt);
2923 if (move_tasks(target_rq, target_cpu, busiest_rq, 1,
2924 RTPRIO_TO_LOAD_WEIGHT(100), sd, SCHED_IDLE,
2926 schedstat_inc(sd, alb_pushed);
2928 schedstat_inc(sd, alb_failed);
2930 spin_unlock(&target_rq->lock);
2933 static void update_load(struct rq *this_rq)
2935 unsigned long this_load;
2938 this_load = this_rq->raw_weighted_load;
2940 /* Update our load: */
2941 for (i = 0, scale = 1; i < 3; i++, scale <<= 1) {
2942 unsigned long old_load, new_load;
2944 old_load = this_rq->cpu_load[i];
2945 new_load = this_load;
2947 * Round up the averaging division if load is increasing. This
2948 * prevents us from getting stuck on 9 if the load is 10, for
2951 if (new_load > old_load)
2952 new_load += scale-1;
2953 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) / scale;
2958 * run_rebalance_domains is triggered when needed from the scheduler tick.
2960 * It checks each scheduling domain to see if it is due to be balanced,
2961 * and initiates a balancing operation if so.
2963 * Balancing parameters are set up in arch_init_sched_domains.
2965 static DEFINE_SPINLOCK(balancing);
2967 static void run_rebalance_domains(struct softirq_action *h)
2969 int this_cpu = smp_processor_id(), balance = 1;
2970 struct rq *this_rq = cpu_rq(this_cpu);
2971 unsigned long interval;
2972 struct sched_domain *sd;
2974 * We are idle if there are no processes running. This
2975 * is valid even if we are the idle process (SMT).
2977 enum idle_type idle = !this_rq->nr_running ?
2978 SCHED_IDLE : NOT_IDLE;
2979 /* Earliest time when we have to call run_rebalance_domains again */
2980 unsigned long next_balance = jiffies + 60*HZ;
2982 for_each_domain(this_cpu, sd) {
2983 if (!(sd->flags & SD_LOAD_BALANCE))
2986 interval = sd->balance_interval;
2987 if (idle != SCHED_IDLE)
2988 interval *= sd->busy_factor;
2990 /* scale ms to jiffies */
2991 interval = msecs_to_jiffies(interval);
2992 if (unlikely(!interval))
2995 if (sd->flags & SD_SERIALIZE) {
2996 if (!spin_trylock(&balancing))
3000 if (time_after_eq(jiffies, sd->last_balance + interval)) {
3001 if (load_balance(this_cpu, this_rq, sd, idle, &balance)) {
3003 * We've pulled tasks over so either we're no
3004 * longer idle, or one of our SMT siblings is
3009 sd->last_balance = jiffies;
3011 if (sd->flags & SD_SERIALIZE)
3012 spin_unlock(&balancing);
3014 if (time_after(next_balance, sd->last_balance + interval))
3015 next_balance = sd->last_balance + interval;
3018 * Stop the load balance at this level. There is another
3019 * CPU in our sched group which is doing load balancing more
3025 this_rq->next_balance = next_balance;
3029 * on UP we do not need to balance between CPUs:
3031 static inline void idle_balance(int cpu, struct rq *rq)
3036 static inline void wake_priority_sleeper(struct rq *rq)
3038 #ifdef CONFIG_SCHED_SMT
3039 if (!rq->nr_running)
3042 spin_lock(&rq->lock);
3044 * If an SMT sibling task has been put to sleep for priority
3045 * reasons reschedule the idle task to see if it can now run.
3048 resched_task(rq->idle);
3049 spin_unlock(&rq->lock);
3053 DEFINE_PER_CPU(struct kernel_stat, kstat);
3055 EXPORT_PER_CPU_SYMBOL(kstat);
3058 * This is called on clock ticks and on context switches.
3059 * Bank in p->sched_time the ns elapsed since the last tick or switch.
3062 update_cpu_clock(struct task_struct *p, struct rq *rq, unsigned long long now)
3064 p->sched_time += now - p->last_ran;
3065 p->last_ran = rq->most_recent_timestamp = now;
3069 * Return current->sched_time plus any more ns on the sched_clock
3070 * that have not yet been banked.
3072 unsigned long long current_sched_time(const struct task_struct *p)
3074 unsigned long long ns;
3075 unsigned long flags;
3077 local_irq_save(flags);
3078 ns = p->sched_time + sched_clock() - p->last_ran;
3079 local_irq_restore(flags);
3085 * We place interactive tasks back into the active array, if possible.
3087 * To guarantee that this does not starve expired tasks we ignore the
3088 * interactivity of a task if the first expired task had to wait more
3089 * than a 'reasonable' amount of time. This deadline timeout is
3090 * load-dependent, as the frequency of array switched decreases with
3091 * increasing number of running tasks. We also ignore the interactivity
3092 * if a better static_prio task has expired:
3094 static inline int expired_starving(struct rq *rq)
3096 if (rq->curr->static_prio > rq->best_expired_prio)
3098 if (!STARVATION_LIMIT || !rq->expired_timestamp)
3100 if (jiffies - rq->expired_timestamp > STARVATION_LIMIT * rq->nr_running)
3106 * Account user cpu time to a process.
3107 * @p: the process that the cpu time gets accounted to
3108 * @hardirq_offset: the offset to subtract from hardirq_count()
3109 * @cputime: the cpu time spent in user space since the last update
3111 void account_user_time(struct task_struct *p, cputime_t cputime)
3113 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3114 struct vx_info *vxi = p->vx_info; /* p is _always_ current */
3116 int nice = (TASK_NICE(p) > 0);
3118 p->utime = cputime_add(p->utime, cputime);
3119 vx_account_user(vxi, cputime, nice);
3121 /* Add user time to cpustat. */
3122 tmp = cputime_to_cputime64(cputime);
3124 cpustat->nice = cputime64_add(cpustat->nice, tmp);
3126 cpustat->user = cputime64_add(cpustat->user, tmp);
3130 * Account system cpu time to a process.
3131 * @p: the process that the cpu time gets accounted to
3132 * @hardirq_offset: the offset to subtract from hardirq_count()
3133 * @cputime: the cpu time spent in kernel space since the last update
3135 void account_system_time(struct task_struct *p, int hardirq_offset,
3138 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3139 struct vx_info *vxi = p->vx_info; /* p is _always_ current */
3140 struct rq *rq = this_rq();
3143 p->stime = cputime_add(p->stime, cputime);
3144 vx_account_system(vxi, cputime, (p == rq->idle));
3146 /* Add system time to cpustat. */
3147 tmp = cputime_to_cputime64(cputime);
3148 if (hardirq_count() - hardirq_offset)
3149 cpustat->irq = cputime64_add(cpustat->irq, tmp);
3150 else if (softirq_count())
3151 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
3152 else if (p != rq->idle)
3153 cpustat->system = cputime64_add(cpustat->system, tmp);
3154 else if (atomic_read(&rq->nr_iowait) > 0)
3155 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3157 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3158 /* Account for system time used */
3159 acct_update_integrals(p);
3163 * Account for involuntary wait time.
3164 * @p: the process from which the cpu time has been stolen
3165 * @steal: the cpu time spent in involuntary wait
3167 void account_steal_time(struct task_struct *p, cputime_t steal)
3169 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
3170 cputime64_t tmp = cputime_to_cputime64(steal);
3171 struct rq *rq = this_rq();
3173 if (p == rq->idle) {
3174 p->stime = cputime_add(p->stime, steal);
3175 if (atomic_read(&rq->nr_iowait) > 0)
3176 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
3178 cpustat->idle = cputime64_add(cpustat->idle, tmp);
3180 cpustat->steal = cputime64_add(cpustat->steal, tmp);
3183 static void task_running_tick(struct rq *rq, struct task_struct *p, int cpu)
3185 if (p->array != rq->active) {
3186 /* Task has expired but was not scheduled yet */
3187 set_tsk_need_resched(p);
3190 spin_lock(&rq->lock);
3192 * The task was running during this tick - update the
3193 * time slice counter. Note: we do not update a thread's
3194 * priority until it either goes to sleep or uses up its
3195 * timeslice. This makes it possible for interactive tasks
3196 * to use up their timeslices at their highest priority levels.
3200 * RR tasks need a special form of timeslice management.
3201 * FIFO tasks have no timeslices.
3203 if ((p->policy == SCHED_RR) && !--p->time_slice) {
3204 p->time_slice = task_timeslice(p);
3205 p->first_time_slice = 0;
3206 set_tsk_need_resched(p);
3208 /* put it at the end of the queue: */
3209 requeue_task(p, rq->active);
3213 if (vx_need_resched(p, --p->time_slice, cpu)) {
3214 dequeue_task(p, rq->active);
3215 set_tsk_need_resched(p);
3216 p->prio = effective_prio(p);
3217 p->time_slice = task_timeslice(p);
3218 p->first_time_slice = 0;
3220 if (!rq->expired_timestamp)
3221 rq->expired_timestamp = jiffies;
3222 if (!TASK_INTERACTIVE(p) || expired_starving(rq)) {
3223 enqueue_task(p, rq->expired);
3224 if (p->static_prio < rq->best_expired_prio)
3225 rq->best_expired_prio = p->static_prio;
3227 enqueue_task(p, rq->active);
3230 * Prevent a too long timeslice allowing a task to monopolize
3231 * the CPU. We do this by splitting up the timeslice into
3234 * Note: this does not mean the task's timeslices expire or
3235 * get lost in any way, they just might be preempted by
3236 * another task of equal priority. (one with higher
3237 * priority would have preempted this task already.) We
3238 * requeue this task to the end of the list on this priority
3239 * level, which is in essence a round-robin of tasks with
3242 * This only applies to tasks in the interactive
3243 * delta range with at least TIMESLICE_GRANULARITY to requeue.
3245 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
3246 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
3247 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
3248 (p->array == rq->active)) {
3250 requeue_task(p, rq->active);
3251 set_tsk_need_resched(p);
3255 spin_unlock(&rq->lock);
3259 * This function gets called by the timer code, with HZ frequency.
3260 * We call it with interrupts disabled.
3262 * It also gets called by the fork code, when changing the parent's
3265 void scheduler_tick(void)
3267 unsigned long long now = sched_clock();
3268 struct task_struct *p = current;
3269 int cpu = smp_processor_id();
3270 struct rq *rq = cpu_rq(cpu);
3272 update_cpu_clock(p, rq, now);
3275 if (p == rq->idle) {
3276 /* Task on the idle queue */
3277 wake_priority_sleeper(rq);
3278 vx_idle_resched(rq);
3280 task_running_tick(rq, p, cpu);
3283 if (time_after_eq(jiffies, rq->next_balance))
3284 raise_softirq(SCHED_SOFTIRQ);
3288 #ifdef CONFIG_SCHED_SMT
3289 static inline void wakeup_busy_runqueue(struct rq *rq)
3291 /* If an SMT runqueue is sleeping due to priority reasons wake it up */
3292 if (rq->curr == rq->idle && rq->nr_running)
3293 resched_task(rq->idle);
3297 * Called with interrupt disabled and this_rq's runqueue locked.
3299 static void wake_sleeping_dependent(int this_cpu)
3301 struct sched_domain *tmp, *sd = NULL;
3304 for_each_domain(this_cpu, tmp) {
3305 if (tmp->flags & SD_SHARE_CPUPOWER) {
3314 for_each_cpu_mask(i, sd->span) {
3315 struct rq *smt_rq = cpu_rq(i);
3319 if (unlikely(!spin_trylock(&smt_rq->lock)))
3322 wakeup_busy_runqueue(smt_rq);
3323 spin_unlock(&smt_rq->lock);
3328 * number of 'lost' timeslices this task wont be able to fully
3329 * utilize, if another task runs on a sibling. This models the
3330 * slowdown effect of other tasks running on siblings:
3332 static inline unsigned long
3333 smt_slice(struct task_struct *p, struct sched_domain *sd)
3335 return p->time_slice * (100 - sd->per_cpu_gain) / 100;
3339 * To minimise lock contention and not have to drop this_rq's runlock we only
3340 * trylock the sibling runqueues and bypass those runqueues if we fail to
3341 * acquire their lock. As we only trylock the normal locking order does not
3342 * need to be obeyed.
3345 dependent_sleeper(int this_cpu, struct rq *this_rq, struct task_struct *p)
3347 struct sched_domain *tmp, *sd = NULL;
3350 /* kernel/rt threads do not participate in dependent sleeping */
3351 if (!p->mm || rt_task(p))
3354 for_each_domain(this_cpu, tmp) {
3355 if (tmp->flags & SD_SHARE_CPUPOWER) {
3364 for_each_cpu_mask(i, sd->span) {
3365 struct task_struct *smt_curr;
3372 if (unlikely(!spin_trylock(&smt_rq->lock)))
3375 smt_curr = smt_rq->curr;
3381 * If a user task with lower static priority than the
3382 * running task on the SMT sibling is trying to schedule,
3383 * delay it till there is proportionately less timeslice
3384 * left of the sibling task to prevent a lower priority
3385 * task from using an unfair proportion of the
3386 * physical cpu's resources. -ck
3388 if (rt_task(smt_curr)) {
3390 * With real time tasks we run non-rt tasks only
3391 * per_cpu_gain% of the time.
3393 if ((jiffies % DEF_TIMESLICE) >
3394 (sd->per_cpu_gain * DEF_TIMESLICE / 100))
3397 if (smt_curr->static_prio < p->static_prio &&
3398 !TASK_PREEMPTS_CURR(p, smt_rq) &&
3399 smt_slice(smt_curr, sd) > task_timeslice(p))
3403 spin_unlock(&smt_rq->lock);
3408 static inline void wake_sleeping_dependent(int this_cpu)
3412 dependent_sleeper(int this_cpu, struct rq *this_rq, struct task_struct *p)
3418 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3420 void fastcall add_preempt_count(int val)
3425 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3427 preempt_count() += val;
3429 * Spinlock count overflowing soon?
3431 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3434 EXPORT_SYMBOL(add_preempt_count);
3436 void fastcall sub_preempt_count(int val)
3441 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3444 * Is the spinlock portion underflowing?
3446 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3447 !(preempt_count() & PREEMPT_MASK)))
3450 preempt_count() -= val;
3452 EXPORT_SYMBOL(sub_preempt_count);
3456 static inline int interactive_sleep(enum sleep_type sleep_type)
3458 return (sleep_type == SLEEP_INTERACTIVE ||
3459 sleep_type == SLEEP_INTERRUPTED);
3463 * schedule() is the main scheduler function.
3465 asmlinkage void __sched schedule(void)
3467 struct task_struct *prev, *next;
3468 struct prio_array *array;
3469 struct list_head *queue;
3470 unsigned long long now;
3471 unsigned long run_time;
3472 int cpu, idx, new_prio;
3477 * Test if we are atomic. Since do_exit() needs to call into
3478 * schedule() atomically, we ignore that path for now.
3479 * Otherwise, whine if we are scheduling when we should not be.
3481 if (unlikely(in_atomic() && !current->exit_state)) {
3482 printk(KERN_ERR "BUG: scheduling while atomic: "
3484 current->comm, preempt_count(), current->pid);
3485 debug_show_held_locks(current);
3486 if (irqs_disabled())
3487 print_irqtrace_events(current);
3490 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3495 release_kernel_lock(prev);
3496 need_resched_nonpreemptible:
3500 * The idle thread is not allowed to schedule!
3501 * Remove this check after it has been exercised a bit.
3503 if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
3504 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
3508 schedstat_inc(rq, sched_cnt);
3509 now = sched_clock();
3510 if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
3511 run_time = now - prev->timestamp;
3512 if (unlikely((long long)(now - prev->timestamp) < 0))
3515 run_time = NS_MAX_SLEEP_AVG;
3518 * Tasks charged proportionately less run_time at high sleep_avg to
3519 * delay them losing their interactive status
3521 run_time /= (CURRENT_BONUS(prev) ? : 1);
3523 spin_lock_irq(&rq->lock);
3525 switch_count = &prev->nivcsw;
3526 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3527 switch_count = &prev->nvcsw;
3528 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
3529 unlikely(signal_pending(prev))))
3530 prev->state = TASK_RUNNING;
3532 if (prev->state == TASK_UNINTERRUPTIBLE) {
3533 rq->nr_uninterruptible++;
3534 vx_uninterruptible_inc(prev);
3536 deactivate_task(prev, rq);
3540 cpu = smp_processor_id();
3541 vx_set_rq_time(rq, jiffies);
3543 vx_try_unhold(rq, cpu);
3546 if (unlikely(!rq->nr_running)) {
3547 /* can we skip idle time? */
3548 if (vx_try_skip(rq, cpu))
3551 idle_balance(cpu, rq);
3552 if (!rq->nr_running) {
3554 rq->expired_timestamp = 0;
3555 wake_sleeping_dependent(cpu);
3561 if (unlikely(!array->nr_active)) {
3563 * Switch the active and expired arrays.
3565 schedstat_inc(rq, sched_switch);
3566 rq->active = rq->expired;
3567 rq->expired = array;
3569 rq->expired_timestamp = 0;
3570 rq->best_expired_prio = MAX_PRIO;
3573 idx = sched_find_first_bit(array->bitmap);
3574 queue = array->queue + idx;
3575 next = list_entry(queue->next, struct task_struct, run_list);
3577 /* check before we schedule this context */
3578 if (!vx_schedule(next, rq, cpu))
3581 if (!rt_task(next) && interactive_sleep(next->sleep_type)) {
3582 unsigned long long delta = now - next->timestamp;
3583 if (unlikely((long long)(now - next->timestamp) < 0))
3586 if (next->sleep_type == SLEEP_INTERACTIVE)
3587 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
3589 array = next->array;
3590 new_prio = recalc_task_prio(next, next->timestamp + delta);
3592 if (unlikely(next->prio != new_prio)) {
3593 dequeue_task(next, array);
3594 next->prio = new_prio;
3595 enqueue_task(next, array);
3598 next->sleep_type = SLEEP_NORMAL;
3599 if (rq->nr_running == 1 && dependent_sleeper(cpu, rq, next))
3602 if (next == rq->idle)
3603 schedstat_inc(rq, sched_goidle);
3605 prefetch_stack(next);
3606 clear_tsk_need_resched(prev);
3607 rcu_qsctr_inc(task_cpu(prev));
3609 update_cpu_clock(prev, rq, now);
3611 prev->sleep_avg -= run_time;
3612 if ((long)prev->sleep_avg <= 0)
3613 prev->sleep_avg = 0;
3614 prev->timestamp = prev->last_ran = now;
3616 sched_info_switch(prev, next);
3617 if (likely(prev != next)) {
3618 next->timestamp = next->last_ran = now;
3623 prepare_task_switch(rq, next);
3624 prev = context_switch(rq, prev, next);
3627 * this_rq must be evaluated again because prev may have moved
3628 * CPUs since it called schedule(), thus the 'rq' on its stack
3629 * frame will be invalid.
3631 finish_task_switch(this_rq(), prev);
3633 spin_unlock_irq(&rq->lock);
3636 if (unlikely(reacquire_kernel_lock(prev) < 0))
3637 goto need_resched_nonpreemptible;
3638 preempt_enable_no_resched();
3639 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3642 EXPORT_SYMBOL(schedule);
3644 #ifdef CONFIG_PREEMPT
3646 * this is the entry point to schedule() from in-kernel preemption
3647 * off of preempt_enable. Kernel preemptions off return from interrupt
3648 * occur there and call schedule directly.
3650 asmlinkage void __sched preempt_schedule(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;
3658 * If there is a non-zero preempt_count or interrupts are disabled,
3659 * we do not want to preempt the current task. Just return..
3661 if (likely(ti->preempt_count || irqs_disabled()))
3665 add_preempt_count(PREEMPT_ACTIVE);
3667 * We keep the big kernel semaphore locked, but we
3668 * clear ->lock_depth so that schedule() doesnt
3669 * auto-release the semaphore:
3671 #ifdef CONFIG_PREEMPT_BKL
3672 saved_lock_depth = task->lock_depth;
3673 task->lock_depth = -1;
3676 #ifdef CONFIG_PREEMPT_BKL
3677 task->lock_depth = saved_lock_depth;
3679 sub_preempt_count(PREEMPT_ACTIVE);
3681 /* we could miss a preemption opportunity between schedule and now */
3683 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3686 EXPORT_SYMBOL(preempt_schedule);
3689 * this is the entry point to schedule() from kernel preemption
3690 * off of irq context.
3691 * Note, that this is called and return with irqs disabled. This will
3692 * protect us against recursive calling from irq.
3694 asmlinkage void __sched preempt_schedule_irq(void)
3696 struct thread_info *ti = current_thread_info();
3697 #ifdef CONFIG_PREEMPT_BKL
3698 struct task_struct *task = current;
3699 int saved_lock_depth;
3701 /* Catch callers which need to be fixed */
3702 BUG_ON(ti->preempt_count || !irqs_disabled());
3705 add_preempt_count(PREEMPT_ACTIVE);
3707 * We keep the big kernel semaphore locked, but we
3708 * clear ->lock_depth so that schedule() doesnt
3709 * auto-release the semaphore:
3711 #ifdef CONFIG_PREEMPT_BKL
3712 saved_lock_depth = task->lock_depth;
3713 task->lock_depth = -1;
3717 local_irq_disable();
3718 #ifdef CONFIG_PREEMPT_BKL
3719 task->lock_depth = saved_lock_depth;
3721 sub_preempt_count(PREEMPT_ACTIVE);
3723 /* we could miss a preemption opportunity between schedule and now */
3725 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3729 #endif /* CONFIG_PREEMPT */
3731 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
3734 return try_to_wake_up(curr->private, mode, sync);
3736 EXPORT_SYMBOL(default_wake_function);
3739 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3740 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3741 * number) then we wake all the non-exclusive tasks and one exclusive task.
3743 * There are circumstances in which we can try to wake a task which has already
3744 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3745 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3747 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3748 int nr_exclusive, int sync, void *key)
3750 struct list_head *tmp, *next;
3752 list_for_each_safe(tmp, next, &q->task_list) {
3753 wait_queue_t *curr = list_entry(tmp, wait_queue_t, task_list);
3754 unsigned flags = curr->flags;
3756 if (curr->func(curr, mode, sync, key) &&
3757 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
3763 * __wake_up - wake up threads blocked on a waitqueue.
3765 * @mode: which threads
3766 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3767 * @key: is directly passed to the wakeup function
3769 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3770 int nr_exclusive, void *key)
3772 unsigned long flags;
3774 spin_lock_irqsave(&q->lock, flags);
3775 __wake_up_common(q, mode, nr_exclusive, 0, key);
3776 spin_unlock_irqrestore(&q->lock, flags);
3778 EXPORT_SYMBOL(__wake_up);
3781 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3783 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3785 __wake_up_common(q, mode, 1, 0, NULL);
3789 * __wake_up_sync - wake up threads blocked on a waitqueue.
3791 * @mode: which threads
3792 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3794 * The sync wakeup differs that the waker knows that it will schedule
3795 * away soon, so while the target thread will be woken up, it will not
3796 * be migrated to another CPU - ie. the two threads are 'synchronized'
3797 * with each other. This can prevent needless bouncing between CPUs.
3799 * On UP it can prevent extra preemption.
3802 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3804 unsigned long flags;
3810 if (unlikely(!nr_exclusive))
3813 spin_lock_irqsave(&q->lock, flags);
3814 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3815 spin_unlock_irqrestore(&q->lock, flags);
3817 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3819 void fastcall complete(struct completion *x)
3821 unsigned long flags;
3823 spin_lock_irqsave(&x->wait.lock, flags);
3825 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3827 spin_unlock_irqrestore(&x->wait.lock, flags);
3829 EXPORT_SYMBOL(complete);
3831 void fastcall complete_all(struct completion *x)
3833 unsigned long flags;
3835 spin_lock_irqsave(&x->wait.lock, flags);
3836 x->done += UINT_MAX/2;
3837 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3839 spin_unlock_irqrestore(&x->wait.lock, flags);
3841 EXPORT_SYMBOL(complete_all);
3843 void fastcall __sched wait_for_completion(struct completion *x)
3847 spin_lock_irq(&x->wait.lock);
3849 DECLARE_WAITQUEUE(wait, current);
3851 wait.flags |= WQ_FLAG_EXCLUSIVE;
3852 __add_wait_queue_tail(&x->wait, &wait);
3854 __set_current_state(TASK_UNINTERRUPTIBLE);
3855 spin_unlock_irq(&x->wait.lock);
3857 spin_lock_irq(&x->wait.lock);
3859 __remove_wait_queue(&x->wait, &wait);
3862 spin_unlock_irq(&x->wait.lock);
3864 EXPORT_SYMBOL(wait_for_completion);
3866 unsigned long fastcall __sched
3867 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3871 spin_lock_irq(&x->wait.lock);
3873 DECLARE_WAITQUEUE(wait, current);
3875 wait.flags |= WQ_FLAG_EXCLUSIVE;
3876 __add_wait_queue_tail(&x->wait, &wait);
3878 __set_current_state(TASK_UNINTERRUPTIBLE);
3879 spin_unlock_irq(&x->wait.lock);
3880 timeout = schedule_timeout(timeout);
3881 spin_lock_irq(&x->wait.lock);
3883 __remove_wait_queue(&x->wait, &wait);
3887 __remove_wait_queue(&x->wait, &wait);
3891 spin_unlock_irq(&x->wait.lock);
3894 EXPORT_SYMBOL(wait_for_completion_timeout);
3896 int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3902 spin_lock_irq(&x->wait.lock);
3904 DECLARE_WAITQUEUE(wait, current);
3906 wait.flags |= WQ_FLAG_EXCLUSIVE;
3907 __add_wait_queue_tail(&x->wait, &wait);
3909 if (signal_pending(current)) {
3911 __remove_wait_queue(&x->wait, &wait);
3914 __set_current_state(TASK_INTERRUPTIBLE);
3915 spin_unlock_irq(&x->wait.lock);
3917 spin_lock_irq(&x->wait.lock);
3919 __remove_wait_queue(&x->wait, &wait);
3923 spin_unlock_irq(&x->wait.lock);
3927 EXPORT_SYMBOL(wait_for_completion_interruptible);
3929 unsigned long fastcall __sched
3930 wait_for_completion_interruptible_timeout(struct completion *x,
3931 unsigned long timeout)
3935 spin_lock_irq(&x->wait.lock);
3937 DECLARE_WAITQUEUE(wait, current);
3939 wait.flags |= WQ_FLAG_EXCLUSIVE;
3940 __add_wait_queue_tail(&x->wait, &wait);
3942 if (signal_pending(current)) {
3943 timeout = -ERESTARTSYS;
3944 __remove_wait_queue(&x->wait, &wait);
3947 __set_current_state(TASK_INTERRUPTIBLE);
3948 spin_unlock_irq(&x->wait.lock);
3949 timeout = schedule_timeout(timeout);
3950 spin_lock_irq(&x->wait.lock);
3952 __remove_wait_queue(&x->wait, &wait);
3956 __remove_wait_queue(&x->wait, &wait);
3960 spin_unlock_irq(&x->wait.lock);
3963 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3966 #define SLEEP_ON_VAR \
3967 unsigned long flags; \
3968 wait_queue_t wait; \
3969 init_waitqueue_entry(&wait, current);
3971 #define SLEEP_ON_HEAD \
3972 spin_lock_irqsave(&q->lock,flags); \
3973 __add_wait_queue(q, &wait); \
3974 spin_unlock(&q->lock);
3976 #define SLEEP_ON_TAIL \
3977 spin_lock_irq(&q->lock); \
3978 __remove_wait_queue(q, &wait); \
3979 spin_unlock_irqrestore(&q->lock, flags);
3981 #define SLEEP_ON_BKLCHECK \
3982 if (unlikely(!kernel_locked()) && \
3983 sleep_on_bkl_warnings < 10) { \
3984 sleep_on_bkl_warnings++; \
3988 static int sleep_on_bkl_warnings;
3990 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3996 current->state = TASK_INTERRUPTIBLE;
4002 EXPORT_SYMBOL(interruptible_sleep_on);
4004 long fastcall __sched
4005 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
4011 current->state = TASK_INTERRUPTIBLE;
4014 timeout = schedule_timeout(timeout);
4019 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
4021 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
4027 current->state = TASK_UNINTERRUPTIBLE;
4030 timeout = schedule_timeout(timeout);
4036 EXPORT_SYMBOL(sleep_on_timeout);
4038 #ifdef CONFIG_RT_MUTEXES
4041 * rt_mutex_setprio - set the current priority of a task
4043 * @prio: prio value (kernel-internal form)
4045 * This function changes the 'effective' priority of a task. It does
4046 * not touch ->normal_prio like __setscheduler().
4048 * Used by the rt_mutex code to implement priority inheritance logic.
4050 void rt_mutex_setprio(struct task_struct *p, int prio)
4052 struct prio_array *array;
4053 unsigned long flags;
4057 BUG_ON(prio < 0 || prio > MAX_PRIO);
4059 rq = task_rq_lock(p, &flags);
4064 dequeue_task(p, array);
4069 * If changing to an RT priority then queue it
4070 * in the active array!
4074 enqueue_task(p, array);
4076 * Reschedule if we are currently running on this runqueue and
4077 * our priority decreased, or if we are not currently running on
4078 * this runqueue and our priority is higher than the current's
4080 if (task_running(rq, p)) {
4081 if (p->prio > oldprio)
4082 resched_task(rq->curr);
4083 } else if (TASK_PREEMPTS_CURR(p, rq))
4084 resched_task(rq->curr);
4086 task_rq_unlock(rq, &flags);
4091 void set_user_nice(struct task_struct *p, long nice)
4093 struct prio_array *array;
4094 int old_prio, delta;
4095 unsigned long flags;
4098 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
4101 * We have to be careful, if called from sys_setpriority(),
4102 * the task might be in the middle of scheduling on another CPU.
4104 rq = task_rq_lock(p, &flags);
4106 * The RT priorities are set via sched_setscheduler(), but we still
4107 * allow the 'normal' nice value to be set - but as expected
4108 * it wont have any effect on scheduling until the task is
4109 * not SCHED_NORMAL/SCHED_BATCH:
4111 if (has_rt_policy(p)) {
4112 p->static_prio = NICE_TO_PRIO(nice);
4117 dequeue_task(p, array);
4118 dec_raw_weighted_load(rq, p);
4121 p->static_prio = NICE_TO_PRIO(nice);
4124 p->prio = effective_prio(p);
4125 delta = p->prio - old_prio;
4128 enqueue_task(p, array);
4129 inc_raw_weighted_load(rq, p);
4131 * If the task increased its priority or is running and
4132 * lowered its priority, then reschedule its CPU:
4134 if (delta < 0 || (delta > 0 && task_running(rq, p)))
4135 resched_task(rq->curr);
4138 task_rq_unlock(rq, &flags);
4140 EXPORT_SYMBOL(set_user_nice);
4143 * can_nice - check if a task can reduce its nice value
4147 int can_nice(const struct task_struct *p, const int nice)
4149 /* convert nice value [19,-20] to rlimit style value [1,40] */
4150 int nice_rlim = 20 - nice;
4152 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
4153 capable(CAP_SYS_NICE));
4156 #ifdef __ARCH_WANT_SYS_NICE
4159 * sys_nice - change the priority of the current process.
4160 * @increment: priority increment
4162 * sys_setpriority is a more generic, but much slower function that
4163 * does similar things.
4165 asmlinkage long sys_nice(int increment)
4170 * Setpriority might change our priority at the same moment.
4171 * We don't have to worry. Conceptually one call occurs first
4172 * and we have a single winner.
4174 if (increment < -40)
4179 nice = PRIO_TO_NICE(current->static_prio) + increment;
4185 if (increment < 0 && !can_nice(current, nice))
4186 return vx_flags(VXF_IGNEG_NICE, 0) ? 0 : -EPERM;
4188 retval = security_task_setnice(current, nice);
4192 set_user_nice(current, nice);
4199 * task_prio - return the priority value of a given task.
4200 * @p: the task in question.
4202 * This is the priority value as seen by users in /proc.
4203 * RT tasks are offset by -200. Normal tasks are centered
4204 * around 0, value goes from -16 to +15.
4206 int task_prio(const struct task_struct *p)
4208 return p->prio - MAX_RT_PRIO;
4212 * task_nice - return the nice value of a given task.
4213 * @p: the task in question.
4215 int task_nice(const struct task_struct *p)
4217 return TASK_NICE(p);
4219 EXPORT_SYMBOL_GPL(task_nice);
4222 * idle_cpu - is a given cpu idle currently?
4223 * @cpu: the processor in question.
4225 int idle_cpu(int cpu)
4227 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
4231 * idle_task - return the idle task for a given cpu.
4232 * @cpu: the processor in question.
4234 struct task_struct *idle_task(int cpu)
4236 return cpu_rq(cpu)->idle;
4240 * find_process_by_pid - find a process with a matching PID value.
4241 * @pid: the pid in question.
4243 static inline struct task_struct *find_process_by_pid(pid_t pid)
4245 return pid ? find_task_by_pid(pid) : current;
4248 /* Actually do priority change: must hold rq lock. */
4249 static void __setscheduler(struct task_struct *p, int policy, int prio)
4254 p->rt_priority = prio;
4255 p->normal_prio = normal_prio(p);
4256 /* we are holding p->pi_lock already */
4257 p->prio = rt_mutex_getprio(p);
4259 * SCHED_BATCH tasks are treated as perpetual CPU hogs:
4261 if (policy == SCHED_BATCH)
4267 * sched_setscheduler - change the scheduling policy and/or RT priority of
4269 * @p: the task in question.
4270 * @policy: new policy.
4271 * @param: structure containing the new RT priority.
4273 * NOTE: the task may be already dead
4275 int sched_setscheduler(struct task_struct *p, int policy,
4276 struct sched_param *param)
4278 int retval, oldprio, oldpolicy = -1;
4279 struct prio_array *array;
4280 unsigned long flags;
4283 /* may grab non-irq protected spin_locks */
4284 BUG_ON(in_interrupt());
4286 /* double check policy once rq lock held */
4288 policy = oldpolicy = p->policy;
4289 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
4290 policy != SCHED_NORMAL && policy != SCHED_BATCH)
4293 * Valid priorities for SCHED_FIFO and SCHED_RR are
4294 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL and
4297 if (param->sched_priority < 0 ||
4298 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
4299 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
4301 if (is_rt_policy(policy) != (param->sched_priority != 0))
4305 * Allow unprivileged RT tasks to decrease priority:
4307 if (!capable(CAP_SYS_NICE)) {
4308 if (is_rt_policy(policy)) {
4309 unsigned long rlim_rtprio;
4310 unsigned long flags;
4312 if (!lock_task_sighand(p, &flags))
4314 rlim_rtprio = p->signal->rlim[RLIMIT_RTPRIO].rlim_cur;
4315 unlock_task_sighand(p, &flags);
4317 /* can't set/change the rt policy */
4318 if (policy != p->policy && !rlim_rtprio)
4321 /* can't increase priority */
4322 if (param->sched_priority > p->rt_priority &&
4323 param->sched_priority > rlim_rtprio)
4327 /* can't change other user's priorities */
4328 if ((current->euid != p->euid) &&
4329 (current->euid != p->uid))
4333 retval = security_task_setscheduler(p, policy, param);
4337 * make sure no PI-waiters arrive (or leave) while we are
4338 * changing the priority of the task:
4340 spin_lock_irqsave(&p->pi_lock, flags);
4342 * To be able to change p->policy safely, the apropriate
4343 * runqueue lock must be held.
4345 rq = __task_rq_lock(p);
4346 /* recheck policy now with rq lock held */
4347 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4348 policy = oldpolicy = -1;
4349 __task_rq_unlock(rq);
4350 spin_unlock_irqrestore(&p->pi_lock, flags);
4355 deactivate_task(p, rq);
4357 __setscheduler(p, policy, param->sched_priority);
4359 vx_activate_task(p);
4360 __activate_task(p, rq);
4362 * Reschedule if we are currently running on this runqueue and
4363 * our priority decreased, or if we are not currently running on
4364 * this runqueue and our priority is higher than the current's
4366 if (task_running(rq, p)) {
4367 if (p->prio > oldprio)
4368 resched_task(rq->curr);
4369 } else if (TASK_PREEMPTS_CURR(p, rq))
4370 resched_task(rq->curr);
4372 __task_rq_unlock(rq);
4373 spin_unlock_irqrestore(&p->pi_lock, flags);
4375 rt_mutex_adjust_pi(p);
4379 EXPORT_SYMBOL_GPL(sched_setscheduler);
4382 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4384 struct sched_param lparam;
4385 struct task_struct *p;
4388 if (!param || pid < 0)
4390 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4395 p = find_process_by_pid(pid);
4397 retval = sched_setscheduler(p, policy, &lparam);
4404 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4405 * @pid: the pid in question.
4406 * @policy: new policy.
4407 * @param: structure containing the new RT priority.
4409 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
4410 struct sched_param __user *param)
4412 /* negative values for policy are not valid */
4416 return do_sched_setscheduler(pid, policy, param);
4420 * sys_sched_setparam - set/change the RT priority of a thread
4421 * @pid: the pid in question.
4422 * @param: structure containing the new RT priority.
4424 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
4426 return do_sched_setscheduler(pid, -1, param);
4430 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4431 * @pid: the pid in question.
4433 asmlinkage long sys_sched_getscheduler(pid_t pid)
4435 struct task_struct *p;
4436 int retval = -EINVAL;
4442 read_lock(&tasklist_lock);
4443 p = find_process_by_pid(pid);
4445 retval = security_task_getscheduler(p);
4449 read_unlock(&tasklist_lock);
4456 * sys_sched_getscheduler - get the RT priority of a thread
4457 * @pid: the pid in question.
4458 * @param: structure containing the RT priority.
4460 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
4462 struct sched_param lp;
4463 struct task_struct *p;
4464 int retval = -EINVAL;
4466 if (!param || pid < 0)
4469 read_lock(&tasklist_lock);
4470 p = find_process_by_pid(pid);
4475 retval = security_task_getscheduler(p);
4479 lp.sched_priority = p->rt_priority;
4480 read_unlock(&tasklist_lock);
4483 * This one might sleep, we cannot do it with a spinlock held ...
4485 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4491 read_unlock(&tasklist_lock);
4495 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
4497 cpumask_t cpus_allowed;
4498 struct task_struct *p;
4502 read_lock(&tasklist_lock);
4504 p = find_process_by_pid(pid);
4506 read_unlock(&tasklist_lock);
4507 unlock_cpu_hotplug();
4512 * It is not safe to call set_cpus_allowed with the
4513 * tasklist_lock held. We will bump the task_struct's
4514 * usage count and then drop tasklist_lock.
4517 read_unlock(&tasklist_lock);
4520 if ((current->euid != p->euid) && (current->euid != p->uid) &&
4521 !capable(CAP_SYS_NICE))
4524 retval = security_task_setscheduler(p, 0, NULL);
4528 cpus_allowed = cpuset_cpus_allowed(p);
4529 cpus_and(new_mask, new_mask, cpus_allowed);
4530 retval = set_cpus_allowed(p, new_mask);
4534 unlock_cpu_hotplug();
4538 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4539 cpumask_t *new_mask)
4541 if (len < sizeof(cpumask_t)) {
4542 memset(new_mask, 0, sizeof(cpumask_t));
4543 } else if (len > sizeof(cpumask_t)) {
4544 len = sizeof(cpumask_t);
4546 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4550 * sys_sched_setaffinity - set the cpu affinity of a process
4551 * @pid: pid of the process
4552 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4553 * @user_mask_ptr: user-space pointer to the new cpu mask
4555 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
4556 unsigned long __user *user_mask_ptr)
4561 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
4565 return sched_setaffinity(pid, new_mask);
4569 * Represents all cpu's present in the system
4570 * In systems capable of hotplug, this map could dynamically grow
4571 * as new cpu's are detected in the system via any platform specific
4572 * method, such as ACPI for e.g.
4575 cpumask_t cpu_present_map __read_mostly;
4576 EXPORT_SYMBOL(cpu_present_map);
4579 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
4580 EXPORT_SYMBOL(cpu_online_map);
4582 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
4583 EXPORT_SYMBOL(cpu_possible_map);
4586 long sched_getaffinity(pid_t pid, cpumask_t *mask)
4588 struct task_struct *p;
4592 read_lock(&tasklist_lock);
4595 p = find_process_by_pid(pid);
4599 retval = security_task_getscheduler(p);
4603 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
4606 read_unlock(&tasklist_lock);
4607 unlock_cpu_hotplug();
4615 * sys_sched_getaffinity - get the cpu affinity of a process
4616 * @pid: pid of the process
4617 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4618 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4620 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
4621 unsigned long __user *user_mask_ptr)
4626 if (len < sizeof(cpumask_t))
4629 ret = sched_getaffinity(pid, &mask);
4633 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
4636 return sizeof(cpumask_t);
4640 * sys_sched_yield - yield the current processor to other threads.
4642 * this function yields the current CPU by moving the calling thread
4643 * to the expired array. If there are no other threads running on this
4644 * CPU then this function will return.
4646 asmlinkage long sys_sched_yield(void)
4648 struct rq *rq = this_rq_lock();
4649 struct prio_array *array = current->array, *target = rq->expired;
4651 schedstat_inc(rq, yld_cnt);
4653 * We implement yielding by moving the task into the expired
4656 * (special rule: RT tasks will just roundrobin in the active
4659 if (rt_task(current))
4660 target = rq->active;
4662 if (array->nr_active == 1) {
4663 schedstat_inc(rq, yld_act_empty);
4664 if (!rq->expired->nr_active)
4665 schedstat_inc(rq, yld_both_empty);
4666 } else if (!rq->expired->nr_active)
4667 schedstat_inc(rq, yld_exp_empty);
4669 if (array != target) {
4670 dequeue_task(current, array);
4671 enqueue_task(current, target);
4674 * requeue_task is cheaper so perform that if possible.
4676 requeue_task(current, array);
4679 * Since we are going to call schedule() anyway, there's
4680 * no need to preempt or enable interrupts:
4682 __release(rq->lock);
4683 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
4684 _raw_spin_unlock(&rq->lock);
4685 preempt_enable_no_resched();
4692 static void __cond_resched(void)
4694 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4695 __might_sleep(__FILE__, __LINE__);
4698 * The BKS might be reacquired before we have dropped
4699 * PREEMPT_ACTIVE, which could trigger a second
4700 * cond_resched() call.
4703 add_preempt_count(PREEMPT_ACTIVE);
4705 sub_preempt_count(PREEMPT_ACTIVE);
4706 } while (need_resched());
4709 int __sched cond_resched(void)
4711 if (need_resched() && !(preempt_count() & PREEMPT_ACTIVE) &&
4712 system_state == SYSTEM_RUNNING) {
4718 EXPORT_SYMBOL(cond_resched);
4721 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4722 * call schedule, and on return reacquire the lock.
4724 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4725 * operations here to prevent schedule() from being called twice (once via
4726 * spin_unlock(), once by hand).
4728 int cond_resched_lock(spinlock_t *lock)
4732 if (need_lockbreak(lock)) {
4738 if (need_resched() && system_state == SYSTEM_RUNNING) {
4739 spin_release(&lock->dep_map, 1, _THIS_IP_);
4740 _raw_spin_unlock(lock);
4741 preempt_enable_no_resched();
4748 EXPORT_SYMBOL(cond_resched_lock);
4750 int __sched cond_resched_softirq(void)
4752 BUG_ON(!in_softirq());
4754 if (need_resched() && system_state == SYSTEM_RUNNING) {
4755 raw_local_irq_disable();
4757 raw_local_irq_enable();
4764 EXPORT_SYMBOL(cond_resched_softirq);
4767 * yield - yield the current processor to other threads.
4769 * this is a shortcut for kernel-space yielding - it marks the
4770 * thread runnable and calls sys_sched_yield().
4772 void __sched yield(void)
4774 set_current_state(TASK_RUNNING);
4777 EXPORT_SYMBOL(yield);
4780 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4781 * that process accounting knows that this is a task in IO wait state.
4783 * But don't do that if it is a deliberate, throttling IO wait (this task
4784 * has set its backing_dev_info: the queue against which it should throttle)
4786 void __sched io_schedule(void)
4788 struct rq *rq = &__raw_get_cpu_var(runqueues);
4790 delayacct_blkio_start();
4791 atomic_inc(&rq->nr_iowait);
4793 atomic_dec(&rq->nr_iowait);
4794 delayacct_blkio_end();
4796 EXPORT_SYMBOL(io_schedule);
4798 long __sched io_schedule_timeout(long timeout)
4800 struct rq *rq = &__raw_get_cpu_var(runqueues);
4803 delayacct_blkio_start();
4804 atomic_inc(&rq->nr_iowait);
4805 ret = schedule_timeout(timeout);
4806 atomic_dec(&rq->nr_iowait);
4807 delayacct_blkio_end();
4812 * sys_sched_get_priority_max - return maximum RT priority.
4813 * @policy: scheduling class.
4815 * this syscall returns the maximum rt_priority that can be used
4816 * by a given scheduling class.
4818 asmlinkage long sys_sched_get_priority_max(int policy)
4825 ret = MAX_USER_RT_PRIO-1;
4836 * sys_sched_get_priority_min - return minimum RT priority.
4837 * @policy: scheduling class.
4839 * this syscall returns the minimum rt_priority that can be used
4840 * by a given scheduling class.
4842 asmlinkage long sys_sched_get_priority_min(int policy)
4859 * sys_sched_rr_get_interval - return the default timeslice of a process.
4860 * @pid: pid of the process.
4861 * @interval: userspace pointer to the timeslice value.
4863 * this syscall writes the default timeslice value of a given process
4864 * into the user-space timespec buffer. A value of '0' means infinity.
4867 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4869 struct task_struct *p;
4870 int retval = -EINVAL;
4877 read_lock(&tasklist_lock);
4878 p = find_process_by_pid(pid);
4882 retval = security_task_getscheduler(p);
4886 jiffies_to_timespec(p->policy == SCHED_FIFO ?
4887 0 : task_timeslice(p), &t);
4888 read_unlock(&tasklist_lock);
4889 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4893 read_unlock(&tasklist_lock);
4897 static inline struct task_struct *eldest_child(struct task_struct *p)
4899 if (list_empty(&p->children))
4901 return list_entry(p->children.next,struct task_struct,sibling);
4904 static inline struct task_struct *older_sibling(struct task_struct *p)
4906 if (p->sibling.prev==&p->parent->children)
4908 return list_entry(p->sibling.prev,struct task_struct,sibling);
4911 static inline struct task_struct *younger_sibling(struct task_struct *p)
4913 if (p->sibling.next==&p->parent->children)
4915 return list_entry(p->sibling.next,struct task_struct,sibling);
4918 static const char stat_nam[] = "RSDTtZX";
4920 static void show_task(struct task_struct *p)
4922 struct task_struct *relative;
4923 unsigned long free = 0;
4926 state = p->state ? __ffs(p->state) + 1 : 0;
4927 printk("%-13.13s %c", p->comm,
4928 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
4929 #if (BITS_PER_LONG == 32)
4930 if (state == TASK_RUNNING)
4931 printk(" running ");
4933 printk(" %08lX ", thread_saved_pc(p));
4935 if (state == TASK_RUNNING)
4936 printk(" running task ");
4938 printk(" %016lx ", thread_saved_pc(p));
4940 #ifdef CONFIG_DEBUG_STACK_USAGE
4942 unsigned long *n = end_of_stack(p);
4945 free = (unsigned long)n - (unsigned long)end_of_stack(p);
4948 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
4949 if ((relative = eldest_child(p)))
4950 printk("%5d ", relative->pid);
4953 if ((relative = younger_sibling(p)))
4954 printk("%7d", relative->pid);
4957 if ((relative = older_sibling(p)))
4958 printk(" %5d", relative->pid);
4962 printk(" (L-TLB)\n");
4964 printk(" (NOTLB)\n");
4966 if (state != TASK_RUNNING)
4967 show_stack(p, NULL);
4970 void show_state_filter(unsigned long state_filter)
4972 struct task_struct *g, *p;
4974 #if (BITS_PER_LONG == 32)
4977 printk(" task PC stack pid father child younger older\n");
4981 printk(" task PC stack pid father child younger older\n");
4983 read_lock(&tasklist_lock);
4984 do_each_thread(g, p) {
4986 * reset the NMI-timeout, listing all files on a slow
4987 * console might take alot of time:
4989 touch_nmi_watchdog();
4990 if (p->state & state_filter)
4992 } while_each_thread(g, p);
4994 read_unlock(&tasklist_lock);
4996 * Only show locks if all tasks are dumped:
4998 if (state_filter == -1)
4999 debug_show_all_locks();
5003 * init_idle - set up an idle thread for a given CPU
5004 * @idle: task in question
5005 * @cpu: cpu the idle task belongs to
5007 * NOTE: this function does not set the idle thread's NEED_RESCHED
5008 * flag, to make booting more robust.
5010 void __cpuinit init_idle(struct task_struct *idle, int cpu)
5012 struct rq *rq = cpu_rq(cpu);
5013 unsigned long flags;
5015 idle->timestamp = sched_clock();
5016 idle->sleep_avg = 0;
5018 idle->prio = idle->normal_prio = MAX_PRIO;
5019 idle->state = TASK_RUNNING;
5020 idle->cpus_allowed = cpumask_of_cpu(cpu);
5021 set_task_cpu(idle, cpu);
5023 spin_lock_irqsave(&rq->lock, flags);
5024 rq->curr = rq->idle = idle;
5025 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
5028 spin_unlock_irqrestore(&rq->lock, flags);
5030 /* Set the preempt count _outside_ the spinlocks! */
5031 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
5032 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
5034 task_thread_info(idle)->preempt_count = 0;
5039 * In a system that switches off the HZ timer nohz_cpu_mask
5040 * indicates which cpus entered this state. This is used
5041 * in the rcu update to wait only for active cpus. For system
5042 * which do not switch off the HZ timer nohz_cpu_mask should
5043 * always be CPU_MASK_NONE.
5045 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
5049 * This is how migration works:
5051 * 1) we queue a struct migration_req structure in the source CPU's
5052 * runqueue and wake up that CPU's migration thread.
5053 * 2) we down() the locked semaphore => thread blocks.
5054 * 3) migration thread wakes up (implicitly it forces the migrated
5055 * thread off the CPU)
5056 * 4) it gets the migration request and checks whether the migrated
5057 * task is still in the wrong runqueue.
5058 * 5) if it's in the wrong runqueue then the migration thread removes
5059 * it and puts it into the right queue.
5060 * 6) migration thread up()s the semaphore.
5061 * 7) we wake up and the migration is done.
5065 * Change a given task's CPU affinity. Migrate the thread to a
5066 * proper CPU and schedule it away if the CPU it's executing on
5067 * is removed from the allowed bitmask.
5069 * NOTE: the caller must have a valid reference to the task, the
5070 * task must not exit() & deallocate itself prematurely. The
5071 * call is not atomic; no spinlocks may be held.
5073 int set_cpus_allowed(struct task_struct *p, cpumask_t new_mask)
5075 struct migration_req req;
5076 unsigned long flags;
5080 rq = task_rq_lock(p, &flags);
5081 if (!cpus_intersects(new_mask, cpu_online_map)) {
5086 p->cpus_allowed = new_mask;
5087 /* Can the task run on the task's current CPU? If so, we're done */
5088 if (cpu_isset(task_cpu(p), new_mask))
5091 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
5092 /* Need help from migration thread: drop lock and wait. */
5093 task_rq_unlock(rq, &flags);
5094 wake_up_process(rq->migration_thread);
5095 wait_for_completion(&req.done);
5096 tlb_migrate_finish(p->mm);
5100 task_rq_unlock(rq, &flags);
5104 EXPORT_SYMBOL_GPL(set_cpus_allowed);
5107 * Move (not current) task off this cpu, onto dest cpu. We're doing
5108 * this because either it can't run here any more (set_cpus_allowed()
5109 * away from this CPU, or CPU going down), or because we're
5110 * attempting to rebalance this task on exec (sched_exec).
5112 * So we race with normal scheduler movements, but that's OK, as long
5113 * as the task is no longer on this CPU.
5115 * Returns non-zero if task was successfully migrated.
5117 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
5119 struct rq *rq_dest, *rq_src;
5122 if (unlikely(cpu_is_offline(dest_cpu)))
5125 rq_src = cpu_rq(src_cpu);
5126 rq_dest = cpu_rq(dest_cpu);
5128 double_rq_lock(rq_src, rq_dest);
5129 /* Already moved. */
5130 if (task_cpu(p) != src_cpu)
5132 /* Affinity changed (again). */
5133 if (!cpu_isset(dest_cpu, p->cpus_allowed))
5136 set_task_cpu(p, dest_cpu);
5139 * Sync timestamp with rq_dest's before activating.
5140 * The same thing could be achieved by doing this step
5141 * afterwards, and pretending it was a local activate.
5142 * This way is cleaner and logically correct.
5144 p->timestamp = p->timestamp - rq_src->most_recent_timestamp
5145 + rq_dest->most_recent_timestamp;
5146 deactivate_task(p, rq_src);
5147 vx_activate_task(p);
5148 __activate_task(p, rq_dest);
5149 if (TASK_PREEMPTS_CURR(p, rq_dest))
5150 resched_task(rq_dest->curr);
5154 double_rq_unlock(rq_src, rq_dest);
5159 * migration_thread - this is a highprio system thread that performs
5160 * thread migration by bumping thread off CPU then 'pushing' onto
5163 static int migration_thread(void *data)
5165 int cpu = (long)data;
5169 BUG_ON(rq->migration_thread != current);
5171 set_current_state(TASK_INTERRUPTIBLE);
5172 while (!kthread_should_stop()) {
5173 struct migration_req *req;
5174 struct list_head *head;
5178 spin_lock_irq(&rq->lock);
5180 if (cpu_is_offline(cpu)) {
5181 spin_unlock_irq(&rq->lock);
5185 if (rq->active_balance) {
5186 active_load_balance(rq, cpu);
5187 rq->active_balance = 0;
5190 head = &rq->migration_queue;
5192 if (list_empty(head)) {
5193 spin_unlock_irq(&rq->lock);
5195 set_current_state(TASK_INTERRUPTIBLE);
5198 req = list_entry(head->next, struct migration_req, list);
5199 list_del_init(head->next);
5201 spin_unlock(&rq->lock);
5202 __migrate_task(req->task, cpu, req->dest_cpu);
5205 complete(&req->done);
5207 __set_current_state(TASK_RUNNING);
5211 /* Wait for kthread_stop */
5212 set_current_state(TASK_INTERRUPTIBLE);
5213 while (!kthread_should_stop()) {
5215 set_current_state(TASK_INTERRUPTIBLE);
5217 __set_current_state(TASK_RUNNING);
5221 #ifdef CONFIG_HOTPLUG_CPU
5223 * Figure out where task on dead CPU should go, use force if neccessary.
5224 * NOTE: interrupts should be disabled by the caller
5226 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
5228 unsigned long flags;
5235 mask = node_to_cpumask(cpu_to_node(dead_cpu));
5236 cpus_and(mask, mask, p->cpus_allowed);
5237 dest_cpu = any_online_cpu(mask);
5239 /* On any allowed CPU? */
5240 if (dest_cpu == NR_CPUS)
5241 dest_cpu = any_online_cpu(p->cpus_allowed);
5243 /* No more Mr. Nice Guy. */
5244 if (dest_cpu == NR_CPUS) {
5245 rq = task_rq_lock(p, &flags);
5246 cpus_setall(p->cpus_allowed);
5247 dest_cpu = any_online_cpu(p->cpus_allowed);
5248 task_rq_unlock(rq, &flags);
5251 * Don't tell them about moving exiting tasks or
5252 * kernel threads (both mm NULL), since they never
5255 if (p->mm && printk_ratelimit())
5256 printk(KERN_INFO "process %d (%s) no "
5257 "longer affine to cpu%d\n",
5258 p->pid, p->comm, dead_cpu);
5260 if (!__migrate_task(p, dead_cpu, dest_cpu))
5265 * While a dead CPU has no uninterruptible tasks queued at this point,
5266 * it might still have a nonzero ->nr_uninterruptible counter, because
5267 * for performance reasons the counter is not stricly tracking tasks to
5268 * their home CPUs. So we just add the counter to another CPU's counter,
5269 * to keep the global sum constant after CPU-down:
5271 static void migrate_nr_uninterruptible(struct rq *rq_src)
5273 struct rq *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
5274 unsigned long flags;
5276 local_irq_save(flags);
5277 double_rq_lock(rq_src, rq_dest);
5278 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5279 rq_src->nr_uninterruptible = 0;
5280 double_rq_unlock(rq_src, rq_dest);
5281 local_irq_restore(flags);
5284 /* Run through task list and migrate tasks from the dead cpu. */
5285 static void migrate_live_tasks(int src_cpu)
5287 struct task_struct *p, *t;
5289 write_lock_irq(&tasklist_lock);
5291 do_each_thread(t, p) {
5295 if (task_cpu(p) == src_cpu)
5296 move_task_off_dead_cpu(src_cpu, p);
5297 } while_each_thread(t, p);
5299 write_unlock_irq(&tasklist_lock);
5302 /* Schedules idle task to be the next runnable task on current CPU.
5303 * It does so by boosting its priority to highest possible and adding it to
5304 * the _front_ of the runqueue. Used by CPU offline code.
5306 void sched_idle_next(void)
5308 int this_cpu = smp_processor_id();
5309 struct rq *rq = cpu_rq(this_cpu);
5310 struct task_struct *p = rq->idle;
5311 unsigned long flags;
5313 /* cpu has to be offline */
5314 BUG_ON(cpu_online(this_cpu));
5317 * Strictly not necessary since rest of the CPUs are stopped by now
5318 * and interrupts disabled on the current cpu.
5320 spin_lock_irqsave(&rq->lock, flags);
5322 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
5324 /* Add idle task to the _front_ of its priority queue: */
5325 __activate_idle_task(p, rq);
5327 spin_unlock_irqrestore(&rq->lock, flags);
5331 * Ensures that the idle task is using init_mm right before its cpu goes
5334 void idle_task_exit(void)
5336 struct mm_struct *mm = current->active_mm;
5338 BUG_ON(cpu_online(smp_processor_id()));
5341 switch_mm(mm, &init_mm, current);
5345 /* called under rq->lock with disabled interrupts */
5346 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
5348 struct rq *rq = cpu_rq(dead_cpu);
5350 /* Must be exiting, otherwise would be on tasklist. */
5351 BUG_ON(p->exit_state != EXIT_ZOMBIE && p->exit_state != EXIT_DEAD);
5353 /* Cannot have done final schedule yet: would have vanished. */
5354 BUG_ON(p->state == TASK_DEAD);
5359 * Drop lock around migration; if someone else moves it,
5360 * that's OK. No task can be added to this CPU, so iteration is
5362 * NOTE: interrupts should be left disabled --dev@
5364 spin_unlock(&rq->lock);
5365 move_task_off_dead_cpu(dead_cpu, p);
5366 spin_lock(&rq->lock);
5371 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5372 static void migrate_dead_tasks(unsigned int dead_cpu)
5374 struct rq *rq = cpu_rq(dead_cpu);
5375 unsigned int arr, i;
5377 for (arr = 0; arr < 2; arr++) {
5378 for (i = 0; i < MAX_PRIO; i++) {
5379 struct list_head *list = &rq->arrays[arr].queue[i];
5381 while (!list_empty(list))
5382 migrate_dead(dead_cpu, list_entry(list->next,
5383 struct task_struct, run_list));
5387 #endif /* CONFIG_HOTPLUG_CPU */
5390 * migration_call - callback that gets triggered when a CPU is added.
5391 * Here we can start up the necessary migration thread for the new CPU.
5393 static int __cpuinit
5394 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
5396 struct task_struct *p;
5397 int cpu = (long)hcpu;
5398 unsigned long flags;
5402 case CPU_UP_PREPARE:
5403 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
5406 p->flags |= PF_NOFREEZE;
5407 kthread_bind(p, cpu);
5408 /* Must be high prio: stop_machine expects to yield to it. */
5409 rq = task_rq_lock(p, &flags);
5410 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
5411 task_rq_unlock(rq, &flags);
5412 cpu_rq(cpu)->migration_thread = p;
5416 /* Strictly unneccessary, as first user will wake it. */
5417 wake_up_process(cpu_rq(cpu)->migration_thread);
5420 #ifdef CONFIG_HOTPLUG_CPU
5421 case CPU_UP_CANCELED:
5422 if (!cpu_rq(cpu)->migration_thread)
5424 /* Unbind it from offline cpu so it can run. Fall thru. */
5425 kthread_bind(cpu_rq(cpu)->migration_thread,
5426 any_online_cpu(cpu_online_map));
5427 kthread_stop(cpu_rq(cpu)->migration_thread);
5428 cpu_rq(cpu)->migration_thread = NULL;
5432 migrate_live_tasks(cpu);
5434 kthread_stop(rq->migration_thread);
5435 rq->migration_thread = NULL;
5436 /* Idle task back to normal (off runqueue, low prio) */
5437 rq = task_rq_lock(rq->idle, &flags);
5438 deactivate_task(rq->idle, rq);
5439 rq->idle->static_prio = MAX_PRIO;
5440 __setscheduler(rq->idle, SCHED_NORMAL, 0);
5441 migrate_dead_tasks(cpu);
5442 task_rq_unlock(rq, &flags);
5443 migrate_nr_uninterruptible(rq);
5444 BUG_ON(rq->nr_running != 0);
5446 /* No need to migrate the tasks: it was best-effort if
5447 * they didn't do lock_cpu_hotplug(). Just wake up
5448 * the requestors. */
5449 spin_lock_irq(&rq->lock);
5450 while (!list_empty(&rq->migration_queue)) {
5451 struct migration_req *req;
5453 req = list_entry(rq->migration_queue.next,
5454 struct migration_req, list);
5455 list_del_init(&req->list);
5456 complete(&req->done);
5458 spin_unlock_irq(&rq->lock);
5465 /* Register at highest priority so that task migration (migrate_all_tasks)
5466 * happens before everything else.
5468 static struct notifier_block __cpuinitdata migration_notifier = {
5469 .notifier_call = migration_call,
5473 int __init migration_init(void)
5475 void *cpu = (void *)(long)smp_processor_id();
5478 /* Start one for the boot CPU: */
5479 err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5480 BUG_ON(err == NOTIFY_BAD);
5481 migration_call(&migration_notifier, CPU_ONLINE, cpu);
5482 register_cpu_notifier(&migration_notifier);
5489 #undef SCHED_DOMAIN_DEBUG
5490 #ifdef SCHED_DOMAIN_DEBUG
5491 static void sched_domain_debug(struct sched_domain *sd, int cpu)
5496 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5500 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5505 struct sched_group *group = sd->groups;
5506 cpumask_t groupmask;
5508 cpumask_scnprintf(str, NR_CPUS, sd->span);
5509 cpus_clear(groupmask);
5512 for (i = 0; i < level + 1; i++)
5514 printk("domain %d: ", level);
5516 if (!(sd->flags & SD_LOAD_BALANCE)) {
5517 printk("does not load-balance\n");
5519 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain"
5524 printk("span %s\n", str);
5526 if (!cpu_isset(cpu, sd->span))
5527 printk(KERN_ERR "ERROR: domain->span does not contain "
5529 if (!cpu_isset(cpu, group->cpumask))
5530 printk(KERN_ERR "ERROR: domain->groups does not contain"
5534 for (i = 0; i < level + 2; i++)
5540 printk(KERN_ERR "ERROR: group is NULL\n");
5544 if (!group->cpu_power) {
5546 printk(KERN_ERR "ERROR: domain->cpu_power not "
5550 if (!cpus_weight(group->cpumask)) {
5552 printk(KERN_ERR "ERROR: empty group\n");
5555 if (cpus_intersects(groupmask, group->cpumask)) {
5557 printk(KERN_ERR "ERROR: repeated CPUs\n");
5560 cpus_or(groupmask, groupmask, group->cpumask);
5562 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
5565 group = group->next;
5566 } while (group != sd->groups);
5569 if (!cpus_equal(sd->span, groupmask))
5570 printk(KERN_ERR "ERROR: groups don't span "
5578 if (!cpus_subset(groupmask, sd->span))
5579 printk(KERN_ERR "ERROR: parent span is not a superset "
5580 "of domain->span\n");
5585 # define sched_domain_debug(sd, cpu) do { } while (0)
5588 static int sd_degenerate(struct sched_domain *sd)
5590 if (cpus_weight(sd->span) == 1)
5593 /* Following flags need at least 2 groups */
5594 if (sd->flags & (SD_LOAD_BALANCE |
5595 SD_BALANCE_NEWIDLE |
5599 SD_SHARE_PKG_RESOURCES)) {
5600 if (sd->groups != sd->groups->next)
5604 /* Following flags don't use groups */
5605 if (sd->flags & (SD_WAKE_IDLE |
5614 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
5616 unsigned long cflags = sd->flags, pflags = parent->flags;
5618 if (sd_degenerate(parent))
5621 if (!cpus_equal(sd->span, parent->span))
5624 /* Does parent contain flags not in child? */
5625 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
5626 if (cflags & SD_WAKE_AFFINE)
5627 pflags &= ~SD_WAKE_BALANCE;
5628 /* Flags needing groups don't count if only 1 group in parent */
5629 if (parent->groups == parent->groups->next) {
5630 pflags &= ~(SD_LOAD_BALANCE |
5631 SD_BALANCE_NEWIDLE |
5635 SD_SHARE_PKG_RESOURCES);
5637 if (~cflags & pflags)
5644 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
5645 * hold the hotplug lock.
5647 static void cpu_attach_domain(struct sched_domain *sd, int cpu)
5649 struct rq *rq = cpu_rq(cpu);
5650 struct sched_domain *tmp;
5652 /* Remove the sched domains which do not contribute to scheduling. */
5653 for (tmp = sd; tmp; tmp = tmp->parent) {
5654 struct sched_domain *parent = tmp->parent;
5657 if (sd_parent_degenerate(tmp, parent)) {
5658 tmp->parent = parent->parent;
5660 parent->parent->child = tmp;
5664 if (sd && sd_degenerate(sd)) {
5670 sched_domain_debug(sd, cpu);
5672 rcu_assign_pointer(rq->sd, sd);
5675 /* cpus with isolated domains */
5676 static cpumask_t cpu_isolated_map = CPU_MASK_NONE;
5678 /* Setup the mask of cpus configured for isolated domains */
5679 static int __init isolated_cpu_setup(char *str)
5681 int ints[NR_CPUS], i;
5683 str = get_options(str, ARRAY_SIZE(ints), ints);
5684 cpus_clear(cpu_isolated_map);
5685 for (i = 1; i <= ints[0]; i++)
5686 if (ints[i] < NR_CPUS)
5687 cpu_set(ints[i], cpu_isolated_map);
5691 __setup ("isolcpus=", isolated_cpu_setup);
5694 * init_sched_build_groups takes the cpumask we wish to span, and a pointer
5695 * to a function which identifies what group(along with sched group) a CPU
5696 * belongs to. The return value of group_fn must be a >= 0 and < NR_CPUS
5697 * (due to the fact that we keep track of groups covered with a cpumask_t).
5699 * init_sched_build_groups will build a circular linked list of the groups
5700 * covered by the given span, and will set each group's ->cpumask correctly,
5701 * and ->cpu_power to 0.
5704 init_sched_build_groups(cpumask_t span, const cpumask_t *cpu_map,
5705 int (*group_fn)(int cpu, const cpumask_t *cpu_map,
5706 struct sched_group **sg))
5708 struct sched_group *first = NULL, *last = NULL;
5709 cpumask_t covered = CPU_MASK_NONE;
5712 for_each_cpu_mask(i, span) {
5713 struct sched_group *sg;
5714 int group = group_fn(i, cpu_map, &sg);
5717 if (cpu_isset(i, covered))
5720 sg->cpumask = CPU_MASK_NONE;
5723 for_each_cpu_mask(j, span) {
5724 if (group_fn(j, cpu_map, NULL) != group)
5727 cpu_set(j, covered);
5728 cpu_set(j, sg->cpumask);
5739 #define SD_NODES_PER_DOMAIN 16
5742 * Self-tuning task migration cost measurement between source and target CPUs.
5744 * This is done by measuring the cost of manipulating buffers of varying
5745 * sizes. For a given buffer-size here are the steps that are taken:
5747 * 1) the source CPU reads+dirties a shared buffer
5748 * 2) the target CPU reads+dirties the same shared buffer
5750 * We measure how long they take, in the following 4 scenarios:
5752 * - source: CPU1, target: CPU2 | cost1
5753 * - source: CPU2, target: CPU1 | cost2
5754 * - source: CPU1, target: CPU1 | cost3
5755 * - source: CPU2, target: CPU2 | cost4
5757 * We then calculate the cost3+cost4-cost1-cost2 difference - this is
5758 * the cost of migration.
5760 * We then start off from a small buffer-size and iterate up to larger
5761 * buffer sizes, in 5% steps - measuring each buffer-size separately, and
5762 * doing a maximum search for the cost. (The maximum cost for a migration
5763 * normally occurs when the working set size is around the effective cache
5766 #define SEARCH_SCOPE 2
5767 #define MIN_CACHE_SIZE (64*1024U)
5768 #define DEFAULT_CACHE_SIZE (5*1024*1024U)
5769 #define ITERATIONS 1
5770 #define SIZE_THRESH 130
5771 #define COST_THRESH 130
5774 * The migration cost is a function of 'domain distance'. Domain
5775 * distance is the number of steps a CPU has to iterate down its
5776 * domain tree to share a domain with the other CPU. The farther
5777 * two CPUs are from each other, the larger the distance gets.
5779 * Note that we use the distance only to cache measurement results,
5780 * the distance value is not used numerically otherwise. When two
5781 * CPUs have the same distance it is assumed that the migration
5782 * cost is the same. (this is a simplification but quite practical)
5784 #define MAX_DOMAIN_DISTANCE 32
5786 static unsigned long long migration_cost[MAX_DOMAIN_DISTANCE] =
5787 { [ 0 ... MAX_DOMAIN_DISTANCE-1 ] =
5789 * Architectures may override the migration cost and thus avoid
5790 * boot-time calibration. Unit is nanoseconds. Mostly useful for
5791 * virtualized hardware:
5793 #ifdef CONFIG_DEFAULT_MIGRATION_COST
5794 CONFIG_DEFAULT_MIGRATION_COST
5801 * Allow override of migration cost - in units of microseconds.
5802 * E.g. migration_cost=1000,2000,3000 will set up a level-1 cost
5803 * of 1 msec, level-2 cost of 2 msecs and level3 cost of 3 msecs:
5805 static int __init migration_cost_setup(char *str)
5807 int ints[MAX_DOMAIN_DISTANCE+1], i;
5809 str = get_options(str, ARRAY_SIZE(ints), ints);
5811 printk("#ints: %d\n", ints[0]);
5812 for (i = 1; i <= ints[0]; i++) {
5813 migration_cost[i-1] = (unsigned long long)ints[i]*1000;
5814 printk("migration_cost[%d]: %Ld\n", i-1, migration_cost[i-1]);
5819 __setup ("migration_cost=", migration_cost_setup);
5822 * Global multiplier (divisor) for migration-cutoff values,
5823 * in percentiles. E.g. use a value of 150 to get 1.5 times
5824 * longer cache-hot cutoff times.
5826 * (We scale it from 100 to 128 to long long handling easier.)
5829 #define MIGRATION_FACTOR_SCALE 128
5831 static unsigned int migration_factor = MIGRATION_FACTOR_SCALE;
5833 static int __init setup_migration_factor(char *str)
5835 get_option(&str, &migration_factor);
5836 migration_factor = migration_factor * MIGRATION_FACTOR_SCALE / 100;
5840 __setup("migration_factor=", setup_migration_factor);
5843 * Estimated distance of two CPUs, measured via the number of domains
5844 * we have to pass for the two CPUs to be in the same span:
5846 static unsigned long domain_distance(int cpu1, int cpu2)
5848 unsigned long distance = 0;
5849 struct sched_domain *sd;
5851 for_each_domain(cpu1, sd) {
5852 WARN_ON(!cpu_isset(cpu1, sd->span));
5853 if (cpu_isset(cpu2, sd->span))
5857 if (distance >= MAX_DOMAIN_DISTANCE) {
5859 distance = MAX_DOMAIN_DISTANCE-1;
5865 static unsigned int migration_debug;
5867 static int __init setup_migration_debug(char *str)
5869 get_option(&str, &migration_debug);
5873 __setup("migration_debug=", setup_migration_debug);
5876 * Maximum cache-size that the scheduler should try to measure.
5877 * Architectures with larger caches should tune this up during
5878 * bootup. Gets used in the domain-setup code (i.e. during SMP
5881 unsigned int max_cache_size;
5883 static int __init setup_max_cache_size(char *str)
5885 get_option(&str, &max_cache_size);
5889 __setup("max_cache_size=", setup_max_cache_size);
5892 * Dirty a big buffer in a hard-to-predict (for the L2 cache) way. This
5893 * is the operation that is timed, so we try to generate unpredictable
5894 * cachemisses that still end up filling the L2 cache:
5896 static void touch_cache(void *__cache, unsigned long __size)
5898 unsigned long size = __size / sizeof(long);
5899 unsigned long chunk1 = size / 3;
5900 unsigned long chunk2 = 2 * size / 3;
5901 unsigned long *cache = __cache;
5904 for (i = 0; i < size/6; i += 8) {
5907 case 1: cache[size-1-i]++;
5908 case 2: cache[chunk1-i]++;
5909 case 3: cache[chunk1+i]++;
5910 case 4: cache[chunk2-i]++;
5911 case 5: cache[chunk2+i]++;
5917 * Measure the cache-cost of one task migration. Returns in units of nsec.
5919 static unsigned long long
5920 measure_one(void *cache, unsigned long size, int source, int target)
5922 cpumask_t mask, saved_mask;
5923 unsigned long long t0, t1, t2, t3, cost;
5925 saved_mask = current->cpus_allowed;
5928 * Flush source caches to RAM and invalidate them:
5933 * Migrate to the source CPU:
5935 mask = cpumask_of_cpu(source);
5936 set_cpus_allowed(current, mask);
5937 WARN_ON(smp_processor_id() != source);
5940 * Dirty the working set:
5943 touch_cache(cache, size);
5947 * Migrate to the target CPU, dirty the L2 cache and access
5948 * the shared buffer. (which represents the working set
5949 * of a migrated task.)
5951 mask = cpumask_of_cpu(target);
5952 set_cpus_allowed(current, mask);
5953 WARN_ON(smp_processor_id() != target);
5956 touch_cache(cache, size);
5959 cost = t1-t0 + t3-t2;
5961 if (migration_debug >= 2)
5962 printk("[%d->%d]: %8Ld %8Ld %8Ld => %10Ld.\n",
5963 source, target, t1-t0, t1-t0, t3-t2, cost);
5965 * Flush target caches to RAM and invalidate them:
5969 set_cpus_allowed(current, saved_mask);
5975 * Measure a series of task migrations and return the average
5976 * result. Since this code runs early during bootup the system
5977 * is 'undisturbed' and the average latency makes sense.
5979 * The algorithm in essence auto-detects the relevant cache-size,
5980 * so it will properly detect different cachesizes for different
5981 * cache-hierarchies, depending on how the CPUs are connected.
5983 * Architectures can prime the upper limit of the search range via
5984 * max_cache_size, otherwise the search range defaults to 20MB...64K.
5986 static unsigned long long
5987 measure_cost(int cpu1, int cpu2, void *cache, unsigned int size)
5989 unsigned long long cost1, cost2;
5993 * Measure the migration cost of 'size' bytes, over an
5994 * average of 10 runs:
5996 * (We perturb the cache size by a small (0..4k)
5997 * value to compensate size/alignment related artifacts.
5998 * We also subtract the cost of the operation done on
6004 * dry run, to make sure we start off cache-cold on cpu1,
6005 * and to get any vmalloc pagefaults in advance:
6007 measure_one(cache, size, cpu1, cpu2);
6008 for (i = 0; i < ITERATIONS; i++)
6009 cost1 += measure_one(cache, size - i * 1024, cpu1, cpu2);
6011 measure_one(cache, size, cpu2, cpu1);
6012 for (i = 0; i < ITERATIONS; i++)
6013 cost1 += measure_one(cache, size - i * 1024, cpu2, cpu1);
6016 * (We measure the non-migrating [cached] cost on both
6017 * cpu1 and cpu2, to handle CPUs with different speeds)
6021 measure_one(cache, size, cpu1, cpu1);
6022 for (i = 0; i < ITERATIONS; i++)
6023 cost2 += measure_one(cache, size - i * 1024, cpu1, cpu1);
6025 measure_one(cache, size, cpu2, cpu2);
6026 for (i = 0; i < ITERATIONS; i++)
6027 cost2 += measure_one(cache, size - i * 1024, cpu2, cpu2);
6030 * Get the per-iteration migration cost:
6032 do_div(cost1, 2 * ITERATIONS);
6033 do_div(cost2, 2 * ITERATIONS);
6035 return cost1 - cost2;
6038 static unsigned long long measure_migration_cost(int cpu1, int cpu2)
6040 unsigned long long max_cost = 0, fluct = 0, avg_fluct = 0;
6041 unsigned int max_size, size, size_found = 0;
6042 long long cost = 0, prev_cost;
6046 * Search from max_cache_size*5 down to 64K - the real relevant
6047 * cachesize has to lie somewhere inbetween.
6049 if (max_cache_size) {
6050 max_size = max(max_cache_size * SEARCH_SCOPE, MIN_CACHE_SIZE);
6051 size = max(max_cache_size / SEARCH_SCOPE, MIN_CACHE_SIZE);
6054 * Since we have no estimation about the relevant
6057 max_size = DEFAULT_CACHE_SIZE * SEARCH_SCOPE;
6058 size = MIN_CACHE_SIZE;
6061 if (!cpu_online(cpu1) || !cpu_online(cpu2)) {
6062 printk("cpu %d and %d not both online!\n", cpu1, cpu2);
6067 * Allocate the working set:
6069 cache = vmalloc(max_size);
6071 printk("could not vmalloc %d bytes for cache!\n", 2 * max_size);
6072 return 1000000; /* return 1 msec on very small boxen */
6075 while (size <= max_size) {
6077 cost = measure_cost(cpu1, cpu2, cache, size);
6083 if (max_cost < cost) {
6089 * Calculate average fluctuation, we use this to prevent
6090 * noise from triggering an early break out of the loop:
6092 fluct = abs(cost - prev_cost);
6093 avg_fluct = (avg_fluct + fluct)/2;
6095 if (migration_debug)
6096 printk("-> [%d][%d][%7d] %3ld.%ld [%3ld.%ld] (%ld): "
6099 (long)cost / 1000000,
6100 ((long)cost / 100000) % 10,
6101 (long)max_cost / 1000000,
6102 ((long)max_cost / 100000) % 10,
6103 domain_distance(cpu1, cpu2),
6107 * If we iterated at least 20% past the previous maximum,
6108 * and the cost has dropped by more than 20% already,
6109 * (taking fluctuations into account) then we assume to
6110 * have found the maximum and break out of the loop early:
6112 if (size_found && (size*100 > size_found*SIZE_THRESH))
6113 if (cost+avg_fluct <= 0 ||
6114 max_cost*100 > (cost+avg_fluct)*COST_THRESH) {
6116 if (migration_debug)
6117 printk("-> found max.\n");
6121 * Increase the cachesize in 10% steps:
6123 size = size * 10 / 9;
6126 if (migration_debug)
6127 printk("[%d][%d] working set size found: %d, cost: %Ld\n",
6128 cpu1, cpu2, size_found, max_cost);
6133 * A task is considered 'cache cold' if at least 2 times
6134 * the worst-case cost of migration has passed.
6136 * (this limit is only listened to if the load-balancing
6137 * situation is 'nice' - if there is a large imbalance we
6138 * ignore it for the sake of CPU utilization and
6139 * processing fairness.)
6141 return 2 * max_cost * migration_factor / MIGRATION_FACTOR_SCALE;
6144 static void calibrate_migration_costs(const cpumask_t *cpu_map)
6146 int cpu1 = -1, cpu2 = -1, cpu, orig_cpu = raw_smp_processor_id();
6147 unsigned long j0, j1, distance, max_distance = 0;
6148 struct sched_domain *sd;
6153 * First pass - calculate the cacheflush times:
6155 for_each_cpu_mask(cpu1, *cpu_map) {
6156 for_each_cpu_mask(cpu2, *cpu_map) {
6159 distance = domain_distance(cpu1, cpu2);
6160 max_distance = max(max_distance, distance);
6162 * No result cached yet?
6164 if (migration_cost[distance] == -1LL)
6165 migration_cost[distance] =
6166 measure_migration_cost(cpu1, cpu2);
6170 * Second pass - update the sched domain hierarchy with
6171 * the new cache-hot-time estimations:
6173 for_each_cpu_mask(cpu, *cpu_map) {
6175 for_each_domain(cpu, sd) {
6176 sd->cache_hot_time = migration_cost[distance];
6183 if (migration_debug)
6184 printk("migration: max_cache_size: %d, cpu: %d MHz:\n",
6192 if (system_state == SYSTEM_BOOTING && num_online_cpus() > 1) {
6193 printk("migration_cost=");
6194 for (distance = 0; distance <= max_distance; distance++) {
6197 printk("%ld", (long)migration_cost[distance] / 1000);
6202 if (migration_debug)
6203 printk("migration: %ld seconds\n", (j1-j0) / HZ);
6206 * Move back to the original CPU. NUMA-Q gets confused
6207 * if we migrate to another quad during bootup.
6209 if (raw_smp_processor_id() != orig_cpu) {
6210 cpumask_t mask = cpumask_of_cpu(orig_cpu),
6211 saved_mask = current->cpus_allowed;
6213 set_cpus_allowed(current, mask);
6214 set_cpus_allowed(current, saved_mask);
6221 * find_next_best_node - find the next node to include in a sched_domain
6222 * @node: node whose sched_domain we're building
6223 * @used_nodes: nodes already in the sched_domain
6225 * Find the next node to include in a given scheduling domain. Simply
6226 * finds the closest node not already in the @used_nodes map.
6228 * Should use nodemask_t.
6230 static int find_next_best_node(int node, unsigned long *used_nodes)
6232 int i, n, val, min_val, best_node = 0;
6236 for (i = 0; i < MAX_NUMNODES; i++) {
6237 /* Start at @node */
6238 n = (node + i) % MAX_NUMNODES;
6240 if (!nr_cpus_node(n))
6243 /* Skip already used nodes */
6244 if (test_bit(n, used_nodes))
6247 /* Simple min distance search */
6248 val = node_distance(node, n);
6250 if (val < min_val) {
6256 set_bit(best_node, used_nodes);
6261 * sched_domain_node_span - get a cpumask for a node's sched_domain
6262 * @node: node whose cpumask we're constructing
6263 * @size: number of nodes to include in this span
6265 * Given a node, construct a good cpumask for its sched_domain to span. It
6266 * should be one that prevents unnecessary balancing, but also spreads tasks
6269 static cpumask_t sched_domain_node_span(int node)
6271 DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
6272 cpumask_t span, nodemask;
6276 bitmap_zero(used_nodes, MAX_NUMNODES);
6278 nodemask = node_to_cpumask(node);
6279 cpus_or(span, span, nodemask);
6280 set_bit(node, used_nodes);
6282 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
6283 int next_node = find_next_best_node(node, used_nodes);
6285 nodemask = node_to_cpumask(next_node);
6286 cpus_or(span, span, nodemask);
6293 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6296 * SMT sched-domains:
6298 #ifdef CONFIG_SCHED_SMT
6299 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
6300 static DEFINE_PER_CPU(struct sched_group, sched_group_cpus);
6302 static int cpu_to_cpu_group(int cpu, const cpumask_t *cpu_map,
6303 struct sched_group **sg)
6306 *sg = &per_cpu(sched_group_cpus, cpu);
6312 * multi-core sched-domains:
6314 #ifdef CONFIG_SCHED_MC
6315 static DEFINE_PER_CPU(struct sched_domain, core_domains);
6316 static DEFINE_PER_CPU(struct sched_group, sched_group_core);
6319 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6320 static int cpu_to_core_group(int cpu, const cpumask_t *cpu_map,
6321 struct sched_group **sg)
6324 cpumask_t mask = cpu_sibling_map[cpu];
6325 cpus_and(mask, mask, *cpu_map);
6326 group = first_cpu(mask);
6328 *sg = &per_cpu(sched_group_core, group);
6331 #elif defined(CONFIG_SCHED_MC)
6332 static int cpu_to_core_group(int cpu, const cpumask_t *cpu_map,
6333 struct sched_group **sg)
6336 *sg = &per_cpu(sched_group_core, cpu);
6341 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
6342 static DEFINE_PER_CPU(struct sched_group, sched_group_phys);
6344 static int cpu_to_phys_group(int cpu, const cpumask_t *cpu_map,
6345 struct sched_group **sg)
6348 #ifdef CONFIG_SCHED_MC
6349 cpumask_t mask = cpu_coregroup_map(cpu);
6350 cpus_and(mask, mask, *cpu_map);
6351 group = first_cpu(mask);
6352 #elif defined(CONFIG_SCHED_SMT)
6353 cpumask_t mask = cpu_sibling_map[cpu];
6354 cpus_and(mask, mask, *cpu_map);
6355 group = first_cpu(mask);
6360 *sg = &per_cpu(sched_group_phys, group);
6366 * The init_sched_build_groups can't handle what we want to do with node
6367 * groups, so roll our own. Now each node has its own list of groups which
6368 * gets dynamically allocated.
6370 static DEFINE_PER_CPU(struct sched_domain, node_domains);
6371 static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
6373 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
6374 static DEFINE_PER_CPU(struct sched_group, sched_group_allnodes);
6376 static int cpu_to_allnodes_group(int cpu, const cpumask_t *cpu_map,
6377 struct sched_group **sg)
6379 cpumask_t nodemask = node_to_cpumask(cpu_to_node(cpu));
6382 cpus_and(nodemask, nodemask, *cpu_map);
6383 group = first_cpu(nodemask);
6386 *sg = &per_cpu(sched_group_allnodes, group);
6390 static void init_numa_sched_groups_power(struct sched_group *group_head)
6392 struct sched_group *sg = group_head;
6398 for_each_cpu_mask(j, sg->cpumask) {
6399 struct sched_domain *sd;
6401 sd = &per_cpu(phys_domains, j);
6402 if (j != first_cpu(sd->groups->cpumask)) {
6404 * Only add "power" once for each
6410 sg->cpu_power += sd->groups->cpu_power;
6413 if (sg != group_head)
6419 /* Free memory allocated for various sched_group structures */
6420 static void free_sched_groups(const cpumask_t *cpu_map)
6424 for_each_cpu_mask(cpu, *cpu_map) {
6425 struct sched_group **sched_group_nodes
6426 = sched_group_nodes_bycpu[cpu];
6428 if (!sched_group_nodes)
6431 for (i = 0; i < MAX_NUMNODES; i++) {
6432 cpumask_t nodemask = node_to_cpumask(i);
6433 struct sched_group *oldsg, *sg = sched_group_nodes[i];
6435 cpus_and(nodemask, nodemask, *cpu_map);
6436 if (cpus_empty(nodemask))
6446 if (oldsg != sched_group_nodes[i])
6449 kfree(sched_group_nodes);
6450 sched_group_nodes_bycpu[cpu] = NULL;
6454 static void free_sched_groups(const cpumask_t *cpu_map)
6460 * Initialize sched groups cpu_power.
6462 * cpu_power indicates the capacity of sched group, which is used while
6463 * distributing the load between different sched groups in a sched domain.
6464 * Typically cpu_power for all the groups in a sched domain will be same unless
6465 * there are asymmetries in the topology. If there are asymmetries, group
6466 * having more cpu_power will pickup more load compared to the group having
6469 * cpu_power will be a multiple of SCHED_LOAD_SCALE. This multiple represents
6470 * the maximum number of tasks a group can handle in the presence of other idle
6471 * or lightly loaded groups in the same sched domain.
6473 static void init_sched_groups_power(int cpu, struct sched_domain *sd)
6475 struct sched_domain *child;
6476 struct sched_group *group;
6478 WARN_ON(!sd || !sd->groups);
6480 if (cpu != first_cpu(sd->groups->cpumask))
6486 * For perf policy, if the groups in child domain share resources
6487 * (for example cores sharing some portions of the cache hierarchy
6488 * or SMT), then set this domain groups cpu_power such that each group
6489 * can handle only one task, when there are other idle groups in the
6490 * same sched domain.
6492 if (!child || (!(sd->flags & SD_POWERSAVINGS_BALANCE) &&
6494 (SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)))) {
6495 sd->groups->cpu_power = SCHED_LOAD_SCALE;
6499 sd->groups->cpu_power = 0;
6502 * add cpu_power of each child group to this groups cpu_power
6504 group = child->groups;
6506 sd->groups->cpu_power += group->cpu_power;
6507 group = group->next;
6508 } while (group != child->groups);
6512 * Build sched domains for a given set of cpus and attach the sched domains
6513 * to the individual cpus
6515 static int build_sched_domains(const cpumask_t *cpu_map)
6518 struct sched_domain *sd;
6520 struct sched_group **sched_group_nodes = NULL;
6521 int sd_allnodes = 0;
6524 * Allocate the per-node list of sched groups
6526 sched_group_nodes = kzalloc(sizeof(struct sched_group*)*MAX_NUMNODES,
6528 if (!sched_group_nodes) {
6529 printk(KERN_WARNING "Can not alloc sched group node list\n");
6532 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
6536 * Set up domains for cpus specified by the cpu_map.
6538 for_each_cpu_mask(i, *cpu_map) {
6539 struct sched_domain *sd = NULL, *p;
6540 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
6542 cpus_and(nodemask, nodemask, *cpu_map);
6545 if (cpus_weight(*cpu_map)
6546 > SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
6547 sd = &per_cpu(allnodes_domains, i);
6548 *sd = SD_ALLNODES_INIT;
6549 sd->span = *cpu_map;
6550 cpu_to_allnodes_group(i, cpu_map, &sd->groups);
6556 sd = &per_cpu(node_domains, i);
6558 sd->span = sched_domain_node_span(cpu_to_node(i));
6562 cpus_and(sd->span, sd->span, *cpu_map);
6566 sd = &per_cpu(phys_domains, i);
6568 sd->span = nodemask;
6572 cpu_to_phys_group(i, cpu_map, &sd->groups);
6574 #ifdef CONFIG_SCHED_MC
6576 sd = &per_cpu(core_domains, i);
6578 sd->span = cpu_coregroup_map(i);
6579 cpus_and(sd->span, sd->span, *cpu_map);
6582 cpu_to_core_group(i, cpu_map, &sd->groups);
6585 #ifdef CONFIG_SCHED_SMT
6587 sd = &per_cpu(cpu_domains, i);
6588 *sd = SD_SIBLING_INIT;
6589 sd->span = cpu_sibling_map[i];
6590 cpus_and(sd->span, sd->span, *cpu_map);
6593 cpu_to_cpu_group(i, cpu_map, &sd->groups);
6597 #ifdef CONFIG_SCHED_SMT
6598 /* Set up CPU (sibling) groups */
6599 for_each_cpu_mask(i, *cpu_map) {
6600 cpumask_t this_sibling_map = cpu_sibling_map[i];
6601 cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
6602 if (i != first_cpu(this_sibling_map))
6605 init_sched_build_groups(this_sibling_map, cpu_map, &cpu_to_cpu_group);
6609 #ifdef CONFIG_SCHED_MC
6610 /* Set up multi-core groups */
6611 for_each_cpu_mask(i, *cpu_map) {
6612 cpumask_t this_core_map = cpu_coregroup_map(i);
6613 cpus_and(this_core_map, this_core_map, *cpu_map);
6614 if (i != first_cpu(this_core_map))
6616 init_sched_build_groups(this_core_map, cpu_map, &cpu_to_core_group);
6621 /* Set up physical groups */
6622 for (i = 0; i < MAX_NUMNODES; i++) {
6623 cpumask_t nodemask = node_to_cpumask(i);
6625 cpus_and(nodemask, nodemask, *cpu_map);
6626 if (cpus_empty(nodemask))
6629 init_sched_build_groups(nodemask, cpu_map, &cpu_to_phys_group);
6633 /* Set up node groups */
6635 init_sched_build_groups(*cpu_map, cpu_map, &cpu_to_allnodes_group);
6637 for (i = 0; i < MAX_NUMNODES; i++) {
6638 /* Set up node groups */
6639 struct sched_group *sg, *prev;
6640 cpumask_t nodemask = node_to_cpumask(i);
6641 cpumask_t domainspan;
6642 cpumask_t covered = CPU_MASK_NONE;
6645 cpus_and(nodemask, nodemask, *cpu_map);
6646 if (cpus_empty(nodemask)) {
6647 sched_group_nodes[i] = NULL;
6651 domainspan = sched_domain_node_span(i);
6652 cpus_and(domainspan, domainspan, *cpu_map);
6654 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
6656 printk(KERN_WARNING "Can not alloc domain group for "
6660 sched_group_nodes[i] = sg;
6661 for_each_cpu_mask(j, nodemask) {
6662 struct sched_domain *sd;
6663 sd = &per_cpu(node_domains, j);
6667 sg->cpumask = nodemask;
6669 cpus_or(covered, covered, nodemask);
6672 for (j = 0; j < MAX_NUMNODES; j++) {
6673 cpumask_t tmp, notcovered;
6674 int n = (i + j) % MAX_NUMNODES;
6676 cpus_complement(notcovered, covered);
6677 cpus_and(tmp, notcovered, *cpu_map);
6678 cpus_and(tmp, tmp, domainspan);
6679 if (cpus_empty(tmp))
6682 nodemask = node_to_cpumask(n);
6683 cpus_and(tmp, tmp, nodemask);
6684 if (cpus_empty(tmp))
6687 sg = kmalloc_node(sizeof(struct sched_group),
6691 "Can not alloc domain group for node %d\n", j);
6696 sg->next = prev->next;
6697 cpus_or(covered, covered, tmp);
6704 /* Calculate CPU power for physical packages and nodes */
6705 #ifdef CONFIG_SCHED_SMT
6706 for_each_cpu_mask(i, *cpu_map) {
6707 sd = &per_cpu(cpu_domains, i);
6708 init_sched_groups_power(i, sd);
6711 #ifdef CONFIG_SCHED_MC
6712 for_each_cpu_mask(i, *cpu_map) {
6713 sd = &per_cpu(core_domains, i);
6714 init_sched_groups_power(i, sd);
6718 for_each_cpu_mask(i, *cpu_map) {
6719 sd = &per_cpu(phys_domains, i);
6720 init_sched_groups_power(i, sd);
6724 for (i = 0; i < MAX_NUMNODES; i++)
6725 init_numa_sched_groups_power(sched_group_nodes[i]);
6728 struct sched_group *sg;
6730 cpu_to_allnodes_group(first_cpu(*cpu_map), cpu_map, &sg);
6731 init_numa_sched_groups_power(sg);
6735 /* Attach the domains */
6736 for_each_cpu_mask(i, *cpu_map) {
6737 struct sched_domain *sd;
6738 #ifdef CONFIG_SCHED_SMT
6739 sd = &per_cpu(cpu_domains, i);
6740 #elif defined(CONFIG_SCHED_MC)
6741 sd = &per_cpu(core_domains, i);
6743 sd = &per_cpu(phys_domains, i);
6745 cpu_attach_domain(sd, i);
6748 * Tune cache-hot values:
6750 calibrate_migration_costs(cpu_map);
6756 free_sched_groups(cpu_map);
6761 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6763 static int arch_init_sched_domains(const cpumask_t *cpu_map)
6765 cpumask_t cpu_default_map;
6769 * Setup mask for cpus without special case scheduling requirements.
6770 * For now this just excludes isolated cpus, but could be used to
6771 * exclude other special cases in the future.
6773 cpus_andnot(cpu_default_map, *cpu_map, cpu_isolated_map);
6775 err = build_sched_domains(&cpu_default_map);
6780 static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
6782 free_sched_groups(cpu_map);
6786 * Detach sched domains from a group of cpus specified in cpu_map
6787 * These cpus will now be attached to the NULL domain
6789 static void detach_destroy_domains(const cpumask_t *cpu_map)
6793 for_each_cpu_mask(i, *cpu_map)
6794 cpu_attach_domain(NULL, i);
6795 synchronize_sched();
6796 arch_destroy_sched_domains(cpu_map);
6800 * Partition sched domains as specified by the cpumasks below.
6801 * This attaches all cpus from the cpumasks to the NULL domain,
6802 * waits for a RCU quiescent period, recalculates sched
6803 * domain information and then attaches them back to the
6804 * correct sched domains
6805 * Call with hotplug lock held
6807 int partition_sched_domains(cpumask_t *partition1, cpumask_t *partition2)
6809 cpumask_t change_map;
6812 cpus_and(*partition1, *partition1, cpu_online_map);
6813 cpus_and(*partition2, *partition2, cpu_online_map);
6814 cpus_or(change_map, *partition1, *partition2);
6816 /* Detach sched domains from all of the affected cpus */
6817 detach_destroy_domains(&change_map);
6818 if (!cpus_empty(*partition1))
6819 err = build_sched_domains(partition1);
6820 if (!err && !cpus_empty(*partition2))
6821 err = build_sched_domains(partition2);
6826 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
6827 int arch_reinit_sched_domains(void)
6832 detach_destroy_domains(&cpu_online_map);
6833 err = arch_init_sched_domains(&cpu_online_map);
6834 unlock_cpu_hotplug();
6839 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
6843 if (buf[0] != '0' && buf[0] != '1')
6847 sched_smt_power_savings = (buf[0] == '1');
6849 sched_mc_power_savings = (buf[0] == '1');
6851 ret = arch_reinit_sched_domains();
6853 return ret ? ret : count;
6856 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
6860 #ifdef CONFIG_SCHED_SMT
6862 err = sysfs_create_file(&cls->kset.kobj,
6863 &attr_sched_smt_power_savings.attr);
6865 #ifdef CONFIG_SCHED_MC
6866 if (!err && mc_capable())
6867 err = sysfs_create_file(&cls->kset.kobj,
6868 &attr_sched_mc_power_savings.attr);
6874 #ifdef CONFIG_SCHED_MC
6875 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
6877 return sprintf(page, "%u\n", sched_mc_power_savings);
6879 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
6880 const char *buf, size_t count)
6882 return sched_power_savings_store(buf, count, 0);
6884 SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
6885 sched_mc_power_savings_store);
6888 #ifdef CONFIG_SCHED_SMT
6889 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
6891 return sprintf(page, "%u\n", sched_smt_power_savings);
6893 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
6894 const char *buf, size_t count)
6896 return sched_power_savings_store(buf, count, 1);
6898 SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
6899 sched_smt_power_savings_store);
6903 * Force a reinitialization of the sched domains hierarchy. The domains
6904 * and groups cannot be updated in place without racing with the balancing
6905 * code, so we temporarily attach all running cpus to the NULL domain
6906 * which will prevent rebalancing while the sched domains are recalculated.
6908 static int update_sched_domains(struct notifier_block *nfb,
6909 unsigned long action, void *hcpu)
6912 case CPU_UP_PREPARE:
6913 case CPU_DOWN_PREPARE:
6914 detach_destroy_domains(&cpu_online_map);
6917 case CPU_UP_CANCELED:
6918 case CPU_DOWN_FAILED:
6922 * Fall through and re-initialise the domains.
6929 /* The hotplug lock is already held by cpu_up/cpu_down */
6930 arch_init_sched_domains(&cpu_online_map);
6935 void __init sched_init_smp(void)
6937 cpumask_t non_isolated_cpus;
6940 arch_init_sched_domains(&cpu_online_map);
6941 cpus_andnot(non_isolated_cpus, cpu_possible_map, cpu_isolated_map);
6942 if (cpus_empty(non_isolated_cpus))
6943 cpu_set(smp_processor_id(), non_isolated_cpus);
6944 unlock_cpu_hotplug();
6945 /* XXX: Theoretical race here - CPU may be hotplugged now */
6946 hotcpu_notifier(update_sched_domains, 0);
6948 /* Move init over to a non-isolated CPU */
6949 if (set_cpus_allowed(current, non_isolated_cpus) < 0)
6953 void __init sched_init_smp(void)
6956 #endif /* CONFIG_SMP */
6958 int in_sched_functions(unsigned long addr)
6960 /* Linker adds these: start and end of __sched functions */
6961 extern char __sched_text_start[], __sched_text_end[];
6963 return in_lock_functions(addr) ||
6964 (addr >= (unsigned long)__sched_text_start
6965 && addr < (unsigned long)__sched_text_end);
6968 void __init sched_init(void)
6972 for_each_possible_cpu(i) {
6973 struct prio_array *array;
6977 spin_lock_init(&rq->lock);
6978 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
6980 rq->active = rq->arrays;
6981 rq->expired = rq->arrays + 1;
6982 rq->best_expired_prio = MAX_PRIO;
6986 for (j = 1; j < 3; j++)
6987 rq->cpu_load[j] = 0;
6988 rq->active_balance = 0;
6991 rq->migration_thread = NULL;
6992 INIT_LIST_HEAD(&rq->migration_queue);
6994 atomic_set(&rq->nr_iowait, 0);
6995 #ifdef CONFIG_VSERVER_HARDCPU
6996 INIT_LIST_HEAD(&rq->hold_queue);
6999 for (j = 0; j < 2; j++) {
7000 array = rq->arrays + j;
7001 for (k = 0; k < MAX_PRIO; k++) {
7002 INIT_LIST_HEAD(array->queue + k);
7003 __clear_bit(k, array->bitmap);
7005 // delimiter for bitsearch
7006 __set_bit(MAX_PRIO, array->bitmap);
7010 set_load_weight(&init_task);
7013 open_softirq(SCHED_SOFTIRQ, run_rebalance_domains, NULL);
7016 #ifdef CONFIG_RT_MUTEXES
7017 plist_head_init(&init_task.pi_waiters, &init_task.pi_lock);
7021 * The boot idle thread does lazy MMU switching as well:
7023 atomic_inc(&init_mm.mm_count);
7024 enter_lazy_tlb(&init_mm, current);
7027 * Make us the idle thread. Technically, schedule() should not be
7028 * called from this thread, however somewhere below it might be,
7029 * but because we are the idle thread, we just pick up running again
7030 * when this runqueue becomes "idle".
7032 init_idle(current, smp_processor_id());
7035 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
7036 void __might_sleep(char *file, int line)
7039 static unsigned long prev_jiffy; /* ratelimiting */
7041 if ((in_atomic() || irqs_disabled()) &&
7042 system_state == SYSTEM_RUNNING && !oops_in_progress) {
7043 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7045 prev_jiffy = jiffies;
7046 printk(KERN_ERR "BUG: sleeping function called from invalid"
7047 " context at %s:%d\n", file, line);
7048 printk("in_atomic():%d, irqs_disabled():%d\n",
7049 in_atomic(), irqs_disabled());
7050 debug_show_held_locks(current);
7051 if (irqs_disabled())
7052 print_irqtrace_events(current);
7057 EXPORT_SYMBOL(__might_sleep);
7060 #ifdef CONFIG_MAGIC_SYSRQ
7061 void normalize_rt_tasks(void)
7063 struct prio_array *array;
7064 struct task_struct *p;
7065 unsigned long flags;
7068 read_lock_irq(&tasklist_lock);
7069 for_each_process(p) {
7073 spin_lock_irqsave(&p->pi_lock, flags);
7074 rq = __task_rq_lock(p);
7078 deactivate_task(p, task_rq(p));
7079 __setscheduler(p, SCHED_NORMAL, 0);
7081 vx_activate_task(p);
7082 __activate_task(p, task_rq(p));
7083 resched_task(rq->curr);
7086 __task_rq_unlock(rq);
7087 spin_unlock_irqrestore(&p->pi_lock, flags);
7089 read_unlock_irq(&tasklist_lock);
7092 #endif /* CONFIG_MAGIC_SYSRQ */
7096 * These functions are only useful for the IA64 MCA handling.
7098 * They can only be called when the whole system has been
7099 * stopped - every CPU needs to be quiescent, and no scheduling
7100 * activity can take place. Using them for anything else would
7101 * be a serious bug, and as a result, they aren't even visible
7102 * under any other configuration.
7106 * curr_task - return the current task for a given cpu.
7107 * @cpu: the processor in question.
7109 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7111 struct task_struct *curr_task(int cpu)
7113 return cpu_curr(cpu);
7117 * set_curr_task - set the current task for a given cpu.
7118 * @cpu: the processor in question.
7119 * @p: the task pointer to set.
7121 * Description: This function must only be used when non-maskable interrupts
7122 * are serviced on a separate stack. It allows the architecture to switch the
7123 * notion of the current task on a cpu in a non-blocking manner. This function
7124 * must be called with all CPU's synchronized, and interrupts disabled, the
7125 * and caller must save the original value of the current task (see
7126 * curr_task() above) and restore that value before reenabling interrupts and
7127 * re-starting the system.
7129 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7131 void set_curr_task(int cpu, struct task_struct *p)