xref: /openbmc/linux/kernel/sched/core.c (revision f79e4d5f92a129a1159c973735007d4ddc8541f3)
1 /*
2  *  kernel/sched/core.c
3  *
4  *  Core kernel scheduler code and related syscalls
5  *
6  *  Copyright (C) 1991-2002  Linus Torvalds
7  */
8 #include "sched.h"
9 
10 #include <linux/nospec.h>
11 
12 #include <linux/kcov.h>
13 
14 #include <asm/switch_to.h>
15 #include <asm/tlb.h>
16 
17 #include "../workqueue_internal.h"
18 #include "../smpboot.h"
19 
20 #define CREATE_TRACE_POINTS
21 #include <trace/events/sched.h>
22 
23 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
24 
25 #if defined(CONFIG_SCHED_DEBUG) && defined(HAVE_JUMP_LABEL)
26 /*
27  * Debugging: various feature bits
28  *
29  * If SCHED_DEBUG is disabled, each compilation unit has its own copy of
30  * sysctl_sched_features, defined in sched.h, to allow constants propagation
31  * at compile time and compiler optimization based on features default.
32  */
33 #define SCHED_FEAT(name, enabled)	\
34 	(1UL << __SCHED_FEAT_##name) * enabled |
35 const_debug unsigned int sysctl_sched_features =
36 #include "features.h"
37 	0;
38 #undef SCHED_FEAT
39 #endif
40 
41 /*
42  * Number of tasks to iterate in a single balance run.
43  * Limited because this is done with IRQs disabled.
44  */
45 const_debug unsigned int sysctl_sched_nr_migrate = 32;
46 
47 /*
48  * period over which we average the RT time consumption, measured
49  * in ms.
50  *
51  * default: 1s
52  */
53 const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC;
54 
55 /*
56  * period over which we measure -rt task CPU usage in us.
57  * default: 1s
58  */
59 unsigned int sysctl_sched_rt_period = 1000000;
60 
61 __read_mostly int scheduler_running;
62 
63 /*
64  * part of the period that we allow rt tasks to run in us.
65  * default: 0.95s
66  */
67 int sysctl_sched_rt_runtime = 950000;
68 
69 /*
70  * __task_rq_lock - lock the rq @p resides on.
71  */
72 struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
73 	__acquires(rq->lock)
74 {
75 	struct rq *rq;
76 
77 	lockdep_assert_held(&p->pi_lock);
78 
79 	for (;;) {
80 		rq = task_rq(p);
81 		raw_spin_lock(&rq->lock);
82 		if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
83 			rq_pin_lock(rq, rf);
84 			return rq;
85 		}
86 		raw_spin_unlock(&rq->lock);
87 
88 		while (unlikely(task_on_rq_migrating(p)))
89 			cpu_relax();
90 	}
91 }
92 
93 /*
94  * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
95  */
96 struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
97 	__acquires(p->pi_lock)
98 	__acquires(rq->lock)
99 {
100 	struct rq *rq;
101 
102 	for (;;) {
103 		raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
104 		rq = task_rq(p);
105 		raw_spin_lock(&rq->lock);
106 		/*
107 		 *	move_queued_task()		task_rq_lock()
108 		 *
109 		 *	ACQUIRE (rq->lock)
110 		 *	[S] ->on_rq = MIGRATING		[L] rq = task_rq()
111 		 *	WMB (__set_task_cpu())		ACQUIRE (rq->lock);
112 		 *	[S] ->cpu = new_cpu		[L] task_rq()
113 		 *					[L] ->on_rq
114 		 *	RELEASE (rq->lock)
115 		 *
116 		 * If we observe the old CPU in task_rq_lock, the acquire of
117 		 * the old rq->lock will fully serialize against the stores.
118 		 *
119 		 * If we observe the new CPU in task_rq_lock, the acquire will
120 		 * pair with the WMB to ensure we must then also see migrating.
121 		 */
122 		if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
123 			rq_pin_lock(rq, rf);
124 			return rq;
125 		}
126 		raw_spin_unlock(&rq->lock);
127 		raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
128 
129 		while (unlikely(task_on_rq_migrating(p)))
130 			cpu_relax();
131 	}
132 }
133 
134 /*
135  * RQ-clock updating methods:
136  */
137 
138 static void update_rq_clock_task(struct rq *rq, s64 delta)
139 {
140 /*
141  * In theory, the compile should just see 0 here, and optimize out the call
142  * to sched_rt_avg_update. But I don't trust it...
143  */
144 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
145 	s64 steal = 0, irq_delta = 0;
146 #endif
147 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
148 	irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
149 
150 	/*
151 	 * Since irq_time is only updated on {soft,}irq_exit, we might run into
152 	 * this case when a previous update_rq_clock() happened inside a
153 	 * {soft,}irq region.
154 	 *
155 	 * When this happens, we stop ->clock_task and only update the
156 	 * prev_irq_time stamp to account for the part that fit, so that a next
157 	 * update will consume the rest. This ensures ->clock_task is
158 	 * monotonic.
159 	 *
160 	 * It does however cause some slight miss-attribution of {soft,}irq
161 	 * time, a more accurate solution would be to update the irq_time using
162 	 * the current rq->clock timestamp, except that would require using
163 	 * atomic ops.
164 	 */
165 	if (irq_delta > delta)
166 		irq_delta = delta;
167 
168 	rq->prev_irq_time += irq_delta;
169 	delta -= irq_delta;
170 #endif
171 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
172 	if (static_key_false((&paravirt_steal_rq_enabled))) {
173 		steal = paravirt_steal_clock(cpu_of(rq));
174 		steal -= rq->prev_steal_time_rq;
175 
176 		if (unlikely(steal > delta))
177 			steal = delta;
178 
179 		rq->prev_steal_time_rq += steal;
180 		delta -= steal;
181 	}
182 #endif
183 
184 	rq->clock_task += delta;
185 
186 #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING)
187 	if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
188 		sched_rt_avg_update(rq, irq_delta + steal);
189 #endif
190 }
191 
192 void update_rq_clock(struct rq *rq)
193 {
194 	s64 delta;
195 
196 	lockdep_assert_held(&rq->lock);
197 
198 	if (rq->clock_update_flags & RQCF_ACT_SKIP)
199 		return;
200 
201 #ifdef CONFIG_SCHED_DEBUG
202 	if (sched_feat(WARN_DOUBLE_CLOCK))
203 		SCHED_WARN_ON(rq->clock_update_flags & RQCF_UPDATED);
204 	rq->clock_update_flags |= RQCF_UPDATED;
205 #endif
206 
207 	delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
208 	if (delta < 0)
209 		return;
210 	rq->clock += delta;
211 	update_rq_clock_task(rq, delta);
212 }
213 
214 
215 #ifdef CONFIG_SCHED_HRTICK
216 /*
217  * Use HR-timers to deliver accurate preemption points.
218  */
219 
220 static void hrtick_clear(struct rq *rq)
221 {
222 	if (hrtimer_active(&rq->hrtick_timer))
223 		hrtimer_cancel(&rq->hrtick_timer);
224 }
225 
226 /*
227  * High-resolution timer tick.
228  * Runs from hardirq context with interrupts disabled.
229  */
230 static enum hrtimer_restart hrtick(struct hrtimer *timer)
231 {
232 	struct rq *rq = container_of(timer, struct rq, hrtick_timer);
233 	struct rq_flags rf;
234 
235 	WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
236 
237 	rq_lock(rq, &rf);
238 	update_rq_clock(rq);
239 	rq->curr->sched_class->task_tick(rq, rq->curr, 1);
240 	rq_unlock(rq, &rf);
241 
242 	return HRTIMER_NORESTART;
243 }
244 
245 #ifdef CONFIG_SMP
246 
247 static void __hrtick_restart(struct rq *rq)
248 {
249 	struct hrtimer *timer = &rq->hrtick_timer;
250 
251 	hrtimer_start_expires(timer, HRTIMER_MODE_ABS_PINNED);
252 }
253 
254 /*
255  * called from hardirq (IPI) context
256  */
257 static void __hrtick_start(void *arg)
258 {
259 	struct rq *rq = arg;
260 	struct rq_flags rf;
261 
262 	rq_lock(rq, &rf);
263 	__hrtick_restart(rq);
264 	rq->hrtick_csd_pending = 0;
265 	rq_unlock(rq, &rf);
266 }
267 
268 /*
269  * Called to set the hrtick timer state.
270  *
271  * called with rq->lock held and irqs disabled
272  */
273 void hrtick_start(struct rq *rq, u64 delay)
274 {
275 	struct hrtimer *timer = &rq->hrtick_timer;
276 	ktime_t time;
277 	s64 delta;
278 
279 	/*
280 	 * Don't schedule slices shorter than 10000ns, that just
281 	 * doesn't make sense and can cause timer DoS.
282 	 */
283 	delta = max_t(s64, delay, 10000LL);
284 	time = ktime_add_ns(timer->base->get_time(), delta);
285 
286 	hrtimer_set_expires(timer, time);
287 
288 	if (rq == this_rq()) {
289 		__hrtick_restart(rq);
290 	} else if (!rq->hrtick_csd_pending) {
291 		smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
292 		rq->hrtick_csd_pending = 1;
293 	}
294 }
295 
296 #else
297 /*
298  * Called to set the hrtick timer state.
299  *
300  * called with rq->lock held and irqs disabled
301  */
302 void hrtick_start(struct rq *rq, u64 delay)
303 {
304 	/*
305 	 * Don't schedule slices shorter than 10000ns, that just
306 	 * doesn't make sense. Rely on vruntime for fairness.
307 	 */
308 	delay = max_t(u64, delay, 10000LL);
309 	hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
310 		      HRTIMER_MODE_REL_PINNED);
311 }
312 #endif /* CONFIG_SMP */
313 
314 static void hrtick_rq_init(struct rq *rq)
315 {
316 #ifdef CONFIG_SMP
317 	rq->hrtick_csd_pending = 0;
318 
319 	rq->hrtick_csd.flags = 0;
320 	rq->hrtick_csd.func = __hrtick_start;
321 	rq->hrtick_csd.info = rq;
322 #endif
323 
324 	hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
325 	rq->hrtick_timer.function = hrtick;
326 }
327 #else	/* CONFIG_SCHED_HRTICK */
328 static inline void hrtick_clear(struct rq *rq)
329 {
330 }
331 
332 static inline void hrtick_rq_init(struct rq *rq)
333 {
334 }
335 #endif	/* CONFIG_SCHED_HRTICK */
336 
337 /*
338  * cmpxchg based fetch_or, macro so it works for different integer types
339  */
340 #define fetch_or(ptr, mask)						\
341 	({								\
342 		typeof(ptr) _ptr = (ptr);				\
343 		typeof(mask) _mask = (mask);				\
344 		typeof(*_ptr) _old, _val = *_ptr;			\
345 									\
346 		for (;;) {						\
347 			_old = cmpxchg(_ptr, _val, _val | _mask);	\
348 			if (_old == _val)				\
349 				break;					\
350 			_val = _old;					\
351 		}							\
352 	_old;								\
353 })
354 
355 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
356 /*
357  * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
358  * this avoids any races wrt polling state changes and thereby avoids
359  * spurious IPIs.
360  */
361 static bool set_nr_and_not_polling(struct task_struct *p)
362 {
363 	struct thread_info *ti = task_thread_info(p);
364 	return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
365 }
366 
367 /*
368  * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
369  *
370  * If this returns true, then the idle task promises to call
371  * sched_ttwu_pending() and reschedule soon.
372  */
373 static bool set_nr_if_polling(struct task_struct *p)
374 {
375 	struct thread_info *ti = task_thread_info(p);
376 	typeof(ti->flags) old, val = READ_ONCE(ti->flags);
377 
378 	for (;;) {
379 		if (!(val & _TIF_POLLING_NRFLAG))
380 			return false;
381 		if (val & _TIF_NEED_RESCHED)
382 			return true;
383 		old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
384 		if (old == val)
385 			break;
386 		val = old;
387 	}
388 	return true;
389 }
390 
391 #else
392 static bool set_nr_and_not_polling(struct task_struct *p)
393 {
394 	set_tsk_need_resched(p);
395 	return true;
396 }
397 
398 #ifdef CONFIG_SMP
399 static bool set_nr_if_polling(struct task_struct *p)
400 {
401 	return false;
402 }
403 #endif
404 #endif
405 
406 void wake_q_add(struct wake_q_head *head, struct task_struct *task)
407 {
408 	struct wake_q_node *node = &task->wake_q;
409 
410 	/*
411 	 * Atomically grab the task, if ->wake_q is !nil already it means
412 	 * its already queued (either by us or someone else) and will get the
413 	 * wakeup due to that.
414 	 *
415 	 * This cmpxchg() implies a full barrier, which pairs with the write
416 	 * barrier implied by the wakeup in wake_up_q().
417 	 */
418 	if (cmpxchg(&node->next, NULL, WAKE_Q_TAIL))
419 		return;
420 
421 	get_task_struct(task);
422 
423 	/*
424 	 * The head is context local, there can be no concurrency.
425 	 */
426 	*head->lastp = node;
427 	head->lastp = &node->next;
428 }
429 
430 void wake_up_q(struct wake_q_head *head)
431 {
432 	struct wake_q_node *node = head->first;
433 
434 	while (node != WAKE_Q_TAIL) {
435 		struct task_struct *task;
436 
437 		task = container_of(node, struct task_struct, wake_q);
438 		BUG_ON(!task);
439 		/* Task can safely be re-inserted now: */
440 		node = node->next;
441 		task->wake_q.next = NULL;
442 
443 		/*
444 		 * wake_up_process() implies a wmb() to pair with the queueing
445 		 * in wake_q_add() so as not to miss wakeups.
446 		 */
447 		wake_up_process(task);
448 		put_task_struct(task);
449 	}
450 }
451 
452 /*
453  * resched_curr - mark rq's current task 'to be rescheduled now'.
454  *
455  * On UP this means the setting of the need_resched flag, on SMP it
456  * might also involve a cross-CPU call to trigger the scheduler on
457  * the target CPU.
458  */
459 void resched_curr(struct rq *rq)
460 {
461 	struct task_struct *curr = rq->curr;
462 	int cpu;
463 
464 	lockdep_assert_held(&rq->lock);
465 
466 	if (test_tsk_need_resched(curr))
467 		return;
468 
469 	cpu = cpu_of(rq);
470 
471 	if (cpu == smp_processor_id()) {
472 		set_tsk_need_resched(curr);
473 		set_preempt_need_resched();
474 		return;
475 	}
476 
477 	if (set_nr_and_not_polling(curr))
478 		smp_send_reschedule(cpu);
479 	else
480 		trace_sched_wake_idle_without_ipi(cpu);
481 }
482 
483 void resched_cpu(int cpu)
484 {
485 	struct rq *rq = cpu_rq(cpu);
486 	unsigned long flags;
487 
488 	raw_spin_lock_irqsave(&rq->lock, flags);
489 	if (cpu_online(cpu) || cpu == smp_processor_id())
490 		resched_curr(rq);
491 	raw_spin_unlock_irqrestore(&rq->lock, flags);
492 }
493 
494 #ifdef CONFIG_SMP
495 #ifdef CONFIG_NO_HZ_COMMON
496 /*
497  * In the semi idle case, use the nearest busy CPU for migrating timers
498  * from an idle CPU.  This is good for power-savings.
499  *
500  * We don't do similar optimization for completely idle system, as
501  * selecting an idle CPU will add more delays to the timers than intended
502  * (as that CPU's timer base may not be uptodate wrt jiffies etc).
503  */
504 int get_nohz_timer_target(void)
505 {
506 	int i, cpu = smp_processor_id();
507 	struct sched_domain *sd;
508 
509 	if (!idle_cpu(cpu) && housekeeping_cpu(cpu, HK_FLAG_TIMER))
510 		return cpu;
511 
512 	rcu_read_lock();
513 	for_each_domain(cpu, sd) {
514 		for_each_cpu(i, sched_domain_span(sd)) {
515 			if (cpu == i)
516 				continue;
517 
518 			if (!idle_cpu(i) && housekeeping_cpu(i, HK_FLAG_TIMER)) {
519 				cpu = i;
520 				goto unlock;
521 			}
522 		}
523 	}
524 
525 	if (!housekeeping_cpu(cpu, HK_FLAG_TIMER))
526 		cpu = housekeeping_any_cpu(HK_FLAG_TIMER);
527 unlock:
528 	rcu_read_unlock();
529 	return cpu;
530 }
531 
532 /*
533  * When add_timer_on() enqueues a timer into the timer wheel of an
534  * idle CPU then this timer might expire before the next timer event
535  * which is scheduled to wake up that CPU. In case of a completely
536  * idle system the next event might even be infinite time into the
537  * future. wake_up_idle_cpu() ensures that the CPU is woken up and
538  * leaves the inner idle loop so the newly added timer is taken into
539  * account when the CPU goes back to idle and evaluates the timer
540  * wheel for the next timer event.
541  */
542 static void wake_up_idle_cpu(int cpu)
543 {
544 	struct rq *rq = cpu_rq(cpu);
545 
546 	if (cpu == smp_processor_id())
547 		return;
548 
549 	if (set_nr_and_not_polling(rq->idle))
550 		smp_send_reschedule(cpu);
551 	else
552 		trace_sched_wake_idle_without_ipi(cpu);
553 }
554 
555 static bool wake_up_full_nohz_cpu(int cpu)
556 {
557 	/*
558 	 * We just need the target to call irq_exit() and re-evaluate
559 	 * the next tick. The nohz full kick at least implies that.
560 	 * If needed we can still optimize that later with an
561 	 * empty IRQ.
562 	 */
563 	if (cpu_is_offline(cpu))
564 		return true;  /* Don't try to wake offline CPUs. */
565 	if (tick_nohz_full_cpu(cpu)) {
566 		if (cpu != smp_processor_id() ||
567 		    tick_nohz_tick_stopped())
568 			tick_nohz_full_kick_cpu(cpu);
569 		return true;
570 	}
571 
572 	return false;
573 }
574 
575 /*
576  * Wake up the specified CPU.  If the CPU is going offline, it is the
577  * caller's responsibility to deal with the lost wakeup, for example,
578  * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
579  */
580 void wake_up_nohz_cpu(int cpu)
581 {
582 	if (!wake_up_full_nohz_cpu(cpu))
583 		wake_up_idle_cpu(cpu);
584 }
585 
586 static inline bool got_nohz_idle_kick(void)
587 {
588 	int cpu = smp_processor_id();
589 
590 	if (!(atomic_read(nohz_flags(cpu)) & NOHZ_KICK_MASK))
591 		return false;
592 
593 	if (idle_cpu(cpu) && !need_resched())
594 		return true;
595 
596 	/*
597 	 * We can't run Idle Load Balance on this CPU for this time so we
598 	 * cancel it and clear NOHZ_BALANCE_KICK
599 	 */
600 	atomic_andnot(NOHZ_KICK_MASK, nohz_flags(cpu));
601 	return false;
602 }
603 
604 #else /* CONFIG_NO_HZ_COMMON */
605 
606 static inline bool got_nohz_idle_kick(void)
607 {
608 	return false;
609 }
610 
611 #endif /* CONFIG_NO_HZ_COMMON */
612 
613 #ifdef CONFIG_NO_HZ_FULL
614 bool sched_can_stop_tick(struct rq *rq)
615 {
616 	int fifo_nr_running;
617 
618 	/* Deadline tasks, even if single, need the tick */
619 	if (rq->dl.dl_nr_running)
620 		return false;
621 
622 	/*
623 	 * If there are more than one RR tasks, we need the tick to effect the
624 	 * actual RR behaviour.
625 	 */
626 	if (rq->rt.rr_nr_running) {
627 		if (rq->rt.rr_nr_running == 1)
628 			return true;
629 		else
630 			return false;
631 	}
632 
633 	/*
634 	 * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
635 	 * forced preemption between FIFO tasks.
636 	 */
637 	fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
638 	if (fifo_nr_running)
639 		return true;
640 
641 	/*
642 	 * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
643 	 * if there's more than one we need the tick for involuntary
644 	 * preemption.
645 	 */
646 	if (rq->nr_running > 1)
647 		return false;
648 
649 	return true;
650 }
651 #endif /* CONFIG_NO_HZ_FULL */
652 
653 void sched_avg_update(struct rq *rq)
654 {
655 	s64 period = sched_avg_period();
656 
657 	while ((s64)(rq_clock(rq) - rq->age_stamp) > period) {
658 		/*
659 		 * Inline assembly required to prevent the compiler
660 		 * optimising this loop into a divmod call.
661 		 * See __iter_div_u64_rem() for another example of this.
662 		 */
663 		asm("" : "+rm" (rq->age_stamp));
664 		rq->age_stamp += period;
665 		rq->rt_avg /= 2;
666 	}
667 }
668 
669 #endif /* CONFIG_SMP */
670 
671 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
672 			(defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
673 /*
674  * Iterate task_group tree rooted at *from, calling @down when first entering a
675  * node and @up when leaving it for the final time.
676  *
677  * Caller must hold rcu_lock or sufficient equivalent.
678  */
679 int walk_tg_tree_from(struct task_group *from,
680 			     tg_visitor down, tg_visitor up, void *data)
681 {
682 	struct task_group *parent, *child;
683 	int ret;
684 
685 	parent = from;
686 
687 down:
688 	ret = (*down)(parent, data);
689 	if (ret)
690 		goto out;
691 	list_for_each_entry_rcu(child, &parent->children, siblings) {
692 		parent = child;
693 		goto down;
694 
695 up:
696 		continue;
697 	}
698 	ret = (*up)(parent, data);
699 	if (ret || parent == from)
700 		goto out;
701 
702 	child = parent;
703 	parent = parent->parent;
704 	if (parent)
705 		goto up;
706 out:
707 	return ret;
708 }
709 
710 int tg_nop(struct task_group *tg, void *data)
711 {
712 	return 0;
713 }
714 #endif
715 
716 static void set_load_weight(struct task_struct *p, bool update_load)
717 {
718 	int prio = p->static_prio - MAX_RT_PRIO;
719 	struct load_weight *load = &p->se.load;
720 
721 	/*
722 	 * SCHED_IDLE tasks get minimal weight:
723 	 */
724 	if (idle_policy(p->policy)) {
725 		load->weight = scale_load(WEIGHT_IDLEPRIO);
726 		load->inv_weight = WMULT_IDLEPRIO;
727 		return;
728 	}
729 
730 	/*
731 	 * SCHED_OTHER tasks have to update their load when changing their
732 	 * weight
733 	 */
734 	if (update_load && p->sched_class == &fair_sched_class) {
735 		reweight_task(p, prio);
736 	} else {
737 		load->weight = scale_load(sched_prio_to_weight[prio]);
738 		load->inv_weight = sched_prio_to_wmult[prio];
739 	}
740 }
741 
742 static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
743 {
744 	if (!(flags & ENQUEUE_NOCLOCK))
745 		update_rq_clock(rq);
746 
747 	if (!(flags & ENQUEUE_RESTORE))
748 		sched_info_queued(rq, p);
749 
750 	p->sched_class->enqueue_task(rq, p, flags);
751 }
752 
753 static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
754 {
755 	if (!(flags & DEQUEUE_NOCLOCK))
756 		update_rq_clock(rq);
757 
758 	if (!(flags & DEQUEUE_SAVE))
759 		sched_info_dequeued(rq, p);
760 
761 	p->sched_class->dequeue_task(rq, p, flags);
762 }
763 
764 void activate_task(struct rq *rq, struct task_struct *p, int flags)
765 {
766 	if (task_contributes_to_load(p))
767 		rq->nr_uninterruptible--;
768 
769 	enqueue_task(rq, p, flags);
770 }
771 
772 void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
773 {
774 	if (task_contributes_to_load(p))
775 		rq->nr_uninterruptible++;
776 
777 	dequeue_task(rq, p, flags);
778 }
779 
780 /*
781  * __normal_prio - return the priority that is based on the static prio
782  */
783 static inline int __normal_prio(struct task_struct *p)
784 {
785 	return p->static_prio;
786 }
787 
788 /*
789  * Calculate the expected normal priority: i.e. priority
790  * without taking RT-inheritance into account. Might be
791  * boosted by interactivity modifiers. Changes upon fork,
792  * setprio syscalls, and whenever the interactivity
793  * estimator recalculates.
794  */
795 static inline int normal_prio(struct task_struct *p)
796 {
797 	int prio;
798 
799 	if (task_has_dl_policy(p))
800 		prio = MAX_DL_PRIO-1;
801 	else if (task_has_rt_policy(p))
802 		prio = MAX_RT_PRIO-1 - p->rt_priority;
803 	else
804 		prio = __normal_prio(p);
805 	return prio;
806 }
807 
808 /*
809  * Calculate the current priority, i.e. the priority
810  * taken into account by the scheduler. This value might
811  * be boosted by RT tasks, or might be boosted by
812  * interactivity modifiers. Will be RT if the task got
813  * RT-boosted. If not then it returns p->normal_prio.
814  */
815 static int effective_prio(struct task_struct *p)
816 {
817 	p->normal_prio = normal_prio(p);
818 	/*
819 	 * If we are RT tasks or we were boosted to RT priority,
820 	 * keep the priority unchanged. Otherwise, update priority
821 	 * to the normal priority:
822 	 */
823 	if (!rt_prio(p->prio))
824 		return p->normal_prio;
825 	return p->prio;
826 }
827 
828 /**
829  * task_curr - is this task currently executing on a CPU?
830  * @p: the task in question.
831  *
832  * Return: 1 if the task is currently executing. 0 otherwise.
833  */
834 inline int task_curr(const struct task_struct *p)
835 {
836 	return cpu_curr(task_cpu(p)) == p;
837 }
838 
839 /*
840  * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
841  * use the balance_callback list if you want balancing.
842  *
843  * this means any call to check_class_changed() must be followed by a call to
844  * balance_callback().
845  */
846 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
847 				       const struct sched_class *prev_class,
848 				       int oldprio)
849 {
850 	if (prev_class != p->sched_class) {
851 		if (prev_class->switched_from)
852 			prev_class->switched_from(rq, p);
853 
854 		p->sched_class->switched_to(rq, p);
855 	} else if (oldprio != p->prio || dl_task(p))
856 		p->sched_class->prio_changed(rq, p, oldprio);
857 }
858 
859 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
860 {
861 	const struct sched_class *class;
862 
863 	if (p->sched_class == rq->curr->sched_class) {
864 		rq->curr->sched_class->check_preempt_curr(rq, p, flags);
865 	} else {
866 		for_each_class(class) {
867 			if (class == rq->curr->sched_class)
868 				break;
869 			if (class == p->sched_class) {
870 				resched_curr(rq);
871 				break;
872 			}
873 		}
874 	}
875 
876 	/*
877 	 * A queue event has occurred, and we're going to schedule.  In
878 	 * this case, we can save a useless back to back clock update.
879 	 */
880 	if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
881 		rq_clock_skip_update(rq);
882 }
883 
884 #ifdef CONFIG_SMP
885 
886 static inline bool is_per_cpu_kthread(struct task_struct *p)
887 {
888 	if (!(p->flags & PF_KTHREAD))
889 		return false;
890 
891 	if (p->nr_cpus_allowed != 1)
892 		return false;
893 
894 	return true;
895 }
896 
897 /*
898  * Per-CPU kthreads are allowed to run on !actie && online CPUs, see
899  * __set_cpus_allowed_ptr() and select_fallback_rq().
900  */
901 static inline bool is_cpu_allowed(struct task_struct *p, int cpu)
902 {
903 	if (!cpumask_test_cpu(cpu, &p->cpus_allowed))
904 		return false;
905 
906 	if (is_per_cpu_kthread(p))
907 		return cpu_online(cpu);
908 
909 	return cpu_active(cpu);
910 }
911 
912 /*
913  * This is how migration works:
914  *
915  * 1) we invoke migration_cpu_stop() on the target CPU using
916  *    stop_one_cpu().
917  * 2) stopper starts to run (implicitly forcing the migrated thread
918  *    off the CPU)
919  * 3) it checks whether the migrated task is still in the wrong runqueue.
920  * 4) if it's in the wrong runqueue then the migration thread removes
921  *    it and puts it into the right queue.
922  * 5) stopper completes and stop_one_cpu() returns and the migration
923  *    is done.
924  */
925 
926 /*
927  * move_queued_task - move a queued task to new rq.
928  *
929  * Returns (locked) new rq. Old rq's lock is released.
930  */
931 static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf,
932 				   struct task_struct *p, int new_cpu)
933 {
934 	lockdep_assert_held(&rq->lock);
935 
936 	p->on_rq = TASK_ON_RQ_MIGRATING;
937 	dequeue_task(rq, p, DEQUEUE_NOCLOCK);
938 	set_task_cpu(p, new_cpu);
939 	rq_unlock(rq, rf);
940 
941 	rq = cpu_rq(new_cpu);
942 
943 	rq_lock(rq, rf);
944 	BUG_ON(task_cpu(p) != new_cpu);
945 	enqueue_task(rq, p, 0);
946 	p->on_rq = TASK_ON_RQ_QUEUED;
947 	check_preempt_curr(rq, p, 0);
948 
949 	return rq;
950 }
951 
952 struct migration_arg {
953 	struct task_struct *task;
954 	int dest_cpu;
955 };
956 
957 /*
958  * Move (not current) task off this CPU, onto the destination CPU. We're doing
959  * this because either it can't run here any more (set_cpus_allowed()
960  * away from this CPU, or CPU going down), or because we're
961  * attempting to rebalance this task on exec (sched_exec).
962  *
963  * So we race with normal scheduler movements, but that's OK, as long
964  * as the task is no longer on this CPU.
965  */
966 static struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf,
967 				 struct task_struct *p, int dest_cpu)
968 {
969 	/* Affinity changed (again). */
970 	if (!is_cpu_allowed(p, dest_cpu))
971 		return rq;
972 
973 	update_rq_clock(rq);
974 	rq = move_queued_task(rq, rf, p, dest_cpu);
975 
976 	return rq;
977 }
978 
979 /*
980  * migration_cpu_stop - this will be executed by a highprio stopper thread
981  * and performs thread migration by bumping thread off CPU then
982  * 'pushing' onto another runqueue.
983  */
984 static int migration_cpu_stop(void *data)
985 {
986 	struct migration_arg *arg = data;
987 	struct task_struct *p = arg->task;
988 	struct rq *rq = this_rq();
989 	struct rq_flags rf;
990 
991 	/*
992 	 * The original target CPU might have gone down and we might
993 	 * be on another CPU but it doesn't matter.
994 	 */
995 	local_irq_disable();
996 	/*
997 	 * We need to explicitly wake pending tasks before running
998 	 * __migrate_task() such that we will not miss enforcing cpus_allowed
999 	 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
1000 	 */
1001 	sched_ttwu_pending();
1002 
1003 	raw_spin_lock(&p->pi_lock);
1004 	rq_lock(rq, &rf);
1005 	/*
1006 	 * If task_rq(p) != rq, it cannot be migrated here, because we're
1007 	 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
1008 	 * we're holding p->pi_lock.
1009 	 */
1010 	if (task_rq(p) == rq) {
1011 		if (task_on_rq_queued(p))
1012 			rq = __migrate_task(rq, &rf, p, arg->dest_cpu);
1013 		else
1014 			p->wake_cpu = arg->dest_cpu;
1015 	}
1016 	rq_unlock(rq, &rf);
1017 	raw_spin_unlock(&p->pi_lock);
1018 
1019 	local_irq_enable();
1020 	return 0;
1021 }
1022 
1023 /*
1024  * sched_class::set_cpus_allowed must do the below, but is not required to
1025  * actually call this function.
1026  */
1027 void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
1028 {
1029 	cpumask_copy(&p->cpus_allowed, new_mask);
1030 	p->nr_cpus_allowed = cpumask_weight(new_mask);
1031 }
1032 
1033 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
1034 {
1035 	struct rq *rq = task_rq(p);
1036 	bool queued, running;
1037 
1038 	lockdep_assert_held(&p->pi_lock);
1039 
1040 	queued = task_on_rq_queued(p);
1041 	running = task_current(rq, p);
1042 
1043 	if (queued) {
1044 		/*
1045 		 * Because __kthread_bind() calls this on blocked tasks without
1046 		 * holding rq->lock.
1047 		 */
1048 		lockdep_assert_held(&rq->lock);
1049 		dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
1050 	}
1051 	if (running)
1052 		put_prev_task(rq, p);
1053 
1054 	p->sched_class->set_cpus_allowed(p, new_mask);
1055 
1056 	if (queued)
1057 		enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
1058 	if (running)
1059 		set_curr_task(rq, p);
1060 }
1061 
1062 /*
1063  * Change a given task's CPU affinity. Migrate the thread to a
1064  * proper CPU and schedule it away if the CPU it's executing on
1065  * is removed from the allowed bitmask.
1066  *
1067  * NOTE: the caller must have a valid reference to the task, the
1068  * task must not exit() & deallocate itself prematurely. The
1069  * call is not atomic; no spinlocks may be held.
1070  */
1071 static int __set_cpus_allowed_ptr(struct task_struct *p,
1072 				  const struct cpumask *new_mask, bool check)
1073 {
1074 	const struct cpumask *cpu_valid_mask = cpu_active_mask;
1075 	unsigned int dest_cpu;
1076 	struct rq_flags rf;
1077 	struct rq *rq;
1078 	int ret = 0;
1079 
1080 	rq = task_rq_lock(p, &rf);
1081 	update_rq_clock(rq);
1082 
1083 	if (p->flags & PF_KTHREAD) {
1084 		/*
1085 		 * Kernel threads are allowed on online && !active CPUs
1086 		 */
1087 		cpu_valid_mask = cpu_online_mask;
1088 	}
1089 
1090 	/*
1091 	 * Must re-check here, to close a race against __kthread_bind(),
1092 	 * sched_setaffinity() is not guaranteed to observe the flag.
1093 	 */
1094 	if (check && (p->flags & PF_NO_SETAFFINITY)) {
1095 		ret = -EINVAL;
1096 		goto out;
1097 	}
1098 
1099 	if (cpumask_equal(&p->cpus_allowed, new_mask))
1100 		goto out;
1101 
1102 	if (!cpumask_intersects(new_mask, cpu_valid_mask)) {
1103 		ret = -EINVAL;
1104 		goto out;
1105 	}
1106 
1107 	do_set_cpus_allowed(p, new_mask);
1108 
1109 	if (p->flags & PF_KTHREAD) {
1110 		/*
1111 		 * For kernel threads that do indeed end up on online &&
1112 		 * !active we want to ensure they are strict per-CPU threads.
1113 		 */
1114 		WARN_ON(cpumask_intersects(new_mask, cpu_online_mask) &&
1115 			!cpumask_intersects(new_mask, cpu_active_mask) &&
1116 			p->nr_cpus_allowed != 1);
1117 	}
1118 
1119 	/* Can the task run on the task's current CPU? If so, we're done */
1120 	if (cpumask_test_cpu(task_cpu(p), new_mask))
1121 		goto out;
1122 
1123 	dest_cpu = cpumask_any_and(cpu_valid_mask, new_mask);
1124 	if (task_running(rq, p) || p->state == TASK_WAKING) {
1125 		struct migration_arg arg = { p, dest_cpu };
1126 		/* Need help from migration thread: drop lock and wait. */
1127 		task_rq_unlock(rq, p, &rf);
1128 		stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
1129 		tlb_migrate_finish(p->mm);
1130 		return 0;
1131 	} else if (task_on_rq_queued(p)) {
1132 		/*
1133 		 * OK, since we're going to drop the lock immediately
1134 		 * afterwards anyway.
1135 		 */
1136 		rq = move_queued_task(rq, &rf, p, dest_cpu);
1137 	}
1138 out:
1139 	task_rq_unlock(rq, p, &rf);
1140 
1141 	return ret;
1142 }
1143 
1144 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
1145 {
1146 	return __set_cpus_allowed_ptr(p, new_mask, false);
1147 }
1148 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
1149 
1150 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
1151 {
1152 #ifdef CONFIG_SCHED_DEBUG
1153 	/*
1154 	 * We should never call set_task_cpu() on a blocked task,
1155 	 * ttwu() will sort out the placement.
1156 	 */
1157 	WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
1158 			!p->on_rq);
1159 
1160 	/*
1161 	 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
1162 	 * because schedstat_wait_{start,end} rebase migrating task's wait_start
1163 	 * time relying on p->on_rq.
1164 	 */
1165 	WARN_ON_ONCE(p->state == TASK_RUNNING &&
1166 		     p->sched_class == &fair_sched_class &&
1167 		     (p->on_rq && !task_on_rq_migrating(p)));
1168 
1169 #ifdef CONFIG_LOCKDEP
1170 	/*
1171 	 * The caller should hold either p->pi_lock or rq->lock, when changing
1172 	 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
1173 	 *
1174 	 * sched_move_task() holds both and thus holding either pins the cgroup,
1175 	 * see task_group().
1176 	 *
1177 	 * Furthermore, all task_rq users should acquire both locks, see
1178 	 * task_rq_lock().
1179 	 */
1180 	WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
1181 				      lockdep_is_held(&task_rq(p)->lock)));
1182 #endif
1183 	/*
1184 	 * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
1185 	 */
1186 	WARN_ON_ONCE(!cpu_online(new_cpu));
1187 #endif
1188 
1189 	trace_sched_migrate_task(p, new_cpu);
1190 
1191 	if (task_cpu(p) != new_cpu) {
1192 		if (p->sched_class->migrate_task_rq)
1193 			p->sched_class->migrate_task_rq(p);
1194 		p->se.nr_migrations++;
1195 		rseq_migrate(p);
1196 		perf_event_task_migrate(p);
1197 	}
1198 
1199 	__set_task_cpu(p, new_cpu);
1200 }
1201 
1202 static void __migrate_swap_task(struct task_struct *p, int cpu)
1203 {
1204 	if (task_on_rq_queued(p)) {
1205 		struct rq *src_rq, *dst_rq;
1206 		struct rq_flags srf, drf;
1207 
1208 		src_rq = task_rq(p);
1209 		dst_rq = cpu_rq(cpu);
1210 
1211 		rq_pin_lock(src_rq, &srf);
1212 		rq_pin_lock(dst_rq, &drf);
1213 
1214 		p->on_rq = TASK_ON_RQ_MIGRATING;
1215 		deactivate_task(src_rq, p, 0);
1216 		set_task_cpu(p, cpu);
1217 		activate_task(dst_rq, p, 0);
1218 		p->on_rq = TASK_ON_RQ_QUEUED;
1219 		check_preempt_curr(dst_rq, p, 0);
1220 
1221 		rq_unpin_lock(dst_rq, &drf);
1222 		rq_unpin_lock(src_rq, &srf);
1223 
1224 	} else {
1225 		/*
1226 		 * Task isn't running anymore; make it appear like we migrated
1227 		 * it before it went to sleep. This means on wakeup we make the
1228 		 * previous CPU our target instead of where it really is.
1229 		 */
1230 		p->wake_cpu = cpu;
1231 	}
1232 }
1233 
1234 struct migration_swap_arg {
1235 	struct task_struct *src_task, *dst_task;
1236 	int src_cpu, dst_cpu;
1237 };
1238 
1239 static int migrate_swap_stop(void *data)
1240 {
1241 	struct migration_swap_arg *arg = data;
1242 	struct rq *src_rq, *dst_rq;
1243 	int ret = -EAGAIN;
1244 
1245 	if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
1246 		return -EAGAIN;
1247 
1248 	src_rq = cpu_rq(arg->src_cpu);
1249 	dst_rq = cpu_rq(arg->dst_cpu);
1250 
1251 	double_raw_lock(&arg->src_task->pi_lock,
1252 			&arg->dst_task->pi_lock);
1253 	double_rq_lock(src_rq, dst_rq);
1254 
1255 	if (task_cpu(arg->dst_task) != arg->dst_cpu)
1256 		goto unlock;
1257 
1258 	if (task_cpu(arg->src_task) != arg->src_cpu)
1259 		goto unlock;
1260 
1261 	if (!cpumask_test_cpu(arg->dst_cpu, &arg->src_task->cpus_allowed))
1262 		goto unlock;
1263 
1264 	if (!cpumask_test_cpu(arg->src_cpu, &arg->dst_task->cpus_allowed))
1265 		goto unlock;
1266 
1267 	__migrate_swap_task(arg->src_task, arg->dst_cpu);
1268 	__migrate_swap_task(arg->dst_task, arg->src_cpu);
1269 
1270 	ret = 0;
1271 
1272 unlock:
1273 	double_rq_unlock(src_rq, dst_rq);
1274 	raw_spin_unlock(&arg->dst_task->pi_lock);
1275 	raw_spin_unlock(&arg->src_task->pi_lock);
1276 
1277 	return ret;
1278 }
1279 
1280 /*
1281  * Cross migrate two tasks
1282  */
1283 int migrate_swap(struct task_struct *cur, struct task_struct *p)
1284 {
1285 	struct migration_swap_arg arg;
1286 	int ret = -EINVAL;
1287 
1288 	arg = (struct migration_swap_arg){
1289 		.src_task = cur,
1290 		.src_cpu = task_cpu(cur),
1291 		.dst_task = p,
1292 		.dst_cpu = task_cpu(p),
1293 	};
1294 
1295 	if (arg.src_cpu == arg.dst_cpu)
1296 		goto out;
1297 
1298 	/*
1299 	 * These three tests are all lockless; this is OK since all of them
1300 	 * will be re-checked with proper locks held further down the line.
1301 	 */
1302 	if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
1303 		goto out;
1304 
1305 	if (!cpumask_test_cpu(arg.dst_cpu, &arg.src_task->cpus_allowed))
1306 		goto out;
1307 
1308 	if (!cpumask_test_cpu(arg.src_cpu, &arg.dst_task->cpus_allowed))
1309 		goto out;
1310 
1311 	trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
1312 	ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
1313 
1314 out:
1315 	return ret;
1316 }
1317 
1318 /*
1319  * wait_task_inactive - wait for a thread to unschedule.
1320  *
1321  * If @match_state is nonzero, it's the @p->state value just checked and
1322  * not expected to change.  If it changes, i.e. @p might have woken up,
1323  * then return zero.  When we succeed in waiting for @p to be off its CPU,
1324  * we return a positive number (its total switch count).  If a second call
1325  * a short while later returns the same number, the caller can be sure that
1326  * @p has remained unscheduled the whole time.
1327  *
1328  * The caller must ensure that the task *will* unschedule sometime soon,
1329  * else this function might spin for a *long* time. This function can't
1330  * be called with interrupts off, or it may introduce deadlock with
1331  * smp_call_function() if an IPI is sent by the same process we are
1332  * waiting to become inactive.
1333  */
1334 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
1335 {
1336 	int running, queued;
1337 	struct rq_flags rf;
1338 	unsigned long ncsw;
1339 	struct rq *rq;
1340 
1341 	for (;;) {
1342 		/*
1343 		 * We do the initial early heuristics without holding
1344 		 * any task-queue locks at all. We'll only try to get
1345 		 * the runqueue lock when things look like they will
1346 		 * work out!
1347 		 */
1348 		rq = task_rq(p);
1349 
1350 		/*
1351 		 * If the task is actively running on another CPU
1352 		 * still, just relax and busy-wait without holding
1353 		 * any locks.
1354 		 *
1355 		 * NOTE! Since we don't hold any locks, it's not
1356 		 * even sure that "rq" stays as the right runqueue!
1357 		 * But we don't care, since "task_running()" will
1358 		 * return false if the runqueue has changed and p
1359 		 * is actually now running somewhere else!
1360 		 */
1361 		while (task_running(rq, p)) {
1362 			if (match_state && unlikely(p->state != match_state))
1363 				return 0;
1364 			cpu_relax();
1365 		}
1366 
1367 		/*
1368 		 * Ok, time to look more closely! We need the rq
1369 		 * lock now, to be *sure*. If we're wrong, we'll
1370 		 * just go back and repeat.
1371 		 */
1372 		rq = task_rq_lock(p, &rf);
1373 		trace_sched_wait_task(p);
1374 		running = task_running(rq, p);
1375 		queued = task_on_rq_queued(p);
1376 		ncsw = 0;
1377 		if (!match_state || p->state == match_state)
1378 			ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
1379 		task_rq_unlock(rq, p, &rf);
1380 
1381 		/*
1382 		 * If it changed from the expected state, bail out now.
1383 		 */
1384 		if (unlikely(!ncsw))
1385 			break;
1386 
1387 		/*
1388 		 * Was it really running after all now that we
1389 		 * checked with the proper locks actually held?
1390 		 *
1391 		 * Oops. Go back and try again..
1392 		 */
1393 		if (unlikely(running)) {
1394 			cpu_relax();
1395 			continue;
1396 		}
1397 
1398 		/*
1399 		 * It's not enough that it's not actively running,
1400 		 * it must be off the runqueue _entirely_, and not
1401 		 * preempted!
1402 		 *
1403 		 * So if it was still runnable (but just not actively
1404 		 * running right now), it's preempted, and we should
1405 		 * yield - it could be a while.
1406 		 */
1407 		if (unlikely(queued)) {
1408 			ktime_t to = NSEC_PER_SEC / HZ;
1409 
1410 			set_current_state(TASK_UNINTERRUPTIBLE);
1411 			schedule_hrtimeout(&to, HRTIMER_MODE_REL);
1412 			continue;
1413 		}
1414 
1415 		/*
1416 		 * Ahh, all good. It wasn't running, and it wasn't
1417 		 * runnable, which means that it will never become
1418 		 * running in the future either. We're all done!
1419 		 */
1420 		break;
1421 	}
1422 
1423 	return ncsw;
1424 }
1425 
1426 /***
1427  * kick_process - kick a running thread to enter/exit the kernel
1428  * @p: the to-be-kicked thread
1429  *
1430  * Cause a process which is running on another CPU to enter
1431  * kernel-mode, without any delay. (to get signals handled.)
1432  *
1433  * NOTE: this function doesn't have to take the runqueue lock,
1434  * because all it wants to ensure is that the remote task enters
1435  * the kernel. If the IPI races and the task has been migrated
1436  * to another CPU then no harm is done and the purpose has been
1437  * achieved as well.
1438  */
1439 void kick_process(struct task_struct *p)
1440 {
1441 	int cpu;
1442 
1443 	preempt_disable();
1444 	cpu = task_cpu(p);
1445 	if ((cpu != smp_processor_id()) && task_curr(p))
1446 		smp_send_reschedule(cpu);
1447 	preempt_enable();
1448 }
1449 EXPORT_SYMBOL_GPL(kick_process);
1450 
1451 /*
1452  * ->cpus_allowed is protected by both rq->lock and p->pi_lock
1453  *
1454  * A few notes on cpu_active vs cpu_online:
1455  *
1456  *  - cpu_active must be a subset of cpu_online
1457  *
1458  *  - on CPU-up we allow per-CPU kthreads on the online && !active CPU,
1459  *    see __set_cpus_allowed_ptr(). At this point the newly online
1460  *    CPU isn't yet part of the sched domains, and balancing will not
1461  *    see it.
1462  *
1463  *  - on CPU-down we clear cpu_active() to mask the sched domains and
1464  *    avoid the load balancer to place new tasks on the to be removed
1465  *    CPU. Existing tasks will remain running there and will be taken
1466  *    off.
1467  *
1468  * This means that fallback selection must not select !active CPUs.
1469  * And can assume that any active CPU must be online. Conversely
1470  * select_task_rq() below may allow selection of !active CPUs in order
1471  * to satisfy the above rules.
1472  */
1473 static int select_fallback_rq(int cpu, struct task_struct *p)
1474 {
1475 	int nid = cpu_to_node(cpu);
1476 	const struct cpumask *nodemask = NULL;
1477 	enum { cpuset, possible, fail } state = cpuset;
1478 	int dest_cpu;
1479 
1480 	/*
1481 	 * If the node that the CPU is on has been offlined, cpu_to_node()
1482 	 * will return -1. There is no CPU on the node, and we should
1483 	 * select the CPU on the other node.
1484 	 */
1485 	if (nid != -1) {
1486 		nodemask = cpumask_of_node(nid);
1487 
1488 		/* Look for allowed, online CPU in same node. */
1489 		for_each_cpu(dest_cpu, nodemask) {
1490 			if (!cpu_active(dest_cpu))
1491 				continue;
1492 			if (cpumask_test_cpu(dest_cpu, &p->cpus_allowed))
1493 				return dest_cpu;
1494 		}
1495 	}
1496 
1497 	for (;;) {
1498 		/* Any allowed, online CPU? */
1499 		for_each_cpu(dest_cpu, &p->cpus_allowed) {
1500 			if (!is_cpu_allowed(p, dest_cpu))
1501 				continue;
1502 
1503 			goto out;
1504 		}
1505 
1506 		/* No more Mr. Nice Guy. */
1507 		switch (state) {
1508 		case cpuset:
1509 			if (IS_ENABLED(CONFIG_CPUSETS)) {
1510 				cpuset_cpus_allowed_fallback(p);
1511 				state = possible;
1512 				break;
1513 			}
1514 			/* Fall-through */
1515 		case possible:
1516 			do_set_cpus_allowed(p, cpu_possible_mask);
1517 			state = fail;
1518 			break;
1519 
1520 		case fail:
1521 			BUG();
1522 			break;
1523 		}
1524 	}
1525 
1526 out:
1527 	if (state != cpuset) {
1528 		/*
1529 		 * Don't tell them about moving exiting tasks or
1530 		 * kernel threads (both mm NULL), since they never
1531 		 * leave kernel.
1532 		 */
1533 		if (p->mm && printk_ratelimit()) {
1534 			printk_deferred("process %d (%s) no longer affine to cpu%d\n",
1535 					task_pid_nr(p), p->comm, cpu);
1536 		}
1537 	}
1538 
1539 	return dest_cpu;
1540 }
1541 
1542 /*
1543  * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable.
1544  */
1545 static inline
1546 int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
1547 {
1548 	lockdep_assert_held(&p->pi_lock);
1549 
1550 	if (p->nr_cpus_allowed > 1)
1551 		cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
1552 	else
1553 		cpu = cpumask_any(&p->cpus_allowed);
1554 
1555 	/*
1556 	 * In order not to call set_task_cpu() on a blocking task we need
1557 	 * to rely on ttwu() to place the task on a valid ->cpus_allowed
1558 	 * CPU.
1559 	 *
1560 	 * Since this is common to all placement strategies, this lives here.
1561 	 *
1562 	 * [ this allows ->select_task() to simply return task_cpu(p) and
1563 	 *   not worry about this generic constraint ]
1564 	 */
1565 	if (unlikely(!is_cpu_allowed(p, cpu)))
1566 		cpu = select_fallback_rq(task_cpu(p), p);
1567 
1568 	return cpu;
1569 }
1570 
1571 static void update_avg(u64 *avg, u64 sample)
1572 {
1573 	s64 diff = sample - *avg;
1574 	*avg += diff >> 3;
1575 }
1576 
1577 void sched_set_stop_task(int cpu, struct task_struct *stop)
1578 {
1579 	struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
1580 	struct task_struct *old_stop = cpu_rq(cpu)->stop;
1581 
1582 	if (stop) {
1583 		/*
1584 		 * Make it appear like a SCHED_FIFO task, its something
1585 		 * userspace knows about and won't get confused about.
1586 		 *
1587 		 * Also, it will make PI more or less work without too
1588 		 * much confusion -- but then, stop work should not
1589 		 * rely on PI working anyway.
1590 		 */
1591 		sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
1592 
1593 		stop->sched_class = &stop_sched_class;
1594 	}
1595 
1596 	cpu_rq(cpu)->stop = stop;
1597 
1598 	if (old_stop) {
1599 		/*
1600 		 * Reset it back to a normal scheduling class so that
1601 		 * it can die in pieces.
1602 		 */
1603 		old_stop->sched_class = &rt_sched_class;
1604 	}
1605 }
1606 
1607 #else
1608 
1609 static inline int __set_cpus_allowed_ptr(struct task_struct *p,
1610 					 const struct cpumask *new_mask, bool check)
1611 {
1612 	return set_cpus_allowed_ptr(p, new_mask);
1613 }
1614 
1615 #endif /* CONFIG_SMP */
1616 
1617 static void
1618 ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
1619 {
1620 	struct rq *rq;
1621 
1622 	if (!schedstat_enabled())
1623 		return;
1624 
1625 	rq = this_rq();
1626 
1627 #ifdef CONFIG_SMP
1628 	if (cpu == rq->cpu) {
1629 		__schedstat_inc(rq->ttwu_local);
1630 		__schedstat_inc(p->se.statistics.nr_wakeups_local);
1631 	} else {
1632 		struct sched_domain *sd;
1633 
1634 		__schedstat_inc(p->se.statistics.nr_wakeups_remote);
1635 		rcu_read_lock();
1636 		for_each_domain(rq->cpu, sd) {
1637 			if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
1638 				__schedstat_inc(sd->ttwu_wake_remote);
1639 				break;
1640 			}
1641 		}
1642 		rcu_read_unlock();
1643 	}
1644 
1645 	if (wake_flags & WF_MIGRATED)
1646 		__schedstat_inc(p->se.statistics.nr_wakeups_migrate);
1647 #endif /* CONFIG_SMP */
1648 
1649 	__schedstat_inc(rq->ttwu_count);
1650 	__schedstat_inc(p->se.statistics.nr_wakeups);
1651 
1652 	if (wake_flags & WF_SYNC)
1653 		__schedstat_inc(p->se.statistics.nr_wakeups_sync);
1654 }
1655 
1656 static inline void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags)
1657 {
1658 	activate_task(rq, p, en_flags);
1659 	p->on_rq = TASK_ON_RQ_QUEUED;
1660 
1661 	/* If a worker is waking up, notify the workqueue: */
1662 	if (p->flags & PF_WQ_WORKER)
1663 		wq_worker_waking_up(p, cpu_of(rq));
1664 }
1665 
1666 /*
1667  * Mark the task runnable and perform wakeup-preemption.
1668  */
1669 static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
1670 			   struct rq_flags *rf)
1671 {
1672 	check_preempt_curr(rq, p, wake_flags);
1673 	p->state = TASK_RUNNING;
1674 	trace_sched_wakeup(p);
1675 
1676 #ifdef CONFIG_SMP
1677 	if (p->sched_class->task_woken) {
1678 		/*
1679 		 * Our task @p is fully woken up and running; so its safe to
1680 		 * drop the rq->lock, hereafter rq is only used for statistics.
1681 		 */
1682 		rq_unpin_lock(rq, rf);
1683 		p->sched_class->task_woken(rq, p);
1684 		rq_repin_lock(rq, rf);
1685 	}
1686 
1687 	if (rq->idle_stamp) {
1688 		u64 delta = rq_clock(rq) - rq->idle_stamp;
1689 		u64 max = 2*rq->max_idle_balance_cost;
1690 
1691 		update_avg(&rq->avg_idle, delta);
1692 
1693 		if (rq->avg_idle > max)
1694 			rq->avg_idle = max;
1695 
1696 		rq->idle_stamp = 0;
1697 	}
1698 #endif
1699 }
1700 
1701 static void
1702 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
1703 		 struct rq_flags *rf)
1704 {
1705 	int en_flags = ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK;
1706 
1707 	lockdep_assert_held(&rq->lock);
1708 
1709 #ifdef CONFIG_SMP
1710 	if (p->sched_contributes_to_load)
1711 		rq->nr_uninterruptible--;
1712 
1713 	if (wake_flags & WF_MIGRATED)
1714 		en_flags |= ENQUEUE_MIGRATED;
1715 #endif
1716 
1717 	ttwu_activate(rq, p, en_flags);
1718 	ttwu_do_wakeup(rq, p, wake_flags, rf);
1719 }
1720 
1721 /*
1722  * Called in case the task @p isn't fully descheduled from its runqueue,
1723  * in this case we must do a remote wakeup. Its a 'light' wakeup though,
1724  * since all we need to do is flip p->state to TASK_RUNNING, since
1725  * the task is still ->on_rq.
1726  */
1727 static int ttwu_remote(struct task_struct *p, int wake_flags)
1728 {
1729 	struct rq_flags rf;
1730 	struct rq *rq;
1731 	int ret = 0;
1732 
1733 	rq = __task_rq_lock(p, &rf);
1734 	if (task_on_rq_queued(p)) {
1735 		/* check_preempt_curr() may use rq clock */
1736 		update_rq_clock(rq);
1737 		ttwu_do_wakeup(rq, p, wake_flags, &rf);
1738 		ret = 1;
1739 	}
1740 	__task_rq_unlock(rq, &rf);
1741 
1742 	return ret;
1743 }
1744 
1745 #ifdef CONFIG_SMP
1746 void sched_ttwu_pending(void)
1747 {
1748 	struct rq *rq = this_rq();
1749 	struct llist_node *llist = llist_del_all(&rq->wake_list);
1750 	struct task_struct *p, *t;
1751 	struct rq_flags rf;
1752 
1753 	if (!llist)
1754 		return;
1755 
1756 	rq_lock_irqsave(rq, &rf);
1757 	update_rq_clock(rq);
1758 
1759 	llist_for_each_entry_safe(p, t, llist, wake_entry)
1760 		ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0, &rf);
1761 
1762 	rq_unlock_irqrestore(rq, &rf);
1763 }
1764 
1765 void scheduler_ipi(void)
1766 {
1767 	/*
1768 	 * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting
1769 	 * TIF_NEED_RESCHED remotely (for the first time) will also send
1770 	 * this IPI.
1771 	 */
1772 	preempt_fold_need_resched();
1773 
1774 	if (llist_empty(&this_rq()->wake_list) && !got_nohz_idle_kick())
1775 		return;
1776 
1777 	/*
1778 	 * Not all reschedule IPI handlers call irq_enter/irq_exit, since
1779 	 * traditionally all their work was done from the interrupt return
1780 	 * path. Now that we actually do some work, we need to make sure
1781 	 * we do call them.
1782 	 *
1783 	 * Some archs already do call them, luckily irq_enter/exit nest
1784 	 * properly.
1785 	 *
1786 	 * Arguably we should visit all archs and update all handlers,
1787 	 * however a fair share of IPIs are still resched only so this would
1788 	 * somewhat pessimize the simple resched case.
1789 	 */
1790 	irq_enter();
1791 	sched_ttwu_pending();
1792 
1793 	/*
1794 	 * Check if someone kicked us for doing the nohz idle load balance.
1795 	 */
1796 	if (unlikely(got_nohz_idle_kick())) {
1797 		this_rq()->idle_balance = 1;
1798 		raise_softirq_irqoff(SCHED_SOFTIRQ);
1799 	}
1800 	irq_exit();
1801 }
1802 
1803 static void ttwu_queue_remote(struct task_struct *p, int cpu, int wake_flags)
1804 {
1805 	struct rq *rq = cpu_rq(cpu);
1806 
1807 	p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
1808 
1809 	if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) {
1810 		if (!set_nr_if_polling(rq->idle))
1811 			smp_send_reschedule(cpu);
1812 		else
1813 			trace_sched_wake_idle_without_ipi(cpu);
1814 	}
1815 }
1816 
1817 void wake_up_if_idle(int cpu)
1818 {
1819 	struct rq *rq = cpu_rq(cpu);
1820 	struct rq_flags rf;
1821 
1822 	rcu_read_lock();
1823 
1824 	if (!is_idle_task(rcu_dereference(rq->curr)))
1825 		goto out;
1826 
1827 	if (set_nr_if_polling(rq->idle)) {
1828 		trace_sched_wake_idle_without_ipi(cpu);
1829 	} else {
1830 		rq_lock_irqsave(rq, &rf);
1831 		if (is_idle_task(rq->curr))
1832 			smp_send_reschedule(cpu);
1833 		/* Else CPU is not idle, do nothing here: */
1834 		rq_unlock_irqrestore(rq, &rf);
1835 	}
1836 
1837 out:
1838 	rcu_read_unlock();
1839 }
1840 
1841 bool cpus_share_cache(int this_cpu, int that_cpu)
1842 {
1843 	return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
1844 }
1845 #endif /* CONFIG_SMP */
1846 
1847 static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
1848 {
1849 	struct rq *rq = cpu_rq(cpu);
1850 	struct rq_flags rf;
1851 
1852 #if defined(CONFIG_SMP)
1853 	if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) {
1854 		sched_clock_cpu(cpu); /* Sync clocks across CPUs */
1855 		ttwu_queue_remote(p, cpu, wake_flags);
1856 		return;
1857 	}
1858 #endif
1859 
1860 	rq_lock(rq, &rf);
1861 	update_rq_clock(rq);
1862 	ttwu_do_activate(rq, p, wake_flags, &rf);
1863 	rq_unlock(rq, &rf);
1864 }
1865 
1866 /*
1867  * Notes on Program-Order guarantees on SMP systems.
1868  *
1869  *  MIGRATION
1870  *
1871  * The basic program-order guarantee on SMP systems is that when a task [t]
1872  * migrates, all its activity on its old CPU [c0] happens-before any subsequent
1873  * execution on its new CPU [c1].
1874  *
1875  * For migration (of runnable tasks) this is provided by the following means:
1876  *
1877  *  A) UNLOCK of the rq(c0)->lock scheduling out task t
1878  *  B) migration for t is required to synchronize *both* rq(c0)->lock and
1879  *     rq(c1)->lock (if not at the same time, then in that order).
1880  *  C) LOCK of the rq(c1)->lock scheduling in task
1881  *
1882  * Transitivity guarantees that B happens after A and C after B.
1883  * Note: we only require RCpc transitivity.
1884  * Note: the CPU doing B need not be c0 or c1
1885  *
1886  * Example:
1887  *
1888  *   CPU0            CPU1            CPU2
1889  *
1890  *   LOCK rq(0)->lock
1891  *   sched-out X
1892  *   sched-in Y
1893  *   UNLOCK rq(0)->lock
1894  *
1895  *                                   LOCK rq(0)->lock // orders against CPU0
1896  *                                   dequeue X
1897  *                                   UNLOCK rq(0)->lock
1898  *
1899  *                                   LOCK rq(1)->lock
1900  *                                   enqueue X
1901  *                                   UNLOCK rq(1)->lock
1902  *
1903  *                   LOCK rq(1)->lock // orders against CPU2
1904  *                   sched-out Z
1905  *                   sched-in X
1906  *                   UNLOCK rq(1)->lock
1907  *
1908  *
1909  *  BLOCKING -- aka. SLEEP + WAKEUP
1910  *
1911  * For blocking we (obviously) need to provide the same guarantee as for
1912  * migration. However the means are completely different as there is no lock
1913  * chain to provide order. Instead we do:
1914  *
1915  *   1) smp_store_release(X->on_cpu, 0)
1916  *   2) smp_cond_load_acquire(!X->on_cpu)
1917  *
1918  * Example:
1919  *
1920  *   CPU0 (schedule)  CPU1 (try_to_wake_up) CPU2 (schedule)
1921  *
1922  *   LOCK rq(0)->lock LOCK X->pi_lock
1923  *   dequeue X
1924  *   sched-out X
1925  *   smp_store_release(X->on_cpu, 0);
1926  *
1927  *                    smp_cond_load_acquire(&X->on_cpu, !VAL);
1928  *                    X->state = WAKING
1929  *                    set_task_cpu(X,2)
1930  *
1931  *                    LOCK rq(2)->lock
1932  *                    enqueue X
1933  *                    X->state = RUNNING
1934  *                    UNLOCK rq(2)->lock
1935  *
1936  *                                          LOCK rq(2)->lock // orders against CPU1
1937  *                                          sched-out Z
1938  *                                          sched-in X
1939  *                                          UNLOCK rq(2)->lock
1940  *
1941  *                    UNLOCK X->pi_lock
1942  *   UNLOCK rq(0)->lock
1943  *
1944  *
1945  * However; for wakeups there is a second guarantee we must provide, namely we
1946  * must observe the state that lead to our wakeup. That is, not only must our
1947  * task observe its own prior state, it must also observe the stores prior to
1948  * its wakeup.
1949  *
1950  * This means that any means of doing remote wakeups must order the CPU doing
1951  * the wakeup against the CPU the task is going to end up running on. This,
1952  * however, is already required for the regular Program-Order guarantee above,
1953  * since the waking CPU is the one issueing the ACQUIRE (smp_cond_load_acquire).
1954  *
1955  */
1956 
1957 /**
1958  * try_to_wake_up - wake up a thread
1959  * @p: the thread to be awakened
1960  * @state: the mask of task states that can be woken
1961  * @wake_flags: wake modifier flags (WF_*)
1962  *
1963  * If (@state & @p->state) @p->state = TASK_RUNNING.
1964  *
1965  * If the task was not queued/runnable, also place it back on a runqueue.
1966  *
1967  * Atomic against schedule() which would dequeue a task, also see
1968  * set_current_state().
1969  *
1970  * Return: %true if @p->state changes (an actual wakeup was done),
1971  *	   %false otherwise.
1972  */
1973 static int
1974 try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
1975 {
1976 	unsigned long flags;
1977 	int cpu, success = 0;
1978 
1979 	/*
1980 	 * If we are going to wake up a thread waiting for CONDITION we
1981 	 * need to ensure that CONDITION=1 done by the caller can not be
1982 	 * reordered with p->state check below. This pairs with mb() in
1983 	 * set_current_state() the waiting thread does.
1984 	 */
1985 	raw_spin_lock_irqsave(&p->pi_lock, flags);
1986 	smp_mb__after_spinlock();
1987 	if (!(p->state & state))
1988 		goto out;
1989 
1990 	trace_sched_waking(p);
1991 
1992 	/* We're going to change ->state: */
1993 	success = 1;
1994 	cpu = task_cpu(p);
1995 
1996 	/*
1997 	 * Ensure we load p->on_rq _after_ p->state, otherwise it would
1998 	 * be possible to, falsely, observe p->on_rq == 0 and get stuck
1999 	 * in smp_cond_load_acquire() below.
2000 	 *
2001 	 * sched_ttwu_pending()                 try_to_wake_up()
2002 	 *   [S] p->on_rq = 1;                  [L] P->state
2003 	 *       UNLOCK rq->lock  -----.
2004 	 *                              \
2005 	 *				 +---   RMB
2006 	 * schedule()                   /
2007 	 *       LOCK rq->lock    -----'
2008 	 *       UNLOCK rq->lock
2009 	 *
2010 	 * [task p]
2011 	 *   [S] p->state = UNINTERRUPTIBLE     [L] p->on_rq
2012 	 *
2013 	 * Pairs with the UNLOCK+LOCK on rq->lock from the
2014 	 * last wakeup of our task and the schedule that got our task
2015 	 * current.
2016 	 */
2017 	smp_rmb();
2018 	if (p->on_rq && ttwu_remote(p, wake_flags))
2019 		goto stat;
2020 
2021 #ifdef CONFIG_SMP
2022 	/*
2023 	 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
2024 	 * possible to, falsely, observe p->on_cpu == 0.
2025 	 *
2026 	 * One must be running (->on_cpu == 1) in order to remove oneself
2027 	 * from the runqueue.
2028 	 *
2029 	 *  [S] ->on_cpu = 1;	[L] ->on_rq
2030 	 *      UNLOCK rq->lock
2031 	 *			RMB
2032 	 *      LOCK   rq->lock
2033 	 *  [S] ->on_rq = 0;    [L] ->on_cpu
2034 	 *
2035 	 * Pairs with the full barrier implied in the UNLOCK+LOCK on rq->lock
2036 	 * from the consecutive calls to schedule(); the first switching to our
2037 	 * task, the second putting it to sleep.
2038 	 */
2039 	smp_rmb();
2040 
2041 	/*
2042 	 * If the owning (remote) CPU is still in the middle of schedule() with
2043 	 * this task as prev, wait until its done referencing the task.
2044 	 *
2045 	 * Pairs with the smp_store_release() in finish_task().
2046 	 *
2047 	 * This ensures that tasks getting woken will be fully ordered against
2048 	 * their previous state and preserve Program Order.
2049 	 */
2050 	smp_cond_load_acquire(&p->on_cpu, !VAL);
2051 
2052 	p->sched_contributes_to_load = !!task_contributes_to_load(p);
2053 	p->state = TASK_WAKING;
2054 
2055 	if (p->in_iowait) {
2056 		delayacct_blkio_end(p);
2057 		atomic_dec(&task_rq(p)->nr_iowait);
2058 	}
2059 
2060 	cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
2061 	if (task_cpu(p) != cpu) {
2062 		wake_flags |= WF_MIGRATED;
2063 		set_task_cpu(p, cpu);
2064 	}
2065 
2066 #else /* CONFIG_SMP */
2067 
2068 	if (p->in_iowait) {
2069 		delayacct_blkio_end(p);
2070 		atomic_dec(&task_rq(p)->nr_iowait);
2071 	}
2072 
2073 #endif /* CONFIG_SMP */
2074 
2075 	ttwu_queue(p, cpu, wake_flags);
2076 stat:
2077 	ttwu_stat(p, cpu, wake_flags);
2078 out:
2079 	raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2080 
2081 	return success;
2082 }
2083 
2084 /**
2085  * try_to_wake_up_local - try to wake up a local task with rq lock held
2086  * @p: the thread to be awakened
2087  * @rf: request-queue flags for pinning
2088  *
2089  * Put @p on the run-queue if it's not already there. The caller must
2090  * ensure that this_rq() is locked, @p is bound to this_rq() and not
2091  * the current task.
2092  */
2093 static void try_to_wake_up_local(struct task_struct *p, struct rq_flags *rf)
2094 {
2095 	struct rq *rq = task_rq(p);
2096 
2097 	if (WARN_ON_ONCE(rq != this_rq()) ||
2098 	    WARN_ON_ONCE(p == current))
2099 		return;
2100 
2101 	lockdep_assert_held(&rq->lock);
2102 
2103 	if (!raw_spin_trylock(&p->pi_lock)) {
2104 		/*
2105 		 * This is OK, because current is on_cpu, which avoids it being
2106 		 * picked for load-balance and preemption/IRQs are still
2107 		 * disabled avoiding further scheduler activity on it and we've
2108 		 * not yet picked a replacement task.
2109 		 */
2110 		rq_unlock(rq, rf);
2111 		raw_spin_lock(&p->pi_lock);
2112 		rq_relock(rq, rf);
2113 	}
2114 
2115 	if (!(p->state & TASK_NORMAL))
2116 		goto out;
2117 
2118 	trace_sched_waking(p);
2119 
2120 	if (!task_on_rq_queued(p)) {
2121 		if (p->in_iowait) {
2122 			delayacct_blkio_end(p);
2123 			atomic_dec(&rq->nr_iowait);
2124 		}
2125 		ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK);
2126 	}
2127 
2128 	ttwu_do_wakeup(rq, p, 0, rf);
2129 	ttwu_stat(p, smp_processor_id(), 0);
2130 out:
2131 	raw_spin_unlock(&p->pi_lock);
2132 }
2133 
2134 /**
2135  * wake_up_process - Wake up a specific process
2136  * @p: The process to be woken up.
2137  *
2138  * Attempt to wake up the nominated process and move it to the set of runnable
2139  * processes.
2140  *
2141  * Return: 1 if the process was woken up, 0 if it was already running.
2142  *
2143  * It may be assumed that this function implies a write memory barrier before
2144  * changing the task state if and only if any tasks are woken up.
2145  */
2146 int wake_up_process(struct task_struct *p)
2147 {
2148 	return try_to_wake_up(p, TASK_NORMAL, 0);
2149 }
2150 EXPORT_SYMBOL(wake_up_process);
2151 
2152 int wake_up_state(struct task_struct *p, unsigned int state)
2153 {
2154 	return try_to_wake_up(p, state, 0);
2155 }
2156 
2157 /*
2158  * Perform scheduler related setup for a newly forked process p.
2159  * p is forked by current.
2160  *
2161  * __sched_fork() is basic setup used by init_idle() too:
2162  */
2163 static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
2164 {
2165 	p->on_rq			= 0;
2166 
2167 	p->se.on_rq			= 0;
2168 	p->se.exec_start		= 0;
2169 	p->se.sum_exec_runtime		= 0;
2170 	p->se.prev_sum_exec_runtime	= 0;
2171 	p->se.nr_migrations		= 0;
2172 	p->se.vruntime			= 0;
2173 	INIT_LIST_HEAD(&p->se.group_node);
2174 
2175 #ifdef CONFIG_FAIR_GROUP_SCHED
2176 	p->se.cfs_rq			= NULL;
2177 #endif
2178 
2179 #ifdef CONFIG_SCHEDSTATS
2180 	/* Even if schedstat is disabled, there should not be garbage */
2181 	memset(&p->se.statistics, 0, sizeof(p->se.statistics));
2182 #endif
2183 
2184 	RB_CLEAR_NODE(&p->dl.rb_node);
2185 	init_dl_task_timer(&p->dl);
2186 	init_dl_inactive_task_timer(&p->dl);
2187 	__dl_clear_params(p);
2188 
2189 	INIT_LIST_HEAD(&p->rt.run_list);
2190 	p->rt.timeout		= 0;
2191 	p->rt.time_slice	= sched_rr_timeslice;
2192 	p->rt.on_rq		= 0;
2193 	p->rt.on_list		= 0;
2194 
2195 #ifdef CONFIG_PREEMPT_NOTIFIERS
2196 	INIT_HLIST_HEAD(&p->preempt_notifiers);
2197 #endif
2198 
2199 	init_numa_balancing(clone_flags, p);
2200 }
2201 
2202 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
2203 
2204 #ifdef CONFIG_NUMA_BALANCING
2205 
2206 void set_numabalancing_state(bool enabled)
2207 {
2208 	if (enabled)
2209 		static_branch_enable(&sched_numa_balancing);
2210 	else
2211 		static_branch_disable(&sched_numa_balancing);
2212 }
2213 
2214 #ifdef CONFIG_PROC_SYSCTL
2215 int sysctl_numa_balancing(struct ctl_table *table, int write,
2216 			 void __user *buffer, size_t *lenp, loff_t *ppos)
2217 {
2218 	struct ctl_table t;
2219 	int err;
2220 	int state = static_branch_likely(&sched_numa_balancing);
2221 
2222 	if (write && !capable(CAP_SYS_ADMIN))
2223 		return -EPERM;
2224 
2225 	t = *table;
2226 	t.data = &state;
2227 	err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2228 	if (err < 0)
2229 		return err;
2230 	if (write)
2231 		set_numabalancing_state(state);
2232 	return err;
2233 }
2234 #endif
2235 #endif
2236 
2237 #ifdef CONFIG_SCHEDSTATS
2238 
2239 DEFINE_STATIC_KEY_FALSE(sched_schedstats);
2240 static bool __initdata __sched_schedstats = false;
2241 
2242 static void set_schedstats(bool enabled)
2243 {
2244 	if (enabled)
2245 		static_branch_enable(&sched_schedstats);
2246 	else
2247 		static_branch_disable(&sched_schedstats);
2248 }
2249 
2250 void force_schedstat_enabled(void)
2251 {
2252 	if (!schedstat_enabled()) {
2253 		pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
2254 		static_branch_enable(&sched_schedstats);
2255 	}
2256 }
2257 
2258 static int __init setup_schedstats(char *str)
2259 {
2260 	int ret = 0;
2261 	if (!str)
2262 		goto out;
2263 
2264 	/*
2265 	 * This code is called before jump labels have been set up, so we can't
2266 	 * change the static branch directly just yet.  Instead set a temporary
2267 	 * variable so init_schedstats() can do it later.
2268 	 */
2269 	if (!strcmp(str, "enable")) {
2270 		__sched_schedstats = true;
2271 		ret = 1;
2272 	} else if (!strcmp(str, "disable")) {
2273 		__sched_schedstats = false;
2274 		ret = 1;
2275 	}
2276 out:
2277 	if (!ret)
2278 		pr_warn("Unable to parse schedstats=\n");
2279 
2280 	return ret;
2281 }
2282 __setup("schedstats=", setup_schedstats);
2283 
2284 static void __init init_schedstats(void)
2285 {
2286 	set_schedstats(__sched_schedstats);
2287 }
2288 
2289 #ifdef CONFIG_PROC_SYSCTL
2290 int sysctl_schedstats(struct ctl_table *table, int write,
2291 			 void __user *buffer, size_t *lenp, loff_t *ppos)
2292 {
2293 	struct ctl_table t;
2294 	int err;
2295 	int state = static_branch_likely(&sched_schedstats);
2296 
2297 	if (write && !capable(CAP_SYS_ADMIN))
2298 		return -EPERM;
2299 
2300 	t = *table;
2301 	t.data = &state;
2302 	err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
2303 	if (err < 0)
2304 		return err;
2305 	if (write)
2306 		set_schedstats(state);
2307 	return err;
2308 }
2309 #endif /* CONFIG_PROC_SYSCTL */
2310 #else  /* !CONFIG_SCHEDSTATS */
2311 static inline void init_schedstats(void) {}
2312 #endif /* CONFIG_SCHEDSTATS */
2313 
2314 /*
2315  * fork()/clone()-time setup:
2316  */
2317 int sched_fork(unsigned long clone_flags, struct task_struct *p)
2318 {
2319 	unsigned long flags;
2320 	int cpu = get_cpu();
2321 
2322 	__sched_fork(clone_flags, p);
2323 	/*
2324 	 * We mark the process as NEW here. This guarantees that
2325 	 * nobody will actually run it, and a signal or other external
2326 	 * event cannot wake it up and insert it on the runqueue either.
2327 	 */
2328 	p->state = TASK_NEW;
2329 
2330 	/*
2331 	 * Make sure we do not leak PI boosting priority to the child.
2332 	 */
2333 	p->prio = current->normal_prio;
2334 
2335 	/*
2336 	 * Revert to default priority/policy on fork if requested.
2337 	 */
2338 	if (unlikely(p->sched_reset_on_fork)) {
2339 		if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
2340 			p->policy = SCHED_NORMAL;
2341 			p->static_prio = NICE_TO_PRIO(0);
2342 			p->rt_priority = 0;
2343 		} else if (PRIO_TO_NICE(p->static_prio) < 0)
2344 			p->static_prio = NICE_TO_PRIO(0);
2345 
2346 		p->prio = p->normal_prio = __normal_prio(p);
2347 		set_load_weight(p, false);
2348 
2349 		/*
2350 		 * We don't need the reset flag anymore after the fork. It has
2351 		 * fulfilled its duty:
2352 		 */
2353 		p->sched_reset_on_fork = 0;
2354 	}
2355 
2356 	if (dl_prio(p->prio)) {
2357 		put_cpu();
2358 		return -EAGAIN;
2359 	} else if (rt_prio(p->prio)) {
2360 		p->sched_class = &rt_sched_class;
2361 	} else {
2362 		p->sched_class = &fair_sched_class;
2363 	}
2364 
2365 	init_entity_runnable_average(&p->se);
2366 
2367 	/*
2368 	 * The child is not yet in the pid-hash so no cgroup attach races,
2369 	 * and the cgroup is pinned to this child due to cgroup_fork()
2370 	 * is ran before sched_fork().
2371 	 *
2372 	 * Silence PROVE_RCU.
2373 	 */
2374 	raw_spin_lock_irqsave(&p->pi_lock, flags);
2375 	/*
2376 	 * We're setting the CPU for the first time, we don't migrate,
2377 	 * so use __set_task_cpu().
2378 	 */
2379 	__set_task_cpu(p, cpu);
2380 	if (p->sched_class->task_fork)
2381 		p->sched_class->task_fork(p);
2382 	raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2383 
2384 #ifdef CONFIG_SCHED_INFO
2385 	if (likely(sched_info_on()))
2386 		memset(&p->sched_info, 0, sizeof(p->sched_info));
2387 #endif
2388 #if defined(CONFIG_SMP)
2389 	p->on_cpu = 0;
2390 #endif
2391 	init_task_preempt_count(p);
2392 #ifdef CONFIG_SMP
2393 	plist_node_init(&p->pushable_tasks, MAX_PRIO);
2394 	RB_CLEAR_NODE(&p->pushable_dl_tasks);
2395 #endif
2396 
2397 	put_cpu();
2398 	return 0;
2399 }
2400 
2401 unsigned long to_ratio(u64 period, u64 runtime)
2402 {
2403 	if (runtime == RUNTIME_INF)
2404 		return BW_UNIT;
2405 
2406 	/*
2407 	 * Doing this here saves a lot of checks in all
2408 	 * the calling paths, and returning zero seems
2409 	 * safe for them anyway.
2410 	 */
2411 	if (period == 0)
2412 		return 0;
2413 
2414 	return div64_u64(runtime << BW_SHIFT, period);
2415 }
2416 
2417 /*
2418  * wake_up_new_task - wake up a newly created task for the first time.
2419  *
2420  * This function will do some initial scheduler statistics housekeeping
2421  * that must be done for every newly created context, then puts the task
2422  * on the runqueue and wakes it.
2423  */
2424 void wake_up_new_task(struct task_struct *p)
2425 {
2426 	struct rq_flags rf;
2427 	struct rq *rq;
2428 
2429 	raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
2430 	p->state = TASK_RUNNING;
2431 #ifdef CONFIG_SMP
2432 	/*
2433 	 * Fork balancing, do it here and not earlier because:
2434 	 *  - cpus_allowed can change in the fork path
2435 	 *  - any previously selected CPU might disappear through hotplug
2436 	 *
2437 	 * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
2438 	 * as we're not fully set-up yet.
2439 	 */
2440 	p->recent_used_cpu = task_cpu(p);
2441 	__set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
2442 #endif
2443 	rq = __task_rq_lock(p, &rf);
2444 	update_rq_clock(rq);
2445 	post_init_entity_util_avg(&p->se);
2446 
2447 	activate_task(rq, p, ENQUEUE_NOCLOCK);
2448 	p->on_rq = TASK_ON_RQ_QUEUED;
2449 	trace_sched_wakeup_new(p);
2450 	check_preempt_curr(rq, p, WF_FORK);
2451 #ifdef CONFIG_SMP
2452 	if (p->sched_class->task_woken) {
2453 		/*
2454 		 * Nothing relies on rq->lock after this, so its fine to
2455 		 * drop it.
2456 		 */
2457 		rq_unpin_lock(rq, &rf);
2458 		p->sched_class->task_woken(rq, p);
2459 		rq_repin_lock(rq, &rf);
2460 	}
2461 #endif
2462 	task_rq_unlock(rq, p, &rf);
2463 }
2464 
2465 #ifdef CONFIG_PREEMPT_NOTIFIERS
2466 
2467 static DEFINE_STATIC_KEY_FALSE(preempt_notifier_key);
2468 
2469 void preempt_notifier_inc(void)
2470 {
2471 	static_branch_inc(&preempt_notifier_key);
2472 }
2473 EXPORT_SYMBOL_GPL(preempt_notifier_inc);
2474 
2475 void preempt_notifier_dec(void)
2476 {
2477 	static_branch_dec(&preempt_notifier_key);
2478 }
2479 EXPORT_SYMBOL_GPL(preempt_notifier_dec);
2480 
2481 /**
2482  * preempt_notifier_register - tell me when current is being preempted & rescheduled
2483  * @notifier: notifier struct to register
2484  */
2485 void preempt_notifier_register(struct preempt_notifier *notifier)
2486 {
2487 	if (!static_branch_unlikely(&preempt_notifier_key))
2488 		WARN(1, "registering preempt_notifier while notifiers disabled\n");
2489 
2490 	hlist_add_head(&notifier->link, &current->preempt_notifiers);
2491 }
2492 EXPORT_SYMBOL_GPL(preempt_notifier_register);
2493 
2494 /**
2495  * preempt_notifier_unregister - no longer interested in preemption notifications
2496  * @notifier: notifier struct to unregister
2497  *
2498  * This is *not* safe to call from within a preemption notifier.
2499  */
2500 void preempt_notifier_unregister(struct preempt_notifier *notifier)
2501 {
2502 	hlist_del(&notifier->link);
2503 }
2504 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
2505 
2506 static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
2507 {
2508 	struct preempt_notifier *notifier;
2509 
2510 	hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2511 		notifier->ops->sched_in(notifier, raw_smp_processor_id());
2512 }
2513 
2514 static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2515 {
2516 	if (static_branch_unlikely(&preempt_notifier_key))
2517 		__fire_sched_in_preempt_notifiers(curr);
2518 }
2519 
2520 static void
2521 __fire_sched_out_preempt_notifiers(struct task_struct *curr,
2522 				   struct task_struct *next)
2523 {
2524 	struct preempt_notifier *notifier;
2525 
2526 	hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
2527 		notifier->ops->sched_out(notifier, next);
2528 }
2529 
2530 static __always_inline void
2531 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2532 				 struct task_struct *next)
2533 {
2534 	if (static_branch_unlikely(&preempt_notifier_key))
2535 		__fire_sched_out_preempt_notifiers(curr, next);
2536 }
2537 
2538 #else /* !CONFIG_PREEMPT_NOTIFIERS */
2539 
2540 static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
2541 {
2542 }
2543 
2544 static inline void
2545 fire_sched_out_preempt_notifiers(struct task_struct *curr,
2546 				 struct task_struct *next)
2547 {
2548 }
2549 
2550 #endif /* CONFIG_PREEMPT_NOTIFIERS */
2551 
2552 static inline void prepare_task(struct task_struct *next)
2553 {
2554 #ifdef CONFIG_SMP
2555 	/*
2556 	 * Claim the task as running, we do this before switching to it
2557 	 * such that any running task will have this set.
2558 	 */
2559 	next->on_cpu = 1;
2560 #endif
2561 }
2562 
2563 static inline void finish_task(struct task_struct *prev)
2564 {
2565 #ifdef CONFIG_SMP
2566 	/*
2567 	 * After ->on_cpu is cleared, the task can be moved to a different CPU.
2568 	 * We must ensure this doesn't happen until the switch is completely
2569 	 * finished.
2570 	 *
2571 	 * In particular, the load of prev->state in finish_task_switch() must
2572 	 * happen before this.
2573 	 *
2574 	 * Pairs with the smp_cond_load_acquire() in try_to_wake_up().
2575 	 */
2576 	smp_store_release(&prev->on_cpu, 0);
2577 #endif
2578 }
2579 
2580 static inline void
2581 prepare_lock_switch(struct rq *rq, struct task_struct *next, struct rq_flags *rf)
2582 {
2583 	/*
2584 	 * Since the runqueue lock will be released by the next
2585 	 * task (which is an invalid locking op but in the case
2586 	 * of the scheduler it's an obvious special-case), so we
2587 	 * do an early lockdep release here:
2588 	 */
2589 	rq_unpin_lock(rq, rf);
2590 	spin_release(&rq->lock.dep_map, 1, _THIS_IP_);
2591 #ifdef CONFIG_DEBUG_SPINLOCK
2592 	/* this is a valid case when another task releases the spinlock */
2593 	rq->lock.owner = next;
2594 #endif
2595 }
2596 
2597 static inline void finish_lock_switch(struct rq *rq)
2598 {
2599 	/*
2600 	 * If we are tracking spinlock dependencies then we have to
2601 	 * fix up the runqueue lock - which gets 'carried over' from
2602 	 * prev into current:
2603 	 */
2604 	spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
2605 	raw_spin_unlock_irq(&rq->lock);
2606 }
2607 
2608 /*
2609  * NOP if the arch has not defined these:
2610  */
2611 
2612 #ifndef prepare_arch_switch
2613 # define prepare_arch_switch(next)	do { } while (0)
2614 #endif
2615 
2616 #ifndef finish_arch_post_lock_switch
2617 # define finish_arch_post_lock_switch()	do { } while (0)
2618 #endif
2619 
2620 /**
2621  * prepare_task_switch - prepare to switch tasks
2622  * @rq: the runqueue preparing to switch
2623  * @prev: the current task that is being switched out
2624  * @next: the task we are going to switch to.
2625  *
2626  * This is called with the rq lock held and interrupts off. It must
2627  * be paired with a subsequent finish_task_switch after the context
2628  * switch.
2629  *
2630  * prepare_task_switch sets up locking and calls architecture specific
2631  * hooks.
2632  */
2633 static inline void
2634 prepare_task_switch(struct rq *rq, struct task_struct *prev,
2635 		    struct task_struct *next)
2636 {
2637 	kcov_prepare_switch(prev);
2638 	sched_info_switch(rq, prev, next);
2639 	perf_event_task_sched_out(prev, next);
2640 	rseq_preempt(prev);
2641 	fire_sched_out_preempt_notifiers(prev, next);
2642 	prepare_task(next);
2643 	prepare_arch_switch(next);
2644 }
2645 
2646 /**
2647  * finish_task_switch - clean up after a task-switch
2648  * @prev: the thread we just switched away from.
2649  *
2650  * finish_task_switch must be called after the context switch, paired
2651  * with a prepare_task_switch call before the context switch.
2652  * finish_task_switch will reconcile locking set up by prepare_task_switch,
2653  * and do any other architecture-specific cleanup actions.
2654  *
2655  * Note that we may have delayed dropping an mm in context_switch(). If
2656  * so, we finish that here outside of the runqueue lock. (Doing it
2657  * with the lock held can cause deadlocks; see schedule() for
2658  * details.)
2659  *
2660  * The context switch have flipped the stack from under us and restored the
2661  * local variables which were saved when this task called schedule() in the
2662  * past. prev == current is still correct but we need to recalculate this_rq
2663  * because prev may have moved to another CPU.
2664  */
2665 static struct rq *finish_task_switch(struct task_struct *prev)
2666 	__releases(rq->lock)
2667 {
2668 	struct rq *rq = this_rq();
2669 	struct mm_struct *mm = rq->prev_mm;
2670 	long prev_state;
2671 
2672 	/*
2673 	 * The previous task will have left us with a preempt_count of 2
2674 	 * because it left us after:
2675 	 *
2676 	 *	schedule()
2677 	 *	  preempt_disable();			// 1
2678 	 *	  __schedule()
2679 	 *	    raw_spin_lock_irq(&rq->lock)	// 2
2680 	 *
2681 	 * Also, see FORK_PREEMPT_COUNT.
2682 	 */
2683 	if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
2684 		      "corrupted preempt_count: %s/%d/0x%x\n",
2685 		      current->comm, current->pid, preempt_count()))
2686 		preempt_count_set(FORK_PREEMPT_COUNT);
2687 
2688 	rq->prev_mm = NULL;
2689 
2690 	/*
2691 	 * A task struct has one reference for the use as "current".
2692 	 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
2693 	 * schedule one last time. The schedule call will never return, and
2694 	 * the scheduled task must drop that reference.
2695 	 *
2696 	 * We must observe prev->state before clearing prev->on_cpu (in
2697 	 * finish_task), otherwise a concurrent wakeup can get prev
2698 	 * running on another CPU and we could rave with its RUNNING -> DEAD
2699 	 * transition, resulting in a double drop.
2700 	 */
2701 	prev_state = prev->state;
2702 	vtime_task_switch(prev);
2703 	perf_event_task_sched_in(prev, current);
2704 	finish_task(prev);
2705 	finish_lock_switch(rq);
2706 	finish_arch_post_lock_switch();
2707 	kcov_finish_switch(current);
2708 
2709 	fire_sched_in_preempt_notifiers(current);
2710 	/*
2711 	 * When switching through a kernel thread, the loop in
2712 	 * membarrier_{private,global}_expedited() may have observed that
2713 	 * kernel thread and not issued an IPI. It is therefore possible to
2714 	 * schedule between user->kernel->user threads without passing though
2715 	 * switch_mm(). Membarrier requires a barrier after storing to
2716 	 * rq->curr, before returning to userspace, so provide them here:
2717 	 *
2718 	 * - a full memory barrier for {PRIVATE,GLOBAL}_EXPEDITED, implicitly
2719 	 *   provided by mmdrop(),
2720 	 * - a sync_core for SYNC_CORE.
2721 	 */
2722 	if (mm) {
2723 		membarrier_mm_sync_core_before_usermode(mm);
2724 		mmdrop(mm);
2725 	}
2726 	if (unlikely(prev_state == TASK_DEAD)) {
2727 		if (prev->sched_class->task_dead)
2728 			prev->sched_class->task_dead(prev);
2729 
2730 		/*
2731 		 * Remove function-return probe instances associated with this
2732 		 * task and put them back on the free list.
2733 		 */
2734 		kprobe_flush_task(prev);
2735 
2736 		/* Task is done with its stack. */
2737 		put_task_stack(prev);
2738 
2739 		put_task_struct(prev);
2740 	}
2741 
2742 	tick_nohz_task_switch();
2743 	return rq;
2744 }
2745 
2746 #ifdef CONFIG_SMP
2747 
2748 /* rq->lock is NOT held, but preemption is disabled */
2749 static void __balance_callback(struct rq *rq)
2750 {
2751 	struct callback_head *head, *next;
2752 	void (*func)(struct rq *rq);
2753 	unsigned long flags;
2754 
2755 	raw_spin_lock_irqsave(&rq->lock, flags);
2756 	head = rq->balance_callback;
2757 	rq->balance_callback = NULL;
2758 	while (head) {
2759 		func = (void (*)(struct rq *))head->func;
2760 		next = head->next;
2761 		head->next = NULL;
2762 		head = next;
2763 
2764 		func(rq);
2765 	}
2766 	raw_spin_unlock_irqrestore(&rq->lock, flags);
2767 }
2768 
2769 static inline void balance_callback(struct rq *rq)
2770 {
2771 	if (unlikely(rq->balance_callback))
2772 		__balance_callback(rq);
2773 }
2774 
2775 #else
2776 
2777 static inline void balance_callback(struct rq *rq)
2778 {
2779 }
2780 
2781 #endif
2782 
2783 /**
2784  * schedule_tail - first thing a freshly forked thread must call.
2785  * @prev: the thread we just switched away from.
2786  */
2787 asmlinkage __visible void schedule_tail(struct task_struct *prev)
2788 	__releases(rq->lock)
2789 {
2790 	struct rq *rq;
2791 
2792 	/*
2793 	 * New tasks start with FORK_PREEMPT_COUNT, see there and
2794 	 * finish_task_switch() for details.
2795 	 *
2796 	 * finish_task_switch() will drop rq->lock() and lower preempt_count
2797 	 * and the preempt_enable() will end up enabling preemption (on
2798 	 * PREEMPT_COUNT kernels).
2799 	 */
2800 
2801 	rq = finish_task_switch(prev);
2802 	balance_callback(rq);
2803 	preempt_enable();
2804 
2805 	if (current->set_child_tid)
2806 		put_user(task_pid_vnr(current), current->set_child_tid);
2807 }
2808 
2809 /*
2810  * context_switch - switch to the new MM and the new thread's register state.
2811  */
2812 static __always_inline struct rq *
2813 context_switch(struct rq *rq, struct task_struct *prev,
2814 	       struct task_struct *next, struct rq_flags *rf)
2815 {
2816 	struct mm_struct *mm, *oldmm;
2817 
2818 	prepare_task_switch(rq, prev, next);
2819 
2820 	mm = next->mm;
2821 	oldmm = prev->active_mm;
2822 	/*
2823 	 * For paravirt, this is coupled with an exit in switch_to to
2824 	 * combine the page table reload and the switch backend into
2825 	 * one hypercall.
2826 	 */
2827 	arch_start_context_switch(prev);
2828 
2829 	/*
2830 	 * If mm is non-NULL, we pass through switch_mm(). If mm is
2831 	 * NULL, we will pass through mmdrop() in finish_task_switch().
2832 	 * Both of these contain the full memory barrier required by
2833 	 * membarrier after storing to rq->curr, before returning to
2834 	 * user-space.
2835 	 */
2836 	if (!mm) {
2837 		next->active_mm = oldmm;
2838 		mmgrab(oldmm);
2839 		enter_lazy_tlb(oldmm, next);
2840 	} else
2841 		switch_mm_irqs_off(oldmm, mm, next);
2842 
2843 	if (!prev->mm) {
2844 		prev->active_mm = NULL;
2845 		rq->prev_mm = oldmm;
2846 	}
2847 
2848 	rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
2849 
2850 	prepare_lock_switch(rq, next, rf);
2851 
2852 	/* Here we just switch the register state and the stack. */
2853 	switch_to(prev, next, prev);
2854 	barrier();
2855 
2856 	return finish_task_switch(prev);
2857 }
2858 
2859 /*
2860  * nr_running and nr_context_switches:
2861  *
2862  * externally visible scheduler statistics: current number of runnable
2863  * threads, total number of context switches performed since bootup.
2864  */
2865 unsigned long nr_running(void)
2866 {
2867 	unsigned long i, sum = 0;
2868 
2869 	for_each_online_cpu(i)
2870 		sum += cpu_rq(i)->nr_running;
2871 
2872 	return sum;
2873 }
2874 
2875 /*
2876  * Check if only the current task is running on the CPU.
2877  *
2878  * Caution: this function does not check that the caller has disabled
2879  * preemption, thus the result might have a time-of-check-to-time-of-use
2880  * race.  The caller is responsible to use it correctly, for example:
2881  *
2882  * - from a non-preemptable section (of course)
2883  *
2884  * - from a thread that is bound to a single CPU
2885  *
2886  * - in a loop with very short iterations (e.g. a polling loop)
2887  */
2888 bool single_task_running(void)
2889 {
2890 	return raw_rq()->nr_running == 1;
2891 }
2892 EXPORT_SYMBOL(single_task_running);
2893 
2894 unsigned long long nr_context_switches(void)
2895 {
2896 	int i;
2897 	unsigned long long sum = 0;
2898 
2899 	for_each_possible_cpu(i)
2900 		sum += cpu_rq(i)->nr_switches;
2901 
2902 	return sum;
2903 }
2904 
2905 /*
2906  * IO-wait accounting, and how its mostly bollocks (on SMP).
2907  *
2908  * The idea behind IO-wait account is to account the idle time that we could
2909  * have spend running if it were not for IO. That is, if we were to improve the
2910  * storage performance, we'd have a proportional reduction in IO-wait time.
2911  *
2912  * This all works nicely on UP, where, when a task blocks on IO, we account
2913  * idle time as IO-wait, because if the storage were faster, it could've been
2914  * running and we'd not be idle.
2915  *
2916  * This has been extended to SMP, by doing the same for each CPU. This however
2917  * is broken.
2918  *
2919  * Imagine for instance the case where two tasks block on one CPU, only the one
2920  * CPU will have IO-wait accounted, while the other has regular idle. Even
2921  * though, if the storage were faster, both could've ran at the same time,
2922  * utilising both CPUs.
2923  *
2924  * This means, that when looking globally, the current IO-wait accounting on
2925  * SMP is a lower bound, by reason of under accounting.
2926  *
2927  * Worse, since the numbers are provided per CPU, they are sometimes
2928  * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
2929  * associated with any one particular CPU, it can wake to another CPU than it
2930  * blocked on. This means the per CPU IO-wait number is meaningless.
2931  *
2932  * Task CPU affinities can make all that even more 'interesting'.
2933  */
2934 
2935 unsigned long nr_iowait(void)
2936 {
2937 	unsigned long i, sum = 0;
2938 
2939 	for_each_possible_cpu(i)
2940 		sum += atomic_read(&cpu_rq(i)->nr_iowait);
2941 
2942 	return sum;
2943 }
2944 
2945 /*
2946  * Consumers of these two interfaces, like for example the cpufreq menu
2947  * governor are using nonsensical data. Boosting frequency for a CPU that has
2948  * IO-wait which might not even end up running the task when it does become
2949  * runnable.
2950  */
2951 
2952 unsigned long nr_iowait_cpu(int cpu)
2953 {
2954 	struct rq *this = cpu_rq(cpu);
2955 	return atomic_read(&this->nr_iowait);
2956 }
2957 
2958 void get_iowait_load(unsigned long *nr_waiters, unsigned long *load)
2959 {
2960 	struct rq *rq = this_rq();
2961 	*nr_waiters = atomic_read(&rq->nr_iowait);
2962 	*load = rq->load.weight;
2963 }
2964 
2965 #ifdef CONFIG_SMP
2966 
2967 /*
2968  * sched_exec - execve() is a valuable balancing opportunity, because at
2969  * this point the task has the smallest effective memory and cache footprint.
2970  */
2971 void sched_exec(void)
2972 {
2973 	struct task_struct *p = current;
2974 	unsigned long flags;
2975 	int dest_cpu;
2976 
2977 	raw_spin_lock_irqsave(&p->pi_lock, flags);
2978 	dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
2979 	if (dest_cpu == smp_processor_id())
2980 		goto unlock;
2981 
2982 	if (likely(cpu_active(dest_cpu))) {
2983 		struct migration_arg arg = { p, dest_cpu };
2984 
2985 		raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2986 		stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
2987 		return;
2988 	}
2989 unlock:
2990 	raw_spin_unlock_irqrestore(&p->pi_lock, flags);
2991 }
2992 
2993 #endif
2994 
2995 DEFINE_PER_CPU(struct kernel_stat, kstat);
2996 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
2997 
2998 EXPORT_PER_CPU_SYMBOL(kstat);
2999 EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
3000 
3001 /*
3002  * The function fair_sched_class.update_curr accesses the struct curr
3003  * and its field curr->exec_start; when called from task_sched_runtime(),
3004  * we observe a high rate of cache misses in practice.
3005  * Prefetching this data results in improved performance.
3006  */
3007 static inline void prefetch_curr_exec_start(struct task_struct *p)
3008 {
3009 #ifdef CONFIG_FAIR_GROUP_SCHED
3010 	struct sched_entity *curr = (&p->se)->cfs_rq->curr;
3011 #else
3012 	struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
3013 #endif
3014 	prefetch(curr);
3015 	prefetch(&curr->exec_start);
3016 }
3017 
3018 /*
3019  * Return accounted runtime for the task.
3020  * In case the task is currently running, return the runtime plus current's
3021  * pending runtime that have not been accounted yet.
3022  */
3023 unsigned long long task_sched_runtime(struct task_struct *p)
3024 {
3025 	struct rq_flags rf;
3026 	struct rq *rq;
3027 	u64 ns;
3028 
3029 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
3030 	/*
3031 	 * 64-bit doesn't need locks to atomically read a 64-bit value.
3032 	 * So we have a optimization chance when the task's delta_exec is 0.
3033 	 * Reading ->on_cpu is racy, but this is ok.
3034 	 *
3035 	 * If we race with it leaving CPU, we'll take a lock. So we're correct.
3036 	 * If we race with it entering CPU, unaccounted time is 0. This is
3037 	 * indistinguishable from the read occurring a few cycles earlier.
3038 	 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
3039 	 * been accounted, so we're correct here as well.
3040 	 */
3041 	if (!p->on_cpu || !task_on_rq_queued(p))
3042 		return p->se.sum_exec_runtime;
3043 #endif
3044 
3045 	rq = task_rq_lock(p, &rf);
3046 	/*
3047 	 * Must be ->curr _and_ ->on_rq.  If dequeued, we would
3048 	 * project cycles that may never be accounted to this
3049 	 * thread, breaking clock_gettime().
3050 	 */
3051 	if (task_current(rq, p) && task_on_rq_queued(p)) {
3052 		prefetch_curr_exec_start(p);
3053 		update_rq_clock(rq);
3054 		p->sched_class->update_curr(rq);
3055 	}
3056 	ns = p->se.sum_exec_runtime;
3057 	task_rq_unlock(rq, p, &rf);
3058 
3059 	return ns;
3060 }
3061 
3062 /*
3063  * This function gets called by the timer code, with HZ frequency.
3064  * We call it with interrupts disabled.
3065  */
3066 void scheduler_tick(void)
3067 {
3068 	int cpu = smp_processor_id();
3069 	struct rq *rq = cpu_rq(cpu);
3070 	struct task_struct *curr = rq->curr;
3071 	struct rq_flags rf;
3072 
3073 	sched_clock_tick();
3074 
3075 	rq_lock(rq, &rf);
3076 
3077 	update_rq_clock(rq);
3078 	curr->sched_class->task_tick(rq, curr, 0);
3079 	cpu_load_update_active(rq);
3080 	calc_global_load_tick(rq);
3081 
3082 	rq_unlock(rq, &rf);
3083 
3084 	perf_event_task_tick();
3085 
3086 #ifdef CONFIG_SMP
3087 	rq->idle_balance = idle_cpu(cpu);
3088 	trigger_load_balance(rq);
3089 #endif
3090 }
3091 
3092 #ifdef CONFIG_NO_HZ_FULL
3093 
3094 struct tick_work {
3095 	int			cpu;
3096 	struct delayed_work	work;
3097 };
3098 
3099 static struct tick_work __percpu *tick_work_cpu;
3100 
3101 static void sched_tick_remote(struct work_struct *work)
3102 {
3103 	struct delayed_work *dwork = to_delayed_work(work);
3104 	struct tick_work *twork = container_of(dwork, struct tick_work, work);
3105 	int cpu = twork->cpu;
3106 	struct rq *rq = cpu_rq(cpu);
3107 	struct task_struct *curr;
3108 	struct rq_flags rf;
3109 	u64 delta;
3110 
3111 	/*
3112 	 * Handle the tick only if it appears the remote CPU is running in full
3113 	 * dynticks mode. The check is racy by nature, but missing a tick or
3114 	 * having one too much is no big deal because the scheduler tick updates
3115 	 * statistics and checks timeslices in a time-independent way, regardless
3116 	 * of when exactly it is running.
3117 	 */
3118 	if (idle_cpu(cpu) || !tick_nohz_tick_stopped_cpu(cpu))
3119 		goto out_requeue;
3120 
3121 	rq_lock_irq(rq, &rf);
3122 	curr = rq->curr;
3123 	if (is_idle_task(curr))
3124 		goto out_unlock;
3125 
3126 	update_rq_clock(rq);
3127 	delta = rq_clock_task(rq) - curr->se.exec_start;
3128 
3129 	/*
3130 	 * Make sure the next tick runs within a reasonable
3131 	 * amount of time.
3132 	 */
3133 	WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 3);
3134 	curr->sched_class->task_tick(rq, curr, 0);
3135 
3136 out_unlock:
3137 	rq_unlock_irq(rq, &rf);
3138 
3139 out_requeue:
3140 	/*
3141 	 * Run the remote tick once per second (1Hz). This arbitrary
3142 	 * frequency is large enough to avoid overload but short enough
3143 	 * to keep scheduler internal stats reasonably up to date.
3144 	 */
3145 	queue_delayed_work(system_unbound_wq, dwork, HZ);
3146 }
3147 
3148 static void sched_tick_start(int cpu)
3149 {
3150 	struct tick_work *twork;
3151 
3152 	if (housekeeping_cpu(cpu, HK_FLAG_TICK))
3153 		return;
3154 
3155 	WARN_ON_ONCE(!tick_work_cpu);
3156 
3157 	twork = per_cpu_ptr(tick_work_cpu, cpu);
3158 	twork->cpu = cpu;
3159 	INIT_DELAYED_WORK(&twork->work, sched_tick_remote);
3160 	queue_delayed_work(system_unbound_wq, &twork->work, HZ);
3161 }
3162 
3163 #ifdef CONFIG_HOTPLUG_CPU
3164 static void sched_tick_stop(int cpu)
3165 {
3166 	struct tick_work *twork;
3167 
3168 	if (housekeeping_cpu(cpu, HK_FLAG_TICK))
3169 		return;
3170 
3171 	WARN_ON_ONCE(!tick_work_cpu);
3172 
3173 	twork = per_cpu_ptr(tick_work_cpu, cpu);
3174 	cancel_delayed_work_sync(&twork->work);
3175 }
3176 #endif /* CONFIG_HOTPLUG_CPU */
3177 
3178 int __init sched_tick_offload_init(void)
3179 {
3180 	tick_work_cpu = alloc_percpu(struct tick_work);
3181 	BUG_ON(!tick_work_cpu);
3182 
3183 	return 0;
3184 }
3185 
3186 #else /* !CONFIG_NO_HZ_FULL */
3187 static inline void sched_tick_start(int cpu) { }
3188 static inline void sched_tick_stop(int cpu) { }
3189 #endif
3190 
3191 #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \
3192 				defined(CONFIG_PREEMPT_TRACER))
3193 /*
3194  * If the value passed in is equal to the current preempt count
3195  * then we just disabled preemption. Start timing the latency.
3196  */
3197 static inline void preempt_latency_start(int val)
3198 {
3199 	if (preempt_count() == val) {
3200 		unsigned long ip = get_lock_parent_ip();
3201 #ifdef CONFIG_DEBUG_PREEMPT
3202 		current->preempt_disable_ip = ip;
3203 #endif
3204 		trace_preempt_off(CALLER_ADDR0, ip);
3205 	}
3206 }
3207 
3208 void preempt_count_add(int val)
3209 {
3210 #ifdef CONFIG_DEBUG_PREEMPT
3211 	/*
3212 	 * Underflow?
3213 	 */
3214 	if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
3215 		return;
3216 #endif
3217 	__preempt_count_add(val);
3218 #ifdef CONFIG_DEBUG_PREEMPT
3219 	/*
3220 	 * Spinlock count overflowing soon?
3221 	 */
3222 	DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
3223 				PREEMPT_MASK - 10);
3224 #endif
3225 	preempt_latency_start(val);
3226 }
3227 EXPORT_SYMBOL(preempt_count_add);
3228 NOKPROBE_SYMBOL(preempt_count_add);
3229 
3230 /*
3231  * If the value passed in equals to the current preempt count
3232  * then we just enabled preemption. Stop timing the latency.
3233  */
3234 static inline void preempt_latency_stop(int val)
3235 {
3236 	if (preempt_count() == val)
3237 		trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
3238 }
3239 
3240 void preempt_count_sub(int val)
3241 {
3242 #ifdef CONFIG_DEBUG_PREEMPT
3243 	/*
3244 	 * Underflow?
3245 	 */
3246 	if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
3247 		return;
3248 	/*
3249 	 * Is the spinlock portion underflowing?
3250 	 */
3251 	if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
3252 			!(preempt_count() & PREEMPT_MASK)))
3253 		return;
3254 #endif
3255 
3256 	preempt_latency_stop(val);
3257 	__preempt_count_sub(val);
3258 }
3259 EXPORT_SYMBOL(preempt_count_sub);
3260 NOKPROBE_SYMBOL(preempt_count_sub);
3261 
3262 #else
3263 static inline void preempt_latency_start(int val) { }
3264 static inline void preempt_latency_stop(int val) { }
3265 #endif
3266 
3267 static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
3268 {
3269 #ifdef CONFIG_DEBUG_PREEMPT
3270 	return p->preempt_disable_ip;
3271 #else
3272 	return 0;
3273 #endif
3274 }
3275 
3276 /*
3277  * Print scheduling while atomic bug:
3278  */
3279 static noinline void __schedule_bug(struct task_struct *prev)
3280 {
3281 	/* Save this before calling printk(), since that will clobber it */
3282 	unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
3283 
3284 	if (oops_in_progress)
3285 		return;
3286 
3287 	printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
3288 		prev->comm, prev->pid, preempt_count());
3289 
3290 	debug_show_held_locks(prev);
3291 	print_modules();
3292 	if (irqs_disabled())
3293 		print_irqtrace_events(prev);
3294 	if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
3295 	    && in_atomic_preempt_off()) {
3296 		pr_err("Preemption disabled at:");
3297 		print_ip_sym(preempt_disable_ip);
3298 		pr_cont("\n");
3299 	}
3300 	if (panic_on_warn)
3301 		panic("scheduling while atomic\n");
3302 
3303 	dump_stack();
3304 	add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
3305 }
3306 
3307 /*
3308  * Various schedule()-time debugging checks and statistics:
3309  */
3310 static inline void schedule_debug(struct task_struct *prev)
3311 {
3312 #ifdef CONFIG_SCHED_STACK_END_CHECK
3313 	if (task_stack_end_corrupted(prev))
3314 		panic("corrupted stack end detected inside scheduler\n");
3315 #endif
3316 
3317 	if (unlikely(in_atomic_preempt_off())) {
3318 		__schedule_bug(prev);
3319 		preempt_count_set(PREEMPT_DISABLED);
3320 	}
3321 	rcu_sleep_check();
3322 
3323 	profile_hit(SCHED_PROFILING, __builtin_return_address(0));
3324 
3325 	schedstat_inc(this_rq()->sched_count);
3326 }
3327 
3328 /*
3329  * Pick up the highest-prio task:
3330  */
3331 static inline struct task_struct *
3332 pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
3333 {
3334 	const struct sched_class *class;
3335 	struct task_struct *p;
3336 
3337 	/*
3338 	 * Optimization: we know that if all tasks are in the fair class we can
3339 	 * call that function directly, but only if the @prev task wasn't of a
3340 	 * higher scheduling class, because otherwise those loose the
3341 	 * opportunity to pull in more work from other CPUs.
3342 	 */
3343 	if (likely((prev->sched_class == &idle_sched_class ||
3344 		    prev->sched_class == &fair_sched_class) &&
3345 		   rq->nr_running == rq->cfs.h_nr_running)) {
3346 
3347 		p = fair_sched_class.pick_next_task(rq, prev, rf);
3348 		if (unlikely(p == RETRY_TASK))
3349 			goto again;
3350 
3351 		/* Assumes fair_sched_class->next == idle_sched_class */
3352 		if (unlikely(!p))
3353 			p = idle_sched_class.pick_next_task(rq, prev, rf);
3354 
3355 		return p;
3356 	}
3357 
3358 again:
3359 	for_each_class(class) {
3360 		p = class->pick_next_task(rq, prev, rf);
3361 		if (p) {
3362 			if (unlikely(p == RETRY_TASK))
3363 				goto again;
3364 			return p;
3365 		}
3366 	}
3367 
3368 	/* The idle class should always have a runnable task: */
3369 	BUG();
3370 }
3371 
3372 /*
3373  * __schedule() is the main scheduler function.
3374  *
3375  * The main means of driving the scheduler and thus entering this function are:
3376  *
3377  *   1. Explicit blocking: mutex, semaphore, waitqueue, etc.
3378  *
3379  *   2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
3380  *      paths. For example, see arch/x86/entry_64.S.
3381  *
3382  *      To drive preemption between tasks, the scheduler sets the flag in timer
3383  *      interrupt handler scheduler_tick().
3384  *
3385  *   3. Wakeups don't really cause entry into schedule(). They add a
3386  *      task to the run-queue and that's it.
3387  *
3388  *      Now, if the new task added to the run-queue preempts the current
3389  *      task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
3390  *      called on the nearest possible occasion:
3391  *
3392  *       - If the kernel is preemptible (CONFIG_PREEMPT=y):
3393  *
3394  *         - in syscall or exception context, at the next outmost
3395  *           preempt_enable(). (this might be as soon as the wake_up()'s
3396  *           spin_unlock()!)
3397  *
3398  *         - in IRQ context, return from interrupt-handler to
3399  *           preemptible context
3400  *
3401  *       - If the kernel is not preemptible (CONFIG_PREEMPT is not set)
3402  *         then at the next:
3403  *
3404  *          - cond_resched() call
3405  *          - explicit schedule() call
3406  *          - return from syscall or exception to user-space
3407  *          - return from interrupt-handler to user-space
3408  *
3409  * WARNING: must be called with preemption disabled!
3410  */
3411 static void __sched notrace __schedule(bool preempt)
3412 {
3413 	struct task_struct *prev, *next;
3414 	unsigned long *switch_count;
3415 	struct rq_flags rf;
3416 	struct rq *rq;
3417 	int cpu;
3418 
3419 	cpu = smp_processor_id();
3420 	rq = cpu_rq(cpu);
3421 	prev = rq->curr;
3422 
3423 	schedule_debug(prev);
3424 
3425 	if (sched_feat(HRTICK))
3426 		hrtick_clear(rq);
3427 
3428 	local_irq_disable();
3429 	rcu_note_context_switch(preempt);
3430 
3431 	/*
3432 	 * Make sure that signal_pending_state()->signal_pending() below
3433 	 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
3434 	 * done by the caller to avoid the race with signal_wake_up().
3435 	 *
3436 	 * The membarrier system call requires a full memory barrier
3437 	 * after coming from user-space, before storing to rq->curr.
3438 	 */
3439 	rq_lock(rq, &rf);
3440 	smp_mb__after_spinlock();
3441 
3442 	/* Promote REQ to ACT */
3443 	rq->clock_update_flags <<= 1;
3444 	update_rq_clock(rq);
3445 
3446 	switch_count = &prev->nivcsw;
3447 	if (!preempt && prev->state) {
3448 		if (unlikely(signal_pending_state(prev->state, prev))) {
3449 			prev->state = TASK_RUNNING;
3450 		} else {
3451 			deactivate_task(rq, prev, DEQUEUE_SLEEP | DEQUEUE_NOCLOCK);
3452 			prev->on_rq = 0;
3453 
3454 			if (prev->in_iowait) {
3455 				atomic_inc(&rq->nr_iowait);
3456 				delayacct_blkio_start();
3457 			}
3458 
3459 			/*
3460 			 * If a worker went to sleep, notify and ask workqueue
3461 			 * whether it wants to wake up a task to maintain
3462 			 * concurrency.
3463 			 */
3464 			if (prev->flags & PF_WQ_WORKER) {
3465 				struct task_struct *to_wakeup;
3466 
3467 				to_wakeup = wq_worker_sleeping(prev);
3468 				if (to_wakeup)
3469 					try_to_wake_up_local(to_wakeup, &rf);
3470 			}
3471 		}
3472 		switch_count = &prev->nvcsw;
3473 	}
3474 
3475 	next = pick_next_task(rq, prev, &rf);
3476 	clear_tsk_need_resched(prev);
3477 	clear_preempt_need_resched();
3478 
3479 	if (likely(prev != next)) {
3480 		rq->nr_switches++;
3481 		rq->curr = next;
3482 		/*
3483 		 * The membarrier system call requires each architecture
3484 		 * to have a full memory barrier after updating
3485 		 * rq->curr, before returning to user-space.
3486 		 *
3487 		 * Here are the schemes providing that barrier on the
3488 		 * various architectures:
3489 		 * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC.
3490 		 *   switch_mm() rely on membarrier_arch_switch_mm() on PowerPC.
3491 		 * - finish_lock_switch() for weakly-ordered
3492 		 *   architectures where spin_unlock is a full barrier,
3493 		 * - switch_to() for arm64 (weakly-ordered, spin_unlock
3494 		 *   is a RELEASE barrier),
3495 		 */
3496 		++*switch_count;
3497 
3498 		trace_sched_switch(preempt, prev, next);
3499 
3500 		/* Also unlocks the rq: */
3501 		rq = context_switch(rq, prev, next, &rf);
3502 	} else {
3503 		rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
3504 		rq_unlock_irq(rq, &rf);
3505 	}
3506 
3507 	balance_callback(rq);
3508 }
3509 
3510 void __noreturn do_task_dead(void)
3511 {
3512 	/* Causes final put_task_struct in finish_task_switch(): */
3513 	set_special_state(TASK_DEAD);
3514 
3515 	/* Tell freezer to ignore us: */
3516 	current->flags |= PF_NOFREEZE;
3517 
3518 	__schedule(false);
3519 	BUG();
3520 
3521 	/* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
3522 	for (;;)
3523 		cpu_relax();
3524 }
3525 
3526 static inline void sched_submit_work(struct task_struct *tsk)
3527 {
3528 	if (!tsk->state || tsk_is_pi_blocked(tsk))
3529 		return;
3530 	/*
3531 	 * If we are going to sleep and we have plugged IO queued,
3532 	 * make sure to submit it to avoid deadlocks.
3533 	 */
3534 	if (blk_needs_flush_plug(tsk))
3535 		blk_schedule_flush_plug(tsk);
3536 }
3537 
3538 asmlinkage __visible void __sched schedule(void)
3539 {
3540 	struct task_struct *tsk = current;
3541 
3542 	sched_submit_work(tsk);
3543 	do {
3544 		preempt_disable();
3545 		__schedule(false);
3546 		sched_preempt_enable_no_resched();
3547 	} while (need_resched());
3548 }
3549 EXPORT_SYMBOL(schedule);
3550 
3551 /*
3552  * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
3553  * state (have scheduled out non-voluntarily) by making sure that all
3554  * tasks have either left the run queue or have gone into user space.
3555  * As idle tasks do not do either, they must not ever be preempted
3556  * (schedule out non-voluntarily).
3557  *
3558  * schedule_idle() is similar to schedule_preempt_disable() except that it
3559  * never enables preemption because it does not call sched_submit_work().
3560  */
3561 void __sched schedule_idle(void)
3562 {
3563 	/*
3564 	 * As this skips calling sched_submit_work(), which the idle task does
3565 	 * regardless because that function is a nop when the task is in a
3566 	 * TASK_RUNNING state, make sure this isn't used someplace that the
3567 	 * current task can be in any other state. Note, idle is always in the
3568 	 * TASK_RUNNING state.
3569 	 */
3570 	WARN_ON_ONCE(current->state);
3571 	do {
3572 		__schedule(false);
3573 	} while (need_resched());
3574 }
3575 
3576 #ifdef CONFIG_CONTEXT_TRACKING
3577 asmlinkage __visible void __sched schedule_user(void)
3578 {
3579 	/*
3580 	 * If we come here after a random call to set_need_resched(),
3581 	 * or we have been woken up remotely but the IPI has not yet arrived,
3582 	 * we haven't yet exited the RCU idle mode. Do it here manually until
3583 	 * we find a better solution.
3584 	 *
3585 	 * NB: There are buggy callers of this function.  Ideally we
3586 	 * should warn if prev_state != CONTEXT_USER, but that will trigger
3587 	 * too frequently to make sense yet.
3588 	 */
3589 	enum ctx_state prev_state = exception_enter();
3590 	schedule();
3591 	exception_exit(prev_state);
3592 }
3593 #endif
3594 
3595 /**
3596  * schedule_preempt_disabled - called with preemption disabled
3597  *
3598  * Returns with preemption disabled. Note: preempt_count must be 1
3599  */
3600 void __sched schedule_preempt_disabled(void)
3601 {
3602 	sched_preempt_enable_no_resched();
3603 	schedule();
3604 	preempt_disable();
3605 }
3606 
3607 static void __sched notrace preempt_schedule_common(void)
3608 {
3609 	do {
3610 		/*
3611 		 * Because the function tracer can trace preempt_count_sub()
3612 		 * and it also uses preempt_enable/disable_notrace(), if
3613 		 * NEED_RESCHED is set, the preempt_enable_notrace() called
3614 		 * by the function tracer will call this function again and
3615 		 * cause infinite recursion.
3616 		 *
3617 		 * Preemption must be disabled here before the function
3618 		 * tracer can trace. Break up preempt_disable() into two
3619 		 * calls. One to disable preemption without fear of being
3620 		 * traced. The other to still record the preemption latency,
3621 		 * which can also be traced by the function tracer.
3622 		 */
3623 		preempt_disable_notrace();
3624 		preempt_latency_start(1);
3625 		__schedule(true);
3626 		preempt_latency_stop(1);
3627 		preempt_enable_no_resched_notrace();
3628 
3629 		/*
3630 		 * Check again in case we missed a preemption opportunity
3631 		 * between schedule and now.
3632 		 */
3633 	} while (need_resched());
3634 }
3635 
3636 #ifdef CONFIG_PREEMPT
3637 /*
3638  * this is the entry point to schedule() from in-kernel preemption
3639  * off of preempt_enable. Kernel preemptions off return from interrupt
3640  * occur there and call schedule directly.
3641  */
3642 asmlinkage __visible void __sched notrace preempt_schedule(void)
3643 {
3644 	/*
3645 	 * If there is a non-zero preempt_count or interrupts are disabled,
3646 	 * we do not want to preempt the current task. Just return..
3647 	 */
3648 	if (likely(!preemptible()))
3649 		return;
3650 
3651 	preempt_schedule_common();
3652 }
3653 NOKPROBE_SYMBOL(preempt_schedule);
3654 EXPORT_SYMBOL(preempt_schedule);
3655 
3656 /**
3657  * preempt_schedule_notrace - preempt_schedule called by tracing
3658  *
3659  * The tracing infrastructure uses preempt_enable_notrace to prevent
3660  * recursion and tracing preempt enabling caused by the tracing
3661  * infrastructure itself. But as tracing can happen in areas coming
3662  * from userspace or just about to enter userspace, a preempt enable
3663  * can occur before user_exit() is called. This will cause the scheduler
3664  * to be called when the system is still in usermode.
3665  *
3666  * To prevent this, the preempt_enable_notrace will use this function
3667  * instead of preempt_schedule() to exit user context if needed before
3668  * calling the scheduler.
3669  */
3670 asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
3671 {
3672 	enum ctx_state prev_ctx;
3673 
3674 	if (likely(!preemptible()))
3675 		return;
3676 
3677 	do {
3678 		/*
3679 		 * Because the function tracer can trace preempt_count_sub()
3680 		 * and it also uses preempt_enable/disable_notrace(), if
3681 		 * NEED_RESCHED is set, the preempt_enable_notrace() called
3682 		 * by the function tracer will call this function again and
3683 		 * cause infinite recursion.
3684 		 *
3685 		 * Preemption must be disabled here before the function
3686 		 * tracer can trace. Break up preempt_disable() into two
3687 		 * calls. One to disable preemption without fear of being
3688 		 * traced. The other to still record the preemption latency,
3689 		 * which can also be traced by the function tracer.
3690 		 */
3691 		preempt_disable_notrace();
3692 		preempt_latency_start(1);
3693 		/*
3694 		 * Needs preempt disabled in case user_exit() is traced
3695 		 * and the tracer calls preempt_enable_notrace() causing
3696 		 * an infinite recursion.
3697 		 */
3698 		prev_ctx = exception_enter();
3699 		__schedule(true);
3700 		exception_exit(prev_ctx);
3701 
3702 		preempt_latency_stop(1);
3703 		preempt_enable_no_resched_notrace();
3704 	} while (need_resched());
3705 }
3706 EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
3707 
3708 #endif /* CONFIG_PREEMPT */
3709 
3710 /*
3711  * this is the entry point to schedule() from kernel preemption
3712  * off of irq context.
3713  * Note, that this is called and return with irqs disabled. This will
3714  * protect us against recursive calling from irq.
3715  */
3716 asmlinkage __visible void __sched preempt_schedule_irq(void)
3717 {
3718 	enum ctx_state prev_state;
3719 
3720 	/* Catch callers which need to be fixed */
3721 	BUG_ON(preempt_count() || !irqs_disabled());
3722 
3723 	prev_state = exception_enter();
3724 
3725 	do {
3726 		preempt_disable();
3727 		local_irq_enable();
3728 		__schedule(true);
3729 		local_irq_disable();
3730 		sched_preempt_enable_no_resched();
3731 	} while (need_resched());
3732 
3733 	exception_exit(prev_state);
3734 }
3735 
3736 int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags,
3737 			  void *key)
3738 {
3739 	return try_to_wake_up(curr->private, mode, wake_flags);
3740 }
3741 EXPORT_SYMBOL(default_wake_function);
3742 
3743 #ifdef CONFIG_RT_MUTEXES
3744 
3745 static inline int __rt_effective_prio(struct task_struct *pi_task, int prio)
3746 {
3747 	if (pi_task)
3748 		prio = min(prio, pi_task->prio);
3749 
3750 	return prio;
3751 }
3752 
3753 static inline int rt_effective_prio(struct task_struct *p, int prio)
3754 {
3755 	struct task_struct *pi_task = rt_mutex_get_top_task(p);
3756 
3757 	return __rt_effective_prio(pi_task, prio);
3758 }
3759 
3760 /*
3761  * rt_mutex_setprio - set the current priority of a task
3762  * @p: task to boost
3763  * @pi_task: donor task
3764  *
3765  * This function changes the 'effective' priority of a task. It does
3766  * not touch ->normal_prio like __setscheduler().
3767  *
3768  * Used by the rt_mutex code to implement priority inheritance
3769  * logic. Call site only calls if the priority of the task changed.
3770  */
3771 void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
3772 {
3773 	int prio, oldprio, queued, running, queue_flag =
3774 		DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
3775 	const struct sched_class *prev_class;
3776 	struct rq_flags rf;
3777 	struct rq *rq;
3778 
3779 	/* XXX used to be waiter->prio, not waiter->task->prio */
3780 	prio = __rt_effective_prio(pi_task, p->normal_prio);
3781 
3782 	/*
3783 	 * If nothing changed; bail early.
3784 	 */
3785 	if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
3786 		return;
3787 
3788 	rq = __task_rq_lock(p, &rf);
3789 	update_rq_clock(rq);
3790 	/*
3791 	 * Set under pi_lock && rq->lock, such that the value can be used under
3792 	 * either lock.
3793 	 *
3794 	 * Note that there is loads of tricky to make this pointer cache work
3795 	 * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
3796 	 * ensure a task is de-boosted (pi_task is set to NULL) before the
3797 	 * task is allowed to run again (and can exit). This ensures the pointer
3798 	 * points to a blocked task -- which guaratees the task is present.
3799 	 */
3800 	p->pi_top_task = pi_task;
3801 
3802 	/*
3803 	 * For FIFO/RR we only need to set prio, if that matches we're done.
3804 	 */
3805 	if (prio == p->prio && !dl_prio(prio))
3806 		goto out_unlock;
3807 
3808 	/*
3809 	 * Idle task boosting is a nono in general. There is one
3810 	 * exception, when PREEMPT_RT and NOHZ is active:
3811 	 *
3812 	 * The idle task calls get_next_timer_interrupt() and holds
3813 	 * the timer wheel base->lock on the CPU and another CPU wants
3814 	 * to access the timer (probably to cancel it). We can safely
3815 	 * ignore the boosting request, as the idle CPU runs this code
3816 	 * with interrupts disabled and will complete the lock
3817 	 * protected section without being interrupted. So there is no
3818 	 * real need to boost.
3819 	 */
3820 	if (unlikely(p == rq->idle)) {
3821 		WARN_ON(p != rq->curr);
3822 		WARN_ON(p->pi_blocked_on);
3823 		goto out_unlock;
3824 	}
3825 
3826 	trace_sched_pi_setprio(p, pi_task);
3827 	oldprio = p->prio;
3828 
3829 	if (oldprio == prio)
3830 		queue_flag &= ~DEQUEUE_MOVE;
3831 
3832 	prev_class = p->sched_class;
3833 	queued = task_on_rq_queued(p);
3834 	running = task_current(rq, p);
3835 	if (queued)
3836 		dequeue_task(rq, p, queue_flag);
3837 	if (running)
3838 		put_prev_task(rq, p);
3839 
3840 	/*
3841 	 * Boosting condition are:
3842 	 * 1. -rt task is running and holds mutex A
3843 	 *      --> -dl task blocks on mutex A
3844 	 *
3845 	 * 2. -dl task is running and holds mutex A
3846 	 *      --> -dl task blocks on mutex A and could preempt the
3847 	 *          running task
3848 	 */
3849 	if (dl_prio(prio)) {
3850 		if (!dl_prio(p->normal_prio) ||
3851 		    (pi_task && dl_entity_preempt(&pi_task->dl, &p->dl))) {
3852 			p->dl.dl_boosted = 1;
3853 			queue_flag |= ENQUEUE_REPLENISH;
3854 		} else
3855 			p->dl.dl_boosted = 0;
3856 		p->sched_class = &dl_sched_class;
3857 	} else if (rt_prio(prio)) {
3858 		if (dl_prio(oldprio))
3859 			p->dl.dl_boosted = 0;
3860 		if (oldprio < prio)
3861 			queue_flag |= ENQUEUE_HEAD;
3862 		p->sched_class = &rt_sched_class;
3863 	} else {
3864 		if (dl_prio(oldprio))
3865 			p->dl.dl_boosted = 0;
3866 		if (rt_prio(oldprio))
3867 			p->rt.timeout = 0;
3868 		p->sched_class = &fair_sched_class;
3869 	}
3870 
3871 	p->prio = prio;
3872 
3873 	if (queued)
3874 		enqueue_task(rq, p, queue_flag);
3875 	if (running)
3876 		set_curr_task(rq, p);
3877 
3878 	check_class_changed(rq, p, prev_class, oldprio);
3879 out_unlock:
3880 	/* Avoid rq from going away on us: */
3881 	preempt_disable();
3882 	__task_rq_unlock(rq, &rf);
3883 
3884 	balance_callback(rq);
3885 	preempt_enable();
3886 }
3887 #else
3888 static inline int rt_effective_prio(struct task_struct *p, int prio)
3889 {
3890 	return prio;
3891 }
3892 #endif
3893 
3894 void set_user_nice(struct task_struct *p, long nice)
3895 {
3896 	bool queued, running;
3897 	int old_prio, delta;
3898 	struct rq_flags rf;
3899 	struct rq *rq;
3900 
3901 	if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
3902 		return;
3903 	/*
3904 	 * We have to be careful, if called from sys_setpriority(),
3905 	 * the task might be in the middle of scheduling on another CPU.
3906 	 */
3907 	rq = task_rq_lock(p, &rf);
3908 	update_rq_clock(rq);
3909 
3910 	/*
3911 	 * The RT priorities are set via sched_setscheduler(), but we still
3912 	 * allow the 'normal' nice value to be set - but as expected
3913 	 * it wont have any effect on scheduling until the task is
3914 	 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
3915 	 */
3916 	if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
3917 		p->static_prio = NICE_TO_PRIO(nice);
3918 		goto out_unlock;
3919 	}
3920 	queued = task_on_rq_queued(p);
3921 	running = task_current(rq, p);
3922 	if (queued)
3923 		dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
3924 	if (running)
3925 		put_prev_task(rq, p);
3926 
3927 	p->static_prio = NICE_TO_PRIO(nice);
3928 	set_load_weight(p, true);
3929 	old_prio = p->prio;
3930 	p->prio = effective_prio(p);
3931 	delta = p->prio - old_prio;
3932 
3933 	if (queued) {
3934 		enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
3935 		/*
3936 		 * If the task increased its priority or is running and
3937 		 * lowered its priority, then reschedule its CPU:
3938 		 */
3939 		if (delta < 0 || (delta > 0 && task_running(rq, p)))
3940 			resched_curr(rq);
3941 	}
3942 	if (running)
3943 		set_curr_task(rq, p);
3944 out_unlock:
3945 	task_rq_unlock(rq, p, &rf);
3946 }
3947 EXPORT_SYMBOL(set_user_nice);
3948 
3949 /*
3950  * can_nice - check if a task can reduce its nice value
3951  * @p: task
3952  * @nice: nice value
3953  */
3954 int can_nice(const struct task_struct *p, const int nice)
3955 {
3956 	/* Convert nice value [19,-20] to rlimit style value [1,40]: */
3957 	int nice_rlim = nice_to_rlimit(nice);
3958 
3959 	return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
3960 		capable(CAP_SYS_NICE));
3961 }
3962 
3963 #ifdef __ARCH_WANT_SYS_NICE
3964 
3965 /*
3966  * sys_nice - change the priority of the current process.
3967  * @increment: priority increment
3968  *
3969  * sys_setpriority is a more generic, but much slower function that
3970  * does similar things.
3971  */
3972 SYSCALL_DEFINE1(nice, int, increment)
3973 {
3974 	long nice, retval;
3975 
3976 	/*
3977 	 * Setpriority might change our priority at the same moment.
3978 	 * We don't have to worry. Conceptually one call occurs first
3979 	 * and we have a single winner.
3980 	 */
3981 	increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
3982 	nice = task_nice(current) + increment;
3983 
3984 	nice = clamp_val(nice, MIN_NICE, MAX_NICE);
3985 	if (increment < 0 && !can_nice(current, nice))
3986 		return -EPERM;
3987 
3988 	retval = security_task_setnice(current, nice);
3989 	if (retval)
3990 		return retval;
3991 
3992 	set_user_nice(current, nice);
3993 	return 0;
3994 }
3995 
3996 #endif
3997 
3998 /**
3999  * task_prio - return the priority value of a given task.
4000  * @p: the task in question.
4001  *
4002  * Return: The priority value as seen by users in /proc.
4003  * RT tasks are offset by -200. Normal tasks are centered
4004  * around 0, value goes from -16 to +15.
4005  */
4006 int task_prio(const struct task_struct *p)
4007 {
4008 	return p->prio - MAX_RT_PRIO;
4009 }
4010 
4011 /**
4012  * idle_cpu - is a given CPU idle currently?
4013  * @cpu: the processor in question.
4014  *
4015  * Return: 1 if the CPU is currently idle. 0 otherwise.
4016  */
4017 int idle_cpu(int cpu)
4018 {
4019 	struct rq *rq = cpu_rq(cpu);
4020 
4021 	if (rq->curr != rq->idle)
4022 		return 0;
4023 
4024 	if (rq->nr_running)
4025 		return 0;
4026 
4027 #ifdef CONFIG_SMP
4028 	if (!llist_empty(&rq->wake_list))
4029 		return 0;
4030 #endif
4031 
4032 	return 1;
4033 }
4034 
4035 /**
4036  * available_idle_cpu - is a given CPU idle for enqueuing work.
4037  * @cpu: the CPU in question.
4038  *
4039  * Return: 1 if the CPU is currently idle. 0 otherwise.
4040  */
4041 int available_idle_cpu(int cpu)
4042 {
4043 	if (!idle_cpu(cpu))
4044 		return 0;
4045 
4046 	if (vcpu_is_preempted(cpu))
4047 		return 0;
4048 
4049 	return 1;
4050 }
4051 
4052 /**
4053  * idle_task - return the idle task for a given CPU.
4054  * @cpu: the processor in question.
4055  *
4056  * Return: The idle task for the CPU @cpu.
4057  */
4058 struct task_struct *idle_task(int cpu)
4059 {
4060 	return cpu_rq(cpu)->idle;
4061 }
4062 
4063 /**
4064  * find_process_by_pid - find a process with a matching PID value.
4065  * @pid: the pid in question.
4066  *
4067  * The task of @pid, if found. %NULL otherwise.
4068  */
4069 static struct task_struct *find_process_by_pid(pid_t pid)
4070 {
4071 	return pid ? find_task_by_vpid(pid) : current;
4072 }
4073 
4074 /*
4075  * sched_setparam() passes in -1 for its policy, to let the functions
4076  * it calls know not to change it.
4077  */
4078 #define SETPARAM_POLICY	-1
4079 
4080 static void __setscheduler_params(struct task_struct *p,
4081 		const struct sched_attr *attr)
4082 {
4083 	int policy = attr->sched_policy;
4084 
4085 	if (policy == SETPARAM_POLICY)
4086 		policy = p->policy;
4087 
4088 	p->policy = policy;
4089 
4090 	if (dl_policy(policy))
4091 		__setparam_dl(p, attr);
4092 	else if (fair_policy(policy))
4093 		p->static_prio = NICE_TO_PRIO(attr->sched_nice);
4094 
4095 	/*
4096 	 * __sched_setscheduler() ensures attr->sched_priority == 0 when
4097 	 * !rt_policy. Always setting this ensures that things like
4098 	 * getparam()/getattr() don't report silly values for !rt tasks.
4099 	 */
4100 	p->rt_priority = attr->sched_priority;
4101 	p->normal_prio = normal_prio(p);
4102 	set_load_weight(p, true);
4103 }
4104 
4105 /* Actually do priority change: must hold pi & rq lock. */
4106 static void __setscheduler(struct rq *rq, struct task_struct *p,
4107 			   const struct sched_attr *attr, bool keep_boost)
4108 {
4109 	__setscheduler_params(p, attr);
4110 
4111 	/*
4112 	 * Keep a potential priority boosting if called from
4113 	 * sched_setscheduler().
4114 	 */
4115 	p->prio = normal_prio(p);
4116 	if (keep_boost)
4117 		p->prio = rt_effective_prio(p, p->prio);
4118 
4119 	if (dl_prio(p->prio))
4120 		p->sched_class = &dl_sched_class;
4121 	else if (rt_prio(p->prio))
4122 		p->sched_class = &rt_sched_class;
4123 	else
4124 		p->sched_class = &fair_sched_class;
4125 }
4126 
4127 /*
4128  * Check the target process has a UID that matches the current process's:
4129  */
4130 static bool check_same_owner(struct task_struct *p)
4131 {
4132 	const struct cred *cred = current_cred(), *pcred;
4133 	bool match;
4134 
4135 	rcu_read_lock();
4136 	pcred = __task_cred(p);
4137 	match = (uid_eq(cred->euid, pcred->euid) ||
4138 		 uid_eq(cred->euid, pcred->uid));
4139 	rcu_read_unlock();
4140 	return match;
4141 }
4142 
4143 static int __sched_setscheduler(struct task_struct *p,
4144 				const struct sched_attr *attr,
4145 				bool user, bool pi)
4146 {
4147 	int newprio = dl_policy(attr->sched_policy) ? MAX_DL_PRIO - 1 :
4148 		      MAX_RT_PRIO - 1 - attr->sched_priority;
4149 	int retval, oldprio, oldpolicy = -1, queued, running;
4150 	int new_effective_prio, policy = attr->sched_policy;
4151 	const struct sched_class *prev_class;
4152 	struct rq_flags rf;
4153 	int reset_on_fork;
4154 	int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
4155 	struct rq *rq;
4156 
4157 	/* The pi code expects interrupts enabled */
4158 	BUG_ON(pi && in_interrupt());
4159 recheck:
4160 	/* Double check policy once rq lock held: */
4161 	if (policy < 0) {
4162 		reset_on_fork = p->sched_reset_on_fork;
4163 		policy = oldpolicy = p->policy;
4164 	} else {
4165 		reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
4166 
4167 		if (!valid_policy(policy))
4168 			return -EINVAL;
4169 	}
4170 
4171 	if (attr->sched_flags & ~(SCHED_FLAG_ALL | SCHED_FLAG_SUGOV))
4172 		return -EINVAL;
4173 
4174 	/*
4175 	 * Valid priorities for SCHED_FIFO and SCHED_RR are
4176 	 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
4177 	 * SCHED_BATCH and SCHED_IDLE is 0.
4178 	 */
4179 	if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
4180 	    (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
4181 		return -EINVAL;
4182 	if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
4183 	    (rt_policy(policy) != (attr->sched_priority != 0)))
4184 		return -EINVAL;
4185 
4186 	/*
4187 	 * Allow unprivileged RT tasks to decrease priority:
4188 	 */
4189 	if (user && !capable(CAP_SYS_NICE)) {
4190 		if (fair_policy(policy)) {
4191 			if (attr->sched_nice < task_nice(p) &&
4192 			    !can_nice(p, attr->sched_nice))
4193 				return -EPERM;
4194 		}
4195 
4196 		if (rt_policy(policy)) {
4197 			unsigned long rlim_rtprio =
4198 					task_rlimit(p, RLIMIT_RTPRIO);
4199 
4200 			/* Can't set/change the rt policy: */
4201 			if (policy != p->policy && !rlim_rtprio)
4202 				return -EPERM;
4203 
4204 			/* Can't increase priority: */
4205 			if (attr->sched_priority > p->rt_priority &&
4206 			    attr->sched_priority > rlim_rtprio)
4207 				return -EPERM;
4208 		}
4209 
4210 		 /*
4211 		  * Can't set/change SCHED_DEADLINE policy at all for now
4212 		  * (safest behavior); in the future we would like to allow
4213 		  * unprivileged DL tasks to increase their relative deadline
4214 		  * or reduce their runtime (both ways reducing utilization)
4215 		  */
4216 		if (dl_policy(policy))
4217 			return -EPERM;
4218 
4219 		/*
4220 		 * Treat SCHED_IDLE as nice 20. Only allow a switch to
4221 		 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
4222 		 */
4223 		if (idle_policy(p->policy) && !idle_policy(policy)) {
4224 			if (!can_nice(p, task_nice(p)))
4225 				return -EPERM;
4226 		}
4227 
4228 		/* Can't change other user's priorities: */
4229 		if (!check_same_owner(p))
4230 			return -EPERM;
4231 
4232 		/* Normal users shall not reset the sched_reset_on_fork flag: */
4233 		if (p->sched_reset_on_fork && !reset_on_fork)
4234 			return -EPERM;
4235 	}
4236 
4237 	if (user) {
4238 		if (attr->sched_flags & SCHED_FLAG_SUGOV)
4239 			return -EINVAL;
4240 
4241 		retval = security_task_setscheduler(p);
4242 		if (retval)
4243 			return retval;
4244 	}
4245 
4246 	/*
4247 	 * Make sure no PI-waiters arrive (or leave) while we are
4248 	 * changing the priority of the task:
4249 	 *
4250 	 * To be able to change p->policy safely, the appropriate
4251 	 * runqueue lock must be held.
4252 	 */
4253 	rq = task_rq_lock(p, &rf);
4254 	update_rq_clock(rq);
4255 
4256 	/*
4257 	 * Changing the policy of the stop threads its a very bad idea:
4258 	 */
4259 	if (p == rq->stop) {
4260 		task_rq_unlock(rq, p, &rf);
4261 		return -EINVAL;
4262 	}
4263 
4264 	/*
4265 	 * If not changing anything there's no need to proceed further,
4266 	 * but store a possible modification of reset_on_fork.
4267 	 */
4268 	if (unlikely(policy == p->policy)) {
4269 		if (fair_policy(policy) && attr->sched_nice != task_nice(p))
4270 			goto change;
4271 		if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
4272 			goto change;
4273 		if (dl_policy(policy) && dl_param_changed(p, attr))
4274 			goto change;
4275 
4276 		p->sched_reset_on_fork = reset_on_fork;
4277 		task_rq_unlock(rq, p, &rf);
4278 		return 0;
4279 	}
4280 change:
4281 
4282 	if (user) {
4283 #ifdef CONFIG_RT_GROUP_SCHED
4284 		/*
4285 		 * Do not allow realtime tasks into groups that have no runtime
4286 		 * assigned.
4287 		 */
4288 		if (rt_bandwidth_enabled() && rt_policy(policy) &&
4289 				task_group(p)->rt_bandwidth.rt_runtime == 0 &&
4290 				!task_group_is_autogroup(task_group(p))) {
4291 			task_rq_unlock(rq, p, &rf);
4292 			return -EPERM;
4293 		}
4294 #endif
4295 #ifdef CONFIG_SMP
4296 		if (dl_bandwidth_enabled() && dl_policy(policy) &&
4297 				!(attr->sched_flags & SCHED_FLAG_SUGOV)) {
4298 			cpumask_t *span = rq->rd->span;
4299 
4300 			/*
4301 			 * Don't allow tasks with an affinity mask smaller than
4302 			 * the entire root_domain to become SCHED_DEADLINE. We
4303 			 * will also fail if there's no bandwidth available.
4304 			 */
4305 			if (!cpumask_subset(span, &p->cpus_allowed) ||
4306 			    rq->rd->dl_bw.bw == 0) {
4307 				task_rq_unlock(rq, p, &rf);
4308 				return -EPERM;
4309 			}
4310 		}
4311 #endif
4312 	}
4313 
4314 	/* Re-check policy now with rq lock held: */
4315 	if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
4316 		policy = oldpolicy = -1;
4317 		task_rq_unlock(rq, p, &rf);
4318 		goto recheck;
4319 	}
4320 
4321 	/*
4322 	 * If setscheduling to SCHED_DEADLINE (or changing the parameters
4323 	 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
4324 	 * is available.
4325 	 */
4326 	if ((dl_policy(policy) || dl_task(p)) && sched_dl_overflow(p, policy, attr)) {
4327 		task_rq_unlock(rq, p, &rf);
4328 		return -EBUSY;
4329 	}
4330 
4331 	p->sched_reset_on_fork = reset_on_fork;
4332 	oldprio = p->prio;
4333 
4334 	if (pi) {
4335 		/*
4336 		 * Take priority boosted tasks into account. If the new
4337 		 * effective priority is unchanged, we just store the new
4338 		 * normal parameters and do not touch the scheduler class and
4339 		 * the runqueue. This will be done when the task deboost
4340 		 * itself.
4341 		 */
4342 		new_effective_prio = rt_effective_prio(p, newprio);
4343 		if (new_effective_prio == oldprio)
4344 			queue_flags &= ~DEQUEUE_MOVE;
4345 	}
4346 
4347 	queued = task_on_rq_queued(p);
4348 	running = task_current(rq, p);
4349 	if (queued)
4350 		dequeue_task(rq, p, queue_flags);
4351 	if (running)
4352 		put_prev_task(rq, p);
4353 
4354 	prev_class = p->sched_class;
4355 	__setscheduler(rq, p, attr, pi);
4356 
4357 	if (queued) {
4358 		/*
4359 		 * We enqueue to tail when the priority of a task is
4360 		 * increased (user space view).
4361 		 */
4362 		if (oldprio < p->prio)
4363 			queue_flags |= ENQUEUE_HEAD;
4364 
4365 		enqueue_task(rq, p, queue_flags);
4366 	}
4367 	if (running)
4368 		set_curr_task(rq, p);
4369 
4370 	check_class_changed(rq, p, prev_class, oldprio);
4371 
4372 	/* Avoid rq from going away on us: */
4373 	preempt_disable();
4374 	task_rq_unlock(rq, p, &rf);
4375 
4376 	if (pi)
4377 		rt_mutex_adjust_pi(p);
4378 
4379 	/* Run balance callbacks after we've adjusted the PI chain: */
4380 	balance_callback(rq);
4381 	preempt_enable();
4382 
4383 	return 0;
4384 }
4385 
4386 static int _sched_setscheduler(struct task_struct *p, int policy,
4387 			       const struct sched_param *param, bool check)
4388 {
4389 	struct sched_attr attr = {
4390 		.sched_policy   = policy,
4391 		.sched_priority = param->sched_priority,
4392 		.sched_nice	= PRIO_TO_NICE(p->static_prio),
4393 	};
4394 
4395 	/* Fixup the legacy SCHED_RESET_ON_FORK hack. */
4396 	if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
4397 		attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4398 		policy &= ~SCHED_RESET_ON_FORK;
4399 		attr.sched_policy = policy;
4400 	}
4401 
4402 	return __sched_setscheduler(p, &attr, check, true);
4403 }
4404 /**
4405  * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
4406  * @p: the task in question.
4407  * @policy: new policy.
4408  * @param: structure containing the new RT priority.
4409  *
4410  * Return: 0 on success. An error code otherwise.
4411  *
4412  * NOTE that the task may be already dead.
4413  */
4414 int sched_setscheduler(struct task_struct *p, int policy,
4415 		       const struct sched_param *param)
4416 {
4417 	return _sched_setscheduler(p, policy, param, true);
4418 }
4419 EXPORT_SYMBOL_GPL(sched_setscheduler);
4420 
4421 int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
4422 {
4423 	return __sched_setscheduler(p, attr, true, true);
4424 }
4425 EXPORT_SYMBOL_GPL(sched_setattr);
4426 
4427 int sched_setattr_nocheck(struct task_struct *p, const struct sched_attr *attr)
4428 {
4429 	return __sched_setscheduler(p, attr, false, true);
4430 }
4431 
4432 /**
4433  * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
4434  * @p: the task in question.
4435  * @policy: new policy.
4436  * @param: structure containing the new RT priority.
4437  *
4438  * Just like sched_setscheduler, only don't bother checking if the
4439  * current context has permission.  For example, this is needed in
4440  * stop_machine(): we create temporary high priority worker threads,
4441  * but our caller might not have that capability.
4442  *
4443  * Return: 0 on success. An error code otherwise.
4444  */
4445 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
4446 			       const struct sched_param *param)
4447 {
4448 	return _sched_setscheduler(p, policy, param, false);
4449 }
4450 EXPORT_SYMBOL_GPL(sched_setscheduler_nocheck);
4451 
4452 static int
4453 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
4454 {
4455 	struct sched_param lparam;
4456 	struct task_struct *p;
4457 	int retval;
4458 
4459 	if (!param || pid < 0)
4460 		return -EINVAL;
4461 	if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
4462 		return -EFAULT;
4463 
4464 	rcu_read_lock();
4465 	retval = -ESRCH;
4466 	p = find_process_by_pid(pid);
4467 	if (p != NULL)
4468 		retval = sched_setscheduler(p, policy, &lparam);
4469 	rcu_read_unlock();
4470 
4471 	return retval;
4472 }
4473 
4474 /*
4475  * Mimics kernel/events/core.c perf_copy_attr().
4476  */
4477 static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *attr)
4478 {
4479 	u32 size;
4480 	int ret;
4481 
4482 	if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0))
4483 		return -EFAULT;
4484 
4485 	/* Zero the full structure, so that a short copy will be nice: */
4486 	memset(attr, 0, sizeof(*attr));
4487 
4488 	ret = get_user(size, &uattr->size);
4489 	if (ret)
4490 		return ret;
4491 
4492 	/* Bail out on silly large: */
4493 	if (size > PAGE_SIZE)
4494 		goto err_size;
4495 
4496 	/* ABI compatibility quirk: */
4497 	if (!size)
4498 		size = SCHED_ATTR_SIZE_VER0;
4499 
4500 	if (size < SCHED_ATTR_SIZE_VER0)
4501 		goto err_size;
4502 
4503 	/*
4504 	 * If we're handed a bigger struct than we know of,
4505 	 * ensure all the unknown bits are 0 - i.e. new
4506 	 * user-space does not rely on any kernel feature
4507 	 * extensions we dont know about yet.
4508 	 */
4509 	if (size > sizeof(*attr)) {
4510 		unsigned char __user *addr;
4511 		unsigned char __user *end;
4512 		unsigned char val;
4513 
4514 		addr = (void __user *)uattr + sizeof(*attr);
4515 		end  = (void __user *)uattr + size;
4516 
4517 		for (; addr < end; addr++) {
4518 			ret = get_user(val, addr);
4519 			if (ret)
4520 				return ret;
4521 			if (val)
4522 				goto err_size;
4523 		}
4524 		size = sizeof(*attr);
4525 	}
4526 
4527 	ret = copy_from_user(attr, uattr, size);
4528 	if (ret)
4529 		return -EFAULT;
4530 
4531 	/*
4532 	 * XXX: Do we want to be lenient like existing syscalls; or do we want
4533 	 * to be strict and return an error on out-of-bounds values?
4534 	 */
4535 	attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
4536 
4537 	return 0;
4538 
4539 err_size:
4540 	put_user(sizeof(*attr), &uattr->size);
4541 	return -E2BIG;
4542 }
4543 
4544 /**
4545  * sys_sched_setscheduler - set/change the scheduler policy and RT priority
4546  * @pid: the pid in question.
4547  * @policy: new policy.
4548  * @param: structure containing the new RT priority.
4549  *
4550  * Return: 0 on success. An error code otherwise.
4551  */
4552 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param)
4553 {
4554 	if (policy < 0)
4555 		return -EINVAL;
4556 
4557 	return do_sched_setscheduler(pid, policy, param);
4558 }
4559 
4560 /**
4561  * sys_sched_setparam - set/change the RT priority of a thread
4562  * @pid: the pid in question.
4563  * @param: structure containing the new RT priority.
4564  *
4565  * Return: 0 on success. An error code otherwise.
4566  */
4567 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
4568 {
4569 	return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
4570 }
4571 
4572 /**
4573  * sys_sched_setattr - same as above, but with extended sched_attr
4574  * @pid: the pid in question.
4575  * @uattr: structure containing the extended parameters.
4576  * @flags: for future extension.
4577  */
4578 SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
4579 			       unsigned int, flags)
4580 {
4581 	struct sched_attr attr;
4582 	struct task_struct *p;
4583 	int retval;
4584 
4585 	if (!uattr || pid < 0 || flags)
4586 		return -EINVAL;
4587 
4588 	retval = sched_copy_attr(uattr, &attr);
4589 	if (retval)
4590 		return retval;
4591 
4592 	if ((int)attr.sched_policy < 0)
4593 		return -EINVAL;
4594 
4595 	rcu_read_lock();
4596 	retval = -ESRCH;
4597 	p = find_process_by_pid(pid);
4598 	if (p != NULL)
4599 		retval = sched_setattr(p, &attr);
4600 	rcu_read_unlock();
4601 
4602 	return retval;
4603 }
4604 
4605 /**
4606  * sys_sched_getscheduler - get the policy (scheduling class) of a thread
4607  * @pid: the pid in question.
4608  *
4609  * Return: On success, the policy of the thread. Otherwise, a negative error
4610  * code.
4611  */
4612 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
4613 {
4614 	struct task_struct *p;
4615 	int retval;
4616 
4617 	if (pid < 0)
4618 		return -EINVAL;
4619 
4620 	retval = -ESRCH;
4621 	rcu_read_lock();
4622 	p = find_process_by_pid(pid);
4623 	if (p) {
4624 		retval = security_task_getscheduler(p);
4625 		if (!retval)
4626 			retval = p->policy
4627 				| (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
4628 	}
4629 	rcu_read_unlock();
4630 	return retval;
4631 }
4632 
4633 /**
4634  * sys_sched_getparam - get the RT priority of a thread
4635  * @pid: the pid in question.
4636  * @param: structure containing the RT priority.
4637  *
4638  * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
4639  * code.
4640  */
4641 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
4642 {
4643 	struct sched_param lp = { .sched_priority = 0 };
4644 	struct task_struct *p;
4645 	int retval;
4646 
4647 	if (!param || pid < 0)
4648 		return -EINVAL;
4649 
4650 	rcu_read_lock();
4651 	p = find_process_by_pid(pid);
4652 	retval = -ESRCH;
4653 	if (!p)
4654 		goto out_unlock;
4655 
4656 	retval = security_task_getscheduler(p);
4657 	if (retval)
4658 		goto out_unlock;
4659 
4660 	if (task_has_rt_policy(p))
4661 		lp.sched_priority = p->rt_priority;
4662 	rcu_read_unlock();
4663 
4664 	/*
4665 	 * This one might sleep, we cannot do it with a spinlock held ...
4666 	 */
4667 	retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
4668 
4669 	return retval;
4670 
4671 out_unlock:
4672 	rcu_read_unlock();
4673 	return retval;
4674 }
4675 
4676 static int sched_read_attr(struct sched_attr __user *uattr,
4677 			   struct sched_attr *attr,
4678 			   unsigned int usize)
4679 {
4680 	int ret;
4681 
4682 	if (!access_ok(VERIFY_WRITE, uattr, usize))
4683 		return -EFAULT;
4684 
4685 	/*
4686 	 * If we're handed a smaller struct than we know of,
4687 	 * ensure all the unknown bits are 0 - i.e. old
4688 	 * user-space does not get uncomplete information.
4689 	 */
4690 	if (usize < sizeof(*attr)) {
4691 		unsigned char *addr;
4692 		unsigned char *end;
4693 
4694 		addr = (void *)attr + usize;
4695 		end  = (void *)attr + sizeof(*attr);
4696 
4697 		for (; addr < end; addr++) {
4698 			if (*addr)
4699 				return -EFBIG;
4700 		}
4701 
4702 		attr->size = usize;
4703 	}
4704 
4705 	ret = copy_to_user(uattr, attr, attr->size);
4706 	if (ret)
4707 		return -EFAULT;
4708 
4709 	return 0;
4710 }
4711 
4712 /**
4713  * sys_sched_getattr - similar to sched_getparam, but with sched_attr
4714  * @pid: the pid in question.
4715  * @uattr: structure containing the extended parameters.
4716  * @size: sizeof(attr) for fwd/bwd comp.
4717  * @flags: for future extension.
4718  */
4719 SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
4720 		unsigned int, size, unsigned int, flags)
4721 {
4722 	struct sched_attr attr = {
4723 		.size = sizeof(struct sched_attr),
4724 	};
4725 	struct task_struct *p;
4726 	int retval;
4727 
4728 	if (!uattr || pid < 0 || size > PAGE_SIZE ||
4729 	    size < SCHED_ATTR_SIZE_VER0 || flags)
4730 		return -EINVAL;
4731 
4732 	rcu_read_lock();
4733 	p = find_process_by_pid(pid);
4734 	retval = -ESRCH;
4735 	if (!p)
4736 		goto out_unlock;
4737 
4738 	retval = security_task_getscheduler(p);
4739 	if (retval)
4740 		goto out_unlock;
4741 
4742 	attr.sched_policy = p->policy;
4743 	if (p->sched_reset_on_fork)
4744 		attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
4745 	if (task_has_dl_policy(p))
4746 		__getparam_dl(p, &attr);
4747 	else if (task_has_rt_policy(p))
4748 		attr.sched_priority = p->rt_priority;
4749 	else
4750 		attr.sched_nice = task_nice(p);
4751 
4752 	rcu_read_unlock();
4753 
4754 	retval = sched_read_attr(uattr, &attr, size);
4755 	return retval;
4756 
4757 out_unlock:
4758 	rcu_read_unlock();
4759 	return retval;
4760 }
4761 
4762 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
4763 {
4764 	cpumask_var_t cpus_allowed, new_mask;
4765 	struct task_struct *p;
4766 	int retval;
4767 
4768 	rcu_read_lock();
4769 
4770 	p = find_process_by_pid(pid);
4771 	if (!p) {
4772 		rcu_read_unlock();
4773 		return -ESRCH;
4774 	}
4775 
4776 	/* Prevent p going away */
4777 	get_task_struct(p);
4778 	rcu_read_unlock();
4779 
4780 	if (p->flags & PF_NO_SETAFFINITY) {
4781 		retval = -EINVAL;
4782 		goto out_put_task;
4783 	}
4784 	if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
4785 		retval = -ENOMEM;
4786 		goto out_put_task;
4787 	}
4788 	if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
4789 		retval = -ENOMEM;
4790 		goto out_free_cpus_allowed;
4791 	}
4792 	retval = -EPERM;
4793 	if (!check_same_owner(p)) {
4794 		rcu_read_lock();
4795 		if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
4796 			rcu_read_unlock();
4797 			goto out_free_new_mask;
4798 		}
4799 		rcu_read_unlock();
4800 	}
4801 
4802 	retval = security_task_setscheduler(p);
4803 	if (retval)
4804 		goto out_free_new_mask;
4805 
4806 
4807 	cpuset_cpus_allowed(p, cpus_allowed);
4808 	cpumask_and(new_mask, in_mask, cpus_allowed);
4809 
4810 	/*
4811 	 * Since bandwidth control happens on root_domain basis,
4812 	 * if admission test is enabled, we only admit -deadline
4813 	 * tasks allowed to run on all the CPUs in the task's
4814 	 * root_domain.
4815 	 */
4816 #ifdef CONFIG_SMP
4817 	if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
4818 		rcu_read_lock();
4819 		if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
4820 			retval = -EBUSY;
4821 			rcu_read_unlock();
4822 			goto out_free_new_mask;
4823 		}
4824 		rcu_read_unlock();
4825 	}
4826 #endif
4827 again:
4828 	retval = __set_cpus_allowed_ptr(p, new_mask, true);
4829 
4830 	if (!retval) {
4831 		cpuset_cpus_allowed(p, cpus_allowed);
4832 		if (!cpumask_subset(new_mask, cpus_allowed)) {
4833 			/*
4834 			 * We must have raced with a concurrent cpuset
4835 			 * update. Just reset the cpus_allowed to the
4836 			 * cpuset's cpus_allowed
4837 			 */
4838 			cpumask_copy(new_mask, cpus_allowed);
4839 			goto again;
4840 		}
4841 	}
4842 out_free_new_mask:
4843 	free_cpumask_var(new_mask);
4844 out_free_cpus_allowed:
4845 	free_cpumask_var(cpus_allowed);
4846 out_put_task:
4847 	put_task_struct(p);
4848 	return retval;
4849 }
4850 
4851 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
4852 			     struct cpumask *new_mask)
4853 {
4854 	if (len < cpumask_size())
4855 		cpumask_clear(new_mask);
4856 	else if (len > cpumask_size())
4857 		len = cpumask_size();
4858 
4859 	return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
4860 }
4861 
4862 /**
4863  * sys_sched_setaffinity - set the CPU affinity of a process
4864  * @pid: pid of the process
4865  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4866  * @user_mask_ptr: user-space pointer to the new CPU mask
4867  *
4868  * Return: 0 on success. An error code otherwise.
4869  */
4870 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
4871 		unsigned long __user *, user_mask_ptr)
4872 {
4873 	cpumask_var_t new_mask;
4874 	int retval;
4875 
4876 	if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
4877 		return -ENOMEM;
4878 
4879 	retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
4880 	if (retval == 0)
4881 		retval = sched_setaffinity(pid, new_mask);
4882 	free_cpumask_var(new_mask);
4883 	return retval;
4884 }
4885 
4886 long sched_getaffinity(pid_t pid, struct cpumask *mask)
4887 {
4888 	struct task_struct *p;
4889 	unsigned long flags;
4890 	int retval;
4891 
4892 	rcu_read_lock();
4893 
4894 	retval = -ESRCH;
4895 	p = find_process_by_pid(pid);
4896 	if (!p)
4897 		goto out_unlock;
4898 
4899 	retval = security_task_getscheduler(p);
4900 	if (retval)
4901 		goto out_unlock;
4902 
4903 	raw_spin_lock_irqsave(&p->pi_lock, flags);
4904 	cpumask_and(mask, &p->cpus_allowed, cpu_active_mask);
4905 	raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4906 
4907 out_unlock:
4908 	rcu_read_unlock();
4909 
4910 	return retval;
4911 }
4912 
4913 /**
4914  * sys_sched_getaffinity - get the CPU affinity of a process
4915  * @pid: pid of the process
4916  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
4917  * @user_mask_ptr: user-space pointer to hold the current CPU mask
4918  *
4919  * Return: size of CPU mask copied to user_mask_ptr on success. An
4920  * error code otherwise.
4921  */
4922 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
4923 		unsigned long __user *, user_mask_ptr)
4924 {
4925 	int ret;
4926 	cpumask_var_t mask;
4927 
4928 	if ((len * BITS_PER_BYTE) < nr_cpu_ids)
4929 		return -EINVAL;
4930 	if (len & (sizeof(unsigned long)-1))
4931 		return -EINVAL;
4932 
4933 	if (!alloc_cpumask_var(&mask, GFP_KERNEL))
4934 		return -ENOMEM;
4935 
4936 	ret = sched_getaffinity(pid, mask);
4937 	if (ret == 0) {
4938 		unsigned int retlen = min(len, cpumask_size());
4939 
4940 		if (copy_to_user(user_mask_ptr, mask, retlen))
4941 			ret = -EFAULT;
4942 		else
4943 			ret = retlen;
4944 	}
4945 	free_cpumask_var(mask);
4946 
4947 	return ret;
4948 }
4949 
4950 /**
4951  * sys_sched_yield - yield the current processor to other threads.
4952  *
4953  * This function yields the current CPU to other tasks. If there are no
4954  * other threads running on this CPU then this function will return.
4955  *
4956  * Return: 0.
4957  */
4958 static void do_sched_yield(void)
4959 {
4960 	struct rq_flags rf;
4961 	struct rq *rq;
4962 
4963 	local_irq_disable();
4964 	rq = this_rq();
4965 	rq_lock(rq, &rf);
4966 
4967 	schedstat_inc(rq->yld_count);
4968 	current->sched_class->yield_task(rq);
4969 
4970 	/*
4971 	 * Since we are going to call schedule() anyway, there's
4972 	 * no need to preempt or enable interrupts:
4973 	 */
4974 	preempt_disable();
4975 	rq_unlock(rq, &rf);
4976 	sched_preempt_enable_no_resched();
4977 
4978 	schedule();
4979 }
4980 
4981 SYSCALL_DEFINE0(sched_yield)
4982 {
4983 	do_sched_yield();
4984 	return 0;
4985 }
4986 
4987 #ifndef CONFIG_PREEMPT
4988 int __sched _cond_resched(void)
4989 {
4990 	if (should_resched(0)) {
4991 		preempt_schedule_common();
4992 		return 1;
4993 	}
4994 	rcu_all_qs();
4995 	return 0;
4996 }
4997 EXPORT_SYMBOL(_cond_resched);
4998 #endif
4999 
5000 /*
5001  * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
5002  * call schedule, and on return reacquire the lock.
5003  *
5004  * This works OK both with and without CONFIG_PREEMPT. We do strange low-level
5005  * operations here to prevent schedule() from being called twice (once via
5006  * spin_unlock(), once by hand).
5007  */
5008 int __cond_resched_lock(spinlock_t *lock)
5009 {
5010 	int resched = should_resched(PREEMPT_LOCK_OFFSET);
5011 	int ret = 0;
5012 
5013 	lockdep_assert_held(lock);
5014 
5015 	if (spin_needbreak(lock) || resched) {
5016 		spin_unlock(lock);
5017 		if (resched)
5018 			preempt_schedule_common();
5019 		else
5020 			cpu_relax();
5021 		ret = 1;
5022 		spin_lock(lock);
5023 	}
5024 	return ret;
5025 }
5026 EXPORT_SYMBOL(__cond_resched_lock);
5027 
5028 /**
5029  * yield - yield the current processor to other threads.
5030  *
5031  * Do not ever use this function, there's a 99% chance you're doing it wrong.
5032  *
5033  * The scheduler is at all times free to pick the calling task as the most
5034  * eligible task to run, if removing the yield() call from your code breaks
5035  * it, its already broken.
5036  *
5037  * Typical broken usage is:
5038  *
5039  * while (!event)
5040  *	yield();
5041  *
5042  * where one assumes that yield() will let 'the other' process run that will
5043  * make event true. If the current task is a SCHED_FIFO task that will never
5044  * happen. Never use yield() as a progress guarantee!!
5045  *
5046  * If you want to use yield() to wait for something, use wait_event().
5047  * If you want to use yield() to be 'nice' for others, use cond_resched().
5048  * If you still want to use yield(), do not!
5049  */
5050 void __sched yield(void)
5051 {
5052 	set_current_state(TASK_RUNNING);
5053 	do_sched_yield();
5054 }
5055 EXPORT_SYMBOL(yield);
5056 
5057 /**
5058  * yield_to - yield the current processor to another thread in
5059  * your thread group, or accelerate that thread toward the
5060  * processor it's on.
5061  * @p: target task
5062  * @preempt: whether task preemption is allowed or not
5063  *
5064  * It's the caller's job to ensure that the target task struct
5065  * can't go away on us before we can do any checks.
5066  *
5067  * Return:
5068  *	true (>0) if we indeed boosted the target task.
5069  *	false (0) if we failed to boost the target.
5070  *	-ESRCH if there's no task to yield to.
5071  */
5072 int __sched yield_to(struct task_struct *p, bool preempt)
5073 {
5074 	struct task_struct *curr = current;
5075 	struct rq *rq, *p_rq;
5076 	unsigned long flags;
5077 	int yielded = 0;
5078 
5079 	local_irq_save(flags);
5080 	rq = this_rq();
5081 
5082 again:
5083 	p_rq = task_rq(p);
5084 	/*
5085 	 * If we're the only runnable task on the rq and target rq also
5086 	 * has only one task, there's absolutely no point in yielding.
5087 	 */
5088 	if (rq->nr_running == 1 && p_rq->nr_running == 1) {
5089 		yielded = -ESRCH;
5090 		goto out_irq;
5091 	}
5092 
5093 	double_rq_lock(rq, p_rq);
5094 	if (task_rq(p) != p_rq) {
5095 		double_rq_unlock(rq, p_rq);
5096 		goto again;
5097 	}
5098 
5099 	if (!curr->sched_class->yield_to_task)
5100 		goto out_unlock;
5101 
5102 	if (curr->sched_class != p->sched_class)
5103 		goto out_unlock;
5104 
5105 	if (task_running(p_rq, p) || p->state)
5106 		goto out_unlock;
5107 
5108 	yielded = curr->sched_class->yield_to_task(rq, p, preempt);
5109 	if (yielded) {
5110 		schedstat_inc(rq->yld_count);
5111 		/*
5112 		 * Make p's CPU reschedule; pick_next_entity takes care of
5113 		 * fairness.
5114 		 */
5115 		if (preempt && rq != p_rq)
5116 			resched_curr(p_rq);
5117 	}
5118 
5119 out_unlock:
5120 	double_rq_unlock(rq, p_rq);
5121 out_irq:
5122 	local_irq_restore(flags);
5123 
5124 	if (yielded > 0)
5125 		schedule();
5126 
5127 	return yielded;
5128 }
5129 EXPORT_SYMBOL_GPL(yield_to);
5130 
5131 int io_schedule_prepare(void)
5132 {
5133 	int old_iowait = current->in_iowait;
5134 
5135 	current->in_iowait = 1;
5136 	blk_schedule_flush_plug(current);
5137 
5138 	return old_iowait;
5139 }
5140 
5141 void io_schedule_finish(int token)
5142 {
5143 	current->in_iowait = token;
5144 }
5145 
5146 /*
5147  * This task is about to go to sleep on IO. Increment rq->nr_iowait so
5148  * that process accounting knows that this is a task in IO wait state.
5149  */
5150 long __sched io_schedule_timeout(long timeout)
5151 {
5152 	int token;
5153 	long ret;
5154 
5155 	token = io_schedule_prepare();
5156 	ret = schedule_timeout(timeout);
5157 	io_schedule_finish(token);
5158 
5159 	return ret;
5160 }
5161 EXPORT_SYMBOL(io_schedule_timeout);
5162 
5163 void io_schedule(void)
5164 {
5165 	int token;
5166 
5167 	token = io_schedule_prepare();
5168 	schedule();
5169 	io_schedule_finish(token);
5170 }
5171 EXPORT_SYMBOL(io_schedule);
5172 
5173 /**
5174  * sys_sched_get_priority_max - return maximum RT priority.
5175  * @policy: scheduling class.
5176  *
5177  * Return: On success, this syscall returns the maximum
5178  * rt_priority that can be used by a given scheduling class.
5179  * On failure, a negative error code is returned.
5180  */
5181 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
5182 {
5183 	int ret = -EINVAL;
5184 
5185 	switch (policy) {
5186 	case SCHED_FIFO:
5187 	case SCHED_RR:
5188 		ret = MAX_USER_RT_PRIO-1;
5189 		break;
5190 	case SCHED_DEADLINE:
5191 	case SCHED_NORMAL:
5192 	case SCHED_BATCH:
5193 	case SCHED_IDLE:
5194 		ret = 0;
5195 		break;
5196 	}
5197 	return ret;
5198 }
5199 
5200 /**
5201  * sys_sched_get_priority_min - return minimum RT priority.
5202  * @policy: scheduling class.
5203  *
5204  * Return: On success, this syscall returns the minimum
5205  * rt_priority that can be used by a given scheduling class.
5206  * On failure, a negative error code is returned.
5207  */
5208 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
5209 {
5210 	int ret = -EINVAL;
5211 
5212 	switch (policy) {
5213 	case SCHED_FIFO:
5214 	case SCHED_RR:
5215 		ret = 1;
5216 		break;
5217 	case SCHED_DEADLINE:
5218 	case SCHED_NORMAL:
5219 	case SCHED_BATCH:
5220 	case SCHED_IDLE:
5221 		ret = 0;
5222 	}
5223 	return ret;
5224 }
5225 
5226 static int sched_rr_get_interval(pid_t pid, struct timespec64 *t)
5227 {
5228 	struct task_struct *p;
5229 	unsigned int time_slice;
5230 	struct rq_flags rf;
5231 	struct rq *rq;
5232 	int retval;
5233 
5234 	if (pid < 0)
5235 		return -EINVAL;
5236 
5237 	retval = -ESRCH;
5238 	rcu_read_lock();
5239 	p = find_process_by_pid(pid);
5240 	if (!p)
5241 		goto out_unlock;
5242 
5243 	retval = security_task_getscheduler(p);
5244 	if (retval)
5245 		goto out_unlock;
5246 
5247 	rq = task_rq_lock(p, &rf);
5248 	time_slice = 0;
5249 	if (p->sched_class->get_rr_interval)
5250 		time_slice = p->sched_class->get_rr_interval(rq, p);
5251 	task_rq_unlock(rq, p, &rf);
5252 
5253 	rcu_read_unlock();
5254 	jiffies_to_timespec64(time_slice, t);
5255 	return 0;
5256 
5257 out_unlock:
5258 	rcu_read_unlock();
5259 	return retval;
5260 }
5261 
5262 /**
5263  * sys_sched_rr_get_interval - return the default timeslice of a process.
5264  * @pid: pid of the process.
5265  * @interval: userspace pointer to the timeslice value.
5266  *
5267  * this syscall writes the default timeslice value of a given process
5268  * into the user-space timespec buffer. A value of '0' means infinity.
5269  *
5270  * Return: On success, 0 and the timeslice is in @interval. Otherwise,
5271  * an error code.
5272  */
5273 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
5274 		struct timespec __user *, interval)
5275 {
5276 	struct timespec64 t;
5277 	int retval = sched_rr_get_interval(pid, &t);
5278 
5279 	if (retval == 0)
5280 		retval = put_timespec64(&t, interval);
5281 
5282 	return retval;
5283 }
5284 
5285 #ifdef CONFIG_COMPAT
5286 COMPAT_SYSCALL_DEFINE2(sched_rr_get_interval,
5287 		       compat_pid_t, pid,
5288 		       struct compat_timespec __user *, interval)
5289 {
5290 	struct timespec64 t;
5291 	int retval = sched_rr_get_interval(pid, &t);
5292 
5293 	if (retval == 0)
5294 		retval = compat_put_timespec64(&t, interval);
5295 	return retval;
5296 }
5297 #endif
5298 
5299 void sched_show_task(struct task_struct *p)
5300 {
5301 	unsigned long free = 0;
5302 	int ppid;
5303 
5304 	if (!try_get_task_stack(p))
5305 		return;
5306 
5307 	printk(KERN_INFO "%-15.15s %c", p->comm, task_state_to_char(p));
5308 
5309 	if (p->state == TASK_RUNNING)
5310 		printk(KERN_CONT "  running task    ");
5311 #ifdef CONFIG_DEBUG_STACK_USAGE
5312 	free = stack_not_used(p);
5313 #endif
5314 	ppid = 0;
5315 	rcu_read_lock();
5316 	if (pid_alive(p))
5317 		ppid = task_pid_nr(rcu_dereference(p->real_parent));
5318 	rcu_read_unlock();
5319 	printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free,
5320 		task_pid_nr(p), ppid,
5321 		(unsigned long)task_thread_info(p)->flags);
5322 
5323 	print_worker_info(KERN_INFO, p);
5324 	show_stack(p, NULL);
5325 	put_task_stack(p);
5326 }
5327 EXPORT_SYMBOL_GPL(sched_show_task);
5328 
5329 static inline bool
5330 state_filter_match(unsigned long state_filter, struct task_struct *p)
5331 {
5332 	/* no filter, everything matches */
5333 	if (!state_filter)
5334 		return true;
5335 
5336 	/* filter, but doesn't match */
5337 	if (!(p->state & state_filter))
5338 		return false;
5339 
5340 	/*
5341 	 * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
5342 	 * TASK_KILLABLE).
5343 	 */
5344 	if (state_filter == TASK_UNINTERRUPTIBLE && p->state == TASK_IDLE)
5345 		return false;
5346 
5347 	return true;
5348 }
5349 
5350 
5351 void show_state_filter(unsigned long state_filter)
5352 {
5353 	struct task_struct *g, *p;
5354 
5355 #if BITS_PER_LONG == 32
5356 	printk(KERN_INFO
5357 		"  task                PC stack   pid father\n");
5358 #else
5359 	printk(KERN_INFO
5360 		"  task                        PC stack   pid father\n");
5361 #endif
5362 	rcu_read_lock();
5363 	for_each_process_thread(g, p) {
5364 		/*
5365 		 * reset the NMI-timeout, listing all files on a slow
5366 		 * console might take a lot of time:
5367 		 * Also, reset softlockup watchdogs on all CPUs, because
5368 		 * another CPU might be blocked waiting for us to process
5369 		 * an IPI.
5370 		 */
5371 		touch_nmi_watchdog();
5372 		touch_all_softlockup_watchdogs();
5373 		if (state_filter_match(state_filter, p))
5374 			sched_show_task(p);
5375 	}
5376 
5377 #ifdef CONFIG_SCHED_DEBUG
5378 	if (!state_filter)
5379 		sysrq_sched_debug_show();
5380 #endif
5381 	rcu_read_unlock();
5382 	/*
5383 	 * Only show locks if all tasks are dumped:
5384 	 */
5385 	if (!state_filter)
5386 		debug_show_all_locks();
5387 }
5388 
5389 /**
5390  * init_idle - set up an idle thread for a given CPU
5391  * @idle: task in question
5392  * @cpu: CPU the idle task belongs to
5393  *
5394  * NOTE: this function does not set the idle thread's NEED_RESCHED
5395  * flag, to make booting more robust.
5396  */
5397 void init_idle(struct task_struct *idle, int cpu)
5398 {
5399 	struct rq *rq = cpu_rq(cpu);
5400 	unsigned long flags;
5401 
5402 	raw_spin_lock_irqsave(&idle->pi_lock, flags);
5403 	raw_spin_lock(&rq->lock);
5404 
5405 	__sched_fork(0, idle);
5406 	idle->state = TASK_RUNNING;
5407 	idle->se.exec_start = sched_clock();
5408 	idle->flags |= PF_IDLE;
5409 
5410 	kasan_unpoison_task_stack(idle);
5411 
5412 #ifdef CONFIG_SMP
5413 	/*
5414 	 * Its possible that init_idle() gets called multiple times on a task,
5415 	 * in that case do_set_cpus_allowed() will not do the right thing.
5416 	 *
5417 	 * And since this is boot we can forgo the serialization.
5418 	 */
5419 	set_cpus_allowed_common(idle, cpumask_of(cpu));
5420 #endif
5421 	/*
5422 	 * We're having a chicken and egg problem, even though we are
5423 	 * holding rq->lock, the CPU isn't yet set to this CPU so the
5424 	 * lockdep check in task_group() will fail.
5425 	 *
5426 	 * Similar case to sched_fork(). / Alternatively we could
5427 	 * use task_rq_lock() here and obtain the other rq->lock.
5428 	 *
5429 	 * Silence PROVE_RCU
5430 	 */
5431 	rcu_read_lock();
5432 	__set_task_cpu(idle, cpu);
5433 	rcu_read_unlock();
5434 
5435 	rq->curr = rq->idle = idle;
5436 	idle->on_rq = TASK_ON_RQ_QUEUED;
5437 #ifdef CONFIG_SMP
5438 	idle->on_cpu = 1;
5439 #endif
5440 	raw_spin_unlock(&rq->lock);
5441 	raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
5442 
5443 	/* Set the preempt count _outside_ the spinlocks! */
5444 	init_idle_preempt_count(idle, cpu);
5445 
5446 	/*
5447 	 * The idle tasks have their own, simple scheduling class:
5448 	 */
5449 	idle->sched_class = &idle_sched_class;
5450 	ftrace_graph_init_idle_task(idle, cpu);
5451 	vtime_init_idle(idle, cpu);
5452 #ifdef CONFIG_SMP
5453 	sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
5454 #endif
5455 }
5456 
5457 #ifdef CONFIG_SMP
5458 
5459 int cpuset_cpumask_can_shrink(const struct cpumask *cur,
5460 			      const struct cpumask *trial)
5461 {
5462 	int ret = 1;
5463 
5464 	if (!cpumask_weight(cur))
5465 		return ret;
5466 
5467 	ret = dl_cpuset_cpumask_can_shrink(cur, trial);
5468 
5469 	return ret;
5470 }
5471 
5472 int task_can_attach(struct task_struct *p,
5473 		    const struct cpumask *cs_cpus_allowed)
5474 {
5475 	int ret = 0;
5476 
5477 	/*
5478 	 * Kthreads which disallow setaffinity shouldn't be moved
5479 	 * to a new cpuset; we don't want to change their CPU
5480 	 * affinity and isolating such threads by their set of
5481 	 * allowed nodes is unnecessary.  Thus, cpusets are not
5482 	 * applicable for such threads.  This prevents checking for
5483 	 * success of set_cpus_allowed_ptr() on all attached tasks
5484 	 * before cpus_allowed may be changed.
5485 	 */
5486 	if (p->flags & PF_NO_SETAFFINITY) {
5487 		ret = -EINVAL;
5488 		goto out;
5489 	}
5490 
5491 	if (dl_task(p) && !cpumask_intersects(task_rq(p)->rd->span,
5492 					      cs_cpus_allowed))
5493 		ret = dl_task_can_attach(p, cs_cpus_allowed);
5494 
5495 out:
5496 	return ret;
5497 }
5498 
5499 bool sched_smp_initialized __read_mostly;
5500 
5501 #ifdef CONFIG_NUMA_BALANCING
5502 /* Migrate current task p to target_cpu */
5503 int migrate_task_to(struct task_struct *p, int target_cpu)
5504 {
5505 	struct migration_arg arg = { p, target_cpu };
5506 	int curr_cpu = task_cpu(p);
5507 
5508 	if (curr_cpu == target_cpu)
5509 		return 0;
5510 
5511 	if (!cpumask_test_cpu(target_cpu, &p->cpus_allowed))
5512 		return -EINVAL;
5513 
5514 	/* TODO: This is not properly updating schedstats */
5515 
5516 	trace_sched_move_numa(p, curr_cpu, target_cpu);
5517 	return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
5518 }
5519 
5520 /*
5521  * Requeue a task on a given node and accurately track the number of NUMA
5522  * tasks on the runqueues
5523  */
5524 void sched_setnuma(struct task_struct *p, int nid)
5525 {
5526 	bool queued, running;
5527 	struct rq_flags rf;
5528 	struct rq *rq;
5529 
5530 	rq = task_rq_lock(p, &rf);
5531 	queued = task_on_rq_queued(p);
5532 	running = task_current(rq, p);
5533 
5534 	if (queued)
5535 		dequeue_task(rq, p, DEQUEUE_SAVE);
5536 	if (running)
5537 		put_prev_task(rq, p);
5538 
5539 	p->numa_preferred_nid = nid;
5540 
5541 	if (queued)
5542 		enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
5543 	if (running)
5544 		set_curr_task(rq, p);
5545 	task_rq_unlock(rq, p, &rf);
5546 }
5547 #endif /* CONFIG_NUMA_BALANCING */
5548 
5549 #ifdef CONFIG_HOTPLUG_CPU
5550 /*
5551  * Ensure that the idle task is using init_mm right before its CPU goes
5552  * offline.
5553  */
5554 void idle_task_exit(void)
5555 {
5556 	struct mm_struct *mm = current->active_mm;
5557 
5558 	BUG_ON(cpu_online(smp_processor_id()));
5559 
5560 	if (mm != &init_mm) {
5561 		switch_mm(mm, &init_mm, current);
5562 		current->active_mm = &init_mm;
5563 		finish_arch_post_lock_switch();
5564 	}
5565 	mmdrop(mm);
5566 }
5567 
5568 /*
5569  * Since this CPU is going 'away' for a while, fold any nr_active delta
5570  * we might have. Assumes we're called after migrate_tasks() so that the
5571  * nr_active count is stable. We need to take the teardown thread which
5572  * is calling this into account, so we hand in adjust = 1 to the load
5573  * calculation.
5574  *
5575  * Also see the comment "Global load-average calculations".
5576  */
5577 static void calc_load_migrate(struct rq *rq)
5578 {
5579 	long delta = calc_load_fold_active(rq, 1);
5580 	if (delta)
5581 		atomic_long_add(delta, &calc_load_tasks);
5582 }
5583 
5584 static void put_prev_task_fake(struct rq *rq, struct task_struct *prev)
5585 {
5586 }
5587 
5588 static const struct sched_class fake_sched_class = {
5589 	.put_prev_task = put_prev_task_fake,
5590 };
5591 
5592 static struct task_struct fake_task = {
5593 	/*
5594 	 * Avoid pull_{rt,dl}_task()
5595 	 */
5596 	.prio = MAX_PRIO + 1,
5597 	.sched_class = &fake_sched_class,
5598 };
5599 
5600 /*
5601  * Migrate all tasks from the rq, sleeping tasks will be migrated by
5602  * try_to_wake_up()->select_task_rq().
5603  *
5604  * Called with rq->lock held even though we'er in stop_machine() and
5605  * there's no concurrency possible, we hold the required locks anyway
5606  * because of lock validation efforts.
5607  */
5608 static void migrate_tasks(struct rq *dead_rq, struct rq_flags *rf)
5609 {
5610 	struct rq *rq = dead_rq;
5611 	struct task_struct *next, *stop = rq->stop;
5612 	struct rq_flags orf = *rf;
5613 	int dest_cpu;
5614 
5615 	/*
5616 	 * Fudge the rq selection such that the below task selection loop
5617 	 * doesn't get stuck on the currently eligible stop task.
5618 	 *
5619 	 * We're currently inside stop_machine() and the rq is either stuck
5620 	 * in the stop_machine_cpu_stop() loop, or we're executing this code,
5621 	 * either way we should never end up calling schedule() until we're
5622 	 * done here.
5623 	 */
5624 	rq->stop = NULL;
5625 
5626 	/*
5627 	 * put_prev_task() and pick_next_task() sched
5628 	 * class method both need to have an up-to-date
5629 	 * value of rq->clock[_task]
5630 	 */
5631 	update_rq_clock(rq);
5632 
5633 	for (;;) {
5634 		/*
5635 		 * There's this thread running, bail when that's the only
5636 		 * remaining thread:
5637 		 */
5638 		if (rq->nr_running == 1)
5639 			break;
5640 
5641 		/*
5642 		 * pick_next_task() assumes pinned rq->lock:
5643 		 */
5644 		next = pick_next_task(rq, &fake_task, rf);
5645 		BUG_ON(!next);
5646 		put_prev_task(rq, next);
5647 
5648 		/*
5649 		 * Rules for changing task_struct::cpus_allowed are holding
5650 		 * both pi_lock and rq->lock, such that holding either
5651 		 * stabilizes the mask.
5652 		 *
5653 		 * Drop rq->lock is not quite as disastrous as it usually is
5654 		 * because !cpu_active at this point, which means load-balance
5655 		 * will not interfere. Also, stop-machine.
5656 		 */
5657 		rq_unlock(rq, rf);
5658 		raw_spin_lock(&next->pi_lock);
5659 		rq_relock(rq, rf);
5660 
5661 		/*
5662 		 * Since we're inside stop-machine, _nothing_ should have
5663 		 * changed the task, WARN if weird stuff happened, because in
5664 		 * that case the above rq->lock drop is a fail too.
5665 		 */
5666 		if (WARN_ON(task_rq(next) != rq || !task_on_rq_queued(next))) {
5667 			raw_spin_unlock(&next->pi_lock);
5668 			continue;
5669 		}
5670 
5671 		/* Find suitable destination for @next, with force if needed. */
5672 		dest_cpu = select_fallback_rq(dead_rq->cpu, next);
5673 		rq = __migrate_task(rq, rf, next, dest_cpu);
5674 		if (rq != dead_rq) {
5675 			rq_unlock(rq, rf);
5676 			rq = dead_rq;
5677 			*rf = orf;
5678 			rq_relock(rq, rf);
5679 		}
5680 		raw_spin_unlock(&next->pi_lock);
5681 	}
5682 
5683 	rq->stop = stop;
5684 }
5685 #endif /* CONFIG_HOTPLUG_CPU */
5686 
5687 void set_rq_online(struct rq *rq)
5688 {
5689 	if (!rq->online) {
5690 		const struct sched_class *class;
5691 
5692 		cpumask_set_cpu(rq->cpu, rq->rd->online);
5693 		rq->online = 1;
5694 
5695 		for_each_class(class) {
5696 			if (class->rq_online)
5697 				class->rq_online(rq);
5698 		}
5699 	}
5700 }
5701 
5702 void set_rq_offline(struct rq *rq)
5703 {
5704 	if (rq->online) {
5705 		const struct sched_class *class;
5706 
5707 		for_each_class(class) {
5708 			if (class->rq_offline)
5709 				class->rq_offline(rq);
5710 		}
5711 
5712 		cpumask_clear_cpu(rq->cpu, rq->rd->online);
5713 		rq->online = 0;
5714 	}
5715 }
5716 
5717 static void set_cpu_rq_start_time(unsigned int cpu)
5718 {
5719 	struct rq *rq = cpu_rq(cpu);
5720 
5721 	rq->age_stamp = sched_clock_cpu(cpu);
5722 }
5723 
5724 /*
5725  * used to mark begin/end of suspend/resume:
5726  */
5727 static int num_cpus_frozen;
5728 
5729 /*
5730  * Update cpusets according to cpu_active mask.  If cpusets are
5731  * disabled, cpuset_update_active_cpus() becomes a simple wrapper
5732  * around partition_sched_domains().
5733  *
5734  * If we come here as part of a suspend/resume, don't touch cpusets because we
5735  * want to restore it back to its original state upon resume anyway.
5736  */
5737 static void cpuset_cpu_active(void)
5738 {
5739 	if (cpuhp_tasks_frozen) {
5740 		/*
5741 		 * num_cpus_frozen tracks how many CPUs are involved in suspend
5742 		 * resume sequence. As long as this is not the last online
5743 		 * operation in the resume sequence, just build a single sched
5744 		 * domain, ignoring cpusets.
5745 		 */
5746 		partition_sched_domains(1, NULL, NULL);
5747 		if (--num_cpus_frozen)
5748 			return;
5749 		/*
5750 		 * This is the last CPU online operation. So fall through and
5751 		 * restore the original sched domains by considering the
5752 		 * cpuset configurations.
5753 		 */
5754 		cpuset_force_rebuild();
5755 	}
5756 	cpuset_update_active_cpus();
5757 }
5758 
5759 static int cpuset_cpu_inactive(unsigned int cpu)
5760 {
5761 	if (!cpuhp_tasks_frozen) {
5762 		if (dl_cpu_busy(cpu))
5763 			return -EBUSY;
5764 		cpuset_update_active_cpus();
5765 	} else {
5766 		num_cpus_frozen++;
5767 		partition_sched_domains(1, NULL, NULL);
5768 	}
5769 	return 0;
5770 }
5771 
5772 int sched_cpu_activate(unsigned int cpu)
5773 {
5774 	struct rq *rq = cpu_rq(cpu);
5775 	struct rq_flags rf;
5776 
5777 	set_cpu_active(cpu, true);
5778 
5779 	if (sched_smp_initialized) {
5780 		sched_domains_numa_masks_set(cpu);
5781 		cpuset_cpu_active();
5782 	}
5783 
5784 	/*
5785 	 * Put the rq online, if not already. This happens:
5786 	 *
5787 	 * 1) In the early boot process, because we build the real domains
5788 	 *    after all CPUs have been brought up.
5789 	 *
5790 	 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
5791 	 *    domains.
5792 	 */
5793 	rq_lock_irqsave(rq, &rf);
5794 	if (rq->rd) {
5795 		BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5796 		set_rq_online(rq);
5797 	}
5798 	rq_unlock_irqrestore(rq, &rf);
5799 
5800 	update_max_interval();
5801 
5802 	return 0;
5803 }
5804 
5805 int sched_cpu_deactivate(unsigned int cpu)
5806 {
5807 	int ret;
5808 
5809 	set_cpu_active(cpu, false);
5810 	/*
5811 	 * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
5812 	 * users of this state to go away such that all new such users will
5813 	 * observe it.
5814 	 *
5815 	 * Do sync before park smpboot threads to take care the rcu boost case.
5816 	 */
5817 	synchronize_rcu_mult(call_rcu, call_rcu_sched);
5818 
5819 	if (!sched_smp_initialized)
5820 		return 0;
5821 
5822 	ret = cpuset_cpu_inactive(cpu);
5823 	if (ret) {
5824 		set_cpu_active(cpu, true);
5825 		return ret;
5826 	}
5827 	sched_domains_numa_masks_clear(cpu);
5828 	return 0;
5829 }
5830 
5831 static void sched_rq_cpu_starting(unsigned int cpu)
5832 {
5833 	struct rq *rq = cpu_rq(cpu);
5834 
5835 	rq->calc_load_update = calc_load_update;
5836 	update_max_interval();
5837 }
5838 
5839 int sched_cpu_starting(unsigned int cpu)
5840 {
5841 	set_cpu_rq_start_time(cpu);
5842 	sched_rq_cpu_starting(cpu);
5843 	sched_tick_start(cpu);
5844 	return 0;
5845 }
5846 
5847 #ifdef CONFIG_HOTPLUG_CPU
5848 int sched_cpu_dying(unsigned int cpu)
5849 {
5850 	struct rq *rq = cpu_rq(cpu);
5851 	struct rq_flags rf;
5852 
5853 	/* Handle pending wakeups and then migrate everything off */
5854 	sched_ttwu_pending();
5855 	sched_tick_stop(cpu);
5856 
5857 	rq_lock_irqsave(rq, &rf);
5858 	if (rq->rd) {
5859 		BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
5860 		set_rq_offline(rq);
5861 	}
5862 	migrate_tasks(rq, &rf);
5863 	BUG_ON(rq->nr_running != 1);
5864 	rq_unlock_irqrestore(rq, &rf);
5865 
5866 	calc_load_migrate(rq);
5867 	update_max_interval();
5868 	nohz_balance_exit_idle(rq);
5869 	hrtick_clear(rq);
5870 	return 0;
5871 }
5872 #endif
5873 
5874 #ifdef CONFIG_SCHED_SMT
5875 DEFINE_STATIC_KEY_FALSE(sched_smt_present);
5876 
5877 static void sched_init_smt(void)
5878 {
5879 	/*
5880 	 * We've enumerated all CPUs and will assume that if any CPU
5881 	 * has SMT siblings, CPU0 will too.
5882 	 */
5883 	if (cpumask_weight(cpu_smt_mask(0)) > 1)
5884 		static_branch_enable(&sched_smt_present);
5885 }
5886 #else
5887 static inline void sched_init_smt(void) { }
5888 #endif
5889 
5890 void __init sched_init_smp(void)
5891 {
5892 	sched_init_numa();
5893 
5894 	/*
5895 	 * There's no userspace yet to cause hotplug operations; hence all the
5896 	 * CPU masks are stable and all blatant races in the below code cannot
5897 	 * happen.
5898 	 */
5899 	mutex_lock(&sched_domains_mutex);
5900 	sched_init_domains(cpu_active_mask);
5901 	mutex_unlock(&sched_domains_mutex);
5902 
5903 	/* Move init over to a non-isolated CPU */
5904 	if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_FLAG_DOMAIN)) < 0)
5905 		BUG();
5906 	sched_init_granularity();
5907 
5908 	init_sched_rt_class();
5909 	init_sched_dl_class();
5910 
5911 	sched_init_smt();
5912 
5913 	sched_smp_initialized = true;
5914 }
5915 
5916 static int __init migration_init(void)
5917 {
5918 	sched_rq_cpu_starting(smp_processor_id());
5919 	return 0;
5920 }
5921 early_initcall(migration_init);
5922 
5923 #else
5924 void __init sched_init_smp(void)
5925 {
5926 	sched_init_granularity();
5927 }
5928 #endif /* CONFIG_SMP */
5929 
5930 int in_sched_functions(unsigned long addr)
5931 {
5932 	return in_lock_functions(addr) ||
5933 		(addr >= (unsigned long)__sched_text_start
5934 		&& addr < (unsigned long)__sched_text_end);
5935 }
5936 
5937 #ifdef CONFIG_CGROUP_SCHED
5938 /*
5939  * Default task group.
5940  * Every task in system belongs to this group at bootup.
5941  */
5942 struct task_group root_task_group;
5943 LIST_HEAD(task_groups);
5944 
5945 /* Cacheline aligned slab cache for task_group */
5946 static struct kmem_cache *task_group_cache __read_mostly;
5947 #endif
5948 
5949 DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
5950 DECLARE_PER_CPU(cpumask_var_t, select_idle_mask);
5951 
5952 void __init sched_init(void)
5953 {
5954 	int i, j;
5955 	unsigned long alloc_size = 0, ptr;
5956 
5957 	sched_clock_init();
5958 	wait_bit_init();
5959 
5960 #ifdef CONFIG_FAIR_GROUP_SCHED
5961 	alloc_size += 2 * nr_cpu_ids * sizeof(void **);
5962 #endif
5963 #ifdef CONFIG_RT_GROUP_SCHED
5964 	alloc_size += 2 * nr_cpu_ids * sizeof(void **);
5965 #endif
5966 	if (alloc_size) {
5967 		ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT);
5968 
5969 #ifdef CONFIG_FAIR_GROUP_SCHED
5970 		root_task_group.se = (struct sched_entity **)ptr;
5971 		ptr += nr_cpu_ids * sizeof(void **);
5972 
5973 		root_task_group.cfs_rq = (struct cfs_rq **)ptr;
5974 		ptr += nr_cpu_ids * sizeof(void **);
5975 
5976 #endif /* CONFIG_FAIR_GROUP_SCHED */
5977 #ifdef CONFIG_RT_GROUP_SCHED
5978 		root_task_group.rt_se = (struct sched_rt_entity **)ptr;
5979 		ptr += nr_cpu_ids * sizeof(void **);
5980 
5981 		root_task_group.rt_rq = (struct rt_rq **)ptr;
5982 		ptr += nr_cpu_ids * sizeof(void **);
5983 
5984 #endif /* CONFIG_RT_GROUP_SCHED */
5985 	}
5986 #ifdef CONFIG_CPUMASK_OFFSTACK
5987 	for_each_possible_cpu(i) {
5988 		per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
5989 			cpumask_size(), GFP_KERNEL, cpu_to_node(i));
5990 		per_cpu(select_idle_mask, i) = (cpumask_var_t)kzalloc_node(
5991 			cpumask_size(), GFP_KERNEL, cpu_to_node(i));
5992 	}
5993 #endif /* CONFIG_CPUMASK_OFFSTACK */
5994 
5995 	init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime());
5996 	init_dl_bandwidth(&def_dl_bandwidth, global_rt_period(), global_rt_runtime());
5997 
5998 #ifdef CONFIG_SMP
5999 	init_defrootdomain();
6000 #endif
6001 
6002 #ifdef CONFIG_RT_GROUP_SCHED
6003 	init_rt_bandwidth(&root_task_group.rt_bandwidth,
6004 			global_rt_period(), global_rt_runtime());
6005 #endif /* CONFIG_RT_GROUP_SCHED */
6006 
6007 #ifdef CONFIG_CGROUP_SCHED
6008 	task_group_cache = KMEM_CACHE(task_group, 0);
6009 
6010 	list_add(&root_task_group.list, &task_groups);
6011 	INIT_LIST_HEAD(&root_task_group.children);
6012 	INIT_LIST_HEAD(&root_task_group.siblings);
6013 	autogroup_init(&init_task);
6014 #endif /* CONFIG_CGROUP_SCHED */
6015 
6016 	for_each_possible_cpu(i) {
6017 		struct rq *rq;
6018 
6019 		rq = cpu_rq(i);
6020 		raw_spin_lock_init(&rq->lock);
6021 		rq->nr_running = 0;
6022 		rq->calc_load_active = 0;
6023 		rq->calc_load_update = jiffies + LOAD_FREQ;
6024 		init_cfs_rq(&rq->cfs);
6025 		init_rt_rq(&rq->rt);
6026 		init_dl_rq(&rq->dl);
6027 #ifdef CONFIG_FAIR_GROUP_SCHED
6028 		root_task_group.shares = ROOT_TASK_GROUP_LOAD;
6029 		INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
6030 		rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
6031 		/*
6032 		 * How much CPU bandwidth does root_task_group get?
6033 		 *
6034 		 * In case of task-groups formed thr' the cgroup filesystem, it
6035 		 * gets 100% of the CPU resources in the system. This overall
6036 		 * system CPU resource is divided among the tasks of
6037 		 * root_task_group and its child task-groups in a fair manner,
6038 		 * based on each entity's (task or task-group's) weight
6039 		 * (se->load.weight).
6040 		 *
6041 		 * In other words, if root_task_group has 10 tasks of weight
6042 		 * 1024) and two child groups A0 and A1 (of weight 1024 each),
6043 		 * then A0's share of the CPU resource is:
6044 		 *
6045 		 *	A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
6046 		 *
6047 		 * We achieve this by letting root_task_group's tasks sit
6048 		 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
6049 		 */
6050 		init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
6051 		init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
6052 #endif /* CONFIG_FAIR_GROUP_SCHED */
6053 
6054 		rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
6055 #ifdef CONFIG_RT_GROUP_SCHED
6056 		init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
6057 #endif
6058 
6059 		for (j = 0; j < CPU_LOAD_IDX_MAX; j++)
6060 			rq->cpu_load[j] = 0;
6061 
6062 #ifdef CONFIG_SMP
6063 		rq->sd = NULL;
6064 		rq->rd = NULL;
6065 		rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
6066 		rq->balance_callback = NULL;
6067 		rq->active_balance = 0;
6068 		rq->next_balance = jiffies;
6069 		rq->push_cpu = 0;
6070 		rq->cpu = i;
6071 		rq->online = 0;
6072 		rq->idle_stamp = 0;
6073 		rq->avg_idle = 2*sysctl_sched_migration_cost;
6074 		rq->max_idle_balance_cost = sysctl_sched_migration_cost;
6075 
6076 		INIT_LIST_HEAD(&rq->cfs_tasks);
6077 
6078 		rq_attach_root(rq, &def_root_domain);
6079 #ifdef CONFIG_NO_HZ_COMMON
6080 		rq->last_load_update_tick = jiffies;
6081 		rq->last_blocked_load_update_tick = jiffies;
6082 		atomic_set(&rq->nohz_flags, 0);
6083 #endif
6084 #endif /* CONFIG_SMP */
6085 		hrtick_rq_init(rq);
6086 		atomic_set(&rq->nr_iowait, 0);
6087 	}
6088 
6089 	set_load_weight(&init_task, false);
6090 
6091 	/*
6092 	 * The boot idle thread does lazy MMU switching as well:
6093 	 */
6094 	mmgrab(&init_mm);
6095 	enter_lazy_tlb(&init_mm, current);
6096 
6097 	/*
6098 	 * Make us the idle thread. Technically, schedule() should not be
6099 	 * called from this thread, however somewhere below it might be,
6100 	 * but because we are the idle thread, we just pick up running again
6101 	 * when this runqueue becomes "idle".
6102 	 */
6103 	init_idle(current, smp_processor_id());
6104 
6105 	calc_load_update = jiffies + LOAD_FREQ;
6106 
6107 #ifdef CONFIG_SMP
6108 	idle_thread_set_boot_cpu();
6109 	set_cpu_rq_start_time(smp_processor_id());
6110 #endif
6111 	init_sched_fair_class();
6112 
6113 	init_schedstats();
6114 
6115 	scheduler_running = 1;
6116 }
6117 
6118 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
6119 static inline int preempt_count_equals(int preempt_offset)
6120 {
6121 	int nested = preempt_count() + rcu_preempt_depth();
6122 
6123 	return (nested == preempt_offset);
6124 }
6125 
6126 void __might_sleep(const char *file, int line, int preempt_offset)
6127 {
6128 	/*
6129 	 * Blocking primitives will set (and therefore destroy) current->state,
6130 	 * since we will exit with TASK_RUNNING make sure we enter with it,
6131 	 * otherwise we will destroy state.
6132 	 */
6133 	WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
6134 			"do not call blocking ops when !TASK_RUNNING; "
6135 			"state=%lx set at [<%p>] %pS\n",
6136 			current->state,
6137 			(void *)current->task_state_change,
6138 			(void *)current->task_state_change);
6139 
6140 	___might_sleep(file, line, preempt_offset);
6141 }
6142 EXPORT_SYMBOL(__might_sleep);
6143 
6144 void ___might_sleep(const char *file, int line, int preempt_offset)
6145 {
6146 	/* Ratelimiting timestamp: */
6147 	static unsigned long prev_jiffy;
6148 
6149 	unsigned long preempt_disable_ip;
6150 
6151 	/* WARN_ON_ONCE() by default, no rate limit required: */
6152 	rcu_sleep_check();
6153 
6154 	if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
6155 	     !is_idle_task(current)) ||
6156 	    system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING ||
6157 	    oops_in_progress)
6158 		return;
6159 
6160 	if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
6161 		return;
6162 	prev_jiffy = jiffies;
6163 
6164 	/* Save this before calling printk(), since that will clobber it: */
6165 	preempt_disable_ip = get_preempt_disable_ip(current);
6166 
6167 	printk(KERN_ERR
6168 		"BUG: sleeping function called from invalid context at %s:%d\n",
6169 			file, line);
6170 	printk(KERN_ERR
6171 		"in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
6172 			in_atomic(), irqs_disabled(),
6173 			current->pid, current->comm);
6174 
6175 	if (task_stack_end_corrupted(current))
6176 		printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
6177 
6178 	debug_show_held_locks(current);
6179 	if (irqs_disabled())
6180 		print_irqtrace_events(current);
6181 	if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
6182 	    && !preempt_count_equals(preempt_offset)) {
6183 		pr_err("Preemption disabled at:");
6184 		print_ip_sym(preempt_disable_ip);
6185 		pr_cont("\n");
6186 	}
6187 	dump_stack();
6188 	add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
6189 }
6190 EXPORT_SYMBOL(___might_sleep);
6191 #endif
6192 
6193 #ifdef CONFIG_MAGIC_SYSRQ
6194 void normalize_rt_tasks(void)
6195 {
6196 	struct task_struct *g, *p;
6197 	struct sched_attr attr = {
6198 		.sched_policy = SCHED_NORMAL,
6199 	};
6200 
6201 	read_lock(&tasklist_lock);
6202 	for_each_process_thread(g, p) {
6203 		/*
6204 		 * Only normalize user tasks:
6205 		 */
6206 		if (p->flags & PF_KTHREAD)
6207 			continue;
6208 
6209 		p->se.exec_start = 0;
6210 		schedstat_set(p->se.statistics.wait_start,  0);
6211 		schedstat_set(p->se.statistics.sleep_start, 0);
6212 		schedstat_set(p->se.statistics.block_start, 0);
6213 
6214 		if (!dl_task(p) && !rt_task(p)) {
6215 			/*
6216 			 * Renice negative nice level userspace
6217 			 * tasks back to 0:
6218 			 */
6219 			if (task_nice(p) < 0)
6220 				set_user_nice(p, 0);
6221 			continue;
6222 		}
6223 
6224 		__sched_setscheduler(p, &attr, false, false);
6225 	}
6226 	read_unlock(&tasklist_lock);
6227 }
6228 
6229 #endif /* CONFIG_MAGIC_SYSRQ */
6230 
6231 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
6232 /*
6233  * These functions are only useful for the IA64 MCA handling, or kdb.
6234  *
6235  * They can only be called when the whole system has been
6236  * stopped - every CPU needs to be quiescent, and no scheduling
6237  * activity can take place. Using them for anything else would
6238  * be a serious bug, and as a result, they aren't even visible
6239  * under any other configuration.
6240  */
6241 
6242 /**
6243  * curr_task - return the current task for a given CPU.
6244  * @cpu: the processor in question.
6245  *
6246  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6247  *
6248  * Return: The current task for @cpu.
6249  */
6250 struct task_struct *curr_task(int cpu)
6251 {
6252 	return cpu_curr(cpu);
6253 }
6254 
6255 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
6256 
6257 #ifdef CONFIG_IA64
6258 /**
6259  * set_curr_task - set the current task for a given CPU.
6260  * @cpu: the processor in question.
6261  * @p: the task pointer to set.
6262  *
6263  * Description: This function must only be used when non-maskable interrupts
6264  * are serviced on a separate stack. It allows the architecture to switch the
6265  * notion of the current task on a CPU in a non-blocking manner. This function
6266  * must be called with all CPU's synchronized, and interrupts disabled, the
6267  * and caller must save the original value of the current task (see
6268  * curr_task() above) and restore that value before reenabling interrupts and
6269  * re-starting the system.
6270  *
6271  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
6272  */
6273 void ia64_set_curr_task(int cpu, struct task_struct *p)
6274 {
6275 	cpu_curr(cpu) = p;
6276 }
6277 
6278 #endif
6279 
6280 #ifdef CONFIG_CGROUP_SCHED
6281 /* task_group_lock serializes the addition/removal of task groups */
6282 static DEFINE_SPINLOCK(task_group_lock);
6283 
6284 static void sched_free_group(struct task_group *tg)
6285 {
6286 	free_fair_sched_group(tg);
6287 	free_rt_sched_group(tg);
6288 	autogroup_free(tg);
6289 	kmem_cache_free(task_group_cache, tg);
6290 }
6291 
6292 /* allocate runqueue etc for a new task group */
6293 struct task_group *sched_create_group(struct task_group *parent)
6294 {
6295 	struct task_group *tg;
6296 
6297 	tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
6298 	if (!tg)
6299 		return ERR_PTR(-ENOMEM);
6300 
6301 	if (!alloc_fair_sched_group(tg, parent))
6302 		goto err;
6303 
6304 	if (!alloc_rt_sched_group(tg, parent))
6305 		goto err;
6306 
6307 	return tg;
6308 
6309 err:
6310 	sched_free_group(tg);
6311 	return ERR_PTR(-ENOMEM);
6312 }
6313 
6314 void sched_online_group(struct task_group *tg, struct task_group *parent)
6315 {
6316 	unsigned long flags;
6317 
6318 	spin_lock_irqsave(&task_group_lock, flags);
6319 	list_add_rcu(&tg->list, &task_groups);
6320 
6321 	/* Root should already exist: */
6322 	WARN_ON(!parent);
6323 
6324 	tg->parent = parent;
6325 	INIT_LIST_HEAD(&tg->children);
6326 	list_add_rcu(&tg->siblings, &parent->children);
6327 	spin_unlock_irqrestore(&task_group_lock, flags);
6328 
6329 	online_fair_sched_group(tg);
6330 }
6331 
6332 /* rcu callback to free various structures associated with a task group */
6333 static void sched_free_group_rcu(struct rcu_head *rhp)
6334 {
6335 	/* Now it should be safe to free those cfs_rqs: */
6336 	sched_free_group(container_of(rhp, struct task_group, rcu));
6337 }
6338 
6339 void sched_destroy_group(struct task_group *tg)
6340 {
6341 	/* Wait for possible concurrent references to cfs_rqs complete: */
6342 	call_rcu(&tg->rcu, sched_free_group_rcu);
6343 }
6344 
6345 void sched_offline_group(struct task_group *tg)
6346 {
6347 	unsigned long flags;
6348 
6349 	/* End participation in shares distribution: */
6350 	unregister_fair_sched_group(tg);
6351 
6352 	spin_lock_irqsave(&task_group_lock, flags);
6353 	list_del_rcu(&tg->list);
6354 	list_del_rcu(&tg->siblings);
6355 	spin_unlock_irqrestore(&task_group_lock, flags);
6356 }
6357 
6358 static void sched_change_group(struct task_struct *tsk, int type)
6359 {
6360 	struct task_group *tg;
6361 
6362 	/*
6363 	 * All callers are synchronized by task_rq_lock(); we do not use RCU
6364 	 * which is pointless here. Thus, we pass "true" to task_css_check()
6365 	 * to prevent lockdep warnings.
6366 	 */
6367 	tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
6368 			  struct task_group, css);
6369 	tg = autogroup_task_group(tsk, tg);
6370 	tsk->sched_task_group = tg;
6371 
6372 #ifdef CONFIG_FAIR_GROUP_SCHED
6373 	if (tsk->sched_class->task_change_group)
6374 		tsk->sched_class->task_change_group(tsk, type);
6375 	else
6376 #endif
6377 		set_task_rq(tsk, task_cpu(tsk));
6378 }
6379 
6380 /*
6381  * Change task's runqueue when it moves between groups.
6382  *
6383  * The caller of this function should have put the task in its new group by
6384  * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
6385  * its new group.
6386  */
6387 void sched_move_task(struct task_struct *tsk)
6388 {
6389 	int queued, running, queue_flags =
6390 		DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
6391 	struct rq_flags rf;
6392 	struct rq *rq;
6393 
6394 	rq = task_rq_lock(tsk, &rf);
6395 	update_rq_clock(rq);
6396 
6397 	running = task_current(rq, tsk);
6398 	queued = task_on_rq_queued(tsk);
6399 
6400 	if (queued)
6401 		dequeue_task(rq, tsk, queue_flags);
6402 	if (running)
6403 		put_prev_task(rq, tsk);
6404 
6405 	sched_change_group(tsk, TASK_MOVE_GROUP);
6406 
6407 	if (queued)
6408 		enqueue_task(rq, tsk, queue_flags);
6409 	if (running)
6410 		set_curr_task(rq, tsk);
6411 
6412 	task_rq_unlock(rq, tsk, &rf);
6413 }
6414 
6415 static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
6416 {
6417 	return css ? container_of(css, struct task_group, css) : NULL;
6418 }
6419 
6420 static struct cgroup_subsys_state *
6421 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
6422 {
6423 	struct task_group *parent = css_tg(parent_css);
6424 	struct task_group *tg;
6425 
6426 	if (!parent) {
6427 		/* This is early initialization for the top cgroup */
6428 		return &root_task_group.css;
6429 	}
6430 
6431 	tg = sched_create_group(parent);
6432 	if (IS_ERR(tg))
6433 		return ERR_PTR(-ENOMEM);
6434 
6435 	return &tg->css;
6436 }
6437 
6438 /* Expose task group only after completing cgroup initialization */
6439 static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
6440 {
6441 	struct task_group *tg = css_tg(css);
6442 	struct task_group *parent = css_tg(css->parent);
6443 
6444 	if (parent)
6445 		sched_online_group(tg, parent);
6446 	return 0;
6447 }
6448 
6449 static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
6450 {
6451 	struct task_group *tg = css_tg(css);
6452 
6453 	sched_offline_group(tg);
6454 }
6455 
6456 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
6457 {
6458 	struct task_group *tg = css_tg(css);
6459 
6460 	/*
6461 	 * Relies on the RCU grace period between css_released() and this.
6462 	 */
6463 	sched_free_group(tg);
6464 }
6465 
6466 /*
6467  * This is called before wake_up_new_task(), therefore we really only
6468  * have to set its group bits, all the other stuff does not apply.
6469  */
6470 static void cpu_cgroup_fork(struct task_struct *task)
6471 {
6472 	struct rq_flags rf;
6473 	struct rq *rq;
6474 
6475 	rq = task_rq_lock(task, &rf);
6476 
6477 	update_rq_clock(rq);
6478 	sched_change_group(task, TASK_SET_GROUP);
6479 
6480 	task_rq_unlock(rq, task, &rf);
6481 }
6482 
6483 static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
6484 {
6485 	struct task_struct *task;
6486 	struct cgroup_subsys_state *css;
6487 	int ret = 0;
6488 
6489 	cgroup_taskset_for_each(task, css, tset) {
6490 #ifdef CONFIG_RT_GROUP_SCHED
6491 		if (!sched_rt_can_attach(css_tg(css), task))
6492 			return -EINVAL;
6493 #else
6494 		/* We don't support RT-tasks being in separate groups */
6495 		if (task->sched_class != &fair_sched_class)
6496 			return -EINVAL;
6497 #endif
6498 		/*
6499 		 * Serialize against wake_up_new_task() such that if its
6500 		 * running, we're sure to observe its full state.
6501 		 */
6502 		raw_spin_lock_irq(&task->pi_lock);
6503 		/*
6504 		 * Avoid calling sched_move_task() before wake_up_new_task()
6505 		 * has happened. This would lead to problems with PELT, due to
6506 		 * move wanting to detach+attach while we're not attached yet.
6507 		 */
6508 		if (task->state == TASK_NEW)
6509 			ret = -EINVAL;
6510 		raw_spin_unlock_irq(&task->pi_lock);
6511 
6512 		if (ret)
6513 			break;
6514 	}
6515 	return ret;
6516 }
6517 
6518 static void cpu_cgroup_attach(struct cgroup_taskset *tset)
6519 {
6520 	struct task_struct *task;
6521 	struct cgroup_subsys_state *css;
6522 
6523 	cgroup_taskset_for_each(task, css, tset)
6524 		sched_move_task(task);
6525 }
6526 
6527 #ifdef CONFIG_FAIR_GROUP_SCHED
6528 static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
6529 				struct cftype *cftype, u64 shareval)
6530 {
6531 	return sched_group_set_shares(css_tg(css), scale_load(shareval));
6532 }
6533 
6534 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
6535 			       struct cftype *cft)
6536 {
6537 	struct task_group *tg = css_tg(css);
6538 
6539 	return (u64) scale_load_down(tg->shares);
6540 }
6541 
6542 #ifdef CONFIG_CFS_BANDWIDTH
6543 static DEFINE_MUTEX(cfs_constraints_mutex);
6544 
6545 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
6546 const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
6547 
6548 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
6549 
6550 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
6551 {
6552 	int i, ret = 0, runtime_enabled, runtime_was_enabled;
6553 	struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6554 
6555 	if (tg == &root_task_group)
6556 		return -EINVAL;
6557 
6558 	/*
6559 	 * Ensure we have at some amount of bandwidth every period.  This is
6560 	 * to prevent reaching a state of large arrears when throttled via
6561 	 * entity_tick() resulting in prolonged exit starvation.
6562 	 */
6563 	if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
6564 		return -EINVAL;
6565 
6566 	/*
6567 	 * Likewise, bound things on the otherside by preventing insane quota
6568 	 * periods.  This also allows us to normalize in computing quota
6569 	 * feasibility.
6570 	 */
6571 	if (period > max_cfs_quota_period)
6572 		return -EINVAL;
6573 
6574 	/*
6575 	 * Prevent race between setting of cfs_rq->runtime_enabled and
6576 	 * unthrottle_offline_cfs_rqs().
6577 	 */
6578 	get_online_cpus();
6579 	mutex_lock(&cfs_constraints_mutex);
6580 	ret = __cfs_schedulable(tg, period, quota);
6581 	if (ret)
6582 		goto out_unlock;
6583 
6584 	runtime_enabled = quota != RUNTIME_INF;
6585 	runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
6586 	/*
6587 	 * If we need to toggle cfs_bandwidth_used, off->on must occur
6588 	 * before making related changes, and on->off must occur afterwards
6589 	 */
6590 	if (runtime_enabled && !runtime_was_enabled)
6591 		cfs_bandwidth_usage_inc();
6592 	raw_spin_lock_irq(&cfs_b->lock);
6593 	cfs_b->period = ns_to_ktime(period);
6594 	cfs_b->quota = quota;
6595 
6596 	__refill_cfs_bandwidth_runtime(cfs_b);
6597 
6598 	/* Restart the period timer (if active) to handle new period expiry: */
6599 	if (runtime_enabled)
6600 		start_cfs_bandwidth(cfs_b);
6601 
6602 	raw_spin_unlock_irq(&cfs_b->lock);
6603 
6604 	for_each_online_cpu(i) {
6605 		struct cfs_rq *cfs_rq = tg->cfs_rq[i];
6606 		struct rq *rq = cfs_rq->rq;
6607 		struct rq_flags rf;
6608 
6609 		rq_lock_irq(rq, &rf);
6610 		cfs_rq->runtime_enabled = runtime_enabled;
6611 		cfs_rq->runtime_remaining = 0;
6612 
6613 		if (cfs_rq->throttled)
6614 			unthrottle_cfs_rq(cfs_rq);
6615 		rq_unlock_irq(rq, &rf);
6616 	}
6617 	if (runtime_was_enabled && !runtime_enabled)
6618 		cfs_bandwidth_usage_dec();
6619 out_unlock:
6620 	mutex_unlock(&cfs_constraints_mutex);
6621 	put_online_cpus();
6622 
6623 	return ret;
6624 }
6625 
6626 int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
6627 {
6628 	u64 quota, period;
6629 
6630 	period = ktime_to_ns(tg->cfs_bandwidth.period);
6631 	if (cfs_quota_us < 0)
6632 		quota = RUNTIME_INF;
6633 	else
6634 		quota = (u64)cfs_quota_us * NSEC_PER_USEC;
6635 
6636 	return tg_set_cfs_bandwidth(tg, period, quota);
6637 }
6638 
6639 long tg_get_cfs_quota(struct task_group *tg)
6640 {
6641 	u64 quota_us;
6642 
6643 	if (tg->cfs_bandwidth.quota == RUNTIME_INF)
6644 		return -1;
6645 
6646 	quota_us = tg->cfs_bandwidth.quota;
6647 	do_div(quota_us, NSEC_PER_USEC);
6648 
6649 	return quota_us;
6650 }
6651 
6652 int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
6653 {
6654 	u64 quota, period;
6655 
6656 	period = (u64)cfs_period_us * NSEC_PER_USEC;
6657 	quota = tg->cfs_bandwidth.quota;
6658 
6659 	return tg_set_cfs_bandwidth(tg, period, quota);
6660 }
6661 
6662 long tg_get_cfs_period(struct task_group *tg)
6663 {
6664 	u64 cfs_period_us;
6665 
6666 	cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
6667 	do_div(cfs_period_us, NSEC_PER_USEC);
6668 
6669 	return cfs_period_us;
6670 }
6671 
6672 static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
6673 				  struct cftype *cft)
6674 {
6675 	return tg_get_cfs_quota(css_tg(css));
6676 }
6677 
6678 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
6679 				   struct cftype *cftype, s64 cfs_quota_us)
6680 {
6681 	return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
6682 }
6683 
6684 static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
6685 				   struct cftype *cft)
6686 {
6687 	return tg_get_cfs_period(css_tg(css));
6688 }
6689 
6690 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
6691 				    struct cftype *cftype, u64 cfs_period_us)
6692 {
6693 	return tg_set_cfs_period(css_tg(css), cfs_period_us);
6694 }
6695 
6696 struct cfs_schedulable_data {
6697 	struct task_group *tg;
6698 	u64 period, quota;
6699 };
6700 
6701 /*
6702  * normalize group quota/period to be quota/max_period
6703  * note: units are usecs
6704  */
6705 static u64 normalize_cfs_quota(struct task_group *tg,
6706 			       struct cfs_schedulable_data *d)
6707 {
6708 	u64 quota, period;
6709 
6710 	if (tg == d->tg) {
6711 		period = d->period;
6712 		quota = d->quota;
6713 	} else {
6714 		period = tg_get_cfs_period(tg);
6715 		quota = tg_get_cfs_quota(tg);
6716 	}
6717 
6718 	/* note: these should typically be equivalent */
6719 	if (quota == RUNTIME_INF || quota == -1)
6720 		return RUNTIME_INF;
6721 
6722 	return to_ratio(period, quota);
6723 }
6724 
6725 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
6726 {
6727 	struct cfs_schedulable_data *d = data;
6728 	struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6729 	s64 quota = 0, parent_quota = -1;
6730 
6731 	if (!tg->parent) {
6732 		quota = RUNTIME_INF;
6733 	} else {
6734 		struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
6735 
6736 		quota = normalize_cfs_quota(tg, d);
6737 		parent_quota = parent_b->hierarchical_quota;
6738 
6739 		/*
6740 		 * Ensure max(child_quota) <= parent_quota.  On cgroup2,
6741 		 * always take the min.  On cgroup1, only inherit when no
6742 		 * limit is set:
6743 		 */
6744 		if (cgroup_subsys_on_dfl(cpu_cgrp_subsys)) {
6745 			quota = min(quota, parent_quota);
6746 		} else {
6747 			if (quota == RUNTIME_INF)
6748 				quota = parent_quota;
6749 			else if (parent_quota != RUNTIME_INF && quota > parent_quota)
6750 				return -EINVAL;
6751 		}
6752 	}
6753 	cfs_b->hierarchical_quota = quota;
6754 
6755 	return 0;
6756 }
6757 
6758 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
6759 {
6760 	int ret;
6761 	struct cfs_schedulable_data data = {
6762 		.tg = tg,
6763 		.period = period,
6764 		.quota = quota,
6765 	};
6766 
6767 	if (quota != RUNTIME_INF) {
6768 		do_div(data.period, NSEC_PER_USEC);
6769 		do_div(data.quota, NSEC_PER_USEC);
6770 	}
6771 
6772 	rcu_read_lock();
6773 	ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
6774 	rcu_read_unlock();
6775 
6776 	return ret;
6777 }
6778 
6779 static int cpu_cfs_stat_show(struct seq_file *sf, void *v)
6780 {
6781 	struct task_group *tg = css_tg(seq_css(sf));
6782 	struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6783 
6784 	seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
6785 	seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
6786 	seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
6787 
6788 	return 0;
6789 }
6790 #endif /* CONFIG_CFS_BANDWIDTH */
6791 #endif /* CONFIG_FAIR_GROUP_SCHED */
6792 
6793 #ifdef CONFIG_RT_GROUP_SCHED
6794 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
6795 				struct cftype *cft, s64 val)
6796 {
6797 	return sched_group_set_rt_runtime(css_tg(css), val);
6798 }
6799 
6800 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
6801 			       struct cftype *cft)
6802 {
6803 	return sched_group_rt_runtime(css_tg(css));
6804 }
6805 
6806 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
6807 				    struct cftype *cftype, u64 rt_period_us)
6808 {
6809 	return sched_group_set_rt_period(css_tg(css), rt_period_us);
6810 }
6811 
6812 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
6813 				   struct cftype *cft)
6814 {
6815 	return sched_group_rt_period(css_tg(css));
6816 }
6817 #endif /* CONFIG_RT_GROUP_SCHED */
6818 
6819 static struct cftype cpu_legacy_files[] = {
6820 #ifdef CONFIG_FAIR_GROUP_SCHED
6821 	{
6822 		.name = "shares",
6823 		.read_u64 = cpu_shares_read_u64,
6824 		.write_u64 = cpu_shares_write_u64,
6825 	},
6826 #endif
6827 #ifdef CONFIG_CFS_BANDWIDTH
6828 	{
6829 		.name = "cfs_quota_us",
6830 		.read_s64 = cpu_cfs_quota_read_s64,
6831 		.write_s64 = cpu_cfs_quota_write_s64,
6832 	},
6833 	{
6834 		.name = "cfs_period_us",
6835 		.read_u64 = cpu_cfs_period_read_u64,
6836 		.write_u64 = cpu_cfs_period_write_u64,
6837 	},
6838 	{
6839 		.name = "stat",
6840 		.seq_show = cpu_cfs_stat_show,
6841 	},
6842 #endif
6843 #ifdef CONFIG_RT_GROUP_SCHED
6844 	{
6845 		.name = "rt_runtime_us",
6846 		.read_s64 = cpu_rt_runtime_read,
6847 		.write_s64 = cpu_rt_runtime_write,
6848 	},
6849 	{
6850 		.name = "rt_period_us",
6851 		.read_u64 = cpu_rt_period_read_uint,
6852 		.write_u64 = cpu_rt_period_write_uint,
6853 	},
6854 #endif
6855 	{ }	/* Terminate */
6856 };
6857 
6858 static int cpu_extra_stat_show(struct seq_file *sf,
6859 			       struct cgroup_subsys_state *css)
6860 {
6861 #ifdef CONFIG_CFS_BANDWIDTH
6862 	{
6863 		struct task_group *tg = css_tg(css);
6864 		struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
6865 		u64 throttled_usec;
6866 
6867 		throttled_usec = cfs_b->throttled_time;
6868 		do_div(throttled_usec, NSEC_PER_USEC);
6869 
6870 		seq_printf(sf, "nr_periods %d\n"
6871 			   "nr_throttled %d\n"
6872 			   "throttled_usec %llu\n",
6873 			   cfs_b->nr_periods, cfs_b->nr_throttled,
6874 			   throttled_usec);
6875 	}
6876 #endif
6877 	return 0;
6878 }
6879 
6880 #ifdef CONFIG_FAIR_GROUP_SCHED
6881 static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css,
6882 			       struct cftype *cft)
6883 {
6884 	struct task_group *tg = css_tg(css);
6885 	u64 weight = scale_load_down(tg->shares);
6886 
6887 	return DIV_ROUND_CLOSEST_ULL(weight * CGROUP_WEIGHT_DFL, 1024);
6888 }
6889 
6890 static int cpu_weight_write_u64(struct cgroup_subsys_state *css,
6891 				struct cftype *cft, u64 weight)
6892 {
6893 	/*
6894 	 * cgroup weight knobs should use the common MIN, DFL and MAX
6895 	 * values which are 1, 100 and 10000 respectively.  While it loses
6896 	 * a bit of range on both ends, it maps pretty well onto the shares
6897 	 * value used by scheduler and the round-trip conversions preserve
6898 	 * the original value over the entire range.
6899 	 */
6900 	if (weight < CGROUP_WEIGHT_MIN || weight > CGROUP_WEIGHT_MAX)
6901 		return -ERANGE;
6902 
6903 	weight = DIV_ROUND_CLOSEST_ULL(weight * 1024, CGROUP_WEIGHT_DFL);
6904 
6905 	return sched_group_set_shares(css_tg(css), scale_load(weight));
6906 }
6907 
6908 static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css,
6909 				    struct cftype *cft)
6910 {
6911 	unsigned long weight = scale_load_down(css_tg(css)->shares);
6912 	int last_delta = INT_MAX;
6913 	int prio, delta;
6914 
6915 	/* find the closest nice value to the current weight */
6916 	for (prio = 0; prio < ARRAY_SIZE(sched_prio_to_weight); prio++) {
6917 		delta = abs(sched_prio_to_weight[prio] - weight);
6918 		if (delta >= last_delta)
6919 			break;
6920 		last_delta = delta;
6921 	}
6922 
6923 	return PRIO_TO_NICE(prio - 1 + MAX_RT_PRIO);
6924 }
6925 
6926 static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css,
6927 				     struct cftype *cft, s64 nice)
6928 {
6929 	unsigned long weight;
6930 	int idx;
6931 
6932 	if (nice < MIN_NICE || nice > MAX_NICE)
6933 		return -ERANGE;
6934 
6935 	idx = NICE_TO_PRIO(nice) - MAX_RT_PRIO;
6936 	idx = array_index_nospec(idx, 40);
6937 	weight = sched_prio_to_weight[idx];
6938 
6939 	return sched_group_set_shares(css_tg(css), scale_load(weight));
6940 }
6941 #endif
6942 
6943 static void __maybe_unused cpu_period_quota_print(struct seq_file *sf,
6944 						  long period, long quota)
6945 {
6946 	if (quota < 0)
6947 		seq_puts(sf, "max");
6948 	else
6949 		seq_printf(sf, "%ld", quota);
6950 
6951 	seq_printf(sf, " %ld\n", period);
6952 }
6953 
6954 /* caller should put the current value in *@periodp before calling */
6955 static int __maybe_unused cpu_period_quota_parse(char *buf,
6956 						 u64 *periodp, u64 *quotap)
6957 {
6958 	char tok[21];	/* U64_MAX */
6959 
6960 	if (!sscanf(buf, "%s %llu", tok, periodp))
6961 		return -EINVAL;
6962 
6963 	*periodp *= NSEC_PER_USEC;
6964 
6965 	if (sscanf(tok, "%llu", quotap))
6966 		*quotap *= NSEC_PER_USEC;
6967 	else if (!strcmp(tok, "max"))
6968 		*quotap = RUNTIME_INF;
6969 	else
6970 		return -EINVAL;
6971 
6972 	return 0;
6973 }
6974 
6975 #ifdef CONFIG_CFS_BANDWIDTH
6976 static int cpu_max_show(struct seq_file *sf, void *v)
6977 {
6978 	struct task_group *tg = css_tg(seq_css(sf));
6979 
6980 	cpu_period_quota_print(sf, tg_get_cfs_period(tg), tg_get_cfs_quota(tg));
6981 	return 0;
6982 }
6983 
6984 static ssize_t cpu_max_write(struct kernfs_open_file *of,
6985 			     char *buf, size_t nbytes, loff_t off)
6986 {
6987 	struct task_group *tg = css_tg(of_css(of));
6988 	u64 period = tg_get_cfs_period(tg);
6989 	u64 quota;
6990 	int ret;
6991 
6992 	ret = cpu_period_quota_parse(buf, &period, &quota);
6993 	if (!ret)
6994 		ret = tg_set_cfs_bandwidth(tg, period, quota);
6995 	return ret ?: nbytes;
6996 }
6997 #endif
6998 
6999 static struct cftype cpu_files[] = {
7000 #ifdef CONFIG_FAIR_GROUP_SCHED
7001 	{
7002 		.name = "weight",
7003 		.flags = CFTYPE_NOT_ON_ROOT,
7004 		.read_u64 = cpu_weight_read_u64,
7005 		.write_u64 = cpu_weight_write_u64,
7006 	},
7007 	{
7008 		.name = "weight.nice",
7009 		.flags = CFTYPE_NOT_ON_ROOT,
7010 		.read_s64 = cpu_weight_nice_read_s64,
7011 		.write_s64 = cpu_weight_nice_write_s64,
7012 	},
7013 #endif
7014 #ifdef CONFIG_CFS_BANDWIDTH
7015 	{
7016 		.name = "max",
7017 		.flags = CFTYPE_NOT_ON_ROOT,
7018 		.seq_show = cpu_max_show,
7019 		.write = cpu_max_write,
7020 	},
7021 #endif
7022 	{ }	/* terminate */
7023 };
7024 
7025 struct cgroup_subsys cpu_cgrp_subsys = {
7026 	.css_alloc	= cpu_cgroup_css_alloc,
7027 	.css_online	= cpu_cgroup_css_online,
7028 	.css_released	= cpu_cgroup_css_released,
7029 	.css_free	= cpu_cgroup_css_free,
7030 	.css_extra_stat_show = cpu_extra_stat_show,
7031 	.fork		= cpu_cgroup_fork,
7032 	.can_attach	= cpu_cgroup_can_attach,
7033 	.attach		= cpu_cgroup_attach,
7034 	.legacy_cftypes	= cpu_legacy_files,
7035 	.dfl_cftypes	= cpu_files,
7036 	.early_init	= true,
7037 	.threaded	= true,
7038 };
7039 
7040 #endif	/* CONFIG_CGROUP_SCHED */
7041 
7042 void dump_cpu_task(int cpu)
7043 {
7044 	pr_info("Task dump for CPU %d:\n", cpu);
7045 	sched_show_task(cpu_curr(cpu));
7046 }
7047 
7048 /*
7049  * Nice levels are multiplicative, with a gentle 10% change for every
7050  * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
7051  * nice 1, it will get ~10% less CPU time than another CPU-bound task
7052  * that remained on nice 0.
7053  *
7054  * The "10% effect" is relative and cumulative: from _any_ nice level,
7055  * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
7056  * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
7057  * If a task goes up by ~10% and another task goes down by ~10% then
7058  * the relative distance between them is ~25%.)
7059  */
7060 const int sched_prio_to_weight[40] = {
7061  /* -20 */     88761,     71755,     56483,     46273,     36291,
7062  /* -15 */     29154,     23254,     18705,     14949,     11916,
7063  /* -10 */      9548,      7620,      6100,      4904,      3906,
7064  /*  -5 */      3121,      2501,      1991,      1586,      1277,
7065  /*   0 */      1024,       820,       655,       526,       423,
7066  /*   5 */       335,       272,       215,       172,       137,
7067  /*  10 */       110,        87,        70,        56,        45,
7068  /*  15 */        36,        29,        23,        18,        15,
7069 };
7070 
7071 /*
7072  * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
7073  *
7074  * In cases where the weight does not change often, we can use the
7075  * precalculated inverse to speed up arithmetics by turning divisions
7076  * into multiplications:
7077  */
7078 const u32 sched_prio_to_wmult[40] = {
7079  /* -20 */     48388,     59856,     76040,     92818,    118348,
7080  /* -15 */    147320,    184698,    229616,    287308,    360437,
7081  /* -10 */    449829,    563644,    704093,    875809,   1099582,
7082  /*  -5 */   1376151,   1717300,   2157191,   2708050,   3363326,
7083  /*   0 */   4194304,   5237765,   6557202,   8165337,  10153587,
7084  /*   5 */  12820798,  15790321,  19976592,  24970740,  31350126,
7085  /*  10 */  39045157,  49367440,  61356676,  76695844,  95443717,
7086  /*  15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
7087 };
7088 
7089 #undef CREATE_TRACE_POINTS
7090