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/security.h>
34 #include <linux/notifier.h>
35 #include <linux/profile.h>
36 #include <linux/suspend.h>
37 #include <linux/vmalloc.h>
38 #include <linux/blkdev.h>
39 #include <linux/delay.h>
40 #include <linux/smp.h>
41 #include <linux/threads.h>
42 #include <linux/timer.h>
43 #include <linux/rcupdate.h>
44 #include <linux/cpu.h>
45 #include <linux/cpuset.h>
46 #include <linux/percpu.h>
47 #include <linux/kthread.h>
48 #include <linux/seq_file.h>
49 #include <linux/syscalls.h>
50 #include <linux/times.h>
51 #include <linux/acct.h>
52 #include <linux/kprobes.h>
55 #include <asm/unistd.h>
58 * Convert user-nice values [ -20 ... 0 ... 19 ]
59 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
62 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
63 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
64 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
67 * 'User priority' is the nice value converted to something we
68 * can work with better when scaling various scheduler parameters,
69 * it's a [ 0 ... 39 ] range.
71 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
72 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
73 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
76 * Some helpers for converting nanosecond timing to jiffy resolution
78 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
79 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
82 * These are the 'tuning knobs' of the scheduler:
84 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
85 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
86 * Timeslices get refilled after they expire.
88 #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
89 #define DEF_TIMESLICE (100 * HZ / 1000)
90 #define ON_RUNQUEUE_WEIGHT 30
91 #define CHILD_PENALTY 95
92 #define PARENT_PENALTY 100
94 #define PRIO_BONUS_RATIO 25
95 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
96 #define INTERACTIVE_DELTA 2
97 #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
98 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
99 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
102 * If a task is 'interactive' then we reinsert it in the active
103 * array after it has expired its current timeslice. (it will not
104 * continue to run immediately, it will still roundrobin with
105 * other interactive tasks.)
107 * This part scales the interactivity limit depending on niceness.
109 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
110 * Here are a few examples of different nice levels:
112 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
113 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
114 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
115 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
116 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
118 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
119 * priority range a task can explore, a value of '1' means the
120 * task is rated interactive.)
122 * Ie. nice +19 tasks can never get 'interactive' enough to be
123 * reinserted into the active array. And only heavily CPU-hog nice -20
124 * tasks will be expired. Default nice 0 tasks are somewhere between,
125 * it takes some effort for them to get interactive, but it's not
129 #define CURRENT_BONUS(p) \
130 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
133 #define GRANULARITY (10 * HZ / 1000 ? : 1)
136 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
137 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
140 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
141 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
144 #define SCALE(v1,v1_max,v2_max) \
145 (v1) * (v2_max) / (v1_max)
148 (SCALE(TASK_NICE(p) + 20, 40, MAX_BONUS) - 20 * MAX_BONUS / 40 + \
151 #define TASK_INTERACTIVE(p) \
152 ((p)->prio <= (p)->static_prio - DELTA(p))
154 #define INTERACTIVE_SLEEP(p) \
155 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
156 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
158 #define TASK_PREEMPTS_CURR(p, rq) \
159 ((p)->prio < (rq)->curr->prio)
162 * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
163 * to time slice values: [800ms ... 100ms ... 5ms]
165 * The higher a thread's priority, the bigger timeslices
166 * it gets during one round of execution. But even the lowest
167 * priority thread gets MIN_TIMESLICE worth of execution time.
170 #define SCALE_PRIO(x, prio) \
171 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO/2), MIN_TIMESLICE)
173 static unsigned int task_timeslice(task_t *p)
175 if (p->static_prio < NICE_TO_PRIO(0))
176 return SCALE_PRIO(DEF_TIMESLICE*4, p->static_prio);
178 return SCALE_PRIO(DEF_TIMESLICE, p->static_prio);
180 #define task_hot(p, now, sd) ((long long) ((now) - (p)->last_ran) \
181 < (long long) (sd)->cache_hot_time)
184 * These are the runqueue data structures:
187 #define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
189 typedef struct runqueue runqueue_t;
192 unsigned int nr_active;
193 unsigned long bitmap[BITMAP_SIZE];
194 struct list_head queue[MAX_PRIO];
198 * This is the main, per-CPU runqueue data structure.
200 * Locking rule: those places that want to lock multiple runqueues
201 * (such as the load balancing or the thread migration code), lock
202 * acquire operations must be ordered by ascending &runqueue.
208 * nr_running and cpu_load should be in the same cacheline because
209 * remote CPUs use both these fields when doing load calculation.
211 unsigned long nr_running;
213 unsigned long cpu_load[3];
215 unsigned long long nr_switches;
218 * This is part of a global counter where only the total sum
219 * over all CPUs matters. A task can increase this counter on
220 * one CPU and if it got migrated afterwards it may decrease
221 * it on another CPU. Always updated under the runqueue lock:
223 unsigned long nr_uninterruptible;
225 unsigned long expired_timestamp;
226 unsigned long long timestamp_last_tick;
228 struct mm_struct *prev_mm;
229 prio_array_t *active, *expired, arrays[2];
230 int best_expired_prio;
234 struct sched_domain *sd;
236 /* For active balancing */
240 task_t *migration_thread;
241 struct list_head migration_queue;
245 #ifdef CONFIG_SCHEDSTATS
247 struct sched_info rq_sched_info;
249 /* sys_sched_yield() stats */
250 unsigned long yld_exp_empty;
251 unsigned long yld_act_empty;
252 unsigned long yld_both_empty;
253 unsigned long yld_cnt;
255 /* schedule() stats */
256 unsigned long sched_switch;
257 unsigned long sched_cnt;
258 unsigned long sched_goidle;
260 /* try_to_wake_up() stats */
261 unsigned long ttwu_cnt;
262 unsigned long ttwu_local;
266 static DEFINE_PER_CPU(struct runqueue, runqueues);
269 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
270 * See detach_destroy_domains: synchronize_sched for details.
272 * The domain tree of any CPU may only be accessed from within
273 * preempt-disabled sections.
275 #define for_each_domain(cpu, domain) \
276 for (domain = rcu_dereference(cpu_rq(cpu)->sd); domain; domain = domain->parent)
278 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
279 #define this_rq() (&__get_cpu_var(runqueues))
280 #define task_rq(p) cpu_rq(task_cpu(p))
281 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
283 #ifndef prepare_arch_switch
284 # define prepare_arch_switch(next) do { } while (0)
286 #ifndef finish_arch_switch
287 # define finish_arch_switch(prev) do { } while (0)
290 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
291 static inline int task_running(runqueue_t *rq, task_t *p)
293 return rq->curr == p;
296 static inline void prepare_lock_switch(runqueue_t *rq, task_t *next)
300 static inline void finish_lock_switch(runqueue_t *rq, task_t *prev)
302 #ifdef CONFIG_DEBUG_SPINLOCK
303 /* this is a valid case when another task releases the spinlock */
304 rq->lock.owner = current;
306 spin_unlock_irq(&rq->lock);
309 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
310 static inline int task_running(runqueue_t *rq, task_t *p)
315 return rq->curr == p;
319 static inline void prepare_lock_switch(runqueue_t *rq, task_t *next)
323 * We can optimise this out completely for !SMP, because the
324 * SMP rebalancing from interrupt is the only thing that cares
329 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
330 spin_unlock_irq(&rq->lock);
332 spin_unlock(&rq->lock);
336 static inline void finish_lock_switch(runqueue_t *rq, task_t *prev)
340 * After ->oncpu is cleared, the task can be moved to a different CPU.
341 * We must ensure this doesn't happen until the switch is completely
347 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
351 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
354 * task_rq_lock - lock the runqueue a given task resides on and disable
355 * interrupts. Note the ordering: we can safely lookup the task_rq without
356 * explicitly disabling preemption.
358 static inline runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
364 local_irq_save(*flags);
366 spin_lock(&rq->lock);
367 if (unlikely(rq != task_rq(p))) {
368 spin_unlock_irqrestore(&rq->lock, *flags);
369 goto repeat_lock_task;
374 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
377 spin_unlock_irqrestore(&rq->lock, *flags);
380 #ifdef CONFIG_SCHEDSTATS
382 * bump this up when changing the output format or the meaning of an existing
383 * format, so that tools can adapt (or abort)
385 #define SCHEDSTAT_VERSION 12
387 static int show_schedstat(struct seq_file *seq, void *v)
391 seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
392 seq_printf(seq, "timestamp %lu\n", jiffies);
393 for_each_online_cpu(cpu) {
394 runqueue_t *rq = cpu_rq(cpu);
396 struct sched_domain *sd;
400 /* runqueue-specific stats */
402 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
403 cpu, rq->yld_both_empty,
404 rq->yld_act_empty, rq->yld_exp_empty, rq->yld_cnt,
405 rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
406 rq->ttwu_cnt, rq->ttwu_local,
407 rq->rq_sched_info.cpu_time,
408 rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
410 seq_printf(seq, "\n");
413 /* domain-specific stats */
415 for_each_domain(cpu, sd) {
416 enum idle_type itype;
417 char mask_str[NR_CPUS];
419 cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
420 seq_printf(seq, "domain%d %s", dcnt++, mask_str);
421 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
423 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu",
425 sd->lb_balanced[itype],
426 sd->lb_failed[itype],
427 sd->lb_imbalance[itype],
428 sd->lb_gained[itype],
429 sd->lb_hot_gained[itype],
430 sd->lb_nobusyq[itype],
431 sd->lb_nobusyg[itype]);
433 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
434 sd->alb_cnt, sd->alb_failed, sd->alb_pushed,
435 sd->sbe_cnt, sd->sbe_balanced, sd->sbe_pushed,
436 sd->sbf_cnt, sd->sbf_balanced, sd->sbf_pushed,
437 sd->ttwu_wake_remote, sd->ttwu_move_affine, sd->ttwu_move_balance);
445 static int schedstat_open(struct inode *inode, struct file *file)
447 unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
448 char *buf = kmalloc(size, GFP_KERNEL);
454 res = single_open(file, show_schedstat, NULL);
456 m = file->private_data;
464 struct file_operations proc_schedstat_operations = {
465 .open = schedstat_open,
468 .release = single_release,
471 # define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
472 # define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
473 #else /* !CONFIG_SCHEDSTATS */
474 # define schedstat_inc(rq, field) do { } while (0)
475 # define schedstat_add(rq, field, amt) do { } while (0)
479 * rq_lock - lock a given runqueue and disable interrupts.
481 static inline runqueue_t *this_rq_lock(void)
488 spin_lock(&rq->lock);
493 #ifdef CONFIG_SCHEDSTATS
495 * Called when a process is dequeued from the active array and given
496 * the cpu. We should note that with the exception of interactive
497 * tasks, the expired queue will become the active queue after the active
498 * queue is empty, without explicitly dequeuing and requeuing tasks in the
499 * expired queue. (Interactive tasks may be requeued directly to the
500 * active queue, thus delaying tasks in the expired queue from running;
501 * see scheduler_tick()).
503 * This function is only called from sched_info_arrive(), rather than
504 * dequeue_task(). Even though a task may be queued and dequeued multiple
505 * times as it is shuffled about, we're really interested in knowing how
506 * long it was from the *first* time it was queued to the time that it
509 static inline void sched_info_dequeued(task_t *t)
511 t->sched_info.last_queued = 0;
515 * Called when a task finally hits the cpu. We can now calculate how
516 * long it was waiting to run. We also note when it began so that we
517 * can keep stats on how long its timeslice is.
519 static void sched_info_arrive(task_t *t)
521 unsigned long now = jiffies, diff = 0;
522 struct runqueue *rq = task_rq(t);
524 if (t->sched_info.last_queued)
525 diff = now - t->sched_info.last_queued;
526 sched_info_dequeued(t);
527 t->sched_info.run_delay += diff;
528 t->sched_info.last_arrival = now;
529 t->sched_info.pcnt++;
534 rq->rq_sched_info.run_delay += diff;
535 rq->rq_sched_info.pcnt++;
539 * Called when a process is queued into either the active or expired
540 * array. The time is noted and later used to determine how long we
541 * had to wait for us to reach the cpu. Since the expired queue will
542 * become the active queue after active queue is empty, without dequeuing
543 * and requeuing any tasks, we are interested in queuing to either. It
544 * is unusual but not impossible for tasks to be dequeued and immediately
545 * requeued in the same or another array: this can happen in sched_yield(),
546 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
549 * This function is only called from enqueue_task(), but also only updates
550 * the timestamp if it is already not set. It's assumed that
551 * sched_info_dequeued() will clear that stamp when appropriate.
553 static inline void sched_info_queued(task_t *t)
555 if (!t->sched_info.last_queued)
556 t->sched_info.last_queued = jiffies;
560 * Called when a process ceases being the active-running process, either
561 * voluntarily or involuntarily. Now we can calculate how long we ran.
563 static inline void sched_info_depart(task_t *t)
565 struct runqueue *rq = task_rq(t);
566 unsigned long diff = jiffies - t->sched_info.last_arrival;
568 t->sched_info.cpu_time += diff;
571 rq->rq_sched_info.cpu_time += diff;
575 * Called when tasks are switched involuntarily due, typically, to expiring
576 * their time slice. (This may also be called when switching to or from
577 * the idle task.) We are only called when prev != next.
579 static inline void sched_info_switch(task_t *prev, task_t *next)
581 struct runqueue *rq = task_rq(prev);
584 * prev now departs the cpu. It's not interesting to record
585 * stats about how efficient we were at scheduling the idle
588 if (prev != rq->idle)
589 sched_info_depart(prev);
591 if (next != rq->idle)
592 sched_info_arrive(next);
595 #define sched_info_queued(t) do { } while (0)
596 #define sched_info_switch(t, next) do { } while (0)
597 #endif /* CONFIG_SCHEDSTATS */
600 * Adding/removing a task to/from a priority array:
602 static void dequeue_task(struct task_struct *p, prio_array_t *array)
605 list_del(&p->run_list);
606 if (list_empty(array->queue + p->prio))
607 __clear_bit(p->prio, array->bitmap);
610 static void enqueue_task(struct task_struct *p, prio_array_t *array)
612 sched_info_queued(p);
613 list_add_tail(&p->run_list, array->queue + p->prio);
614 __set_bit(p->prio, array->bitmap);
620 * Put task to the end of the run list without the overhead of dequeue
621 * followed by enqueue.
623 static void requeue_task(struct task_struct *p, prio_array_t *array)
625 list_move_tail(&p->run_list, array->queue + p->prio);
628 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
630 list_add(&p->run_list, array->queue + p->prio);
631 __set_bit(p->prio, array->bitmap);
637 * effective_prio - return the priority that is based on the static
638 * priority but is modified by bonuses/penalties.
640 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
641 * into the -5 ... 0 ... +5 bonus/penalty range.
643 * We use 25% of the full 0...39 priority range so that:
645 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
646 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
648 * Both properties are important to certain workloads.
650 static int effective_prio(task_t *p)
657 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
659 prio = p->static_prio - bonus;
660 if (prio < MAX_RT_PRIO)
662 if (prio > MAX_PRIO-1)
668 * We place interactive tasks back into the active array, if possible.
670 * To guarantee that this does not starve expired tasks we ignore the
671 * interactivity of a task if the first expired task had to wait more
672 * than a 'reasonable' amount of time. This deadline timeout is
673 * load-dependent, as the frequency of array switched decreases with
674 * increasing number of running tasks. We also ignore the interactivity
675 * if a better static_prio task has expired, and switch periodically
676 * regardless, to ensure that highly interactive tasks do not starve
677 * the less fortunate for unreasonably long periods.
679 static inline int expired_starving(runqueue_t *rq)
684 * Arrays were recently switched, all is well
686 if (!rq->expired_timestamp)
689 limit = STARVATION_LIMIT * rq->nr_running;
692 * It's time to switch arrays
694 if (jiffies - rq->expired_timestamp >= limit)
698 * There's a better selection in the expired array
700 if (rq->curr->static_prio > rq->best_expired_prio)
710 * __activate_task - move a task to the runqueue.
712 static void __activate_task(task_t *p, runqueue_t *rq)
714 prio_array_t *target = rq->active;
716 if (unlikely(batch_task(p) || (expired_starving(rq) && !rt_task(p))))
717 target = rq->expired;
718 enqueue_task(p, target);
723 * __activate_idle_task - move idle task to the _front_ of runqueue.
725 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
727 enqueue_task_head(p, rq->active);
731 static int recalc_task_prio(task_t *p, unsigned long long now)
733 /* Caller must always ensure 'now >= p->timestamp' */
734 unsigned long long __sleep_time = now - p->timestamp;
735 unsigned long sleep_time;
740 if (__sleep_time > NS_MAX_SLEEP_AVG)
741 sleep_time = NS_MAX_SLEEP_AVG;
743 sleep_time = (unsigned long)__sleep_time;
746 if (likely(sleep_time > 0)) {
748 * User tasks that sleep a long time are categorised as
749 * idle. They will only have their sleep_avg increased to a
750 * level that makes them just interactive priority to stay
751 * active yet prevent them suddenly becoming cpu hogs and
752 * starving other processes.
754 if (p->mm && sleep_time > INTERACTIVE_SLEEP(p)) {
755 unsigned long ceiling;
757 ceiling = JIFFIES_TO_NS(MAX_SLEEP_AVG -
759 if (p->sleep_avg < ceiling)
760 p->sleep_avg = ceiling;
763 * Tasks waking from uninterruptible sleep are
764 * limited in their sleep_avg rise as they
765 * are likely to be waiting on I/O
767 if (p->sleep_type == SLEEP_NONINTERACTIVE && p->mm) {
768 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
770 else if (p->sleep_avg + sleep_time >=
771 INTERACTIVE_SLEEP(p)) {
772 p->sleep_avg = INTERACTIVE_SLEEP(p);
778 * This code gives a bonus to interactive tasks.
780 * The boost works by updating the 'average sleep time'
781 * value here, based on ->timestamp. The more time a
782 * task spends sleeping, the higher the average gets -
783 * and the higher the priority boost gets as well.
785 p->sleep_avg += sleep_time;
787 if (p->sleep_avg > NS_MAX_SLEEP_AVG)
788 p->sleep_avg = NS_MAX_SLEEP_AVG;
792 return effective_prio(p);
796 * activate_task - move a task to the runqueue and do priority recalculation
798 * Update all the scheduling statistics stuff. (sleep average
799 * calculation, priority modifiers, etc.)
801 static void activate_task(task_t *p, runqueue_t *rq, int local)
803 unsigned long long now;
808 /* Compensate for drifting sched_clock */
809 runqueue_t *this_rq = this_rq();
810 now = (now - this_rq->timestamp_last_tick)
811 + rq->timestamp_last_tick;
816 p->prio = recalc_task_prio(p, now);
819 * This checks to make sure it's not an uninterruptible task
820 * that is now waking up.
822 if (p->sleep_type == SLEEP_NORMAL) {
824 * Tasks which were woken up by interrupts (ie. hw events)
825 * are most likely of interactive nature. So we give them
826 * the credit of extending their sleep time to the period
827 * of time they spend on the runqueue, waiting for execution
828 * on a CPU, first time around:
831 p->sleep_type = SLEEP_INTERRUPTED;
834 * Normal first-time wakeups get a credit too for
835 * on-runqueue time, but it will be weighted down:
837 p->sleep_type = SLEEP_INTERACTIVE;
842 __activate_task(p, rq);
846 * deactivate_task - remove a task from the runqueue.
848 static void deactivate_task(struct task_struct *p, runqueue_t *rq)
851 dequeue_task(p, p->array);
856 * resched_task - mark a task 'to be rescheduled now'.
858 * On UP this means the setting of the need_resched flag, on SMP it
859 * might also involve a cross-CPU call to trigger the scheduler on
863 static void resched_task(task_t *p)
867 assert_spin_locked(&task_rq(p)->lock);
869 if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
872 set_tsk_thread_flag(p, TIF_NEED_RESCHED);
875 if (cpu == smp_processor_id())
878 /* NEED_RESCHED must be visible before we test POLLING_NRFLAG */
880 if (!test_tsk_thread_flag(p, TIF_POLLING_NRFLAG))
881 smp_send_reschedule(cpu);
884 static inline void resched_task(task_t *p)
886 assert_spin_locked(&task_rq(p)->lock);
887 set_tsk_need_resched(p);
892 * task_curr - is this task currently executing on a CPU?
893 * @p: the task in question.
895 inline int task_curr(const task_t *p)
897 return cpu_curr(task_cpu(p)) == p;
902 struct list_head list;
907 struct completion done;
911 * The task's runqueue lock must be held.
912 * Returns true if you have to wait for migration thread.
914 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
916 runqueue_t *rq = task_rq(p);
919 * If the task is not on a runqueue (and not running), then
920 * it is sufficient to simply update the task's cpu field.
922 if (!p->array && !task_running(rq, p)) {
923 set_task_cpu(p, dest_cpu);
927 init_completion(&req->done);
929 req->dest_cpu = dest_cpu;
930 list_add(&req->list, &rq->migration_queue);
935 * wait_task_inactive - wait for a thread to unschedule.
937 * The caller must ensure that the task *will* unschedule sometime soon,
938 * else this function might spin for a *long* time. This function can't
939 * be called with interrupts off, or it may introduce deadlock with
940 * smp_call_function() if an IPI is sent by the same process we are
941 * waiting to become inactive.
943 void wait_task_inactive(task_t *p)
950 rq = task_rq_lock(p, &flags);
951 /* Must be off runqueue entirely, not preempted. */
952 if (unlikely(p->array || task_running(rq, p))) {
953 /* If it's preempted, we yield. It could be a while. */
954 preempted = !task_running(rq, p);
955 task_rq_unlock(rq, &flags);
961 task_rq_unlock(rq, &flags);
965 * kick_process - kick a running thread to enter/exit the kernel
966 * @p: the to-be-kicked thread
968 * Cause a process which is running on another CPU to enter
969 * kernel-mode, without any delay. (to get signals handled.)
971 * NOTE: this function doesnt have to take the runqueue lock,
972 * because all it wants to ensure is that the remote task enters
973 * the kernel. If the IPI races and the task has been migrated
974 * to another CPU then no harm is done and the purpose has been
977 void kick_process(task_t *p)
983 if ((cpu != smp_processor_id()) && task_curr(p))
984 smp_send_reschedule(cpu);
989 * Return a low guess at the load of a migration-source cpu.
991 * We want to under-estimate the load of migration sources, to
992 * balance conservatively.
994 static inline unsigned long source_load(int cpu, int type)
996 runqueue_t *rq = cpu_rq(cpu);
997 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
1001 return min(rq->cpu_load[type-1], load_now);
1005 * Return a high guess at the load of a migration-target cpu
1007 static inline unsigned long target_load(int cpu, int type)
1009 runqueue_t *rq = cpu_rq(cpu);
1010 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
1014 return max(rq->cpu_load[type-1], load_now);
1018 * find_idlest_group finds and returns the least busy CPU group within the
1021 static struct sched_group *
1022 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1024 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1025 unsigned long min_load = ULONG_MAX, this_load = 0;
1026 int load_idx = sd->forkexec_idx;
1027 int imbalance = 100 + (sd->imbalance_pct-100)/2;
1030 unsigned long load, avg_load;
1034 /* Skip over this group if it has no CPUs allowed */
1035 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
1038 local_group = cpu_isset(this_cpu, group->cpumask);
1040 /* Tally up the load of all CPUs in the group */
1043 for_each_cpu_mask(i, group->cpumask) {
1044 /* Bias balancing toward cpus of our domain */
1046 load = source_load(i, load_idx);
1048 load = target_load(i, load_idx);
1053 /* Adjust by relative CPU power of the group */
1054 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1057 this_load = avg_load;
1059 } else if (avg_load < min_load) {
1060 min_load = avg_load;
1064 group = group->next;
1065 } while (group != sd->groups);
1067 if (!idlest || 100*this_load < imbalance*min_load)
1073 * find_idlest_queue - find the idlest runqueue among the cpus in group.
1076 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
1079 unsigned long load, min_load = ULONG_MAX;
1083 /* Traverse only the allowed CPUs */
1084 cpus_and(tmp, group->cpumask, p->cpus_allowed);
1086 for_each_cpu_mask(i, tmp) {
1087 load = source_load(i, 0);
1089 if (load < min_load || (load == min_load && i == this_cpu)) {
1099 * sched_balance_self: balance the current task (running on cpu) in domains
1100 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1103 * Balance, ie. select the least loaded group.
1105 * Returns the target CPU number, or the same CPU if no balancing is needed.
1107 * preempt must be disabled.
1109 static int sched_balance_self(int cpu, int flag)
1111 struct task_struct *t = current;
1112 struct sched_domain *tmp, *sd = NULL;
1114 for_each_domain(cpu, tmp)
1115 if (tmp->flags & flag)
1120 struct sched_group *group;
1125 group = find_idlest_group(sd, t, cpu);
1129 new_cpu = find_idlest_cpu(group, t, cpu);
1130 if (new_cpu == -1 || new_cpu == cpu)
1133 /* Now try balancing at a lower domain level */
1137 weight = cpus_weight(span);
1138 for_each_domain(cpu, tmp) {
1139 if (weight <= cpus_weight(tmp->span))
1141 if (tmp->flags & flag)
1144 /* while loop will break here if sd == NULL */
1150 #endif /* CONFIG_SMP */
1153 * wake_idle() will wake a task on an idle cpu if task->cpu is
1154 * not idle and an idle cpu is available. The span of cpus to
1155 * search starts with cpus closest then further out as needed,
1156 * so we always favor a closer, idle cpu.
1158 * Returns the CPU we should wake onto.
1160 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1161 static int wake_idle(int cpu, task_t *p)
1164 struct sched_domain *sd;
1170 for_each_domain(cpu, sd) {
1171 if (sd->flags & SD_WAKE_IDLE) {
1172 cpus_and(tmp, sd->span, p->cpus_allowed);
1173 for_each_cpu_mask(i, tmp) {
1184 static inline int wake_idle(int cpu, task_t *p)
1191 * try_to_wake_up - wake up a thread
1192 * @p: the to-be-woken-up thread
1193 * @state: the mask of task states that can be woken
1194 * @sync: do a synchronous wakeup?
1196 * Put it on the run-queue if it's not already there. The "current"
1197 * thread is always on the run-queue (except when the actual
1198 * re-schedule is in progress), and as such you're allowed to do
1199 * the simpler "current->state = TASK_RUNNING" to mark yourself
1200 * runnable without the overhead of this.
1202 * returns failure only if the task is already active.
1204 static int try_to_wake_up(task_t *p, unsigned int state, int sync)
1206 int cpu, this_cpu, success = 0;
1207 unsigned long flags;
1211 unsigned long load, this_load;
1212 struct sched_domain *sd, *this_sd = NULL;
1216 rq = task_rq_lock(p, &flags);
1217 old_state = p->state;
1218 if (!(old_state & state))
1225 this_cpu = smp_processor_id();
1228 if (unlikely(task_running(rq, p)))
1233 schedstat_inc(rq, ttwu_cnt);
1234 if (cpu == this_cpu) {
1235 schedstat_inc(rq, ttwu_local);
1239 for_each_domain(this_cpu, sd) {
1240 if (cpu_isset(cpu, sd->span)) {
1241 schedstat_inc(sd, ttwu_wake_remote);
1247 if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1251 * Check for affine wakeup and passive balancing possibilities.
1254 int idx = this_sd->wake_idx;
1255 unsigned int imbalance;
1257 imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
1259 load = source_load(cpu, idx);
1260 this_load = target_load(this_cpu, idx);
1262 new_cpu = this_cpu; /* Wake to this CPU if we can */
1264 if (this_sd->flags & SD_WAKE_AFFINE) {
1265 unsigned long tl = this_load;
1267 * If sync wakeup then subtract the (maximum possible)
1268 * effect of the currently running task from the load
1269 * of the current CPU:
1272 tl -= SCHED_LOAD_SCALE;
1275 tl + target_load(cpu, idx) <= SCHED_LOAD_SCALE) ||
1276 100*(tl + SCHED_LOAD_SCALE) <= imbalance*load) {
1278 * This domain has SD_WAKE_AFFINE and
1279 * p is cache cold in this domain, and
1280 * there is no bad imbalance.
1282 schedstat_inc(this_sd, ttwu_move_affine);
1288 * Start passive balancing when half the imbalance_pct
1291 if (this_sd->flags & SD_WAKE_BALANCE) {
1292 if (imbalance*this_load <= 100*load) {
1293 schedstat_inc(this_sd, ttwu_move_balance);
1299 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1301 new_cpu = wake_idle(new_cpu, p);
1302 if (new_cpu != cpu) {
1303 set_task_cpu(p, new_cpu);
1304 task_rq_unlock(rq, &flags);
1305 /* might preempt at this point */
1306 rq = task_rq_lock(p, &flags);
1307 old_state = p->state;
1308 if (!(old_state & state))
1313 this_cpu = smp_processor_id();
1318 #endif /* CONFIG_SMP */
1319 if (old_state == TASK_UNINTERRUPTIBLE) {
1320 rq->nr_uninterruptible--;
1322 * Tasks on involuntary sleep don't earn
1323 * sleep_avg beyond just interactive state.
1325 p->sleep_type = SLEEP_NONINTERACTIVE;
1329 * Tasks that have marked their sleep as noninteractive get
1330 * woken up with their sleep average not weighted in an
1333 if (old_state & TASK_NONINTERACTIVE)
1334 p->sleep_type = SLEEP_NONINTERACTIVE;
1337 activate_task(p, rq, cpu == this_cpu);
1339 * Sync wakeups (i.e. those types of wakeups where the waker
1340 * has indicated that it will leave the CPU in short order)
1341 * don't trigger a preemption, if the woken up task will run on
1342 * this cpu. (in this case the 'I will reschedule' promise of
1343 * the waker guarantees that the freshly woken up task is going
1344 * to be considered on this CPU.)
1346 if (!sync || cpu != this_cpu) {
1347 if (TASK_PREEMPTS_CURR(p, rq))
1348 resched_task(rq->curr);
1353 p->state = TASK_RUNNING;
1355 task_rq_unlock(rq, &flags);
1360 int fastcall wake_up_process(task_t *p)
1362 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1363 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1366 EXPORT_SYMBOL(wake_up_process);
1368 int fastcall wake_up_state(task_t *p, unsigned int state)
1370 return try_to_wake_up(p, state, 0);
1374 * Perform scheduler related setup for a newly forked process p.
1375 * p is forked by current.
1377 void fastcall sched_fork(task_t *p, int clone_flags)
1379 int cpu = get_cpu();
1382 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
1384 set_task_cpu(p, cpu);
1387 * We mark the process as running here, but have not actually
1388 * inserted it onto the runqueue yet. This guarantees that
1389 * nobody will actually run it, and a signal or other external
1390 * event cannot wake it up and insert it on the runqueue either.
1392 p->state = TASK_RUNNING;
1393 INIT_LIST_HEAD(&p->run_list);
1395 #ifdef CONFIG_SCHEDSTATS
1396 memset(&p->sched_info, 0, sizeof(p->sched_info));
1398 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
1401 #ifdef CONFIG_PREEMPT
1402 /* Want to start with kernel preemption disabled. */
1403 task_thread_info(p)->preempt_count = 1;
1406 * Share the timeslice between parent and child, thus the
1407 * total amount of pending timeslices in the system doesn't change,
1408 * resulting in more scheduling fairness.
1410 local_irq_disable();
1411 p->time_slice = (current->time_slice + 1) >> 1;
1413 * The remainder of the first timeslice might be recovered by
1414 * the parent if the child exits early enough.
1416 p->first_time_slice = 1;
1417 current->time_slice >>= 1;
1418 p->timestamp = sched_clock();
1419 if (unlikely(!current->time_slice)) {
1421 * This case is rare, it happens when the parent has only
1422 * a single jiffy left from its timeslice. Taking the
1423 * runqueue lock is not a problem.
1425 current->time_slice = 1;
1433 * wake_up_new_task - wake up a newly created task for the first time.
1435 * This function will do some initial scheduler statistics housekeeping
1436 * that must be done for every newly created context, then puts the task
1437 * on the runqueue and wakes it.
1439 void fastcall wake_up_new_task(task_t *p, unsigned long clone_flags)
1441 unsigned long flags;
1443 runqueue_t *rq, *this_rq;
1445 rq = task_rq_lock(p, &flags);
1446 BUG_ON(p->state != TASK_RUNNING);
1447 this_cpu = smp_processor_id();
1451 * We decrease the sleep average of forking parents
1452 * and children as well, to keep max-interactive tasks
1453 * from forking tasks that are max-interactive. The parent
1454 * (current) is done further down, under its lock.
1456 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1457 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1459 p->prio = effective_prio(p);
1461 if (likely(cpu == this_cpu)) {
1462 if (!(clone_flags & CLONE_VM)) {
1464 * The VM isn't cloned, so we're in a good position to
1465 * do child-runs-first in anticipation of an exec. This
1466 * usually avoids a lot of COW overhead.
1468 if (unlikely(!current->array))
1469 __activate_task(p, rq);
1471 p->prio = current->prio;
1472 list_add_tail(&p->run_list, ¤t->run_list);
1473 p->array = current->array;
1474 p->array->nr_active++;
1479 /* Run child last */
1480 __activate_task(p, rq);
1482 * We skip the following code due to cpu == this_cpu
1484 * task_rq_unlock(rq, &flags);
1485 * this_rq = task_rq_lock(current, &flags);
1489 this_rq = cpu_rq(this_cpu);
1492 * Not the local CPU - must adjust timestamp. This should
1493 * get optimised away in the !CONFIG_SMP case.
1495 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1496 + rq->timestamp_last_tick;
1497 __activate_task(p, rq);
1498 if (TASK_PREEMPTS_CURR(p, rq))
1499 resched_task(rq->curr);
1502 * Parent and child are on different CPUs, now get the
1503 * parent runqueue to update the parent's ->sleep_avg:
1505 task_rq_unlock(rq, &flags);
1506 this_rq = task_rq_lock(current, &flags);
1508 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1509 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1510 task_rq_unlock(this_rq, &flags);
1514 * Potentially available exiting-child timeslices are
1515 * retrieved here - this way the parent does not get
1516 * penalized for creating too many threads.
1518 * (this cannot be used to 'generate' timeslices
1519 * artificially, because any timeslice recovered here
1520 * was given away by the parent in the first place.)
1522 void fastcall sched_exit(task_t *p)
1524 unsigned long flags;
1528 * If the child was a (relative-) CPU hog then decrease
1529 * the sleep_avg of the parent as well.
1531 rq = task_rq_lock(p->parent, &flags);
1532 if (p->first_time_slice && task_cpu(p) == task_cpu(p->parent)) {
1533 p->parent->time_slice += p->time_slice;
1534 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1535 p->parent->time_slice = task_timeslice(p);
1537 if (p->sleep_avg < p->parent->sleep_avg)
1538 p->parent->sleep_avg = p->parent->sleep_avg /
1539 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1541 task_rq_unlock(rq, &flags);
1545 * prepare_task_switch - prepare to switch tasks
1546 * @rq: the runqueue preparing to switch
1547 * @next: the task we are going to switch to.
1549 * This is called with the rq lock held and interrupts off. It must
1550 * be paired with a subsequent finish_task_switch after the context
1553 * prepare_task_switch sets up locking and calls architecture specific
1556 static inline void prepare_task_switch(runqueue_t *rq, task_t *next)
1558 prepare_lock_switch(rq, next);
1559 prepare_arch_switch(next);
1563 * finish_task_switch - clean up after a task-switch
1564 * @rq: runqueue associated with task-switch
1565 * @prev: the thread we just switched away from.
1567 * finish_task_switch must be called after the context switch, paired
1568 * with a prepare_task_switch call before the context switch.
1569 * finish_task_switch will reconcile locking set up by prepare_task_switch,
1570 * and do any other architecture-specific cleanup actions.
1572 * Note that we may have delayed dropping an mm in context_switch(). If
1573 * so, we finish that here outside of the runqueue lock. (Doing it
1574 * with the lock held can cause deadlocks; see schedule() for
1577 static inline void finish_task_switch(runqueue_t *rq, task_t *prev)
1578 __releases(rq->lock)
1580 struct mm_struct *mm = rq->prev_mm;
1581 unsigned long prev_task_flags;
1586 * A task struct has one reference for the use as "current".
1587 * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1588 * calls schedule one last time. The schedule call will never return,
1589 * and the scheduled task must drop that reference.
1590 * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1591 * still held, otherwise prev could be scheduled on another cpu, die
1592 * there before we look at prev->state, and then the reference would
1594 * Manfred Spraul <manfred@colorfullife.com>
1596 prev_task_flags = prev->flags;
1597 finish_arch_switch(prev);
1598 finish_lock_switch(rq, prev);
1601 if (unlikely(prev_task_flags & PF_DEAD)) {
1603 * Remove function-return probe instances associated with this
1604 * task and put them back on the free list.
1606 kprobe_flush_task(prev);
1607 put_task_struct(prev);
1612 * schedule_tail - first thing a freshly forked thread must call.
1613 * @prev: the thread we just switched away from.
1615 asmlinkage void schedule_tail(task_t *prev)
1616 __releases(rq->lock)
1618 runqueue_t *rq = this_rq();
1619 finish_task_switch(rq, prev);
1620 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
1621 /* In this case, finish_task_switch does not reenable preemption */
1624 if (current->set_child_tid)
1625 put_user(current->pid, current->set_child_tid);
1629 * context_switch - switch to the new MM and the new
1630 * thread's register state.
1633 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1635 struct mm_struct *mm = next->mm;
1636 struct mm_struct *oldmm = prev->active_mm;
1638 if (unlikely(!mm)) {
1639 next->active_mm = oldmm;
1640 atomic_inc(&oldmm->mm_count);
1641 enter_lazy_tlb(oldmm, next);
1643 switch_mm(oldmm, mm, next);
1645 if (unlikely(!prev->mm)) {
1646 prev->active_mm = NULL;
1647 WARN_ON(rq->prev_mm);
1648 rq->prev_mm = oldmm;
1651 /* Here we just switch the register state and the stack. */
1652 switch_to(prev, next, prev);
1658 * nr_running, nr_uninterruptible and nr_context_switches:
1660 * externally visible scheduler statistics: current number of runnable
1661 * threads, current number of uninterruptible-sleeping threads, total
1662 * number of context switches performed since bootup.
1664 unsigned long nr_running(void)
1666 unsigned long i, sum = 0;
1668 for_each_online_cpu(i)
1669 sum += cpu_rq(i)->nr_running;
1674 unsigned long nr_uninterruptible(void)
1676 unsigned long i, sum = 0;
1678 for_each_possible_cpu(i)
1679 sum += cpu_rq(i)->nr_uninterruptible;
1682 * Since we read the counters lockless, it might be slightly
1683 * inaccurate. Do not allow it to go below zero though:
1685 if (unlikely((long)sum < 0))
1691 unsigned long long nr_context_switches(void)
1693 unsigned long long i, sum = 0;
1695 for_each_possible_cpu(i)
1696 sum += cpu_rq(i)->nr_switches;
1701 unsigned long nr_iowait(void)
1703 unsigned long i, sum = 0;
1705 for_each_possible_cpu(i)
1706 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1711 unsigned long nr_active(void)
1713 unsigned long i, running = 0, uninterruptible = 0;
1715 for_each_online_cpu(i) {
1716 running += cpu_rq(i)->nr_running;
1717 uninterruptible += cpu_rq(i)->nr_uninterruptible;
1720 if (unlikely((long)uninterruptible < 0))
1721 uninterruptible = 0;
1723 return running + uninterruptible;
1729 * double_rq_lock - safely lock two runqueues
1731 * We must take them in cpu order to match code in
1732 * dependent_sleeper and wake_dependent_sleeper.
1734 * Note this does not disable interrupts like task_rq_lock,
1735 * you need to do so manually before calling.
1737 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1738 __acquires(rq1->lock)
1739 __acquires(rq2->lock)
1742 spin_lock(&rq1->lock);
1743 __acquire(rq2->lock); /* Fake it out ;) */
1745 if (rq1->cpu < rq2->cpu) {
1746 spin_lock(&rq1->lock);
1747 spin_lock(&rq2->lock);
1749 spin_lock(&rq2->lock);
1750 spin_lock(&rq1->lock);
1756 * double_rq_unlock - safely unlock two runqueues
1758 * Note this does not restore interrupts like task_rq_unlock,
1759 * you need to do so manually after calling.
1761 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1762 __releases(rq1->lock)
1763 __releases(rq2->lock)
1765 spin_unlock(&rq1->lock);
1767 spin_unlock(&rq2->lock);
1769 __release(rq2->lock);
1773 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1775 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1776 __releases(this_rq->lock)
1777 __acquires(busiest->lock)
1778 __acquires(this_rq->lock)
1780 if (unlikely(!spin_trylock(&busiest->lock))) {
1781 if (busiest->cpu < this_rq->cpu) {
1782 spin_unlock(&this_rq->lock);
1783 spin_lock(&busiest->lock);
1784 spin_lock(&this_rq->lock);
1786 spin_lock(&busiest->lock);
1791 * If dest_cpu is allowed for this process, migrate the task to it.
1792 * This is accomplished by forcing the cpu_allowed mask to only
1793 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1794 * the cpu_allowed mask is restored.
1796 static void sched_migrate_task(task_t *p, int dest_cpu)
1798 migration_req_t req;
1800 unsigned long flags;
1802 rq = task_rq_lock(p, &flags);
1803 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1804 || unlikely(cpu_is_offline(dest_cpu)))
1807 /* force the process onto the specified CPU */
1808 if (migrate_task(p, dest_cpu, &req)) {
1809 /* Need to wait for migration thread (might exit: take ref). */
1810 struct task_struct *mt = rq->migration_thread;
1811 get_task_struct(mt);
1812 task_rq_unlock(rq, &flags);
1813 wake_up_process(mt);
1814 put_task_struct(mt);
1815 wait_for_completion(&req.done);
1819 task_rq_unlock(rq, &flags);
1823 * sched_exec - execve() is a valuable balancing opportunity, because at
1824 * this point the task has the smallest effective memory and cache footprint.
1826 void sched_exec(void)
1828 int new_cpu, this_cpu = get_cpu();
1829 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
1831 if (new_cpu != this_cpu)
1832 sched_migrate_task(current, new_cpu);
1836 * pull_task - move a task from a remote runqueue to the local runqueue.
1837 * Both runqueues must be locked.
1840 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1841 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1843 dequeue_task(p, src_array);
1844 src_rq->nr_running--;
1845 set_task_cpu(p, this_cpu);
1846 this_rq->nr_running++;
1847 enqueue_task(p, this_array);
1848 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1849 + this_rq->timestamp_last_tick;
1851 * Note that idle threads have a prio of MAX_PRIO, for this test
1852 * to be always true for them.
1854 if (TASK_PREEMPTS_CURR(p, this_rq))
1855 resched_task(this_rq->curr);
1859 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1862 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1863 struct sched_domain *sd, enum idle_type idle,
1867 * We do not migrate tasks that are:
1868 * 1) running (obviously), or
1869 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1870 * 3) are cache-hot on their current CPU.
1872 if (!cpu_isset(this_cpu, p->cpus_allowed))
1876 if (task_running(rq, p))
1880 * Aggressive migration if:
1881 * 1) task is cache cold, or
1882 * 2) too many balance attempts have failed.
1885 if (sd->nr_balance_failed > sd->cache_nice_tries)
1888 if (task_hot(p, rq->timestamp_last_tick, sd))
1894 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1895 * as part of a balancing operation within "domain". Returns the number of
1898 * Called with both runqueues locked.
1900 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1901 unsigned long max_nr_move, struct sched_domain *sd,
1902 enum idle_type idle, int *all_pinned)
1904 prio_array_t *array, *dst_array;
1905 struct list_head *head, *curr;
1906 int idx, pulled = 0, pinned = 0;
1909 if (max_nr_move == 0)
1915 * We first consider expired tasks. Those will likely not be
1916 * executed in the near future, and they are most likely to
1917 * be cache-cold, thus switching CPUs has the least effect
1920 if (busiest->expired->nr_active) {
1921 array = busiest->expired;
1922 dst_array = this_rq->expired;
1924 array = busiest->active;
1925 dst_array = this_rq->active;
1929 /* Start searching at priority 0: */
1933 idx = sched_find_first_bit(array->bitmap);
1935 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1936 if (idx >= MAX_PRIO) {
1937 if (array == busiest->expired && busiest->active->nr_active) {
1938 array = busiest->active;
1939 dst_array = this_rq->active;
1945 head = array->queue + idx;
1948 tmp = list_entry(curr, task_t, run_list);
1952 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle, &pinned)) {
1959 #ifdef CONFIG_SCHEDSTATS
1960 if (task_hot(tmp, busiest->timestamp_last_tick, sd))
1961 schedstat_inc(sd, lb_hot_gained[idle]);
1964 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
1967 /* We only want to steal up to the prescribed number of tasks. */
1968 if (pulled < max_nr_move) {
1976 * Right now, this is the only place pull_task() is called,
1977 * so we can safely collect pull_task() stats here rather than
1978 * inside pull_task().
1980 schedstat_add(sd, lb_gained[idle], pulled);
1983 *all_pinned = pinned;
1988 * find_busiest_group finds and returns the busiest CPU group within the
1989 * domain. It calculates and returns the number of tasks which should be
1990 * moved to restore balance via the imbalance parameter.
1992 static struct sched_group *
1993 find_busiest_group(struct sched_domain *sd, int this_cpu,
1994 unsigned long *imbalance, enum idle_type idle, int *sd_idle)
1996 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
1997 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
1998 unsigned long max_pull;
2001 max_load = this_load = total_load = total_pwr = 0;
2002 if (idle == NOT_IDLE)
2003 load_idx = sd->busy_idx;
2004 else if (idle == NEWLY_IDLE)
2005 load_idx = sd->newidle_idx;
2007 load_idx = sd->idle_idx;
2014 local_group = cpu_isset(this_cpu, group->cpumask);
2016 /* Tally up the load of all CPUs in the group */
2019 for_each_cpu_mask(i, group->cpumask) {
2020 if (*sd_idle && !idle_cpu(i))
2023 /* Bias balancing toward cpus of our domain */
2025 load = target_load(i, load_idx);
2027 load = source_load(i, load_idx);
2032 total_load += avg_load;
2033 total_pwr += group->cpu_power;
2035 /* Adjust by relative CPU power of the group */
2036 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
2039 this_load = avg_load;
2041 } else if (avg_load > max_load) {
2042 max_load = avg_load;
2045 group = group->next;
2046 } while (group != sd->groups);
2048 if (!busiest || this_load >= max_load || max_load <= SCHED_LOAD_SCALE)
2051 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2053 if (this_load >= avg_load ||
2054 100*max_load <= sd->imbalance_pct*this_load)
2058 * We're trying to get all the cpus to the average_load, so we don't
2059 * want to push ourselves above the average load, nor do we wish to
2060 * reduce the max loaded cpu below the average load, as either of these
2061 * actions would just result in more rebalancing later, and ping-pong
2062 * tasks around. Thus we look for the minimum possible imbalance.
2063 * Negative imbalances (*we* are more loaded than anyone else) will
2064 * be counted as no imbalance for these purposes -- we can't fix that
2065 * by pulling tasks to us. Be careful of negative numbers as they'll
2066 * appear as very large values with unsigned longs.
2069 /* Don't want to pull so many tasks that a group would go idle */
2070 max_pull = min(max_load - avg_load, max_load - SCHED_LOAD_SCALE);
2072 /* How much load to actually move to equalise the imbalance */
2073 *imbalance = min(max_pull * busiest->cpu_power,
2074 (avg_load - this_load) * this->cpu_power)
2077 if (*imbalance < SCHED_LOAD_SCALE) {
2078 unsigned long pwr_now = 0, pwr_move = 0;
2081 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
2087 * OK, we don't have enough imbalance to justify moving tasks,
2088 * however we may be able to increase total CPU power used by
2092 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
2093 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
2094 pwr_now /= SCHED_LOAD_SCALE;
2096 /* Amount of load we'd subtract */
2097 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
2099 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
2102 /* Amount of load we'd add */
2103 if (max_load*busiest->cpu_power <
2104 SCHED_LOAD_SCALE*SCHED_LOAD_SCALE)
2105 tmp = max_load*busiest->cpu_power/this->cpu_power;
2107 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
2108 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
2109 pwr_move /= SCHED_LOAD_SCALE;
2111 /* Move if we gain throughput */
2112 if (pwr_move <= pwr_now)
2119 /* Get rid of the scaling factor, rounding down as we divide */
2120 *imbalance = *imbalance / SCHED_LOAD_SCALE;
2130 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2132 static runqueue_t *find_busiest_queue(struct sched_group *group,
2133 enum idle_type idle)
2135 unsigned long load, max_load = 0;
2136 runqueue_t *busiest = NULL;
2139 for_each_cpu_mask(i, group->cpumask) {
2140 load = source_load(i, 0);
2142 if (load > max_load) {
2144 busiest = cpu_rq(i);
2152 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2153 * so long as it is large enough.
2155 #define MAX_PINNED_INTERVAL 512
2158 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2159 * tasks if there is an imbalance.
2161 * Called with this_rq unlocked.
2163 static int load_balance(int this_cpu, runqueue_t *this_rq,
2164 struct sched_domain *sd, enum idle_type idle)
2166 struct sched_group *group;
2167 runqueue_t *busiest;
2168 unsigned long imbalance;
2169 int nr_moved, all_pinned = 0;
2170 int active_balance = 0;
2173 if (idle != NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER)
2176 schedstat_inc(sd, lb_cnt[idle]);
2178 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle);
2180 schedstat_inc(sd, lb_nobusyg[idle]);
2184 busiest = find_busiest_queue(group, idle);
2186 schedstat_inc(sd, lb_nobusyq[idle]);
2190 BUG_ON(busiest == this_rq);
2192 schedstat_add(sd, lb_imbalance[idle], imbalance);
2195 if (busiest->nr_running > 1) {
2197 * Attempt to move tasks. If find_busiest_group has found
2198 * an imbalance but busiest->nr_running <= 1, the group is
2199 * still unbalanced. nr_moved simply stays zero, so it is
2200 * correctly treated as an imbalance.
2202 double_rq_lock(this_rq, busiest);
2203 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2204 imbalance, sd, idle, &all_pinned);
2205 double_rq_unlock(this_rq, busiest);
2207 /* All tasks on this runqueue were pinned by CPU affinity */
2208 if (unlikely(all_pinned))
2213 schedstat_inc(sd, lb_failed[idle]);
2214 sd->nr_balance_failed++;
2216 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2218 spin_lock(&busiest->lock);
2220 /* don't kick the migration_thread, if the curr
2221 * task on busiest cpu can't be moved to this_cpu
2223 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
2224 spin_unlock(&busiest->lock);
2226 goto out_one_pinned;
2229 if (!busiest->active_balance) {
2230 busiest->active_balance = 1;
2231 busiest->push_cpu = this_cpu;
2234 spin_unlock(&busiest->lock);
2236 wake_up_process(busiest->migration_thread);
2239 * We've kicked active balancing, reset the failure
2242 sd->nr_balance_failed = sd->cache_nice_tries+1;
2245 sd->nr_balance_failed = 0;
2247 if (likely(!active_balance)) {
2248 /* We were unbalanced, so reset the balancing interval */
2249 sd->balance_interval = sd->min_interval;
2252 * If we've begun active balancing, start to back off. This
2253 * case may not be covered by the all_pinned logic if there
2254 * is only 1 task on the busy runqueue (because we don't call
2257 if (sd->balance_interval < sd->max_interval)
2258 sd->balance_interval *= 2;
2261 if (!nr_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2266 schedstat_inc(sd, lb_balanced[idle]);
2268 sd->nr_balance_failed = 0;
2271 /* tune up the balancing interval */
2272 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
2273 (sd->balance_interval < sd->max_interval))
2274 sd->balance_interval *= 2;
2276 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2282 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2283 * tasks if there is an imbalance.
2285 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2286 * this_rq is locked.
2288 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2289 struct sched_domain *sd)
2291 struct sched_group *group;
2292 runqueue_t *busiest = NULL;
2293 unsigned long imbalance;
2297 if (sd->flags & SD_SHARE_CPUPOWER)
2300 schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2301 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE, &sd_idle);
2303 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2307 busiest = find_busiest_queue(group, NEWLY_IDLE);
2309 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2313 BUG_ON(busiest == this_rq);
2315 schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2318 if (busiest->nr_running > 1) {
2319 /* Attempt to move tasks */
2320 double_lock_balance(this_rq, busiest);
2321 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2322 imbalance, sd, NEWLY_IDLE, NULL);
2323 spin_unlock(&busiest->lock);
2327 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2328 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2331 sd->nr_balance_failed = 0;
2336 schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
2337 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2339 sd->nr_balance_failed = 0;
2344 * idle_balance is called by schedule() if this_cpu is about to become
2345 * idle. Attempts to pull tasks from other CPUs.
2347 static void idle_balance(int this_cpu, runqueue_t *this_rq)
2349 struct sched_domain *sd;
2351 for_each_domain(this_cpu, sd) {
2352 if (sd->flags & SD_BALANCE_NEWIDLE) {
2353 if (load_balance_newidle(this_cpu, this_rq, sd)) {
2354 /* We've pulled tasks over so stop searching */
2362 * active_load_balance is run by migration threads. It pushes running tasks
2363 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2364 * running on each physical CPU where possible, and avoids physical /
2365 * logical imbalances.
2367 * Called with busiest_rq locked.
2369 static void active_load_balance(runqueue_t *busiest_rq, int busiest_cpu)
2371 struct sched_domain *sd;
2372 runqueue_t *target_rq;
2373 int target_cpu = busiest_rq->push_cpu;
2375 if (busiest_rq->nr_running <= 1)
2376 /* no task to move */
2379 target_rq = cpu_rq(target_cpu);
2382 * This condition is "impossible", if it occurs
2383 * we need to fix it. Originally reported by
2384 * Bjorn Helgaas on a 128-cpu setup.
2386 BUG_ON(busiest_rq == target_rq);
2388 /* move a task from busiest_rq to target_rq */
2389 double_lock_balance(busiest_rq, target_rq);
2391 /* Search for an sd spanning us and the target CPU. */
2392 for_each_domain(target_cpu, sd)
2393 if ((sd->flags & SD_LOAD_BALANCE) &&
2394 cpu_isset(busiest_cpu, sd->span))
2397 if (unlikely(sd == NULL))
2400 schedstat_inc(sd, alb_cnt);
2402 if (move_tasks(target_rq, target_cpu, busiest_rq, 1, sd, SCHED_IDLE, NULL))
2403 schedstat_inc(sd, alb_pushed);
2405 schedstat_inc(sd, alb_failed);
2407 spin_unlock(&target_rq->lock);
2411 * rebalance_tick will get called every timer tick, on every CPU.
2413 * It checks each scheduling domain to see if it is due to be balanced,
2414 * and initiates a balancing operation if so.
2416 * Balancing parameters are set up in arch_init_sched_domains.
2419 /* Don't have all balancing operations going off at once */
2420 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2422 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2423 enum idle_type idle)
2425 unsigned long old_load, this_load;
2426 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2427 struct sched_domain *sd;
2430 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
2431 /* Update our load */
2432 for (i = 0; i < 3; i++) {
2433 unsigned long new_load = this_load;
2435 old_load = this_rq->cpu_load[i];
2437 * Round up the averaging division if load is increasing. This
2438 * prevents us from getting stuck on 9 if the load is 10, for
2441 if (new_load > old_load)
2442 new_load += scale-1;
2443 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) / scale;
2446 for_each_domain(this_cpu, sd) {
2447 unsigned long interval;
2449 if (!(sd->flags & SD_LOAD_BALANCE))
2452 interval = sd->balance_interval;
2453 if (idle != SCHED_IDLE)
2454 interval *= sd->busy_factor;
2456 /* scale ms to jiffies */
2457 interval = msecs_to_jiffies(interval);
2458 if (unlikely(!interval))
2461 if (j - sd->last_balance >= interval) {
2462 if (load_balance(this_cpu, this_rq, sd, idle)) {
2464 * We've pulled tasks over so either we're no
2465 * longer idle, or one of our SMT siblings is
2470 sd->last_balance += interval;
2476 * on UP we do not need to balance between CPUs:
2478 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2481 static inline void idle_balance(int cpu, runqueue_t *rq)
2486 static inline int wake_priority_sleeper(runqueue_t *rq)
2489 #ifdef CONFIG_SCHED_SMT
2490 spin_lock(&rq->lock);
2492 * If an SMT sibling task has been put to sleep for priority
2493 * reasons reschedule the idle task to see if it can now run.
2495 if (rq->nr_running) {
2496 resched_task(rq->idle);
2499 spin_unlock(&rq->lock);
2504 DEFINE_PER_CPU(struct kernel_stat, kstat);
2506 EXPORT_PER_CPU_SYMBOL(kstat);
2509 * This is called on clock ticks and on context switches.
2510 * Bank in p->sched_time the ns elapsed since the last tick or switch.
2512 static inline void update_cpu_clock(task_t *p, runqueue_t *rq,
2513 unsigned long long now)
2515 unsigned long long last = max(p->timestamp, rq->timestamp_last_tick);
2516 p->sched_time += now - last;
2520 * Return current->sched_time plus any more ns on the sched_clock
2521 * that have not yet been banked.
2523 unsigned long long current_sched_time(const task_t *tsk)
2525 unsigned long long ns;
2526 unsigned long flags;
2527 local_irq_save(flags);
2528 ns = max(tsk->timestamp, task_rq(tsk)->timestamp_last_tick);
2529 ns = tsk->sched_time + (sched_clock() - ns);
2530 local_irq_restore(flags);
2535 * Account user cpu time to a process.
2536 * @p: the process that the cpu time gets accounted to
2537 * @hardirq_offset: the offset to subtract from hardirq_count()
2538 * @cputime: the cpu time spent in user space since the last update
2540 void account_user_time(struct task_struct *p, cputime_t cputime)
2542 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2545 p->utime = cputime_add(p->utime, cputime);
2547 /* Add user time to cpustat. */
2548 tmp = cputime_to_cputime64(cputime);
2549 if (TASK_NICE(p) > 0)
2550 cpustat->nice = cputime64_add(cpustat->nice, tmp);
2552 cpustat->user = cputime64_add(cpustat->user, tmp);
2556 * Account system cpu time to a process.
2557 * @p: the process that the cpu time gets accounted to
2558 * @hardirq_offset: the offset to subtract from hardirq_count()
2559 * @cputime: the cpu time spent in kernel space since the last update
2561 void account_system_time(struct task_struct *p, int hardirq_offset,
2564 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2565 runqueue_t *rq = this_rq();
2568 p->stime = cputime_add(p->stime, cputime);
2570 /* Add system time to cpustat. */
2571 tmp = cputime_to_cputime64(cputime);
2572 if (hardirq_count() - hardirq_offset)
2573 cpustat->irq = cputime64_add(cpustat->irq, tmp);
2574 else if (softirq_count())
2575 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
2576 else if (p != rq->idle)
2577 cpustat->system = cputime64_add(cpustat->system, tmp);
2578 else if (atomic_read(&rq->nr_iowait) > 0)
2579 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2581 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2582 /* Account for system time used */
2583 acct_update_integrals(p);
2587 * Account for involuntary wait time.
2588 * @p: the process from which the cpu time has been stolen
2589 * @steal: the cpu time spent in involuntary wait
2591 void account_steal_time(struct task_struct *p, cputime_t steal)
2593 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2594 cputime64_t tmp = cputime_to_cputime64(steal);
2595 runqueue_t *rq = this_rq();
2597 if (p == rq->idle) {
2598 p->stime = cputime_add(p->stime, steal);
2599 if (atomic_read(&rq->nr_iowait) > 0)
2600 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2602 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2604 cpustat->steal = cputime64_add(cpustat->steal, tmp);
2608 * This function gets called by the timer code, with HZ frequency.
2609 * We call it with interrupts disabled.
2611 * It also gets called by the fork code, when changing the parent's
2614 void scheduler_tick(void)
2616 int cpu = smp_processor_id();
2617 runqueue_t *rq = this_rq();
2618 task_t *p = current;
2619 unsigned long long now = sched_clock();
2621 update_cpu_clock(p, rq, now);
2623 rq->timestamp_last_tick = now;
2625 if (p == rq->idle) {
2626 if (wake_priority_sleeper(rq))
2628 rebalance_tick(cpu, rq, SCHED_IDLE);
2632 /* Task might have expired already, but not scheduled off yet */
2633 if (p->array != rq->active) {
2634 set_tsk_need_resched(p);
2637 spin_lock(&rq->lock);
2639 * The task was running during this tick - update the
2640 * time slice counter. Note: we do not update a thread's
2641 * priority until it either goes to sleep or uses up its
2642 * timeslice. This makes it possible for interactive tasks
2643 * to use up their timeslices at their highest priority levels.
2647 * RR tasks need a special form of timeslice management.
2648 * FIFO tasks have no timeslices.
2650 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2651 p->time_slice = task_timeslice(p);
2652 p->first_time_slice = 0;
2653 set_tsk_need_resched(p);
2655 /* put it at the end of the queue: */
2656 requeue_task(p, rq->active);
2660 if (!--p->time_slice) {
2661 dequeue_task(p, rq->active);
2662 set_tsk_need_resched(p);
2663 p->prio = effective_prio(p);
2664 p->time_slice = task_timeslice(p);
2665 p->first_time_slice = 0;
2667 if (!rq->expired_timestamp)
2668 rq->expired_timestamp = jiffies;
2669 if (!TASK_INTERACTIVE(p) || expired_starving(rq)) {
2670 enqueue_task(p, rq->expired);
2671 if (p->static_prio < rq->best_expired_prio)
2672 rq->best_expired_prio = p->static_prio;
2674 enqueue_task(p, rq->active);
2677 * Prevent a too long timeslice allowing a task to monopolize
2678 * the CPU. We do this by splitting up the timeslice into
2681 * Note: this does not mean the task's timeslices expire or
2682 * get lost in any way, they just might be preempted by
2683 * another task of equal priority. (one with higher
2684 * priority would have preempted this task already.) We
2685 * requeue this task to the end of the list on this priority
2686 * level, which is in essence a round-robin of tasks with
2689 * This only applies to tasks in the interactive
2690 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2692 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2693 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2694 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2695 (p->array == rq->active)) {
2697 requeue_task(p, rq->active);
2698 set_tsk_need_resched(p);
2702 spin_unlock(&rq->lock);
2704 rebalance_tick(cpu, rq, NOT_IDLE);
2707 #ifdef CONFIG_SCHED_SMT
2708 static inline void wakeup_busy_runqueue(runqueue_t *rq)
2710 /* If an SMT runqueue is sleeping due to priority reasons wake it up */
2711 if (rq->curr == rq->idle && rq->nr_running)
2712 resched_task(rq->idle);
2715 static void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2717 struct sched_domain *tmp, *sd = NULL;
2718 cpumask_t sibling_map;
2721 for_each_domain(this_cpu, tmp)
2722 if (tmp->flags & SD_SHARE_CPUPOWER)
2729 * Unlock the current runqueue because we have to lock in
2730 * CPU order to avoid deadlocks. Caller knows that we might
2731 * unlock. We keep IRQs disabled.
2733 spin_unlock(&this_rq->lock);
2735 sibling_map = sd->span;
2737 for_each_cpu_mask(i, sibling_map)
2738 spin_lock(&cpu_rq(i)->lock);
2740 * We clear this CPU from the mask. This both simplifies the
2741 * inner loop and keps this_rq locked when we exit:
2743 cpu_clear(this_cpu, sibling_map);
2745 for_each_cpu_mask(i, sibling_map) {
2746 runqueue_t *smt_rq = cpu_rq(i);
2748 wakeup_busy_runqueue(smt_rq);
2751 for_each_cpu_mask(i, sibling_map)
2752 spin_unlock(&cpu_rq(i)->lock);
2754 * We exit with this_cpu's rq still held and IRQs
2760 * number of 'lost' timeslices this task wont be able to fully
2761 * utilize, if another task runs on a sibling. This models the
2762 * slowdown effect of other tasks running on siblings:
2764 static inline unsigned long smt_slice(task_t *p, struct sched_domain *sd)
2766 return p->time_slice * (100 - sd->per_cpu_gain) / 100;
2769 static int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2771 struct sched_domain *tmp, *sd = NULL;
2772 cpumask_t sibling_map;
2773 prio_array_t *array;
2777 for_each_domain(this_cpu, tmp)
2778 if (tmp->flags & SD_SHARE_CPUPOWER)
2785 * The same locking rules and details apply as for
2786 * wake_sleeping_dependent():
2788 spin_unlock(&this_rq->lock);
2789 sibling_map = sd->span;
2790 for_each_cpu_mask(i, sibling_map)
2791 spin_lock(&cpu_rq(i)->lock);
2792 cpu_clear(this_cpu, sibling_map);
2795 * Establish next task to be run - it might have gone away because
2796 * we released the runqueue lock above:
2798 if (!this_rq->nr_running)
2800 array = this_rq->active;
2801 if (!array->nr_active)
2802 array = this_rq->expired;
2803 BUG_ON(!array->nr_active);
2805 p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
2808 for_each_cpu_mask(i, sibling_map) {
2809 runqueue_t *smt_rq = cpu_rq(i);
2810 task_t *smt_curr = smt_rq->curr;
2812 /* Kernel threads do not participate in dependent sleeping */
2813 if (!p->mm || !smt_curr->mm || rt_task(p))
2814 goto check_smt_task;
2817 * If a user task with lower static priority than the
2818 * running task on the SMT sibling is trying to schedule,
2819 * delay it till there is proportionately less timeslice
2820 * left of the sibling task to prevent a lower priority
2821 * task from using an unfair proportion of the
2822 * physical cpu's resources. -ck
2824 if (rt_task(smt_curr)) {
2826 * With real time tasks we run non-rt tasks only
2827 * per_cpu_gain% of the time.
2829 if ((jiffies % DEF_TIMESLICE) >
2830 (sd->per_cpu_gain * DEF_TIMESLICE / 100))
2833 if (smt_curr->static_prio < p->static_prio &&
2834 !TASK_PREEMPTS_CURR(p, smt_rq) &&
2835 smt_slice(smt_curr, sd) > task_timeslice(p))
2839 if ((!smt_curr->mm && smt_curr != smt_rq->idle) ||
2843 wakeup_busy_runqueue(smt_rq);
2848 * Reschedule a lower priority task on the SMT sibling for
2849 * it to be put to sleep, or wake it up if it has been put to
2850 * sleep for priority reasons to see if it should run now.
2853 if ((jiffies % DEF_TIMESLICE) >
2854 (sd->per_cpu_gain * DEF_TIMESLICE / 100))
2855 resched_task(smt_curr);
2857 if (TASK_PREEMPTS_CURR(p, smt_rq) &&
2858 smt_slice(p, sd) > task_timeslice(smt_curr))
2859 resched_task(smt_curr);
2861 wakeup_busy_runqueue(smt_rq);
2865 for_each_cpu_mask(i, sibling_map)
2866 spin_unlock(&cpu_rq(i)->lock);
2870 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2874 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2880 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
2882 void fastcall add_preempt_count(int val)
2887 BUG_ON((preempt_count() < 0));
2888 preempt_count() += val;
2890 * Spinlock count overflowing soon?
2892 BUG_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
2894 EXPORT_SYMBOL(add_preempt_count);
2896 void fastcall sub_preempt_count(int val)
2901 BUG_ON(val > preempt_count());
2903 * Is the spinlock portion underflowing?
2905 BUG_ON((val < PREEMPT_MASK) && !(preempt_count() & PREEMPT_MASK));
2906 preempt_count() -= val;
2908 EXPORT_SYMBOL(sub_preempt_count);
2912 static inline int interactive_sleep(enum sleep_type sleep_type)
2914 return (sleep_type == SLEEP_INTERACTIVE ||
2915 sleep_type == SLEEP_INTERRUPTED);
2919 * schedule() is the main scheduler function.
2921 asmlinkage void __sched schedule(void)
2924 task_t *prev, *next;
2926 prio_array_t *array;
2927 struct list_head *queue;
2928 unsigned long long now;
2929 unsigned long run_time;
2930 int cpu, idx, new_prio;
2933 * Test if we are atomic. Since do_exit() needs to call into
2934 * schedule() atomically, we ignore that path for now.
2935 * Otherwise, whine if we are scheduling when we should not be.
2937 if (unlikely(in_atomic() && !current->exit_state)) {
2938 printk(KERN_ERR "BUG: scheduling while atomic: "
2940 current->comm, preempt_count(), current->pid);
2943 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
2948 release_kernel_lock(prev);
2949 need_resched_nonpreemptible:
2953 * The idle thread is not allowed to schedule!
2954 * Remove this check after it has been exercised a bit.
2956 if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
2957 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
2961 schedstat_inc(rq, sched_cnt);
2962 now = sched_clock();
2963 if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
2964 run_time = now - prev->timestamp;
2965 if (unlikely((long long)(now - prev->timestamp) < 0))
2968 run_time = NS_MAX_SLEEP_AVG;
2971 * Tasks charged proportionately less run_time at high sleep_avg to
2972 * delay them losing their interactive status
2974 run_time /= (CURRENT_BONUS(prev) ? : 1);
2976 spin_lock_irq(&rq->lock);
2978 if (unlikely(prev->flags & PF_DEAD))
2979 prev->state = EXIT_DEAD;
2981 switch_count = &prev->nivcsw;
2982 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2983 switch_count = &prev->nvcsw;
2984 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2985 unlikely(signal_pending(prev))))
2986 prev->state = TASK_RUNNING;
2988 if (prev->state == TASK_UNINTERRUPTIBLE)
2989 rq->nr_uninterruptible++;
2990 deactivate_task(prev, rq);
2994 cpu = smp_processor_id();
2995 if (unlikely(!rq->nr_running)) {
2997 idle_balance(cpu, rq);
2998 if (!rq->nr_running) {
3000 rq->expired_timestamp = 0;
3001 wake_sleeping_dependent(cpu, rq);
3003 * wake_sleeping_dependent() might have released
3004 * the runqueue, so break out if we got new
3007 if (!rq->nr_running)
3011 if (dependent_sleeper(cpu, rq)) {
3016 * dependent_sleeper() releases and reacquires the runqueue
3017 * lock, hence go into the idle loop if the rq went
3020 if (unlikely(!rq->nr_running))
3025 if (unlikely(!array->nr_active)) {
3027 * Switch the active and expired arrays.
3029 schedstat_inc(rq, sched_switch);
3030 rq->active = rq->expired;
3031 rq->expired = array;
3033 rq->expired_timestamp = 0;
3034 rq->best_expired_prio = MAX_PRIO;
3037 idx = sched_find_first_bit(array->bitmap);
3038 queue = array->queue + idx;
3039 next = list_entry(queue->next, task_t, run_list);
3041 if (!rt_task(next) && interactive_sleep(next->sleep_type)) {
3042 unsigned long long delta = now - next->timestamp;
3043 if (unlikely((long long)(now - next->timestamp) < 0))
3046 if (next->sleep_type == SLEEP_INTERACTIVE)
3047 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
3049 array = next->array;
3050 new_prio = recalc_task_prio(next, next->timestamp + delta);
3052 if (unlikely(next->prio != new_prio)) {
3053 dequeue_task(next, array);
3054 next->prio = new_prio;
3055 enqueue_task(next, array);
3058 next->sleep_type = SLEEP_NORMAL;
3060 if (next == rq->idle)
3061 schedstat_inc(rq, sched_goidle);
3063 prefetch_stack(next);
3064 clear_tsk_need_resched(prev);
3065 rcu_qsctr_inc(task_cpu(prev));
3067 update_cpu_clock(prev, rq, now);
3069 prev->sleep_avg -= run_time;
3070 if ((long)prev->sleep_avg <= 0)
3071 prev->sleep_avg = 0;
3072 prev->timestamp = prev->last_ran = now;
3074 sched_info_switch(prev, next);
3075 if (likely(prev != next)) {
3076 next->timestamp = now;
3081 prepare_task_switch(rq, next);
3082 prev = context_switch(rq, prev, next);
3085 * this_rq must be evaluated again because prev may have moved
3086 * CPUs since it called schedule(), thus the 'rq' on its stack
3087 * frame will be invalid.
3089 finish_task_switch(this_rq(), prev);
3091 spin_unlock_irq(&rq->lock);
3094 if (unlikely(reacquire_kernel_lock(prev) < 0))
3095 goto need_resched_nonpreemptible;
3096 preempt_enable_no_resched();
3097 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3101 EXPORT_SYMBOL(schedule);
3103 #ifdef CONFIG_PREEMPT
3105 * this is is the entry point to schedule() from in-kernel preemption
3106 * off of preempt_enable. Kernel preemptions off return from interrupt
3107 * occur there and call schedule directly.
3109 asmlinkage void __sched preempt_schedule(void)
3111 struct thread_info *ti = current_thread_info();
3112 #ifdef CONFIG_PREEMPT_BKL
3113 struct task_struct *task = current;
3114 int saved_lock_depth;
3117 * If there is a non-zero preempt_count or interrupts are disabled,
3118 * we do not want to preempt the current task. Just return..
3120 if (unlikely(ti->preempt_count || irqs_disabled()))
3124 add_preempt_count(PREEMPT_ACTIVE);
3126 * We keep the big kernel semaphore locked, but we
3127 * clear ->lock_depth so that schedule() doesnt
3128 * auto-release the semaphore:
3130 #ifdef CONFIG_PREEMPT_BKL
3131 saved_lock_depth = task->lock_depth;
3132 task->lock_depth = -1;
3135 #ifdef CONFIG_PREEMPT_BKL
3136 task->lock_depth = saved_lock_depth;
3138 sub_preempt_count(PREEMPT_ACTIVE);
3140 /* we could miss a preemption opportunity between schedule and now */
3142 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3146 EXPORT_SYMBOL(preempt_schedule);
3149 * this is is the entry point to schedule() from kernel preemption
3150 * off of irq context.
3151 * Note, that this is called and return with irqs disabled. This will
3152 * protect us against recursive calling from irq.
3154 asmlinkage void __sched preempt_schedule_irq(void)
3156 struct thread_info *ti = current_thread_info();
3157 #ifdef CONFIG_PREEMPT_BKL
3158 struct task_struct *task = current;
3159 int saved_lock_depth;
3161 /* Catch callers which need to be fixed*/
3162 BUG_ON(ti->preempt_count || !irqs_disabled());
3165 add_preempt_count(PREEMPT_ACTIVE);
3167 * We keep the big kernel semaphore locked, but we
3168 * clear ->lock_depth so that schedule() doesnt
3169 * auto-release the semaphore:
3171 #ifdef CONFIG_PREEMPT_BKL
3172 saved_lock_depth = task->lock_depth;
3173 task->lock_depth = -1;
3177 local_irq_disable();
3178 #ifdef CONFIG_PREEMPT_BKL
3179 task->lock_depth = saved_lock_depth;
3181 sub_preempt_count(PREEMPT_ACTIVE);
3183 /* we could miss a preemption opportunity between schedule and now */
3185 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3189 #endif /* CONFIG_PREEMPT */
3191 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
3194 task_t *p = curr->private;
3195 return try_to_wake_up(p, mode, sync);
3198 EXPORT_SYMBOL(default_wake_function);
3201 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3202 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3203 * number) then we wake all the non-exclusive tasks and one exclusive task.
3205 * There are circumstances in which we can try to wake a task which has already
3206 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3207 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3209 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3210 int nr_exclusive, int sync, void *key)
3212 struct list_head *tmp, *next;
3214 list_for_each_safe(tmp, next, &q->task_list) {
3217 curr = list_entry(tmp, wait_queue_t, task_list);
3218 flags = curr->flags;
3219 if (curr->func(curr, mode, sync, key) &&
3220 (flags & WQ_FLAG_EXCLUSIVE) &&
3227 * __wake_up - wake up threads blocked on a waitqueue.
3229 * @mode: which threads
3230 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3231 * @key: is directly passed to the wakeup function
3233 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3234 int nr_exclusive, void *key)
3236 unsigned long flags;
3238 spin_lock_irqsave(&q->lock, flags);
3239 __wake_up_common(q, mode, nr_exclusive, 0, key);
3240 spin_unlock_irqrestore(&q->lock, flags);
3243 EXPORT_SYMBOL(__wake_up);
3246 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3248 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3250 __wake_up_common(q, mode, 1, 0, NULL);
3254 * __wake_up_sync - wake up threads blocked on a waitqueue.
3256 * @mode: which threads
3257 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3259 * The sync wakeup differs that the waker knows that it will schedule
3260 * away soon, so while the target thread will be woken up, it will not
3261 * be migrated to another CPU - ie. the two threads are 'synchronized'
3262 * with each other. This can prevent needless bouncing between CPUs.
3264 * On UP it can prevent extra preemption.
3267 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3269 unsigned long flags;
3275 if (unlikely(!nr_exclusive))
3278 spin_lock_irqsave(&q->lock, flags);
3279 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3280 spin_unlock_irqrestore(&q->lock, flags);
3282 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3284 void fastcall complete(struct completion *x)
3286 unsigned long flags;
3288 spin_lock_irqsave(&x->wait.lock, flags);
3290 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3292 spin_unlock_irqrestore(&x->wait.lock, flags);
3294 EXPORT_SYMBOL(complete);
3296 void fastcall complete_all(struct completion *x)
3298 unsigned long flags;
3300 spin_lock_irqsave(&x->wait.lock, flags);
3301 x->done += UINT_MAX/2;
3302 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3304 spin_unlock_irqrestore(&x->wait.lock, flags);
3306 EXPORT_SYMBOL(complete_all);
3308 void fastcall __sched wait_for_completion(struct completion *x)
3311 spin_lock_irq(&x->wait.lock);
3313 DECLARE_WAITQUEUE(wait, current);
3315 wait.flags |= WQ_FLAG_EXCLUSIVE;
3316 __add_wait_queue_tail(&x->wait, &wait);
3318 __set_current_state(TASK_UNINTERRUPTIBLE);
3319 spin_unlock_irq(&x->wait.lock);
3321 spin_lock_irq(&x->wait.lock);
3323 __remove_wait_queue(&x->wait, &wait);
3326 spin_unlock_irq(&x->wait.lock);
3328 EXPORT_SYMBOL(wait_for_completion);
3330 unsigned long fastcall __sched
3331 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3335 spin_lock_irq(&x->wait.lock);
3337 DECLARE_WAITQUEUE(wait, current);
3339 wait.flags |= WQ_FLAG_EXCLUSIVE;
3340 __add_wait_queue_tail(&x->wait, &wait);
3342 __set_current_state(TASK_UNINTERRUPTIBLE);
3343 spin_unlock_irq(&x->wait.lock);
3344 timeout = schedule_timeout(timeout);
3345 spin_lock_irq(&x->wait.lock);
3347 __remove_wait_queue(&x->wait, &wait);
3351 __remove_wait_queue(&x->wait, &wait);
3355 spin_unlock_irq(&x->wait.lock);
3358 EXPORT_SYMBOL(wait_for_completion_timeout);
3360 int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3366 spin_lock_irq(&x->wait.lock);
3368 DECLARE_WAITQUEUE(wait, current);
3370 wait.flags |= WQ_FLAG_EXCLUSIVE;
3371 __add_wait_queue_tail(&x->wait, &wait);
3373 if (signal_pending(current)) {
3375 __remove_wait_queue(&x->wait, &wait);
3378 __set_current_state(TASK_INTERRUPTIBLE);
3379 spin_unlock_irq(&x->wait.lock);
3381 spin_lock_irq(&x->wait.lock);
3383 __remove_wait_queue(&x->wait, &wait);
3387 spin_unlock_irq(&x->wait.lock);
3391 EXPORT_SYMBOL(wait_for_completion_interruptible);
3393 unsigned long fastcall __sched
3394 wait_for_completion_interruptible_timeout(struct completion *x,
3395 unsigned long timeout)
3399 spin_lock_irq(&x->wait.lock);
3401 DECLARE_WAITQUEUE(wait, current);
3403 wait.flags |= WQ_FLAG_EXCLUSIVE;
3404 __add_wait_queue_tail(&x->wait, &wait);
3406 if (signal_pending(current)) {
3407 timeout = -ERESTARTSYS;
3408 __remove_wait_queue(&x->wait, &wait);
3411 __set_current_state(TASK_INTERRUPTIBLE);
3412 spin_unlock_irq(&x->wait.lock);
3413 timeout = schedule_timeout(timeout);
3414 spin_lock_irq(&x->wait.lock);
3416 __remove_wait_queue(&x->wait, &wait);
3420 __remove_wait_queue(&x->wait, &wait);
3424 spin_unlock_irq(&x->wait.lock);
3427 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3430 #define SLEEP_ON_VAR \
3431 unsigned long flags; \
3432 wait_queue_t wait; \
3433 init_waitqueue_entry(&wait, current);
3435 #define SLEEP_ON_HEAD \
3436 spin_lock_irqsave(&q->lock,flags); \
3437 __add_wait_queue(q, &wait); \
3438 spin_unlock(&q->lock);
3440 #define SLEEP_ON_TAIL \
3441 spin_lock_irq(&q->lock); \
3442 __remove_wait_queue(q, &wait); \
3443 spin_unlock_irqrestore(&q->lock, flags);
3445 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3449 current->state = TASK_INTERRUPTIBLE;
3456 EXPORT_SYMBOL(interruptible_sleep_on);
3458 long fastcall __sched
3459 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3463 current->state = TASK_INTERRUPTIBLE;
3466 timeout = schedule_timeout(timeout);
3472 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3474 void fastcall __sched sleep_on(wait_queue_head_t *q)
3478 current->state = TASK_UNINTERRUPTIBLE;
3485 EXPORT_SYMBOL(sleep_on);
3487 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3491 current->state = TASK_UNINTERRUPTIBLE;
3494 timeout = schedule_timeout(timeout);
3500 EXPORT_SYMBOL(sleep_on_timeout);
3502 void set_user_nice(task_t *p, long nice)
3504 unsigned long flags;
3505 prio_array_t *array;
3507 int old_prio, new_prio, delta;
3509 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3512 * We have to be careful, if called from sys_setpriority(),
3513 * the task might be in the middle of scheduling on another CPU.
3515 rq = task_rq_lock(p, &flags);
3517 * The RT priorities are set via sched_setscheduler(), but we still
3518 * allow the 'normal' nice value to be set - but as expected
3519 * it wont have any effect on scheduling until the task is
3520 * not SCHED_NORMAL/SCHED_BATCH:
3523 p->static_prio = NICE_TO_PRIO(nice);
3528 dequeue_task(p, array);
3531 new_prio = NICE_TO_PRIO(nice);
3532 delta = new_prio - old_prio;
3533 p->static_prio = NICE_TO_PRIO(nice);
3537 enqueue_task(p, array);
3539 * If the task increased its priority or is running and
3540 * lowered its priority, then reschedule its CPU:
3542 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3543 resched_task(rq->curr);
3546 task_rq_unlock(rq, &flags);
3549 EXPORT_SYMBOL(set_user_nice);
3552 * can_nice - check if a task can reduce its nice value
3556 int can_nice(const task_t *p, const int nice)
3558 /* convert nice value [19,-20] to rlimit style value [1,40] */
3559 int nice_rlim = 20 - nice;
3560 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
3561 capable(CAP_SYS_NICE));
3564 #ifdef __ARCH_WANT_SYS_NICE
3567 * sys_nice - change the priority of the current process.
3568 * @increment: priority increment
3570 * sys_setpriority is a more generic, but much slower function that
3571 * does similar things.
3573 asmlinkage long sys_nice(int increment)
3579 * Setpriority might change our priority at the same moment.
3580 * We don't have to worry. Conceptually one call occurs first
3581 * and we have a single winner.
3583 if (increment < -40)
3588 nice = PRIO_TO_NICE(current->static_prio) + increment;
3594 if (increment < 0 && !can_nice(current, nice))
3597 retval = security_task_setnice(current, nice);
3601 set_user_nice(current, nice);
3608 * task_prio - return the priority value of a given task.
3609 * @p: the task in question.
3611 * This is the priority value as seen by users in /proc.
3612 * RT tasks are offset by -200. Normal tasks are centered
3613 * around 0, value goes from -16 to +15.
3615 int task_prio(const task_t *p)
3617 return p->prio - MAX_RT_PRIO;
3621 * task_nice - return the nice value of a given task.
3622 * @p: the task in question.
3624 int task_nice(const task_t *p)
3626 return TASK_NICE(p);
3628 EXPORT_SYMBOL_GPL(task_nice);
3631 * idle_cpu - is a given cpu idle currently?
3632 * @cpu: the processor in question.
3634 int idle_cpu(int cpu)
3636 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3640 * idle_task - return the idle task for a given cpu.
3641 * @cpu: the processor in question.
3643 task_t *idle_task(int cpu)
3645 return cpu_rq(cpu)->idle;
3649 * find_process_by_pid - find a process with a matching PID value.
3650 * @pid: the pid in question.
3652 static inline task_t *find_process_by_pid(pid_t pid)
3654 return pid ? find_task_by_pid(pid) : current;
3657 /* Actually do priority change: must hold rq lock. */
3658 static void __setscheduler(struct task_struct *p, int policy, int prio)
3662 p->rt_priority = prio;
3663 if (policy != SCHED_NORMAL && policy != SCHED_BATCH) {
3664 p->prio = MAX_RT_PRIO-1 - p->rt_priority;
3666 p->prio = p->static_prio;
3668 * SCHED_BATCH tasks are treated as perpetual CPU hogs:
3670 if (policy == SCHED_BATCH)
3676 * sched_setscheduler - change the scheduling policy and/or RT priority of
3678 * @p: the task in question.
3679 * @policy: new policy.
3680 * @param: structure containing the new RT priority.
3682 int sched_setscheduler(struct task_struct *p, int policy,
3683 struct sched_param *param)
3686 int oldprio, oldpolicy = -1;
3687 prio_array_t *array;
3688 unsigned long flags;
3692 /* double check policy once rq lock held */
3694 policy = oldpolicy = p->policy;
3695 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
3696 policy != SCHED_NORMAL && policy != SCHED_BATCH)
3699 * Valid priorities for SCHED_FIFO and SCHED_RR are
3700 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL and
3703 if (param->sched_priority < 0 ||
3704 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
3705 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
3707 if ((policy == SCHED_NORMAL || policy == SCHED_BATCH)
3708 != (param->sched_priority == 0))
3712 * Allow unprivileged RT tasks to decrease priority:
3714 if (!capable(CAP_SYS_NICE)) {
3716 * can't change policy, except between SCHED_NORMAL
3719 if (((policy != SCHED_NORMAL && p->policy != SCHED_BATCH) &&
3720 (policy != SCHED_BATCH && p->policy != SCHED_NORMAL)) &&
3721 !p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
3723 /* can't increase priority */
3724 if ((policy != SCHED_NORMAL && policy != SCHED_BATCH) &&
3725 param->sched_priority > p->rt_priority &&
3726 param->sched_priority >
3727 p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
3729 /* can't change other user's priorities */
3730 if ((current->euid != p->euid) &&
3731 (current->euid != p->uid))
3735 retval = security_task_setscheduler(p, policy, param);
3739 * To be able to change p->policy safely, the apropriate
3740 * runqueue lock must be held.
3742 rq = task_rq_lock(p, &flags);
3743 /* recheck policy now with rq lock held */
3744 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3745 policy = oldpolicy = -1;
3746 task_rq_unlock(rq, &flags);
3751 deactivate_task(p, rq);
3753 __setscheduler(p, policy, param->sched_priority);
3755 __activate_task(p, rq);
3757 * Reschedule if we are currently running on this runqueue and
3758 * our priority decreased, or if we are not currently running on
3759 * this runqueue and our priority is higher than the current's
3761 if (task_running(rq, p)) {
3762 if (p->prio > oldprio)
3763 resched_task(rq->curr);
3764 } else if (TASK_PREEMPTS_CURR(p, rq))
3765 resched_task(rq->curr);
3767 task_rq_unlock(rq, &flags);
3770 EXPORT_SYMBOL_GPL(sched_setscheduler);
3773 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3776 struct sched_param lparam;
3777 struct task_struct *p;
3779 if (!param || pid < 0)
3781 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
3783 read_lock_irq(&tasklist_lock);
3784 p = find_process_by_pid(pid);
3786 read_unlock_irq(&tasklist_lock);
3789 retval = sched_setscheduler(p, policy, &lparam);
3790 read_unlock_irq(&tasklist_lock);
3795 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3796 * @pid: the pid in question.
3797 * @policy: new policy.
3798 * @param: structure containing the new RT priority.
3800 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3801 struct sched_param __user *param)
3803 /* negative values for policy are not valid */
3807 return do_sched_setscheduler(pid, policy, param);
3811 * sys_sched_setparam - set/change the RT priority of a thread
3812 * @pid: the pid in question.
3813 * @param: structure containing the new RT priority.
3815 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3817 return do_sched_setscheduler(pid, -1, param);
3821 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3822 * @pid: the pid in question.
3824 asmlinkage long sys_sched_getscheduler(pid_t pid)
3826 int retval = -EINVAL;
3833 read_lock(&tasklist_lock);
3834 p = find_process_by_pid(pid);
3836 retval = security_task_getscheduler(p);
3840 read_unlock(&tasklist_lock);
3847 * sys_sched_getscheduler - get the RT priority of a thread
3848 * @pid: the pid in question.
3849 * @param: structure containing the RT priority.
3851 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3853 struct sched_param lp;
3854 int retval = -EINVAL;
3857 if (!param || pid < 0)
3860 read_lock(&tasklist_lock);
3861 p = find_process_by_pid(pid);
3866 retval = security_task_getscheduler(p);
3870 lp.sched_priority = p->rt_priority;
3871 read_unlock(&tasklist_lock);
3874 * This one might sleep, we cannot do it with a spinlock held ...
3876 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3882 read_unlock(&tasklist_lock);
3886 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
3890 cpumask_t cpus_allowed;
3893 read_lock(&tasklist_lock);
3895 p = find_process_by_pid(pid);
3897 read_unlock(&tasklist_lock);
3898 unlock_cpu_hotplug();
3903 * It is not safe to call set_cpus_allowed with the
3904 * tasklist_lock held. We will bump the task_struct's
3905 * usage count and then drop tasklist_lock.
3908 read_unlock(&tasklist_lock);
3911 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3912 !capable(CAP_SYS_NICE))
3915 cpus_allowed = cpuset_cpus_allowed(p);
3916 cpus_and(new_mask, new_mask, cpus_allowed);
3917 retval = set_cpus_allowed(p, new_mask);
3921 unlock_cpu_hotplug();
3925 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
3926 cpumask_t *new_mask)
3928 if (len < sizeof(cpumask_t)) {
3929 memset(new_mask, 0, sizeof(cpumask_t));
3930 } else if (len > sizeof(cpumask_t)) {
3931 len = sizeof(cpumask_t);
3933 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
3937 * sys_sched_setaffinity - set the cpu affinity of a process
3938 * @pid: pid of the process
3939 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3940 * @user_mask_ptr: user-space pointer to the new cpu mask
3942 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
3943 unsigned long __user *user_mask_ptr)
3948 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
3952 return sched_setaffinity(pid, new_mask);
3956 * Represents all cpu's present in the system
3957 * In systems capable of hotplug, this map could dynamically grow
3958 * as new cpu's are detected in the system via any platform specific
3959 * method, such as ACPI for e.g.
3962 cpumask_t cpu_present_map __read_mostly;
3963 EXPORT_SYMBOL(cpu_present_map);
3966 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
3967 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
3970 long sched_getaffinity(pid_t pid, cpumask_t *mask)
3976 read_lock(&tasklist_lock);
3979 p = find_process_by_pid(pid);
3984 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
3987 read_unlock(&tasklist_lock);
3988 unlock_cpu_hotplug();
3996 * sys_sched_getaffinity - get the cpu affinity of a process
3997 * @pid: pid of the process
3998 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3999 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4001 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
4002 unsigned long __user *user_mask_ptr)
4007 if (len < sizeof(cpumask_t))
4010 ret = sched_getaffinity(pid, &mask);
4014 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
4017 return sizeof(cpumask_t);
4021 * sys_sched_yield - yield the current processor to other threads.
4023 * this function yields the current CPU by moving the calling thread
4024 * to the expired array. If there are no other threads running on this
4025 * CPU then this function will return.
4027 asmlinkage long sys_sched_yield(void)
4029 runqueue_t *rq = this_rq_lock();
4030 prio_array_t *array = current->array;
4031 prio_array_t *target = rq->expired;
4033 schedstat_inc(rq, yld_cnt);
4035 * We implement yielding by moving the task into the expired
4038 * (special rule: RT tasks will just roundrobin in the active
4041 if (rt_task(current))
4042 target = rq->active;
4044 if (array->nr_active == 1) {
4045 schedstat_inc(rq, yld_act_empty);
4046 if (!rq->expired->nr_active)
4047 schedstat_inc(rq, yld_both_empty);
4048 } else if (!rq->expired->nr_active)
4049 schedstat_inc(rq, yld_exp_empty);
4051 if (array != target) {
4052 dequeue_task(current, array);
4053 enqueue_task(current, target);
4056 * requeue_task is cheaper so perform that if possible.
4058 requeue_task(current, array);
4061 * Since we are going to call schedule() anyway, there's
4062 * no need to preempt or enable interrupts:
4064 __release(rq->lock);
4065 _raw_spin_unlock(&rq->lock);
4066 preempt_enable_no_resched();
4073 static inline void __cond_resched(void)
4076 * The BKS might be reacquired before we have dropped
4077 * PREEMPT_ACTIVE, which could trigger a second
4078 * cond_resched() call.
4080 if (unlikely(preempt_count()))
4082 if (unlikely(system_state != SYSTEM_RUNNING))
4085 add_preempt_count(PREEMPT_ACTIVE);
4087 sub_preempt_count(PREEMPT_ACTIVE);
4088 } while (need_resched());
4091 int __sched cond_resched(void)
4093 if (need_resched()) {
4100 EXPORT_SYMBOL(cond_resched);
4103 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4104 * call schedule, and on return reacquire the lock.
4106 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4107 * operations here to prevent schedule() from being called twice (once via
4108 * spin_unlock(), once by hand).
4110 int cond_resched_lock(spinlock_t *lock)
4114 if (need_lockbreak(lock)) {
4120 if (need_resched()) {
4121 _raw_spin_unlock(lock);
4122 preempt_enable_no_resched();
4130 EXPORT_SYMBOL(cond_resched_lock);
4132 int __sched cond_resched_softirq(void)
4134 BUG_ON(!in_softirq());
4136 if (need_resched()) {
4137 __local_bh_enable();
4145 EXPORT_SYMBOL(cond_resched_softirq);
4149 * yield - yield the current processor to other threads.
4151 * this is a shortcut for kernel-space yielding - it marks the
4152 * thread runnable and calls sys_sched_yield().
4154 void __sched yield(void)
4156 set_current_state(TASK_RUNNING);
4160 EXPORT_SYMBOL(yield);
4163 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4164 * that process accounting knows that this is a task in IO wait state.
4166 * But don't do that if it is a deliberate, throttling IO wait (this task
4167 * has set its backing_dev_info: the queue against which it should throttle)
4169 void __sched io_schedule(void)
4171 struct runqueue *rq = &per_cpu(runqueues, raw_smp_processor_id());
4173 atomic_inc(&rq->nr_iowait);
4175 atomic_dec(&rq->nr_iowait);
4178 EXPORT_SYMBOL(io_schedule);
4180 long __sched io_schedule_timeout(long timeout)
4182 struct runqueue *rq = &per_cpu(runqueues, raw_smp_processor_id());
4185 atomic_inc(&rq->nr_iowait);
4186 ret = schedule_timeout(timeout);
4187 atomic_dec(&rq->nr_iowait);
4192 * sys_sched_get_priority_max - return maximum RT priority.
4193 * @policy: scheduling class.
4195 * this syscall returns the maximum rt_priority that can be used
4196 * by a given scheduling class.
4198 asmlinkage long sys_sched_get_priority_max(int policy)
4205 ret = MAX_USER_RT_PRIO-1;
4216 * sys_sched_get_priority_min - return minimum RT priority.
4217 * @policy: scheduling class.
4219 * this syscall returns the minimum rt_priority that can be used
4220 * by a given scheduling class.
4222 asmlinkage long sys_sched_get_priority_min(int policy)
4239 * sys_sched_rr_get_interval - return the default timeslice of a process.
4240 * @pid: pid of the process.
4241 * @interval: userspace pointer to the timeslice value.
4243 * this syscall writes the default timeslice value of a given process
4244 * into the user-space timespec buffer. A value of '0' means infinity.
4247 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4249 int retval = -EINVAL;
4257 read_lock(&tasklist_lock);
4258 p = find_process_by_pid(pid);
4262 retval = security_task_getscheduler(p);
4266 jiffies_to_timespec(p->policy & SCHED_FIFO ?
4267 0 : task_timeslice(p), &t);
4268 read_unlock(&tasklist_lock);
4269 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4273 read_unlock(&tasklist_lock);
4277 static inline struct task_struct *eldest_child(struct task_struct *p)
4279 if (list_empty(&p->children)) return NULL;
4280 return list_entry(p->children.next,struct task_struct,sibling);
4283 static inline struct task_struct *older_sibling(struct task_struct *p)
4285 if (p->sibling.prev==&p->parent->children) return NULL;
4286 return list_entry(p->sibling.prev,struct task_struct,sibling);
4289 static inline struct task_struct *younger_sibling(struct task_struct *p)
4291 if (p->sibling.next==&p->parent->children) return NULL;
4292 return list_entry(p->sibling.next,struct task_struct,sibling);
4295 static void show_task(task_t *p)
4299 unsigned long free = 0;
4300 static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
4302 printk("%-13.13s ", p->comm);
4303 state = p->state ? __ffs(p->state) + 1 : 0;
4304 if (state < ARRAY_SIZE(stat_nam))
4305 printk(stat_nam[state]);
4308 #if (BITS_PER_LONG == 32)
4309 if (state == TASK_RUNNING)
4310 printk(" running ");
4312 printk(" %08lX ", thread_saved_pc(p));
4314 if (state == TASK_RUNNING)
4315 printk(" running task ");
4317 printk(" %016lx ", thread_saved_pc(p));
4319 #ifdef CONFIG_DEBUG_STACK_USAGE
4321 unsigned long *n = end_of_stack(p);
4324 free = (unsigned long)n - (unsigned long)end_of_stack(p);
4327 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
4328 if ((relative = eldest_child(p)))
4329 printk("%5d ", relative->pid);
4332 if ((relative = younger_sibling(p)))
4333 printk("%7d", relative->pid);
4336 if ((relative = older_sibling(p)))
4337 printk(" %5d", relative->pid);
4341 printk(" (L-TLB)\n");
4343 printk(" (NOTLB)\n");
4345 if (state != TASK_RUNNING)
4346 show_stack(p, NULL);
4349 void show_state(void)
4353 #if (BITS_PER_LONG == 32)
4356 printk(" task PC pid father child younger older\n");
4360 printk(" task PC pid father child younger older\n");
4362 read_lock(&tasklist_lock);
4363 do_each_thread(g, p) {
4365 * reset the NMI-timeout, listing all files on a slow
4366 * console might take alot of time:
4368 touch_nmi_watchdog();
4370 } while_each_thread(g, p);
4372 read_unlock(&tasklist_lock);
4373 mutex_debug_show_all_locks();
4377 * init_idle - set up an idle thread for a given CPU
4378 * @idle: task in question
4379 * @cpu: cpu the idle task belongs to
4381 * NOTE: this function does not set the idle thread's NEED_RESCHED
4382 * flag, to make booting more robust.
4384 void __devinit init_idle(task_t *idle, int cpu)
4386 runqueue_t *rq = cpu_rq(cpu);
4387 unsigned long flags;
4389 idle->timestamp = sched_clock();
4390 idle->sleep_avg = 0;
4392 idle->prio = MAX_PRIO;
4393 idle->state = TASK_RUNNING;
4394 idle->cpus_allowed = cpumask_of_cpu(cpu);
4395 set_task_cpu(idle, cpu);
4397 spin_lock_irqsave(&rq->lock, flags);
4398 rq->curr = rq->idle = idle;
4399 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
4402 spin_unlock_irqrestore(&rq->lock, flags);
4404 /* Set the preempt count _outside_ the spinlocks! */
4405 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4406 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
4408 task_thread_info(idle)->preempt_count = 0;
4413 * In a system that switches off the HZ timer nohz_cpu_mask
4414 * indicates which cpus entered this state. This is used
4415 * in the rcu update to wait only for active cpus. For system
4416 * which do not switch off the HZ timer nohz_cpu_mask should
4417 * always be CPU_MASK_NONE.
4419 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4423 * This is how migration works:
4425 * 1) we queue a migration_req_t structure in the source CPU's
4426 * runqueue and wake up that CPU's migration thread.
4427 * 2) we down() the locked semaphore => thread blocks.
4428 * 3) migration thread wakes up (implicitly it forces the migrated
4429 * thread off the CPU)
4430 * 4) it gets the migration request and checks whether the migrated
4431 * task is still in the wrong runqueue.
4432 * 5) if it's in the wrong runqueue then the migration thread removes
4433 * it and puts it into the right queue.
4434 * 6) migration thread up()s the semaphore.
4435 * 7) we wake up and the migration is done.
4439 * Change a given task's CPU affinity. Migrate the thread to a
4440 * proper CPU and schedule it away if the CPU it's executing on
4441 * is removed from the allowed bitmask.
4443 * NOTE: the caller must have a valid reference to the task, the
4444 * task must not exit() & deallocate itself prematurely. The
4445 * call is not atomic; no spinlocks may be held.
4447 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
4449 unsigned long flags;
4451 migration_req_t req;
4454 rq = task_rq_lock(p, &flags);
4455 if (!cpus_intersects(new_mask, cpu_online_map)) {
4460 p->cpus_allowed = new_mask;
4461 /* Can the task run on the task's current CPU? If so, we're done */
4462 if (cpu_isset(task_cpu(p), new_mask))
4465 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4466 /* Need help from migration thread: drop lock and wait. */
4467 task_rq_unlock(rq, &flags);
4468 wake_up_process(rq->migration_thread);
4469 wait_for_completion(&req.done);
4470 tlb_migrate_finish(p->mm);
4474 task_rq_unlock(rq, &flags);
4478 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4481 * Move (not current) task off this cpu, onto dest cpu. We're doing
4482 * this because either it can't run here any more (set_cpus_allowed()
4483 * away from this CPU, or CPU going down), or because we're
4484 * attempting to rebalance this task on exec (sched_exec).
4486 * So we race with normal scheduler movements, but that's OK, as long
4487 * as the task is no longer on this CPU.
4489 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4491 runqueue_t *rq_dest, *rq_src;
4493 if (unlikely(cpu_is_offline(dest_cpu)))
4496 rq_src = cpu_rq(src_cpu);
4497 rq_dest = cpu_rq(dest_cpu);
4499 double_rq_lock(rq_src, rq_dest);
4500 /* Already moved. */
4501 if (task_cpu(p) != src_cpu)
4503 /* Affinity changed (again). */
4504 if (!cpu_isset(dest_cpu, p->cpus_allowed))
4507 set_task_cpu(p, dest_cpu);
4510 * Sync timestamp with rq_dest's before activating.
4511 * The same thing could be achieved by doing this step
4512 * afterwards, and pretending it was a local activate.
4513 * This way is cleaner and logically correct.
4515 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4516 + rq_dest->timestamp_last_tick;
4517 deactivate_task(p, rq_src);
4518 activate_task(p, rq_dest, 0);
4519 if (TASK_PREEMPTS_CURR(p, rq_dest))
4520 resched_task(rq_dest->curr);
4524 double_rq_unlock(rq_src, rq_dest);
4528 * migration_thread - this is a highprio system thread that performs
4529 * thread migration by bumping thread off CPU then 'pushing' onto
4532 static int migration_thread(void *data)
4535 int cpu = (long)data;
4538 BUG_ON(rq->migration_thread != current);
4540 set_current_state(TASK_INTERRUPTIBLE);
4541 while (!kthread_should_stop()) {
4542 struct list_head *head;
4543 migration_req_t *req;
4547 spin_lock_irq(&rq->lock);
4549 if (cpu_is_offline(cpu)) {
4550 spin_unlock_irq(&rq->lock);
4554 if (rq->active_balance) {
4555 active_load_balance(rq, cpu);
4556 rq->active_balance = 0;
4559 head = &rq->migration_queue;
4561 if (list_empty(head)) {
4562 spin_unlock_irq(&rq->lock);
4564 set_current_state(TASK_INTERRUPTIBLE);
4567 req = list_entry(head->next, migration_req_t, list);
4568 list_del_init(head->next);
4570 spin_unlock(&rq->lock);
4571 __migrate_task(req->task, cpu, req->dest_cpu);
4574 complete(&req->done);
4576 __set_current_state(TASK_RUNNING);
4580 /* Wait for kthread_stop */
4581 set_current_state(TASK_INTERRUPTIBLE);
4582 while (!kthread_should_stop()) {
4584 set_current_state(TASK_INTERRUPTIBLE);
4586 __set_current_state(TASK_RUNNING);
4590 #ifdef CONFIG_HOTPLUG_CPU
4591 /* Figure out where task on dead CPU should go, use force if neccessary. */
4592 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
4598 mask = node_to_cpumask(cpu_to_node(dead_cpu));
4599 cpus_and(mask, mask, tsk->cpus_allowed);
4600 dest_cpu = any_online_cpu(mask);
4602 /* On any allowed CPU? */
4603 if (dest_cpu == NR_CPUS)
4604 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4606 /* No more Mr. Nice Guy. */
4607 if (dest_cpu == NR_CPUS) {
4608 cpus_setall(tsk->cpus_allowed);
4609 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4612 * Don't tell them about moving exiting tasks or
4613 * kernel threads (both mm NULL), since they never
4616 if (tsk->mm && printk_ratelimit())
4617 printk(KERN_INFO "process %d (%s) no "
4618 "longer affine to cpu%d\n",
4619 tsk->pid, tsk->comm, dead_cpu);
4621 __migrate_task(tsk, dead_cpu, dest_cpu);
4625 * While a dead CPU has no uninterruptible tasks queued at this point,
4626 * it might still have a nonzero ->nr_uninterruptible counter, because
4627 * for performance reasons the counter is not stricly tracking tasks to
4628 * their home CPUs. So we just add the counter to another CPU's counter,
4629 * to keep the global sum constant after CPU-down:
4631 static void migrate_nr_uninterruptible(runqueue_t *rq_src)
4633 runqueue_t *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
4634 unsigned long flags;
4636 local_irq_save(flags);
4637 double_rq_lock(rq_src, rq_dest);
4638 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
4639 rq_src->nr_uninterruptible = 0;
4640 double_rq_unlock(rq_src, rq_dest);
4641 local_irq_restore(flags);
4644 /* Run through task list and migrate tasks from the dead cpu. */
4645 static void migrate_live_tasks(int src_cpu)
4647 struct task_struct *tsk, *t;
4649 write_lock_irq(&tasklist_lock);
4651 do_each_thread(t, tsk) {
4655 if (task_cpu(tsk) == src_cpu)
4656 move_task_off_dead_cpu(src_cpu, tsk);
4657 } while_each_thread(t, tsk);
4659 write_unlock_irq(&tasklist_lock);
4662 /* Schedules idle task to be the next runnable task on current CPU.
4663 * It does so by boosting its priority to highest possible and adding it to
4664 * the _front_ of runqueue. Used by CPU offline code.
4666 void sched_idle_next(void)
4668 int cpu = smp_processor_id();
4669 runqueue_t *rq = this_rq();
4670 struct task_struct *p = rq->idle;
4671 unsigned long flags;
4673 /* cpu has to be offline */
4674 BUG_ON(cpu_online(cpu));
4676 /* Strictly not necessary since rest of the CPUs are stopped by now
4677 * and interrupts disabled on current cpu.
4679 spin_lock_irqsave(&rq->lock, flags);
4681 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4682 /* Add idle task to _front_ of it's priority queue */
4683 __activate_idle_task(p, rq);
4685 spin_unlock_irqrestore(&rq->lock, flags);
4688 /* Ensures that the idle task is using init_mm right before its cpu goes
4691 void idle_task_exit(void)
4693 struct mm_struct *mm = current->active_mm;
4695 BUG_ON(cpu_online(smp_processor_id()));
4698 switch_mm(mm, &init_mm, current);
4702 static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
4704 struct runqueue *rq = cpu_rq(dead_cpu);
4706 /* Must be exiting, otherwise would be on tasklist. */
4707 BUG_ON(tsk->exit_state != EXIT_ZOMBIE && tsk->exit_state != EXIT_DEAD);
4709 /* Cannot have done final schedule yet: would have vanished. */
4710 BUG_ON(tsk->flags & PF_DEAD);
4712 get_task_struct(tsk);
4715 * Drop lock around migration; if someone else moves it,
4716 * that's OK. No task can be added to this CPU, so iteration is
4719 spin_unlock_irq(&rq->lock);
4720 move_task_off_dead_cpu(dead_cpu, tsk);
4721 spin_lock_irq(&rq->lock);
4723 put_task_struct(tsk);
4726 /* release_task() removes task from tasklist, so we won't find dead tasks. */
4727 static void migrate_dead_tasks(unsigned int dead_cpu)
4730 struct runqueue *rq = cpu_rq(dead_cpu);
4732 for (arr = 0; arr < 2; arr++) {
4733 for (i = 0; i < MAX_PRIO; i++) {
4734 struct list_head *list = &rq->arrays[arr].queue[i];
4735 while (!list_empty(list))
4736 migrate_dead(dead_cpu,
4737 list_entry(list->next, task_t,
4742 #endif /* CONFIG_HOTPLUG_CPU */
4745 * migration_call - callback that gets triggered when a CPU is added.
4746 * Here we can start up the necessary migration thread for the new CPU.
4748 static int migration_call(struct notifier_block *nfb, unsigned long action,
4751 int cpu = (long)hcpu;
4752 struct task_struct *p;
4753 struct runqueue *rq;
4754 unsigned long flags;
4757 case CPU_UP_PREPARE:
4758 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4761 p->flags |= PF_NOFREEZE;
4762 kthread_bind(p, cpu);
4763 /* Must be high prio: stop_machine expects to yield to it. */
4764 rq = task_rq_lock(p, &flags);
4765 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4766 task_rq_unlock(rq, &flags);
4767 cpu_rq(cpu)->migration_thread = p;
4770 /* Strictly unneccessary, as first user will wake it. */
4771 wake_up_process(cpu_rq(cpu)->migration_thread);
4773 #ifdef CONFIG_HOTPLUG_CPU
4774 case CPU_UP_CANCELED:
4775 /* Unbind it from offline cpu so it can run. Fall thru. */
4776 kthread_bind(cpu_rq(cpu)->migration_thread,
4777 any_online_cpu(cpu_online_map));
4778 kthread_stop(cpu_rq(cpu)->migration_thread);
4779 cpu_rq(cpu)->migration_thread = NULL;
4782 migrate_live_tasks(cpu);
4784 kthread_stop(rq->migration_thread);
4785 rq->migration_thread = NULL;
4786 /* Idle task back to normal (off runqueue, low prio) */
4787 rq = task_rq_lock(rq->idle, &flags);
4788 deactivate_task(rq->idle, rq);
4789 rq->idle->static_prio = MAX_PRIO;
4790 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4791 migrate_dead_tasks(cpu);
4792 task_rq_unlock(rq, &flags);
4793 migrate_nr_uninterruptible(rq);
4794 BUG_ON(rq->nr_running != 0);
4796 /* No need to migrate the tasks: it was best-effort if
4797 * they didn't do lock_cpu_hotplug(). Just wake up
4798 * the requestors. */
4799 spin_lock_irq(&rq->lock);
4800 while (!list_empty(&rq->migration_queue)) {
4801 migration_req_t *req;
4802 req = list_entry(rq->migration_queue.next,
4803 migration_req_t, list);
4804 list_del_init(&req->list);
4805 complete(&req->done);
4807 spin_unlock_irq(&rq->lock);
4814 /* Register at highest priority so that task migration (migrate_all_tasks)
4815 * happens before everything else.
4817 static struct notifier_block migration_notifier = {
4818 .notifier_call = migration_call,
4822 int __init migration_init(void)
4824 void *cpu = (void *)(long)smp_processor_id();
4825 /* Start one for boot CPU. */
4826 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4827 migration_call(&migration_notifier, CPU_ONLINE, cpu);
4828 register_cpu_notifier(&migration_notifier);
4834 #undef SCHED_DOMAIN_DEBUG
4835 #ifdef SCHED_DOMAIN_DEBUG
4836 static void sched_domain_debug(struct sched_domain *sd, int cpu)
4841 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
4845 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
4850 struct sched_group *group = sd->groups;
4851 cpumask_t groupmask;
4853 cpumask_scnprintf(str, NR_CPUS, sd->span);
4854 cpus_clear(groupmask);
4857 for (i = 0; i < level + 1; i++)
4859 printk("domain %d: ", level);
4861 if (!(sd->flags & SD_LOAD_BALANCE)) {
4862 printk("does not load-balance\n");
4864 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
4868 printk("span %s\n", str);
4870 if (!cpu_isset(cpu, sd->span))
4871 printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
4872 if (!cpu_isset(cpu, group->cpumask))
4873 printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
4876 for (i = 0; i < level + 2; i++)
4882 printk(KERN_ERR "ERROR: group is NULL\n");
4886 if (!group->cpu_power) {
4888 printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
4891 if (!cpus_weight(group->cpumask)) {
4893 printk(KERN_ERR "ERROR: empty group\n");
4896 if (cpus_intersects(groupmask, group->cpumask)) {
4898 printk(KERN_ERR "ERROR: repeated CPUs\n");
4901 cpus_or(groupmask, groupmask, group->cpumask);
4903 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
4906 group = group->next;
4907 } while (group != sd->groups);
4910 if (!cpus_equal(sd->span, groupmask))
4911 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
4917 if (!cpus_subset(groupmask, sd->span))
4918 printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
4924 #define sched_domain_debug(sd, cpu) {}
4927 static int sd_degenerate(struct sched_domain *sd)
4929 if (cpus_weight(sd->span) == 1)
4932 /* Following flags need at least 2 groups */
4933 if (sd->flags & (SD_LOAD_BALANCE |
4934 SD_BALANCE_NEWIDLE |
4937 if (sd->groups != sd->groups->next)
4941 /* Following flags don't use groups */
4942 if (sd->flags & (SD_WAKE_IDLE |
4950 static int sd_parent_degenerate(struct sched_domain *sd,
4951 struct sched_domain *parent)
4953 unsigned long cflags = sd->flags, pflags = parent->flags;
4955 if (sd_degenerate(parent))
4958 if (!cpus_equal(sd->span, parent->span))
4961 /* Does parent contain flags not in child? */
4962 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
4963 if (cflags & SD_WAKE_AFFINE)
4964 pflags &= ~SD_WAKE_BALANCE;
4965 /* Flags needing groups don't count if only 1 group in parent */
4966 if (parent->groups == parent->groups->next) {
4967 pflags &= ~(SD_LOAD_BALANCE |
4968 SD_BALANCE_NEWIDLE |
4972 if (~cflags & pflags)
4979 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
4980 * hold the hotplug lock.
4982 static void cpu_attach_domain(struct sched_domain *sd, int cpu)
4984 runqueue_t *rq = cpu_rq(cpu);
4985 struct sched_domain *tmp;
4987 /* Remove the sched domains which do not contribute to scheduling. */
4988 for (tmp = sd; tmp; tmp = tmp->parent) {
4989 struct sched_domain *parent = tmp->parent;
4992 if (sd_parent_degenerate(tmp, parent))
4993 tmp->parent = parent->parent;
4996 if (sd && sd_degenerate(sd))
4999 sched_domain_debug(sd, cpu);
5001 rcu_assign_pointer(rq->sd, sd);
5004 /* cpus with isolated domains */
5005 static cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
5007 /* Setup the mask of cpus configured for isolated domains */
5008 static int __init isolated_cpu_setup(char *str)
5010 int ints[NR_CPUS], i;
5012 str = get_options(str, ARRAY_SIZE(ints), ints);
5013 cpus_clear(cpu_isolated_map);
5014 for (i = 1; i <= ints[0]; i++)
5015 if (ints[i] < NR_CPUS)
5016 cpu_set(ints[i], cpu_isolated_map);
5020 __setup ("isolcpus=", isolated_cpu_setup);
5023 * init_sched_build_groups takes an array of groups, the cpumask we wish
5024 * to span, and a pointer to a function which identifies what group a CPU
5025 * belongs to. The return value of group_fn must be a valid index into the
5026 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
5027 * keep track of groups covered with a cpumask_t).
5029 * init_sched_build_groups will build a circular linked list of the groups
5030 * covered by the given span, and will set each group's ->cpumask correctly,
5031 * and ->cpu_power to 0.
5033 static void init_sched_build_groups(struct sched_group groups[], cpumask_t span,
5034 int (*group_fn)(int cpu))
5036 struct sched_group *first = NULL, *last = NULL;
5037 cpumask_t covered = CPU_MASK_NONE;
5040 for_each_cpu_mask(i, span) {
5041 int group = group_fn(i);
5042 struct sched_group *sg = &groups[group];
5045 if (cpu_isset(i, covered))
5048 sg->cpumask = CPU_MASK_NONE;
5051 for_each_cpu_mask(j, span) {
5052 if (group_fn(j) != group)
5055 cpu_set(j, covered);
5056 cpu_set(j, sg->cpumask);
5067 #define SD_NODES_PER_DOMAIN 16
5070 * Self-tuning task migration cost measurement between source and target CPUs.
5072 * This is done by measuring the cost of manipulating buffers of varying
5073 * sizes. For a given buffer-size here are the steps that are taken:
5075 * 1) the source CPU reads+dirties a shared buffer
5076 * 2) the target CPU reads+dirties the same shared buffer
5078 * We measure how long they take, in the following 4 scenarios:
5080 * - source: CPU1, target: CPU2 | cost1
5081 * - source: CPU2, target: CPU1 | cost2
5082 * - source: CPU1, target: CPU1 | cost3
5083 * - source: CPU2, target: CPU2 | cost4
5085 * We then calculate the cost3+cost4-cost1-cost2 difference - this is
5086 * the cost of migration.
5088 * We then start off from a small buffer-size and iterate up to larger
5089 * buffer sizes, in 5% steps - measuring each buffer-size separately, and
5090 * doing a maximum search for the cost. (The maximum cost for a migration
5091 * normally occurs when the working set size is around the effective cache
5094 #define SEARCH_SCOPE 2
5095 #define MIN_CACHE_SIZE (64*1024U)
5096 #define DEFAULT_CACHE_SIZE (5*1024*1024U)
5097 #define ITERATIONS 1
5098 #define SIZE_THRESH 130
5099 #define COST_THRESH 130
5102 * The migration cost is a function of 'domain distance'. Domain
5103 * distance is the number of steps a CPU has to iterate down its
5104 * domain tree to share a domain with the other CPU. The farther
5105 * two CPUs are from each other, the larger the distance gets.
5107 * Note that we use the distance only to cache measurement results,
5108 * the distance value is not used numerically otherwise. When two
5109 * CPUs have the same distance it is assumed that the migration
5110 * cost is the same. (this is a simplification but quite practical)
5112 #define MAX_DOMAIN_DISTANCE 32
5114 static unsigned long long migration_cost[MAX_DOMAIN_DISTANCE] =
5115 { [ 0 ... MAX_DOMAIN_DISTANCE-1 ] =
5117 * Architectures may override the migration cost and thus avoid
5118 * boot-time calibration. Unit is nanoseconds. Mostly useful for
5119 * virtualized hardware:
5121 #ifdef CONFIG_DEFAULT_MIGRATION_COST
5122 CONFIG_DEFAULT_MIGRATION_COST
5129 * Allow override of migration cost - in units of microseconds.
5130 * E.g. migration_cost=1000,2000,3000 will set up a level-1 cost
5131 * of 1 msec, level-2 cost of 2 msecs and level3 cost of 3 msecs:
5133 static int __init migration_cost_setup(char *str)
5135 int ints[MAX_DOMAIN_DISTANCE+1], i;
5137 str = get_options(str, ARRAY_SIZE(ints), ints);
5139 printk("#ints: %d\n", ints[0]);
5140 for (i = 1; i <= ints[0]; i++) {
5141 migration_cost[i-1] = (unsigned long long)ints[i]*1000;
5142 printk("migration_cost[%d]: %Ld\n", i-1, migration_cost[i-1]);
5147 __setup ("migration_cost=", migration_cost_setup);
5150 * Global multiplier (divisor) for migration-cutoff values,
5151 * in percentiles. E.g. use a value of 150 to get 1.5 times
5152 * longer cache-hot cutoff times.
5154 * (We scale it from 100 to 128 to long long handling easier.)
5157 #define MIGRATION_FACTOR_SCALE 128
5159 static unsigned int migration_factor = MIGRATION_FACTOR_SCALE;
5161 static int __init setup_migration_factor(char *str)
5163 get_option(&str, &migration_factor);
5164 migration_factor = migration_factor * MIGRATION_FACTOR_SCALE / 100;
5168 __setup("migration_factor=", setup_migration_factor);
5171 * Estimated distance of two CPUs, measured via the number of domains
5172 * we have to pass for the two CPUs to be in the same span:
5174 static unsigned long domain_distance(int cpu1, int cpu2)
5176 unsigned long distance = 0;
5177 struct sched_domain *sd;
5179 for_each_domain(cpu1, sd) {
5180 WARN_ON(!cpu_isset(cpu1, sd->span));
5181 if (cpu_isset(cpu2, sd->span))
5185 if (distance >= MAX_DOMAIN_DISTANCE) {
5187 distance = MAX_DOMAIN_DISTANCE-1;
5193 static unsigned int migration_debug;
5195 static int __init setup_migration_debug(char *str)
5197 get_option(&str, &migration_debug);
5201 __setup("migration_debug=", setup_migration_debug);
5204 * Maximum cache-size that the scheduler should try to measure.
5205 * Architectures with larger caches should tune this up during
5206 * bootup. Gets used in the domain-setup code (i.e. during SMP
5209 unsigned int max_cache_size;
5211 static int __init setup_max_cache_size(char *str)
5213 get_option(&str, &max_cache_size);
5217 __setup("max_cache_size=", setup_max_cache_size);
5220 * Dirty a big buffer in a hard-to-predict (for the L2 cache) way. This
5221 * is the operation that is timed, so we try to generate unpredictable
5222 * cachemisses that still end up filling the L2 cache:
5224 static void touch_cache(void *__cache, unsigned long __size)
5226 unsigned long size = __size/sizeof(long), chunk1 = size/3,
5228 unsigned long *cache = __cache;
5231 for (i = 0; i < size/6; i += 8) {
5234 case 1: cache[size-1-i]++;
5235 case 2: cache[chunk1-i]++;
5236 case 3: cache[chunk1+i]++;
5237 case 4: cache[chunk2-i]++;
5238 case 5: cache[chunk2+i]++;
5244 * Measure the cache-cost of one task migration. Returns in units of nsec.
5246 static unsigned long long measure_one(void *cache, unsigned long size,
5247 int source, int target)
5249 cpumask_t mask, saved_mask;
5250 unsigned long long t0, t1, t2, t3, cost;
5252 saved_mask = current->cpus_allowed;
5255 * Flush source caches to RAM and invalidate them:
5260 * Migrate to the source CPU:
5262 mask = cpumask_of_cpu(source);
5263 set_cpus_allowed(current, mask);
5264 WARN_ON(smp_processor_id() != source);
5267 * Dirty the working set:
5270 touch_cache(cache, size);
5274 * Migrate to the target CPU, dirty the L2 cache and access
5275 * the shared buffer. (which represents the working set
5276 * of a migrated task.)
5278 mask = cpumask_of_cpu(target);
5279 set_cpus_allowed(current, mask);
5280 WARN_ON(smp_processor_id() != target);
5283 touch_cache(cache, size);
5286 cost = t1-t0 + t3-t2;
5288 if (migration_debug >= 2)
5289 printk("[%d->%d]: %8Ld %8Ld %8Ld => %10Ld.\n",
5290 source, target, t1-t0, t1-t0, t3-t2, cost);
5292 * Flush target caches to RAM and invalidate them:
5296 set_cpus_allowed(current, saved_mask);
5302 * Measure a series of task migrations and return the average
5303 * result. Since this code runs early during bootup the system
5304 * is 'undisturbed' and the average latency makes sense.
5306 * The algorithm in essence auto-detects the relevant cache-size,
5307 * so it will properly detect different cachesizes for different
5308 * cache-hierarchies, depending on how the CPUs are connected.
5310 * Architectures can prime the upper limit of the search range via
5311 * max_cache_size, otherwise the search range defaults to 20MB...64K.
5313 static unsigned long long
5314 measure_cost(int cpu1, int cpu2, void *cache, unsigned int size)
5316 unsigned long long cost1, cost2;
5320 * Measure the migration cost of 'size' bytes, over an
5321 * average of 10 runs:
5323 * (We perturb the cache size by a small (0..4k)
5324 * value to compensate size/alignment related artifacts.
5325 * We also subtract the cost of the operation done on
5331 * dry run, to make sure we start off cache-cold on cpu1,
5332 * and to get any vmalloc pagefaults in advance:
5334 measure_one(cache, size, cpu1, cpu2);
5335 for (i = 0; i < ITERATIONS; i++)
5336 cost1 += measure_one(cache, size - i*1024, cpu1, cpu2);
5338 measure_one(cache, size, cpu2, cpu1);
5339 for (i = 0; i < ITERATIONS; i++)
5340 cost1 += measure_one(cache, size - i*1024, cpu2, cpu1);
5343 * (We measure the non-migrating [cached] cost on both
5344 * cpu1 and cpu2, to handle CPUs with different speeds)
5348 measure_one(cache, size, cpu1, cpu1);
5349 for (i = 0; i < ITERATIONS; i++)
5350 cost2 += measure_one(cache, size - i*1024, cpu1, cpu1);
5352 measure_one(cache, size, cpu2, cpu2);
5353 for (i = 0; i < ITERATIONS; i++)
5354 cost2 += measure_one(cache, size - i*1024, cpu2, cpu2);
5357 * Get the per-iteration migration cost:
5359 do_div(cost1, 2*ITERATIONS);
5360 do_div(cost2, 2*ITERATIONS);
5362 return cost1 - cost2;
5365 static unsigned long long measure_migration_cost(int cpu1, int cpu2)
5367 unsigned long long max_cost = 0, fluct = 0, avg_fluct = 0;
5368 unsigned int max_size, size, size_found = 0;
5369 long long cost = 0, prev_cost;
5373 * Search from max_cache_size*5 down to 64K - the real relevant
5374 * cachesize has to lie somewhere inbetween.
5376 if (max_cache_size) {
5377 max_size = max(max_cache_size * SEARCH_SCOPE, MIN_CACHE_SIZE);
5378 size = max(max_cache_size / SEARCH_SCOPE, MIN_CACHE_SIZE);
5381 * Since we have no estimation about the relevant
5384 max_size = DEFAULT_CACHE_SIZE * SEARCH_SCOPE;
5385 size = MIN_CACHE_SIZE;
5388 if (!cpu_online(cpu1) || !cpu_online(cpu2)) {
5389 printk("cpu %d and %d not both online!\n", cpu1, cpu2);
5394 * Allocate the working set:
5396 cache = vmalloc(max_size);
5398 printk("could not vmalloc %d bytes for cache!\n", 2*max_size);
5399 return 1000000; // return 1 msec on very small boxen
5402 while (size <= max_size) {
5404 cost = measure_cost(cpu1, cpu2, cache, size);
5410 if (max_cost < cost) {
5416 * Calculate average fluctuation, we use this to prevent
5417 * noise from triggering an early break out of the loop:
5419 fluct = abs(cost - prev_cost);
5420 avg_fluct = (avg_fluct + fluct)/2;
5422 if (migration_debug)
5423 printk("-> [%d][%d][%7d] %3ld.%ld [%3ld.%ld] (%ld): (%8Ld %8Ld)\n",
5425 (long)cost / 1000000,
5426 ((long)cost / 100000) % 10,
5427 (long)max_cost / 1000000,
5428 ((long)max_cost / 100000) % 10,
5429 domain_distance(cpu1, cpu2),
5433 * If we iterated at least 20% past the previous maximum,
5434 * and the cost has dropped by more than 20% already,
5435 * (taking fluctuations into account) then we assume to
5436 * have found the maximum and break out of the loop early:
5438 if (size_found && (size*100 > size_found*SIZE_THRESH))
5439 if (cost+avg_fluct <= 0 ||
5440 max_cost*100 > (cost+avg_fluct)*COST_THRESH) {
5442 if (migration_debug)
5443 printk("-> found max.\n");
5447 * Increase the cachesize in 10% steps:
5449 size = size * 10 / 9;
5452 if (migration_debug)
5453 printk("[%d][%d] working set size found: %d, cost: %Ld\n",
5454 cpu1, cpu2, size_found, max_cost);
5459 * A task is considered 'cache cold' if at least 2 times
5460 * the worst-case cost of migration has passed.
5462 * (this limit is only listened to if the load-balancing
5463 * situation is 'nice' - if there is a large imbalance we
5464 * ignore it for the sake of CPU utilization and
5465 * processing fairness.)
5467 return 2 * max_cost * migration_factor / MIGRATION_FACTOR_SCALE;
5470 static void calibrate_migration_costs(const cpumask_t *cpu_map)
5472 int cpu1 = -1, cpu2 = -1, cpu, orig_cpu = raw_smp_processor_id();
5473 unsigned long j0, j1, distance, max_distance = 0;
5474 struct sched_domain *sd;
5479 * First pass - calculate the cacheflush times:
5481 for_each_cpu_mask(cpu1, *cpu_map) {
5482 for_each_cpu_mask(cpu2, *cpu_map) {
5485 distance = domain_distance(cpu1, cpu2);
5486 max_distance = max(max_distance, distance);
5488 * No result cached yet?
5490 if (migration_cost[distance] == -1LL)
5491 migration_cost[distance] =
5492 measure_migration_cost(cpu1, cpu2);
5496 * Second pass - update the sched domain hierarchy with
5497 * the new cache-hot-time estimations:
5499 for_each_cpu_mask(cpu, *cpu_map) {
5501 for_each_domain(cpu, sd) {
5502 sd->cache_hot_time = migration_cost[distance];
5509 if (migration_debug)
5510 printk("migration: max_cache_size: %d, cpu: %d MHz:\n",
5518 if (system_state == SYSTEM_BOOTING) {
5519 printk("migration_cost=");
5520 for (distance = 0; distance <= max_distance; distance++) {
5523 printk("%ld", (long)migration_cost[distance] / 1000);
5528 if (migration_debug)
5529 printk("migration: %ld seconds\n", (j1-j0)/HZ);
5532 * Move back to the original CPU. NUMA-Q gets confused
5533 * if we migrate to another quad during bootup.
5535 if (raw_smp_processor_id() != orig_cpu) {
5536 cpumask_t mask = cpumask_of_cpu(orig_cpu),
5537 saved_mask = current->cpus_allowed;
5539 set_cpus_allowed(current, mask);
5540 set_cpus_allowed(current, saved_mask);
5547 * find_next_best_node - find the next node to include in a sched_domain
5548 * @node: node whose sched_domain we're building
5549 * @used_nodes: nodes already in the sched_domain
5551 * Find the next node to include in a given scheduling domain. Simply
5552 * finds the closest node not already in the @used_nodes map.
5554 * Should use nodemask_t.
5556 static int find_next_best_node(int node, unsigned long *used_nodes)
5558 int i, n, val, min_val, best_node = 0;
5562 for (i = 0; i < MAX_NUMNODES; i++) {
5563 /* Start at @node */
5564 n = (node + i) % MAX_NUMNODES;
5566 if (!nr_cpus_node(n))
5569 /* Skip already used nodes */
5570 if (test_bit(n, used_nodes))
5573 /* Simple min distance search */
5574 val = node_distance(node, n);
5576 if (val < min_val) {
5582 set_bit(best_node, used_nodes);
5587 * sched_domain_node_span - get a cpumask for a node's sched_domain
5588 * @node: node whose cpumask we're constructing
5589 * @size: number of nodes to include in this span
5591 * Given a node, construct a good cpumask for its sched_domain to span. It
5592 * should be one that prevents unnecessary balancing, but also spreads tasks
5595 static cpumask_t sched_domain_node_span(int node)
5598 cpumask_t span, nodemask;
5599 DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
5602 bitmap_zero(used_nodes, MAX_NUMNODES);
5604 nodemask = node_to_cpumask(node);
5605 cpus_or(span, span, nodemask);
5606 set_bit(node, used_nodes);
5608 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
5609 int next_node = find_next_best_node(node, used_nodes);
5610 nodemask = node_to_cpumask(next_node);
5611 cpus_or(span, span, nodemask);
5619 * At the moment, CONFIG_SCHED_SMT is never defined, but leave it in so we
5620 * can switch it on easily if needed.
5622 #ifdef CONFIG_SCHED_SMT
5623 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
5624 static struct sched_group sched_group_cpus[NR_CPUS];
5625 static int cpu_to_cpu_group(int cpu)
5631 #ifdef CONFIG_SCHED_MC
5632 static DEFINE_PER_CPU(struct sched_domain, core_domains);
5633 static struct sched_group sched_group_core[NR_CPUS];
5636 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
5637 static int cpu_to_core_group(int cpu)
5639 return first_cpu(cpu_sibling_map[cpu]);
5641 #elif defined(CONFIG_SCHED_MC)
5642 static int cpu_to_core_group(int cpu)
5648 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
5649 static struct sched_group sched_group_phys[NR_CPUS];
5650 static int cpu_to_phys_group(int cpu)
5652 #if defined(CONFIG_SCHED_MC)
5653 cpumask_t mask = cpu_coregroup_map(cpu);
5654 return first_cpu(mask);
5655 #elif defined(CONFIG_SCHED_SMT)
5656 return first_cpu(cpu_sibling_map[cpu]);
5664 * The init_sched_build_groups can't handle what we want to do with node
5665 * groups, so roll our own. Now each node has its own list of groups which
5666 * gets dynamically allocated.
5668 static DEFINE_PER_CPU(struct sched_domain, node_domains);
5669 static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
5671 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
5672 static struct sched_group *sched_group_allnodes_bycpu[NR_CPUS];
5674 static int cpu_to_allnodes_group(int cpu)
5676 return cpu_to_node(cpu);
5678 static void init_numa_sched_groups_power(struct sched_group *group_head)
5680 struct sched_group *sg = group_head;
5686 for_each_cpu_mask(j, sg->cpumask) {
5687 struct sched_domain *sd;
5689 sd = &per_cpu(phys_domains, j);
5690 if (j != first_cpu(sd->groups->cpumask)) {
5692 * Only add "power" once for each
5698 sg->cpu_power += sd->groups->cpu_power;
5701 if (sg != group_head)
5707 * Build sched domains for a given set of cpus and attach the sched domains
5708 * to the individual cpus
5710 void build_sched_domains(const cpumask_t *cpu_map)
5714 struct sched_group **sched_group_nodes = NULL;
5715 struct sched_group *sched_group_allnodes = NULL;
5718 * Allocate the per-node list of sched groups
5720 sched_group_nodes = kmalloc(sizeof(struct sched_group*)*MAX_NUMNODES,
5722 if (!sched_group_nodes) {
5723 printk(KERN_WARNING "Can not alloc sched group node list\n");
5726 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
5730 * Set up domains for cpus specified by the cpu_map.
5732 for_each_cpu_mask(i, *cpu_map) {
5734 struct sched_domain *sd = NULL, *p;
5735 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
5737 cpus_and(nodemask, nodemask, *cpu_map);
5740 if (cpus_weight(*cpu_map)
5741 > SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
5742 if (!sched_group_allnodes) {
5743 sched_group_allnodes
5744 = kmalloc(sizeof(struct sched_group)
5747 if (!sched_group_allnodes) {
5749 "Can not alloc allnodes sched group\n");
5752 sched_group_allnodes_bycpu[i]
5753 = sched_group_allnodes;
5755 sd = &per_cpu(allnodes_domains, i);
5756 *sd = SD_ALLNODES_INIT;
5757 sd->span = *cpu_map;
5758 group = cpu_to_allnodes_group(i);
5759 sd->groups = &sched_group_allnodes[group];
5764 sd = &per_cpu(node_domains, i);
5766 sd->span = sched_domain_node_span(cpu_to_node(i));
5768 cpus_and(sd->span, sd->span, *cpu_map);
5772 sd = &per_cpu(phys_domains, i);
5773 group = cpu_to_phys_group(i);
5775 sd->span = nodemask;
5777 sd->groups = &sched_group_phys[group];
5779 #ifdef CONFIG_SCHED_MC
5781 sd = &per_cpu(core_domains, i);
5782 group = cpu_to_core_group(i);
5784 sd->span = cpu_coregroup_map(i);
5785 cpus_and(sd->span, sd->span, *cpu_map);
5787 sd->groups = &sched_group_core[group];
5790 #ifdef CONFIG_SCHED_SMT
5792 sd = &per_cpu(cpu_domains, i);
5793 group = cpu_to_cpu_group(i);
5794 *sd = SD_SIBLING_INIT;
5795 sd->span = cpu_sibling_map[i];
5796 cpus_and(sd->span, sd->span, *cpu_map);
5798 sd->groups = &sched_group_cpus[group];
5802 #ifdef CONFIG_SCHED_SMT
5803 /* Set up CPU (sibling) groups */
5804 for_each_cpu_mask(i, *cpu_map) {
5805 cpumask_t this_sibling_map = cpu_sibling_map[i];
5806 cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
5807 if (i != first_cpu(this_sibling_map))
5810 init_sched_build_groups(sched_group_cpus, this_sibling_map,
5815 #ifdef CONFIG_SCHED_MC
5816 /* Set up multi-core groups */
5817 for_each_cpu_mask(i, *cpu_map) {
5818 cpumask_t this_core_map = cpu_coregroup_map(i);
5819 cpus_and(this_core_map, this_core_map, *cpu_map);
5820 if (i != first_cpu(this_core_map))
5822 init_sched_build_groups(sched_group_core, this_core_map,
5823 &cpu_to_core_group);
5828 /* Set up physical groups */
5829 for (i = 0; i < MAX_NUMNODES; i++) {
5830 cpumask_t nodemask = node_to_cpumask(i);
5832 cpus_and(nodemask, nodemask, *cpu_map);
5833 if (cpus_empty(nodemask))
5836 init_sched_build_groups(sched_group_phys, nodemask,
5837 &cpu_to_phys_group);
5841 /* Set up node groups */
5842 if (sched_group_allnodes)
5843 init_sched_build_groups(sched_group_allnodes, *cpu_map,
5844 &cpu_to_allnodes_group);
5846 for (i = 0; i < MAX_NUMNODES; i++) {
5847 /* Set up node groups */
5848 struct sched_group *sg, *prev;
5849 cpumask_t nodemask = node_to_cpumask(i);
5850 cpumask_t domainspan;
5851 cpumask_t covered = CPU_MASK_NONE;
5854 cpus_and(nodemask, nodemask, *cpu_map);
5855 if (cpus_empty(nodemask)) {
5856 sched_group_nodes[i] = NULL;
5860 domainspan = sched_domain_node_span(i);
5861 cpus_and(domainspan, domainspan, *cpu_map);
5863 sg = kmalloc(sizeof(struct sched_group), GFP_KERNEL);
5864 sched_group_nodes[i] = sg;
5865 for_each_cpu_mask(j, nodemask) {
5866 struct sched_domain *sd;
5867 sd = &per_cpu(node_domains, j);
5869 if (sd->groups == NULL) {
5870 /* Turn off balancing if we have no groups */
5876 "Can not alloc domain group for node %d\n", i);
5880 sg->cpumask = nodemask;
5881 cpus_or(covered, covered, nodemask);
5884 for (j = 0; j < MAX_NUMNODES; j++) {
5885 cpumask_t tmp, notcovered;
5886 int n = (i + j) % MAX_NUMNODES;
5888 cpus_complement(notcovered, covered);
5889 cpus_and(tmp, notcovered, *cpu_map);
5890 cpus_and(tmp, tmp, domainspan);
5891 if (cpus_empty(tmp))
5894 nodemask = node_to_cpumask(n);
5895 cpus_and(tmp, tmp, nodemask);
5896 if (cpus_empty(tmp))
5899 sg = kmalloc(sizeof(struct sched_group), GFP_KERNEL);
5902 "Can not alloc domain group for node %d\n", j);
5907 cpus_or(covered, covered, tmp);
5911 prev->next = sched_group_nodes[i];
5915 /* Calculate CPU power for physical packages and nodes */
5916 for_each_cpu_mask(i, *cpu_map) {
5918 struct sched_domain *sd;
5919 #ifdef CONFIG_SCHED_SMT
5920 sd = &per_cpu(cpu_domains, i);
5921 power = SCHED_LOAD_SCALE;
5922 sd->groups->cpu_power = power;
5924 #ifdef CONFIG_SCHED_MC
5925 sd = &per_cpu(core_domains, i);
5926 power = SCHED_LOAD_SCALE + (cpus_weight(sd->groups->cpumask)-1)
5927 * SCHED_LOAD_SCALE / 10;
5928 sd->groups->cpu_power = power;
5930 sd = &per_cpu(phys_domains, i);
5933 * This has to be < 2 * SCHED_LOAD_SCALE
5934 * Lets keep it SCHED_LOAD_SCALE, so that
5935 * while calculating NUMA group's cpu_power
5937 * numa_group->cpu_power += phys_group->cpu_power;
5939 * See "only add power once for each physical pkg"
5942 sd->groups->cpu_power = SCHED_LOAD_SCALE;
5944 sd = &per_cpu(phys_domains, i);
5945 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
5946 (cpus_weight(sd->groups->cpumask)-1) / 10;
5947 sd->groups->cpu_power = power;
5952 for (i = 0; i < MAX_NUMNODES; i++)
5953 init_numa_sched_groups_power(sched_group_nodes[i]);
5955 init_numa_sched_groups_power(sched_group_allnodes);
5958 /* Attach the domains */
5959 for_each_cpu_mask(i, *cpu_map) {
5960 struct sched_domain *sd;
5961 #ifdef CONFIG_SCHED_SMT
5962 sd = &per_cpu(cpu_domains, i);
5963 #elif defined(CONFIG_SCHED_MC)
5964 sd = &per_cpu(core_domains, i);
5966 sd = &per_cpu(phys_domains, i);
5968 cpu_attach_domain(sd, i);
5971 * Tune cache-hot values:
5973 calibrate_migration_costs(cpu_map);
5976 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
5978 static void arch_init_sched_domains(const cpumask_t *cpu_map)
5980 cpumask_t cpu_default_map;
5983 * Setup mask for cpus without special case scheduling requirements.
5984 * For now this just excludes isolated cpus, but could be used to
5985 * exclude other special cases in the future.
5987 cpus_andnot(cpu_default_map, *cpu_map, cpu_isolated_map);
5989 build_sched_domains(&cpu_default_map);
5992 static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
5998 for_each_cpu_mask(cpu, *cpu_map) {
5999 struct sched_group *sched_group_allnodes
6000 = sched_group_allnodes_bycpu[cpu];
6001 struct sched_group **sched_group_nodes
6002 = sched_group_nodes_bycpu[cpu];
6004 if (sched_group_allnodes) {
6005 kfree(sched_group_allnodes);
6006 sched_group_allnodes_bycpu[cpu] = NULL;
6009 if (!sched_group_nodes)
6012 for (i = 0; i < MAX_NUMNODES; i++) {
6013 cpumask_t nodemask = node_to_cpumask(i);
6014 struct sched_group *oldsg, *sg = sched_group_nodes[i];
6016 cpus_and(nodemask, nodemask, *cpu_map);
6017 if (cpus_empty(nodemask))
6027 if (oldsg != sched_group_nodes[i])
6030 kfree(sched_group_nodes);
6031 sched_group_nodes_bycpu[cpu] = NULL;
6037 * Detach sched domains from a group of cpus specified in cpu_map
6038 * These cpus will now be attached to the NULL domain
6040 static void detach_destroy_domains(const cpumask_t *cpu_map)
6044 for_each_cpu_mask(i, *cpu_map)
6045 cpu_attach_domain(NULL, i);
6046 synchronize_sched();
6047 arch_destroy_sched_domains(cpu_map);
6051 * Partition sched domains as specified by the cpumasks below.
6052 * This attaches all cpus from the cpumasks to the NULL domain,
6053 * waits for a RCU quiescent period, recalculates sched
6054 * domain information and then attaches them back to the
6055 * correct sched domains
6056 * Call with hotplug lock held
6058 void partition_sched_domains(cpumask_t *partition1, cpumask_t *partition2)
6060 cpumask_t change_map;
6062 cpus_and(*partition1, *partition1, cpu_online_map);
6063 cpus_and(*partition2, *partition2, cpu_online_map);
6064 cpus_or(change_map, *partition1, *partition2);
6066 /* Detach sched domains from all of the affected cpus */
6067 detach_destroy_domains(&change_map);
6068 if (!cpus_empty(*partition1))
6069 build_sched_domains(partition1);
6070 if (!cpus_empty(*partition2))
6071 build_sched_domains(partition2);
6074 #ifdef CONFIG_HOTPLUG_CPU
6076 * Force a reinitialization of the sched domains hierarchy. The domains
6077 * and groups cannot be updated in place without racing with the balancing
6078 * code, so we temporarily attach all running cpus to the NULL domain
6079 * which will prevent rebalancing while the sched domains are recalculated.
6081 static int update_sched_domains(struct notifier_block *nfb,
6082 unsigned long action, void *hcpu)
6085 case CPU_UP_PREPARE:
6086 case CPU_DOWN_PREPARE:
6087 detach_destroy_domains(&cpu_online_map);
6090 case CPU_UP_CANCELED:
6091 case CPU_DOWN_FAILED:
6095 * Fall through and re-initialise the domains.
6102 /* The hotplug lock is already held by cpu_up/cpu_down */
6103 arch_init_sched_domains(&cpu_online_map);
6109 void __init sched_init_smp(void)
6112 arch_init_sched_domains(&cpu_online_map);
6113 unlock_cpu_hotplug();
6114 /* XXX: Theoretical race here - CPU may be hotplugged now */
6115 hotcpu_notifier(update_sched_domains, 0);
6118 void __init sched_init_smp(void)
6121 #endif /* CONFIG_SMP */
6123 int in_sched_functions(unsigned long addr)
6125 /* Linker adds these: start and end of __sched functions */
6126 extern char __sched_text_start[], __sched_text_end[];
6127 return in_lock_functions(addr) ||
6128 (addr >= (unsigned long)__sched_text_start
6129 && addr < (unsigned long)__sched_text_end);
6132 void __init sched_init(void)
6137 for_each_possible_cpu(i) {
6138 prio_array_t *array;
6141 spin_lock_init(&rq->lock);
6143 rq->active = rq->arrays;
6144 rq->expired = rq->arrays + 1;
6145 rq->best_expired_prio = MAX_PRIO;
6149 for (j = 1; j < 3; j++)
6150 rq->cpu_load[j] = 0;
6151 rq->active_balance = 0;
6153 rq->migration_thread = NULL;
6154 INIT_LIST_HEAD(&rq->migration_queue);
6157 atomic_set(&rq->nr_iowait, 0);
6159 for (j = 0; j < 2; j++) {
6160 array = rq->arrays + j;
6161 for (k = 0; k < MAX_PRIO; k++) {
6162 INIT_LIST_HEAD(array->queue + k);
6163 __clear_bit(k, array->bitmap);
6165 // delimiter for bitsearch
6166 __set_bit(MAX_PRIO, array->bitmap);
6171 * The boot idle thread does lazy MMU switching as well:
6173 atomic_inc(&init_mm.mm_count);
6174 enter_lazy_tlb(&init_mm, current);
6177 * Make us the idle thread. Technically, schedule() should not be
6178 * called from this thread, however somewhere below it might be,
6179 * but because we are the idle thread, we just pick up running again
6180 * when this runqueue becomes "idle".
6182 init_idle(current, smp_processor_id());
6185 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
6186 void __might_sleep(char *file, int line)
6188 #if defined(in_atomic)
6189 static unsigned long prev_jiffy; /* ratelimiting */
6191 if ((in_atomic() || irqs_disabled()) &&
6192 system_state == SYSTEM_RUNNING && !oops_in_progress) {
6193 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6195 prev_jiffy = jiffies;
6196 printk(KERN_ERR "BUG: sleeping function called from invalid"
6197 " context at %s:%d\n", file, line);
6198 printk("in_atomic():%d, irqs_disabled():%d\n",
6199 in_atomic(), irqs_disabled());
6204 EXPORT_SYMBOL(__might_sleep);
6207 #ifdef CONFIG_MAGIC_SYSRQ
6208 void normalize_rt_tasks(void)
6210 struct task_struct *p;
6211 prio_array_t *array;
6212 unsigned long flags;
6215 read_lock_irq(&tasklist_lock);
6216 for_each_process (p) {
6220 rq = task_rq_lock(p, &flags);
6224 deactivate_task(p, task_rq(p));
6225 __setscheduler(p, SCHED_NORMAL, 0);
6227 __activate_task(p, task_rq(p));
6228 resched_task(rq->curr);
6231 task_rq_unlock(rq, &flags);
6233 read_unlock_irq(&tasklist_lock);
6236 #endif /* CONFIG_MAGIC_SYSRQ */
6240 * These functions are only useful for the IA64 MCA handling.
6242 * They can only be called when the whole system has been
6243 * stopped - every CPU needs to be quiescent, and no scheduling
6244 * activity can take place. Using them for anything else would
6245 * be a serious bug, and as a result, they aren't even visible
6246 * under any other configuration.
6250 * curr_task - return the current task for a given cpu.
6251 * @cpu: the processor in question.
6253 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6255 task_t *curr_task(int cpu)
6257 return cpu_curr(cpu);
6261 * set_curr_task - set the current task for a given cpu.
6262 * @cpu: the processor in question.
6263 * @p: the task pointer to set.
6265 * Description: This function must only be used when non-maskable interrupts
6266 * are serviced on a separate stack. It allows the architecture to switch the
6267 * notion of the current task on a cpu in a non-blocking manner. This function
6268 * must be called with all CPU's synchronized, and interrupts disabled, the
6269 * and caller must save the original value of the current task (see
6270 * curr_task() above) and restore that value before reenabling interrupts and
6271 * re-starting the system.
6273 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6275 void set_curr_task(int cpu, task_t *p)