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