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