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