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