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