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>
57 #include <linux/vs_context.h>
58 #include <linux/vs_cvirt.h>
59 #include <linux/vs_sched.h>
62 * Convert user-nice values [ -20 ... 0 ... 19 ]
63 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
66 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
67 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
68 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
71 * 'User priority' is the nice value converted to something we
72 * can work with better when scaling various scheduler parameters,
73 * it's a [ 0 ... 39 ] range.
75 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
76 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
77 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
80 * Some helpers for converting nanosecond timing to jiffy resolution
82 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
83 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
86 * These are the 'tuning knobs' of the scheduler:
88 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
89 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
90 * Timeslices get refilled after they expire.
92 #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
93 #define DEF_TIMESLICE (100 * HZ / 1000)
94 #define ON_RUNQUEUE_WEIGHT 30
95 #define CHILD_PENALTY 95
96 #define PARENT_PENALTY 100
98 #define PRIO_BONUS_RATIO 25
99 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
100 #define INTERACTIVE_DELTA 2
101 #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
102 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
103 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
106 * If a task is 'interactive' then we reinsert it in the active
107 * array after it has expired its current timeslice. (it will not
108 * continue to run immediately, it will still roundrobin with
109 * other interactive tasks.)
111 * This part scales the interactivity limit depending on niceness.
113 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
114 * Here are a few examples of different nice levels:
116 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
117 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
118 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
119 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
120 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
122 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
123 * priority range a task can explore, a value of '1' means the
124 * task is rated interactive.)
126 * Ie. nice +19 tasks can never get 'interactive' enough to be
127 * reinserted into the active array. And only heavily CPU-hog nice -20
128 * tasks will be expired. Default nice 0 tasks are somewhere between,
129 * it takes some effort for them to get interactive, but it's not
133 #define CURRENT_BONUS(p) \
134 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
137 #define GRANULARITY (10 * HZ / 1000 ? : 1)
140 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
141 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
144 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
145 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
148 #define SCALE(v1,v1_max,v2_max) \
149 (v1) * (v2_max) / (v1_max)
152 (SCALE(TASK_NICE(p) + 20, 40, MAX_BONUS) - 20 * MAX_BONUS / 40 + \
155 #define TASK_INTERACTIVE(p) \
156 ((p)->prio <= (p)->static_prio - DELTA(p))
158 #define INTERACTIVE_SLEEP(p) \
159 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
160 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
162 #define TASK_PREEMPTS_CURR(p, rq) \
163 ((p)->prio < (rq)->curr->prio)
166 * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
167 * to time slice values: [800ms ... 100ms ... 5ms]
169 * The higher a thread's priority, the bigger timeslices
170 * it gets during one round of execution. But even the lowest
171 * priority thread gets MIN_TIMESLICE worth of execution time.
174 #define SCALE_PRIO(x, prio) \
175 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO/2), MIN_TIMESLICE)
177 static unsigned int task_timeslice(task_t *p)
179 if (p->static_prio < NICE_TO_PRIO(0))
180 return SCALE_PRIO(DEF_TIMESLICE*4, p->static_prio);
182 return SCALE_PRIO(DEF_TIMESLICE, p->static_prio);
184 #define task_hot(p, now, sd) ((long long) ((now) - (p)->last_ran) \
185 < (long long) (sd)->cache_hot_time)
188 * These are the runqueue data structures:
191 #define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
193 typedef struct runqueue runqueue_t;
196 unsigned int nr_active;
197 unsigned long bitmap[BITMAP_SIZE];
198 struct list_head queue[MAX_PRIO];
202 * This is the main, per-CPU runqueue data structure.
204 * Locking rule: those places that want to lock multiple runqueues
205 * (such as the load balancing or the thread migration code), lock
206 * acquire operations must be ordered by ascending &runqueue.
212 * nr_running and cpu_load should be in the same cacheline because
213 * remote CPUs use both these fields when doing load calculation.
215 unsigned long nr_running;
217 unsigned long cpu_load[3];
219 unsigned long long nr_switches;
222 * This is part of a global counter where only the total sum
223 * over all CPUs matters. A task can increase this counter on
224 * one CPU and if it got migrated afterwards it may decrease
225 * it on another CPU. Always updated under the runqueue lock:
227 unsigned long nr_uninterruptible;
229 unsigned long expired_timestamp;
230 unsigned long long timestamp_last_tick;
232 struct mm_struct *prev_mm;
233 prio_array_t *active, *expired, arrays[2];
234 int best_expired_prio;
238 struct sched_domain *sd;
240 /* For active balancing */
244 task_t *migration_thread;
245 struct list_head migration_queue;
248 #ifdef CONFIG_VSERVER_HARDCPU
249 struct list_head hold_queue;
253 #ifdef CONFIG_SCHEDSTATS
255 struct sched_info rq_sched_info;
257 /* sys_sched_yield() stats */
258 unsigned long yld_exp_empty;
259 unsigned long yld_act_empty;
260 unsigned long yld_both_empty;
261 unsigned long yld_cnt;
263 /* schedule() stats */
264 unsigned long sched_switch;
265 unsigned long sched_cnt;
266 unsigned long sched_goidle;
268 /* try_to_wake_up() stats */
269 unsigned long ttwu_cnt;
270 unsigned long ttwu_local;
274 static DEFINE_PER_CPU(struct runqueue, runqueues);
277 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
278 * See detach_destroy_domains: synchronize_sched for details.
280 * The domain tree of any CPU may only be accessed from within
281 * preempt-disabled sections.
283 #define for_each_domain(cpu, domain) \
284 for (domain = rcu_dereference(cpu_rq(cpu)->sd); domain; domain = domain->parent)
286 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
287 #define this_rq() (&__get_cpu_var(runqueues))
288 #define task_rq(p) cpu_rq(task_cpu(p))
289 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
291 #ifndef prepare_arch_switch
292 # define prepare_arch_switch(next) do { } while (0)
294 #ifndef finish_arch_switch
295 # define finish_arch_switch(prev) do { } while (0)
298 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
299 static inline int task_running(runqueue_t *rq, task_t *p)
301 return rq->curr == p;
304 static inline void prepare_lock_switch(runqueue_t *rq, task_t *next)
308 static inline void finish_lock_switch(runqueue_t *rq, task_t *prev)
310 #ifdef CONFIG_DEBUG_SPINLOCK
311 /* this is a valid case when another task releases the spinlock */
312 rq->lock.owner = current;
314 spin_unlock_irq(&rq->lock);
317 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
318 static inline int task_running(runqueue_t *rq, task_t *p)
323 return rq->curr == p;
327 static inline void prepare_lock_switch(runqueue_t *rq, task_t *next)
331 * We can optimise this out completely for !SMP, because the
332 * SMP rebalancing from interrupt is the only thing that cares
337 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
338 spin_unlock_irq(&rq->lock);
340 spin_unlock(&rq->lock);
344 static inline void finish_lock_switch(runqueue_t *rq, task_t *prev)
348 * After ->oncpu is cleared, the task can be moved to a different CPU.
349 * We must ensure this doesn't happen until the switch is completely
355 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
359 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
362 * task_rq_lock - lock the runqueue a given task resides on and disable
363 * interrupts. Note the ordering: we can safely lookup the task_rq without
364 * explicitly disabling preemption.
366 static inline runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
372 local_irq_save(*flags);
374 spin_lock(&rq->lock);
375 if (unlikely(rq != task_rq(p))) {
376 spin_unlock_irqrestore(&rq->lock, *flags);
377 goto repeat_lock_task;
382 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
385 spin_unlock_irqrestore(&rq->lock, *flags);
388 #ifdef CONFIG_SCHEDSTATS
390 * bump this up when changing the output format or the meaning of an existing
391 * format, so that tools can adapt (or abort)
393 #define SCHEDSTAT_VERSION 12
395 static int show_schedstat(struct seq_file *seq, void *v)
399 seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
400 seq_printf(seq, "timestamp %lu\n", jiffies);
401 for_each_online_cpu(cpu) {
402 runqueue_t *rq = cpu_rq(cpu);
404 struct sched_domain *sd;
408 /* runqueue-specific stats */
410 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
411 cpu, rq->yld_both_empty,
412 rq->yld_act_empty, rq->yld_exp_empty, rq->yld_cnt,
413 rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
414 rq->ttwu_cnt, rq->ttwu_local,
415 rq->rq_sched_info.cpu_time,
416 rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
418 seq_printf(seq, "\n");
421 /* domain-specific stats */
423 for_each_domain(cpu, sd) {
424 enum idle_type itype;
425 char mask_str[NR_CPUS];
427 cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
428 seq_printf(seq, "domain%d %s", dcnt++, mask_str);
429 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
431 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu",
433 sd->lb_balanced[itype],
434 sd->lb_failed[itype],
435 sd->lb_imbalance[itype],
436 sd->lb_gained[itype],
437 sd->lb_hot_gained[itype],
438 sd->lb_nobusyq[itype],
439 sd->lb_nobusyg[itype]);
441 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
442 sd->alb_cnt, sd->alb_failed, sd->alb_pushed,
443 sd->sbe_cnt, sd->sbe_balanced, sd->sbe_pushed,
444 sd->sbf_cnt, sd->sbf_balanced, sd->sbf_pushed,
445 sd->ttwu_wake_remote, sd->ttwu_move_affine, sd->ttwu_move_balance);
453 static int schedstat_open(struct inode *inode, struct file *file)
455 unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
456 char *buf = kmalloc(size, GFP_KERNEL);
462 res = single_open(file, show_schedstat, NULL);
464 m = file->private_data;
472 struct file_operations proc_schedstat_operations = {
473 .open = schedstat_open,
476 .release = single_release,
479 # define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
480 # define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
481 #else /* !CONFIG_SCHEDSTATS */
482 # define schedstat_inc(rq, field) do { } while (0)
483 # define schedstat_add(rq, field, amt) do { } while (0)
487 * rq_lock - lock a given runqueue and disable interrupts.
489 static inline runqueue_t *this_rq_lock(void)
496 spin_lock(&rq->lock);
501 #ifdef CONFIG_SCHEDSTATS
503 * Called when a process is dequeued from the active array and given
504 * the cpu. We should note that with the exception of interactive
505 * tasks, the expired queue will become the active queue after the active
506 * queue is empty, without explicitly dequeuing and requeuing tasks in the
507 * expired queue. (Interactive tasks may be requeued directly to the
508 * active queue, thus delaying tasks in the expired queue from running;
509 * see scheduler_tick()).
511 * This function is only called from sched_info_arrive(), rather than
512 * dequeue_task(). Even though a task may be queued and dequeued multiple
513 * times as it is shuffled about, we're really interested in knowing how
514 * long it was from the *first* time it was queued to the time that it
517 static inline void sched_info_dequeued(task_t *t)
519 t->sched_info.last_queued = 0;
523 * Called when a task finally hits the cpu. We can now calculate how
524 * long it was waiting to run. We also note when it began so that we
525 * can keep stats on how long its timeslice is.
527 static void sched_info_arrive(task_t *t)
529 unsigned long now = jiffies, diff = 0;
530 struct runqueue *rq = task_rq(t);
532 if (t->sched_info.last_queued)
533 diff = now - t->sched_info.last_queued;
534 sched_info_dequeued(t);
535 t->sched_info.run_delay += diff;
536 t->sched_info.last_arrival = now;
537 t->sched_info.pcnt++;
542 rq->rq_sched_info.run_delay += diff;
543 rq->rq_sched_info.pcnt++;
547 * Called when a process is queued into either the active or expired
548 * array. The time is noted and later used to determine how long we
549 * had to wait for us to reach the cpu. Since the expired queue will
550 * become the active queue after active queue is empty, without dequeuing
551 * and requeuing any tasks, we are interested in queuing to either. It
552 * is unusual but not impossible for tasks to be dequeued and immediately
553 * requeued in the same or another array: this can happen in sched_yield(),
554 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
557 * This function is only called from enqueue_task(), but also only updates
558 * the timestamp if it is already not set. It's assumed that
559 * sched_info_dequeued() will clear that stamp when appropriate.
561 static inline void sched_info_queued(task_t *t)
563 if (!t->sched_info.last_queued)
564 t->sched_info.last_queued = jiffies;
568 * Called when a process ceases being the active-running process, either
569 * voluntarily or involuntarily. Now we can calculate how long we ran.
571 static inline void sched_info_depart(task_t *t)
573 struct runqueue *rq = task_rq(t);
574 unsigned long diff = jiffies - t->sched_info.last_arrival;
576 t->sched_info.cpu_time += diff;
579 rq->rq_sched_info.cpu_time += diff;
583 * Called when tasks are switched involuntarily due, typically, to expiring
584 * their time slice. (This may also be called when switching to or from
585 * the idle task.) We are only called when prev != next.
587 static inline void sched_info_switch(task_t *prev, task_t *next)
589 struct runqueue *rq = task_rq(prev);
592 * prev now departs the cpu. It's not interesting to record
593 * stats about how efficient we were at scheduling the idle
596 if (prev != rq->idle)
597 sched_info_depart(prev);
599 if (next != rq->idle)
600 sched_info_arrive(next);
603 #define sched_info_queued(t) do { } while (0)
604 #define sched_info_switch(t, next) do { } while (0)
605 #endif /* CONFIG_SCHEDSTATS */
608 * Adding/removing a task to/from a priority array:
610 static void dequeue_task(struct task_struct *p, prio_array_t *array)
612 BUG_ON(p->state & TASK_ONHOLD);
614 list_del(&p->run_list);
615 if (list_empty(array->queue + p->prio))
616 __clear_bit(p->prio, array->bitmap);
619 static void enqueue_task(struct task_struct *p, prio_array_t *array)
621 BUG_ON(p->state & TASK_ONHOLD);
622 sched_info_queued(p);
623 list_add_tail(&p->run_list, array->queue + p->prio);
624 __set_bit(p->prio, array->bitmap);
630 * Put task to the end of the run list without the overhead of dequeue
631 * followed by enqueue.
633 static void requeue_task(struct task_struct *p, prio_array_t *array)
635 BUG_ON(p->state & TASK_ONHOLD);
636 list_move_tail(&p->run_list, array->queue + p->prio);
639 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
641 BUG_ON(p->state & TASK_ONHOLD);
642 list_add(&p->run_list, array->queue + p->prio);
643 __set_bit(p->prio, array->bitmap);
649 * effective_prio - return the priority that is based on the static
650 * priority but is modified by bonuses/penalties.
652 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
653 * into the -5 ... 0 ... +5 bonus/penalty range.
655 * We use 25% of the full 0...39 priority range so that:
657 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
658 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
660 * Both properties are important to certain workloads.
662 static int effective_prio(task_t *p)
670 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
672 prio = p->static_prio - bonus;
674 if ((vxi = p->vx_info) &&
675 vx_info_flags(vxi, VXF_SCHED_PRIO, 0))
676 prio += vx_effective_vavavoom(vxi, MAX_USER_PRIO);
678 if (prio < MAX_RT_PRIO)
680 if (prio > MAX_PRIO-1)
686 * __activate_task - move a task to the runqueue.
688 static void __activate_task(task_t *p, runqueue_t *rq)
690 prio_array_t *target = rq->active;
693 target = rq->expired;
694 enqueue_task(p, target);
699 * __activate_idle_task - move idle task to the _front_ of runqueue.
701 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
703 enqueue_task_head(p, rq->active);
707 static int recalc_task_prio(task_t *p, unsigned long long now)
709 /* Caller must always ensure 'now >= p->timestamp' */
710 unsigned long long __sleep_time = now - p->timestamp;
711 unsigned long sleep_time;
716 if (__sleep_time > NS_MAX_SLEEP_AVG)
717 sleep_time = NS_MAX_SLEEP_AVG;
719 sleep_time = (unsigned long)__sleep_time;
722 if (likely(sleep_time > 0)) {
724 * User tasks that sleep a long time are categorised as
725 * idle. They will only have their sleep_avg increased to a
726 * level that makes them just interactive priority to stay
727 * active yet prevent them suddenly becoming cpu hogs and
728 * starving other processes.
730 if (p->mm && sleep_time > INTERACTIVE_SLEEP(p)) {
731 unsigned long ceiling;
733 ceiling = JIFFIES_TO_NS(MAX_SLEEP_AVG -
735 if (p->sleep_avg < ceiling)
736 p->sleep_avg = ceiling;
739 * Tasks waking from uninterruptible sleep are
740 * limited in their sleep_avg rise as they
741 * are likely to be waiting on I/O
743 if (p->sleep_type == SLEEP_NONINTERACTIVE && p->mm) {
744 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
746 else if (p->sleep_avg + sleep_time >=
747 INTERACTIVE_SLEEP(p)) {
748 p->sleep_avg = INTERACTIVE_SLEEP(p);
754 * This code gives a bonus to interactive tasks.
756 * The boost works by updating the 'average sleep time'
757 * value here, based on ->timestamp. The more time a
758 * task spends sleeping, the higher the average gets -
759 * and the higher the priority boost gets as well.
761 p->sleep_avg += sleep_time;
763 if (p->sleep_avg > NS_MAX_SLEEP_AVG)
764 p->sleep_avg = NS_MAX_SLEEP_AVG;
768 return effective_prio(p);
772 * activate_task - move a task to the runqueue and do priority recalculation
774 * Update all the scheduling statistics stuff. (sleep average
775 * calculation, priority modifiers, etc.)
777 static void activate_task(task_t *p, runqueue_t *rq, int local)
779 unsigned long long now;
784 /* Compensate for drifting sched_clock */
785 runqueue_t *this_rq = this_rq();
786 now = (now - this_rq->timestamp_last_tick)
787 + rq->timestamp_last_tick;
792 p->prio = recalc_task_prio(p, now);
795 * This checks to make sure it's not an uninterruptible task
796 * that is now waking up.
798 if (p->sleep_type == SLEEP_NORMAL) {
800 * Tasks which were woken up by interrupts (ie. hw events)
801 * are most likely of interactive nature. So we give them
802 * the credit of extending their sleep time to the period
803 * of time they spend on the runqueue, waiting for execution
804 * on a CPU, first time around:
807 p->sleep_type = SLEEP_INTERRUPTED;
810 * Normal first-time wakeups get a credit too for
811 * on-runqueue time, but it will be weighted down:
813 p->sleep_type = SLEEP_INTERACTIVE;
819 __activate_task(p, rq);
823 * deactivate_task - remove a task from the runqueue.
825 static void __deactivate_task(struct task_struct *p, runqueue_t *rq)
828 dequeue_task(p, p->array);
833 void deactivate_task(struct task_struct *p, runqueue_t *rq)
835 vx_deactivate_task(p);
836 __deactivate_task(p, rq);
840 #ifdef CONFIG_VSERVER_HARDCPU
842 * vx_hold_task - put a task on the hold queue
845 void vx_hold_task(struct vx_info *vxi,
846 struct task_struct *p, runqueue_t *rq)
848 __deactivate_task(p, rq);
849 p->state |= TASK_ONHOLD;
850 /* a new one on hold */
852 list_add_tail(&p->run_list, &rq->hold_queue);
856 * vx_unhold_task - put a task back to the runqueue
859 void vx_unhold_task(struct vx_info *vxi,
860 struct task_struct *p, runqueue_t *rq)
862 list_del(&p->run_list);
863 /* one less waiting */
865 p->state &= ~TASK_ONHOLD;
866 enqueue_task(p, rq->expired);
869 if (p->static_prio < rq->best_expired_prio)
870 rq->best_expired_prio = p->static_prio;
874 void vx_hold_task(struct vx_info *vxi,
875 struct task_struct *p, runqueue_t *rq)
881 void vx_unhold_task(struct vx_info *vxi,
882 struct task_struct *p, runqueue_t *rq)
886 #endif /* CONFIG_VSERVER_HARDCPU */
890 * resched_task - mark a task 'to be rescheduled now'.
892 * On UP this means the setting of the need_resched flag, on SMP it
893 * might also involve a cross-CPU call to trigger the scheduler on
897 static void resched_task(task_t *p)
901 assert_spin_locked(&task_rq(p)->lock);
903 if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
906 set_tsk_thread_flag(p, TIF_NEED_RESCHED);
909 if (cpu == smp_processor_id())
912 /* NEED_RESCHED must be visible before we test POLLING_NRFLAG */
914 if (!test_tsk_thread_flag(p, TIF_POLLING_NRFLAG))
915 smp_send_reschedule(cpu);
918 static inline void resched_task(task_t *p)
920 assert_spin_locked(&task_rq(p)->lock);
921 set_tsk_need_resched(p);
926 * task_curr - is this task currently executing on a CPU?
927 * @p: the task in question.
929 inline int task_curr(const task_t *p)
931 return cpu_curr(task_cpu(p)) == p;
936 struct list_head list;
941 struct completion done;
945 * The task's runqueue lock must be held.
946 * Returns true if you have to wait for migration thread.
948 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
950 runqueue_t *rq = task_rq(p);
953 * If the task is not on a runqueue (and not running), then
954 * it is sufficient to simply update the task's cpu field.
956 if (!p->array && !task_running(rq, p)) {
957 set_task_cpu(p, dest_cpu);
961 init_completion(&req->done);
963 req->dest_cpu = dest_cpu;
964 list_add(&req->list, &rq->migration_queue);
969 * wait_task_inactive - wait for a thread to unschedule.
971 * The caller must ensure that the task *will* unschedule sometime soon,
972 * else this function might spin for a *long* time. This function can't
973 * be called with interrupts off, or it may introduce deadlock with
974 * smp_call_function() if an IPI is sent by the same process we are
975 * waiting to become inactive.
977 void wait_task_inactive(task_t *p)
984 rq = task_rq_lock(p, &flags);
985 /* Must be off runqueue entirely, not preempted. */
986 if (unlikely(p->array || task_running(rq, p))) {
987 /* If it's preempted, we yield. It could be a while. */
988 preempted = !task_running(rq, p);
989 task_rq_unlock(rq, &flags);
995 task_rq_unlock(rq, &flags);
999 * kick_process - kick a running thread to enter/exit the kernel
1000 * @p: the to-be-kicked thread
1002 * Cause a process which is running on another CPU to enter
1003 * kernel-mode, without any delay. (to get signals handled.)
1005 * NOTE: this function doesnt have to take the runqueue lock,
1006 * because all it wants to ensure is that the remote task enters
1007 * the kernel. If the IPI races and the task has been migrated
1008 * to another CPU then no harm is done and the purpose has been
1011 void kick_process(task_t *p)
1017 if ((cpu != smp_processor_id()) && task_curr(p))
1018 smp_send_reschedule(cpu);
1023 * Return a low guess at the load of a migration-source cpu.
1025 * We want to under-estimate the load of migration sources, to
1026 * balance conservatively.
1028 static inline unsigned long source_load(int cpu, int type)
1030 runqueue_t *rq = cpu_rq(cpu);
1031 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
1035 return min(rq->cpu_load[type-1], load_now);
1039 * Return a high guess at the load of a migration-target cpu
1041 static inline unsigned long target_load(int cpu, int type)
1043 runqueue_t *rq = cpu_rq(cpu);
1044 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
1048 return max(rq->cpu_load[type-1], load_now);
1052 * find_idlest_group finds and returns the least busy CPU group within the
1055 static struct sched_group *
1056 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1058 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1059 unsigned long min_load = ULONG_MAX, this_load = 0;
1060 int load_idx = sd->forkexec_idx;
1061 int imbalance = 100 + (sd->imbalance_pct-100)/2;
1064 unsigned long load, avg_load;
1068 /* Skip over this group if it has no CPUs allowed */
1069 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
1072 local_group = cpu_isset(this_cpu, group->cpumask);
1074 /* Tally up the load of all CPUs in the group */
1077 for_each_cpu_mask(i, group->cpumask) {
1078 /* Bias balancing toward cpus of our domain */
1080 load = source_load(i, load_idx);
1082 load = target_load(i, load_idx);
1087 /* Adjust by relative CPU power of the group */
1088 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1091 this_load = avg_load;
1093 } else if (avg_load < min_load) {
1094 min_load = avg_load;
1098 group = group->next;
1099 } while (group != sd->groups);
1101 if (!idlest || 100*this_load < imbalance*min_load)
1107 * find_idlest_queue - find the idlest runqueue among the cpus in group.
1110 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
1113 unsigned long load, min_load = ULONG_MAX;
1117 /* Traverse only the allowed CPUs */
1118 cpus_and(tmp, group->cpumask, p->cpus_allowed);
1120 for_each_cpu_mask(i, tmp) {
1121 load = source_load(i, 0);
1123 if (load < min_load || (load == min_load && i == this_cpu)) {
1133 * sched_balance_self: balance the current task (running on cpu) in domains
1134 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1137 * Balance, ie. select the least loaded group.
1139 * Returns the target CPU number, or the same CPU if no balancing is needed.
1141 * preempt must be disabled.
1143 static int sched_balance_self(int cpu, int flag)
1145 struct task_struct *t = current;
1146 struct sched_domain *tmp, *sd = NULL;
1148 for_each_domain(cpu, tmp)
1149 if (tmp->flags & flag)
1154 struct sched_group *group;
1159 group = find_idlest_group(sd, t, cpu);
1163 new_cpu = find_idlest_cpu(group, t, cpu);
1164 if (new_cpu == -1 || new_cpu == cpu)
1167 /* Now try balancing at a lower domain level */
1171 weight = cpus_weight(span);
1172 for_each_domain(cpu, tmp) {
1173 if (weight <= cpus_weight(tmp->span))
1175 if (tmp->flags & flag)
1178 /* while loop will break here if sd == NULL */
1184 #endif /* CONFIG_SMP */
1187 * wake_idle() will wake a task on an idle cpu if task->cpu is
1188 * not idle and an idle cpu is available. The span of cpus to
1189 * search starts with cpus closest then further out as needed,
1190 * so we always favor a closer, idle cpu.
1192 * Returns the CPU we should wake onto.
1194 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1195 static int wake_idle(int cpu, task_t *p)
1198 struct sched_domain *sd;
1204 for_each_domain(cpu, sd) {
1205 if (sd->flags & SD_WAKE_IDLE) {
1206 cpus_and(tmp, sd->span, p->cpus_allowed);
1207 for_each_cpu_mask(i, tmp) {
1218 static inline int wake_idle(int cpu, task_t *p)
1225 * try_to_wake_up - wake up a thread
1226 * @p: the to-be-woken-up thread
1227 * @state: the mask of task states that can be woken
1228 * @sync: do a synchronous wakeup?
1230 * Put it on the run-queue if it's not already there. The "current"
1231 * thread is always on the run-queue (except when the actual
1232 * re-schedule is in progress), and as such you're allowed to do
1233 * the simpler "current->state = TASK_RUNNING" to mark yourself
1234 * runnable without the overhead of this.
1236 * returns failure only if the task is already active.
1238 static int try_to_wake_up(task_t *p, unsigned int state, int sync)
1240 int cpu, this_cpu, success = 0;
1241 unsigned long flags;
1245 unsigned long load, this_load;
1246 struct sched_domain *sd, *this_sd = NULL;
1250 rq = task_rq_lock(p, &flags);
1251 old_state = p->state;
1253 /* we need to unhold suspended tasks */
1254 if (old_state & TASK_ONHOLD) {
1255 vx_unhold_task(p->vx_info, p, rq);
1256 old_state = p->state;
1258 if (!(old_state & state))
1265 this_cpu = smp_processor_id();
1268 if (unlikely(task_running(rq, p)))
1273 schedstat_inc(rq, ttwu_cnt);
1274 if (cpu == this_cpu) {
1275 schedstat_inc(rq, ttwu_local);
1279 for_each_domain(this_cpu, sd) {
1280 if (cpu_isset(cpu, sd->span)) {
1281 schedstat_inc(sd, ttwu_wake_remote);
1287 if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1291 * Check for affine wakeup and passive balancing possibilities.
1294 int idx = this_sd->wake_idx;
1295 unsigned int imbalance;
1297 imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
1299 load = source_load(cpu, idx);
1300 this_load = target_load(this_cpu, idx);
1302 new_cpu = this_cpu; /* Wake to this CPU if we can */
1304 if (this_sd->flags & SD_WAKE_AFFINE) {
1305 unsigned long tl = this_load;
1307 * If sync wakeup then subtract the (maximum possible)
1308 * effect of the currently running task from the load
1309 * of the current CPU:
1312 tl -= SCHED_LOAD_SCALE;
1315 tl + target_load(cpu, idx) <= SCHED_LOAD_SCALE) ||
1316 100*(tl + SCHED_LOAD_SCALE) <= imbalance*load) {
1318 * This domain has SD_WAKE_AFFINE and
1319 * p is cache cold in this domain, and
1320 * there is no bad imbalance.
1322 schedstat_inc(this_sd, ttwu_move_affine);
1328 * Start passive balancing when half the imbalance_pct
1331 if (this_sd->flags & SD_WAKE_BALANCE) {
1332 if (imbalance*this_load <= 100*load) {
1333 schedstat_inc(this_sd, ttwu_move_balance);
1339 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1341 new_cpu = wake_idle(new_cpu, p);
1342 if (new_cpu != cpu) {
1343 set_task_cpu(p, new_cpu);
1344 task_rq_unlock(rq, &flags);
1345 /* might preempt at this point */
1346 rq = task_rq_lock(p, &flags);
1347 old_state = p->state;
1348 if (!(old_state & state))
1353 this_cpu = smp_processor_id();
1358 #endif /* CONFIG_SMP */
1359 if (old_state == TASK_UNINTERRUPTIBLE) {
1360 rq->nr_uninterruptible--;
1361 vx_uninterruptible_dec(p);
1363 * Tasks on involuntary sleep don't earn
1364 * sleep_avg beyond just interactive state.
1366 p->sleep_type = SLEEP_NONINTERACTIVE;
1370 * Tasks that have marked their sleep as noninteractive get
1371 * woken up with their sleep average not weighted in an
1374 if (old_state & TASK_NONINTERACTIVE)
1375 p->sleep_type = SLEEP_NONINTERACTIVE;
1378 activate_task(p, rq, cpu == this_cpu);
1380 * Sync wakeups (i.e. those types of wakeups where the waker
1381 * has indicated that it will leave the CPU in short order)
1382 * don't trigger a preemption, if the woken up task will run on
1383 * this cpu. (in this case the 'I will reschedule' promise of
1384 * the waker guarantees that the freshly woken up task is going
1385 * to be considered on this CPU.)
1387 if (!sync || cpu != this_cpu) {
1388 if (TASK_PREEMPTS_CURR(p, rq))
1389 resched_task(rq->curr);
1394 p->state = TASK_RUNNING;
1396 task_rq_unlock(rq, &flags);
1401 int fastcall wake_up_process(task_t *p)
1403 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1404 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1407 EXPORT_SYMBOL(wake_up_process);
1409 int fastcall wake_up_state(task_t *p, unsigned int state)
1411 return try_to_wake_up(p, state, 0);
1415 * Perform scheduler related setup for a newly forked process p.
1416 * p is forked by current.
1418 void fastcall sched_fork(task_t *p, int clone_flags)
1420 int cpu = get_cpu();
1423 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
1425 set_task_cpu(p, cpu);
1428 * We mark the process as running here, but have not actually
1429 * inserted it onto the runqueue yet. This guarantees that
1430 * nobody will actually run it, and a signal or other external
1431 * event cannot wake it up and insert it on the runqueue either.
1433 p->state = TASK_RUNNING;
1434 INIT_LIST_HEAD(&p->run_list);
1436 #ifdef CONFIG_SCHEDSTATS
1437 memset(&p->sched_info, 0, sizeof(p->sched_info));
1439 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
1442 #ifdef CONFIG_PREEMPT
1443 /* Want to start with kernel preemption disabled. */
1444 task_thread_info(p)->preempt_count = 1;
1447 * Share the timeslice between parent and child, thus the
1448 * total amount of pending timeslices in the system doesn't change,
1449 * resulting in more scheduling fairness.
1451 local_irq_disable();
1452 p->time_slice = (current->time_slice + 1) >> 1;
1454 * The remainder of the first timeslice might be recovered by
1455 * the parent if the child exits early enough.
1457 p->first_time_slice = 1;
1458 current->time_slice >>= 1;
1459 p->timestamp = sched_clock();
1460 if (unlikely(!current->time_slice)) {
1462 * This case is rare, it happens when the parent has only
1463 * a single jiffy left from its timeslice. Taking the
1464 * runqueue lock is not a problem.
1466 current->time_slice = 1;
1474 * wake_up_new_task - wake up a newly created task for the first time.
1476 * This function will do some initial scheduler statistics housekeeping
1477 * that must be done for every newly created context, then puts the task
1478 * on the runqueue and wakes it.
1480 void fastcall wake_up_new_task(task_t *p, unsigned long clone_flags)
1482 unsigned long flags;
1484 runqueue_t *rq, *this_rq;
1486 rq = task_rq_lock(p, &flags);
1487 BUG_ON(p->state != TASK_RUNNING);
1488 this_cpu = smp_processor_id();
1492 * We decrease the sleep average of forking parents
1493 * and children as well, to keep max-interactive tasks
1494 * from forking tasks that are max-interactive. The parent
1495 * (current) is done further down, under its lock.
1497 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1498 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1500 p->prio = effective_prio(p);
1502 vx_activate_task(p);
1503 if (likely(cpu == this_cpu)) {
1504 if (!(clone_flags & CLONE_VM)) {
1506 * The VM isn't cloned, so we're in a good position to
1507 * do child-runs-first in anticipation of an exec. This
1508 * usually avoids a lot of COW overhead.
1510 if (unlikely(!current->array))
1511 __activate_task(p, rq);
1513 p->prio = current->prio;
1514 BUG_ON(p->state & TASK_ONHOLD);
1515 list_add_tail(&p->run_list, ¤t->run_list);
1516 p->array = current->array;
1517 p->array->nr_active++;
1522 /* Run child last */
1523 __activate_task(p, rq);
1525 * We skip the following code due to cpu == this_cpu
1527 * task_rq_unlock(rq, &flags);
1528 * this_rq = task_rq_lock(current, &flags);
1532 this_rq = cpu_rq(this_cpu);
1535 * Not the local CPU - must adjust timestamp. This should
1536 * get optimised away in the !CONFIG_SMP case.
1538 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1539 + rq->timestamp_last_tick;
1540 __activate_task(p, rq);
1541 if (TASK_PREEMPTS_CURR(p, rq))
1542 resched_task(rq->curr);
1545 * Parent and child are on different CPUs, now get the
1546 * parent runqueue to update the parent's ->sleep_avg:
1548 task_rq_unlock(rq, &flags);
1549 this_rq = task_rq_lock(current, &flags);
1551 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1552 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1553 task_rq_unlock(this_rq, &flags);
1557 * Potentially available exiting-child timeslices are
1558 * retrieved here - this way the parent does not get
1559 * penalized for creating too many threads.
1561 * (this cannot be used to 'generate' timeslices
1562 * artificially, because any timeslice recovered here
1563 * was given away by the parent in the first place.)
1565 void fastcall sched_exit(task_t *p)
1567 unsigned long flags;
1571 * If the child was a (relative-) CPU hog then decrease
1572 * the sleep_avg of the parent as well.
1574 rq = task_rq_lock(p->parent, &flags);
1575 if (p->first_time_slice && task_cpu(p) == task_cpu(p->parent)) {
1576 p->parent->time_slice += p->time_slice;
1577 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1578 p->parent->time_slice = task_timeslice(p);
1580 if (p->sleep_avg < p->parent->sleep_avg)
1581 p->parent->sleep_avg = p->parent->sleep_avg /
1582 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1584 task_rq_unlock(rq, &flags);
1588 * prepare_task_switch - prepare to switch tasks
1589 * @rq: the runqueue preparing to switch
1590 * @next: the task we are going to switch to.
1592 * This is called with the rq lock held and interrupts off. It must
1593 * be paired with a subsequent finish_task_switch after the context
1596 * prepare_task_switch sets up locking and calls architecture specific
1599 static inline void prepare_task_switch(runqueue_t *rq, task_t *next)
1601 prepare_lock_switch(rq, next);
1602 prepare_arch_switch(next);
1606 * finish_task_switch - clean up after a task-switch
1607 * @rq: runqueue associated with task-switch
1608 * @prev: the thread we just switched away from.
1610 * finish_task_switch must be called after the context switch, paired
1611 * with a prepare_task_switch call before the context switch.
1612 * finish_task_switch will reconcile locking set up by prepare_task_switch,
1613 * and do any other architecture-specific cleanup actions.
1615 * Note that we may have delayed dropping an mm in context_switch(). If
1616 * so, we finish that here outside of the runqueue lock. (Doing it
1617 * with the lock held can cause deadlocks; see schedule() for
1620 static inline void finish_task_switch(runqueue_t *rq, task_t *prev)
1621 __releases(rq->lock)
1623 struct mm_struct *mm = rq->prev_mm;
1624 unsigned long prev_task_flags;
1629 * A task struct has one reference for the use as "current".
1630 * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1631 * calls schedule one last time. The schedule call will never return,
1632 * and the scheduled task must drop that reference.
1633 * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1634 * still held, otherwise prev could be scheduled on another cpu, die
1635 * there before we look at prev->state, and then the reference would
1637 * Manfred Spraul <manfred@colorfullife.com>
1639 prev_task_flags = prev->flags;
1640 finish_arch_switch(prev);
1641 finish_lock_switch(rq, prev);
1644 if (unlikely(prev_task_flags & PF_DEAD)) {
1646 * Remove function-return probe instances associated with this
1647 * task and put them back on the free list.
1649 kprobe_flush_task(prev);
1650 put_task_struct(prev);
1655 * schedule_tail - first thing a freshly forked thread must call.
1656 * @prev: the thread we just switched away from.
1658 asmlinkage void schedule_tail(task_t *prev)
1659 __releases(rq->lock)
1661 runqueue_t *rq = this_rq();
1662 finish_task_switch(rq, prev);
1663 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
1664 /* In this case, finish_task_switch does not reenable preemption */
1667 if (current->set_child_tid)
1668 put_user(current->pid, current->set_child_tid);
1672 * context_switch - switch to the new MM and the new
1673 * thread's register state.
1676 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1678 struct mm_struct *mm = next->mm;
1679 struct mm_struct *oldmm = prev->active_mm;
1681 if (unlikely(!mm)) {
1682 next->active_mm = oldmm;
1683 atomic_inc(&oldmm->mm_count);
1684 enter_lazy_tlb(oldmm, next);
1686 switch_mm(oldmm, mm, next);
1688 if (unlikely(!prev->mm)) {
1689 prev->active_mm = NULL;
1690 WARN_ON(rq->prev_mm);
1691 rq->prev_mm = oldmm;
1694 /* Here we just switch the register state and the stack. */
1695 switch_to(prev, next, prev);
1701 * nr_running, nr_uninterruptible and nr_context_switches:
1703 * externally visible scheduler statistics: current number of runnable
1704 * threads, current number of uninterruptible-sleeping threads, total
1705 * number of context switches performed since bootup.
1707 unsigned long nr_running(void)
1709 unsigned long i, sum = 0;
1711 for_each_online_cpu(i)
1712 sum += cpu_rq(i)->nr_running;
1717 unsigned long nr_uninterruptible(void)
1719 unsigned long i, sum = 0;
1721 for_each_possible_cpu(i)
1722 sum += cpu_rq(i)->nr_uninterruptible;
1725 * Since we read the counters lockless, it might be slightly
1726 * inaccurate. Do not allow it to go below zero though:
1728 if (unlikely((long)sum < 0))
1734 unsigned long long nr_context_switches(void)
1736 unsigned long long i, sum = 0;
1738 for_each_possible_cpu(i)
1739 sum += cpu_rq(i)->nr_switches;
1744 unsigned long nr_iowait(void)
1746 unsigned long i, sum = 0;
1748 for_each_possible_cpu(i)
1749 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1754 unsigned long nr_active(void)
1756 unsigned long i, running = 0, uninterruptible = 0;
1758 for_each_online_cpu(i) {
1759 running += cpu_rq(i)->nr_running;
1760 uninterruptible += cpu_rq(i)->nr_uninterruptible;
1763 if (unlikely((long)uninterruptible < 0))
1764 uninterruptible = 0;
1766 return running + uninterruptible;
1772 * double_rq_lock - safely lock two runqueues
1774 * We must take them in cpu order to match code in
1775 * dependent_sleeper and wake_dependent_sleeper.
1777 * Note this does not disable interrupts like task_rq_lock,
1778 * you need to do so manually before calling.
1780 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1781 __acquires(rq1->lock)
1782 __acquires(rq2->lock)
1785 spin_lock(&rq1->lock);
1786 __acquire(rq2->lock); /* Fake it out ;) */
1788 if (rq1->cpu < rq2->cpu) {
1789 spin_lock(&rq1->lock);
1790 spin_lock(&rq2->lock);
1792 spin_lock(&rq2->lock);
1793 spin_lock(&rq1->lock);
1799 * double_rq_unlock - safely unlock two runqueues
1801 * Note this does not restore interrupts like task_rq_unlock,
1802 * you need to do so manually after calling.
1804 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1805 __releases(rq1->lock)
1806 __releases(rq2->lock)
1808 spin_unlock(&rq1->lock);
1810 spin_unlock(&rq2->lock);
1812 __release(rq2->lock);
1816 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1818 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1819 __releases(this_rq->lock)
1820 __acquires(busiest->lock)
1821 __acquires(this_rq->lock)
1823 if (unlikely(!spin_trylock(&busiest->lock))) {
1824 if (busiest->cpu < this_rq->cpu) {
1825 spin_unlock(&this_rq->lock);
1826 spin_lock(&busiest->lock);
1827 spin_lock(&this_rq->lock);
1829 spin_lock(&busiest->lock);
1834 * If dest_cpu is allowed for this process, migrate the task to it.
1835 * This is accomplished by forcing the cpu_allowed mask to only
1836 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1837 * the cpu_allowed mask is restored.
1839 static void sched_migrate_task(task_t *p, int dest_cpu)
1841 migration_req_t req;
1843 unsigned long flags;
1845 rq = task_rq_lock(p, &flags);
1846 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1847 || unlikely(cpu_is_offline(dest_cpu)))
1850 /* force the process onto the specified CPU */
1851 if (migrate_task(p, dest_cpu, &req)) {
1852 /* Need to wait for migration thread (might exit: take ref). */
1853 struct task_struct *mt = rq->migration_thread;
1854 get_task_struct(mt);
1855 task_rq_unlock(rq, &flags);
1856 wake_up_process(mt);
1857 put_task_struct(mt);
1858 wait_for_completion(&req.done);
1862 task_rq_unlock(rq, &flags);
1866 * sched_exec - execve() is a valuable balancing opportunity, because at
1867 * this point the task has the smallest effective memory and cache footprint.
1869 void sched_exec(void)
1871 int new_cpu, this_cpu = get_cpu();
1872 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
1874 if (new_cpu != this_cpu)
1875 sched_migrate_task(current, new_cpu);
1879 * pull_task - move a task from a remote runqueue to the local runqueue.
1880 * Both runqueues must be locked.
1883 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1884 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1886 dequeue_task(p, src_array);
1887 src_rq->nr_running--;
1888 set_task_cpu(p, this_cpu);
1889 this_rq->nr_running++;
1890 enqueue_task(p, this_array);
1891 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1892 + this_rq->timestamp_last_tick;
1894 * Note that idle threads have a prio of MAX_PRIO, for this test
1895 * to be always true for them.
1897 if (TASK_PREEMPTS_CURR(p, this_rq))
1898 resched_task(this_rq->curr);
1902 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1905 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1906 struct sched_domain *sd, enum idle_type idle,
1910 * We do not migrate tasks that are:
1911 * 1) running (obviously), or
1912 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1913 * 3) are cache-hot on their current CPU.
1915 if (!cpu_isset(this_cpu, p->cpus_allowed))
1919 if (task_running(rq, p))
1923 * Aggressive migration if:
1924 * 1) task is cache cold, or
1925 * 2) too many balance attempts have failed.
1928 if (sd->nr_balance_failed > sd->cache_nice_tries)
1931 if (task_hot(p, rq->timestamp_last_tick, sd))
1937 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1938 * as part of a balancing operation within "domain". Returns the number of
1941 * Called with both runqueues locked.
1943 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1944 unsigned long max_nr_move, struct sched_domain *sd,
1945 enum idle_type idle, int *all_pinned)
1947 prio_array_t *array, *dst_array;
1948 struct list_head *head, *curr;
1949 int idx, pulled = 0, pinned = 0;
1952 if (max_nr_move == 0)
1958 * We first consider expired tasks. Those will likely not be
1959 * executed in the near future, and they are most likely to
1960 * be cache-cold, thus switching CPUs has the least effect
1963 if (busiest->expired->nr_active) {
1964 array = busiest->expired;
1965 dst_array = this_rq->expired;
1967 array = busiest->active;
1968 dst_array = this_rq->active;
1972 /* Start searching at priority 0: */
1976 idx = sched_find_first_bit(array->bitmap);
1978 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1979 if (idx >= MAX_PRIO) {
1980 if (array == busiest->expired && busiest->active->nr_active) {
1981 array = busiest->active;
1982 dst_array = this_rq->active;
1988 head = array->queue + idx;
1991 tmp = list_entry(curr, task_t, run_list);
1995 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle, &pinned)) {
2002 #ifdef CONFIG_SCHEDSTATS
2003 if (task_hot(tmp, busiest->timestamp_last_tick, sd))
2004 schedstat_inc(sd, lb_hot_gained[idle]);
2007 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
2010 /* We only want to steal up to the prescribed number of tasks. */
2011 if (pulled < max_nr_move) {
2019 * Right now, this is the only place pull_task() is called,
2020 * so we can safely collect pull_task() stats here rather than
2021 * inside pull_task().
2023 schedstat_add(sd, lb_gained[idle], pulled);
2026 *all_pinned = pinned;
2031 * find_busiest_group finds and returns the busiest CPU group within the
2032 * domain. It calculates and returns the number of tasks which should be
2033 * moved to restore balance via the imbalance parameter.
2035 static struct sched_group *
2036 find_busiest_group(struct sched_domain *sd, int this_cpu,
2037 unsigned long *imbalance, enum idle_type idle, int *sd_idle)
2039 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2040 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2041 unsigned long max_pull;
2044 max_load = this_load = total_load = total_pwr = 0;
2045 if (idle == NOT_IDLE)
2046 load_idx = sd->busy_idx;
2047 else if (idle == NEWLY_IDLE)
2048 load_idx = sd->newidle_idx;
2050 load_idx = sd->idle_idx;
2057 local_group = cpu_isset(this_cpu, group->cpumask);
2059 /* Tally up the load of all CPUs in the group */
2062 for_each_cpu_mask(i, group->cpumask) {
2063 if (*sd_idle && !idle_cpu(i))
2066 /* Bias balancing toward cpus of our domain */
2068 load = target_load(i, load_idx);
2070 load = source_load(i, load_idx);
2075 total_load += avg_load;
2076 total_pwr += group->cpu_power;
2078 /* Adjust by relative CPU power of the group */
2079 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
2082 this_load = avg_load;
2084 } else if (avg_load > max_load) {
2085 max_load = avg_load;
2088 group = group->next;
2089 } while (group != sd->groups);
2091 if (!busiest || this_load >= max_load || max_load <= SCHED_LOAD_SCALE)
2094 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2096 if (this_load >= avg_load ||
2097 100*max_load <= sd->imbalance_pct*this_load)
2101 * We're trying to get all the cpus to the average_load, so we don't
2102 * want to push ourselves above the average load, nor do we wish to
2103 * reduce the max loaded cpu below the average load, as either of these
2104 * actions would just result in more rebalancing later, and ping-pong
2105 * tasks around. Thus we look for the minimum possible imbalance.
2106 * Negative imbalances (*we* are more loaded than anyone else) will
2107 * be counted as no imbalance for these purposes -- we can't fix that
2108 * by pulling tasks to us. Be careful of negative numbers as they'll
2109 * appear as very large values with unsigned longs.
2112 /* Don't want to pull so many tasks that a group would go idle */
2113 max_pull = min(max_load - avg_load, max_load - SCHED_LOAD_SCALE);
2115 /* How much load to actually move to equalise the imbalance */
2116 *imbalance = min(max_pull * busiest->cpu_power,
2117 (avg_load - this_load) * this->cpu_power)
2120 if (*imbalance < SCHED_LOAD_SCALE) {
2121 unsigned long pwr_now = 0, pwr_move = 0;
2124 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
2130 * OK, we don't have enough imbalance to justify moving tasks,
2131 * however we may be able to increase total CPU power used by
2135 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
2136 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
2137 pwr_now /= SCHED_LOAD_SCALE;
2139 /* Amount of load we'd subtract */
2140 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
2142 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
2145 /* Amount of load we'd add */
2146 if (max_load*busiest->cpu_power <
2147 SCHED_LOAD_SCALE*SCHED_LOAD_SCALE)
2148 tmp = max_load*busiest->cpu_power/this->cpu_power;
2150 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
2151 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
2152 pwr_move /= SCHED_LOAD_SCALE;
2154 /* Move if we gain throughput */
2155 if (pwr_move <= pwr_now)
2162 /* Get rid of the scaling factor, rounding down as we divide */
2163 *imbalance = *imbalance / SCHED_LOAD_SCALE;
2173 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2175 static runqueue_t *find_busiest_queue(struct sched_group *group,
2176 enum idle_type idle)
2178 unsigned long load, max_load = 0;
2179 runqueue_t *busiest = NULL;
2182 for_each_cpu_mask(i, group->cpumask) {
2183 load = source_load(i, 0);
2185 if (load > max_load) {
2187 busiest = cpu_rq(i);
2195 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2196 * so long as it is large enough.
2198 #define MAX_PINNED_INTERVAL 512
2201 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2202 * tasks if there is an imbalance.
2204 * Called with this_rq unlocked.
2206 static int load_balance(int this_cpu, runqueue_t *this_rq,
2207 struct sched_domain *sd, enum idle_type idle)
2209 struct sched_group *group;
2210 runqueue_t *busiest;
2211 unsigned long imbalance;
2212 int nr_moved, all_pinned = 0;
2213 int active_balance = 0;
2216 if (idle != NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER)
2219 schedstat_inc(sd, lb_cnt[idle]);
2221 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle);
2223 schedstat_inc(sd, lb_nobusyg[idle]);
2227 busiest = find_busiest_queue(group, idle);
2229 schedstat_inc(sd, lb_nobusyq[idle]);
2233 BUG_ON(busiest == this_rq);
2235 schedstat_add(sd, lb_imbalance[idle], imbalance);
2238 if (busiest->nr_running > 1) {
2240 * Attempt to move tasks. If find_busiest_group has found
2241 * an imbalance but busiest->nr_running <= 1, the group is
2242 * still unbalanced. nr_moved simply stays zero, so it is
2243 * correctly treated as an imbalance.
2245 double_rq_lock(this_rq, busiest);
2246 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2247 imbalance, sd, idle, &all_pinned);
2248 double_rq_unlock(this_rq, busiest);
2250 /* All tasks on this runqueue were pinned by CPU affinity */
2251 if (unlikely(all_pinned))
2256 schedstat_inc(sd, lb_failed[idle]);
2257 sd->nr_balance_failed++;
2259 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2261 spin_lock(&busiest->lock);
2263 /* don't kick the migration_thread, if the curr
2264 * task on busiest cpu can't be moved to this_cpu
2266 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
2267 spin_unlock(&busiest->lock);
2269 goto out_one_pinned;
2272 if (!busiest->active_balance) {
2273 busiest->active_balance = 1;
2274 busiest->push_cpu = this_cpu;
2277 spin_unlock(&busiest->lock);
2279 wake_up_process(busiest->migration_thread);
2282 * We've kicked active balancing, reset the failure
2285 sd->nr_balance_failed = sd->cache_nice_tries+1;
2288 sd->nr_balance_failed = 0;
2290 if (likely(!active_balance)) {
2291 /* We were unbalanced, so reset the balancing interval */
2292 sd->balance_interval = sd->min_interval;
2295 * If we've begun active balancing, start to back off. This
2296 * case may not be covered by the all_pinned logic if there
2297 * is only 1 task on the busy runqueue (because we don't call
2300 if (sd->balance_interval < sd->max_interval)
2301 sd->balance_interval *= 2;
2304 if (!nr_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2309 schedstat_inc(sd, lb_balanced[idle]);
2311 sd->nr_balance_failed = 0;
2314 /* tune up the balancing interval */
2315 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
2316 (sd->balance_interval < sd->max_interval))
2317 sd->balance_interval *= 2;
2319 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2325 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2326 * tasks if there is an imbalance.
2328 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2329 * this_rq is locked.
2331 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2332 struct sched_domain *sd)
2334 struct sched_group *group;
2335 runqueue_t *busiest = NULL;
2336 unsigned long imbalance;
2340 if (sd->flags & SD_SHARE_CPUPOWER)
2343 schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2344 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE, &sd_idle);
2346 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2350 busiest = find_busiest_queue(group, NEWLY_IDLE);
2352 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2356 BUG_ON(busiest == this_rq);
2358 schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2361 if (busiest->nr_running > 1) {
2362 /* Attempt to move tasks */
2363 double_lock_balance(this_rq, busiest);
2364 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2365 imbalance, sd, NEWLY_IDLE, NULL);
2366 spin_unlock(&busiest->lock);
2370 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2371 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2374 sd->nr_balance_failed = 0;
2379 schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
2380 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2382 sd->nr_balance_failed = 0;
2387 * idle_balance is called by schedule() if this_cpu is about to become
2388 * idle. Attempts to pull tasks from other CPUs.
2390 static void idle_balance(int this_cpu, runqueue_t *this_rq)
2392 struct sched_domain *sd;
2394 for_each_domain(this_cpu, sd) {
2395 if (sd->flags & SD_BALANCE_NEWIDLE) {
2396 if (load_balance_newidle(this_cpu, this_rq, sd)) {
2397 /* We've pulled tasks over so stop searching */
2405 * active_load_balance is run by migration threads. It pushes running tasks
2406 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2407 * running on each physical CPU where possible, and avoids physical /
2408 * logical imbalances.
2410 * Called with busiest_rq locked.
2412 static void active_load_balance(runqueue_t *busiest_rq, int busiest_cpu)
2414 struct sched_domain *sd;
2415 runqueue_t *target_rq;
2416 int target_cpu = busiest_rq->push_cpu;
2418 if (busiest_rq->nr_running <= 1)
2419 /* no task to move */
2422 target_rq = cpu_rq(target_cpu);
2425 * This condition is "impossible", if it occurs
2426 * we need to fix it. Originally reported by
2427 * Bjorn Helgaas on a 128-cpu setup.
2429 BUG_ON(busiest_rq == target_rq);
2431 /* move a task from busiest_rq to target_rq */
2432 double_lock_balance(busiest_rq, target_rq);
2434 /* Search for an sd spanning us and the target CPU. */
2435 for_each_domain(target_cpu, sd)
2436 if ((sd->flags & SD_LOAD_BALANCE) &&
2437 cpu_isset(busiest_cpu, sd->span))
2440 if (unlikely(sd == NULL))
2443 schedstat_inc(sd, alb_cnt);
2445 if (move_tasks(target_rq, target_cpu, busiest_rq, 1, sd, SCHED_IDLE, NULL))
2446 schedstat_inc(sd, alb_pushed);
2448 schedstat_inc(sd, alb_failed);
2450 spin_unlock(&target_rq->lock);
2454 * rebalance_tick will get called every timer tick, on every CPU.
2456 * It checks each scheduling domain to see if it is due to be balanced,
2457 * and initiates a balancing operation if so.
2459 * Balancing parameters are set up in arch_init_sched_domains.
2462 /* Don't have all balancing operations going off at once */
2463 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2465 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2466 enum idle_type idle)
2468 unsigned long old_load, this_load;
2469 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2470 struct sched_domain *sd;
2473 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
2474 /* Update our load */
2475 for (i = 0; i < 3; i++) {
2476 unsigned long new_load = this_load;
2478 old_load = this_rq->cpu_load[i];
2480 * Round up the averaging division if load is increasing. This
2481 * prevents us from getting stuck on 9 if the load is 10, for
2484 if (new_load > old_load)
2485 new_load += scale-1;
2486 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) / scale;
2489 for_each_domain(this_cpu, sd) {
2490 unsigned long interval;
2492 if (!(sd->flags & SD_LOAD_BALANCE))
2495 interval = sd->balance_interval;
2496 if (idle != SCHED_IDLE)
2497 interval *= sd->busy_factor;
2499 /* scale ms to jiffies */
2500 interval = msecs_to_jiffies(interval);
2501 if (unlikely(!interval))
2504 if (j - sd->last_balance >= interval) {
2505 if (load_balance(this_cpu, this_rq, sd, idle)) {
2507 * We've pulled tasks over so either we're no
2508 * longer idle, or one of our SMT siblings is
2513 sd->last_balance += interval;
2519 * on UP we do not need to balance between CPUs:
2521 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2524 static inline void idle_balance(int cpu, runqueue_t *rq)
2529 static inline int wake_priority_sleeper(runqueue_t *rq)
2532 #ifdef CONFIG_SCHED_SMT
2533 spin_lock(&rq->lock);
2535 * If an SMT sibling task has been put to sleep for priority
2536 * reasons reschedule the idle task to see if it can now run.
2538 if (rq->nr_running) {
2539 resched_task(rq->idle);
2542 spin_unlock(&rq->lock);
2547 DEFINE_PER_CPU(struct kernel_stat, kstat);
2549 EXPORT_PER_CPU_SYMBOL(kstat);
2552 * This is called on clock ticks and on context switches.
2553 * Bank in p->sched_time the ns elapsed since the last tick or switch.
2555 static inline void update_cpu_clock(task_t *p, runqueue_t *rq,
2556 unsigned long long now)
2558 unsigned long long last = max(p->timestamp, rq->timestamp_last_tick);
2559 p->sched_time += now - last;
2563 * Return current->sched_time plus any more ns on the sched_clock
2564 * that have not yet been banked.
2566 unsigned long long current_sched_time(const task_t *tsk)
2568 unsigned long long ns;
2569 unsigned long flags;
2570 local_irq_save(flags);
2571 ns = max(tsk->timestamp, task_rq(tsk)->timestamp_last_tick);
2572 ns = tsk->sched_time + (sched_clock() - ns);
2573 local_irq_restore(flags);
2578 * We place interactive tasks back into the active array, if possible.
2580 * To guarantee that this does not starve expired tasks we ignore the
2581 * interactivity of a task if the first expired task had to wait more
2582 * than a 'reasonable' amount of time. This deadline timeout is
2583 * load-dependent, as the frequency of array switched decreases with
2584 * increasing number of running tasks. We also ignore the interactivity
2585 * if a better static_prio task has expired:
2587 #define EXPIRED_STARVING(rq) \
2588 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2589 (jiffies - (rq)->expired_timestamp >= \
2590 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2591 ((rq)->curr->static_prio > (rq)->best_expired_prio))
2594 * Account user cpu time to a process.
2595 * @p: the process that the cpu time gets accounted to
2596 * @hardirq_offset: the offset to subtract from hardirq_count()
2597 * @cputime: the cpu time spent in user space since the last update
2599 void account_user_time(struct task_struct *p, cputime_t cputime)
2601 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2602 struct vx_info *vxi = p->vx_info; /* p is _always_ current */
2604 int nice = (TASK_NICE(p) > 0);
2606 p->utime = cputime_add(p->utime, cputime);
2607 vx_account_user(vxi, cputime, nice);
2609 /* Add user time to cpustat. */
2610 tmp = cputime_to_cputime64(cputime);
2612 cpustat->nice = cputime64_add(cpustat->nice, tmp);
2614 cpustat->user = cputime64_add(cpustat->user, tmp);
2618 * Account system cpu time to a process.
2619 * @p: the process that the cpu time gets accounted to
2620 * @hardirq_offset: the offset to subtract from hardirq_count()
2621 * @cputime: the cpu time spent in kernel space since the last update
2623 void account_system_time(struct task_struct *p, int hardirq_offset,
2626 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2627 struct vx_info *vxi = p->vx_info; /* p is _always_ current */
2628 runqueue_t *rq = this_rq();
2631 p->stime = cputime_add(p->stime, cputime);
2632 vx_account_system(vxi, cputime, (p == rq->idle));
2634 /* Add system time to cpustat. */
2635 tmp = cputime_to_cputime64(cputime);
2636 if (hardirq_count() - hardirq_offset)
2637 cpustat->irq = cputime64_add(cpustat->irq, tmp);
2638 else if (softirq_count())
2639 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
2640 else if (p != rq->idle)
2641 cpustat->system = cputime64_add(cpustat->system, tmp);
2642 else if (atomic_read(&rq->nr_iowait) > 0)
2643 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2645 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2646 /* Account for system time used */
2647 acct_update_integrals(p);
2651 * Account for involuntary wait time.
2652 * @p: the process from which the cpu time has been stolen
2653 * @steal: the cpu time spent in involuntary wait
2655 void account_steal_time(struct task_struct *p, cputime_t steal)
2657 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2658 cputime64_t tmp = cputime_to_cputime64(steal);
2659 runqueue_t *rq = this_rq();
2661 if (p == rq->idle) {
2662 p->stime = cputime_add(p->stime, steal);
2663 if (atomic_read(&rq->nr_iowait) > 0)
2664 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2666 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2668 cpustat->steal = cputime64_add(cpustat->steal, tmp);
2672 * This function gets called by the timer code, with HZ frequency.
2673 * We call it with interrupts disabled.
2675 * It also gets called by the fork code, when changing the parent's
2678 void scheduler_tick(void)
2680 int cpu = smp_processor_id();
2681 runqueue_t *rq = this_rq();
2682 task_t *p = current;
2683 unsigned long long now = sched_clock();
2685 update_cpu_clock(p, rq, now);
2687 rq->timestamp_last_tick = now;
2689 #if defined(CONFIG_VSERVER_HARDCPU) && defined(CONFIG_VSERVER_ACB_SCHED)
2690 vx_scheduler_tick();
2693 if (p == rq->idle) {
2694 if (wake_priority_sleeper(rq))
2696 #ifdef CONFIG_VSERVER_HARDCPU_IDLE
2697 if (!--rq->idle_tokens && !list_empty(&rq->hold_queue))
2700 rebalance_tick(cpu, rq, SCHED_IDLE);
2704 /* Task might have expired already, but not scheduled off yet */
2705 if (p->array != rq->active) {
2706 set_tsk_need_resched(p);
2709 spin_lock(&rq->lock);
2711 * The task was running during this tick - update the
2712 * time slice counter. Note: we do not update a thread's
2713 * priority until it either goes to sleep or uses up its
2714 * timeslice. This makes it possible for interactive tasks
2715 * to use up their timeslices at their highest priority levels.
2719 * RR tasks need a special form of timeslice management.
2720 * FIFO tasks have no timeslices.
2722 if ((p->policy == SCHED_RR) && vx_need_resched(p)) {
2723 p->time_slice = task_timeslice(p);
2724 p->first_time_slice = 0;
2725 set_tsk_need_resched(p);
2727 /* put it at the end of the queue: */
2728 requeue_task(p, rq->active);
2732 if (vx_need_resched(p)) {
2733 dequeue_task(p, rq->active);
2734 set_tsk_need_resched(p);
2735 p->prio = effective_prio(p);
2736 p->time_slice = task_timeslice(p);
2737 p->first_time_slice = 0;
2739 if (!rq->expired_timestamp)
2740 rq->expired_timestamp = jiffies;
2741 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2742 enqueue_task(p, rq->expired);
2743 if (p->static_prio < rq->best_expired_prio)
2744 rq->best_expired_prio = p->static_prio;
2746 enqueue_task(p, rq->active);
2749 * Prevent a too long timeslice allowing a task to monopolize
2750 * the CPU. We do this by splitting up the timeslice into
2753 * Note: this does not mean the task's timeslices expire or
2754 * get lost in any way, they just might be preempted by
2755 * another task of equal priority. (one with higher
2756 * priority would have preempted this task already.) We
2757 * requeue this task to the end of the list on this priority
2758 * level, which is in essence a round-robin of tasks with
2761 * This only applies to tasks in the interactive
2762 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2764 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2765 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2766 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2767 (p->array == rq->active)) {
2769 requeue_task(p, rq->active);
2770 set_tsk_need_resched(p);
2774 spin_unlock(&rq->lock);
2776 rebalance_tick(cpu, rq, NOT_IDLE);
2779 #ifdef CONFIG_SCHED_SMT
2780 static inline void wakeup_busy_runqueue(runqueue_t *rq)
2782 /* If an SMT runqueue is sleeping due to priority reasons wake it up */
2783 if (rq->curr == rq->idle && rq->nr_running)
2784 resched_task(rq->idle);
2787 static void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2789 struct sched_domain *tmp, *sd = NULL;
2790 cpumask_t sibling_map;
2793 for_each_domain(this_cpu, tmp)
2794 if (tmp->flags & SD_SHARE_CPUPOWER)
2801 * Unlock the current runqueue because we have to lock in
2802 * CPU order to avoid deadlocks. Caller knows that we might
2803 * unlock. We keep IRQs disabled.
2805 spin_unlock(&this_rq->lock);
2807 sibling_map = sd->span;
2809 for_each_cpu_mask(i, sibling_map)
2810 spin_lock(&cpu_rq(i)->lock);
2812 * We clear this CPU from the mask. This both simplifies the
2813 * inner loop and keps this_rq locked when we exit:
2815 cpu_clear(this_cpu, sibling_map);
2817 for_each_cpu_mask(i, sibling_map) {
2818 runqueue_t *smt_rq = cpu_rq(i);
2820 wakeup_busy_runqueue(smt_rq);
2823 for_each_cpu_mask(i, sibling_map)
2824 spin_unlock(&cpu_rq(i)->lock);
2826 * We exit with this_cpu's rq still held and IRQs
2832 * number of 'lost' timeslices this task wont be able to fully
2833 * utilize, if another task runs on a sibling. This models the
2834 * slowdown effect of other tasks running on siblings:
2836 static inline unsigned long smt_slice(task_t *p, struct sched_domain *sd)
2838 return p->time_slice * (100 - sd->per_cpu_gain) / 100;
2841 static int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2843 struct sched_domain *tmp, *sd = NULL;
2844 cpumask_t sibling_map;
2845 prio_array_t *array;
2849 for_each_domain(this_cpu, tmp)
2850 if (tmp->flags & SD_SHARE_CPUPOWER)
2857 * The same locking rules and details apply as for
2858 * wake_sleeping_dependent():
2860 spin_unlock(&this_rq->lock);
2861 sibling_map = sd->span;
2862 for_each_cpu_mask(i, sibling_map)
2863 spin_lock(&cpu_rq(i)->lock);
2864 cpu_clear(this_cpu, sibling_map);
2867 * Establish next task to be run - it might have gone away because
2868 * we released the runqueue lock above:
2870 if (!this_rq->nr_running)
2872 array = this_rq->active;
2873 if (!array->nr_active)
2874 array = this_rq->expired;
2875 BUG_ON(!array->nr_active);
2877 p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
2880 for_each_cpu_mask(i, sibling_map) {
2881 runqueue_t *smt_rq = cpu_rq(i);
2882 task_t *smt_curr = smt_rq->curr;
2884 /* Kernel threads do not participate in dependent sleeping */
2885 if (!p->mm || !smt_curr->mm || rt_task(p))
2886 goto check_smt_task;
2889 * If a user task with lower static priority than the
2890 * running task on the SMT sibling is trying to schedule,
2891 * delay it till there is proportionately less timeslice
2892 * left of the sibling task to prevent a lower priority
2893 * task from using an unfair proportion of the
2894 * physical cpu's resources. -ck
2896 if (rt_task(smt_curr)) {
2898 * With real time tasks we run non-rt tasks only
2899 * per_cpu_gain% of the time.
2901 if ((jiffies % DEF_TIMESLICE) >
2902 (sd->per_cpu_gain * DEF_TIMESLICE / 100))
2905 if (smt_curr->static_prio < p->static_prio &&
2906 !TASK_PREEMPTS_CURR(p, smt_rq) &&
2907 smt_slice(smt_curr, sd) > task_timeslice(p))
2911 if ((!smt_curr->mm && smt_curr != smt_rq->idle) ||
2915 wakeup_busy_runqueue(smt_rq);
2920 * Reschedule a lower priority task on the SMT sibling for
2921 * it to be put to sleep, or wake it up if it has been put to
2922 * sleep for priority reasons to see if it should run now.
2925 if ((jiffies % DEF_TIMESLICE) >
2926 (sd->per_cpu_gain * DEF_TIMESLICE / 100))
2927 resched_task(smt_curr);
2929 if (TASK_PREEMPTS_CURR(p, smt_rq) &&
2930 smt_slice(p, sd) > task_timeslice(smt_curr))
2931 resched_task(smt_curr);
2933 wakeup_busy_runqueue(smt_rq);
2937 for_each_cpu_mask(i, sibling_map)
2938 spin_unlock(&cpu_rq(i)->lock);
2942 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2946 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2952 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
2954 void fastcall add_preempt_count(int val)
2959 BUG_ON((preempt_count() < 0));
2960 preempt_count() += val;
2962 * Spinlock count overflowing soon?
2964 BUG_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
2966 EXPORT_SYMBOL(add_preempt_count);
2968 void fastcall sub_preempt_count(int val)
2973 BUG_ON(val > preempt_count());
2975 * Is the spinlock portion underflowing?
2977 BUG_ON((val < PREEMPT_MASK) && !(preempt_count() & PREEMPT_MASK));
2978 preempt_count() -= val;
2980 EXPORT_SYMBOL(sub_preempt_count);
2984 static inline int interactive_sleep(enum sleep_type sleep_type)
2986 return (sleep_type == SLEEP_INTERACTIVE ||
2987 sleep_type == SLEEP_INTERRUPTED);
2991 * schedule() is the main scheduler function.
2993 asmlinkage void __sched schedule(void)
2996 task_t *prev, *next;
2998 prio_array_t *array;
2999 struct list_head *queue;
3000 unsigned long long now;
3001 unsigned long run_time;
3002 int cpu, idx, new_prio;
3003 struct vx_info *vxi;
3004 #ifdef CONFIG_VSERVER_HARDCPU
3006 # ifdef CONFIG_VSERVER_ACB_SCHED
3007 int min_guarantee_ticks = VX_INVALID_TICKS;
3008 int min_best_effort_ticks = VX_INVALID_TICKS;
3013 * Test if we are atomic. Since do_exit() needs to call into
3014 * schedule() atomically, we ignore that path for now.
3015 * Otherwise, whine if we are scheduling when we should not be.
3017 if (unlikely(in_atomic() && !current->exit_state)) {
3018 printk(KERN_ERR "BUG: scheduling while atomic: "
3020 current->comm, preempt_count(), current->pid);
3023 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3028 release_kernel_lock(prev);
3029 need_resched_nonpreemptible:
3033 * The idle thread is not allowed to schedule!
3034 * Remove this check after it has been exercised a bit.
3036 if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
3037 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
3041 schedstat_inc(rq, sched_cnt);
3042 now = sched_clock();
3043 if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
3044 run_time = now - prev->timestamp;
3045 if (unlikely((long long)(now - prev->timestamp) < 0))
3048 run_time = NS_MAX_SLEEP_AVG;
3051 * Tasks charged proportionately less run_time at high sleep_avg to
3052 * delay them losing their interactive status
3054 run_time /= (CURRENT_BONUS(prev) ? : 1);
3056 spin_lock_irq(&rq->lock);
3058 if (unlikely(prev->flags & PF_DEAD))
3059 prev->state = EXIT_DEAD;
3061 switch_count = &prev->nivcsw;
3062 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3063 switch_count = &prev->nvcsw;
3064 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
3065 unlikely(signal_pending(prev))))
3066 prev->state = TASK_RUNNING;
3068 if (prev->state == TASK_UNINTERRUPTIBLE) {
3069 rq->nr_uninterruptible++;
3070 vx_uninterruptible_inc(prev);
3072 deactivate_task(prev, rq);
3076 #ifdef CONFIG_VSERVER_HARDCPU
3077 # ifdef CONFIG_VSERVER_ACB_SCHED
3080 min_guarantee_ticks = VX_INVALID_TICKS;
3081 min_best_effort_ticks = VX_INVALID_TICKS;
3084 if (!list_empty(&rq->hold_queue)) {
3085 struct list_head *l, *n;
3089 list_for_each_safe(l, n, &rq->hold_queue) {
3090 next = list_entry(l, task_t, run_list);
3091 if (vxi == next->vx_info)
3094 vxi = next->vx_info;
3095 ret = vx_tokens_recalc(vxi);
3098 vx_unhold_task(vxi, next, rq);
3101 if ((ret < 0) && (maxidle < ret))
3103 # ifdef CONFIG_VSERVER_ACB_SCHED
3105 if (IS_BEST_EFFORT(vxi)) {
3106 if (min_best_effort_ticks < ret)
3107 min_best_effort_ticks = ret;
3109 if (min_guarantee_ticks < ret)
3110 min_guarantee_ticks = ret;
3116 rq->idle_tokens = -maxidle;
3121 cpu = smp_processor_id();
3122 if (unlikely(!rq->nr_running)) {
3124 idle_balance(cpu, rq);
3125 if (!rq->nr_running) {
3127 rq->expired_timestamp = 0;
3128 wake_sleeping_dependent(cpu, rq);
3130 * wake_sleeping_dependent() might have released
3131 * the runqueue, so break out if we got new
3134 if (!rq->nr_running)
3138 if (dependent_sleeper(cpu, rq)) {
3143 * dependent_sleeper() releases and reacquires the runqueue
3144 * lock, hence go into the idle loop if the rq went
3147 if (unlikely(!rq->nr_running))
3152 if (unlikely(!array->nr_active)) {
3154 * Switch the active and expired arrays.
3156 schedstat_inc(rq, sched_switch);
3157 rq->active = rq->expired;
3158 rq->expired = array;
3160 rq->expired_timestamp = 0;
3161 rq->best_expired_prio = MAX_PRIO;
3164 idx = sched_find_first_bit(array->bitmap);
3165 queue = array->queue + idx;
3166 next = list_entry(queue->next, task_t, run_list);
3168 vxi = next->vx_info;
3169 #ifdef CONFIG_VSERVER_HARDCPU
3170 if (vx_info_flags(vxi, VXF_SCHED_PAUSE|VXF_SCHED_HARD, 0)) {
3171 int ret = vx_tokens_recalc(vxi);
3173 if (unlikely(ret <= 0)) {
3175 if ((rq->idle_tokens > -ret))
3176 rq->idle_tokens = -ret;
3177 # ifdef CONFIG_VSERVER_ACB_SCHED
3178 if (IS_BEST_EFFORT(vxi)) {
3179 if (min_best_effort_ticks < ret)
3180 min_best_effort_ticks = ret;
3182 if (min_guarantee_ticks < ret)
3183 min_guarantee_ticks = ret;
3187 vx_hold_task(vxi, next, rq);
3190 } else /* well, looks ugly but not as ugly as the ifdef-ed version */
3192 if (vx_info_flags(vxi, VXF_SCHED_PRIO, 0))
3193 vx_tokens_recalc(vxi);
3195 if (!rt_task(next) && interactive_sleep(next->sleep_type)) {
3196 unsigned long long delta = now - next->timestamp;
3197 if (unlikely((long long)(now - next->timestamp) < 0))
3200 if (next->sleep_type == SLEEP_INTERACTIVE)
3201 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
3203 array = next->array;
3204 new_prio = recalc_task_prio(next, next->timestamp + delta);
3206 if (unlikely(next->prio != new_prio)) {
3207 dequeue_task(next, array);
3208 next->prio = new_prio;
3209 enqueue_task(next, array);
3212 next->sleep_type = SLEEP_NORMAL;
3214 #if defined(CONFIG_VSERVER_HARDCPU) && defined(CONFIG_VSERVER_ACB_SCHED)
3215 if (next == rq->idle && !list_empty(&rq->hold_queue)) {
3216 if (min_best_effort_ticks != VX_INVALID_TICKS) {
3217 vx_advance_best_effort_ticks(-min_best_effort_ticks);
3218 goto drain_hold_queue;
3220 if (min_guarantee_ticks != VX_INVALID_TICKS) {
3221 vx_advance_guaranteed_ticks(-min_guarantee_ticks);
3222 goto drain_hold_queue;
3226 if (next == rq->idle)
3227 schedstat_inc(rq, sched_goidle);
3229 prefetch_stack(next);
3230 clear_tsk_need_resched(prev);
3231 rcu_qsctr_inc(task_cpu(prev));
3233 update_cpu_clock(prev, rq, now);
3235 prev->sleep_avg -= run_time;
3236 if ((long)prev->sleep_avg <= 0)
3237 prev->sleep_avg = 0;
3238 prev->timestamp = prev->last_ran = now;
3240 sched_info_switch(prev, next);
3241 if (likely(prev != next)) {
3242 next->timestamp = now;
3247 prepare_task_switch(rq, next);
3248 prev = context_switch(rq, prev, next);
3251 * this_rq must be evaluated again because prev may have moved
3252 * CPUs since it called schedule(), thus the 'rq' on its stack
3253 * frame will be invalid.
3255 finish_task_switch(this_rq(), prev);
3257 spin_unlock_irq(&rq->lock);
3260 if (unlikely(reacquire_kernel_lock(prev) < 0))
3261 goto need_resched_nonpreemptible;
3262 preempt_enable_no_resched();
3263 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3267 EXPORT_SYMBOL(schedule);
3269 #ifdef CONFIG_PREEMPT
3271 * this is is the entry point to schedule() from in-kernel preemption
3272 * off of preempt_enable. Kernel preemptions off return from interrupt
3273 * occur there and call schedule directly.
3275 asmlinkage void __sched preempt_schedule(void)
3277 struct thread_info *ti = current_thread_info();
3278 #ifdef CONFIG_PREEMPT_BKL
3279 struct task_struct *task = current;
3280 int saved_lock_depth;
3283 * If there is a non-zero preempt_count or interrupts are disabled,
3284 * we do not want to preempt the current task. Just return..
3286 if (unlikely(ti->preempt_count || irqs_disabled()))
3290 add_preempt_count(PREEMPT_ACTIVE);
3292 * We keep the big kernel semaphore locked, but we
3293 * clear ->lock_depth so that schedule() doesnt
3294 * auto-release the semaphore:
3296 #ifdef CONFIG_PREEMPT_BKL
3297 saved_lock_depth = task->lock_depth;
3298 task->lock_depth = -1;
3301 #ifdef CONFIG_PREEMPT_BKL
3302 task->lock_depth = saved_lock_depth;
3304 sub_preempt_count(PREEMPT_ACTIVE);
3306 /* we could miss a preemption opportunity between schedule and now */
3308 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3312 EXPORT_SYMBOL(preempt_schedule);
3315 * this is is the entry point to schedule() from kernel preemption
3316 * off of irq context.
3317 * Note, that this is called and return with irqs disabled. This will
3318 * protect us against recursive calling from irq.
3320 asmlinkage void __sched preempt_schedule_irq(void)
3322 struct thread_info *ti = current_thread_info();
3323 #ifdef CONFIG_PREEMPT_BKL
3324 struct task_struct *task = current;
3325 int saved_lock_depth;
3327 /* Catch callers which need to be fixed*/
3328 BUG_ON(ti->preempt_count || !irqs_disabled());
3331 add_preempt_count(PREEMPT_ACTIVE);
3333 * We keep the big kernel semaphore locked, but we
3334 * clear ->lock_depth so that schedule() doesnt
3335 * auto-release the semaphore:
3337 #ifdef CONFIG_PREEMPT_BKL
3338 saved_lock_depth = task->lock_depth;
3339 task->lock_depth = -1;
3343 local_irq_disable();
3344 #ifdef CONFIG_PREEMPT_BKL
3345 task->lock_depth = saved_lock_depth;
3347 sub_preempt_count(PREEMPT_ACTIVE);
3349 /* we could miss a preemption opportunity between schedule and now */
3351 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3355 #endif /* CONFIG_PREEMPT */
3357 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
3360 task_t *p = curr->private;
3361 return try_to_wake_up(p, mode, sync);
3364 EXPORT_SYMBOL(default_wake_function);
3367 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3368 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3369 * number) then we wake all the non-exclusive tasks and one exclusive task.
3371 * There are circumstances in which we can try to wake a task which has already
3372 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3373 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3375 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3376 int nr_exclusive, int sync, void *key)
3378 struct list_head *tmp, *next;
3380 list_for_each_safe(tmp, next, &q->task_list) {
3383 curr = list_entry(tmp, wait_queue_t, task_list);
3384 flags = curr->flags;
3385 if (curr->func(curr, mode, sync, key) &&
3386 (flags & WQ_FLAG_EXCLUSIVE) &&
3393 * __wake_up - wake up threads blocked on a waitqueue.
3395 * @mode: which threads
3396 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3397 * @key: is directly passed to the wakeup function
3399 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3400 int nr_exclusive, void *key)
3402 unsigned long flags;
3404 spin_lock_irqsave(&q->lock, flags);
3405 __wake_up_common(q, mode, nr_exclusive, 0, key);
3406 spin_unlock_irqrestore(&q->lock, flags);
3409 EXPORT_SYMBOL(__wake_up);
3412 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3414 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3416 __wake_up_common(q, mode, 1, 0, NULL);
3420 * __wake_up_sync - wake up threads blocked on a waitqueue.
3422 * @mode: which threads
3423 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3425 * The sync wakeup differs that the waker knows that it will schedule
3426 * away soon, so while the target thread will be woken up, it will not
3427 * be migrated to another CPU - ie. the two threads are 'synchronized'
3428 * with each other. This can prevent needless bouncing between CPUs.
3430 * On UP it can prevent extra preemption.
3433 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3435 unsigned long flags;
3441 if (unlikely(!nr_exclusive))
3444 spin_lock_irqsave(&q->lock, flags);
3445 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3446 spin_unlock_irqrestore(&q->lock, flags);
3448 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3450 void fastcall complete(struct completion *x)
3452 unsigned long flags;
3454 spin_lock_irqsave(&x->wait.lock, flags);
3456 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3458 spin_unlock_irqrestore(&x->wait.lock, flags);
3460 EXPORT_SYMBOL(complete);
3462 void fastcall complete_all(struct completion *x)
3464 unsigned long flags;
3466 spin_lock_irqsave(&x->wait.lock, flags);
3467 x->done += UINT_MAX/2;
3468 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3470 spin_unlock_irqrestore(&x->wait.lock, flags);
3472 EXPORT_SYMBOL(complete_all);
3474 void fastcall __sched wait_for_completion(struct completion *x)
3477 spin_lock_irq(&x->wait.lock);
3479 DECLARE_WAITQUEUE(wait, current);
3481 wait.flags |= WQ_FLAG_EXCLUSIVE;
3482 __add_wait_queue_tail(&x->wait, &wait);
3484 __set_current_state(TASK_UNINTERRUPTIBLE);
3485 spin_unlock_irq(&x->wait.lock);
3487 spin_lock_irq(&x->wait.lock);
3489 __remove_wait_queue(&x->wait, &wait);
3492 spin_unlock_irq(&x->wait.lock);
3494 EXPORT_SYMBOL(wait_for_completion);
3496 unsigned long fastcall __sched
3497 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3501 spin_lock_irq(&x->wait.lock);
3503 DECLARE_WAITQUEUE(wait, current);
3505 wait.flags |= WQ_FLAG_EXCLUSIVE;
3506 __add_wait_queue_tail(&x->wait, &wait);
3508 __set_current_state(TASK_UNINTERRUPTIBLE);
3509 spin_unlock_irq(&x->wait.lock);
3510 timeout = schedule_timeout(timeout);
3511 spin_lock_irq(&x->wait.lock);
3513 __remove_wait_queue(&x->wait, &wait);
3517 __remove_wait_queue(&x->wait, &wait);
3521 spin_unlock_irq(&x->wait.lock);
3524 EXPORT_SYMBOL(wait_for_completion_timeout);
3526 int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3532 spin_lock_irq(&x->wait.lock);
3534 DECLARE_WAITQUEUE(wait, current);
3536 wait.flags |= WQ_FLAG_EXCLUSIVE;
3537 __add_wait_queue_tail(&x->wait, &wait);
3539 if (signal_pending(current)) {
3541 __remove_wait_queue(&x->wait, &wait);
3544 __set_current_state(TASK_INTERRUPTIBLE);
3545 spin_unlock_irq(&x->wait.lock);
3547 spin_lock_irq(&x->wait.lock);
3549 __remove_wait_queue(&x->wait, &wait);
3553 spin_unlock_irq(&x->wait.lock);
3557 EXPORT_SYMBOL(wait_for_completion_interruptible);
3559 unsigned long fastcall __sched
3560 wait_for_completion_interruptible_timeout(struct completion *x,
3561 unsigned long timeout)
3565 spin_lock_irq(&x->wait.lock);
3567 DECLARE_WAITQUEUE(wait, current);
3569 wait.flags |= WQ_FLAG_EXCLUSIVE;
3570 __add_wait_queue_tail(&x->wait, &wait);
3572 if (signal_pending(current)) {
3573 timeout = -ERESTARTSYS;
3574 __remove_wait_queue(&x->wait, &wait);
3577 __set_current_state(TASK_INTERRUPTIBLE);
3578 spin_unlock_irq(&x->wait.lock);
3579 timeout = schedule_timeout(timeout);
3580 spin_lock_irq(&x->wait.lock);
3582 __remove_wait_queue(&x->wait, &wait);
3586 __remove_wait_queue(&x->wait, &wait);
3590 spin_unlock_irq(&x->wait.lock);
3593 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3596 #define SLEEP_ON_VAR \
3597 unsigned long flags; \
3598 wait_queue_t wait; \
3599 init_waitqueue_entry(&wait, current);
3601 #define SLEEP_ON_HEAD \
3602 spin_lock_irqsave(&q->lock,flags); \
3603 __add_wait_queue(q, &wait); \
3604 spin_unlock(&q->lock);
3606 #define SLEEP_ON_TAIL \
3607 spin_lock_irq(&q->lock); \
3608 __remove_wait_queue(q, &wait); \
3609 spin_unlock_irqrestore(&q->lock, flags);
3611 #define SLEEP_ON_BKLCHECK \
3612 if (unlikely(!kernel_locked()) && \
3613 sleep_on_bkl_warnings < 10) { \
3614 sleep_on_bkl_warnings++; \
3618 static int sleep_on_bkl_warnings;
3620 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3626 current->state = TASK_INTERRUPTIBLE;
3633 EXPORT_SYMBOL(interruptible_sleep_on);
3635 long fastcall __sched
3636 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3642 current->state = TASK_INTERRUPTIBLE;
3645 timeout = schedule_timeout(timeout);
3651 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3653 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3659 current->state = TASK_UNINTERRUPTIBLE;
3662 timeout = schedule_timeout(timeout);
3668 EXPORT_SYMBOL(sleep_on_timeout);
3670 void set_user_nice(task_t *p, long nice)
3672 unsigned long flags;
3673 prio_array_t *array;
3675 int old_prio, new_prio, delta;
3677 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3680 * We have to be careful, if called from sys_setpriority(),
3681 * the task might be in the middle of scheduling on another CPU.
3683 rq = task_rq_lock(p, &flags);
3685 * The RT priorities are set via sched_setscheduler(), but we still
3686 * allow the 'normal' nice value to be set - but as expected
3687 * it wont have any effect on scheduling until the task is
3688 * not SCHED_NORMAL/SCHED_BATCH:
3691 p->static_prio = NICE_TO_PRIO(nice);
3696 dequeue_task(p, array);
3699 new_prio = NICE_TO_PRIO(nice);
3700 delta = new_prio - old_prio;
3701 p->static_prio = NICE_TO_PRIO(nice);
3705 enqueue_task(p, array);
3707 * If the task increased its priority or is running and
3708 * lowered its priority, then reschedule its CPU:
3710 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3711 resched_task(rq->curr);
3714 task_rq_unlock(rq, &flags);
3717 EXPORT_SYMBOL(set_user_nice);
3720 * can_nice - check if a task can reduce its nice value
3724 int can_nice(const task_t *p, const int nice)
3726 /* convert nice value [19,-20] to rlimit style value [1,40] */
3727 int nice_rlim = 20 - nice;
3728 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
3729 capable(CAP_SYS_NICE));
3732 #ifdef __ARCH_WANT_SYS_NICE
3735 * sys_nice - change the priority of the current process.
3736 * @increment: priority increment
3738 * sys_setpriority is a more generic, but much slower function that
3739 * does similar things.
3741 asmlinkage long sys_nice(int increment)
3747 * Setpriority might change our priority at the same moment.
3748 * We don't have to worry. Conceptually one call occurs first
3749 * and we have a single winner.
3751 if (increment < -40)
3756 nice = PRIO_TO_NICE(current->static_prio) + increment;
3762 if (increment < 0 && !can_nice(current, nice))
3763 return vx_flags(VXF_IGNEG_NICE, 0) ? 0 : -EPERM;
3765 retval = security_task_setnice(current, nice);
3769 set_user_nice(current, nice);
3776 * task_prio - return the priority value of a given task.
3777 * @p: the task in question.
3779 * This is the priority value as seen by users in /proc.
3780 * RT tasks are offset by -200. Normal tasks are centered
3781 * around 0, value goes from -16 to +15.
3783 int task_prio(const task_t *p)
3785 return p->prio - MAX_RT_PRIO;
3789 * task_nice - return the nice value of a given task.
3790 * @p: the task in question.
3792 int task_nice(const task_t *p)
3794 return TASK_NICE(p);
3796 EXPORT_SYMBOL_GPL(task_nice);
3799 * idle_cpu - is a given cpu idle currently?
3800 * @cpu: the processor in question.
3802 int idle_cpu(int cpu)
3804 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3808 * idle_task - return the idle task for a given cpu.
3809 * @cpu: the processor in question.
3811 task_t *idle_task(int cpu)
3813 return cpu_rq(cpu)->idle;
3817 * find_process_by_pid - find a process with a matching PID value.
3818 * @pid: the pid in question.
3820 static inline task_t *find_process_by_pid(pid_t pid)
3822 return pid ? find_task_by_pid(pid) : current;
3825 /* Actually do priority change: must hold rq lock. */
3826 static void __setscheduler(struct task_struct *p, int policy, int prio)
3830 p->rt_priority = prio;
3831 if (policy != SCHED_NORMAL && policy != SCHED_BATCH) {
3832 p->prio = MAX_RT_PRIO-1 - p->rt_priority;
3834 p->prio = p->static_prio;
3836 * SCHED_BATCH tasks are treated as perpetual CPU hogs:
3838 if (policy == SCHED_BATCH)
3844 * sched_setscheduler - change the scheduling policy and/or RT priority of
3846 * @p: the task in question.
3847 * @policy: new policy.
3848 * @param: structure containing the new RT priority.
3850 int sched_setscheduler(struct task_struct *p, int policy,
3851 struct sched_param *param)
3854 int oldprio, oldpolicy = -1;
3855 prio_array_t *array;
3856 unsigned long flags;
3860 /* double check policy once rq lock held */
3862 policy = oldpolicy = p->policy;
3863 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
3864 policy != SCHED_NORMAL && policy != SCHED_BATCH)
3867 * Valid priorities for SCHED_FIFO and SCHED_RR are
3868 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL and
3871 if (param->sched_priority < 0 ||
3872 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
3873 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
3875 if ((policy == SCHED_NORMAL || policy == SCHED_BATCH)
3876 != (param->sched_priority == 0))
3880 * Allow unprivileged RT tasks to decrease priority:
3882 if (!capable(CAP_SYS_NICE)) {
3884 * can't change policy, except between SCHED_NORMAL
3887 if (((policy != SCHED_NORMAL && p->policy != SCHED_BATCH) &&
3888 (policy != SCHED_BATCH && p->policy != SCHED_NORMAL)) &&
3889 !p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
3891 /* can't increase priority */
3892 if ((policy != SCHED_NORMAL && policy != SCHED_BATCH) &&
3893 param->sched_priority > p->rt_priority &&
3894 param->sched_priority >
3895 p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
3897 /* can't change other user's priorities */
3898 if ((current->euid != p->euid) &&
3899 (current->euid != p->uid))
3903 retval = security_task_setscheduler(p, policy, param);
3907 * To be able to change p->policy safely, the apropriate
3908 * runqueue lock must be held.
3910 rq = task_rq_lock(p, &flags);
3911 /* recheck policy now with rq lock held */
3912 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3913 policy = oldpolicy = -1;
3914 task_rq_unlock(rq, &flags);
3919 deactivate_task(p, rq);
3921 __setscheduler(p, policy, param->sched_priority);
3923 vx_activate_task(p);
3924 __activate_task(p, rq);
3926 * Reschedule if we are currently running on this runqueue and
3927 * our priority decreased, or if we are not currently running on
3928 * this runqueue and our priority is higher than the current's
3930 if (task_running(rq, p)) {
3931 if (p->prio > oldprio)
3932 resched_task(rq->curr);
3933 } else if (TASK_PREEMPTS_CURR(p, rq))
3934 resched_task(rq->curr);
3936 task_rq_unlock(rq, &flags);
3939 EXPORT_SYMBOL_GPL(sched_setscheduler);
3942 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3945 struct sched_param lparam;
3946 struct task_struct *p;
3948 if (!param || pid < 0)
3950 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
3952 read_lock_irq(&tasklist_lock);
3953 p = find_process_by_pid(pid);
3955 read_unlock_irq(&tasklist_lock);
3958 retval = sched_setscheduler(p, policy, &lparam);
3959 read_unlock_irq(&tasklist_lock);
3964 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3965 * @pid: the pid in question.
3966 * @policy: new policy.
3967 * @param: structure containing the new RT priority.
3969 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3970 struct sched_param __user *param)
3972 /* negative values for policy are not valid */
3976 return do_sched_setscheduler(pid, policy, param);
3980 * sys_sched_setparam - set/change the RT priority of a thread
3981 * @pid: the pid in question.
3982 * @param: structure containing the new RT priority.
3984 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3986 return do_sched_setscheduler(pid, -1, param);
3990 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3991 * @pid: the pid in question.
3993 asmlinkage long sys_sched_getscheduler(pid_t pid)
3995 int retval = -EINVAL;
4002 read_lock(&tasklist_lock);
4003 p = find_process_by_pid(pid);
4005 retval = security_task_getscheduler(p);
4009 read_unlock(&tasklist_lock);
4016 * sys_sched_getscheduler - get the RT priority of a thread
4017 * @pid: the pid in question.
4018 * @param: structure containing the RT priority.
4020 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
4022 struct sched_param lp;
4023 int retval = -EINVAL;
4026 if (!param || pid < 0)
4029 read_lock(&tasklist_lock);
4030 p = find_process_by_pid(pid);
4035 retval = security_task_getscheduler(p);
4039 lp.sched_priority = p->rt_priority;
4040 read_unlock(&tasklist_lock);
4043 * This one might sleep, we cannot do it with a spinlock held ...
4045 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4051 read_unlock(&tasklist_lock);
4055 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
4059 cpumask_t cpus_allowed;
4062 read_lock(&tasklist_lock);
4064 p = find_process_by_pid(pid);
4066 read_unlock(&tasklist_lock);
4067 unlock_cpu_hotplug();
4072 * It is not safe to call set_cpus_allowed with the
4073 * tasklist_lock held. We will bump the task_struct's
4074 * usage count and then drop tasklist_lock.
4077 read_unlock(&tasklist_lock);
4080 if ((current->euid != p->euid) && (current->euid != p->uid) &&
4081 !capable(CAP_SYS_NICE))
4084 cpus_allowed = cpuset_cpus_allowed(p);
4085 cpus_and(new_mask, new_mask, cpus_allowed);
4086 retval = set_cpus_allowed(p, new_mask);
4090 unlock_cpu_hotplug();
4094 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4095 cpumask_t *new_mask)
4097 if (len < sizeof(cpumask_t)) {
4098 memset(new_mask, 0, sizeof(cpumask_t));
4099 } else if (len > sizeof(cpumask_t)) {
4100 len = sizeof(cpumask_t);
4102 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4106 * sys_sched_setaffinity - set the cpu affinity of a process
4107 * @pid: pid of the process
4108 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4109 * @user_mask_ptr: user-space pointer to the new cpu mask
4111 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
4112 unsigned long __user *user_mask_ptr)
4117 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
4121 return sched_setaffinity(pid, new_mask);
4125 * Represents all cpu's present in the system
4126 * In systems capable of hotplug, this map could dynamically grow
4127 * as new cpu's are detected in the system via any platform specific
4128 * method, such as ACPI for e.g.
4131 cpumask_t cpu_present_map __read_mostly;
4132 EXPORT_SYMBOL(cpu_present_map);
4135 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
4136 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
4139 long sched_getaffinity(pid_t pid, cpumask_t *mask)
4145 read_lock(&tasklist_lock);
4148 p = find_process_by_pid(pid);
4153 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
4156 read_unlock(&tasklist_lock);
4157 unlock_cpu_hotplug();
4165 * sys_sched_getaffinity - get the cpu affinity of a process
4166 * @pid: pid of the process
4167 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4168 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4170 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
4171 unsigned long __user *user_mask_ptr)
4176 if (len < sizeof(cpumask_t))
4179 ret = sched_getaffinity(pid, &mask);
4183 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
4186 return sizeof(cpumask_t);
4190 * sys_sched_yield - yield the current processor to other threads.
4192 * this function yields the current CPU by moving the calling thread
4193 * to the expired array. If there are no other threads running on this
4194 * CPU then this function will return.
4196 asmlinkage long sys_sched_yield(void)
4198 runqueue_t *rq = this_rq_lock();
4199 prio_array_t *array = current->array;
4200 prio_array_t *target = rq->expired;
4202 schedstat_inc(rq, yld_cnt);
4204 * We implement yielding by moving the task into the expired
4207 * (special rule: RT tasks will just roundrobin in the active
4210 if (rt_task(current))
4211 target = rq->active;
4213 if (array->nr_active == 1) {
4214 schedstat_inc(rq, yld_act_empty);
4215 if (!rq->expired->nr_active)
4216 schedstat_inc(rq, yld_both_empty);
4217 } else if (!rq->expired->nr_active)
4218 schedstat_inc(rq, yld_exp_empty);
4220 if (array != target) {
4221 dequeue_task(current, array);
4222 enqueue_task(current, target);
4225 * requeue_task is cheaper so perform that if possible.
4227 requeue_task(current, array);
4230 * Since we are going to call schedule() anyway, there's
4231 * no need to preempt or enable interrupts:
4233 __release(rq->lock);
4234 _raw_spin_unlock(&rq->lock);
4235 preempt_enable_no_resched();
4242 static inline int __resched_legal(int expected_preempt_count)
4244 if (unlikely(preempt_count() != expected_preempt_count))
4246 if (unlikely(system_state != SYSTEM_RUNNING))
4251 static void __cond_resched(void)
4254 * The BKS might be reacquired before we have dropped
4255 * PREEMPT_ACTIVE, which could trigger a second
4256 * cond_resched() call.
4259 add_preempt_count(PREEMPT_ACTIVE);
4261 sub_preempt_count(PREEMPT_ACTIVE);
4262 } while (need_resched());
4265 int __sched cond_resched(void)
4267 if (need_resched() && __resched_legal(0)) {
4273 EXPORT_SYMBOL(cond_resched);
4276 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4277 * call schedule, and on return reacquire the lock.
4279 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4280 * operations here to prevent schedule() from being called twice (once via
4281 * spin_unlock(), once by hand).
4283 int cond_resched_lock(spinlock_t *lock)
4287 if (need_lockbreak(lock)) {
4293 if (need_resched() && __resched_legal(1)) {
4294 _raw_spin_unlock(lock);
4295 preempt_enable_no_resched();
4302 EXPORT_SYMBOL(cond_resched_lock);
4304 int __sched cond_resched_softirq(void)
4306 BUG_ON(!in_softirq());
4308 if (need_resched() && __resched_legal(0)) {
4309 __local_bh_enable();
4316 EXPORT_SYMBOL(cond_resched_softirq);
4319 * yield - yield the current processor to other threads.
4321 * this is a shortcut for kernel-space yielding - it marks the
4322 * thread runnable and calls sys_sched_yield().
4324 void __sched yield(void)
4326 set_current_state(TASK_RUNNING);
4330 EXPORT_SYMBOL(yield);
4333 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4334 * that process accounting knows that this is a task in IO wait state.
4336 * But don't do that if it is a deliberate, throttling IO wait (this task
4337 * has set its backing_dev_info: the queue against which it should throttle)
4339 void __sched io_schedule(void)
4341 struct runqueue *rq = &per_cpu(runqueues, raw_smp_processor_id());
4343 atomic_inc(&rq->nr_iowait);
4345 atomic_dec(&rq->nr_iowait);
4348 EXPORT_SYMBOL(io_schedule);
4350 long __sched io_schedule_timeout(long timeout)
4352 struct runqueue *rq = &per_cpu(runqueues, raw_smp_processor_id());
4355 atomic_inc(&rq->nr_iowait);
4356 ret = schedule_timeout(timeout);
4357 atomic_dec(&rq->nr_iowait);
4362 * sys_sched_get_priority_max - return maximum RT priority.
4363 * @policy: scheduling class.
4365 * this syscall returns the maximum rt_priority that can be used
4366 * by a given scheduling class.
4368 asmlinkage long sys_sched_get_priority_max(int policy)
4375 ret = MAX_USER_RT_PRIO-1;
4386 * sys_sched_get_priority_min - return minimum RT priority.
4387 * @policy: scheduling class.
4389 * this syscall returns the minimum rt_priority that can be used
4390 * by a given scheduling class.
4392 asmlinkage long sys_sched_get_priority_min(int policy)
4409 * sys_sched_rr_get_interval - return the default timeslice of a process.
4410 * @pid: pid of the process.
4411 * @interval: userspace pointer to the timeslice value.
4413 * this syscall writes the default timeslice value of a given process
4414 * into the user-space timespec buffer. A value of '0' means infinity.
4417 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4419 int retval = -EINVAL;
4427 read_lock(&tasklist_lock);
4428 p = find_process_by_pid(pid);
4432 retval = security_task_getscheduler(p);
4436 jiffies_to_timespec(p->policy & SCHED_FIFO ?
4437 0 : task_timeslice(p), &t);
4438 read_unlock(&tasklist_lock);
4439 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4443 read_unlock(&tasklist_lock);
4447 static inline struct task_struct *eldest_child(struct task_struct *p)
4449 if (list_empty(&p->children)) return NULL;
4450 return list_entry(p->children.next,struct task_struct,sibling);
4453 static inline struct task_struct *older_sibling(struct task_struct *p)
4455 if (p->sibling.prev==&p->parent->children) return NULL;
4456 return list_entry(p->sibling.prev,struct task_struct,sibling);
4459 static inline struct task_struct *younger_sibling(struct task_struct *p)
4461 if (p->sibling.next==&p->parent->children) return NULL;
4462 return list_entry(p->sibling.next,struct task_struct,sibling);
4465 static void show_task(task_t *p)
4469 unsigned long free = 0;
4470 static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
4472 printk("%-13.13s ", p->comm);
4473 state = p->state ? __ffs(p->state) + 1 : 0;
4474 if (state < ARRAY_SIZE(stat_nam))
4475 printk(stat_nam[state]);
4478 #if (BITS_PER_LONG == 32)
4479 if (state == TASK_RUNNING)
4480 printk(" running ");
4482 printk(" %08lX ", thread_saved_pc(p));
4484 if (state == TASK_RUNNING)
4485 printk(" running task ");
4487 printk(" %016lx ", thread_saved_pc(p));
4489 #ifdef CONFIG_DEBUG_STACK_USAGE
4491 unsigned long *n = end_of_stack(p);
4494 free = (unsigned long)n - (unsigned long)end_of_stack(p);
4497 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
4498 if ((relative = eldest_child(p)))
4499 printk("%5d ", relative->pid);
4502 if ((relative = younger_sibling(p)))
4503 printk("%7d", relative->pid);
4506 if ((relative = older_sibling(p)))
4507 printk(" %5d", relative->pid);
4511 printk(" (L-TLB)\n");
4513 printk(" (NOTLB)\n");
4515 if (state != TASK_RUNNING)
4516 show_stack(p, NULL);
4519 void show_state(void)
4523 #if (BITS_PER_LONG == 32)
4526 printk(" task PC pid father child younger older\n");
4530 printk(" task PC pid father child younger older\n");
4532 read_lock(&tasklist_lock);
4533 do_each_thread(g, p) {
4535 * reset the NMI-timeout, listing all files on a slow
4536 * console might take alot of time:
4538 touch_nmi_watchdog();
4540 } while_each_thread(g, p);
4542 read_unlock(&tasklist_lock);
4543 mutex_debug_show_all_locks();
4547 * init_idle - set up an idle thread for a given CPU
4548 * @idle: task in question
4549 * @cpu: cpu the idle task belongs to
4551 * NOTE: this function does not set the idle thread's NEED_RESCHED
4552 * flag, to make booting more robust.
4554 void __devinit init_idle(task_t *idle, int cpu)
4556 runqueue_t *rq = cpu_rq(cpu);
4557 unsigned long flags;
4559 idle->timestamp = sched_clock();
4560 idle->sleep_avg = 0;
4562 idle->prio = MAX_PRIO;
4563 idle->state = TASK_RUNNING;
4564 idle->cpus_allowed = cpumask_of_cpu(cpu);
4565 set_task_cpu(idle, cpu);
4567 spin_lock_irqsave(&rq->lock, flags);
4568 rq->curr = rq->idle = idle;
4569 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
4572 spin_unlock_irqrestore(&rq->lock, flags);
4574 /* Set the preempt count _outside_ the spinlocks! */
4575 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4576 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
4578 task_thread_info(idle)->preempt_count = 0;
4583 * In a system that switches off the HZ timer nohz_cpu_mask
4584 * indicates which cpus entered this state. This is used
4585 * in the rcu update to wait only for active cpus. For system
4586 * which do not switch off the HZ timer nohz_cpu_mask should
4587 * always be CPU_MASK_NONE.
4589 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4593 * This is how migration works:
4595 * 1) we queue a migration_req_t structure in the source CPU's
4596 * runqueue and wake up that CPU's migration thread.
4597 * 2) we down() the locked semaphore => thread blocks.
4598 * 3) migration thread wakes up (implicitly it forces the migrated
4599 * thread off the CPU)
4600 * 4) it gets the migration request and checks whether the migrated
4601 * task is still in the wrong runqueue.
4602 * 5) if it's in the wrong runqueue then the migration thread removes
4603 * it and puts it into the right queue.
4604 * 6) migration thread up()s the semaphore.
4605 * 7) we wake up and the migration is done.
4609 * Change a given task's CPU affinity. Migrate the thread to a
4610 * proper CPU and schedule it away if the CPU it's executing on
4611 * is removed from the allowed bitmask.
4613 * NOTE: the caller must have a valid reference to the task, the
4614 * task must not exit() & deallocate itself prematurely. The
4615 * call is not atomic; no spinlocks may be held.
4617 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
4619 unsigned long flags;
4621 migration_req_t req;
4624 rq = task_rq_lock(p, &flags);
4625 if (!cpus_intersects(new_mask, cpu_online_map)) {
4630 p->cpus_allowed = new_mask;
4631 /* Can the task run on the task's current CPU? If so, we're done */
4632 if (cpu_isset(task_cpu(p), new_mask))
4635 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4636 /* Need help from migration thread: drop lock and wait. */
4637 task_rq_unlock(rq, &flags);
4638 wake_up_process(rq->migration_thread);
4639 wait_for_completion(&req.done);
4640 tlb_migrate_finish(p->mm);
4644 task_rq_unlock(rq, &flags);
4648 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4651 * Move (not current) task off this cpu, onto dest cpu. We're doing
4652 * this because either it can't run here any more (set_cpus_allowed()
4653 * away from this CPU, or CPU going down), or because we're
4654 * attempting to rebalance this task on exec (sched_exec).
4656 * So we race with normal scheduler movements, but that's OK, as long
4657 * as the task is no longer on this CPU.
4659 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4661 runqueue_t *rq_dest, *rq_src;
4663 if (unlikely(cpu_is_offline(dest_cpu)))
4666 rq_src = cpu_rq(src_cpu);
4667 rq_dest = cpu_rq(dest_cpu);
4669 double_rq_lock(rq_src, rq_dest);
4670 /* Already moved. */
4671 if (task_cpu(p) != src_cpu)
4673 /* Affinity changed (again). */
4674 if (!cpu_isset(dest_cpu, p->cpus_allowed))
4677 set_task_cpu(p, dest_cpu);
4680 * Sync timestamp with rq_dest's before activating.
4681 * The same thing could be achieved by doing this step
4682 * afterwards, and pretending it was a local activate.
4683 * This way is cleaner and logically correct.
4685 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4686 + rq_dest->timestamp_last_tick;
4687 deactivate_task(p, rq_src);
4688 activate_task(p, rq_dest, 0);
4689 if (TASK_PREEMPTS_CURR(p, rq_dest))
4690 resched_task(rq_dest->curr);
4694 double_rq_unlock(rq_src, rq_dest);
4698 * migration_thread - this is a highprio system thread that performs
4699 * thread migration by bumping thread off CPU then 'pushing' onto
4702 static int migration_thread(void *data)
4705 int cpu = (long)data;
4708 BUG_ON(rq->migration_thread != current);
4710 set_current_state(TASK_INTERRUPTIBLE);
4711 while (!kthread_should_stop()) {
4712 struct list_head *head;
4713 migration_req_t *req;
4717 spin_lock_irq(&rq->lock);
4719 if (cpu_is_offline(cpu)) {
4720 spin_unlock_irq(&rq->lock);
4724 if (rq->active_balance) {
4725 active_load_balance(rq, cpu);
4726 rq->active_balance = 0;
4729 head = &rq->migration_queue;
4731 if (list_empty(head)) {
4732 spin_unlock_irq(&rq->lock);
4734 set_current_state(TASK_INTERRUPTIBLE);
4737 req = list_entry(head->next, migration_req_t, list);
4738 list_del_init(head->next);
4740 spin_unlock(&rq->lock);
4741 __migrate_task(req->task, cpu, req->dest_cpu);
4744 complete(&req->done);
4746 __set_current_state(TASK_RUNNING);
4750 /* Wait for kthread_stop */
4751 set_current_state(TASK_INTERRUPTIBLE);
4752 while (!kthread_should_stop()) {
4754 set_current_state(TASK_INTERRUPTIBLE);
4756 __set_current_state(TASK_RUNNING);
4760 #ifdef CONFIG_HOTPLUG_CPU
4761 /* Figure out where task on dead CPU should go, use force if neccessary. */
4762 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
4768 mask = node_to_cpumask(cpu_to_node(dead_cpu));
4769 cpus_and(mask, mask, tsk->cpus_allowed);
4770 dest_cpu = any_online_cpu(mask);
4772 /* On any allowed CPU? */
4773 if (dest_cpu == NR_CPUS)
4774 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4776 /* No more Mr. Nice Guy. */
4777 if (dest_cpu == NR_CPUS) {
4778 cpus_setall(tsk->cpus_allowed);
4779 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4782 * Don't tell them about moving exiting tasks or
4783 * kernel threads (both mm NULL), since they never
4786 if (tsk->mm && printk_ratelimit())
4787 printk(KERN_INFO "process %d (%s) no "
4788 "longer affine to cpu%d\n",
4789 tsk->pid, tsk->comm, dead_cpu);
4791 __migrate_task(tsk, dead_cpu, dest_cpu);
4795 * While a dead CPU has no uninterruptible tasks queued at this point,
4796 * it might still have a nonzero ->nr_uninterruptible counter, because
4797 * for performance reasons the counter is not stricly tracking tasks to
4798 * their home CPUs. So we just add the counter to another CPU's counter,
4799 * to keep the global sum constant after CPU-down:
4801 static void migrate_nr_uninterruptible(runqueue_t *rq_src)
4803 runqueue_t *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
4804 unsigned long flags;
4806 local_irq_save(flags);
4807 double_rq_lock(rq_src, rq_dest);
4808 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
4809 rq_src->nr_uninterruptible = 0;
4810 double_rq_unlock(rq_src, rq_dest);
4811 local_irq_restore(flags);
4814 /* Run through task list and migrate tasks from the dead cpu. */
4815 static void migrate_live_tasks(int src_cpu)
4817 struct task_struct *tsk, *t;
4819 write_lock_irq(&tasklist_lock);
4821 do_each_thread(t, tsk) {
4825 if (task_cpu(tsk) == src_cpu)
4826 move_task_off_dead_cpu(src_cpu, tsk);
4827 } while_each_thread(t, tsk);
4829 write_unlock_irq(&tasklist_lock);
4832 /* Schedules idle task to be the next runnable task on current CPU.
4833 * It does so by boosting its priority to highest possible and adding it to
4834 * the _front_ of runqueue. Used by CPU offline code.
4836 void sched_idle_next(void)
4838 int cpu = smp_processor_id();
4839 runqueue_t *rq = this_rq();
4840 struct task_struct *p = rq->idle;
4841 unsigned long flags;
4843 /* cpu has to be offline */
4844 BUG_ON(cpu_online(cpu));
4846 /* Strictly not necessary since rest of the CPUs are stopped by now
4847 * and interrupts disabled on current cpu.
4849 spin_lock_irqsave(&rq->lock, flags);
4851 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4852 /* Add idle task to _front_ of it's priority queue */
4853 __activate_idle_task(p, rq);
4855 spin_unlock_irqrestore(&rq->lock, flags);
4858 /* Ensures that the idle task is using init_mm right before its cpu goes
4861 void idle_task_exit(void)
4863 struct mm_struct *mm = current->active_mm;
4865 BUG_ON(cpu_online(smp_processor_id()));
4868 switch_mm(mm, &init_mm, current);
4872 static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
4874 struct runqueue *rq = cpu_rq(dead_cpu);
4876 /* Must be exiting, otherwise would be on tasklist. */
4877 BUG_ON(tsk->exit_state != EXIT_ZOMBIE && tsk->exit_state != EXIT_DEAD);
4879 /* Cannot have done final schedule yet: would have vanished. */
4880 BUG_ON(tsk->flags & PF_DEAD);
4882 get_task_struct(tsk);
4885 * Drop lock around migration; if someone else moves it,
4886 * that's OK. No task can be added to this CPU, so iteration is
4889 spin_unlock_irq(&rq->lock);
4890 move_task_off_dead_cpu(dead_cpu, tsk);
4891 spin_lock_irq(&rq->lock);
4893 put_task_struct(tsk);
4896 /* release_task() removes task from tasklist, so we won't find dead tasks. */
4897 static void migrate_dead_tasks(unsigned int dead_cpu)
4900 struct runqueue *rq = cpu_rq(dead_cpu);
4902 for (arr = 0; arr < 2; arr++) {
4903 for (i = 0; i < MAX_PRIO; i++) {
4904 struct list_head *list = &rq->arrays[arr].queue[i];
4905 while (!list_empty(list))
4906 migrate_dead(dead_cpu,
4907 list_entry(list->next, task_t,
4912 #endif /* CONFIG_HOTPLUG_CPU */
4915 * migration_call - callback that gets triggered when a CPU is added.
4916 * Here we can start up the necessary migration thread for the new CPU.
4918 static int migration_call(struct notifier_block *nfb, unsigned long action,
4921 int cpu = (long)hcpu;
4922 struct task_struct *p;
4923 struct runqueue *rq;
4924 unsigned long flags;
4927 case CPU_UP_PREPARE:
4928 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4931 p->flags |= PF_NOFREEZE;
4932 kthread_bind(p, cpu);
4933 /* Must be high prio: stop_machine expects to yield to it. */
4934 rq = task_rq_lock(p, &flags);
4935 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4936 task_rq_unlock(rq, &flags);
4937 cpu_rq(cpu)->migration_thread = p;
4940 /* Strictly unneccessary, as first user will wake it. */
4941 wake_up_process(cpu_rq(cpu)->migration_thread);
4943 #ifdef CONFIG_HOTPLUG_CPU
4944 case CPU_UP_CANCELED:
4945 /* Unbind it from offline cpu so it can run. Fall thru. */
4946 kthread_bind(cpu_rq(cpu)->migration_thread,
4947 any_online_cpu(cpu_online_map));
4948 kthread_stop(cpu_rq(cpu)->migration_thread);
4949 cpu_rq(cpu)->migration_thread = NULL;
4952 migrate_live_tasks(cpu);
4954 kthread_stop(rq->migration_thread);
4955 rq->migration_thread = NULL;
4956 /* Idle task back to normal (off runqueue, low prio) */
4957 rq = task_rq_lock(rq->idle, &flags);
4958 deactivate_task(rq->idle, rq);
4959 rq->idle->static_prio = MAX_PRIO;
4960 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4961 migrate_dead_tasks(cpu);
4962 task_rq_unlock(rq, &flags);
4963 migrate_nr_uninterruptible(rq);
4964 BUG_ON(rq->nr_running != 0);
4966 /* No need to migrate the tasks: it was best-effort if
4967 * they didn't do lock_cpu_hotplug(). Just wake up
4968 * the requestors. */
4969 spin_lock_irq(&rq->lock);
4970 while (!list_empty(&rq->migration_queue)) {
4971 migration_req_t *req;
4972 req = list_entry(rq->migration_queue.next,
4973 migration_req_t, list);
4974 list_del_init(&req->list);
4975 complete(&req->done);
4977 spin_unlock_irq(&rq->lock);
4984 /* Register at highest priority so that task migration (migrate_all_tasks)
4985 * happens before everything else.
4987 static struct notifier_block migration_notifier = {
4988 .notifier_call = migration_call,
4992 int __init migration_init(void)
4994 void *cpu = (void *)(long)smp_processor_id();
4995 /* Start one for boot CPU. */
4996 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4997 migration_call(&migration_notifier, CPU_ONLINE, cpu);
4998 register_cpu_notifier(&migration_notifier);
5004 #undef SCHED_DOMAIN_DEBUG
5005 #ifdef SCHED_DOMAIN_DEBUG
5006 static void sched_domain_debug(struct sched_domain *sd, int cpu)
5011 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5015 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5020 struct sched_group *group = sd->groups;
5021 cpumask_t groupmask;
5023 cpumask_scnprintf(str, NR_CPUS, sd->span);
5024 cpus_clear(groupmask);
5027 for (i = 0; i < level + 1; i++)
5029 printk("domain %d: ", level);
5031 if (!(sd->flags & SD_LOAD_BALANCE)) {
5032 printk("does not load-balance\n");
5034 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
5038 printk("span %s\n", str);
5040 if (!cpu_isset(cpu, sd->span))
5041 printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
5042 if (!cpu_isset(cpu, group->cpumask))
5043 printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
5046 for (i = 0; i < level + 2; i++)
5052 printk(KERN_ERR "ERROR: group is NULL\n");
5056 if (!group->cpu_power) {
5058 printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
5061 if (!cpus_weight(group->cpumask)) {
5063 printk(KERN_ERR "ERROR: empty group\n");
5066 if (cpus_intersects(groupmask, group->cpumask)) {
5068 printk(KERN_ERR "ERROR: repeated CPUs\n");
5071 cpus_or(groupmask, groupmask, group->cpumask);
5073 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
5076 group = group->next;
5077 } while (group != sd->groups);
5080 if (!cpus_equal(sd->span, groupmask))
5081 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
5087 if (!cpus_subset(groupmask, sd->span))
5088 printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
5094 #define sched_domain_debug(sd, cpu) {}
5097 static int sd_degenerate(struct sched_domain *sd)
5099 if (cpus_weight(sd->span) == 1)
5102 /* Following flags need at least 2 groups */
5103 if (sd->flags & (SD_LOAD_BALANCE |
5104 SD_BALANCE_NEWIDLE |
5107 if (sd->groups != sd->groups->next)
5111 /* Following flags don't use groups */
5112 if (sd->flags & (SD_WAKE_IDLE |
5120 static int sd_parent_degenerate(struct sched_domain *sd,
5121 struct sched_domain *parent)
5123 unsigned long cflags = sd->flags, pflags = parent->flags;
5125 if (sd_degenerate(parent))
5128 if (!cpus_equal(sd->span, parent->span))
5131 /* Does parent contain flags not in child? */
5132 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
5133 if (cflags & SD_WAKE_AFFINE)
5134 pflags &= ~SD_WAKE_BALANCE;
5135 /* Flags needing groups don't count if only 1 group in parent */
5136 if (parent->groups == parent->groups->next) {
5137 pflags &= ~(SD_LOAD_BALANCE |
5138 SD_BALANCE_NEWIDLE |
5142 if (~cflags & pflags)
5149 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
5150 * hold the hotplug lock.
5152 static void cpu_attach_domain(struct sched_domain *sd, int cpu)
5154 runqueue_t *rq = cpu_rq(cpu);
5155 struct sched_domain *tmp;
5157 /* Remove the sched domains which do not contribute to scheduling. */
5158 for (tmp = sd; tmp; tmp = tmp->parent) {
5159 struct sched_domain *parent = tmp->parent;
5162 if (sd_parent_degenerate(tmp, parent))
5163 tmp->parent = parent->parent;
5166 if (sd && sd_degenerate(sd))
5169 sched_domain_debug(sd, cpu);
5171 rcu_assign_pointer(rq->sd, sd);
5174 /* cpus with isolated domains */
5175 static cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
5177 /* Setup the mask of cpus configured for isolated domains */
5178 static int __init isolated_cpu_setup(char *str)
5180 int ints[NR_CPUS], i;
5182 str = get_options(str, ARRAY_SIZE(ints), ints);
5183 cpus_clear(cpu_isolated_map);
5184 for (i = 1; i <= ints[0]; i++)
5185 if (ints[i] < NR_CPUS)
5186 cpu_set(ints[i], cpu_isolated_map);
5190 __setup ("isolcpus=", isolated_cpu_setup);
5193 * init_sched_build_groups takes an array of groups, the cpumask we wish
5194 * to span, and a pointer to a function which identifies what group a CPU
5195 * belongs to. The return value of group_fn must be a valid index into the
5196 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
5197 * keep track of groups covered with a cpumask_t).
5199 * init_sched_build_groups will build a circular linked list of the groups
5200 * covered by the given span, and will set each group's ->cpumask correctly,
5201 * and ->cpu_power to 0.
5203 static void init_sched_build_groups(struct sched_group groups[], cpumask_t span,
5204 int (*group_fn)(int cpu))
5206 struct sched_group *first = NULL, *last = NULL;
5207 cpumask_t covered = CPU_MASK_NONE;
5210 for_each_cpu_mask(i, span) {
5211 int group = group_fn(i);
5212 struct sched_group *sg = &groups[group];
5215 if (cpu_isset(i, covered))
5218 sg->cpumask = CPU_MASK_NONE;
5221 for_each_cpu_mask(j, span) {
5222 if (group_fn(j) != group)
5225 cpu_set(j, covered);
5226 cpu_set(j, sg->cpumask);
5237 #define SD_NODES_PER_DOMAIN 16
5240 * Self-tuning task migration cost measurement between source and target CPUs.
5242 * This is done by measuring the cost of manipulating buffers of varying
5243 * sizes. For a given buffer-size here are the steps that are taken:
5245 * 1) the source CPU reads+dirties a shared buffer
5246 * 2) the target CPU reads+dirties the same shared buffer
5248 * We measure how long they take, in the following 4 scenarios:
5250 * - source: CPU1, target: CPU2 | cost1
5251 * - source: CPU2, target: CPU1 | cost2
5252 * - source: CPU1, target: CPU1 | cost3
5253 * - source: CPU2, target: CPU2 | cost4
5255 * We then calculate the cost3+cost4-cost1-cost2 difference - this is
5256 * the cost of migration.
5258 * We then start off from a small buffer-size and iterate up to larger
5259 * buffer sizes, in 5% steps - measuring each buffer-size separately, and
5260 * doing a maximum search for the cost. (The maximum cost for a migration
5261 * normally occurs when the working set size is around the effective cache
5264 #define SEARCH_SCOPE 2
5265 #define MIN_CACHE_SIZE (64*1024U)
5266 #define DEFAULT_CACHE_SIZE (5*1024*1024U)
5267 #define ITERATIONS 1
5268 #define SIZE_THRESH 130
5269 #define COST_THRESH 130
5272 * The migration cost is a function of 'domain distance'. Domain
5273 * distance is the number of steps a CPU has to iterate down its
5274 * domain tree to share a domain with the other CPU. The farther
5275 * two CPUs are from each other, the larger the distance gets.
5277 * Note that we use the distance only to cache measurement results,
5278 * the distance value is not used numerically otherwise. When two
5279 * CPUs have the same distance it is assumed that the migration
5280 * cost is the same. (this is a simplification but quite practical)
5282 #define MAX_DOMAIN_DISTANCE 32
5284 static unsigned long long migration_cost[MAX_DOMAIN_DISTANCE] =
5285 { [ 0 ... MAX_DOMAIN_DISTANCE-1 ] =
5287 * Architectures may override the migration cost and thus avoid
5288 * boot-time calibration. Unit is nanoseconds. Mostly useful for
5289 * virtualized hardware:
5291 #ifdef CONFIG_DEFAULT_MIGRATION_COST
5292 CONFIG_DEFAULT_MIGRATION_COST
5299 * Allow override of migration cost - in units of microseconds.
5300 * E.g. migration_cost=1000,2000,3000 will set up a level-1 cost
5301 * of 1 msec, level-2 cost of 2 msecs and level3 cost of 3 msecs:
5303 static int __init migration_cost_setup(char *str)
5305 int ints[MAX_DOMAIN_DISTANCE+1], i;
5307 str = get_options(str, ARRAY_SIZE(ints), ints);
5309 printk("#ints: %d\n", ints[0]);
5310 for (i = 1; i <= ints[0]; i++) {
5311 migration_cost[i-1] = (unsigned long long)ints[i]*1000;
5312 printk("migration_cost[%d]: %Ld\n", i-1, migration_cost[i-1]);
5317 __setup ("migration_cost=", migration_cost_setup);
5320 * Global multiplier (divisor) for migration-cutoff values,
5321 * in percentiles. E.g. use a value of 150 to get 1.5 times
5322 * longer cache-hot cutoff times.
5324 * (We scale it from 100 to 128 to long long handling easier.)
5327 #define MIGRATION_FACTOR_SCALE 128
5329 static unsigned int migration_factor = MIGRATION_FACTOR_SCALE;
5331 static int __init setup_migration_factor(char *str)
5333 get_option(&str, &migration_factor);
5334 migration_factor = migration_factor * MIGRATION_FACTOR_SCALE / 100;
5338 __setup("migration_factor=", setup_migration_factor);
5341 * Estimated distance of two CPUs, measured via the number of domains
5342 * we have to pass for the two CPUs to be in the same span:
5344 static unsigned long domain_distance(int cpu1, int cpu2)
5346 unsigned long distance = 0;
5347 struct sched_domain *sd;
5349 for_each_domain(cpu1, sd) {
5350 WARN_ON(!cpu_isset(cpu1, sd->span));
5351 if (cpu_isset(cpu2, sd->span))
5355 if (distance >= MAX_DOMAIN_DISTANCE) {
5357 distance = MAX_DOMAIN_DISTANCE-1;
5363 static unsigned int migration_debug;
5365 static int __init setup_migration_debug(char *str)
5367 get_option(&str, &migration_debug);
5371 __setup("migration_debug=", setup_migration_debug);
5374 * Maximum cache-size that the scheduler should try to measure.
5375 * Architectures with larger caches should tune this up during
5376 * bootup. Gets used in the domain-setup code (i.e. during SMP
5379 unsigned int max_cache_size;
5381 static int __init setup_max_cache_size(char *str)
5383 get_option(&str, &max_cache_size);
5387 __setup("max_cache_size=", setup_max_cache_size);
5390 * Dirty a big buffer in a hard-to-predict (for the L2 cache) way. This
5391 * is the operation that is timed, so we try to generate unpredictable
5392 * cachemisses that still end up filling the L2 cache:
5394 static void touch_cache(void *__cache, unsigned long __size)
5396 unsigned long size = __size/sizeof(long), chunk1 = size/3,
5398 unsigned long *cache = __cache;
5401 for (i = 0; i < size/6; i += 8) {
5404 case 1: cache[size-1-i]++;
5405 case 2: cache[chunk1-i]++;
5406 case 3: cache[chunk1+i]++;
5407 case 4: cache[chunk2-i]++;
5408 case 5: cache[chunk2+i]++;
5414 * Measure the cache-cost of one task migration. Returns in units of nsec.
5416 static unsigned long long measure_one(void *cache, unsigned long size,
5417 int source, int target)
5419 cpumask_t mask, saved_mask;
5420 unsigned long long t0, t1, t2, t3, cost;
5422 saved_mask = current->cpus_allowed;
5425 * Flush source caches to RAM and invalidate them:
5430 * Migrate to the source CPU:
5432 mask = cpumask_of_cpu(source);
5433 set_cpus_allowed(current, mask);
5434 WARN_ON(smp_processor_id() != source);
5437 * Dirty the working set:
5440 touch_cache(cache, size);
5444 * Migrate to the target CPU, dirty the L2 cache and access
5445 * the shared buffer. (which represents the working set
5446 * of a migrated task.)
5448 mask = cpumask_of_cpu(target);
5449 set_cpus_allowed(current, mask);
5450 WARN_ON(smp_processor_id() != target);
5453 touch_cache(cache, size);
5456 cost = t1-t0 + t3-t2;
5458 if (migration_debug >= 2)
5459 printk("[%d->%d]: %8Ld %8Ld %8Ld => %10Ld.\n",
5460 source, target, t1-t0, t1-t0, t3-t2, cost);
5462 * Flush target caches to RAM and invalidate them:
5466 set_cpus_allowed(current, saved_mask);
5472 * Measure a series of task migrations and return the average
5473 * result. Since this code runs early during bootup the system
5474 * is 'undisturbed' and the average latency makes sense.
5476 * The algorithm in essence auto-detects the relevant cache-size,
5477 * so it will properly detect different cachesizes for different
5478 * cache-hierarchies, depending on how the CPUs are connected.
5480 * Architectures can prime the upper limit of the search range via
5481 * max_cache_size, otherwise the search range defaults to 20MB...64K.
5483 static unsigned long long
5484 measure_cost(int cpu1, int cpu2, void *cache, unsigned int size)
5486 unsigned long long cost1, cost2;
5490 * Measure the migration cost of 'size' bytes, over an
5491 * average of 10 runs:
5493 * (We perturb the cache size by a small (0..4k)
5494 * value to compensate size/alignment related artifacts.
5495 * We also subtract the cost of the operation done on
5501 * dry run, to make sure we start off cache-cold on cpu1,
5502 * and to get any vmalloc pagefaults in advance:
5504 measure_one(cache, size, cpu1, cpu2);
5505 for (i = 0; i < ITERATIONS; i++)
5506 cost1 += measure_one(cache, size - i*1024, cpu1, cpu2);
5508 measure_one(cache, size, cpu2, cpu1);
5509 for (i = 0; i < ITERATIONS; i++)
5510 cost1 += measure_one(cache, size - i*1024, cpu2, cpu1);
5513 * (We measure the non-migrating [cached] cost on both
5514 * cpu1 and cpu2, to handle CPUs with different speeds)
5518 measure_one(cache, size, cpu1, cpu1);
5519 for (i = 0; i < ITERATIONS; i++)
5520 cost2 += measure_one(cache, size - i*1024, cpu1, cpu1);
5522 measure_one(cache, size, cpu2, cpu2);
5523 for (i = 0; i < ITERATIONS; i++)
5524 cost2 += measure_one(cache, size - i*1024, cpu2, cpu2);
5527 * Get the per-iteration migration cost:
5529 do_div(cost1, 2*ITERATIONS);
5530 do_div(cost2, 2*ITERATIONS);
5532 return cost1 - cost2;
5535 static unsigned long long measure_migration_cost(int cpu1, int cpu2)
5537 unsigned long long max_cost = 0, fluct = 0, avg_fluct = 0;
5538 unsigned int max_size, size, size_found = 0;
5539 long long cost = 0, prev_cost;
5543 * Search from max_cache_size*5 down to 64K - the real relevant
5544 * cachesize has to lie somewhere inbetween.
5546 if (max_cache_size) {
5547 max_size = max(max_cache_size * SEARCH_SCOPE, MIN_CACHE_SIZE);
5548 size = max(max_cache_size / SEARCH_SCOPE, MIN_CACHE_SIZE);
5551 * Since we have no estimation about the relevant
5554 max_size = DEFAULT_CACHE_SIZE * SEARCH_SCOPE;
5555 size = MIN_CACHE_SIZE;
5558 if (!cpu_online(cpu1) || !cpu_online(cpu2)) {
5559 printk("cpu %d and %d not both online!\n", cpu1, cpu2);
5564 * Allocate the working set:
5566 cache = vmalloc(max_size);
5568 printk("could not vmalloc %d bytes for cache!\n", 2*max_size);
5569 return 1000000; // return 1 msec on very small boxen
5572 while (size <= max_size) {
5574 cost = measure_cost(cpu1, cpu2, cache, size);
5580 if (max_cost < cost) {
5586 * Calculate average fluctuation, we use this to prevent
5587 * noise from triggering an early break out of the loop:
5589 fluct = abs(cost - prev_cost);
5590 avg_fluct = (avg_fluct + fluct)/2;
5592 if (migration_debug)
5593 printk("-> [%d][%d][%7d] %3ld.%ld [%3ld.%ld] (%ld): (%8Ld %8Ld)\n",
5595 (long)cost / 1000000,
5596 ((long)cost / 100000) % 10,
5597 (long)max_cost / 1000000,
5598 ((long)max_cost / 100000) % 10,
5599 domain_distance(cpu1, cpu2),
5603 * If we iterated at least 20% past the previous maximum,
5604 * and the cost has dropped by more than 20% already,
5605 * (taking fluctuations into account) then we assume to
5606 * have found the maximum and break out of the loop early:
5608 if (size_found && (size*100 > size_found*SIZE_THRESH))
5609 if (cost+avg_fluct <= 0 ||
5610 max_cost*100 > (cost+avg_fluct)*COST_THRESH) {
5612 if (migration_debug)
5613 printk("-> found max.\n");
5617 * Increase the cachesize in 10% steps:
5619 size = size * 10 / 9;
5622 if (migration_debug)
5623 printk("[%d][%d] working set size found: %d, cost: %Ld\n",
5624 cpu1, cpu2, size_found, max_cost);
5629 * A task is considered 'cache cold' if at least 2 times
5630 * the worst-case cost of migration has passed.
5632 * (this limit is only listened to if the load-balancing
5633 * situation is 'nice' - if there is a large imbalance we
5634 * ignore it for the sake of CPU utilization and
5635 * processing fairness.)
5637 return 2 * max_cost * migration_factor / MIGRATION_FACTOR_SCALE;
5640 static void calibrate_migration_costs(const cpumask_t *cpu_map)
5642 int cpu1 = -1, cpu2 = -1, cpu, orig_cpu = raw_smp_processor_id();
5643 unsigned long j0, j1, distance, max_distance = 0;
5644 struct sched_domain *sd;
5649 * First pass - calculate the cacheflush times:
5651 for_each_cpu_mask(cpu1, *cpu_map) {
5652 for_each_cpu_mask(cpu2, *cpu_map) {
5655 distance = domain_distance(cpu1, cpu2);
5656 max_distance = max(max_distance, distance);
5658 * No result cached yet?
5660 if (migration_cost[distance] == -1LL)
5661 migration_cost[distance] =
5662 measure_migration_cost(cpu1, cpu2);
5666 * Second pass - update the sched domain hierarchy with
5667 * the new cache-hot-time estimations:
5669 for_each_cpu_mask(cpu, *cpu_map) {
5671 for_each_domain(cpu, sd) {
5672 sd->cache_hot_time = migration_cost[distance];
5679 if (migration_debug)
5680 printk("migration: max_cache_size: %d, cpu: %d MHz:\n",
5688 if (system_state == SYSTEM_BOOTING) {
5689 if (num_online_cpus() > 1) {
5690 printk("migration_cost=");
5691 for (distance = 0; distance <= max_distance; distance++) {
5694 printk("%ld", (long)migration_cost[distance] / 1000);
5700 if (migration_debug)
5701 printk("migration: %ld seconds\n", (j1-j0)/HZ);
5704 * Move back to the original CPU. NUMA-Q gets confused
5705 * if we migrate to another quad during bootup.
5707 if (raw_smp_processor_id() != orig_cpu) {
5708 cpumask_t mask = cpumask_of_cpu(orig_cpu),
5709 saved_mask = current->cpus_allowed;
5711 set_cpus_allowed(current, mask);
5712 set_cpus_allowed(current, saved_mask);
5719 * find_next_best_node - find the next node to include in a sched_domain
5720 * @node: node whose sched_domain we're building
5721 * @used_nodes: nodes already in the sched_domain
5723 * Find the next node to include in a given scheduling domain. Simply
5724 * finds the closest node not already in the @used_nodes map.
5726 * Should use nodemask_t.
5728 static int find_next_best_node(int node, unsigned long *used_nodes)
5730 int i, n, val, min_val, best_node = 0;
5734 for (i = 0; i < MAX_NUMNODES; i++) {
5735 /* Start at @node */
5736 n = (node + i) % MAX_NUMNODES;
5738 if (!nr_cpus_node(n))
5741 /* Skip already used nodes */
5742 if (test_bit(n, used_nodes))
5745 /* Simple min distance search */
5746 val = node_distance(node, n);
5748 if (val < min_val) {
5754 set_bit(best_node, used_nodes);
5759 * sched_domain_node_span - get a cpumask for a node's sched_domain
5760 * @node: node whose cpumask we're constructing
5761 * @size: number of nodes to include in this span
5763 * Given a node, construct a good cpumask for its sched_domain to span. It
5764 * should be one that prevents unnecessary balancing, but also spreads tasks
5767 static cpumask_t sched_domain_node_span(int node)
5770 cpumask_t span, nodemask;
5771 DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
5774 bitmap_zero(used_nodes, MAX_NUMNODES);
5776 nodemask = node_to_cpumask(node);
5777 cpus_or(span, span, nodemask);
5778 set_bit(node, used_nodes);
5780 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
5781 int next_node = find_next_best_node(node, used_nodes);
5782 nodemask = node_to_cpumask(next_node);
5783 cpus_or(span, span, nodemask);
5791 * At the moment, CONFIG_SCHED_SMT is never defined, but leave it in so we
5792 * can switch it on easily if needed.
5794 #ifdef CONFIG_SCHED_SMT
5795 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
5796 static struct sched_group sched_group_cpus[NR_CPUS];
5797 static int cpu_to_cpu_group(int cpu)
5803 #ifdef CONFIG_SCHED_MC
5804 static DEFINE_PER_CPU(struct sched_domain, core_domains);
5805 static struct sched_group sched_group_core[NR_CPUS];
5808 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
5809 static int cpu_to_core_group(int cpu)
5811 return first_cpu(cpu_sibling_map[cpu]);
5813 #elif defined(CONFIG_SCHED_MC)
5814 static int cpu_to_core_group(int cpu)
5820 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
5821 static struct sched_group sched_group_phys[NR_CPUS];
5822 static int cpu_to_phys_group(int cpu)
5824 #if defined(CONFIG_SCHED_MC)
5825 cpumask_t mask = cpu_coregroup_map(cpu);
5826 return first_cpu(mask);
5827 #elif defined(CONFIG_SCHED_SMT)
5828 return first_cpu(cpu_sibling_map[cpu]);
5836 * The init_sched_build_groups can't handle what we want to do with node
5837 * groups, so roll our own. Now each node has its own list of groups which
5838 * gets dynamically allocated.
5840 static DEFINE_PER_CPU(struct sched_domain, node_domains);
5841 static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
5843 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
5844 static struct sched_group *sched_group_allnodes_bycpu[NR_CPUS];
5846 static int cpu_to_allnodes_group(int cpu)
5848 return cpu_to_node(cpu);
5850 static void init_numa_sched_groups_power(struct sched_group *group_head)
5852 struct sched_group *sg = group_head;
5858 for_each_cpu_mask(j, sg->cpumask) {
5859 struct sched_domain *sd;
5861 sd = &per_cpu(phys_domains, j);
5862 if (j != first_cpu(sd->groups->cpumask)) {
5864 * Only add "power" once for each
5870 sg->cpu_power += sd->groups->cpu_power;
5873 if (sg != group_head)
5879 * Build sched domains for a given set of cpus and attach the sched domains
5880 * to the individual cpus
5882 void build_sched_domains(const cpumask_t *cpu_map)
5886 struct sched_group **sched_group_nodes = NULL;
5887 struct sched_group *sched_group_allnodes = NULL;
5890 * Allocate the per-node list of sched groups
5892 sched_group_nodes = kmalloc(sizeof(struct sched_group*)*MAX_NUMNODES,
5894 if (!sched_group_nodes) {
5895 printk(KERN_WARNING "Can not alloc sched group node list\n");
5898 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
5902 * Set up domains for cpus specified by the cpu_map.
5904 for_each_cpu_mask(i, *cpu_map) {
5906 struct sched_domain *sd = NULL, *p;
5907 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
5909 cpus_and(nodemask, nodemask, *cpu_map);
5912 if (cpus_weight(*cpu_map)
5913 > SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
5914 if (!sched_group_allnodes) {
5915 sched_group_allnodes
5916 = kmalloc(sizeof(struct sched_group)
5919 if (!sched_group_allnodes) {
5921 "Can not alloc allnodes sched group\n");
5924 sched_group_allnodes_bycpu[i]
5925 = sched_group_allnodes;
5927 sd = &per_cpu(allnodes_domains, i);
5928 *sd = SD_ALLNODES_INIT;
5929 sd->span = *cpu_map;
5930 group = cpu_to_allnodes_group(i);
5931 sd->groups = &sched_group_allnodes[group];
5936 sd = &per_cpu(node_domains, i);
5938 sd->span = sched_domain_node_span(cpu_to_node(i));
5940 cpus_and(sd->span, sd->span, *cpu_map);
5944 sd = &per_cpu(phys_domains, i);
5945 group = cpu_to_phys_group(i);
5947 sd->span = nodemask;
5949 sd->groups = &sched_group_phys[group];
5951 #ifdef CONFIG_SCHED_MC
5953 sd = &per_cpu(core_domains, i);
5954 group = cpu_to_core_group(i);
5956 sd->span = cpu_coregroup_map(i);
5957 cpus_and(sd->span, sd->span, *cpu_map);
5959 sd->groups = &sched_group_core[group];
5962 #ifdef CONFIG_SCHED_SMT
5964 sd = &per_cpu(cpu_domains, i);
5965 group = cpu_to_cpu_group(i);
5966 *sd = SD_SIBLING_INIT;
5967 sd->span = cpu_sibling_map[i];
5968 cpus_and(sd->span, sd->span, *cpu_map);
5970 sd->groups = &sched_group_cpus[group];
5974 #ifdef CONFIG_SCHED_SMT
5975 /* Set up CPU (sibling) groups */
5976 for_each_cpu_mask(i, *cpu_map) {
5977 cpumask_t this_sibling_map = cpu_sibling_map[i];
5978 cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
5979 if (i != first_cpu(this_sibling_map))
5982 init_sched_build_groups(sched_group_cpus, this_sibling_map,
5987 #ifdef CONFIG_SCHED_MC
5988 /* Set up multi-core groups */
5989 for_each_cpu_mask(i, *cpu_map) {
5990 cpumask_t this_core_map = cpu_coregroup_map(i);
5991 cpus_and(this_core_map, this_core_map, *cpu_map);
5992 if (i != first_cpu(this_core_map))
5994 init_sched_build_groups(sched_group_core, this_core_map,
5995 &cpu_to_core_group);
6000 /* Set up physical groups */
6001 for (i = 0; i < MAX_NUMNODES; i++) {
6002 cpumask_t nodemask = node_to_cpumask(i);
6004 cpus_and(nodemask, nodemask, *cpu_map);
6005 if (cpus_empty(nodemask))
6008 init_sched_build_groups(sched_group_phys, nodemask,
6009 &cpu_to_phys_group);
6013 /* Set up node groups */
6014 if (sched_group_allnodes)
6015 init_sched_build_groups(sched_group_allnodes, *cpu_map,
6016 &cpu_to_allnodes_group);
6018 for (i = 0; i < MAX_NUMNODES; i++) {
6019 /* Set up node groups */
6020 struct sched_group *sg, *prev;
6021 cpumask_t nodemask = node_to_cpumask(i);
6022 cpumask_t domainspan;
6023 cpumask_t covered = CPU_MASK_NONE;
6026 cpus_and(nodemask, nodemask, *cpu_map);
6027 if (cpus_empty(nodemask)) {
6028 sched_group_nodes[i] = NULL;
6032 domainspan = sched_domain_node_span(i);
6033 cpus_and(domainspan, domainspan, *cpu_map);
6035 sg = kmalloc(sizeof(struct sched_group), GFP_KERNEL);
6036 sched_group_nodes[i] = sg;
6037 for_each_cpu_mask(j, nodemask) {
6038 struct sched_domain *sd;
6039 sd = &per_cpu(node_domains, j);
6041 if (sd->groups == NULL) {
6042 /* Turn off balancing if we have no groups */
6048 "Can not alloc domain group for node %d\n", i);
6052 sg->cpumask = nodemask;
6053 cpus_or(covered, covered, nodemask);
6056 for (j = 0; j < MAX_NUMNODES; j++) {
6057 cpumask_t tmp, notcovered;
6058 int n = (i + j) % MAX_NUMNODES;
6060 cpus_complement(notcovered, covered);
6061 cpus_and(tmp, notcovered, *cpu_map);
6062 cpus_and(tmp, tmp, domainspan);
6063 if (cpus_empty(tmp))
6066 nodemask = node_to_cpumask(n);
6067 cpus_and(tmp, tmp, nodemask);
6068 if (cpus_empty(tmp))
6071 sg = kmalloc(sizeof(struct sched_group), GFP_KERNEL);
6074 "Can not alloc domain group for node %d\n", j);
6079 cpus_or(covered, covered, tmp);
6083 prev->next = sched_group_nodes[i];
6087 /* Calculate CPU power for physical packages and nodes */
6088 for_each_cpu_mask(i, *cpu_map) {
6090 struct sched_domain *sd;
6091 #ifdef CONFIG_SCHED_SMT
6092 sd = &per_cpu(cpu_domains, i);
6093 power = SCHED_LOAD_SCALE;
6094 sd->groups->cpu_power = power;
6096 #ifdef CONFIG_SCHED_MC
6097 sd = &per_cpu(core_domains, i);
6098 power = SCHED_LOAD_SCALE + (cpus_weight(sd->groups->cpumask)-1)
6099 * SCHED_LOAD_SCALE / 10;
6100 sd->groups->cpu_power = power;
6102 sd = &per_cpu(phys_domains, i);
6105 * This has to be < 2 * SCHED_LOAD_SCALE
6106 * Lets keep it SCHED_LOAD_SCALE, so that
6107 * while calculating NUMA group's cpu_power
6109 * numa_group->cpu_power += phys_group->cpu_power;
6111 * See "only add power once for each physical pkg"
6114 sd->groups->cpu_power = SCHED_LOAD_SCALE;
6116 sd = &per_cpu(phys_domains, i);
6117 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
6118 (cpus_weight(sd->groups->cpumask)-1) / 10;
6119 sd->groups->cpu_power = power;
6124 for (i = 0; i < MAX_NUMNODES; i++)
6125 init_numa_sched_groups_power(sched_group_nodes[i]);
6127 init_numa_sched_groups_power(sched_group_allnodes);
6130 /* Attach the domains */
6131 for_each_cpu_mask(i, *cpu_map) {
6132 struct sched_domain *sd;
6133 #ifdef CONFIG_SCHED_SMT
6134 sd = &per_cpu(cpu_domains, i);
6135 #elif defined(CONFIG_SCHED_MC)
6136 sd = &per_cpu(core_domains, i);
6138 sd = &per_cpu(phys_domains, i);
6140 cpu_attach_domain(sd, i);
6143 * Tune cache-hot values:
6145 calibrate_migration_costs(cpu_map);
6148 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6150 static void arch_init_sched_domains(const cpumask_t *cpu_map)
6152 cpumask_t cpu_default_map;
6155 * Setup mask for cpus without special case scheduling requirements.
6156 * For now this just excludes isolated cpus, but could be used to
6157 * exclude other special cases in the future.
6159 cpus_andnot(cpu_default_map, *cpu_map, cpu_isolated_map);
6161 build_sched_domains(&cpu_default_map);
6164 static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
6170 for_each_cpu_mask(cpu, *cpu_map) {
6171 struct sched_group *sched_group_allnodes
6172 = sched_group_allnodes_bycpu[cpu];
6173 struct sched_group **sched_group_nodes
6174 = sched_group_nodes_bycpu[cpu];
6176 if (sched_group_allnodes) {
6177 kfree(sched_group_allnodes);
6178 sched_group_allnodes_bycpu[cpu] = NULL;
6181 if (!sched_group_nodes)
6184 for (i = 0; i < MAX_NUMNODES; i++) {
6185 cpumask_t nodemask = node_to_cpumask(i);
6186 struct sched_group *oldsg, *sg = sched_group_nodes[i];
6188 cpus_and(nodemask, nodemask, *cpu_map);
6189 if (cpus_empty(nodemask))
6199 if (oldsg != sched_group_nodes[i])
6202 kfree(sched_group_nodes);
6203 sched_group_nodes_bycpu[cpu] = NULL;
6209 * Detach sched domains from a group of cpus specified in cpu_map
6210 * These cpus will now be attached to the NULL domain
6212 static void detach_destroy_domains(const cpumask_t *cpu_map)
6216 for_each_cpu_mask(i, *cpu_map)
6217 cpu_attach_domain(NULL, i);
6218 synchronize_sched();
6219 arch_destroy_sched_domains(cpu_map);
6223 * Partition sched domains as specified by the cpumasks below.
6224 * This attaches all cpus from the cpumasks to the NULL domain,
6225 * waits for a RCU quiescent period, recalculates sched
6226 * domain information and then attaches them back to the
6227 * correct sched domains
6228 * Call with hotplug lock held
6230 void partition_sched_domains(cpumask_t *partition1, cpumask_t *partition2)
6232 cpumask_t change_map;
6234 cpus_and(*partition1, *partition1, cpu_online_map);
6235 cpus_and(*partition2, *partition2, cpu_online_map);
6236 cpus_or(change_map, *partition1, *partition2);
6238 /* Detach sched domains from all of the affected cpus */
6239 detach_destroy_domains(&change_map);
6240 if (!cpus_empty(*partition1))
6241 build_sched_domains(partition1);
6242 if (!cpus_empty(*partition2))
6243 build_sched_domains(partition2);
6246 #ifdef CONFIG_HOTPLUG_CPU
6248 * Force a reinitialization of the sched domains hierarchy. The domains
6249 * and groups cannot be updated in place without racing with the balancing
6250 * code, so we temporarily attach all running cpus to the NULL domain
6251 * which will prevent rebalancing while the sched domains are recalculated.
6253 static int update_sched_domains(struct notifier_block *nfb,
6254 unsigned long action, void *hcpu)
6257 case CPU_UP_PREPARE:
6258 case CPU_DOWN_PREPARE:
6259 detach_destroy_domains(&cpu_online_map);
6262 case CPU_UP_CANCELED:
6263 case CPU_DOWN_FAILED:
6267 * Fall through and re-initialise the domains.
6274 /* The hotplug lock is already held by cpu_up/cpu_down */
6275 arch_init_sched_domains(&cpu_online_map);
6281 void __init sched_init_smp(void)
6284 arch_init_sched_domains(&cpu_online_map);
6285 unlock_cpu_hotplug();
6286 /* XXX: Theoretical race here - CPU may be hotplugged now */
6287 hotcpu_notifier(update_sched_domains, 0);
6290 void __init sched_init_smp(void)
6293 #endif /* CONFIG_SMP */
6295 int in_sched_functions(unsigned long addr)
6297 /* Linker adds these: start and end of __sched functions */
6298 extern char __sched_text_start[], __sched_text_end[];
6299 return in_lock_functions(addr) ||
6300 (addr >= (unsigned long)__sched_text_start
6301 && addr < (unsigned long)__sched_text_end);
6304 void __init sched_init(void)
6309 for_each_possible_cpu(i) {
6310 prio_array_t *array;
6313 spin_lock_init(&rq->lock);
6315 rq->active = rq->arrays;
6316 rq->expired = rq->arrays + 1;
6317 rq->best_expired_prio = MAX_PRIO;
6321 for (j = 1; j < 3; j++)
6322 rq->cpu_load[j] = 0;
6323 rq->active_balance = 0;
6325 rq->migration_thread = NULL;
6326 INIT_LIST_HEAD(&rq->migration_queue);
6329 atomic_set(&rq->nr_iowait, 0);
6330 #ifdef CONFIG_VSERVER_HARDCPU
6331 INIT_LIST_HEAD(&rq->hold_queue);
6334 for (j = 0; j < 2; j++) {
6335 array = rq->arrays + j;
6336 for (k = 0; k < MAX_PRIO; k++) {
6337 INIT_LIST_HEAD(array->queue + k);
6338 __clear_bit(k, array->bitmap);
6340 // delimiter for bitsearch
6341 __set_bit(MAX_PRIO, array->bitmap);
6346 * The boot idle thread does lazy MMU switching as well:
6348 atomic_inc(&init_mm.mm_count);
6349 enter_lazy_tlb(&init_mm, current);
6352 * Make us the idle thread. Technically, schedule() should not be
6353 * called from this thread, however somewhere below it might be,
6354 * but because we are the idle thread, we just pick up running again
6355 * when this runqueue becomes "idle".
6357 init_idle(current, smp_processor_id());
6360 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
6361 void __might_sleep(char *file, int line)
6363 #if defined(in_atomic)
6364 static unsigned long prev_jiffy; /* ratelimiting */
6366 if ((in_atomic() || irqs_disabled()) &&
6367 system_state == SYSTEM_RUNNING && !oops_in_progress) {
6368 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6370 prev_jiffy = jiffies;
6371 printk(KERN_ERR "BUG: sleeping function called from invalid"
6372 " context at %s:%d\n", file, line);
6373 printk("in_atomic():%d, irqs_disabled():%d\n",
6374 in_atomic(), irqs_disabled());
6379 EXPORT_SYMBOL(__might_sleep);
6382 #ifdef CONFIG_MAGIC_SYSRQ
6383 void normalize_rt_tasks(void)
6385 struct task_struct *p;
6386 prio_array_t *array;
6387 unsigned long flags;
6390 read_lock_irq(&tasklist_lock);
6391 for_each_process (p) {
6395 rq = task_rq_lock(p, &flags);
6399 deactivate_task(p, task_rq(p));
6400 __setscheduler(p, SCHED_NORMAL, 0);
6402 vx_activate_task(p);
6403 __activate_task(p, task_rq(p));
6404 resched_task(rq->curr);
6407 task_rq_unlock(rq, &flags);
6409 read_unlock_irq(&tasklist_lock);
6412 #endif /* CONFIG_MAGIC_SYSRQ */
6416 * These functions are only useful for the IA64 MCA handling.
6418 * They can only be called when the whole system has been
6419 * stopped - every CPU needs to be quiescent, and no scheduling
6420 * activity can take place. Using them for anything else would
6421 * be a serious bug, and as a result, they aren't even visible
6422 * under any other configuration.
6426 * curr_task - return the current task for a given cpu.
6427 * @cpu: the processor in question.
6429 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6431 task_t *curr_task(int cpu)
6433 return cpu_curr(cpu);
6437 * set_curr_task - set the current task for a given cpu.
6438 * @cpu: the processor in question.
6439 * @p: the task pointer to set.
6441 * Description: This function must only be used when non-maskable interrupts
6442 * are serviced on a separate stack. It allows the architecture to switch the
6443 * notion of the current task on a cpu in a non-blocking manner. This function
6444 * must be called with all CPU's synchronized, and interrupts disabled, the
6445 * and caller must save the original value of the current task (see
6446 * curr_task() above) and restore that value before reenabling interrupts and
6447 * re-starting the system.
6449 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6451 void set_curr_task(int cpu, task_t *p)