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 struct sched_entity *curr = task_rq(p)->cfs.curr; 5661 5662 prefetch(curr); 5663 prefetch(&curr->exec_start); 5664 } 5665 5666 /* 5667 * Return accounted runtime for the task. 5668 * In case the task is currently running, return the runtime plus current's 5669 * pending runtime that have not been accounted yet. 5670 */ 5671 unsigned long long task_sched_runtime(struct task_struct *p) 5672 { 5673 struct rq_flags rf; 5674 struct rq *rq; 5675 u64 ns; 5676 5677 #ifdef CONFIG_64BIT 5678 /* 5679 * 64-bit doesn't need locks to atomically read a 64-bit value. 5680 * So we have a optimization chance when the task's delta_exec is 0. 5681 * Reading ->on_cpu is racy, but this is OK. 5682 * 5683 * If we race with it leaving CPU, we'll take a lock. So we're correct. 5684 * If we race with it entering CPU, unaccounted time is 0. This is 5685 * indistinguishable from the read occurring a few cycles earlier. 5686 * If we see ->on_cpu without ->on_rq, the task is leaving, and has 5687 * been accounted, so we're correct here as well. 5688 */ 5689 if (!p->on_cpu || !task_on_rq_queued(p)) 5690 return p->se.sum_exec_runtime; 5691 #endif 5692 5693 rq = task_rq_lock(p, &rf); 5694 /* 5695 * Must be ->curr _and_ ->on_rq. If dequeued, we would 5696 * project cycles that may never be accounted to this 5697 * thread, breaking clock_gettime(). 5698 */ 5699 if (task_current_donor(rq, p) && task_on_rq_queued(p)) { 5700 prefetch_curr_exec_start(p); 5701 update_rq_clock(rq); 5702 p->sched_class->update_curr(rq); 5703 } 5704 ns = p->se.sum_exec_runtime; 5705 task_rq_unlock(rq, p, &rf); 5706 5707 return ns; 5708 } 5709 5710 static u64 cpu_resched_latency(struct rq *rq) 5711 { 5712 int latency_warn_ms = READ_ONCE(sysctl_resched_latency_warn_ms); 5713 u64 resched_latency, now = rq_clock(rq); 5714 static bool warned_once; 5715 5716 if (sysctl_resched_latency_warn_once && warned_once) 5717 return 0; 5718 5719 if (!need_resched() || !latency_warn_ms) 5720 return 0; 5721 5722 if (system_state == SYSTEM_BOOTING) 5723 return 0; 5724 5725 if (!rq->last_seen_need_resched_ns) { 5726 rq->last_seen_need_resched_ns = now; 5727 rq->ticks_without_resched = 0; 5728 return 0; 5729 } 5730 5731 rq->ticks_without_resched++; 5732 resched_latency = now - rq->last_seen_need_resched_ns; 5733 if (resched_latency <= latency_warn_ms * NSEC_PER_MSEC) 5734 return 0; 5735 5736 warned_once = true; 5737 5738 return resched_latency; 5739 } 5740 5741 static int __init setup_resched_latency_warn_ms(char *str) 5742 { 5743 long val; 5744 5745 if ((kstrtol(str, 0, &val))) { 5746 pr_warn("Unable to set resched_latency_warn_ms\n"); 5747 return 1; 5748 } 5749 5750 sysctl_resched_latency_warn_ms = val; 5751 return 1; 5752 } 5753 __setup("resched_latency_warn_ms=", setup_resched_latency_warn_ms); 5754 5755 /* 5756 * This function gets called by the timer code, with HZ frequency. 5757 * We call it with interrupts disabled. 5758 */ 5759 void sched_tick(void) 5760 { 5761 int cpu = smp_processor_id(); 5762 struct rq *rq = cpu_rq(cpu); 5763 /* accounting goes to the donor task */ 5764 struct task_struct *donor; 5765 struct rq_flags rf; 5766 unsigned long hw_pressure; 5767 u64 resched_latency; 5768 5769 if (housekeeping_cpu(cpu, HK_TYPE_KERNEL_NOISE)) 5770 arch_scale_freq_tick(); 5771 5772 sched_clock_tick(); 5773 5774 rq_lock(rq, &rf); 5775 donor = rq->donor; 5776 5777 psi_account_irqtime(rq, donor, NULL); 5778 5779 update_rq_clock(rq); 5780 hw_pressure = arch_scale_hw_pressure(cpu_of(rq)); 5781 update_hw_load_avg(rq_clock_task(rq), rq, hw_pressure); 5782 5783 if (dynamic_preempt_lazy() && tif_test_bit(TIF_NEED_RESCHED_LAZY)) 5784 resched_curr(rq); 5785 5786 donor->sched_class->task_tick(rq, donor, 0); 5787 if (sched_feat(LATENCY_WARN)) 5788 resched_latency = cpu_resched_latency(rq); 5789 calc_global_load_tick(rq); 5790 sched_core_tick(rq); 5791 scx_tick(rq); 5792 5793 rq_unlock(rq, &rf); 5794 5795 if (sched_feat(LATENCY_WARN) && resched_latency) 5796 resched_latency_warn(cpu, resched_latency); 5797 5798 perf_event_task_tick(); 5799 5800 if (donor->flags & PF_WQ_WORKER) 5801 wq_worker_tick(donor); 5802 5803 if (!scx_switched_all()) { 5804 rq->idle_balance = idle_cpu(cpu); 5805 sched_balance_trigger(rq); 5806 } 5807 } 5808 5809 #ifdef CONFIG_NO_HZ_FULL 5810 5811 struct tick_work { 5812 int cpu; 5813 atomic_t state; 5814 struct delayed_work work; 5815 }; 5816 /* Values for ->state, see diagram below. */ 5817 #define TICK_SCHED_REMOTE_OFFLINE 0 5818 #define TICK_SCHED_REMOTE_OFFLINING 1 5819 #define TICK_SCHED_REMOTE_RUNNING 2 5820 5821 /* 5822 * State diagram for ->state: 5823 * 5824 * 5825 * TICK_SCHED_REMOTE_OFFLINE 5826 * | ^ 5827 * | | 5828 * | | sched_tick_remote() 5829 * | | 5830 * | | 5831 * +--TICK_SCHED_REMOTE_OFFLINING 5832 * | ^ 5833 * | | 5834 * sched_tick_start() | | sched_tick_stop() 5835 * | | 5836 * V | 5837 * TICK_SCHED_REMOTE_RUNNING 5838 * 5839 * 5840 * Other transitions get WARN_ON_ONCE(), except that sched_tick_remote() 5841 * and sched_tick_start() are happy to leave the state in RUNNING. 5842 */ 5843 5844 static struct tick_work __percpu *tick_work_cpu; 5845 5846 static void sched_tick_remote(struct work_struct *work) 5847 { 5848 struct delayed_work *dwork = to_delayed_work(work); 5849 struct tick_work *twork = container_of(dwork, struct tick_work, work); 5850 int cpu = twork->cpu; 5851 struct rq *rq = cpu_rq(cpu); 5852 int os; 5853 5854 /* 5855 * Handle the tick only if it appears the remote CPU is running in full 5856 * dynticks mode. The check is racy by nature, but missing a tick or 5857 * having one too much is no big deal because the scheduler tick updates 5858 * statistics and checks timeslices in a time-independent way, regardless 5859 * of when exactly it is running. 5860 */ 5861 if (tick_nohz_tick_stopped_cpu(cpu)) { 5862 guard(rq_lock_irq)(rq); 5863 struct task_struct *curr = rq->curr; 5864 5865 if (cpu_online(cpu)) { 5866 /* 5867 * Since this is a remote tick for full dynticks mode, 5868 * we are always sure that there is no proxy (only a 5869 * single task is running). 5870 */ 5871 WARN_ON_ONCE(rq->curr != rq->donor); 5872 update_rq_clock(rq); 5873 5874 if (!is_idle_task(curr)) { 5875 /* 5876 * Make sure the next tick runs within a 5877 * reasonable amount of time. 5878 */ 5879 u64 delta = rq_clock_task(rq) - curr->se.exec_start; 5880 WARN_ON_ONCE(delta > (u64)NSEC_PER_SEC * 30); 5881 } 5882 curr->sched_class->task_tick(rq, curr, 0); 5883 5884 calc_load_nohz_remote(rq); 5885 } 5886 } 5887 5888 /* 5889 * Run the remote tick once per second (1Hz). This arbitrary 5890 * frequency is large enough to avoid overload but short enough 5891 * to keep scheduler internal stats reasonably up to date. But 5892 * first update state to reflect hotplug activity if required. 5893 */ 5894 os = atomic_fetch_add_unless(&twork->state, -1, TICK_SCHED_REMOTE_RUNNING); 5895 WARN_ON_ONCE(os == TICK_SCHED_REMOTE_OFFLINE); 5896 if (os == TICK_SCHED_REMOTE_RUNNING) 5897 queue_delayed_work(system_dfl_wq, dwork, HZ); 5898 } 5899 5900 static void sched_tick_start(int cpu) 5901 { 5902 int os; 5903 struct tick_work *twork; 5904 5905 if (housekeeping_cpu(cpu, HK_TYPE_KERNEL_NOISE)) 5906 return; 5907 5908 WARN_ON_ONCE(!tick_work_cpu); 5909 5910 twork = per_cpu_ptr(tick_work_cpu, cpu); 5911 os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_RUNNING); 5912 WARN_ON_ONCE(os == TICK_SCHED_REMOTE_RUNNING); 5913 if (os == TICK_SCHED_REMOTE_OFFLINE) { 5914 twork->cpu = cpu; 5915 INIT_DELAYED_WORK(&twork->work, sched_tick_remote); 5916 queue_delayed_work(system_dfl_wq, &twork->work, HZ); 5917 } 5918 } 5919 5920 #ifdef CONFIG_HOTPLUG_CPU 5921 static void sched_tick_stop(int cpu) 5922 { 5923 struct tick_work *twork; 5924 int os; 5925 5926 if (housekeeping_cpu(cpu, HK_TYPE_KERNEL_NOISE)) 5927 return; 5928 5929 WARN_ON_ONCE(!tick_work_cpu); 5930 5931 twork = per_cpu_ptr(tick_work_cpu, cpu); 5932 /* There cannot be competing actions, but don't rely on stop-machine. */ 5933 os = atomic_xchg(&twork->state, TICK_SCHED_REMOTE_OFFLINING); 5934 WARN_ON_ONCE(os != TICK_SCHED_REMOTE_RUNNING); 5935 /* Don't cancel, as this would mess up the state machine. */ 5936 } 5937 #endif /* CONFIG_HOTPLUG_CPU */ 5938 5939 int __init sched_tick_offload_init(void) 5940 { 5941 tick_work_cpu = alloc_percpu(struct tick_work); 5942 BUG_ON(!tick_work_cpu); 5943 return 0; 5944 } 5945 5946 #else /* !CONFIG_NO_HZ_FULL: */ 5947 static inline void sched_tick_start(int cpu) { } 5948 static inline void sched_tick_stop(int cpu) { } 5949 #endif /* !CONFIG_NO_HZ_FULL */ 5950 5951 #if defined(CONFIG_PREEMPTION) && (defined(CONFIG_DEBUG_PREEMPT) || \ 5952 defined(CONFIG_TRACE_PREEMPT_TOGGLE)) 5953 /* 5954 * If the value passed in is equal to the current preempt count 5955 * then we just disabled preemption. Start timing the latency. 5956 */ 5957 static inline void preempt_latency_start(int val) 5958 { 5959 if (preempt_count() == val) { 5960 unsigned long ip = get_lock_parent_ip(); 5961 #ifdef CONFIG_DEBUG_PREEMPT 5962 current->preempt_disable_ip = ip; 5963 #endif 5964 trace_preempt_off(CALLER_ADDR0, ip); 5965 } 5966 } 5967 5968 void preempt_count_add(int val) 5969 { 5970 #ifdef CONFIG_DEBUG_PREEMPT 5971 /* 5972 * Underflow? 5973 * 5974 * Cannot detect underflow based on the current preempt_count() value 5975 * if using HAS_SEPARATE_PREEMPT_RESCHED_BITS because preempt count takes all 32 5976 * bits. 5977 */ 5978 if (!IS_ENABLED(CONFIG_HAS_SEPARATE_PREEMPT_RESCHED_BITS) && 5979 DEBUG_LOCKS_WARN_ON((preempt_count() < 0))) 5980 return; 5981 #endif 5982 __preempt_count_add(val); 5983 #ifdef CONFIG_DEBUG_PREEMPT 5984 /* 5985 * Spinlock count overflowing soon? 5986 */ 5987 DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >= 5988 PREEMPT_MASK - 10); 5989 #endif 5990 preempt_latency_start(val); 5991 } 5992 EXPORT_SYMBOL(preempt_count_add); 5993 NOKPROBE_SYMBOL(preempt_count_add); 5994 5995 /* 5996 * If the value passed in equals to the current preempt count 5997 * then we just enabled preemption. Stop timing the latency. 5998 */ 5999 static inline void preempt_latency_stop(int val) 6000 { 6001 if (preempt_count() == val) 6002 trace_preempt_on(CALLER_ADDR0, get_lock_parent_ip()); 6003 } 6004 6005 void preempt_count_sub(int val) 6006 { 6007 #ifdef CONFIG_DEBUG_PREEMPT 6008 /* 6009 * Underflow? 6010 */ 6011 unsigned int uval = val; 6012 unsigned int pc = preempt_count(); 6013 6014 if (DEBUG_LOCKS_WARN_ON(pc - uval > pc)) 6015 return; 6016 /* 6017 * Is the spinlock portion underflowing? 6018 */ 6019 if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) && 6020 !(preempt_count() & PREEMPT_MASK))) 6021 return; 6022 #endif 6023 6024 preempt_latency_stop(val); 6025 __preempt_count_sub(val); 6026 } 6027 EXPORT_SYMBOL(preempt_count_sub); 6028 NOKPROBE_SYMBOL(preempt_count_sub); 6029 6030 #else 6031 static inline void preempt_latency_start(int val) { } 6032 static inline void preempt_latency_stop(int val) { } 6033 #endif 6034 6035 static inline unsigned long get_preempt_disable_ip(struct task_struct *p) 6036 { 6037 #ifdef CONFIG_DEBUG_PREEMPT 6038 return p->preempt_disable_ip; 6039 #else 6040 return 0; 6041 #endif 6042 } 6043 6044 /* 6045 * Print scheduling while atomic bug: 6046 */ 6047 static noinline void __schedule_bug(struct task_struct *prev) 6048 { 6049 /* Save this before calling printk(), since that will clobber it */ 6050 unsigned long preempt_disable_ip = get_preempt_disable_ip(current); 6051 6052 if (oops_in_progress) 6053 return; 6054 6055 printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n", 6056 prev->comm, prev->pid, preempt_count()); 6057 6058 debug_show_held_locks(prev); 6059 print_modules(); 6060 if (irqs_disabled()) 6061 print_irqtrace_events(prev); 6062 if (IS_ENABLED(CONFIG_DEBUG_PREEMPT)) { 6063 pr_err("Preemption disabled at:"); 6064 print_ip_sym(KERN_ERR, preempt_disable_ip); 6065 } 6066 check_panic_on_warn("scheduling while atomic"); 6067 6068 dump_stack(); 6069 add_taint(TAINT_WARN, LOCKDEP_STILL_OK); 6070 } 6071 6072 /* 6073 * Various schedule()-time debugging checks and statistics: 6074 */ 6075 static inline void schedule_debug(struct task_struct *prev, bool preempt) 6076 { 6077 #ifdef CONFIG_SCHED_STACK_END_CHECK 6078 if (task_stack_end_corrupted(prev)) 6079 panic("corrupted stack end detected inside scheduler\n"); 6080 6081 if (task_scs_end_corrupted(prev)) 6082 panic("corrupted shadow stack detected inside scheduler\n"); 6083 #endif 6084 6085 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP 6086 if (!preempt && READ_ONCE(prev->__state) && prev->non_block_count) { 6087 printk(KERN_ERR "BUG: scheduling in a non-blocking section: %s/%d/%i\n", 6088 prev->comm, prev->pid, prev->non_block_count); 6089 dump_stack(); 6090 add_taint(TAINT_WARN, LOCKDEP_STILL_OK); 6091 } 6092 #endif 6093 6094 if (unlikely(in_atomic_preempt_off())) { 6095 __schedule_bug(prev); 6096 preempt_count_set(PREEMPT_DISABLED); 6097 } 6098 rcu_sleep_check(); 6099 WARN_ON_ONCE(ct_state() == CT_STATE_USER); 6100 6101 profile_hit(SCHED_PROFILING, __builtin_return_address(0)); 6102 6103 schedstat_inc(this_rq()->sched_count); 6104 } 6105 6106 static void prev_balance(struct rq *rq, struct rq_flags *rf) 6107 { 6108 const struct sched_class *start_class = rq->donor->sched_class; 6109 const struct sched_class *class; 6110 6111 /* 6112 * We must do the balancing pass before put_prev_task(), such 6113 * that when we release the rq->lock the task is in the same 6114 * state as before we took rq->lock. 6115 * 6116 * We can terminate the balance pass as soon as we know there is 6117 * a runnable task of @class priority or higher. 6118 */ 6119 for_active_class_range(class, start_class, &idle_sched_class) { 6120 if (class->balance && class->balance(rq, rf)) 6121 break; 6122 } 6123 } 6124 6125 /* 6126 * Pick up the highest-prio task: 6127 */ 6128 static inline struct task_struct * 6129 __pick_next_task(struct rq *rq, struct rq_flags *rf) 6130 __must_hold(__rq_lockp(rq)) 6131 { 6132 const struct sched_class *class; 6133 struct task_struct *p; 6134 6135 rq->dl_server = NULL; 6136 6137 if (scx_enabled()) 6138 goto restart; 6139 6140 /* 6141 * Optimization: we know that if all tasks are in the fair class we can 6142 * call that function directly, but only if the @prev task wasn't of a 6143 * higher scheduling class, because otherwise those lose the 6144 * opportunity to pull in more work from other CPUs. 6145 */ 6146 if (likely(!sched_class_above(rq->donor->sched_class, &fair_sched_class) && 6147 rq->nr_running == rq->cfs.h_nr_queued)) { 6148 6149 p = pick_task_fair(rq, rf); 6150 if (unlikely(p == RETRY_TASK)) 6151 goto restart; 6152 6153 /* Assume the next prioritized class is idle_sched_class */ 6154 if (!p) 6155 p = pick_task_idle(rq, rf); 6156 6157 put_prev_set_next_task(rq, rq->donor, p); 6158 return p; 6159 } 6160 6161 restart: 6162 prev_balance(rq, rf); 6163 6164 for_each_active_class(class) { 6165 p = class->pick_task(rq, rf); 6166 if (unlikely(p == RETRY_TASK)) 6167 goto restart; 6168 if (p) { 6169 put_prev_set_next_task(rq, rq->donor, p); 6170 return p; 6171 } 6172 } 6173 6174 BUG(); /* The idle class should always have a runnable task. */ 6175 } 6176 6177 #ifdef CONFIG_SCHED_CORE 6178 static inline bool is_task_rq_idle(struct task_struct *t) 6179 { 6180 return (task_rq(t)->idle == t); 6181 } 6182 6183 static inline bool cookie_equals(struct task_struct *a, unsigned long cookie) 6184 { 6185 return is_task_rq_idle(a) || (a->core_cookie == cookie); 6186 } 6187 6188 static inline bool cookie_match(struct task_struct *a, struct task_struct *b) 6189 { 6190 if (is_task_rq_idle(a) || is_task_rq_idle(b)) 6191 return true; 6192 6193 return a->core_cookie == b->core_cookie; 6194 } 6195 6196 /* 6197 * Careful; this can return RETRY_TASK, it does not include the retry-loop 6198 * itself due to the whole SMT pick retry thing below. 6199 */ 6200 static inline struct task_struct *pick_task(struct rq *rq, struct rq_flags *rf) 6201 { 6202 const struct sched_class *class; 6203 struct task_struct *p; 6204 6205 rq->dl_server = NULL; 6206 6207 for_each_active_class(class) { 6208 p = class->pick_task(rq, rf); 6209 if (p) 6210 return p; 6211 } 6212 6213 BUG(); /* The idle class should always have a runnable task. */ 6214 } 6215 6216 extern void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi); 6217 6218 static void queue_core_balance(struct rq *rq); 6219 6220 static struct task_struct * 6221 pick_next_task(struct rq *rq, struct rq_flags *rf) 6222 __must_hold(__rq_lockp(rq)) 6223 { 6224 struct task_struct *next, *p, *max; 6225 const struct cpumask *smt_mask; 6226 bool fi_before = false; 6227 bool core_clock_updated = (rq == rq->core); 6228 unsigned long cookie; 6229 int i, cpu, occ = 0; 6230 struct rq *rq_i; 6231 bool need_sync; 6232 6233 if (!sched_core_enabled(rq)) 6234 return __pick_next_task(rq, rf); 6235 6236 cpu = cpu_of(rq); 6237 6238 /* Stopper task is switching into idle, no need core-wide selection. */ 6239 if (cpu_is_offline(cpu)) { 6240 /* 6241 * Reset core_pick so that we don't enter the fastpath when 6242 * coming online. core_pick would already be migrated to 6243 * another cpu during offline. 6244 */ 6245 rq->core_pick = NULL; 6246 rq->core_dl_server = NULL; 6247 return __pick_next_task(rq, rf); 6248 } 6249 6250 /* 6251 * If there were no {en,de}queues since we picked (IOW, the task 6252 * pointers are all still valid), and we haven't scheduled the last 6253 * pick yet, do so now. 6254 * 6255 * rq->core_pick can be NULL if no selection was made for a CPU because 6256 * it was either offline or went offline during a sibling's core-wide 6257 * selection. In this case, do a core-wide selection. 6258 */ 6259 if (rq->core->core_pick_seq == rq->core->core_task_seq && 6260 rq->core->core_pick_seq != rq->core_sched_seq && 6261 rq->core_pick) { 6262 WRITE_ONCE(rq->core_sched_seq, rq->core->core_pick_seq); 6263 6264 next = rq->core_pick; 6265 rq->dl_server = rq->core_dl_server; 6266 rq->core_pick = NULL; 6267 rq->core_dl_server = NULL; 6268 goto out_set_next; 6269 } 6270 6271 prev_balance(rq, rf); 6272 6273 smt_mask = cpu_smt_mask(cpu); 6274 need_sync = !!rq->core->core_cookie; 6275 6276 /* reset state */ 6277 rq->core->core_cookie = 0UL; 6278 if (rq->core->core_forceidle_count) { 6279 if (!core_clock_updated) { 6280 update_rq_clock(rq->core); 6281 core_clock_updated = true; 6282 } 6283 sched_core_account_forceidle(rq); 6284 /* reset after accounting force idle */ 6285 rq->core->core_forceidle_start = 0; 6286 rq->core->core_forceidle_count = 0; 6287 rq->core->core_forceidle_occupation = 0; 6288 need_sync = true; 6289 fi_before = true; 6290 } 6291 6292 /* 6293 * core->core_task_seq, core->core_pick_seq, rq->core_sched_seq 6294 * 6295 * @task_seq guards the task state ({en,de}queues) 6296 * @pick_seq is the @task_seq we did a selection on 6297 * @sched_seq is the @pick_seq we scheduled 6298 * 6299 * However, preemptions can cause multiple picks on the same task set. 6300 * 'Fix' this by also increasing @task_seq for every pick. 6301 */ 6302 rq->core->core_task_seq++; 6303 6304 /* 6305 * Optimize for common case where this CPU has no cookies 6306 * and there are no cookied tasks running on siblings. 6307 */ 6308 if (!need_sync) { 6309 restart_single: 6310 next = pick_task(rq, rf); 6311 if (unlikely(next == RETRY_TASK)) 6312 goto restart_single; 6313 if (!next->core_cookie) { 6314 rq->core_pick = NULL; 6315 rq->core_dl_server = NULL; 6316 /* 6317 * For robustness, update the min_vruntime_fi for 6318 * unconstrained picks as well. 6319 */ 6320 WARN_ON_ONCE(fi_before); 6321 task_vruntime_update(rq, next, false); 6322 goto out_set_next; 6323 } 6324 } 6325 6326 /* 6327 * For each thread: do the regular task pick and find the max prio task 6328 * amongst them. 6329 * 6330 * Tie-break prio towards the current CPU 6331 */ 6332 restart_multi: 6333 max = NULL; 6334 for_each_cpu_wrap(i, smt_mask, cpu) { 6335 rq_i = cpu_rq(i); 6336 6337 /* 6338 * Current cpu always has its clock updated on entrance to 6339 * pick_next_task(). If the current cpu is not the core, 6340 * the core may also have been updated above. 6341 */ 6342 if (i != cpu && (rq_i != rq->core || !core_clock_updated)) 6343 update_rq_clock(rq_i); 6344 6345 p = pick_task(rq_i, rf); 6346 if (unlikely(p == RETRY_TASK)) 6347 goto restart_multi; 6348 6349 rq_i->core_pick = p; 6350 rq_i->core_dl_server = rq_i->dl_server; 6351 6352 if (!max || prio_less(max, p, fi_before)) 6353 max = p; 6354 } 6355 6356 cookie = rq->core->core_cookie = max->core_cookie; 6357 6358 /* 6359 * For each thread: try and find a runnable task that matches @max or 6360 * force idle. 6361 */ 6362 for_each_cpu(i, smt_mask) { 6363 rq_i = cpu_rq(i); 6364 p = rq_i->core_pick; 6365 6366 if (!cookie_equals(p, cookie)) { 6367 p = NULL; 6368 if (cookie) 6369 p = sched_core_find(rq_i, cookie); 6370 if (!p) 6371 p = idle_sched_class.pick_task(rq_i, rf); 6372 } 6373 6374 rq_i->core_pick = p; 6375 rq_i->core_dl_server = NULL; 6376 6377 if (p == rq_i->idle) { 6378 if (rq_i->nr_running) { 6379 rq->core->core_forceidle_count++; 6380 if (!fi_before) 6381 rq->core->core_forceidle_seq++; 6382 } 6383 } else { 6384 occ++; 6385 } 6386 } 6387 6388 if (schedstat_enabled() && rq->core->core_forceidle_count) { 6389 rq->core->core_forceidle_start = rq_clock(rq->core); 6390 rq->core->core_forceidle_occupation = occ; 6391 } 6392 6393 rq->core->core_pick_seq = rq->core->core_task_seq; 6394 next = rq->core_pick; 6395 rq->core_sched_seq = rq->core->core_pick_seq; 6396 6397 /* Something should have been selected for current CPU */ 6398 WARN_ON_ONCE(!next); 6399 6400 /* 6401 * Reschedule siblings 6402 * 6403 * NOTE: L1TF -- at this point we're no longer running the old task and 6404 * sending an IPI (below) ensures the sibling will no longer be running 6405 * their task. This ensures there is no inter-sibling overlap between 6406 * non-matching user state. 6407 */ 6408 for_each_cpu(i, smt_mask) { 6409 rq_i = cpu_rq(i); 6410 6411 /* 6412 * An online sibling might have gone offline before a task 6413 * could be picked for it, or it might be offline but later 6414 * happen to come online, but its too late and nothing was 6415 * picked for it. That's Ok - it will pick tasks for itself, 6416 * so ignore it. 6417 */ 6418 if (!rq_i->core_pick) 6419 continue; 6420 6421 /* 6422 * Update for new !FI->FI transitions, or if continuing to be in !FI: 6423 * fi_before fi update? 6424 * 0 0 1 6425 * 0 1 1 6426 * 1 0 1 6427 * 1 1 0 6428 */ 6429 if (!(fi_before && rq->core->core_forceidle_count)) 6430 task_vruntime_update(rq_i, rq_i->core_pick, !!rq->core->core_forceidle_count); 6431 6432 rq_i->core_pick->core_occupation = occ; 6433 6434 if (i == cpu) { 6435 rq_i->core_pick = NULL; 6436 rq_i->core_dl_server = NULL; 6437 continue; 6438 } 6439 6440 /* Did we break L1TF mitigation requirements? */ 6441 WARN_ON_ONCE(!cookie_match(next, rq_i->core_pick)); 6442 6443 if (rq_i->curr == rq_i->core_pick) { 6444 rq_i->core_pick = NULL; 6445 rq_i->core_dl_server = NULL; 6446 continue; 6447 } 6448 6449 resched_curr(rq_i); 6450 } 6451 6452 out_set_next: 6453 put_prev_set_next_task(rq, rq->donor, next); 6454 if (rq->core->core_forceidle_count && next == rq->idle) 6455 queue_core_balance(rq); 6456 6457 return next; 6458 } 6459 6460 static bool try_steal_cookie(int this, int that) 6461 { 6462 struct rq *dst = cpu_rq(this), *src = cpu_rq(that); 6463 struct task_struct *p; 6464 unsigned long cookie; 6465 bool success = false; 6466 6467 guard(irq)(); 6468 guard(double_rq_lock)(dst, src); 6469 6470 cookie = dst->core->core_cookie; 6471 if (!cookie) 6472 return false; 6473 6474 if (dst->curr != dst->idle) 6475 return false; 6476 6477 p = sched_core_find(src, cookie); 6478 if (!p) 6479 return false; 6480 6481 do { 6482 if (p == src->core_pick || p == src->curr) 6483 goto next; 6484 6485 if (!is_cpu_allowed(p, this)) 6486 goto next; 6487 6488 if (p->core_occupation > dst->idle->core_occupation) 6489 goto next; 6490 /* 6491 * sched_core_find() and sched_core_next() will ensure 6492 * that task @p is not throttled now, we also need to 6493 * check whether the runqueue of the destination CPU is 6494 * being throttled. 6495 */ 6496 if (sched_task_is_throttled(p, this)) 6497 goto next; 6498 6499 move_queued_task_locked(src, dst, p); 6500 resched_curr(dst); 6501 6502 success = true; 6503 break; 6504 6505 next: 6506 p = sched_core_next(p, cookie); 6507 } while (p); 6508 6509 return success; 6510 } 6511 6512 static bool steal_cookie_task(int cpu, struct sched_domain *sd) 6513 { 6514 int i; 6515 6516 for_each_cpu_wrap(i, sched_domain_span(sd), cpu + 1) { 6517 if (i == cpu) 6518 continue; 6519 6520 if (need_resched()) 6521 break; 6522 6523 if (try_steal_cookie(cpu, i)) 6524 return true; 6525 } 6526 6527 return false; 6528 } 6529 6530 static void sched_core_balance(struct rq *rq) 6531 __must_hold(__rq_lockp(rq)) 6532 { 6533 struct sched_domain *sd; 6534 int cpu = cpu_of(rq); 6535 6536 guard(preempt)(); 6537 guard(rcu)(); 6538 6539 raw_spin_rq_unlock_irq(rq); 6540 for_each_domain(cpu, sd) { 6541 if (need_resched()) 6542 break; 6543 6544 if (steal_cookie_task(cpu, sd)) 6545 break; 6546 } 6547 raw_spin_rq_lock_irq(rq); 6548 } 6549 6550 static DEFINE_PER_CPU(struct balance_callback, core_balance_head); 6551 6552 static void queue_core_balance(struct rq *rq) 6553 { 6554 if (!sched_core_enabled(rq)) 6555 return; 6556 6557 if (!rq->core->core_cookie) 6558 return; 6559 6560 if (!rq->nr_running) /* not forced idle */ 6561 return; 6562 6563 queue_balance_callback(rq, &per_cpu(core_balance_head, rq->cpu), sched_core_balance); 6564 } 6565 6566 DEFINE_LOCK_GUARD_1(core_lock, int, 6567 sched_core_lock(*_T->lock, &_T->flags), 6568 sched_core_unlock(*_T->lock, &_T->flags), 6569 unsigned long flags) 6570 6571 static void sched_core_cpu_starting(unsigned int cpu) 6572 { 6573 const struct cpumask *smt_mask = cpu_smt_mask(cpu); 6574 struct rq *rq = cpu_rq(cpu), *core_rq = NULL; 6575 int t; 6576 6577 guard(core_lock)(&cpu); 6578 6579 WARN_ON_ONCE(rq->core != rq); 6580 6581 /* if we're the first, we'll be our own leader */ 6582 if (cpumask_weight(smt_mask) == 1) 6583 return; 6584 6585 /* find the leader */ 6586 for_each_cpu(t, smt_mask) { 6587 if (t == cpu) 6588 continue; 6589 rq = cpu_rq(t); 6590 if (rq->core == rq) { 6591 core_rq = rq; 6592 break; 6593 } 6594 } 6595 6596 if (WARN_ON_ONCE(!core_rq)) /* whoopsie */ 6597 return; 6598 6599 /* install and validate core_rq */ 6600 for_each_cpu(t, smt_mask) { 6601 rq = cpu_rq(t); 6602 6603 if (t == cpu) 6604 rq->core = core_rq; 6605 6606 WARN_ON_ONCE(rq->core != core_rq); 6607 } 6608 } 6609 6610 static void sched_core_cpu_deactivate(unsigned int cpu) 6611 { 6612 const struct cpumask *smt_mask = cpu_smt_mask(cpu); 6613 struct rq *rq = cpu_rq(cpu), *core_rq = NULL; 6614 int t; 6615 6616 guard(core_lock)(&cpu); 6617 6618 /* if we're the last man standing, nothing to do */ 6619 if (cpumask_weight(smt_mask) == 1) { 6620 WARN_ON_ONCE(rq->core != rq); 6621 return; 6622 } 6623 6624 /* if we're not the leader, nothing to do */ 6625 if (rq->core != rq) 6626 return; 6627 6628 /* find a new leader */ 6629 for_each_cpu(t, smt_mask) { 6630 if (t == cpu) 6631 continue; 6632 core_rq = cpu_rq(t); 6633 break; 6634 } 6635 6636 if (WARN_ON_ONCE(!core_rq)) /* impossible */ 6637 return; 6638 6639 /* copy the shared state to the new leader */ 6640 core_rq->core_task_seq = rq->core_task_seq; 6641 core_rq->core_pick_seq = rq->core_pick_seq; 6642 core_rq->core_cookie = rq->core_cookie; 6643 core_rq->core_forceidle_count = rq->core_forceidle_count; 6644 core_rq->core_forceidle_seq = rq->core_forceidle_seq; 6645 core_rq->core_forceidle_occupation = rq->core_forceidle_occupation; 6646 6647 /* 6648 * Accounting edge for forced idle is handled in pick_next_task(). 6649 * Don't need another one here, since the hotplug thread shouldn't 6650 * have a cookie. 6651 */ 6652 core_rq->core_forceidle_start = 0; 6653 6654 /* install new leader */ 6655 for_each_cpu(t, smt_mask) { 6656 rq = cpu_rq(t); 6657 rq->core = core_rq; 6658 } 6659 } 6660 6661 static inline void sched_core_cpu_dying(unsigned int cpu) 6662 { 6663 struct rq *rq = cpu_rq(cpu); 6664 6665 if (rq->core != rq) 6666 rq->core = rq; 6667 } 6668 6669 #else /* !CONFIG_SCHED_CORE: */ 6670 6671 static inline void sched_core_cpu_starting(unsigned int cpu) {} 6672 static inline void sched_core_cpu_deactivate(unsigned int cpu) {} 6673 static inline void sched_core_cpu_dying(unsigned int cpu) {} 6674 6675 static struct task_struct * 6676 pick_next_task(struct rq *rq, struct rq_flags *rf) 6677 __must_hold(__rq_lockp(rq)) 6678 { 6679 return __pick_next_task(rq, rf); 6680 } 6681 6682 #endif /* !CONFIG_SCHED_CORE */ 6683 6684 /* 6685 * Constants for the sched_mode argument of __schedule(). 6686 * 6687 * The mode argument allows RT enabled kernels to differentiate a 6688 * preemption from blocking on an 'sleeping' spin/rwlock. 6689 */ 6690 #define SM_IDLE (-1) 6691 #define SM_NONE 0 6692 #define SM_PREEMPT 1 6693 #define SM_RTLOCK_WAIT 2 6694 6695 /* 6696 * Helper function for __schedule() 6697 * 6698 * Tries to deactivate the task, unless the should_block arg 6699 * is false or if a signal is pending. In the case a signal 6700 * is pending, marks the task's __state as RUNNING (and clear 6701 * blocked_on). 6702 */ 6703 static bool try_to_block_task(struct rq *rq, struct task_struct *p, 6704 unsigned long *task_state_p, bool should_block) 6705 { 6706 unsigned long task_state = *task_state_p; 6707 6708 WARN_ON_ONCE(p->is_blocked); 6709 6710 if (signal_pending_state(task_state, p)) { 6711 WRITE_ONCE(p->__state, TASK_RUNNING); 6712 *task_state_p = TASK_RUNNING; 6713 clear_task_blocked_on(p, NULL); 6714 6715 return false; 6716 } 6717 6718 p->is_blocked = 1; 6719 6720 /* 6721 * We check should_block after signal_pending because we 6722 * will want to wake the task in that case. But if 6723 * should_block is false, its likely due to the task being 6724 * blocked on a mutex, and we want to keep it on the runqueue 6725 * to be selectable for proxy-execution. 6726 */ 6727 if (!should_block) 6728 return false; 6729 6730 block_task(rq, p, task_state); 6731 return true; 6732 } 6733 6734 #ifdef CONFIG_SCHED_PROXY_EXEC 6735 static inline void proxy_set_task_cpu(struct task_struct *p, int cpu) 6736 { 6737 unsigned int wake_cpu; 6738 6739 /* 6740 * Since we are enqueuing a blocked task on a cpu it may 6741 * not be able to run on, preserve wake_cpu when we 6742 * __set_task_cpu so we can return the task to where it 6743 * was previously runnable. 6744 */ 6745 wake_cpu = p->wake_cpu; 6746 __set_task_cpu(p, cpu); 6747 p->wake_cpu = wake_cpu; 6748 } 6749 6750 static inline struct task_struct *proxy_resched_idle(struct rq *rq) 6751 { 6752 put_prev_set_next_task(rq, rq->donor, rq->idle); 6753 rq->next_class = &idle_sched_class; 6754 rq_set_donor(rq, rq->idle); 6755 set_tsk_need_resched(rq->idle); 6756 return rq->idle; 6757 } 6758 6759 static void proxy_deactivate(struct rq *rq, struct task_struct *donor) 6760 { 6761 unsigned long state = READ_ONCE(donor->__state); 6762 6763 WARN_ON_ONCE(state == TASK_RUNNING); 6764 WARN_ON_ONCE(donor->blocked_on); 6765 /* 6766 * Because we got donor from pick_next_task(), it is *crucial* 6767 * that we call proxy_resched_idle() before we deactivate it. 6768 * As once we deactivate donor, donor->on_rq is set to zero, 6769 * which allows ttwu() to immediately try to wake the task on 6770 * another rq. So we cannot use *any* references to donor 6771 * after that point. So things like cfs_rq->curr or rq->donor 6772 * need to be changed from next *before* we deactivate. 6773 */ 6774 proxy_resched_idle(rq); 6775 block_task(rq, donor, state); 6776 } 6777 6778 static inline void proxy_release_rq_lock(struct rq *rq, struct rq_flags *rf) 6779 __releases(__rq_lockp(rq)) 6780 { 6781 /* 6782 * The class scheduler may have queued a balance callback 6783 * from pick_next_task() called earlier. 6784 * 6785 * So here we have to zap callbacks before unlocking the rq 6786 * as another CPU may jump in and call sched_balance_rq 6787 * which can trip the warning in rq_pin_lock() if we 6788 * leave callbacks set. 6789 * 6790 * After we later reaquire the rq lock, we will force __schedule() 6791 * to pick_again, so the callbacks will get re-established. 6792 */ 6793 zap_balance_callbacks(rq); 6794 rq_unpin_lock(rq, rf); 6795 raw_spin_rq_unlock(rq); 6796 } 6797 6798 static inline void proxy_reacquire_rq_lock(struct rq *rq, struct rq_flags *rf) 6799 __acquires(__rq_lockp(rq)) 6800 { 6801 raw_spin_rq_lock(rq); 6802 rq_repin_lock(rq, rf); 6803 update_rq_clock(rq); 6804 } 6805 6806 /* 6807 * If the blocked-on relationship crosses CPUs, migrate @p to the 6808 * owner's CPU. 6809 * 6810 * This is because we must respect the CPU affinity of execution 6811 * contexts (owner) but we can ignore affinity for scheduling 6812 * contexts (@p). So we have to move scheduling contexts towards 6813 * potential execution contexts. 6814 * 6815 * Note: The owner can disappear, but simply migrate to @target_cpu 6816 * and leave that CPU to sort things out. 6817 */ 6818 static void proxy_migrate_task(struct rq *rq, struct rq_flags *rf, 6819 struct task_struct *p, int target_cpu) 6820 __must_hold(__rq_lockp(rq)) 6821 { 6822 struct rq *target_rq = cpu_rq(target_cpu); 6823 6824 lockdep_assert_rq_held(rq); 6825 WARN_ON(p == rq->curr); 6826 /* 6827 * Since we are migrating a blocked donor, it could be rq->donor, 6828 * and we want to make sure there aren't any references from this 6829 * rq to it before we drop the lock. This avoids another cpu 6830 * jumping in and grabbing the rq lock and referencing rq->donor 6831 * or cfs_rq->curr, etc after we have migrated it to another cpu, 6832 * and before we pick_again in __schedule. 6833 * 6834 * So call proxy_resched_idle() to drop the rq->donor references 6835 * before we release the lock. 6836 */ 6837 proxy_resched_idle(rq); 6838 6839 deactivate_task(rq, p, DEQUEUE_NOCLOCK); 6840 proxy_set_task_cpu(p, target_cpu); 6841 6842 proxy_release_rq_lock(rq, rf); 6843 6844 attach_one_task(target_rq, p); 6845 6846 proxy_reacquire_rq_lock(rq, rf); 6847 } 6848 6849 /* 6850 * Find runnable lock owner to proxy for mutex blocked donor 6851 * 6852 * Follow the blocked-on relation: 6853 * 6854 * ,-> task 6855 * | | blocked-on 6856 * | v 6857 * blocked_donor | mutex 6858 * | | owner 6859 * | v 6860 * `-- task 6861 * 6862 * and set the blocked_donor relation, this latter is used by the mutex 6863 * code to find which (blocked) task to hand-off to. 6864 * 6865 * Lock order: 6866 * 6867 * p->pi_lock 6868 * rq->lock 6869 * mutex->wait_lock 6870 * p->blocked_lock 6871 * 6872 * Returns the task that is going to be used as execution context (the one 6873 * that is actually going to be run on cpu_of(rq)). 6874 */ 6875 static struct task_struct * 6876 find_proxy_task(struct rq *rq, struct task_struct *donor, struct rq_flags *rf) 6877 __must_hold(__rq_lockp(rq)) 6878 { 6879 struct task_struct *owner = NULL; 6880 bool curr_in_chain = false; 6881 int this_cpu = cpu_of(rq); 6882 struct task_struct *p; 6883 int owner_cpu; 6884 6885 /* Follow blocked_on chain. */ 6886 for (p = donor; p->is_blocked; p = owner) { 6887 /* if its PROXY_WAKING, do return migration or run if current */ 6888 struct mutex *mutex = p->blocked_on; 6889 if (!mutex) { 6890 clear_task_blocked_on(p, mutex); 6891 if (task_current(rq, p)) { 6892 p->is_blocked = 0; 6893 return p; 6894 } 6895 goto deactivate; 6896 } 6897 6898 /* 6899 * By taking mutex->wait_lock we hold off concurrent mutex_unlock() 6900 * and ensure @owner sticks around. 6901 */ 6902 guard(raw_spinlock)(&mutex->wait_lock); 6903 guard(raw_spinlock)(&p->blocked_lock); 6904 6905 /* Check again that p is blocked with blocked_lock held */ 6906 if (mutex != __get_task_blocked_on(p)) { 6907 /* 6908 * Something changed in the blocked_on chain and 6909 * we don't know if only at this level. So, let's 6910 * just bail out completely and let __schedule() 6911 * figure things out (pick_again loop). 6912 */ 6913 return NULL; 6914 } 6915 6916 if (task_current(rq, p)) 6917 curr_in_chain = true; 6918 6919 owner = __mutex_owner(mutex); 6920 if (!owner) { 6921 /* 6922 * If there is no owner, either clear blocked_on 6923 * and return p (if it is current and safe to 6924 * just run on this rq), or return-migrate the task. 6925 */ 6926 __clear_task_blocked_on(p, NULL); 6927 if (task_current(rq, p)) { 6928 p->is_blocked = 0; 6929 return p; 6930 } 6931 goto deactivate; 6932 } 6933 6934 if (!READ_ONCE(owner->on_rq) || owner->se.sched_delayed) { 6935 /* XXX Don't handle blocked owners/delayed dequeue yet */ 6936 if (curr_in_chain) 6937 return proxy_resched_idle(rq); 6938 __clear_task_blocked_on(p, NULL); 6939 goto deactivate; 6940 } 6941 6942 owner_cpu = task_cpu(owner); 6943 if (owner_cpu != this_cpu) { 6944 /* 6945 * @owner can disappear, simply migrate to @owner_cpu 6946 * and leave that CPU to sort things out. 6947 */ 6948 if (curr_in_chain) 6949 return proxy_resched_idle(rq); 6950 goto migrate_task; 6951 } 6952 6953 if (task_on_rq_migrating(owner)) { 6954 /* 6955 * One of the chain of mutex owners is currently migrating to this 6956 * CPU, but has not yet been enqueued because we are holding the 6957 * rq lock. As a simple solution, just schedule rq->idle to give 6958 * the migration a chance to complete. Much like the migrate_task 6959 * case we should end up back in find_proxy_task(), this time 6960 * hopefully with all relevant tasks already enqueued. 6961 */ 6962 return proxy_resched_idle(rq); 6963 } 6964 6965 /* 6966 * Its possible to race where after we check owner->on_rq 6967 * but before we check (owner_cpu != this_cpu) that the 6968 * task on another cpu was migrated back to this cpu. In 6969 * that case it could slip by our checks. So double check 6970 * we are still on this cpu and not migrating. If we get 6971 * inconsistent results, try again. 6972 */ 6973 if (!task_on_rq_queued(owner) || task_cpu(owner) != this_cpu) 6974 return NULL; 6975 6976 if (owner == p) { 6977 /* 6978 * It's possible we interleave with mutex_unlock like: 6979 * 6980 * lock(&rq->lock); 6981 * find_proxy_task() 6982 * mutex_unlock() 6983 * lock(&wait_lock); 6984 * donor(owner) = current->blocked_donor; 6985 * unlock(&wait_lock); 6986 * 6987 * wake_up_q(); 6988 * ... 6989 * ttwu_runnable() 6990 * __task_rq_lock() 6991 * lock(&wait_lock); 6992 * owner == p 6993 * 6994 * Which leaves us to finish the ttwu_runnable() and make it go. 6995 * 6996 * So schedule rq->idle so that ttwu_runnable() can get the rq 6997 * lock and mark owner as running. 6998 */ 6999 return proxy_resched_idle(rq); 7000 } 7001 /* 7002 * OK, now we're absolutely sure @owner is on this 7003 * rq, therefore holding @rq->lock is sufficient to 7004 * guarantee its existence, as per ttwu_remote(). 7005 */ 7006 owner->blocked_donor = p; 7007 } 7008 WARN_ON_ONCE(owner && !owner->on_rq); 7009 return owner; 7010 7011 deactivate: 7012 proxy_deactivate(rq, p); 7013 return NULL; 7014 migrate_task: 7015 proxy_migrate_task(rq, rf, p, owner_cpu); 7016 return NULL; 7017 } 7018 #else /* SCHED_PROXY_EXEC */ 7019 static struct task_struct * 7020 find_proxy_task(struct rq *rq, struct task_struct *donor, struct rq_flags *rf) 7021 { 7022 WARN_ONCE(1, "This should never be called in the !SCHED_PROXY_EXEC case\n"); 7023 return donor; 7024 } 7025 #endif /* SCHED_PROXY_EXEC */ 7026 7027 /* 7028 * __schedule() is the main scheduler function. 7029 * 7030 * The main means of driving the scheduler and thus entering this function are: 7031 * 7032 * 1. Explicit blocking: mutex, semaphore, waitqueue, etc. 7033 * 7034 * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return 7035 * paths. For example, see arch/x86/entry_64.S. 7036 * 7037 * To drive preemption between tasks, the scheduler sets the flag in timer 7038 * interrupt handler sched_tick(). 7039 * 7040 * 3. Wakeups don't really cause entry into schedule(). They add a 7041 * task to the run-queue and that's it. 7042 * 7043 * Now, if the new task added to the run-queue preempts the current 7044 * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets 7045 * called on the nearest possible occasion: 7046 * 7047 * - If the kernel is preemptible (CONFIG_PREEMPTION=y): 7048 * 7049 * - in syscall or exception context, at the next outmost 7050 * preempt_enable(). (this might be as soon as the wake_up()'s 7051 * spin_unlock()!) 7052 * 7053 * - in IRQ context, return from interrupt-handler to 7054 * preemptible context 7055 * 7056 * - If the kernel is not preemptible (CONFIG_PREEMPTION is not set) 7057 * then at the next: 7058 * 7059 * - cond_resched() call 7060 * - explicit schedule() call 7061 * - return from syscall or exception to user-space 7062 * - return from interrupt-handler to user-space 7063 * 7064 * WARNING: must be called with preemption disabled! 7065 */ 7066 static void __sched notrace __schedule(int sched_mode) 7067 { 7068 struct task_struct *prev, *next; 7069 /* 7070 * On PREEMPT_RT kernel, SM_RTLOCK_WAIT is noted 7071 * as a preemption by schedule_debug() and RCU. 7072 */ 7073 bool preempt = sched_mode > SM_NONE; 7074 bool is_switch = false; 7075 unsigned long *switch_count; 7076 unsigned long prev_state; 7077 struct rq_flags rf; 7078 struct rq *rq; 7079 int cpu; 7080 7081 /* Trace preemptions consistently with task switches */ 7082 trace_sched_entry_tp(sched_mode == SM_PREEMPT); 7083 7084 cpu = smp_processor_id(); 7085 rq = cpu_rq(cpu); 7086 prev = rq->curr; 7087 7088 schedule_debug(prev, preempt); 7089 7090 klp_sched_try_switch(prev); 7091 7092 local_irq_disable(); 7093 rcu_note_context_switch(preempt); 7094 migrate_disable_switch(rq, prev); 7095 7096 /* 7097 * Make sure that signal_pending_state()->signal_pending() below 7098 * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE) 7099 * done by the caller to avoid the race with signal_wake_up(): 7100 * 7101 * __set_current_state(@state) signal_wake_up() 7102 * schedule() set_tsk_thread_flag(p, TIF_SIGPENDING) 7103 * wake_up_state(p, state) 7104 * LOCK rq->lock LOCK p->pi_state 7105 * smp_mb__after_spinlock() smp_mb__after_spinlock() 7106 * if (signal_pending_state()) if (p->state & @state) 7107 * 7108 * Also, the membarrier system call requires a full memory barrier 7109 * after coming from user-space, before storing to rq->curr; this 7110 * barrier matches a full barrier in the proximity of the membarrier 7111 * system call exit. 7112 */ 7113 rq_lock(rq, &rf); 7114 smp_mb__after_spinlock(); 7115 7116 hrtick_schedule_enter(rq); 7117 7118 /* Promote REQ to ACT */ 7119 rq->clock_update_flags <<= 1; 7120 update_rq_clock(rq); 7121 rq->clock_update_flags = RQCF_UPDATED; 7122 7123 switch_count = &prev->nivcsw; 7124 7125 /* Task state changes only considers SM_PREEMPT as preemption */ 7126 preempt = sched_mode == SM_PREEMPT; 7127 7128 /* 7129 * We must load prev->state once (task_struct::state is volatile), such 7130 * that we form a control dependency vs deactivate_task() below. 7131 */ 7132 prev_state = READ_ONCE(prev->__state); 7133 if (sched_mode == SM_IDLE) { 7134 /* SCX must consult the BPF scheduler to tell if rq is empty */ 7135 if (!rq->nr_running && !scx_enabled()) { 7136 next = prev; 7137 rq->next_class = &idle_sched_class; 7138 goto picked; 7139 } 7140 } else if (!preempt && prev_state) { 7141 /* 7142 * We pass task_is_blocked() as the should_block arg 7143 * in order to keep mutex-blocked tasks on the runqueue 7144 * for slection with proxy-exec (without proxy-exec 7145 * task_is_blocked() will always be false). 7146 */ 7147 try_to_block_task(rq, prev, &prev_state, 7148 !task_is_blocked(prev)); 7149 switch_count = &prev->nvcsw; 7150 } 7151 7152 pick_again: 7153 assert_balance_callbacks_empty(rq); 7154 next = pick_next_task(rq, &rf); 7155 rq->next_class = next->sched_class; 7156 if (sched_proxy_exec()) { 7157 struct task_struct *prev_donor = rq->donor; 7158 7159 rq_set_donor(rq, next); 7160 next->blocked_donor = NULL; 7161 if (unlikely(next->is_blocked)) { 7162 next = find_proxy_task(rq, next, &rf); 7163 if (!next) { 7164 zap_balance_callbacks(rq); 7165 goto pick_again; 7166 } 7167 if (next == rq->idle) { 7168 zap_balance_callbacks(rq); 7169 goto keep_resched; 7170 } 7171 } 7172 if (rq->donor == prev_donor && prev != next) { 7173 struct task_struct *donor = rq->donor; 7174 /* 7175 * When transitioning like: 7176 * 7177 * prev next 7178 * donor: B B 7179 * curr: A B or C 7180 * 7181 * then put_prev_set_next_task() will not have done 7182 * anything, since B == B. However, A might have 7183 * missed a RT/DL balance opportunity due to being 7184 * on_cpu. 7185 */ 7186 donor->sched_class->put_prev_task(rq, donor, donor); 7187 donor->sched_class->set_next_task(rq, donor, true); 7188 } 7189 } else { 7190 rq_set_donor(rq, next); 7191 } 7192 7193 picked: 7194 clear_tsk_need_resched(prev); 7195 clear_preempt_need_resched(); 7196 keep_resched: 7197 rq->last_seen_need_resched_ns = 0; 7198 7199 is_switch = prev != next; 7200 if (likely(is_switch)) { 7201 rq->nr_switches++; 7202 /* 7203 * RCU users of rcu_dereference(rq->curr) may not see 7204 * changes to task_struct made by pick_next_task(). 7205 */ 7206 RCU_INIT_POINTER(rq->curr, next); 7207 7208 /* 7209 * The membarrier system call requires each architecture 7210 * to have a full memory barrier after updating 7211 * rq->curr, before returning to user-space. 7212 * 7213 * Here are the schemes providing that barrier on the 7214 * various architectures: 7215 * - mm ? switch_mm() : mmdrop() for x86, s390, sparc, PowerPC, 7216 * RISC-V. switch_mm() relies on membarrier_arch_switch_mm() 7217 * on PowerPC and on RISC-V. 7218 * - finish_lock_switch() for weakly-ordered 7219 * architectures where spin_unlock is a full barrier, 7220 * - switch_to() for arm64 (weakly-ordered, spin_unlock 7221 * is a RELEASE barrier), 7222 * 7223 * The barrier matches a full barrier in the proximity of 7224 * the membarrier system call entry. 7225 * 7226 * On RISC-V, this barrier pairing is also needed for the 7227 * SYNC_CORE command when switching between processes, cf. 7228 * the inline comments in membarrier_arch_switch_mm(). 7229 */ 7230 ++*switch_count; 7231 7232 psi_account_irqtime(rq, prev, next); 7233 psi_sched_switch(prev, next, !task_on_rq_queued(prev) || 7234 prev->se.sched_delayed); 7235 7236 trace_sched_switch(preempt, prev, next, prev_state); 7237 7238 /* Also unlocks the rq: */ 7239 rq = context_switch(rq, prev, next, &rf); 7240 } else { 7241 rq_unpin_lock(rq, &rf); 7242 __balance_callbacks(rq, NULL); 7243 hrtick_schedule_exit(rq); 7244 raw_spin_rq_unlock_irq(rq); 7245 } 7246 trace_sched_exit_tp(is_switch); 7247 } 7248 7249 void __noreturn do_task_dead(void) 7250 { 7251 /* Causes final put_task_struct in finish_task_switch(): */ 7252 set_special_state(TASK_DEAD); 7253 7254 /* Tell freezer to ignore us: */ 7255 current->flags |= PF_NOFREEZE; 7256 7257 __schedule(SM_NONE); 7258 BUG(); 7259 7260 /* Avoid "noreturn function does return" - but don't continue if BUG() is a NOP: */ 7261 for (;;) 7262 cpu_relax(); 7263 } 7264 7265 static inline void sched_submit_work(struct task_struct *tsk) 7266 { 7267 static DEFINE_WAIT_OVERRIDE_MAP(sched_map, LD_WAIT_CONFIG); 7268 unsigned int task_flags; 7269 7270 /* 7271 * Establish LD_WAIT_CONFIG context to ensure none of the code called 7272 * will use a blocking primitive -- which would lead to recursion. 7273 */ 7274 lock_map_acquire_try(&sched_map); 7275 7276 task_flags = tsk->flags; 7277 /* 7278 * If a worker goes to sleep, notify and ask workqueue whether it 7279 * wants to wake up a task to maintain concurrency. 7280 */ 7281 if (task_flags & PF_WQ_WORKER) 7282 wq_worker_sleeping(tsk); 7283 else if (task_flags & PF_IO_WORKER) 7284 io_wq_worker_sleeping(tsk); 7285 7286 /* 7287 * spinlock and rwlock must not flush block requests. This will 7288 * deadlock if the callback attempts to acquire a lock which is 7289 * already acquired. 7290 */ 7291 WARN_ON_ONCE(current->__state & TASK_RTLOCK_WAIT); 7292 7293 /* 7294 * If we are going to sleep and we have plugged IO queued, 7295 * make sure to submit it to avoid deadlocks. 7296 */ 7297 blk_flush_plug(tsk->plug, true); 7298 7299 lock_map_release(&sched_map); 7300 } 7301 7302 static void sched_update_worker(struct task_struct *tsk) 7303 { 7304 if (tsk->flags & (PF_WQ_WORKER | PF_IO_WORKER)) { 7305 if (tsk->flags & PF_WQ_WORKER) 7306 wq_worker_running(tsk); 7307 else 7308 io_wq_worker_running(tsk); 7309 } 7310 } 7311 7312 static __always_inline void __schedule_loop(int sched_mode) 7313 { 7314 do { 7315 preempt_disable(); 7316 __schedule(sched_mode); 7317 sched_preempt_enable_no_resched(); 7318 } while (need_resched()); 7319 } 7320 7321 asmlinkage __visible void __sched schedule(void) 7322 { 7323 struct task_struct *tsk = current; 7324 7325 #ifdef CONFIG_RT_MUTEXES 7326 lockdep_assert(!tsk->sched_rt_mutex); 7327 #endif 7328 7329 if (!task_is_running(tsk)) 7330 sched_submit_work(tsk); 7331 __schedule_loop(SM_NONE); 7332 sched_update_worker(tsk); 7333 } 7334 EXPORT_SYMBOL(schedule); 7335 7336 /* 7337 * synchronize_rcu_tasks() makes sure that no task is stuck in preempted 7338 * state (have scheduled out non-voluntarily) by making sure that all 7339 * tasks have either left the run queue or have gone into user space. 7340 * As idle tasks do not do either, they must not ever be preempted 7341 * (schedule out non-voluntarily). 7342 * 7343 * schedule_idle() is similar to schedule_preempt_disable() except that it 7344 * never enables preemption because it does not call sched_submit_work(). 7345 */ 7346 void __sched schedule_idle(void) 7347 { 7348 /* 7349 * As this skips calling sched_submit_work(), which the idle task does 7350 * regardless because that function is a NOP when the task is in a 7351 * TASK_RUNNING state, make sure this isn't used someplace that the 7352 * current task can be in any other state. Note, idle is always in the 7353 * TASK_RUNNING state. 7354 */ 7355 WARN_ON_ONCE(current->__state); 7356 do { 7357 __schedule(SM_IDLE); 7358 } while (need_resched()); 7359 } 7360 7361 #if defined(CONFIG_CONTEXT_TRACKING_USER) && !defined(CONFIG_HAVE_CONTEXT_TRACKING_USER_OFFSTACK) 7362 asmlinkage __visible void __sched schedule_user(void) 7363 { 7364 /* 7365 * If we come here after a random call to set_need_resched(), 7366 * or we have been woken up remotely but the IPI has not yet arrived, 7367 * we haven't yet exited the RCU idle mode. Do it here manually until 7368 * we find a better solution. 7369 * 7370 * NB: There are buggy callers of this function. Ideally we 7371 * should warn if prev_state != CT_STATE_USER, but that will trigger 7372 * too frequently to make sense yet. 7373 */ 7374 enum ctx_state prev_state = exception_enter(); 7375 schedule(); 7376 exception_exit(prev_state); 7377 } 7378 #endif 7379 7380 /** 7381 * schedule_preempt_disabled - called with preemption disabled 7382 * 7383 * Returns with preemption disabled. Note: preempt_count must be 1 7384 */ 7385 void __sched schedule_preempt_disabled(void) 7386 { 7387 sched_preempt_enable_no_resched(); 7388 schedule(); 7389 preempt_disable(); 7390 } 7391 7392 #ifdef CONFIG_PREEMPT_RT 7393 void __sched notrace schedule_rtlock(void) 7394 { 7395 __schedule_loop(SM_RTLOCK_WAIT); 7396 } 7397 NOKPROBE_SYMBOL(schedule_rtlock); 7398 #endif 7399 7400 static void __sched notrace preempt_schedule_common(void) 7401 { 7402 do { 7403 /* 7404 * Because the function tracer can trace preempt_count_sub() 7405 * and it also uses preempt_enable/disable_notrace(), if 7406 * NEED_RESCHED is set, the preempt_enable_notrace() called 7407 * by the function tracer will call this function again and 7408 * cause infinite recursion. 7409 * 7410 * Preemption must be disabled here before the function 7411 * tracer can trace. Break up preempt_disable() into two 7412 * calls. One to disable preemption without fear of being 7413 * traced. The other to still record the preemption latency, 7414 * which can also be traced by the function tracer. 7415 */ 7416 preempt_disable_notrace(); 7417 preempt_latency_start(1); 7418 __schedule(SM_PREEMPT); 7419 preempt_latency_stop(1); 7420 preempt_enable_no_resched_notrace(); 7421 7422 /* 7423 * Check again in case we missed a preemption opportunity 7424 * between schedule and now. 7425 */ 7426 } while (need_resched()); 7427 } 7428 7429 #ifdef CONFIG_PREEMPTION 7430 /* 7431 * This is the entry point to schedule() from in-kernel preemption 7432 * off of preempt_enable. 7433 */ 7434 asmlinkage __visible void __sched notrace preempt_schedule(void) 7435 { 7436 /* 7437 * If there is a non-zero preempt_count or interrupts are disabled, 7438 * we do not want to preempt the current task. Just return.. 7439 */ 7440 if (likely(!preemptible())) 7441 return; 7442 preempt_schedule_common(); 7443 } 7444 NOKPROBE_SYMBOL(preempt_schedule); 7445 EXPORT_SYMBOL(preempt_schedule); 7446 7447 #ifdef CONFIG_PREEMPT_DYNAMIC 7448 # ifdef CONFIG_HAVE_PREEMPT_DYNAMIC_CALL 7449 # ifndef preempt_schedule_dynamic_enabled 7450 # define preempt_schedule_dynamic_enabled preempt_schedule 7451 # define preempt_schedule_dynamic_disabled NULL 7452 # endif 7453 DEFINE_STATIC_CALL(preempt_schedule, preempt_schedule_dynamic_enabled); 7454 EXPORT_STATIC_CALL_TRAMP(preempt_schedule); 7455 # elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY) 7456 static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule); 7457 void __sched notrace dynamic_preempt_schedule(void) 7458 { 7459 if (!static_branch_unlikely(&sk_dynamic_preempt_schedule)) 7460 return; 7461 preempt_schedule(); 7462 } 7463 NOKPROBE_SYMBOL(dynamic_preempt_schedule); 7464 EXPORT_SYMBOL(dynamic_preempt_schedule); 7465 # endif 7466 #endif /* CONFIG_PREEMPT_DYNAMIC */ 7467 7468 /** 7469 * preempt_schedule_notrace - preempt_schedule called by tracing 7470 * 7471 * The tracing infrastructure uses preempt_enable_notrace to prevent 7472 * recursion and tracing preempt enabling caused by the tracing 7473 * infrastructure itself. But as tracing can happen in areas coming 7474 * from userspace or just about to enter userspace, a preempt enable 7475 * can occur before user_exit() is called. This will cause the scheduler 7476 * to be called when the system is still in usermode. 7477 * 7478 * To prevent this, the preempt_enable_notrace will use this function 7479 * instead of preempt_schedule() to exit user context if needed before 7480 * calling the scheduler. 7481 */ 7482 asmlinkage __visible void __sched notrace preempt_schedule_notrace(void) 7483 { 7484 enum ctx_state prev_ctx; 7485 7486 if (likely(!preemptible())) 7487 return; 7488 7489 do { 7490 /* 7491 * Because the function tracer can trace preempt_count_sub() 7492 * and it also uses preempt_enable/disable_notrace(), if 7493 * NEED_RESCHED is set, the preempt_enable_notrace() called 7494 * by the function tracer will call this function again and 7495 * cause infinite recursion. 7496 * 7497 * Preemption must be disabled here before the function 7498 * tracer can trace. Break up preempt_disable() into two 7499 * calls. One to disable preemption without fear of being 7500 * traced. The other to still record the preemption latency, 7501 * which can also be traced by the function tracer. 7502 */ 7503 preempt_disable_notrace(); 7504 preempt_latency_start(1); 7505 /* 7506 * Needs preempt disabled in case user_exit() is traced 7507 * and the tracer calls preempt_enable_notrace() causing 7508 * an infinite recursion. 7509 */ 7510 prev_ctx = exception_enter(); 7511 __schedule(SM_PREEMPT); 7512 exception_exit(prev_ctx); 7513 7514 preempt_latency_stop(1); 7515 preempt_enable_no_resched_notrace(); 7516 } while (need_resched()); 7517 } 7518 EXPORT_SYMBOL_GPL(preempt_schedule_notrace); 7519 7520 #ifdef CONFIG_PREEMPT_DYNAMIC 7521 # if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL) 7522 # ifndef preempt_schedule_notrace_dynamic_enabled 7523 # define preempt_schedule_notrace_dynamic_enabled preempt_schedule_notrace 7524 # define preempt_schedule_notrace_dynamic_disabled NULL 7525 # endif 7526 DEFINE_STATIC_CALL(preempt_schedule_notrace, preempt_schedule_notrace_dynamic_enabled); 7527 EXPORT_STATIC_CALL_TRAMP(preempt_schedule_notrace); 7528 # elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY) 7529 static DEFINE_STATIC_KEY_TRUE(sk_dynamic_preempt_schedule_notrace); 7530 void __sched notrace dynamic_preempt_schedule_notrace(void) 7531 { 7532 if (!static_branch_unlikely(&sk_dynamic_preempt_schedule_notrace)) 7533 return; 7534 preempt_schedule_notrace(); 7535 } 7536 NOKPROBE_SYMBOL(dynamic_preempt_schedule_notrace); 7537 EXPORT_SYMBOL(dynamic_preempt_schedule_notrace); 7538 # endif 7539 #endif 7540 7541 #endif /* CONFIG_PREEMPTION */ 7542 7543 /* 7544 * This is the entry point to schedule() from kernel preemption 7545 * off of IRQ context. 7546 * Note, that this is called and return with IRQs disabled. This will 7547 * protect us against recursive calling from IRQ contexts. 7548 */ 7549 asmlinkage __visible void __sched preempt_schedule_irq(void) 7550 { 7551 enum ctx_state prev_state; 7552 7553 /* Catch callers which need to be fixed */ 7554 BUG_ON(preempt_count() || !irqs_disabled()); 7555 7556 prev_state = exception_enter(); 7557 7558 do { 7559 preempt_disable(); 7560 local_irq_enable(); 7561 __schedule(SM_PREEMPT); 7562 local_irq_disable(); 7563 sched_preempt_enable_no_resched(); 7564 } while (need_resched()); 7565 7566 exception_exit(prev_state); 7567 } 7568 7569 int default_wake_function(wait_queue_entry_t *curr, unsigned mode, int wake_flags, 7570 void *key) 7571 { 7572 WARN_ON_ONCE(wake_flags & ~(WF_SYNC|WF_CURRENT_CPU)); 7573 return try_to_wake_up(curr->private, mode, wake_flags); 7574 } 7575 EXPORT_SYMBOL(default_wake_function); 7576 7577 const struct sched_class *__setscheduler_class(int policy, int prio) 7578 { 7579 if (dl_prio(prio)) 7580 return &dl_sched_class; 7581 7582 if (rt_prio(prio)) 7583 return &rt_sched_class; 7584 7585 #ifdef CONFIG_SCHED_CLASS_EXT 7586 if (task_should_scx(policy)) 7587 return &ext_sched_class; 7588 #endif 7589 7590 return &fair_sched_class; 7591 } 7592 7593 #ifdef CONFIG_RT_MUTEXES 7594 7595 /* 7596 * Would be more useful with typeof()/auto_type but they don't mix with 7597 * bit-fields. Since it's a local thing, use int. Keep the generic sounding 7598 * name such that if someone were to implement this function we get to compare 7599 * notes. 7600 */ 7601 #define fetch_and_set(x, v) ({ int _x = (x); (x) = (v); _x; }) 7602 7603 void rt_mutex_pre_schedule(void) 7604 { 7605 lockdep_assert(!fetch_and_set(current->sched_rt_mutex, 1)); 7606 sched_submit_work(current); 7607 } 7608 7609 void rt_mutex_schedule(void) 7610 { 7611 lockdep_assert(current->sched_rt_mutex); 7612 __schedule_loop(SM_NONE); 7613 } 7614 7615 void rt_mutex_post_schedule(void) 7616 { 7617 sched_update_worker(current); 7618 lockdep_assert(fetch_and_set(current->sched_rt_mutex, 0)); 7619 } 7620 7621 /* 7622 * rt_mutex_setprio - set the current priority of a task 7623 * @p: task to boost 7624 * @pi_task: donor task 7625 * 7626 * This function changes the 'effective' priority of a task. It does 7627 * not touch ->normal_prio like __setscheduler(). 7628 * 7629 * Used by the rt_mutex code to implement priority inheritance 7630 * logic. Call site only calls if the priority of the task changed. 7631 */ 7632 void rt_mutex_setprio(struct task_struct *p, struct task_struct *pi_task) 7633 { 7634 int prio, oldprio, queue_flag = 7635 DEQUEUE_SAVE | DEQUEUE_MOVE | DEQUEUE_NOCLOCK; 7636 const struct sched_class *prev_class, *next_class; 7637 struct rq_flags rf; 7638 struct rq *rq; 7639 7640 /* XXX used to be waiter->prio, not waiter->task->prio */ 7641 prio = __rt_effective_prio(pi_task, p->normal_prio); 7642 7643 /* 7644 * If nothing changed; bail early. 7645 */ 7646 if (p->pi_top_task == pi_task && prio == p->prio && !dl_prio(prio)) 7647 return; 7648 7649 rq = __task_rq_lock(p, &rf); 7650 update_rq_clock(rq); 7651 /* 7652 * Set under pi_lock && rq->lock, such that the value can be used under 7653 * either lock. 7654 * 7655 * Note that there is loads of tricky to make this pointer cache work 7656 * right. rt_mutex_slowunlock()+rt_mutex_postunlock() work together to 7657 * ensure a task is de-boosted (pi_task is set to NULL) before the 7658 * task is allowed to run again (and can exit). This ensures the pointer 7659 * points to a blocked task -- which guarantees the task is present. 7660 */ 7661 p->pi_top_task = pi_task; 7662 7663 /* 7664 * For FIFO/RR we only need to set prio, if that matches we're done. 7665 */ 7666 if (prio == p->prio && !dl_prio(prio)) 7667 goto out_unlock; 7668 7669 /* 7670 * Idle task boosting is a no-no in general. There is one 7671 * exception, when PREEMPT_RT and NOHZ is active: 7672 * 7673 * The idle task calls get_next_timer_interrupt() and holds 7674 * the timer wheel base->lock on the CPU and another CPU wants 7675 * to access the timer (probably to cancel it). We can safely 7676 * ignore the boosting request, as the idle CPU runs this code 7677 * with interrupts disabled and will complete the lock 7678 * protected section without being interrupted. So there is no 7679 * real need to boost. 7680 */ 7681 if (unlikely(p == rq->idle)) { 7682 WARN_ON(p != rq->curr); 7683 WARN_ON(p->pi_blocked_on); 7684 goto out_unlock; 7685 } 7686 7687 trace_sched_pi_setprio(p, pi_task); 7688 oldprio = p->prio; 7689 7690 if (oldprio == prio && !dl_prio(prio)) 7691 queue_flag &= ~DEQUEUE_MOVE; 7692 7693 prev_class = p->sched_class; 7694 next_class = __setscheduler_class(p->policy, prio); 7695 7696 if (prev_class != next_class) 7697 queue_flag |= DEQUEUE_CLASS; 7698 7699 scoped_guard (sched_change, p, queue_flag) { 7700 /* 7701 * Boosting condition are: 7702 * 1. -rt task is running and holds mutex A 7703 * --> -dl task blocks on mutex A 7704 * 7705 * 2. -dl task is running and holds mutex A 7706 * --> -dl task blocks on mutex A and could preempt the 7707 * running task 7708 */ 7709 if (dl_prio(prio)) { 7710 if (!dl_prio(p->normal_prio) || 7711 (pi_task && dl_prio(pi_task->prio) && 7712 dl_entity_preempt(&pi_task->dl, &p->dl))) { 7713 p->dl.pi_se = pi_task->dl.pi_se; 7714 scope->flags |= ENQUEUE_REPLENISH; 7715 } else { 7716 p->dl.pi_se = &p->dl; 7717 } 7718 } else if (rt_prio(prio)) { 7719 if (dl_prio(oldprio)) 7720 p->dl.pi_se = &p->dl; 7721 if (oldprio < prio) 7722 scope->flags |= ENQUEUE_HEAD; 7723 } else { 7724 if (dl_prio(oldprio)) 7725 p->dl.pi_se = &p->dl; 7726 if (rt_prio(oldprio)) 7727 p->rt.timeout = 0; 7728 } 7729 7730 p->sched_class = next_class; 7731 p->prio = prio; 7732 } 7733 out_unlock: 7734 /* Caller holds task_struct::pi_lock, IRQs are still disabled */ 7735 7736 __balance_callbacks(rq, &rf); 7737 __task_rq_unlock(rq, p, &rf); 7738 } 7739 #endif /* CONFIG_RT_MUTEXES */ 7740 7741 #if !defined(CONFIG_PREEMPTION) || defined(CONFIG_PREEMPT_DYNAMIC) 7742 int __sched __cond_resched(void) 7743 { 7744 if (should_resched(0) && !irqs_disabled()) { 7745 preempt_schedule_common(); 7746 return 1; 7747 } 7748 /* 7749 * In PREEMPT_RCU kernels, ->rcu_read_lock_nesting tells the tick 7750 * whether the current CPU is in an RCU read-side critical section, 7751 * so the tick can report quiescent states even for CPUs looping 7752 * in kernel context. In contrast, in non-preemptible kernels, 7753 * RCU readers leave no in-memory hints, which means that CPU-bound 7754 * processes executing in kernel context might never report an 7755 * RCU quiescent state. Therefore, the following code causes 7756 * cond_resched() to report a quiescent state, but only when RCU 7757 * is in urgent need of one. 7758 * A third case, preemptible, but non-PREEMPT_RCU provides for 7759 * urgently needed quiescent states via rcu_flavor_sched_clock_irq(). 7760 */ 7761 #ifndef CONFIG_PREEMPT_RCU 7762 rcu_all_qs(); 7763 #endif 7764 return 0; 7765 } 7766 EXPORT_SYMBOL(__cond_resched); 7767 #endif 7768 7769 #ifdef CONFIG_PREEMPT_DYNAMIC 7770 # ifdef CONFIG_HAVE_PREEMPT_DYNAMIC_CALL 7771 # define cond_resched_dynamic_enabled __cond_resched 7772 # define cond_resched_dynamic_disabled ((void *)&__static_call_return0) 7773 DEFINE_STATIC_CALL_RET0(cond_resched, __cond_resched); 7774 EXPORT_STATIC_CALL_TRAMP(cond_resched); 7775 7776 # define might_resched_dynamic_enabled __cond_resched 7777 # define might_resched_dynamic_disabled ((void *)&__static_call_return0) 7778 DEFINE_STATIC_CALL_RET0(might_resched, __cond_resched); 7779 EXPORT_STATIC_CALL_TRAMP(might_resched); 7780 # elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY) 7781 static DEFINE_STATIC_KEY_FALSE(sk_dynamic_cond_resched); 7782 int __sched dynamic_cond_resched(void) 7783 { 7784 if (!static_branch_unlikely(&sk_dynamic_cond_resched)) 7785 return 0; 7786 return __cond_resched(); 7787 } 7788 EXPORT_SYMBOL(dynamic_cond_resched); 7789 7790 static DEFINE_STATIC_KEY_FALSE(sk_dynamic_might_resched); 7791 int __sched dynamic_might_resched(void) 7792 { 7793 if (!static_branch_unlikely(&sk_dynamic_might_resched)) 7794 return 0; 7795 return __cond_resched(); 7796 } 7797 EXPORT_SYMBOL(dynamic_might_resched); 7798 # endif 7799 #endif /* CONFIG_PREEMPT_DYNAMIC */ 7800 7801 /* 7802 * __cond_resched_lock() - if a reschedule is pending, drop the given lock, 7803 * call schedule, and on return reacquire the lock. 7804 * 7805 * This works OK both with and without CONFIG_PREEMPTION. We do strange low-level 7806 * operations here to prevent schedule() from being called twice (once via 7807 * spin_unlock(), once by hand). 7808 */ 7809 int __cond_resched_lock(spinlock_t *lock) 7810 { 7811 int resched = should_resched(PREEMPT_LOCK_OFFSET); 7812 int ret = 0; 7813 7814 lockdep_assert_held(lock); 7815 7816 if (spin_needbreak(lock) || resched) { 7817 spin_unlock(lock); 7818 if (!_cond_resched()) 7819 cpu_relax(); 7820 ret = 1; 7821 spin_lock(lock); 7822 } 7823 return ret; 7824 } 7825 EXPORT_SYMBOL(__cond_resched_lock); 7826 7827 int __cond_resched_rwlock_read(rwlock_t *lock) 7828 { 7829 int resched = should_resched(PREEMPT_LOCK_OFFSET); 7830 int ret = 0; 7831 7832 lockdep_assert_held_read(lock); 7833 7834 if (rwlock_needbreak(lock) || resched) { 7835 read_unlock(lock); 7836 if (!_cond_resched()) 7837 cpu_relax(); 7838 ret = 1; 7839 read_lock(lock); 7840 } 7841 return ret; 7842 } 7843 EXPORT_SYMBOL(__cond_resched_rwlock_read); 7844 7845 int __cond_resched_rwlock_write(rwlock_t *lock) 7846 { 7847 int resched = should_resched(PREEMPT_LOCK_OFFSET); 7848 int ret = 0; 7849 7850 lockdep_assert_held_write(lock); 7851 7852 if (rwlock_needbreak(lock) || resched) { 7853 write_unlock(lock); 7854 if (!_cond_resched()) 7855 cpu_relax(); 7856 ret = 1; 7857 write_lock(lock); 7858 } 7859 return ret; 7860 } 7861 EXPORT_SYMBOL(__cond_resched_rwlock_write); 7862 7863 #ifdef CONFIG_PREEMPT_DYNAMIC 7864 7865 # ifdef CONFIG_GENERIC_IRQ_ENTRY 7866 # include <linux/irq-entry-common.h> 7867 # endif 7868 7869 /* 7870 * SC:cond_resched 7871 * SC:might_resched 7872 * SC:preempt_schedule 7873 * SC:preempt_schedule_notrace 7874 * SC:irqentry_exit_cond_resched 7875 * 7876 * 7877 * NONE: 7878 * cond_resched <- __cond_resched 7879 * might_resched <- RET0 7880 * preempt_schedule <- NOP 7881 * preempt_schedule_notrace <- NOP 7882 * irqentry_exit_cond_resched <- NOP 7883 * dynamic_preempt_lazy <- false 7884 * 7885 * VOLUNTARY: 7886 * cond_resched <- __cond_resched 7887 * might_resched <- __cond_resched 7888 * preempt_schedule <- NOP 7889 * preempt_schedule_notrace <- NOP 7890 * irqentry_exit_cond_resched <- NOP 7891 * dynamic_preempt_lazy <- false 7892 * 7893 * FULL: 7894 * cond_resched <- RET0 7895 * might_resched <- RET0 7896 * preempt_schedule <- preempt_schedule 7897 * preempt_schedule_notrace <- preempt_schedule_notrace 7898 * irqentry_exit_cond_resched <- irqentry_exit_cond_resched 7899 * dynamic_preempt_lazy <- false 7900 * 7901 * LAZY: 7902 * cond_resched <- RET0 7903 * might_resched <- RET0 7904 * preempt_schedule <- preempt_schedule 7905 * preempt_schedule_notrace <- preempt_schedule_notrace 7906 * irqentry_exit_cond_resched <- irqentry_exit_cond_resched 7907 * dynamic_preempt_lazy <- true 7908 */ 7909 7910 enum { 7911 preempt_dynamic_undefined = -1, 7912 preempt_dynamic_none, 7913 preempt_dynamic_voluntary, 7914 preempt_dynamic_full, 7915 preempt_dynamic_lazy, 7916 }; 7917 7918 int preempt_dynamic_mode = preempt_dynamic_undefined; 7919 7920 int sched_dynamic_mode(const char *str) 7921 { 7922 # if !(defined(CONFIG_PREEMPT_RT) || defined(CONFIG_ARCH_HAS_PREEMPT_LAZY)) 7923 if (!strcmp(str, "none")) 7924 return preempt_dynamic_none; 7925 7926 if (!strcmp(str, "voluntary")) 7927 return preempt_dynamic_voluntary; 7928 # endif 7929 7930 if (!strcmp(str, "full")) 7931 return preempt_dynamic_full; 7932 7933 # ifdef CONFIG_ARCH_HAS_PREEMPT_LAZY 7934 if (!strcmp(str, "lazy")) 7935 return preempt_dynamic_lazy; 7936 # endif 7937 7938 return -EINVAL; 7939 } 7940 7941 # define preempt_dynamic_key_enable(f) static_key_enable(&sk_dynamic_##f.key) 7942 # define preempt_dynamic_key_disable(f) static_key_disable(&sk_dynamic_##f.key) 7943 7944 # if defined(CONFIG_HAVE_PREEMPT_DYNAMIC_CALL) 7945 # define preempt_dynamic_enable(f) static_call_update(f, f##_dynamic_enabled) 7946 # define preempt_dynamic_disable(f) static_call_update(f, f##_dynamic_disabled) 7947 # elif defined(CONFIG_HAVE_PREEMPT_DYNAMIC_KEY) 7948 # define preempt_dynamic_enable(f) preempt_dynamic_key_enable(f) 7949 # define preempt_dynamic_disable(f) preempt_dynamic_key_disable(f) 7950 # else 7951 # error "Unsupported PREEMPT_DYNAMIC mechanism" 7952 # endif 7953 7954 static DEFINE_MUTEX(sched_dynamic_mutex); 7955 7956 static void __sched_dynamic_update(int mode) 7957 { 7958 /* 7959 * Avoid {NONE,VOLUNTARY} -> FULL transitions from ever ending up in 7960 * the ZERO state, which is invalid. 7961 */ 7962 preempt_dynamic_enable(cond_resched); 7963 preempt_dynamic_enable(might_resched); 7964 preempt_dynamic_enable(preempt_schedule); 7965 preempt_dynamic_enable(preempt_schedule_notrace); 7966 preempt_dynamic_enable(irqentry_exit_cond_resched); 7967 preempt_dynamic_key_disable(preempt_lazy); 7968 7969 switch (mode) { 7970 case preempt_dynamic_none: 7971 preempt_dynamic_enable(cond_resched); 7972 preempt_dynamic_disable(might_resched); 7973 preempt_dynamic_disable(preempt_schedule); 7974 preempt_dynamic_disable(preempt_schedule_notrace); 7975 preempt_dynamic_disable(irqentry_exit_cond_resched); 7976 preempt_dynamic_key_disable(preempt_lazy); 7977 if (mode != preempt_dynamic_mode) 7978 pr_info("Dynamic Preempt: none\n"); 7979 break; 7980 7981 case preempt_dynamic_voluntary: 7982 preempt_dynamic_enable(cond_resched); 7983 preempt_dynamic_enable(might_resched); 7984 preempt_dynamic_disable(preempt_schedule); 7985 preempt_dynamic_disable(preempt_schedule_notrace); 7986 preempt_dynamic_disable(irqentry_exit_cond_resched); 7987 preempt_dynamic_key_disable(preempt_lazy); 7988 if (mode != preempt_dynamic_mode) 7989 pr_info("Dynamic Preempt: voluntary\n"); 7990 break; 7991 7992 case preempt_dynamic_full: 7993 preempt_dynamic_disable(cond_resched); 7994 preempt_dynamic_disable(might_resched); 7995 preempt_dynamic_enable(preempt_schedule); 7996 preempt_dynamic_enable(preempt_schedule_notrace); 7997 preempt_dynamic_enable(irqentry_exit_cond_resched); 7998 preempt_dynamic_key_disable(preempt_lazy); 7999 if (mode != preempt_dynamic_mode) 8000 pr_info("Dynamic Preempt: full\n"); 8001 break; 8002 8003 case preempt_dynamic_lazy: 8004 preempt_dynamic_disable(cond_resched); 8005 preempt_dynamic_disable(might_resched); 8006 preempt_dynamic_enable(preempt_schedule); 8007 preempt_dynamic_enable(preempt_schedule_notrace); 8008 preempt_dynamic_enable(irqentry_exit_cond_resched); 8009 preempt_dynamic_key_enable(preempt_lazy); 8010 if (mode != preempt_dynamic_mode) 8011 pr_info("Dynamic Preempt: lazy\n"); 8012 break; 8013 } 8014 8015 WRITE_ONCE(preempt_dynamic_mode, mode); 8016 } 8017 8018 void sched_dynamic_update(int mode) 8019 { 8020 mutex_lock(&sched_dynamic_mutex); 8021 __sched_dynamic_update(mode); 8022 mutex_unlock(&sched_dynamic_mutex); 8023 } 8024 8025 static int __init setup_preempt_mode(char *str) 8026 { 8027 int mode = sched_dynamic_mode(str); 8028 if (mode < 0) { 8029 pr_warn("Dynamic Preempt: unsupported mode: %s\n", str); 8030 return 0; 8031 } 8032 8033 sched_dynamic_update(mode); 8034 return 1; 8035 } 8036 __setup("preempt=", setup_preempt_mode); 8037 8038 static void __init preempt_dynamic_init(void) 8039 { 8040 if (preempt_dynamic_mode == preempt_dynamic_undefined) { 8041 if (IS_ENABLED(CONFIG_PREEMPT_NONE)) { 8042 sched_dynamic_update(preempt_dynamic_none); 8043 } else if (IS_ENABLED(CONFIG_PREEMPT_VOLUNTARY)) { 8044 sched_dynamic_update(preempt_dynamic_voluntary); 8045 } else if (IS_ENABLED(CONFIG_PREEMPT_LAZY)) { 8046 sched_dynamic_update(preempt_dynamic_lazy); 8047 } else { 8048 /* Default static call setting, nothing to do */ 8049 WARN_ON_ONCE(!IS_ENABLED(CONFIG_PREEMPT)); 8050 preempt_dynamic_mode = preempt_dynamic_full; 8051 pr_info("Dynamic Preempt: full\n"); 8052 } 8053 } 8054 } 8055 8056 # define PREEMPT_MODEL_ACCESSOR(mode) \ 8057 bool preempt_model_##mode(void) \ 8058 { \ 8059 int mode = READ_ONCE(preempt_dynamic_mode); \ 8060 WARN_ON_ONCE(mode == preempt_dynamic_undefined); \ 8061 return mode == preempt_dynamic_##mode; \ 8062 } \ 8063 EXPORT_SYMBOL_GPL(preempt_model_##mode) 8064 8065 PREEMPT_MODEL_ACCESSOR(none); 8066 PREEMPT_MODEL_ACCESSOR(voluntary); 8067 PREEMPT_MODEL_ACCESSOR(full); 8068 PREEMPT_MODEL_ACCESSOR(lazy); 8069 8070 #else /* !CONFIG_PREEMPT_DYNAMIC: */ 8071 8072 #define preempt_dynamic_mode -1 8073 8074 static inline void preempt_dynamic_init(void) { } 8075 8076 #endif /* CONFIG_PREEMPT_DYNAMIC */ 8077 8078 const char *preempt_modes[] = { 8079 "none", "voluntary", "full", "lazy", NULL, 8080 }; 8081 8082 const char *preempt_model_str(void) 8083 { 8084 bool brace = IS_ENABLED(CONFIG_PREEMPT_RT) && 8085 (IS_ENABLED(CONFIG_PREEMPT_DYNAMIC) || 8086 IS_ENABLED(CONFIG_PREEMPT_LAZY)); 8087 static char buf[128]; 8088 8089 if (IS_ENABLED(CONFIG_PREEMPT_BUILD)) { 8090 struct seq_buf s; 8091 8092 seq_buf_init(&s, buf, sizeof(buf)); 8093 seq_buf_puts(&s, "PREEMPT"); 8094 8095 if (IS_ENABLED(CONFIG_PREEMPT_RT)) 8096 seq_buf_printf(&s, "%sRT%s", 8097 brace ? "_{" : "_", 8098 brace ? "," : ""); 8099 8100 if (IS_ENABLED(CONFIG_PREEMPT_DYNAMIC)) { 8101 seq_buf_printf(&s, "(%s)%s", 8102 preempt_dynamic_mode >= 0 ? 8103 preempt_modes[preempt_dynamic_mode] : "undef", 8104 brace ? "}" : ""); 8105 return seq_buf_str(&s); 8106 } 8107 8108 if (IS_ENABLED(CONFIG_PREEMPT_LAZY)) { 8109 seq_buf_printf(&s, "LAZY%s", 8110 brace ? "}" : ""); 8111 return seq_buf_str(&s); 8112 } 8113 8114 return seq_buf_str(&s); 8115 } 8116 8117 if (IS_ENABLED(CONFIG_PREEMPT_VOLUNTARY_BUILD)) 8118 return "VOLUNTARY"; 8119 8120 return "NONE"; 8121 } 8122 8123 int io_schedule_prepare(void) 8124 { 8125 int old_iowait = current->in_iowait; 8126 8127 current->in_iowait = 1; 8128 blk_flush_plug(current->plug, true); 8129 return old_iowait; 8130 } 8131 8132 void io_schedule_finish(int token) 8133 { 8134 current->in_iowait = token; 8135 } 8136 8137 /* 8138 * This task is about to go to sleep on IO. Increment rq->nr_iowait so 8139 * that process accounting knows that this is a task in IO wait state. 8140 */ 8141 long __sched io_schedule_timeout(long timeout) 8142 { 8143 int token; 8144 long ret; 8145 8146 token = io_schedule_prepare(); 8147 ret = schedule_timeout(timeout); 8148 io_schedule_finish(token); 8149 8150 return ret; 8151 } 8152 EXPORT_SYMBOL(io_schedule_timeout); 8153 8154 void __sched io_schedule(void) 8155 { 8156 int token; 8157 8158 token = io_schedule_prepare(); 8159 schedule(); 8160 io_schedule_finish(token); 8161 } 8162 EXPORT_SYMBOL(io_schedule); 8163 8164 void sched_show_task(struct task_struct *p) 8165 { 8166 unsigned long free; 8167 int ppid; 8168 8169 if (!try_get_task_stack(p)) 8170 return; 8171 8172 pr_info("task:%-15.15s state:%c", p->comm, task_state_to_char(p)); 8173 8174 if (task_is_running(p)) 8175 pr_cont(" running task "); 8176 free = stack_not_used(p); 8177 ppid = 0; 8178 rcu_read_lock(); 8179 if (pid_alive(p)) 8180 ppid = task_pid_nr(rcu_dereference(p->real_parent)); 8181 rcu_read_unlock(); 8182 pr_cont(" stack:%-5lu pid:%-5d tgid:%-5d ppid:%-6d task_flags:0x%04x flags:0x%08lx\n", 8183 free, task_pid_nr(p), task_tgid_nr(p), 8184 ppid, p->flags, read_task_thread_flags(p)); 8185 8186 print_worker_info(KERN_INFO, p); 8187 print_stop_info(KERN_INFO, p); 8188 print_scx_info(KERN_INFO, p); 8189 show_stack(p, NULL, KERN_INFO); 8190 put_task_stack(p); 8191 } 8192 EXPORT_SYMBOL_GPL(sched_show_task); 8193 8194 static inline bool 8195 state_filter_match(unsigned long state_filter, struct task_struct *p) 8196 { 8197 unsigned int state = READ_ONCE(p->__state); 8198 8199 /* no filter, everything matches */ 8200 if (!state_filter) 8201 return true; 8202 8203 /* filter, but doesn't match */ 8204 if (!(state & state_filter)) 8205 return false; 8206 8207 /* 8208 * When looking for TASK_UNINTERRUPTIBLE skip TASK_IDLE (allows 8209 * TASK_KILLABLE). 8210 */ 8211 if (state_filter == TASK_UNINTERRUPTIBLE && (state & TASK_NOLOAD)) 8212 return false; 8213 8214 return true; 8215 } 8216 8217 8218 void show_state_filter(unsigned int state_filter) 8219 { 8220 struct task_struct *g, *p; 8221 8222 rcu_read_lock(); 8223 for_each_process_thread(g, p) { 8224 /* 8225 * reset the NMI-timeout, listing all files on a slow 8226 * console might take a lot of time: 8227 * Also, reset softlockup watchdogs on all CPUs, because 8228 * another CPU might be blocked waiting for us to process 8229 * an IPI. 8230 */ 8231 touch_nmi_watchdog(); 8232 touch_all_softlockup_watchdogs(); 8233 if (state_filter_match(state_filter, p)) 8234 sched_show_task(p); 8235 } 8236 8237 if (!state_filter) 8238 sysrq_sched_debug_show(); 8239 8240 rcu_read_unlock(); 8241 /* 8242 * Only show locks if all tasks are dumped: 8243 */ 8244 if (!state_filter) 8245 debug_show_all_locks(); 8246 } 8247 8248 /** 8249 * init_idle - set up an idle thread for a given CPU 8250 * @idle: task in question 8251 * @cpu: CPU the idle task belongs to 8252 * 8253 * NOTE: this function does not set the idle thread's NEED_RESCHED 8254 * flag, to make booting more robust. 8255 */ 8256 void __init init_idle(struct task_struct *idle, int cpu) 8257 { 8258 struct affinity_context ac = (struct affinity_context) { 8259 .new_mask = cpumask_of(cpu), 8260 .flags = 0, 8261 }; 8262 struct rq *rq = cpu_rq(cpu); 8263 unsigned long flags; 8264 8265 raw_spin_lock_irqsave(&idle->pi_lock, flags); 8266 raw_spin_rq_lock(rq); 8267 8268 idle->__state = TASK_RUNNING; 8269 idle->se.exec_start = sched_clock(); 8270 /* 8271 * PF_KTHREAD should already be set at this point; regardless, make it 8272 * look like a proper per-CPU kthread. 8273 */ 8274 idle->flags |= PF_KTHREAD | PF_NO_SETAFFINITY; 8275 kthread_set_per_cpu(idle, cpu); 8276 8277 /* 8278 * No validation and serialization required at boot time and for 8279 * setting up the idle tasks of not yet online CPUs. 8280 */ 8281 set_cpus_allowed_common(idle, &ac); 8282 /* 8283 * We're having a chicken and egg problem, even though we are 8284 * holding rq->lock, the CPU isn't yet set to this CPU so the 8285 * lockdep check in task_group() will fail. 8286 * 8287 * Similar case to sched_fork(). / Alternatively we could 8288 * use task_rq_lock() here and obtain the other rq->lock. 8289 * 8290 * Silence PROVE_RCU 8291 */ 8292 rcu_read_lock(); 8293 __set_task_cpu(idle, cpu); 8294 rcu_read_unlock(); 8295 8296 rq->idle = idle; 8297 rq_set_donor(rq, idle); 8298 rcu_assign_pointer(rq->curr, idle); 8299 idle->on_rq = TASK_ON_RQ_QUEUED; 8300 idle->on_cpu = 1; 8301 raw_spin_rq_unlock(rq); 8302 raw_spin_unlock_irqrestore(&idle->pi_lock, flags); 8303 8304 /* Set the preempt count _outside_ the spinlocks! */ 8305 init_idle_preempt_count(idle, cpu); 8306 8307 /* 8308 * The idle tasks have their own, simple scheduling class: 8309 */ 8310 idle->sched_class = &idle_sched_class; 8311 ftrace_graph_init_idle_task(idle, cpu); 8312 vtime_init_idle(idle, cpu); 8313 sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu); 8314 } 8315 8316 int cpuset_cpumask_can_shrink(const struct cpumask *cur, 8317 const struct cpumask *trial) 8318 { 8319 int ret = 1; 8320 8321 if (cpumask_empty(cur)) 8322 return ret; 8323 8324 ret = dl_cpuset_cpumask_can_shrink(cur, trial); 8325 8326 return ret; 8327 } 8328 8329 int task_can_attach(struct task_struct *p) 8330 { 8331 int ret = 0; 8332 8333 /* 8334 * Kthreads which disallow setaffinity shouldn't be moved 8335 * to a new cpuset; we don't want to change their CPU 8336 * affinity and isolating such threads by their set of 8337 * allowed nodes is unnecessary. Thus, cpusets are not 8338 * applicable for such threads. This prevents checking for 8339 * success of set_cpus_allowed_ptr() on all attached tasks 8340 * before cpus_mask may be changed. 8341 */ 8342 if (p->flags & PF_NO_SETAFFINITY) 8343 ret = -EINVAL; 8344 8345 return ret; 8346 } 8347 8348 bool sched_smp_initialized __read_mostly; 8349 8350 #ifdef CONFIG_NUMA_BALANCING 8351 /* Migrate current task p to target_cpu */ 8352 int migrate_task_to(struct task_struct *p, int target_cpu) 8353 { 8354 struct migration_arg arg = { p, target_cpu }; 8355 int curr_cpu = task_cpu(p); 8356 8357 if (curr_cpu == target_cpu) 8358 return 0; 8359 8360 if (!cpumask_test_cpu(target_cpu, p->cpus_ptr)) 8361 return -EINVAL; 8362 8363 /* TODO: This is not properly updating schedstats */ 8364 8365 trace_sched_move_numa(p, curr_cpu, target_cpu); 8366 return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg); 8367 } 8368 8369 /* 8370 * Requeue a task on a given node and accurately track the number of NUMA 8371 * tasks on the runqueues 8372 */ 8373 void sched_setnuma(struct task_struct *p, int nid) 8374 { 8375 guard(task_rq_lock)(p); 8376 scoped_guard (sched_change, p, DEQUEUE_SAVE) 8377 p->numa_preferred_nid = nid; 8378 } 8379 #endif /* CONFIG_NUMA_BALANCING */ 8380 8381 #ifdef CONFIG_HOTPLUG_CPU 8382 /* 8383 * Invoked on the outgoing CPU in context of the CPU hotplug thread 8384 * after ensuring that there are no user space tasks left on the CPU. 8385 * 8386 * If there is a lazy mm in use on the hotplug thread, drop it and 8387 * switch to init_mm. 8388 * 8389 * The reference count on init_mm is dropped in finish_cpu(). 8390 */ 8391 static void sched_force_init_mm(void) 8392 { 8393 struct mm_struct *mm = current->active_mm; 8394 8395 if (mm != &init_mm) { 8396 mmgrab_lazy_tlb(&init_mm); 8397 local_irq_disable(); 8398 current->active_mm = &init_mm; 8399 switch_mm_irqs_off(mm, &init_mm, current); 8400 local_irq_enable(); 8401 finish_arch_post_lock_switch(); 8402 mmdrop_lazy_tlb(mm); 8403 } 8404 8405 /* finish_cpu(), as ran on the BP, will clean up the active_mm state */ 8406 } 8407 8408 static int __balance_push_cpu_stop(void *arg) 8409 { 8410 struct task_struct *p = arg; 8411 struct rq *rq = this_rq(); 8412 struct rq_flags rf; 8413 int cpu; 8414 8415 scoped_guard (raw_spinlock_irq, &p->pi_lock) { 8416 /* 8417 * We may change the underlying rq, but the locks held will 8418 * appropriately be "transferred" when switching. 8419 */ 8420 context_unsafe_alias(rq); 8421 8422 cpu = select_fallback_rq(rq->cpu, p); 8423 8424 rq_lock(rq, &rf); 8425 update_rq_clock(rq); 8426 if (task_rq(p) == rq && task_on_rq_queued(p)) 8427 rq = __migrate_task(rq, &rf, p, cpu); 8428 rq_unlock(rq, &rf); 8429 } 8430 8431 put_task_struct(p); 8432 8433 return 0; 8434 } 8435 8436 static DEFINE_PER_CPU(struct cpu_stop_work, push_work); 8437 8438 /* 8439 * Ensure we only run per-cpu kthreads once the CPU goes !active. 8440 * 8441 * This is enabled below SCHED_AP_ACTIVE; when !cpu_active(), but only 8442 * effective when the hotplug motion is down. 8443 */ 8444 static void balance_push(struct rq *rq) 8445 __must_hold(__rq_lockp(rq)) 8446 { 8447 struct task_struct *push_task = rq->curr; 8448 8449 lockdep_assert_rq_held(rq); 8450 8451 /* 8452 * Ensure the thing is persistent until balance_push_set(.on = false); 8453 */ 8454 rq->balance_callback = &balance_push_callback; 8455 8456 /* 8457 * Only active while going offline and when invoked on the outgoing 8458 * CPU. 8459 */ 8460 if (!cpu_dying(rq->cpu) || rq != this_rq()) 8461 return; 8462 8463 /* 8464 * Both the cpu-hotplug and stop task are in this case and are 8465 * required to complete the hotplug process. 8466 */ 8467 if (kthread_is_per_cpu(push_task) || 8468 is_migration_disabled(push_task)) { 8469 8470 /* 8471 * If this is the idle task on the outgoing CPU try to wake 8472 * up the hotplug control thread which might wait for the 8473 * last task to vanish. The rcuwait_active() check is 8474 * accurate here because the waiter is pinned on this CPU 8475 * and can't obviously be running in parallel. 8476 * 8477 * On RT kernels this also has to check whether there are 8478 * pinned and scheduled out tasks on the runqueue. They 8479 * need to leave the migrate disabled section first. 8480 */ 8481 if (!rq->nr_running && !rq_has_pinned_tasks(rq) && 8482 rcuwait_active(&rq->hotplug_wait)) { 8483 raw_spin_rq_unlock(rq); 8484 rcuwait_wake_up(&rq->hotplug_wait); 8485 raw_spin_rq_lock(rq); 8486 } 8487 return; 8488 } 8489 8490 get_task_struct(push_task); 8491 /* 8492 * Temporarily drop rq->lock such that we can wake-up the stop task. 8493 * Both preemption and IRQs are still disabled. 8494 */ 8495 preempt_disable(); 8496 raw_spin_rq_unlock(rq); 8497 stop_one_cpu_nowait(rq->cpu, __balance_push_cpu_stop, push_task, 8498 this_cpu_ptr(&push_work)); 8499 preempt_enable(); 8500 /* 8501 * At this point need_resched() is true and we'll take the loop in 8502 * schedule(). The next pick is obviously going to be the stop task 8503 * which kthread_is_per_cpu() and will push this task away. 8504 */ 8505 raw_spin_rq_lock(rq); 8506 } 8507 8508 static void balance_push_set(int cpu, bool on) 8509 { 8510 struct rq *rq = cpu_rq(cpu); 8511 struct rq_flags rf; 8512 8513 rq_lock_irqsave(rq, &rf); 8514 if (on) { 8515 WARN_ON_ONCE(rq->balance_callback); 8516 rq->balance_callback = &balance_push_callback; 8517 } else if (rq->balance_callback == &balance_push_callback) { 8518 rq->balance_callback = NULL; 8519 } 8520 rq_unlock_irqrestore(rq, &rf); 8521 } 8522 8523 /* 8524 * Invoked from a CPUs hotplug control thread after the CPU has been marked 8525 * inactive. All tasks which are not per CPU kernel threads are either 8526 * pushed off this CPU now via balance_push() or placed on a different CPU 8527 * during wakeup. Wait until the CPU is quiescent. 8528 */ 8529 static void balance_hotplug_wait(void) 8530 { 8531 struct rq *rq = this_rq(); 8532 8533 rcuwait_wait_event(&rq->hotplug_wait, 8534 rq->nr_running == 1 && !rq_has_pinned_tasks(rq), 8535 TASK_UNINTERRUPTIBLE); 8536 } 8537 8538 #else /* !CONFIG_HOTPLUG_CPU: */ 8539 8540 static inline void balance_push(struct rq *rq) 8541 { 8542 } 8543 8544 static inline void balance_push_set(int cpu, bool on) 8545 { 8546 } 8547 8548 static inline void balance_hotplug_wait(void) 8549 { 8550 } 8551 8552 #endif /* !CONFIG_HOTPLUG_CPU */ 8553 8554 void set_rq_online(struct rq *rq) 8555 { 8556 if (!rq->online) { 8557 const struct sched_class *class; 8558 8559 cpumask_set_cpu(rq->cpu, rq->rd->online); 8560 rq->online = 1; 8561 8562 for_each_class(class) { 8563 if (class->rq_online) 8564 class->rq_online(rq); 8565 } 8566 } 8567 } 8568 8569 void set_rq_offline(struct rq *rq) 8570 { 8571 if (rq->online) { 8572 const struct sched_class *class; 8573 8574 update_rq_clock(rq); 8575 for_each_class(class) { 8576 if (class->rq_offline) 8577 class->rq_offline(rq); 8578 } 8579 8580 cpumask_clear_cpu(rq->cpu, rq->rd->online); 8581 rq->online = 0; 8582 } 8583 } 8584 8585 static inline void sched_set_rq_online(struct rq *rq, int cpu) 8586 { 8587 struct rq_flags rf; 8588 8589 rq_lock_irqsave(rq, &rf); 8590 if (rq->rd) { 8591 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span)); 8592 set_rq_online(rq); 8593 } 8594 rq_unlock_irqrestore(rq, &rf); 8595 } 8596 8597 static inline void sched_set_rq_offline(struct rq *rq, int cpu) 8598 { 8599 struct rq_flags rf; 8600 8601 rq_lock_irqsave(rq, &rf); 8602 if (rq->rd) { 8603 BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span)); 8604 set_rq_offline(rq); 8605 } 8606 rq_unlock_irqrestore(rq, &rf); 8607 } 8608 8609 /* 8610 * used to mark begin/end of suspend/resume: 8611 */ 8612 static int num_cpus_frozen; 8613 8614 /* 8615 * Update cpusets according to cpu_active mask. If cpusets are 8616 * disabled, cpuset_update_active_cpus() becomes a simple wrapper 8617 * around partition_sched_domains(). 8618 * 8619 * If we come here as part of a suspend/resume, don't touch cpusets because we 8620 * want to restore it back to its original state upon resume anyway. 8621 */ 8622 static void cpuset_cpu_active(void) 8623 { 8624 if (cpuhp_tasks_frozen) { 8625 /* 8626 * num_cpus_frozen tracks how many CPUs are involved in suspend 8627 * resume sequence. As long as this is not the last online 8628 * operation in the resume sequence, just build a single sched 8629 * domain, ignoring cpusets. 8630 */ 8631 cpuset_reset_sched_domains(); 8632 if (--num_cpus_frozen) 8633 return; 8634 /* 8635 * This is the last CPU online operation. So fall through and 8636 * restore the original sched domains by considering the 8637 * cpuset configurations. 8638 */ 8639 cpuset_force_rebuild(); 8640 } 8641 cpuset_update_active_cpus(); 8642 } 8643 8644 static void cpuset_cpu_inactive(unsigned int cpu) 8645 { 8646 if (!cpuhp_tasks_frozen) { 8647 cpuset_update_active_cpus(); 8648 } else { 8649 num_cpus_frozen++; 8650 cpuset_reset_sched_domains(); 8651 } 8652 } 8653 8654 static inline void sched_smt_present_inc(int cpu) 8655 { 8656 if (cpumask_weight(cpu_smt_mask(cpu)) == 2) 8657 static_branch_inc_cpuslocked(&sched_smt_present); 8658 } 8659 8660 static inline void sched_smt_present_dec(int cpu) 8661 { 8662 if (cpumask_weight(cpu_smt_mask(cpu)) == 2) 8663 static_branch_dec_cpuslocked(&sched_smt_present); 8664 } 8665 8666 int sched_cpu_activate(unsigned int cpu) 8667 { 8668 struct rq *rq = cpu_rq(cpu); 8669 8670 /* 8671 * Clear the balance_push callback and prepare to schedule 8672 * regular tasks. 8673 */ 8674 balance_push_set(cpu, false); 8675 8676 /* 8677 * When going up, increment the number of cores with SMT present. 8678 */ 8679 sched_smt_present_inc(cpu); 8680 set_cpu_active(cpu, true); 8681 8682 if (sched_smp_initialized) { 8683 sched_update_numa(cpu, true); 8684 sched_domains_numa_masks_set(cpu); 8685 cpuset_cpu_active(); 8686 } 8687 8688 scx_rq_activate(rq); 8689 8690 /* 8691 * Put the rq online, if not already. This happens: 8692 * 8693 * 1) In the early boot process, because we build the real domains 8694 * after all CPUs have been brought up. 8695 * 8696 * 2) At runtime, if cpuset_cpu_active() fails to rebuild the 8697 * domains. 8698 */ 8699 sched_set_rq_online(rq, cpu); 8700 8701 return 0; 8702 } 8703 8704 int sched_cpu_deactivate(unsigned int cpu) 8705 { 8706 struct rq *rq = cpu_rq(cpu); 8707 int ret; 8708 8709 ret = dl_bw_deactivate(cpu); 8710 8711 if (ret) 8712 return ret; 8713 8714 /* 8715 * Remove CPU from nohz.idle_cpus_mask to prevent participating in 8716 * load balancing when not active 8717 */ 8718 scoped_guard (rcu) 8719 nohz_balance_exit_idle(rq); 8720 8721 set_cpu_active(cpu, false); 8722 8723 /* 8724 * From this point forward, this CPU will refuse to run any task that 8725 * is not: migrate_disable() or KTHREAD_IS_PER_CPU, and will actively 8726 * push those tasks away until this gets cleared, see 8727 * sched_cpu_dying(). 8728 */ 8729 balance_push_set(cpu, true); 8730 8731 /* 8732 * We've cleared cpu_active_mask / set balance_push, wait for all 8733 * preempt-disabled and RCU users of this state to go away such that 8734 * all new such users will observe it. 8735 * 8736 * Specifically, we rely on ttwu to no longer target this CPU, see 8737 * ttwu_queue_cond() and is_cpu_allowed(). 8738 * 8739 * Do sync before park smpboot threads to take care the RCU boost case. 8740 */ 8741 synchronize_rcu(); 8742 8743 sched_domains_free_llc_id(cpu); 8744 8745 sched_set_rq_offline(rq, cpu); 8746 8747 scx_rq_deactivate(rq); 8748 8749 /* 8750 * When going down, decrement the number of cores with SMT present. 8751 */ 8752 sched_smt_present_dec(cpu); 8753 8754 sched_core_cpu_deactivate(cpu); 8755 8756 if (!sched_smp_initialized) 8757 return 0; 8758 8759 sched_update_numa(cpu, false); 8760 cpuset_cpu_inactive(cpu); 8761 sched_domains_numa_masks_clear(cpu); 8762 return 0; 8763 } 8764 8765 static void sched_rq_cpu_starting(unsigned int cpu) 8766 { 8767 struct rq *rq = cpu_rq(cpu); 8768 8769 rq->calc_load_update = calc_load_update; 8770 update_max_interval(); 8771 } 8772 8773 int sched_cpu_starting(unsigned int cpu) 8774 { 8775 sched_core_cpu_starting(cpu); 8776 sched_rq_cpu_starting(cpu); 8777 sched_tick_start(cpu); 8778 return 0; 8779 } 8780 8781 #ifdef CONFIG_HOTPLUG_CPU 8782 8783 /* 8784 * Invoked immediately before the stopper thread is invoked to bring the 8785 * CPU down completely. At this point all per CPU kthreads except the 8786 * hotplug thread (current) and the stopper thread (inactive) have been 8787 * either parked or have been unbound from the outgoing CPU. Ensure that 8788 * any of those which might be on the way out are gone. 8789 * 8790 * If after this point a bound task is being woken on this CPU then the 8791 * responsible hotplug callback has failed to do it's job. 8792 * sched_cpu_dying() will catch it with the appropriate fireworks. 8793 */ 8794 int sched_cpu_wait_empty(unsigned int cpu) 8795 { 8796 balance_hotplug_wait(); 8797 sched_force_init_mm(); 8798 return 0; 8799 } 8800 8801 /* 8802 * Since this CPU is going 'away' for a while, fold any nr_active delta we 8803 * might have. Called from the CPU stopper task after ensuring that the 8804 * stopper is the last running task on the CPU, so nr_active count is 8805 * stable. We need to take the tear-down thread which is calling this into 8806 * account, so we hand in adjust = 1 to the load calculation. 8807 * 8808 * Also see the comment "Global load-average calculations". 8809 */ 8810 static void calc_load_migrate(struct rq *rq) 8811 { 8812 long delta = calc_load_fold_active(rq, 1); 8813 8814 if (delta) 8815 atomic_long_add(delta, &calc_load_tasks); 8816 } 8817 8818 static void dump_rq_tasks(struct rq *rq, const char *loglvl) 8819 { 8820 struct task_struct *g, *p; 8821 int cpu = cpu_of(rq); 8822 8823 lockdep_assert_rq_held(rq); 8824 8825 printk("%sCPU%d enqueued tasks (%u total):\n", loglvl, cpu, rq->nr_running); 8826 for_each_process_thread(g, p) { 8827 if (task_cpu(p) != cpu) 8828 continue; 8829 8830 if (!task_on_rq_queued(p)) 8831 continue; 8832 8833 printk("%s\tpid: %d, name: %s\n", loglvl, p->pid, p->comm); 8834 } 8835 } 8836 8837 int sched_cpu_dying(unsigned int cpu) 8838 { 8839 struct rq *rq = cpu_rq(cpu); 8840 struct rq_flags rf; 8841 8842 /* Handle pending wakeups and then migrate everything off */ 8843 sched_tick_stop(cpu); 8844 8845 rq_lock_irqsave(rq, &rf); 8846 update_rq_clock(rq); 8847 if (rq->nr_running != 1 || rq_has_pinned_tasks(rq)) { 8848 WARN(true, "Dying CPU not properly vacated!"); 8849 dump_rq_tasks(rq, KERN_WARNING); 8850 } 8851 dl_server_stop(&rq->fair_server); 8852 #ifdef CONFIG_SCHED_CLASS_EXT 8853 dl_server_stop(&rq->ext_server); 8854 #endif 8855 rq_unlock_irqrestore(rq, &rf); 8856 8857 calc_load_migrate(rq); 8858 update_max_interval(); 8859 hrtick_clear(rq); 8860 sched_core_cpu_dying(cpu); 8861 return 0; 8862 } 8863 #endif /* CONFIG_HOTPLUG_CPU */ 8864 8865 void __init sched_init_smp(void) 8866 { 8867 sched_init_numa(NUMA_NO_NODE); 8868 8869 prandom_init_once(&sched_rnd_state); 8870 8871 /* 8872 * There's no userspace yet to cause hotplug operations; hence all the 8873 * CPU masks are stable and all blatant races in the below code cannot 8874 * happen. 8875 */ 8876 sched_domains_mutex_lock(); 8877 sched_init_domains(cpu_active_mask); 8878 sched_domains_mutex_unlock(); 8879 8880 /* Move init over to a non-isolated CPU */ 8881 if (set_cpus_allowed_ptr(current, housekeeping_cpumask(HK_TYPE_DOMAIN)) < 0) 8882 BUG(); 8883 current->flags &= ~PF_NO_SETAFFINITY; 8884 sched_init_granularity(); 8885 8886 init_sched_rt_class(); 8887 init_sched_dl_class(); 8888 8889 sched_init_dl_servers(); 8890 8891 sched_smp_initialized = true; 8892 } 8893 8894 static int __init migration_init(void) 8895 { 8896 sched_cpu_starting(smp_processor_id()); 8897 return 0; 8898 } 8899 early_initcall(migration_init); 8900 8901 int in_sched_functions(unsigned long addr) 8902 { 8903 return in_lock_functions(addr) || 8904 (addr >= (unsigned long)__sched_text_start 8905 && addr < (unsigned long)__sched_text_end); 8906 } 8907 8908 #ifdef CONFIG_CGROUP_SCHED 8909 /* 8910 * Default task group. 8911 * Every task in system belongs to this group at bootup. 8912 */ 8913 struct task_group root_task_group; 8914 LIST_HEAD(task_groups); 8915 8916 /* Cacheline aligned slab cache for task_group */ 8917 static struct kmem_cache *task_group_cache __ro_after_init; 8918 #endif 8919 8920 void __init sched_init(void) 8921 { 8922 unsigned long __maybe_unused ptr = 0; 8923 int i; 8924 8925 /* Make sure the linker didn't screw up */ 8926 BUG_ON(!sched_class_above(&stop_sched_class, &dl_sched_class)); 8927 BUG_ON(!sched_class_above(&dl_sched_class, &rt_sched_class)); 8928 BUG_ON(!sched_class_above(&rt_sched_class, &fair_sched_class)); 8929 BUG_ON(!sched_class_above(&fair_sched_class, &idle_sched_class)); 8930 #ifdef CONFIG_SCHED_CLASS_EXT 8931 BUG_ON(!sched_class_above(&fair_sched_class, &ext_sched_class)); 8932 BUG_ON(!sched_class_above(&ext_sched_class, &idle_sched_class)); 8933 #endif 8934 8935 wait_bit_init(); 8936 8937 #ifdef CONFIG_FAIR_GROUP_SCHED 8938 root_task_group.cfs_rq = &runqueues.cfs; 8939 8940 root_task_group.shares = ROOT_TASK_GROUP_LOAD; 8941 init_cfs_bandwidth(&root_task_group.cfs_bandwidth, NULL); 8942 #endif /* CONFIG_FAIR_GROUP_SCHED */ 8943 #ifdef CONFIG_EXT_GROUP_SCHED 8944 scx_tg_init(&root_task_group); 8945 #endif /* CONFIG_EXT_GROUP_SCHED */ 8946 #ifdef CONFIG_RT_GROUP_SCHED 8947 ptr += 2 * nr_cpu_ids * sizeof(void **); 8948 ptr = (unsigned long)kzalloc(ptr, GFP_NOWAIT); 8949 root_task_group.rt_se = (struct sched_rt_entity **)ptr; 8950 ptr += nr_cpu_ids * sizeof(void **); 8951 8952 root_task_group.rt_rq = (struct rt_rq **)ptr; 8953 ptr += nr_cpu_ids * sizeof(void **); 8954 8955 #endif /* CONFIG_RT_GROUP_SCHED */ 8956 8957 init_defrootdomain(); 8958 8959 #ifdef CONFIG_RT_GROUP_SCHED 8960 init_rt_bandwidth(&root_task_group.rt_bandwidth, 8961 global_rt_period(), global_rt_runtime()); 8962 #endif /* CONFIG_RT_GROUP_SCHED */ 8963 8964 #ifdef CONFIG_CGROUP_SCHED 8965 task_group_cache = KMEM_CACHE(task_group, 0); 8966 8967 list_add(&root_task_group.list, &task_groups); 8968 INIT_LIST_HEAD(&root_task_group.children); 8969 INIT_LIST_HEAD(&root_task_group.siblings); 8970 autogroup_init(&init_task); 8971 #endif /* CONFIG_CGROUP_SCHED */ 8972 8973 for_each_possible_cpu(i) { 8974 struct rq *rq; 8975 8976 rq = cpu_rq(i); 8977 raw_spin_lock_init(&rq->__lock); 8978 rq->nr_running = 0; 8979 rq->calc_load_active = 0; 8980 rq->calc_load_update = jiffies + LOAD_FREQ; 8981 init_cfs_rq(&rq->cfs); 8982 init_rt_rq(&rq->rt); 8983 init_dl_rq(&rq->dl); 8984 #ifdef CONFIG_FAIR_GROUP_SCHED 8985 INIT_LIST_HEAD(&rq->leaf_cfs_rq_list); 8986 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list; 8987 /* 8988 * How much CPU bandwidth does root_task_group get? 8989 * 8990 * In case of task-groups formed through the cgroup filesystem, it 8991 * gets 100% of the CPU resources in the system. This overall 8992 * system CPU resource is divided among the tasks of 8993 * root_task_group and its child task-groups in a fair manner, 8994 * based on each entity's (task or task-group's) weight 8995 * (se->load.weight). 8996 * 8997 * In other words, if root_task_group has 10 tasks of weight 8998 * 1024) and two child groups A0 and A1 (of weight 1024 each), 8999 * then A0's share of the CPU resource is: 9000 * 9001 * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33% 9002 * 9003 * We achieve this by letting root_task_group's tasks sit 9004 * directly in rq->cfs (i.e root_task_group->se[] = NULL). 9005 */ 9006 init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL); 9007 #endif /* CONFIG_FAIR_GROUP_SCHED */ 9008 9009 #ifdef CONFIG_RT_GROUP_SCHED 9010 /* 9011 * This is required for init cpu because rt.c:__enable_runtime() 9012 * starts working after scheduler_running, which is not the case 9013 * yet. 9014 */ 9015 rq->rt.rt_runtime = global_rt_runtime(); 9016 init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL); 9017 #endif 9018 rq->next_class = &idle_sched_class; 9019 9020 rq->sd = NULL; 9021 rq->rd = NULL; 9022 rq->cpu_capacity = SCHED_CAPACITY_SCALE; 9023 rq->balance_callback = &balance_push_callback; 9024 rq->active_balance = 0; 9025 rq->next_balance = jiffies; 9026 rq->push_cpu = 0; 9027 rq->cpu = i; 9028 rq->online = 0; 9029 rq->idle_stamp = 0; 9030 rq->avg_idle = 2*sysctl_sched_migration_cost; 9031 rq->max_idle_balance_cost = sysctl_sched_migration_cost; 9032 9033 INIT_LIST_HEAD(&rq->cfs_tasks); 9034 9035 rq_attach_root(rq, &def_root_domain); 9036 #ifdef CONFIG_NO_HZ_COMMON 9037 rq->last_blocked_load_update_tick = jiffies; 9038 atomic_set(&rq->nohz_flags, 0); 9039 9040 INIT_CSD(&rq->nohz_csd, nohz_csd_func, rq); 9041 #endif 9042 #ifdef CONFIG_HOTPLUG_CPU 9043 rcuwait_init(&rq->hotplug_wait); 9044 #endif 9045 hrtick_rq_init(rq); 9046 atomic_set(&rq->nr_iowait, 0); 9047 fair_server_init(rq); 9048 #ifdef CONFIG_SCHED_CLASS_EXT 9049 ext_server_init(rq); 9050 #endif 9051 9052 #ifdef CONFIG_SCHED_CORE 9053 rq->core = rq; 9054 rq->core_pick = NULL; 9055 rq->core_dl_server = NULL; 9056 rq->core_enabled = 0; 9057 rq->core_tree = RB_ROOT; 9058 rq->core_forceidle_count = 0; 9059 rq->core_forceidle_occupation = 0; 9060 rq->core_forceidle_start = 0; 9061 9062 rq->core_cookie = 0UL; 9063 #endif 9064 #ifdef CONFIG_SCHED_CACHE 9065 raw_spin_lock_init(&rq->cpu_epoch_lock); 9066 rq->cpu_epoch_next = jiffies; 9067 #endif 9068 9069 zalloc_cpumask_var_node(&rq->scratch_mask, GFP_KERNEL, cpu_to_node(i)); 9070 } 9071 9072 set_load_weight(&init_task, false); 9073 init_task.se.slice = sysctl_sched_base_slice, 9074 9075 /* 9076 * The boot idle thread does lazy MMU switching as well: 9077 */ 9078 mmgrab_lazy_tlb(&init_mm); 9079 enter_lazy_tlb(&init_mm, current); 9080 9081 /* 9082 * The idle task doesn't need the kthread struct to function, but it 9083 * is dressed up as a per-CPU kthread and thus needs to play the part 9084 * if we want to avoid special-casing it in code that deals with per-CPU 9085 * kthreads. 9086 */ 9087 WARN_ON(!set_kthread_struct(current)); 9088 9089 /* 9090 * Make us the idle thread. Technically, schedule() should not be 9091 * called from this thread, however somewhere below it might be, 9092 * but because we are the idle thread, we just pick up running again 9093 * when this runqueue becomes "idle". 9094 */ 9095 __sched_fork(0, current); 9096 init_idle(current, smp_processor_id()); 9097 9098 calc_load_update = jiffies + LOAD_FREQ; 9099 9100 idle_thread_set_boot_cpu(); 9101 9102 balance_push_set(smp_processor_id(), false); 9103 init_sched_fair_class(); 9104 init_sched_ext_class(); 9105 9106 psi_init(); 9107 9108 init_uclamp(); 9109 9110 preempt_dynamic_init(); 9111 9112 scheduler_running = 1; 9113 } 9114 9115 #ifdef CONFIG_DEBUG_ATOMIC_SLEEP 9116 9117 void __might_sleep(const char *file, int line) 9118 { 9119 unsigned int state = get_current_state(); 9120 /* 9121 * Blocking primitives will set (and therefore destroy) current->state, 9122 * since we will exit with TASK_RUNNING make sure we enter with it, 9123 * otherwise we will destroy state. 9124 */ 9125 WARN_ONCE(state != TASK_RUNNING && current->task_state_change, 9126 "do not call blocking ops when !TASK_RUNNING; " 9127 "state=%x set at [<%p>] %pS\n", state, 9128 (void *)current->task_state_change, 9129 (void *)current->task_state_change); 9130 9131 __might_resched(file, line, 0); 9132 } 9133 EXPORT_SYMBOL(__might_sleep); 9134 9135 static void print_preempt_disable_ip(int preempt_offset, unsigned long ip) 9136 { 9137 if (!IS_ENABLED(CONFIG_DEBUG_PREEMPT)) 9138 return; 9139 9140 if (preempt_count() == preempt_offset) 9141 return; 9142 9143 pr_err("Preemption disabled at:"); 9144 print_ip_sym(KERN_ERR, ip); 9145 } 9146 9147 static inline bool resched_offsets_ok(unsigned int offsets) 9148 { 9149 unsigned int nested = preempt_count(); 9150 9151 nested += rcu_preempt_depth() << MIGHT_RESCHED_RCU_SHIFT; 9152 9153 return nested == offsets; 9154 } 9155 9156 void __might_resched(const char *file, int line, unsigned int offsets) 9157 { 9158 /* Ratelimiting timestamp: */ 9159 static unsigned long prev_jiffy; 9160 9161 unsigned long preempt_disable_ip; 9162 9163 /* WARN_ON_ONCE() by default, no rate limit required: */ 9164 rcu_sleep_check(); 9165 9166 if ((resched_offsets_ok(offsets) && !irqs_disabled() && 9167 !is_idle_task(current) && !current->non_block_count) || 9168 system_state == SYSTEM_BOOTING || system_state > SYSTEM_RUNNING || 9169 oops_in_progress) 9170 return; 9171 9172 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy) 9173 return; 9174 prev_jiffy = jiffies; 9175 9176 /* Save this before calling printk(), since that will clobber it: */ 9177 preempt_disable_ip = get_preempt_disable_ip(current); 9178 9179 pr_err("BUG: sleeping function called from invalid context at %s:%d\n", 9180 file, line); 9181 pr_err("in_atomic(): %d, irqs_disabled(): %d, non_block: %d, pid: %d, name: %s\n", 9182 in_atomic(), irqs_disabled(), current->non_block_count, 9183 current->pid, current->comm); 9184 pr_err("preempt_count: %x, expected: %x\n", preempt_count(), 9185 offsets & MIGHT_RESCHED_PREEMPT_MASK); 9186 9187 if (IS_ENABLED(CONFIG_PREEMPT_RCU)) { 9188 pr_err("RCU nest depth: %d, expected: %u\n", 9189 rcu_preempt_depth(), offsets >> MIGHT_RESCHED_RCU_SHIFT); 9190 } 9191 9192 if (task_stack_end_corrupted(current)) 9193 pr_emerg("Thread overran stack, or stack corrupted\n"); 9194 9195 debug_show_held_locks(current); 9196 if (irqs_disabled()) 9197 print_irqtrace_events(current); 9198 9199 print_preempt_disable_ip(offsets & MIGHT_RESCHED_PREEMPT_MASK, 9200 preempt_disable_ip); 9201 9202 dump_stack(); 9203 add_taint(TAINT_WARN, LOCKDEP_STILL_OK); 9204 } 9205 EXPORT_SYMBOL(__might_resched); 9206 9207 void __cant_sleep(const char *file, int line) 9208 { 9209 static unsigned long prev_jiffy; 9210 9211 if (irqs_disabled()) 9212 return; 9213 9214 if (!IS_ENABLED(CONFIG_PREEMPT_COUNT)) 9215 return; 9216 9217 if (preempt_count()) 9218 return; 9219 9220 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy) 9221 return; 9222 prev_jiffy = jiffies; 9223 9224 printk(KERN_ERR "BUG: assuming atomic context at %s:%d\n", file, line); 9225 printk(KERN_ERR "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n", 9226 in_atomic(), irqs_disabled(), 9227 current->pid, current->comm); 9228 9229 debug_show_held_locks(current); 9230 dump_stack(); 9231 add_taint(TAINT_WARN, LOCKDEP_STILL_OK); 9232 } 9233 EXPORT_SYMBOL_GPL(__cant_sleep); 9234 9235 # ifdef CONFIG_SMP 9236 void __cant_migrate(const char *file, int line) 9237 { 9238 static unsigned long prev_jiffy; 9239 9240 if (irqs_disabled()) 9241 return; 9242 9243 if (is_migration_disabled(current)) 9244 return; 9245 9246 if (!IS_ENABLED(CONFIG_PREEMPT_COUNT)) 9247 return; 9248 9249 if (preempt_count()) 9250 return; 9251 9252 if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy) 9253 return; 9254 prev_jiffy = jiffies; 9255 9256 pr_err("BUG: assuming non migratable context at %s:%d\n", file, line); 9257 pr_err("in_atomic(): %d, irqs_disabled(): %d, migration_disabled() %u pid: %d, name: %s\n", 9258 in_atomic(), irqs_disabled(), is_migration_disabled(current), 9259 current->pid, current->comm); 9260 9261 debug_show_held_locks(current); 9262 dump_stack(); 9263 add_taint(TAINT_WARN, LOCKDEP_STILL_OK); 9264 } 9265 EXPORT_SYMBOL_GPL(__cant_migrate); 9266 # endif /* CONFIG_SMP */ 9267 #endif /* CONFIG_DEBUG_ATOMIC_SLEEP */ 9268 9269 #ifdef CONFIG_MAGIC_SYSRQ 9270 void normalize_rt_tasks(void) 9271 { 9272 struct task_struct *g, *p; 9273 struct sched_attr attr = { 9274 .sched_policy = SCHED_NORMAL, 9275 }; 9276 9277 read_lock(&tasklist_lock); 9278 for_each_process_thread(g, p) { 9279 /* 9280 * Only normalize user tasks: 9281 */ 9282 if (p->flags & PF_KTHREAD) 9283 continue; 9284 9285 p->se.exec_start = 0; 9286 schedstat_set(p->stats.wait_start, 0); 9287 schedstat_set(p->stats.sleep_start, 0); 9288 schedstat_set(p->stats.block_start, 0); 9289 9290 if (!rt_or_dl_task(p)) { 9291 /* 9292 * Renice negative nice level userspace 9293 * tasks back to 0: 9294 */ 9295 if (task_nice(p) < 0) 9296 set_user_nice(p, 0); 9297 continue; 9298 } 9299 9300 __sched_setscheduler(p, &attr, false, false); 9301 } 9302 read_unlock(&tasklist_lock); 9303 } 9304 9305 #endif /* CONFIG_MAGIC_SYSRQ */ 9306 9307 #ifdef CONFIG_KGDB_KDB 9308 /* 9309 * These functions are only useful for KDB. 9310 * 9311 * They can only be called when the whole system has been 9312 * stopped - every CPU needs to be quiescent, and no scheduling 9313 * activity can take place. Using them for anything else would 9314 * be a serious bug, and as a result, they aren't even visible 9315 * under any other configuration. 9316 */ 9317 9318 /** 9319 * curr_task - return the current task for a given CPU. 9320 * @cpu: the processor in question. 9321 * 9322 * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED! 9323 * 9324 * Return: The current task for @cpu. 9325 */ 9326 struct task_struct *curr_task(int cpu) 9327 { 9328 return cpu_curr(cpu); 9329 } 9330 9331 #endif /* CONFIG_KGDB_KDB */ 9332 9333 #ifdef CONFIG_CGROUP_SCHED 9334 /* task_group_lock serializes the addition/removal of task groups */ 9335 static DEFINE_SPINLOCK(task_group_lock); 9336 9337 static inline void alloc_uclamp_sched_group(struct task_group *tg, 9338 struct task_group *parent) 9339 { 9340 #ifdef CONFIG_UCLAMP_TASK_GROUP 9341 enum uclamp_id clamp_id; 9342 9343 for_each_clamp_id(clamp_id) { 9344 uclamp_se_set(&tg->uclamp_req[clamp_id], 9345 uclamp_none(clamp_id), false); 9346 tg->uclamp[clamp_id] = parent->uclamp[clamp_id]; 9347 } 9348 #endif 9349 } 9350 9351 static void sched_free_group(struct task_group *tg) 9352 { 9353 free_fair_sched_group(tg); 9354 free_rt_sched_group(tg); 9355 autogroup_free(tg); 9356 kmem_cache_free(task_group_cache, tg); 9357 } 9358 9359 static void sched_free_group_rcu(struct rcu_head *rcu) 9360 { 9361 sched_free_group(container_of(rcu, struct task_group, rcu)); 9362 } 9363 9364 static void sched_unregister_group(struct task_group *tg) 9365 { 9366 unregister_fair_sched_group(tg); 9367 unregister_rt_sched_group(tg); 9368 /* 9369 * We have to wait for yet another RCU grace period to expire, as 9370 * print_cfs_stats() might run concurrently. 9371 */ 9372 call_rcu(&tg->rcu, sched_free_group_rcu); 9373 } 9374 9375 /* allocate runqueue etc for a new task group */ 9376 struct task_group *sched_create_group(struct task_group *parent) 9377 { 9378 struct task_group *tg; 9379 9380 tg = kmem_cache_alloc(task_group_cache, GFP_KERNEL | __GFP_ZERO); 9381 if (!tg) 9382 return ERR_PTR(-ENOMEM); 9383 9384 if (!alloc_fair_sched_group(tg, parent)) 9385 goto err; 9386 9387 if (!alloc_rt_sched_group(tg, parent)) 9388 goto err; 9389 9390 scx_tg_init(tg); 9391 alloc_uclamp_sched_group(tg, parent); 9392 9393 return tg; 9394 9395 err: 9396 sched_free_group(tg); 9397 return ERR_PTR(-ENOMEM); 9398 } 9399 9400 void sched_online_group(struct task_group *tg, struct task_group *parent) 9401 { 9402 unsigned long flags; 9403 9404 spin_lock_irqsave(&task_group_lock, flags); 9405 list_add_tail_rcu(&tg->list, &task_groups); 9406 9407 /* Root should already exist: */ 9408 WARN_ON(!parent); 9409 9410 tg->parent = parent; 9411 INIT_LIST_HEAD(&tg->children); 9412 list_add_rcu(&tg->siblings, &parent->children); 9413 spin_unlock_irqrestore(&task_group_lock, flags); 9414 9415 online_fair_sched_group(tg); 9416 } 9417 9418 /* RCU callback to free various structures associated with a task group */ 9419 static void sched_unregister_group_rcu(struct rcu_head *rhp) 9420 { 9421 /* Now it should be safe to free those cfs_rqs: */ 9422 sched_unregister_group(container_of(rhp, struct task_group, rcu)); 9423 } 9424 9425 void sched_destroy_group(struct task_group *tg) 9426 { 9427 /* Wait for possible concurrent references to cfs_rqs complete: */ 9428 call_rcu(&tg->rcu, sched_unregister_group_rcu); 9429 } 9430 9431 void sched_release_group(struct task_group *tg) 9432 { 9433 unsigned long flags; 9434 9435 /* 9436 * Unlink first, to avoid walk_tg_tree_from() from finding us (via 9437 * sched_cfs_period_timer()). 9438 * 9439 * For this to be effective, we have to wait for all pending users of 9440 * this task group to leave their RCU critical section to ensure no new 9441 * user will see our dying task group any more. Specifically ensure 9442 * that tg_unthrottle_up() won't add decayed cfs_rq's to it. 9443 * 9444 * We therefore defer calling unregister_fair_sched_group() to 9445 * sched_unregister_group() which is guarantied to get called only after the 9446 * current RCU grace period has expired. 9447 */ 9448 spin_lock_irqsave(&task_group_lock, flags); 9449 list_del_rcu(&tg->list); 9450 list_del_rcu(&tg->siblings); 9451 spin_unlock_irqrestore(&task_group_lock, flags); 9452 } 9453 9454 static void sched_change_group(struct task_struct *tsk) 9455 { 9456 struct task_group *tg; 9457 9458 /* 9459 * All callers are synchronized by task_rq_lock(); we do not use RCU 9460 * which is pointless here. Thus, we pass "true" to task_css_check() 9461 * to prevent lockdep warnings. 9462 */ 9463 tg = container_of(task_css_check(tsk, cpu_cgrp_id, true), 9464 struct task_group, css); 9465 tg = autogroup_task_group(tsk, tg); 9466 tsk->sched_task_group = tg; 9467 9468 #ifdef CONFIG_FAIR_GROUP_SCHED 9469 if (tsk->sched_class->task_change_group) 9470 tsk->sched_class->task_change_group(tsk); 9471 else 9472 #endif 9473 set_task_rq(tsk, task_cpu(tsk)); 9474 } 9475 9476 /* 9477 * Change task's runqueue when it moves between groups. 9478 * 9479 * The caller of this function should have put the task in its new group by 9480 * now. This function just updates tsk->se.cfs_rq and tsk->se.parent to reflect 9481 * its new group. 9482 */ 9483 void sched_move_task(struct task_struct *tsk, bool for_autogroup) 9484 { 9485 unsigned int queue_flags = DEQUEUE_SAVE | DEQUEUE_MOVE; 9486 bool resched = false; 9487 bool queued = false; 9488 struct rq *rq; 9489 9490 CLASS(task_rq_lock, rq_guard)(tsk); 9491 rq = rq_guard.rq; 9492 9493 scoped_guard (sched_change, tsk, queue_flags) { 9494 sched_change_group(tsk); 9495 if (!for_autogroup) 9496 scx_cgroup_move_task(tsk); 9497 if (scope->running) 9498 resched = true; 9499 queued = scope->queued; 9500 } 9501 9502 if (resched) 9503 resched_curr(rq); 9504 else if (queued) 9505 wakeup_preempt(rq, tsk, 0); 9506 9507 __balance_callbacks(rq, &rq_guard.rf); 9508 } 9509 9510 static struct cgroup_subsys_state * 9511 cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css) 9512 { 9513 struct task_group *parent = css_tg(parent_css); 9514 struct task_group *tg; 9515 9516 if (!parent) { 9517 /* This is early initialization for the top cgroup */ 9518 return &root_task_group.css; 9519 } 9520 9521 tg = sched_create_group(parent); 9522 if (IS_ERR(tg)) 9523 return ERR_PTR(-ENOMEM); 9524 9525 return &tg->css; 9526 } 9527 9528 /* Expose task group only after completing cgroup initialization */ 9529 static int cpu_cgroup_css_online(struct cgroup_subsys_state *css) 9530 { 9531 struct task_group *tg = css_tg(css); 9532 struct task_group *parent = css_tg(css->parent); 9533 int ret; 9534 9535 ret = scx_tg_online(tg); 9536 if (ret) 9537 return ret; 9538 9539 if (parent) 9540 sched_online_group(tg, parent); 9541 9542 #ifdef CONFIG_UCLAMP_TASK_GROUP 9543 /* Propagate the effective uclamp value for the new group */ 9544 guard(mutex)(&uclamp_mutex); 9545 guard(rcu)(); 9546 cpu_util_update_eff(css); 9547 #endif 9548 9549 return 0; 9550 } 9551 9552 static void cpu_cgroup_css_offline(struct cgroup_subsys_state *css) 9553 { 9554 struct task_group *tg = css_tg(css); 9555 9556 scx_tg_offline(tg); 9557 } 9558 9559 static void cpu_cgroup_css_released(struct cgroup_subsys_state *css) 9560 { 9561 struct task_group *tg = css_tg(css); 9562 9563 sched_release_group(tg); 9564 } 9565 9566 static void cpu_cgroup_css_free(struct cgroup_subsys_state *css) 9567 { 9568 struct task_group *tg = css_tg(css); 9569 9570 /* 9571 * Relies on the RCU grace period between css_released() and this. 9572 */ 9573 sched_unregister_group(tg); 9574 } 9575 9576 static int cpu_cgroup_can_attach(struct cgroup_taskset *tset) 9577 { 9578 #ifdef CONFIG_RT_GROUP_SCHED 9579 struct task_struct *task; 9580 struct cgroup_subsys_state *css; 9581 9582 if (!rt_group_sched_enabled()) 9583 goto scx_check; 9584 9585 cgroup_taskset_for_each(task, css, tset) { 9586 if (!sched_rt_can_attach(css_tg(css), task)) 9587 return -EINVAL; 9588 } 9589 scx_check: 9590 #endif /* CONFIG_RT_GROUP_SCHED */ 9591 return scx_cgroup_can_attach(tset); 9592 } 9593 9594 static void cpu_cgroup_attach(struct cgroup_taskset *tset) 9595 { 9596 struct task_struct *task; 9597 struct cgroup_subsys_state *css; 9598 9599 cgroup_taskset_for_each(task, css, tset) 9600 sched_move_task(task, false); 9601 } 9602 9603 static void cpu_cgroup_cancel_attach(struct cgroup_taskset *tset) 9604 { 9605 scx_cgroup_cancel_attach(tset); 9606 } 9607 9608 #ifdef CONFIG_UCLAMP_TASK_GROUP 9609 static void cpu_util_update_eff(struct cgroup_subsys_state *css) 9610 { 9611 struct cgroup_subsys_state *top_css = css; 9612 struct uclamp_se *uc_parent = NULL; 9613 struct uclamp_se *uc_se = NULL; 9614 unsigned int eff[UCLAMP_CNT]; 9615 enum uclamp_id clamp_id; 9616 unsigned int clamps; 9617 9618 lockdep_assert_held(&uclamp_mutex); 9619 WARN_ON_ONCE(!rcu_read_lock_held()); 9620 9621 css_for_each_descendant_pre(css, top_css) { 9622 uc_parent = css_tg(css)->parent 9623 ? css_tg(css)->parent->uclamp : NULL; 9624 9625 for_each_clamp_id(clamp_id) { 9626 /* Assume effective clamps matches requested clamps */ 9627 eff[clamp_id] = css_tg(css)->uclamp_req[clamp_id].value; 9628 /* Cap effective clamps with parent's effective clamps */ 9629 if (uc_parent && 9630 eff[clamp_id] > uc_parent[clamp_id].value) { 9631 eff[clamp_id] = uc_parent[clamp_id].value; 9632 } 9633 } 9634 /* Ensure protection is always capped by limit */ 9635 eff[UCLAMP_MIN] = min(eff[UCLAMP_MIN], eff[UCLAMP_MAX]); 9636 9637 /* Propagate most restrictive effective clamps */ 9638 clamps = 0x0; 9639 uc_se = css_tg(css)->uclamp; 9640 for_each_clamp_id(clamp_id) { 9641 if (eff[clamp_id] == uc_se[clamp_id].value) 9642 continue; 9643 uc_se[clamp_id].value = eff[clamp_id]; 9644 uc_se[clamp_id].bucket_id = uclamp_bucket_id(eff[clamp_id]); 9645 clamps |= (0x1 << clamp_id); 9646 } 9647 if (!clamps) { 9648 css = css_rightmost_descendant(css); 9649 continue; 9650 } 9651 9652 /* Immediately update descendants RUNNABLE tasks */ 9653 uclamp_update_active_tasks(css); 9654 } 9655 } 9656 9657 /* 9658 * Integer 10^N with a given N exponent by casting to integer the literal "1eN" 9659 * C expression. Since there is no way to convert a macro argument (N) into a 9660 * character constant, use two levels of macros. 9661 */ 9662 #define _POW10(exp) ((unsigned int)1e##exp) 9663 #define POW10(exp) _POW10(exp) 9664 9665 struct uclamp_request { 9666 #define UCLAMP_PERCENT_SHIFT 2 9667 #define UCLAMP_PERCENT_SCALE (100 * POW10(UCLAMP_PERCENT_SHIFT)) 9668 s64 percent; 9669 u64 util; 9670 int ret; 9671 }; 9672 9673 static inline struct uclamp_request 9674 capacity_from_percent(char *buf) 9675 { 9676 struct uclamp_request req = { 9677 .percent = UCLAMP_PERCENT_SCALE, 9678 .util = SCHED_CAPACITY_SCALE, 9679 .ret = 0, 9680 }; 9681 9682 buf = strim(buf); 9683 if (strcmp(buf, "max")) { 9684 req.ret = cgroup_parse_float(buf, UCLAMP_PERCENT_SHIFT, 9685 &req.percent); 9686 if (req.ret) 9687 return req; 9688 if ((u64)req.percent > UCLAMP_PERCENT_SCALE) { 9689 req.ret = -ERANGE; 9690 return req; 9691 } 9692 9693 req.util = req.percent << SCHED_CAPACITY_SHIFT; 9694 req.util = DIV_ROUND_CLOSEST_ULL(req.util, UCLAMP_PERCENT_SCALE); 9695 } 9696 9697 return req; 9698 } 9699 9700 static ssize_t cpu_uclamp_write(struct kernfs_open_file *of, char *buf, 9701 size_t nbytes, loff_t off, 9702 enum uclamp_id clamp_id) 9703 { 9704 struct uclamp_request req; 9705 struct task_group *tg; 9706 9707 req = capacity_from_percent(buf); 9708 if (req.ret) 9709 return req.ret; 9710 9711 sched_uclamp_enable(); 9712 9713 guard(mutex)(&uclamp_mutex); 9714 guard(rcu)(); 9715 9716 tg = css_tg(of_css(of)); 9717 if (tg->uclamp_req[clamp_id].value != req.util) 9718 uclamp_se_set(&tg->uclamp_req[clamp_id], req.util, false); 9719 9720 /* 9721 * Because of not recoverable conversion rounding we keep track of the 9722 * exact requested value 9723 */ 9724 tg->uclamp_pct[clamp_id] = req.percent; 9725 9726 /* Update effective clamps to track the most restrictive value */ 9727 cpu_util_update_eff(of_css(of)); 9728 9729 return nbytes; 9730 } 9731 9732 static ssize_t cpu_uclamp_min_write(struct kernfs_open_file *of, 9733 char *buf, size_t nbytes, 9734 loff_t off) 9735 { 9736 return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MIN); 9737 } 9738 9739 static ssize_t cpu_uclamp_max_write(struct kernfs_open_file *of, 9740 char *buf, size_t nbytes, 9741 loff_t off) 9742 { 9743 return cpu_uclamp_write(of, buf, nbytes, off, UCLAMP_MAX); 9744 } 9745 9746 static inline void cpu_uclamp_print(struct seq_file *sf, 9747 enum uclamp_id clamp_id) 9748 { 9749 struct task_group *tg; 9750 u64 util_clamp; 9751 u64 percent; 9752 u32 rem; 9753 9754 scoped_guard (rcu) { 9755 tg = css_tg(seq_css(sf)); 9756 util_clamp = tg->uclamp_req[clamp_id].value; 9757 } 9758 9759 if (util_clamp == SCHED_CAPACITY_SCALE) { 9760 seq_puts(sf, "max\n"); 9761 return; 9762 } 9763 9764 percent = tg->uclamp_pct[clamp_id]; 9765 percent = div_u64_rem(percent, POW10(UCLAMP_PERCENT_SHIFT), &rem); 9766 seq_printf(sf, "%llu.%0*u\n", percent, UCLAMP_PERCENT_SHIFT, rem); 9767 } 9768 9769 static int cpu_uclamp_min_show(struct seq_file *sf, void *v) 9770 { 9771 cpu_uclamp_print(sf, UCLAMP_MIN); 9772 return 0; 9773 } 9774 9775 static int cpu_uclamp_max_show(struct seq_file *sf, void *v) 9776 { 9777 cpu_uclamp_print(sf, UCLAMP_MAX); 9778 return 0; 9779 } 9780 #endif /* CONFIG_UCLAMP_TASK_GROUP */ 9781 9782 #ifdef CONFIG_GROUP_SCHED_WEIGHT 9783 static unsigned long tg_weight(struct task_group *tg) 9784 { 9785 #ifdef CONFIG_FAIR_GROUP_SCHED 9786 return scale_load_down(tg->shares); 9787 #else 9788 return sched_weight_from_cgroup(tg->scx.weight); 9789 #endif 9790 } 9791 9792 static int cpu_shares_write_u64(struct cgroup_subsys_state *css, 9793 struct cftype *cftype, u64 shareval) 9794 { 9795 int ret; 9796 9797 if (shareval > scale_load_down(ULONG_MAX)) 9798 shareval = MAX_SHARES; 9799 ret = sched_group_set_shares(css_tg(css), scale_load(shareval)); 9800 if (!ret) 9801 scx_group_set_weight(css_tg(css), 9802 sched_weight_to_cgroup(shareval)); 9803 return ret; 9804 } 9805 9806 static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css, 9807 struct cftype *cft) 9808 { 9809 return tg_weight(css_tg(css)); 9810 } 9811 #endif /* CONFIG_GROUP_SCHED_WEIGHT */ 9812 9813 #ifdef CONFIG_CFS_BANDWIDTH 9814 static DEFINE_MUTEX(cfs_constraints_mutex); 9815 9816 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime); 9817 9818 static int tg_set_cfs_bandwidth(struct task_group *tg, 9819 u64 period_us, u64 quota_us, u64 burst_us) 9820 { 9821 int i, ret = 0, runtime_enabled, runtime_was_enabled; 9822 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; 9823 u64 period, quota, burst; 9824 9825 period = (u64)period_us * NSEC_PER_USEC; 9826 9827 if (quota_us == RUNTIME_INF) 9828 quota = RUNTIME_INF; 9829 else 9830 quota = (u64)quota_us * NSEC_PER_USEC; 9831 9832 burst = (u64)burst_us * NSEC_PER_USEC; 9833 9834 /* 9835 * Prevent race between setting of cfs_rq->runtime_enabled and 9836 * unthrottle_offline_cfs_rqs(). 9837 */ 9838 guard(cpus_read_lock)(); 9839 guard(mutex)(&cfs_constraints_mutex); 9840 9841 ret = __cfs_schedulable(tg, period, quota); 9842 if (ret) 9843 return ret; 9844 9845 runtime_enabled = quota != RUNTIME_INF; 9846 runtime_was_enabled = cfs_b->quota != RUNTIME_INF; 9847 /* 9848 * If we need to toggle cfs_bandwidth_used, off->on must occur 9849 * before making related changes, and on->off must occur afterwards 9850 */ 9851 if (runtime_enabled && !runtime_was_enabled) 9852 cfs_bandwidth_usage_inc(); 9853 9854 scoped_guard (raw_spinlock_irq, &cfs_b->lock) { 9855 cfs_b->period = ns_to_ktime(period); 9856 cfs_b->quota = quota; 9857 cfs_b->burst = burst; 9858 9859 __refill_cfs_bandwidth_runtime(cfs_b); 9860 9861 /* 9862 * Restart the period timer (if active) to handle new 9863 * period expiry: 9864 */ 9865 if (runtime_enabled) 9866 start_cfs_bandwidth(cfs_b); 9867 } 9868 9869 for_each_online_cpu(i) { 9870 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, i); 9871 struct rq *rq = cfs_rq->rq; 9872 9873 guard(rq_lock_irq)(rq); 9874 9875 cfs_rq->runtime_enabled = runtime_enabled; 9876 cfs_rq->runtime_remaining = 1; 9877 9878 if (cfs_rq->throttled) { 9879 update_rq_clock(rq); 9880 unthrottle_cfs_rq(cfs_rq); 9881 } 9882 } 9883 9884 if (runtime_was_enabled && !runtime_enabled) 9885 cfs_bandwidth_usage_dec(); 9886 9887 return 0; 9888 } 9889 9890 static u64 tg_get_cfs_period(struct task_group *tg) 9891 { 9892 u64 cfs_period_us; 9893 9894 cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period); 9895 do_div(cfs_period_us, NSEC_PER_USEC); 9896 9897 return cfs_period_us; 9898 } 9899 9900 static u64 tg_get_cfs_quota(struct task_group *tg) 9901 { 9902 u64 quota_us; 9903 9904 if (tg->cfs_bandwidth.quota == RUNTIME_INF) 9905 return RUNTIME_INF; 9906 9907 quota_us = tg->cfs_bandwidth.quota; 9908 do_div(quota_us, NSEC_PER_USEC); 9909 9910 return quota_us; 9911 } 9912 9913 static u64 tg_get_cfs_burst(struct task_group *tg) 9914 { 9915 u64 burst_us; 9916 9917 burst_us = tg->cfs_bandwidth.burst; 9918 do_div(burst_us, NSEC_PER_USEC); 9919 9920 return burst_us; 9921 } 9922 9923 struct cfs_schedulable_data { 9924 struct task_group *tg; 9925 u64 period, quota; 9926 }; 9927 9928 /* 9929 * normalize group quota/period to be quota/max_period 9930 * note: units are usecs 9931 */ 9932 static u64 normalize_cfs_quota(struct task_group *tg, 9933 struct cfs_schedulable_data *d) 9934 { 9935 u64 quota, period; 9936 9937 if (tg == d->tg) { 9938 period = d->period; 9939 quota = d->quota; 9940 } else { 9941 period = tg_get_cfs_period(tg); 9942 quota = tg_get_cfs_quota(tg); 9943 } 9944 9945 /* note: these should typically be equivalent */ 9946 if (quota == RUNTIME_INF || quota == -1) 9947 return RUNTIME_INF; 9948 9949 return to_ratio(period, quota); 9950 } 9951 9952 static int tg_cfs_schedulable_down(struct task_group *tg, void *data) 9953 { 9954 struct cfs_schedulable_data *d = data; 9955 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; 9956 s64 quota = 0, parent_quota = -1; 9957 9958 if (!tg->parent) { 9959 quota = RUNTIME_INF; 9960 } else { 9961 struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth; 9962 9963 quota = normalize_cfs_quota(tg, d); 9964 parent_quota = parent_b->hierarchical_quota; 9965 9966 /* 9967 * Ensure max(child_quota) <= parent_quota. On cgroup2, 9968 * always take the non-RUNTIME_INF min. On cgroup1, only 9969 * inherit when no limit is set. In both cases this is used 9970 * by the scheduler to determine if a given CFS task has a 9971 * bandwidth constraint at some higher level. 9972 */ 9973 if (cgroup_subsys_on_dfl(cpu_cgrp_subsys)) { 9974 if (quota == RUNTIME_INF) 9975 quota = parent_quota; 9976 else if (parent_quota != RUNTIME_INF) 9977 quota = min(quota, parent_quota); 9978 } else { 9979 if (quota == RUNTIME_INF) 9980 quota = parent_quota; 9981 else if (parent_quota != RUNTIME_INF && quota > parent_quota) 9982 return -EINVAL; 9983 } 9984 } 9985 cfs_b->hierarchical_quota = quota; 9986 9987 return 0; 9988 } 9989 9990 static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota) 9991 { 9992 struct cfs_schedulable_data data = { 9993 .tg = tg, 9994 .period = period, 9995 .quota = quota, 9996 }; 9997 9998 if (quota != RUNTIME_INF) { 9999 do_div(data.period, NSEC_PER_USEC); 10000 do_div(data.quota, NSEC_PER_USEC); 10001 } 10002 10003 guard(rcu)(); 10004 return walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data); 10005 } 10006 10007 static int cpu_cfs_stat_show(struct seq_file *sf, void *v) 10008 { 10009 struct task_group *tg = css_tg(seq_css(sf)); 10010 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; 10011 10012 seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods); 10013 seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled); 10014 seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time); 10015 10016 if (schedstat_enabled() && tg != &root_task_group) { 10017 struct sched_statistics *stats; 10018 u64 ws = 0; 10019 int i; 10020 10021 for_each_possible_cpu(i) { 10022 stats = __schedstats_from_se(tg_se(tg, i)); 10023 ws += schedstat_val(stats->wait_sum); 10024 } 10025 10026 seq_printf(sf, "wait_sum %llu\n", ws); 10027 } 10028 10029 seq_printf(sf, "nr_bursts %d\n", cfs_b->nr_burst); 10030 seq_printf(sf, "burst_time %llu\n", cfs_b->burst_time); 10031 10032 return 0; 10033 } 10034 10035 static u64 throttled_time_self(struct task_group *tg) 10036 { 10037 int i; 10038 u64 total = 0; 10039 10040 for_each_possible_cpu(i) { 10041 total += READ_ONCE(tg_cfs_rq(tg, i)->throttled_clock_self_time); 10042 } 10043 10044 return total; 10045 } 10046 10047 static int cpu_cfs_local_stat_show(struct seq_file *sf, void *v) 10048 { 10049 struct task_group *tg = css_tg(seq_css(sf)); 10050 10051 seq_printf(sf, "throttled_time %llu\n", throttled_time_self(tg)); 10052 10053 return 0; 10054 } 10055 #endif /* CONFIG_CFS_BANDWIDTH */ 10056 10057 #ifdef CONFIG_GROUP_SCHED_BANDWIDTH 10058 const u64 max_bw_quota_period_us = 1 * USEC_PER_SEC; /* 1s */ 10059 static const u64 min_bw_quota_period_us = 1 * USEC_PER_MSEC; /* 1ms */ 10060 /* More than 203 days if BW_SHIFT equals 20. */ 10061 static const u64 max_bw_runtime_us = MAX_BW; 10062 10063 static void tg_bandwidth(struct task_group *tg, 10064 u64 *period_us_p, u64 *quota_us_p, u64 *burst_us_p) 10065 { 10066 #ifdef CONFIG_CFS_BANDWIDTH 10067 if (period_us_p) 10068 *period_us_p = tg_get_cfs_period(tg); 10069 if (quota_us_p) 10070 *quota_us_p = tg_get_cfs_quota(tg); 10071 if (burst_us_p) 10072 *burst_us_p = tg_get_cfs_burst(tg); 10073 #else /* !CONFIG_CFS_BANDWIDTH */ 10074 if (period_us_p) 10075 *period_us_p = tg->scx.bw_period_us; 10076 if (quota_us_p) 10077 *quota_us_p = tg->scx.bw_quota_us; 10078 if (burst_us_p) 10079 *burst_us_p = tg->scx.bw_burst_us; 10080 #endif /* CONFIG_CFS_BANDWIDTH */ 10081 } 10082 10083 static u64 cpu_period_read_u64(struct cgroup_subsys_state *css, 10084 struct cftype *cft) 10085 { 10086 u64 period_us; 10087 10088 tg_bandwidth(css_tg(css), &period_us, NULL, NULL); 10089 return period_us; 10090 } 10091 10092 static int tg_set_bandwidth(struct task_group *tg, 10093 u64 period_us, u64 quota_us, u64 burst_us) 10094 { 10095 const u64 max_usec = U64_MAX / NSEC_PER_USEC; 10096 int ret = 0; 10097 10098 if (tg == &root_task_group) 10099 return -EINVAL; 10100 10101 /* Values should survive translation to nsec */ 10102 if (period_us > max_usec || 10103 (quota_us != RUNTIME_INF && quota_us > max_usec) || 10104 burst_us > max_usec) 10105 return -EINVAL; 10106 10107 /* 10108 * Ensure we have some amount of bandwidth every period. This is to 10109 * prevent reaching a state of large arrears when throttled via 10110 * entity_tick() resulting in prolonged exit starvation. 10111 */ 10112 if (quota_us < min_bw_quota_period_us || 10113 period_us < min_bw_quota_period_us) 10114 return -EINVAL; 10115 10116 /* 10117 * Likewise, bound things on the other side by preventing insane quota 10118 * periods. This also allows us to normalize in computing quota 10119 * feasibility. 10120 */ 10121 if (period_us > max_bw_quota_period_us) 10122 return -EINVAL; 10123 10124 /* 10125 * Bound quota to defend quota against overflow during bandwidth shift. 10126 */ 10127 if (quota_us != RUNTIME_INF && quota_us > max_bw_runtime_us) 10128 return -EINVAL; 10129 10130 if (quota_us != RUNTIME_INF && (burst_us > quota_us || 10131 burst_us + quota_us > max_bw_runtime_us)) 10132 return -EINVAL; 10133 10134 #ifdef CONFIG_CFS_BANDWIDTH 10135 ret = tg_set_cfs_bandwidth(tg, period_us, quota_us, burst_us); 10136 #endif /* CONFIG_CFS_BANDWIDTH */ 10137 if (!ret) 10138 scx_group_set_bandwidth(tg, period_us, quota_us, burst_us); 10139 return ret; 10140 } 10141 10142 static s64 cpu_quota_read_s64(struct cgroup_subsys_state *css, 10143 struct cftype *cft) 10144 { 10145 u64 quota_us; 10146 10147 tg_bandwidth(css_tg(css), NULL, "a_us, NULL); 10148 return quota_us; /* (s64)RUNTIME_INF becomes -1 */ 10149 } 10150 10151 static u64 cpu_burst_read_u64(struct cgroup_subsys_state *css, 10152 struct cftype *cft) 10153 { 10154 u64 burst_us; 10155 10156 tg_bandwidth(css_tg(css), NULL, NULL, &burst_us); 10157 return burst_us; 10158 } 10159 10160 static int cpu_period_write_u64(struct cgroup_subsys_state *css, 10161 struct cftype *cftype, u64 period_us) 10162 { 10163 struct task_group *tg = css_tg(css); 10164 u64 quota_us, burst_us; 10165 10166 tg_bandwidth(tg, NULL, "a_us, &burst_us); 10167 return tg_set_bandwidth(tg, period_us, quota_us, burst_us); 10168 } 10169 10170 static int cpu_quota_write_s64(struct cgroup_subsys_state *css, 10171 struct cftype *cftype, s64 quota_us) 10172 { 10173 struct task_group *tg = css_tg(css); 10174 u64 period_us, burst_us; 10175 10176 if (quota_us < 0) 10177 quota_us = RUNTIME_INF; 10178 10179 tg_bandwidth(tg, &period_us, NULL, &burst_us); 10180 return tg_set_bandwidth(tg, period_us, quota_us, burst_us); 10181 } 10182 10183 static int cpu_burst_write_u64(struct cgroup_subsys_state *css, 10184 struct cftype *cftype, u64 burst_us) 10185 { 10186 struct task_group *tg = css_tg(css); 10187 u64 period_us, quota_us; 10188 10189 tg_bandwidth(tg, &period_us, "a_us, NULL); 10190 return tg_set_bandwidth(tg, period_us, quota_us, burst_us); 10191 } 10192 #endif /* CONFIG_GROUP_SCHED_BANDWIDTH */ 10193 10194 #ifdef CONFIG_RT_GROUP_SCHED 10195 static int cpu_rt_runtime_write(struct cgroup_subsys_state *css, 10196 struct cftype *cft, s64 val) 10197 { 10198 return sched_group_set_rt_runtime(css_tg(css), val); 10199 } 10200 10201 static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css, 10202 struct cftype *cft) 10203 { 10204 return sched_group_rt_runtime(css_tg(css)); 10205 } 10206 10207 static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css, 10208 struct cftype *cftype, u64 rt_period_us) 10209 { 10210 return sched_group_set_rt_period(css_tg(css), rt_period_us); 10211 } 10212 10213 static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css, 10214 struct cftype *cft) 10215 { 10216 return sched_group_rt_period(css_tg(css)); 10217 } 10218 #endif /* CONFIG_RT_GROUP_SCHED */ 10219 10220 #ifdef CONFIG_GROUP_SCHED_WEIGHT 10221 static s64 cpu_idle_read_s64(struct cgroup_subsys_state *css, 10222 struct cftype *cft) 10223 { 10224 return css_tg(css)->idle; 10225 } 10226 10227 static int cpu_idle_write_s64(struct cgroup_subsys_state *css, 10228 struct cftype *cft, s64 idle) 10229 { 10230 int ret; 10231 10232 ret = sched_group_set_idle(css_tg(css), idle); 10233 if (!ret) 10234 scx_group_set_idle(css_tg(css), idle); 10235 return ret; 10236 } 10237 #endif /* CONFIG_GROUP_SCHED_WEIGHT */ 10238 10239 static struct cftype cpu_legacy_files[] = { 10240 #ifdef CONFIG_GROUP_SCHED_WEIGHT 10241 { 10242 .name = "shares", 10243 .read_u64 = cpu_shares_read_u64, 10244 .write_u64 = cpu_shares_write_u64, 10245 }, 10246 { 10247 .name = "idle", 10248 .read_s64 = cpu_idle_read_s64, 10249 .write_s64 = cpu_idle_write_s64, 10250 }, 10251 #endif 10252 #ifdef CONFIG_GROUP_SCHED_BANDWIDTH 10253 { 10254 .name = "cfs_period_us", 10255 .read_u64 = cpu_period_read_u64, 10256 .write_u64 = cpu_period_write_u64, 10257 }, 10258 { 10259 .name = "cfs_quota_us", 10260 .read_s64 = cpu_quota_read_s64, 10261 .write_s64 = cpu_quota_write_s64, 10262 }, 10263 { 10264 .name = "cfs_burst_us", 10265 .read_u64 = cpu_burst_read_u64, 10266 .write_u64 = cpu_burst_write_u64, 10267 }, 10268 #endif 10269 #ifdef CONFIG_CFS_BANDWIDTH 10270 { 10271 .name = "stat", 10272 .seq_show = cpu_cfs_stat_show, 10273 }, 10274 { 10275 .name = "stat.local", 10276 .seq_show = cpu_cfs_local_stat_show, 10277 }, 10278 #endif 10279 #ifdef CONFIG_UCLAMP_TASK_GROUP 10280 { 10281 .name = "uclamp.min", 10282 .flags = CFTYPE_NOT_ON_ROOT, 10283 .seq_show = cpu_uclamp_min_show, 10284 .write = cpu_uclamp_min_write, 10285 }, 10286 { 10287 .name = "uclamp.max", 10288 .flags = CFTYPE_NOT_ON_ROOT, 10289 .seq_show = cpu_uclamp_max_show, 10290 .write = cpu_uclamp_max_write, 10291 }, 10292 #endif 10293 { } /* Terminate */ 10294 }; 10295 10296 #ifdef CONFIG_RT_GROUP_SCHED 10297 static struct cftype rt_group_files[] = { 10298 { 10299 .name = "rt_runtime_us", 10300 .read_s64 = cpu_rt_runtime_read, 10301 .write_s64 = cpu_rt_runtime_write, 10302 }, 10303 { 10304 .name = "rt_period_us", 10305 .read_u64 = cpu_rt_period_read_uint, 10306 .write_u64 = cpu_rt_period_write_uint, 10307 }, 10308 { } /* Terminate */ 10309 }; 10310 10311 # ifdef CONFIG_RT_GROUP_SCHED_DEFAULT_DISABLED 10312 DEFINE_STATIC_KEY_FALSE(rt_group_sched); 10313 # else 10314 DEFINE_STATIC_KEY_TRUE(rt_group_sched); 10315 # endif 10316 10317 static int __init setup_rt_group_sched(char *str) 10318 { 10319 long val; 10320 10321 if (kstrtol(str, 0, &val) || val < 0 || val > 1) { 10322 pr_warn("Unable to set rt_group_sched\n"); 10323 return 1; 10324 } 10325 if (val) 10326 static_branch_enable(&rt_group_sched); 10327 else 10328 static_branch_disable(&rt_group_sched); 10329 10330 return 1; 10331 } 10332 __setup("rt_group_sched=", setup_rt_group_sched); 10333 10334 static int __init cpu_rt_group_init(void) 10335 { 10336 if (!rt_group_sched_enabled()) 10337 return 0; 10338 10339 WARN_ON(cgroup_add_legacy_cftypes(&cpu_cgrp_subsys, rt_group_files)); 10340 return 0; 10341 } 10342 subsys_initcall(cpu_rt_group_init); 10343 #endif /* CONFIG_RT_GROUP_SCHED */ 10344 10345 static int cpu_extra_stat_show(struct seq_file *sf, 10346 struct cgroup_subsys_state *css) 10347 { 10348 #ifdef CONFIG_CFS_BANDWIDTH 10349 { 10350 struct task_group *tg = css_tg(css); 10351 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; 10352 u64 throttled_usec, burst_usec; 10353 10354 throttled_usec = cfs_b->throttled_time; 10355 do_div(throttled_usec, NSEC_PER_USEC); 10356 burst_usec = cfs_b->burst_time; 10357 do_div(burst_usec, NSEC_PER_USEC); 10358 10359 seq_printf(sf, "nr_periods %d\n" 10360 "nr_throttled %d\n" 10361 "throttled_usec %llu\n" 10362 "nr_bursts %d\n" 10363 "burst_usec %llu\n", 10364 cfs_b->nr_periods, cfs_b->nr_throttled, 10365 throttled_usec, cfs_b->nr_burst, burst_usec); 10366 } 10367 #endif /* CONFIG_CFS_BANDWIDTH */ 10368 return 0; 10369 } 10370 10371 static int cpu_local_stat_show(struct seq_file *sf, 10372 struct cgroup_subsys_state *css) 10373 { 10374 #ifdef CONFIG_CFS_BANDWIDTH 10375 { 10376 struct task_group *tg = css_tg(css); 10377 u64 throttled_self_usec; 10378 10379 throttled_self_usec = throttled_time_self(tg); 10380 do_div(throttled_self_usec, NSEC_PER_USEC); 10381 10382 seq_printf(sf, "throttled_usec %llu\n", 10383 throttled_self_usec); 10384 } 10385 #endif 10386 return 0; 10387 } 10388 10389 #ifdef CONFIG_GROUP_SCHED_WEIGHT 10390 10391 static u64 cpu_weight_read_u64(struct cgroup_subsys_state *css, 10392 struct cftype *cft) 10393 { 10394 return sched_weight_to_cgroup(tg_weight(css_tg(css))); 10395 } 10396 10397 static int cpu_weight_write_u64(struct cgroup_subsys_state *css, 10398 struct cftype *cft, u64 cgrp_weight) 10399 { 10400 unsigned long weight; 10401 int ret; 10402 10403 if (cgrp_weight < CGROUP_WEIGHT_MIN || cgrp_weight > CGROUP_WEIGHT_MAX) 10404 return -ERANGE; 10405 10406 weight = sched_weight_from_cgroup(cgrp_weight); 10407 10408 ret = sched_group_set_shares(css_tg(css), scale_load(weight)); 10409 if (!ret) 10410 scx_group_set_weight(css_tg(css), cgrp_weight); 10411 return ret; 10412 } 10413 10414 static s64 cpu_weight_nice_read_s64(struct cgroup_subsys_state *css, 10415 struct cftype *cft) 10416 { 10417 unsigned long weight = tg_weight(css_tg(css)); 10418 int last_delta = INT_MAX; 10419 int prio, delta; 10420 10421 /* find the closest nice value to the current weight */ 10422 for (prio = 0; prio < ARRAY_SIZE(sched_prio_to_weight); prio++) { 10423 delta = abs(sched_prio_to_weight[prio] - weight); 10424 if (delta >= last_delta) 10425 break; 10426 last_delta = delta; 10427 } 10428 10429 return PRIO_TO_NICE(prio - 1 + MAX_RT_PRIO); 10430 } 10431 10432 static int cpu_weight_nice_write_s64(struct cgroup_subsys_state *css, 10433 struct cftype *cft, s64 nice) 10434 { 10435 unsigned long weight; 10436 int idx, ret; 10437 10438 if (nice < MIN_NICE || nice > MAX_NICE) 10439 return -ERANGE; 10440 10441 idx = NICE_TO_PRIO(nice) - MAX_RT_PRIO; 10442 idx = array_index_nospec(idx, 40); 10443 weight = sched_prio_to_weight[idx]; 10444 10445 ret = sched_group_set_shares(css_tg(css), scale_load(weight)); 10446 if (!ret) 10447 scx_group_set_weight(css_tg(css), 10448 sched_weight_to_cgroup(weight)); 10449 return ret; 10450 } 10451 #endif /* CONFIG_GROUP_SCHED_WEIGHT */ 10452 10453 static void __maybe_unused cpu_period_quota_print(struct seq_file *sf, 10454 long period, long quota) 10455 { 10456 if (quota < 0) 10457 seq_puts(sf, "max"); 10458 else 10459 seq_printf(sf, "%ld", quota); 10460 10461 seq_printf(sf, " %ld\n", period); 10462 } 10463 10464 /* caller should put the current value in *@periodp before calling */ 10465 static int __maybe_unused cpu_period_quota_parse(char *buf, u64 *period_us_p, 10466 u64 *quota_us_p) 10467 { 10468 char tok[21]; /* U64_MAX */ 10469 10470 if (sscanf(buf, "%20s %llu", tok, period_us_p) < 1) 10471 return -EINVAL; 10472 10473 if (sscanf(tok, "%llu", quota_us_p) < 1) { 10474 if (!strcmp(tok, "max")) 10475 *quota_us_p = RUNTIME_INF; 10476 else 10477 return -EINVAL; 10478 } 10479 10480 return 0; 10481 } 10482 10483 #ifdef CONFIG_GROUP_SCHED_BANDWIDTH 10484 static int cpu_max_show(struct seq_file *sf, void *v) 10485 { 10486 struct task_group *tg = css_tg(seq_css(sf)); 10487 u64 period_us, quota_us; 10488 10489 tg_bandwidth(tg, &period_us, "a_us, NULL); 10490 cpu_period_quota_print(sf, period_us, quota_us); 10491 return 0; 10492 } 10493 10494 static ssize_t cpu_max_write(struct kernfs_open_file *of, 10495 char *buf, size_t nbytes, loff_t off) 10496 { 10497 struct task_group *tg = css_tg(of_css(of)); 10498 u64 period_us, quota_us, burst_us; 10499 int ret; 10500 10501 tg_bandwidth(tg, &period_us, NULL, &burst_us); 10502 ret = cpu_period_quota_parse(buf, &period_us, "a_us); 10503 if (!ret) 10504 ret = tg_set_bandwidth(tg, period_us, quota_us, burst_us); 10505 return ret ?: nbytes; 10506 } 10507 #endif /* CONFIG_CFS_BANDWIDTH */ 10508 10509 static struct cftype cpu_files[] = { 10510 #ifdef CONFIG_GROUP_SCHED_WEIGHT 10511 { 10512 .name = "weight", 10513 .flags = CFTYPE_NOT_ON_ROOT, 10514 .read_u64 = cpu_weight_read_u64, 10515 .write_u64 = cpu_weight_write_u64, 10516 }, 10517 { 10518 .name = "weight.nice", 10519 .flags = CFTYPE_NOT_ON_ROOT, 10520 .read_s64 = cpu_weight_nice_read_s64, 10521 .write_s64 = cpu_weight_nice_write_s64, 10522 }, 10523 { 10524 .name = "idle", 10525 .flags = CFTYPE_NOT_ON_ROOT, 10526 .read_s64 = cpu_idle_read_s64, 10527 .write_s64 = cpu_idle_write_s64, 10528 }, 10529 #endif 10530 #ifdef CONFIG_GROUP_SCHED_BANDWIDTH 10531 { 10532 .name = "max", 10533 .flags = CFTYPE_NOT_ON_ROOT, 10534 .seq_show = cpu_max_show, 10535 .write = cpu_max_write, 10536 }, 10537 { 10538 .name = "max.burst", 10539 .flags = CFTYPE_NOT_ON_ROOT, 10540 .read_u64 = cpu_burst_read_u64, 10541 .write_u64 = cpu_burst_write_u64, 10542 }, 10543 #endif /* CONFIG_CFS_BANDWIDTH */ 10544 #ifdef CONFIG_UCLAMP_TASK_GROUP 10545 { 10546 .name = "uclamp.min", 10547 .flags = CFTYPE_NOT_ON_ROOT, 10548 .seq_show = cpu_uclamp_min_show, 10549 .write = cpu_uclamp_min_write, 10550 }, 10551 { 10552 .name = "uclamp.max", 10553 .flags = CFTYPE_NOT_ON_ROOT, 10554 .seq_show = cpu_uclamp_max_show, 10555 .write = cpu_uclamp_max_write, 10556 }, 10557 #endif /* CONFIG_UCLAMP_TASK_GROUP */ 10558 { } /* terminate */ 10559 }; 10560 10561 struct cgroup_subsys cpu_cgrp_subsys = { 10562 .css_alloc = cpu_cgroup_css_alloc, 10563 .css_online = cpu_cgroup_css_online, 10564 .css_offline = cpu_cgroup_css_offline, 10565 .css_released = cpu_cgroup_css_released, 10566 .css_free = cpu_cgroup_css_free, 10567 .css_extra_stat_show = cpu_extra_stat_show, 10568 .css_local_stat_show = cpu_local_stat_show, 10569 .can_attach = cpu_cgroup_can_attach, 10570 .attach = cpu_cgroup_attach, 10571 .cancel_attach = cpu_cgroup_cancel_attach, 10572 .legacy_cftypes = cpu_legacy_files, 10573 .dfl_cftypes = cpu_files, 10574 .early_init = true, 10575 .threaded = true, 10576 }; 10577 10578 #endif /* CONFIG_CGROUP_SCHED */ 10579 10580 void dump_cpu_task(int cpu) 10581 { 10582 if (in_hardirq() && cpu == smp_processor_id()) { 10583 struct pt_regs *regs; 10584 10585 regs = get_irq_regs(); 10586 if (regs) { 10587 show_regs(regs); 10588 return; 10589 } 10590 } 10591 10592 if (trigger_single_cpu_backtrace(cpu)) 10593 return; 10594 10595 pr_info("Task dump for CPU %d:\n", cpu); 10596 sched_show_task(cpu_curr(cpu)); 10597 } 10598 10599 /* 10600 * Nice levels are multiplicative, with a gentle 10% change for every 10601 * nice level changed. I.e. when a CPU-bound task goes from nice 0 to 10602 * nice 1, it will get ~10% less CPU time than another CPU-bound task 10603 * that remained on nice 0. 10604 * 10605 * The "10% effect" is relative and cumulative: from _any_ nice level, 10606 * if you go up 1 level, it's -10% CPU usage, if you go down 1 level 10607 * it's +10% CPU usage. (to achieve that we use a multiplier of 1.25. 10608 * If a task goes up by ~10% and another task goes down by ~10% then 10609 * the relative distance between them is ~25%.) 10610 */ 10611 const int sched_prio_to_weight[40] = { 10612 /* -20 */ 88761, 71755, 56483, 46273, 36291, 10613 /* -15 */ 29154, 23254, 18705, 14949, 11916, 10614 /* -10 */ 9548, 7620, 6100, 4904, 3906, 10615 /* -5 */ 3121, 2501, 1991, 1586, 1277, 10616 /* 0 */ 1024, 820, 655, 526, 423, 10617 /* 5 */ 335, 272, 215, 172, 137, 10618 /* 10 */ 110, 87, 70, 56, 45, 10619 /* 15 */ 36, 29, 23, 18, 15, 10620 }; 10621 10622 /* 10623 * Inverse (2^32/x) values of the sched_prio_to_weight[] array, pre-calculated. 10624 * 10625 * In cases where the weight does not change often, we can use the 10626 * pre-calculated inverse to speed up arithmetics by turning divisions 10627 * into multiplications: 10628 */ 10629 const u32 sched_prio_to_wmult[40] = { 10630 /* -20 */ 48388, 59856, 76040, 92818, 118348, 10631 /* -15 */ 147320, 184698, 229616, 287308, 360437, 10632 /* -10 */ 449829, 563644, 704093, 875809, 1099582, 10633 /* -5 */ 1376151, 1717300, 2157191, 2708050, 3363326, 10634 /* 0 */ 4194304, 5237765, 6557202, 8165337, 10153587, 10635 /* 5 */ 12820798, 15790321, 19976592, 24970740, 31350126, 10636 /* 10 */ 39045157, 49367440, 61356676, 76695844, 95443717, 10637 /* 15 */ 119304647, 148102320, 186737708, 238609294, 286331153, 10638 }; 10639 10640 void call_trace_sched_update_nr_running(struct rq *rq, int count) 10641 { 10642 trace_sched_update_nr_running_tp(rq, count); 10643 } 10644 10645 #ifdef CONFIG_SCHED_MM_CID 10646 /* 10647 * Concurrency IDentifier management 10648 * 10649 * Serialization rules: 10650 * 10651 * mm::mm_cid::mutex: Serializes fork() and exit() and therefore 10652 * protects mm::mm_cid::users and mode switch 10653 * transitions 10654 * 10655 * mm::mm_cid::lock: Serializes mm_update_max_cids() and 10656 * mm_update_cpus_allowed(). Nests in mm_cid::mutex 10657 * and runqueue lock. 10658 * 10659 * The mm_cidmask bitmap is not protected by any of the mm::mm_cid locks 10660 * and can only be modified with atomic operations. 10661 * 10662 * The mm::mm_cid:pcpu per CPU storage is protected by the CPUs runqueue 10663 * lock. 10664 * 10665 * CID ownership: 10666 * 10667 * A CID is either owned by a task (stored in task_struct::mm_cid.cid) or 10668 * by a CPU (stored in mm::mm_cid.pcpu::cid). CIDs owned by CPUs have the 10669 * MM_CID_ONCPU bit set. 10670 * 10671 * During the transition of ownership mode, the MM_CID_TRANSIT bit is set 10672 * on the CIDs. When this bit is set the tasks drop the CID back into the 10673 * pool when scheduling out. 10674 * 10675 * Both bits (ONCPU and TRANSIT) are filtered out by task_cid() when the 10676 * CID is actually handed over to user space in the RSEQ memory. 10677 * 10678 * Mode switching: 10679 * 10680 * The ownership mode is per process and stored in mm:mm_cid::mode with the 10681 * following possible states: 10682 * 10683 * 0: Per task ownership 10684 * 0 | MM_CID_TRANSIT: Transition from per CPU to per task 10685 * MM_CID_ONCPU: Per CPU ownership 10686 * MM_CID_ONCPU | MM_CID_TRANSIT: Transition from per task to per CPU 10687 * 10688 * All transitions of ownership mode happen in two phases: 10689 * 10690 * 1) mm:mm_cid::mode has the MM_CID_TRANSIT bit set. This is OR'ed on the 10691 * CIDs and denotes that the CID is only temporarily owned by a 10692 * task. When the task schedules out it drops the CID back into the 10693 * pool if this bit is set. 10694 * 10695 * 2) The initiating context walks the per CPU space or the tasks to fixup 10696 * or drop the CIDs and after completion it clears MM_CID_TRANSIT in 10697 * mm:mm_cid::mode. After that point the CIDs are strictly task or CPU 10698 * owned again. 10699 * 10700 * This two phase transition is required to prevent CID space exhaustion 10701 * during the transition as a direct transfer of ownership would fail: 10702 * 10703 * - On task to CPU mode switch if a task is scheduled in on one CPU and 10704 * then migrated to another CPU before the fixup freed enough per task 10705 * CIDs. 10706 * 10707 * - On CPU to task mode switch if two tasks are scheduled in on the same 10708 * CPU before the fixup freed per CPU CIDs. 10709 * 10710 * Both scenarios can result in a live lock because sched_in() is invoked 10711 * with runqueue lock held and loops in search of a CID and the fixup 10712 * thread can't make progress freeing them up because it is stuck on the 10713 * same runqueue lock. 10714 * 10715 * While MM_CID_TRANSIT is active during the transition phase the MM_CID 10716 * bitmap can be contended, but that's a temporary contention bound to the 10717 * transition period. After that everything goes back into steady state and 10718 * nothing except fork() and exit() will touch the bitmap. This is an 10719 * acceptable tradeoff as it completely avoids complex serialization, 10720 * memory barriers and atomic operations for the common case. 10721 * 10722 * Aside of that this mechanism also ensures RT compability: 10723 * 10724 * - The task which runs the fixup is fully preemptible except for the 10725 * short runqueue lock held sections. 10726 * 10727 * - The transient impact of the bitmap contention is only problematic 10728 * when there is a thundering herd scenario of tasks scheduling in and 10729 * out concurrently. There is not much which can be done about that 10730 * except for avoiding mode switching by a proper overall system 10731 * configuration. 10732 * 10733 * Switching to per CPU mode happens when the user count becomes greater 10734 * than the maximum number of CIDs, which is calculated by: 10735 * 10736 * opt_cids = min(mm_cid::nr_cpus_allowed, mm_cid::users); 10737 * max_cids = min(1.25 * opt_cids, num_possible_cpus()); 10738 * 10739 * The +25% allowance is useful for tight CPU masks in scenarios where only 10740 * a few threads are created and destroyed to avoid frequent mode 10741 * switches. Though this allowance shrinks, the closer opt_cids becomes to 10742 * num_possible_cpus(), which is the (unfortunate) hard ABI limit. 10743 * 10744 * At the point of switching to per CPU mode the new user is not yet 10745 * visible in the system, so the task which initiated the fork() runs the 10746 * fixup function. mm_cid_fixup_tasks_to_cpu() walks the thread list and 10747 * either marks each task owned CID with MM_CID_TRANSIT if the task is 10748 * running on a CPU or drops it into the CID pool if a task is not on a 10749 * CPU. Tasks which schedule in before the task walk reaches them do the 10750 * handover in mm_cid_schedin(). When mm_cid_fixup_tasks_to_cpus() 10751 * completes it is guaranteed that no task related to that MM owns a CID 10752 * anymore. 10753 * 10754 * Switching back to task mode happens when the user count goes below the 10755 * threshold which was recorded on the per CPU mode switch: 10756 * 10757 * pcpu_thrs = min(opt_cids - (opt_cids / 4), num_possible_cpus() / 2); 10758 * 10759 * This threshold is updated when a affinity change increases the number of 10760 * allowed CPUs for the MM, which might cause a switch back to per task 10761 * mode. 10762 * 10763 * If the switch back was initiated by a exiting task, then that task runs 10764 * the fixup function. If it was initiated by a affinity change, then it's 10765 * run either in the deferred update function in context of a workqueue or 10766 * by a task which forks a new one or by a task which exits. Whatever 10767 * happens first. mm_cid_fixup_cpus_to_task() walks through the possible 10768 * CPUs and either marks the CPU owned CIDs with MM_CID_TRANSIT if a 10769 * related task is running on the CPU or drops it into the pool. Tasks 10770 * which are scheduled in before the fixup covered them do the handover 10771 * themself. When mm_cid_fixup_cpus_to_tasks() completes it is guaranteed 10772 * that no CID related to that MM is owned by a CPU anymore. 10773 */ 10774 10775 /* 10776 * Update the CID range properties when the constraints change. Invoked via 10777 * fork(), exit() and affinity changes 10778 */ 10779 static void __mm_update_max_cids(struct mm_mm_cid *mc) 10780 { 10781 unsigned int opt_cids, max_cids; 10782 10783 /* Calculate the new optimal constraint */ 10784 opt_cids = min(mc->nr_cpus_allowed, mc->users); 10785 10786 /* Adjust the maximum CIDs to +25% limited by the number of possible CPUs */ 10787 max_cids = min(opt_cids + (opt_cids / 4), num_possible_cpus()); 10788 WRITE_ONCE(mc->max_cids, max_cids); 10789 } 10790 10791 static inline unsigned int mm_cid_calc_pcpu_thrs(struct mm_mm_cid *mc) 10792 { 10793 unsigned int opt_cids; 10794 10795 opt_cids = min(mc->nr_cpus_allowed, mc->users); 10796 /* Has to be at least 1 because 0 indicates PCPU mode off */ 10797 return max(min(opt_cids - opt_cids / 4, num_possible_cpus() / 2), 1); 10798 } 10799 10800 static bool mm_update_max_cids(struct mm_struct *mm) 10801 { 10802 struct mm_mm_cid *mc = &mm->mm_cid; 10803 bool percpu = cid_on_cpu(mc->mode); 10804 10805 lockdep_assert_held(&mm->mm_cid.lock); 10806 10807 /* Clear deferred mode switch flag. A change is handled by the caller */ 10808 mc->update_deferred = false; 10809 __mm_update_max_cids(mc); 10810 10811 /* Check whether owner mode must be changed */ 10812 if (!percpu) { 10813 /* Enable per CPU mode when the number of users is above max_cids */ 10814 if (mc->users > mc->max_cids) 10815 mc->pcpu_thrs = mm_cid_calc_pcpu_thrs(mc); 10816 } else { 10817 /* Switch back to per task if user count under threshold */ 10818 if (mc->users < mc->pcpu_thrs) 10819 mc->pcpu_thrs = 0; 10820 } 10821 10822 /* Mode change required? */ 10823 if (percpu == !!mc->pcpu_thrs) 10824 return false; 10825 10826 /* Flip the mode and set the transition flag to bridge the transfer */ 10827 WRITE_ONCE(mc->mode, mc->mode ^ (MM_CID_TRANSIT | MM_CID_ONCPU)); 10828 /* 10829 * Order the store against the subsequent fixups so that 10830 * acquire(rq::lock) cannot be reordered by the CPU before the 10831 * store. 10832 */ 10833 smp_mb(); 10834 return true; 10835 } 10836 10837 static inline void mm_update_cpus_allowed(struct mm_struct *mm, const struct cpumask *affmsk) 10838 { 10839 struct cpumask *mm_allowed; 10840 struct mm_mm_cid *mc; 10841 unsigned int weight; 10842 10843 if (!mm || !READ_ONCE(mm->mm_cid.users)) 10844 return; 10845 /* 10846 * mm::mm_cid::mm_cpus_allowed is the superset of each threads 10847 * allowed CPUs mask which means it can only grow. 10848 */ 10849 mc = &mm->mm_cid; 10850 guard(raw_spinlock)(&mc->lock); 10851 mm_allowed = mm_cpus_allowed(mm); 10852 weight = cpumask_weighted_or(mm_allowed, mm_allowed, affmsk); 10853 if (weight == mc->nr_cpus_allowed) 10854 return; 10855 10856 WRITE_ONCE(mc->nr_cpus_allowed, weight); 10857 __mm_update_max_cids(mc); 10858 if (!cid_on_cpu(mc->mode)) 10859 return; 10860 10861 /* Adjust the threshold to the wider set */ 10862 mc->pcpu_thrs = mm_cid_calc_pcpu_thrs(mc); 10863 /* Switch back to per task mode? */ 10864 if (mc->users >= mc->pcpu_thrs) 10865 return; 10866 10867 /* Don't queue twice */ 10868 if (mc->update_deferred) 10869 return; 10870 10871 /* Queue the irq work, which schedules the real work */ 10872 mc->update_deferred = true; 10873 irq_work_queue(&mc->irq_work); 10874 } 10875 10876 static inline void mm_cid_complete_transit(struct mm_struct *mm, unsigned int mode) 10877 { 10878 /* 10879 * Ensure that the store removing the TRANSIT bit cannot be 10880 * reordered by the CPU before the fixups have been completed. 10881 */ 10882 smp_mb(); 10883 WRITE_ONCE(mm->mm_cid.mode, mode); 10884 } 10885 10886 static inline void mm_cid_transit_to_task(struct task_struct *t, struct mm_cid_pcpu *pcp) 10887 { 10888 if (cid_on_cpu(t->mm_cid.cid)) { 10889 unsigned int cid = cpu_cid_to_cid(t->mm_cid.cid); 10890 10891 t->mm_cid.cid = cid_to_transit_cid(cid); 10892 pcp->cid = t->mm_cid.cid; 10893 } 10894 } 10895 10896 static void mm_cid_fixup_cpus_to_tasks(struct mm_struct *mm) 10897 { 10898 unsigned int cpu; 10899 10900 /* Walk the CPUs and fixup all stale CIDs */ 10901 for_each_possible_cpu(cpu) { 10902 struct mm_cid_pcpu *pcp = per_cpu_ptr(mm->mm_cid.pcpu, cpu); 10903 struct rq *rq = cpu_rq(cpu); 10904 10905 /* Remote access to mm::mm_cid::pcpu requires rq_lock */ 10906 guard(rq_lock_irq)(rq); 10907 /* Is the CID still owned by the CPU? */ 10908 if (cid_on_cpu(pcp->cid)) { 10909 /* 10910 * If rq->curr has @mm, transfer it with the 10911 * transition bit set. Otherwise drop it. 10912 */ 10913 if (rq->curr->mm == mm && rq->curr->mm_cid.active) 10914 mm_cid_transit_to_task(rq->curr, pcp); 10915 else 10916 mm_drop_cid_on_cpu(mm, pcp); 10917 10918 } else if (rq->curr->mm == mm && rq->curr->mm_cid.active) { 10919 unsigned int cid = rq->curr->mm_cid.cid; 10920 10921 /* 10922 * Set the transition bit only on a genuine task-owned 10923 * CID. A running active task can legitimately have 10924 * MM_CID_UNSET here: in per-CPU mode CIDs are assigned 10925 * lazily on schedule-in, so the fork()/execve() window 10926 * leaves the task active with no owned CID. Setting the 10927 * transition bit on MM_CID_UNSET would later feed 10928 * clear_bit() an out-of-bounds bit number via 10929 * mm_cid_schedout(), so exclude it. A CPU-owned 10930 * (MM_CID_ONCPU) CID is handled by the cid_on_cpu() 10931 * branch above and never reaches here. 10932 */ 10933 if (cid != MM_CID_UNSET && !cid_in_transit(cid)) { 10934 cid = cid_to_transit_cid(cid); 10935 rq->curr->mm_cid.cid = cid; 10936 pcp->cid = cid; 10937 } 10938 } 10939 } 10940 mm_cid_complete_transit(mm, 0); 10941 } 10942 10943 static inline void mm_cid_transit_to_cpu(struct task_struct *t, struct mm_cid_pcpu *pcp) 10944 { 10945 if (cid_on_task(t->mm_cid.cid)) { 10946 t->mm_cid.cid = cid_to_transit_cid(t->mm_cid.cid); 10947 pcp->cid = t->mm_cid.cid; 10948 } 10949 } 10950 10951 static void mm_cid_fixup_task_to_cpu(struct task_struct *t, struct mm_struct *mm) 10952 { 10953 /* Remote access to mm::mm_cid::pcpu requires rq_lock */ 10954 guard(task_rq_lock)(t); 10955 if (cid_on_task(t->mm_cid.cid)) { 10956 /* If running on the CPU, put the CID in transit mode, otherwise drop it */ 10957 if (task_rq(t)->curr == t) 10958 mm_cid_transit_to_cpu(t, per_cpu_ptr(mm->mm_cid.pcpu, task_cpu(t))); 10959 else 10960 mm_unset_cid_on_task(t); 10961 } 10962 } 10963 10964 static void mm_cid_fixup_tasks_to_cpus(void) 10965 { 10966 struct mm_struct *mm = current->mm; 10967 struct task_struct *t; 10968 10969 lockdep_assert_held(&mm->mm_cid.mutex); 10970 10971 hlist_for_each_entry(t, &mm->mm_cid.user_list, mm_cid.node) { 10972 /* Current has already transferred before invoking the fixup. */ 10973 if (t != current) 10974 mm_cid_fixup_task_to_cpu(t, mm); 10975 } 10976 10977 mm_cid_complete_transit(mm, MM_CID_ONCPU); 10978 } 10979 10980 static bool sched_mm_cid_add_user(struct task_struct *t, struct mm_struct *mm) 10981 { 10982 lockdep_assert_held(&mm->mm_cid.lock); 10983 10984 t->mm_cid.active = 1; 10985 hlist_add_head(&t->mm_cid.node, &mm->mm_cid.user_list); 10986 mm->mm_cid.users++; 10987 return mm_update_max_cids(mm); 10988 } 10989 10990 static void sched_mm_cid_fork(struct task_struct *t) 10991 { 10992 struct mm_struct *mm = t->mm; 10993 bool percpu; 10994 10995 if (!mm) 10996 return; 10997 10998 WARN_ON_ONCE(t->mm_cid.cid != MM_CID_UNSET); 10999 11000 guard(mutex)(&mm->mm_cid.mutex); 11001 scoped_guard(raw_spinlock_irq, &mm->mm_cid.lock) { 11002 struct mm_cid_pcpu *pcp = this_cpu_ptr(mm->mm_cid.pcpu); 11003 11004 /* First user ? */ 11005 if (!mm->mm_cid.users) { 11006 sched_mm_cid_add_user(t, mm); 11007 t->mm_cid.cid = mm_get_cid(mm); 11008 /* Required for execve() */ 11009 pcp->cid = t->mm_cid.cid; 11010 return; 11011 } 11012 11013 if (!sched_mm_cid_add_user(t, mm)) { 11014 if (!cid_on_cpu(mm->mm_cid.mode)) 11015 t->mm_cid.cid = mm_get_cid(mm); 11016 return; 11017 } 11018 11019 /* Handle the mode change and transfer current's CID */ 11020 percpu = cid_on_cpu(mm->mm_cid.mode); 11021 if (!percpu) 11022 mm_cid_transit_to_task(current, pcp); 11023 else 11024 mm_cid_transit_to_cpu(current, pcp); 11025 } 11026 11027 if (percpu) { 11028 mm_cid_fixup_tasks_to_cpus(); 11029 } else { 11030 mm_cid_fixup_cpus_to_tasks(mm); 11031 t->mm_cid.cid = mm_get_cid(mm); 11032 } 11033 } 11034 11035 static bool sched_mm_cid_remove_user(struct task_struct *t) 11036 { 11037 lockdep_assert_held(&t->mm->mm_cid.lock); 11038 11039 t->mm_cid.active = 0; 11040 /* Clear the transition bit */ 11041 t->mm_cid.cid = cid_from_transit_cid(t->mm_cid.cid); 11042 mm_unset_cid_on_task(t); 11043 hlist_del_init(&t->mm_cid.node); 11044 t->mm->mm_cid.users--; 11045 return mm_update_max_cids(t->mm); 11046 } 11047 11048 static bool __sched_mm_cid_exit(struct task_struct *t) 11049 { 11050 struct mm_struct *mm = t->mm; 11051 11052 if (!sched_mm_cid_remove_user(t)) 11053 return false; 11054 /* 11055 * Contrary to fork() this only deals with a switch back to per 11056 * task mode either because the above decreased users or an 11057 * affinity change increased the number of allowed CPUs and the 11058 * deferred fixup did not run yet. 11059 */ 11060 if (WARN_ON_ONCE(cid_on_cpu(mm->mm_cid.mode))) 11061 return false; 11062 /* 11063 * A failed fork(2) cleanup never gets here, so @current must have 11064 * the same MM as @t. That's true for exit() and the failed 11065 * pthread_create() cleanup case. 11066 */ 11067 if (WARN_ON_ONCE(current->mm != mm)) 11068 return false; 11069 return true; 11070 } 11071 11072 /* 11073 * When a task exits, the MM CID held by the task is not longer required as 11074 * the task cannot return to user space. 11075 */ 11076 void sched_mm_cid_exit(struct task_struct *t) 11077 { 11078 struct mm_struct *mm = t->mm; 11079 11080 if (!mm || !t->mm_cid.active) 11081 return; 11082 /* 11083 * Ensure that only one instance is doing MM CID operations within 11084 * a MM. The common case is uncontended. The rare fixup case adds 11085 * some overhead. 11086 */ 11087 scoped_guard(mutex, &mm->mm_cid.mutex) { 11088 /* mm_cid::mutex is sufficient to protect mm_cid::users */ 11089 if (likely(mm->mm_cid.users > 1)) { 11090 scoped_guard(raw_spinlock_irq, &mm->mm_cid.lock) { 11091 if (!__sched_mm_cid_exit(t)) 11092 return; 11093 /* 11094 * Mode change. The task has the CID unset 11095 * already and dealt with an eventually set 11096 * TRANSIT bit. If the CID is owned by the CPU 11097 * then drop it. 11098 */ 11099 mm_drop_cid_on_cpu(mm, this_cpu_ptr(mm->mm_cid.pcpu)); 11100 } 11101 mm_cid_fixup_cpus_to_tasks(mm); 11102 return; 11103 } 11104 /* Last user */ 11105 scoped_guard(raw_spinlock_irq, &mm->mm_cid.lock) { 11106 /* Required across execve() */ 11107 if (t == current) 11108 mm_cid_transit_to_task(t, this_cpu_ptr(mm->mm_cid.pcpu)); 11109 /* Ignore mode change. There is nothing to do. */ 11110 sched_mm_cid_remove_user(t); 11111 } 11112 } 11113 11114 /* 11115 * As this is the last user (execve(), process exit or failed 11116 * fork(2)) there is no concurrency anymore. 11117 * 11118 * Synchronize eventually pending work to ensure that there are no 11119 * dangling references left. @t->mm_cid.users is zero so nothing 11120 * can queue this work anymore. 11121 */ 11122 irq_work_sync(&mm->mm_cid.irq_work); 11123 cancel_work_sync(&mm->mm_cid.work); 11124 } 11125 11126 /* Deactivate MM CID allocation across execve() */ 11127 void sched_mm_cid_before_execve(struct task_struct *t) 11128 { 11129 sched_mm_cid_exit(t); 11130 } 11131 11132 /* Reactivate MM CID after execve() */ 11133 void sched_mm_cid_after_execve(struct task_struct *t) 11134 { 11135 if (t->mm) 11136 sched_mm_cid_fork(t); 11137 } 11138 11139 static void mm_cid_work_fn(struct work_struct *work) 11140 { 11141 struct mm_struct *mm = container_of(work, struct mm_struct, mm_cid.work); 11142 11143 guard(mutex)(&mm->mm_cid.mutex); 11144 /* Did the last user task exit already? */ 11145 if (!mm->mm_cid.users) 11146 return; 11147 11148 scoped_guard(raw_spinlock_irq, &mm->mm_cid.lock) { 11149 /* Have fork() or exit() handled it already? */ 11150 if (!mm->mm_cid.update_deferred) 11151 return; 11152 /* This clears mm_cid::update_deferred */ 11153 if (!mm_update_max_cids(mm)) 11154 return; 11155 /* Affinity changes can only switch back to task mode */ 11156 if (WARN_ON_ONCE(cid_on_cpu(mm->mm_cid.mode))) 11157 return; 11158 } 11159 mm_cid_fixup_cpus_to_tasks(mm); 11160 } 11161 11162 static void mm_cid_irq_work(struct irq_work *work) 11163 { 11164 struct mm_struct *mm = container_of(work, struct mm_struct, mm_cid.irq_work); 11165 11166 /* 11167 * Needs to be unconditional because mm_cid::lock cannot be held 11168 * when scheduling work as mm_update_cpus_allowed() nests inside 11169 * rq::lock and schedule_work() might end up in wakeup... 11170 */ 11171 schedule_work(&mm->mm_cid.work); 11172 } 11173 11174 void mm_init_cid(struct mm_struct *mm, struct task_struct *p) 11175 { 11176 mm->mm_cid.max_cids = 0; 11177 mm->mm_cid.mode = 0; 11178 mm->mm_cid.nr_cpus_allowed = p->nr_cpus_allowed; 11179 mm->mm_cid.users = 0; 11180 mm->mm_cid.pcpu_thrs = 0; 11181 mm->mm_cid.update_deferred = 0; 11182 raw_spin_lock_init(&mm->mm_cid.lock); 11183 mutex_init(&mm->mm_cid.mutex); 11184 mm->mm_cid.irq_work = IRQ_WORK_INIT_HARD(mm_cid_irq_work); 11185 INIT_WORK(&mm->mm_cid.work, mm_cid_work_fn); 11186 INIT_HLIST_HEAD(&mm->mm_cid.user_list); 11187 cpumask_copy(mm_cpus_allowed(mm), &p->cpus_mask); 11188 bitmap_zero(mm_cidmask(mm), num_possible_cpus()); 11189 } 11190 #else /* CONFIG_SCHED_MM_CID */ 11191 static inline void mm_update_cpus_allowed(struct mm_struct *mm, const struct cpumask *affmsk) { } 11192 static inline void sched_mm_cid_fork(struct task_struct *t) { } 11193 #endif /* !CONFIG_SCHED_MM_CID */ 11194 11195 static DEFINE_PER_CPU(struct sched_change_ctx, sched_change_ctx); 11196 11197 struct sched_change_ctx *sched_change_begin(struct task_struct *p, unsigned int flags) 11198 { 11199 struct sched_change_ctx *ctx = this_cpu_ptr(&sched_change_ctx); 11200 struct rq *rq = task_rq(p); 11201 11202 /* 11203 * Must exclusively use matched flags since this is both dequeue and 11204 * enqueue. 11205 */ 11206 WARN_ON_ONCE(flags & 0xFFFF0000); 11207 11208 lockdep_assert_rq_held(rq); 11209 11210 if (!(flags & DEQUEUE_NOCLOCK)) { 11211 update_rq_clock(rq); 11212 flags |= DEQUEUE_NOCLOCK; 11213 } 11214 11215 if ((flags & DEQUEUE_CLASS) && p->sched_class->switching_from) 11216 p->sched_class->switching_from(rq, p); 11217 11218 *ctx = (struct sched_change_ctx){ 11219 .p = p, 11220 .class = p->sched_class, 11221 .flags = flags, 11222 .queued = task_on_rq_queued(p), 11223 .running = task_current_donor(rq, p), 11224 }; 11225 11226 if (!(flags & DEQUEUE_CLASS)) { 11227 if (p->sched_class->get_prio) 11228 ctx->prio = p->sched_class->get_prio(rq, p); 11229 else 11230 ctx->prio = p->prio; 11231 } 11232 11233 if (ctx->queued) 11234 dequeue_task(rq, p, flags); 11235 if (ctx->running) 11236 put_prev_task(rq, p); 11237 11238 if ((flags & DEQUEUE_CLASS) && p->sched_class->switched_from) 11239 p->sched_class->switched_from(rq, p); 11240 11241 return ctx; 11242 } 11243 11244 void sched_change_end(struct sched_change_ctx *ctx) 11245 { 11246 struct task_struct *p = ctx->p; 11247 struct rq *rq = task_rq(p); 11248 11249 lockdep_assert_rq_held(rq); 11250 11251 /* 11252 * Changing class without *QUEUE_CLASS is bad. 11253 */ 11254 WARN_ON_ONCE(p->sched_class != ctx->class && !(ctx->flags & ENQUEUE_CLASS)); 11255 11256 if ((ctx->flags & ENQUEUE_CLASS) && p->sched_class->switching_to) 11257 p->sched_class->switching_to(rq, p); 11258 11259 if (ctx->queued) 11260 enqueue_task(rq, p, ctx->flags); 11261 if (ctx->running) 11262 set_next_task(rq, p); 11263 11264 if (ctx->flags & ENQUEUE_CLASS) { 11265 if (p->sched_class->switched_to) 11266 p->sched_class->switched_to(rq, p); 11267 11268 if (ctx->running) { 11269 /* 11270 * If this was a class promotion; let the old class 11271 * know it got preempted. Note that none of the 11272 * switch*_from() methods know the new class and none 11273 * of the switch*_to() methods know the old class. 11274 */ 11275 if (sched_class_above(p->sched_class, ctx->class)) { 11276 rq->next_class->wakeup_preempt(rq, p, 0); 11277 rq->next_class = p->sched_class; 11278 } 11279 /* 11280 * If this was a degradation in class; make sure to 11281 * reschedule. 11282 */ 11283 if (sched_class_above(ctx->class, p->sched_class)) 11284 resched_curr(rq); 11285 } 11286 } else { 11287 p->sched_class->prio_changed(rq, p, ctx->prio); 11288 } 11289 } 11290