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