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