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