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