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