[PATCH] actual mailing list in MAINTAINERS
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / kernel / sched.c
blobe9a0b61f12ab3c2679e283f5c0ed26a18d9bbabb
1 /*
2 * kernel/sched.c
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
11 * by Andrea Arcangeli
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
21 #include <linux/mm.h>
22 #include <linux/module.h>
23 #include <linux/nmi.h>
24 #include <linux/init.h>
25 #include <asm/uaccess.h>
26 #include <linux/highmem.h>
27 #include <linux/smp_lock.h>
28 #include <asm/mmu_context.h>
29 #include <linux/interrupt.h>
30 #include <linux/capability.h>
31 #include <linux/completion.h>
32 #include <linux/kernel_stat.h>
33 #include <linux/debug_locks.h>
34 #include <linux/security.h>
35 #include <linux/notifier.h>
36 #include <linux/profile.h>
37 #include <linux/suspend.h>
38 #include <linux/vmalloc.h>
39 #include <linux/blkdev.h>
40 #include <linux/delay.h>
41 #include <linux/smp.h>
42 #include <linux/threads.h>
43 #include <linux/timer.h>
44 #include <linux/rcupdate.h>
45 #include <linux/cpu.h>
46 #include <linux/cpuset.h>
47 #include <linux/percpu.h>
48 #include <linux/kthread.h>
49 #include <linux/seq_file.h>
50 #include <linux/syscalls.h>
51 #include <linux/times.h>
52 #include <linux/acct.h>
53 #include <linux/kprobes.h>
54 #include <asm/tlb.h>
56 #include <asm/unistd.h>
59 * Convert user-nice values [ -20 ... 0 ... 19 ]
60 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
61 * and back.
63 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
64 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
65 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
68 * 'User priority' is the nice value converted to something we
69 * can work with better when scaling various scheduler parameters,
70 * it's a [ 0 ... 39 ] range.
72 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
73 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
74 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
77 * Some helpers for converting nanosecond timing to jiffy resolution
79 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
80 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
83 * These are the 'tuning knobs' of the scheduler:
85 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
86 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
87 * Timeslices get refilled after they expire.
89 #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
90 #define DEF_TIMESLICE (100 * HZ / 1000)
91 #define ON_RUNQUEUE_WEIGHT 30
92 #define CHILD_PENALTY 95
93 #define PARENT_PENALTY 100
94 #define EXIT_WEIGHT 3
95 #define PRIO_BONUS_RATIO 25
96 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
97 #define INTERACTIVE_DELTA 2
98 #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
99 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
100 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
103 * If a task is 'interactive' then we reinsert it in the active
104 * array after it has expired its current timeslice. (it will not
105 * continue to run immediately, it will still roundrobin with
106 * other interactive tasks.)
108 * This part scales the interactivity limit depending on niceness.
110 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
111 * Here are a few examples of different nice levels:
113 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
114 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
115 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
116 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
117 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
119 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
120 * priority range a task can explore, a value of '1' means the
121 * task is rated interactive.)
123 * Ie. nice +19 tasks can never get 'interactive' enough to be
124 * reinserted into the active array. And only heavily CPU-hog nice -20
125 * tasks will be expired. Default nice 0 tasks are somewhere between,
126 * it takes some effort for them to get interactive, but it's not
127 * too hard.
130 #define CURRENT_BONUS(p) \
131 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
132 MAX_SLEEP_AVG)
134 #define GRANULARITY (10 * HZ / 1000 ? : 1)
136 #ifdef CONFIG_SMP
137 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
138 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
139 num_online_cpus())
140 #else
141 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
142 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
143 #endif
145 #define SCALE(v1,v1_max,v2_max) \
146 (v1) * (v2_max) / (v1_max)
148 #define DELTA(p) \
149 (SCALE(TASK_NICE(p) + 20, 40, MAX_BONUS) - 20 * MAX_BONUS / 40 + \
150 INTERACTIVE_DELTA)
152 #define TASK_INTERACTIVE(p) \
153 ((p)->prio <= (p)->static_prio - DELTA(p))
155 #define INTERACTIVE_SLEEP(p) \
156 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
157 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
159 #define TASK_PREEMPTS_CURR(p, rq) \
160 ((p)->prio < (rq)->curr->prio)
163 * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
164 * to time slice values: [800ms ... 100ms ... 5ms]
166 * The higher a thread's priority, the bigger timeslices
167 * it gets during one round of execution. But even the lowest
168 * priority thread gets MIN_TIMESLICE worth of execution time.
171 #define SCALE_PRIO(x, prio) \
172 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO / 2), MIN_TIMESLICE)
174 static unsigned int static_prio_timeslice(int static_prio)
176 if (static_prio < NICE_TO_PRIO(0))
177 return SCALE_PRIO(DEF_TIMESLICE * 4, static_prio);
178 else
179 return SCALE_PRIO(DEF_TIMESLICE, static_prio);
182 static inline unsigned int task_timeslice(struct task_struct *p)
184 return static_prio_timeslice(p->static_prio);
188 * These are the runqueue data structures:
191 struct prio_array {
192 unsigned int nr_active;
193 DECLARE_BITMAP(bitmap, MAX_PRIO+1); /* include 1 bit for delimiter */
194 struct list_head queue[MAX_PRIO];
198 * This is the main, per-CPU runqueue data structure.
200 * Locking rule: those places that want to lock multiple runqueues
201 * (such as the load balancing or the thread migration code), lock
202 * acquire operations must be ordered by ascending &runqueue.
204 struct rq {
205 spinlock_t lock;
208 * nr_running and cpu_load should be in the same cacheline because
209 * remote CPUs use both these fields when doing load calculation.
211 unsigned long nr_running;
212 unsigned long raw_weighted_load;
213 #ifdef CONFIG_SMP
214 unsigned long cpu_load[3];
215 #endif
216 unsigned long long nr_switches;
219 * This is part of a global counter where only the total sum
220 * over all CPUs matters. A task can increase this counter on
221 * one CPU and if it got migrated afterwards it may decrease
222 * it on another CPU. Always updated under the runqueue lock:
224 unsigned long nr_uninterruptible;
226 unsigned long expired_timestamp;
227 unsigned long long timestamp_last_tick;
228 struct task_struct *curr, *idle;
229 struct mm_struct *prev_mm;
230 struct prio_array *active, *expired, arrays[2];
231 int best_expired_prio;
232 atomic_t nr_iowait;
234 #ifdef CONFIG_SMP
235 struct sched_domain *sd;
237 /* For active balancing */
238 int active_balance;
239 int push_cpu;
241 struct task_struct *migration_thread;
242 struct list_head migration_queue;
243 #endif
245 #ifdef CONFIG_SCHEDSTATS
246 /* latency stats */
247 struct sched_info rq_sched_info;
249 /* sys_sched_yield() stats */
250 unsigned long yld_exp_empty;
251 unsigned long yld_act_empty;
252 unsigned long yld_both_empty;
253 unsigned long yld_cnt;
255 /* schedule() stats */
256 unsigned long sched_switch;
257 unsigned long sched_cnt;
258 unsigned long sched_goidle;
260 /* try_to_wake_up() stats */
261 unsigned long ttwu_cnt;
262 unsigned long ttwu_local;
263 #endif
264 struct lock_class_key rq_lock_key;
267 static DEFINE_PER_CPU(struct rq, runqueues);
270 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
271 * See detach_destroy_domains: synchronize_sched for details.
273 * The domain tree of any CPU may only be accessed from within
274 * preempt-disabled sections.
276 #define for_each_domain(cpu, __sd) \
277 for (__sd = rcu_dereference(cpu_rq(cpu)->sd); __sd; __sd = __sd->parent)
279 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
280 #define this_rq() (&__get_cpu_var(runqueues))
281 #define task_rq(p) cpu_rq(task_cpu(p))
282 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
284 #ifndef prepare_arch_switch
285 # define prepare_arch_switch(next) do { } while (0)
286 #endif
287 #ifndef finish_arch_switch
288 # define finish_arch_switch(prev) do { } while (0)
289 #endif
291 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
292 static inline int task_running(struct rq *rq, struct task_struct *p)
294 return rq->curr == p;
297 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
301 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
303 #ifdef CONFIG_DEBUG_SPINLOCK
304 /* this is a valid case when another task releases the spinlock */
305 rq->lock.owner = current;
306 #endif
308 * If we are tracking spinlock dependencies then we have to
309 * fix up the runqueue lock - which gets 'carried over' from
310 * prev into current:
312 spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
314 spin_unlock_irq(&rq->lock);
317 #else /* __ARCH_WANT_UNLOCKED_CTXSW */
318 static inline int task_running(struct rq *rq, struct task_struct *p)
320 #ifdef CONFIG_SMP
321 return p->oncpu;
322 #else
323 return rq->curr == p;
324 #endif
327 static inline void prepare_lock_switch(struct rq *rq, struct task_struct *next)
329 #ifdef CONFIG_SMP
331 * We can optimise this out completely for !SMP, because the
332 * SMP rebalancing from interrupt is the only thing that cares
333 * here.
335 next->oncpu = 1;
336 #endif
337 #ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
338 spin_unlock_irq(&rq->lock);
339 #else
340 spin_unlock(&rq->lock);
341 #endif
344 static inline void finish_lock_switch(struct rq *rq, struct task_struct *prev)
346 #ifdef CONFIG_SMP
348 * After ->oncpu is cleared, the task can be moved to a different CPU.
349 * We must ensure this doesn't happen until the switch is completely
350 * finished.
352 smp_wmb();
353 prev->oncpu = 0;
354 #endif
355 #ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
356 local_irq_enable();
357 #endif
359 #endif /* __ARCH_WANT_UNLOCKED_CTXSW */
362 * __task_rq_lock - lock the runqueue a given task resides on.
363 * Must be called interrupts disabled.
365 static inline struct rq *__task_rq_lock(struct task_struct *p)
366 __acquires(rq->lock)
368 struct rq *rq;
370 repeat_lock_task:
371 rq = task_rq(p);
372 spin_lock(&rq->lock);
373 if (unlikely(rq != task_rq(p))) {
374 spin_unlock(&rq->lock);
375 goto repeat_lock_task;
377 return rq;
381 * task_rq_lock - lock the runqueue a given task resides on and disable
382 * interrupts. Note the ordering: we can safely lookup the task_rq without
383 * explicitly disabling preemption.
385 static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags)
386 __acquires(rq->lock)
388 struct rq *rq;
390 repeat_lock_task:
391 local_irq_save(*flags);
392 rq = task_rq(p);
393 spin_lock(&rq->lock);
394 if (unlikely(rq != task_rq(p))) {
395 spin_unlock_irqrestore(&rq->lock, *flags);
396 goto repeat_lock_task;
398 return rq;
401 static inline void __task_rq_unlock(struct rq *rq)
402 __releases(rq->lock)
404 spin_unlock(&rq->lock);
407 static inline void task_rq_unlock(struct rq *rq, unsigned long *flags)
408 __releases(rq->lock)
410 spin_unlock_irqrestore(&rq->lock, *flags);
413 #ifdef CONFIG_SCHEDSTATS
415 * bump this up when changing the output format or the meaning of an existing
416 * format, so that tools can adapt (or abort)
418 #define SCHEDSTAT_VERSION 12
420 static int show_schedstat(struct seq_file *seq, void *v)
422 int cpu;
424 seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
425 seq_printf(seq, "timestamp %lu\n", jiffies);
426 for_each_online_cpu(cpu) {
427 struct rq *rq = cpu_rq(cpu);
428 #ifdef CONFIG_SMP
429 struct sched_domain *sd;
430 int dcnt = 0;
431 #endif
433 /* runqueue-specific stats */
434 seq_printf(seq,
435 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
436 cpu, rq->yld_both_empty,
437 rq->yld_act_empty, rq->yld_exp_empty, rq->yld_cnt,
438 rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
439 rq->ttwu_cnt, rq->ttwu_local,
440 rq->rq_sched_info.cpu_time,
441 rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
443 seq_printf(seq, "\n");
445 #ifdef CONFIG_SMP
446 /* domain-specific stats */
447 preempt_disable();
448 for_each_domain(cpu, sd) {
449 enum idle_type itype;
450 char mask_str[NR_CPUS];
452 cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
453 seq_printf(seq, "domain%d %s", dcnt++, mask_str);
454 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
455 itype++) {
456 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu",
457 sd->lb_cnt[itype],
458 sd->lb_balanced[itype],
459 sd->lb_failed[itype],
460 sd->lb_imbalance[itype],
461 sd->lb_gained[itype],
462 sd->lb_hot_gained[itype],
463 sd->lb_nobusyq[itype],
464 sd->lb_nobusyg[itype]);
466 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
467 sd->alb_cnt, sd->alb_failed, sd->alb_pushed,
468 sd->sbe_cnt, sd->sbe_balanced, sd->sbe_pushed,
469 sd->sbf_cnt, sd->sbf_balanced, sd->sbf_pushed,
470 sd->ttwu_wake_remote, sd->ttwu_move_affine, sd->ttwu_move_balance);
472 preempt_enable();
473 #endif
475 return 0;
478 static int schedstat_open(struct inode *inode, struct file *file)
480 unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
481 char *buf = kmalloc(size, GFP_KERNEL);
482 struct seq_file *m;
483 int res;
485 if (!buf)
486 return -ENOMEM;
487 res = single_open(file, show_schedstat, NULL);
488 if (!res) {
489 m = file->private_data;
490 m->buf = buf;
491 m->size = size;
492 } else
493 kfree(buf);
494 return res;
497 struct file_operations proc_schedstat_operations = {
498 .open = schedstat_open,
499 .read = seq_read,
500 .llseek = seq_lseek,
501 .release = single_release,
504 # define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
505 # define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
506 #else /* !CONFIG_SCHEDSTATS */
507 # define schedstat_inc(rq, field) do { } while (0)
508 # define schedstat_add(rq, field, amt) do { } while (0)
509 #endif
512 * rq_lock - lock a given runqueue and disable interrupts.
514 static inline struct rq *this_rq_lock(void)
515 __acquires(rq->lock)
517 struct rq *rq;
519 local_irq_disable();
520 rq = this_rq();
521 spin_lock(&rq->lock);
523 return rq;
526 #ifdef CONFIG_SCHEDSTATS
528 * Called when a process is dequeued from the active array and given
529 * the cpu. We should note that with the exception of interactive
530 * tasks, the expired queue will become the active queue after the active
531 * queue is empty, without explicitly dequeuing and requeuing tasks in the
532 * expired queue. (Interactive tasks may be requeued directly to the
533 * active queue, thus delaying tasks in the expired queue from running;
534 * see scheduler_tick()).
536 * This function is only called from sched_info_arrive(), rather than
537 * dequeue_task(). Even though a task may be queued and dequeued multiple
538 * times as it is shuffled about, we're really interested in knowing how
539 * long it was from the *first* time it was queued to the time that it
540 * finally hit a cpu.
542 static inline void sched_info_dequeued(struct task_struct *t)
544 t->sched_info.last_queued = 0;
548 * Called when a task finally hits the cpu. We can now calculate how
549 * long it was waiting to run. We also note when it began so that we
550 * can keep stats on how long its timeslice is.
552 static void sched_info_arrive(struct task_struct *t)
554 unsigned long now = jiffies, diff = 0;
555 struct rq *rq = task_rq(t);
557 if (t->sched_info.last_queued)
558 diff = now - t->sched_info.last_queued;
559 sched_info_dequeued(t);
560 t->sched_info.run_delay += diff;
561 t->sched_info.last_arrival = now;
562 t->sched_info.pcnt++;
564 if (!rq)
565 return;
567 rq->rq_sched_info.run_delay += diff;
568 rq->rq_sched_info.pcnt++;
572 * Called when a process is queued into either the active or expired
573 * array. The time is noted and later used to determine how long we
574 * had to wait for us to reach the cpu. Since the expired queue will
575 * become the active queue after active queue is empty, without dequeuing
576 * and requeuing any tasks, we are interested in queuing to either. It
577 * is unusual but not impossible for tasks to be dequeued and immediately
578 * requeued in the same or another array: this can happen in sched_yield(),
579 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
580 * to runqueue.
582 * This function is only called from enqueue_task(), but also only updates
583 * the timestamp if it is already not set. It's assumed that
584 * sched_info_dequeued() will clear that stamp when appropriate.
586 static inline void sched_info_queued(struct task_struct *t)
588 if (!t->sched_info.last_queued)
589 t->sched_info.last_queued = jiffies;
593 * Called when a process ceases being the active-running process, either
594 * voluntarily or involuntarily. Now we can calculate how long we ran.
596 static inline void sched_info_depart(struct task_struct *t)
598 struct rq *rq = task_rq(t);
599 unsigned long diff = jiffies - t->sched_info.last_arrival;
601 t->sched_info.cpu_time += diff;
603 if (rq)
604 rq->rq_sched_info.cpu_time += diff;
608 * Called when tasks are switched involuntarily due, typically, to expiring
609 * their time slice. (This may also be called when switching to or from
610 * the idle task.) We are only called when prev != next.
612 static inline void
613 sched_info_switch(struct task_struct *prev, struct task_struct *next)
615 struct rq *rq = task_rq(prev);
618 * prev now departs the cpu. It's not interesting to record
619 * stats about how efficient we were at scheduling the idle
620 * process, however.
622 if (prev != rq->idle)
623 sched_info_depart(prev);
625 if (next != rq->idle)
626 sched_info_arrive(next);
628 #else
629 #define sched_info_queued(t) do { } while (0)
630 #define sched_info_switch(t, next) do { } while (0)
631 #endif /* CONFIG_SCHEDSTATS */
634 * Adding/removing a task to/from a priority array:
636 static void dequeue_task(struct task_struct *p, struct prio_array *array)
638 array->nr_active--;
639 list_del(&p->run_list);
640 if (list_empty(array->queue + p->prio))
641 __clear_bit(p->prio, array->bitmap);
644 static void enqueue_task(struct task_struct *p, struct prio_array *array)
646 sched_info_queued(p);
647 list_add_tail(&p->run_list, array->queue + p->prio);
648 __set_bit(p->prio, array->bitmap);
649 array->nr_active++;
650 p->array = array;
654 * Put task to the end of the run list without the overhead of dequeue
655 * followed by enqueue.
657 static void requeue_task(struct task_struct *p, struct prio_array *array)
659 list_move_tail(&p->run_list, array->queue + p->prio);
662 static inline void
663 enqueue_task_head(struct task_struct *p, struct prio_array *array)
665 list_add(&p->run_list, array->queue + p->prio);
666 __set_bit(p->prio, array->bitmap);
667 array->nr_active++;
668 p->array = array;
672 * __normal_prio - return the priority that is based on the static
673 * priority but is modified by bonuses/penalties.
675 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
676 * into the -5 ... 0 ... +5 bonus/penalty range.
678 * We use 25% of the full 0...39 priority range so that:
680 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
681 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
683 * Both properties are important to certain workloads.
686 static inline int __normal_prio(struct task_struct *p)
688 int bonus, prio;
690 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
692 prio = p->static_prio - bonus;
693 if (prio < MAX_RT_PRIO)
694 prio = MAX_RT_PRIO;
695 if (prio > MAX_PRIO-1)
696 prio = MAX_PRIO-1;
697 return prio;
701 * To aid in avoiding the subversion of "niceness" due to uneven distribution
702 * of tasks with abnormal "nice" values across CPUs the contribution that
703 * each task makes to its run queue's load is weighted according to its
704 * scheduling class and "nice" value. For SCHED_NORMAL tasks this is just a
705 * scaled version of the new time slice allocation that they receive on time
706 * slice expiry etc.
710 * Assume: static_prio_timeslice(NICE_TO_PRIO(0)) == DEF_TIMESLICE
711 * If static_prio_timeslice() is ever changed to break this assumption then
712 * this code will need modification
714 #define TIME_SLICE_NICE_ZERO DEF_TIMESLICE
715 #define LOAD_WEIGHT(lp) \
716 (((lp) * SCHED_LOAD_SCALE) / TIME_SLICE_NICE_ZERO)
717 #define PRIO_TO_LOAD_WEIGHT(prio) \
718 LOAD_WEIGHT(static_prio_timeslice(prio))
719 #define RTPRIO_TO_LOAD_WEIGHT(rp) \
720 (PRIO_TO_LOAD_WEIGHT(MAX_RT_PRIO) + LOAD_WEIGHT(rp))
722 static void set_load_weight(struct task_struct *p)
724 if (has_rt_policy(p)) {
725 #ifdef CONFIG_SMP
726 if (p == task_rq(p)->migration_thread)
728 * The migration thread does the actual balancing.
729 * Giving its load any weight will skew balancing
730 * adversely.
732 p->load_weight = 0;
733 else
734 #endif
735 p->load_weight = RTPRIO_TO_LOAD_WEIGHT(p->rt_priority);
736 } else
737 p->load_weight = PRIO_TO_LOAD_WEIGHT(p->static_prio);
740 static inline void
741 inc_raw_weighted_load(struct rq *rq, const struct task_struct *p)
743 rq->raw_weighted_load += p->load_weight;
746 static inline void
747 dec_raw_weighted_load(struct rq *rq, const struct task_struct *p)
749 rq->raw_weighted_load -= p->load_weight;
752 static inline void inc_nr_running(struct task_struct *p, struct rq *rq)
754 rq->nr_running++;
755 inc_raw_weighted_load(rq, p);
758 static inline void dec_nr_running(struct task_struct *p, struct rq *rq)
760 rq->nr_running--;
761 dec_raw_weighted_load(rq, p);
765 * Calculate the expected normal priority: i.e. priority
766 * without taking RT-inheritance into account. Might be
767 * boosted by interactivity modifiers. Changes upon fork,
768 * setprio syscalls, and whenever the interactivity
769 * estimator recalculates.
771 static inline int normal_prio(struct task_struct *p)
773 int prio;
775 if (has_rt_policy(p))
776 prio = MAX_RT_PRIO-1 - p->rt_priority;
777 else
778 prio = __normal_prio(p);
779 return prio;
783 * Calculate the current priority, i.e. the priority
784 * taken into account by the scheduler. This value might
785 * be boosted by RT tasks, or might be boosted by
786 * interactivity modifiers. Will be RT if the task got
787 * RT-boosted. If not then it returns p->normal_prio.
789 static int effective_prio(struct task_struct *p)
791 p->normal_prio = normal_prio(p);
793 * If we are RT tasks or we were boosted to RT priority,
794 * keep the priority unchanged. Otherwise, update priority
795 * to the normal priority:
797 if (!rt_prio(p->prio))
798 return p->normal_prio;
799 return p->prio;
803 * __activate_task - move a task to the runqueue.
805 static void __activate_task(struct task_struct *p, struct rq *rq)
807 struct prio_array *target = rq->active;
809 if (batch_task(p))
810 target = rq->expired;
811 enqueue_task(p, target);
812 inc_nr_running(p, rq);
816 * __activate_idle_task - move idle task to the _front_ of runqueue.
818 static inline void __activate_idle_task(struct task_struct *p, struct rq *rq)
820 enqueue_task_head(p, rq->active);
821 inc_nr_running(p, rq);
825 * Recalculate p->normal_prio and p->prio after having slept,
826 * updating the sleep-average too:
828 static int recalc_task_prio(struct task_struct *p, unsigned long long now)
830 /* Caller must always ensure 'now >= p->timestamp' */
831 unsigned long sleep_time = now - p->timestamp;
833 if (batch_task(p))
834 sleep_time = 0;
836 if (likely(sleep_time > 0)) {
838 * This ceiling is set to the lowest priority that would allow
839 * a task to be reinserted into the active array on timeslice
840 * completion.
842 unsigned long ceiling = INTERACTIVE_SLEEP(p);
844 if (p->mm && sleep_time > ceiling && p->sleep_avg < ceiling) {
846 * Prevents user tasks from achieving best priority
847 * with one single large enough sleep.
849 p->sleep_avg = ceiling;
851 * Using INTERACTIVE_SLEEP() as a ceiling places a
852 * nice(0) task 1ms sleep away from promotion, and
853 * gives it 700ms to round-robin with no chance of
854 * being demoted. This is more than generous, so
855 * mark this sleep as non-interactive to prevent the
856 * on-runqueue bonus logic from intervening should
857 * this task not receive cpu immediately.
859 p->sleep_type = SLEEP_NONINTERACTIVE;
860 } else {
862 * Tasks waking from uninterruptible sleep are
863 * limited in their sleep_avg rise as they
864 * are likely to be waiting on I/O
866 if (p->sleep_type == SLEEP_NONINTERACTIVE && p->mm) {
867 if (p->sleep_avg >= ceiling)
868 sleep_time = 0;
869 else if (p->sleep_avg + sleep_time >=
870 ceiling) {
871 p->sleep_avg = ceiling;
872 sleep_time = 0;
877 * This code gives a bonus to interactive tasks.
879 * The boost works by updating the 'average sleep time'
880 * value here, based on ->timestamp. The more time a
881 * task spends sleeping, the higher the average gets -
882 * and the higher the priority boost gets as well.
884 p->sleep_avg += sleep_time;
887 if (p->sleep_avg > NS_MAX_SLEEP_AVG)
888 p->sleep_avg = NS_MAX_SLEEP_AVG;
891 return effective_prio(p);
895 * activate_task - move a task to the runqueue and do priority recalculation
897 * Update all the scheduling statistics stuff. (sleep average
898 * calculation, priority modifiers, etc.)
900 static void activate_task(struct task_struct *p, struct rq *rq, int local)
902 unsigned long long now;
904 now = sched_clock();
905 #ifdef CONFIG_SMP
906 if (!local) {
907 /* Compensate for drifting sched_clock */
908 struct rq *this_rq = this_rq();
909 now = (now - this_rq->timestamp_last_tick)
910 + rq->timestamp_last_tick;
912 #endif
914 if (!rt_task(p))
915 p->prio = recalc_task_prio(p, now);
918 * This checks to make sure it's not an uninterruptible task
919 * that is now waking up.
921 if (p->sleep_type == SLEEP_NORMAL) {
923 * Tasks which were woken up by interrupts (ie. hw events)
924 * are most likely of interactive nature. So we give them
925 * the credit of extending their sleep time to the period
926 * of time they spend on the runqueue, waiting for execution
927 * on a CPU, first time around:
929 if (in_interrupt())
930 p->sleep_type = SLEEP_INTERRUPTED;
931 else {
933 * Normal first-time wakeups get a credit too for
934 * on-runqueue time, but it will be weighted down:
936 p->sleep_type = SLEEP_INTERACTIVE;
939 p->timestamp = now;
941 __activate_task(p, rq);
945 * deactivate_task - remove a task from the runqueue.
947 static void deactivate_task(struct task_struct *p, struct rq *rq)
949 dec_nr_running(p, rq);
950 dequeue_task(p, p->array);
951 p->array = NULL;
955 * resched_task - mark a task 'to be rescheduled now'.
957 * On UP this means the setting of the need_resched flag, on SMP it
958 * might also involve a cross-CPU call to trigger the scheduler on
959 * the target CPU.
961 #ifdef CONFIG_SMP
963 #ifndef tsk_is_polling
964 #define tsk_is_polling(t) test_tsk_thread_flag(t, TIF_POLLING_NRFLAG)
965 #endif
967 static void resched_task(struct task_struct *p)
969 int cpu;
971 assert_spin_locked(&task_rq(p)->lock);
973 if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
974 return;
976 set_tsk_thread_flag(p, TIF_NEED_RESCHED);
978 cpu = task_cpu(p);
979 if (cpu == smp_processor_id())
980 return;
982 /* NEED_RESCHED must be visible before we test polling */
983 smp_mb();
984 if (!tsk_is_polling(p))
985 smp_send_reschedule(cpu);
987 #else
988 static inline void resched_task(struct task_struct *p)
990 assert_spin_locked(&task_rq(p)->lock);
991 set_tsk_need_resched(p);
993 #endif
996 * task_curr - is this task currently executing on a CPU?
997 * @p: the task in question.
999 inline int task_curr(const struct task_struct *p)
1001 return cpu_curr(task_cpu(p)) == p;
1004 /* Used instead of source_load when we know the type == 0 */
1005 unsigned long weighted_cpuload(const int cpu)
1007 return cpu_rq(cpu)->raw_weighted_load;
1010 #ifdef CONFIG_SMP
1011 struct migration_req {
1012 struct list_head list;
1014 struct task_struct *task;
1015 int dest_cpu;
1017 struct completion done;
1021 * The task's runqueue lock must be held.
1022 * Returns true if you have to wait for migration thread.
1024 static int
1025 migrate_task(struct task_struct *p, int dest_cpu, struct migration_req *req)
1027 struct rq *rq = task_rq(p);
1030 * If the task is not on a runqueue (and not running), then
1031 * it is sufficient to simply update the task's cpu field.
1033 if (!p->array && !task_running(rq, p)) {
1034 set_task_cpu(p, dest_cpu);
1035 return 0;
1038 init_completion(&req->done);
1039 req->task = p;
1040 req->dest_cpu = dest_cpu;
1041 list_add(&req->list, &rq->migration_queue);
1043 return 1;
1047 * wait_task_inactive - wait for a thread to unschedule.
1049 * The caller must ensure that the task *will* unschedule sometime soon,
1050 * else this function might spin for a *long* time. This function can't
1051 * be called with interrupts off, or it may introduce deadlock with
1052 * smp_call_function() if an IPI is sent by the same process we are
1053 * waiting to become inactive.
1055 void wait_task_inactive(struct task_struct *p)
1057 unsigned long flags;
1058 struct rq *rq;
1059 int preempted;
1061 repeat:
1062 rq = task_rq_lock(p, &flags);
1063 /* Must be off runqueue entirely, not preempted. */
1064 if (unlikely(p->array || task_running(rq, p))) {
1065 /* If it's preempted, we yield. It could be a while. */
1066 preempted = !task_running(rq, p);
1067 task_rq_unlock(rq, &flags);
1068 cpu_relax();
1069 if (preempted)
1070 yield();
1071 goto repeat;
1073 task_rq_unlock(rq, &flags);
1076 /***
1077 * kick_process - kick a running thread to enter/exit the kernel
1078 * @p: the to-be-kicked thread
1080 * Cause a process which is running on another CPU to enter
1081 * kernel-mode, without any delay. (to get signals handled.)
1083 * NOTE: this function doesnt have to take the runqueue lock,
1084 * because all it wants to ensure is that the remote task enters
1085 * the kernel. If the IPI races and the task has been migrated
1086 * to another CPU then no harm is done and the purpose has been
1087 * achieved as well.
1089 void kick_process(struct task_struct *p)
1091 int cpu;
1093 preempt_disable();
1094 cpu = task_cpu(p);
1095 if ((cpu != smp_processor_id()) && task_curr(p))
1096 smp_send_reschedule(cpu);
1097 preempt_enable();
1101 * Return a low guess at the load of a migration-source cpu weighted
1102 * according to the scheduling class and "nice" value.
1104 * We want to under-estimate the load of migration sources, to
1105 * balance conservatively.
1107 static inline unsigned long source_load(int cpu, int type)
1109 struct rq *rq = cpu_rq(cpu);
1111 if (type == 0)
1112 return rq->raw_weighted_load;
1114 return min(rq->cpu_load[type-1], rq->raw_weighted_load);
1118 * Return a high guess at the load of a migration-target cpu weighted
1119 * according to the scheduling class and "nice" value.
1121 static inline unsigned long target_load(int cpu, int type)
1123 struct rq *rq = cpu_rq(cpu);
1125 if (type == 0)
1126 return rq->raw_weighted_load;
1128 return max(rq->cpu_load[type-1], rq->raw_weighted_load);
1132 * Return the average load per task on the cpu's run queue
1134 static inline unsigned long cpu_avg_load_per_task(int cpu)
1136 struct rq *rq = cpu_rq(cpu);
1137 unsigned long n = rq->nr_running;
1139 return n ? rq->raw_weighted_load / n : SCHED_LOAD_SCALE;
1143 * find_idlest_group finds and returns the least busy CPU group within the
1144 * domain.
1146 static struct sched_group *
1147 find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
1149 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
1150 unsigned long min_load = ULONG_MAX, this_load = 0;
1151 int load_idx = sd->forkexec_idx;
1152 int imbalance = 100 + (sd->imbalance_pct-100)/2;
1154 do {
1155 unsigned long load, avg_load;
1156 int local_group;
1157 int i;
1159 /* Skip over this group if it has no CPUs allowed */
1160 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
1161 goto nextgroup;
1163 local_group = cpu_isset(this_cpu, group->cpumask);
1165 /* Tally up the load of all CPUs in the group */
1166 avg_load = 0;
1168 for_each_cpu_mask(i, group->cpumask) {
1169 /* Bias balancing toward cpus of our domain */
1170 if (local_group)
1171 load = source_load(i, load_idx);
1172 else
1173 load = target_load(i, load_idx);
1175 avg_load += load;
1178 /* Adjust by relative CPU power of the group */
1179 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1181 if (local_group) {
1182 this_load = avg_load;
1183 this = group;
1184 } else if (avg_load < min_load) {
1185 min_load = avg_load;
1186 idlest = group;
1188 nextgroup:
1189 group = group->next;
1190 } while (group != sd->groups);
1192 if (!idlest || 100*this_load < imbalance*min_load)
1193 return NULL;
1194 return idlest;
1198 * find_idlest_queue - find the idlest runqueue among the cpus in group.
1200 static int
1201 find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
1203 cpumask_t tmp;
1204 unsigned long load, min_load = ULONG_MAX;
1205 int idlest = -1;
1206 int i;
1208 /* Traverse only the allowed CPUs */
1209 cpus_and(tmp, group->cpumask, p->cpus_allowed);
1211 for_each_cpu_mask(i, tmp) {
1212 load = weighted_cpuload(i);
1214 if (load < min_load || (load == min_load && i == this_cpu)) {
1215 min_load = load;
1216 idlest = i;
1220 return idlest;
1224 * sched_balance_self: balance the current task (running on cpu) in domains
1225 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1226 * SD_BALANCE_EXEC.
1228 * Balance, ie. select the least loaded group.
1230 * Returns the target CPU number, or the same CPU if no balancing is needed.
1232 * preempt must be disabled.
1234 static int sched_balance_self(int cpu, int flag)
1236 struct task_struct *t = current;
1237 struct sched_domain *tmp, *sd = NULL;
1239 for_each_domain(cpu, tmp) {
1241 * If power savings logic is enabled for a domain, stop there.
1243 if (tmp->flags & SD_POWERSAVINGS_BALANCE)
1244 break;
1245 if (tmp->flags & flag)
1246 sd = tmp;
1249 while (sd) {
1250 cpumask_t span;
1251 struct sched_group *group;
1252 int new_cpu;
1253 int weight;
1255 span = sd->span;
1256 group = find_idlest_group(sd, t, cpu);
1257 if (!group)
1258 goto nextlevel;
1260 new_cpu = find_idlest_cpu(group, t, cpu);
1261 if (new_cpu == -1 || new_cpu == cpu)
1262 goto nextlevel;
1264 /* Now try balancing at a lower domain level */
1265 cpu = new_cpu;
1266 nextlevel:
1267 sd = NULL;
1268 weight = cpus_weight(span);
1269 for_each_domain(cpu, tmp) {
1270 if (weight <= cpus_weight(tmp->span))
1271 break;
1272 if (tmp->flags & flag)
1273 sd = tmp;
1275 /* while loop will break here if sd == NULL */
1278 return cpu;
1281 #endif /* CONFIG_SMP */
1284 * wake_idle() will wake a task on an idle cpu if task->cpu is
1285 * not idle and an idle cpu is available. The span of cpus to
1286 * search starts with cpus closest then further out as needed,
1287 * so we always favor a closer, idle cpu.
1289 * Returns the CPU we should wake onto.
1291 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1292 static int wake_idle(int cpu, struct task_struct *p)
1294 cpumask_t tmp;
1295 struct sched_domain *sd;
1296 int i;
1298 if (idle_cpu(cpu))
1299 return cpu;
1301 for_each_domain(cpu, sd) {
1302 if (sd->flags & SD_WAKE_IDLE) {
1303 cpus_and(tmp, sd->span, p->cpus_allowed);
1304 for_each_cpu_mask(i, tmp) {
1305 if (idle_cpu(i))
1306 return i;
1309 else
1310 break;
1312 return cpu;
1314 #else
1315 static inline int wake_idle(int cpu, struct task_struct *p)
1317 return cpu;
1319 #endif
1321 /***
1322 * try_to_wake_up - wake up a thread
1323 * @p: the to-be-woken-up thread
1324 * @state: the mask of task states that can be woken
1325 * @sync: do a synchronous wakeup?
1327 * Put it on the run-queue if it's not already there. The "current"
1328 * thread is always on the run-queue (except when the actual
1329 * re-schedule is in progress), and as such you're allowed to do
1330 * the simpler "current->state = TASK_RUNNING" to mark yourself
1331 * runnable without the overhead of this.
1333 * returns failure only if the task is already active.
1335 static int try_to_wake_up(struct task_struct *p, unsigned int state, int sync)
1337 int cpu, this_cpu, success = 0;
1338 unsigned long flags;
1339 long old_state;
1340 struct rq *rq;
1341 #ifdef CONFIG_SMP
1342 struct sched_domain *sd, *this_sd = NULL;
1343 unsigned long load, this_load;
1344 int new_cpu;
1345 #endif
1347 rq = task_rq_lock(p, &flags);
1348 old_state = p->state;
1349 if (!(old_state & state))
1350 goto out;
1352 if (p->array)
1353 goto out_running;
1355 cpu = task_cpu(p);
1356 this_cpu = smp_processor_id();
1358 #ifdef CONFIG_SMP
1359 if (unlikely(task_running(rq, p)))
1360 goto out_activate;
1362 new_cpu = cpu;
1364 schedstat_inc(rq, ttwu_cnt);
1365 if (cpu == this_cpu) {
1366 schedstat_inc(rq, ttwu_local);
1367 goto out_set_cpu;
1370 for_each_domain(this_cpu, sd) {
1371 if (cpu_isset(cpu, sd->span)) {
1372 schedstat_inc(sd, ttwu_wake_remote);
1373 this_sd = sd;
1374 break;
1378 if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1379 goto out_set_cpu;
1382 * Check for affine wakeup and passive balancing possibilities.
1384 if (this_sd) {
1385 int idx = this_sd->wake_idx;
1386 unsigned int imbalance;
1388 imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
1390 load = source_load(cpu, idx);
1391 this_load = target_load(this_cpu, idx);
1393 new_cpu = this_cpu; /* Wake to this CPU if we can */
1395 if (this_sd->flags & SD_WAKE_AFFINE) {
1396 unsigned long tl = this_load;
1397 unsigned long tl_per_task = cpu_avg_load_per_task(this_cpu);
1400 * If sync wakeup then subtract the (maximum possible)
1401 * effect of the currently running task from the load
1402 * of the current CPU:
1404 if (sync)
1405 tl -= current->load_weight;
1407 if ((tl <= load &&
1408 tl + target_load(cpu, idx) <= tl_per_task) ||
1409 100*(tl + p->load_weight) <= imbalance*load) {
1411 * This domain has SD_WAKE_AFFINE and
1412 * p is cache cold in this domain, and
1413 * there is no bad imbalance.
1415 schedstat_inc(this_sd, ttwu_move_affine);
1416 goto out_set_cpu;
1421 * Start passive balancing when half the imbalance_pct
1422 * limit is reached.
1424 if (this_sd->flags & SD_WAKE_BALANCE) {
1425 if (imbalance*this_load <= 100*load) {
1426 schedstat_inc(this_sd, ttwu_move_balance);
1427 goto out_set_cpu;
1432 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1433 out_set_cpu:
1434 new_cpu = wake_idle(new_cpu, p);
1435 if (new_cpu != cpu) {
1436 set_task_cpu(p, new_cpu);
1437 task_rq_unlock(rq, &flags);
1438 /* might preempt at this point */
1439 rq = task_rq_lock(p, &flags);
1440 old_state = p->state;
1441 if (!(old_state & state))
1442 goto out;
1443 if (p->array)
1444 goto out_running;
1446 this_cpu = smp_processor_id();
1447 cpu = task_cpu(p);
1450 out_activate:
1451 #endif /* CONFIG_SMP */
1452 if (old_state == TASK_UNINTERRUPTIBLE) {
1453 rq->nr_uninterruptible--;
1455 * Tasks on involuntary sleep don't earn
1456 * sleep_avg beyond just interactive state.
1458 p->sleep_type = SLEEP_NONINTERACTIVE;
1459 } else
1462 * Tasks that have marked their sleep as noninteractive get
1463 * woken up with their sleep average not weighted in an
1464 * interactive way.
1466 if (old_state & TASK_NONINTERACTIVE)
1467 p->sleep_type = SLEEP_NONINTERACTIVE;
1470 activate_task(p, rq, cpu == this_cpu);
1472 * Sync wakeups (i.e. those types of wakeups where the waker
1473 * has indicated that it will leave the CPU in short order)
1474 * don't trigger a preemption, if the woken up task will run on
1475 * this cpu. (in this case the 'I will reschedule' promise of
1476 * the waker guarantees that the freshly woken up task is going
1477 * to be considered on this CPU.)
1479 if (!sync || cpu != this_cpu) {
1480 if (TASK_PREEMPTS_CURR(p, rq))
1481 resched_task(rq->curr);
1483 success = 1;
1485 out_running:
1486 p->state = TASK_RUNNING;
1487 out:
1488 task_rq_unlock(rq, &flags);
1490 return success;
1493 int fastcall wake_up_process(struct task_struct *p)
1495 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1496 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1498 EXPORT_SYMBOL(wake_up_process);
1500 int fastcall wake_up_state(struct task_struct *p, unsigned int state)
1502 return try_to_wake_up(p, state, 0);
1506 * Perform scheduler related setup for a newly forked process p.
1507 * p is forked by current.
1509 void fastcall sched_fork(struct task_struct *p, int clone_flags)
1511 int cpu = get_cpu();
1513 #ifdef CONFIG_SMP
1514 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
1515 #endif
1516 set_task_cpu(p, cpu);
1519 * We mark the process as running here, but have not actually
1520 * inserted it onto the runqueue yet. This guarantees that
1521 * nobody will actually run it, and a signal or other external
1522 * event cannot wake it up and insert it on the runqueue either.
1524 p->state = TASK_RUNNING;
1527 * Make sure we do not leak PI boosting priority to the child:
1529 p->prio = current->normal_prio;
1531 INIT_LIST_HEAD(&p->run_list);
1532 p->array = NULL;
1533 #ifdef CONFIG_SCHEDSTATS
1534 memset(&p->sched_info, 0, sizeof(p->sched_info));
1535 #endif
1536 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
1537 p->oncpu = 0;
1538 #endif
1539 #ifdef CONFIG_PREEMPT
1540 /* Want to start with kernel preemption disabled. */
1541 task_thread_info(p)->preempt_count = 1;
1542 #endif
1544 * Share the timeslice between parent and child, thus the
1545 * total amount of pending timeslices in the system doesn't change,
1546 * resulting in more scheduling fairness.
1548 local_irq_disable();
1549 p->time_slice = (current->time_slice + 1) >> 1;
1551 * The remainder of the first timeslice might be recovered by
1552 * the parent if the child exits early enough.
1554 p->first_time_slice = 1;
1555 current->time_slice >>= 1;
1556 p->timestamp = sched_clock();
1557 if (unlikely(!current->time_slice)) {
1559 * This case is rare, it happens when the parent has only
1560 * a single jiffy left from its timeslice. Taking the
1561 * runqueue lock is not a problem.
1563 current->time_slice = 1;
1564 scheduler_tick();
1566 local_irq_enable();
1567 put_cpu();
1571 * wake_up_new_task - wake up a newly created task for the first time.
1573 * This function will do some initial scheduler statistics housekeeping
1574 * that must be done for every newly created context, then puts the task
1575 * on the runqueue and wakes it.
1577 void fastcall wake_up_new_task(struct task_struct *p, unsigned long clone_flags)
1579 struct rq *rq, *this_rq;
1580 unsigned long flags;
1581 int this_cpu, cpu;
1583 rq = task_rq_lock(p, &flags);
1584 BUG_ON(p->state != TASK_RUNNING);
1585 this_cpu = smp_processor_id();
1586 cpu = task_cpu(p);
1589 * We decrease the sleep average of forking parents
1590 * and children as well, to keep max-interactive tasks
1591 * from forking tasks that are max-interactive. The parent
1592 * (current) is done further down, under its lock.
1594 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1595 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1597 p->prio = effective_prio(p);
1599 if (likely(cpu == this_cpu)) {
1600 if (!(clone_flags & CLONE_VM)) {
1602 * The VM isn't cloned, so we're in a good position to
1603 * do child-runs-first in anticipation of an exec. This
1604 * usually avoids a lot of COW overhead.
1606 if (unlikely(!current->array))
1607 __activate_task(p, rq);
1608 else {
1609 p->prio = current->prio;
1610 p->normal_prio = current->normal_prio;
1611 list_add_tail(&p->run_list, &current->run_list);
1612 p->array = current->array;
1613 p->array->nr_active++;
1614 inc_nr_running(p, rq);
1616 set_need_resched();
1617 } else
1618 /* Run child last */
1619 __activate_task(p, rq);
1621 * We skip the following code due to cpu == this_cpu
1623 * task_rq_unlock(rq, &flags);
1624 * this_rq = task_rq_lock(current, &flags);
1626 this_rq = rq;
1627 } else {
1628 this_rq = cpu_rq(this_cpu);
1631 * Not the local CPU - must adjust timestamp. This should
1632 * get optimised away in the !CONFIG_SMP case.
1634 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1635 + rq->timestamp_last_tick;
1636 __activate_task(p, rq);
1637 if (TASK_PREEMPTS_CURR(p, rq))
1638 resched_task(rq->curr);
1641 * Parent and child are on different CPUs, now get the
1642 * parent runqueue to update the parent's ->sleep_avg:
1644 task_rq_unlock(rq, &flags);
1645 this_rq = task_rq_lock(current, &flags);
1647 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1648 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1649 task_rq_unlock(this_rq, &flags);
1653 * Potentially available exiting-child timeslices are
1654 * retrieved here - this way the parent does not get
1655 * penalized for creating too many threads.
1657 * (this cannot be used to 'generate' timeslices
1658 * artificially, because any timeslice recovered here
1659 * was given away by the parent in the first place.)
1661 void fastcall sched_exit(struct task_struct *p)
1663 unsigned long flags;
1664 struct rq *rq;
1667 * If the child was a (relative-) CPU hog then decrease
1668 * the sleep_avg of the parent as well.
1670 rq = task_rq_lock(p->parent, &flags);
1671 if (p->first_time_slice && task_cpu(p) == task_cpu(p->parent)) {
1672 p->parent->time_slice += p->time_slice;
1673 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1674 p->parent->time_slice = task_timeslice(p);
1676 if (p->sleep_avg < p->parent->sleep_avg)
1677 p->parent->sleep_avg = p->parent->sleep_avg /
1678 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1679 (EXIT_WEIGHT + 1);
1680 task_rq_unlock(rq, &flags);
1684 * prepare_task_switch - prepare to switch tasks
1685 * @rq: the runqueue preparing to switch
1686 * @next: the task we are going to switch to.
1688 * This is called with the rq lock held and interrupts off. It must
1689 * be paired with a subsequent finish_task_switch after the context
1690 * switch.
1692 * prepare_task_switch sets up locking and calls architecture specific
1693 * hooks.
1695 static inline void prepare_task_switch(struct rq *rq, struct task_struct *next)
1697 prepare_lock_switch(rq, next);
1698 prepare_arch_switch(next);
1702 * finish_task_switch - clean up after a task-switch
1703 * @rq: runqueue associated with task-switch
1704 * @prev: the thread we just switched away from.
1706 * finish_task_switch must be called after the context switch, paired
1707 * with a prepare_task_switch call before the context switch.
1708 * finish_task_switch will reconcile locking set up by prepare_task_switch,
1709 * and do any other architecture-specific cleanup actions.
1711 * Note that we may have delayed dropping an mm in context_switch(). If
1712 * so, we finish that here outside of the runqueue lock. (Doing it
1713 * with the lock held can cause deadlocks; see schedule() for
1714 * details.)
1716 static inline void finish_task_switch(struct rq *rq, struct task_struct *prev)
1717 __releases(rq->lock)
1719 struct mm_struct *mm = rq->prev_mm;
1720 unsigned long prev_task_flags;
1722 rq->prev_mm = NULL;
1725 * A task struct has one reference for the use as "current".
1726 * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1727 * calls schedule one last time. The schedule call will never return,
1728 * and the scheduled task must drop that reference.
1729 * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1730 * still held, otherwise prev could be scheduled on another cpu, die
1731 * there before we look at prev->state, and then the reference would
1732 * be dropped twice.
1733 * Manfred Spraul <manfred@colorfullife.com>
1735 prev_task_flags = prev->flags;
1736 finish_arch_switch(prev);
1737 finish_lock_switch(rq, prev);
1738 if (mm)
1739 mmdrop(mm);
1740 if (unlikely(prev_task_flags & PF_DEAD)) {
1742 * Remove function-return probe instances associated with this
1743 * task and put them back on the free list.
1745 kprobe_flush_task(prev);
1746 put_task_struct(prev);
1751 * schedule_tail - first thing a freshly forked thread must call.
1752 * @prev: the thread we just switched away from.
1754 asmlinkage void schedule_tail(struct task_struct *prev)
1755 __releases(rq->lock)
1757 struct rq *rq = this_rq();
1759 finish_task_switch(rq, prev);
1760 #ifdef __ARCH_WANT_UNLOCKED_CTXSW
1761 /* In this case, finish_task_switch does not reenable preemption */
1762 preempt_enable();
1763 #endif
1764 if (current->set_child_tid)
1765 put_user(current->pid, current->set_child_tid);
1769 * context_switch - switch to the new MM and the new
1770 * thread's register state.
1772 static inline struct task_struct *
1773 context_switch(struct rq *rq, struct task_struct *prev,
1774 struct task_struct *next)
1776 struct mm_struct *mm = next->mm;
1777 struct mm_struct *oldmm = prev->active_mm;
1779 if (unlikely(!mm)) {
1780 next->active_mm = oldmm;
1781 atomic_inc(&oldmm->mm_count);
1782 enter_lazy_tlb(oldmm, next);
1783 } else
1784 switch_mm(oldmm, mm, next);
1786 if (unlikely(!prev->mm)) {
1787 prev->active_mm = NULL;
1788 WARN_ON(rq->prev_mm);
1789 rq->prev_mm = oldmm;
1792 * Since the runqueue lock will be released by the next
1793 * task (which is an invalid locking op but in the case
1794 * of the scheduler it's an obvious special-case), so we
1795 * do an early lockdep release here:
1797 #ifndef __ARCH_WANT_UNLOCKED_CTXSW
1798 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
1799 #endif
1801 /* Here we just switch the register state and the stack. */
1802 switch_to(prev, next, prev);
1804 return prev;
1808 * nr_running, nr_uninterruptible and nr_context_switches:
1810 * externally visible scheduler statistics: current number of runnable
1811 * threads, current number of uninterruptible-sleeping threads, total
1812 * number of context switches performed since bootup.
1814 unsigned long nr_running(void)
1816 unsigned long i, sum = 0;
1818 for_each_online_cpu(i)
1819 sum += cpu_rq(i)->nr_running;
1821 return sum;
1824 unsigned long nr_uninterruptible(void)
1826 unsigned long i, sum = 0;
1828 for_each_possible_cpu(i)
1829 sum += cpu_rq(i)->nr_uninterruptible;
1832 * Since we read the counters lockless, it might be slightly
1833 * inaccurate. Do not allow it to go below zero though:
1835 if (unlikely((long)sum < 0))
1836 sum = 0;
1838 return sum;
1841 unsigned long long nr_context_switches(void)
1843 int i;
1844 unsigned long long sum = 0;
1846 for_each_possible_cpu(i)
1847 sum += cpu_rq(i)->nr_switches;
1849 return sum;
1852 unsigned long nr_iowait(void)
1854 unsigned long i, sum = 0;
1856 for_each_possible_cpu(i)
1857 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1859 return sum;
1862 unsigned long nr_active(void)
1864 unsigned long i, running = 0, uninterruptible = 0;
1866 for_each_online_cpu(i) {
1867 running += cpu_rq(i)->nr_running;
1868 uninterruptible += cpu_rq(i)->nr_uninterruptible;
1871 if (unlikely((long)uninterruptible < 0))
1872 uninterruptible = 0;
1874 return running + uninterruptible;
1877 #ifdef CONFIG_SMP
1880 * Is this task likely cache-hot:
1882 static inline int
1883 task_hot(struct task_struct *p, unsigned long long now, struct sched_domain *sd)
1885 return (long long)(now - p->last_ran) < (long long)sd->cache_hot_time;
1889 * double_rq_lock - safely lock two runqueues
1891 * Note this does not disable interrupts like task_rq_lock,
1892 * you need to do so manually before calling.
1894 static void double_rq_lock(struct rq *rq1, struct rq *rq2)
1895 __acquires(rq1->lock)
1896 __acquires(rq2->lock)
1898 if (rq1 == rq2) {
1899 spin_lock(&rq1->lock);
1900 __acquire(rq2->lock); /* Fake it out ;) */
1901 } else {
1902 if (rq1 < rq2) {
1903 spin_lock(&rq1->lock);
1904 spin_lock(&rq2->lock);
1905 } else {
1906 spin_lock(&rq2->lock);
1907 spin_lock(&rq1->lock);
1913 * double_rq_unlock - safely unlock two runqueues
1915 * Note this does not restore interrupts like task_rq_unlock,
1916 * you need to do so manually after calling.
1918 static void double_rq_unlock(struct rq *rq1, struct rq *rq2)
1919 __releases(rq1->lock)
1920 __releases(rq2->lock)
1922 spin_unlock(&rq1->lock);
1923 if (rq1 != rq2)
1924 spin_unlock(&rq2->lock);
1925 else
1926 __release(rq2->lock);
1930 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1932 static void double_lock_balance(struct rq *this_rq, struct rq *busiest)
1933 __releases(this_rq->lock)
1934 __acquires(busiest->lock)
1935 __acquires(this_rq->lock)
1937 if (unlikely(!spin_trylock(&busiest->lock))) {
1938 if (busiest < this_rq) {
1939 spin_unlock(&this_rq->lock);
1940 spin_lock(&busiest->lock);
1941 spin_lock(&this_rq->lock);
1942 } else
1943 spin_lock(&busiest->lock);
1948 * If dest_cpu is allowed for this process, migrate the task to it.
1949 * This is accomplished by forcing the cpu_allowed mask to only
1950 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1951 * the cpu_allowed mask is restored.
1953 static void sched_migrate_task(struct task_struct *p, int dest_cpu)
1955 struct migration_req req;
1956 unsigned long flags;
1957 struct rq *rq;
1959 rq = task_rq_lock(p, &flags);
1960 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1961 || unlikely(cpu_is_offline(dest_cpu)))
1962 goto out;
1964 /* force the process onto the specified CPU */
1965 if (migrate_task(p, dest_cpu, &req)) {
1966 /* Need to wait for migration thread (might exit: take ref). */
1967 struct task_struct *mt = rq->migration_thread;
1969 get_task_struct(mt);
1970 task_rq_unlock(rq, &flags);
1971 wake_up_process(mt);
1972 put_task_struct(mt);
1973 wait_for_completion(&req.done);
1975 return;
1977 out:
1978 task_rq_unlock(rq, &flags);
1982 * sched_exec - execve() is a valuable balancing opportunity, because at
1983 * this point the task has the smallest effective memory and cache footprint.
1985 void sched_exec(void)
1987 int new_cpu, this_cpu = get_cpu();
1988 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
1989 put_cpu();
1990 if (new_cpu != this_cpu)
1991 sched_migrate_task(current, new_cpu);
1995 * pull_task - move a task from a remote runqueue to the local runqueue.
1996 * Both runqueues must be locked.
1998 static void pull_task(struct rq *src_rq, struct prio_array *src_array,
1999 struct task_struct *p, struct rq *this_rq,
2000 struct prio_array *this_array, int this_cpu)
2002 dequeue_task(p, src_array);
2003 dec_nr_running(p, src_rq);
2004 set_task_cpu(p, this_cpu);
2005 inc_nr_running(p, this_rq);
2006 enqueue_task(p, this_array);
2007 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
2008 + this_rq->timestamp_last_tick;
2010 * Note that idle threads have a prio of MAX_PRIO, for this test
2011 * to be always true for them.
2013 if (TASK_PREEMPTS_CURR(p, this_rq))
2014 resched_task(this_rq->curr);
2018 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
2020 static
2021 int can_migrate_task(struct task_struct *p, struct rq *rq, int this_cpu,
2022 struct sched_domain *sd, enum idle_type idle,
2023 int *all_pinned)
2026 * We do not migrate tasks that are:
2027 * 1) running (obviously), or
2028 * 2) cannot be migrated to this CPU due to cpus_allowed, or
2029 * 3) are cache-hot on their current CPU.
2031 if (!cpu_isset(this_cpu, p->cpus_allowed))
2032 return 0;
2033 *all_pinned = 0;
2035 if (task_running(rq, p))
2036 return 0;
2039 * Aggressive migration if:
2040 * 1) task is cache cold, or
2041 * 2) too many balance attempts have failed.
2044 if (sd->nr_balance_failed > sd->cache_nice_tries)
2045 return 1;
2047 if (task_hot(p, rq->timestamp_last_tick, sd))
2048 return 0;
2049 return 1;
2052 #define rq_best_prio(rq) min((rq)->curr->prio, (rq)->best_expired_prio)
2055 * move_tasks tries to move up to max_nr_move tasks and max_load_move weighted
2056 * load from busiest to this_rq, as part of a balancing operation within
2057 * "domain". Returns the number of tasks moved.
2059 * Called with both runqueues locked.
2061 static int move_tasks(struct rq *this_rq, int this_cpu, struct rq *busiest,
2062 unsigned long max_nr_move, unsigned long max_load_move,
2063 struct sched_domain *sd, enum idle_type idle,
2064 int *all_pinned)
2066 int idx, pulled = 0, pinned = 0, this_best_prio, best_prio,
2067 best_prio_seen, skip_for_load;
2068 struct prio_array *array, *dst_array;
2069 struct list_head *head, *curr;
2070 struct task_struct *tmp;
2071 long rem_load_move;
2073 if (max_nr_move == 0 || max_load_move == 0)
2074 goto out;
2076 rem_load_move = max_load_move;
2077 pinned = 1;
2078 this_best_prio = rq_best_prio(this_rq);
2079 best_prio = rq_best_prio(busiest);
2081 * Enable handling of the case where there is more than one task
2082 * with the best priority. If the current running task is one
2083 * of those with prio==best_prio we know it won't be moved
2084 * and therefore it's safe to override the skip (based on load) of
2085 * any task we find with that prio.
2087 best_prio_seen = best_prio == busiest->curr->prio;
2090 * We first consider expired tasks. Those will likely not be
2091 * executed in the near future, and they are most likely to
2092 * be cache-cold, thus switching CPUs has the least effect
2093 * on them.
2095 if (busiest->expired->nr_active) {
2096 array = busiest->expired;
2097 dst_array = this_rq->expired;
2098 } else {
2099 array = busiest->active;
2100 dst_array = this_rq->active;
2103 new_array:
2104 /* Start searching at priority 0: */
2105 idx = 0;
2106 skip_bitmap:
2107 if (!idx)
2108 idx = sched_find_first_bit(array->bitmap);
2109 else
2110 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
2111 if (idx >= MAX_PRIO) {
2112 if (array == busiest->expired && busiest->active->nr_active) {
2113 array = busiest->active;
2114 dst_array = this_rq->active;
2115 goto new_array;
2117 goto out;
2120 head = array->queue + idx;
2121 curr = head->prev;
2122 skip_queue:
2123 tmp = list_entry(curr, struct task_struct, run_list);
2125 curr = curr->prev;
2128 * To help distribute high priority tasks accross CPUs we don't
2129 * skip a task if it will be the highest priority task (i.e. smallest
2130 * prio value) on its new queue regardless of its load weight
2132 skip_for_load = tmp->load_weight > rem_load_move;
2133 if (skip_for_load && idx < this_best_prio)
2134 skip_for_load = !best_prio_seen && idx == best_prio;
2135 if (skip_for_load ||
2136 !can_migrate_task(tmp, busiest, this_cpu, sd, idle, &pinned)) {
2138 best_prio_seen |= idx == best_prio;
2139 if (curr != head)
2140 goto skip_queue;
2141 idx++;
2142 goto skip_bitmap;
2145 #ifdef CONFIG_SCHEDSTATS
2146 if (task_hot(tmp, busiest->timestamp_last_tick, sd))
2147 schedstat_inc(sd, lb_hot_gained[idle]);
2148 #endif
2150 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
2151 pulled++;
2152 rem_load_move -= tmp->load_weight;
2155 * We only want to steal up to the prescribed number of tasks
2156 * and the prescribed amount of weighted load.
2158 if (pulled < max_nr_move && rem_load_move > 0) {
2159 if (idx < this_best_prio)
2160 this_best_prio = idx;
2161 if (curr != head)
2162 goto skip_queue;
2163 idx++;
2164 goto skip_bitmap;
2166 out:
2168 * Right now, this is the only place pull_task() is called,
2169 * so we can safely collect pull_task() stats here rather than
2170 * inside pull_task().
2172 schedstat_add(sd, lb_gained[idle], pulled);
2174 if (all_pinned)
2175 *all_pinned = pinned;
2176 return pulled;
2180 * find_busiest_group finds and returns the busiest CPU group within the
2181 * domain. It calculates and returns the amount of weighted load which
2182 * should be moved to restore balance via the imbalance parameter.
2184 static struct sched_group *
2185 find_busiest_group(struct sched_domain *sd, int this_cpu,
2186 unsigned long *imbalance, enum idle_type idle, int *sd_idle)
2188 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
2189 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
2190 unsigned long max_pull;
2191 unsigned long busiest_load_per_task, busiest_nr_running;
2192 unsigned long this_load_per_task, this_nr_running;
2193 int load_idx;
2194 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2195 int power_savings_balance = 1;
2196 unsigned long leader_nr_running = 0, min_load_per_task = 0;
2197 unsigned long min_nr_running = ULONG_MAX;
2198 struct sched_group *group_min = NULL, *group_leader = NULL;
2199 #endif
2201 max_load = this_load = total_load = total_pwr = 0;
2202 busiest_load_per_task = busiest_nr_running = 0;
2203 this_load_per_task = this_nr_running = 0;
2204 if (idle == NOT_IDLE)
2205 load_idx = sd->busy_idx;
2206 else if (idle == NEWLY_IDLE)
2207 load_idx = sd->newidle_idx;
2208 else
2209 load_idx = sd->idle_idx;
2211 do {
2212 unsigned long load, group_capacity;
2213 int local_group;
2214 int i;
2215 unsigned long sum_nr_running, sum_weighted_load;
2217 local_group = cpu_isset(this_cpu, group->cpumask);
2219 /* Tally up the load of all CPUs in the group */
2220 sum_weighted_load = sum_nr_running = avg_load = 0;
2222 for_each_cpu_mask(i, group->cpumask) {
2223 struct rq *rq = cpu_rq(i);
2225 if (*sd_idle && !idle_cpu(i))
2226 *sd_idle = 0;
2228 /* Bias balancing toward cpus of our domain */
2229 if (local_group)
2230 load = target_load(i, load_idx);
2231 else
2232 load = source_load(i, load_idx);
2234 avg_load += load;
2235 sum_nr_running += rq->nr_running;
2236 sum_weighted_load += rq->raw_weighted_load;
2239 total_load += avg_load;
2240 total_pwr += group->cpu_power;
2242 /* Adjust by relative CPU power of the group */
2243 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
2245 group_capacity = group->cpu_power / SCHED_LOAD_SCALE;
2247 if (local_group) {
2248 this_load = avg_load;
2249 this = group;
2250 this_nr_running = sum_nr_running;
2251 this_load_per_task = sum_weighted_load;
2252 } else if (avg_load > max_load &&
2253 sum_nr_running > group_capacity) {
2254 max_load = avg_load;
2255 busiest = group;
2256 busiest_nr_running = sum_nr_running;
2257 busiest_load_per_task = sum_weighted_load;
2260 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2262 * Busy processors will not participate in power savings
2263 * balance.
2265 if (idle == NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
2266 goto group_next;
2269 * If the local group is idle or completely loaded
2270 * no need to do power savings balance at this domain
2272 if (local_group && (this_nr_running >= group_capacity ||
2273 !this_nr_running))
2274 power_savings_balance = 0;
2277 * If a group is already running at full capacity or idle,
2278 * don't include that group in power savings calculations
2280 if (!power_savings_balance || sum_nr_running >= group_capacity
2281 || !sum_nr_running)
2282 goto group_next;
2285 * Calculate the group which has the least non-idle load.
2286 * This is the group from where we need to pick up the load
2287 * for saving power
2289 if ((sum_nr_running < min_nr_running) ||
2290 (sum_nr_running == min_nr_running &&
2291 first_cpu(group->cpumask) <
2292 first_cpu(group_min->cpumask))) {
2293 group_min = group;
2294 min_nr_running = sum_nr_running;
2295 min_load_per_task = sum_weighted_load /
2296 sum_nr_running;
2300 * Calculate the group which is almost near its
2301 * capacity but still has some space to pick up some load
2302 * from other group and save more power
2304 if (sum_nr_running <= group_capacity - 1) {
2305 if (sum_nr_running > leader_nr_running ||
2306 (sum_nr_running == leader_nr_running &&
2307 first_cpu(group->cpumask) >
2308 first_cpu(group_leader->cpumask))) {
2309 group_leader = group;
2310 leader_nr_running = sum_nr_running;
2313 group_next:
2314 #endif
2315 group = group->next;
2316 } while (group != sd->groups);
2318 if (!busiest || this_load >= max_load || busiest_nr_running == 0)
2319 goto out_balanced;
2321 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
2323 if (this_load >= avg_load ||
2324 100*max_load <= sd->imbalance_pct*this_load)
2325 goto out_balanced;
2327 busiest_load_per_task /= busiest_nr_running;
2329 * We're trying to get all the cpus to the average_load, so we don't
2330 * want to push ourselves above the average load, nor do we wish to
2331 * reduce the max loaded cpu below the average load, as either of these
2332 * actions would just result in more rebalancing later, and ping-pong
2333 * tasks around. Thus we look for the minimum possible imbalance.
2334 * Negative imbalances (*we* are more loaded than anyone else) will
2335 * be counted as no imbalance for these purposes -- we can't fix that
2336 * by pulling tasks to us. Be careful of negative numbers as they'll
2337 * appear as very large values with unsigned longs.
2339 if (max_load <= busiest_load_per_task)
2340 goto out_balanced;
2343 * In the presence of smp nice balancing, certain scenarios can have
2344 * max load less than avg load(as we skip the groups at or below
2345 * its cpu_power, while calculating max_load..)
2347 if (max_load < avg_load) {
2348 *imbalance = 0;
2349 goto small_imbalance;
2352 /* Don't want to pull so many tasks that a group would go idle */
2353 max_pull = min(max_load - avg_load, max_load - busiest_load_per_task);
2355 /* How much load to actually move to equalise the imbalance */
2356 *imbalance = min(max_pull * busiest->cpu_power,
2357 (avg_load - this_load) * this->cpu_power)
2358 / SCHED_LOAD_SCALE;
2361 * if *imbalance is less than the average load per runnable task
2362 * there is no gaurantee that any tasks will be moved so we'll have
2363 * a think about bumping its value to force at least one task to be
2364 * moved
2366 if (*imbalance < busiest_load_per_task) {
2367 unsigned long tmp, pwr_now, pwr_move;
2368 unsigned int imbn;
2370 small_imbalance:
2371 pwr_move = pwr_now = 0;
2372 imbn = 2;
2373 if (this_nr_running) {
2374 this_load_per_task /= this_nr_running;
2375 if (busiest_load_per_task > this_load_per_task)
2376 imbn = 1;
2377 } else
2378 this_load_per_task = SCHED_LOAD_SCALE;
2380 if (max_load - this_load >= busiest_load_per_task * imbn) {
2381 *imbalance = busiest_load_per_task;
2382 return busiest;
2386 * OK, we don't have enough imbalance to justify moving tasks,
2387 * however we may be able to increase total CPU power used by
2388 * moving them.
2391 pwr_now += busiest->cpu_power *
2392 min(busiest_load_per_task, max_load);
2393 pwr_now += this->cpu_power *
2394 min(this_load_per_task, this_load);
2395 pwr_now /= SCHED_LOAD_SCALE;
2397 /* Amount of load we'd subtract */
2398 tmp = busiest_load_per_task*SCHED_LOAD_SCALE/busiest->cpu_power;
2399 if (max_load > tmp)
2400 pwr_move += busiest->cpu_power *
2401 min(busiest_load_per_task, max_load - tmp);
2403 /* Amount of load we'd add */
2404 if (max_load*busiest->cpu_power <
2405 busiest_load_per_task*SCHED_LOAD_SCALE)
2406 tmp = max_load*busiest->cpu_power/this->cpu_power;
2407 else
2408 tmp = busiest_load_per_task*SCHED_LOAD_SCALE/this->cpu_power;
2409 pwr_move += this->cpu_power*min(this_load_per_task, this_load + tmp);
2410 pwr_move /= SCHED_LOAD_SCALE;
2412 /* Move if we gain throughput */
2413 if (pwr_move <= pwr_now)
2414 goto out_balanced;
2416 *imbalance = busiest_load_per_task;
2419 return busiest;
2421 out_balanced:
2422 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
2423 if (idle == NOT_IDLE || !(sd->flags & SD_POWERSAVINGS_BALANCE))
2424 goto ret;
2426 if (this == group_leader && group_leader != group_min) {
2427 *imbalance = min_load_per_task;
2428 return group_min;
2430 ret:
2431 #endif
2432 *imbalance = 0;
2433 return NULL;
2437 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2439 static struct rq *
2440 find_busiest_queue(struct sched_group *group, enum idle_type idle,
2441 unsigned long imbalance)
2443 struct rq *busiest = NULL, *rq;
2444 unsigned long max_load = 0;
2445 int i;
2447 for_each_cpu_mask(i, group->cpumask) {
2448 rq = cpu_rq(i);
2450 if (rq->nr_running == 1 && rq->raw_weighted_load > imbalance)
2451 continue;
2453 if (rq->raw_weighted_load > max_load) {
2454 max_load = rq->raw_weighted_load;
2455 busiest = rq;
2459 return busiest;
2463 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2464 * so long as it is large enough.
2466 #define MAX_PINNED_INTERVAL 512
2468 static inline unsigned long minus_1_or_zero(unsigned long n)
2470 return n > 0 ? n - 1 : 0;
2474 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2475 * tasks if there is an imbalance.
2477 * Called with this_rq unlocked.
2479 static int load_balance(int this_cpu, struct rq *this_rq,
2480 struct sched_domain *sd, enum idle_type idle)
2482 int nr_moved, all_pinned = 0, active_balance = 0, sd_idle = 0;
2483 struct sched_group *group;
2484 unsigned long imbalance;
2485 struct rq *busiest;
2487 if (idle != NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER &&
2488 !sched_smt_power_savings)
2489 sd_idle = 1;
2491 schedstat_inc(sd, lb_cnt[idle]);
2493 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle);
2494 if (!group) {
2495 schedstat_inc(sd, lb_nobusyg[idle]);
2496 goto out_balanced;
2499 busiest = find_busiest_queue(group, idle, imbalance);
2500 if (!busiest) {
2501 schedstat_inc(sd, lb_nobusyq[idle]);
2502 goto out_balanced;
2505 BUG_ON(busiest == this_rq);
2507 schedstat_add(sd, lb_imbalance[idle], imbalance);
2509 nr_moved = 0;
2510 if (busiest->nr_running > 1) {
2512 * Attempt to move tasks. If find_busiest_group has found
2513 * an imbalance but busiest->nr_running <= 1, the group is
2514 * still unbalanced. nr_moved simply stays zero, so it is
2515 * correctly treated as an imbalance.
2517 double_rq_lock(this_rq, busiest);
2518 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2519 minus_1_or_zero(busiest->nr_running),
2520 imbalance, sd, idle, &all_pinned);
2521 double_rq_unlock(this_rq, busiest);
2523 /* All tasks on this runqueue were pinned by CPU affinity */
2524 if (unlikely(all_pinned))
2525 goto out_balanced;
2528 if (!nr_moved) {
2529 schedstat_inc(sd, lb_failed[idle]);
2530 sd->nr_balance_failed++;
2532 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
2534 spin_lock(&busiest->lock);
2536 /* don't kick the migration_thread, if the curr
2537 * task on busiest cpu can't be moved to this_cpu
2539 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
2540 spin_unlock(&busiest->lock);
2541 all_pinned = 1;
2542 goto out_one_pinned;
2545 if (!busiest->active_balance) {
2546 busiest->active_balance = 1;
2547 busiest->push_cpu = this_cpu;
2548 active_balance = 1;
2550 spin_unlock(&busiest->lock);
2551 if (active_balance)
2552 wake_up_process(busiest->migration_thread);
2555 * We've kicked active balancing, reset the failure
2556 * counter.
2558 sd->nr_balance_failed = sd->cache_nice_tries+1;
2560 } else
2561 sd->nr_balance_failed = 0;
2563 if (likely(!active_balance)) {
2564 /* We were unbalanced, so reset the balancing interval */
2565 sd->balance_interval = sd->min_interval;
2566 } else {
2568 * If we've begun active balancing, start to back off. This
2569 * case may not be covered by the all_pinned logic if there
2570 * is only 1 task on the busy runqueue (because we don't call
2571 * move_tasks).
2573 if (sd->balance_interval < sd->max_interval)
2574 sd->balance_interval *= 2;
2577 if (!nr_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2578 !sched_smt_power_savings)
2579 return -1;
2580 return nr_moved;
2582 out_balanced:
2583 schedstat_inc(sd, lb_balanced[idle]);
2585 sd->nr_balance_failed = 0;
2587 out_one_pinned:
2588 /* tune up the balancing interval */
2589 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
2590 (sd->balance_interval < sd->max_interval))
2591 sd->balance_interval *= 2;
2593 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2594 !sched_smt_power_savings)
2595 return -1;
2596 return 0;
2600 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2601 * tasks if there is an imbalance.
2603 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2604 * this_rq is locked.
2606 static int
2607 load_balance_newidle(int this_cpu, struct rq *this_rq, struct sched_domain *sd)
2609 struct sched_group *group;
2610 struct rq *busiest = NULL;
2611 unsigned long imbalance;
2612 int nr_moved = 0;
2613 int sd_idle = 0;
2615 if (sd->flags & SD_SHARE_CPUPOWER && !sched_smt_power_savings)
2616 sd_idle = 1;
2618 schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2619 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE, &sd_idle);
2620 if (!group) {
2621 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2622 goto out_balanced;
2625 busiest = find_busiest_queue(group, NEWLY_IDLE, imbalance);
2626 if (!busiest) {
2627 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2628 goto out_balanced;
2631 BUG_ON(busiest == this_rq);
2633 schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2635 nr_moved = 0;
2636 if (busiest->nr_running > 1) {
2637 /* Attempt to move tasks */
2638 double_lock_balance(this_rq, busiest);
2639 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2640 minus_1_or_zero(busiest->nr_running),
2641 imbalance, sd, NEWLY_IDLE, NULL);
2642 spin_unlock(&busiest->lock);
2645 if (!nr_moved) {
2646 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2647 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2648 return -1;
2649 } else
2650 sd->nr_balance_failed = 0;
2652 return nr_moved;
2654 out_balanced:
2655 schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
2656 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER &&
2657 !sched_smt_power_savings)
2658 return -1;
2659 sd->nr_balance_failed = 0;
2661 return 0;
2665 * idle_balance is called by schedule() if this_cpu is about to become
2666 * idle. Attempts to pull tasks from other CPUs.
2668 static void idle_balance(int this_cpu, struct rq *this_rq)
2670 struct sched_domain *sd;
2672 for_each_domain(this_cpu, sd) {
2673 if (sd->flags & SD_BALANCE_NEWIDLE) {
2674 /* If we've pulled tasks over stop searching: */
2675 if (load_balance_newidle(this_cpu, this_rq, sd))
2676 break;
2682 * active_load_balance is run by migration threads. It pushes running tasks
2683 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2684 * running on each physical CPU where possible, and avoids physical /
2685 * logical imbalances.
2687 * Called with busiest_rq locked.
2689 static void active_load_balance(struct rq *busiest_rq, int busiest_cpu)
2691 int target_cpu = busiest_rq->push_cpu;
2692 struct sched_domain *sd;
2693 struct rq *target_rq;
2695 /* Is there any task to move? */
2696 if (busiest_rq->nr_running <= 1)
2697 return;
2699 target_rq = cpu_rq(target_cpu);
2702 * This condition is "impossible", if it occurs
2703 * we need to fix it. Originally reported by
2704 * Bjorn Helgaas on a 128-cpu setup.
2706 BUG_ON(busiest_rq == target_rq);
2708 /* move a task from busiest_rq to target_rq */
2709 double_lock_balance(busiest_rq, target_rq);
2711 /* Search for an sd spanning us and the target CPU. */
2712 for_each_domain(target_cpu, sd) {
2713 if ((sd->flags & SD_LOAD_BALANCE) &&
2714 cpu_isset(busiest_cpu, sd->span))
2715 break;
2718 if (likely(sd)) {
2719 schedstat_inc(sd, alb_cnt);
2721 if (move_tasks(target_rq, target_cpu, busiest_rq, 1,
2722 RTPRIO_TO_LOAD_WEIGHT(100), sd, SCHED_IDLE,
2723 NULL))
2724 schedstat_inc(sd, alb_pushed);
2725 else
2726 schedstat_inc(sd, alb_failed);
2728 spin_unlock(&target_rq->lock);
2732 * rebalance_tick will get called every timer tick, on every CPU.
2734 * It checks each scheduling domain to see if it is due to be balanced,
2735 * and initiates a balancing operation if so.
2737 * Balancing parameters are set up in arch_init_sched_domains.
2740 /* Don't have all balancing operations going off at once: */
2741 static inline unsigned long cpu_offset(int cpu)
2743 return jiffies + cpu * HZ / NR_CPUS;
2746 static void
2747 rebalance_tick(int this_cpu, struct rq *this_rq, enum idle_type idle)
2749 unsigned long this_load, interval, j = cpu_offset(this_cpu);
2750 struct sched_domain *sd;
2751 int i, scale;
2753 this_load = this_rq->raw_weighted_load;
2755 /* Update our load: */
2756 for (i = 0, scale = 1; i < 3; i++, scale <<= 1) {
2757 unsigned long old_load, new_load;
2759 old_load = this_rq->cpu_load[i];
2760 new_load = this_load;
2762 * Round up the averaging division if load is increasing. This
2763 * prevents us from getting stuck on 9 if the load is 10, for
2764 * example.
2766 if (new_load > old_load)
2767 new_load += scale-1;
2768 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) / scale;
2771 for_each_domain(this_cpu, sd) {
2772 if (!(sd->flags & SD_LOAD_BALANCE))
2773 continue;
2775 interval = sd->balance_interval;
2776 if (idle != SCHED_IDLE)
2777 interval *= sd->busy_factor;
2779 /* scale ms to jiffies */
2780 interval = msecs_to_jiffies(interval);
2781 if (unlikely(!interval))
2782 interval = 1;
2784 if (j - sd->last_balance >= interval) {
2785 if (load_balance(this_cpu, this_rq, sd, idle)) {
2787 * We've pulled tasks over so either we're no
2788 * longer idle, or one of our SMT siblings is
2789 * not idle.
2791 idle = NOT_IDLE;
2793 sd->last_balance += interval;
2797 #else
2799 * on UP we do not need to balance between CPUs:
2801 static inline void rebalance_tick(int cpu, struct rq *rq, enum idle_type idle)
2804 static inline void idle_balance(int cpu, struct rq *rq)
2807 #endif
2809 static inline int wake_priority_sleeper(struct rq *rq)
2811 int ret = 0;
2813 #ifdef CONFIG_SCHED_SMT
2814 spin_lock(&rq->lock);
2816 * If an SMT sibling task has been put to sleep for priority
2817 * reasons reschedule the idle task to see if it can now run.
2819 if (rq->nr_running) {
2820 resched_task(rq->idle);
2821 ret = 1;
2823 spin_unlock(&rq->lock);
2824 #endif
2825 return ret;
2828 DEFINE_PER_CPU(struct kernel_stat, kstat);
2830 EXPORT_PER_CPU_SYMBOL(kstat);
2833 * This is called on clock ticks and on context switches.
2834 * Bank in p->sched_time the ns elapsed since the last tick or switch.
2836 static inline void
2837 update_cpu_clock(struct task_struct *p, struct rq *rq, unsigned long long now)
2839 p->sched_time += now - max(p->timestamp, rq->timestamp_last_tick);
2843 * Return current->sched_time plus any more ns on the sched_clock
2844 * that have not yet been banked.
2846 unsigned long long current_sched_time(const struct task_struct *p)
2848 unsigned long long ns;
2849 unsigned long flags;
2851 local_irq_save(flags);
2852 ns = max(p->timestamp, task_rq(p)->timestamp_last_tick);
2853 ns = p->sched_time + sched_clock() - ns;
2854 local_irq_restore(flags);
2856 return ns;
2860 * We place interactive tasks back into the active array, if possible.
2862 * To guarantee that this does not starve expired tasks we ignore the
2863 * interactivity of a task if the first expired task had to wait more
2864 * than a 'reasonable' amount of time. This deadline timeout is
2865 * load-dependent, as the frequency of array switched decreases with
2866 * increasing number of running tasks. We also ignore the interactivity
2867 * if a better static_prio task has expired:
2869 static inline int expired_starving(struct rq *rq)
2871 if (rq->curr->static_prio > rq->best_expired_prio)
2872 return 1;
2873 if (!STARVATION_LIMIT || !rq->expired_timestamp)
2874 return 0;
2875 if (jiffies - rq->expired_timestamp > STARVATION_LIMIT * rq->nr_running)
2876 return 1;
2877 return 0;
2881 * Account user cpu time to a process.
2882 * @p: the process that the cpu time gets accounted to
2883 * @hardirq_offset: the offset to subtract from hardirq_count()
2884 * @cputime: the cpu time spent in user space since the last update
2886 void account_user_time(struct task_struct *p, cputime_t cputime)
2888 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2889 cputime64_t tmp;
2891 p->utime = cputime_add(p->utime, cputime);
2893 /* Add user time to cpustat. */
2894 tmp = cputime_to_cputime64(cputime);
2895 if (TASK_NICE(p) > 0)
2896 cpustat->nice = cputime64_add(cpustat->nice, tmp);
2897 else
2898 cpustat->user = cputime64_add(cpustat->user, tmp);
2902 * Account system cpu time to a process.
2903 * @p: the process that the cpu time gets accounted to
2904 * @hardirq_offset: the offset to subtract from hardirq_count()
2905 * @cputime: the cpu time spent in kernel space since the last update
2907 void account_system_time(struct task_struct *p, int hardirq_offset,
2908 cputime_t cputime)
2910 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2911 struct rq *rq = this_rq();
2912 cputime64_t tmp;
2914 p->stime = cputime_add(p->stime, cputime);
2916 /* Add system time to cpustat. */
2917 tmp = cputime_to_cputime64(cputime);
2918 if (hardirq_count() - hardirq_offset)
2919 cpustat->irq = cputime64_add(cpustat->irq, tmp);
2920 else if (softirq_count())
2921 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
2922 else if (p != rq->idle)
2923 cpustat->system = cputime64_add(cpustat->system, tmp);
2924 else if (atomic_read(&rq->nr_iowait) > 0)
2925 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2926 else
2927 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2928 /* Account for system time used */
2929 acct_update_integrals(p);
2933 * Account for involuntary wait time.
2934 * @p: the process from which the cpu time has been stolen
2935 * @steal: the cpu time spent in involuntary wait
2937 void account_steal_time(struct task_struct *p, cputime_t steal)
2939 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2940 cputime64_t tmp = cputime_to_cputime64(steal);
2941 struct rq *rq = this_rq();
2943 if (p == rq->idle) {
2944 p->stime = cputime_add(p->stime, steal);
2945 if (atomic_read(&rq->nr_iowait) > 0)
2946 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2947 else
2948 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2949 } else
2950 cpustat->steal = cputime64_add(cpustat->steal, tmp);
2954 * This function gets called by the timer code, with HZ frequency.
2955 * We call it with interrupts disabled.
2957 * It also gets called by the fork code, when changing the parent's
2958 * timeslices.
2960 void scheduler_tick(void)
2962 unsigned long long now = sched_clock();
2963 struct task_struct *p = current;
2964 int cpu = smp_processor_id();
2965 struct rq *rq = cpu_rq(cpu);
2967 update_cpu_clock(p, rq, now);
2969 rq->timestamp_last_tick = now;
2971 if (p == rq->idle) {
2972 if (wake_priority_sleeper(rq))
2973 goto out;
2974 rebalance_tick(cpu, rq, SCHED_IDLE);
2975 return;
2978 /* Task might have expired already, but not scheduled off yet */
2979 if (p->array != rq->active) {
2980 set_tsk_need_resched(p);
2981 goto out;
2983 spin_lock(&rq->lock);
2985 * The task was running during this tick - update the
2986 * time slice counter. Note: we do not update a thread's
2987 * priority until it either goes to sleep or uses up its
2988 * timeslice. This makes it possible for interactive tasks
2989 * to use up their timeslices at their highest priority levels.
2991 if (rt_task(p)) {
2993 * RR tasks need a special form of timeslice management.
2994 * FIFO tasks have no timeslices.
2996 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2997 p->time_slice = task_timeslice(p);
2998 p->first_time_slice = 0;
2999 set_tsk_need_resched(p);
3001 /* put it at the end of the queue: */
3002 requeue_task(p, rq->active);
3004 goto out_unlock;
3006 if (!--p->time_slice) {
3007 dequeue_task(p, rq->active);
3008 set_tsk_need_resched(p);
3009 p->prio = effective_prio(p);
3010 p->time_slice = task_timeslice(p);
3011 p->first_time_slice = 0;
3013 if (!rq->expired_timestamp)
3014 rq->expired_timestamp = jiffies;
3015 if (!TASK_INTERACTIVE(p) || expired_starving(rq)) {
3016 enqueue_task(p, rq->expired);
3017 if (p->static_prio < rq->best_expired_prio)
3018 rq->best_expired_prio = p->static_prio;
3019 } else
3020 enqueue_task(p, rq->active);
3021 } else {
3023 * Prevent a too long timeslice allowing a task to monopolize
3024 * the CPU. We do this by splitting up the timeslice into
3025 * smaller pieces.
3027 * Note: this does not mean the task's timeslices expire or
3028 * get lost in any way, they just might be preempted by
3029 * another task of equal priority. (one with higher
3030 * priority would have preempted this task already.) We
3031 * requeue this task to the end of the list on this priority
3032 * level, which is in essence a round-robin of tasks with
3033 * equal priority.
3035 * This only applies to tasks in the interactive
3036 * delta range with at least TIMESLICE_GRANULARITY to requeue.
3038 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
3039 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
3040 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
3041 (p->array == rq->active)) {
3043 requeue_task(p, rq->active);
3044 set_tsk_need_resched(p);
3047 out_unlock:
3048 spin_unlock(&rq->lock);
3049 out:
3050 rebalance_tick(cpu, rq, NOT_IDLE);
3053 #ifdef CONFIG_SCHED_SMT
3054 static inline void wakeup_busy_runqueue(struct rq *rq)
3056 /* If an SMT runqueue is sleeping due to priority reasons wake it up */
3057 if (rq->curr == rq->idle && rq->nr_running)
3058 resched_task(rq->idle);
3062 * Called with interrupt disabled and this_rq's runqueue locked.
3064 static void wake_sleeping_dependent(int this_cpu)
3066 struct sched_domain *tmp, *sd = NULL;
3067 int i;
3069 for_each_domain(this_cpu, tmp) {
3070 if (tmp->flags & SD_SHARE_CPUPOWER) {
3071 sd = tmp;
3072 break;
3076 if (!sd)
3077 return;
3079 for_each_cpu_mask(i, sd->span) {
3080 struct rq *smt_rq = cpu_rq(i);
3082 if (i == this_cpu)
3083 continue;
3084 if (unlikely(!spin_trylock(&smt_rq->lock)))
3085 continue;
3087 wakeup_busy_runqueue(smt_rq);
3088 spin_unlock(&smt_rq->lock);
3093 * number of 'lost' timeslices this task wont be able to fully
3094 * utilize, if another task runs on a sibling. This models the
3095 * slowdown effect of other tasks running on siblings:
3097 static inline unsigned long
3098 smt_slice(struct task_struct *p, struct sched_domain *sd)
3100 return p->time_slice * (100 - sd->per_cpu_gain) / 100;
3104 * To minimise lock contention and not have to drop this_rq's runlock we only
3105 * trylock the sibling runqueues and bypass those runqueues if we fail to
3106 * acquire their lock. As we only trylock the normal locking order does not
3107 * need to be obeyed.
3109 static int
3110 dependent_sleeper(int this_cpu, struct rq *this_rq, struct task_struct *p)
3112 struct sched_domain *tmp, *sd = NULL;
3113 int ret = 0, i;
3115 /* kernel/rt threads do not participate in dependent sleeping */
3116 if (!p->mm || rt_task(p))
3117 return 0;
3119 for_each_domain(this_cpu, tmp) {
3120 if (tmp->flags & SD_SHARE_CPUPOWER) {
3121 sd = tmp;
3122 break;
3126 if (!sd)
3127 return 0;
3129 for_each_cpu_mask(i, sd->span) {
3130 struct task_struct *smt_curr;
3131 struct rq *smt_rq;
3133 if (i == this_cpu)
3134 continue;
3136 smt_rq = cpu_rq(i);
3137 if (unlikely(!spin_trylock(&smt_rq->lock)))
3138 continue;
3140 smt_curr = smt_rq->curr;
3142 if (!smt_curr->mm)
3143 goto unlock;
3146 * If a user task with lower static priority than the
3147 * running task on the SMT sibling is trying to schedule,
3148 * delay it till there is proportionately less timeslice
3149 * left of the sibling task to prevent a lower priority
3150 * task from using an unfair proportion of the
3151 * physical cpu's resources. -ck
3153 if (rt_task(smt_curr)) {
3155 * With real time tasks we run non-rt tasks only
3156 * per_cpu_gain% of the time.
3158 if ((jiffies % DEF_TIMESLICE) >
3159 (sd->per_cpu_gain * DEF_TIMESLICE / 100))
3160 ret = 1;
3161 } else {
3162 if (smt_curr->static_prio < p->static_prio &&
3163 !TASK_PREEMPTS_CURR(p, smt_rq) &&
3164 smt_slice(smt_curr, sd) > task_timeslice(p))
3165 ret = 1;
3167 unlock:
3168 spin_unlock(&smt_rq->lock);
3170 return ret;
3172 #else
3173 static inline void wake_sleeping_dependent(int this_cpu)
3176 static inline int
3177 dependent_sleeper(int this_cpu, struct rq *this_rq, struct task_struct *p)
3179 return 0;
3181 #endif
3183 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
3185 void fastcall add_preempt_count(int val)
3188 * Underflow?
3190 if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3191 return;
3192 preempt_count() += val;
3194 * Spinlock count overflowing soon?
3196 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
3198 EXPORT_SYMBOL(add_preempt_count);
3200 void fastcall sub_preempt_count(int val)
3203 * Underflow?
3205 if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3206 return;
3208 * Is the spinlock portion underflowing?
3210 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3211 !(preempt_count() & PREEMPT_MASK)))
3212 return;
3214 preempt_count() -= val;
3216 EXPORT_SYMBOL(sub_preempt_count);
3218 #endif
3220 static inline int interactive_sleep(enum sleep_type sleep_type)
3222 return (sleep_type == SLEEP_INTERACTIVE ||
3223 sleep_type == SLEEP_INTERRUPTED);
3227 * schedule() is the main scheduler function.
3229 asmlinkage void __sched schedule(void)
3231 struct task_struct *prev, *next;
3232 struct prio_array *array;
3233 struct list_head *queue;
3234 unsigned long long now;
3235 unsigned long run_time;
3236 int cpu, idx, new_prio;
3237 long *switch_count;
3238 struct rq *rq;
3241 * Test if we are atomic. Since do_exit() needs to call into
3242 * schedule() atomically, we ignore that path for now.
3243 * Otherwise, whine if we are scheduling when we should not be.
3245 if (unlikely(in_atomic() && !current->exit_state)) {
3246 printk(KERN_ERR "BUG: scheduling while atomic: "
3247 "%s/0x%08x/%d\n",
3248 current->comm, preempt_count(), current->pid);
3249 dump_stack();
3251 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3253 need_resched:
3254 preempt_disable();
3255 prev = current;
3256 release_kernel_lock(prev);
3257 need_resched_nonpreemptible:
3258 rq = this_rq();
3261 * The idle thread is not allowed to schedule!
3262 * Remove this check after it has been exercised a bit.
3264 if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
3265 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
3266 dump_stack();
3269 schedstat_inc(rq, sched_cnt);
3270 now = sched_clock();
3271 if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
3272 run_time = now - prev->timestamp;
3273 if (unlikely((long long)(now - prev->timestamp) < 0))
3274 run_time = 0;
3275 } else
3276 run_time = NS_MAX_SLEEP_AVG;
3279 * Tasks charged proportionately less run_time at high sleep_avg to
3280 * delay them losing their interactive status
3282 run_time /= (CURRENT_BONUS(prev) ? : 1);
3284 spin_lock_irq(&rq->lock);
3286 if (unlikely(prev->flags & PF_DEAD))
3287 prev->state = EXIT_DEAD;
3289 switch_count = &prev->nivcsw;
3290 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
3291 switch_count = &prev->nvcsw;
3292 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
3293 unlikely(signal_pending(prev))))
3294 prev->state = TASK_RUNNING;
3295 else {
3296 if (prev->state == TASK_UNINTERRUPTIBLE)
3297 rq->nr_uninterruptible++;
3298 deactivate_task(prev, rq);
3302 cpu = smp_processor_id();
3303 if (unlikely(!rq->nr_running)) {
3304 idle_balance(cpu, rq);
3305 if (!rq->nr_running) {
3306 next = rq->idle;
3307 rq->expired_timestamp = 0;
3308 wake_sleeping_dependent(cpu);
3309 goto switch_tasks;
3313 array = rq->active;
3314 if (unlikely(!array->nr_active)) {
3316 * Switch the active and expired arrays.
3318 schedstat_inc(rq, sched_switch);
3319 rq->active = rq->expired;
3320 rq->expired = array;
3321 array = rq->active;
3322 rq->expired_timestamp = 0;
3323 rq->best_expired_prio = MAX_PRIO;
3326 idx = sched_find_first_bit(array->bitmap);
3327 queue = array->queue + idx;
3328 next = list_entry(queue->next, struct task_struct, run_list);
3330 if (!rt_task(next) && interactive_sleep(next->sleep_type)) {
3331 unsigned long long delta = now - next->timestamp;
3332 if (unlikely((long long)(now - next->timestamp) < 0))
3333 delta = 0;
3335 if (next->sleep_type == SLEEP_INTERACTIVE)
3336 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
3338 array = next->array;
3339 new_prio = recalc_task_prio(next, next->timestamp + delta);
3341 if (unlikely(next->prio != new_prio)) {
3342 dequeue_task(next, array);
3343 next->prio = new_prio;
3344 enqueue_task(next, array);
3347 next->sleep_type = SLEEP_NORMAL;
3348 if (dependent_sleeper(cpu, rq, next))
3349 next = rq->idle;
3350 switch_tasks:
3351 if (next == rq->idle)
3352 schedstat_inc(rq, sched_goidle);
3353 prefetch(next);
3354 prefetch_stack(next);
3355 clear_tsk_need_resched(prev);
3356 rcu_qsctr_inc(task_cpu(prev));
3358 update_cpu_clock(prev, rq, now);
3360 prev->sleep_avg -= run_time;
3361 if ((long)prev->sleep_avg <= 0)
3362 prev->sleep_avg = 0;
3363 prev->timestamp = prev->last_ran = now;
3365 sched_info_switch(prev, next);
3366 if (likely(prev != next)) {
3367 next->timestamp = now;
3368 rq->nr_switches++;
3369 rq->curr = next;
3370 ++*switch_count;
3372 prepare_task_switch(rq, next);
3373 prev = context_switch(rq, prev, next);
3374 barrier();
3376 * this_rq must be evaluated again because prev may have moved
3377 * CPUs since it called schedule(), thus the 'rq' on its stack
3378 * frame will be invalid.
3380 finish_task_switch(this_rq(), prev);
3381 } else
3382 spin_unlock_irq(&rq->lock);
3384 prev = current;
3385 if (unlikely(reacquire_kernel_lock(prev) < 0))
3386 goto need_resched_nonpreemptible;
3387 preempt_enable_no_resched();
3388 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3389 goto need_resched;
3391 EXPORT_SYMBOL(schedule);
3393 #ifdef CONFIG_PREEMPT
3395 * this is the entry point to schedule() from in-kernel preemption
3396 * off of preempt_enable. Kernel preemptions off return from interrupt
3397 * occur there and call schedule directly.
3399 asmlinkage void __sched preempt_schedule(void)
3401 struct thread_info *ti = current_thread_info();
3402 #ifdef CONFIG_PREEMPT_BKL
3403 struct task_struct *task = current;
3404 int saved_lock_depth;
3405 #endif
3407 * If there is a non-zero preempt_count or interrupts are disabled,
3408 * we do not want to preempt the current task. Just return..
3410 if (unlikely(ti->preempt_count || irqs_disabled()))
3411 return;
3413 need_resched:
3414 add_preempt_count(PREEMPT_ACTIVE);
3416 * We keep the big kernel semaphore locked, but we
3417 * clear ->lock_depth so that schedule() doesnt
3418 * auto-release the semaphore:
3420 #ifdef CONFIG_PREEMPT_BKL
3421 saved_lock_depth = task->lock_depth;
3422 task->lock_depth = -1;
3423 #endif
3424 schedule();
3425 #ifdef CONFIG_PREEMPT_BKL
3426 task->lock_depth = saved_lock_depth;
3427 #endif
3428 sub_preempt_count(PREEMPT_ACTIVE);
3430 /* we could miss a preemption opportunity between schedule and now */
3431 barrier();
3432 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3433 goto need_resched;
3435 EXPORT_SYMBOL(preempt_schedule);
3438 * this is the entry point to schedule() from kernel preemption
3439 * off of irq context.
3440 * Note, that this is called and return with irqs disabled. This will
3441 * protect us against recursive calling from irq.
3443 asmlinkage void __sched preempt_schedule_irq(void)
3445 struct thread_info *ti = current_thread_info();
3446 #ifdef CONFIG_PREEMPT_BKL
3447 struct task_struct *task = current;
3448 int saved_lock_depth;
3449 #endif
3450 /* Catch callers which need to be fixed */
3451 BUG_ON(ti->preempt_count || !irqs_disabled());
3453 need_resched:
3454 add_preempt_count(PREEMPT_ACTIVE);
3456 * We keep the big kernel semaphore locked, but we
3457 * clear ->lock_depth so that schedule() doesnt
3458 * auto-release the semaphore:
3460 #ifdef CONFIG_PREEMPT_BKL
3461 saved_lock_depth = task->lock_depth;
3462 task->lock_depth = -1;
3463 #endif
3464 local_irq_enable();
3465 schedule();
3466 local_irq_disable();
3467 #ifdef CONFIG_PREEMPT_BKL
3468 task->lock_depth = saved_lock_depth;
3469 #endif
3470 sub_preempt_count(PREEMPT_ACTIVE);
3472 /* we could miss a preemption opportunity between schedule and now */
3473 barrier();
3474 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3475 goto need_resched;
3478 #endif /* CONFIG_PREEMPT */
3480 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
3481 void *key)
3483 return try_to_wake_up(curr->private, mode, sync);
3485 EXPORT_SYMBOL(default_wake_function);
3488 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3489 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3490 * number) then we wake all the non-exclusive tasks and one exclusive task.
3492 * There are circumstances in which we can try to wake a task which has already
3493 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3494 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3496 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3497 int nr_exclusive, int sync, void *key)
3499 struct list_head *tmp, *next;
3501 list_for_each_safe(tmp, next, &q->task_list) {
3502 wait_queue_t *curr = list_entry(tmp, wait_queue_t, task_list);
3503 unsigned flags = curr->flags;
3505 if (curr->func(curr, mode, sync, key) &&
3506 (flags & WQ_FLAG_EXCLUSIVE) && !--nr_exclusive)
3507 break;
3512 * __wake_up - wake up threads blocked on a waitqueue.
3513 * @q: the waitqueue
3514 * @mode: which threads
3515 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3516 * @key: is directly passed to the wakeup function
3518 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
3519 int nr_exclusive, void *key)
3521 unsigned long flags;
3523 spin_lock_irqsave(&q->lock, flags);
3524 __wake_up_common(q, mode, nr_exclusive, 0, key);
3525 spin_unlock_irqrestore(&q->lock, flags);
3527 EXPORT_SYMBOL(__wake_up);
3530 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3532 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3534 __wake_up_common(q, mode, 1, 0, NULL);
3538 * __wake_up_sync - wake up threads blocked on a waitqueue.
3539 * @q: the waitqueue
3540 * @mode: which threads
3541 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3543 * The sync wakeup differs that the waker knows that it will schedule
3544 * away soon, so while the target thread will be woken up, it will not
3545 * be migrated to another CPU - ie. the two threads are 'synchronized'
3546 * with each other. This can prevent needless bouncing between CPUs.
3548 * On UP it can prevent extra preemption.
3550 void fastcall
3551 __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
3553 unsigned long flags;
3554 int sync = 1;
3556 if (unlikely(!q))
3557 return;
3559 if (unlikely(!nr_exclusive))
3560 sync = 0;
3562 spin_lock_irqsave(&q->lock, flags);
3563 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3564 spin_unlock_irqrestore(&q->lock, flags);
3566 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3568 void fastcall complete(struct completion *x)
3570 unsigned long flags;
3572 spin_lock_irqsave(&x->wait.lock, flags);
3573 x->done++;
3574 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3575 1, 0, NULL);
3576 spin_unlock_irqrestore(&x->wait.lock, flags);
3578 EXPORT_SYMBOL(complete);
3580 void fastcall complete_all(struct completion *x)
3582 unsigned long flags;
3584 spin_lock_irqsave(&x->wait.lock, flags);
3585 x->done += UINT_MAX/2;
3586 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3587 0, 0, NULL);
3588 spin_unlock_irqrestore(&x->wait.lock, flags);
3590 EXPORT_SYMBOL(complete_all);
3592 void fastcall __sched wait_for_completion(struct completion *x)
3594 might_sleep();
3596 spin_lock_irq(&x->wait.lock);
3597 if (!x->done) {
3598 DECLARE_WAITQUEUE(wait, current);
3600 wait.flags |= WQ_FLAG_EXCLUSIVE;
3601 __add_wait_queue_tail(&x->wait, &wait);
3602 do {
3603 __set_current_state(TASK_UNINTERRUPTIBLE);
3604 spin_unlock_irq(&x->wait.lock);
3605 schedule();
3606 spin_lock_irq(&x->wait.lock);
3607 } while (!x->done);
3608 __remove_wait_queue(&x->wait, &wait);
3610 x->done--;
3611 spin_unlock_irq(&x->wait.lock);
3613 EXPORT_SYMBOL(wait_for_completion);
3615 unsigned long fastcall __sched
3616 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3618 might_sleep();
3620 spin_lock_irq(&x->wait.lock);
3621 if (!x->done) {
3622 DECLARE_WAITQUEUE(wait, current);
3624 wait.flags |= WQ_FLAG_EXCLUSIVE;
3625 __add_wait_queue_tail(&x->wait, &wait);
3626 do {
3627 __set_current_state(TASK_UNINTERRUPTIBLE);
3628 spin_unlock_irq(&x->wait.lock);
3629 timeout = schedule_timeout(timeout);
3630 spin_lock_irq(&x->wait.lock);
3631 if (!timeout) {
3632 __remove_wait_queue(&x->wait, &wait);
3633 goto out;
3635 } while (!x->done);
3636 __remove_wait_queue(&x->wait, &wait);
3638 x->done--;
3639 out:
3640 spin_unlock_irq(&x->wait.lock);
3641 return timeout;
3643 EXPORT_SYMBOL(wait_for_completion_timeout);
3645 int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3647 int ret = 0;
3649 might_sleep();
3651 spin_lock_irq(&x->wait.lock);
3652 if (!x->done) {
3653 DECLARE_WAITQUEUE(wait, current);
3655 wait.flags |= WQ_FLAG_EXCLUSIVE;
3656 __add_wait_queue_tail(&x->wait, &wait);
3657 do {
3658 if (signal_pending(current)) {
3659 ret = -ERESTARTSYS;
3660 __remove_wait_queue(&x->wait, &wait);
3661 goto out;
3663 __set_current_state(TASK_INTERRUPTIBLE);
3664 spin_unlock_irq(&x->wait.lock);
3665 schedule();
3666 spin_lock_irq(&x->wait.lock);
3667 } while (!x->done);
3668 __remove_wait_queue(&x->wait, &wait);
3670 x->done--;
3671 out:
3672 spin_unlock_irq(&x->wait.lock);
3674 return ret;
3676 EXPORT_SYMBOL(wait_for_completion_interruptible);
3678 unsigned long fastcall __sched
3679 wait_for_completion_interruptible_timeout(struct completion *x,
3680 unsigned long timeout)
3682 might_sleep();
3684 spin_lock_irq(&x->wait.lock);
3685 if (!x->done) {
3686 DECLARE_WAITQUEUE(wait, current);
3688 wait.flags |= WQ_FLAG_EXCLUSIVE;
3689 __add_wait_queue_tail(&x->wait, &wait);
3690 do {
3691 if (signal_pending(current)) {
3692 timeout = -ERESTARTSYS;
3693 __remove_wait_queue(&x->wait, &wait);
3694 goto out;
3696 __set_current_state(TASK_INTERRUPTIBLE);
3697 spin_unlock_irq(&x->wait.lock);
3698 timeout = schedule_timeout(timeout);
3699 spin_lock_irq(&x->wait.lock);
3700 if (!timeout) {
3701 __remove_wait_queue(&x->wait, &wait);
3702 goto out;
3704 } while (!x->done);
3705 __remove_wait_queue(&x->wait, &wait);
3707 x->done--;
3708 out:
3709 spin_unlock_irq(&x->wait.lock);
3710 return timeout;
3712 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3715 #define SLEEP_ON_VAR \
3716 unsigned long flags; \
3717 wait_queue_t wait; \
3718 init_waitqueue_entry(&wait, current);
3720 #define SLEEP_ON_HEAD \
3721 spin_lock_irqsave(&q->lock,flags); \
3722 __add_wait_queue(q, &wait); \
3723 spin_unlock(&q->lock);
3725 #define SLEEP_ON_TAIL \
3726 spin_lock_irq(&q->lock); \
3727 __remove_wait_queue(q, &wait); \
3728 spin_unlock_irqrestore(&q->lock, flags);
3730 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3732 SLEEP_ON_VAR
3734 current->state = TASK_INTERRUPTIBLE;
3736 SLEEP_ON_HEAD
3737 schedule();
3738 SLEEP_ON_TAIL
3740 EXPORT_SYMBOL(interruptible_sleep_on);
3742 long fastcall __sched
3743 interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3745 SLEEP_ON_VAR
3747 current->state = TASK_INTERRUPTIBLE;
3749 SLEEP_ON_HEAD
3750 timeout = schedule_timeout(timeout);
3751 SLEEP_ON_TAIL
3753 return timeout;
3755 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3757 void fastcall __sched sleep_on(wait_queue_head_t *q)
3759 SLEEP_ON_VAR
3761 current->state = TASK_UNINTERRUPTIBLE;
3763 SLEEP_ON_HEAD
3764 schedule();
3765 SLEEP_ON_TAIL
3767 EXPORT_SYMBOL(sleep_on);
3769 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3771 SLEEP_ON_VAR
3773 current->state = TASK_UNINTERRUPTIBLE;
3775 SLEEP_ON_HEAD
3776 timeout = schedule_timeout(timeout);
3777 SLEEP_ON_TAIL
3779 return timeout;
3782 EXPORT_SYMBOL(sleep_on_timeout);
3784 #ifdef CONFIG_RT_MUTEXES
3787 * rt_mutex_setprio - set the current priority of a task
3788 * @p: task
3789 * @prio: prio value (kernel-internal form)
3791 * This function changes the 'effective' priority of a task. It does
3792 * not touch ->normal_prio like __setscheduler().
3794 * Used by the rt_mutex code to implement priority inheritance logic.
3796 void rt_mutex_setprio(struct task_struct *p, int prio)
3798 struct prio_array *array;
3799 unsigned long flags;
3800 struct rq *rq;
3801 int oldprio;
3803 BUG_ON(prio < 0 || prio > MAX_PRIO);
3805 rq = task_rq_lock(p, &flags);
3807 oldprio = p->prio;
3808 array = p->array;
3809 if (array)
3810 dequeue_task(p, array);
3811 p->prio = prio;
3813 if (array) {
3815 * If changing to an RT priority then queue it
3816 * in the active array!
3818 if (rt_task(p))
3819 array = rq->active;
3820 enqueue_task(p, array);
3822 * Reschedule if we are currently running on this runqueue and
3823 * our priority decreased, or if we are not currently running on
3824 * this runqueue and our priority is higher than the current's
3826 if (task_running(rq, p)) {
3827 if (p->prio > oldprio)
3828 resched_task(rq->curr);
3829 } else if (TASK_PREEMPTS_CURR(p, rq))
3830 resched_task(rq->curr);
3832 task_rq_unlock(rq, &flags);
3835 #endif
3837 void set_user_nice(struct task_struct *p, long nice)
3839 struct prio_array *array;
3840 int old_prio, delta;
3841 unsigned long flags;
3842 struct rq *rq;
3844 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3845 return;
3847 * We have to be careful, if called from sys_setpriority(),
3848 * the task might be in the middle of scheduling on another CPU.
3850 rq = task_rq_lock(p, &flags);
3852 * The RT priorities are set via sched_setscheduler(), but we still
3853 * allow the 'normal' nice value to be set - but as expected
3854 * it wont have any effect on scheduling until the task is
3855 * not SCHED_NORMAL/SCHED_BATCH:
3857 if (has_rt_policy(p)) {
3858 p->static_prio = NICE_TO_PRIO(nice);
3859 goto out_unlock;
3861 array = p->array;
3862 if (array) {
3863 dequeue_task(p, array);
3864 dec_raw_weighted_load(rq, p);
3867 p->static_prio = NICE_TO_PRIO(nice);
3868 set_load_weight(p);
3869 old_prio = p->prio;
3870 p->prio = effective_prio(p);
3871 delta = p->prio - old_prio;
3873 if (array) {
3874 enqueue_task(p, array);
3875 inc_raw_weighted_load(rq, p);
3877 * If the task increased its priority or is running and
3878 * lowered its priority, then reschedule its CPU:
3880 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3881 resched_task(rq->curr);
3883 out_unlock:
3884 task_rq_unlock(rq, &flags);
3886 EXPORT_SYMBOL(set_user_nice);
3889 * can_nice - check if a task can reduce its nice value
3890 * @p: task
3891 * @nice: nice value
3893 int can_nice(const struct task_struct *p, const int nice)
3895 /* convert nice value [19,-20] to rlimit style value [1,40] */
3896 int nice_rlim = 20 - nice;
3898 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
3899 capable(CAP_SYS_NICE));
3902 #ifdef __ARCH_WANT_SYS_NICE
3905 * sys_nice - change the priority of the current process.
3906 * @increment: priority increment
3908 * sys_setpriority is a more generic, but much slower function that
3909 * does similar things.
3911 asmlinkage long sys_nice(int increment)
3913 long nice, retval;
3916 * Setpriority might change our priority at the same moment.
3917 * We don't have to worry. Conceptually one call occurs first
3918 * and we have a single winner.
3920 if (increment < -40)
3921 increment = -40;
3922 if (increment > 40)
3923 increment = 40;
3925 nice = PRIO_TO_NICE(current->static_prio) + increment;
3926 if (nice < -20)
3927 nice = -20;
3928 if (nice > 19)
3929 nice = 19;
3931 if (increment < 0 && !can_nice(current, nice))
3932 return -EPERM;
3934 retval = security_task_setnice(current, nice);
3935 if (retval)
3936 return retval;
3938 set_user_nice(current, nice);
3939 return 0;
3942 #endif
3945 * task_prio - return the priority value of a given task.
3946 * @p: the task in question.
3948 * This is the priority value as seen by users in /proc.
3949 * RT tasks are offset by -200. Normal tasks are centered
3950 * around 0, value goes from -16 to +15.
3952 int task_prio(const struct task_struct *p)
3954 return p->prio - MAX_RT_PRIO;
3958 * task_nice - return the nice value of a given task.
3959 * @p: the task in question.
3961 int task_nice(const struct task_struct *p)
3963 return TASK_NICE(p);
3965 EXPORT_SYMBOL_GPL(task_nice);
3968 * idle_cpu - is a given cpu idle currently?
3969 * @cpu: the processor in question.
3971 int idle_cpu(int cpu)
3973 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3977 * idle_task - return the idle task for a given cpu.
3978 * @cpu: the processor in question.
3980 struct task_struct *idle_task(int cpu)
3982 return cpu_rq(cpu)->idle;
3986 * find_process_by_pid - find a process with a matching PID value.
3987 * @pid: the pid in question.
3989 static inline struct task_struct *find_process_by_pid(pid_t pid)
3991 return pid ? find_task_by_pid(pid) : current;
3994 /* Actually do priority change: must hold rq lock. */
3995 static void __setscheduler(struct task_struct *p, int policy, int prio)
3997 BUG_ON(p->array);
3999 p->policy = policy;
4000 p->rt_priority = prio;
4001 p->normal_prio = normal_prio(p);
4002 /* we are holding p->pi_lock already */
4003 p->prio = rt_mutex_getprio(p);
4005 * SCHED_BATCH tasks are treated as perpetual CPU hogs:
4007 if (policy == SCHED_BATCH)
4008 p->sleep_avg = 0;
4009 set_load_weight(p);
4013 * sched_setscheduler - change the scheduling policy and/or RT priority of
4014 * a thread.
4015 * @p: the task in question.
4016 * @policy: new policy.
4017 * @param: structure containing the new RT priority.
4019 int sched_setscheduler(struct task_struct *p, int policy,
4020 struct sched_param *param)
4022 int retval, oldprio, oldpolicy = -1;
4023 struct prio_array *array;
4024 unsigned long flags;
4025 struct rq *rq;
4027 /* may grab non-irq protected spin_locks */
4028 BUG_ON(in_interrupt());
4029 recheck:
4030 /* double check policy once rq lock held */
4031 if (policy < 0)
4032 policy = oldpolicy = p->policy;
4033 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
4034 policy != SCHED_NORMAL && policy != SCHED_BATCH)
4035 return -EINVAL;
4037 * Valid priorities for SCHED_FIFO and SCHED_RR are
4038 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL and
4039 * SCHED_BATCH is 0.
4041 if (param->sched_priority < 0 ||
4042 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
4043 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
4044 return -EINVAL;
4045 if ((policy == SCHED_NORMAL || policy == SCHED_BATCH)
4046 != (param->sched_priority == 0))
4047 return -EINVAL;
4050 * Allow unprivileged RT tasks to decrease priority:
4052 if (!capable(CAP_SYS_NICE)) {
4054 * can't change policy, except between SCHED_NORMAL
4055 * and SCHED_BATCH:
4057 if (((policy != SCHED_NORMAL && p->policy != SCHED_BATCH) &&
4058 (policy != SCHED_BATCH && p->policy != SCHED_NORMAL)) &&
4059 !p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
4060 return -EPERM;
4061 /* can't increase priority */
4062 if ((policy != SCHED_NORMAL && policy != SCHED_BATCH) &&
4063 param->sched_priority > p->rt_priority &&
4064 param->sched_priority >
4065 p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
4066 return -EPERM;
4067 /* can't change other user's priorities */
4068 if ((current->euid != p->euid) &&
4069 (current->euid != p->uid))
4070 return -EPERM;
4073 retval = security_task_setscheduler(p, policy, param);
4074 if (retval)
4075 return retval;
4077 * make sure no PI-waiters arrive (or leave) while we are
4078 * changing the priority of the task:
4080 spin_lock_irqsave(&p->pi_lock, flags);
4082 * To be able to change p->policy safely, the apropriate
4083 * runqueue lock must be held.
4085 rq = __task_rq_lock(p);
4086 /* recheck policy now with rq lock held */
4087 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4088 policy = oldpolicy = -1;
4089 __task_rq_unlock(rq);
4090 spin_unlock_irqrestore(&p->pi_lock, flags);
4091 goto recheck;
4093 array = p->array;
4094 if (array)
4095 deactivate_task(p, rq);
4096 oldprio = p->prio;
4097 __setscheduler(p, policy, param->sched_priority);
4098 if (array) {
4099 __activate_task(p, rq);
4101 * Reschedule if we are currently running on this runqueue and
4102 * our priority decreased, or if we are not currently running on
4103 * this runqueue and our priority is higher than the current's
4105 if (task_running(rq, p)) {
4106 if (p->prio > oldprio)
4107 resched_task(rq->curr);
4108 } else if (TASK_PREEMPTS_CURR(p, rq))
4109 resched_task(rq->curr);
4111 __task_rq_unlock(rq);
4112 spin_unlock_irqrestore(&p->pi_lock, flags);
4114 rt_mutex_adjust_pi(p);
4116 return 0;
4118 EXPORT_SYMBOL_GPL(sched_setscheduler);
4120 static int
4121 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4123 struct sched_param lparam;
4124 struct task_struct *p;
4125 int retval;
4127 if (!param || pid < 0)
4128 return -EINVAL;
4129 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4130 return -EFAULT;
4131 read_lock_irq(&tasklist_lock);
4132 p = find_process_by_pid(pid);
4133 if (!p) {
4134 read_unlock_irq(&tasklist_lock);
4135 return -ESRCH;
4137 get_task_struct(p);
4138 read_unlock_irq(&tasklist_lock);
4139 retval = sched_setscheduler(p, policy, &lparam);
4140 put_task_struct(p);
4142 return retval;
4146 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4147 * @pid: the pid in question.
4148 * @policy: new policy.
4149 * @param: structure containing the new RT priority.
4151 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
4152 struct sched_param __user *param)
4154 /* negative values for policy are not valid */
4155 if (policy < 0)
4156 return -EINVAL;
4158 return do_sched_setscheduler(pid, policy, param);
4162 * sys_sched_setparam - set/change the RT priority of a thread
4163 * @pid: the pid in question.
4164 * @param: structure containing the new RT priority.
4166 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
4168 return do_sched_setscheduler(pid, -1, param);
4172 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4173 * @pid: the pid in question.
4175 asmlinkage long sys_sched_getscheduler(pid_t pid)
4177 struct task_struct *p;
4178 int retval = -EINVAL;
4180 if (pid < 0)
4181 goto out_nounlock;
4183 retval = -ESRCH;
4184 read_lock(&tasklist_lock);
4185 p = find_process_by_pid(pid);
4186 if (p) {
4187 retval = security_task_getscheduler(p);
4188 if (!retval)
4189 retval = p->policy;
4191 read_unlock(&tasklist_lock);
4193 out_nounlock:
4194 return retval;
4198 * sys_sched_getscheduler - get the RT priority of a thread
4199 * @pid: the pid in question.
4200 * @param: structure containing the RT priority.
4202 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
4204 struct sched_param lp;
4205 struct task_struct *p;
4206 int retval = -EINVAL;
4208 if (!param || pid < 0)
4209 goto out_nounlock;
4211 read_lock(&tasklist_lock);
4212 p = find_process_by_pid(pid);
4213 retval = -ESRCH;
4214 if (!p)
4215 goto out_unlock;
4217 retval = security_task_getscheduler(p);
4218 if (retval)
4219 goto out_unlock;
4221 lp.sched_priority = p->rt_priority;
4222 read_unlock(&tasklist_lock);
4225 * This one might sleep, we cannot do it with a spinlock held ...
4227 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4229 out_nounlock:
4230 return retval;
4232 out_unlock:
4233 read_unlock(&tasklist_lock);
4234 return retval;
4237 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
4239 cpumask_t cpus_allowed;
4240 struct task_struct *p;
4241 int retval;
4243 lock_cpu_hotplug();
4244 read_lock(&tasklist_lock);
4246 p = find_process_by_pid(pid);
4247 if (!p) {
4248 read_unlock(&tasklist_lock);
4249 unlock_cpu_hotplug();
4250 return -ESRCH;
4254 * It is not safe to call set_cpus_allowed with the
4255 * tasklist_lock held. We will bump the task_struct's
4256 * usage count and then drop tasklist_lock.
4258 get_task_struct(p);
4259 read_unlock(&tasklist_lock);
4261 retval = -EPERM;
4262 if ((current->euid != p->euid) && (current->euid != p->uid) &&
4263 !capable(CAP_SYS_NICE))
4264 goto out_unlock;
4266 retval = security_task_setscheduler(p, 0, NULL);
4267 if (retval)
4268 goto out_unlock;
4270 cpus_allowed = cpuset_cpus_allowed(p);
4271 cpus_and(new_mask, new_mask, cpus_allowed);
4272 retval = set_cpus_allowed(p, new_mask);
4274 out_unlock:
4275 put_task_struct(p);
4276 unlock_cpu_hotplug();
4277 return retval;
4280 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4281 cpumask_t *new_mask)
4283 if (len < sizeof(cpumask_t)) {
4284 memset(new_mask, 0, sizeof(cpumask_t));
4285 } else if (len > sizeof(cpumask_t)) {
4286 len = sizeof(cpumask_t);
4288 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4292 * sys_sched_setaffinity - set the cpu affinity of a process
4293 * @pid: pid of the process
4294 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4295 * @user_mask_ptr: user-space pointer to the new cpu mask
4297 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
4298 unsigned long __user *user_mask_ptr)
4300 cpumask_t new_mask;
4301 int retval;
4303 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
4304 if (retval)
4305 return retval;
4307 return sched_setaffinity(pid, new_mask);
4311 * Represents all cpu's present in the system
4312 * In systems capable of hotplug, this map could dynamically grow
4313 * as new cpu's are detected in the system via any platform specific
4314 * method, such as ACPI for e.g.
4317 cpumask_t cpu_present_map __read_mostly;
4318 EXPORT_SYMBOL(cpu_present_map);
4320 #ifndef CONFIG_SMP
4321 cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
4322 cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
4323 #endif
4325 long sched_getaffinity(pid_t pid, cpumask_t *mask)
4327 struct task_struct *p;
4328 int retval;
4330 lock_cpu_hotplug();
4331 read_lock(&tasklist_lock);
4333 retval = -ESRCH;
4334 p = find_process_by_pid(pid);
4335 if (!p)
4336 goto out_unlock;
4338 retval = security_task_getscheduler(p);
4339 if (retval)
4340 goto out_unlock;
4342 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
4344 out_unlock:
4345 read_unlock(&tasklist_lock);
4346 unlock_cpu_hotplug();
4347 if (retval)
4348 return retval;
4350 return 0;
4354 * sys_sched_getaffinity - get the cpu affinity of a process
4355 * @pid: pid of the process
4356 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4357 * @user_mask_ptr: user-space pointer to hold the current cpu mask
4359 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
4360 unsigned long __user *user_mask_ptr)
4362 int ret;
4363 cpumask_t mask;
4365 if (len < sizeof(cpumask_t))
4366 return -EINVAL;
4368 ret = sched_getaffinity(pid, &mask);
4369 if (ret < 0)
4370 return ret;
4372 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
4373 return -EFAULT;
4375 return sizeof(cpumask_t);
4379 * sys_sched_yield - yield the current processor to other threads.
4381 * this function yields the current CPU by moving the calling thread
4382 * to the expired array. If there are no other threads running on this
4383 * CPU then this function will return.
4385 asmlinkage long sys_sched_yield(void)
4387 struct rq *rq = this_rq_lock();
4388 struct prio_array *array = current->array, *target = rq->expired;
4390 schedstat_inc(rq, yld_cnt);
4392 * We implement yielding by moving the task into the expired
4393 * queue.
4395 * (special rule: RT tasks will just roundrobin in the active
4396 * array.)
4398 if (rt_task(current))
4399 target = rq->active;
4401 if (array->nr_active == 1) {
4402 schedstat_inc(rq, yld_act_empty);
4403 if (!rq->expired->nr_active)
4404 schedstat_inc(rq, yld_both_empty);
4405 } else if (!rq->expired->nr_active)
4406 schedstat_inc(rq, yld_exp_empty);
4408 if (array != target) {
4409 dequeue_task(current, array);
4410 enqueue_task(current, target);
4411 } else
4413 * requeue_task is cheaper so perform that if possible.
4415 requeue_task(current, array);
4418 * Since we are going to call schedule() anyway, there's
4419 * no need to preempt or enable interrupts:
4421 __release(rq->lock);
4422 spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
4423 _raw_spin_unlock(&rq->lock);
4424 preempt_enable_no_resched();
4426 schedule();
4428 return 0;
4431 static inline int __resched_legal(void)
4433 if (unlikely(preempt_count()))
4434 return 0;
4435 if (unlikely(system_state != SYSTEM_RUNNING))
4436 return 0;
4437 return 1;
4440 static void __cond_resched(void)
4442 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4443 __might_sleep(__FILE__, __LINE__);
4444 #endif
4446 * The BKS might be reacquired before we have dropped
4447 * PREEMPT_ACTIVE, which could trigger a second
4448 * cond_resched() call.
4450 do {
4451 add_preempt_count(PREEMPT_ACTIVE);
4452 schedule();
4453 sub_preempt_count(PREEMPT_ACTIVE);
4454 } while (need_resched());
4457 int __sched cond_resched(void)
4459 if (need_resched() && __resched_legal()) {
4460 __cond_resched();
4461 return 1;
4463 return 0;
4465 EXPORT_SYMBOL(cond_resched);
4468 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4469 * call schedule, and on return reacquire the lock.
4471 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4472 * operations here to prevent schedule() from being called twice (once via
4473 * spin_unlock(), once by hand).
4475 int cond_resched_lock(spinlock_t *lock)
4477 int ret = 0;
4479 if (need_lockbreak(lock)) {
4480 spin_unlock(lock);
4481 cpu_relax();
4482 ret = 1;
4483 spin_lock(lock);
4485 if (need_resched() && __resched_legal()) {
4486 spin_release(&lock->dep_map, 1, _THIS_IP_);
4487 _raw_spin_unlock(lock);
4488 preempt_enable_no_resched();
4489 __cond_resched();
4490 ret = 1;
4491 spin_lock(lock);
4493 return ret;
4495 EXPORT_SYMBOL(cond_resched_lock);
4497 int __sched cond_resched_softirq(void)
4499 BUG_ON(!in_softirq());
4501 if (need_resched() && __resched_legal()) {
4502 raw_local_irq_disable();
4503 _local_bh_enable();
4504 raw_local_irq_enable();
4505 __cond_resched();
4506 local_bh_disable();
4507 return 1;
4509 return 0;
4511 EXPORT_SYMBOL(cond_resched_softirq);
4514 * yield - yield the current processor to other threads.
4516 * this is a shortcut for kernel-space yielding - it marks the
4517 * thread runnable and calls sys_sched_yield().
4519 void __sched yield(void)
4521 set_current_state(TASK_RUNNING);
4522 sys_sched_yield();
4524 EXPORT_SYMBOL(yield);
4527 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4528 * that process accounting knows that this is a task in IO wait state.
4530 * But don't do that if it is a deliberate, throttling IO wait (this task
4531 * has set its backing_dev_info: the queue against which it should throttle)
4533 void __sched io_schedule(void)
4535 struct rq *rq = &__raw_get_cpu_var(runqueues);
4537 atomic_inc(&rq->nr_iowait);
4538 schedule();
4539 atomic_dec(&rq->nr_iowait);
4541 EXPORT_SYMBOL(io_schedule);
4543 long __sched io_schedule_timeout(long timeout)
4545 struct rq *rq = &__raw_get_cpu_var(runqueues);
4546 long ret;
4548 atomic_inc(&rq->nr_iowait);
4549 ret = schedule_timeout(timeout);
4550 atomic_dec(&rq->nr_iowait);
4551 return ret;
4555 * sys_sched_get_priority_max - return maximum RT priority.
4556 * @policy: scheduling class.
4558 * this syscall returns the maximum rt_priority that can be used
4559 * by a given scheduling class.
4561 asmlinkage long sys_sched_get_priority_max(int policy)
4563 int ret = -EINVAL;
4565 switch (policy) {
4566 case SCHED_FIFO:
4567 case SCHED_RR:
4568 ret = MAX_USER_RT_PRIO-1;
4569 break;
4570 case SCHED_NORMAL:
4571 case SCHED_BATCH:
4572 ret = 0;
4573 break;
4575 return ret;
4579 * sys_sched_get_priority_min - return minimum RT priority.
4580 * @policy: scheduling class.
4582 * this syscall returns the minimum rt_priority that can be used
4583 * by a given scheduling class.
4585 asmlinkage long sys_sched_get_priority_min(int policy)
4587 int ret = -EINVAL;
4589 switch (policy) {
4590 case SCHED_FIFO:
4591 case SCHED_RR:
4592 ret = 1;
4593 break;
4594 case SCHED_NORMAL:
4595 case SCHED_BATCH:
4596 ret = 0;
4598 return ret;
4602 * sys_sched_rr_get_interval - return the default timeslice of a process.
4603 * @pid: pid of the process.
4604 * @interval: userspace pointer to the timeslice value.
4606 * this syscall writes the default timeslice value of a given process
4607 * into the user-space timespec buffer. A value of '0' means infinity.
4609 asmlinkage
4610 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4612 struct task_struct *p;
4613 int retval = -EINVAL;
4614 struct timespec t;
4616 if (pid < 0)
4617 goto out_nounlock;
4619 retval = -ESRCH;
4620 read_lock(&tasklist_lock);
4621 p = find_process_by_pid(pid);
4622 if (!p)
4623 goto out_unlock;
4625 retval = security_task_getscheduler(p);
4626 if (retval)
4627 goto out_unlock;
4629 jiffies_to_timespec(p->policy == SCHED_FIFO ?
4630 0 : task_timeslice(p), &t);
4631 read_unlock(&tasklist_lock);
4632 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4633 out_nounlock:
4634 return retval;
4635 out_unlock:
4636 read_unlock(&tasklist_lock);
4637 return retval;
4640 static inline struct task_struct *eldest_child(struct task_struct *p)
4642 if (list_empty(&p->children))
4643 return NULL;
4644 return list_entry(p->children.next,struct task_struct,sibling);
4647 static inline struct task_struct *older_sibling(struct task_struct *p)
4649 if (p->sibling.prev==&p->parent->children)
4650 return NULL;
4651 return list_entry(p->sibling.prev,struct task_struct,sibling);
4654 static inline struct task_struct *younger_sibling(struct task_struct *p)
4656 if (p->sibling.next==&p->parent->children)
4657 return NULL;
4658 return list_entry(p->sibling.next,struct task_struct,sibling);
4661 static const char stat_nam[] = "RSDTtZX";
4663 static void show_task(struct task_struct *p)
4665 struct task_struct *relative;
4666 unsigned long free = 0;
4667 unsigned state;
4669 state = p->state ? __ffs(p->state) + 1 : 0;
4670 printk("%-13.13s %c", p->comm,
4671 state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?');
4672 #if (BITS_PER_LONG == 32)
4673 if (state == TASK_RUNNING)
4674 printk(" running ");
4675 else
4676 printk(" %08lX ", thread_saved_pc(p));
4677 #else
4678 if (state == TASK_RUNNING)
4679 printk(" running task ");
4680 else
4681 printk(" %016lx ", thread_saved_pc(p));
4682 #endif
4683 #ifdef CONFIG_DEBUG_STACK_USAGE
4685 unsigned long *n = end_of_stack(p);
4686 while (!*n)
4687 n++;
4688 free = (unsigned long)n - (unsigned long)end_of_stack(p);
4690 #endif
4691 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
4692 if ((relative = eldest_child(p)))
4693 printk("%5d ", relative->pid);
4694 else
4695 printk(" ");
4696 if ((relative = younger_sibling(p)))
4697 printk("%7d", relative->pid);
4698 else
4699 printk(" ");
4700 if ((relative = older_sibling(p)))
4701 printk(" %5d", relative->pid);
4702 else
4703 printk(" ");
4704 if (!p->mm)
4705 printk(" (L-TLB)\n");
4706 else
4707 printk(" (NOTLB)\n");
4709 if (state != TASK_RUNNING)
4710 show_stack(p, NULL);
4713 void show_state(void)
4715 struct task_struct *g, *p;
4717 #if (BITS_PER_LONG == 32)
4718 printk("\n"
4719 " sibling\n");
4720 printk(" task PC pid father child younger older\n");
4721 #else
4722 printk("\n"
4723 " sibling\n");
4724 printk(" task PC pid father child younger older\n");
4725 #endif
4726 read_lock(&tasklist_lock);
4727 do_each_thread(g, p) {
4729 * reset the NMI-timeout, listing all files on a slow
4730 * console might take alot of time:
4732 touch_nmi_watchdog();
4733 show_task(p);
4734 } while_each_thread(g, p);
4736 read_unlock(&tasklist_lock);
4737 debug_show_all_locks();
4741 * init_idle - set up an idle thread for a given CPU
4742 * @idle: task in question
4743 * @cpu: cpu the idle task belongs to
4745 * NOTE: this function does not set the idle thread's NEED_RESCHED
4746 * flag, to make booting more robust.
4748 void __devinit init_idle(struct task_struct *idle, int cpu)
4750 struct rq *rq = cpu_rq(cpu);
4751 unsigned long flags;
4753 idle->timestamp = sched_clock();
4754 idle->sleep_avg = 0;
4755 idle->array = NULL;
4756 idle->prio = idle->normal_prio = MAX_PRIO;
4757 idle->state = TASK_RUNNING;
4758 idle->cpus_allowed = cpumask_of_cpu(cpu);
4759 set_task_cpu(idle, cpu);
4761 spin_lock_irqsave(&rq->lock, flags);
4762 rq->curr = rq->idle = idle;
4763 #if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
4764 idle->oncpu = 1;
4765 #endif
4766 spin_unlock_irqrestore(&rq->lock, flags);
4768 /* Set the preempt count _outside_ the spinlocks! */
4769 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4770 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
4771 #else
4772 task_thread_info(idle)->preempt_count = 0;
4773 #endif
4777 * In a system that switches off the HZ timer nohz_cpu_mask
4778 * indicates which cpus entered this state. This is used
4779 * in the rcu update to wait only for active cpus. For system
4780 * which do not switch off the HZ timer nohz_cpu_mask should
4781 * always be CPU_MASK_NONE.
4783 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4785 #ifdef CONFIG_SMP
4787 * This is how migration works:
4789 * 1) we queue a struct migration_req structure in the source CPU's
4790 * runqueue and wake up that CPU's migration thread.
4791 * 2) we down() the locked semaphore => thread blocks.
4792 * 3) migration thread wakes up (implicitly it forces the migrated
4793 * thread off the CPU)
4794 * 4) it gets the migration request and checks whether the migrated
4795 * task is still in the wrong runqueue.
4796 * 5) if it's in the wrong runqueue then the migration thread removes
4797 * it and puts it into the right queue.
4798 * 6) migration thread up()s the semaphore.
4799 * 7) we wake up and the migration is done.
4803 * Change a given task's CPU affinity. Migrate the thread to a
4804 * proper CPU and schedule it away if the CPU it's executing on
4805 * is removed from the allowed bitmask.
4807 * NOTE: the caller must have a valid reference to the task, the
4808 * task must not exit() & deallocate itself prematurely. The
4809 * call is not atomic; no spinlocks may be held.
4811 int set_cpus_allowed(struct task_struct *p, cpumask_t new_mask)
4813 struct migration_req req;
4814 unsigned long flags;
4815 struct rq *rq;
4816 int ret = 0;
4818 rq = task_rq_lock(p, &flags);
4819 if (!cpus_intersects(new_mask, cpu_online_map)) {
4820 ret = -EINVAL;
4821 goto out;
4824 p->cpus_allowed = new_mask;
4825 /* Can the task run on the task's current CPU? If so, we're done */
4826 if (cpu_isset(task_cpu(p), new_mask))
4827 goto out;
4829 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4830 /* Need help from migration thread: drop lock and wait. */
4831 task_rq_unlock(rq, &flags);
4832 wake_up_process(rq->migration_thread);
4833 wait_for_completion(&req.done);
4834 tlb_migrate_finish(p->mm);
4835 return 0;
4837 out:
4838 task_rq_unlock(rq, &flags);
4840 return ret;
4842 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4845 * Move (not current) task off this cpu, onto dest cpu. We're doing
4846 * this because either it can't run here any more (set_cpus_allowed()
4847 * away from this CPU, or CPU going down), or because we're
4848 * attempting to rebalance this task on exec (sched_exec).
4850 * So we race with normal scheduler movements, but that's OK, as long
4851 * as the task is no longer on this CPU.
4853 * Returns non-zero if task was successfully migrated.
4855 static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4857 struct rq *rq_dest, *rq_src;
4858 int ret = 0;
4860 if (unlikely(cpu_is_offline(dest_cpu)))
4861 return ret;
4863 rq_src = cpu_rq(src_cpu);
4864 rq_dest = cpu_rq(dest_cpu);
4866 double_rq_lock(rq_src, rq_dest);
4867 /* Already moved. */
4868 if (task_cpu(p) != src_cpu)
4869 goto out;
4870 /* Affinity changed (again). */
4871 if (!cpu_isset(dest_cpu, p->cpus_allowed))
4872 goto out;
4874 set_task_cpu(p, dest_cpu);
4875 if (p->array) {
4877 * Sync timestamp with rq_dest's before activating.
4878 * The same thing could be achieved by doing this step
4879 * afterwards, and pretending it was a local activate.
4880 * This way is cleaner and logically correct.
4882 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4883 + rq_dest->timestamp_last_tick;
4884 deactivate_task(p, rq_src);
4885 __activate_task(p, rq_dest);
4886 if (TASK_PREEMPTS_CURR(p, rq_dest))
4887 resched_task(rq_dest->curr);
4889 ret = 1;
4890 out:
4891 double_rq_unlock(rq_src, rq_dest);
4892 return ret;
4896 * migration_thread - this is a highprio system thread that performs
4897 * thread migration by bumping thread off CPU then 'pushing' onto
4898 * another runqueue.
4900 static int migration_thread(void *data)
4902 int cpu = (long)data;
4903 struct rq *rq;
4905 rq = cpu_rq(cpu);
4906 BUG_ON(rq->migration_thread != current);
4908 set_current_state(TASK_INTERRUPTIBLE);
4909 while (!kthread_should_stop()) {
4910 struct migration_req *req;
4911 struct list_head *head;
4913 try_to_freeze();
4915 spin_lock_irq(&rq->lock);
4917 if (cpu_is_offline(cpu)) {
4918 spin_unlock_irq(&rq->lock);
4919 goto wait_to_die;
4922 if (rq->active_balance) {
4923 active_load_balance(rq, cpu);
4924 rq->active_balance = 0;
4927 head = &rq->migration_queue;
4929 if (list_empty(head)) {
4930 spin_unlock_irq(&rq->lock);
4931 schedule();
4932 set_current_state(TASK_INTERRUPTIBLE);
4933 continue;
4935 req = list_entry(head->next, struct migration_req, list);
4936 list_del_init(head->next);
4938 spin_unlock(&rq->lock);
4939 __migrate_task(req->task, cpu, req->dest_cpu);
4940 local_irq_enable();
4942 complete(&req->done);
4944 __set_current_state(TASK_RUNNING);
4945 return 0;
4947 wait_to_die:
4948 /* Wait for kthread_stop */
4949 set_current_state(TASK_INTERRUPTIBLE);
4950 while (!kthread_should_stop()) {
4951 schedule();
4952 set_current_state(TASK_INTERRUPTIBLE);
4954 __set_current_state(TASK_RUNNING);
4955 return 0;
4958 #ifdef CONFIG_HOTPLUG_CPU
4959 /* Figure out where task on dead CPU should go, use force if neccessary. */
4960 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *p)
4962 unsigned long flags;
4963 cpumask_t mask;
4964 struct rq *rq;
4965 int dest_cpu;
4967 restart:
4968 /* On same node? */
4969 mask = node_to_cpumask(cpu_to_node(dead_cpu));
4970 cpus_and(mask, mask, p->cpus_allowed);
4971 dest_cpu = any_online_cpu(mask);
4973 /* On any allowed CPU? */
4974 if (dest_cpu == NR_CPUS)
4975 dest_cpu = any_online_cpu(p->cpus_allowed);
4977 /* No more Mr. Nice Guy. */
4978 if (dest_cpu == NR_CPUS) {
4979 rq = task_rq_lock(p, &flags);
4980 cpus_setall(p->cpus_allowed);
4981 dest_cpu = any_online_cpu(p->cpus_allowed);
4982 task_rq_unlock(rq, &flags);
4985 * Don't tell them about moving exiting tasks or
4986 * kernel threads (both mm NULL), since they never
4987 * leave kernel.
4989 if (p->mm && printk_ratelimit())
4990 printk(KERN_INFO "process %d (%s) no "
4991 "longer affine to cpu%d\n",
4992 p->pid, p->comm, dead_cpu);
4994 if (!__migrate_task(p, dead_cpu, dest_cpu))
4995 goto restart;
4999 * While a dead CPU has no uninterruptible tasks queued at this point,
5000 * it might still have a nonzero ->nr_uninterruptible counter, because
5001 * for performance reasons the counter is not stricly tracking tasks to
5002 * their home CPUs. So we just add the counter to another CPU's counter,
5003 * to keep the global sum constant after CPU-down:
5005 static void migrate_nr_uninterruptible(struct rq *rq_src)
5007 struct rq *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
5008 unsigned long flags;
5010 local_irq_save(flags);
5011 double_rq_lock(rq_src, rq_dest);
5012 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
5013 rq_src->nr_uninterruptible = 0;
5014 double_rq_unlock(rq_src, rq_dest);
5015 local_irq_restore(flags);
5018 /* Run through task list and migrate tasks from the dead cpu. */
5019 static void migrate_live_tasks(int src_cpu)
5021 struct task_struct *p, *t;
5023 write_lock_irq(&tasklist_lock);
5025 do_each_thread(t, p) {
5026 if (p == current)
5027 continue;
5029 if (task_cpu(p) == src_cpu)
5030 move_task_off_dead_cpu(src_cpu, p);
5031 } while_each_thread(t, p);
5033 write_unlock_irq(&tasklist_lock);
5036 /* Schedules idle task to be the next runnable task on current CPU.
5037 * It does so by boosting its priority to highest possible and adding it to
5038 * the _front_ of the runqueue. Used by CPU offline code.
5040 void sched_idle_next(void)
5042 int this_cpu = smp_processor_id();
5043 struct rq *rq = cpu_rq(this_cpu);
5044 struct task_struct *p = rq->idle;
5045 unsigned long flags;
5047 /* cpu has to be offline */
5048 BUG_ON(cpu_online(this_cpu));
5051 * Strictly not necessary since rest of the CPUs are stopped by now
5052 * and interrupts disabled on the current cpu.
5054 spin_lock_irqsave(&rq->lock, flags);
5056 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
5058 /* Add idle task to the _front_ of its priority queue: */
5059 __activate_idle_task(p, rq);
5061 spin_unlock_irqrestore(&rq->lock, flags);
5065 * Ensures that the idle task is using init_mm right before its cpu goes
5066 * offline.
5068 void idle_task_exit(void)
5070 struct mm_struct *mm = current->active_mm;
5072 BUG_ON(cpu_online(smp_processor_id()));
5074 if (mm != &init_mm)
5075 switch_mm(mm, &init_mm, current);
5076 mmdrop(mm);
5079 static void migrate_dead(unsigned int dead_cpu, struct task_struct *p)
5081 struct rq *rq = cpu_rq(dead_cpu);
5083 /* Must be exiting, otherwise would be on tasklist. */
5084 BUG_ON(p->exit_state != EXIT_ZOMBIE && p->exit_state != EXIT_DEAD);
5086 /* Cannot have done final schedule yet: would have vanished. */
5087 BUG_ON(p->flags & PF_DEAD);
5089 get_task_struct(p);
5092 * Drop lock around migration; if someone else moves it,
5093 * that's OK. No task can be added to this CPU, so iteration is
5094 * fine.
5096 spin_unlock_irq(&rq->lock);
5097 move_task_off_dead_cpu(dead_cpu, p);
5098 spin_lock_irq(&rq->lock);
5100 put_task_struct(p);
5103 /* release_task() removes task from tasklist, so we won't find dead tasks. */
5104 static void migrate_dead_tasks(unsigned int dead_cpu)
5106 struct rq *rq = cpu_rq(dead_cpu);
5107 unsigned int arr, i;
5109 for (arr = 0; arr < 2; arr++) {
5110 for (i = 0; i < MAX_PRIO; i++) {
5111 struct list_head *list = &rq->arrays[arr].queue[i];
5113 while (!list_empty(list))
5114 migrate_dead(dead_cpu, list_entry(list->next,
5115 struct task_struct, run_list));
5119 #endif /* CONFIG_HOTPLUG_CPU */
5122 * migration_call - callback that gets triggered when a CPU is added.
5123 * Here we can start up the necessary migration thread for the new CPU.
5125 static int __cpuinit
5126 migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu)
5128 struct task_struct *p;
5129 int cpu = (long)hcpu;
5130 unsigned long flags;
5131 struct rq *rq;
5133 switch (action) {
5134 case CPU_UP_PREPARE:
5135 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
5136 if (IS_ERR(p))
5137 return NOTIFY_BAD;
5138 p->flags |= PF_NOFREEZE;
5139 kthread_bind(p, cpu);
5140 /* Must be high prio: stop_machine expects to yield to it. */
5141 rq = task_rq_lock(p, &flags);
5142 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
5143 task_rq_unlock(rq, &flags);
5144 cpu_rq(cpu)->migration_thread = p;
5145 break;
5147 case CPU_ONLINE:
5148 /* Strictly unneccessary, as first user will wake it. */
5149 wake_up_process(cpu_rq(cpu)->migration_thread);
5150 break;
5152 #ifdef CONFIG_HOTPLUG_CPU
5153 case CPU_UP_CANCELED:
5154 if (!cpu_rq(cpu)->migration_thread)
5155 break;
5156 /* Unbind it from offline cpu so it can run. Fall thru. */
5157 kthread_bind(cpu_rq(cpu)->migration_thread,
5158 any_online_cpu(cpu_online_map));
5159 kthread_stop(cpu_rq(cpu)->migration_thread);
5160 cpu_rq(cpu)->migration_thread = NULL;
5161 break;
5163 case CPU_DEAD:
5164 migrate_live_tasks(cpu);
5165 rq = cpu_rq(cpu);
5166 kthread_stop(rq->migration_thread);
5167 rq->migration_thread = NULL;
5168 /* Idle task back to normal (off runqueue, low prio) */
5169 rq = task_rq_lock(rq->idle, &flags);
5170 deactivate_task(rq->idle, rq);
5171 rq->idle->static_prio = MAX_PRIO;
5172 __setscheduler(rq->idle, SCHED_NORMAL, 0);
5173 migrate_dead_tasks(cpu);
5174 task_rq_unlock(rq, &flags);
5175 migrate_nr_uninterruptible(rq);
5176 BUG_ON(rq->nr_running != 0);
5178 /* No need to migrate the tasks: it was best-effort if
5179 * they didn't do lock_cpu_hotplug(). Just wake up
5180 * the requestors. */
5181 spin_lock_irq(&rq->lock);
5182 while (!list_empty(&rq->migration_queue)) {
5183 struct migration_req *req;
5185 req = list_entry(rq->migration_queue.next,
5186 struct migration_req, list);
5187 list_del_init(&req->list);
5188 complete(&req->done);
5190 spin_unlock_irq(&rq->lock);
5191 break;
5192 #endif
5194 return NOTIFY_OK;
5197 /* Register at highest priority so that task migration (migrate_all_tasks)
5198 * happens before everything else.
5200 static struct notifier_block __cpuinitdata migration_notifier = {
5201 .notifier_call = migration_call,
5202 .priority = 10
5205 int __init migration_init(void)
5207 void *cpu = (void *)(long)smp_processor_id();
5209 /* Start one for the boot CPU: */
5210 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
5211 migration_call(&migration_notifier, CPU_ONLINE, cpu);
5212 register_cpu_notifier(&migration_notifier);
5214 return 0;
5216 #endif
5218 #ifdef CONFIG_SMP
5219 #undef SCHED_DOMAIN_DEBUG
5220 #ifdef SCHED_DOMAIN_DEBUG
5221 static void sched_domain_debug(struct sched_domain *sd, int cpu)
5223 int level = 0;
5225 if (!sd) {
5226 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
5227 return;
5230 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
5232 do {
5233 int i;
5234 char str[NR_CPUS];
5235 struct sched_group *group = sd->groups;
5236 cpumask_t groupmask;
5238 cpumask_scnprintf(str, NR_CPUS, sd->span);
5239 cpus_clear(groupmask);
5241 printk(KERN_DEBUG);
5242 for (i = 0; i < level + 1; i++)
5243 printk(" ");
5244 printk("domain %d: ", level);
5246 if (!(sd->flags & SD_LOAD_BALANCE)) {
5247 printk("does not load-balance\n");
5248 if (sd->parent)
5249 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
5250 break;
5253 printk("span %s\n", str);
5255 if (!cpu_isset(cpu, sd->span))
5256 printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
5257 if (!cpu_isset(cpu, group->cpumask))
5258 printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
5260 printk(KERN_DEBUG);
5261 for (i = 0; i < level + 2; i++)
5262 printk(" ");
5263 printk("groups:");
5264 do {
5265 if (!group) {
5266 printk("\n");
5267 printk(KERN_ERR "ERROR: group is NULL\n");
5268 break;
5271 if (!group->cpu_power) {
5272 printk("\n");
5273 printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
5276 if (!cpus_weight(group->cpumask)) {
5277 printk("\n");
5278 printk(KERN_ERR "ERROR: empty group\n");
5281 if (cpus_intersects(groupmask, group->cpumask)) {
5282 printk("\n");
5283 printk(KERN_ERR "ERROR: repeated CPUs\n");
5286 cpus_or(groupmask, groupmask, group->cpumask);
5288 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
5289 printk(" %s", str);
5291 group = group->next;
5292 } while (group != sd->groups);
5293 printk("\n");
5295 if (!cpus_equal(sd->span, groupmask))
5296 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
5298 level++;
5299 sd = sd->parent;
5301 if (sd) {
5302 if (!cpus_subset(groupmask, sd->span))
5303 printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
5306 } while (sd);
5308 #else
5309 # define sched_domain_debug(sd, cpu) do { } while (0)
5310 #endif
5312 static int sd_degenerate(struct sched_domain *sd)
5314 if (cpus_weight(sd->span) == 1)
5315 return 1;
5317 /* Following flags need at least 2 groups */
5318 if (sd->flags & (SD_LOAD_BALANCE |
5319 SD_BALANCE_NEWIDLE |
5320 SD_BALANCE_FORK |
5321 SD_BALANCE_EXEC)) {
5322 if (sd->groups != sd->groups->next)
5323 return 0;
5326 /* Following flags don't use groups */
5327 if (sd->flags & (SD_WAKE_IDLE |
5328 SD_WAKE_AFFINE |
5329 SD_WAKE_BALANCE))
5330 return 0;
5332 return 1;
5335 static int
5336 sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent)
5338 unsigned long cflags = sd->flags, pflags = parent->flags;
5340 if (sd_degenerate(parent))
5341 return 1;
5343 if (!cpus_equal(sd->span, parent->span))
5344 return 0;
5346 /* Does parent contain flags not in child? */
5347 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
5348 if (cflags & SD_WAKE_AFFINE)
5349 pflags &= ~SD_WAKE_BALANCE;
5350 /* Flags needing groups don't count if only 1 group in parent */
5351 if (parent->groups == parent->groups->next) {
5352 pflags &= ~(SD_LOAD_BALANCE |
5353 SD_BALANCE_NEWIDLE |
5354 SD_BALANCE_FORK |
5355 SD_BALANCE_EXEC);
5357 if (~cflags & pflags)
5358 return 0;
5360 return 1;
5364 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
5365 * hold the hotplug lock.
5367 static void cpu_attach_domain(struct sched_domain *sd, int cpu)
5369 struct rq *rq = cpu_rq(cpu);
5370 struct sched_domain *tmp;
5372 /* Remove the sched domains which do not contribute to scheduling. */
5373 for (tmp = sd; tmp; tmp = tmp->parent) {
5374 struct sched_domain *parent = tmp->parent;
5375 if (!parent)
5376 break;
5377 if (sd_parent_degenerate(tmp, parent))
5378 tmp->parent = parent->parent;
5381 if (sd && sd_degenerate(sd))
5382 sd = sd->parent;
5384 sched_domain_debug(sd, cpu);
5386 rcu_assign_pointer(rq->sd, sd);
5389 /* cpus with isolated domains */
5390 static cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
5392 /* Setup the mask of cpus configured for isolated domains */
5393 static int __init isolated_cpu_setup(char *str)
5395 int ints[NR_CPUS], i;
5397 str = get_options(str, ARRAY_SIZE(ints), ints);
5398 cpus_clear(cpu_isolated_map);
5399 for (i = 1; i <= ints[0]; i++)
5400 if (ints[i] < NR_CPUS)
5401 cpu_set(ints[i], cpu_isolated_map);
5402 return 1;
5405 __setup ("isolcpus=", isolated_cpu_setup);
5408 * init_sched_build_groups takes an array of groups, the cpumask we wish
5409 * to span, and a pointer to a function which identifies what group a CPU
5410 * belongs to. The return value of group_fn must be a valid index into the
5411 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
5412 * keep track of groups covered with a cpumask_t).
5414 * init_sched_build_groups will build a circular linked list of the groups
5415 * covered by the given span, and will set each group's ->cpumask correctly,
5416 * and ->cpu_power to 0.
5418 static void init_sched_build_groups(struct sched_group groups[], cpumask_t span,
5419 int (*group_fn)(int cpu))
5421 struct sched_group *first = NULL, *last = NULL;
5422 cpumask_t covered = CPU_MASK_NONE;
5423 int i;
5425 for_each_cpu_mask(i, span) {
5426 int group = group_fn(i);
5427 struct sched_group *sg = &groups[group];
5428 int j;
5430 if (cpu_isset(i, covered))
5431 continue;
5433 sg->cpumask = CPU_MASK_NONE;
5434 sg->cpu_power = 0;
5436 for_each_cpu_mask(j, span) {
5437 if (group_fn(j) != group)
5438 continue;
5440 cpu_set(j, covered);
5441 cpu_set(j, sg->cpumask);
5443 if (!first)
5444 first = sg;
5445 if (last)
5446 last->next = sg;
5447 last = sg;
5449 last->next = first;
5452 #define SD_NODES_PER_DOMAIN 16
5455 * Self-tuning task migration cost measurement between source and target CPUs.
5457 * This is done by measuring the cost of manipulating buffers of varying
5458 * sizes. For a given buffer-size here are the steps that are taken:
5460 * 1) the source CPU reads+dirties a shared buffer
5461 * 2) the target CPU reads+dirties the same shared buffer
5463 * We measure how long they take, in the following 4 scenarios:
5465 * - source: CPU1, target: CPU2 | cost1
5466 * - source: CPU2, target: CPU1 | cost2
5467 * - source: CPU1, target: CPU1 | cost3
5468 * - source: CPU2, target: CPU2 | cost4
5470 * We then calculate the cost3+cost4-cost1-cost2 difference - this is
5471 * the cost of migration.
5473 * We then start off from a small buffer-size and iterate up to larger
5474 * buffer sizes, in 5% steps - measuring each buffer-size separately, and
5475 * doing a maximum search for the cost. (The maximum cost for a migration
5476 * normally occurs when the working set size is around the effective cache
5477 * size.)
5479 #define SEARCH_SCOPE 2
5480 #define MIN_CACHE_SIZE (64*1024U)
5481 #define DEFAULT_CACHE_SIZE (5*1024*1024U)
5482 #define ITERATIONS 1
5483 #define SIZE_THRESH 130
5484 #define COST_THRESH 130
5487 * The migration cost is a function of 'domain distance'. Domain
5488 * distance is the number of steps a CPU has to iterate down its
5489 * domain tree to share a domain with the other CPU. The farther
5490 * two CPUs are from each other, the larger the distance gets.
5492 * Note that we use the distance only to cache measurement results,
5493 * the distance value is not used numerically otherwise. When two
5494 * CPUs have the same distance it is assumed that the migration
5495 * cost is the same. (this is a simplification but quite practical)
5497 #define MAX_DOMAIN_DISTANCE 32
5499 static unsigned long long migration_cost[MAX_DOMAIN_DISTANCE] =
5500 { [ 0 ... MAX_DOMAIN_DISTANCE-1 ] =
5502 * Architectures may override the migration cost and thus avoid
5503 * boot-time calibration. Unit is nanoseconds. Mostly useful for
5504 * virtualized hardware:
5506 #ifdef CONFIG_DEFAULT_MIGRATION_COST
5507 CONFIG_DEFAULT_MIGRATION_COST
5508 #else
5509 -1LL
5510 #endif
5514 * Allow override of migration cost - in units of microseconds.
5515 * E.g. migration_cost=1000,2000,3000 will set up a level-1 cost
5516 * of 1 msec, level-2 cost of 2 msecs and level3 cost of 3 msecs:
5518 static int __init migration_cost_setup(char *str)
5520 int ints[MAX_DOMAIN_DISTANCE+1], i;
5522 str = get_options(str, ARRAY_SIZE(ints), ints);
5524 printk("#ints: %d\n", ints[0]);
5525 for (i = 1; i <= ints[0]; i++) {
5526 migration_cost[i-1] = (unsigned long long)ints[i]*1000;
5527 printk("migration_cost[%d]: %Ld\n", i-1, migration_cost[i-1]);
5529 return 1;
5532 __setup ("migration_cost=", migration_cost_setup);
5535 * Global multiplier (divisor) for migration-cutoff values,
5536 * in percentiles. E.g. use a value of 150 to get 1.5 times
5537 * longer cache-hot cutoff times.
5539 * (We scale it from 100 to 128 to long long handling easier.)
5542 #define MIGRATION_FACTOR_SCALE 128
5544 static unsigned int migration_factor = MIGRATION_FACTOR_SCALE;
5546 static int __init setup_migration_factor(char *str)
5548 get_option(&str, &migration_factor);
5549 migration_factor = migration_factor * MIGRATION_FACTOR_SCALE / 100;
5550 return 1;
5553 __setup("migration_factor=", setup_migration_factor);
5556 * Estimated distance of two CPUs, measured via the number of domains
5557 * we have to pass for the two CPUs to be in the same span:
5559 static unsigned long domain_distance(int cpu1, int cpu2)
5561 unsigned long distance = 0;
5562 struct sched_domain *sd;
5564 for_each_domain(cpu1, sd) {
5565 WARN_ON(!cpu_isset(cpu1, sd->span));
5566 if (cpu_isset(cpu2, sd->span))
5567 return distance;
5568 distance++;
5570 if (distance >= MAX_DOMAIN_DISTANCE) {
5571 WARN_ON(1);
5572 distance = MAX_DOMAIN_DISTANCE-1;
5575 return distance;
5578 static unsigned int migration_debug;
5580 static int __init setup_migration_debug(char *str)
5582 get_option(&str, &migration_debug);
5583 return 1;
5586 __setup("migration_debug=", setup_migration_debug);
5589 * Maximum cache-size that the scheduler should try to measure.
5590 * Architectures with larger caches should tune this up during
5591 * bootup. Gets used in the domain-setup code (i.e. during SMP
5592 * bootup).
5594 unsigned int max_cache_size;
5596 static int __init setup_max_cache_size(char *str)
5598 get_option(&str, &max_cache_size);
5599 return 1;
5602 __setup("max_cache_size=", setup_max_cache_size);
5605 * Dirty a big buffer in a hard-to-predict (for the L2 cache) way. This
5606 * is the operation that is timed, so we try to generate unpredictable
5607 * cachemisses that still end up filling the L2 cache:
5609 static void touch_cache(void *__cache, unsigned long __size)
5611 unsigned long size = __size/sizeof(long), chunk1 = size/3,
5612 chunk2 = 2*size/3;
5613 unsigned long *cache = __cache;
5614 int i;
5616 for (i = 0; i < size/6; i += 8) {
5617 switch (i % 6) {
5618 case 0: cache[i]++;
5619 case 1: cache[size-1-i]++;
5620 case 2: cache[chunk1-i]++;
5621 case 3: cache[chunk1+i]++;
5622 case 4: cache[chunk2-i]++;
5623 case 5: cache[chunk2+i]++;
5629 * Measure the cache-cost of one task migration. Returns in units of nsec.
5631 static unsigned long long
5632 measure_one(void *cache, unsigned long size, int source, int target)
5634 cpumask_t mask, saved_mask;
5635 unsigned long long t0, t1, t2, t3, cost;
5637 saved_mask = current->cpus_allowed;
5640 * Flush source caches to RAM and invalidate them:
5642 sched_cacheflush();
5645 * Migrate to the source CPU:
5647 mask = cpumask_of_cpu(source);
5648 set_cpus_allowed(current, mask);
5649 WARN_ON(smp_processor_id() != source);
5652 * Dirty the working set:
5654 t0 = sched_clock();
5655 touch_cache(cache, size);
5656 t1 = sched_clock();
5659 * Migrate to the target CPU, dirty the L2 cache and access
5660 * the shared buffer. (which represents the working set
5661 * of a migrated task.)
5663 mask = cpumask_of_cpu(target);
5664 set_cpus_allowed(current, mask);
5665 WARN_ON(smp_processor_id() != target);
5667 t2 = sched_clock();
5668 touch_cache(cache, size);
5669 t3 = sched_clock();
5671 cost = t1-t0 + t3-t2;
5673 if (migration_debug >= 2)
5674 printk("[%d->%d]: %8Ld %8Ld %8Ld => %10Ld.\n",
5675 source, target, t1-t0, t1-t0, t3-t2, cost);
5677 * Flush target caches to RAM and invalidate them:
5679 sched_cacheflush();
5681 set_cpus_allowed(current, saved_mask);
5683 return cost;
5687 * Measure a series of task migrations and return the average
5688 * result. Since this code runs early during bootup the system
5689 * is 'undisturbed' and the average latency makes sense.
5691 * The algorithm in essence auto-detects the relevant cache-size,
5692 * so it will properly detect different cachesizes for different
5693 * cache-hierarchies, depending on how the CPUs are connected.
5695 * Architectures can prime the upper limit of the search range via
5696 * max_cache_size, otherwise the search range defaults to 20MB...64K.
5698 static unsigned long long
5699 measure_cost(int cpu1, int cpu2, void *cache, unsigned int size)
5701 unsigned long long cost1, cost2;
5702 int i;
5705 * Measure the migration cost of 'size' bytes, over an
5706 * average of 10 runs:
5708 * (We perturb the cache size by a small (0..4k)
5709 * value to compensate size/alignment related artifacts.
5710 * We also subtract the cost of the operation done on
5711 * the same CPU.)
5713 cost1 = 0;
5716 * dry run, to make sure we start off cache-cold on cpu1,
5717 * and to get any vmalloc pagefaults in advance:
5719 measure_one(cache, size, cpu1, cpu2);
5720 for (i = 0; i < ITERATIONS; i++)
5721 cost1 += measure_one(cache, size - i*1024, cpu1, cpu2);
5723 measure_one(cache, size, cpu2, cpu1);
5724 for (i = 0; i < ITERATIONS; i++)
5725 cost1 += measure_one(cache, size - i*1024, cpu2, cpu1);
5728 * (We measure the non-migrating [cached] cost on both
5729 * cpu1 and cpu2, to handle CPUs with different speeds)
5731 cost2 = 0;
5733 measure_one(cache, size, cpu1, cpu1);
5734 for (i = 0; i < ITERATIONS; i++)
5735 cost2 += measure_one(cache, size - i*1024, cpu1, cpu1);
5737 measure_one(cache, size, cpu2, cpu2);
5738 for (i = 0; i < ITERATIONS; i++)
5739 cost2 += measure_one(cache, size - i*1024, cpu2, cpu2);
5742 * Get the per-iteration migration cost:
5744 do_div(cost1, 2*ITERATIONS);
5745 do_div(cost2, 2*ITERATIONS);
5747 return cost1 - cost2;
5750 static unsigned long long measure_migration_cost(int cpu1, int cpu2)
5752 unsigned long long max_cost = 0, fluct = 0, avg_fluct = 0;
5753 unsigned int max_size, size, size_found = 0;
5754 long long cost = 0, prev_cost;
5755 void *cache;
5758 * Search from max_cache_size*5 down to 64K - the real relevant
5759 * cachesize has to lie somewhere inbetween.
5761 if (max_cache_size) {
5762 max_size = max(max_cache_size * SEARCH_SCOPE, MIN_CACHE_SIZE);
5763 size = max(max_cache_size / SEARCH_SCOPE, MIN_CACHE_SIZE);
5764 } else {
5766 * Since we have no estimation about the relevant
5767 * search range
5769 max_size = DEFAULT_CACHE_SIZE * SEARCH_SCOPE;
5770 size = MIN_CACHE_SIZE;
5773 if (!cpu_online(cpu1) || !cpu_online(cpu2)) {
5774 printk("cpu %d and %d not both online!\n", cpu1, cpu2);
5775 return 0;
5779 * Allocate the working set:
5781 cache = vmalloc(max_size);
5782 if (!cache) {
5783 printk("could not vmalloc %d bytes for cache!\n", 2*max_size);
5784 return 1000000; /* return 1 msec on very small boxen */
5787 while (size <= max_size) {
5788 prev_cost = cost;
5789 cost = measure_cost(cpu1, cpu2, cache, size);
5792 * Update the max:
5794 if (cost > 0) {
5795 if (max_cost < cost) {
5796 max_cost = cost;
5797 size_found = size;
5801 * Calculate average fluctuation, we use this to prevent
5802 * noise from triggering an early break out of the loop:
5804 fluct = abs(cost - prev_cost);
5805 avg_fluct = (avg_fluct + fluct)/2;
5807 if (migration_debug)
5808 printk("-> [%d][%d][%7d] %3ld.%ld [%3ld.%ld] (%ld): (%8Ld %8Ld)\n",
5809 cpu1, cpu2, size,
5810 (long)cost / 1000000,
5811 ((long)cost / 100000) % 10,
5812 (long)max_cost / 1000000,
5813 ((long)max_cost / 100000) % 10,
5814 domain_distance(cpu1, cpu2),
5815 cost, avg_fluct);
5818 * If we iterated at least 20% past the previous maximum,
5819 * and the cost has dropped by more than 20% already,
5820 * (taking fluctuations into account) then we assume to
5821 * have found the maximum and break out of the loop early:
5823 if (size_found && (size*100 > size_found*SIZE_THRESH))
5824 if (cost+avg_fluct <= 0 ||
5825 max_cost*100 > (cost+avg_fluct)*COST_THRESH) {
5827 if (migration_debug)
5828 printk("-> found max.\n");
5829 break;
5832 * Increase the cachesize in 10% steps:
5834 size = size * 10 / 9;
5837 if (migration_debug)
5838 printk("[%d][%d] working set size found: %d, cost: %Ld\n",
5839 cpu1, cpu2, size_found, max_cost);
5841 vfree(cache);
5844 * A task is considered 'cache cold' if at least 2 times
5845 * the worst-case cost of migration has passed.
5847 * (this limit is only listened to if the load-balancing
5848 * situation is 'nice' - if there is a large imbalance we
5849 * ignore it for the sake of CPU utilization and
5850 * processing fairness.)
5852 return 2 * max_cost * migration_factor / MIGRATION_FACTOR_SCALE;
5855 static void calibrate_migration_costs(const cpumask_t *cpu_map)
5857 int cpu1 = -1, cpu2 = -1, cpu, orig_cpu = raw_smp_processor_id();
5858 unsigned long j0, j1, distance, max_distance = 0;
5859 struct sched_domain *sd;
5861 j0 = jiffies;
5864 * First pass - calculate the cacheflush times:
5866 for_each_cpu_mask(cpu1, *cpu_map) {
5867 for_each_cpu_mask(cpu2, *cpu_map) {
5868 if (cpu1 == cpu2)
5869 continue;
5870 distance = domain_distance(cpu1, cpu2);
5871 max_distance = max(max_distance, distance);
5873 * No result cached yet?
5875 if (migration_cost[distance] == -1LL)
5876 migration_cost[distance] =
5877 measure_migration_cost(cpu1, cpu2);
5881 * Second pass - update the sched domain hierarchy with
5882 * the new cache-hot-time estimations:
5884 for_each_cpu_mask(cpu, *cpu_map) {
5885 distance = 0;
5886 for_each_domain(cpu, sd) {
5887 sd->cache_hot_time = migration_cost[distance];
5888 distance++;
5892 * Print the matrix:
5894 if (migration_debug)
5895 printk("migration: max_cache_size: %d, cpu: %d MHz:\n",
5896 max_cache_size,
5897 #ifdef CONFIG_X86
5898 cpu_khz/1000
5899 #else
5901 #endif
5903 if (system_state == SYSTEM_BOOTING) {
5904 printk("migration_cost=");
5905 for (distance = 0; distance <= max_distance; distance++) {
5906 if (distance)
5907 printk(",");
5908 printk("%ld", (long)migration_cost[distance] / 1000);
5910 printk("\n");
5912 j1 = jiffies;
5913 if (migration_debug)
5914 printk("migration: %ld seconds\n", (j1-j0)/HZ);
5917 * Move back to the original CPU. NUMA-Q gets confused
5918 * if we migrate to another quad during bootup.
5920 if (raw_smp_processor_id() != orig_cpu) {
5921 cpumask_t mask = cpumask_of_cpu(orig_cpu),
5922 saved_mask = current->cpus_allowed;
5924 set_cpus_allowed(current, mask);
5925 set_cpus_allowed(current, saved_mask);
5929 #ifdef CONFIG_NUMA
5932 * find_next_best_node - find the next node to include in a sched_domain
5933 * @node: node whose sched_domain we're building
5934 * @used_nodes: nodes already in the sched_domain
5936 * Find the next node to include in a given scheduling domain. Simply
5937 * finds the closest node not already in the @used_nodes map.
5939 * Should use nodemask_t.
5941 static int find_next_best_node(int node, unsigned long *used_nodes)
5943 int i, n, val, min_val, best_node = 0;
5945 min_val = INT_MAX;
5947 for (i = 0; i < MAX_NUMNODES; i++) {
5948 /* Start at @node */
5949 n = (node + i) % MAX_NUMNODES;
5951 if (!nr_cpus_node(n))
5952 continue;
5954 /* Skip already used nodes */
5955 if (test_bit(n, used_nodes))
5956 continue;
5958 /* Simple min distance search */
5959 val = node_distance(node, n);
5961 if (val < min_val) {
5962 min_val = val;
5963 best_node = n;
5967 set_bit(best_node, used_nodes);
5968 return best_node;
5972 * sched_domain_node_span - get a cpumask for a node's sched_domain
5973 * @node: node whose cpumask we're constructing
5974 * @size: number of nodes to include in this span
5976 * Given a node, construct a good cpumask for its sched_domain to span. It
5977 * should be one that prevents unnecessary balancing, but also spreads tasks
5978 * out optimally.
5980 static cpumask_t sched_domain_node_span(int node)
5982 DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
5983 cpumask_t span, nodemask;
5984 int i;
5986 cpus_clear(span);
5987 bitmap_zero(used_nodes, MAX_NUMNODES);
5989 nodemask = node_to_cpumask(node);
5990 cpus_or(span, span, nodemask);
5991 set_bit(node, used_nodes);
5993 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
5994 int next_node = find_next_best_node(node, used_nodes);
5996 nodemask = node_to_cpumask(next_node);
5997 cpus_or(span, span, nodemask);
6000 return span;
6002 #endif
6004 int sched_smt_power_savings = 0, sched_mc_power_savings = 0;
6007 * SMT sched-domains:
6009 #ifdef CONFIG_SCHED_SMT
6010 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
6011 static struct sched_group sched_group_cpus[NR_CPUS];
6013 static int cpu_to_cpu_group(int cpu)
6015 return cpu;
6017 #endif
6020 * multi-core sched-domains:
6022 #ifdef CONFIG_SCHED_MC
6023 static DEFINE_PER_CPU(struct sched_domain, core_domains);
6024 static struct sched_group *sched_group_core_bycpu[NR_CPUS];
6025 #endif
6027 #if defined(CONFIG_SCHED_MC) && defined(CONFIG_SCHED_SMT)
6028 static int cpu_to_core_group(int cpu)
6030 return first_cpu(cpu_sibling_map[cpu]);
6032 #elif defined(CONFIG_SCHED_MC)
6033 static int cpu_to_core_group(int cpu)
6035 return cpu;
6037 #endif
6039 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
6040 static struct sched_group *sched_group_phys_bycpu[NR_CPUS];
6042 static int cpu_to_phys_group(int cpu)
6044 #ifdef CONFIG_SCHED_MC
6045 cpumask_t mask = cpu_coregroup_map(cpu);
6046 return first_cpu(mask);
6047 #elif defined(CONFIG_SCHED_SMT)
6048 return first_cpu(cpu_sibling_map[cpu]);
6049 #else
6050 return cpu;
6051 #endif
6054 #ifdef CONFIG_NUMA
6056 * The init_sched_build_groups can't handle what we want to do with node
6057 * groups, so roll our own. Now each node has its own list of groups which
6058 * gets dynamically allocated.
6060 static DEFINE_PER_CPU(struct sched_domain, node_domains);
6061 static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
6063 static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
6064 static struct sched_group *sched_group_allnodes_bycpu[NR_CPUS];
6066 static int cpu_to_allnodes_group(int cpu)
6068 return cpu_to_node(cpu);
6070 static void init_numa_sched_groups_power(struct sched_group *group_head)
6072 struct sched_group *sg = group_head;
6073 int j;
6075 if (!sg)
6076 return;
6077 next_sg:
6078 for_each_cpu_mask(j, sg->cpumask) {
6079 struct sched_domain *sd;
6081 sd = &per_cpu(phys_domains, j);
6082 if (j != first_cpu(sd->groups->cpumask)) {
6084 * Only add "power" once for each
6085 * physical package.
6087 continue;
6090 sg->cpu_power += sd->groups->cpu_power;
6092 sg = sg->next;
6093 if (sg != group_head)
6094 goto next_sg;
6096 #endif
6098 /* Free memory allocated for various sched_group structures */
6099 static void free_sched_groups(const cpumask_t *cpu_map)
6101 int cpu;
6102 #ifdef CONFIG_NUMA
6103 int i;
6105 for_each_cpu_mask(cpu, *cpu_map) {
6106 struct sched_group *sched_group_allnodes
6107 = sched_group_allnodes_bycpu[cpu];
6108 struct sched_group **sched_group_nodes
6109 = sched_group_nodes_bycpu[cpu];
6111 if (sched_group_allnodes) {
6112 kfree(sched_group_allnodes);
6113 sched_group_allnodes_bycpu[cpu] = NULL;
6116 if (!sched_group_nodes)
6117 continue;
6119 for (i = 0; i < MAX_NUMNODES; i++) {
6120 cpumask_t nodemask = node_to_cpumask(i);
6121 struct sched_group *oldsg, *sg = sched_group_nodes[i];
6123 cpus_and(nodemask, nodemask, *cpu_map);
6124 if (cpus_empty(nodemask))
6125 continue;
6127 if (sg == NULL)
6128 continue;
6129 sg = sg->next;
6130 next_sg:
6131 oldsg = sg;
6132 sg = sg->next;
6133 kfree(oldsg);
6134 if (oldsg != sched_group_nodes[i])
6135 goto next_sg;
6137 kfree(sched_group_nodes);
6138 sched_group_nodes_bycpu[cpu] = NULL;
6140 #endif
6141 for_each_cpu_mask(cpu, *cpu_map) {
6142 if (sched_group_phys_bycpu[cpu]) {
6143 kfree(sched_group_phys_bycpu[cpu]);
6144 sched_group_phys_bycpu[cpu] = NULL;
6146 #ifdef CONFIG_SCHED_MC
6147 if (sched_group_core_bycpu[cpu]) {
6148 kfree(sched_group_core_bycpu[cpu]);
6149 sched_group_core_bycpu[cpu] = NULL;
6151 #endif
6156 * Build sched domains for a given set of cpus and attach the sched domains
6157 * to the individual cpus
6159 static int build_sched_domains(const cpumask_t *cpu_map)
6161 int i;
6162 struct sched_group *sched_group_phys = NULL;
6163 #ifdef CONFIG_SCHED_MC
6164 struct sched_group *sched_group_core = NULL;
6165 #endif
6166 #ifdef CONFIG_NUMA
6167 struct sched_group **sched_group_nodes = NULL;
6168 struct sched_group *sched_group_allnodes = NULL;
6171 * Allocate the per-node list of sched groups
6173 sched_group_nodes = kzalloc(sizeof(struct sched_group*)*MAX_NUMNODES,
6174 GFP_KERNEL);
6175 if (!sched_group_nodes) {
6176 printk(KERN_WARNING "Can not alloc sched group node list\n");
6177 return -ENOMEM;
6179 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
6180 #endif
6183 * Set up domains for cpus specified by the cpu_map.
6185 for_each_cpu_mask(i, *cpu_map) {
6186 int group;
6187 struct sched_domain *sd = NULL, *p;
6188 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
6190 cpus_and(nodemask, nodemask, *cpu_map);
6192 #ifdef CONFIG_NUMA
6193 if (cpus_weight(*cpu_map)
6194 > SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
6195 if (!sched_group_allnodes) {
6196 sched_group_allnodes
6197 = kmalloc(sizeof(struct sched_group)
6198 * MAX_NUMNODES,
6199 GFP_KERNEL);
6200 if (!sched_group_allnodes) {
6201 printk(KERN_WARNING
6202 "Can not alloc allnodes sched group\n");
6203 goto error;
6205 sched_group_allnodes_bycpu[i]
6206 = sched_group_allnodes;
6208 sd = &per_cpu(allnodes_domains, i);
6209 *sd = SD_ALLNODES_INIT;
6210 sd->span = *cpu_map;
6211 group = cpu_to_allnodes_group(i);
6212 sd->groups = &sched_group_allnodes[group];
6213 p = sd;
6214 } else
6215 p = NULL;
6217 sd = &per_cpu(node_domains, i);
6218 *sd = SD_NODE_INIT;
6219 sd->span = sched_domain_node_span(cpu_to_node(i));
6220 sd->parent = p;
6221 cpus_and(sd->span, sd->span, *cpu_map);
6222 #endif
6224 if (!sched_group_phys) {
6225 sched_group_phys
6226 = kmalloc(sizeof(struct sched_group) * NR_CPUS,
6227 GFP_KERNEL);
6228 if (!sched_group_phys) {
6229 printk (KERN_WARNING "Can not alloc phys sched"
6230 "group\n");
6231 goto error;
6233 sched_group_phys_bycpu[i] = sched_group_phys;
6236 p = sd;
6237 sd = &per_cpu(phys_domains, i);
6238 group = cpu_to_phys_group(i);
6239 *sd = SD_CPU_INIT;
6240 sd->span = nodemask;
6241 sd->parent = p;
6242 sd->groups = &sched_group_phys[group];
6244 #ifdef CONFIG_SCHED_MC
6245 if (!sched_group_core) {
6246 sched_group_core
6247 = kmalloc(sizeof(struct sched_group) * NR_CPUS,
6248 GFP_KERNEL);
6249 if (!sched_group_core) {
6250 printk (KERN_WARNING "Can not alloc core sched"
6251 "group\n");
6252 goto error;
6254 sched_group_core_bycpu[i] = sched_group_core;
6257 p = sd;
6258 sd = &per_cpu(core_domains, i);
6259 group = cpu_to_core_group(i);
6260 *sd = SD_MC_INIT;
6261 sd->span = cpu_coregroup_map(i);
6262 cpus_and(sd->span, sd->span, *cpu_map);
6263 sd->parent = p;
6264 sd->groups = &sched_group_core[group];
6265 #endif
6267 #ifdef CONFIG_SCHED_SMT
6268 p = sd;
6269 sd = &per_cpu(cpu_domains, i);
6270 group = cpu_to_cpu_group(i);
6271 *sd = SD_SIBLING_INIT;
6272 sd->span = cpu_sibling_map[i];
6273 cpus_and(sd->span, sd->span, *cpu_map);
6274 sd->parent = p;
6275 sd->groups = &sched_group_cpus[group];
6276 #endif
6279 #ifdef CONFIG_SCHED_SMT
6280 /* Set up CPU (sibling) groups */
6281 for_each_cpu_mask(i, *cpu_map) {
6282 cpumask_t this_sibling_map = cpu_sibling_map[i];
6283 cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
6284 if (i != first_cpu(this_sibling_map))
6285 continue;
6287 init_sched_build_groups(sched_group_cpus, this_sibling_map,
6288 &cpu_to_cpu_group);
6290 #endif
6292 #ifdef CONFIG_SCHED_MC
6293 /* Set up multi-core groups */
6294 for_each_cpu_mask(i, *cpu_map) {
6295 cpumask_t this_core_map = cpu_coregroup_map(i);
6296 cpus_and(this_core_map, this_core_map, *cpu_map);
6297 if (i != first_cpu(this_core_map))
6298 continue;
6299 init_sched_build_groups(sched_group_core, this_core_map,
6300 &cpu_to_core_group);
6302 #endif
6305 /* Set up physical groups */
6306 for (i = 0; i < MAX_NUMNODES; i++) {
6307 cpumask_t nodemask = node_to_cpumask(i);
6309 cpus_and(nodemask, nodemask, *cpu_map);
6310 if (cpus_empty(nodemask))
6311 continue;
6313 init_sched_build_groups(sched_group_phys, nodemask,
6314 &cpu_to_phys_group);
6317 #ifdef CONFIG_NUMA
6318 /* Set up node groups */
6319 if (sched_group_allnodes)
6320 init_sched_build_groups(sched_group_allnodes, *cpu_map,
6321 &cpu_to_allnodes_group);
6323 for (i = 0; i < MAX_NUMNODES; i++) {
6324 /* Set up node groups */
6325 struct sched_group *sg, *prev;
6326 cpumask_t nodemask = node_to_cpumask(i);
6327 cpumask_t domainspan;
6328 cpumask_t covered = CPU_MASK_NONE;
6329 int j;
6331 cpus_and(nodemask, nodemask, *cpu_map);
6332 if (cpus_empty(nodemask)) {
6333 sched_group_nodes[i] = NULL;
6334 continue;
6337 domainspan = sched_domain_node_span(i);
6338 cpus_and(domainspan, domainspan, *cpu_map);
6340 sg = kmalloc_node(sizeof(struct sched_group), GFP_KERNEL, i);
6341 if (!sg) {
6342 printk(KERN_WARNING "Can not alloc domain group for "
6343 "node %d\n", i);
6344 goto error;
6346 sched_group_nodes[i] = sg;
6347 for_each_cpu_mask(j, nodemask) {
6348 struct sched_domain *sd;
6349 sd = &per_cpu(node_domains, j);
6350 sd->groups = sg;
6352 sg->cpu_power = 0;
6353 sg->cpumask = nodemask;
6354 sg->next = sg;
6355 cpus_or(covered, covered, nodemask);
6356 prev = sg;
6358 for (j = 0; j < MAX_NUMNODES; j++) {
6359 cpumask_t tmp, notcovered;
6360 int n = (i + j) % MAX_NUMNODES;
6362 cpus_complement(notcovered, covered);
6363 cpus_and(tmp, notcovered, *cpu_map);
6364 cpus_and(tmp, tmp, domainspan);
6365 if (cpus_empty(tmp))
6366 break;
6368 nodemask = node_to_cpumask(n);
6369 cpus_and(tmp, tmp, nodemask);
6370 if (cpus_empty(tmp))
6371 continue;
6373 sg = kmalloc_node(sizeof(struct sched_group),
6374 GFP_KERNEL, i);
6375 if (!sg) {
6376 printk(KERN_WARNING
6377 "Can not alloc domain group for node %d\n", j);
6378 goto error;
6380 sg->cpu_power = 0;
6381 sg->cpumask = tmp;
6382 sg->next = prev->next;
6383 cpus_or(covered, covered, tmp);
6384 prev->next = sg;
6385 prev = sg;
6388 #endif
6390 /* Calculate CPU power for physical packages and nodes */
6391 #ifdef CONFIG_SCHED_SMT
6392 for_each_cpu_mask(i, *cpu_map) {
6393 struct sched_domain *sd;
6394 sd = &per_cpu(cpu_domains, i);
6395 sd->groups->cpu_power = SCHED_LOAD_SCALE;
6397 #endif
6398 #ifdef CONFIG_SCHED_MC
6399 for_each_cpu_mask(i, *cpu_map) {
6400 int power;
6401 struct sched_domain *sd;
6402 sd = &per_cpu(core_domains, i);
6403 if (sched_smt_power_savings)
6404 power = SCHED_LOAD_SCALE * cpus_weight(sd->groups->cpumask);
6405 else
6406 power = SCHED_LOAD_SCALE + (cpus_weight(sd->groups->cpumask)-1)
6407 * SCHED_LOAD_SCALE / 10;
6408 sd->groups->cpu_power = power;
6410 #endif
6412 for_each_cpu_mask(i, *cpu_map) {
6413 struct sched_domain *sd;
6414 #ifdef CONFIG_SCHED_MC
6415 sd = &per_cpu(phys_domains, i);
6416 if (i != first_cpu(sd->groups->cpumask))
6417 continue;
6419 sd->groups->cpu_power = 0;
6420 if (sched_mc_power_savings || sched_smt_power_savings) {
6421 int j;
6423 for_each_cpu_mask(j, sd->groups->cpumask) {
6424 struct sched_domain *sd1;
6425 sd1 = &per_cpu(core_domains, j);
6427 * for each core we will add once
6428 * to the group in physical domain
6430 if (j != first_cpu(sd1->groups->cpumask))
6431 continue;
6433 if (sched_smt_power_savings)
6434 sd->groups->cpu_power += sd1->groups->cpu_power;
6435 else
6436 sd->groups->cpu_power += SCHED_LOAD_SCALE;
6438 } else
6440 * This has to be < 2 * SCHED_LOAD_SCALE
6441 * Lets keep it SCHED_LOAD_SCALE, so that
6442 * while calculating NUMA group's cpu_power
6443 * we can simply do
6444 * numa_group->cpu_power += phys_group->cpu_power;
6446 * See "only add power once for each physical pkg"
6447 * comment below
6449 sd->groups->cpu_power = SCHED_LOAD_SCALE;
6450 #else
6451 int power;
6452 sd = &per_cpu(phys_domains, i);
6453 if (sched_smt_power_savings)
6454 power = SCHED_LOAD_SCALE * cpus_weight(sd->groups->cpumask);
6455 else
6456 power = SCHED_LOAD_SCALE;
6457 sd->groups->cpu_power = power;
6458 #endif
6461 #ifdef CONFIG_NUMA
6462 for (i = 0; i < MAX_NUMNODES; i++)
6463 init_numa_sched_groups_power(sched_group_nodes[i]);
6465 init_numa_sched_groups_power(sched_group_allnodes);
6466 #endif
6468 /* Attach the domains */
6469 for_each_cpu_mask(i, *cpu_map) {
6470 struct sched_domain *sd;
6471 #ifdef CONFIG_SCHED_SMT
6472 sd = &per_cpu(cpu_domains, i);
6473 #elif defined(CONFIG_SCHED_MC)
6474 sd = &per_cpu(core_domains, i);
6475 #else
6476 sd = &per_cpu(phys_domains, i);
6477 #endif
6478 cpu_attach_domain(sd, i);
6481 * Tune cache-hot values:
6483 calibrate_migration_costs(cpu_map);
6485 return 0;
6487 error:
6488 free_sched_groups(cpu_map);
6489 return -ENOMEM;
6492 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
6494 static int arch_init_sched_domains(const cpumask_t *cpu_map)
6496 cpumask_t cpu_default_map;
6497 int err;
6500 * Setup mask for cpus without special case scheduling requirements.
6501 * For now this just excludes isolated cpus, but could be used to
6502 * exclude other special cases in the future.
6504 cpus_andnot(cpu_default_map, *cpu_map, cpu_isolated_map);
6506 err = build_sched_domains(&cpu_default_map);
6508 return err;
6511 static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
6513 free_sched_groups(cpu_map);
6517 * Detach sched domains from a group of cpus specified in cpu_map
6518 * These cpus will now be attached to the NULL domain
6520 static void detach_destroy_domains(const cpumask_t *cpu_map)
6522 int i;
6524 for_each_cpu_mask(i, *cpu_map)
6525 cpu_attach_domain(NULL, i);
6526 synchronize_sched();
6527 arch_destroy_sched_domains(cpu_map);
6531 * Partition sched domains as specified by the cpumasks below.
6532 * This attaches all cpus from the cpumasks to the NULL domain,
6533 * waits for a RCU quiescent period, recalculates sched
6534 * domain information and then attaches them back to the
6535 * correct sched domains
6536 * Call with hotplug lock held
6538 int partition_sched_domains(cpumask_t *partition1, cpumask_t *partition2)
6540 cpumask_t change_map;
6541 int err = 0;
6543 cpus_and(*partition1, *partition1, cpu_online_map);
6544 cpus_and(*partition2, *partition2, cpu_online_map);
6545 cpus_or(change_map, *partition1, *partition2);
6547 /* Detach sched domains from all of the affected cpus */
6548 detach_destroy_domains(&change_map);
6549 if (!cpus_empty(*partition1))
6550 err = build_sched_domains(partition1);
6551 if (!err && !cpus_empty(*partition2))
6552 err = build_sched_domains(partition2);
6554 return err;
6557 #if defined(CONFIG_SCHED_MC) || defined(CONFIG_SCHED_SMT)
6558 int arch_reinit_sched_domains(void)
6560 int err;
6562 lock_cpu_hotplug();
6563 detach_destroy_domains(&cpu_online_map);
6564 err = arch_init_sched_domains(&cpu_online_map);
6565 unlock_cpu_hotplug();
6567 return err;
6570 static ssize_t sched_power_savings_store(const char *buf, size_t count, int smt)
6572 int ret;
6574 if (buf[0] != '0' && buf[0] != '1')
6575 return -EINVAL;
6577 if (smt)
6578 sched_smt_power_savings = (buf[0] == '1');
6579 else
6580 sched_mc_power_savings = (buf[0] == '1');
6582 ret = arch_reinit_sched_domains();
6584 return ret ? ret : count;
6587 int sched_create_sysfs_power_savings_entries(struct sysdev_class *cls)
6589 int err = 0;
6591 #ifdef CONFIG_SCHED_SMT
6592 if (smt_capable())
6593 err = sysfs_create_file(&cls->kset.kobj,
6594 &attr_sched_smt_power_savings.attr);
6595 #endif
6596 #ifdef CONFIG_SCHED_MC
6597 if (!err && mc_capable())
6598 err = sysfs_create_file(&cls->kset.kobj,
6599 &attr_sched_mc_power_savings.attr);
6600 #endif
6601 return err;
6603 #endif
6605 #ifdef CONFIG_SCHED_MC
6606 static ssize_t sched_mc_power_savings_show(struct sys_device *dev, char *page)
6608 return sprintf(page, "%u\n", sched_mc_power_savings);
6610 static ssize_t sched_mc_power_savings_store(struct sys_device *dev,
6611 const char *buf, size_t count)
6613 return sched_power_savings_store(buf, count, 0);
6615 SYSDEV_ATTR(sched_mc_power_savings, 0644, sched_mc_power_savings_show,
6616 sched_mc_power_savings_store);
6617 #endif
6619 #ifdef CONFIG_SCHED_SMT
6620 static ssize_t sched_smt_power_savings_show(struct sys_device *dev, char *page)
6622 return sprintf(page, "%u\n", sched_smt_power_savings);
6624 static ssize_t sched_smt_power_savings_store(struct sys_device *dev,
6625 const char *buf, size_t count)
6627 return sched_power_savings_store(buf, count, 1);
6629 SYSDEV_ATTR(sched_smt_power_savings, 0644, sched_smt_power_savings_show,
6630 sched_smt_power_savings_store);
6631 #endif
6634 #ifdef CONFIG_HOTPLUG_CPU
6636 * Force a reinitialization of the sched domains hierarchy. The domains
6637 * and groups cannot be updated in place without racing with the balancing
6638 * code, so we temporarily attach all running cpus to the NULL domain
6639 * which will prevent rebalancing while the sched domains are recalculated.
6641 static int update_sched_domains(struct notifier_block *nfb,
6642 unsigned long action, void *hcpu)
6644 switch (action) {
6645 case CPU_UP_PREPARE:
6646 case CPU_DOWN_PREPARE:
6647 detach_destroy_domains(&cpu_online_map);
6648 return NOTIFY_OK;
6650 case CPU_UP_CANCELED:
6651 case CPU_DOWN_FAILED:
6652 case CPU_ONLINE:
6653 case CPU_DEAD:
6655 * Fall through and re-initialise the domains.
6657 break;
6658 default:
6659 return NOTIFY_DONE;
6662 /* The hotplug lock is already held by cpu_up/cpu_down */
6663 arch_init_sched_domains(&cpu_online_map);
6665 return NOTIFY_OK;
6667 #endif
6669 void __init sched_init_smp(void)
6671 lock_cpu_hotplug();
6672 arch_init_sched_domains(&cpu_online_map);
6673 unlock_cpu_hotplug();
6674 /* XXX: Theoretical race here - CPU may be hotplugged now */
6675 hotcpu_notifier(update_sched_domains, 0);
6677 #else
6678 void __init sched_init_smp(void)
6681 #endif /* CONFIG_SMP */
6683 int in_sched_functions(unsigned long addr)
6685 /* Linker adds these: start and end of __sched functions */
6686 extern char __sched_text_start[], __sched_text_end[];
6688 return in_lock_functions(addr) ||
6689 (addr >= (unsigned long)__sched_text_start
6690 && addr < (unsigned long)__sched_text_end);
6693 void __init sched_init(void)
6695 int i, j, k;
6697 for_each_possible_cpu(i) {
6698 struct prio_array *array;
6699 struct rq *rq;
6701 rq = cpu_rq(i);
6702 spin_lock_init(&rq->lock);
6703 lockdep_set_class(&rq->lock, &rq->rq_lock_key);
6704 rq->nr_running = 0;
6705 rq->active = rq->arrays;
6706 rq->expired = rq->arrays + 1;
6707 rq->best_expired_prio = MAX_PRIO;
6709 #ifdef CONFIG_SMP
6710 rq->sd = NULL;
6711 for (j = 1; j < 3; j++)
6712 rq->cpu_load[j] = 0;
6713 rq->active_balance = 0;
6714 rq->push_cpu = 0;
6715 rq->migration_thread = NULL;
6716 INIT_LIST_HEAD(&rq->migration_queue);
6717 #endif
6718 atomic_set(&rq->nr_iowait, 0);
6720 for (j = 0; j < 2; j++) {
6721 array = rq->arrays + j;
6722 for (k = 0; k < MAX_PRIO; k++) {
6723 INIT_LIST_HEAD(array->queue + k);
6724 __clear_bit(k, array->bitmap);
6726 // delimiter for bitsearch
6727 __set_bit(MAX_PRIO, array->bitmap);
6731 set_load_weight(&init_task);
6733 * The boot idle thread does lazy MMU switching as well:
6735 atomic_inc(&init_mm.mm_count);
6736 enter_lazy_tlb(&init_mm, current);
6739 * Make us the idle thread. Technically, schedule() should not be
6740 * called from this thread, however somewhere below it might be,
6741 * but because we are the idle thread, we just pick up running again
6742 * when this runqueue becomes "idle".
6744 init_idle(current, smp_processor_id());
6747 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
6748 void __might_sleep(char *file, int line)
6750 #ifdef in_atomic
6751 static unsigned long prev_jiffy; /* ratelimiting */
6753 if ((in_atomic() || irqs_disabled()) &&
6754 system_state == SYSTEM_RUNNING && !oops_in_progress) {
6755 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6756 return;
6757 prev_jiffy = jiffies;
6758 printk(KERN_ERR "BUG: sleeping function called from invalid"
6759 " context at %s:%d\n", file, line);
6760 printk("in_atomic():%d, irqs_disabled():%d\n",
6761 in_atomic(), irqs_disabled());
6762 dump_stack();
6764 #endif
6766 EXPORT_SYMBOL(__might_sleep);
6767 #endif
6769 #ifdef CONFIG_MAGIC_SYSRQ
6770 void normalize_rt_tasks(void)
6772 struct prio_array *array;
6773 struct task_struct *p;
6774 unsigned long flags;
6775 struct rq *rq;
6777 read_lock_irq(&tasklist_lock);
6778 for_each_process(p) {
6779 if (!rt_task(p))
6780 continue;
6782 spin_lock_irqsave(&p->pi_lock, flags);
6783 rq = __task_rq_lock(p);
6785 array = p->array;
6786 if (array)
6787 deactivate_task(p, task_rq(p));
6788 __setscheduler(p, SCHED_NORMAL, 0);
6789 if (array) {
6790 __activate_task(p, task_rq(p));
6791 resched_task(rq->curr);
6794 __task_rq_unlock(rq);
6795 spin_unlock_irqrestore(&p->pi_lock, flags);
6797 read_unlock_irq(&tasklist_lock);
6800 #endif /* CONFIG_MAGIC_SYSRQ */
6802 #ifdef CONFIG_IA64
6804 * These functions are only useful for the IA64 MCA handling.
6806 * They can only be called when the whole system has been
6807 * stopped - every CPU needs to be quiescent, and no scheduling
6808 * activity can take place. Using them for anything else would
6809 * be a serious bug, and as a result, they aren't even visible
6810 * under any other configuration.
6814 * curr_task - return the current task for a given cpu.
6815 * @cpu: the processor in question.
6817 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6819 struct task_struct *curr_task(int cpu)
6821 return cpu_curr(cpu);
6825 * set_curr_task - set the current task for a given cpu.
6826 * @cpu: the processor in question.
6827 * @p: the task pointer to set.
6829 * Description: This function must only be used when non-maskable interrupts
6830 * are serviced on a separate stack. It allows the architecture to switch the
6831 * notion of the current task on a cpu in a non-blocking manner. This function
6832 * must be called with all CPU's synchronized, and interrupts disabled, the
6833 * and caller must save the original value of the current task (see
6834 * curr_task() above) and restore that value before reenabling interrupts and
6835 * re-starting the system.
6837 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6839 void set_curr_task(int cpu, struct task_struct *p)
6841 cpu_curr(cpu) = p;
6844 #endif