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