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