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