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