[PATCH] sched: balance on fork
[deliverable/linux.git] / kernel / sched.c
CommitLineData
1da177e4
LT
1/*
2 * kernel/sched.c
3 *
4 * Kernel scheduler and related syscalls
5 *
6 * Copyright (C) 1991-2002 Linus Torvalds
7 *
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
19 */
20
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>
51
52#include <asm/unistd.h>
53
54/*
55 * Convert user-nice values [ -20 ... 0 ... 19 ]
56 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
57 * and back.
58 */
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)
62
63/*
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.
67 */
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))
71
72/*
73 * Some helpers for converting nanosecond timing to jiffy resolution
74 */
75#define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
76#define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
77
78/*
79 * These are the 'tuning knobs' of the scheduler:
80 *
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.
84 */
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))
97
98/*
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.)
103 *
104 * This part scales the interactivity limit depending on niceness.
105 *
106 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
107 * Here are a few examples of different nice levels:
108 *
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]
114 *
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.)
118 *
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.
124 */
125
126#define CURRENT_BONUS(p) \
127 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
128 MAX_SLEEP_AVG)
129
130#define GRANULARITY (10 * HZ / 1000 ? : 1)
131
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
140
141#define SCALE(v1,v1_max,v2_max) \
142 (v1) * (v2_max) / (v1_max)
143
144#define DELTA(p) \
145 (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
146
147#define TASK_INTERACTIVE(p) \
148 ((p)->prio <= (p)->static_prio - DELTA(p))
149
150#define INTERACTIVE_SLEEP(p) \
151 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
152 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
153
154#define TASK_PREEMPTS_CURR(p, rq) \
155 ((p)->prio < (rq)->curr->prio)
156
157/*
158 * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
159 * to time slice values: [800ms ... 100ms ... 5ms]
160 *
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.
164 */
165
166#define SCALE_PRIO(x, prio) \
167 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO/2), MIN_TIMESLICE)
168
169static inline unsigned int task_timeslice(task_t *p)
170{
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);
175}
176#define task_hot(p, now, sd) ((long long) ((now) - (p)->last_ran) \
177 < (long long) (sd)->cache_hot_time)
178
179/*
180 * These are the runqueue data structures:
181 */
182
183#define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
184
185typedef struct runqueue runqueue_t;
186
187struct prio_array {
188 unsigned int nr_active;
189 unsigned long bitmap[BITMAP_SIZE];
190 struct list_head queue[MAX_PRIO];
191};
192
193/*
194 * This is the main, per-CPU runqueue data structure.
195 *
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.
199 */
200struct runqueue {
201 spinlock_t lock;
202
203 /*
204 * nr_running and cpu_load should be in the same cacheline because
205 * remote CPUs use both these fields when doing load calculation.
206 */
207 unsigned long nr_running;
208#ifdef CONFIG_SMP
7897986b 209 unsigned long cpu_load[3];
1da177e4
LT
210#endif
211 unsigned long long nr_switches;
212
213 /*
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:
218 */
219 unsigned long nr_uninterruptible;
220
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;
228
229#ifdef CONFIG_SMP
230 struct sched_domain *sd;
231
232 /* For active balancing */
233 int active_balance;
234 int push_cpu;
235
236 task_t *migration_thread;
237 struct list_head migration_queue;
238#endif
239
240#ifdef CONFIG_SCHEDSTATS
241 /* latency stats */
242 struct sched_info rq_sched_info;
243
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;
249
250 /* schedule() stats */
251 unsigned long sched_switch;
252 unsigned long sched_cnt;
253 unsigned long sched_goidle;
254
255 /* try_to_wake_up() stats */
256 unsigned long ttwu_cnt;
257 unsigned long ttwu_local;
258#endif
259};
260
261static DEFINE_PER_CPU(struct runqueue, runqueues);
262
263#define for_each_domain(cpu, domain) \
264 for (domain = cpu_rq(cpu)->sd; domain; domain = domain->parent)
265
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)
270
271/*
272 * Default context-switch locking:
273 */
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
279
280/*
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.
284 */
285static inline runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
286 __acquires(rq->lock)
287{
288 struct runqueue *rq;
289
290repeat_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;
297 }
298 return rq;
299}
300
301static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
302 __releases(rq->lock)
303{
304 spin_unlock_irqrestore(&rq->lock, *flags);
305}
306
307#ifdef CONFIG_SCHEDSTATS
308/*
309 * bump this up when changing the output format or the meaning of an existing
310 * format, so that tools can adapt (or abort)
311 */
312#define SCHEDSTAT_VERSION 11
313
314static int show_schedstat(struct seq_file *seq, void *v)
315{
316 int cpu;
317
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
326
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);
336
337 seq_printf(seq, "\n");
338
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];
344
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]);
358 }
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);
363 }
364#endif
365 }
366 return 0;
367}
368
369static int schedstat_open(struct inode *inode, struct file *file)
370{
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;
375
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;
386}
387
388struct file_operations proc_schedstat_operations = {
389 .open = schedstat_open,
390 .read = seq_read,
391 .llseek = seq_lseek,
392 .release = single_release,
393};
394
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
401
402/*
403 * rq_lock - lock a given runqueue and disable interrupts.
404 */
405static inline runqueue_t *this_rq_lock(void)
406 __acquires(rq->lock)
407{
408 runqueue_t *rq;
409
410 local_irq_disable();
411 rq = this_rq();
412 spin_lock(&rq->lock);
413
414 return rq;
415}
416
1da177e4
LT
417#ifdef CONFIG_SCHEDSTATS
418/*
419 * Called when a process is dequeued from the active array and given
420 * the cpu. We should note that with the exception of interactive
421 * tasks, the expired queue will become the active queue after the active
422 * queue is empty, without explicitly dequeuing and requeuing tasks in the
423 * expired queue. (Interactive tasks may be requeued directly to the
424 * active queue, thus delaying tasks in the expired queue from running;
425 * see scheduler_tick()).
426 *
427 * This function is only called from sched_info_arrive(), rather than
428 * dequeue_task(). Even though a task may be queued and dequeued multiple
429 * times as it is shuffled about, we're really interested in knowing how
430 * long it was from the *first* time it was queued to the time that it
431 * finally hit a cpu.
432 */
433static inline void sched_info_dequeued(task_t *t)
434{
435 t->sched_info.last_queued = 0;
436}
437
438/*
439 * Called when a task finally hits the cpu. We can now calculate how
440 * long it was waiting to run. We also note when it began so that we
441 * can keep stats on how long its timeslice is.
442 */
443static inline void sched_info_arrive(task_t *t)
444{
445 unsigned long now = jiffies, diff = 0;
446 struct runqueue *rq = task_rq(t);
447
448 if (t->sched_info.last_queued)
449 diff = now - t->sched_info.last_queued;
450 sched_info_dequeued(t);
451 t->sched_info.run_delay += diff;
452 t->sched_info.last_arrival = now;
453 t->sched_info.pcnt++;
454
455 if (!rq)
456 return;
457
458 rq->rq_sched_info.run_delay += diff;
459 rq->rq_sched_info.pcnt++;
460}
461
462/*
463 * Called when a process is queued into either the active or expired
464 * array. The time is noted and later used to determine how long we
465 * had to wait for us to reach the cpu. Since the expired queue will
466 * become the active queue after active queue is empty, without dequeuing
467 * and requeuing any tasks, we are interested in queuing to either. It
468 * is unusual but not impossible for tasks to be dequeued and immediately
469 * requeued in the same or another array: this can happen in sched_yield(),
470 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
471 * to runqueue.
472 *
473 * This function is only called from enqueue_task(), but also only updates
474 * the timestamp if it is already not set. It's assumed that
475 * sched_info_dequeued() will clear that stamp when appropriate.
476 */
477static inline void sched_info_queued(task_t *t)
478{
479 if (!t->sched_info.last_queued)
480 t->sched_info.last_queued = jiffies;
481}
482
483/*
484 * Called when a process ceases being the active-running process, either
485 * voluntarily or involuntarily. Now we can calculate how long we ran.
486 */
487static inline void sched_info_depart(task_t *t)
488{
489 struct runqueue *rq = task_rq(t);
490 unsigned long diff = jiffies - t->sched_info.last_arrival;
491
492 t->sched_info.cpu_time += diff;
493
494 if (rq)
495 rq->rq_sched_info.cpu_time += diff;
496}
497
498/*
499 * Called when tasks are switched involuntarily due, typically, to expiring
500 * their time slice. (This may also be called when switching to or from
501 * the idle task.) We are only called when prev != next.
502 */
503static inline void sched_info_switch(task_t *prev, task_t *next)
504{
505 struct runqueue *rq = task_rq(prev);
506
507 /*
508 * prev now departs the cpu. It's not interesting to record
509 * stats about how efficient we were at scheduling the idle
510 * process, however.
511 */
512 if (prev != rq->idle)
513 sched_info_depart(prev);
514
515 if (next != rq->idle)
516 sched_info_arrive(next);
517}
518#else
519#define sched_info_queued(t) do { } while (0)
520#define sched_info_switch(t, next) do { } while (0)
521#endif /* CONFIG_SCHEDSTATS */
522
523/*
524 * Adding/removing a task to/from a priority array:
525 */
526static void dequeue_task(struct task_struct *p, prio_array_t *array)
527{
528 array->nr_active--;
529 list_del(&p->run_list);
530 if (list_empty(array->queue + p->prio))
531 __clear_bit(p->prio, array->bitmap);
532}
533
534static void enqueue_task(struct task_struct *p, prio_array_t *array)
535{
536 sched_info_queued(p);
537 list_add_tail(&p->run_list, array->queue + p->prio);
538 __set_bit(p->prio, array->bitmap);
539 array->nr_active++;
540 p->array = array;
541}
542
543/*
544 * Put task to the end of the run list without the overhead of dequeue
545 * followed by enqueue.
546 */
547static void requeue_task(struct task_struct *p, prio_array_t *array)
548{
549 list_move_tail(&p->run_list, array->queue + p->prio);
550}
551
552static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
553{
554 list_add(&p->run_list, array->queue + p->prio);
555 __set_bit(p->prio, array->bitmap);
556 array->nr_active++;
557 p->array = array;
558}
559
560/*
561 * effective_prio - return the priority that is based on the static
562 * priority but is modified by bonuses/penalties.
563 *
564 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
565 * into the -5 ... 0 ... +5 bonus/penalty range.
566 *
567 * We use 25% of the full 0...39 priority range so that:
568 *
569 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
570 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
571 *
572 * Both properties are important to certain workloads.
573 */
574static int effective_prio(task_t *p)
575{
576 int bonus, prio;
577
578 if (rt_task(p))
579 return p->prio;
580
581 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
582
583 prio = p->static_prio - bonus;
584 if (prio < MAX_RT_PRIO)
585 prio = MAX_RT_PRIO;
586 if (prio > MAX_PRIO-1)
587 prio = MAX_PRIO-1;
588 return prio;
589}
590
591/*
592 * __activate_task - move a task to the runqueue.
593 */
594static inline void __activate_task(task_t *p, runqueue_t *rq)
595{
596 enqueue_task(p, rq->active);
597 rq->nr_running++;
598}
599
600/*
601 * __activate_idle_task - move idle task to the _front_ of runqueue.
602 */
603static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
604{
605 enqueue_task_head(p, rq->active);
606 rq->nr_running++;
607}
608
609static void recalc_task_prio(task_t *p, unsigned long long now)
610{
611 /* Caller must always ensure 'now >= p->timestamp' */
612 unsigned long long __sleep_time = now - p->timestamp;
613 unsigned long sleep_time;
614
615 if (__sleep_time > NS_MAX_SLEEP_AVG)
616 sleep_time = NS_MAX_SLEEP_AVG;
617 else
618 sleep_time = (unsigned long)__sleep_time;
619
620 if (likely(sleep_time > 0)) {
621 /*
622 * User tasks that sleep a long time are categorised as
623 * idle and will get just interactive status to stay active &
624 * prevent them suddenly becoming cpu hogs and starving
625 * other processes.
626 */
627 if (p->mm && p->activated != -1 &&
628 sleep_time > INTERACTIVE_SLEEP(p)) {
629 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
630 DEF_TIMESLICE);
631 } else {
632 /*
633 * The lower the sleep avg a task has the more
634 * rapidly it will rise with sleep time.
635 */
636 sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
637
638 /*
639 * Tasks waking from uninterruptible sleep are
640 * limited in their sleep_avg rise as they
641 * are likely to be waiting on I/O
642 */
643 if (p->activated == -1 && p->mm) {
644 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
645 sleep_time = 0;
646 else if (p->sleep_avg + sleep_time >=
647 INTERACTIVE_SLEEP(p)) {
648 p->sleep_avg = INTERACTIVE_SLEEP(p);
649 sleep_time = 0;
650 }
651 }
652
653 /*
654 * This code gives a bonus to interactive tasks.
655 *
656 * The boost works by updating the 'average sleep time'
657 * value here, based on ->timestamp. The more time a
658 * task spends sleeping, the higher the average gets -
659 * and the higher the priority boost gets as well.
660 */
661 p->sleep_avg += sleep_time;
662
663 if (p->sleep_avg > NS_MAX_SLEEP_AVG)
664 p->sleep_avg = NS_MAX_SLEEP_AVG;
665 }
666 }
667
668 p->prio = effective_prio(p);
669}
670
671/*
672 * activate_task - move a task to the runqueue and do priority recalculation
673 *
674 * Update all the scheduling statistics stuff. (sleep average
675 * calculation, priority modifiers, etc.)
676 */
677static void activate_task(task_t *p, runqueue_t *rq, int local)
678{
679 unsigned long long now;
680
681 now = sched_clock();
682#ifdef CONFIG_SMP
683 if (!local) {
684 /* Compensate for drifting sched_clock */
685 runqueue_t *this_rq = this_rq();
686 now = (now - this_rq->timestamp_last_tick)
687 + rq->timestamp_last_tick;
688 }
689#endif
690
691 recalc_task_prio(p, now);
692
693 /*
694 * This checks to make sure it's not an uninterruptible task
695 * that is now waking up.
696 */
697 if (!p->activated) {
698 /*
699 * Tasks which were woken up by interrupts (ie. hw events)
700 * are most likely of interactive nature. So we give them
701 * the credit of extending their sleep time to the period
702 * of time they spend on the runqueue, waiting for execution
703 * on a CPU, first time around:
704 */
705 if (in_interrupt())
706 p->activated = 2;
707 else {
708 /*
709 * Normal first-time wakeups get a credit too for
710 * on-runqueue time, but it will be weighted down:
711 */
712 p->activated = 1;
713 }
714 }
715 p->timestamp = now;
716
717 __activate_task(p, rq);
718}
719
720/*
721 * deactivate_task - remove a task from the runqueue.
722 */
723static void deactivate_task(struct task_struct *p, runqueue_t *rq)
724{
725 rq->nr_running--;
726 dequeue_task(p, p->array);
727 p->array = NULL;
728}
729
730/*
731 * resched_task - mark a task 'to be rescheduled now'.
732 *
733 * On UP this means the setting of the need_resched flag, on SMP it
734 * might also involve a cross-CPU call to trigger the scheduler on
735 * the target CPU.
736 */
737#ifdef CONFIG_SMP
738static void resched_task(task_t *p)
739{
740 int need_resched, nrpolling;
741
742 assert_spin_locked(&task_rq(p)->lock);
743
744 /* minimise the chance of sending an interrupt to poll_idle() */
745 nrpolling = test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
746 need_resched = test_and_set_tsk_thread_flag(p,TIF_NEED_RESCHED);
747 nrpolling |= test_tsk_thread_flag(p,TIF_POLLING_NRFLAG);
748
749 if (!need_resched && !nrpolling && (task_cpu(p) != smp_processor_id()))
750 smp_send_reschedule(task_cpu(p));
751}
752#else
753static inline void resched_task(task_t *p)
754{
755 set_tsk_need_resched(p);
756}
757#endif
758
759/**
760 * task_curr - is this task currently executing on a CPU?
761 * @p: the task in question.
762 */
763inline int task_curr(const task_t *p)
764{
765 return cpu_curr(task_cpu(p)) == p;
766}
767
768#ifdef CONFIG_SMP
769enum request_type {
770 REQ_MOVE_TASK,
771 REQ_SET_DOMAIN,
772};
773
774typedef struct {
775 struct list_head list;
776 enum request_type type;
777
778 /* For REQ_MOVE_TASK */
779 task_t *task;
780 int dest_cpu;
781
782 /* For REQ_SET_DOMAIN */
783 struct sched_domain *sd;
784
785 struct completion done;
786} migration_req_t;
787
788/*
789 * The task's runqueue lock must be held.
790 * Returns true if you have to wait for migration thread.
791 */
792static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
793{
794 runqueue_t *rq = task_rq(p);
795
796 /*
797 * If the task is not on a runqueue (and not running), then
798 * it is sufficient to simply update the task's cpu field.
799 */
800 if (!p->array && !task_running(rq, p)) {
801 set_task_cpu(p, dest_cpu);
802 return 0;
803 }
804
805 init_completion(&req->done);
806 req->type = REQ_MOVE_TASK;
807 req->task = p;
808 req->dest_cpu = dest_cpu;
809 list_add(&req->list, &rq->migration_queue);
810 return 1;
811}
812
813/*
814 * wait_task_inactive - wait for a thread to unschedule.
815 *
816 * The caller must ensure that the task *will* unschedule sometime soon,
817 * else this function might spin for a *long* time. This function can't
818 * be called with interrupts off, or it may introduce deadlock with
819 * smp_call_function() if an IPI is sent by the same process we are
820 * waiting to become inactive.
821 */
822void wait_task_inactive(task_t * p)
823{
824 unsigned long flags;
825 runqueue_t *rq;
826 int preempted;
827
828repeat:
829 rq = task_rq_lock(p, &flags);
830 /* Must be off runqueue entirely, not preempted. */
831 if (unlikely(p->array || task_running(rq, p))) {
832 /* If it's preempted, we yield. It could be a while. */
833 preempted = !task_running(rq, p);
834 task_rq_unlock(rq, &flags);
835 cpu_relax();
836 if (preempted)
837 yield();
838 goto repeat;
839 }
840 task_rq_unlock(rq, &flags);
841}
842
843/***
844 * kick_process - kick a running thread to enter/exit the kernel
845 * @p: the to-be-kicked thread
846 *
847 * Cause a process which is running on another CPU to enter
848 * kernel-mode, without any delay. (to get signals handled.)
849 *
850 * NOTE: this function doesnt have to take the runqueue lock,
851 * because all it wants to ensure is that the remote task enters
852 * the kernel. If the IPI races and the task has been migrated
853 * to another CPU then no harm is done and the purpose has been
854 * achieved as well.
855 */
856void kick_process(task_t *p)
857{
858 int cpu;
859
860 preempt_disable();
861 cpu = task_cpu(p);
862 if ((cpu != smp_processor_id()) && task_curr(p))
863 smp_send_reschedule(cpu);
864 preempt_enable();
865}
866
867/*
868 * Return a low guess at the load of a migration-source cpu.
869 *
870 * We want to under-estimate the load of migration sources, to
871 * balance conservatively.
872 */
7897986b 873static inline unsigned long source_load(int cpu, int type)
1da177e4
LT
874{
875 runqueue_t *rq = cpu_rq(cpu);
876 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
7897986b
NP
877 if (type == 0)
878 return load_now;
1da177e4 879
7897986b 880 return min(rq->cpu_load[type-1], load_now);
1da177e4
LT
881}
882
883/*
884 * Return a high guess at the load of a migration-target cpu
885 */
7897986b 886static inline unsigned long target_load(int cpu, int type)
1da177e4
LT
887{
888 runqueue_t *rq = cpu_rq(cpu);
889 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
7897986b
NP
890 if (type == 0)
891 return load_now;
1da177e4 892
7897986b 893 return max(rq->cpu_load[type-1], load_now);
1da177e4
LT
894}
895
147cbb4b
NP
896/*
897 * find_idlest_group finds and returns the least busy CPU group within the
898 * domain.
899 */
900static struct sched_group *
901find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
902{
903 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
904 unsigned long min_load = ULONG_MAX, this_load = 0;
905 int load_idx = sd->forkexec_idx;
906 int imbalance = 100 + (sd->imbalance_pct-100)/2;
907
908 do {
909 unsigned long load, avg_load;
910 int local_group;
911 int i;
912
913 local_group = cpu_isset(this_cpu, group->cpumask);
914 /* XXX: put a cpus allowed check */
915
916 /* Tally up the load of all CPUs in the group */
917 avg_load = 0;
918
919 for_each_cpu_mask(i, group->cpumask) {
920 /* Bias balancing toward cpus of our domain */
921 if (local_group)
922 load = source_load(i, load_idx);
923 else
924 load = target_load(i, load_idx);
925
926 avg_load += load;
927 }
928
929 /* Adjust by relative CPU power of the group */
930 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
931
932 if (local_group) {
933 this_load = avg_load;
934 this = group;
935 } else if (avg_load < min_load) {
936 min_load = avg_load;
937 idlest = group;
938 }
939 group = group->next;
940 } while (group != sd->groups);
941
942 if (!idlest || 100*this_load < imbalance*min_load)
943 return NULL;
944 return idlest;
945}
946
947/*
948 * find_idlest_queue - find the idlest runqueue among the cpus in group.
949 */
950static int find_idlest_cpu(struct sched_group *group, int this_cpu)
951{
952 unsigned long load, min_load = ULONG_MAX;
953 int idlest = -1;
954 int i;
955
956 for_each_cpu_mask(i, group->cpumask) {
957 load = source_load(i, 0);
958
959 if (load < min_load || (load == min_load && i == this_cpu)) {
960 min_load = load;
961 idlest = i;
962 }
963 }
964
965 return idlest;
966}
967
968
1da177e4
LT
969#endif
970
971/*
972 * wake_idle() will wake a task on an idle cpu if task->cpu is
973 * not idle and an idle cpu is available. The span of cpus to
974 * search starts with cpus closest then further out as needed,
975 * so we always favor a closer, idle cpu.
976 *
977 * Returns the CPU we should wake onto.
978 */
979#if defined(ARCH_HAS_SCHED_WAKE_IDLE)
980static int wake_idle(int cpu, task_t *p)
981{
982 cpumask_t tmp;
983 struct sched_domain *sd;
984 int i;
985
986 if (idle_cpu(cpu))
987 return cpu;
988
989 for_each_domain(cpu, sd) {
990 if (sd->flags & SD_WAKE_IDLE) {
e0f364f4 991 cpus_and(tmp, sd->span, p->cpus_allowed);
1da177e4
LT
992 for_each_cpu_mask(i, tmp) {
993 if (idle_cpu(i))
994 return i;
995 }
996 }
e0f364f4
NP
997 else
998 break;
1da177e4
LT
999 }
1000 return cpu;
1001}
1002#else
1003static inline int wake_idle(int cpu, task_t *p)
1004{
1005 return cpu;
1006}
1007#endif
1008
1009/***
1010 * try_to_wake_up - wake up a thread
1011 * @p: the to-be-woken-up thread
1012 * @state: the mask of task states that can be woken
1013 * @sync: do a synchronous wakeup?
1014 *
1015 * Put it on the run-queue if it's not already there. The "current"
1016 * thread is always on the run-queue (except when the actual
1017 * re-schedule is in progress), and as such you're allowed to do
1018 * the simpler "current->state = TASK_RUNNING" to mark yourself
1019 * runnable without the overhead of this.
1020 *
1021 * returns failure only if the task is already active.
1022 */
1023static int try_to_wake_up(task_t * p, unsigned int state, int sync)
1024{
1025 int cpu, this_cpu, success = 0;
1026 unsigned long flags;
1027 long old_state;
1028 runqueue_t *rq;
1029#ifdef CONFIG_SMP
1030 unsigned long load, this_load;
7897986b 1031 struct sched_domain *sd, *this_sd = NULL;
1da177e4
LT
1032 int new_cpu;
1033#endif
1034
1035 rq = task_rq_lock(p, &flags);
1036 old_state = p->state;
1037 if (!(old_state & state))
1038 goto out;
1039
1040 if (p->array)
1041 goto out_running;
1042
1043 cpu = task_cpu(p);
1044 this_cpu = smp_processor_id();
1045
1046#ifdef CONFIG_SMP
1047 if (unlikely(task_running(rq, p)))
1048 goto out_activate;
1049
7897986b
NP
1050 new_cpu = cpu;
1051
1da177e4
LT
1052 schedstat_inc(rq, ttwu_cnt);
1053 if (cpu == this_cpu) {
1054 schedstat_inc(rq, ttwu_local);
7897986b
NP
1055 goto out_set_cpu;
1056 }
1057
1058 for_each_domain(this_cpu, sd) {
1059 if (cpu_isset(cpu, sd->span)) {
1060 schedstat_inc(sd, ttwu_wake_remote);
1061 this_sd = sd;
1062 break;
1da177e4
LT
1063 }
1064 }
1da177e4 1065
7897986b 1066 if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1da177e4
LT
1067 goto out_set_cpu;
1068
1da177e4 1069 /*
7897986b 1070 * Check for affine wakeup and passive balancing possibilities.
1da177e4 1071 */
7897986b
NP
1072 if (this_sd) {
1073 int idx = this_sd->wake_idx;
1074 unsigned int imbalance;
1da177e4 1075
a3f21bce
NP
1076 imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
1077
7897986b
NP
1078 load = source_load(cpu, idx);
1079 this_load = target_load(this_cpu, idx);
1da177e4 1080
7897986b
NP
1081 new_cpu = this_cpu; /* Wake to this CPU if we can */
1082
a3f21bce
NP
1083 if (this_sd->flags & SD_WAKE_AFFINE) {
1084 unsigned long tl = this_load;
1da177e4 1085 /*
a3f21bce
NP
1086 * If sync wakeup then subtract the (maximum possible)
1087 * effect of the currently running task from the load
1088 * of the current CPU:
1da177e4 1089 */
a3f21bce
NP
1090 if (sync)
1091 tl -= SCHED_LOAD_SCALE;
1092
1093 if ((tl <= load &&
1094 tl + target_load(cpu, idx) <= SCHED_LOAD_SCALE) ||
1095 100*(tl + SCHED_LOAD_SCALE) <= imbalance*load) {
1096 /*
1097 * This domain has SD_WAKE_AFFINE and
1098 * p is cache cold in this domain, and
1099 * there is no bad imbalance.
1100 */
1101 schedstat_inc(this_sd, ttwu_move_affine);
1102 goto out_set_cpu;
1103 }
1104 }
1105
1106 /*
1107 * Start passive balancing when half the imbalance_pct
1108 * limit is reached.
1109 */
1110 if (this_sd->flags & SD_WAKE_BALANCE) {
1111 if (imbalance*this_load <= 100*load) {
1112 schedstat_inc(this_sd, ttwu_move_balance);
1113 goto out_set_cpu;
1114 }
1da177e4
LT
1115 }
1116 }
1117
1118 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1119out_set_cpu:
1120 new_cpu = wake_idle(new_cpu, p);
1121 if (new_cpu != cpu) {
1122 set_task_cpu(p, new_cpu);
1123 task_rq_unlock(rq, &flags);
1124 /* might preempt at this point */
1125 rq = task_rq_lock(p, &flags);
1126 old_state = p->state;
1127 if (!(old_state & state))
1128 goto out;
1129 if (p->array)
1130 goto out_running;
1131
1132 this_cpu = smp_processor_id();
1133 cpu = task_cpu(p);
1134 }
1135
1136out_activate:
1137#endif /* CONFIG_SMP */
1138 if (old_state == TASK_UNINTERRUPTIBLE) {
1139 rq->nr_uninterruptible--;
1140 /*
1141 * Tasks on involuntary sleep don't earn
1142 * sleep_avg beyond just interactive state.
1143 */
1144 p->activated = -1;
1145 }
1146
1147 /*
1148 * Sync wakeups (i.e. those types of wakeups where the waker
1149 * has indicated that it will leave the CPU in short order)
1150 * don't trigger a preemption, if the woken up task will run on
1151 * this cpu. (in this case the 'I will reschedule' promise of
1152 * the waker guarantees that the freshly woken up task is going
1153 * to be considered on this CPU.)
1154 */
1155 activate_task(p, rq, cpu == this_cpu);
1156 if (!sync || cpu != this_cpu) {
1157 if (TASK_PREEMPTS_CURR(p, rq))
1158 resched_task(rq->curr);
1159 }
1160 success = 1;
1161
1162out_running:
1163 p->state = TASK_RUNNING;
1164out:
1165 task_rq_unlock(rq, &flags);
1166
1167 return success;
1168}
1169
1170int fastcall wake_up_process(task_t * p)
1171{
1172 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1173 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1174}
1175
1176EXPORT_SYMBOL(wake_up_process);
1177
1178int fastcall wake_up_state(task_t *p, unsigned int state)
1179{
1180 return try_to_wake_up(p, state, 0);
1181}
1182
1da177e4
LT
1183/*
1184 * Perform scheduler related setup for a newly forked process p.
1185 * p is forked by current.
1186 */
1187void fastcall sched_fork(task_t *p)
1188{
1189 /*
1190 * We mark the process as running here, but have not actually
1191 * inserted it onto the runqueue yet. This guarantees that
1192 * nobody will actually run it, and a signal or other external
1193 * event cannot wake it up and insert it on the runqueue either.
1194 */
1195 p->state = TASK_RUNNING;
1196 INIT_LIST_HEAD(&p->run_list);
1197 p->array = NULL;
1198 spin_lock_init(&p->switch_lock);
1199#ifdef CONFIG_SCHEDSTATS
1200 memset(&p->sched_info, 0, sizeof(p->sched_info));
1201#endif
1202#ifdef CONFIG_PREEMPT
1203 /*
1204 * During context-switch we hold precisely one spinlock, which
1205 * schedule_tail drops. (in the common case it's this_rq()->lock,
1206 * but it also can be p->switch_lock.) So we compensate with a count
1207 * of 1. Also, we want to start with kernel preemption disabled.
1208 */
1209 p->thread_info->preempt_count = 1;
1210#endif
1211 /*
1212 * Share the timeslice between parent and child, thus the
1213 * total amount of pending timeslices in the system doesn't change,
1214 * resulting in more scheduling fairness.
1215 */
1216 local_irq_disable();
1217 p->time_slice = (current->time_slice + 1) >> 1;
1218 /*
1219 * The remainder of the first timeslice might be recovered by
1220 * the parent if the child exits early enough.
1221 */
1222 p->first_time_slice = 1;
1223 current->time_slice >>= 1;
1224 p->timestamp = sched_clock();
1225 if (unlikely(!current->time_slice)) {
1226 /*
1227 * This case is rare, it happens when the parent has only
1228 * a single jiffy left from its timeslice. Taking the
1229 * runqueue lock is not a problem.
1230 */
1231 current->time_slice = 1;
1232 preempt_disable();
1233 scheduler_tick();
1234 local_irq_enable();
1235 preempt_enable();
1236 } else
1237 local_irq_enable();
1238}
1239
1240/*
1241 * wake_up_new_task - wake up a newly created task for the first time.
1242 *
1243 * This function will do some initial scheduler statistics housekeeping
1244 * that must be done for every newly created context, then puts the task
1245 * on the runqueue and wakes it.
1246 */
1247void fastcall wake_up_new_task(task_t * p, unsigned long clone_flags)
1248{
1249 unsigned long flags;
1250 int this_cpu, cpu;
1251 runqueue_t *rq, *this_rq;
147cbb4b
NP
1252#ifdef CONFIG_SMP
1253 struct sched_domain *tmp, *sd = NULL;
1254#endif
1da177e4
LT
1255
1256 rq = task_rq_lock(p, &flags);
147cbb4b 1257 BUG_ON(p->state != TASK_RUNNING);
1da177e4 1258 this_cpu = smp_processor_id();
147cbb4b 1259 cpu = task_cpu(p);
1da177e4 1260
147cbb4b
NP
1261#ifdef CONFIG_SMP
1262 for_each_domain(cpu, tmp)
1263 if (tmp->flags & SD_BALANCE_FORK)
1264 sd = tmp;
1265
1266 if (sd) {
1267 struct sched_group *group;
1268
1269 cpu = task_cpu(p);
1270 group = find_idlest_group(sd, p, cpu);
1271 if (group) {
1272 int new_cpu;
1273 new_cpu = find_idlest_cpu(group, cpu);
1274 if (new_cpu != -1 && new_cpu != cpu &&
1275 cpu_isset(new_cpu, p->cpus_allowed)) {
1276 set_task_cpu(p, new_cpu);
1277 task_rq_unlock(rq, &flags);
1278 rq = task_rq_lock(p, &flags);
1279 cpu = task_cpu(p);
1280 }
1281 }
1282 }
1283#endif
1da177e4
LT
1284
1285 /*
1286 * We decrease the sleep average of forking parents
1287 * and children as well, to keep max-interactive tasks
1288 * from forking tasks that are max-interactive. The parent
1289 * (current) is done further down, under its lock.
1290 */
1291 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1292 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1293
1294 p->prio = effective_prio(p);
1295
1296 if (likely(cpu == this_cpu)) {
1297 if (!(clone_flags & CLONE_VM)) {
1298 /*
1299 * The VM isn't cloned, so we're in a good position to
1300 * do child-runs-first in anticipation of an exec. This
1301 * usually avoids a lot of COW overhead.
1302 */
1303 if (unlikely(!current->array))
1304 __activate_task(p, rq);
1305 else {
1306 p->prio = current->prio;
1307 list_add_tail(&p->run_list, &current->run_list);
1308 p->array = current->array;
1309 p->array->nr_active++;
1310 rq->nr_running++;
1311 }
1312 set_need_resched();
1313 } else
1314 /* Run child last */
1315 __activate_task(p, rq);
1316 /*
1317 * We skip the following code due to cpu == this_cpu
1318 *
1319 * task_rq_unlock(rq, &flags);
1320 * this_rq = task_rq_lock(current, &flags);
1321 */
1322 this_rq = rq;
1323 } else {
1324 this_rq = cpu_rq(this_cpu);
1325
1326 /*
1327 * Not the local CPU - must adjust timestamp. This should
1328 * get optimised away in the !CONFIG_SMP case.
1329 */
1330 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1331 + rq->timestamp_last_tick;
1332 __activate_task(p, rq);
1333 if (TASK_PREEMPTS_CURR(p, rq))
1334 resched_task(rq->curr);
1335
1336 /*
1337 * Parent and child are on different CPUs, now get the
1338 * parent runqueue to update the parent's ->sleep_avg:
1339 */
1340 task_rq_unlock(rq, &flags);
1341 this_rq = task_rq_lock(current, &flags);
1342 }
1343 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1344 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1345 task_rq_unlock(this_rq, &flags);
1346}
1347
1348/*
1349 * Potentially available exiting-child timeslices are
1350 * retrieved here - this way the parent does not get
1351 * penalized for creating too many threads.
1352 *
1353 * (this cannot be used to 'generate' timeslices
1354 * artificially, because any timeslice recovered here
1355 * was given away by the parent in the first place.)
1356 */
1357void fastcall sched_exit(task_t * p)
1358{
1359 unsigned long flags;
1360 runqueue_t *rq;
1361
1362 /*
1363 * If the child was a (relative-) CPU hog then decrease
1364 * the sleep_avg of the parent as well.
1365 */
1366 rq = task_rq_lock(p->parent, &flags);
1367 if (p->first_time_slice) {
1368 p->parent->time_slice += p->time_slice;
1369 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1370 p->parent->time_slice = task_timeslice(p);
1371 }
1372 if (p->sleep_avg < p->parent->sleep_avg)
1373 p->parent->sleep_avg = p->parent->sleep_avg /
1374 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1375 (EXIT_WEIGHT + 1);
1376 task_rq_unlock(rq, &flags);
1377}
1378
1379/**
1380 * finish_task_switch - clean up after a task-switch
1381 * @prev: the thread we just switched away from.
1382 *
1383 * We enter this with the runqueue still locked, and finish_arch_switch()
1384 * will unlock it along with doing any other architecture-specific cleanup
1385 * actions.
1386 *
1387 * Note that we may have delayed dropping an mm in context_switch(). If
1388 * so, we finish that here outside of the runqueue lock. (Doing it
1389 * with the lock held can cause deadlocks; see schedule() for
1390 * details.)
1391 */
1392static inline void finish_task_switch(task_t *prev)
1393 __releases(rq->lock)
1394{
1395 runqueue_t *rq = this_rq();
1396 struct mm_struct *mm = rq->prev_mm;
1397 unsigned long prev_task_flags;
1398
1399 rq->prev_mm = NULL;
1400
1401 /*
1402 * A task struct has one reference for the use as "current".
1403 * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1404 * calls schedule one last time. The schedule call will never return,
1405 * and the scheduled task must drop that reference.
1406 * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1407 * still held, otherwise prev could be scheduled on another cpu, die
1408 * there before we look at prev->state, and then the reference would
1409 * be dropped twice.
1410 * Manfred Spraul <manfred@colorfullife.com>
1411 */
1412 prev_task_flags = prev->flags;
1413 finish_arch_switch(rq, prev);
1414 if (mm)
1415 mmdrop(mm);
1416 if (unlikely(prev_task_flags & PF_DEAD))
1417 put_task_struct(prev);
1418}
1419
1420/**
1421 * schedule_tail - first thing a freshly forked thread must call.
1422 * @prev: the thread we just switched away from.
1423 */
1424asmlinkage void schedule_tail(task_t *prev)
1425 __releases(rq->lock)
1426{
1427 finish_task_switch(prev);
1428
1429 if (current->set_child_tid)
1430 put_user(current->pid, current->set_child_tid);
1431}
1432
1433/*
1434 * context_switch - switch to the new MM and the new
1435 * thread's register state.
1436 */
1437static inline
1438task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1439{
1440 struct mm_struct *mm = next->mm;
1441 struct mm_struct *oldmm = prev->active_mm;
1442
1443 if (unlikely(!mm)) {
1444 next->active_mm = oldmm;
1445 atomic_inc(&oldmm->mm_count);
1446 enter_lazy_tlb(oldmm, next);
1447 } else
1448 switch_mm(oldmm, mm, next);
1449
1450 if (unlikely(!prev->mm)) {
1451 prev->active_mm = NULL;
1452 WARN_ON(rq->prev_mm);
1453 rq->prev_mm = oldmm;
1454 }
1455
1456 /* Here we just switch the register state and the stack. */
1457 switch_to(prev, next, prev);
1458
1459 return prev;
1460}
1461
1462/*
1463 * nr_running, nr_uninterruptible and nr_context_switches:
1464 *
1465 * externally visible scheduler statistics: current number of runnable
1466 * threads, current number of uninterruptible-sleeping threads, total
1467 * number of context switches performed since bootup.
1468 */
1469unsigned long nr_running(void)
1470{
1471 unsigned long i, sum = 0;
1472
1473 for_each_online_cpu(i)
1474 sum += cpu_rq(i)->nr_running;
1475
1476 return sum;
1477}
1478
1479unsigned long nr_uninterruptible(void)
1480{
1481 unsigned long i, sum = 0;
1482
1483 for_each_cpu(i)
1484 sum += cpu_rq(i)->nr_uninterruptible;
1485
1486 /*
1487 * Since we read the counters lockless, it might be slightly
1488 * inaccurate. Do not allow it to go below zero though:
1489 */
1490 if (unlikely((long)sum < 0))
1491 sum = 0;
1492
1493 return sum;
1494}
1495
1496unsigned long long nr_context_switches(void)
1497{
1498 unsigned long long i, sum = 0;
1499
1500 for_each_cpu(i)
1501 sum += cpu_rq(i)->nr_switches;
1502
1503 return sum;
1504}
1505
1506unsigned long nr_iowait(void)
1507{
1508 unsigned long i, sum = 0;
1509
1510 for_each_cpu(i)
1511 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1512
1513 return sum;
1514}
1515
1516#ifdef CONFIG_SMP
1517
1518/*
1519 * double_rq_lock - safely lock two runqueues
1520 *
1521 * Note this does not disable interrupts like task_rq_lock,
1522 * you need to do so manually before calling.
1523 */
1524static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1525 __acquires(rq1->lock)
1526 __acquires(rq2->lock)
1527{
1528 if (rq1 == rq2) {
1529 spin_lock(&rq1->lock);
1530 __acquire(rq2->lock); /* Fake it out ;) */
1531 } else {
1532 if (rq1 < rq2) {
1533 spin_lock(&rq1->lock);
1534 spin_lock(&rq2->lock);
1535 } else {
1536 spin_lock(&rq2->lock);
1537 spin_lock(&rq1->lock);
1538 }
1539 }
1540}
1541
1542/*
1543 * double_rq_unlock - safely unlock two runqueues
1544 *
1545 * Note this does not restore interrupts like task_rq_unlock,
1546 * you need to do so manually after calling.
1547 */
1548static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1549 __releases(rq1->lock)
1550 __releases(rq2->lock)
1551{
1552 spin_unlock(&rq1->lock);
1553 if (rq1 != rq2)
1554 spin_unlock(&rq2->lock);
1555 else
1556 __release(rq2->lock);
1557}
1558
1559/*
1560 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1561 */
1562static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1563 __releases(this_rq->lock)
1564 __acquires(busiest->lock)
1565 __acquires(this_rq->lock)
1566{
1567 if (unlikely(!spin_trylock(&busiest->lock))) {
1568 if (busiest < this_rq) {
1569 spin_unlock(&this_rq->lock);
1570 spin_lock(&busiest->lock);
1571 spin_lock(&this_rq->lock);
1572 } else
1573 spin_lock(&busiest->lock);
1574 }
1575}
1576
1da177e4
LT
1577/*
1578 * If dest_cpu is allowed for this process, migrate the task to it.
1579 * This is accomplished by forcing the cpu_allowed mask to only
1580 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1581 * the cpu_allowed mask is restored.
1582 */
1583static void sched_migrate_task(task_t *p, int dest_cpu)
1584{
1585 migration_req_t req;
1586 runqueue_t *rq;
1587 unsigned long flags;
1588
1589 rq = task_rq_lock(p, &flags);
1590 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1591 || unlikely(cpu_is_offline(dest_cpu)))
1592 goto out;
1593
1594 /* force the process onto the specified CPU */
1595 if (migrate_task(p, dest_cpu, &req)) {
1596 /* Need to wait for migration thread (might exit: take ref). */
1597 struct task_struct *mt = rq->migration_thread;
1598 get_task_struct(mt);
1599 task_rq_unlock(rq, &flags);
1600 wake_up_process(mt);
1601 put_task_struct(mt);
1602 wait_for_completion(&req.done);
1603 return;
1604 }
1605out:
1606 task_rq_unlock(rq, &flags);
1607}
1608
1609/*
1610 * sched_exec(): find the highest-level, exec-balance-capable
1611 * domain and try to migrate the task to the least loaded CPU.
1612 *
1613 * execve() is a valuable balancing opportunity, because at this point
1614 * the task has the smallest effective memory and cache footprint.
1615 */
1616void sched_exec(void)
1617{
1618 struct sched_domain *tmp, *sd = NULL;
1619 int new_cpu, this_cpu = get_cpu();
1620
1621 /* Prefer the current CPU if there's only this task running */
1622 if (this_rq()->nr_running <= 1)
1623 goto out;
1624
1625 for_each_domain(this_cpu, tmp)
1626 if (tmp->flags & SD_BALANCE_EXEC)
1627 sd = tmp;
1628
1629 if (sd) {
147cbb4b 1630 struct sched_group *group;
1da177e4 1631 schedstat_inc(sd, sbe_attempts);
147cbb4b
NP
1632 group = find_idlest_group(sd, current, this_cpu);
1633 if (!group)
1634 goto out;
1635 new_cpu = find_idlest_cpu(group, this_cpu);
1636 if (new_cpu == -1)
1637 goto out;
1638
1da177e4
LT
1639 if (new_cpu != this_cpu) {
1640 schedstat_inc(sd, sbe_pushed);
1641 put_cpu();
1642 sched_migrate_task(current, new_cpu);
1643 return;
1644 }
1645 }
1646out:
1647 put_cpu();
1648}
1649
1650/*
1651 * pull_task - move a task from a remote runqueue to the local runqueue.
1652 * Both runqueues must be locked.
1653 */
1654static inline
1655void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1656 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1657{
1658 dequeue_task(p, src_array);
1659 src_rq->nr_running--;
1660 set_task_cpu(p, this_cpu);
1661 this_rq->nr_running++;
1662 enqueue_task(p, this_array);
1663 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1664 + this_rq->timestamp_last_tick;
1665 /*
1666 * Note that idle threads have a prio of MAX_PRIO, for this test
1667 * to be always true for them.
1668 */
1669 if (TASK_PREEMPTS_CURR(p, this_rq))
1670 resched_task(this_rq->curr);
1671}
1672
1673/*
1674 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1675 */
1676static inline
1677int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
81026794 1678 struct sched_domain *sd, enum idle_type idle, int *all_pinned)
1da177e4
LT
1679{
1680 /*
1681 * We do not migrate tasks that are:
1682 * 1) running (obviously), or
1683 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1684 * 3) are cache-hot on their current CPU.
1685 */
1da177e4
LT
1686 if (!cpu_isset(this_cpu, p->cpus_allowed))
1687 return 0;
81026794
NP
1688 *all_pinned = 0;
1689
1690 if (task_running(rq, p))
1691 return 0;
1da177e4
LT
1692
1693 /*
1694 * Aggressive migration if:
cafb20c1 1695 * 1) task is cache cold, or
1da177e4
LT
1696 * 2) too many balance attempts have failed.
1697 */
1698
cafb20c1 1699 if (sd->nr_balance_failed > sd->cache_nice_tries)
1da177e4
LT
1700 return 1;
1701
1702 if (task_hot(p, rq->timestamp_last_tick, sd))
81026794 1703 return 0;
1da177e4
LT
1704 return 1;
1705}
1706
1707/*
1708 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1709 * as part of a balancing operation within "domain". Returns the number of
1710 * tasks moved.
1711 *
1712 * Called with both runqueues locked.
1713 */
1714static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1715 unsigned long max_nr_move, struct sched_domain *sd,
81026794 1716 enum idle_type idle, int *all_pinned)
1da177e4
LT
1717{
1718 prio_array_t *array, *dst_array;
1719 struct list_head *head, *curr;
81026794 1720 int idx, pulled = 0, pinned = 0;
1da177e4
LT
1721 task_t *tmp;
1722
81026794 1723 if (max_nr_move == 0)
1da177e4
LT
1724 goto out;
1725
81026794
NP
1726 pinned = 1;
1727
1da177e4
LT
1728 /*
1729 * We first consider expired tasks. Those will likely not be
1730 * executed in the near future, and they are most likely to
1731 * be cache-cold, thus switching CPUs has the least effect
1732 * on them.
1733 */
1734 if (busiest->expired->nr_active) {
1735 array = busiest->expired;
1736 dst_array = this_rq->expired;
1737 } else {
1738 array = busiest->active;
1739 dst_array = this_rq->active;
1740 }
1741
1742new_array:
1743 /* Start searching at priority 0: */
1744 idx = 0;
1745skip_bitmap:
1746 if (!idx)
1747 idx = sched_find_first_bit(array->bitmap);
1748 else
1749 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1750 if (idx >= MAX_PRIO) {
1751 if (array == busiest->expired && busiest->active->nr_active) {
1752 array = busiest->active;
1753 dst_array = this_rq->active;
1754 goto new_array;
1755 }
1756 goto out;
1757 }
1758
1759 head = array->queue + idx;
1760 curr = head->prev;
1761skip_queue:
1762 tmp = list_entry(curr, task_t, run_list);
1763
1764 curr = curr->prev;
1765
81026794 1766 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle, &pinned)) {
1da177e4
LT
1767 if (curr != head)
1768 goto skip_queue;
1769 idx++;
1770 goto skip_bitmap;
1771 }
1772
1773#ifdef CONFIG_SCHEDSTATS
1774 if (task_hot(tmp, busiest->timestamp_last_tick, sd))
1775 schedstat_inc(sd, lb_hot_gained[idle]);
1776#endif
1777
1778 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
1779 pulled++;
1780
1781 /* We only want to steal up to the prescribed number of tasks. */
1782 if (pulled < max_nr_move) {
1783 if (curr != head)
1784 goto skip_queue;
1785 idx++;
1786 goto skip_bitmap;
1787 }
1788out:
1789 /*
1790 * Right now, this is the only place pull_task() is called,
1791 * so we can safely collect pull_task() stats here rather than
1792 * inside pull_task().
1793 */
1794 schedstat_add(sd, lb_gained[idle], pulled);
81026794
NP
1795
1796 if (all_pinned)
1797 *all_pinned = pinned;
1da177e4
LT
1798 return pulled;
1799}
1800
1801/*
1802 * find_busiest_group finds and returns the busiest CPU group within the
1803 * domain. It calculates and returns the number of tasks which should be
1804 * moved to restore balance via the imbalance parameter.
1805 */
1806static struct sched_group *
1807find_busiest_group(struct sched_domain *sd, int this_cpu,
1808 unsigned long *imbalance, enum idle_type idle)
1809{
1810 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
1811 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
7897986b 1812 int load_idx;
1da177e4
LT
1813
1814 max_load = this_load = total_load = total_pwr = 0;
7897986b
NP
1815 if (idle == NOT_IDLE)
1816 load_idx = sd->busy_idx;
1817 else if (idle == NEWLY_IDLE)
1818 load_idx = sd->newidle_idx;
1819 else
1820 load_idx = sd->idle_idx;
1da177e4
LT
1821
1822 do {
1823 unsigned long load;
1824 int local_group;
1825 int i;
1826
1827 local_group = cpu_isset(this_cpu, group->cpumask);
1828
1829 /* Tally up the load of all CPUs in the group */
1830 avg_load = 0;
1831
1832 for_each_cpu_mask(i, group->cpumask) {
1833 /* Bias balancing toward cpus of our domain */
1834 if (local_group)
7897986b 1835 load = target_load(i, load_idx);
1da177e4 1836 else
7897986b 1837 load = source_load(i, load_idx);
1da177e4
LT
1838
1839 avg_load += load;
1840 }
1841
1842 total_load += avg_load;
1843 total_pwr += group->cpu_power;
1844
1845 /* Adjust by relative CPU power of the group */
1846 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1847
1848 if (local_group) {
1849 this_load = avg_load;
1850 this = group;
1da177e4
LT
1851 } else if (avg_load > max_load) {
1852 max_load = avg_load;
1853 busiest = group;
1854 }
1da177e4
LT
1855 group = group->next;
1856 } while (group != sd->groups);
1857
1858 if (!busiest || this_load >= max_load)
1859 goto out_balanced;
1860
1861 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
1862
1863 if (this_load >= avg_load ||
1864 100*max_load <= sd->imbalance_pct*this_load)
1865 goto out_balanced;
1866
1867 /*
1868 * We're trying to get all the cpus to the average_load, so we don't
1869 * want to push ourselves above the average load, nor do we wish to
1870 * reduce the max loaded cpu below the average load, as either of these
1871 * actions would just result in more rebalancing later, and ping-pong
1872 * tasks around. Thus we look for the minimum possible imbalance.
1873 * Negative imbalances (*we* are more loaded than anyone else) will
1874 * be counted as no imbalance for these purposes -- we can't fix that
1875 * by pulling tasks to us. Be careful of negative numbers as they'll
1876 * appear as very large values with unsigned longs.
1877 */
1878 /* How much load to actually move to equalise the imbalance */
1879 *imbalance = min((max_load - avg_load) * busiest->cpu_power,
1880 (avg_load - this_load) * this->cpu_power)
1881 / SCHED_LOAD_SCALE;
1882
1883 if (*imbalance < SCHED_LOAD_SCALE) {
1884 unsigned long pwr_now = 0, pwr_move = 0;
1885 unsigned long tmp;
1886
1887 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
1888 *imbalance = 1;
1889 return busiest;
1890 }
1891
1892 /*
1893 * OK, we don't have enough imbalance to justify moving tasks,
1894 * however we may be able to increase total CPU power used by
1895 * moving them.
1896 */
1897
1898 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
1899 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
1900 pwr_now /= SCHED_LOAD_SCALE;
1901
1902 /* Amount of load we'd subtract */
1903 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
1904 if (max_load > tmp)
1905 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
1906 max_load - tmp);
1907
1908 /* Amount of load we'd add */
1909 if (max_load*busiest->cpu_power <
1910 SCHED_LOAD_SCALE*SCHED_LOAD_SCALE)
1911 tmp = max_load*busiest->cpu_power/this->cpu_power;
1912 else
1913 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
1914 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
1915 pwr_move /= SCHED_LOAD_SCALE;
1916
1917 /* Move if we gain throughput */
1918 if (pwr_move <= pwr_now)
1919 goto out_balanced;
1920
1921 *imbalance = 1;
1922 return busiest;
1923 }
1924
1925 /* Get rid of the scaling factor, rounding down as we divide */
1926 *imbalance = *imbalance / SCHED_LOAD_SCALE;
1da177e4
LT
1927 return busiest;
1928
1929out_balanced:
1da177e4
LT
1930
1931 *imbalance = 0;
1932 return NULL;
1933}
1934
1935/*
1936 * find_busiest_queue - find the busiest runqueue among the cpus in group.
1937 */
1938static runqueue_t *find_busiest_queue(struct sched_group *group)
1939{
1940 unsigned long load, max_load = 0;
1941 runqueue_t *busiest = NULL;
1942 int i;
1943
1944 for_each_cpu_mask(i, group->cpumask) {
7897986b 1945 load = source_load(i, 0);
1da177e4
LT
1946
1947 if (load > max_load) {
1948 max_load = load;
1949 busiest = cpu_rq(i);
1950 }
1951 }
1952
1953 return busiest;
1954}
1955
1956/*
1957 * Check this_cpu to ensure it is balanced within domain. Attempt to move
1958 * tasks if there is an imbalance.
1959 *
1960 * Called with this_rq unlocked.
1961 */
1962static int load_balance(int this_cpu, runqueue_t *this_rq,
1963 struct sched_domain *sd, enum idle_type idle)
1964{
1965 struct sched_group *group;
1966 runqueue_t *busiest;
1967 unsigned long imbalance;
81026794
NP
1968 int nr_moved, all_pinned;
1969 int active_balance = 0;
1da177e4
LT
1970
1971 spin_lock(&this_rq->lock);
1972 schedstat_inc(sd, lb_cnt[idle]);
1973
1974 group = find_busiest_group(sd, this_cpu, &imbalance, idle);
1975 if (!group) {
1976 schedstat_inc(sd, lb_nobusyg[idle]);
1977 goto out_balanced;
1978 }
1979
1980 busiest = find_busiest_queue(group);
1981 if (!busiest) {
1982 schedstat_inc(sd, lb_nobusyq[idle]);
1983 goto out_balanced;
1984 }
1985
db935dbd 1986 BUG_ON(busiest == this_rq);
1da177e4
LT
1987
1988 schedstat_add(sd, lb_imbalance[idle], imbalance);
1989
1990 nr_moved = 0;
1991 if (busiest->nr_running > 1) {
1992 /*
1993 * Attempt to move tasks. If find_busiest_group has found
1994 * an imbalance but busiest->nr_running <= 1, the group is
1995 * still unbalanced. nr_moved simply stays zero, so it is
1996 * correctly treated as an imbalance.
1997 */
1998 double_lock_balance(this_rq, busiest);
1999 nr_moved = move_tasks(this_rq, this_cpu, busiest,
81026794
NP
2000 imbalance, sd, idle,
2001 &all_pinned);
1da177e4 2002 spin_unlock(&busiest->lock);
81026794
NP
2003
2004 /* All tasks on this runqueue were pinned by CPU affinity */
2005 if (unlikely(all_pinned))
2006 goto out_balanced;
1da177e4 2007 }
81026794 2008
1da177e4
LT
2009 spin_unlock(&this_rq->lock);
2010
2011 if (!nr_moved) {
2012 schedstat_inc(sd, lb_failed[idle]);
2013 sd->nr_balance_failed++;
2014
2015 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
1da177e4
LT
2016
2017 spin_lock(&busiest->lock);
2018 if (!busiest->active_balance) {
2019 busiest->active_balance = 1;
2020 busiest->push_cpu = this_cpu;
81026794 2021 active_balance = 1;
1da177e4
LT
2022 }
2023 spin_unlock(&busiest->lock);
81026794 2024 if (active_balance)
1da177e4
LT
2025 wake_up_process(busiest->migration_thread);
2026
2027 /*
2028 * We've kicked active balancing, reset the failure
2029 * counter.
2030 */
39507451 2031 sd->nr_balance_failed = sd->cache_nice_tries+1;
1da177e4 2032 }
81026794 2033 } else
1da177e4
LT
2034 sd->nr_balance_failed = 0;
2035
81026794 2036 if (likely(!active_balance)) {
1da177e4
LT
2037 /* We were unbalanced, so reset the balancing interval */
2038 sd->balance_interval = sd->min_interval;
81026794
NP
2039 } else {
2040 /*
2041 * If we've begun active balancing, start to back off. This
2042 * case may not be covered by the all_pinned logic if there
2043 * is only 1 task on the busy runqueue (because we don't call
2044 * move_tasks).
2045 */
2046 if (sd->balance_interval < sd->max_interval)
2047 sd->balance_interval *= 2;
1da177e4
LT
2048 }
2049
2050 return nr_moved;
2051
2052out_balanced:
2053 spin_unlock(&this_rq->lock);
2054
2055 schedstat_inc(sd, lb_balanced[idle]);
2056
16cfb1c0 2057 sd->nr_balance_failed = 0;
1da177e4
LT
2058 /* tune up the balancing interval */
2059 if (sd->balance_interval < sd->max_interval)
2060 sd->balance_interval *= 2;
2061
2062 return 0;
2063}
2064
2065/*
2066 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2067 * tasks if there is an imbalance.
2068 *
2069 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2070 * this_rq is locked.
2071 */
2072static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2073 struct sched_domain *sd)
2074{
2075 struct sched_group *group;
2076 runqueue_t *busiest = NULL;
2077 unsigned long imbalance;
2078 int nr_moved = 0;
2079
2080 schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
2081 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE);
2082 if (!group) {
1da177e4 2083 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
16cfb1c0 2084 goto out_balanced;
1da177e4
LT
2085 }
2086
2087 busiest = find_busiest_queue(group);
db935dbd 2088 if (!busiest) {
1da177e4 2089 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
16cfb1c0 2090 goto out_balanced;
1da177e4
LT
2091 }
2092
db935dbd
NP
2093 BUG_ON(busiest == this_rq);
2094
1da177e4
LT
2095 /* Attempt to move tasks */
2096 double_lock_balance(this_rq, busiest);
2097
2098 schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
2099 nr_moved = move_tasks(this_rq, this_cpu, busiest,
81026794 2100 imbalance, sd, NEWLY_IDLE, NULL);
1da177e4
LT
2101 if (!nr_moved)
2102 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
16cfb1c0
NP
2103 else
2104 sd->nr_balance_failed = 0;
1da177e4
LT
2105
2106 spin_unlock(&busiest->lock);
1da177e4 2107 return nr_moved;
16cfb1c0
NP
2108
2109out_balanced:
2110 schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
2111 sd->nr_balance_failed = 0;
2112 return 0;
1da177e4
LT
2113}
2114
2115/*
2116 * idle_balance is called by schedule() if this_cpu is about to become
2117 * idle. Attempts to pull tasks from other CPUs.
2118 */
2119static inline void idle_balance(int this_cpu, runqueue_t *this_rq)
2120{
2121 struct sched_domain *sd;
2122
2123 for_each_domain(this_cpu, sd) {
2124 if (sd->flags & SD_BALANCE_NEWIDLE) {
2125 if (load_balance_newidle(this_cpu, this_rq, sd)) {
2126 /* We've pulled tasks over so stop searching */
2127 break;
2128 }
2129 }
2130 }
2131}
2132
2133/*
2134 * active_load_balance is run by migration threads. It pushes running tasks
2135 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2136 * running on each physical CPU where possible, and avoids physical /
2137 * logical imbalances.
2138 *
2139 * Called with busiest_rq locked.
2140 */
2141static void active_load_balance(runqueue_t *busiest_rq, int busiest_cpu)
2142{
2143 struct sched_domain *sd;
1da177e4 2144 runqueue_t *target_rq;
39507451
NP
2145 int target_cpu = busiest_rq->push_cpu;
2146
2147 if (busiest_rq->nr_running <= 1)
2148 /* no task to move */
2149 return;
2150
2151 target_rq = cpu_rq(target_cpu);
1da177e4
LT
2152
2153 /*
39507451
NP
2154 * This condition is "impossible", if it occurs
2155 * we need to fix it. Originally reported by
2156 * Bjorn Helgaas on a 128-cpu setup.
1da177e4 2157 */
39507451 2158 BUG_ON(busiest_rq == target_rq);
1da177e4 2159
39507451
NP
2160 /* move a task from busiest_rq to target_rq */
2161 double_lock_balance(busiest_rq, target_rq);
2162
2163 /* Search for an sd spanning us and the target CPU. */
2164 for_each_domain(target_cpu, sd)
2165 if ((sd->flags & SD_LOAD_BALANCE) &&
2166 cpu_isset(busiest_cpu, sd->span))
2167 break;
2168
2169 if (unlikely(sd == NULL))
2170 goto out;
2171
2172 schedstat_inc(sd, alb_cnt);
2173
2174 if (move_tasks(target_rq, target_cpu, busiest_rq, 1, sd, SCHED_IDLE, NULL))
2175 schedstat_inc(sd, alb_pushed);
2176 else
2177 schedstat_inc(sd, alb_failed);
2178out:
2179 spin_unlock(&target_rq->lock);
1da177e4
LT
2180}
2181
2182/*
2183 * rebalance_tick will get called every timer tick, on every CPU.
2184 *
2185 * It checks each scheduling domain to see if it is due to be balanced,
2186 * and initiates a balancing operation if so.
2187 *
2188 * Balancing parameters are set up in arch_init_sched_domains.
2189 */
2190
2191/* Don't have all balancing operations going off at once */
2192#define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2193
2194static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2195 enum idle_type idle)
2196{
2197 unsigned long old_load, this_load;
2198 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2199 struct sched_domain *sd;
7897986b 2200 int i;
1da177e4 2201
1da177e4 2202 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
7897986b
NP
2203 /* Update our load */
2204 for (i = 0; i < 3; i++) {
2205 unsigned long new_load = this_load;
2206 int scale = 1 << i;
2207 old_load = this_rq->cpu_load[i];
2208 /*
2209 * Round up the averaging division if load is increasing. This
2210 * prevents us from getting stuck on 9 if the load is 10, for
2211 * example.
2212 */
2213 if (new_load > old_load)
2214 new_load += scale-1;
2215 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) / scale;
2216 }
1da177e4
LT
2217
2218 for_each_domain(this_cpu, sd) {
2219 unsigned long interval;
2220
2221 if (!(sd->flags & SD_LOAD_BALANCE))
2222 continue;
2223
2224 interval = sd->balance_interval;
2225 if (idle != SCHED_IDLE)
2226 interval *= sd->busy_factor;
2227
2228 /* scale ms to jiffies */
2229 interval = msecs_to_jiffies(interval);
2230 if (unlikely(!interval))
2231 interval = 1;
2232
2233 if (j - sd->last_balance >= interval) {
2234 if (load_balance(this_cpu, this_rq, sd, idle)) {
2235 /* We've pulled tasks over so no longer idle */
2236 idle = NOT_IDLE;
2237 }
2238 sd->last_balance += interval;
2239 }
2240 }
2241}
2242#else
2243/*
2244 * on UP we do not need to balance between CPUs:
2245 */
2246static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2247{
2248}
2249static inline void idle_balance(int cpu, runqueue_t *rq)
2250{
2251}
2252#endif
2253
2254static inline int wake_priority_sleeper(runqueue_t *rq)
2255{
2256 int ret = 0;
2257#ifdef CONFIG_SCHED_SMT
2258 spin_lock(&rq->lock);
2259 /*
2260 * If an SMT sibling task has been put to sleep for priority
2261 * reasons reschedule the idle task to see if it can now run.
2262 */
2263 if (rq->nr_running) {
2264 resched_task(rq->idle);
2265 ret = 1;
2266 }
2267 spin_unlock(&rq->lock);
2268#endif
2269 return ret;
2270}
2271
2272DEFINE_PER_CPU(struct kernel_stat, kstat);
2273
2274EXPORT_PER_CPU_SYMBOL(kstat);
2275
2276/*
2277 * This is called on clock ticks and on context switches.
2278 * Bank in p->sched_time the ns elapsed since the last tick or switch.
2279 */
2280static inline void update_cpu_clock(task_t *p, runqueue_t *rq,
2281 unsigned long long now)
2282{
2283 unsigned long long last = max(p->timestamp, rq->timestamp_last_tick);
2284 p->sched_time += now - last;
2285}
2286
2287/*
2288 * Return current->sched_time plus any more ns on the sched_clock
2289 * that have not yet been banked.
2290 */
2291unsigned long long current_sched_time(const task_t *tsk)
2292{
2293 unsigned long long ns;
2294 unsigned long flags;
2295 local_irq_save(flags);
2296 ns = max(tsk->timestamp, task_rq(tsk)->timestamp_last_tick);
2297 ns = tsk->sched_time + (sched_clock() - ns);
2298 local_irq_restore(flags);
2299 return ns;
2300}
2301
2302/*
2303 * We place interactive tasks back into the active array, if possible.
2304 *
2305 * To guarantee that this does not starve expired tasks we ignore the
2306 * interactivity of a task if the first expired task had to wait more
2307 * than a 'reasonable' amount of time. This deadline timeout is
2308 * load-dependent, as the frequency of array switched decreases with
2309 * increasing number of running tasks. We also ignore the interactivity
2310 * if a better static_prio task has expired:
2311 */
2312#define EXPIRED_STARVING(rq) \
2313 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2314 (jiffies - (rq)->expired_timestamp >= \
2315 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2316 ((rq)->curr->static_prio > (rq)->best_expired_prio))
2317
2318/*
2319 * Account user cpu time to a process.
2320 * @p: the process that the cpu time gets accounted to
2321 * @hardirq_offset: the offset to subtract from hardirq_count()
2322 * @cputime: the cpu time spent in user space since the last update
2323 */
2324void account_user_time(struct task_struct *p, cputime_t cputime)
2325{
2326 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2327 cputime64_t tmp;
2328
2329 p->utime = cputime_add(p->utime, cputime);
2330
2331 /* Add user time to cpustat. */
2332 tmp = cputime_to_cputime64(cputime);
2333 if (TASK_NICE(p) > 0)
2334 cpustat->nice = cputime64_add(cpustat->nice, tmp);
2335 else
2336 cpustat->user = cputime64_add(cpustat->user, tmp);
2337}
2338
2339/*
2340 * Account system cpu time to a process.
2341 * @p: the process that the cpu time gets accounted to
2342 * @hardirq_offset: the offset to subtract from hardirq_count()
2343 * @cputime: the cpu time spent in kernel space since the last update
2344 */
2345void account_system_time(struct task_struct *p, int hardirq_offset,
2346 cputime_t cputime)
2347{
2348 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2349 runqueue_t *rq = this_rq();
2350 cputime64_t tmp;
2351
2352 p->stime = cputime_add(p->stime, cputime);
2353
2354 /* Add system time to cpustat. */
2355 tmp = cputime_to_cputime64(cputime);
2356 if (hardirq_count() - hardirq_offset)
2357 cpustat->irq = cputime64_add(cpustat->irq, tmp);
2358 else if (softirq_count())
2359 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
2360 else if (p != rq->idle)
2361 cpustat->system = cputime64_add(cpustat->system, tmp);
2362 else if (atomic_read(&rq->nr_iowait) > 0)
2363 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2364 else
2365 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2366 /* Account for system time used */
2367 acct_update_integrals(p);
2368 /* Update rss highwater mark */
2369 update_mem_hiwater(p);
2370}
2371
2372/*
2373 * Account for involuntary wait time.
2374 * @p: the process from which the cpu time has been stolen
2375 * @steal: the cpu time spent in involuntary wait
2376 */
2377void account_steal_time(struct task_struct *p, cputime_t steal)
2378{
2379 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2380 cputime64_t tmp = cputime_to_cputime64(steal);
2381 runqueue_t *rq = this_rq();
2382
2383 if (p == rq->idle) {
2384 p->stime = cputime_add(p->stime, steal);
2385 if (atomic_read(&rq->nr_iowait) > 0)
2386 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2387 else
2388 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2389 } else
2390 cpustat->steal = cputime64_add(cpustat->steal, tmp);
2391}
2392
2393/*
2394 * This function gets called by the timer code, with HZ frequency.
2395 * We call it with interrupts disabled.
2396 *
2397 * It also gets called by the fork code, when changing the parent's
2398 * timeslices.
2399 */
2400void scheduler_tick(void)
2401{
2402 int cpu = smp_processor_id();
2403 runqueue_t *rq = this_rq();
2404 task_t *p = current;
2405 unsigned long long now = sched_clock();
2406
2407 update_cpu_clock(p, rq, now);
2408
2409 rq->timestamp_last_tick = now;
2410
2411 if (p == rq->idle) {
2412 if (wake_priority_sleeper(rq))
2413 goto out;
2414 rebalance_tick(cpu, rq, SCHED_IDLE);
2415 return;
2416 }
2417
2418 /* Task might have expired already, but not scheduled off yet */
2419 if (p->array != rq->active) {
2420 set_tsk_need_resched(p);
2421 goto out;
2422 }
2423 spin_lock(&rq->lock);
2424 /*
2425 * The task was running during this tick - update the
2426 * time slice counter. Note: we do not update a thread's
2427 * priority until it either goes to sleep or uses up its
2428 * timeslice. This makes it possible for interactive tasks
2429 * to use up their timeslices at their highest priority levels.
2430 */
2431 if (rt_task(p)) {
2432 /*
2433 * RR tasks need a special form of timeslice management.
2434 * FIFO tasks have no timeslices.
2435 */
2436 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2437 p->time_slice = task_timeslice(p);
2438 p->first_time_slice = 0;
2439 set_tsk_need_resched(p);
2440
2441 /* put it at the end of the queue: */
2442 requeue_task(p, rq->active);
2443 }
2444 goto out_unlock;
2445 }
2446 if (!--p->time_slice) {
2447 dequeue_task(p, rq->active);
2448 set_tsk_need_resched(p);
2449 p->prio = effective_prio(p);
2450 p->time_slice = task_timeslice(p);
2451 p->first_time_slice = 0;
2452
2453 if (!rq->expired_timestamp)
2454 rq->expired_timestamp = jiffies;
2455 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2456 enqueue_task(p, rq->expired);
2457 if (p->static_prio < rq->best_expired_prio)
2458 rq->best_expired_prio = p->static_prio;
2459 } else
2460 enqueue_task(p, rq->active);
2461 } else {
2462 /*
2463 * Prevent a too long timeslice allowing a task to monopolize
2464 * the CPU. We do this by splitting up the timeslice into
2465 * smaller pieces.
2466 *
2467 * Note: this does not mean the task's timeslices expire or
2468 * get lost in any way, they just might be preempted by
2469 * another task of equal priority. (one with higher
2470 * priority would have preempted this task already.) We
2471 * requeue this task to the end of the list on this priority
2472 * level, which is in essence a round-robin of tasks with
2473 * equal priority.
2474 *
2475 * This only applies to tasks in the interactive
2476 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2477 */
2478 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2479 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2480 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2481 (p->array == rq->active)) {
2482
2483 requeue_task(p, rq->active);
2484 set_tsk_need_resched(p);
2485 }
2486 }
2487out_unlock:
2488 spin_unlock(&rq->lock);
2489out:
2490 rebalance_tick(cpu, rq, NOT_IDLE);
2491}
2492
2493#ifdef CONFIG_SCHED_SMT
2494static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2495{
2496 struct sched_domain *sd = this_rq->sd;
2497 cpumask_t sibling_map;
2498 int i;
2499
2500 if (!(sd->flags & SD_SHARE_CPUPOWER))
2501 return;
2502
2503 /*
2504 * Unlock the current runqueue because we have to lock in
2505 * CPU order to avoid deadlocks. Caller knows that we might
2506 * unlock. We keep IRQs disabled.
2507 */
2508 spin_unlock(&this_rq->lock);
2509
2510 sibling_map = sd->span;
2511
2512 for_each_cpu_mask(i, sibling_map)
2513 spin_lock(&cpu_rq(i)->lock);
2514 /*
2515 * We clear this CPU from the mask. This both simplifies the
2516 * inner loop and keps this_rq locked when we exit:
2517 */
2518 cpu_clear(this_cpu, sibling_map);
2519
2520 for_each_cpu_mask(i, sibling_map) {
2521 runqueue_t *smt_rq = cpu_rq(i);
2522
2523 /*
2524 * If an SMT sibling task is sleeping due to priority
2525 * reasons wake it up now.
2526 */
2527 if (smt_rq->curr == smt_rq->idle && smt_rq->nr_running)
2528 resched_task(smt_rq->idle);
2529 }
2530
2531 for_each_cpu_mask(i, sibling_map)
2532 spin_unlock(&cpu_rq(i)->lock);
2533 /*
2534 * We exit with this_cpu's rq still held and IRQs
2535 * still disabled:
2536 */
2537}
2538
2539static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2540{
2541 struct sched_domain *sd = this_rq->sd;
2542 cpumask_t sibling_map;
2543 prio_array_t *array;
2544 int ret = 0, i;
2545 task_t *p;
2546
2547 if (!(sd->flags & SD_SHARE_CPUPOWER))
2548 return 0;
2549
2550 /*
2551 * The same locking rules and details apply as for
2552 * wake_sleeping_dependent():
2553 */
2554 spin_unlock(&this_rq->lock);
2555 sibling_map = sd->span;
2556 for_each_cpu_mask(i, sibling_map)
2557 spin_lock(&cpu_rq(i)->lock);
2558 cpu_clear(this_cpu, sibling_map);
2559
2560 /*
2561 * Establish next task to be run - it might have gone away because
2562 * we released the runqueue lock above:
2563 */
2564 if (!this_rq->nr_running)
2565 goto out_unlock;
2566 array = this_rq->active;
2567 if (!array->nr_active)
2568 array = this_rq->expired;
2569 BUG_ON(!array->nr_active);
2570
2571 p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
2572 task_t, run_list);
2573
2574 for_each_cpu_mask(i, sibling_map) {
2575 runqueue_t *smt_rq = cpu_rq(i);
2576 task_t *smt_curr = smt_rq->curr;
2577
2578 /*
2579 * If a user task with lower static priority than the
2580 * running task on the SMT sibling is trying to schedule,
2581 * delay it till there is proportionately less timeslice
2582 * left of the sibling task to prevent a lower priority
2583 * task from using an unfair proportion of the
2584 * physical cpu's resources. -ck
2585 */
2586 if (((smt_curr->time_slice * (100 - sd->per_cpu_gain) / 100) >
2587 task_timeslice(p) || rt_task(smt_curr)) &&
2588 p->mm && smt_curr->mm && !rt_task(p))
2589 ret = 1;
2590
2591 /*
2592 * Reschedule a lower priority task on the SMT sibling,
2593 * or wake it up if it has been put to sleep for priority
2594 * reasons.
2595 */
2596 if ((((p->time_slice * (100 - sd->per_cpu_gain) / 100) >
2597 task_timeslice(smt_curr) || rt_task(p)) &&
2598 smt_curr->mm && p->mm && !rt_task(smt_curr)) ||
2599 (smt_curr == smt_rq->idle && smt_rq->nr_running))
2600 resched_task(smt_curr);
2601 }
2602out_unlock:
2603 for_each_cpu_mask(i, sibling_map)
2604 spin_unlock(&cpu_rq(i)->lock);
2605 return ret;
2606}
2607#else
2608static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2609{
2610}
2611
2612static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2613{
2614 return 0;
2615}
2616#endif
2617
2618#if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
2619
2620void fastcall add_preempt_count(int val)
2621{
2622 /*
2623 * Underflow?
2624 */
be5b4fbd 2625 BUG_ON((preempt_count() < 0));
1da177e4
LT
2626 preempt_count() += val;
2627 /*
2628 * Spinlock count overflowing soon?
2629 */
2630 BUG_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
2631}
2632EXPORT_SYMBOL(add_preempt_count);
2633
2634void fastcall sub_preempt_count(int val)
2635{
2636 /*
2637 * Underflow?
2638 */
2639 BUG_ON(val > preempt_count());
2640 /*
2641 * Is the spinlock portion underflowing?
2642 */
2643 BUG_ON((val < PREEMPT_MASK) && !(preempt_count() & PREEMPT_MASK));
2644 preempt_count() -= val;
2645}
2646EXPORT_SYMBOL(sub_preempt_count);
2647
2648#endif
2649
2650/*
2651 * schedule() is the main scheduler function.
2652 */
2653asmlinkage void __sched schedule(void)
2654{
2655 long *switch_count;
2656 task_t *prev, *next;
2657 runqueue_t *rq;
2658 prio_array_t *array;
2659 struct list_head *queue;
2660 unsigned long long now;
2661 unsigned long run_time;
2662 int cpu, idx;
2663
2664 /*
2665 * Test if we are atomic. Since do_exit() needs to call into
2666 * schedule() atomically, we ignore that path for now.
2667 * Otherwise, whine if we are scheduling when we should not be.
2668 */
2669 if (likely(!current->exit_state)) {
2670 if (unlikely(in_atomic())) {
2671 printk(KERN_ERR "scheduling while atomic: "
2672 "%s/0x%08x/%d\n",
2673 current->comm, preempt_count(), current->pid);
2674 dump_stack();
2675 }
2676 }
2677 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
2678
2679need_resched:
2680 preempt_disable();
2681 prev = current;
2682 release_kernel_lock(prev);
2683need_resched_nonpreemptible:
2684 rq = this_rq();
2685
2686 /*
2687 * The idle thread is not allowed to schedule!
2688 * Remove this check after it has been exercised a bit.
2689 */
2690 if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
2691 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
2692 dump_stack();
2693 }
2694
2695 schedstat_inc(rq, sched_cnt);
2696 now = sched_clock();
238628ed 2697 if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
1da177e4 2698 run_time = now - prev->timestamp;
238628ed 2699 if (unlikely((long long)(now - prev->timestamp) < 0))
1da177e4
LT
2700 run_time = 0;
2701 } else
2702 run_time = NS_MAX_SLEEP_AVG;
2703
2704 /*
2705 * Tasks charged proportionately less run_time at high sleep_avg to
2706 * delay them losing their interactive status
2707 */
2708 run_time /= (CURRENT_BONUS(prev) ? : 1);
2709
2710 spin_lock_irq(&rq->lock);
2711
2712 if (unlikely(prev->flags & PF_DEAD))
2713 prev->state = EXIT_DEAD;
2714
2715 switch_count = &prev->nivcsw;
2716 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2717 switch_count = &prev->nvcsw;
2718 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2719 unlikely(signal_pending(prev))))
2720 prev->state = TASK_RUNNING;
2721 else {
2722 if (prev->state == TASK_UNINTERRUPTIBLE)
2723 rq->nr_uninterruptible++;
2724 deactivate_task(prev, rq);
2725 }
2726 }
2727
2728 cpu = smp_processor_id();
2729 if (unlikely(!rq->nr_running)) {
2730go_idle:
2731 idle_balance(cpu, rq);
2732 if (!rq->nr_running) {
2733 next = rq->idle;
2734 rq->expired_timestamp = 0;
2735 wake_sleeping_dependent(cpu, rq);
2736 /*
2737 * wake_sleeping_dependent() might have released
2738 * the runqueue, so break out if we got new
2739 * tasks meanwhile:
2740 */
2741 if (!rq->nr_running)
2742 goto switch_tasks;
2743 }
2744 } else {
2745 if (dependent_sleeper(cpu, rq)) {
2746 next = rq->idle;
2747 goto switch_tasks;
2748 }
2749 /*
2750 * dependent_sleeper() releases and reacquires the runqueue
2751 * lock, hence go into the idle loop if the rq went
2752 * empty meanwhile:
2753 */
2754 if (unlikely(!rq->nr_running))
2755 goto go_idle;
2756 }
2757
2758 array = rq->active;
2759 if (unlikely(!array->nr_active)) {
2760 /*
2761 * Switch the active and expired arrays.
2762 */
2763 schedstat_inc(rq, sched_switch);
2764 rq->active = rq->expired;
2765 rq->expired = array;
2766 array = rq->active;
2767 rq->expired_timestamp = 0;
2768 rq->best_expired_prio = MAX_PRIO;
2769 }
2770
2771 idx = sched_find_first_bit(array->bitmap);
2772 queue = array->queue + idx;
2773 next = list_entry(queue->next, task_t, run_list);
2774
2775 if (!rt_task(next) && next->activated > 0) {
2776 unsigned long long delta = now - next->timestamp;
238628ed 2777 if (unlikely((long long)(now - next->timestamp) < 0))
1da177e4
LT
2778 delta = 0;
2779
2780 if (next->activated == 1)
2781 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
2782
2783 array = next->array;
2784 dequeue_task(next, array);
2785 recalc_task_prio(next, next->timestamp + delta);
2786 enqueue_task(next, array);
2787 }
2788 next->activated = 0;
2789switch_tasks:
2790 if (next == rq->idle)
2791 schedstat_inc(rq, sched_goidle);
2792 prefetch(next);
2793 clear_tsk_need_resched(prev);
2794 rcu_qsctr_inc(task_cpu(prev));
2795
2796 update_cpu_clock(prev, rq, now);
2797
2798 prev->sleep_avg -= run_time;
2799 if ((long)prev->sleep_avg <= 0)
2800 prev->sleep_avg = 0;
2801 prev->timestamp = prev->last_ran = now;
2802
2803 sched_info_switch(prev, next);
2804 if (likely(prev != next)) {
2805 next->timestamp = now;
2806 rq->nr_switches++;
2807 rq->curr = next;
2808 ++*switch_count;
2809
2810 prepare_arch_switch(rq, next);
2811 prev = context_switch(rq, prev, next);
2812 barrier();
2813
2814 finish_task_switch(prev);
2815 } else
2816 spin_unlock_irq(&rq->lock);
2817
2818 prev = current;
2819 if (unlikely(reacquire_kernel_lock(prev) < 0))
2820 goto need_resched_nonpreemptible;
2821 preempt_enable_no_resched();
2822 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2823 goto need_resched;
2824}
2825
2826EXPORT_SYMBOL(schedule);
2827
2828#ifdef CONFIG_PREEMPT
2829/*
2830 * this is is the entry point to schedule() from in-kernel preemption
2831 * off of preempt_enable. Kernel preemptions off return from interrupt
2832 * occur there and call schedule directly.
2833 */
2834asmlinkage void __sched preempt_schedule(void)
2835{
2836 struct thread_info *ti = current_thread_info();
2837#ifdef CONFIG_PREEMPT_BKL
2838 struct task_struct *task = current;
2839 int saved_lock_depth;
2840#endif
2841 /*
2842 * If there is a non-zero preempt_count or interrupts are disabled,
2843 * we do not want to preempt the current task. Just return..
2844 */
2845 if (unlikely(ti->preempt_count || irqs_disabled()))
2846 return;
2847
2848need_resched:
2849 add_preempt_count(PREEMPT_ACTIVE);
2850 /*
2851 * We keep the big kernel semaphore locked, but we
2852 * clear ->lock_depth so that schedule() doesnt
2853 * auto-release the semaphore:
2854 */
2855#ifdef CONFIG_PREEMPT_BKL
2856 saved_lock_depth = task->lock_depth;
2857 task->lock_depth = -1;
2858#endif
2859 schedule();
2860#ifdef CONFIG_PREEMPT_BKL
2861 task->lock_depth = saved_lock_depth;
2862#endif
2863 sub_preempt_count(PREEMPT_ACTIVE);
2864
2865 /* we could miss a preemption opportunity between schedule and now */
2866 barrier();
2867 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2868 goto need_resched;
2869}
2870
2871EXPORT_SYMBOL(preempt_schedule);
2872
2873/*
2874 * this is is the entry point to schedule() from kernel preemption
2875 * off of irq context.
2876 * Note, that this is called and return with irqs disabled. This will
2877 * protect us against recursive calling from irq.
2878 */
2879asmlinkage void __sched preempt_schedule_irq(void)
2880{
2881 struct thread_info *ti = current_thread_info();
2882#ifdef CONFIG_PREEMPT_BKL
2883 struct task_struct *task = current;
2884 int saved_lock_depth;
2885#endif
2886 /* Catch callers which need to be fixed*/
2887 BUG_ON(ti->preempt_count || !irqs_disabled());
2888
2889need_resched:
2890 add_preempt_count(PREEMPT_ACTIVE);
2891 /*
2892 * We keep the big kernel semaphore locked, but we
2893 * clear ->lock_depth so that schedule() doesnt
2894 * auto-release the semaphore:
2895 */
2896#ifdef CONFIG_PREEMPT_BKL
2897 saved_lock_depth = task->lock_depth;
2898 task->lock_depth = -1;
2899#endif
2900 local_irq_enable();
2901 schedule();
2902 local_irq_disable();
2903#ifdef CONFIG_PREEMPT_BKL
2904 task->lock_depth = saved_lock_depth;
2905#endif
2906 sub_preempt_count(PREEMPT_ACTIVE);
2907
2908 /* we could miss a preemption opportunity between schedule and now */
2909 barrier();
2910 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
2911 goto need_resched;
2912}
2913
2914#endif /* CONFIG_PREEMPT */
2915
2916int default_wake_function(wait_queue_t *curr, unsigned mode, int sync, void *key)
2917{
c43dc2fd 2918 task_t *p = curr->private;
1da177e4
LT
2919 return try_to_wake_up(p, mode, sync);
2920}
2921
2922EXPORT_SYMBOL(default_wake_function);
2923
2924/*
2925 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
2926 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
2927 * number) then we wake all the non-exclusive tasks and one exclusive task.
2928 *
2929 * There are circumstances in which we can try to wake a task which has already
2930 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
2931 * zero in this (rare) case, and we handle it by continuing to scan the queue.
2932 */
2933static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
2934 int nr_exclusive, int sync, void *key)
2935{
2936 struct list_head *tmp, *next;
2937
2938 list_for_each_safe(tmp, next, &q->task_list) {
2939 wait_queue_t *curr;
2940 unsigned flags;
2941 curr = list_entry(tmp, wait_queue_t, task_list);
2942 flags = curr->flags;
2943 if (curr->func(curr, mode, sync, key) &&
2944 (flags & WQ_FLAG_EXCLUSIVE) &&
2945 !--nr_exclusive)
2946 break;
2947 }
2948}
2949
2950/**
2951 * __wake_up - wake up threads blocked on a waitqueue.
2952 * @q: the waitqueue
2953 * @mode: which threads
2954 * @nr_exclusive: how many wake-one or wake-many threads to wake up
67be2dd1 2955 * @key: is directly passed to the wakeup function
1da177e4
LT
2956 */
2957void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
2958 int nr_exclusive, void *key)
2959{
2960 unsigned long flags;
2961
2962 spin_lock_irqsave(&q->lock, flags);
2963 __wake_up_common(q, mode, nr_exclusive, 0, key);
2964 spin_unlock_irqrestore(&q->lock, flags);
2965}
2966
2967EXPORT_SYMBOL(__wake_up);
2968
2969/*
2970 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
2971 */
2972void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
2973{
2974 __wake_up_common(q, mode, 1, 0, NULL);
2975}
2976
2977/**
67be2dd1 2978 * __wake_up_sync - wake up threads blocked on a waitqueue.
1da177e4
LT
2979 * @q: the waitqueue
2980 * @mode: which threads
2981 * @nr_exclusive: how many wake-one or wake-many threads to wake up
2982 *
2983 * The sync wakeup differs that the waker knows that it will schedule
2984 * away soon, so while the target thread will be woken up, it will not
2985 * be migrated to another CPU - ie. the two threads are 'synchronized'
2986 * with each other. This can prevent needless bouncing between CPUs.
2987 *
2988 * On UP it can prevent extra preemption.
2989 */
2990void fastcall __wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
2991{
2992 unsigned long flags;
2993 int sync = 1;
2994
2995 if (unlikely(!q))
2996 return;
2997
2998 if (unlikely(!nr_exclusive))
2999 sync = 0;
3000
3001 spin_lock_irqsave(&q->lock, flags);
3002 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3003 spin_unlock_irqrestore(&q->lock, flags);
3004}
3005EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3006
3007void fastcall complete(struct completion *x)
3008{
3009 unsigned long flags;
3010
3011 spin_lock_irqsave(&x->wait.lock, flags);
3012 x->done++;
3013 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3014 1, 0, NULL);
3015 spin_unlock_irqrestore(&x->wait.lock, flags);
3016}
3017EXPORT_SYMBOL(complete);
3018
3019void fastcall complete_all(struct completion *x)
3020{
3021 unsigned long flags;
3022
3023 spin_lock_irqsave(&x->wait.lock, flags);
3024 x->done += UINT_MAX/2;
3025 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3026 0, 0, NULL);
3027 spin_unlock_irqrestore(&x->wait.lock, flags);
3028}
3029EXPORT_SYMBOL(complete_all);
3030
3031void fastcall __sched wait_for_completion(struct completion *x)
3032{
3033 might_sleep();
3034 spin_lock_irq(&x->wait.lock);
3035 if (!x->done) {
3036 DECLARE_WAITQUEUE(wait, current);
3037
3038 wait.flags |= WQ_FLAG_EXCLUSIVE;
3039 __add_wait_queue_tail(&x->wait, &wait);
3040 do {
3041 __set_current_state(TASK_UNINTERRUPTIBLE);
3042 spin_unlock_irq(&x->wait.lock);
3043 schedule();
3044 spin_lock_irq(&x->wait.lock);
3045 } while (!x->done);
3046 __remove_wait_queue(&x->wait, &wait);
3047 }
3048 x->done--;
3049 spin_unlock_irq(&x->wait.lock);
3050}
3051EXPORT_SYMBOL(wait_for_completion);
3052
3053unsigned long fastcall __sched
3054wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3055{
3056 might_sleep();
3057
3058 spin_lock_irq(&x->wait.lock);
3059 if (!x->done) {
3060 DECLARE_WAITQUEUE(wait, current);
3061
3062 wait.flags |= WQ_FLAG_EXCLUSIVE;
3063 __add_wait_queue_tail(&x->wait, &wait);
3064 do {
3065 __set_current_state(TASK_UNINTERRUPTIBLE);
3066 spin_unlock_irq(&x->wait.lock);
3067 timeout = schedule_timeout(timeout);
3068 spin_lock_irq(&x->wait.lock);
3069 if (!timeout) {
3070 __remove_wait_queue(&x->wait, &wait);
3071 goto out;
3072 }
3073 } while (!x->done);
3074 __remove_wait_queue(&x->wait, &wait);
3075 }
3076 x->done--;
3077out:
3078 spin_unlock_irq(&x->wait.lock);
3079 return timeout;
3080}
3081EXPORT_SYMBOL(wait_for_completion_timeout);
3082
3083int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3084{
3085 int ret = 0;
3086
3087 might_sleep();
3088
3089 spin_lock_irq(&x->wait.lock);
3090 if (!x->done) {
3091 DECLARE_WAITQUEUE(wait, current);
3092
3093 wait.flags |= WQ_FLAG_EXCLUSIVE;
3094 __add_wait_queue_tail(&x->wait, &wait);
3095 do {
3096 if (signal_pending(current)) {
3097 ret = -ERESTARTSYS;
3098 __remove_wait_queue(&x->wait, &wait);
3099 goto out;
3100 }
3101 __set_current_state(TASK_INTERRUPTIBLE);
3102 spin_unlock_irq(&x->wait.lock);
3103 schedule();
3104 spin_lock_irq(&x->wait.lock);
3105 } while (!x->done);
3106 __remove_wait_queue(&x->wait, &wait);
3107 }
3108 x->done--;
3109out:
3110 spin_unlock_irq(&x->wait.lock);
3111
3112 return ret;
3113}
3114EXPORT_SYMBOL(wait_for_completion_interruptible);
3115
3116unsigned long fastcall __sched
3117wait_for_completion_interruptible_timeout(struct completion *x,
3118 unsigned long timeout)
3119{
3120 might_sleep();
3121
3122 spin_lock_irq(&x->wait.lock);
3123 if (!x->done) {
3124 DECLARE_WAITQUEUE(wait, current);
3125
3126 wait.flags |= WQ_FLAG_EXCLUSIVE;
3127 __add_wait_queue_tail(&x->wait, &wait);
3128 do {
3129 if (signal_pending(current)) {
3130 timeout = -ERESTARTSYS;
3131 __remove_wait_queue(&x->wait, &wait);
3132 goto out;
3133 }
3134 __set_current_state(TASK_INTERRUPTIBLE);
3135 spin_unlock_irq(&x->wait.lock);
3136 timeout = schedule_timeout(timeout);
3137 spin_lock_irq(&x->wait.lock);
3138 if (!timeout) {
3139 __remove_wait_queue(&x->wait, &wait);
3140 goto out;
3141 }
3142 } while (!x->done);
3143 __remove_wait_queue(&x->wait, &wait);
3144 }
3145 x->done--;
3146out:
3147 spin_unlock_irq(&x->wait.lock);
3148 return timeout;
3149}
3150EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3151
3152
3153#define SLEEP_ON_VAR \
3154 unsigned long flags; \
3155 wait_queue_t wait; \
3156 init_waitqueue_entry(&wait, current);
3157
3158#define SLEEP_ON_HEAD \
3159 spin_lock_irqsave(&q->lock,flags); \
3160 __add_wait_queue(q, &wait); \
3161 spin_unlock(&q->lock);
3162
3163#define SLEEP_ON_TAIL \
3164 spin_lock_irq(&q->lock); \
3165 __remove_wait_queue(q, &wait); \
3166 spin_unlock_irqrestore(&q->lock, flags);
3167
3168void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3169{
3170 SLEEP_ON_VAR
3171
3172 current->state = TASK_INTERRUPTIBLE;
3173
3174 SLEEP_ON_HEAD
3175 schedule();
3176 SLEEP_ON_TAIL
3177}
3178
3179EXPORT_SYMBOL(interruptible_sleep_on);
3180
3181long fastcall __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
3182{
3183 SLEEP_ON_VAR
3184
3185 current->state = TASK_INTERRUPTIBLE;
3186
3187 SLEEP_ON_HEAD
3188 timeout = schedule_timeout(timeout);
3189 SLEEP_ON_TAIL
3190
3191 return timeout;
3192}
3193
3194EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3195
3196void fastcall __sched sleep_on(wait_queue_head_t *q)
3197{
3198 SLEEP_ON_VAR
3199
3200 current->state = TASK_UNINTERRUPTIBLE;
3201
3202 SLEEP_ON_HEAD
3203 schedule();
3204 SLEEP_ON_TAIL
3205}
3206
3207EXPORT_SYMBOL(sleep_on);
3208
3209long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3210{
3211 SLEEP_ON_VAR
3212
3213 current->state = TASK_UNINTERRUPTIBLE;
3214
3215 SLEEP_ON_HEAD
3216 timeout = schedule_timeout(timeout);
3217 SLEEP_ON_TAIL
3218
3219 return timeout;
3220}
3221
3222EXPORT_SYMBOL(sleep_on_timeout);
3223
3224void set_user_nice(task_t *p, long nice)
3225{
3226 unsigned long flags;
3227 prio_array_t *array;
3228 runqueue_t *rq;
3229 int old_prio, new_prio, delta;
3230
3231 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3232 return;
3233 /*
3234 * We have to be careful, if called from sys_setpriority(),
3235 * the task might be in the middle of scheduling on another CPU.
3236 */
3237 rq = task_rq_lock(p, &flags);
3238 /*
3239 * The RT priorities are set via sched_setscheduler(), but we still
3240 * allow the 'normal' nice value to be set - but as expected
3241 * it wont have any effect on scheduling until the task is
3242 * not SCHED_NORMAL:
3243 */
3244 if (rt_task(p)) {
3245 p->static_prio = NICE_TO_PRIO(nice);
3246 goto out_unlock;
3247 }
3248 array = p->array;
3249 if (array)
3250 dequeue_task(p, array);
3251
3252 old_prio = p->prio;
3253 new_prio = NICE_TO_PRIO(nice);
3254 delta = new_prio - old_prio;
3255 p->static_prio = NICE_TO_PRIO(nice);
3256 p->prio += delta;
3257
3258 if (array) {
3259 enqueue_task(p, array);
3260 /*
3261 * If the task increased its priority or is running and
3262 * lowered its priority, then reschedule its CPU:
3263 */
3264 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3265 resched_task(rq->curr);
3266 }
3267out_unlock:
3268 task_rq_unlock(rq, &flags);
3269}
3270
3271EXPORT_SYMBOL(set_user_nice);
3272
e43379f1
MM
3273/*
3274 * can_nice - check if a task can reduce its nice value
3275 * @p: task
3276 * @nice: nice value
3277 */
3278int can_nice(const task_t *p, const int nice)
3279{
3280 /* convert nice value [19,-20] to rlimit style value [0,39] */
3281 int nice_rlim = 19 - nice;
3282 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
3283 capable(CAP_SYS_NICE));
3284}
3285
1da177e4
LT
3286#ifdef __ARCH_WANT_SYS_NICE
3287
3288/*
3289 * sys_nice - change the priority of the current process.
3290 * @increment: priority increment
3291 *
3292 * sys_setpriority is a more generic, but much slower function that
3293 * does similar things.
3294 */
3295asmlinkage long sys_nice(int increment)
3296{
3297 int retval;
3298 long nice;
3299
3300 /*
3301 * Setpriority might change our priority at the same moment.
3302 * We don't have to worry. Conceptually one call occurs first
3303 * and we have a single winner.
3304 */
e43379f1
MM
3305 if (increment < -40)
3306 increment = -40;
1da177e4
LT
3307 if (increment > 40)
3308 increment = 40;
3309
3310 nice = PRIO_TO_NICE(current->static_prio) + increment;
3311 if (nice < -20)
3312 nice = -20;
3313 if (nice > 19)
3314 nice = 19;
3315
e43379f1
MM
3316 if (increment < 0 && !can_nice(current, nice))
3317 return -EPERM;
3318
1da177e4
LT
3319 retval = security_task_setnice(current, nice);
3320 if (retval)
3321 return retval;
3322
3323 set_user_nice(current, nice);
3324 return 0;
3325}
3326
3327#endif
3328
3329/**
3330 * task_prio - return the priority value of a given task.
3331 * @p: the task in question.
3332 *
3333 * This is the priority value as seen by users in /proc.
3334 * RT tasks are offset by -200. Normal tasks are centered
3335 * around 0, value goes from -16 to +15.
3336 */
3337int task_prio(const task_t *p)
3338{
3339 return p->prio - MAX_RT_PRIO;
3340}
3341
3342/**
3343 * task_nice - return the nice value of a given task.
3344 * @p: the task in question.
3345 */
3346int task_nice(const task_t *p)
3347{
3348 return TASK_NICE(p);
3349}
3350
3351/*
3352 * The only users of task_nice are binfmt_elf and binfmt_elf32.
3353 * binfmt_elf is no longer modular, but binfmt_elf32 still is.
3354 * Therefore, task_nice is needed if there is a compat_mode.
3355 */
3356#ifdef CONFIG_COMPAT
3357EXPORT_SYMBOL_GPL(task_nice);
3358#endif
3359
3360/**
3361 * idle_cpu - is a given cpu idle currently?
3362 * @cpu: the processor in question.
3363 */
3364int idle_cpu(int cpu)
3365{
3366 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3367}
3368
3369EXPORT_SYMBOL_GPL(idle_cpu);
3370
3371/**
3372 * idle_task - return the idle task for a given cpu.
3373 * @cpu: the processor in question.
3374 */
3375task_t *idle_task(int cpu)
3376{
3377 return cpu_rq(cpu)->idle;
3378}
3379
3380/**
3381 * find_process_by_pid - find a process with a matching PID value.
3382 * @pid: the pid in question.
3383 */
3384static inline task_t *find_process_by_pid(pid_t pid)
3385{
3386 return pid ? find_task_by_pid(pid) : current;
3387}
3388
3389/* Actually do priority change: must hold rq lock. */
3390static void __setscheduler(struct task_struct *p, int policy, int prio)
3391{
3392 BUG_ON(p->array);
3393 p->policy = policy;
3394 p->rt_priority = prio;
3395 if (policy != SCHED_NORMAL)
3396 p->prio = MAX_USER_RT_PRIO-1 - p->rt_priority;
3397 else
3398 p->prio = p->static_prio;
3399}
3400
3401/**
3402 * sched_setscheduler - change the scheduling policy and/or RT priority of
3403 * a thread.
3404 * @p: the task in question.
3405 * @policy: new policy.
3406 * @param: structure containing the new RT priority.
3407 */
3408int sched_setscheduler(struct task_struct *p, int policy, struct sched_param *param)
3409{
3410 int retval;
3411 int oldprio, oldpolicy = -1;
3412 prio_array_t *array;
3413 unsigned long flags;
3414 runqueue_t *rq;
3415
3416recheck:
3417 /* double check policy once rq lock held */
3418 if (policy < 0)
3419 policy = oldpolicy = p->policy;
3420 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
3421 policy != SCHED_NORMAL)
3422 return -EINVAL;
3423 /*
3424 * Valid priorities for SCHED_FIFO and SCHED_RR are
3425 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL is 0.
3426 */
3427 if (param->sched_priority < 0 ||
3428 param->sched_priority > MAX_USER_RT_PRIO-1)
3429 return -EINVAL;
3430 if ((policy == SCHED_NORMAL) != (param->sched_priority == 0))
3431 return -EINVAL;
3432
3433 if ((policy == SCHED_FIFO || policy == SCHED_RR) &&
e43379f1 3434 param->sched_priority > p->signal->rlim[RLIMIT_RTPRIO].rlim_cur &&
1da177e4
LT
3435 !capable(CAP_SYS_NICE))
3436 return -EPERM;
3437 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3438 !capable(CAP_SYS_NICE))
3439 return -EPERM;
3440
3441 retval = security_task_setscheduler(p, policy, param);
3442 if (retval)
3443 return retval;
3444 /*
3445 * To be able to change p->policy safely, the apropriate
3446 * runqueue lock must be held.
3447 */
3448 rq = task_rq_lock(p, &flags);
3449 /* recheck policy now with rq lock held */
3450 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3451 policy = oldpolicy = -1;
3452 task_rq_unlock(rq, &flags);
3453 goto recheck;
3454 }
3455 array = p->array;
3456 if (array)
3457 deactivate_task(p, rq);
3458 oldprio = p->prio;
3459 __setscheduler(p, policy, param->sched_priority);
3460 if (array) {
3461 __activate_task(p, rq);
3462 /*
3463 * Reschedule if we are currently running on this runqueue and
3464 * our priority decreased, or if we are not currently running on
3465 * this runqueue and our priority is higher than the current's
3466 */
3467 if (task_running(rq, p)) {
3468 if (p->prio > oldprio)
3469 resched_task(rq->curr);
3470 } else if (TASK_PREEMPTS_CURR(p, rq))
3471 resched_task(rq->curr);
3472 }
3473 task_rq_unlock(rq, &flags);
3474 return 0;
3475}
3476EXPORT_SYMBOL_GPL(sched_setscheduler);
3477
3478static int do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
3479{
3480 int retval;
3481 struct sched_param lparam;
3482 struct task_struct *p;
3483
3484 if (!param || pid < 0)
3485 return -EINVAL;
3486 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
3487 return -EFAULT;
3488 read_lock_irq(&tasklist_lock);
3489 p = find_process_by_pid(pid);
3490 if (!p) {
3491 read_unlock_irq(&tasklist_lock);
3492 return -ESRCH;
3493 }
3494 retval = sched_setscheduler(p, policy, &lparam);
3495 read_unlock_irq(&tasklist_lock);
3496 return retval;
3497}
3498
3499/**
3500 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3501 * @pid: the pid in question.
3502 * @policy: new policy.
3503 * @param: structure containing the new RT priority.
3504 */
3505asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3506 struct sched_param __user *param)
3507{
3508 return do_sched_setscheduler(pid, policy, param);
3509}
3510
3511/**
3512 * sys_sched_setparam - set/change the RT priority of a thread
3513 * @pid: the pid in question.
3514 * @param: structure containing the new RT priority.
3515 */
3516asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3517{
3518 return do_sched_setscheduler(pid, -1, param);
3519}
3520
3521/**
3522 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3523 * @pid: the pid in question.
3524 */
3525asmlinkage long sys_sched_getscheduler(pid_t pid)
3526{
3527 int retval = -EINVAL;
3528 task_t *p;
3529
3530 if (pid < 0)
3531 goto out_nounlock;
3532
3533 retval = -ESRCH;
3534 read_lock(&tasklist_lock);
3535 p = find_process_by_pid(pid);
3536 if (p) {
3537 retval = security_task_getscheduler(p);
3538 if (!retval)
3539 retval = p->policy;
3540 }
3541 read_unlock(&tasklist_lock);
3542
3543out_nounlock:
3544 return retval;
3545}
3546
3547/**
3548 * sys_sched_getscheduler - get the RT priority of a thread
3549 * @pid: the pid in question.
3550 * @param: structure containing the RT priority.
3551 */
3552asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3553{
3554 struct sched_param lp;
3555 int retval = -EINVAL;
3556 task_t *p;
3557
3558 if (!param || pid < 0)
3559 goto out_nounlock;
3560
3561 read_lock(&tasklist_lock);
3562 p = find_process_by_pid(pid);
3563 retval = -ESRCH;
3564 if (!p)
3565 goto out_unlock;
3566
3567 retval = security_task_getscheduler(p);
3568 if (retval)
3569 goto out_unlock;
3570
3571 lp.sched_priority = p->rt_priority;
3572 read_unlock(&tasklist_lock);
3573
3574 /*
3575 * This one might sleep, we cannot do it with a spinlock held ...
3576 */
3577 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3578
3579out_nounlock:
3580 return retval;
3581
3582out_unlock:
3583 read_unlock(&tasklist_lock);
3584 return retval;
3585}
3586
3587long sched_setaffinity(pid_t pid, cpumask_t new_mask)
3588{
3589 task_t *p;
3590 int retval;
3591 cpumask_t cpus_allowed;
3592
3593 lock_cpu_hotplug();
3594 read_lock(&tasklist_lock);
3595
3596 p = find_process_by_pid(pid);
3597 if (!p) {
3598 read_unlock(&tasklist_lock);
3599 unlock_cpu_hotplug();
3600 return -ESRCH;
3601 }
3602
3603 /*
3604 * It is not safe to call set_cpus_allowed with the
3605 * tasklist_lock held. We will bump the task_struct's
3606 * usage count and then drop tasklist_lock.
3607 */
3608 get_task_struct(p);
3609 read_unlock(&tasklist_lock);
3610
3611 retval = -EPERM;
3612 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3613 !capable(CAP_SYS_NICE))
3614 goto out_unlock;
3615
3616 cpus_allowed = cpuset_cpus_allowed(p);
3617 cpus_and(new_mask, new_mask, cpus_allowed);
3618 retval = set_cpus_allowed(p, new_mask);
3619
3620out_unlock:
3621 put_task_struct(p);
3622 unlock_cpu_hotplug();
3623 return retval;
3624}
3625
3626static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
3627 cpumask_t *new_mask)
3628{
3629 if (len < sizeof(cpumask_t)) {
3630 memset(new_mask, 0, sizeof(cpumask_t));
3631 } else if (len > sizeof(cpumask_t)) {
3632 len = sizeof(cpumask_t);
3633 }
3634 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
3635}
3636
3637/**
3638 * sys_sched_setaffinity - set the cpu affinity of a process
3639 * @pid: pid of the process
3640 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3641 * @user_mask_ptr: user-space pointer to the new cpu mask
3642 */
3643asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
3644 unsigned long __user *user_mask_ptr)
3645{
3646 cpumask_t new_mask;
3647 int retval;
3648
3649 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
3650 if (retval)
3651 return retval;
3652
3653 return sched_setaffinity(pid, new_mask);
3654}
3655
3656/*
3657 * Represents all cpu's present in the system
3658 * In systems capable of hotplug, this map could dynamically grow
3659 * as new cpu's are detected in the system via any platform specific
3660 * method, such as ACPI for e.g.
3661 */
3662
3663cpumask_t cpu_present_map;
3664EXPORT_SYMBOL(cpu_present_map);
3665
3666#ifndef CONFIG_SMP
3667cpumask_t cpu_online_map = CPU_MASK_ALL;
3668cpumask_t cpu_possible_map = CPU_MASK_ALL;
3669#endif
3670
3671long sched_getaffinity(pid_t pid, cpumask_t *mask)
3672{
3673 int retval;
3674 task_t *p;
3675
3676 lock_cpu_hotplug();
3677 read_lock(&tasklist_lock);
3678
3679 retval = -ESRCH;
3680 p = find_process_by_pid(pid);
3681 if (!p)
3682 goto out_unlock;
3683
3684 retval = 0;
3685 cpus_and(*mask, p->cpus_allowed, cpu_possible_map);
3686
3687out_unlock:
3688 read_unlock(&tasklist_lock);
3689 unlock_cpu_hotplug();
3690 if (retval)
3691 return retval;
3692
3693 return 0;
3694}
3695
3696/**
3697 * sys_sched_getaffinity - get the cpu affinity of a process
3698 * @pid: pid of the process
3699 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3700 * @user_mask_ptr: user-space pointer to hold the current cpu mask
3701 */
3702asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
3703 unsigned long __user *user_mask_ptr)
3704{
3705 int ret;
3706 cpumask_t mask;
3707
3708 if (len < sizeof(cpumask_t))
3709 return -EINVAL;
3710
3711 ret = sched_getaffinity(pid, &mask);
3712 if (ret < 0)
3713 return ret;
3714
3715 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
3716 return -EFAULT;
3717
3718 return sizeof(cpumask_t);
3719}
3720
3721/**
3722 * sys_sched_yield - yield the current processor to other threads.
3723 *
3724 * this function yields the current CPU by moving the calling thread
3725 * to the expired array. If there are no other threads running on this
3726 * CPU then this function will return.
3727 */
3728asmlinkage long sys_sched_yield(void)
3729{
3730 runqueue_t *rq = this_rq_lock();
3731 prio_array_t *array = current->array;
3732 prio_array_t *target = rq->expired;
3733
3734 schedstat_inc(rq, yld_cnt);
3735 /*
3736 * We implement yielding by moving the task into the expired
3737 * queue.
3738 *
3739 * (special rule: RT tasks will just roundrobin in the active
3740 * array.)
3741 */
3742 if (rt_task(current))
3743 target = rq->active;
3744
3745 if (current->array->nr_active == 1) {
3746 schedstat_inc(rq, yld_act_empty);
3747 if (!rq->expired->nr_active)
3748 schedstat_inc(rq, yld_both_empty);
3749 } else if (!rq->expired->nr_active)
3750 schedstat_inc(rq, yld_exp_empty);
3751
3752 if (array != target) {
3753 dequeue_task(current, array);
3754 enqueue_task(current, target);
3755 } else
3756 /*
3757 * requeue_task is cheaper so perform that if possible.
3758 */
3759 requeue_task(current, array);
3760
3761 /*
3762 * Since we are going to call schedule() anyway, there's
3763 * no need to preempt or enable interrupts:
3764 */
3765 __release(rq->lock);
3766 _raw_spin_unlock(&rq->lock);
3767 preempt_enable_no_resched();
3768
3769 schedule();
3770
3771 return 0;
3772}
3773
3774static inline void __cond_resched(void)
3775{
3776 do {
3777 add_preempt_count(PREEMPT_ACTIVE);
3778 schedule();
3779 sub_preempt_count(PREEMPT_ACTIVE);
3780 } while (need_resched());
3781}
3782
3783int __sched cond_resched(void)
3784{
3785 if (need_resched()) {
3786 __cond_resched();
3787 return 1;
3788 }
3789 return 0;
3790}
3791
3792EXPORT_SYMBOL(cond_resched);
3793
3794/*
3795 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
3796 * call schedule, and on return reacquire the lock.
3797 *
3798 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
3799 * operations here to prevent schedule() from being called twice (once via
3800 * spin_unlock(), once by hand).
3801 */
3802int cond_resched_lock(spinlock_t * lock)
3803{
6df3cecb
JK
3804 int ret = 0;
3805
1da177e4
LT
3806 if (need_lockbreak(lock)) {
3807 spin_unlock(lock);
3808 cpu_relax();
6df3cecb 3809 ret = 1;
1da177e4
LT
3810 spin_lock(lock);
3811 }
3812 if (need_resched()) {
3813 _raw_spin_unlock(lock);
3814 preempt_enable_no_resched();
3815 __cond_resched();
6df3cecb 3816 ret = 1;
1da177e4 3817 spin_lock(lock);
1da177e4 3818 }
6df3cecb 3819 return ret;
1da177e4
LT
3820}
3821
3822EXPORT_SYMBOL(cond_resched_lock);
3823
3824int __sched cond_resched_softirq(void)
3825{
3826 BUG_ON(!in_softirq());
3827
3828 if (need_resched()) {
3829 __local_bh_enable();
3830 __cond_resched();
3831 local_bh_disable();
3832 return 1;
3833 }
3834 return 0;
3835}
3836
3837EXPORT_SYMBOL(cond_resched_softirq);
3838
3839
3840/**
3841 * yield - yield the current processor to other threads.
3842 *
3843 * this is a shortcut for kernel-space yielding - it marks the
3844 * thread runnable and calls sys_sched_yield().
3845 */
3846void __sched yield(void)
3847{
3848 set_current_state(TASK_RUNNING);
3849 sys_sched_yield();
3850}
3851
3852EXPORT_SYMBOL(yield);
3853
3854/*
3855 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
3856 * that process accounting knows that this is a task in IO wait state.
3857 *
3858 * But don't do that if it is a deliberate, throttling IO wait (this task
3859 * has set its backing_dev_info: the queue against which it should throttle)
3860 */
3861void __sched io_schedule(void)
3862{
39c715b7 3863 struct runqueue *rq = &per_cpu(runqueues, raw_smp_processor_id());
1da177e4
LT
3864
3865 atomic_inc(&rq->nr_iowait);
3866 schedule();
3867 atomic_dec(&rq->nr_iowait);
3868}
3869
3870EXPORT_SYMBOL(io_schedule);
3871
3872long __sched io_schedule_timeout(long timeout)
3873{
39c715b7 3874 struct runqueue *rq = &per_cpu(runqueues, raw_smp_processor_id());
1da177e4
LT
3875 long ret;
3876
3877 atomic_inc(&rq->nr_iowait);
3878 ret = schedule_timeout(timeout);
3879 atomic_dec(&rq->nr_iowait);
3880 return ret;
3881}
3882
3883/**
3884 * sys_sched_get_priority_max - return maximum RT priority.
3885 * @policy: scheduling class.
3886 *
3887 * this syscall returns the maximum rt_priority that can be used
3888 * by a given scheduling class.
3889 */
3890asmlinkage long sys_sched_get_priority_max(int policy)
3891{
3892 int ret = -EINVAL;
3893
3894 switch (policy) {
3895 case SCHED_FIFO:
3896 case SCHED_RR:
3897 ret = MAX_USER_RT_PRIO-1;
3898 break;
3899 case SCHED_NORMAL:
3900 ret = 0;
3901 break;
3902 }
3903 return ret;
3904}
3905
3906/**
3907 * sys_sched_get_priority_min - return minimum RT priority.
3908 * @policy: scheduling class.
3909 *
3910 * this syscall returns the minimum rt_priority that can be used
3911 * by a given scheduling class.
3912 */
3913asmlinkage long sys_sched_get_priority_min(int policy)
3914{
3915 int ret = -EINVAL;
3916
3917 switch (policy) {
3918 case SCHED_FIFO:
3919 case SCHED_RR:
3920 ret = 1;
3921 break;
3922 case SCHED_NORMAL:
3923 ret = 0;
3924 }
3925 return ret;
3926}
3927
3928/**
3929 * sys_sched_rr_get_interval - return the default timeslice of a process.
3930 * @pid: pid of the process.
3931 * @interval: userspace pointer to the timeslice value.
3932 *
3933 * this syscall writes the default timeslice value of a given process
3934 * into the user-space timespec buffer. A value of '0' means infinity.
3935 */
3936asmlinkage
3937long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
3938{
3939 int retval = -EINVAL;
3940 struct timespec t;
3941 task_t *p;
3942
3943 if (pid < 0)
3944 goto out_nounlock;
3945
3946 retval = -ESRCH;
3947 read_lock(&tasklist_lock);
3948 p = find_process_by_pid(pid);
3949 if (!p)
3950 goto out_unlock;
3951
3952 retval = security_task_getscheduler(p);
3953 if (retval)
3954 goto out_unlock;
3955
3956 jiffies_to_timespec(p->policy & SCHED_FIFO ?
3957 0 : task_timeslice(p), &t);
3958 read_unlock(&tasklist_lock);
3959 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
3960out_nounlock:
3961 return retval;
3962out_unlock:
3963 read_unlock(&tasklist_lock);
3964 return retval;
3965}
3966
3967static inline struct task_struct *eldest_child(struct task_struct *p)
3968{
3969 if (list_empty(&p->children)) return NULL;
3970 return list_entry(p->children.next,struct task_struct,sibling);
3971}
3972
3973static inline struct task_struct *older_sibling(struct task_struct *p)
3974{
3975 if (p->sibling.prev==&p->parent->children) return NULL;
3976 return list_entry(p->sibling.prev,struct task_struct,sibling);
3977}
3978
3979static inline struct task_struct *younger_sibling(struct task_struct *p)
3980{
3981 if (p->sibling.next==&p->parent->children) return NULL;
3982 return list_entry(p->sibling.next,struct task_struct,sibling);
3983}
3984
3985static void show_task(task_t * p)
3986{
3987 task_t *relative;
3988 unsigned state;
3989 unsigned long free = 0;
3990 static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
3991
3992 printk("%-13.13s ", p->comm);
3993 state = p->state ? __ffs(p->state) + 1 : 0;
3994 if (state < ARRAY_SIZE(stat_nam))
3995 printk(stat_nam[state]);
3996 else
3997 printk("?");
3998#if (BITS_PER_LONG == 32)
3999 if (state == TASK_RUNNING)
4000 printk(" running ");
4001 else
4002 printk(" %08lX ", thread_saved_pc(p));
4003#else
4004 if (state == TASK_RUNNING)
4005 printk(" running task ");
4006 else
4007 printk(" %016lx ", thread_saved_pc(p));
4008#endif
4009#ifdef CONFIG_DEBUG_STACK_USAGE
4010 {
4011 unsigned long * n = (unsigned long *) (p->thread_info+1);
4012 while (!*n)
4013 n++;
4014 free = (unsigned long) n - (unsigned long)(p->thread_info+1);
4015 }
4016#endif
4017 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
4018 if ((relative = eldest_child(p)))
4019 printk("%5d ", relative->pid);
4020 else
4021 printk(" ");
4022 if ((relative = younger_sibling(p)))
4023 printk("%7d", relative->pid);
4024 else
4025 printk(" ");
4026 if ((relative = older_sibling(p)))
4027 printk(" %5d", relative->pid);
4028 else
4029 printk(" ");
4030 if (!p->mm)
4031 printk(" (L-TLB)\n");
4032 else
4033 printk(" (NOTLB)\n");
4034
4035 if (state != TASK_RUNNING)
4036 show_stack(p, NULL);
4037}
4038
4039void show_state(void)
4040{
4041 task_t *g, *p;
4042
4043#if (BITS_PER_LONG == 32)
4044 printk("\n"
4045 " sibling\n");
4046 printk(" task PC pid father child younger older\n");
4047#else
4048 printk("\n"
4049 " sibling\n");
4050 printk(" task PC pid father child younger older\n");
4051#endif
4052 read_lock(&tasklist_lock);
4053 do_each_thread(g, p) {
4054 /*
4055 * reset the NMI-timeout, listing all files on a slow
4056 * console might take alot of time:
4057 */
4058 touch_nmi_watchdog();
4059 show_task(p);
4060 } while_each_thread(g, p);
4061
4062 read_unlock(&tasklist_lock);
4063}
4064
4065void __devinit init_idle(task_t *idle, int cpu)
4066{
4067 runqueue_t *rq = cpu_rq(cpu);
4068 unsigned long flags;
4069
4070 idle->sleep_avg = 0;
4071 idle->array = NULL;
4072 idle->prio = MAX_PRIO;
4073 idle->state = TASK_RUNNING;
4074 idle->cpus_allowed = cpumask_of_cpu(cpu);
4075 set_task_cpu(idle, cpu);
4076
4077 spin_lock_irqsave(&rq->lock, flags);
4078 rq->curr = rq->idle = idle;
4079 set_tsk_need_resched(idle);
4080 spin_unlock_irqrestore(&rq->lock, flags);
4081
4082 /* Set the preempt count _outside_ the spinlocks! */
4083#if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
4084 idle->thread_info->preempt_count = (idle->lock_depth >= 0);
4085#else
4086 idle->thread_info->preempt_count = 0;
4087#endif
4088}
4089
4090/*
4091 * In a system that switches off the HZ timer nohz_cpu_mask
4092 * indicates which cpus entered this state. This is used
4093 * in the rcu update to wait only for active cpus. For system
4094 * which do not switch off the HZ timer nohz_cpu_mask should
4095 * always be CPU_MASK_NONE.
4096 */
4097cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4098
4099#ifdef CONFIG_SMP
4100/*
4101 * This is how migration works:
4102 *
4103 * 1) we queue a migration_req_t structure in the source CPU's
4104 * runqueue and wake up that CPU's migration thread.
4105 * 2) we down() the locked semaphore => thread blocks.
4106 * 3) migration thread wakes up (implicitly it forces the migrated
4107 * thread off the CPU)
4108 * 4) it gets the migration request and checks whether the migrated
4109 * task is still in the wrong runqueue.
4110 * 5) if it's in the wrong runqueue then the migration thread removes
4111 * it and puts it into the right queue.
4112 * 6) migration thread up()s the semaphore.
4113 * 7) we wake up and the migration is done.
4114 */
4115
4116/*
4117 * Change a given task's CPU affinity. Migrate the thread to a
4118 * proper CPU and schedule it away if the CPU it's executing on
4119 * is removed from the allowed bitmask.
4120 *
4121 * NOTE: the caller must have a valid reference to the task, the
4122 * task must not exit() & deallocate itself prematurely. The
4123 * call is not atomic; no spinlocks may be held.
4124 */
4125int set_cpus_allowed(task_t *p, cpumask_t new_mask)
4126{
4127 unsigned long flags;
4128 int ret = 0;
4129 migration_req_t req;
4130 runqueue_t *rq;
4131
4132 rq = task_rq_lock(p, &flags);
4133 if (!cpus_intersects(new_mask, cpu_online_map)) {
4134 ret = -EINVAL;
4135 goto out;
4136 }
4137
4138 p->cpus_allowed = new_mask;
4139 /* Can the task run on the task's current CPU? If so, we're done */
4140 if (cpu_isset(task_cpu(p), new_mask))
4141 goto out;
4142
4143 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4144 /* Need help from migration thread: drop lock and wait. */
4145 task_rq_unlock(rq, &flags);
4146 wake_up_process(rq->migration_thread);
4147 wait_for_completion(&req.done);
4148 tlb_migrate_finish(p->mm);
4149 return 0;
4150 }
4151out:
4152 task_rq_unlock(rq, &flags);
4153 return ret;
4154}
4155
4156EXPORT_SYMBOL_GPL(set_cpus_allowed);
4157
4158/*
4159 * Move (not current) task off this cpu, onto dest cpu. We're doing
4160 * this because either it can't run here any more (set_cpus_allowed()
4161 * away from this CPU, or CPU going down), or because we're
4162 * attempting to rebalance this task on exec (sched_exec).
4163 *
4164 * So we race with normal scheduler movements, but that's OK, as long
4165 * as the task is no longer on this CPU.
4166 */
4167static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4168{
4169 runqueue_t *rq_dest, *rq_src;
4170
4171 if (unlikely(cpu_is_offline(dest_cpu)))
4172 return;
4173
4174 rq_src = cpu_rq(src_cpu);
4175 rq_dest = cpu_rq(dest_cpu);
4176
4177 double_rq_lock(rq_src, rq_dest);
4178 /* Already moved. */
4179 if (task_cpu(p) != src_cpu)
4180 goto out;
4181 /* Affinity changed (again). */
4182 if (!cpu_isset(dest_cpu, p->cpus_allowed))
4183 goto out;
4184
4185 set_task_cpu(p, dest_cpu);
4186 if (p->array) {
4187 /*
4188 * Sync timestamp with rq_dest's before activating.
4189 * The same thing could be achieved by doing this step
4190 * afterwards, and pretending it was a local activate.
4191 * This way is cleaner and logically correct.
4192 */
4193 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4194 + rq_dest->timestamp_last_tick;
4195 deactivate_task(p, rq_src);
4196 activate_task(p, rq_dest, 0);
4197 if (TASK_PREEMPTS_CURR(p, rq_dest))
4198 resched_task(rq_dest->curr);
4199 }
4200
4201out:
4202 double_rq_unlock(rq_src, rq_dest);
4203}
4204
4205/*
4206 * migration_thread - this is a highprio system thread that performs
4207 * thread migration by bumping thread off CPU then 'pushing' onto
4208 * another runqueue.
4209 */
4210static int migration_thread(void * data)
4211{
4212 runqueue_t *rq;
4213 int cpu = (long)data;
4214
4215 rq = cpu_rq(cpu);
4216 BUG_ON(rq->migration_thread != current);
4217
4218 set_current_state(TASK_INTERRUPTIBLE);
4219 while (!kthread_should_stop()) {
4220 struct list_head *head;
4221 migration_req_t *req;
4222
4223 if (current->flags & PF_FREEZE)
4224 refrigerator(PF_FREEZE);
4225
4226 spin_lock_irq(&rq->lock);
4227
4228 if (cpu_is_offline(cpu)) {
4229 spin_unlock_irq(&rq->lock);
4230 goto wait_to_die;
4231 }
4232
4233 if (rq->active_balance) {
4234 active_load_balance(rq, cpu);
4235 rq->active_balance = 0;
4236 }
4237
4238 head = &rq->migration_queue;
4239
4240 if (list_empty(head)) {
4241 spin_unlock_irq(&rq->lock);
4242 schedule();
4243 set_current_state(TASK_INTERRUPTIBLE);
4244 continue;
4245 }
4246 req = list_entry(head->next, migration_req_t, list);
4247 list_del_init(head->next);
4248
4249 if (req->type == REQ_MOVE_TASK) {
4250 spin_unlock(&rq->lock);
4251 __migrate_task(req->task, cpu, req->dest_cpu);
4252 local_irq_enable();
4253 } else if (req->type == REQ_SET_DOMAIN) {
4254 rq->sd = req->sd;
4255 spin_unlock_irq(&rq->lock);
4256 } else {
4257 spin_unlock_irq(&rq->lock);
4258 WARN_ON(1);
4259 }
4260
4261 complete(&req->done);
4262 }
4263 __set_current_state(TASK_RUNNING);
4264 return 0;
4265
4266wait_to_die:
4267 /* Wait for kthread_stop */
4268 set_current_state(TASK_INTERRUPTIBLE);
4269 while (!kthread_should_stop()) {
4270 schedule();
4271 set_current_state(TASK_INTERRUPTIBLE);
4272 }
4273 __set_current_state(TASK_RUNNING);
4274 return 0;
4275}
4276
4277#ifdef CONFIG_HOTPLUG_CPU
4278/* Figure out where task on dead CPU should go, use force if neccessary. */
4279static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
4280{
4281 int dest_cpu;
4282 cpumask_t mask;
4283
4284 /* On same node? */
4285 mask = node_to_cpumask(cpu_to_node(dead_cpu));
4286 cpus_and(mask, mask, tsk->cpus_allowed);
4287 dest_cpu = any_online_cpu(mask);
4288
4289 /* On any allowed CPU? */
4290 if (dest_cpu == NR_CPUS)
4291 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4292
4293 /* No more Mr. Nice Guy. */
4294 if (dest_cpu == NR_CPUS) {
b39c4fab 4295 cpus_setall(tsk->cpus_allowed);
1da177e4
LT
4296 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4297
4298 /*
4299 * Don't tell them about moving exiting tasks or
4300 * kernel threads (both mm NULL), since they never
4301 * leave kernel.
4302 */
4303 if (tsk->mm && printk_ratelimit())
4304 printk(KERN_INFO "process %d (%s) no "
4305 "longer affine to cpu%d\n",
4306 tsk->pid, tsk->comm, dead_cpu);
4307 }
4308 __migrate_task(tsk, dead_cpu, dest_cpu);
4309}
4310
4311/*
4312 * While a dead CPU has no uninterruptible tasks queued at this point,
4313 * it might still have a nonzero ->nr_uninterruptible counter, because
4314 * for performance reasons the counter is not stricly tracking tasks to
4315 * their home CPUs. So we just add the counter to another CPU's counter,
4316 * to keep the global sum constant after CPU-down:
4317 */
4318static void migrate_nr_uninterruptible(runqueue_t *rq_src)
4319{
4320 runqueue_t *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
4321 unsigned long flags;
4322
4323 local_irq_save(flags);
4324 double_rq_lock(rq_src, rq_dest);
4325 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
4326 rq_src->nr_uninterruptible = 0;
4327 double_rq_unlock(rq_src, rq_dest);
4328 local_irq_restore(flags);
4329}
4330
4331/* Run through task list and migrate tasks from the dead cpu. */
4332static void migrate_live_tasks(int src_cpu)
4333{
4334 struct task_struct *tsk, *t;
4335
4336 write_lock_irq(&tasklist_lock);
4337
4338 do_each_thread(t, tsk) {
4339 if (tsk == current)
4340 continue;
4341
4342 if (task_cpu(tsk) == src_cpu)
4343 move_task_off_dead_cpu(src_cpu, tsk);
4344 } while_each_thread(t, tsk);
4345
4346 write_unlock_irq(&tasklist_lock);
4347}
4348
4349/* Schedules idle task to be the next runnable task on current CPU.
4350 * It does so by boosting its priority to highest possible and adding it to
4351 * the _front_ of runqueue. Used by CPU offline code.
4352 */
4353void sched_idle_next(void)
4354{
4355 int cpu = smp_processor_id();
4356 runqueue_t *rq = this_rq();
4357 struct task_struct *p = rq->idle;
4358 unsigned long flags;
4359
4360 /* cpu has to be offline */
4361 BUG_ON(cpu_online(cpu));
4362
4363 /* Strictly not necessary since rest of the CPUs are stopped by now
4364 * and interrupts disabled on current cpu.
4365 */
4366 spin_lock_irqsave(&rq->lock, flags);
4367
4368 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4369 /* Add idle task to _front_ of it's priority queue */
4370 __activate_idle_task(p, rq);
4371
4372 spin_unlock_irqrestore(&rq->lock, flags);
4373}
4374
4375/* Ensures that the idle task is using init_mm right before its cpu goes
4376 * offline.
4377 */
4378void idle_task_exit(void)
4379{
4380 struct mm_struct *mm = current->active_mm;
4381
4382 BUG_ON(cpu_online(smp_processor_id()));
4383
4384 if (mm != &init_mm)
4385 switch_mm(mm, &init_mm, current);
4386 mmdrop(mm);
4387}
4388
4389static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
4390{
4391 struct runqueue *rq = cpu_rq(dead_cpu);
4392
4393 /* Must be exiting, otherwise would be on tasklist. */
4394 BUG_ON(tsk->exit_state != EXIT_ZOMBIE && tsk->exit_state != EXIT_DEAD);
4395
4396 /* Cannot have done final schedule yet: would have vanished. */
4397 BUG_ON(tsk->flags & PF_DEAD);
4398
4399 get_task_struct(tsk);
4400
4401 /*
4402 * Drop lock around migration; if someone else moves it,
4403 * that's OK. No task can be added to this CPU, so iteration is
4404 * fine.
4405 */
4406 spin_unlock_irq(&rq->lock);
4407 move_task_off_dead_cpu(dead_cpu, tsk);
4408 spin_lock_irq(&rq->lock);
4409
4410 put_task_struct(tsk);
4411}
4412
4413/* release_task() removes task from tasklist, so we won't find dead tasks. */
4414static void migrate_dead_tasks(unsigned int dead_cpu)
4415{
4416 unsigned arr, i;
4417 struct runqueue *rq = cpu_rq(dead_cpu);
4418
4419 for (arr = 0; arr < 2; arr++) {
4420 for (i = 0; i < MAX_PRIO; i++) {
4421 struct list_head *list = &rq->arrays[arr].queue[i];
4422 while (!list_empty(list))
4423 migrate_dead(dead_cpu,
4424 list_entry(list->next, task_t,
4425 run_list));
4426 }
4427 }
4428}
4429#endif /* CONFIG_HOTPLUG_CPU */
4430
4431/*
4432 * migration_call - callback that gets triggered when a CPU is added.
4433 * Here we can start up the necessary migration thread for the new CPU.
4434 */
4435static int migration_call(struct notifier_block *nfb, unsigned long action,
4436 void *hcpu)
4437{
4438 int cpu = (long)hcpu;
4439 struct task_struct *p;
4440 struct runqueue *rq;
4441 unsigned long flags;
4442
4443 switch (action) {
4444 case CPU_UP_PREPARE:
4445 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4446 if (IS_ERR(p))
4447 return NOTIFY_BAD;
4448 p->flags |= PF_NOFREEZE;
4449 kthread_bind(p, cpu);
4450 /* Must be high prio: stop_machine expects to yield to it. */
4451 rq = task_rq_lock(p, &flags);
4452 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4453 task_rq_unlock(rq, &flags);
4454 cpu_rq(cpu)->migration_thread = p;
4455 break;
4456 case CPU_ONLINE:
4457 /* Strictly unneccessary, as first user will wake it. */
4458 wake_up_process(cpu_rq(cpu)->migration_thread);
4459 break;
4460#ifdef CONFIG_HOTPLUG_CPU
4461 case CPU_UP_CANCELED:
4462 /* Unbind it from offline cpu so it can run. Fall thru. */
4463 kthread_bind(cpu_rq(cpu)->migration_thread,smp_processor_id());
4464 kthread_stop(cpu_rq(cpu)->migration_thread);
4465 cpu_rq(cpu)->migration_thread = NULL;
4466 break;
4467 case CPU_DEAD:
4468 migrate_live_tasks(cpu);
4469 rq = cpu_rq(cpu);
4470 kthread_stop(rq->migration_thread);
4471 rq->migration_thread = NULL;
4472 /* Idle task back to normal (off runqueue, low prio) */
4473 rq = task_rq_lock(rq->idle, &flags);
4474 deactivate_task(rq->idle, rq);
4475 rq->idle->static_prio = MAX_PRIO;
4476 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4477 migrate_dead_tasks(cpu);
4478 task_rq_unlock(rq, &flags);
4479 migrate_nr_uninterruptible(rq);
4480 BUG_ON(rq->nr_running != 0);
4481
4482 /* No need to migrate the tasks: it was best-effort if
4483 * they didn't do lock_cpu_hotplug(). Just wake up
4484 * the requestors. */
4485 spin_lock_irq(&rq->lock);
4486 while (!list_empty(&rq->migration_queue)) {
4487 migration_req_t *req;
4488 req = list_entry(rq->migration_queue.next,
4489 migration_req_t, list);
4490 BUG_ON(req->type != REQ_MOVE_TASK);
4491 list_del_init(&req->list);
4492 complete(&req->done);
4493 }
4494 spin_unlock_irq(&rq->lock);
4495 break;
4496#endif
4497 }
4498 return NOTIFY_OK;
4499}
4500
4501/* Register at highest priority so that task migration (migrate_all_tasks)
4502 * happens before everything else.
4503 */
4504static struct notifier_block __devinitdata migration_notifier = {
4505 .notifier_call = migration_call,
4506 .priority = 10
4507};
4508
4509int __init migration_init(void)
4510{
4511 void *cpu = (void *)(long)smp_processor_id();
4512 /* Start one for boot CPU. */
4513 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4514 migration_call(&migration_notifier, CPU_ONLINE, cpu);
4515 register_cpu_notifier(&migration_notifier);
4516 return 0;
4517}
4518#endif
4519
4520#ifdef CONFIG_SMP
4521#define SCHED_DOMAIN_DEBUG
4522#ifdef SCHED_DOMAIN_DEBUG
4523static void sched_domain_debug(struct sched_domain *sd, int cpu)
4524{
4525 int level = 0;
4526
4527 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
4528
4529 do {
4530 int i;
4531 char str[NR_CPUS];
4532 struct sched_group *group = sd->groups;
4533 cpumask_t groupmask;
4534
4535 cpumask_scnprintf(str, NR_CPUS, sd->span);
4536 cpus_clear(groupmask);
4537
4538 printk(KERN_DEBUG);
4539 for (i = 0; i < level + 1; i++)
4540 printk(" ");
4541 printk("domain %d: ", level);
4542
4543 if (!(sd->flags & SD_LOAD_BALANCE)) {
4544 printk("does not load-balance\n");
4545 if (sd->parent)
4546 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
4547 break;
4548 }
4549
4550 printk("span %s\n", str);
4551
4552 if (!cpu_isset(cpu, sd->span))
4553 printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
4554 if (!cpu_isset(cpu, group->cpumask))
4555 printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
4556
4557 printk(KERN_DEBUG);
4558 for (i = 0; i < level + 2; i++)
4559 printk(" ");
4560 printk("groups:");
4561 do {
4562 if (!group) {
4563 printk("\n");
4564 printk(KERN_ERR "ERROR: group is NULL\n");
4565 break;
4566 }
4567
4568 if (!group->cpu_power) {
4569 printk("\n");
4570 printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
4571 }
4572
4573 if (!cpus_weight(group->cpumask)) {
4574 printk("\n");
4575 printk(KERN_ERR "ERROR: empty group\n");
4576 }
4577
4578 if (cpus_intersects(groupmask, group->cpumask)) {
4579 printk("\n");
4580 printk(KERN_ERR "ERROR: repeated CPUs\n");
4581 }
4582
4583 cpus_or(groupmask, groupmask, group->cpumask);
4584
4585 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
4586 printk(" %s", str);
4587
4588 group = group->next;
4589 } while (group != sd->groups);
4590 printk("\n");
4591
4592 if (!cpus_equal(sd->span, groupmask))
4593 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
4594
4595 level++;
4596 sd = sd->parent;
4597
4598 if (sd) {
4599 if (!cpus_subset(groupmask, sd->span))
4600 printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
4601 }
4602
4603 } while (sd);
4604}
4605#else
4606#define sched_domain_debug(sd, cpu) {}
4607#endif
4608
4609/*
4610 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
4611 * hold the hotplug lock.
4612 */
4613void __devinit cpu_attach_domain(struct sched_domain *sd, int cpu)
4614{
4615 migration_req_t req;
4616 unsigned long flags;
4617 runqueue_t *rq = cpu_rq(cpu);
4618 int local = 1;
4619
4620 sched_domain_debug(sd, cpu);
4621
4622 spin_lock_irqsave(&rq->lock, flags);
4623
4624 if (cpu == smp_processor_id() || !cpu_online(cpu)) {
4625 rq->sd = sd;
4626 } else {
4627 init_completion(&req.done);
4628 req.type = REQ_SET_DOMAIN;
4629 req.sd = sd;
4630 list_add(&req.list, &rq->migration_queue);
4631 local = 0;
4632 }
4633
4634 spin_unlock_irqrestore(&rq->lock, flags);
4635
4636 if (!local) {
4637 wake_up_process(rq->migration_thread);
4638 wait_for_completion(&req.done);
4639 }
4640}
4641
4642/* cpus with isolated domains */
4643cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
4644
4645/* Setup the mask of cpus configured for isolated domains */
4646static int __init isolated_cpu_setup(char *str)
4647{
4648 int ints[NR_CPUS], i;
4649
4650 str = get_options(str, ARRAY_SIZE(ints), ints);
4651 cpus_clear(cpu_isolated_map);
4652 for (i = 1; i <= ints[0]; i++)
4653 if (ints[i] < NR_CPUS)
4654 cpu_set(ints[i], cpu_isolated_map);
4655 return 1;
4656}
4657
4658__setup ("isolcpus=", isolated_cpu_setup);
4659
4660/*
4661 * init_sched_build_groups takes an array of groups, the cpumask we wish
4662 * to span, and a pointer to a function which identifies what group a CPU
4663 * belongs to. The return value of group_fn must be a valid index into the
4664 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
4665 * keep track of groups covered with a cpumask_t).
4666 *
4667 * init_sched_build_groups will build a circular linked list of the groups
4668 * covered by the given span, and will set each group's ->cpumask correctly,
4669 * and ->cpu_power to 0.
4670 */
4671void __devinit init_sched_build_groups(struct sched_group groups[],
4672 cpumask_t span, int (*group_fn)(int cpu))
4673{
4674 struct sched_group *first = NULL, *last = NULL;
4675 cpumask_t covered = CPU_MASK_NONE;
4676 int i;
4677
4678 for_each_cpu_mask(i, span) {
4679 int group = group_fn(i);
4680 struct sched_group *sg = &groups[group];
4681 int j;
4682
4683 if (cpu_isset(i, covered))
4684 continue;
4685
4686 sg->cpumask = CPU_MASK_NONE;
4687 sg->cpu_power = 0;
4688
4689 for_each_cpu_mask(j, span) {
4690 if (group_fn(j) != group)
4691 continue;
4692
4693 cpu_set(j, covered);
4694 cpu_set(j, sg->cpumask);
4695 }
4696 if (!first)
4697 first = sg;
4698 if (last)
4699 last->next = sg;
4700 last = sg;
4701 }
4702 last->next = first;
4703}
4704
4705
4706#ifdef ARCH_HAS_SCHED_DOMAIN
4707extern void __devinit arch_init_sched_domains(void);
4708extern void __devinit arch_destroy_sched_domains(void);
4709#else
4710#ifdef CONFIG_SCHED_SMT
4711static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
4712static struct sched_group sched_group_cpus[NR_CPUS];
4713static int __devinit cpu_to_cpu_group(int cpu)
4714{
4715 return cpu;
4716}
4717#endif
4718
4719static DEFINE_PER_CPU(struct sched_domain, phys_domains);
4720static struct sched_group sched_group_phys[NR_CPUS];
4721static int __devinit cpu_to_phys_group(int cpu)
4722{
4723#ifdef CONFIG_SCHED_SMT
4724 return first_cpu(cpu_sibling_map[cpu]);
4725#else
4726 return cpu;
4727#endif
4728}
4729
4730#ifdef CONFIG_NUMA
4731
4732static DEFINE_PER_CPU(struct sched_domain, node_domains);
4733static struct sched_group sched_group_nodes[MAX_NUMNODES];
4734static int __devinit cpu_to_node_group(int cpu)
4735{
4736 return cpu_to_node(cpu);
4737}
4738#endif
4739
4740#if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
4741/*
4742 * The domains setup code relies on siblings not spanning
4743 * multiple nodes. Make sure the architecture has a proper
4744 * siblings map:
4745 */
4746static void check_sibling_maps(void)
4747{
4748 int i, j;
4749
4750 for_each_online_cpu(i) {
4751 for_each_cpu_mask(j, cpu_sibling_map[i]) {
4752 if (cpu_to_node(i) != cpu_to_node(j)) {
4753 printk(KERN_INFO "warning: CPU %d siblings map "
4754 "to different node - isolating "
4755 "them.\n", i);
4756 cpu_sibling_map[i] = cpumask_of_cpu(i);
4757 break;
4758 }
4759 }
4760 }
4761}
4762#endif
4763
4764/*
4765 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
4766 */
4767static void __devinit arch_init_sched_domains(void)
4768{
4769 int i;
4770 cpumask_t cpu_default_map;
4771
4772#if defined(CONFIG_SCHED_SMT) && defined(CONFIG_NUMA)
4773 check_sibling_maps();
4774#endif
4775 /*
4776 * Setup mask for cpus without special case scheduling requirements.
4777 * For now this just excludes isolated cpus, but could be used to
4778 * exclude other special cases in the future.
4779 */
4780 cpus_complement(cpu_default_map, cpu_isolated_map);
4781 cpus_and(cpu_default_map, cpu_default_map, cpu_online_map);
4782
4783 /*
4784 * Set up domains. Isolated domains just stay on the dummy domain.
4785 */
4786 for_each_cpu_mask(i, cpu_default_map) {
4787 int group;
4788 struct sched_domain *sd = NULL, *p;
4789 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
4790
4791 cpus_and(nodemask, nodemask, cpu_default_map);
4792
4793#ifdef CONFIG_NUMA
4794 sd = &per_cpu(node_domains, i);
4795 group = cpu_to_node_group(i);
4796 *sd = SD_NODE_INIT;
4797 sd->span = cpu_default_map;
4798 sd->groups = &sched_group_nodes[group];
4799#endif
4800
4801 p = sd;
4802 sd = &per_cpu(phys_domains, i);
4803 group = cpu_to_phys_group(i);
4804 *sd = SD_CPU_INIT;
4805 sd->span = nodemask;
4806 sd->parent = p;
4807 sd->groups = &sched_group_phys[group];
4808
4809#ifdef CONFIG_SCHED_SMT
4810 p = sd;
4811 sd = &per_cpu(cpu_domains, i);
4812 group = cpu_to_cpu_group(i);
4813 *sd = SD_SIBLING_INIT;
4814 sd->span = cpu_sibling_map[i];
4815 cpus_and(sd->span, sd->span, cpu_default_map);
4816 sd->parent = p;
4817 sd->groups = &sched_group_cpus[group];
4818#endif
4819 }
4820
4821#ifdef CONFIG_SCHED_SMT
4822 /* Set up CPU (sibling) groups */
4823 for_each_online_cpu(i) {
4824 cpumask_t this_sibling_map = cpu_sibling_map[i];
4825 cpus_and(this_sibling_map, this_sibling_map, cpu_default_map);
4826 if (i != first_cpu(this_sibling_map))
4827 continue;
4828
4829 init_sched_build_groups(sched_group_cpus, this_sibling_map,
4830 &cpu_to_cpu_group);
4831 }
4832#endif
4833
4834 /* Set up physical groups */
4835 for (i = 0; i < MAX_NUMNODES; i++) {
4836 cpumask_t nodemask = node_to_cpumask(i);
4837
4838 cpus_and(nodemask, nodemask, cpu_default_map);
4839 if (cpus_empty(nodemask))
4840 continue;
4841
4842 init_sched_build_groups(sched_group_phys, nodemask,
4843 &cpu_to_phys_group);
4844 }
4845
4846#ifdef CONFIG_NUMA
4847 /* Set up node groups */
4848 init_sched_build_groups(sched_group_nodes, cpu_default_map,
4849 &cpu_to_node_group);
4850#endif
4851
4852 /* Calculate CPU power for physical packages and nodes */
4853 for_each_cpu_mask(i, cpu_default_map) {
4854 int power;
4855 struct sched_domain *sd;
4856#ifdef CONFIG_SCHED_SMT
4857 sd = &per_cpu(cpu_domains, i);
4858 power = SCHED_LOAD_SCALE;
4859 sd->groups->cpu_power = power;
4860#endif
4861
4862 sd = &per_cpu(phys_domains, i);
4863 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
4864 (cpus_weight(sd->groups->cpumask)-1) / 10;
4865 sd->groups->cpu_power = power;
4866
4867#ifdef CONFIG_NUMA
4868 if (i == first_cpu(sd->groups->cpumask)) {
4869 /* Only add "power" once for each physical package. */
4870 sd = &per_cpu(node_domains, i);
4871 sd->groups->cpu_power += power;
4872 }
4873#endif
4874 }
4875
4876 /* Attach the domains */
4877 for_each_online_cpu(i) {
4878 struct sched_domain *sd;
4879#ifdef CONFIG_SCHED_SMT
4880 sd = &per_cpu(cpu_domains, i);
4881#else
4882 sd = &per_cpu(phys_domains, i);
4883#endif
4884 cpu_attach_domain(sd, i);
4885 }
4886}
4887
4888#ifdef CONFIG_HOTPLUG_CPU
4889static void __devinit arch_destroy_sched_domains(void)
4890{
4891 /* Do nothing: everything is statically allocated. */
4892}
4893#endif
4894
4895#endif /* ARCH_HAS_SCHED_DOMAIN */
4896
4897/*
4898 * Initial dummy domain for early boot and for hotplug cpu. Being static,
4899 * it is initialized to zero, so all balancing flags are cleared which is
4900 * what we want.
4901 */
4902static struct sched_domain sched_domain_dummy;
4903
4904#ifdef CONFIG_HOTPLUG_CPU
4905/*
4906 * Force a reinitialization of the sched domains hierarchy. The domains
4907 * and groups cannot be updated in place without racing with the balancing
4908 * code, so we temporarily attach all running cpus to a "dummy" domain
4909 * which will prevent rebalancing while the sched domains are recalculated.
4910 */
4911static int update_sched_domains(struct notifier_block *nfb,
4912 unsigned long action, void *hcpu)
4913{
4914 int i;
4915
4916 switch (action) {
4917 case CPU_UP_PREPARE:
4918 case CPU_DOWN_PREPARE:
4919 for_each_online_cpu(i)
4920 cpu_attach_domain(&sched_domain_dummy, i);
4921 arch_destroy_sched_domains();
4922 return NOTIFY_OK;
4923
4924 case CPU_UP_CANCELED:
4925 case CPU_DOWN_FAILED:
4926 case CPU_ONLINE:
4927 case CPU_DEAD:
4928 /*
4929 * Fall through and re-initialise the domains.
4930 */
4931 break;
4932 default:
4933 return NOTIFY_DONE;
4934 }
4935
4936 /* The hotplug lock is already held by cpu_up/cpu_down */
4937 arch_init_sched_domains();
4938
4939 return NOTIFY_OK;
4940}
4941#endif
4942
4943void __init sched_init_smp(void)
4944{
4945 lock_cpu_hotplug();
4946 arch_init_sched_domains();
4947 unlock_cpu_hotplug();
4948 /* XXX: Theoretical race here - CPU may be hotplugged now */
4949 hotcpu_notifier(update_sched_domains, 0);
4950}
4951#else
4952void __init sched_init_smp(void)
4953{
4954}
4955#endif /* CONFIG_SMP */
4956
4957int in_sched_functions(unsigned long addr)
4958{
4959 /* Linker adds these: start and end of __sched functions */
4960 extern char __sched_text_start[], __sched_text_end[];
4961 return in_lock_functions(addr) ||
4962 (addr >= (unsigned long)__sched_text_start
4963 && addr < (unsigned long)__sched_text_end);
4964}
4965
4966void __init sched_init(void)
4967{
4968 runqueue_t *rq;
4969 int i, j, k;
4970
4971 for (i = 0; i < NR_CPUS; i++) {
4972 prio_array_t *array;
4973
4974 rq = cpu_rq(i);
4975 spin_lock_init(&rq->lock);
7897986b 4976 rq->nr_running = 0;
1da177e4
LT
4977 rq->active = rq->arrays;
4978 rq->expired = rq->arrays + 1;
4979 rq->best_expired_prio = MAX_PRIO;
4980
4981#ifdef CONFIG_SMP
4982 rq->sd = &sched_domain_dummy;
7897986b
NP
4983 for (j = 1; j < 3; j++)
4984 rq->cpu_load[j] = 0;
1da177e4
LT
4985 rq->active_balance = 0;
4986 rq->push_cpu = 0;
4987 rq->migration_thread = NULL;
4988 INIT_LIST_HEAD(&rq->migration_queue);
4989#endif
4990 atomic_set(&rq->nr_iowait, 0);
4991
4992 for (j = 0; j < 2; j++) {
4993 array = rq->arrays + j;
4994 for (k = 0; k < MAX_PRIO; k++) {
4995 INIT_LIST_HEAD(array->queue + k);
4996 __clear_bit(k, array->bitmap);
4997 }
4998 // delimiter for bitsearch
4999 __set_bit(MAX_PRIO, array->bitmap);
5000 }
5001 }
5002
5003 /*
5004 * The boot idle thread does lazy MMU switching as well:
5005 */
5006 atomic_inc(&init_mm.mm_count);
5007 enter_lazy_tlb(&init_mm, current);
5008
5009 /*
5010 * Make us the idle thread. Technically, schedule() should not be
5011 * called from this thread, however somewhere below it might be,
5012 * but because we are the idle thread, we just pick up running again
5013 * when this runqueue becomes "idle".
5014 */
5015 init_idle(current, smp_processor_id());
5016}
5017
5018#ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
5019void __might_sleep(char *file, int line)
5020{
5021#if defined(in_atomic)
5022 static unsigned long prev_jiffy; /* ratelimiting */
5023
5024 if ((in_atomic() || irqs_disabled()) &&
5025 system_state == SYSTEM_RUNNING && !oops_in_progress) {
5026 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
5027 return;
5028 prev_jiffy = jiffies;
5029 printk(KERN_ERR "Debug: sleeping function called from invalid"
5030 " context at %s:%d\n", file, line);
5031 printk("in_atomic():%d, irqs_disabled():%d\n",
5032 in_atomic(), irqs_disabled());
5033 dump_stack();
5034 }
5035#endif
5036}
5037EXPORT_SYMBOL(__might_sleep);
5038#endif
5039
5040#ifdef CONFIG_MAGIC_SYSRQ
5041void normalize_rt_tasks(void)
5042{
5043 struct task_struct *p;
5044 prio_array_t *array;
5045 unsigned long flags;
5046 runqueue_t *rq;
5047
5048 read_lock_irq(&tasklist_lock);
5049 for_each_process (p) {
5050 if (!rt_task(p))
5051 continue;
5052
5053 rq = task_rq_lock(p, &flags);
5054
5055 array = p->array;
5056 if (array)
5057 deactivate_task(p, task_rq(p));
5058 __setscheduler(p, SCHED_NORMAL, 0);
5059 if (array) {
5060 __activate_task(p, task_rq(p));
5061 resched_task(rq->curr);
5062 }
5063
5064 task_rq_unlock(rq, &flags);
5065 }
5066 read_unlock_irq(&tasklist_lock);
5067}
5068
5069#endif /* CONFIG_MAGIC_SYSRQ */
This page took 0.30526 seconds and 5 git commands to generate.