4 * Kernel scheduler and related syscalls
6 * Copyright (C) 1991-2002 Linus Torvalds
8 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
9 * make semaphores SMP safe
10 * 1998-11-19 Implemented schedule_timeout() and related stuff
12 * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
13 * hybrid priority-list and round-robin design with
14 * an array-switch method of distributing timeslices
15 * and per-CPU runqueues. Cleanups and useful suggestions
16 * by Davide Libenzi, preemptible kernel bits by Robert Love.
17 * 2003-09-03 Interactivity tuning by Con Kolivas.
18 * 2004-04-02 Scheduler domains code by Nick Piggin
22 #include <linux/module.h>
23 #include <linux/nmi.h>
24 #include <linux/init.h>
25 #include <asm/uaccess.h>
26 #include <linux/highmem.h>
27 #include <linux/smp_lock.h>
28 #include <asm/mmu_context.h>
29 #include <linux/interrupt.h>
30 #include <linux/completion.h>
31 #include <linux/kernel_stat.h>
32 #include <linux/security.h>
33 #include <linux/notifier.h>
34 #include <linux/profile.h>
35 #include <linux/suspend.h>
36 #include <linux/blkdev.h>
37 #include <linux/delay.h>
38 #include <linux/smp.h>
39 #include <linux/threads.h>
40 #include <linux/timer.h>
41 #include <linux/rcupdate.h>
42 #include <linux/cpu.h>
43 #include <linux/percpu.h>
44 #include <linux/kthread.h>
45 #include <linux/seq_file.h>
46 #include <linux/syscalls.h>
47 #include <linux/times.h>
50 #include <asm/unistd.h>
51 #include <linux/vs_context.h>
52 #include <linux/vs_cvirt.h>
53 #include <linux/vs_sched.h>
56 * Convert user-nice values [ -20 ... 0 ... 19 ]
57 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
60 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
61 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
62 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
65 * 'User priority' is the nice value converted to something we
66 * can work with better when scaling various scheduler parameters,
67 * it's a [ 0 ... 39 ] range.
69 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
70 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
71 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
74 * Some helpers for converting nanosecond timing to jiffy resolution
76 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
77 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
80 * These are the 'tuning knobs' of the scheduler:
82 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
83 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
84 * Timeslices get refilled after they expire.
86 #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
87 #define DEF_TIMESLICE (100 * HZ / 1000)
88 #define ON_RUNQUEUE_WEIGHT 30
89 #define CHILD_PENALTY 95
90 #define PARENT_PENALTY 100
92 #define PRIO_BONUS_RATIO 25
93 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
94 #define INTERACTIVE_DELTA 2
95 #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
96 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
97 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
100 * If a task is 'interactive' then we reinsert it in the active
101 * array after it has expired its current timeslice. (it will not
102 * continue to run immediately, it will still roundrobin with
103 * other interactive tasks.)
105 * This part scales the interactivity limit depending on niceness.
107 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
108 * Here are a few examples of different nice levels:
110 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
111 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
112 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
113 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
114 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
116 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
117 * priority range a task can explore, a value of '1' means the
118 * task is rated interactive.)
120 * Ie. nice +19 tasks can never get 'interactive' enough to be
121 * reinserted into the active array. And only heavily CPU-hog nice -20
122 * tasks will be expired. Default nice 0 tasks are somewhere between,
123 * it takes some effort for them to get interactive, but it's not
127 #define CURRENT_BONUS(p) \
128 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
131 #define GRANULARITY (10 * HZ / 1000 ? : 1)
134 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
135 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
138 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
139 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
142 #define SCALE(v1,v1_max,v2_max) \
143 (v1) * (v2_max) / (v1_max)
146 (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
148 #define TASK_INTERACTIVE(p) \
149 ((p)->prio <= (p)->static_prio - DELTA(p))
151 #define INTERACTIVE_SLEEP(p) \
152 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
153 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
155 #define TASK_PREEMPTS_CURR(p, rq) \
156 ((p)->prio < (rq)->curr->prio)
159 * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
160 * to time slice values: [800ms ... 100ms ... 5ms]
162 * The higher a thread's priority, the bigger timeslices
163 * it gets during one round of execution. But even the lowest
164 * priority thread gets MIN_TIMESLICE worth of execution time.
167 #define SCALE_PRIO(x, prio) \
168 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO/2), MIN_TIMESLICE)
170 static unsigned int task_timeslice(task_t *p)
172 if (p->static_prio < NICE_TO_PRIO(0))
173 return SCALE_PRIO(DEF_TIMESLICE*4, p->static_prio);
175 return SCALE_PRIO(DEF_TIMESLICE, p->static_prio);
177 #define task_hot(p, now, sd) ((long long) ((now) - (p)->last_ran) \
178 < (long long) (sd)->cache_hot_time)
181 * These are the runqueue data structures:
184 #define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
186 typedef struct runqueue runqueue_t;
189 unsigned int nr_active;
190 unsigned long bitmap[BITMAP_SIZE];
191 struct list_head queue[MAX_PRIO];
195 * This is the main, per-CPU runqueue data structure.
197 * Locking rule: those places that want to lock multiple runqueues
198 * (such as the load balancing or the thread migration code), lock
199 * acquire operations must be ordered by ascending &runqueue.
205 * nr_running and cpu_load should be in the same cacheline because
206 * remote CPUs use both these fields when doing load calculation.
208 unsigned long nr_running;
210 unsigned long cpu_load;
212 unsigned long long nr_switches;
215 * This is part of a global counter where only the total sum
216 * over all CPUs matters. A task can increase this counter on
217 * one CPU and if it got migrated afterwards it may decrease
218 * it on another CPU. Always updated under the runqueue lock:
220 unsigned long nr_uninterruptible;
222 unsigned long expired_timestamp;
223 unsigned long long timestamp_last_tick;
225 struct mm_struct *prev_mm;
226 prio_array_t *active, *expired, arrays[2];
227 int best_expired_prio;
231 struct sched_domain *sd;
233 /* For active balancing */
237 task_t *migration_thread;
238 struct list_head migration_queue;
240 #ifdef CONFIG_VSERVER_HARDCPU
241 struct list_head hold_queue;
245 #ifdef CONFIG_SCHEDSTATS
247 struct sched_info rq_sched_info;
249 /* sys_sched_yield() stats */
250 unsigned long yld_exp_empty;
251 unsigned long yld_act_empty;
252 unsigned long yld_both_empty;
253 unsigned long yld_cnt;
255 /* schedule() stats */
256 unsigned long sched_noswitch;
257 unsigned long sched_switch;
258 unsigned long sched_cnt;
259 unsigned long sched_goidle;
261 /* pull_task() stats */
262 unsigned long pt_gained[MAX_IDLE_TYPES];
263 unsigned long pt_lost[MAX_IDLE_TYPES];
265 /* active_load_balance() stats */
266 unsigned long alb_cnt;
267 unsigned long alb_lost;
268 unsigned long alb_gained;
269 unsigned long alb_failed;
271 /* try_to_wake_up() stats */
272 unsigned long ttwu_cnt;
273 unsigned long ttwu_attempts;
274 unsigned long ttwu_moved;
276 /* wake_up_new_task() stats */
277 unsigned long wunt_cnt;
278 unsigned long wunt_moved;
280 /* sched_migrate_task() stats */
281 unsigned long smt_cnt;
283 /* sched_balance_exec() stats */
284 unsigned long sbe_cnt;
288 static DEFINE_PER_CPU(struct runqueue, runqueues);
290 #define for_each_domain(cpu, domain) \
291 for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
293 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
294 #define this_rq() (&__get_cpu_var(runqueues))
295 #define task_rq(p) cpu_rq(task_cpu(p))
296 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
299 * Default context-switch locking:
301 #ifndef prepare_arch_switch
302 # define prepare_arch_switch(rq, next) do { } while (0)
303 # define finish_arch_switch(rq, next) spin_unlock_irq(&(rq)->lock)
304 # define task_running(rq, p) ((rq)->curr == (p))
308 * task_rq_lock - lock the runqueue a given task resides on and disable
309 * interrupts. Note the ordering: we can safely lookup the task_rq without
310 * explicitly disabling preemption.
312 static runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
318 local_irq_save(*flags);
320 spin_lock(&rq->lock);
321 if (unlikely(rq != task_rq(p))) {
322 spin_unlock_irqrestore(&rq->lock, *flags);
323 goto repeat_lock_task;
328 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
331 spin_unlock_irqrestore(&rq->lock, *flags);
334 #ifdef CONFIG_SCHEDSTATS
336 * bump this up when changing the output format or the meaning of an existing
337 * format, so that tools can adapt (or abort)
339 #define SCHEDSTAT_VERSION 10
341 static int show_schedstat(struct seq_file *seq, void *v)
344 enum idle_type itype;
346 seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
347 seq_printf(seq, "timestamp %lu\n", jiffies);
348 for_each_online_cpu(cpu) {
349 runqueue_t *rq = cpu_rq(cpu);
351 struct sched_domain *sd;
355 /* runqueue-specific stats */
357 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu "
358 "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
359 cpu, rq->yld_both_empty,
360 rq->yld_act_empty, rq->yld_exp_empty,
361 rq->yld_cnt, rq->sched_noswitch,
362 rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
363 rq->alb_cnt, rq->alb_gained, rq->alb_lost,
365 rq->ttwu_cnt, rq->ttwu_moved, rq->ttwu_attempts,
366 rq->wunt_cnt, rq->wunt_moved,
367 rq->smt_cnt, rq->sbe_cnt, rq->rq_sched_info.cpu_time,
368 rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
370 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES; itype++)
371 seq_printf(seq, " %lu %lu", rq->pt_gained[itype],
373 seq_printf(seq, "\n");
376 /* domain-specific stats */
377 for_each_domain(cpu, sd) {
378 char mask_str[NR_CPUS];
380 cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
381 seq_printf(seq, "domain%d %s", dcnt++, mask_str);
382 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
384 seq_printf(seq, " %lu %lu %lu %lu %lu",
386 sd->lb_failed[itype],
387 sd->lb_imbalance[itype],
388 sd->lb_nobusyq[itype],
389 sd->lb_nobusyg[itype]);
391 seq_printf(seq, " %lu %lu %lu %lu\n",
392 sd->sbe_pushed, sd->sbe_attempts,
393 sd->ttwu_wake_affine, sd->ttwu_wake_balance);
400 static int schedstat_open(struct inode *inode, struct file *file)
402 unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
403 char *buf = kmalloc(size, GFP_KERNEL);
409 res = single_open(file, show_schedstat, NULL);
411 m = file->private_data;
419 struct file_operations proc_schedstat_operations = {
420 .open = schedstat_open,
423 .release = single_release,
426 # define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
427 # define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
428 #else /* !CONFIG_SCHEDSTATS */
429 # define schedstat_inc(rq, field) do { } while (0)
430 # define schedstat_add(rq, field, amt) do { } while (0)
434 * rq_lock - lock a given runqueue and disable interrupts.
436 static runqueue_t *this_rq_lock(void)
443 spin_lock(&rq->lock);
448 #ifdef CONFIG_SCHED_SMT
449 static int cpu_and_siblings_are_idle(int cpu)
452 for_each_cpu_mask(sib, cpu_sibling_map[cpu]) {
461 #define cpu_and_siblings_are_idle(A) idle_cpu(A)
464 #ifdef CONFIG_SCHEDSTATS
466 * Called when a process is dequeued from the active array and given
467 * the cpu. We should note that with the exception of interactive
468 * tasks, the expired queue will become the active queue after the active
469 * queue is empty, without explicitly dequeuing and requeuing tasks in the
470 * expired queue. (Interactive tasks may be requeued directly to the
471 * active queue, thus delaying tasks in the expired queue from running;
472 * see scheduler_tick()).
474 * This function is only called from sched_info_arrive(), rather than
475 * dequeue_task(). Even though a task may be queued and dequeued multiple
476 * times as it is shuffled about, we're really interested in knowing how
477 * long it was from the *first* time it was queued to the time that it
480 static inline void sched_info_dequeued(task_t *t)
482 t->sched_info.last_queued = 0;
486 * Called when a task finally hits the cpu. We can now calculate how
487 * long it was waiting to run. We also note when it began so that we
488 * can keep stats on how long its timeslice is.
490 static inline void sched_info_arrive(task_t *t)
492 unsigned long now = jiffies, diff = 0;
493 struct runqueue *rq = task_rq(t);
495 if (t->sched_info.last_queued)
496 diff = now - t->sched_info.last_queued;
497 sched_info_dequeued(t);
498 t->sched_info.run_delay += diff;
499 t->sched_info.last_arrival = now;
500 t->sched_info.pcnt++;
505 rq->rq_sched_info.run_delay += diff;
506 rq->rq_sched_info.pcnt++;
510 * Called when a process is queued into either the active or expired
511 * array. The time is noted and later used to determine how long we
512 * had to wait for us to reach the cpu. Since the expired queue will
513 * become the active queue after active queue is empty, without dequeuing
514 * and requeuing any tasks, we are interested in queuing to either. It
515 * is unusual but not impossible for tasks to be dequeued and immediately
516 * requeued in the same or another array: this can happen in sched_yield(),
517 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
520 * This function is only called from enqueue_task(), but also only updates
521 * the timestamp if it is already not set. It's assumed that
522 * sched_info_dequeued() will clear that stamp when appropriate.
524 static inline void sched_info_queued(task_t *t)
526 if (!t->sched_info.last_queued)
527 t->sched_info.last_queued = jiffies;
531 * Called when a process ceases being the active-running process, either
532 * voluntarily or involuntarily. Now we can calculate how long we ran.
534 static inline void sched_info_depart(task_t *t)
536 struct runqueue *rq = task_rq(t);
537 unsigned long diff = jiffies - t->sched_info.last_arrival;
539 t->sched_info.cpu_time += diff;
542 rq->rq_sched_info.cpu_time += diff;
546 * Called when tasks are switched involuntarily due, typically, to expiring
547 * their time slice. (This may also be called when switching to or from
548 * the idle task.) We are only called when prev != next.
550 static inline void sched_info_switch(task_t *prev, task_t *next)
552 struct runqueue *rq = task_rq(prev);
555 * prev now departs the cpu. It's not interesting to record
556 * stats about how efficient we were at scheduling the idle
559 if (prev != rq->idle)
560 sched_info_depart(prev);
562 if (next != rq->idle)
563 sched_info_arrive(next);
566 #define sched_info_queued(t) do { } while (0)
567 #define sched_info_switch(t, next) do { } while (0)
568 #endif /* CONFIG_SCHEDSTATS */
571 * Adding/removing a task to/from a priority array:
573 static void dequeue_task(struct task_struct *p, prio_array_t *array)
575 BUG_ON(p->state & TASK_ONHOLD);
577 list_del(&p->run_list);
578 if (list_empty(array->queue + p->prio))
579 __clear_bit(p->prio, array->bitmap);
582 static void enqueue_task(struct task_struct *p, prio_array_t *array)
584 BUG_ON(p->state & TASK_ONHOLD);
585 sched_info_queued(p);
586 list_add_tail(&p->run_list, array->queue + p->prio);
587 __set_bit(p->prio, array->bitmap);
593 * Put task to the end of the run list without the overhead of dequeue
594 * followed by enqueue.
596 static void requeue_task(struct task_struct *p, prio_array_t *array)
598 BUG_ON(p->state & TASK_ONHOLD);
599 list_move_tail(&p->run_list, array->queue + p->prio);
602 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
604 BUG_ON(p->state & TASK_ONHOLD);
605 list_add(&p->run_list, array->queue + p->prio);
606 __set_bit(p->prio, array->bitmap);
612 * effective_prio - return the priority that is based on the static
613 * priority but is modified by bonuses/penalties.
615 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
616 * into the -5 ... 0 ... +5 bonus/penalty range.
618 * We use 25% of the full 0...39 priority range so that:
620 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
621 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
623 * Both properties are important to certain workloads.
625 static int effective_prio(task_t *p)
633 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
635 prio = p->static_prio - bonus;
637 if ((vxi = p->vx_info) &&
638 vx_info_flags(vxi, VXF_SCHED_PRIO, 0))
639 prio += vx_effective_vavavoom(vxi, MAX_USER_PRIO);
641 if (prio < MAX_RT_PRIO)
643 if (prio > MAX_PRIO-1)
649 * __activate_task - move a task to the runqueue.
651 static inline void __activate_task(task_t *p, runqueue_t *rq)
653 enqueue_task(p, rq->active);
658 * __activate_idle_task - move idle task to the _front_ of runqueue.
660 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
662 enqueue_task_head(p, rq->active);
666 static void recalc_task_prio(task_t *p, unsigned long long now)
668 unsigned long long __sleep_time = now - p->timestamp;
669 unsigned long sleep_time;
671 if (__sleep_time > NS_MAX_SLEEP_AVG)
672 sleep_time = NS_MAX_SLEEP_AVG;
674 sleep_time = (unsigned long)__sleep_time;
676 if (likely(sleep_time > 0)) {
678 * User tasks that sleep a long time are categorised as
679 * idle and will get just interactive status to stay active &
680 * prevent them suddenly becoming cpu hogs and starving
683 if (p->mm && p->activated != -1 &&
684 sleep_time > INTERACTIVE_SLEEP(p)) {
685 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
689 * The lower the sleep avg a task has the more
690 * rapidly it will rise with sleep time.
692 sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
695 * Tasks waking from uninterruptible sleep are
696 * limited in their sleep_avg rise as they
697 * are likely to be waiting on I/O
699 if (p->activated == -1 && p->mm) {
700 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
702 else if (p->sleep_avg + sleep_time >=
703 INTERACTIVE_SLEEP(p)) {
704 p->sleep_avg = INTERACTIVE_SLEEP(p);
710 * This code gives a bonus to interactive tasks.
712 * The boost works by updating the 'average sleep time'
713 * value here, based on ->timestamp. The more time a
714 * task spends sleeping, the higher the average gets -
715 * and the higher the priority boost gets as well.
717 p->sleep_avg += sleep_time;
719 if (p->sleep_avg > NS_MAX_SLEEP_AVG)
720 p->sleep_avg = NS_MAX_SLEEP_AVG;
724 p->prio = effective_prio(p);
728 * activate_task - move a task to the runqueue and do priority recalculation
730 * Update all the scheduling statistics stuff. (sleep average
731 * calculation, priority modifiers, etc.)
733 static void activate_task(task_t *p, runqueue_t *rq, int local)
735 unsigned long long now;
740 /* Compensate for drifting sched_clock */
741 runqueue_t *this_rq = this_rq();
742 now = (now - this_rq->timestamp_last_tick)
743 + rq->timestamp_last_tick;
747 recalc_task_prio(p, now);
750 * This checks to make sure it's not an uninterruptible task
751 * that is now waking up.
755 * Tasks which were woken up by interrupts (ie. hw events)
756 * are most likely of interactive nature. So we give them
757 * the credit of extending their sleep time to the period
758 * of time they spend on the runqueue, waiting for execution
759 * on a CPU, first time around:
765 * Normal first-time wakeups get a credit too for
766 * on-runqueue time, but it will be weighted down:
774 __activate_task(p, rq);
778 * deactivate_task - remove a task from the runqueue.
780 static void __deactivate_task(struct task_struct *p, runqueue_t *rq)
783 dequeue_task(p, p->array);
788 void deactivate_task(struct task_struct *p, runqueue_t *rq)
790 vx_deactivate_task(p);
791 __deactivate_task(p, rq);
795 #ifdef CONFIG_VSERVER_HARDCPU
797 * vx_hold_task - put a task on the hold queue
800 void vx_hold_task(struct vx_info *vxi,
801 struct task_struct *p, runqueue_t *rq)
803 __deactivate_task(p, rq);
804 p->state |= TASK_ONHOLD;
805 /* a new one on hold */
807 list_add_tail(&p->run_list, &rq->hold_queue);
811 * vx_unhold_task - put a task back to the runqueue
814 void vx_unhold_task(struct vx_info *vxi,
815 struct task_struct *p, runqueue_t *rq)
817 list_del(&p->run_list);
818 /* one less waiting */
820 p->state &= ~TASK_ONHOLD;
821 enqueue_task(p, rq->expired);
824 if (p->static_prio < rq->best_expired_prio)
825 rq->best_expired_prio = p->static_prio;
829 void vx_hold_task(struct vx_info *vxi,
830 struct task_struct *p, runqueue_t *rq)
836 void vx_unhold_task(struct vx_info *vxi,
837 struct task_struct *p, runqueue_t *rq)
841 #endif /* CONFIG_VSERVER_HARDCPU */
845 * resched_task - mark a task 'to be rescheduled now'.
847 * On UP this means the setting of the need_resched flag, on SMP it
848 * might also involve a cross-CPU call to trigger the scheduler on
852 static void resched_task(task_t *p)
854 int need_resched, nrpolling;
856 assert_spin_locked(&task_rq(p)->lock);
858 /* minimise the chance of sending an interrupt to poll_idle() */
859 nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
860 need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
861 nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
863 if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
864 smp_send_reschedule(task_cpu(p));
867 static inline void resched_task(task_t *p)
869 set_tsk_need_resched(p);
874 * task_curr - is this task currently executing on a CPU?
875 * @p: the task in question.
877 inline int task_curr(const task_t *p)
879 return cpu_curr(task_cpu(p)) == p;
889 struct list_head list;
890 enum request_type type;
892 /* For REQ_MOVE_TASK */
896 /* For REQ_SET_DOMAIN */
897 struct sched_domain *sd;
899 struct completion done;
903 * The task's runqueue lock must be held.
904 * Returns true if you have to wait for migration thread.
906 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
908 runqueue_t *rq = task_rq(p);
911 * If the task is not on a runqueue (and not running), then
912 * it is sufficient to simply update the task's cpu field.
914 if (!p->array && !task_running(rq, p)) {
915 set_task_cpu(p, dest_cpu);
919 init_completion(&req->done);
920 req->type = REQ_MOVE_TASK;
922 req->dest_cpu = dest_cpu;
923 list_add(&req->list, &rq->migration_queue);
928 * wait_task_inactive - wait for a thread to unschedule.
930 * The caller must ensure that the task *will* unschedule sometime soon,
931 * else this function might spin for a *long* time. This function can't
932 * be called with interrupts off, or it may introduce deadlock with
933 * smp_call_function() if an IPI is sent by the same process we are
934 * waiting to become inactive.
936 void wait_task_inactive(task_t * p)
943 rq = task_rq_lock(p, &flags);
944 /* Must be off runqueue entirely, not preempted. */
945 if (unlikely(p->array || task_running(rq, p))) {
946 /* If it's preempted, we yield. It could be a while. */
947 preempted = !task_running(rq, p);
948 task_rq_unlock(rq, &flags);
954 task_rq_unlock(rq, &flags);
958 * kick_process - kick a running thread to enter/exit the kernel
959 * @p: the to-be-kicked thread
961 * Cause a process which is running on another CPU to enter
962 * kernel-mode, without any delay. (to get signals handled.)
964 * NOTE: this function doesnt have to take the runqueue lock,
965 * because all it wants to ensure is that the remote task enters
966 * the kernel. If the IPI races and the task has been migrated
967 * to another CPU then no harm is done and the purpose has been
970 void kick_process(task_t *p)
976 if ((cpu != smp_processor_id()) && task_curr(p))
977 smp_send_reschedule(cpu);
982 * Return a low guess at the load of a migration-source cpu.
984 * We want to under-estimate the load of migration sources, to
985 * balance conservatively.
987 static inline unsigned long source_load(int cpu)
989 runqueue_t *rq = cpu_rq(cpu);
990 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
992 return min(rq->cpu_load, load_now);
996 * Return a high guess at the load of a migration-target cpu
998 static inline unsigned long target_load(int cpu)
1000 runqueue_t *rq = cpu_rq(cpu);
1001 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
1003 return max(rq->cpu_load, load_now);
1009 * wake_idle() will wake a task on an idle cpu if task->cpu is
1010 * not idle and an idle cpu is available. The span of cpus to
1011 * search starts with cpus closest then further out as needed,
1012 * so we always favor a closer, idle cpu.
1014 * Returns the CPU we should wake onto.
1016 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1017 static int wake_idle(int cpu, task_t *p)
1020 struct sched_domain *sd;
1026 for_each_domain(cpu, sd) {
1027 if (sd->flags & SD_WAKE_IDLE) {
1028 cpus_and(tmp, sd->span, cpu_online_map);
1029 cpus_and(tmp, tmp, p->cpus_allowed);
1030 for_each_cpu_mask(i, tmp) {
1040 static inline int wake_idle(int cpu, task_t *p)
1047 * try_to_wake_up - wake up a thread
1048 * @p: the to-be-woken-up thread
1049 * @state: the mask of task states that can be woken
1050 * @sync: do a synchronous wakeup?
1052 * Put it on the run-queue if it's not already there. The "current"
1053 * thread is always on the run-queue (except when the actual
1054 * re-schedule is in progress), and as such you're allowed to do
1055 * the simpler "current->state = TASK_RUNNING" to mark yourself
1056 * runnable without the overhead of this.
1058 * returns failure only if the task is already active.
1060 static int try_to_wake_up(task_t * p, unsigned int state, int sync)
1062 int cpu, this_cpu, success = 0;
1063 unsigned long flags;
1067 unsigned long load, this_load;
1068 struct sched_domain *sd;
1072 rq = task_rq_lock(p, &flags);
1073 schedstat_inc(rq, ttwu_cnt);
1074 old_state = p->state;
1076 /* we need to unhold suspended tasks */
1077 if (old_state & TASK_ONHOLD) {
1078 vx_unhold_task(p->vx_info, p, rq);
1079 old_state = p->state;
1081 if (!(old_state & state))
1088 this_cpu = smp_processor_id();
1091 if (unlikely(task_running(rq, p)))
1096 if (cpu == this_cpu || unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1099 load = source_load(cpu);
1100 this_load = target_load(this_cpu);
1103 * If sync wakeup then subtract the (maximum possible) effect of
1104 * the currently running task from the load of the current CPU:
1107 this_load -= SCHED_LOAD_SCALE;
1109 /* Don't pull the task off an idle CPU to a busy one */
1110 if (load < SCHED_LOAD_SCALE/2 && this_load > SCHED_LOAD_SCALE/2)
1113 new_cpu = this_cpu; /* Wake to this CPU if we can */
1116 * Scan domains for affine wakeup and passive balancing
1119 for_each_domain(this_cpu, sd) {
1120 unsigned int imbalance;
1122 * Start passive balancing when half the imbalance_pct
1125 imbalance = sd->imbalance_pct + (sd->imbalance_pct - 100) / 2;
1127 if ((sd->flags & SD_WAKE_AFFINE) &&
1128 !task_hot(p, rq->timestamp_last_tick, sd)) {
1130 * This domain has SD_WAKE_AFFINE and p is cache cold
1133 if (cpu_isset(cpu, sd->span)) {
1134 schedstat_inc(sd, ttwu_wake_affine);
1137 } else if ((sd->flags & SD_WAKE_BALANCE) &&
1138 imbalance*this_load <= 100*load) {
1140 * This domain has SD_WAKE_BALANCE and there is
1143 if (cpu_isset(cpu, sd->span)) {
1144 schedstat_inc(sd, ttwu_wake_balance);
1150 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1152 schedstat_inc(rq, ttwu_attempts);
1153 new_cpu = wake_idle(new_cpu, p);
1154 if (new_cpu != cpu) {
1155 schedstat_inc(rq, ttwu_moved);
1156 set_task_cpu(p, new_cpu);
1157 task_rq_unlock(rq, &flags);
1158 /* might preempt at this point */
1159 rq = task_rq_lock(p, &flags);
1160 old_state = p->state;
1161 if (!(old_state & state))
1166 this_cpu = smp_processor_id();
1171 #endif /* CONFIG_SMP */
1172 if (old_state == TASK_UNINTERRUPTIBLE) {
1173 rq->nr_uninterruptible--;
1175 * Tasks on involuntary sleep don't earn
1176 * sleep_avg beyond just interactive state.
1182 * Sync wakeups (i.e. those types of wakeups where the waker
1183 * has indicated that it will leave the CPU in short order)
1184 * don't trigger a preemption, if the woken up task will run on
1185 * this cpu. (in this case the 'I will reschedule' promise of
1186 * the waker guarantees that the freshly woken up task is going
1187 * to be considered on this CPU.)
1189 activate_task(p, rq, cpu == this_cpu);
1190 /* this is to get the accounting behind the load update */
1191 if (old_state == TASK_UNINTERRUPTIBLE)
1192 vx_uninterruptible_dec(p);
1193 if (!sync || cpu != this_cpu) {
1194 if (TASK_PREEMPTS_CURR(p, rq))
1195 resched_task(rq->curr);
1200 p->state = TASK_RUNNING;
1202 task_rq_unlock(rq, &flags);
1207 int fastcall wake_up_process(task_t * p)
1209 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1210 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1213 EXPORT_SYMBOL(wake_up_process);
1215 int fastcall wake_up_state(task_t *p, unsigned int state)
1217 return try_to_wake_up(p, state, 0);
1221 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1222 struct sched_domain *sd);
1226 * Perform scheduler related setup for a newly forked process p.
1227 * p is forked by current.
1229 void fastcall sched_fork(task_t *p)
1232 * We mark the process as running here, but have not actually
1233 * inserted it onto the runqueue yet. This guarantees that
1234 * nobody will actually run it, and a signal or other external
1235 * event cannot wake it up and insert it on the runqueue either.
1237 p->state = TASK_RUNNING;
1238 INIT_LIST_HEAD(&p->run_list);
1240 spin_lock_init(&p->switch_lock);
1241 #ifdef CONFIG_SCHEDSTATS
1242 memset(&p->sched_info, 0, sizeof(p->sched_info));
1244 #ifdef CONFIG_PREEMPT
1246 * During context-switch we hold precisely one spinlock, which
1247 * schedule_tail drops. (in the common case it's this_rq()->lock,
1248 * but it also can be p->switch_lock.) So we compensate with a count
1249 * of 1. Also, we want to start with kernel preemption disabled.
1251 p->thread_info->preempt_count = 1;
1254 * Share the timeslice between parent and child, thus the
1255 * total amount of pending timeslices in the system doesn't change,
1256 * resulting in more scheduling fairness.
1258 local_irq_disable();
1259 p->time_slice = (current->time_slice + 1) >> 1;
1261 * The remainder of the first timeslice might be recovered by
1262 * the parent if the child exits early enough.
1264 p->first_time_slice = 1;
1265 current->time_slice >>= 1;
1266 p->timestamp = sched_clock();
1267 if (unlikely(!current->time_slice)) {
1269 * This case is rare, it happens when the parent has only
1270 * a single jiffy left from its timeslice. Taking the
1271 * runqueue lock is not a problem.
1273 current->time_slice = 1;
1283 * wake_up_new_task - wake up a newly created task for the first time.
1285 * This function will do some initial scheduler statistics housekeeping
1286 * that must be done for every newly created context, then puts the task
1287 * on the runqueue and wakes it.
1289 void fastcall wake_up_new_task(task_t * p, unsigned long clone_flags)
1291 unsigned long flags;
1293 runqueue_t *rq, *this_rq;
1295 rq = task_rq_lock(p, &flags);
1297 this_cpu = smp_processor_id();
1299 BUG_ON(p->state != TASK_RUNNING);
1301 schedstat_inc(rq, wunt_cnt);
1303 * We decrease the sleep average of forking parents
1304 * and children as well, to keep max-interactive tasks
1305 * from forking tasks that are max-interactive. The parent
1306 * (current) is done further down, under its lock.
1308 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1309 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1311 p->prio = effective_prio(p);
1313 vx_activate_task(p);
1314 if (likely(cpu == this_cpu)) {
1315 if (!(clone_flags & CLONE_VM)) {
1317 * The VM isn't cloned, so we're in a good position to
1318 * do child-runs-first in anticipation of an exec. This
1319 * usually avoids a lot of COW overhead.
1321 if (unlikely(!current->array))
1322 __activate_task(p, rq);
1324 p->prio = current->prio;
1325 BUG_ON(p->state & TASK_ONHOLD);
1326 list_add_tail(&p->run_list, ¤t->run_list);
1327 p->array = current->array;
1328 p->array->nr_active++;
1333 /* Run child last */
1334 __activate_task(p, rq);
1336 * We skip the following code due to cpu == this_cpu
1338 * task_rq_unlock(rq, &flags);
1339 * this_rq = task_rq_lock(current, &flags);
1343 this_rq = cpu_rq(this_cpu);
1346 * Not the local CPU - must adjust timestamp. This should
1347 * get optimised away in the !CONFIG_SMP case.
1349 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1350 + rq->timestamp_last_tick;
1351 __activate_task(p, rq);
1352 if (TASK_PREEMPTS_CURR(p, rq))
1353 resched_task(rq->curr);
1355 schedstat_inc(rq, wunt_moved);
1357 * Parent and child are on different CPUs, now get the
1358 * parent runqueue to update the parent's ->sleep_avg:
1360 task_rq_unlock(rq, &flags);
1361 this_rq = task_rq_lock(current, &flags);
1363 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1364 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1365 task_rq_unlock(this_rq, &flags);
1369 * Potentially available exiting-child timeslices are
1370 * retrieved here - this way the parent does not get
1371 * penalized for creating too many threads.
1373 * (this cannot be used to 'generate' timeslices
1374 * artificially, because any timeslice recovered here
1375 * was given away by the parent in the first place.)
1377 void fastcall sched_exit(task_t * p)
1379 unsigned long flags;
1383 * If the child was a (relative-) CPU hog then decrease
1384 * the sleep_avg of the parent as well.
1386 rq = task_rq_lock(p->parent, &flags);
1387 if (p->first_time_slice) {
1388 p->parent->time_slice += p->time_slice;
1389 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1390 p->parent->time_slice = task_timeslice(p);
1392 if (p->sleep_avg < p->parent->sleep_avg)
1393 p->parent->sleep_avg = p->parent->sleep_avg /
1394 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1396 task_rq_unlock(rq, &flags);
1400 * finish_task_switch - clean up after a task-switch
1401 * @prev: the thread we just switched away from.
1403 * We enter this with the runqueue still locked, and finish_arch_switch()
1404 * will unlock it along with doing any other architecture-specific cleanup
1407 * Note that we may have delayed dropping an mm in context_switch(). If
1408 * so, we finish that here outside of the runqueue lock. (Doing it
1409 * with the lock held can cause deadlocks; see schedule() for
1412 static void finish_task_switch(task_t *prev)
1413 __releases(rq->lock)
1415 runqueue_t *rq = this_rq();
1416 struct mm_struct *mm = rq->prev_mm;
1417 unsigned long prev_task_flags;
1422 * A task struct has one reference for the use as "current".
1423 * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1424 * calls schedule one last time. The schedule call will never return,
1425 * and the scheduled task must drop that reference.
1426 * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1427 * still held, otherwise prev could be scheduled on another cpu, die
1428 * there before we look at prev->state, and then the reference would
1430 * Manfred Spraul <manfred@colorfullife.com>
1432 prev_task_flags = prev->flags;
1433 finish_arch_switch(rq, prev);
1436 if (unlikely(prev_task_flags & PF_DEAD))
1437 put_task_struct(prev);
1441 * schedule_tail - first thing a freshly forked thread must call.
1442 * @prev: the thread we just switched away from.
1444 asmlinkage void schedule_tail(task_t *prev)
1445 __releases(rq->lock)
1447 finish_task_switch(prev);
1449 if (current->set_child_tid)
1450 put_user(current->pid, current->set_child_tid);
1454 * context_switch - switch to the new MM and the new
1455 * thread's register state.
1458 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1460 struct mm_struct *mm = next->mm;
1461 struct mm_struct *oldmm = prev->active_mm;
1463 if (unlikely(!mm)) {
1464 next->active_mm = oldmm;
1465 atomic_inc(&oldmm->mm_count);
1466 enter_lazy_tlb(oldmm, next);
1468 switch_mm(oldmm, mm, next);
1470 if (unlikely(!prev->mm)) {
1471 prev->active_mm = NULL;
1472 WARN_ON(rq->prev_mm);
1473 rq->prev_mm = oldmm;
1476 /* Here we just switch the register state and the stack. */
1477 switch_to(prev, next, prev);
1483 * nr_running, nr_uninterruptible and nr_context_switches:
1485 * externally visible scheduler statistics: current number of runnable
1486 * threads, current number of uninterruptible-sleeping threads, total
1487 * number of context switches performed since bootup.
1489 unsigned long nr_running(void)
1491 unsigned long i, sum = 0;
1493 for_each_online_cpu(i)
1494 sum += cpu_rq(i)->nr_running;
1499 unsigned long nr_uninterruptible(void)
1501 unsigned long i, sum = 0;
1504 sum += cpu_rq(i)->nr_uninterruptible;
1507 * Since we read the counters lockless, it might be slightly
1508 * inaccurate. Do not allow it to go below zero though:
1510 if (unlikely((long)sum < 0))
1516 unsigned long long nr_context_switches(void)
1518 unsigned long long i, sum = 0;
1521 sum += cpu_rq(i)->nr_switches;
1526 unsigned long nr_iowait(void)
1528 unsigned long i, sum = 0;
1531 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1539 * double_rq_lock - safely lock two runqueues
1541 * Note this does not disable interrupts like task_rq_lock,
1542 * you need to do so manually before calling.
1544 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1545 __acquires(rq1->lock)
1546 __acquires(rq2->lock)
1549 spin_lock(&rq1->lock);
1550 __acquire(rq2->lock); /* Fake it out ;) */
1553 spin_lock(&rq1->lock);
1554 spin_lock(&rq2->lock);
1556 spin_lock(&rq2->lock);
1557 spin_lock(&rq1->lock);
1563 * double_rq_unlock - safely unlock two runqueues
1565 * Note this does not restore interrupts like task_rq_unlock,
1566 * you need to do so manually after calling.
1568 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1569 __releases(rq1->lock)
1570 __releases(rq2->lock)
1572 spin_unlock(&rq1->lock);
1574 spin_unlock(&rq2->lock);
1576 __release(rq2->lock);
1580 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1582 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1583 __releases(this_rq->lock)
1584 __acquires(busiest->lock)
1585 __acquires(this_rq->lock)
1587 if (unlikely(!spin_trylock(&busiest->lock))) {
1588 if (busiest < this_rq) {
1589 spin_unlock(&this_rq->lock);
1590 spin_lock(&busiest->lock);
1591 spin_lock(&this_rq->lock);
1593 spin_lock(&busiest->lock);
1598 * find_idlest_cpu - find the least busy runqueue.
1600 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1601 struct sched_domain *sd)
1603 unsigned long load, min_load, this_load;
1608 min_load = ULONG_MAX;
1610 cpus_and(mask, sd->span, p->cpus_allowed);
1612 for_each_cpu_mask(i, mask) {
1613 load = target_load(i);
1615 if (load < min_load) {
1619 /* break out early on an idle CPU: */
1625 /* add +1 to account for the new task */
1626 this_load = source_load(this_cpu) + SCHED_LOAD_SCALE;
1629 * Would with the addition of the new task to the
1630 * current CPU there be an imbalance between this
1631 * CPU and the idlest CPU?
1633 * Use half of the balancing threshold - new-context is
1634 * a good opportunity to balance.
1636 if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1643 * If dest_cpu is allowed for this process, migrate the task to it.
1644 * This is accomplished by forcing the cpu_allowed mask to only
1645 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1646 * the cpu_allowed mask is restored.
1648 static void sched_migrate_task(task_t *p, int dest_cpu)
1650 migration_req_t req;
1652 unsigned long flags;
1654 rq = task_rq_lock(p, &flags);
1655 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1656 || unlikely(cpu_is_offline(dest_cpu)))
1659 schedstat_inc(rq, smt_cnt);
1660 /* force the process onto the specified CPU */
1661 if (migrate_task(p, dest_cpu, &req)) {
1662 /* Need to wait for migration thread (might exit: take ref). */
1663 struct task_struct *mt = rq->migration_thread;
1664 get_task_struct(mt);
1665 task_rq_unlock(rq, &flags);
1666 wake_up_process(mt);
1667 put_task_struct(mt);
1668 wait_for_completion(&req.done);
1672 task_rq_unlock(rq, &flags);
1676 * sched_exec(): find the highest-level, exec-balance-capable
1677 * domain and try to migrate the task to the least loaded CPU.
1679 * execve() is a valuable balancing opportunity, because at this point
1680 * the task has the smallest effective memory and cache footprint.
1682 void sched_exec(void)
1684 struct sched_domain *tmp, *sd = NULL;
1685 int new_cpu, this_cpu = get_cpu();
1687 schedstat_inc(this_rq(), sbe_cnt);
1688 /* Prefer the current CPU if there's only this task running */
1689 if (this_rq()->nr_running <= 1)
1692 for_each_domain(this_cpu, tmp)
1693 if (tmp->flags & SD_BALANCE_EXEC)
1697 schedstat_inc(sd, sbe_attempts);
1698 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1699 if (new_cpu != this_cpu) {
1700 schedstat_inc(sd, sbe_pushed);
1702 sched_migrate_task(current, new_cpu);
1711 * pull_task - move a task from a remote runqueue to the local runqueue.
1712 * Both runqueues must be locked.
1715 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1716 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1718 dequeue_task(p, src_array);
1719 src_rq->nr_running--;
1720 set_task_cpu(p, this_cpu);
1721 this_rq->nr_running++;
1722 enqueue_task(p, this_array);
1723 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1724 + this_rq->timestamp_last_tick;
1726 * Note that idle threads have a prio of MAX_PRIO, for this test
1727 * to be always true for them.
1729 if (TASK_PREEMPTS_CURR(p, this_rq))
1730 resched_task(this_rq->curr);
1734 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1737 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1738 struct sched_domain *sd, enum idle_type idle)
1741 * We do not migrate tasks that are:
1742 * 1) running (obviously), or
1743 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1744 * 3) are cache-hot on their current CPU.
1746 if (task_running(rq, p))
1748 if (!cpu_isset(this_cpu, p->cpus_allowed))
1752 * Aggressive migration if:
1753 * 1) the [whole] cpu is idle, or
1754 * 2) too many balance attempts have failed.
1757 if (cpu_and_siblings_are_idle(this_cpu) || \
1758 sd->nr_balance_failed > sd->cache_nice_tries)
1761 if (task_hot(p, rq->timestamp_last_tick, sd))
1767 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1768 * as part of a balancing operation within "domain". Returns the number of
1771 * Called with both runqueues locked.
1773 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1774 unsigned long max_nr_move, struct sched_domain *sd,
1775 enum idle_type idle)
1777 prio_array_t *array, *dst_array;
1778 struct list_head *head, *curr;
1779 int idx, pulled = 0;
1782 if (max_nr_move <= 0 || busiest->nr_running <= 1)
1786 * We first consider expired tasks. Those will likely not be
1787 * executed in the near future, and they are most likely to
1788 * be cache-cold, thus switching CPUs has the least effect
1791 if (busiest->expired->nr_active) {
1792 array = busiest->expired;
1793 dst_array = this_rq->expired;
1795 array = busiest->active;
1796 dst_array = this_rq->active;
1800 /* Start searching at priority 0: */
1804 idx = sched_find_first_bit(array->bitmap);
1806 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1807 if (idx >= MAX_PRIO) {
1808 if (array == busiest->expired && busiest->active->nr_active) {
1809 array = busiest->active;
1810 dst_array = this_rq->active;
1816 head = array->queue + idx;
1819 tmp = list_entry(curr, task_t, run_list);
1823 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
1831 * Right now, this is the only place pull_task() is called,
1832 * so we can safely collect pull_task() stats here rather than
1833 * inside pull_task().
1835 schedstat_inc(this_rq, pt_gained[idle]);
1836 schedstat_inc(busiest, pt_lost[idle]);
1838 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
1841 /* We only want to steal up to the prescribed number of tasks. */
1842 if (pulled < max_nr_move) {
1853 * find_busiest_group finds and returns the busiest CPU group within the
1854 * domain. It calculates and returns the number of tasks which should be
1855 * moved to restore balance via the imbalance parameter.
1857 static struct sched_group *
1858 find_busiest_group(struct sched_domain *sd, int this_cpu,
1859 unsigned long *imbalance, enum idle_type idle)
1861 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
1862 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
1864 max_load = this_load = total_load = total_pwr = 0;
1871 local_group = cpu_isset(this_cpu, group->cpumask);
1873 /* Tally up the load of all CPUs in the group */
1876 for_each_cpu_mask(i, group->cpumask) {
1877 /* Bias balancing toward cpus of our domain */
1879 load = target_load(i);
1881 load = source_load(i);
1890 total_load += avg_load;
1891 total_pwr += group->cpu_power;
1893 /* Adjust by relative CPU power of the group */
1894 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1897 this_load = avg_load;
1900 } else if (avg_load > max_load) {
1901 max_load = avg_load;
1905 group = group->next;
1906 } while (group != sd->groups);
1908 if (!busiest || this_load >= max_load)
1911 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
1913 if (this_load >= avg_load ||
1914 100*max_load <= sd->imbalance_pct*this_load)
1918 * We're trying to get all the cpus to the average_load, so we don't
1919 * want to push ourselves above the average load, nor do we wish to
1920 * reduce the max loaded cpu below the average load, as either of these
1921 * actions would just result in more rebalancing later, and ping-pong
1922 * tasks around. Thus we look for the minimum possible imbalance.
1923 * Negative imbalances (*we* are more loaded than anyone else) will
1924 * be counted as no imbalance for these purposes -- we can't fix that
1925 * by pulling tasks to us. Be careful of negative numbers as they'll
1926 * appear as very large values with unsigned longs.
1928 *imbalance = min(max_load - avg_load, avg_load - this_load);
1930 /* How much load to actually move to equalise the imbalance */
1931 *imbalance = (*imbalance * min(busiest->cpu_power, this->cpu_power))
1934 if (*imbalance < SCHED_LOAD_SCALE - 1) {
1935 unsigned long pwr_now = 0, pwr_move = 0;
1938 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
1944 * OK, we don't have enough imbalance to justify moving tasks,
1945 * however we may be able to increase total CPU power used by
1949 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
1950 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
1951 pwr_now /= SCHED_LOAD_SCALE;
1953 /* Amount of load we'd subtract */
1954 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
1956 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
1959 /* Amount of load we'd add */
1960 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
1963 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
1964 pwr_move /= SCHED_LOAD_SCALE;
1966 /* Move if we gain another 8th of a CPU worth of throughput */
1967 if (pwr_move < pwr_now + SCHED_LOAD_SCALE / 8)
1974 /* Get rid of the scaling factor, rounding down as we divide */
1975 *imbalance = (*imbalance + 1) / SCHED_LOAD_SCALE;
1980 if (busiest && (idle == NEWLY_IDLE ||
1981 (idle == SCHED_IDLE && max_load > SCHED_LOAD_SCALE)) ) {
1991 * find_busiest_queue - find the busiest runqueue among the cpus in group.
1993 static runqueue_t *find_busiest_queue(struct sched_group *group)
1995 unsigned long load, max_load = 0;
1996 runqueue_t *busiest = NULL;
1999 for_each_cpu_mask(i, group->cpumask) {
2000 load = source_load(i);
2002 if (load > max_load) {
2004 busiest = cpu_rq(i);
2012 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2013 * tasks if there is an imbalance.
2015 * Called with this_rq unlocked.
2017 static int load_balance(int this_cpu, runqueue_t *this_rq,
2018 struct sched_domain *sd, enum idle_type idle)
2020 struct sched_group *group;
2021 runqueue_t *busiest;
2022 unsigned long imbalance;
2025 spin_lock(&this_rq->lock);
2026 schedstat_inc(sd, lb_cnt[idle]);
2028 group = find_busiest_group(sd, this_cpu, &imbalance, idle);
2030 schedstat_inc(sd, lb_nobusyg[idle]);
2034 busiest = find_busiest_queue(group);
2036 schedstat_inc(sd, lb_nobusyq[idle]);
2041 * This should be "impossible", but since load
2042 * balancing is inherently racy and statistical,
2043 * it could happen in theory.
2045 if (unlikely(busiest == this_rq)) {
2050 schedstat_add(sd, lb_imbalance[idle], imbalance);
2053 if (busiest->nr_running > 1) {
2055 * Attempt to move tasks. If find_busiest_group has found
2056 * an imbalance but busiest->nr_running <= 1, the group is
2057 * still unbalanced. nr_moved simply stays zero, so it is
2058 * correctly treated as an imbalance.
2060 double_lock_balance(this_rq, busiest);
2061 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2062 imbalance, sd, idle);
2063 spin_unlock(&busiest->lock);
2065 spin_unlock(&this_rq->lock);
2068 schedstat_inc(sd, lb_failed[idle]);
2069 sd->nr_balance_failed++;
2071 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2074 spin_lock(&busiest->lock);
2075 if (!busiest->active_balance) {
2076 busiest->active_balance = 1;
2077 busiest->push_cpu = this_cpu;
2080 spin_unlock(&busiest->lock);
2082 wake_up_process(busiest->migration_thread);
2085 * We've kicked active balancing, reset the failure
2088 sd->nr_balance_failed = sd->cache_nice_tries;
2092 * We were unbalanced, but unsuccessful in move_tasks(),
2093 * so bump the balance_interval to lessen the lock contention.
2095 if (sd->balance_interval < sd->max_interval)
2096 sd->balance_interval++;
2098 sd->nr_balance_failed = 0;
2100 /* We were unbalanced, so reset the balancing interval */
2101 sd->balance_interval = sd->min_interval;
2107 spin_unlock(&this_rq->lock);
2109 /* tune up the balancing interval */
2110 if (sd->balance_interval < sd->max_interval)
2111 sd->balance_interval *= 2;
2117 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2118 * tasks if there is an imbalance.
2120 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2121 * this_rq is locked.
2123 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2124 struct sched_domain *sd)
2126 struct sched_group *group;
2127 runqueue_t *busiest = NULL;
2128 unsigned long imbalance;
2131 schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2132 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
2134 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2138 busiest = find_busiest_queue(group);
2139 if (!busiest || busiest == this_rq) {
2140 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2144 /* Attempt to move tasks */
2145 double_lock_balance(this_rq, busiest);
2147 schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2148 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2149 imbalance, sd, NEWLY_IDLE);
2151 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2153 spin_unlock(&busiest->lock);
2160 * idle_balance is called by schedule() if this_cpu is about to become
2161 * idle. Attempts to pull tasks from other CPUs.
2163 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
2165 struct sched_domain *sd;
2167 for_each_domain(this_cpu, sd) {
2168 if (sd->flags & SD_BALANCE_NEWIDLE) {
2169 if (load_balance_newidle(this_cpu, this_rq, sd)) {
2170 /* We've pulled tasks over so stop searching */
2178 * active_load_balance is run by migration threads. It pushes running tasks
2179 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2180 * running on each physical CPU where possible, and avoids physical /
2181 * logical imbalances.
2183 * Called with busiest_rq locked.
2185 static void active_load_balance(runqueue_t *busiest_rq, int busiest_cpu)
2187 struct sched_domain *sd;
2188 struct sched_group *cpu_group;
2189 runqueue_t *target_rq;
2190 cpumask_t visited_cpus;
2193 schedstat_inc(busiest_rq, alb_cnt);
2195 * Search for suitable CPUs to push tasks to in successively higher
2196 * domains with SD_LOAD_BALANCE set.
2198 visited_cpus = CPU_MASK_NONE;
2199 for_each_domain(busiest_cpu, sd) {
2200 if (!(sd->flags & SD_LOAD_BALANCE))
2201 /* no more domains to search */
2204 cpu_group = sd->groups;
2206 for_each_cpu_mask(cpu, cpu_group->cpumask) {
2207 if (busiest_rq->nr_running <= 1)
2208 /* no more tasks left to move */
2210 if (cpu_isset(cpu, visited_cpus))
2212 cpu_set(cpu, visited_cpus);
2213 if (!cpu_and_siblings_are_idle(cpu) || cpu == busiest_cpu)
2216 target_rq = cpu_rq(cpu);
2218 * This condition is "impossible", if it occurs
2219 * we need to fix it. Originally reported by
2220 * Bjorn Helgaas on a 128-cpu setup.
2222 BUG_ON(busiest_rq == target_rq);
2224 /* move a task from busiest_rq to target_rq */
2225 double_lock_balance(busiest_rq, target_rq);
2226 if (move_tasks(target_rq, cpu, busiest_rq,
2227 1, sd, SCHED_IDLE)) {
2228 schedstat_inc(busiest_rq, alb_lost);
2229 schedstat_inc(target_rq, alb_gained);
2231 schedstat_inc(busiest_rq, alb_failed);
2233 spin_unlock(&target_rq->lock);
2235 cpu_group = cpu_group->next;
2236 } while (cpu_group != sd->groups);
2241 * rebalance_tick will get called every timer tick, on every CPU.
2243 * It checks each scheduling domain to see if it is due to be balanced,
2244 * and initiates a balancing operation if so.
2246 * Balancing parameters are set up in arch_init_sched_domains.
2249 /* Don't have all balancing operations going off at once */
2250 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2252 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2253 enum idle_type idle)
2255 unsigned long old_load, this_load;
2256 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2257 struct sched_domain *sd;
2259 /* Update our load */
2260 old_load = this_rq->cpu_load;
2261 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
2263 * Round up the averaging division if load is increasing. This
2264 * prevents us from getting stuck on 9 if the load is 10, for
2267 if (this_load > old_load)
2269 this_rq->cpu_load = (old_load + this_load) / 2;
2271 for_each_domain(this_cpu, sd) {
2272 unsigned long interval;
2274 if (!(sd->flags & SD_LOAD_BALANCE))
2277 interval = sd->balance_interval;
2278 if (idle != SCHED_IDLE)
2279 interval *= sd->busy_factor;
2281 /* scale ms to jiffies */
2282 interval = msecs_to_jiffies(interval);
2283 if (unlikely(!interval))
2286 if (j - sd->last_balance >= interval) {
2287 if (load_balance(this_cpu, this_rq, sd, idle)) {
2288 /* We've pulled tasks over so no longer idle */
2291 sd->last_balance += interval;
2297 * on UP we do not need to balance between CPUs:
2299 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2302 static inline void idle_balance(int cpu, runqueue_t *rq)
2307 static inline int wake_priority_sleeper(runqueue_t *rq)
2310 #ifdef CONFIG_SCHED_SMT
2311 spin_lock(&rq->lock);
2313 * If an SMT sibling task has been put to sleep for priority
2314 * reasons reschedule the idle task to see if it can now run.
2316 if (rq->nr_running) {
2317 resched_task(rq->idle);
2320 spin_unlock(&rq->lock);
2325 DEFINE_PER_CPU(struct kernel_stat, kstat);
2327 EXPORT_PER_CPU_SYMBOL(kstat);
2330 * We place interactive tasks back into the active array, if possible.
2332 * To guarantee that this does not starve expired tasks we ignore the
2333 * interactivity of a task if the first expired task had to wait more
2334 * than a 'reasonable' amount of time. This deadline timeout is
2335 * load-dependent, as the frequency of array switched decreases with
2336 * increasing number of running tasks. We also ignore the interactivity
2337 * if a better static_prio task has expired:
2339 #define EXPIRED_STARVING(rq) \
2340 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2341 (jiffies - (rq)->expired_timestamp >= \
2342 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2343 ((rq)->curr->static_prio > (rq)->best_expired_prio))
2346 * Do the virtual cpu time signal calculations.
2347 * @p: the process that the cpu time gets accounted to
2348 * @cputime: the cpu time spent in user space since the last update
2350 static inline void account_it_virt(struct task_struct * p, cputime_t cputime)
2352 cputime_t it_virt = p->it_virt_value;
2354 if (cputime_gt(it_virt, cputime_zero) &&
2355 cputime_gt(cputime, cputime_zero)) {
2356 if (cputime_ge(cputime, it_virt)) {
2357 it_virt = cputime_add(it_virt, p->it_virt_incr);
2358 send_sig(SIGVTALRM, p, 1);
2360 it_virt = cputime_sub(it_virt, cputime);
2361 p->it_virt_value = it_virt;
2366 * Do the virtual profiling signal calculations.
2367 * @p: the process that the cpu time gets accounted to
2368 * @cputime: the cpu time spent in user and kernel space since the last update
2370 static void account_it_prof(struct task_struct *p, cputime_t cputime)
2372 cputime_t it_prof = p->it_prof_value;
2374 if (cputime_gt(it_prof, cputime_zero) &&
2375 cputime_gt(cputime, cputime_zero)) {
2376 if (cputime_ge(cputime, it_prof)) {
2377 it_prof = cputime_add(it_prof, p->it_prof_incr);
2378 send_sig(SIGPROF, p, 1);
2380 it_prof = cputime_sub(it_prof, cputime);
2381 p->it_prof_value = it_prof;
2386 * Check if the process went over its cputime resource limit after
2387 * some cpu time got added to utime/stime.
2388 * @p: the process that the cpu time gets accounted to
2389 * @cputime: the cpu time spent in user and kernel space since the last update
2391 static void check_rlimit(struct task_struct *p, cputime_t cputime)
2393 cputime_t total, tmp;
2396 total = cputime_add(p->utime, p->stime);
2397 secs = cputime_to_secs(total);
2398 if (unlikely(secs >= p->signal->rlim[RLIMIT_CPU].rlim_cur)) {
2399 /* Send SIGXCPU every second. */
2400 tmp = cputime_sub(total, cputime);
2401 if (cputime_to_secs(tmp) < secs)
2402 send_sig(SIGXCPU, p, 1);
2403 /* and SIGKILL when we go over max.. */
2404 if (secs >= p->signal->rlim[RLIMIT_CPU].rlim_max)
2405 send_sig(SIGKILL, p, 1);
2410 * Account user cpu time to a process.
2411 * @p: the process that the cpu time gets accounted to
2412 * @hardirq_offset: the offset to subtract from hardirq_count()
2413 * @cputime: the cpu time spent in user space since the last update
2415 void account_user_time(struct task_struct *p, cputime_t cputime)
2417 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2418 struct vx_info *vxi = p->vx_info; /* p is _always_ current */
2420 int nice = (TASK_NICE(p) > 0);
2422 p->utime = cputime_add(p->utime, cputime);
2423 vx_account_user(vxi, cputime, nice);
2425 /* Check for signals (SIGVTALRM, SIGPROF, SIGXCPU & SIGKILL). */
2426 check_rlimit(p, cputime);
2427 account_it_virt(p, cputime);
2428 account_it_prof(p, cputime);
2430 /* Add user time to cpustat. */
2431 tmp = cputime_to_cputime64(cputime);
2433 cpustat->nice = cputime64_add(cpustat->nice, tmp);
2435 cpustat->user = cputime64_add(cpustat->user, tmp);
2439 * Account system cpu time to a process.
2440 * @p: the process that the cpu time gets accounted to
2441 * @hardirq_offset: the offset to subtract from hardirq_count()
2442 * @cputime: the cpu time spent in kernel space since the last update
2444 void account_system_time(struct task_struct *p, int hardirq_offset,
2447 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2448 struct vx_info *vxi = p->vx_info; /* p is _always_ current */
2449 runqueue_t *rq = this_rq();
2452 p->stime = cputime_add(p->stime, cputime);
2453 vx_account_system(vxi, cputime, (p == rq->idle));
2455 /* Check for signals (SIGPROF, SIGXCPU & SIGKILL). */
2456 if (likely(p->signal && p->exit_state < EXIT_ZOMBIE)) {
2457 check_rlimit(p, cputime);
2458 account_it_prof(p, cputime);
2461 /* Add system time to cpustat. */
2462 tmp = cputime_to_cputime64(cputime);
2463 if (hardirq_count() - hardirq_offset)
2464 cpustat->irq = cputime64_add(cpustat->irq, tmp);
2465 else if (softirq_count())
2466 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
2467 else if (p != rq->idle)
2468 cpustat->system = cputime64_add(cpustat->system, tmp);
2469 else if (atomic_read(&rq->nr_iowait) > 0)
2470 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2472 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2476 * Account for involuntary wait time.
2477 * @p: the process from which the cpu time has been stolen
2478 * @steal: the cpu time spent in involuntary wait
2480 void account_steal_time(struct task_struct *p, cputime_t steal)
2482 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2483 cputime64_t tmp = cputime_to_cputime64(steal);
2484 runqueue_t *rq = this_rq();
2486 if (p == rq->idle) {
2487 p->stime = cputime_add(p->stime, steal);
2488 if (atomic_read(&rq->nr_iowait) > 0)
2489 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2491 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2493 cpustat->steal = cputime64_add(cpustat->steal, tmp);
2497 * This function gets called by the timer code, with HZ frequency.
2498 * We call it with interrupts disabled.
2500 * It also gets called by the fork code, when changing the parent's
2503 void scheduler_tick(void)
2505 int cpu = smp_processor_id();
2506 runqueue_t *rq = this_rq();
2507 task_t *p = current;
2509 rq->timestamp_last_tick = sched_clock();
2511 if (p == rq->idle) {
2512 if (wake_priority_sleeper(rq))
2514 #ifdef CONFIG_VSERVER_HARDCPU_IDLE
2515 if (!--rq->idle_tokens && !list_empty(&rq->hold_queue))
2518 rebalance_tick(cpu, rq, SCHED_IDLE);
2522 /* Task might have expired already, but not scheduled off yet */
2523 if (p->array != rq->active) {
2524 set_tsk_need_resched(p);
2527 spin_lock(&rq->lock);
2529 * The task was running during this tick - update the
2530 * time slice counter. Note: we do not update a thread's
2531 * priority until it either goes to sleep or uses up its
2532 * timeslice. This makes it possible for interactive tasks
2533 * to use up their timeslices at their highest priority levels.
2537 * RR tasks need a special form of timeslice management.
2538 * FIFO tasks have no timeslices.
2540 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2541 p->time_slice = task_timeslice(p);
2542 p->first_time_slice = 0;
2543 set_tsk_need_resched(p);
2545 /* put it at the end of the queue: */
2546 requeue_task(p, rq->active);
2550 if (vx_need_resched(p)) {
2551 dequeue_task(p, rq->active);
2552 set_tsk_need_resched(p);
2553 p->prio = effective_prio(p);
2554 p->time_slice = task_timeslice(p);
2555 p->first_time_slice = 0;
2557 if (!rq->expired_timestamp)
2558 rq->expired_timestamp = jiffies;
2559 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2560 enqueue_task(p, rq->expired);
2561 if (p->static_prio < rq->best_expired_prio)
2562 rq->best_expired_prio = p->static_prio;
2564 enqueue_task(p, rq->active);
2567 * Prevent a too long timeslice allowing a task to monopolize
2568 * the CPU. We do this by splitting up the timeslice into
2571 * Note: this does not mean the task's timeslices expire or
2572 * get lost in any way, they just might be preempted by
2573 * another task of equal priority. (one with higher
2574 * priority would have preempted this task already.) We
2575 * requeue this task to the end of the list on this priority
2576 * level, which is in essence a round-robin of tasks with
2579 * This only applies to tasks in the interactive
2580 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2582 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2583 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2584 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2585 (p->array == rq->active)) {
2587 requeue_task(p, rq->active);
2588 set_tsk_need_resched(p);
2592 spin_unlock(&rq->lock);
2594 rebalance_tick(cpu, rq, NOT_IDLE);
2597 #ifdef CONFIG_SCHED_SMT
2598 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2600 struct sched_domain *sd = this_rq->sd;
2601 cpumask_t sibling_map;
2604 if (!(sd->flags & SD_SHARE_CPUPOWER))
2608 * Unlock the current runqueue because we have to lock in
2609 * CPU order to avoid deadlocks. Caller knows that we might
2610 * unlock. We keep IRQs disabled.
2612 spin_unlock(&this_rq->lock);
2614 sibling_map = sd->span;
2616 for_each_cpu_mask(i, sibling_map)
2617 spin_lock(&cpu_rq(i)->lock);
2619 * We clear this CPU from the mask. This both simplifies the
2620 * inner loop and keps this_rq locked when we exit:
2622 cpu_clear(this_cpu, sibling_map);
2624 for_each_cpu_mask(i, sibling_map) {
2625 runqueue_t *smt_rq = cpu_rq(i);
2628 * If an SMT sibling task is sleeping due to priority
2629 * reasons wake it up now.
2631 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
2632 resched_task(smt_rq->idle);
2635 for_each_cpu_mask(i, sibling_map)
2636 spin_unlock(&cpu_rq(i)->lock);
2638 * We exit with this_cpu's rq still held and IRQs
2643 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2645 struct sched_domain *sd = this_rq->sd;
2646 cpumask_t sibling_map;
2647 prio_array_t *array;
2651 if (!(sd->flags & SD_SHARE_CPUPOWER))
2655 * The same locking rules and details apply as for
2656 * wake_sleeping_dependent():
2658 spin_unlock(&this_rq->lock);
2659 sibling_map = sd->span;
2660 for_each_cpu_mask(i, sibling_map)
2661 spin_lock(&cpu_rq(i)->lock);
2662 cpu_clear(this_cpu, sibling_map);
2665 * Establish next task to be run - it might have gone away because
2666 * we released the runqueue lock above:
2668 if (!this_rq->nr_running)
2670 array = this_rq->active;
2671 if (!array->nr_active)
2672 array = this_rq->expired;
2673 BUG_ON(!array->nr_active);
2675 p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
2678 for_each_cpu_mask(i, sibling_map) {
2679 runqueue_t *smt_rq = cpu_rq(i);
2680 task_t *smt_curr = smt_rq->curr;
2683 * If a user task with lower static priority than the
2684 * running task on the SMT sibling is trying to schedule,
2685 * delay it till there is proportionately less timeslice
2686 * left of the sibling task to prevent a lower priority
2687 * task from using an unfair proportion of the
2688 * physical cpu's resources. -ck
2690 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
2691 task_timeslice(p) || rt_task(smt_curr)) &&
2692 p->mm && smt_curr->mm && !rt_task(p))
2696 * Reschedule a lower priority task on the SMT sibling,
2697 * or wake it up if it has been put to sleep for priority
2700 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
2701 task_timeslice(smt_curr) || rt_task(p)) &&
2702 smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
2703 (smt_curr == smt_rq->idle && smt_rq->nr_running))
2704 resched_task(smt_curr);
2707 for_each_cpu_mask(i, sibling_map)
2708 spin_unlock(&cpu_rq(i)->lock);
2712 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2716 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2722 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
2724 void fastcall add_preempt_count(int val)
2729 BUG_ON(((int)preempt_count() < 0));
2730 preempt_count() += val;
2732 * Spinlock count overflowing soon?
2734 BUG_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
2736 EXPORT_SYMBOL(add_preempt_count);
2738 void fastcall sub_preempt_count(int val)
2743 BUG_ON(val > preempt_count());
2745 * Is the spinlock portion underflowing?
2747 BUG_ON((val < PREEMPT_MASK) && !(preempt_count() & PREEMPT_MASK));
2748 preempt_count() -= val;
2750 EXPORT_SYMBOL(sub_preempt_count);
2755 * schedule() is the main scheduler function.
2757 asmlinkage void __sched schedule(void)
2760 task_t *prev, *next;
2762 prio_array_t *array;
2763 struct list_head *queue;
2764 unsigned long long now;
2765 unsigned long run_time;
2766 struct vx_info *vxi;
2767 #ifdef CONFIG_VSERVER_HARDCPU
2773 * Test if we are atomic. Since do_exit() needs to call into
2774 * schedule() atomically, we ignore that path for now.
2775 * Otherwise, whine if we are scheduling when we should not be.
2777 if (likely(!current->exit_state)) {
2778 if (unlikely(in_atomic())) {
2779 printk(KERN_ERR "scheduling while atomic: "
2781 current->comm, preempt_count(), current->pid);
2785 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
2790 release_kernel_lock(prev);
2791 need_resched_nonpreemptible:
2795 * The idle thread is not allowed to schedule!
2796 * Remove this check after it has been exercised a bit.
2798 if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
2799 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
2803 schedstat_inc(rq, sched_cnt);
2804 now = sched_clock();
2805 if (likely(now - prev->timestamp < NS_MAX_SLEEP_AVG))
2806 run_time = now - prev->timestamp;
2808 run_time = NS_MAX_SLEEP_AVG;
2811 * Tasks charged proportionately less run_time at high sleep_avg to
2812 * delay them losing their interactive status
2814 run_time /= (CURRENT_BONUS(prev) ? : 1);
2816 spin_lock_irq(&rq->lock);
2818 if (unlikely(prev->flags & PF_DEAD))
2819 prev->state = EXIT_DEAD;
2821 switch_count = &prev->nivcsw;
2822 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2823 switch_count = &prev->nvcsw;
2824 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2825 unlikely(signal_pending(prev))))
2826 prev->state = TASK_RUNNING;
2828 if (prev->state == TASK_UNINTERRUPTIBLE) {
2829 rq->nr_uninterruptible++;
2830 vx_uninterruptible_inc(prev);
2832 deactivate_task(prev, rq);
2836 #ifdef CONFIG_VSERVER_HARDCPU
2837 if (!list_empty(&rq->hold_queue)) {
2838 struct list_head *l, *n;
2842 list_for_each_safe(l, n, &rq->hold_queue) {
2843 next = list_entry(l, task_t, run_list);
2844 if (vxi == next->vx_info)
2847 vxi = next->vx_info;
2848 ret = vx_tokens_recalc(vxi);
2851 vx_unhold_task(vxi, next, rq);
2854 if ((ret < 0) && (maxidle < ret))
2858 rq->idle_tokens = -maxidle;
2863 cpu = smp_processor_id();
2864 if (unlikely(!rq->nr_running)) {
2866 idle_balance(cpu, rq);
2867 if (!rq->nr_running) {
2869 rq->expired_timestamp = 0;
2870 wake_sleeping_dependent(cpu, rq);
2872 * wake_sleeping_dependent() might have released
2873 * the runqueue, so break out if we got new
2876 if (!rq->nr_running)
2880 if (dependent_sleeper(cpu, rq)) {
2885 * dependent_sleeper() releases and reacquires the runqueue
2886 * lock, hence go into the idle loop if the rq went
2889 if (unlikely(!rq->nr_running))
2894 if (unlikely(!array->nr_active)) {
2896 * Switch the active and expired arrays.
2898 schedstat_inc(rq, sched_switch);
2899 rq->active = rq->expired;
2900 rq->expired = array;
2902 rq->expired_timestamp = 0;
2903 rq->best_expired_prio = MAX_PRIO;
2905 schedstat_inc(rq, sched_noswitch);
2907 idx = sched_find_first_bit(array->bitmap);
2908 queue = array->queue + idx;
2909 next = list_entry(queue->next, task_t, run_list);
2911 vxi = next->vx_info;
2912 #ifdef CONFIG_VSERVER_HARDCPU
2913 if (vx_info_flags(vxi, VXF_SCHED_PAUSE|VXF_SCHED_HARD, 0)) {
2914 int ret = vx_tokens_recalc(vxi);
2916 if (unlikely(ret <= 0)) {
2917 if (ret && (rq->idle_tokens > -ret))
2918 rq->idle_tokens = -ret;
2919 vx_hold_task(vxi, next, rq);
2922 } else /* well, looks ugly but not as ugly as the ifdef-ed version */
2924 if (vx_info_flags(vxi, VXF_SCHED_PRIO, 0))
2925 vx_tokens_recalc(vxi);
2927 if (!rt_task(next) && next->activated > 0) {
2928 unsigned long long delta = now - next->timestamp;
2930 if (next->activated == 1)
2931 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
2933 array = next->array;
2934 dequeue_task(next, array);
2935 recalc_task_prio(next, next->timestamp + delta);
2936 enqueue_task(next, array);
2938 next->activated = 0;
2940 if (next == rq->idle)
2941 schedstat_inc(rq, sched_goidle);
2943 clear_tsk_need_resched(prev);
2944 rcu_qsctr_inc(task_cpu(prev));
2946 prev->sleep_avg -= run_time;
2947 if ((long)prev->sleep_avg <= 0)
2948 prev->sleep_avg = 0;
2949 prev->timestamp = prev->last_ran = now;
2951 sched_info_switch(prev, next);
2952 if (likely(prev != next)) {
2953 next->timestamp = now;
2958 prepare_arch_switch(rq, next);
2959 prev = context_switch(rq, prev, next);
2962 finish_task_switch(prev);
2964 spin_unlock_irq(&rq->lock);
2967 if (unlikely(reacquire_kernel_lock(prev) < 0))
2968 goto need_resched_nonpreemptible;
2969 preempt_enable_no_resched();
2970 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2974 EXPORT_SYMBOL(schedule);
2976 #ifdef CONFIG_PREEMPT
2978 * this is is the entry point to schedule() from in-kernel preemption
2979 * off of preempt_enable. Kernel preemptions off return from interrupt
2980 * occur there and call schedule directly.
2982 asmlinkage void __sched preempt_schedule(void)
2984 struct thread_info *ti = current_thread_info();
2985 #ifdef CONFIG_PREEMPT_BKL
2986 struct task_struct *task = current;
2987 int saved_lock_depth;
2990 * If there is a non-zero preempt_count or interrupts are disabled,
2991 * we do not want to preempt the current task. Just return..
2993 if (unlikely(ti->preempt_count || irqs_disabled()))
2997 add_preempt_count(PREEMPT_ACTIVE);
2999 * We keep the big kernel semaphore locked, but we
3000 * clear ->lock_depth so that schedule() doesnt
3001 * auto-release the semaphore:
3003 #ifdef CONFIG_PREEMPT_BKL
3004 saved_lock_depth = task->lock_depth;
3005 task->lock_depth = -1;
3008 #ifdef CONFIG_PREEMPT_BKL
3009 task->lock_depth = saved_lock_depth;
3011 sub_preempt_count(PREEMPT_ACTIVE);
3013 /* we could miss a preemption opportunity between schedule and now */
3015 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3019 EXPORT_SYMBOL(preempt_schedule);
3022 * this is is the entry point to schedule() from kernel preemption
3023 * off of irq context.
3024 * Note, that this is called and return with irqs disabled. This will
3025 * protect us against recursive calling from irq.
3027 asmlinkage void __sched preempt_schedule_irq(void)
3029 struct thread_info *ti = current_thread_info();
3030 #ifdef CONFIG_PREEMPT_BKL
3031 struct task_struct *task = current;
3032 int saved_lock_depth;
3034 /* Catch callers which need to be fixed*/
3035 BUG_ON(ti->preempt_count || !irqs_disabled());
3038 add_preempt_count(PREEMPT_ACTIVE);
3040 * We keep the big kernel semaphore locked, but we
3041 * clear ->lock_depth so that schedule() doesnt
3042 * auto-release the semaphore:
3044 #ifdef CONFIG_PREEMPT_BKL
3045 saved_lock_depth = task->lock_depth;
3046 task->lock_depth = -1;
3050 local_irq_disable();
3051 #ifdef CONFIG_PREEMPT_BKL
3052 task->lock_depth = saved_lock_depth;
3054 sub_preempt_count(PREEMPT_ACTIVE);
3056 /* we could miss a preemption opportunity between schedule and now */
3058 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3062 #endif /* CONFIG_PREEMPT */
3064 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
3066 task_t *p = curr->task;
3067 return try_to_wake_up(p, mode, sync);
3070 EXPORT_SYMBOL(default_wake_function);
3073 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3074 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3075 * number) then we wake all the non-exclusive tasks and one exclusive task.
3077 * There are circumstances in which we can try to wake a task which has already
3078 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3079 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3081 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3082 int nr_exclusive, int sync, void *key)
3084 struct list_head *tmp, *next;
3086 list_for_each_safe(tmp, next, &q->task_list) {
3089 curr = list_entry(tmp, wait_queue_t, task_list);
3090 flags = curr->flags;
3091 if (curr->func(curr, mode, sync, key) &&
3092 (flags & WQ_FLAG_EXCLUSIVE) &&
3099 * __wake_up - wake up threads blocked on a waitqueue.
3101 * @mode: which threads
3102 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3104 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3105 int nr_exclusive, void *key)
3107 unsigned long flags;
3109 spin_lock_irqsave(&q->lock, flags);
3110 __wake_up_common(q, mode, nr_exclusive, 0, key);
3111 spin_unlock_irqrestore(&q->lock, flags);
3114 EXPORT_SYMBOL(__wake_up);
3117 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3119 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3121 __wake_up_common(q, mode, 1, 0, NULL);
3125 * __wake_up - sync- wake up threads blocked on a waitqueue.
3127 * @mode: which threads
3128 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3130 * The sync wakeup differs that the waker knows that it will schedule
3131 * away soon, so while the target thread will be woken up, it will not
3132 * be migrated to another CPU - ie. the two threads are 'synchronized'
3133 * with each other. This can prevent needless bouncing between CPUs.
3135 * On UP it can prevent extra preemption.
3137 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3139 unsigned long flags;
3145 if (unlikely(!nr_exclusive))
3148 spin_lock_irqsave(&q->lock, flags);
3149 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3150 spin_unlock_irqrestore(&q->lock, flags);
3152 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3154 void fastcall complete(struct completion *x)
3156 unsigned long flags;
3158 spin_lock_irqsave(&x->wait.lock, flags);
3160 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3162 spin_unlock_irqrestore(&x->wait.lock, flags);
3164 EXPORT_SYMBOL(complete);
3166 void fastcall complete_all(struct completion *x)
3168 unsigned long flags;
3170 spin_lock_irqsave(&x->wait.lock, flags);
3171 x->done += UINT_MAX/2;
3172 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3174 spin_unlock_irqrestore(&x->wait.lock, flags);
3176 EXPORT_SYMBOL(complete_all);
3178 void fastcall __sched wait_for_completion(struct completion *x)
3181 spin_lock_irq(&x->wait.lock);
3183 DECLARE_WAITQUEUE(wait, current);
3185 wait.flags |= WQ_FLAG_EXCLUSIVE;
3186 __add_wait_queue_tail(&x->wait, &wait);
3188 __set_current_state(TASK_UNINTERRUPTIBLE);
3189 spin_unlock_irq(&x->wait.lock);
3191 spin_lock_irq(&x->wait.lock);
3193 __remove_wait_queue(&x->wait, &wait);
3196 spin_unlock_irq(&x->wait.lock);
3198 EXPORT_SYMBOL(wait_for_completion);
3200 unsigned long fastcall __sched
3201 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3205 spin_lock_irq(&x->wait.lock);
3207 DECLARE_WAITQUEUE(wait, current);
3209 wait.flags |= WQ_FLAG_EXCLUSIVE;
3210 __add_wait_queue_tail(&x->wait, &wait);
3212 __set_current_state(TASK_UNINTERRUPTIBLE);
3213 spin_unlock_irq(&x->wait.lock);
3214 timeout = schedule_timeout(timeout);
3215 spin_lock_irq(&x->wait.lock);
3217 __remove_wait_queue(&x->wait, &wait);
3221 __remove_wait_queue(&x->wait, &wait);
3225 spin_unlock_irq(&x->wait.lock);
3228 EXPORT_SYMBOL(wait_for_completion_timeout);
3230 int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3236 spin_lock_irq(&x->wait.lock);
3238 DECLARE_WAITQUEUE(wait, current);
3240 wait.flags |= WQ_FLAG_EXCLUSIVE;
3241 __add_wait_queue_tail(&x->wait, &wait);
3243 if (signal_pending(current)) {
3245 __remove_wait_queue(&x->wait, &wait);
3248 __set_current_state(TASK_INTERRUPTIBLE);
3249 spin_unlock_irq(&x->wait.lock);
3251 spin_lock_irq(&x->wait.lock);
3253 __remove_wait_queue(&x->wait, &wait);
3257 spin_unlock_irq(&x->wait.lock);
3261 EXPORT_SYMBOL(wait_for_completion_interruptible);
3263 unsigned long fastcall __sched
3264 wait_for_completion_interruptible_timeout(struct completion *x,
3265 unsigned long timeout)
3269 spin_lock_irq(&x->wait.lock);
3271 DECLARE_WAITQUEUE(wait, current);
3273 wait.flags |= WQ_FLAG_EXCLUSIVE;
3274 __add_wait_queue_tail(&x->wait, &wait);
3276 if (signal_pending(current)) {
3277 timeout = -ERESTARTSYS;
3278 __remove_wait_queue(&x->wait, &wait);
3281 __set_current_state(TASK_INTERRUPTIBLE);
3282 spin_unlock_irq(&x->wait.lock);
3283 timeout = schedule_timeout(timeout);
3284 spin_lock_irq(&x->wait.lock);
3286 __remove_wait_queue(&x->wait, &wait);
3290 __remove_wait_queue(&x->wait, &wait);
3294 spin_unlock_irq(&x->wait.lock);
3297 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3300 #define SLEEP_ON_VAR \
3301 unsigned long flags; \
3302 wait_queue_t wait; \
3303 init_waitqueue_entry(&wait, current);
3305 #define SLEEP_ON_HEAD \
3306 spin_lock_irqsave(&q->lock,flags); \
3307 __add_wait_queue(q, &wait); \
3308 spin_unlock(&q->lock);
3310 #define SLEEP_ON_TAIL \
3311 spin_lock_irq(&q->lock); \
3312 __remove_wait_queue(q, &wait); \
3313 spin_unlock_irqrestore(&q->lock, flags);
3315 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3319 current->state = TASK_INTERRUPTIBLE;
3326 EXPORT_SYMBOL(interruptible_sleep_on);
3328 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3332 current->state = TASK_INTERRUPTIBLE;
3335 timeout = schedule_timeout(timeout);
3341 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3343 void fastcall __sched sleep_on(wait_queue_head_t *q)
3347 current->state = TASK_UNINTERRUPTIBLE;
3354 EXPORT_SYMBOL(sleep_on);
3356 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3360 current->state = TASK_UNINTERRUPTIBLE;
3363 timeout = schedule_timeout(timeout);
3369 EXPORT_SYMBOL(sleep_on_timeout);
3371 void set_user_nice(task_t *p, long nice)
3373 unsigned long flags;
3374 prio_array_t *array;
3376 int old_prio, new_prio, delta;
3378 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3381 * We have to be careful, if called from sys_setpriority(),
3382 * the task might be in the middle of scheduling on another CPU.
3384 rq = task_rq_lock(p, &flags);
3386 * The RT priorities are set via sched_setscheduler(), but we still
3387 * allow the 'normal' nice value to be set - but as expected
3388 * it wont have any effect on scheduling until the task is
3392 p->static_prio = NICE_TO_PRIO(nice);
3397 dequeue_task(p, array);
3400 new_prio = NICE_TO_PRIO(nice);
3401 delta = new_prio - old_prio;
3402 p->static_prio = NICE_TO_PRIO(nice);
3406 enqueue_task(p, array);
3408 * If the task increased its priority or is running and
3409 * lowered its priority, then reschedule its CPU:
3411 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3412 resched_task(rq->curr);
3415 task_rq_unlock(rq, &flags);
3418 EXPORT_SYMBOL(set_user_nice);
3420 #ifdef __ARCH_WANT_SYS_NICE
3423 * sys_nice - change the priority of the current process.
3424 * @increment: priority increment
3426 * sys_setpriority is a more generic, but much slower function that
3427 * does similar things.
3429 asmlinkage long sys_nice(int increment)
3435 * Setpriority might change our priority at the same moment.
3436 * We don't have to worry. Conceptually one call occurs first
3437 * and we have a single winner.
3439 if (increment < 0) {
3440 if (vx_flags(VXF_IGNEG_NICE, 0))
3442 if (!capable(CAP_SYS_NICE))
3444 if (increment < -40)
3450 nice = PRIO_TO_NICE(current->static_prio) + increment;
3456 retval = security_task_setnice(current, nice);
3460 set_user_nice(current, nice);
3467 * task_prio - return the priority value of a given task.
3468 * @p: the task in question.
3470 * This is the priority value as seen by users in /proc.
3471 * RT tasks are offset by -200. Normal tasks are centered
3472 * around 0, value goes from -16 to +15.
3474 int task_prio(const task_t *p)
3476 return p->prio - MAX_RT_PRIO;
3480 * task_nice - return the nice value of a given task.
3481 * @p: the task in question.
3483 int task_nice(const task_t *p)
3485 return TASK_NICE(p);
3489 * The only users of task_nice are binfmt_elf and binfmt_elf32.
3490 * binfmt_elf is no longer modular, but binfmt_elf32 still is.
3491 * Therefore, task_nice is needed if there is a compat_mode.
3493 #ifdef CONFIG_COMPAT
3494 EXPORT_SYMBOL_GPL(task_nice);
3498 * idle_cpu - is a given cpu idle currently?
3499 * @cpu: the processor in question.
3501 int idle_cpu(int cpu)
3503 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3506 EXPORT_SYMBOL_GPL(idle_cpu);
3509 * idle_task - return the idle task for a given cpu.
3510 * @cpu: the processor in question.
3512 task_t *idle_task(int cpu)
3514 return cpu_rq(cpu)->idle;
3518 * find_process_by_pid - find a process with a matching PID value.
3519 * @pid: the pid in question.
3521 static inline task_t *find_process_by_pid(pid_t pid)
3523 return pid ? find_task_by_pid(pid) : current;
3526 /* Actually do priority change: must hold rq lock. */
3527 static void __setscheduler(struct task_struct *p, int policy, int prio)
3531 p->rt_priority = prio;
3532 if (policy != SCHED_NORMAL)
3533 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
3535 p->prio = p->static_prio;
3539 * sched_setscheduler - change the scheduling policy and/or RT priority of
3541 * @p: the task in question.
3542 * @policy: new policy.
3543 * @param: structure containing the new RT priority.
3545 int sched_setscheduler(struct task_struct *p, int policy, struct sched_param *param)
3548 int oldprio, oldpolicy = -1;
3549 prio_array_t *array;
3550 unsigned long flags;
3554 /* double check policy once rq lock held */
3556 policy = oldpolicy = p->policy;
3557 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
3558 policy != SCHED_NORMAL)
3561 * Valid priorities for SCHED_FIFO and SCHED_RR are
3562 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
3564 if (param->sched_priority < 0 ||
3565 param->sched_priority > MAX_USER_RT_PRIO-1)
3567 if ((policy == SCHED_NORMAL) != (param->sched_priority == 0))
3570 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
3571 !capable(CAP_SYS_NICE))
3573 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3574 !capable(CAP_SYS_NICE))
3577 retval = security_task_setscheduler(p, policy, param);
3581 * To be able to change p->policy safely, the apropriate
3582 * runqueue lock must be held.
3584 rq = task_rq_lock(p, &flags);
3585 /* recheck policy now with rq lock held */
3586 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3587 policy = oldpolicy = -1;
3588 task_rq_unlock(rq, &flags);
3593 deactivate_task(p, rq);
3595 __setscheduler(p, policy, param->sched_priority);
3597 vx_activate_task(p);
3598 __activate_task(p, rq);
3600 * Reschedule if we are currently running on this runqueue and
3601 * our priority decreased, or if we are not currently running on
3602 * this runqueue and our priority is higher than the current's
3604 if (task_running(rq, p)) {
3605 if (p->prio > oldprio)
3606 resched_task(rq->curr);
3607 } else if (TASK_PREEMPTS_CURR(p, rq))
3608 resched_task(rq->curr);
3610 task_rq_unlock(rq, &flags);
3613 EXPORT_SYMBOL_GPL(sched_setscheduler);
3615 static int do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3618 struct sched_param lparam;
3619 struct task_struct *p;
3621 if (!param || pid < 0)
3623 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
3625 read_lock_irq(&tasklist_lock);
3626 p = find_process_by_pid(pid);
3628 read_unlock_irq(&tasklist_lock);
3631 retval = sched_setscheduler(p, policy, &lparam);
3632 read_unlock_irq(&tasklist_lock);
3637 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3638 * @pid: the pid in question.
3639 * @policy: new policy.
3640 * @param: structure containing the new RT priority.
3642 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3643 struct sched_param __user *param)
3645 return do_sched_setscheduler(pid, policy, param);
3649 * sys_sched_setparam - set/change the RT priority of a thread
3650 * @pid: the pid in question.
3651 * @param: structure containing the new RT priority.
3653 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3655 return do_sched_setscheduler(pid, -1, param);
3659 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3660 * @pid: the pid in question.
3662 asmlinkage long sys_sched_getscheduler(pid_t pid)
3664 int retval = -EINVAL;
3671 read_lock(&tasklist_lock);
3672 p = find_process_by_pid(pid);
3674 retval = security_task_getscheduler(p);
3678 read_unlock(&tasklist_lock);
3685 * sys_sched_getscheduler - get the RT priority of a thread
3686 * @pid: the pid in question.
3687 * @param: structure containing the RT priority.
3689 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3691 struct sched_param lp;
3692 int retval = -EINVAL;
3695 if (!param || pid < 0)
3698 read_lock(&tasklist_lock);
3699 p = find_process_by_pid(pid);
3704 retval = security_task_getscheduler(p);
3708 lp.sched_priority = p->rt_priority;
3709 read_unlock(&tasklist_lock);
3712 * This one might sleep, we cannot do it with a spinlock held ...
3714 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3720 read_unlock(&tasklist_lock);
3724 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
3730 read_lock(&tasklist_lock);
3732 p = find_process_by_pid(pid);
3734 read_unlock(&tasklist_lock);
3735 unlock_cpu_hotplug();
3740 * It is not safe to call set_cpus_allowed with the
3741 * tasklist_lock held. We will bump the task_struct's
3742 * usage count and then drop tasklist_lock.
3745 read_unlock(&tasklist_lock);
3748 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3749 !capable(CAP_SYS_NICE))
3752 retval = set_cpus_allowed(p, new_mask);
3756 unlock_cpu_hotplug();
3760 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
3761 cpumask_t *new_mask)
3763 if (len < sizeof(cpumask_t)) {
3764 memset(new_mask, 0, sizeof(cpumask_t));
3765 } else if (len > sizeof(cpumask_t)) {
3766 len = sizeof(cpumask_t);
3768 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
3772 * sys_sched_setaffinity - set the cpu affinity of a process
3773 * @pid: pid of the process
3774 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3775 * @user_mask_ptr: user-space pointer to the new cpu mask
3777 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
3778 unsigned long __user *user_mask_ptr)
3783 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
3787 return sched_setaffinity(pid, new_mask);
3791 * Represents all cpu's present in the system
3792 * In systems capable of hotplug, this map could dynamically grow
3793 * as new cpu's are detected in the system via any platform specific
3794 * method, such as ACPI for e.g.
3797 cpumask_t cpu_present_map;
3798 EXPORT_SYMBOL(cpu_present_map);
3801 cpumask_t cpu_online_map = CPU_MASK_ALL;
3802 cpumask_t cpu_possible_map = CPU_MASK_ALL;
3805 long sched_getaffinity(pid_t pid, cpumask_t *mask)
3811 read_lock(&tasklist_lock);
3814 p = find_process_by_pid(pid);
3819 cpus_and(*mask, p->cpus_allowed, cpu_possible_map);
3822 read_unlock(&tasklist_lock);
3823 unlock_cpu_hotplug();
3831 * sys_sched_getaffinity - get the cpu affinity of a process
3832 * @pid: pid of the process
3833 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3834 * @user_mask_ptr: user-space pointer to hold the current cpu mask
3836 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
3837 unsigned long __user *user_mask_ptr)
3842 if (len < sizeof(cpumask_t))
3845 ret = sched_getaffinity(pid, &mask);
3849 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
3852 return sizeof(cpumask_t);
3856 * sys_sched_yield - yield the current processor to other threads.
3858 * this function yields the current CPU by moving the calling thread
3859 * to the expired array. If there are no other threads running on this
3860 * CPU then this function will return.
3862 asmlinkage long sys_sched_yield(void)
3864 runqueue_t *rq = this_rq_lock();
3865 prio_array_t *array = current->array;
3866 prio_array_t *target = rq->expired;
3868 schedstat_inc(rq, yld_cnt);
3870 * We implement yielding by moving the task into the expired
3873 * (special rule: RT tasks will just roundrobin in the active
3876 if (rt_task(current))
3877 target = rq->active;
3879 if (current->array->nr_active == 1) {
3880 schedstat_inc(rq, yld_act_empty);
3881 if (!rq->expired->nr_active)
3882 schedstat_inc(rq, yld_both_empty);
3883 } else if (!rq->expired->nr_active)
3884 schedstat_inc(rq, yld_exp_empty);
3886 if (array != target) {
3887 dequeue_task(current, array);
3888 enqueue_task(current, target);
3891 * requeue_task is cheaper so perform that if possible.
3893 requeue_task(current, array);
3896 * Since we are going to call schedule() anyway, there's
3897 * no need to preempt or enable interrupts:
3899 __release(rq->lock);
3900 _raw_spin_unlock(&rq->lock);
3901 preempt_enable_no_resched();
3908 static inline void __cond_resched(void)
3911 add_preempt_count(PREEMPT_ACTIVE);
3913 sub_preempt_count(PREEMPT_ACTIVE);
3914 } while (need_resched());
3917 int __sched cond_resched(void)
3919 if (need_resched()) {
3926 EXPORT_SYMBOL(cond_resched);
3929 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
3930 * call schedule, and on return reacquire the lock.
3932 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
3933 * operations here to prevent schedule() from being called twice (once via
3934 * spin_unlock(), once by hand).
3936 int cond_resched_lock(spinlock_t * lock)
3938 #if defined(CONFIG_SMP) && defined(CONFIG_PREEMPT)
3939 if (lock->break_lock) {
3940 lock->break_lock = 0;
3946 if (need_resched()) {
3947 _raw_spin_unlock(lock);
3948 preempt_enable_no_resched();
3956 EXPORT_SYMBOL(cond_resched_lock);
3958 int __sched cond_resched_softirq(void)
3960 BUG_ON(!in_softirq());
3962 if (need_resched()) {
3963 __local_bh_enable();
3971 EXPORT_SYMBOL(cond_resched_softirq);
3975 * yield - yield the current processor to other threads.
3977 * this is a shortcut for kernel-space yielding - it marks the
3978 * thread runnable and calls sys_sched_yield().
3980 void __sched yield(void)
3982 set_current_state(TASK_RUNNING);
3986 EXPORT_SYMBOL(yield);
3989 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
3990 * that process accounting knows that this is a task in IO wait state.
3992 * But don't do that if it is a deliberate, throttling IO wait (this task
3993 * has set its backing_dev_info: the queue against which it should throttle)
3995 void __sched io_schedule(void)
3997 struct runqueue *rq = &per_cpu(runqueues, _smp_processor_id());
3999 atomic_inc(&rq->nr_iowait);
4001 atomic_dec(&rq->nr_iowait);
4004 EXPORT_SYMBOL(io_schedule);
4006 long __sched io_schedule_timeout(long timeout)
4008 struct runqueue *rq = &per_cpu(runqueues, _smp_processor_id());
4011 atomic_inc(&rq->nr_iowait);
4012 ret = schedule_timeout(timeout);
4013 atomic_dec(&rq->nr_iowait);
4018 * sys_sched_get_priority_max - return maximum RT priority.
4019 * @policy: scheduling class.
4021 * this syscall returns the maximum rt_priority that can be used
4022 * by a given scheduling class.
4024 asmlinkage long sys_sched_get_priority_max(int policy)
4031 ret = MAX_USER_RT_PRIO-1;
4041 * sys_sched_get_priority_min - return minimum RT priority.
4042 * @policy: scheduling class.
4044 * this syscall returns the minimum rt_priority that can be used
4045 * by a given scheduling class.
4047 asmlinkage long sys_sched_get_priority_min(int policy)
4063 * sys_sched_rr_get_interval - return the default timeslice of a process.
4064 * @pid: pid of the process.
4065 * @interval: userspace pointer to the timeslice value.
4067 * this syscall writes the default timeslice value of a given process
4068 * into the user-space timespec buffer. A value of '0' means infinity.
4071 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4073 int retval = -EINVAL;
4081 read_lock(&tasklist_lock);
4082 p = find_process_by_pid(pid);
4086 retval = security_task_getscheduler(p);
4090 jiffies_to_timespec(p->policy & SCHED_FIFO ?
4091 0 : task_timeslice(p), &t);
4092 read_unlock(&tasklist_lock);
4093 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4097 read_unlock(&tasklist_lock);
4101 static inline struct task_struct *eldest_child(struct task_struct *p)
4103 if (list_empty(&p->children)) return NULL;
4104 return list_entry(p->children.next,struct task_struct,sibling);
4107 static inline struct task_struct *older_sibling(struct task_struct *p)
4109 if (p->sibling.prev==&p->parent->children) return NULL;
4110 return list_entry(p->sibling.prev,struct task_struct,sibling);
4113 static inline struct task_struct *younger_sibling(struct task_struct *p)
4115 if (p->sibling.next==&p->parent->children) return NULL;
4116 return list_entry(p->sibling.next,struct task_struct,sibling);
4119 static void show_task(task_t * p)
4123 unsigned long free = 0;
4124 static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
4126 printk("%-13.13s ", p->comm);
4127 state = p->state ? __ffs(p->state) + 1 : 0;
4128 if (state < ARRAY_SIZE(stat_nam))
4129 printk(stat_nam[state]);
4132 #if (BITS_PER_LONG == 32)
4133 if (state == TASK_RUNNING)
4134 printk(" running ");
4136 printk(" %08lX ", thread_saved_pc(p));
4138 if (state == TASK_RUNNING)
4139 printk(" running task ");
4141 printk(" %016lx ", thread_saved_pc(p));
4143 #ifdef CONFIG_DEBUG_STACK_USAGE
4145 unsigned long * n = (unsigned long *) (p->thread_info+1);
4148 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
4151 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
4152 if ((relative = eldest_child(p)))
4153 printk("%5d ", relative->pid);
4156 if ((relative = younger_sibling(p)))
4157 printk("%7d", relative->pid);
4160 if ((relative = older_sibling(p)))
4161 printk(" %5d", relative->pid);
4165 printk(" (L-TLB)\n");
4167 printk(" (NOTLB)\n");
4169 if (state != TASK_RUNNING)
4170 show_stack(p, NULL);
4173 void show_state(void)
4177 #if (BITS_PER_LONG == 32)
4180 printk(" task PC pid father child younger older\n");
4184 printk(" task PC pid father child younger older\n");
4186 read_lock(&tasklist_lock);
4187 do_each_thread(g, p) {
4189 * reset the NMI-timeout, listing all files on a slow
4190 * console might take alot of time:
4192 touch_nmi_watchdog();
4194 } while_each_thread(g, p);
4196 read_unlock(&tasklist_lock);
4199 void __devinit init_idle(task_t *idle, int cpu)
4201 runqueue_t *rq = cpu_rq(cpu);
4202 unsigned long flags;
4204 idle->sleep_avg = 0;
4206 idle->prio = MAX_PRIO;
4207 idle->state = TASK_RUNNING;
4208 set_task_cpu(idle, cpu);
4210 spin_lock_irqsave(&rq->lock, flags);
4211 rq->curr = rq->idle = idle;
4212 set_tsk_need_resched(idle);
4213 spin_unlock_irqrestore(&rq->lock, flags);
4215 /* Set the preempt count _outside_ the spinlocks! */
4216 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4217 idle->thread_info->preempt_count = (idle->lock_depth >= 0);
4219 idle->thread_info->preempt_count = 0;
4224 * In a system that switches off the HZ timer nohz_cpu_mask
4225 * indicates which cpus entered this state. This is used
4226 * in the rcu update to wait only for active cpus. For system
4227 * which do not switch off the HZ timer nohz_cpu_mask should
4228 * always be CPU_MASK_NONE.
4230 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4234 * This is how migration works:
4236 * 1) we queue a migration_req_t structure in the source CPU's
4237 * runqueue and wake up that CPU's migration thread.
4238 * 2) we down() the locked semaphore => thread blocks.
4239 * 3) migration thread wakes up (implicitly it forces the migrated
4240 * thread off the CPU)
4241 * 4) it gets the migration request and checks whether the migrated
4242 * task is still in the wrong runqueue.
4243 * 5) if it's in the wrong runqueue then the migration thread removes
4244 * it and puts it into the right queue.
4245 * 6) migration thread up()s the semaphore.
4246 * 7) we wake up and the migration is done.
4250 * Change a given task's CPU affinity. Migrate the thread to a
4251 * proper CPU and schedule it away if the CPU it's executing on
4252 * is removed from the allowed bitmask.
4254 * NOTE: the caller must have a valid reference to the task, the
4255 * task must not exit() & deallocate itself prematurely. The
4256 * call is not atomic; no spinlocks may be held.
4258 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
4260 unsigned long flags;
4262 migration_req_t req;
4265 rq = task_rq_lock(p, &flags);
4266 if (!cpus_intersects(new_mask, cpu_online_map)) {
4271 p->cpus_allowed = new_mask;
4272 /* Can the task run on the task's current CPU? If so, we're done */
4273 if (cpu_isset(task_cpu(p), new_mask))
4276 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4277 /* Need help from migration thread: drop lock and wait. */
4278 task_rq_unlock(rq, &flags);
4279 wake_up_process(rq->migration_thread);
4280 wait_for_completion(&req.done);
4281 tlb_migrate_finish(p->mm);
4285 task_rq_unlock(rq, &flags);
4289 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4292 * Move (not current) task off this cpu, onto dest cpu. We're doing
4293 * this because either it can't run here any more (set_cpus_allowed()
4294 * away from this CPU, or CPU going down), or because we're
4295 * attempting to rebalance this task on exec (sched_exec).
4297 * So we race with normal scheduler movements, but that's OK, as long
4298 * as the task is no longer on this CPU.
4300 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4302 runqueue_t *rq_dest, *rq_src;
4304 if (unlikely(cpu_is_offline(dest_cpu)))
4307 rq_src = cpu_rq(src_cpu);
4308 rq_dest = cpu_rq(dest_cpu);
4310 double_rq_lock(rq_src, rq_dest);
4311 /* Already moved. */
4312 if (task_cpu(p) != src_cpu)
4314 /* Affinity changed (again). */
4315 if (!cpu_isset(dest_cpu, p->cpus_allowed))
4318 set_task_cpu(p, dest_cpu);
4321 * Sync timestamp with rq_dest's before activating.
4322 * The same thing could be achieved by doing this step
4323 * afterwards, and pretending it was a local activate.
4324 * This way is cleaner and logically correct.
4326 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4327 + rq_dest->timestamp_last_tick;
4328 deactivate_task(p, rq_src);
4329 activate_task(p, rq_dest, 0);
4330 if (TASK_PREEMPTS_CURR(p, rq_dest))
4331 resched_task(rq_dest->curr);
4335 double_rq_unlock(rq_src, rq_dest);
4339 * migration_thread - this is a highprio system thread that performs
4340 * thread migration by bumping thread off CPU then 'pushing' onto
4343 static int migration_thread(void * data)
4346 int cpu = (long)data;
4349 BUG_ON(rq->migration_thread != current);
4351 set_current_state(TASK_INTERRUPTIBLE);
4352 while (!kthread_should_stop()) {
4353 struct list_head *head;
4354 migration_req_t *req;
4356 if (current->flags & PF_FREEZE)
4357 refrigerator(PF_FREEZE);
4359 spin_lock_irq(&rq->lock);
4361 if (cpu_is_offline(cpu)) {
4362 spin_unlock_irq(&rq->lock);
4366 if (rq->active_balance) {
4367 active_load_balance(rq, cpu);
4368 rq->active_balance = 0;
4371 head = &rq->migration_queue;
4373 if (list_empty(head)) {
4374 spin_unlock_irq(&rq->lock);
4376 set_current_state(TASK_INTERRUPTIBLE);
4379 req = list_entry(head->next, migration_req_t, list);
4380 list_del_init(head->next);
4382 if (req->type == REQ_MOVE_TASK) {
4383 spin_unlock(&rq->lock);
4384 __migrate_task(req->task, cpu, req->dest_cpu);
4386 } else if (req->type == REQ_SET_DOMAIN) {
4388 spin_unlock_irq(&rq->lock);
4390 spin_unlock_irq(&rq->lock);
4394 complete(&req->done);
4396 __set_current_state(TASK_RUNNING);
4400 /* Wait for kthread_stop */
4401 set_current_state(TASK_INTERRUPTIBLE);
4402 while (!kthread_should_stop()) {
4404 set_current_state(TASK_INTERRUPTIBLE);
4406 __set_current_state(TASK_RUNNING);
4410 #ifdef CONFIG_HOTPLUG_CPU
4411 /* Figure out where task on dead CPU should go, use force if neccessary. */
4412 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
4418 mask = node_to_cpumask(cpu_to_node(dead_cpu));
4419 cpus_and(mask, mask, tsk->cpus_allowed);
4420 dest_cpu = any_online_cpu(mask);
4422 /* On any allowed CPU? */
4423 if (dest_cpu == NR_CPUS)
4424 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4426 /* No more Mr. Nice Guy. */
4427 if (dest_cpu == NR_CPUS) {
4428 cpus_setall(tsk->cpus_allowed);
4429 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4432 * Don't tell them about moving exiting tasks or
4433 * kernel threads (both mm NULL), since they never
4436 if (tsk->mm && printk_ratelimit())
4437 printk(KERN_INFO "process %d (%s) no "
4438 "longer affine to cpu%d\n",
4439 tsk->pid, tsk->comm, dead_cpu);
4441 __migrate_task(tsk, dead_cpu, dest_cpu);
4445 * While a dead CPU has no uninterruptible tasks queued at this point,
4446 * it might still have a nonzero ->nr_uninterruptible counter, because
4447 * for performance reasons the counter is not stricly tracking tasks to
4448 * their home CPUs. So we just add the counter to another CPU's counter,
4449 * to keep the global sum constant after CPU-down:
4451 static void migrate_nr_uninterruptible(runqueue_t *rq_src)
4453 runqueue_t *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
4454 unsigned long flags;
4456 local_irq_save(flags);
4457 double_rq_lock(rq_src, rq_dest);
4458 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
4459 rq_src->nr_uninterruptible = 0;
4460 double_rq_unlock(rq_src, rq_dest);
4461 local_irq_restore(flags);
4464 /* Run through task list and migrate tasks from the dead cpu. */
4465 static void migrate_live_tasks(int src_cpu)
4467 struct task_struct *tsk, *t;
4469 write_lock_irq(&tasklist_lock);
4471 do_each_thread(t, tsk) {
4475 if (task_cpu(tsk) == src_cpu)
4476 move_task_off_dead_cpu(src_cpu, tsk);
4477 } while_each_thread(t, tsk);
4479 write_unlock_irq(&tasklist_lock);
4482 /* Schedules idle task to be the next runnable task on current CPU.
4483 * It does so by boosting its priority to highest possible and adding it to
4484 * the _front_ of runqueue. Used by CPU offline code.
4486 void sched_idle_next(void)
4488 int cpu = smp_processor_id();
4489 runqueue_t *rq = this_rq();
4490 struct task_struct *p = rq->idle;
4491 unsigned long flags;
4493 /* cpu has to be offline */
4494 BUG_ON(cpu_online(cpu));
4496 /* Strictly not necessary since rest of the CPUs are stopped by now
4497 * and interrupts disabled on current cpu.
4499 spin_lock_irqsave(&rq->lock, flags);
4501 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4502 /* Add idle task to _front_ of it's priority queue */
4503 __activate_idle_task(p, rq);
4505 spin_unlock_irqrestore(&rq->lock, flags);
4508 /* Ensures that the idle task is using init_mm right before its cpu goes
4511 void idle_task_exit(void)
4513 struct mm_struct *mm = current->active_mm;
4515 BUG_ON(cpu_online(smp_processor_id()));
4518 switch_mm(mm, &init_mm, current);
4522 static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
4524 struct runqueue *rq = cpu_rq(dead_cpu);
4526 /* Must be exiting, otherwise would be on tasklist. */
4527 BUG_ON(tsk->exit_state != EXIT_ZOMBIE && tsk->exit_state != EXIT_DEAD);
4529 /* Cannot have done final schedule yet: would have vanished. */
4530 BUG_ON(tsk->flags & PF_DEAD);
4532 get_task_struct(tsk);
4535 * Drop lock around migration; if someone else moves it,
4536 * that's OK. No task can be added to this CPU, so iteration is
4539 spin_unlock_irq(&rq->lock);
4540 move_task_off_dead_cpu(dead_cpu, tsk);
4541 spin_lock_irq(&rq->lock);
4543 put_task_struct(tsk);
4546 /* release_task() removes task from tasklist, so we won't find dead tasks. */
4547 static void migrate_dead_tasks(unsigned int dead_cpu)
4550 struct runqueue *rq = cpu_rq(dead_cpu);
4552 for (arr = 0; arr < 2; arr++) {
4553 for (i = 0; i < MAX_PRIO; i++) {
4554 struct list_head *list = &rq->arrays[arr].queue[i];
4555 while (!list_empty(list))
4556 migrate_dead(dead_cpu,
4557 list_entry(list->next, task_t,
4562 #endif /* CONFIG_HOTPLUG_CPU */
4565 * migration_call - callback that gets triggered when a CPU is added.
4566 * Here we can start up the necessary migration thread for the new CPU.
4568 static int migration_call(struct notifier_block *nfb, unsigned long action,
4571 int cpu = (long)hcpu;
4572 struct task_struct *p;
4573 struct runqueue *rq;
4574 unsigned long flags;
4577 case CPU_UP_PREPARE:
4578 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4581 p->flags |= PF_NOFREEZE;
4582 kthread_bind(p, cpu);
4583 /* Must be high prio: stop_machine expects to yield to it. */
4584 rq = task_rq_lock(p, &flags);
4585 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4586 task_rq_unlock(rq, &flags);
4587 cpu_rq(cpu)->migration_thread = p;
4590 /* Strictly unneccessary, as first user will wake it. */
4591 wake_up_process(cpu_rq(cpu)->migration_thread);
4593 #ifdef CONFIG_HOTPLUG_CPU
4594 case CPU_UP_CANCELED:
4595 /* Unbind it from offline cpu so it can run. Fall thru. */
4596 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
4597 kthread_stop(cpu_rq(cpu)->migration_thread);
4598 cpu_rq(cpu)->migration_thread = NULL;
4601 migrate_live_tasks(cpu);
4603 kthread_stop(rq->migration_thread);
4604 rq->migration_thread = NULL;
4605 /* Idle task back to normal (off runqueue, low prio) */
4606 rq = task_rq_lock(rq->idle, &flags);
4607 deactivate_task(rq->idle, rq);
4608 rq->idle->static_prio = MAX_PRIO;
4609 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4610 migrate_dead_tasks(cpu);
4611 task_rq_unlock(rq, &flags);
4612 migrate_nr_uninterruptible(rq);
4613 BUG_ON(rq->nr_running != 0);
4615 /* No need to migrate the tasks: it was best-effort if
4616 * they didn't do lock_cpu_hotplug(). Just wake up
4617 * the requestors. */
4618 spin_lock_irq(&rq->lock);
4619 while (!list_empty(&rq->migration_queue)) {
4620 migration_req_t *req;
4621 req = list_entry(rq->migration_queue.next,
4622 migration_req_t, list);
4623 BUG_ON(req->type != REQ_MOVE_TASK);
4624 list_del_init(&req->list);
4625 complete(&req->done);
4627 spin_unlock_irq(&rq->lock);
4634 /* Register at highest priority so that task migration (migrate_all_tasks)
4635 * happens before everything else.
4637 static struct notifier_block __devinitdata migration_notifier = {
4638 .notifier_call = migration_call,
4642 int __init migration_init(void)
4644 void *cpu = (void *)(long)smp_processor_id();
4645 /* Start one for boot CPU. */
4646 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4647 migration_call(&migration_notifier, CPU_ONLINE, cpu);
4648 register_cpu_notifier(&migration_notifier);
4654 #define SCHED_DOMAIN_DEBUG
4655 #ifdef SCHED_DOMAIN_DEBUG
4656 static void sched_domain_debug(struct sched_domain *sd, int cpu)
4660 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
4665 struct sched_group *group = sd->groups;
4666 cpumask_t groupmask;
4668 cpumask_scnprintf(str, NR_CPUS, sd->span);
4669 cpus_clear(groupmask);
4672 for (i = 0; i < level + 1; i++)
4674 printk("domain %d: ", level);
4676 if (!(sd->flags & SD_LOAD_BALANCE)) {
4677 printk("does not load-balance\n");
4679 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
4683 printk("span %s\n", str);
4685 if (!cpu_isset(cpu, sd->span))
4686 printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
4687 if (!cpu_isset(cpu, group->cpumask))
4688 printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
4691 for (i = 0; i < level + 2; i++)
4697 printk(KERN_ERR "ERROR: group is NULL\n");
4701 if (!group->cpu_power) {
4703 printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
4706 if (!cpus_weight(group->cpumask)) {
4708 printk(KERN_ERR "ERROR: empty group\n");
4711 if (cpus_intersects(groupmask, group->cpumask)) {
4713 printk(KERN_ERR "ERROR: repeated CPUs\n");
4716 cpus_or(groupmask, groupmask, group->cpumask);
4718 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
4721 group = group->next;
4722 } while (group != sd->groups);
4725 if (!cpus_equal(sd->span, groupmask))
4726 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
4732 if (!cpus_subset(groupmask, sd->span))
4733 printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
4739 #define sched_domain_debug(sd, cpu) {}
4743 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
4744 * hold the hotplug lock.
4746 void __devinit cpu_attach_domain(struct sched_domain *sd, int cpu)
4748 migration_req_t req;
4749 unsigned long flags;
4750 runqueue_t *rq = cpu_rq(cpu);
4753 sched_domain_debug(sd, cpu);
4755 spin_lock_irqsave(&rq->lock, flags);
4757 if (cpu == smp_processor_id() || !cpu_online(cpu)) {
4760 init_completion(&req.done);
4761 req.type = REQ_SET_DOMAIN;
4763 list_add(&req.list, &rq->migration_queue);
4767 spin_unlock_irqrestore(&rq->lock, flags);
4770 wake_up_process(rq->migration_thread);
4771 wait_for_completion(&req.done);
4775 /* cpus with isolated domains */
4776 cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
4778 /* Setup the mask of cpus configured for isolated domains */
4779 static int __init isolated_cpu_setup(char *str)
4781 int ints[NR_CPUS], i;
4783 str = get_options(str, ARRAY_SIZE(ints), ints);
4784 cpus_clear(cpu_isolated_map);
4785 for (i = 1; i <= ints[0]; i++)
4786 if (ints[i] < NR_CPUS)
4787 cpu_set(ints[i], cpu_isolated_map);
4791 __setup ("isolcpus=", isolated_cpu_setup);
4794 * init_sched_build_groups takes an array of groups, the cpumask we wish
4795 * to span, and a pointer to a function which identifies what group a CPU
4796 * belongs to. The return value of group_fn must be a valid index into the
4797 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
4798 * keep track of groups covered with a cpumask_t).
4800 * init_sched_build_groups will build a circular linked list of the groups
4801 * covered by the given span, and will set each group's ->cpumask correctly,
4802 * and ->cpu_power to 0.
4804 void __devinit init_sched_build_groups(struct sched_group groups[],
4805 cpumask_t span, int (*group_fn)(int cpu))
4807 struct sched_group *first = NULL, *last = NULL;
4808 cpumask_t covered = CPU_MASK_NONE;
4811 for_each_cpu_mask(i, span) {
4812 int group = group_fn(i);
4813 struct sched_group *sg = &groups[group];
4816 if (cpu_isset(i, covered))
4819 sg->cpumask = CPU_MASK_NONE;
4822 for_each_cpu_mask(j, span) {
4823 if (group_fn(j) != group)
4826 cpu_set(j, covered);
4827 cpu_set(j, sg->cpumask);
4839 #ifdef ARCH_HAS_SCHED_DOMAIN
4840 extern void __devinit arch_init_sched_domains(void);
4841 extern void __devinit arch_destroy_sched_domains(void);
4843 #ifdef CONFIG_SCHED_SMT
4844 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
4845 static struct sched_group sched_group_cpus[NR_CPUS];
4846 static int __devinit cpu_to_cpu_group(int cpu)
4852 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
4853 static struct sched_group sched_group_phys[NR_CPUS];
4854 static int __devinit cpu_to_phys_group(int cpu)
4856 #ifdef CONFIG_SCHED_SMT
4857 return first_cpu(cpu_sibling_map[cpu]);
4865 static DEFINE_PER_CPU(struct sched_domain, node_domains);
4866 static struct sched_group sched_group_nodes[MAX_NUMNODES];
4867 static int __devinit cpu_to_node_group(int cpu)
4869 return cpu_to_node(cpu);
4873 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
4875 * The domains setup code relies on siblings not spanning
4876 * multiple nodes. Make sure the architecture has a proper
4879 static void check_sibling_maps(void)
4883 for_each_online_cpu(i) {
4884 for_each_cpu_mask(j, cpu_sibling_map[i]) {
4885 if (cpu_to_node(i) != cpu_to_node(j)) {
4886 printk(KERN_INFO "warning: CPU %d siblings map "
4887 "to different node - isolating "
4889 cpu_sibling_map[i] = cpumask_of_cpu(i);
4898 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
4900 static void __devinit arch_init_sched_domains(void)
4903 cpumask_t cpu_default_map;
4905 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
4906 check_sibling_maps();
4909 * Setup mask for cpus without special case scheduling requirements.
4910 * For now this just excludes isolated cpus, but could be used to
4911 * exclude other special cases in the future.
4913 cpus_complement(cpu_default_map, cpu_isolated_map);
4914 cpus_and(cpu_default_map, cpu_default_map, cpu_online_map);
4917 * Set up domains. Isolated domains just stay on the dummy domain.
4919 for_each_cpu_mask(i, cpu_default_map) {
4921 struct sched_domain *sd = NULL, *p;
4922 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
4924 cpus_and(nodemask, nodemask, cpu_default_map);
4927 sd = &per_cpu(node_domains, i);
4928 group = cpu_to_node_group(i);
4930 sd->span = cpu_default_map;
4931 sd->groups = &sched_group_nodes[group];
4935 sd = &per_cpu(phys_domains, i);
4936 group = cpu_to_phys_group(i);
4938 sd->span = nodemask;
4940 sd->groups = &sched_group_phys[group];
4942 #ifdef CONFIG_SCHED_SMT
4944 sd = &per_cpu(cpu_domains, i);
4945 group = cpu_to_cpu_group(i);
4946 *sd = SD_SIBLING_INIT;
4947 sd->span = cpu_sibling_map[i];
4948 cpus_and(sd->span, sd->span, cpu_default_map);
4950 sd->groups = &sched_group_cpus[group];
4954 #ifdef CONFIG_SCHED_SMT
4955 /* Set up CPU (sibling) groups */
4956 for_each_online_cpu(i) {
4957 cpumask_t this_sibling_map = cpu_sibling_map[i];
4958 cpus_and(this_sibling_map, this_sibling_map, cpu_default_map);
4959 if (i != first_cpu(this_sibling_map))
4962 init_sched_build_groups(sched_group_cpus, this_sibling_map,
4967 /* Set up physical groups */
4968 for (i = 0; i < MAX_NUMNODES; i++) {
4969 cpumask_t nodemask = node_to_cpumask(i);
4971 cpus_and(nodemask, nodemask, cpu_default_map);
4972 if (cpus_empty(nodemask))
4975 init_sched_build_groups(sched_group_phys, nodemask,
4976 &cpu_to_phys_group);
4980 /* Set up node groups */
4981 init_sched_build_groups(sched_group_nodes, cpu_default_map,
4982 &cpu_to_node_group);
4985 /* Calculate CPU power for physical packages and nodes */
4986 for_each_cpu_mask(i, cpu_default_map) {
4988 struct sched_domain *sd;
4989 #ifdef CONFIG_SCHED_SMT
4990 sd = &per_cpu(cpu_domains, i);
4991 power = SCHED_LOAD_SCALE;
4992 sd->groups->cpu_power = power;
4995 sd = &per_cpu(phys_domains, i);
4996 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
4997 (cpus_weight(sd->groups->cpumask)-1) / 10;
4998 sd->groups->cpu_power = power;
5001 if (i == first_cpu(sd->groups->cpumask)) {
5002 /* Only add "power" once for each physical package. */
5003 sd = &per_cpu(node_domains, i);
5004 sd->groups->cpu_power += power;
5009 /* Attach the domains */
5010 for_each_online_cpu(i) {
5011 struct sched_domain *sd;
5012 #ifdef CONFIG_SCHED_SMT
5013 sd = &per_cpu(cpu_domains, i);
5015 sd = &per_cpu(phys_domains, i);
5017 cpu_attach_domain(sd, i);
5021 #ifdef CONFIG_HOTPLUG_CPU
5022 static void __devinit arch_destroy_sched_domains(void)
5024 /* Do nothing: everything is statically allocated. */
5028 #endif /* ARCH_HAS_SCHED_DOMAIN */
5031 * Initial dummy domain for early boot and for hotplug cpu. Being static,
5032 * it is initialized to zero, so all balancing flags are cleared which is
5035 static struct sched_domain sched_domain_dummy;
5037 #ifdef CONFIG_HOTPLUG_CPU
5039 * Force a reinitialization of the sched domains hierarchy. The domains
5040 * and groups cannot be updated in place without racing with the balancing
5041 * code, so we temporarily attach all running cpus to a "dummy" domain
5042 * which will prevent rebalancing while the sched domains are recalculated.
5044 static int update_sched_domains(struct notifier_block *nfb,
5045 unsigned long action, void *hcpu)
5050 case CPU_UP_PREPARE:
5051 case CPU_DOWN_PREPARE:
5052 for_each_online_cpu(i)
5053 cpu_attach_domain(&sched_domain_dummy, i);
5054 arch_destroy_sched_domains();
5057 case CPU_UP_CANCELED:
5058 case CPU_DOWN_FAILED:
5062 * Fall through and re-initialise the domains.
5069 /* The hotplug lock is already held by cpu_up/cpu_down */
5070 arch_init_sched_domains();
5076 void __init sched_init_smp(void)
5079 arch_init_sched_domains();
5080 unlock_cpu_hotplug();
5081 /* XXX: Theoretical race here - CPU may be hotplugged now */
5082 hotcpu_notifier(update_sched_domains, 0);
5085 void __init sched_init_smp(void)
5088 #endif /* CONFIG_SMP */
5090 int in_sched_functions(unsigned long addr)
5092 /* Linker adds these: start and end of __sched functions */
5093 extern char __sched_text_start[], __sched_text_end[];
5094 return in_lock_functions(addr) ||
5095 (addr >= (unsigned long)__sched_text_start
5096 && addr < (unsigned long)__sched_text_end);
5099 void __init sched_init(void)
5104 for (i = 0; i < NR_CPUS; i++) {
5105 prio_array_t *array;
5108 spin_lock_init(&rq->lock);
5109 rq->active = rq->arrays;
5110 rq->expired = rq->arrays + 1;
5111 rq->best_expired_prio = MAX_PRIO;
5114 rq->sd = &sched_domain_dummy;
5116 rq->active_balance = 0;
5118 rq->migration_thread = NULL;
5119 INIT_LIST_HEAD(&rq->migration_queue);
5121 atomic_set(&rq->nr_iowait, 0);
5122 #ifdef CONFIG_VSERVER_HARDCPU
5123 INIT_LIST_HEAD(&rq->hold_queue);
5126 for (j = 0; j < 2; j++) {
5127 array = rq->arrays + j;
5128 for (k = 0; k < MAX_PRIO; k++) {
5129 INIT_LIST_HEAD(array->queue + k);
5130 __clear_bit(k, array->bitmap);
5132 // delimiter for bitsearch
5133 __set_bit(MAX_PRIO, array->bitmap);
5138 * The boot idle thread does lazy MMU switching as well:
5140 atomic_inc(&init_mm.mm_count);
5141 enter_lazy_tlb(&init_mm, current);
5144 * Make us the idle thread. Technically, schedule() should not be
5145 * called from this thread, however somewhere below it might be,
5146 * but because we are the idle thread, we just pick up running again
5147 * when this runqueue becomes "idle".
5149 init_idle(current, smp_processor_id());
5152 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5153 void __might_sleep(char *file, int line)
5155 #if defined(in_atomic)
5156 static unsigned long prev_jiffy; /* ratelimiting */
5158 if ((in_atomic() || irqs_disabled()) &&
5159 system_state == SYSTEM_RUNNING && !oops_in_progress) {
5160 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
5162 prev_jiffy = jiffies;
5163 printk(KERN_ERR "Debug: sleeping function called from invalid"
5164 " context at %s:%d\n", file, line);
5165 printk("in_atomic():%d, irqs_disabled():%d\n",
5166 in_atomic(), irqs_disabled());
5171 EXPORT_SYMBOL(__might_sleep);
5174 #ifdef CONFIG_MAGIC_SYSRQ
5175 void normalize_rt_tasks(void)
5177 struct task_struct *p;
5178 prio_array_t *array;
5179 unsigned long flags;
5182 read_lock_irq(&tasklist_lock);
5183 for_each_process (p) {
5187 rq = task_rq_lock(p, &flags);
5191 deactivate_task(p, task_rq(p));
5192 __setscheduler(p, SCHED_NORMAL, 0);
5194 vx_activate_task(p);
5195 __activate_task(p, task_rq(p));
5196 resched_task(rq->curr);
5199 task_rq_unlock(rq, &flags);
5201 read_unlock_irq(&tasklist_lock);
5204 #endif /* CONFIG_MAGIC_SYSRQ */