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