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