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