[PATCH] mm: pcp use non powers of 2 for batch size
[wandboard.git] / kernel / sched.c
blob9bb7489ee64509eca180fe3cfe755db49b153702
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/completion.h>
31 #include <linux/kernel_stat.h>
32 #include <linux/security.h>
33 #include <linux/notifier.h>
34 #include <linux/profile.h>
35 #include <linux/suspend.h>
36 #include <linux/blkdev.h>
37 #include <linux/delay.h>
38 #include <linux/smp.h>
39 #include <linux/threads.h>
40 #include <linux/timer.h>
41 #include <linux/rcupdate.h>
42 #include <linux/cpu.h>
43 #include <linux/cpuset.h>
44 #include <linux/percpu.h>
45 #include <linux/kthread.h>
46 #include <linux/seq_file.h>
47 #include <linux/syscalls.h>
48 #include <linux/times.h>
49 #include <linux/acct.h>
50 #include <asm/tlb.h>
52 #include <asm/unistd.h>
55 * Convert user-nice values [ -20 ... 0 ... 19 ]
56 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
57 * and back.
59 #define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
60 #define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
61 #define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
64 * 'User priority' is the nice value converted to something we
65 * can work with better when scaling various scheduler parameters,
66 * it's a [ 0 ... 39 ] range.
68 #define USER_PRIO(p) ((p)-MAX_RT_PRIO)
69 #define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
70 #define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
73 * Some helpers for converting nanosecond timing to jiffy resolution
75 #define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
76 #define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
79 * These are the 'tuning knobs' of the scheduler:
81 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
82 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
83 * Timeslices get refilled after they expire.
85 #define MIN_TIMESLICE max(5 * HZ / 1000, 1)
86 #define DEF_TIMESLICE (100 * HZ / 1000)
87 #define ON_RUNQUEUE_WEIGHT 30
88 #define CHILD_PENALTY 95
89 #define PARENT_PENALTY 100
90 #define EXIT_WEIGHT 3
91 #define PRIO_BONUS_RATIO 25
92 #define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
93 #define INTERACTIVE_DELTA 2
94 #define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
95 #define STARVATION_LIMIT (MAX_SLEEP_AVG)
96 #define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
99 * If a task is 'interactive' then we reinsert it in the active
100 * array after it has expired its current timeslice. (it will not
101 * continue to run immediately, it will still roundrobin with
102 * other interactive tasks.)
104 * This part scales the interactivity limit depending on niceness.
106 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
107 * Here are a few examples of different nice levels:
109 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
110 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
111 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
112 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
113 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
115 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
116 * priority range a task can explore, a value of '1' means the
117 * task is rated interactive.)
119 * Ie. nice +19 tasks can never get 'interactive' enough to be
120 * reinserted into the active array. And only heavily CPU-hog nice -20
121 * tasks will be expired. Default nice 0 tasks are somewhere between,
122 * it takes some effort for them to get interactive, but it's not
123 * too hard.
126 #define CURRENT_BONUS(p) \
127 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
128 MAX_SLEEP_AVG)
130 #define GRANULARITY (10 * HZ / 1000 ? : 1)
132 #ifdef CONFIG_SMP
133 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
134 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
135 num_online_cpus())
136 #else
137 #define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
138 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
139 #endif
141 #define SCALE(v1,v1_max,v2_max) \
142 (v1) * (v2_max) / (v1_max)
144 #define DELTA(p) \
145 (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
147 #define TASK_INTERACTIVE(p) \
148 ((p)->prio <= (p)->static_prio - DELTA(p))
150 #define INTERACTIVE_SLEEP(p) \
151 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
152 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
154 #define TASK_PREEMPTS_CURR(p, rq) \
155 ((p)->prio < (rq)->curr->prio)
158 * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
159 * to time slice values: [800ms ... 100ms ... 5ms]
161 * The higher a thread's priority, the bigger timeslices
162 * it gets during one round of execution. But even the lowest
163 * priority thread gets MIN_TIMESLICE worth of execution time.
166 #define SCALE_PRIO(x, prio) \
167 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO/2), MIN_TIMESLICE)
169 static inline unsigned int task_timeslice(task_t *p)
171 if (p->static_prio < NICE_TO_PRIO(0))
172 return SCALE_PRIO(DEF_TIMESLICE*4, p->static_prio);
173 else
174 return SCALE_PRIO(DEF_TIMESLICE, p->static_prio);
176 #define task_hot(p, now, sd) ((long long) ((now) - (p)->last_ran) \
177 < (long long) (sd)->cache_hot_time)
180 * These are the runqueue data structures:
183 #define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
185 typedef struct runqueue runqueue_t;
187 struct prio_array {
188 unsigned int nr_active;
189 unsigned long bitmap[BITMAP_SIZE];
190 struct list_head queue[MAX_PRIO];
194 * This is the main, per-CPU runqueue data structure.
196 * Locking rule: those places that want to lock multiple runqueues
197 * (such as the load balancing or the thread migration code), lock
198 * acquire operations must be ordered by ascending &runqueue.
200 struct runqueue {
201 spinlock_t lock;
204 * nr_running and cpu_load should be in the same cacheline because
205 * remote CPUs use both these fields when doing load calculation.
207 unsigned long nr_running;
208 #ifdef CONFIG_SMP
209 unsigned long cpu_load;
210 #endif
211 unsigned long long nr_switches;
214 * This is part of a global counter where only the total sum
215 * over all CPUs matters. A task can increase this counter on
216 * one CPU and if it got migrated afterwards it may decrease
217 * it on another CPU. Always updated under the runqueue lock:
219 unsigned long nr_uninterruptible;
221 unsigned long expired_timestamp;
222 unsigned long long timestamp_last_tick;
223 task_t *curr, *idle;
224 struct mm_struct *prev_mm;
225 prio_array_t *active, *expired, arrays[2];
226 int best_expired_prio;
227 atomic_t nr_iowait;
229 #ifdef CONFIG_SMP
230 struct sched_domain *sd;
232 /* For active balancing */
233 int active_balance;
234 int push_cpu;
236 task_t *migration_thread;
237 struct list_head migration_queue;
238 #endif
240 #ifdef CONFIG_SCHEDSTATS
241 /* latency stats */
242 struct sched_info rq_sched_info;
244 /* sys_sched_yield() stats */
245 unsigned long yld_exp_empty;
246 unsigned long yld_act_empty;
247 unsigned long yld_both_empty;
248 unsigned long yld_cnt;
250 /* schedule() stats */
251 unsigned long sched_switch;
252 unsigned long sched_cnt;
253 unsigned long sched_goidle;
255 /* try_to_wake_up() stats */
256 unsigned long ttwu_cnt;
257 unsigned long ttwu_local;
258 #endif
261 static DEFINE_PER_CPU(struct runqueue, runqueues);
263 #define for_each_domain(cpu, domain) \
264 for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
266 #define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
267 #define this_rq() (&__get_cpu_var(runqueues))
268 #define task_rq(p) cpu_rq(task_cpu(p))
269 #define cpu_curr(cpu) (cpu_rq(cpu)->curr)
272 * Default context-switch locking:
274 #ifndef prepare_arch_switch
275 # define prepare_arch_switch(rq, next) do { } while (0)
276 # define finish_arch_switch(rq, next) spin_unlock_irq(&(rq)->lock)
277 # define task_running(rq, p) ((rq)->curr == (p))
278 #endif
281 * task_rq_lock - lock the runqueue a given task resides on and disable
282 * interrupts. Note the ordering: we can safely lookup the task_rq without
283 * explicitly disabling preemption.
285 static inline runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
286 __acquires(rq->lock)
288 struct runqueue *rq;
290 repeat_lock_task:
291 local_irq_save(*flags);
292 rq = task_rq(p);
293 spin_lock(&rq->lock);
294 if (unlikely(rq != task_rq(p))) {
295 spin_unlock_irqrestore(&rq->lock, *flags);
296 goto repeat_lock_task;
298 return rq;
301 static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
302 __releases(rq->lock)
304 spin_unlock_irqrestore(&rq->lock, *flags);
307 #ifdef CONFIG_SCHEDSTATS
309 * bump this up when changing the output format or the meaning of an existing
310 * format, so that tools can adapt (or abort)
312 #define SCHEDSTAT_VERSION 11
314 static int show_schedstat(struct seq_file *seq, void *v)
316 int cpu;
318 seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
319 seq_printf(seq, "timestamp %lu\n", jiffies);
320 for_each_online_cpu(cpu) {
321 runqueue_t *rq = cpu_rq(cpu);
322 #ifdef CONFIG_SMP
323 struct sched_domain *sd;
324 int dcnt = 0;
325 #endif
327 /* runqueue-specific stats */
328 seq_printf(seq,
329 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
330 cpu, rq->yld_both_empty,
331 rq->yld_act_empty, rq->yld_exp_empty, rq->yld_cnt,
332 rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
333 rq->ttwu_cnt, rq->ttwu_local,
334 rq->rq_sched_info.cpu_time,
335 rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
337 seq_printf(seq, "\n");
339 #ifdef CONFIG_SMP
340 /* domain-specific stats */
341 for_each_domain(cpu, sd) {
342 enum idle_type itype;
343 char mask_str[NR_CPUS];
345 cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
346 seq_printf(seq, "domain%d %s", dcnt++, mask_str);
347 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
348 itype++) {
349 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu",
350 sd->lb_cnt[itype],
351 sd->lb_balanced[itype],
352 sd->lb_failed[itype],
353 sd->lb_imbalance[itype],
354 sd->lb_gained[itype],
355 sd->lb_hot_gained[itype],
356 sd->lb_nobusyq[itype],
357 sd->lb_nobusyg[itype]);
359 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu\n",
360 sd->alb_cnt, sd->alb_failed, sd->alb_pushed,
361 sd->sbe_pushed, sd->sbe_attempts,
362 sd->ttwu_wake_remote, sd->ttwu_move_affine, sd->ttwu_move_balance);
364 #endif
366 return 0;
369 static int schedstat_open(struct inode *inode, struct file *file)
371 unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
372 char *buf = kmalloc(size, GFP_KERNEL);
373 struct seq_file *m;
374 int res;
376 if (!buf)
377 return -ENOMEM;
378 res = single_open(file, show_schedstat, NULL);
379 if (!res) {
380 m = file->private_data;
381 m->buf = buf;
382 m->size = size;
383 } else
384 kfree(buf);
385 return res;
388 struct file_operations proc_schedstat_operations = {
389 .open = schedstat_open,
390 .read = seq_read,
391 .llseek = seq_lseek,
392 .release = single_release,
395 # define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
396 # define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
397 #else /* !CONFIG_SCHEDSTATS */
398 # define schedstat_inc(rq, field) do { } while (0)
399 # define schedstat_add(rq, field, amt) do { } while (0)
400 #endif
403 * rq_lock - lock a given runqueue and disable interrupts.
405 static inline runqueue_t *this_rq_lock(void)
406 __acquires(rq->lock)
408 runqueue_t *rq;
410 local_irq_disable();
411 rq = this_rq();
412 spin_lock(&rq->lock);
414 return rq;
417 #ifdef CONFIG_SCHED_SMT
418 static int cpu_and_siblings_are_idle(int cpu)
420 int sib;
421 for_each_cpu_mask(sib, cpu_sibling_map[cpu]) {
422 if (idle_cpu(sib))
423 continue;
424 return 0;
427 return 1;
429 #else
430 #define cpu_and_siblings_are_idle(A) idle_cpu(A)
431 #endif
433 #ifdef CONFIG_SCHEDSTATS
435 * Called when a process is dequeued from the active array and given
436 * the cpu. We should note that with the exception of interactive
437 * tasks, the expired queue will become the active queue after the active
438 * queue is empty, without explicitly dequeuing and requeuing tasks in the
439 * expired queue. (Interactive tasks may be requeued directly to the
440 * active queue, thus delaying tasks in the expired queue from running;
441 * see scheduler_tick()).
443 * This function is only called from sched_info_arrive(), rather than
444 * dequeue_task(). Even though a task may be queued and dequeued multiple
445 * times as it is shuffled about, we're really interested in knowing how
446 * long it was from the *first* time it was queued to the time that it
447 * finally hit a cpu.
449 static inline void sched_info_dequeued(task_t *t)
451 t->sched_info.last_queued = 0;
455 * Called when a task finally hits the cpu. We can now calculate how
456 * long it was waiting to run. We also note when it began so that we
457 * can keep stats on how long its timeslice is.
459 static inline void sched_info_arrive(task_t *t)
461 unsigned long now = jiffies, diff = 0;
462 struct runqueue *rq = task_rq(t);
464 if (t->sched_info.last_queued)
465 diff = now - t->sched_info.last_queued;
466 sched_info_dequeued(t);
467 t->sched_info.run_delay += diff;
468 t->sched_info.last_arrival = now;
469 t->sched_info.pcnt++;
471 if (!rq)
472 return;
474 rq->rq_sched_info.run_delay += diff;
475 rq->rq_sched_info.pcnt++;
479 * Called when a process is queued into either the active or expired
480 * array. The time is noted and later used to determine how long we
481 * had to wait for us to reach the cpu. Since the expired queue will
482 * become the active queue after active queue is empty, without dequeuing
483 * and requeuing any tasks, we are interested in queuing to either. It
484 * is unusual but not impossible for tasks to be dequeued and immediately
485 * requeued in the same or another array: this can happen in sched_yield(),
486 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
487 * to runqueue.
489 * This function is only called from enqueue_task(), but also only updates
490 * the timestamp if it is already not set. It's assumed that
491 * sched_info_dequeued() will clear that stamp when appropriate.
493 static inline void sched_info_queued(task_t *t)
495 if (!t->sched_info.last_queued)
496 t->sched_info.last_queued = jiffies;
500 * Called when a process ceases being the active-running process, either
501 * voluntarily or involuntarily. Now we can calculate how long we ran.
503 static inline void sched_info_depart(task_t *t)
505 struct runqueue *rq = task_rq(t);
506 unsigned long diff = jiffies - t->sched_info.last_arrival;
508 t->sched_info.cpu_time += diff;
510 if (rq)
511 rq->rq_sched_info.cpu_time += diff;
515 * Called when tasks are switched involuntarily due, typically, to expiring
516 * their time slice. (This may also be called when switching to or from
517 * the idle task.) We are only called when prev != next.
519 static inline void sched_info_switch(task_t *prev, task_t *next)
521 struct runqueue *rq = task_rq(prev);
524 * prev now departs the cpu. It's not interesting to record
525 * stats about how efficient we were at scheduling the idle
526 * process, however.
528 if (prev != rq->idle)
529 sched_info_depart(prev);
531 if (next != rq->idle)
532 sched_info_arrive(next);
534 #else
535 #define sched_info_queued(t) do { } while (0)
536 #define sched_info_switch(t, next) do { } while (0)
537 #endif /* CONFIG_SCHEDSTATS */
540 * Adding/removing a task to/from a priority array:
542 static void dequeue_task(struct task_struct *p, prio_array_t *array)
544 array->nr_active--;
545 list_del(&p->run_list);
546 if (list_empty(array->queue + p->prio))
547 __clear_bit(p->prio, array->bitmap);
550 static void enqueue_task(struct task_struct *p, prio_array_t *array)
552 sched_info_queued(p);
553 list_add_tail(&p->run_list, array->queue + p->prio);
554 __set_bit(p->prio, array->bitmap);
555 array->nr_active++;
556 p->array = array;
560 * Put task to the end of the run list without the overhead of dequeue
561 * followed by enqueue.
563 static void requeue_task(struct task_struct *p, prio_array_t *array)
565 list_move_tail(&p->run_list, array->queue + p->prio);
568 static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
570 list_add(&p->run_list, array->queue + p->prio);
571 __set_bit(p->prio, array->bitmap);
572 array->nr_active++;
573 p->array = array;
577 * effective_prio - return the priority that is based on the static
578 * priority but is modified by bonuses/penalties.
580 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
581 * into the -5 ... 0 ... +5 bonus/penalty range.
583 * We use 25% of the full 0...39 priority range so that:
585 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
586 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
588 * Both properties are important to certain workloads.
590 static int effective_prio(task_t *p)
592 int bonus, prio;
594 if (rt_task(p))
595 return p->prio;
597 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
599 prio = p->static_prio - bonus;
600 if (prio < MAX_RT_PRIO)
601 prio = MAX_RT_PRIO;
602 if (prio > MAX_PRIO-1)
603 prio = MAX_PRIO-1;
604 return prio;
608 * __activate_task - move a task to the runqueue.
610 static inline void __activate_task(task_t *p, runqueue_t *rq)
612 enqueue_task(p, rq->active);
613 rq->nr_running++;
617 * __activate_idle_task - move idle task to the _front_ of runqueue.
619 static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
621 enqueue_task_head(p, rq->active);
622 rq->nr_running++;
625 static void recalc_task_prio(task_t *p, unsigned long long now)
627 /* Caller must always ensure 'now >= p->timestamp' */
628 unsigned long long __sleep_time = now - p->timestamp;
629 unsigned long sleep_time;
631 if (__sleep_time > NS_MAX_SLEEP_AVG)
632 sleep_time = NS_MAX_SLEEP_AVG;
633 else
634 sleep_time = (unsigned long)__sleep_time;
636 if (likely(sleep_time > 0)) {
638 * User tasks that sleep a long time are categorised as
639 * idle and will get just interactive status to stay active &
640 * prevent them suddenly becoming cpu hogs and starving
641 * other processes.
643 if (p->mm && p->activated != -1 &&
644 sleep_time > INTERACTIVE_SLEEP(p)) {
645 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
646 DEF_TIMESLICE);
647 } else {
649 * The lower the sleep avg a task has the more
650 * rapidly it will rise with sleep time.
652 sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
655 * Tasks waking from uninterruptible sleep are
656 * limited in their sleep_avg rise as they
657 * are likely to be waiting on I/O
659 if (p->activated == -1 && p->mm) {
660 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
661 sleep_time = 0;
662 else if (p->sleep_avg + sleep_time >=
663 INTERACTIVE_SLEEP(p)) {
664 p->sleep_avg = INTERACTIVE_SLEEP(p);
665 sleep_time = 0;
670 * This code gives a bonus to interactive tasks.
672 * The boost works by updating the 'average sleep time'
673 * value here, based on ->timestamp. The more time a
674 * task spends sleeping, the higher the average gets -
675 * and the higher the priority boost gets as well.
677 p->sleep_avg += sleep_time;
679 if (p->sleep_avg > NS_MAX_SLEEP_AVG)
680 p->sleep_avg = NS_MAX_SLEEP_AVG;
684 p->prio = effective_prio(p);
688 * activate_task - move a task to the runqueue and do priority recalculation
690 * Update all the scheduling statistics stuff. (sleep average
691 * calculation, priority modifiers, etc.)
693 static void activate_task(task_t *p, runqueue_t *rq, int local)
695 unsigned long long now;
697 now = sched_clock();
698 #ifdef CONFIG_SMP
699 if (!local) {
700 /* Compensate for drifting sched_clock */
701 runqueue_t *this_rq = this_rq();
702 now = (now - this_rq->timestamp_last_tick)
703 + rq->timestamp_last_tick;
705 #endif
707 recalc_task_prio(p, now);
710 * This checks to make sure it's not an uninterruptible task
711 * that is now waking up.
713 if (!p->activated) {
715 * Tasks which were woken up by interrupts (ie. hw events)
716 * are most likely of interactive nature. So we give them
717 * the credit of extending their sleep time to the period
718 * of time they spend on the runqueue, waiting for execution
719 * on a CPU, first time around:
721 if (in_interrupt())
722 p->activated = 2;
723 else {
725 * Normal first-time wakeups get a credit too for
726 * on-runqueue time, but it will be weighted down:
728 p->activated = 1;
731 p->timestamp = now;
733 __activate_task(p, rq);
737 * deactivate_task - remove a task from the runqueue.
739 static void deactivate_task(struct task_struct *p, runqueue_t *rq)
741 rq->nr_running--;
742 dequeue_task(p, p->array);
743 p->array = NULL;
747 * resched_task - mark a task 'to be rescheduled now'.
749 * On UP this means the setting of the need_resched flag, on SMP it
750 * might also involve a cross-CPU call to trigger the scheduler on
751 * the target CPU.
753 #ifdef CONFIG_SMP
754 static void resched_task(task_t *p)
756 int need_resched, nrpolling;
758 assert_spin_locked(&task_rq(p)->lock);
760 /* minimise the chance of sending an interrupt to poll_idle() */
761 nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
762 need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
763 nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
765 if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
766 smp_send_reschedule(task_cpu(p));
768 #else
769 static inline void resched_task(task_t *p)
771 set_tsk_need_resched(p);
773 #endif
776 * task_curr - is this task currently executing on a CPU?
777 * @p: the task in question.
779 inline int task_curr(const task_t *p)
781 return cpu_curr(task_cpu(p)) == p;
784 #ifdef CONFIG_SMP
785 enum request_type {
786 REQ_MOVE_TASK,
787 REQ_SET_DOMAIN,
790 typedef struct {
791 struct list_head list;
792 enum request_type type;
794 /* For REQ_MOVE_TASK */
795 task_t *task;
796 int dest_cpu;
798 /* For REQ_SET_DOMAIN */
799 struct sched_domain *sd;
801 struct completion done;
802 } migration_req_t;
805 * The task's runqueue lock must be held.
806 * Returns true if you have to wait for migration thread.
808 static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
810 runqueue_t *rq = task_rq(p);
813 * If the task is not on a runqueue (and not running), then
814 * it is sufficient to simply update the task's cpu field.
816 if (!p->array && !task_running(rq, p)) {
817 set_task_cpu(p, dest_cpu);
818 return 0;
821 init_completion(&req->done);
822 req->type = REQ_MOVE_TASK;
823 req->task = p;
824 req->dest_cpu = dest_cpu;
825 list_add(&req->list, &rq->migration_queue);
826 return 1;
830 * wait_task_inactive - wait for a thread to unschedule.
832 * The caller must ensure that the task *will* unschedule sometime soon,
833 * else this function might spin for a *long* time. This function can't
834 * be called with interrupts off, or it may introduce deadlock with
835 * smp_call_function() if an IPI is sent by the same process we are
836 * waiting to become inactive.
838 void wait_task_inactive(task_t * p)
840 unsigned long flags;
841 runqueue_t *rq;
842 int preempted;
844 repeat:
845 rq = task_rq_lock(p, &flags);
846 /* Must be off runqueue entirely, not preempted. */
847 if (unlikely(p->array || task_running(rq, p))) {
848 /* If it's preempted, we yield. It could be a while. */
849 preempted = !task_running(rq, p);
850 task_rq_unlock(rq, &flags);
851 cpu_relax();
852 if (preempted)
853 yield();
854 goto repeat;
856 task_rq_unlock(rq, &flags);
859 /***
860 * kick_process - kick a running thread to enter/exit the kernel
861 * @p: the to-be-kicked thread
863 * Cause a process which is running on another CPU to enter
864 * kernel-mode, without any delay. (to get signals handled.)
866 * NOTE: this function doesnt have to take the runqueue lock,
867 * because all it wants to ensure is that the remote task enters
868 * the kernel. If the IPI races and the task has been migrated
869 * to another CPU then no harm is done and the purpose has been
870 * achieved as well.
872 void kick_process(task_t *p)
874 int cpu;
876 preempt_disable();
877 cpu = task_cpu(p);
878 if ((cpu != smp_processor_id()) && task_curr(p))
879 smp_send_reschedule(cpu);
880 preempt_enable();
884 * Return a low guess at the load of a migration-source cpu.
886 * We want to under-estimate the load of migration sources, to
887 * balance conservatively.
889 static inline unsigned long source_load(int cpu)
891 runqueue_t *rq = cpu_rq(cpu);
892 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
894 return min(rq->cpu_load, load_now);
898 * Return a high guess at the load of a migration-target cpu
900 static inline unsigned long target_load(int cpu)
902 runqueue_t *rq = cpu_rq(cpu);
903 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
905 return max(rq->cpu_load, load_now);
908 #endif
911 * wake_idle() will wake a task on an idle cpu if task->cpu is
912 * not idle and an idle cpu is available. The span of cpus to
913 * search starts with cpus closest then further out as needed,
914 * so we always favor a closer, idle cpu.
916 * Returns the CPU we should wake onto.
918 #if defined(ARCH_HAS_SCHED_WAKE_IDLE)
919 static int wake_idle(int cpu, task_t *p)
921 cpumask_t tmp;
922 struct sched_domain *sd;
923 int i;
925 if (idle_cpu(cpu))
926 return cpu;
928 for_each_domain(cpu, sd) {
929 if (sd->flags & SD_WAKE_IDLE) {
930 cpus_and(tmp, sd->span, cpu_online_map);
931 cpus_and(tmp, tmp, p->cpus_allowed);
932 for_each_cpu_mask(i, tmp) {
933 if (idle_cpu(i))
934 return i;
937 else break;
939 return cpu;
941 #else
942 static inline int wake_idle(int cpu, task_t *p)
944 return cpu;
946 #endif
948 /***
949 * try_to_wake_up - wake up a thread
950 * @p: the to-be-woken-up thread
951 * @state: the mask of task states that can be woken
952 * @sync: do a synchronous wakeup?
954 * Put it on the run-queue if it's not already there. The "current"
955 * thread is always on the run-queue (except when the actual
956 * re-schedule is in progress), and as such you're allowed to do
957 * the simpler "current->state = TASK_RUNNING" to mark yourself
958 * runnable without the overhead of this.
960 * returns failure only if the task is already active.
962 static int try_to_wake_up(task_t * p, unsigned int state, int sync)
964 int cpu, this_cpu, success = 0;
965 unsigned long flags;
966 long old_state;
967 runqueue_t *rq;
968 #ifdef CONFIG_SMP
969 unsigned long load, this_load;
970 struct sched_domain *sd;
971 int new_cpu;
972 #endif
974 rq = task_rq_lock(p, &flags);
975 old_state = p->state;
976 if (!(old_state & state))
977 goto out;
979 if (p->array)
980 goto out_running;
982 cpu = task_cpu(p);
983 this_cpu = smp_processor_id();
985 #ifdef CONFIG_SMP
986 if (unlikely(task_running(rq, p)))
987 goto out_activate;
989 #ifdef CONFIG_SCHEDSTATS
990 schedstat_inc(rq, ttwu_cnt);
991 if (cpu == this_cpu) {
992 schedstat_inc(rq, ttwu_local);
993 } else {
994 for_each_domain(this_cpu, sd) {
995 if (cpu_isset(cpu, sd->span)) {
996 schedstat_inc(sd, ttwu_wake_remote);
997 break;
1001 #endif
1003 new_cpu = cpu;
1004 if (cpu == this_cpu || unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1005 goto out_set_cpu;
1007 load = source_load(cpu);
1008 this_load = target_load(this_cpu);
1011 * If sync wakeup then subtract the (maximum possible) effect of
1012 * the currently running task from the load of the current CPU:
1014 if (sync)
1015 this_load -= SCHED_LOAD_SCALE;
1017 /* Don't pull the task off an idle CPU to a busy one */
1018 if (load < SCHED_LOAD_SCALE/2 && this_load > SCHED_LOAD_SCALE/2)
1019 goto out_set_cpu;
1021 new_cpu = this_cpu; /* Wake to this CPU if we can */
1024 * Scan domains for affine wakeup and passive balancing
1025 * possibilities.
1027 for_each_domain(this_cpu, sd) {
1028 unsigned int imbalance;
1030 * Start passive balancing when half the imbalance_pct
1031 * limit is reached.
1033 imbalance = sd->imbalance_pct + (sd->imbalance_pct - 100) / 2;
1035 if ((sd->flags & SD_WAKE_AFFINE) &&
1036 !task_hot(p, rq->timestamp_last_tick, sd)) {
1038 * This domain has SD_WAKE_AFFINE and p is cache cold
1039 * in this domain.
1041 if (cpu_isset(cpu, sd->span)) {
1042 schedstat_inc(sd, ttwu_move_affine);
1043 goto out_set_cpu;
1045 } else if ((sd->flags & SD_WAKE_BALANCE) &&
1046 imbalance*this_load <= 100*load) {
1048 * This domain has SD_WAKE_BALANCE and there is
1049 * an imbalance.
1051 if (cpu_isset(cpu, sd->span)) {
1052 schedstat_inc(sd, ttwu_move_balance);
1053 goto out_set_cpu;
1058 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1059 out_set_cpu:
1060 new_cpu = wake_idle(new_cpu, p);
1061 if (new_cpu != cpu) {
1062 set_task_cpu(p, new_cpu);
1063 task_rq_unlock(rq, &flags);
1064 /* might preempt at this point */
1065 rq = task_rq_lock(p, &flags);
1066 old_state = p->state;
1067 if (!(old_state & state))
1068 goto out;
1069 if (p->array)
1070 goto out_running;
1072 this_cpu = smp_processor_id();
1073 cpu = task_cpu(p);
1076 out_activate:
1077 #endif /* CONFIG_SMP */
1078 if (old_state == TASK_UNINTERRUPTIBLE) {
1079 rq->nr_uninterruptible--;
1081 * Tasks on involuntary sleep don't earn
1082 * sleep_avg beyond just interactive state.
1084 p->activated = -1;
1088 * Sync wakeups (i.e. those types of wakeups where the waker
1089 * has indicated that it will leave the CPU in short order)
1090 * don't trigger a preemption, if the woken up task will run on
1091 * this cpu. (in this case the 'I will reschedule' promise of
1092 * the waker guarantees that the freshly woken up task is going
1093 * to be considered on this CPU.)
1095 activate_task(p, rq, cpu == this_cpu);
1096 if (!sync || cpu != this_cpu) {
1097 if (TASK_PREEMPTS_CURR(p, rq))
1098 resched_task(rq->curr);
1100 success = 1;
1102 out_running:
1103 p->state = TASK_RUNNING;
1104 out:
1105 task_rq_unlock(rq, &flags);
1107 return success;
1110 int fastcall wake_up_process(task_t * p)
1112 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1113 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1116 EXPORT_SYMBOL(wake_up_process);
1118 int fastcall wake_up_state(task_t *p, unsigned int state)
1120 return try_to_wake_up(p, state, 0);
1123 #ifdef CONFIG_SMP
1124 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1125 struct sched_domain *sd);
1126 #endif
1129 * Perform scheduler related setup for a newly forked process p.
1130 * p is forked by current.
1132 void fastcall sched_fork(task_t *p)
1135 * We mark the process as running here, but have not actually
1136 * inserted it onto the runqueue yet. This guarantees that
1137 * nobody will actually run it, and a signal or other external
1138 * event cannot wake it up and insert it on the runqueue either.
1140 p->state = TASK_RUNNING;
1141 INIT_LIST_HEAD(&p->run_list);
1142 p->array = NULL;
1143 spin_lock_init(&p->switch_lock);
1144 #ifdef CONFIG_SCHEDSTATS
1145 memset(&p->sched_info, 0, sizeof(p->sched_info));
1146 #endif
1147 #ifdef CONFIG_PREEMPT
1149 * During context-switch we hold precisely one spinlock, which
1150 * schedule_tail drops. (in the common case it's this_rq()->lock,
1151 * but it also can be p->switch_lock.) So we compensate with a count
1152 * of 1. Also, we want to start with kernel preemption disabled.
1154 p->thread_info->preempt_count = 1;
1155 #endif
1157 * Share the timeslice between parent and child, thus the
1158 * total amount of pending timeslices in the system doesn't change,
1159 * resulting in more scheduling fairness.
1161 local_irq_disable();
1162 p->time_slice = (current->time_slice + 1) >> 1;
1164 * The remainder of the first timeslice might be recovered by
1165 * the parent if the child exits early enough.
1167 p->first_time_slice = 1;
1168 current->time_slice >>= 1;
1169 p->timestamp = sched_clock();
1170 if (unlikely(!current->time_slice)) {
1172 * This case is rare, it happens when the parent has only
1173 * a single jiffy left from its timeslice. Taking the
1174 * runqueue lock is not a problem.
1176 current->time_slice = 1;
1177 preempt_disable();
1178 scheduler_tick();
1179 local_irq_enable();
1180 preempt_enable();
1181 } else
1182 local_irq_enable();
1186 * wake_up_new_task - wake up a newly created task for the first time.
1188 * This function will do some initial scheduler statistics housekeeping
1189 * that must be done for every newly created context, then puts the task
1190 * on the runqueue and wakes it.
1192 void fastcall wake_up_new_task(task_t * p, unsigned long clone_flags)
1194 unsigned long flags;
1195 int this_cpu, cpu;
1196 runqueue_t *rq, *this_rq;
1198 rq = task_rq_lock(p, &flags);
1199 cpu = task_cpu(p);
1200 this_cpu = smp_processor_id();
1202 BUG_ON(p->state != TASK_RUNNING);
1205 * We decrease the sleep average of forking parents
1206 * and children as well, to keep max-interactive tasks
1207 * from forking tasks that are max-interactive. The parent
1208 * (current) is done further down, under its lock.
1210 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1211 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1213 p->prio = effective_prio(p);
1215 if (likely(cpu == this_cpu)) {
1216 if (!(clone_flags & CLONE_VM)) {
1218 * The VM isn't cloned, so we're in a good position to
1219 * do child-runs-first in anticipation of an exec. This
1220 * usually avoids a lot of COW overhead.
1222 if (unlikely(!current->array))
1223 __activate_task(p, rq);
1224 else {
1225 p->prio = current->prio;
1226 list_add_tail(&p->run_list, &current->run_list);
1227 p->array = current->array;
1228 p->array->nr_active++;
1229 rq->nr_running++;
1231 set_need_resched();
1232 } else
1233 /* Run child last */
1234 __activate_task(p, rq);
1236 * We skip the following code due to cpu == this_cpu
1238 * task_rq_unlock(rq, &flags);
1239 * this_rq = task_rq_lock(current, &flags);
1241 this_rq = rq;
1242 } else {
1243 this_rq = cpu_rq(this_cpu);
1246 * Not the local CPU - must adjust timestamp. This should
1247 * get optimised away in the !CONFIG_SMP case.
1249 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1250 + rq->timestamp_last_tick;
1251 __activate_task(p, rq);
1252 if (TASK_PREEMPTS_CURR(p, rq))
1253 resched_task(rq->curr);
1256 * Parent and child are on different CPUs, now get the
1257 * parent runqueue to update the parent's ->sleep_avg:
1259 task_rq_unlock(rq, &flags);
1260 this_rq = task_rq_lock(current, &flags);
1262 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1263 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1264 task_rq_unlock(this_rq, &flags);
1268 * Potentially available exiting-child timeslices are
1269 * retrieved here - this way the parent does not get
1270 * penalized for creating too many threads.
1272 * (this cannot be used to 'generate' timeslices
1273 * artificially, because any timeslice recovered here
1274 * was given away by the parent in the first place.)
1276 void fastcall sched_exit(task_t * p)
1278 unsigned long flags;
1279 runqueue_t *rq;
1282 * If the child was a (relative-) CPU hog then decrease
1283 * the sleep_avg of the parent as well.
1285 rq = task_rq_lock(p->parent, &flags);
1286 if (p->first_time_slice) {
1287 p->parent->time_slice += p->time_slice;
1288 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1289 p->parent->time_slice = task_timeslice(p);
1291 if (p->sleep_avg < p->parent->sleep_avg)
1292 p->parent->sleep_avg = p->parent->sleep_avg /
1293 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1294 (EXIT_WEIGHT + 1);
1295 task_rq_unlock(rq, &flags);
1299 * finish_task_switch - clean up after a task-switch
1300 * @prev: the thread we just switched away from.
1302 * We enter this with the runqueue still locked, and finish_arch_switch()
1303 * will unlock it along with doing any other architecture-specific cleanup
1304 * actions.
1306 * Note that we may have delayed dropping an mm in context_switch(). If
1307 * so, we finish that here outside of the runqueue lock. (Doing it
1308 * with the lock held can cause deadlocks; see schedule() for
1309 * details.)
1311 static inline void finish_task_switch(task_t *prev)
1312 __releases(rq->lock)
1314 runqueue_t *rq = this_rq();
1315 struct mm_struct *mm = rq->prev_mm;
1316 unsigned long prev_task_flags;
1318 rq->prev_mm = NULL;
1321 * A task struct has one reference for the use as "current".
1322 * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1323 * calls schedule one last time. The schedule call will never return,
1324 * and the scheduled task must drop that reference.
1325 * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1326 * still held, otherwise prev could be scheduled on another cpu, die
1327 * there before we look at prev->state, and then the reference would
1328 * be dropped twice.
1329 * Manfred Spraul <manfred@colorfullife.com>
1331 prev_task_flags = prev->flags;
1332 finish_arch_switch(rq, prev);
1333 if (mm)
1334 mmdrop(mm);
1335 if (unlikely(prev_task_flags & PF_DEAD))
1336 put_task_struct(prev);
1340 * schedule_tail - first thing a freshly forked thread must call.
1341 * @prev: the thread we just switched away from.
1343 asmlinkage void schedule_tail(task_t *prev)
1344 __releases(rq->lock)
1346 finish_task_switch(prev);
1348 if (current->set_child_tid)
1349 put_user(current->pid, current->set_child_tid);
1353 * context_switch - switch to the new MM and the new
1354 * thread's register state.
1356 static inline
1357 task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1359 struct mm_struct *mm = next->mm;
1360 struct mm_struct *oldmm = prev->active_mm;
1362 if (unlikely(!mm)) {
1363 next->active_mm = oldmm;
1364 atomic_inc(&oldmm->mm_count);
1365 enter_lazy_tlb(oldmm, next);
1366 } else
1367 switch_mm(oldmm, mm, next);
1369 if (unlikely(!prev->mm)) {
1370 prev->active_mm = NULL;
1371 WARN_ON(rq->prev_mm);
1372 rq->prev_mm = oldmm;
1375 /* Here we just switch the register state and the stack. */
1376 switch_to(prev, next, prev);
1378 return prev;
1382 * nr_running, nr_uninterruptible and nr_context_switches:
1384 * externally visible scheduler statistics: current number of runnable
1385 * threads, current number of uninterruptible-sleeping threads, total
1386 * number of context switches performed since bootup.
1388 unsigned long nr_running(void)
1390 unsigned long i, sum = 0;
1392 for_each_online_cpu(i)
1393 sum += cpu_rq(i)->nr_running;
1395 return sum;
1398 unsigned long nr_uninterruptible(void)
1400 unsigned long i, sum = 0;
1402 for_each_cpu(i)
1403 sum += cpu_rq(i)->nr_uninterruptible;
1406 * Since we read the counters lockless, it might be slightly
1407 * inaccurate. Do not allow it to go below zero though:
1409 if (unlikely((long)sum < 0))
1410 sum = 0;
1412 return sum;
1415 unsigned long long nr_context_switches(void)
1417 unsigned long long i, sum = 0;
1419 for_each_cpu(i)
1420 sum += cpu_rq(i)->nr_switches;
1422 return sum;
1425 unsigned long nr_iowait(void)
1427 unsigned long i, sum = 0;
1429 for_each_cpu(i)
1430 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1432 return sum;
1435 #ifdef CONFIG_SMP
1438 * double_rq_lock - safely lock two runqueues
1440 * Note this does not disable interrupts like task_rq_lock,
1441 * you need to do so manually before calling.
1443 static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1444 __acquires(rq1->lock)
1445 __acquires(rq2->lock)
1447 if (rq1 == rq2) {
1448 spin_lock(&rq1->lock);
1449 __acquire(rq2->lock); /* Fake it out ;) */
1450 } else {
1451 if (rq1 < rq2) {
1452 spin_lock(&rq1->lock);
1453 spin_lock(&rq2->lock);
1454 } else {
1455 spin_lock(&rq2->lock);
1456 spin_lock(&rq1->lock);
1462 * double_rq_unlock - safely unlock two runqueues
1464 * Note this does not restore interrupts like task_rq_unlock,
1465 * you need to do so manually after calling.
1467 static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1468 __releases(rq1->lock)
1469 __releases(rq2->lock)
1471 spin_unlock(&rq1->lock);
1472 if (rq1 != rq2)
1473 spin_unlock(&rq2->lock);
1474 else
1475 __release(rq2->lock);
1479 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1481 static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1482 __releases(this_rq->lock)
1483 __acquires(busiest->lock)
1484 __acquires(this_rq->lock)
1486 if (unlikely(!spin_trylock(&busiest->lock))) {
1487 if (busiest < this_rq) {
1488 spin_unlock(&this_rq->lock);
1489 spin_lock(&busiest->lock);
1490 spin_lock(&this_rq->lock);
1491 } else
1492 spin_lock(&busiest->lock);
1497 * find_idlest_cpu - find the least busy runqueue.
1499 static int find_idlest_cpu(struct task_struct *p, int this_cpu,
1500 struct sched_domain *sd)
1502 unsigned long load, min_load, this_load;
1503 int i, min_cpu;
1504 cpumask_t mask;
1506 min_cpu = UINT_MAX;
1507 min_load = ULONG_MAX;
1509 cpus_and(mask, sd->span, p->cpus_allowed);
1511 for_each_cpu_mask(i, mask) {
1512 load = target_load(i);
1514 if (load < min_load) {
1515 min_cpu = i;
1516 min_load = load;
1518 /* break out early on an idle CPU: */
1519 if (!min_load)
1520 break;
1524 /* add +1 to account for the new task */
1525 this_load = source_load(this_cpu) + SCHED_LOAD_SCALE;
1528 * Would with the addition of the new task to the
1529 * current CPU there be an imbalance between this
1530 * CPU and the idlest CPU?
1532 * Use half of the balancing threshold - new-context is
1533 * a good opportunity to balance.
1535 if (min_load*(100 + (sd->imbalance_pct-100)/2) < this_load*100)
1536 return min_cpu;
1538 return this_cpu;
1542 * If dest_cpu is allowed for this process, migrate the task to it.
1543 * This is accomplished by forcing the cpu_allowed mask to only
1544 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1545 * the cpu_allowed mask is restored.
1547 static void sched_migrate_task(task_t *p, int dest_cpu)
1549 migration_req_t req;
1550 runqueue_t *rq;
1551 unsigned long flags;
1553 rq = task_rq_lock(p, &flags);
1554 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1555 || unlikely(cpu_is_offline(dest_cpu)))
1556 goto out;
1558 /* force the process onto the specified CPU */
1559 if (migrate_task(p, dest_cpu, &req)) {
1560 /* Need to wait for migration thread (might exit: take ref). */
1561 struct task_struct *mt = rq->migration_thread;
1562 get_task_struct(mt);
1563 task_rq_unlock(rq, &flags);
1564 wake_up_process(mt);
1565 put_task_struct(mt);
1566 wait_for_completion(&req.done);
1567 return;
1569 out:
1570 task_rq_unlock(rq, &flags);
1574 * sched_exec(): find the highest-level, exec-balance-capable
1575 * domain and try to migrate the task to the least loaded CPU.
1577 * execve() is a valuable balancing opportunity, because at this point
1578 * the task has the smallest effective memory and cache footprint.
1580 void sched_exec(void)
1582 struct sched_domain *tmp, *sd = NULL;
1583 int new_cpu, this_cpu = get_cpu();
1585 /* Prefer the current CPU if there's only this task running */
1586 if (this_rq()->nr_running <= 1)
1587 goto out;
1589 for_each_domain(this_cpu, tmp)
1590 if (tmp->flags & SD_BALANCE_EXEC)
1591 sd = tmp;
1593 if (sd) {
1594 schedstat_inc(sd, sbe_attempts);
1595 new_cpu = find_idlest_cpu(current, this_cpu, sd);
1596 if (new_cpu != this_cpu) {
1597 schedstat_inc(sd, sbe_pushed);
1598 put_cpu();
1599 sched_migrate_task(current, new_cpu);
1600 return;
1603 out:
1604 put_cpu();
1608 * pull_task - move a task from a remote runqueue to the local runqueue.
1609 * Both runqueues must be locked.
1611 static inline
1612 void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1613 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1615 dequeue_task(p, src_array);
1616 src_rq->nr_running--;
1617 set_task_cpu(p, this_cpu);
1618 this_rq->nr_running++;
1619 enqueue_task(p, this_array);
1620 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1621 + this_rq->timestamp_last_tick;
1623 * Note that idle threads have a prio of MAX_PRIO, for this test
1624 * to be always true for them.
1626 if (TASK_PREEMPTS_CURR(p, this_rq))
1627 resched_task(this_rq->curr);
1631 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1633 static inline
1634 int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
1635 struct sched_domain *sd, enum idle_type idle)
1638 * We do not migrate tasks that are:
1639 * 1) running (obviously), or
1640 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1641 * 3) are cache-hot on their current CPU.
1643 if (task_running(rq, p))
1644 return 0;
1645 if (!cpu_isset(this_cpu, p->cpus_allowed))
1646 return 0;
1649 * Aggressive migration if:
1650 * 1) the [whole] cpu is idle, or
1651 * 2) too many balance attempts have failed.
1654 if (cpu_and_siblings_are_idle(this_cpu) || \
1655 sd->nr_balance_failed > sd->cache_nice_tries)
1656 return 1;
1658 if (task_hot(p, rq->timestamp_last_tick, sd))
1659 return 0;
1660 return 1;
1664 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1665 * as part of a balancing operation within "domain". Returns the number of
1666 * tasks moved.
1668 * Called with both runqueues locked.
1670 static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1671 unsigned long max_nr_move, struct sched_domain *sd,
1672 enum idle_type idle)
1674 prio_array_t *array, *dst_array;
1675 struct list_head *head, *curr;
1676 int idx, pulled = 0;
1677 task_t *tmp;
1679 if (max_nr_move <= 0 || busiest->nr_running <= 1)
1680 goto out;
1683 * We first consider expired tasks. Those will likely not be
1684 * executed in the near future, and they are most likely to
1685 * be cache-cold, thus switching CPUs has the least effect
1686 * on them.
1688 if (busiest->expired->nr_active) {
1689 array = busiest->expired;
1690 dst_array = this_rq->expired;
1691 } else {
1692 array = busiest->active;
1693 dst_array = this_rq->active;
1696 new_array:
1697 /* Start searching at priority 0: */
1698 idx = 0;
1699 skip_bitmap:
1700 if (!idx)
1701 idx = sched_find_first_bit(array->bitmap);
1702 else
1703 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1704 if (idx >= MAX_PRIO) {
1705 if (array == busiest->expired && busiest->active->nr_active) {
1706 array = busiest->active;
1707 dst_array = this_rq->active;
1708 goto new_array;
1710 goto out;
1713 head = array->queue + idx;
1714 curr = head->prev;
1715 skip_queue:
1716 tmp = list_entry(curr, task_t, run_list);
1718 curr = curr->prev;
1720 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle)) {
1721 if (curr != head)
1722 goto skip_queue;
1723 idx++;
1724 goto skip_bitmap;
1727 #ifdef CONFIG_SCHEDSTATS
1728 if (task_hot(tmp, busiest->timestamp_last_tick, sd))
1729 schedstat_inc(sd, lb_hot_gained[idle]);
1730 #endif
1732 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
1733 pulled++;
1735 /* We only want to steal up to the prescribed number of tasks. */
1736 if (pulled < max_nr_move) {
1737 if (curr != head)
1738 goto skip_queue;
1739 idx++;
1740 goto skip_bitmap;
1742 out:
1744 * Right now, this is the only place pull_task() is called,
1745 * so we can safely collect pull_task() stats here rather than
1746 * inside pull_task().
1748 schedstat_add(sd, lb_gained[idle], pulled);
1749 return pulled;
1753 * find_busiest_group finds and returns the busiest CPU group within the
1754 * domain. It calculates and returns the number of tasks which should be
1755 * moved to restore balance via the imbalance parameter.
1757 static struct sched_group *
1758 find_busiest_group(struct sched_domain *sd, int this_cpu,
1759 unsigned long *imbalance, enum idle_type idle)
1761 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
1762 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
1764 max_load = this_load = total_load = total_pwr = 0;
1766 do {
1767 unsigned long load;
1768 int local_group;
1769 int i;
1771 local_group = cpu_isset(this_cpu, group->cpumask);
1773 /* Tally up the load of all CPUs in the group */
1774 avg_load = 0;
1776 for_each_cpu_mask(i, group->cpumask) {
1777 /* Bias balancing toward cpus of our domain */
1778 if (local_group)
1779 load = target_load(i);
1780 else
1781 load = source_load(i);
1783 avg_load += load;
1786 total_load += avg_load;
1787 total_pwr += group->cpu_power;
1789 /* Adjust by relative CPU power of the group */
1790 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1792 if (local_group) {
1793 this_load = avg_load;
1794 this = group;
1795 goto nextgroup;
1796 } else if (avg_load > max_load) {
1797 max_load = avg_load;
1798 busiest = group;
1800 nextgroup:
1801 group = group->next;
1802 } while (group != sd->groups);
1804 if (!busiest || this_load >= max_load)
1805 goto out_balanced;
1807 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
1809 if (this_load >= avg_load ||
1810 100*max_load <= sd->imbalance_pct*this_load)
1811 goto out_balanced;
1814 * We're trying to get all the cpus to the average_load, so we don't
1815 * want to push ourselves above the average load, nor do we wish to
1816 * reduce the max loaded cpu below the average load, as either of these
1817 * actions would just result in more rebalancing later, and ping-pong
1818 * tasks around. Thus we look for the minimum possible imbalance.
1819 * Negative imbalances (*we* are more loaded than anyone else) will
1820 * be counted as no imbalance for these purposes -- we can't fix that
1821 * by pulling tasks to us. Be careful of negative numbers as they'll
1822 * appear as very large values with unsigned longs.
1824 /* How much load to actually move to equalise the imbalance */
1825 *imbalance = min((max_load - avg_load) * busiest->cpu_power,
1826 (avg_load - this_load) * this->cpu_power)
1827 / SCHED_LOAD_SCALE;
1829 if (*imbalance < SCHED_LOAD_SCALE) {
1830 unsigned long pwr_now = 0, pwr_move = 0;
1831 unsigned long tmp;
1833 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
1834 *imbalance = 1;
1835 return busiest;
1839 * OK, we don't have enough imbalance to justify moving tasks,
1840 * however we may be able to increase total CPU power used by
1841 * moving them.
1844 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
1845 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
1846 pwr_now /= SCHED_LOAD_SCALE;
1848 /* Amount of load we'd subtract */
1849 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
1850 if (max_load > tmp)
1851 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
1852 max_load - tmp);
1854 /* Amount of load we'd add */
1855 if (max_load*busiest->cpu_power <
1856 SCHED_LOAD_SCALE*SCHED_LOAD_SCALE)
1857 tmp = max_load*busiest->cpu_power/this->cpu_power;
1858 else
1859 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
1860 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
1861 pwr_move /= SCHED_LOAD_SCALE;
1863 /* Move if we gain throughput */
1864 if (pwr_move <= pwr_now)
1865 goto out_balanced;
1867 *imbalance = 1;
1868 return busiest;
1871 /* Get rid of the scaling factor, rounding down as we divide */
1872 *imbalance = *imbalance / SCHED_LOAD_SCALE;
1874 return busiest;
1876 out_balanced:
1877 if (busiest && (idle == NEWLY_IDLE ||
1878 (idle == SCHED_IDLE && max_load > SCHED_LOAD_SCALE)) ) {
1879 *imbalance = 1;
1880 return busiest;
1883 *imbalance = 0;
1884 return NULL;
1888 * find_busiest_queue - find the busiest runqueue among the cpus in group.
1890 static runqueue_t *find_busiest_queue(struct sched_group *group)
1892 unsigned long load, max_load = 0;
1893 runqueue_t *busiest = NULL;
1894 int i;
1896 for_each_cpu_mask(i, group->cpumask) {
1897 load = source_load(i);
1899 if (load > max_load) {
1900 max_load = load;
1901 busiest = cpu_rq(i);
1905 return busiest;
1909 * Check this_cpu to ensure it is balanced within domain. Attempt to move
1910 * tasks if there is an imbalance.
1912 * Called with this_rq unlocked.
1914 static int load_balance(int this_cpu, runqueue_t *this_rq,
1915 struct sched_domain *sd, enum idle_type idle)
1917 struct sched_group *group;
1918 runqueue_t *busiest;
1919 unsigned long imbalance;
1920 int nr_moved;
1922 spin_lock(&this_rq->lock);
1923 schedstat_inc(sd, lb_cnt[idle]);
1925 group = find_busiest_group(sd, this_cpu, &imbalance, idle);
1926 if (!group) {
1927 schedstat_inc(sd, lb_nobusyg[idle]);
1928 goto out_balanced;
1931 busiest = find_busiest_queue(group);
1932 if (!busiest) {
1933 schedstat_inc(sd, lb_nobusyq[idle]);
1934 goto out_balanced;
1938 * This should be "impossible", but since load
1939 * balancing is inherently racy and statistical,
1940 * it could happen in theory.
1942 if (unlikely(busiest == this_rq)) {
1943 WARN_ON(1);
1944 goto out_balanced;
1947 schedstat_add(sd, lb_imbalance[idle], imbalance);
1949 nr_moved = 0;
1950 if (busiest->nr_running > 1) {
1952 * Attempt to move tasks. If find_busiest_group has found
1953 * an imbalance but busiest->nr_running <= 1, the group is
1954 * still unbalanced. nr_moved simply stays zero, so it is
1955 * correctly treated as an imbalance.
1957 double_lock_balance(this_rq, busiest);
1958 nr_moved = move_tasks(this_rq, this_cpu, busiest,
1959 imbalance, sd, idle);
1960 spin_unlock(&busiest->lock);
1962 spin_unlock(&this_rq->lock);
1964 if (!nr_moved) {
1965 schedstat_inc(sd, lb_failed[idle]);
1966 sd->nr_balance_failed++;
1968 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
1969 int wake = 0;
1971 spin_lock(&busiest->lock);
1972 if (!busiest->active_balance) {
1973 busiest->active_balance = 1;
1974 busiest->push_cpu = this_cpu;
1975 wake = 1;
1977 spin_unlock(&busiest->lock);
1978 if (wake)
1979 wake_up_process(busiest->migration_thread);
1982 * We've kicked active balancing, reset the failure
1983 * counter.
1985 sd->nr_balance_failed = sd->cache_nice_tries;
1989 * We were unbalanced, but unsuccessful in move_tasks(),
1990 * so bump the balance_interval to lessen the lock contention.
1992 if (sd->balance_interval < sd->max_interval)
1993 sd->balance_interval++;
1994 } else {
1995 sd->nr_balance_failed = 0;
1997 /* We were unbalanced, so reset the balancing interval */
1998 sd->balance_interval = sd->min_interval;
2001 return nr_moved;
2003 out_balanced:
2004 spin_unlock(&this_rq->lock);
2006 schedstat_inc(sd, lb_balanced[idle]);
2008 /* tune up the balancing interval */
2009 if (sd->balance_interval < sd->max_interval)
2010 sd->balance_interval *= 2;
2012 return 0;
2016 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2017 * tasks if there is an imbalance.
2019 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2020 * this_rq is locked.
2022 static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2023 struct sched_domain *sd)
2025 struct sched_group *group;
2026 runqueue_t *busiest = NULL;
2027 unsigned long imbalance;
2028 int nr_moved = 0;
2030 schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2031 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
2032 if (!group) {
2033 schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
2034 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
2035 goto out;
2038 busiest = find_busiest_queue(group);
2039 if (!busiest || busiest == this_rq) {
2040 schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
2041 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
2042 goto out;
2045 /* Attempt to move tasks */
2046 double_lock_balance(this_rq, busiest);
2048 schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2049 nr_moved = move_tasks(this_rq, this_cpu, busiest,
2050 imbalance, sd, NEWLY_IDLE);
2051 if (!nr_moved)
2052 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
2054 spin_unlock(&busiest->lock);
2056 out:
2057 return nr_moved;
2061 * idle_balance is called by schedule() if this_cpu is about to become
2062 * idle. Attempts to pull tasks from other CPUs.
2064 static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
2066 struct sched_domain *sd;
2068 for_each_domain(this_cpu, sd) {
2069 if (sd->flags & SD_BALANCE_NEWIDLE) {
2070 if (load_balance_newidle(this_cpu, this_rq, sd)) {
2071 /* We've pulled tasks over so stop searching */
2072 break;
2079 * active_load_balance is run by migration threads. It pushes running tasks
2080 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2081 * running on each physical CPU where possible, and avoids physical /
2082 * logical imbalances.
2084 * Called with busiest_rq locked.
2086 static void active_load_balance(runqueue_t *busiest_rq, int busiest_cpu)
2088 struct sched_domain *sd;
2089 struct sched_group *cpu_group;
2090 runqueue_t *target_rq;
2091 cpumask_t visited_cpus;
2092 int cpu;
2095 * Search for suitable CPUs to push tasks to in successively higher
2096 * domains with SD_LOAD_BALANCE set.
2098 visited_cpus = CPU_MASK_NONE;
2099 for_each_domain(busiest_cpu, sd) {
2100 if (!(sd->flags & SD_LOAD_BALANCE))
2101 /* no more domains to search */
2102 break;
2104 schedstat_inc(sd, alb_cnt);
2106 cpu_group = sd->groups;
2107 do {
2108 for_each_cpu_mask(cpu, cpu_group->cpumask) {
2109 if (busiest_rq->nr_running <= 1)
2110 /* no more tasks left to move */
2111 return;
2112 if (cpu_isset(cpu, visited_cpus))
2113 continue;
2114 cpu_set(cpu, visited_cpus);
2115 if (!cpu_and_siblings_are_idle(cpu) || cpu == busiest_cpu)
2116 continue;
2118 target_rq = cpu_rq(cpu);
2120 * This condition is "impossible", if it occurs
2121 * we need to fix it. Originally reported by
2122 * Bjorn Helgaas on a 128-cpu setup.
2124 BUG_ON(busiest_rq == target_rq);
2126 /* move a task from busiest_rq to target_rq */
2127 double_lock_balance(busiest_rq, target_rq);
2128 if (move_tasks(target_rq, cpu, busiest_rq,
2129 1, sd, SCHED_IDLE)) {
2130 schedstat_inc(sd, alb_pushed);
2131 } else {
2132 schedstat_inc(sd, alb_failed);
2134 spin_unlock(&target_rq->lock);
2136 cpu_group = cpu_group->next;
2137 } while (cpu_group != sd->groups);
2142 * rebalance_tick will get called every timer tick, on every CPU.
2144 * It checks each scheduling domain to see if it is due to be balanced,
2145 * and initiates a balancing operation if so.
2147 * Balancing parameters are set up in arch_init_sched_domains.
2150 /* Don't have all balancing operations going off at once */
2151 #define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2153 static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2154 enum idle_type idle)
2156 unsigned long old_load, this_load;
2157 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2158 struct sched_domain *sd;
2160 /* Update our load */
2161 old_load = this_rq->cpu_load;
2162 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
2164 * Round up the averaging division if load is increasing. This
2165 * prevents us from getting stuck on 9 if the load is 10, for
2166 * example.
2168 if (this_load > old_load)
2169 old_load++;
2170 this_rq->cpu_load = (old_load + this_load) / 2;
2172 for_each_domain(this_cpu, sd) {
2173 unsigned long interval;
2175 if (!(sd->flags & SD_LOAD_BALANCE))
2176 continue;
2178 interval = sd->balance_interval;
2179 if (idle != SCHED_IDLE)
2180 interval *= sd->busy_factor;
2182 /* scale ms to jiffies */
2183 interval = msecs_to_jiffies(interval);
2184 if (unlikely(!interval))
2185 interval = 1;
2187 if (j - sd->last_balance >= interval) {
2188 if (load_balance(this_cpu, this_rq, sd, idle)) {
2189 /* We've pulled tasks over so no longer idle */
2190 idle = NOT_IDLE;
2192 sd->last_balance += interval;
2196 #else
2198 * on UP we do not need to balance between CPUs:
2200 static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2203 static inline void idle_balance(int cpu, runqueue_t *rq)
2206 #endif
2208 static inline int wake_priority_sleeper(runqueue_t *rq)
2210 int ret = 0;
2211 #ifdef CONFIG_SCHED_SMT
2212 spin_lock(&rq->lock);
2214 * If an SMT sibling task has been put to sleep for priority
2215 * reasons reschedule the idle task to see if it can now run.
2217 if (rq->nr_running) {
2218 resched_task(rq->idle);
2219 ret = 1;
2221 spin_unlock(&rq->lock);
2222 #endif
2223 return ret;
2226 DEFINE_PER_CPU(struct kernel_stat, kstat);
2228 EXPORT_PER_CPU_SYMBOL(kstat);
2231 * This is called on clock ticks and on context switches.
2232 * Bank in p->sched_time the ns elapsed since the last tick or switch.
2234 static inline void update_cpu_clock(task_t *p, runqueue_t *rq,
2235 unsigned long long now)
2237 unsigned long long last = max(p->timestamp, rq->timestamp_last_tick);
2238 p->sched_time += now - last;
2242 * Return current->sched_time plus any more ns on the sched_clock
2243 * that have not yet been banked.
2245 unsigned long long current_sched_time(const task_t *tsk)
2247 unsigned long long ns;
2248 unsigned long flags;
2249 local_irq_save(flags);
2250 ns = max(tsk->timestamp, task_rq(tsk)->timestamp_last_tick);
2251 ns = tsk->sched_time + (sched_clock() - ns);
2252 local_irq_restore(flags);
2253 return ns;
2257 * We place interactive tasks back into the active array, if possible.
2259 * To guarantee that this does not starve expired tasks we ignore the
2260 * interactivity of a task if the first expired task had to wait more
2261 * than a 'reasonable' amount of time. This deadline timeout is
2262 * load-dependent, as the frequency of array switched decreases with
2263 * increasing number of running tasks. We also ignore the interactivity
2264 * if a better static_prio task has expired:
2266 #define EXPIRED_STARVING(rq) \
2267 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2268 (jiffies - (rq)->expired_timestamp >= \
2269 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2270 ((rq)->curr->static_prio > (rq)->best_expired_prio))
2273 * Account user cpu time to a process.
2274 * @p: the process that the cpu time gets accounted to
2275 * @hardirq_offset: the offset to subtract from hardirq_count()
2276 * @cputime: the cpu time spent in user space since the last update
2278 void account_user_time(struct task_struct *p, cputime_t cputime)
2280 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2281 cputime64_t tmp;
2283 p->utime = cputime_add(p->utime, cputime);
2285 /* Add user time to cpustat. */
2286 tmp = cputime_to_cputime64(cputime);
2287 if (TASK_NICE(p) > 0)
2288 cpustat->nice = cputime64_add(cpustat->nice, tmp);
2289 else
2290 cpustat->user = cputime64_add(cpustat->user, tmp);
2294 * Account system cpu time to a process.
2295 * @p: the process that the cpu time gets accounted to
2296 * @hardirq_offset: the offset to subtract from hardirq_count()
2297 * @cputime: the cpu time spent in kernel space since the last update
2299 void account_system_time(struct task_struct *p, int hardirq_offset,
2300 cputime_t cputime)
2302 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2303 runqueue_t *rq = this_rq();
2304 cputime64_t tmp;
2306 p->stime = cputime_add(p->stime, cputime);
2308 /* Add system time to cpustat. */
2309 tmp = cputime_to_cputime64(cputime);
2310 if (hardirq_count() - hardirq_offset)
2311 cpustat->irq = cputime64_add(cpustat->irq, tmp);
2312 else if (softirq_count())
2313 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
2314 else if (p != rq->idle)
2315 cpustat->system = cputime64_add(cpustat->system, tmp);
2316 else if (atomic_read(&rq->nr_iowait) > 0)
2317 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2318 else
2319 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2320 /* Account for system time used */
2321 acct_update_integrals(p);
2322 /* Update rss highwater mark */
2323 update_mem_hiwater(p);
2327 * Account for involuntary wait time.
2328 * @p: the process from which the cpu time has been stolen
2329 * @steal: the cpu time spent in involuntary wait
2331 void account_steal_time(struct task_struct *p, cputime_t steal)
2333 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2334 cputime64_t tmp = cputime_to_cputime64(steal);
2335 runqueue_t *rq = this_rq();
2337 if (p == rq->idle) {
2338 p->stime = cputime_add(p->stime, steal);
2339 if (atomic_read(&rq->nr_iowait) > 0)
2340 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2341 else
2342 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2343 } else
2344 cpustat->steal = cputime64_add(cpustat->steal, tmp);
2348 * This function gets called by the timer code, with HZ frequency.
2349 * We call it with interrupts disabled.
2351 * It also gets called by the fork code, when changing the parent's
2352 * timeslices.
2354 void scheduler_tick(void)
2356 int cpu = smp_processor_id();
2357 runqueue_t *rq = this_rq();
2358 task_t *p = current;
2359 unsigned long long now = sched_clock();
2361 update_cpu_clock(p, rq, now);
2363 rq->timestamp_last_tick = now;
2365 if (p == rq->idle) {
2366 if (wake_priority_sleeper(rq))
2367 goto out;
2368 rebalance_tick(cpu, rq, SCHED_IDLE);
2369 return;
2372 /* Task might have expired already, but not scheduled off yet */
2373 if (p->array != rq->active) {
2374 set_tsk_need_resched(p);
2375 goto out;
2377 spin_lock(&rq->lock);
2379 * The task was running during this tick - update the
2380 * time slice counter. Note: we do not update a thread's
2381 * priority until it either goes to sleep or uses up its
2382 * timeslice. This makes it possible for interactive tasks
2383 * to use up their timeslices at their highest priority levels.
2385 if (rt_task(p)) {
2387 * RR tasks need a special form of timeslice management.
2388 * FIFO tasks have no timeslices.
2390 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2391 p->time_slice = task_timeslice(p);
2392 p->first_time_slice = 0;
2393 set_tsk_need_resched(p);
2395 /* put it at the end of the queue: */
2396 requeue_task(p, rq->active);
2398 goto out_unlock;
2400 if (!--p->time_slice) {
2401 dequeue_task(p, rq->active);
2402 set_tsk_need_resched(p);
2403 p->prio = effective_prio(p);
2404 p->time_slice = task_timeslice(p);
2405 p->first_time_slice = 0;
2407 if (!rq->expired_timestamp)
2408 rq->expired_timestamp = jiffies;
2409 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2410 enqueue_task(p, rq->expired);
2411 if (p->static_prio < rq->best_expired_prio)
2412 rq->best_expired_prio = p->static_prio;
2413 } else
2414 enqueue_task(p, rq->active);
2415 } else {
2417 * Prevent a too long timeslice allowing a task to monopolize
2418 * the CPU. We do this by splitting up the timeslice into
2419 * smaller pieces.
2421 * Note: this does not mean the task's timeslices expire or
2422 * get lost in any way, they just might be preempted by
2423 * another task of equal priority. (one with higher
2424 * priority would have preempted this task already.) We
2425 * requeue this task to the end of the list on this priority
2426 * level, which is in essence a round-robin of tasks with
2427 * equal priority.
2429 * This only applies to tasks in the interactive
2430 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2432 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2433 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2434 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2435 (p->array == rq->active)) {
2437 requeue_task(p, rq->active);
2438 set_tsk_need_resched(p);
2441 out_unlock:
2442 spin_unlock(&rq->lock);
2443 out:
2444 rebalance_tick(cpu, rq, NOT_IDLE);
2447 #ifdef CONFIG_SCHED_SMT
2448 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2450 struct sched_domain *sd = this_rq->sd;
2451 cpumask_t sibling_map;
2452 int i;
2454 if (!(sd->flags & SD_SHARE_CPUPOWER))
2455 return;
2458 * Unlock the current runqueue because we have to lock in
2459 * CPU order to avoid deadlocks. Caller knows that we might
2460 * unlock. We keep IRQs disabled.
2462 spin_unlock(&this_rq->lock);
2464 sibling_map = sd->span;
2466 for_each_cpu_mask(i, sibling_map)
2467 spin_lock(&cpu_rq(i)->lock);
2469 * We clear this CPU from the mask. This both simplifies the
2470 * inner loop and keps this_rq locked when we exit:
2472 cpu_clear(this_cpu, sibling_map);
2474 for_each_cpu_mask(i, sibling_map) {
2475 runqueue_t *smt_rq = cpu_rq(i);
2478 * If an SMT sibling task is sleeping due to priority
2479 * reasons wake it up now.
2481 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
2482 resched_task(smt_rq->idle);
2485 for_each_cpu_mask(i, sibling_map)
2486 spin_unlock(&cpu_rq(i)->lock);
2488 * We exit with this_cpu's rq still held and IRQs
2489 * still disabled:
2493 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2495 struct sched_domain *sd = this_rq->sd;
2496 cpumask_t sibling_map;
2497 prio_array_t *array;
2498 int ret = 0, i;
2499 task_t *p;
2501 if (!(sd->flags & SD_SHARE_CPUPOWER))
2502 return 0;
2505 * The same locking rules and details apply as for
2506 * wake_sleeping_dependent():
2508 spin_unlock(&this_rq->lock);
2509 sibling_map = sd->span;
2510 for_each_cpu_mask(i, sibling_map)
2511 spin_lock(&cpu_rq(i)->lock);
2512 cpu_clear(this_cpu, sibling_map);
2515 * Establish next task to be run - it might have gone away because
2516 * we released the runqueue lock above:
2518 if (!this_rq->nr_running)
2519 goto out_unlock;
2520 array = this_rq->active;
2521 if (!array->nr_active)
2522 array = this_rq->expired;
2523 BUG_ON(!array->nr_active);
2525 p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
2526 task_t, run_list);
2528 for_each_cpu_mask(i, sibling_map) {
2529 runqueue_t *smt_rq = cpu_rq(i);
2530 task_t *smt_curr = smt_rq->curr;
2533 * If a user task with lower static priority than the
2534 * running task on the SMT sibling is trying to schedule,
2535 * delay it till there is proportionately less timeslice
2536 * left of the sibling task to prevent a lower priority
2537 * task from using an unfair proportion of the
2538 * physical cpu's resources. -ck
2540 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
2541 task_timeslice(p) || rt_task(smt_curr)) &&
2542 p->mm && smt_curr->mm && !rt_task(p))
2543 ret = 1;
2546 * Reschedule a lower priority task on the SMT sibling,
2547 * or wake it up if it has been put to sleep for priority
2548 * reasons.
2550 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
2551 task_timeslice(smt_curr) || rt_task(p)) &&
2552 smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
2553 (smt_curr == smt_rq->idle && smt_rq->nr_running))
2554 resched_task(smt_curr);
2556 out_unlock:
2557 for_each_cpu_mask(i, sibling_map)
2558 spin_unlock(&cpu_rq(i)->lock);
2559 return ret;
2561 #else
2562 static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2566 static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2568 return 0;
2570 #endif
2572 #if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
2574 void fastcall add_preempt_count(int val)
2577 * Underflow?
2579 BUG_ON(((int)preempt_count() < 0));
2580 preempt_count() += val;
2582 * Spinlock count overflowing soon?
2584 BUG_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
2586 EXPORT_SYMBOL(add_preempt_count);
2588 void fastcall sub_preempt_count(int val)
2591 * Underflow?
2593 BUG_ON(val > preempt_count());
2595 * Is the spinlock portion underflowing?
2597 BUG_ON((val < PREEMPT_MASK) && !(preempt_count() & PREEMPT_MASK));
2598 preempt_count() -= val;
2600 EXPORT_SYMBOL(sub_preempt_count);
2602 #endif
2605 * schedule() is the main scheduler function.
2607 asmlinkage void __sched schedule(void)
2609 long *switch_count;
2610 task_t *prev, *next;
2611 runqueue_t *rq;
2612 prio_array_t *array;
2613 struct list_head *queue;
2614 unsigned long long now;
2615 unsigned long run_time;
2616 int cpu, idx;
2619 * Test if we are atomic. Since do_exit() needs to call into
2620 * schedule() atomically, we ignore that path for now.
2621 * Otherwise, whine if we are scheduling when we should not be.
2623 if (likely(!current->exit_state)) {
2624 if (unlikely(in_atomic())) {
2625 printk(KERN_ERR "scheduling while atomic: "
2626 "%s/0x%08x/%d\n",
2627 current->comm, preempt_count(), current->pid);
2628 dump_stack();
2631 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
2633 need_resched:
2634 preempt_disable();
2635 prev = current;
2636 release_kernel_lock(prev);
2637 need_resched_nonpreemptible:
2638 rq = this_rq();
2641 * The idle thread is not allowed to schedule!
2642 * Remove this check after it has been exercised a bit.
2644 if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
2645 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
2646 dump_stack();
2649 schedstat_inc(rq, sched_cnt);
2650 now = sched_clock();
2651 if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
2652 run_time = now - prev->timestamp;
2653 if (unlikely((long long)(now - prev->timestamp) < 0))
2654 run_time = 0;
2655 } else
2656 run_time = NS_MAX_SLEEP_AVG;
2659 * Tasks charged proportionately less run_time at high sleep_avg to
2660 * delay them losing their interactive status
2662 run_time /= (CURRENT_BONUS(prev) ? : 1);
2664 spin_lock_irq(&rq->lock);
2666 if (unlikely(prev->flags & PF_DEAD))
2667 prev->state = EXIT_DEAD;
2669 switch_count = &prev->nivcsw;
2670 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2671 switch_count = &prev->nvcsw;
2672 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2673 unlikely(signal_pending(prev))))
2674 prev->state = TASK_RUNNING;
2675 else {
2676 if (prev->state == TASK_UNINTERRUPTIBLE)
2677 rq->nr_uninterruptible++;
2678 deactivate_task(prev, rq);
2682 cpu = smp_processor_id();
2683 if (unlikely(!rq->nr_running)) {
2684 go_idle:
2685 idle_balance(cpu, rq);
2686 if (!rq->nr_running) {
2687 next = rq->idle;
2688 rq->expired_timestamp = 0;
2689 wake_sleeping_dependent(cpu, rq);
2691 * wake_sleeping_dependent() might have released
2692 * the runqueue, so break out if we got new
2693 * tasks meanwhile:
2695 if (!rq->nr_running)
2696 goto switch_tasks;
2698 } else {
2699 if (dependent_sleeper(cpu, rq)) {
2700 next = rq->idle;
2701 goto switch_tasks;
2704 * dependent_sleeper() releases and reacquires the runqueue
2705 * lock, hence go into the idle loop if the rq went
2706 * empty meanwhile:
2708 if (unlikely(!rq->nr_running))
2709 goto go_idle;
2712 array = rq->active;
2713 if (unlikely(!array->nr_active)) {
2715 * Switch the active and expired arrays.
2717 schedstat_inc(rq, sched_switch);
2718 rq->active = rq->expired;
2719 rq->expired = array;
2720 array = rq->active;
2721 rq->expired_timestamp = 0;
2722 rq->best_expired_prio = MAX_PRIO;
2725 idx = sched_find_first_bit(array->bitmap);
2726 queue = array->queue + idx;
2727 next = list_entry(queue->next, task_t, run_list);
2729 if (!rt_task(next) && next->activated > 0) {
2730 unsigned long long delta = now - next->timestamp;
2731 if (unlikely((long long)(now - next->timestamp) < 0))
2732 delta = 0;
2734 if (next->activated == 1)
2735 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
2737 array = next->array;
2738 dequeue_task(next, array);
2739 recalc_task_prio(next, next->timestamp + delta);
2740 enqueue_task(next, array);
2742 next->activated = 0;
2743 switch_tasks:
2744 if (next == rq->idle)
2745 schedstat_inc(rq, sched_goidle);
2746 prefetch(next);
2747 clear_tsk_need_resched(prev);
2748 rcu_qsctr_inc(task_cpu(prev));
2750 update_cpu_clock(prev, rq, now);
2752 prev->sleep_avg -= run_time;
2753 if ((long)prev->sleep_avg <= 0)
2754 prev->sleep_avg = 0;
2755 prev->timestamp = prev->last_ran = now;
2757 sched_info_switch(prev, next);
2758 if (likely(prev != next)) {
2759 next->timestamp = now;
2760 rq->nr_switches++;
2761 rq->curr = next;
2762 ++*switch_count;
2764 prepare_arch_switch(rq, next);
2765 prev = context_switch(rq, prev, next);
2766 barrier();
2768 finish_task_switch(prev);
2769 } else
2770 spin_unlock_irq(&rq->lock);
2772 prev = current;
2773 if (unlikely(reacquire_kernel_lock(prev) < 0))
2774 goto need_resched_nonpreemptible;
2775 preempt_enable_no_resched();
2776 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2777 goto need_resched;
2780 EXPORT_SYMBOL(schedule);
2782 #ifdef CONFIG_PREEMPT
2784 * this is is the entry point to schedule() from in-kernel preemption
2785 * off of preempt_enable. Kernel preemptions off return from interrupt
2786 * occur there and call schedule directly.
2788 asmlinkage void __sched preempt_schedule(void)
2790 struct thread_info *ti = current_thread_info();
2791 #ifdef CONFIG_PREEMPT_BKL
2792 struct task_struct *task = current;
2793 int saved_lock_depth;
2794 #endif
2796 * If there is a non-zero preempt_count or interrupts are disabled,
2797 * we do not want to preempt the current task. Just return..
2799 if (unlikely(ti->preempt_count || irqs_disabled()))
2800 return;
2802 need_resched:
2803 add_preempt_count(PREEMPT_ACTIVE);
2805 * We keep the big kernel semaphore locked, but we
2806 * clear ->lock_depth so that schedule() doesnt
2807 * auto-release the semaphore:
2809 #ifdef CONFIG_PREEMPT_BKL
2810 saved_lock_depth = task->lock_depth;
2811 task->lock_depth = -1;
2812 #endif
2813 schedule();
2814 #ifdef CONFIG_PREEMPT_BKL
2815 task->lock_depth = saved_lock_depth;
2816 #endif
2817 sub_preempt_count(PREEMPT_ACTIVE);
2819 /* we could miss a preemption opportunity between schedule and now */
2820 barrier();
2821 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2822 goto need_resched;
2825 EXPORT_SYMBOL(preempt_schedule);
2828 * this is is the entry point to schedule() from kernel preemption
2829 * off of irq context.
2830 * Note, that this is called and return with irqs disabled. This will
2831 * protect us against recursive calling from irq.
2833 asmlinkage void __sched preempt_schedule_irq(void)
2835 struct thread_info *ti = current_thread_info();
2836 #ifdef CONFIG_PREEMPT_BKL
2837 struct task_struct *task = current;
2838 int saved_lock_depth;
2839 #endif
2840 /* Catch callers which need to be fixed*/
2841 BUG_ON(ti->preempt_count || !irqs_disabled());
2843 need_resched:
2844 add_preempt_count(PREEMPT_ACTIVE);
2846 * We keep the big kernel semaphore locked, but we
2847 * clear ->lock_depth so that schedule() doesnt
2848 * auto-release the semaphore:
2850 #ifdef CONFIG_PREEMPT_BKL
2851 saved_lock_depth = task->lock_depth;
2852 task->lock_depth = -1;
2853 #endif
2854 local_irq_enable();
2855 schedule();
2856 local_irq_disable();
2857 #ifdef CONFIG_PREEMPT_BKL
2858 task->lock_depth = saved_lock_depth;
2859 #endif
2860 sub_preempt_count(PREEMPT_ACTIVE);
2862 /* we could miss a preemption opportunity between schedule and now */
2863 barrier();
2864 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2865 goto need_resched;
2868 #endif /* CONFIG_PREEMPT */
2870 int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
2872 task_t *p = curr->task;
2873 return try_to_wake_up(p, mode, sync);
2876 EXPORT_SYMBOL(default_wake_function);
2879 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
2880 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
2881 * number) then we wake all the non-exclusive tasks and one exclusive task.
2883 * There are circumstances in which we can try to wake a task which has already
2884 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
2885 * zero in this (rare) case, and we handle it by continuing to scan the queue.
2887 static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
2888 int nr_exclusive, int sync, void *key)
2890 struct list_head *tmp, *next;
2892 list_for_each_safe(tmp, next, &q->task_list) {
2893 wait_queue_t *curr;
2894 unsigned flags;
2895 curr = list_entry(tmp, wait_queue_t, task_list);
2896 flags = curr->flags;
2897 if (curr->func(curr, mode, sync, key) &&
2898 (flags & WQ_FLAG_EXCLUSIVE) &&
2899 !--nr_exclusive)
2900 break;
2905 * __wake_up - wake up threads blocked on a waitqueue.
2906 * @q: the waitqueue
2907 * @mode: which threads
2908 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2910 void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
2911 int nr_exclusive, void *key)
2913 unsigned long flags;
2915 spin_lock_irqsave(&q->lock, flags);
2916 __wake_up_common(q, mode, nr_exclusive, 0, key);
2917 spin_unlock_irqrestore(&q->lock, flags);
2920 EXPORT_SYMBOL(__wake_up);
2923 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
2925 void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
2927 __wake_up_common(q, mode, 1, 0, NULL);
2931 * __wake_up - sync- wake up threads blocked on a waitqueue.
2932 * @q: the waitqueue
2933 * @mode: which threads
2934 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2936 * The sync wakeup differs that the waker knows that it will schedule
2937 * away soon, so while the target thread will be woken up, it will not
2938 * be migrated to another CPU - ie. the two threads are 'synchronized'
2939 * with each other. This can prevent needless bouncing between CPUs.
2941 * On UP it can prevent extra preemption.
2943 void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
2945 unsigned long flags;
2946 int sync = 1;
2948 if (unlikely(!q))
2949 return;
2951 if (unlikely(!nr_exclusive))
2952 sync = 0;
2954 spin_lock_irqsave(&q->lock, flags);
2955 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
2956 spin_unlock_irqrestore(&q->lock, flags);
2958 EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
2960 void fastcall complete(struct completion *x)
2962 unsigned long flags;
2964 spin_lock_irqsave(&x->wait.lock, flags);
2965 x->done++;
2966 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2967 1, 0, NULL);
2968 spin_unlock_irqrestore(&x->wait.lock, flags);
2970 EXPORT_SYMBOL(complete);
2972 void fastcall complete_all(struct completion *x)
2974 unsigned long flags;
2976 spin_lock_irqsave(&x->wait.lock, flags);
2977 x->done += UINT_MAX/2;
2978 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
2979 0, 0, NULL);
2980 spin_unlock_irqrestore(&x->wait.lock, flags);
2982 EXPORT_SYMBOL(complete_all);
2984 void fastcall __sched wait_for_completion(struct completion *x)
2986 might_sleep();
2987 spin_lock_irq(&x->wait.lock);
2988 if (!x->done) {
2989 DECLARE_WAITQUEUE(wait, current);
2991 wait.flags |= WQ_FLAG_EXCLUSIVE;
2992 __add_wait_queue_tail(&x->wait, &wait);
2993 do {
2994 __set_current_state(TASK_UNINTERRUPTIBLE);
2995 spin_unlock_irq(&x->wait.lock);
2996 schedule();
2997 spin_lock_irq(&x->wait.lock);
2998 } while (!x->done);
2999 __remove_wait_queue(&x->wait, &wait);
3001 x->done--;
3002 spin_unlock_irq(&x->wait.lock);
3004 EXPORT_SYMBOL(wait_for_completion);
3006 unsigned long fastcall __sched
3007 wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3009 might_sleep();
3011 spin_lock_irq(&x->wait.lock);
3012 if (!x->done) {
3013 DECLARE_WAITQUEUE(wait, current);
3015 wait.flags |= WQ_FLAG_EXCLUSIVE;
3016 __add_wait_queue_tail(&x->wait, &wait);
3017 do {
3018 __set_current_state(TASK_UNINTERRUPTIBLE);
3019 spin_unlock_irq(&x->wait.lock);
3020 timeout = schedule_timeout(timeout);
3021 spin_lock_irq(&x->wait.lock);
3022 if (!timeout) {
3023 __remove_wait_queue(&x->wait, &wait);
3024 goto out;
3026 } while (!x->done);
3027 __remove_wait_queue(&x->wait, &wait);
3029 x->done--;
3030 out:
3031 spin_unlock_irq(&x->wait.lock);
3032 return timeout;
3034 EXPORT_SYMBOL(wait_for_completion_timeout);
3036 int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3038 int ret = 0;
3040 might_sleep();
3042 spin_lock_irq(&x->wait.lock);
3043 if (!x->done) {
3044 DECLARE_WAITQUEUE(wait, current);
3046 wait.flags |= WQ_FLAG_EXCLUSIVE;
3047 __add_wait_queue_tail(&x->wait, &wait);
3048 do {
3049 if (signal_pending(current)) {
3050 ret = -ERESTARTSYS;
3051 __remove_wait_queue(&x->wait, &wait);
3052 goto out;
3054 __set_current_state(TASK_INTERRUPTIBLE);
3055 spin_unlock_irq(&x->wait.lock);
3056 schedule();
3057 spin_lock_irq(&x->wait.lock);
3058 } while (!x->done);
3059 __remove_wait_queue(&x->wait, &wait);
3061 x->done--;
3062 out:
3063 spin_unlock_irq(&x->wait.lock);
3065 return ret;
3067 EXPORT_SYMBOL(wait_for_completion_interruptible);
3069 unsigned long fastcall __sched
3070 wait_for_completion_interruptible_timeout(struct completion *x,
3071 unsigned long timeout)
3073 might_sleep();
3075 spin_lock_irq(&x->wait.lock);
3076 if (!x->done) {
3077 DECLARE_WAITQUEUE(wait, current);
3079 wait.flags |= WQ_FLAG_EXCLUSIVE;
3080 __add_wait_queue_tail(&x->wait, &wait);
3081 do {
3082 if (signal_pending(current)) {
3083 timeout = -ERESTARTSYS;
3084 __remove_wait_queue(&x->wait, &wait);
3085 goto out;
3087 __set_current_state(TASK_INTERRUPTIBLE);
3088 spin_unlock_irq(&x->wait.lock);
3089 timeout = schedule_timeout(timeout);
3090 spin_lock_irq(&x->wait.lock);
3091 if (!timeout) {
3092 __remove_wait_queue(&x->wait, &wait);
3093 goto out;
3095 } while (!x->done);
3096 __remove_wait_queue(&x->wait, &wait);
3098 x->done--;
3099 out:
3100 spin_unlock_irq(&x->wait.lock);
3101 return timeout;
3103 EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3106 #define SLEEP_ON_VAR \
3107 unsigned long flags; \
3108 wait_queue_t wait; \
3109 init_waitqueue_entry(&wait, current);
3111 #define SLEEP_ON_HEAD \
3112 spin_lock_irqsave(&q->lock,flags); \
3113 __add_wait_queue(q, &wait); \
3114 spin_unlock(&q->lock);
3116 #define SLEEP_ON_TAIL \
3117 spin_lock_irq(&q->lock); \
3118 __remove_wait_queue(q, &wait); \
3119 spin_unlock_irqrestore(&q->lock, flags);
3121 void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3123 SLEEP_ON_VAR
3125 current->state = TASK_INTERRUPTIBLE;
3127 SLEEP_ON_HEAD
3128 schedule();
3129 SLEEP_ON_TAIL
3132 EXPORT_SYMBOL(interruptible_sleep_on);
3134 long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3136 SLEEP_ON_VAR
3138 current->state = TASK_INTERRUPTIBLE;
3140 SLEEP_ON_HEAD
3141 timeout = schedule_timeout(timeout);
3142 SLEEP_ON_TAIL
3144 return timeout;
3147 EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3149 void fastcall __sched sleep_on(wait_queue_head_t *q)
3151 SLEEP_ON_VAR
3153 current->state = TASK_UNINTERRUPTIBLE;
3155 SLEEP_ON_HEAD
3156 schedule();
3157 SLEEP_ON_TAIL
3160 EXPORT_SYMBOL(sleep_on);
3162 long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3164 SLEEP_ON_VAR
3166 current->state = TASK_UNINTERRUPTIBLE;
3168 SLEEP_ON_HEAD
3169 timeout = schedule_timeout(timeout);
3170 SLEEP_ON_TAIL
3172 return timeout;
3175 EXPORT_SYMBOL(sleep_on_timeout);
3177 void set_user_nice(task_t *p, long nice)
3179 unsigned long flags;
3180 prio_array_t *array;
3181 runqueue_t *rq;
3182 int old_prio, new_prio, delta;
3184 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3185 return;
3187 * We have to be careful, if called from sys_setpriority(),
3188 * the task might be in the middle of scheduling on another CPU.
3190 rq = task_rq_lock(p, &flags);
3192 * The RT priorities are set via sched_setscheduler(), but we still
3193 * allow the 'normal' nice value to be set - but as expected
3194 * it wont have any effect on scheduling until the task is
3195 * not SCHED_NORMAL:
3197 if (rt_task(p)) {
3198 p->static_prio = NICE_TO_PRIO(nice);
3199 goto out_unlock;
3201 array = p->array;
3202 if (array)
3203 dequeue_task(p, array);
3205 old_prio = p->prio;
3206 new_prio = NICE_TO_PRIO(nice);
3207 delta = new_prio - old_prio;
3208 p->static_prio = NICE_TO_PRIO(nice);
3209 p->prio += delta;
3211 if (array) {
3212 enqueue_task(p, array);
3214 * If the task increased its priority or is running and
3215 * lowered its priority, then reschedule its CPU:
3217 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3218 resched_task(rq->curr);
3220 out_unlock:
3221 task_rq_unlock(rq, &flags);
3224 EXPORT_SYMBOL(set_user_nice);
3226 #ifdef __ARCH_WANT_SYS_NICE
3229 * sys_nice - change the priority of the current process.
3230 * @increment: priority increment
3232 * sys_setpriority is a more generic, but much slower function that
3233 * does similar things.
3235 asmlinkage long sys_nice(int increment)
3237 int retval;
3238 long nice;
3241 * Setpriority might change our priority at the same moment.
3242 * We don't have to worry. Conceptually one call occurs first
3243 * and we have a single winner.
3245 if (increment < 0) {
3246 if (!capable(CAP_SYS_NICE))
3247 return -EPERM;
3248 if (increment < -40)
3249 increment = -40;
3251 if (increment > 40)
3252 increment = 40;
3254 nice = PRIO_TO_NICE(current->static_prio) + increment;
3255 if (nice < -20)
3256 nice = -20;
3257 if (nice > 19)
3258 nice = 19;
3260 retval = security_task_setnice(current, nice);
3261 if (retval)
3262 return retval;
3264 set_user_nice(current, nice);
3265 return 0;
3268 #endif
3271 * task_prio - return the priority value of a given task.
3272 * @p: the task in question.
3274 * This is the priority value as seen by users in /proc.
3275 * RT tasks are offset by -200. Normal tasks are centered
3276 * around 0, value goes from -16 to +15.
3278 int task_prio(const task_t *p)
3280 return p->prio - MAX_RT_PRIO;
3284 * task_nice - return the nice value of a given task.
3285 * @p: the task in question.
3287 int task_nice(const task_t *p)
3289 return TASK_NICE(p);
3293 * The only users of task_nice are binfmt_elf and binfmt_elf32.
3294 * binfmt_elf is no longer modular, but binfmt_elf32 still is.
3295 * Therefore, task_nice is needed if there is a compat_mode.
3297 #ifdef CONFIG_COMPAT
3298 EXPORT_SYMBOL_GPL(task_nice);
3299 #endif
3302 * idle_cpu - is a given cpu idle currently?
3303 * @cpu: the processor in question.
3305 int idle_cpu(int cpu)
3307 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3310 EXPORT_SYMBOL_GPL(idle_cpu);
3313 * idle_task - return the idle task for a given cpu.
3314 * @cpu: the processor in question.
3316 task_t *idle_task(int cpu)
3318 return cpu_rq(cpu)->idle;
3322 * find_process_by_pid - find a process with a matching PID value.
3323 * @pid: the pid in question.
3325 static inline task_t *find_process_by_pid(pid_t pid)
3327 return pid ? find_task_by_pid(pid) : current;
3330 /* Actually do priority change: must hold rq lock. */
3331 static void __setscheduler(struct task_struct *p, int policy, int prio)
3333 BUG_ON(p->array);
3334 p->policy = policy;
3335 p->rt_priority = prio;
3336 if (policy != SCHED_NORMAL)
3337 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
3338 else
3339 p->prio = p->static_prio;
3343 * sched_setscheduler - change the scheduling policy and/or RT priority of
3344 * a thread.
3345 * @p: the task in question.
3346 * @policy: new policy.
3347 * @param: structure containing the new RT priority.
3349 int sched_setscheduler(struct task_struct *p, int policy, struct sched_param *param)
3351 int retval;
3352 int oldprio, oldpolicy = -1;
3353 prio_array_t *array;
3354 unsigned long flags;
3355 runqueue_t *rq;
3357 recheck:
3358 /* double check policy once rq lock held */
3359 if (policy < 0)
3360 policy = oldpolicy = p->policy;
3361 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
3362 policy != SCHED_NORMAL)
3363 return -EINVAL;
3365 * Valid priorities for SCHED_FIFO and SCHED_RR are
3366 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
3368 if (param->sched_priority < 0 ||
3369 param->sched_priority > MAX_USER_RT_PRIO-1)
3370 return -EINVAL;
3371 if ((policy == SCHED_NORMAL) != (param->sched_priority == 0))
3372 return -EINVAL;
3374 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
3375 !capable(CAP_SYS_NICE))
3376 return -EPERM;
3377 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3378 !capable(CAP_SYS_NICE))
3379 return -EPERM;
3381 retval = security_task_setscheduler(p, policy, param);
3382 if (retval)
3383 return retval;
3385 * To be able to change p->policy safely, the apropriate
3386 * runqueue lock must be held.
3388 rq = task_rq_lock(p, &flags);
3389 /* recheck policy now with rq lock held */
3390 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3391 policy = oldpolicy = -1;
3392 task_rq_unlock(rq, &flags);
3393 goto recheck;
3395 array = p->array;
3396 if (array)
3397 deactivate_task(p, rq);
3398 oldprio = p->prio;
3399 __setscheduler(p, policy, param->sched_priority);
3400 if (array) {
3401 __activate_task(p, rq);
3403 * Reschedule if we are currently running on this runqueue and
3404 * our priority decreased, or if we are not currently running on
3405 * this runqueue and our priority is higher than the current's
3407 if (task_running(rq, p)) {
3408 if (p->prio > oldprio)
3409 resched_task(rq->curr);
3410 } else if (TASK_PREEMPTS_CURR(p, rq))
3411 resched_task(rq->curr);
3413 task_rq_unlock(rq, &flags);
3414 return 0;
3416 EXPORT_SYMBOL_GPL(sched_setscheduler);
3418 static int do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3420 int retval;
3421 struct sched_param lparam;
3422 struct task_struct *p;
3424 if (!param || pid < 0)
3425 return -EINVAL;
3426 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
3427 return -EFAULT;
3428 read_lock_irq(&tasklist_lock);
3429 p = find_process_by_pid(pid);
3430 if (!p) {
3431 read_unlock_irq(&tasklist_lock);
3432 return -ESRCH;
3434 retval = sched_setscheduler(p, policy, &lparam);
3435 read_unlock_irq(&tasklist_lock);
3436 return retval;
3440 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3441 * @pid: the pid in question.
3442 * @policy: new policy.
3443 * @param: structure containing the new RT priority.
3445 asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3446 struct sched_param __user *param)
3448 return do_sched_setscheduler(pid, policy, param);
3452 * sys_sched_setparam - set/change the RT priority of a thread
3453 * @pid: the pid in question.
3454 * @param: structure containing the new RT priority.
3456 asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3458 return do_sched_setscheduler(pid, -1, param);
3462 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3463 * @pid: the pid in question.
3465 asmlinkage long sys_sched_getscheduler(pid_t pid)
3467 int retval = -EINVAL;
3468 task_t *p;
3470 if (pid < 0)
3471 goto out_nounlock;
3473 retval = -ESRCH;
3474 read_lock(&tasklist_lock);
3475 p = find_process_by_pid(pid);
3476 if (p) {
3477 retval = security_task_getscheduler(p);
3478 if (!retval)
3479 retval = p->policy;
3481 read_unlock(&tasklist_lock);
3483 out_nounlock:
3484 return retval;
3488 * sys_sched_getscheduler - get the RT priority of a thread
3489 * @pid: the pid in question.
3490 * @param: structure containing the RT priority.
3492 asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3494 struct sched_param lp;
3495 int retval = -EINVAL;
3496 task_t *p;
3498 if (!param || pid < 0)
3499 goto out_nounlock;
3501 read_lock(&tasklist_lock);
3502 p = find_process_by_pid(pid);
3503 retval = -ESRCH;
3504 if (!p)
3505 goto out_unlock;
3507 retval = security_task_getscheduler(p);
3508 if (retval)
3509 goto out_unlock;
3511 lp.sched_priority = p->rt_priority;
3512 read_unlock(&tasklist_lock);
3515 * This one might sleep, we cannot do it with a spinlock held ...
3517 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3519 out_nounlock:
3520 return retval;
3522 out_unlock:
3523 read_unlock(&tasklist_lock);
3524 return retval;
3527 long sched_setaffinity(pid_t pid, cpumask_t new_mask)
3529 task_t *p;
3530 int retval;
3531 cpumask_t cpus_allowed;
3533 lock_cpu_hotplug();
3534 read_lock(&tasklist_lock);
3536 p = find_process_by_pid(pid);
3537 if (!p) {
3538 read_unlock(&tasklist_lock);
3539 unlock_cpu_hotplug();
3540 return -ESRCH;
3544 * It is not safe to call set_cpus_allowed with the
3545 * tasklist_lock held. We will bump the task_struct's
3546 * usage count and then drop tasklist_lock.
3548 get_task_struct(p);
3549 read_unlock(&tasklist_lock);
3551 retval = -EPERM;
3552 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3553 !capable(CAP_SYS_NICE))
3554 goto out_unlock;
3556 cpus_allowed = cpuset_cpus_allowed(p);
3557 cpus_and(new_mask, new_mask, cpus_allowed);
3558 retval = set_cpus_allowed(p, new_mask);
3560 out_unlock:
3561 put_task_struct(p);
3562 unlock_cpu_hotplug();
3563 return retval;
3566 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
3567 cpumask_t *new_mask)
3569 if (len < sizeof(cpumask_t)) {
3570 memset(new_mask, 0, sizeof(cpumask_t));
3571 } else if (len > sizeof(cpumask_t)) {
3572 len = sizeof(cpumask_t);
3574 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
3578 * sys_sched_setaffinity - set the cpu affinity of a process
3579 * @pid: pid of the process
3580 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3581 * @user_mask_ptr: user-space pointer to the new cpu mask
3583 asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
3584 unsigned long __user *user_mask_ptr)
3586 cpumask_t new_mask;
3587 int retval;
3589 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
3590 if (retval)
3591 return retval;
3593 return sched_setaffinity(pid, new_mask);
3597 * Represents all cpu's present in the system
3598 * In systems capable of hotplug, this map could dynamically grow
3599 * as new cpu's are detected in the system via any platform specific
3600 * method, such as ACPI for e.g.
3603 cpumask_t cpu_present_map;
3604 EXPORT_SYMBOL(cpu_present_map);
3606 #ifndef CONFIG_SMP
3607 cpumask_t cpu_online_map = CPU_MASK_ALL;
3608 cpumask_t cpu_possible_map = CPU_MASK_ALL;
3609 #endif
3611 long sched_getaffinity(pid_t pid, cpumask_t *mask)
3613 int retval;
3614 task_t *p;
3616 lock_cpu_hotplug();
3617 read_lock(&tasklist_lock);
3619 retval = -ESRCH;
3620 p = find_process_by_pid(pid);
3621 if (!p)
3622 goto out_unlock;
3624 retval = 0;
3625 cpus_and(*mask, p->cpus_allowed, cpu_possible_map);
3627 out_unlock:
3628 read_unlock(&tasklist_lock);
3629 unlock_cpu_hotplug();
3630 if (retval)
3631 return retval;
3633 return 0;
3637 * sys_sched_getaffinity - get the cpu affinity of a process
3638 * @pid: pid of the process
3639 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3640 * @user_mask_ptr: user-space pointer to hold the current cpu mask
3642 asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
3643 unsigned long __user *user_mask_ptr)
3645 int ret;
3646 cpumask_t mask;
3648 if (len < sizeof(cpumask_t))
3649 return -EINVAL;
3651 ret = sched_getaffinity(pid, &mask);
3652 if (ret < 0)
3653 return ret;
3655 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
3656 return -EFAULT;
3658 return sizeof(cpumask_t);
3662 * sys_sched_yield - yield the current processor to other threads.
3664 * this function yields the current CPU by moving the calling thread
3665 * to the expired array. If there are no other threads running on this
3666 * CPU then this function will return.
3668 asmlinkage long sys_sched_yield(void)
3670 runqueue_t *rq = this_rq_lock();
3671 prio_array_t *array = current->array;
3672 prio_array_t *target = rq->expired;
3674 schedstat_inc(rq, yld_cnt);
3676 * We implement yielding by moving the task into the expired
3677 * queue.
3679 * (special rule: RT tasks will just roundrobin in the active
3680 * array.)
3682 if (rt_task(current))
3683 target = rq->active;
3685 if (current->array->nr_active == 1) {
3686 schedstat_inc(rq, yld_act_empty);
3687 if (!rq->expired->nr_active)
3688 schedstat_inc(rq, yld_both_empty);
3689 } else if (!rq->expired->nr_active)
3690 schedstat_inc(rq, yld_exp_empty);
3692 if (array != target) {
3693 dequeue_task(current, array);
3694 enqueue_task(current, target);
3695 } else
3697 * requeue_task is cheaper so perform that if possible.
3699 requeue_task(current, array);
3702 * Since we are going to call schedule() anyway, there's
3703 * no need to preempt or enable interrupts:
3705 __release(rq->lock);
3706 _raw_spin_unlock(&rq->lock);
3707 preempt_enable_no_resched();
3709 schedule();
3711 return 0;
3714 static inline void __cond_resched(void)
3716 do {
3717 add_preempt_count(PREEMPT_ACTIVE);
3718 schedule();
3719 sub_preempt_count(PREEMPT_ACTIVE);
3720 } while (need_resched());
3723 int __sched cond_resched(void)
3725 if (need_resched()) {
3726 __cond_resched();
3727 return 1;
3729 return 0;
3732 EXPORT_SYMBOL(cond_resched);
3735 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
3736 * call schedule, and on return reacquire the lock.
3738 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
3739 * operations here to prevent schedule() from being called twice (once via
3740 * spin_unlock(), once by hand).
3742 int cond_resched_lock(spinlock_t * lock)
3744 if (need_lockbreak(lock)) {
3745 spin_unlock(lock);
3746 cpu_relax();
3747 spin_lock(lock);
3749 if (need_resched()) {
3750 _raw_spin_unlock(lock);
3751 preempt_enable_no_resched();
3752 __cond_resched();
3753 spin_lock(lock);
3754 return 1;
3756 return 0;
3759 EXPORT_SYMBOL(cond_resched_lock);
3761 int __sched cond_resched_softirq(void)
3763 BUG_ON(!in_softirq());
3765 if (need_resched()) {
3766 __local_bh_enable();
3767 __cond_resched();
3768 local_bh_disable();
3769 return 1;
3771 return 0;
3774 EXPORT_SYMBOL(cond_resched_softirq);
3778 * yield - yield the current processor to other threads.
3780 * this is a shortcut for kernel-space yielding - it marks the
3781 * thread runnable and calls sys_sched_yield().
3783 void __sched yield(void)
3785 set_current_state(TASK_RUNNING);
3786 sys_sched_yield();
3789 EXPORT_SYMBOL(yield);
3792 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
3793 * that process accounting knows that this is a task in IO wait state.
3795 * But don't do that if it is a deliberate, throttling IO wait (this task
3796 * has set its backing_dev_info: the queue against which it should throttle)
3798 void __sched io_schedule(void)
3800 struct runqueue *rq = &per_cpu(runqueues, _smp_processor_id());
3802 atomic_inc(&rq->nr_iowait);
3803 schedule();
3804 atomic_dec(&rq->nr_iowait);
3807 EXPORT_SYMBOL(io_schedule);
3809 long __sched io_schedule_timeout(long timeout)
3811 struct runqueue *rq = &per_cpu(runqueues, _smp_processor_id());
3812 long ret;
3814 atomic_inc(&rq->nr_iowait);
3815 ret = schedule_timeout(timeout);
3816 atomic_dec(&rq->nr_iowait);
3817 return ret;
3821 * sys_sched_get_priority_max - return maximum RT priority.
3822 * @policy: scheduling class.
3824 * this syscall returns the maximum rt_priority that can be used
3825 * by a given scheduling class.
3827 asmlinkage long sys_sched_get_priority_max(int policy)
3829 int ret = -EINVAL;
3831 switch (policy) {
3832 case SCHED_FIFO:
3833 case SCHED_RR:
3834 ret = MAX_USER_RT_PRIO-1;
3835 break;
3836 case SCHED_NORMAL:
3837 ret = 0;
3838 break;
3840 return ret;
3844 * sys_sched_get_priority_min - return minimum RT priority.
3845 * @policy: scheduling class.
3847 * this syscall returns the minimum rt_priority that can be used
3848 * by a given scheduling class.
3850 asmlinkage long sys_sched_get_priority_min(int policy)
3852 int ret = -EINVAL;
3854 switch (policy) {
3855 case SCHED_FIFO:
3856 case SCHED_RR:
3857 ret = 1;
3858 break;
3859 case SCHED_NORMAL:
3860 ret = 0;
3862 return ret;
3866 * sys_sched_rr_get_interval - return the default timeslice of a process.
3867 * @pid: pid of the process.
3868 * @interval: userspace pointer to the timeslice value.
3870 * this syscall writes the default timeslice value of a given process
3871 * into the user-space timespec buffer. A value of '0' means infinity.
3873 asmlinkage
3874 long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
3876 int retval = -EINVAL;
3877 struct timespec t;
3878 task_t *p;
3880 if (pid < 0)
3881 goto out_nounlock;
3883 retval = -ESRCH;
3884 read_lock(&tasklist_lock);
3885 p = find_process_by_pid(pid);
3886 if (!p)
3887 goto out_unlock;
3889 retval = security_task_getscheduler(p);
3890 if (retval)
3891 goto out_unlock;
3893 jiffies_to_timespec(p->policy & SCHED_FIFO ?
3894 0 : task_timeslice(p), &t);
3895 read_unlock(&tasklist_lock);
3896 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
3897 out_nounlock:
3898 return retval;
3899 out_unlock:
3900 read_unlock(&tasklist_lock);
3901 return retval;
3904 static inline struct task_struct *eldest_child(struct task_struct *p)
3906 if (list_empty(&p->children)) return NULL;
3907 return list_entry(p->children.next,struct task_struct,sibling);
3910 static inline struct task_struct *older_sibling(struct task_struct *p)
3912 if (p->sibling.prev==&p->parent->children) return NULL;
3913 return list_entry(p->sibling.prev,struct task_struct,sibling);
3916 static inline struct task_struct *younger_sibling(struct task_struct *p)
3918 if (p->sibling.next==&p->parent->children) return NULL;
3919 return list_entry(p->sibling.next,struct task_struct,sibling);
3922 static void show_task(task_t * p)
3924 task_t *relative;
3925 unsigned state;
3926 unsigned long free = 0;
3927 static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
3929 printk("%-13.13s ", p->comm);
3930 state = p->state ? __ffs(p->state) + 1 : 0;
3931 if (state < ARRAY_SIZE(stat_nam))
3932 printk(stat_nam[state]);
3933 else
3934 printk("?");
3935 #if (BITS_PER_LONG == 32)
3936 if (state == TASK_RUNNING)
3937 printk(" running ");
3938 else
3939 printk(" %08lX ", thread_saved_pc(p));
3940 #else
3941 if (state == TASK_RUNNING)
3942 printk(" running task ");
3943 else
3944 printk(" %016lx ", thread_saved_pc(p));
3945 #endif
3946 #ifdef CONFIG_DEBUG_STACK_USAGE
3948 unsigned long * n = (unsigned long *) (p->thread_info+1);
3949 while (!*n)
3950 n++;
3951 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
3953 #endif
3954 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
3955 if ((relative = eldest_child(p)))
3956 printk("%5d ", relative->pid);
3957 else
3958 printk(" ");
3959 if ((relative = younger_sibling(p)))
3960 printk("%7d", relative->pid);
3961 else
3962 printk(" ");
3963 if ((relative = older_sibling(p)))
3964 printk(" %5d", relative->pid);
3965 else
3966 printk(" ");
3967 if (!p->mm)
3968 printk(" (L-TLB)\n");
3969 else
3970 printk(" (NOTLB)\n");
3972 if (state != TASK_RUNNING)
3973 show_stack(p, NULL);
3976 void show_state(void)
3978 task_t *g, *p;
3980 #if (BITS_PER_LONG == 32)
3981 printk("\n"
3982 " sibling\n");
3983 printk(" task PC pid father child younger older\n");
3984 #else
3985 printk("\n"
3986 " sibling\n");
3987 printk(" task PC pid father child younger older\n");
3988 #endif
3989 read_lock(&tasklist_lock);
3990 do_each_thread(g, p) {
3992 * reset the NMI-timeout, listing all files on a slow
3993 * console might take alot of time:
3995 touch_nmi_watchdog();
3996 show_task(p);
3997 } while_each_thread(g, p);
3999 read_unlock(&tasklist_lock);
4002 void __devinit init_idle(task_t *idle, int cpu)
4004 runqueue_t *rq = cpu_rq(cpu);
4005 unsigned long flags;
4007 idle->sleep_avg = 0;
4008 idle->array = NULL;
4009 idle->prio = MAX_PRIO;
4010 idle->state = TASK_RUNNING;
4011 idle->cpus_allowed = cpumask_of_cpu(cpu);
4012 set_task_cpu(idle, cpu);
4014 spin_lock_irqsave(&rq->lock, flags);
4015 rq->curr = rq->idle = idle;
4016 set_tsk_need_resched(idle);
4017 spin_unlock_irqrestore(&rq->lock, flags);
4019 /* Set the preempt count _outside_ the spinlocks! */
4020 #if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4021 idle->thread_info->preempt_count = (idle->lock_depth >= 0);
4022 #else
4023 idle->thread_info->preempt_count = 0;
4024 #endif
4028 * In a system that switches off the HZ timer nohz_cpu_mask
4029 * indicates which cpus entered this state. This is used
4030 * in the rcu update to wait only for active cpus. For system
4031 * which do not switch off the HZ timer nohz_cpu_mask should
4032 * always be CPU_MASK_NONE.
4034 cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4036 #ifdef CONFIG_SMP
4038 * This is how migration works:
4040 * 1) we queue a migration_req_t structure in the source CPU's
4041 * runqueue and wake up that CPU's migration thread.
4042 * 2) we down() the locked semaphore => thread blocks.
4043 * 3) migration thread wakes up (implicitly it forces the migrated
4044 * thread off the CPU)
4045 * 4) it gets the migration request and checks whether the migrated
4046 * task is still in the wrong runqueue.
4047 * 5) if it's in the wrong runqueue then the migration thread removes
4048 * it and puts it into the right queue.
4049 * 6) migration thread up()s the semaphore.
4050 * 7) we wake up and the migration is done.
4054 * Change a given task's CPU affinity. Migrate the thread to a
4055 * proper CPU and schedule it away if the CPU it's executing on
4056 * is removed from the allowed bitmask.
4058 * NOTE: the caller must have a valid reference to the task, the
4059 * task must not exit() & deallocate itself prematurely. The
4060 * call is not atomic; no spinlocks may be held.
4062 int set_cpus_allowed(task_t *p, cpumask_t new_mask)
4064 unsigned long flags;
4065 int ret = 0;
4066 migration_req_t req;
4067 runqueue_t *rq;
4069 rq = task_rq_lock(p, &flags);
4070 if (!cpus_intersects(new_mask, cpu_online_map)) {
4071 ret = -EINVAL;
4072 goto out;
4075 p->cpus_allowed = new_mask;
4076 /* Can the task run on the task's current CPU? If so, we're done */
4077 if (cpu_isset(task_cpu(p), new_mask))
4078 goto out;
4080 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4081 /* Need help from migration thread: drop lock and wait. */
4082 task_rq_unlock(rq, &flags);
4083 wake_up_process(rq->migration_thread);
4084 wait_for_completion(&req.done);
4085 tlb_migrate_finish(p->mm);
4086 return 0;
4088 out:
4089 task_rq_unlock(rq, &flags);
4090 return ret;
4093 EXPORT_SYMBOL_GPL(set_cpus_allowed);
4096 * Move (not current) task off this cpu, onto dest cpu. We're doing
4097 * this because either it can't run here any more (set_cpus_allowed()
4098 * away from this CPU, or CPU going down), or because we're
4099 * attempting to rebalance this task on exec (sched_exec).
4101 * So we race with normal scheduler movements, but that's OK, as long
4102 * as the task is no longer on this CPU.
4104 static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4106 runqueue_t *rq_dest, *rq_src;
4108 if (unlikely(cpu_is_offline(dest_cpu)))
4109 return;
4111 rq_src = cpu_rq(src_cpu);
4112 rq_dest = cpu_rq(dest_cpu);
4114 double_rq_lock(rq_src, rq_dest);
4115 /* Already moved. */
4116 if (task_cpu(p) != src_cpu)
4117 goto out;
4118 /* Affinity changed (again). */
4119 if (!cpu_isset(dest_cpu, p->cpus_allowed))
4120 goto out;
4122 set_task_cpu(p, dest_cpu);
4123 if (p->array) {
4125 * Sync timestamp with rq_dest's before activating.
4126 * The same thing could be achieved by doing this step
4127 * afterwards, and pretending it was a local activate.
4128 * This way is cleaner and logically correct.
4130 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4131 + rq_dest->timestamp_last_tick;
4132 deactivate_task(p, rq_src);
4133 activate_task(p, rq_dest, 0);
4134 if (TASK_PREEMPTS_CURR(p, rq_dest))
4135 resched_task(rq_dest->curr);
4138 out:
4139 double_rq_unlock(rq_src, rq_dest);
4143 * migration_thread - this is a highprio system thread that performs
4144 * thread migration by bumping thread off CPU then 'pushing' onto
4145 * another runqueue.
4147 static int migration_thread(void * data)
4149 runqueue_t *rq;
4150 int cpu = (long)data;
4152 rq = cpu_rq(cpu);
4153 BUG_ON(rq->migration_thread != current);
4155 set_current_state(TASK_INTERRUPTIBLE);
4156 while (!kthread_should_stop()) {
4157 struct list_head *head;
4158 migration_req_t *req;
4160 if (current->flags & PF_FREEZE)
4161 refrigerator(PF_FREEZE);
4163 spin_lock_irq(&rq->lock);
4165 if (cpu_is_offline(cpu)) {
4166 spin_unlock_irq(&rq->lock);
4167 goto wait_to_die;
4170 if (rq->active_balance) {
4171 active_load_balance(rq, cpu);
4172 rq->active_balance = 0;
4175 head = &rq->migration_queue;
4177 if (list_empty(head)) {
4178 spin_unlock_irq(&rq->lock);
4179 schedule();
4180 set_current_state(TASK_INTERRUPTIBLE);
4181 continue;
4183 req = list_entry(head->next, migration_req_t, list);
4184 list_del_init(head->next);
4186 if (req->type == REQ_MOVE_TASK) {
4187 spin_unlock(&rq->lock);
4188 __migrate_task(req->task, cpu, req->dest_cpu);
4189 local_irq_enable();
4190 } else if (req->type == REQ_SET_DOMAIN) {
4191 rq->sd = req->sd;
4192 spin_unlock_irq(&rq->lock);
4193 } else {
4194 spin_unlock_irq(&rq->lock);
4195 WARN_ON(1);
4198 complete(&req->done);
4200 __set_current_state(TASK_RUNNING);
4201 return 0;
4203 wait_to_die:
4204 /* Wait for kthread_stop */
4205 set_current_state(TASK_INTERRUPTIBLE);
4206 while (!kthread_should_stop()) {
4207 schedule();
4208 set_current_state(TASK_INTERRUPTIBLE);
4210 __set_current_state(TASK_RUNNING);
4211 return 0;
4214 #ifdef CONFIG_HOTPLUG_CPU
4215 /* Figure out where task on dead CPU should go, use force if neccessary. */
4216 static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
4218 int dest_cpu;
4219 cpumask_t mask;
4221 /* On same node? */
4222 mask = node_to_cpumask(cpu_to_node(dead_cpu));
4223 cpus_and(mask, mask, tsk->cpus_allowed);
4224 dest_cpu = any_online_cpu(mask);
4226 /* On any allowed CPU? */
4227 if (dest_cpu == NR_CPUS)
4228 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4230 /* No more Mr. Nice Guy. */
4231 if (dest_cpu == NR_CPUS) {
4232 tsk->cpus_allowed = cpuset_cpus_allowed(tsk);
4233 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4236 * Don't tell them about moving exiting tasks or
4237 * kernel threads (both mm NULL), since they never
4238 * leave kernel.
4240 if (tsk->mm && printk_ratelimit())
4241 printk(KERN_INFO "process %d (%s) no "
4242 "longer affine to cpu%d\n",
4243 tsk->pid, tsk->comm, dead_cpu);
4245 __migrate_task(tsk, dead_cpu, dest_cpu);
4249 * While a dead CPU has no uninterruptible tasks queued at this point,
4250 * it might still have a nonzero ->nr_uninterruptible counter, because
4251 * for performance reasons the counter is not stricly tracking tasks to
4252 * their home CPUs. So we just add the counter to another CPU's counter,
4253 * to keep the global sum constant after CPU-down:
4255 static void migrate_nr_uninterruptible(runqueue_t *rq_src)
4257 runqueue_t *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
4258 unsigned long flags;
4260 local_irq_save(flags);
4261 double_rq_lock(rq_src, rq_dest);
4262 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
4263 rq_src->nr_uninterruptible = 0;
4264 double_rq_unlock(rq_src, rq_dest);
4265 local_irq_restore(flags);
4268 /* Run through task list and migrate tasks from the dead cpu. */
4269 static void migrate_live_tasks(int src_cpu)
4271 struct task_struct *tsk, *t;
4273 write_lock_irq(&tasklist_lock);
4275 do_each_thread(t, tsk) {
4276 if (tsk == current)
4277 continue;
4279 if (task_cpu(tsk) == src_cpu)
4280 move_task_off_dead_cpu(src_cpu, tsk);
4281 } while_each_thread(t, tsk);
4283 write_unlock_irq(&tasklist_lock);
4286 /* Schedules idle task to be the next runnable task on current CPU.
4287 * It does so by boosting its priority to highest possible and adding it to
4288 * the _front_ of runqueue. Used by CPU offline code.
4290 void sched_idle_next(void)
4292 int cpu = smp_processor_id();
4293 runqueue_t *rq = this_rq();
4294 struct task_struct *p = rq->idle;
4295 unsigned long flags;
4297 /* cpu has to be offline */
4298 BUG_ON(cpu_online(cpu));
4300 /* Strictly not necessary since rest of the CPUs are stopped by now
4301 * and interrupts disabled on current cpu.
4303 spin_lock_irqsave(&rq->lock, flags);
4305 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4306 /* Add idle task to _front_ of it's priority queue */
4307 __activate_idle_task(p, rq);
4309 spin_unlock_irqrestore(&rq->lock, flags);
4312 /* Ensures that the idle task is using init_mm right before its cpu goes
4313 * offline.
4315 void idle_task_exit(void)
4317 struct mm_struct *mm = current->active_mm;
4319 BUG_ON(cpu_online(smp_processor_id()));
4321 if (mm != &init_mm)
4322 switch_mm(mm, &init_mm, current);
4323 mmdrop(mm);
4326 static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
4328 struct runqueue *rq = cpu_rq(dead_cpu);
4330 /* Must be exiting, otherwise would be on tasklist. */
4331 BUG_ON(tsk->exit_state != EXIT_ZOMBIE && tsk->exit_state != EXIT_DEAD);
4333 /* Cannot have done final schedule yet: would have vanished. */
4334 BUG_ON(tsk->flags & PF_DEAD);
4336 get_task_struct(tsk);
4339 * Drop lock around migration; if someone else moves it,
4340 * that's OK. No task can be added to this CPU, so iteration is
4341 * fine.
4343 spin_unlock_irq(&rq->lock);
4344 move_task_off_dead_cpu(dead_cpu, tsk);
4345 spin_lock_irq(&rq->lock);
4347 put_task_struct(tsk);
4350 /* release_task() removes task from tasklist, so we won't find dead tasks. */
4351 static void migrate_dead_tasks(unsigned int dead_cpu)
4353 unsigned arr, i;
4354 struct runqueue *rq = cpu_rq(dead_cpu);
4356 for (arr = 0; arr < 2; arr++) {
4357 for (i = 0; i < MAX_PRIO; i++) {
4358 struct list_head *list = &rq->arrays[arr].queue[i];
4359 while (!list_empty(list))
4360 migrate_dead(dead_cpu,
4361 list_entry(list->next, task_t,
4362 run_list));
4366 #endif /* CONFIG_HOTPLUG_CPU */
4369 * migration_call - callback that gets triggered when a CPU is added.
4370 * Here we can start up the necessary migration thread for the new CPU.
4372 static int migration_call(struct notifier_block *nfb, unsigned long action,
4373 void *hcpu)
4375 int cpu = (long)hcpu;
4376 struct task_struct *p;
4377 struct runqueue *rq;
4378 unsigned long flags;
4380 switch (action) {
4381 case CPU_UP_PREPARE:
4382 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4383 if (IS_ERR(p))
4384 return NOTIFY_BAD;
4385 p->flags |= PF_NOFREEZE;
4386 kthread_bind(p, cpu);
4387 /* Must be high prio: stop_machine expects to yield to it. */
4388 rq = task_rq_lock(p, &flags);
4389 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4390 task_rq_unlock(rq, &flags);
4391 cpu_rq(cpu)->migration_thread = p;
4392 break;
4393 case CPU_ONLINE:
4394 /* Strictly unneccessary, as first user will wake it. */
4395 wake_up_process(cpu_rq(cpu)->migration_thread);
4396 break;
4397 #ifdef CONFIG_HOTPLUG_CPU
4398 case CPU_UP_CANCELED:
4399 /* Unbind it from offline cpu so it can run. Fall thru. */
4400 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
4401 kthread_stop(cpu_rq(cpu)->migration_thread);
4402 cpu_rq(cpu)->migration_thread = NULL;
4403 break;
4404 case CPU_DEAD:
4405 migrate_live_tasks(cpu);
4406 rq = cpu_rq(cpu);
4407 kthread_stop(rq->migration_thread);
4408 rq->migration_thread = NULL;
4409 /* Idle task back to normal (off runqueue, low prio) */
4410 rq = task_rq_lock(rq->idle, &flags);
4411 deactivate_task(rq->idle, rq);
4412 rq->idle->static_prio = MAX_PRIO;
4413 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4414 migrate_dead_tasks(cpu);
4415 task_rq_unlock(rq, &flags);
4416 migrate_nr_uninterruptible(rq);
4417 BUG_ON(rq->nr_running != 0);
4419 /* No need to migrate the tasks: it was best-effort if
4420 * they didn't do lock_cpu_hotplug(). Just wake up
4421 * the requestors. */
4422 spin_lock_irq(&rq->lock);
4423 while (!list_empty(&rq->migration_queue)) {
4424 migration_req_t *req;
4425 req = list_entry(rq->migration_queue.next,
4426 migration_req_t, list);
4427 BUG_ON(req->type != REQ_MOVE_TASK);
4428 list_del_init(&req->list);
4429 complete(&req->done);
4431 spin_unlock_irq(&rq->lock);
4432 break;
4433 #endif
4435 return NOTIFY_OK;
4438 /* Register at highest priority so that task migration (migrate_all_tasks)
4439 * happens before everything else.
4441 static struct notifier_block __devinitdata migration_notifier = {
4442 .notifier_call = migration_call,
4443 .priority = 10
4446 int __init migration_init(void)
4448 void *cpu = (void *)(long)smp_processor_id();
4449 /* Start one for boot CPU. */
4450 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4451 migration_call(&migration_notifier, CPU_ONLINE, cpu);
4452 register_cpu_notifier(&migration_notifier);
4453 return 0;
4455 #endif
4457 #ifdef CONFIG_SMP
4458 #define SCHED_DOMAIN_DEBUG
4459 #ifdef SCHED_DOMAIN_DEBUG
4460 static void sched_domain_debug(struct sched_domain *sd, int cpu)
4462 int level = 0;
4464 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
4466 do {
4467 int i;
4468 char str[NR_CPUS];
4469 struct sched_group *group = sd->groups;
4470 cpumask_t groupmask;
4472 cpumask_scnprintf(str, NR_CPUS, sd->span);
4473 cpus_clear(groupmask);
4475 printk(KERN_DEBUG);
4476 for (i = 0; i < level + 1; i++)
4477 printk(" ");
4478 printk("domain %d: ", level);
4480 if (!(sd->flags & SD_LOAD_BALANCE)) {
4481 printk("does not load-balance\n");
4482 if (sd->parent)
4483 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
4484 break;
4487 printk("span %s\n", str);
4489 if (!cpu_isset(cpu, sd->span))
4490 printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
4491 if (!cpu_isset(cpu, group->cpumask))
4492 printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
4494 printk(KERN_DEBUG);
4495 for (i = 0; i < level + 2; i++)
4496 printk(" ");
4497 printk("groups:");
4498 do {
4499 if (!group) {
4500 printk("\n");
4501 printk(KERN_ERR "ERROR: group is NULL\n");
4502 break;
4505 if (!group->cpu_power) {
4506 printk("\n");
4507 printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
4510 if (!cpus_weight(group->cpumask)) {
4511 printk("\n");
4512 printk(KERN_ERR "ERROR: empty group\n");
4515 if (cpus_intersects(groupmask, group->cpumask)) {
4516 printk("\n");
4517 printk(KERN_ERR "ERROR: repeated CPUs\n");
4520 cpus_or(groupmask, groupmask, group->cpumask);
4522 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
4523 printk(" %s", str);
4525 group = group->next;
4526 } while (group != sd->groups);
4527 printk("\n");
4529 if (!cpus_equal(sd->span, groupmask))
4530 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
4532 level++;
4533 sd = sd->parent;
4535 if (sd) {
4536 if (!cpus_subset(groupmask, sd->span))
4537 printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
4540 } while (sd);
4542 #else
4543 #define sched_domain_debug(sd, cpu) {}
4544 #endif
4547 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
4548 * hold the hotplug lock.
4550 void __devinit cpu_attach_domain(struct sched_domain *sd, int cpu)
4552 migration_req_t req;
4553 unsigned long flags;
4554 runqueue_t *rq = cpu_rq(cpu);
4555 int local = 1;
4557 sched_domain_debug(sd, cpu);
4559 spin_lock_irqsave(&rq->lock, flags);
4561 if (cpu == smp_processor_id() || !cpu_online(cpu)) {
4562 rq->sd = sd;
4563 } else {
4564 init_completion(&req.done);
4565 req.type = REQ_SET_DOMAIN;
4566 req.sd = sd;
4567 list_add(&req.list, &rq->migration_queue);
4568 local = 0;
4571 spin_unlock_irqrestore(&rq->lock, flags);
4573 if (!local) {
4574 wake_up_process(rq->migration_thread);
4575 wait_for_completion(&req.done);
4579 /* cpus with isolated domains */
4580 cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
4582 /* Setup the mask of cpus configured for isolated domains */
4583 static int __init isolated_cpu_setup(char *str)
4585 int ints[NR_CPUS], i;
4587 str = get_options(str, ARRAY_SIZE(ints), ints);
4588 cpus_clear(cpu_isolated_map);
4589 for (i = 1; i <= ints[0]; i++)
4590 if (ints[i] < NR_CPUS)
4591 cpu_set(ints[i], cpu_isolated_map);
4592 return 1;
4595 __setup ("isolcpus=", isolated_cpu_setup);
4598 * init_sched_build_groups takes an array of groups, the cpumask we wish
4599 * to span, and a pointer to a function which identifies what group a CPU
4600 * belongs to. The return value of group_fn must be a valid index into the
4601 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
4602 * keep track of groups covered with a cpumask_t).
4604 * init_sched_build_groups will build a circular linked list of the groups
4605 * covered by the given span, and will set each group's ->cpumask correctly,
4606 * and ->cpu_power to 0.
4608 void __devinit init_sched_build_groups(struct sched_group groups[],
4609 cpumask_t span, int (*group_fn)(int cpu))
4611 struct sched_group *first = NULL, *last = NULL;
4612 cpumask_t covered = CPU_MASK_NONE;
4613 int i;
4615 for_each_cpu_mask(i, span) {
4616 int group = group_fn(i);
4617 struct sched_group *sg = &groups[group];
4618 int j;
4620 if (cpu_isset(i, covered))
4621 continue;
4623 sg->cpumask = CPU_MASK_NONE;
4624 sg->cpu_power = 0;
4626 for_each_cpu_mask(j, span) {
4627 if (group_fn(j) != group)
4628 continue;
4630 cpu_set(j, covered);
4631 cpu_set(j, sg->cpumask);
4633 if (!first)
4634 first = sg;
4635 if (last)
4636 last->next = sg;
4637 last = sg;
4639 last->next = first;
4643 #ifdef ARCH_HAS_SCHED_DOMAIN
4644 extern void __devinit arch_init_sched_domains(void);
4645 extern void __devinit arch_destroy_sched_domains(void);
4646 #else
4647 #ifdef CONFIG_SCHED_SMT
4648 static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
4649 static struct sched_group sched_group_cpus[NR_CPUS];
4650 static int __devinit cpu_to_cpu_group(int cpu)
4652 return cpu;
4654 #endif
4656 static DEFINE_PER_CPU(struct sched_domain, phys_domains);
4657 static struct sched_group sched_group_phys[NR_CPUS];
4658 static int __devinit cpu_to_phys_group(int cpu)
4660 #ifdef CONFIG_SCHED_SMT
4661 return first_cpu(cpu_sibling_map[cpu]);
4662 #else
4663 return cpu;
4664 #endif
4667 #ifdef CONFIG_NUMA
4669 static DEFINE_PER_CPU(struct sched_domain, node_domains);
4670 static struct sched_group sched_group_nodes[MAX_NUMNODES];
4671 static int __devinit cpu_to_node_group(int cpu)
4673 return cpu_to_node(cpu);
4675 #endif
4677 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
4679 * The domains setup code relies on siblings not spanning
4680 * multiple nodes. Make sure the architecture has a proper
4681 * siblings map:
4683 static void check_sibling_maps(void)
4685 int i, j;
4687 for_each_online_cpu(i) {
4688 for_each_cpu_mask(j, cpu_sibling_map[i]) {
4689 if (cpu_to_node(i) != cpu_to_node(j)) {
4690 printk(KERN_INFO "warning: CPU %d siblings map "
4691 "to different node - isolating "
4692 "them.\n", i);
4693 cpu_sibling_map[i] = cpumask_of_cpu(i);
4694 break;
4699 #endif
4702 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
4704 static void __devinit arch_init_sched_domains(void)
4706 int i;
4707 cpumask_t cpu_default_map;
4709 #if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
4710 check_sibling_maps();
4711 #endif
4713 * Setup mask for cpus without special case scheduling requirements.
4714 * For now this just excludes isolated cpus, but could be used to
4715 * exclude other special cases in the future.
4717 cpus_complement(cpu_default_map, cpu_isolated_map);
4718 cpus_and(cpu_default_map, cpu_default_map, cpu_online_map);
4721 * Set up domains. Isolated domains just stay on the dummy domain.
4723 for_each_cpu_mask(i, cpu_default_map) {
4724 int group;
4725 struct sched_domain *sd = NULL, *p;
4726 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
4728 cpus_and(nodemask, nodemask, cpu_default_map);
4730 #ifdef CONFIG_NUMA
4731 sd = &per_cpu(node_domains, i);
4732 group = cpu_to_node_group(i);
4733 *sd = SD_NODE_INIT;
4734 sd->span = cpu_default_map;
4735 sd->groups = &sched_group_nodes[group];
4736 #endif
4738 p = sd;
4739 sd = &per_cpu(phys_domains, i);
4740 group = cpu_to_phys_group(i);
4741 *sd = SD_CPU_INIT;
4742 sd->span = nodemask;
4743 sd->parent = p;
4744 sd->groups = &sched_group_phys[group];
4746 #ifdef CONFIG_SCHED_SMT
4747 p = sd;
4748 sd = &per_cpu(cpu_domains, i);
4749 group = cpu_to_cpu_group(i);
4750 *sd = SD_SIBLING_INIT;
4751 sd->span = cpu_sibling_map[i];
4752 cpus_and(sd->span, sd->span, cpu_default_map);
4753 sd->parent = p;
4754 sd->groups = &sched_group_cpus[group];
4755 #endif
4758 #ifdef CONFIG_SCHED_SMT
4759 /* Set up CPU (sibling) groups */
4760 for_each_online_cpu(i) {
4761 cpumask_t this_sibling_map = cpu_sibling_map[i];
4762 cpus_and(this_sibling_map, this_sibling_map, cpu_default_map);
4763 if (i != first_cpu(this_sibling_map))
4764 continue;
4766 init_sched_build_groups(sched_group_cpus, this_sibling_map,
4767 &cpu_to_cpu_group);
4769 #endif
4771 /* Set up physical groups */
4772 for (i = 0; i < MAX_NUMNODES; i++) {
4773 cpumask_t nodemask = node_to_cpumask(i);
4775 cpus_and(nodemask, nodemask, cpu_default_map);
4776 if (cpus_empty(nodemask))
4777 continue;
4779 init_sched_build_groups(sched_group_phys, nodemask,
4780 &cpu_to_phys_group);
4783 #ifdef CONFIG_NUMA
4784 /* Set up node groups */
4785 init_sched_build_groups(sched_group_nodes, cpu_default_map,
4786 &cpu_to_node_group);
4787 #endif
4789 /* Calculate CPU power for physical packages and nodes */
4790 for_each_cpu_mask(i, cpu_default_map) {
4791 int power;
4792 struct sched_domain *sd;
4793 #ifdef CONFIG_SCHED_SMT
4794 sd = &per_cpu(cpu_domains, i);
4795 power = SCHED_LOAD_SCALE;
4796 sd->groups->cpu_power = power;
4797 #endif
4799 sd = &per_cpu(phys_domains, i);
4800 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
4801 (cpus_weight(sd->groups->cpumask)-1) / 10;
4802 sd->groups->cpu_power = power;
4804 #ifdef CONFIG_NUMA
4805 if (i == first_cpu(sd->groups->cpumask)) {
4806 /* Only add "power" once for each physical package. */
4807 sd = &per_cpu(node_domains, i);
4808 sd->groups->cpu_power += power;
4810 #endif
4813 /* Attach the domains */
4814 for_each_online_cpu(i) {
4815 struct sched_domain *sd;
4816 #ifdef CONFIG_SCHED_SMT
4817 sd = &per_cpu(cpu_domains, i);
4818 #else
4819 sd = &per_cpu(phys_domains, i);
4820 #endif
4821 cpu_attach_domain(sd, i);
4825 #ifdef CONFIG_HOTPLUG_CPU
4826 static void __devinit arch_destroy_sched_domains(void)
4828 /* Do nothing: everything is statically allocated. */
4830 #endif
4832 #endif /* ARCH_HAS_SCHED_DOMAIN */
4835 * Initial dummy domain for early boot and for hotplug cpu. Being static,
4836 * it is initialized to zero, so all balancing flags are cleared which is
4837 * what we want.
4839 static struct sched_domain sched_domain_dummy;
4841 #ifdef CONFIG_HOTPLUG_CPU
4843 * Force a reinitialization of the sched domains hierarchy. The domains
4844 * and groups cannot be updated in place without racing with the balancing
4845 * code, so we temporarily attach all running cpus to a "dummy" domain
4846 * which will prevent rebalancing while the sched domains are recalculated.
4848 static int update_sched_domains(struct notifier_block *nfb,
4849 unsigned long action, void *hcpu)
4851 int i;
4853 switch (action) {
4854 case CPU_UP_PREPARE:
4855 case CPU_DOWN_PREPARE:
4856 for_each_online_cpu(i)
4857 cpu_attach_domain(&sched_domain_dummy, i);
4858 arch_destroy_sched_domains();
4859 return NOTIFY_OK;
4861 case CPU_UP_CANCELED:
4862 case CPU_DOWN_FAILED:
4863 case CPU_ONLINE:
4864 case CPU_DEAD:
4866 * Fall through and re-initialise the domains.
4868 break;
4869 default:
4870 return NOTIFY_DONE;
4873 /* The hotplug lock is already held by cpu_up/cpu_down */
4874 arch_init_sched_domains();
4876 return NOTIFY_OK;
4878 #endif
4880 void __init sched_init_smp(void)
4882 lock_cpu_hotplug();
4883 arch_init_sched_domains();
4884 unlock_cpu_hotplug();
4885 /* XXX: Theoretical race here - CPU may be hotplugged now */
4886 hotcpu_notifier(update_sched_domains, 0);
4888 #else
4889 void __init sched_init_smp(void)
4892 #endif /* CONFIG_SMP */
4894 int in_sched_functions(unsigned long addr)
4896 /* Linker adds these: start and end of __sched functions */
4897 extern char __sched_text_start[], __sched_text_end[];
4898 return in_lock_functions(addr) ||
4899 (addr >= (unsigned long)__sched_text_start
4900 && addr < (unsigned long)__sched_text_end);
4903 void __init sched_init(void)
4905 runqueue_t *rq;
4906 int i, j, k;
4908 for (i = 0; i < NR_CPUS; i++) {
4909 prio_array_t *array;
4911 rq = cpu_rq(i);
4912 spin_lock_init(&rq->lock);
4913 rq->active = rq->arrays;
4914 rq->expired = rq->arrays + 1;
4915 rq->best_expired_prio = MAX_PRIO;
4917 #ifdef CONFIG_SMP
4918 rq->sd = &sched_domain_dummy;
4919 rq->cpu_load = 0;
4920 rq->active_balance = 0;
4921 rq->push_cpu = 0;
4922 rq->migration_thread = NULL;
4923 INIT_LIST_HEAD(&rq->migration_queue);
4924 #endif
4925 atomic_set(&rq->nr_iowait, 0);
4927 for (j = 0; j < 2; j++) {
4928 array = rq->arrays + j;
4929 for (k = 0; k < MAX_PRIO; k++) {
4930 INIT_LIST_HEAD(array->queue + k);
4931 __clear_bit(k, array->bitmap);
4933 // delimiter for bitsearch
4934 __set_bit(MAX_PRIO, array->bitmap);
4939 * The boot idle thread does lazy MMU switching as well:
4941 atomic_inc(&init_mm.mm_count);
4942 enter_lazy_tlb(&init_mm, current);
4945 * Make us the idle thread. Technically, schedule() should not be
4946 * called from this thread, however somewhere below it might be,
4947 * but because we are the idle thread, we just pick up running again
4948 * when this runqueue becomes "idle".
4950 init_idle(current, smp_processor_id());
4953 #ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
4954 void __might_sleep(char *file, int line)
4956 #if defined(in_atomic)
4957 static unsigned long prev_jiffy; /* ratelimiting */
4959 if ((in_atomic() || irqs_disabled()) &&
4960 system_state == SYSTEM_RUNNING && !oops_in_progress) {
4961 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
4962 return;
4963 prev_jiffy = jiffies;
4964 printk(KERN_ERR "Debug: sleeping function called from invalid"
4965 " context at %s:%d\n", file, line);
4966 printk("in_atomic():%d, irqs_disabled():%d\n",
4967 in_atomic(), irqs_disabled());
4968 dump_stack();
4970 #endif
4972 EXPORT_SYMBOL(__might_sleep);
4973 #endif
4975 #ifdef CONFIG_MAGIC_SYSRQ
4976 void normalize_rt_tasks(void)
4978 struct task_struct *p;
4979 prio_array_t *array;
4980 unsigned long flags;
4981 runqueue_t *rq;
4983 read_lock_irq(&tasklist_lock);
4984 for_each_process (p) {
4985 if (!rt_task(p))
4986 continue;
4988 rq = task_rq_lock(p, &flags);
4990 array = p->array;
4991 if (array)
4992 deactivate_task(p, task_rq(p));
4993 __setscheduler(p, SCHED_NORMAL, 0);
4994 if (array) {
4995 __activate_task(p, task_rq(p));
4996 resched_task(rq->curr);
4999 task_rq_unlock(rq, &flags);
5001 read_unlock_irq(&tasklist_lock);
5004 #endif /* CONFIG_MAGIC_SYSRQ */