• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #define CREATE_TRACE_POINTS
10 #include <trace/events/sched.h>
11 #undef CREATE_TRACE_POINTS
12 
13 #include "sched.h"
14 
15 #include <linux/nospec.h>
16 
17 #include <linux/kcov.h>
18 #include <linux/scs.h>
19 #include <linux/irq.h>
20 #include <linux/delay.h>
21 
22 #ifdef CONFIG_QOS_CTRL
23 #include <linux/sched/qos_ctrl.h>
24 #endif
25 
26 #include <asm/switch_to.h>
27 #include <asm/tlb.h>
28 
29 #include "../workqueue_internal.h"
30 #include "../../io_uring/io-wq.h"
31 #include "../smpboot.h"
32 
33 #include "pelt.h"
34 #include "smp.h"
35 #include "walt.h"
36 #include "rtg/rtg.h"
37 
38 /*
39  * Export tracepoints that act as a bare tracehook (ie: have no trace event
40  * associated with them) to allow external modules to probe them.
41  */
42 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_cfs_tp);
43 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_rt_tp);
44 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_dl_tp);
45 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_irq_tp);
46 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_se_tp);
47 EXPORT_TRACEPOINT_SYMBOL_GPL(pelt_thermal_tp);
48 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_cpu_capacity_tp);
49 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_overutilized_tp);
50 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_util_est_cfs_tp);
51 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_util_est_se_tp);
52 EXPORT_TRACEPOINT_SYMBOL_GPL(sched_update_nr_running_tp);
53 
54 DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues);
55 
56 #ifdef CONFIG_SCHED_DEBUG
57 /*
58  * Debugging: various feature bits
59  *
60  * If SCHED_DEBUG is disabled, each compilation unit has its own copy of
61  * sysctl_sched_features, defined in sched.h, to allow constants propagation
62  * at compile time and compiler optimization based on features default.
63  */
64 #define SCHED_FEAT(name, enabled)	\
65 	(1UL << __SCHED_FEAT_##name) * enabled |
66 const_debug unsigned int sysctl_sched_features =
67 #include "features.h"
68 	0;
69 #undef SCHED_FEAT
70 #endif
71 
72 /*
73  * Number of tasks to iterate in a single balance run.
74  * Limited because this is done with IRQs disabled.
75  */
76 const_debug unsigned int sysctl_sched_nr_migrate = 32;
77 
78 /*
79  * period over which we measure -rt task CPU usage in us.
80  * default: 1s
81  */
82 unsigned int sysctl_sched_rt_period = 1000000;
83 
84 __read_mostly int scheduler_running;
85 
86 /*
87  * part of the period that we allow rt tasks to run in us.
88  * default: 0.95s
89  */
90 int sysctl_sched_rt_runtime = 950000;
91 
92 
93 /*
94  * Serialization rules:
95  *
96  * Lock order:
97  *
98  *   p->pi_lock
99  *     rq->lock
100  *       hrtimer_cpu_base->lock (hrtimer_start() for bandwidth controls)
101  *
102  *  rq1->lock
103  *    rq2->lock  where: rq1 < rq2
104  *
105  * Regular state:
106  *
107  * Normal scheduling state is serialized by rq->lock. __schedule() takes the
108  * local CPU's rq->lock, it optionally removes the task from the runqueue and
109  * always looks at the local rq data structures to find the most elegible task
110  * to run next.
111  *
112  * Task enqueue is also under rq->lock, possibly taken from another CPU.
113  * Wakeups from another LLC domain might use an IPI to transfer the enqueue to
114  * the local CPU to avoid bouncing the runqueue state around [ see
115  * ttwu_queue_wakelist() ]
116  *
117  * Task wakeup, specifically wakeups that involve migration, are horribly
118  * complicated to avoid having to take two rq->locks.
119  *
120  * Special state:
121  *
122  * System-calls and anything external will use task_rq_lock() which acquires
123  * both p->pi_lock and rq->lock. As a consequence the state they change is
124  * stable while holding either lock:
125  *
126  *  - sched_setaffinity()/
127  *    set_cpus_allowed_ptr():	p->cpus_ptr, p->nr_cpus_allowed
128  *  - set_user_nice():		p->se.load, p->*prio
129  *  - __sched_setscheduler():	p->sched_class, p->policy, p->*prio,
130  *				p->se.load, p->rt_priority,
131  *				p->dl.dl_{runtime, deadline, period, flags, bw, density}
132  *  - sched_setnuma():		p->numa_preferred_nid
133  *  - sched_move_task()/
134  *    cpu_cgroup_fork():	p->sched_task_group
135  *  - uclamp_update_active()	p->uclamp*
136  *
137  * p->state <- TASK_*:
138  *
139  *   is changed locklessly using set_current_state(), __set_current_state() or
140  *   set_special_state(), see their respective comments, or by
141  *   try_to_wake_up(). This latter uses p->pi_lock to serialize against
142  *   concurrent self.
143  *
144  * p->on_rq <- { 0, 1 = TASK_ON_RQ_QUEUED, 2 = TASK_ON_RQ_MIGRATING }:
145  *
146  *   is set by activate_task() and cleared by deactivate_task(), under
147  *   rq->lock. Non-zero indicates the task is runnable, the special
148  *   ON_RQ_MIGRATING state is used for migration without holding both
149  *   rq->locks. It indicates task_cpu() is not stable, see task_rq_lock().
150  *
151  * p->on_cpu <- { 0, 1 }:
152  *
153  *   is set by prepare_task() and cleared by finish_task() such that it will be
154  *   set before p is scheduled-in and cleared after p is scheduled-out, both
155  *   under rq->lock. Non-zero indicates the task is running on its CPU.
156  *
157  *   [ The astute reader will observe that it is possible for two tasks on one
158  *     CPU to have ->on_cpu = 1 at the same time. ]
159  *
160  * task_cpu(p): is changed by set_task_cpu(), the rules are:
161  *
162  *  - Don't call set_task_cpu() on a blocked task:
163  *
164  *    We don't care what CPU we're not running on, this simplifies hotplug,
165  *    the CPU assignment of blocked tasks isn't required to be valid.
166  *
167  *  - for try_to_wake_up(), called under p->pi_lock:
168  *
169  *    This allows try_to_wake_up() to only take one rq->lock, see its comment.
170  *
171  *  - for migration called under rq->lock:
172  *    [ see task_on_rq_migrating() in task_rq_lock() ]
173  *
174  *    o move_queued_task()
175  *    o detach_task()
176  *
177  *  - for migration called under double_rq_lock():
178  *
179  *    o __migrate_swap_task()
180  *    o push_rt_task() / pull_rt_task()
181  *    o push_dl_task() / pull_dl_task()
182  *    o dl_task_offline_migration()
183  *
184  */
185 
186 /*
187  * __task_rq_lock - lock the rq @p resides on.
188  */
__task_rq_lock(struct task_struct * p,struct rq_flags * rf)189 struct rq *__task_rq_lock(struct task_struct *p, struct rq_flags *rf)
190 	__acquires(rq->lock)
191 {
192 	struct rq *rq;
193 
194 	lockdep_assert_held(&p->pi_lock);
195 
196 	for (;;) {
197 		rq = task_rq(p);
198 		raw_spin_lock(&rq->lock);
199 		if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
200 			rq_pin_lock(rq, rf);
201 			return rq;
202 		}
203 		raw_spin_unlock(&rq->lock);
204 
205 		while (unlikely(task_on_rq_migrating(p)))
206 			cpu_relax();
207 	}
208 }
209 
210 /*
211  * task_rq_lock - lock p->pi_lock and lock the rq @p resides on.
212  */
task_rq_lock(struct task_struct * p,struct rq_flags * rf)213 struct rq *task_rq_lock(struct task_struct *p, struct rq_flags *rf)
214 	__acquires(p->pi_lock)
215 	__acquires(rq->lock)
216 {
217 	struct rq *rq;
218 
219 	for (;;) {
220 		raw_spin_lock_irqsave(&p->pi_lock, rf->flags);
221 		rq = task_rq(p);
222 		raw_spin_lock(&rq->lock);
223 		/*
224 		 *	move_queued_task()		task_rq_lock()
225 		 *
226 		 *	ACQUIRE (rq->lock)
227 		 *	[S] ->on_rq = MIGRATING		[L] rq = task_rq()
228 		 *	WMB (__set_task_cpu())		ACQUIRE (rq->lock);
229 		 *	[S] ->cpu = new_cpu		[L] task_rq()
230 		 *					[L] ->on_rq
231 		 *	RELEASE (rq->lock)
232 		 *
233 		 * If we observe the old CPU in task_rq_lock(), the acquire of
234 		 * the old rq->lock will fully serialize against the stores.
235 		 *
236 		 * If we observe the new CPU in task_rq_lock(), the address
237 		 * dependency headed by '[L] rq = task_rq()' and the acquire
238 		 * will pair with the WMB to ensure we then also see migrating.
239 		 */
240 		if (likely(rq == task_rq(p) && !task_on_rq_migrating(p))) {
241 			rq_pin_lock(rq, rf);
242 			return rq;
243 		}
244 		raw_spin_unlock(&rq->lock);
245 		raw_spin_unlock_irqrestore(&p->pi_lock, rf->flags);
246 
247 		while (unlikely(task_on_rq_migrating(p)))
248 			cpu_relax();
249 	}
250 }
251 
252 /*
253  * RQ-clock updating methods:
254  */
255 
update_rq_clock_task(struct rq * rq,s64 delta)256 static void update_rq_clock_task(struct rq *rq, s64 delta)
257 {
258 /*
259  * In theory, the compile should just see 0 here, and optimize out the call
260  * to sched_rt_avg_update. But I don't trust it...
261  */
262 	s64 __maybe_unused steal = 0, irq_delta = 0;
263 
264 #ifdef CONFIG_IRQ_TIME_ACCOUNTING
265 	irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time;
266 
267 	/*
268 	 * Since irq_time is only updated on {soft,}irq_exit, we might run into
269 	 * this case when a previous update_rq_clock() happened inside a
270 	 * {soft,}irq region.
271 	 *
272 	 * When this happens, we stop ->clock_task and only update the
273 	 * prev_irq_time stamp to account for the part that fit, so that a next
274 	 * update will consume the rest. This ensures ->clock_task is
275 	 * monotonic.
276 	 *
277 	 * It does however cause some slight miss-attribution of {soft,}irq
278 	 * time, a more accurate solution would be to update the irq_time using
279 	 * the current rq->clock timestamp, except that would require using
280 	 * atomic ops.
281 	 */
282 	if (irq_delta > delta)
283 		irq_delta = delta;
284 
285 	rq->prev_irq_time += irq_delta;
286 	delta -= irq_delta;
287 #endif
288 #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING
289 	if (static_key_false((&paravirt_steal_rq_enabled))) {
290 		steal = paravirt_steal_clock(cpu_of(rq));
291 		steal -= rq->prev_steal_time_rq;
292 
293 		if (unlikely(steal > delta))
294 			steal = delta;
295 
296 		rq->prev_steal_time_rq += steal;
297 		delta -= steal;
298 	}
299 #endif
300 
301 	rq->clock_task += delta;
302 
303 #ifdef CONFIG_HAVE_SCHED_AVG_IRQ
304 	if ((irq_delta + steal) && sched_feat(NONTASK_CAPACITY))
305 		update_irq_load_avg(rq, irq_delta + steal);
306 #endif
307 	update_rq_clock_pelt(rq, delta);
308 }
309 
update_rq_clock(struct rq * rq)310 void update_rq_clock(struct rq *rq)
311 {
312 	s64 delta;
313 
314 	lockdep_assert_held(&rq->lock);
315 
316 	if (rq->clock_update_flags & RQCF_ACT_SKIP)
317 		return;
318 
319 #ifdef CONFIG_SCHED_DEBUG
320 	if (sched_feat(WARN_DOUBLE_CLOCK))
321 		SCHED_WARN_ON(rq->clock_update_flags & RQCF_UPDATED);
322 	rq->clock_update_flags |= RQCF_UPDATED;
323 #endif
324 
325 	delta = sched_clock_cpu(cpu_of(rq)) - rq->clock;
326 	if (delta < 0)
327 		return;
328 	rq->clock += delta;
329 	update_rq_clock_task(rq, delta);
330 }
331 
332 static inline void
rq_csd_init(struct rq * rq,struct __call_single_data * csd,smp_call_func_t func)333 rq_csd_init(struct rq *rq, struct __call_single_data *csd, smp_call_func_t func)
334 {
335 	csd->flags = 0;
336 	csd->func = func;
337 	csd->info = rq;
338 }
339 
340 #ifdef CONFIG_SCHED_HRTICK
341 /*
342  * Use HR-timers to deliver accurate preemption points.
343  */
344 
hrtick_clear(struct rq * rq)345 static void hrtick_clear(struct rq *rq)
346 {
347 	if (hrtimer_active(&rq->hrtick_timer))
348 		hrtimer_cancel(&rq->hrtick_timer);
349 }
350 
351 /*
352  * High-resolution timer tick.
353  * Runs from hardirq context with interrupts disabled.
354  */
hrtick(struct hrtimer * timer)355 static enum hrtimer_restart hrtick(struct hrtimer *timer)
356 {
357 	struct rq *rq = container_of(timer, struct rq, hrtick_timer);
358 	struct rq_flags rf;
359 
360 	WARN_ON_ONCE(cpu_of(rq) != smp_processor_id());
361 
362 	rq_lock(rq, &rf);
363 	update_rq_clock(rq);
364 	rq->curr->sched_class->task_tick(rq, rq->curr, 1);
365 	rq_unlock(rq, &rf);
366 
367 	return HRTIMER_NORESTART;
368 }
369 
370 #ifdef CONFIG_SMP
371 
__hrtick_restart(struct rq * rq)372 static void __hrtick_restart(struct rq *rq)
373 {
374 	struct hrtimer *timer = &rq->hrtick_timer;
375 	ktime_t time = rq->hrtick_time;
376 
377 	hrtimer_start(timer, time, HRTIMER_MODE_ABS_PINNED_HARD);
378 }
379 
380 /*
381  * called from hardirq (IPI) context
382  */
__hrtick_start(void * arg)383 static void __hrtick_start(void *arg)
384 {
385 	struct rq *rq = arg;
386 	struct rq_flags rf;
387 
388 	rq_lock(rq, &rf);
389 	__hrtick_restart(rq);
390 	rq_unlock(rq, &rf);
391 }
392 
393 /*
394  * Called to set the hrtick timer state.
395  *
396  * called with rq->lock held and irqs disabled
397  */
hrtick_start(struct rq * rq,u64 delay)398 void hrtick_start(struct rq *rq, u64 delay)
399 {
400 	struct hrtimer *timer = &rq->hrtick_timer;
401 	s64 delta;
402 
403 	/*
404 	 * Don't schedule slices shorter than 10000ns, that just
405 	 * doesn't make sense and can cause timer DoS.
406 	 */
407 	delta = max_t(s64, delay, 10000LL);
408 	rq->hrtick_time = ktime_add_ns(timer->base->get_time(), delta);
409 
410 	if (rq == this_rq())
411 		__hrtick_restart(rq);
412 	else
413 		smp_call_function_single_async(cpu_of(rq), &rq->hrtick_csd);
414 }
415 
416 #else
417 /*
418  * Called to set the hrtick timer state.
419  *
420  * called with rq->lock held and irqs disabled
421  */
hrtick_start(struct rq * rq,u64 delay)422 void hrtick_start(struct rq *rq, u64 delay)
423 {
424 	/*
425 	 * Don't schedule slices shorter than 10000ns, that just
426 	 * doesn't make sense. Rely on vruntime for fairness.
427 	 */
428 	delay = max_t(u64, delay, 10000LL);
429 	hrtimer_start(&rq->hrtick_timer, ns_to_ktime(delay),
430 		      HRTIMER_MODE_REL_PINNED_HARD);
431 }
432 
433 #endif /* CONFIG_SMP */
434 
hrtick_rq_init(struct rq * rq)435 static void hrtick_rq_init(struct rq *rq)
436 {
437 #ifdef CONFIG_SMP
438 	rq_csd_init(rq, &rq->hrtick_csd, __hrtick_start);
439 #endif
440 	hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL_HARD);
441 	rq->hrtick_timer.function = hrtick;
442 }
443 #else	/* CONFIG_SCHED_HRTICK */
hrtick_clear(struct rq * rq)444 static inline void hrtick_clear(struct rq *rq)
445 {
446 }
447 
hrtick_rq_init(struct rq * rq)448 static inline void hrtick_rq_init(struct rq *rq)
449 {
450 }
451 #endif	/* CONFIG_SCHED_HRTICK */
452 
453 /*
454  * cmpxchg based fetch_or, macro so it works for different integer types
455  */
456 #define fetch_or(ptr, mask)						\
457 	({								\
458 		typeof(ptr) _ptr = (ptr);				\
459 		typeof(mask) _mask = (mask);				\
460 		typeof(*_ptr) _old, _val = *_ptr;			\
461 									\
462 		for (;;) {						\
463 			_old = cmpxchg(_ptr, _val, _val | _mask);	\
464 			if (_old == _val)				\
465 				break;					\
466 			_val = _old;					\
467 		}							\
468 	_old;								\
469 })
470 
471 #if defined(CONFIG_SMP) && defined(TIF_POLLING_NRFLAG)
472 /*
473  * Atomically set TIF_NEED_RESCHED and test for TIF_POLLING_NRFLAG,
474  * this avoids any races wrt polling state changes and thereby avoids
475  * spurious IPIs.
476  */
set_nr_and_not_polling(struct task_struct * p)477 static bool set_nr_and_not_polling(struct task_struct *p)
478 {
479 	struct thread_info *ti = task_thread_info(p);
480 	return !(fetch_or(&ti->flags, _TIF_NEED_RESCHED) & _TIF_POLLING_NRFLAG);
481 }
482 
483 /*
484  * Atomically set TIF_NEED_RESCHED if TIF_POLLING_NRFLAG is set.
485  *
486  * If this returns true, then the idle task promises to call
487  * sched_ttwu_pending() and reschedule soon.
488  */
set_nr_if_polling(struct task_struct * p)489 static bool set_nr_if_polling(struct task_struct *p)
490 {
491 	struct thread_info *ti = task_thread_info(p);
492 	typeof(ti->flags) old, val = READ_ONCE(ti->flags);
493 
494 	for (;;) {
495 		if (!(val & _TIF_POLLING_NRFLAG))
496 			return false;
497 		if (val & _TIF_NEED_RESCHED)
498 			return true;
499 		old = cmpxchg(&ti->flags, val, val | _TIF_NEED_RESCHED);
500 		if (old == val)
501 			break;
502 		val = old;
503 	}
504 	return true;
505 }
506 
507 #else
set_nr_and_not_polling(struct task_struct * p)508 static bool set_nr_and_not_polling(struct task_struct *p)
509 {
510 	set_tsk_need_resched(p);
511 	return true;
512 }
513 
514 #ifdef CONFIG_SMP
set_nr_if_polling(struct task_struct * p)515 static bool set_nr_if_polling(struct task_struct *p)
516 {
517 	return false;
518 }
519 #endif
520 #endif
521 
__wake_q_add(struct wake_q_head * head,struct task_struct * task)522 static bool __wake_q_add(struct wake_q_head *head, struct task_struct *task)
523 {
524 	struct wake_q_node *node = &task->wake_q;
525 
526 	/*
527 	 * Atomically grab the task, if ->wake_q is !nil already it means
528 	 * its already queued (either by us or someone else) and will get the
529 	 * wakeup due to that.
530 	 *
531 	 * In order to ensure that a pending wakeup will observe our pending
532 	 * state, even in the failed case, an explicit smp_mb() must be used.
533 	 */
534 	smp_mb__before_atomic();
535 	if (unlikely(cmpxchg_relaxed(&node->next, NULL, WAKE_Q_TAIL)))
536 		return false;
537 
538 	/*
539 	 * The head is context local, there can be no concurrency.
540 	 */
541 	*head->lastp = node;
542 	head->lastp = &node->next;
543 	return true;
544 }
545 
546 /**
547  * wake_q_add() - queue a wakeup for 'later' waking.
548  * @head: the wake_q_head to add @task to
549  * @task: the task to queue for 'later' wakeup
550  *
551  * Queue a task for later wakeup, most likely by the wake_up_q() call in the
552  * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
553  * instantly.
554  *
555  * This function must be used as-if it were wake_up_process(); IOW the task
556  * must be ready to be woken at this location.
557  */
wake_q_add(struct wake_q_head * head,struct task_struct * task)558 void wake_q_add(struct wake_q_head *head, struct task_struct *task)
559 {
560 	if (__wake_q_add(head, task))
561 		get_task_struct(task);
562 }
563 
564 /**
565  * wake_q_add_safe() - safely queue a wakeup for 'later' waking.
566  * @head: the wake_q_head to add @task to
567  * @task: the task to queue for 'later' wakeup
568  *
569  * Queue a task for later wakeup, most likely by the wake_up_q() call in the
570  * same context, _HOWEVER_ this is not guaranteed, the wakeup can come
571  * instantly.
572  *
573  * This function must be used as-if it were wake_up_process(); IOW the task
574  * must be ready to be woken at this location.
575  *
576  * This function is essentially a task-safe equivalent to wake_q_add(). Callers
577  * that already hold reference to @task can call the 'safe' version and trust
578  * wake_q to do the right thing depending whether or not the @task is already
579  * queued for wakeup.
580  */
wake_q_add_safe(struct wake_q_head * head,struct task_struct * task)581 void wake_q_add_safe(struct wake_q_head *head, struct task_struct *task)
582 {
583 	if (!__wake_q_add(head, task))
584 		put_task_struct(task);
585 }
586 
wake_up_q(struct wake_q_head * head)587 void wake_up_q(struct wake_q_head *head)
588 {
589 	struct wake_q_node *node = head->first;
590 
591 	while (node != WAKE_Q_TAIL) {
592 		struct task_struct *task;
593 
594 		task = container_of(node, struct task_struct, wake_q);
595 		BUG_ON(!task);
596 		/* Task can safely be re-inserted now: */
597 		node = node->next;
598 		task->wake_q.next = NULL;
599 
600 		/*
601 		 * wake_up_process() executes a full barrier, which pairs with
602 		 * the queueing in wake_q_add() so as not to miss wakeups.
603 		 */
604 		wake_up_process(task);
605 		put_task_struct(task);
606 	}
607 }
608 
609 /*
610  * resched_curr - mark rq's current task 'to be rescheduled now'.
611  *
612  * On UP this means the setting of the need_resched flag, on SMP it
613  * might also involve a cross-CPU call to trigger the scheduler on
614  * the target CPU.
615  */
resched_curr(struct rq * rq)616 void resched_curr(struct rq *rq)
617 {
618 	struct task_struct *curr = rq->curr;
619 	int cpu;
620 
621 	lockdep_assert_held(&rq->lock);
622 
623 	if (test_tsk_need_resched(curr))
624 		return;
625 
626 	cpu = cpu_of(rq);
627 
628 	if (cpu == smp_processor_id()) {
629 		set_tsk_need_resched(curr);
630 		set_preempt_need_resched();
631 		return;
632 	}
633 
634 	if (set_nr_and_not_polling(curr))
635 		smp_send_reschedule(cpu);
636 	else
637 		trace_sched_wake_idle_without_ipi(cpu);
638 }
639 
resched_cpu(int cpu)640 void resched_cpu(int cpu)
641 {
642 	struct rq *rq = cpu_rq(cpu);
643 	unsigned long flags;
644 
645 	raw_spin_lock_irqsave(&rq->lock, flags);
646 	if (cpu_online(cpu) || cpu == smp_processor_id())
647 		resched_curr(rq);
648 	raw_spin_unlock_irqrestore(&rq->lock, flags);
649 }
650 
651 #ifdef CONFIG_SMP
652 #ifdef CONFIG_NO_HZ_COMMON
653 /*
654  * In the semi idle case, use the nearest busy CPU for migrating timers
655  * from an idle CPU.  This is good for power-savings.
656  *
657  * We don't do similar optimization for completely idle system, as
658  * selecting an idle CPU will add more delays to the timers than intended
659  * (as that CPU's timer base may not be uptodate wrt jiffies etc).
660  */
get_nohz_timer_target(void)661 int get_nohz_timer_target(void)
662 {
663 	int i, cpu = smp_processor_id(), default_cpu = -1;
664 	struct sched_domain *sd;
665 
666 	if (housekeeping_cpu(cpu, HK_FLAG_TIMER)) {
667 		if (!idle_cpu(cpu))
668 			return cpu;
669 		default_cpu = cpu;
670 	}
671 
672 	rcu_read_lock();
673 	for_each_domain(cpu, sd) {
674 		for_each_cpu_and(i, sched_domain_span(sd),
675 			housekeeping_cpumask(HK_FLAG_TIMER)) {
676 			if (cpu == i)
677 				continue;
678 
679 			if (!idle_cpu(i)) {
680 				cpu = i;
681 				goto unlock;
682 			}
683 		}
684 	}
685 
686 	if (default_cpu == -1)
687 		default_cpu = housekeeping_any_cpu(HK_FLAG_TIMER);
688 	cpu = default_cpu;
689 unlock:
690 	rcu_read_unlock();
691 	return cpu;
692 }
693 
694 /*
695  * When add_timer_on() enqueues a timer into the timer wheel of an
696  * idle CPU then this timer might expire before the next timer event
697  * which is scheduled to wake up that CPU. In case of a completely
698  * idle system the next event might even be infinite time into the
699  * future. wake_up_idle_cpu() ensures that the CPU is woken up and
700  * leaves the inner idle loop so the newly added timer is taken into
701  * account when the CPU goes back to idle and evaluates the timer
702  * wheel for the next timer event.
703  */
wake_up_idle_cpu(int cpu)704 static void wake_up_idle_cpu(int cpu)
705 {
706 	struct rq *rq = cpu_rq(cpu);
707 
708 	if (cpu == smp_processor_id())
709 		return;
710 
711 	if (set_nr_and_not_polling(rq->idle))
712 		smp_send_reschedule(cpu);
713 	else
714 		trace_sched_wake_idle_without_ipi(cpu);
715 }
716 
wake_up_full_nohz_cpu(int cpu)717 static bool wake_up_full_nohz_cpu(int cpu)
718 {
719 	/*
720 	 * We just need the target to call irq_exit() and re-evaluate
721 	 * the next tick. The nohz full kick at least implies that.
722 	 * If needed we can still optimize that later with an
723 	 * empty IRQ.
724 	 */
725 	if (cpu_is_offline(cpu))
726 		return true;  /* Don't try to wake offline CPUs. */
727 	if (tick_nohz_full_cpu(cpu)) {
728 		if (cpu != smp_processor_id() ||
729 		    tick_nohz_tick_stopped())
730 			tick_nohz_full_kick_cpu(cpu);
731 		return true;
732 	}
733 
734 	return false;
735 }
736 
737 /*
738  * Wake up the specified CPU.  If the CPU is going offline, it is the
739  * caller's responsibility to deal with the lost wakeup, for example,
740  * by hooking into the CPU_DEAD notifier like timers and hrtimers do.
741  */
wake_up_nohz_cpu(int cpu)742 void wake_up_nohz_cpu(int cpu)
743 {
744 	if (!wake_up_full_nohz_cpu(cpu))
745 		wake_up_idle_cpu(cpu);
746 }
747 
nohz_csd_func(void * info)748 static void nohz_csd_func(void *info)
749 {
750 	struct rq *rq = info;
751 	int cpu = cpu_of(rq);
752 	unsigned int flags;
753 
754 	/*
755 	 * Release the rq::nohz_csd.
756 	 */
757 	flags = atomic_fetch_andnot(NOHZ_KICK_MASK, nohz_flags(cpu));
758 	WARN_ON(!(flags & NOHZ_KICK_MASK));
759 
760 	rq->idle_balance = idle_cpu(cpu);
761 	if (rq->idle_balance && !need_resched()) {
762 		rq->nohz_idle_balance = flags;
763 		raise_softirq_irqoff(SCHED_SOFTIRQ);
764 	}
765 }
766 
767 #endif /* CONFIG_NO_HZ_COMMON */
768 
769 #ifdef CONFIG_NO_HZ_FULL
sched_can_stop_tick(struct rq * rq)770 bool sched_can_stop_tick(struct rq *rq)
771 {
772 	int fifo_nr_running;
773 
774 	/* Deadline tasks, even if single, need the tick */
775 	if (rq->dl.dl_nr_running)
776 		return false;
777 
778 	/*
779 	 * If there are more than one RR tasks, we need the tick to effect the
780 	 * actual RR behaviour.
781 	 */
782 	if (rq->rt.rr_nr_running) {
783 		if (rq->rt.rr_nr_running == 1)
784 			return true;
785 		else
786 			return false;
787 	}
788 
789 	/*
790 	 * If there's no RR tasks, but FIFO tasks, we can skip the tick, no
791 	 * forced preemption between FIFO tasks.
792 	 */
793 	fifo_nr_running = rq->rt.rt_nr_running - rq->rt.rr_nr_running;
794 	if (fifo_nr_running)
795 		return true;
796 
797 	/*
798 	 * If there are no DL,RR/FIFO tasks, there must only be CFS tasks left;
799 	 * if there's more than one we need the tick for involuntary
800 	 * preemption.
801 	 */
802 	if (rq->nr_running > 1)
803 		return false;
804 
805 	return true;
806 }
807 #endif /* CONFIG_NO_HZ_FULL */
808 #endif /* CONFIG_SMP */
809 
810 #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \
811 			(defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH)))
812 /*
813  * Iterate task_group tree rooted at *from, calling @down when first entering a
814  * node and @up when leaving it for the final time.
815  *
816  * Caller must hold rcu_lock or sufficient equivalent.
817  */
walk_tg_tree_from(struct task_group * from,tg_visitor down,tg_visitor up,void * data)818 int walk_tg_tree_from(struct task_group *from,
819 			     tg_visitor down, tg_visitor up, void *data)
820 {
821 	struct task_group *parent, *child;
822 	int ret;
823 
824 	parent = from;
825 
826 down:
827 	ret = (*down)(parent, data);
828 	if (ret)
829 		goto out;
830 	list_for_each_entry_rcu(child, &parent->children, siblings) {
831 		parent = child;
832 		goto down;
833 
834 up:
835 		continue;
836 	}
837 	ret = (*up)(parent, data);
838 	if (ret || parent == from)
839 		goto out;
840 
841 	child = parent;
842 	parent = parent->parent;
843 	if (parent)
844 		goto up;
845 out:
846 	return ret;
847 }
848 
tg_nop(struct task_group * tg,void * data)849 int tg_nop(struct task_group *tg, void *data)
850 {
851 	return 0;
852 }
853 #endif
854 
set_load_weight(struct task_struct * p)855 static void set_load_weight(struct task_struct *p)
856 {
857 	bool update_load = !(READ_ONCE(p->state) & TASK_NEW);
858 	int prio = p->static_prio - MAX_RT_PRIO;
859 	struct load_weight *load = &p->se.load;
860 
861 	/*
862 	 * SCHED_IDLE tasks get minimal weight:
863 	 */
864 	if (task_has_idle_policy(p)) {
865 		load->weight = scale_load(WEIGHT_IDLEPRIO);
866 		load->inv_weight = WMULT_IDLEPRIO;
867 		return;
868 	}
869 
870 	/*
871 	 * SCHED_OTHER tasks have to update their load when changing their
872 	 * weight
873 	 */
874 	if (update_load && p->sched_class == &fair_sched_class) {
875 		reweight_task(p, prio);
876 	} else {
877 		load->weight = scale_load(sched_prio_to_weight[prio]);
878 		load->inv_weight = sched_prio_to_wmult[prio];
879 	}
880 }
881 
882 #ifdef CONFIG_SCHED_LATENCY_NICE
set_latency_weight(struct task_struct * p)883 static void set_latency_weight(struct task_struct *p)
884 {
885 	p->se.latency_weight = sched_latency_to_weight[p->latency_prio];
886 }
887 
__setscheduler_latency(struct task_struct * p,const struct sched_attr * attr)888 static void __setscheduler_latency(struct task_struct *p,
889 		const struct sched_attr *attr)
890 {
891 	if (attr->sched_flags & SCHED_FLAG_LATENCY_NICE) {
892 		p->latency_prio = NICE_TO_LATENCY(attr->sched_latency_nice);
893 		set_latency_weight(p);
894 	}
895 }
896 
latency_nice_validate(struct task_struct * p,bool user,const struct sched_attr * attr)897 static int latency_nice_validate(struct task_struct *p, bool user,
898 				 const struct sched_attr *attr)
899 {
900 	if (attr->sched_latency_nice > MAX_LATENCY_NICE)
901 		return -EINVAL;
902 	if (attr->sched_latency_nice < MIN_LATENCY_NICE)
903 		return -EINVAL;
904 	/* Use the same security checks as NICE */
905 	if (user && attr->sched_latency_nice < LATENCY_TO_NICE(p->latency_prio)
906 	    && !capable(CAP_SYS_NICE))
907 		return -EPERM;
908 
909 	return 0;
910 }
911 #else
912 static void
__setscheduler_latency(struct task_struct * p,const struct sched_attr * attr)913 __setscheduler_latency(struct task_struct *p, const struct sched_attr *attr)
914 {
915 }
916 
917 static inline
latency_nice_validate(struct task_struct * p,bool user,const struct sched_attr * attr)918 int latency_nice_validate(struct task_struct *p, bool user,
919 			  const struct sched_attr *attr)
920 {
921 	return -EOPNOTSUPP;
922 }
923 #endif
924 
925 #ifdef CONFIG_UCLAMP_TASK
926 /*
927  * Serializes updates of utilization clamp values
928  *
929  * The (slow-path) user-space triggers utilization clamp value updates which
930  * can require updates on (fast-path) scheduler's data structures used to
931  * support enqueue/dequeue operations.
932  * While the per-CPU rq lock protects fast-path update operations, user-space
933  * requests are serialized using a mutex to reduce the risk of conflicting
934  * updates or API abuses.
935  */
936 static DEFINE_MUTEX(uclamp_mutex);
937 
938 /* Max allowed minimum utilization */
939 unsigned int sysctl_sched_uclamp_util_min = SCHED_CAPACITY_SCALE;
940 
941 /* Max allowed maximum utilization */
942 unsigned int sysctl_sched_uclamp_util_max = SCHED_CAPACITY_SCALE;
943 
944 /*
945  * By default RT tasks run at the maximum performance point/capacity of the
946  * system. Uclamp enforces this by always setting UCLAMP_MIN of RT tasks to
947  * SCHED_CAPACITY_SCALE.
948  *
949  * This knob allows admins to change the default behavior when uclamp is being
950  * used. In battery powered devices, particularly, running at the maximum
951  * capacity and frequency will increase energy consumption and shorten the
952  * battery life.
953  *
954  * This knob only affects RT tasks that their uclamp_se->user_defined == false.
955  *
956  * This knob will not override the system default sched_util_clamp_min defined
957  * above.
958  */
959 unsigned int sysctl_sched_uclamp_util_min_rt_default = SCHED_CAPACITY_SCALE;
960 
961 /* All clamps are required to be less or equal than these values */
962 static struct uclamp_se uclamp_default[UCLAMP_CNT];
963 
964 /*
965  * This static key is used to reduce the uclamp overhead in the fast path. It
966  * primarily disables the call to uclamp_rq_{inc, dec}() in
967  * enqueue/dequeue_task().
968  *
969  * This allows users to continue to enable uclamp in their kernel config with
970  * minimum uclamp overhead in the fast path.
971  *
972  * As soon as userspace modifies any of the uclamp knobs, the static key is
973  * enabled, since we have an actual users that make use of uclamp
974  * functionality.
975  *
976  * The knobs that would enable this static key are:
977  *
978  *   * A task modifying its uclamp value with sched_setattr().
979  *   * An admin modifying the sysctl_sched_uclamp_{min, max} via procfs.
980  *   * An admin modifying the cgroup cpu.uclamp.{min, max}
981  */
982 DEFINE_STATIC_KEY_FALSE(sched_uclamp_used);
983 
984 /* Integer rounded range for each bucket */
985 #define UCLAMP_BUCKET_DELTA DIV_ROUND_CLOSEST(SCHED_CAPACITY_SCALE, UCLAMP_BUCKETS)
986 
987 #define for_each_clamp_id(clamp_id) \
988 	for ((clamp_id) = 0; (clamp_id) < UCLAMP_CNT; (clamp_id)++)
989 
uclamp_bucket_id(unsigned int clamp_value)990 static inline unsigned int uclamp_bucket_id(unsigned int clamp_value)
991 {
992 	return min_t(unsigned int, clamp_value / UCLAMP_BUCKET_DELTA, UCLAMP_BUCKETS - 1);
993 }
994 
uclamp_none(enum uclamp_id clamp_id)995 static inline unsigned int uclamp_none(enum uclamp_id clamp_id)
996 {
997 	if (clamp_id == UCLAMP_MIN)
998 		return 0;
999 	return SCHED_CAPACITY_SCALE;
1000 }
1001 
uclamp_se_set(struct uclamp_se * uc_se,unsigned int value,bool user_defined)1002 static inline void uclamp_se_set(struct uclamp_se *uc_se,
1003 				 unsigned int value, bool user_defined)
1004 {
1005 	uc_se->value = value;
1006 	uc_se->bucket_id = uclamp_bucket_id(value);
1007 	uc_se->user_defined = user_defined;
1008 }
1009 
1010 static inline unsigned int
uclamp_idle_value(struct rq * rq,enum uclamp_id clamp_id,unsigned int clamp_value)1011 uclamp_idle_value(struct rq *rq, enum uclamp_id clamp_id,
1012 		  unsigned int clamp_value)
1013 {
1014 	/*
1015 	 * Avoid blocked utilization pushing up the frequency when we go
1016 	 * idle (which drops the max-clamp) by retaining the last known
1017 	 * max-clamp.
1018 	 */
1019 	if (clamp_id == UCLAMP_MAX) {
1020 		rq->uclamp_flags |= UCLAMP_FLAG_IDLE;
1021 		return clamp_value;
1022 	}
1023 
1024 	return uclamp_none(UCLAMP_MIN);
1025 }
1026 
uclamp_idle_reset(struct rq * rq,enum uclamp_id clamp_id,unsigned int clamp_value)1027 static inline void uclamp_idle_reset(struct rq *rq, enum uclamp_id clamp_id,
1028 				     unsigned int clamp_value)
1029 {
1030 	/* Reset max-clamp retention only on idle exit */
1031 	if (!(rq->uclamp_flags & UCLAMP_FLAG_IDLE))
1032 		return;
1033 
1034 	uclamp_rq_set(rq, clamp_id, clamp_value);
1035 }
1036 
1037 static inline
uclamp_rq_max_value(struct rq * rq,enum uclamp_id clamp_id,unsigned int clamp_value)1038 unsigned int uclamp_rq_max_value(struct rq *rq, enum uclamp_id clamp_id,
1039 				   unsigned int clamp_value)
1040 {
1041 	struct uclamp_bucket *bucket = rq->uclamp[clamp_id].bucket;
1042 	int bucket_id = UCLAMP_BUCKETS - 1;
1043 
1044 	/*
1045 	 * Since both min and max clamps are max aggregated, find the
1046 	 * top most bucket with tasks in.
1047 	 */
1048 	for ( ; bucket_id >= 0; bucket_id--) {
1049 		if (!bucket[bucket_id].tasks)
1050 			continue;
1051 		return bucket[bucket_id].value;
1052 	}
1053 
1054 	/* No tasks -- default clamp values */
1055 	return uclamp_idle_value(rq, clamp_id, clamp_value);
1056 }
1057 
__uclamp_update_util_min_rt_default(struct task_struct * p)1058 static void __uclamp_update_util_min_rt_default(struct task_struct *p)
1059 {
1060 	unsigned int default_util_min;
1061 	struct uclamp_se *uc_se;
1062 
1063 	lockdep_assert_held(&p->pi_lock);
1064 
1065 	uc_se = &p->uclamp_req[UCLAMP_MIN];
1066 
1067 	/* Only sync if user didn't override the default */
1068 	if (uc_se->user_defined)
1069 		return;
1070 
1071 	default_util_min = sysctl_sched_uclamp_util_min_rt_default;
1072 	uclamp_se_set(uc_se, default_util_min, false);
1073 }
1074 
uclamp_update_util_min_rt_default(struct task_struct * p)1075 static void uclamp_update_util_min_rt_default(struct task_struct *p)
1076 {
1077 	struct rq_flags rf;
1078 	struct rq *rq;
1079 
1080 	if (!rt_task(p))
1081 		return;
1082 
1083 	/* Protect updates to p->uclamp_* */
1084 	rq = task_rq_lock(p, &rf);
1085 	__uclamp_update_util_min_rt_default(p);
1086 	task_rq_unlock(rq, p, &rf);
1087 }
1088 
uclamp_sync_util_min_rt_default(void)1089 static void uclamp_sync_util_min_rt_default(void)
1090 {
1091 	struct task_struct *g, *p;
1092 
1093 	/*
1094 	 * copy_process()			sysctl_uclamp
1095 	 *					  uclamp_min_rt = X;
1096 	 *   write_lock(&tasklist_lock)		  read_lock(&tasklist_lock)
1097 	 *   // link thread			  smp_mb__after_spinlock()
1098 	 *   write_unlock(&tasklist_lock)	  read_unlock(&tasklist_lock);
1099 	 *   sched_post_fork()			  for_each_process_thread()
1100 	 *     __uclamp_sync_rt()		    __uclamp_sync_rt()
1101 	 *
1102 	 * Ensures that either sched_post_fork() will observe the new
1103 	 * uclamp_min_rt or for_each_process_thread() will observe the new
1104 	 * task.
1105 	 */
1106 	read_lock(&tasklist_lock);
1107 	smp_mb__after_spinlock();
1108 	read_unlock(&tasklist_lock);
1109 
1110 	rcu_read_lock();
1111 	for_each_process_thread(g, p)
1112 		uclamp_update_util_min_rt_default(p);
1113 	rcu_read_unlock();
1114 }
1115 
1116 static inline struct uclamp_se
uclamp_tg_restrict(struct task_struct * p,enum uclamp_id clamp_id)1117 uclamp_tg_restrict(struct task_struct *p, enum uclamp_id clamp_id)
1118 {
1119 	/* Copy by value as we could modify it */
1120 	struct uclamp_se uc_req = p->uclamp_req[clamp_id];
1121 #ifdef CONFIG_UCLAMP_TASK_GROUP
1122 	unsigned int tg_min, tg_max, value;
1123 
1124 	/*
1125 	 * Tasks in autogroups or root task group will be
1126 	 * restricted by system defaults.
1127 	 */
1128 	if (task_group_is_autogroup(task_group(p)))
1129 		return uc_req;
1130 	if (task_group(p) == &root_task_group)
1131 		return uc_req;
1132 
1133 	tg_min = task_group(p)->uclamp[UCLAMP_MIN].value;
1134 	tg_max = task_group(p)->uclamp[UCLAMP_MAX].value;
1135 	value = uc_req.value;
1136 	value = clamp(value, tg_min, tg_max);
1137 	uclamp_se_set(&uc_req, value, false);
1138 #endif
1139 
1140 	return uc_req;
1141 }
1142 
1143 /*
1144  * The effective clamp bucket index of a task depends on, by increasing
1145  * priority:
1146  * - the task specific clamp value, when explicitly requested from userspace
1147  * - the task group effective clamp value, for tasks not either in the root
1148  *   group or in an autogroup
1149  * - the system default clamp value, defined by the sysadmin
1150  */
1151 static inline struct uclamp_se
uclamp_eff_get(struct task_struct * p,enum uclamp_id clamp_id)1152 uclamp_eff_get(struct task_struct *p, enum uclamp_id clamp_id)
1153 {
1154 	struct uclamp_se uc_req = uclamp_tg_restrict(p, clamp_id);
1155 	struct uclamp_se uc_max = uclamp_default[clamp_id];
1156 
1157 	/* System default restrictions always apply */
1158 	if (unlikely(uc_req.value > uc_max.value))
1159 		return uc_max;
1160 
1161 	return uc_req;
1162 }
1163 
uclamp_eff_value(struct task_struct * p,enum uclamp_id clamp_id)1164 unsigned long uclamp_eff_value(struct task_struct *p, enum uclamp_id clamp_id)
1165 {
1166 	struct uclamp_se uc_eff;
1167 
1168 	/* Task currently refcounted: use back-annotated (effective) value */
1169 	if (p->uclamp[clamp_id].active)
1170 		return (unsigned long)p->uclamp[clamp_id].value;
1171 
1172 	uc_eff = uclamp_eff_get(p, clamp_id);
1173 
1174 	return (unsigned long)uc_eff.value;
1175 }
1176 
1177 /*
1178  * When a task is enqueued on a rq, the clamp bucket currently defined by the
1179  * task's uclamp::bucket_id is refcounted on that rq. This also immediately
1180  * updates the rq's clamp value if required.
1181  *
1182  * Tasks can have a task-specific value requested from user-space, track
1183  * within each bucket the maximum value for tasks refcounted in it.
1184  * This "local max aggregation" allows to track the exact "requested" value
1185  * for each bucket when all its RUNNABLE tasks require the same clamp.
1186  */
uclamp_rq_inc_id(struct rq * rq,struct task_struct * p,enum uclamp_id clamp_id)1187 static inline void uclamp_rq_inc_id(struct rq *rq, struct task_struct *p,
1188 				    enum uclamp_id clamp_id)
1189 {
1190 	struct uclamp_rq *uc_rq = &rq->uclamp[clamp_id];
1191 	struct uclamp_se *uc_se = &p->uclamp[clamp_id];
1192 	struct uclamp_bucket *bucket;
1193 
1194 	lockdep_assert_held(&rq->lock);
1195 
1196 	/* Update task effective clamp */
1197 	p->uclamp[clamp_id] = uclamp_eff_get(p, clamp_id);
1198 
1199 	bucket = &uc_rq->bucket[uc_se->bucket_id];
1200 	bucket->tasks++;
1201 	uc_se->active = true;
1202 
1203 	uclamp_idle_reset(rq, clamp_id, uc_se->value);
1204 
1205 	/*
1206 	 * Local max aggregation: rq buckets always track the max
1207 	 * "requested" clamp value of its RUNNABLE tasks.
1208 	 */
1209 	if (bucket->tasks == 1 || uc_se->value > bucket->value)
1210 		bucket->value = uc_se->value;
1211 
1212 	if (uc_se->value > uclamp_rq_get(rq, clamp_id))
1213 		uclamp_rq_set(rq, clamp_id, uc_se->value);
1214 }
1215 
1216 /*
1217  * When a task is dequeued from a rq, the clamp bucket refcounted by the task
1218  * is released. If this is the last task reference counting the rq's max
1219  * active clamp value, then the rq's clamp value is updated.
1220  *
1221  * Both refcounted tasks and rq's cached clamp values are expected to be
1222  * always valid. If it's detected they are not, as defensive programming,
1223  * enforce the expected state and warn.
1224  */
uclamp_rq_dec_id(struct rq * rq,struct task_struct * p,enum uclamp_id clamp_id)1225 static inline void uclamp_rq_dec_id(struct rq *rq, struct task_struct *p,
1226 				    enum uclamp_id clamp_id)
1227 {
1228 	struct uclamp_rq *uc_rq = &rq->uclamp[clamp_id];
1229 	struct uclamp_se *uc_se = &p->uclamp[clamp_id];
1230 	struct uclamp_bucket *bucket;
1231 	unsigned int bkt_clamp;
1232 	unsigned int rq_clamp;
1233 
1234 	lockdep_assert_held(&rq->lock);
1235 
1236 	/*
1237 	 * If sched_uclamp_used was enabled after task @p was enqueued,
1238 	 * we could end up with unbalanced call to uclamp_rq_dec_id().
1239 	 *
1240 	 * In this case the uc_se->active flag should be false since no uclamp
1241 	 * accounting was performed at enqueue time and we can just return
1242 	 * here.
1243 	 *
1244 	 * Need to be careful of the following enqeueue/dequeue ordering
1245 	 * problem too
1246 	 *
1247 	 *	enqueue(taskA)
1248 	 *	// sched_uclamp_used gets enabled
1249 	 *	enqueue(taskB)
1250 	 *	dequeue(taskA)
1251 	 *	// Must not decrement bukcet->tasks here
1252 	 *	dequeue(taskB)
1253 	 *
1254 	 * where we could end up with stale data in uc_se and
1255 	 * bucket[uc_se->bucket_id].
1256 	 *
1257 	 * The following check here eliminates the possibility of such race.
1258 	 */
1259 	if (unlikely(!uc_se->active))
1260 		return;
1261 
1262 	bucket = &uc_rq->bucket[uc_se->bucket_id];
1263 
1264 	SCHED_WARN_ON(!bucket->tasks);
1265 	if (likely(bucket->tasks))
1266 		bucket->tasks--;
1267 
1268 	uc_se->active = false;
1269 
1270 	/*
1271 	 * Keep "local max aggregation" simple and accept to (possibly)
1272 	 * overboost some RUNNABLE tasks in the same bucket.
1273 	 * The rq clamp bucket value is reset to its base value whenever
1274 	 * there are no more RUNNABLE tasks refcounting it.
1275 	 */
1276 	if (likely(bucket->tasks))
1277 		return;
1278 
1279 	rq_clamp = uclamp_rq_get(rq, clamp_id);
1280 	/*
1281 	 * Defensive programming: this should never happen. If it happens,
1282 	 * e.g. due to future modification, warn and fixup the expected value.
1283 	 */
1284 	SCHED_WARN_ON(bucket->value > rq_clamp);
1285 	if (bucket->value >= rq_clamp) {
1286 		bkt_clamp = uclamp_rq_max_value(rq, clamp_id, uc_se->value);
1287 		uclamp_rq_set(rq, clamp_id, bkt_clamp);
1288 	}
1289 }
1290 
uclamp_rq_inc(struct rq * rq,struct task_struct * p)1291 static inline void uclamp_rq_inc(struct rq *rq, struct task_struct *p)
1292 {
1293 	enum uclamp_id clamp_id;
1294 
1295 	/*
1296 	 * Avoid any overhead until uclamp is actually used by the userspace.
1297 	 *
1298 	 * The condition is constructed such that a NOP is generated when
1299 	 * sched_uclamp_used is disabled.
1300 	 */
1301 	if (!static_branch_unlikely(&sched_uclamp_used))
1302 		return;
1303 
1304 	if (unlikely(!p->sched_class->uclamp_enabled))
1305 		return;
1306 
1307 	for_each_clamp_id(clamp_id)
1308 		uclamp_rq_inc_id(rq, p, clamp_id);
1309 
1310 	/* Reset clamp idle holding when there is one RUNNABLE task */
1311 	if (rq->uclamp_flags & UCLAMP_FLAG_IDLE)
1312 		rq->uclamp_flags &= ~UCLAMP_FLAG_IDLE;
1313 }
1314 
uclamp_rq_dec(struct rq * rq,struct task_struct * p)1315 static inline void uclamp_rq_dec(struct rq *rq, struct task_struct *p)
1316 {
1317 	enum uclamp_id clamp_id;
1318 
1319 	/*
1320 	 * Avoid any overhead until uclamp is actually used by the userspace.
1321 	 *
1322 	 * The condition is constructed such that a NOP is generated when
1323 	 * sched_uclamp_used is disabled.
1324 	 */
1325 	if (!static_branch_unlikely(&sched_uclamp_used))
1326 		return;
1327 
1328 	if (unlikely(!p->sched_class->uclamp_enabled))
1329 		return;
1330 
1331 	for_each_clamp_id(clamp_id)
1332 		uclamp_rq_dec_id(rq, p, clamp_id);
1333 }
1334 
uclamp_rq_reinc_id(struct rq * rq,struct task_struct * p,enum uclamp_id clamp_id)1335 static inline void uclamp_rq_reinc_id(struct rq *rq, struct task_struct *p,
1336 				      enum uclamp_id clamp_id)
1337 {
1338 	if (!p->uclamp[clamp_id].active)
1339 		return;
1340 
1341 	uclamp_rq_dec_id(rq, p, clamp_id);
1342 	uclamp_rq_inc_id(rq, p, clamp_id);
1343 
1344 	/*
1345 	 * Make sure to clear the idle flag if we've transiently reached 0
1346 	 * active tasks on rq.
1347 	 */
1348 	if (clamp_id == UCLAMP_MAX && (rq->uclamp_flags & UCLAMP_FLAG_IDLE))
1349 		rq->uclamp_flags &= ~UCLAMP_FLAG_IDLE;
1350 }
1351 
1352 static inline void
uclamp_update_active(struct task_struct * p)1353 uclamp_update_active(struct task_struct *p)
1354 {
1355 	enum uclamp_id clamp_id;
1356 	struct rq_flags rf;
1357 	struct rq *rq;
1358 
1359 	/*
1360 	 * Lock the task and the rq where the task is (or was) queued.
1361 	 *
1362 	 * We might lock the (previous) rq of a !RUNNABLE task, but that's the
1363 	 * price to pay to safely serialize util_{min,max} updates with
1364 	 * enqueues, dequeues and migration operations.
1365 	 * This is the same locking schema used by __set_cpus_allowed_ptr().
1366 	 */
1367 	rq = task_rq_lock(p, &rf);
1368 
1369 	/*
1370 	 * Setting the clamp bucket is serialized by task_rq_lock().
1371 	 * If the task is not yet RUNNABLE and its task_struct is not
1372 	 * affecting a valid clamp bucket, the next time it's enqueued,
1373 	 * it will already see the updated clamp bucket value.
1374 	 */
1375 	for_each_clamp_id(clamp_id)
1376 		uclamp_rq_reinc_id(rq, p, clamp_id);
1377 
1378 	task_rq_unlock(rq, p, &rf);
1379 }
1380 
1381 #ifdef CONFIG_UCLAMP_TASK_GROUP
1382 static inline void
uclamp_update_active_tasks(struct cgroup_subsys_state * css)1383 uclamp_update_active_tasks(struct cgroup_subsys_state *css)
1384 {
1385 	struct css_task_iter it;
1386 	struct task_struct *p;
1387 
1388 	css_task_iter_start(css, 0, &it);
1389 	while ((p = css_task_iter_next(&it)))
1390 		uclamp_update_active(p);
1391 	css_task_iter_end(&it);
1392 }
1393 
1394 static void cpu_util_update_eff(struct cgroup_subsys_state *css);
uclamp_update_root_tg(void)1395 static void uclamp_update_root_tg(void)
1396 {
1397 	struct task_group *tg = &root_task_group;
1398 
1399 	uclamp_se_set(&tg->uclamp_req[UCLAMP_MIN],
1400 		      sysctl_sched_uclamp_util_min, false);
1401 	uclamp_se_set(&tg->uclamp_req[UCLAMP_MAX],
1402 		      sysctl_sched_uclamp_util_max, false);
1403 
1404 	rcu_read_lock();
1405 	cpu_util_update_eff(&root_task_group.css);
1406 	rcu_read_unlock();
1407 }
1408 #else
uclamp_update_root_tg(void)1409 static void uclamp_update_root_tg(void) { }
1410 #endif
1411 
sysctl_sched_uclamp_handler(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)1412 int sysctl_sched_uclamp_handler(struct ctl_table *table, int write,
1413 				void *buffer, size_t *lenp, loff_t *ppos)
1414 {
1415 	bool update_root_tg = false;
1416 	int old_min, old_max, old_min_rt;
1417 	int result;
1418 
1419 	mutex_lock(&uclamp_mutex);
1420 	old_min = sysctl_sched_uclamp_util_min;
1421 	old_max = sysctl_sched_uclamp_util_max;
1422 	old_min_rt = sysctl_sched_uclamp_util_min_rt_default;
1423 
1424 	result = proc_dointvec(table, write, buffer, lenp, ppos);
1425 	if (result)
1426 		goto undo;
1427 	if (!write)
1428 		goto done;
1429 
1430 	if (sysctl_sched_uclamp_util_min > sysctl_sched_uclamp_util_max ||
1431 	    sysctl_sched_uclamp_util_max > SCHED_CAPACITY_SCALE	||
1432 	    sysctl_sched_uclamp_util_min_rt_default > SCHED_CAPACITY_SCALE) {
1433 
1434 		result = -EINVAL;
1435 		goto undo;
1436 	}
1437 
1438 	if (old_min != sysctl_sched_uclamp_util_min) {
1439 		uclamp_se_set(&uclamp_default[UCLAMP_MIN],
1440 			      sysctl_sched_uclamp_util_min, false);
1441 		update_root_tg = true;
1442 	}
1443 	if (old_max != sysctl_sched_uclamp_util_max) {
1444 		uclamp_se_set(&uclamp_default[UCLAMP_MAX],
1445 			      sysctl_sched_uclamp_util_max, false);
1446 		update_root_tg = true;
1447 	}
1448 
1449 	if (update_root_tg) {
1450 		static_branch_enable(&sched_uclamp_used);
1451 		uclamp_update_root_tg();
1452 	}
1453 
1454 	if (old_min_rt != sysctl_sched_uclamp_util_min_rt_default) {
1455 		static_branch_enable(&sched_uclamp_used);
1456 		uclamp_sync_util_min_rt_default();
1457 	}
1458 
1459 	/*
1460 	 * We update all RUNNABLE tasks only when task groups are in use.
1461 	 * Otherwise, keep it simple and do just a lazy update at each next
1462 	 * task enqueue time.
1463 	 */
1464 
1465 	goto done;
1466 
1467 undo:
1468 	sysctl_sched_uclamp_util_min = old_min;
1469 	sysctl_sched_uclamp_util_max = old_max;
1470 	sysctl_sched_uclamp_util_min_rt_default = old_min_rt;
1471 done:
1472 	mutex_unlock(&uclamp_mutex);
1473 
1474 	return result;
1475 }
1476 
uclamp_validate(struct task_struct * p,const struct sched_attr * attr)1477 static int uclamp_validate(struct task_struct *p,
1478 			   const struct sched_attr *attr)
1479 {
1480 	unsigned int lower_bound = p->uclamp_req[UCLAMP_MIN].value;
1481 	unsigned int upper_bound = p->uclamp_req[UCLAMP_MAX].value;
1482 
1483 	if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN)
1484 		lower_bound = attr->sched_util_min;
1485 	if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX)
1486 		upper_bound = attr->sched_util_max;
1487 
1488 	if (lower_bound > upper_bound)
1489 		return -EINVAL;
1490 	if (upper_bound > SCHED_CAPACITY_SCALE)
1491 		return -EINVAL;
1492 
1493 	/*
1494 	 * We have valid uclamp attributes; make sure uclamp is enabled.
1495 	 *
1496 	 * We need to do that here, because enabling static branches is a
1497 	 * blocking operation which obviously cannot be done while holding
1498 	 * scheduler locks.
1499 	 */
1500 	static_branch_enable(&sched_uclamp_used);
1501 
1502 	return 0;
1503 }
1504 
__setscheduler_uclamp(struct task_struct * p,const struct sched_attr * attr)1505 static void __setscheduler_uclamp(struct task_struct *p,
1506 				  const struct sched_attr *attr)
1507 {
1508 	enum uclamp_id clamp_id;
1509 
1510 	/*
1511 	 * On scheduling class change, reset to default clamps for tasks
1512 	 * without a task-specific value.
1513 	 */
1514 	for_each_clamp_id(clamp_id) {
1515 		struct uclamp_se *uc_se = &p->uclamp_req[clamp_id];
1516 
1517 		/* Keep using defined clamps across class changes */
1518 		if (uc_se->user_defined)
1519 			continue;
1520 
1521 		/*
1522 		 * RT by default have a 100% boost value that could be modified
1523 		 * at runtime.
1524 		 */
1525 		if (unlikely(rt_task(p) && clamp_id == UCLAMP_MIN))
1526 			__uclamp_update_util_min_rt_default(p);
1527 		else
1528 			uclamp_se_set(uc_se, uclamp_none(clamp_id), false);
1529 
1530 	}
1531 
1532 	if (likely(!(attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)))
1533 		return;
1534 
1535 	if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MIN) {
1536 		uclamp_se_set(&p->uclamp_req[UCLAMP_MIN],
1537 			      attr->sched_util_min, true);
1538 	}
1539 
1540 	if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP_MAX) {
1541 		uclamp_se_set(&p->uclamp_req[UCLAMP_MAX],
1542 			      attr->sched_util_max, true);
1543 	}
1544 }
1545 
uclamp_fork(struct task_struct * p)1546 static void uclamp_fork(struct task_struct *p)
1547 {
1548 	enum uclamp_id clamp_id;
1549 
1550 	/*
1551 	 * We don't need to hold task_rq_lock() when updating p->uclamp_* here
1552 	 * as the task is still at its early fork stages.
1553 	 */
1554 	for_each_clamp_id(clamp_id)
1555 		p->uclamp[clamp_id].active = false;
1556 
1557 	if (likely(!p->sched_reset_on_fork))
1558 		return;
1559 
1560 	for_each_clamp_id(clamp_id) {
1561 		uclamp_se_set(&p->uclamp_req[clamp_id],
1562 			      uclamp_none(clamp_id), false);
1563 	}
1564 }
1565 
uclamp_post_fork(struct task_struct * p)1566 static void uclamp_post_fork(struct task_struct *p)
1567 {
1568 	uclamp_update_util_min_rt_default(p);
1569 }
1570 
init_uclamp_rq(struct rq * rq)1571 static void __init init_uclamp_rq(struct rq *rq)
1572 {
1573 	enum uclamp_id clamp_id;
1574 	struct uclamp_rq *uc_rq = rq->uclamp;
1575 
1576 	for_each_clamp_id(clamp_id) {
1577 		uc_rq[clamp_id] = (struct uclamp_rq) {
1578 			.value = uclamp_none(clamp_id)
1579 		};
1580 	}
1581 
1582 	rq->uclamp_flags = UCLAMP_FLAG_IDLE;
1583 }
1584 
init_uclamp(void)1585 static void __init init_uclamp(void)
1586 {
1587 	struct uclamp_se uc_max = {};
1588 	enum uclamp_id clamp_id;
1589 	int cpu;
1590 
1591 	for_each_possible_cpu(cpu)
1592 		init_uclamp_rq(cpu_rq(cpu));
1593 
1594 	for_each_clamp_id(clamp_id) {
1595 		uclamp_se_set(&init_task.uclamp_req[clamp_id],
1596 			      uclamp_none(clamp_id), false);
1597 	}
1598 
1599 	/* System defaults allow max clamp values for both indexes */
1600 	uclamp_se_set(&uc_max, uclamp_none(UCLAMP_MAX), false);
1601 	for_each_clamp_id(clamp_id) {
1602 		uclamp_default[clamp_id] = uc_max;
1603 #ifdef CONFIG_UCLAMP_TASK_GROUP
1604 		root_task_group.uclamp_req[clamp_id] = uc_max;
1605 		root_task_group.uclamp[clamp_id] = uc_max;
1606 #endif
1607 	}
1608 }
1609 
1610 #else /* CONFIG_UCLAMP_TASK */
uclamp_rq_inc(struct rq * rq,struct task_struct * p)1611 static inline void uclamp_rq_inc(struct rq *rq, struct task_struct *p) { }
uclamp_rq_dec(struct rq * rq,struct task_struct * p)1612 static inline void uclamp_rq_dec(struct rq *rq, struct task_struct *p) { }
uclamp_validate(struct task_struct * p,const struct sched_attr * attr)1613 static inline int uclamp_validate(struct task_struct *p,
1614 				  const struct sched_attr *attr)
1615 {
1616 	return -EOPNOTSUPP;
1617 }
__setscheduler_uclamp(struct task_struct * p,const struct sched_attr * attr)1618 static void __setscheduler_uclamp(struct task_struct *p,
1619 				  const struct sched_attr *attr) { }
uclamp_fork(struct task_struct * p)1620 static inline void uclamp_fork(struct task_struct *p) { }
uclamp_post_fork(struct task_struct * p)1621 static inline void uclamp_post_fork(struct task_struct *p) { }
init_uclamp(void)1622 static inline void init_uclamp(void) { }
1623 #endif /* CONFIG_UCLAMP_TASK */
1624 
enqueue_task(struct rq * rq,struct task_struct * p,int flags)1625 static inline void enqueue_task(struct rq *rq, struct task_struct *p, int flags)
1626 {
1627 	if (!(flags & ENQUEUE_NOCLOCK))
1628 		update_rq_clock(rq);
1629 
1630 	if (!(flags & ENQUEUE_RESTORE)) {
1631 		sched_info_queued(rq, p);
1632 		psi_enqueue(p, flags & ENQUEUE_WAKEUP);
1633 	}
1634 
1635 	uclamp_rq_inc(rq, p);
1636 	p->sched_class->enqueue_task(rq, p, flags);
1637 }
1638 
dequeue_task(struct rq * rq,struct task_struct * p,int flags)1639 static inline void dequeue_task(struct rq *rq, struct task_struct *p, int flags)
1640 {
1641 	if (!(flags & DEQUEUE_NOCLOCK))
1642 		update_rq_clock(rq);
1643 
1644 	if (!(flags & DEQUEUE_SAVE)) {
1645 		sched_info_dequeued(rq, p);
1646 		psi_dequeue(p, flags & DEQUEUE_SLEEP);
1647 	}
1648 
1649 	uclamp_rq_dec(rq, p);
1650 	p->sched_class->dequeue_task(rq, p, flags);
1651 }
1652 
activate_task(struct rq * rq,struct task_struct * p,int flags)1653 void activate_task(struct rq *rq, struct task_struct *p, int flags)
1654 {
1655 	if (task_on_rq_migrating(p))
1656 		flags |= ENQUEUE_MIGRATED;
1657 
1658 	enqueue_task(rq, p, flags);
1659 
1660 	p->on_rq = TASK_ON_RQ_QUEUED;
1661 }
1662 
deactivate_task(struct rq * rq,struct task_struct * p,int flags)1663 void deactivate_task(struct rq *rq, struct task_struct *p, int flags)
1664 {
1665 	p->on_rq = (flags & DEQUEUE_SLEEP) ? 0 : TASK_ON_RQ_MIGRATING;
1666 
1667 	dequeue_task(rq, p, flags);
1668 }
1669 
__normal_prio(int policy,int rt_prio,int nice)1670 static inline int __normal_prio(int policy, int rt_prio, int nice)
1671 {
1672 	int prio;
1673 
1674 	if (dl_policy(policy))
1675 		prio = MAX_DL_PRIO - 1;
1676 	else if (rt_policy(policy))
1677 		prio = MAX_RT_PRIO - 1 - rt_prio;
1678 	else
1679 		prio = NICE_TO_PRIO(nice);
1680 
1681 	return prio;
1682 }
1683 
1684 /*
1685  * Calculate the expected normal priority: i.e. priority
1686  * without taking RT-inheritance into account. Might be
1687  * boosted by interactivity modifiers. Changes upon fork,
1688  * setprio syscalls, and whenever the interactivity
1689  * estimator recalculates.
1690  */
normal_prio(struct task_struct * p)1691 static inline int normal_prio(struct task_struct *p)
1692 {
1693 	return __normal_prio(p->policy, p->rt_priority, PRIO_TO_NICE(p->static_prio));
1694 }
1695 
1696 /*
1697  * Calculate the current priority, i.e. the priority
1698  * taken into account by the scheduler. This value might
1699  * be boosted by RT tasks, or might be boosted by
1700  * interactivity modifiers. Will be RT if the task got
1701  * RT-boosted. If not then it returns p->normal_prio.
1702  */
effective_prio(struct task_struct * p)1703 static int effective_prio(struct task_struct *p)
1704 {
1705 	p->normal_prio = normal_prio(p);
1706 	/*
1707 	 * If we are RT tasks or we were boosted to RT priority,
1708 	 * keep the priority unchanged. Otherwise, update priority
1709 	 * to the normal priority:
1710 	 */
1711 	if (!rt_prio(p->prio))
1712 		return p->normal_prio;
1713 	return p->prio;
1714 }
1715 
1716 /**
1717  * task_curr - is this task currently executing on a CPU?
1718  * @p: the task in question.
1719  *
1720  * Return: 1 if the task is currently executing. 0 otherwise.
1721  */
task_curr(const struct task_struct * p)1722 inline int task_curr(const struct task_struct *p)
1723 {
1724 	return cpu_curr(task_cpu(p)) == p;
1725 }
1726 
1727 /*
1728  * switched_from, switched_to and prio_changed must _NOT_ drop rq->lock,
1729  * use the balance_callback list if you want balancing.
1730  *
1731  * this means any call to check_class_changed() must be followed by a call to
1732  * balance_callback().
1733  */
check_class_changed(struct rq * rq,struct task_struct * p,const struct sched_class * prev_class,int oldprio)1734 static inline void check_class_changed(struct rq *rq, struct task_struct *p,
1735 				       const struct sched_class *prev_class,
1736 				       int oldprio)
1737 {
1738 	if (prev_class != p->sched_class) {
1739 		if (prev_class->switched_from)
1740 			prev_class->switched_from(rq, p);
1741 
1742 		p->sched_class->switched_to(rq, p);
1743 	} else if (oldprio != p->prio || dl_task(p))
1744 		p->sched_class->prio_changed(rq, p, oldprio);
1745 }
1746 
check_preempt_curr(struct rq * rq,struct task_struct * p,int flags)1747 void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags)
1748 {
1749 	if (p->sched_class == rq->curr->sched_class)
1750 		rq->curr->sched_class->check_preempt_curr(rq, p, flags);
1751 	else if (p->sched_class > rq->curr->sched_class)
1752 		resched_curr(rq);
1753 
1754 	/*
1755 	 * A queue event has occurred, and we're going to schedule.  In
1756 	 * this case, we can save a useless back to back clock update.
1757 	 */
1758 	if (task_on_rq_queued(rq->curr) && test_tsk_need_resched(rq->curr))
1759 		rq_clock_skip_update(rq);
1760 }
1761 
1762 #ifdef CONFIG_SMP
1763 
1764 /*
1765  * Per-CPU kthreads are allowed to run on !active && online CPUs, see
1766  * __set_cpus_allowed_ptr() and select_fallback_rq().
1767  */
is_cpu_allowed(struct task_struct * p,int cpu)1768 static inline bool is_cpu_allowed(struct task_struct *p, int cpu)
1769 {
1770 	if (!cpumask_test_cpu(cpu, p->cpus_ptr))
1771 		return false;
1772 
1773 	if (is_per_cpu_kthread(p))
1774 		return cpu_online(cpu);
1775 
1776 	return cpu_active(cpu);
1777 }
1778 
1779 /*
1780  * This is how migration works:
1781  *
1782  * 1) we invoke migration_cpu_stop() on the target CPU using
1783  *    stop_one_cpu().
1784  * 2) stopper starts to run (implicitly forcing the migrated thread
1785  *    off the CPU)
1786  * 3) it checks whether the migrated task is still in the wrong runqueue.
1787  * 4) if it's in the wrong runqueue then the migration thread removes
1788  *    it and puts it into the right queue.
1789  * 5) stopper completes and stop_one_cpu() returns and the migration
1790  *    is done.
1791  */
1792 
1793 /*
1794  * move_queued_task - move a queued task to new rq.
1795  *
1796  * Returns (locked) new rq. Old rq's lock is released.
1797  */
move_queued_task(struct rq * rq,struct rq_flags * rf,struct task_struct * p,int new_cpu)1798 static struct rq *move_queued_task(struct rq *rq, struct rq_flags *rf,
1799 				   struct task_struct *p, int new_cpu)
1800 {
1801 	lockdep_assert_held(&rq->lock);
1802 
1803 	deactivate_task(rq, p, DEQUEUE_NOCLOCK);
1804 #ifdef CONFIG_SCHED_WALT
1805 	double_lock_balance(rq, cpu_rq(new_cpu));
1806 	if (!(rq->clock_update_flags & RQCF_UPDATED))
1807 		update_rq_clock(rq);
1808 #endif
1809 	set_task_cpu(p, new_cpu);
1810 #ifdef CONFIG_SCHED_WALT
1811 	double_rq_unlock(cpu_rq(new_cpu), rq);
1812 #else
1813 	rq_unlock(rq, rf);
1814 #endif
1815 
1816 	rq = cpu_rq(new_cpu);
1817 
1818 	rq_lock(rq, rf);
1819 	BUG_ON(task_cpu(p) != new_cpu);
1820 	activate_task(rq, p, 0);
1821 	check_preempt_curr(rq, p, 0);
1822 
1823 	return rq;
1824 }
1825 
1826 struct migration_arg {
1827 	struct task_struct *task;
1828 	int dest_cpu;
1829 };
1830 
1831 /*
1832  * Move (not current) task off this CPU, onto the destination CPU. We're doing
1833  * this because either it can't run here any more (set_cpus_allowed()
1834  * away from this CPU, or CPU going down), or because we're
1835  * attempting to rebalance this task on exec (sched_exec).
1836  *
1837  * So we race with normal scheduler movements, but that's OK, as long
1838  * as the task is no longer on this CPU.
1839  */
__migrate_task(struct rq * rq,struct rq_flags * rf,struct task_struct * p,int dest_cpu)1840 static struct rq *__migrate_task(struct rq *rq, struct rq_flags *rf,
1841 				 struct task_struct *p, int dest_cpu)
1842 {
1843 	/* Affinity changed (again). */
1844 	if (!is_cpu_allowed(p, dest_cpu))
1845 		return rq;
1846 
1847 	update_rq_clock(rq);
1848 	rq = move_queued_task(rq, rf, p, dest_cpu);
1849 
1850 	return rq;
1851 }
1852 
1853 /*
1854  * migration_cpu_stop - this will be executed by a highprio stopper thread
1855  * and performs thread migration by bumping thread off CPU then
1856  * 'pushing' onto another runqueue.
1857  */
migration_cpu_stop(void * data)1858 static int migration_cpu_stop(void *data)
1859 {
1860 	struct migration_arg *arg = data;
1861 	struct task_struct *p = arg->task;
1862 	struct rq *rq = this_rq();
1863 	struct rq_flags rf;
1864 
1865 	/*
1866 	 * The original target CPU might have gone down and we might
1867 	 * be on another CPU but it doesn't matter.
1868 	 */
1869 	local_irq_disable();
1870 	/*
1871 	 * We need to explicitly wake pending tasks before running
1872 	 * __migrate_task() such that we will not miss enforcing cpus_ptr
1873 	 * during wakeups, see set_cpus_allowed_ptr()'s TASK_WAKING test.
1874 	 */
1875 	flush_smp_call_function_from_idle();
1876 
1877 	raw_spin_lock(&p->pi_lock);
1878 	rq_lock(rq, &rf);
1879 	/*
1880 	 * If task_rq(p) != rq, it cannot be migrated here, because we're
1881 	 * holding rq->lock, if p->on_rq == 0 it cannot get enqueued because
1882 	 * we're holding p->pi_lock.
1883 	 */
1884 	if (task_rq(p) == rq) {
1885 		if (task_on_rq_queued(p))
1886 			rq = __migrate_task(rq, &rf, p, arg->dest_cpu);
1887 		else
1888 			p->wake_cpu = arg->dest_cpu;
1889 	}
1890 	rq_unlock(rq, &rf);
1891 	raw_spin_unlock(&p->pi_lock);
1892 
1893 	local_irq_enable();
1894 	return 0;
1895 }
1896 
1897 /*
1898  * sched_class::set_cpus_allowed must do the below, but is not required to
1899  * actually call this function.
1900  */
set_cpus_allowed_common(struct task_struct * p,const struct cpumask * new_mask)1901 void set_cpus_allowed_common(struct task_struct *p, const struct cpumask *new_mask)
1902 {
1903 	cpumask_copy(&p->cpus_mask, new_mask);
1904 	p->nr_cpus_allowed = cpumask_weight(new_mask);
1905 }
1906 
do_set_cpus_allowed(struct task_struct * p,const struct cpumask * new_mask)1907 void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask)
1908 {
1909 	struct rq *rq = task_rq(p);
1910 	bool queued, running;
1911 
1912 	lockdep_assert_held(&p->pi_lock);
1913 
1914 	queued = task_on_rq_queued(p);
1915 	running = task_current(rq, p);
1916 
1917 	if (queued) {
1918 		/*
1919 		 * Because __kthread_bind() calls this on blocked tasks without
1920 		 * holding rq->lock.
1921 		 */
1922 		lockdep_assert_held(&rq->lock);
1923 		dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
1924 	}
1925 	if (running)
1926 		put_prev_task(rq, p);
1927 
1928 	p->sched_class->set_cpus_allowed(p, new_mask);
1929 
1930 	if (queued)
1931 		enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
1932 	if (running)
1933 		set_next_task(rq, p);
1934 }
1935 
1936 /*
1937  * Change a given task's CPU affinity. Migrate the thread to a
1938  * proper CPU and schedule it away if the CPU it's executing on
1939  * is removed from the allowed bitmask.
1940  *
1941  * NOTE: the caller must have a valid reference to the task, the
1942  * task must not exit() & deallocate itself prematurely. The
1943  * call is not atomic; no spinlocks may be held.
1944  */
__set_cpus_allowed_ptr(struct task_struct * p,const struct cpumask * new_mask,bool check)1945 static int __set_cpus_allowed_ptr(struct task_struct *p,
1946 				  const struct cpumask *new_mask, bool check)
1947 {
1948 	const struct cpumask *cpu_valid_mask = cpu_active_mask;
1949 	unsigned int dest_cpu;
1950 	struct rq_flags rf;
1951 	struct rq *rq;
1952 	int ret = 0;
1953 #ifdef CONFIG_CPU_ISOLATION_OPT
1954 	cpumask_t allowed_mask;
1955 #endif
1956 
1957 	rq = task_rq_lock(p, &rf);
1958 	update_rq_clock(rq);
1959 
1960 	if (p->flags & PF_KTHREAD) {
1961 		/*
1962 		 * Kernel threads are allowed on online && !active CPUs
1963 		 */
1964 		cpu_valid_mask = cpu_online_mask;
1965 	}
1966 
1967 	/*
1968 	 * Must re-check here, to close a race against __kthread_bind(),
1969 	 * sched_setaffinity() is not guaranteed to observe the flag.
1970 	 */
1971 	if (check && (p->flags & PF_NO_SETAFFINITY)) {
1972 		ret = -EINVAL;
1973 		goto out;
1974 	}
1975 
1976 	if (cpumask_equal(&p->cpus_mask, new_mask))
1977 		goto out;
1978 
1979 #ifdef CONFIG_CPU_ISOLATION_OPT
1980 	cpumask_andnot(&allowed_mask, new_mask, cpu_isolated_mask);
1981 	cpumask_and(&allowed_mask, &allowed_mask, cpu_valid_mask);
1982 
1983 	dest_cpu = cpumask_any(&allowed_mask);
1984 	if (dest_cpu >= nr_cpu_ids) {
1985 		cpumask_and(&allowed_mask, cpu_valid_mask, new_mask);
1986 		dest_cpu = cpumask_any(&allowed_mask);
1987 		if (!cpumask_intersects(new_mask, cpu_valid_mask)) {
1988 			ret = -EINVAL;
1989 			goto out;
1990 		}
1991 	}
1992 #else
1993 	/*
1994 	 * Picking a ~random cpu helps in cases where we are changing affinity
1995 	 * for groups of tasks (ie. cpuset), so that load balancing is not
1996 	 * immediately required to distribute the tasks within their new mask.
1997 	 */
1998 	dest_cpu = cpumask_any_and_distribute(cpu_valid_mask, new_mask);
1999 	if (dest_cpu >= nr_cpu_ids) {
2000 		ret = -EINVAL;
2001 		goto out;
2002 	}
2003 #endif
2004 
2005 	do_set_cpus_allowed(p, new_mask);
2006 
2007 	if (p->flags & PF_KTHREAD) {
2008 		/*
2009 		 * For kernel threads that do indeed end up on online &&
2010 		 * !active we want to ensure they are strict per-CPU threads.
2011 		 */
2012 		WARN_ON(cpumask_intersects(new_mask, cpu_online_mask) &&
2013 			!cpumask_intersects(new_mask, cpu_active_mask) &&
2014 			p->nr_cpus_allowed != 1);
2015 	}
2016 
2017 	/* Can the task run on the task's current CPU? If so, we're done */
2018 #ifdef CONFIG_CPU_ISOLATION_OPT
2019 	if (cpumask_test_cpu(task_cpu(p), &allowed_mask))
2020 		goto out;
2021 #else
2022 	if (cpumask_test_cpu(task_cpu(p), new_mask))
2023 		goto out;
2024 #endif
2025 
2026 	if (task_running(rq, p) || p->state == TASK_WAKING) {
2027 		struct migration_arg arg = { p, dest_cpu };
2028 		/* Need help from migration thread: drop lock and wait. */
2029 		task_rq_unlock(rq, p, &rf);
2030 		stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg);
2031 		return 0;
2032 	} else if (task_on_rq_queued(p)) {
2033 		/*
2034 		 * OK, since we're going to drop the lock immediately
2035 		 * afterwards anyway.
2036 		 */
2037 		rq = move_queued_task(rq, &rf, p, dest_cpu);
2038 	}
2039 out:
2040 	task_rq_unlock(rq, p, &rf);
2041 
2042 	return ret;
2043 }
2044 
set_cpus_allowed_ptr(struct task_struct * p,const struct cpumask * new_mask)2045 int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask)
2046 {
2047 	return __set_cpus_allowed_ptr(p, new_mask, false);
2048 }
2049 EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr);
2050 
set_task_cpu(struct task_struct * p,unsigned int new_cpu)2051 void set_task_cpu(struct task_struct *p, unsigned int new_cpu)
2052 {
2053 #ifdef CONFIG_SCHED_DEBUG
2054 	/*
2055 	 * We should never call set_task_cpu() on a blocked task,
2056 	 * ttwu() will sort out the placement.
2057 	 */
2058 	WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING &&
2059 			!p->on_rq);
2060 
2061 	/*
2062 	 * Migrating fair class task must have p->on_rq = TASK_ON_RQ_MIGRATING,
2063 	 * because schedstat_wait_{start,end} rebase migrating task's wait_start
2064 	 * time relying on p->on_rq.
2065 	 */
2066 	WARN_ON_ONCE(p->state == TASK_RUNNING &&
2067 		     p->sched_class == &fair_sched_class &&
2068 		     (p->on_rq && !task_on_rq_migrating(p)));
2069 
2070 #ifdef CONFIG_LOCKDEP
2071 	/*
2072 	 * The caller should hold either p->pi_lock or rq->lock, when changing
2073 	 * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks.
2074 	 *
2075 	 * sched_move_task() holds both and thus holding either pins the cgroup,
2076 	 * see task_group().
2077 	 *
2078 	 * Furthermore, all task_rq users should acquire both locks, see
2079 	 * task_rq_lock().
2080 	 */
2081 	WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) ||
2082 				      lockdep_is_held(&task_rq(p)->lock)));
2083 #endif
2084 	/*
2085 	 * Clearly, migrating tasks to offline CPUs is a fairly daft thing.
2086 	 */
2087 	WARN_ON_ONCE(!cpu_online(new_cpu));
2088 #endif
2089 
2090 	trace_sched_migrate_task(p, new_cpu);
2091 
2092 	if (task_cpu(p) != new_cpu) {
2093 		if (p->sched_class->migrate_task_rq)
2094 			p->sched_class->migrate_task_rq(p, new_cpu);
2095 		p->se.nr_migrations++;
2096 		rseq_migrate(p);
2097 		perf_event_task_migrate(p);
2098 		fixup_busy_time(p, new_cpu);
2099 	}
2100 
2101 	__set_task_cpu(p, new_cpu);
2102 }
2103 
2104 #ifdef CONFIG_NUMA_BALANCING
__migrate_swap_task(struct task_struct * p,int cpu)2105 static void __migrate_swap_task(struct task_struct *p, int cpu)
2106 {
2107 	if (task_on_rq_queued(p)) {
2108 		struct rq *src_rq, *dst_rq;
2109 		struct rq_flags srf, drf;
2110 
2111 		src_rq = task_rq(p);
2112 		dst_rq = cpu_rq(cpu);
2113 
2114 		rq_pin_lock(src_rq, &srf);
2115 		rq_pin_lock(dst_rq, &drf);
2116 
2117 		deactivate_task(src_rq, p, 0);
2118 		set_task_cpu(p, cpu);
2119 		activate_task(dst_rq, p, 0);
2120 		check_preempt_curr(dst_rq, p, 0);
2121 
2122 		rq_unpin_lock(dst_rq, &drf);
2123 		rq_unpin_lock(src_rq, &srf);
2124 
2125 	} else {
2126 		/*
2127 		 * Task isn't running anymore; make it appear like we migrated
2128 		 * it before it went to sleep. This means on wakeup we make the
2129 		 * previous CPU our target instead of where it really is.
2130 		 */
2131 		p->wake_cpu = cpu;
2132 	}
2133 }
2134 
2135 struct migration_swap_arg {
2136 	struct task_struct *src_task, *dst_task;
2137 	int src_cpu, dst_cpu;
2138 };
2139 
migrate_swap_stop(void * data)2140 static int migrate_swap_stop(void *data)
2141 {
2142 	struct migration_swap_arg *arg = data;
2143 	struct rq *src_rq, *dst_rq;
2144 	int ret = -EAGAIN;
2145 
2146 	if (!cpu_active(arg->src_cpu) || !cpu_active(arg->dst_cpu))
2147 		return -EAGAIN;
2148 
2149 	src_rq = cpu_rq(arg->src_cpu);
2150 	dst_rq = cpu_rq(arg->dst_cpu);
2151 
2152 	double_raw_lock(&arg->src_task->pi_lock,
2153 			&arg->dst_task->pi_lock);
2154 	double_rq_lock(src_rq, dst_rq);
2155 
2156 	if (task_cpu(arg->dst_task) != arg->dst_cpu)
2157 		goto unlock;
2158 
2159 	if (task_cpu(arg->src_task) != arg->src_cpu)
2160 		goto unlock;
2161 
2162 	if (!cpumask_test_cpu(arg->dst_cpu, arg->src_task->cpus_ptr))
2163 		goto unlock;
2164 
2165 	if (!cpumask_test_cpu(arg->src_cpu, arg->dst_task->cpus_ptr))
2166 		goto unlock;
2167 
2168 	__migrate_swap_task(arg->src_task, arg->dst_cpu);
2169 	__migrate_swap_task(arg->dst_task, arg->src_cpu);
2170 
2171 	ret = 0;
2172 
2173 unlock:
2174 	double_rq_unlock(src_rq, dst_rq);
2175 	raw_spin_unlock(&arg->dst_task->pi_lock);
2176 	raw_spin_unlock(&arg->src_task->pi_lock);
2177 
2178 	return ret;
2179 }
2180 
2181 /*
2182  * Cross migrate two tasks
2183  */
migrate_swap(struct task_struct * cur,struct task_struct * p,int target_cpu,int curr_cpu)2184 int migrate_swap(struct task_struct *cur, struct task_struct *p,
2185 		int target_cpu, int curr_cpu)
2186 {
2187 	struct migration_swap_arg arg;
2188 	int ret = -EINVAL;
2189 
2190 	arg = (struct migration_swap_arg){
2191 		.src_task = cur,
2192 		.src_cpu = curr_cpu,
2193 		.dst_task = p,
2194 		.dst_cpu = target_cpu,
2195 	};
2196 
2197 	if (arg.src_cpu == arg.dst_cpu)
2198 		goto out;
2199 
2200 	/*
2201 	 * These three tests are all lockless; this is OK since all of them
2202 	 * will be re-checked with proper locks held further down the line.
2203 	 */
2204 	if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu))
2205 		goto out;
2206 
2207 	if (!cpumask_test_cpu(arg.dst_cpu, arg.src_task->cpus_ptr))
2208 		goto out;
2209 
2210 	if (!cpumask_test_cpu(arg.src_cpu, arg.dst_task->cpus_ptr))
2211 		goto out;
2212 
2213 	trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu);
2214 	ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg);
2215 
2216 out:
2217 	return ret;
2218 }
2219 #endif /* CONFIG_NUMA_BALANCING */
2220 
2221 /*
2222  * wait_task_inactive - wait for a thread to unschedule.
2223  *
2224  * If @match_state is nonzero, it's the @p->state value just checked and
2225  * not expected to change.  If it changes, i.e. @p might have woken up,
2226  * then return zero.  When we succeed in waiting for @p to be off its CPU,
2227  * we return a positive number (its total switch count).  If a second call
2228  * a short while later returns the same number, the caller can be sure that
2229  * @p has remained unscheduled the whole time.
2230  *
2231  * The caller must ensure that the task *will* unschedule sometime soon,
2232  * else this function might spin for a *long* time. This function can't
2233  * be called with interrupts off, or it may introduce deadlock with
2234  * smp_call_function() if an IPI is sent by the same process we are
2235  * waiting to become inactive.
2236  */
wait_task_inactive(struct task_struct * p,long match_state)2237 unsigned long wait_task_inactive(struct task_struct *p, long match_state)
2238 {
2239 	int running, queued;
2240 	struct rq_flags rf;
2241 	unsigned long ncsw;
2242 	struct rq *rq;
2243 
2244 	for (;;) {
2245 		/*
2246 		 * We do the initial early heuristics without holding
2247 		 * any task-queue locks at all. We'll only try to get
2248 		 * the runqueue lock when things look like they will
2249 		 * work out!
2250 		 */
2251 		rq = task_rq(p);
2252 
2253 		/*
2254 		 * If the task is actively running on another CPU
2255 		 * still, just relax and busy-wait without holding
2256 		 * any locks.
2257 		 *
2258 		 * NOTE! Since we don't hold any locks, it's not
2259 		 * even sure that "rq" stays as the right runqueue!
2260 		 * But we don't care, since "task_running()" will
2261 		 * return false if the runqueue has changed and p
2262 		 * is actually now running somewhere else!
2263 		 */
2264 		while (task_running(rq, p)) {
2265 			if (match_state && unlikely(p->state != match_state))
2266 				return 0;
2267 			cpu_relax();
2268 		}
2269 
2270 		/*
2271 		 * Ok, time to look more closely! We need the rq
2272 		 * lock now, to be *sure*. If we're wrong, we'll
2273 		 * just go back and repeat.
2274 		 */
2275 		rq = task_rq_lock(p, &rf);
2276 		trace_sched_wait_task(p);
2277 		running = task_running(rq, p);
2278 		queued = task_on_rq_queued(p);
2279 		ncsw = 0;
2280 		if (!match_state || p->state == match_state)
2281 			ncsw = p->nvcsw | LONG_MIN; /* sets MSB */
2282 		task_rq_unlock(rq, p, &rf);
2283 
2284 		/*
2285 		 * If it changed from the expected state, bail out now.
2286 		 */
2287 		if (unlikely(!ncsw))
2288 			break;
2289 
2290 		/*
2291 		 * Was it really running after all now that we
2292 		 * checked with the proper locks actually held?
2293 		 *
2294 		 * Oops. Go back and try again..
2295 		 */
2296 		if (unlikely(running)) {
2297 			cpu_relax();
2298 			continue;
2299 		}
2300 
2301 		/*
2302 		 * It's not enough that it's not actively running,
2303 		 * it must be off the runqueue _entirely_, and not
2304 		 * preempted!
2305 		 *
2306 		 * So if it was still runnable (but just not actively
2307 		 * running right now), it's preempted, and we should
2308 		 * yield - it could be a while.
2309 		 */
2310 		if (unlikely(queued)) {
2311 			ktime_t to = NSEC_PER_SEC / HZ;
2312 
2313 			set_current_state(TASK_UNINTERRUPTIBLE);
2314 			schedule_hrtimeout(&to, HRTIMER_MODE_REL);
2315 			continue;
2316 		}
2317 
2318 		/*
2319 		 * Ahh, all good. It wasn't running, and it wasn't
2320 		 * runnable, which means that it will never become
2321 		 * running in the future either. We're all done!
2322 		 */
2323 		break;
2324 	}
2325 
2326 	return ncsw;
2327 }
2328 
2329 /***
2330  * kick_process - kick a running thread to enter/exit the kernel
2331  * @p: the to-be-kicked thread
2332  *
2333  * Cause a process which is running on another CPU to enter
2334  * kernel-mode, without any delay. (to get signals handled.)
2335  *
2336  * NOTE: this function doesn't have to take the runqueue lock,
2337  * because all it wants to ensure is that the remote task enters
2338  * the kernel. If the IPI races and the task has been migrated
2339  * to another CPU then no harm is done and the purpose has been
2340  * achieved as well.
2341  */
kick_process(struct task_struct * p)2342 void kick_process(struct task_struct *p)
2343 {
2344 	int cpu;
2345 
2346 	preempt_disable();
2347 	cpu = task_cpu(p);
2348 	if ((cpu != smp_processor_id()) && task_curr(p))
2349 		smp_send_reschedule(cpu);
2350 	preempt_enable();
2351 }
2352 EXPORT_SYMBOL_GPL(kick_process);
2353 
2354 /*
2355  * ->cpus_ptr is protected by both rq->lock and p->pi_lock
2356  *
2357  * A few notes on cpu_active vs cpu_online:
2358  *
2359  *  - cpu_active must be a subset of cpu_online
2360  *
2361  *  - on CPU-up we allow per-CPU kthreads on the online && !active CPU,
2362  *    see __set_cpus_allowed_ptr(). At this point the newly online
2363  *    CPU isn't yet part of the sched domains, and balancing will not
2364  *    see it.
2365  *
2366  *  - on CPU-down we clear cpu_active() to mask the sched domains and
2367  *    avoid the load balancer to place new tasks on the to be removed
2368  *    CPU. Existing tasks will remain running there and will be taken
2369  *    off.
2370  *
2371  * This means that fallback selection must not select !active CPUs.
2372  * And can assume that any active CPU must be online. Conversely
2373  * select_task_rq() below may allow selection of !active CPUs in order
2374  * to satisfy the above rules.
2375  */
2376 #ifdef CONFIG_CPU_ISOLATION_OPT
select_fallback_rq(int cpu,struct task_struct * p,bool allow_iso)2377 static int select_fallback_rq(int cpu, struct task_struct *p, bool allow_iso)
2378 #else
2379 static int select_fallback_rq(int cpu, struct task_struct *p)
2380 #endif
2381 {
2382 	int nid = cpu_to_node(cpu);
2383 	const struct cpumask *nodemask = NULL;
2384 	enum { cpuset, possible, fail, bug } state = cpuset;
2385 	int dest_cpu;
2386 #ifdef CONFIG_CPU_ISOLATION_OPT
2387 	int isolated_candidate = -1;
2388 #endif
2389 
2390 	/*
2391 	 * If the node that the CPU is on has been offlined, cpu_to_node()
2392 	 * will return -1. There is no CPU on the node, and we should
2393 	 * select the CPU on the other node.
2394 	 */
2395 	if (nid != -1) {
2396 		nodemask = cpumask_of_node(nid);
2397 
2398 		/* Look for allowed, online CPU in same node. */
2399 		for_each_cpu(dest_cpu, nodemask) {
2400 			if (!cpu_active(dest_cpu))
2401 				continue;
2402 			if (cpu_isolated(dest_cpu))
2403 				continue;
2404 			if (cpumask_test_cpu(dest_cpu, p->cpus_ptr))
2405 				return dest_cpu;
2406 		}
2407 	}
2408 
2409 	for (;;) {
2410 		/* Any allowed, online CPU? */
2411 		for_each_cpu(dest_cpu, p->cpus_ptr) {
2412 			if (!is_cpu_allowed(p, dest_cpu))
2413 				continue;
2414 #ifdef CONFIG_CPU_ISOLATION_OPT
2415 			if (cpu_isolated(dest_cpu)) {
2416 				if (allow_iso)
2417 					isolated_candidate = dest_cpu;
2418 				continue;
2419 			}
2420 			goto out;
2421 		}
2422 
2423 		if (isolated_candidate != -1) {
2424 			dest_cpu = isolated_candidate;
2425 #endif
2426 			goto out;
2427 		}
2428 
2429 		/* No more Mr. Nice Guy. */
2430 		switch (state) {
2431 		case cpuset:
2432 			if (IS_ENABLED(CONFIG_CPUSETS)) {
2433 				cpuset_cpus_allowed_fallback(p);
2434 				state = possible;
2435 				break;
2436 			}
2437 			fallthrough;
2438 		case possible:
2439 			do_set_cpus_allowed(p, cpu_possible_mask);
2440 			state = fail;
2441 			break;
2442 
2443 		case fail:
2444 #ifdef CONFIG_CPU_ISOLATION_OPT
2445 			allow_iso = true;
2446 			state = bug;
2447 			break;
2448 #else
2449 			/* fall through; */
2450 #endif
2451 
2452 		case bug:
2453 			BUG();
2454 			break;
2455 		}
2456 	}
2457 
2458 out:
2459 	if (state != cpuset) {
2460 		/*
2461 		 * Don't tell them about moving exiting tasks or
2462 		 * kernel threads (both mm NULL), since they never
2463 		 * leave kernel.
2464 		 */
2465 		if (p->mm && printk_ratelimit()) {
2466 			printk_deferred("process %d (%s) no longer affine to cpu%d\n",
2467 					task_pid_nr(p), p->comm, cpu);
2468 		}
2469 	}
2470 
2471 	return dest_cpu;
2472 }
2473 
2474 /*
2475  * The caller (fork, wakeup) owns p->pi_lock, ->cpus_ptr is stable.
2476  */
2477 static inline
select_task_rq(struct task_struct * p,int cpu,int sd_flags,int wake_flags)2478 int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags)
2479 {
2480 #ifdef CONFIG_CPU_ISOLATION_OPT
2481 	bool allow_isolated = (p->flags & PF_KTHREAD);
2482 #endif
2483 
2484 	lockdep_assert_held(&p->pi_lock);
2485 
2486 	if (p->nr_cpus_allowed > 1)
2487 		cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags);
2488 	else
2489 		cpu = cpumask_any(p->cpus_ptr);
2490 
2491 	/*
2492 	 * In order not to call set_task_cpu() on a blocking task we need
2493 	 * to rely on ttwu() to place the task on a valid ->cpus_ptr
2494 	 * CPU.
2495 	 *
2496 	 * Since this is common to all placement strategies, this lives here.
2497 	 *
2498 	 * [ this allows ->select_task() to simply return task_cpu(p) and
2499 	 *   not worry about this generic constraint ]
2500 	 */
2501 #ifdef CONFIG_CPU_ISOLATION_OPT
2502 	if (unlikely(!is_cpu_allowed(p, cpu)) ||
2503 			(cpu_isolated(cpu) && !allow_isolated))
2504 		cpu = select_fallback_rq(task_cpu(p), p, allow_isolated);
2505 #else
2506 	if (unlikely(!is_cpu_allowed(p, cpu)))
2507 		cpu = select_fallback_rq(task_cpu(p), p);
2508 #endif
2509 
2510 	return cpu;
2511 }
2512 
sched_set_stop_task(int cpu,struct task_struct * stop)2513 void sched_set_stop_task(int cpu, struct task_struct *stop)
2514 {
2515 	struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
2516 	struct task_struct *old_stop = cpu_rq(cpu)->stop;
2517 
2518 	if (stop) {
2519 		/*
2520 		 * Make it appear like a SCHED_FIFO task, its something
2521 		 * userspace knows about and won't get confused about.
2522 		 *
2523 		 * Also, it will make PI more or less work without too
2524 		 * much confusion -- but then, stop work should not
2525 		 * rely on PI working anyway.
2526 		 */
2527 		sched_setscheduler_nocheck(stop, SCHED_FIFO, &param);
2528 
2529 		stop->sched_class = &stop_sched_class;
2530 	}
2531 
2532 	cpu_rq(cpu)->stop = stop;
2533 
2534 	if (old_stop) {
2535 		/*
2536 		 * Reset it back to a normal scheduling class so that
2537 		 * it can die in pieces.
2538 		 */
2539 		old_stop->sched_class = &rt_sched_class;
2540 	}
2541 }
2542 
2543 #else
2544 
__set_cpus_allowed_ptr(struct task_struct * p,const struct cpumask * new_mask,bool check)2545 static inline int __set_cpus_allowed_ptr(struct task_struct *p,
2546 					 const struct cpumask *new_mask, bool check)
2547 {
2548 	return set_cpus_allowed_ptr(p, new_mask);
2549 }
2550 
2551 #endif /* CONFIG_SMP */
2552 
2553 static void
ttwu_stat(struct task_struct * p,int cpu,int wake_flags)2554 ttwu_stat(struct task_struct *p, int cpu, int wake_flags)
2555 {
2556 	struct rq *rq;
2557 
2558 	if (!schedstat_enabled())
2559 		return;
2560 
2561 	rq = this_rq();
2562 
2563 #ifdef CONFIG_SMP
2564 	if (cpu == rq->cpu) {
2565 		__schedstat_inc(rq->ttwu_local);
2566 		__schedstat_inc(p->se.statistics.nr_wakeups_local);
2567 	} else {
2568 		struct sched_domain *sd;
2569 
2570 		__schedstat_inc(p->se.statistics.nr_wakeups_remote);
2571 		rcu_read_lock();
2572 		for_each_domain(rq->cpu, sd) {
2573 			if (cpumask_test_cpu(cpu, sched_domain_span(sd))) {
2574 				__schedstat_inc(sd->ttwu_wake_remote);
2575 				break;
2576 			}
2577 		}
2578 		rcu_read_unlock();
2579 	}
2580 
2581 	if (wake_flags & WF_MIGRATED)
2582 		__schedstat_inc(p->se.statistics.nr_wakeups_migrate);
2583 #endif /* CONFIG_SMP */
2584 
2585 	__schedstat_inc(rq->ttwu_count);
2586 	__schedstat_inc(p->se.statistics.nr_wakeups);
2587 
2588 	if (wake_flags & WF_SYNC)
2589 		__schedstat_inc(p->se.statistics.nr_wakeups_sync);
2590 }
2591 
2592 /*
2593  * Mark the task runnable and perform wakeup-preemption.
2594  */
ttwu_do_wakeup(struct rq * rq,struct task_struct * p,int wake_flags,struct rq_flags * rf)2595 static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags,
2596 			   struct rq_flags *rf)
2597 {
2598 	check_preempt_curr(rq, p, wake_flags);
2599 	p->state = TASK_RUNNING;
2600 	trace_sched_wakeup(p);
2601 
2602 #ifdef CONFIG_SMP
2603 	if (p->sched_class->task_woken) {
2604 		/*
2605 		 * Our task @p is fully woken up and running; so its safe to
2606 		 * drop the rq->lock, hereafter rq is only used for statistics.
2607 		 */
2608 		rq_unpin_lock(rq, rf);
2609 		p->sched_class->task_woken(rq, p);
2610 		rq_repin_lock(rq, rf);
2611 	}
2612 
2613 	if (rq->idle_stamp) {
2614 		u64 delta = rq_clock(rq) - rq->idle_stamp;
2615 		u64 max = 2*rq->max_idle_balance_cost;
2616 
2617 		update_avg(&rq->avg_idle, delta);
2618 
2619 		if (rq->avg_idle > max)
2620 			rq->avg_idle = max;
2621 
2622 		rq->idle_stamp = 0;
2623 	}
2624 #endif
2625 }
2626 
2627 static void
ttwu_do_activate(struct rq * rq,struct task_struct * p,int wake_flags,struct rq_flags * rf)2628 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags,
2629 		 struct rq_flags *rf)
2630 {
2631 	int en_flags = ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK;
2632 
2633 	lockdep_assert_held(&rq->lock);
2634 
2635 	if (p->sched_contributes_to_load)
2636 		rq->nr_uninterruptible--;
2637 
2638 #ifdef CONFIG_SMP
2639 	if (wake_flags & WF_MIGRATED)
2640 		en_flags |= ENQUEUE_MIGRATED;
2641 	else
2642 #endif
2643 	if (p->in_iowait) {
2644 		delayacct_blkio_end(p);
2645 		atomic_dec(&task_rq(p)->nr_iowait);
2646 	}
2647 
2648 	activate_task(rq, p, en_flags);
2649 	ttwu_do_wakeup(rq, p, wake_flags, rf);
2650 }
2651 
2652 /*
2653  * Consider @p being inside a wait loop:
2654  *
2655  *   for (;;) {
2656  *      set_current_state(TASK_UNINTERRUPTIBLE);
2657  *
2658  *      if (CONDITION)
2659  *         break;
2660  *
2661  *      schedule();
2662  *   }
2663  *   __set_current_state(TASK_RUNNING);
2664  *
2665  * between set_current_state() and schedule(). In this case @p is still
2666  * runnable, so all that needs doing is change p->state back to TASK_RUNNING in
2667  * an atomic manner.
2668  *
2669  * By taking task_rq(p)->lock we serialize against schedule(), if @p->on_rq
2670  * then schedule() must still happen and p->state can be changed to
2671  * TASK_RUNNING. Otherwise we lost the race, schedule() has happened, and we
2672  * need to do a full wakeup with enqueue.
2673  *
2674  * Returns: %true when the wakeup is done,
2675  *          %false otherwise.
2676  */
ttwu_runnable(struct task_struct * p,int wake_flags)2677 static int ttwu_runnable(struct task_struct *p, int wake_flags)
2678 {
2679 	struct rq_flags rf;
2680 	struct rq *rq;
2681 	int ret = 0;
2682 
2683 	rq = __task_rq_lock(p, &rf);
2684 	if (task_on_rq_queued(p)) {
2685 		/* check_preempt_curr() may use rq clock */
2686 		update_rq_clock(rq);
2687 		ttwu_do_wakeup(rq, p, wake_flags, &rf);
2688 		ret = 1;
2689 	}
2690 	__task_rq_unlock(rq, &rf);
2691 
2692 	return ret;
2693 }
2694 
2695 #ifdef CONFIG_SMP
sched_ttwu_pending(void * arg)2696 void sched_ttwu_pending(void *arg)
2697 {
2698 	struct llist_node *llist = arg;
2699 	struct rq *rq = this_rq();
2700 	struct task_struct *p, *t;
2701 	struct rq_flags rf;
2702 
2703 	if (!llist)
2704 		return;
2705 
2706 	/*
2707 	 * rq::ttwu_pending racy indication of out-standing wakeups.
2708 	 * Races such that false-negatives are possible, since they
2709 	 * are shorter lived that false-positives would be.
2710 	 */
2711 	WRITE_ONCE(rq->ttwu_pending, 0);
2712 
2713 	rq_lock_irqsave(rq, &rf);
2714 	update_rq_clock(rq);
2715 
2716 	llist_for_each_entry_safe(p, t, llist, wake_entry.llist) {
2717 		if (WARN_ON_ONCE(p->on_cpu))
2718 			smp_cond_load_acquire(&p->on_cpu, !VAL);
2719 
2720 		if (WARN_ON_ONCE(task_cpu(p) != cpu_of(rq)))
2721 			set_task_cpu(p, cpu_of(rq));
2722 
2723 		ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0, &rf);
2724 	}
2725 
2726 	rq_unlock_irqrestore(rq, &rf);
2727 }
2728 
send_call_function_single_ipi(int cpu)2729 void send_call_function_single_ipi(int cpu)
2730 {
2731 	struct rq *rq = cpu_rq(cpu);
2732 
2733 	if (!set_nr_if_polling(rq->idle))
2734 		arch_send_call_function_single_ipi(cpu);
2735 	else
2736 		trace_sched_wake_idle_without_ipi(cpu);
2737 }
2738 
2739 /*
2740  * Queue a task on the target CPUs wake_list and wake the CPU via IPI if
2741  * necessary. The wakee CPU on receipt of the IPI will queue the task
2742  * via sched_ttwu_wakeup() for activation so the wakee incurs the cost
2743  * of the wakeup instead of the waker.
2744  */
__ttwu_queue_wakelist(struct task_struct * p,int cpu,int wake_flags)2745 static void __ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
2746 {
2747 	struct rq *rq = cpu_rq(cpu);
2748 
2749 	p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED);
2750 
2751 	WRITE_ONCE(rq->ttwu_pending, 1);
2752 	__smp_call_single_queue(cpu, &p->wake_entry.llist);
2753 }
2754 
wake_up_if_idle(int cpu)2755 void wake_up_if_idle(int cpu)
2756 {
2757 	struct rq *rq = cpu_rq(cpu);
2758 	struct rq_flags rf;
2759 
2760 	rcu_read_lock();
2761 
2762 	if (!is_idle_task(rcu_dereference(rq->curr)))
2763 		goto out;
2764 
2765 	if (set_nr_if_polling(rq->idle)) {
2766 		trace_sched_wake_idle_without_ipi(cpu);
2767 	} else {
2768 		rq_lock_irqsave(rq, &rf);
2769 		if (is_idle_task(rq->curr))
2770 			smp_send_reschedule(cpu);
2771 		/* Else CPU is not idle, do nothing here: */
2772 		rq_unlock_irqrestore(rq, &rf);
2773 	}
2774 
2775 out:
2776 	rcu_read_unlock();
2777 }
2778 
cpus_share_cache(int this_cpu,int that_cpu)2779 bool cpus_share_cache(int this_cpu, int that_cpu)
2780 {
2781 	if (this_cpu == that_cpu)
2782 		return true;
2783 
2784 	return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu);
2785 }
2786 
ttwu_queue_cond(int cpu,int wake_flags)2787 static inline bool ttwu_queue_cond(int cpu, int wake_flags)
2788 {
2789 	/*
2790 	 * If the CPU does not share cache, then queue the task on the
2791 	 * remote rqs wakelist to avoid accessing remote data.
2792 	 */
2793 	if (!cpus_share_cache(smp_processor_id(), cpu))
2794 		return true;
2795 
2796 	/*
2797 	 * If the task is descheduling and the only running task on the
2798 	 * CPU then use the wakelist to offload the task activation to
2799 	 * the soon-to-be-idle CPU as the current CPU is likely busy.
2800 	 * nr_running is checked to avoid unnecessary task stacking.
2801 	 *
2802 	 * Note that we can only get here with (wakee) p->on_rq=0,
2803 	 * p->on_cpu can be whatever, we've done the dequeue, so
2804 	 * the wakee has been accounted out of ->nr_running.
2805 	 */
2806 	if ((wake_flags & WF_ON_CPU) && !cpu_rq(cpu)->nr_running)
2807 		return true;
2808 
2809 	return false;
2810 }
2811 
ttwu_queue_wakelist(struct task_struct * p,int cpu,int wake_flags)2812 static bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
2813 {
2814 	if (sched_feat(TTWU_QUEUE) && ttwu_queue_cond(cpu, wake_flags)) {
2815 		if (WARN_ON_ONCE(cpu == smp_processor_id()))
2816 			return false;
2817 
2818 		sched_clock_cpu(cpu); /* Sync clocks across CPUs */
2819 		__ttwu_queue_wakelist(p, cpu, wake_flags);
2820 		return true;
2821 	}
2822 
2823 	return false;
2824 }
2825 
2826 #else /* !CONFIG_SMP */
2827 
ttwu_queue_wakelist(struct task_struct * p,int cpu,int wake_flags)2828 static inline bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags)
2829 {
2830 	return false;
2831 }
2832 
2833 #endif /* CONFIG_SMP */
2834 
ttwu_queue(struct task_struct * p,int cpu,int wake_flags)2835 static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags)
2836 {
2837 	struct rq *rq = cpu_rq(cpu);
2838 	struct rq_flags rf;
2839 
2840 	if (ttwu_queue_wakelist(p, cpu, wake_flags))
2841 		return;
2842 
2843 	rq_lock(rq, &rf);
2844 	update_rq_clock(rq);
2845 	ttwu_do_activate(rq, p, wake_flags, &rf);
2846 	rq_unlock(rq, &rf);
2847 }
2848 
2849 /*
2850  * Notes on Program-Order guarantees on SMP systems.
2851  *
2852  *  MIGRATION
2853  *
2854  * The basic program-order guarantee on SMP systems is that when a task [t]
2855  * migrates, all its activity on its old CPU [c0] happens-before any subsequent
2856  * execution on its new CPU [c1].
2857  *
2858  * For migration (of runnable tasks) this is provided by the following means:
2859  *
2860  *  A) UNLOCK of the rq(c0)->lock scheduling out task t
2861  *  B) migration for t is required to synchronize *both* rq(c0)->lock and
2862  *     rq(c1)->lock (if not at the same time, then in that order).
2863  *  C) LOCK of the rq(c1)->lock scheduling in task
2864  *
2865  * Release/acquire chaining guarantees that B happens after A and C after B.
2866  * Note: the CPU doing B need not be c0 or c1
2867  *
2868  * Example:
2869  *
2870  *   CPU0            CPU1            CPU2
2871  *
2872  *   LOCK rq(0)->lock
2873  *   sched-out X
2874  *   sched-in Y
2875  *   UNLOCK rq(0)->lock
2876  *
2877  *                                   LOCK rq(0)->lock // orders against CPU0
2878  *                                   dequeue X
2879  *                                   UNLOCK rq(0)->lock
2880  *
2881  *                                   LOCK rq(1)->lock
2882  *                                   enqueue X
2883  *                                   UNLOCK rq(1)->lock
2884  *
2885  *                   LOCK rq(1)->lock // orders against CPU2
2886  *                   sched-out Z
2887  *                   sched-in X
2888  *                   UNLOCK rq(1)->lock
2889  *
2890  *
2891  *  BLOCKING -- aka. SLEEP + WAKEUP
2892  *
2893  * For blocking we (obviously) need to provide the same guarantee as for
2894  * migration. However the means are completely different as there is no lock
2895  * chain to provide order. Instead we do:
2896  *
2897  *   1) smp_store_release(X->on_cpu, 0)   -- finish_task()
2898  *   2) smp_cond_load_acquire(!X->on_cpu) -- try_to_wake_up()
2899  *
2900  * Example:
2901  *
2902  *   CPU0 (schedule)  CPU1 (try_to_wake_up) CPU2 (schedule)
2903  *
2904  *   LOCK rq(0)->lock LOCK X->pi_lock
2905  *   dequeue X
2906  *   sched-out X
2907  *   smp_store_release(X->on_cpu, 0);
2908  *
2909  *                    smp_cond_load_acquire(&X->on_cpu, !VAL);
2910  *                    X->state = WAKING
2911  *                    set_task_cpu(X,2)
2912  *
2913  *                    LOCK rq(2)->lock
2914  *                    enqueue X
2915  *                    X->state = RUNNING
2916  *                    UNLOCK rq(2)->lock
2917  *
2918  *                                          LOCK rq(2)->lock // orders against CPU1
2919  *                                          sched-out Z
2920  *                                          sched-in X
2921  *                                          UNLOCK rq(2)->lock
2922  *
2923  *                    UNLOCK X->pi_lock
2924  *   UNLOCK rq(0)->lock
2925  *
2926  *
2927  * However, for wakeups there is a second guarantee we must provide, namely we
2928  * must ensure that CONDITION=1 done by the caller can not be reordered with
2929  * accesses to the task state; see try_to_wake_up() and set_current_state().
2930  */
2931 
2932 #ifdef CONFIG_SMP
2933 #ifdef CONFIG_SCHED_WALT
2934 /* utility function to update walt signals at wakeup */
walt_try_to_wake_up(struct task_struct * p)2935 static inline void walt_try_to_wake_up(struct task_struct *p)
2936 {
2937 	struct rq *rq = cpu_rq(task_cpu(p));
2938 	struct rq_flags rf;
2939 	u64 wallclock;
2940 
2941 	rq_lock_irqsave(rq, &rf);
2942 	wallclock = sched_ktime_clock();
2943 	update_task_ravg(rq->curr, rq, TASK_UPDATE, wallclock, 0);
2944 	update_task_ravg(p, rq, TASK_WAKE, wallclock, 0);
2945 	rq_unlock_irqrestore(rq, &rf);
2946 }
2947 #else
2948 #define walt_try_to_wake_up(a) {}
2949 #endif
2950 #endif
2951 
2952 /**
2953  * try_to_wake_up - wake up a thread
2954  * @p: the thread to be awakened
2955  * @state: the mask of task states that can be woken
2956  * @wake_flags: wake modifier flags (WF_*)
2957  *
2958  * Conceptually does:
2959  *
2960  *   If (@state & @p->state) @p->state = TASK_RUNNING.
2961  *
2962  * If the task was not queued/runnable, also place it back on a runqueue.
2963  *
2964  * This function is atomic against schedule() which would dequeue the task.
2965  *
2966  * It issues a full memory barrier before accessing @p->state, see the comment
2967  * with set_current_state().
2968  *
2969  * Uses p->pi_lock to serialize against concurrent wake-ups.
2970  *
2971  * Relies on p->pi_lock stabilizing:
2972  *  - p->sched_class
2973  *  - p->cpus_ptr
2974  *  - p->sched_task_group
2975  * in order to do migration, see its use of select_task_rq()/set_task_cpu().
2976  *
2977  * Tries really hard to only take one task_rq(p)->lock for performance.
2978  * Takes rq->lock in:
2979  *  - ttwu_runnable()    -- old rq, unavoidable, see comment there;
2980  *  - ttwu_queue()       -- new rq, for enqueue of the task;
2981  *  - psi_ttwu_dequeue() -- much sadness :-( accounting will kill us.
2982  *
2983  * As a consequence we race really badly with just about everything. See the
2984  * many memory barriers and their comments for details.
2985  *
2986  * Return: %true if @p->state changes (an actual wakeup was done),
2987  *	   %false otherwise.
2988  */
2989 static int
try_to_wake_up(struct task_struct * p,unsigned int state,int wake_flags)2990 try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags)
2991 {
2992 	unsigned long flags;
2993 	int cpu, success = 0;
2994 
2995 	preempt_disable();
2996 	if (p == current) {
2997 		/*
2998 		 * We're waking current, this means 'p->on_rq' and 'task_cpu(p)
2999 		 * == smp_processor_id()'. Together this means we can special
3000 		 * case the whole 'p->on_rq && ttwu_runnable()' case below
3001 		 * without taking any locks.
3002 		 *
3003 		 * In particular:
3004 		 *  - we rely on Program-Order guarantees for all the ordering,
3005 		 *  - we're serialized against set_special_state() by virtue of
3006 		 *    it disabling IRQs (this allows not taking ->pi_lock).
3007 		 */
3008 		if (!(p->state & state))
3009 			goto out;
3010 
3011 		success = 1;
3012 		trace_sched_waking(p);
3013 		p->state = TASK_RUNNING;
3014 		trace_sched_wakeup(p);
3015 		goto out;
3016 	}
3017 
3018 	/*
3019 	 * If we are going to wake up a thread waiting for CONDITION we
3020 	 * need to ensure that CONDITION=1 done by the caller can not be
3021 	 * reordered with p->state check below. This pairs with smp_store_mb()
3022 	 * in set_current_state() that the waiting thread does.
3023 	 */
3024 	raw_spin_lock_irqsave(&p->pi_lock, flags);
3025 	smp_mb__after_spinlock();
3026 	if (!(p->state & state))
3027 		goto unlock;
3028 
3029 	trace_sched_waking(p);
3030 
3031 	/* We're going to change ->state: */
3032 	success = 1;
3033 
3034 	/*
3035 	 * Ensure we load p->on_rq _after_ p->state, otherwise it would
3036 	 * be possible to, falsely, observe p->on_rq == 0 and get stuck
3037 	 * in smp_cond_load_acquire() below.
3038 	 *
3039 	 * sched_ttwu_pending()			try_to_wake_up()
3040 	 *   STORE p->on_rq = 1			  LOAD p->state
3041 	 *   UNLOCK rq->lock
3042 	 *
3043 	 * __schedule() (switch to task 'p')
3044 	 *   LOCK rq->lock			  smp_rmb();
3045 	 *   smp_mb__after_spinlock();
3046 	 *   UNLOCK rq->lock
3047 	 *
3048 	 * [task p]
3049 	 *   STORE p->state = UNINTERRUPTIBLE	  LOAD p->on_rq
3050 	 *
3051 	 * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
3052 	 * __schedule().  See the comment for smp_mb__after_spinlock().
3053 	 *
3054 	 * A similar smb_rmb() lives in try_invoke_on_locked_down_task().
3055 	 */
3056 	smp_rmb();
3057 	if (READ_ONCE(p->on_rq) && ttwu_runnable(p, wake_flags))
3058 		goto unlock;
3059 
3060 #ifdef CONFIG_SMP
3061 	/*
3062 	 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be
3063 	 * possible to, falsely, observe p->on_cpu == 0.
3064 	 *
3065 	 * One must be running (->on_cpu == 1) in order to remove oneself
3066 	 * from the runqueue.
3067 	 *
3068 	 * __schedule() (switch to task 'p')	try_to_wake_up()
3069 	 *   STORE p->on_cpu = 1		  LOAD p->on_rq
3070 	 *   UNLOCK rq->lock
3071 	 *
3072 	 * __schedule() (put 'p' to sleep)
3073 	 *   LOCK rq->lock			  smp_rmb();
3074 	 *   smp_mb__after_spinlock();
3075 	 *   STORE p->on_rq = 0			  LOAD p->on_cpu
3076 	 *
3077 	 * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in
3078 	 * __schedule().  See the comment for smp_mb__after_spinlock().
3079 	 *
3080 	 * Form a control-dep-acquire with p->on_rq == 0 above, to ensure
3081 	 * schedule()'s deactivate_task() has 'happened' and p will no longer
3082 	 * care about it's own p->state. See the comment in __schedule().
3083 	 */
3084 	smp_acquire__after_ctrl_dep();
3085 
3086 	walt_try_to_wake_up(p);
3087 
3088 	/*
3089 	 * We're doing the wakeup (@success == 1), they did a dequeue (p->on_rq
3090 	 * == 0), which means we need to do an enqueue, change p->state to
3091 	 * TASK_WAKING such that we can unlock p->pi_lock before doing the
3092 	 * enqueue, such as ttwu_queue_wakelist().
3093 	 */
3094 	p->state = TASK_WAKING;
3095 
3096 	/*
3097 	 * If the owning (remote) CPU is still in the middle of schedule() with
3098 	 * this task as prev, considering queueing p on the remote CPUs wake_list
3099 	 * which potentially sends an IPI instead of spinning on p->on_cpu to
3100 	 * let the waker make forward progress. This is safe because IRQs are
3101 	 * disabled and the IPI will deliver after on_cpu is cleared.
3102 	 *
3103 	 * Ensure we load task_cpu(p) after p->on_cpu:
3104 	 *
3105 	 * set_task_cpu(p, cpu);
3106 	 *   STORE p->cpu = @cpu
3107 	 * __schedule() (switch to task 'p')
3108 	 *   LOCK rq->lock
3109 	 *   smp_mb__after_spin_lock()		smp_cond_load_acquire(&p->on_cpu)
3110 	 *   STORE p->on_cpu = 1		LOAD p->cpu
3111 	 *
3112 	 * to ensure we observe the correct CPU on which the task is currently
3113 	 * scheduling.
3114 	 */
3115 	if (smp_load_acquire(&p->on_cpu) &&
3116 	    ttwu_queue_wakelist(p, task_cpu(p), wake_flags | WF_ON_CPU))
3117 		goto unlock;
3118 
3119 	/*
3120 	 * If the owning (remote) CPU is still in the middle of schedule() with
3121 	 * this task as prev, wait until its done referencing the task.
3122 	 *
3123 	 * Pairs with the smp_store_release() in finish_task().
3124 	 *
3125 	 * This ensures that tasks getting woken will be fully ordered against
3126 	 * their previous state and preserve Program Order.
3127 	 */
3128 	smp_cond_load_acquire(&p->on_cpu, !VAL);
3129 
3130 	cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags);
3131 	if (task_cpu(p) != cpu) {
3132 		if (p->in_iowait) {
3133 			delayacct_blkio_end(p);
3134 			atomic_dec(&task_rq(p)->nr_iowait);
3135 		}
3136 
3137 		wake_flags |= WF_MIGRATED;
3138 		psi_ttwu_dequeue(p);
3139 		set_task_cpu(p, cpu);
3140 	}
3141 #else
3142 	cpu = task_cpu(p);
3143 #endif /* CONFIG_SMP */
3144 
3145 	ttwu_queue(p, cpu, wake_flags);
3146 unlock:
3147 	raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3148 out:
3149 	if (success)
3150 		ttwu_stat(p, task_cpu(p), wake_flags);
3151 	preempt_enable();
3152 
3153 	return success;
3154 }
3155 
3156 /**
3157  * try_invoke_on_locked_down_task - Invoke a function on task in fixed state
3158  * @p: Process for which the function is to be invoked, can be @current.
3159  * @func: Function to invoke.
3160  * @arg: Argument to function.
3161  *
3162  * If the specified task can be quickly locked into a definite state
3163  * (either sleeping or on a given runqueue), arrange to keep it in that
3164  * state while invoking @func(@arg).  This function can use ->on_rq and
3165  * task_curr() to work out what the state is, if required.  Given that
3166  * @func can be invoked with a runqueue lock held, it had better be quite
3167  * lightweight.
3168  *
3169  * Returns:
3170  *	@false if the task slipped out from under the locks.
3171  *	@true if the task was locked onto a runqueue or is sleeping.
3172  *		However, @func can override this by returning @false.
3173  */
try_invoke_on_locked_down_task(struct task_struct * p,bool (* func)(struct task_struct * t,void * arg),void * arg)3174 bool try_invoke_on_locked_down_task(struct task_struct *p, bool (*func)(struct task_struct *t, void *arg), void *arg)
3175 {
3176 	struct rq_flags rf;
3177 	bool ret = false;
3178 	struct rq *rq;
3179 
3180 	raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
3181 	if (p->on_rq) {
3182 		rq = __task_rq_lock(p, &rf);
3183 		if (task_rq(p) == rq)
3184 			ret = func(p, arg);
3185 		rq_unlock(rq, &rf);
3186 	} else {
3187 		switch (p->state) {
3188 		case TASK_RUNNING:
3189 		case TASK_WAKING:
3190 			break;
3191 		default:
3192 			smp_rmb(); // See smp_rmb() comment in try_to_wake_up().
3193 			if (!p->on_rq)
3194 				ret = func(p, arg);
3195 		}
3196 	}
3197 	raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags);
3198 	return ret;
3199 }
3200 
3201 /**
3202  * wake_up_process - Wake up a specific process
3203  * @p: The process to be woken up.
3204  *
3205  * Attempt to wake up the nominated process and move it to the set of runnable
3206  * processes.
3207  *
3208  * Return: 1 if the process was woken up, 0 if it was already running.
3209  *
3210  * This function executes a full memory barrier before accessing the task state.
3211  */
wake_up_process(struct task_struct * p)3212 int wake_up_process(struct task_struct *p)
3213 {
3214 	return try_to_wake_up(p, TASK_NORMAL, 0);
3215 }
3216 EXPORT_SYMBOL(wake_up_process);
3217 
wake_up_state(struct task_struct * p,unsigned int state)3218 int wake_up_state(struct task_struct *p, unsigned int state)
3219 {
3220 	return try_to_wake_up(p, state, 0);
3221 }
3222 
3223 /*
3224  * Perform scheduler related setup for a newly forked process p.
3225  * p is forked by current.
3226  *
3227  * __sched_fork() is basic setup used by init_idle() too:
3228  */
__sched_fork(unsigned long clone_flags,struct task_struct * p)3229 static void __sched_fork(unsigned long clone_flags, struct task_struct *p)
3230 {
3231 	p->on_rq			= 0;
3232 
3233 	p->se.on_rq			= 0;
3234 	p->se.exec_start		= 0;
3235 	p->se.sum_exec_runtime		= 0;
3236 	p->se.prev_sum_exec_runtime	= 0;
3237 	p->se.nr_migrations		= 0;
3238 	p->se.vruntime			= 0;
3239 	INIT_LIST_HEAD(&p->se.group_node);
3240 
3241 #ifdef CONFIG_FAIR_GROUP_SCHED
3242 	p->se.cfs_rq			= NULL;
3243 #endif
3244 
3245 #ifdef CONFIG_SCHEDSTATS
3246 	/* Even if schedstat is disabled, there should not be garbage */
3247 	memset(&p->se.statistics, 0, sizeof(p->se.statistics));
3248 #endif
3249 
3250 	RB_CLEAR_NODE(&p->dl.rb_node);
3251 	init_dl_task_timer(&p->dl);
3252 	init_dl_inactive_task_timer(&p->dl);
3253 	__dl_clear_params(p);
3254 
3255 	INIT_LIST_HEAD(&p->rt.run_list);
3256 	p->rt.timeout		= 0;
3257 	p->rt.time_slice	= sched_rr_timeslice;
3258 	p->rt.on_rq		= 0;
3259 	p->rt.on_list		= 0;
3260 
3261 #ifdef CONFIG_PREEMPT_NOTIFIERS
3262 	INIT_HLIST_HEAD(&p->preempt_notifiers);
3263 #endif
3264 
3265 #ifdef CONFIG_COMPACTION
3266 	p->capture_control = NULL;
3267 #endif
3268 	init_numa_balancing(clone_flags, p);
3269 #ifdef CONFIG_SMP
3270 	p->wake_entry.u_flags = CSD_TYPE_TTWU;
3271 #endif
3272 #ifdef CONFIG_SCHED_RTG
3273 	p->rtg_depth = 0;
3274 #endif
3275 }
3276 
3277 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing);
3278 
3279 #ifdef CONFIG_NUMA_BALANCING
3280 
set_numabalancing_state(bool enabled)3281 void set_numabalancing_state(bool enabled)
3282 {
3283 	if (enabled)
3284 		static_branch_enable(&sched_numa_balancing);
3285 	else
3286 		static_branch_disable(&sched_numa_balancing);
3287 }
3288 
3289 #ifdef CONFIG_PROC_SYSCTL
sysctl_numa_balancing(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)3290 int sysctl_numa_balancing(struct ctl_table *table, int write,
3291 			  void *buffer, size_t *lenp, loff_t *ppos)
3292 {
3293 	struct ctl_table t;
3294 	int err;
3295 	int state = static_branch_likely(&sched_numa_balancing);
3296 
3297 	if (write && !capable(CAP_SYS_ADMIN))
3298 		return -EPERM;
3299 
3300 	t = *table;
3301 	t.data = &state;
3302 	err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
3303 	if (err < 0)
3304 		return err;
3305 	if (write)
3306 		set_numabalancing_state(state);
3307 	return err;
3308 }
3309 #endif
3310 #endif
3311 
3312 #ifdef CONFIG_SCHEDSTATS
3313 
3314 DEFINE_STATIC_KEY_FALSE(sched_schedstats);
3315 static bool __initdata __sched_schedstats = false;
3316 
set_schedstats(bool enabled)3317 static void set_schedstats(bool enabled)
3318 {
3319 	if (enabled)
3320 		static_branch_enable(&sched_schedstats);
3321 	else
3322 		static_branch_disable(&sched_schedstats);
3323 }
3324 
force_schedstat_enabled(void)3325 void force_schedstat_enabled(void)
3326 {
3327 	if (!schedstat_enabled()) {
3328 		pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n");
3329 		static_branch_enable(&sched_schedstats);
3330 	}
3331 }
3332 
setup_schedstats(char * str)3333 static int __init setup_schedstats(char *str)
3334 {
3335 	int ret = 0;
3336 	if (!str)
3337 		goto out;
3338 
3339 	/*
3340 	 * This code is called before jump labels have been set up, so we can't
3341 	 * change the static branch directly just yet.  Instead set a temporary
3342 	 * variable so init_schedstats() can do it later.
3343 	 */
3344 	if (!strcmp(str, "enable")) {
3345 		__sched_schedstats = true;
3346 		ret = 1;
3347 	} else if (!strcmp(str, "disable")) {
3348 		__sched_schedstats = false;
3349 		ret = 1;
3350 	}
3351 out:
3352 	if (!ret)
3353 		pr_warn("Unable to parse schedstats=\n");
3354 
3355 	return ret;
3356 }
3357 __setup("schedstats=", setup_schedstats);
3358 
init_schedstats(void)3359 static void __init init_schedstats(void)
3360 {
3361 	set_schedstats(__sched_schedstats);
3362 }
3363 
3364 #ifdef CONFIG_PROC_SYSCTL
sysctl_schedstats(struct ctl_table * table,int write,void * buffer,size_t * lenp,loff_t * ppos)3365 int sysctl_schedstats(struct ctl_table *table, int write, void *buffer,
3366 		size_t *lenp, loff_t *ppos)
3367 {
3368 	struct ctl_table t;
3369 	int err;
3370 	int state = static_branch_likely(&sched_schedstats);
3371 
3372 	if (write && !capable(CAP_SYS_ADMIN))
3373 		return -EPERM;
3374 
3375 	t = *table;
3376 	t.data = &state;
3377 	err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos);
3378 	if (err < 0)
3379 		return err;
3380 	if (write)
3381 		set_schedstats(state);
3382 	return err;
3383 }
3384 #endif /* CONFIG_PROC_SYSCTL */
3385 #else  /* !CONFIG_SCHEDSTATS */
init_schedstats(void)3386 static inline void init_schedstats(void) {}
3387 #endif /* CONFIG_SCHEDSTATS */
3388 
3389 /*
3390  * fork()/clone()-time setup:
3391  */
sched_fork(unsigned long clone_flags,struct task_struct * p)3392 int sched_fork(unsigned long clone_flags, struct task_struct *p)
3393 {
3394 	init_new_task_load(p);
3395 
3396 #ifdef CONFIG_QOS_CTRL
3397 	init_task_qos(p);
3398 #endif
3399 
3400 	__sched_fork(clone_flags, p);
3401 	/*
3402 	 * We mark the process as NEW here. This guarantees that
3403 	 * nobody will actually run it, and a signal or other external
3404 	 * event cannot wake it up and insert it on the runqueue either.
3405 	 */
3406 	p->state = TASK_NEW;
3407 
3408 	/*
3409 	 * Make sure we do not leak PI boosting priority to the child.
3410 	 */
3411 	p->prio = current->normal_prio;
3412 
3413 #ifdef CONFIG_SCHED_LATENCY_NICE
3414 	/* Propagate the parent's latency requirements to the child as well */
3415 	p->latency_prio = current->latency_prio;
3416 #endif
3417 
3418 	uclamp_fork(p);
3419 
3420 	/*
3421 	 * Revert to default priority/policy on fork if requested.
3422 	 */
3423 	if (unlikely(p->sched_reset_on_fork)) {
3424 		if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
3425 			p->policy = SCHED_NORMAL;
3426 #ifdef CONFIG_SCHED_RTG
3427 			if (current->rtg_depth != 0)
3428 				p->static_prio = current->static_prio;
3429 			else
3430 				p->static_prio = NICE_TO_PRIO(0);
3431 #else
3432 			p->static_prio = NICE_TO_PRIO(0);
3433 #endif
3434 			p->rt_priority = 0;
3435 		} else if (PRIO_TO_NICE(p->static_prio) < 0)
3436 			p->static_prio = NICE_TO_PRIO(0);
3437 
3438 		p->prio = p->normal_prio = p->static_prio;
3439 		set_load_weight(p);
3440 
3441 #ifdef CONFIG_SCHED_LATENCY_NICE
3442 		p->latency_prio = NICE_TO_LATENCY(0);
3443 		set_latency_weight(p);
3444 #endif
3445 
3446 		/*
3447 		 * We don't need the reset flag anymore after the fork. It has
3448 		 * fulfilled its duty:
3449 		 */
3450 		p->sched_reset_on_fork = 0;
3451 	}
3452 
3453 	if (dl_prio(p->prio))
3454 		return -EAGAIN;
3455 	else if (rt_prio(p->prio))
3456 		p->sched_class = &rt_sched_class;
3457 	else
3458 		p->sched_class = &fair_sched_class;
3459 
3460 	init_entity_runnable_average(&p->se);
3461 
3462 #ifdef CONFIG_SCHED_INFO
3463 	if (likely(sched_info_on()))
3464 		memset(&p->sched_info, 0, sizeof(p->sched_info));
3465 #endif
3466 #if defined(CONFIG_SMP)
3467 	p->on_cpu = 0;
3468 #endif
3469 	init_task_preempt_count(p);
3470 #ifdef CONFIG_SMP
3471 	plist_node_init(&p->pushable_tasks, MAX_PRIO);
3472 	RB_CLEAR_NODE(&p->pushable_dl_tasks);
3473 #endif
3474 	return 0;
3475 }
3476 
sched_post_fork(struct task_struct * p,struct kernel_clone_args * kargs)3477 void sched_post_fork(struct task_struct *p, struct kernel_clone_args *kargs)
3478 {
3479 	unsigned long flags;
3480 #ifdef CONFIG_CGROUP_SCHED
3481 	struct task_group *tg;
3482 #endif
3483 
3484 	raw_spin_lock_irqsave(&p->pi_lock, flags);
3485 #ifdef CONFIG_CGROUP_SCHED
3486 	tg = container_of(kargs->cset->subsys[cpu_cgrp_id],
3487 			  struct task_group, css);
3488 	p->sched_task_group = autogroup_task_group(p, tg);
3489 #endif
3490 	rseq_migrate(p);
3491 	/*
3492 	 * We're setting the CPU for the first time, we don't migrate,
3493 	 * so use __set_task_cpu().
3494 	 */
3495 	__set_task_cpu(p, smp_processor_id());
3496 	if (p->sched_class->task_fork)
3497 		p->sched_class->task_fork(p);
3498 	raw_spin_unlock_irqrestore(&p->pi_lock, flags);
3499 
3500 	uclamp_post_fork(p);
3501 }
3502 
to_ratio(u64 period,u64 runtime)3503 unsigned long to_ratio(u64 period, u64 runtime)
3504 {
3505 	if (runtime == RUNTIME_INF)
3506 		return BW_UNIT;
3507 
3508 	/*
3509 	 * Doing this here saves a lot of checks in all
3510 	 * the calling paths, and returning zero seems
3511 	 * safe for them anyway.
3512 	 */
3513 	if (period == 0)
3514 		return 0;
3515 
3516 	return div64_u64(runtime << BW_SHIFT, period);
3517 }
3518 
3519 /*
3520  * wake_up_new_task - wake up a newly created task for the first time.
3521  *
3522  * This function will do some initial scheduler statistics housekeeping
3523  * that must be done for every newly created context, then puts the task
3524  * on the runqueue and wakes it.
3525  */
wake_up_new_task(struct task_struct * p)3526 void wake_up_new_task(struct task_struct *p)
3527 {
3528 	struct rq_flags rf;
3529 	struct rq *rq;
3530 
3531 	raw_spin_lock_irqsave(&p->pi_lock, rf.flags);
3532 	add_new_task_to_grp(p);
3533 
3534 	p->state = TASK_RUNNING;
3535 #ifdef CONFIG_SMP
3536 	/*
3537 	 * Fork balancing, do it here and not earlier because:
3538 	 *  - cpus_ptr can change in the fork path
3539 	 *  - any previously selected CPU might disappear through hotplug
3540 	 *
3541 	 * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq,
3542 	 * as we're not fully set-up yet.
3543 	 */
3544 	p->recent_used_cpu = task_cpu(p);
3545 	rseq_migrate(p);
3546 	__set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0));
3547 #endif
3548 	rq = __task_rq_lock(p, &rf);
3549 	update_rq_clock(rq);
3550 	post_init_entity_util_avg(p);
3551 
3552 	mark_task_starting(p);
3553 
3554 	activate_task(rq, p, ENQUEUE_NOCLOCK);
3555 	trace_sched_wakeup_new(p);
3556 	check_preempt_curr(rq, p, WF_FORK);
3557 #ifdef CONFIG_SMP
3558 	if (p->sched_class->task_woken) {
3559 		/*
3560 		 * Nothing relies on rq->lock after this, so its fine to
3561 		 * drop it.
3562 		 */
3563 		rq_unpin_lock(rq, &rf);
3564 		p->sched_class->task_woken(rq, p);
3565 		rq_repin_lock(rq, &rf);
3566 	}
3567 #endif
3568 	task_rq_unlock(rq, p, &rf);
3569 }
3570 
3571 #ifdef CONFIG_PREEMPT_NOTIFIERS
3572 
3573 static DEFINE_STATIC_KEY_FALSE(preempt_notifier_key);
3574 
preempt_notifier_inc(void)3575 void preempt_notifier_inc(void)
3576 {
3577 	static_branch_inc(&preempt_notifier_key);
3578 }
3579 EXPORT_SYMBOL_GPL(preempt_notifier_inc);
3580 
preempt_notifier_dec(void)3581 void preempt_notifier_dec(void)
3582 {
3583 	static_branch_dec(&preempt_notifier_key);
3584 }
3585 EXPORT_SYMBOL_GPL(preempt_notifier_dec);
3586 
3587 /**
3588  * preempt_notifier_register - tell me when current is being preempted & rescheduled
3589  * @notifier: notifier struct to register
3590  */
preempt_notifier_register(struct preempt_notifier * notifier)3591 void preempt_notifier_register(struct preempt_notifier *notifier)
3592 {
3593 	if (!static_branch_unlikely(&preempt_notifier_key))
3594 		WARN(1, "registering preempt_notifier while notifiers disabled\n");
3595 
3596 	hlist_add_head(&notifier->link, &current->preempt_notifiers);
3597 }
3598 EXPORT_SYMBOL_GPL(preempt_notifier_register);
3599 
3600 /**
3601  * preempt_notifier_unregister - no longer interested in preemption notifications
3602  * @notifier: notifier struct to unregister
3603  *
3604  * This is *not* safe to call from within a preemption notifier.
3605  */
preempt_notifier_unregister(struct preempt_notifier * notifier)3606 void preempt_notifier_unregister(struct preempt_notifier *notifier)
3607 {
3608 	hlist_del(&notifier->link);
3609 }
3610 EXPORT_SYMBOL_GPL(preempt_notifier_unregister);
3611 
__fire_sched_in_preempt_notifiers(struct task_struct * curr)3612 static void __fire_sched_in_preempt_notifiers(struct task_struct *curr)
3613 {
3614 	struct preempt_notifier *notifier;
3615 
3616 	hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
3617 		notifier->ops->sched_in(notifier, raw_smp_processor_id());
3618 }
3619 
fire_sched_in_preempt_notifiers(struct task_struct * curr)3620 static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
3621 {
3622 	if (static_branch_unlikely(&preempt_notifier_key))
3623 		__fire_sched_in_preempt_notifiers(curr);
3624 }
3625 
3626 static void
__fire_sched_out_preempt_notifiers(struct task_struct * curr,struct task_struct * next)3627 __fire_sched_out_preempt_notifiers(struct task_struct *curr,
3628 				   struct task_struct *next)
3629 {
3630 	struct preempt_notifier *notifier;
3631 
3632 	hlist_for_each_entry(notifier, &curr->preempt_notifiers, link)
3633 		notifier->ops->sched_out(notifier, next);
3634 }
3635 
3636 static __always_inline void
fire_sched_out_preempt_notifiers(struct task_struct * curr,struct task_struct * next)3637 fire_sched_out_preempt_notifiers(struct task_struct *curr,
3638 				 struct task_struct *next)
3639 {
3640 	if (static_branch_unlikely(&preempt_notifier_key))
3641 		__fire_sched_out_preempt_notifiers(curr, next);
3642 }
3643 
3644 #else /* !CONFIG_PREEMPT_NOTIFIERS */
3645 
fire_sched_in_preempt_notifiers(struct task_struct * curr)3646 static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr)
3647 {
3648 }
3649 
3650 static inline void
fire_sched_out_preempt_notifiers(struct task_struct * curr,struct task_struct * next)3651 fire_sched_out_preempt_notifiers(struct task_struct *curr,
3652 				 struct task_struct *next)
3653 {
3654 }
3655 
3656 #endif /* CONFIG_PREEMPT_NOTIFIERS */
3657 
prepare_task(struct task_struct * next)3658 static inline void prepare_task(struct task_struct *next)
3659 {
3660 #ifdef CONFIG_SMP
3661 	/*
3662 	 * Claim the task as running, we do this before switching to it
3663 	 * such that any running task will have this set.
3664 	 *
3665 	 * See the ttwu() WF_ON_CPU case and its ordering comment.
3666 	 */
3667 	WRITE_ONCE(next->on_cpu, 1);
3668 #endif
3669 }
3670 
finish_task(struct task_struct * prev)3671 static inline void finish_task(struct task_struct *prev)
3672 {
3673 #ifdef CONFIG_SMP
3674 	/*
3675 	 * This must be the very last reference to @prev from this CPU. After
3676 	 * p->on_cpu is cleared, the task can be moved to a different CPU. We
3677 	 * must ensure this doesn't happen until the switch is completely
3678 	 * finished.
3679 	 *
3680 	 * In particular, the load of prev->state in finish_task_switch() must
3681 	 * happen before this.
3682 	 *
3683 	 * Pairs with the smp_cond_load_acquire() in try_to_wake_up().
3684 	 */
3685 	smp_store_release(&prev->on_cpu, 0);
3686 #endif
3687 }
3688 
3689 static inline void
prepare_lock_switch(struct rq * rq,struct task_struct * next,struct rq_flags * rf)3690 prepare_lock_switch(struct rq *rq, struct task_struct *next, struct rq_flags *rf)
3691 {
3692 	/*
3693 	 * Since the runqueue lock will be released by the next
3694 	 * task (which is an invalid locking op but in the case
3695 	 * of the scheduler it's an obvious special-case), so we
3696 	 * do an early lockdep release here:
3697 	 */
3698 	rq_unpin_lock(rq, rf);
3699 	spin_release(&rq->lock.dep_map, _THIS_IP_);
3700 #ifdef CONFIG_DEBUG_SPINLOCK
3701 	/* this is a valid case when another task releases the spinlock */
3702 	rq->lock.owner = next;
3703 #endif
3704 }
3705 
finish_lock_switch(struct rq * rq)3706 static inline void finish_lock_switch(struct rq *rq)
3707 {
3708 	/*
3709 	 * If we are tracking spinlock dependencies then we have to
3710 	 * fix up the runqueue lock - which gets 'carried over' from
3711 	 * prev into current:
3712 	 */
3713 	spin_acquire(&rq->lock.dep_map, 0, 0, _THIS_IP_);
3714 	raw_spin_unlock_irq(&rq->lock);
3715 }
3716 
3717 /*
3718  * NOP if the arch has not defined these:
3719  */
3720 
3721 #ifndef prepare_arch_switch
3722 # define prepare_arch_switch(next)	do { } while (0)
3723 #endif
3724 
3725 #ifndef finish_arch_post_lock_switch
3726 # define finish_arch_post_lock_switch()	do { } while (0)
3727 #endif
3728 
3729 /**
3730  * prepare_task_switch - prepare to switch tasks
3731  * @rq: the runqueue preparing to switch
3732  * @prev: the current task that is being switched out
3733  * @next: the task we are going to switch to.
3734  *
3735  * This is called with the rq lock held and interrupts off. It must
3736  * be paired with a subsequent finish_task_switch after the context
3737  * switch.
3738  *
3739  * prepare_task_switch sets up locking and calls architecture specific
3740  * hooks.
3741  */
3742 static inline void
prepare_task_switch(struct rq * rq,struct task_struct * prev,struct task_struct * next)3743 prepare_task_switch(struct rq *rq, struct task_struct *prev,
3744 		    struct task_struct *next)
3745 {
3746 	kcov_prepare_switch(prev);
3747 	sched_info_switch(rq, prev, next);
3748 	perf_event_task_sched_out(prev, next);
3749 	rseq_preempt(prev);
3750 	fire_sched_out_preempt_notifiers(prev, next);
3751 	prepare_task(next);
3752 	prepare_arch_switch(next);
3753 }
3754 
3755 /**
3756  * finish_task_switch - clean up after a task-switch
3757  * @prev: the thread we just switched away from.
3758  *
3759  * finish_task_switch must be called after the context switch, paired
3760  * with a prepare_task_switch call before the context switch.
3761  * finish_task_switch will reconcile locking set up by prepare_task_switch,
3762  * and do any other architecture-specific cleanup actions.
3763  *
3764  * Note that we may have delayed dropping an mm in context_switch(). If
3765  * so, we finish that here outside of the runqueue lock. (Doing it
3766  * with the lock held can cause deadlocks; see schedule() for
3767  * details.)
3768  *
3769  * The context switch have flipped the stack from under us and restored the
3770  * local variables which were saved when this task called schedule() in the
3771  * past. prev == current is still correct but we need to recalculate this_rq
3772  * because prev may have moved to another CPU.
3773  */
finish_task_switch(struct task_struct * prev)3774 static struct rq *finish_task_switch(struct task_struct *prev)
3775 	__releases(rq->lock)
3776 {
3777 	struct rq *rq = this_rq();
3778 	struct mm_struct *mm = rq->prev_mm;
3779 	long prev_state;
3780 
3781 	/*
3782 	 * The previous task will have left us with a preempt_count of 2
3783 	 * because it left us after:
3784 	 *
3785 	 *	schedule()
3786 	 *	  preempt_disable();			// 1
3787 	 *	  __schedule()
3788 	 *	    raw_spin_lock_irq(&rq->lock)	// 2
3789 	 *
3790 	 * Also, see FORK_PREEMPT_COUNT.
3791 	 */
3792 	if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET,
3793 		      "corrupted preempt_count: %s/%d/0x%x\n",
3794 		      current->comm, current->pid, preempt_count()))
3795 		preempt_count_set(FORK_PREEMPT_COUNT);
3796 
3797 	rq->prev_mm = NULL;
3798 
3799 	/*
3800 	 * A task struct has one reference for the use as "current".
3801 	 * If a task dies, then it sets TASK_DEAD in tsk->state and calls
3802 	 * schedule one last time. The schedule call will never return, and
3803 	 * the scheduled task must drop that reference.
3804 	 *
3805 	 * We must observe prev->state before clearing prev->on_cpu (in
3806 	 * finish_task), otherwise a concurrent wakeup can get prev
3807 	 * running on another CPU and we could rave with its RUNNING -> DEAD
3808 	 * transition, resulting in a double drop.
3809 	 */
3810 	prev_state = prev->state;
3811 	vtime_task_switch(prev);
3812 	perf_event_task_sched_in(prev, current);
3813 	finish_task(prev);
3814 	finish_lock_switch(rq);
3815 	finish_arch_post_lock_switch();
3816 	kcov_finish_switch(current);
3817 
3818 	fire_sched_in_preempt_notifiers(current);
3819 	/*
3820 	 * When switching through a kernel thread, the loop in
3821 	 * membarrier_{private,global}_expedited() may have observed that
3822 	 * kernel thread and not issued an IPI. It is therefore possible to
3823 	 * schedule between user->kernel->user threads without passing though
3824 	 * switch_mm(). Membarrier requires a barrier after storing to
3825 	 * rq->curr, before returning to userspace, so provide them here:
3826 	 *
3827 	 * - a full memory barrier for {PRIVATE,GLOBAL}_EXPEDITED, implicitly
3828 	 *   provided by mmdrop(),
3829 	 * - a sync_core for SYNC_CORE.
3830 	 */
3831 	if (mm) {
3832 		membarrier_mm_sync_core_before_usermode(mm);
3833 		mmdrop(mm);
3834 	}
3835 	if (unlikely(prev_state == TASK_DEAD)) {
3836 		if (prev->sched_class->task_dead)
3837 			prev->sched_class->task_dead(prev);
3838 
3839 		/*
3840 		 * Remove function-return probe instances associated with this
3841 		 * task and put them back on the free list.
3842 		 */
3843 		kprobe_flush_task(prev);
3844 
3845 		/* Task is done with its stack. */
3846 		put_task_stack(prev);
3847 
3848 		put_task_struct_rcu_user(prev);
3849 	}
3850 
3851 	tick_nohz_task_switch();
3852 	return rq;
3853 }
3854 
3855 #ifdef CONFIG_SMP
3856 
3857 /* rq->lock is NOT held, but preemption is disabled */
__balance_callback(struct rq * rq)3858 static void __balance_callback(struct rq *rq)
3859 {
3860 	struct callback_head *head, *next;
3861 	void (*func)(struct rq *rq);
3862 	unsigned long flags;
3863 
3864 	raw_spin_lock_irqsave(&rq->lock, flags);
3865 	head = rq->balance_callback;
3866 	rq->balance_callback = NULL;
3867 	while (head) {
3868 		func = (void (*)(struct rq *))head->func;
3869 		next = head->next;
3870 		head->next = NULL;
3871 		head = next;
3872 
3873 		func(rq);
3874 	}
3875 	raw_spin_unlock_irqrestore(&rq->lock, flags);
3876 }
3877 
balance_callback(struct rq * rq)3878 static inline void balance_callback(struct rq *rq)
3879 {
3880 	if (unlikely(rq->balance_callback))
3881 		__balance_callback(rq);
3882 }
3883 
3884 #else
3885 
balance_callback(struct rq * rq)3886 static inline void balance_callback(struct rq *rq)
3887 {
3888 }
3889 
3890 #endif
3891 
3892 /**
3893  * schedule_tail - first thing a freshly forked thread must call.
3894  * @prev: the thread we just switched away from.
3895  */
schedule_tail(struct task_struct * prev)3896 asmlinkage __visible void schedule_tail(struct task_struct *prev)
3897 	__releases(rq->lock)
3898 {
3899 	struct rq *rq;
3900 
3901 	/*
3902 	 * New tasks start with FORK_PREEMPT_COUNT, see there and
3903 	 * finish_task_switch() for details.
3904 	 *
3905 	 * finish_task_switch() will drop rq->lock() and lower preempt_count
3906 	 * and the preempt_enable() will end up enabling preemption (on
3907 	 * PREEMPT_COUNT kernels).
3908 	 */
3909 
3910 	rq = finish_task_switch(prev);
3911 	balance_callback(rq);
3912 	preempt_enable();
3913 
3914 	if (current->set_child_tid)
3915 		put_user(task_pid_vnr(current), current->set_child_tid);
3916 
3917 	calculate_sigpending();
3918 }
3919 
3920 /*
3921  * context_switch - switch to the new MM and the new thread's register state.
3922  */
3923 static __always_inline struct rq *
context_switch(struct rq * rq,struct task_struct * prev,struct task_struct * next,struct rq_flags * rf)3924 context_switch(struct rq *rq, struct task_struct *prev,
3925 	       struct task_struct *next, struct rq_flags *rf)
3926 {
3927 	prepare_task_switch(rq, prev, next);
3928 
3929 	/*
3930 	 * For paravirt, this is coupled with an exit in switch_to to
3931 	 * combine the page table reload and the switch backend into
3932 	 * one hypercall.
3933 	 */
3934 	arch_start_context_switch(prev);
3935 
3936 	/*
3937 	 * kernel -> kernel   lazy + transfer active
3938 	 *   user -> kernel   lazy + mmgrab() active
3939 	 *
3940 	 * kernel ->   user   switch + mmdrop() active
3941 	 *   user ->   user   switch
3942 	 */
3943 	if (!next->mm) {                                // to kernel
3944 		enter_lazy_tlb(prev->active_mm, next);
3945 
3946 		next->active_mm = prev->active_mm;
3947 		if (prev->mm)                           // from user
3948 			mmgrab(prev->active_mm);
3949 		else
3950 			prev->active_mm = NULL;
3951 	} else {                                        // to user
3952 		membarrier_switch_mm(rq, prev->active_mm, next->mm);
3953 		/*
3954 		 * sys_membarrier() requires an smp_mb() between setting
3955 		 * rq->curr / membarrier_switch_mm() and returning to userspace.
3956 		 *
3957 		 * The below provides this either through switch_mm(), or in
3958 		 * case 'prev->active_mm == next->mm' through
3959 		 * finish_task_switch()'s mmdrop().
3960 		 */
3961 		switch_mm_irqs_off(prev->active_mm, next->mm, next);
3962 
3963 		if (!prev->mm) {                        // from kernel
3964 			/* will mmdrop() in finish_task_switch(). */
3965 			rq->prev_mm = prev->active_mm;
3966 			prev->active_mm = NULL;
3967 		}
3968 	}
3969 
3970 	rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
3971 
3972 	prepare_lock_switch(rq, next, rf);
3973 
3974 	/* Here we just switch the register state and the stack. */
3975 	switch_to(prev, next, prev);
3976 	barrier();
3977 
3978 	return finish_task_switch(prev);
3979 }
3980 
3981 /*
3982  * nr_running and nr_context_switches:
3983  *
3984  * externally visible scheduler statistics: current number of runnable
3985  * threads, total number of context switches performed since bootup.
3986  */
nr_running(void)3987 unsigned long nr_running(void)
3988 {
3989 	unsigned long i, sum = 0;
3990 
3991 	for_each_online_cpu(i)
3992 		sum += cpu_rq(i)->nr_running;
3993 
3994 	return sum;
3995 }
3996 
3997 /*
3998  * Check if only the current task is running on the CPU.
3999  *
4000  * Caution: this function does not check that the caller has disabled
4001  * preemption, thus the result might have a time-of-check-to-time-of-use
4002  * race.  The caller is responsible to use it correctly, for example:
4003  *
4004  * - from a non-preemptible section (of course)
4005  *
4006  * - from a thread that is bound to a single CPU
4007  *
4008  * - in a loop with very short iterations (e.g. a polling loop)
4009  */
single_task_running(void)4010 bool single_task_running(void)
4011 {
4012 	return raw_rq()->nr_running == 1;
4013 }
4014 EXPORT_SYMBOL(single_task_running);
4015 
nr_context_switches(void)4016 unsigned long long nr_context_switches(void)
4017 {
4018 	int i;
4019 	unsigned long long sum = 0;
4020 
4021 	for_each_possible_cpu(i)
4022 		sum += cpu_rq(i)->nr_switches;
4023 
4024 	return sum;
4025 }
4026 
4027 /*
4028  * Consumers of these two interfaces, like for example the cpuidle menu
4029  * governor, are using nonsensical data. Preferring shallow idle state selection
4030  * for a CPU that has IO-wait which might not even end up running the task when
4031  * it does become runnable.
4032  */
4033 
nr_iowait_cpu(int cpu)4034 unsigned long nr_iowait_cpu(int cpu)
4035 {
4036 	return atomic_read(&cpu_rq(cpu)->nr_iowait);
4037 }
4038 
4039 /*
4040  * IO-wait accounting, and how its mostly bollocks (on SMP).
4041  *
4042  * The idea behind IO-wait account is to account the idle time that we could
4043  * have spend running if it were not for IO. That is, if we were to improve the
4044  * storage performance, we'd have a proportional reduction in IO-wait time.
4045  *
4046  * This all works nicely on UP, where, when a task blocks on IO, we account
4047  * idle time as IO-wait, because if the storage were faster, it could've been
4048  * running and we'd not be idle.
4049  *
4050  * This has been extended to SMP, by doing the same for each CPU. This however
4051  * is broken.
4052  *
4053  * Imagine for instance the case where two tasks block on one CPU, only the one
4054  * CPU will have IO-wait accounted, while the other has regular idle. Even
4055  * though, if the storage were faster, both could've ran at the same time,
4056  * utilising both CPUs.
4057  *
4058  * This means, that when looking globally, the current IO-wait accounting on
4059  * SMP is a lower bound, by reason of under accounting.
4060  *
4061  * Worse, since the numbers are provided per CPU, they are sometimes
4062  * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly
4063  * associated with any one particular CPU, it can wake to another CPU than it
4064  * blocked on. This means the per CPU IO-wait number is meaningless.
4065  *
4066  * Task CPU affinities can make all that even more 'interesting'.
4067  */
4068 
nr_iowait(void)4069 unsigned long nr_iowait(void)
4070 {
4071 	unsigned long i, sum = 0;
4072 
4073 	for_each_possible_cpu(i)
4074 		sum += nr_iowait_cpu(i);
4075 
4076 	return sum;
4077 }
4078 
4079 #ifdef CONFIG_SMP
4080 
4081 /*
4082  * sched_exec - execve() is a valuable balancing opportunity, because at
4083  * this point the task has the smallest effective memory and cache footprint.
4084  */
sched_exec(void)4085 void sched_exec(void)
4086 {
4087 	struct task_struct *p = current;
4088 	unsigned long flags;
4089 	int dest_cpu;
4090 
4091 	raw_spin_lock_irqsave(&p->pi_lock, flags);
4092 	dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0);
4093 	if (dest_cpu == smp_processor_id())
4094 		goto unlock;
4095 
4096 	if (likely(cpu_active(dest_cpu) && likely(!cpu_isolated(dest_cpu)))) {
4097 		struct migration_arg arg = { p, dest_cpu };
4098 
4099 		raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4100 		stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg);
4101 		return;
4102 	}
4103 unlock:
4104 	raw_spin_unlock_irqrestore(&p->pi_lock, flags);
4105 }
4106 
4107 #endif
4108 
4109 DEFINE_PER_CPU(struct kernel_stat, kstat);
4110 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat);
4111 
4112 EXPORT_PER_CPU_SYMBOL(kstat);
4113 EXPORT_PER_CPU_SYMBOL(kernel_cpustat);
4114 
4115 /*
4116  * The function fair_sched_class.update_curr accesses the struct curr
4117  * and its field curr->exec_start; when called from task_sched_runtime(),
4118  * we observe a high rate of cache misses in practice.
4119  * Prefetching this data results in improved performance.
4120  */
prefetch_curr_exec_start(struct task_struct * p)4121 static inline void prefetch_curr_exec_start(struct task_struct *p)
4122 {
4123 #ifdef CONFIG_FAIR_GROUP_SCHED
4124 	struct sched_entity *curr = (&p->se)->cfs_rq->curr;
4125 #else
4126 	struct sched_entity *curr = (&task_rq(p)->cfs)->curr;
4127 #endif
4128 	prefetch(curr);
4129 	prefetch(&curr->exec_start);
4130 }
4131 
4132 /*
4133  * Return accounted runtime for the task.
4134  * In case the task is currently running, return the runtime plus current's
4135  * pending runtime that have not been accounted yet.
4136  */
task_sched_runtime(struct task_struct * p)4137 unsigned long long task_sched_runtime(struct task_struct *p)
4138 {
4139 	struct rq_flags rf;
4140 	struct rq *rq;
4141 	u64 ns;
4142 
4143 #if defined(CONFIG_64BIT) && defined(CONFIG_SMP)
4144 	/*
4145 	 * 64-bit doesn't need locks to atomically read a 64-bit value.
4146 	 * So we have a optimization chance when the task's delta_exec is 0.
4147 	 * Reading ->on_cpu is racy, but this is ok.
4148 	 *
4149 	 * If we race with it leaving CPU, we'll take a lock. So we're correct.
4150 	 * If we race with it entering CPU, unaccounted time is 0. This is
4151 	 * indistinguishable from the read occurring a few cycles earlier.
4152 	 * If we see ->on_cpu without ->on_rq, the task is leaving, and has
4153 	 * been accounted, so we're correct here as well.
4154 	 */
4155 	if (!p->on_cpu || !task_on_rq_queued(p))
4156 		return p->se.sum_exec_runtime;
4157 #endif
4158 
4159 	rq = task_rq_lock(p, &rf);
4160 	/*
4161 	 * Must be ->curr _and_ ->on_rq.  If dequeued, we would
4162 	 * project cycles that may never be accounted to this
4163 	 * thread, breaking clock_gettime().
4164 	 */
4165 	if (task_current(rq, p) && task_on_rq_queued(p)) {
4166 		prefetch_curr_exec_start(p);
4167 		update_rq_clock(rq);
4168 		p->sched_class->update_curr(rq);
4169 	}
4170 	ns = p->se.sum_exec_runtime;
4171 	task_rq_unlock(rq, p, &rf);
4172 
4173 	return ns;
4174 }
4175 
4176 /*
4177  * This function gets called by the timer code, with HZ frequency.
4178  * We call it with interrupts disabled.
4179  */
scheduler_tick(void)4180 void scheduler_tick(void)
4181 {
4182 	int cpu = smp_processor_id();
4183 	struct rq *rq = cpu_rq(cpu);
4184 	struct task_struct *curr = rq->curr;
4185 	struct rq_flags rf;
4186 	u64 wallclock;
4187 	unsigned long thermal_pressure;
4188 
4189 	arch_scale_freq_tick();
4190 	sched_clock_tick();
4191 
4192 	rq_lock(rq, &rf);
4193 
4194 	set_window_start(rq);
4195 	wallclock = sched_ktime_clock();
4196 	update_task_ravg(rq->curr, rq, TASK_UPDATE, wallclock, 0);
4197 	update_rq_clock(rq);
4198 	thermal_pressure = arch_scale_thermal_pressure(cpu_of(rq));
4199 	update_thermal_load_avg(rq_clock_thermal(rq), rq, thermal_pressure);
4200 	curr->sched_class->task_tick(rq, curr, 0);
4201 	calc_global_load_tick(rq);
4202 	psi_task_tick(rq);
4203 
4204 	rq_unlock(rq, &rf);
4205 
4206 #ifdef CONFIG_SCHED_RTG
4207 	sched_update_rtg_tick(curr);
4208 #endif
4209 	perf_event_task_tick();
4210 
4211 #ifdef CONFIG_SMP
4212 	rq->idle_balance = idle_cpu(cpu);
4213 	trigger_load_balance(rq);
4214 
4215 #ifdef CONFIG_SCHED_EAS
4216 	if (curr->sched_class->check_for_migration)
4217 		curr->sched_class->check_for_migration(rq, curr);
4218 #endif
4219 #endif
4220 }
4221 
4222 #ifdef CONFIG_NO_HZ_FULL
4223 
4224 struct tick_work {
4225 	int			cpu;
4226 	atomic_t		state;
4227 	struct delayed_work	work;
4228 };
4229 /* Values for ->state, see diagram below. */
4230 #define TICK_SCHED_REMOTE_OFFLINE	0
4231 #define TICK_SCHED_REMOTE_OFFLINING	1
4232 #define TICK_SCHED_REMOTE_RUNNING	2
4233 
4234 /*
4235  * State diagram for ->state:
4236  *
4237  *
4238  *          TICK_SCHED_REMOTE_OFFLINE
4239  *                    |   ^
4240  *                    |   |
4241  *                    |   | sched_tick_remote()
4242  *                    |   |
4243  *                    |   |
4244  *                    +--TICK_SCHED_REMOTE_OFFLINING
4245  *                    |   ^
4246  *                    |   |
4247  * sched_tick_start() |   | sched_tick_stop()
4248  *                    |   |
4249  *                    V   |
4250  *          TICK_SCHED_REMOTE_RUNNING
4251  *
4252  *
4253  * Other transitions get WARN_ON_ONCE(), except that sched_tick_remote()
4254  * and sched_tick_start() are happy to leave the state in RUNNING.
4255  */
4256 
4257 static struct tick_work __percpu *tick_work_cpu;
4258 
sched_tick_remote(struct work_struct * work)4259 static void sched_tick_remote(struct work_struct *work)
4260 {
4261 	struct delayed_work *dwork = to_delayed_work(work);
4262 	struct tick_work *twork = container_of(dwork, struct tick_work, work);
4263 	int cpu = twork->cpu;
4264 	struct rq *rq = cpu_rq(cpu);
4265 	struct task_struct *curr;
4266 	struct rq_flags rf;
4267 	u64 delta;
4268 	int os;
4269 
4270 	/*
4271 	 * Handle the tick only if it appears the remote CPU is running in full
4272 	 * dynticks mode. The check is racy by nature, but missing a tick or
4273 	 * having one too much is no big deal because the scheduler tick updates
4274 	 * statistics and checks timeslices in a time-independent way, regardless
4275 	 * of when exactly it is running.
4276 	 */
4277 	if (!tick_nohz_tick_stopped_cpu(cpu))
4278 		goto out_requeue;
4279 
4280 	rq_lock_irq(rq, &rf);
4281 	curr = rq->curr;
4282 	if (cpu_is_offline(cpu))
4283 		goto out_unlock;
4284 
4285 	update_rq_clock(rq);
4286 
4287 	if (!is_idle_task(curr)) {
4288 		/*
4289 		 * Make sure the next tick runs within a reasonable
4290 		 * amount of time.
4291 		 */
4292 		delta = rq_clock_task(rq) - curr->se.exec_start;
4293 		WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 3);
4294 	}
4295 	curr->sched_class->task_tick(rq, curr, 0);
4296 
4297 	calc_load_nohz_remote(rq);
4298 out_unlock:
4299 	rq_unlock_irq(rq, &rf);
4300 out_requeue:
4301 
4302 	/*
4303 	 * Run the remote tick once per second (1Hz). This arbitrary
4304 	 * frequency is large enough to avoid overload but short enough
4305 	 * to keep scheduler internal stats reasonably up to date.  But
4306 	 * first update state to reflect hotplug activity if required.
4307 	 */
4308 	os = atomic_fetch_add_unless(&twork->state, -1, TICK_SCHED_REMOTE_RUNNING);
4309 	WARN_ON_ONCE(os == TICK_SCHED_REMOTE_OFFLINE);
4310 	if (os == TICK_SCHED_REMOTE_RUNNING)
4311 		queue_delayed_work(system_unbound_wq, dwork, HZ);
4312 }
4313 
sched_tick_start(int cpu)4314 static void sched_tick_start(int cpu)
4315 {
4316 	int os;
4317 	struct tick_work *twork;
4318 
4319 	if (housekeeping_cpu(cpu, HK_FLAG_TICK))
4320 		return;
4321 
4322 	WARN_ON_ONCE(!tick_work_cpu);
4323 
4324 	twork = per_cpu_ptr(tick_work_cpu, cpu);
4325 	os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_RUNNING);
4326 	WARN_ON_ONCE(os == TICK_SCHED_REMOTE_RUNNING);
4327 	if (os == TICK_SCHED_REMOTE_OFFLINE) {
4328 		twork->cpu = cpu;
4329 		INIT_DELAYED_WORK(&twork->work, sched_tick_remote);
4330 		queue_delayed_work(system_unbound_wq, &twork->work, HZ);
4331 	}
4332 }
4333 
4334 #ifdef CONFIG_HOTPLUG_CPU
sched_tick_stop(int cpu)4335 static void sched_tick_stop(int cpu)
4336 {
4337 	struct tick_work *twork;
4338 	int os;
4339 
4340 	if (housekeeping_cpu(cpu, HK_FLAG_TICK))
4341 		return;
4342 
4343 	WARN_ON_ONCE(!tick_work_cpu);
4344 
4345 	twork = per_cpu_ptr(tick_work_cpu, cpu);
4346 	/* There cannot be competing actions, but don't rely on stop-machine. */
4347 	os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_OFFLINING);
4348 	WARN_ON_ONCE(os != TICK_SCHED_REMOTE_RUNNING);
4349 	/* Don't cancel, as this would mess up the state machine. */
4350 }
4351 #endif /* CONFIG_HOTPLUG_CPU */
4352 
sched_tick_offload_init(void)4353 int __init sched_tick_offload_init(void)
4354 {
4355 	tick_work_cpu = alloc_percpu(struct tick_work);
4356 	BUG_ON(!tick_work_cpu);
4357 	return 0;
4358 }
4359 
4360 #else /* !CONFIG_NO_HZ_FULL */
sched_tick_start(int cpu)4361 static inline void sched_tick_start(int cpu) { }
sched_tick_stop(int cpu)4362 static inline void sched_tick_stop(int cpu) { }
4363 #endif
4364 
4365 #if defined(CONFIG_PREEMPTION) && (defined(CONFIG_DEBUG_PREEMPT) || \
4366 				defined(CONFIG_TRACE_PREEMPT_TOGGLE))
4367 /*
4368  * If the value passed in is equal to the current preempt count
4369  * then we just disabled preemption. Start timing the latency.
4370  */
preempt_latency_start(int val)4371 static inline void preempt_latency_start(int val)
4372 {
4373 	if (preempt_count() == val) {
4374 		unsigned long ip = get_lock_parent_ip();
4375 #ifdef CONFIG_DEBUG_PREEMPT
4376 		current->preempt_disable_ip = ip;
4377 #endif
4378 		trace_preempt_off(CALLER_ADDR0, ip);
4379 	}
4380 }
4381 
preempt_count_add(int val)4382 void preempt_count_add(int val)
4383 {
4384 #ifdef CONFIG_DEBUG_PREEMPT
4385 	/*
4386 	 * Underflow?
4387 	 */
4388 	if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0)))
4389 		return;
4390 #endif
4391 	__preempt_count_add(val);
4392 #ifdef CONFIG_DEBUG_PREEMPT
4393 	/*
4394 	 * Spinlock count overflowing soon?
4395 	 */
4396 	DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >=
4397 				PREEMPT_MASK - 10);
4398 #endif
4399 	preempt_latency_start(val);
4400 }
4401 EXPORT_SYMBOL(preempt_count_add);
4402 NOKPROBE_SYMBOL(preempt_count_add);
4403 
4404 /*
4405  * If the value passed in equals to the current preempt count
4406  * then we just enabled preemption. Stop timing the latency.
4407  */
preempt_latency_stop(int val)4408 static inline void preempt_latency_stop(int val)
4409 {
4410 	if (preempt_count() == val)
4411 		trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip());
4412 }
4413 
preempt_count_sub(int val)4414 void preempt_count_sub(int val)
4415 {
4416 #ifdef CONFIG_DEBUG_PREEMPT
4417 	/*
4418 	 * Underflow?
4419 	 */
4420 	if (DEBUG_LOCKS_WARN_ON(val > preempt_count()))
4421 		return;
4422 	/*
4423 	 * Is the spinlock portion underflowing?
4424 	 */
4425 	if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) &&
4426 			!(preempt_count() & PREEMPT_MASK)))
4427 		return;
4428 #endif
4429 
4430 	preempt_latency_stop(val);
4431 	__preempt_count_sub(val);
4432 }
4433 EXPORT_SYMBOL(preempt_count_sub);
4434 NOKPROBE_SYMBOL(preempt_count_sub);
4435 
4436 #else
preempt_latency_start(int val)4437 static inline void preempt_latency_start(int val) { }
preempt_latency_stop(int val)4438 static inline void preempt_latency_stop(int val) { }
4439 #endif
4440 
get_preempt_disable_ip(struct task_struct * p)4441 static inline unsigned long get_preempt_disable_ip(struct task_struct *p)
4442 {
4443 #ifdef CONFIG_DEBUG_PREEMPT
4444 	return p->preempt_disable_ip;
4445 #else
4446 	return 0;
4447 #endif
4448 }
4449 
4450 /*
4451  * Print scheduling while atomic bug:
4452  */
__schedule_bug(struct task_struct * prev)4453 static noinline void __schedule_bug(struct task_struct *prev)
4454 {
4455 	/* Save this before calling printk(), since that will clobber it */
4456 	unsigned long preempt_disable_ip = get_preempt_disable_ip(current);
4457 
4458 	if (oops_in_progress)
4459 		return;
4460 
4461 	printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n",
4462 		prev->comm, prev->pid, preempt_count());
4463 
4464 	debug_show_held_locks(prev);
4465 	print_modules();
4466 	if (irqs_disabled())
4467 		print_irqtrace_events(prev);
4468 	if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
4469 	    && in_atomic_preempt_off()) {
4470 		pr_err("Preemption disabled at:");
4471 		print_ip_sym(KERN_ERR, preempt_disable_ip);
4472 	}
4473 	check_panic_on_warn("scheduling while atomic");
4474 
4475 	dump_stack();
4476 	add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
4477 }
4478 
4479 /*
4480  * Various schedule()-time debugging checks and statistics:
4481  */
schedule_debug(struct task_struct * prev,bool preempt)4482 static inline void schedule_debug(struct task_struct *prev, bool preempt)
4483 {
4484 #ifdef CONFIG_SCHED_STACK_END_CHECK
4485 	if (task_stack_end_corrupted(prev))
4486 		panic("corrupted stack end detected inside scheduler\n");
4487 
4488 	if (task_scs_end_corrupted(prev))
4489 		panic("corrupted shadow stack detected inside scheduler\n");
4490 #endif
4491 
4492 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
4493 	if (!preempt && prev->state && prev->non_block_count) {
4494 		printk(KERN_ERR "BUG: scheduling in a non-blocking section: %s/%d/%i\n",
4495 			prev->comm, prev->pid, prev->non_block_count);
4496 		dump_stack();
4497 		add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
4498 	}
4499 #endif
4500 
4501 	if (unlikely(in_atomic_preempt_off())) {
4502 		__schedule_bug(prev);
4503 		preempt_count_set(PREEMPT_DISABLED);
4504 	}
4505 	rcu_sleep_check();
4506 
4507 	profile_hit(SCHED_PROFILING, __builtin_return_address(0));
4508 
4509 	schedstat_inc(this_rq()->sched_count);
4510 }
4511 
put_prev_task_balance(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)4512 static void put_prev_task_balance(struct rq *rq, struct task_struct *prev,
4513 				  struct rq_flags *rf)
4514 {
4515 #ifdef CONFIG_SMP
4516 	const struct sched_class *class;
4517 	/*
4518 	 * We must do the balancing pass before put_prev_task(), such
4519 	 * that when we release the rq->lock the task is in the same
4520 	 * state as before we took rq->lock.
4521 	 *
4522 	 * We can terminate the balance pass as soon as we know there is
4523 	 * a runnable task of @class priority or higher.
4524 	 */
4525 	for_class_range(class, prev->sched_class, &idle_sched_class) {
4526 		if (class->balance(rq, prev, rf))
4527 			break;
4528 	}
4529 #endif
4530 
4531 	put_prev_task(rq, prev);
4532 }
4533 
4534 /*
4535  * Pick up the highest-prio task:
4536  */
4537 static inline struct task_struct *
pick_next_task(struct rq * rq,struct task_struct * prev,struct rq_flags * rf)4538 pick_next_task(struct rq *rq, struct task_struct *prev, struct rq_flags *rf)
4539 {
4540 	const struct sched_class *class;
4541 	struct task_struct *p;
4542 
4543 	/*
4544 	 * Optimization: we know that if all tasks are in the fair class we can
4545 	 * call that function directly, but only if the @prev task wasn't of a
4546 	 * higher scheduling class, because otherwise those loose the
4547 	 * opportunity to pull in more work from other CPUs.
4548 	 */
4549 	if (likely(prev->sched_class <= &fair_sched_class &&
4550 		   rq->nr_running == rq->cfs.h_nr_running)) {
4551 
4552 		p = pick_next_task_fair(rq, prev, rf);
4553 		if (unlikely(p == RETRY_TASK))
4554 			goto restart;
4555 
4556 		/* Assumes fair_sched_class->next == idle_sched_class */
4557 		if (!p) {
4558 			put_prev_task(rq, prev);
4559 			p = pick_next_task_idle(rq);
4560 		}
4561 
4562 		return p;
4563 	}
4564 
4565 restart:
4566 	put_prev_task_balance(rq, prev, rf);
4567 
4568 	for_each_class(class) {
4569 		p = class->pick_next_task(rq);
4570 		if (p)
4571 			return p;
4572 	}
4573 
4574 	/* The idle class should always have a runnable task: */
4575 	BUG();
4576 }
4577 
4578 /*
4579  * __schedule() is the main scheduler function.
4580  *
4581  * The main means of driving the scheduler and thus entering this function are:
4582  *
4583  *   1. Explicit blocking: mutex, semaphore, waitqueue, etc.
4584  *
4585  *   2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return
4586  *      paths. For example, see arch/x86/entry_64.S.
4587  *
4588  *      To drive preemption between tasks, the scheduler sets the flag in timer
4589  *      interrupt handler scheduler_tick().
4590  *
4591  *   3. Wakeups don't really cause entry into schedule(). They add a
4592  *      task to the run-queue and that's it.
4593  *
4594  *      Now, if the new task added to the run-queue preempts the current
4595  *      task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets
4596  *      called on the nearest possible occasion:
4597  *
4598  *       - If the kernel is preemptible (CONFIG_PREEMPTION=y):
4599  *
4600  *         - in syscall or exception context, at the next outmost
4601  *           preempt_enable(). (this might be as soon as the wake_up()'s
4602  *           spin_unlock()!)
4603  *
4604  *         - in IRQ context, return from interrupt-handler to
4605  *           preemptible context
4606  *
4607  *       - If the kernel is not preemptible (CONFIG_PREEMPTION is not set)
4608  *         then at the next:
4609  *
4610  *          - cond_resched() call
4611  *          - explicit schedule() call
4612  *          - return from syscall or exception to user-space
4613  *          - return from interrupt-handler to user-space
4614  *
4615  * WARNING: must be called with preemption disabled!
4616  */
__schedule(bool preempt)4617 static void __sched notrace __schedule(bool preempt)
4618 {
4619 	struct task_struct *prev, *next;
4620 	unsigned long *switch_count;
4621 	unsigned long prev_state;
4622 	struct rq_flags rf;
4623 	struct rq *rq;
4624 	int cpu;
4625 	u64 wallclock;
4626 
4627 	cpu = smp_processor_id();
4628 	rq = cpu_rq(cpu);
4629 	prev = rq->curr;
4630 
4631 	schedule_debug(prev, preempt);
4632 
4633 	if (sched_feat(HRTICK))
4634 		hrtick_clear(rq);
4635 
4636 	local_irq_disable();
4637 	rcu_note_context_switch(preempt);
4638 
4639 	/*
4640 	 * Make sure that signal_pending_state()->signal_pending() below
4641 	 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE)
4642 	 * done by the caller to avoid the race with signal_wake_up():
4643 	 *
4644 	 * __set_current_state(@state)		signal_wake_up()
4645 	 * schedule()				  set_tsk_thread_flag(p, TIF_SIGPENDING)
4646 	 *					  wake_up_state(p, state)
4647 	 *   LOCK rq->lock			    LOCK p->pi_state
4648 	 *   smp_mb__after_spinlock()		    smp_mb__after_spinlock()
4649 	 *     if (signal_pending_state())	    if (p->state & @state)
4650 	 *
4651 	 * Also, the membarrier system call requires a full memory barrier
4652 	 * after coming from user-space, before storing to rq->curr.
4653 	 */
4654 	rq_lock(rq, &rf);
4655 	smp_mb__after_spinlock();
4656 
4657 	/* Promote REQ to ACT */
4658 	rq->clock_update_flags <<= 1;
4659 	update_rq_clock(rq);
4660 
4661 	switch_count = &prev->nivcsw;
4662 
4663 	/*
4664 	 * We must load prev->state once (task_struct::state is volatile), such
4665 	 * that:
4666 	 *
4667 	 *  - we form a control dependency vs deactivate_task() below.
4668 	 *  - ptrace_{,un}freeze_traced() can change ->state underneath us.
4669 	 */
4670 	prev_state = prev->state;
4671 	if (!preempt && prev_state) {
4672 		if (signal_pending_state(prev_state, prev)) {
4673 			prev->state = TASK_RUNNING;
4674 		} else {
4675 			prev->sched_contributes_to_load =
4676 				(prev_state & TASK_UNINTERRUPTIBLE) &&
4677 				!(prev_state & TASK_NOLOAD) &&
4678 				!(prev->flags & PF_FROZEN);
4679 
4680 			if (prev->sched_contributes_to_load)
4681 				rq->nr_uninterruptible++;
4682 
4683 			/*
4684 			 * __schedule()			ttwu()
4685 			 *   prev_state = prev->state;    if (p->on_rq && ...)
4686 			 *   if (prev_state)		    goto out;
4687 			 *     p->on_rq = 0;		  smp_acquire__after_ctrl_dep();
4688 			 *				  p->state = TASK_WAKING
4689 			 *
4690 			 * Where __schedule() and ttwu() have matching control dependencies.
4691 			 *
4692 			 * After this, schedule() must not care about p->state any more.
4693 			 */
4694 			deactivate_task(rq, prev, DEQUEUE_SLEEP | DEQUEUE_NOCLOCK);
4695 
4696 			if (prev->in_iowait) {
4697 				atomic_inc(&rq->nr_iowait);
4698 				delayacct_blkio_start();
4699 			}
4700 		}
4701 		switch_count = &prev->nvcsw;
4702 	}
4703 
4704 	next = pick_next_task(rq, prev, &rf);
4705 	clear_tsk_need_resched(prev);
4706 	clear_preempt_need_resched();
4707 
4708 	wallclock = sched_ktime_clock();
4709 	if (likely(prev != next)) {
4710 #ifdef CONFIG_SCHED_WALT
4711 		if (!prev->on_rq)
4712 			prev->last_sleep_ts = wallclock;
4713 #endif
4714 		update_task_ravg(prev, rq, PUT_PREV_TASK, wallclock, 0);
4715 		update_task_ravg(next, rq, PICK_NEXT_TASK, wallclock, 0);
4716 		rq->nr_switches++;
4717 		/*
4718 		 * RCU users of rcu_dereference(rq->curr) may not see
4719 		 * changes to task_struct made by pick_next_task().
4720 		 */
4721 		RCU_INIT_POINTER(rq->curr, next);
4722 		/*
4723 		 * The membarrier system call requires each architecture
4724 		 * to have a full memory barrier after updating
4725 		 * rq->curr, before returning to user-space.
4726 		 *
4727 		 * Here are the schemes providing that barrier on the
4728 		 * various architectures:
4729 		 * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC.
4730 		 *   switch_mm() rely on membarrier_arch_switch_mm() on PowerPC.
4731 		 * - finish_lock_switch() for weakly-ordered
4732 		 *   architectures where spin_unlock is a full barrier,
4733 		 * - switch_to() for arm64 (weakly-ordered, spin_unlock
4734 		 *   is a RELEASE barrier),
4735 		 */
4736 		++*switch_count;
4737 
4738 		psi_sched_switch(prev, next, !task_on_rq_queued(prev));
4739 
4740 		trace_sched_switch(preempt, prev, next);
4741 
4742 		/* Also unlocks the rq: */
4743 		rq = context_switch(rq, prev, next, &rf);
4744 	} else {
4745 		update_task_ravg(prev, rq, TASK_UPDATE, wallclock, 0);
4746 		rq->clock_update_flags &= ~(RQCF_ACT_SKIP|RQCF_REQ_SKIP);
4747 		rq_unlock_irq(rq, &rf);
4748 	}
4749 
4750 	balance_callback(rq);
4751 }
4752 
do_task_dead(void)4753 void __noreturn do_task_dead(void)
4754 {
4755 	/* Causes final put_task_struct in finish_task_switch(): */
4756 	set_special_state(TASK_DEAD);
4757 
4758 	/* Tell freezer to ignore us: */
4759 	current->flags |= PF_NOFREEZE;
4760 
4761 	__schedule(false);
4762 	BUG();
4763 
4764 	/* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */
4765 	for (;;)
4766 		cpu_relax();
4767 }
4768 
sched_submit_work(struct task_struct * tsk)4769 static inline void sched_submit_work(struct task_struct *tsk)
4770 {
4771 	unsigned int task_flags;
4772 
4773 	if (!tsk->state)
4774 		return;
4775 
4776 	task_flags = tsk->flags;
4777 	/*
4778 	 * If a worker went to sleep, notify and ask workqueue whether
4779 	 * it wants to wake up a task to maintain concurrency.
4780 	 * As this function is called inside the schedule() context,
4781 	 * we disable preemption to avoid it calling schedule() again
4782 	 * in the possible wakeup of a kworker and because wq_worker_sleeping()
4783 	 * requires it.
4784 	 */
4785 	if (task_flags & (PF_WQ_WORKER | PF_IO_WORKER)) {
4786 		preempt_disable();
4787 		if (task_flags & PF_WQ_WORKER)
4788 			wq_worker_sleeping(tsk);
4789 		else
4790 			io_wq_worker_sleeping(tsk);
4791 		preempt_enable_no_resched();
4792 	}
4793 
4794 	if (tsk_is_pi_blocked(tsk))
4795 		return;
4796 
4797 	/*
4798 	 * If we are going to sleep and we have plugged IO queued,
4799 	 * make sure to submit it to avoid deadlocks.
4800 	 */
4801 	if (blk_needs_flush_plug(tsk))
4802 		blk_schedule_flush_plug(tsk);
4803 }
4804 
sched_update_worker(struct task_struct * tsk)4805 static void sched_update_worker(struct task_struct *tsk)
4806 {
4807 	if (tsk->flags & (PF_WQ_WORKER | PF_IO_WORKER)) {
4808 		if (tsk->flags & PF_WQ_WORKER)
4809 			wq_worker_running(tsk);
4810 		else
4811 			io_wq_worker_running(tsk);
4812 	}
4813 }
4814 
schedule(void)4815 asmlinkage __visible void __sched schedule(void)
4816 {
4817 	struct task_struct *tsk = current;
4818 
4819 	sched_submit_work(tsk);
4820 	do {
4821 		preempt_disable();
4822 		__schedule(false);
4823 		sched_preempt_enable_no_resched();
4824 	} while (need_resched());
4825 	sched_update_worker(tsk);
4826 }
4827 EXPORT_SYMBOL(schedule);
4828 
4829 /*
4830  * synchronize_rcu_tasks() makes sure that no task is stuck in preempted
4831  * state (have scheduled out non-voluntarily) by making sure that all
4832  * tasks have either left the run queue or have gone into user space.
4833  * As idle tasks do not do either, they must not ever be preempted
4834  * (schedule out non-voluntarily).
4835  *
4836  * schedule_idle() is similar to schedule_preempt_disable() except that it
4837  * never enables preemption because it does not call sched_submit_work().
4838  */
schedule_idle(void)4839 void __sched schedule_idle(void)
4840 {
4841 	/*
4842 	 * As this skips calling sched_submit_work(), which the idle task does
4843 	 * regardless because that function is a nop when the task is in a
4844 	 * TASK_RUNNING state, make sure this isn't used someplace that the
4845 	 * current task can be in any other state. Note, idle is always in the
4846 	 * TASK_RUNNING state.
4847 	 */
4848 	WARN_ON_ONCE(current->state);
4849 	do {
4850 		__schedule(false);
4851 	} while (need_resched());
4852 }
4853 
4854 #ifdef CONFIG_CONTEXT_TRACKING
schedule_user(void)4855 asmlinkage __visible void __sched schedule_user(void)
4856 {
4857 	/*
4858 	 * If we come here after a random call to set_need_resched(),
4859 	 * or we have been woken up remotely but the IPI has not yet arrived,
4860 	 * we haven't yet exited the RCU idle mode. Do it here manually until
4861 	 * we find a better solution.
4862 	 *
4863 	 * NB: There are buggy callers of this function.  Ideally we
4864 	 * should warn if prev_state != CONTEXT_USER, but that will trigger
4865 	 * too frequently to make sense yet.
4866 	 */
4867 	enum ctx_state prev_state = exception_enter();
4868 	schedule();
4869 	exception_exit(prev_state);
4870 }
4871 #endif
4872 
4873 /**
4874  * schedule_preempt_disabled - called with preemption disabled
4875  *
4876  * Returns with preemption disabled. Note: preempt_count must be 1
4877  */
schedule_preempt_disabled(void)4878 void __sched schedule_preempt_disabled(void)
4879 {
4880 	sched_preempt_enable_no_resched();
4881 	schedule();
4882 	preempt_disable();
4883 }
4884 
preempt_schedule_common(void)4885 static void __sched notrace preempt_schedule_common(void)
4886 {
4887 	do {
4888 		/*
4889 		 * Because the function tracer can trace preempt_count_sub()
4890 		 * and it also uses preempt_enable/disable_notrace(), if
4891 		 * NEED_RESCHED is set, the preempt_enable_notrace() called
4892 		 * by the function tracer will call this function again and
4893 		 * cause infinite recursion.
4894 		 *
4895 		 * Preemption must be disabled here before the function
4896 		 * tracer can trace. Break up preempt_disable() into two
4897 		 * calls. One to disable preemption without fear of being
4898 		 * traced. The other to still record the preemption latency,
4899 		 * which can also be traced by the function tracer.
4900 		 */
4901 		preempt_disable_notrace();
4902 		preempt_latency_start(1);
4903 		__schedule(true);
4904 		preempt_latency_stop(1);
4905 		preempt_enable_no_resched_notrace();
4906 
4907 		/*
4908 		 * Check again in case we missed a preemption opportunity
4909 		 * between schedule and now.
4910 		 */
4911 	} while (need_resched());
4912 }
4913 
4914 #ifdef CONFIG_PREEMPTION
4915 /*
4916  * This is the entry point to schedule() from in-kernel preemption
4917  * off of preempt_enable.
4918  */
preempt_schedule(void)4919 asmlinkage __visible void __sched notrace preempt_schedule(void)
4920 {
4921 	/*
4922 	 * If there is a non-zero preempt_count or interrupts are disabled,
4923 	 * we do not want to preempt the current task. Just return..
4924 	 */
4925 	if (likely(!preemptible()))
4926 		return;
4927 
4928 	preempt_schedule_common();
4929 }
4930 NOKPROBE_SYMBOL(preempt_schedule);
4931 EXPORT_SYMBOL(preempt_schedule);
4932 
4933 /**
4934  * preempt_schedule_notrace - preempt_schedule called by tracing
4935  *
4936  * The tracing infrastructure uses preempt_enable_notrace to prevent
4937  * recursion and tracing preempt enabling caused by the tracing
4938  * infrastructure itself. But as tracing can happen in areas coming
4939  * from userspace or just about to enter userspace, a preempt enable
4940  * can occur before user_exit() is called. This will cause the scheduler
4941  * to be called when the system is still in usermode.
4942  *
4943  * To prevent this, the preempt_enable_notrace will use this function
4944  * instead of preempt_schedule() to exit user context if needed before
4945  * calling the scheduler.
4946  */
preempt_schedule_notrace(void)4947 asmlinkage __visible void __sched notrace preempt_schedule_notrace(void)
4948 {
4949 	enum ctx_state prev_ctx;
4950 
4951 	if (likely(!preemptible()))
4952 		return;
4953 
4954 	do {
4955 		/*
4956 		 * Because the function tracer can trace preempt_count_sub()
4957 		 * and it also uses preempt_enable/disable_notrace(), if
4958 		 * NEED_RESCHED is set, the preempt_enable_notrace() called
4959 		 * by the function tracer will call this function again and
4960 		 * cause infinite recursion.
4961 		 *
4962 		 * Preemption must be disabled here before the function
4963 		 * tracer can trace. Break up preempt_disable() into two
4964 		 * calls. One to disable preemption without fear of being
4965 		 * traced. The other to still record the preemption latency,
4966 		 * which can also be traced by the function tracer.
4967 		 */
4968 		preempt_disable_notrace();
4969 		preempt_latency_start(1);
4970 		/*
4971 		 * Needs preempt disabled in case user_exit() is traced
4972 		 * and the tracer calls preempt_enable_notrace() causing
4973 		 * an infinite recursion.
4974 		 */
4975 		prev_ctx = exception_enter();
4976 		__schedule(true);
4977 		exception_exit(prev_ctx);
4978 
4979 		preempt_latency_stop(1);
4980 		preempt_enable_no_resched_notrace();
4981 	} while (need_resched());
4982 }
4983 EXPORT_SYMBOL_GPL(preempt_schedule_notrace);
4984 
4985 #endif /* CONFIG_PREEMPTION */
4986 
4987 /*
4988  * This is the entry point to schedule() from kernel preemption
4989  * off of irq context.
4990  * Note, that this is called and return with irqs disabled. This will
4991  * protect us against recursive calling from irq.
4992  */
preempt_schedule_irq(void)4993 asmlinkage __visible void __sched preempt_schedule_irq(void)
4994 {
4995 	enum ctx_state prev_state;
4996 
4997 	/* Catch callers which need to be fixed */
4998 	BUG_ON(preempt_count() || !irqs_disabled());
4999 
5000 	prev_state = exception_enter();
5001 
5002 	do {
5003 		preempt_disable();
5004 		local_irq_enable();
5005 		__schedule(true);
5006 		local_irq_disable();
5007 		sched_preempt_enable_no_resched();
5008 	} while (need_resched());
5009 
5010 	exception_exit(prev_state);
5011 }
5012 
default_wake_function(wait_queue_entry_t * curr,unsigned mode,int wake_flags,void * key)5013 int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags,
5014 			  void *key)
5015 {
5016 	WARN_ON_ONCE(IS_ENABLED(CONFIG_SCHED_DEBUG) && wake_flags & ~WF_SYNC);
5017 	return try_to_wake_up(curr->private, mode, wake_flags);
5018 }
5019 EXPORT_SYMBOL(default_wake_function);
5020 
__setscheduler_prio(struct task_struct * p,int prio)5021 static void __setscheduler_prio(struct task_struct *p, int prio)
5022 {
5023 	if (dl_prio(prio))
5024 		p->sched_class = &dl_sched_class;
5025 	else if (rt_prio(prio))
5026 		p->sched_class = &rt_sched_class;
5027 	else
5028 		p->sched_class = &fair_sched_class;
5029 
5030 	p->prio = prio;
5031 }
5032 
5033 #ifdef CONFIG_RT_MUTEXES
5034 
__rt_effective_prio(struct task_struct * pi_task,int prio)5035 static inline int __rt_effective_prio(struct task_struct *pi_task, int prio)
5036 {
5037 	if (pi_task)
5038 		prio = min(prio, pi_task->prio);
5039 
5040 	return prio;
5041 }
5042 
rt_effective_prio(struct task_struct * p,int prio)5043 static inline int rt_effective_prio(struct task_struct *p, int prio)
5044 {
5045 	struct task_struct *pi_task = rt_mutex_get_top_task(p);
5046 
5047 	return __rt_effective_prio(pi_task, prio);
5048 }
5049 
5050 /*
5051  * rt_mutex_setprio - set the current priority of a task
5052  * @p: task to boost
5053  * @pi_task: donor task
5054  *
5055  * This function changes the 'effective' priority of a task. It does
5056  * not touch ->normal_prio like __setscheduler().
5057  *
5058  * Used by the rt_mutex code to implement priority inheritance
5059  * logic. Call site only calls if the priority of the task changed.
5060  */
rt_mutex_setprio(struct task_struct * p,struct task_struct * pi_task)5061 void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task)
5062 {
5063 	int prio, oldprio, queued, running, queue_flag =
5064 		DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
5065 	const struct sched_class *prev_class;
5066 	struct rq_flags rf;
5067 	struct rq *rq;
5068 
5069 	/* XXX used to be waiter->prio, not waiter->task->prio */
5070 	prio = __rt_effective_prio(pi_task, p->normal_prio);
5071 
5072 	/*
5073 	 * If nothing changed; bail early.
5074 	 */
5075 	if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio))
5076 		return;
5077 
5078 	rq = __task_rq_lock(p, &rf);
5079 	update_rq_clock(rq);
5080 	/*
5081 	 * Set under pi_lock && rq->lock, such that the value can be used under
5082 	 * either lock.
5083 	 *
5084 	 * Note that there is loads of tricky to make this pointer cache work
5085 	 * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to
5086 	 * ensure a task is de-boosted (pi_task is set to NULL) before the
5087 	 * task is allowed to run again (and can exit). This ensures the pointer
5088 	 * points to a blocked task -- which guaratees the task is present.
5089 	 */
5090 	p->pi_top_task = pi_task;
5091 
5092 	/*
5093 	 * For FIFO/RR we only need to set prio, if that matches we're done.
5094 	 */
5095 	if (prio == p->prio && !dl_prio(prio))
5096 		goto out_unlock;
5097 
5098 	/*
5099 	 * Idle task boosting is a nono in general. There is one
5100 	 * exception, when PREEMPT_RT and NOHZ is active:
5101 	 *
5102 	 * The idle task calls get_next_timer_interrupt() and holds
5103 	 * the timer wheel base->lock on the CPU and another CPU wants
5104 	 * to access the timer (probably to cancel it). We can safely
5105 	 * ignore the boosting request, as the idle CPU runs this code
5106 	 * with interrupts disabled and will complete the lock
5107 	 * protected section without being interrupted. So there is no
5108 	 * real need to boost.
5109 	 */
5110 	if (unlikely(p == rq->idle)) {
5111 		WARN_ON(p != rq->curr);
5112 		WARN_ON(p->pi_blocked_on);
5113 		goto out_unlock;
5114 	}
5115 
5116 	trace_sched_pi_setprio(p, pi_task);
5117 	oldprio = p->prio;
5118 
5119 	if (oldprio == prio)
5120 		queue_flag &= ~DEQUEUE_MOVE;
5121 
5122 	prev_class = p->sched_class;
5123 	queued = task_on_rq_queued(p);
5124 	running = task_current(rq, p);
5125 	if (queued)
5126 		dequeue_task(rq, p, queue_flag);
5127 	if (running)
5128 		put_prev_task(rq, p);
5129 
5130 	/*
5131 	 * Boosting condition are:
5132 	 * 1. -rt task is running and holds mutex A
5133 	 *      --> -dl task blocks on mutex A
5134 	 *
5135 	 * 2. -dl task is running and holds mutex A
5136 	 *      --> -dl task blocks on mutex A and could preempt the
5137 	 *          running task
5138 	 */
5139 	if (dl_prio(prio)) {
5140 		if (!dl_prio(p->normal_prio) ||
5141 		    (pi_task && dl_prio(pi_task->prio) &&
5142 		     dl_entity_preempt(&pi_task->dl, &p->dl))) {
5143 			p->dl.pi_se = pi_task->dl.pi_se;
5144 			queue_flag |= ENQUEUE_REPLENISH;
5145 		} else {
5146 			p->dl.pi_se = &p->dl;
5147 		}
5148 	} else if (rt_prio(prio)) {
5149 		if (dl_prio(oldprio))
5150 			p->dl.pi_se = &p->dl;
5151 		if (oldprio < prio)
5152 			queue_flag |= ENQUEUE_HEAD;
5153 	} else {
5154 		if (dl_prio(oldprio))
5155 			p->dl.pi_se = &p->dl;
5156 		if (rt_prio(oldprio))
5157 			p->rt.timeout = 0;
5158 	}
5159 
5160 	__setscheduler_prio(p, prio);
5161 
5162 	if (queued)
5163 		enqueue_task(rq, p, queue_flag);
5164 	if (running)
5165 		set_next_task(rq, p);
5166 
5167 	check_class_changed(rq, p, prev_class, oldprio);
5168 out_unlock:
5169 	/* Avoid rq from going away on us: */
5170 	preempt_disable();
5171 	__task_rq_unlock(rq, &rf);
5172 
5173 	balance_callback(rq);
5174 	preempt_enable();
5175 }
5176 #else
rt_effective_prio(struct task_struct * p,int prio)5177 static inline int rt_effective_prio(struct task_struct *p, int prio)
5178 {
5179 	return prio;
5180 }
5181 #endif
5182 
set_user_nice(struct task_struct * p,long nice)5183 void set_user_nice(struct task_struct *p, long nice)
5184 {
5185 	bool queued, running;
5186 	int old_prio;
5187 	struct rq_flags rf;
5188 	struct rq *rq;
5189 
5190 	if (task_nice(p) == nice || nice < MIN_NICE || nice > MAX_NICE)
5191 		return;
5192 	/*
5193 	 * We have to be careful, if called from sys_setpriority(),
5194 	 * the task might be in the middle of scheduling on another CPU.
5195 	 */
5196 	rq = task_rq_lock(p, &rf);
5197 	update_rq_clock(rq);
5198 
5199 	/*
5200 	 * The RT priorities are set via sched_setscheduler(), but we still
5201 	 * allow the 'normal' nice value to be set - but as expected
5202 	 * it wont have any effect on scheduling until the task is
5203 	 * SCHED_DEADLINE, SCHED_FIFO or SCHED_RR:
5204 	 */
5205 	if (task_has_dl_policy(p) || task_has_rt_policy(p)) {
5206 		p->static_prio = NICE_TO_PRIO(nice);
5207 		goto out_unlock;
5208 	}
5209 	queued = task_on_rq_queued(p);
5210 	running = task_current(rq, p);
5211 	if (queued)
5212 		dequeue_task(rq, p, DEQUEUE_SAVE | DEQUEUE_NOCLOCK);
5213 	if (running)
5214 		put_prev_task(rq, p);
5215 
5216 	p->static_prio = NICE_TO_PRIO(nice);
5217 	set_load_weight(p);
5218 	old_prio = p->prio;
5219 	p->prio = effective_prio(p);
5220 
5221 	if (queued)
5222 		enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
5223 	if (running)
5224 		set_next_task(rq, p);
5225 
5226 	/*
5227 	 * If the task increased its priority or is running and
5228 	 * lowered its priority, then reschedule its CPU:
5229 	 */
5230 	p->sched_class->prio_changed(rq, p, old_prio);
5231 
5232 out_unlock:
5233 	task_rq_unlock(rq, p, &rf);
5234 }
5235 EXPORT_SYMBOL(set_user_nice);
5236 
5237 /*
5238  * can_nice - check if a task can reduce its nice value
5239  * @p: task
5240  * @nice: nice value
5241  */
can_nice(const struct task_struct * p,const int nice)5242 int can_nice(const struct task_struct *p, const int nice)
5243 {
5244 	/* Convert nice value [19,-20] to rlimit style value [1,40]: */
5245 	int nice_rlim = nice_to_rlimit(nice);
5246 
5247 	return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) ||
5248 		capable(CAP_SYS_NICE));
5249 }
5250 
5251 #ifdef __ARCH_WANT_SYS_NICE
5252 
5253 /*
5254  * sys_nice - change the priority of the current process.
5255  * @increment: priority increment
5256  *
5257  * sys_setpriority is a more generic, but much slower function that
5258  * does similar things.
5259  */
SYSCALL_DEFINE1(nice,int,increment)5260 SYSCALL_DEFINE1(nice, int, increment)
5261 {
5262 	long nice, retval;
5263 
5264 	/*
5265 	 * Setpriority might change our priority at the same moment.
5266 	 * We don't have to worry. Conceptually one call occurs first
5267 	 * and we have a single winner.
5268 	 */
5269 	increment = clamp(increment, -NICE_WIDTH, NICE_WIDTH);
5270 	nice = task_nice(current) + increment;
5271 
5272 	nice = clamp_val(nice, MIN_NICE, MAX_NICE);
5273 	if (increment < 0 && !can_nice(current, nice))
5274 		return -EPERM;
5275 
5276 	retval = security_task_setnice(current, nice);
5277 	if (retval)
5278 		return retval;
5279 
5280 	set_user_nice(current, nice);
5281 	return 0;
5282 }
5283 
5284 #endif
5285 
5286 /**
5287  * task_prio - return the priority value of a given task.
5288  * @p: the task in question.
5289  *
5290  * Return: The priority value as seen by users in /proc.
5291  * RT tasks are offset by -200. Normal tasks are centered
5292  * around 0, value goes from -16 to +15.
5293  */
task_prio(const struct task_struct * p)5294 int task_prio(const struct task_struct *p)
5295 {
5296 	return p->prio - MAX_RT_PRIO;
5297 }
5298 
5299 /**
5300  * idle_cpu - is a given CPU idle currently?
5301  * @cpu: the processor in question.
5302  *
5303  * Return: 1 if the CPU is currently idle. 0 otherwise.
5304  */
idle_cpu(int cpu)5305 int idle_cpu(int cpu)
5306 {
5307 	struct rq *rq = cpu_rq(cpu);
5308 
5309 	if (rq->curr != rq->idle)
5310 		return 0;
5311 
5312 	if (rq->nr_running)
5313 		return 0;
5314 
5315 #ifdef CONFIG_SMP
5316 	if (rq->ttwu_pending)
5317 		return 0;
5318 #endif
5319 
5320 	return 1;
5321 }
5322 
5323 /**
5324  * available_idle_cpu - is a given CPU idle for enqueuing work.
5325  * @cpu: the CPU in question.
5326  *
5327  * Return: 1 if the CPU is currently idle. 0 otherwise.
5328  */
available_idle_cpu(int cpu)5329 int available_idle_cpu(int cpu)
5330 {
5331 	if (!idle_cpu(cpu))
5332 		return 0;
5333 
5334 	if (vcpu_is_preempted(cpu))
5335 		return 0;
5336 
5337 	return 1;
5338 }
5339 
5340 /**
5341  * idle_task - return the idle task for a given CPU.
5342  * @cpu: the processor in question.
5343  *
5344  * Return: The idle task for the CPU @cpu.
5345  */
idle_task(int cpu)5346 struct task_struct *idle_task(int cpu)
5347 {
5348 	return cpu_rq(cpu)->idle;
5349 }
5350 
5351 /**
5352  * find_process_by_pid - find a process with a matching PID value.
5353  * @pid: the pid in question.
5354  *
5355  * The task of @pid, if found. %NULL otherwise.
5356  */
find_process_by_pid(pid_t pid)5357 static struct task_struct *find_process_by_pid(pid_t pid)
5358 {
5359 	return pid ? find_task_by_vpid(pid) : current;
5360 }
5361 
5362 /*
5363  * sched_setparam() passes in -1 for its policy, to let the functions
5364  * it calls know not to change it.
5365  */
5366 #define SETPARAM_POLICY	-1
5367 
__setscheduler_params(struct task_struct * p,const struct sched_attr * attr)5368 static void __setscheduler_params(struct task_struct *p,
5369 		const struct sched_attr *attr)
5370 {
5371 	int policy = attr->sched_policy;
5372 
5373 	if (policy == SETPARAM_POLICY)
5374 		policy = p->policy;
5375 
5376 	p->policy = policy;
5377 
5378 	if (dl_policy(policy))
5379 		__setparam_dl(p, attr);
5380 	else if (fair_policy(policy))
5381 		p->static_prio = NICE_TO_PRIO(attr->sched_nice);
5382 
5383 	/*
5384 	 * __sched_setscheduler() ensures attr->sched_priority == 0 when
5385 	 * !rt_policy. Always setting this ensures that things like
5386 	 * getparam()/getattr() don't report silly values for !rt tasks.
5387 	 */
5388 	p->rt_priority = attr->sched_priority;
5389 	p->normal_prio = normal_prio(p);
5390 	set_load_weight(p);
5391 }
5392 
5393 /*
5394  * Check the target process has a UID that matches the current process's:
5395  */
check_same_owner(struct task_struct * p)5396 static bool check_same_owner(struct task_struct *p)
5397 {
5398 	const struct cred *cred = current_cred(), *pcred;
5399 	bool match;
5400 
5401 	rcu_read_lock();
5402 	pcred = __task_cred(p);
5403 	match = (uid_eq(cred->euid, pcred->euid) ||
5404 		 uid_eq(cred->euid, pcred->uid));
5405 	rcu_read_unlock();
5406 	return match;
5407 }
5408 
__sched_setscheduler(struct task_struct * p,const struct sched_attr * attr,bool user,bool pi)5409 static int __sched_setscheduler(struct task_struct *p,
5410 				const struct sched_attr *attr,
5411 				bool user, bool pi)
5412 {
5413 	int oldpolicy = -1, policy = attr->sched_policy;
5414 	int retval, oldprio, newprio, queued, running;
5415 	const struct sched_class *prev_class;
5416 	struct rq_flags rf;
5417 	int reset_on_fork;
5418 	int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
5419 	struct rq *rq;
5420 	bool cpuset_locked = false;
5421 
5422 	/* The pi code expects interrupts enabled */
5423 	BUG_ON(pi && in_interrupt());
5424 recheck:
5425 	/* Double check policy once rq lock held: */
5426 	if (policy < 0) {
5427 		reset_on_fork = p->sched_reset_on_fork;
5428 		policy = oldpolicy = p->policy;
5429 	} else {
5430 		reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK);
5431 
5432 		if (!valid_policy(policy))
5433 			return -EINVAL;
5434 	}
5435 
5436 	if (attr->sched_flags & ~(SCHED_FLAG_ALL | SCHED_FLAG_SUGOV))
5437 		return -EINVAL;
5438 
5439 	/*
5440 	 * Valid priorities for SCHED_FIFO and SCHED_RR are
5441 	 * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL,
5442 	 * SCHED_BATCH and SCHED_IDLE is 0.
5443 	 */
5444 	if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) ||
5445 	    (!p->mm && attr->sched_priority > MAX_RT_PRIO-1))
5446 		return -EINVAL;
5447 	if ((dl_policy(policy) && !__checkparam_dl(attr)) ||
5448 	    (rt_policy(policy) != (attr->sched_priority != 0)))
5449 		return -EINVAL;
5450 
5451 	/*
5452 	 * Allow unprivileged RT tasks to decrease priority:
5453 	 */
5454 	if (user && !capable(CAP_SYS_NICE)) {
5455 		if (fair_policy(policy)) {
5456 			if (attr->sched_nice < task_nice(p) &&
5457 			    !can_nice(p, attr->sched_nice))
5458 				return -EPERM;
5459 		}
5460 
5461 		if (rt_policy(policy)) {
5462 			unsigned long rlim_rtprio =
5463 					task_rlimit(p, RLIMIT_RTPRIO);
5464 
5465 			/* Can't set/change the rt policy: */
5466 			if (policy != p->policy && !rlim_rtprio)
5467 				return -EPERM;
5468 
5469 			/* Can't increase priority: */
5470 			if (attr->sched_priority > p->rt_priority &&
5471 			    attr->sched_priority > rlim_rtprio)
5472 				return -EPERM;
5473 		}
5474 
5475 		 /*
5476 		  * Can't set/change SCHED_DEADLINE policy at all for now
5477 		  * (safest behavior); in the future we would like to allow
5478 		  * unprivileged DL tasks to increase their relative deadline
5479 		  * or reduce their runtime (both ways reducing utilization)
5480 		  */
5481 		if (dl_policy(policy))
5482 			return -EPERM;
5483 
5484 		/*
5485 		 * Treat SCHED_IDLE as nice 20. Only allow a switch to
5486 		 * SCHED_NORMAL if the RLIMIT_NICE would normally permit it.
5487 		 */
5488 		if (task_has_idle_policy(p) && !idle_policy(policy)) {
5489 			if (!can_nice(p, task_nice(p)))
5490 				return -EPERM;
5491 		}
5492 
5493 		/* Can't change other user's priorities: */
5494 		if (!check_same_owner(p))
5495 			return -EPERM;
5496 
5497 		/* Normal users shall not reset the sched_reset_on_fork flag: */
5498 		if (p->sched_reset_on_fork && !reset_on_fork)
5499 			return -EPERM;
5500 	}
5501 
5502 	if (user) {
5503 		if (attr->sched_flags & SCHED_FLAG_SUGOV)
5504 			return -EINVAL;
5505 
5506 		retval = security_task_setscheduler(p);
5507 		if (retval)
5508 			return retval;
5509 	}
5510 
5511 	/* Update task specific "requested" clamps */
5512 	if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP) {
5513 		retval = uclamp_validate(p, attr);
5514 		if (retval)
5515 			return retval;
5516 	}
5517 
5518 	if (attr->sched_flags & SCHED_FLAG_LATENCY_NICE) {
5519 		retval = latency_nice_validate(p, user, attr);
5520 		if (retval)
5521 			return retval;
5522 	}
5523 
5524 	/*
5525 	 * SCHED_DEADLINE bandwidth accounting relies on stable cpusets
5526 	 * information.
5527 	 */
5528 	if (dl_policy(policy) || dl_policy(p->policy)) {
5529 		cpuset_locked = true;
5530 		cpuset_lock();
5531 	}
5532 
5533 	/*
5534 	 * Make sure no PI-waiters arrive (or leave) while we are
5535 	 * changing the priority of the task:
5536 	 *
5537 	 * To be able to change p->policy safely, the appropriate
5538 	 * runqueue lock must be held.
5539 	 */
5540 	rq = task_rq_lock(p, &rf);
5541 	update_rq_clock(rq);
5542 
5543 	/*
5544 	 * Changing the policy of the stop threads its a very bad idea:
5545 	 */
5546 	if (p == rq->stop) {
5547 		retval = -EINVAL;
5548 		goto unlock;
5549 	}
5550 
5551 	/*
5552 	 * If not changing anything there's no need to proceed further,
5553 	 * but store a possible modification of reset_on_fork.
5554 	 */
5555 	if (unlikely(policy == p->policy)) {
5556 		if (fair_policy(policy) && attr->sched_nice != task_nice(p))
5557 			goto change;
5558 		if (rt_policy(policy) && attr->sched_priority != p->rt_priority)
5559 			goto change;
5560 		if (dl_policy(policy) && dl_param_changed(p, attr))
5561 			goto change;
5562 		if (attr->sched_flags & SCHED_FLAG_UTIL_CLAMP)
5563 			goto change;
5564 #ifdef CONFIG_SCHED_LATENCY_NICE
5565 		if (attr->sched_flags & SCHED_FLAG_LATENCY_NICE &&
5566 		    attr->sched_latency_nice != LATENCY_TO_NICE(p->latency_prio))
5567 			goto change;
5568 #endif
5569 
5570 		p->sched_reset_on_fork = reset_on_fork;
5571 		retval = 0;
5572 		goto unlock;
5573 	}
5574 change:
5575 
5576 	if (user) {
5577 #ifdef CONFIG_RT_GROUP_SCHED
5578 		/*
5579 		 * Do not allow realtime tasks into groups that have no runtime
5580 		 * assigned.
5581 		 */
5582 		if (rt_bandwidth_enabled() && rt_policy(policy) &&
5583 				task_group(p)->rt_bandwidth.rt_runtime == 0 &&
5584 				!task_group_is_autogroup(task_group(p))) {
5585 			retval = -EPERM;
5586 			goto unlock;
5587 		}
5588 #endif
5589 #ifdef CONFIG_SMP
5590 		if (dl_bandwidth_enabled() && dl_policy(policy) &&
5591 				!(attr->sched_flags & SCHED_FLAG_SUGOV)) {
5592 			cpumask_t *span = rq->rd->span;
5593 
5594 			/*
5595 			 * Don't allow tasks with an affinity mask smaller than
5596 			 * the entire root_domain to become SCHED_DEADLINE. We
5597 			 * will also fail if there's no bandwidth available.
5598 			 */
5599 			if (!cpumask_subset(span, p->cpus_ptr) ||
5600 			    rq->rd->dl_bw.bw == 0) {
5601 				retval = -EPERM;
5602 				goto unlock;
5603 			}
5604 		}
5605 #endif
5606 	}
5607 
5608 	/* Re-check policy now with rq lock held: */
5609 	if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) {
5610 		policy = oldpolicy = -1;
5611 		task_rq_unlock(rq, p, &rf);
5612 		if (cpuset_locked)
5613 			cpuset_unlock();
5614 		goto recheck;
5615 	}
5616 
5617 	/*
5618 	 * If setscheduling to SCHED_DEADLINE (or changing the parameters
5619 	 * of a SCHED_DEADLINE task) we need to check if enough bandwidth
5620 	 * is available.
5621 	 */
5622 	if ((dl_policy(policy) || dl_task(p)) && sched_dl_overflow(p, policy, attr)) {
5623 		retval = -EBUSY;
5624 		goto unlock;
5625 	}
5626 
5627 	p->sched_reset_on_fork = reset_on_fork;
5628 	oldprio = p->prio;
5629 
5630 	newprio = __normal_prio(policy, attr->sched_priority, attr->sched_nice);
5631 	if (pi) {
5632 		/*
5633 		 * Take priority boosted tasks into account. If the new
5634 		 * effective priority is unchanged, we just store the new
5635 		 * normal parameters and do not touch the scheduler class and
5636 		 * the runqueue. This will be done when the task deboost
5637 		 * itself.
5638 		 */
5639 		newprio = rt_effective_prio(p, newprio);
5640 		if (newprio == oldprio)
5641 			queue_flags &= ~DEQUEUE_MOVE;
5642 	}
5643 
5644 	queued = task_on_rq_queued(p);
5645 	running = task_current(rq, p);
5646 	if (queued)
5647 		dequeue_task(rq, p, queue_flags);
5648 	if (running)
5649 		put_prev_task(rq, p);
5650 
5651 	prev_class = p->sched_class;
5652 
5653 	if (!(attr->sched_flags & SCHED_FLAG_KEEP_PARAMS)) {
5654 		__setscheduler_params(p, attr);
5655 		__setscheduler_prio(p, newprio);
5656 	}
5657 	__setscheduler_latency(p, attr);
5658 	__setscheduler_uclamp(p, attr);
5659 
5660 	if (queued) {
5661 		/*
5662 		 * We enqueue to tail when the priority of a task is
5663 		 * increased (user space view).
5664 		 */
5665 		if (oldprio < p->prio)
5666 			queue_flags |= ENQUEUE_HEAD;
5667 
5668 		enqueue_task(rq, p, queue_flags);
5669 	}
5670 	if (running)
5671 		set_next_task(rq, p);
5672 
5673 	check_class_changed(rq, p, prev_class, oldprio);
5674 
5675 	/* Avoid rq from going away on us: */
5676 	preempt_disable();
5677 	task_rq_unlock(rq, p, &rf);
5678 
5679 	if (pi) {
5680 		if (cpuset_locked)
5681 			cpuset_unlock();
5682 		rt_mutex_adjust_pi(p);
5683 	}
5684 
5685 	/* Run balance callbacks after we've adjusted the PI chain: */
5686 	balance_callback(rq);
5687 	preempt_enable();
5688 
5689 	return 0;
5690 
5691 unlock:
5692 	task_rq_unlock(rq, p, &rf);
5693 	if (cpuset_locked)
5694 		cpuset_unlock();
5695 	return retval;
5696 }
5697 
_sched_setscheduler(struct task_struct * p,int policy,const struct sched_param * param,bool check)5698 static int _sched_setscheduler(struct task_struct *p, int policy,
5699 			       const struct sched_param *param, bool check)
5700 {
5701 	struct sched_attr attr = {
5702 		.sched_policy   = policy,
5703 		.sched_priority = param->sched_priority,
5704 		.sched_nice	= PRIO_TO_NICE(p->static_prio),
5705 	};
5706 
5707 	/* Fixup the legacy SCHED_RESET_ON_FORK hack. */
5708 	if ((policy != SETPARAM_POLICY) && (policy & SCHED_RESET_ON_FORK)) {
5709 		attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
5710 		policy &= ~SCHED_RESET_ON_FORK;
5711 		attr.sched_policy = policy;
5712 	}
5713 
5714 	return __sched_setscheduler(p, &attr, check, true);
5715 }
5716 /**
5717  * sched_setscheduler - change the scheduling policy and/or RT priority of a thread.
5718  * @p: the task in question.
5719  * @policy: new policy.
5720  * @param: structure containing the new RT priority.
5721  *
5722  * Use sched_set_fifo(), read its comment.
5723  *
5724  * Return: 0 on success. An error code otherwise.
5725  *
5726  * NOTE that the task may be already dead.
5727  */
sched_setscheduler(struct task_struct * p,int policy,const struct sched_param * param)5728 int sched_setscheduler(struct task_struct *p, int policy,
5729 		       const struct sched_param *param)
5730 {
5731 	return _sched_setscheduler(p, policy, param, true);
5732 }
5733 
sched_setattr(struct task_struct * p,const struct sched_attr * attr)5734 int sched_setattr(struct task_struct *p, const struct sched_attr *attr)
5735 {
5736 	return __sched_setscheduler(p, attr, true, true);
5737 }
5738 
sched_setattr_nocheck(struct task_struct * p,const struct sched_attr * attr)5739 int sched_setattr_nocheck(struct task_struct *p, const struct sched_attr *attr)
5740 {
5741 	return __sched_setscheduler(p, attr, false, true);
5742 }
5743 
5744 /**
5745  * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace.
5746  * @p: the task in question.
5747  * @policy: new policy.
5748  * @param: structure containing the new RT priority.
5749  *
5750  * Just like sched_setscheduler, only don't bother checking if the
5751  * current context has permission.  For example, this is needed in
5752  * stop_machine(): we create temporary high priority worker threads,
5753  * but our caller might not have that capability.
5754  *
5755  * Return: 0 on success. An error code otherwise.
5756  */
sched_setscheduler_nocheck(struct task_struct * p,int policy,const struct sched_param * param)5757 int sched_setscheduler_nocheck(struct task_struct *p, int policy,
5758 			       const struct sched_param *param)
5759 {
5760 	return _sched_setscheduler(p, policy, param, false);
5761 }
5762 
5763 /*
5764  * SCHED_FIFO is a broken scheduler model; that is, it is fundamentally
5765  * incapable of resource management, which is the one thing an OS really should
5766  * be doing.
5767  *
5768  * This is of course the reason it is limited to privileged users only.
5769  *
5770  * Worse still; it is fundamentally impossible to compose static priority
5771  * workloads. You cannot take two correctly working static prio workloads
5772  * and smash them together and still expect them to work.
5773  *
5774  * For this reason 'all' FIFO tasks the kernel creates are basically at:
5775  *
5776  *   MAX_RT_PRIO / 2
5777  *
5778  * The administrator _MUST_ configure the system, the kernel simply doesn't
5779  * know enough information to make a sensible choice.
5780  */
sched_set_fifo(struct task_struct * p)5781 void sched_set_fifo(struct task_struct *p)
5782 {
5783 	struct sched_param sp = { .sched_priority = MAX_RT_PRIO / 2 };
5784 	WARN_ON_ONCE(sched_setscheduler_nocheck(p, SCHED_FIFO, &sp) != 0);
5785 }
5786 EXPORT_SYMBOL_GPL(sched_set_fifo);
5787 
5788 /*
5789  * For when you don't much care about FIFO, but want to be above SCHED_NORMAL.
5790  */
sched_set_fifo_low(struct task_struct * p)5791 void sched_set_fifo_low(struct task_struct *p)
5792 {
5793 	struct sched_param sp = { .sched_priority = 1 };
5794 	WARN_ON_ONCE(sched_setscheduler_nocheck(p, SCHED_FIFO, &sp) != 0);
5795 }
5796 EXPORT_SYMBOL_GPL(sched_set_fifo_low);
5797 
sched_set_normal(struct task_struct * p,int nice)5798 void sched_set_normal(struct task_struct *p, int nice)
5799 {
5800 	struct sched_attr attr = {
5801 		.sched_policy = SCHED_NORMAL,
5802 		.sched_nice = nice,
5803 	};
5804 	WARN_ON_ONCE(sched_setattr_nocheck(p, &attr) != 0);
5805 }
5806 EXPORT_SYMBOL_GPL(sched_set_normal);
5807 
5808 static int
do_sched_setscheduler(pid_t pid,int policy,struct sched_param __user * param)5809 do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param)
5810 {
5811 	struct sched_param lparam;
5812 	struct task_struct *p;
5813 	int retval;
5814 
5815 	if (!param || pid < 0)
5816 		return -EINVAL;
5817 	if (copy_from_user(&lparam, param, sizeof(struct sched_param)))
5818 		return -EFAULT;
5819 
5820 	rcu_read_lock();
5821 	retval = -ESRCH;
5822 	p = find_process_by_pid(pid);
5823 	if (likely(p))
5824 		get_task_struct(p);
5825 	rcu_read_unlock();
5826 
5827 	if (likely(p)) {
5828 		retval = sched_setscheduler(p, policy, &lparam);
5829 		put_task_struct(p);
5830 	}
5831 
5832 	return retval;
5833 }
5834 
5835 /*
5836  * Mimics kernel/events/core.c perf_copy_attr().
5837  */
sched_copy_attr(struct sched_attr __user * uattr,struct sched_attr * attr)5838 static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *attr)
5839 {
5840 	u32 size;
5841 	int ret;
5842 
5843 	/* Zero the full structure, so that a short copy will be nice: */
5844 	memset(attr, 0, sizeof(*attr));
5845 
5846 	ret = get_user(size, &uattr->size);
5847 	if (ret)
5848 		return ret;
5849 
5850 	/* ABI compatibility quirk: */
5851 	if (!size)
5852 		size = SCHED_ATTR_SIZE_VER0;
5853 	if (size < SCHED_ATTR_SIZE_VER0 || size > PAGE_SIZE)
5854 		goto err_size;
5855 
5856 	ret = copy_struct_from_user(attr, sizeof(*attr), uattr, size);
5857 	if (ret) {
5858 		if (ret == -E2BIG)
5859 			goto err_size;
5860 		return ret;
5861 	}
5862 
5863 	if ((attr->sched_flags & SCHED_FLAG_UTIL_CLAMP) &&
5864 	    size < SCHED_ATTR_SIZE_VER1)
5865 		return -EINVAL;
5866 
5867 #ifdef CONFIG_SCHED_LATENCY_NICE
5868 	if ((attr->sched_flags & SCHED_FLAG_LATENCY_NICE) &&
5869 	    size < SCHED_ATTR_SIZE_VER2)
5870 		return -EINVAL;
5871 #endif
5872 	/*
5873 	 * XXX: Do we want to be lenient like existing syscalls; or do we want
5874 	 * to be strict and return an error on out-of-bounds values?
5875 	 */
5876 	attr->sched_nice = clamp(attr->sched_nice, MIN_NICE, MAX_NICE);
5877 
5878 	return 0;
5879 
5880 err_size:
5881 	put_user(sizeof(*attr), &uattr->size);
5882 	return -E2BIG;
5883 }
5884 
5885 /**
5886  * sys_sched_setscheduler - set/change the scheduler policy and RT priority
5887  * @pid: the pid in question.
5888  * @policy: new policy.
5889  * @param: structure containing the new RT priority.
5890  *
5891  * Return: 0 on success. An error code otherwise.
5892  */
SYSCALL_DEFINE3(sched_setscheduler,pid_t,pid,int,policy,struct sched_param __user *,param)5893 SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param)
5894 {
5895 	if (policy < 0)
5896 		return -EINVAL;
5897 
5898 	return do_sched_setscheduler(pid, policy, param);
5899 }
5900 
5901 /**
5902  * sys_sched_setparam - set/change the RT priority of a thread
5903  * @pid: the pid in question.
5904  * @param: structure containing the new RT priority.
5905  *
5906  * Return: 0 on success. An error code otherwise.
5907  */
SYSCALL_DEFINE2(sched_setparam,pid_t,pid,struct sched_param __user *,param)5908 SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param)
5909 {
5910 	return do_sched_setscheduler(pid, SETPARAM_POLICY, param);
5911 }
5912 
5913 /**
5914  * sys_sched_setattr - same as above, but with extended sched_attr
5915  * @pid: the pid in question.
5916  * @uattr: structure containing the extended parameters.
5917  * @flags: for future extension.
5918  */
SYSCALL_DEFINE3(sched_setattr,pid_t,pid,struct sched_attr __user *,uattr,unsigned int,flags)5919 SYSCALL_DEFINE3(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr,
5920 			       unsigned int, flags)
5921 {
5922 	struct sched_attr attr;
5923 	struct task_struct *p;
5924 	int retval;
5925 
5926 	if (!uattr || pid < 0 || flags)
5927 		return -EINVAL;
5928 
5929 	retval = sched_copy_attr(uattr, &attr);
5930 	if (retval)
5931 		return retval;
5932 
5933 	if ((int)attr.sched_policy < 0)
5934 		return -EINVAL;
5935 	if (attr.sched_flags & SCHED_FLAG_KEEP_POLICY)
5936 		attr.sched_policy = SETPARAM_POLICY;
5937 
5938 	rcu_read_lock();
5939 	retval = -ESRCH;
5940 	p = find_process_by_pid(pid);
5941 	if (likely(p))
5942 		get_task_struct(p);
5943 	rcu_read_unlock();
5944 
5945 	if (likely(p)) {
5946 		retval = sched_setattr(p, &attr);
5947 		put_task_struct(p);
5948 	}
5949 
5950 	return retval;
5951 }
5952 
5953 /**
5954  * sys_sched_getscheduler - get the policy (scheduling class) of a thread
5955  * @pid: the pid in question.
5956  *
5957  * Return: On success, the policy of the thread. Otherwise, a negative error
5958  * code.
5959  */
SYSCALL_DEFINE1(sched_getscheduler,pid_t,pid)5960 SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid)
5961 {
5962 	struct task_struct *p;
5963 	int retval;
5964 
5965 	if (pid < 0)
5966 		return -EINVAL;
5967 
5968 	retval = -ESRCH;
5969 	rcu_read_lock();
5970 	p = find_process_by_pid(pid);
5971 	if (p) {
5972 		retval = security_task_getscheduler(p);
5973 		if (!retval)
5974 			retval = p->policy
5975 				| (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0);
5976 	}
5977 	rcu_read_unlock();
5978 	return retval;
5979 }
5980 
5981 /**
5982  * sys_sched_getparam - get the RT priority of a thread
5983  * @pid: the pid in question.
5984  * @param: structure containing the RT priority.
5985  *
5986  * Return: On success, 0 and the RT priority is in @param. Otherwise, an error
5987  * code.
5988  */
SYSCALL_DEFINE2(sched_getparam,pid_t,pid,struct sched_param __user *,param)5989 SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param)
5990 {
5991 	struct sched_param lp = { .sched_priority = 0 };
5992 	struct task_struct *p;
5993 	int retval;
5994 
5995 	if (!param || pid < 0)
5996 		return -EINVAL;
5997 
5998 	rcu_read_lock();
5999 	p = find_process_by_pid(pid);
6000 	retval = -ESRCH;
6001 	if (!p)
6002 		goto out_unlock;
6003 
6004 	retval = security_task_getscheduler(p);
6005 	if (retval)
6006 		goto out_unlock;
6007 
6008 	if (task_has_rt_policy(p))
6009 		lp.sched_priority = p->rt_priority;
6010 	rcu_read_unlock();
6011 
6012 	/*
6013 	 * This one might sleep, we cannot do it with a spinlock held ...
6014 	 */
6015 	retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0;
6016 
6017 	return retval;
6018 
6019 out_unlock:
6020 	rcu_read_unlock();
6021 	return retval;
6022 }
6023 
6024 /*
6025  * Copy the kernel size attribute structure (which might be larger
6026  * than what user-space knows about) to user-space.
6027  *
6028  * Note that all cases are valid: user-space buffer can be larger or
6029  * smaller than the kernel-space buffer. The usual case is that both
6030  * have the same size.
6031  */
6032 static int
sched_attr_copy_to_user(struct sched_attr __user * uattr,struct sched_attr * kattr,unsigned int usize)6033 sched_attr_copy_to_user(struct sched_attr __user *uattr,
6034 			struct sched_attr *kattr,
6035 			unsigned int usize)
6036 {
6037 	unsigned int ksize = sizeof(*kattr);
6038 
6039 	if (!access_ok(uattr, usize))
6040 		return -EFAULT;
6041 
6042 	/*
6043 	 * sched_getattr() ABI forwards and backwards compatibility:
6044 	 *
6045 	 * If usize == ksize then we just copy everything to user-space and all is good.
6046 	 *
6047 	 * If usize < ksize then we only copy as much as user-space has space for,
6048 	 * this keeps ABI compatibility as well. We skip the rest.
6049 	 *
6050 	 * If usize > ksize then user-space is using a newer version of the ABI,
6051 	 * which part the kernel doesn't know about. Just ignore it - tooling can
6052 	 * detect the kernel's knowledge of attributes from the attr->size value
6053 	 * which is set to ksize in this case.
6054 	 */
6055 	kattr->size = min(usize, ksize);
6056 
6057 	if (copy_to_user(uattr, kattr, kattr->size))
6058 		return -EFAULT;
6059 
6060 	return 0;
6061 }
6062 
6063 /**
6064  * sys_sched_getattr - similar to sched_getparam, but with sched_attr
6065  * @pid: the pid in question.
6066  * @uattr: structure containing the extended parameters.
6067  * @usize: sizeof(attr) for fwd/bwd comp.
6068  * @flags: for future extension.
6069  */
SYSCALL_DEFINE4(sched_getattr,pid_t,pid,struct sched_attr __user *,uattr,unsigned int,usize,unsigned int,flags)6070 SYSCALL_DEFINE4(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr,
6071 		unsigned int, usize, unsigned int, flags)
6072 {
6073 	struct sched_attr kattr = { };
6074 	struct task_struct *p;
6075 	int retval;
6076 
6077 	if (!uattr || pid < 0 || usize > PAGE_SIZE ||
6078 	    usize < SCHED_ATTR_SIZE_VER0 || flags)
6079 		return -EINVAL;
6080 
6081 	rcu_read_lock();
6082 	p = find_process_by_pid(pid);
6083 	retval = -ESRCH;
6084 	if (!p)
6085 		goto out_unlock;
6086 
6087 	retval = security_task_getscheduler(p);
6088 	if (retval)
6089 		goto out_unlock;
6090 
6091 	kattr.sched_policy = p->policy;
6092 	if (p->sched_reset_on_fork)
6093 		kattr.sched_flags |= SCHED_FLAG_RESET_ON_FORK;
6094 	if (task_has_dl_policy(p))
6095 		__getparam_dl(p, &kattr);
6096 	else if (task_has_rt_policy(p))
6097 		kattr.sched_priority = p->rt_priority;
6098 	else
6099 		kattr.sched_nice = task_nice(p);
6100 
6101 #ifdef CONFIG_SCHED_LATENCY_NICE
6102 	kattr.sched_latency_nice = LATENCY_TO_NICE(p->latency_prio);
6103 #endif
6104 
6105 #ifdef CONFIG_UCLAMP_TASK
6106 	/*
6107 	 * This could race with another potential updater, but this is fine
6108 	 * because it'll correctly read the old or the new value. We don't need
6109 	 * to guarantee who wins the race as long as it doesn't return garbage.
6110 	 */
6111 	kattr.sched_util_min = p->uclamp_req[UCLAMP_MIN].value;
6112 	kattr.sched_util_max = p->uclamp_req[UCLAMP_MAX].value;
6113 #endif
6114 
6115 	rcu_read_unlock();
6116 
6117 	return sched_attr_copy_to_user(uattr, &kattr, usize);
6118 
6119 out_unlock:
6120 	rcu_read_unlock();
6121 	return retval;
6122 }
6123 
sched_setaffinity(pid_t pid,const struct cpumask * in_mask)6124 long sched_setaffinity(pid_t pid, const struct cpumask *in_mask)
6125 {
6126 	cpumask_var_t cpus_allowed, new_mask;
6127 	struct task_struct *p;
6128 	int retval;
6129 #ifdef CONFIG_CPU_ISOLATION_OPT
6130 	int dest_cpu;
6131 	cpumask_t allowed_mask;
6132 #endif
6133 
6134 	rcu_read_lock();
6135 
6136 	p = find_process_by_pid(pid);
6137 	if (!p) {
6138 		rcu_read_unlock();
6139 		return -ESRCH;
6140 	}
6141 
6142 	/* Prevent p going away */
6143 	get_task_struct(p);
6144 	rcu_read_unlock();
6145 
6146 	if (p->flags & PF_NO_SETAFFINITY) {
6147 		retval = -EINVAL;
6148 		goto out_put_task;
6149 	}
6150 	if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) {
6151 		retval = -ENOMEM;
6152 		goto out_put_task;
6153 	}
6154 	if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) {
6155 		retval = -ENOMEM;
6156 		goto out_free_cpus_allowed;
6157 	}
6158 	retval = -EPERM;
6159 	if (!check_same_owner(p)) {
6160 		rcu_read_lock();
6161 		if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) {
6162 			rcu_read_unlock();
6163 			goto out_free_new_mask;
6164 		}
6165 		rcu_read_unlock();
6166 	}
6167 
6168 	retval = security_task_setscheduler(p);
6169 	if (retval)
6170 		goto out_free_new_mask;
6171 
6172 
6173 	cpuset_cpus_allowed(p, cpus_allowed);
6174 	cpumask_and(new_mask, in_mask, cpus_allowed);
6175 
6176 	/*
6177 	 * Since bandwidth control happens on root_domain basis,
6178 	 * if admission test is enabled, we only admit -deadline
6179 	 * tasks allowed to run on all the CPUs in the task's
6180 	 * root_domain.
6181 	 */
6182 #ifdef CONFIG_SMP
6183 	if (task_has_dl_policy(p) && dl_bandwidth_enabled()) {
6184 		rcu_read_lock();
6185 		if (!cpumask_subset(task_rq(p)->rd->span, new_mask)) {
6186 			retval = -EBUSY;
6187 			rcu_read_unlock();
6188 			goto out_free_new_mask;
6189 		}
6190 		rcu_read_unlock();
6191 	}
6192 #endif
6193 again:
6194 #ifdef CONFIG_CPU_ISOLATION_OPT
6195 	cpumask_andnot(&allowed_mask, new_mask, cpu_isolated_mask);
6196 	dest_cpu = cpumask_any_and(cpu_active_mask, &allowed_mask);
6197 	if (dest_cpu < nr_cpu_ids) {
6198 #endif
6199 		retval = __set_cpus_allowed_ptr(p, new_mask, true);
6200 		if (!retval) {
6201 			cpuset_cpus_allowed(p, cpus_allowed);
6202 			if (!cpumask_subset(new_mask, cpus_allowed)) {
6203 				/*
6204 				 * We must have raced with a concurrent cpuset
6205 				 * update. Just reset the cpus_allowed to the
6206 				 * cpuset's cpus_allowed
6207 				 */
6208 				cpumask_copy(new_mask, cpus_allowed);
6209 				goto again;
6210 			}
6211 		}
6212 #ifdef CONFIG_CPU_ISOLATION_OPT
6213 	} else {
6214 		retval = -EINVAL;
6215 	}
6216 #endif
6217 
6218 out_free_new_mask:
6219 	free_cpumask_var(new_mask);
6220 out_free_cpus_allowed:
6221 	free_cpumask_var(cpus_allowed);
6222 out_put_task:
6223 	put_task_struct(p);
6224 	return retval;
6225 }
6226 
get_user_cpu_mask(unsigned long __user * user_mask_ptr,unsigned len,struct cpumask * new_mask)6227 static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len,
6228 			     struct cpumask *new_mask)
6229 {
6230 	if (len < cpumask_size())
6231 		cpumask_clear(new_mask);
6232 	else if (len > cpumask_size())
6233 		len = cpumask_size();
6234 
6235 	return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0;
6236 }
6237 
6238 /**
6239  * sys_sched_setaffinity - set the CPU affinity of a process
6240  * @pid: pid of the process
6241  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
6242  * @user_mask_ptr: user-space pointer to the new CPU mask
6243  *
6244  * Return: 0 on success. An error code otherwise.
6245  */
SYSCALL_DEFINE3(sched_setaffinity,pid_t,pid,unsigned int,len,unsigned long __user *,user_mask_ptr)6246 SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len,
6247 		unsigned long __user *, user_mask_ptr)
6248 {
6249 	cpumask_var_t new_mask;
6250 	int retval;
6251 
6252 	if (!alloc_cpumask_var(&new_mask, GFP_KERNEL))
6253 		return -ENOMEM;
6254 
6255 	retval = get_user_cpu_mask(user_mask_ptr, len, new_mask);
6256 	if (retval == 0)
6257 		retval = sched_setaffinity(pid, new_mask);
6258 	free_cpumask_var(new_mask);
6259 	return retval;
6260 }
6261 
sched_getaffinity(pid_t pid,struct cpumask * mask)6262 long sched_getaffinity(pid_t pid, struct cpumask *mask)
6263 {
6264 	struct task_struct *p;
6265 	unsigned long flags;
6266 	int retval;
6267 
6268 	rcu_read_lock();
6269 
6270 	retval = -ESRCH;
6271 	p = find_process_by_pid(pid);
6272 	if (!p)
6273 		goto out_unlock;
6274 
6275 	retval = security_task_getscheduler(p);
6276 	if (retval)
6277 		goto out_unlock;
6278 
6279 	raw_spin_lock_irqsave(&p->pi_lock, flags);
6280 	cpumask_and(mask, &p->cpus_mask, cpu_active_mask);
6281 
6282 #ifdef CONFIG_CPU_ISOLATION_OPT
6283 	/* The userspace tasks are forbidden to run on
6284 	 * isolated CPUs. So exclude isolated CPUs from
6285 	 * the getaffinity.
6286 	 */
6287 	if (!(p->flags & PF_KTHREAD))
6288 		cpumask_andnot(mask, mask, cpu_isolated_mask);
6289 #endif
6290 
6291 	raw_spin_unlock_irqrestore(&p->pi_lock, flags);
6292 
6293 out_unlock:
6294 	rcu_read_unlock();
6295 
6296 	return retval;
6297 }
6298 
6299 /**
6300  * sys_sched_getaffinity - get the CPU affinity of a process
6301  * @pid: pid of the process
6302  * @len: length in bytes of the bitmask pointed to by user_mask_ptr
6303  * @user_mask_ptr: user-space pointer to hold the current CPU mask
6304  *
6305  * Return: size of CPU mask copied to user_mask_ptr on success. An
6306  * error code otherwise.
6307  */
SYSCALL_DEFINE3(sched_getaffinity,pid_t,pid,unsigned int,len,unsigned long __user *,user_mask_ptr)6308 SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len,
6309 		unsigned long __user *, user_mask_ptr)
6310 {
6311 	int ret;
6312 	cpumask_var_t mask;
6313 
6314 	if ((len * BITS_PER_BYTE) < nr_cpu_ids)
6315 		return -EINVAL;
6316 	if (len & (sizeof(unsigned long)-1))
6317 		return -EINVAL;
6318 
6319 	if (!zalloc_cpumask_var(&mask, GFP_KERNEL))
6320 		return -ENOMEM;
6321 
6322 	ret = sched_getaffinity(pid, mask);
6323 	if (ret == 0) {
6324 		unsigned int retlen = min(len, cpumask_size());
6325 
6326 		if (copy_to_user(user_mask_ptr, cpumask_bits(mask), retlen))
6327 			ret = -EFAULT;
6328 		else
6329 			ret = retlen;
6330 	}
6331 	free_cpumask_var(mask);
6332 
6333 	return ret;
6334 }
6335 
6336 /**
6337  * sys_sched_yield - yield the current processor to other threads.
6338  *
6339  * This function yields the current CPU to other tasks. If there are no
6340  * other threads running on this CPU then this function will return.
6341  *
6342  * Return: 0.
6343  */
do_sched_yield(void)6344 static void do_sched_yield(void)
6345 {
6346 	struct rq_flags rf;
6347 	struct rq *rq;
6348 
6349 	rq = this_rq_lock_irq(&rf);
6350 
6351 	schedstat_inc(rq->yld_count);
6352 	current->sched_class->yield_task(rq);
6353 
6354 	preempt_disable();
6355 	rq_unlock_irq(rq, &rf);
6356 	sched_preempt_enable_no_resched();
6357 
6358 	schedule();
6359 }
6360 
SYSCALL_DEFINE0(sched_yield)6361 SYSCALL_DEFINE0(sched_yield)
6362 {
6363 	do_sched_yield();
6364 	return 0;
6365 }
6366 
6367 #ifndef CONFIG_PREEMPTION
_cond_resched(void)6368 int __sched _cond_resched(void)
6369 {
6370 	if (should_resched(0)) {
6371 		preempt_schedule_common();
6372 		return 1;
6373 	}
6374 	rcu_all_qs();
6375 	return 0;
6376 }
6377 EXPORT_SYMBOL(_cond_resched);
6378 #endif
6379 
6380 /*
6381  * __cond_resched_lock() - if a reschedule is pending, drop the given lock,
6382  * call schedule, and on return reacquire the lock.
6383  *
6384  * This works OK both with and without CONFIG_PREEMPTION. We do strange low-level
6385  * operations here to prevent schedule() from being called twice (once via
6386  * spin_unlock(), once by hand).
6387  */
__cond_resched_lock(spinlock_t * lock)6388 int __cond_resched_lock(spinlock_t *lock)
6389 {
6390 	int resched = should_resched(PREEMPT_LOCK_OFFSET);
6391 	int ret = 0;
6392 
6393 	lockdep_assert_held(lock);
6394 
6395 	if (spin_needbreak(lock) || resched) {
6396 		spin_unlock(lock);
6397 		if (resched)
6398 			preempt_schedule_common();
6399 		else
6400 			cpu_relax();
6401 		ret = 1;
6402 		spin_lock(lock);
6403 	}
6404 	return ret;
6405 }
6406 EXPORT_SYMBOL(__cond_resched_lock);
6407 
6408 /**
6409  * yield - yield the current processor to other threads.
6410  *
6411  * Do not ever use this function, there's a 99% chance you're doing it wrong.
6412  *
6413  * The scheduler is at all times free to pick the calling task as the most
6414  * eligible task to run, if removing the yield() call from your code breaks
6415  * it, its already broken.
6416  *
6417  * Typical broken usage is:
6418  *
6419  * while (!event)
6420  *	yield();
6421  *
6422  * where one assumes that yield() will let 'the other' process run that will
6423  * make event true. If the current task is a SCHED_FIFO task that will never
6424  * happen. Never use yield() as a progress guarantee!!
6425  *
6426  * If you want to use yield() to wait for something, use wait_event().
6427  * If you want to use yield() to be 'nice' for others, use cond_resched().
6428  * If you still want to use yield(), do not!
6429  */
yield(void)6430 void __sched yield(void)
6431 {
6432 	set_current_state(TASK_RUNNING);
6433 	do_sched_yield();
6434 }
6435 EXPORT_SYMBOL(yield);
6436 
6437 /**
6438  * yield_to - yield the current processor to another thread in
6439  * your thread group, or accelerate that thread toward the
6440  * processor it's on.
6441  * @p: target task
6442  * @preempt: whether task preemption is allowed or not
6443  *
6444  * It's the caller's job to ensure that the target task struct
6445  * can't go away on us before we can do any checks.
6446  *
6447  * Return:
6448  *	true (>0) if we indeed boosted the target task.
6449  *	false (0) if we failed to boost the target.
6450  *	-ESRCH if there's no task to yield to.
6451  */
yield_to(struct task_struct * p,bool preempt)6452 int __sched yield_to(struct task_struct *p, bool preempt)
6453 {
6454 	struct task_struct *curr = current;
6455 	struct rq *rq, *p_rq;
6456 	unsigned long flags;
6457 	int yielded = 0;
6458 
6459 	local_irq_save(flags);
6460 	rq = this_rq();
6461 
6462 again:
6463 	p_rq = task_rq(p);
6464 	/*
6465 	 * If we're the only runnable task on the rq and target rq also
6466 	 * has only one task, there's absolutely no point in yielding.
6467 	 */
6468 	if (rq->nr_running == 1 && p_rq->nr_running == 1) {
6469 		yielded = -ESRCH;
6470 		goto out_irq;
6471 	}
6472 
6473 	double_rq_lock(rq, p_rq);
6474 	if (task_rq(p) != p_rq) {
6475 		double_rq_unlock(rq, p_rq);
6476 		goto again;
6477 	}
6478 
6479 	if (!curr->sched_class->yield_to_task)
6480 		goto out_unlock;
6481 
6482 	if (curr->sched_class != p->sched_class)
6483 		goto out_unlock;
6484 
6485 	if (task_running(p_rq, p) || p->state)
6486 		goto out_unlock;
6487 
6488 	yielded = curr->sched_class->yield_to_task(rq, p);
6489 	if (yielded) {
6490 		schedstat_inc(rq->yld_count);
6491 		/*
6492 		 * Make p's CPU reschedule; pick_next_entity takes care of
6493 		 * fairness.
6494 		 */
6495 		if (preempt && rq != p_rq)
6496 			resched_curr(p_rq);
6497 	}
6498 
6499 out_unlock:
6500 	double_rq_unlock(rq, p_rq);
6501 out_irq:
6502 	local_irq_restore(flags);
6503 
6504 	if (yielded > 0)
6505 		schedule();
6506 
6507 	return yielded;
6508 }
6509 EXPORT_SYMBOL_GPL(yield_to);
6510 
io_schedule_prepare(void)6511 int io_schedule_prepare(void)
6512 {
6513 	int old_iowait = current->in_iowait;
6514 
6515 	current->in_iowait = 1;
6516 	blk_schedule_flush_plug(current);
6517 
6518 	return old_iowait;
6519 }
6520 
io_schedule_finish(int token)6521 void io_schedule_finish(int token)
6522 {
6523 	current->in_iowait = token;
6524 }
6525 
6526 /*
6527  * This task is about to go to sleep on IO. Increment rq->nr_iowait so
6528  * that process accounting knows that this is a task in IO wait state.
6529  */
io_schedule_timeout(long timeout)6530 long __sched io_schedule_timeout(long timeout)
6531 {
6532 	int token;
6533 	long ret;
6534 
6535 	token = io_schedule_prepare();
6536 	ret = schedule_timeout(timeout);
6537 	io_schedule_finish(token);
6538 
6539 	return ret;
6540 }
6541 EXPORT_SYMBOL(io_schedule_timeout);
6542 
io_schedule(void)6543 void __sched io_schedule(void)
6544 {
6545 	int token;
6546 
6547 	token = io_schedule_prepare();
6548 	schedule();
6549 	io_schedule_finish(token);
6550 }
6551 EXPORT_SYMBOL(io_schedule);
6552 
6553 /**
6554  * sys_sched_get_priority_max - return maximum RT priority.
6555  * @policy: scheduling class.
6556  *
6557  * Return: On success, this syscall returns the maximum
6558  * rt_priority that can be used by a given scheduling class.
6559  * On failure, a negative error code is returned.
6560  */
SYSCALL_DEFINE1(sched_get_priority_max,int,policy)6561 SYSCALL_DEFINE1(sched_get_priority_max, int, policy)
6562 {
6563 	int ret = -EINVAL;
6564 
6565 	switch (policy) {
6566 	case SCHED_FIFO:
6567 	case SCHED_RR:
6568 		ret = MAX_USER_RT_PRIO-1;
6569 		break;
6570 	case SCHED_DEADLINE:
6571 	case SCHED_NORMAL:
6572 	case SCHED_BATCH:
6573 	case SCHED_IDLE:
6574 		ret = 0;
6575 		break;
6576 	}
6577 	return ret;
6578 }
6579 
6580 /**
6581  * sys_sched_get_priority_min - return minimum RT priority.
6582  * @policy: scheduling class.
6583  *
6584  * Return: On success, this syscall returns the minimum
6585  * rt_priority that can be used by a given scheduling class.
6586  * On failure, a negative error code is returned.
6587  */
SYSCALL_DEFINE1(sched_get_priority_min,int,policy)6588 SYSCALL_DEFINE1(sched_get_priority_min, int, policy)
6589 {
6590 	int ret = -EINVAL;
6591 
6592 	switch (policy) {
6593 	case SCHED_FIFO:
6594 	case SCHED_RR:
6595 		ret = 1;
6596 		break;
6597 	case SCHED_DEADLINE:
6598 	case SCHED_NORMAL:
6599 	case SCHED_BATCH:
6600 	case SCHED_IDLE:
6601 		ret = 0;
6602 	}
6603 	return ret;
6604 }
6605 
sched_rr_get_interval(pid_t pid,struct timespec64 * t)6606 static int sched_rr_get_interval(pid_t pid, struct timespec64 *t)
6607 {
6608 	struct task_struct *p;
6609 	unsigned int time_slice;
6610 	struct rq_flags rf;
6611 	struct rq *rq;
6612 	int retval;
6613 
6614 	if (pid < 0)
6615 		return -EINVAL;
6616 
6617 	retval = -ESRCH;
6618 	rcu_read_lock();
6619 	p = find_process_by_pid(pid);
6620 	if (!p)
6621 		goto out_unlock;
6622 
6623 	retval = security_task_getscheduler(p);
6624 	if (retval)
6625 		goto out_unlock;
6626 
6627 	rq = task_rq_lock(p, &rf);
6628 	time_slice = 0;
6629 	if (p->sched_class->get_rr_interval)
6630 		time_slice = p->sched_class->get_rr_interval(rq, p);
6631 	task_rq_unlock(rq, p, &rf);
6632 
6633 	rcu_read_unlock();
6634 	jiffies_to_timespec64(time_slice, t);
6635 	return 0;
6636 
6637 out_unlock:
6638 	rcu_read_unlock();
6639 	return retval;
6640 }
6641 
6642 /**
6643  * sys_sched_rr_get_interval - return the default timeslice of a process.
6644  * @pid: pid of the process.
6645  * @interval: userspace pointer to the timeslice value.
6646  *
6647  * this syscall writes the default timeslice value of a given process
6648  * into the user-space timespec buffer. A value of '0' means infinity.
6649  *
6650  * Return: On success, 0 and the timeslice is in @interval. Otherwise,
6651  * an error code.
6652  */
SYSCALL_DEFINE2(sched_rr_get_interval,pid_t,pid,struct __kernel_timespec __user *,interval)6653 SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid,
6654 		struct __kernel_timespec __user *, interval)
6655 {
6656 	struct timespec64 t;
6657 	int retval = sched_rr_get_interval(pid, &t);
6658 
6659 	if (retval == 0)
6660 		retval = put_timespec64(&t, interval);
6661 
6662 	return retval;
6663 }
6664 
6665 #ifdef CONFIG_COMPAT_32BIT_TIME
SYSCALL_DEFINE2(sched_rr_get_interval_time32,pid_t,pid,struct old_timespec32 __user *,interval)6666 SYSCALL_DEFINE2(sched_rr_get_interval_time32, pid_t, pid,
6667 		struct old_timespec32 __user *, interval)
6668 {
6669 	struct timespec64 t;
6670 	int retval = sched_rr_get_interval(pid, &t);
6671 
6672 	if (retval == 0)
6673 		retval = put_old_timespec32(&t, interval);
6674 	return retval;
6675 }
6676 #endif
6677 
sched_show_task(struct task_struct * p)6678 void sched_show_task(struct task_struct *p)
6679 {
6680 	unsigned long free = 0;
6681 	int ppid;
6682 
6683 	if (!try_get_task_stack(p))
6684 		return;
6685 
6686 	pr_info("task:%-15.15s state:%c", p->comm, task_state_to_char(p));
6687 
6688 	if (p->state == TASK_RUNNING)
6689 		pr_cont("  running task    ");
6690 #ifdef CONFIG_DEBUG_STACK_USAGE
6691 	free = stack_not_used(p);
6692 #endif
6693 	ppid = 0;
6694 	rcu_read_lock();
6695 	if (pid_alive(p))
6696 		ppid = task_pid_nr(rcu_dereference(p->real_parent));
6697 	rcu_read_unlock();
6698 	pr_cont(" stack:%5lu pid:%5d ppid:%6d flags:0x%08lx\n",
6699 		free, task_pid_nr(p), ppid,
6700 		(unsigned long)task_thread_info(p)->flags);
6701 
6702 	print_worker_info(KERN_INFO, p);
6703 	show_stack(p, NULL, KERN_INFO);
6704 	put_task_stack(p);
6705 }
6706 EXPORT_SYMBOL_GPL(sched_show_task);
6707 
6708 static inline bool
state_filter_match(unsigned long state_filter,struct task_struct * p)6709 state_filter_match(unsigned long state_filter, struct task_struct *p)
6710 {
6711 	/* no filter, everything matches */
6712 	if (!state_filter)
6713 		return true;
6714 
6715 	/* filter, but doesn't match */
6716 	if (!(p->state & state_filter))
6717 		return false;
6718 
6719 	/*
6720 	 * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows
6721 	 * TASK_KILLABLE).
6722 	 */
6723 	if (state_filter == TASK_UNINTERRUPTIBLE && p->state == TASK_IDLE)
6724 		return false;
6725 
6726 	return true;
6727 }
6728 
6729 
show_state_filter(unsigned long state_filter)6730 void show_state_filter(unsigned long state_filter)
6731 {
6732 	struct task_struct *g, *p;
6733 
6734 	rcu_read_lock();
6735 	for_each_process_thread(g, p) {
6736 		/*
6737 		 * reset the NMI-timeout, listing all files on a slow
6738 		 * console might take a lot of time:
6739 		 * Also, reset softlockup watchdogs on all CPUs, because
6740 		 * another CPU might be blocked waiting for us to process
6741 		 * an IPI.
6742 		 */
6743 		touch_nmi_watchdog();
6744 		touch_all_softlockup_watchdogs();
6745 		if (state_filter_match(state_filter, p))
6746 			sched_show_task(p);
6747 	}
6748 
6749 #ifdef CONFIG_SCHED_DEBUG
6750 	if (!state_filter)
6751 		sysrq_sched_debug_show();
6752 #endif
6753 	rcu_read_unlock();
6754 	/*
6755 	 * Only show locks if all tasks are dumped:
6756 	 */
6757 	if (!state_filter)
6758 		debug_show_all_locks();
6759 }
6760 
6761 /**
6762  * init_idle - set up an idle thread for a given CPU
6763  * @idle: task in question
6764  * @cpu: CPU the idle task belongs to
6765  *
6766  * NOTE: this function does not set the idle thread's NEED_RESCHED
6767  * flag, to make booting more robust.
6768  */
init_idle(struct task_struct * idle,int cpu)6769 void __init init_idle(struct task_struct *idle, int cpu)
6770 {
6771 	struct rq *rq = cpu_rq(cpu);
6772 	unsigned long flags;
6773 
6774 	__sched_fork(0, idle);
6775 
6776 	raw_spin_lock_irqsave(&idle->pi_lock, flags);
6777 	raw_spin_lock(&rq->lock);
6778 
6779 	idle->state = TASK_RUNNING;
6780 	idle->se.exec_start = sched_clock();
6781 	idle->flags |= PF_IDLE;
6782 
6783 #ifdef CONFIG_SMP
6784 	/*
6785 	 * Its possible that init_idle() gets called multiple times on a task,
6786 	 * in that case do_set_cpus_allowed() will not do the right thing.
6787 	 *
6788 	 * And since this is boot we can forgo the serialization.
6789 	 */
6790 	set_cpus_allowed_common(idle, cpumask_of(cpu));
6791 #endif
6792 	/*
6793 	 * We're having a chicken and egg problem, even though we are
6794 	 * holding rq->lock, the CPU isn't yet set to this CPU so the
6795 	 * lockdep check in task_group() will fail.
6796 	 *
6797 	 * Similar case to sched_fork(). / Alternatively we could
6798 	 * use task_rq_lock() here and obtain the other rq->lock.
6799 	 *
6800 	 * Silence PROVE_RCU
6801 	 */
6802 	rcu_read_lock();
6803 	__set_task_cpu(idle, cpu);
6804 	rcu_read_unlock();
6805 
6806 	rq->idle = idle;
6807 	rcu_assign_pointer(rq->curr, idle);
6808 	idle->on_rq = TASK_ON_RQ_QUEUED;
6809 #ifdef CONFIG_SMP
6810 	idle->on_cpu = 1;
6811 #endif
6812 	raw_spin_unlock(&rq->lock);
6813 	raw_spin_unlock_irqrestore(&idle->pi_lock, flags);
6814 
6815 	/* Set the preempt count _outside_ the spinlocks! */
6816 	init_idle_preempt_count(idle, cpu);
6817 
6818 	/*
6819 	 * The idle tasks have their own, simple scheduling class:
6820 	 */
6821 	idle->sched_class = &idle_sched_class;
6822 	ftrace_graph_init_idle_task(idle, cpu);
6823 	vtime_init_idle(idle, cpu);
6824 #ifdef CONFIG_SMP
6825 	sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu);
6826 #endif
6827 }
6828 
6829 #ifdef CONFIG_SMP
6830 
cpuset_cpumask_can_shrink(const struct cpumask * cur,const struct cpumask * trial)6831 int cpuset_cpumask_can_shrink(const struct cpumask *cur,
6832 			      const struct cpumask *trial)
6833 {
6834 	int ret = 1;
6835 
6836 	if (!cpumask_weight(cur))
6837 		return ret;
6838 
6839 	ret = dl_cpuset_cpumask_can_shrink(cur, trial);
6840 
6841 	return ret;
6842 }
6843 
task_can_attach(struct task_struct * p)6844 int task_can_attach(struct task_struct *p)
6845 {
6846 	int ret = 0;
6847 
6848 	/*
6849 	 * Kthreads which disallow setaffinity shouldn't be moved
6850 	 * to a new cpuset; we don't want to change their CPU
6851 	 * affinity and isolating such threads by their set of
6852 	 * allowed nodes is unnecessary.  Thus, cpusets are not
6853 	 * applicable for such threads.  This prevents checking for
6854 	 * success of set_cpus_allowed_ptr() on all attached tasks
6855 	 * before cpus_mask may be changed.
6856 	 */
6857 	if (p->flags & PF_NO_SETAFFINITY)
6858 		ret = -EINVAL;
6859 
6860 	return ret;
6861 }
6862 
6863 bool sched_smp_initialized __read_mostly;
6864 
6865 #ifdef CONFIG_NUMA_BALANCING
6866 /* Migrate current task p to target_cpu */
migrate_task_to(struct task_struct * p,int target_cpu)6867 int migrate_task_to(struct task_struct *p, int target_cpu)
6868 {
6869 	struct migration_arg arg = { p, target_cpu };
6870 	int curr_cpu = task_cpu(p);
6871 
6872 	if (curr_cpu == target_cpu)
6873 		return 0;
6874 
6875 	if (!cpumask_test_cpu(target_cpu, p->cpus_ptr))
6876 		return -EINVAL;
6877 
6878 	/* TODO: This is not properly updating schedstats */
6879 
6880 	trace_sched_move_numa(p, curr_cpu, target_cpu);
6881 	return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg);
6882 }
6883 
6884 /*
6885  * Requeue a task on a given node and accurately track the number of NUMA
6886  * tasks on the runqueues
6887  */
sched_setnuma(struct task_struct * p,int nid)6888 void sched_setnuma(struct task_struct *p, int nid)
6889 {
6890 	bool queued, running;
6891 	struct rq_flags rf;
6892 	struct rq *rq;
6893 
6894 	rq = task_rq_lock(p, &rf);
6895 	queued = task_on_rq_queued(p);
6896 	running = task_current(rq, p);
6897 
6898 	if (queued)
6899 		dequeue_task(rq, p, DEQUEUE_SAVE);
6900 	if (running)
6901 		put_prev_task(rq, p);
6902 
6903 	p->numa_preferred_nid = nid;
6904 
6905 	if (queued)
6906 		enqueue_task(rq, p, ENQUEUE_RESTORE | ENQUEUE_NOCLOCK);
6907 	if (running)
6908 		set_next_task(rq, p);
6909 	task_rq_unlock(rq, p, &rf);
6910 }
6911 #endif /* CONFIG_NUMA_BALANCING */
6912 
6913 #ifdef CONFIG_HOTPLUG_CPU
6914 /*
6915  * Ensure that the idle task is using init_mm right before its CPU goes
6916  * offline.
6917  */
idle_task_exit(void)6918 void idle_task_exit(void)
6919 {
6920 	struct mm_struct *mm = current->active_mm;
6921 
6922 	BUG_ON(cpu_online(smp_processor_id()));
6923 	BUG_ON(current != this_rq()->idle);
6924 
6925 	if (mm != &init_mm) {
6926 		switch_mm(mm, &init_mm, current);
6927 		finish_arch_post_lock_switch();
6928 	}
6929 
6930 	/* finish_cpu(), as ran on the BP, will clean up the active_mm state */
6931 }
6932 
6933 /*
6934  * Since this CPU is going 'away' for a while, fold any nr_active delta
6935  * we might have. Assumes we're called after migrate_tasks() so that the
6936  * nr_active count is stable. We need to take the teardown thread which
6937  * is calling this into account, so we hand in adjust = 1 to the load
6938  * calculation.
6939  *
6940  * Also see the comment "Global load-average calculations".
6941  */
calc_load_migrate(struct rq * rq)6942 static void calc_load_migrate(struct rq *rq)
6943 {
6944 	long delta = calc_load_fold_active(rq, 1);
6945 	if (delta)
6946 		atomic_long_add(delta, &calc_load_tasks);
6947 }
6948 
__pick_migrate_task(struct rq * rq)6949 static struct task_struct *__pick_migrate_task(struct rq *rq)
6950 {
6951 	const struct sched_class *class;
6952 	struct task_struct *next;
6953 
6954 	for_each_class(class) {
6955 		next = class->pick_next_task(rq);
6956 		if (next) {
6957 			next->sched_class->put_prev_task(rq, next);
6958 			return next;
6959 		}
6960 	}
6961 
6962 	/* The idle class should always have a runnable task */
6963 	BUG();
6964 }
6965 
6966 #ifdef CONFIG_CPU_ISOLATION_OPT
6967 /*
6968  * Remove a task from the runqueue and pretend that it's migrating. This
6969  * should prevent migrations for the detached task and disallow further
6970  * changes to tsk_cpus_allowed.
6971  */
6972 static void
detach_one_task_core(struct task_struct * p,struct rq * rq,struct list_head * tasks)6973 detach_one_task_core(struct task_struct *p, struct rq *rq,
6974 		     struct list_head *tasks)
6975 {
6976 	lockdep_assert_held(&rq->lock);
6977 
6978 	p->on_rq = TASK_ON_RQ_MIGRATING;
6979 	deactivate_task(rq, p, 0);
6980 	list_add(&p->se.group_node, tasks);
6981 }
6982 
attach_tasks_core(struct list_head * tasks,struct rq * rq)6983 static void attach_tasks_core(struct list_head *tasks, struct rq *rq)
6984 {
6985 	struct task_struct *p;
6986 
6987 	lockdep_assert_held(&rq->lock);
6988 
6989 	while (!list_empty(tasks)) {
6990 		p = list_first_entry(tasks, struct task_struct, se.group_node);
6991 		list_del_init(&p->se.group_node);
6992 
6993 		BUG_ON(task_rq(p) != rq);
6994 		activate_task(rq, p, 0);
6995 		p->on_rq = TASK_ON_RQ_QUEUED;
6996 	}
6997 }
6998 
6999 #else
7000 
7001 static void
detach_one_task_core(struct task_struct * p,struct rq * rq,struct list_head * tasks)7002 detach_one_task_core(struct task_struct *p, struct rq *rq,
7003 		     struct list_head *tasks)
7004 {
7005 }
7006 
attach_tasks_core(struct list_head * tasks,struct rq * rq)7007 static void attach_tasks_core(struct list_head *tasks, struct rq *rq)
7008 {
7009 }
7010 
7011 #endif /* CONFIG_CPU_ISOLATION_OPT */
7012 
7013 /*
7014  * Migrate all tasks (not pinned if pinned argument say so) from the rq,
7015  * sleeping tasks will be migrated by try_to_wake_up()->select_task_rq().
7016  *
7017  * Called with rq->lock held even though we'er in stop_machine() and
7018  * there's no concurrency possible, we hold the required locks anyway
7019  * because of lock validation efforts.
7020  */
migrate_tasks(struct rq * dead_rq,struct rq_flags * rf,bool migrate_pinned_tasks)7021 void migrate_tasks(struct rq *dead_rq, struct rq_flags *rf,
7022 			  bool migrate_pinned_tasks)
7023 {
7024 	struct rq *rq = dead_rq;
7025 	struct task_struct *next, *stop = rq->stop;
7026 	struct rq_flags orf = *rf;
7027 	int dest_cpu;
7028 	unsigned int num_pinned_kthreads = 1; /* this thread */
7029 	LIST_HEAD(tasks);
7030 	cpumask_t avail_cpus;
7031 
7032 #ifdef CONFIG_CPU_ISOLATION_OPT
7033 	cpumask_andnot(&avail_cpus, cpu_online_mask, cpu_isolated_mask);
7034 #else
7035 	cpumask_copy(&avail_cpus, cpu_online_mask);
7036 #endif
7037 
7038 	/*
7039 	 * Fudge the rq selection such that the below task selection loop
7040 	 * doesn't get stuck on the currently eligible stop task.
7041 	 *
7042 	 * We're currently inside stop_machine() and the rq is either stuck
7043 	 * in the stop_machine_cpu_stop() loop, or we're executing this code,
7044 	 * either way we should never end up calling schedule() until we're
7045 	 * done here.
7046 	 */
7047 	rq->stop = NULL;
7048 
7049 	/*
7050 	 * put_prev_task() and pick_next_task() sched
7051 	 * class method both need to have an up-to-date
7052 	 * value of rq->clock[_task]
7053 	 */
7054 	update_rq_clock(rq);
7055 
7056 	for (;;) {
7057 		/*
7058 		 * There's this thread running, bail when that's the only
7059 		 * remaining thread.
7060 		 */
7061 		if (rq->nr_running == 1)
7062 			break;
7063 
7064 		next = __pick_migrate_task(rq);
7065 
7066 		if (!migrate_pinned_tasks && next->flags & PF_KTHREAD &&
7067 			!cpumask_intersects(&avail_cpus, &next->cpus_mask)) {
7068 			detach_one_task_core(next, rq, &tasks);
7069 			num_pinned_kthreads += 1;
7070 			continue;
7071 		}
7072 
7073 		/*
7074 		 * Rules for changing task_struct::cpus_mask are holding
7075 		 * both pi_lock and rq->lock, such that holding either
7076 		 * stabilizes the mask.
7077 		 *
7078 		 * Drop rq->lock is not quite as disastrous as it usually is
7079 		 * because !cpu_active at this point, which means load-balance
7080 		 * will not interfere. Also, stop-machine.
7081 		 */
7082 		rq_unlock(rq, rf);
7083 		raw_spin_lock(&next->pi_lock);
7084 		rq_relock(rq, rf);
7085 		if (!(rq->clock_update_flags & RQCF_UPDATED))
7086 			update_rq_clock(rq);
7087 
7088 		/*
7089 		 * Since we're inside stop-machine, _nothing_ should have
7090 		 * changed the task, WARN if weird stuff happened, because in
7091 		 * that case the above rq->lock drop is a fail too.
7092 		 * However, during cpu isolation the load balancer might have
7093 		 * interferred since we don't stop all CPUs. Ignore warning for
7094 		 * this case.
7095 		 */
7096 		if (task_rq(next) != rq || !task_on_rq_queued(next)) {
7097 			WARN_ON(migrate_pinned_tasks);
7098 			raw_spin_unlock(&next->pi_lock);
7099 			continue;
7100 		}
7101 
7102 		/* Find suitable destination for @next, with force if needed. */
7103 #ifdef CONFIG_CPU_ISOLATION_OPT
7104 		dest_cpu = select_fallback_rq(dead_rq->cpu, next, false);
7105 #else
7106 		dest_cpu = select_fallback_rq(dead_rq->cpu, next);
7107 #endif
7108 		rq = __migrate_task(rq, rf, next, dest_cpu);
7109 		if (rq != dead_rq) {
7110 			rq_unlock(rq, rf);
7111 			rq = dead_rq;
7112 			*rf = orf;
7113 			rq_relock(rq, rf);
7114 			if (!(rq->clock_update_flags & RQCF_UPDATED))
7115 				update_rq_clock(rq);
7116 		}
7117 		raw_spin_unlock(&next->pi_lock);
7118 	}
7119 
7120 	rq->stop = stop;
7121 
7122 	if (num_pinned_kthreads > 1)
7123 		attach_tasks_core(&tasks, rq);
7124 }
7125 
7126 #ifdef CONFIG_SCHED_EAS
clear_eas_migration_request(int cpu)7127 static void clear_eas_migration_request(int cpu)
7128 {
7129 	struct rq *rq = cpu_rq(cpu);
7130 	unsigned long flags;
7131 
7132 	clear_reserved(cpu);
7133 	if (rq->push_task) {
7134 		struct task_struct *push_task = NULL;
7135 
7136 		raw_spin_lock_irqsave(&rq->lock, flags);
7137 		if (rq->push_task) {
7138 			clear_reserved(rq->push_cpu);
7139 			push_task = rq->push_task;
7140 			rq->push_task = NULL;
7141 		}
7142 		rq->active_balance = 0;
7143 		raw_spin_unlock_irqrestore(&rq->lock, flags);
7144 		if (push_task)
7145 			put_task_struct(push_task);
7146 	}
7147 }
7148 #else
clear_eas_migration_request(int cpu)7149 static inline void clear_eas_migration_request(int cpu) {}
7150 #endif
7151 
7152 #ifdef CONFIG_CPU_ISOLATION_OPT
do_isolation_work_cpu_stop(void * data)7153 int do_isolation_work_cpu_stop(void *data)
7154 {
7155 	unsigned int cpu = smp_processor_id();
7156 	struct rq *rq = cpu_rq(cpu);
7157 	struct rq_flags rf;
7158 
7159 	watchdog_disable(cpu);
7160 
7161 	local_irq_disable();
7162 
7163 	irq_migrate_all_off_this_cpu();
7164 
7165 	flush_smp_call_function_from_idle();
7166 
7167 	/* Update our root-domain */
7168 	rq_lock(rq, &rf);
7169 
7170 	/*
7171 	 * Temporarily mark the rq as offline. This will allow us to
7172 	 * move tasks off the CPU.
7173 	 */
7174 	if (rq->rd) {
7175 		BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7176 		set_rq_offline(rq);
7177 	}
7178 
7179 	migrate_tasks(rq, &rf, false);
7180 
7181 	if (rq->rd)
7182 		set_rq_online(rq);
7183 	rq_unlock(rq, &rf);
7184 
7185 	clear_eas_migration_request(cpu);
7186 	local_irq_enable();
7187 	return 0;
7188 }
7189 
do_unisolation_work_cpu_stop(void * data)7190 int do_unisolation_work_cpu_stop(void *data)
7191 {
7192 	watchdog_enable(smp_processor_id());
7193 	return 0;
7194 }
7195 
sched_update_group_capacities(int cpu)7196 static void sched_update_group_capacities(int cpu)
7197 {
7198 	struct sched_domain *sd;
7199 
7200 	mutex_lock(&sched_domains_mutex);
7201 	rcu_read_lock();
7202 
7203 	for_each_domain(cpu, sd) {
7204 		int balance_cpu = group_balance_cpu(sd->groups);
7205 
7206 		init_sched_groups_capacity(cpu, sd);
7207 		/*
7208 		 * Need to ensure this is also called with balancing
7209 		 * cpu.
7210 		 */
7211 		if (cpu != balance_cpu)
7212 			init_sched_groups_capacity(balance_cpu, sd);
7213 	}
7214 
7215 	rcu_read_unlock();
7216 	mutex_unlock(&sched_domains_mutex);
7217 }
7218 
7219 static unsigned int cpu_isolation_vote[NR_CPUS];
7220 
sched_isolate_count(const cpumask_t * mask,bool include_offline)7221 int sched_isolate_count(const cpumask_t *mask, bool include_offline)
7222 {
7223 	cpumask_t count_mask = CPU_MASK_NONE;
7224 
7225 	if (include_offline) {
7226 		cpumask_complement(&count_mask, cpu_online_mask);
7227 		cpumask_or(&count_mask, &count_mask, cpu_isolated_mask);
7228 		cpumask_and(&count_mask, &count_mask, mask);
7229 	} else {
7230 		cpumask_and(&count_mask, mask, cpu_isolated_mask);
7231 	}
7232 
7233 	return cpumask_weight(&count_mask);
7234 }
7235 
7236 /*
7237  * 1) CPU is isolated and cpu is offlined:
7238  *	Unisolate the core.
7239  * 2) CPU is not isolated and CPU is offlined:
7240  *	No action taken.
7241  * 3) CPU is offline and request to isolate
7242  *	Request ignored.
7243  * 4) CPU is offline and isolated:
7244  *	Not a possible state.
7245  * 5) CPU is online and request to isolate
7246  *	Normal case: Isolate the CPU
7247  * 6) CPU is not isolated and comes back online
7248  *	Nothing to do
7249  *
7250  * Note: The client calling sched_isolate_cpu() is repsonsible for ONLY
7251  * calling sched_unisolate_cpu() on a CPU that the client previously isolated.
7252  * Client is also responsible for unisolating when a core goes offline
7253  * (after CPU is marked offline).
7254  */
sched_isolate_cpu(int cpu)7255 int sched_isolate_cpu(int cpu)
7256 {
7257 	struct rq *rq;
7258 	cpumask_t avail_cpus;
7259 	int ret_code = 0;
7260 	u64 start_time = 0;
7261 
7262 	if (trace_sched_isolate_enabled())
7263 		start_time = sched_clock();
7264 
7265 	cpu_maps_update_begin();
7266 
7267 	cpumask_andnot(&avail_cpus, cpu_online_mask, cpu_isolated_mask);
7268 
7269 	if (cpu < 0 || cpu >= nr_cpu_ids || !cpu_possible(cpu) ||
7270 				!cpu_online(cpu) || cpu >= NR_CPUS) {
7271 		ret_code = -EINVAL;
7272 		goto out;
7273 	}
7274 
7275 	rq = cpu_rq(cpu);
7276 
7277 	if (++cpu_isolation_vote[cpu] > 1)
7278 		goto out;
7279 
7280 	/* We cannot isolate ALL cpus in the system */
7281 	if (cpumask_weight(&avail_cpus) == 1) {
7282 		--cpu_isolation_vote[cpu];
7283 		ret_code = -EINVAL;
7284 		goto out;
7285 	}
7286 
7287 	/*
7288 	 * There is a race between watchdog being enabled by hotplug and
7289 	 * core isolation disabling the watchdog. When a CPU is hotplugged in
7290 	 * and the hotplug lock has been released the watchdog thread might
7291 	 * not have run yet to enable the watchdog.
7292 	 * We have to wait for the watchdog to be enabled before proceeding.
7293 	 */
7294 	if (!watchdog_configured(cpu)) {
7295 		msleep(20);
7296 		if (!watchdog_configured(cpu)) {
7297 			--cpu_isolation_vote[cpu];
7298 			ret_code = -EBUSY;
7299 			goto out;
7300 		}
7301 	}
7302 
7303 	set_cpu_isolated(cpu, true);
7304 	cpumask_clear_cpu(cpu, &avail_cpus);
7305 
7306 	/* Migrate timers */
7307 	smp_call_function_any(&avail_cpus, hrtimer_quiesce_cpu, &cpu, 1);
7308 	smp_call_function_any(&avail_cpus, timer_quiesce_cpu, &cpu, 1);
7309 
7310 	watchdog_disable(cpu);
7311 	irq_lock_sparse();
7312 	stop_cpus(cpumask_of(cpu), do_isolation_work_cpu_stop, 0);
7313 	irq_unlock_sparse();
7314 
7315 	calc_load_migrate(rq);
7316 	update_max_interval();
7317 	sched_update_group_capacities(cpu);
7318 
7319 out:
7320 	cpu_maps_update_done();
7321 	trace_sched_isolate(cpu, cpumask_bits(cpu_isolated_mask)[0],
7322 			    start_time, 1);
7323 	return ret_code;
7324 }
7325 
7326 /*
7327  * Note: The client calling sched_isolate_cpu() is repsonsible for ONLY
7328  * calling sched_unisolate_cpu() on a CPU that the client previously isolated.
7329  * Client is also responsible for unisolating when a core goes offline
7330  * (after CPU is marked offline).
7331  */
sched_unisolate_cpu_unlocked(int cpu)7332 int sched_unisolate_cpu_unlocked(int cpu)
7333 {
7334 	int ret_code = 0;
7335 	u64 start_time = 0;
7336 
7337 	if (cpu < 0 || cpu >= nr_cpu_ids || !cpu_possible(cpu)
7338 						|| cpu >= NR_CPUS) {
7339 		ret_code = -EINVAL;
7340 		goto out;
7341 	}
7342 
7343 	if (trace_sched_isolate_enabled())
7344 		start_time = sched_clock();
7345 
7346 	if (!cpu_isolation_vote[cpu]) {
7347 		ret_code = -EINVAL;
7348 		goto out;
7349 	}
7350 
7351 	if (--cpu_isolation_vote[cpu])
7352 		goto out;
7353 
7354 	set_cpu_isolated(cpu, false);
7355 	update_max_interval();
7356 	sched_update_group_capacities(cpu);
7357 
7358 	if (cpu_online(cpu)) {
7359 		stop_cpus(cpumask_of(cpu), do_unisolation_work_cpu_stop, 0);
7360 
7361 		/* Kick CPU to immediately do load balancing */
7362 		if (!atomic_fetch_or(NOHZ_KICK_MASK, nohz_flags(cpu)))
7363 			smp_send_reschedule(cpu);
7364 	}
7365 
7366 out:
7367 	trace_sched_isolate(cpu, cpumask_bits(cpu_isolated_mask)[0],
7368 			    start_time, 0);
7369 	return ret_code;
7370 }
7371 
sched_unisolate_cpu(int cpu)7372 int sched_unisolate_cpu(int cpu)
7373 {
7374 	int ret_code;
7375 
7376 	cpu_maps_update_begin();
7377 	ret_code = sched_unisolate_cpu_unlocked(cpu);
7378 	cpu_maps_update_done();
7379 	return ret_code;
7380 }
7381 
7382 #endif /* CONFIG_CPU_ISOLATION_OPT */
7383 
7384 #endif /* CONFIG_HOTPLUG_CPU */
7385 
set_rq_online(struct rq * rq)7386 void set_rq_online(struct rq *rq)
7387 {
7388 	if (!rq->online) {
7389 		const struct sched_class *class;
7390 
7391 		cpumask_set_cpu(rq->cpu, rq->rd->online);
7392 		rq->online = 1;
7393 
7394 		for_each_class(class) {
7395 			if (class->rq_online)
7396 				class->rq_online(rq);
7397 		}
7398 	}
7399 }
7400 
set_rq_offline(struct rq * rq)7401 void set_rq_offline(struct rq *rq)
7402 {
7403 	if (rq->online) {
7404 		const struct sched_class *class;
7405 
7406 		for_each_class(class) {
7407 			if (class->rq_offline)
7408 				class->rq_offline(rq);
7409 		}
7410 
7411 		cpumask_clear_cpu(rq->cpu, rq->rd->online);
7412 		rq->online = 0;
7413 	}
7414 }
7415 
7416 /*
7417  * used to mark begin/end of suspend/resume:
7418  */
7419 static int num_cpus_frozen;
7420 
7421 /*
7422  * Update cpusets according to cpu_active mask.  If cpusets are
7423  * disabled, cpuset_update_active_cpus() becomes a simple wrapper
7424  * around partition_sched_domains().
7425  *
7426  * If we come here as part of a suspend/resume, don't touch cpusets because we
7427  * want to restore it back to its original state upon resume anyway.
7428  */
cpuset_cpu_active(void)7429 static void cpuset_cpu_active(void)
7430 {
7431 	if (cpuhp_tasks_frozen) {
7432 		/*
7433 		 * num_cpus_frozen tracks how many CPUs are involved in suspend
7434 		 * resume sequence. As long as this is not the last online
7435 		 * operation in the resume sequence, just build a single sched
7436 		 * domain, ignoring cpusets.
7437 		 */
7438 		partition_sched_domains(1, NULL, NULL);
7439 		if (--num_cpus_frozen)
7440 			return;
7441 		/*
7442 		 * This is the last CPU online operation. So fall through and
7443 		 * restore the original sched domains by considering the
7444 		 * cpuset configurations.
7445 		 */
7446 		cpuset_force_rebuild();
7447 	}
7448 	cpuset_update_active_cpus();
7449 }
7450 
cpuset_cpu_inactive(unsigned int cpu)7451 static int cpuset_cpu_inactive(unsigned int cpu)
7452 {
7453 	if (!cpuhp_tasks_frozen) {
7454 		int ret = dl_bw_check_overflow(cpu);
7455 
7456 		if (ret)
7457 			return ret;
7458 		cpuset_update_active_cpus();
7459 	} else {
7460 		num_cpus_frozen++;
7461 		partition_sched_domains(1, NULL, NULL);
7462 	}
7463 	return 0;
7464 }
7465 
sched_cpu_activate(unsigned int cpu)7466 int sched_cpu_activate(unsigned int cpu)
7467 {
7468 	struct rq *rq = cpu_rq(cpu);
7469 	struct rq_flags rf;
7470 
7471 #ifdef CONFIG_SCHED_SMT
7472 	/*
7473 	 * When going up, increment the number of cores with SMT present.
7474 	 */
7475 	if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
7476 		static_branch_inc_cpuslocked(&sched_smt_present);
7477 #endif
7478 	set_cpu_active(cpu, true);
7479 
7480 	if (sched_smp_initialized) {
7481 		sched_domains_numa_masks_set(cpu);
7482 		cpuset_cpu_active();
7483 	}
7484 
7485 	/*
7486 	 * Put the rq online, if not already. This happens:
7487 	 *
7488 	 * 1) In the early boot process, because we build the real domains
7489 	 *    after all CPUs have been brought up.
7490 	 *
7491 	 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the
7492 	 *    domains.
7493 	 */
7494 	rq_lock_irqsave(rq, &rf);
7495 	if (rq->rd) {
7496 		BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7497 		set_rq_online(rq);
7498 	}
7499 	rq_unlock_irqrestore(rq, &rf);
7500 
7501 	return 0;
7502 }
7503 
sched_cpu_deactivate(unsigned int cpu)7504 int sched_cpu_deactivate(unsigned int cpu)
7505 {
7506 	int ret;
7507 
7508 	set_cpu_active(cpu, false);
7509 	/*
7510 	 * We've cleared cpu_active_mask, wait for all preempt-disabled and RCU
7511 	 * users of this state to go away such that all new such users will
7512 	 * observe it.
7513 	 *
7514 	 * Do sync before park smpboot threads to take care the rcu boost case.
7515 	 */
7516 	synchronize_rcu();
7517 
7518 #ifdef CONFIG_SCHED_SMT
7519 	/*
7520 	 * When going down, decrement the number of cores with SMT present.
7521 	 */
7522 	if (cpumask_weight(cpu_smt_mask(cpu)) == 2)
7523 		static_branch_dec_cpuslocked(&sched_smt_present);
7524 #endif
7525 
7526 	if (!sched_smp_initialized)
7527 		return 0;
7528 
7529 	ret = cpuset_cpu_inactive(cpu);
7530 	if (ret) {
7531 		set_cpu_active(cpu, true);
7532 		return ret;
7533 	}
7534 	sched_domains_numa_masks_clear(cpu);
7535 	return 0;
7536 }
7537 
sched_rq_cpu_starting(unsigned int cpu)7538 static void sched_rq_cpu_starting(unsigned int cpu)
7539 {
7540 	struct rq *rq = cpu_rq(cpu);
7541 	unsigned long flags;
7542 
7543 	raw_spin_lock_irqsave(&rq->lock, flags);
7544 	set_window_start(rq);
7545 	raw_spin_unlock_irqrestore(&rq->lock, flags);
7546 
7547 	rq->calc_load_update = calc_load_update;
7548 	update_max_interval();
7549 }
7550 
sched_cpu_starting(unsigned int cpu)7551 int sched_cpu_starting(unsigned int cpu)
7552 {
7553 	sched_rq_cpu_starting(cpu);
7554 	sched_tick_start(cpu);
7555 	clear_eas_migration_request(cpu);
7556 	return 0;
7557 }
7558 
7559 #ifdef CONFIG_HOTPLUG_CPU
sched_cpu_dying(unsigned int cpu)7560 int sched_cpu_dying(unsigned int cpu)
7561 {
7562 	struct rq *rq = cpu_rq(cpu);
7563 	struct rq_flags rf;
7564 
7565 	/* Handle pending wakeups and then migrate everything off */
7566 	sched_tick_stop(cpu);
7567 
7568 	rq_lock_irqsave(rq, &rf);
7569 
7570 	if (rq->rd) {
7571 		BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span));
7572 		set_rq_offline(rq);
7573 	}
7574 	migrate_tasks(rq, &rf, true);
7575 	BUG_ON(rq->nr_running != 1);
7576 	rq_unlock_irqrestore(rq, &rf);
7577 
7578 	clear_eas_migration_request(cpu);
7579 
7580 	calc_load_migrate(rq);
7581 	update_max_interval();
7582 	nohz_balance_exit_idle(rq);
7583 	hrtick_clear(rq);
7584 	return 0;
7585 }
7586 #endif
7587 
sched_init_smp(void)7588 void __init sched_init_smp(void)
7589 {
7590 	sched_init_numa();
7591 
7592 	/*
7593 	 * There's no userspace yet to cause hotplug operations; hence all the
7594 	 * CPU masks are stable and all blatant races in the below code cannot
7595 	 * happen.
7596 	 */
7597 	mutex_lock(&sched_domains_mutex);
7598 	sched_init_domains(cpu_active_mask);
7599 	mutex_unlock(&sched_domains_mutex);
7600 
7601 	update_cluster_topology();
7602 
7603 	/* Move init over to a non-isolated CPU */
7604 	if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_FLAG_DOMAIN)) < 0)
7605 		BUG();
7606 	sched_init_granularity();
7607 
7608 	init_sched_rt_class();
7609 	init_sched_dl_class();
7610 
7611 	sched_smp_initialized = true;
7612 }
7613 
migration_init(void)7614 static int __init migration_init(void)
7615 {
7616 	sched_cpu_starting(smp_processor_id());
7617 	return 0;
7618 }
7619 early_initcall(migration_init);
7620 
7621 #else
sched_init_smp(void)7622 void __init sched_init_smp(void)
7623 {
7624 	sched_init_granularity();
7625 }
7626 #endif /* CONFIG_SMP */
7627 
in_sched_functions(unsigned long addr)7628 int in_sched_functions(unsigned long addr)
7629 {
7630 	return in_lock_functions(addr) ||
7631 		(addr >= (unsigned long)__sched_text_start
7632 		&& addr < (unsigned long)__sched_text_end);
7633 }
7634 
7635 #ifdef CONFIG_CGROUP_SCHED
7636 /*
7637  * Default task group.
7638  * Every task in system belongs to this group at bootup.
7639  */
7640 struct task_group root_task_group;
7641 LIST_HEAD(task_groups);
7642 
7643 /* Cacheline aligned slab cache for task_group */
7644 static struct kmem_cache *task_group_cache __read_mostly;
7645 #endif
7646 
7647 DECLARE_PER_CPU(cpumask_var_t, load_balance_mask);
7648 DECLARE_PER_CPU(cpumask_var_t, select_idle_mask);
7649 
sched_init(void)7650 void __init sched_init(void)
7651 {
7652 	unsigned long ptr = 0;
7653 	int i;
7654 
7655 	/* Make sure the linker didn't screw up */
7656 	BUG_ON(&idle_sched_class + 1 != &fair_sched_class ||
7657 	       &fair_sched_class + 1 != &rt_sched_class ||
7658 	       &rt_sched_class + 1   != &dl_sched_class);
7659 #ifdef CONFIG_SMP
7660 	BUG_ON(&dl_sched_class + 1 != &stop_sched_class);
7661 #endif
7662 
7663 	wait_bit_init();
7664 
7665 	init_clusters();
7666 
7667 #ifdef CONFIG_FAIR_GROUP_SCHED
7668 	ptr += 2 * nr_cpu_ids * sizeof(void **);
7669 #endif
7670 #ifdef CONFIG_RT_GROUP_SCHED
7671 	ptr += 2 * nr_cpu_ids * sizeof(void **);
7672 #endif
7673 	if (ptr) {
7674 		ptr = (unsigned long)kzalloc(ptr, GFP_NOWAIT);
7675 
7676 #ifdef CONFIG_FAIR_GROUP_SCHED
7677 		root_task_group.se = (struct sched_entity **)ptr;
7678 		ptr += nr_cpu_ids * sizeof(void **);
7679 
7680 		root_task_group.cfs_rq = (struct cfs_rq **)ptr;
7681 		ptr += nr_cpu_ids * sizeof(void **);
7682 
7683 		root_task_group.shares = ROOT_TASK_GROUP_LOAD;
7684 		init_cfs_bandwidth(&root_task_group.cfs_bandwidth);
7685 #endif /* CONFIG_FAIR_GROUP_SCHED */
7686 #ifdef CONFIG_RT_GROUP_SCHED
7687 		root_task_group.rt_se = (struct sched_rt_entity **)ptr;
7688 		ptr += nr_cpu_ids * sizeof(void **);
7689 
7690 		root_task_group.rt_rq = (struct rt_rq **)ptr;
7691 		ptr += nr_cpu_ids * sizeof(void **);
7692 
7693 #endif /* CONFIG_RT_GROUP_SCHED */
7694 	}
7695 #ifdef CONFIG_CPUMASK_OFFSTACK
7696 	for_each_possible_cpu(i) {
7697 		per_cpu(load_balance_mask, i) = (cpumask_var_t)kzalloc_node(
7698 			cpumask_size(), GFP_KERNEL, cpu_to_node(i));
7699 		per_cpu(select_idle_mask, i) = (cpumask_var_t)kzalloc_node(
7700 			cpumask_size(), GFP_KERNEL, cpu_to_node(i));
7701 	}
7702 #endif /* CONFIG_CPUMASK_OFFSTACK */
7703 
7704 	init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime());
7705 	init_dl_bandwidth(&def_dl_bandwidth, global_rt_period(), global_rt_runtime());
7706 
7707 #ifdef CONFIG_SMP
7708 	init_defrootdomain();
7709 #endif
7710 
7711 #ifdef CONFIG_RT_GROUP_SCHED
7712 	init_rt_bandwidth(&root_task_group.rt_bandwidth,
7713 			global_rt_period(), global_rt_runtime());
7714 #endif /* CONFIG_RT_GROUP_SCHED */
7715 
7716 #ifdef CONFIG_CGROUP_SCHED
7717 	task_group_cache = KMEM_CACHE(task_group, 0);
7718 
7719 	list_add(&root_task_group.list, &task_groups);
7720 	INIT_LIST_HEAD(&root_task_group.children);
7721 	INIT_LIST_HEAD(&root_task_group.siblings);
7722 	autogroup_init(&init_task);
7723 #endif /* CONFIG_CGROUP_SCHED */
7724 
7725 	for_each_possible_cpu(i) {
7726 		struct rq *rq;
7727 
7728 		rq = cpu_rq(i);
7729 		raw_spin_lock_init(&rq->lock);
7730 		rq->nr_running = 0;
7731 		rq->calc_load_active = 0;
7732 		rq->calc_load_update = jiffies + LOAD_FREQ;
7733 		init_cfs_rq(&rq->cfs);
7734 		init_rt_rq(&rq->rt);
7735 		init_dl_rq(&rq->dl);
7736 #ifdef CONFIG_FAIR_GROUP_SCHED
7737 		INIT_LIST_HEAD(&rq->leaf_cfs_rq_list);
7738 		rq->tmp_alone_branch = &rq->leaf_cfs_rq_list;
7739 		/*
7740 		 * How much CPU bandwidth does root_task_group get?
7741 		 *
7742 		 * In case of task-groups formed thr' the cgroup filesystem, it
7743 		 * gets 100% of the CPU resources in the system. This overall
7744 		 * system CPU resource is divided among the tasks of
7745 		 * root_task_group and its child task-groups in a fair manner,
7746 		 * based on each entity's (task or task-group's) weight
7747 		 * (se->load.weight).
7748 		 *
7749 		 * In other words, if root_task_group has 10 tasks of weight
7750 		 * 1024) and two child groups A0 and A1 (of weight 1024 each),
7751 		 * then A0's share of the CPU resource is:
7752 		 *
7753 		 *	A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33%
7754 		 *
7755 		 * We achieve this by letting root_task_group's tasks sit
7756 		 * directly in rq->cfs (i.e root_task_group->se[] = NULL).
7757 		 */
7758 		init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL);
7759 #endif /* CONFIG_FAIR_GROUP_SCHED */
7760 
7761 		rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime;
7762 #ifdef CONFIG_RT_GROUP_SCHED
7763 		init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL);
7764 #endif
7765 #ifdef CONFIG_SMP
7766 		rq->sd = NULL;
7767 		rq->rd = NULL;
7768 		rq->cpu_capacity = rq->cpu_capacity_orig = SCHED_CAPACITY_SCALE;
7769 		rq->balance_callback = NULL;
7770 		rq->active_balance = 0;
7771 		rq->next_balance = jiffies;
7772 		rq->push_cpu = 0;
7773 		rq->cpu = i;
7774 		rq->online = 0;
7775 		rq->idle_stamp = 0;
7776 		rq->avg_idle = 2*sysctl_sched_migration_cost;
7777 		rq->max_idle_balance_cost = sysctl_sched_migration_cost;
7778 		walt_sched_init_rq(rq);
7779 
7780 		INIT_LIST_HEAD(&rq->cfs_tasks);
7781 
7782 		rq_attach_root(rq, &def_root_domain);
7783 #ifdef CONFIG_NO_HZ_COMMON
7784 		rq->last_blocked_load_update_tick = jiffies;
7785 		atomic_set(&rq->nohz_flags, 0);
7786 
7787 		rq_csd_init(rq, &rq->nohz_csd, nohz_csd_func);
7788 #endif
7789 #endif /* CONFIG_SMP */
7790 		hrtick_rq_init(rq);
7791 		atomic_set(&rq->nr_iowait, 0);
7792 	}
7793 
7794 	BUG_ON(alloc_related_thread_groups());
7795 	set_load_weight(&init_task);
7796 
7797 	/*
7798 	 * The boot idle thread does lazy MMU switching as well:
7799 	 */
7800 	mmgrab(&init_mm);
7801 	enter_lazy_tlb(&init_mm, current);
7802 
7803 	/*
7804 	 * Make us the idle thread. Technically, schedule() should not be
7805 	 * called from this thread, however somewhere below it might be,
7806 	 * but because we are the idle thread, we just pick up running again
7807 	 * when this runqueue becomes "idle".
7808 	 */
7809 	init_idle(current, smp_processor_id());
7810 	init_new_task_load(current);
7811 
7812 #ifdef CONIG_QOS_CTRL
7813 	init_task_qos(current);
7814 #endif
7815 
7816 	calc_load_update = jiffies + LOAD_FREQ;
7817 
7818 #ifdef CONFIG_SMP
7819 	idle_thread_set_boot_cpu();
7820 #endif
7821 	init_sched_fair_class();
7822 
7823 	init_schedstats();
7824 
7825 	psi_init();
7826 
7827 	init_uclamp();
7828 
7829 	scheduler_running = 1;
7830 }
7831 
7832 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP
preempt_count_equals(int preempt_offset)7833 static inline int preempt_count_equals(int preempt_offset)
7834 {
7835 	int nested = preempt_count() + rcu_preempt_depth();
7836 
7837 	return (nested == preempt_offset);
7838 }
7839 
__might_sleep(const char * file,int line,int preempt_offset)7840 void __might_sleep(const char *file, int line, int preempt_offset)
7841 {
7842 	/*
7843 	 * Blocking primitives will set (and therefore destroy) current->state,
7844 	 * since we will exit with TASK_RUNNING make sure we enter with it,
7845 	 * otherwise we will destroy state.
7846 	 */
7847 	WARN_ONCE(current->state != TASK_RUNNING && current->task_state_change,
7848 			"do not call blocking ops when !TASK_RUNNING; "
7849 			"state=%lx set at [<%p>] %pS\n",
7850 			current->state,
7851 			(void *)current->task_state_change,
7852 			(void *)current->task_state_change);
7853 
7854 	___might_sleep(file, line, preempt_offset);
7855 }
7856 EXPORT_SYMBOL(__might_sleep);
7857 
___might_sleep(const char * file,int line,int preempt_offset)7858 void ___might_sleep(const char *file, int line, int preempt_offset)
7859 {
7860 	/* Ratelimiting timestamp: */
7861 	static unsigned long prev_jiffy;
7862 
7863 	unsigned long preempt_disable_ip;
7864 
7865 	/* WARN_ON_ONCE() by default, no rate limit required: */
7866 	rcu_sleep_check();
7867 
7868 	if ((preempt_count_equals(preempt_offset) && !irqs_disabled() &&
7869 	     !is_idle_task(current) && !current->non_block_count) ||
7870 	    system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING ||
7871 	    oops_in_progress)
7872 		return;
7873 
7874 	if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7875 		return;
7876 	prev_jiffy = jiffies;
7877 
7878 	/* Save this before calling printk(), since that will clobber it: */
7879 	preempt_disable_ip = get_preempt_disable_ip(current);
7880 
7881 	printk(KERN_ERR
7882 		"BUG: sleeping function called from invalid context at %s:%d\n",
7883 			file, line);
7884 	printk(KERN_ERR
7885 		"in_atomic(): %d, irqs_disabled(): %d, non_block: %d, pid: %d, name: %s\n",
7886 			in_atomic(), irqs_disabled(), current->non_block_count,
7887 			current->pid, current->comm);
7888 
7889 	if (task_stack_end_corrupted(current))
7890 		printk(KERN_EMERG "Thread overran stack, or stack corrupted\n");
7891 
7892 	debug_show_held_locks(current);
7893 	if (irqs_disabled())
7894 		print_irqtrace_events(current);
7895 	if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)
7896 	    && !preempt_count_equals(preempt_offset)) {
7897 		pr_err("Preemption disabled at:");
7898 		print_ip_sym(KERN_ERR, preempt_disable_ip);
7899 	}
7900 	dump_stack();
7901 	add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
7902 }
7903 EXPORT_SYMBOL(___might_sleep);
7904 
__cant_sleep(const char * file,int line,int preempt_offset)7905 void __cant_sleep(const char *file, int line, int preempt_offset)
7906 {
7907 	static unsigned long prev_jiffy;
7908 
7909 	if (irqs_disabled())
7910 		return;
7911 
7912 	if (!IS_ENABLED(CONFIG_PREEMPT_COUNT))
7913 		return;
7914 
7915 	if (preempt_count() > preempt_offset)
7916 		return;
7917 
7918 	if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy)
7919 		return;
7920 	prev_jiffy = jiffies;
7921 
7922 	printk(KERN_ERR "BUG: assuming atomic context at %s:%d\n", file, line);
7923 	printk(KERN_ERR "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n",
7924 			in_atomic(), irqs_disabled(),
7925 			current->pid, current->comm);
7926 
7927 	debug_show_held_locks(current);
7928 	dump_stack();
7929 	add_taint(TAINT_WARN, LOCKDEP_STILL_OK);
7930 }
7931 EXPORT_SYMBOL_GPL(__cant_sleep);
7932 #endif
7933 
7934 #ifdef CONFIG_MAGIC_SYSRQ
normalize_rt_tasks(void)7935 void normalize_rt_tasks(void)
7936 {
7937 	struct task_struct *g, *p;
7938 	struct sched_attr attr = {
7939 		.sched_policy = SCHED_NORMAL,
7940 	};
7941 
7942 	read_lock(&tasklist_lock);
7943 	for_each_process_thread(g, p) {
7944 		/*
7945 		 * Only normalize user tasks:
7946 		 */
7947 		if (p->flags & PF_KTHREAD)
7948 			continue;
7949 
7950 		p->se.exec_start = 0;
7951 		schedstat_set(p->se.statistics.wait_start,  0);
7952 		schedstat_set(p->se.statistics.sleep_start, 0);
7953 		schedstat_set(p->se.statistics.block_start, 0);
7954 
7955 		if (!dl_task(p) && !rt_task(p)) {
7956 			/*
7957 			 * Renice negative nice level userspace
7958 			 * tasks back to 0:
7959 			 */
7960 			if (task_nice(p) < 0)
7961 				set_user_nice(p, 0);
7962 			continue;
7963 		}
7964 
7965 		__sched_setscheduler(p, &attr, false, false);
7966 	}
7967 	read_unlock(&tasklist_lock);
7968 }
7969 
7970 #endif /* CONFIG_MAGIC_SYSRQ */
7971 
7972 #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB)
7973 /*
7974  * These functions are only useful for the IA64 MCA handling, or kdb.
7975  *
7976  * They can only be called when the whole system has been
7977  * stopped - every CPU needs to be quiescent, and no scheduling
7978  * activity can take place. Using them for anything else would
7979  * be a serious bug, and as a result, they aren't even visible
7980  * under any other configuration.
7981  */
7982 
7983 /**
7984  * curr_task - return the current task for a given CPU.
7985  * @cpu: the processor in question.
7986  *
7987  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
7988  *
7989  * Return: The current task for @cpu.
7990  */
curr_task(int cpu)7991 struct task_struct *curr_task(int cpu)
7992 {
7993 	return cpu_curr(cpu);
7994 }
7995 
7996 #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */
7997 
7998 #ifdef CONFIG_IA64
7999 /**
8000  * ia64_set_curr_task - set the current task for a given CPU.
8001  * @cpu: the processor in question.
8002  * @p: the task pointer to set.
8003  *
8004  * Description: This function must only be used when non-maskable interrupts
8005  * are serviced on a separate stack. It allows the architecture to switch the
8006  * notion of the current task on a CPU in a non-blocking manner. This function
8007  * must be called with all CPU's synchronized, and interrupts disabled, the
8008  * and caller must save the original value of the current task (see
8009  * curr_task() above) and restore that value before reenabling interrupts and
8010  * re-starting the system.
8011  *
8012  * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED!
8013  */
ia64_set_curr_task(int cpu,struct task_struct * p)8014 void ia64_set_curr_task(int cpu, struct task_struct *p)
8015 {
8016 	cpu_curr(cpu) = p;
8017 }
8018 
8019 #endif
8020 
8021 #ifdef CONFIG_CGROUP_SCHED
8022 /* task_group_lock serializes the addition/removal of task groups */
8023 static DEFINE_SPINLOCK(task_group_lock);
8024 
alloc_uclamp_sched_group(struct task_group * tg,struct task_group * parent)8025 static inline void alloc_uclamp_sched_group(struct task_group *tg,
8026 					    struct task_group *parent)
8027 {
8028 #ifdef CONFIG_UCLAMP_TASK_GROUP
8029 	enum uclamp_id clamp_id;
8030 
8031 	for_each_clamp_id(clamp_id) {
8032 		uclamp_se_set(&tg->uclamp_req[clamp_id],
8033 			      uclamp_none(clamp_id), false);
8034 		tg->uclamp[clamp_id] = parent->uclamp[clamp_id];
8035 	}
8036 #endif
8037 }
8038 
sched_free_group(struct task_group * tg)8039 static void sched_free_group(struct task_group *tg)
8040 {
8041 	free_fair_sched_group(tg);
8042 	free_rt_sched_group(tg);
8043 	autogroup_free(tg);
8044 	kmem_cache_free(task_group_cache, tg);
8045 }
8046 
8047 /* allocate runqueue etc for a new task group */
sched_create_group(struct task_group * parent)8048 struct task_group *sched_create_group(struct task_group *parent)
8049 {
8050 	struct task_group *tg;
8051 
8052 	tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO);
8053 	if (!tg)
8054 		return ERR_PTR(-ENOMEM);
8055 
8056 	if (!alloc_fair_sched_group(tg, parent))
8057 		goto err;
8058 
8059 	if (!alloc_rt_sched_group(tg, parent))
8060 		goto err;
8061 
8062 	alloc_uclamp_sched_group(tg, parent);
8063 
8064 	return tg;
8065 
8066 err:
8067 	sched_free_group(tg);
8068 	return ERR_PTR(-ENOMEM);
8069 }
8070 
sched_online_group(struct task_group * tg,struct task_group * parent)8071 void sched_online_group(struct task_group *tg, struct task_group *parent)
8072 {
8073 	unsigned long flags;
8074 
8075 	spin_lock_irqsave(&task_group_lock, flags);
8076 	list_add_rcu(&tg->list, &task_groups);
8077 
8078 	/* Root should already exist: */
8079 	WARN_ON(!parent);
8080 
8081 	tg->parent = parent;
8082 	INIT_LIST_HEAD(&tg->children);
8083 	list_add_rcu(&tg->siblings, &parent->children);
8084 	spin_unlock_irqrestore(&task_group_lock, flags);
8085 
8086 	online_fair_sched_group(tg);
8087 }
8088 
8089 /* rcu callback to free various structures associated with a task group */
sched_free_group_rcu(struct rcu_head * rhp)8090 static void sched_free_group_rcu(struct rcu_head *rhp)
8091 {
8092 	/* Now it should be safe to free those cfs_rqs: */
8093 	sched_free_group(container_of(rhp, struct task_group, rcu));
8094 }
8095 
sched_destroy_group(struct task_group * tg)8096 void sched_destroy_group(struct task_group *tg)
8097 {
8098 	/* Wait for possible concurrent references to cfs_rqs complete: */
8099 	call_rcu(&tg->rcu, sched_free_group_rcu);
8100 }
8101 
sched_offline_group(struct task_group * tg)8102 void sched_offline_group(struct task_group *tg)
8103 {
8104 	unsigned long flags;
8105 
8106 	/* End participation in shares distribution: */
8107 	unregister_fair_sched_group(tg);
8108 
8109 	spin_lock_irqsave(&task_group_lock, flags);
8110 	list_del_rcu(&tg->list);
8111 	list_del_rcu(&tg->siblings);
8112 	spin_unlock_irqrestore(&task_group_lock, flags);
8113 }
8114 
sched_change_group(struct task_struct * tsk,int type)8115 static void sched_change_group(struct task_struct *tsk, int type)
8116 {
8117 	struct task_group *tg;
8118 
8119 	/*
8120 	 * All callers are synchronized by task_rq_lock(); we do not use RCU
8121 	 * which is pointless here. Thus, we pass "true" to task_css_check()
8122 	 * to prevent lockdep warnings.
8123 	 */
8124 	tg = container_of(task_css_check(tsk, cpu_cgrp_id, true),
8125 			  struct task_group, css);
8126 	tg = autogroup_task_group(tsk, tg);
8127 	tsk->sched_task_group = tg;
8128 
8129 #ifdef CONFIG_FAIR_GROUP_SCHED
8130 	if (tsk->sched_class->task_change_group)
8131 		tsk->sched_class->task_change_group(tsk, type);
8132 	else
8133 #endif
8134 		set_task_rq(tsk, task_cpu(tsk));
8135 }
8136 
8137 /*
8138  * Change task's runqueue when it moves between groups.
8139  *
8140  * The caller of this function should have put the task in its new group by
8141  * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect
8142  * its new group.
8143  */
sched_move_task(struct task_struct * tsk)8144 void sched_move_task(struct task_struct *tsk)
8145 {
8146 	int queued, running, queue_flags =
8147 		DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK;
8148 	struct rq_flags rf;
8149 	struct rq *rq;
8150 
8151 	rq = task_rq_lock(tsk, &rf);
8152 	update_rq_clock(rq);
8153 
8154 	running = task_current(rq, tsk);
8155 	queued = task_on_rq_queued(tsk);
8156 
8157 	if (queued)
8158 		dequeue_task(rq, tsk, queue_flags);
8159 	if (running)
8160 		put_prev_task(rq, tsk);
8161 
8162 	sched_change_group(tsk, TASK_MOVE_GROUP);
8163 
8164 	if (queued)
8165 		enqueue_task(rq, tsk, queue_flags);
8166 	if (running) {
8167 		set_next_task(rq, tsk);
8168 		/*
8169 		 * After changing group, the running task may have joined a
8170 		 * throttled one but it's still the running task. Trigger a
8171 		 * resched to make sure that task can still run.
8172 		 */
8173 		resched_curr(rq);
8174 	}
8175 
8176 	task_rq_unlock(rq, tsk, &rf);
8177 }
8178 
css_tg(struct cgroup_subsys_state * css)8179 static inline struct task_group *css_tg(struct cgroup_subsys_state *css)
8180 {
8181 	return css ? container_of(css, struct task_group, css) : NULL;
8182 }
8183 
8184 static struct cgroup_subsys_state *
cpu_cgroup_css_alloc(struct cgroup_subsys_state * parent_css)8185 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css)
8186 {
8187 	struct task_group *parent = css_tg(parent_css);
8188 	struct task_group *tg;
8189 
8190 	if (!parent) {
8191 		/* This is early initialization for the top cgroup */
8192 		return &root_task_group.css;
8193 	}
8194 
8195 	tg = sched_create_group(parent);
8196 	if (IS_ERR(tg))
8197 		return ERR_PTR(-ENOMEM);
8198 
8199 #ifdef CONFIG_SCHED_RTG_CGROUP
8200 	tg->colocate = false;
8201 	tg->colocate_update_disabled = false;
8202 #endif
8203 
8204 	return &tg->css;
8205 }
8206 
8207 /* Expose task group only after completing cgroup initialization */
cpu_cgroup_css_online(struct cgroup_subsys_state * css)8208 static int cpu_cgroup_css_online(struct cgroup_subsys_state *css)
8209 {
8210 	struct task_group *tg = css_tg(css);
8211 	struct task_group *parent = css_tg(css->parent);
8212 
8213 	if (parent)
8214 		sched_online_group(tg, parent);
8215 
8216 #ifdef CONFIG_UCLAMP_TASK_GROUP
8217 	/* Propagate the effective uclamp value for the new group */
8218 	mutex_lock(&uclamp_mutex);
8219 	rcu_read_lock();
8220 	cpu_util_update_eff(css);
8221 	rcu_read_unlock();
8222 	mutex_unlock(&uclamp_mutex);
8223 #endif
8224 
8225 	return 0;
8226 }
8227 
cpu_cgroup_css_released(struct cgroup_subsys_state * css)8228 static void cpu_cgroup_css_released(struct cgroup_subsys_state *css)
8229 {
8230 	struct task_group *tg = css_tg(css);
8231 
8232 	sched_offline_group(tg);
8233 }
8234 
cpu_cgroup_css_free(struct cgroup_subsys_state * css)8235 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css)
8236 {
8237 	struct task_group *tg = css_tg(css);
8238 
8239 	/*
8240 	 * Relies on the RCU grace period between css_released() and this.
8241 	 */
8242 	sched_free_group(tg);
8243 }
8244 
8245 /*
8246  * This is called before wake_up_new_task(), therefore we really only
8247  * have to set its group bits, all the other stuff does not apply.
8248  */
cpu_cgroup_fork(struct task_struct * task)8249 static void cpu_cgroup_fork(struct task_struct *task)
8250 {
8251 	struct rq_flags rf;
8252 	struct rq *rq;
8253 
8254 	rq = task_rq_lock(task, &rf);
8255 
8256 	update_rq_clock(rq);
8257 	sched_change_group(task, TASK_SET_GROUP);
8258 
8259 	task_rq_unlock(rq, task, &rf);
8260 }
8261 
cpu_cgroup_can_attach(struct cgroup_taskset * tset)8262 static int cpu_cgroup_can_attach(struct cgroup_taskset *tset)
8263 {
8264 	struct task_struct *task;
8265 	struct cgroup_subsys_state *css;
8266 	int ret = 0;
8267 
8268 	cgroup_taskset_for_each(task, css, tset) {
8269 #ifdef CONFIG_RT_GROUP_SCHED
8270 		if (!sched_rt_can_attach(css_tg(css), task))
8271 			return -EINVAL;
8272 #endif
8273 		/*
8274 		 * Serialize against wake_up_new_task() such that if its
8275 		 * running, we're sure to observe its full state.
8276 		 */
8277 		raw_spin_lock_irq(&task->pi_lock);
8278 		/*
8279 		 * Avoid calling sched_move_task() before wake_up_new_task()
8280 		 * has happened. This would lead to problems with PELT, due to
8281 		 * move wanting to detach+attach while we're not attached yet.
8282 		 */
8283 		if (task->state == TASK_NEW)
8284 			ret = -EINVAL;
8285 		raw_spin_unlock_irq(&task->pi_lock);
8286 
8287 		if (ret)
8288 			break;
8289 	}
8290 	return ret;
8291 }
8292 
8293 #if defined(CONFIG_UCLAMP_TASK_GROUP) && defined(CONFIG_SCHED_RTG_CGROUP)
schedgp_attach(struct cgroup_taskset * tset)8294 static void schedgp_attach(struct cgroup_taskset *tset)
8295 {
8296 	struct task_struct *task;
8297 	struct cgroup_subsys_state *css;
8298 	bool colocate;
8299 	struct task_group *tg;
8300 
8301 	cgroup_taskset_first(tset, &css);
8302 	tg = css_tg(css);
8303 
8304 	colocate = tg->colocate;
8305 
8306 	cgroup_taskset_for_each(task, css, tset)
8307 		sync_cgroup_colocation(task, colocate);
8308 }
8309 #else
schedgp_attach(struct cgroup_taskset * tset)8310 static void schedgp_attach(struct cgroup_taskset *tset) { }
8311 #endif
cpu_cgroup_attach(struct cgroup_taskset * tset)8312 static void cpu_cgroup_attach(struct cgroup_taskset *tset)
8313 {
8314 	struct task_struct *task;
8315 	struct cgroup_subsys_state *css;
8316 
8317 	cgroup_taskset_for_each(task, css, tset)
8318 		sched_move_task(task);
8319 
8320 	schedgp_attach(tset);
8321 }
8322 
8323 #ifdef CONFIG_UCLAMP_TASK_GROUP
cpu_util_update_eff(struct cgroup_subsys_state * css)8324 static void cpu_util_update_eff(struct cgroup_subsys_state *css)
8325 {
8326 	struct cgroup_subsys_state *top_css = css;
8327 	struct uclamp_se *uc_parent = NULL;
8328 	struct uclamp_se *uc_se = NULL;
8329 	unsigned int eff[UCLAMP_CNT];
8330 	enum uclamp_id clamp_id;
8331 	unsigned int clamps;
8332 
8333 	lockdep_assert_held(&uclamp_mutex);
8334 	SCHED_WARN_ON(!rcu_read_lock_held());
8335 
8336 	css_for_each_descendant_pre(css, top_css) {
8337 		uc_parent = css_tg(css)->parent
8338 			? css_tg(css)->parent->uclamp : NULL;
8339 
8340 		for_each_clamp_id(clamp_id) {
8341 			/* Assume effective clamps matches requested clamps */
8342 			eff[clamp_id] = css_tg(css)->uclamp_req[clamp_id].value;
8343 			/* Cap effective clamps with parent's effective clamps */
8344 			if (uc_parent &&
8345 			    eff[clamp_id] > uc_parent[clamp_id].value) {
8346 				eff[clamp_id] = uc_parent[clamp_id].value;
8347 			}
8348 		}
8349 		/* Ensure protection is always capped by limit */
8350 		eff[UCLAMP_MIN] = min(eff[UCLAMP_MIN], eff[UCLAMP_MAX]);
8351 
8352 		/* Propagate most restrictive effective clamps */
8353 		clamps = 0x0;
8354 		uc_se = css_tg(css)->uclamp;
8355 		for_each_clamp_id(clamp_id) {
8356 			if (eff[clamp_id] == uc_se[clamp_id].value)
8357 				continue;
8358 			uc_se[clamp_id].value = eff[clamp_id];
8359 			uc_se[clamp_id].bucket_id = uclamp_bucket_id(eff[clamp_id]);
8360 			clamps |= (0x1 << clamp_id);
8361 		}
8362 		if (!clamps) {
8363 			css = css_rightmost_descendant(css);
8364 			continue;
8365 		}
8366 
8367 		/* Immediately update descendants RUNNABLE tasks */
8368 		uclamp_update_active_tasks(css);
8369 	}
8370 }
8371 
8372 /*
8373  * Integer 10^N with a given N exponent by casting to integer the literal "1eN"
8374  * C expression. Since there is no way to convert a macro argument (N) into a
8375  * character constant, use two levels of macros.
8376  */
8377 #define _POW10(exp) ((unsigned int)1e##exp)
8378 #define POW10(exp) _POW10(exp)
8379 
8380 struct uclamp_request {
8381 #define UCLAMP_PERCENT_SHIFT	2
8382 #define UCLAMP_PERCENT_SCALE	(100 * POW10(UCLAMP_PERCENT_SHIFT))
8383 	s64 percent;
8384 	u64 util;
8385 	int ret;
8386 };
8387 
8388 static inline struct uclamp_request
capacity_from_percent(char * buf)8389 capacity_from_percent(char *buf)
8390 {
8391 	struct uclamp_request req = {
8392 		.percent = UCLAMP_PERCENT_SCALE,
8393 		.util = SCHED_CAPACITY_SCALE,
8394 		.ret = 0,
8395 	};
8396 
8397 	buf = strim(buf);
8398 	if (strcmp(buf, "max")) {
8399 		req.ret = cgroup_parse_float(buf, UCLAMP_PERCENT_SHIFT,
8400 					     &req.percent);
8401 		if (req.ret)
8402 			return req;
8403 		if ((u64)req.percent > UCLAMP_PERCENT_SCALE) {
8404 			req.ret = -ERANGE;
8405 			return req;
8406 		}
8407 
8408 		req.util = req.percent << SCHED_CAPACITY_SHIFT;
8409 		req.util = DIV_ROUND_CLOSEST_ULL(req.util, UCLAMP_PERCENT_SCALE);
8410 	}
8411 
8412 	return req;
8413 }
8414 
cpu_uclamp_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off,enum uclamp_id clamp_id)8415 static ssize_t cpu_uclamp_write(struct kernfs_open_file *of, char *buf,
8416 				size_t nbytes, loff_t off,
8417 				enum uclamp_id clamp_id)
8418 {
8419 	struct uclamp_request req;
8420 	struct task_group *tg;
8421 
8422 	req = capacity_from_percent(buf);
8423 	if (req.ret)
8424 		return req.ret;
8425 
8426 	static_branch_enable(&sched_uclamp_used);
8427 
8428 	mutex_lock(&uclamp_mutex);
8429 	rcu_read_lock();
8430 
8431 	tg = css_tg(of_css(of));
8432 	if (tg->uclamp_req[clamp_id].value != req.util)
8433 		uclamp_se_set(&tg->uclamp_req[clamp_id], req.util, false);
8434 
8435 	/*
8436 	 * Because of not recoverable conversion rounding we keep track of the
8437 	 * exact requested value
8438 	 */
8439 	tg->uclamp_pct[clamp_id] = req.percent;
8440 
8441 	/* Update effective clamps to track the most restrictive value */
8442 	cpu_util_update_eff(of_css(of));
8443 
8444 	rcu_read_unlock();
8445 	mutex_unlock(&uclamp_mutex);
8446 
8447 	return nbytes;
8448 }
8449 
cpu_uclamp_min_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)8450 static ssize_t cpu_uclamp_min_write(struct kernfs_open_file *of,
8451 				    char *buf, size_t nbytes,
8452 				    loff_t off)
8453 {
8454 	return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MIN);
8455 }
8456 
cpu_uclamp_max_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)8457 static ssize_t cpu_uclamp_max_write(struct kernfs_open_file *of,
8458 				    char *buf, size_t nbytes,
8459 				    loff_t off)
8460 {
8461 	return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MAX);
8462 }
8463 
cpu_uclamp_print(struct seq_file * sf,enum uclamp_id clamp_id)8464 static inline void cpu_uclamp_print(struct seq_file *sf,
8465 				    enum uclamp_id clamp_id)
8466 {
8467 	struct task_group *tg;
8468 	u64 util_clamp;
8469 	u64 percent;
8470 	u32 rem;
8471 
8472 	rcu_read_lock();
8473 	tg = css_tg(seq_css(sf));
8474 	util_clamp = tg->uclamp_req[clamp_id].value;
8475 	rcu_read_unlock();
8476 
8477 	if (util_clamp == SCHED_CAPACITY_SCALE) {
8478 		seq_puts(sf, "max\n");
8479 		return;
8480 	}
8481 
8482 	percent = tg->uclamp_pct[clamp_id];
8483 	percent = div_u64_rem(percent, POW10(UCLAMP_PERCENT_SHIFT), &rem);
8484 	seq_printf(sf, "%llu.%0*u\n", percent, UCLAMP_PERCENT_SHIFT, rem);
8485 }
8486 
cpu_uclamp_min_show(struct seq_file * sf,void * v)8487 static int cpu_uclamp_min_show(struct seq_file *sf, void *v)
8488 {
8489 	cpu_uclamp_print(sf, UCLAMP_MIN);
8490 	return 0;
8491 }
8492 
cpu_uclamp_max_show(struct seq_file * sf,void * v)8493 static int cpu_uclamp_max_show(struct seq_file *sf, void *v)
8494 {
8495 	cpu_uclamp_print(sf, UCLAMP_MAX);
8496 	return 0;
8497 }
8498 
8499 #ifdef CONFIG_SCHED_RTG_CGROUP
sched_colocate_read(struct cgroup_subsys_state * css,struct cftype * cft)8500 static u64 sched_colocate_read(struct cgroup_subsys_state *css,
8501 				struct cftype *cft)
8502 {
8503 	struct task_group *tg = css_tg(css);
8504 
8505 	return (u64) tg->colocate;
8506 }
8507 
sched_colocate_write(struct cgroup_subsys_state * css,struct cftype * cft,u64 colocate)8508 static int sched_colocate_write(struct cgroup_subsys_state *css,
8509 				struct cftype *cft, u64 colocate)
8510 {
8511 	struct task_group *tg = css_tg(css);
8512 
8513 	if (tg->colocate_update_disabled)
8514 		return -EPERM;
8515 
8516 	tg->colocate = !!colocate;
8517 	tg->colocate_update_disabled = true;
8518 
8519 	return 0;
8520 }
8521 #endif /* CONFIG_SCHED_RTG_CGROUP */
8522 #endif /* CONFIG_UCLAMP_TASK_GROUP */
8523 
8524 #ifdef CONFIG_FAIR_GROUP_SCHED
cpu_shares_write_u64(struct cgroup_subsys_state * css,struct cftype * cftype,u64 shareval)8525 static int cpu_shares_write_u64(struct cgroup_subsys_state *css,
8526 				struct cftype *cftype, u64 shareval)
8527 {
8528 	if (shareval > scale_load_down(ULONG_MAX))
8529 		shareval = MAX_SHARES;
8530 	return sched_group_set_shares(css_tg(css), scale_load(shareval));
8531 }
8532 
cpu_shares_read_u64(struct cgroup_subsys_state * css,struct cftype * cft)8533 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css,
8534 			       struct cftype *cft)
8535 {
8536 	struct task_group *tg = css_tg(css);
8537 
8538 	return (u64) scale_load_down(tg->shares);
8539 }
8540 
8541 #ifdef CONFIG_CFS_BANDWIDTH
8542 static DEFINE_MUTEX(cfs_constraints_mutex);
8543 
8544 const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */
8545 static const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */
8546 /* More than 203 days if BW_SHIFT equals 20. */
8547 static const u64 max_cfs_runtime = MAX_BW * NSEC_PER_USEC;
8548 
8549 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime);
8550 
tg_set_cfs_bandwidth(struct task_group * tg,u64 period,u64 quota)8551 static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota)
8552 {
8553 	int i, ret = 0, runtime_enabled, runtime_was_enabled;
8554 	struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8555 
8556 	if (tg == &root_task_group)
8557 		return -EINVAL;
8558 
8559 	/*
8560 	 * Ensure we have at some amount of bandwidth every period.  This is
8561 	 * to prevent reaching a state of large arrears when throttled via
8562 	 * entity_tick() resulting in prolonged exit starvation.
8563 	 */
8564 	if (quota < min_cfs_quota_period || period < min_cfs_quota_period)
8565 		return -EINVAL;
8566 
8567 	/*
8568 	 * Likewise, bound things on the otherside by preventing insane quota
8569 	 * periods.  This also allows us to normalize in computing quota
8570 	 * feasibility.
8571 	 */
8572 	if (period > max_cfs_quota_period)
8573 		return -EINVAL;
8574 
8575 	/*
8576 	 * Bound quota to defend quota against overflow during bandwidth shift.
8577 	 */
8578 	if (quota != RUNTIME_INF && quota > max_cfs_runtime)
8579 		return -EINVAL;
8580 
8581 	/*
8582 	 * Prevent race between setting of cfs_rq->runtime_enabled and
8583 	 * unthrottle_offline_cfs_rqs().
8584 	 */
8585 	get_online_cpus();
8586 	mutex_lock(&cfs_constraints_mutex);
8587 	ret = __cfs_schedulable(tg, period, quota);
8588 	if (ret)
8589 		goto out_unlock;
8590 
8591 	runtime_enabled = quota != RUNTIME_INF;
8592 	runtime_was_enabled = cfs_b->quota != RUNTIME_INF;
8593 	/*
8594 	 * If we need to toggle cfs_bandwidth_used, off->on must occur
8595 	 * before making related changes, and on->off must occur afterwards
8596 	 */
8597 	if (runtime_enabled && !runtime_was_enabled)
8598 		cfs_bandwidth_usage_inc();
8599 	raw_spin_lock_irq(&cfs_b->lock);
8600 	cfs_b->period = ns_to_ktime(period);
8601 	cfs_b->quota = quota;
8602 
8603 	__refill_cfs_bandwidth_runtime(cfs_b);
8604 
8605 	/* Restart the period timer (if active) to handle new period expiry: */
8606 	if (runtime_enabled)
8607 		start_cfs_bandwidth(cfs_b);
8608 
8609 	raw_spin_unlock_irq(&cfs_b->lock);
8610 
8611 	for_each_online_cpu(i) {
8612 		struct cfs_rq *cfs_rq = tg->cfs_rq[i];
8613 		struct rq *rq = cfs_rq->rq;
8614 		struct rq_flags rf;
8615 
8616 		rq_lock_irq(rq, &rf);
8617 		cfs_rq->runtime_enabled = runtime_enabled;
8618 		cfs_rq->runtime_remaining = 0;
8619 
8620 		if (cfs_rq->throttled)
8621 			unthrottle_cfs_rq(cfs_rq);
8622 		rq_unlock_irq(rq, &rf);
8623 	}
8624 	if (runtime_was_enabled && !runtime_enabled)
8625 		cfs_bandwidth_usage_dec();
8626 out_unlock:
8627 	mutex_unlock(&cfs_constraints_mutex);
8628 	put_online_cpus();
8629 
8630 	return ret;
8631 }
8632 
tg_set_cfs_quota(struct task_group * tg,long cfs_quota_us)8633 static int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us)
8634 {
8635 	u64 quota, period;
8636 
8637 	period = ktime_to_ns(tg->cfs_bandwidth.period);
8638 	if (cfs_quota_us < 0)
8639 		quota = RUNTIME_INF;
8640 	else if ((u64)cfs_quota_us <= U64_MAX / NSEC_PER_USEC)
8641 		quota = (u64)cfs_quota_us * NSEC_PER_USEC;
8642 	else
8643 		return -EINVAL;
8644 
8645 	return tg_set_cfs_bandwidth(tg, period, quota);
8646 }
8647 
tg_get_cfs_quota(struct task_group * tg)8648 static long tg_get_cfs_quota(struct task_group *tg)
8649 {
8650 	u64 quota_us;
8651 
8652 	if (tg->cfs_bandwidth.quota == RUNTIME_INF)
8653 		return -1;
8654 
8655 	quota_us = tg->cfs_bandwidth.quota;
8656 	do_div(quota_us, NSEC_PER_USEC);
8657 
8658 	return quota_us;
8659 }
8660 
tg_set_cfs_period(struct task_group * tg,long cfs_period_us)8661 static int tg_set_cfs_period(struct task_group *tg, long cfs_period_us)
8662 {
8663 	u64 quota, period;
8664 
8665 	if ((u64)cfs_period_us > U64_MAX / NSEC_PER_USEC)
8666 		return -EINVAL;
8667 
8668 	period = (u64)cfs_period_us * NSEC_PER_USEC;
8669 	quota = tg->cfs_bandwidth.quota;
8670 
8671 	return tg_set_cfs_bandwidth(tg, period, quota);
8672 }
8673 
tg_get_cfs_period(struct task_group * tg)8674 static long tg_get_cfs_period(struct task_group *tg)
8675 {
8676 	u64 cfs_period_us;
8677 
8678 	cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period);
8679 	do_div(cfs_period_us, NSEC_PER_USEC);
8680 
8681 	return cfs_period_us;
8682 }
8683 
cpu_cfs_quota_read_s64(struct cgroup_subsys_state * css,struct cftype * cft)8684 static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css,
8685 				  struct cftype *cft)
8686 {
8687 	return tg_get_cfs_quota(css_tg(css));
8688 }
8689 
cpu_cfs_quota_write_s64(struct cgroup_subsys_state * css,struct cftype * cftype,s64 cfs_quota_us)8690 static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css,
8691 				   struct cftype *cftype, s64 cfs_quota_us)
8692 {
8693 	return tg_set_cfs_quota(css_tg(css), cfs_quota_us);
8694 }
8695 
cpu_cfs_period_read_u64(struct cgroup_subsys_state * css,struct cftype * cft)8696 static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css,
8697 				   struct cftype *cft)
8698 {
8699 	return tg_get_cfs_period(css_tg(css));
8700 }
8701 
cpu_cfs_period_write_u64(struct cgroup_subsys_state * css,struct cftype * cftype,u64 cfs_period_us)8702 static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css,
8703 				    struct cftype *cftype, u64 cfs_period_us)
8704 {
8705 	return tg_set_cfs_period(css_tg(css), cfs_period_us);
8706 }
8707 
8708 struct cfs_schedulable_data {
8709 	struct task_group *tg;
8710 	u64 period, quota;
8711 };
8712 
8713 /*
8714  * normalize group quota/period to be quota/max_period
8715  * note: units are usecs
8716  */
normalize_cfs_quota(struct task_group * tg,struct cfs_schedulable_data * d)8717 static u64 normalize_cfs_quota(struct task_group *tg,
8718 			       struct cfs_schedulable_data *d)
8719 {
8720 	u64 quota, period;
8721 
8722 	if (tg == d->tg) {
8723 		period = d->period;
8724 		quota = d->quota;
8725 	} else {
8726 		period = tg_get_cfs_period(tg);
8727 		quota = tg_get_cfs_quota(tg);
8728 	}
8729 
8730 	/* note: these should typically be equivalent */
8731 	if (quota == RUNTIME_INF || quota == -1)
8732 		return RUNTIME_INF;
8733 
8734 	return to_ratio(period, quota);
8735 }
8736 
tg_cfs_schedulable_down(struct task_group * tg,void * data)8737 static int tg_cfs_schedulable_down(struct task_group *tg, void *data)
8738 {
8739 	struct cfs_schedulable_data *d = data;
8740 	struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8741 	s64 quota = 0, parent_quota = -1;
8742 
8743 	if (!tg->parent) {
8744 		quota = RUNTIME_INF;
8745 	} else {
8746 		struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth;
8747 
8748 		quota = normalize_cfs_quota(tg, d);
8749 		parent_quota = parent_b->hierarchical_quota;
8750 
8751 		/*
8752 		 * Ensure max(child_quota) <= parent_quota.  On cgroup2,
8753 		 * always take the min.  On cgroup1, only inherit when no
8754 		 * limit is set:
8755 		 */
8756 		if (cgroup_subsys_on_dfl(cpu_cgrp_subsys)) {
8757 			quota = min(quota, parent_quota);
8758 		} else {
8759 			if (quota == RUNTIME_INF)
8760 				quota = parent_quota;
8761 			else if (parent_quota != RUNTIME_INF && quota > parent_quota)
8762 				return -EINVAL;
8763 		}
8764 	}
8765 	cfs_b->hierarchical_quota = quota;
8766 
8767 	return 0;
8768 }
8769 
__cfs_schedulable(struct task_group * tg,u64 period,u64 quota)8770 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota)
8771 {
8772 	int ret;
8773 	struct cfs_schedulable_data data = {
8774 		.tg = tg,
8775 		.period = period,
8776 		.quota = quota,
8777 	};
8778 
8779 	if (quota != RUNTIME_INF) {
8780 		do_div(data.period, NSEC_PER_USEC);
8781 		do_div(data.quota, NSEC_PER_USEC);
8782 	}
8783 
8784 	rcu_read_lock();
8785 	ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data);
8786 	rcu_read_unlock();
8787 
8788 	return ret;
8789 }
8790 
cpu_cfs_stat_show(struct seq_file * sf,void * v)8791 static int cpu_cfs_stat_show(struct seq_file *sf, void *v)
8792 {
8793 	struct task_group *tg = css_tg(seq_css(sf));
8794 	struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8795 
8796 	seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods);
8797 	seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled);
8798 	seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time);
8799 
8800 	if (schedstat_enabled() && tg != &root_task_group) {
8801 		u64 ws = 0;
8802 		int i;
8803 
8804 		for_each_possible_cpu(i)
8805 			ws += schedstat_val(tg->se[i]->statistics.wait_sum);
8806 
8807 		seq_printf(sf, "wait_sum %llu\n", ws);
8808 	}
8809 
8810 	return 0;
8811 }
8812 #endif /* CONFIG_CFS_BANDWIDTH */
8813 #endif /* CONFIG_FAIR_GROUP_SCHED */
8814 
8815 #ifdef CONFIG_RT_GROUP_SCHED
cpu_rt_runtime_write(struct cgroup_subsys_state * css,struct cftype * cft,s64 val)8816 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css,
8817 				struct cftype *cft, s64 val)
8818 {
8819 	return sched_group_set_rt_runtime(css_tg(css), val);
8820 }
8821 
cpu_rt_runtime_read(struct cgroup_subsys_state * css,struct cftype * cft)8822 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css,
8823 			       struct cftype *cft)
8824 {
8825 	return sched_group_rt_runtime(css_tg(css));
8826 }
8827 
cpu_rt_period_write_uint(struct cgroup_subsys_state * css,struct cftype * cftype,u64 rt_period_us)8828 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css,
8829 				    struct cftype *cftype, u64 rt_period_us)
8830 {
8831 	return sched_group_set_rt_period(css_tg(css), rt_period_us);
8832 }
8833 
cpu_rt_period_read_uint(struct cgroup_subsys_state * css,struct cftype * cft)8834 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css,
8835 				   struct cftype *cft)
8836 {
8837 	return sched_group_rt_period(css_tg(css));
8838 }
8839 #endif /* CONFIG_RT_GROUP_SCHED */
8840 
8841 static struct cftype cpu_legacy_files[] = {
8842 #ifdef CONFIG_FAIR_GROUP_SCHED
8843 	{
8844 		.name = "shares",
8845 		.read_u64 = cpu_shares_read_u64,
8846 		.write_u64 = cpu_shares_write_u64,
8847 	},
8848 #endif
8849 #ifdef CONFIG_CFS_BANDWIDTH
8850 	{
8851 		.name = "cfs_quota_us",
8852 		.read_s64 = cpu_cfs_quota_read_s64,
8853 		.write_s64 = cpu_cfs_quota_write_s64,
8854 	},
8855 	{
8856 		.name = "cfs_period_us",
8857 		.read_u64 = cpu_cfs_period_read_u64,
8858 		.write_u64 = cpu_cfs_period_write_u64,
8859 	},
8860 	{
8861 		.name = "stat",
8862 		.seq_show = cpu_cfs_stat_show,
8863 	},
8864 #endif
8865 #ifdef CONFIG_RT_GROUP_SCHED
8866 	{
8867 		.name = "rt_runtime_us",
8868 		.read_s64 = cpu_rt_runtime_read,
8869 		.write_s64 = cpu_rt_runtime_write,
8870 	},
8871 	{
8872 		.name = "rt_period_us",
8873 		.read_u64 = cpu_rt_period_read_uint,
8874 		.write_u64 = cpu_rt_period_write_uint,
8875 	},
8876 #endif
8877 #ifdef CONFIG_UCLAMP_TASK_GROUP
8878 	{
8879 		.name = "uclamp.min",
8880 		.flags = CFTYPE_NOT_ON_ROOT,
8881 		.seq_show = cpu_uclamp_min_show,
8882 		.write = cpu_uclamp_min_write,
8883 	},
8884 	{
8885 		.name = "uclamp.max",
8886 		.flags = CFTYPE_NOT_ON_ROOT,
8887 		.seq_show = cpu_uclamp_max_show,
8888 		.write = cpu_uclamp_max_write,
8889 	},
8890 #ifdef CONFIG_SCHED_RTG_CGROUP
8891 	{
8892 		.name = "uclamp.colocate",
8893 		.flags = CFTYPE_NOT_ON_ROOT,
8894 		.read_u64 = sched_colocate_read,
8895 		.write_u64 = sched_colocate_write,
8896 	},
8897 #endif
8898 #endif
8899 	{ }	/* Terminate */
8900 };
8901 
cpu_extra_stat_show(struct seq_file * sf,struct cgroup_subsys_state * css)8902 static int cpu_extra_stat_show(struct seq_file *sf,
8903 			       struct cgroup_subsys_state *css)
8904 {
8905 #ifdef CONFIG_CFS_BANDWIDTH
8906 	{
8907 		struct task_group *tg = css_tg(css);
8908 		struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth;
8909 		u64 throttled_usec;
8910 
8911 		throttled_usec = cfs_b->throttled_time;
8912 		do_div(throttled_usec, NSEC_PER_USEC);
8913 
8914 		seq_printf(sf, "nr_periods %d\n"
8915 			   "nr_throttled %d\n"
8916 			   "throttled_usec %llu\n",
8917 			   cfs_b->nr_periods, cfs_b->nr_throttled,
8918 			   throttled_usec);
8919 	}
8920 #endif
8921 	return 0;
8922 }
8923 
8924 #ifdef CONFIG_FAIR_GROUP_SCHED
cpu_weight_read_u64(struct cgroup_subsys_state * css,struct cftype * cft)8925 static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css,
8926 			       struct cftype *cft)
8927 {
8928 	struct task_group *tg = css_tg(css);
8929 	u64 weight = scale_load_down(tg->shares);
8930 
8931 	return DIV_ROUND_CLOSEST_ULL(weight * CGROUP_WEIGHT_DFL, 1024);
8932 }
8933 
cpu_weight_write_u64(struct cgroup_subsys_state * css,struct cftype * cft,u64 weight)8934 static int cpu_weight_write_u64(struct cgroup_subsys_state *css,
8935 				struct cftype *cft, u64 weight)
8936 {
8937 	/*
8938 	 * cgroup weight knobs should use the common MIN, DFL and MAX
8939 	 * values which are 1, 100 and 10000 respectively.  While it loses
8940 	 * a bit of range on both ends, it maps pretty well onto the shares
8941 	 * value used by scheduler and the round-trip conversions preserve
8942 	 * the original value over the entire range.
8943 	 */
8944 	if (weight < CGROUP_WEIGHT_MIN || weight > CGROUP_WEIGHT_MAX)
8945 		return -ERANGE;
8946 
8947 	weight = DIV_ROUND_CLOSEST_ULL(weight * 1024, CGROUP_WEIGHT_DFL);
8948 
8949 	return sched_group_set_shares(css_tg(css), scale_load(weight));
8950 }
8951 
cpu_weight_nice_read_s64(struct cgroup_subsys_state * css,struct cftype * cft)8952 static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css,
8953 				    struct cftype *cft)
8954 {
8955 	unsigned long weight = scale_load_down(css_tg(css)->shares);
8956 	int last_delta = INT_MAX;
8957 	int prio, delta;
8958 
8959 	/* find the closest nice value to the current weight */
8960 	for (prio = 0; prio < ARRAY_SIZE(sched_prio_to_weight); prio++) {
8961 		delta = abs(sched_prio_to_weight[prio] - weight);
8962 		if (delta >= last_delta)
8963 			break;
8964 		last_delta = delta;
8965 	}
8966 
8967 	return PRIO_TO_NICE(prio - 1 + MAX_RT_PRIO);
8968 }
8969 
cpu_weight_nice_write_s64(struct cgroup_subsys_state * css,struct cftype * cft,s64 nice)8970 static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css,
8971 				     struct cftype *cft, s64 nice)
8972 {
8973 	unsigned long weight;
8974 	int idx;
8975 
8976 	if (nice < MIN_NICE || nice > MAX_NICE)
8977 		return -ERANGE;
8978 
8979 	idx = NICE_TO_PRIO(nice) - MAX_RT_PRIO;
8980 	idx = array_index_nospec(idx, 40);
8981 	weight = sched_prio_to_weight[idx];
8982 
8983 	return sched_group_set_shares(css_tg(css), scale_load(weight));
8984 }
8985 #endif
8986 
cpu_period_quota_print(struct seq_file * sf,long period,long quota)8987 static void __maybe_unused cpu_period_quota_print(struct seq_file *sf,
8988 						  long period, long quota)
8989 {
8990 	if (quota < 0)
8991 		seq_puts(sf, "max");
8992 	else
8993 		seq_printf(sf, "%ld", quota);
8994 
8995 	seq_printf(sf, " %ld\n", period);
8996 }
8997 
8998 /* caller should put the current value in *@periodp before calling */
cpu_period_quota_parse(char * buf,u64 * periodp,u64 * quotap)8999 static int __maybe_unused cpu_period_quota_parse(char *buf,
9000 						 u64 *periodp, u64 *quotap)
9001 {
9002 	char tok[21];	/* U64_MAX */
9003 
9004 	if (sscanf(buf, "%20s %llu", tok, periodp) < 1)
9005 		return -EINVAL;
9006 
9007 	*periodp *= NSEC_PER_USEC;
9008 
9009 	if (sscanf(tok, "%llu", quotap))
9010 		*quotap *= NSEC_PER_USEC;
9011 	else if (!strcmp(tok, "max"))
9012 		*quotap = RUNTIME_INF;
9013 	else
9014 		return -EINVAL;
9015 
9016 	return 0;
9017 }
9018 
9019 #ifdef CONFIG_CFS_BANDWIDTH
cpu_max_show(struct seq_file * sf,void * v)9020 static int cpu_max_show(struct seq_file *sf, void *v)
9021 {
9022 	struct task_group *tg = css_tg(seq_css(sf));
9023 
9024 	cpu_period_quota_print(sf, tg_get_cfs_period(tg), tg_get_cfs_quota(tg));
9025 	return 0;
9026 }
9027 
cpu_max_write(struct kernfs_open_file * of,char * buf,size_t nbytes,loff_t off)9028 static ssize_t cpu_max_write(struct kernfs_open_file *of,
9029 			     char *buf, size_t nbytes, loff_t off)
9030 {
9031 	struct task_group *tg = css_tg(of_css(of));
9032 	u64 period = tg_get_cfs_period(tg);
9033 	u64 quota;
9034 	int ret;
9035 
9036 	ret = cpu_period_quota_parse(buf, &period, &quota);
9037 	if (!ret)
9038 		ret = tg_set_cfs_bandwidth(tg, period, quota);
9039 	return ret ?: nbytes;
9040 }
9041 #endif
9042 
9043 static struct cftype cpu_files[] = {
9044 #ifdef CONFIG_FAIR_GROUP_SCHED
9045 	{
9046 		.name = "weight",
9047 		.flags = CFTYPE_NOT_ON_ROOT,
9048 		.read_u64 = cpu_weight_read_u64,
9049 		.write_u64 = cpu_weight_write_u64,
9050 	},
9051 	{
9052 		.name = "weight.nice",
9053 		.flags = CFTYPE_NOT_ON_ROOT,
9054 		.read_s64 = cpu_weight_nice_read_s64,
9055 		.write_s64 = cpu_weight_nice_write_s64,
9056 	},
9057 #endif
9058 #ifdef CONFIG_CFS_BANDWIDTH
9059 	{
9060 		.name = "max",
9061 		.flags = CFTYPE_NOT_ON_ROOT,
9062 		.seq_show = cpu_max_show,
9063 		.write = cpu_max_write,
9064 	},
9065 #endif
9066 #ifdef CONFIG_UCLAMP_TASK_GROUP
9067 	{
9068 		.name = "uclamp.min",
9069 		.flags = CFTYPE_NOT_ON_ROOT,
9070 		.seq_show = cpu_uclamp_min_show,
9071 		.write = cpu_uclamp_min_write,
9072 	},
9073 	{
9074 		.name = "uclamp.max",
9075 		.flags = CFTYPE_NOT_ON_ROOT,
9076 		.seq_show = cpu_uclamp_max_show,
9077 		.write = cpu_uclamp_max_write,
9078 	},
9079 #endif
9080 	{ }	/* terminate */
9081 };
9082 
9083 struct cgroup_subsys cpu_cgrp_subsys = {
9084 	.css_alloc	= cpu_cgroup_css_alloc,
9085 	.css_online	= cpu_cgroup_css_online,
9086 	.css_released	= cpu_cgroup_css_released,
9087 	.css_free	= cpu_cgroup_css_free,
9088 	.css_extra_stat_show = cpu_extra_stat_show,
9089 	.fork		= cpu_cgroup_fork,
9090 	.can_attach	= cpu_cgroup_can_attach,
9091 	.attach		= cpu_cgroup_attach,
9092 	.legacy_cftypes	= cpu_legacy_files,
9093 	.dfl_cftypes	= cpu_files,
9094 	.early_init	= true,
9095 	.threaded	= true,
9096 };
9097 
9098 #endif	/* CONFIG_CGROUP_SCHED */
9099 
dump_cpu_task(int cpu)9100 void dump_cpu_task(int cpu)
9101 {
9102 	pr_info("Task dump for CPU %d:\n", cpu);
9103 	sched_show_task(cpu_curr(cpu));
9104 }
9105 
9106 /*
9107  * Nice levels are multiplicative, with a gentle 10% change for every
9108  * nice level changed. I.e. when a CPU-bound task goes from nice 0 to
9109  * nice 1, it will get ~10% less CPU time than another CPU-bound task
9110  * that remained on nice 0.
9111  *
9112  * The "10% effect" is relative and cumulative: from _any_ nice level,
9113  * if you go up 1 level, it's -10% CPU usage, if you go down 1 level
9114  * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25.
9115  * If a task goes up by ~10% and another task goes down by ~10% then
9116  * the relative distance between them is ~25%.)
9117  */
9118 const int sched_prio_to_weight[40] = {
9119  /* -20 */     88761,     71755,     56483,     46273,     36291,
9120  /* -15 */     29154,     23254,     18705,     14949,     11916,
9121  /* -10 */      9548,      7620,      6100,      4904,      3906,
9122  /*  -5 */      3121,      2501,      1991,      1586,      1277,
9123  /*   0 */      1024,       820,       655,       526,       423,
9124  /*   5 */       335,       272,       215,       172,       137,
9125  /*  10 */       110,        87,        70,        56,        45,
9126  /*  15 */        36,        29,        23,        18,        15,
9127 };
9128 
9129 /*
9130  * Inverse (2^32/x) values of the sched_prio_to_weight[] array, precalculated.
9131  *
9132  * In cases where the weight does not change often, we can use the
9133  * precalculated inverse to speed up arithmetics by turning divisions
9134  * into multiplications:
9135  */
9136 const u32 sched_prio_to_wmult[40] = {
9137  /* -20 */     48388,     59856,     76040,     92818,    118348,
9138  /* -15 */    147320,    184698,    229616,    287308,    360437,
9139  /* -10 */    449829,    563644,    704093,    875809,   1099582,
9140  /*  -5 */   1376151,   1717300,   2157191,   2708050,   3363326,
9141  /*   0 */   4194304,   5237765,   6557202,   8165337,  10153587,
9142  /*   5 */  12820798,  15790321,  19976592,  24970740,  31350126,
9143  /*  10 */  39045157,  49367440,  61356676,  76695844,  95443717,
9144  /*  15 */ 119304647, 148102320, 186737708, 238609294, 286331153,
9145 };
9146 
9147 #ifdef CONFIG_SCHED_LATENCY_NICE
9148 /*
9149  * latency weight for wakeup preemption
9150  */
9151 const int sched_latency_to_weight[40] = {
9152  /* -20 */      1024,       973,       922,       870,       819,
9153  /* -15 */       768,       717,       666,       614,       563,
9154  /* -10 */       512,       461,       410,       358,       307,
9155  /*  -5 */       256,       205,       154,       102,       51,
9156  /*   0 */	   0,       -51,      -102,      -154,      -205,
9157  /*   5 */      -256,      -307,      -358,      -410,      -461,
9158  /*  10 */      -512,      -563,      -614,      -666,      -717,
9159  /*  15 */      -768,      -819,      -870,      -922,      -973,
9160 };
9161 #endif
9162 
call_trace_sched_update_nr_running(struct rq * rq,int count)9163 void call_trace_sched_update_nr_running(struct rq *rq, int count)
9164 {
9165         trace_sched_update_nr_running_tp(rq, count);
9166 }
9167 
9168 #ifdef CONFIG_SCHED_WALT
9169 /*
9170  * sched_exit() - Set EXITING_TASK_MARKER in task's ravg.demand field
9171  *
9172  * Stop accounting (exiting) task's future cpu usage
9173  *
9174  * We need this so that reset_all_windows_stats() can function correctly.
9175  * reset_all_window_stats() depends on do_each_thread/for_each_thread task
9176  * iterators to reset *all* task's statistics. Exiting tasks however become
9177  * invisible to those iterators. sched_exit() is called on a exiting task prior
9178  * to being removed from task_list, which will let reset_all_window_stats()
9179  * function correctly.
9180  */
sched_exit(struct task_struct * p)9181 void sched_exit(struct task_struct *p)
9182 {
9183 	struct rq_flags rf;
9184 	struct rq *rq;
9185 	u64 wallclock;
9186 
9187 #ifdef CONFIG_SCHED_RTG
9188 	sched_set_group_id(p, 0);
9189 #endif
9190 
9191 	rq = task_rq_lock(p, &rf);
9192 
9193 	/* rq->curr == p */
9194 	wallclock = sched_ktime_clock();
9195 	update_task_ravg(rq->curr, rq, TASK_UPDATE, wallclock, 0);
9196 	dequeue_task(rq, p, 0);
9197 	/*
9198 	 * task's contribution is already removed from the
9199 	 * cumulative window demand in dequeue. As the
9200 	 * task's stats are reset, the next enqueue does
9201 	 * not change the cumulative window demand.
9202 	 */
9203 	reset_task_stats(p);
9204 	p->ravg.mark_start = wallclock;
9205 	p->ravg.sum_history[0] = EXITING_TASK_MARKER;
9206 
9207 	enqueue_task(rq, p, 0);
9208 	task_rq_unlock(rq, p, &rf);
9209 	free_task_load_ptrs(p);
9210 }
9211 #endif /* CONFIG_SCHED_WALT */
9212