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