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