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