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/cpuset.h>
44 #include <linux/percpu.h>
45 #include <linux/kthread.h>
46 #include <linux/seq_file.h>
47 #include <linux/syscalls.h>
48 #include <linux/times.h>
49 #include <linux/acct.h>
52 #include <asm/unistd.h>
53 #include <linux/vs_context.h>
54 #include <linux/vs_cvirt.h>
55 #include <linux/vs_sched.h>
58 * Convert user-nice values [ -20 ... 0 ... 19 ]
59 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
62 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
63 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
64 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
67 * 'User priority' is the nice value converted to something we
68 * can work with better when scaling various scheduler parameters,
69 * it's a [ 0 ... 39 ] range.
71 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
72 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
73 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
76 * Some helpers for converting nanosecond timing to jiffy resolution
78 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
79 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
82 * These are the 'tuning knobs' of the scheduler:
84 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
85 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
86 * Timeslices get refilled after they expire.
88 #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
89 #define DEF_TIMESLICE (100 * HZ / 1000)
90 #define ON_RUNQUEUE_WEIGHT 30
91 #define CHILD_PENALTY 95
92 #define PARENT_PENALTY 100
94 #define PRIO_BONUS_RATIO 25
95 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
96 #define INTERACTIVE_DELTA 2
97 #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
98 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
99 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
102 * If a task is 'interactive' then we reinsert it in the active
103 * array after it has expired its current timeslice. (it will not
104 * continue to run immediately, it will still roundrobin with
105 * other interactive tasks.)
107 * This part scales the interactivity limit depending on niceness.
109 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
110 * Here are a few examples of different nice levels:
112 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
113 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
114 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
115 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
116 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
118 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
119 * priority range a task can explore, a value of '1' means the
120 * task is rated interactive.)
122 * Ie. nice +19 tasks can never get 'interactive' enough to be
123 * reinserted into the active array. And only heavily CPU-hog nice -20
124 * tasks will be expired. Default nice 0 tasks are somewhere between,
125 * it takes some effort for them to get interactive, but it's not
129 #define CURRENT_BONUS(p) \
130 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
133 #define GRANULARITY (10 * HZ / 1000 ? : 1)
136 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
137 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
140 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
141 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
144 #define SCALE(v1,v1_max,v2_max) \
145 (v1) * (v2_max) / (v1_max)
148 (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
150 #define TASK_INTERACTIVE(p) \
151 ((p)->prio <= (p)->static_prio - DELTA(p))
153 #define INTERACTIVE_SLEEP(p) \
154 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
155 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
157 #define TASK_PREEMPTS_CURR(p, rq) \
158 ((p)->prio < (rq)->curr->prio)
161 * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
162 * to time slice values: [800ms ... 100ms ... 5ms]
164 * The higher a thread's priority, the bigger timeslices
165 * it gets during one round of execution. But even the lowest
166 * priority thread gets MIN_TIMESLICE worth of execution time.
169 #define SCALE_PRIO(x, prio) \
170 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO/2), MIN_TIMESLICE)
172 static inline unsigned int task_timeslice(task_t *p)
174 if (p->static_prio < NICE_TO_PRIO(0))
175 return SCALE_PRIO(DEF_TIMESLICE*4, p->static_prio);
177 return SCALE_PRIO(DEF_TIMESLICE, p->static_prio);
179 #define task_hot(p, now, sd) ((long long) ((now) - (p)->last_ran) \
180 < (long long) (sd)->cache_hot_time)
183 * These are the runqueue data structures:
186 #define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
188 typedef struct runqueue runqueue_t;
191 unsigned int nr_active;
192 unsigned long bitmap[BITMAP_SIZE];
193 struct list_head queue[MAX_PRIO];
197 * This is the main, per-CPU runqueue data structure.
199 * Locking rule: those places that want to lock multiple runqueues
200 * (such as the load balancing or the thread migration code), lock
201 * acquire operations must be ordered by ascending &runqueue.
207 * nr_running and cpu_load should be in the same cacheline because
208 * remote CPUs use both these fields when doing load calculation.
210 unsigned long nr_running;
212 unsigned long cpu_load;
214 unsigned long long nr_switches;
217 * This is part of a global counter where only the total sum
218 * over all CPUs matters. A task can increase this counter on
219 * one CPU and if it got migrated afterwards it may decrease
220 * it on another CPU. Always updated under the runqueue lock:
222 unsigned long nr_uninterruptible;
224 unsigned long expired_timestamp;
225 unsigned long long timestamp_last_tick;
227 struct mm_struct *prev_mm;
228 prio_array_t *active, *expired, arrays[2];
229 int best_expired_prio;
233 struct sched_domain *sd;
235 /* For active balancing */
239 task_t *migration_thread;
240 struct list_head migration_queue;
242 #ifdef CONFIG_VSERVER_HARDCPU
243 struct list_head hold_queue;
247 #ifdef CONFIG_SCHEDSTATS
249 struct sched_info rq_sched_info;
251 /* sys_sched_yield() stats */
252 unsigned long yld_exp_empty;
253 unsigned long yld_act_empty;
254 unsigned long yld_both_empty;
255 unsigned long yld_cnt;
257 /* schedule() stats */
258 unsigned long sched_switch;
259 unsigned long sched_cnt;
260 unsigned long sched_goidle;
262 /* try_to_wake_up() stats */
263 unsigned long ttwu_cnt;
264 unsigned long ttwu_local;
268 static DEFINE_PER_CPU(struct runqueue, runqueues);
270 #define for_each_domain(cpu, domain) \
271 for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
273 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
274 #define this_rq() (&__get_cpu_var(runqueues))
275 #define task_rq(p) cpu_rq(task_cpu(p))
276 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
279 * Default context-switch locking:
281 #ifndef prepare_arch_switch
282 # define prepare_arch_switch(rq, next) do { } while (0)
283 # define finish_arch_switch(rq, next) spin_unlock_irq(&(rq)->lock)
284 # define task_running(rq, p) ((rq)->curr == (p))
288 * task_rq_lock - lock the runqueue a given task resides on and disable
289 * interrupts. Note the ordering: we can safely lookup the task_rq without
290 * explicitly disabling preemption.
292 static inline runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
298 local_irq_save(*flags);
300 spin_lock(&rq->lock);
301 if (unlikely(rq != task_rq(p))) {
302 spin_unlock_irqrestore(&rq->lock, *flags);
303 goto repeat_lock_task;
308 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
311 spin_unlock_irqrestore(&rq->lock, *flags);
314 #ifdef CONFIG_SCHEDSTATS
316 * bump this up when changing the output format or the meaning of an existing
317 * format, so that tools can adapt (or abort)
319 #define SCHEDSTAT_VERSION 11
321 static int show_schedstat(struct seq_file *seq, void *v)
325 seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
326 seq_printf(seq, "timestamp %lu\n", jiffies);
327 for_each_online_cpu(cpu) {
328 runqueue_t *rq = cpu_rq(cpu);
330 struct sched_domain *sd;
334 /* runqueue-specific stats */
336 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
337 cpu, rq->yld_both_empty,
338 rq->yld_act_empty, rq->yld_exp_empty, rq->yld_cnt,
339 rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
340 rq->ttwu_cnt, rq->ttwu_local,
341 rq->rq_sched_info.cpu_time,
342 rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
344 seq_printf(seq, "\n");
347 /* domain-specific stats */
348 for_each_domain(cpu, sd) {
349 enum idle_type itype;
350 char mask_str[NR_CPUS];
352 cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
353 seq_printf(seq, "domain%d %s", dcnt++, mask_str);
354 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
356 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu",
358 sd->lb_balanced[itype],
359 sd->lb_failed[itype],
360 sd->lb_imbalance[itype],
361 sd->lb_gained[itype],
362 sd->lb_hot_gained[itype],
363 sd->lb_nobusyq[itype],
364 sd->lb_nobusyg[itype]);
366 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu\n",
367 sd->alb_cnt, sd->alb_failed, sd->alb_pushed,
368 sd->sbe_pushed, sd->sbe_attempts,
369 sd->ttwu_wake_remote, sd->ttwu_move_affine, sd->ttwu_move_balance);
376 static int schedstat_open(struct inode *inode, struct file *file)
378 unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
379 char *buf = kmalloc(size, GFP_KERNEL);
385 res = single_open(file, show_schedstat, NULL);
387 m = file->private_data;
395 struct file_operations proc_schedstat_operations = {
396 .open = schedstat_open,
399 .release = single_release,
402 # define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
403 # define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
404 #else /* !CONFIG_SCHEDSTATS */
405 # define schedstat_inc(rq, field) do { } while (0)
406 # define schedstat_add(rq, field, amt) do { } while (0)
410 * rq_lock - lock a given runqueue and disable interrupts.
412 static inline runqueue_t *this_rq_lock(void)
419 spin_lock(&rq->lock);
424 #ifdef CONFIG_SCHED_SMT
425 static int cpu_and_siblings_are_idle(int cpu)
428 for_each_cpu_mask(sib, cpu_sibling_map[cpu]) {
437 #define cpu_and_siblings_are_idle(A) idle_cpu(A)
440 #ifdef CONFIG_SCHEDSTATS
442 * Called when a process is dequeued from the active array and given
443 * the cpu. We should note that with the exception of interactive
444 * tasks, the expired queue will become the active queue after the active
445 * queue is empty, without explicitly dequeuing and requeuing tasks in the
446 * expired queue. (Interactive tasks may be requeued directly to the
447 * active queue, thus delaying tasks in the expired queue from running;
448 * see scheduler_tick()).
450 * This function is only called from sched_info_arrive(), rather than
451 * dequeue_task(). Even though a task may be queued and dequeued multiple
452 * times as it is shuffled about, we're really interested in knowing how
453 * long it was from the *first* time it was queued to the time that it
456 static inline void sched_info_dequeued(task_t *t)
458 t->sched_info.last_queued = 0;
462 * Called when a task finally hits the cpu. We can now calculate how
463 * long it was waiting to run. We also note when it began so that we
464 * can keep stats on how long its timeslice is.
466 static inline void sched_info_arrive(task_t *t)
468 unsigned long now = jiffies, diff = 0;
469 struct runqueue *rq = task_rq(t);
471 if (t->sched_info.last_queued)
472 diff = now - t->sched_info.last_queued;
473 sched_info_dequeued(t);
474 t->sched_info.run_delay += diff;
475 t->sched_info.last_arrival = now;
476 t->sched_info.pcnt++;
481 rq->rq_sched_info.run_delay += diff;
482 rq->rq_sched_info.pcnt++;
486 * Called when a process is queued into either the active or expired
487 * array. The time is noted and later used to determine how long we
488 * had to wait for us to reach the cpu. Since the expired queue will
489 * become the active queue after active queue is empty, without dequeuing
490 * and requeuing any tasks, we are interested in queuing to either. It
491 * is unusual but not impossible for tasks to be dequeued and immediately
492 * requeued in the same or another array: this can happen in sched_yield(),
493 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
496 * This function is only called from enqueue_task(), but also only updates
497 * the timestamp if it is already not set. It's assumed that
498 * sched_info_dequeued() will clear that stamp when appropriate.
500 static inline void sched_info_queued(task_t *t)
502 if (!t->sched_info.last_queued)
503 t->sched_info.last_queued = jiffies;
507 * Called when a process ceases being the active-running process, either
508 * voluntarily or involuntarily. Now we can calculate how long we ran.
510 static inline void sched_info_depart(task_t *t)
512 struct runqueue *rq = task_rq(t);
513 unsigned long diff = jiffies - t->sched_info.last_arrival;
515 t->sched_info.cpu_time += diff;
518 rq->rq_sched_info.cpu_time += diff;
522 * Called when tasks are switched involuntarily due, typically, to expiring
523 * their time slice. (This may also be called when switching to or from
524 * the idle task.) We are only called when prev != next.
526 static inline void sched_info_switch(task_t *prev, task_t *next)
528 struct runqueue *rq = task_rq(prev);
531 * prev now departs the cpu. It's not interesting to record
532 * stats about how efficient we were at scheduling the idle
535 if (prev != rq->idle)
536 sched_info_depart(prev);
538 if (next != rq->idle)
539 sched_info_arrive(next);
542 #define sched_info_queued(t) do { } while (0)
543 #define sched_info_switch(t, next) do { } while (0)
544 #endif /* CONFIG_SCHEDSTATS */
547 * Adding/removing a task to/from a priority array:
549 static void dequeue_task(struct task_struct *p, prio_array_t *array)
551 BUG_ON(p->state & TASK_ONHOLD);
553 list_del(&p->run_list);
554 if (list_empty(array->queue + p->prio))
555 __clear_bit(p->prio, array->bitmap);
558 static void enqueue_task(struct task_struct *p, prio_array_t *array)
560 BUG_ON(p->state & TASK_ONHOLD);
561 sched_info_queued(p);
562 list_add_tail(&p->run_list, array->queue + p->prio);
563 __set_bit(p->prio, array->bitmap);
569 * Put task to the end of the run list without the overhead of dequeue
570 * followed by enqueue.
572 static void requeue_task(struct task_struct *p, prio_array_t *array)
574 BUG_ON(p->state & TASK_ONHOLD);
575 list_move_tail(&p->run_list, array->queue + p->prio);
578 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
580 BUG_ON(p->state & TASK_ONHOLD);
581 list_add(&p->run_list, array->queue + p->prio);
582 __set_bit(p->prio, array->bitmap);
588 * effective_prio - return the priority that is based on the static
589 * priority but is modified by bonuses/penalties.
591 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
592 * into the -5 ... 0 ... +5 bonus/penalty range.
594 * We use 25% of the full 0...39 priority range so that:
596 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
597 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
599 * Both properties are important to certain workloads.
601 static int effective_prio(task_t *p)
609 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
611 prio = p->static_prio - bonus;
613 if ((vxi = p->vx_info) &&
614 vx_info_flags(vxi, VXF_SCHED_PRIO, 0))
615 prio += vx_effective_vavavoom(vxi, MAX_USER_PRIO);
617 if (prio < MAX_RT_PRIO)
619 if (prio > MAX_PRIO-1)
625 * __activate_task - move a task to the runqueue.
627 static inline void __activate_task(task_t *p, runqueue_t *rq)
629 enqueue_task(p, rq->active);
634 * __activate_idle_task - move idle task to the _front_ of runqueue.
636 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
638 enqueue_task_head(p, rq->active);
642 static void recalc_task_prio(task_t *p, unsigned long long now)
644 /* Caller must always ensure 'now >= p->timestamp' */
645 unsigned long long __sleep_time = now - p->timestamp;
646 unsigned long sleep_time;
648 if (__sleep_time > NS_MAX_SLEEP_AVG)
649 sleep_time = NS_MAX_SLEEP_AVG;
651 sleep_time = (unsigned long)__sleep_time;
653 if (likely(sleep_time > 0)) {
655 * User tasks that sleep a long time are categorised as
656 * idle and will get just interactive status to stay active &
657 * prevent them suddenly becoming cpu hogs and starving
660 if (p->mm && p->activated != -1 &&
661 sleep_time > INTERACTIVE_SLEEP(p)) {
662 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
666 * The lower the sleep avg a task has the more
667 * rapidly it will rise with sleep time.
669 sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
672 * Tasks waking from uninterruptible sleep are
673 * limited in their sleep_avg rise as they
674 * are likely to be waiting on I/O
676 if (p->activated == -1 && p->mm) {
677 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
679 else if (p->sleep_avg + sleep_time >=
680 INTERACTIVE_SLEEP(p)) {
681 p->sleep_avg = INTERACTIVE_SLEEP(p);
687 * This code gives a bonus to interactive tasks.
689 * The boost works by updating the 'average sleep time'
690 * value here, based on ->timestamp. The more time a
691 * task spends sleeping, the higher the average gets -
692 * and the higher the priority boost gets as well.
694 p->sleep_avg += sleep_time;
696 if (p->sleep_avg > NS_MAX_SLEEP_AVG)
697 p->sleep_avg = NS_MAX_SLEEP_AVG;
701 p->prio = effective_prio(p);
705 * activate_task - move a task to the runqueue and do priority recalculation
707 * Update all the scheduling statistics stuff. (sleep average
708 * calculation, priority modifiers, etc.)
710 static void activate_task(task_t *p, runqueue_t *rq, int local)
712 unsigned long long now;
717 /* Compensate for drifting sched_clock */
718 runqueue_t *this_rq = this_rq();
719 now = (now - this_rq->timestamp_last_tick)
720 + rq->timestamp_last_tick;
724 recalc_task_prio(p, now);
727 * This checks to make sure it's not an uninterruptible task
728 * that is now waking up.
732 * Tasks which were woken up by interrupts (ie. hw events)
733 * are most likely of interactive nature. So we give them
734 * the credit of extending their sleep time to the period
735 * of time they spend on the runqueue, waiting for execution
736 * on a CPU, first time around:
742 * Normal first-time wakeups get a credit too for
743 * on-runqueue time, but it will be weighted down:
751 __activate_task(p, rq);
755 * deactivate_task - remove a task from the runqueue.
757 static void __deactivate_task(struct task_struct *p, runqueue_t *rq)
760 dequeue_task(p, p->array);
765 void deactivate_task(struct task_struct *p, runqueue_t *rq)
767 vx_deactivate_task(p);
768 __deactivate_task(p, rq);
772 #ifdef CONFIG_VSERVER_HARDCPU
774 * vx_hold_task - put a task on the hold queue
777 void vx_hold_task(struct vx_info *vxi,
778 struct task_struct *p, runqueue_t *rq)
780 __deactivate_task(p, rq);
781 p->state |= TASK_ONHOLD;
782 /* a new one on hold */
784 list_add_tail(&p->run_list, &rq->hold_queue);
788 * vx_unhold_task - put a task back to the runqueue
791 void vx_unhold_task(struct vx_info *vxi,
792 struct task_struct *p, runqueue_t *rq)
794 list_del(&p->run_list);
795 /* one less waiting */
797 p->state &= ~TASK_ONHOLD;
798 enqueue_task(p, rq->expired);
801 if (p->static_prio < rq->best_expired_prio)
802 rq->best_expired_prio = p->static_prio;
806 void vx_hold_task(struct vx_info *vxi,
807 struct task_struct *p, runqueue_t *rq)
813 void vx_unhold_task(struct vx_info *vxi,
814 struct task_struct *p, runqueue_t *rq)
818 #endif /* CONFIG_VSERVER_HARDCPU */
822 * resched_task - mark a task 'to be rescheduled now'.
824 * On UP this means the setting of the need_resched flag, on SMP it
825 * might also involve a cross-CPU call to trigger the scheduler on
829 static void resched_task(task_t *p)
831 int need_resched, nrpolling;
833 assert_spin_locked(&task_rq(p)->lock);
835 /* minimise the chance of sending an interrupt to poll_idle() */
836 nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
837 need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
838 nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
840 if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
841 smp_send_reschedule(task_cpu(p));
844 static inline void resched_task(task_t *p)
846 set_tsk_need_resched(p);
851 * task_curr - is this task currently executing on a CPU?
852 * @p: the task in question.
854 inline int task_curr(const task_t *p)
856 return cpu_curr(task_cpu(p)) == p;
866 struct list_head list;
867 enum request_type type;
869 /* For REQ_MOVE_TASK */
873 /* For REQ_SET_DOMAIN */
874 struct sched_domain *sd;
876 struct completion done;
880 * The task's runqueue lock must be held.
881 * Returns true if you have to wait for migration thread.
883 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
885 runqueue_t *rq = task_rq(p);
888 * If the task is not on a runqueue (and not running), then
889 * it is sufficient to simply update the task's cpu field.
891 if (!p->array && !task_running(rq, p)) {
892 set_task_cpu(p, dest_cpu);
896 init_completion(&req->done);
897 req->type = REQ_MOVE_TASK;
899 req->dest_cpu = dest_cpu;
900 list_add(&req->list, &rq->migration_queue);
905 * wait_task_inactive - wait for a thread to unschedule.
907 * The caller must ensure that the task *will* unschedule sometime soon,
908 * else this function might spin for a *long* time. This function can't
909 * be called with interrupts off, or it may introduce deadlock with
910 * smp_call_function() if an IPI is sent by the same process we are
911 * waiting to become inactive.
913 void wait_task_inactive(task_t * p)
920 rq = task_rq_lock(p, &flags);
921 /* Must be off runqueue entirely, not preempted. */
922 if (unlikely(p->array || task_running(rq, p))) {
923 /* If it's preempted, we yield. It could be a while. */
924 preempted = !task_running(rq, p);
925 task_rq_unlock(rq, &flags);
931 task_rq_unlock(rq, &flags);
935 * kick_process - kick a running thread to enter/exit the kernel
936 * @p: the to-be-kicked thread
938 * Cause a process which is running on another CPU to enter
939 * kernel-mode, without any delay. (to get signals handled.)
941 * NOTE: this function doesnt have to take the runqueue lock,
942 * because all it wants to ensure is that the remote task enters
943 * the kernel. If the IPI races and the task has been migrated
944 * to another CPU then no harm is done and the purpose has been
947 void kick_process(task_t *p)
953 if ((cpu != smp_processor_id()) && task_curr(p))
954 smp_send_reschedule(cpu);
959 * Return a low guess at the load of a migration-source cpu.
961 * We want to under-estimate the load of migration sources, to
962 * balance conservatively.
964 static inline unsigned long source_load(int cpu)
966 runqueue_t *rq = cpu_rq(cpu);
967 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
969 return min(rq->cpu_load, load_now);
973 * Return a high guess at the load of a migration-target cpu
975 static inline unsigned long target_load(int cpu)
977 runqueue_t *rq = cpu_rq(cpu);
978 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
980 return max(rq->cpu_load, load_now);
986 * wake_idle() will wake a task on an idle cpu if task->cpu is
987 * not idle and an idle cpu is available. The span of cpus to
988 * search starts with cpus closest then further out as needed,
989 * so we always favor a closer, idle cpu.
991 * Returns the CPU we should wake onto.
993 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
994 static int wake_idle(int cpu, task_t *p)
997 struct sched_domain *sd;
1003 for_each_domain(cpu, sd) {
1004 if (sd->flags & SD_WAKE_IDLE) {
1005 cpus_and(tmp, sd->span, cpu_online_map);
1006 cpus_and(tmp, tmp, p->cpus_allowed);
1007 for_each_cpu_mask(i, tmp) {
1017 static inline int wake_idle(int cpu, task_t *p)
1024 * try_to_wake_up - wake up a thread
1025 * @p: the to-be-woken-up thread
1026 * @state: the mask of task states that can be woken
1027 * @sync: do a synchronous wakeup?
1029 * Put it on the run-queue if it's not already there. The "current"
1030 * thread is always on the run-queue (except when the actual
1031 * re-schedule is in progress), and as such you're allowed to do
1032 * the simpler "current->state = TASK_RUNNING" to mark yourself
1033 * runnable without the overhead of this.
1035 * returns failure only if the task is already active.
1037 static int try_to_wake_up(task_t * p, unsigned int state, int sync)
1039 int cpu, this_cpu, success = 0;
1040 unsigned long flags;
1044 unsigned long load, this_load;
1045 struct sched_domain *sd;
1049 rq = task_rq_lock(p, &flags);
1050 old_state = p->state;
1052 /* we need to unhold suspended tasks */
1053 if (old_state & TASK_ONHOLD) {
1054 vx_unhold_task(p->vx_info, p, rq);
1055 old_state = p->state;
1057 if (!(old_state & state))
1064 this_cpu = smp_processor_id();
1067 if (unlikely(task_running(rq, p)))
1070 #ifdef CONFIG_SCHEDSTATS
1071 schedstat_inc(rq, ttwu_cnt);
1072 if (cpu == this_cpu) {
1073 schedstat_inc(rq, ttwu_local);
1075 for_each_domain(this_cpu, sd) {
1076 if (cpu_isset(cpu, sd->span)) {
1077 schedstat_inc(sd, ttwu_wake_remote);
1085 if (cpu == this_cpu || unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1088 load = source_load(cpu);
1089 this_load = target_load(this_cpu);
1092 * If sync wakeup then subtract the (maximum possible) effect of
1093 * the currently running task from the load of the current CPU:
1096 this_load -= SCHED_LOAD_SCALE;
1098 /* Don't pull the task off an idle CPU to a busy one */
1099 if (load < SCHED_LOAD_SCALE/2 && this_load > SCHED_LOAD_SCALE/2)
1102 new_cpu = this_cpu; /* Wake to this CPU if we can */
1105 * Scan domains for affine wakeup and passive balancing
1108 for_each_domain(this_cpu, sd) {
1109 unsigned int imbalance;
1111 * Start passive balancing when half the imbalance_pct
1114 imbalance = sd->imbalance_pct + (sd->imbalance_pct - 100) / 2;
1116 if ((sd->flags & SD_WAKE_AFFINE) &&
1117 !task_hot(p, rq->timestamp_last_tick, sd)) {
1119 * This domain has SD_WAKE_AFFINE and p is cache cold
1122 if (cpu_isset(cpu, sd->span)) {
1123 schedstat_inc(sd, ttwu_move_affine);
1126 } else if ((sd->flags & SD_WAKE_BALANCE) &&
1127 imbalance*this_load <= 100*load) {
1129 * This domain has SD_WAKE_BALANCE and there is
1132 if (cpu_isset(cpu, sd->span)) {
1133 schedstat_inc(sd, ttwu_move_balance);
1139 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1141 new_cpu = wake_idle(new_cpu, p);
1142 if (new_cpu != cpu) {
1143 set_task_cpu(p, new_cpu);
1144 task_rq_unlock(rq, &flags);
1145 /* might preempt at this point */
1146 rq = task_rq_lock(p, &flags);
1147 old_state = p->state;
1148 if (!(old_state & state))
1153 this_cpu = smp_processor_id();
1158 #endif /* CONFIG_SMP */
1159 if (old_state == TASK_UNINTERRUPTIBLE) {
1160 rq->nr_uninterruptible--;
1162 * Tasks on involuntary sleep don't earn
1163 * sleep_avg beyond just interactive state.
1169 * Sync wakeups (i.e. those types of wakeups where the waker
1170 * has indicated that it will leave the CPU in short order)
1171 * don't trigger a preemption, if the woken up task will run on
1172 * this cpu. (in this case the 'I will reschedule' promise of
1173 * the waker guarantees that the freshly woken up task is going
1174 * to be considered on this CPU.)
1176 activate_task(p, rq, cpu == this_cpu);
1177 /* this is to get the accounting behind the load update */
1178 if (old_state == TASK_UNINTERRUPTIBLE)
1179 vx_uninterruptible_dec(p);
1180 if (!sync || cpu != this_cpu) {
1181 if (TASK_PREEMPTS_CURR(p, rq))
1182 resched_task(rq->curr);
1187 p->state = TASK_RUNNING;
1189 task_rq_unlock(rq, &flags);
1194 int fastcall wake_up_process(task_t * p)
1196 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1197 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1200 EXPORT_SYMBOL(wake_up_process);
1202 int fastcall wake_up_state(task_t *p, unsigned int state)
1204 return try_to_wake_up(p, state, 0);
1208 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1209 struct sched_domain *sd);
1213 * Perform scheduler related setup for a newly forked process p.
1214 * p is forked by current.
1216 void fastcall sched_fork(task_t *p)
1219 * We mark the process as running here, but have not actually
1220 * inserted it onto the runqueue yet. This guarantees that
1221 * nobody will actually run it, and a signal or other external
1222 * event cannot wake it up and insert it on the runqueue either.
1224 p->state = TASK_RUNNING;
1225 INIT_LIST_HEAD(&p->run_list);
1227 spin_lock_init(&p->switch_lock);
1228 #ifdef CONFIG_SCHEDSTATS
1229 memset(&p->sched_info, 0, sizeof(p->sched_info));
1231 #ifdef CONFIG_PREEMPT
1233 * During context-switch we hold precisely one spinlock, which
1234 * schedule_tail drops. (in the common case it's this_rq()->lock,
1235 * but it also can be p->switch_lock.) So we compensate with a count
1236 * of 1. Also, we want to start with kernel preemption disabled.
1238 p->thread_info->preempt_count = 1;
1241 * Share the timeslice between parent and child, thus the
1242 * total amount of pending timeslices in the system doesn't change,
1243 * resulting in more scheduling fairness.
1245 local_irq_disable();
1246 p->time_slice = (current->time_slice + 1) >> 1;
1248 * The remainder of the first timeslice might be recovered by
1249 * the parent if the child exits early enough.
1251 p->first_time_slice = 1;
1252 current->time_slice >>= 1;
1253 p->timestamp = sched_clock();
1254 if (unlikely(!current->time_slice)) {
1256 * This case is rare, it happens when the parent has only
1257 * a single jiffy left from its timeslice. Taking the
1258 * runqueue lock is not a problem.
1260 current->time_slice = 1;
1270 * wake_up_new_task - wake up a newly created task for the first time.
1272 * This function will do some initial scheduler statistics housekeeping
1273 * that must be done for every newly created context, then puts the task
1274 * on the runqueue and wakes it.
1276 void fastcall wake_up_new_task(task_t * p, unsigned long clone_flags)
1278 unsigned long flags;
1280 runqueue_t *rq, *this_rq;
1282 rq = task_rq_lock(p, &flags);
1284 this_cpu = smp_processor_id();
1286 BUG_ON(p->state != TASK_RUNNING);
1289 * We decrease the sleep average of forking parents
1290 * and children as well, to keep max-interactive tasks
1291 * from forking tasks that are max-interactive. The parent
1292 * (current) is done further down, under its lock.
1294 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1295 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1297 p->prio = effective_prio(p);
1299 vx_activate_task(p);
1300 if (likely(cpu == this_cpu)) {
1301 if (!(clone_flags & CLONE_VM)) {
1303 * The VM isn't cloned, so we're in a good position to
1304 * do child-runs-first in anticipation of an exec. This
1305 * usually avoids a lot of COW overhead.
1307 if (unlikely(!current->array))
1308 __activate_task(p, rq);
1310 p->prio = current->prio;
1311 BUG_ON(p->state & TASK_ONHOLD);
1312 list_add_tail(&p->run_list, ¤t->run_list);
1313 p->array = current->array;
1314 p->array->nr_active++;
1319 /* Run child last */
1320 __activate_task(p, rq);
1322 * We skip the following code due to cpu == this_cpu
1324 * task_rq_unlock(rq, &flags);
1325 * this_rq = task_rq_lock(current, &flags);
1329 this_rq = cpu_rq(this_cpu);
1332 * Not the local CPU - must adjust timestamp. This should
1333 * get optimised away in the !CONFIG_SMP case.
1335 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1336 + rq->timestamp_last_tick;
1337 __activate_task(p, rq);
1338 if (TASK_PREEMPTS_CURR(p, rq))
1339 resched_task(rq->curr);
1342 * Parent and child are on different CPUs, now get the
1343 * parent runqueue to update the parent's ->sleep_avg:
1345 task_rq_unlock(rq, &flags);
1346 this_rq = task_rq_lock(current, &flags);
1348 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1349 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1350 task_rq_unlock(this_rq, &flags);
1354 * Potentially available exiting-child timeslices are
1355 * retrieved here - this way the parent does not get
1356 * penalized for creating too many threads.
1358 * (this cannot be used to 'generate' timeslices
1359 * artificially, because any timeslice recovered here
1360 * was given away by the parent in the first place.)
1362 void fastcall sched_exit(task_t * p)
1364 unsigned long flags;
1368 * If the child was a (relative-) CPU hog then decrease
1369 * the sleep_avg of the parent as well.
1371 rq = task_rq_lock(p->parent, &flags);
1372 if (p->first_time_slice) {
1373 p->parent->time_slice += p->time_slice;
1374 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1375 p->parent->time_slice = task_timeslice(p);
1377 if (p->sleep_avg < p->parent->sleep_avg)
1378 p->parent->sleep_avg = p->parent->sleep_avg /
1379 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1381 task_rq_unlock(rq, &flags);
1385 * finish_task_switch - clean up after a task-switch
1386 * @prev: the thread we just switched away from.
1388 * We enter this with the runqueue still locked, and finish_arch_switch()
1389 * will unlock it along with doing any other architecture-specific cleanup
1392 * Note that we may have delayed dropping an mm in context_switch(). If
1393 * so, we finish that here outside of the runqueue lock. (Doing it
1394 * with the lock held can cause deadlocks; see schedule() for
1397 static inline void finish_task_switch(task_t *prev)
1398 __releases(rq->lock)
1400 runqueue_t *rq = this_rq();
1401 struct mm_struct *mm = rq->prev_mm;
1402 unsigned long prev_task_flags;
1407 * A task struct has one reference for the use as "current".
1408 * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1409 * calls schedule one last time. The schedule call will never return,
1410 * and the scheduled task must drop that reference.
1411 * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1412 * still held, otherwise prev could be scheduled on another cpu, die
1413 * there before we look at prev->state, and then the reference would
1415 * Manfred Spraul <manfred@colorfullife.com>
1417 prev_task_flags = prev->flags;
1418 finish_arch_switch(rq, prev);
1421 if (unlikely(prev_task_flags & PF_DEAD))
1422 put_task_struct(prev);
1426 * schedule_tail - first thing a freshly forked thread must call.
1427 * @prev: the thread we just switched away from.
1429 asmlinkage void schedule_tail(task_t *prev)
1430 __releases(rq->lock)
1432 finish_task_switch(prev);
1434 if (current->set_child_tid)
1435 put_user(current->pid, current->set_child_tid);
1439 * context_switch - switch to the new MM and the new
1440 * thread's register state.
1443 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1445 struct mm_struct *mm = next->mm;
1446 struct mm_struct *oldmm = prev->active_mm;
1448 if (unlikely(!mm)) {
1449 next->active_mm = oldmm;
1450 atomic_inc(&oldmm->mm_count);
1451 enter_lazy_tlb(oldmm, next);
1453 switch_mm(oldmm, mm, next);
1455 if (unlikely(!prev->mm)) {
1456 prev->active_mm = NULL;
1457 WARN_ON(rq->prev_mm);
1458 rq->prev_mm = oldmm;
1461 /* Here we just switch the register state and the stack. */
1462 switch_to(prev, next, prev);
1468 * nr_running, nr_uninterruptible and nr_context_switches:
1470 * externally visible scheduler statistics: current number of runnable
1471 * threads, current number of uninterruptible-sleeping threads, total
1472 * number of context switches performed since bootup.
1474 unsigned long nr_running(void)
1476 unsigned long i, sum = 0;
1478 for_each_online_cpu(i)
1479 sum += cpu_rq(i)->nr_running;
1484 unsigned long nr_uninterruptible(void)
1486 unsigned long i, sum = 0;
1489 sum += cpu_rq(i)->nr_uninterruptible;
1492 * Since we read the counters lockless, it might be slightly
1493 * inaccurate. Do not allow it to go below zero though:
1495 if (unlikely((long)sum < 0))
1501 unsigned long long nr_context_switches(void)
1503 unsigned long long i, sum = 0;
1506 sum += cpu_rq(i)->nr_switches;
1511 unsigned long nr_iowait(void)
1513 unsigned long i, sum = 0;
1516 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1524 * double_rq_lock - safely lock two runqueues
1526 * Note this does not disable interrupts like task_rq_lock,
1527 * you need to do so manually before calling.
1529 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1530 __acquires(rq1->lock)
1531 __acquires(rq2->lock)
1534 spin_lock(&rq1->lock);
1535 __acquire(rq2->lock); /* Fake it out ;) */
1538 spin_lock(&rq1->lock);
1539 spin_lock(&rq2->lock);
1541 spin_lock(&rq2->lock);
1542 spin_lock(&rq1->lock);
1548 * double_rq_unlock - safely unlock two runqueues
1550 * Note this does not restore interrupts like task_rq_unlock,
1551 * you need to do so manually after calling.
1553 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1554 __releases(rq1->lock)
1555 __releases(rq2->lock)
1557 spin_unlock(&rq1->lock);
1559 spin_unlock(&rq2->lock);
1561 __release(rq2->lock);
1565 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1567 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1568 __releases(this_rq->lock)
1569 __acquires(busiest->lock)
1570 __acquires(this_rq->lock)
1572 if (unlikely(!spin_trylock(&busiest->lock))) {
1573 if (busiest < this_rq) {
1574 spin_unlock(&this_rq->lock);
1575 spin_lock(&busiest->lock);
1576 spin_lock(&this_rq->lock);
1578 spin_lock(&busiest->lock);
1583 * find_idlest_cpu - find the least busy runqueue.
1585 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1586 struct sched_domain *sd)
1588 unsigned long load, min_load, this_load;
1593 min_load = ULONG_MAX;
1595 cpus_and(mask, sd->span, p->cpus_allowed);
1597 for_each_cpu_mask(i, mask) {
1598 load = target_load(i);
1600 if (load < min_load) {
1604 /* break out early on an idle CPU: */
1610 /* add +1 to account for the new task */
1611 this_load = source_load(this_cpu) + SCHED_LOAD_SCALE;
1614 * Would with the addition of the new task to the
1615 * current CPU there be an imbalance between this
1616 * CPU and the idlest CPU?
1618 * Use half of the balancing threshold - new-context is
1619 * a good opportunity to balance.
1621 if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1628 * If dest_cpu is allowed for this process, migrate the task to it.
1629 * This is accomplished by forcing the cpu_allowed mask to only
1630 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1631 * the cpu_allowed mask is restored.
1633 static void sched_migrate_task(task_t *p, int dest_cpu)
1635 migration_req_t req;
1637 unsigned long flags;
1639 rq = task_rq_lock(p, &flags);
1640 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1641 || unlikely(cpu_is_offline(dest_cpu)))
1644 /* force the process onto the specified CPU */
1645 if (migrate_task(p, dest_cpu, &req)) {
1646 /* Need to wait for migration thread (might exit: take ref). */
1647 struct task_struct *mt = rq->migration_thread;
1648 get_task_struct(mt);
1649 task_rq_unlock(rq, &flags);
1650 wake_up_process(mt);
1651 put_task_struct(mt);
1652 wait_for_completion(&req.done);
1656 task_rq_unlock(rq, &flags);
1660 * sched_exec(): find the highest-level, exec-balance-capable
1661 * domain and try to migrate the task to the least loaded CPU.
1663 * execve() is a valuable balancing opportunity, because at this point
1664 * the task has the smallest effective memory and cache footprint.
1666 void sched_exec(void)
1668 struct sched_domain *tmp, *sd = NULL;
1669 int new_cpu, this_cpu = get_cpu();
1671 /* Prefer the current CPU if there's only this task running */
1672 if (this_rq()->nr_running <= 1)
1675 for_each_domain(this_cpu, tmp)
1676 if (tmp->flags & SD_BALANCE_EXEC)
1680 schedstat_inc(sd, sbe_attempts);
1681 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1682 if (new_cpu != this_cpu) {
1683 schedstat_inc(sd, sbe_pushed);
1685 sched_migrate_task(current, new_cpu);
1694 * pull_task - move a task from a remote runqueue to the local runqueue.
1695 * Both runqueues must be locked.
1698 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1699 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1701 dequeue_task(p, src_array);
1702 src_rq->nr_running--;
1703 set_task_cpu(p, this_cpu);
1704 this_rq->nr_running++;
1705 enqueue_task(p, this_array);
1706 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1707 + this_rq->timestamp_last_tick;
1709 * Note that idle threads have a prio of MAX_PRIO, for this test
1710 * to be always true for them.
1712 if (TASK_PREEMPTS_CURR(p, this_rq))
1713 resched_task(this_rq->curr);
1717 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1720 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1721 struct sched_domain *sd, enum idle_type idle)
1724 * We do not migrate tasks that are:
1725 * 1) running (obviously), or
1726 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1727 * 3) are cache-hot on their current CPU.
1729 if (task_running(rq, p))
1731 if (!cpu_isset(this_cpu, p->cpus_allowed))
1735 * Aggressive migration if:
1736 * 1) the [whole] cpu is idle, or
1737 * 2) too many balance attempts have failed.
1740 if (cpu_and_siblings_are_idle(this_cpu) || \
1741 sd->nr_balance_failed > sd->cache_nice_tries)
1744 if (task_hot(p, rq->timestamp_last_tick, sd))
1750 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1751 * as part of a balancing operation within "domain". Returns the number of
1754 * Called with both runqueues locked.
1756 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1757 unsigned long max_nr_move, struct sched_domain *sd,
1758 enum idle_type idle)
1760 prio_array_t *array, *dst_array;
1761 struct list_head *head, *curr;
1762 int idx, pulled = 0;
1765 if (max_nr_move <= 0 || busiest->nr_running <= 1)
1769 * We first consider expired tasks. Those will likely not be
1770 * executed in the near future, and they are most likely to
1771 * be cache-cold, thus switching CPUs has the least effect
1774 if (busiest->expired->nr_active) {
1775 array = busiest->expired;
1776 dst_array = this_rq->expired;
1778 array = busiest->active;
1779 dst_array = this_rq->active;
1783 /* Start searching at priority 0: */
1787 idx = sched_find_first_bit(array->bitmap);
1789 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1790 if (idx >= MAX_PRIO) {
1791 if (array == busiest->expired && busiest->active->nr_active) {
1792 array = busiest->active;
1793 dst_array = this_rq->active;
1799 head = array->queue + idx;
1802 tmp = list_entry(curr, task_t, run_list);
1806 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
1813 #ifdef CONFIG_SCHEDSTATS
1814 if (task_hot(tmp, busiest->timestamp_last_tick, sd))
1815 schedstat_inc(sd, lb_hot_gained[idle]);
1818 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
1821 /* We only want to steal up to the prescribed number of tasks. */
1822 if (pulled < max_nr_move) {
1830 * Right now, this is the only place pull_task() is called,
1831 * so we can safely collect pull_task() stats here rather than
1832 * inside pull_task().
1834 schedstat_add(sd, lb_gained[idle], pulled);
1839 * find_busiest_group finds and returns the busiest CPU group within the
1840 * domain. It calculates and returns the number of tasks which should be
1841 * moved to restore balance via the imbalance parameter.
1843 static struct sched_group *
1844 find_busiest_group(struct sched_domain *sd, int this_cpu,
1845 unsigned long *imbalance, enum idle_type idle)
1847 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
1848 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
1850 max_load = this_load = total_load = total_pwr = 0;
1857 local_group = cpu_isset(this_cpu, group->cpumask);
1859 /* Tally up the load of all CPUs in the group */
1862 for_each_cpu_mask(i, group->cpumask) {
1863 /* Bias balancing toward cpus of our domain */
1865 load = target_load(i);
1867 load = source_load(i);
1872 total_load += avg_load;
1873 total_pwr += group->cpu_power;
1875 /* Adjust by relative CPU power of the group */
1876 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1879 this_load = avg_load;
1882 } else if (avg_load > max_load) {
1883 max_load = avg_load;
1887 group = group->next;
1888 } while (group != sd->groups);
1890 if (!busiest || this_load >= max_load)
1893 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
1895 if (this_load >= avg_load ||
1896 100*max_load <= sd->imbalance_pct*this_load)
1900 * We're trying to get all the cpus to the average_load, so we don't
1901 * want to push ourselves above the average load, nor do we wish to
1902 * reduce the max loaded cpu below the average load, as either of these
1903 * actions would just result in more rebalancing later, and ping-pong
1904 * tasks around. Thus we look for the minimum possible imbalance.
1905 * Negative imbalances (*we* are more loaded than anyone else) will
1906 * be counted as no imbalance for these purposes -- we can't fix that
1907 * by pulling tasks to us. Be careful of negative numbers as they'll
1908 * appear as very large values with unsigned longs.
1910 /* How much load to actually move to equalise the imbalance */
1911 *imbalance = min((max_load - avg_load) * busiest->cpu_power,
1912 (avg_load - this_load) * this->cpu_power)
1915 if (*imbalance < SCHED_LOAD_SCALE) {
1916 unsigned long pwr_now = 0, pwr_move = 0;
1919 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
1925 * OK, we don't have enough imbalance to justify moving tasks,
1926 * however we may be able to increase total CPU power used by
1930 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
1931 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
1932 pwr_now /= SCHED_LOAD_SCALE;
1934 /* Amount of load we'd subtract */
1935 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
1937 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
1940 /* Amount of load we'd add */
1941 if (max_load*busiest->cpu_power <
1942 SCHED_LOAD_SCALE*SCHED_LOAD_SCALE)
1943 tmp = max_load*busiest->cpu_power/this->cpu_power;
1945 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
1946 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
1947 pwr_move /= SCHED_LOAD_SCALE;
1949 /* Move if we gain throughput */
1950 if (pwr_move <= pwr_now)
1957 /* Get rid of the scaling factor, rounding down as we divide */
1958 *imbalance = *imbalance / SCHED_LOAD_SCALE;
1963 if (busiest && (idle == NEWLY_IDLE ||
1964 (idle == SCHED_IDLE && max_load > SCHED_LOAD_SCALE)) ) {
1974 * find_busiest_queue - find the busiest runqueue among the cpus in group.
1976 static runqueue_t *find_busiest_queue(struct sched_group *group)
1978 unsigned long load, max_load = 0;
1979 runqueue_t *busiest = NULL;
1982 for_each_cpu_mask(i, group->cpumask) {
1983 load = source_load(i);
1985 if (load > max_load) {
1987 busiest = cpu_rq(i);
1995 * Check this_cpu to ensure it is balanced within domain. Attempt to move
1996 * tasks if there is an imbalance.
1998 * Called with this_rq unlocked.
2000 static int load_balance(int this_cpu, runqueue_t *this_rq,
2001 struct sched_domain *sd, enum idle_type idle)
2003 struct sched_group *group;
2004 runqueue_t *busiest;
2005 unsigned long imbalance;
2008 spin_lock(&this_rq->lock);
2009 schedstat_inc(sd, lb_cnt[idle]);
2011 group = find_busiest_group(sd, this_cpu, &imbalance, idle);
2013 schedstat_inc(sd, lb_nobusyg[idle]);
2017 busiest = find_busiest_queue(group);
2019 schedstat_inc(sd, lb_nobusyq[idle]);
2024 * This should be "impossible", but since load
2025 * balancing is inherently racy and statistical,
2026 * it could happen in theory.
2028 if (unlikely(busiest == this_rq)) {
2033 schedstat_add(sd, lb_imbalance[idle], imbalance);
2036 if (busiest->nr_running > 1) {
2038 * Attempt to move tasks. If find_busiest_group has found
2039 * an imbalance but busiest->nr_running <= 1, the group is
2040 * still unbalanced. nr_moved simply stays zero, so it is
2041 * correctly treated as an imbalance.
2043 double_lock_balance(this_rq, busiest);
2044 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2045 imbalance, sd, idle);
2046 spin_unlock(&busiest->lock);
2048 spin_unlock(&this_rq->lock);
2051 schedstat_inc(sd, lb_failed[idle]);
2052 sd->nr_balance_failed++;
2054 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2057 spin_lock(&busiest->lock);
2058 if (!busiest->active_balance) {
2059 busiest->active_balance = 1;
2060 busiest->push_cpu = this_cpu;
2063 spin_unlock(&busiest->lock);
2065 wake_up_process(busiest->migration_thread);
2068 * We've kicked active balancing, reset the failure
2071 sd->nr_balance_failed = sd->cache_nice_tries;
2075 * We were unbalanced, but unsuccessful in move_tasks(),
2076 * so bump the balance_interval to lessen the lock contention.
2078 if (sd->balance_interval < sd->max_interval)
2079 sd->balance_interval++;
2081 sd->nr_balance_failed = 0;
2083 /* We were unbalanced, so reset the balancing interval */
2084 sd->balance_interval = sd->min_interval;
2090 spin_unlock(&this_rq->lock);
2092 schedstat_inc(sd, lb_balanced[idle]);
2094 /* tune up the balancing interval */
2095 if (sd->balance_interval < sd->max_interval)
2096 sd->balance_interval *= 2;
2102 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2103 * tasks if there is an imbalance.
2105 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2106 * this_rq is locked.
2108 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2109 struct sched_domain *sd)
2111 struct sched_group *group;
2112 runqueue_t *busiest = NULL;
2113 unsigned long imbalance;
2116 schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2117 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
2119 schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
2120 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2124 busiest = find_busiest_queue(group);
2125 if (!busiest || busiest == this_rq) {
2126 schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
2127 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2131 /* Attempt to move tasks */
2132 double_lock_balance(this_rq, busiest);
2134 schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2135 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2136 imbalance, sd, NEWLY_IDLE);
2138 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2140 spin_unlock(&busiest->lock);
2147 * idle_balance is called by schedule() if this_cpu is about to become
2148 * idle. Attempts to pull tasks from other CPUs.
2150 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
2152 struct sched_domain *sd;
2154 for_each_domain(this_cpu, sd) {
2155 if (sd->flags & SD_BALANCE_NEWIDLE) {
2156 if (load_balance_newidle(this_cpu, this_rq, sd)) {
2157 /* We've pulled tasks over so stop searching */
2165 * active_load_balance is run by migration threads. It pushes running tasks
2166 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2167 * running on each physical CPU where possible, and avoids physical /
2168 * logical imbalances.
2170 * Called with busiest_rq locked.
2172 static void active_load_balance(runqueue_t *busiest_rq, int busiest_cpu)
2174 struct sched_domain *sd;
2175 struct sched_group *cpu_group;
2176 runqueue_t *target_rq;
2177 cpumask_t visited_cpus;
2181 * Search for suitable CPUs to push tasks to in successively higher
2182 * domains with SD_LOAD_BALANCE set.
2184 visited_cpus = CPU_MASK_NONE;
2185 for_each_domain(busiest_cpu, sd) {
2186 if (!(sd->flags & SD_LOAD_BALANCE))
2187 /* no more domains to search */
2190 schedstat_inc(sd, alb_cnt);
2192 cpu_group = sd->groups;
2194 for_each_cpu_mask(cpu, cpu_group->cpumask) {
2195 if (busiest_rq->nr_running <= 1)
2196 /* no more tasks left to move */
2198 if (cpu_isset(cpu, visited_cpus))
2200 cpu_set(cpu, visited_cpus);
2201 if (!cpu_and_siblings_are_idle(cpu) || cpu == busiest_cpu)
2204 target_rq = cpu_rq(cpu);
2206 * This condition is "impossible", if it occurs
2207 * we need to fix it. Originally reported by
2208 * Bjorn Helgaas on a 128-cpu setup.
2210 BUG_ON(busiest_rq == target_rq);
2212 /* move a task from busiest_rq to target_rq */
2213 double_lock_balance(busiest_rq, target_rq);
2214 if (move_tasks(target_rq, cpu, busiest_rq,
2215 1, sd, SCHED_IDLE)) {
2216 schedstat_inc(sd, alb_pushed);
2218 schedstat_inc(sd, alb_failed);
2220 spin_unlock(&target_rq->lock);
2222 cpu_group = cpu_group->next;
2223 } while (cpu_group != sd->groups);
2228 * rebalance_tick will get called every timer tick, on every CPU.
2230 * It checks each scheduling domain to see if it is due to be balanced,
2231 * and initiates a balancing operation if so.
2233 * Balancing parameters are set up in arch_init_sched_domains.
2236 /* Don't have all balancing operations going off at once */
2237 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2239 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2240 enum idle_type idle)
2242 unsigned long old_load, this_load;
2243 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2244 struct sched_domain *sd;
2246 /* Update our load */
2247 old_load = this_rq->cpu_load;
2248 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
2250 * Round up the averaging division if load is increasing. This
2251 * prevents us from getting stuck on 9 if the load is 10, for
2254 if (this_load > old_load)
2256 this_rq->cpu_load = (old_load + this_load) / 2;
2258 for_each_domain(this_cpu, sd) {
2259 unsigned long interval;
2261 if (!(sd->flags & SD_LOAD_BALANCE))
2264 interval = sd->balance_interval;
2265 if (idle != SCHED_IDLE)
2266 interval *= sd->busy_factor;
2268 /* scale ms to jiffies */
2269 interval = msecs_to_jiffies(interval);
2270 if (unlikely(!interval))
2273 if (j - sd->last_balance >= interval) {
2274 if (load_balance(this_cpu, this_rq, sd, idle)) {
2275 /* We've pulled tasks over so no longer idle */
2278 sd->last_balance += interval;
2284 * on UP we do not need to balance between CPUs:
2286 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2289 static inline void idle_balance(int cpu, runqueue_t *rq)
2294 static inline int wake_priority_sleeper(runqueue_t *rq)
2297 #ifdef CONFIG_SCHED_SMT
2298 spin_lock(&rq->lock);
2300 * If an SMT sibling task has been put to sleep for priority
2301 * reasons reschedule the idle task to see if it can now run.
2303 if (rq->nr_running) {
2304 resched_task(rq->idle);
2307 spin_unlock(&rq->lock);
2312 DEFINE_PER_CPU(struct kernel_stat, kstat);
2314 EXPORT_PER_CPU_SYMBOL(kstat);
2317 * This is called on clock ticks and on context switches.
2318 * Bank in p->sched_time the ns elapsed since the last tick or switch.
2320 static inline void update_cpu_clock(task_t *p, runqueue_t *rq,
2321 unsigned long long now)
2323 unsigned long long last = max(p->timestamp, rq->timestamp_last_tick);
2324 p->sched_time += now - last;
2328 * Return current->sched_time plus any more ns on the sched_clock
2329 * that have not yet been banked.
2331 unsigned long long current_sched_time(const task_t *tsk)
2333 unsigned long long ns;
2334 unsigned long flags;
2335 local_irq_save(flags);
2336 ns = max(tsk->timestamp, task_rq(tsk)->timestamp_last_tick);
2337 ns = tsk->sched_time + (sched_clock() - ns);
2338 local_irq_restore(flags);
2343 * We place interactive tasks back into the active array, if possible.
2345 * To guarantee that this does not starve expired tasks we ignore the
2346 * interactivity of a task if the first expired task had to wait more
2347 * than a 'reasonable' amount of time. This deadline timeout is
2348 * load-dependent, as the frequency of array switched decreases with
2349 * increasing number of running tasks. We also ignore the interactivity
2350 * if a better static_prio task has expired:
2352 #define EXPIRED_STARVING(rq) \
2353 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2354 (jiffies - (rq)->expired_timestamp >= \
2355 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2356 ((rq)->curr->static_prio > (rq)->best_expired_prio))
2359 * Account user cpu time to a process.
2360 * @p: the process that the cpu time gets accounted to
2361 * @hardirq_offset: the offset to subtract from hardirq_count()
2362 * @cputime: the cpu time spent in user space since the last update
2364 void account_user_time(struct task_struct *p, cputime_t cputime)
2366 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2367 struct vx_info *vxi = p->vx_info; /* p is _always_ current */
2369 int nice = (TASK_NICE(p) > 0);
2371 p->utime = cputime_add(p->utime, cputime);
2372 vx_account_user(vxi, cputime, nice);
2374 /* Add user time to cpustat. */
2375 tmp = cputime_to_cputime64(cputime);
2377 cpustat->nice = cputime64_add(cpustat->nice, tmp);
2379 cpustat->user = cputime64_add(cpustat->user, tmp);
2383 * Account system cpu time to a process.
2384 * @p: the process that the cpu time gets accounted to
2385 * @hardirq_offset: the offset to subtract from hardirq_count()
2386 * @cputime: the cpu time spent in kernel space since the last update
2388 void account_system_time(struct task_struct *p, int hardirq_offset,
2391 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2392 struct vx_info *vxi = p->vx_info; /* p is _always_ current */
2393 runqueue_t *rq = this_rq();
2396 p->stime = cputime_add(p->stime, cputime);
2397 vx_account_system(vxi, cputime, (p == rq->idle));
2399 /* Add system time to cpustat. */
2400 tmp = cputime_to_cputime64(cputime);
2401 if (hardirq_count() - hardirq_offset)
2402 cpustat->irq = cputime64_add(cpustat->irq, tmp);
2403 else if (softirq_count())
2404 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
2405 else if (p != rq->idle)
2406 cpustat->system = cputime64_add(cpustat->system, tmp);
2407 else if (atomic_read(&rq->nr_iowait) > 0)
2408 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2410 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2411 /* Account for system time used */
2412 acct_update_integrals(p);
2413 /* Update rss highwater mark */
2414 update_mem_hiwater(p);
2418 * Account for involuntary wait time.
2419 * @p: the process from which the cpu time has been stolen
2420 * @steal: the cpu time spent in involuntary wait
2422 void account_steal_time(struct task_struct *p, cputime_t steal)
2424 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2425 cputime64_t tmp = cputime_to_cputime64(steal);
2426 runqueue_t *rq = this_rq();
2428 if (p == rq->idle) {
2429 p->stime = cputime_add(p->stime, steal);
2430 if (atomic_read(&rq->nr_iowait) > 0)
2431 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2433 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2435 cpustat->steal = cputime64_add(cpustat->steal, tmp);
2439 * This function gets called by the timer code, with HZ frequency.
2440 * We call it with interrupts disabled.
2442 * It also gets called by the fork code, when changing the parent's
2445 void scheduler_tick(void)
2447 int cpu = smp_processor_id();
2448 runqueue_t *rq = this_rq();
2449 task_t *p = current;
2450 unsigned long long now = sched_clock();
2452 update_cpu_clock(p, rq, now);
2454 rq->timestamp_last_tick = now;
2456 if (p == rq->idle) {
2457 if (wake_priority_sleeper(rq))
2459 #ifdef CONFIG_VSERVER_HARDCPU_IDLE
2460 if (!--rq->idle_tokens && !list_empty(&rq->hold_queue))
2463 rebalance_tick(cpu, rq, SCHED_IDLE);
2467 /* Task might have expired already, but not scheduled off yet */
2468 if (p->array != rq->active) {
2469 set_tsk_need_resched(p);
2472 spin_lock(&rq->lock);
2474 * The task was running during this tick - update the
2475 * time slice counter. Note: we do not update a thread's
2476 * priority until it either goes to sleep or uses up its
2477 * timeslice. This makes it possible for interactive tasks
2478 * to use up their timeslices at their highest priority levels.
2482 * RR tasks need a special form of timeslice management.
2483 * FIFO tasks have no timeslices.
2485 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2486 p->time_slice = task_timeslice(p);
2487 p->first_time_slice = 0;
2488 set_tsk_need_resched(p);
2490 /* put it at the end of the queue: */
2491 requeue_task(p, rq->active);
2495 if (vx_need_resched(p)) {
2496 dequeue_task(p, rq->active);
2497 set_tsk_need_resched(p);
2498 p->prio = effective_prio(p);
2499 p->time_slice = task_timeslice(p);
2500 p->first_time_slice = 0;
2502 if (!rq->expired_timestamp)
2503 rq->expired_timestamp = jiffies;
2504 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2505 enqueue_task(p, rq->expired);
2506 if (p->static_prio < rq->best_expired_prio)
2507 rq->best_expired_prio = p->static_prio;
2509 enqueue_task(p, rq->active);
2512 * Prevent a too long timeslice allowing a task to monopolize
2513 * the CPU. We do this by splitting up the timeslice into
2516 * Note: this does not mean the task's timeslices expire or
2517 * get lost in any way, they just might be preempted by
2518 * another task of equal priority. (one with higher
2519 * priority would have preempted this task already.) We
2520 * requeue this task to the end of the list on this priority
2521 * level, which is in essence a round-robin of tasks with
2524 * This only applies to tasks in the interactive
2525 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2527 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2528 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2529 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2530 (p->array == rq->active)) {
2532 requeue_task(p, rq->active);
2533 set_tsk_need_resched(p);
2537 spin_unlock(&rq->lock);
2539 rebalance_tick(cpu, rq, NOT_IDLE);
2542 #ifdef CONFIG_SCHED_SMT
2543 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2545 struct sched_domain *sd = this_rq->sd;
2546 cpumask_t sibling_map;
2549 if (!(sd->flags & SD_SHARE_CPUPOWER))
2553 * Unlock the current runqueue because we have to lock in
2554 * CPU order to avoid deadlocks. Caller knows that we might
2555 * unlock. We keep IRQs disabled.
2557 spin_unlock(&this_rq->lock);
2559 sibling_map = sd->span;
2561 for_each_cpu_mask(i, sibling_map)
2562 spin_lock(&cpu_rq(i)->lock);
2564 * We clear this CPU from the mask. This both simplifies the
2565 * inner loop and keps this_rq locked when we exit:
2567 cpu_clear(this_cpu, sibling_map);
2569 for_each_cpu_mask(i, sibling_map) {
2570 runqueue_t *smt_rq = cpu_rq(i);
2573 * If an SMT sibling task is sleeping due to priority
2574 * reasons wake it up now.
2576 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
2577 resched_task(smt_rq->idle);
2580 for_each_cpu_mask(i, sibling_map)
2581 spin_unlock(&cpu_rq(i)->lock);
2583 * We exit with this_cpu's rq still held and IRQs
2588 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2590 struct sched_domain *sd = this_rq->sd;
2591 cpumask_t sibling_map;
2592 prio_array_t *array;
2596 if (!(sd->flags & SD_SHARE_CPUPOWER))
2600 * The same locking rules and details apply as for
2601 * wake_sleeping_dependent():
2603 spin_unlock(&this_rq->lock);
2604 sibling_map = sd->span;
2605 for_each_cpu_mask(i, sibling_map)
2606 spin_lock(&cpu_rq(i)->lock);
2607 cpu_clear(this_cpu, sibling_map);
2610 * Establish next task to be run - it might have gone away because
2611 * we released the runqueue lock above:
2613 if (!this_rq->nr_running)
2615 array = this_rq->active;
2616 if (!array->nr_active)
2617 array = this_rq->expired;
2618 BUG_ON(!array->nr_active);
2620 p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
2623 for_each_cpu_mask(i, sibling_map) {
2624 runqueue_t *smt_rq = cpu_rq(i);
2625 task_t *smt_curr = smt_rq->curr;
2628 * If a user task with lower static priority than the
2629 * running task on the SMT sibling is trying to schedule,
2630 * delay it till there is proportionately less timeslice
2631 * left of the sibling task to prevent a lower priority
2632 * task from using an unfair proportion of the
2633 * physical cpu's resources. -ck
2635 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
2636 task_timeslice(p) || rt_task(smt_curr)) &&
2637 p->mm && smt_curr->mm && !rt_task(p))
2641 * Reschedule a lower priority task on the SMT sibling,
2642 * or wake it up if it has been put to sleep for priority
2645 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
2646 task_timeslice(smt_curr) || rt_task(p)) &&
2647 smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
2648 (smt_curr == smt_rq->idle && smt_rq->nr_running))
2649 resched_task(smt_curr);
2652 for_each_cpu_mask(i, sibling_map)
2653 spin_unlock(&cpu_rq(i)->lock);
2657 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2661 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2667 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
2669 void fastcall add_preempt_count(int val)
2674 BUG_ON(((int)preempt_count() < 0));
2675 preempt_count() += val;
2677 * Spinlock count overflowing soon?
2679 BUG_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
2681 EXPORT_SYMBOL(add_preempt_count);
2683 void fastcall sub_preempt_count(int val)
2688 BUG_ON(val > preempt_count());
2690 * Is the spinlock portion underflowing?
2692 BUG_ON((val < PREEMPT_MASK) && !(preempt_count() & PREEMPT_MASK));
2693 preempt_count() -= val;
2695 EXPORT_SYMBOL(sub_preempt_count);
2700 * schedule() is the main scheduler function.
2702 asmlinkage void __sched schedule(void)
2705 task_t *prev, *next;
2707 prio_array_t *array;
2708 struct list_head *queue;
2709 unsigned long long now;
2710 unsigned long run_time;
2711 struct vx_info *vxi;
2712 #ifdef CONFIG_VSERVER_HARDCPU
2718 * Test if we are atomic. Since do_exit() needs to call into
2719 * schedule() atomically, we ignore that path for now.
2720 * Otherwise, whine if we are scheduling when we should not be.
2722 if (likely(!current->exit_state)) {
2723 if (unlikely(in_atomic())) {
2724 printk(KERN_ERR "scheduling while atomic: "
2726 current->comm, preempt_count(), current->pid);
2730 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
2735 release_kernel_lock(prev);
2736 need_resched_nonpreemptible:
2740 * The idle thread is not allowed to schedule!
2741 * Remove this check after it has been exercised a bit.
2743 if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
2744 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
2748 schedstat_inc(rq, sched_cnt);
2749 now = sched_clock();
2750 if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
2751 run_time = now - prev->timestamp;
2752 if (unlikely((long long)(now - prev->timestamp) < 0))
2755 run_time = NS_MAX_SLEEP_AVG;
2758 * Tasks charged proportionately less run_time at high sleep_avg to
2759 * delay them losing their interactive status
2761 run_time /= (CURRENT_BONUS(prev) ? : 1);
2763 spin_lock_irq(&rq->lock);
2765 if (unlikely(prev->flags & PF_DEAD))
2766 prev->state = EXIT_DEAD;
2768 switch_count = &prev->nivcsw;
2769 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2770 switch_count = &prev->nvcsw;
2771 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2772 unlikely(signal_pending(prev))))
2773 prev->state = TASK_RUNNING;
2775 if (prev->state == TASK_UNINTERRUPTIBLE) {
2776 rq->nr_uninterruptible++;
2777 vx_uninterruptible_inc(prev);
2779 deactivate_task(prev, rq);
2783 #ifdef CONFIG_VSERVER_HARDCPU
2784 if (!list_empty(&rq->hold_queue)) {
2785 struct list_head *l, *n;
2789 list_for_each_safe(l, n, &rq->hold_queue) {
2790 next = list_entry(l, task_t, run_list);
2791 if (vxi == next->vx_info)
2794 vxi = next->vx_info;
2795 ret = vx_tokens_recalc(vxi);
2798 vx_unhold_task(vxi, next, rq);
2801 if ((ret < 0) && (maxidle < ret))
2805 rq->idle_tokens = -maxidle;
2810 cpu = smp_processor_id();
2811 if (unlikely(!rq->nr_running)) {
2813 idle_balance(cpu, rq);
2814 if (!rq->nr_running) {
2816 rq->expired_timestamp = 0;
2817 wake_sleeping_dependent(cpu, rq);
2819 * wake_sleeping_dependent() might have released
2820 * the runqueue, so break out if we got new
2823 if (!rq->nr_running)
2827 if (dependent_sleeper(cpu, rq)) {
2832 * dependent_sleeper() releases and reacquires the runqueue
2833 * lock, hence go into the idle loop if the rq went
2836 if (unlikely(!rq->nr_running))
2841 if (unlikely(!array->nr_active)) {
2843 * Switch the active and expired arrays.
2845 schedstat_inc(rq, sched_switch);
2846 rq->active = rq->expired;
2847 rq->expired = array;
2849 rq->expired_timestamp = 0;
2850 rq->best_expired_prio = MAX_PRIO;
2853 idx = sched_find_first_bit(array->bitmap);
2854 queue = array->queue + idx;
2855 next = list_entry(queue->next, task_t, run_list);
2857 vxi = next->vx_info;
2858 #ifdef CONFIG_VSERVER_HARDCPU
2859 if (vx_info_flags(vxi, VXF_SCHED_PAUSE|VXF_SCHED_HARD, 0)) {
2860 int ret = vx_tokens_recalc(vxi);
2862 if (unlikely(ret <= 0)) {
2863 if (ret && (rq->idle_tokens > -ret))
2864 rq->idle_tokens = -ret;
2865 vx_hold_task(vxi, next, rq);
2868 } else /* well, looks ugly but not as ugly as the ifdef-ed version */
2870 if (vx_info_flags(vxi, VXF_SCHED_PRIO, 0))
2871 vx_tokens_recalc(vxi);
2873 if (!rt_task(next) && next->activated > 0) {
2874 unsigned long long delta = now - next->timestamp;
2875 if (unlikely((long long)(now - next->timestamp) < 0))
2878 if (next->activated == 1)
2879 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
2881 array = next->array;
2882 dequeue_task(next, array);
2883 recalc_task_prio(next, next->timestamp + delta);
2884 enqueue_task(next, array);
2886 next->activated = 0;
2888 if (next == rq->idle)
2889 schedstat_inc(rq, sched_goidle);
2891 clear_tsk_need_resched(prev);
2892 rcu_qsctr_inc(task_cpu(prev));
2894 update_cpu_clock(prev, rq, now);
2896 prev->sleep_avg -= run_time;
2897 if ((long)prev->sleep_avg <= 0)
2898 prev->sleep_avg = 0;
2899 prev->timestamp = prev->last_ran = now;
2901 sched_info_switch(prev, next);
2902 if (likely(prev != next)) {
2903 next->timestamp = now;
2908 prepare_arch_switch(rq, next);
2909 prev = context_switch(rq, prev, next);
2912 finish_task_switch(prev);
2914 spin_unlock_irq(&rq->lock);
2917 if (unlikely(reacquire_kernel_lock(prev) < 0))
2918 goto need_resched_nonpreemptible;
2919 preempt_enable_no_resched();
2920 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2924 EXPORT_SYMBOL(schedule);
2926 #ifdef CONFIG_PREEMPT
2928 * this is is the entry point to schedule() from in-kernel preemption
2929 * off of preempt_enable. Kernel preemptions off return from interrupt
2930 * occur there and call schedule directly.
2932 asmlinkage void __sched preempt_schedule(void)
2934 struct thread_info *ti = current_thread_info();
2935 #ifdef CONFIG_PREEMPT_BKL
2936 struct task_struct *task = current;
2937 int saved_lock_depth;
2940 * If there is a non-zero preempt_count or interrupts are disabled,
2941 * we do not want to preempt the current task. Just return..
2943 if (unlikely(ti->preempt_count || irqs_disabled()))
2947 add_preempt_count(PREEMPT_ACTIVE);
2949 * We keep the big kernel semaphore locked, but we
2950 * clear ->lock_depth so that schedule() doesnt
2951 * auto-release the semaphore:
2953 #ifdef CONFIG_PREEMPT_BKL
2954 saved_lock_depth = task->lock_depth;
2955 task->lock_depth = -1;
2958 #ifdef CONFIG_PREEMPT_BKL
2959 task->lock_depth = saved_lock_depth;
2961 sub_preempt_count(PREEMPT_ACTIVE);
2963 /* we could miss a preemption opportunity between schedule and now */
2965 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2969 EXPORT_SYMBOL(preempt_schedule);
2972 * this is is the entry point to schedule() from kernel preemption
2973 * off of irq context.
2974 * Note, that this is called and return with irqs disabled. This will
2975 * protect us against recursive calling from irq.
2977 asmlinkage void __sched preempt_schedule_irq(void)
2979 struct thread_info *ti = current_thread_info();
2980 #ifdef CONFIG_PREEMPT_BKL
2981 struct task_struct *task = current;
2982 int saved_lock_depth;
2984 /* Catch callers which need to be fixed*/
2985 BUG_ON(ti->preempt_count || !irqs_disabled());
2988 add_preempt_count(PREEMPT_ACTIVE);
2990 * We keep the big kernel semaphore locked, but we
2991 * clear ->lock_depth so that schedule() doesnt
2992 * auto-release the semaphore:
2994 #ifdef CONFIG_PREEMPT_BKL
2995 saved_lock_depth = task->lock_depth;
2996 task->lock_depth = -1;
3000 local_irq_disable();
3001 #ifdef CONFIG_PREEMPT_BKL
3002 task->lock_depth = saved_lock_depth;
3004 sub_preempt_count(PREEMPT_ACTIVE);
3006 /* we could miss a preemption opportunity between schedule and now */
3008 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3012 #endif /* CONFIG_PREEMPT */
3014 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
3016 task_t *p = curr->task;
3017 return try_to_wake_up(p, mode, sync);
3020 EXPORT_SYMBOL(default_wake_function);
3023 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3024 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3025 * number) then we wake all the non-exclusive tasks and one exclusive task.
3027 * There are circumstances in which we can try to wake a task which has already
3028 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3029 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3031 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3032 int nr_exclusive, int sync, void *key)
3034 struct list_head *tmp, *next;
3036 list_for_each_safe(tmp, next, &q->task_list) {
3039 curr = list_entry(tmp, wait_queue_t, task_list);
3040 flags = curr->flags;
3041 if (curr->func(curr, mode, sync, key) &&
3042 (flags & WQ_FLAG_EXCLUSIVE) &&
3049 * __wake_up - wake up threads blocked on a waitqueue.
3051 * @mode: which threads
3052 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3053 * @key: is directly passed to the wakeup function
3055 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3056 int nr_exclusive, void *key)
3058 unsigned long flags;
3060 spin_lock_irqsave(&q->lock, flags);
3061 __wake_up_common(q, mode, nr_exclusive, 0, key);
3062 spin_unlock_irqrestore(&q->lock, flags);
3065 EXPORT_SYMBOL(__wake_up);
3068 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3070 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3072 __wake_up_common(q, mode, 1, 0, NULL);
3076 * __wake_up_sync - wake up threads blocked on a waitqueue.
3078 * @mode: which threads
3079 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3081 * The sync wakeup differs that the waker knows that it will schedule
3082 * away soon, so while the target thread will be woken up, it will not
3083 * be migrated to another CPU - ie. the two threads are 'synchronized'
3084 * with each other. This can prevent needless bouncing between CPUs.
3086 * On UP it can prevent extra preemption.
3088 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3090 unsigned long flags;
3096 if (unlikely(!nr_exclusive))
3099 spin_lock_irqsave(&q->lock, flags);
3100 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3101 spin_unlock_irqrestore(&q->lock, flags);
3103 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3105 void fastcall complete(struct completion *x)
3107 unsigned long flags;
3109 spin_lock_irqsave(&x->wait.lock, flags);
3111 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3113 spin_unlock_irqrestore(&x->wait.lock, flags);
3115 EXPORT_SYMBOL(complete);
3117 void fastcall complete_all(struct completion *x)
3119 unsigned long flags;
3121 spin_lock_irqsave(&x->wait.lock, flags);
3122 x->done += UINT_MAX/2;
3123 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3125 spin_unlock_irqrestore(&x->wait.lock, flags);
3127 EXPORT_SYMBOL(complete_all);
3129 void fastcall __sched wait_for_completion(struct completion *x)
3132 spin_lock_irq(&x->wait.lock);
3134 DECLARE_WAITQUEUE(wait, current);
3136 wait.flags |= WQ_FLAG_EXCLUSIVE;
3137 __add_wait_queue_tail(&x->wait, &wait);
3139 __set_current_state(TASK_UNINTERRUPTIBLE);
3140 spin_unlock_irq(&x->wait.lock);
3142 spin_lock_irq(&x->wait.lock);
3144 __remove_wait_queue(&x->wait, &wait);
3147 spin_unlock_irq(&x->wait.lock);
3149 EXPORT_SYMBOL(wait_for_completion);
3151 unsigned long fastcall __sched
3152 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3156 spin_lock_irq(&x->wait.lock);
3158 DECLARE_WAITQUEUE(wait, current);
3160 wait.flags |= WQ_FLAG_EXCLUSIVE;
3161 __add_wait_queue_tail(&x->wait, &wait);
3163 __set_current_state(TASK_UNINTERRUPTIBLE);
3164 spin_unlock_irq(&x->wait.lock);
3165 timeout = schedule_timeout(timeout);
3166 spin_lock_irq(&x->wait.lock);
3168 __remove_wait_queue(&x->wait, &wait);
3172 __remove_wait_queue(&x->wait, &wait);
3176 spin_unlock_irq(&x->wait.lock);
3179 EXPORT_SYMBOL(wait_for_completion_timeout);
3181 int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3187 spin_lock_irq(&x->wait.lock);
3189 DECLARE_WAITQUEUE(wait, current);
3191 wait.flags |= WQ_FLAG_EXCLUSIVE;
3192 __add_wait_queue_tail(&x->wait, &wait);
3194 if (signal_pending(current)) {
3196 __remove_wait_queue(&x->wait, &wait);
3199 __set_current_state(TASK_INTERRUPTIBLE);
3200 spin_unlock_irq(&x->wait.lock);
3202 spin_lock_irq(&x->wait.lock);
3204 __remove_wait_queue(&x->wait, &wait);
3208 spin_unlock_irq(&x->wait.lock);
3212 EXPORT_SYMBOL(wait_for_completion_interruptible);
3214 unsigned long fastcall __sched
3215 wait_for_completion_interruptible_timeout(struct completion *x,
3216 unsigned long timeout)
3220 spin_lock_irq(&x->wait.lock);
3222 DECLARE_WAITQUEUE(wait, current);
3224 wait.flags |= WQ_FLAG_EXCLUSIVE;
3225 __add_wait_queue_tail(&x->wait, &wait);
3227 if (signal_pending(current)) {
3228 timeout = -ERESTARTSYS;
3229 __remove_wait_queue(&x->wait, &wait);
3232 __set_current_state(TASK_INTERRUPTIBLE);
3233 spin_unlock_irq(&x->wait.lock);
3234 timeout = schedule_timeout(timeout);
3235 spin_lock_irq(&x->wait.lock);
3237 __remove_wait_queue(&x->wait, &wait);
3241 __remove_wait_queue(&x->wait, &wait);
3245 spin_unlock_irq(&x->wait.lock);
3248 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3251 #define SLEEP_ON_VAR \
3252 unsigned long flags; \
3253 wait_queue_t wait; \
3254 init_waitqueue_entry(&wait, current);
3256 #define SLEEP_ON_HEAD \
3257 spin_lock_irqsave(&q->lock,flags); \
3258 __add_wait_queue(q, &wait); \
3259 spin_unlock(&q->lock);
3261 #define SLEEP_ON_TAIL \
3262 spin_lock_irq(&q->lock); \
3263 __remove_wait_queue(q, &wait); \
3264 spin_unlock_irqrestore(&q->lock, flags);
3266 #define SLEEP_ON_BKLCHECK \
3267 if (unlikely(!kernel_locked()) && \
3268 sleep_on_bkl_warnings < 10) { \
3269 sleep_on_bkl_warnings++; \
3273 static int sleep_on_bkl_warnings;
3275 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3281 current->state = TASK_INTERRUPTIBLE;
3288 EXPORT_SYMBOL(interruptible_sleep_on);
3290 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3296 current->state = TASK_INTERRUPTIBLE;
3299 timeout = schedule_timeout(timeout);
3305 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3307 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3313 current->state = TASK_UNINTERRUPTIBLE;
3316 timeout = schedule_timeout(timeout);
3322 EXPORT_SYMBOL(sleep_on_timeout);
3324 void set_user_nice(task_t *p, long nice)
3326 unsigned long flags;
3327 prio_array_t *array;
3329 int old_prio, new_prio, delta;
3331 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3334 * We have to be careful, if called from sys_setpriority(),
3335 * the task might be in the middle of scheduling on another CPU.
3337 rq = task_rq_lock(p, &flags);
3339 * The RT priorities are set via sched_setscheduler(), but we still
3340 * allow the 'normal' nice value to be set - but as expected
3341 * it wont have any effect on scheduling until the task is
3345 p->static_prio = NICE_TO_PRIO(nice);
3350 dequeue_task(p, array);
3353 new_prio = NICE_TO_PRIO(nice);
3354 delta = new_prio - old_prio;
3355 p->static_prio = NICE_TO_PRIO(nice);
3359 enqueue_task(p, array);
3361 * If the task increased its priority or is running and
3362 * lowered its priority, then reschedule its CPU:
3364 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3365 resched_task(rq->curr);
3368 task_rq_unlock(rq, &flags);
3371 EXPORT_SYMBOL(set_user_nice);
3374 * can_nice - check if a task can reduce its nice value
3378 int can_nice(const task_t *p, const int nice)
3380 /* convert nice value [19,-20] to rlimit style value [0,39] */
3381 int nice_rlim = 19 - nice;
3382 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
3383 capable(CAP_SYS_NICE));
3386 #ifdef __ARCH_WANT_SYS_NICE
3389 * sys_nice - change the priority of the current process.
3390 * @increment: priority increment
3392 * sys_setpriority is a more generic, but much slower function that
3393 * does similar things.
3395 asmlinkage long sys_nice(int increment)
3401 * Setpriority might change our priority at the same moment.
3402 * We don't have to worry. Conceptually one call occurs first
3403 * and we have a single winner.
3405 if (increment < -40)
3410 nice = PRIO_TO_NICE(current->static_prio) + increment;
3416 if (increment < 0 && !can_nice(current, nice))
3417 return vx_flags(VXF_IGNEG_NICE, 0) ? 0 : -EPERM;
3419 retval = security_task_setnice(current, nice);
3423 set_user_nice(current, nice);
3430 * task_prio - return the priority value of a given task.
3431 * @p: the task in question.
3433 * This is the priority value as seen by users in /proc.
3434 * RT tasks are offset by -200. Normal tasks are centered
3435 * around 0, value goes from -16 to +15.
3437 int task_prio(const task_t *p)
3439 return p->prio - MAX_RT_PRIO;
3443 * task_nice - return the nice value of a given task.
3444 * @p: the task in question.
3446 int task_nice(const task_t *p)
3448 return TASK_NICE(p);
3452 * The only users of task_nice are binfmt_elf and binfmt_elf32.
3453 * binfmt_elf is no longer modular, but binfmt_elf32 still is.
3454 * Therefore, task_nice is needed if there is a compat_mode.
3456 #ifdef CONFIG_COMPAT
3457 EXPORT_SYMBOL_GPL(task_nice);
3461 * idle_cpu - is a given cpu idle currently?
3462 * @cpu: the processor in question.
3464 int idle_cpu(int cpu)
3466 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3469 EXPORT_SYMBOL_GPL(idle_cpu);
3472 * idle_task - return the idle task for a given cpu.
3473 * @cpu: the processor in question.
3475 task_t *idle_task(int cpu)
3477 return cpu_rq(cpu)->idle;
3481 * find_process_by_pid - find a process with a matching PID value.
3482 * @pid: the pid in question.
3484 static inline task_t *find_process_by_pid(pid_t pid)
3486 return pid ? find_task_by_pid(pid) : current;
3489 /* Actually do priority change: must hold rq lock. */
3490 static void __setscheduler(struct task_struct *p, int policy, int prio)
3494 p->rt_priority = prio;
3495 if (policy != SCHED_NORMAL)
3496 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
3498 p->prio = p->static_prio;
3502 * sched_setscheduler - change the scheduling policy and/or RT priority of
3504 * @p: the task in question.
3505 * @policy: new policy.
3506 * @param: structure containing the new RT priority.
3508 int sched_setscheduler(struct task_struct *p, int policy, struct sched_param *param)
3511 int oldprio, oldpolicy = -1;
3512 prio_array_t *array;
3513 unsigned long flags;
3517 /* double check policy once rq lock held */
3519 policy = oldpolicy = p->policy;
3520 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
3521 policy != SCHED_NORMAL)
3524 * Valid priorities for SCHED_FIFO and SCHED_RR are
3525 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
3527 if (param->sched_priority < 0 ||
3528 param->sched_priority > MAX_USER_RT_PRIO-1)
3530 if ((policy == SCHED_NORMAL) != (param->sched_priority == 0))
3533 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
3534 param->sched_priority > p->signal->rlim[RLIMIT_RTPRIO].rlim_cur &&
3535 !capable(CAP_SYS_NICE))
3537 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3538 !capable(CAP_SYS_NICE))
3541 retval = security_task_setscheduler(p, policy, param);
3545 * To be able to change p->policy safely, the apropriate
3546 * runqueue lock must be held.
3548 rq = task_rq_lock(p, &flags);
3549 /* recheck policy now with rq lock held */
3550 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3551 policy = oldpolicy = -1;
3552 task_rq_unlock(rq, &flags);
3557 deactivate_task(p, rq);
3559 __setscheduler(p, policy, param->sched_priority);
3561 vx_activate_task(p);
3562 __activate_task(p, rq);
3564 * Reschedule if we are currently running on this runqueue and
3565 * our priority decreased, or if we are not currently running on
3566 * this runqueue and our priority is higher than the current's
3568 if (task_running(rq, p)) {
3569 if (p->prio > oldprio)
3570 resched_task(rq->curr);
3571 } else if (TASK_PREEMPTS_CURR(p, rq))
3572 resched_task(rq->curr);
3574 task_rq_unlock(rq, &flags);
3577 EXPORT_SYMBOL_GPL(sched_setscheduler);
3579 static int do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3582 struct sched_param lparam;
3583 struct task_struct *p;
3585 if (!param || pid < 0)
3587 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
3589 read_lock_irq(&tasklist_lock);
3590 p = find_process_by_pid(pid);
3592 read_unlock_irq(&tasklist_lock);
3595 retval = sched_setscheduler(p, policy, &lparam);
3596 read_unlock_irq(&tasklist_lock);
3601 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3602 * @pid: the pid in question.
3603 * @policy: new policy.
3604 * @param: structure containing the new RT priority.
3606 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3607 struct sched_param __user *param)
3609 return do_sched_setscheduler(pid, policy, param);
3613 * sys_sched_setparam - set/change the RT priority of a thread
3614 * @pid: the pid in question.
3615 * @param: structure containing the new RT priority.
3617 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3619 return do_sched_setscheduler(pid, -1, param);
3623 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3624 * @pid: the pid in question.
3626 asmlinkage long sys_sched_getscheduler(pid_t pid)
3628 int retval = -EINVAL;
3635 read_lock(&tasklist_lock);
3636 p = find_process_by_pid(pid);
3638 retval = security_task_getscheduler(p);
3642 read_unlock(&tasklist_lock);
3649 * sys_sched_getscheduler - get the RT priority of a thread
3650 * @pid: the pid in question.
3651 * @param: structure containing the RT priority.
3653 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3655 struct sched_param lp;
3656 int retval = -EINVAL;
3659 if (!param || pid < 0)
3662 read_lock(&tasklist_lock);
3663 p = find_process_by_pid(pid);
3668 retval = security_task_getscheduler(p);
3672 lp.sched_priority = p->rt_priority;
3673 read_unlock(&tasklist_lock);
3676 * This one might sleep, we cannot do it with a spinlock held ...
3678 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3684 read_unlock(&tasklist_lock);
3688 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
3692 cpumask_t cpus_allowed;
3695 read_lock(&tasklist_lock);
3697 p = find_process_by_pid(pid);
3699 read_unlock(&tasklist_lock);
3700 unlock_cpu_hotplug();
3705 * It is not safe to call set_cpus_allowed with the
3706 * tasklist_lock held. We will bump the task_struct's
3707 * usage count and then drop tasklist_lock.
3710 read_unlock(&tasklist_lock);
3713 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3714 !capable(CAP_SYS_NICE))
3717 cpus_allowed = cpuset_cpus_allowed(p);
3718 cpus_and(new_mask, new_mask, cpus_allowed);
3719 retval = set_cpus_allowed(p, new_mask);
3723 unlock_cpu_hotplug();
3727 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
3728 cpumask_t *new_mask)
3730 if (len < sizeof(cpumask_t)) {
3731 memset(new_mask, 0, sizeof(cpumask_t));
3732 } else if (len > sizeof(cpumask_t)) {
3733 len = sizeof(cpumask_t);
3735 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
3739 * sys_sched_setaffinity - set the cpu affinity of a process
3740 * @pid: pid of the process
3741 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3742 * @user_mask_ptr: user-space pointer to the new cpu mask
3744 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
3745 unsigned long __user *user_mask_ptr)
3750 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
3754 return sched_setaffinity(pid, new_mask);
3758 * Represents all cpu's present in the system
3759 * In systems capable of hotplug, this map could dynamically grow
3760 * as new cpu's are detected in the system via any platform specific
3761 * method, such as ACPI for e.g.
3764 cpumask_t cpu_present_map;
3765 EXPORT_SYMBOL(cpu_present_map);
3768 cpumask_t cpu_online_map = CPU_MASK_ALL;
3769 cpumask_t cpu_possible_map = CPU_MASK_ALL;
3772 long sched_getaffinity(pid_t pid, cpumask_t *mask)
3778 read_lock(&tasklist_lock);
3781 p = find_process_by_pid(pid);
3786 cpus_and(*mask, p->cpus_allowed, cpu_possible_map);
3789 read_unlock(&tasklist_lock);
3790 unlock_cpu_hotplug();
3798 * sys_sched_getaffinity - get the cpu affinity of a process
3799 * @pid: pid of the process
3800 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3801 * @user_mask_ptr: user-space pointer to hold the current cpu mask
3803 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
3804 unsigned long __user *user_mask_ptr)
3809 if (len < sizeof(cpumask_t))
3812 ret = sched_getaffinity(pid, &mask);
3816 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
3819 return sizeof(cpumask_t);
3823 * sys_sched_yield - yield the current processor to other threads.
3825 * this function yields the current CPU by moving the calling thread
3826 * to the expired array. If there are no other threads running on this
3827 * CPU then this function will return.
3829 asmlinkage long sys_sched_yield(void)
3831 runqueue_t *rq = this_rq_lock();
3832 prio_array_t *array = current->array;
3833 prio_array_t *target = rq->expired;
3835 schedstat_inc(rq, yld_cnt);
3837 * We implement yielding by moving the task into the expired
3840 * (special rule: RT tasks will just roundrobin in the active
3843 if (rt_task(current))
3844 target = rq->active;
3846 if (current->array->nr_active == 1) {
3847 schedstat_inc(rq, yld_act_empty);
3848 if (!rq->expired->nr_active)
3849 schedstat_inc(rq, yld_both_empty);
3850 } else if (!rq->expired->nr_active)
3851 schedstat_inc(rq, yld_exp_empty);
3853 if (array != target) {
3854 dequeue_task(current, array);
3855 enqueue_task(current, target);
3858 * requeue_task is cheaper so perform that if possible.
3860 requeue_task(current, array);
3863 * Since we are going to call schedule() anyway, there's
3864 * no need to preempt or enable interrupts:
3866 __release(rq->lock);
3867 _raw_spin_unlock(&rq->lock);
3868 preempt_enable_no_resched();
3875 static inline void __cond_resched(void)
3878 add_preempt_count(PREEMPT_ACTIVE);
3880 sub_preempt_count(PREEMPT_ACTIVE);
3881 } while (need_resched());
3884 int __sched cond_resched(void)
3886 if (need_resched()) {
3893 EXPORT_SYMBOL(cond_resched);
3896 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
3897 * call schedule, and on return reacquire the lock.
3899 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
3900 * operations here to prevent schedule() from being called twice (once via
3901 * spin_unlock(), once by hand).
3903 int cond_resched_lock(spinlock_t * lock)
3907 if (need_lockbreak(lock)) {
3913 if (need_resched()) {
3914 _raw_spin_unlock(lock);
3915 preempt_enable_no_resched();
3923 EXPORT_SYMBOL(cond_resched_lock);
3925 int __sched cond_resched_softirq(void)
3927 BUG_ON(!in_softirq());
3929 if (need_resched()) {
3930 __local_bh_enable();
3938 EXPORT_SYMBOL(cond_resched_softirq);
3942 * yield - yield the current processor to other threads.
3944 * this is a shortcut for kernel-space yielding - it marks the
3945 * thread runnable and calls sys_sched_yield().
3947 void __sched yield(void)
3949 set_current_state(TASK_RUNNING);
3953 EXPORT_SYMBOL(yield);
3956 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
3957 * that process accounting knows that this is a task in IO wait state.
3959 * But don't do that if it is a deliberate, throttling IO wait (this task
3960 * has set its backing_dev_info: the queue against which it should throttle)
3962 void __sched io_schedule(void)
3964 struct runqueue *rq = &per_cpu(runqueues, _smp_processor_id());
3966 atomic_inc(&rq->nr_iowait);
3968 atomic_dec(&rq->nr_iowait);
3971 EXPORT_SYMBOL(io_schedule);
3973 long __sched io_schedule_timeout(long timeout)
3975 struct runqueue *rq = &per_cpu(runqueues, _smp_processor_id());
3978 atomic_inc(&rq->nr_iowait);
3979 ret = schedule_timeout(timeout);
3980 atomic_dec(&rq->nr_iowait);
3985 * sys_sched_get_priority_max - return maximum RT priority.
3986 * @policy: scheduling class.
3988 * this syscall returns the maximum rt_priority that can be used
3989 * by a given scheduling class.
3991 asmlinkage long sys_sched_get_priority_max(int policy)
3998 ret = MAX_USER_RT_PRIO-1;
4008 * sys_sched_get_priority_min - return minimum RT priority.
4009 * @policy: scheduling class.
4011 * this syscall returns the minimum rt_priority that can be used
4012 * by a given scheduling class.
4014 asmlinkage long sys_sched_get_priority_min(int policy)
4030 * sys_sched_rr_get_interval - return the default timeslice of a process.
4031 * @pid: pid of the process.
4032 * @interval: userspace pointer to the timeslice value.
4034 * this syscall writes the default timeslice value of a given process
4035 * into the user-space timespec buffer. A value of '0' means infinity.
4038 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4040 int retval = -EINVAL;
4048 read_lock(&tasklist_lock);
4049 p = find_process_by_pid(pid);
4053 retval = security_task_getscheduler(p);
4057 jiffies_to_timespec(p->policy & SCHED_FIFO ?
4058 0 : task_timeslice(p), &t);
4059 read_unlock(&tasklist_lock);
4060 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4064 read_unlock(&tasklist_lock);
4068 static inline struct task_struct *eldest_child(struct task_struct *p)
4070 if (list_empty(&p->children)) return NULL;
4071 return list_entry(p->children.next,struct task_struct,sibling);
4074 static inline struct task_struct *older_sibling(struct task_struct *p)
4076 if (p->sibling.prev==&p->parent->children) return NULL;
4077 return list_entry(p->sibling.prev,struct task_struct,sibling);
4080 static inline struct task_struct *younger_sibling(struct task_struct *p)
4082 if (p->sibling.next==&p->parent->children) return NULL;
4083 return list_entry(p->sibling.next,struct task_struct,sibling);
4086 static void show_task(task_t * p)
4090 unsigned long free = 0;
4091 static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
4093 printk("%-13.13s ", p->comm);
4094 state = p->state ? __ffs(p->state) + 1 : 0;
4095 if (state < ARRAY_SIZE(stat_nam))
4096 printk(stat_nam[state]);
4099 #if (BITS_PER_LONG == 32)
4100 if (state == TASK_RUNNING)
4101 printk(" running ");
4103 printk(" %08lX ", thread_saved_pc(p));
4105 if (state == TASK_RUNNING)
4106 printk(" running task ");
4108 printk(" %016lx ", thread_saved_pc(p));
4110 #ifdef CONFIG_DEBUG_STACK_USAGE
4112 unsigned long * n = (unsigned long *) (p->thread_info+1);
4115 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
4118 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
4119 if ((relative = eldest_child(p)))
4120 printk("%5d ", relative->pid);
4123 if ((relative = younger_sibling(p)))
4124 printk("%7d", relative->pid);
4127 if ((relative = older_sibling(p)))
4128 printk(" %5d", relative->pid);
4132 printk(" (L-TLB)\n");
4134 printk(" (NOTLB)\n");
4136 if (state != TASK_RUNNING)
4137 show_stack(p, NULL);
4140 void show_state(void)
4144 #if (BITS_PER_LONG == 32)
4147 printk(" task PC pid father child younger older\n");
4151 printk(" task PC pid father child younger older\n");
4153 read_lock(&tasklist_lock);
4154 do_each_thread(g, p) {
4156 * reset the NMI-timeout, listing all files on a slow
4157 * console might take alot of time:
4159 touch_nmi_watchdog();
4161 } while_each_thread(g, p);
4163 read_unlock(&tasklist_lock);
4166 EXPORT_SYMBOL_GPL(show_state);
4168 void __devinit init_idle(task_t *idle, int cpu)
4170 runqueue_t *rq = cpu_rq(cpu);
4171 unsigned long flags;
4173 idle->sleep_avg = 0;
4175 idle->prio = MAX_PRIO;
4176 idle->state = TASK_RUNNING;
4177 idle->cpus_allowed = cpumask_of_cpu(cpu);
4178 set_task_cpu(idle, cpu);
4180 spin_lock_irqsave(&rq->lock, flags);
4181 rq->curr = rq->idle = idle;
4182 set_tsk_need_resched(idle);
4183 spin_unlock_irqrestore(&rq->lock, flags);
4185 /* Set the preempt count _outside_ the spinlocks! */
4186 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4187 idle->thread_info->preempt_count = (idle->lock_depth >= 0);
4189 idle->thread_info->preempt_count = 0;
4194 * In a system that switches off the HZ timer nohz_cpu_mask
4195 * indicates which cpus entered this state. This is used
4196 * in the rcu update to wait only for active cpus. For system
4197 * which do not switch off the HZ timer nohz_cpu_mask should
4198 * always be CPU_MASK_NONE.
4200 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4204 * This is how migration works:
4206 * 1) we queue a migration_req_t structure in the source CPU's
4207 * runqueue and wake up that CPU's migration thread.
4208 * 2) we down() the locked semaphore => thread blocks.
4209 * 3) migration thread wakes up (implicitly it forces the migrated
4210 * thread off the CPU)
4211 * 4) it gets the migration request and checks whether the migrated
4212 * task is still in the wrong runqueue.
4213 * 5) if it's in the wrong runqueue then the migration thread removes
4214 * it and puts it into the right queue.
4215 * 6) migration thread up()s the semaphore.
4216 * 7) we wake up and the migration is done.
4220 * Change a given task's CPU affinity. Migrate the thread to a
4221 * proper CPU and schedule it away if the CPU it's executing on
4222 * is removed from the allowed bitmask.
4224 * NOTE: the caller must have a valid reference to the task, the
4225 * task must not exit() & deallocate itself prematurely. The
4226 * call is not atomic; no spinlocks may be held.
4228 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
4230 unsigned long flags;
4232 migration_req_t req;
4235 rq = task_rq_lock(p, &flags);
4236 if (!cpus_intersects(new_mask, cpu_online_map)) {
4241 p->cpus_allowed = new_mask;
4242 /* Can the task run on the task's current CPU? If so, we're done */
4243 if (cpu_isset(task_cpu(p), new_mask))
4246 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4247 /* Need help from migration thread: drop lock and wait. */
4248 task_rq_unlock(rq, &flags);
4249 wake_up_process(rq->migration_thread);
4250 wait_for_completion(&req.done);
4251 tlb_migrate_finish(p->mm);
4255 task_rq_unlock(rq, &flags);
4259 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4262 * Move (not current) task off this cpu, onto dest cpu. We're doing
4263 * this because either it can't run here any more (set_cpus_allowed()
4264 * away from this CPU, or CPU going down), or because we're
4265 * attempting to rebalance this task on exec (sched_exec).
4267 * So we race with normal scheduler movements, but that's OK, as long
4268 * as the task is no longer on this CPU.
4270 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4272 runqueue_t *rq_dest, *rq_src;
4274 if (unlikely(cpu_is_offline(dest_cpu)))
4277 rq_src = cpu_rq(src_cpu);
4278 rq_dest = cpu_rq(dest_cpu);
4280 double_rq_lock(rq_src, rq_dest);
4281 /* Already moved. */
4282 if (task_cpu(p) != src_cpu)
4284 /* Affinity changed (again). */
4285 if (!cpu_isset(dest_cpu, p->cpus_allowed))
4288 set_task_cpu(p, dest_cpu);
4291 * Sync timestamp with rq_dest's before activating.
4292 * The same thing could be achieved by doing this step
4293 * afterwards, and pretending it was a local activate.
4294 * This way is cleaner and logically correct.
4296 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4297 + rq_dest->timestamp_last_tick;
4298 deactivate_task(p, rq_src);
4299 activate_task(p, rq_dest, 0);
4300 if (TASK_PREEMPTS_CURR(p, rq_dest))
4301 resched_task(rq_dest->curr);
4305 double_rq_unlock(rq_src, rq_dest);
4309 * migration_thread - this is a highprio system thread that performs
4310 * thread migration by bumping thread off CPU then 'pushing' onto
4313 static int migration_thread(void * data)
4316 int cpu = (long)data;
4319 BUG_ON(rq->migration_thread != current);
4321 set_current_state(TASK_INTERRUPTIBLE);
4322 while (!kthread_should_stop()) {
4323 struct list_head *head;
4324 migration_req_t *req;
4326 if (current->flags & PF_FREEZE)
4327 refrigerator(PF_FREEZE);
4329 spin_lock_irq(&rq->lock);
4331 if (cpu_is_offline(cpu)) {
4332 spin_unlock_irq(&rq->lock);
4336 if (rq->active_balance) {
4337 active_load_balance(rq, cpu);
4338 rq->active_balance = 0;
4341 head = &rq->migration_queue;
4343 if (list_empty(head)) {
4344 spin_unlock_irq(&rq->lock);
4346 set_current_state(TASK_INTERRUPTIBLE);
4349 req = list_entry(head->next, migration_req_t, list);
4350 list_del_init(head->next);
4352 if (req->type == REQ_MOVE_TASK) {
4353 spin_unlock(&rq->lock);
4354 __migrate_task(req->task, cpu, req->dest_cpu);
4356 } else if (req->type == REQ_SET_DOMAIN) {
4358 spin_unlock_irq(&rq->lock);
4360 spin_unlock_irq(&rq->lock);
4364 complete(&req->done);
4366 __set_current_state(TASK_RUNNING);
4370 /* Wait for kthread_stop */
4371 set_current_state(TASK_INTERRUPTIBLE);
4372 while (!kthread_should_stop()) {
4374 set_current_state(TASK_INTERRUPTIBLE);
4376 __set_current_state(TASK_RUNNING);
4380 #ifdef CONFIG_HOTPLUG_CPU
4381 /* Figure out where task on dead CPU should go, use force if neccessary. */
4382 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
4388 mask = node_to_cpumask(cpu_to_node(dead_cpu));
4389 cpus_and(mask, mask, tsk->cpus_allowed);
4390 dest_cpu = any_online_cpu(mask);
4392 /* On any allowed CPU? */
4393 if (dest_cpu == NR_CPUS)
4394 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4396 /* No more Mr. Nice Guy. */
4397 if (dest_cpu == NR_CPUS) {
4398 cpus_setall(tsk->cpus_allowed);
4399 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4402 * Don't tell them about moving exiting tasks or
4403 * kernel threads (both mm NULL), since they never
4406 if (tsk->mm && printk_ratelimit())
4407 printk(KERN_INFO "process %d (%s) no "
4408 "longer affine to cpu%d\n",
4409 tsk->pid, tsk->comm, dead_cpu);
4411 __migrate_task(tsk, dead_cpu, dest_cpu);
4415 * While a dead CPU has no uninterruptible tasks queued at this point,
4416 * it might still have a nonzero ->nr_uninterruptible counter, because
4417 * for performance reasons the counter is not stricly tracking tasks to
4418 * their home CPUs. So we just add the counter to another CPU's counter,
4419 * to keep the global sum constant after CPU-down:
4421 static void migrate_nr_uninterruptible(runqueue_t *rq_src)
4423 runqueue_t *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
4424 unsigned long flags;
4426 local_irq_save(flags);
4427 double_rq_lock(rq_src, rq_dest);
4428 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
4429 rq_src->nr_uninterruptible = 0;
4430 double_rq_unlock(rq_src, rq_dest);
4431 local_irq_restore(flags);
4434 /* Run through task list and migrate tasks from the dead cpu. */
4435 static void migrate_live_tasks(int src_cpu)
4437 struct task_struct *tsk, *t;
4439 write_lock_irq(&tasklist_lock);
4441 do_each_thread(t, tsk) {
4445 if (task_cpu(tsk) == src_cpu)
4446 move_task_off_dead_cpu(src_cpu, tsk);
4447 } while_each_thread(t, tsk);
4449 write_unlock_irq(&tasklist_lock);
4452 /* Schedules idle task to be the next runnable task on current CPU.
4453 * It does so by boosting its priority to highest possible and adding it to
4454 * the _front_ of runqueue. Used by CPU offline code.
4456 void sched_idle_next(void)
4458 int cpu = smp_processor_id();
4459 runqueue_t *rq = this_rq();
4460 struct task_struct *p = rq->idle;
4461 unsigned long flags;
4463 /* cpu has to be offline */
4464 BUG_ON(cpu_online(cpu));
4466 /* Strictly not necessary since rest of the CPUs are stopped by now
4467 * and interrupts disabled on current cpu.
4469 spin_lock_irqsave(&rq->lock, flags);
4471 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4472 /* Add idle task to _front_ of it's priority queue */
4473 __activate_idle_task(p, rq);
4475 spin_unlock_irqrestore(&rq->lock, flags);
4478 /* Ensures that the idle task is using init_mm right before its cpu goes
4481 void idle_task_exit(void)
4483 struct mm_struct *mm = current->active_mm;
4485 BUG_ON(cpu_online(smp_processor_id()));
4488 switch_mm(mm, &init_mm, current);
4492 static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
4494 struct runqueue *rq = cpu_rq(dead_cpu);
4496 /* Must be exiting, otherwise would be on tasklist. */
4497 BUG_ON(tsk->exit_state != EXIT_ZOMBIE && tsk->exit_state != EXIT_DEAD);
4499 /* Cannot have done final schedule yet: would have vanished. */
4500 BUG_ON(tsk->flags & PF_DEAD);
4502 get_task_struct(tsk);
4505 * Drop lock around migration; if someone else moves it,
4506 * that's OK. No task can be added to this CPU, so iteration is
4509 spin_unlock_irq(&rq->lock);
4510 move_task_off_dead_cpu(dead_cpu, tsk);
4511 spin_lock_irq(&rq->lock);
4513 put_task_struct(tsk);
4516 /* release_task() removes task from tasklist, so we won't find dead tasks. */
4517 static void migrate_dead_tasks(unsigned int dead_cpu)
4520 struct runqueue *rq = cpu_rq(dead_cpu);
4522 for (arr = 0; arr < 2; arr++) {
4523 for (i = 0; i < MAX_PRIO; i++) {
4524 struct list_head *list = &rq->arrays[arr].queue[i];
4525 while (!list_empty(list))
4526 migrate_dead(dead_cpu,
4527 list_entry(list->next, task_t,
4532 #endif /* CONFIG_HOTPLUG_CPU */
4535 * migration_call - callback that gets triggered when a CPU is added.
4536 * Here we can start up the necessary migration thread for the new CPU.
4538 static int migration_call(struct notifier_block *nfb, unsigned long action,
4541 int cpu = (long)hcpu;
4542 struct task_struct *p;
4543 struct runqueue *rq;
4544 unsigned long flags;
4547 case CPU_UP_PREPARE:
4548 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4551 p->flags |= PF_NOFREEZE;
4552 kthread_bind(p, cpu);
4553 /* Must be high prio: stop_machine expects to yield to it. */
4554 rq = task_rq_lock(p, &flags);
4555 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4556 task_rq_unlock(rq, &flags);
4557 cpu_rq(cpu)->migration_thread = p;
4560 /* Strictly unneccessary, as first user will wake it. */
4561 wake_up_process(cpu_rq(cpu)->migration_thread);
4563 #ifdef CONFIG_HOTPLUG_CPU
4564 case CPU_UP_CANCELED:
4565 /* Unbind it from offline cpu so it can run. Fall thru. */
4566 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
4567 kthread_stop(cpu_rq(cpu)->migration_thread);
4568 cpu_rq(cpu)->migration_thread = NULL;
4571 migrate_live_tasks(cpu);
4573 kthread_stop(rq->migration_thread);
4574 rq->migration_thread = NULL;
4575 /* Idle task back to normal (off runqueue, low prio) */
4576 rq = task_rq_lock(rq->idle, &flags);
4577 deactivate_task(rq->idle, rq);
4578 rq->idle->static_prio = MAX_PRIO;
4579 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4580 migrate_dead_tasks(cpu);
4581 task_rq_unlock(rq, &flags);
4582 migrate_nr_uninterruptible(rq);
4583 BUG_ON(rq->nr_running != 0);
4585 /* No need to migrate the tasks: it was best-effort if
4586 * they didn't do lock_cpu_hotplug(). Just wake up
4587 * the requestors. */
4588 spin_lock_irq(&rq->lock);
4589 while (!list_empty(&rq->migration_queue)) {
4590 migration_req_t *req;
4591 req = list_entry(rq->migration_queue.next,
4592 migration_req_t, list);
4593 BUG_ON(req->type != REQ_MOVE_TASK);
4594 list_del_init(&req->list);
4595 complete(&req->done);
4597 spin_unlock_irq(&rq->lock);
4604 /* Register at highest priority so that task migration (migrate_all_tasks)
4605 * happens before everything else.
4607 static struct notifier_block __devinitdata migration_notifier = {
4608 .notifier_call = migration_call,
4612 int __init migration_init(void)
4614 void *cpu = (void *)(long)smp_processor_id();
4615 /* Start one for boot CPU. */
4616 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4617 migration_call(&migration_notifier, CPU_ONLINE, cpu);
4618 register_cpu_notifier(&migration_notifier);
4624 #define SCHED_DOMAIN_DEBUG
4625 #ifdef SCHED_DOMAIN_DEBUG
4626 static void sched_domain_debug(struct sched_domain *sd, int cpu)
4630 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
4635 struct sched_group *group = sd->groups;
4636 cpumask_t groupmask;
4638 cpumask_scnprintf(str, NR_CPUS, sd->span);
4639 cpus_clear(groupmask);
4642 for (i = 0; i < level + 1; i++)
4644 printk("domain %d: ", level);
4646 if (!(sd->flags & SD_LOAD_BALANCE)) {
4647 printk("does not load-balance\n");
4649 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
4653 printk("span %s\n", str);
4655 if (!cpu_isset(cpu, sd->span))
4656 printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
4657 if (!cpu_isset(cpu, group->cpumask))
4658 printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
4661 for (i = 0; i < level + 2; i++)
4667 printk(KERN_ERR "ERROR: group is NULL\n");
4671 if (!group->cpu_power) {
4673 printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
4676 if (!cpus_weight(group->cpumask)) {
4678 printk(KERN_ERR "ERROR: empty group\n");
4681 if (cpus_intersects(groupmask, group->cpumask)) {
4683 printk(KERN_ERR "ERROR: repeated CPUs\n");
4686 cpus_or(groupmask, groupmask, group->cpumask);
4688 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
4691 group = group->next;
4692 } while (group != sd->groups);
4695 if (!cpus_equal(sd->span, groupmask))
4696 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
4702 if (!cpus_subset(groupmask, sd->span))
4703 printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
4709 #define sched_domain_debug(sd, cpu) {}
4713 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
4714 * hold the hotplug lock.
4716 void __devinit cpu_attach_domain(struct sched_domain *sd, int cpu)
4718 migration_req_t req;
4719 unsigned long flags;
4720 runqueue_t *rq = cpu_rq(cpu);
4723 sched_domain_debug(sd, cpu);
4725 spin_lock_irqsave(&rq->lock, flags);
4727 if (cpu == smp_processor_id() || !cpu_online(cpu)) {
4730 init_completion(&req.done);
4731 req.type = REQ_SET_DOMAIN;
4733 list_add(&req.list, &rq->migration_queue);
4737 spin_unlock_irqrestore(&rq->lock, flags);
4740 wake_up_process(rq->migration_thread);
4741 wait_for_completion(&req.done);
4745 /* cpus with isolated domains */
4746 cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
4748 /* Setup the mask of cpus configured for isolated domains */
4749 static int __init isolated_cpu_setup(char *str)
4751 int ints[NR_CPUS], i;
4753 str = get_options(str, ARRAY_SIZE(ints), ints);
4754 cpus_clear(cpu_isolated_map);
4755 for (i = 1; i <= ints[0]; i++)
4756 if (ints[i] < NR_CPUS)
4757 cpu_set(ints[i], cpu_isolated_map);
4761 __setup ("isolcpus=", isolated_cpu_setup);
4764 * init_sched_build_groups takes an array of groups, the cpumask we wish
4765 * to span, and a pointer to a function which identifies what group a CPU
4766 * belongs to. The return value of group_fn must be a valid index into the
4767 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
4768 * keep track of groups covered with a cpumask_t).
4770 * init_sched_build_groups will build a circular linked list of the groups
4771 * covered by the given span, and will set each group's ->cpumask correctly,
4772 * and ->cpu_power to 0.
4774 void __devinit init_sched_build_groups(struct sched_group groups[],
4775 cpumask_t span, int (*group_fn)(int cpu))
4777 struct sched_group *first = NULL, *last = NULL;
4778 cpumask_t covered = CPU_MASK_NONE;
4781 for_each_cpu_mask(i, span) {
4782 int group = group_fn(i);
4783 struct sched_group *sg = &groups[group];
4786 if (cpu_isset(i, covered))
4789 sg->cpumask = CPU_MASK_NONE;
4792 for_each_cpu_mask(j, span) {
4793 if (group_fn(j) != group)
4796 cpu_set(j, covered);
4797 cpu_set(j, sg->cpumask);
4809 #ifdef ARCH_HAS_SCHED_DOMAIN
4810 extern void __devinit arch_init_sched_domains(void);
4811 extern void __devinit arch_destroy_sched_domains(void);
4813 #ifdef CONFIG_SCHED_SMT
4814 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
4815 static struct sched_group sched_group_cpus[NR_CPUS];
4816 static int __devinit cpu_to_cpu_group(int cpu)
4822 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
4823 static struct sched_group sched_group_phys[NR_CPUS];
4824 static int __devinit cpu_to_phys_group(int cpu)
4826 #ifdef CONFIG_SCHED_SMT
4827 return first_cpu(cpu_sibling_map[cpu]);
4835 static DEFINE_PER_CPU(struct sched_domain, node_domains);
4836 static struct sched_group sched_group_nodes[MAX_NUMNODES];
4837 static int __devinit cpu_to_node_group(int cpu)
4839 return cpu_to_node(cpu);
4843 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
4845 * The domains setup code relies on siblings not spanning
4846 * multiple nodes. Make sure the architecture has a proper
4849 static void check_sibling_maps(void)
4853 for_each_online_cpu(i) {
4854 for_each_cpu_mask(j, cpu_sibling_map[i]) {
4855 if (cpu_to_node(i) != cpu_to_node(j)) {
4856 printk(KERN_INFO "warning: CPU %d siblings map "
4857 "to different node - isolating "
4859 cpu_sibling_map[i] = cpumask_of_cpu(i);
4868 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
4870 static void __devinit arch_init_sched_domains(void)
4873 cpumask_t cpu_default_map;
4875 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
4876 check_sibling_maps();
4879 * Setup mask for cpus without special case scheduling requirements.
4880 * For now this just excludes isolated cpus, but could be used to
4881 * exclude other special cases in the future.
4883 cpus_complement(cpu_default_map, cpu_isolated_map);
4884 cpus_and(cpu_default_map, cpu_default_map, cpu_online_map);
4887 * Set up domains. Isolated domains just stay on the dummy domain.
4889 for_each_cpu_mask(i, cpu_default_map) {
4891 struct sched_domain *sd = NULL, *p;
4892 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
4894 cpus_and(nodemask, nodemask, cpu_default_map);
4897 sd = &per_cpu(node_domains, i);
4898 group = cpu_to_node_group(i);
4900 sd->span = cpu_default_map;
4901 sd->groups = &sched_group_nodes[group];
4905 sd = &per_cpu(phys_domains, i);
4906 group = cpu_to_phys_group(i);
4908 sd->span = nodemask;
4910 sd->groups = &sched_group_phys[group];
4912 #ifdef CONFIG_SCHED_SMT
4914 sd = &per_cpu(cpu_domains, i);
4915 group = cpu_to_cpu_group(i);
4916 *sd = SD_SIBLING_INIT;
4917 sd->span = cpu_sibling_map[i];
4918 cpus_and(sd->span, sd->span, cpu_default_map);
4920 sd->groups = &sched_group_cpus[group];
4924 #ifdef CONFIG_SCHED_SMT
4925 /* Set up CPU (sibling) groups */
4926 for_each_online_cpu(i) {
4927 cpumask_t this_sibling_map = cpu_sibling_map[i];
4928 cpus_and(this_sibling_map, this_sibling_map, cpu_default_map);
4929 if (i != first_cpu(this_sibling_map))
4932 init_sched_build_groups(sched_group_cpus, this_sibling_map,
4937 /* Set up physical groups */
4938 for (i = 0; i < MAX_NUMNODES; i++) {
4939 cpumask_t nodemask = node_to_cpumask(i);
4941 cpus_and(nodemask, nodemask, cpu_default_map);
4942 if (cpus_empty(nodemask))
4945 init_sched_build_groups(sched_group_phys, nodemask,
4946 &cpu_to_phys_group);
4950 /* Set up node groups */
4951 init_sched_build_groups(sched_group_nodes, cpu_default_map,
4952 &cpu_to_node_group);
4955 /* Calculate CPU power for physical packages and nodes */
4956 for_each_cpu_mask(i, cpu_default_map) {
4958 struct sched_domain *sd;
4959 #ifdef CONFIG_SCHED_SMT
4960 sd = &per_cpu(cpu_domains, i);
4961 power = SCHED_LOAD_SCALE;
4962 sd->groups->cpu_power = power;
4965 sd = &per_cpu(phys_domains, i);
4966 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
4967 (cpus_weight(sd->groups->cpumask)-1) / 10;
4968 sd->groups->cpu_power = power;
4971 if (i == first_cpu(sd->groups->cpumask)) {
4972 /* Only add "power" once for each physical package. */
4973 sd = &per_cpu(node_domains, i);
4974 sd->groups->cpu_power += power;
4979 /* Attach the domains */
4980 for_each_online_cpu(i) {
4981 struct sched_domain *sd;
4982 #ifdef CONFIG_SCHED_SMT
4983 sd = &per_cpu(cpu_domains, i);
4985 sd = &per_cpu(phys_domains, i);
4987 cpu_attach_domain(sd, i);
4991 #ifdef CONFIG_HOTPLUG_CPU
4992 static void __devinit arch_destroy_sched_domains(void)
4994 /* Do nothing: everything is statically allocated. */
4998 #endif /* ARCH_HAS_SCHED_DOMAIN */
5001 * Initial dummy domain for early boot and for hotplug cpu. Being static,
5002 * it is initialized to zero, so all balancing flags are cleared which is
5005 static struct sched_domain sched_domain_dummy;
5007 #ifdef CONFIG_HOTPLUG_CPU
5009 * Force a reinitialization of the sched domains hierarchy. The domains
5010 * and groups cannot be updated in place without racing with the balancing
5011 * code, so we temporarily attach all running cpus to a "dummy" domain
5012 * which will prevent rebalancing while the sched domains are recalculated.
5014 static int update_sched_domains(struct notifier_block *nfb,
5015 unsigned long action, void *hcpu)
5020 case CPU_UP_PREPARE:
5021 case CPU_DOWN_PREPARE:
5022 for_each_online_cpu(i)
5023 cpu_attach_domain(&sched_domain_dummy, i);
5024 arch_destroy_sched_domains();
5027 case CPU_UP_CANCELED:
5028 case CPU_DOWN_FAILED:
5032 * Fall through and re-initialise the domains.
5039 /* The hotplug lock is already held by cpu_up/cpu_down */
5040 arch_init_sched_domains();
5046 void __init sched_init_smp(void)
5049 arch_init_sched_domains();
5050 unlock_cpu_hotplug();
5051 /* XXX: Theoretical race here - CPU may be hotplugged now */
5052 hotcpu_notifier(update_sched_domains, 0);
5055 void __init sched_init_smp(void)
5058 #endif /* CONFIG_SMP */
5060 int in_sched_functions(unsigned long addr)
5062 /* Linker adds these: start and end of __sched functions */
5063 extern char __sched_text_start[], __sched_text_end[];
5064 return in_lock_functions(addr) ||
5065 (addr >= (unsigned long)__sched_text_start
5066 && addr < (unsigned long)__sched_text_end);
5069 void __init sched_init(void)
5074 for (i = 0; i < NR_CPUS; i++) {
5075 prio_array_t *array;
5078 spin_lock_init(&rq->lock);
5079 rq->active = rq->arrays;
5080 rq->expired = rq->arrays + 1;
5081 rq->best_expired_prio = MAX_PRIO;
5084 rq->sd = &sched_domain_dummy;
5086 rq->active_balance = 0;
5088 rq->migration_thread = NULL;
5089 INIT_LIST_HEAD(&rq->migration_queue);
5091 #ifdef CONFIG_VSERVER_HARDCPU
5092 INIT_LIST_HEAD(&rq->hold_queue);
5094 atomic_set(&rq->nr_iowait, 0);
5095 #ifdef CONFIG_VSERVER_HARDCPU
5096 INIT_LIST_HEAD(&rq->hold_queue);
5099 for (j = 0; j < 2; j++) {
5100 array = rq->arrays + j;
5101 for (k = 0; k < MAX_PRIO; k++) {
5102 INIT_LIST_HEAD(array->queue + k);
5103 __clear_bit(k, array->bitmap);
5105 // delimiter for bitsearch
5106 __set_bit(MAX_PRIO, array->bitmap);
5111 * The boot idle thread does lazy MMU switching as well:
5113 atomic_inc(&init_mm.mm_count);
5114 enter_lazy_tlb(&init_mm, current);
5117 * Make us the idle thread. Technically, schedule() should not be
5118 * called from this thread, however somewhere below it might be,
5119 * but because we are the idle thread, we just pick up running again
5120 * when this runqueue becomes "idle".
5122 init_idle(current, smp_processor_id());
5125 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5126 void __might_sleep(char *file, int line)
5128 #if defined(in_atomic)
5129 static unsigned long prev_jiffy; /* ratelimiting */
5131 if ((in_atomic() || irqs_disabled()) &&
5132 system_state == SYSTEM_RUNNING && !oops_in_progress) {
5133 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
5135 prev_jiffy = jiffies;
5136 printk(KERN_ERR "Debug: sleeping function called from invalid"
5137 " context at %s:%d\n", file, line);
5138 printk("in_atomic():%d, irqs_disabled():%d\n",
5139 in_atomic(), irqs_disabled());
5144 EXPORT_SYMBOL(__might_sleep);
5147 #ifdef CONFIG_MAGIC_SYSRQ
5148 void normalize_rt_tasks(void)
5150 struct task_struct *p;
5151 prio_array_t *array;
5152 unsigned long flags;
5155 read_lock_irq(&tasklist_lock);
5156 for_each_process (p) {
5160 rq = task_rq_lock(p, &flags);
5164 deactivate_task(p, task_rq(p));
5165 __setscheduler(p, SCHED_NORMAL, 0);
5167 vx_activate_task(p);
5168 __activate_task(p, task_rq(p));
5169 resched_task(rq->curr);
5172 task_rq_unlock(rq, &flags);
5174 read_unlock_irq(&tasklist_lock);
5177 #endif /* CONFIG_MAGIC_SYSRQ */