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