4 * Kernel scheduler and related syscalls
6 * Copyright (C) 1991-2002 Linus Torvalds
8 * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and
9 * make semaphores SMP safe
10 * 1998-11-19 Implemented schedule_timeout() and related stuff
12 * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar:
13 * hybrid priority-list and round-robin design with
14 * an array-switch method of distributing timeslices
15 * and per-CPU runqueues. Cleanups and useful suggestions
16 * by Davide Libenzi, preemptible kernel bits by Robert Love.
17 * 2003-09-03 Interactivity tuning by Con Kolivas.
18 * 2004-04-02 Scheduler domains code by Nick Piggin
22 #include <linux/module.h>
23 #include <linux/nmi.h>
24 #include <linux/init.h>
25 #include <asm/uaccess.h>
26 #include <linux/highmem.h>
27 #include <linux/smp_lock.h>
28 #include <asm/mmu_context.h>
29 #include <linux/interrupt.h>
30 #include <linux/completion.h>
31 #include <linux/kernel_stat.h>
32 #include <linux/security.h>
33 #include <linux/notifier.h>
34 #include <linux/profile.h>
35 #include <linux/suspend.h>
36 #include <linux/blkdev.h>
37 #include <linux/delay.h>
38 #include <linux/smp.h>
39 #include <linux/threads.h>
40 #include <linux/timer.h>
41 #include <linux/rcupdate.h>
42 #include <linux/cpu.h>
43 #include <linux/percpu.h>
44 #include <linux/kthread.h>
45 #include <linux/seq_file.h>
46 #include <linux/syscalls.h>
47 #include <linux/times.h>
50 #include <asm/unistd.h>
51 #include <linux/vs_context.h>
52 #include <linux/vs_cvirt.h>
53 #include <linux/vs_sched.h>
56 * Convert user-nice values [ -20 ... 0 ... 19 ]
57 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
60 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
61 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
62 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
65 * 'User priority' is the nice value converted to something we
66 * can work with better when scaling various scheduler parameters,
67 * it's a [ 0 ... 39 ] range.
69 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
70 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
71 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
74 * Some helpers for converting nanosecond timing to jiffy resolution
76 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
77 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
80 * These are the 'tuning knobs' of the scheduler:
82 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
83 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
84 * Timeslices get refilled after they expire.
86 #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
87 #define DEF_TIMESLICE (100 * HZ / 1000)
88 #define ON_RUNQUEUE_WEIGHT 30
89 #define CHILD_PENALTY 95
90 #define PARENT_PENALTY 100
92 #define PRIO_BONUS_RATIO 25
93 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
94 #define INTERACTIVE_DELTA 2
95 #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
96 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
97 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
100 * If a task is 'interactive' then we reinsert it in the active
101 * array after it has expired its current timeslice. (it will not
102 * continue to run immediately, it will still roundrobin with
103 * other interactive tasks.)
105 * This part scales the interactivity limit depending on niceness.
107 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
108 * Here are a few examples of different nice levels:
110 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
111 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
112 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
113 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
114 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
116 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
117 * priority range a task can explore, a value of '1' means the
118 * task is rated interactive.)
120 * Ie. nice +19 tasks can never get 'interactive' enough to be
121 * reinserted into the active array. And only heavily CPU-hog nice -20
122 * tasks will be expired. Default nice 0 tasks are somewhere between,
123 * it takes some effort for them to get interactive, but it's not
127 #define CURRENT_BONUS(p) \
128 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
131 #define GRANULARITY (10 * HZ / 1000 ? : 1)
134 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
135 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
138 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
139 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
142 #define SCALE(v1,v1_max,v2_max) \
143 (v1) * (v2_max) / (v1_max)
146 (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
148 #define TASK_INTERACTIVE(p) \
149 ((p)->prio <= (p)->static_prio - DELTA(p))
151 #define INTERACTIVE_SLEEP(p) \
152 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
153 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
155 #define TASK_PREEMPTS_CURR(p, rq) \
156 ((p)->prio < (rq)->curr->prio)
159 * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
160 * to time slice values: [800ms ... 100ms ... 5ms]
162 * The higher a thread's priority, the bigger timeslices
163 * it gets during one round of execution. But even the lowest
164 * priority thread gets MIN_TIMESLICE worth of execution time.
167 #define SCALE_PRIO(x, prio) \
168 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO/2), MIN_TIMESLICE)
170 static unsigned int task_timeslice(task_t *p)
172 if (p->static_prio < NICE_TO_PRIO(0))
173 return SCALE_PRIO(DEF_TIMESLICE*4, p->static_prio);
175 return SCALE_PRIO(DEF_TIMESLICE, p->static_prio);
177 #define task_hot(p, now, sd) ((long long) ((now) - (p)->last_ran) \
178 < (long long) (sd)->cache_hot_time)
181 * These are the runqueue data structures:
184 #define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
186 typedef struct runqueue runqueue_t;
189 unsigned int nr_active;
190 unsigned long bitmap[BITMAP_SIZE];
191 struct list_head queue[MAX_PRIO];
195 * This is the main, per-CPU runqueue data structure.
197 * Locking rule: those places that want to lock multiple runqueues
198 * (such as the load balancing or the thread migration code), lock
199 * acquire operations must be ordered by ascending &runqueue.
205 * nr_running and cpu_load should be in the same cacheline because
206 * remote CPUs use both these fields when doing load calculation.
208 unsigned long nr_running;
210 unsigned long cpu_load;
212 unsigned long long nr_switches;
215 * This is part of a global counter where only the total sum
216 * over all CPUs matters. A task can increase this counter on
217 * one CPU and if it got migrated afterwards it may decrease
218 * it on another CPU. Always updated under the runqueue lock:
220 unsigned long nr_uninterruptible;
222 unsigned long expired_timestamp;
223 unsigned long long timestamp_last_tick;
225 struct mm_struct *prev_mm;
226 prio_array_t *active, *expired, arrays[2];
227 int best_expired_prio;
231 struct sched_domain *sd;
233 /* For active balancing */
237 task_t *migration_thread;
238 struct list_head migration_queue;
240 #ifdef CONFIG_VSERVER_HARDCPU
241 struct list_head hold_queue;
245 #ifdef CONFIG_SCHEDSTATS
247 struct sched_info rq_sched_info;
249 /* sys_sched_yield() stats */
250 unsigned long yld_exp_empty;
251 unsigned long yld_act_empty;
252 unsigned long yld_both_empty;
253 unsigned long yld_cnt;
255 /* schedule() stats */
256 unsigned long sched_noswitch;
257 unsigned long sched_switch;
258 unsigned long sched_cnt;
259 unsigned long sched_goidle;
261 /* pull_task() stats */
262 unsigned long pt_gained[MAX_IDLE_TYPES];
263 unsigned long pt_lost[MAX_IDLE_TYPES];
265 /* active_load_balance() stats */
266 unsigned long alb_cnt;
267 unsigned long alb_lost;
268 unsigned long alb_gained;
269 unsigned long alb_failed;
271 /* try_to_wake_up() stats */
272 unsigned long ttwu_cnt;
273 unsigned long ttwu_attempts;
274 unsigned long ttwu_moved;
276 /* wake_up_new_task() stats */
277 unsigned long wunt_cnt;
278 unsigned long wunt_moved;
280 /* sched_migrate_task() stats */
281 unsigned long smt_cnt;
283 /* sched_balance_exec() stats */
284 unsigned long sbe_cnt;
288 static DEFINE_PER_CPU(struct runqueue, runqueues);
290 #define for_each_domain(cpu, domain) \
291 for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
293 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
294 #define this_rq() (&__get_cpu_var(runqueues))
295 #define task_rq(p) cpu_rq(task_cpu(p))
296 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
299 * Default context-switch locking:
301 #ifndef prepare_arch_switch
302 # define prepare_arch_switch(rq, next) do { } while (0)
303 # define finish_arch_switch(rq, next) spin_unlock_irq(&(rq)->lock)
304 # define task_running(rq, p) ((rq)->curr == (p))
308 * task_rq_lock - lock the runqueue a given task resides on and disable
309 * interrupts. Note the ordering: we can safely lookup the task_rq without
310 * explicitly disabling preemption.
312 static runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
318 local_irq_save(*flags);
320 spin_lock(&rq->lock);
321 if (unlikely(rq != task_rq(p))) {
322 spin_unlock_irqrestore(&rq->lock, *flags);
323 goto repeat_lock_task;
328 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
331 spin_unlock_irqrestore(&rq->lock, *flags);
334 #ifdef CONFIG_SCHEDSTATS
336 * bump this up when changing the output format or the meaning of an existing
337 * format, so that tools can adapt (or abort)
339 #define SCHEDSTAT_VERSION 10
341 static int show_schedstat(struct seq_file *seq, void *v)
344 enum idle_type itype;
346 seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
347 seq_printf(seq, "timestamp %lu\n", jiffies);
348 for_each_online_cpu(cpu) {
349 runqueue_t *rq = cpu_rq(cpu);
351 struct sched_domain *sd;
355 /* runqueue-specific stats */
357 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu "
358 "%lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
359 cpu, rq->yld_both_empty,
360 rq->yld_act_empty, rq->yld_exp_empty,
361 rq->yld_cnt, rq->sched_noswitch,
362 rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
363 rq->alb_cnt, rq->alb_gained, rq->alb_lost,
365 rq->ttwu_cnt, rq->ttwu_moved, rq->ttwu_attempts,
366 rq->wunt_cnt, rq->wunt_moved,
367 rq->smt_cnt, rq->sbe_cnt, rq->rq_sched_info.cpu_time,
368 rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
370 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES; itype++)
371 seq_printf(seq, " %lu %lu", rq->pt_gained[itype],
373 seq_printf(seq, "\n");
376 /* domain-specific stats */
377 for_each_domain(cpu, sd) {
378 char mask_str[NR_CPUS];
380 cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
381 seq_printf(seq, "domain%d %s", dcnt++, mask_str);
382 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
384 seq_printf(seq, " %lu %lu %lu %lu %lu",
386 sd->lb_failed[itype],
387 sd->lb_imbalance[itype],
388 sd->lb_nobusyq[itype],
389 sd->lb_nobusyg[itype]);
391 seq_printf(seq, " %lu %lu %lu %lu\n",
392 sd->sbe_pushed, sd->sbe_attempts,
393 sd->ttwu_wake_affine, sd->ttwu_wake_balance);
400 static int schedstat_open(struct inode *inode, struct file *file)
402 unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
403 char *buf = kmalloc(size, GFP_KERNEL);
409 res = single_open(file, show_schedstat, NULL);
411 m = file->private_data;
419 struct file_operations proc_schedstat_operations = {
420 .open = schedstat_open,
423 .release = single_release,
426 # define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
427 # define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
428 #else /* !CONFIG_SCHEDSTATS */
429 # define schedstat_inc(rq, field) do { } while (0)
430 # define schedstat_add(rq, field, amt) do { } while (0)
434 * rq_lock - lock a given runqueue and disable interrupts.
436 static runqueue_t *this_rq_lock(void)
443 spin_lock(&rq->lock);
448 #ifdef CONFIG_SCHED_SMT
449 static int cpu_and_siblings_are_idle(int cpu)
452 for_each_cpu_mask(sib, cpu_sibling_map[cpu]) {
461 #define cpu_and_siblings_are_idle(A) idle_cpu(A)
464 #ifdef CONFIG_SCHEDSTATS
466 * Called when a process is dequeued from the active array and given
467 * the cpu. We should note that with the exception of interactive
468 * tasks, the expired queue will become the active queue after the active
469 * queue is empty, without explicitly dequeuing and requeuing tasks in the
470 * expired queue. (Interactive tasks may be requeued directly to the
471 * active queue, thus delaying tasks in the expired queue from running;
472 * see scheduler_tick()).
474 * This function is only called from sched_info_arrive(), rather than
475 * dequeue_task(). Even though a task may be queued and dequeued multiple
476 * times as it is shuffled about, we're really interested in knowing how
477 * long it was from the *first* time it was queued to the time that it
480 static inline void sched_info_dequeued(task_t *t)
482 t->sched_info.last_queued = 0;
486 * Called when a task finally hits the cpu. We can now calculate how
487 * long it was waiting to run. We also note when it began so that we
488 * can keep stats on how long its timeslice is.
490 static inline void sched_info_arrive(task_t *t)
492 unsigned long now = jiffies, diff = 0;
493 struct runqueue *rq = task_rq(t);
495 if (t->sched_info.last_queued)
496 diff = now - t->sched_info.last_queued;
497 sched_info_dequeued(t);
498 t->sched_info.run_delay += diff;
499 t->sched_info.last_arrival = now;
500 t->sched_info.pcnt++;
505 rq->rq_sched_info.run_delay += diff;
506 rq->rq_sched_info.pcnt++;
510 * Called when a process is queued into either the active or expired
511 * array. The time is noted and later used to determine how long we
512 * had to wait for us to reach the cpu. Since the expired queue will
513 * become the active queue after active queue is empty, without dequeuing
514 * and requeuing any tasks, we are interested in queuing to either. It
515 * is unusual but not impossible for tasks to be dequeued and immediately
516 * requeued in the same or another array: this can happen in sched_yield(),
517 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
520 * This function is only called from enqueue_task(), but also only updates
521 * the timestamp if it is already not set. It's assumed that
522 * sched_info_dequeued() will clear that stamp when appropriate.
524 static inline void sched_info_queued(task_t *t)
526 if (!t->sched_info.last_queued)
527 t->sched_info.last_queued = jiffies;
531 * Called when a process ceases being the active-running process, either
532 * voluntarily or involuntarily. Now we can calculate how long we ran.
534 static inline void sched_info_depart(task_t *t)
536 struct runqueue *rq = task_rq(t);
537 unsigned long diff = jiffies - t->sched_info.last_arrival;
539 t->sched_info.cpu_time += diff;
542 rq->rq_sched_info.cpu_time += diff;
546 * Called when tasks are switched involuntarily due, typically, to expiring
547 * their time slice. (This may also be called when switching to or from
548 * the idle task.) We are only called when prev != next.
550 static inline void sched_info_switch(task_t *prev, task_t *next)
552 struct runqueue *rq = task_rq(prev);
555 * prev now departs the cpu. It's not interesting to record
556 * stats about how efficient we were at scheduling the idle
559 if (prev != rq->idle)
560 sched_info_depart(prev);
562 if (next != rq->idle)
563 sched_info_arrive(next);
566 #define sched_info_queued(t) do { } while (0)
567 #define sched_info_switch(t, next) do { } while (0)
568 #endif /* CONFIG_SCHEDSTATS */
571 * Adding/removing a task to/from a priority array:
573 static void dequeue_task(struct task_struct *p, prio_array_t *array)
575 BUG_ON(p->state & TASK_ONHOLD);
577 list_del(&p->run_list);
578 if (list_empty(array->queue + p->prio))
579 __clear_bit(p->prio, array->bitmap);
582 static void enqueue_task(struct task_struct *p, prio_array_t *array)
584 BUG_ON(p->state & TASK_ONHOLD);
585 sched_info_queued(p);
586 list_add_tail(&p->run_list, array->queue + p->prio);
587 __set_bit(p->prio, array->bitmap);
593 * Put task to the end of the run list without the overhead of dequeue
594 * followed by enqueue.
596 static void requeue_task(struct task_struct *p, prio_array_t *array)
598 BUG_ON(p->state & TASK_ONHOLD);
599 list_move_tail(&p->run_list, array->queue + p->prio);
602 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
604 BUG_ON(p->state & TASK_ONHOLD);
605 list_add(&p->run_list, array->queue + p->prio);
606 __set_bit(p->prio, array->bitmap);
612 * effective_prio - return the priority that is based on the static
613 * priority but is modified by bonuses/penalties.
615 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
616 * into the -5 ... 0 ... +5 bonus/penalty range.
618 * We use 25% of the full 0...39 priority range so that:
620 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
621 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
623 * Both properties are important to certain workloads.
625 static int effective_prio(task_t *p)
633 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
635 prio = p->static_prio - bonus;
637 if ((vxi = p->vx_info) &&
638 vx_info_flags(vxi, VXF_SCHED_PRIO, 0))
639 prio += vx_effective_vavavoom(vxi, MAX_USER_PRIO);
641 if (prio < MAX_RT_PRIO)
643 if (prio > MAX_PRIO-1)
649 * __activate_task - move a task to the runqueue.
651 static inline void __activate_task(task_t *p, runqueue_t *rq)
653 enqueue_task(p, rq->active);
658 * __activate_idle_task - move idle task to the _front_ of runqueue.
660 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
662 enqueue_task_head(p, rq->active);
666 static void recalc_task_prio(task_t *p, unsigned long long now)
668 unsigned long long __sleep_time = now - p->timestamp;
669 unsigned long sleep_time;
671 if (__sleep_time > NS_MAX_SLEEP_AVG)
672 sleep_time = NS_MAX_SLEEP_AVG;
674 sleep_time = (unsigned long)__sleep_time;
676 if (likely(sleep_time > 0)) {
678 * User tasks that sleep a long time are categorised as
679 * idle and will get just interactive status to stay active &
680 * prevent them suddenly becoming cpu hogs and starving
683 if (p->mm && p->activated != -1 &&
684 sleep_time > INTERACTIVE_SLEEP(p)) {
685 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
689 * The lower the sleep avg a task has the more
690 * rapidly it will rise with sleep time.
692 sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
695 * Tasks waking from uninterruptible sleep are
696 * limited in their sleep_avg rise as they
697 * are likely to be waiting on I/O
699 if (p->activated == -1 && p->mm) {
700 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
702 else if (p->sleep_avg + sleep_time >=
703 INTERACTIVE_SLEEP(p)) {
704 p->sleep_avg = INTERACTIVE_SLEEP(p);
710 * This code gives a bonus to interactive tasks.
712 * The boost works by updating the 'average sleep time'
713 * value here, based on ->timestamp. The more time a
714 * task spends sleeping, the higher the average gets -
715 * and the higher the priority boost gets as well.
717 p->sleep_avg += sleep_time;
719 if (p->sleep_avg > NS_MAX_SLEEP_AVG)
720 p->sleep_avg = NS_MAX_SLEEP_AVG;
724 p->prio = effective_prio(p);
728 * activate_task - move a task to the runqueue and do priority recalculation
730 * Update all the scheduling statistics stuff. (sleep average
731 * calculation, priority modifiers, etc.)
733 static void activate_task(task_t *p, runqueue_t *rq, int local)
735 unsigned long long now;
740 /* Compensate for drifting sched_clock */
741 runqueue_t *this_rq = this_rq();
742 now = (now - this_rq->timestamp_last_tick)
743 + rq->timestamp_last_tick;
747 recalc_task_prio(p, now);
750 * This checks to make sure it's not an uninterruptible task
751 * that is now waking up.
755 * Tasks which were woken up by interrupts (ie. hw events)
756 * are most likely of interactive nature. So we give them
757 * the credit of extending their sleep time to the period
758 * of time they spend on the runqueue, waiting for execution
759 * on a CPU, first time around:
765 * Normal first-time wakeups get a credit too for
766 * on-runqueue time, but it will be weighted down:
774 __activate_task(p, rq);
778 * deactivate_task - remove a task from the runqueue.
780 static void __deactivate_task(struct task_struct *p, runqueue_t *rq)
783 dequeue_task(p, p->array);
788 void deactivate_task(struct task_struct *p, runqueue_t *rq)
790 vx_deactivate_task(p);
791 __deactivate_task(p, rq);
795 #ifdef CONFIG_VSERVER_HARDCPU
797 * vx_hold_task - put a task on the hold queue
800 void vx_hold_task(struct vx_info *vxi,
801 struct task_struct *p, runqueue_t *rq)
803 __deactivate_task(p, rq);
804 p->state |= TASK_ONHOLD;
805 // recalc_task_prio(p, now);
808 list_add_tail(&p->run_list, &rq->hold_queue);
810 //printk("··· %8lu hold %p [%d]\n", jiffies, p, p->prio);
814 * vx_unhold_task - put a task back to the runqueue
817 void vx_unhold_task(struct vx_info *vxi,
818 struct task_struct *p, runqueue_t *rq)
820 list_del(&p->run_list);
823 // p->prio = MAX_PRIO-1;
825 // recalc_task_prio(p, now);
826 p->state &= ~TASK_ONHOLD;
827 enqueue_task(p, rq->expired);
830 if (p->static_prio < rq->best_expired_prio)
831 rq->best_expired_prio = p->static_prio;
833 // printk("··· %8lu unhold %p [%d]\n", jiffies, p, p->prio);
837 void vx_hold_task(struct vx_info *vxi,
838 struct task_struct *p, runqueue_t *rq)
844 void vx_unhold_task(struct vx_info *vxi,
845 struct task_struct *p, runqueue_t *rq)
849 #endif /* CONFIG_VSERVER_HARDCPU */
853 * resched_task - mark a task 'to be rescheduled now'.
855 * On UP this means the setting of the need_resched flag, on SMP it
856 * might also involve a cross-CPU call to trigger the scheduler on
860 static void resched_task(task_t *p)
862 int need_resched, nrpolling;
864 assert_spin_locked(&task_rq(p)->lock);
866 /* minimise the chance of sending an interrupt to poll_idle() */
867 nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
868 need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
869 nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
871 if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
872 smp_send_reschedule(task_cpu(p));
875 static inline void resched_task(task_t *p)
877 set_tsk_need_resched(p);
882 * task_curr - is this task currently executing on a CPU?
883 * @p: the task in question.
885 inline int task_curr(const task_t *p)
887 return cpu_curr(task_cpu(p)) == p;
897 struct list_head list;
898 enum request_type type;
900 /* For REQ_MOVE_TASK */
904 /* For REQ_SET_DOMAIN */
905 struct sched_domain *sd;
907 struct completion done;
911 * The task's runqueue lock must be held.
912 * Returns true if you have to wait for migration thread.
914 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
916 runqueue_t *rq = task_rq(p);
919 * If the task is not on a runqueue (and not running), then
920 * it is sufficient to simply update the task's cpu field.
922 if (!p->array && !task_running(rq, p)) {
923 set_task_cpu(p, dest_cpu);
927 init_completion(&req->done);
928 req->type = REQ_MOVE_TASK;
930 req->dest_cpu = dest_cpu;
931 list_add(&req->list, &rq->migration_queue);
936 * wait_task_inactive - wait for a thread to unschedule.
938 * The caller must ensure that the task *will* unschedule sometime soon,
939 * else this function might spin for a *long* time. This function can't
940 * be called with interrupts off, or it may introduce deadlock with
941 * smp_call_function() if an IPI is sent by the same process we are
942 * waiting to become inactive.
944 void wait_task_inactive(task_t * p)
951 rq = task_rq_lock(p, &flags);
952 /* Must be off runqueue entirely, not preempted. */
953 if (unlikely(p->array || task_running(rq, p))) {
954 /* If it's preempted, we yield. It could be a while. */
955 preempted = !task_running(rq, p);
956 task_rq_unlock(rq, &flags);
962 task_rq_unlock(rq, &flags);
966 * kick_process - kick a running thread to enter/exit the kernel
967 * @p: the to-be-kicked thread
969 * Cause a process which is running on another CPU to enter
970 * kernel-mode, without any delay. (to get signals handled.)
972 * NOTE: this function doesnt have to take the runqueue lock,
973 * because all it wants to ensure is that the remote task enters
974 * the kernel. If the IPI races and the task has been migrated
975 * to another CPU then no harm is done and the purpose has been
978 void kick_process(task_t *p)
984 if ((cpu != smp_processor_id()) && task_curr(p))
985 smp_send_reschedule(cpu);
990 * Return a low guess at the load of a migration-source cpu.
992 * We want to under-estimate the load of migration sources, to
993 * balance conservatively.
995 static inline unsigned long source_load(int cpu)
997 runqueue_t *rq = cpu_rq(cpu);
998 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
1000 return min(rq->cpu_load, load_now);
1004 * Return a high guess at the load of a migration-target cpu
1006 static inline unsigned long target_load(int cpu)
1008 runqueue_t *rq = cpu_rq(cpu);
1009 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
1011 return max(rq->cpu_load, load_now);
1017 * wake_idle() will wake a task on an idle cpu if task->cpu is
1018 * not idle and an idle cpu is available. The span of cpus to
1019 * search starts with cpus closest then further out as needed,
1020 * so we always favor a closer, idle cpu.
1022 * Returns the CPU we should wake onto.
1024 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1025 static int wake_idle(int cpu, task_t *p)
1028 struct sched_domain *sd;
1034 for_each_domain(cpu, sd) {
1035 if (sd->flags & SD_WAKE_IDLE) {
1036 cpus_and(tmp, sd->span, cpu_online_map);
1037 cpus_and(tmp, tmp, p->cpus_allowed);
1038 for_each_cpu_mask(i, tmp) {
1048 static inline int wake_idle(int cpu, task_t *p)
1055 * try_to_wake_up - wake up a thread
1056 * @p: the to-be-woken-up thread
1057 * @state: the mask of task states that can be woken
1058 * @sync: do a synchronous wakeup?
1060 * Put it on the run-queue if it's not already there. The "current"
1061 * thread is always on the run-queue (except when the actual
1062 * re-schedule is in progress), and as such you're allowed to do
1063 * the simpler "current->state = TASK_RUNNING" to mark yourself
1064 * runnable without the overhead of this.
1066 * returns failure only if the task is already active.
1068 static int try_to_wake_up(task_t * p, unsigned int state, int sync)
1070 int cpu, this_cpu, success = 0;
1071 unsigned long flags;
1075 unsigned long load, this_load;
1076 struct sched_domain *sd;
1080 rq = task_rq_lock(p, &flags);
1081 schedstat_inc(rq, ttwu_cnt);
1082 old_state = p->state;
1084 /* we need to unhold suspended tasks */
1085 if (old_state & TASK_ONHOLD) {
1086 vx_unhold_task(p->vx_info, p, rq);
1087 old_state = p->state;
1089 if (!(old_state & state))
1096 this_cpu = smp_processor_id();
1099 if (unlikely(task_running(rq, p)))
1104 if (cpu == this_cpu || unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1107 load = source_load(cpu);
1108 this_load = target_load(this_cpu);
1111 * If sync wakeup then subtract the (maximum possible) effect of
1112 * the currently running task from the load of the current CPU:
1115 this_load -= SCHED_LOAD_SCALE;
1117 /* Don't pull the task off an idle CPU to a busy one */
1118 if (load < SCHED_LOAD_SCALE/2 && this_load > SCHED_LOAD_SCALE/2)
1121 new_cpu = this_cpu; /* Wake to this CPU if we can */
1124 * Scan domains for affine wakeup and passive balancing
1127 for_each_domain(this_cpu, sd) {
1128 unsigned int imbalance;
1130 * Start passive balancing when half the imbalance_pct
1133 imbalance = sd->imbalance_pct + (sd->imbalance_pct - 100) / 2;
1135 if ((sd->flags & SD_WAKE_AFFINE) &&
1136 !task_hot(p, rq->timestamp_last_tick, sd)) {
1138 * This domain has SD_WAKE_AFFINE and p is cache cold
1141 if (cpu_isset(cpu, sd->span)) {
1142 schedstat_inc(sd, ttwu_wake_affine);
1145 } else if ((sd->flags & SD_WAKE_BALANCE) &&
1146 imbalance*this_load <= 100*load) {
1148 * This domain has SD_WAKE_BALANCE and there is
1151 if (cpu_isset(cpu, sd->span)) {
1152 schedstat_inc(sd, ttwu_wake_balance);
1158 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1160 schedstat_inc(rq, ttwu_attempts);
1161 new_cpu = wake_idle(new_cpu, p);
1162 if (new_cpu != cpu) {
1163 schedstat_inc(rq, ttwu_moved);
1164 set_task_cpu(p, new_cpu);
1165 task_rq_unlock(rq, &flags);
1166 /* might preempt at this point */
1167 rq = task_rq_lock(p, &flags);
1168 old_state = p->state;
1169 if (!(old_state & state))
1174 this_cpu = smp_processor_id();
1179 #endif /* CONFIG_SMP */
1180 if (old_state == TASK_UNINTERRUPTIBLE) {
1181 rq->nr_uninterruptible--;
1183 * Tasks on involuntary sleep don't earn
1184 * sleep_avg beyond just interactive state.
1190 * Sync wakeups (i.e. those types of wakeups where the waker
1191 * has indicated that it will leave the CPU in short order)
1192 * don't trigger a preemption, if the woken up task will run on
1193 * this cpu. (in this case the 'I will reschedule' promise of
1194 * the waker guarantees that the freshly woken up task is going
1195 * to be considered on this CPU.)
1197 activate_task(p, rq, cpu == this_cpu);
1198 /* this is to get the accounting behind the load update */
1199 if (old_state == TASK_UNINTERRUPTIBLE)
1200 vx_uninterruptible_dec(p);
1201 if (!sync || cpu != this_cpu) {
1202 if (TASK_PREEMPTS_CURR(p, rq))
1203 resched_task(rq->curr);
1208 p->state = TASK_RUNNING;
1210 task_rq_unlock(rq, &flags);
1215 int fastcall wake_up_process(task_t * p)
1217 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1218 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1221 EXPORT_SYMBOL(wake_up_process);
1223 int fastcall wake_up_state(task_t *p, unsigned int state)
1225 return try_to_wake_up(p, state, 0);
1229 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1230 struct sched_domain *sd);
1234 * Perform scheduler related setup for a newly forked process p.
1235 * p is forked by current.
1237 void fastcall sched_fork(task_t *p)
1240 * We mark the process as running here, but have not actually
1241 * inserted it onto the runqueue yet. This guarantees that
1242 * nobody will actually run it, and a signal or other external
1243 * event cannot wake it up and insert it on the runqueue either.
1245 p->state = TASK_RUNNING;
1246 INIT_LIST_HEAD(&p->run_list);
1248 spin_lock_init(&p->switch_lock);
1249 #ifdef CONFIG_SCHEDSTATS
1250 memset(&p->sched_info, 0, sizeof(p->sched_info));
1252 #ifdef CONFIG_PREEMPT
1254 * During context-switch we hold precisely one spinlock, which
1255 * schedule_tail drops. (in the common case it's this_rq()->lock,
1256 * but it also can be p->switch_lock.) So we compensate with a count
1257 * of 1. Also, we want to start with kernel preemption disabled.
1259 p->thread_info->preempt_count = 1;
1262 * Share the timeslice between parent and child, thus the
1263 * total amount of pending timeslices in the system doesn't change,
1264 * resulting in more scheduling fairness.
1266 local_irq_disable();
1267 p->time_slice = (current->time_slice + 1) >> 1;
1269 * The remainder of the first timeslice might be recovered by
1270 * the parent if the child exits early enough.
1272 p->first_time_slice = 1;
1273 current->time_slice >>= 1;
1274 p->timestamp = sched_clock();
1275 if (unlikely(!current->time_slice)) {
1277 * This case is rare, it happens when the parent has only
1278 * a single jiffy left from its timeslice. Taking the
1279 * runqueue lock is not a problem.
1281 current->time_slice = 1;
1291 * wake_up_new_task - wake up a newly created task for the first time.
1293 * This function will do some initial scheduler statistics housekeeping
1294 * that must be done for every newly created context, then puts the task
1295 * on the runqueue and wakes it.
1297 void fastcall wake_up_new_task(task_t * p, unsigned long clone_flags)
1299 unsigned long flags;
1301 runqueue_t *rq, *this_rq;
1303 rq = task_rq_lock(p, &flags);
1305 this_cpu = smp_processor_id();
1307 BUG_ON(p->state != TASK_RUNNING);
1309 schedstat_inc(rq, wunt_cnt);
1311 * We decrease the sleep average of forking parents
1312 * and children as well, to keep max-interactive tasks
1313 * from forking tasks that are max-interactive. The parent
1314 * (current) is done further down, under its lock.
1316 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1317 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1319 p->prio = effective_prio(p);
1321 vx_activate_task(p);
1322 if (likely(cpu == this_cpu)) {
1323 if (!(clone_flags & CLONE_VM)) {
1325 * The VM isn't cloned, so we're in a good position to
1326 * do child-runs-first in anticipation of an exec. This
1327 * usually avoids a lot of COW overhead.
1329 if (unlikely(!current->array))
1330 __activate_task(p, rq);
1332 p->prio = current->prio;
1333 BUG_ON(p->state & TASK_ONHOLD);
1334 list_add_tail(&p->run_list, ¤t->run_list);
1335 p->array = current->array;
1336 p->array->nr_active++;
1341 /* Run child last */
1342 __activate_task(p, rq);
1344 * We skip the following code due to cpu == this_cpu
1346 * task_rq_unlock(rq, &flags);
1347 * this_rq = task_rq_lock(current, &flags);
1351 this_rq = cpu_rq(this_cpu);
1354 * Not the local CPU - must adjust timestamp. This should
1355 * get optimised away in the !CONFIG_SMP case.
1357 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1358 + rq->timestamp_last_tick;
1359 __activate_task(p, rq);
1360 if (TASK_PREEMPTS_CURR(p, rq))
1361 resched_task(rq->curr);
1363 schedstat_inc(rq, wunt_moved);
1365 * Parent and child are on different CPUs, now get the
1366 * parent runqueue to update the parent's ->sleep_avg:
1368 task_rq_unlock(rq, &flags);
1369 this_rq = task_rq_lock(current, &flags);
1371 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1372 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1373 task_rq_unlock(this_rq, &flags);
1377 * Potentially available exiting-child timeslices are
1378 * retrieved here - this way the parent does not get
1379 * penalized for creating too many threads.
1381 * (this cannot be used to 'generate' timeslices
1382 * artificially, because any timeslice recovered here
1383 * was given away by the parent in the first place.)
1385 void fastcall sched_exit(task_t * p)
1387 unsigned long flags;
1391 * If the child was a (relative-) CPU hog then decrease
1392 * the sleep_avg of the parent as well.
1394 rq = task_rq_lock(p->parent, &flags);
1395 if (p->first_time_slice) {
1396 p->parent->time_slice += p->time_slice;
1397 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1398 p->parent->time_slice = task_timeslice(p);
1400 if (p->sleep_avg < p->parent->sleep_avg)
1401 p->parent->sleep_avg = p->parent->sleep_avg /
1402 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1404 task_rq_unlock(rq, &flags);
1408 * finish_task_switch - clean up after a task-switch
1409 * @prev: the thread we just switched away from.
1411 * We enter this with the runqueue still locked, and finish_arch_switch()
1412 * will unlock it along with doing any other architecture-specific cleanup
1415 * Note that we may have delayed dropping an mm in context_switch(). If
1416 * so, we finish that here outside of the runqueue lock. (Doing it
1417 * with the lock held can cause deadlocks; see schedule() for
1420 static void finish_task_switch(task_t *prev)
1421 __releases(rq->lock)
1423 runqueue_t *rq = this_rq();
1424 struct mm_struct *mm = rq->prev_mm;
1425 unsigned long prev_task_flags;
1430 * A task struct has one reference for the use as "current".
1431 * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1432 * calls schedule one last time. The schedule call will never return,
1433 * and the scheduled task must drop that reference.
1434 * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1435 * still held, otherwise prev could be scheduled on another cpu, die
1436 * there before we look at prev->state, and then the reference would
1438 * Manfred Spraul <manfred@colorfullife.com>
1440 prev_task_flags = prev->flags;
1441 finish_arch_switch(rq, prev);
1444 if (unlikely(prev_task_flags & PF_DEAD))
1445 put_task_struct(prev);
1449 * schedule_tail - first thing a freshly forked thread must call.
1450 * @prev: the thread we just switched away from.
1452 asmlinkage void schedule_tail(task_t *prev)
1453 __releases(rq->lock)
1455 finish_task_switch(prev);
1457 if (current->set_child_tid)
1458 put_user(current->pid, current->set_child_tid);
1462 * context_switch - switch to the new MM and the new
1463 * thread's register state.
1466 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1468 struct mm_struct *mm = next->mm;
1469 struct mm_struct *oldmm = prev->active_mm;
1471 if (unlikely(!mm)) {
1472 next->active_mm = oldmm;
1473 atomic_inc(&oldmm->mm_count);
1474 enter_lazy_tlb(oldmm, next);
1476 switch_mm(oldmm, mm, next);
1478 if (unlikely(!prev->mm)) {
1479 prev->active_mm = NULL;
1480 WARN_ON(rq->prev_mm);
1481 rq->prev_mm = oldmm;
1484 /* Here we just switch the register state and the stack. */
1485 switch_to(prev, next, prev);
1491 * nr_running, nr_uninterruptible and nr_context_switches:
1493 * externally visible scheduler statistics: current number of runnable
1494 * threads, current number of uninterruptible-sleeping threads, total
1495 * number of context switches performed since bootup.
1497 unsigned long nr_running(void)
1499 unsigned long i, sum = 0;
1501 for_each_online_cpu(i)
1502 sum += cpu_rq(i)->nr_running;
1507 unsigned long nr_uninterruptible(void)
1509 unsigned long i, sum = 0;
1512 sum += cpu_rq(i)->nr_uninterruptible;
1515 * Since we read the counters lockless, it might be slightly
1516 * inaccurate. Do not allow it to go below zero though:
1518 if (unlikely((long)sum < 0))
1524 unsigned long long nr_context_switches(void)
1526 unsigned long long i, sum = 0;
1529 sum += cpu_rq(i)->nr_switches;
1534 unsigned long nr_iowait(void)
1536 unsigned long i, sum = 0;
1539 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1547 * double_rq_lock - safely lock two runqueues
1549 * Note this does not disable interrupts like task_rq_lock,
1550 * you need to do so manually before calling.
1552 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1553 __acquires(rq1->lock)
1554 __acquires(rq2->lock)
1557 spin_lock(&rq1->lock);
1558 __acquire(rq2->lock); /* Fake it out ;) */
1561 spin_lock(&rq1->lock);
1562 spin_lock(&rq2->lock);
1564 spin_lock(&rq2->lock);
1565 spin_lock(&rq1->lock);
1571 * double_rq_unlock - safely unlock two runqueues
1573 * Note this does not restore interrupts like task_rq_unlock,
1574 * you need to do so manually after calling.
1576 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1577 __releases(rq1->lock)
1578 __releases(rq2->lock)
1580 spin_unlock(&rq1->lock);
1582 spin_unlock(&rq2->lock);
1584 __release(rq2->lock);
1588 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1590 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1591 __releases(this_rq->lock)
1592 __acquires(busiest->lock)
1593 __acquires(this_rq->lock)
1595 if (unlikely(!spin_trylock(&busiest->lock))) {
1596 if (busiest < this_rq) {
1597 spin_unlock(&this_rq->lock);
1598 spin_lock(&busiest->lock);
1599 spin_lock(&this_rq->lock);
1601 spin_lock(&busiest->lock);
1606 * find_idlest_cpu - find the least busy runqueue.
1608 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1609 struct sched_domain *sd)
1611 unsigned long load, min_load, this_load;
1616 min_load = ULONG_MAX;
1618 cpus_and(mask, sd->span, p->cpus_allowed);
1620 for_each_cpu_mask(i, mask) {
1621 load = target_load(i);
1623 if (load < min_load) {
1627 /* break out early on an idle CPU: */
1633 /* add +1 to account for the new task */
1634 this_load = source_load(this_cpu) + SCHED_LOAD_SCALE;
1637 * Would with the addition of the new task to the
1638 * current CPU there be an imbalance between this
1639 * CPU and the idlest CPU?
1641 * Use half of the balancing threshold - new-context is
1642 * a good opportunity to balance.
1644 if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1651 * If dest_cpu is allowed for this process, migrate the task to it.
1652 * This is accomplished by forcing the cpu_allowed mask to only
1653 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1654 * the cpu_allowed mask is restored.
1656 static void sched_migrate_task(task_t *p, int dest_cpu)
1658 migration_req_t req;
1660 unsigned long flags;
1662 rq = task_rq_lock(p, &flags);
1663 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1664 || unlikely(cpu_is_offline(dest_cpu)))
1667 schedstat_inc(rq, smt_cnt);
1668 /* force the process onto the specified CPU */
1669 if (migrate_task(p, dest_cpu, &req)) {
1670 /* Need to wait for migration thread (might exit: take ref). */
1671 struct task_struct *mt = rq->migration_thread;
1672 get_task_struct(mt);
1673 task_rq_unlock(rq, &flags);
1674 wake_up_process(mt);
1675 put_task_struct(mt);
1676 wait_for_completion(&req.done);
1680 task_rq_unlock(rq, &flags);
1684 * sched_exec(): find the highest-level, exec-balance-capable
1685 * domain and try to migrate the task to the least loaded CPU.
1687 * execve() is a valuable balancing opportunity, because at this point
1688 * the task has the smallest effective memory and cache footprint.
1690 void sched_exec(void)
1692 struct sched_domain *tmp, *sd = NULL;
1693 int new_cpu, this_cpu = get_cpu();
1695 schedstat_inc(this_rq(), sbe_cnt);
1696 /* Prefer the current CPU if there's only this task running */
1697 if (this_rq()->nr_running <= 1)
1700 for_each_domain(this_cpu, tmp)
1701 if (tmp->flags & SD_BALANCE_EXEC)
1705 schedstat_inc(sd, sbe_attempts);
1706 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1707 if (new_cpu != this_cpu) {
1708 schedstat_inc(sd, sbe_pushed);
1710 sched_migrate_task(current, new_cpu);
1719 * pull_task - move a task from a remote runqueue to the local runqueue.
1720 * Both runqueues must be locked.
1723 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1724 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1726 dequeue_task(p, src_array);
1727 src_rq->nr_running--;
1728 set_task_cpu(p, this_cpu);
1729 this_rq->nr_running++;
1730 enqueue_task(p, this_array);
1731 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1732 + this_rq->timestamp_last_tick;
1734 * Note that idle threads have a prio of MAX_PRIO, for this test
1735 * to be always true for them.
1737 if (TASK_PREEMPTS_CURR(p, this_rq))
1738 resched_task(this_rq->curr);
1742 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1745 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1746 struct sched_domain *sd, enum idle_type idle)
1749 * We do not migrate tasks that are:
1750 * 1) running (obviously), or
1751 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1752 * 3) are cache-hot on their current CPU.
1754 if (task_running(rq, p))
1756 if (!cpu_isset(this_cpu, p->cpus_allowed))
1760 * Aggressive migration if:
1761 * 1) the [whole] cpu is idle, or
1762 * 2) too many balance attempts have failed.
1765 if (cpu_and_siblings_are_idle(this_cpu) || \
1766 sd->nr_balance_failed > sd->cache_nice_tries)
1769 if (task_hot(p, rq->timestamp_last_tick, sd))
1775 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1776 * as part of a balancing operation within "domain". Returns the number of
1779 * Called with both runqueues locked.
1781 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1782 unsigned long max_nr_move, struct sched_domain *sd,
1783 enum idle_type idle)
1785 prio_array_t *array, *dst_array;
1786 struct list_head *head, *curr;
1787 int idx, pulled = 0;
1790 if (max_nr_move <= 0 || busiest->nr_running <= 1)
1794 * We first consider expired tasks. Those will likely not be
1795 * executed in the near future, and they are most likely to
1796 * be cache-cold, thus switching CPUs has the least effect
1799 if (busiest->expired->nr_active) {
1800 array = busiest->expired;
1801 dst_array = this_rq->expired;
1803 array = busiest->active;
1804 dst_array = this_rq->active;
1808 /* Start searching at priority 0: */
1812 idx = sched_find_first_bit(array->bitmap);
1814 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1815 if (idx >= MAX_PRIO) {
1816 if (array == busiest->expired && busiest->active->nr_active) {
1817 array = busiest->active;
1818 dst_array = this_rq->active;
1824 head = array->queue + idx;
1827 tmp = list_entry(curr, task_t, run_list);
1831 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
1839 * Right now, this is the only place pull_task() is called,
1840 * so we can safely collect pull_task() stats here rather than
1841 * inside pull_task().
1843 schedstat_inc(this_rq, pt_gained[idle]);
1844 schedstat_inc(busiest, pt_lost[idle]);
1846 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
1849 /* We only want to steal up to the prescribed number of tasks. */
1850 if (pulled < max_nr_move) {
1861 * find_busiest_group finds and returns the busiest CPU group within the
1862 * domain. It calculates and returns the number of tasks which should be
1863 * moved to restore balance via the imbalance parameter.
1865 static struct sched_group *
1866 find_busiest_group(struct sched_domain *sd, int this_cpu,
1867 unsigned long *imbalance, enum idle_type idle)
1869 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
1870 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
1872 max_load = this_load = total_load = total_pwr = 0;
1879 local_group = cpu_isset(this_cpu, group->cpumask);
1881 /* Tally up the load of all CPUs in the group */
1884 for_each_cpu_mask(i, group->cpumask) {
1885 /* Bias balancing toward cpus of our domain */
1887 load = target_load(i);
1889 load = source_load(i);
1898 total_load += avg_load;
1899 total_pwr += group->cpu_power;
1901 /* Adjust by relative CPU power of the group */
1902 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1905 this_load = avg_load;
1908 } else if (avg_load > max_load) {
1909 max_load = avg_load;
1913 group = group->next;
1914 } while (group != sd->groups);
1916 if (!busiest || this_load >= max_load)
1919 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
1921 if (this_load >= avg_load ||
1922 100*max_load <= sd->imbalance_pct*this_load)
1926 * We're trying to get all the cpus to the average_load, so we don't
1927 * want to push ourselves above the average load, nor do we wish to
1928 * reduce the max loaded cpu below the average load, as either of these
1929 * actions would just result in more rebalancing later, and ping-pong
1930 * tasks around. Thus we look for the minimum possible imbalance.
1931 * Negative imbalances (*we* are more loaded than anyone else) will
1932 * be counted as no imbalance for these purposes -- we can't fix that
1933 * by pulling tasks to us. Be careful of negative numbers as they'll
1934 * appear as very large values with unsigned longs.
1936 *imbalance = min(max_load - avg_load, avg_load - this_load);
1938 /* How much load to actually move to equalise the imbalance */
1939 *imbalance = (*imbalance * min(busiest->cpu_power, this->cpu_power))
1942 if (*imbalance < SCHED_LOAD_SCALE - 1) {
1943 unsigned long pwr_now = 0, pwr_move = 0;
1946 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
1952 * OK, we don't have enough imbalance to justify moving tasks,
1953 * however we may be able to increase total CPU power used by
1957 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
1958 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
1959 pwr_now /= SCHED_LOAD_SCALE;
1961 /* Amount of load we'd subtract */
1962 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
1964 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
1967 /* Amount of load we'd add */
1968 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
1971 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
1972 pwr_move /= SCHED_LOAD_SCALE;
1974 /* Move if we gain another 8th of a CPU worth of throughput */
1975 if (pwr_move < pwr_now + SCHED_LOAD_SCALE / 8)
1982 /* Get rid of the scaling factor, rounding down as we divide */
1983 *imbalance = (*imbalance + 1) / SCHED_LOAD_SCALE;
1988 if (busiest && (idle == NEWLY_IDLE ||
1989 (idle == SCHED_IDLE && max_load > SCHED_LOAD_SCALE)) ) {
1999 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2001 static runqueue_t *find_busiest_queue(struct sched_group *group)
2003 unsigned long load, max_load = 0;
2004 runqueue_t *busiest = NULL;
2007 for_each_cpu_mask(i, group->cpumask) {
2008 load = source_load(i);
2010 if (load > max_load) {
2012 busiest = cpu_rq(i);
2020 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2021 * tasks if there is an imbalance.
2023 * Called with this_rq unlocked.
2025 static int load_balance(int this_cpu, runqueue_t *this_rq,
2026 struct sched_domain *sd, enum idle_type idle)
2028 struct sched_group *group;
2029 runqueue_t *busiest;
2030 unsigned long imbalance;
2033 spin_lock(&this_rq->lock);
2034 schedstat_inc(sd, lb_cnt[idle]);
2036 group = find_busiest_group(sd, this_cpu, &imbalance, idle);
2038 schedstat_inc(sd, lb_nobusyg[idle]);
2042 busiest = find_busiest_queue(group);
2044 schedstat_inc(sd, lb_nobusyq[idle]);
2049 * This should be "impossible", but since load
2050 * balancing is inherently racy and statistical,
2051 * it could happen in theory.
2053 if (unlikely(busiest == this_rq)) {
2058 schedstat_add(sd, lb_imbalance[idle], imbalance);
2061 if (busiest->nr_running > 1) {
2063 * Attempt to move tasks. If find_busiest_group has found
2064 * an imbalance but busiest->nr_running <= 1, the group is
2065 * still unbalanced. nr_moved simply stays zero, so it is
2066 * correctly treated as an imbalance.
2068 double_lock_balance(this_rq, busiest);
2069 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2070 imbalance, sd, idle);
2071 spin_unlock(&busiest->lock);
2073 spin_unlock(&this_rq->lock);
2076 schedstat_inc(sd, lb_failed[idle]);
2077 sd->nr_balance_failed++;
2079 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2082 spin_lock(&busiest->lock);
2083 if (!busiest->active_balance) {
2084 busiest->active_balance = 1;
2085 busiest->push_cpu = this_cpu;
2088 spin_unlock(&busiest->lock);
2090 wake_up_process(busiest->migration_thread);
2093 * We've kicked active balancing, reset the failure
2096 sd->nr_balance_failed = sd->cache_nice_tries;
2100 * We were unbalanced, but unsuccessful in move_tasks(),
2101 * so bump the balance_interval to lessen the lock contention.
2103 if (sd->balance_interval < sd->max_interval)
2104 sd->balance_interval++;
2106 sd->nr_balance_failed = 0;
2108 /* We were unbalanced, so reset the balancing interval */
2109 sd->balance_interval = sd->min_interval;
2115 spin_unlock(&this_rq->lock);
2117 /* tune up the balancing interval */
2118 if (sd->balance_interval < sd->max_interval)
2119 sd->balance_interval *= 2;
2125 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2126 * tasks if there is an imbalance.
2128 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2129 * this_rq is locked.
2131 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2132 struct sched_domain *sd)
2134 struct sched_group *group;
2135 runqueue_t *busiest = NULL;
2136 unsigned long imbalance;
2139 schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2140 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
2142 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2146 busiest = find_busiest_queue(group);
2147 if (!busiest || busiest == this_rq) {
2148 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2152 /* Attempt to move tasks */
2153 double_lock_balance(this_rq, busiest);
2155 schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2156 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2157 imbalance, sd, NEWLY_IDLE);
2159 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2161 spin_unlock(&busiest->lock);
2168 * idle_balance is called by schedule() if this_cpu is about to become
2169 * idle. Attempts to pull tasks from other CPUs.
2171 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
2173 struct sched_domain *sd;
2175 for_each_domain(this_cpu, sd) {
2176 if (sd->flags & SD_BALANCE_NEWIDLE) {
2177 if (load_balance_newidle(this_cpu, this_rq, sd)) {
2178 /* We've pulled tasks over so stop searching */
2186 * active_load_balance is run by migration threads. It pushes running tasks
2187 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2188 * running on each physical CPU where possible, and avoids physical /
2189 * logical imbalances.
2191 * Called with busiest_rq locked.
2193 static void active_load_balance(runqueue_t *busiest_rq, int busiest_cpu)
2195 struct sched_domain *sd;
2196 struct sched_group *cpu_group;
2197 runqueue_t *target_rq;
2198 cpumask_t visited_cpus;
2201 schedstat_inc(busiest_rq, alb_cnt);
2203 * Search for suitable CPUs to push tasks to in successively higher
2204 * domains with SD_LOAD_BALANCE set.
2206 visited_cpus = CPU_MASK_NONE;
2207 for_each_domain(busiest_cpu, sd) {
2208 if (!(sd->flags & SD_LOAD_BALANCE))
2209 /* no more domains to search */
2212 cpu_group = sd->groups;
2214 for_each_cpu_mask(cpu, cpu_group->cpumask) {
2215 if (busiest_rq->nr_running <= 1)
2216 /* no more tasks left to move */
2218 if (cpu_isset(cpu, visited_cpus))
2220 cpu_set(cpu, visited_cpus);
2221 if (!cpu_and_siblings_are_idle(cpu) || cpu == busiest_cpu)
2224 target_rq = cpu_rq(cpu);
2226 * This condition is "impossible", if it occurs
2227 * we need to fix it. Originally reported by
2228 * Bjorn Helgaas on a 128-cpu setup.
2230 BUG_ON(busiest_rq == target_rq);
2232 /* move a task from busiest_rq to target_rq */
2233 double_lock_balance(busiest_rq, target_rq);
2234 if (move_tasks(target_rq, cpu, busiest_rq,
2235 1, sd, SCHED_IDLE)) {
2236 schedstat_inc(busiest_rq, alb_lost);
2237 schedstat_inc(target_rq, alb_gained);
2239 schedstat_inc(busiest_rq, alb_failed);
2241 spin_unlock(&target_rq->lock);
2243 cpu_group = cpu_group->next;
2244 } while (cpu_group != sd->groups);
2249 * rebalance_tick will get called every timer tick, on every CPU.
2251 * It checks each scheduling domain to see if it is due to be balanced,
2252 * and initiates a balancing operation if so.
2254 * Balancing parameters are set up in arch_init_sched_domains.
2257 /* Don't have all balancing operations going off at once */
2258 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2260 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2261 enum idle_type idle)
2263 unsigned long old_load, this_load;
2264 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2265 struct sched_domain *sd;
2267 /* Update our load */
2268 old_load = this_rq->cpu_load;
2269 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
2271 * Round up the averaging division if load is increasing. This
2272 * prevents us from getting stuck on 9 if the load is 10, for
2275 if (this_load > old_load)
2277 this_rq->cpu_load = (old_load + this_load) / 2;
2279 for_each_domain(this_cpu, sd) {
2280 unsigned long interval;
2282 if (!(sd->flags & SD_LOAD_BALANCE))
2285 interval = sd->balance_interval;
2286 if (idle != SCHED_IDLE)
2287 interval *= sd->busy_factor;
2289 /* scale ms to jiffies */
2290 interval = msecs_to_jiffies(interval);
2291 if (unlikely(!interval))
2294 if (j - sd->last_balance >= interval) {
2295 if (load_balance(this_cpu, this_rq, sd, idle)) {
2296 /* We've pulled tasks over so no longer idle */
2299 sd->last_balance += interval;
2305 * on UP we do not need to balance between CPUs:
2307 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2310 static inline void idle_balance(int cpu, runqueue_t *rq)
2315 static inline int wake_priority_sleeper(runqueue_t *rq)
2318 #ifdef CONFIG_SCHED_SMT
2319 spin_lock(&rq->lock);
2321 * If an SMT sibling task has been put to sleep for priority
2322 * reasons reschedule the idle task to see if it can now run.
2324 if (rq->nr_running) {
2325 resched_task(rq->idle);
2328 spin_unlock(&rq->lock);
2333 DEFINE_PER_CPU(struct kernel_stat, kstat);
2335 EXPORT_PER_CPU_SYMBOL(kstat);
2338 * We place interactive tasks back into the active array, if possible.
2340 * To guarantee that this does not starve expired tasks we ignore the
2341 * interactivity of a task if the first expired task had to wait more
2342 * than a 'reasonable' amount of time. This deadline timeout is
2343 * load-dependent, as the frequency of array switched decreases with
2344 * increasing number of running tasks. We also ignore the interactivity
2345 * if a better static_prio task has expired:
2347 #define EXPIRED_STARVING(rq) \
2348 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2349 (jiffies - (rq)->expired_timestamp >= \
2350 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2351 ((rq)->curr->static_prio > (rq)->best_expired_prio))
2354 * Do the virtual cpu time signal calculations.
2355 * @p: the process that the cpu time gets accounted to
2356 * @cputime: the cpu time spent in user space since the last update
2358 static inline void account_it_virt(struct task_struct * p, cputime_t cputime)
2360 cputime_t it_virt = p->it_virt_value;
2362 if (cputime_gt(it_virt, cputime_zero) &&
2363 cputime_gt(cputime, cputime_zero)) {
2364 if (cputime_ge(cputime, it_virt)) {
2365 it_virt = cputime_add(it_virt, p->it_virt_incr);
2366 send_sig(SIGVTALRM, p, 1);
2368 it_virt = cputime_sub(it_virt, cputime);
2369 p->it_virt_value = it_virt;
2374 * Do the virtual profiling signal calculations.
2375 * @p: the process that the cpu time gets accounted to
2376 * @cputime: the cpu time spent in user and kernel space since the last update
2378 static void account_it_prof(struct task_struct *p, cputime_t cputime)
2380 cputime_t it_prof = p->it_prof_value;
2382 if (cputime_gt(it_prof, cputime_zero) &&
2383 cputime_gt(cputime, cputime_zero)) {
2384 if (cputime_ge(cputime, it_prof)) {
2385 it_prof = cputime_add(it_prof, p->it_prof_incr);
2386 send_sig(SIGPROF, p, 1);
2388 it_prof = cputime_sub(it_prof, cputime);
2389 p->it_prof_value = it_prof;
2394 * Check if the process went over its cputime resource limit after
2395 * some cpu time got added to utime/stime.
2396 * @p: the process that the cpu time gets accounted to
2397 * @cputime: the cpu time spent in user and kernel space since the last update
2399 static void check_rlimit(struct task_struct *p, cputime_t cputime)
2401 cputime_t total, tmp;
2404 total = cputime_add(p->utime, p->stime);
2405 secs = cputime_to_secs(total);
2406 if (unlikely(secs >= p->signal->rlim[RLIMIT_CPU].rlim_cur)) {
2407 /* Send SIGXCPU every second. */
2408 tmp = cputime_sub(total, cputime);
2409 if (cputime_to_secs(tmp) < secs)
2410 send_sig(SIGXCPU, p, 1);
2411 /* and SIGKILL when we go over max.. */
2412 if (secs >= p->signal->rlim[RLIMIT_CPU].rlim_max)
2413 send_sig(SIGKILL, p, 1);
2418 * Account user cpu time to a process.
2419 * @p: the process that the cpu time gets accounted to
2420 * @hardirq_offset: the offset to subtract from hardirq_count()
2421 * @cputime: the cpu time spent in user space since the last update
2423 void account_user_time(struct task_struct *p, cputime_t cputime)
2425 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2428 p->utime = cputime_add(p->utime, cputime);
2430 /* Check for signals (SIGVTALRM, SIGPROF, SIGXCPU & SIGKILL). */
2431 check_rlimit(p, cputime);
2432 account_it_virt(p, cputime);
2433 account_it_prof(p, cputime);
2435 /* Add user time to cpustat. */
2436 tmp = cputime_to_cputime64(cputime);
2437 if (TASK_NICE(p) > 0)
2438 cpustat->nice = cputime64_add(cpustat->nice, tmp);
2440 cpustat->user = cputime64_add(cpustat->user, tmp);
2444 * Account system cpu time to a process.
2445 * @p: the process that the cpu time gets accounted to
2446 * @hardirq_offset: the offset to subtract from hardirq_count()
2447 * @cputime: the cpu time spent in kernel space since the last update
2449 void account_system_time(struct task_struct *p, int hardirq_offset,
2452 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2453 runqueue_t *rq = this_rq();
2456 p->stime = cputime_add(p->stime, cputime);
2458 /* Check for signals (SIGPROF, SIGXCPU & SIGKILL). */
2459 if (likely(p->signal && p->exit_state < EXIT_ZOMBIE)) {
2460 check_rlimit(p, cputime);
2461 account_it_prof(p, cputime);
2464 /* Add system time to cpustat. */
2465 tmp = cputime_to_cputime64(cputime);
2466 if (hardirq_count() - hardirq_offset)
2467 cpustat->irq = cputime64_add(cpustat->irq, tmp);
2468 else if (softirq_count())
2469 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
2470 else if (p != rq->idle)
2471 cpustat->system = cputime64_add(cpustat->system, tmp);
2472 else if (atomic_read(&rq->nr_iowait) > 0)
2473 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2475 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2479 * Account for involuntary wait time.
2480 * @p: the process from which the cpu time has been stolen
2481 * @steal: the cpu time spent in involuntary wait
2483 void account_steal_time(struct task_struct *p, cputime_t steal)
2485 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2486 cputime64_t tmp = cputime_to_cputime64(steal);
2487 runqueue_t *rq = this_rq();
2489 if (p == rq->idle) {
2490 p->stime = cputime_add(p->stime, steal);
2491 if (atomic_read(&rq->nr_iowait) > 0)
2492 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2494 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2496 cpustat->steal = cputime64_add(cpustat->steal, tmp);
2500 * This function gets called by the timer code, with HZ frequency.
2501 * We call it with interrupts disabled.
2503 * It also gets called by the fork code, when changing the parent's
2506 void scheduler_tick(void)
2508 int cpu = smp_processor_id();
2509 runqueue_t *rq = this_rq();
2510 task_t *p = current;
2512 rq->timestamp_last_tick = sched_clock();
2514 if (p == rq->idle) {
2515 if (wake_priority_sleeper(rq))
2517 #ifdef CONFIG_VSERVER_HARDCPU_IDLE
2518 if (!--rq->idle_tokens && !list_empty(&rq->hold_queue))
2521 rebalance_tick(cpu, rq, SCHED_IDLE);
2525 /* Task might have expired already, but not scheduled off yet */
2526 if (p->array != rq->active) {
2527 set_tsk_need_resched(p);
2530 spin_lock(&rq->lock);
2532 * The task was running during this tick - update the
2533 * time slice counter. Note: we do not update a thread's
2534 * priority until it either goes to sleep or uses up its
2535 * timeslice. This makes it possible for interactive tasks
2536 * to use up their timeslices at their highest priority levels.
2540 * RR tasks need a special form of timeslice management.
2541 * FIFO tasks have no timeslices.
2543 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2544 p->time_slice = task_timeslice(p);
2545 p->first_time_slice = 0;
2546 set_tsk_need_resched(p);
2548 /* put it at the end of the queue: */
2549 requeue_task(p, rq->active);
2553 if (vx_need_resched(p)) {
2554 dequeue_task(p, rq->active);
2555 set_tsk_need_resched(p);
2556 p->prio = effective_prio(p);
2557 p->time_slice = task_timeslice(p);
2558 p->first_time_slice = 0;
2560 if (!rq->expired_timestamp)
2561 rq->expired_timestamp = jiffies;
2562 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2563 enqueue_task(p, rq->expired);
2564 if (p->static_prio < rq->best_expired_prio)
2565 rq->best_expired_prio = p->static_prio;
2567 enqueue_task(p, rq->active);
2570 * Prevent a too long timeslice allowing a task to monopolize
2571 * the CPU. We do this by splitting up the timeslice into
2574 * Note: this does not mean the task's timeslices expire or
2575 * get lost in any way, they just might be preempted by
2576 * another task of equal priority. (one with higher
2577 * priority would have preempted this task already.) We
2578 * requeue this task to the end of the list on this priority
2579 * level, which is in essence a round-robin of tasks with
2582 * This only applies to tasks in the interactive
2583 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2585 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2586 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2587 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2588 (p->array == rq->active)) {
2590 requeue_task(p, rq->active);
2591 set_tsk_need_resched(p);
2595 spin_unlock(&rq->lock);
2597 rebalance_tick(cpu, rq, NOT_IDLE);
2600 #ifdef CONFIG_SCHED_SMT
2601 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2603 struct sched_domain *sd = this_rq->sd;
2604 cpumask_t sibling_map;
2607 if (!(sd->flags & SD_SHARE_CPUPOWER))
2611 * Unlock the current runqueue because we have to lock in
2612 * CPU order to avoid deadlocks. Caller knows that we might
2613 * unlock. We keep IRQs disabled.
2615 spin_unlock(&this_rq->lock);
2617 sibling_map = sd->span;
2619 for_each_cpu_mask(i, sibling_map)
2620 spin_lock(&cpu_rq(i)->lock);
2622 * We clear this CPU from the mask. This both simplifies the
2623 * inner loop and keps this_rq locked when we exit:
2625 cpu_clear(this_cpu, sibling_map);
2627 for_each_cpu_mask(i, sibling_map) {
2628 runqueue_t *smt_rq = cpu_rq(i);
2631 * If an SMT sibling task is sleeping due to priority
2632 * reasons wake it up now.
2634 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
2635 resched_task(smt_rq->idle);
2638 for_each_cpu_mask(i, sibling_map)
2639 spin_unlock(&cpu_rq(i)->lock);
2641 * We exit with this_cpu's rq still held and IRQs
2646 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2648 struct sched_domain *sd = this_rq->sd;
2649 cpumask_t sibling_map;
2650 prio_array_t *array;
2654 if (!(sd->flags & SD_SHARE_CPUPOWER))
2658 * The same locking rules and details apply as for
2659 * wake_sleeping_dependent():
2661 spin_unlock(&this_rq->lock);
2662 sibling_map = sd->span;
2663 for_each_cpu_mask(i, sibling_map)
2664 spin_lock(&cpu_rq(i)->lock);
2665 cpu_clear(this_cpu, sibling_map);
2668 * Establish next task to be run - it might have gone away because
2669 * we released the runqueue lock above:
2671 if (!this_rq->nr_running)
2673 array = this_rq->active;
2674 if (!array->nr_active)
2675 array = this_rq->expired;
2676 BUG_ON(!array->nr_active);
2678 p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
2681 for_each_cpu_mask(i, sibling_map) {
2682 runqueue_t *smt_rq = cpu_rq(i);
2683 task_t *smt_curr = smt_rq->curr;
2686 * If a user task with lower static priority than the
2687 * running task on the SMT sibling is trying to schedule,
2688 * delay it till there is proportionately less timeslice
2689 * left of the sibling task to prevent a lower priority
2690 * task from using an unfair proportion of the
2691 * physical cpu's resources. -ck
2693 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
2694 task_timeslice(p) || rt_task(smt_curr)) &&
2695 p->mm && smt_curr->mm && !rt_task(p))
2699 * Reschedule a lower priority task on the SMT sibling,
2700 * or wake it up if it has been put to sleep for priority
2703 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
2704 task_timeslice(smt_curr) || rt_task(p)) &&
2705 smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
2706 (smt_curr == smt_rq->idle && smt_rq->nr_running))
2707 resched_task(smt_curr);
2710 for_each_cpu_mask(i, sibling_map)
2711 spin_unlock(&cpu_rq(i)->lock);
2715 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2719 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2725 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
2727 void fastcall add_preempt_count(int val)
2732 BUG_ON(((int)preempt_count() < 0));
2733 preempt_count() += val;
2735 * Spinlock count overflowing soon?
2737 BUG_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
2739 EXPORT_SYMBOL(add_preempt_count);
2741 void fastcall sub_preempt_count(int val)
2746 BUG_ON(val > preempt_count());
2748 * Is the spinlock portion underflowing?
2750 BUG_ON((val < PREEMPT_MASK) && !(preempt_count() & PREEMPT_MASK));
2751 preempt_count() -= val;
2753 EXPORT_SYMBOL(sub_preempt_count);
2758 * schedule() is the main scheduler function.
2760 asmlinkage void __sched schedule(void)
2763 task_t *prev, *next;
2765 prio_array_t *array;
2766 struct list_head *queue;
2767 unsigned long long now;
2768 unsigned long run_time;
2769 struct vx_info *vxi;
2770 #ifdef CONFIG_VSERVER_HARDCPU
2776 * Test if we are atomic. Since do_exit() needs to call into
2777 * schedule() atomically, we ignore that path for now.
2778 * Otherwise, whine if we are scheduling when we should not be.
2780 if (likely(!current->exit_state)) {
2781 if (unlikely(in_atomic())) {
2782 printk(KERN_ERR "scheduling while atomic: "
2784 current->comm, preempt_count(), current->pid);
2788 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
2793 release_kernel_lock(prev);
2794 need_resched_nonpreemptible:
2798 * The idle thread is not allowed to schedule!
2799 * Remove this check after it has been exercised a bit.
2801 if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
2802 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
2806 schedstat_inc(rq, sched_cnt);
2807 now = sched_clock();
2808 if (likely(now - prev->timestamp < NS_MAX_SLEEP_AVG))
2809 run_time = now - prev->timestamp;
2811 run_time = NS_MAX_SLEEP_AVG;
2814 * Tasks charged proportionately less run_time at high sleep_avg to
2815 * delay them losing their interactive status
2817 run_time /= (CURRENT_BONUS(prev) ? : 1);
2819 spin_lock_irq(&rq->lock);
2821 if (unlikely(prev->flags & PF_DEAD))
2822 prev->state = EXIT_DEAD;
2824 switch_count = &prev->nivcsw;
2825 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2826 switch_count = &prev->nvcsw;
2827 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2828 unlikely(signal_pending(prev))))
2829 prev->state = TASK_RUNNING;
2831 if (prev->state == TASK_UNINTERRUPTIBLE) {
2832 rq->nr_uninterruptible++;
2833 vx_uninterruptible_inc(prev);
2835 deactivate_task(prev, rq);
2839 #ifdef CONFIG_VSERVER_HARDCPU
2840 if (!list_empty(&rq->hold_queue)) {
2841 struct list_head *l, *n;
2845 list_for_each_safe(l, n, &rq->hold_queue) {
2846 next = list_entry(l, task_t, run_list);
2847 if (vxi == next->vx_info)
2850 vxi = next->vx_info;
2851 ret = vx_tokens_recalc(vxi);
2852 // tokens = vx_tokens_avail(next);
2855 vx_unhold_task(vxi, next, rq);
2858 if ((ret < 0) && (maxidle < ret))
2862 rq->idle_tokens = -maxidle;
2867 cpu = smp_processor_id();
2868 if (unlikely(!rq->nr_running)) {
2870 idle_balance(cpu, rq);
2871 if (!rq->nr_running) {
2873 rq->expired_timestamp = 0;
2874 wake_sleeping_dependent(cpu, rq);
2876 * wake_sleeping_dependent() might have released
2877 * the runqueue, so break out if we got new
2880 if (!rq->nr_running)
2884 if (dependent_sleeper(cpu, rq)) {
2889 * dependent_sleeper() releases and reacquires the runqueue
2890 * lock, hence go into the idle loop if the rq went
2893 if (unlikely(!rq->nr_running))
2898 if (unlikely(!array->nr_active)) {
2900 * Switch the active and expired arrays.
2902 schedstat_inc(rq, sched_switch);
2903 rq->active = rq->expired;
2904 rq->expired = array;
2906 rq->expired_timestamp = 0;
2907 rq->best_expired_prio = MAX_PRIO;
2909 schedstat_inc(rq, sched_noswitch);
2911 idx = sched_find_first_bit(array->bitmap);
2912 queue = array->queue + idx;
2913 next = list_entry(queue->next, task_t, run_list);
2915 vxi = next->vx_info;
2916 #ifdef CONFIG_VSERVER_HARDCPU
2917 if (vx_info_flags(vxi, VXF_SCHED_PAUSE|VXF_SCHED_HARD, 0)) {
2918 int ret = vx_tokens_recalc(vxi);
2920 if (unlikely(ret <= 0)) {
2921 if (ret && (rq->idle_tokens > -ret))
2922 rq->idle_tokens = -ret;
2923 vx_hold_task(vxi, next, rq);
2926 } else /* well, looks ugly but not as ugly as the ifdef-ed version */
2928 if (vx_info_flags(vxi, VXF_SCHED_PRIO, 0))
2929 vx_tokens_recalc(vxi);
2931 if (!rt_task(next) && next->activated > 0) {
2932 unsigned long long delta = now - next->timestamp;
2934 if (next->activated == 1)
2935 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
2937 array = next->array;
2938 dequeue_task(next, array);
2939 recalc_task_prio(next, next->timestamp + delta);
2940 enqueue_task(next, array);
2942 next->activated = 0;
2944 if (next == rq->idle)
2945 schedstat_inc(rq, sched_goidle);
2947 clear_tsk_need_resched(prev);
2948 rcu_qsctr_inc(task_cpu(prev));
2950 prev->sleep_avg -= run_time;
2951 if ((long)prev->sleep_avg <= 0)
2952 prev->sleep_avg = 0;
2953 prev->timestamp = prev->last_ran = now;
2955 sched_info_switch(prev, next);
2956 if (likely(prev != next)) {
2957 next->timestamp = now;
2962 prepare_arch_switch(rq, next);
2963 prev = context_switch(rq, prev, next);
2966 finish_task_switch(prev);
2968 spin_unlock_irq(&rq->lock);
2971 if (unlikely(reacquire_kernel_lock(prev) < 0))
2972 goto need_resched_nonpreemptible;
2973 preempt_enable_no_resched();
2974 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2978 EXPORT_SYMBOL(schedule);
2980 #ifdef CONFIG_PREEMPT
2982 * this is is the entry point to schedule() from in-kernel preemption
2983 * off of preempt_enable. Kernel preemptions off return from interrupt
2984 * occur there and call schedule directly.
2986 asmlinkage void __sched preempt_schedule(void)
2988 struct thread_info *ti = current_thread_info();
2989 #ifdef CONFIG_PREEMPT_BKL
2990 struct task_struct *task = current;
2991 int saved_lock_depth;
2994 * If there is a non-zero preempt_count or interrupts are disabled,
2995 * we do not want to preempt the current task. Just return..
2997 if (unlikely(ti->preempt_count || irqs_disabled()))
3001 add_preempt_count(PREEMPT_ACTIVE);
3003 * We keep the big kernel semaphore locked, but we
3004 * clear ->lock_depth so that schedule() doesnt
3005 * auto-release the semaphore:
3007 #ifdef CONFIG_PREEMPT_BKL
3008 saved_lock_depth = task->lock_depth;
3009 task->lock_depth = -1;
3012 #ifdef CONFIG_PREEMPT_BKL
3013 task->lock_depth = saved_lock_depth;
3015 sub_preempt_count(PREEMPT_ACTIVE);
3017 /* we could miss a preemption opportunity between schedule and now */
3019 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3023 EXPORT_SYMBOL(preempt_schedule);
3026 * this is is the entry point to schedule() from kernel preemption
3027 * off of irq context.
3028 * Note, that this is called and return with irqs disabled. This will
3029 * protect us against recursive calling from irq.
3031 asmlinkage void __sched preempt_schedule_irq(void)
3033 struct thread_info *ti = current_thread_info();
3034 #ifdef CONFIG_PREEMPT_BKL
3035 struct task_struct *task = current;
3036 int saved_lock_depth;
3038 /* Catch callers which need to be fixed*/
3039 BUG_ON(ti->preempt_count || !irqs_disabled());
3042 add_preempt_count(PREEMPT_ACTIVE);
3044 * We keep the big kernel semaphore locked, but we
3045 * clear ->lock_depth so that schedule() doesnt
3046 * auto-release the semaphore:
3048 #ifdef CONFIG_PREEMPT_BKL
3049 saved_lock_depth = task->lock_depth;
3050 task->lock_depth = -1;
3054 local_irq_disable();
3055 #ifdef CONFIG_PREEMPT_BKL
3056 task->lock_depth = saved_lock_depth;
3058 sub_preempt_count(PREEMPT_ACTIVE);
3060 /* we could miss a preemption opportunity between schedule and now */
3062 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3066 #endif /* CONFIG_PREEMPT */
3068 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
3070 task_t *p = curr->task;
3071 return try_to_wake_up(p, mode, sync);
3074 EXPORT_SYMBOL(default_wake_function);
3077 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3078 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3079 * number) then we wake all the non-exclusive tasks and one exclusive task.
3081 * There are circumstances in which we can try to wake a task which has already
3082 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3083 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3085 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3086 int nr_exclusive, int sync, void *key)
3088 struct list_head *tmp, *next;
3090 list_for_each_safe(tmp, next, &q->task_list) {
3093 curr = list_entry(tmp, wait_queue_t, task_list);
3094 flags = curr->flags;
3095 if (curr->func(curr, mode, sync, key) &&
3096 (flags & WQ_FLAG_EXCLUSIVE) &&
3103 * __wake_up - wake up threads blocked on a waitqueue.
3105 * @mode: which threads
3106 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3108 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3109 int nr_exclusive, void *key)
3111 unsigned long flags;
3113 spin_lock_irqsave(&q->lock, flags);
3114 __wake_up_common(q, mode, nr_exclusive, 0, key);
3115 spin_unlock_irqrestore(&q->lock, flags);
3118 EXPORT_SYMBOL(__wake_up);
3121 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3123 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3125 __wake_up_common(q, mode, 1, 0, NULL);
3129 * __wake_up - sync- wake up threads blocked on a waitqueue.
3131 * @mode: which threads
3132 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3134 * The sync wakeup differs that the waker knows that it will schedule
3135 * away soon, so while the target thread will be woken up, it will not
3136 * be migrated to another CPU - ie. the two threads are 'synchronized'
3137 * with each other. This can prevent needless bouncing between CPUs.
3139 * On UP it can prevent extra preemption.
3141 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3143 unsigned long flags;
3149 if (unlikely(!nr_exclusive))
3152 spin_lock_irqsave(&q->lock, flags);
3153 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3154 spin_unlock_irqrestore(&q->lock, flags);
3156 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3158 void fastcall complete(struct completion *x)
3160 unsigned long flags;
3162 spin_lock_irqsave(&x->wait.lock, flags);
3164 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3166 spin_unlock_irqrestore(&x->wait.lock, flags);
3168 EXPORT_SYMBOL(complete);
3170 void fastcall complete_all(struct completion *x)
3172 unsigned long flags;
3174 spin_lock_irqsave(&x->wait.lock, flags);
3175 x->done += UINT_MAX/2;
3176 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3178 spin_unlock_irqrestore(&x->wait.lock, flags);
3180 EXPORT_SYMBOL(complete_all);
3182 void fastcall __sched wait_for_completion(struct completion *x)
3185 spin_lock_irq(&x->wait.lock);
3187 DECLARE_WAITQUEUE(wait, current);
3189 wait.flags |= WQ_FLAG_EXCLUSIVE;
3190 __add_wait_queue_tail(&x->wait, &wait);
3192 __set_current_state(TASK_UNINTERRUPTIBLE);
3193 spin_unlock_irq(&x->wait.lock);
3195 spin_lock_irq(&x->wait.lock);
3197 __remove_wait_queue(&x->wait, &wait);
3200 spin_unlock_irq(&x->wait.lock);
3202 EXPORT_SYMBOL(wait_for_completion);
3204 unsigned long fastcall __sched
3205 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3209 spin_lock_irq(&x->wait.lock);
3211 DECLARE_WAITQUEUE(wait, current);
3213 wait.flags |= WQ_FLAG_EXCLUSIVE;
3214 __add_wait_queue_tail(&x->wait, &wait);
3216 __set_current_state(TASK_UNINTERRUPTIBLE);
3217 spin_unlock_irq(&x->wait.lock);
3218 timeout = schedule_timeout(timeout);
3219 spin_lock_irq(&x->wait.lock);
3221 __remove_wait_queue(&x->wait, &wait);
3225 __remove_wait_queue(&x->wait, &wait);
3229 spin_unlock_irq(&x->wait.lock);
3232 EXPORT_SYMBOL(wait_for_completion_timeout);
3234 int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3240 spin_lock_irq(&x->wait.lock);
3242 DECLARE_WAITQUEUE(wait, current);
3244 wait.flags |= WQ_FLAG_EXCLUSIVE;
3245 __add_wait_queue_tail(&x->wait, &wait);
3247 if (signal_pending(current)) {
3249 __remove_wait_queue(&x->wait, &wait);
3252 __set_current_state(TASK_INTERRUPTIBLE);
3253 spin_unlock_irq(&x->wait.lock);
3255 spin_lock_irq(&x->wait.lock);
3257 __remove_wait_queue(&x->wait, &wait);
3261 spin_unlock_irq(&x->wait.lock);
3265 EXPORT_SYMBOL(wait_for_completion_interruptible);
3267 unsigned long fastcall __sched
3268 wait_for_completion_interruptible_timeout(struct completion *x,
3269 unsigned long timeout)
3273 spin_lock_irq(&x->wait.lock);
3275 DECLARE_WAITQUEUE(wait, current);
3277 wait.flags |= WQ_FLAG_EXCLUSIVE;
3278 __add_wait_queue_tail(&x->wait, &wait);
3280 if (signal_pending(current)) {
3281 timeout = -ERESTARTSYS;
3282 __remove_wait_queue(&x->wait, &wait);
3285 __set_current_state(TASK_INTERRUPTIBLE);
3286 spin_unlock_irq(&x->wait.lock);
3287 timeout = schedule_timeout(timeout);
3288 spin_lock_irq(&x->wait.lock);
3290 __remove_wait_queue(&x->wait, &wait);
3294 __remove_wait_queue(&x->wait, &wait);
3298 spin_unlock_irq(&x->wait.lock);
3301 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3304 #define SLEEP_ON_VAR \
3305 unsigned long flags; \
3306 wait_queue_t wait; \
3307 init_waitqueue_entry(&wait, current);
3309 #define SLEEP_ON_HEAD \
3310 spin_lock_irqsave(&q->lock,flags); \
3311 __add_wait_queue(q, &wait); \
3312 spin_unlock(&q->lock);
3314 #define SLEEP_ON_TAIL \
3315 spin_lock_irq(&q->lock); \
3316 __remove_wait_queue(q, &wait); \
3317 spin_unlock_irqrestore(&q->lock, flags);
3319 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3323 current->state = TASK_INTERRUPTIBLE;
3330 EXPORT_SYMBOL(interruptible_sleep_on);
3332 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3336 current->state = TASK_INTERRUPTIBLE;
3339 timeout = schedule_timeout(timeout);
3345 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3347 void fastcall __sched sleep_on(wait_queue_head_t *q)
3351 current->state = TASK_UNINTERRUPTIBLE;
3358 EXPORT_SYMBOL(sleep_on);
3360 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3364 current->state = TASK_UNINTERRUPTIBLE;
3367 timeout = schedule_timeout(timeout);
3373 EXPORT_SYMBOL(sleep_on_timeout);
3375 void set_user_nice(task_t *p, long nice)
3377 unsigned long flags;
3378 prio_array_t *array;
3380 int old_prio, new_prio, delta;
3382 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3385 * We have to be careful, if called from sys_setpriority(),
3386 * the task might be in the middle of scheduling on another CPU.
3388 rq = task_rq_lock(p, &flags);
3390 * The RT priorities are set via sched_setscheduler(), but we still
3391 * allow the 'normal' nice value to be set - but as expected
3392 * it wont have any effect on scheduling until the task is
3396 p->static_prio = NICE_TO_PRIO(nice);
3401 dequeue_task(p, array);
3404 new_prio = NICE_TO_PRIO(nice);
3405 delta = new_prio - old_prio;
3406 p->static_prio = NICE_TO_PRIO(nice);
3410 enqueue_task(p, array);
3412 * If the task increased its priority or is running and
3413 * lowered its priority, then reschedule its CPU:
3415 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3416 resched_task(rq->curr);
3419 task_rq_unlock(rq, &flags);
3422 EXPORT_SYMBOL(set_user_nice);
3424 #ifdef __ARCH_WANT_SYS_NICE
3427 * sys_nice - change the priority of the current process.
3428 * @increment: priority increment
3430 * sys_setpriority is a more generic, but much slower function that
3431 * does similar things.
3433 asmlinkage long sys_nice(int increment)
3439 * Setpriority might change our priority at the same moment.
3440 * We don't have to worry. Conceptually one call occurs first
3441 * and we have a single winner.
3443 if (increment < 0) {
3444 if (vx_flags(VXF_IGNEG_NICE, 0))
3446 if (!capable(CAP_SYS_NICE))
3448 if (increment < -40)
3454 nice = PRIO_TO_NICE(current->static_prio) + increment;
3460 retval = security_task_setnice(current, nice);
3464 set_user_nice(current, nice);
3471 * task_prio - return the priority value of a given task.
3472 * @p: the task in question.
3474 * This is the priority value as seen by users in /proc.
3475 * RT tasks are offset by -200. Normal tasks are centered
3476 * around 0, value goes from -16 to +15.
3478 int task_prio(const task_t *p)
3480 return p->prio - MAX_RT_PRIO;
3484 * task_nice - return the nice value of a given task.
3485 * @p: the task in question.
3487 int task_nice(const task_t *p)
3489 return TASK_NICE(p);
3493 * The only users of task_nice are binfmt_elf and binfmt_elf32.
3494 * binfmt_elf is no longer modular, but binfmt_elf32 still is.
3495 * Therefore, task_nice is needed if there is a compat_mode.
3497 #ifdef CONFIG_COMPAT
3498 EXPORT_SYMBOL_GPL(task_nice);
3502 * idle_cpu - is a given cpu idle currently?
3503 * @cpu: the processor in question.
3505 int idle_cpu(int cpu)
3507 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3510 EXPORT_SYMBOL_GPL(idle_cpu);
3513 * idle_task - return the idle task for a given cpu.
3514 * @cpu: the processor in question.
3516 task_t *idle_task(int cpu)
3518 return cpu_rq(cpu)->idle;
3522 * find_process_by_pid - find a process with a matching PID value.
3523 * @pid: the pid in question.
3525 static inline task_t *find_process_by_pid(pid_t pid)
3527 return pid ? find_task_by_pid(pid) : current;
3530 /* Actually do priority change: must hold rq lock. */
3531 static void __setscheduler(struct task_struct *p, int policy, int prio)
3535 p->rt_priority = prio;
3536 if (policy != SCHED_NORMAL)
3537 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
3539 p->prio = p->static_prio;
3543 * sched_setscheduler - change the scheduling policy and/or RT priority of
3545 * @p: the task in question.
3546 * @policy: new policy.
3547 * @param: structure containing the new RT priority.
3549 int sched_setscheduler(struct task_struct *p, int policy, struct sched_param *param)
3552 int oldprio, oldpolicy = -1;
3553 prio_array_t *array;
3554 unsigned long flags;
3558 /* double check policy once rq lock held */
3560 policy = oldpolicy = p->policy;
3561 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
3562 policy != SCHED_NORMAL)
3565 * Valid priorities for SCHED_FIFO and SCHED_RR are
3566 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
3568 if (param->sched_priority < 0 ||
3569 param->sched_priority > MAX_USER_RT_PRIO-1)
3571 if ((policy == SCHED_NORMAL) != (param->sched_priority == 0))
3574 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
3575 !capable(CAP_SYS_NICE))
3577 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3578 !capable(CAP_SYS_NICE))
3581 retval = security_task_setscheduler(p, policy, param);
3585 * To be able to change p->policy safely, the apropriate
3586 * runqueue lock must be held.
3588 rq = task_rq_lock(p, &flags);
3589 /* recheck policy now with rq lock held */
3590 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3591 policy = oldpolicy = -1;
3592 task_rq_unlock(rq, &flags);
3597 deactivate_task(p, rq);
3599 __setscheduler(p, policy, param->sched_priority);
3601 vx_activate_task(p);
3602 __activate_task(p, rq);
3604 * Reschedule if we are currently running on this runqueue and
3605 * our priority decreased, or if we are not currently running on
3606 * this runqueue and our priority is higher than the current's
3608 if (task_running(rq, p)) {
3609 if (p->prio > oldprio)
3610 resched_task(rq->curr);
3611 } else if (TASK_PREEMPTS_CURR(p, rq))
3612 resched_task(rq->curr);
3614 task_rq_unlock(rq, &flags);
3617 EXPORT_SYMBOL_GPL(sched_setscheduler);
3619 static int do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3622 struct sched_param lparam;
3623 struct task_struct *p;
3625 if (!param || pid < 0)
3627 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
3629 read_lock_irq(&tasklist_lock);
3630 p = find_process_by_pid(pid);
3632 read_unlock_irq(&tasklist_lock);
3635 retval = sched_setscheduler(p, policy, &lparam);
3636 read_unlock_irq(&tasklist_lock);
3641 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3642 * @pid: the pid in question.
3643 * @policy: new policy.
3644 * @param: structure containing the new RT priority.
3646 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3647 struct sched_param __user *param)
3649 return do_sched_setscheduler(pid, policy, param);
3653 * sys_sched_setparam - set/change the RT priority of a thread
3654 * @pid: the pid in question.
3655 * @param: structure containing the new RT priority.
3657 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3659 return do_sched_setscheduler(pid, -1, param);
3663 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3664 * @pid: the pid in question.
3666 asmlinkage long sys_sched_getscheduler(pid_t pid)
3668 int retval = -EINVAL;
3675 read_lock(&tasklist_lock);
3676 p = find_process_by_pid(pid);
3678 retval = security_task_getscheduler(p);
3682 read_unlock(&tasklist_lock);
3689 * sys_sched_getscheduler - get the RT priority of a thread
3690 * @pid: the pid in question.
3691 * @param: structure containing the RT priority.
3693 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3695 struct sched_param lp;
3696 int retval = -EINVAL;
3699 if (!param || pid < 0)
3702 read_lock(&tasklist_lock);
3703 p = find_process_by_pid(pid);
3708 retval = security_task_getscheduler(p);
3712 lp.sched_priority = p->rt_priority;
3713 read_unlock(&tasklist_lock);
3716 * This one might sleep, we cannot do it with a spinlock held ...
3718 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3724 read_unlock(&tasklist_lock);
3728 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
3734 read_lock(&tasklist_lock);
3736 p = find_process_by_pid(pid);
3738 read_unlock(&tasklist_lock);
3739 unlock_cpu_hotplug();
3744 * It is not safe to call set_cpus_allowed with the
3745 * tasklist_lock held. We will bump the task_struct's
3746 * usage count and then drop tasklist_lock.
3749 read_unlock(&tasklist_lock);
3752 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3753 !capable(CAP_SYS_NICE))
3756 retval = set_cpus_allowed(p, new_mask);
3760 unlock_cpu_hotplug();
3764 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
3765 cpumask_t *new_mask)
3767 if (len < sizeof(cpumask_t)) {
3768 memset(new_mask, 0, sizeof(cpumask_t));
3769 } else if (len > sizeof(cpumask_t)) {
3770 len = sizeof(cpumask_t);
3772 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
3776 * sys_sched_setaffinity - set the cpu affinity of a process
3777 * @pid: pid of the process
3778 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3779 * @user_mask_ptr: user-space pointer to the new cpu mask
3781 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
3782 unsigned long __user *user_mask_ptr)
3787 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
3791 return sched_setaffinity(pid, new_mask);
3795 * Represents all cpu's present in the system
3796 * In systems capable of hotplug, this map could dynamically grow
3797 * as new cpu's are detected in the system via any platform specific
3798 * method, such as ACPI for e.g.
3801 cpumask_t cpu_present_map;
3802 EXPORT_SYMBOL(cpu_present_map);
3805 cpumask_t cpu_online_map = CPU_MASK_ALL;
3806 cpumask_t cpu_possible_map = CPU_MASK_ALL;
3809 long sched_getaffinity(pid_t pid, cpumask_t *mask)
3815 read_lock(&tasklist_lock);
3818 p = find_process_by_pid(pid);
3823 cpus_and(*mask, p->cpus_allowed, cpu_possible_map);
3826 read_unlock(&tasklist_lock);
3827 unlock_cpu_hotplug();
3835 * sys_sched_getaffinity - get the cpu affinity of a process
3836 * @pid: pid of the process
3837 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3838 * @user_mask_ptr: user-space pointer to hold the current cpu mask
3840 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
3841 unsigned long __user *user_mask_ptr)
3846 if (len < sizeof(cpumask_t))
3849 ret = sched_getaffinity(pid, &mask);
3853 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
3856 return sizeof(cpumask_t);
3860 * sys_sched_yield - yield the current processor to other threads.
3862 * this function yields the current CPU by moving the calling thread
3863 * to the expired array. If there are no other threads running on this
3864 * CPU then this function will return.
3866 asmlinkage long sys_sched_yield(void)
3868 runqueue_t *rq = this_rq_lock();
3869 prio_array_t *array = current->array;
3870 prio_array_t *target = rq->expired;
3872 schedstat_inc(rq, yld_cnt);
3874 * We implement yielding by moving the task into the expired
3877 * (special rule: RT tasks will just roundrobin in the active
3880 if (rt_task(current))
3881 target = rq->active;
3883 if (current->array->nr_active == 1) {
3884 schedstat_inc(rq, yld_act_empty);
3885 if (!rq->expired->nr_active)
3886 schedstat_inc(rq, yld_both_empty);
3887 } else if (!rq->expired->nr_active)
3888 schedstat_inc(rq, yld_exp_empty);
3890 if (array != target) {
3891 dequeue_task(current, array);
3892 enqueue_task(current, target);
3895 * requeue_task is cheaper so perform that if possible.
3897 requeue_task(current, array);
3900 * Since we are going to call schedule() anyway, there's
3901 * no need to preempt or enable interrupts:
3903 __release(rq->lock);
3904 _raw_spin_unlock(&rq->lock);
3905 preempt_enable_no_resched();
3912 static inline void __cond_resched(void)
3915 add_preempt_count(PREEMPT_ACTIVE);
3917 sub_preempt_count(PREEMPT_ACTIVE);
3918 } while (need_resched());
3921 int __sched cond_resched(void)
3923 if (need_resched()) {
3930 EXPORT_SYMBOL(cond_resched);
3933 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
3934 * call schedule, and on return reacquire the lock.
3936 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
3937 * operations here to prevent schedule() from being called twice (once via
3938 * spin_unlock(), once by hand).
3940 int cond_resched_lock(spinlock_t * lock)
3942 #if defined(CONFIG_SMP) && defined(CONFIG_PREEMPT)
3943 if (lock->break_lock) {
3944 lock->break_lock = 0;
3950 if (need_resched()) {
3951 _raw_spin_unlock(lock);
3952 preempt_enable_no_resched();
3960 EXPORT_SYMBOL(cond_resched_lock);
3962 int __sched cond_resched_softirq(void)
3964 BUG_ON(!in_softirq());
3966 if (need_resched()) {
3967 __local_bh_enable();
3975 EXPORT_SYMBOL(cond_resched_softirq);
3979 * yield - yield the current processor to other threads.
3981 * this is a shortcut for kernel-space yielding - it marks the
3982 * thread runnable and calls sys_sched_yield().
3984 void __sched yield(void)
3986 set_current_state(TASK_RUNNING);
3990 EXPORT_SYMBOL(yield);
3993 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
3994 * that process accounting knows that this is a task in IO wait state.
3996 * But don't do that if it is a deliberate, throttling IO wait (this task
3997 * has set its backing_dev_info: the queue against which it should throttle)
3999 void __sched io_schedule(void)
4001 struct runqueue *rq = &per_cpu(runqueues, _smp_processor_id());
4003 atomic_inc(&rq->nr_iowait);
4005 atomic_dec(&rq->nr_iowait);
4008 EXPORT_SYMBOL(io_schedule);
4010 long __sched io_schedule_timeout(long timeout)
4012 struct runqueue *rq = &per_cpu(runqueues, _smp_processor_id());
4015 atomic_inc(&rq->nr_iowait);
4016 ret = schedule_timeout(timeout);
4017 atomic_dec(&rq->nr_iowait);
4022 * sys_sched_get_priority_max - return maximum RT priority.
4023 * @policy: scheduling class.
4025 * this syscall returns the maximum rt_priority that can be used
4026 * by a given scheduling class.
4028 asmlinkage long sys_sched_get_priority_max(int policy)
4035 ret = MAX_USER_RT_PRIO-1;
4045 * sys_sched_get_priority_min - return minimum RT priority.
4046 * @policy: scheduling class.
4048 * this syscall returns the minimum rt_priority that can be used
4049 * by a given scheduling class.
4051 asmlinkage long sys_sched_get_priority_min(int policy)
4067 * sys_sched_rr_get_interval - return the default timeslice of a process.
4068 * @pid: pid of the process.
4069 * @interval: userspace pointer to the timeslice value.
4071 * this syscall writes the default timeslice value of a given process
4072 * into the user-space timespec buffer. A value of '0' means infinity.
4075 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4077 int retval = -EINVAL;
4085 read_lock(&tasklist_lock);
4086 p = find_process_by_pid(pid);
4090 retval = security_task_getscheduler(p);
4094 jiffies_to_timespec(p->policy & SCHED_FIFO ?
4095 0 : task_timeslice(p), &t);
4096 read_unlock(&tasklist_lock);
4097 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4101 read_unlock(&tasklist_lock);
4105 static inline struct task_struct *eldest_child(struct task_struct *p)
4107 if (list_empty(&p->children)) return NULL;
4108 return list_entry(p->children.next,struct task_struct,sibling);
4111 static inline struct task_struct *older_sibling(struct task_struct *p)
4113 if (p->sibling.prev==&p->parent->children) return NULL;
4114 return list_entry(p->sibling.prev,struct task_struct,sibling);
4117 static inline struct task_struct *younger_sibling(struct task_struct *p)
4119 if (p->sibling.next==&p->parent->children) return NULL;
4120 return list_entry(p->sibling.next,struct task_struct,sibling);
4123 static void show_task(task_t * p)
4127 unsigned long free = 0;
4128 static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
4130 printk("%-13.13s ", p->comm);
4131 state = p->state ? __ffs(p->state) + 1 : 0;
4132 if (state < ARRAY_SIZE(stat_nam))
4133 printk(stat_nam[state]);
4136 #if (BITS_PER_LONG == 32)
4137 if (state == TASK_RUNNING)
4138 printk(" running ");
4140 printk(" %08lX ", thread_saved_pc(p));
4142 if (state == TASK_RUNNING)
4143 printk(" running task ");
4145 printk(" %016lx ", thread_saved_pc(p));
4147 #ifdef CONFIG_DEBUG_STACK_USAGE
4149 unsigned long * n = (unsigned long *) (p->thread_info+1);
4152 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
4155 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
4156 if ((relative = eldest_child(p)))
4157 printk("%5d ", relative->pid);
4160 if ((relative = younger_sibling(p)))
4161 printk("%7d", relative->pid);
4164 if ((relative = older_sibling(p)))
4165 printk(" %5d", relative->pid);
4169 printk(" (L-TLB)\n");
4171 printk(" (NOTLB)\n");
4173 if (state != TASK_RUNNING)
4174 show_stack(p, NULL);
4177 void show_state(void)
4181 #if (BITS_PER_LONG == 32)
4184 printk(" task PC pid father child younger older\n");
4188 printk(" task PC pid father child younger older\n");
4190 read_lock(&tasklist_lock);
4191 do_each_thread(g, p) {
4193 * reset the NMI-timeout, listing all files on a slow
4194 * console might take alot of time:
4196 touch_nmi_watchdog();
4198 } while_each_thread(g, p);
4200 read_unlock(&tasklist_lock);
4203 void __devinit init_idle(task_t *idle, int cpu)
4205 runqueue_t *rq = cpu_rq(cpu);
4206 unsigned long flags;
4208 idle->sleep_avg = 0;
4210 idle->prio = MAX_PRIO;
4211 idle->state = TASK_RUNNING;
4212 set_task_cpu(idle, cpu);
4214 spin_lock_irqsave(&rq->lock, flags);
4215 rq->curr = rq->idle = idle;
4216 set_tsk_need_resched(idle);
4217 spin_unlock_irqrestore(&rq->lock, flags);
4219 /* Set the preempt count _outside_ the spinlocks! */
4220 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4221 idle->thread_info->preempt_count = (idle->lock_depth >= 0);
4223 idle->thread_info->preempt_count = 0;
4228 * In a system that switches off the HZ timer nohz_cpu_mask
4229 * indicates which cpus entered this state. This is used
4230 * in the rcu update to wait only for active cpus. For system
4231 * which do not switch off the HZ timer nohz_cpu_mask should
4232 * always be CPU_MASK_NONE.
4234 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4238 * This is how migration works:
4240 * 1) we queue a migration_req_t structure in the source CPU's
4241 * runqueue and wake up that CPU's migration thread.
4242 * 2) we down() the locked semaphore => thread blocks.
4243 * 3) migration thread wakes up (implicitly it forces the migrated
4244 * thread off the CPU)
4245 * 4) it gets the migration request and checks whether the migrated
4246 * task is still in the wrong runqueue.
4247 * 5) if it's in the wrong runqueue then the migration thread removes
4248 * it and puts it into the right queue.
4249 * 6) migration thread up()s the semaphore.
4250 * 7) we wake up and the migration is done.
4254 * Change a given task's CPU affinity. Migrate the thread to a
4255 * proper CPU and schedule it away if the CPU it's executing on
4256 * is removed from the allowed bitmask.
4258 * NOTE: the caller must have a valid reference to the task, the
4259 * task must not exit() & deallocate itself prematurely. The
4260 * call is not atomic; no spinlocks may be held.
4262 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
4264 unsigned long flags;
4266 migration_req_t req;
4269 rq = task_rq_lock(p, &flags);
4270 if (!cpus_intersects(new_mask, cpu_online_map)) {
4275 p->cpus_allowed = new_mask;
4276 /* Can the task run on the task's current CPU? If so, we're done */
4277 if (cpu_isset(task_cpu(p), new_mask))
4280 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4281 /* Need help from migration thread: drop lock and wait. */
4282 task_rq_unlock(rq, &flags);
4283 wake_up_process(rq->migration_thread);
4284 wait_for_completion(&req.done);
4285 tlb_migrate_finish(p->mm);
4289 task_rq_unlock(rq, &flags);
4293 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4296 * Move (not current) task off this cpu, onto dest cpu. We're doing
4297 * this because either it can't run here any more (set_cpus_allowed()
4298 * away from this CPU, or CPU going down), or because we're
4299 * attempting to rebalance this task on exec (sched_exec).
4301 * So we race with normal scheduler movements, but that's OK, as long
4302 * as the task is no longer on this CPU.
4304 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4306 runqueue_t *rq_dest, *rq_src;
4308 if (unlikely(cpu_is_offline(dest_cpu)))
4311 rq_src = cpu_rq(src_cpu);
4312 rq_dest = cpu_rq(dest_cpu);
4314 double_rq_lock(rq_src, rq_dest);
4315 /* Already moved. */
4316 if (task_cpu(p) != src_cpu)
4318 /* Affinity changed (again). */
4319 if (!cpu_isset(dest_cpu, p->cpus_allowed))
4322 set_task_cpu(p, dest_cpu);
4325 * Sync timestamp with rq_dest's before activating.
4326 * The same thing could be achieved by doing this step
4327 * afterwards, and pretending it was a local activate.
4328 * This way is cleaner and logically correct.
4330 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4331 + rq_dest->timestamp_last_tick;
4332 deactivate_task(p, rq_src);
4333 activate_task(p, rq_dest, 0);
4334 if (TASK_PREEMPTS_CURR(p, rq_dest))
4335 resched_task(rq_dest->curr);
4339 double_rq_unlock(rq_src, rq_dest);
4343 * migration_thread - this is a highprio system thread that performs
4344 * thread migration by bumping thread off CPU then 'pushing' onto
4347 static int migration_thread(void * data)
4350 int cpu = (long)data;
4353 BUG_ON(rq->migration_thread != current);
4355 set_current_state(TASK_INTERRUPTIBLE);
4356 while (!kthread_should_stop()) {
4357 struct list_head *head;
4358 migration_req_t *req;
4360 if (current->flags & PF_FREEZE)
4361 refrigerator(PF_FREEZE);
4363 spin_lock_irq(&rq->lock);
4365 if (cpu_is_offline(cpu)) {
4366 spin_unlock_irq(&rq->lock);
4370 if (rq->active_balance) {
4371 active_load_balance(rq, cpu);
4372 rq->active_balance = 0;
4375 head = &rq->migration_queue;
4377 if (list_empty(head)) {
4378 spin_unlock_irq(&rq->lock);
4380 set_current_state(TASK_INTERRUPTIBLE);
4383 req = list_entry(head->next, migration_req_t, list);
4384 list_del_init(head->next);
4386 if (req->type == REQ_MOVE_TASK) {
4387 spin_unlock(&rq->lock);
4388 __migrate_task(req->task, cpu, req->dest_cpu);
4390 } else if (req->type == REQ_SET_DOMAIN) {
4392 spin_unlock_irq(&rq->lock);
4394 spin_unlock_irq(&rq->lock);
4398 complete(&req->done);
4400 __set_current_state(TASK_RUNNING);
4404 /* Wait for kthread_stop */
4405 set_current_state(TASK_INTERRUPTIBLE);
4406 while (!kthread_should_stop()) {
4408 set_current_state(TASK_INTERRUPTIBLE);
4410 __set_current_state(TASK_RUNNING);
4414 #ifdef CONFIG_HOTPLUG_CPU
4415 /* Figure out where task on dead CPU should go, use force if neccessary. */
4416 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
4422 mask = node_to_cpumask(cpu_to_node(dead_cpu));
4423 cpus_and(mask, mask, tsk->cpus_allowed);
4424 dest_cpu = any_online_cpu(mask);
4426 /* On any allowed CPU? */
4427 if (dest_cpu == NR_CPUS)
4428 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4430 /* No more Mr. Nice Guy. */
4431 if (dest_cpu == NR_CPUS) {
4432 cpus_setall(tsk->cpus_allowed);
4433 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4436 * Don't tell them about moving exiting tasks or
4437 * kernel threads (both mm NULL), since they never
4440 if (tsk->mm && printk_ratelimit())
4441 printk(KERN_INFO "process %d (%s) no "
4442 "longer affine to cpu%d\n",
4443 tsk->pid, tsk->comm, dead_cpu);
4445 __migrate_task(tsk, dead_cpu, dest_cpu);
4449 * While a dead CPU has no uninterruptible tasks queued at this point,
4450 * it might still have a nonzero ->nr_uninterruptible counter, because
4451 * for performance reasons the counter is not stricly tracking tasks to
4452 * their home CPUs. So we just add the counter to another CPU's counter,
4453 * to keep the global sum constant after CPU-down:
4455 static void migrate_nr_uninterruptible(runqueue_t *rq_src)
4457 runqueue_t *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
4458 unsigned long flags;
4460 local_irq_save(flags);
4461 double_rq_lock(rq_src, rq_dest);
4462 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
4463 rq_src->nr_uninterruptible = 0;
4464 double_rq_unlock(rq_src, rq_dest);
4465 local_irq_restore(flags);
4468 /* Run through task list and migrate tasks from the dead cpu. */
4469 static void migrate_live_tasks(int src_cpu)
4471 struct task_struct *tsk, *t;
4473 write_lock_irq(&tasklist_lock);
4475 do_each_thread(t, tsk) {
4479 if (task_cpu(tsk) == src_cpu)
4480 move_task_off_dead_cpu(src_cpu, tsk);
4481 } while_each_thread(t, tsk);
4483 write_unlock_irq(&tasklist_lock);
4486 /* Schedules idle task to be the next runnable task on current CPU.
4487 * It does so by boosting its priority to highest possible and adding it to
4488 * the _front_ of runqueue. Used by CPU offline code.
4490 void sched_idle_next(void)
4492 int cpu = smp_processor_id();
4493 runqueue_t *rq = this_rq();
4494 struct task_struct *p = rq->idle;
4495 unsigned long flags;
4497 /* cpu has to be offline */
4498 BUG_ON(cpu_online(cpu));
4500 /* Strictly not necessary since rest of the CPUs are stopped by now
4501 * and interrupts disabled on current cpu.
4503 spin_lock_irqsave(&rq->lock, flags);
4505 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4506 /* Add idle task to _front_ of it's priority queue */
4507 __activate_idle_task(p, rq);
4509 spin_unlock_irqrestore(&rq->lock, flags);
4512 /* Ensures that the idle task is using init_mm right before its cpu goes
4515 void idle_task_exit(void)
4517 struct mm_struct *mm = current->active_mm;
4519 BUG_ON(cpu_online(smp_processor_id()));
4522 switch_mm(mm, &init_mm, current);
4526 static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
4528 struct runqueue *rq = cpu_rq(dead_cpu);
4530 /* Must be exiting, otherwise would be on tasklist. */
4531 BUG_ON(tsk->exit_state != EXIT_ZOMBIE && tsk->exit_state != EXIT_DEAD);
4533 /* Cannot have done final schedule yet: would have vanished. */
4534 BUG_ON(tsk->flags & PF_DEAD);
4536 get_task_struct(tsk);
4539 * Drop lock around migration; if someone else moves it,
4540 * that's OK. No task can be added to this CPU, so iteration is
4543 spin_unlock_irq(&rq->lock);
4544 move_task_off_dead_cpu(dead_cpu, tsk);
4545 spin_lock_irq(&rq->lock);
4547 put_task_struct(tsk);
4550 /* release_task() removes task from tasklist, so we won't find dead tasks. */
4551 static void migrate_dead_tasks(unsigned int dead_cpu)
4554 struct runqueue *rq = cpu_rq(dead_cpu);
4556 for (arr = 0; arr < 2; arr++) {
4557 for (i = 0; i < MAX_PRIO; i++) {
4558 struct list_head *list = &rq->arrays[arr].queue[i];
4559 while (!list_empty(list))
4560 migrate_dead(dead_cpu,
4561 list_entry(list->next, task_t,
4566 #endif /* CONFIG_HOTPLUG_CPU */
4569 * migration_call - callback that gets triggered when a CPU is added.
4570 * Here we can start up the necessary migration thread for the new CPU.
4572 static int migration_call(struct notifier_block *nfb, unsigned long action,
4575 int cpu = (long)hcpu;
4576 struct task_struct *p;
4577 struct runqueue *rq;
4578 unsigned long flags;
4581 case CPU_UP_PREPARE:
4582 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4585 p->flags |= PF_NOFREEZE;
4586 kthread_bind(p, cpu);
4587 /* Must be high prio: stop_machine expects to yield to it. */
4588 rq = task_rq_lock(p, &flags);
4589 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4590 task_rq_unlock(rq, &flags);
4591 cpu_rq(cpu)->migration_thread = p;
4594 /* Strictly unneccessary, as first user will wake it. */
4595 wake_up_process(cpu_rq(cpu)->migration_thread);
4597 #ifdef CONFIG_HOTPLUG_CPU
4598 case CPU_UP_CANCELED:
4599 /* Unbind it from offline cpu so it can run. Fall thru. */
4600 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
4601 kthread_stop(cpu_rq(cpu)->migration_thread);
4602 cpu_rq(cpu)->migration_thread = NULL;
4605 migrate_live_tasks(cpu);
4607 kthread_stop(rq->migration_thread);
4608 rq->migration_thread = NULL;
4609 /* Idle task back to normal (off runqueue, low prio) */
4610 rq = task_rq_lock(rq->idle, &flags);
4611 deactivate_task(rq->idle, rq);
4612 rq->idle->static_prio = MAX_PRIO;
4613 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4614 migrate_dead_tasks(cpu);
4615 task_rq_unlock(rq, &flags);
4616 migrate_nr_uninterruptible(rq);
4617 BUG_ON(rq->nr_running != 0);
4619 /* No need to migrate the tasks: it was best-effort if
4620 * they didn't do lock_cpu_hotplug(). Just wake up
4621 * the requestors. */
4622 spin_lock_irq(&rq->lock);
4623 while (!list_empty(&rq->migration_queue)) {
4624 migration_req_t *req;
4625 req = list_entry(rq->migration_queue.next,
4626 migration_req_t, list);
4627 BUG_ON(req->type != REQ_MOVE_TASK);
4628 list_del_init(&req->list);
4629 complete(&req->done);
4631 spin_unlock_irq(&rq->lock);
4638 /* Register at highest priority so that task migration (migrate_all_tasks)
4639 * happens before everything else.
4641 static struct notifier_block __devinitdata migration_notifier = {
4642 .notifier_call = migration_call,
4646 int __init migration_init(void)
4648 void *cpu = (void *)(long)smp_processor_id();
4649 /* Start one for boot CPU. */
4650 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4651 migration_call(&migration_notifier, CPU_ONLINE, cpu);
4652 register_cpu_notifier(&migration_notifier);
4658 #define SCHED_DOMAIN_DEBUG
4659 #ifdef SCHED_DOMAIN_DEBUG
4660 static void sched_domain_debug(struct sched_domain *sd, int cpu)
4664 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
4669 struct sched_group *group = sd->groups;
4670 cpumask_t groupmask;
4672 cpumask_scnprintf(str, NR_CPUS, sd->span);
4673 cpus_clear(groupmask);
4676 for (i = 0; i < level + 1; i++)
4678 printk("domain %d: ", level);
4680 if (!(sd->flags & SD_LOAD_BALANCE)) {
4681 printk("does not load-balance\n");
4683 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
4687 printk("span %s\n", str);
4689 if (!cpu_isset(cpu, sd->span))
4690 printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
4691 if (!cpu_isset(cpu, group->cpumask))
4692 printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
4695 for (i = 0; i < level + 2; i++)
4701 printk(KERN_ERR "ERROR: group is NULL\n");
4705 if (!group->cpu_power) {
4707 printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
4710 if (!cpus_weight(group->cpumask)) {
4712 printk(KERN_ERR "ERROR: empty group\n");
4715 if (cpus_intersects(groupmask, group->cpumask)) {
4717 printk(KERN_ERR "ERROR: repeated CPUs\n");
4720 cpus_or(groupmask, groupmask, group->cpumask);
4722 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
4725 group = group->next;
4726 } while (group != sd->groups);
4729 if (!cpus_equal(sd->span, groupmask))
4730 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
4736 if (!cpus_subset(groupmask, sd->span))
4737 printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
4743 #define sched_domain_debug(sd, cpu) {}
4747 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
4748 * hold the hotplug lock.
4750 void __devinit cpu_attach_domain(struct sched_domain *sd, int cpu)
4752 migration_req_t req;
4753 unsigned long flags;
4754 runqueue_t *rq = cpu_rq(cpu);
4757 sched_domain_debug(sd, cpu);
4759 spin_lock_irqsave(&rq->lock, flags);
4761 if (cpu == smp_processor_id() || !cpu_online(cpu)) {
4764 init_completion(&req.done);
4765 req.type = REQ_SET_DOMAIN;
4767 list_add(&req.list, &rq->migration_queue);
4771 spin_unlock_irqrestore(&rq->lock, flags);
4774 wake_up_process(rq->migration_thread);
4775 wait_for_completion(&req.done);
4779 /* cpus with isolated domains */
4780 cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
4782 /* Setup the mask of cpus configured for isolated domains */
4783 static int __init isolated_cpu_setup(char *str)
4785 int ints[NR_CPUS], i;
4787 str = get_options(str, ARRAY_SIZE(ints), ints);
4788 cpus_clear(cpu_isolated_map);
4789 for (i = 1; i <= ints[0]; i++)
4790 if (ints[i] < NR_CPUS)
4791 cpu_set(ints[i], cpu_isolated_map);
4795 __setup ("isolcpus=", isolated_cpu_setup);
4798 * init_sched_build_groups takes an array of groups, the cpumask we wish
4799 * to span, and a pointer to a function which identifies what group a CPU
4800 * belongs to. The return value of group_fn must be a valid index into the
4801 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
4802 * keep track of groups covered with a cpumask_t).
4804 * init_sched_build_groups will build a circular linked list of the groups
4805 * covered by the given span, and will set each group's ->cpumask correctly,
4806 * and ->cpu_power to 0.
4808 void __devinit init_sched_build_groups(struct sched_group groups[],
4809 cpumask_t span, int (*group_fn)(int cpu))
4811 struct sched_group *first = NULL, *last = NULL;
4812 cpumask_t covered = CPU_MASK_NONE;
4815 for_each_cpu_mask(i, span) {
4816 int group = group_fn(i);
4817 struct sched_group *sg = &groups[group];
4820 if (cpu_isset(i, covered))
4823 sg->cpumask = CPU_MASK_NONE;
4826 for_each_cpu_mask(j, span) {
4827 if (group_fn(j) != group)
4830 cpu_set(j, covered);
4831 cpu_set(j, sg->cpumask);
4843 #ifdef ARCH_HAS_SCHED_DOMAIN
4844 extern void __devinit arch_init_sched_domains(void);
4845 extern void __devinit arch_destroy_sched_domains(void);
4847 #ifdef CONFIG_SCHED_SMT
4848 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
4849 static struct sched_group sched_group_cpus[NR_CPUS];
4850 static int __devinit cpu_to_cpu_group(int cpu)
4856 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
4857 static struct sched_group sched_group_phys[NR_CPUS];
4858 static int __devinit cpu_to_phys_group(int cpu)
4860 #ifdef CONFIG_SCHED_SMT
4861 return first_cpu(cpu_sibling_map[cpu]);
4869 static DEFINE_PER_CPU(struct sched_domain, node_domains);
4870 static struct sched_group sched_group_nodes[MAX_NUMNODES];
4871 static int __devinit cpu_to_node_group(int cpu)
4873 return cpu_to_node(cpu);
4877 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
4879 * The domains setup code relies on siblings not spanning
4880 * multiple nodes. Make sure the architecture has a proper
4883 static void check_sibling_maps(void)
4887 for_each_online_cpu(i) {
4888 for_each_cpu_mask(j, cpu_sibling_map[i]) {
4889 if (cpu_to_node(i) != cpu_to_node(j)) {
4890 printk(KERN_INFO "warning: CPU %d siblings map "
4891 "to different node - isolating "
4893 cpu_sibling_map[i] = cpumask_of_cpu(i);
4902 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
4904 static void __devinit arch_init_sched_domains(void)
4907 cpumask_t cpu_default_map;
4909 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
4910 check_sibling_maps();
4913 * Setup mask for cpus without special case scheduling requirements.
4914 * For now this just excludes isolated cpus, but could be used to
4915 * exclude other special cases in the future.
4917 cpus_complement(cpu_default_map, cpu_isolated_map);
4918 cpus_and(cpu_default_map, cpu_default_map, cpu_online_map);
4921 * Set up domains. Isolated domains just stay on the dummy domain.
4923 for_each_cpu_mask(i, cpu_default_map) {
4925 struct sched_domain *sd = NULL, *p;
4926 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
4928 cpus_and(nodemask, nodemask, cpu_default_map);
4931 sd = &per_cpu(node_domains, i);
4932 group = cpu_to_node_group(i);
4934 sd->span = cpu_default_map;
4935 sd->groups = &sched_group_nodes[group];
4939 sd = &per_cpu(phys_domains, i);
4940 group = cpu_to_phys_group(i);
4942 sd->span = nodemask;
4944 sd->groups = &sched_group_phys[group];
4946 #ifdef CONFIG_SCHED_SMT
4948 sd = &per_cpu(cpu_domains, i);
4949 group = cpu_to_cpu_group(i);
4950 *sd = SD_SIBLING_INIT;
4951 sd->span = cpu_sibling_map[i];
4952 cpus_and(sd->span, sd->span, cpu_default_map);
4954 sd->groups = &sched_group_cpus[group];
4958 #ifdef CONFIG_SCHED_SMT
4959 /* Set up CPU (sibling) groups */
4960 for_each_online_cpu(i) {
4961 cpumask_t this_sibling_map = cpu_sibling_map[i];
4962 cpus_and(this_sibling_map, this_sibling_map, cpu_default_map);
4963 if (i != first_cpu(this_sibling_map))
4966 init_sched_build_groups(sched_group_cpus, this_sibling_map,
4971 /* Set up physical groups */
4972 for (i = 0; i < MAX_NUMNODES; i++) {
4973 cpumask_t nodemask = node_to_cpumask(i);
4975 cpus_and(nodemask, nodemask, cpu_default_map);
4976 if (cpus_empty(nodemask))
4979 init_sched_build_groups(sched_group_phys, nodemask,
4980 &cpu_to_phys_group);
4984 /* Set up node groups */
4985 init_sched_build_groups(sched_group_nodes, cpu_default_map,
4986 &cpu_to_node_group);
4989 /* Calculate CPU power for physical packages and nodes */
4990 for_each_cpu_mask(i, cpu_default_map) {
4992 struct sched_domain *sd;
4993 #ifdef CONFIG_SCHED_SMT
4994 sd = &per_cpu(cpu_domains, i);
4995 power = SCHED_LOAD_SCALE;
4996 sd->groups->cpu_power = power;
4999 sd = &per_cpu(phys_domains, i);
5000 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
5001 (cpus_weight(sd->groups->cpumask)-1) / 10;
5002 sd->groups->cpu_power = power;
5005 if (i == first_cpu(sd->groups->cpumask)) {
5006 /* Only add "power" once for each physical package. */
5007 sd = &per_cpu(node_domains, i);
5008 sd->groups->cpu_power += power;
5013 /* Attach the domains */
5014 for_each_online_cpu(i) {
5015 struct sched_domain *sd;
5016 #ifdef CONFIG_SCHED_SMT
5017 sd = &per_cpu(cpu_domains, i);
5019 sd = &per_cpu(phys_domains, i);
5021 cpu_attach_domain(sd, i);
5025 #ifdef CONFIG_HOTPLUG_CPU
5026 static void __devinit arch_destroy_sched_domains(void)
5028 /* Do nothing: everything is statically allocated. */
5032 #endif /* ARCH_HAS_SCHED_DOMAIN */
5035 * Initial dummy domain for early boot and for hotplug cpu. Being static,
5036 * it is initialized to zero, so all balancing flags are cleared which is
5039 static struct sched_domain sched_domain_dummy;
5041 #ifdef CONFIG_HOTPLUG_CPU
5043 * Force a reinitialization of the sched domains hierarchy. The domains
5044 * and groups cannot be updated in place without racing with the balancing
5045 * code, so we temporarily attach all running cpus to a "dummy" domain
5046 * which will prevent rebalancing while the sched domains are recalculated.
5048 static int update_sched_domains(struct notifier_block *nfb,
5049 unsigned long action, void *hcpu)
5054 case CPU_UP_PREPARE:
5055 case CPU_DOWN_PREPARE:
5056 for_each_online_cpu(i)
5057 cpu_attach_domain(&sched_domain_dummy, i);
5058 arch_destroy_sched_domains();
5061 case CPU_UP_CANCELED:
5062 case CPU_DOWN_FAILED:
5066 * Fall through and re-initialise the domains.
5073 /* The hotplug lock is already held by cpu_up/cpu_down */
5074 arch_init_sched_domains();
5080 void __init sched_init_smp(void)
5083 arch_init_sched_domains();
5084 unlock_cpu_hotplug();
5085 /* XXX: Theoretical race here - CPU may be hotplugged now */
5086 hotcpu_notifier(update_sched_domains, 0);
5089 void __init sched_init_smp(void)
5092 #endif /* CONFIG_SMP */
5094 int in_sched_functions(unsigned long addr)
5096 /* Linker adds these: start and end of __sched functions */
5097 extern char __sched_text_start[], __sched_text_end[];
5098 return in_lock_functions(addr) ||
5099 (addr >= (unsigned long)__sched_text_start
5100 && addr < (unsigned long)__sched_text_end);
5103 void __init sched_init(void)
5108 for (i = 0; i < NR_CPUS; i++) {
5109 prio_array_t *array;
5112 spin_lock_init(&rq->lock);
5113 rq->active = rq->arrays;
5114 rq->expired = rq->arrays + 1;
5115 rq->best_expired_prio = MAX_PRIO;
5118 rq->sd = &sched_domain_dummy;
5120 rq->active_balance = 0;
5122 rq->migration_thread = NULL;
5123 INIT_LIST_HEAD(&rq->migration_queue);
5125 atomic_set(&rq->nr_iowait, 0);
5126 #ifdef CONFIG_VSERVER_HARDCPU
5127 INIT_LIST_HEAD(&rq->hold_queue);
5130 for (j = 0; j < 2; j++) {
5131 array = rq->arrays + j;
5132 for (k = 0; k < MAX_PRIO; k++) {
5133 INIT_LIST_HEAD(array->queue + k);
5134 __clear_bit(k, array->bitmap);
5136 // delimiter for bitsearch
5137 __set_bit(MAX_PRIO, array->bitmap);
5142 * The boot idle thread does lazy MMU switching as well:
5144 atomic_inc(&init_mm.mm_count);
5145 enter_lazy_tlb(&init_mm, current);
5148 * Make us the idle thread. Technically, schedule() should not be
5149 * called from this thread, however somewhere below it might be,
5150 * but because we are the idle thread, we just pick up running again
5151 * when this runqueue becomes "idle".
5153 init_idle(current, smp_processor_id());
5156 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5157 void __might_sleep(char *file, int line)
5159 #if defined(in_atomic)
5160 static unsigned long prev_jiffy; /* ratelimiting */
5162 if ((in_atomic() || irqs_disabled()) &&
5163 system_state == SYSTEM_RUNNING && !oops_in_progress) {
5164 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
5166 prev_jiffy = jiffies;
5167 printk(KERN_ERR "Debug: sleeping function called from invalid"
5168 " context at %s:%d\n", file, line);
5169 printk("in_atomic():%d, irqs_disabled():%d\n",
5170 in_atomic(), irqs_disabled());
5175 EXPORT_SYMBOL(__might_sleep);
5178 #ifdef CONFIG_MAGIC_SYSRQ
5179 void normalize_rt_tasks(void)
5181 struct task_struct *p;
5182 prio_array_t *array;
5183 unsigned long flags;
5186 read_lock_irq(&tasklist_lock);
5187 for_each_process (p) {
5191 rq = task_rq_lock(p, &flags);
5195 deactivate_task(p, task_rq(p));
5196 __setscheduler(p, SCHED_NORMAL, 0);
5198 vx_activate_task(p);
5199 __activate_task(p, task_rq(p));
5200 resched_task(rq->curr);
5203 task_rq_unlock(rq, &flags);
5205 read_unlock_irq(&tasklist_lock);
5208 #endif /* CONFIG_MAGIC_SYSRQ */