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