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