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 idle_stamp = rq->idle_stamp; 3746 u64 delta, max; 3747 3748 if (!idle_stamp) 3749 return; 3750 3751 delta = rq_clock(rq) - idle_stamp; 3752 3753 update_avg(&rq->avg_idle, delta); 3754 3755 max = 2 * rq->max_idle_balance_cost; 3756 if (rq->avg_idle > max) 3757 rq->avg_idle = max; 3758 rq->idle_stamp = 0; 3759 } 3760 3761 #ifdef CONFIG_SCHED_PROXY_EXEC 3762 static void zap_balance_callbacks(struct rq *rq); 3763 3764 static inline void proxy_reset_donor(struct rq *rq) 3765 { 3766 WARN_ON_ONCE(rq->donor == rq->curr); 3767 3768 put_prev_set_next_task(rq, rq->donor, rq->curr); 3769 rq_set_donor(rq, rq->curr); 3770 zap_balance_callbacks(rq); 3771 resched_curr(rq); 3772 } 3773 3774 /* 3775 * Checks to see if task p has been proxy-migrated to another rq 3776 * and needs to be returned. If so, we deactivate the task here 3777 * so that it can be properly woken up on the p->wake_cpu 3778 * (or whichever cpu select_task_rq() picks at the bottom of 3779 * try_to_wake_up() 3780 */ 3781 static inline bool proxy_needs_return(struct rq *rq, struct task_struct *p) 3782 { 3783 /* 3784 * Typically per __set_task_cpu(), task_cpu(p) == p->wake_cpu. 3785 * 3786 * However, proxy_set_task_cpu() is such that it preserves the 3787 * original cpu in p->wake_cpu while migrating p for proxy reasons 3788 * (possibly outside of the allowed p->cpus_ptr). 3789 * 3790 * Furthermore, migration_cpu_stop() / __migrate_swap_task(), will 3791 * only set p->wake_cpu when !p->on_rq, and since here p->on_rq, this 3792 * will not apply. But if it did, this check is the safe way around 3793 * and would migrate. 3794 */ 3795 if (task_cpu(p) == p->wake_cpu) 3796 return false; 3797 3798 scoped_guard(raw_spinlock, &p->blocked_lock) { 3799 /* Task is waking up; clear any blocked_on relationship */ 3800 __clear_task_blocked_on(p, NULL); 3801 3802 /* If already current, don't need to return migrate */ 3803 if (task_current(rq, p)) 3804 return false; 3805 3806 /* If we're return migrating the rq->donor, switch it out for idle */ 3807 if (task_current_donor(rq, p)) 3808 proxy_reset_donor(rq); 3809 } 3810 block_task(rq, p, TASK_WAKING); 3811 return true; 3812 } 3813 #else /* !CONFIG_SCHED_PROXY_EXEC */ 3814 static inline bool proxy_needs_return(struct rq *rq, struct task_struct *p) 3815 { 3816 return false; 3817 } 3818 #endif /* CONFIG_SCHED_PROXY_EXEC */ 3819 3820 static void 3821 ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags, 3822 struct rq_flags *rf) 3823 { 3824 int en_flags = ENQUEUE_WAKEUP | ENQUEUE_NOCLOCK; 3825 3826 lockdep_assert_rq_held(rq); 3827 3828 if (p->sched_contributes_to_load) 3829 rq->nr_uninterruptible--; 3830 3831 if (wake_flags & WF_RQ_SELECTED) 3832 en_flags |= ENQUEUE_RQ_SELECTED; 3833 if (wake_flags & WF_MIGRATED) 3834 en_flags |= ENQUEUE_MIGRATED; 3835 else if (p->in_iowait) { 3836 delayacct_blkio_end(p); 3837 atomic_dec(&task_rq(p)->nr_iowait); 3838 } 3839 3840 activate_task(rq, p, en_flags); 3841 wakeup_preempt(rq, p, wake_flags); 3842 3843 ttwu_do_wakeup(p); 3844 3845 if (p->sched_class->task_woken) { 3846 /* 3847 * Our task @p is fully woken up and running; so it's safe to 3848 * drop the rq->lock, hereafter rq is only used for statistics. 3849 */ 3850 rq_unpin_lock(rq, rf); 3851 p->sched_class->task_woken(rq, p); 3852 rq_repin_lock(rq, rf); 3853 } 3854 } 3855 3856 /* 3857 * Consider @p being inside a wait loop: 3858 * 3859 * for (;;) { 3860 * set_current_state(TASK_UNINTERRUPTIBLE); 3861 * 3862 * if (CONDITION) 3863 * break; 3864 * 3865 * schedule(); 3866 * } 3867 * __set_current_state(TASK_RUNNING); 3868 * 3869 * between set_current_state() and schedule(). In this case @p is still 3870 * runnable, so all that needs doing is change p->state back to TASK_RUNNING in 3871 * an atomic manner. 3872 * 3873 * By taking task_rq(p)->lock we serialize against schedule(), if @p->on_rq 3874 * then schedule() must still happen and p->state can be changed to 3875 * TASK_RUNNING. Otherwise we lost the race, schedule() has happened, and we 3876 * need to do a full wakeup with enqueue. 3877 * 3878 * Returns: %true when the wakeup is done, 3879 * %false otherwise. 3880 */ 3881 static int ttwu_runnable(struct task_struct *p, int wake_flags) 3882 { 3883 ACQUIRE(__task_rq_lock, guard)(p); 3884 struct rq *rq = guard.rq; 3885 3886 if (!task_on_rq_queued(p)) 3887 return 0; 3888 3889 update_rq_clock(rq); 3890 if (p->is_blocked) { 3891 if (p->se.sched_delayed) 3892 enqueue_task(rq, p, ENQUEUE_NOCLOCK | ENQUEUE_DELAYED); 3893 if (proxy_needs_return(rq, p)) 3894 return 0; 3895 } 3896 if (!task_on_cpu(rq, p)) { 3897 /* 3898 * When on_rq && !on_cpu the task is preempted, see if 3899 * it should preempt the task that is current now. 3900 */ 3901 wakeup_preempt(rq, p, wake_flags); 3902 } 3903 ttwu_do_wakeup(p); 3904 return 1; 3905 } 3906 3907 void sched_ttwu_pending(void *arg) 3908 { 3909 struct llist_node *llist = arg; 3910 struct rq *rq = this_rq(); 3911 struct task_struct *p, *t; 3912 struct rq_flags rf; 3913 3914 if (!llist) 3915 return; 3916 3917 rq_lock_irqsave(rq, &rf); 3918 update_rq_clock(rq); 3919 3920 llist_for_each_entry_safe(p, t, llist, wake_entry.llist) { 3921 if (WARN_ON_ONCE(p->on_cpu)) 3922 smp_cond_load_acquire(&p->on_cpu, !VAL); 3923 3924 if (WARN_ON_ONCE(task_cpu(p) != cpu_of(rq))) 3925 set_task_cpu(p, cpu_of(rq)); 3926 3927 ttwu_do_activate(rq, p, p->sched_remote_wakeup ? WF_MIGRATED : 0, &rf); 3928 } 3929 3930 /* 3931 * Must be after enqueueing at least once task such that 3932 * idle_cpu() does not observe a false-negative -- if it does, 3933 * it is possible for select_idle_siblings() to stack a number 3934 * of tasks on this CPU during that window. 3935 * 3936 * It is OK to clear ttwu_pending when another task pending. 3937 * We will receive IPI after local IRQ enabled and then enqueue it. 3938 * Since now nr_running > 0, idle_cpu() will always get correct result. 3939 */ 3940 WRITE_ONCE(rq->ttwu_pending, 0); 3941 rq_unlock_irqrestore(rq, &rf); 3942 } 3943 3944 /* 3945 * Prepare the scene for sending an IPI for a remote smp_call 3946 * 3947 * Returns true if the caller can proceed with sending the IPI. 3948 * Returns false otherwise. 3949 */ 3950 bool call_function_single_prep_ipi(int cpu) 3951 { 3952 if (set_nr_if_polling(cpu_rq(cpu)->idle)) { 3953 trace_sched_wake_idle_without_ipi(cpu); 3954 return false; 3955 } 3956 3957 return true; 3958 } 3959 3960 /* 3961 * Queue a task on the target CPUs wake_list and wake the CPU via IPI if 3962 * necessary. The wakee CPU on receipt of the IPI will queue the task 3963 * via sched_ttwu_wakeup() for activation so the wakee incurs the cost 3964 * of the wakeup instead of the waker. 3965 */ 3966 static void __ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags) 3967 { 3968 struct rq *rq = cpu_rq(cpu); 3969 3970 p->sched_remote_wakeup = !!(wake_flags & WF_MIGRATED); 3971 3972 WRITE_ONCE(rq->ttwu_pending, 1); 3973 #ifdef CONFIG_SMP 3974 __smp_call_single_queue(cpu, &p->wake_entry.llist); 3975 #endif 3976 } 3977 3978 void wake_up_if_idle(int cpu) 3979 { 3980 struct rq *rq = cpu_rq(cpu); 3981 3982 guard(rcu)(); 3983 if (is_idle_task(rcu_dereference(rq->curr))) { 3984 guard(rq_lock_irqsave)(rq); 3985 if (is_idle_task(rq->curr)) 3986 resched_curr(rq); 3987 } 3988 } 3989 3990 bool cpus_equal_capacity(int this_cpu, int that_cpu) 3991 { 3992 if (!sched_asym_cpucap_active()) 3993 return true; 3994 3995 if (this_cpu == that_cpu) 3996 return true; 3997 3998 return arch_scale_cpu_capacity(this_cpu) == arch_scale_cpu_capacity(that_cpu); 3999 } 4000 4001 bool cpus_share_cache(int this_cpu, int that_cpu) 4002 { 4003 if (this_cpu == that_cpu) 4004 return true; 4005 4006 return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu); 4007 } 4008 4009 /* 4010 * Whether CPUs are share cache resources, which means LLC on non-cluster 4011 * machines and LLC tag or L2 on machines with clusters. 4012 */ 4013 bool cpus_share_resources(int this_cpu, int that_cpu) 4014 { 4015 if (this_cpu == that_cpu) 4016 return true; 4017 4018 return per_cpu(sd_share_id, this_cpu) == per_cpu(sd_share_id, that_cpu); 4019 } 4020 4021 static inline bool ttwu_queue_cond(struct task_struct *p, int cpu) 4022 { 4023 int this_cpu = smp_processor_id(); 4024 4025 /* See SCX_OPS_ALLOW_QUEUED_WAKEUP. */ 4026 if (!scx_allow_ttwu_queue(p)) 4027 return false; 4028 4029 #ifdef CONFIG_SMP 4030 if (p->sched_class == &stop_sched_class) 4031 return false; 4032 #endif 4033 4034 /* 4035 * Do not complicate things with the async wake_list while the CPU is 4036 * in hotplug state. 4037 */ 4038 if (!cpu_active(cpu)) 4039 return false; 4040 4041 /* Ensure the task will still be allowed to run on the CPU. */ 4042 if (!cpumask_test_cpu(cpu, p->cpus_ptr)) 4043 return false; 4044 4045 /* 4046 * If the CPU does not share cache, then queue the task on the 4047 * remote rqs wakelist to avoid accessing remote data. 4048 */ 4049 if (!cpus_share_cache(this_cpu, cpu)) 4050 return true; 4051 4052 if (cpu == this_cpu) 4053 return false; 4054 4055 /* 4056 * If the wakee cpu is idle, or the task is descheduling and the 4057 * only running task on the CPU, then use the wakelist to offload 4058 * the task activation to the idle (or soon-to-be-idle) CPU as 4059 * the current CPU is likely busy. nr_running is checked to 4060 * avoid unnecessary task stacking. 4061 * 4062 * Note that we can only get here with (wakee) p->on_rq=0, 4063 * p->on_cpu can be whatever, we've done the dequeue, so 4064 * the wakee has been accounted out of ->nr_running. 4065 */ 4066 if (!cpu_rq(cpu)->nr_running) 4067 return true; 4068 4069 return false; 4070 } 4071 4072 static bool ttwu_queue_wakelist(struct task_struct *p, int cpu, int wake_flags) 4073 { 4074 if (sched_feat(TTWU_QUEUE) && ttwu_queue_cond(p, cpu)) { 4075 sched_clock_cpu(cpu); /* Sync clocks across CPUs */ 4076 __ttwu_queue_wakelist(p, cpu, wake_flags); 4077 return true; 4078 } 4079 4080 return false; 4081 } 4082 4083 static void ttwu_queue(struct task_struct *p, int cpu, int wake_flags) 4084 { 4085 struct rq *rq = cpu_rq(cpu); 4086 struct rq_flags rf; 4087 4088 if (ttwu_queue_wakelist(p, cpu, wake_flags)) 4089 return; 4090 4091 rq_lock(rq, &rf); 4092 update_rq_clock(rq); 4093 ttwu_do_activate(rq, p, wake_flags, &rf); 4094 rq_unlock(rq, &rf); 4095 } 4096 4097 /* 4098 * Invoked from try_to_wake_up() to check whether the task can be woken up. 4099 * 4100 * The caller holds p::pi_lock if p != current or has preemption 4101 * disabled when p == current. 4102 * 4103 * The rules of saved_state: 4104 * 4105 * The related locking code always holds p::pi_lock when updating 4106 * p::saved_state, which means the code is fully serialized in both cases. 4107 * 4108 * For PREEMPT_RT, the lock wait and lock wakeups happen via TASK_RTLOCK_WAIT. 4109 * No other bits set. This allows to distinguish all wakeup scenarios. 4110 * 4111 * For FREEZER, the wakeup happens via TASK_FROZEN. No other bits set. This 4112 * allows us to prevent early wakeup of tasks before they can be run on 4113 * asymmetric ISA architectures (eg ARMv9). 4114 */ 4115 static __always_inline 4116 bool ttwu_state_match(struct task_struct *p, unsigned int state, int *success) 4117 { 4118 int match; 4119 4120 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)) { 4121 WARN_ON_ONCE((state & TASK_RTLOCK_WAIT) && 4122 state != TASK_RTLOCK_WAIT); 4123 } 4124 4125 *success = !!(match = __task_state_match(p, state)); 4126 4127 /* 4128 * Saved state preserves the task state across blocking on 4129 * an RT lock or TASK_FREEZABLE tasks. If the state matches, 4130 * set p::saved_state to TASK_RUNNING, but do not wake the task 4131 * because it waits for a lock wakeup or __thaw_task(). Also 4132 * indicate success because from the regular waker's point of 4133 * view this has succeeded. 4134 * 4135 * After acquiring the lock the task will restore p::__state 4136 * from p::saved_state which ensures that the regular 4137 * wakeup is not lost. The restore will also set 4138 * p::saved_state to TASK_RUNNING so any further tests will 4139 * not result in false positives vs. @success 4140 */ 4141 if (match < 0) 4142 p->saved_state = TASK_RUNNING; 4143 4144 return match > 0; 4145 } 4146 4147 /* 4148 * Notes on Program-Order guarantees on SMP systems. 4149 * 4150 * MIGRATION 4151 * 4152 * The basic program-order guarantee on SMP systems is that when a task [t] 4153 * migrates, all its activity on its old CPU [c0] happens-before any subsequent 4154 * execution on its new CPU [c1]. 4155 * 4156 * For migration (of runnable tasks) this is provided by the following means: 4157 * 4158 * A) UNLOCK of the rq(c0)->lock scheduling out task t 4159 * B) migration for t is required to synchronize *both* rq(c0)->lock and 4160 * rq(c1)->lock (if not at the same time, then in that order). 4161 * C) LOCK of the rq(c1)->lock scheduling in task 4162 * 4163 * Release/acquire chaining guarantees that B happens after A and C after B. 4164 * Note: the CPU doing B need not be c0 or c1 4165 * 4166 * Example: 4167 * 4168 * CPU0 CPU1 CPU2 4169 * 4170 * LOCK rq(0)->lock 4171 * sched-out X 4172 * sched-in Y 4173 * UNLOCK rq(0)->lock 4174 * 4175 * LOCK rq(0)->lock // orders against CPU0 4176 * dequeue X 4177 * UNLOCK rq(0)->lock 4178 * 4179 * LOCK rq(1)->lock 4180 * enqueue X 4181 * UNLOCK rq(1)->lock 4182 * 4183 * LOCK rq(1)->lock // orders against CPU2 4184 * sched-out Z 4185 * sched-in X 4186 * UNLOCK rq(1)->lock 4187 * 4188 * 4189 * BLOCKING -- aka. SLEEP + WAKEUP 4190 * 4191 * For blocking we (obviously) need to provide the same guarantee as for 4192 * migration. However the means are completely different as there is no lock 4193 * chain to provide order. Instead we do: 4194 * 4195 * 1) smp_store_release(X->on_cpu, 0) -- finish_task() 4196 * 2) smp_cond_load_acquire(!X->on_cpu) -- try_to_wake_up() 4197 * 4198 * Example: 4199 * 4200 * CPU0 (schedule) CPU1 (try_to_wake_up) CPU2 (schedule) 4201 * 4202 * LOCK rq(0)->lock LOCK X->pi_lock 4203 * dequeue X 4204 * sched-out X 4205 * smp_store_release(X->on_cpu, 0); 4206 * 4207 * smp_cond_load_acquire(&X->on_cpu, !VAL); 4208 * X->state = WAKING 4209 * set_task_cpu(X,2) 4210 * 4211 * LOCK rq(2)->lock 4212 * enqueue X 4213 * X->state = RUNNING 4214 * UNLOCK rq(2)->lock 4215 * 4216 * LOCK rq(2)->lock // orders against CPU1 4217 * sched-out Z 4218 * sched-in X 4219 * UNLOCK rq(2)->lock 4220 * 4221 * UNLOCK X->pi_lock 4222 * UNLOCK rq(0)->lock 4223 * 4224 * 4225 * However, for wakeups there is a second guarantee we must provide, namely we 4226 * must ensure that CONDITION=1 done by the caller can not be reordered with 4227 * accesses to the task state; see try_to_wake_up() and set_current_state(). 4228 */ 4229 4230 /** 4231 * try_to_wake_up - wake up a thread 4232 * @p: the thread to be awakened 4233 * @state: the mask of task states that can be woken 4234 * @wake_flags: wake modifier flags (WF_*) 4235 * 4236 * Conceptually does: 4237 * 4238 * If (@state & @p->state) @p->state = TASK_RUNNING. 4239 * 4240 * If the task was not queued/runnable, also place it back on a runqueue. 4241 * 4242 * This function is atomic against schedule() which would dequeue the task. 4243 * 4244 * It issues a full memory barrier before accessing @p->state, see the comment 4245 * with set_current_state(). 4246 * 4247 * Uses p->pi_lock to serialize against concurrent wake-ups. 4248 * 4249 * Relies on p->pi_lock stabilizing: 4250 * - p->sched_class 4251 * - p->cpus_ptr 4252 * - p->sched_task_group 4253 * in order to do migration, see its use of select_task_rq()/set_task_cpu(). 4254 * 4255 * Tries really hard to only take one task_rq(p)->lock for performance. 4256 * Takes rq->lock in: 4257 * - ttwu_runnable() -- old rq, unavoidable, see comment there; 4258 * - ttwu_queue() -- new rq, for enqueue of the task; 4259 * - psi_ttwu_dequeue() -- much sadness :-( accounting will kill us. 4260 * 4261 * As a consequence we race really badly with just about everything. See the 4262 * many memory barriers and their comments for details. 4263 * 4264 * Return: %true if @p->state changes (an actual wakeup was done), 4265 * %false otherwise. 4266 */ 4267 int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags) 4268 { 4269 guard(preempt)(); 4270 int cpu, success = 0; 4271 4272 wake_flags |= WF_TTWU; 4273 4274 if (p == current) { 4275 /* 4276 * We're waking current, this means 'p->on_rq' and 'task_cpu(p) 4277 * == smp_processor_id()'. Together this means we can special 4278 * case the whole 'p->on_rq && ttwu_runnable()' case below 4279 * without taking any locks. 4280 * 4281 * Specifically, given current runs ttwu() we must be before 4282 * schedule()'s block_task(), as such this must not observe 4283 * sched_delayed. 4284 * 4285 * In particular: 4286 * - we rely on Program-Order guarantees for all the ordering, 4287 * - we're serialized against set_special_state() by virtue of 4288 * it disabling IRQs (this allows not taking ->pi_lock). 4289 */ 4290 WARN_ON_ONCE(p->se.sched_delayed); 4291 WARN_ON_ONCE(p->is_blocked); 4292 /* If p is current, we know we can run here, so clear blocked_on */ 4293 clear_task_blocked_on(p, NULL); 4294 if (!ttwu_state_match(p, state, &success)) 4295 goto out; 4296 4297 trace_sched_waking(p); 4298 ttwu_do_wakeup(p); 4299 goto out; 4300 } 4301 4302 /* 4303 * If we are going to wake up a thread waiting for CONDITION we 4304 * need to ensure that CONDITION=1 done by the caller can not be 4305 * reordered with p->state check below. This pairs with smp_store_mb() 4306 * in set_current_state() that the waiting thread does. 4307 */ 4308 scoped_guard (raw_spinlock_irqsave, &p->pi_lock) { 4309 smp_mb__after_spinlock(); 4310 4311 if (!ttwu_state_match(p, state, &success)) 4312 break; 4313 4314 trace_sched_waking(p); 4315 4316 /* 4317 * Ensure we load p->on_rq _after_ p->state, otherwise it would 4318 * be possible to, falsely, observe p->on_rq == 0 and get stuck 4319 * in smp_cond_load_acquire() below. 4320 * 4321 * sched_ttwu_pending() try_to_wake_up() 4322 * STORE p->on_rq = 1 LOAD p->state 4323 * UNLOCK rq->lock 4324 * 4325 * __schedule() (switch to task 'p') 4326 * LOCK rq->lock smp_rmb(); 4327 * smp_mb__after_spinlock(); 4328 * UNLOCK rq->lock 4329 * 4330 * [task p] 4331 * STORE p->state = UNINTERRUPTIBLE LOAD p->on_rq 4332 * 4333 * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in 4334 * __schedule(). See the comment for smp_mb__after_spinlock(). 4335 * 4336 * A similar smp_rmb() lives in __task_needs_rq_lock(). 4337 */ 4338 smp_rmb(); 4339 if (READ_ONCE(p->on_rq) && ttwu_runnable(p, wake_flags)) 4340 break; 4341 4342 /* 4343 * Ensure we load p->on_cpu _after_ p->on_rq, otherwise it would be 4344 * possible to, falsely, observe p->on_cpu == 0. 4345 * 4346 * One must be running (->on_cpu == 1) in order to remove oneself 4347 * from the runqueue. 4348 * 4349 * __schedule() (switch to task 'p') try_to_wake_up() 4350 * STORE p->on_cpu = 1 LOAD p->on_rq 4351 * UNLOCK rq->lock 4352 * 4353 * __schedule() (put 'p' to sleep) 4354 * LOCK rq->lock smp_rmb(); 4355 * smp_mb__after_spinlock(); 4356 * STORE p->on_rq = 0 LOAD p->on_cpu 4357 * 4358 * Pairs with the LOCK+smp_mb__after_spinlock() on rq->lock in 4359 * __schedule(). See the comment for smp_mb__after_spinlock(). 4360 * 4361 * Form a control-dep-acquire with p->on_rq == 0 above, to ensure 4362 * schedule()'s block_task() has 'happened' and p will no longer 4363 * care about it's own p->state. See the comment in __schedule(). 4364 */ 4365 smp_acquire__after_ctrl_dep(); 4366 4367 /* 4368 * We're doing the wakeup (@success == 1), they did a dequeue (p->on_rq 4369 * == 0), which means we need to do an enqueue, change p->state to 4370 * TASK_WAKING such that we can unlock p->pi_lock before doing the 4371 * enqueue, such as ttwu_queue_wakelist(). 4372 */ 4373 WRITE_ONCE(p->__state, TASK_WAKING); 4374 4375 /* 4376 * If the owning (remote) CPU is still in the middle of schedule() with 4377 * this task as prev, considering queueing p on the remote CPUs wake_list 4378 * which potentially sends an IPI instead of spinning on p->on_cpu to 4379 * let the waker make forward progress. This is safe because IRQs are 4380 * disabled and the IPI will deliver after on_cpu is cleared. 4381 * 4382 * Ensure we load task_cpu(p) after p->on_cpu: 4383 * 4384 * set_task_cpu(p, cpu); 4385 * STORE p->cpu = @cpu 4386 * __schedule() (switch to task 'p') 4387 * LOCK rq->lock 4388 * smp_mb__after_spin_lock() smp_cond_load_acquire(&p->on_cpu) 4389 * STORE p->on_cpu = 1 LOAD p->cpu 4390 * 4391 * to ensure we observe the correct CPU on which the task is currently 4392 * scheduling. 4393 */ 4394 if (smp_load_acquire(&p->on_cpu) && 4395 ttwu_queue_wakelist(p, task_cpu(p), wake_flags)) 4396 break; 4397 4398 /* 4399 * If the owning (remote) CPU is still in the middle of schedule() with 4400 * this task as prev, wait until it's done referencing the task. 4401 * 4402 * Pairs with the smp_store_release() in finish_task(). 4403 * 4404 * This ensures that tasks getting woken will be fully ordered against 4405 * their previous state and preserve Program Order. 4406 */ 4407 smp_cond_load_acquire(&p->on_cpu, !VAL); 4408 4409 cpu = select_task_rq(p, p->wake_cpu, &wake_flags); 4410 if (task_cpu(p) != cpu) { 4411 if (p->in_iowait) { 4412 delayacct_blkio_end(p); 4413 atomic_dec(&task_rq(p)->nr_iowait); 4414 } 4415 4416 wake_flags |= WF_MIGRATED; 4417 psi_ttwu_dequeue(p); 4418 set_task_cpu(p, cpu); 4419 } else if (cpu != p->wake_cpu) { 4420 /* 4421 * If we were proxy-migrated to cpu, then 4422 * select_task_rq() picks cpu instead of wake_cpu 4423 * to return to, we won't call set_task_cpu(), 4424 * leaving a stale wake_cpu pointing to where we 4425 * proxy-migrated from. So just fixup wake_cpu here 4426 * if its not correct 4427 */ 4428 p->wake_cpu = cpu; 4429 } 4430 4431 ttwu_queue(p, cpu, wake_flags); 4432 } 4433 out: 4434 if (success) 4435 ttwu_stat(p, task_cpu(p), wake_flags); 4436 4437 return success; 4438 } 4439 4440 static bool __task_needs_rq_lock(struct task_struct *p) 4441 { 4442 unsigned int state = READ_ONCE(p->__state); 4443 4444 /* 4445 * Since pi->lock blocks try_to_wake_up(), we don't need rq->lock when 4446 * the task is blocked. Make sure to check @state since ttwu() can drop 4447 * locks at the end, see ttwu_queue_wakelist(). 4448 */ 4449 if (state == TASK_RUNNING || state == TASK_WAKING) 4450 return true; 4451 4452 /* 4453 * Ensure we load p->on_rq after p->__state, otherwise it would be 4454 * possible to, falsely, observe p->on_rq == 0. 4455 * 4456 * See try_to_wake_up() for a longer comment. 4457 */ 4458 smp_rmb(); 4459 if (p->on_rq) 4460 return true; 4461 4462 /* 4463 * Ensure the task has finished __schedule() and will not be referenced 4464 * anymore. Again, see try_to_wake_up() for a longer comment. 4465 */ 4466 smp_rmb(); 4467 smp_cond_load_acquire(&p->on_cpu, !VAL); 4468 4469 return false; 4470 } 4471 4472 /** 4473 * task_call_func - Invoke a function on task in fixed state 4474 * @p: Process for which the function is to be invoked, can be @current. 4475 * @func: Function to invoke. 4476 * @arg: Argument to function. 4477 * 4478 * Fix the task in it's current state by avoiding wakeups and or rq operations 4479 * and call @func(@arg) on it. This function can use task_is_runnable() and 4480 * task_curr() to work out what the state is, if required. Given that @func 4481 * can be invoked with a runqueue lock held, it had better be quite 4482 * lightweight. 4483 * 4484 * Returns: 4485 * Whatever @func returns 4486 */ 4487 int task_call_func(struct task_struct *p, task_call_f func, void *arg) 4488 { 4489 struct rq_flags rf; 4490 int ret; 4491 4492 raw_spin_lock_irqsave(&p->pi_lock, rf.flags); 4493 4494 if (__task_needs_rq_lock(p)) { 4495 struct rq *rq = __task_rq_lock(p, &rf); 4496 4497 /* 4498 * At this point the task is pinned; either: 4499 * - blocked and we're holding off wakeups (pi->lock) 4500 * - woken, and we're holding off enqueue (rq->lock) 4501 * - queued, and we're holding off schedule (rq->lock) 4502 * - running, and we're holding off de-schedule (rq->lock) 4503 * 4504 * The called function (@func) can use: task_curr(), p->on_rq and 4505 * p->__state to differentiate between these states. 4506 */ 4507 ret = func(p, arg); 4508 4509 __task_rq_unlock(rq, p, &rf); 4510 } else { 4511 ret = func(p, arg); 4512 } 4513 4514 raw_spin_unlock_irqrestore(&p->pi_lock, rf.flags); 4515 return ret; 4516 } 4517 4518 /** 4519 * cpu_curr_snapshot - Return a snapshot of the currently running task 4520 * @cpu: The CPU on which to snapshot the task. 4521 * 4522 * Returns the task_struct pointer of the task "currently" running on 4523 * the specified CPU. 4524 * 4525 * If the specified CPU was offline, the return value is whatever it 4526 * is, perhaps a pointer to the task_struct structure of that CPU's idle 4527 * task, but there is no guarantee. Callers wishing a useful return 4528 * value must take some action to ensure that the specified CPU remains 4529 * online throughout. 4530 * 4531 * This function executes full memory barriers before and after fetching 4532 * the pointer, which permits the caller to confine this function's fetch 4533 * with respect to the caller's accesses to other shared variables. 4534 */ 4535 struct task_struct *cpu_curr_snapshot(int cpu) 4536 { 4537 struct rq *rq = cpu_rq(cpu); 4538 struct task_struct *t; 4539 struct rq_flags rf; 4540 4541 rq_lock_irqsave(rq, &rf); 4542 smp_mb__after_spinlock(); /* Pairing determined by caller's synchronization design. */ 4543 t = rcu_dereference(cpu_curr(cpu)); 4544 rq_unlock_irqrestore(rq, &rf); 4545 smp_mb(); /* Pairing determined by caller's synchronization design. */ 4546 4547 return t; 4548 } 4549 4550 /** 4551 * wake_up_process - Wake up a specific process 4552 * @p: The process to be woken up. 4553 * 4554 * Attempt to wake up the nominated process and move it to the set of runnable 4555 * processes. 4556 * 4557 * Return: 1 if the process was woken up, 0 if it was already running. 4558 * 4559 * This function executes a full memory barrier before accessing the task state. 4560 */ 4561 int wake_up_process(struct task_struct *p) 4562 { 4563 return try_to_wake_up(p, TASK_NORMAL, 0); 4564 } 4565 EXPORT_SYMBOL(wake_up_process); 4566 4567 int wake_up_state(struct task_struct *p, unsigned int state) 4568 { 4569 return try_to_wake_up(p, state, 0); 4570 } 4571 4572 /* 4573 * Perform scheduler related setup for a newly forked process p. 4574 * p is forked by current. 4575 * 4576 * __sched_fork() is basic setup which is also used by sched_init() to 4577 * initialize the boot CPU's idle task. 4578 */ 4579 static void __sched_fork(u64 clone_flags, struct task_struct *p) 4580 { 4581 p->on_rq = 0; 4582 4583 p->se.on_rq = 0; 4584 p->se.exec_start = 0; 4585 p->se.sum_exec_runtime = 0; 4586 p->se.prev_sum_exec_runtime = 0; 4587 p->se.nr_migrations = 0; 4588 p->se.vruntime = 0; 4589 p->se.vlag = 0; 4590 p->se.rel_deadline = 0; 4591 INIT_LIST_HEAD(&p->se.group_node); 4592 4593 /* A delayed task cannot be in clone(). */ 4594 WARN_ON_ONCE(p->se.sched_delayed); 4595 WARN_ON_ONCE(p->is_blocked); 4596 4597 #ifdef CONFIG_FAIR_GROUP_SCHED 4598 p->se.cfs_rq = NULL; 4599 #ifdef CONFIG_CFS_BANDWIDTH 4600 init_cfs_throttle_work(p); 4601 #endif 4602 #endif 4603 4604 #ifdef CONFIG_SCHEDSTATS 4605 /* Even if schedstat is disabled, there should not be garbage */ 4606 memset(&p->stats, 0, sizeof(p->stats)); 4607 #endif 4608 4609 init_dl_entity(&p->dl); 4610 4611 INIT_LIST_HEAD(&p->rt.run_list); 4612 p->rt.timeout = 0; 4613 p->rt.time_slice = sched_rr_timeslice; 4614 p->rt.on_rq = 0; 4615 p->rt.on_list = 0; 4616 4617 #ifdef CONFIG_SCHED_CLASS_EXT 4618 init_scx_entity(&p->scx); 4619 #endif 4620 4621 #ifdef CONFIG_PREEMPT_NOTIFIERS 4622 INIT_HLIST_HEAD(&p->preempt_notifiers); 4623 #endif 4624 4625 #ifdef CONFIG_COMPACTION 4626 p->capture_control = NULL; 4627 #endif 4628 init_numa_balancing(clone_flags, p); 4629 p->wake_entry.u_flags = CSD_TYPE_TTWU; 4630 p->migration_pending = NULL; 4631 init_sched_mm(p); 4632 } 4633 4634 DEFINE_STATIC_KEY_FALSE(sched_numa_balancing); 4635 4636 #ifdef CONFIG_NUMA_BALANCING 4637 4638 int sysctl_numa_balancing_mode; 4639 4640 static void __set_numabalancing_state(bool enabled) 4641 { 4642 if (enabled) 4643 static_branch_enable(&sched_numa_balancing); 4644 else 4645 static_branch_disable(&sched_numa_balancing); 4646 } 4647 4648 void set_numabalancing_state(bool enabled) 4649 { 4650 if (enabled) 4651 sysctl_numa_balancing_mode = NUMA_BALANCING_NORMAL; 4652 else 4653 sysctl_numa_balancing_mode = NUMA_BALANCING_DISABLED; 4654 __set_numabalancing_state(enabled); 4655 } 4656 4657 #ifdef CONFIG_SYSCTL 4658 static void reset_memory_tiering(void) 4659 { 4660 struct pglist_data *pgdat; 4661 4662 for_each_online_pgdat(pgdat) { 4663 pgdat->nbp_threshold = 0; 4664 pgdat->nbp_th_nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE); 4665 pgdat->nbp_th_start = jiffies_to_msecs(jiffies); 4666 } 4667 } 4668 4669 static int sysctl_numa_balancing(const struct ctl_table *table, int write, 4670 void *buffer, size_t *lenp, loff_t *ppos) 4671 { 4672 struct ctl_table t; 4673 int err; 4674 int state = sysctl_numa_balancing_mode; 4675 4676 if (write && !capable(CAP_SYS_ADMIN)) 4677 return -EPERM; 4678 4679 t = *table; 4680 t.data = &state; 4681 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos); 4682 if (err < 0) 4683 return err; 4684 if (write) { 4685 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) && 4686 (state & NUMA_BALANCING_MEMORY_TIERING)) 4687 reset_memory_tiering(); 4688 sysctl_numa_balancing_mode = state; 4689 __set_numabalancing_state(state); 4690 } 4691 return err; 4692 } 4693 #endif /* CONFIG_SYSCTL */ 4694 #endif /* CONFIG_NUMA_BALANCING */ 4695 4696 #ifdef CONFIG_SCHEDSTATS 4697 4698 DEFINE_STATIC_KEY_FALSE(sched_schedstats); 4699 4700 static void set_schedstats(bool enabled) 4701 { 4702 if (enabled) 4703 static_branch_enable(&sched_schedstats); 4704 else 4705 static_branch_disable(&sched_schedstats); 4706 } 4707 4708 void force_schedstat_enabled(void) 4709 { 4710 if (!schedstat_enabled()) { 4711 pr_info("kernel profiling enabled schedstats, disable via kernel.sched_schedstats.\n"); 4712 static_branch_enable(&sched_schedstats); 4713 } 4714 } 4715 4716 static int __init setup_schedstats(char *str) 4717 { 4718 int ret = 0; 4719 if (!str) 4720 goto out; 4721 4722 if (!strcmp(str, "enable")) { 4723 set_schedstats(true); 4724 ret = 1; 4725 } else if (!strcmp(str, "disable")) { 4726 set_schedstats(false); 4727 ret = 1; 4728 } 4729 out: 4730 if (!ret) 4731 pr_warn("Unable to parse schedstats=\n"); 4732 4733 return ret; 4734 } 4735 __setup("schedstats=", setup_schedstats); 4736 4737 #ifdef CONFIG_SYSCTL 4738 static int sysctl_schedstats(const struct ctl_table *table, int write, void *buffer, 4739 size_t *lenp, loff_t *ppos) 4740 { 4741 struct ctl_table t; 4742 int err; 4743 int state = static_branch_likely(&sched_schedstats); 4744 4745 if (write && !capable(CAP_SYS_ADMIN)) 4746 return -EPERM; 4747 4748 t = *table; 4749 t.data = &state; 4750 err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos); 4751 if (err < 0) 4752 return err; 4753 if (write) 4754 set_schedstats(state); 4755 return err; 4756 } 4757 #endif /* CONFIG_SYSCTL */ 4758 #endif /* CONFIG_SCHEDSTATS */ 4759 4760 #ifdef CONFIG_SYSCTL 4761 static const struct ctl_table sched_core_sysctls[] = { 4762 #ifdef CONFIG_SCHEDSTATS 4763 { 4764 .procname = "sched_schedstats", 4765 .data = NULL, 4766 .maxlen = sizeof(unsigned int), 4767 .mode = 0644, 4768 .proc_handler = sysctl_schedstats, 4769 .extra1 = SYSCTL_ZERO, 4770 .extra2 = SYSCTL_ONE, 4771 }, 4772 #endif /* CONFIG_SCHEDSTATS */ 4773 #ifdef CONFIG_UCLAMP_TASK 4774 { 4775 .procname = "sched_util_clamp_min", 4776 .data = &sysctl_sched_uclamp_util_min, 4777 .maxlen = sizeof(unsigned int), 4778 .mode = 0644, 4779 .proc_handler = sysctl_sched_uclamp_handler, 4780 }, 4781 { 4782 .procname = "sched_util_clamp_max", 4783 .data = &sysctl_sched_uclamp_util_max, 4784 .maxlen = sizeof(unsigned int), 4785 .mode = 0644, 4786 .proc_handler = sysctl_sched_uclamp_handler, 4787 }, 4788 { 4789 .procname = "sched_util_clamp_min_rt_default", 4790 .data = &sysctl_sched_uclamp_util_min_rt_default, 4791 .maxlen = sizeof(unsigned int), 4792 .mode = 0644, 4793 .proc_handler = sysctl_sched_uclamp_handler, 4794 }, 4795 #endif /* CONFIG_UCLAMP_TASK */ 4796 #ifdef CONFIG_NUMA_BALANCING 4797 { 4798 .procname = "numa_balancing", 4799 .data = NULL, /* filled in by handler */ 4800 .maxlen = sizeof(unsigned int), 4801 .mode = 0644, 4802 .proc_handler = sysctl_numa_balancing, 4803 .extra1 = SYSCTL_ZERO, 4804 .extra2 = SYSCTL_FOUR, 4805 }, 4806 #endif /* CONFIG_NUMA_BALANCING */ 4807 }; 4808 static int __init sched_core_sysctl_init(void) 4809 { 4810 register_sysctl_init("kernel", sched_core_sysctls); 4811 return 0; 4812 } 4813 late_initcall(sched_core_sysctl_init); 4814 #endif /* CONFIG_SYSCTL */ 4815 4816 /* 4817 * fork()/clone()-time setup: 4818 */ 4819 int sched_fork(u64 clone_flags, struct task_struct *p) 4820 { 4821 __sched_fork(clone_flags, p); 4822 /* 4823 * We mark the process as NEW here. This guarantees that 4824 * nobody will actually run it, and a signal or other external 4825 * event cannot wake it up and insert it on the runqueue either. 4826 */ 4827 p->__state = TASK_NEW; 4828 4829 /* 4830 * Make sure we do not leak PI boosting priority to the child. 4831 */ 4832 p->prio = current->normal_prio; 4833 4834 uclamp_fork(p); 4835 4836 /* 4837 * Revert to default priority/policy on fork if requested. 4838 */ 4839 if (unlikely(p->sched_reset_on_fork)) { 4840 if (task_has_dl_policy(p) || task_has_rt_policy(p)) { 4841 p->policy = SCHED_NORMAL; 4842 p->static_prio = NICE_TO_PRIO(0); 4843 p->rt_priority = 0; 4844 p->timer_slack_ns = p->default_timer_slack_ns; 4845 } else if (PRIO_TO_NICE(p->static_prio) < 0) 4846 p->static_prio = NICE_TO_PRIO(0); 4847 4848 p->prio = p->normal_prio = p->static_prio; 4849 set_load_weight(p, false); 4850 p->se.custom_slice = 0; 4851 p->se.slice = sysctl_sched_base_slice; 4852 4853 /* 4854 * We don't need the reset flag anymore after the fork. It has 4855 * fulfilled its duty: 4856 */ 4857 p->sched_reset_on_fork = 0; 4858 } 4859 4860 if (dl_prio(p->prio)) 4861 return -EAGAIN; 4862 4863 scx_pre_fork(p); 4864 4865 if (rt_prio(p->prio)) { 4866 p->sched_class = &rt_sched_class; 4867 #ifdef CONFIG_SCHED_CLASS_EXT 4868 } else if (task_should_scx(p->policy)) { 4869 p->sched_class = &ext_sched_class; 4870 #endif 4871 } else { 4872 p->sched_class = &fair_sched_class; 4873 } 4874 4875 init_entity_runnable_average(&p->se); 4876 4877 4878 #ifdef CONFIG_SCHED_INFO 4879 if (likely(sched_info_on())) 4880 memset(&p->sched_info, 0, sizeof(p->sched_info)); 4881 #endif 4882 p->on_cpu = 0; 4883 init_task_preempt_count(p); 4884 plist_node_init(&p->pushable_tasks, MAX_PRIO); 4885 RB_CLEAR_NODE(&p->pushable_dl_tasks); 4886 4887 return 0; 4888 } 4889 4890 int sched_cgroup_fork(struct task_struct *p, struct kernel_clone_args *kargs) 4891 { 4892 unsigned long flags; 4893 4894 /* 4895 * Because we're not yet on the pid-hash, p->pi_lock isn't strictly 4896 * required yet, but lockdep gets upset if rules are violated. 4897 */ 4898 raw_spin_lock_irqsave(&p->pi_lock, flags); 4899 #ifdef CONFIG_CGROUP_SCHED 4900 if (1) { 4901 struct task_group *tg; 4902 tg = container_of(kargs->cset->subsys[cpu_cgrp_id], 4903 struct task_group, css); 4904 tg = autogroup_task_group(p, tg); 4905 p->sched_task_group = tg; 4906 } 4907 #endif 4908 /* 4909 * We're setting the CPU for the first time, we don't migrate, 4910 * so use __set_task_cpu(). 4911 */ 4912 __set_task_cpu(p, smp_processor_id()); 4913 if (p->sched_class->task_fork) 4914 p->sched_class->task_fork(p); 4915 raw_spin_unlock_irqrestore(&p->pi_lock, flags); 4916 4917 return scx_fork(p, kargs); 4918 } 4919 4920 void sched_cancel_fork(struct task_struct *p) 4921 { 4922 scx_cancel_fork(p); 4923 } 4924 4925 static void sched_mm_cid_fork(struct task_struct *t); 4926 4927 void sched_post_fork(struct task_struct *p) 4928 { 4929 sched_mm_cid_fork(p); 4930 uclamp_post_fork(p); 4931 scx_post_fork(p); 4932 } 4933 4934 u64 to_ratio(u64 period, u64 runtime) 4935 { 4936 if (runtime == RUNTIME_INF) 4937 return BW_UNIT; 4938 4939 /* 4940 * Doing this here saves a lot of checks in all 4941 * the calling paths, and returning zero seems 4942 * safe for them anyway. 4943 */ 4944 if (period == 0) 4945 return 0; 4946 4947 return div64_u64(runtime << BW_SHIFT, period); 4948 } 4949 4950 /* 4951 * wake_up_new_task - wake up a newly created task for the first time. 4952 * 4953 * This function will do some initial scheduler statistics housekeeping 4954 * that must be done for every newly created context, then puts the task 4955 * on the runqueue and wakes it. 4956 */ 4957 void wake_up_new_task(struct task_struct *p) 4958 { 4959 struct rq_flags rf; 4960 struct rq *rq; 4961 int wake_flags = WF_FORK; 4962 4963 raw_spin_lock_irqsave(&p->pi_lock, rf.flags); 4964 WRITE_ONCE(p->__state, TASK_RUNNING); 4965 /* 4966 * Fork balancing, do it here and not earlier because: 4967 * - cpus_ptr can change in the fork path 4968 * - any previously selected CPU might disappear through hotplug 4969 * 4970 * Use __set_task_cpu() to avoid calling sched_class::migrate_task_rq, 4971 * as we're not fully set-up yet. 4972 */ 4973 p->recent_used_cpu = task_cpu(p); 4974 __set_task_cpu(p, select_task_rq(p, task_cpu(p), &wake_flags)); 4975 rq = __task_rq_lock(p, &rf); 4976 update_rq_clock(rq); 4977 post_init_entity_util_avg(p); 4978 4979 activate_task(rq, p, ENQUEUE_NOCLOCK | ENQUEUE_INITIAL); 4980 trace_sched_wakeup_new(p); 4981 wakeup_preempt(rq, p, wake_flags); 4982 if (p->sched_class->task_woken) { 4983 /* 4984 * Nothing relies on rq->lock after this, so it's fine to 4985 * drop it. 4986 */ 4987 rq_unpin_lock(rq, &rf); 4988 p->sched_class->task_woken(rq, p); 4989 rq_repin_lock(rq, &rf); 4990 } 4991 task_rq_unlock(rq, p, &rf); 4992 } 4993 4994 #ifdef CONFIG_PREEMPT_NOTIFIERS 4995 4996 static DEFINE_STATIC_KEY_FALSE(preempt_notifier_key); 4997 4998 void preempt_notifier_inc(void) 4999 { 5000 static_branch_inc(&preempt_notifier_key); 5001 } 5002 EXPORT_SYMBOL_GPL(preempt_notifier_inc); 5003 5004 void preempt_notifier_dec(void) 5005 { 5006 static_branch_dec(&preempt_notifier_key); 5007 } 5008 EXPORT_SYMBOL_GPL(preempt_notifier_dec); 5009 5010 /** 5011 * preempt_notifier_register - tell me when current is being preempted & rescheduled 5012 * @notifier: notifier struct to register 5013 */ 5014 void preempt_notifier_register(struct preempt_notifier *notifier) 5015 { 5016 if (!static_branch_unlikely(&preempt_notifier_key)) 5017 WARN(1, "registering preempt_notifier while notifiers disabled\n"); 5018 5019 hlist_add_head(¬ifier->link, ¤t->preempt_notifiers); 5020 } 5021 EXPORT_SYMBOL_GPL(preempt_notifier_register); 5022 5023 /** 5024 * preempt_notifier_unregister - no longer interested in preemption notifications 5025 * @notifier: notifier struct to unregister 5026 * 5027 * This is *not* safe to call from within a preemption notifier. 5028 */ 5029 void preempt_notifier_unregister(struct preempt_notifier *notifier) 5030 { 5031 hlist_del(¬ifier->link); 5032 } 5033 EXPORT_SYMBOL_GPL(preempt_notifier_unregister); 5034 5035 static void __fire_sched_in_preempt_notifiers(struct task_struct *curr) 5036 { 5037 struct preempt_notifier *notifier; 5038 5039 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link) 5040 notifier->ops->sched_in(notifier, raw_smp_processor_id()); 5041 } 5042 5043 static __always_inline void fire_sched_in_preempt_notifiers(struct task_struct *curr) 5044 { 5045 if (static_branch_unlikely(&preempt_notifier_key)) 5046 __fire_sched_in_preempt_notifiers(curr); 5047 } 5048 5049 static void 5050 __fire_sched_out_preempt_notifiers(struct task_struct *curr, 5051 struct task_struct *next) 5052 { 5053 struct preempt_notifier *notifier; 5054 5055 hlist_for_each_entry(notifier, &curr->preempt_notifiers, link) 5056 notifier->ops->sched_out(notifier, next); 5057 } 5058 5059 static __always_inline void 5060 fire_sched_out_preempt_notifiers(struct task_struct *curr, 5061 struct task_struct *next) 5062 { 5063 if (static_branch_unlikely(&preempt_notifier_key)) 5064 __fire_sched_out_preempt_notifiers(curr, next); 5065 } 5066 5067 #else /* !CONFIG_PREEMPT_NOTIFIERS: */ 5068 5069 static inline void fire_sched_in_preempt_notifiers(struct task_struct *curr) 5070 { 5071 } 5072 5073 static inline void 5074 fire_sched_out_preempt_notifiers(struct task_struct *curr, 5075 struct task_struct *next) 5076 { 5077 } 5078 5079 #endif /* !CONFIG_PREEMPT_NOTIFIERS */ 5080 5081 static inline void prepare_task(struct task_struct *next) 5082 { 5083 /* 5084 * Claim the task as running, we do this before switching to it 5085 * such that any running task will have this set. 5086 * 5087 * See the smp_load_acquire(&p->on_cpu) case in ttwu() and 5088 * its ordering comment. 5089 */ 5090 WRITE_ONCE(next->on_cpu, 1); 5091 } 5092 5093 static inline void finish_task(struct task_struct *prev) 5094 { 5095 /* 5096 * This must be the very last reference to @prev from this CPU. After 5097 * p->on_cpu is cleared, the task can be moved to a different CPU. We 5098 * must ensure this doesn't happen until the switch is completely 5099 * finished. 5100 * 5101 * In particular, the load of prev->state in finish_task_switch() must 5102 * happen before this. 5103 * 5104 * Pairs with the smp_cond_load_acquire() in try_to_wake_up(). 5105 */ 5106 smp_store_release(&prev->on_cpu, 0); 5107 } 5108 5109 /* 5110 * Only called from __schedule context 5111 * 5112 * There are some cases where we are going to re-do the action 5113 * that added the balance callbacks. We may not be in a state 5114 * where we can run them, so just zap them so they can be 5115 * properly re-added on the next time around. This is similar 5116 * handling to running the callbacks, except we just don't call 5117 * them. 5118 */ 5119 static void zap_balance_callbacks(struct rq *rq) 5120 { 5121 struct balance_callback *next, *head; 5122 bool found = false; 5123 5124 lockdep_assert_rq_held(rq); 5125 5126 head = rq->balance_callback; 5127 while (head) { 5128 if (head == &balance_push_callback) 5129 found = true; 5130 next = head->next; 5131 head->next = NULL; 5132 head = next; 5133 } 5134 rq->balance_callback = found ? &balance_push_callback : NULL; 5135 } 5136 5137 static void do_balance_callbacks(struct rq *rq, struct balance_callback *head) 5138 { 5139 void (*func)(struct rq *rq); 5140 struct balance_callback *next; 5141 5142 lockdep_assert_rq_held(rq); 5143 5144 while (head) { 5145 func = (void (*)(struct rq *))head->func; 5146 next = head->next; 5147 head->next = NULL; 5148 head = next; 5149 5150 func(rq); 5151 } 5152 } 5153 5154 static void balance_push(struct rq *rq); 5155 5156 /* 5157 * balance_push_callback is a right abuse of the callback interface and plays 5158 * by significantly different rules. 5159 * 5160 * Where the normal balance_callback's purpose is to be ran in the same context 5161 * that queued it (only later, when it's safe to drop rq->lock again), 5162 * balance_push_callback is specifically targeted at __schedule(). 5163 * 5164 * This abuse is tolerated because it places all the unlikely/odd cases behind 5165 * a single test, namely: rq->balance_callback == NULL. 5166 */ 5167 struct balance_callback balance_push_callback = { 5168 .next = NULL, 5169 .func = balance_push, 5170 }; 5171 5172 static inline struct balance_callback * 5173 __splice_balance_callbacks(struct rq *rq, bool split) 5174 { 5175 struct balance_callback *head = rq->balance_callback; 5176 5177 if (likely(!head)) 5178 return NULL; 5179 5180 lockdep_assert_rq_held(rq); 5181 /* 5182 * Must not take balance_push_callback off the list when 5183 * splice_balance_callbacks() and balance_callbacks() are not 5184 * in the same rq->lock section. 5185 * 5186 * In that case it would be possible for __schedule() to interleave 5187 * and observe the list empty. 5188 */ 5189 if (split && head == &balance_push_callback) 5190 head = NULL; 5191 else 5192 rq->balance_callback = NULL; 5193 5194 return head; 5195 } 5196 5197 struct balance_callback *splice_balance_callbacks(struct rq *rq) 5198 { 5199 return __splice_balance_callbacks(rq, true); 5200 } 5201 5202 void __balance_callbacks(struct rq *rq, struct rq_flags *rf) 5203 { 5204 if (rf) 5205 rq_unpin_lock(rq, rf); 5206 do_balance_callbacks(rq, __splice_balance_callbacks(rq, false)); 5207 if (rf) 5208 rq_repin_lock(rq, rf); 5209 } 5210 5211 void balance_callbacks(struct rq *rq, struct balance_callback *head) 5212 { 5213 unsigned long flags; 5214 5215 if (unlikely(head)) { 5216 raw_spin_rq_lock_irqsave(rq, flags); 5217 do_balance_callbacks(rq, head); 5218 raw_spin_rq_unlock_irqrestore(rq, flags); 5219 } 5220 } 5221 5222 static inline void 5223 prepare_lock_switch(struct rq *rq, struct task_struct *next, struct rq_flags *rf) 5224 __releases(__rq_lockp(rq)) 5225 __acquires(__rq_lockp(this_rq())) 5226 { 5227 /* 5228 * Since the runqueue lock will be released by the next 5229 * task (which is an invalid locking op but in the case 5230 * of the scheduler it's an obvious special-case), so we 5231 * do an early lockdep release here: 5232 */ 5233 rq_unpin_lock(rq, rf); 5234 spin_release(&__rq_lockp(rq)->dep_map, _THIS_IP_); 5235 #ifdef CONFIG_DEBUG_SPINLOCK 5236 /* this is a valid case when another task releases the spinlock */ 5237 rq_lockp(rq)->owner = next; 5238 #endif 5239 /* 5240 * Model the rq reference switcheroo. 5241 */ 5242 __release(__rq_lockp(rq)); 5243 __acquire(__rq_lockp(this_rq())); 5244 } 5245 5246 static inline void finish_lock_switch(struct rq *rq) 5247 __releases(__rq_lockp(rq)) 5248 { 5249 /* 5250 * If we are tracking spinlock dependencies then we have to 5251 * fix up the runqueue lock - which gets 'carried over' from 5252 * prev into current: 5253 */ 5254 spin_acquire(&__rq_lockp(rq)->dep_map, 0, 0, _THIS_IP_); 5255 __balance_callbacks(rq, NULL); 5256 hrtick_schedule_exit(rq); 5257 raw_spin_rq_unlock_irq(rq); 5258 } 5259 5260 /* 5261 * NOP if the arch has not defined these: 5262 */ 5263 5264 #ifndef prepare_arch_switch 5265 # define prepare_arch_switch(next) do { } while (0) 5266 #endif 5267 5268 #ifndef finish_arch_post_lock_switch 5269 # define finish_arch_post_lock_switch() do { } while (0) 5270 #endif 5271 5272 static inline void kmap_local_sched_out(void) 5273 { 5274 #ifdef CONFIG_KMAP_LOCAL 5275 if (unlikely(current->kmap_ctrl.idx)) 5276 __kmap_local_sched_out(); 5277 #endif 5278 } 5279 5280 static inline void kmap_local_sched_in(void) 5281 { 5282 #ifdef CONFIG_KMAP_LOCAL 5283 if (unlikely(current->kmap_ctrl.idx)) 5284 __kmap_local_sched_in(); 5285 #endif 5286 } 5287 5288 /** 5289 * prepare_task_switch - prepare to switch tasks 5290 * @rq: the runqueue preparing to switch 5291 * @prev: the current task that is being switched out 5292 * @next: the task we are going to switch to. 5293 * 5294 * This is called with the rq lock held and interrupts off. It must 5295 * be paired with a subsequent finish_task_switch after the context 5296 * switch. 5297 * 5298 * prepare_task_switch sets up locking and calls architecture specific 5299 * hooks. 5300 */ 5301 static inline void 5302 prepare_task_switch(struct rq *rq, struct task_struct *prev, 5303 struct task_struct *next) 5304 __must_hold(__rq_lockp(rq)) 5305 { 5306 kcov_prepare_switch(prev); 5307 sched_info_switch(rq, prev, next); 5308 perf_event_task_sched_out(prev, next); 5309 fire_sched_out_preempt_notifiers(prev, next); 5310 kmap_local_sched_out(); 5311 prepare_task(next); 5312 prepare_arch_switch(next); 5313 } 5314 5315 /** 5316 * finish_task_switch - clean up after a task-switch 5317 * @prev: the thread we just switched away from. 5318 * 5319 * finish_task_switch must be called after the context switch, paired 5320 * with a prepare_task_switch call before the context switch. 5321 * finish_task_switch will reconcile locking set up by prepare_task_switch, 5322 * and do any other architecture-specific cleanup actions. 5323 * 5324 * Note that we may have delayed dropping an mm in context_switch(). If 5325 * so, we finish that here outside of the runqueue lock. (Doing it 5326 * with the lock held can cause deadlocks; see schedule() for 5327 * details.) 5328 * 5329 * The context switch have flipped the stack from under us and restored the 5330 * local variables which were saved when this task called schedule() in the 5331 * past. 'prev == current' is still correct but we need to recalculate this_rq 5332 * because prev may have moved to another CPU. 5333 */ 5334 static struct rq *finish_task_switch(struct task_struct *prev) 5335 __releases(__rq_lockp(this_rq())) 5336 { 5337 struct rq *rq = this_rq(); 5338 struct mm_struct *mm = rq->prev_mm; 5339 unsigned int prev_state; 5340 5341 /* 5342 * The previous task will have left us with a preempt_count of 2 5343 * because it left us after: 5344 * 5345 * schedule() 5346 * preempt_disable(); // 1 5347 * __schedule() 5348 * raw_spin_lock_irq(&rq->lock) // 2 5349 * 5350 * Also, see FORK_PREEMPT_COUNT. 5351 */ 5352 if (WARN_ONCE(preempt_count() != 2*PREEMPT_DISABLE_OFFSET, 5353 "corrupted preempt_count: %s/%d/0x%x\n", 5354 current->comm, current->pid, preempt_count())) 5355 preempt_count_set(FORK_PREEMPT_COUNT); 5356 5357 rq->prev_mm = NULL; 5358 5359 /* 5360 * A task struct has one reference for the use as "current". 5361 * If a task dies, then it sets TASK_DEAD in tsk->state and calls 5362 * schedule one last time. The schedule call will never return, and 5363 * the scheduled task must drop that reference. 5364 * 5365 * We must observe prev->state before clearing prev->on_cpu (in 5366 * finish_task), otherwise a concurrent wakeup can get prev 5367 * running on another CPU and we could rave with its RUNNING -> DEAD 5368 * transition, resulting in a double drop. 5369 */ 5370 prev_state = READ_ONCE(prev->__state); 5371 vtime_task_switch(prev); 5372 perf_event_task_sched_in(prev, current); 5373 finish_task(prev); 5374 tick_nohz_task_switch(); 5375 finish_lock_switch(rq); 5376 finish_arch_post_lock_switch(); 5377 kcov_finish_switch(current); 5378 /* 5379 * kmap_local_sched_out() is invoked with rq::lock held and 5380 * interrupts disabled. There is no requirement for that, but the 5381 * sched out code does not have an interrupt enabled section. 5382 * Restoring the maps on sched in does not require interrupts being 5383 * disabled either. 5384 */ 5385 kmap_local_sched_in(); 5386 5387 /* 5388 * Any cached block-layer timestamp (plug->cur_ktime) is stale now, 5389 * invalidate it. 5390 */ 5391 blk_plug_invalidate_ts(); 5392 5393 fire_sched_in_preempt_notifiers(current); 5394 /* 5395 * When switching through a kernel thread, the loop in 5396 * membarrier_{private,global}_expedited() may have observed that 5397 * kernel thread and not issued an IPI. It is therefore possible to 5398 * schedule between user->kernel->user threads without passing though 5399 * switch_mm(). Membarrier requires a barrier after storing to 5400 * rq->curr, before returning to userspace, so provide them here: 5401 * 5402 * - a full memory barrier for {PRIVATE,GLOBAL}_EXPEDITED, implicitly 5403 * provided by mmdrop_lazy_tlb(), 5404 * - a sync_core for SYNC_CORE. 5405 */ 5406 if (mm) { 5407 membarrier_mm_sync_core_before_usermode(mm); 5408 mmdrop_lazy_tlb_sched(mm); 5409 } 5410 5411 if (unlikely(prev_state == TASK_DEAD)) { 5412 if (prev->sched_class->task_dead) 5413 prev->sched_class->task_dead(prev); 5414 5415 /* 5416 * sched_ext_dead() must come before cgroup_task_dead() to 5417 * prevent cgroups from being removed while its member tasks are 5418 * visible to SCX schedulers. 5419 */ 5420 sched_ext_dead(prev); 5421 cgroup_task_dead(prev); 5422 5423 /* Task is done with its stack. */ 5424 put_task_stack(prev); 5425 5426 put_task_struct_rcu_user(prev); 5427 } 5428 5429 return rq; 5430 } 5431 5432 /** 5433 * schedule_tail - first thing a freshly forked thread must call. 5434 * @prev: the thread we just switched away from. 5435 */ 5436 asmlinkage __visible void schedule_tail(struct task_struct *prev) 5437 __releases(__rq_lockp(this_rq())) 5438 { 5439 /* 5440 * New tasks start with FORK_PREEMPT_COUNT, see there and 5441 * finish_task_switch() for details. 5442 * 5443 * finish_task_switch() will drop rq->lock() and lower preempt_count 5444 * and the preempt_enable() will end up enabling preemption (on 5445 * PREEMPT_COUNT kernels). 5446 */ 5447 5448 finish_task_switch(prev); 5449 /* 5450 * This is a special case: the newly created task has just 5451 * switched the context for the first time. It is returning from 5452 * schedule for the first time in this path. 5453 */ 5454 trace_sched_exit_tp(true); 5455 preempt_enable(); 5456 5457 if (current->set_child_tid) 5458 put_user(task_pid_vnr(current), current->set_child_tid); 5459 5460 calculate_sigpending(); 5461 } 5462 5463 /* 5464 * context_switch - switch to the new MM and the new thread's register state. 5465 */ 5466 static __always_inline struct rq * 5467 context_switch(struct rq *rq, struct task_struct *prev, 5468 struct task_struct *next, struct rq_flags *rf) 5469 __releases(__rq_lockp(rq)) 5470 { 5471 prepare_task_switch(rq, prev, next); 5472 5473 /* 5474 * For paravirt, this is coupled with an exit in switch_to to 5475 * combine the page table reload and the switch backend into 5476 * one hypercall. 5477 */ 5478 arch_start_context_switch(prev); 5479 5480 /* 5481 * kernel -> kernel lazy + transfer active 5482 * user -> kernel lazy + mmgrab_lazy_tlb() active 5483 * 5484 * kernel -> user switch + mmdrop_lazy_tlb() active 5485 * user -> user switch 5486 */ 5487 if (!next->mm) { // to kernel 5488 enter_lazy_tlb(prev->active_mm, next); 5489 5490 next->active_mm = prev->active_mm; 5491 if (prev->mm) // from user 5492 mmgrab_lazy_tlb(prev->active_mm); 5493 else 5494 prev->active_mm = NULL; 5495 } else { // to user 5496 membarrier_switch_mm(rq, prev->active_mm, next->mm); 5497 /* 5498 * sys_membarrier() requires an smp_mb() between setting 5499 * rq->curr / membarrier_switch_mm() and returning to userspace. 5500 * 5501 * The below provides this either through switch_mm(), or in 5502 * case 'prev->active_mm == next->mm' through 5503 * finish_task_switch()'s mmdrop(). 5504 */ 5505 switch_mm_irqs_off(prev->active_mm, next->mm, next); 5506 lru_gen_use_mm(next->mm); 5507 5508 if (!prev->mm) { // from kernel 5509 /* will mmdrop_lazy_tlb() in finish_task_switch(). */ 5510 rq->prev_mm = prev->active_mm; 5511 prev->active_mm = NULL; 5512 } 5513 } 5514 5515 mm_cid_switch_to(prev, next); 5516 5517 /* 5518 * Tell rseq that the task was scheduled in. Must be after 5519 * switch_mm_cid() to get the TIF flag set. 5520 */ 5521 rseq_sched_switch_event(next); 5522 5523 prepare_lock_switch(rq, next, rf); 5524 5525 /* Here we just switch the register state and the stack. */ 5526 switch_to(prev, next, prev); 5527 barrier(); 5528 5529 return finish_task_switch(prev); 5530 } 5531 5532 /* 5533 * nr_running and nr_context_switches: 5534 * 5535 * externally visible scheduler statistics: current number of runnable 5536 * threads, total number of context switches performed since bootup. 5537 */ 5538 unsigned int nr_running(void) 5539 { 5540 unsigned int i, sum = 0; 5541 5542 for_each_online_cpu(i) 5543 sum += cpu_rq(i)->nr_running; 5544 5545 return sum; 5546 } 5547 5548 /* 5549 * Check if only the current task is running on the CPU. 5550 * 5551 * Caution: this function does not check that the caller has disabled 5552 * preemption, thus the result might have a time-of-check-to-time-of-use 5553 * race. The caller is responsible to use it correctly, for example: 5554 * 5555 * - from a non-preemptible section (of course) 5556 * 5557 * - from a thread that is bound to a single CPU 5558 * 5559 * - in a loop with very short iterations (e.g. a polling loop) 5560 */ 5561 bool single_task_running(void) 5562 { 5563 return raw_rq()->nr_running == 1; 5564 } 5565 EXPORT_SYMBOL(single_task_running); 5566 5567 unsigned long long nr_context_switches_cpu(int cpu) 5568 { 5569 return cpu_rq(cpu)->nr_switches; 5570 } 5571 5572 unsigned long long nr_context_switches(void) 5573 { 5574 int i; 5575 unsigned long long sum = 0; 5576 5577 for_each_possible_cpu(i) 5578 sum += cpu_rq(i)->nr_switches; 5579 5580 return sum; 5581 } 5582 5583 /* 5584 * Consumers of these two interfaces, like for example the cpuidle menu 5585 * governor, are using nonsensical data. Preferring shallow idle state selection 5586 * for a CPU that has IO-wait which might not even end up running the task when 5587 * it does become runnable. 5588 */ 5589 5590 unsigned int nr_iowait_cpu(int cpu) 5591 { 5592 return atomic_read(&cpu_rq(cpu)->nr_iowait); 5593 } 5594 5595 /* 5596 * IO-wait accounting, and how it's mostly bollocks (on SMP). 5597 * 5598 * The idea behind IO-wait account is to account the idle time that we could 5599 * have spend running if it were not for IO. That is, if we were to improve the 5600 * storage performance, we'd have a proportional reduction in IO-wait time. 5601 * 5602 * This all works nicely on UP, where, when a task blocks on IO, we account 5603 * idle time as IO-wait, because if the storage were faster, it could've been 5604 * running and we'd not be idle. 5605 * 5606 * This has been extended to SMP, by doing the same for each CPU. This however 5607 * is broken. 5608 * 5609 * Imagine for instance the case where two tasks block on one CPU, only the one 5610 * CPU will have IO-wait accounted, while the other has regular idle. Even 5611 * though, if the storage were faster, both could've ran at the same time, 5612 * utilising both CPUs. 5613 * 5614 * This means, that when looking globally, the current IO-wait accounting on 5615 * SMP is a lower bound, by reason of under accounting. 5616 * 5617 * Worse, since the numbers are provided per CPU, they are sometimes 5618 * interpreted per CPU, and that is nonsensical. A blocked task isn't strictly 5619 * associated with any one particular CPU, it can wake to another CPU than it 5620 * blocked on. This means the per CPU IO-wait number is meaningless. 5621 * 5622 * Task CPU affinities can make all that even more 'interesting'. 5623 */ 5624 5625 unsigned int nr_iowait(void) 5626 { 5627 unsigned int i, sum = 0; 5628 5629 for_each_possible_cpu(i) 5630 sum += nr_iowait_cpu(i); 5631 5632 return sum; 5633 } 5634 5635 /* 5636 * sched_exec - execve() is a valuable balancing opportunity, because at 5637 * this point the task has the smallest effective memory and cache footprint. 5638 */ 5639 void sched_exec(void) 5640 { 5641 struct task_struct *p = current; 5642 struct migration_arg arg; 5643 int dest_cpu; 5644 5645 scoped_guard (raw_spinlock_irqsave, &p->pi_lock) { 5646 dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), WF_EXEC); 5647 if (dest_cpu == smp_processor_id()) 5648 return; 5649 5650 if (unlikely(!cpu_active(dest_cpu))) 5651 return; 5652 5653 arg = (struct migration_arg){ p, dest_cpu }; 5654 } 5655 stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg); 5656 } 5657 5658 DEFINE_PER_CPU(struct kernel_stat, kstat); 5659 DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat) = { 5660 #ifdef CONFIG_NO_HZ_COMMON 5661 .idle_sleeptime_seq = SEQCNT_ZERO(kernel_cpustat.idle_sleeptime_seq) 5662 #endif 5663 }; 5664 5665 EXPORT_PER_CPU_SYMBOL(kstat); 5666 EXPORT_PER_CPU_SYMBOL(kernel_cpustat); 5667 5668 /* 5669 * The function fair_sched_class.update_curr accesses the struct curr 5670 * and its field curr->exec_start; when called from task_sched_runtime(), 5671 * we observe a high rate of cache misses in practice. 5672 * Prefetching this data results in improved performance. 5673 */ 5674 static inline void prefetch_curr_exec_start(struct task_struct *p) 5675 { 5676 struct sched_entity *curr = task_rq(p)->cfs.curr; 5677 5678 prefetch(curr); 5679 prefetch(&curr->exec_start); 5680 } 5681 5682 /* 5683 * Return accounted runtime for the task. 5684 * In case the task is currently running, return the runtime plus current's 5685 * pending runtime that have not been accounted yet. 5686 */ 5687 unsigned long long task_sched_runtime(struct task_struct *p) 5688 { 5689 struct rq_flags rf; 5690 struct rq *rq; 5691 u64 ns; 5692 5693 #ifdef CONFIG_64BIT 5694 /* 5695 * 64-bit doesn't need locks to atomically read a 64-bit value. 5696 * So we have a optimization chance when the task's delta_exec is 0. 5697 * Reading ->on_cpu is racy, but this is OK. 5698 * 5699 * If we race with it leaving CPU, we'll take a lock. So we're correct. 5700 * If we race with it entering CPU, unaccounted time is 0. This is 5701 * indistinguishable from the read occurring a few cycles earlier. 5702 * If we see ->on_cpu without ->on_rq, the task is leaving, and has 5703 * been accounted, so we're correct here as well. 5704 */ 5705 if (!p->on_cpu || !task_on_rq_queued(p)) 5706 return p->se.sum_exec_runtime; 5707 #endif 5708 5709 rq = task_rq_lock(p, &rf); 5710 /* 5711 * Must be ->curr _and_ ->on_rq. If dequeued, we would 5712 * project cycles that may never be accounted to this 5713 * thread, breaking clock_gettime(). 5714 */ 5715 if (task_current_donor(rq, p) && task_on_rq_queued(p)) { 5716 prefetch_curr_exec_start(p); 5717 update_rq_clock(rq); 5718 p->sched_class->update_curr(rq); 5719 } 5720 ns = p->se.sum_exec_runtime; 5721 task_rq_unlock(rq, p, &rf); 5722 5723 return ns; 5724 } 5725 5726 static u64 cpu_resched_latency(struct rq *rq) 5727 { 5728 int latency_warn_ms = READ_ONCE(sysctl_resched_latency_warn_ms); 5729 u64 resched_latency, now = rq_clock(rq); 5730 static bool warned_once; 5731 5732 if (sysctl_resched_latency_warn_once && warned_once) 5733 return 0; 5734 5735 if (!need_resched() || !latency_warn_ms) 5736 return 0; 5737 5738 if (system_state == SYSTEM_BOOTING) 5739 return 0; 5740 5741 if (!rq->last_seen_need_resched_ns) { 5742 rq->last_seen_need_resched_ns = now; 5743 rq->ticks_without_resched = 0; 5744 return 0; 5745 } 5746 5747 rq->ticks_without_resched++; 5748 resched_latency = now - rq->last_seen_need_resched_ns; 5749 if (resched_latency <= latency_warn_ms * NSEC_PER_MSEC) 5750 return 0; 5751 5752 warned_once = true; 5753 5754 return resched_latency; 5755 } 5756 5757 static int __init setup_resched_latency_warn_ms(char *str) 5758 { 5759 long val; 5760 5761 if ((kstrtol(str, 0, &val))) { 5762 pr_warn("Unable to set resched_latency_warn_ms\n"); 5763 return 1; 5764 } 5765 5766 sysctl_resched_latency_warn_ms = val; 5767 return 1; 5768 } 5769 __setup("resched_latency_warn_ms=", setup_resched_latency_warn_ms); 5770 5771 /* 5772 * This function gets called by the timer code, with HZ frequency. 5773 * We call it with interrupts disabled. 5774 */ 5775 void sched_tick(void) 5776 { 5777 int cpu = smp_processor_id(); 5778 struct rq *rq = cpu_rq(cpu); 5779 /* scheduler accounting goes to the donor task */ 5780 struct task_struct *curr, *donor; 5781 struct rq_flags rf; 5782 unsigned long hw_pressure; 5783 u64 resched_latency; 5784 5785 if (housekeeping_cpu(cpu, HK_TYPE_KERNEL_NOISE)) 5786 arch_scale_freq_tick(); 5787 5788 sched_clock_tick(); 5789 5790 rq_lock(rq, &rf); 5791 curr = rq->curr; 5792 donor = rq->donor; 5793 5794 psi_account_irqtime(rq, donor, NULL); 5795 5796 update_rq_clock(rq); 5797 hw_pressure = arch_scale_hw_pressure(cpu_of(rq)); 5798 update_hw_load_avg(rq_clock_task(rq), rq, hw_pressure); 5799 5800 if (dynamic_preempt_lazy() && tif_test_bit(TIF_NEED_RESCHED_LAZY)) 5801 resched_curr(rq); 5802 5803 donor->sched_class->task_tick(rq, donor, 0); 5804 if (sched_feat(LATENCY_WARN)) 5805 resched_latency = cpu_resched_latency(rq); 5806 calc_global_load_tick(rq); 5807 sched_core_tick(rq); 5808 scx_tick(rq); 5809 5810 rq_unlock(rq, &rf); 5811 5812 if (sched_feat(LATENCY_WARN) && resched_latency) 5813 resched_latency_warn(cpu, resched_latency); 5814 5815 perf_event_task_tick(); 5816 5817 if (curr->flags & PF_WQ_WORKER) 5818 wq_worker_tick(curr); 5819 5820 if (!scx_switched_all()) { 5821 rq->idle_balance = idle_cpu(cpu); 5822 sched_balance_trigger(rq); 5823 } 5824 } 5825 5826 #ifdef CONFIG_NO_HZ_FULL 5827 5828 struct tick_work { 5829 int cpu; 5830 atomic_t state; 5831 struct delayed_work work; 5832 }; 5833 /* Values for ->state, see diagram below. */ 5834 #define TICK_SCHED_REMOTE_OFFLINE 0 5835 #define TICK_SCHED_REMOTE_OFFLINING 1 5836 #define TICK_SCHED_REMOTE_RUNNING 2 5837 5838 /* 5839 * State diagram for ->state: 5840 * 5841 * 5842 * TICK_SCHED_REMOTE_OFFLINE 5843 * | ^ 5844 * | | 5845 * | | sched_tick_remote() 5846 * | | 5847 * | | 5848 * +--TICK_SCHED_REMOTE_OFFLINING 5849 * | ^ 5850 * | | 5851 * sched_tick_start() | | sched_tick_stop() 5852 * | | 5853 * V | 5854 * TICK_SCHED_REMOTE_RUNNING 5855 * 5856 * 5857 * Other transitions get WARN_ON_ONCE(), except that sched_tick_remote() 5858 * and sched_tick_start() are happy to leave the state in RUNNING. 5859 */ 5860 5861 static struct tick_work __percpu *tick_work_cpu; 5862 5863 static void sched_tick_remote(struct work_struct *work) 5864 { 5865 struct delayed_work *dwork = to_delayed_work(work); 5866 struct tick_work *twork = container_of(dwork, struct tick_work, work); 5867 int cpu = twork->cpu; 5868 struct rq *rq = cpu_rq(cpu); 5869 int os; 5870 5871 /* 5872 * Handle the tick only if it appears the remote CPU is running in full 5873 * dynticks mode. The check is racy by nature, but missing a tick or 5874 * having one too much is no big deal because the scheduler tick updates 5875 * statistics and checks timeslices in a time-independent way, regardless 5876 * of when exactly it is running. 5877 */ 5878 if (tick_nohz_tick_stopped_cpu(cpu)) { 5879 guard(rq_lock_irq)(rq); 5880 struct task_struct *curr = rq->curr; 5881 5882 if (cpu_online(cpu)) { 5883 /* 5884 * Since this is a remote tick for full dynticks mode, 5885 * we are always sure that there is no proxy (only a 5886 * single task is running). 5887 */ 5888 WARN_ON_ONCE(rq->curr != rq->donor); 5889 update_rq_clock(rq); 5890 5891 if (!is_idle_task(curr)) { 5892 /* 5893 * Make sure the next tick runs within a 5894 * reasonable amount of time. 5895 */ 5896 u64 delta = rq_clock_task(rq) - curr->se.exec_start; 5897 WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 30); 5898 } 5899 curr->sched_class->task_tick(rq, curr, 0); 5900 5901 calc_load_nohz_remote(rq); 5902 } 5903 } 5904 5905 /* 5906 * Run the remote tick once per second (1Hz). This arbitrary 5907 * frequency is large enough to avoid overload but short enough 5908 * to keep scheduler internal stats reasonably up to date. But 5909 * first update state to reflect hotplug activity if required. 5910 */ 5911 os = atomic_fetch_add_unless(&twork->state, -1, TICK_SCHED_REMOTE_RUNNING); 5912 WARN_ON_ONCE(os == TICK_SCHED_REMOTE_OFFLINE); 5913 if (os == TICK_SCHED_REMOTE_RUNNING) 5914 queue_delayed_work(system_dfl_wq, dwork, HZ); 5915 } 5916 5917 static void sched_tick_start(int cpu) 5918 { 5919 int os; 5920 struct tick_work *twork; 5921 5922 if (housekeeping_cpu(cpu, HK_TYPE_KERNEL_NOISE)) 5923 return; 5924 5925 WARN_ON_ONCE(!tick_work_cpu); 5926 5927 twork = per_cpu_ptr(tick_work_cpu, cpu); 5928 os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_RUNNING); 5929 WARN_ON_ONCE(os == TICK_SCHED_REMOTE_RUNNING); 5930 if (os == TICK_SCHED_REMOTE_OFFLINE) { 5931 twork->cpu = cpu; 5932 INIT_DELAYED_WORK(&twork->work, sched_tick_remote); 5933 queue_delayed_work(system_dfl_wq, &twork->work, HZ); 5934 } 5935 } 5936 5937 #ifdef CONFIG_HOTPLUG_CPU 5938 static void sched_tick_stop(int cpu) 5939 { 5940 struct tick_work *twork; 5941 int os; 5942 5943 if (housekeeping_cpu(cpu, HK_TYPE_KERNEL_NOISE)) 5944 return; 5945 5946 WARN_ON_ONCE(!tick_work_cpu); 5947 5948 twork = per_cpu_ptr(tick_work_cpu, cpu); 5949 /* There cannot be competing actions, but don't rely on stop-machine. */ 5950 os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_OFFLINING); 5951 WARN_ON_ONCE(os != TICK_SCHED_REMOTE_RUNNING); 5952 /* Don't cancel, as this would mess up the state machine. */ 5953 } 5954 #endif /* CONFIG_HOTPLUG_CPU */ 5955 5956 int __init sched_tick_offload_init(void) 5957 { 5958 tick_work_cpu = alloc_percpu(struct tick_work); 5959 BUG_ON(!tick_work_cpu); 5960 return 0; 5961 } 5962 5963 #else /* !CONFIG_NO_HZ_FULL: */ 5964 static inline void sched_tick_start(int cpu) { } 5965 static inline void sched_tick_stop(int cpu) { } 5966 #endif /* !CONFIG_NO_HZ_FULL */ 5967 5968 #if defined(CONFIG_PREEMPTION) && (defined(CONFIG_DEBUG_PREEMPT) || \ 5969 defined(CONFIG_TRACE_PREEMPT_TOGGLE)) 5970 /* 5971 * If the value passed in is equal to the current preempt count 5972 * then we just disabled preemption. Start timing the latency. 5973 */ 5974 static inline void preempt_latency_start(int val) 5975 { 5976 if (preempt_count() == val) { 5977 unsigned long ip = get_lock_parent_ip(); 5978 #ifdef CONFIG_DEBUG_PREEMPT 5979 current->preempt_disable_ip = ip; 5980 #endif 5981 trace_preempt_off(CALLER_ADDR0, ip); 5982 } 5983 } 5984 5985 void preempt_count_add(int val) 5986 { 5987 #ifdef CONFIG_DEBUG_PREEMPT 5988 /* 5989 * Underflow? 5990 * 5991 * Cannot detect underflow based on the current preempt_count() value 5992 * if using HAS_SEPARATE_PREEMPT_RESCHED_BITS because preempt count takes all 32 5993 * bits. 5994 */ 5995 if (!IS_ENABLED(CONFIG_HAS_SEPARATE_PREEMPT_RESCHED_BITS) && 5996 DEBUG_LOCKS_WARN_ON((preempt_count() < 0))) 5997 return; 5998 #endif 5999 __preempt_count_add(val); 6000 #ifdef CONFIG_DEBUG_PREEMPT 6001 /* 6002 * Spinlock count overflowing soon? 6003 */ 6004 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >= 6005 PREEMPT_MASK - 10); 6006 #endif 6007 preempt_latency_start(val); 6008 } 6009 EXPORT_SYMBOL(preempt_count_add); 6010 NOKPROBE_SYMBOL(preempt_count_add); 6011 6012 /* 6013 * If the value passed in equals to the current preempt count 6014 * then we just enabled preemption. Stop timing the latency. 6015 */ 6016 static inline void preempt_latency_stop(int val) 6017 { 6018 if (preempt_count() == val) 6019 trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip()); 6020 } 6021 6022 void preempt_count_sub(int val) 6023 { 6024 #ifdef CONFIG_DEBUG_PREEMPT 6025 /* 6026 * Underflow? 6027 */ 6028 unsigned int uval = val; 6029 unsigned int pc = preempt_count(); 6030 6031 if (DEBUG_LOCKS_WARN_ON(pc - uval > pc)) 6032 return; 6033 /* 6034 * Is the spinlock portion underflowing? 6035 */ 6036 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) && 6037 !(preempt_count() & PREEMPT_MASK))) 6038 return; 6039 #endif 6040 6041 preempt_latency_stop(val); 6042 __preempt_count_sub(val); 6043 } 6044 EXPORT_SYMBOL(preempt_count_sub); 6045 NOKPROBE_SYMBOL(preempt_count_sub); 6046 6047 #else 6048 static inline void preempt_latency_start(int val) { } 6049 static inline void preempt_latency_stop(int val) { } 6050 #endif 6051 6052 static inline unsigned long get_preempt_disable_ip(struct task_struct *p) 6053 { 6054 #ifdef CONFIG_DEBUG_PREEMPT 6055 return p->preempt_disable_ip; 6056 #else 6057 return 0; 6058 #endif 6059 } 6060 6061 /* 6062 * Print scheduling while atomic bug: 6063 */ 6064 static noinline void __schedule_bug(struct task_struct *prev) 6065 { 6066 /* Save this before calling printk(), since that will clobber it */ 6067 unsigned long preempt_disable_ip = get_preempt_disable_ip(current); 6068 6069 if (oops_in_progress) 6070 return; 6071 6072 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n", 6073 prev->comm, prev->pid, preempt_count()); 6074 6075 debug_show_held_locks(prev); 6076 print_modules(); 6077 if (irqs_disabled()) 6078 print_irqtrace_events(prev); 6079 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)) { 6080 pr_err("Preemption disabled at:"); 6081 print_ip_sym(KERN_ERR, preempt_disable_ip); 6082 } 6083 check_panic_on_warn("scheduling while atomic"); 6084 6085 dump_stack(); 6086 add_taint(TAINT_WARN, LOCKDEP_STILL_OK); 6087 } 6088 6089 /* 6090 * Various schedule()-time debugging checks and statistics: 6091 */ 6092 static inline void schedule_debug(struct task_struct *prev, bool preempt) 6093 { 6094 #ifdef CONFIG_SCHED_STACK_END_CHECK 6095 if (task_stack_end_corrupted(prev)) 6096 panic("corrupted stack end detected inside scheduler\n"); 6097 6098 if (task_scs_end_corrupted(prev)) 6099 panic("corrupted shadow stack detected inside scheduler\n"); 6100 #endif 6101 6102 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP 6103 if (!preempt && READ_ONCE(prev->__state) && prev->non_block_count) { 6104 printk(KERN_ERR "BUG: scheduling in a non-blocking section: %s/%d/%i\n", 6105 prev->comm, prev->pid, prev->non_block_count); 6106 dump_stack(); 6107 add_taint(TAINT_WARN, LOCKDEP_STILL_OK); 6108 } 6109 #endif 6110 6111 if (unlikely(in_atomic_preempt_off())) { 6112 __schedule_bug(prev); 6113 preempt_count_set(PREEMPT_DISABLED); 6114 } 6115 rcu_sleep_check(); 6116 WARN_ON_ONCE(ct_state() == CT_STATE_USER); 6117 6118 profile_hit(SCHED_PROFILING, __builtin_return_address(0)); 6119 6120 schedstat_inc(this_rq()->sched_count); 6121 } 6122 6123 static void prev_balance(struct rq *rq, struct rq_flags *rf) 6124 { 6125 const struct sched_class *start_class = rq->donor->sched_class; 6126 const struct sched_class *class; 6127 6128 /* 6129 * We must do the balancing pass before put_prev_task(), such 6130 * that when we release the rq->lock the task is in the same 6131 * state as before we took rq->lock. 6132 * 6133 * We can terminate the balance pass as soon as we know there is 6134 * a runnable task of @class priority or higher. 6135 */ 6136 for_active_class_range(class, start_class, &idle_sched_class) { 6137 if (class->balance && class->balance(rq, rf)) 6138 break; 6139 } 6140 } 6141 6142 /* 6143 * Pick up the highest-prio task: 6144 */ 6145 static inline struct task_struct * 6146 __pick_next_task(struct rq *rq, struct rq_flags *rf) 6147 __must_hold(__rq_lockp(rq)) 6148 { 6149 const struct sched_class *class; 6150 struct task_struct *p; 6151 6152 rq->dl_server = NULL; 6153 6154 if (scx_enabled()) 6155 goto restart; 6156 6157 /* 6158 * Optimization: we know that if all tasks are in the fair class we can 6159 * call that function directly, but only if the @prev task wasn't of a 6160 * higher scheduling class, because otherwise those lose the 6161 * opportunity to pull in more work from other CPUs. 6162 */ 6163 if (likely(!sched_class_above(rq->donor->sched_class, &fair_sched_class) && 6164 rq->nr_running == rq->cfs.h_nr_queued)) { 6165 6166 p = pick_task_fair(rq, rf); 6167 if (unlikely(p == RETRY_TASK)) 6168 goto restart; 6169 6170 /* Assume the next prioritized class is idle_sched_class */ 6171 if (!p) 6172 p = pick_task_idle(rq, rf); 6173 6174 put_prev_set_next_task(rq, rq->donor, p); 6175 return p; 6176 } 6177 6178 restart: 6179 prev_balance(rq, rf); 6180 6181 for_each_active_class(class) { 6182 p = class->pick_task(rq, rf); 6183 if (unlikely(p == RETRY_TASK)) 6184 goto restart; 6185 if (p) { 6186 put_prev_set_next_task(rq, rq->donor, p); 6187 return p; 6188 } 6189 } 6190 6191 BUG(); /* The idle class should always have a runnable task. */ 6192 } 6193 6194 #ifdef CONFIG_SCHED_CORE 6195 static inline bool is_task_rq_idle(struct task_struct *t) 6196 { 6197 return (task_rq(t)->idle == t); 6198 } 6199 6200 static inline bool cookie_equals(struct task_struct *a, unsigned long cookie) 6201 { 6202 return is_task_rq_idle(a) || (a->core_cookie == cookie); 6203 } 6204 6205 static inline bool cookie_match(struct task_struct *a, struct task_struct *b) 6206 { 6207 if (is_task_rq_idle(a) || is_task_rq_idle(b)) 6208 return true; 6209 6210 return a->core_cookie == b->core_cookie; 6211 } 6212 6213 /* 6214 * Careful; this can return RETRY_TASK, it does not include the retry-loop 6215 * itself due to the whole SMT pick retry thing below. 6216 */ 6217 static inline struct task_struct *pick_task(struct rq *rq, struct rq_flags *rf) 6218 { 6219 const struct sched_class *class; 6220 struct task_struct *p; 6221 6222 rq->dl_server = NULL; 6223 6224 for_each_active_class(class) { 6225 p = class->pick_task(rq, rf); 6226 if (p) 6227 return p; 6228 } 6229 6230 BUG(); /* The idle class should always have a runnable task. */ 6231 } 6232 6233 extern void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi); 6234 6235 static void queue_core_balance(struct rq *rq); 6236 6237 static struct task_struct * 6238 pick_next_task(struct rq *rq, struct rq_flags *rf) 6239 __must_hold(__rq_lockp(rq)) 6240 { 6241 struct task_struct *next, *p, *max; 6242 const struct cpumask *smt_mask; 6243 bool fi_before = false; 6244 bool core_clock_updated = (rq == rq->core); 6245 unsigned long cookie; 6246 int i, cpu, occ = 0; 6247 struct rq *rq_i; 6248 bool need_sync = false; 6249 6250 if (!sched_core_enabled(rq)) 6251 return __pick_next_task(rq, rf); 6252 6253 cpu = cpu_of(rq); 6254 6255 /* Stopper task is switching into idle, no need core-wide selection. */ 6256 if (cpu_is_offline(cpu)) { 6257 /* 6258 * Reset core_pick so that we don't enter the fastpath when 6259 * coming online. core_pick would already be migrated to 6260 * another cpu during offline. 6261 */ 6262 rq->core_pick = NULL; 6263 rq->core_dl_server = NULL; 6264 return __pick_next_task(rq, rf); 6265 } 6266 6267 rq->core->core_pick_in_flight++; 6268 6269 /* 6270 * If there were no {en,de}queues since we picked (IOW, the task 6271 * pointers are all still valid), and we haven't scheduled the last 6272 * pick yet, do so now. 6273 * 6274 * rq->core_pick can be NULL if no selection was made for a CPU because 6275 * it was either offline or went offline during a sibling's core-wide 6276 * selection. In this case, do a core-wide selection. 6277 */ 6278 if (rq->core->core_pick_seq == rq->core->core_task_seq && 6279 rq->core->core_pick_seq != rq->core_sched_seq && 6280 rq->core_pick) { 6281 WRITE_ONCE(rq->core_sched_seq, rq->core->core_pick_seq); 6282 6283 next = rq->core_pick; 6284 rq->dl_server = rq->core_dl_server; 6285 rq->core_pick = NULL; 6286 rq->core_dl_server = NULL; 6287 goto out_set_next; 6288 } 6289 6290 prev_balance(rq, rf); 6291 6292 smt_mask = cpu_smt_mask(cpu); 6293 6294 restart: 6295 need_sync |= !!rq->core->core_cookie; 6296 6297 /* reset state */ 6298 rq->core->core_cookie = 0UL; 6299 if (rq->core->core_forceidle_count) { 6300 if (!core_clock_updated) { 6301 update_rq_clock(rq->core); 6302 core_clock_updated = true; 6303 } 6304 sched_core_account_forceidle(rq); 6305 /* reset after accounting force idle */ 6306 rq->core->core_forceidle_start = 0; 6307 rq->core->core_forceidle_count = 0; 6308 rq->core->core_forceidle_occupation = 0; 6309 need_sync = true; 6310 fi_before = true; 6311 } 6312 6313 /* 6314 * core->core_task_seq, core->core_pick_seq, rq->core_sched_seq 6315 * 6316 * @task_seq guards the task state ({en,de}queues) 6317 * @pick_seq is the @task_seq we did a selection on 6318 * @sched_seq is the @pick_seq we scheduled 6319 * 6320 * However, preemptions can cause multiple picks on the same task set. 6321 * 'Fix' this by also increasing @task_seq for every pick. 6322 */ 6323 rq->core->core_task_seq++; 6324 6325 /* 6326 * Optimize for common case where this CPU has no cookies 6327 * and there are no cookied tasks running on siblings. 6328 */ 6329 if (!need_sync) { 6330 next = pick_task(rq, rf); 6331 if (unlikely(next == RETRY_TASK)) { 6332 /* rq lock may have been dropped, clocks invalidated */ 6333 core_clock_updated = false; 6334 if (!(rq->clock_update_flags & RQCF_UPDATED)) 6335 update_rq_clock(rq); 6336 goto restart; 6337 } 6338 6339 if (!next->core_cookie) { 6340 rq->core_pick = NULL; 6341 rq->core_dl_server = NULL; 6342 /* 6343 * For robustness, update the min_vruntime_fi for 6344 * unconstrained picks as well. 6345 */ 6346 WARN_ON_ONCE(fi_before); 6347 task_vruntime_update(rq, next, false); 6348 goto out_set_next; 6349 } 6350 } 6351 6352 /* 6353 * For each thread: do the regular task pick and find the max prio task 6354 * amongst them. 6355 * 6356 * Tie-break prio towards the current CPU 6357 */ 6358 max = NULL; 6359 for_each_cpu_wrap(i, smt_mask, cpu) { 6360 rq_i = cpu_rq(i); 6361 6362 /* 6363 * Current cpu always has its clock updated on entrance to 6364 * pick_next_task(). If the current cpu is not the core, 6365 * the core may also have been updated above. 6366 */ 6367 if (i != cpu && (rq_i != rq->core || !core_clock_updated)) 6368 update_rq_clock(rq_i); 6369 6370 p = pick_task(rq_i, rf); 6371 if (unlikely(p == RETRY_TASK)) { 6372 /* rq lock may have been dropped, clocks invalidated */ 6373 core_clock_updated = false; 6374 if (!(rq->clock_update_flags & RQCF_UPDATED)) 6375 update_rq_clock(rq); 6376 goto restart; 6377 } 6378 6379 rq_i->core_pick = p; 6380 rq_i->core_dl_server = rq_i->dl_server; 6381 6382 if (!max || prio_less(max, p, fi_before)) 6383 max = p; 6384 } 6385 6386 cookie = rq->core->core_cookie = max->core_cookie; 6387 6388 /* 6389 * For each thread: try and find a runnable task that matches @max or 6390 * force idle. 6391 */ 6392 for_each_cpu(i, smt_mask) { 6393 rq_i = cpu_rq(i); 6394 p = rq_i->core_pick; 6395 6396 if (!cookie_equals(p, cookie)) { 6397 p = NULL; 6398 if (cookie) 6399 p = sched_core_find(rq_i, cookie); 6400 if (!p) 6401 p = idle_sched_class.pick_task(rq_i, rf); 6402 } 6403 6404 rq_i->core_pick = p; 6405 rq_i->core_dl_server = NULL; 6406 6407 if (p == rq_i->idle) { 6408 if (rq_i->nr_running) { 6409 rq->core->core_forceidle_count++; 6410 if (!fi_before) 6411 rq->core->core_forceidle_seq++; 6412 } 6413 } else { 6414 occ++; 6415 } 6416 } 6417 6418 if (schedstat_enabled() && rq->core->core_forceidle_count) { 6419 rq->core->core_forceidle_start = rq_clock(rq->core); 6420 rq->core->core_forceidle_occupation = occ; 6421 } 6422 6423 rq->core->core_pick_seq = rq->core->core_task_seq; 6424 next = rq->core_pick; 6425 rq->core_sched_seq = rq->core->core_pick_seq; 6426 6427 /* Something should have been selected for current CPU */ 6428 WARN_ON_ONCE(!next); 6429 6430 /* 6431 * Reschedule siblings 6432 * 6433 * NOTE: L1TF -- at this point we're no longer running the old task and 6434 * sending an IPI (below) ensures the sibling will no longer be running 6435 * their task. This ensures there is no inter-sibling overlap between 6436 * non-matching user state. 6437 */ 6438 for_each_cpu(i, smt_mask) { 6439 rq_i = cpu_rq(i); 6440 6441 /* 6442 * An online sibling might have gone offline before a task 6443 * could be picked for it, or it might be offline but later 6444 * happen to come online, but its too late and nothing was 6445 * picked for it. That's Ok - it will pick tasks for itself, 6446 * so ignore it. 6447 */ 6448 if (!rq_i->core_pick) 6449 continue; 6450 6451 /* 6452 * Update for new !FI->FI transitions, or if continuing to be in !FI: 6453 * fi_before fi update? 6454 * 0 0 1 6455 * 0 1 1 6456 * 1 0 1 6457 * 1 1 0 6458 */ 6459 if (!(fi_before && rq->core->core_forceidle_count)) 6460 task_vruntime_update(rq_i, rq_i->core_pick, !!rq->core->core_forceidle_count); 6461 6462 rq_i->core_pick->core_occupation = occ; 6463 6464 if (i == cpu) { 6465 rq_i->core_pick = NULL; 6466 rq_i->core_dl_server = NULL; 6467 continue; 6468 } 6469 6470 /* Did we break L1TF mitigation requirements? */ 6471 WARN_ON_ONCE(!cookie_match(next, rq_i->core_pick)); 6472 6473 if (rq_i->curr == rq_i->core_pick) { 6474 rq_i->core_pick = NULL; 6475 rq_i->core_dl_server = NULL; 6476 continue; 6477 } 6478 6479 resched_curr(rq_i); 6480 } 6481 6482 out_set_next: 6483 rq->core->core_pick_in_flight--; 6484 put_prev_set_next_task(rq, rq->donor, next); 6485 if (rq->core->core_forceidle_count && next == rq->idle) 6486 queue_core_balance(rq); 6487 6488 return next; 6489 } 6490 6491 static bool try_steal_cookie(int this, int that) 6492 { 6493 struct rq *dst = cpu_rq(this), *src = cpu_rq(that); 6494 struct task_struct *p; 6495 unsigned long cookie; 6496 bool success = false; 6497 6498 guard(irq)(); 6499 guard(double_rq_lock)(dst, src); 6500 6501 cookie = dst->core->core_cookie; 6502 if (!cookie) 6503 return false; 6504 6505 if (dst->curr != dst->idle) 6506 return false; 6507 6508 p = sched_core_find(src, cookie); 6509 if (!p) 6510 return false; 6511 6512 do { 6513 if (p == src->core_pick || p == src->curr) 6514 goto next; 6515 6516 if (!is_cpu_allowed(p, this)) 6517 goto next; 6518 6519 if (p->core_occupation > dst->idle->core_occupation) 6520 goto next; 6521 /* 6522 * sched_core_find() and sched_core_next() will ensure 6523 * that task @p is not throttled now, we also need to 6524 * check whether the runqueue of the destination CPU is 6525 * being throttled. 6526 */ 6527 if (sched_task_is_throttled(p, this)) 6528 goto next; 6529 6530 move_queued_task_locked(src, dst, p); 6531 resched_curr(dst); 6532 6533 success = true; 6534 break; 6535 6536 next: 6537 p = sched_core_next(p, cookie); 6538 } while (p); 6539 6540 return success; 6541 } 6542 6543 static bool steal_cookie_task(int cpu, struct sched_domain *sd) 6544 { 6545 int i; 6546 6547 for_each_cpu_wrap(i, sched_domain_span(sd), cpu + 1) { 6548 if (i == cpu) 6549 continue; 6550 6551 if (need_resched()) 6552 break; 6553 6554 if (try_steal_cookie(cpu, i)) 6555 return true; 6556 } 6557 6558 return false; 6559 } 6560 6561 static void sched_core_balance(struct rq *rq) 6562 __must_hold(__rq_lockp(rq)) 6563 { 6564 struct sched_domain *sd; 6565 int cpu = cpu_of(rq); 6566 6567 guard(preempt)(); 6568 guard(rcu)(); 6569 6570 raw_spin_rq_unlock_irq(rq); 6571 for_each_domain(cpu, sd) { 6572 if (need_resched()) 6573 break; 6574 6575 if (steal_cookie_task(cpu, sd)) 6576 break; 6577 } 6578 raw_spin_rq_lock_irq(rq); 6579 } 6580 6581 static DEFINE_PER_CPU(struct balance_callback, core_balance_head); 6582 6583 static void queue_core_balance(struct rq *rq) 6584 { 6585 if (!sched_core_enabled(rq)) 6586 return; 6587 6588 if (!rq->core->core_cookie) 6589 return; 6590 6591 if (!rq->nr_running) /* not forced idle */ 6592 return; 6593 6594 queue_balance_callback(rq, &per_cpu(core_balance_head, rq->cpu), sched_core_balance); 6595 } 6596 6597 DEFINE_LOCK_GUARD_1(core_lock, int, 6598 sched_core_lock(*_T->lock, &_T->flags), 6599 sched_core_unlock(*_T->lock, &_T->flags), 6600 unsigned long flags) 6601 6602 static void sched_core_cpu_starting(unsigned int cpu) 6603 { 6604 const struct cpumask *smt_mask = cpu_smt_mask(cpu); 6605 struct rq *rq = cpu_rq(cpu), *core_rq = NULL; 6606 int t; 6607 6608 guard(core_lock)(&cpu); 6609 6610 WARN_ON_ONCE(rq->core != rq); 6611 6612 /* if we're the first, we'll be our own leader */ 6613 if (cpumask_weight(smt_mask) == 1) 6614 return; 6615 6616 /* find the leader */ 6617 for_each_cpu(t, smt_mask) { 6618 if (t == cpu) 6619 continue; 6620 rq = cpu_rq(t); 6621 if (rq->core == rq) { 6622 core_rq = rq; 6623 break; 6624 } 6625 } 6626 6627 if (WARN_ON_ONCE(!core_rq)) /* whoopsie */ 6628 return; 6629 6630 /* install and validate core_rq */ 6631 for_each_cpu(t, smt_mask) { 6632 rq = cpu_rq(t); 6633 6634 if (t == cpu) 6635 rq->core = core_rq; 6636 6637 WARN_ON_ONCE(rq->core != core_rq); 6638 } 6639 } 6640 6641 static void sched_core_cpu_deactivate(unsigned int cpu) 6642 { 6643 const struct cpumask *smt_mask = cpu_smt_mask(cpu); 6644 struct rq *rq = cpu_rq(cpu), *core_rq = NULL; 6645 int t; 6646 6647 guard(core_lock)(&cpu); 6648 6649 /* if we're the last man standing, nothing to do */ 6650 if (cpumask_weight(smt_mask) == 1) { 6651 WARN_ON_ONCE(rq->core != rq); 6652 return; 6653 } 6654 6655 /* if we're not the leader, nothing to do */ 6656 if (rq->core != rq) 6657 return; 6658 6659 /* find a new leader */ 6660 for_each_cpu(t, smt_mask) { 6661 if (t == cpu) 6662 continue; 6663 core_rq = cpu_rq(t); 6664 break; 6665 } 6666 6667 if (WARN_ON_ONCE(!core_rq)) /* impossible */ 6668 return; 6669 6670 /* copy the shared state to the new leader */ 6671 core_rq->core_task_seq = rq->core_task_seq; 6672 core_rq->core_pick_seq = rq->core_pick_seq; 6673 core_rq->core_cookie = rq->core_cookie; 6674 core_rq->core_forceidle_count = rq->core_forceidle_count; 6675 core_rq->core_forceidle_seq = rq->core_forceidle_seq; 6676 core_rq->core_forceidle_occupation = rq->core_forceidle_occupation; 6677 6678 /* 6679 * A stale leftover would bias the count forever if this CPU later 6680 * returns as its own leader. Move, don't copy. 6681 */ 6682 core_rq->core_pick_in_flight = rq->core_pick_in_flight; 6683 rq->core_pick_in_flight = 0; 6684 6685 /* 6686 * Accounting edge for forced idle is handled in pick_next_task(). 6687 * Don't need another one here, since the hotplug thread shouldn't 6688 * have a cookie. 6689 */ 6690 core_rq->core_forceidle_start = 0; 6691 6692 /* install new leader */ 6693 for_each_cpu(t, smt_mask) { 6694 rq = cpu_rq(t); 6695 rq->core = core_rq; 6696 } 6697 } 6698 6699 static inline void sched_core_cpu_dying(unsigned int cpu) 6700 { 6701 struct rq *rq = cpu_rq(cpu); 6702 6703 if (rq->core != rq) 6704 rq->core = rq; 6705 } 6706 6707 #else /* !CONFIG_SCHED_CORE: */ 6708 6709 static inline void sched_core_cpu_starting(unsigned int cpu) {} 6710 static inline void sched_core_cpu_deactivate(unsigned int cpu) {} 6711 static inline void sched_core_cpu_dying(unsigned int cpu) {} 6712 6713 static struct task_struct * 6714 pick_next_task(struct rq *rq, struct rq_flags *rf) 6715 __must_hold(__rq_lockp(rq)) 6716 { 6717 return __pick_next_task(rq, rf); 6718 } 6719 6720 #endif /* !CONFIG_SCHED_CORE */ 6721 6722 /* 6723 * Constants for the sched_mode argument of __schedule(). 6724 * 6725 * The mode argument allows RT enabled kernels to differentiate a 6726 * preemption from blocking on an 'sleeping' spin/rwlock. 6727 */ 6728 #define SM_IDLE (-1) 6729 #define SM_NONE 0 6730 #define SM_PREEMPT 1 6731 #define SM_RTLOCK_WAIT 2 6732 6733 /* 6734 * Helper function for __schedule() 6735 * 6736 * Tries to deactivate the task, unless the should_block arg 6737 * is false or if a signal is pending. In the case a signal 6738 * is pending, marks the task's __state as RUNNING (and clear 6739 * blocked_on). 6740 */ 6741 static bool try_to_block_task(struct rq *rq, struct task_struct *p, 6742 unsigned long *task_state_p, bool should_block) 6743 { 6744 unsigned long task_state = *task_state_p; 6745 6746 WARN_ON_ONCE(p->is_blocked); 6747 6748 if (signal_pending_state(task_state, p)) { 6749 WRITE_ONCE(p->__state, TASK_RUNNING); 6750 *task_state_p = TASK_RUNNING; 6751 clear_task_blocked_on(p, NULL); 6752 6753 return false; 6754 } 6755 6756 p->is_blocked = 1; 6757 6758 /* 6759 * We check should_block after signal_pending because we 6760 * will want to wake the task in that case. But if 6761 * should_block is false, its likely due to the task being 6762 * blocked on a mutex, and we want to keep it on the runqueue 6763 * to be selectable for proxy-execution. 6764 */ 6765 if (!should_block) 6766 return false; 6767 6768 block_task(rq, p, task_state); 6769 return true; 6770 } 6771 6772 #ifdef CONFIG_SCHED_PROXY_EXEC 6773 static inline void proxy_set_task_cpu(struct task_struct *p, int cpu) 6774 { 6775 unsigned int wake_cpu; 6776 6777 /* 6778 * Since we are enqueuing a blocked task on a cpu it may 6779 * not be able to run on, preserve wake_cpu when we 6780 * __set_task_cpu so we can return the task to where it 6781 * was previously runnable. 6782 */ 6783 wake_cpu = p->wake_cpu; 6784 __set_task_cpu(p, cpu); 6785 p->wake_cpu = wake_cpu; 6786 } 6787 6788 static inline struct task_struct *proxy_resched_idle(struct rq *rq) 6789 { 6790 put_prev_set_next_task(rq, rq->donor, rq->idle); 6791 rq->next_class = &idle_sched_class; 6792 rq_set_donor(rq, rq->idle); 6793 set_tsk_need_resched(rq->idle); 6794 return rq->idle; 6795 } 6796 6797 static void proxy_deactivate(struct rq *rq, struct task_struct *donor) 6798 { 6799 unsigned long state = READ_ONCE(donor->__state); 6800 6801 WARN_ON_ONCE(state == TASK_RUNNING); 6802 WARN_ON_ONCE(donor->blocked_on); 6803 /* 6804 * Because we got donor from pick_next_task(), it is *crucial* 6805 * that we call proxy_resched_idle() before we deactivate it. 6806 * As once we deactivate donor, donor->on_rq is set to zero, 6807 * which allows ttwu() to immediately try to wake the task on 6808 * another rq. So we cannot use *any* references to donor 6809 * after that point. So things like cfs_rq->curr or rq->donor 6810 * need to be changed from next *before* we deactivate. 6811 */ 6812 proxy_resched_idle(rq); 6813 block_task(rq, donor, state); 6814 } 6815 6816 static inline void proxy_release_rq_lock(struct rq *rq, struct rq_flags *rf) 6817 __releases(__rq_lockp(rq)) 6818 { 6819 /* 6820 * The class scheduler may have queued a balance callback 6821 * from pick_next_task() called earlier. 6822 * 6823 * So here we have to zap callbacks before unlocking the rq 6824 * as another CPU may jump in and call sched_balance_rq 6825 * which can trip the warning in rq_pin_lock() if we 6826 * leave callbacks set. 6827 * 6828 * After we later reaquire the rq lock, we will force __schedule() 6829 * to pick_again, so the callbacks will get re-established. 6830 */ 6831 zap_balance_callbacks(rq); 6832 rq_unpin_lock(rq, rf); 6833 raw_spin_rq_unlock(rq); 6834 } 6835 6836 static inline void proxy_reacquire_rq_lock(struct rq *rq, struct rq_flags *rf) 6837 __acquires(__rq_lockp(rq)) 6838 { 6839 raw_spin_rq_lock(rq); 6840 rq_repin_lock(rq, rf); 6841 update_rq_clock(rq); 6842 } 6843 6844 /* 6845 * If the blocked-on relationship crosses CPUs, migrate @p to the 6846 * owner's CPU. 6847 * 6848 * This is because we must respect the CPU affinity of execution 6849 * contexts (owner) but we can ignore affinity for scheduling 6850 * contexts (@p). So we have to move scheduling contexts towards 6851 * potential execution contexts. 6852 * 6853 * Note: The owner can disappear, but simply migrate to @target_cpu 6854 * and leave that CPU to sort things out. 6855 */ 6856 static void proxy_migrate_task(struct rq *rq, struct rq_flags *rf, 6857 struct task_struct *p, int target_cpu) 6858 __must_hold(__rq_lockp(rq)) 6859 { 6860 struct rq *target_rq = cpu_rq(target_cpu); 6861 6862 lockdep_assert_rq_held(rq); 6863 WARN_ON(p == rq->curr); 6864 /* 6865 * Since we are migrating a blocked donor, it could be rq->donor, 6866 * and we want to make sure there aren't any references from this 6867 * rq to it before we drop the lock. This avoids another cpu 6868 * jumping in and grabbing the rq lock and referencing rq->donor 6869 * or cfs_rq->curr, etc after we have migrated it to another cpu, 6870 * and before we pick_again in __schedule. 6871 * 6872 * So call proxy_resched_idle() to drop the rq->donor references 6873 * before we release the lock. 6874 */ 6875 proxy_resched_idle(rq); 6876 6877 deactivate_task(rq, p, DEQUEUE_NOCLOCK); 6878 proxy_set_task_cpu(p, target_cpu); 6879 6880 proxy_release_rq_lock(rq, rf); 6881 6882 attach_one_task(target_rq, p); 6883 6884 proxy_reacquire_rq_lock(rq, rf); 6885 } 6886 6887 /* 6888 * Find runnable lock owner to proxy for mutex blocked donor 6889 * 6890 * Follow the blocked-on relation: 6891 * 6892 * ,-> task 6893 * | | blocked-on 6894 * | v 6895 * blocked_donor | mutex 6896 * | | owner 6897 * | v 6898 * `-- task 6899 * 6900 * and set the blocked_donor relation, this latter is used by the mutex 6901 * code to find which (blocked) task to hand-off to. 6902 * 6903 * Lock order: 6904 * 6905 * p->pi_lock 6906 * rq->lock 6907 * mutex->wait_lock 6908 * p->blocked_lock 6909 * 6910 * Returns the task that is going to be used as execution context (the one 6911 * that is actually going to be run on cpu_of(rq)). 6912 */ 6913 static struct task_struct * 6914 find_proxy_task(struct rq *rq, struct task_struct *donor, struct rq_flags *rf) 6915 __must_hold(__rq_lockp(rq)) 6916 { 6917 struct task_struct *owner = NULL; 6918 bool curr_in_chain = false; 6919 int this_cpu = cpu_of(rq); 6920 struct task_struct *p; 6921 int owner_cpu; 6922 6923 /* Follow blocked_on chain. */ 6924 for (p = donor; p->is_blocked; p = owner) { 6925 /* if its PROXY_WAKING, do return migration or run if current */ 6926 struct mutex *mutex = p->blocked_on; 6927 if (!mutex) { 6928 clear_task_blocked_on(p, mutex); 6929 if (task_current(rq, p)) { 6930 p->is_blocked = 0; 6931 return p; 6932 } 6933 goto deactivate; 6934 } 6935 6936 /* 6937 * By taking mutex->wait_lock we hold off concurrent mutex_unlock() 6938 * and ensure @owner sticks around. 6939 */ 6940 guard(raw_spinlock)(&mutex->wait_lock); 6941 guard(raw_spinlock)(&p->blocked_lock); 6942 6943 /* Check again that p is blocked with blocked_lock held */ 6944 if (mutex != __get_task_blocked_on(p)) { 6945 /* 6946 * Something changed in the blocked_on chain and 6947 * we don't know if only at this level. So, let's 6948 * just bail out completely and let __schedule() 6949 * figure things out (pick_again loop). 6950 */ 6951 return NULL; 6952 } 6953 6954 if (task_current(rq, p)) 6955 curr_in_chain = true; 6956 6957 owner = __mutex_owner(mutex); 6958 if (!owner) { 6959 /* 6960 * If there is no owner, either clear blocked_on 6961 * and return p (if it is current and safe to 6962 * just run on this rq), or return-migrate the task. 6963 */ 6964 __clear_task_blocked_on(p, NULL); 6965 if (task_current(rq, p)) { 6966 p->is_blocked = 0; 6967 return p; 6968 } 6969 goto deactivate; 6970 } 6971 6972 if (!READ_ONCE(owner->on_rq) || owner->se.sched_delayed) { 6973 /* XXX Don't handle blocked owners/delayed dequeue yet */ 6974 if (curr_in_chain) 6975 return proxy_resched_idle(rq); 6976 __clear_task_blocked_on(p, NULL); 6977 goto deactivate; 6978 } 6979 6980 owner_cpu = task_cpu(owner); 6981 if (owner_cpu != this_cpu) { 6982 /* 6983 * @owner can disappear, simply migrate to @owner_cpu 6984 * and leave that CPU to sort things out. 6985 */ 6986 if (curr_in_chain) 6987 return proxy_resched_idle(rq); 6988 goto migrate_task; 6989 } 6990 6991 if (task_on_rq_migrating(owner)) { 6992 /* 6993 * One of the chain of mutex owners is currently migrating to this 6994 * CPU, but has not yet been enqueued because we are holding the 6995 * rq lock. As a simple solution, just schedule rq->idle to give 6996 * the migration a chance to complete. Much like the migrate_task 6997 * case we should end up back in find_proxy_task(), this time 6998 * hopefully with all relevant tasks already enqueued. 6999 */ 7000 return proxy_resched_idle(rq); 7001 } 7002 7003 /* 7004 * Its possible to race where after we check owner->on_rq 7005 * but before we check (owner_cpu != this_cpu) that the 7006 * task on another cpu was migrated back to this cpu. In 7007 * that case it could slip by our checks. So double check 7008 * we are still on this cpu and not migrating. If we get 7009 * inconsistent results, try again. 7010 */ 7011 if (!task_on_rq_queued(owner) || task_cpu(owner) != this_cpu) 7012 return NULL; 7013 7014 if (owner == p) { 7015 /* 7016 * It's possible we interleave with mutex_unlock like: 7017 * 7018 * lock(&rq->lock); 7019 * find_proxy_task() 7020 * mutex_unlock() 7021 * lock(&wait_lock); 7022 * donor(owner) = current->blocked_donor; 7023 * unlock(&wait_lock); 7024 * 7025 * wake_up_q(); 7026 * ... 7027 * ttwu_runnable() 7028 * __task_rq_lock() 7029 * lock(&wait_lock); 7030 * owner == p 7031 * 7032 * Which leaves us to finish the ttwu_runnable() and make it go. 7033 * 7034 * So schedule rq->idle so that ttwu_runnable() can get the rq 7035 * lock and mark owner as running. 7036 */ 7037 return proxy_resched_idle(rq); 7038 } 7039 /* 7040 * OK, now we're absolutely sure @owner is on this 7041 * rq, therefore holding @rq->lock is sufficient to 7042 * guarantee its existence, as per ttwu_remote(). 7043 */ 7044 owner->blocked_donor = p; 7045 } 7046 WARN_ON_ONCE(owner && !owner->on_rq); 7047 return owner; 7048 7049 deactivate: 7050 proxy_deactivate(rq, p); 7051 return NULL; 7052 migrate_task: 7053 proxy_migrate_task(rq, rf, p, owner_cpu); 7054 return NULL; 7055 } 7056 #else /* SCHED_PROXY_EXEC */ 7057 static struct task_struct * 7058 find_proxy_task(struct rq *rq, struct task_struct *donor, struct rq_flags *rf) 7059 { 7060 WARN_ONCE(1, "This should never be called in the !SCHED_PROXY_EXEC case\n"); 7061 return donor; 7062 } 7063 #endif /* SCHED_PROXY_EXEC */ 7064 7065 /* 7066 * __schedule() is the main scheduler function. 7067 * 7068 * The main means of driving the scheduler and thus entering this function are: 7069 * 7070 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc. 7071 * 7072 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return 7073 * paths. For example, see arch/x86/entry_64.S. 7074 * 7075 * To drive preemption between tasks, the scheduler sets the flag in timer 7076 * interrupt handler sched_tick(). 7077 * 7078 * 3. Wakeups don't really cause entry into schedule(). They add a 7079 * task to the run-queue and that's it. 7080 * 7081 * Now, if the new task added to the run-queue preempts the current 7082 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets 7083 * called on the nearest possible occasion: 7084 * 7085 * - If the kernel is preemptible (CONFIG_PREEMPTION=y): 7086 * 7087 * - in syscall or exception context, at the next outmost 7088 * preempt_enable(). (this might be as soon as the wake_up()'s 7089 * spin_unlock()!) 7090 * 7091 * - in IRQ context, return from interrupt-handler to 7092 * preemptible context 7093 * 7094 * - If the kernel is not preemptible (CONFIG_PREEMPTION is not set) 7095 * then at the next: 7096 * 7097 * - cond_resched() call 7098 * - explicit schedule() call 7099 * - return from syscall or exception to user-space 7100 * - return from interrupt-handler to user-space 7101 * 7102 * WARNING: must be called with preemption disabled! 7103 */ 7104 static void __sched notrace __schedule(int sched_mode) 7105 { 7106 struct task_struct *prev, *next; 7107 /* 7108 * On PREEMPT_RT kernel, SM_RTLOCK_WAIT is noted 7109 * as a preemption by schedule_debug() and RCU. 7110 */ 7111 bool preempt = sched_mode > SM_NONE; 7112 bool is_switch = false; 7113 unsigned long *switch_count; 7114 unsigned long prev_state; 7115 struct rq_flags rf; 7116 struct rq *rq; 7117 int cpu; 7118 7119 /* Trace preemptions consistently with task switches */ 7120 trace_sched_entry_tp(sched_mode == SM_PREEMPT); 7121 7122 cpu = smp_processor_id(); 7123 rq = cpu_rq(cpu); 7124 prev = rq->curr; 7125 7126 schedule_debug(prev, preempt); 7127 7128 klp_sched_try_switch(prev); 7129 7130 local_irq_disable(); 7131 rcu_note_context_switch(preempt); 7132 migrate_disable_switch(rq, prev); 7133 7134 /* 7135 * Make sure that signal_pending_state()->signal_pending() below 7136 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE) 7137 * done by the caller to avoid the race with signal_wake_up(): 7138 * 7139 * __set_current_state(@state) signal_wake_up() 7140 * schedule() set_tsk_thread_flag(p, TIF_SIGPENDING) 7141 * wake_up_state(p, state) 7142 * LOCK rq->lock LOCK p->pi_state 7143 * smp_mb__after_spinlock() smp_mb__after_spinlock() 7144 * if (signal_pending_state()) if (p->state & @state) 7145 * 7146 * Also, the membarrier system call requires a full memory barrier 7147 * after coming from user-space, before storing to rq->curr; this 7148 * barrier matches a full barrier in the proximity of the membarrier 7149 * system call exit. 7150 */ 7151 rq_lock(rq, &rf); 7152 smp_mb__after_spinlock(); 7153 7154 hrtick_schedule_enter(rq); 7155 7156 /* Promote REQ to ACT */ 7157 rq->clock_update_flags <<= 1; 7158 update_rq_clock(rq); 7159 rq->clock_update_flags = RQCF_UPDATED; 7160 7161 switch_count = &prev->nivcsw; 7162 7163 /* Task state changes only considers SM_PREEMPT as preemption */ 7164 preempt = sched_mode == SM_PREEMPT; 7165 7166 /* 7167 * We must load prev->state once (task_struct::state is volatile), such 7168 * that we form a control dependency vs deactivate_task() below. 7169 */ 7170 prev_state = READ_ONCE(prev->__state); 7171 if (sched_mode == SM_IDLE) { 7172 /* SCX must consult the BPF scheduler to tell if rq is empty */ 7173 if (!rq->nr_running && !scx_enabled()) { 7174 next = prev; 7175 rq->next_class = &idle_sched_class; 7176 goto picked; 7177 } 7178 } else if (!preempt && prev_state) { 7179 /* 7180 * We pass task_is_blocked() as the should_block arg 7181 * in order to keep mutex-blocked tasks on the runqueue 7182 * for slection with proxy-exec (without proxy-exec 7183 * task_is_blocked() will always be false). 7184 */ 7185 try_to_block_task(rq, prev, &prev_state, 7186 !task_is_blocked(prev)); 7187 switch_count = &prev->nvcsw; 7188 } 7189 7190 pick_again: 7191 assert_balance_callbacks_empty(rq); 7192 next = pick_next_task(rq, &rf); 7193 rq->next_class = next->sched_class; 7194 if (sched_proxy_exec()) { 7195 struct task_struct *prev_donor = rq->donor; 7196 7197 rq_set_donor(rq, next); 7198 next->blocked_donor = NULL; 7199 if (unlikely(next->is_blocked)) { 7200 next = find_proxy_task(rq, next, &rf); 7201 if (!next) { 7202 zap_balance_callbacks(rq); 7203 goto pick_again; 7204 } 7205 if (next == rq->idle) { 7206 zap_balance_callbacks(rq); 7207 goto keep_resched; 7208 } 7209 } 7210 if (rq->donor == prev_donor && prev != next) { 7211 struct task_struct *donor = rq->donor; 7212 /* 7213 * When transitioning like: 7214 * 7215 * prev next 7216 * donor: B B 7217 * curr: A B or C 7218 * 7219 * then put_prev_set_next_task() will not have done 7220 * anything, since B == B. However, A might have 7221 * missed a RT/DL balance opportunity due to being 7222 * on_cpu. 7223 */ 7224 donor->sched_class->put_prev_task(rq, donor, donor); 7225 donor->sched_class->set_next_task(rq, donor, true); 7226 } 7227 } else { 7228 rq_set_donor(rq, next); 7229 } 7230 7231 picked: 7232 clear_tsk_need_resched(prev); 7233 clear_preempt_need_resched(); 7234 keep_resched: 7235 rq->last_seen_need_resched_ns = 0; 7236 7237 is_switch = prev != next; 7238 if (likely(is_switch)) { 7239 rq->nr_switches++; 7240 /* 7241 * RCU users of rcu_dereference(rq->curr) may not see 7242 * changes to task_struct made by pick_next_task(). 7243 */ 7244 RCU_INIT_POINTER(rq->curr, next); 7245 7246 /* 7247 * The membarrier system call requires each architecture 7248 * to have a full memory barrier after updating 7249 * rq->curr, before returning to user-space. 7250 * 7251 * Here are the schemes providing that barrier on the 7252 * various architectures: 7253 * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC, 7254 * RISC-V. switch_mm() relies on membarrier_arch_switch_mm() 7255 * on PowerPC and on RISC-V. 7256 * - finish_lock_switch() for weakly-ordered 7257 * architectures where spin_unlock is a full barrier, 7258 * - switch_to() for arm64 (weakly-ordered, spin_unlock 7259 * is a RELEASE barrier), 7260 * 7261 * The barrier matches a full barrier in the proximity of 7262 * the membarrier system call entry. 7263 * 7264 * On RISC-V, this barrier pairing is also needed for the 7265 * SYNC_CORE command when switching between processes, cf. 7266 * the inline comments in membarrier_arch_switch_mm(). 7267 */ 7268 ++*switch_count; 7269 7270 psi_account_irqtime(rq, prev, next); 7271 psi_sched_switch(prev, next, !task_on_rq_queued(prev) || 7272 prev->se.sched_delayed); 7273 7274 trace_sched_switch(preempt, prev, next, prev_state); 7275 7276 /* Also unlocks the rq: */ 7277 rq = context_switch(rq, prev, next, &rf); 7278 } else { 7279 rq_unpin_lock(rq, &rf); 7280 __balance_callbacks(rq, NULL); 7281 hrtick_schedule_exit(rq); 7282 raw_spin_rq_unlock_irq(rq); 7283 } 7284 trace_sched_exit_tp(is_switch); 7285 } 7286 7287 void __noreturn do_task_dead(void) 7288 { 7289 /* Causes final put_task_struct in finish_task_switch(): */ 7290 set_special_state(TASK_DEAD); 7291 7292 /* Tell freezer to ignore us: */ 7293 current->flags |= PF_NOFREEZE; 7294 7295 __schedule(SM_NONE); 7296 BUG(); 7297 7298 /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */ 7299 for (;;) 7300 cpu_relax(); 7301 } 7302 7303 static inline void sched_submit_work(struct task_struct *tsk) 7304 { 7305 static DEFINE_WAIT_OVERRIDE_MAP(sched_map, LD_WAIT_CONFIG); 7306 unsigned int task_flags; 7307 7308 /* 7309 * Establish LD_WAIT_CONFIG context to ensure none of the code called 7310 * will use a blocking primitive -- which would lead to recursion. 7311 */ 7312 lock_map_acquire_try(&sched_map); 7313 7314 task_flags = tsk->flags; 7315 /* 7316 * If a worker goes to sleep, notify and ask workqueue whether it 7317 * wants to wake up a task to maintain concurrency. 7318 */ 7319 if (task_flags & PF_WQ_WORKER) 7320 wq_worker_sleeping(tsk); 7321 else if (task_flags & PF_IO_WORKER) 7322 io_wq_worker_sleeping(tsk); 7323 7324 /* 7325 * spinlock and rwlock must not flush block requests. This will 7326 * deadlock if the callback attempts to acquire a lock which is 7327 * already acquired. 7328 */ 7329 WARN_ON_ONCE(current->__state & TASK_RTLOCK_WAIT); 7330 7331 /* 7332 * If we are going to sleep and we have plugged IO queued, 7333 * make sure to submit it to avoid deadlocks. 7334 */ 7335 blk_flush_plug(tsk->plug, true); 7336 7337 lock_map_release(&sched_map); 7338 } 7339 7340 static void sched_update_worker(struct task_struct *tsk) 7341 { 7342 if (tsk->flags & (PF_WQ_WORKER | PF_IO_WORKER)) { 7343 if (tsk->flags & PF_WQ_WORKER) 7344 wq_worker_running(tsk); 7345 else 7346 io_wq_worker_running(tsk); 7347 } 7348 } 7349 7350 static __always_inline void __schedule_loop(int sched_mode) 7351 { 7352 do { 7353 preempt_disable(); 7354 __schedule(sched_mode); 7355 sched_preempt_enable_no_resched(); 7356 } while (need_resched()); 7357 } 7358 7359 asmlinkage __visible void __sched schedule(void) 7360 { 7361 struct task_struct *tsk = current; 7362 7363 #ifdef CONFIG_RT_MUTEXES 7364 lockdep_assert(!tsk->sched_rt_mutex); 7365 #endif 7366 7367 if (!task_is_running(tsk)) 7368 sched_submit_work(tsk); 7369 __schedule_loop(SM_NONE); 7370 sched_update_worker(tsk); 7371 } 7372 EXPORT_SYMBOL(schedule); 7373 7374 /* 7375 * synchronize_rcu_tasks() makes sure that no task is stuck in preempted 7376 * state (have scheduled out non-voluntarily) by making sure that all 7377 * tasks have either left the run queue or have gone into user space. 7378 * As idle tasks do not do either, they must not ever be preempted 7379 * (schedule out non-voluntarily). 7380 * 7381 * schedule_idle() is similar to schedule_preempt_disable() except that it 7382 * never enables preemption because it does not call sched_submit_work(). 7383 */ 7384 void __sched schedule_idle(void) 7385 { 7386 /* 7387 * As this skips calling sched_submit_work(), which the idle task does 7388 * regardless because that function is a NOP when the task is in a 7389 * TASK_RUNNING state, make sure this isn't used someplace that the 7390 * current task can be in any other state. Note, idle is always in the 7391 * TASK_RUNNING state. 7392 */ 7393 WARN_ON_ONCE(current->__state); 7394 do { 7395 __schedule(SM_IDLE); 7396 } while (need_resched()); 7397 } 7398 7399 #if defined(CONFIG_CONTEXT_TRACKING_USER) && !defined(CONFIG_HAVE_CONTEXT_TRACKING_USER_OFFSTACK) 7400 asmlinkage __visible void __sched schedule_user(void) 7401 { 7402 /* 7403 * If we come here after a random call to set_need_resched(), 7404 * or we have been woken up remotely but the IPI has not yet arrived, 7405 * we haven't yet exited the RCU idle mode. Do it here manually until 7406 * we find a better solution. 7407 * 7408 * NB: There are buggy callers of this function. Ideally we 7409 * should warn if prev_state != CT_STATE_USER, but that will trigger 7410 * too frequently to make sense yet. 7411 */ 7412 enum ctx_state prev_state = exception_enter(); 7413 schedule(); 7414 exception_exit(prev_state); 7415 } 7416 #endif 7417 7418 /** 7419 * schedule_preempt_disabled - called with preemption disabled 7420 * 7421 * Returns with preemption disabled. Note: preempt_count must be 1 7422 */ 7423 void __sched schedule_preempt_disabled(void) 7424 { 7425 sched_preempt_enable_no_resched(); 7426 schedule(); 7427 preempt_disable(); 7428 } 7429 7430 #ifdef CONFIG_PREEMPT_RT 7431 void __sched notrace schedule_rtlock(void) 7432 { 7433 __schedule_loop(SM_RTLOCK_WAIT); 7434 } 7435 NOKPROBE_SYMBOL(schedule_rtlock); 7436 #endif 7437 7438 static void __sched notrace preempt_schedule_common(void) 7439 { 7440 do { 7441 /* 7442 * Because the function tracer can trace preempt_count_sub() 7443 * and it also uses preempt_enable/disable_notrace(), if 7444 * NEED_RESCHED is set, the preempt_enable_notrace() called 7445 * by the function tracer will call this function again and 7446 * cause infinite recursion. 7447 * 7448 * Preemption must be disabled here before the function 7449 * tracer can trace. Break up preempt_disable() into two 7450 * calls. One to disable preemption without fear of being 7451 * traced. The other to still record the preemption latency, 7452 * which can also be traced by the function tracer. 7453 */ 7454 preempt_disable_notrace(); 7455 preempt_latency_start(1); 7456 __schedule(SM_PREEMPT); 7457 preempt_latency_stop(1); 7458 preempt_enable_no_resched_notrace(); 7459 7460 /* 7461 * Check again in case we missed a preemption opportunity 7462 * between schedule and now. 7463 */ 7464 } while (need_resched()); 7465 } 7466 7467 #ifdef CONFIG_PREEMPTION 7468 /* 7469 * This is the entry point to schedule() from in-kernel preemption 7470 * off of preempt_enable. 7471 */ 7472 asmlinkage __visible void __sched notrace preempt_schedule(void) 7473 { 7474 /* 7475 * If there is a non-zero preempt_count or interrupts are disabled, 7476 * we do not want to preempt the current task. Just return.. 7477 */ 7478 if (likely(!preemptible())) 7479 return; 7480 preempt_schedule_common(); 7481 } 7482 NOKPROBE_SYMBOL(preempt_schedule); 7483 EXPORT_SYMBOL(preempt_schedule); 7484 7485 #ifdef CONFIG_PREEMPT_DYNAMIC 7486 # ifdef CONFIG_HAVE_PREEMPT_DYNAMIC_CALL 7487 # ifndef preempt_schedule_dynamic_enabled 7488 # define preempt_schedule_dynamic_enabled preempt_schedule 7489 # define preempt_schedule_dynamic_disabled NULL 7490 # endif 7491 DEFINE_STATIC_CALL(preempt_schedule, preempt_schedule_dynamic_enabled); 7492 EXPORT_STATIC_CALL_TRAMP(preempt_schedule); 7493 # elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY) 7494 static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule); 7495 void __sched notrace dynamic_preempt_schedule(void) 7496 { 7497 if (!static_branch_unlikely(&sk_dynamic_preempt_schedule)) 7498 return; 7499 preempt_schedule(); 7500 } 7501 NOKPROBE_SYMBOL(dynamic_preempt_schedule); 7502 EXPORT_SYMBOL(dynamic_preempt_schedule); 7503 # endif 7504 #endif /* CONFIG_PREEMPT_DYNAMIC */ 7505 7506 /** 7507 * preempt_schedule_notrace - preempt_schedule called by tracing 7508 * 7509 * The tracing infrastructure uses preempt_enable_notrace to prevent 7510 * recursion and tracing preempt enabling caused by the tracing 7511 * infrastructure itself. But as tracing can happen in areas coming 7512 * from userspace or just about to enter userspace, a preempt enable 7513 * can occur before user_exit() is called. This will cause the scheduler 7514 * to be called when the system is still in usermode. 7515 * 7516 * To prevent this, the preempt_enable_notrace will use this function 7517 * instead of preempt_schedule() to exit user context if needed before 7518 * calling the scheduler. 7519 */ 7520 asmlinkage __visible void __sched notrace preempt_schedule_notrace(void) 7521 { 7522 enum ctx_state prev_ctx; 7523 7524 if (likely(!preemptible())) 7525 return; 7526 7527 do { 7528 /* 7529 * Because the function tracer can trace preempt_count_sub() 7530 * and it also uses preempt_enable/disable_notrace(), if 7531 * NEED_RESCHED is set, the preempt_enable_notrace() called 7532 * by the function tracer will call this function again and 7533 * cause infinite recursion. 7534 * 7535 * Preemption must be disabled here before the function 7536 * tracer can trace. Break up preempt_disable() into two 7537 * calls. One to disable preemption without fear of being 7538 * traced. The other to still record the preemption latency, 7539 * which can also be traced by the function tracer. 7540 */ 7541 preempt_disable_notrace(); 7542 preempt_latency_start(1); 7543 /* 7544 * Needs preempt disabled in case user_exit() is traced 7545 * and the tracer calls preempt_enable_notrace() causing 7546 * an infinite recursion. 7547 */ 7548 prev_ctx = exception_enter(); 7549 __schedule(SM_PREEMPT); 7550 exception_exit(prev_ctx); 7551 7552 preempt_latency_stop(1); 7553 preempt_enable_no_resched_notrace(); 7554 } while (need_resched()); 7555 } 7556 EXPORT_SYMBOL_GPL(preempt_schedule_notrace); 7557 7558 #ifdef CONFIG_PREEMPT_DYNAMIC 7559 # if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL) 7560 # ifndef preempt_schedule_notrace_dynamic_enabled 7561 # define preempt_schedule_notrace_dynamic_enabled preempt_schedule_notrace 7562 # define preempt_schedule_notrace_dynamic_disabled NULL 7563 # endif 7564 DEFINE_STATIC_CALL(preempt_schedule_notrace, preempt_schedule_notrace_dynamic_enabled); 7565 EXPORT_STATIC_CALL_TRAMP(preempt_schedule_notrace); 7566 # elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY) 7567 static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule_notrace); 7568 void __sched notrace dynamic_preempt_schedule_notrace(void) 7569 { 7570 if (!static_branch_unlikely(&sk_dynamic_preempt_schedule_notrace)) 7571 return; 7572 preempt_schedule_notrace(); 7573 } 7574 NOKPROBE_SYMBOL(dynamic_preempt_schedule_notrace); 7575 EXPORT_SYMBOL(dynamic_preempt_schedule_notrace); 7576 # endif 7577 #endif 7578 7579 #endif /* CONFIG_PREEMPTION */ 7580 7581 /* 7582 * This is the entry point to schedule() from kernel preemption 7583 * off of IRQ context. 7584 * Note, that this is called and return with IRQs disabled. This will 7585 * protect us against recursive calling from IRQ contexts. 7586 */ 7587 asmlinkage __visible void __sched preempt_schedule_irq(void) 7588 { 7589 enum ctx_state prev_state; 7590 7591 /* Catch callers which need to be fixed */ 7592 BUG_ON(preempt_count() || !irqs_disabled()); 7593 7594 prev_state = exception_enter(); 7595 7596 do { 7597 preempt_disable(); 7598 local_irq_enable(); 7599 __schedule(SM_PREEMPT); 7600 local_irq_disable(); 7601 sched_preempt_enable_no_resched(); 7602 } while (need_resched()); 7603 7604 exception_exit(prev_state); 7605 } 7606 7607 int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags, 7608 void *key) 7609 { 7610 WARN_ON_ONCE(wake_flags & ~(WF_SYNC|WF_CURRENT_CPU)); 7611 return try_to_wake_up(curr->private, mode, wake_flags); 7612 } 7613 EXPORT_SYMBOL(default_wake_function); 7614 7615 const struct sched_class *__setscheduler_class(int policy, int prio) 7616 { 7617 if (dl_prio(prio)) 7618 return &dl_sched_class; 7619 7620 if (rt_prio(prio)) 7621 return &rt_sched_class; 7622 7623 #ifdef CONFIG_SCHED_CLASS_EXT 7624 if (task_should_scx(policy)) 7625 return &ext_sched_class; 7626 #endif 7627 7628 return &fair_sched_class; 7629 } 7630 7631 #ifdef CONFIG_RT_MUTEXES 7632 7633 /* 7634 * Would be more useful with typeof()/auto_type but they don't mix with 7635 * bit-fields. Since it's a local thing, use int. Keep the generic sounding 7636 * name such that if someone were to implement this function we get to compare 7637 * notes. 7638 */ 7639 #define fetch_and_set(x, v) ({ int _x = (x); (x) = (v); _x; }) 7640 7641 void rt_mutex_pre_schedule(void) 7642 { 7643 lockdep_assert(!fetch_and_set(current->sched_rt_mutex, 1)); 7644 sched_submit_work(current); 7645 } 7646 7647 /* 7648 * Used within the futex syscall context, skips sched_submit_work() because none 7649 * its work will be done. Asserts ensure that it is indeed the case. 7650 */ 7651 void rt_mutex_futex_pre_schedule(void) 7652 { 7653 lockdep_assert(!(current->flags & (PF_WQ_WORKER | PF_IO_WORKER))); 7654 lockdep_assert(!current->plug); 7655 lockdep_assert(!fetch_and_set(current->sched_rt_mutex, 1)); 7656 } 7657 7658 void rt_mutex_schedule(void) 7659 { 7660 lockdep_assert(current->sched_rt_mutex); 7661 __schedule_loop(SM_NONE); 7662 } 7663 7664 void rt_mutex_post_schedule(void) 7665 { 7666 sched_update_worker(current); 7667 lockdep_assert(fetch_and_set(current->sched_rt_mutex, 0)); 7668 } 7669 7670 void rt_mutex_futex_post_schedule(void) 7671 { 7672 lockdep_assert(fetch_and_set(current->sched_rt_mutex, 0)); 7673 } 7674 7675 /* 7676 * rt_mutex_setprio - set the current priority of a task 7677 * @p: task to boost 7678 * @pi_task: donor task 7679 * 7680 * This function changes the 'effective' priority of a task. It does 7681 * not touch ->normal_prio like __setscheduler(). 7682 * 7683 * Used by the rt_mutex code to implement priority inheritance 7684 * logic. Call site only calls if the priority of the task changed. 7685 */ 7686 void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task) 7687 { 7688 int prio, oldprio, queue_flag = 7689 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK; 7690 const struct sched_class *prev_class, *next_class; 7691 struct rq_flags rf; 7692 struct rq *rq; 7693 7694 /* XXX used to be waiter->prio, not waiter->task->prio */ 7695 prio = __rt_effective_prio(pi_task, p->normal_prio); 7696 7697 /* 7698 * If nothing changed; bail early. 7699 */ 7700 if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio)) 7701 return; 7702 7703 rq = __task_rq_lock(p, &rf); 7704 update_rq_clock(rq); 7705 /* 7706 * Set under pi_lock && rq->lock, such that the value can be used under 7707 * either lock. 7708 * 7709 * Note that there is loads of tricky to make this pointer cache work 7710 * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to 7711 * ensure a task is de-boosted (pi_task is set to NULL) before the 7712 * task is allowed to run again (and can exit). This ensures the pointer 7713 * points to a blocked task -- which guarantees the task is present. 7714 */ 7715 p->pi_top_task = pi_task; 7716 7717 /* 7718 * For FIFO/RR we only need to set prio, if that matches we're done. 7719 */ 7720 if (prio == p->prio && !dl_prio(prio)) 7721 goto out_unlock; 7722 7723 /* 7724 * Idle task boosting is a no-no in general. There is one 7725 * exception, when PREEMPT_RT and NOHZ is active: 7726 * 7727 * The idle task calls get_next_timer_interrupt() and holds 7728 * the timer wheel base->lock on the CPU and another CPU wants 7729 * to access the timer (probably to cancel it). We can safely 7730 * ignore the boosting request, as the idle CPU runs this code 7731 * with interrupts disabled and will complete the lock 7732 * protected section without being interrupted. So there is no 7733 * real need to boost. 7734 */ 7735 if (unlikely(p == rq->idle)) { 7736 WARN_ON(p != rq->curr); 7737 WARN_ON(p->pi_blocked_on); 7738 goto out_unlock; 7739 } 7740 7741 trace_sched_pi_setprio(p, pi_task); 7742 oldprio = p->prio; 7743 7744 if (oldprio == prio && !dl_prio(prio)) 7745 queue_flag &= ~DEQUEUE_MOVE; 7746 7747 prev_class = p->sched_class; 7748 next_class = __setscheduler_class(p->policy, prio); 7749 7750 if (prev_class != next_class) 7751 queue_flag |= DEQUEUE_CLASS; 7752 7753 scoped_guard (sched_change, p, queue_flag) { 7754 /* 7755 * Boosting condition are: 7756 * 1. -rt task is running and holds mutex A 7757 * --> -dl task blocks on mutex A 7758 * 7759 * 2. -dl task is running and holds mutex A 7760 * --> -dl task blocks on mutex A and could preempt the 7761 * running task 7762 */ 7763 if (dl_prio(prio)) { 7764 if (!dl_prio(p->normal_prio) || 7765 (pi_task && dl_prio(pi_task->prio) && 7766 dl_entity_preempt(&pi_task->dl, &p->dl))) { 7767 p->dl.pi_se = pi_task->dl.pi_se; 7768 scope->flags |= ENQUEUE_REPLENISH; 7769 } else { 7770 p->dl.pi_se = &p->dl; 7771 } 7772 } else if (rt_prio(prio)) { 7773 if (dl_prio(oldprio)) 7774 p->dl.pi_se = &p->dl; 7775 if (oldprio < prio) 7776 scope->flags |= ENQUEUE_HEAD; 7777 } else { 7778 if (dl_prio(oldprio)) 7779 p->dl.pi_se = &p->dl; 7780 if (rt_prio(oldprio)) 7781 p->rt.timeout = 0; 7782 } 7783 7784 p->sched_class = next_class; 7785 p->prio = prio; 7786 } 7787 out_unlock: 7788 /* Caller holds task_struct::pi_lock, IRQs are still disabled */ 7789 7790 __balance_callbacks(rq, &rf); 7791 __task_rq_unlock(rq, p, &rf); 7792 } 7793 #endif /* CONFIG_RT_MUTEXES */ 7794 7795 #if !defined(CONFIG_PREEMPTION) || defined(CONFIG_PREEMPT_DYNAMIC) 7796 int __sched __cond_resched(void) 7797 { 7798 if (should_resched(0) && !irqs_disabled()) { 7799 preempt_schedule_common(); 7800 return 1; 7801 } 7802 /* 7803 * In PREEMPT_RCU kernels, ->rcu_read_lock_nesting tells the tick 7804 * whether the current CPU is in an RCU read-side critical section, 7805 * so the tick can report quiescent states even for CPUs looping 7806 * in kernel context. In contrast, in non-preemptible kernels, 7807 * RCU readers leave no in-memory hints, which means that CPU-bound 7808 * processes executing in kernel context might never report an 7809 * RCU quiescent state. Therefore, the following code causes 7810 * cond_resched() to report a quiescent state, but only when RCU 7811 * is in urgent need of one. 7812 * A third case, preemptible, but non-PREEMPT_RCU provides for 7813 * urgently needed quiescent states via rcu_flavor_sched_clock_irq(). 7814 */ 7815 #ifndef CONFIG_PREEMPT_RCU 7816 rcu_all_qs(); 7817 #endif 7818 return 0; 7819 } 7820 EXPORT_SYMBOL(__cond_resched); 7821 #endif 7822 7823 #ifdef CONFIG_PREEMPT_DYNAMIC 7824 # ifdef CONFIG_HAVE_PREEMPT_DYNAMIC_CALL 7825 # define cond_resched_dynamic_enabled __cond_resched 7826 # define cond_resched_dynamic_disabled ((void *)&__static_call_return0) 7827 DEFINE_STATIC_CALL_RET0(cond_resched, __cond_resched); 7828 EXPORT_STATIC_CALL_TRAMP(cond_resched); 7829 7830 # define might_resched_dynamic_enabled __cond_resched 7831 # define might_resched_dynamic_disabled ((void *)&__static_call_return0) 7832 DEFINE_STATIC_CALL_RET0(might_resched, __cond_resched); 7833 EXPORT_STATIC_CALL_TRAMP(might_resched); 7834 # elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY) 7835 static DEFINE_STATIC_KEY_FALSE(sk_dynamic_cond_resched); 7836 int __sched dynamic_cond_resched(void) 7837 { 7838 if (!static_branch_unlikely(&sk_dynamic_cond_resched)) 7839 return 0; 7840 return __cond_resched(); 7841 } 7842 EXPORT_SYMBOL(dynamic_cond_resched); 7843 7844 static DEFINE_STATIC_KEY_FALSE(sk_dynamic_might_resched); 7845 int __sched dynamic_might_resched(void) 7846 { 7847 if (!static_branch_unlikely(&sk_dynamic_might_resched)) 7848 return 0; 7849 return __cond_resched(); 7850 } 7851 EXPORT_SYMBOL(dynamic_might_resched); 7852 # endif 7853 #endif /* CONFIG_PREEMPT_DYNAMIC */ 7854 7855 /* 7856 * __cond_resched_lock() - if a reschedule is pending, drop the given lock, 7857 * call schedule, and on return reacquire the lock. 7858 * 7859 * This works OK both with and without CONFIG_PREEMPTION. We do strange low-level 7860 * operations here to prevent schedule() from being called twice (once via 7861 * spin_unlock(), once by hand). 7862 */ 7863 int __cond_resched_lock(spinlock_t *lock) 7864 { 7865 int resched = should_resched(PREEMPT_LOCK_OFFSET); 7866 int ret = 0; 7867 7868 lockdep_assert_held(lock); 7869 7870 if (spin_needbreak(lock) || resched) { 7871 spin_unlock(lock); 7872 if (!_cond_resched()) 7873 cpu_relax(); 7874 ret = 1; 7875 spin_lock(lock); 7876 } 7877 return ret; 7878 } 7879 EXPORT_SYMBOL(__cond_resched_lock); 7880 7881 int __cond_resched_rwlock_read(rwlock_t *lock) 7882 { 7883 int resched = should_resched(PREEMPT_LOCK_OFFSET); 7884 int ret = 0; 7885 7886 lockdep_assert_held_read(lock); 7887 7888 if (rwlock_needbreak(lock) || resched) { 7889 read_unlock(lock); 7890 if (!_cond_resched()) 7891 cpu_relax(); 7892 ret = 1; 7893 read_lock(lock); 7894 } 7895 return ret; 7896 } 7897 EXPORT_SYMBOL(__cond_resched_rwlock_read); 7898 7899 int __cond_resched_rwlock_write(rwlock_t *lock) 7900 { 7901 int resched = should_resched(PREEMPT_LOCK_OFFSET); 7902 int ret = 0; 7903 7904 lockdep_assert_held_write(lock); 7905 7906 if (rwlock_needbreak(lock) || resched) { 7907 write_unlock(lock); 7908 if (!_cond_resched()) 7909 cpu_relax(); 7910 ret = 1; 7911 write_lock(lock); 7912 } 7913 return ret; 7914 } 7915 EXPORT_SYMBOL(__cond_resched_rwlock_write); 7916 7917 #ifdef CONFIG_PREEMPT_DYNAMIC 7918 7919 # ifdef CONFIG_GENERIC_IRQ_ENTRY 7920 # include <linux/irq-entry-common.h> 7921 # endif 7922 7923 /* 7924 * SC:cond_resched 7925 * SC:might_resched 7926 * SC:preempt_schedule 7927 * SC:preempt_schedule_notrace 7928 * SC:irqentry_exit_cond_resched 7929 * 7930 * 7931 * NONE: 7932 * cond_resched <- __cond_resched 7933 * might_resched <- RET0 7934 * preempt_schedule <- NOP 7935 * preempt_schedule_notrace <- NOP 7936 * irqentry_exit_cond_resched <- NOP 7937 * dynamic_preempt_lazy <- false 7938 * 7939 * VOLUNTARY: 7940 * cond_resched <- __cond_resched 7941 * might_resched <- __cond_resched 7942 * preempt_schedule <- NOP 7943 * preempt_schedule_notrace <- NOP 7944 * irqentry_exit_cond_resched <- NOP 7945 * dynamic_preempt_lazy <- false 7946 * 7947 * FULL: 7948 * cond_resched <- RET0 7949 * might_resched <- RET0 7950 * preempt_schedule <- preempt_schedule 7951 * preempt_schedule_notrace <- preempt_schedule_notrace 7952 * irqentry_exit_cond_resched <- irqentry_exit_cond_resched 7953 * dynamic_preempt_lazy <- false 7954 * 7955 * LAZY: 7956 * cond_resched <- RET0 7957 * might_resched <- RET0 7958 * preempt_schedule <- preempt_schedule 7959 * preempt_schedule_notrace <- preempt_schedule_notrace 7960 * irqentry_exit_cond_resched <- irqentry_exit_cond_resched 7961 * dynamic_preempt_lazy <- true 7962 */ 7963 7964 enum { 7965 preempt_dynamic_undefined = -1, 7966 preempt_dynamic_none, 7967 preempt_dynamic_voluntary, 7968 preempt_dynamic_full, 7969 preempt_dynamic_lazy, 7970 }; 7971 7972 int preempt_dynamic_mode = preempt_dynamic_undefined; 7973 7974 int sched_dynamic_mode(const char *str) 7975 { 7976 # if !(defined(CONFIG_PREEMPT_RT) || defined(CONFIG_ARCH_HAS_PREEMPT_LAZY)) 7977 if (!strcmp(str, "none")) 7978 return preempt_dynamic_none; 7979 7980 if (!strcmp(str, "voluntary")) 7981 return preempt_dynamic_voluntary; 7982 # endif 7983 7984 if (!strcmp(str, "full")) 7985 return preempt_dynamic_full; 7986 7987 # ifdef CONFIG_ARCH_HAS_PREEMPT_LAZY 7988 if (!strcmp(str, "lazy")) 7989 return preempt_dynamic_lazy; 7990 # endif 7991 7992 return -EINVAL; 7993 } 7994 7995 # define preempt_dynamic_key_enable(f) static_key_enable(&sk_dynamic_##f.key) 7996 # define preempt_dynamic_key_disable(f) static_key_disable(&sk_dynamic_##f.key) 7997 7998 # if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL) 7999 # define preempt_dynamic_enable(f) static_call_update(f, f##_dynamic_enabled) 8000 # define preempt_dynamic_disable(f) static_call_update(f, f##_dynamic_disabled) 8001 # elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY) 8002 # define preempt_dynamic_enable(f) preempt_dynamic_key_enable(f) 8003 # define preempt_dynamic_disable(f) preempt_dynamic_key_disable(f) 8004 # else 8005 # error "Unsupported PREEMPT_DYNAMIC mechanism" 8006 # endif 8007 8008 static DEFINE_MUTEX(sched_dynamic_mutex); 8009 8010 static void __sched_dynamic_update(int mode) 8011 { 8012 /* 8013 * Avoid {NONE,VOLUNTARY} -> FULL transitions from ever ending up in 8014 * the ZERO state, which is invalid. 8015 */ 8016 preempt_dynamic_enable(cond_resched); 8017 preempt_dynamic_enable(might_resched); 8018 preempt_dynamic_enable(preempt_schedule); 8019 preempt_dynamic_enable(preempt_schedule_notrace); 8020 preempt_dynamic_enable(irqentry_exit_cond_resched); 8021 preempt_dynamic_key_disable(preempt_lazy); 8022 8023 switch (mode) { 8024 case preempt_dynamic_none: 8025 preempt_dynamic_enable(cond_resched); 8026 preempt_dynamic_disable(might_resched); 8027 preempt_dynamic_disable(preempt_schedule); 8028 preempt_dynamic_disable(preempt_schedule_notrace); 8029 preempt_dynamic_disable(irqentry_exit_cond_resched); 8030 preempt_dynamic_key_disable(preempt_lazy); 8031 if (mode != preempt_dynamic_mode) 8032 pr_info("Dynamic Preempt: none\n"); 8033 break; 8034 8035 case preempt_dynamic_voluntary: 8036 preempt_dynamic_enable(cond_resched); 8037 preempt_dynamic_enable(might_resched); 8038 preempt_dynamic_disable(preempt_schedule); 8039 preempt_dynamic_disable(preempt_schedule_notrace); 8040 preempt_dynamic_disable(irqentry_exit_cond_resched); 8041 preempt_dynamic_key_disable(preempt_lazy); 8042 if (mode != preempt_dynamic_mode) 8043 pr_info("Dynamic Preempt: voluntary\n"); 8044 break; 8045 8046 case preempt_dynamic_full: 8047 preempt_dynamic_disable(cond_resched); 8048 preempt_dynamic_disable(might_resched); 8049 preempt_dynamic_enable(preempt_schedule); 8050 preempt_dynamic_enable(preempt_schedule_notrace); 8051 preempt_dynamic_enable(irqentry_exit_cond_resched); 8052 preempt_dynamic_key_disable(preempt_lazy); 8053 if (mode != preempt_dynamic_mode) 8054 pr_info("Dynamic Preempt: full\n"); 8055 break; 8056 8057 case preempt_dynamic_lazy: 8058 preempt_dynamic_disable(cond_resched); 8059 preempt_dynamic_disable(might_resched); 8060 preempt_dynamic_enable(preempt_schedule); 8061 preempt_dynamic_enable(preempt_schedule_notrace); 8062 preempt_dynamic_enable(irqentry_exit_cond_resched); 8063 preempt_dynamic_key_enable(preempt_lazy); 8064 if (mode != preempt_dynamic_mode) 8065 pr_info("Dynamic Preempt: lazy\n"); 8066 break; 8067 } 8068 8069 WRITE_ONCE(preempt_dynamic_mode, mode); 8070 } 8071 8072 void sched_dynamic_update(int mode) 8073 { 8074 mutex_lock(&sched_dynamic_mutex); 8075 __sched_dynamic_update(mode); 8076 mutex_unlock(&sched_dynamic_mutex); 8077 } 8078 8079 static int __init setup_preempt_mode(char *str) 8080 { 8081 int mode = sched_dynamic_mode(str); 8082 if (mode < 0) { 8083 pr_warn("Dynamic Preempt: unsupported mode: %s\n", str); 8084 return 0; 8085 } 8086 8087 sched_dynamic_update(mode); 8088 return 1; 8089 } 8090 __setup("preempt=", setup_preempt_mode); 8091 8092 static void __init preempt_dynamic_init(void) 8093 { 8094 if (preempt_dynamic_mode == preempt_dynamic_undefined) { 8095 if (IS_ENABLED(CONFIG_PREEMPT_NONE)) { 8096 sched_dynamic_update(preempt_dynamic_none); 8097 } else if (IS_ENABLED(CONFIG_PREEMPT_VOLUNTARY)) { 8098 sched_dynamic_update(preempt_dynamic_voluntary); 8099 } else if (IS_ENABLED(CONFIG_PREEMPT_LAZY)) { 8100 sched_dynamic_update(preempt_dynamic_lazy); 8101 } else { 8102 /* Default static call setting, nothing to do */ 8103 WARN_ON_ONCE(!IS_ENABLED(CONFIG_PREEMPT)); 8104 preempt_dynamic_mode = preempt_dynamic_full; 8105 pr_info("Dynamic Preempt: full\n"); 8106 } 8107 } 8108 } 8109 8110 # define PREEMPT_MODEL_ACCESSOR(mode) \ 8111 bool preempt_model_##mode(void) \ 8112 { \ 8113 int mode = READ_ONCE(preempt_dynamic_mode); \ 8114 WARN_ON_ONCE(mode == preempt_dynamic_undefined); \ 8115 return mode == preempt_dynamic_##mode; \ 8116 } \ 8117 EXPORT_SYMBOL_GPL(preempt_model_##mode) 8118 8119 PREEMPT_MODEL_ACCESSOR(none); 8120 PREEMPT_MODEL_ACCESSOR(voluntary); 8121 PREEMPT_MODEL_ACCESSOR(full); 8122 PREEMPT_MODEL_ACCESSOR(lazy); 8123 8124 #else /* !CONFIG_PREEMPT_DYNAMIC: */ 8125 8126 #define preempt_dynamic_mode -1 8127 8128 static inline void preempt_dynamic_init(void) { } 8129 8130 #endif /* CONFIG_PREEMPT_DYNAMIC */ 8131 8132 const char *preempt_modes[] = { 8133 "none", "voluntary", "full", "lazy", NULL, 8134 }; 8135 8136 const char *preempt_model_str(void) 8137 { 8138 bool brace = IS_ENABLED(CONFIG_PREEMPT_RT) && 8139 (IS_ENABLED(CONFIG_PREEMPT_DYNAMIC) || 8140 IS_ENABLED(CONFIG_PREEMPT_LAZY)); 8141 static char buf[128]; 8142 8143 if (IS_ENABLED(CONFIG_PREEMPT_BUILD)) { 8144 struct seq_buf s; 8145 8146 seq_buf_init(&s, buf, sizeof(buf)); 8147 seq_buf_puts(&s, "PREEMPT"); 8148 8149 if (IS_ENABLED(CONFIG_PREEMPT_RT)) 8150 seq_buf_printf(&s, "%sRT%s", 8151 brace ? "_{" : "_", 8152 brace ? "," : ""); 8153 8154 if (IS_ENABLED(CONFIG_PREEMPT_DYNAMIC)) { 8155 seq_buf_printf(&s, "(%s)%s", 8156 preempt_dynamic_mode >= 0 ? 8157 preempt_modes[preempt_dynamic_mode] : "undef", 8158 brace ? "}" : ""); 8159 return seq_buf_str(&s); 8160 } 8161 8162 if (IS_ENABLED(CONFIG_PREEMPT_LAZY)) { 8163 seq_buf_printf(&s, "LAZY%s", 8164 brace ? "}" : ""); 8165 return seq_buf_str(&s); 8166 } 8167 8168 return seq_buf_str(&s); 8169 } 8170 8171 if (IS_ENABLED(CONFIG_PREEMPT_VOLUNTARY_BUILD)) 8172 return "VOLUNTARY"; 8173 8174 return "NONE"; 8175 } 8176 8177 int io_schedule_prepare(void) 8178 { 8179 int old_iowait = current->in_iowait; 8180 8181 current->in_iowait = 1; 8182 blk_flush_plug(current->plug, true); 8183 return old_iowait; 8184 } 8185 8186 void io_schedule_finish(int token) 8187 { 8188 current->in_iowait = token; 8189 } 8190 8191 /* 8192 * This task is about to go to sleep on IO. Increment rq->nr_iowait so 8193 * that process accounting knows that this is a task in IO wait state. 8194 */ 8195 long __sched io_schedule_timeout(long timeout) 8196 { 8197 int token; 8198 long ret; 8199 8200 token = io_schedule_prepare(); 8201 ret = schedule_timeout(timeout); 8202 io_schedule_finish(token); 8203 8204 return ret; 8205 } 8206 EXPORT_SYMBOL(io_schedule_timeout); 8207 8208 void __sched io_schedule(void) 8209 { 8210 int token; 8211 8212 token = io_schedule_prepare(); 8213 schedule(); 8214 io_schedule_finish(token); 8215 } 8216 EXPORT_SYMBOL(io_schedule); 8217 8218 void sched_show_task(struct task_struct *p) 8219 { 8220 unsigned long free; 8221 int ppid; 8222 8223 if (!try_get_task_stack(p)) 8224 return; 8225 8226 pr_info("task:%-15.15s state:%c", p->comm, task_state_to_char(p)); 8227 8228 if (task_is_running(p)) 8229 pr_cont(" running task "); 8230 free = stack_not_used(p); 8231 ppid = 0; 8232 rcu_read_lock(); 8233 if (pid_alive(p)) 8234 ppid = task_pid_nr(rcu_dereference(p->real_parent)); 8235 rcu_read_unlock(); 8236 pr_cont(" stack:%-5lu pid:%-5d tgid:%-5d ppid:%-6d task_flags:0x%04x flags:0x%08lx\n", 8237 free, task_pid_nr(p), task_tgid_nr(p), 8238 ppid, p->flags, read_task_thread_flags(p)); 8239 8240 print_worker_info(KERN_INFO, p); 8241 print_stop_info(KERN_INFO, p); 8242 print_scx_info(KERN_INFO, p); 8243 show_stack(p, NULL, KERN_INFO); 8244 put_task_stack(p); 8245 } 8246 EXPORT_SYMBOL_GPL(sched_show_task); 8247 8248 static inline bool 8249 state_filter_match(unsigned long state_filter, struct task_struct *p) 8250 { 8251 unsigned int state = READ_ONCE(p->__state); 8252 8253 /* no filter, everything matches */ 8254 if (!state_filter) 8255 return true; 8256 8257 /* filter, but doesn't match */ 8258 if (!(state & state_filter)) 8259 return false; 8260 8261 /* 8262 * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows 8263 * TASK_KILLABLE). 8264 */ 8265 if (state_filter == TASK_UNINTERRUPTIBLE && (state & TASK_NOLOAD)) 8266 return false; 8267 8268 return true; 8269 } 8270 8271 8272 void show_state_filter(unsigned int state_filter) 8273 { 8274 struct task_struct *g, *p; 8275 8276 rcu_read_lock(); 8277 for_each_process_thread(g, p) { 8278 /* 8279 * reset the NMI-timeout, listing all files on a slow 8280 * console might take a lot of time: 8281 * Also, reset softlockup watchdogs on all CPUs, because 8282 * another CPU might be blocked waiting for us to process 8283 * an IPI. 8284 */ 8285 touch_nmi_watchdog(); 8286 touch_all_softlockup_watchdogs(); 8287 if (state_filter_match(state_filter, p)) 8288 sched_show_task(p); 8289 } 8290 8291 if (!state_filter) 8292 sysrq_sched_debug_show(); 8293 8294 rcu_read_unlock(); 8295 /* 8296 * Only show locks if all tasks are dumped: 8297 */ 8298 if (!state_filter) 8299 debug_show_all_locks(); 8300 } 8301 8302 /** 8303 * init_idle - set up an idle thread for a given CPU 8304 * @idle: task in question 8305 * @cpu: CPU the idle task belongs to 8306 * 8307 * NOTE: this function does not set the idle thread's NEED_RESCHED 8308 * flag, to make booting more robust. 8309 */ 8310 void __init init_idle(struct task_struct *idle, int cpu) 8311 { 8312 struct affinity_context ac = (struct affinity_context) { 8313 .new_mask = cpumask_of(cpu), 8314 .flags = 0, 8315 }; 8316 struct rq *rq = cpu_rq(cpu); 8317 unsigned long flags; 8318 8319 raw_spin_lock_irqsave(&idle->pi_lock, flags); 8320 raw_spin_rq_lock(rq); 8321 8322 idle->__state = TASK_RUNNING; 8323 idle->se.exec_start = sched_clock(); 8324 /* 8325 * PF_KTHREAD should already be set at this point; regardless, make it 8326 * look like a proper per-CPU kthread. 8327 */ 8328 idle->flags |= PF_KTHREAD | PF_NO_SETAFFINITY; 8329 kthread_set_per_cpu(idle, cpu); 8330 8331 /* 8332 * No validation and serialization required at boot time and for 8333 * setting up the idle tasks of not yet online CPUs. 8334 */ 8335 set_cpus_allowed_common(idle, &ac); 8336 /* 8337 * We're having a chicken and egg problem, even though we are 8338 * holding rq->lock, the CPU isn't yet set to this CPU so the 8339 * lockdep check in task_group() will fail. 8340 * 8341 * Similar case to sched_fork(). / Alternatively we could 8342 * use task_rq_lock() here and obtain the other rq->lock. 8343 * 8344 * Silence PROVE_RCU 8345 */ 8346 rcu_read_lock(); 8347 __set_task_cpu(idle, cpu); 8348 rcu_read_unlock(); 8349 8350 rq->idle = idle; 8351 rq_set_donor(rq, idle); 8352 rcu_assign_pointer(rq->curr, idle); 8353 idle->on_rq = TASK_ON_RQ_QUEUED; 8354 idle->on_cpu = 1; 8355 raw_spin_rq_unlock(rq); 8356 raw_spin_unlock_irqrestore(&idle->pi_lock, flags); 8357 8358 /* Set the preempt count _outside_ the spinlocks! */ 8359 init_idle_preempt_count(idle, cpu); 8360 8361 /* 8362 * The idle tasks have their own, simple scheduling class: 8363 */ 8364 idle->sched_class = &idle_sched_class; 8365 ftrace_graph_init_idle_task(idle, cpu); 8366 vtime_init_idle(idle, cpu); 8367 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu); 8368 } 8369 8370 int cpuset_cpumask_can_shrink(const struct cpumask *cur, 8371 const struct cpumask *trial) 8372 { 8373 int ret = 1; 8374 8375 if (cpumask_empty(cur)) 8376 return ret; 8377 8378 ret = dl_cpuset_cpumask_can_shrink(cur, trial); 8379 8380 return ret; 8381 } 8382 8383 int task_can_attach(struct task_struct *p) 8384 { 8385 int ret = 0; 8386 8387 /* 8388 * Kthreads which disallow setaffinity shouldn't be moved 8389 * to a new cpuset; we don't want to change their CPU 8390 * affinity and isolating such threads by their set of 8391 * allowed nodes is unnecessary. Thus, cpusets are not 8392 * applicable for such threads. This prevents checking for 8393 * success of set_cpus_allowed_ptr() on all attached tasks 8394 * before cpus_mask may be changed. 8395 */ 8396 if (p->flags & PF_NO_SETAFFINITY) 8397 ret = -EINVAL; 8398 8399 return ret; 8400 } 8401 8402 bool sched_smp_initialized __read_mostly; 8403 8404 #ifdef CONFIG_NUMA_BALANCING 8405 /* Migrate current task p to target_cpu */ 8406 int migrate_task_to(struct task_struct *p, int target_cpu) 8407 { 8408 struct migration_arg arg = { p, target_cpu }; 8409 int curr_cpu = task_cpu(p); 8410 8411 if (curr_cpu == target_cpu) 8412 return 0; 8413 8414 if (!cpumask_test_cpu(target_cpu, p->cpus_ptr)) 8415 return -EINVAL; 8416 8417 /* TODO: This is not properly updating schedstats */ 8418 8419 trace_sched_move_numa(p, curr_cpu, target_cpu); 8420 return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg); 8421 } 8422 8423 /* 8424 * Requeue a task on a given node and accurately track the number of NUMA 8425 * tasks on the runqueues 8426 */ 8427 void sched_setnuma(struct task_struct *p, int nid) 8428 { 8429 guard(task_rq_lock)(p); 8430 scoped_guard (sched_change, p, DEQUEUE_SAVE) 8431 p->numa_preferred_nid = nid; 8432 } 8433 #endif /* CONFIG_NUMA_BALANCING */ 8434 8435 #ifdef CONFIG_HOTPLUG_CPU 8436 /* 8437 * Invoked on the outgoing CPU in context of the CPU hotplug thread 8438 * after ensuring that there are no user space tasks left on the CPU. 8439 * 8440 * If there is a lazy mm in use on the hotplug thread, drop it and 8441 * switch to init_mm. 8442 * 8443 * The reference count on init_mm is dropped in finish_cpu(). 8444 */ 8445 static void sched_force_init_mm(void) 8446 { 8447 struct mm_struct *mm = current->active_mm; 8448 8449 if (mm != &init_mm) { 8450 mmgrab_lazy_tlb(&init_mm); 8451 local_irq_disable(); 8452 current->active_mm = &init_mm; 8453 switch_mm_irqs_off(mm, &init_mm, current); 8454 local_irq_enable(); 8455 finish_arch_post_lock_switch(); 8456 mmdrop_lazy_tlb(mm); 8457 } 8458 8459 /* finish_cpu(), as ran on the BP, will clean up the active_mm state */ 8460 } 8461 8462 static int __balance_push_cpu_stop(void *arg) 8463 { 8464 struct task_struct *p = arg; 8465 struct rq *rq = this_rq(); 8466 struct rq_flags rf; 8467 int cpu; 8468 8469 scoped_guard (raw_spinlock_irq, &p->pi_lock) { 8470 /* 8471 * We may change the underlying rq, but the locks held will 8472 * appropriately be "transferred" when switching. 8473 */ 8474 context_unsafe_alias(rq); 8475 8476 cpu = select_fallback_rq(rq->cpu, p); 8477 8478 rq_lock(rq, &rf); 8479 update_rq_clock(rq); 8480 if (task_rq(p) == rq && task_on_rq_queued(p)) 8481 rq = __migrate_task(rq, &rf, p, cpu); 8482 rq_unlock(rq, &rf); 8483 } 8484 8485 put_task_struct(p); 8486 8487 return 0; 8488 } 8489 8490 static DEFINE_PER_CPU(struct cpu_stop_work, push_work); 8491 8492 /* 8493 * Ensure we only run per-cpu kthreads once the CPU goes !active. 8494 * 8495 * This is enabled below SCHED_AP_ACTIVE; when !cpu_active(), but only 8496 * effective when the hotplug motion is down. 8497 */ 8498 static void balance_push(struct rq *rq) 8499 __must_hold(__rq_lockp(rq)) 8500 { 8501 struct task_struct *push_task = rq->curr; 8502 8503 lockdep_assert_rq_held(rq); 8504 8505 /* 8506 * Ensure the thing is persistent until balance_push_set(.on = false); 8507 */ 8508 rq->balance_callback = &balance_push_callback; 8509 8510 /* 8511 * Only active while going offline and when invoked on the outgoing 8512 * CPU. 8513 */ 8514 if (!cpu_dying(rq->cpu) || rq != this_rq()) 8515 return; 8516 8517 /* 8518 * Both the cpu-hotplug and stop task are in this case and are 8519 * required to complete the hotplug process. 8520 */ 8521 if (kthread_is_per_cpu(push_task) || 8522 is_migration_disabled(push_task)) { 8523 8524 /* 8525 * If this is the idle task on the outgoing CPU try to wake 8526 * up the hotplug control thread which might wait for the 8527 * last task to vanish. The rcuwait_active() check is 8528 * accurate here because the waiter is pinned on this CPU 8529 * and can't obviously be running in parallel. 8530 * 8531 * On RT kernels this also has to check whether there are 8532 * pinned and scheduled out tasks on the runqueue. They 8533 * need to leave the migrate disabled section first. 8534 */ 8535 if (!rq->nr_running && !rq_has_pinned_tasks(rq) && 8536 rcuwait_active(&rq->hotplug_wait)) { 8537 raw_spin_rq_unlock(rq); 8538 rcuwait_wake_up(&rq->hotplug_wait); 8539 raw_spin_rq_lock(rq); 8540 } 8541 return; 8542 } 8543 8544 get_task_struct(push_task); 8545 /* 8546 * Temporarily drop rq->lock such that we can wake-up the stop task. 8547 * Both preemption and IRQs are still disabled. 8548 */ 8549 preempt_disable(); 8550 raw_spin_rq_unlock(rq); 8551 stop_one_cpu_nowait(rq->cpu, __balance_push_cpu_stop, push_task, 8552 this_cpu_ptr(&push_work)); 8553 preempt_enable(); 8554 /* 8555 * At this point need_resched() is true and we'll take the loop in 8556 * schedule(). The next pick is obviously going to be the stop task 8557 * which kthread_is_per_cpu() and will push this task away. 8558 */ 8559 raw_spin_rq_lock(rq); 8560 } 8561 8562 static void balance_push_set(int cpu, bool on) 8563 { 8564 struct rq *rq = cpu_rq(cpu); 8565 struct rq_flags rf; 8566 8567 rq_lock_irqsave(rq, &rf); 8568 if (on) { 8569 WARN_ON_ONCE(rq->balance_callback); 8570 rq->balance_callback = &balance_push_callback; 8571 } else if (rq->balance_callback == &balance_push_callback) { 8572 rq->balance_callback = NULL; 8573 } 8574 rq_unlock_irqrestore(rq, &rf); 8575 } 8576 8577 /* 8578 * Invoked from a CPUs hotplug control thread after the CPU has been marked 8579 * inactive. All tasks which are not per CPU kernel threads are either 8580 * pushed off this CPU now via balance_push() or placed on a different CPU 8581 * during wakeup. Wait until the CPU is quiescent. 8582 */ 8583 static void balance_hotplug_wait(void) 8584 { 8585 struct rq *rq = this_rq(); 8586 8587 rcuwait_wait_event(&rq->hotplug_wait, 8588 rq->nr_running == 1 && !rq_has_pinned_tasks(rq), 8589 TASK_UNINTERRUPTIBLE); 8590 } 8591 8592 #else /* !CONFIG_HOTPLUG_CPU: */ 8593 8594 static inline void balance_push(struct rq *rq) 8595 { 8596 } 8597 8598 static inline void balance_push_set(int cpu, bool on) 8599 { 8600 } 8601 8602 static inline void balance_hotplug_wait(void) 8603 { 8604 } 8605 8606 #endif /* !CONFIG_HOTPLUG_CPU */ 8607 8608 void set_rq_online(struct rq *rq) 8609 { 8610 if (!rq->online) { 8611 const struct sched_class *class; 8612 8613 cpumask_set_cpu(rq->cpu, rq->rd->online); 8614 rq->online = 1; 8615 8616 for_each_class(class) { 8617 if (class->rq_online) 8618 class->rq_online(rq); 8619 } 8620 } 8621 } 8622 8623 void set_rq_offline(struct rq *rq) 8624 { 8625 if (rq->online) { 8626 const struct sched_class *class; 8627 8628 update_rq_clock(rq); 8629 for_each_class(class) { 8630 if (class->rq_offline) 8631 class->rq_offline(rq); 8632 } 8633 8634 cpumask_clear_cpu(rq->cpu, rq->rd->online); 8635 rq->online = 0; 8636 } 8637 } 8638 8639 static inline void sched_set_rq_online(struct rq *rq, int cpu) 8640 { 8641 struct rq_flags rf; 8642 8643 rq_lock_irqsave(rq, &rf); 8644 if (rq->rd) { 8645 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span)); 8646 set_rq_online(rq); 8647 } 8648 rq_unlock_irqrestore(rq, &rf); 8649 } 8650 8651 static inline void sched_set_rq_offline(struct rq *rq, int cpu) 8652 { 8653 struct rq_flags rf; 8654 8655 rq_lock_irqsave(rq, &rf); 8656 if (rq->rd) { 8657 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span)); 8658 set_rq_offline(rq); 8659 } 8660 rq_unlock_irqrestore(rq, &rf); 8661 } 8662 8663 /* 8664 * used to mark begin/end of suspend/resume: 8665 */ 8666 static int num_cpus_frozen; 8667 8668 /* 8669 * Update cpusets according to cpu_active mask. If cpusets are 8670 * disabled, cpuset_update_active_cpus() becomes a simple wrapper 8671 * around partition_sched_domains(). 8672 * 8673 * If we come here as part of a suspend/resume, don't touch cpusets because we 8674 * want to restore it back to its original state upon resume anyway. 8675 */ 8676 static void cpuset_cpu_active(void) 8677 { 8678 if (cpuhp_tasks_frozen) { 8679 /* 8680 * num_cpus_frozen tracks how many CPUs are involved in suspend 8681 * resume sequence. As long as this is not the last online 8682 * operation in the resume sequence, just build a single sched 8683 * domain, ignoring cpusets. 8684 */ 8685 cpuset_reset_sched_domains(); 8686 if (--num_cpus_frozen) 8687 return; 8688 /* 8689 * This is the last CPU online operation. So fall through and 8690 * restore the original sched domains by considering the 8691 * cpuset configurations. 8692 */ 8693 cpuset_force_rebuild(); 8694 } 8695 cpuset_update_active_cpus(); 8696 } 8697 8698 static void cpuset_cpu_inactive(unsigned int cpu) 8699 { 8700 if (!cpuhp_tasks_frozen) { 8701 cpuset_update_active_cpus(); 8702 } else { 8703 num_cpus_frozen++; 8704 cpuset_reset_sched_domains(); 8705 } 8706 } 8707 8708 static inline void sched_smt_present_inc(int cpu) 8709 { 8710 if (cpumask_weight(cpu_smt_mask(cpu)) == 2) 8711 static_branch_inc_cpuslocked(&sched_smt_present); 8712 } 8713 8714 static inline void sched_smt_present_dec(int cpu) 8715 { 8716 if (cpumask_weight(cpu_smt_mask(cpu)) == 2) 8717 static_branch_dec_cpuslocked(&sched_smt_present); 8718 } 8719 8720 int sched_cpu_activate(unsigned int cpu) 8721 { 8722 struct rq *rq = cpu_rq(cpu); 8723 8724 /* 8725 * Clear the balance_push callback and prepare to schedule 8726 * regular tasks. 8727 */ 8728 balance_push_set(cpu, false); 8729 8730 /* 8731 * When going up, increment the number of cores with SMT present. 8732 */ 8733 sched_smt_present_inc(cpu); 8734 set_cpu_active(cpu, true); 8735 8736 if (sched_smp_initialized) { 8737 sched_update_numa(cpu, true); 8738 sched_domains_numa_masks_set(cpu); 8739 cpuset_cpu_active(); 8740 } 8741 8742 scx_rq_activate(rq); 8743 8744 /* 8745 * Put the rq online, if not already. This happens: 8746 * 8747 * 1) In the early boot process, because we build the real domains 8748 * after all CPUs have been brought up. 8749 * 8750 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the 8751 * domains. 8752 */ 8753 sched_set_rq_online(rq, cpu); 8754 8755 return 0; 8756 } 8757 8758 int sched_cpu_deactivate(unsigned int cpu) 8759 { 8760 struct rq *rq = cpu_rq(cpu); 8761 int ret; 8762 8763 ret = dl_bw_deactivate(cpu); 8764 8765 if (ret) 8766 return ret; 8767 8768 /* 8769 * Remove CPU from nohz.idle_cpus_mask to prevent participating in 8770 * load balancing when not active 8771 */ 8772 scoped_guard (rcu) 8773 nohz_balance_exit_idle(rq); 8774 8775 set_cpu_active(cpu, false); 8776 8777 /* 8778 * From this point forward, this CPU will refuse to run any task that 8779 * is not: migrate_disable() or KTHREAD_IS_PER_CPU, and will actively 8780 * push those tasks away until this gets cleared, see 8781 * sched_cpu_dying(). 8782 */ 8783 balance_push_set(cpu, true); 8784 8785 /* 8786 * We've cleared cpu_active_mask / set balance_push, wait for all 8787 * preempt-disabled and RCU users of this state to go away such that 8788 * all new such users will observe it. 8789 * 8790 * Specifically, we rely on ttwu to no longer target this CPU, see 8791 * ttwu_queue_cond() and is_cpu_allowed(). 8792 * 8793 * Do sync before park smpboot threads to take care the RCU boost case. 8794 */ 8795 synchronize_rcu(); 8796 8797 sched_domains_free_llc_id(cpu); 8798 8799 sched_set_rq_offline(rq, cpu); 8800 8801 scx_rq_deactivate(rq); 8802 8803 /* 8804 * When going down, decrement the number of cores with SMT present. 8805 */ 8806 sched_smt_present_dec(cpu); 8807 8808 sched_core_cpu_deactivate(cpu); 8809 8810 if (!sched_smp_initialized) 8811 return 0; 8812 8813 sched_update_numa(cpu, false); 8814 cpuset_cpu_inactive(cpu); 8815 sched_domains_numa_masks_clear(cpu); 8816 return 0; 8817 } 8818 8819 static void sched_rq_cpu_starting(unsigned int cpu) 8820 { 8821 struct rq *rq = cpu_rq(cpu); 8822 8823 rq->calc_load_update = calc_load_update; 8824 update_max_interval(); 8825 } 8826 8827 int sched_cpu_starting(unsigned int cpu) 8828 { 8829 sched_core_cpu_starting(cpu); 8830 sched_rq_cpu_starting(cpu); 8831 sched_tick_start(cpu); 8832 return 0; 8833 } 8834 8835 #ifdef CONFIG_HOTPLUG_CPU 8836 8837 /* 8838 * Invoked immediately before the stopper thread is invoked to bring the 8839 * CPU down completely. At this point all per CPU kthreads except the 8840 * hotplug thread (current) and the stopper thread (inactive) have been 8841 * either parked or have been unbound from the outgoing CPU. Ensure that 8842 * any of those which might be on the way out are gone. 8843 * 8844 * If after this point a bound task is being woken on this CPU then the 8845 * responsible hotplug callback has failed to do it's job. 8846 * sched_cpu_dying() will catch it with the appropriate fireworks. 8847 */ 8848 int sched_cpu_wait_empty(unsigned int cpu) 8849 { 8850 balance_hotplug_wait(); 8851 sched_force_init_mm(); 8852 return 0; 8853 } 8854 8855 /* 8856 * Since this CPU is going 'away' for a while, fold any nr_active delta we 8857 * might have. Called from the CPU stopper task after ensuring that the 8858 * stopper is the last running task on the CPU, so nr_active count is 8859 * stable. We need to take the tear-down thread which is calling this into 8860 * account, so we hand in adjust = 1 to the load calculation. 8861 * 8862 * Also see the comment "Global load-average calculations". 8863 */ 8864 static void calc_load_migrate(struct rq *rq) 8865 { 8866 long delta = calc_load_fold_active(rq, 1); 8867 8868 if (delta) 8869 atomic_long_add(delta, &calc_load_tasks); 8870 } 8871 8872 static void dump_rq_tasks(struct rq *rq, const char *loglvl) 8873 { 8874 struct task_struct *g, *p; 8875 int cpu = cpu_of(rq); 8876 8877 lockdep_assert_rq_held(rq); 8878 8879 printk("%sCPU%d enqueued tasks (%u total):\n", loglvl, cpu, rq->nr_running); 8880 for_each_process_thread(g, p) { 8881 if (task_cpu(p) != cpu) 8882 continue; 8883 8884 if (!task_on_rq_queued(p)) 8885 continue; 8886 8887 printk("%s\tpid: %d, name: %s\n", loglvl, p->pid, p->comm); 8888 } 8889 } 8890 8891 int sched_cpu_dying(unsigned int cpu) 8892 { 8893 struct rq *rq = cpu_rq(cpu); 8894 struct rq_flags rf; 8895 8896 /* Handle pending wakeups and then migrate everything off */ 8897 sched_tick_stop(cpu); 8898 8899 rq_lock_irqsave(rq, &rf); 8900 update_rq_clock(rq); 8901 if (rq->nr_running != 1 || rq_has_pinned_tasks(rq)) { 8902 WARN(true, "Dying CPU not properly vacated!"); 8903 dump_rq_tasks(rq, KERN_WARNING); 8904 } 8905 dl_server_stop(&rq->fair_server); 8906 #ifdef CONFIG_SCHED_CLASS_EXT 8907 dl_server_stop(&rq->ext_server); 8908 #endif 8909 rq_unlock_irqrestore(rq, &rf); 8910 8911 calc_load_migrate(rq); 8912 update_max_interval(); 8913 hrtick_clear(rq); 8914 sched_core_cpu_dying(cpu); 8915 return 0; 8916 } 8917 #endif /* CONFIG_HOTPLUG_CPU */ 8918 8919 void __init sched_init_smp(void) 8920 { 8921 sched_init_numa(NUMA_NO_NODE); 8922 8923 prandom_init_once(&sched_rnd_state); 8924 8925 /* 8926 * There's no userspace yet to cause hotplug operations; hence all the 8927 * CPU masks are stable and all blatant races in the below code cannot 8928 * happen. 8929 */ 8930 sched_domains_mutex_lock(); 8931 sched_init_domains(cpu_active_mask); 8932 sched_domains_mutex_unlock(); 8933 8934 /* Move init over to a non-isolated CPU */ 8935 if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_TYPE_DOMAIN)) < 0) 8936 BUG(); 8937 current->flags &= ~PF_NO_SETAFFINITY; 8938 sched_init_granularity(); 8939 8940 init_sched_rt_class(); 8941 init_sched_dl_class(); 8942 8943 sched_init_dl_servers(); 8944 8945 sched_smp_initialized = true; 8946 } 8947 8948 static int __init migration_init(void) 8949 { 8950 sched_cpu_starting(smp_processor_id()); 8951 return 0; 8952 } 8953 early_initcall(migration_init); 8954 8955 int in_sched_functions(unsigned long addr) 8956 { 8957 return in_lock_functions(addr) || 8958 (addr >= (unsigned long)__sched_text_start 8959 && addr < (unsigned long)__sched_text_end); 8960 } 8961 8962 #ifdef CONFIG_CGROUP_SCHED 8963 /* 8964 * Default task group. 8965 * Every task in system belongs to this group at bootup. 8966 */ 8967 struct task_group root_task_group; 8968 LIST_HEAD(task_groups); 8969 8970 /* Cacheline aligned slab cache for task_group */ 8971 static struct kmem_cache *task_group_cache __ro_after_init; 8972 #endif 8973 8974 void __init sched_init(void) 8975 { 8976 unsigned long __maybe_unused ptr = 0; 8977 int i; 8978 8979 /* Make sure the linker didn't screw up */ 8980 BUG_ON(!sched_class_above(&stop_sched_class, &dl_sched_class)); 8981 BUG_ON(!sched_class_above(&dl_sched_class, &rt_sched_class)); 8982 BUG_ON(!sched_class_above(&rt_sched_class, &fair_sched_class)); 8983 BUG_ON(!sched_class_above(&fair_sched_class, &idle_sched_class)); 8984 #ifdef CONFIG_SCHED_CLASS_EXT 8985 BUG_ON(!sched_class_above(&fair_sched_class, &ext_sched_class)); 8986 BUG_ON(!sched_class_above(&ext_sched_class, &idle_sched_class)); 8987 #endif 8988 8989 wait_bit_init(); 8990 8991 #ifdef CONFIG_FAIR_GROUP_SCHED 8992 root_task_group.cfs_rq = &runqueues.cfs; 8993 8994 root_task_group.shares = ROOT_TASK_GROUP_LOAD; 8995 init_cfs_bandwidth(&root_task_group.cfs_bandwidth, NULL); 8996 #endif /* CONFIG_FAIR_GROUP_SCHED */ 8997 #ifdef CONFIG_EXT_GROUP_SCHED 8998 scx_tg_init(&root_task_group); 8999 #endif /* CONFIG_EXT_GROUP_SCHED */ 9000 #ifdef CONFIG_RT_GROUP_SCHED 9001 ptr += 2 * nr_cpu_ids * sizeof(void **); 9002 ptr = (unsigned long)kzalloc(ptr, GFP_NOWAIT); 9003 root_task_group.rt_se = (struct sched_rt_entity **)ptr; 9004 ptr += nr_cpu_ids * sizeof(void **); 9005 9006 root_task_group.rt_rq = (struct rt_rq **)ptr; 9007 ptr += nr_cpu_ids * sizeof(void **); 9008 9009 #endif /* CONFIG_RT_GROUP_SCHED */ 9010 9011 init_defrootdomain(); 9012 9013 #ifdef CONFIG_RT_GROUP_SCHED 9014 init_rt_bandwidth(&root_task_group.rt_bandwidth, 9015 global_rt_period(), global_rt_runtime()); 9016 #endif /* CONFIG_RT_GROUP_SCHED */ 9017 9018 #ifdef CONFIG_CGROUP_SCHED 9019 task_group_cache = KMEM_CACHE(task_group, 0); 9020 9021 list_add(&root_task_group.list, &task_groups); 9022 INIT_LIST_HEAD(&root_task_group.children); 9023 INIT_LIST_HEAD(&root_task_group.siblings); 9024 autogroup_init(&init_task); 9025 #endif /* CONFIG_CGROUP_SCHED */ 9026 9027 for_each_possible_cpu(i) { 9028 struct rq *rq; 9029 9030 rq = cpu_rq(i); 9031 raw_spin_lock_init(&rq->__lock); 9032 rq->nr_running = 0; 9033 rq->calc_load_active = 0; 9034 rq->calc_load_update = jiffies + LOAD_FREQ; 9035 init_cfs_rq(&rq->cfs); 9036 init_rt_rq(&rq->rt); 9037 init_dl_rq(&rq->dl); 9038 #ifdef CONFIG_FAIR_GROUP_SCHED 9039 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list); 9040 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list; 9041 /* 9042 * How much CPU bandwidth does root_task_group get? 9043 * 9044 * In case of task-groups formed through the cgroup filesystem, it 9045 * gets 100% of the CPU resources in the system. This overall 9046 * system CPU resource is divided among the tasks of 9047 * root_task_group and its child task-groups in a fair manner, 9048 * based on each entity's (task or task-group's) weight 9049 * (se->load.weight). 9050 * 9051 * In other words, if root_task_group has 10 tasks of weight 9052 * 1024) and two child groups A0 and A1 (of weight 1024 each), 9053 * then A0's share of the CPU resource is: 9054 * 9055 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33% 9056 * 9057 * We achieve this by letting root_task_group's tasks sit 9058 * directly in rq->cfs (i.e root_task_group->se[] = NULL). 9059 */ 9060 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL); 9061 #endif /* CONFIG_FAIR_GROUP_SCHED */ 9062 9063 #ifdef CONFIG_RT_GROUP_SCHED 9064 /* 9065 * This is required for init cpu because rt.c:__enable_runtime() 9066 * starts working after scheduler_running, which is not the case 9067 * yet. 9068 */ 9069 rq->rt.rt_runtime = global_rt_runtime(); 9070 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL); 9071 #endif 9072 rq->next_class = &idle_sched_class; 9073 9074 rq->sd = NULL; 9075 rq->rd = NULL; 9076 rq->cpu_capacity = SCHED_CAPACITY_SCALE; 9077 rq->balance_callback = &balance_push_callback; 9078 rq->active_balance = 0; 9079 rq->next_balance = jiffies; 9080 rq->push_cpu = 0; 9081 rq->cpu = i; 9082 rq->online = 0; 9083 rq->idle_stamp = 0; 9084 rq->avg_idle = 2*sysctl_sched_migration_cost; 9085 rq->max_idle_balance_cost = sysctl_sched_migration_cost; 9086 9087 INIT_LIST_HEAD(&rq->cfs_tasks); 9088 9089 rq_attach_root(rq, &def_root_domain); 9090 #ifdef CONFIG_NO_HZ_COMMON 9091 rq->last_blocked_load_update_tick = jiffies; 9092 atomic_set(&rq->nohz_flags, 0); 9093 9094 INIT_CSD(&rq->nohz_csd, nohz_csd_func, rq); 9095 #endif 9096 #ifdef CONFIG_HOTPLUG_CPU 9097 rcuwait_init(&rq->hotplug_wait); 9098 #endif 9099 hrtick_rq_init(rq); 9100 atomic_set(&rq->nr_iowait, 0); 9101 fair_server_init(rq); 9102 #ifdef CONFIG_SCHED_CLASS_EXT 9103 ext_server_init(rq); 9104 #endif 9105 9106 #ifdef CONFIG_SCHED_CORE 9107 rq->core = rq; 9108 rq->core_pick = NULL; 9109 rq->core_dl_server = NULL; 9110 rq->core_enabled = 0; 9111 rq->core_tree = RB_ROOT; 9112 rq->core_forceidle_count = 0; 9113 rq->core_forceidle_occupation = 0; 9114 rq->core_forceidle_start = 0; 9115 rq->core_pick_in_flight = 0; 9116 9117 rq->core_cookie = 0UL; 9118 #endif 9119 #ifdef CONFIG_SCHED_CACHE 9120 raw_spin_lock_init(&rq->cpu_epoch_lock); 9121 rq->cpu_epoch_next = jiffies; 9122 #endif 9123 9124 zalloc_cpumask_var_node(&rq->scratch_mask, GFP_KERNEL, cpu_to_node(i)); 9125 } 9126 9127 set_load_weight(&init_task, false); 9128 init_task.se.slice = sysctl_sched_base_slice, 9129 9130 /* 9131 * The boot idle thread does lazy MMU switching as well: 9132 */ 9133 mmgrab_lazy_tlb(&init_mm); 9134 enter_lazy_tlb(&init_mm, current); 9135 9136 /* 9137 * The idle task doesn't need the kthread struct to function, but it 9138 * is dressed up as a per-CPU kthread and thus needs to play the part 9139 * if we want to avoid special-casing it in code that deals with per-CPU 9140 * kthreads. 9141 */ 9142 WARN_ON(!set_kthread_struct(current)); 9143 9144 /* 9145 * Make us the idle thread. Technically, schedule() should not be 9146 * called from this thread, however somewhere below it might be, 9147 * but because we are the idle thread, we just pick up running again 9148 * when this runqueue becomes "idle". 9149 */ 9150 __sched_fork(0, current); 9151 init_idle(current, smp_processor_id()); 9152 9153 calc_load_update = jiffies + LOAD_FREQ; 9154 9155 idle_thread_set_boot_cpu(); 9156 9157 balance_push_set(smp_processor_id(), false); 9158 init_sched_fair_class(); 9159 init_sched_ext_class(); 9160 9161 psi_init(); 9162 9163 init_uclamp(); 9164 9165 preempt_dynamic_init(); 9166 9167 scheduler_running = 1; 9168 } 9169 9170 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP 9171 9172 void __might_sleep(const char *file, int line) 9173 { 9174 unsigned int state = get_current_state(); 9175 /* 9176 * Blocking primitives will set (and therefore destroy) current->state, 9177 * since we will exit with TASK_RUNNING make sure we enter with it, 9178 * otherwise we will destroy state. 9179 */ 9180 WARN_ONCE(state != TASK_RUNNING && current->task_state_change, 9181 "do not call blocking ops when !TASK_RUNNING; " 9182 "state=%x set at [<%p>] %pS\n", state, 9183 (void *)current->task_state_change, 9184 (void *)current->task_state_change); 9185 9186 __might_resched(file, line, 0); 9187 } 9188 EXPORT_SYMBOL(__might_sleep); 9189 9190 static void print_preempt_disable_ip(int preempt_offset, unsigned long ip) 9191 { 9192 if (!IS_ENABLED(CONFIG_DEBUG_PREEMPT)) 9193 return; 9194 9195 if (preempt_count() == preempt_offset) 9196 return; 9197 9198 pr_err("Preemption disabled at:"); 9199 print_ip_sym(KERN_ERR, ip); 9200 } 9201 9202 static inline bool resched_offsets_ok(unsigned int offsets) 9203 { 9204 unsigned int nested = preempt_count(); 9205 9206 nested += rcu_preempt_depth() << MIGHT_RESCHED_RCU_SHIFT; 9207 9208 return nested == offsets; 9209 } 9210 9211 void __might_resched(const char *file, int line, unsigned int offsets) 9212 { 9213 /* Ratelimiting timestamp: */ 9214 static unsigned long prev_jiffy; 9215 9216 unsigned long preempt_disable_ip; 9217 9218 /* WARN_ON_ONCE() by default, no rate limit required: */ 9219 rcu_sleep_check(); 9220 9221 if ((resched_offsets_ok(offsets) && !irqs_disabled() && 9222 !is_idle_task(current) && !current->non_block_count) || 9223 system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING || 9224 oops_in_progress) 9225 return; 9226 9227 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy) 9228 return; 9229 prev_jiffy = jiffies; 9230 9231 /* Save this before calling printk(), since that will clobber it: */ 9232 preempt_disable_ip = get_preempt_disable_ip(current); 9233 9234 pr_err("BUG: sleeping function called from invalid context at %s:%d\n", 9235 file, line); 9236 pr_err("in_atomic(): %d, irqs_disabled(): %d, non_block: %d, pid: %d, name: %s\n", 9237 in_atomic(), irqs_disabled(), current->non_block_count, 9238 current->pid, current->comm); 9239 pr_err("preempt_count: %x, expected: %x\n", preempt_count(), 9240 offsets & MIGHT_RESCHED_PREEMPT_MASK); 9241 9242 if (IS_ENABLED(CONFIG_PREEMPT_RCU)) { 9243 pr_err("RCU nest depth: %d, expected: %u\n", 9244 rcu_preempt_depth(), offsets >> MIGHT_RESCHED_RCU_SHIFT); 9245 } 9246 9247 if (task_stack_end_corrupted(current)) 9248 pr_emerg("Thread overran stack, or stack corrupted\n"); 9249 9250 debug_show_held_locks(current); 9251 if (irqs_disabled()) 9252 print_irqtrace_events(current); 9253 9254 print_preempt_disable_ip(offsets & MIGHT_RESCHED_PREEMPT_MASK, 9255 preempt_disable_ip); 9256 9257 dump_stack(); 9258 add_taint(TAINT_WARN, LOCKDEP_STILL_OK); 9259 } 9260 EXPORT_SYMBOL(__might_resched); 9261 9262 void __cant_sleep(const char *file, int line) 9263 { 9264 static unsigned long prev_jiffy; 9265 9266 if (irqs_disabled()) 9267 return; 9268 9269 if (!IS_ENABLED(CONFIG_PREEMPT_COUNT)) 9270 return; 9271 9272 if (preempt_count()) 9273 return; 9274 9275 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy) 9276 return; 9277 prev_jiffy = jiffies; 9278 9279 printk(KERN_ERR "BUG: assuming atomic context at %s:%d\n", file, line); 9280 printk(KERN_ERR "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n", 9281 in_atomic(), irqs_disabled(), 9282 current->pid, current->comm); 9283 9284 debug_show_held_locks(current); 9285 dump_stack(); 9286 add_taint(TAINT_WARN, LOCKDEP_STILL_OK); 9287 } 9288 EXPORT_SYMBOL_GPL(__cant_sleep); 9289 9290 # ifdef CONFIG_SMP 9291 void __cant_migrate(const char *file, int line) 9292 { 9293 static unsigned long prev_jiffy; 9294 9295 if (irqs_disabled()) 9296 return; 9297 9298 if (is_migration_disabled(current)) 9299 return; 9300 9301 if (!IS_ENABLED(CONFIG_PREEMPT_COUNT)) 9302 return; 9303 9304 if (preempt_count()) 9305 return; 9306 9307 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy) 9308 return; 9309 prev_jiffy = jiffies; 9310 9311 pr_err("BUG: assuming non migratable context at %s:%d\n", file, line); 9312 pr_err("in_atomic(): %d, irqs_disabled(): %d, migration_disabled() %u pid: %d, name: %s\n", 9313 in_atomic(), irqs_disabled(), is_migration_disabled(current), 9314 current->pid, current->comm); 9315 9316 debug_show_held_locks(current); 9317 dump_stack(); 9318 add_taint(TAINT_WARN, LOCKDEP_STILL_OK); 9319 } 9320 EXPORT_SYMBOL_GPL(__cant_migrate); 9321 # endif /* CONFIG_SMP */ 9322 #endif /* CONFIG_DEBUG_ATOMIC_SLEEP */ 9323 9324 #ifdef CONFIG_MAGIC_SYSRQ 9325 void normalize_rt_tasks(void) 9326 { 9327 struct task_struct *g, *p; 9328 struct sched_attr attr = { 9329 .sched_policy = SCHED_NORMAL, 9330 }; 9331 9332 read_lock(&tasklist_lock); 9333 for_each_process_thread(g, p) { 9334 /* 9335 * Only normalize user tasks: 9336 */ 9337 if (p->flags & PF_KTHREAD) 9338 continue; 9339 9340 p->se.exec_start = 0; 9341 schedstat_set(p->stats.wait_start, 0); 9342 schedstat_set(p->stats.sleep_start, 0); 9343 schedstat_set(p->stats.block_start, 0); 9344 9345 if (!rt_or_dl_task(p)) { 9346 /* 9347 * Renice negative nice level userspace 9348 * tasks back to 0: 9349 */ 9350 if (task_nice(p) < 0) 9351 set_user_nice(p, 0); 9352 continue; 9353 } 9354 9355 __sched_setscheduler(p, &attr, false, false); 9356 } 9357 read_unlock(&tasklist_lock); 9358 } 9359 9360 #endif /* CONFIG_MAGIC_SYSRQ */ 9361 9362 #ifdef CONFIG_KGDB_KDB 9363 /* 9364 * These functions are only useful for KDB. 9365 * 9366 * They can only be called when the whole system has been 9367 * stopped - every CPU needs to be quiescent, and no scheduling 9368 * activity can take place. Using them for anything else would 9369 * be a serious bug, and as a result, they aren't even visible 9370 * under any other configuration. 9371 */ 9372 9373 /** 9374 * curr_task - return the current task for a given CPU. 9375 * @cpu: the processor in question. 9376 * 9377 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED! 9378 * 9379 * Return: The current task for @cpu. 9380 */ 9381 struct task_struct *curr_task(int cpu) 9382 { 9383 return cpu_curr(cpu); 9384 } 9385 9386 #endif /* CONFIG_KGDB_KDB */ 9387 9388 #ifdef CONFIG_CGROUP_SCHED 9389 /* task_group_lock serializes the addition/removal of task groups */ 9390 static DEFINE_SPINLOCK(task_group_lock); 9391 9392 static inline void alloc_uclamp_sched_group(struct task_group *tg, 9393 struct task_group *parent) 9394 { 9395 #ifdef CONFIG_UCLAMP_TASK_GROUP 9396 enum uclamp_id clamp_id; 9397 9398 for_each_clamp_id(clamp_id) { 9399 uclamp_se_set(&tg->uclamp_req[clamp_id], 9400 uclamp_none(clamp_id), false); 9401 tg->uclamp[clamp_id] = parent->uclamp[clamp_id]; 9402 } 9403 #endif 9404 } 9405 9406 static void sched_free_group(struct task_group *tg) 9407 { 9408 free_fair_sched_group(tg); 9409 free_rt_sched_group(tg); 9410 autogroup_free(tg); 9411 kmem_cache_free(task_group_cache, tg); 9412 } 9413 9414 static void sched_free_group_rcu(struct rcu_head *rcu) 9415 { 9416 sched_free_group(container_of(rcu, struct task_group, rcu)); 9417 } 9418 9419 static void sched_unregister_group(struct task_group *tg) 9420 { 9421 unregister_fair_sched_group(tg); 9422 unregister_rt_sched_group(tg); 9423 /* 9424 * We have to wait for yet another RCU grace period to expire, as 9425 * print_cfs_stats() might run concurrently. 9426 */ 9427 call_rcu(&tg->rcu, sched_free_group_rcu); 9428 } 9429 9430 /* allocate runqueue etc for a new task group */ 9431 struct task_group *sched_create_group(struct task_group *parent) 9432 { 9433 struct task_group *tg; 9434 9435 tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO); 9436 if (!tg) 9437 return ERR_PTR(-ENOMEM); 9438 9439 if (!alloc_fair_sched_group(tg, parent)) 9440 goto err; 9441 9442 if (!alloc_rt_sched_group(tg, parent)) 9443 goto err; 9444 9445 scx_tg_init(tg); 9446 alloc_uclamp_sched_group(tg, parent); 9447 9448 return tg; 9449 9450 err: 9451 sched_free_group(tg); 9452 return ERR_PTR(-ENOMEM); 9453 } 9454 9455 void sched_online_group(struct task_group *tg, struct task_group *parent) 9456 { 9457 unsigned long flags; 9458 9459 spin_lock_irqsave(&task_group_lock, flags); 9460 list_add_tail_rcu(&tg->list, &task_groups); 9461 9462 /* Root should already exist: */ 9463 WARN_ON(!parent); 9464 9465 tg->parent = parent; 9466 INIT_LIST_HEAD(&tg->children); 9467 list_add_rcu(&tg->siblings, &parent->children); 9468 spin_unlock_irqrestore(&task_group_lock, flags); 9469 9470 online_fair_sched_group(tg); 9471 } 9472 9473 /* RCU callback to free various structures associated with a task group */ 9474 static void sched_unregister_group_rcu(struct rcu_head *rhp) 9475 { 9476 /* Now it should be safe to free those cfs_rqs: */ 9477 sched_unregister_group(container_of(rhp, struct task_group, rcu)); 9478 } 9479 9480 void sched_destroy_group(struct task_group *tg) 9481 { 9482 /* Wait for possible concurrent references to cfs_rqs complete: */ 9483 call_rcu(&tg->rcu, sched_unregister_group_rcu); 9484 } 9485 9486 void sched_release_group(struct task_group *tg) 9487 { 9488 unsigned long flags; 9489 9490 /* 9491 * Unlink first, to avoid walk_tg_tree_from() from finding us (via 9492 * sched_cfs_period_timer()). 9493 * 9494 * For this to be effective, we have to wait for all pending users of 9495 * this task group to leave their RCU critical section to ensure no new 9496 * user will see our dying task group any more. Specifically ensure 9497 * that tg_unthrottle_up() won't add decayed cfs_rq's to it. 9498 * 9499 * We therefore defer calling unregister_fair_sched_group() to 9500 * sched_unregister_group() which is guarantied to get called only after the 9501 * current RCU grace period has expired. 9502 */ 9503 spin_lock_irqsave(&task_group_lock, flags); 9504 list_del_rcu(&tg->list); 9505 list_del_rcu(&tg->siblings); 9506 spin_unlock_irqrestore(&task_group_lock, flags); 9507 } 9508 9509 static void sched_change_group(struct task_struct *tsk) 9510 { 9511 struct task_group *tg; 9512 9513 /* 9514 * All callers are synchronized by task_rq_lock(); we do not use RCU 9515 * which is pointless here. Thus, we pass "true" to task_css_check() 9516 * to prevent lockdep warnings. 9517 */ 9518 tg = container_of(task_css_check(tsk, cpu_cgrp_id, true), 9519 struct task_group, css); 9520 tg = autogroup_task_group(tsk, tg); 9521 tsk->sched_task_group = tg; 9522 9523 #ifdef CONFIG_FAIR_GROUP_SCHED 9524 if (tsk->sched_class->task_change_group) 9525 tsk->sched_class->task_change_group(tsk); 9526 else 9527 #endif 9528 set_task_rq(tsk, task_cpu(tsk)); 9529 } 9530 9531 /* 9532 * Change task's runqueue when it moves between groups. 9533 * 9534 * The caller of this function should have put the task in its new group by 9535 * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect 9536 * its new group. 9537 */ 9538 void sched_move_task(struct task_struct *tsk, bool for_autogroup) 9539 { 9540 unsigned int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE; 9541 bool resched = false; 9542 bool queued = false; 9543 struct rq *rq; 9544 9545 CLASS(task_rq_lock, rq_guard)(tsk); 9546 rq = rq_guard.rq; 9547 9548 scoped_guard (sched_change, tsk, queue_flags) { 9549 sched_change_group(tsk); 9550 if (!for_autogroup) 9551 scx_cgroup_move_task(tsk); 9552 if (scope->running) 9553 resched = true; 9554 queued = scope->queued; 9555 } 9556 9557 if (resched) 9558 resched_curr(rq); 9559 else if (queued) 9560 wakeup_preempt(rq, tsk, 0); 9561 9562 __balance_callbacks(rq, &rq_guard.rf); 9563 } 9564 9565 static struct cgroup_subsys_state * 9566 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css) 9567 { 9568 struct task_group *parent = css_tg(parent_css); 9569 struct task_group *tg; 9570 9571 if (!parent) { 9572 /* This is early initialization for the top cgroup */ 9573 return &root_task_group.css; 9574 } 9575 9576 tg = sched_create_group(parent); 9577 if (IS_ERR(tg)) 9578 return ERR_PTR(-ENOMEM); 9579 9580 return &tg->css; 9581 } 9582 9583 /* Expose task group only after completing cgroup initialization */ 9584 static int cpu_cgroup_css_online(struct cgroup_subsys_state *css) 9585 { 9586 struct task_group *tg = css_tg(css); 9587 struct task_group *parent = css_tg(css->parent); 9588 int ret; 9589 9590 ret = scx_tg_online(tg); 9591 if (ret) 9592 return ret; 9593 9594 if (parent) 9595 sched_online_group(tg, parent); 9596 9597 #ifdef CONFIG_UCLAMP_TASK_GROUP 9598 /* Propagate the effective uclamp value for the new group */ 9599 guard(mutex)(&uclamp_mutex); 9600 guard(rcu)(); 9601 cpu_util_update_eff(css); 9602 #endif 9603 9604 return 0; 9605 } 9606 9607 static void cpu_cgroup_css_offline(struct cgroup_subsys_state *css) 9608 { 9609 struct task_group *tg = css_tg(css); 9610 9611 scx_tg_offline(tg); 9612 } 9613 9614 static void cpu_cgroup_css_released(struct cgroup_subsys_state *css) 9615 { 9616 struct task_group *tg = css_tg(css); 9617 9618 sched_release_group(tg); 9619 } 9620 9621 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css) 9622 { 9623 struct task_group *tg = css_tg(css); 9624 9625 /* 9626 * Relies on the RCU grace period between css_released() and this. 9627 */ 9628 sched_unregister_group(tg); 9629 } 9630 9631 static int cpu_cgroup_can_attach(struct cgroup_taskset *tset) 9632 { 9633 #ifdef CONFIG_RT_GROUP_SCHED 9634 struct task_struct *task; 9635 struct cgroup_subsys_state *css; 9636 9637 if (!rt_group_sched_enabled()) 9638 goto scx_check; 9639 9640 cgroup_taskset_for_each(task, css, tset) { 9641 if (!sched_rt_can_attach(css_tg(css), task)) 9642 return -EINVAL; 9643 } 9644 scx_check: 9645 #endif /* CONFIG_RT_GROUP_SCHED */ 9646 return scx_cgroup_can_attach(tset); 9647 } 9648 9649 static void cpu_cgroup_attach(struct cgroup_taskset *tset) 9650 { 9651 struct task_struct *task; 9652 struct cgroup_subsys_state *css; 9653 9654 cgroup_taskset_for_each(task, css, tset) 9655 sched_move_task(task, false); 9656 } 9657 9658 static void cpu_cgroup_cancel_attach(struct cgroup_taskset *tset) 9659 { 9660 scx_cgroup_cancel_attach(tset); 9661 } 9662 9663 #ifdef CONFIG_UCLAMP_TASK_GROUP 9664 static void cpu_util_update_eff(struct cgroup_subsys_state *css) 9665 { 9666 struct cgroup_subsys_state *top_css = css; 9667 struct uclamp_se *uc_parent = NULL; 9668 struct uclamp_se *uc_se = NULL; 9669 unsigned int eff[UCLAMP_CNT]; 9670 enum uclamp_id clamp_id; 9671 unsigned int clamps; 9672 9673 lockdep_assert_held(&uclamp_mutex); 9674 WARN_ON_ONCE(!rcu_read_lock_held()); 9675 9676 css_for_each_descendant_pre(css, top_css) { 9677 uc_parent = css_tg(css)->parent 9678 ? css_tg(css)->parent->uclamp : NULL; 9679 9680 for_each_clamp_id(clamp_id) { 9681 /* Assume effective clamps matches requested clamps */ 9682 eff[clamp_id] = css_tg(css)->uclamp_req[clamp_id].value; 9683 /* Cap effective clamps with parent's effective clamps */ 9684 if (uc_parent && 9685 eff[clamp_id] > uc_parent[clamp_id].value) { 9686 eff[clamp_id] = uc_parent[clamp_id].value; 9687 } 9688 } 9689 /* Ensure protection is always capped by limit */ 9690 eff[UCLAMP_MIN] = min(eff[UCLAMP_MIN], eff[UCLAMP_MAX]); 9691 9692 /* Propagate most restrictive effective clamps */ 9693 clamps = 0x0; 9694 uc_se = css_tg(css)->uclamp; 9695 for_each_clamp_id(clamp_id) { 9696 if (eff[clamp_id] == uc_se[clamp_id].value) 9697 continue; 9698 uc_se[clamp_id].value = eff[clamp_id]; 9699 uc_se[clamp_id].bucket_id = uclamp_bucket_id(eff[clamp_id]); 9700 clamps |= (0x1 << clamp_id); 9701 } 9702 if (!clamps) { 9703 css = css_rightmost_descendant(css); 9704 continue; 9705 } 9706 9707 /* Immediately update descendants RUNNABLE tasks */ 9708 uclamp_update_active_tasks(css); 9709 } 9710 } 9711 9712 /* 9713 * Integer 10^N with a given N exponent by casting to integer the literal "1eN" 9714 * C expression. Since there is no way to convert a macro argument (N) into a 9715 * character constant, use two levels of macros. 9716 */ 9717 #define _POW10(exp) ((unsigned int)1e##exp) 9718 #define POW10(exp) _POW10(exp) 9719 9720 struct uclamp_request { 9721 #define UCLAMP_PERCENT_SHIFT 2 9722 #define UCLAMP_PERCENT_SCALE (100 * POW10(UCLAMP_PERCENT_SHIFT)) 9723 s64 percent; 9724 u64 util; 9725 int ret; 9726 }; 9727 9728 static inline struct uclamp_request 9729 capacity_from_percent(char *buf) 9730 { 9731 struct uclamp_request req = { 9732 .percent = UCLAMP_PERCENT_SCALE, 9733 .util = SCHED_CAPACITY_SCALE, 9734 .ret = 0, 9735 }; 9736 9737 buf = strim(buf); 9738 if (strcmp(buf, "max")) { 9739 req.ret = cgroup_parse_float(buf, UCLAMP_PERCENT_SHIFT, 9740 &req.percent); 9741 if (req.ret) 9742 return req; 9743 if ((u64)req.percent > UCLAMP_PERCENT_SCALE) { 9744 req.ret = -ERANGE; 9745 return req; 9746 } 9747 9748 req.util = req.percent << SCHED_CAPACITY_SHIFT; 9749 req.util = DIV_ROUND_CLOSEST_ULL(req.util, UCLAMP_PERCENT_SCALE); 9750 } 9751 9752 return req; 9753 } 9754 9755 static ssize_t cpu_uclamp_write(struct kernfs_open_file *of, char *buf, 9756 size_t nbytes, loff_t off, 9757 enum uclamp_id clamp_id) 9758 { 9759 struct uclamp_request req; 9760 struct task_group *tg; 9761 9762 req = capacity_from_percent(buf); 9763 if (req.ret) 9764 return req.ret; 9765 9766 sched_uclamp_enable(); 9767 9768 guard(mutex)(&uclamp_mutex); 9769 guard(rcu)(); 9770 9771 tg = css_tg(of_css(of)); 9772 if (tg->uclamp_req[clamp_id].value != req.util) 9773 uclamp_se_set(&tg->uclamp_req[clamp_id], req.util, false); 9774 9775 /* 9776 * Because of not recoverable conversion rounding we keep track of the 9777 * exact requested value 9778 */ 9779 tg->uclamp_pct[clamp_id] = req.percent; 9780 9781 /* Update effective clamps to track the most restrictive value */ 9782 cpu_util_update_eff(of_css(of)); 9783 9784 return nbytes; 9785 } 9786 9787 static ssize_t cpu_uclamp_min_write(struct kernfs_open_file *of, 9788 char *buf, size_t nbytes, 9789 loff_t off) 9790 { 9791 return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MIN); 9792 } 9793 9794 static ssize_t cpu_uclamp_max_write(struct kernfs_open_file *of, 9795 char *buf, size_t nbytes, 9796 loff_t off) 9797 { 9798 return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MAX); 9799 } 9800 9801 static inline void cpu_uclamp_print(struct seq_file *sf, 9802 enum uclamp_id clamp_id) 9803 { 9804 struct task_group *tg; 9805 u64 util_clamp; 9806 u64 percent; 9807 u32 rem; 9808 9809 scoped_guard (rcu) { 9810 tg = css_tg(seq_css(sf)); 9811 util_clamp = tg->uclamp_req[clamp_id].value; 9812 } 9813 9814 if (util_clamp == SCHED_CAPACITY_SCALE) { 9815 seq_puts(sf, "max\n"); 9816 return; 9817 } 9818 9819 percent = tg->uclamp_pct[clamp_id]; 9820 percent = div_u64_rem(percent, POW10(UCLAMP_PERCENT_SHIFT), &rem); 9821 seq_printf(sf, "%llu.%0*u\n", percent, UCLAMP_PERCENT_SHIFT, rem); 9822 } 9823 9824 static int cpu_uclamp_min_show(struct seq_file *sf, void *v) 9825 { 9826 cpu_uclamp_print(sf, UCLAMP_MIN); 9827 return 0; 9828 } 9829 9830 static int cpu_uclamp_max_show(struct seq_file *sf, void *v) 9831 { 9832 cpu_uclamp_print(sf, UCLAMP_MAX); 9833 return 0; 9834 } 9835 #endif /* CONFIG_UCLAMP_TASK_GROUP */ 9836 9837 #ifdef CONFIG_GROUP_SCHED_WEIGHT 9838 static unsigned long tg_weight(struct task_group *tg) 9839 { 9840 #ifdef CONFIG_FAIR_GROUP_SCHED 9841 return scale_load_down(tg->shares); 9842 #else 9843 return sched_weight_from_cgroup(tg->scx.weight); 9844 #endif 9845 } 9846 9847 static int cpu_shares_write_u64(struct cgroup_subsys_state *css, 9848 struct cftype *cftype, u64 shareval) 9849 { 9850 int ret; 9851 9852 if (shareval > scale_load_down(ULONG_MAX)) 9853 shareval = MAX_SHARES; 9854 ret = sched_group_set_shares(css_tg(css), scale_load(shareval)); 9855 if (!ret) 9856 scx_group_set_weight(css_tg(css), 9857 sched_weight_to_cgroup(shareval)); 9858 return ret; 9859 } 9860 9861 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css, 9862 struct cftype *cft) 9863 { 9864 return tg_weight(css_tg(css)); 9865 } 9866 #endif /* CONFIG_GROUP_SCHED_WEIGHT */ 9867 9868 #ifdef CONFIG_CFS_BANDWIDTH 9869 static DEFINE_MUTEX(cfs_constraints_mutex); 9870 9871 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime); 9872 9873 static int tg_set_cfs_bandwidth(struct task_group *tg, 9874 u64 period_us, u64 quota_us, u64 burst_us) 9875 { 9876 int i, ret = 0, runtime_enabled, runtime_was_enabled; 9877 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; 9878 u64 period, quota, burst; 9879 9880 period = (u64)period_us * NSEC_PER_USEC; 9881 9882 if (quota_us == RUNTIME_INF) 9883 quota = RUNTIME_INF; 9884 else 9885 quota = (u64)quota_us * NSEC_PER_USEC; 9886 9887 burst = (u64)burst_us * NSEC_PER_USEC; 9888 9889 /* 9890 * Prevent race between setting of cfs_rq->runtime_enabled and 9891 * unthrottle_offline_cfs_rqs(). 9892 */ 9893 guard(cpus_read_lock)(); 9894 guard(mutex)(&cfs_constraints_mutex); 9895 9896 ret = __cfs_schedulable(tg, period, quota); 9897 if (ret) 9898 return ret; 9899 9900 runtime_enabled = quota != RUNTIME_INF; 9901 runtime_was_enabled = cfs_b->quota != RUNTIME_INF; 9902 /* 9903 * If we need to toggle cfs_bandwidth_used, off->on must occur 9904 * before making related changes, and on->off must occur afterwards 9905 */ 9906 if (runtime_enabled && !runtime_was_enabled) 9907 cfs_bandwidth_usage_inc(); 9908 9909 scoped_guard (raw_spinlock_irq, &cfs_b->lock) { 9910 cfs_b->period = ns_to_ktime(period); 9911 cfs_b->quota = quota; 9912 cfs_b->burst = burst; 9913 9914 __refill_cfs_bandwidth_runtime(cfs_b); 9915 9916 /* 9917 * Restart the period timer (if active) to handle new 9918 * period expiry: 9919 */ 9920 if (runtime_enabled) 9921 start_cfs_bandwidth(cfs_b); 9922 } 9923 9924 for_each_online_cpu(i) { 9925 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, i); 9926 struct rq *rq = cfs_rq->rq; 9927 9928 guard(rq_lock_irq)(rq); 9929 9930 cfs_rq->runtime_enabled = runtime_enabled; 9931 cfs_rq->runtime_remaining = 1; 9932 9933 if (cfs_rq->throttled) { 9934 update_rq_clock(rq); 9935 unthrottle_cfs_rq(cfs_rq); 9936 } 9937 } 9938 9939 if (runtime_was_enabled && !runtime_enabled) 9940 cfs_bandwidth_usage_dec(); 9941 9942 return 0; 9943 } 9944 9945 static u64 tg_get_cfs_period(struct task_group *tg) 9946 { 9947 u64 cfs_period_us; 9948 9949 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period); 9950 do_div(cfs_period_us, NSEC_PER_USEC); 9951 9952 return cfs_period_us; 9953 } 9954 9955 static u64 tg_get_cfs_quota(struct task_group *tg) 9956 { 9957 u64 quota_us; 9958 9959 if (tg->cfs_bandwidth.quota == RUNTIME_INF) 9960 return RUNTIME_INF; 9961 9962 quota_us = tg->cfs_bandwidth.quota; 9963 do_div(quota_us, NSEC_PER_USEC); 9964 9965 return quota_us; 9966 } 9967 9968 static u64 tg_get_cfs_burst(struct task_group *tg) 9969 { 9970 u64 burst_us; 9971 9972 burst_us = tg->cfs_bandwidth.burst; 9973 do_div(burst_us, NSEC_PER_USEC); 9974 9975 return burst_us; 9976 } 9977 9978 struct cfs_schedulable_data { 9979 struct task_group *tg; 9980 u64 period, quota; 9981 }; 9982 9983 /* 9984 * normalize group quota/period to be quota/max_period 9985 * note: units are usecs 9986 */ 9987 static u64 normalize_cfs_quota(struct task_group *tg, 9988 struct cfs_schedulable_data *d) 9989 { 9990 u64 quota, period; 9991 9992 if (tg == d->tg) { 9993 period = d->period; 9994 quota = d->quota; 9995 } else { 9996 period = tg_get_cfs_period(tg); 9997 quota = tg_get_cfs_quota(tg); 9998 } 9999 10000 /* note: these should typically be equivalent */ 10001 if (quota == RUNTIME_INF || quota == -1) 10002 return RUNTIME_INF; 10003 10004 return to_ratio(period, quota); 10005 } 10006 10007 static int tg_cfs_schedulable_down(struct task_group *tg, void *data) 10008 { 10009 struct cfs_schedulable_data *d = data; 10010 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; 10011 s64 quota = 0, parent_quota = -1; 10012 10013 if (!tg->parent) { 10014 quota = RUNTIME_INF; 10015 } else { 10016 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth; 10017 10018 quota = normalize_cfs_quota(tg, d); 10019 parent_quota = parent_b->hierarchical_quota; 10020 10021 /* 10022 * Ensure max(child_quota) <= parent_quota. On cgroup2, 10023 * always take the non-RUNTIME_INF min. On cgroup1, only 10024 * inherit when no limit is set. In both cases this is used 10025 * by the scheduler to determine if a given CFS task has a 10026 * bandwidth constraint at some higher level. 10027 */ 10028 if (cgroup_subsys_on_dfl(cpu_cgrp_subsys)) { 10029 if (quota == RUNTIME_INF) 10030 quota = parent_quota; 10031 else if (parent_quota != RUNTIME_INF) 10032 quota = min(quota, parent_quota); 10033 } else { 10034 if (quota == RUNTIME_INF) 10035 quota = parent_quota; 10036 else if (parent_quota != RUNTIME_INF && quota > parent_quota) 10037 return -EINVAL; 10038 } 10039 } 10040 cfs_b->hierarchical_quota = quota; 10041 10042 return 0; 10043 } 10044 10045 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota) 10046 { 10047 struct cfs_schedulable_data data = { 10048 .tg = tg, 10049 .period = period, 10050 .quota = quota, 10051 }; 10052 10053 if (quota != RUNTIME_INF) { 10054 do_div(data.period, NSEC_PER_USEC); 10055 do_div(data.quota, NSEC_PER_USEC); 10056 } 10057 10058 guard(rcu)(); 10059 return walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data); 10060 } 10061 10062 static int cpu_cfs_stat_show(struct seq_file *sf, void *v) 10063 { 10064 struct task_group *tg = css_tg(seq_css(sf)); 10065 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; 10066 10067 seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods); 10068 seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled); 10069 seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time); 10070 10071 if (schedstat_enabled() && tg != &root_task_group) { 10072 struct sched_statistics *stats; 10073 u64 ws = 0; 10074 int i; 10075 10076 for_each_possible_cpu(i) { 10077 stats = __schedstats_from_se(tg_se(tg, i)); 10078 ws += schedstat_val(stats->wait_sum); 10079 } 10080 10081 seq_printf(sf, "wait_sum %llu\n", ws); 10082 } 10083 10084 seq_printf(sf, "nr_bursts %d\n", cfs_b->nr_burst); 10085 seq_printf(sf, "burst_time %llu\n", cfs_b->burst_time); 10086 10087 return 0; 10088 } 10089 10090 static u64 throttled_time_self(struct task_group *tg) 10091 { 10092 int i; 10093 u64 total = 0; 10094 10095 for_each_possible_cpu(i) { 10096 total += READ_ONCE(tg_cfs_rq(tg, i)->throttled_clock_self_time); 10097 } 10098 10099 return total; 10100 } 10101 10102 static int cpu_cfs_local_stat_show(struct seq_file *sf, void *v) 10103 { 10104 struct task_group *tg = css_tg(seq_css(sf)); 10105 10106 seq_printf(sf, "throttled_time %llu\n", throttled_time_self(tg)); 10107 10108 return 0; 10109 } 10110 #endif /* CONFIG_CFS_BANDWIDTH */ 10111 10112 #ifdef CONFIG_GROUP_SCHED_BANDWIDTH 10113 const u64 max_bw_quota_period_us = 1 * USEC_PER_SEC; /* 1s */ 10114 static const u64 min_bw_quota_period_us = 1 * USEC_PER_MSEC; /* 1ms */ 10115 /* More than 203 days if BW_SHIFT equals 20. */ 10116 static const u64 max_bw_runtime_us = MAX_BW; 10117 10118 static void tg_bandwidth(struct task_group *tg, 10119 u64 *period_us_p, u64 *quota_us_p, u64 *burst_us_p) 10120 { 10121 #ifdef CONFIG_CFS_BANDWIDTH 10122 if (period_us_p) 10123 *period_us_p = tg_get_cfs_period(tg); 10124 if (quota_us_p) 10125 *quota_us_p = tg_get_cfs_quota(tg); 10126 if (burst_us_p) 10127 *burst_us_p = tg_get_cfs_burst(tg); 10128 #else /* !CONFIG_CFS_BANDWIDTH */ 10129 if (period_us_p) 10130 *period_us_p = tg->scx.bw_period_us; 10131 if (quota_us_p) 10132 *quota_us_p = tg->scx.bw_quota_us; 10133 if (burst_us_p) 10134 *burst_us_p = tg->scx.bw_burst_us; 10135 #endif /* CONFIG_CFS_BANDWIDTH */ 10136 } 10137 10138 static u64 cpu_period_read_u64(struct cgroup_subsys_state *css, 10139 struct cftype *cft) 10140 { 10141 u64 period_us; 10142 10143 tg_bandwidth(css_tg(css), &period_us, NULL, NULL); 10144 return period_us; 10145 } 10146 10147 static int tg_set_bandwidth(struct task_group *tg, 10148 u64 period_us, u64 quota_us, u64 burst_us) 10149 { 10150 const u64 max_usec = U64_MAX / NSEC_PER_USEC; 10151 int ret = 0; 10152 10153 if (tg == &root_task_group) 10154 return -EINVAL; 10155 10156 /* Values should survive translation to nsec */ 10157 if (period_us > max_usec || 10158 (quota_us != RUNTIME_INF && quota_us > max_usec) || 10159 burst_us > max_usec) 10160 return -EINVAL; 10161 10162 /* 10163 * Ensure we have some amount of bandwidth every period. This is to 10164 * prevent reaching a state of large arrears when throttled via 10165 * entity_tick() resulting in prolonged exit starvation. 10166 */ 10167 if (quota_us < min_bw_quota_period_us || 10168 period_us < min_bw_quota_period_us) 10169 return -EINVAL; 10170 10171 /* 10172 * Likewise, bound things on the other side by preventing insane quota 10173 * periods. This also allows us to normalize in computing quota 10174 * feasibility. 10175 */ 10176 if (period_us > max_bw_quota_period_us) 10177 return -EINVAL; 10178 10179 /* 10180 * Bound quota to defend quota against overflow during bandwidth shift. 10181 */ 10182 if (quota_us != RUNTIME_INF && quota_us > max_bw_runtime_us) 10183 return -EINVAL; 10184 10185 if (quota_us != RUNTIME_INF && (burst_us > quota_us || 10186 burst_us + quota_us > max_bw_runtime_us)) 10187 return -EINVAL; 10188 10189 #ifdef CONFIG_CFS_BANDWIDTH 10190 ret = tg_set_cfs_bandwidth(tg, period_us, quota_us, burst_us); 10191 #endif /* CONFIG_CFS_BANDWIDTH */ 10192 if (!ret) 10193 scx_group_set_bandwidth(tg, period_us, quota_us, burst_us); 10194 return ret; 10195 } 10196 10197 static s64 cpu_quota_read_s64(struct cgroup_subsys_state *css, 10198 struct cftype *cft) 10199 { 10200 u64 quota_us; 10201 10202 tg_bandwidth(css_tg(css), NULL, "a_us, NULL); 10203 return quota_us; /* (s64)RUNTIME_INF becomes -1 */ 10204 } 10205 10206 static u64 cpu_burst_read_u64(struct cgroup_subsys_state *css, 10207 struct cftype *cft) 10208 { 10209 u64 burst_us; 10210 10211 tg_bandwidth(css_tg(css), NULL, NULL, &burst_us); 10212 return burst_us; 10213 } 10214 10215 static int cpu_period_write_u64(struct cgroup_subsys_state *css, 10216 struct cftype *cftype, u64 period_us) 10217 { 10218 struct task_group *tg = css_tg(css); 10219 u64 quota_us, burst_us; 10220 10221 tg_bandwidth(tg, NULL, "a_us, &burst_us); 10222 return tg_set_bandwidth(tg, period_us, quota_us, burst_us); 10223 } 10224 10225 static int cpu_quota_write_s64(struct cgroup_subsys_state *css, 10226 struct cftype *cftype, s64 quota_us) 10227 { 10228 struct task_group *tg = css_tg(css); 10229 u64 period_us, burst_us; 10230 10231 if (quota_us < 0) 10232 quota_us = RUNTIME_INF; 10233 10234 tg_bandwidth(tg, &period_us, NULL, &burst_us); 10235 return tg_set_bandwidth(tg, period_us, quota_us, burst_us); 10236 } 10237 10238 static int cpu_burst_write_u64(struct cgroup_subsys_state *css, 10239 struct cftype *cftype, u64 burst_us) 10240 { 10241 struct task_group *tg = css_tg(css); 10242 u64 period_us, quota_us; 10243 10244 tg_bandwidth(tg, &period_us, "a_us, NULL); 10245 return tg_set_bandwidth(tg, period_us, quota_us, burst_us); 10246 } 10247 #endif /* CONFIG_GROUP_SCHED_BANDWIDTH */ 10248 10249 #ifdef CONFIG_RT_GROUP_SCHED 10250 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css, 10251 struct cftype *cft, s64 val) 10252 { 10253 return sched_group_set_rt_runtime(css_tg(css), val); 10254 } 10255 10256 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css, 10257 struct cftype *cft) 10258 { 10259 return sched_group_rt_runtime(css_tg(css)); 10260 } 10261 10262 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css, 10263 struct cftype *cftype, u64 rt_period_us) 10264 { 10265 return sched_group_set_rt_period(css_tg(css), rt_period_us); 10266 } 10267 10268 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css, 10269 struct cftype *cft) 10270 { 10271 return sched_group_rt_period(css_tg(css)); 10272 } 10273 #endif /* CONFIG_RT_GROUP_SCHED */ 10274 10275 #ifdef CONFIG_GROUP_SCHED_WEIGHT 10276 static s64 cpu_idle_read_s64(struct cgroup_subsys_state *css, 10277 struct cftype *cft) 10278 { 10279 return css_tg(css)->idle; 10280 } 10281 10282 static int cpu_idle_write_s64(struct cgroup_subsys_state *css, 10283 struct cftype *cft, s64 idle) 10284 { 10285 int ret; 10286 10287 ret = sched_group_set_idle(css_tg(css), idle); 10288 if (!ret) 10289 scx_group_set_idle(css_tg(css), idle); 10290 return ret; 10291 } 10292 #endif /* CONFIG_GROUP_SCHED_WEIGHT */ 10293 10294 static struct cftype cpu_legacy_files[] = { 10295 #ifdef CONFIG_GROUP_SCHED_WEIGHT 10296 { 10297 .name = "shares", 10298 .read_u64 = cpu_shares_read_u64, 10299 .write_u64 = cpu_shares_write_u64, 10300 }, 10301 { 10302 .name = "idle", 10303 .read_s64 = cpu_idle_read_s64, 10304 .write_s64 = cpu_idle_write_s64, 10305 }, 10306 #endif 10307 #ifdef CONFIG_GROUP_SCHED_BANDWIDTH 10308 { 10309 .name = "cfs_period_us", 10310 .read_u64 = cpu_period_read_u64, 10311 .write_u64 = cpu_period_write_u64, 10312 }, 10313 { 10314 .name = "cfs_quota_us", 10315 .read_s64 = cpu_quota_read_s64, 10316 .write_s64 = cpu_quota_write_s64, 10317 }, 10318 { 10319 .name = "cfs_burst_us", 10320 .read_u64 = cpu_burst_read_u64, 10321 .write_u64 = cpu_burst_write_u64, 10322 }, 10323 #endif 10324 #ifdef CONFIG_CFS_BANDWIDTH 10325 { 10326 .name = "stat", 10327 .seq_show = cpu_cfs_stat_show, 10328 }, 10329 { 10330 .name = "stat.local", 10331 .seq_show = cpu_cfs_local_stat_show, 10332 }, 10333 #endif 10334 #ifdef CONFIG_UCLAMP_TASK_GROUP 10335 { 10336 .name = "uclamp.min", 10337 .flags = CFTYPE_NOT_ON_ROOT, 10338 .seq_show = cpu_uclamp_min_show, 10339 .write = cpu_uclamp_min_write, 10340 }, 10341 { 10342 .name = "uclamp.max", 10343 .flags = CFTYPE_NOT_ON_ROOT, 10344 .seq_show = cpu_uclamp_max_show, 10345 .write = cpu_uclamp_max_write, 10346 }, 10347 #endif 10348 { } /* Terminate */ 10349 }; 10350 10351 #ifdef CONFIG_RT_GROUP_SCHED 10352 static struct cftype rt_group_files[] = { 10353 { 10354 .name = "rt_runtime_us", 10355 .read_s64 = cpu_rt_runtime_read, 10356 .write_s64 = cpu_rt_runtime_write, 10357 }, 10358 { 10359 .name = "rt_period_us", 10360 .read_u64 = cpu_rt_period_read_uint, 10361 .write_u64 = cpu_rt_period_write_uint, 10362 }, 10363 { } /* Terminate */ 10364 }; 10365 10366 # ifdef CONFIG_RT_GROUP_SCHED_DEFAULT_DISABLED 10367 DEFINE_STATIC_KEY_FALSE(rt_group_sched); 10368 # else 10369 DEFINE_STATIC_KEY_TRUE(rt_group_sched); 10370 # endif 10371 10372 static int __init setup_rt_group_sched(char *str) 10373 { 10374 long val; 10375 10376 if (kstrtol(str, 0, &val) || val < 0 || val > 1) { 10377 pr_warn("Unable to set rt_group_sched\n"); 10378 return 1; 10379 } 10380 if (val) 10381 static_branch_enable(&rt_group_sched); 10382 else 10383 static_branch_disable(&rt_group_sched); 10384 10385 return 1; 10386 } 10387 __setup("rt_group_sched=", setup_rt_group_sched); 10388 10389 static int __init cpu_rt_group_init(void) 10390 { 10391 if (!rt_group_sched_enabled()) 10392 return 0; 10393 10394 WARN_ON(cgroup_add_legacy_cftypes(&cpu_cgrp_subsys, rt_group_files)); 10395 return 0; 10396 } 10397 subsys_initcall(cpu_rt_group_init); 10398 #endif /* CONFIG_RT_GROUP_SCHED */ 10399 10400 static int cpu_extra_stat_show(struct seq_file *sf, 10401 struct cgroup_subsys_state *css) 10402 { 10403 #ifdef CONFIG_CFS_BANDWIDTH 10404 { 10405 struct task_group *tg = css_tg(css); 10406 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; 10407 u64 throttled_usec, burst_usec; 10408 10409 throttled_usec = cfs_b->throttled_time; 10410 do_div(throttled_usec, NSEC_PER_USEC); 10411 burst_usec = cfs_b->burst_time; 10412 do_div(burst_usec, NSEC_PER_USEC); 10413 10414 seq_printf(sf, "nr_periods %d\n" 10415 "nr_throttled %d\n" 10416 "throttled_usec %llu\n" 10417 "nr_bursts %d\n" 10418 "burst_usec %llu\n", 10419 cfs_b->nr_periods, cfs_b->nr_throttled, 10420 throttled_usec, cfs_b->nr_burst, burst_usec); 10421 } 10422 #endif /* CONFIG_CFS_BANDWIDTH */ 10423 return 0; 10424 } 10425 10426 static int cpu_local_stat_show(struct seq_file *sf, 10427 struct cgroup_subsys_state *css) 10428 { 10429 #ifdef CONFIG_CFS_BANDWIDTH 10430 { 10431 struct task_group *tg = css_tg(css); 10432 u64 throttled_self_usec; 10433 10434 throttled_self_usec = throttled_time_self(tg); 10435 do_div(throttled_self_usec, NSEC_PER_USEC); 10436 10437 seq_printf(sf, "throttled_usec %llu\n", 10438 throttled_self_usec); 10439 } 10440 #endif 10441 return 0; 10442 } 10443 10444 #ifdef CONFIG_GROUP_SCHED_WEIGHT 10445 10446 static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css, 10447 struct cftype *cft) 10448 { 10449 return sched_weight_to_cgroup(tg_weight(css_tg(css))); 10450 } 10451 10452 static int cpu_weight_write_u64(struct cgroup_subsys_state *css, 10453 struct cftype *cft, u64 cgrp_weight) 10454 { 10455 unsigned long weight; 10456 int ret; 10457 10458 if (cgrp_weight < CGROUP_WEIGHT_MIN || cgrp_weight > CGROUP_WEIGHT_MAX) 10459 return -ERANGE; 10460 10461 weight = sched_weight_from_cgroup(cgrp_weight); 10462 10463 ret = sched_group_set_shares(css_tg(css), scale_load(weight)); 10464 if (!ret) 10465 scx_group_set_weight(css_tg(css), cgrp_weight); 10466 return ret; 10467 } 10468 10469 static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css, 10470 struct cftype *cft) 10471 { 10472 unsigned long weight = tg_weight(css_tg(css)); 10473 int last_delta = INT_MAX; 10474 int prio, delta; 10475 10476 /* find the closest nice value to the current weight */ 10477 for (prio = 0; prio < ARRAY_SIZE(sched_prio_to_weight); prio++) { 10478 delta = abs(sched_prio_to_weight[prio] - weight); 10479 if (delta >= last_delta) 10480 break; 10481 last_delta = delta; 10482 } 10483 10484 return PRIO_TO_NICE(prio - 1 + MAX_RT_PRIO); 10485 } 10486 10487 static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css, 10488 struct cftype *cft, s64 nice) 10489 { 10490 unsigned long weight; 10491 int idx, ret; 10492 10493 if (nice < MIN_NICE || nice > MAX_NICE) 10494 return -ERANGE; 10495 10496 idx = NICE_TO_PRIO(nice) - MAX_RT_PRIO; 10497 idx = array_index_nospec(idx, 40); 10498 weight = sched_prio_to_weight[idx]; 10499 10500 ret = sched_group_set_shares(css_tg(css), scale_load(weight)); 10501 if (!ret) 10502 scx_group_set_weight(css_tg(css), 10503 sched_weight_to_cgroup(weight)); 10504 return ret; 10505 } 10506 #endif /* CONFIG_GROUP_SCHED_WEIGHT */ 10507 10508 static void __maybe_unused cpu_period_quota_print(struct seq_file *sf, 10509 long period, long quota) 10510 { 10511 if (quota < 0) 10512 seq_puts(sf, "max"); 10513 else 10514 seq_printf(sf, "%ld", quota); 10515 10516 seq_printf(sf, " %ld\n", period); 10517 } 10518 10519 /* caller should put the current value in *@periodp before calling */ 10520 static int __maybe_unused cpu_period_quota_parse(char *buf, u64 *period_us_p, 10521 u64 *quota_us_p) 10522 { 10523 char tok[21]; /* U64_MAX */ 10524 10525 if (sscanf(buf, "%20s %llu", tok, period_us_p) < 1) 10526 return -EINVAL; 10527 10528 if (sscanf(tok, "%llu", quota_us_p) < 1) { 10529 if (!strcmp(tok, "max")) 10530 *quota_us_p = RUNTIME_INF; 10531 else 10532 return -EINVAL; 10533 } 10534 10535 return 0; 10536 } 10537 10538 #ifdef CONFIG_GROUP_SCHED_BANDWIDTH 10539 static int cpu_max_show(struct seq_file *sf, void *v) 10540 { 10541 struct task_group *tg = css_tg(seq_css(sf)); 10542 u64 period_us, quota_us; 10543 10544 tg_bandwidth(tg, &period_us, "a_us, NULL); 10545 cpu_period_quota_print(sf, period_us, quota_us); 10546 return 0; 10547 } 10548 10549 static ssize_t cpu_max_write(struct kernfs_open_file *of, 10550 char *buf, size_t nbytes, loff_t off) 10551 { 10552 struct task_group *tg = css_tg(of_css(of)); 10553 u64 period_us, quota_us, burst_us; 10554 int ret; 10555 10556 tg_bandwidth(tg, &period_us, NULL, &burst_us); 10557 ret = cpu_period_quota_parse(buf, &period_us, "a_us); 10558 if (!ret) 10559 ret = tg_set_bandwidth(tg, period_us, quota_us, burst_us); 10560 return ret ?: nbytes; 10561 } 10562 #endif /* CONFIG_CFS_BANDWIDTH */ 10563 10564 static struct cftype cpu_files[] = { 10565 #ifdef CONFIG_GROUP_SCHED_WEIGHT 10566 { 10567 .name = "weight", 10568 .flags = CFTYPE_NOT_ON_ROOT, 10569 .read_u64 = cpu_weight_read_u64, 10570 .write_u64 = cpu_weight_write_u64, 10571 }, 10572 { 10573 .name = "weight.nice", 10574 .flags = CFTYPE_NOT_ON_ROOT, 10575 .read_s64 = cpu_weight_nice_read_s64, 10576 .write_s64 = cpu_weight_nice_write_s64, 10577 }, 10578 { 10579 .name = "idle", 10580 .flags = CFTYPE_NOT_ON_ROOT, 10581 .read_s64 = cpu_idle_read_s64, 10582 .write_s64 = cpu_idle_write_s64, 10583 }, 10584 #endif 10585 #ifdef CONFIG_GROUP_SCHED_BANDWIDTH 10586 { 10587 .name = "max", 10588 .flags = CFTYPE_NOT_ON_ROOT, 10589 .seq_show = cpu_max_show, 10590 .write = cpu_max_write, 10591 }, 10592 { 10593 .name = "max.burst", 10594 .flags = CFTYPE_NOT_ON_ROOT, 10595 .read_u64 = cpu_burst_read_u64, 10596 .write_u64 = cpu_burst_write_u64, 10597 }, 10598 #endif /* CONFIG_CFS_BANDWIDTH */ 10599 #ifdef CONFIG_UCLAMP_TASK_GROUP 10600 { 10601 .name = "uclamp.min", 10602 .flags = CFTYPE_NOT_ON_ROOT, 10603 .seq_show = cpu_uclamp_min_show, 10604 .write = cpu_uclamp_min_write, 10605 }, 10606 { 10607 .name = "uclamp.max", 10608 .flags = CFTYPE_NOT_ON_ROOT, 10609 .seq_show = cpu_uclamp_max_show, 10610 .write = cpu_uclamp_max_write, 10611 }, 10612 #endif /* CONFIG_UCLAMP_TASK_GROUP */ 10613 { } /* terminate */ 10614 }; 10615 10616 struct cgroup_subsys cpu_cgrp_subsys = { 10617 .css_alloc = cpu_cgroup_css_alloc, 10618 .css_online = cpu_cgroup_css_online, 10619 .css_offline = cpu_cgroup_css_offline, 10620 .css_released = cpu_cgroup_css_released, 10621 .css_free = cpu_cgroup_css_free, 10622 .css_extra_stat_show = cpu_extra_stat_show, 10623 .css_local_stat_show = cpu_local_stat_show, 10624 .can_attach = cpu_cgroup_can_attach, 10625 .attach = cpu_cgroup_attach, 10626 .cancel_attach = cpu_cgroup_cancel_attach, 10627 .legacy_cftypes = cpu_legacy_files, 10628 .dfl_cftypes = cpu_files, 10629 .early_init = true, 10630 .threaded = true, 10631 }; 10632 10633 #endif /* CONFIG_CGROUP_SCHED */ 10634 10635 void dump_cpu_task(int cpu) 10636 { 10637 if (in_hardirq() && cpu == smp_processor_id()) { 10638 struct pt_regs *regs; 10639 10640 regs = get_irq_regs(); 10641 if (regs) { 10642 show_regs(regs); 10643 return; 10644 } 10645 } 10646 10647 if (trigger_single_cpu_backtrace(cpu)) 10648 return; 10649 10650 pr_info("Task dump for CPU %d:\n", cpu); 10651 sched_show_task(cpu_curr(cpu)); 10652 } 10653 10654 /* 10655 * Nice levels are multiplicative, with a gentle 10% change for every 10656 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to 10657 * nice 1, it will get ~10% less CPU time than another CPU-bound task 10658 * that remained on nice 0. 10659 * 10660 * The "10% effect" is relative and cumulative: from _any_ nice level, 10661 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level 10662 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25. 10663 * If a task goes up by ~10% and another task goes down by ~10% then 10664 * the relative distance between them is ~25%.) 10665 */ 10666 const int sched_prio_to_weight[40] = { 10667 /* -20 */ 88761, 71755, 56483, 46273, 36291, 10668 /* -15 */ 29154, 23254, 18705, 14949, 11916, 10669 /* -10 */ 9548, 7620, 6100, 4904, 3906, 10670 /* -5 */ 3121, 2501, 1991, 1586, 1277, 10671 /* 0 */ 1024, 820, 655, 526, 423, 10672 /* 5 */ 335, 272, 215, 172, 137, 10673 /* 10 */ 110, 87, 70, 56, 45, 10674 /* 15 */ 36, 29, 23, 18, 15, 10675 }; 10676 10677 /* 10678 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, pre-calculated. 10679 * 10680 * In cases where the weight does not change often, we can use the 10681 * pre-calculated inverse to speed up arithmetics by turning divisions 10682 * into multiplications: 10683 */ 10684 const u32 sched_prio_to_wmult[40] = { 10685 /* -20 */ 48388, 59856, 76040, 92818, 118348, 10686 /* -15 */ 147320, 184698, 229616, 287308, 360437, 10687 /* -10 */ 449829, 563644, 704093, 875809, 1099582, 10688 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326, 10689 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587, 10690 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126, 10691 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717, 10692 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153, 10693 }; 10694 10695 void call_trace_sched_update_nr_running(struct rq *rq, int count) 10696 { 10697 trace_sched_update_nr_running_tp(rq, count); 10698 } 10699 10700 #ifdef CONFIG_SCHED_MM_CID 10701 /* 10702 * Concurrency IDentifier management 10703 * 10704 * Serialization rules: 10705 * 10706 * mm::mm_cid::mutex: Serializes fork() and exit() and therefore 10707 * protects mm::mm_cid::users and mode switch 10708 * transitions 10709 * 10710 * mm::mm_cid::lock: Serializes mm_update_max_cids() and 10711 * mm_update_cpus_allowed(). Nests in mm_cid::mutex 10712 * and runqueue lock. 10713 * 10714 * The mm_cidmask bitmap is not protected by any of the mm::mm_cid locks 10715 * and can only be modified with atomic operations. 10716 * 10717 * The mm::mm_cid:pcpu per CPU storage is protected by the CPUs runqueue 10718 * lock. 10719 * 10720 * CID ownership: 10721 * 10722 * A CID is either owned by a task (stored in task_struct::mm_cid.cid) or 10723 * by a CPU (stored in mm::mm_cid.pcpu::cid). CIDs owned by CPUs have the 10724 * MM_CID_ONCPU bit set. 10725 * 10726 * During the transition of ownership mode, the MM_CID_TRANSIT bit is set 10727 * on the CIDs. When this bit is set the tasks drop the CID back into the 10728 * pool when scheduling out. 10729 * 10730 * Both bits (ONCPU and TRANSIT) are filtered out by task_cid() when the 10731 * CID is actually handed over to user space in the RSEQ memory. 10732 * 10733 * Mode switching: 10734 * 10735 * The ownership mode is per process and stored in mm:mm_cid::mode with the 10736 * following possible states: 10737 * 10738 * 0: Per task ownership 10739 * 0 | MM_CID_TRANSIT: Transition from per CPU to per task 10740 * MM_CID_ONCPU: Per CPU ownership 10741 * MM_CID_ONCPU | MM_CID_TRANSIT: Transition from per task to per CPU 10742 * 10743 * All transitions of ownership mode happen in two phases: 10744 * 10745 * 1) mm:mm_cid::mode has the MM_CID_TRANSIT bit set. This is OR'ed on the 10746 * CIDs and denotes that the CID is only temporarily owned by a 10747 * task. When the task schedules out it drops the CID back into the 10748 * pool if this bit is set. 10749 * 10750 * 2) The initiating context walks the per CPU space or the tasks to fixup 10751 * or drop the CIDs and after completion it clears MM_CID_TRANSIT in 10752 * mm:mm_cid::mode. After that point the CIDs are strictly task or CPU 10753 * owned again. 10754 * 10755 * This two phase transition is required to prevent CID space exhaustion 10756 * during the transition as a direct transfer of ownership would fail: 10757 * 10758 * - On task to CPU mode switch if a task is scheduled in on one CPU and 10759 * then migrated to another CPU before the fixup freed enough per task 10760 * CIDs. 10761 * 10762 * - On CPU to task mode switch if two tasks are scheduled in on the same 10763 * CPU before the fixup freed per CPU CIDs. 10764 * 10765 * Both scenarios can result in a live lock because sched_in() is invoked 10766 * with runqueue lock held and loops in search of a CID and the fixup 10767 * thread can't make progress freeing them up because it is stuck on the 10768 * same runqueue lock. 10769 * 10770 * While MM_CID_TRANSIT is active during the transition phase the MM_CID 10771 * bitmap can be contended, but that's a temporary contention bound to the 10772 * transition period. After that everything goes back into steady state and 10773 * nothing except fork() and exit() will touch the bitmap. This is an 10774 * acceptable tradeoff as it completely avoids complex serialization, 10775 * memory barriers and atomic operations for the common case. 10776 * 10777 * Aside of that this mechanism also ensures RT compability: 10778 * 10779 * - The task which runs the fixup is fully preemptible except for the 10780 * short runqueue lock held sections. 10781 * 10782 * - The transient impact of the bitmap contention is only problematic 10783 * when there is a thundering herd scenario of tasks scheduling in and 10784 * out concurrently. There is not much which can be done about that 10785 * except for avoiding mode switching by a proper overall system 10786 * configuration. 10787 * 10788 * Switching to per CPU mode happens when the user count becomes greater 10789 * than the maximum number of CIDs, which is calculated by: 10790 * 10791 * opt_cids = min(mm_cid::nr_cpus_allowed, mm_cid::users); 10792 * max_cids = min(1.25 * opt_cids, num_possible_cpus()); 10793 * 10794 * The +25% allowance is useful for tight CPU masks in scenarios where only 10795 * a few threads are created and destroyed to avoid frequent mode 10796 * switches. Though this allowance shrinks, the closer opt_cids becomes to 10797 * num_possible_cpus(), which is the (unfortunate) hard ABI limit. 10798 * 10799 * At the point of switching to per CPU mode the new user is not yet 10800 * visible in the system, so the task which initiated the fork() runs the 10801 * fixup function. mm_cid_fixup_tasks_to_cpu() walks the thread list and 10802 * either marks each task owned CID with MM_CID_TRANSIT if the task is 10803 * running on a CPU or drops it into the CID pool if a task is not on a 10804 * CPU. Tasks which schedule in before the task walk reaches them do the 10805 * handover in mm_cid_schedin(). When mm_cid_fixup_tasks_to_cpus() 10806 * completes it is guaranteed that no task related to that MM owns a CID 10807 * anymore. 10808 * 10809 * Switching back to task mode happens when the user count goes below the 10810 * threshold which was recorded on the per CPU mode switch: 10811 * 10812 * pcpu_thrs = min(opt_cids - (opt_cids / 4), num_possible_cpus() / 2); 10813 * 10814 * This threshold is updated when a affinity change increases the number of 10815 * allowed CPUs for the MM, which might cause a switch back to per task 10816 * mode. 10817 * 10818 * If the switch back was initiated by a exiting task, then that task runs 10819 * the fixup function. If it was initiated by a affinity change, then it's 10820 * run either in the deferred update function in context of a workqueue or 10821 * by a task which forks a new one or by a task which exits. Whatever 10822 * happens first. mm_cid_fixup_cpus_to_task() walks through the possible 10823 * CPUs and either marks the CPU owned CIDs with MM_CID_TRANSIT if a 10824 * related task is running on the CPU or drops it into the pool. Tasks 10825 * which are scheduled in before the fixup covered them do the handover 10826 * themself. When mm_cid_fixup_cpus_to_tasks() completes it is guaranteed 10827 * that no CID related to that MM is owned by a CPU anymore. 10828 */ 10829 10830 /* 10831 * Update the CID range properties when the constraints change. Invoked via 10832 * fork(), exit() and affinity changes 10833 */ 10834 static void __mm_update_max_cids(struct mm_mm_cid *mc) 10835 { 10836 unsigned int opt_cids, max_cids; 10837 10838 /* Calculate the new optimal constraint */ 10839 opt_cids = min(mc->nr_cpus_allowed, mc->users); 10840 10841 /* Adjust the maximum CIDs to +25% limited by the number of possible CPUs */ 10842 max_cids = min(opt_cids + (opt_cids / 4), num_possible_cpus()); 10843 WRITE_ONCE(mc->max_cids, max_cids); 10844 } 10845 10846 static inline unsigned int mm_cid_calc_pcpu_thrs(struct mm_mm_cid *mc) 10847 { 10848 unsigned int opt_cids; 10849 10850 opt_cids = min(mc->nr_cpus_allowed, mc->users); 10851 /* Has to be at least 1 because 0 indicates PCPU mode off */ 10852 return max(min(opt_cids - opt_cids / 4, num_possible_cpus() / 2), 1); 10853 } 10854 10855 static bool mm_update_max_cids(struct mm_struct *mm) 10856 { 10857 struct mm_mm_cid *mc = &mm->mm_cid; 10858 bool percpu = cid_on_cpu(mc->mode); 10859 10860 lockdep_assert_held(&mm->mm_cid.lock); 10861 10862 /* Clear deferred mode switch flag. A change is handled by the caller */ 10863 mc->update_deferred = false; 10864 __mm_update_max_cids(mc); 10865 10866 /* Check whether owner mode must be changed */ 10867 if (!percpu) { 10868 /* Enable per CPU mode when the number of users is above max_cids */ 10869 if (mc->users > mc->max_cids) 10870 mc->pcpu_thrs = mm_cid_calc_pcpu_thrs(mc); 10871 } else { 10872 /* Switch back to per task if user count under threshold */ 10873 if (mc->users < mc->pcpu_thrs) 10874 mc->pcpu_thrs = 0; 10875 } 10876 10877 /* Mode change required? */ 10878 if (percpu == !!mc->pcpu_thrs) 10879 return false; 10880 10881 /* Flip the mode and set the transition flag to bridge the transfer */ 10882 WRITE_ONCE(mc->mode, mc->mode ^ (MM_CID_TRANSIT | MM_CID_ONCPU)); 10883 /* 10884 * Order the store against the subsequent fixups so that 10885 * acquire(rq::lock) cannot be reordered by the CPU before the 10886 * store. 10887 */ 10888 smp_mb(); 10889 return true; 10890 } 10891 10892 static inline void mm_update_cpus_allowed(struct mm_struct *mm, const struct cpumask *affmsk) 10893 { 10894 struct cpumask *mm_allowed; 10895 struct mm_mm_cid *mc; 10896 unsigned int weight; 10897 10898 if (!mm || !READ_ONCE(mm->mm_cid.users)) 10899 return; 10900 /* 10901 * mm::mm_cid::mm_cpus_allowed is the superset of each threads 10902 * allowed CPUs mask which means it can only grow. 10903 */ 10904 mc = &mm->mm_cid; 10905 guard(raw_spinlock)(&mc->lock); 10906 mm_allowed = mm_cpus_allowed(mm); 10907 weight = cpumask_weighted_or(mm_allowed, mm_allowed, affmsk); 10908 if (weight == mc->nr_cpus_allowed) 10909 return; 10910 10911 WRITE_ONCE(mc->nr_cpus_allowed, weight); 10912 __mm_update_max_cids(mc); 10913 if (!cid_on_cpu(mc->mode)) 10914 return; 10915 10916 /* Adjust the threshold to the wider set */ 10917 mc->pcpu_thrs = mm_cid_calc_pcpu_thrs(mc); 10918 /* Switch back to per task mode? */ 10919 if (mc->users >= mc->pcpu_thrs) 10920 return; 10921 10922 /* Don't queue twice */ 10923 if (mc->update_deferred) 10924 return; 10925 10926 /* Queue the irq work, which schedules the real work */ 10927 mc->update_deferred = true; 10928 irq_work_queue(&mc->irq_work); 10929 } 10930 10931 static inline void mm_cid_complete_transit(struct mm_struct *mm, unsigned int mode) 10932 { 10933 /* 10934 * Ensure that the store removing the TRANSIT bit cannot be 10935 * reordered by the CPU before the fixups have been completed. 10936 */ 10937 smp_mb(); 10938 WRITE_ONCE(mm->mm_cid.mode, mode); 10939 } 10940 10941 static inline void mm_cid_transit_to_task(struct task_struct *t, struct mm_cid_pcpu *pcp) 10942 { 10943 if (cid_on_cpu(t->mm_cid.cid)) { 10944 unsigned int cid = cpu_cid_to_cid(t->mm_cid.cid); 10945 10946 t->mm_cid.cid = cid_to_transit_cid(cid); 10947 pcp->cid = t->mm_cid.cid; 10948 } 10949 } 10950 10951 static void mm_cid_fixup_cpus_to_tasks(struct mm_struct *mm) 10952 { 10953 unsigned int cpu; 10954 10955 /* Walk the CPUs and fixup all stale CIDs */ 10956 for_each_possible_cpu(cpu) { 10957 struct mm_cid_pcpu *pcp = per_cpu_ptr(mm->mm_cid.pcpu, cpu); 10958 struct rq *rq = cpu_rq(cpu); 10959 10960 /* Remote access to mm::mm_cid::pcpu requires rq_lock */ 10961 guard(rq_lock_irq)(rq); 10962 /* Is the CID still owned by the CPU? */ 10963 if (cid_on_cpu(pcp->cid)) { 10964 /* 10965 * If rq->curr has @mm, transfer it with the 10966 * transition bit set. Otherwise drop it. 10967 */ 10968 if (rq->curr->mm == mm && rq->curr->mm_cid.active) 10969 mm_cid_transit_to_task(rq->curr, pcp); 10970 else 10971 mm_drop_cid_on_cpu(mm, pcp); 10972 10973 } else if (rq->curr->mm == mm && rq->curr->mm_cid.active) { 10974 unsigned int cid = rq->curr->mm_cid.cid; 10975 10976 /* 10977 * Set the transition bit only on a genuine task-owned 10978 * CID. A running active task can legitimately have 10979 * MM_CID_UNSET here: in per-CPU mode CIDs are assigned 10980 * lazily on schedule-in, so the fork()/execve() window 10981 * leaves the task active with no owned CID. Setting the 10982 * transition bit on MM_CID_UNSET would later feed 10983 * clear_bit() an out-of-bounds bit number via 10984 * mm_cid_schedout(), so exclude it. A CPU-owned 10985 * (MM_CID_ONCPU) CID is handled by the cid_on_cpu() 10986 * branch above and never reaches here. 10987 */ 10988 if (cid != MM_CID_UNSET && !cid_in_transit(cid)) { 10989 cid = cid_to_transit_cid(cid); 10990 rq->curr->mm_cid.cid = cid; 10991 pcp->cid = cid; 10992 } 10993 } 10994 } 10995 mm_cid_complete_transit(mm, 0); 10996 } 10997 10998 static inline void mm_cid_transit_to_cpu(struct task_struct *t, struct mm_cid_pcpu *pcp) 10999 { 11000 if (cid_on_task(t->mm_cid.cid)) { 11001 t->mm_cid.cid = cid_to_transit_cid(t->mm_cid.cid); 11002 pcp->cid = t->mm_cid.cid; 11003 } 11004 } 11005 11006 static void mm_cid_fixup_task_to_cpu(struct task_struct *t, struct mm_struct *mm) 11007 { 11008 /* Remote access to mm::mm_cid::pcpu requires rq_lock */ 11009 guard(task_rq_lock)(t); 11010 if (cid_on_task(t->mm_cid.cid)) { 11011 /* If running on the CPU, put the CID in transit mode, otherwise drop it */ 11012 if (task_rq(t)->curr == t) 11013 mm_cid_transit_to_cpu(t, per_cpu_ptr(mm->mm_cid.pcpu, task_cpu(t))); 11014 else 11015 mm_unset_cid_on_task(t); 11016 } 11017 } 11018 11019 static void mm_cid_fixup_tasks_to_cpus(void) 11020 { 11021 struct mm_struct *mm = current->mm; 11022 struct task_struct *t; 11023 11024 lockdep_assert_held(&mm->mm_cid.mutex); 11025 11026 hlist_for_each_entry(t, &mm->mm_cid.user_list, mm_cid.node) { 11027 /* Current has already transferred before invoking the fixup. */ 11028 if (t != current) 11029 mm_cid_fixup_task_to_cpu(t, mm); 11030 } 11031 11032 mm_cid_complete_transit(mm, MM_CID_ONCPU); 11033 } 11034 11035 static bool sched_mm_cid_add_user(struct task_struct *t, struct mm_struct *mm) 11036 { 11037 lockdep_assert_held(&mm->mm_cid.lock); 11038 11039 t->mm_cid.active = 1; 11040 hlist_add_head(&t->mm_cid.node, &mm->mm_cid.user_list); 11041 mm->mm_cid.users++; 11042 return mm_update_max_cids(mm); 11043 } 11044 11045 static void sched_mm_cid_fork(struct task_struct *t) 11046 { 11047 struct mm_struct *mm = t->mm; 11048 bool percpu; 11049 11050 if (!mm) 11051 return; 11052 11053 WARN_ON_ONCE(t->mm_cid.cid != MM_CID_UNSET); 11054 11055 guard(mutex)(&mm->mm_cid.mutex); 11056 scoped_guard(raw_spinlock_irq, &mm->mm_cid.lock) { 11057 struct mm_cid_pcpu *pcp = this_cpu_ptr(mm->mm_cid.pcpu); 11058 11059 /* First user ? */ 11060 if (!mm->mm_cid.users) { 11061 sched_mm_cid_add_user(t, mm); 11062 t->mm_cid.cid = mm_get_cid(mm); 11063 /* Required for execve() */ 11064 pcp->cid = t->mm_cid.cid; 11065 return; 11066 } 11067 11068 if (!sched_mm_cid_add_user(t, mm)) { 11069 if (!cid_on_cpu(mm->mm_cid.mode)) 11070 t->mm_cid.cid = mm_get_cid(mm); 11071 return; 11072 } 11073 11074 /* Handle the mode change and transfer current's CID */ 11075 percpu = cid_on_cpu(mm->mm_cid.mode); 11076 if (!percpu) 11077 mm_cid_transit_to_task(current, pcp); 11078 else 11079 mm_cid_transit_to_cpu(current, pcp); 11080 } 11081 11082 if (percpu) { 11083 mm_cid_fixup_tasks_to_cpus(); 11084 } else { 11085 mm_cid_fixup_cpus_to_tasks(mm); 11086 t->mm_cid.cid = mm_get_cid(mm); 11087 } 11088 } 11089 11090 static bool sched_mm_cid_remove_user(struct task_struct *t) 11091 { 11092 lockdep_assert_held(&t->mm->mm_cid.lock); 11093 11094 t->mm_cid.active = 0; 11095 /* Clear the transition bit */ 11096 t->mm_cid.cid = cid_from_transit_cid(t->mm_cid.cid); 11097 mm_unset_cid_on_task(t); 11098 hlist_del_init(&t->mm_cid.node); 11099 t->mm->mm_cid.users--; 11100 return mm_update_max_cids(t->mm); 11101 } 11102 11103 static bool __sched_mm_cid_exit(struct task_struct *t) 11104 { 11105 struct mm_struct *mm = t->mm; 11106 11107 if (!sched_mm_cid_remove_user(t)) 11108 return false; 11109 /* 11110 * Contrary to fork() this only deals with a switch back to per 11111 * task mode either because the above decreased users or an 11112 * affinity change increased the number of allowed CPUs and the 11113 * deferred fixup did not run yet. 11114 */ 11115 if (WARN_ON_ONCE(cid_on_cpu(mm->mm_cid.mode))) 11116 return false; 11117 /* 11118 * A failed fork(2) cleanup never gets here, so @current must have 11119 * the same MM as @t. That's true for exit() and the failed 11120 * pthread_create() cleanup case. 11121 */ 11122 if (WARN_ON_ONCE(current->mm != mm)) 11123 return false; 11124 return true; 11125 } 11126 11127 /* 11128 * When a task exits, the MM CID held by the task is not longer required as 11129 * the task cannot return to user space. 11130 */ 11131 void sched_mm_cid_exit(struct task_struct *t) 11132 { 11133 struct mm_struct *mm = t->mm; 11134 11135 if (!mm || !t->mm_cid.active) 11136 return; 11137 /* 11138 * Ensure that only one instance is doing MM CID operations within 11139 * a MM. The common case is uncontended. The rare fixup case adds 11140 * some overhead. 11141 */ 11142 scoped_guard(mutex, &mm->mm_cid.mutex) { 11143 /* mm_cid::mutex is sufficient to protect mm_cid::users */ 11144 if (likely(mm->mm_cid.users > 1)) { 11145 scoped_guard(raw_spinlock_irq, &mm->mm_cid.lock) { 11146 if (!__sched_mm_cid_exit(t)) 11147 return; 11148 /* 11149 * Mode change. The task has the CID unset 11150 * already and dealt with an eventually set 11151 * TRANSIT bit. If the CID is owned by the CPU 11152 * then drop it. 11153 */ 11154 mm_drop_cid_on_cpu(mm, this_cpu_ptr(mm->mm_cid.pcpu)); 11155 } 11156 mm_cid_fixup_cpus_to_tasks(mm); 11157 return; 11158 } 11159 /* Last user */ 11160 scoped_guard(raw_spinlock_irq, &mm->mm_cid.lock) { 11161 /* Required across execve() */ 11162 if (t == current) 11163 mm_cid_transit_to_task(t, this_cpu_ptr(mm->mm_cid.pcpu)); 11164 /* Ignore mode change. There is nothing to do. */ 11165 sched_mm_cid_remove_user(t); 11166 } 11167 } 11168 11169 /* 11170 * As this is the last user (execve(), process exit or failed 11171 * fork(2)) there is no concurrency anymore. 11172 * 11173 * Synchronize eventually pending work to ensure that there are no 11174 * dangling references left. @t->mm_cid.users is zero so nothing 11175 * can queue this work anymore. 11176 */ 11177 irq_work_sync(&mm->mm_cid.irq_work); 11178 cancel_work_sync(&mm->mm_cid.work); 11179 } 11180 11181 /* Deactivate MM CID allocation across execve() */ 11182 void sched_mm_cid_before_execve(struct task_struct *t) 11183 { 11184 sched_mm_cid_exit(t); 11185 } 11186 11187 /* Reactivate MM CID after execve() */ 11188 void sched_mm_cid_after_execve(struct task_struct *t) 11189 { 11190 if (t->mm) 11191 sched_mm_cid_fork(t); 11192 } 11193 11194 static void mm_cid_work_fn(struct work_struct *work) 11195 { 11196 struct mm_struct *mm = container_of(work, struct mm_struct, mm_cid.work); 11197 11198 guard(mutex)(&mm->mm_cid.mutex); 11199 /* Did the last user task exit already? */ 11200 if (!mm->mm_cid.users) 11201 return; 11202 11203 scoped_guard(raw_spinlock_irq, &mm->mm_cid.lock) { 11204 /* Have fork() or exit() handled it already? */ 11205 if (!mm->mm_cid.update_deferred) 11206 return; 11207 /* This clears mm_cid::update_deferred */ 11208 if (!mm_update_max_cids(mm)) 11209 return; 11210 /* Affinity changes can only switch back to task mode */ 11211 if (WARN_ON_ONCE(cid_on_cpu(mm->mm_cid.mode))) 11212 return; 11213 } 11214 mm_cid_fixup_cpus_to_tasks(mm); 11215 } 11216 11217 static void mm_cid_irq_work(struct irq_work *work) 11218 { 11219 struct mm_struct *mm = container_of(work, struct mm_struct, mm_cid.irq_work); 11220 11221 /* 11222 * Needs to be unconditional because mm_cid::lock cannot be held 11223 * when scheduling work as mm_update_cpus_allowed() nests inside 11224 * rq::lock and schedule_work() might end up in wakeup... 11225 */ 11226 schedule_work(&mm->mm_cid.work); 11227 } 11228 11229 void mm_init_cid(struct mm_struct *mm, struct task_struct *p) 11230 { 11231 mm->mm_cid.max_cids = 0; 11232 mm->mm_cid.mode = 0; 11233 mm->mm_cid.nr_cpus_allowed = p->nr_cpus_allowed; 11234 mm->mm_cid.users = 0; 11235 mm->mm_cid.pcpu_thrs = 0; 11236 mm->mm_cid.update_deferred = 0; 11237 raw_spin_lock_init(&mm->mm_cid.lock); 11238 mutex_init(&mm->mm_cid.mutex); 11239 mm->mm_cid.irq_work = IRQ_WORK_INIT_HARD(mm_cid_irq_work); 11240 INIT_WORK(&mm->mm_cid.work, mm_cid_work_fn); 11241 INIT_HLIST_HEAD(&mm->mm_cid.user_list); 11242 cpumask_copy(mm_cpus_allowed(mm), &p->cpus_mask); 11243 bitmap_zero(mm_cidmask(mm), num_possible_cpus()); 11244 } 11245 #else /* CONFIG_SCHED_MM_CID */ 11246 static inline void mm_update_cpus_allowed(struct mm_struct *mm, const struct cpumask *affmsk) { } 11247 static inline void sched_mm_cid_fork(struct task_struct *t) { } 11248 #endif /* !CONFIG_SCHED_MM_CID */ 11249 11250 static DEFINE_PER_CPU(struct sched_change_ctx, sched_change_ctx); 11251 11252 struct sched_change_ctx *sched_change_begin(struct task_struct *p, unsigned int flags) 11253 { 11254 struct sched_change_ctx *ctx = this_cpu_ptr(&sched_change_ctx); 11255 struct rq *rq = task_rq(p); 11256 11257 /* 11258 * Must exclusively use matched flags since this is both dequeue and 11259 * enqueue. 11260 */ 11261 WARN_ON_ONCE(flags & 0xFFFF0000); 11262 11263 lockdep_assert_rq_held(rq); 11264 11265 if (!(flags & DEQUEUE_NOCLOCK)) { 11266 update_rq_clock(rq); 11267 flags |= DEQUEUE_NOCLOCK; 11268 } 11269 11270 if ((flags & DEQUEUE_CLASS) && p->sched_class->switching_from) 11271 p->sched_class->switching_from(rq, p); 11272 11273 *ctx = (struct sched_change_ctx){ 11274 .p = p, 11275 .class = p->sched_class, 11276 .flags = flags, 11277 .queued = task_on_rq_queued(p), 11278 .running = task_current_donor(rq, p), 11279 }; 11280 11281 if (!(flags & DEQUEUE_CLASS)) { 11282 if (p->sched_class->get_prio) 11283 ctx->prio = p->sched_class->get_prio(rq, p); 11284 else 11285 ctx->prio = p->prio; 11286 } 11287 11288 if (ctx->queued) 11289 dequeue_task(rq, p, flags); 11290 if (ctx->running) 11291 put_prev_task(rq, p); 11292 11293 if ((flags & DEQUEUE_CLASS) && p->sched_class->switched_from) 11294 p->sched_class->switched_from(rq, p); 11295 11296 return ctx; 11297 } 11298 11299 void sched_change_end(struct sched_change_ctx *ctx) 11300 { 11301 struct task_struct *p = ctx->p; 11302 struct rq *rq = task_rq(p); 11303 11304 lockdep_assert_rq_held(rq); 11305 11306 /* 11307 * Changing class without *QUEUE_CLASS is bad. 11308 */ 11309 WARN_ON_ONCE(p->sched_class != ctx->class && !(ctx->flags & ENQUEUE_CLASS)); 11310 11311 if ((ctx->flags & ENQUEUE_CLASS) && p->sched_class->switching_to) 11312 p->sched_class->switching_to(rq, p); 11313 11314 if (ctx->queued) 11315 enqueue_task(rq, p, ctx->flags); 11316 if (ctx->running) 11317 set_next_task(rq, p); 11318 11319 if (ctx->flags & ENQUEUE_CLASS) { 11320 if (p->sched_class->switched_to) 11321 p->sched_class->switched_to(rq, p); 11322 11323 if (ctx->running) { 11324 /* 11325 * If this was a class promotion; let the old class 11326 * know it got preempted. Note that none of the 11327 * switch*_from() methods know the new class and none 11328 * of the switch*_to() methods know the old class. 11329 */ 11330 if (sched_class_above(p->sched_class, ctx->class)) { 11331 rq->next_class->wakeup_preempt(rq, p, 0); 11332 rq->next_class = p->sched_class; 11333 } 11334 /* 11335 * If this was a degradation in class; make sure to 11336 * reschedule. 11337 */ 11338 if (sched_class_above(ctx->class, p->sched_class)) 11339 resched_curr(rq); 11340 } 11341 } else { 11342 p->sched_class->prio_changed(rq, p, ctx->prio); 11343 } 11344 } 11345