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