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