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