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