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