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