[PATCH] compound page: no access_process_vm check
[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>
c59ede7b 30#include <linux/capability.h>
1da177e4
LT
31#include <linux/completion.h>
32#include <linux/kernel_stat.h>
33#include <linux/security.h>
34#include <linux/notifier.h>
35#include <linux/profile.h>
36#include <linux/suspend.h>
198e2f18 37#include <linux/vmalloc.h>
1da177e4
LT
38#include <linux/blkdev.h>
39#include <linux/delay.h>
40#include <linux/smp.h>
41#include <linux/threads.h>
42#include <linux/timer.h>
43#include <linux/rcupdate.h>
44#include <linux/cpu.h>
45#include <linux/cpuset.h>
46#include <linux/percpu.h>
47#include <linux/kthread.h>
48#include <linux/seq_file.h>
49#include <linux/syscalls.h>
50#include <linux/times.h>
51#include <linux/acct.h>
52#include <asm/tlb.h>
53
54#include <asm/unistd.h>
55
56/*
57 * Convert user-nice values [ -20 ... 0 ... 19 ]
58 * to static priority [ MAX_RT_PRIO..MAX_PRIO-1 ],
59 * and back.
60 */
61#define NICE_TO_PRIO(nice) (MAX_RT_PRIO + (nice) + 20)
62#define PRIO_TO_NICE(prio) ((prio) - MAX_RT_PRIO - 20)
63#define TASK_NICE(p) PRIO_TO_NICE((p)->static_prio)
64
65/*
66 * 'User priority' is the nice value converted to something we
67 * can work with better when scaling various scheduler parameters,
68 * it's a [ 0 ... 39 ] range.
69 */
70#define USER_PRIO(p) ((p)-MAX_RT_PRIO)
71#define TASK_USER_PRIO(p) USER_PRIO((p)->static_prio)
72#define MAX_USER_PRIO (USER_PRIO(MAX_PRIO))
73
74/*
75 * Some helpers for converting nanosecond timing to jiffy resolution
76 */
77#define NS_TO_JIFFIES(TIME) ((TIME) / (1000000000 / HZ))
78#define JIFFIES_TO_NS(TIME) ((TIME) * (1000000000 / HZ))
79
80/*
81 * These are the 'tuning knobs' of the scheduler:
82 *
83 * Minimum timeslice is 5 msecs (or 1 jiffy, whichever is larger),
84 * default timeslice is 100 msecs, maximum timeslice is 800 msecs.
85 * Timeslices get refilled after they expire.
86 */
87#define MIN_TIMESLICE max(5 * HZ / 1000, 1)
88#define DEF_TIMESLICE (100 * HZ / 1000)
89#define ON_RUNQUEUE_WEIGHT 30
90#define CHILD_PENALTY 95
91#define PARENT_PENALTY 100
92#define EXIT_WEIGHT 3
93#define PRIO_BONUS_RATIO 25
94#define MAX_BONUS (MAX_USER_PRIO * PRIO_BONUS_RATIO / 100)
95#define INTERACTIVE_DELTA 2
96#define MAX_SLEEP_AVG (DEF_TIMESLICE * MAX_BONUS)
97#define STARVATION_LIMIT (MAX_SLEEP_AVG)
98#define NS_MAX_SLEEP_AVG (JIFFIES_TO_NS(MAX_SLEEP_AVG))
99
100/*
101 * If a task is 'interactive' then we reinsert it in the active
102 * array after it has expired its current timeslice. (it will not
103 * continue to run immediately, it will still roundrobin with
104 * other interactive tasks.)
105 *
106 * This part scales the interactivity limit depending on niceness.
107 *
108 * We scale it linearly, offset by the INTERACTIVE_DELTA delta.
109 * Here are a few examples of different nice levels:
110 *
111 * TASK_INTERACTIVE(-20): [1,1,1,1,1,1,1,1,1,0,0]
112 * TASK_INTERACTIVE(-10): [1,1,1,1,1,1,1,0,0,0,0]
113 * TASK_INTERACTIVE( 0): [1,1,1,1,0,0,0,0,0,0,0]
114 * TASK_INTERACTIVE( 10): [1,1,0,0,0,0,0,0,0,0,0]
115 * TASK_INTERACTIVE( 19): [0,0,0,0,0,0,0,0,0,0,0]
116 *
117 * (the X axis represents the possible -5 ... 0 ... +5 dynamic
118 * priority range a task can explore, a value of '1' means the
119 * task is rated interactive.)
120 *
121 * Ie. nice +19 tasks can never get 'interactive' enough to be
122 * reinserted into the active array. And only heavily CPU-hog nice -20
123 * tasks will be expired. Default nice 0 tasks are somewhere between,
124 * it takes some effort for them to get interactive, but it's not
125 * too hard.
126 */
127
128#define CURRENT_BONUS(p) \
129 (NS_TO_JIFFIES((p)->sleep_avg) * MAX_BONUS / \
130 MAX_SLEEP_AVG)
131
132#define GRANULARITY (10 * HZ / 1000 ? : 1)
133
134#ifdef CONFIG_SMP
135#define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
136 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)) * \
137 num_online_cpus())
138#else
139#define TIMESLICE_GRANULARITY(p) (GRANULARITY * \
140 (1 << (((MAX_BONUS - CURRENT_BONUS(p)) ? : 1) - 1)))
141#endif
142
143#define SCALE(v1,v1_max,v2_max) \
144 (v1) * (v2_max) / (v1_max)
145
146#define DELTA(p) \
147 (SCALE(TASK_NICE(p), 40, MAX_BONUS) + INTERACTIVE_DELTA)
148
149#define TASK_INTERACTIVE(p) \
150 ((p)->prio <= (p)->static_prio - DELTA(p))
151
152#define INTERACTIVE_SLEEP(p) \
153 (JIFFIES_TO_NS(MAX_SLEEP_AVG * \
154 (MAX_BONUS / 2 + DELTA((p)) + 1) / MAX_BONUS - 1))
155
156#define TASK_PREEMPTS_CURR(p, rq) \
157 ((p)->prio < (rq)->curr->prio)
158
159/*
160 * task_timeslice() scales user-nice values [ -20 ... 0 ... 19 ]
161 * to time slice values: [800ms ... 100ms ... 5ms]
162 *
163 * The higher a thread's priority, the bigger timeslices
164 * it gets during one round of execution. But even the lowest
165 * priority thread gets MIN_TIMESLICE worth of execution time.
166 */
167
168#define SCALE_PRIO(x, prio) \
169 max(x * (MAX_PRIO - prio) / (MAX_USER_PRIO/2), MIN_TIMESLICE)
170
48c08d3f 171static unsigned int task_timeslice(task_t *p)
1da177e4
LT
172{
173 if (p->static_prio < NICE_TO_PRIO(0))
174 return SCALE_PRIO(DEF_TIMESLICE*4, p->static_prio);
175 else
176 return SCALE_PRIO(DEF_TIMESLICE, p->static_prio);
177}
178#define task_hot(p, now, sd) ((long long) ((now) - (p)->last_ran) \
179 < (long long) (sd)->cache_hot_time)
180
e56d0903
IM
181void __put_task_struct_cb(struct rcu_head *rhp)
182{
183 __put_task_struct(container_of(rhp, struct task_struct, rcu));
184}
185
186EXPORT_SYMBOL_GPL(__put_task_struct_cb);
187
1da177e4
LT
188/*
189 * These are the runqueue data structures:
190 */
191
192#define BITMAP_SIZE ((((MAX_PRIO+1+7)/8)+sizeof(long)-1)/sizeof(long))
193
194typedef struct runqueue runqueue_t;
195
196struct prio_array {
197 unsigned int nr_active;
198 unsigned long bitmap[BITMAP_SIZE];
199 struct list_head queue[MAX_PRIO];
200};
201
202/*
203 * This is the main, per-CPU runqueue data structure.
204 *
205 * Locking rule: those places that want to lock multiple runqueues
206 * (such as the load balancing or the thread migration code), lock
207 * acquire operations must be ordered by ascending &runqueue.
208 */
209struct runqueue {
210 spinlock_t lock;
211
212 /*
213 * nr_running and cpu_load should be in the same cacheline because
214 * remote CPUs use both these fields when doing load calculation.
215 */
216 unsigned long nr_running;
217#ifdef CONFIG_SMP
7897986b 218 unsigned long cpu_load[3];
1da177e4
LT
219#endif
220 unsigned long long nr_switches;
221
222 /*
223 * This is part of a global counter where only the total sum
224 * over all CPUs matters. A task can increase this counter on
225 * one CPU and if it got migrated afterwards it may decrease
226 * it on another CPU. Always updated under the runqueue lock:
227 */
228 unsigned long nr_uninterruptible;
229
230 unsigned long expired_timestamp;
231 unsigned long long timestamp_last_tick;
232 task_t *curr, *idle;
233 struct mm_struct *prev_mm;
234 prio_array_t *active, *expired, arrays[2];
235 int best_expired_prio;
236 atomic_t nr_iowait;
237
238#ifdef CONFIG_SMP
239 struct sched_domain *sd;
240
241 /* For active balancing */
242 int active_balance;
243 int push_cpu;
244
245 task_t *migration_thread;
246 struct list_head migration_queue;
247#endif
248
249#ifdef CONFIG_SCHEDSTATS
250 /* latency stats */
251 struct sched_info rq_sched_info;
252
253 /* sys_sched_yield() stats */
254 unsigned long yld_exp_empty;
255 unsigned long yld_act_empty;
256 unsigned long yld_both_empty;
257 unsigned long yld_cnt;
258
259 /* schedule() stats */
260 unsigned long sched_switch;
261 unsigned long sched_cnt;
262 unsigned long sched_goidle;
263
264 /* try_to_wake_up() stats */
265 unsigned long ttwu_cnt;
266 unsigned long ttwu_local;
267#endif
268};
269
270static DEFINE_PER_CPU(struct runqueue, runqueues);
271
674311d5
NP
272/*
273 * The domain tree (rq->sd) is protected by RCU's quiescent state transition.
1a20ff27 274 * See detach_destroy_domains: synchronize_sched for details.
674311d5
NP
275 *
276 * The domain tree of any CPU may only be accessed from within
277 * preempt-disabled sections.
278 */
1da177e4 279#define for_each_domain(cpu, domain) \
674311d5 280for (domain = rcu_dereference(cpu_rq(cpu)->sd); domain; domain = domain->parent)
1da177e4
LT
281
282#define cpu_rq(cpu) (&per_cpu(runqueues, (cpu)))
283#define this_rq() (&__get_cpu_var(runqueues))
284#define task_rq(p) cpu_rq(task_cpu(p))
285#define cpu_curr(cpu) (cpu_rq(cpu)->curr)
286
1da177e4 287#ifndef prepare_arch_switch
4866cde0
NP
288# define prepare_arch_switch(next) do { } while (0)
289#endif
290#ifndef finish_arch_switch
291# define finish_arch_switch(prev) do { } while (0)
292#endif
293
294#ifndef __ARCH_WANT_UNLOCKED_CTXSW
295static inline int task_running(runqueue_t *rq, task_t *p)
296{
297 return rq->curr == p;
298}
299
300static inline void prepare_lock_switch(runqueue_t *rq, task_t *next)
301{
302}
303
304static inline void finish_lock_switch(runqueue_t *rq, task_t *prev)
305{
da04c035
IM
306#ifdef CONFIG_DEBUG_SPINLOCK
307 /* this is a valid case when another task releases the spinlock */
308 rq->lock.owner = current;
309#endif
4866cde0
NP
310 spin_unlock_irq(&rq->lock);
311}
312
313#else /* __ARCH_WANT_UNLOCKED_CTXSW */
314static inline int task_running(runqueue_t *rq, task_t *p)
315{
316#ifdef CONFIG_SMP
317 return p->oncpu;
318#else
319 return rq->curr == p;
320#endif
321}
322
323static inline void prepare_lock_switch(runqueue_t *rq, task_t *next)
324{
325#ifdef CONFIG_SMP
326 /*
327 * We can optimise this out completely for !SMP, because the
328 * SMP rebalancing from interrupt is the only thing that cares
329 * here.
330 */
331 next->oncpu = 1;
332#endif
333#ifdef __ARCH_WANT_INTERRUPTS_ON_CTXSW
334 spin_unlock_irq(&rq->lock);
335#else
336 spin_unlock(&rq->lock);
337#endif
338}
339
340static inline void finish_lock_switch(runqueue_t *rq, task_t *prev)
341{
342#ifdef CONFIG_SMP
343 /*
344 * After ->oncpu is cleared, the task can be moved to a different CPU.
345 * We must ensure this doesn't happen until the switch is completely
346 * finished.
347 */
348 smp_wmb();
349 prev->oncpu = 0;
350#endif
351#ifndef __ARCH_WANT_INTERRUPTS_ON_CTXSW
352 local_irq_enable();
1da177e4 353#endif
4866cde0
NP
354}
355#endif /* __ARCH_WANT_UNLOCKED_CTXSW */
1da177e4
LT
356
357/*
358 * task_rq_lock - lock the runqueue a given task resides on and disable
359 * interrupts. Note the ordering: we can safely lookup the task_rq without
360 * explicitly disabling preemption.
361 */
362static inline runqueue_t *task_rq_lock(task_t *p, unsigned long *flags)
363 __acquires(rq->lock)
364{
365 struct runqueue *rq;
366
367repeat_lock_task:
368 local_irq_save(*flags);
369 rq = task_rq(p);
370 spin_lock(&rq->lock);
371 if (unlikely(rq != task_rq(p))) {
372 spin_unlock_irqrestore(&rq->lock, *flags);
373 goto repeat_lock_task;
374 }
375 return rq;
376}
377
378static inline void task_rq_unlock(runqueue_t *rq, unsigned long *flags)
379 __releases(rq->lock)
380{
381 spin_unlock_irqrestore(&rq->lock, *flags);
382}
383
384#ifdef CONFIG_SCHEDSTATS
385/*
386 * bump this up when changing the output format or the meaning of an existing
387 * format, so that tools can adapt (or abort)
388 */
68767a0a 389#define SCHEDSTAT_VERSION 12
1da177e4
LT
390
391static int show_schedstat(struct seq_file *seq, void *v)
392{
393 int cpu;
394
395 seq_printf(seq, "version %d\n", SCHEDSTAT_VERSION);
396 seq_printf(seq, "timestamp %lu\n", jiffies);
397 for_each_online_cpu(cpu) {
398 runqueue_t *rq = cpu_rq(cpu);
399#ifdef CONFIG_SMP
400 struct sched_domain *sd;
401 int dcnt = 0;
402#endif
403
404 /* runqueue-specific stats */
405 seq_printf(seq,
406 "cpu%d %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu",
407 cpu, rq->yld_both_empty,
408 rq->yld_act_empty, rq->yld_exp_empty, rq->yld_cnt,
409 rq->sched_switch, rq->sched_cnt, rq->sched_goidle,
410 rq->ttwu_cnt, rq->ttwu_local,
411 rq->rq_sched_info.cpu_time,
412 rq->rq_sched_info.run_delay, rq->rq_sched_info.pcnt);
413
414 seq_printf(seq, "\n");
415
416#ifdef CONFIG_SMP
417 /* domain-specific stats */
674311d5 418 preempt_disable();
1da177e4
LT
419 for_each_domain(cpu, sd) {
420 enum idle_type itype;
421 char mask_str[NR_CPUS];
422
423 cpumask_scnprintf(mask_str, NR_CPUS, sd->span);
424 seq_printf(seq, "domain%d %s", dcnt++, mask_str);
425 for (itype = SCHED_IDLE; itype < MAX_IDLE_TYPES;
426 itype++) {
427 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu",
428 sd->lb_cnt[itype],
429 sd->lb_balanced[itype],
430 sd->lb_failed[itype],
431 sd->lb_imbalance[itype],
432 sd->lb_gained[itype],
433 sd->lb_hot_gained[itype],
434 sd->lb_nobusyq[itype],
435 sd->lb_nobusyg[itype]);
436 }
68767a0a 437 seq_printf(seq, " %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu %lu\n",
1da177e4 438 sd->alb_cnt, sd->alb_failed, sd->alb_pushed,
68767a0a
NP
439 sd->sbe_cnt, sd->sbe_balanced, sd->sbe_pushed,
440 sd->sbf_cnt, sd->sbf_balanced, sd->sbf_pushed,
1da177e4
LT
441 sd->ttwu_wake_remote, sd->ttwu_move_affine, sd->ttwu_move_balance);
442 }
674311d5 443 preempt_enable();
1da177e4
LT
444#endif
445 }
446 return 0;
447}
448
449static int schedstat_open(struct inode *inode, struct file *file)
450{
451 unsigned int size = PAGE_SIZE * (1 + num_online_cpus() / 32);
452 char *buf = kmalloc(size, GFP_KERNEL);
453 struct seq_file *m;
454 int res;
455
456 if (!buf)
457 return -ENOMEM;
458 res = single_open(file, show_schedstat, NULL);
459 if (!res) {
460 m = file->private_data;
461 m->buf = buf;
462 m->size = size;
463 } else
464 kfree(buf);
465 return res;
466}
467
468struct file_operations proc_schedstat_operations = {
469 .open = schedstat_open,
470 .read = seq_read,
471 .llseek = seq_lseek,
472 .release = single_release,
473};
474
475# define schedstat_inc(rq, field) do { (rq)->field++; } while (0)
476# define schedstat_add(rq, field, amt) do { (rq)->field += (amt); } while (0)
477#else /* !CONFIG_SCHEDSTATS */
478# define schedstat_inc(rq, field) do { } while (0)
479# define schedstat_add(rq, field, amt) do { } while (0)
480#endif
481
482/*
483 * rq_lock - lock a given runqueue and disable interrupts.
484 */
485static inline runqueue_t *this_rq_lock(void)
486 __acquires(rq->lock)
487{
488 runqueue_t *rq;
489
490 local_irq_disable();
491 rq = this_rq();
492 spin_lock(&rq->lock);
493
494 return rq;
495}
496
1da177e4
LT
497#ifdef CONFIG_SCHEDSTATS
498/*
499 * Called when a process is dequeued from the active array and given
500 * the cpu. We should note that with the exception of interactive
501 * tasks, the expired queue will become the active queue after the active
502 * queue is empty, without explicitly dequeuing and requeuing tasks in the
503 * expired queue. (Interactive tasks may be requeued directly to the
504 * active queue, thus delaying tasks in the expired queue from running;
505 * see scheduler_tick()).
506 *
507 * This function is only called from sched_info_arrive(), rather than
508 * dequeue_task(). Even though a task may be queued and dequeued multiple
509 * times as it is shuffled about, we're really interested in knowing how
510 * long it was from the *first* time it was queued to the time that it
511 * finally hit a cpu.
512 */
513static inline void sched_info_dequeued(task_t *t)
514{
515 t->sched_info.last_queued = 0;
516}
517
518/*
519 * Called when a task finally hits the cpu. We can now calculate how
520 * long it was waiting to run. We also note when it began so that we
521 * can keep stats on how long its timeslice is.
522 */
858119e1 523static void sched_info_arrive(task_t *t)
1da177e4
LT
524{
525 unsigned long now = jiffies, diff = 0;
526 struct runqueue *rq = task_rq(t);
527
528 if (t->sched_info.last_queued)
529 diff = now - t->sched_info.last_queued;
530 sched_info_dequeued(t);
531 t->sched_info.run_delay += diff;
532 t->sched_info.last_arrival = now;
533 t->sched_info.pcnt++;
534
535 if (!rq)
536 return;
537
538 rq->rq_sched_info.run_delay += diff;
539 rq->rq_sched_info.pcnt++;
540}
541
542/*
543 * Called when a process is queued into either the active or expired
544 * array. The time is noted and later used to determine how long we
545 * had to wait for us to reach the cpu. Since the expired queue will
546 * become the active queue after active queue is empty, without dequeuing
547 * and requeuing any tasks, we are interested in queuing to either. It
548 * is unusual but not impossible for tasks to be dequeued and immediately
549 * requeued in the same or another array: this can happen in sched_yield(),
550 * set_user_nice(), and even load_balance() as it moves tasks from runqueue
551 * to runqueue.
552 *
553 * This function is only called from enqueue_task(), but also only updates
554 * the timestamp if it is already not set. It's assumed that
555 * sched_info_dequeued() will clear that stamp when appropriate.
556 */
557static inline void sched_info_queued(task_t *t)
558{
559 if (!t->sched_info.last_queued)
560 t->sched_info.last_queued = jiffies;
561}
562
563/*
564 * Called when a process ceases being the active-running process, either
565 * voluntarily or involuntarily. Now we can calculate how long we ran.
566 */
567static inline void sched_info_depart(task_t *t)
568{
569 struct runqueue *rq = task_rq(t);
570 unsigned long diff = jiffies - t->sched_info.last_arrival;
571
572 t->sched_info.cpu_time += diff;
573
574 if (rq)
575 rq->rq_sched_info.cpu_time += diff;
576}
577
578/*
579 * Called when tasks are switched involuntarily due, typically, to expiring
580 * their time slice. (This may also be called when switching to or from
581 * the idle task.) We are only called when prev != next.
582 */
583static inline void sched_info_switch(task_t *prev, task_t *next)
584{
585 struct runqueue *rq = task_rq(prev);
586
587 /*
588 * prev now departs the cpu. It's not interesting to record
589 * stats about how efficient we were at scheduling the idle
590 * process, however.
591 */
592 if (prev != rq->idle)
593 sched_info_depart(prev);
594
595 if (next != rq->idle)
596 sched_info_arrive(next);
597}
598#else
599#define sched_info_queued(t) do { } while (0)
600#define sched_info_switch(t, next) do { } while (0)
601#endif /* CONFIG_SCHEDSTATS */
602
603/*
604 * Adding/removing a task to/from a priority array:
605 */
606static void dequeue_task(struct task_struct *p, prio_array_t *array)
607{
608 array->nr_active--;
609 list_del(&p->run_list);
610 if (list_empty(array->queue + p->prio))
611 __clear_bit(p->prio, array->bitmap);
612}
613
614static void enqueue_task(struct task_struct *p, prio_array_t *array)
615{
616 sched_info_queued(p);
617 list_add_tail(&p->run_list, array->queue + p->prio);
618 __set_bit(p->prio, array->bitmap);
619 array->nr_active++;
620 p->array = array;
621}
622
623/*
624 * Put task to the end of the run list without the overhead of dequeue
625 * followed by enqueue.
626 */
627static void requeue_task(struct task_struct *p, prio_array_t *array)
628{
629 list_move_tail(&p->run_list, array->queue + p->prio);
630}
631
632static inline void enqueue_task_head(struct task_struct *p, prio_array_t *array)
633{
634 list_add(&p->run_list, array->queue + p->prio);
635 __set_bit(p->prio, array->bitmap);
636 array->nr_active++;
637 p->array = array;
638}
639
640/*
641 * effective_prio - return the priority that is based on the static
642 * priority but is modified by bonuses/penalties.
643 *
644 * We scale the actual sleep average [0 .... MAX_SLEEP_AVG]
645 * into the -5 ... 0 ... +5 bonus/penalty range.
646 *
647 * We use 25% of the full 0...39 priority range so that:
648 *
649 * 1) nice +19 interactive tasks do not preempt nice 0 CPU hogs.
650 * 2) nice -20 CPU hogs do not get preempted by nice 0 tasks.
651 *
652 * Both properties are important to certain workloads.
653 */
654static int effective_prio(task_t *p)
655{
656 int bonus, prio;
657
658 if (rt_task(p))
659 return p->prio;
660
661 bonus = CURRENT_BONUS(p) - MAX_BONUS / 2;
662
663 prio = p->static_prio - bonus;
664 if (prio < MAX_RT_PRIO)
665 prio = MAX_RT_PRIO;
666 if (prio > MAX_PRIO-1)
667 prio = MAX_PRIO-1;
668 return prio;
669}
670
671/*
672 * __activate_task - move a task to the runqueue.
673 */
674static inline void __activate_task(task_t *p, runqueue_t *rq)
675{
676 enqueue_task(p, rq->active);
a2000572 677 rq->nr_running++;
1da177e4
LT
678}
679
680/*
681 * __activate_idle_task - move idle task to the _front_ of runqueue.
682 */
683static inline void __activate_idle_task(task_t *p, runqueue_t *rq)
684{
685 enqueue_task_head(p, rq->active);
a2000572 686 rq->nr_running++;
1da177e4
LT
687}
688
a3464a10 689static int recalc_task_prio(task_t *p, unsigned long long now)
1da177e4
LT
690{
691 /* Caller must always ensure 'now >= p->timestamp' */
692 unsigned long long __sleep_time = now - p->timestamp;
693 unsigned long sleep_time;
694
b0a9499c
IM
695 if (unlikely(p->policy == SCHED_BATCH))
696 sleep_time = 0;
697 else {
698 if (__sleep_time > NS_MAX_SLEEP_AVG)
699 sleep_time = NS_MAX_SLEEP_AVG;
700 else
701 sleep_time = (unsigned long)__sleep_time;
702 }
1da177e4
LT
703
704 if (likely(sleep_time > 0)) {
705 /*
706 * User tasks that sleep a long time are categorised as
707 * idle and will get just interactive status to stay active &
708 * prevent them suddenly becoming cpu hogs and starving
709 * other processes.
710 */
711 if (p->mm && p->activated != -1 &&
712 sleep_time > INTERACTIVE_SLEEP(p)) {
713 p->sleep_avg = JIFFIES_TO_NS(MAX_SLEEP_AVG -
714 DEF_TIMESLICE);
715 } else {
716 /*
717 * The lower the sleep avg a task has the more
718 * rapidly it will rise with sleep time.
719 */
720 sleep_time *= (MAX_BONUS - CURRENT_BONUS(p)) ? : 1;
721
722 /*
723 * Tasks waking from uninterruptible sleep are
724 * limited in their sleep_avg rise as they
725 * are likely to be waiting on I/O
726 */
727 if (p->activated == -1 && p->mm) {
728 if (p->sleep_avg >= INTERACTIVE_SLEEP(p))
729 sleep_time = 0;
730 else if (p->sleep_avg + sleep_time >=
731 INTERACTIVE_SLEEP(p)) {
732 p->sleep_avg = INTERACTIVE_SLEEP(p);
733 sleep_time = 0;
734 }
735 }
736
737 /*
738 * This code gives a bonus to interactive tasks.
739 *
740 * The boost works by updating the 'average sleep time'
741 * value here, based on ->timestamp. The more time a
742 * task spends sleeping, the higher the average gets -
743 * and the higher the priority boost gets as well.
744 */
745 p->sleep_avg += sleep_time;
746
747 if (p->sleep_avg > NS_MAX_SLEEP_AVG)
748 p->sleep_avg = NS_MAX_SLEEP_AVG;
749 }
750 }
751
a3464a10 752 return effective_prio(p);
1da177e4
LT
753}
754
755/*
756 * activate_task - move a task to the runqueue and do priority recalculation
757 *
758 * Update all the scheduling statistics stuff. (sleep average
759 * calculation, priority modifiers, etc.)
760 */
761static void activate_task(task_t *p, runqueue_t *rq, int local)
762{
763 unsigned long long now;
764
765 now = sched_clock();
766#ifdef CONFIG_SMP
767 if (!local) {
768 /* Compensate for drifting sched_clock */
769 runqueue_t *this_rq = this_rq();
770 now = (now - this_rq->timestamp_last_tick)
771 + rq->timestamp_last_tick;
772 }
773#endif
774
a47ab937
CK
775 if (!rt_task(p))
776 p->prio = recalc_task_prio(p, now);
1da177e4
LT
777
778 /*
779 * This checks to make sure it's not an uninterruptible task
780 * that is now waking up.
781 */
782 if (!p->activated) {
783 /*
784 * Tasks which were woken up by interrupts (ie. hw events)
785 * are most likely of interactive nature. So we give them
786 * the credit of extending their sleep time to the period
787 * of time they spend on the runqueue, waiting for execution
788 * on a CPU, first time around:
789 */
790 if (in_interrupt())
791 p->activated = 2;
792 else {
793 /*
794 * Normal first-time wakeups get a credit too for
795 * on-runqueue time, but it will be weighted down:
796 */
797 p->activated = 1;
798 }
799 }
800 p->timestamp = now;
801
802 __activate_task(p, rq);
803}
804
805/*
806 * deactivate_task - remove a task from the runqueue.
807 */
808static void deactivate_task(struct task_struct *p, runqueue_t *rq)
809{
a2000572 810 rq->nr_running--;
1da177e4
LT
811 dequeue_task(p, p->array);
812 p->array = NULL;
813}
814
815/*
816 * resched_task - mark a task 'to be rescheduled now'.
817 *
818 * On UP this means the setting of the need_resched flag, on SMP it
819 * might also involve a cross-CPU call to trigger the scheduler on
820 * the target CPU.
821 */
822#ifdef CONFIG_SMP
823static void resched_task(task_t *p)
824{
64c7c8f8 825 int cpu;
1da177e4
LT
826
827 assert_spin_locked(&task_rq(p)->lock);
828
64c7c8f8
NP
829 if (unlikely(test_tsk_thread_flag(p, TIF_NEED_RESCHED)))
830 return;
831
832 set_tsk_thread_flag(p, TIF_NEED_RESCHED);
1da177e4 833
64c7c8f8
NP
834 cpu = task_cpu(p);
835 if (cpu == smp_processor_id())
836 return;
837
838 /* NEED_RESCHED must be visible before we test POLLING_NRFLAG */
839 smp_mb();
840 if (!test_tsk_thread_flag(p, TIF_POLLING_NRFLAG))
841 smp_send_reschedule(cpu);
1da177e4
LT
842}
843#else
844static inline void resched_task(task_t *p)
845{
64c7c8f8 846 assert_spin_locked(&task_rq(p)->lock);
1da177e4
LT
847 set_tsk_need_resched(p);
848}
849#endif
850
851/**
852 * task_curr - is this task currently executing on a CPU?
853 * @p: the task in question.
854 */
855inline int task_curr(const task_t *p)
856{
857 return cpu_curr(task_cpu(p)) == p;
858}
859
860#ifdef CONFIG_SMP
1da177e4
LT
861typedef struct {
862 struct list_head list;
1da177e4 863
1da177e4
LT
864 task_t *task;
865 int dest_cpu;
866
1da177e4
LT
867 struct completion done;
868} migration_req_t;
869
870/*
871 * The task's runqueue lock must be held.
872 * Returns true if you have to wait for migration thread.
873 */
874static int migrate_task(task_t *p, int dest_cpu, migration_req_t *req)
875{
876 runqueue_t *rq = task_rq(p);
877
878 /*
879 * If the task is not on a runqueue (and not running), then
880 * it is sufficient to simply update the task's cpu field.
881 */
882 if (!p->array && !task_running(rq, p)) {
883 set_task_cpu(p, dest_cpu);
884 return 0;
885 }
886
887 init_completion(&req->done);
1da177e4
LT
888 req->task = p;
889 req->dest_cpu = dest_cpu;
890 list_add(&req->list, &rq->migration_queue);
891 return 1;
892}
893
894/*
895 * wait_task_inactive - wait for a thread to unschedule.
896 *
897 * The caller must ensure that the task *will* unschedule sometime soon,
898 * else this function might spin for a *long* time. This function can't
899 * be called with interrupts off, or it may introduce deadlock with
900 * smp_call_function() if an IPI is sent by the same process we are
901 * waiting to become inactive.
902 */
95cdf3b7 903void wait_task_inactive(task_t *p)
1da177e4
LT
904{
905 unsigned long flags;
906 runqueue_t *rq;
907 int preempted;
908
909repeat:
910 rq = task_rq_lock(p, &flags);
911 /* Must be off runqueue entirely, not preempted. */
912 if (unlikely(p->array || task_running(rq, p))) {
913 /* If it's preempted, we yield. It could be a while. */
914 preempted = !task_running(rq, p);
915 task_rq_unlock(rq, &flags);
916 cpu_relax();
917 if (preempted)
918 yield();
919 goto repeat;
920 }
921 task_rq_unlock(rq, &flags);
922}
923
924/***
925 * kick_process - kick a running thread to enter/exit the kernel
926 * @p: the to-be-kicked thread
927 *
928 * Cause a process which is running on another CPU to enter
929 * kernel-mode, without any delay. (to get signals handled.)
930 *
931 * NOTE: this function doesnt have to take the runqueue lock,
932 * because all it wants to ensure is that the remote task enters
933 * the kernel. If the IPI races and the task has been migrated
934 * to another CPU then no harm is done and the purpose has been
935 * achieved as well.
936 */
937void kick_process(task_t *p)
938{
939 int cpu;
940
941 preempt_disable();
942 cpu = task_cpu(p);
943 if ((cpu != smp_processor_id()) && task_curr(p))
944 smp_send_reschedule(cpu);
945 preempt_enable();
946}
947
948/*
949 * Return a low guess at the load of a migration-source cpu.
950 *
951 * We want to under-estimate the load of migration sources, to
952 * balance conservatively.
953 */
a2000572 954static inline unsigned long source_load(int cpu, int type)
1da177e4
LT
955{
956 runqueue_t *rq = cpu_rq(cpu);
a2000572 957 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
3b0bd9bc 958 if (type == 0)
a2000572 959 return load_now;
b910472d 960
a2000572 961 return min(rq->cpu_load[type-1], load_now);
1da177e4
LT
962}
963
964/*
965 * Return a high guess at the load of a migration-target cpu
966 */
a2000572 967static inline unsigned long target_load(int cpu, int type)
1da177e4
LT
968{
969 runqueue_t *rq = cpu_rq(cpu);
a2000572 970 unsigned long load_now = rq->nr_running * SCHED_LOAD_SCALE;
7897986b 971 if (type == 0)
a2000572 972 return load_now;
3b0bd9bc 973
a2000572 974 return max(rq->cpu_load[type-1], load_now);
1da177e4
LT
975}
976
147cbb4b
NP
977/*
978 * find_idlest_group finds and returns the least busy CPU group within the
979 * domain.
980 */
981static struct sched_group *
982find_idlest_group(struct sched_domain *sd, struct task_struct *p, int this_cpu)
983{
984 struct sched_group *idlest = NULL, *this = NULL, *group = sd->groups;
985 unsigned long min_load = ULONG_MAX, this_load = 0;
986 int load_idx = sd->forkexec_idx;
987 int imbalance = 100 + (sd->imbalance_pct-100)/2;
988
989 do {
990 unsigned long load, avg_load;
991 int local_group;
992 int i;
993
da5a5522
BD
994 /* Skip over this group if it has no CPUs allowed */
995 if (!cpus_intersects(group->cpumask, p->cpus_allowed))
996 goto nextgroup;
997
147cbb4b 998 local_group = cpu_isset(this_cpu, group->cpumask);
147cbb4b
NP
999
1000 /* Tally up the load of all CPUs in the group */
1001 avg_load = 0;
1002
1003 for_each_cpu_mask(i, group->cpumask) {
1004 /* Bias balancing toward cpus of our domain */
1005 if (local_group)
1006 load = source_load(i, load_idx);
1007 else
1008 load = target_load(i, load_idx);
1009
1010 avg_load += load;
1011 }
1012
1013 /* Adjust by relative CPU power of the group */
1014 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1015
1016 if (local_group) {
1017 this_load = avg_load;
1018 this = group;
1019 } else if (avg_load < min_load) {
1020 min_load = avg_load;
1021 idlest = group;
1022 }
da5a5522 1023nextgroup:
147cbb4b
NP
1024 group = group->next;
1025 } while (group != sd->groups);
1026
1027 if (!idlest || 100*this_load < imbalance*min_load)
1028 return NULL;
1029 return idlest;
1030}
1031
1032/*
1033 * find_idlest_queue - find the idlest runqueue among the cpus in group.
1034 */
95cdf3b7
IM
1035static int
1036find_idlest_cpu(struct sched_group *group, struct task_struct *p, int this_cpu)
147cbb4b 1037{
da5a5522 1038 cpumask_t tmp;
147cbb4b
NP
1039 unsigned long load, min_load = ULONG_MAX;
1040 int idlest = -1;
1041 int i;
1042
da5a5522
BD
1043 /* Traverse only the allowed CPUs */
1044 cpus_and(tmp, group->cpumask, p->cpus_allowed);
1045
1046 for_each_cpu_mask(i, tmp) {
147cbb4b
NP
1047 load = source_load(i, 0);
1048
1049 if (load < min_load || (load == min_load && i == this_cpu)) {
1050 min_load = load;
1051 idlest = i;
1052 }
1053 }
1054
1055 return idlest;
1056}
1057
476d139c
NP
1058/*
1059 * sched_balance_self: balance the current task (running on cpu) in domains
1060 * that have the 'flag' flag set. In practice, this is SD_BALANCE_FORK and
1061 * SD_BALANCE_EXEC.
1062 *
1063 * Balance, ie. select the least loaded group.
1064 *
1065 * Returns the target CPU number, or the same CPU if no balancing is needed.
1066 *
1067 * preempt must be disabled.
1068 */
1069static int sched_balance_self(int cpu, int flag)
1070{
1071 struct task_struct *t = current;
1072 struct sched_domain *tmp, *sd = NULL;
147cbb4b 1073
476d139c
NP
1074 for_each_domain(cpu, tmp)
1075 if (tmp->flags & flag)
1076 sd = tmp;
1077
1078 while (sd) {
1079 cpumask_t span;
1080 struct sched_group *group;
1081 int new_cpu;
1082 int weight;
1083
1084 span = sd->span;
1085 group = find_idlest_group(sd, t, cpu);
1086 if (!group)
1087 goto nextlevel;
1088
da5a5522 1089 new_cpu = find_idlest_cpu(group, t, cpu);
476d139c
NP
1090 if (new_cpu == -1 || new_cpu == cpu)
1091 goto nextlevel;
1092
1093 /* Now try balancing at a lower domain level */
1094 cpu = new_cpu;
1095nextlevel:
1096 sd = NULL;
1097 weight = cpus_weight(span);
1098 for_each_domain(cpu, tmp) {
1099 if (weight <= cpus_weight(tmp->span))
1100 break;
1101 if (tmp->flags & flag)
1102 sd = tmp;
1103 }
1104 /* while loop will break here if sd == NULL */
1105 }
1106
1107 return cpu;
1108}
1109
1110#endif /* CONFIG_SMP */
1da177e4
LT
1111
1112/*
1113 * wake_idle() will wake a task on an idle cpu if task->cpu is
1114 * not idle and an idle cpu is available. The span of cpus to
1115 * search starts with cpus closest then further out as needed,
1116 * so we always favor a closer, idle cpu.
1117 *
1118 * Returns the CPU we should wake onto.
1119 */
1120#if defined(ARCH_HAS_SCHED_WAKE_IDLE)
1121static int wake_idle(int cpu, task_t *p)
1122{
1123 cpumask_t tmp;
1124 struct sched_domain *sd;
1125 int i;
1126
1127 if (idle_cpu(cpu))
1128 return cpu;
1129
1130 for_each_domain(cpu, sd) {
1131 if (sd->flags & SD_WAKE_IDLE) {
e0f364f4 1132 cpus_and(tmp, sd->span, p->cpus_allowed);
1da177e4
LT
1133 for_each_cpu_mask(i, tmp) {
1134 if (idle_cpu(i))
1135 return i;
1136 }
1137 }
e0f364f4
NP
1138 else
1139 break;
1da177e4
LT
1140 }
1141 return cpu;
1142}
1143#else
1144static inline int wake_idle(int cpu, task_t *p)
1145{
1146 return cpu;
1147}
1148#endif
1149
1150/***
1151 * try_to_wake_up - wake up a thread
1152 * @p: the to-be-woken-up thread
1153 * @state: the mask of task states that can be woken
1154 * @sync: do a synchronous wakeup?
1155 *
1156 * Put it on the run-queue if it's not already there. The "current"
1157 * thread is always on the run-queue (except when the actual
1158 * re-schedule is in progress), and as such you're allowed to do
1159 * the simpler "current->state = TASK_RUNNING" to mark yourself
1160 * runnable without the overhead of this.
1161 *
1162 * returns failure only if the task is already active.
1163 */
95cdf3b7 1164static int try_to_wake_up(task_t *p, unsigned int state, int sync)
1da177e4
LT
1165{
1166 int cpu, this_cpu, success = 0;
1167 unsigned long flags;
1168 long old_state;
1169 runqueue_t *rq;
1170#ifdef CONFIG_SMP
1171 unsigned long load, this_load;
7897986b 1172 struct sched_domain *sd, *this_sd = NULL;
1da177e4
LT
1173 int new_cpu;
1174#endif
1175
1176 rq = task_rq_lock(p, &flags);
1177 old_state = p->state;
1178 if (!(old_state & state))
1179 goto out;
1180
1181 if (p->array)
1182 goto out_running;
1183
1184 cpu = task_cpu(p);
1185 this_cpu = smp_processor_id();
1186
1187#ifdef CONFIG_SMP
1188 if (unlikely(task_running(rq, p)))
1189 goto out_activate;
1190
7897986b
NP
1191 new_cpu = cpu;
1192
1da177e4
LT
1193 schedstat_inc(rq, ttwu_cnt);
1194 if (cpu == this_cpu) {
1195 schedstat_inc(rq, ttwu_local);
7897986b
NP
1196 goto out_set_cpu;
1197 }
1198
1199 for_each_domain(this_cpu, sd) {
1200 if (cpu_isset(cpu, sd->span)) {
1201 schedstat_inc(sd, ttwu_wake_remote);
1202 this_sd = sd;
1203 break;
1da177e4
LT
1204 }
1205 }
1da177e4 1206
d7102e95 1207 if (p->last_waker_cpu != this_cpu)
1208 goto out_set_cpu;
1209
7897986b 1210 if (unlikely(!cpu_isset(this_cpu, p->cpus_allowed)))
1da177e4
LT
1211 goto out_set_cpu;
1212
1da177e4 1213 /*
7897986b 1214 * Check for affine wakeup and passive balancing possibilities.
1da177e4 1215 */
7897986b
NP
1216 if (this_sd) {
1217 int idx = this_sd->wake_idx;
1218 unsigned int imbalance;
1da177e4 1219
a3f21bce
NP
1220 imbalance = 100 + (this_sd->imbalance_pct - 100) / 2;
1221
7897986b
NP
1222 load = source_load(cpu, idx);
1223 this_load = target_load(this_cpu, idx);
1da177e4 1224
7897986b
NP
1225 new_cpu = this_cpu; /* Wake to this CPU if we can */
1226
a3f21bce
NP
1227 if (this_sd->flags & SD_WAKE_AFFINE) {
1228 unsigned long tl = this_load;
1da177e4 1229 /*
a3f21bce
NP
1230 * If sync wakeup then subtract the (maximum possible)
1231 * effect of the currently running task from the load
1232 * of the current CPU:
1da177e4 1233 */
a3f21bce
NP
1234 if (sync)
1235 tl -= SCHED_LOAD_SCALE;
1236
1237 if ((tl <= load &&
1238 tl + target_load(cpu, idx) <= SCHED_LOAD_SCALE) ||
1239 100*(tl + SCHED_LOAD_SCALE) <= imbalance*load) {
1240 /*
1241 * This domain has SD_WAKE_AFFINE and
1242 * p is cache cold in this domain, and
1243 * there is no bad imbalance.
1244 */
1245 schedstat_inc(this_sd, ttwu_move_affine);
1246 goto out_set_cpu;
1247 }
1248 }
1249
1250 /*
1251 * Start passive balancing when half the imbalance_pct
1252 * limit is reached.
1253 */
1254 if (this_sd->flags & SD_WAKE_BALANCE) {
1255 if (imbalance*this_load <= 100*load) {
1256 schedstat_inc(this_sd, ttwu_move_balance);
1257 goto out_set_cpu;
1258 }
1da177e4
LT
1259 }
1260 }
1261
1262 new_cpu = cpu; /* Could not wake to this_cpu. Wake to cpu instead */
1263out_set_cpu:
1264 new_cpu = wake_idle(new_cpu, p);
1265 if (new_cpu != cpu) {
1266 set_task_cpu(p, new_cpu);
1267 task_rq_unlock(rq, &flags);
1268 /* might preempt at this point */
1269 rq = task_rq_lock(p, &flags);
1270 old_state = p->state;
1271 if (!(old_state & state))
1272 goto out;
1273 if (p->array)
1274 goto out_running;
1275
1276 this_cpu = smp_processor_id();
1277 cpu = task_cpu(p);
1278 }
1279
d7102e95 1280 p->last_waker_cpu = this_cpu;
1281
1da177e4
LT
1282out_activate:
1283#endif /* CONFIG_SMP */
1284 if (old_state == TASK_UNINTERRUPTIBLE) {
1285 rq->nr_uninterruptible--;
1286 /*
1287 * Tasks on involuntary sleep don't earn
1288 * sleep_avg beyond just interactive state.
1289 */
1290 p->activated = -1;
1291 }
1292
d79fc0fc
IM
1293 /*
1294 * Tasks that have marked their sleep as noninteractive get
1295 * woken up without updating their sleep average. (i.e. their
1296 * sleep is handled in a priority-neutral manner, no priority
1297 * boost and no penalty.)
1298 */
1299 if (old_state & TASK_NONINTERACTIVE)
1300 __activate_task(p, rq);
1301 else
1302 activate_task(p, rq, cpu == this_cpu);
1da177e4
LT
1303 /*
1304 * Sync wakeups (i.e. those types of wakeups where the waker
1305 * has indicated that it will leave the CPU in short order)
1306 * don't trigger a preemption, if the woken up task will run on
1307 * this cpu. (in this case the 'I will reschedule' promise of
1308 * the waker guarantees that the freshly woken up task is going
1309 * to be considered on this CPU.)
1310 */
1da177e4
LT
1311 if (!sync || cpu != this_cpu) {
1312 if (TASK_PREEMPTS_CURR(p, rq))
1313 resched_task(rq->curr);
1314 }
1315 success = 1;
1316
1317out_running:
1318 p->state = TASK_RUNNING;
1319out:
1320 task_rq_unlock(rq, &flags);
1321
1322 return success;
1323}
1324
95cdf3b7 1325int fastcall wake_up_process(task_t *p)
1da177e4
LT
1326{
1327 return try_to_wake_up(p, TASK_STOPPED | TASK_TRACED |
1328 TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE, 0);
1329}
1330
1331EXPORT_SYMBOL(wake_up_process);
1332
1333int fastcall wake_up_state(task_t *p, unsigned int state)
1334{
1335 return try_to_wake_up(p, state, 0);
1336}
1337
1da177e4
LT
1338/*
1339 * Perform scheduler related setup for a newly forked process p.
1340 * p is forked by current.
1341 */
476d139c 1342void fastcall sched_fork(task_t *p, int clone_flags)
1da177e4 1343{
476d139c
NP
1344 int cpu = get_cpu();
1345
1346#ifdef CONFIG_SMP
1347 cpu = sched_balance_self(cpu, SD_BALANCE_FORK);
1348#endif
1349 set_task_cpu(p, cpu);
1350
1da177e4
LT
1351 /*
1352 * We mark the process as running here, but have not actually
1353 * inserted it onto the runqueue yet. This guarantees that
1354 * nobody will actually run it, and a signal or other external
1355 * event cannot wake it up and insert it on the runqueue either.
1356 */
1357 p->state = TASK_RUNNING;
1358 INIT_LIST_HEAD(&p->run_list);
1359 p->array = NULL;
1da177e4
LT
1360#ifdef CONFIG_SCHEDSTATS
1361 memset(&p->sched_info, 0, sizeof(p->sched_info));
1362#endif
d7102e95 1363#if defined(CONFIG_SMP)
1364 p->last_waker_cpu = cpu;
1365#if defined(__ARCH_WANT_UNLOCKED_CTXSW)
4866cde0
NP
1366 p->oncpu = 0;
1367#endif
d7102e95 1368#endif
1da177e4 1369#ifdef CONFIG_PREEMPT
4866cde0 1370 /* Want to start with kernel preemption disabled. */
a1261f54 1371 task_thread_info(p)->preempt_count = 1;
1da177e4
LT
1372#endif
1373 /*
1374 * Share the timeslice between parent and child, thus the
1375 * total amount of pending timeslices in the system doesn't change,
1376 * resulting in more scheduling fairness.
1377 */
1378 local_irq_disable();
1379 p->time_slice = (current->time_slice + 1) >> 1;
1380 /*
1381 * The remainder of the first timeslice might be recovered by
1382 * the parent if the child exits early enough.
1383 */
1384 p->first_time_slice = 1;
1385 current->time_slice >>= 1;
1386 p->timestamp = sched_clock();
1387 if (unlikely(!current->time_slice)) {
1388 /*
1389 * This case is rare, it happens when the parent has only
1390 * a single jiffy left from its timeslice. Taking the
1391 * runqueue lock is not a problem.
1392 */
1393 current->time_slice = 1;
1da177e4 1394 scheduler_tick();
476d139c
NP
1395 }
1396 local_irq_enable();
1397 put_cpu();
1da177e4
LT
1398}
1399
1400/*
1401 * wake_up_new_task - wake up a newly created task for the first time.
1402 *
1403 * This function will do some initial scheduler statistics housekeeping
1404 * that must be done for every newly created context, then puts the task
1405 * on the runqueue and wakes it.
1406 */
95cdf3b7 1407void fastcall wake_up_new_task(task_t *p, unsigned long clone_flags)
1da177e4
LT
1408{
1409 unsigned long flags;
1410 int this_cpu, cpu;
1411 runqueue_t *rq, *this_rq;
1412
1413 rq = task_rq_lock(p, &flags);
147cbb4b 1414 BUG_ON(p->state != TASK_RUNNING);
1da177e4 1415 this_cpu = smp_processor_id();
147cbb4b 1416 cpu = task_cpu(p);
1da177e4 1417
1da177e4
LT
1418 /*
1419 * We decrease the sleep average of forking parents
1420 * and children as well, to keep max-interactive tasks
1421 * from forking tasks that are max-interactive. The parent
1422 * (current) is done further down, under its lock.
1423 */
1424 p->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(p) *
1425 CHILD_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1426
1427 p->prio = effective_prio(p);
1428
1429 if (likely(cpu == this_cpu)) {
1430 if (!(clone_flags & CLONE_VM)) {
1431 /*
1432 * The VM isn't cloned, so we're in a good position to
1433 * do child-runs-first in anticipation of an exec. This
1434 * usually avoids a lot of COW overhead.
1435 */
1436 if (unlikely(!current->array))
1437 __activate_task(p, rq);
1438 else {
1439 p->prio = current->prio;
1440 list_add_tail(&p->run_list, &current->run_list);
1441 p->array = current->array;
1442 p->array->nr_active++;
a2000572 1443 rq->nr_running++;
1da177e4
LT
1444 }
1445 set_need_resched();
1446 } else
1447 /* Run child last */
1448 __activate_task(p, rq);
1449 /*
1450 * We skip the following code due to cpu == this_cpu
1451 *
1452 * task_rq_unlock(rq, &flags);
1453 * this_rq = task_rq_lock(current, &flags);
1454 */
1455 this_rq = rq;
1456 } else {
1457 this_rq = cpu_rq(this_cpu);
1458
1459 /*
1460 * Not the local CPU - must adjust timestamp. This should
1461 * get optimised away in the !CONFIG_SMP case.
1462 */
1463 p->timestamp = (p->timestamp - this_rq->timestamp_last_tick)
1464 + rq->timestamp_last_tick;
1465 __activate_task(p, rq);
1466 if (TASK_PREEMPTS_CURR(p, rq))
1467 resched_task(rq->curr);
1468
1469 /*
1470 * Parent and child are on different CPUs, now get the
1471 * parent runqueue to update the parent's ->sleep_avg:
1472 */
1473 task_rq_unlock(rq, &flags);
1474 this_rq = task_rq_lock(current, &flags);
1475 }
1476 current->sleep_avg = JIFFIES_TO_NS(CURRENT_BONUS(current) *
1477 PARENT_PENALTY / 100 * MAX_SLEEP_AVG / MAX_BONUS);
1478 task_rq_unlock(this_rq, &flags);
1479}
1480
1481/*
1482 * Potentially available exiting-child timeslices are
1483 * retrieved here - this way the parent does not get
1484 * penalized for creating too many threads.
1485 *
1486 * (this cannot be used to 'generate' timeslices
1487 * artificially, because any timeslice recovered here
1488 * was given away by the parent in the first place.)
1489 */
95cdf3b7 1490void fastcall sched_exit(task_t *p)
1da177e4
LT
1491{
1492 unsigned long flags;
1493 runqueue_t *rq;
1494
1495 /*
1496 * If the child was a (relative-) CPU hog then decrease
1497 * the sleep_avg of the parent as well.
1498 */
1499 rq = task_rq_lock(p->parent, &flags);
889dfafe 1500 if (p->first_time_slice && task_cpu(p) == task_cpu(p->parent)) {
1da177e4
LT
1501 p->parent->time_slice += p->time_slice;
1502 if (unlikely(p->parent->time_slice > task_timeslice(p)))
1503 p->parent->time_slice = task_timeslice(p);
1504 }
1505 if (p->sleep_avg < p->parent->sleep_avg)
1506 p->parent->sleep_avg = p->parent->sleep_avg /
1507 (EXIT_WEIGHT + 1) * EXIT_WEIGHT + p->sleep_avg /
1508 (EXIT_WEIGHT + 1);
1509 task_rq_unlock(rq, &flags);
1510}
1511
4866cde0
NP
1512/**
1513 * prepare_task_switch - prepare to switch tasks
1514 * @rq: the runqueue preparing to switch
1515 * @next: the task we are going to switch to.
1516 *
1517 * This is called with the rq lock held and interrupts off. It must
1518 * be paired with a subsequent finish_task_switch after the context
1519 * switch.
1520 *
1521 * prepare_task_switch sets up locking and calls architecture specific
1522 * hooks.
1523 */
1524static inline void prepare_task_switch(runqueue_t *rq, task_t *next)
1525{
1526 prepare_lock_switch(rq, next);
1527 prepare_arch_switch(next);
1528}
1529
1da177e4
LT
1530/**
1531 * finish_task_switch - clean up after a task-switch
344babaa 1532 * @rq: runqueue associated with task-switch
1da177e4
LT
1533 * @prev: the thread we just switched away from.
1534 *
4866cde0
NP
1535 * finish_task_switch must be called after the context switch, paired
1536 * with a prepare_task_switch call before the context switch.
1537 * finish_task_switch will reconcile locking set up by prepare_task_switch,
1538 * and do any other architecture-specific cleanup actions.
1da177e4
LT
1539 *
1540 * Note that we may have delayed dropping an mm in context_switch(). If
1541 * so, we finish that here outside of the runqueue lock. (Doing it
1542 * with the lock held can cause deadlocks; see schedule() for
1543 * details.)
1544 */
4866cde0 1545static inline void finish_task_switch(runqueue_t *rq, task_t *prev)
1da177e4
LT
1546 __releases(rq->lock)
1547{
1da177e4
LT
1548 struct mm_struct *mm = rq->prev_mm;
1549 unsigned long prev_task_flags;
1550
1551 rq->prev_mm = NULL;
1552
1553 /*
1554 * A task struct has one reference for the use as "current".
1555 * If a task dies, then it sets EXIT_ZOMBIE in tsk->exit_state and
1556 * calls schedule one last time. The schedule call will never return,
1557 * and the scheduled task must drop that reference.
1558 * The test for EXIT_ZOMBIE must occur while the runqueue locks are
1559 * still held, otherwise prev could be scheduled on another cpu, die
1560 * there before we look at prev->state, and then the reference would
1561 * be dropped twice.
1562 * Manfred Spraul <manfred@colorfullife.com>
1563 */
1564 prev_task_flags = prev->flags;
4866cde0
NP
1565 finish_arch_switch(prev);
1566 finish_lock_switch(rq, prev);
1da177e4
LT
1567 if (mm)
1568 mmdrop(mm);
1569 if (unlikely(prev_task_flags & PF_DEAD))
1570 put_task_struct(prev);
1571}
1572
1573/**
1574 * schedule_tail - first thing a freshly forked thread must call.
1575 * @prev: the thread we just switched away from.
1576 */
1577asmlinkage void schedule_tail(task_t *prev)
1578 __releases(rq->lock)
1579{
4866cde0
NP
1580 runqueue_t *rq = this_rq();
1581 finish_task_switch(rq, prev);
1582#ifdef __ARCH_WANT_UNLOCKED_CTXSW
1583 /* In this case, finish_task_switch does not reenable preemption */
1584 preempt_enable();
1585#endif
1da177e4
LT
1586 if (current->set_child_tid)
1587 put_user(current->pid, current->set_child_tid);
1588}
1589
1590/*
1591 * context_switch - switch to the new MM and the new
1592 * thread's register state.
1593 */
1594static inline
1595task_t * context_switch(runqueue_t *rq, task_t *prev, task_t *next)
1596{
1597 struct mm_struct *mm = next->mm;
1598 struct mm_struct *oldmm = prev->active_mm;
1599
1600 if (unlikely(!mm)) {
1601 next->active_mm = oldmm;
1602 atomic_inc(&oldmm->mm_count);
1603 enter_lazy_tlb(oldmm, next);
1604 } else
1605 switch_mm(oldmm, mm, next);
1606
1607 if (unlikely(!prev->mm)) {
1608 prev->active_mm = NULL;
1609 WARN_ON(rq->prev_mm);
1610 rq->prev_mm = oldmm;
1611 }
1612
1613 /* Here we just switch the register state and the stack. */
1614 switch_to(prev, next, prev);
1615
1616 return prev;
1617}
1618
1619/*
1620 * nr_running, nr_uninterruptible and nr_context_switches:
1621 *
1622 * externally visible scheduler statistics: current number of runnable
1623 * threads, current number of uninterruptible-sleeping threads, total
1624 * number of context switches performed since bootup.
1625 */
1626unsigned long nr_running(void)
1627{
1628 unsigned long i, sum = 0;
1629
1630 for_each_online_cpu(i)
1631 sum += cpu_rq(i)->nr_running;
1632
1633 return sum;
1634}
1635
1636unsigned long nr_uninterruptible(void)
1637{
1638 unsigned long i, sum = 0;
1639
1640 for_each_cpu(i)
1641 sum += cpu_rq(i)->nr_uninterruptible;
1642
1643 /*
1644 * Since we read the counters lockless, it might be slightly
1645 * inaccurate. Do not allow it to go below zero though:
1646 */
1647 if (unlikely((long)sum < 0))
1648 sum = 0;
1649
1650 return sum;
1651}
1652
1653unsigned long long nr_context_switches(void)
1654{
1655 unsigned long long i, sum = 0;
1656
1657 for_each_cpu(i)
1658 sum += cpu_rq(i)->nr_switches;
1659
1660 return sum;
1661}
1662
1663unsigned long nr_iowait(void)
1664{
1665 unsigned long i, sum = 0;
1666
1667 for_each_cpu(i)
1668 sum += atomic_read(&cpu_rq(i)->nr_iowait);
1669
1670 return sum;
1671}
1672
1673#ifdef CONFIG_SMP
1674
1675/*
1676 * double_rq_lock - safely lock two runqueues
1677 *
1678 * Note this does not disable interrupts like task_rq_lock,
1679 * you need to do so manually before calling.
1680 */
1681static void double_rq_lock(runqueue_t *rq1, runqueue_t *rq2)
1682 __acquires(rq1->lock)
1683 __acquires(rq2->lock)
1684{
1685 if (rq1 == rq2) {
1686 spin_lock(&rq1->lock);
1687 __acquire(rq2->lock); /* Fake it out ;) */
1688 } else {
1689 if (rq1 < rq2) {
1690 spin_lock(&rq1->lock);
1691 spin_lock(&rq2->lock);
1692 } else {
1693 spin_lock(&rq2->lock);
1694 spin_lock(&rq1->lock);
1695 }
1696 }
1697}
1698
1699/*
1700 * double_rq_unlock - safely unlock two runqueues
1701 *
1702 * Note this does not restore interrupts like task_rq_unlock,
1703 * you need to do so manually after calling.
1704 */
1705static void double_rq_unlock(runqueue_t *rq1, runqueue_t *rq2)
1706 __releases(rq1->lock)
1707 __releases(rq2->lock)
1708{
1709 spin_unlock(&rq1->lock);
1710 if (rq1 != rq2)
1711 spin_unlock(&rq2->lock);
1712 else
1713 __release(rq2->lock);
1714}
1715
1716/*
1717 * double_lock_balance - lock the busiest runqueue, this_rq is locked already.
1718 */
1719static void double_lock_balance(runqueue_t *this_rq, runqueue_t *busiest)
1720 __releases(this_rq->lock)
1721 __acquires(busiest->lock)
1722 __acquires(this_rq->lock)
1723{
1724 if (unlikely(!spin_trylock(&busiest->lock))) {
1725 if (busiest < this_rq) {
1726 spin_unlock(&this_rq->lock);
1727 spin_lock(&busiest->lock);
1728 spin_lock(&this_rq->lock);
1729 } else
1730 spin_lock(&busiest->lock);
1731 }
1732}
1733
1da177e4
LT
1734/*
1735 * If dest_cpu is allowed for this process, migrate the task to it.
1736 * This is accomplished by forcing the cpu_allowed mask to only
1737 * allow dest_cpu, which will force the cpu onto dest_cpu. Then
1738 * the cpu_allowed mask is restored.
1739 */
1740static void sched_migrate_task(task_t *p, int dest_cpu)
1741{
1742 migration_req_t req;
1743 runqueue_t *rq;
1744 unsigned long flags;
1745
1746 rq = task_rq_lock(p, &flags);
1747 if (!cpu_isset(dest_cpu, p->cpus_allowed)
1748 || unlikely(cpu_is_offline(dest_cpu)))
1749 goto out;
1750
1751 /* force the process onto the specified CPU */
1752 if (migrate_task(p, dest_cpu, &req)) {
1753 /* Need to wait for migration thread (might exit: take ref). */
1754 struct task_struct *mt = rq->migration_thread;
1755 get_task_struct(mt);
1756 task_rq_unlock(rq, &flags);
1757 wake_up_process(mt);
1758 put_task_struct(mt);
1759 wait_for_completion(&req.done);
1760 return;
1761 }
1762out:
1763 task_rq_unlock(rq, &flags);
1764}
1765
1766/*
476d139c
NP
1767 * sched_exec - execve() is a valuable balancing opportunity, because at
1768 * this point the task has the smallest effective memory and cache footprint.
1da177e4
LT
1769 */
1770void sched_exec(void)
1771{
1da177e4 1772 int new_cpu, this_cpu = get_cpu();
476d139c 1773 new_cpu = sched_balance_self(this_cpu, SD_BALANCE_EXEC);
1da177e4 1774 put_cpu();
476d139c
NP
1775 if (new_cpu != this_cpu)
1776 sched_migrate_task(current, new_cpu);
1da177e4
LT
1777}
1778
1779/*
1780 * pull_task - move a task from a remote runqueue to the local runqueue.
1781 * Both runqueues must be locked.
1782 */
858119e1 1783static
1da177e4
LT
1784void pull_task(runqueue_t *src_rq, prio_array_t *src_array, task_t *p,
1785 runqueue_t *this_rq, prio_array_t *this_array, int this_cpu)
1786{
1787 dequeue_task(p, src_array);
a2000572 1788 src_rq->nr_running--;
1da177e4 1789 set_task_cpu(p, this_cpu);
a2000572 1790 this_rq->nr_running++;
1da177e4
LT
1791 enqueue_task(p, this_array);
1792 p->timestamp = (p->timestamp - src_rq->timestamp_last_tick)
1793 + this_rq->timestamp_last_tick;
1794 /*
1795 * Note that idle threads have a prio of MAX_PRIO, for this test
1796 * to be always true for them.
1797 */
1798 if (TASK_PREEMPTS_CURR(p, this_rq))
1799 resched_task(this_rq->curr);
1800}
1801
1802/*
1803 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu?
1804 */
858119e1 1805static
1da177e4 1806int can_migrate_task(task_t *p, runqueue_t *rq, int this_cpu,
95cdf3b7
IM
1807 struct sched_domain *sd, enum idle_type idle,
1808 int *all_pinned)
1da177e4
LT
1809{
1810 /*
1811 * We do not migrate tasks that are:
1812 * 1) running (obviously), or
1813 * 2) cannot be migrated to this CPU due to cpus_allowed, or
1814 * 3) are cache-hot on their current CPU.
1815 */
1da177e4
LT
1816 if (!cpu_isset(this_cpu, p->cpus_allowed))
1817 return 0;
81026794
NP
1818 *all_pinned = 0;
1819
1820 if (task_running(rq, p))
1821 return 0;
1da177e4
LT
1822
1823 /*
1824 * Aggressive migration if:
cafb20c1 1825 * 1) task is cache cold, or
1da177e4
LT
1826 * 2) too many balance attempts have failed.
1827 */
1828
cafb20c1 1829 if (sd->nr_balance_failed > sd->cache_nice_tries)
1da177e4
LT
1830 return 1;
1831
1832 if (task_hot(p, rq->timestamp_last_tick, sd))
81026794 1833 return 0;
1da177e4
LT
1834 return 1;
1835}
1836
1837/*
1838 * move_tasks tries to move up to max_nr_move tasks from busiest to this_rq,
1839 * as part of a balancing operation within "domain". Returns the number of
1840 * tasks moved.
1841 *
1842 * Called with both runqueues locked.
1843 */
1844static int move_tasks(runqueue_t *this_rq, int this_cpu, runqueue_t *busiest,
1845 unsigned long max_nr_move, struct sched_domain *sd,
81026794 1846 enum idle_type idle, int *all_pinned)
1da177e4
LT
1847{
1848 prio_array_t *array, *dst_array;
1849 struct list_head *head, *curr;
81026794 1850 int idx, pulled = 0, pinned = 0;
1da177e4
LT
1851 task_t *tmp;
1852
81026794 1853 if (max_nr_move == 0)
1da177e4
LT
1854 goto out;
1855
81026794
NP
1856 pinned = 1;
1857
1da177e4
LT
1858 /*
1859 * We first consider expired tasks. Those will likely not be
1860 * executed in the near future, and they are most likely to
1861 * be cache-cold, thus switching CPUs has the least effect
1862 * on them.
1863 */
1864 if (busiest->expired->nr_active) {
1865 array = busiest->expired;
1866 dst_array = this_rq->expired;
1867 } else {
1868 array = busiest->active;
1869 dst_array = this_rq->active;
1870 }
1871
1872new_array:
1873 /* Start searching at priority 0: */
1874 idx = 0;
1875skip_bitmap:
1876 if (!idx)
1877 idx = sched_find_first_bit(array->bitmap);
1878 else
1879 idx = find_next_bit(array->bitmap, MAX_PRIO, idx);
1880 if (idx >= MAX_PRIO) {
1881 if (array == busiest->expired && busiest->active->nr_active) {
1882 array = busiest->active;
1883 dst_array = this_rq->active;
1884 goto new_array;
1885 }
1886 goto out;
1887 }
1888
1889 head = array->queue + idx;
1890 curr = head->prev;
1891skip_queue:
1892 tmp = list_entry(curr, task_t, run_list);
1893
1894 curr = curr->prev;
1895
81026794 1896 if (!can_migrate_task(tmp, busiest, this_cpu, sd, idle, &pinned)) {
1da177e4
LT
1897 if (curr != head)
1898 goto skip_queue;
1899 idx++;
1900 goto skip_bitmap;
1901 }
1902
1903#ifdef CONFIG_SCHEDSTATS
1904 if (task_hot(tmp, busiest->timestamp_last_tick, sd))
1905 schedstat_inc(sd, lb_hot_gained[idle]);
1906#endif
1907
1908 pull_task(busiest, array, tmp, this_rq, dst_array, this_cpu);
1909 pulled++;
1910
1911 /* We only want to steal up to the prescribed number of tasks. */
1912 if (pulled < max_nr_move) {
1913 if (curr != head)
1914 goto skip_queue;
1915 idx++;
1916 goto skip_bitmap;
1917 }
1918out:
1919 /*
1920 * Right now, this is the only place pull_task() is called,
1921 * so we can safely collect pull_task() stats here rather than
1922 * inside pull_task().
1923 */
1924 schedstat_add(sd, lb_gained[idle], pulled);
81026794
NP
1925
1926 if (all_pinned)
1927 *all_pinned = pinned;
1da177e4
LT
1928 return pulled;
1929}
1930
1931/*
1932 * find_busiest_group finds and returns the busiest CPU group within the
1933 * domain. It calculates and returns the number of tasks which should be
1934 * moved to restore balance via the imbalance parameter.
1935 */
1936static struct sched_group *
1937find_busiest_group(struct sched_domain *sd, int this_cpu,
5969fe06 1938 unsigned long *imbalance, enum idle_type idle, int *sd_idle)
1da177e4
LT
1939{
1940 struct sched_group *busiest = NULL, *this = NULL, *group = sd->groups;
1941 unsigned long max_load, avg_load, total_load, this_load, total_pwr;
0c117f1b 1942 unsigned long max_pull;
7897986b 1943 int load_idx;
1da177e4
LT
1944
1945 max_load = this_load = total_load = total_pwr = 0;
7897986b
NP
1946 if (idle == NOT_IDLE)
1947 load_idx = sd->busy_idx;
1948 else if (idle == NEWLY_IDLE)
1949 load_idx = sd->newidle_idx;
1950 else
1951 load_idx = sd->idle_idx;
1da177e4
LT
1952
1953 do {
1954 unsigned long load;
1955 int local_group;
1956 int i;
1957
1958 local_group = cpu_isset(this_cpu, group->cpumask);
1959
1960 /* Tally up the load of all CPUs in the group */
1961 avg_load = 0;
1962
1963 for_each_cpu_mask(i, group->cpumask) {
5969fe06
NP
1964 if (*sd_idle && !idle_cpu(i))
1965 *sd_idle = 0;
1966
1da177e4
LT
1967 /* Bias balancing toward cpus of our domain */
1968 if (local_group)
a2000572 1969 load = target_load(i, load_idx);
1da177e4 1970 else
a2000572 1971 load = source_load(i, load_idx);
1da177e4
LT
1972
1973 avg_load += load;
1974 }
1975
1976 total_load += avg_load;
1977 total_pwr += group->cpu_power;
1978
1979 /* Adjust by relative CPU power of the group */
1980 avg_load = (avg_load * SCHED_LOAD_SCALE) / group->cpu_power;
1981
1982 if (local_group) {
1983 this_load = avg_load;
1984 this = group;
1da177e4
LT
1985 } else if (avg_load > max_load) {
1986 max_load = avg_load;
1987 busiest = group;
1988 }
1da177e4
LT
1989 group = group->next;
1990 } while (group != sd->groups);
1991
0c117f1b 1992 if (!busiest || this_load >= max_load || max_load <= SCHED_LOAD_SCALE)
1da177e4
LT
1993 goto out_balanced;
1994
1995 avg_load = (SCHED_LOAD_SCALE * total_load) / total_pwr;
1996
1997 if (this_load >= avg_load ||
1998 100*max_load <= sd->imbalance_pct*this_load)
1999 goto out_balanced;
2000
2001 /*
2002 * We're trying to get all the cpus to the average_load, so we don't
2003 * want to push ourselves above the average load, nor do we wish to
2004 * reduce the max loaded cpu below the average load, as either of these
2005 * actions would just result in more rebalancing later, and ping-pong
2006 * tasks around. Thus we look for the minimum possible imbalance.
2007 * Negative imbalances (*we* are more loaded than anyone else) will
2008 * be counted as no imbalance for these purposes -- we can't fix that
2009 * by pulling tasks to us. Be careful of negative numbers as they'll
2010 * appear as very large values with unsigned longs.
2011 */
0c117f1b
SS
2012
2013 /* Don't want to pull so many tasks that a group would go idle */
2014 max_pull = min(max_load - avg_load, max_load - SCHED_LOAD_SCALE);
2015
1da177e4 2016 /* How much load to actually move to equalise the imbalance */
0c117f1b 2017 *imbalance = min(max_pull * busiest->cpu_power,
1da177e4
LT
2018 (avg_load - this_load) * this->cpu_power)
2019 / SCHED_LOAD_SCALE;
2020
2021 if (*imbalance < SCHED_LOAD_SCALE) {
2022 unsigned long pwr_now = 0, pwr_move = 0;
2023 unsigned long tmp;
2024
2025 if (max_load - this_load >= SCHED_LOAD_SCALE*2) {
2026 *imbalance = 1;
2027 return busiest;
2028 }
2029
2030 /*
2031 * OK, we don't have enough imbalance to justify moving tasks,
2032 * however we may be able to increase total CPU power used by
2033 * moving them.
2034 */
2035
2036 pwr_now += busiest->cpu_power*min(SCHED_LOAD_SCALE, max_load);
2037 pwr_now += this->cpu_power*min(SCHED_LOAD_SCALE, this_load);
2038 pwr_now /= SCHED_LOAD_SCALE;
2039
2040 /* Amount of load we'd subtract */
2041 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/busiest->cpu_power;
2042 if (max_load > tmp)
2043 pwr_move += busiest->cpu_power*min(SCHED_LOAD_SCALE,
2044 max_load - tmp);
2045
2046 /* Amount of load we'd add */
2047 if (max_load*busiest->cpu_power <
2048 SCHED_LOAD_SCALE*SCHED_LOAD_SCALE)
2049 tmp = max_load*busiest->cpu_power/this->cpu_power;
2050 else
2051 tmp = SCHED_LOAD_SCALE*SCHED_LOAD_SCALE/this->cpu_power;
2052 pwr_move += this->cpu_power*min(SCHED_LOAD_SCALE, this_load + tmp);
2053 pwr_move /= SCHED_LOAD_SCALE;
2054
2055 /* Move if we gain throughput */
2056 if (pwr_move <= pwr_now)
2057 goto out_balanced;
2058
2059 *imbalance = 1;
2060 return busiest;
2061 }
2062
2063 /* Get rid of the scaling factor, rounding down as we divide */
2064 *imbalance = *imbalance / SCHED_LOAD_SCALE;
1da177e4
LT
2065 return busiest;
2066
2067out_balanced:
1da177e4
LT
2068
2069 *imbalance = 0;
2070 return NULL;
2071}
2072
2073/*
2074 * find_busiest_queue - find the busiest runqueue among the cpus in group.
2075 */
b910472d
CK
2076static runqueue_t *find_busiest_queue(struct sched_group *group,
2077 enum idle_type idle)
1da177e4
LT
2078{
2079 unsigned long load, max_load = 0;
2080 runqueue_t *busiest = NULL;
2081 int i;
2082
2083 for_each_cpu_mask(i, group->cpumask) {
a2000572 2084 load = source_load(i, 0);
1da177e4
LT
2085
2086 if (load > max_load) {
2087 max_load = load;
2088 busiest = cpu_rq(i);
2089 }
2090 }
2091
2092 return busiest;
2093}
2094
77391d71
NP
2095/*
2096 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but
2097 * so long as it is large enough.
2098 */
2099#define MAX_PINNED_INTERVAL 512
2100
1da177e4
LT
2101/*
2102 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2103 * tasks if there is an imbalance.
2104 *
2105 * Called with this_rq unlocked.
2106 */
2107static int load_balance(int this_cpu, runqueue_t *this_rq,
2108 struct sched_domain *sd, enum idle_type idle)
2109{
2110 struct sched_group *group;
2111 runqueue_t *busiest;
2112 unsigned long imbalance;
77391d71 2113 int nr_moved, all_pinned = 0;
81026794 2114 int active_balance = 0;
5969fe06
NP
2115 int sd_idle = 0;
2116
2117 if (idle != NOT_IDLE && sd->flags & SD_SHARE_CPUPOWER)
2118 sd_idle = 1;
1da177e4 2119
1da177e4
LT
2120 schedstat_inc(sd, lb_cnt[idle]);
2121
5969fe06 2122 group = find_busiest_group(sd, this_cpu, &imbalance, idle, &sd_idle);
1da177e4
LT
2123 if (!group) {
2124 schedstat_inc(sd, lb_nobusyg[idle]);
2125 goto out_balanced;
2126 }
2127
b910472d 2128 busiest = find_busiest_queue(group, idle);
1da177e4
LT
2129 if (!busiest) {
2130 schedstat_inc(sd, lb_nobusyq[idle]);
2131 goto out_balanced;
2132 }
2133
db935dbd 2134 BUG_ON(busiest == this_rq);
1da177e4
LT
2135
2136 schedstat_add(sd, lb_imbalance[idle], imbalance);
2137
2138 nr_moved = 0;
2139 if (busiest->nr_running > 1) {
2140 /*
2141 * Attempt to move tasks. If find_busiest_group has found
2142 * an imbalance but busiest->nr_running <= 1, the group is
2143 * still unbalanced. nr_moved simply stays zero, so it is
2144 * correctly treated as an imbalance.
2145 */
e17224bf 2146 double_rq_lock(this_rq, busiest);
1da177e4 2147 nr_moved = move_tasks(this_rq, this_cpu, busiest,
d6d5cfaf 2148 imbalance, sd, idle, &all_pinned);
e17224bf 2149 double_rq_unlock(this_rq, busiest);
81026794
NP
2150
2151 /* All tasks on this runqueue were pinned by CPU affinity */
2152 if (unlikely(all_pinned))
2153 goto out_balanced;
1da177e4 2154 }
81026794 2155
1da177e4
LT
2156 if (!nr_moved) {
2157 schedstat_inc(sd, lb_failed[idle]);
2158 sd->nr_balance_failed++;
2159
2160 if (unlikely(sd->nr_balance_failed > sd->cache_nice_tries+2)) {
1da177e4
LT
2161
2162 spin_lock(&busiest->lock);
fa3b6ddc
SS
2163
2164 /* don't kick the migration_thread, if the curr
2165 * task on busiest cpu can't be moved to this_cpu
2166 */
2167 if (!cpu_isset(this_cpu, busiest->curr->cpus_allowed)) {
2168 spin_unlock(&busiest->lock);
2169 all_pinned = 1;
2170 goto out_one_pinned;
2171 }
2172
1da177e4
LT
2173 if (!busiest->active_balance) {
2174 busiest->active_balance = 1;
2175 busiest->push_cpu = this_cpu;
81026794 2176 active_balance = 1;
1da177e4
LT
2177 }
2178 spin_unlock(&busiest->lock);
81026794 2179 if (active_balance)
1da177e4
LT
2180 wake_up_process(busiest->migration_thread);
2181
2182 /*
2183 * We've kicked active balancing, reset the failure
2184 * counter.
2185 */
39507451 2186 sd->nr_balance_failed = sd->cache_nice_tries+1;
1da177e4 2187 }
81026794 2188 } else
1da177e4
LT
2189 sd->nr_balance_failed = 0;
2190
81026794 2191 if (likely(!active_balance)) {
1da177e4
LT
2192 /* We were unbalanced, so reset the balancing interval */
2193 sd->balance_interval = sd->min_interval;
81026794
NP
2194 } else {
2195 /*
2196 * If we've begun active balancing, start to back off. This
2197 * case may not be covered by the all_pinned logic if there
2198 * is only 1 task on the busy runqueue (because we don't call
2199 * move_tasks).
2200 */
2201 if (sd->balance_interval < sd->max_interval)
2202 sd->balance_interval *= 2;
1da177e4
LT
2203 }
2204
5969fe06
NP
2205 if (!nr_moved && !sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2206 return -1;
1da177e4
LT
2207 return nr_moved;
2208
2209out_balanced:
1da177e4
LT
2210 schedstat_inc(sd, lb_balanced[idle]);
2211
16cfb1c0 2212 sd->nr_balance_failed = 0;
fa3b6ddc
SS
2213
2214out_one_pinned:
1da177e4 2215 /* tune up the balancing interval */
77391d71
NP
2216 if ((all_pinned && sd->balance_interval < MAX_PINNED_INTERVAL) ||
2217 (sd->balance_interval < sd->max_interval))
1da177e4
LT
2218 sd->balance_interval *= 2;
2219
5969fe06
NP
2220 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2221 return -1;
1da177e4
LT
2222 return 0;
2223}
2224
2225/*
2226 * Check this_cpu to ensure it is balanced within domain. Attempt to move
2227 * tasks if there is an imbalance.
2228 *
2229 * Called from schedule when this_rq is about to become idle (NEWLY_IDLE).
2230 * this_rq is locked.
2231 */
2232static int load_balance_newidle(int this_cpu, runqueue_t *this_rq,
2233 struct sched_domain *sd)
2234{
2235 struct sched_group *group;
2236 runqueue_t *busiest = NULL;
2237 unsigned long imbalance;
2238 int nr_moved = 0;
5969fe06
NP
2239 int sd_idle = 0;
2240
2241 if (sd->flags & SD_SHARE_CPUPOWER)
2242 sd_idle = 1;
1da177e4
LT
2243
2244 schedstat_inc(sd, lb_cnt[NEWLY_IDLE]);
5969fe06 2245 group = find_busiest_group(sd, this_cpu, &imbalance, NEWLY_IDLE, &sd_idle);
1da177e4 2246 if (!group) {
1da177e4 2247 schedstat_inc(sd, lb_nobusyg[NEWLY_IDLE]);
16cfb1c0 2248 goto out_balanced;
1da177e4
LT
2249 }
2250
b910472d 2251 busiest = find_busiest_queue(group, NEWLY_IDLE);
db935dbd 2252 if (!busiest) {
1da177e4 2253 schedstat_inc(sd, lb_nobusyq[NEWLY_IDLE]);
16cfb1c0 2254 goto out_balanced;
1da177e4
LT
2255 }
2256
db935dbd
NP
2257 BUG_ON(busiest == this_rq);
2258
1da177e4 2259 schedstat_add(sd, lb_imbalance[NEWLY_IDLE], imbalance);
d6d5cfaf
NP
2260
2261 nr_moved = 0;
2262 if (busiest->nr_running > 1) {
2263 /* Attempt to move tasks */
2264 double_lock_balance(this_rq, busiest);
2265 nr_moved = move_tasks(this_rq, this_cpu, busiest,
81026794 2266 imbalance, sd, NEWLY_IDLE, NULL);
d6d5cfaf
NP
2267 spin_unlock(&busiest->lock);
2268 }
2269
5969fe06 2270 if (!nr_moved) {
1da177e4 2271 schedstat_inc(sd, lb_failed[NEWLY_IDLE]);
5969fe06
NP
2272 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2273 return -1;
2274 } else
16cfb1c0 2275 sd->nr_balance_failed = 0;
1da177e4 2276
1da177e4 2277 return nr_moved;
16cfb1c0
NP
2278
2279out_balanced:
2280 schedstat_inc(sd, lb_balanced[NEWLY_IDLE]);
5969fe06
NP
2281 if (!sd_idle && sd->flags & SD_SHARE_CPUPOWER)
2282 return -1;
16cfb1c0
NP
2283 sd->nr_balance_failed = 0;
2284 return 0;
1da177e4
LT
2285}
2286
2287/*
2288 * idle_balance is called by schedule() if this_cpu is about to become
2289 * idle. Attempts to pull tasks from other CPUs.
2290 */
858119e1 2291static void idle_balance(int this_cpu, runqueue_t *this_rq)
1da177e4
LT
2292{
2293 struct sched_domain *sd;
2294
2295 for_each_domain(this_cpu, sd) {
2296 if (sd->flags & SD_BALANCE_NEWIDLE) {
2297 if (load_balance_newidle(this_cpu, this_rq, sd)) {
2298 /* We've pulled tasks over so stop searching */
2299 break;
2300 }
2301 }
2302 }
2303}
2304
2305/*
2306 * active_load_balance is run by migration threads. It pushes running tasks
2307 * off the busiest CPU onto idle CPUs. It requires at least 1 task to be
2308 * running on each physical CPU where possible, and avoids physical /
2309 * logical imbalances.
2310 *
2311 * Called with busiest_rq locked.
2312 */
2313static void active_load_balance(runqueue_t *busiest_rq, int busiest_cpu)
2314{
2315 struct sched_domain *sd;
1da177e4 2316 runqueue_t *target_rq;
39507451
NP
2317 int target_cpu = busiest_rq->push_cpu;
2318
2319 if (busiest_rq->nr_running <= 1)
2320 /* no task to move */
2321 return;
2322
2323 target_rq = cpu_rq(target_cpu);
1da177e4
LT
2324
2325 /*
39507451
NP
2326 * This condition is "impossible", if it occurs
2327 * we need to fix it. Originally reported by
2328 * Bjorn Helgaas on a 128-cpu setup.
1da177e4 2329 */
39507451 2330 BUG_ON(busiest_rq == target_rq);
1da177e4 2331
39507451
NP
2332 /* move a task from busiest_rq to target_rq */
2333 double_lock_balance(busiest_rq, target_rq);
2334
2335 /* Search for an sd spanning us and the target CPU. */
2336 for_each_domain(target_cpu, sd)
2337 if ((sd->flags & SD_LOAD_BALANCE) &&
2338 cpu_isset(busiest_cpu, sd->span))
2339 break;
2340
2341 if (unlikely(sd == NULL))
2342 goto out;
2343
2344 schedstat_inc(sd, alb_cnt);
2345
2346 if (move_tasks(target_rq, target_cpu, busiest_rq, 1, sd, SCHED_IDLE, NULL))
2347 schedstat_inc(sd, alb_pushed);
2348 else
2349 schedstat_inc(sd, alb_failed);
2350out:
2351 spin_unlock(&target_rq->lock);
1da177e4
LT
2352}
2353
2354/*
2355 * rebalance_tick will get called every timer tick, on every CPU.
2356 *
2357 * It checks each scheduling domain to see if it is due to be balanced,
2358 * and initiates a balancing operation if so.
2359 *
2360 * Balancing parameters are set up in arch_init_sched_domains.
2361 */
2362
2363/* Don't have all balancing operations going off at once */
2364#define CPU_OFFSET(cpu) (HZ * cpu / NR_CPUS)
2365
2366static void rebalance_tick(int this_cpu, runqueue_t *this_rq,
2367 enum idle_type idle)
2368{
2369 unsigned long old_load, this_load;
2370 unsigned long j = jiffies + CPU_OFFSET(this_cpu);
2371 struct sched_domain *sd;
7897986b 2372 int i;
1da177e4 2373
1da177e4 2374 this_load = this_rq->nr_running * SCHED_LOAD_SCALE;
7897986b
NP
2375 /* Update our load */
2376 for (i = 0; i < 3; i++) {
2377 unsigned long new_load = this_load;
2378 int scale = 1 << i;
2379 old_load = this_rq->cpu_load[i];
2380 /*
2381 * Round up the averaging division if load is increasing. This
2382 * prevents us from getting stuck on 9 if the load is 10, for
2383 * example.
2384 */
2385 if (new_load > old_load)
2386 new_load += scale-1;
2387 this_rq->cpu_load[i] = (old_load*(scale-1) + new_load) / scale;
2388 }
1da177e4
LT
2389
2390 for_each_domain(this_cpu, sd) {
2391 unsigned long interval;
2392
2393 if (!(sd->flags & SD_LOAD_BALANCE))
2394 continue;
2395
2396 interval = sd->balance_interval;
2397 if (idle != SCHED_IDLE)
2398 interval *= sd->busy_factor;
2399
2400 /* scale ms to jiffies */
2401 interval = msecs_to_jiffies(interval);
2402 if (unlikely(!interval))
2403 interval = 1;
2404
2405 if (j - sd->last_balance >= interval) {
2406 if (load_balance(this_cpu, this_rq, sd, idle)) {
fa3b6ddc
SS
2407 /*
2408 * We've pulled tasks over so either we're no
5969fe06
NP
2409 * longer idle, or one of our SMT siblings is
2410 * not idle.
2411 */
1da177e4
LT
2412 idle = NOT_IDLE;
2413 }
2414 sd->last_balance += interval;
2415 }
2416 }
2417}
2418#else
2419/*
2420 * on UP we do not need to balance between CPUs:
2421 */
2422static inline void rebalance_tick(int cpu, runqueue_t *rq, enum idle_type idle)
2423{
2424}
2425static inline void idle_balance(int cpu, runqueue_t *rq)
2426{
2427}
2428#endif
2429
2430static inline int wake_priority_sleeper(runqueue_t *rq)
2431{
2432 int ret = 0;
2433#ifdef CONFIG_SCHED_SMT
2434 spin_lock(&rq->lock);
2435 /*
2436 * If an SMT sibling task has been put to sleep for priority
2437 * reasons reschedule the idle task to see if it can now run.
2438 */
2439 if (rq->nr_running) {
2440 resched_task(rq->idle);
2441 ret = 1;
2442 }
2443 spin_unlock(&rq->lock);
2444#endif
2445 return ret;
2446}
2447
2448DEFINE_PER_CPU(struct kernel_stat, kstat);
2449
2450EXPORT_PER_CPU_SYMBOL(kstat);
2451
2452/*
2453 * This is called on clock ticks and on context switches.
2454 * Bank in p->sched_time the ns elapsed since the last tick or switch.
2455 */
2456static inline void update_cpu_clock(task_t *p, runqueue_t *rq,
2457 unsigned long long now)
2458{
2459 unsigned long long last = max(p->timestamp, rq->timestamp_last_tick);
2460 p->sched_time += now - last;
2461}
2462
2463/*
2464 * Return current->sched_time plus any more ns on the sched_clock
2465 * that have not yet been banked.
2466 */
2467unsigned long long current_sched_time(const task_t *tsk)
2468{
2469 unsigned long long ns;
2470 unsigned long flags;
2471 local_irq_save(flags);
2472 ns = max(tsk->timestamp, task_rq(tsk)->timestamp_last_tick);
2473 ns = tsk->sched_time + (sched_clock() - ns);
2474 local_irq_restore(flags);
2475 return ns;
2476}
2477
2478/*
2479 * We place interactive tasks back into the active array, if possible.
2480 *
2481 * To guarantee that this does not starve expired tasks we ignore the
2482 * interactivity of a task if the first expired task had to wait more
2483 * than a 'reasonable' amount of time. This deadline timeout is
2484 * load-dependent, as the frequency of array switched decreases with
2485 * increasing number of running tasks. We also ignore the interactivity
2486 * if a better static_prio task has expired:
2487 */
2488#define EXPIRED_STARVING(rq) \
2489 ((STARVATION_LIMIT && ((rq)->expired_timestamp && \
2490 (jiffies - (rq)->expired_timestamp >= \
2491 STARVATION_LIMIT * ((rq)->nr_running) + 1))) || \
2492 ((rq)->curr->static_prio > (rq)->best_expired_prio))
2493
2494/*
2495 * Account user cpu time to a process.
2496 * @p: the process that the cpu time gets accounted to
2497 * @hardirq_offset: the offset to subtract from hardirq_count()
2498 * @cputime: the cpu time spent in user space since the last update
2499 */
2500void account_user_time(struct task_struct *p, cputime_t cputime)
2501{
2502 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2503 cputime64_t tmp;
2504
2505 p->utime = cputime_add(p->utime, cputime);
2506
2507 /* Add user time to cpustat. */
2508 tmp = cputime_to_cputime64(cputime);
2509 if (TASK_NICE(p) > 0)
2510 cpustat->nice = cputime64_add(cpustat->nice, tmp);
2511 else
2512 cpustat->user = cputime64_add(cpustat->user, tmp);
2513}
2514
2515/*
2516 * Account system cpu time to a process.
2517 * @p: the process that the cpu time gets accounted to
2518 * @hardirq_offset: the offset to subtract from hardirq_count()
2519 * @cputime: the cpu time spent in kernel space since the last update
2520 */
2521void account_system_time(struct task_struct *p, int hardirq_offset,
2522 cputime_t cputime)
2523{
2524 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2525 runqueue_t *rq = this_rq();
2526 cputime64_t tmp;
2527
2528 p->stime = cputime_add(p->stime, cputime);
2529
2530 /* Add system time to cpustat. */
2531 tmp = cputime_to_cputime64(cputime);
2532 if (hardirq_count() - hardirq_offset)
2533 cpustat->irq = cputime64_add(cpustat->irq, tmp);
2534 else if (softirq_count())
2535 cpustat->softirq = cputime64_add(cpustat->softirq, tmp);
2536 else if (p != rq->idle)
2537 cpustat->system = cputime64_add(cpustat->system, tmp);
2538 else if (atomic_read(&rq->nr_iowait) > 0)
2539 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2540 else
2541 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2542 /* Account for system time used */
2543 acct_update_integrals(p);
1da177e4
LT
2544}
2545
2546/*
2547 * Account for involuntary wait time.
2548 * @p: the process from which the cpu time has been stolen
2549 * @steal: the cpu time spent in involuntary wait
2550 */
2551void account_steal_time(struct task_struct *p, cputime_t steal)
2552{
2553 struct cpu_usage_stat *cpustat = &kstat_this_cpu.cpustat;
2554 cputime64_t tmp = cputime_to_cputime64(steal);
2555 runqueue_t *rq = this_rq();
2556
2557 if (p == rq->idle) {
2558 p->stime = cputime_add(p->stime, steal);
2559 if (atomic_read(&rq->nr_iowait) > 0)
2560 cpustat->iowait = cputime64_add(cpustat->iowait, tmp);
2561 else
2562 cpustat->idle = cputime64_add(cpustat->idle, tmp);
2563 } else
2564 cpustat->steal = cputime64_add(cpustat->steal, tmp);
2565}
2566
2567/*
2568 * This function gets called by the timer code, with HZ frequency.
2569 * We call it with interrupts disabled.
2570 *
2571 * It also gets called by the fork code, when changing the parent's
2572 * timeslices.
2573 */
2574void scheduler_tick(void)
2575{
2576 int cpu = smp_processor_id();
2577 runqueue_t *rq = this_rq();
2578 task_t *p = current;
2579 unsigned long long now = sched_clock();
2580
2581 update_cpu_clock(p, rq, now);
2582
2583 rq->timestamp_last_tick = now;
2584
2585 if (p == rq->idle) {
2586 if (wake_priority_sleeper(rq))
2587 goto out;
2588 rebalance_tick(cpu, rq, SCHED_IDLE);
2589 return;
2590 }
2591
2592 /* Task might have expired already, but not scheduled off yet */
2593 if (p->array != rq->active) {
2594 set_tsk_need_resched(p);
2595 goto out;
2596 }
2597 spin_lock(&rq->lock);
2598 /*
2599 * The task was running during this tick - update the
2600 * time slice counter. Note: we do not update a thread's
2601 * priority until it either goes to sleep or uses up its
2602 * timeslice. This makes it possible for interactive tasks
2603 * to use up their timeslices at their highest priority levels.
2604 */
2605 if (rt_task(p)) {
2606 /*
2607 * RR tasks need a special form of timeslice management.
2608 * FIFO tasks have no timeslices.
2609 */
2610 if ((p->policy == SCHED_RR) && !--p->time_slice) {
2611 p->time_slice = task_timeslice(p);
2612 p->first_time_slice = 0;
2613 set_tsk_need_resched(p);
2614
2615 /* put it at the end of the queue: */
2616 requeue_task(p, rq->active);
2617 }
2618 goto out_unlock;
2619 }
2620 if (!--p->time_slice) {
2621 dequeue_task(p, rq->active);
2622 set_tsk_need_resched(p);
2623 p->prio = effective_prio(p);
2624 p->time_slice = task_timeslice(p);
2625 p->first_time_slice = 0;
2626
2627 if (!rq->expired_timestamp)
2628 rq->expired_timestamp = jiffies;
2629 if (!TASK_INTERACTIVE(p) || EXPIRED_STARVING(rq)) {
2630 enqueue_task(p, rq->expired);
2631 if (p->static_prio < rq->best_expired_prio)
2632 rq->best_expired_prio = p->static_prio;
2633 } else
2634 enqueue_task(p, rq->active);
2635 } else {
2636 /*
2637 * Prevent a too long timeslice allowing a task to monopolize
2638 * the CPU. We do this by splitting up the timeslice into
2639 * smaller pieces.
2640 *
2641 * Note: this does not mean the task's timeslices expire or
2642 * get lost in any way, they just might be preempted by
2643 * another task of equal priority. (one with higher
2644 * priority would have preempted this task already.) We
2645 * requeue this task to the end of the list on this priority
2646 * level, which is in essence a round-robin of tasks with
2647 * equal priority.
2648 *
2649 * This only applies to tasks in the interactive
2650 * delta range with at least TIMESLICE_GRANULARITY to requeue.
2651 */
2652 if (TASK_INTERACTIVE(p) && !((task_timeslice(p) -
2653 p->time_slice) % TIMESLICE_GRANULARITY(p)) &&
2654 (p->time_slice >= TIMESLICE_GRANULARITY(p)) &&
2655 (p->array == rq->active)) {
2656
2657 requeue_task(p, rq->active);
2658 set_tsk_need_resched(p);
2659 }
2660 }
2661out_unlock:
2662 spin_unlock(&rq->lock);
2663out:
2664 rebalance_tick(cpu, rq, NOT_IDLE);
2665}
2666
2667#ifdef CONFIG_SCHED_SMT
fc38ed75
CK
2668static inline void wakeup_busy_runqueue(runqueue_t *rq)
2669{
2670 /* If an SMT runqueue is sleeping due to priority reasons wake it up */
2671 if (rq->curr == rq->idle && rq->nr_running)
2672 resched_task(rq->idle);
2673}
2674
858119e1 2675static void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
1da177e4 2676{
41c7ce9a 2677 struct sched_domain *tmp, *sd = NULL;
1da177e4
LT
2678 cpumask_t sibling_map;
2679 int i;
2680
41c7ce9a
NP
2681 for_each_domain(this_cpu, tmp)
2682 if (tmp->flags & SD_SHARE_CPUPOWER)
2683 sd = tmp;
2684
2685 if (!sd)
1da177e4
LT
2686 return;
2687
2688 /*
2689 * Unlock the current runqueue because we have to lock in
2690 * CPU order to avoid deadlocks. Caller knows that we might
2691 * unlock. We keep IRQs disabled.
2692 */
2693 spin_unlock(&this_rq->lock);
2694
2695 sibling_map = sd->span;
2696
2697 for_each_cpu_mask(i, sibling_map)
2698 spin_lock(&cpu_rq(i)->lock);
2699 /*
2700 * We clear this CPU from the mask. This both simplifies the
2701 * inner loop and keps this_rq locked when we exit:
2702 */
2703 cpu_clear(this_cpu, sibling_map);
2704
2705 for_each_cpu_mask(i, sibling_map) {
2706 runqueue_t *smt_rq = cpu_rq(i);
2707
fc38ed75 2708 wakeup_busy_runqueue(smt_rq);
1da177e4
LT
2709 }
2710
2711 for_each_cpu_mask(i, sibling_map)
2712 spin_unlock(&cpu_rq(i)->lock);
2713 /*
2714 * We exit with this_cpu's rq still held and IRQs
2715 * still disabled:
2716 */
2717}
2718
67f9a619
IM
2719/*
2720 * number of 'lost' timeslices this task wont be able to fully
2721 * utilize, if another task runs on a sibling. This models the
2722 * slowdown effect of other tasks running on siblings:
2723 */
2724static inline unsigned long smt_slice(task_t *p, struct sched_domain *sd)
2725{
2726 return p->time_slice * (100 - sd->per_cpu_gain) / 100;
2727}
2728
858119e1 2729static int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
1da177e4 2730{
41c7ce9a 2731 struct sched_domain *tmp, *sd = NULL;
1da177e4
LT
2732 cpumask_t sibling_map;
2733 prio_array_t *array;
2734 int ret = 0, i;
2735 task_t *p;
2736
41c7ce9a
NP
2737 for_each_domain(this_cpu, tmp)
2738 if (tmp->flags & SD_SHARE_CPUPOWER)
2739 sd = tmp;
2740
2741 if (!sd)
1da177e4
LT
2742 return 0;
2743
2744 /*
2745 * The same locking rules and details apply as for
2746 * wake_sleeping_dependent():
2747 */
2748 spin_unlock(&this_rq->lock);
2749 sibling_map = sd->span;
2750 for_each_cpu_mask(i, sibling_map)
2751 spin_lock(&cpu_rq(i)->lock);
2752 cpu_clear(this_cpu, sibling_map);
2753
2754 /*
2755 * Establish next task to be run - it might have gone away because
2756 * we released the runqueue lock above:
2757 */
2758 if (!this_rq->nr_running)
2759 goto out_unlock;
2760 array = this_rq->active;
2761 if (!array->nr_active)
2762 array = this_rq->expired;
2763 BUG_ON(!array->nr_active);
2764
2765 p = list_entry(array->queue[sched_find_first_bit(array->bitmap)].next,
2766 task_t, run_list);
2767
2768 for_each_cpu_mask(i, sibling_map) {
2769 runqueue_t *smt_rq = cpu_rq(i);
2770 task_t *smt_curr = smt_rq->curr;
2771
fc38ed75
CK
2772 /* Kernel threads do not participate in dependent sleeping */
2773 if (!p->mm || !smt_curr->mm || rt_task(p))
2774 goto check_smt_task;
2775
1da177e4
LT
2776 /*
2777 * If a user task with lower static priority than the
2778 * running task on the SMT sibling is trying to schedule,
2779 * delay it till there is proportionately less timeslice
2780 * left of the sibling task to prevent a lower priority
2781 * task from using an unfair proportion of the
2782 * physical cpu's resources. -ck
2783 */
fc38ed75
CK
2784 if (rt_task(smt_curr)) {
2785 /*
2786 * With real time tasks we run non-rt tasks only
2787 * per_cpu_gain% of the time.
2788 */
2789 if ((jiffies % DEF_TIMESLICE) >
2790 (sd->per_cpu_gain * DEF_TIMESLICE / 100))
2791 ret = 1;
2792 } else
67f9a619
IM
2793 if (smt_curr->static_prio < p->static_prio &&
2794 !TASK_PREEMPTS_CURR(p, smt_rq) &&
2795 smt_slice(smt_curr, sd) > task_timeslice(p))
fc38ed75
CK
2796 ret = 1;
2797
2798check_smt_task:
2799 if ((!smt_curr->mm && smt_curr != smt_rq->idle) ||
2800 rt_task(smt_curr))
2801 continue;
2802 if (!p->mm) {
2803 wakeup_busy_runqueue(smt_rq);
2804 continue;
2805 }
1da177e4
LT
2806
2807 /*
fc38ed75
CK
2808 * Reschedule a lower priority task on the SMT sibling for
2809 * it to be put to sleep, or wake it up if it has been put to
2810 * sleep for priority reasons to see if it should run now.
1da177e4 2811 */
fc38ed75
CK
2812 if (rt_task(p)) {
2813 if ((jiffies % DEF_TIMESLICE) >
2814 (sd->per_cpu_gain * DEF_TIMESLICE / 100))
2815 resched_task(smt_curr);
2816 } else {
67f9a619
IM
2817 if (TASK_PREEMPTS_CURR(p, smt_rq) &&
2818 smt_slice(p, sd) > task_timeslice(smt_curr))
fc38ed75
CK
2819 resched_task(smt_curr);
2820 else
2821 wakeup_busy_runqueue(smt_rq);
2822 }
1da177e4
LT
2823 }
2824out_unlock:
2825 for_each_cpu_mask(i, sibling_map)
2826 spin_unlock(&cpu_rq(i)->lock);
2827 return ret;
2828}
2829#else
2830static inline void wake_sleeping_dependent(int this_cpu, runqueue_t *this_rq)
2831{
2832}
2833
2834static inline int dependent_sleeper(int this_cpu, runqueue_t *this_rq)
2835{
2836 return 0;
2837}
2838#endif
2839
2840#if defined(CONFIG_PREEMPT) && defined(CONFIG_DEBUG_PREEMPT)
2841
2842void fastcall add_preempt_count(int val)
2843{
2844 /*
2845 * Underflow?
2846 */
be5b4fbd 2847 BUG_ON((preempt_count() < 0));
1da177e4
LT
2848 preempt_count() += val;
2849 /*
2850 * Spinlock count overflowing soon?
2851 */
2852 BUG_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK-10);
2853}
2854EXPORT_SYMBOL(add_preempt_count);
2855
2856void fastcall sub_preempt_count(int val)
2857{
2858 /*
2859 * Underflow?
2860 */
2861 BUG_ON(val > preempt_count());
2862 /*
2863 * Is the spinlock portion underflowing?
2864 */
2865 BUG_ON((val < PREEMPT_MASK) && !(preempt_count() & PREEMPT_MASK));
2866 preempt_count() -= val;
2867}
2868EXPORT_SYMBOL(sub_preempt_count);
2869
2870#endif
2871
2872/*
2873 * schedule() is the main scheduler function.
2874 */
2875asmlinkage void __sched schedule(void)
2876{
2877 long *switch_count;
2878 task_t *prev, *next;
2879 runqueue_t *rq;
2880 prio_array_t *array;
2881 struct list_head *queue;
2882 unsigned long long now;
2883 unsigned long run_time;
a3464a10 2884 int cpu, idx, new_prio;
1da177e4
LT
2885
2886 /*
2887 * Test if we are atomic. Since do_exit() needs to call into
2888 * schedule() atomically, we ignore that path for now.
2889 * Otherwise, whine if we are scheduling when we should not be.
2890 */
2891 if (likely(!current->exit_state)) {
2892 if (unlikely(in_atomic())) {
2893 printk(KERN_ERR "scheduling while atomic: "
2894 "%s/0x%08x/%d\n",
2895 current->comm, preempt_count(), current->pid);
2896 dump_stack();
2897 }
2898 }
2899 profile_hit(SCHED_PROFILING, __builtin_return_address(0));
2900
2901need_resched:
2902 preempt_disable();
2903 prev = current;
2904 release_kernel_lock(prev);
2905need_resched_nonpreemptible:
2906 rq = this_rq();
2907
2908 /*
2909 * The idle thread is not allowed to schedule!
2910 * Remove this check after it has been exercised a bit.
2911 */
2912 if (unlikely(prev == rq->idle) && prev->state != TASK_RUNNING) {
2913 printk(KERN_ERR "bad: scheduling from the idle thread!\n");
2914 dump_stack();
2915 }
2916
2917 schedstat_inc(rq, sched_cnt);
2918 now = sched_clock();
238628ed 2919 if (likely((long long)(now - prev->timestamp) < NS_MAX_SLEEP_AVG)) {
1da177e4 2920 run_time = now - prev->timestamp;
238628ed 2921 if (unlikely((long long)(now - prev->timestamp) < 0))
1da177e4
LT
2922 run_time = 0;
2923 } else
2924 run_time = NS_MAX_SLEEP_AVG;
2925
2926 /*
2927 * Tasks charged proportionately less run_time at high sleep_avg to
2928 * delay them losing their interactive status
2929 */
2930 run_time /= (CURRENT_BONUS(prev) ? : 1);
2931
2932 spin_lock_irq(&rq->lock);
2933
2934 if (unlikely(prev->flags & PF_DEAD))
2935 prev->state = EXIT_DEAD;
2936
2937 switch_count = &prev->nivcsw;
2938 if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) {
2939 switch_count = &prev->nvcsw;
2940 if (unlikely((prev->state & TASK_INTERRUPTIBLE) &&
2941 unlikely(signal_pending(prev))))
2942 prev->state = TASK_RUNNING;
2943 else {
2944 if (prev->state == TASK_UNINTERRUPTIBLE)
2945 rq->nr_uninterruptible++;
2946 deactivate_task(prev, rq);
2947 }
2948 }
2949
2950 cpu = smp_processor_id();
2951 if (unlikely(!rq->nr_running)) {
2952go_idle:
2953 idle_balance(cpu, rq);
2954 if (!rq->nr_running) {
2955 next = rq->idle;
2956 rq->expired_timestamp = 0;
2957 wake_sleeping_dependent(cpu, rq);
2958 /*
2959 * wake_sleeping_dependent() might have released
2960 * the runqueue, so break out if we got new
2961 * tasks meanwhile:
2962 */
2963 if (!rq->nr_running)
2964 goto switch_tasks;
2965 }
2966 } else {
2967 if (dependent_sleeper(cpu, rq)) {
2968 next = rq->idle;
2969 goto switch_tasks;
2970 }
2971 /*
2972 * dependent_sleeper() releases and reacquires the runqueue
2973 * lock, hence go into the idle loop if the rq went
2974 * empty meanwhile:
2975 */
2976 if (unlikely(!rq->nr_running))
2977 goto go_idle;
2978 }
2979
2980 array = rq->active;
2981 if (unlikely(!array->nr_active)) {
2982 /*
2983 * Switch the active and expired arrays.
2984 */
2985 schedstat_inc(rq, sched_switch);
2986 rq->active = rq->expired;
2987 rq->expired = array;
2988 array = rq->active;
2989 rq->expired_timestamp = 0;
2990 rq->best_expired_prio = MAX_PRIO;
2991 }
2992
2993 idx = sched_find_first_bit(array->bitmap);
2994 queue = array->queue + idx;
2995 next = list_entry(queue->next, task_t, run_list);
2996
2997 if (!rt_task(next) && next->activated > 0) {
2998 unsigned long long delta = now - next->timestamp;
238628ed 2999 if (unlikely((long long)(now - next->timestamp) < 0))
1da177e4
LT
3000 delta = 0;
3001
3002 if (next->activated == 1)
3003 delta = delta * (ON_RUNQUEUE_WEIGHT * 128 / 100) / 128;
3004
3005 array = next->array;
a3464a10
CS
3006 new_prio = recalc_task_prio(next, next->timestamp + delta);
3007
3008 if (unlikely(next->prio != new_prio)) {
3009 dequeue_task(next, array);
3010 next->prio = new_prio;
3011 enqueue_task(next, array);
3012 } else
3013 requeue_task(next, array);
1da177e4
LT
3014 }
3015 next->activated = 0;
3016switch_tasks:
3017 if (next == rq->idle)
3018 schedstat_inc(rq, sched_goidle);
3019 prefetch(next);
383f2835 3020 prefetch_stack(next);
1da177e4
LT
3021 clear_tsk_need_resched(prev);
3022 rcu_qsctr_inc(task_cpu(prev));
3023
3024 update_cpu_clock(prev, rq, now);
3025
3026 prev->sleep_avg -= run_time;
3027 if ((long)prev->sleep_avg <= 0)
3028 prev->sleep_avg = 0;
3029 prev->timestamp = prev->last_ran = now;
3030
3031 sched_info_switch(prev, next);
3032 if (likely(prev != next)) {
3033 next->timestamp = now;
3034 rq->nr_switches++;
3035 rq->curr = next;
3036 ++*switch_count;
3037
4866cde0 3038 prepare_task_switch(rq, next);
1da177e4
LT
3039 prev = context_switch(rq, prev, next);
3040 barrier();
4866cde0
NP
3041 /*
3042 * this_rq must be evaluated again because prev may have moved
3043 * CPUs since it called schedule(), thus the 'rq' on its stack
3044 * frame will be invalid.
3045 */
3046 finish_task_switch(this_rq(), prev);
1da177e4
LT
3047 } else
3048 spin_unlock_irq(&rq->lock);
3049
3050 prev = current;
3051 if (unlikely(reacquire_kernel_lock(prev) < 0))
3052 goto need_resched_nonpreemptible;
3053 preempt_enable_no_resched();
3054 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3055 goto need_resched;
3056}
3057
3058EXPORT_SYMBOL(schedule);
3059
3060#ifdef CONFIG_PREEMPT
3061/*
3062 * this is is the entry point to schedule() from in-kernel preemption
3063 * off of preempt_enable. Kernel preemptions off return from interrupt
3064 * occur there and call schedule directly.
3065 */
3066asmlinkage void __sched preempt_schedule(void)
3067{
3068 struct thread_info *ti = current_thread_info();
3069#ifdef CONFIG_PREEMPT_BKL
3070 struct task_struct *task = current;
3071 int saved_lock_depth;
3072#endif
3073 /*
3074 * If there is a non-zero preempt_count or interrupts are disabled,
3075 * we do not want to preempt the current task. Just return..
3076 */
3077 if (unlikely(ti->preempt_count || irqs_disabled()))
3078 return;
3079
3080need_resched:
3081 add_preempt_count(PREEMPT_ACTIVE);
3082 /*
3083 * We keep the big kernel semaphore locked, but we
3084 * clear ->lock_depth so that schedule() doesnt
3085 * auto-release the semaphore:
3086 */
3087#ifdef CONFIG_PREEMPT_BKL
3088 saved_lock_depth = task->lock_depth;
3089 task->lock_depth = -1;
3090#endif
3091 schedule();
3092#ifdef CONFIG_PREEMPT_BKL
3093 task->lock_depth = saved_lock_depth;
3094#endif
3095 sub_preempt_count(PREEMPT_ACTIVE);
3096
3097 /* we could miss a preemption opportunity between schedule and now */
3098 barrier();
3099 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3100 goto need_resched;
3101}
3102
3103EXPORT_SYMBOL(preempt_schedule);
3104
3105/*
3106 * this is is the entry point to schedule() from kernel preemption
3107 * off of irq context.
3108 * Note, that this is called and return with irqs disabled. This will
3109 * protect us against recursive calling from irq.
3110 */
3111asmlinkage void __sched preempt_schedule_irq(void)
3112{
3113 struct thread_info *ti = current_thread_info();
3114#ifdef CONFIG_PREEMPT_BKL
3115 struct task_struct *task = current;
3116 int saved_lock_depth;
3117#endif
3118 /* Catch callers which need to be fixed*/
3119 BUG_ON(ti->preempt_count || !irqs_disabled());
3120
3121need_resched:
3122 add_preempt_count(PREEMPT_ACTIVE);
3123 /*
3124 * We keep the big kernel semaphore locked, but we
3125 * clear ->lock_depth so that schedule() doesnt
3126 * auto-release the semaphore:
3127 */
3128#ifdef CONFIG_PREEMPT_BKL
3129 saved_lock_depth = task->lock_depth;
3130 task->lock_depth = -1;
3131#endif
3132 local_irq_enable();
3133 schedule();
3134 local_irq_disable();
3135#ifdef CONFIG_PREEMPT_BKL
3136 task->lock_depth = saved_lock_depth;
3137#endif
3138 sub_preempt_count(PREEMPT_ACTIVE);
3139
3140 /* we could miss a preemption opportunity between schedule and now */
3141 barrier();
3142 if (unlikely(test_thread_flag(TIF_NEED_RESCHED)))
3143 goto need_resched;
3144}
3145
3146#endif /* CONFIG_PREEMPT */
3147
95cdf3b7
IM
3148int default_wake_function(wait_queue_t *curr, unsigned mode, int sync,
3149 void *key)
1da177e4 3150{
c43dc2fd 3151 task_t *p = curr->private;
1da177e4
LT
3152 return try_to_wake_up(p, mode, sync);
3153}
3154
3155EXPORT_SYMBOL(default_wake_function);
3156
3157/*
3158 * The core wakeup function. Non-exclusive wakeups (nr_exclusive == 0) just
3159 * wake everything up. If it's an exclusive wakeup (nr_exclusive == small +ve
3160 * number) then we wake all the non-exclusive tasks and one exclusive task.
3161 *
3162 * There are circumstances in which we can try to wake a task which has already
3163 * started to run but is not in state TASK_RUNNING. try_to_wake_up() returns
3164 * zero in this (rare) case, and we handle it by continuing to scan the queue.
3165 */
3166static void __wake_up_common(wait_queue_head_t *q, unsigned int mode,
3167 int nr_exclusive, int sync, void *key)
3168{
3169 struct list_head *tmp, *next;
3170
3171 list_for_each_safe(tmp, next, &q->task_list) {
3172 wait_queue_t *curr;
3173 unsigned flags;
3174 curr = list_entry(tmp, wait_queue_t, task_list);
3175 flags = curr->flags;
3176 if (curr->func(curr, mode, sync, key) &&
3177 (flags & WQ_FLAG_EXCLUSIVE) &&
3178 !--nr_exclusive)
3179 break;
3180 }
3181}
3182
3183/**
3184 * __wake_up - wake up threads blocked on a waitqueue.
3185 * @q: the waitqueue
3186 * @mode: which threads
3187 * @nr_exclusive: how many wake-one or wake-many threads to wake up
67be2dd1 3188 * @key: is directly passed to the wakeup function
1da177e4
LT
3189 */
3190void fastcall __wake_up(wait_queue_head_t *q, unsigned int mode,
95cdf3b7 3191 int nr_exclusive, void *key)
1da177e4
LT
3192{
3193 unsigned long flags;
3194
3195 spin_lock_irqsave(&q->lock, flags);
3196 __wake_up_common(q, mode, nr_exclusive, 0, key);
3197 spin_unlock_irqrestore(&q->lock, flags);
3198}
3199
3200EXPORT_SYMBOL(__wake_up);
3201
3202/*
3203 * Same as __wake_up but called with the spinlock in wait_queue_head_t held.
3204 */
3205void fastcall __wake_up_locked(wait_queue_head_t *q, unsigned int mode)
3206{
3207 __wake_up_common(q, mode, 1, 0, NULL);
3208}
3209
3210/**
67be2dd1 3211 * __wake_up_sync - wake up threads blocked on a waitqueue.
1da177e4
LT
3212 * @q: the waitqueue
3213 * @mode: which threads
3214 * @nr_exclusive: how many wake-one or wake-many threads to wake up
3215 *
3216 * The sync wakeup differs that the waker knows that it will schedule
3217 * away soon, so while the target thread will be woken up, it will not
3218 * be migrated to another CPU - ie. the two threads are 'synchronized'
3219 * with each other. This can prevent needless bouncing between CPUs.
3220 *
3221 * On UP it can prevent extra preemption.
3222 */
95cdf3b7
IM
3223void fastcall
3224__wake_up_sync(wait_queue_head_t *q, unsigned int mode, int nr_exclusive)
1da177e4
LT
3225{
3226 unsigned long flags;
3227 int sync = 1;
3228
3229 if (unlikely(!q))
3230 return;
3231
3232 if (unlikely(!nr_exclusive))
3233 sync = 0;
3234
3235 spin_lock_irqsave(&q->lock, flags);
3236 __wake_up_common(q, mode, nr_exclusive, sync, NULL);
3237 spin_unlock_irqrestore(&q->lock, flags);
3238}
3239EXPORT_SYMBOL_GPL(__wake_up_sync); /* For internal use only */
3240
3241void fastcall complete(struct completion *x)
3242{
3243 unsigned long flags;
3244
3245 spin_lock_irqsave(&x->wait.lock, flags);
3246 x->done++;
3247 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3248 1, 0, NULL);
3249 spin_unlock_irqrestore(&x->wait.lock, flags);
3250}
3251EXPORT_SYMBOL(complete);
3252
3253void fastcall complete_all(struct completion *x)
3254{
3255 unsigned long flags;
3256
3257 spin_lock_irqsave(&x->wait.lock, flags);
3258 x->done += UINT_MAX/2;
3259 __wake_up_common(&x->wait, TASK_UNINTERRUPTIBLE | TASK_INTERRUPTIBLE,
3260 0, 0, NULL);
3261 spin_unlock_irqrestore(&x->wait.lock, flags);
3262}
3263EXPORT_SYMBOL(complete_all);
3264
3265void fastcall __sched wait_for_completion(struct completion *x)
3266{
3267 might_sleep();
3268 spin_lock_irq(&x->wait.lock);
3269 if (!x->done) {
3270 DECLARE_WAITQUEUE(wait, current);
3271
3272 wait.flags |= WQ_FLAG_EXCLUSIVE;
3273 __add_wait_queue_tail(&x->wait, &wait);
3274 do {
3275 __set_current_state(TASK_UNINTERRUPTIBLE);
3276 spin_unlock_irq(&x->wait.lock);
3277 schedule();
3278 spin_lock_irq(&x->wait.lock);
3279 } while (!x->done);
3280 __remove_wait_queue(&x->wait, &wait);
3281 }
3282 x->done--;
3283 spin_unlock_irq(&x->wait.lock);
3284}
3285EXPORT_SYMBOL(wait_for_completion);
3286
3287unsigned long fastcall __sched
3288wait_for_completion_timeout(struct completion *x, unsigned long timeout)
3289{
3290 might_sleep();
3291
3292 spin_lock_irq(&x->wait.lock);
3293 if (!x->done) {
3294 DECLARE_WAITQUEUE(wait, current);
3295
3296 wait.flags |= WQ_FLAG_EXCLUSIVE;
3297 __add_wait_queue_tail(&x->wait, &wait);
3298 do {
3299 __set_current_state(TASK_UNINTERRUPTIBLE);
3300 spin_unlock_irq(&x->wait.lock);
3301 timeout = schedule_timeout(timeout);
3302 spin_lock_irq(&x->wait.lock);
3303 if (!timeout) {
3304 __remove_wait_queue(&x->wait, &wait);
3305 goto out;
3306 }
3307 } while (!x->done);
3308 __remove_wait_queue(&x->wait, &wait);
3309 }
3310 x->done--;
3311out:
3312 spin_unlock_irq(&x->wait.lock);
3313 return timeout;
3314}
3315EXPORT_SYMBOL(wait_for_completion_timeout);
3316
3317int fastcall __sched wait_for_completion_interruptible(struct completion *x)
3318{
3319 int ret = 0;
3320
3321 might_sleep();
3322
3323 spin_lock_irq(&x->wait.lock);
3324 if (!x->done) {
3325 DECLARE_WAITQUEUE(wait, current);
3326
3327 wait.flags |= WQ_FLAG_EXCLUSIVE;
3328 __add_wait_queue_tail(&x->wait, &wait);
3329 do {
3330 if (signal_pending(current)) {
3331 ret = -ERESTARTSYS;
3332 __remove_wait_queue(&x->wait, &wait);
3333 goto out;
3334 }
3335 __set_current_state(TASK_INTERRUPTIBLE);
3336 spin_unlock_irq(&x->wait.lock);
3337 schedule();
3338 spin_lock_irq(&x->wait.lock);
3339 } while (!x->done);
3340 __remove_wait_queue(&x->wait, &wait);
3341 }
3342 x->done--;
3343out:
3344 spin_unlock_irq(&x->wait.lock);
3345
3346 return ret;
3347}
3348EXPORT_SYMBOL(wait_for_completion_interruptible);
3349
3350unsigned long fastcall __sched
3351wait_for_completion_interruptible_timeout(struct completion *x,
3352 unsigned long timeout)
3353{
3354 might_sleep();
3355
3356 spin_lock_irq(&x->wait.lock);
3357 if (!x->done) {
3358 DECLARE_WAITQUEUE(wait, current);
3359
3360 wait.flags |= WQ_FLAG_EXCLUSIVE;
3361 __add_wait_queue_tail(&x->wait, &wait);
3362 do {
3363 if (signal_pending(current)) {
3364 timeout = -ERESTARTSYS;
3365 __remove_wait_queue(&x->wait, &wait);
3366 goto out;
3367 }
3368 __set_current_state(TASK_INTERRUPTIBLE);
3369 spin_unlock_irq(&x->wait.lock);
3370 timeout = schedule_timeout(timeout);
3371 spin_lock_irq(&x->wait.lock);
3372 if (!timeout) {
3373 __remove_wait_queue(&x->wait, &wait);
3374 goto out;
3375 }
3376 } while (!x->done);
3377 __remove_wait_queue(&x->wait, &wait);
3378 }
3379 x->done--;
3380out:
3381 spin_unlock_irq(&x->wait.lock);
3382 return timeout;
3383}
3384EXPORT_SYMBOL(wait_for_completion_interruptible_timeout);
3385
3386
3387#define SLEEP_ON_VAR \
3388 unsigned long flags; \
3389 wait_queue_t wait; \
3390 init_waitqueue_entry(&wait, current);
3391
3392#define SLEEP_ON_HEAD \
3393 spin_lock_irqsave(&q->lock,flags); \
3394 __add_wait_queue(q, &wait); \
3395 spin_unlock(&q->lock);
3396
3397#define SLEEP_ON_TAIL \
3398 spin_lock_irq(&q->lock); \
3399 __remove_wait_queue(q, &wait); \
3400 spin_unlock_irqrestore(&q->lock, flags);
3401
3402void fastcall __sched interruptible_sleep_on(wait_queue_head_t *q)
3403{
3404 SLEEP_ON_VAR
3405
3406 current->state = TASK_INTERRUPTIBLE;
3407
3408 SLEEP_ON_HEAD
3409 schedule();
3410 SLEEP_ON_TAIL
3411}
3412
3413EXPORT_SYMBOL(interruptible_sleep_on);
3414
95cdf3b7
IM
3415long fastcall __sched
3416interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout)
1da177e4
LT
3417{
3418 SLEEP_ON_VAR
3419
3420 current->state = TASK_INTERRUPTIBLE;
3421
3422 SLEEP_ON_HEAD
3423 timeout = schedule_timeout(timeout);
3424 SLEEP_ON_TAIL
3425
3426 return timeout;
3427}
3428
3429EXPORT_SYMBOL(interruptible_sleep_on_timeout);
3430
3431void fastcall __sched sleep_on(wait_queue_head_t *q)
3432{
3433 SLEEP_ON_VAR
3434
3435 current->state = TASK_UNINTERRUPTIBLE;
3436
3437 SLEEP_ON_HEAD
3438 schedule();
3439 SLEEP_ON_TAIL
3440}
3441
3442EXPORT_SYMBOL(sleep_on);
3443
3444long fastcall __sched sleep_on_timeout(wait_queue_head_t *q, long timeout)
3445{
3446 SLEEP_ON_VAR
3447
3448 current->state = TASK_UNINTERRUPTIBLE;
3449
3450 SLEEP_ON_HEAD
3451 timeout = schedule_timeout(timeout);
3452 SLEEP_ON_TAIL
3453
3454 return timeout;
3455}
3456
3457EXPORT_SYMBOL(sleep_on_timeout);
3458
3459void set_user_nice(task_t *p, long nice)
3460{
3461 unsigned long flags;
3462 prio_array_t *array;
3463 runqueue_t *rq;
3464 int old_prio, new_prio, delta;
3465
3466 if (TASK_NICE(p) == nice || nice < -20 || nice > 19)
3467 return;
3468 /*
3469 * We have to be careful, if called from sys_setpriority(),
3470 * the task might be in the middle of scheduling on another CPU.
3471 */
3472 rq = task_rq_lock(p, &flags);
3473 /*
3474 * The RT priorities are set via sched_setscheduler(), but we still
3475 * allow the 'normal' nice value to be set - but as expected
3476 * it wont have any effect on scheduling until the task is
b0a9499c 3477 * not SCHED_NORMAL/SCHED_BATCH:
1da177e4
LT
3478 */
3479 if (rt_task(p)) {
3480 p->static_prio = NICE_TO_PRIO(nice);
3481 goto out_unlock;
3482 }
3483 array = p->array;
a2000572 3484 if (array)
1da177e4
LT
3485 dequeue_task(p, array);
3486
3487 old_prio = p->prio;
3488 new_prio = NICE_TO_PRIO(nice);
3489 delta = new_prio - old_prio;
3490 p->static_prio = NICE_TO_PRIO(nice);
3491 p->prio += delta;
3492
3493 if (array) {
3494 enqueue_task(p, array);
3495 /*
3496 * If the task increased its priority or is running and
3497 * lowered its priority, then reschedule its CPU:
3498 */
3499 if (delta < 0 || (delta > 0 && task_running(rq, p)))
3500 resched_task(rq->curr);
3501 }
3502out_unlock:
3503 task_rq_unlock(rq, &flags);
3504}
3505
3506EXPORT_SYMBOL(set_user_nice);
3507
e43379f1
MM
3508/*
3509 * can_nice - check if a task can reduce its nice value
3510 * @p: task
3511 * @nice: nice value
3512 */
3513int can_nice(const task_t *p, const int nice)
3514{
024f4747
MM
3515 /* convert nice value [19,-20] to rlimit style value [1,40] */
3516 int nice_rlim = 20 - nice;
e43379f1
MM
3517 return (nice_rlim <= p->signal->rlim[RLIMIT_NICE].rlim_cur ||
3518 capable(CAP_SYS_NICE));
3519}
3520
1da177e4
LT
3521#ifdef __ARCH_WANT_SYS_NICE
3522
3523/*
3524 * sys_nice - change the priority of the current process.
3525 * @increment: priority increment
3526 *
3527 * sys_setpriority is a more generic, but much slower function that
3528 * does similar things.
3529 */
3530asmlinkage long sys_nice(int increment)
3531{
3532 int retval;
3533 long nice;
3534
3535 /*
3536 * Setpriority might change our priority at the same moment.
3537 * We don't have to worry. Conceptually one call occurs first
3538 * and we have a single winner.
3539 */
e43379f1
MM
3540 if (increment < -40)
3541 increment = -40;
1da177e4
LT
3542 if (increment > 40)
3543 increment = 40;
3544
3545 nice = PRIO_TO_NICE(current->static_prio) + increment;
3546 if (nice < -20)
3547 nice = -20;
3548 if (nice > 19)
3549 nice = 19;
3550
e43379f1
MM
3551 if (increment < 0 && !can_nice(current, nice))
3552 return -EPERM;
3553
1da177e4
LT
3554 retval = security_task_setnice(current, nice);
3555 if (retval)
3556 return retval;
3557
3558 set_user_nice(current, nice);
3559 return 0;
3560}
3561
3562#endif
3563
3564/**
3565 * task_prio - return the priority value of a given task.
3566 * @p: the task in question.
3567 *
3568 * This is the priority value as seen by users in /proc.
3569 * RT tasks are offset by -200. Normal tasks are centered
3570 * around 0, value goes from -16 to +15.
3571 */
3572int task_prio(const task_t *p)
3573{
3574 return p->prio - MAX_RT_PRIO;
3575}
3576
3577/**
3578 * task_nice - return the nice value of a given task.
3579 * @p: the task in question.
3580 */
3581int task_nice(const task_t *p)
3582{
3583 return TASK_NICE(p);
3584}
1da177e4 3585EXPORT_SYMBOL_GPL(task_nice);
1da177e4
LT
3586
3587/**
3588 * idle_cpu - is a given cpu idle currently?
3589 * @cpu: the processor in question.
3590 */
3591int idle_cpu(int cpu)
3592{
3593 return cpu_curr(cpu) == cpu_rq(cpu)->idle;
3594}
3595
1da177e4
LT
3596/**
3597 * idle_task - return the idle task for a given cpu.
3598 * @cpu: the processor in question.
3599 */
3600task_t *idle_task(int cpu)
3601{
3602 return cpu_rq(cpu)->idle;
3603}
3604
3605/**
3606 * find_process_by_pid - find a process with a matching PID value.
3607 * @pid: the pid in question.
3608 */
3609static inline task_t *find_process_by_pid(pid_t pid)
3610{
3611 return pid ? find_task_by_pid(pid) : current;
3612}
3613
3614/* Actually do priority change: must hold rq lock. */
3615static void __setscheduler(struct task_struct *p, int policy, int prio)
3616{
3617 BUG_ON(p->array);
3618 p->policy = policy;
3619 p->rt_priority = prio;
b0a9499c 3620 if (policy != SCHED_NORMAL && policy != SCHED_BATCH) {
d46523ea 3621 p->prio = MAX_RT_PRIO-1 - p->rt_priority;
b0a9499c 3622 } else {
1da177e4 3623 p->prio = p->static_prio;
b0a9499c
IM
3624 /*
3625 * SCHED_BATCH tasks are treated as perpetual CPU hogs:
3626 */
3627 if (policy == SCHED_BATCH)
3628 p->sleep_avg = 0;
3629 }
1da177e4
LT
3630}
3631
3632/**
3633 * sched_setscheduler - change the scheduling policy and/or RT priority of
3634 * a thread.
3635 * @p: the task in question.
3636 * @policy: new policy.
3637 * @param: structure containing the new RT priority.
3638 */
95cdf3b7
IM
3639int sched_setscheduler(struct task_struct *p, int policy,
3640 struct sched_param *param)
1da177e4
LT
3641{
3642 int retval;
3643 int oldprio, oldpolicy = -1;
3644 prio_array_t *array;
3645 unsigned long flags;
3646 runqueue_t *rq;
3647
3648recheck:
3649 /* double check policy once rq lock held */
3650 if (policy < 0)
3651 policy = oldpolicy = p->policy;
3652 else if (policy != SCHED_FIFO && policy != SCHED_RR &&
b0a9499c
IM
3653 policy != SCHED_NORMAL && policy != SCHED_BATCH)
3654 return -EINVAL;
1da177e4
LT
3655 /*
3656 * Valid priorities for SCHED_FIFO and SCHED_RR are
b0a9499c
IM
3657 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL and
3658 * SCHED_BATCH is 0.
1da177e4
LT
3659 */
3660 if (param->sched_priority < 0 ||
95cdf3b7 3661 (p->mm && param->sched_priority > MAX_USER_RT_PRIO-1) ||
d46523ea 3662 (!p->mm && param->sched_priority > MAX_RT_PRIO-1))
1da177e4 3663 return -EINVAL;
b0a9499c
IM
3664 if ((policy == SCHED_NORMAL || policy == SCHED_BATCH)
3665 != (param->sched_priority == 0))
1da177e4
LT
3666 return -EINVAL;
3667
37e4ab3f
OC
3668 /*
3669 * Allow unprivileged RT tasks to decrease priority:
3670 */
3671 if (!capable(CAP_SYS_NICE)) {
b0a9499c
IM
3672 /*
3673 * can't change policy, except between SCHED_NORMAL
3674 * and SCHED_BATCH:
3675 */
3676 if (((policy != SCHED_NORMAL && p->policy != SCHED_BATCH) &&
3677 (policy != SCHED_BATCH && p->policy != SCHED_NORMAL)) &&
3678 !p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
37e4ab3f
OC
3679 return -EPERM;
3680 /* can't increase priority */
b0a9499c 3681 if ((policy != SCHED_NORMAL && policy != SCHED_BATCH) &&
37e4ab3f
OC
3682 param->sched_priority > p->rt_priority &&
3683 param->sched_priority >
3684 p->signal->rlim[RLIMIT_RTPRIO].rlim_cur)
3685 return -EPERM;
3686 /* can't change other user's priorities */
3687 if ((current->euid != p->euid) &&
3688 (current->euid != p->uid))
3689 return -EPERM;
3690 }
1da177e4
LT
3691
3692 retval = security_task_setscheduler(p, policy, param);
3693 if (retval)
3694 return retval;
3695 /*
3696 * To be able to change p->policy safely, the apropriate
3697 * runqueue lock must be held.
3698 */
3699 rq = task_rq_lock(p, &flags);
3700 /* recheck policy now with rq lock held */
3701 if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
3702 policy = oldpolicy = -1;
3703 task_rq_unlock(rq, &flags);
3704 goto recheck;
3705 }
3706 array = p->array;
3707 if (array)
3708 deactivate_task(p, rq);
3709 oldprio = p->prio;
3710 __setscheduler(p, policy, param->sched_priority);
3711 if (array) {
3712 __activate_task(p, rq);
3713 /*
3714 * Reschedule if we are currently running on this runqueue and
3715 * our priority decreased, or if we are not currently running on
3716 * this runqueue and our priority is higher than the current's
3717 */
3718 if (task_running(rq, p)) {
3719 if (p->prio > oldprio)
3720 resched_task(rq->curr);
3721 } else if (TASK_PREEMPTS_CURR(p, rq))
3722 resched_task(rq->curr);
3723 }
3724 task_rq_unlock(rq, &flags);
3725 return 0;
3726}
3727EXPORT_SYMBOL_GPL(sched_setscheduler);
3728
95cdf3b7
IM
3729static int
3730do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
1da177e4
LT
3731{
3732 int retval;
3733 struct sched_param lparam;
3734 struct task_struct *p;
3735
3736 if (!param || pid < 0)
3737 return -EINVAL;
3738 if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
3739 return -EFAULT;
3740 read_lock_irq(&tasklist_lock);
3741 p = find_process_by_pid(pid);
3742 if (!p) {
3743 read_unlock_irq(&tasklist_lock);
3744 return -ESRCH;
3745 }
3746 retval = sched_setscheduler(p, policy, &lparam);
3747 read_unlock_irq(&tasklist_lock);
3748 return retval;
3749}
3750
3751/**
3752 * sys_sched_setscheduler - set/change the scheduler policy and RT priority
3753 * @pid: the pid in question.
3754 * @policy: new policy.
3755 * @param: structure containing the new RT priority.
3756 */
3757asmlinkage long sys_sched_setscheduler(pid_t pid, int policy,
3758 struct sched_param __user *param)
3759{
c21761f1
JB
3760 /* negative values for policy are not valid */
3761 if (policy < 0)
3762 return -EINVAL;
3763
1da177e4
LT
3764 return do_sched_setscheduler(pid, policy, param);
3765}
3766
3767/**
3768 * sys_sched_setparam - set/change the RT priority of a thread
3769 * @pid: the pid in question.
3770 * @param: structure containing the new RT priority.
3771 */
3772asmlinkage long sys_sched_setparam(pid_t pid, struct sched_param __user *param)
3773{
3774 return do_sched_setscheduler(pid, -1, param);
3775}
3776
3777/**
3778 * sys_sched_getscheduler - get the policy (scheduling class) of a thread
3779 * @pid: the pid in question.
3780 */
3781asmlinkage long sys_sched_getscheduler(pid_t pid)
3782{
3783 int retval = -EINVAL;
3784 task_t *p;
3785
3786 if (pid < 0)
3787 goto out_nounlock;
3788
3789 retval = -ESRCH;
3790 read_lock(&tasklist_lock);
3791 p = find_process_by_pid(pid);
3792 if (p) {
3793 retval = security_task_getscheduler(p);
3794 if (!retval)
3795 retval = p->policy;
3796 }
3797 read_unlock(&tasklist_lock);
3798
3799out_nounlock:
3800 return retval;
3801}
3802
3803/**
3804 * sys_sched_getscheduler - get the RT priority of a thread
3805 * @pid: the pid in question.
3806 * @param: structure containing the RT priority.
3807 */
3808asmlinkage long sys_sched_getparam(pid_t pid, struct sched_param __user *param)
3809{
3810 struct sched_param lp;
3811 int retval = -EINVAL;
3812 task_t *p;
3813
3814 if (!param || pid < 0)
3815 goto out_nounlock;
3816
3817 read_lock(&tasklist_lock);
3818 p = find_process_by_pid(pid);
3819 retval = -ESRCH;
3820 if (!p)
3821 goto out_unlock;
3822
3823 retval = security_task_getscheduler(p);
3824 if (retval)
3825 goto out_unlock;
3826
3827 lp.sched_priority = p->rt_priority;
3828 read_unlock(&tasklist_lock);
3829
3830 /*
3831 * This one might sleep, we cannot do it with a spinlock held ...
3832 */
3833 retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
3834
3835out_nounlock:
3836 return retval;
3837
3838out_unlock:
3839 read_unlock(&tasklist_lock);
3840 return retval;
3841}
3842
3843long sched_setaffinity(pid_t pid, cpumask_t new_mask)
3844{
3845 task_t *p;
3846 int retval;
3847 cpumask_t cpus_allowed;
3848
3849 lock_cpu_hotplug();
3850 read_lock(&tasklist_lock);
3851
3852 p = find_process_by_pid(pid);
3853 if (!p) {
3854 read_unlock(&tasklist_lock);
3855 unlock_cpu_hotplug();
3856 return -ESRCH;
3857 }
3858
3859 /*
3860 * It is not safe to call set_cpus_allowed with the
3861 * tasklist_lock held. We will bump the task_struct's
3862 * usage count and then drop tasklist_lock.
3863 */
3864 get_task_struct(p);
3865 read_unlock(&tasklist_lock);
3866
3867 retval = -EPERM;
3868 if ((current->euid != p->euid) && (current->euid != p->uid) &&
3869 !capable(CAP_SYS_NICE))
3870 goto out_unlock;
3871
3872 cpus_allowed = cpuset_cpus_allowed(p);
3873 cpus_and(new_mask, new_mask, cpus_allowed);
3874 retval = set_cpus_allowed(p, new_mask);
3875
3876out_unlock:
3877 put_task_struct(p);
3878 unlock_cpu_hotplug();
3879 return retval;
3880}
3881
3882static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
3883 cpumask_t *new_mask)
3884{
3885 if (len < sizeof(cpumask_t)) {
3886 memset(new_mask, 0, sizeof(cpumask_t));
3887 } else if (len > sizeof(cpumask_t)) {
3888 len = sizeof(cpumask_t);
3889 }
3890 return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
3891}
3892
3893/**
3894 * sys_sched_setaffinity - set the cpu affinity of a process
3895 * @pid: pid of the process
3896 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3897 * @user_mask_ptr: user-space pointer to the new cpu mask
3898 */
3899asmlinkage long sys_sched_setaffinity(pid_t pid, unsigned int len,
3900 unsigned long __user *user_mask_ptr)
3901{
3902 cpumask_t new_mask;
3903 int retval;
3904
3905 retval = get_user_cpu_mask(user_mask_ptr, len, &new_mask);
3906 if (retval)
3907 return retval;
3908
3909 return sched_setaffinity(pid, new_mask);
3910}
3911
3912/*
3913 * Represents all cpu's present in the system
3914 * In systems capable of hotplug, this map could dynamically grow
3915 * as new cpu's are detected in the system via any platform specific
3916 * method, such as ACPI for e.g.
3917 */
3918
4cef0c61 3919cpumask_t cpu_present_map __read_mostly;
1da177e4
LT
3920EXPORT_SYMBOL(cpu_present_map);
3921
3922#ifndef CONFIG_SMP
4cef0c61
AK
3923cpumask_t cpu_online_map __read_mostly = CPU_MASK_ALL;
3924cpumask_t cpu_possible_map __read_mostly = CPU_MASK_ALL;
1da177e4
LT
3925#endif
3926
3927long sched_getaffinity(pid_t pid, cpumask_t *mask)
3928{
3929 int retval;
3930 task_t *p;
3931
3932 lock_cpu_hotplug();
3933 read_lock(&tasklist_lock);
3934
3935 retval = -ESRCH;
3936 p = find_process_by_pid(pid);
3937 if (!p)
3938 goto out_unlock;
3939
3940 retval = 0;
2f7016d9 3941 cpus_and(*mask, p->cpus_allowed, cpu_online_map);
1da177e4
LT
3942
3943out_unlock:
3944 read_unlock(&tasklist_lock);
3945 unlock_cpu_hotplug();
3946 if (retval)
3947 return retval;
3948
3949 return 0;
3950}
3951
3952/**
3953 * sys_sched_getaffinity - get the cpu affinity of a process
3954 * @pid: pid of the process
3955 * @len: length in bytes of the bitmask pointed to by user_mask_ptr
3956 * @user_mask_ptr: user-space pointer to hold the current cpu mask
3957 */
3958asmlinkage long sys_sched_getaffinity(pid_t pid, unsigned int len,
3959 unsigned long __user *user_mask_ptr)
3960{
3961 int ret;
3962 cpumask_t mask;
3963
3964 if (len < sizeof(cpumask_t))
3965 return -EINVAL;
3966
3967 ret = sched_getaffinity(pid, &mask);
3968 if (ret < 0)
3969 return ret;
3970
3971 if (copy_to_user(user_mask_ptr, &mask, sizeof(cpumask_t)))
3972 return -EFAULT;
3973
3974 return sizeof(cpumask_t);
3975}
3976
3977/**
3978 * sys_sched_yield - yield the current processor to other threads.
3979 *
3980 * this function yields the current CPU by moving the calling thread
3981 * to the expired array. If there are no other threads running on this
3982 * CPU then this function will return.
3983 */
3984asmlinkage long sys_sched_yield(void)
3985{
3986 runqueue_t *rq = this_rq_lock();
3987 prio_array_t *array = current->array;
3988 prio_array_t *target = rq->expired;
3989
3990 schedstat_inc(rq, yld_cnt);
3991 /*
3992 * We implement yielding by moving the task into the expired
3993 * queue.
3994 *
3995 * (special rule: RT tasks will just roundrobin in the active
3996 * array.)
3997 */
3998 if (rt_task(current))
3999 target = rq->active;
4000
5927ad78 4001 if (array->nr_active == 1) {
1da177e4
LT
4002 schedstat_inc(rq, yld_act_empty);
4003 if (!rq->expired->nr_active)
4004 schedstat_inc(rq, yld_both_empty);
4005 } else if (!rq->expired->nr_active)
4006 schedstat_inc(rq, yld_exp_empty);
4007
4008 if (array != target) {
4009 dequeue_task(current, array);
4010 enqueue_task(current, target);
4011 } else
4012 /*
4013 * requeue_task is cheaper so perform that if possible.
4014 */
4015 requeue_task(current, array);
4016
4017 /*
4018 * Since we are going to call schedule() anyway, there's
4019 * no need to preempt or enable interrupts:
4020 */
4021 __release(rq->lock);
4022 _raw_spin_unlock(&rq->lock);
4023 preempt_enable_no_resched();
4024
4025 schedule();
4026
4027 return 0;
4028}
4029
4030static inline void __cond_resched(void)
4031{
5bbcfd90
IM
4032 /*
4033 * The BKS might be reacquired before we have dropped
4034 * PREEMPT_ACTIVE, which could trigger a second
4035 * cond_resched() call.
4036 */
4037 if (unlikely(preempt_count()))
4038 return;
1da177e4
LT
4039 do {
4040 add_preempt_count(PREEMPT_ACTIVE);
4041 schedule();
4042 sub_preempt_count(PREEMPT_ACTIVE);
4043 } while (need_resched());
4044}
4045
4046int __sched cond_resched(void)
4047{
4048 if (need_resched()) {
4049 __cond_resched();
4050 return 1;
4051 }
4052 return 0;
4053}
4054
4055EXPORT_SYMBOL(cond_resched);
4056
4057/*
4058 * cond_resched_lock() - if a reschedule is pending, drop the given lock,
4059 * call schedule, and on return reacquire the lock.
4060 *
4061 * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
4062 * operations here to prevent schedule() from being called twice (once via
4063 * spin_unlock(), once by hand).
4064 */
95cdf3b7 4065int cond_resched_lock(spinlock_t *lock)
1da177e4 4066{
6df3cecb
JK
4067 int ret = 0;
4068
1da177e4
LT
4069 if (need_lockbreak(lock)) {
4070 spin_unlock(lock);
4071 cpu_relax();
6df3cecb 4072 ret = 1;
1da177e4
LT
4073 spin_lock(lock);
4074 }
4075 if (need_resched()) {
4076 _raw_spin_unlock(lock);
4077 preempt_enable_no_resched();
4078 __cond_resched();
6df3cecb 4079 ret = 1;
1da177e4 4080 spin_lock(lock);
1da177e4 4081 }
6df3cecb 4082 return ret;
1da177e4
LT
4083}
4084
4085EXPORT_SYMBOL(cond_resched_lock);
4086
4087int __sched cond_resched_softirq(void)
4088{
4089 BUG_ON(!in_softirq());
4090
4091 if (need_resched()) {
4092 __local_bh_enable();
4093 __cond_resched();
4094 local_bh_disable();
4095 return 1;
4096 }
4097 return 0;
4098}
4099
4100EXPORT_SYMBOL(cond_resched_softirq);
4101
4102
4103/**
4104 * yield - yield the current processor to other threads.
4105 *
4106 * this is a shortcut for kernel-space yielding - it marks the
4107 * thread runnable and calls sys_sched_yield().
4108 */
4109void __sched yield(void)
4110{
4111 set_current_state(TASK_RUNNING);
4112 sys_sched_yield();
4113}
4114
4115EXPORT_SYMBOL(yield);
4116
4117/*
4118 * This task is about to go to sleep on IO. Increment rq->nr_iowait so
4119 * that process accounting knows that this is a task in IO wait state.
4120 *
4121 * But don't do that if it is a deliberate, throttling IO wait (this task
4122 * has set its backing_dev_info: the queue against which it should throttle)
4123 */
4124void __sched io_schedule(void)
4125{
39c715b7 4126 struct runqueue *rq = &per_cpu(runqueues, raw_smp_processor_id());
1da177e4
LT
4127
4128 atomic_inc(&rq->nr_iowait);
4129 schedule();
4130 atomic_dec(&rq->nr_iowait);
4131}
4132
4133EXPORT_SYMBOL(io_schedule);
4134
4135long __sched io_schedule_timeout(long timeout)
4136{
39c715b7 4137 struct runqueue *rq = &per_cpu(runqueues, raw_smp_processor_id());
1da177e4
LT
4138 long ret;
4139
4140 atomic_inc(&rq->nr_iowait);
4141 ret = schedule_timeout(timeout);
4142 atomic_dec(&rq->nr_iowait);
4143 return ret;
4144}
4145
4146/**
4147 * sys_sched_get_priority_max - return maximum RT priority.
4148 * @policy: scheduling class.
4149 *
4150 * this syscall returns the maximum rt_priority that can be used
4151 * by a given scheduling class.
4152 */
4153asmlinkage long sys_sched_get_priority_max(int policy)
4154{
4155 int ret = -EINVAL;
4156
4157 switch (policy) {
4158 case SCHED_FIFO:
4159 case SCHED_RR:
4160 ret = MAX_USER_RT_PRIO-1;
4161 break;
4162 case SCHED_NORMAL:
b0a9499c 4163 case SCHED_BATCH:
1da177e4
LT
4164 ret = 0;
4165 break;
4166 }
4167 return ret;
4168}
4169
4170/**
4171 * sys_sched_get_priority_min - return minimum RT priority.
4172 * @policy: scheduling class.
4173 *
4174 * this syscall returns the minimum rt_priority that can be used
4175 * by a given scheduling class.
4176 */
4177asmlinkage long sys_sched_get_priority_min(int policy)
4178{
4179 int ret = -EINVAL;
4180
4181 switch (policy) {
4182 case SCHED_FIFO:
4183 case SCHED_RR:
4184 ret = 1;
4185 break;
4186 case SCHED_NORMAL:
b0a9499c 4187 case SCHED_BATCH:
1da177e4
LT
4188 ret = 0;
4189 }
4190 return ret;
4191}
4192
4193/**
4194 * sys_sched_rr_get_interval - return the default timeslice of a process.
4195 * @pid: pid of the process.
4196 * @interval: userspace pointer to the timeslice value.
4197 *
4198 * this syscall writes the default timeslice value of a given process
4199 * into the user-space timespec buffer. A value of '0' means infinity.
4200 */
4201asmlinkage
4202long sys_sched_rr_get_interval(pid_t pid, struct timespec __user *interval)
4203{
4204 int retval = -EINVAL;
4205 struct timespec t;
4206 task_t *p;
4207
4208 if (pid < 0)
4209 goto out_nounlock;
4210
4211 retval = -ESRCH;
4212 read_lock(&tasklist_lock);
4213 p = find_process_by_pid(pid);
4214 if (!p)
4215 goto out_unlock;
4216
4217 retval = security_task_getscheduler(p);
4218 if (retval)
4219 goto out_unlock;
4220
4221 jiffies_to_timespec(p->policy & SCHED_FIFO ?
4222 0 : task_timeslice(p), &t);
4223 read_unlock(&tasklist_lock);
4224 retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0;
4225out_nounlock:
4226 return retval;
4227out_unlock:
4228 read_unlock(&tasklist_lock);
4229 return retval;
4230}
4231
4232static inline struct task_struct *eldest_child(struct task_struct *p)
4233{
4234 if (list_empty(&p->children)) return NULL;
4235 return list_entry(p->children.next,struct task_struct,sibling);
4236}
4237
4238static inline struct task_struct *older_sibling(struct task_struct *p)
4239{
4240 if (p->sibling.prev==&p->parent->children) return NULL;
4241 return list_entry(p->sibling.prev,struct task_struct,sibling);
4242}
4243
4244static inline struct task_struct *younger_sibling(struct task_struct *p)
4245{
4246 if (p->sibling.next==&p->parent->children) return NULL;
4247 return list_entry(p->sibling.next,struct task_struct,sibling);
4248}
4249
95cdf3b7 4250static void show_task(task_t *p)
1da177e4
LT
4251{
4252 task_t *relative;
4253 unsigned state;
4254 unsigned long free = 0;
4255 static const char *stat_nam[] = { "R", "S", "D", "T", "t", "Z", "X" };
4256
4257 printk("%-13.13s ", p->comm);
4258 state = p->state ? __ffs(p->state) + 1 : 0;
4259 if (state < ARRAY_SIZE(stat_nam))
4260 printk(stat_nam[state]);
4261 else
4262 printk("?");
4263#if (BITS_PER_LONG == 32)
4264 if (state == TASK_RUNNING)
4265 printk(" running ");
4266 else
4267 printk(" %08lX ", thread_saved_pc(p));
4268#else
4269 if (state == TASK_RUNNING)
4270 printk(" running task ");
4271 else
4272 printk(" %016lx ", thread_saved_pc(p));
4273#endif
4274#ifdef CONFIG_DEBUG_STACK_USAGE
4275 {
10ebffde 4276 unsigned long *n = end_of_stack(p);
1da177e4
LT
4277 while (!*n)
4278 n++;
10ebffde 4279 free = (unsigned long)n - (unsigned long)end_of_stack(p);
1da177e4
LT
4280 }
4281#endif
4282 printk("%5lu %5d %6d ", free, p->pid, p->parent->pid);
4283 if ((relative = eldest_child(p)))
4284 printk("%5d ", relative->pid);
4285 else
4286 printk(" ");
4287 if ((relative = younger_sibling(p)))
4288 printk("%7d", relative->pid);
4289 else
4290 printk(" ");
4291 if ((relative = older_sibling(p)))
4292 printk(" %5d", relative->pid);
4293 else
4294 printk(" ");
4295 if (!p->mm)
4296 printk(" (L-TLB)\n");
4297 else
4298 printk(" (NOTLB)\n");
4299
4300 if (state != TASK_RUNNING)
4301 show_stack(p, NULL);
4302}
4303
4304void show_state(void)
4305{
4306 task_t *g, *p;
4307
4308#if (BITS_PER_LONG == 32)
4309 printk("\n"
4310 " sibling\n");
4311 printk(" task PC pid father child younger older\n");
4312#else
4313 printk("\n"
4314 " sibling\n");
4315 printk(" task PC pid father child younger older\n");
4316#endif
4317 read_lock(&tasklist_lock);
4318 do_each_thread(g, p) {
4319 /*
4320 * reset the NMI-timeout, listing all files on a slow
4321 * console might take alot of time:
4322 */
4323 touch_nmi_watchdog();
4324 show_task(p);
4325 } while_each_thread(g, p);
4326
4327 read_unlock(&tasklist_lock);
de5097c2 4328 mutex_debug_show_all_locks();
1da177e4
LT
4329}
4330
f340c0d1
IM
4331/**
4332 * init_idle - set up an idle thread for a given CPU
4333 * @idle: task in question
4334 * @cpu: cpu the idle task belongs to
4335 *
4336 * NOTE: this function does not set the idle thread's NEED_RESCHED
4337 * flag, to make booting more robust.
4338 */
1da177e4
LT
4339void __devinit init_idle(task_t *idle, int cpu)
4340{
4341 runqueue_t *rq = cpu_rq(cpu);
4342 unsigned long flags;
4343
4344 idle->sleep_avg = 0;
4345 idle->array = NULL;
4346 idle->prio = MAX_PRIO;
4347 idle->state = TASK_RUNNING;
4348 idle->cpus_allowed = cpumask_of_cpu(cpu);
4349 set_task_cpu(idle, cpu);
4350
4351 spin_lock_irqsave(&rq->lock, flags);
4352 rq->curr = rq->idle = idle;
4866cde0
NP
4353#if defined(CONFIG_SMP) && defined(__ARCH_WANT_UNLOCKED_CTXSW)
4354 idle->oncpu = 1;
4355#endif
1da177e4
LT
4356 spin_unlock_irqrestore(&rq->lock, flags);
4357
4358 /* Set the preempt count _outside_ the spinlocks! */
4359#if defined(CONFIG_PREEMPT) && !defined(CONFIG_PREEMPT_BKL)
a1261f54 4360 task_thread_info(idle)->preempt_count = (idle->lock_depth >= 0);
1da177e4 4361#else
a1261f54 4362 task_thread_info(idle)->preempt_count = 0;
1da177e4
LT
4363#endif
4364}
4365
4366/*
4367 * In a system that switches off the HZ timer nohz_cpu_mask
4368 * indicates which cpus entered this state. This is used
4369 * in the rcu update to wait only for active cpus. For system
4370 * which do not switch off the HZ timer nohz_cpu_mask should
4371 * always be CPU_MASK_NONE.
4372 */
4373cpumask_t nohz_cpu_mask = CPU_MASK_NONE;
4374
4375#ifdef CONFIG_SMP
4376/*
4377 * This is how migration works:
4378 *
4379 * 1) we queue a migration_req_t structure in the source CPU's
4380 * runqueue and wake up that CPU's migration thread.
4381 * 2) we down() the locked semaphore => thread blocks.
4382 * 3) migration thread wakes up (implicitly it forces the migrated
4383 * thread off the CPU)
4384 * 4) it gets the migration request and checks whether the migrated
4385 * task is still in the wrong runqueue.
4386 * 5) if it's in the wrong runqueue then the migration thread removes
4387 * it and puts it into the right queue.
4388 * 6) migration thread up()s the semaphore.
4389 * 7) we wake up and the migration is done.
4390 */
4391
4392/*
4393 * Change a given task's CPU affinity. Migrate the thread to a
4394 * proper CPU and schedule it away if the CPU it's executing on
4395 * is removed from the allowed bitmask.
4396 *
4397 * NOTE: the caller must have a valid reference to the task, the
4398 * task must not exit() & deallocate itself prematurely. The
4399 * call is not atomic; no spinlocks may be held.
4400 */
4401int set_cpus_allowed(task_t *p, cpumask_t new_mask)
4402{
4403 unsigned long flags;
4404 int ret = 0;
4405 migration_req_t req;
4406 runqueue_t *rq;
4407
4408 rq = task_rq_lock(p, &flags);
4409 if (!cpus_intersects(new_mask, cpu_online_map)) {
4410 ret = -EINVAL;
4411 goto out;
4412 }
4413
4414 p->cpus_allowed = new_mask;
4415 /* Can the task run on the task's current CPU? If so, we're done */
4416 if (cpu_isset(task_cpu(p), new_mask))
4417 goto out;
4418
4419 if (migrate_task(p, any_online_cpu(new_mask), &req)) {
4420 /* Need help from migration thread: drop lock and wait. */
4421 task_rq_unlock(rq, &flags);
4422 wake_up_process(rq->migration_thread);
4423 wait_for_completion(&req.done);
4424 tlb_migrate_finish(p->mm);
4425 return 0;
4426 }
4427out:
4428 task_rq_unlock(rq, &flags);
4429 return ret;
4430}
4431
4432EXPORT_SYMBOL_GPL(set_cpus_allowed);
4433
4434/*
4435 * Move (not current) task off this cpu, onto dest cpu. We're doing
4436 * this because either it can't run here any more (set_cpus_allowed()
4437 * away from this CPU, or CPU going down), or because we're
4438 * attempting to rebalance this task on exec (sched_exec).
4439 *
4440 * So we race with normal scheduler movements, but that's OK, as long
4441 * as the task is no longer on this CPU.
4442 */
4443static void __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu)
4444{
4445 runqueue_t *rq_dest, *rq_src;
4446
4447 if (unlikely(cpu_is_offline(dest_cpu)))
4448 return;
4449
4450 rq_src = cpu_rq(src_cpu);
4451 rq_dest = cpu_rq(dest_cpu);
4452
4453 double_rq_lock(rq_src, rq_dest);
4454 /* Already moved. */
4455 if (task_cpu(p) != src_cpu)
4456 goto out;
4457 /* Affinity changed (again). */
4458 if (!cpu_isset(dest_cpu, p->cpus_allowed))
4459 goto out;
4460
4461 set_task_cpu(p, dest_cpu);
4462 if (p->array) {
4463 /*
4464 * Sync timestamp with rq_dest's before activating.
4465 * The same thing could be achieved by doing this step
4466 * afterwards, and pretending it was a local activate.
4467 * This way is cleaner and logically correct.
4468 */
4469 p->timestamp = p->timestamp - rq_src->timestamp_last_tick
4470 + rq_dest->timestamp_last_tick;
4471 deactivate_task(p, rq_src);
4472 activate_task(p, rq_dest, 0);
4473 if (TASK_PREEMPTS_CURR(p, rq_dest))
4474 resched_task(rq_dest->curr);
4475 }
4476
4477out:
4478 double_rq_unlock(rq_src, rq_dest);
4479}
4480
4481/*
4482 * migration_thread - this is a highprio system thread that performs
4483 * thread migration by bumping thread off CPU then 'pushing' onto
4484 * another runqueue.
4485 */
95cdf3b7 4486static int migration_thread(void *data)
1da177e4
LT
4487{
4488 runqueue_t *rq;
4489 int cpu = (long)data;
4490
4491 rq = cpu_rq(cpu);
4492 BUG_ON(rq->migration_thread != current);
4493
4494 set_current_state(TASK_INTERRUPTIBLE);
4495 while (!kthread_should_stop()) {
4496 struct list_head *head;
4497 migration_req_t *req;
4498
3e1d1d28 4499 try_to_freeze();
1da177e4
LT
4500
4501 spin_lock_irq(&rq->lock);
4502
4503 if (cpu_is_offline(cpu)) {
4504 spin_unlock_irq(&rq->lock);
4505 goto wait_to_die;
4506 }
4507
4508 if (rq->active_balance) {
4509 active_load_balance(rq, cpu);
4510 rq->active_balance = 0;
4511 }
4512
4513 head = &rq->migration_queue;
4514
4515 if (list_empty(head)) {
4516 spin_unlock_irq(&rq->lock);
4517 schedule();
4518 set_current_state(TASK_INTERRUPTIBLE);
4519 continue;
4520 }
4521 req = list_entry(head->next, migration_req_t, list);
4522 list_del_init(head->next);
4523
674311d5
NP
4524 spin_unlock(&rq->lock);
4525 __migrate_task(req->task, cpu, req->dest_cpu);
4526 local_irq_enable();
1da177e4
LT
4527
4528 complete(&req->done);
4529 }
4530 __set_current_state(TASK_RUNNING);
4531 return 0;
4532
4533wait_to_die:
4534 /* Wait for kthread_stop */
4535 set_current_state(TASK_INTERRUPTIBLE);
4536 while (!kthread_should_stop()) {
4537 schedule();
4538 set_current_state(TASK_INTERRUPTIBLE);
4539 }
4540 __set_current_state(TASK_RUNNING);
4541 return 0;
4542}
4543
4544#ifdef CONFIG_HOTPLUG_CPU
4545/* Figure out where task on dead CPU should go, use force if neccessary. */
4546static void move_task_off_dead_cpu(int dead_cpu, struct task_struct *tsk)
4547{
4548 int dest_cpu;
4549 cpumask_t mask;
4550
4551 /* On same node? */
4552 mask = node_to_cpumask(cpu_to_node(dead_cpu));
4553 cpus_and(mask, mask, tsk->cpus_allowed);
4554 dest_cpu = any_online_cpu(mask);
4555
4556 /* On any allowed CPU? */
4557 if (dest_cpu == NR_CPUS)
4558 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4559
4560 /* No more Mr. Nice Guy. */
4561 if (dest_cpu == NR_CPUS) {
b39c4fab 4562 cpus_setall(tsk->cpus_allowed);
1da177e4
LT
4563 dest_cpu = any_online_cpu(tsk->cpus_allowed);
4564
4565 /*
4566 * Don't tell them about moving exiting tasks or
4567 * kernel threads (both mm NULL), since they never
4568 * leave kernel.
4569 */
4570 if (tsk->mm && printk_ratelimit())
4571 printk(KERN_INFO "process %d (%s) no "
4572 "longer affine to cpu%d\n",
4573 tsk->pid, tsk->comm, dead_cpu);
4574 }
4575 __migrate_task(tsk, dead_cpu, dest_cpu);
4576}
4577
4578/*
4579 * While a dead CPU has no uninterruptible tasks queued at this point,
4580 * it might still have a nonzero ->nr_uninterruptible counter, because
4581 * for performance reasons the counter is not stricly tracking tasks to
4582 * their home CPUs. So we just add the counter to another CPU's counter,
4583 * to keep the global sum constant after CPU-down:
4584 */
4585static void migrate_nr_uninterruptible(runqueue_t *rq_src)
4586{
4587 runqueue_t *rq_dest = cpu_rq(any_online_cpu(CPU_MASK_ALL));
4588 unsigned long flags;
4589
4590 local_irq_save(flags);
4591 double_rq_lock(rq_src, rq_dest);
4592 rq_dest->nr_uninterruptible += rq_src->nr_uninterruptible;
4593 rq_src->nr_uninterruptible = 0;
4594 double_rq_unlock(rq_src, rq_dest);
4595 local_irq_restore(flags);
4596}
4597
4598/* Run through task list and migrate tasks from the dead cpu. */
4599static void migrate_live_tasks(int src_cpu)
4600{
4601 struct task_struct *tsk, *t;
4602
4603 write_lock_irq(&tasklist_lock);
4604
4605 do_each_thread(t, tsk) {
4606 if (tsk == current)
4607 continue;
4608
4609 if (task_cpu(tsk) == src_cpu)
4610 move_task_off_dead_cpu(src_cpu, tsk);
4611 } while_each_thread(t, tsk);
4612
4613 write_unlock_irq(&tasklist_lock);
4614}
4615
4616/* Schedules idle task to be the next runnable task on current CPU.
4617 * It does so by boosting its priority to highest possible and adding it to
4618 * the _front_ of runqueue. Used by CPU offline code.
4619 */
4620void sched_idle_next(void)
4621{
4622 int cpu = smp_processor_id();
4623 runqueue_t *rq = this_rq();
4624 struct task_struct *p = rq->idle;
4625 unsigned long flags;
4626
4627 /* cpu has to be offline */
4628 BUG_ON(cpu_online(cpu));
4629
4630 /* Strictly not necessary since rest of the CPUs are stopped by now
4631 * and interrupts disabled on current cpu.
4632 */
4633 spin_lock_irqsave(&rq->lock, flags);
4634
4635 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4636 /* Add idle task to _front_ of it's priority queue */
4637 __activate_idle_task(p, rq);
4638
4639 spin_unlock_irqrestore(&rq->lock, flags);
4640}
4641
4642/* Ensures that the idle task is using init_mm right before its cpu goes
4643 * offline.
4644 */
4645void idle_task_exit(void)
4646{
4647 struct mm_struct *mm = current->active_mm;
4648
4649 BUG_ON(cpu_online(smp_processor_id()));
4650
4651 if (mm != &init_mm)
4652 switch_mm(mm, &init_mm, current);
4653 mmdrop(mm);
4654}
4655
4656static void migrate_dead(unsigned int dead_cpu, task_t *tsk)
4657{
4658 struct runqueue *rq = cpu_rq(dead_cpu);
4659
4660 /* Must be exiting, otherwise would be on tasklist. */
4661 BUG_ON(tsk->exit_state != EXIT_ZOMBIE && tsk->exit_state != EXIT_DEAD);
4662
4663 /* Cannot have done final schedule yet: would have vanished. */
4664 BUG_ON(tsk->flags & PF_DEAD);
4665
4666 get_task_struct(tsk);
4667
4668 /*
4669 * Drop lock around migration; if someone else moves it,
4670 * that's OK. No task can be added to this CPU, so iteration is
4671 * fine.
4672 */
4673 spin_unlock_irq(&rq->lock);
4674 move_task_off_dead_cpu(dead_cpu, tsk);
4675 spin_lock_irq(&rq->lock);
4676
4677 put_task_struct(tsk);
4678}
4679
4680/* release_task() removes task from tasklist, so we won't find dead tasks. */
4681static void migrate_dead_tasks(unsigned int dead_cpu)
4682{
4683 unsigned arr, i;
4684 struct runqueue *rq = cpu_rq(dead_cpu);
4685
4686 for (arr = 0; arr < 2; arr++) {
4687 for (i = 0; i < MAX_PRIO; i++) {
4688 struct list_head *list = &rq->arrays[arr].queue[i];
4689 while (!list_empty(list))
4690 migrate_dead(dead_cpu,
4691 list_entry(list->next, task_t,
4692 run_list));
4693 }
4694 }
4695}
4696#endif /* CONFIG_HOTPLUG_CPU */
4697
4698/*
4699 * migration_call - callback that gets triggered when a CPU is added.
4700 * Here we can start up the necessary migration thread for the new CPU.
4701 */
4702static int migration_call(struct notifier_block *nfb, unsigned long action,
4703 void *hcpu)
4704{
4705 int cpu = (long)hcpu;
4706 struct task_struct *p;
4707 struct runqueue *rq;
4708 unsigned long flags;
4709
4710 switch (action) {
4711 case CPU_UP_PREPARE:
4712 p = kthread_create(migration_thread, hcpu, "migration/%d",cpu);
4713 if (IS_ERR(p))
4714 return NOTIFY_BAD;
4715 p->flags |= PF_NOFREEZE;
4716 kthread_bind(p, cpu);
4717 /* Must be high prio: stop_machine expects to yield to it. */
4718 rq = task_rq_lock(p, &flags);
4719 __setscheduler(p, SCHED_FIFO, MAX_RT_PRIO-1);
4720 task_rq_unlock(rq, &flags);
4721 cpu_rq(cpu)->migration_thread = p;
4722 break;
4723 case CPU_ONLINE:
4724 /* Strictly unneccessary, as first user will wake it. */
4725 wake_up_process(cpu_rq(cpu)->migration_thread);
4726 break;
4727#ifdef CONFIG_HOTPLUG_CPU
4728 case CPU_UP_CANCELED:
4729 /* Unbind it from offline cpu so it can run. Fall thru. */
a4c4af7c
HC
4730 kthread_bind(cpu_rq(cpu)->migration_thread,
4731 any_online_cpu(cpu_online_map));
1da177e4
LT
4732 kthread_stop(cpu_rq(cpu)->migration_thread);
4733 cpu_rq(cpu)->migration_thread = NULL;
4734 break;
4735 case CPU_DEAD:
4736 migrate_live_tasks(cpu);
4737 rq = cpu_rq(cpu);
4738 kthread_stop(rq->migration_thread);
4739 rq->migration_thread = NULL;
4740 /* Idle task back to normal (off runqueue, low prio) */
4741 rq = task_rq_lock(rq->idle, &flags);
4742 deactivate_task(rq->idle, rq);
4743 rq->idle->static_prio = MAX_PRIO;
4744 __setscheduler(rq->idle, SCHED_NORMAL, 0);
4745 migrate_dead_tasks(cpu);
4746 task_rq_unlock(rq, &flags);
4747 migrate_nr_uninterruptible(rq);
4748 BUG_ON(rq->nr_running != 0);
4749
4750 /* No need to migrate the tasks: it was best-effort if
4751 * they didn't do lock_cpu_hotplug(). Just wake up
4752 * the requestors. */
4753 spin_lock_irq(&rq->lock);
4754 while (!list_empty(&rq->migration_queue)) {
4755 migration_req_t *req;
4756 req = list_entry(rq->migration_queue.next,
4757 migration_req_t, list);
1da177e4
LT
4758 list_del_init(&req->list);
4759 complete(&req->done);
4760 }
4761 spin_unlock_irq(&rq->lock);
4762 break;
4763#endif
4764 }
4765 return NOTIFY_OK;
4766}
4767
4768/* Register at highest priority so that task migration (migrate_all_tasks)
4769 * happens before everything else.
4770 */
4771static struct notifier_block __devinitdata migration_notifier = {
4772 .notifier_call = migration_call,
4773 .priority = 10
4774};
4775
4776int __init migration_init(void)
4777{
4778 void *cpu = (void *)(long)smp_processor_id();
4779 /* Start one for boot CPU. */
4780 migration_call(&migration_notifier, CPU_UP_PREPARE, cpu);
4781 migration_call(&migration_notifier, CPU_ONLINE, cpu);
4782 register_cpu_notifier(&migration_notifier);
4783 return 0;
4784}
4785#endif
4786
4787#ifdef CONFIG_SMP
1a20ff27 4788#undef SCHED_DOMAIN_DEBUG
1da177e4
LT
4789#ifdef SCHED_DOMAIN_DEBUG
4790static void sched_domain_debug(struct sched_domain *sd, int cpu)
4791{
4792 int level = 0;
4793
41c7ce9a
NP
4794 if (!sd) {
4795 printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu);
4796 return;
4797 }
4798
1da177e4
LT
4799 printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu);
4800
4801 do {
4802 int i;
4803 char str[NR_CPUS];
4804 struct sched_group *group = sd->groups;
4805 cpumask_t groupmask;
4806
4807 cpumask_scnprintf(str, NR_CPUS, sd->span);
4808 cpus_clear(groupmask);
4809
4810 printk(KERN_DEBUG);
4811 for (i = 0; i < level + 1; i++)
4812 printk(" ");
4813 printk("domain %d: ", level);
4814
4815 if (!(sd->flags & SD_LOAD_BALANCE)) {
4816 printk("does not load-balance\n");
4817 if (sd->parent)
4818 printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain has parent");
4819 break;
4820 }
4821
4822 printk("span %s\n", str);
4823
4824 if (!cpu_isset(cpu, sd->span))
4825 printk(KERN_ERR "ERROR: domain->span does not contain CPU%d\n", cpu);
4826 if (!cpu_isset(cpu, group->cpumask))
4827 printk(KERN_ERR "ERROR: domain->groups does not contain CPU%d\n", cpu);
4828
4829 printk(KERN_DEBUG);
4830 for (i = 0; i < level + 2; i++)
4831 printk(" ");
4832 printk("groups:");
4833 do {
4834 if (!group) {
4835 printk("\n");
4836 printk(KERN_ERR "ERROR: group is NULL\n");
4837 break;
4838 }
4839
4840 if (!group->cpu_power) {
4841 printk("\n");
4842 printk(KERN_ERR "ERROR: domain->cpu_power not set\n");
4843 }
4844
4845 if (!cpus_weight(group->cpumask)) {
4846 printk("\n");
4847 printk(KERN_ERR "ERROR: empty group\n");
4848 }
4849
4850 if (cpus_intersects(groupmask, group->cpumask)) {
4851 printk("\n");
4852 printk(KERN_ERR "ERROR: repeated CPUs\n");
4853 }
4854
4855 cpus_or(groupmask, groupmask, group->cpumask);
4856
4857 cpumask_scnprintf(str, NR_CPUS, group->cpumask);
4858 printk(" %s", str);
4859
4860 group = group->next;
4861 } while (group != sd->groups);
4862 printk("\n");
4863
4864 if (!cpus_equal(sd->span, groupmask))
4865 printk(KERN_ERR "ERROR: groups don't span domain->span\n");
4866
4867 level++;
4868 sd = sd->parent;
4869
4870 if (sd) {
4871 if (!cpus_subset(groupmask, sd->span))
4872 printk(KERN_ERR "ERROR: parent span is not a superset of domain->span\n");
4873 }
4874
4875 } while (sd);
4876}
4877#else
4878#define sched_domain_debug(sd, cpu) {}
4879#endif
4880
1a20ff27 4881static int sd_degenerate(struct sched_domain *sd)
245af2c7
SS
4882{
4883 if (cpus_weight(sd->span) == 1)
4884 return 1;
4885
4886 /* Following flags need at least 2 groups */
4887 if (sd->flags & (SD_LOAD_BALANCE |
4888 SD_BALANCE_NEWIDLE |
4889 SD_BALANCE_FORK |
4890 SD_BALANCE_EXEC)) {
4891 if (sd->groups != sd->groups->next)
4892 return 0;
4893 }
4894
4895 /* Following flags don't use groups */
4896 if (sd->flags & (SD_WAKE_IDLE |
4897 SD_WAKE_AFFINE |
4898 SD_WAKE_BALANCE))
4899 return 0;
4900
4901 return 1;
4902}
4903
1a20ff27 4904static int sd_parent_degenerate(struct sched_domain *sd,
245af2c7
SS
4905 struct sched_domain *parent)
4906{
4907 unsigned long cflags = sd->flags, pflags = parent->flags;
4908
4909 if (sd_degenerate(parent))
4910 return 1;
4911
4912 if (!cpus_equal(sd->span, parent->span))
4913 return 0;
4914
4915 /* Does parent contain flags not in child? */
4916 /* WAKE_BALANCE is a subset of WAKE_AFFINE */
4917 if (cflags & SD_WAKE_AFFINE)
4918 pflags &= ~SD_WAKE_BALANCE;
4919 /* Flags needing groups don't count if only 1 group in parent */
4920 if (parent->groups == parent->groups->next) {
4921 pflags &= ~(SD_LOAD_BALANCE |
4922 SD_BALANCE_NEWIDLE |
4923 SD_BALANCE_FORK |
4924 SD_BALANCE_EXEC);
4925 }
4926 if (~cflags & pflags)
4927 return 0;
4928
4929 return 1;
4930}
4931
1da177e4
LT
4932/*
4933 * Attach the domain 'sd' to 'cpu' as its base domain. Callers must
4934 * hold the hotplug lock.
4935 */
9c1cfda2 4936static void cpu_attach_domain(struct sched_domain *sd, int cpu)
1da177e4 4937{
1da177e4 4938 runqueue_t *rq = cpu_rq(cpu);
245af2c7
SS
4939 struct sched_domain *tmp;
4940
4941 /* Remove the sched domains which do not contribute to scheduling. */
4942 for (tmp = sd; tmp; tmp = tmp->parent) {
4943 struct sched_domain *parent = tmp->parent;
4944 if (!parent)
4945 break;
4946 if (sd_parent_degenerate(tmp, parent))
4947 tmp->parent = parent->parent;
4948 }
4949
4950 if (sd && sd_degenerate(sd))
4951 sd = sd->parent;
1da177e4
LT
4952
4953 sched_domain_debug(sd, cpu);
4954
674311d5 4955 rcu_assign_pointer(rq->sd, sd);
1da177e4
LT
4956}
4957
4958/* cpus with isolated domains */
9c1cfda2 4959static cpumask_t __devinitdata cpu_isolated_map = CPU_MASK_NONE;
1da177e4
LT
4960
4961/* Setup the mask of cpus configured for isolated domains */
4962static int __init isolated_cpu_setup(char *str)
4963{
4964 int ints[NR_CPUS], i;
4965
4966 str = get_options(str, ARRAY_SIZE(ints), ints);
4967 cpus_clear(cpu_isolated_map);
4968 for (i = 1; i <= ints[0]; i++)
4969 if (ints[i] < NR_CPUS)
4970 cpu_set(ints[i], cpu_isolated_map);
4971 return 1;
4972}
4973
4974__setup ("isolcpus=", isolated_cpu_setup);
4975
4976/*
4977 * init_sched_build_groups takes an array of groups, the cpumask we wish
4978 * to span, and a pointer to a function which identifies what group a CPU
4979 * belongs to. The return value of group_fn must be a valid index into the
4980 * groups[] array, and must be >= 0 and < NR_CPUS (due to the fact that we
4981 * keep track of groups covered with a cpumask_t).
4982 *
4983 * init_sched_build_groups will build a circular linked list of the groups
4984 * covered by the given span, and will set each group's ->cpumask correctly,
4985 * and ->cpu_power to 0.
4986 */
9c1cfda2
JH
4987static void init_sched_build_groups(struct sched_group groups[], cpumask_t span,
4988 int (*group_fn)(int cpu))
1da177e4
LT
4989{
4990 struct sched_group *first = NULL, *last = NULL;
4991 cpumask_t covered = CPU_MASK_NONE;
4992 int i;
4993
4994 for_each_cpu_mask(i, span) {
4995 int group = group_fn(i);
4996 struct sched_group *sg = &groups[group];
4997 int j;
4998
4999 if (cpu_isset(i, covered))
5000 continue;
5001
5002 sg->cpumask = CPU_MASK_NONE;
5003 sg->cpu_power = 0;
5004
5005 for_each_cpu_mask(j, span) {
5006 if (group_fn(j) != group)
5007 continue;
5008
5009 cpu_set(j, covered);
5010 cpu_set(j, sg->cpumask);
5011 }
5012 if (!first)
5013 first = sg;
5014 if (last)
5015 last->next = sg;
5016 last = sg;
5017 }
5018 last->next = first;
5019}
5020
9c1cfda2 5021#define SD_NODES_PER_DOMAIN 16
1da177e4 5022
198e2f18 5023/*
5024 * Self-tuning task migration cost measurement between source and target CPUs.
5025 *
5026 * This is done by measuring the cost of manipulating buffers of varying
5027 * sizes. For a given buffer-size here are the steps that are taken:
5028 *
5029 * 1) the source CPU reads+dirties a shared buffer
5030 * 2) the target CPU reads+dirties the same shared buffer
5031 *
5032 * We measure how long they take, in the following 4 scenarios:
5033 *
5034 * - source: CPU1, target: CPU2 | cost1
5035 * - source: CPU2, target: CPU1 | cost2
5036 * - source: CPU1, target: CPU1 | cost3
5037 * - source: CPU2, target: CPU2 | cost4
5038 *
5039 * We then calculate the cost3+cost4-cost1-cost2 difference - this is
5040 * the cost of migration.
5041 *
5042 * We then start off from a small buffer-size and iterate up to larger
5043 * buffer sizes, in 5% steps - measuring each buffer-size separately, and
5044 * doing a maximum search for the cost. (The maximum cost for a migration
5045 * normally occurs when the working set size is around the effective cache
5046 * size.)
5047 */
5048#define SEARCH_SCOPE 2
5049#define MIN_CACHE_SIZE (64*1024U)
5050#define DEFAULT_CACHE_SIZE (5*1024*1024U)
70b4d63e 5051#define ITERATIONS 1
198e2f18 5052#define SIZE_THRESH 130
5053#define COST_THRESH 130
5054
5055/*
5056 * The migration cost is a function of 'domain distance'. Domain
5057 * distance is the number of steps a CPU has to iterate down its
5058 * domain tree to share a domain with the other CPU. The farther
5059 * two CPUs are from each other, the larger the distance gets.
5060 *
5061 * Note that we use the distance only to cache measurement results,
5062 * the distance value is not used numerically otherwise. When two
5063 * CPUs have the same distance it is assumed that the migration
5064 * cost is the same. (this is a simplification but quite practical)
5065 */
5066#define MAX_DOMAIN_DISTANCE 32
5067
5068static unsigned long long migration_cost[MAX_DOMAIN_DISTANCE] =
5069 { [ 0 ... MAX_DOMAIN_DISTANCE-1 ] = -1LL };
5070
5071/*
5072 * Allow override of migration cost - in units of microseconds.
5073 * E.g. migration_cost=1000,2000,3000 will set up a level-1 cost
5074 * of 1 msec, level-2 cost of 2 msecs and level3 cost of 3 msecs:
5075 */
5076static int __init migration_cost_setup(char *str)
5077{
5078 int ints[MAX_DOMAIN_DISTANCE+1], i;
5079
5080 str = get_options(str, ARRAY_SIZE(ints), ints);
5081
5082 printk("#ints: %d\n", ints[0]);
5083 for (i = 1; i <= ints[0]; i++) {
5084 migration_cost[i-1] = (unsigned long long)ints[i]*1000;
5085 printk("migration_cost[%d]: %Ld\n", i-1, migration_cost[i-1]);
5086 }
5087 return 1;
5088}
5089
5090__setup ("migration_cost=", migration_cost_setup);
5091
5092/*
5093 * Global multiplier (divisor) for migration-cutoff values,
5094 * in percentiles. E.g. use a value of 150 to get 1.5 times
5095 * longer cache-hot cutoff times.
5096 *
5097 * (We scale it from 100 to 128 to long long handling easier.)
5098 */
5099
5100#define MIGRATION_FACTOR_SCALE 128
5101
5102static unsigned int migration_factor = MIGRATION_FACTOR_SCALE;
5103
5104static int __init setup_migration_factor(char *str)
5105{
5106 get_option(&str, &migration_factor);
5107 migration_factor = migration_factor * MIGRATION_FACTOR_SCALE / 100;
5108 return 1;
5109}
5110
5111__setup("migration_factor=", setup_migration_factor);
5112
5113/*
5114 * Estimated distance of two CPUs, measured via the number of domains
5115 * we have to pass for the two CPUs to be in the same span:
5116 */
5117static unsigned long domain_distance(int cpu1, int cpu2)
5118{
5119 unsigned long distance = 0;
5120 struct sched_domain *sd;
5121
5122 for_each_domain(cpu1, sd) {
5123 WARN_ON(!cpu_isset(cpu1, sd->span));
5124 if (cpu_isset(cpu2, sd->span))
5125 return distance;
5126 distance++;
5127 }
5128 if (distance >= MAX_DOMAIN_DISTANCE) {
5129 WARN_ON(1);
5130 distance = MAX_DOMAIN_DISTANCE-1;
5131 }
5132
5133 return distance;
5134}
5135
5136static unsigned int migration_debug;
5137
5138static int __init setup_migration_debug(char *str)
5139{
5140 get_option(&str, &migration_debug);
5141 return 1;
5142}
5143
5144__setup("migration_debug=", setup_migration_debug);
5145
5146/*
5147 * Maximum cache-size that the scheduler should try to measure.
5148 * Architectures with larger caches should tune this up during
5149 * bootup. Gets used in the domain-setup code (i.e. during SMP
5150 * bootup).
5151 */
5152unsigned int max_cache_size;
5153
5154static int __init setup_max_cache_size(char *str)
5155{
5156 get_option(&str, &max_cache_size);
5157 return 1;
5158}
5159
5160__setup("max_cache_size=", setup_max_cache_size);
5161
5162/*
5163 * Dirty a big buffer in a hard-to-predict (for the L2 cache) way. This
5164 * is the operation that is timed, so we try to generate unpredictable
5165 * cachemisses that still end up filling the L2 cache:
5166 */
5167static void touch_cache(void *__cache, unsigned long __size)
5168{
5169 unsigned long size = __size/sizeof(long), chunk1 = size/3,
5170 chunk2 = 2*size/3;
5171 unsigned long *cache = __cache;
5172 int i;
5173
5174 for (i = 0; i < size/6; i += 8) {
5175 switch (i % 6) {
5176 case 0: cache[i]++;
5177 case 1: cache[size-1-i]++;
5178 case 2: cache[chunk1-i]++;
5179 case 3: cache[chunk1+i]++;
5180 case 4: cache[chunk2-i]++;
5181 case 5: cache[chunk2+i]++;
5182 }
5183 }
5184}
5185
5186/*
5187 * Measure the cache-cost of one task migration. Returns in units of nsec.
5188 */
5189static unsigned long long measure_one(void *cache, unsigned long size,
5190 int source, int target)
5191{
5192 cpumask_t mask, saved_mask;
5193 unsigned long long t0, t1, t2, t3, cost;
5194
5195 saved_mask = current->cpus_allowed;
5196
5197 /*
5198 * Flush source caches to RAM and invalidate them:
5199 */
5200 sched_cacheflush();
5201
5202 /*
5203 * Migrate to the source CPU:
5204 */
5205 mask = cpumask_of_cpu(source);
5206 set_cpus_allowed(current, mask);
5207 WARN_ON(smp_processor_id() != source);
5208
5209 /*
5210 * Dirty the working set:
5211 */
5212 t0 = sched_clock();
5213 touch_cache(cache, size);
5214 t1 = sched_clock();
5215
5216 /*
5217 * Migrate to the target CPU, dirty the L2 cache and access
5218 * the shared buffer. (which represents the working set
5219 * of a migrated task.)
5220 */
5221 mask = cpumask_of_cpu(target);
5222 set_cpus_allowed(current, mask);
5223 WARN_ON(smp_processor_id() != target);
5224
5225 t2 = sched_clock();
5226 touch_cache(cache, size);
5227 t3 = sched_clock();
5228
5229 cost = t1-t0 + t3-t2;
5230
5231 if (migration_debug >= 2)
5232 printk("[%d->%d]: %8Ld %8Ld %8Ld => %10Ld.\n",
5233 source, target, t1-t0, t1-t0, t3-t2, cost);
5234 /*
5235 * Flush target caches to RAM and invalidate them:
5236 */
5237 sched_cacheflush();
5238
5239 set_cpus_allowed(current, saved_mask);
5240
5241 return cost;
5242}
5243
5244/*
5245 * Measure a series of task migrations and return the average
5246 * result. Since this code runs early during bootup the system
5247 * is 'undisturbed' and the average latency makes sense.
5248 *
5249 * The algorithm in essence auto-detects the relevant cache-size,
5250 * so it will properly detect different cachesizes for different
5251 * cache-hierarchies, depending on how the CPUs are connected.
5252 *
5253 * Architectures can prime the upper limit of the search range via
5254 * max_cache_size, otherwise the search range defaults to 20MB...64K.
5255 */
5256static unsigned long long
5257measure_cost(int cpu1, int cpu2, void *cache, unsigned int size)
5258{
5259 unsigned long long cost1, cost2;
5260 int i;
5261
5262 /*
5263 * Measure the migration cost of 'size' bytes, over an
5264 * average of 10 runs:
5265 *
5266 * (We perturb the cache size by a small (0..4k)
5267 * value to compensate size/alignment related artifacts.
5268 * We also subtract the cost of the operation done on
5269 * the same CPU.)
5270 */
5271 cost1 = 0;
5272
5273 /*
5274 * dry run, to make sure we start off cache-cold on cpu1,
5275 * and to get any vmalloc pagefaults in advance:
5276 */
5277 measure_one(cache, size, cpu1, cpu2);
5278 for (i = 0; i < ITERATIONS; i++)
5279 cost1 += measure_one(cache, size - i*1024, cpu1, cpu2);
5280
5281 measure_one(cache, size, cpu2, cpu1);
5282 for (i = 0; i < ITERATIONS; i++)
5283 cost1 += measure_one(cache, size - i*1024, cpu2, cpu1);
5284
5285 /*
5286 * (We measure the non-migrating [cached] cost on both
5287 * cpu1 and cpu2, to handle CPUs with different speeds)
5288 */
5289 cost2 = 0;
5290
5291 measure_one(cache, size, cpu1, cpu1);
5292 for (i = 0; i < ITERATIONS; i++)
5293 cost2 += measure_one(cache, size - i*1024, cpu1, cpu1);
5294
5295 measure_one(cache, size, cpu2, cpu2);
5296 for (i = 0; i < ITERATIONS; i++)
5297 cost2 += measure_one(cache, size - i*1024, cpu2, cpu2);
5298
5299 /*
5300 * Get the per-iteration migration cost:
5301 */
5302 do_div(cost1, 2*ITERATIONS);
5303 do_div(cost2, 2*ITERATIONS);
5304
5305 return cost1 - cost2;
5306}
5307
5308static unsigned long long measure_migration_cost(int cpu1, int cpu2)
5309{
5310 unsigned long long max_cost = 0, fluct = 0, avg_fluct = 0;
5311 unsigned int max_size, size, size_found = 0;
5312 long long cost = 0, prev_cost;
5313 void *cache;
5314
5315 /*
5316 * Search from max_cache_size*5 down to 64K - the real relevant
5317 * cachesize has to lie somewhere inbetween.
5318 */
5319 if (max_cache_size) {
5320 max_size = max(max_cache_size * SEARCH_SCOPE, MIN_CACHE_SIZE);
5321 size = max(max_cache_size / SEARCH_SCOPE, MIN_CACHE_SIZE);
5322 } else {
5323 /*
5324 * Since we have no estimation about the relevant
5325 * search range
5326 */
5327 max_size = DEFAULT_CACHE_SIZE * SEARCH_SCOPE;
5328 size = MIN_CACHE_SIZE;
5329 }
5330
5331 if (!cpu_online(cpu1) || !cpu_online(cpu2)) {
5332 printk("cpu %d and %d not both online!\n", cpu1, cpu2);
5333 return 0;
5334 }
5335
5336 /*
5337 * Allocate the working set:
5338 */
5339 cache = vmalloc(max_size);
5340 if (!cache) {
5341 printk("could not vmalloc %d bytes for cache!\n", 2*max_size);
5342 return 1000000; // return 1 msec on very small boxen
5343 }
5344
5345 while (size <= max_size) {
5346 prev_cost = cost;
5347 cost = measure_cost(cpu1, cpu2, cache, size);
5348
5349 /*
5350 * Update the max:
5351 */
5352 if (cost > 0) {
5353 if (max_cost < cost) {
5354 max_cost = cost;
5355 size_found = size;
5356 }
5357 }
5358 /*
5359 * Calculate average fluctuation, we use this to prevent
5360 * noise from triggering an early break out of the loop:
5361 */
5362 fluct = abs(cost - prev_cost);
5363 avg_fluct = (avg_fluct + fluct)/2;
5364
5365 if (migration_debug)
5366 printk("-> [%d][%d][%7d] %3ld.%ld [%3ld.%ld] (%ld): (%8Ld %8Ld)\n",
5367 cpu1, cpu2, size,
5368 (long)cost / 1000000,
5369 ((long)cost / 100000) % 10,
5370 (long)max_cost / 1000000,
5371 ((long)max_cost / 100000) % 10,
5372 domain_distance(cpu1, cpu2),
5373 cost, avg_fluct);
5374
5375 /*
5376 * If we iterated at least 20% past the previous maximum,
5377 * and the cost has dropped by more than 20% already,
5378 * (taking fluctuations into account) then we assume to
5379 * have found the maximum and break out of the loop early:
5380 */
5381 if (size_found && (size*100 > size_found*SIZE_THRESH))
5382 if (cost+avg_fluct <= 0 ||
5383 max_cost*100 > (cost+avg_fluct)*COST_THRESH) {
5384
5385 if (migration_debug)
5386 printk("-> found max.\n");
5387 break;
5388 }
5389 /*
70b4d63e 5390 * Increase the cachesize in 10% steps:
198e2f18 5391 */
70b4d63e 5392 size = size * 10 / 9;
198e2f18 5393 }
5394
5395 if (migration_debug)
5396 printk("[%d][%d] working set size found: %d, cost: %Ld\n",
5397 cpu1, cpu2, size_found, max_cost);
5398
5399 vfree(cache);
5400
5401 /*
5402 * A task is considered 'cache cold' if at least 2 times
5403 * the worst-case cost of migration has passed.
5404 *
5405 * (this limit is only listened to if the load-balancing
5406 * situation is 'nice' - if there is a large imbalance we
5407 * ignore it for the sake of CPU utilization and
5408 * processing fairness.)
5409 */
5410 return 2 * max_cost * migration_factor / MIGRATION_FACTOR_SCALE;
5411}
5412
5413static void calibrate_migration_costs(const cpumask_t *cpu_map)
5414{
5415 int cpu1 = -1, cpu2 = -1, cpu, orig_cpu = raw_smp_processor_id();
5416 unsigned long j0, j1, distance, max_distance = 0;
5417 struct sched_domain *sd;
5418
5419 j0 = jiffies;
5420
5421 /*
5422 * First pass - calculate the cacheflush times:
5423 */
5424 for_each_cpu_mask(cpu1, *cpu_map) {
5425 for_each_cpu_mask(cpu2, *cpu_map) {
5426 if (cpu1 == cpu2)
5427 continue;
5428 distance = domain_distance(cpu1, cpu2);
5429 max_distance = max(max_distance, distance);
5430 /*
5431 * No result cached yet?
5432 */
5433 if (migration_cost[distance] == -1LL)
5434 migration_cost[distance] =
5435 measure_migration_cost(cpu1, cpu2);
5436 }
5437 }
5438 /*
5439 * Second pass - update the sched domain hierarchy with
5440 * the new cache-hot-time estimations:
5441 */
5442 for_each_cpu_mask(cpu, *cpu_map) {
5443 distance = 0;
5444 for_each_domain(cpu, sd) {
5445 sd->cache_hot_time = migration_cost[distance];
5446 distance++;
5447 }
5448 }
5449 /*
5450 * Print the matrix:
5451 */
5452 if (migration_debug)
5453 printk("migration: max_cache_size: %d, cpu: %d MHz:\n",
5454 max_cache_size,
5455#ifdef CONFIG_X86
5456 cpu_khz/1000
5457#else
5458 -1
5459#endif
5460 );
bd576c95
CE
5461 if (system_state == SYSTEM_BOOTING) {
5462 printk("migration_cost=");
5463 for (distance = 0; distance <= max_distance; distance++) {
5464 if (distance)
5465 printk(",");
5466 printk("%ld", (long)migration_cost[distance] / 1000);
5467 }
5468 printk("\n");
198e2f18 5469 }
198e2f18 5470 j1 = jiffies;
5471 if (migration_debug)
5472 printk("migration: %ld seconds\n", (j1-j0)/HZ);
5473
5474 /*
5475 * Move back to the original CPU. NUMA-Q gets confused
5476 * if we migrate to another quad during bootup.
5477 */
5478 if (raw_smp_processor_id() != orig_cpu) {
5479 cpumask_t mask = cpumask_of_cpu(orig_cpu),
5480 saved_mask = current->cpus_allowed;
5481
5482 set_cpus_allowed(current, mask);
5483 set_cpus_allowed(current, saved_mask);
5484 }
5485}
5486
9c1cfda2 5487#ifdef CONFIG_NUMA
198e2f18 5488
9c1cfda2
JH
5489/**
5490 * find_next_best_node - find the next node to include in a sched_domain
5491 * @node: node whose sched_domain we're building
5492 * @used_nodes: nodes already in the sched_domain
5493 *
5494 * Find the next node to include in a given scheduling domain. Simply
5495 * finds the closest node not already in the @used_nodes map.
5496 *
5497 * Should use nodemask_t.
5498 */
5499static int find_next_best_node(int node, unsigned long *used_nodes)
5500{
5501 int i, n, val, min_val, best_node = 0;
5502
5503 min_val = INT_MAX;
5504
5505 for (i = 0; i < MAX_NUMNODES; i++) {
5506 /* Start at @node */
5507 n = (node + i) % MAX_NUMNODES;
5508
5509 if (!nr_cpus_node(n))
5510 continue;
5511
5512 /* Skip already used nodes */
5513 if (test_bit(n, used_nodes))
5514 continue;
5515
5516 /* Simple min distance search */
5517 val = node_distance(node, n);
5518
5519 if (val < min_val) {
5520 min_val = val;
5521 best_node = n;
5522 }
5523 }
5524
5525 set_bit(best_node, used_nodes);
5526 return best_node;
5527}
5528
5529/**
5530 * sched_domain_node_span - get a cpumask for a node's sched_domain
5531 * @node: node whose cpumask we're constructing
5532 * @size: number of nodes to include in this span
5533 *
5534 * Given a node, construct a good cpumask for its sched_domain to span. It
5535 * should be one that prevents unnecessary balancing, but also spreads tasks
5536 * out optimally.
5537 */
5538static cpumask_t sched_domain_node_span(int node)
5539{
5540 int i;
5541 cpumask_t span, nodemask;
5542 DECLARE_BITMAP(used_nodes, MAX_NUMNODES);
5543
5544 cpus_clear(span);
5545 bitmap_zero(used_nodes, MAX_NUMNODES);
5546
5547 nodemask = node_to_cpumask(node);
5548 cpus_or(span, span, nodemask);
5549 set_bit(node, used_nodes);
5550
5551 for (i = 1; i < SD_NODES_PER_DOMAIN; i++) {
5552 int next_node = find_next_best_node(node, used_nodes);
5553 nodemask = node_to_cpumask(next_node);
5554 cpus_or(span, span, nodemask);
5555 }
5556
5557 return span;
5558}
5559#endif
5560
5561/*
5562 * At the moment, CONFIG_SCHED_SMT is never defined, but leave it in so we
5563 * can switch it on easily if needed.
5564 */
1da177e4
LT
5565#ifdef CONFIG_SCHED_SMT
5566static DEFINE_PER_CPU(struct sched_domain, cpu_domains);
5567static struct sched_group sched_group_cpus[NR_CPUS];
1a20ff27 5568static int cpu_to_cpu_group(int cpu)
1da177e4
LT
5569{
5570 return cpu;
5571}
5572#endif
5573
5574static DEFINE_PER_CPU(struct sched_domain, phys_domains);
5575static struct sched_group sched_group_phys[NR_CPUS];
1a20ff27 5576static int cpu_to_phys_group(int cpu)
1da177e4
LT
5577{
5578#ifdef CONFIG_SCHED_SMT
5579 return first_cpu(cpu_sibling_map[cpu]);
5580#else
5581 return cpu;
5582#endif
5583}
5584
5585#ifdef CONFIG_NUMA
1da177e4 5586/*
9c1cfda2
JH
5587 * The init_sched_build_groups can't handle what we want to do with node
5588 * groups, so roll our own. Now each node has its own list of groups which
5589 * gets dynamically allocated.
1da177e4 5590 */
9c1cfda2 5591static DEFINE_PER_CPU(struct sched_domain, node_domains);
d1b55138 5592static struct sched_group **sched_group_nodes_bycpu[NR_CPUS];
1da177e4 5593
9c1cfda2 5594static DEFINE_PER_CPU(struct sched_domain, allnodes_domains);
d1b55138 5595static struct sched_group *sched_group_allnodes_bycpu[NR_CPUS];
9c1cfda2
JH
5596
5597static int cpu_to_allnodes_group(int cpu)
5598{
5599 return cpu_to_node(cpu);
1da177e4
LT
5600}
5601#endif
5602
5603/*
1a20ff27
DG
5604 * Build sched domains for a given set of cpus and attach the sched domains
5605 * to the individual cpus
1da177e4 5606 */
9c1cfda2 5607void build_sched_domains(const cpumask_t *cpu_map)
1da177e4
LT
5608{
5609 int i;
d1b55138
JH
5610#ifdef CONFIG_NUMA
5611 struct sched_group **sched_group_nodes = NULL;
5612 struct sched_group *sched_group_allnodes = NULL;
5613
5614 /*
5615 * Allocate the per-node list of sched groups
5616 */
5617 sched_group_nodes = kmalloc(sizeof(struct sched_group*)*MAX_NUMNODES,
5618 GFP_ATOMIC);
5619 if (!sched_group_nodes) {
5620 printk(KERN_WARNING "Can not alloc sched group node list\n");
5621 return;
5622 }
5623 sched_group_nodes_bycpu[first_cpu(*cpu_map)] = sched_group_nodes;
5624#endif
1da177e4
LT
5625
5626 /*
1a20ff27 5627 * Set up domains for cpus specified by the cpu_map.
1da177e4 5628 */
1a20ff27 5629 for_each_cpu_mask(i, *cpu_map) {
1da177e4
LT
5630 int group;
5631 struct sched_domain *sd = NULL, *p;
5632 cpumask_t nodemask = node_to_cpumask(cpu_to_node(i));
5633
1a20ff27 5634 cpus_and(nodemask, nodemask, *cpu_map);
1da177e4
LT
5635
5636#ifdef CONFIG_NUMA
d1b55138 5637 if (cpus_weight(*cpu_map)
9c1cfda2 5638 > SD_NODES_PER_DOMAIN*cpus_weight(nodemask)) {
d1b55138
JH
5639 if (!sched_group_allnodes) {
5640 sched_group_allnodes
5641 = kmalloc(sizeof(struct sched_group)
5642 * MAX_NUMNODES,
5643 GFP_KERNEL);
5644 if (!sched_group_allnodes) {
5645 printk(KERN_WARNING
5646 "Can not alloc allnodes sched group\n");
5647 break;
5648 }
5649 sched_group_allnodes_bycpu[i]
5650 = sched_group_allnodes;
5651 }
9c1cfda2
JH
5652 sd = &per_cpu(allnodes_domains, i);
5653 *sd = SD_ALLNODES_INIT;
5654 sd->span = *cpu_map;
5655 group = cpu_to_allnodes_group(i);
5656 sd->groups = &sched_group_allnodes[group];
5657 p = sd;
5658 } else
5659 p = NULL;
5660
1da177e4 5661 sd = &per_cpu(node_domains, i);
1da177e4 5662 *sd = SD_NODE_INIT;
9c1cfda2
JH
5663 sd->span = sched_domain_node_span(cpu_to_node(i));
5664 sd->parent = p;
5665 cpus_and(sd->span, sd->span, *cpu_map);
1da177e4
LT
5666#endif
5667
5668 p = sd;
5669 sd = &per_cpu(phys_domains, i);
5670 group = cpu_to_phys_group(i);
5671 *sd = SD_CPU_INIT;
5672 sd->span = nodemask;
5673 sd->parent = p;
5674 sd->groups = &sched_group_phys[group];
5675
5676#ifdef CONFIG_SCHED_SMT
5677 p = sd;
5678 sd = &per_cpu(cpu_domains, i);
5679 group = cpu_to_cpu_group(i);
5680 *sd = SD_SIBLING_INIT;
5681 sd->span = cpu_sibling_map[i];
1a20ff27 5682 cpus_and(sd->span, sd->span, *cpu_map);
1da177e4
LT
5683 sd->parent = p;
5684 sd->groups = &sched_group_cpus[group];
5685#endif
5686 }
5687
5688#ifdef CONFIG_SCHED_SMT
5689 /* Set up CPU (sibling) groups */
9c1cfda2 5690 for_each_cpu_mask(i, *cpu_map) {
1da177e4 5691 cpumask_t this_sibling_map = cpu_sibling_map[i];
1a20ff27 5692 cpus_and(this_sibling_map, this_sibling_map, *cpu_map);
1da177e4
LT
5693 if (i != first_cpu(this_sibling_map))
5694 continue;
5695
5696 init_sched_build_groups(sched_group_cpus, this_sibling_map,
5697 &cpu_to_cpu_group);
5698 }
5699#endif
5700
5701 /* Set up physical groups */
5702 for (i = 0; i < MAX_NUMNODES; i++) {
5703 cpumask_t nodemask = node_to_cpumask(i);
5704
1a20ff27 5705 cpus_and(nodemask, nodemask, *cpu_map);
1da177e4
LT
5706 if (cpus_empty(nodemask))
5707 continue;
5708
5709 init_sched_build_groups(sched_group_phys, nodemask,
5710 &cpu_to_phys_group);
5711 }
5712
5713#ifdef CONFIG_NUMA
5714 /* Set up node groups */
d1b55138
JH
5715 if (sched_group_allnodes)
5716 init_sched_build_groups(sched_group_allnodes, *cpu_map,
5717 &cpu_to_allnodes_group);
9c1cfda2
JH
5718
5719 for (i = 0; i < MAX_NUMNODES; i++) {
5720 /* Set up node groups */
5721 struct sched_group *sg, *prev;
5722 cpumask_t nodemask = node_to_cpumask(i);
5723 cpumask_t domainspan;
5724 cpumask_t covered = CPU_MASK_NONE;
5725 int j;
5726
5727 cpus_and(nodemask, nodemask, *cpu_map);
d1b55138
JH
5728 if (cpus_empty(nodemask)) {
5729 sched_group_nodes[i] = NULL;
9c1cfda2 5730 continue;
d1b55138 5731 }
9c1cfda2
JH
5732
5733 domainspan = sched_domain_node_span(i);
5734 cpus_and(domainspan, domainspan, *cpu_map);
5735
5736 sg = kmalloc(sizeof(struct sched_group), GFP_KERNEL);
5737 sched_group_nodes[i] = sg;
5738 for_each_cpu_mask(j, nodemask) {
5739 struct sched_domain *sd;
5740 sd = &per_cpu(node_domains, j);
5741 sd->groups = sg;
5742 if (sd->groups == NULL) {
5743 /* Turn off balancing if we have no groups */
5744 sd->flags = 0;
5745 }
5746 }
5747 if (!sg) {
5748 printk(KERN_WARNING
5749 "Can not alloc domain group for node %d\n", i);
5750 continue;
5751 }
5752 sg->cpu_power = 0;
5753 sg->cpumask = nodemask;
5754 cpus_or(covered, covered, nodemask);
5755 prev = sg;
5756
5757 for (j = 0; j < MAX_NUMNODES; j++) {
5758 cpumask_t tmp, notcovered;
5759 int n = (i + j) % MAX_NUMNODES;
5760
5761 cpus_complement(notcovered, covered);
5762 cpus_and(tmp, notcovered, *cpu_map);
5763 cpus_and(tmp, tmp, domainspan);
5764 if (cpus_empty(tmp))
5765 break;
5766
5767 nodemask = node_to_cpumask(n);
5768 cpus_and(tmp, tmp, nodemask);
5769 if (cpus_empty(tmp))
5770 continue;
5771
5772 sg = kmalloc(sizeof(struct sched_group), GFP_KERNEL);
5773 if (!sg) {
5774 printk(KERN_WARNING
5775 "Can not alloc domain group for node %d\n", j);
5776 break;
5777 }
5778 sg->cpu_power = 0;
5779 sg->cpumask = tmp;
5780 cpus_or(covered, covered, tmp);
5781 prev->next = sg;
5782 prev = sg;
5783 }
5784 prev->next = sched_group_nodes[i];
5785 }
1da177e4
LT
5786#endif
5787
5788 /* Calculate CPU power for physical packages and nodes */
1a20ff27 5789 for_each_cpu_mask(i, *cpu_map) {
1da177e4
LT
5790 int power;
5791 struct sched_domain *sd;
5792#ifdef CONFIG_SCHED_SMT
5793 sd = &per_cpu(cpu_domains, i);
5794 power = SCHED_LOAD_SCALE;
5795 sd->groups->cpu_power = power;
5796#endif
5797
5798 sd = &per_cpu(phys_domains, i);
5799 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
5800 (cpus_weight(sd->groups->cpumask)-1) / 10;
5801 sd->groups->cpu_power = power;
5802
5803#ifdef CONFIG_NUMA
9c1cfda2
JH
5804 sd = &per_cpu(allnodes_domains, i);
5805 if (sd->groups) {
5806 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
5807 (cpus_weight(sd->groups->cpumask)-1) / 10;
5808 sd->groups->cpu_power = power;
1da177e4
LT
5809 }
5810#endif
5811 }
5812
9c1cfda2
JH
5813#ifdef CONFIG_NUMA
5814 for (i = 0; i < MAX_NUMNODES; i++) {
5815 struct sched_group *sg = sched_group_nodes[i];
5816 int j;
5817
5818 if (sg == NULL)
5819 continue;
5820next_sg:
5821 for_each_cpu_mask(j, sg->cpumask) {
5822 struct sched_domain *sd;
5823 int power;
5824
5825 sd = &per_cpu(phys_domains, j);
5826 if (j != first_cpu(sd->groups->cpumask)) {
5827 /*
5828 * Only add "power" once for each
5829 * physical package.
5830 */
5831 continue;
5832 }
5833 power = SCHED_LOAD_SCALE + SCHED_LOAD_SCALE *
5834 (cpus_weight(sd->groups->cpumask)-1) / 10;
5835
5836 sg->cpu_power += power;
5837 }
5838 sg = sg->next;
5839 if (sg != sched_group_nodes[i])
5840 goto next_sg;
5841 }
5842#endif
5843
1da177e4 5844 /* Attach the domains */
1a20ff27 5845 for_each_cpu_mask(i, *cpu_map) {
1da177e4
LT
5846 struct sched_domain *sd;
5847#ifdef CONFIG_SCHED_SMT
5848 sd = &per_cpu(cpu_domains, i);
5849#else
5850 sd = &per_cpu(phys_domains, i);
5851#endif
5852 cpu_attach_domain(sd, i);
5853 }
198e2f18 5854 /*
5855 * Tune cache-hot values:
5856 */
5857 calibrate_migration_costs(cpu_map);
1da177e4 5858}
1a20ff27
DG
5859/*
5860 * Set up scheduler domains and groups. Callers must hold the hotplug lock.
5861 */
9c1cfda2 5862static void arch_init_sched_domains(const cpumask_t *cpu_map)
1a20ff27
DG
5863{
5864 cpumask_t cpu_default_map;
1da177e4 5865
1a20ff27
DG
5866 /*
5867 * Setup mask for cpus without special case scheduling requirements.
5868 * For now this just excludes isolated cpus, but could be used to
5869 * exclude other special cases in the future.
5870 */
5871 cpus_andnot(cpu_default_map, *cpu_map, cpu_isolated_map);
5872
5873 build_sched_domains(&cpu_default_map);
5874}
5875
5876static void arch_destroy_sched_domains(const cpumask_t *cpu_map)
1da177e4 5877{
9c1cfda2
JH
5878#ifdef CONFIG_NUMA
5879 int i;
d1b55138 5880 int cpu;
1da177e4 5881
d1b55138
JH
5882 for_each_cpu_mask(cpu, *cpu_map) {
5883 struct sched_group *sched_group_allnodes
5884 = sched_group_allnodes_bycpu[cpu];
5885 struct sched_group **sched_group_nodes
5886 = sched_group_nodes_bycpu[cpu];
9c1cfda2 5887
d1b55138
JH
5888 if (sched_group_allnodes) {
5889 kfree(sched_group_allnodes);
5890 sched_group_allnodes_bycpu[cpu] = NULL;
5891 }
5892
5893 if (!sched_group_nodes)
9c1cfda2 5894 continue;
d1b55138
JH
5895
5896 for (i = 0; i < MAX_NUMNODES; i++) {
5897 cpumask_t nodemask = node_to_cpumask(i);
5898 struct sched_group *oldsg, *sg = sched_group_nodes[i];
5899
5900 cpus_and(nodemask, nodemask, *cpu_map);
5901 if (cpus_empty(nodemask))
5902 continue;
5903
5904 if (sg == NULL)
5905 continue;
5906 sg = sg->next;
9c1cfda2 5907next_sg:
d1b55138
JH
5908 oldsg = sg;
5909 sg = sg->next;
5910 kfree(oldsg);
5911 if (oldsg != sched_group_nodes[i])
5912 goto next_sg;
5913 }
5914 kfree(sched_group_nodes);
5915 sched_group_nodes_bycpu[cpu] = NULL;
9c1cfda2
JH
5916 }
5917#endif
5918}
1da177e4 5919
1a20ff27
DG
5920/*
5921 * Detach sched domains from a group of cpus specified in cpu_map
5922 * These cpus will now be attached to the NULL domain
5923 */
858119e1 5924static void detach_destroy_domains(const cpumask_t *cpu_map)
1a20ff27
DG
5925{
5926 int i;
5927
5928 for_each_cpu_mask(i, *cpu_map)
5929 cpu_attach_domain(NULL, i);
5930 synchronize_sched();
5931 arch_destroy_sched_domains(cpu_map);
5932}
5933
5934/*
5935 * Partition sched domains as specified by the cpumasks below.
5936 * This attaches all cpus from the cpumasks to the NULL domain,
5937 * waits for a RCU quiescent period, recalculates sched
5938 * domain information and then attaches them back to the
5939 * correct sched domains
5940 * Call with hotplug lock held
5941 */
5942void partition_sched_domains(cpumask_t *partition1, cpumask_t *partition2)
5943{
5944 cpumask_t change_map;
5945
5946 cpus_and(*partition1, *partition1, cpu_online_map);
5947 cpus_and(*partition2, *partition2, cpu_online_map);
5948 cpus_or(change_map, *partition1, *partition2);
5949
5950 /* Detach sched domains from all of the affected cpus */
5951 detach_destroy_domains(&change_map);
5952 if (!cpus_empty(*partition1))
5953 build_sched_domains(partition1);
5954 if (!cpus_empty(*partition2))
5955 build_sched_domains(partition2);
5956}
5957
1da177e4
LT
5958#ifdef CONFIG_HOTPLUG_CPU
5959/*
5960 * Force a reinitialization of the sched domains hierarchy. The domains
5961 * and groups cannot be updated in place without racing with the balancing
41c7ce9a 5962 * code, so we temporarily attach all running cpus to the NULL domain
1da177e4
LT
5963 * which will prevent rebalancing while the sched domains are recalculated.
5964 */
5965static int update_sched_domains(struct notifier_block *nfb,
5966 unsigned long action, void *hcpu)
5967{
1da177e4
LT
5968 switch (action) {
5969 case CPU_UP_PREPARE:
5970 case CPU_DOWN_PREPARE:
1a20ff27 5971 detach_destroy_domains(&cpu_online_map);
1da177e4
LT
5972 return NOTIFY_OK;
5973
5974 case CPU_UP_CANCELED:
5975 case CPU_DOWN_FAILED:
5976 case CPU_ONLINE:
5977 case CPU_DEAD:
5978 /*
5979 * Fall through and re-initialise the domains.
5980 */
5981 break;
5982 default:
5983 return NOTIFY_DONE;
5984 }
5985
5986 /* The hotplug lock is already held by cpu_up/cpu_down */
1a20ff27 5987 arch_init_sched_domains(&cpu_online_map);
1da177e4
LT
5988
5989 return NOTIFY_OK;
5990}
5991#endif
5992
5993void __init sched_init_smp(void)
5994{
5995 lock_cpu_hotplug();
1a20ff27 5996 arch_init_sched_domains(&cpu_online_map);
1da177e4
LT
5997 unlock_cpu_hotplug();
5998 /* XXX: Theoretical race here - CPU may be hotplugged now */
5999 hotcpu_notifier(update_sched_domains, 0);
6000}
6001#else
6002void __init sched_init_smp(void)
6003{
6004}
6005#endif /* CONFIG_SMP */
6006
6007int in_sched_functions(unsigned long addr)
6008{
6009 /* Linker adds these: start and end of __sched functions */
6010 extern char __sched_text_start[], __sched_text_end[];
6011 return in_lock_functions(addr) ||
6012 (addr >= (unsigned long)__sched_text_start
6013 && addr < (unsigned long)__sched_text_end);
6014}
6015
6016void __init sched_init(void)
6017{
6018 runqueue_t *rq;
6019 int i, j, k;
6020
88a2a4ac 6021 for_each_cpu(i) {
1da177e4
LT
6022 prio_array_t *array;
6023
6024 rq = cpu_rq(i);
6025 spin_lock_init(&rq->lock);
7897986b 6026 rq->nr_running = 0;
1da177e4
LT
6027 rq->active = rq->arrays;
6028 rq->expired = rq->arrays + 1;
6029 rq->best_expired_prio = MAX_PRIO;
6030
6031#ifdef CONFIG_SMP
41c7ce9a 6032 rq->sd = NULL;
7897986b
NP
6033 for (j = 1; j < 3; j++)
6034 rq->cpu_load[j] = 0;
1da177e4
LT
6035 rq->active_balance = 0;
6036 rq->push_cpu = 0;
6037 rq->migration_thread = NULL;
6038 INIT_LIST_HEAD(&rq->migration_queue);
6039#endif
6040 atomic_set(&rq->nr_iowait, 0);
6041
6042 for (j = 0; j < 2; j++) {
6043 array = rq->arrays + j;
6044 for (k = 0; k < MAX_PRIO; k++) {
6045 INIT_LIST_HEAD(array->queue + k);
6046 __clear_bit(k, array->bitmap);
6047 }
6048 // delimiter for bitsearch
6049 __set_bit(MAX_PRIO, array->bitmap);
6050 }
6051 }
6052
6053 /*
6054 * The boot idle thread does lazy MMU switching as well:
6055 */
6056 atomic_inc(&init_mm.mm_count);
6057 enter_lazy_tlb(&init_mm, current);
6058
6059 /*
6060 * Make us the idle thread. Technically, schedule() should not be
6061 * called from this thread, however somewhere below it might be,
6062 * but because we are the idle thread, we just pick up running again
6063 * when this runqueue becomes "idle".
6064 */
6065 init_idle(current, smp_processor_id());
6066}
6067
6068#ifdef CONFIG_DEBUG_SPINLOCK_SLEEP
6069void __might_sleep(char *file, int line)
6070{
6071#if defined(in_atomic)
6072 static unsigned long prev_jiffy; /* ratelimiting */
6073
6074 if ((in_atomic() || irqs_disabled()) &&
6075 system_state == SYSTEM_RUNNING && !oops_in_progress) {
6076 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6077 return;
6078 prev_jiffy = jiffies;
6079 printk(KERN_ERR "Debug: sleeping function called from invalid"
6080 " context at %s:%d\n", file, line);
6081 printk("in_atomic():%d, irqs_disabled():%d\n",
6082 in_atomic(), irqs_disabled());
6083 dump_stack();
6084 }
6085#endif
6086}
6087EXPORT_SYMBOL(__might_sleep);
6088#endif
6089
6090#ifdef CONFIG_MAGIC_SYSRQ
6091void normalize_rt_tasks(void)
6092{
6093 struct task_struct *p;
6094 prio_array_t *array;
6095 unsigned long flags;
6096 runqueue_t *rq;
6097
6098 read_lock_irq(&tasklist_lock);
6099 for_each_process (p) {
6100 if (!rt_task(p))
6101 continue;
6102
6103 rq = task_rq_lock(p, &flags);
6104
6105 array = p->array;
6106 if (array)
6107 deactivate_task(p, task_rq(p));
6108 __setscheduler(p, SCHED_NORMAL, 0);
6109 if (array) {
6110 __activate_task(p, task_rq(p));
6111 resched_task(rq->curr);
6112 }
6113
6114 task_rq_unlock(rq, &flags);
6115 }
6116 read_unlock_irq(&tasklist_lock);
6117}
6118
6119#endif /* CONFIG_MAGIC_SYSRQ */
1df5c10a
LT
6120
6121#ifdef CONFIG_IA64
6122/*
6123 * These functions are only useful for the IA64 MCA handling.
6124 *
6125 * They can only be called when the whole system has been
6126 * stopped - every CPU needs to be quiescent, and no scheduling
6127 * activity can take place. Using them for anything else would
6128 * be a serious bug, and as a result, they aren't even visible
6129 * under any other configuration.
6130 */
6131
6132/**
6133 * curr_task - return the current task for a given cpu.
6134 * @cpu: the processor in question.
6135 *
6136 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6137 */
6138task_t *curr_task(int cpu)
6139{
6140 return cpu_curr(cpu);
6141}
6142
6143/**
6144 * set_curr_task - set the current task for a given cpu.
6145 * @cpu: the processor in question.
6146 * @p: the task pointer to set.
6147 *
6148 * Description: This function must only be used when non-maskable interrupts
6149 * are serviced on a separate stack. It allows the architecture to switch the
6150 * notion of the current task on a cpu in a non-blocking manner. This function
6151 * must be called with all CPU's synchronized, and interrupts disabled, the
6152 * and caller must save the original value of the current task (see
6153 * curr_task() above) and restore that value before reenabling interrupts and
6154 * re-starting the system.
6155 *
6156 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6157 */
6158void set_curr_task(int cpu, task_t *p)
6159{
6160 cpu_curr(cpu) = p;
6161}
6162
6163#endif
This page took 0.481132 seconds and 5 git commands to generate.