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