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