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