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