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