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