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