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