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