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