1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * Completely Fair Scheduling (CFS) Class (SCHED_NORMAL/SCHED_BATCH) 4 * 5 * Copyright (C) 2007 Red Hat, Inc., Ingo Molnar <mingo@redhat.com> 6 * 7 * Interactivity improvements by Mike Galbraith 8 * (C) 2007 Mike Galbraith <efault@gmx.de> 9 * 10 * Various enhancements by Dmitry Adamushko. 11 * (C) 2007 Dmitry Adamushko <dmitry.adamushko@gmail.com> 12 * 13 * Group scheduling enhancements by Srivatsa Vaddagiri 14 * Copyright IBM Corporation, 2007 15 * Author: Srivatsa Vaddagiri <vatsa@linux.vnet.ibm.com> 16 * 17 * Scaled math optimizations by Thomas Gleixner 18 * Copyright (C) 2007, Linutronix GmbH, Thomas Gleixner <tglx@kernel.org> 19 * 20 * Adaptive scheduling granularity, math enhancements by Peter Zijlstra 21 * Copyright (C) 2007 Red Hat, Inc., Peter Zijlstra 22 */ 23 #include <linux/energy_model.h> 24 #include <linux/mmap_lock.h> 25 #include <linux/jiffies.h> 26 #include <linux/math.h> 27 #include <linux/mm_api.h> 28 #include <linux/highmem.h> 29 #include <linux/hrtimer.h> 30 #include <linux/hrtimer_bases.h> 31 #include <linux/spinlock_api.h> 32 #include <linux/cpumask_api.h> 33 #include <linux/lockdep_api.h> 34 #include <linux/softirq.h> 35 #include <linux/refcount_api.h> 36 #include <linux/topology.h> 37 #include <linux/sched/clock.h> 38 #include <linux/sched/cond_resched.h> 39 #include <linux/sched/cputime.h> 40 #include <linux/sched/isolation.h> 41 #include <linux/sched/nohz.h> 42 #include <linux/sched/prio.h> 43 #include <linux/static_call.h> 44 45 #include <linux/cpuidle.h> 46 #include <linux/interrupt.h> 47 #include <linux/memory-tiers.h> 48 #include <linux/mempolicy.h> 49 #include <linux/mutex_api.h> 50 #include <linux/profile.h> 51 #include <linux/psi.h> 52 #include <linux/ratelimit.h> 53 #include <linux/task_work.h> 54 #include <linux/rbtree_augmented.h> 55 56 #include <asm/switch_to.h> 57 58 #include <uapi/linux/sched/types.h> 59 60 #include "sched.h" 61 #include "stats.h" 62 #include "autogroup.h" 63 64 /* 65 * The initial- and re-scaling of tunables is configurable 66 * 67 * Options are: 68 * 69 * SCHED_TUNABLESCALING_NONE - unscaled, always *1 70 * SCHED_TUNABLESCALING_LOG - scaled logarithmically, *1+ilog(ncpus) 71 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus 72 * 73 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus)) 74 */ 75 unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG; 76 77 /* 78 * Default base time slice (request size r_i) for SCHED_NORMAL/SCHED_BATCH: 79 * 80 * Under EEVDF this is the request size used to compute the virtual 81 * deadline; see update_deadline(). 82 * 83 * (default: 0.70 msec * (1 + ilog(ncpus)), units: nanoseconds) 84 */ 85 unsigned int sysctl_sched_base_slice = 700000ULL; 86 static unsigned int normalized_sysctl_sched_base_slice = 700000ULL; 87 88 __read_mostly unsigned int sysctl_sched_migration_cost = 500000UL; 89 90 static int __init setup_sched_thermal_decay_shift(char *str) 91 { 92 pr_warn("Ignoring the deprecated sched_thermal_decay_shift= option\n"); 93 return 1; 94 } 95 __setup("sched_thermal_decay_shift=", setup_sched_thermal_decay_shift); 96 97 /* 98 * For asym packing, by default the lower numbered CPU has higher priority. 99 */ 100 int __weak arch_asym_cpu_priority(int cpu) 101 { 102 return -cpu; 103 } 104 105 /* 106 * The margin used when comparing utilization with CPU capacity. 107 * 108 * (default: ~20%) 109 */ 110 #define fits_capacity(cap, max) ((cap) * 1280 < (max) * 1024) 111 112 /* 113 * The margin used when comparing CPU capacities. 114 * is 'cap1' noticeably greater than 'cap2' 115 * 116 * (default: ~5%) 117 */ 118 #define capacity_greater(cap1, cap2) ((cap1) * 1024 > (cap2) * 1078) 119 120 #ifdef CONFIG_CFS_BANDWIDTH 121 /* 122 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool 123 * each time a cfs_rq requests quota. 124 * 125 * Note: in the case that the slice exceeds the runtime remaining (either due 126 * to consumption or the quota being specified to be smaller than the slice) 127 * we will always only issue the remaining available time. 128 * 129 * (default: 5 msec, units: microseconds) 130 */ 131 static unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL; 132 #endif 133 134 #ifdef CONFIG_NUMA_BALANCING 135 /* Restrict the NUMA promotion throughput (MB/s) for each target node. */ 136 static unsigned int sysctl_numa_balancing_promote_rate_limit = 65536; 137 #endif 138 139 #ifdef CONFIG_SYSCTL 140 static const struct ctl_table sched_fair_sysctls[] = { 141 #ifdef CONFIG_CFS_BANDWIDTH 142 { 143 .procname = "sched_cfs_bandwidth_slice_us", 144 .data = &sysctl_sched_cfs_bandwidth_slice, 145 .maxlen = sizeof(unsigned int), 146 .mode = 0644, 147 .proc_handler = proc_dointvec_minmax, 148 .extra1 = SYSCTL_ONE, 149 }, 150 #endif 151 #ifdef CONFIG_NUMA_BALANCING 152 { 153 .procname = "numa_balancing_promote_rate_limit_MBps", 154 .data = &sysctl_numa_balancing_promote_rate_limit, 155 .maxlen = sizeof(unsigned int), 156 .mode = 0644, 157 .proc_handler = proc_dointvec_minmax, 158 .extra1 = SYSCTL_ZERO, 159 }, 160 #endif /* CONFIG_NUMA_BALANCING */ 161 }; 162 163 static int __init sched_fair_sysctl_init(void) 164 { 165 register_sysctl_init("kernel", sched_fair_sysctls); 166 return 0; 167 } 168 late_initcall(sched_fair_sysctl_init); 169 #endif /* CONFIG_SYSCTL */ 170 171 static inline void update_load_add(struct load_weight *lw, unsigned long inc) 172 { 173 lw->weight += inc; 174 lw->inv_weight = 0; 175 } 176 177 static inline void update_load_sub(struct load_weight *lw, unsigned long dec) 178 { 179 lw->weight -= dec; 180 lw->inv_weight = 0; 181 } 182 183 static inline void update_load_set(struct load_weight *lw, unsigned long w) 184 { 185 lw->weight = w; 186 lw->inv_weight = 0; 187 } 188 189 /* 190 * Increase the granularity value when there are more CPUs, 191 * because with more CPUs the 'effective latency' as visible 192 * to users decreases. But the relationship is not linear, 193 * so pick a second-best guess by going with the log2 of the 194 * number of CPUs. 195 * 196 * This idea comes from the SD scheduler of Con Kolivas: 197 */ 198 static unsigned int get_update_sysctl_factor(void) 199 { 200 unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8); 201 unsigned int factor; 202 203 switch (sysctl_sched_tunable_scaling) { 204 case SCHED_TUNABLESCALING_NONE: 205 factor = 1; 206 break; 207 case SCHED_TUNABLESCALING_LINEAR: 208 factor = cpus; 209 break; 210 case SCHED_TUNABLESCALING_LOG: 211 default: 212 factor = 1 + ilog2(cpus); 213 break; 214 } 215 216 return factor; 217 } 218 219 static void update_sysctl(void) 220 { 221 unsigned int factor = get_update_sysctl_factor(); 222 223 #define SET_SYSCTL(name) \ 224 (sysctl_##name = (factor) * normalized_sysctl_##name) 225 SET_SYSCTL(sched_base_slice); 226 #undef SET_SYSCTL 227 } 228 229 void __init sched_init_granularity(void) 230 { 231 update_sysctl(); 232 } 233 234 #ifndef CONFIG_64BIT 235 #define WMULT_CONST (~0U) 236 #define WMULT_SHIFT 32 237 238 static void __update_inv_weight(struct load_weight *lw) 239 { 240 unsigned long w; 241 242 if (likely(lw->inv_weight)) 243 return; 244 245 w = scale_load_down(lw->weight); 246 247 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST)) 248 lw->inv_weight = 1; 249 else if (unlikely(!w)) 250 lw->inv_weight = WMULT_CONST; 251 else 252 lw->inv_weight = WMULT_CONST / w; 253 } 254 255 /* 256 * delta_exec * weight / lw.weight 257 * OR 258 * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT 259 * 260 * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case 261 * we're guaranteed shift stays positive because inv_weight is guaranteed to 262 * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22. 263 * 264 * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus 265 * weight/lw.weight <= 1, and therefore our shift will also be positive. 266 */ 267 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw) 268 { 269 u64 fact = scale_load_down(weight); 270 u32 fact_hi = (u32)(fact >> 32); 271 int shift = WMULT_SHIFT; 272 int fs; 273 274 __update_inv_weight(lw); 275 276 if (unlikely(fact_hi)) { 277 fs = fls(fact_hi); 278 shift -= fs; 279 fact >>= fs; 280 } 281 282 fact = mul_u32_u32(fact, lw->inv_weight); 283 284 fact_hi = (u32)(fact >> 32); 285 if (fact_hi) { 286 fs = fls(fact_hi); 287 shift -= fs; 288 fact >>= fs; 289 } 290 291 return mul_u64_u32_shr(delta_exec, fact, shift); 292 } 293 #else 294 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw) 295 { 296 return (delta_exec * weight) / lw->weight; 297 } 298 #endif 299 300 /* 301 * delta /= w 302 */ 303 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se) 304 { 305 if (se->h_load.weight != NICE_0_LOAD) 306 delta = __calc_delta(delta, NICE_0_LOAD, &se->h_load); 307 308 return delta; 309 } 310 311 const struct sched_class fair_sched_class; 312 313 /************************************************************** 314 * CFS operations on generic schedulable entities: 315 */ 316 317 #ifdef CONFIG_FAIR_GROUP_SCHED 318 319 /* Walk up scheduling entities hierarchy */ 320 #define for_each_sched_entity(se) \ 321 for (; se; se = se->parent) 322 323 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq) 324 { 325 struct rq *rq = rq_of(cfs_rq); 326 int cpu = cpu_of(rq); 327 328 if (cfs_rq->on_list) 329 return rq->tmp_alone_branch == &rq->leaf_cfs_rq_list; 330 331 cfs_rq->on_list = 1; 332 333 /* 334 * Ensure we either appear before our parent (if already 335 * enqueued) or force our parent to appear after us when it is 336 * enqueued. The fact that we always enqueue bottom-up 337 * reduces this to two cases and a special case for the root 338 * cfs_rq. Furthermore, it also means that we will always reset 339 * tmp_alone_branch either when the branch is connected 340 * to a tree or when we reach the top of the tree 341 */ 342 if (cfs_rq->tg->parent && 343 tg_cfs_rq(cfs_rq->tg->parent, cpu)->on_list) { 344 /* 345 * If parent is already on the list, we add the child 346 * just before. Thanks to circular linked property of 347 * the list, this means to put the child at the tail 348 * of the list that starts by parent. 349 */ 350 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list, 351 &(tg_cfs_rq(cfs_rq->tg->parent, cpu)->leaf_cfs_rq_list)); 352 /* 353 * The branch is now connected to its tree so we can 354 * reset tmp_alone_branch to the beginning of the 355 * list. 356 */ 357 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list; 358 return true; 359 } 360 361 if (!cfs_rq->tg->parent) { 362 /* 363 * cfs rq without parent should be put 364 * at the tail of the list. 365 */ 366 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list, 367 &rq->leaf_cfs_rq_list); 368 /* 369 * We have reach the top of a tree so we can reset 370 * tmp_alone_branch to the beginning of the list. 371 */ 372 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list; 373 return true; 374 } 375 376 /* 377 * The parent has not already been added so we want to 378 * make sure that it will be put after us. 379 * tmp_alone_branch points to the begin of the branch 380 * where we will add parent. 381 */ 382 list_add_rcu(&cfs_rq->leaf_cfs_rq_list, rq->tmp_alone_branch); 383 /* 384 * update tmp_alone_branch to points to the new begin 385 * of the branch 386 */ 387 rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list; 388 return false; 389 } 390 391 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq) 392 { 393 if (cfs_rq->on_list) { 394 struct rq *rq = rq_of(cfs_rq); 395 396 /* 397 * With cfs_rq being unthrottled/throttled during an enqueue, 398 * it can happen the tmp_alone_branch points to the leaf that 399 * we finally want to delete. In this case, tmp_alone_branch moves 400 * to the prev element but it will point to rq->leaf_cfs_rq_list 401 * at the end of the enqueue. 402 */ 403 if (rq->tmp_alone_branch == &cfs_rq->leaf_cfs_rq_list) 404 rq->tmp_alone_branch = cfs_rq->leaf_cfs_rq_list.prev; 405 406 list_del_rcu(&cfs_rq->leaf_cfs_rq_list); 407 cfs_rq->on_list = 0; 408 } 409 } 410 411 static inline void assert_list_leaf_cfs_rq(struct rq *rq) 412 { 413 WARN_ON_ONCE(rq->tmp_alone_branch != &rq->leaf_cfs_rq_list); 414 } 415 416 /* Iterate through all leaf cfs_rq's on a runqueue */ 417 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \ 418 list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list, \ 419 leaf_cfs_rq_list) 420 421 /* Do the two (enqueued) entities belong to the same group ? */ 422 static inline struct cfs_rq * 423 is_same_group(struct sched_entity *se, struct sched_entity *pse) 424 { 425 if (se->cfs_rq == pse->cfs_rq) 426 return se->cfs_rq; 427 428 return NULL; 429 } 430 431 static inline struct sched_entity *parent_entity(const struct sched_entity *se) 432 { 433 return se->parent; 434 } 435 436 static int tg_is_idle(struct task_group *tg) 437 { 438 return tg->idle > 0; 439 } 440 441 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq) 442 { 443 return cfs_rq->idle > 0; 444 } 445 446 static int se_is_idle(struct sched_entity *se) 447 { 448 if (entity_is_task(se)) 449 return task_has_idle_policy(task_of(se)); 450 return cfs_rq_is_idle(group_cfs_rq(se)); 451 } 452 453 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 454 455 #define for_each_sched_entity(se) \ 456 for (; se; se = NULL) 457 458 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq) 459 { 460 return true; 461 } 462 463 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq) 464 { 465 } 466 467 static inline void assert_list_leaf_cfs_rq(struct rq *rq) 468 { 469 } 470 471 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \ 472 for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos) 473 474 static inline struct sched_entity *parent_entity(struct sched_entity *se) 475 { 476 return NULL; 477 } 478 479 static inline int tg_is_idle(struct task_group *tg) 480 { 481 return 0; 482 } 483 484 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq) 485 { 486 return 0; 487 } 488 489 static int se_is_idle(struct sched_entity *se) 490 { 491 return task_has_idle_policy(task_of(se)); 492 } 493 494 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 495 496 static __always_inline 497 bool account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec); 498 499 /************************************************************** 500 * Scheduling class tree data structure manipulation methods: 501 */ 502 503 extern void __BUILD_BUG_vruntime_cmp(void); 504 505 /* Use __builtin_strcmp() because of __HAVE_ARCH_STRCMP: */ 506 507 #define vruntime_cmp(A, CMP_STR, B) ({ \ 508 int __res = 0; \ 509 \ 510 if (!__builtin_strcmp(CMP_STR, "<")) { \ 511 __res = ((s64)((A)-(B)) < 0); \ 512 } else if (!__builtin_strcmp(CMP_STR, "<=")) { \ 513 __res = ((s64)((A)-(B)) <= 0); \ 514 } else if (!__builtin_strcmp(CMP_STR, ">")) { \ 515 __res = ((s64)((A)-(B)) > 0); \ 516 } else if (!__builtin_strcmp(CMP_STR, ">=")) { \ 517 __res = ((s64)((A)-(B)) >= 0); \ 518 } else { \ 519 /* Unknown operator throws linker error: */ \ 520 __BUILD_BUG_vruntime_cmp(); \ 521 } \ 522 \ 523 __res; \ 524 }) 525 526 extern void __BUILD_BUG_vruntime_op(void); 527 528 #define vruntime_op(A, OP_STR, B) ({ \ 529 s64 __res = 0; \ 530 \ 531 if (!__builtin_strcmp(OP_STR, "-")) { \ 532 __res = (s64)((A)-(B)); \ 533 } else { \ 534 /* Unknown operator throws linker error: */ \ 535 __BUILD_BUG_vruntime_op(); \ 536 } \ 537 \ 538 __res; \ 539 }) 540 541 542 static inline __maybe_unused u64 max_vruntime(u64 max_vruntime, u64 vruntime) 543 { 544 if (vruntime_cmp(vruntime, ">", max_vruntime)) 545 max_vruntime = vruntime; 546 547 return max_vruntime; 548 } 549 550 static inline __maybe_unused u64 min_vruntime(u64 min_vruntime, u64 vruntime) 551 { 552 if (vruntime_cmp(vruntime, "<", min_vruntime)) 553 min_vruntime = vruntime; 554 555 return min_vruntime; 556 } 557 558 static inline bool entity_before(const struct sched_entity *a, 559 const struct sched_entity *b) 560 { 561 /* 562 * Tiebreak on vruntime seems unnecessary since it can 563 * hardly happen. 564 */ 565 return vruntime_cmp(a->deadline, "<", b->deadline); 566 } 567 568 /* 569 * Per avg_vruntime() below, cfs_rq::zero_vruntime is only slightly stale 570 * and this value should be no more than two lag bounds. Which puts it in the 571 * general order of: 572 * 573 * (slice + TICK_NSEC) << NICE_0_LOAD_SHIFT 574 * 575 * which is around 44 bits in size (on 64bit); that is 20 for 576 * NICE_0_LOAD_SHIFT, another 20 for NSEC_PER_MSEC and then a handful for 577 * however many msec the actual slice+tick ends up begin. 578 * 579 * (disregarding the actual divide-by-weight part makes for the worst case 580 * weight of 2, which nicely cancels vs the fuzz in zero_vruntime not actually 581 * being the zero-lag point). 582 */ 583 static inline s64 entity_key(struct cfs_rq *cfs_rq, struct sched_entity *se) 584 { 585 return vruntime_op(se->vruntime, "-", cfs_rq->zero_vruntime); 586 } 587 588 #define __node_2_se(node) \ 589 rb_entry((node), struct sched_entity, run_node) 590 591 /* 592 * Compute virtual time from the per-task service numbers: 593 * 594 * Fair schedulers conserve lag: 595 * 596 * \Sum lag_i = 0 597 * 598 * Where lag_i is given by: 599 * 600 * lag_i = S - s_i = w_i * (V - v_i) 601 * 602 * Where S is the ideal service time and V is it's virtual time counterpart. 603 * Therefore: 604 * 605 * \Sum lag_i = 0 606 * \Sum w_i * (V - v_i) = 0 607 * \Sum (w_i * V - w_i * v_i) = 0 608 * 609 * From which we can solve an expression for V in v_i (which we have in 610 * se->vruntime): 611 * 612 * \Sum v_i * w_i \Sum v_i * w_i 613 * V = -------------- = -------------- 614 * \Sum w_i W 615 * 616 * Specifically, this is the weighted average of all entity virtual runtimes. 617 * 618 * [[ NOTE: this is only equal to the ideal scheduler under the condition 619 * that join/leave operations happen at lag_i = 0, otherwise the 620 * virtual time has non-contiguous motion equivalent to: 621 * 622 * V +-= lag_i / W 623 * 624 * Also see the comment in place_entity() that deals with this. ]] 625 * 626 * However, since v_i is u64, and the multiplication could easily overflow 627 * transform it into a relative form that uses smaller quantities: 628 * 629 * Substitute: v_i == (v_i - v0) + v0 630 * 631 * \Sum ((v_i - v0) + v0) * w_i \Sum (v_i - v0) * w_i 632 * V = ---------------------------- = --------------------- + v0 633 * W W 634 * 635 * Which we track using: 636 * 637 * v0 := cfs_rq->zero_vruntime 638 * \Sum (v_i - v0) * w_i := cfs_rq->sum_w_vruntime 639 * \Sum w_i := cfs_rq->sum_weight 640 * 641 * Since zero_vruntime closely tracks the per-task service, these 642 * deltas: (v_i - v0), will be in the order of the maximal (virtual) lag 643 * induced in the system due to quantisation. 644 */ 645 static inline unsigned long avg_vruntime_weight(struct cfs_rq *cfs_rq, unsigned long w) 646 { 647 #ifdef CONFIG_64BIT 648 if (cfs_rq->sum_shift) 649 w = max(2UL, w >> cfs_rq->sum_shift); 650 #endif 651 return w; 652 } 653 654 static inline void 655 __sum_w_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se) 656 { 657 unsigned long weight = avg_vruntime_weight(cfs_rq, se->h_load.weight); 658 s64 w_vruntime, key = entity_key(cfs_rq, se); 659 660 w_vruntime = key * weight; 661 WARN_ON_ONCE((w_vruntime >> 63) != (w_vruntime >> 62)); 662 663 cfs_rq->sum_w_vruntime += w_vruntime; 664 cfs_rq->sum_weight += weight; 665 } 666 667 static void 668 sum_w_vruntime_add_paranoid(struct cfs_rq *cfs_rq, struct sched_entity *se) 669 { 670 unsigned long weight; 671 s64 key, tmp; 672 673 again: 674 weight = avg_vruntime_weight(cfs_rq, se->h_load.weight); 675 key = entity_key(cfs_rq, se); 676 677 if (check_mul_overflow(key, weight, &key)) 678 goto overflow; 679 680 if (check_add_overflow(cfs_rq->sum_w_vruntime, key, &tmp)) 681 goto overflow; 682 683 cfs_rq->sum_w_vruntime = tmp; 684 cfs_rq->sum_weight += weight; 685 return; 686 687 overflow: 688 /* 689 * There's gotta be a limit -- if we're still failing at this point 690 * there's really nothing much to be done about things. 691 */ 692 BUG_ON(cfs_rq->sum_shift >= 10); 693 cfs_rq->sum_shift++; 694 695 /* 696 * Note: \Sum (k_i * (w_i >> 1)) != (\Sum (k_i * w_i)) >> 1 697 */ 698 cfs_rq->sum_w_vruntime = 0; 699 cfs_rq->sum_weight = 0; 700 701 for (struct rb_node *node = cfs_rq->tasks_timeline.rb_leftmost; 702 node; node = rb_next(node)) 703 __sum_w_vruntime_add(cfs_rq, __node_2_se(node)); 704 705 goto again; 706 } 707 708 static void 709 sum_w_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se) 710 { 711 if (sched_feat(PARANOID_AVG)) 712 return sum_w_vruntime_add_paranoid(cfs_rq, se); 713 714 __sum_w_vruntime_add(cfs_rq, se); 715 } 716 717 static void 718 sum_w_vruntime_sub(struct cfs_rq *cfs_rq, struct sched_entity *se) 719 { 720 unsigned long weight = avg_vruntime_weight(cfs_rq, se->h_load.weight); 721 s64 key = entity_key(cfs_rq, se); 722 723 cfs_rq->sum_w_vruntime -= key * weight; 724 cfs_rq->sum_weight -= weight; 725 } 726 727 static inline 728 void update_zero_vruntime(struct cfs_rq *cfs_rq, s64 delta) 729 { 730 /* 731 * v' = v + d ==> sum_w_vruntime' = sum_w_vruntime - d*sum_weight 732 */ 733 cfs_rq->sum_w_vruntime -= cfs_rq->sum_weight * delta; 734 cfs_rq->zero_vruntime += delta; 735 } 736 737 /* 738 * Specifically: avg_vruntime() + 0 must result in entity_eligible() := true 739 * For this to be so, the result of this function must have a left bias. 740 * 741 * Called in: 742 * - place_entity() -- before enqueue 743 * - update_entity_lag() -- before dequeue 744 * - update_deadline() -- slice expiration 745 * 746 * This means it is one entry 'behind' but that puts it close enough to where 747 * the bound on entity_key() is at most two lag bounds. 748 */ 749 u64 avg_vruntime(struct cfs_rq *cfs_rq) 750 { 751 struct sched_entity *curr = cfs_rq->curr; 752 long weight = cfs_rq->sum_weight; 753 s64 delta = 0; 754 755 if (curr && !curr->on_rq) 756 curr = NULL; 757 758 if (weight) { 759 s64 runtime = cfs_rq->sum_w_vruntime; 760 761 if (curr) { 762 unsigned long w = avg_vruntime_weight(cfs_rq, curr->h_load.weight); 763 764 runtime += entity_key(cfs_rq, curr) * w; 765 weight += w; 766 } 767 768 /* sign flips effective floor / ceiling */ 769 if (runtime < 0) 770 runtime -= (weight - 1); 771 772 delta = div64_long(runtime, weight); 773 } else if (curr) { 774 /* 775 * When there is but one element, it is the average. 776 */ 777 delta = curr->vruntime - cfs_rq->zero_vruntime; 778 } 779 780 update_zero_vruntime(cfs_rq, delta); 781 782 return cfs_rq->zero_vruntime; 783 } 784 785 /* 786 * \Sum (v_i - v0)*w_i 787 * V = ------------------- + v0 788 * \Sum w_i 789 * 790 * Let W = \Sum w_i, and move v_j such that 'v_j == V', thus: 791 * 792 * V = 1/W * {(v_j - v0)*w_j + \Sum_i!=j (v_i - v0)*w_i} + v0 793 * 794 * v_j = 1/W * {(v_j - v0)*w_j + \Sum_i!=j (v_i - v0)*w_i} + v0 795 * 796 * v_j = 1/W * (v_j - v0)*w_j + 1/W * \Sum_i!=j (v_i - v0)*w_i + v0 797 * 798 * v_j - 1/W * (v_j - v0)*w_j = 1/W * \Sum_i!=j (v_i - v0)*w_i + v0 799 * 800 * v_j*W - (v_j - v0)*w_j = \Sum_i!=j (v_i - v0)*w_i + v0*W 801 * 802 * v_j*(W - w_j) + v0*w_j = \Sum_i!=j (v_i - v0)*w_i + v0*W 803 * 804 * v_j*(W - w_j) = \Sum_i!=j (v_i - v0)*w_i + v0*(W - w_j) 805 * 806 * \Sum_i!=j (v_i - v0)*w_i 807 * v_j = ------------------------ + v0 808 * W - w_j 809 * 810 * When v_j happens to be curr, then '\Sum_i!=j (v_i - v0)*w_i' 811 * is cfs_rq->sum_w_runtime, and 'W - w_j' is cfs_rq->sum_weight, since curr 812 * is not included in the sum. 813 */ 814 static u64 ineligible_vruntime(struct cfs_rq *cfs_rq) 815 { 816 struct sched_entity *curr = cfs_rq->curr; 817 long weight = cfs_rq->sum_weight; 818 s64 delta = 0; 819 820 if (curr && !curr->on_rq) 821 curr = NULL; 822 823 if (weight) { 824 s64 runtime = cfs_rq->sum_w_vruntime; 825 826 /* 827 * Do not add @curr to obtain the effective '- w_j' terms. 828 */ 829 830 /* sign flips effective floor / ceiling */ 831 if (runtime < 0) 832 runtime -= (weight - 1); 833 834 delta = div64_long(runtime, weight); 835 } 836 837 return cfs_rq->zero_vruntime + delta + 1; 838 } 839 840 static inline u64 cfs_rq_max_slice(struct cfs_rq *cfs_rq); 841 842 /* 843 * lag_i = S - s_i = w_i * (V - v_i) 844 * 845 * However, since V is approximated by the weighted average of all entities it 846 * is possible -- by addition/removal/reweight to the tree -- to move V around 847 * and end up with a larger lag than we started with. 848 * 849 * Limit this to either double the slice length with a minimum of TICK_NSEC 850 * since that is the timing granularity. 851 * 852 * EEVDF gives the following limit for a steady state system: 853 * 854 * -r_max < lag < max(r_max, q) 855 */ 856 static s64 entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se, u64 avruntime) 857 { 858 u64 max_slice = cfs_rq_max_slice(cfs_rq) + TICK_NSEC; 859 s64 vlag, limit; 860 861 vlag = avruntime - se->vruntime; 862 limit = calc_delta_fair(max_slice, se); 863 864 return clamp(vlag, -limit, limit); 865 } 866 867 /* 868 * Delayed dequeue aims to reduce the negative lag of a dequeued task. While 869 * updating the lag of an entity, check that negative lag didn't increase 870 * during the delayed dequeue period which would be unfair. 871 * Similarly, check that the entity didn't gain positive lag when DELAY_ZERO 872 * is set. 873 * 874 * Return true if the vlag has been modified. Specifically: 875 * 876 * se->vlag != avg_vruntime() - se->vruntime 877 * 878 * This can be due to clamping in entity_lag() or clamping due to 879 * sched_delayed. Either way, when vlag is modified and the entity is 880 * retained, the tree needs to be adjusted. 881 */ 882 static __always_inline 883 bool update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se) 884 { 885 u64 avruntime = avg_vruntime(cfs_rq); 886 s64 vlag = entity_lag(cfs_rq, se, avruntime); 887 888 if (se->sched_delayed) { 889 /* previous vlag < 0 otherwise se would not be delayed */ 890 vlag = max(vlag, se->vlag); 891 if (sched_feat(DELAY_ZERO)) 892 vlag = min(vlag, 0); 893 } 894 se->vlag = vlag; 895 896 return avruntime - vlag != se->vruntime; 897 } 898 899 /* 900 * Entity is eligible once it received less service than it ought to have, 901 * eg. lag >= 0. 902 * 903 * lag_i = S - s_i = w_i*(V - v_i) 904 * 905 * lag_i >= 0 -> V >= v_i 906 * 907 * \Sum (v_i - v0)*w_i 908 * V = ------------------- + v0 909 * \Sum w_i 910 * 911 * lag_i >= 0 -> \Sum (v_i - v0)*w_i >= (v_i - v0)*(\Sum w_i) 912 * 913 * Note: using 'avg_vruntime() > se->vruntime' is inaccurate due 914 * to the loss in precision caused by the division. 915 */ 916 static int vruntime_eligible(struct cfs_rq *cfs_rq, u64 vruntime) 917 { 918 struct sched_entity *curr = cfs_rq->curr; 919 s64 key, avg = cfs_rq->sum_w_vruntime; 920 long load = cfs_rq->sum_weight; 921 922 if (curr && curr->on_rq) { 923 unsigned long weight = avg_vruntime_weight(cfs_rq, curr->h_load.weight); 924 925 avg += entity_key(cfs_rq, curr) * weight; 926 load += weight; 927 } 928 929 key = vruntime_op(vruntime, "-", cfs_rq->zero_vruntime); 930 931 /* 932 * The worst case term for @key includes 'NSEC_TICK * NICE_0_LOAD' 933 * and @load obviously includes NICE_0_LOAD. NSEC_TICK is around 24 934 * bits, while NICE_0_LOAD is 20 on 64bit and 10 otherwise. 935 * 936 * This gives that on 64bit the product will be at least 64bit which 937 * overflows s64, while on 32bit it will only be 44bits and should fit 938 * comfortably. 939 */ 940 #ifdef CONFIG_64BIT 941 #ifdef CONFIG_ARCH_SUPPORTS_INT128 942 /* This often results in simpler code than __builtin_mul_overflow(). */ 943 return avg >= (__int128)key * load; 944 #else 945 s64 rhs; 946 /* 947 * On overflow, the sign of key tells us the correct answer: a large 948 * positive key means vruntime >> V, so not eligible; a large negative 949 * key means vruntime << V, so eligible. 950 */ 951 if (check_mul_overflow(key, load, &rhs)) 952 return key <= 0; 953 954 return avg >= rhs; 955 #endif 956 #else /* 32bit */ 957 return avg >= key * load; 958 #endif 959 } 960 961 int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se) 962 { 963 return vruntime_eligible(cfs_rq, se->vruntime); 964 } 965 966 static inline u64 cfs_rq_min_slice(struct cfs_rq *cfs_rq) 967 { 968 struct sched_entity *root = __pick_root_entity(cfs_rq); 969 struct sched_entity *curr = cfs_rq->curr; 970 u64 min_slice = ~0ULL; 971 972 if (curr && curr->on_rq) 973 min_slice = curr->slice; 974 975 if (root) 976 min_slice = min(min_slice, root->min_slice); 977 978 return min_slice; 979 } 980 981 static inline u64 cfs_rq_max_slice(struct cfs_rq *cfs_rq) 982 { 983 struct sched_entity *root = __pick_root_entity(cfs_rq); 984 struct sched_entity *curr = cfs_rq->curr; 985 u64 max_slice = 0ULL; 986 987 if (curr && curr->on_rq) 988 max_slice = curr->slice; 989 990 if (root) 991 max_slice = max(max_slice, root->max_slice); 992 993 return max_slice; 994 } 995 996 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b) 997 { 998 return entity_before(__node_2_se(a), __node_2_se(b)); 999 } 1000 1001 /* min() for wrapping vruntimes */ 1002 static inline u64 __min_vruntime(u64 a, u64 b) 1003 { 1004 return vruntime_cmp(a, "<", b) ? a : b; 1005 } 1006 1007 RB_DECLARE_CALLBACKS(static, min_vruntime_cb, 1008 struct sched_entity, run_node, 1009 RB_AUG(vruntime, min_vruntime, __min_vruntime), 1010 RB_AUG(slice, min_slice, min), 1011 RB_AUG(slice, max_slice, max)); 1012 1013 /* 1014 * Enqueue an entity into the rb-tree: 1015 */ 1016 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) 1017 { 1018 WARN_ON_ONCE(&rq_of(cfs_rq)->cfs != cfs_rq); 1019 WARN_ON_ONCE(!entity_is_task(se)); 1020 1021 sum_w_vruntime_add(cfs_rq, se); 1022 se->min_vruntime = se->vruntime; 1023 se->min_slice = se->slice; 1024 se->max_slice = se->slice; 1025 1026 rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline, 1027 __entity_less, &min_vruntime_cb); 1028 } 1029 1030 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) 1031 { 1032 WARN_ON_ONCE(&rq_of(cfs_rq)->cfs != cfs_rq); 1033 WARN_ON_ONCE(!entity_is_task(se)); 1034 1035 rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline, 1036 &min_vruntime_cb); 1037 sum_w_vruntime_sub(cfs_rq, se); 1038 } 1039 1040 struct sched_entity *__pick_root_entity(struct cfs_rq *cfs_rq) 1041 { 1042 struct rb_node *root = cfs_rq->tasks_timeline.rb_root.rb_node; 1043 1044 if (!root) 1045 return NULL; 1046 1047 return __node_2_se(root); 1048 } 1049 1050 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq) 1051 { 1052 struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline); 1053 1054 if (!left) 1055 return NULL; 1056 1057 return __node_2_se(left); 1058 } 1059 1060 /* 1061 * Set the vruntime up to which an entity can run before looking 1062 * for another entity to pick. 1063 * In case of run to parity, we use the shortest slice of the enqueued 1064 * entities to set the protected period. 1065 * When run to parity is disabled, we give a minimum quantum to the running 1066 * entity to ensure progress. 1067 */ 1068 static inline void set_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se) 1069 { 1070 u64 slice = normalized_sysctl_sched_base_slice; 1071 u64 vprot = se->deadline; 1072 1073 if (sched_feat(RUN_TO_PARITY)) 1074 slice = cfs_rq_min_slice(cfs_rq); 1075 1076 slice = min(slice, se->slice); 1077 1078 /* If there are shorter slices than se's one */ 1079 if (slice != se->slice) { 1080 vprot = min_vruntime(vprot, se->vruntime + calc_delta_fair(slice, se)); 1081 if (sched_feat(PREEMPT_SHORT)) 1082 vprot = min_vruntime(vprot, ineligible_vruntime(cfs_rq)); 1083 } 1084 1085 se->vprot = vprot; 1086 } 1087 1088 static inline void update_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se) 1089 { 1090 u64 vruntime = min_vruntime(se->vruntime, avg_vruntime(cfs_rq)); 1091 u64 slice = cfs_rq_min_slice(cfs_rq); 1092 u64 vprot = min_vruntime(se->vprot, vruntime + calc_delta_fair(slice, se)); 1093 1094 if (sched_feat(PREEMPT_SHORT) && slice != se->slice) 1095 vprot = min_vruntime(vprot, ineligible_vruntime(cfs_rq)); 1096 1097 se->vprot = vprot; 1098 } 1099 1100 static inline bool protect_slice(struct sched_entity *se) 1101 { 1102 return vruntime_cmp(se->vruntime, "<", se->vprot); 1103 } 1104 1105 static inline void cancel_protect_slice(struct sched_entity *se) 1106 { 1107 if (protect_slice(se)) 1108 se->vprot = se->vruntime; 1109 } 1110 1111 /* 1112 * Earliest Eligible Virtual Deadline First 1113 * 1114 * In order to provide latency guarantees for different request sizes 1115 * EEVDF selects the best runnable task from two criteria: 1116 * 1117 * 1) the task must be eligible (must be owed service) 1118 * 1119 * 2) from those tasks that meet 1), we select the one 1120 * with the earliest virtual deadline. 1121 * 1122 * We can do this in O(log n) time due to an augmented RB-tree. The 1123 * tree keeps the entries sorted on deadline, but also functions as a 1124 * heap based on the vruntime by keeping: 1125 * 1126 * se->min_vruntime = min(se->vruntime, se->{left,right}->min_vruntime) 1127 * 1128 * Which allows tree pruning through eligibility. 1129 */ 1130 static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq, bool protect) 1131 { 1132 struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node; 1133 struct sched_entity *se = __pick_first_entity(cfs_rq); 1134 struct sched_entity *curr = cfs_rq->curr; 1135 struct sched_entity *best = NULL; 1136 1137 /* 1138 * We can safely skip eligibility check if there is only one entity 1139 * in this cfs_rq, saving some cycles. 1140 */ 1141 if (cfs_rq->h_nr_queued == 1) 1142 return curr && curr->on_rq ? curr : se; 1143 1144 /* 1145 * Picking the ->next buddy will affect latency but not fairness. 1146 */ 1147 if (sched_feat(PICK_BUDDY) && protect && 1148 cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next)) { 1149 /* ->next will never be delayed */ 1150 WARN_ON_ONCE(cfs_rq->next->sched_delayed); 1151 return cfs_rq->next; 1152 } 1153 1154 if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr))) 1155 curr = NULL; 1156 1157 if (curr && protect && protect_slice(curr)) 1158 return curr; 1159 1160 /* Pick the leftmost entity if it's eligible */ 1161 if (se && entity_eligible(cfs_rq, se)) { 1162 best = se; 1163 goto found; 1164 } 1165 1166 /* Heap search for the EEVD entity */ 1167 while (node) { 1168 struct rb_node *left = node->rb_left; 1169 1170 /* 1171 * Eligible entities in left subtree are always better 1172 * choices, since they have earlier deadlines. 1173 */ 1174 if (left && vruntime_eligible(cfs_rq, 1175 __node_2_se(left)->min_vruntime)) { 1176 node = left; 1177 continue; 1178 } 1179 1180 se = __node_2_se(node); 1181 1182 /* 1183 * The left subtree either is empty or has no eligible 1184 * entity, so check the current node since it is the one 1185 * with earliest deadline that might be eligible. 1186 */ 1187 if (entity_eligible(cfs_rq, se)) { 1188 best = se; 1189 break; 1190 } 1191 1192 node = node->rb_right; 1193 } 1194 found: 1195 if (!best || (curr && entity_before(curr, best))) 1196 best = curr; 1197 1198 return best; 1199 } 1200 1201 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq) 1202 { 1203 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root); 1204 1205 if (!last) 1206 return NULL; 1207 1208 return __node_2_se(last); 1209 } 1210 1211 /************************************************************** 1212 * Scheduling class statistics methods: 1213 */ 1214 int sched_update_scaling(void) 1215 { 1216 unsigned int factor = get_update_sysctl_factor(); 1217 1218 #define WRT_SYSCTL(name) \ 1219 (normalized_sysctl_##name = sysctl_##name / (factor)) 1220 WRT_SYSCTL(sched_base_slice); 1221 #undef WRT_SYSCTL 1222 1223 return 0; 1224 } 1225 1226 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se); 1227 1228 /* 1229 * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i 1230 * this is probably good enough. 1231 */ 1232 static bool update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se) 1233 { 1234 if (vruntime_cmp(se->vruntime, "<", se->deadline)) 1235 return false; 1236 1237 /* 1238 * For EEVDF the virtual time slope is determined by w_i (iow. 1239 * nice) while the request time r_i is determined by 1240 * sysctl_sched_base_slice. 1241 */ 1242 if (!se->custom_slice) 1243 se->slice = sysctl_sched_base_slice; 1244 1245 /* 1246 * EEVDF: vd_i = ve_i + r_i / w_i 1247 */ 1248 se->deadline = se->vruntime + calc_delta_fair(se->slice, se); 1249 avg_vruntime(cfs_rq); 1250 1251 /* 1252 * The task has consumed its request, reschedule. 1253 */ 1254 return true; 1255 } 1256 1257 #include "pelt.h" 1258 1259 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu); 1260 static unsigned long task_h_load(struct task_struct *p); 1261 static unsigned long capacity_of(int cpu); 1262 1263 /* Give new sched_entity start runnable values to heavy its load in infant time */ 1264 void init_entity_runnable_average(struct sched_entity *se) 1265 { 1266 struct sched_avg *sa = &se->avg; 1267 1268 memset(sa, 0, sizeof(*sa)); 1269 1270 /* 1271 * Tasks are initialized with full load to be seen as heavy tasks until 1272 * they get a chance to stabilize to their real load level. 1273 * Group entities are initialized with zero load to reflect the fact that 1274 * nothing has been attached to the task group yet. 1275 */ 1276 if (entity_is_task(se)) 1277 sa->load_avg = scale_load_down(se->load.weight); 1278 1279 /* when this task is enqueued, it will contribute to its cfs_rq's load_avg */ 1280 } 1281 1282 /* 1283 * With new tasks being created, their initial util_avgs are extrapolated 1284 * based on the cfs_rq's current util_avg: 1285 * 1286 * util_avg = cfs_rq->avg.util_avg / (cfs_rq->avg.load_avg + 1) 1287 * * se_weight(se) 1288 * 1289 * However, in many cases, the above util_avg does not give a desired 1290 * value. Moreover, the sum of the util_avgs may be divergent, such 1291 * as when the series is a harmonic series. 1292 * 1293 * To solve this problem, we also cap the util_avg of successive tasks to 1294 * only 1/2 of the left utilization budget: 1295 * 1296 * util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n 1297 * 1298 * where n denotes the nth task and cpu_scale the CPU capacity. 1299 * 1300 * For example, for a CPU with 1024 of capacity, a simplest series from 1301 * the beginning would be like: 1302 * 1303 * task util_avg: 512, 256, 128, 64, 32, 16, 8, ... 1304 * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ... 1305 * 1306 * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap) 1307 * if util_avg > util_avg_cap. 1308 */ 1309 void post_init_entity_util_avg(struct task_struct *p) 1310 { 1311 struct sched_entity *se = &p->se; 1312 struct cfs_rq *cfs_rq = cfs_rq_of(se); 1313 struct sched_avg *sa = &se->avg; 1314 long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq))); 1315 long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2; 1316 1317 if (p->sched_class != &fair_sched_class) { 1318 /* 1319 * For !fair tasks do: 1320 * 1321 update_cfs_rq_load_avg(now, cfs_rq); 1322 attach_entity_load_avg(cfs_rq, se); 1323 switched_from_fair(rq, p); 1324 * 1325 * such that the next switched_to_fair() has the 1326 * expected state. 1327 */ 1328 se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq); 1329 return; 1330 } 1331 1332 if (cap > 0) { 1333 if (cfs_rq->avg.util_avg != 0) { 1334 sa->util_avg = cfs_rq->avg.util_avg * se_weight(se); 1335 sa->util_avg /= (cfs_rq->avg.load_avg + 1); 1336 1337 if (sa->util_avg > cap) 1338 sa->util_avg = cap; 1339 } else { 1340 sa->util_avg = cap; 1341 } 1342 } 1343 1344 sa->runnable_avg = sa->util_avg; 1345 } 1346 1347 static inline void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec); 1348 1349 static s64 update_se(struct rq *rq, struct sched_entity *se) 1350 { 1351 u64 now = rq_clock_task(rq); 1352 s64 delta_exec; 1353 1354 delta_exec = now - se->exec_start; 1355 if (unlikely(delta_exec <= 0)) 1356 return delta_exec; 1357 1358 se->exec_start = now; 1359 if (entity_is_task(se)) { 1360 struct task_struct *running = rq->curr; 1361 /* 1362 * If se is a task, we account the time against the running 1363 * task, as w/ proxy-exec they may not be the same. 1364 */ 1365 running->se.exec_start = now; 1366 running->se.sum_exec_runtime += delta_exec; 1367 1368 trace_sched_stat_runtime(running, delta_exec); 1369 account_group_exec_runtime(running, delta_exec); 1370 account_mm_sched(rq, running, delta_exec); 1371 1372 cgroup_account_cputime(running, delta_exec); 1373 } else { 1374 /* If not task, account the time against donor se */ 1375 se->sum_exec_runtime += delta_exec; 1376 } 1377 1378 if (schedstat_enabled()) { 1379 struct sched_statistics *stats; 1380 1381 stats = __schedstats_from_se(se); 1382 __schedstat_set(stats->exec_max, 1383 max(delta_exec, stats->exec_max)); 1384 } 1385 1386 return delta_exec; 1387 } 1388 1389 #ifdef CONFIG_SCHED_CACHE 1390 1391 /* 1392 * XXX numbers come from a place the sun don't shine -- probably wants to be SD 1393 * tunable or so. 1394 */ 1395 #define EPOCH_PERIOD (HZ / 100) /* 10 ms */ 1396 #define EPOCH_LLC_AFFINITY_TIMEOUT 5 /* 50 ms */ 1397 __read_mostly unsigned int llc_aggr_tolerance = 1; 1398 __read_mostly unsigned int llc_epoch_period = EPOCH_PERIOD; 1399 __read_mostly unsigned int llc_epoch_affinity_timeout = EPOCH_LLC_AFFINITY_TIMEOUT; 1400 __read_mostly unsigned int llc_imb_pct = 20; 1401 __read_mostly unsigned int llc_overaggr_pct = 50; 1402 1403 static int llc_id(int cpu) 1404 { 1405 if (cpu < 0) 1406 return -1; 1407 1408 return per_cpu(sd_llc_id, cpu); 1409 } 1410 1411 static inline int get_sched_cache_scale(int mul) 1412 { 1413 unsigned int tol = READ_ONCE(llc_aggr_tolerance); 1414 1415 if (!tol) 1416 return 0; 1417 1418 if (tol >= 100) 1419 return INT_MAX; 1420 1421 return (1 + (tol - 1) * mul); 1422 } 1423 1424 static bool exceed_llc_capacity(struct sched_cache_group *grp, int cpu) 1425 { 1426 #ifdef CONFIG_NUMA_BALANCING 1427 unsigned long llc, footprint; 1428 struct sched_domain *sd; 1429 int scale; 1430 1431 guard(rcu)(); 1432 1433 sd = rcu_dereference_sched_domain(cpu_rq(cpu)->sd); 1434 if (!sd) 1435 return true; 1436 1437 if (static_branch_likely(&sched_numa_balancing)) { 1438 /* 1439 * TBD: RDT exclusive LLC ways reserved should be 1440 * excluded. 1441 */ 1442 llc = sd->llc_bytes; 1443 footprint = READ_ONCE(grp->footprint); 1444 1445 /* 1446 * Scale the LLC size by 256*llc_aggr_tolerance 1447 * and compare it to the task's footprint. 1448 * 1449 * Suppose the L3 size is 32MB. If the 1450 * llc_aggr_tolerance is 1: 1451 * When the footprint is larger than 32MB, the 1452 * process is regarded as exceeding the LLC 1453 * capacity. If the llc_aggr_tolerance is 99: 1454 * When the footprint is larger than 784GB, the 1455 * process is regarded as exceeding the LLC 1456 * capacity: 1457 * 784GB = (1 + (99 - 1) * 256) * 32MB 1458 * If the llc_aggr_tolerance is 100: 1459 * ignore the footprint and do the aggregation 1460 * anyway. 1461 */ 1462 scale = get_sched_cache_scale(256); 1463 if (scale == INT_MAX) 1464 return false; 1465 1466 return ((llc * (u64)scale) < (footprint * PAGE_SIZE)); 1467 } 1468 #endif 1469 return false; 1470 } 1471 1472 static bool invalid_llc_nr(struct sched_cache_group *grp, struct task_struct *p, 1473 int cpu) 1474 { 1475 int scale; 1476 1477 if (get_nr_threads(p) <= 1) 1478 return true; 1479 1480 /* 1481 * Scale the number of 'cores' in a LLC by llc_aggr_tolerance 1482 * and compare it to the task's active threads. 1483 */ 1484 scale = get_sched_cache_scale(1); 1485 if (scale == INT_MAX) 1486 return false; 1487 1488 return !fits_capacity((READ_ONCE(grp->nr_running_avg) * cpu_smt_num_threads), 1489 (scale * per_cpu(sd_llc_size, cpu))); 1490 } 1491 1492 /* 1493 * A task counts in nr_pref_llc_running while it is queued on its preferred 1494 * LLC (pref_llc_queued) and runnable (!sched_delayed), keeping the counter in 1495 * the runnable domain so alb_break_llc() can compare it with h_nr_runnable. 1496 */ 1497 static bool task_pref_llc_runnable(struct task_struct *p) 1498 { 1499 return p->pref_llc_queued && !p->se.sched_delayed; 1500 } 1501 1502 static void pref_llc_running_inc(struct rq *rq, struct task_struct *p) 1503 { 1504 if (task_pref_llc_runnable(p)) 1505 rq->nr_pref_llc_running++; 1506 } 1507 1508 static void pref_llc_running_dec(struct rq *rq, struct task_struct *p) 1509 { 1510 if (task_pref_llc_runnable(p)) 1511 rq->nr_pref_llc_running--; 1512 } 1513 1514 static void account_llc_enqueue(struct rq *rq, struct task_struct *p) 1515 { 1516 int pref_llc, pref_llc_queued; 1517 struct sched_domain *sd; 1518 1519 pref_llc = p->preferred_llc; 1520 if (pref_llc < 0) 1521 return; 1522 1523 pref_llc_queued = (pref_llc == task_llc(p)); 1524 rq->nr_llc_running++; 1525 1526 /* 1527 * Record whether p is enqueued on its preferred 1528 * LLC, in order to pair with account_llc_dequeue() 1529 * to maintain a consistent nr_pref_llc_running per 1530 * runqueue. 1531 * This is necessary because a race condition exists: 1532 * after a task is enqueued on a runqueue, task_llc(p) 1533 * may change due to CPU hotplug. Therefore, checking 1534 * task_llc(p) to determine whether the task is being 1535 * dequeued from its preferred LLC is unreliable and 1536 * can cause inconsistent values - checking the 1537 * p->pref_llc_queued in account_llc_dequeue() would 1538 * be reliable. 1539 */ 1540 p->pref_llc_queued = pref_llc_queued; 1541 1542 /* Skipped while delayed; clear_delayed() adds it back on wake. */ 1543 pref_llc_running_inc(rq, p); 1544 1545 sd = rcu_dereference_all(rq->sd); 1546 if (sd && (unsigned int)pref_llc < sd->llc_max) 1547 sd->llc_counts[pref_llc]++; 1548 } 1549 1550 static void account_llc_dequeue(struct rq *rq, struct task_struct *p) 1551 { 1552 struct sched_domain *sd; 1553 int pref_llc; 1554 1555 pref_llc = p->preferred_llc; 1556 if (pref_llc < 0) 1557 return; 1558 1559 rq->nr_llc_running--; 1560 if (p->pref_llc_queued) { 1561 /* 1562 * Skipped if still delayed (set_delayed() already removed it); 1563 * clearing pref_llc_queued below also stops clear_delayed() 1564 * from re-adding it. 1565 */ 1566 pref_llc_running_dec(rq, p); 1567 /* 1568 * Update the status in case 1569 * other logic might query 1570 * this. 1571 */ 1572 p->pref_llc_queued = 0; 1573 } 1574 1575 sd = rcu_dereference_all(rq->sd); 1576 if (sd && (unsigned int)pref_llc < sd->llc_max) { 1577 /* 1578 * There is a race condition between dequeue 1579 * and CPU hotplug. After a task has been enqueued 1580 * on CPUx, a CPU hotplug event occurs, and all online 1581 * CPUs (including CPUx) rebuild their sched_domains 1582 * and reset statistics to zero(including sd->llc_counts). 1583 * This can cause temporary undercount and we have to 1584 * check for such underflow in sd->llc_counts. 1585 * 1586 * This undercount is temporary and accurate accounting 1587 * will resume once the rq has a chance to be idle. 1588 */ 1589 if (sd->llc_counts[pref_llc]) 1590 sd->llc_counts[pref_llc]--; 1591 } 1592 } 1593 1594 int mm_init_sched(struct mm_struct *mm, 1595 struct sched_cache_time __percpu *_pcpu_sched) 1596 { 1597 struct sched_cache_group *grp; 1598 unsigned long epoch = 0; 1599 int i; 1600 1601 grp = kzalloc_obj(*grp); 1602 if (!grp) { 1603 free_percpu(_pcpu_sched); 1604 mm->sched_cache_grp = NULL; 1605 return -ENOMEM; 1606 } 1607 1608 for_each_possible_cpu(i) { 1609 struct sched_cache_time *pcpu_sched = per_cpu_ptr(_pcpu_sched, i); 1610 struct rq *rq = cpu_rq(i); 1611 1612 pcpu_sched->runtime = 0; 1613 /* a slightly stale cpu epoch is acceptible */ 1614 pcpu_sched->epoch = rq->cpu_epoch; 1615 epoch = rq->cpu_epoch; 1616 } 1617 1618 raw_spin_lock_init(&grp->lock); 1619 grp->epoch = epoch; 1620 grp->cpu = -1; 1621 grp->next_scan = jiffies; 1622 grp->nr_running_avg = 0; 1623 grp->footprint = 0; 1624 refcount_set(&grp->refcnt, 1); 1625 /* 1626 * The update to grp->pcpu_sched should not be reordered 1627 * before initialization to grp's other fields, in case 1628 * the readers may get invalid mm_sched_epoch, etc. 1629 */ 1630 smp_store_release(&grp->pcpu_sched, _pcpu_sched); 1631 /* 1632 * Publish the group last. Not every reader qualifies it by 1633 * grp->pcpu_sched - can_migrate_llc_task() only checks that the 1634 * pointer is non-NULL before reading grp->footprint and 1635 * grp->nr_running_avg - so a reachable group must already be 1636 * fully initialized. 1637 */ 1638 smp_store_release(&mm->sched_cache_grp, grp); 1639 return 0; 1640 } 1641 1642 static void sched_cache_group_free_rcu(struct rcu_head *rcu) 1643 { 1644 struct sched_cache_group *grp = 1645 container_of(rcu, struct sched_cache_group, rcu); 1646 1647 free_percpu(grp->pcpu_sched); 1648 kfree(grp); 1649 } 1650 1651 static void sched_cache_group_put(struct sched_cache_group *grp) 1652 { 1653 if (!grp || !refcount_dec_and_test(&grp->refcnt)) 1654 return; 1655 1656 call_rcu(&grp->rcu, sched_cache_group_free_rcu); 1657 } 1658 1659 DEFINE_FREE(sched_cache_group_put, struct sched_cache_group *, 1660 sched_cache_group_put(_T)); 1661 1662 #define rcu_deref_sched_cache_grp(tsk) \ 1663 rcu_dereference_check((tsk)->sched_cache_grp, (tsk) == current) 1664 1665 static struct sched_cache_group *sched_cache_replace_grp(struct task_struct *p, 1666 struct sched_cache_group *new) 1667 { 1668 struct sched_cache_group *old; 1669 1670 old = rcu_deref_sched_cache_grp(p); 1671 rcu_assign_pointer(p->sched_cache_grp, new); 1672 1673 return old; 1674 } 1675 1676 struct sched_cache_group *sched_cache_group_get(struct sched_cache_group *grp) 1677 { 1678 /* 1679 * refcount_inc_not_zero() is the acquire primitive for lockless 1680 * (RCU) lookups; plain refcount_inc() would scribble the count if 1681 * it already reached zero. Return NULL in that case. 1682 */ 1683 if (grp && !refcount_inc_not_zero(&grp->refcnt)) 1684 grp = NULL; 1685 1686 return grp; 1687 } 1688 1689 struct sched_cache_group *task_cache_group_get(struct task_struct *p) 1690 { 1691 guard(rcu)(); 1692 return sched_cache_group_get(rcu_dereference(p->sched_cache_grp)); 1693 } 1694 1695 void sched_cache_fork(struct task_struct *p) 1696 { 1697 /* 1698 * The child takes its own reference on the mm's cache group, separate 1699 * from the reference held by the mm. @p is not yet visible to readers, 1700 * so a plain initializing store is enough. 1701 */ 1702 RCU_INIT_POINTER(p->sched_cache_grp, 1703 sched_cache_group_get(p->mm->sched_cache_grp)); 1704 } 1705 1706 void sched_cache_fork_cleanup(struct task_struct *p) 1707 { 1708 /* 1709 * A fork that fails after sched_cache_fork() never reaches exit_mm(), 1710 * so drop the reference here. @p never became visible, so there are no 1711 * concurrent readers and the reference we hold keeps the group alive. 1712 */ 1713 sched_cache_group_put(rcu_access_pointer(p->sched_cache_grp)); 1714 RCU_INIT_POINTER(p->sched_cache_grp, NULL); 1715 } 1716 1717 void sched_cache_exec_mmap(struct task_struct *p, struct mm_struct *mm) 1718 { 1719 struct sched_cache_group *old; 1720 1721 /* 1722 * Acquire the new reference before publishing the pointer, then drop 1723 * the old one. @p is current and the only writer of its own pointer. 1724 */ 1725 old = sched_cache_replace_grp(p, sched_cache_group_get(mm->sched_cache_grp)); 1726 sched_cache_group_put(old); 1727 } 1728 1729 void sched_cache_exit_mm(struct task_struct *p) 1730 { 1731 struct sched_cache_group *grp = sched_cache_replace_grp(p, NULL); 1732 1733 #ifdef CONFIG_NUMA_BALANCING 1734 /* 1735 * Subtract this task's footprint from the group before dropping the 1736 * reference, so the group footprint converges as its threads exit. 1737 * Unlocked for performance; clamp to avoid underflow. 1738 */ 1739 if (grp && p->total_numa_faults) { 1740 unsigned long fp = READ_ONCE(grp->footprint); 1741 unsigned long sub = min(fp, p->total_numa_faults); 1742 1743 WRITE_ONCE(grp->footprint, fp - sub); 1744 } 1745 #endif 1746 sched_cache_group_put(grp); 1747 } 1748 1749 void mm_destroy_sched(struct mm_struct *mm) 1750 { 1751 sched_cache_group_put(mm->sched_cache_grp); 1752 mm->sched_cache_grp = NULL; 1753 } 1754 1755 /* because why would C be fully specified */ 1756 static __always_inline void __shr_u64(u64 *val, unsigned int n) 1757 { 1758 if (n >= 64) { 1759 *val = 0; 1760 return; 1761 } 1762 *val >>= n; 1763 } 1764 1765 static inline void __update_mm_sched(struct rq *rq, 1766 struct sched_cache_time *pcpu_sched) 1767 { 1768 lockdep_assert_held(&rq->cpu_epoch_lock); 1769 1770 unsigned int period = max(READ_ONCE(llc_epoch_period), 1U); 1771 unsigned long n, now = jiffies; 1772 long delta = now - rq->cpu_epoch_next; 1773 1774 if (delta > 0) { 1775 n = (delta + period - 1) / period; 1776 rq->cpu_epoch += n; 1777 rq->cpu_epoch_next += n * period; 1778 __shr_u64(&rq->cpu_runtime, n); 1779 } 1780 1781 n = rq->cpu_epoch - pcpu_sched->epoch; 1782 if (n) { 1783 pcpu_sched->epoch += n; 1784 __shr_u64(&pcpu_sched->runtime, n); 1785 } 1786 } 1787 1788 static unsigned long fraction_mm_sched(struct rq *rq, 1789 struct sched_cache_time *pcpu_sched) 1790 { 1791 guard(raw_spinlock_irqsave)(&rq->cpu_epoch_lock); 1792 1793 __update_mm_sched(rq, pcpu_sched); 1794 1795 /* 1796 * Runtime is a geometric series (r=0.5) and as such will sum to twice 1797 * the accumulation period, this means the multiplcation here should 1798 * not overflow. 1799 */ 1800 return div64_u64(NICE_0_LOAD * pcpu_sched->runtime, rq->cpu_runtime + 1); 1801 } 1802 1803 static int get_pref_llc(struct task_struct *p, struct sched_cache_group *grp) 1804 { 1805 int mm_sched_llc = -1, mm_sched_cpu; 1806 1807 if (!grp) 1808 return -1; 1809 1810 mm_sched_cpu = READ_ONCE(grp->cpu); 1811 if (mm_sched_cpu != -1) { 1812 mm_sched_llc = llc_id(mm_sched_cpu); 1813 1814 #ifdef CONFIG_NUMA_BALANCING 1815 /* 1816 * Don't assign preferred LLC if it 1817 * conflicts with NUMA balancing. 1818 * This can happen when sched_setnuma() gets 1819 * called, however it is not much of an issue 1820 * because we expect account_mm_sched() to get 1821 * called fairly regularly -- at a higher rate 1822 * than sched_setnuma() at least -- and thus the 1823 * conflict only exists for a short period of time. 1824 */ 1825 if (static_branch_likely(&sched_numa_balancing) && 1826 p->numa_preferred_nid >= 0 && 1827 cpu_to_node(mm_sched_cpu) != p->numa_preferred_nid) 1828 mm_sched_llc = -1; 1829 #endif 1830 } 1831 1832 return mm_sched_llc; 1833 } 1834 1835 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p); 1836 1837 static inline 1838 void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec) 1839 { 1840 struct sched_cache_group *grp = rcu_dereference_all(p->sched_cache_grp); 1841 struct sched_cache_time *pcpu_sched; 1842 int mm_sched_llc = -1; 1843 unsigned long epoch; 1844 1845 if (!sched_cache_enabled()) 1846 return; 1847 1848 if (p->sched_class != &fair_sched_class) 1849 return; 1850 /* 1851 * init_task, kthreads and user thread created 1852 * by user_mode_thread() don't have a cache group. 1853 * In theory a kernel thread does not have any valid 1854 * cache group, because sched_cache_fork() is not 1855 * invoked for a kernel thread - !grp should gate the 1856 * kernel thread. Use the PF_KTHREAD check explicitly 1857 * here for safety reasons, to guard against future 1858 * modifications and to pair with task_tick_cache(). 1859 */ 1860 if (p->flags & PF_KTHREAD || !grp || !grp->pcpu_sched) 1861 return; 1862 1863 pcpu_sched = per_cpu_ptr(grp->pcpu_sched, cpu_of(rq)); 1864 1865 scoped_guard (raw_spinlock, &rq->cpu_epoch_lock) { 1866 __update_mm_sched(rq, pcpu_sched); 1867 pcpu_sched->runtime += delta_exec; 1868 rq->cpu_runtime += delta_exec; 1869 epoch = rq->cpu_epoch; 1870 } 1871 1872 /* 1873 * If this process hasn't hit task_cache_work() for a while invalidate 1874 * its preferred state. 1875 */ 1876 if ((long)(epoch - READ_ONCE(grp->epoch)) > llc_epoch_affinity_timeout || 1877 invalid_llc_nr(grp, p, cpu_of(rq)) || 1878 exceed_llc_capacity(grp, cpu_of(rq))) { 1879 if (READ_ONCE(grp->cpu) != -1) 1880 WRITE_ONCE(grp->cpu, -1); 1881 } 1882 1883 mm_sched_llc = get_pref_llc(p, grp); 1884 1885 /* task not on rq accounted later in account_entity_enqueue() */ 1886 if (task_running_on_cpu(rq->cpu, p) && 1887 READ_ONCE(p->preferred_llc) != mm_sched_llc) { 1888 account_llc_dequeue(rq, p); 1889 WRITE_ONCE(p->preferred_llc, mm_sched_llc); 1890 account_llc_enqueue(rq, p); 1891 } 1892 } 1893 1894 static void task_tick_cache(struct rq *rq, struct task_struct *p) 1895 { 1896 struct sched_cache_group *grp = rcu_dereference_all(p->sched_cache_grp); 1897 struct callback_head *work = &p->cache_work; 1898 unsigned long epoch; 1899 1900 if (!sched_cache_enabled()) 1901 return; 1902 1903 if (!grp || p->flags & PF_KTHREAD || 1904 !grp->pcpu_sched) 1905 return; 1906 1907 epoch = rq->cpu_epoch; 1908 /* avoid moving backwards */ 1909 if (time_after_eq(grp->epoch, epoch)) 1910 return; 1911 1912 guard(raw_spinlock)(&grp->lock); 1913 1914 if (work->next == work) { 1915 task_work_add(p, work, TWA_RESUME); 1916 WRITE_ONCE(grp->epoch, epoch); 1917 } 1918 } 1919 1920 static void get_scan_cpumasks(cpumask_var_t cpus, struct task_struct *p, 1921 struct sched_cache_group *grp) 1922 { 1923 #ifdef CONFIG_NUMA_BALANCING 1924 int cpu, curr_cpu, nid, pref_nid; 1925 1926 if (!static_branch_likely(&sched_numa_balancing)) 1927 goto out; 1928 1929 cpu = READ_ONCE(grp->cpu); 1930 if (cpu != -1) 1931 nid = cpu_to_node(cpu); 1932 curr_cpu = task_cpu(p); 1933 1934 /* 1935 * Scanning in the preferred NUMA node is ideal. However, the NUMA 1936 * preferred node is per-task rather than per-process. It is possible 1937 * for different threads of the process to have distinct preferred 1938 * nodes; consequently, the process-wide preferred LLC may bounce 1939 * between different nodes. As a workaround, maintain the scan 1940 * CPU mask to also cover the process's current preferred LLC and the 1941 * current running node to mitigate the bouncing risk. 1942 * TBD: numa_group should be considered during task aggregation. 1943 */ 1944 pref_nid = p->numa_preferred_nid; 1945 /* honor the task's preferred node */ 1946 if (pref_nid == NUMA_NO_NODE) 1947 goto out; 1948 1949 cpumask_or(cpus, cpus, cpumask_of_node(pref_nid)); 1950 1951 /* honor the task's preferred LLC CPU */ 1952 if (cpu != -1 && !cpumask_test_cpu(cpu, cpus) && nid != NUMA_NO_NODE) 1953 cpumask_or(cpus, cpus, cpumask_of_node(nid)); 1954 1955 /* make sure the task's current running node is included */ 1956 if (!cpumask_test_cpu(curr_cpu, cpus)) 1957 cpumask_or(cpus, cpus, cpumask_of_node(cpu_to_node(curr_cpu))); 1958 1959 return; 1960 1961 out: 1962 #endif 1963 cpumask_copy(cpus, cpu_online_mask); 1964 } 1965 1966 static inline void update_avg_scale(u64 *avg, u64 sample) 1967 { 1968 int factor = per_cpu(sd_llc_size, raw_smp_processor_id()); 1969 s64 diff = sample - *avg; 1970 u32 divisor; 1971 1972 /* 1973 * Scale the divisor based on the number of CPUs contained 1974 * in the LLC. This scaling ensures smaller LLC domains use 1975 * a smaller divisor to achieve more precise sensitivity to 1976 * changes in nr_running, while larger LLC domains are capped 1977 * at a maximum divisor of 8 which is the default smoothing 1978 * factor of EWMA in update_avg(). 1979 */ 1980 divisor = clamp_t(u32, (factor >> 2), 2, 8); 1981 *avg += div64_s64(diff, divisor); 1982 } 1983 1984 static void task_cache_work(struct callback_head *work) 1985 { 1986 struct sched_cache_group *grp __free(sched_cache_group_put) = NULL; 1987 cpumask_var_t cpus __free(free_cpumask_var) = CPUMASK_VAR_NULL; 1988 int cpu, m_a_cpu = -1, nr_running = 0, curr_cpu; 1989 unsigned long next_scan, now = jiffies; 1990 struct task_struct *p = current, *cur; 1991 unsigned long curr_m_a_occ = 0; 1992 unsigned long m_a_occ = 0; 1993 1994 WARN_ON_ONCE(work != &p->cache_work); 1995 1996 work->next = work; 1997 1998 if (p->flags & PF_EXITING) 1999 return; 2000 2001 /* 2002 * A reference makes sure grp is not released by others. The rcu 2003 * lock can not be held till after zalloc_cpumask_var() below, 2004 * because the latter might sleep. 2005 */ 2006 grp = task_cache_group_get(p); 2007 if (!grp) 2008 return; 2009 2010 next_scan = READ_ONCE(grp->next_scan); 2011 if (time_before(now, next_scan)) 2012 return; 2013 2014 /* only 1 thread is allowed to scan */ 2015 if (!try_cmpxchg(&grp->next_scan, &next_scan, 2016 now + max_t(unsigned long, 2017 READ_ONCE(llc_epoch_period), 1))) 2018 return; 2019 2020 curr_cpu = task_cpu(p); 2021 if (invalid_llc_nr(grp, p, curr_cpu) || 2022 exceed_llc_capacity(grp, curr_cpu)) { 2023 if (READ_ONCE(grp->cpu) != -1) 2024 WRITE_ONCE(grp->cpu, -1); 2025 2026 return; 2027 } 2028 2029 if (!zalloc_cpumask_var(&cpus, GFP_KERNEL)) 2030 return; 2031 2032 scoped_guard (cpus_read_lock) { 2033 guard(rcu)(); 2034 2035 get_scan_cpumasks(cpus, p, grp); 2036 2037 for_each_cpu(cpu, cpus) { 2038 /* XXX sched_cluster_active */ 2039 struct sched_domain *sd = rcu_dereference_all(per_cpu(sd_llc, cpu)); 2040 unsigned long occ, m_occ = 0, a_occ = 0; 2041 int m_cpu = -1, i; 2042 2043 if (!sd) 2044 continue; 2045 2046 for_each_cpu(i, sched_domain_span(sd)) { 2047 occ = fraction_mm_sched(cpu_rq(i), 2048 per_cpu_ptr(grp->pcpu_sched, i)); 2049 a_occ += occ; 2050 if (occ > m_occ) { 2051 m_occ = occ; 2052 m_cpu = i; 2053 } 2054 2055 /* 2056 * rcu_access_pointer() is used because the 2057 * pointer is only compared, never dereferenced. 2058 */ 2059 cur = rcu_dereference_all(cpu_rq(i)->curr); 2060 if (cur && !(cur->flags & (PF_EXITING | PF_KTHREAD)) && 2061 rcu_access_pointer(cur->sched_cache_grp) == grp) 2062 nr_running++; 2063 } 2064 2065 /* 2066 * Compare the accumulated occupancy of each LLC. The 2067 * reason for using accumulated occupancy rather than average 2068 * per CPU occupancy is that it works better in asymmetric LLC 2069 * scenarios. 2070 * For example, if there are 2 threads in a 4CPU LLC and 3 2071 * threads in an 8CPU LLC, it might be better to choose the one 2072 * with 3 threads. However, this would not be the case if the 2073 * occupancy is divided by the number of CPUs in an LLC (i.e., 2074 * if average per CPU occupancy is used). 2075 * Besides, NUMA balancing fault statistics behave similarly: 2076 * the total number of faults per node is compared rather than 2077 * the average number of faults per CPU. This strategy is also 2078 * followed here. 2079 */ 2080 if (a_occ > m_a_occ) { 2081 m_a_occ = a_occ; 2082 m_a_cpu = m_cpu; 2083 } 2084 2085 if (llc_id(cpu) == llc_id(READ_ONCE(grp->cpu))) 2086 curr_m_a_occ = a_occ; 2087 2088 cpumask_andnot(cpus, cpus, sched_domain_span(sd)); 2089 } 2090 } 2091 2092 if (m_a_occ > (2 * curr_m_a_occ)) { 2093 /* 2094 * Avoid switching sched_cache_grp->cpu too fast. 2095 * The reason to choose 2X is because: 2096 * 1. It is better to keep the preferred LLC stable, 2097 * rather than changing it frequently and cause migrations 2098 * 2. 2X means the new preferred LLC has at least 1 more 2099 * busy CPU than the old one(200% vs 100%, eg) 2100 * 3. 2X is chosen based on test results, as it delivers 2101 * the optimal performance gain so far. 2102 */ 2103 WRITE_ONCE(grp->cpu, m_a_cpu); 2104 } 2105 2106 update_avg_scale(&grp->nr_running_avg, nr_running); 2107 } 2108 2109 void init_sched_mm(struct task_struct *p) 2110 { 2111 struct callback_head *work = &p->cache_work; 2112 2113 init_task_work(work, task_cache_work); 2114 work->next = work; 2115 /* 2116 * dup_task_struct() copies the parent's task_struct, including its 2117 * sched_cache_grp, for which the child holds no reference. Clear it 2118 * here - before copy_mm() runs - so the child never carries a 2119 * borrowed pointer that the fork error path would put. 2120 */ 2121 RCU_INIT_POINTER(p->sched_cache_grp, NULL); 2122 /* 2123 * Reset new task's preference to avoid 2124 * polluting account_llc_enqueue(). 2125 */ 2126 p->preferred_llc = -1; 2127 p->pref_llc_queued = 0; 2128 } 2129 2130 #else /* CONFIG_SCHED_CACHE */ 2131 2132 static inline void account_mm_sched(struct rq *rq, struct task_struct *p, 2133 s64 delta_exec) { } 2134 2135 void init_sched_mm(struct task_struct *p) { } 2136 2137 static void task_tick_cache(struct rq *rq, struct task_struct *p) { } 2138 2139 static inline int get_pref_llc(struct task_struct *p, 2140 struct sched_cache_group *grp) 2141 { 2142 return -1; 2143 } 2144 2145 static void account_llc_enqueue(struct rq *rq, struct task_struct *p) {} 2146 2147 static void account_llc_dequeue(struct rq *rq, struct task_struct *p) {} 2148 2149 static void pref_llc_running_inc(struct rq *rq, struct task_struct *p) {} 2150 2151 static void pref_llc_running_dec(struct rq *rq, struct task_struct *p) {} 2152 2153 #endif /* CONFIG_SCHED_CACHE */ 2154 2155 /* 2156 * Used by other classes to account runtime. 2157 */ 2158 s64 update_curr_common(struct rq *rq) 2159 { 2160 return update_se(rq, &rq->donor->se); 2161 } 2162 2163 /* 2164 * Update the current task's runtime statistics. 2165 */ 2166 static void update_curr(struct cfs_rq *cfs_rq) 2167 { 2168 /* 2169 * Note: cfs_rq->curr corresponds to the task picked to 2170 * run (ie: rq->donor.se) which due to proxy-exec may 2171 * not necessarily be the actual task running 2172 * (rq->curr.se). This is easy to confuse! 2173 */ 2174 struct sched_entity *curr = cfs_rq->h_curr; 2175 struct rq *rq = rq_of(cfs_rq); 2176 s64 delta_exec; 2177 bool resched; 2178 2179 if (unlikely(!curr)) 2180 return; 2181 2182 delta_exec = update_se(rq, curr); 2183 if (unlikely(delta_exec <= 0)) 2184 return; 2185 2186 account_cfs_rq_runtime(cfs_rq, delta_exec); 2187 2188 if (!entity_is_task(curr)) 2189 return; 2190 2191 cfs_rq = &rq->cfs; 2192 2193 curr->vruntime += calc_delta_fair(delta_exec, curr); 2194 resched = update_deadline(cfs_rq, curr); 2195 2196 /* 2197 * If the fair_server is active, we need to account for the 2198 * fair_server time whether or not the task is running on 2199 * behalf of fair_server or not: 2200 * - If the task is running on behalf of fair_server, we need 2201 * to limit its time based on the assigned runtime. 2202 * - Fair task that runs outside of fair_server should account 2203 * against fair_server such that it can account for this time 2204 * and possibly avoid running this period. 2205 */ 2206 dl_server_update(&rq->fair_server, delta_exec); 2207 2208 if (cfs_rq->h_nr_queued == 1) 2209 return; 2210 2211 if (resched || !protect_slice(curr)) { 2212 resched_curr_lazy(rq); 2213 clear_buddies(cfs_rq, curr); 2214 } 2215 } 2216 2217 static void update_curr_fair(struct rq *rq) 2218 { 2219 struct sched_entity *se = &rq->donor->se; 2220 2221 for_each_sched_entity(se) 2222 update_curr(cfs_rq_of(se)); 2223 } 2224 2225 static inline void 2226 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se) 2227 { 2228 struct sched_statistics *stats; 2229 struct task_struct *p = NULL; 2230 2231 if (!schedstat_enabled()) 2232 return; 2233 2234 stats = __schedstats_from_se(se); 2235 2236 if (entity_is_task(se)) 2237 p = task_of(se); 2238 2239 __update_stats_wait_start(rq_of(cfs_rq), p, stats); 2240 } 2241 2242 static inline void 2243 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se) 2244 { 2245 struct sched_statistics *stats; 2246 struct task_struct *p = NULL; 2247 2248 if (!schedstat_enabled()) 2249 return; 2250 2251 stats = __schedstats_from_se(se); 2252 2253 /* 2254 * When the sched_schedstat changes from 0 to 1, some sched se 2255 * maybe already in the runqueue, the se->statistics.wait_start 2256 * will be 0.So it will let the delta wrong. We need to avoid this 2257 * scenario. 2258 */ 2259 if (unlikely(!schedstat_val(stats->wait_start))) 2260 return; 2261 2262 if (entity_is_task(se)) 2263 p = task_of(se); 2264 2265 __update_stats_wait_end(rq_of(cfs_rq), p, stats); 2266 } 2267 2268 static inline void 2269 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se) 2270 { 2271 struct sched_statistics *stats; 2272 struct task_struct *tsk = NULL; 2273 2274 if (!schedstat_enabled()) 2275 return; 2276 2277 stats = __schedstats_from_se(se); 2278 2279 if (entity_is_task(se)) 2280 tsk = task_of(se); 2281 2282 __update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats); 2283 } 2284 2285 /* 2286 * Task is being enqueued - update stats: 2287 */ 2288 static inline void 2289 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 2290 { 2291 if (!schedstat_enabled()) 2292 return; 2293 2294 /* 2295 * Are we enqueueing a waiting task? (for current tasks 2296 * a dequeue/enqueue event is a NOP) 2297 */ 2298 if (se != cfs_rq->h_curr) 2299 update_stats_wait_start_fair(cfs_rq, se); 2300 2301 if (flags & ENQUEUE_WAKEUP) 2302 update_stats_enqueue_sleeper_fair(cfs_rq, se); 2303 } 2304 2305 static inline void 2306 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 2307 { 2308 2309 if (!schedstat_enabled()) 2310 return; 2311 2312 /* 2313 * Mark the end of the wait period if dequeueing a 2314 * waiting task: 2315 */ 2316 if (se != cfs_rq->h_curr) 2317 update_stats_wait_end_fair(cfs_rq, se); 2318 2319 if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) { 2320 struct task_struct *tsk = task_of(se); 2321 unsigned int state; 2322 2323 /* XXX racy against TTWU */ 2324 state = READ_ONCE(tsk->__state); 2325 if (state & TASK_INTERRUPTIBLE) 2326 __schedstat_set(tsk->stats.sleep_start, 2327 rq_clock(rq_of(cfs_rq))); 2328 if (state & TASK_UNINTERRUPTIBLE) 2329 __schedstat_set(tsk->stats.block_start, 2330 rq_clock(rq_of(cfs_rq))); 2331 } 2332 } 2333 2334 /* 2335 * We are picking a new current task - update its stats: 2336 */ 2337 static inline void 2338 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se) 2339 { 2340 /* 2341 * We are starting a new run period: 2342 */ 2343 se->exec_start = rq_clock_task(rq_of(cfs_rq)); 2344 } 2345 2346 /* Check sched_smt_active before calling this to avoid overheads in fastpaths */ 2347 static inline bool is_core_idle(int cpu) 2348 { 2349 int sibling; 2350 2351 for_each_cpu(sibling, cpu_smt_mask(cpu)) { 2352 if (cpu == sibling) 2353 continue; 2354 2355 if (!idle_cpu(sibling)) 2356 return false; 2357 } 2358 2359 return true; 2360 } 2361 2362 #ifdef CONFIG_NUMA 2363 #define NUMA_IMBALANCE_MIN 2 2364 2365 static inline long 2366 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr) 2367 { 2368 /* 2369 * Allow a NUMA imbalance if busy CPUs is less than the maximum 2370 * threshold. Above this threshold, individual tasks may be contending 2371 * for both memory bandwidth and any shared HT resources. This is an 2372 * approximation as the number of running tasks may not be related to 2373 * the number of busy CPUs due to sched_setaffinity. 2374 */ 2375 if (dst_running > imb_numa_nr) 2376 return imbalance; 2377 2378 /* 2379 * Allow a small imbalance based on a simple pair of communicating 2380 * tasks that remain local when the destination is lightly loaded. 2381 */ 2382 if (imbalance <= NUMA_IMBALANCE_MIN) 2383 return 0; 2384 2385 return imbalance; 2386 } 2387 #endif /* CONFIG_NUMA */ 2388 2389 #ifdef CONFIG_NUMA_BALANCING 2390 /* 2391 * Approximate time to scan a full NUMA task in ms. The task scan period is 2392 * calculated based on the tasks virtual memory size and 2393 * numa_balancing_scan_size. 2394 */ 2395 unsigned int sysctl_numa_balancing_scan_period_min = 1000; 2396 unsigned int sysctl_numa_balancing_scan_period_max = 60000; 2397 2398 /* Portion of address space to scan in MB */ 2399 unsigned int sysctl_numa_balancing_scan_size = 256; 2400 2401 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */ 2402 unsigned int sysctl_numa_balancing_scan_delay = 1000; 2403 2404 /* The page with hint page fault latency < threshold in ms is considered hot */ 2405 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC; 2406 2407 struct numa_group { 2408 refcount_t refcount; 2409 2410 spinlock_t lock; /* nr_tasks, tasks */ 2411 int nr_tasks; 2412 pid_t gid; 2413 int active_nodes; 2414 2415 struct rcu_head rcu; 2416 unsigned long total_faults; 2417 unsigned long max_faults_cpu; 2418 /* 2419 * faults[] array is split into two regions: faults_mem and faults_cpu. 2420 * 2421 * Faults_cpu is used to decide whether memory should move 2422 * towards the CPU. As a consequence, these stats are weighted 2423 * more by CPU use than by memory faults. 2424 */ 2425 unsigned long faults[]; 2426 }; 2427 2428 /* 2429 * For functions that can be called in multiple contexts that permit reading 2430 * ->numa_group (see struct task_struct for locking rules). 2431 */ 2432 static struct numa_group *deref_task_numa_group(struct task_struct *p) 2433 { 2434 return rcu_dereference_check(p->numa_group, p == current || 2435 (lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu))); 2436 } 2437 2438 static struct numa_group *deref_curr_numa_group(struct task_struct *p) 2439 { 2440 return rcu_dereference_protected(p->numa_group, p == current); 2441 } 2442 2443 static inline unsigned long group_faults_priv(struct numa_group *ng); 2444 static inline unsigned long group_faults_shared(struct numa_group *ng); 2445 2446 static unsigned int task_nr_scan_windows(struct task_struct *p) 2447 { 2448 unsigned long rss = 0; 2449 unsigned long nr_scan_pages; 2450 2451 /* 2452 * Calculations based on RSS as non-present and empty pages are skipped 2453 * by the PTE scanner and NUMA hinting faults should be trapped based 2454 * on resident pages 2455 */ 2456 nr_scan_pages = MB_TO_PAGES(sysctl_numa_balancing_scan_size); 2457 rss = get_mm_rss(p->mm); 2458 if (!rss) 2459 rss = nr_scan_pages; 2460 2461 rss = round_up(rss, nr_scan_pages); 2462 return rss / nr_scan_pages; 2463 } 2464 2465 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */ 2466 #define MAX_SCAN_WINDOW 2560 2467 2468 static unsigned int task_scan_min(struct task_struct *p) 2469 { 2470 unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size); 2471 unsigned int scan, floor; 2472 unsigned int windows = 1; 2473 2474 if (scan_size < MAX_SCAN_WINDOW) 2475 windows = MAX_SCAN_WINDOW / scan_size; 2476 floor = 1000 / windows; 2477 2478 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p); 2479 return max_t(unsigned int, floor, scan); 2480 } 2481 2482 static unsigned int task_scan_start(struct task_struct *p) 2483 { 2484 unsigned long smin = task_scan_min(p); 2485 unsigned long period = smin; 2486 struct numa_group *ng; 2487 2488 /* Scale the maximum scan period with the amount of shared memory. */ 2489 rcu_read_lock(); 2490 ng = rcu_dereference_all(p->numa_group); 2491 if (ng) { 2492 unsigned long shared = group_faults_shared(ng); 2493 unsigned long private = group_faults_priv(ng); 2494 2495 period *= refcount_read(&ng->refcount); 2496 period *= shared + 1; 2497 period /= private + shared + 1; 2498 } 2499 rcu_read_unlock(); 2500 2501 return max(smin, period); 2502 } 2503 2504 static unsigned int task_scan_max(struct task_struct *p) 2505 { 2506 unsigned long smin = task_scan_min(p); 2507 unsigned long smax; 2508 struct numa_group *ng; 2509 2510 /* Watch for min being lower than max due to floor calculations */ 2511 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p); 2512 2513 /* Scale the maximum scan period with the amount of shared memory. */ 2514 ng = deref_curr_numa_group(p); 2515 if (ng) { 2516 unsigned long shared = group_faults_shared(ng); 2517 unsigned long private = group_faults_priv(ng); 2518 unsigned long period = smax; 2519 2520 period *= refcount_read(&ng->refcount); 2521 period *= shared + 1; 2522 period /= private + shared + 1; 2523 2524 smax = max(smax, period); 2525 } 2526 2527 return max(smin, smax); 2528 } 2529 2530 static void account_numa_enqueue(struct rq *rq, struct task_struct *p) 2531 { 2532 rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE); 2533 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p)); 2534 } 2535 2536 static void account_numa_dequeue(struct rq *rq, struct task_struct *p) 2537 { 2538 rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE); 2539 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p)); 2540 } 2541 2542 /* Shared or private faults. */ 2543 #define NR_NUMA_HINT_FAULT_TYPES 2 2544 2545 /* Memory and CPU locality */ 2546 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2) 2547 2548 /* Averaged statistics, and temporary buffers. */ 2549 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2) 2550 2551 pid_t task_numa_group_id(struct task_struct *p) 2552 { 2553 struct numa_group *ng; 2554 pid_t gid = 0; 2555 2556 rcu_read_lock(); 2557 ng = rcu_dereference_all(p->numa_group); 2558 if (ng) 2559 gid = ng->gid; 2560 rcu_read_unlock(); 2561 2562 return gid; 2563 } 2564 2565 /* 2566 * The averaged statistics, shared & private, memory & CPU, 2567 * occupy the first half of the array. The second half of the 2568 * array is for current counters, which are averaged into the 2569 * first set by task_numa_placement. 2570 */ 2571 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv) 2572 { 2573 return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv; 2574 } 2575 2576 static inline unsigned long task_faults(struct task_struct *p, int nid) 2577 { 2578 if (!p->numa_faults) 2579 return 0; 2580 2581 return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] + 2582 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)]; 2583 } 2584 2585 static inline unsigned long group_faults(struct task_struct *p, int nid) 2586 { 2587 struct numa_group *ng = deref_task_numa_group(p); 2588 2589 if (!ng) 2590 return 0; 2591 2592 return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] + 2593 ng->faults[task_faults_idx(NUMA_MEM, nid, 1)]; 2594 } 2595 2596 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid) 2597 { 2598 return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] + 2599 group->faults[task_faults_idx(NUMA_CPU, nid, 1)]; 2600 } 2601 2602 static inline unsigned long group_faults_priv(struct numa_group *ng) 2603 { 2604 unsigned long faults = 0; 2605 int node; 2606 2607 for_each_online_node(node) { 2608 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)]; 2609 } 2610 2611 return faults; 2612 } 2613 2614 static inline unsigned long group_faults_shared(struct numa_group *ng) 2615 { 2616 unsigned long faults = 0; 2617 int node; 2618 2619 for_each_online_node(node) { 2620 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)]; 2621 } 2622 2623 return faults; 2624 } 2625 2626 /* 2627 * A node triggering more than 1/3 as many NUMA faults as the maximum is 2628 * considered part of a numa group's pseudo-interleaving set. Migrations 2629 * between these nodes are slowed down, to allow things to settle down. 2630 */ 2631 #define ACTIVE_NODE_FRACTION 3 2632 2633 static bool numa_is_active_node(int nid, struct numa_group *ng) 2634 { 2635 return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu; 2636 } 2637 2638 /* Handle placement on systems where not all nodes are directly connected. */ 2639 static unsigned long score_nearby_nodes(struct task_struct *p, int nid, 2640 int lim_dist, bool task) 2641 { 2642 unsigned long score = 0; 2643 int node, max_dist; 2644 2645 /* 2646 * All nodes are directly connected, and the same distance 2647 * from each other. No need for fancy placement algorithms. 2648 */ 2649 if (sched_numa_topology_type == NUMA_DIRECT) 2650 return 0; 2651 2652 /* sched_max_numa_distance may be changed in parallel. */ 2653 max_dist = READ_ONCE(sched_max_numa_distance); 2654 /* 2655 * This code is called for each node, introducing N^2 complexity, 2656 * which should be OK given the number of nodes rarely exceeds 8. 2657 */ 2658 for_each_online_node(node) { 2659 unsigned long faults; 2660 int dist = node_distance(nid, node); 2661 2662 /* 2663 * The furthest away nodes in the system are not interesting 2664 * for placement; nid was already counted. 2665 */ 2666 if (dist >= max_dist || node == nid) 2667 continue; 2668 2669 /* 2670 * On systems with a backplane NUMA topology, compare groups 2671 * of nodes, and move tasks towards the group with the most 2672 * memory accesses. When comparing two nodes at distance 2673 * "hoplimit", only nodes closer by than "hoplimit" are part 2674 * of each group. Skip other nodes. 2675 */ 2676 if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist) 2677 continue; 2678 2679 /* Add up the faults from nearby nodes. */ 2680 if (task) 2681 faults = task_faults(p, node); 2682 else 2683 faults = group_faults(p, node); 2684 2685 /* 2686 * On systems with a glueless mesh NUMA topology, there are 2687 * no fixed "groups of nodes". Instead, nodes that are not 2688 * directly connected bounce traffic through intermediate 2689 * nodes; a numa_group can occupy any set of nodes. 2690 * The further away a node is, the less the faults count. 2691 * This seems to result in good task placement. 2692 */ 2693 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) { 2694 faults *= (max_dist - dist); 2695 faults /= (max_dist - LOCAL_DISTANCE); 2696 } 2697 2698 score += faults; 2699 } 2700 2701 return score; 2702 } 2703 2704 /* 2705 * These return the fraction of accesses done by a particular task, or 2706 * task group, on a particular numa node. The group weight is given a 2707 * larger multiplier, in order to group tasks together that are almost 2708 * evenly spread out between numa nodes. 2709 */ 2710 static inline unsigned long task_weight(struct task_struct *p, int nid, 2711 int dist) 2712 { 2713 unsigned long faults, total_faults; 2714 2715 if (!p->numa_faults) 2716 return 0; 2717 2718 total_faults = p->total_numa_faults; 2719 2720 if (!total_faults) 2721 return 0; 2722 2723 faults = task_faults(p, nid); 2724 faults += score_nearby_nodes(p, nid, dist, true); 2725 2726 return 1000 * faults / total_faults; 2727 } 2728 2729 static inline unsigned long group_weight(struct task_struct *p, int nid, 2730 int dist) 2731 { 2732 struct numa_group *ng = deref_task_numa_group(p); 2733 unsigned long faults, total_faults; 2734 2735 if (!ng) 2736 return 0; 2737 2738 total_faults = ng->total_faults; 2739 2740 if (!total_faults) 2741 return 0; 2742 2743 faults = group_faults(p, nid); 2744 faults += score_nearby_nodes(p, nid, dist, false); 2745 2746 return 1000 * faults / total_faults; 2747 } 2748 2749 /* 2750 * If memory tiering mode is enabled, cpupid of slow memory page is 2751 * used to record scan time instead of CPU and PID. When tiering mode 2752 * is disabled at run time, the scan time (in cpupid) will be 2753 * interpreted as CPU and PID. So CPU needs to be checked to avoid to 2754 * access out of array bound. 2755 */ 2756 static inline bool cpupid_valid(int cpupid) 2757 { 2758 return cpupid_to_cpu(cpupid) < nr_cpu_ids; 2759 } 2760 2761 /* 2762 * For memory tiering mode, if there are enough free pages (more than 2763 * enough watermark defined here) in fast memory node, to take full 2764 * advantage of fast memory capacity, all recently accessed slow 2765 * memory pages will be migrated to fast memory node without 2766 * considering hot threshold. 2767 */ 2768 static bool pgdat_free_space_enough(struct pglist_data *pgdat) 2769 { 2770 int z; 2771 unsigned long enough_wmark; 2772 2773 enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT, 2774 pgdat->node_present_pages >> 4); 2775 for (z = pgdat->nr_zones - 1; z >= 0; z--) { 2776 struct zone *zone = pgdat->node_zones + z; 2777 2778 if (!populated_zone(zone)) 2779 continue; 2780 2781 if (zone_watermark_ok(zone, 0, 2782 promo_wmark_pages(zone) + enough_wmark, 2783 ZONE_MOVABLE, 0)) 2784 return true; 2785 } 2786 return false; 2787 } 2788 2789 /* 2790 * For memory tiering mode, when page tables are scanned, the scan 2791 * time will be recorded in struct page in addition to make page 2792 * PROT_NONE for slow memory page. So when the page is accessed, in 2793 * hint page fault handler, the hint page fault latency is calculated 2794 * via, 2795 * 2796 * hint page fault latency = hint page fault time - scan time 2797 * 2798 * The smaller the hint page fault latency, the higher the possibility 2799 * for the page to be hot. 2800 */ 2801 static int numa_hint_fault_latency(struct folio *folio) 2802 { 2803 int last_time, time; 2804 2805 time = jiffies_to_msecs(jiffies); 2806 last_time = folio_xchg_access_time(folio, time); 2807 2808 return (time - last_time) & PAGE_ACCESS_TIME_MASK; 2809 } 2810 2811 /* 2812 * For memory tiering mode, too high promotion/demotion throughput may 2813 * hurt application latency. So we provide a mechanism to rate limit 2814 * the number of pages that are tried to be promoted. 2815 */ 2816 static bool numa_promotion_rate_limit(struct pglist_data *pgdat, 2817 unsigned long rate_limit, int nr) 2818 { 2819 unsigned long nr_cand; 2820 unsigned int now, start; 2821 2822 now = jiffies_to_msecs(jiffies); 2823 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr); 2824 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE); 2825 start = pgdat->nbp_rl_start; 2826 if (now - start > MSEC_PER_SEC && 2827 cmpxchg(&pgdat->nbp_rl_start, start, now) == start) 2828 pgdat->nbp_rl_nr_cand = nr_cand; 2829 if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit) 2830 return true; 2831 return false; 2832 } 2833 2834 #define NUMA_MIGRATION_ADJUST_STEPS 16 2835 2836 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat, 2837 unsigned long rate_limit, 2838 unsigned int ref_th) 2839 { 2840 unsigned int now, start, th_period, unit_th, th; 2841 unsigned long nr_cand, ref_cand, diff_cand; 2842 2843 now = jiffies_to_msecs(jiffies); 2844 th_period = sysctl_numa_balancing_scan_period_max; 2845 start = pgdat->nbp_th_start; 2846 if (now - start > th_period && 2847 cmpxchg(&pgdat->nbp_th_start, start, now) == start) { 2848 ref_cand = rate_limit * 2849 sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC; 2850 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE); 2851 diff_cand = nr_cand - pgdat->nbp_th_nr_cand; 2852 unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS; 2853 th = pgdat->nbp_threshold ? : ref_th; 2854 if (diff_cand > ref_cand * 11 / 10) 2855 th = max(th - unit_th, unit_th); 2856 else if (diff_cand < ref_cand * 9 / 10) 2857 th = min(th + unit_th, ref_th * 2); 2858 pgdat->nbp_th_nr_cand = nr_cand; 2859 pgdat->nbp_threshold = th; 2860 } 2861 } 2862 2863 bool should_numa_migrate_memory(struct task_struct *p, struct folio *folio, 2864 int src_nid, int dst_cpu) 2865 { 2866 struct numa_group *ng = deref_curr_numa_group(p); 2867 int dst_nid = cpu_to_node(dst_cpu); 2868 int last_cpupid, this_cpupid; 2869 2870 /* 2871 * Cannot migrate to memoryless nodes. 2872 */ 2873 if (!node_state(dst_nid, N_MEMORY)) 2874 return false; 2875 2876 /* 2877 * The pages in slow memory node should be migrated according 2878 * to hot/cold instead of private/shared. 2879 */ 2880 if (folio_use_access_time(folio)) { 2881 struct pglist_data *pgdat; 2882 unsigned long rate_limit; 2883 unsigned int latency, th, def_th; 2884 long nr = folio_nr_pages(folio); 2885 2886 pgdat = NODE_DATA(dst_nid); 2887 if (pgdat_free_space_enough(pgdat)) { 2888 /* workload changed, reset hot threshold */ 2889 pgdat->nbp_threshold = 0; 2890 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE_NRL, nr); 2891 return true; 2892 } 2893 2894 def_th = sysctl_numa_balancing_hot_threshold; 2895 rate_limit = MB_TO_PAGES(sysctl_numa_balancing_promote_rate_limit); 2896 numa_promotion_adjust_threshold(pgdat, rate_limit, def_th); 2897 2898 th = pgdat->nbp_threshold ? : def_th; 2899 latency = numa_hint_fault_latency(folio); 2900 if (latency >= th) 2901 return false; 2902 2903 return !numa_promotion_rate_limit(pgdat, rate_limit, nr); 2904 } 2905 2906 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid); 2907 last_cpupid = folio_xchg_last_cpupid(folio, this_cpupid); 2908 2909 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) && 2910 !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid)) 2911 return false; 2912 2913 /* 2914 * Allow first faults or private faults to migrate immediately early in 2915 * the lifetime of a task. The magic number 4 is based on waiting for 2916 * two full passes of the "multi-stage node selection" test that is 2917 * executed below. 2918 */ 2919 if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) && 2920 (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid))) 2921 return true; 2922 2923 /* 2924 * Multi-stage node selection is used in conjunction with a periodic 2925 * migration fault to build a temporal task<->page relation. By using 2926 * a two-stage filter we remove short/unlikely relations. 2927 * 2928 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate 2929 * a task's usage of a particular page (n_p) per total usage of this 2930 * page (n_t) (in a given time-span) to a probability. 2931 * 2932 * Our periodic faults will sample this probability and getting the 2933 * same result twice in a row, given these samples are fully 2934 * independent, is then given by P(n)^2, provided our sample period 2935 * is sufficiently short compared to the usage pattern. 2936 * 2937 * This quadric squishes small probabilities, making it less likely we 2938 * act on an unlikely task<->page relation. 2939 */ 2940 if (!cpupid_pid_unset(last_cpupid) && 2941 cpupid_to_nid(last_cpupid) != dst_nid) 2942 return false; 2943 2944 /* Always allow migrate on private faults */ 2945 if (cpupid_match_pid(p, last_cpupid)) 2946 return true; 2947 2948 /* A shared fault, but p->numa_group has not been set up yet. */ 2949 if (!ng) 2950 return true; 2951 2952 /* 2953 * Destination node is much more heavily used than the source 2954 * node? Allow migration. 2955 */ 2956 if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) * 2957 ACTIVE_NODE_FRACTION) 2958 return true; 2959 2960 /* 2961 * Distribute memory according to CPU & memory use on each node, 2962 * with 3/4 hysteresis to avoid unnecessary memory migrations: 2963 * 2964 * faults_cpu(dst) 3 faults_cpu(src) 2965 * --------------- * - > --------------- 2966 * faults_mem(dst) 4 faults_mem(src) 2967 */ 2968 return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 > 2969 group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4; 2970 } 2971 2972 /* 2973 * 'numa_type' describes the node at the moment of load balancing. 2974 */ 2975 enum numa_type { 2976 /* The node has spare capacity that can be used to run more tasks. */ 2977 node_has_spare = 0, 2978 /* 2979 * The node is fully used and the tasks don't compete for more CPU 2980 * cycles. Nevertheless, some tasks might wait before running. 2981 */ 2982 node_fully_busy, 2983 /* 2984 * The node is overloaded and can't provide expected CPU cycles to all 2985 * tasks. 2986 */ 2987 node_overloaded 2988 }; 2989 2990 /* Cached statistics for all CPUs within a node */ 2991 struct numa_stats { 2992 unsigned long load; 2993 unsigned long runnable; 2994 unsigned long util; 2995 /* Total compute capacity of CPUs on a node */ 2996 unsigned long compute_capacity; 2997 unsigned int nr_running; 2998 unsigned int weight; 2999 enum numa_type node_type; 3000 int idle_cpu; 3001 }; 3002 3003 struct task_numa_env { 3004 struct task_struct *p; 3005 3006 int src_cpu, src_nid; 3007 int dst_cpu, dst_nid; 3008 int imb_numa_nr; 3009 3010 struct numa_stats src_stats, dst_stats; 3011 3012 int imbalance_pct; 3013 int dist; 3014 3015 struct task_struct *best_task; 3016 long best_imp; 3017 int best_cpu; 3018 }; 3019 3020 static unsigned long cpu_load(struct rq *rq); 3021 static unsigned long cpu_runnable(struct rq *rq); 3022 3023 static inline enum 3024 numa_type numa_classify(unsigned int imbalance_pct, 3025 struct numa_stats *ns) 3026 { 3027 if ((ns->nr_running > ns->weight) && 3028 (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) || 3029 ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100)))) 3030 return node_overloaded; 3031 3032 if ((ns->nr_running < ns->weight) || 3033 (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) && 3034 ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100)))) 3035 return node_has_spare; 3036 3037 return node_fully_busy; 3038 } 3039 3040 /* Forward declarations of select_idle_sibling helpers */ 3041 static inline bool test_idle_cores(int cpu); 3042 static inline int numa_idle_core(int idle_core, int cpu) 3043 { 3044 if (!sched_smt_active() || 3045 idle_core >= 0 || !test_idle_cores(cpu)) 3046 return idle_core; 3047 3048 /* 3049 * Prefer cores instead of packing HT siblings 3050 * and triggering future load balancing. 3051 */ 3052 if (is_core_idle(cpu)) 3053 idle_core = cpu; 3054 3055 return idle_core; 3056 } 3057 3058 /* 3059 * Gather all necessary information to make NUMA balancing placement 3060 * decisions that are compatible with standard load balancer. This 3061 * borrows code and logic from update_sg_lb_stats but sharing a 3062 * common implementation is impractical. 3063 */ 3064 static void update_numa_stats(struct task_numa_env *env, 3065 struct numa_stats *ns, int nid, 3066 bool find_idle) 3067 { 3068 int cpu, idle_core = -1; 3069 3070 memset(ns, 0, sizeof(*ns)); 3071 ns->idle_cpu = -1; 3072 3073 rcu_read_lock(); 3074 for_each_cpu(cpu, cpumask_of_node(nid)) { 3075 struct rq *rq = cpu_rq(cpu); 3076 3077 ns->load += cpu_load(rq); 3078 ns->runnable += cpu_runnable(rq); 3079 ns->util += cpu_util_cfs(cpu); 3080 ns->nr_running += rq->cfs.h_nr_runnable; 3081 ns->compute_capacity += capacity_of(cpu); 3082 3083 if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) { 3084 if (READ_ONCE(rq->numa_migrate_on) || 3085 !cpumask_test_cpu(cpu, env->p->cpus_ptr)) 3086 continue; 3087 3088 if (ns->idle_cpu == -1) 3089 ns->idle_cpu = cpu; 3090 3091 idle_core = numa_idle_core(idle_core, cpu); 3092 } 3093 } 3094 rcu_read_unlock(); 3095 3096 ns->weight = cpumask_weight(cpumask_of_node(nid)); 3097 3098 ns->node_type = numa_classify(env->imbalance_pct, ns); 3099 3100 if (idle_core >= 0) 3101 ns->idle_cpu = idle_core; 3102 } 3103 3104 static void task_numa_assign(struct task_numa_env *env, 3105 struct task_struct *p, long imp) 3106 { 3107 struct rq *rq = cpu_rq(env->dst_cpu); 3108 3109 /* Check if run-queue part of active NUMA balance. */ 3110 if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) { 3111 int cpu; 3112 int start = env->dst_cpu; 3113 3114 /* Find alternative idle CPU. */ 3115 for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) { 3116 if (cpu == env->best_cpu || !idle_cpu(cpu) || 3117 !cpumask_test_cpu(cpu, env->p->cpus_ptr)) { 3118 continue; 3119 } 3120 3121 env->dst_cpu = cpu; 3122 rq = cpu_rq(env->dst_cpu); 3123 if (!xchg(&rq->numa_migrate_on, 1)) 3124 goto assign; 3125 } 3126 3127 /* Failed to find an alternative idle CPU */ 3128 return; 3129 } 3130 3131 assign: 3132 /* 3133 * Clear previous best_cpu/rq numa-migrate flag, since task now 3134 * found a better CPU to move/swap. 3135 */ 3136 if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) { 3137 rq = cpu_rq(env->best_cpu); 3138 WRITE_ONCE(rq->numa_migrate_on, 0); 3139 } 3140 3141 if (env->best_task) 3142 put_task_struct(env->best_task); 3143 if (p) 3144 get_task_struct(p); 3145 3146 env->best_task = p; 3147 env->best_imp = imp; 3148 env->best_cpu = env->dst_cpu; 3149 } 3150 3151 static bool load_too_imbalanced(long src_load, long dst_load, 3152 struct task_numa_env *env) 3153 { 3154 long imb, old_imb; 3155 long orig_src_load, orig_dst_load; 3156 long src_capacity, dst_capacity; 3157 3158 /* 3159 * The load is corrected for the CPU capacity available on each node. 3160 * 3161 * src_load dst_load 3162 * ------------ vs --------- 3163 * src_capacity dst_capacity 3164 */ 3165 src_capacity = env->src_stats.compute_capacity; 3166 dst_capacity = env->dst_stats.compute_capacity; 3167 3168 imb = abs(dst_load * src_capacity - src_load * dst_capacity); 3169 3170 orig_src_load = env->src_stats.load; 3171 orig_dst_load = env->dst_stats.load; 3172 3173 old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity); 3174 3175 /* Would this change make things worse? */ 3176 return (imb > old_imb); 3177 } 3178 3179 /* 3180 * Maximum NUMA importance can be 1998 (2*999); 3181 * SMALLIMP @ 30 would be close to 1998/64. 3182 * Used to deter task migration. 3183 */ 3184 #define SMALLIMP 30 3185 3186 /* 3187 * This checks if the overall compute and NUMA accesses of the system would 3188 * be improved if the source tasks was migrated to the target dst_cpu taking 3189 * into account that it might be best if task running on the dst_cpu should 3190 * be exchanged with the source task 3191 */ 3192 static bool task_numa_compare(struct task_numa_env *env, 3193 long taskimp, long groupimp, bool maymove) 3194 { 3195 struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p); 3196 struct rq *dst_rq = cpu_rq(env->dst_cpu); 3197 long imp = p_ng ? groupimp : taskimp; 3198 struct task_struct *cur; 3199 long src_load, dst_load; 3200 int dist = env->dist; 3201 long moveimp = imp; 3202 long load; 3203 bool stopsearch = false; 3204 3205 if (READ_ONCE(dst_rq->numa_migrate_on)) 3206 return false; 3207 3208 rcu_read_lock(); 3209 cur = rcu_dereference_all(dst_rq->curr); 3210 if (cur && ((cur->flags & (PF_EXITING | PF_KTHREAD)) || 3211 !cur->mm)) 3212 cur = NULL; 3213 3214 /* 3215 * Because we have preemption enabled we can get migrated around and 3216 * end try selecting ourselves (current == env->p) as a swap candidate. 3217 */ 3218 if (cur == env->p) { 3219 stopsearch = true; 3220 goto unlock; 3221 } 3222 3223 if (!cur) { 3224 if (maymove && moveimp >= env->best_imp) 3225 goto assign; 3226 else 3227 goto unlock; 3228 } 3229 3230 /* Skip this swap candidate if cannot move to the source cpu. */ 3231 if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr)) 3232 goto unlock; 3233 3234 /* 3235 * Skip this swap candidate if it is not moving to its preferred 3236 * node and the best task is. 3237 */ 3238 if (env->best_task && 3239 env->best_task->numa_preferred_nid == env->src_nid && 3240 cur->numa_preferred_nid != env->src_nid) { 3241 goto unlock; 3242 } 3243 3244 /* 3245 * "imp" is the fault differential for the source task between the 3246 * source and destination node. Calculate the total differential for 3247 * the source task and potential destination task. The more negative 3248 * the value is, the more remote accesses that would be expected to 3249 * be incurred if the tasks were swapped. 3250 * 3251 * If dst and source tasks are in the same NUMA group, or not 3252 * in any group then look only at task weights. 3253 */ 3254 cur_ng = rcu_dereference_all(cur->numa_group); 3255 if (cur_ng == p_ng) { 3256 /* 3257 * Do not swap within a group or between tasks that have 3258 * no group if there is spare capacity. Swapping does 3259 * not address the load imbalance and helps one task at 3260 * the cost of punishing another. 3261 */ 3262 if (env->dst_stats.node_type == node_has_spare) 3263 goto unlock; 3264 3265 imp = taskimp + task_weight(cur, env->src_nid, dist) - 3266 task_weight(cur, env->dst_nid, dist); 3267 /* 3268 * Add some hysteresis to prevent swapping the 3269 * tasks within a group over tiny differences. 3270 */ 3271 if (cur_ng) 3272 imp -= imp / 16; 3273 } else { 3274 /* 3275 * Compare the group weights. If a task is all by itself 3276 * (not part of a group), use the task weight instead. 3277 */ 3278 if (cur_ng && p_ng) 3279 imp += group_weight(cur, env->src_nid, dist) - 3280 group_weight(cur, env->dst_nid, dist); 3281 else 3282 imp += task_weight(cur, env->src_nid, dist) - 3283 task_weight(cur, env->dst_nid, dist); 3284 } 3285 3286 /* Discourage picking a task already on its preferred node */ 3287 if (cur->numa_preferred_nid == env->dst_nid) 3288 imp -= imp / 16; 3289 3290 /* 3291 * Encourage picking a task that moves to its preferred node. 3292 * This potentially makes imp larger than it's maximum of 3293 * 1998 (see SMALLIMP and task_weight for why) but in this 3294 * case, it does not matter. 3295 */ 3296 if (cur->numa_preferred_nid == env->src_nid) 3297 imp += imp / 8; 3298 3299 if (maymove && moveimp > imp && moveimp > env->best_imp) { 3300 imp = moveimp; 3301 cur = NULL; 3302 goto assign; 3303 } 3304 3305 /* 3306 * Prefer swapping with a task moving to its preferred node over a 3307 * task that is not. 3308 */ 3309 if (env->best_task && cur->numa_preferred_nid == env->src_nid && 3310 env->best_task->numa_preferred_nid != env->src_nid) { 3311 goto assign; 3312 } 3313 3314 /* 3315 * If the NUMA importance is less than SMALLIMP, 3316 * task migration might only result in ping pong 3317 * of tasks and also hurt performance due to cache 3318 * misses. 3319 */ 3320 if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2) 3321 goto unlock; 3322 3323 /* 3324 * In the overloaded case, try and keep the load balanced. 3325 */ 3326 load = task_h_load(env->p) - task_h_load(cur); 3327 if (!load) 3328 goto assign; 3329 3330 dst_load = env->dst_stats.load + load; 3331 src_load = env->src_stats.load - load; 3332 3333 if (load_too_imbalanced(src_load, dst_load, env)) 3334 goto unlock; 3335 3336 assign: 3337 /* Evaluate an idle CPU for a task numa move. */ 3338 if (!cur) { 3339 int cpu = env->dst_stats.idle_cpu; 3340 3341 /* Nothing cached so current CPU went idle since the search. */ 3342 if (cpu < 0) 3343 cpu = env->dst_cpu; 3344 3345 /* 3346 * If the CPU is no longer truly idle and the previous best CPU 3347 * is, keep using it. 3348 */ 3349 if (!idle_cpu(cpu) && env->best_cpu >= 0 && 3350 idle_cpu(env->best_cpu)) { 3351 cpu = env->best_cpu; 3352 } 3353 3354 env->dst_cpu = cpu; 3355 } 3356 3357 task_numa_assign(env, cur, imp); 3358 3359 /* 3360 * If a move to idle is allowed because there is capacity or load 3361 * balance improves then stop the search. While a better swap 3362 * candidate may exist, a search is not free. 3363 */ 3364 if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu)) 3365 stopsearch = true; 3366 3367 /* 3368 * If a swap candidate must be identified and the current best task 3369 * moves its preferred node then stop the search. 3370 */ 3371 if (!maymove && env->best_task && 3372 env->best_task->numa_preferred_nid == env->src_nid) { 3373 stopsearch = true; 3374 } 3375 unlock: 3376 rcu_read_unlock(); 3377 3378 return stopsearch; 3379 } 3380 3381 static void task_numa_find_cpu(struct task_numa_env *env, 3382 long taskimp, long groupimp) 3383 { 3384 bool maymove = false; 3385 int cpu; 3386 3387 /* 3388 * If dst node has spare capacity, then check if there is an 3389 * imbalance that would be overruled by the load balancer. 3390 */ 3391 if (env->dst_stats.node_type == node_has_spare) { 3392 unsigned int imbalance; 3393 int src_running, dst_running; 3394 3395 /* 3396 * Would movement cause an imbalance? Note that if src has 3397 * more running tasks that the imbalance is ignored as the 3398 * move improves the imbalance from the perspective of the 3399 * CPU load balancer. 3400 * */ 3401 src_running = env->src_stats.nr_running - 1; 3402 dst_running = env->dst_stats.nr_running + 1; 3403 imbalance = max(0, dst_running - src_running); 3404 imbalance = adjust_numa_imbalance(imbalance, dst_running, 3405 env->imb_numa_nr); 3406 3407 /* Use idle CPU if there is no imbalance */ 3408 if (!imbalance) { 3409 maymove = true; 3410 if (env->dst_stats.idle_cpu >= 0) { 3411 env->dst_cpu = env->dst_stats.idle_cpu; 3412 task_numa_assign(env, NULL, 0); 3413 return; 3414 } 3415 } 3416 } else { 3417 long src_load, dst_load, load; 3418 /* 3419 * If the improvement from just moving env->p direction is better 3420 * than swapping tasks around, check if a move is possible. 3421 */ 3422 load = task_h_load(env->p); 3423 dst_load = env->dst_stats.load + load; 3424 src_load = env->src_stats.load - load; 3425 maymove = !load_too_imbalanced(src_load, dst_load, env); 3426 } 3427 3428 /* Skip CPUs if the source task cannot migrate */ 3429 for_each_cpu_and(cpu, cpumask_of_node(env->dst_nid), env->p->cpus_ptr) { 3430 env->dst_cpu = cpu; 3431 if (task_numa_compare(env, taskimp, groupimp, maymove)) 3432 break; 3433 } 3434 } 3435 3436 static int task_numa_migrate(struct task_struct *p) 3437 { 3438 struct task_numa_env env = { 3439 .p = p, 3440 3441 .src_cpu = task_cpu(p), 3442 .src_nid = task_node(p), 3443 3444 .imbalance_pct = 112, 3445 3446 .best_task = NULL, 3447 .best_imp = 0, 3448 .best_cpu = -1, 3449 }; 3450 unsigned long taskweight, groupweight; 3451 struct sched_domain *sd; 3452 long taskimp, groupimp; 3453 struct numa_group *ng; 3454 struct rq *best_rq; 3455 int nid, ret, dist; 3456 3457 /* 3458 * Pick the lowest SD_NUMA domain, as that would have the smallest 3459 * imbalance and would be the first to start moving tasks about. 3460 * 3461 * And we want to avoid any moving of tasks about, as that would create 3462 * random movement of tasks -- counter the numa conditions we're trying 3463 * to satisfy here. 3464 */ 3465 rcu_read_lock(); 3466 sd = rcu_dereference_all(per_cpu(sd_numa, env.src_cpu)); 3467 if (sd) { 3468 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2; 3469 env.imb_numa_nr = sd->imb_numa_nr; 3470 } 3471 rcu_read_unlock(); 3472 3473 /* 3474 * Cpusets can break the scheduler domain tree into smaller 3475 * balance domains, some of which do not cross NUMA boundaries. 3476 * Tasks that are "trapped" in such domains cannot be migrated 3477 * elsewhere, so there is no point in (re)trying. 3478 */ 3479 if (unlikely(!sd)) { 3480 sched_setnuma(p, task_node(p)); 3481 return -EINVAL; 3482 } 3483 3484 env.dst_nid = p->numa_preferred_nid; 3485 dist = env.dist = node_distance(env.src_nid, env.dst_nid); 3486 taskweight = task_weight(p, env.src_nid, dist); 3487 groupweight = group_weight(p, env.src_nid, dist); 3488 update_numa_stats(&env, &env.src_stats, env.src_nid, false); 3489 taskimp = task_weight(p, env.dst_nid, dist) - taskweight; 3490 groupimp = group_weight(p, env.dst_nid, dist) - groupweight; 3491 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true); 3492 3493 /* Try to find a spot on the preferred nid. */ 3494 task_numa_find_cpu(&env, taskimp, groupimp); 3495 3496 /* 3497 * Look at other nodes in these cases: 3498 * - there is no space available on the preferred_nid 3499 * - the task is part of a numa_group that is interleaved across 3500 * multiple NUMA nodes; in order to better consolidate the group, 3501 * we need to check other locations. 3502 */ 3503 ng = deref_curr_numa_group(p); 3504 if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) { 3505 for_each_node_state(nid, N_CPU) { 3506 if (nid == env.src_nid || nid == p->numa_preferred_nid) 3507 continue; 3508 3509 dist = node_distance(env.src_nid, env.dst_nid); 3510 if (sched_numa_topology_type == NUMA_BACKPLANE && 3511 dist != env.dist) { 3512 taskweight = task_weight(p, env.src_nid, dist); 3513 groupweight = group_weight(p, env.src_nid, dist); 3514 } 3515 3516 /* Only consider nodes where both task and groups benefit */ 3517 taskimp = task_weight(p, nid, dist) - taskweight; 3518 groupimp = group_weight(p, nid, dist) - groupweight; 3519 if (taskimp < 0 && groupimp < 0) 3520 continue; 3521 3522 env.dist = dist; 3523 env.dst_nid = nid; 3524 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true); 3525 task_numa_find_cpu(&env, taskimp, groupimp); 3526 } 3527 } 3528 3529 /* 3530 * If the task is part of a workload that spans multiple NUMA nodes, 3531 * and is migrating into one of the workload's active nodes, remember 3532 * this node as the task's preferred numa node, so the workload can 3533 * settle down. 3534 * A task that migrated to a second choice node will be better off 3535 * trying for a better one later. Do not set the preferred node here. 3536 */ 3537 if (ng) { 3538 if (env.best_cpu == -1) 3539 nid = env.src_nid; 3540 else 3541 nid = cpu_to_node(env.best_cpu); 3542 3543 if (nid != p->numa_preferred_nid) 3544 sched_setnuma(p, nid); 3545 } 3546 3547 /* No better CPU than the current one was found. */ 3548 if (env.best_cpu == -1) { 3549 trace_sched_stick_numa(p, env.src_cpu, NULL, -1); 3550 return -EAGAIN; 3551 } 3552 3553 best_rq = cpu_rq(env.best_cpu); 3554 if (env.best_task == NULL) { 3555 ret = migrate_task_to(p, env.best_cpu); 3556 WRITE_ONCE(best_rq->numa_migrate_on, 0); 3557 if (ret != 0) 3558 trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu); 3559 return ret; 3560 } 3561 3562 ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu); 3563 WRITE_ONCE(best_rq->numa_migrate_on, 0); 3564 3565 if (ret != 0) 3566 trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu); 3567 put_task_struct(env.best_task); 3568 return ret; 3569 } 3570 3571 /* Attempt to migrate a task to a CPU on the preferred node. */ 3572 static void numa_migrate_preferred(struct task_struct *p) 3573 { 3574 unsigned long interval = HZ; 3575 3576 /* This task has no NUMA fault statistics yet */ 3577 if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults)) 3578 return; 3579 3580 /* Periodically retry migrating the task to the preferred node */ 3581 interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16); 3582 p->numa_migrate_retry = jiffies + interval; 3583 3584 /* Success if task is already running on preferred CPU */ 3585 if (task_node(p) == p->numa_preferred_nid) 3586 return; 3587 3588 /* Otherwise, try migrate to a CPU on the preferred node */ 3589 task_numa_migrate(p); 3590 } 3591 3592 /* 3593 * Find out how many nodes the workload is actively running on. Do this by 3594 * tracking the nodes from which NUMA hinting faults are triggered. This can 3595 * be different from the set of nodes where the workload's memory is currently 3596 * located. 3597 */ 3598 static void numa_group_count_active_nodes(struct numa_group *numa_group) 3599 { 3600 unsigned long faults, max_faults = 0; 3601 int nid, active_nodes = 0; 3602 3603 for_each_node_state(nid, N_CPU) { 3604 faults = group_faults_cpu(numa_group, nid); 3605 if (faults > max_faults) 3606 max_faults = faults; 3607 } 3608 3609 for_each_node_state(nid, N_CPU) { 3610 faults = group_faults_cpu(numa_group, nid); 3611 if (faults * ACTIVE_NODE_FRACTION > max_faults) 3612 active_nodes++; 3613 } 3614 3615 numa_group->max_faults_cpu = max_faults; 3616 numa_group->active_nodes = active_nodes; 3617 } 3618 3619 /* 3620 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS 3621 * increments. The more local the fault statistics are, the higher the scan 3622 * period will be for the next scan window. If local/(local+remote) ratio is 3623 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS) 3624 * the scan period will decrease. Aim for 70% local accesses. 3625 */ 3626 #define NUMA_PERIOD_SLOTS 10 3627 #define NUMA_PERIOD_THRESHOLD 7 3628 3629 /* 3630 * Increase the scan period (slow down scanning) if the majority of 3631 * our memory is already on our local node, or if the majority of 3632 * the page accesses are shared with other processes. 3633 * Otherwise, decrease the scan period. 3634 */ 3635 static void update_task_scan_period(struct task_struct *p, 3636 unsigned long shared, unsigned long private) 3637 { 3638 unsigned int period_slot; 3639 int lr_ratio, ps_ratio; 3640 int diff; 3641 3642 unsigned long remote = p->numa_faults_locality[0]; 3643 unsigned long local = p->numa_faults_locality[1]; 3644 3645 /* 3646 * If there were no record hinting faults then either the task is 3647 * completely idle or all activity is in areas that are not of interest 3648 * to automatic numa balancing. Related to that, if there were failed 3649 * migration then it implies we are migrating too quickly or the local 3650 * node is overloaded. In either case, scan slower 3651 */ 3652 if (local + shared == 0 || p->numa_faults_locality[2]) { 3653 p->numa_scan_period = min(p->numa_scan_period_max, 3654 p->numa_scan_period << 1); 3655 3656 p->mm->numa_next_scan = jiffies + 3657 msecs_to_jiffies(p->numa_scan_period); 3658 3659 goto out; 3660 } 3661 3662 /* 3663 * Prepare to scale scan period relative to the current period. 3664 * == NUMA_PERIOD_THRESHOLD scan period stays the same 3665 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster) 3666 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower) 3667 */ 3668 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS); 3669 lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote); 3670 ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared); 3671 3672 if (ps_ratio >= NUMA_PERIOD_THRESHOLD) { 3673 /* 3674 * Most memory accesses are local. There is no need to 3675 * do fast NUMA scanning, since memory is already local. 3676 */ 3677 int slot = ps_ratio - NUMA_PERIOD_THRESHOLD; 3678 if (!slot) 3679 slot = 1; 3680 diff = slot * period_slot; 3681 } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) { 3682 /* 3683 * Most memory accesses are shared with other tasks. 3684 * There is no point in continuing fast NUMA scanning, 3685 * since other tasks may just move the memory elsewhere. 3686 */ 3687 int slot = lr_ratio - NUMA_PERIOD_THRESHOLD; 3688 if (!slot) 3689 slot = 1; 3690 diff = slot * period_slot; 3691 } else { 3692 /* 3693 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS, 3694 * yet they are not on the local NUMA node. Speed up 3695 * NUMA scanning to get the memory moved over. 3696 */ 3697 int ratio = max(lr_ratio, ps_ratio); 3698 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot; 3699 } 3700 3701 p->numa_scan_period = clamp(p->numa_scan_period + diff, 3702 task_scan_min(p), task_scan_max(p)); 3703 3704 out: 3705 memset(p->numa_faults_locality, 0, 3706 sizeof(p->numa_faults_locality)); 3707 } 3708 3709 /* 3710 * Get the fraction of time the task has been running since the last 3711 * NUMA placement cycle. The scheduler keeps similar statistics, but 3712 * decays those on a 32ms period, which is orders of magnitude off 3713 * from the dozens-of-seconds NUMA balancing period. Use the scheduler 3714 * stats only if the task is so new there are no NUMA statistics yet. 3715 */ 3716 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period) 3717 { 3718 u64 runtime, delta, now; 3719 /* Use the start of this time slice to avoid calculations. */ 3720 now = p->se.exec_start; 3721 runtime = p->se.sum_exec_runtime; 3722 3723 if (p->last_task_numa_placement) { 3724 delta = runtime - p->last_sum_exec_runtime; 3725 *period = now - p->last_task_numa_placement; 3726 3727 /* Avoid time going backwards, prevent potential divide error: */ 3728 if (unlikely((s64)*period < 0)) 3729 *period = 0; 3730 } else { 3731 delta = p->se.avg.load_sum; 3732 *period = LOAD_AVG_MAX; 3733 } 3734 3735 p->last_sum_exec_runtime = runtime; 3736 p->last_task_numa_placement = now; 3737 3738 return delta; 3739 } 3740 3741 /* 3742 * Determine the preferred nid for a task in a numa_group. This needs to 3743 * be done in a way that produces consistent results with group_weight, 3744 * otherwise workloads might not converge. 3745 */ 3746 static int preferred_group_nid(struct task_struct *p, int nid) 3747 { 3748 nodemask_t nodes; 3749 int dist; 3750 3751 /* Direct connections between all NUMA nodes. */ 3752 if (sched_numa_topology_type == NUMA_DIRECT) 3753 return nid; 3754 3755 /* 3756 * On a system with glueless mesh NUMA topology, group_weight 3757 * scores nodes according to the number of NUMA hinting faults on 3758 * both the node itself, and on nearby nodes. 3759 */ 3760 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) { 3761 unsigned long score, max_score = 0; 3762 int node, max_node = nid; 3763 3764 dist = sched_max_numa_distance; 3765 3766 for_each_node_state(node, N_CPU) { 3767 score = group_weight(p, node, dist); 3768 if (score > max_score) { 3769 max_score = score; 3770 max_node = node; 3771 } 3772 } 3773 return max_node; 3774 } 3775 3776 /* 3777 * Finding the preferred nid in a system with NUMA backplane 3778 * interconnect topology is more involved. The goal is to locate 3779 * tasks from numa_groups near each other in the system, and 3780 * untangle workloads from different sides of the system. This requires 3781 * searching down the hierarchy of node groups, recursively searching 3782 * inside the highest scoring group of nodes. The nodemask tricks 3783 * keep the complexity of the search down. 3784 */ 3785 nodes = node_states[N_CPU]; 3786 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) { 3787 unsigned long max_faults = 0; 3788 nodemask_t max_group = NODE_MASK_NONE; 3789 int a, b; 3790 3791 /* Are there nodes at this distance from each other? */ 3792 if (!find_numa_distance(dist)) 3793 continue; 3794 3795 for_each_node_mask(a, nodes) { 3796 unsigned long faults = 0; 3797 nodemask_t this_group; 3798 nodes_clear(this_group); 3799 3800 /* Sum group's NUMA faults; includes a==b case. */ 3801 for_each_node_mask(b, nodes) { 3802 if (node_distance(a, b) < dist) { 3803 faults += group_faults(p, b); 3804 node_set(b, this_group); 3805 node_clear(b, nodes); 3806 } 3807 } 3808 3809 /* Remember the top group. */ 3810 if (faults > max_faults) { 3811 max_faults = faults; 3812 max_group = this_group; 3813 /* 3814 * subtle: at the smallest distance there is 3815 * just one node left in each "group", the 3816 * winner is the preferred nid. 3817 */ 3818 nid = a; 3819 } 3820 } 3821 /* Next round, evaluate the nodes within max_group. */ 3822 if (!max_faults) 3823 break; 3824 nodes = max_group; 3825 } 3826 return nid; 3827 } 3828 3829 static void task_numa_placement(struct task_struct *p) 3830 __context_unsafe(/* conditional locking */) 3831 { 3832 struct sched_cache_group __maybe_unused *grp; 3833 int seq, nid, max_nid = NUMA_NO_NODE; 3834 unsigned long max_faults = 0; 3835 unsigned long fault_types[2] = { 0, 0 }; 3836 unsigned long total_faults; 3837 u64 runtime, period; 3838 spinlock_t *group_lock = NULL; 3839 long __maybe_unused new_fp; 3840 struct numa_group *ng; 3841 3842 /* 3843 * The p->mm->numa_scan_seq field gets updated without 3844 * exclusive access. Use READ_ONCE() here to ensure 3845 * that the field is read in a single access: 3846 */ 3847 seq = READ_ONCE(p->mm->numa_scan_seq); 3848 if (p->numa_scan_seq == seq) 3849 return; 3850 p->numa_scan_seq = seq; 3851 p->numa_scan_period_max = task_scan_max(p); 3852 3853 total_faults = p->numa_faults_locality[0] + 3854 p->numa_faults_locality[1]; 3855 runtime = numa_get_avg_runtime(p, &period); 3856 3857 /* If the task is part of a group prevent parallel updates to group stats */ 3858 ng = deref_curr_numa_group(p); 3859 if (ng) { 3860 group_lock = &ng->lock; 3861 spin_lock_irq(group_lock); 3862 } 3863 3864 /* Find the node with the highest number of faults */ 3865 for_each_online_node(nid) { 3866 /* Keep track of the offsets in numa_faults array */ 3867 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx; 3868 unsigned long faults = 0, group_faults = 0; 3869 int priv; 3870 3871 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) { 3872 long diff, f_diff, f_weight; 3873 3874 mem_idx = task_faults_idx(NUMA_MEM, nid, priv); 3875 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv); 3876 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv); 3877 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv); 3878 3879 /* Decay existing window, copy faults since last scan */ 3880 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2; 3881 fault_types[priv] += p->numa_faults[membuf_idx]; 3882 p->numa_faults[membuf_idx] = 0; 3883 3884 /* 3885 * Normalize the faults_from, so all tasks in a group 3886 * count according to CPU use, instead of by the raw 3887 * number of faults. Tasks with little runtime have 3888 * little over-all impact on throughput, and thus their 3889 * faults are less important. 3890 */ 3891 f_weight = div64_u64(runtime << 16, period + 1); 3892 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) / 3893 (total_faults + 1); 3894 f_diff = f_weight - p->numa_faults[cpu_idx] / 2; 3895 p->numa_faults[cpubuf_idx] = 0; 3896 3897 p->numa_faults[mem_idx] += diff; 3898 p->numa_faults[cpu_idx] += f_diff; 3899 faults += p->numa_faults[mem_idx]; 3900 p->total_numa_faults += diff; 3901 if (ng) { 3902 /* 3903 * safe because we can only change our own group 3904 * 3905 * mem_idx represents the offset for a given 3906 * nid and priv in a specific region because it 3907 * is at the beginning of the numa_faults array. 3908 */ 3909 ng->faults[mem_idx] += diff; 3910 ng->faults[cpu_idx] += f_diff; 3911 ng->total_faults += diff; 3912 group_faults += ng->faults[mem_idx]; 3913 } 3914 #ifdef CONFIG_SCHED_CACHE 3915 /* 3916 * Per task p->numa_faults[mem_idx] converges, 3917 * so the accumulation of each task's faults 3918 * converges too - Given the number of threads, 3919 * it cannot overflow an unsigned long. 3920 * Racy with concurrent updates from other threads 3921 * sharing this mm. Acceptable since footprint is a 3922 * heuristic and occasional lost updates are tolerable. 3923 * 3924 * If a task exits, its corresponding footprint must 3925 * be subtracted from p->sched_cache_grp->footprint, 3926 * otherwise the footprint will not converge: the 3927 * exiting thread's footprint remains unchanged/undecayed. 3928 * See exit_mm(). 3929 * 3930 * Lost updates and unsynchronized subtraction 3931 * in exit_mm() can cause footprint + diff to 3932 * go negative. Clamp to zero to prevent the 3933 * unsigned footprint from wrapping. 3934 */ 3935 scoped_guard(rcu) { 3936 grp = rcu_dereference(p->sched_cache_grp); 3937 3938 if (grp) { 3939 new_fp = (long)READ_ONCE(grp->footprint) + diff; 3940 WRITE_ONCE(grp->footprint, max(new_fp, 0L)); 3941 } 3942 } 3943 #endif 3944 } 3945 3946 if (!ng) { 3947 if (faults > max_faults) { 3948 max_faults = faults; 3949 max_nid = nid; 3950 } 3951 } else if (group_faults > max_faults) { 3952 max_faults = group_faults; 3953 max_nid = nid; 3954 } 3955 } 3956 3957 /* Cannot migrate task to CPU-less node */ 3958 max_nid = numa_nearest_node(max_nid, N_CPU); 3959 3960 if (ng) { 3961 numa_group_count_active_nodes(ng); 3962 spin_unlock_irq(group_lock); 3963 max_nid = preferred_group_nid(p, max_nid); 3964 } 3965 3966 if (max_faults) { 3967 /* Set the new preferred node */ 3968 if (max_nid != p->numa_preferred_nid) 3969 sched_setnuma(p, max_nid); 3970 } 3971 3972 update_task_scan_period(p, fault_types[0], fault_types[1]); 3973 } 3974 3975 static inline int get_numa_group(struct numa_group *grp) 3976 { 3977 return refcount_inc_not_zero(&grp->refcount); 3978 } 3979 3980 static inline void put_numa_group(struct numa_group *grp) 3981 { 3982 if (refcount_dec_and_test(&grp->refcount)) 3983 kfree_rcu(grp, rcu); 3984 } 3985 3986 static void task_numa_group(struct task_struct *p, int cpupid, int flags, 3987 int *priv) 3988 { 3989 struct numa_group *grp, *my_grp; 3990 struct task_struct *tsk; 3991 bool join = false; 3992 int cpu = cpupid_to_cpu(cpupid); 3993 int i; 3994 3995 if (unlikely(!deref_curr_numa_group(p))) { 3996 unsigned int size = sizeof(struct numa_group) + 3997 NR_NUMA_HINT_FAULT_STATS * 3998 nr_node_ids * sizeof(unsigned long); 3999 4000 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN); 4001 if (!grp) 4002 return; 4003 4004 refcount_set(&grp->refcount, 1); 4005 grp->active_nodes = 1; 4006 grp->max_faults_cpu = 0; 4007 spin_lock_init(&grp->lock); 4008 grp->gid = p->pid; 4009 4010 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) 4011 grp->faults[i] = p->numa_faults[i]; 4012 4013 grp->total_faults = p->total_numa_faults; 4014 4015 grp->nr_tasks++; 4016 rcu_assign_pointer(p->numa_group, grp); 4017 } 4018 4019 rcu_read_lock(); 4020 tsk = READ_ONCE(cpu_rq(cpu)->curr); 4021 4022 if (!cpupid_match_pid(tsk, cpupid)) 4023 goto no_join; 4024 4025 grp = rcu_dereference_all(tsk->numa_group); 4026 if (!grp) 4027 goto no_join; 4028 4029 my_grp = deref_curr_numa_group(p); 4030 if (grp == my_grp) 4031 goto no_join; 4032 4033 /* 4034 * Only join the other group if its bigger; if we're the bigger group, 4035 * the other task will join us. 4036 */ 4037 if (my_grp->nr_tasks > grp->nr_tasks) 4038 goto no_join; 4039 4040 /* 4041 * Tie-break on the grp address. 4042 */ 4043 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp) 4044 goto no_join; 4045 4046 /* Always join threads in the same process. */ 4047 if (tsk->mm == current->mm) 4048 join = true; 4049 4050 /* Simple filter to avoid false positives due to PID collisions */ 4051 if (flags & TNF_SHARED) 4052 join = true; 4053 4054 /* Update priv based on whether false sharing was detected */ 4055 *priv = !join; 4056 4057 if (join && !get_numa_group(grp)) 4058 goto no_join; 4059 4060 rcu_read_unlock(); 4061 4062 if (!join) 4063 return; 4064 4065 WARN_ON_ONCE(irqs_disabled()); 4066 double_lock_irq(&my_grp->lock, &grp->lock); 4067 4068 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) { 4069 my_grp->faults[i] -= p->numa_faults[i]; 4070 grp->faults[i] += p->numa_faults[i]; 4071 } 4072 my_grp->total_faults -= p->total_numa_faults; 4073 grp->total_faults += p->total_numa_faults; 4074 4075 my_grp->nr_tasks--; 4076 grp->nr_tasks++; 4077 4078 spin_unlock(&my_grp->lock); 4079 spin_unlock_irq(&grp->lock); 4080 4081 rcu_assign_pointer(p->numa_group, grp); 4082 4083 put_numa_group(my_grp); 4084 return; 4085 4086 no_join: 4087 rcu_read_unlock(); 4088 return; 4089 } 4090 4091 /* 4092 * Get rid of NUMA statistics associated with a task (either current or dead). 4093 * If @final is set, the task is dead and has reached refcount zero, so we can 4094 * safely free all relevant data structures. Otherwise, there might be 4095 * concurrent reads from places like load balancing and procfs, and we should 4096 * reset the data back to default state without freeing ->numa_faults. 4097 */ 4098 void task_numa_free(struct task_struct *p, bool final) 4099 { 4100 /* safe: p either is current or is being freed by current */ 4101 struct numa_group *grp = rcu_dereference_raw(p->numa_group); 4102 unsigned long *numa_faults = p->numa_faults; 4103 unsigned long flags; 4104 int i; 4105 4106 if (!numa_faults) 4107 return; 4108 4109 if (grp) { 4110 spin_lock_irqsave(&grp->lock, flags); 4111 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) 4112 grp->faults[i] -= p->numa_faults[i]; 4113 grp->total_faults -= p->total_numa_faults; 4114 4115 grp->nr_tasks--; 4116 spin_unlock_irqrestore(&grp->lock, flags); 4117 RCU_INIT_POINTER(p->numa_group, NULL); 4118 put_numa_group(grp); 4119 } 4120 4121 if (final) { 4122 p->numa_faults = NULL; 4123 kfree(numa_faults); 4124 } else { 4125 p->total_numa_faults = 0; 4126 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) 4127 numa_faults[i] = 0; 4128 } 4129 } 4130 4131 /* 4132 * Got a PROT_NONE fault for a page on @node. 4133 */ 4134 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags) 4135 { 4136 struct task_struct *p = current; 4137 bool migrated = flags & TNF_MIGRATED; 4138 int cpu_node = task_node(current); 4139 int local = !!(flags & TNF_FAULT_LOCAL); 4140 struct numa_group *ng; 4141 int priv; 4142 4143 if (!static_branch_likely(&sched_numa_balancing)) 4144 return; 4145 4146 /* for example, ksmd faulting in a user's mm */ 4147 if (!p->mm) 4148 return; 4149 4150 /* 4151 * NUMA faults statistics are unnecessary for the slow memory 4152 * node for memory tiering mode. 4153 */ 4154 if (!node_is_toptier(mem_node) && 4155 (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING || 4156 !cpupid_valid(last_cpupid))) 4157 return; 4158 4159 /* Allocate buffer to track faults on a per-node basis */ 4160 if (unlikely(!p->numa_faults)) { 4161 int size = sizeof(*p->numa_faults) * 4162 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids; 4163 4164 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN); 4165 if (!p->numa_faults) 4166 return; 4167 4168 p->total_numa_faults = 0; 4169 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality)); 4170 } 4171 4172 /* 4173 * First accesses are treated as private, otherwise consider accesses 4174 * to be private if the accessing pid has not changed 4175 */ 4176 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) { 4177 priv = 1; 4178 } else { 4179 priv = cpupid_match_pid(p, last_cpupid); 4180 if (!priv && !(flags & TNF_NO_GROUP)) 4181 task_numa_group(p, last_cpupid, flags, &priv); 4182 } 4183 4184 /* 4185 * If a workload spans multiple NUMA nodes, a shared fault that 4186 * occurs wholly within the set of nodes that the workload is 4187 * actively using should be counted as local. This allows the 4188 * scan rate to slow down when a workload has settled down. 4189 */ 4190 ng = deref_curr_numa_group(p); 4191 if (!priv && !local && ng && ng->active_nodes > 1 && 4192 numa_is_active_node(cpu_node, ng) && 4193 numa_is_active_node(mem_node, ng)) 4194 local = 1; 4195 4196 /* 4197 * Retry to migrate task to preferred node periodically, in case it 4198 * previously failed, or the scheduler moved us. 4199 */ 4200 if (time_after(jiffies, p->numa_migrate_retry)) { 4201 task_numa_placement(p); 4202 numa_migrate_preferred(p); 4203 } 4204 4205 if (migrated) 4206 p->numa_pages_migrated += pages; 4207 if (flags & TNF_MIGRATE_FAIL) 4208 p->numa_faults_locality[2] += pages; 4209 4210 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages; 4211 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages; 4212 p->numa_faults_locality[local] += pages; 4213 } 4214 4215 static void reset_ptenuma_scan(struct task_struct *p) 4216 { 4217 /* 4218 * We only did a read acquisition of the mmap sem, so 4219 * p->mm->numa_scan_seq is written to without exclusive access 4220 * and the update is not guaranteed to be atomic. That's not 4221 * much of an issue though, since this is just used for 4222 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not 4223 * expensive, to avoid any form of compiler optimizations: 4224 */ 4225 WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1); 4226 p->mm->numa_scan_offset = 0; 4227 } 4228 4229 static bool vma_is_accessed(struct mm_struct *mm, struct vm_area_struct *vma) 4230 { 4231 unsigned long pids; 4232 /* 4233 * Allow unconditional access first two times, so that all the (pages) 4234 * of VMAs get prot_none fault introduced irrespective of accesses. 4235 * This is also done to avoid any side effect of task scanning 4236 * amplifying the unfairness of disjoint set of VMAs' access. 4237 */ 4238 if ((READ_ONCE(current->mm->numa_scan_seq) - vma->numab_state->start_scan_seq) < 2) 4239 return true; 4240 4241 pids = vma->numab_state->pids_active[0] | vma->numab_state->pids_active[1]; 4242 if (test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids)) 4243 return true; 4244 4245 /* 4246 * Complete a scan that has already started regardless of PID access, or 4247 * some VMAs may never be scanned in multi-threaded applications: 4248 */ 4249 if (mm->numa_scan_offset > vma->vm_start) { 4250 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_IGNORE_PID); 4251 return true; 4252 } 4253 4254 /* 4255 * This vma has not been accessed for a while, and if the number 4256 * the threads in the same process is low, which means no other 4257 * threads can help scan this vma, force a vma scan. 4258 */ 4259 if (READ_ONCE(mm->numa_scan_seq) > 4260 (vma->numab_state->prev_scan_seq + get_nr_threads(current))) 4261 return true; 4262 4263 return false; 4264 } 4265 4266 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay) 4267 4268 /* 4269 * The expensive part of numa migration is done from task_work context. 4270 * Triggered from task_tick_numa(). 4271 */ 4272 static void task_numa_work(struct callback_head *work) 4273 { 4274 unsigned long migrate, next_scan, now = jiffies; 4275 struct task_struct *p = current; 4276 struct mm_struct *mm = p->mm; 4277 u64 runtime = p->se.sum_exec_runtime; 4278 struct vm_area_struct *vma; 4279 unsigned long start, end; 4280 unsigned long nr_pte_updates = 0; 4281 long pages, virtpages; 4282 struct vma_iterator vmi; 4283 bool vma_pids_skipped; 4284 bool vma_pids_forced = false; 4285 4286 WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work)); 4287 4288 work->next = work; 4289 /* 4290 * Who cares about NUMA placement when they're dying. 4291 * 4292 * NOTE: make sure not to dereference p->mm before this check, 4293 * exit_task_work() happens _after_ exit_mm() so we could be called 4294 * without p->mm even though we still had it when we enqueued this 4295 * work. 4296 */ 4297 if (p->flags & PF_EXITING) 4298 return; 4299 4300 /* 4301 * Memory is pinned to only one NUMA node via cpuset.mems, naturally 4302 * no page can be migrated. 4303 */ 4304 if (cpusets_enabled() && nodes_weight(cpuset_current_mems_allowed) == 1) { 4305 trace_sched_skip_cpuset_numa(current, &cpuset_current_mems_allowed); 4306 return; 4307 } 4308 4309 if (!mm->numa_next_scan) { 4310 mm->numa_next_scan = now + 4311 msecs_to_jiffies(sysctl_numa_balancing_scan_delay); 4312 } 4313 4314 /* 4315 * Enforce maximal scan/migration frequency.. 4316 */ 4317 migrate = mm->numa_next_scan; 4318 if (time_before(now, migrate)) 4319 return; 4320 4321 if (p->numa_scan_period == 0) { 4322 p->numa_scan_period_max = task_scan_max(p); 4323 p->numa_scan_period = task_scan_start(p); 4324 } 4325 4326 next_scan = now + msecs_to_jiffies(p->numa_scan_period); 4327 if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan)) 4328 return; 4329 4330 /* 4331 * Delay this task enough that another task of this mm will likely win 4332 * the next time around. 4333 */ 4334 p->node_stamp += 2 * TICK_NSEC; 4335 4336 pages = sysctl_numa_balancing_scan_size; 4337 pages <<= 20 - PAGE_SHIFT; /* MB in pages */ 4338 virtpages = pages * 8; /* Scan up to this much virtual space */ 4339 if (!pages) 4340 return; 4341 4342 4343 if (!mmap_read_trylock(mm)) 4344 return; 4345 4346 /* 4347 * VMAs are skipped if the current PID has not trapped a fault within 4348 * the VMA recently. Allow scanning to be forced if there is no 4349 * suitable VMA remaining. 4350 */ 4351 vma_pids_skipped = false; 4352 4353 retry_pids: 4354 start = mm->numa_scan_offset; 4355 vma_iter_init(&vmi, mm, start); 4356 vma = vma_next(&vmi); 4357 if (!vma) { 4358 reset_ptenuma_scan(p); 4359 start = 0; 4360 vma_iter_set(&vmi, start); 4361 vma = vma_next(&vmi); 4362 } 4363 4364 for (; vma; vma = vma_next(&vmi)) { 4365 if (!vma_migratable(vma) || !vma_policy_mof(vma) || 4366 vma_is_hugetlb(vma) || !vma_is_mm_managed(vma)) { 4367 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_UNSUITABLE); 4368 continue; 4369 } 4370 4371 /* 4372 * Shared library pages mapped by multiple processes are not 4373 * migrated as it is expected they are cache replicated. Avoid 4374 * hinting faults in read-only file-backed mappings or the vDSO 4375 * as migrating the pages will be of marginal benefit. 4376 */ 4377 if (!vma->vm_mm || 4378 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ))) { 4379 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SHARED_RO); 4380 continue; 4381 } 4382 4383 /* 4384 * Skip inaccessible VMAs to avoid any confusion between 4385 * PROT_NONE and NUMA hinting PTEs 4386 */ 4387 if (!vma_is_accessible(vma)) { 4388 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_INACCESSIBLE); 4389 continue; 4390 } 4391 4392 /* Initialise new per-VMA NUMAB state. */ 4393 if (!vma->numab_state) { 4394 struct vma_numab_state *ptr; 4395 4396 ptr = kzalloc_obj(*ptr); 4397 if (!ptr) 4398 continue; 4399 4400 if (cmpxchg(&vma->numab_state, NULL, ptr)) { 4401 kfree(ptr); 4402 continue; 4403 } 4404 4405 vma->numab_state->start_scan_seq = mm->numa_scan_seq; 4406 4407 vma->numab_state->next_scan = now + 4408 msecs_to_jiffies(sysctl_numa_balancing_scan_delay); 4409 4410 /* Reset happens after 4 times scan delay of scan start */ 4411 vma->numab_state->pids_active_reset = vma->numab_state->next_scan + 4412 msecs_to_jiffies(VMA_PID_RESET_PERIOD); 4413 4414 /* 4415 * Ensure prev_scan_seq does not match numa_scan_seq, 4416 * to prevent VMAs being skipped prematurely on the 4417 * first scan: 4418 */ 4419 vma->numab_state->prev_scan_seq = mm->numa_scan_seq - 1; 4420 } 4421 4422 /* 4423 * Scanning the VMAs of short lived tasks add more overhead. So 4424 * delay the scan for new VMAs. 4425 */ 4426 if (mm->numa_scan_seq && time_before(jiffies, 4427 vma->numab_state->next_scan)) { 4428 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SCAN_DELAY); 4429 continue; 4430 } 4431 4432 /* RESET access PIDs regularly for old VMAs. */ 4433 if (mm->numa_scan_seq && 4434 time_after(jiffies, vma->numab_state->pids_active_reset)) { 4435 vma->numab_state->pids_active_reset = vma->numab_state->pids_active_reset + 4436 msecs_to_jiffies(VMA_PID_RESET_PERIOD); 4437 vma->numab_state->pids_active[0] = READ_ONCE(vma->numab_state->pids_active[1]); 4438 vma->numab_state->pids_active[1] = 0; 4439 } 4440 4441 /* Do not rescan VMAs twice within the same sequence. */ 4442 if (vma->numab_state->prev_scan_seq == mm->numa_scan_seq) { 4443 mm->numa_scan_offset = vma->vm_end; 4444 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SEQ_COMPLETED); 4445 continue; 4446 } 4447 4448 /* 4449 * Do not scan the VMA if task has not accessed it, unless no other 4450 * VMA candidate exists. 4451 */ 4452 if (!vma_pids_forced && !vma_is_accessed(mm, vma)) { 4453 vma_pids_skipped = true; 4454 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_PID_INACTIVE); 4455 continue; 4456 } 4457 4458 do { 4459 start = max(start, vma->vm_start); 4460 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE); 4461 end = min(end, vma->vm_end); 4462 nr_pte_updates = change_prot_numa(vma, start, end); 4463 4464 /* 4465 * Try to scan sysctl_numa_balancing_size worth of 4466 * hpages that have at least one present PTE that 4467 * is not already PTE-numa. If the VMA contains 4468 * areas that are unused or already full of prot_numa 4469 * PTEs, scan up to virtpages, to skip through those 4470 * areas faster. 4471 */ 4472 if (nr_pte_updates) 4473 pages -= (end - start) >> PAGE_SHIFT; 4474 virtpages -= (end - start) >> PAGE_SHIFT; 4475 4476 start = end; 4477 if (pages <= 0 || virtpages <= 0) 4478 goto out; 4479 4480 cond_resched(); 4481 } while (end != vma->vm_end); 4482 4483 /* VMA scan is complete, do not scan until next sequence. */ 4484 vma->numab_state->prev_scan_seq = mm->numa_scan_seq; 4485 4486 /* 4487 * Only force scan within one VMA at a time, to limit the 4488 * cost of scanning a potentially uninteresting VMA. 4489 */ 4490 if (vma_pids_forced) 4491 break; 4492 } 4493 4494 /* 4495 * If no VMAs are remaining and VMAs were skipped due to the PID 4496 * not accessing the VMA previously, then force a scan to ensure 4497 * forward progress: 4498 */ 4499 if (!vma && !vma_pids_forced && vma_pids_skipped) { 4500 vma_pids_forced = true; 4501 goto retry_pids; 4502 } 4503 4504 out: 4505 /* 4506 * It is possible to reach the end of the VMA list but the last few 4507 * VMAs are not guaranteed to the vma_migratable. If they are not, we 4508 * would find the !migratable VMA on the next scan but not reset the 4509 * scanner to the start so check it now. 4510 */ 4511 if (vma) 4512 mm->numa_scan_offset = start; 4513 else 4514 reset_ptenuma_scan(p); 4515 mmap_read_unlock(mm); 4516 4517 /* 4518 * Make sure tasks use at least 32x as much time to run other code 4519 * than they used here, to limit NUMA PTE scanning overhead to 3% max. 4520 * Usually update_task_scan_period slows down scanning enough; on an 4521 * overloaded system we need to limit overhead on a per task basis. 4522 */ 4523 if (unlikely(p->se.sum_exec_runtime != runtime)) { 4524 u64 diff = p->se.sum_exec_runtime - runtime; 4525 p->node_stamp += 32 * diff; 4526 } 4527 } 4528 4529 void init_numa_balancing(u64 clone_flags, struct task_struct *p) 4530 { 4531 int mm_users = 0; 4532 struct mm_struct *mm = p->mm; 4533 4534 if (mm) { 4535 mm_users = atomic_read(&mm->mm_users); 4536 if (mm_users == 1) { 4537 mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay); 4538 mm->numa_scan_seq = 0; 4539 } 4540 } 4541 p->node_stamp = 0; 4542 p->numa_scan_seq = mm ? mm->numa_scan_seq : 0; 4543 p->numa_scan_period = sysctl_numa_balancing_scan_delay; 4544 p->numa_migrate_retry = 0; 4545 /* Protect against double add, see task_tick_numa and task_numa_work */ 4546 p->numa_work.next = &p->numa_work; 4547 p->numa_faults = NULL; 4548 p->numa_pages_migrated = 0; 4549 p->total_numa_faults = 0; 4550 RCU_INIT_POINTER(p->numa_group, NULL); 4551 p->last_task_numa_placement = 0; 4552 p->last_sum_exec_runtime = 0; 4553 4554 init_task_work(&p->numa_work, task_numa_work); 4555 4556 /* New address space, reset the preferred nid */ 4557 if (!(clone_flags & CLONE_VM)) { 4558 p->numa_preferred_nid = NUMA_NO_NODE; 4559 return; 4560 } 4561 4562 /* 4563 * New thread, keep existing numa_preferred_nid which should be copied 4564 * already by arch_dup_task_struct but stagger when scans start. 4565 */ 4566 if (mm) { 4567 unsigned int delay; 4568 4569 delay = min_t(unsigned int, task_scan_max(current), 4570 current->numa_scan_period * mm_users * NSEC_PER_MSEC); 4571 delay += 2 * TICK_NSEC; 4572 p->node_stamp = delay; 4573 } 4574 } 4575 4576 /* 4577 * Drive the periodic memory faults.. 4578 */ 4579 static void task_tick_numa(struct rq *rq, struct task_struct *curr) 4580 { 4581 struct callback_head *work = &curr->numa_work; 4582 u64 period, now; 4583 4584 /* 4585 * We don't care about NUMA placement if we don't have memory. 4586 */ 4587 if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work) 4588 return; 4589 4590 /* 4591 * Using runtime rather than walltime has the dual advantage that 4592 * we (mostly) drive the selection from busy threads and that the 4593 * task needs to have done some actual work before we bother with 4594 * NUMA placement. 4595 */ 4596 now = curr->se.sum_exec_runtime; 4597 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC; 4598 4599 if (now > curr->node_stamp + period) { 4600 if (!curr->node_stamp) 4601 curr->numa_scan_period = task_scan_start(curr); 4602 curr->node_stamp += period; 4603 4604 if (!time_before(jiffies, curr->mm->numa_next_scan)) 4605 task_work_add(curr, work, TWA_RESUME); 4606 } 4607 } 4608 4609 static void update_scan_period(struct task_struct *p, int new_cpu) 4610 { 4611 int src_nid = cpu_to_node(task_cpu(p)); 4612 int dst_nid = cpu_to_node(new_cpu); 4613 4614 if (!static_branch_likely(&sched_numa_balancing)) 4615 return; 4616 4617 if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING)) 4618 return; 4619 4620 if (src_nid == dst_nid) 4621 return; 4622 4623 /* 4624 * Allow resets if faults have been trapped before one scan 4625 * has completed. This is most likely due to a new task that 4626 * is pulled cross-node due to wakeups or load balancing. 4627 */ 4628 if (p->numa_scan_seq) { 4629 /* 4630 * Avoid scan adjustments if moving to the preferred 4631 * node or if the task was not previously running on 4632 * the preferred node. 4633 */ 4634 if (dst_nid == p->numa_preferred_nid || 4635 (p->numa_preferred_nid != NUMA_NO_NODE && 4636 src_nid != p->numa_preferred_nid)) 4637 return; 4638 } 4639 4640 p->numa_scan_period = task_scan_start(p); 4641 } 4642 4643 #else /* !CONFIG_NUMA_BALANCING: */ 4644 4645 static void task_tick_numa(struct rq *rq, struct task_struct *curr) 4646 { 4647 } 4648 4649 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p) 4650 { 4651 } 4652 4653 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p) 4654 { 4655 } 4656 4657 static inline void update_scan_period(struct task_struct *p, int new_cpu) 4658 { 4659 } 4660 4661 #endif /* !CONFIG_NUMA_BALANCING */ 4662 4663 static void 4664 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se) 4665 { 4666 WARN_ON_ONCE(cfs_rq != cfs_rq_of(se)); 4667 update_load_add(&cfs_rq->load, se->load.weight); 4668 if (entity_is_task(se)) { 4669 struct task_struct *p = task_of(se); 4670 struct rq *rq = rq_of(cfs_rq); 4671 4672 account_numa_enqueue(rq, p); 4673 account_llc_enqueue(rq, p); 4674 list_add(&se->group_node, &rq->cfs_tasks); 4675 } 4676 cfs_rq->nr_queued++; 4677 } 4678 4679 static void 4680 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se) 4681 { 4682 WARN_ON_ONCE(cfs_rq != cfs_rq_of(se)); 4683 update_load_sub(&cfs_rq->load, se->load.weight); 4684 if (entity_is_task(se)) { 4685 struct task_struct *p = task_of(se); 4686 struct rq *rq = rq_of(cfs_rq); 4687 4688 account_numa_dequeue(rq, p); 4689 account_llc_dequeue(rq, p); 4690 list_del_init(&se->group_node); 4691 } 4692 cfs_rq->nr_queued--; 4693 } 4694 4695 /* 4696 * Signed add and clamp on underflow. 4697 * 4698 * Explicitly do a load-store to ensure the intermediate value never hits 4699 * memory. This allows lockless observations without ever seeing the negative 4700 * values. 4701 */ 4702 #define add_positive(_ptr, _val) do { \ 4703 typeof(_ptr) ptr = (_ptr); \ 4704 __signed_scalar_typeof(*ptr) val = (_val); \ 4705 typeof(*ptr) res, var = READ_ONCE(*ptr); \ 4706 \ 4707 res = var + val; \ 4708 \ 4709 if (val < 0 && res > var) \ 4710 res = 0; \ 4711 \ 4712 WRITE_ONCE(*ptr, res); \ 4713 } while (0) 4714 4715 /* 4716 * Remove and clamp on negative, from a local variable. 4717 * 4718 * A variant of sub_positive(), which does not use explicit load-store 4719 * and is thus optimized for local variable updates. 4720 */ 4721 #define lsub_positive(_ptr, _val) do { \ 4722 typeof(_ptr) ptr = (_ptr); \ 4723 *ptr -= min_t(typeof(*ptr), *ptr, _val); \ 4724 } while (0) 4725 4726 4727 /* 4728 * Because of rounding, se->util_sum might ends up being +1 more than 4729 * cfs->util_sum. Although this is not a problem by itself, detaching 4730 * a lot of tasks with the rounding problem between 2 updates of 4731 * util_avg (~1ms) can make cfs->util_sum becoming null whereas 4732 * cfs_util_avg is not. 4733 * 4734 * Check that util_sum is still above its lower bound for the new 4735 * util_avg. Given that period_contrib might have moved since the last 4736 * sync, we are only sure that util_sum must be above or equal to 4737 * util_avg * minimum possible divider 4738 */ 4739 #define __update_sa(sa, name, delta_avg, delta_sum) do { \ 4740 add_positive(&(sa)->name##_avg, delta_avg); \ 4741 add_positive(&(sa)->name##_sum, delta_sum); \ 4742 (sa)->name##_sum = max_t(typeof((sa)->name##_sum), \ 4743 (sa)->name##_sum, \ 4744 (sa)->name##_avg * PELT_MIN_DIVIDER); \ 4745 } while (0) 4746 4747 static inline void 4748 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) 4749 { 4750 __update_sa(&cfs_rq->avg, load, se->avg.load_avg, 4751 se_weight(se) * se->avg.load_sum); 4752 } 4753 4754 static inline void 4755 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) 4756 { 4757 __update_sa(&cfs_rq->avg, load, -se->avg.load_avg, 4758 se_weight(se) * -se->avg.load_sum); 4759 } 4760 4761 static void 4762 rescale_entity(struct sched_entity *se, unsigned long weight, bool rel_vprot) 4763 { 4764 long old_weight = se->h_load.weight; 4765 4766 /* 4767 * VRUNTIME 4768 * -------- 4769 * 4770 * COROLLARY #1: The virtual runtime of the entity needs to be 4771 * adjusted if re-weight at !0-lag point. 4772 * 4773 * Proof: For contradiction assume this is not true, so we can 4774 * re-weight without changing vruntime at !0-lag point. 4775 * 4776 * Weight VRuntime Avg-VRuntime 4777 * before w v V 4778 * after w' v' V' 4779 * 4780 * Since lag needs to be preserved through re-weight: 4781 * 4782 * lag = (V - v)*w = (V'- v')*w', where v = v' 4783 * ==> V' = (V - v)*w/w' + v (1) 4784 * 4785 * Let W be the total weight of the entities before reweight, 4786 * since V' is the new weighted average of entities: 4787 * 4788 * V' = (WV + w'v - wv) / (W + w' - w) (2) 4789 * 4790 * by using (1) & (2) we obtain: 4791 * 4792 * (WV + w'v - wv) / (W + w' - w) = (V - v)*w/w' + v 4793 * ==> (WV-Wv+Wv+w'v-wv)/(W+w'-w) = (V - v)*w/w' + v 4794 * ==> (WV - Wv)/(W + w' - w) + v = (V - v)*w/w' + v 4795 * ==> (V - v)*W/(W + w' - w) = (V - v)*w/w' (3) 4796 * 4797 * Since we are doing at !0-lag point which means V != v, we 4798 * can simplify (3): 4799 * 4800 * ==> W / (W + w' - w) = w / w' 4801 * ==> Ww' = Ww + ww' - ww 4802 * ==> W * (w' - w) = w * (w' - w) 4803 * ==> W = w (re-weight indicates w' != w) 4804 * 4805 * So the cfs_rq contains only one entity, hence vruntime of 4806 * the entity @v should always equal to the cfs_rq's weighted 4807 * average vruntime @V, which means we will always re-weight 4808 * at 0-lag point, thus breach assumption. Proof completed. 4809 * 4810 * 4811 * COROLLARY #2: Re-weight does NOT affect weighted average 4812 * vruntime of all the entities. 4813 * 4814 * Proof: According to corollary #1, Eq. (1) should be: 4815 * 4816 * (V - v)*w = (V' - v')*w' 4817 * ==> v' = V' - (V - v)*w/w' (4) 4818 * 4819 * According to the weighted average formula, we have: 4820 * 4821 * V' = (WV - wv + w'v') / (W - w + w') 4822 * = (WV - wv + w'(V' - (V - v)w/w')) / (W - w + w') 4823 * = (WV - wv + w'V' - Vw + wv) / (W - w + w') 4824 * = (WV + w'V' - Vw) / (W - w + w') 4825 * 4826 * ==> V'*(W - w + w') = WV + w'V' - Vw 4827 * ==> V' * (W - w) = (W - w) * V (5) 4828 * 4829 * If the entity is the only one in the cfs_rq, then reweight 4830 * always occurs at 0-lag point, so V won't change. Or else 4831 * there are other entities, hence W != w, then Eq. (5) turns 4832 * into V' = V. So V won't change in either case, proof done. 4833 * 4834 * 4835 * So according to corollary #1 & #2, the effect of re-weight 4836 * on vruntime should be: 4837 * 4838 * v' = V' - (V - v) * w / w' (4) 4839 * = V - (V - v) * w / w' 4840 * = V - vl * w / w' 4841 * = V - vl' 4842 */ 4843 se->vlag = div64_long(se->vlag * old_weight, weight); 4844 4845 /* 4846 * DEADLINE 4847 * -------- 4848 * 4849 * When the weight changes, the virtual time slope changes and 4850 * we should adjust the relative virtual deadline accordingly. 4851 * 4852 * d' = v' + (d - v)*w/w' 4853 * = V' - (V - v)*w/w' + (d - v)*w/w' 4854 * = V - (V - v)*w/w' + (d - v)*w/w' 4855 * = V + (d - V)*w/w' 4856 */ 4857 if (se->rel_deadline) 4858 se->deadline = div64_long(se->deadline * old_weight, weight); 4859 4860 if (rel_vprot) 4861 se->vprot = div64_long(se->vprot * old_weight, weight); 4862 } 4863 4864 static void reweight_eevdf(struct cfs_rq *cfs_rq, struct sched_entity *se, 4865 unsigned long weight, bool on_rq) 4866 { 4867 bool curr = cfs_rq->curr == se; 4868 bool rel_vprot = false; 4869 u64 avruntime = 0; 4870 4871 if (se->h_load.weight == weight) 4872 return; 4873 4874 if (on_rq) { 4875 avruntime = avg_vruntime(cfs_rq); 4876 se->vlag = entity_lag(cfs_rq, se, avruntime); 4877 se->deadline -= avruntime; 4878 se->rel_deadline = 1; 4879 if (curr && protect_slice(se)) { 4880 se->vprot -= avruntime; 4881 rel_vprot = true; 4882 } 4883 4884 cfs_rq->h_nr_queued--; 4885 if (!curr) 4886 __dequeue_entity(cfs_rq, se); 4887 } 4888 4889 rescale_entity(se, weight, rel_vprot); 4890 4891 update_load_set(&se->h_load, weight); 4892 4893 if (on_rq) { 4894 if (rel_vprot) 4895 se->vprot += avruntime; 4896 se->deadline += avruntime; 4897 se->rel_deadline = 0; 4898 se->vruntime = avruntime - se->vlag; 4899 4900 if (!curr) 4901 __enqueue_entity(cfs_rq, se); 4902 cfs_rq->h_nr_queued++; 4903 } 4904 } 4905 4906 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, 4907 unsigned long weight) 4908 { 4909 if (se->load.weight == weight) 4910 return; 4911 4912 if (se->on_rq) { 4913 WARN_ON_ONCE(cfs_rq != cfs_rq_of(se)); 4914 update_load_sub(&cfs_rq->load, se->load.weight); 4915 } 4916 dequeue_load_avg(cfs_rq, se); 4917 4918 update_load_set(&se->load, weight); 4919 4920 do { 4921 u32 divider = get_pelt_divider(&se->avg); 4922 se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider); 4923 } while (0); 4924 4925 enqueue_load_avg(cfs_rq, se); 4926 4927 if (se->on_rq) 4928 update_load_add(&cfs_rq->load, se->load.weight); 4929 } 4930 4931 /* 4932 * weight = NICE_0_LOAD; 4933 * for_each_entity_se(se) 4934 * weight = __calc_prop_weight(cfs_rq_of(se), se, weight); 4935 */ 4936 static __always_inline 4937 unsigned long __calc_prop_weight(struct cfs_rq *cfs_rq, struct sched_entity *se, 4938 unsigned long weight) 4939 { 4940 weight *= se->load.weight; 4941 if (parent_entity(se)) 4942 weight /= cfs_rq->load.weight; 4943 else 4944 weight /= NICE_0_LOAD; 4945 4946 return max(weight, MIN_SHARES); 4947 } 4948 4949 static void reweight_task_fair(struct rq *rq, struct task_struct *p, 4950 const struct load_weight *lw) 4951 { 4952 struct sched_entity *se = &p->se; 4953 unsigned long weight = NICE_0_LOAD; 4954 4955 if (se->on_rq) 4956 update_curr_fair(rq); 4957 4958 reweight_entity(cfs_rq_of(se), se, lw->weight); 4959 se->load.inv_weight = lw->inv_weight; 4960 4961 if (!se->on_rq) 4962 return; 4963 4964 for_each_sched_entity(se) 4965 weight = __calc_prop_weight(cfs_rq_of(se), se, weight); 4966 4967 reweight_eevdf(&rq->cfs, &p->se, weight, p->se.on_rq); 4968 } 4969 4970 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq); 4971 4972 #ifdef CONFIG_FAIR_GROUP_SCHED 4973 /* 4974 * All this does is approximate the hierarchical proportion which includes that 4975 * global sum we all love to hate. 4976 * 4977 * That is, the weight of a group entity, is the proportional share of the 4978 * group weight based on the group runqueue weights. That is: 4979 * 4980 * tg->weight * grq->load.weight 4981 * ge->load.weight = ----------------------------- (1) 4982 * \Sum grq->load.weight 4983 * 4984 * Now, because computing that sum is prohibitively expensive to compute (been 4985 * there, done that) we approximate it with this average stuff. The average 4986 * moves slower and therefore the approximation is cheaper and more stable. 4987 * 4988 * So instead of the above, we substitute: 4989 * 4990 * grq->load.weight -> grq->avg.load_avg (2) 4991 * 4992 * which yields the following: 4993 * 4994 * tg->weight * grq->avg.load_avg 4995 * ge->load.weight = ------------------------------ (3) 4996 * tg->load_avg 4997 * 4998 * Where: tg->load_avg ~= \Sum grq->avg.load_avg 4999 * 5000 * That is shares_avg, and it is right (given the approximation (2)). 5001 * 5002 * The problem with it is that because the average is slow -- it was designed 5003 * to be exactly that of course -- this leads to transients in boundary 5004 * conditions. In specific, the case where the group was idle and we start the 5005 * one task. It takes time for our CPU's grq->avg.load_avg to build up, 5006 * yielding bad latency etc.. 5007 * 5008 * Now, in that special case (1) reduces to: 5009 * 5010 * tg->weight * grq->load.weight 5011 * ge->load.weight = ----------------------------- = tg->weight (4) 5012 * grp->load.weight 5013 * 5014 * That is, the sum collapses because all other CPUs are idle; the UP scenario. 5015 * 5016 * So what we do is modify our approximation (3) to approach (4) in the (near) 5017 * UP case, like: 5018 * 5019 * ge->load.weight = 5020 * 5021 * tg->weight * grq->load.weight 5022 * --------------------------------------------------- (5) 5023 * tg->load_avg - grq->avg.load_avg + grq->load.weight 5024 * 5025 * But because grq->load.weight can drop to 0, resulting in a divide by zero, 5026 * we need to use grq->avg.load_avg as its lower bound, which then gives: 5027 * 5028 * 5029 * tg->weight * grq->load.weight 5030 * ge->load.weight = ----------------------------- (6) 5031 * tg_load_avg' 5032 * 5033 * Where: 5034 * 5035 * tg_load_avg' = tg->load_avg - grq->avg.load_avg + 5036 * max(grq->load.weight, grq->avg.load_avg) 5037 * 5038 * And that is shares_weight and is icky. In the (near) UP case it approaches 5039 * (4) while in the normal case it approaches (3). It consistently 5040 * overestimates the ge->load.weight and therefore: 5041 * 5042 * \Sum ge->load.weight >= tg->weight 5043 * 5044 * hence icky! 5045 */ 5046 static long __calc_smp_shares(struct cfs_rq *cfs_rq, long tg_shares, long shares_max) 5047 { 5048 struct task_group *tg = cfs_rq->tg; 5049 long tg_weight, load, shares; 5050 5051 load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg); 5052 5053 tg_weight = atomic_long_read(&tg->load_avg); 5054 5055 /* Ensure tg_weight >= load */ 5056 tg_weight -= cfs_rq->tg_load_avg_contrib; 5057 tg_weight += load; 5058 5059 shares = (tg_shares * load); 5060 if (tg_weight) 5061 shares /= tg_weight; 5062 5063 /* 5064 * MIN_SHARES has to be unscaled here to support per-CPU partitioning 5065 * of a group with small tg->shares value. It is a floor value which is 5066 * assigned as a minimum load.weight to the sched_entity representing 5067 * the group on a CPU. 5068 * 5069 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024 5070 * on an 8-core system with 8 tasks each runnable on one CPU shares has 5071 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In 5072 * case no task is runnable on a CPU MIN_SHARES=2 should be returned 5073 * instead of 0. 5074 */ 5075 return clamp_t(long, shares, MIN_SHARES, shares_max); 5076 } 5077 5078 static int tg_cpus(struct task_group *tg) 5079 { 5080 int nr = num_online_cpus(); 5081 5082 if (cpusets_enabled()) { 5083 struct cgroup *cgrp = tg->css.cgroup; 5084 if (cgrp) 5085 nr = cpuset_num_cpus(cgrp); 5086 } 5087 5088 /* 5089 * An empty cpuset would propagate a 0 shares_max into 5090 * __calc_smp_shares(), where clamp() yields hi when hi < lo and so 5091 * defeats the MIN_SHARES floor. Match tg_tasks(), which floors at 1. 5092 */ 5093 return max(nr, 1); 5094 } 5095 5096 static inline int tg_tasks(struct task_group *tg) 5097 { 5098 return max(1, atomic_long_read(&tg->runnable_avg) >> SCHED_CAPACITY_SHIFT); 5099 } 5100 5101 /* 5102 * Func: fraction(nr_tasks * tg->shares) 5103 * 5104 * Scale tg->shares by the number of tasks. 5105 */ 5106 static long calc_tasks_shares(struct cfs_rq *cfs_rq) 5107 { 5108 struct task_group *tg = cfs_rq->tg; 5109 int nr = tg_tasks(tg); 5110 long tg_shares = READ_ONCE(tg->shares); 5111 return __calc_smp_shares(cfs_rq, nr * tg_shares, nr * tg_shares); 5112 } 5113 5114 /* 5115 * Func: min(fraction(nr_cpus * tg->shares), nice -20) 5116 * 5117 * Scale tg->shares by the maximal number of CPUs; but clip the max shares at 5118 * nice -20, otherwise a single spinner on a 512 CPU machine would result in 5119 * 512*NICE_0_LOAD, which is also crazy. 5120 */ 5121 static long calc_max_shares(struct cfs_rq *cfs_rq) 5122 { 5123 struct task_group *tg = cfs_rq->tg; 5124 int nr = tg_cpus(tg); 5125 long tg_shares = READ_ONCE(tg->shares); 5126 long max_shares = scale_load(sched_prio_to_weight[0]); 5127 return __calc_smp_shares(cfs_rq, tg_shares * nr, max_shares); 5128 } 5129 5130 /* 5131 * Func: fraction(nr * tg->shares); nr = min(nr_tasks, nr_cpus) 5132 * 5133 * Scales between "smp" and "max" in a natural way. No longer needs clipping 5134 * since there are no unnatural inflations like with "max". 5135 */ 5136 static long calc_concur_shares(struct cfs_rq *cfs_rq) 5137 { 5138 struct task_group *tg = cfs_rq->tg; 5139 int nr = min(tg_tasks(tg), tg_cpus(tg)); 5140 long tg_shares = READ_ONCE(tg->shares); 5141 return __calc_smp_shares(cfs_rq, nr * tg_shares, nr * tg_shares); 5142 } 5143 5144 /* 5145 * Func: fraction(tg->shares) 5146 * 5147 * This infamously results in tiny shares when you have many CPUs. 5148 */ 5149 static long calc_smp_shares(struct cfs_rq *cfs_rq) 5150 { 5151 struct task_group *tg = cfs_rq->tg; 5152 long tg_shares = READ_ONCE(tg->shares); 5153 return __calc_smp_shares(cfs_rq, tg_shares, tg_shares); 5154 } 5155 5156 /* 5157 * Ignore this pesky SMP stuff, use (4). 5158 */ 5159 static long calc_up_shares(struct cfs_rq *cfs_rq) 5160 { 5161 struct task_group *tg = cfs_rq->tg; 5162 return READ_ONCE(tg->shares); 5163 } 5164 5165 DEFINE_STATIC_CALL(calc_group_shares, calc_concur_shares); 5166 5167 void __sched_cgroup_mode_update(int mode) 5168 { 5169 long (*func)(struct cfs_rq *); 5170 switch (mode) { 5171 case 0: 5172 func = &calc_up_shares; 5173 break; 5174 case 1: 5175 func = &calc_smp_shares; 5176 break; 5177 case 2: 5178 default: 5179 func = &calc_concur_shares; 5180 break; 5181 case 3: 5182 func = &calc_max_shares; 5183 break; 5184 case 4: 5185 func = &calc_tasks_shares; 5186 break; 5187 } 5188 static_call_update(calc_group_shares, func); 5189 } 5190 5191 /* 5192 * Recomputes the group entity based on the current state of its group 5193 * runqueue. 5194 */ 5195 static void update_cfs_group(struct sched_entity *se) 5196 { 5197 struct cfs_rq *gcfs_rq = group_cfs_rq(se); 5198 long shares; 5199 5200 /* 5201 * When a group becomes empty, preserve its weight. This matters for 5202 * DELAY_DEQUEUE. 5203 */ 5204 if (!gcfs_rq || !gcfs_rq->load.weight) 5205 return; 5206 5207 shares = static_call(calc_group_shares)(gcfs_rq); 5208 reweight_entity(cfs_rq_of(se), se, shares); 5209 } 5210 5211 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 5212 static inline void update_cfs_group(struct sched_entity *se) 5213 { 5214 } 5215 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 5216 5217 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags) 5218 { 5219 struct rq *rq = rq_of(cfs_rq); 5220 5221 if (&rq->cfs == cfs_rq) { 5222 /* 5223 * There are a few boundary cases this might miss but it should 5224 * get called often enough that that should (hopefully) not be 5225 * a real problem. 5226 * 5227 * It will not get called when we go idle, because the idle 5228 * thread is a different class (!fair), nor will the utilization 5229 * number include things like RT tasks. 5230 * 5231 * As is, the util number is not freq-invariant (we'd have to 5232 * implement arch_scale_freq_capacity() for that). 5233 * 5234 * See cpu_util_cfs(). 5235 */ 5236 cpufreq_update_util(rq, flags); 5237 } 5238 } 5239 5240 static inline bool load_avg_is_decayed(struct sched_avg *sa) 5241 { 5242 if (sa->load_sum) 5243 return false; 5244 5245 if (sa->util_sum) 5246 return false; 5247 5248 if (sa->runnable_sum) 5249 return false; 5250 5251 /* 5252 * _avg must be null when _sum are null because _avg = _sum / divider 5253 * Make sure that rounding and/or propagation of PELT values never 5254 * break this. 5255 */ 5256 WARN_ON_ONCE(sa->load_avg || 5257 sa->util_avg || 5258 sa->runnable_avg); 5259 5260 return true; 5261 } 5262 5263 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq) 5264 { 5265 return u64_u32_load_copy(cfs_rq->avg.last_update_time, 5266 cfs_rq->last_update_time_copy); 5267 } 5268 #ifdef CONFIG_FAIR_GROUP_SCHED 5269 /* 5270 * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list 5271 * immediately before a parent cfs_rq, and cfs_rqs are removed from the list 5272 * bottom-up, we only have to test whether the cfs_rq before us on the list 5273 * is our child. 5274 * If cfs_rq is not on the list, test whether a child needs its to be added to 5275 * connect a branch to the tree * (see list_add_leaf_cfs_rq() for details). 5276 */ 5277 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq) 5278 { 5279 struct cfs_rq *prev_cfs_rq; 5280 struct list_head *prev; 5281 struct rq *rq = rq_of(cfs_rq); 5282 5283 if (cfs_rq->on_list) { 5284 prev = cfs_rq->leaf_cfs_rq_list.prev; 5285 } else { 5286 prev = rq->tmp_alone_branch; 5287 } 5288 5289 if (prev == &rq->leaf_cfs_rq_list) 5290 return false; 5291 5292 prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list); 5293 5294 return (prev_cfs_rq->tg->parent == cfs_rq->tg); 5295 } 5296 5297 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq) 5298 { 5299 if (cfs_rq->load.weight) 5300 return false; 5301 5302 if (!load_avg_is_decayed(&cfs_rq->avg)) 5303 return false; 5304 5305 if (child_cfs_rq_on_list(cfs_rq)) 5306 return false; 5307 5308 if (cfs_rq->tg_load_avg_contrib) 5309 return false; 5310 5311 return true; 5312 } 5313 5314 /** 5315 * update_tg_load_avg - update the tg's load avg 5316 * @cfs_rq: the cfs_rq whose avg changed 5317 * 5318 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load. 5319 * However, because tg->load_avg is a global value there are performance 5320 * considerations. 5321 * 5322 * In order to avoid having to look at the other cfs_rq's, we use a 5323 * differential update where we store the last value we propagated. This in 5324 * turn allows skipping updates if the differential is 'small'. 5325 * 5326 * Updating tg's load_avg is necessary before update_cfs_group(). 5327 */ 5328 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) 5329 { 5330 long dl, dr; 5331 u64 now; 5332 5333 /* 5334 * No need to update load_avg for root_task_group as it is not used. 5335 */ 5336 if (cfs_rq->tg == &root_task_group) 5337 return; 5338 5339 /* rq has been offline and doesn't contribute to the share anymore: */ 5340 if (!cpu_active(cpu_of(rq_of(cfs_rq)))) 5341 return; 5342 5343 /* 5344 * For migration heavy workloads, access to tg->load_avg can be 5345 * unbound. Limit the update rate to at most once per ms. 5346 */ 5347 now = rq_clock(rq_of(cfs_rq)); 5348 if (now - cfs_rq->last_update_tg_load_avg < NSEC_PER_MSEC) 5349 return; 5350 5351 dl = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib; 5352 dr = cfs_rq->avg.runnable_avg - cfs_rq->tg_runnable_avg_contrib; 5353 if (abs(dl) > cfs_rq->tg_load_avg_contrib / 64 || 5354 abs(dr) > cfs_rq->tg_runnable_avg_contrib / 64) { 5355 atomic_long_add(dl, &cfs_rq->tg->load_avg); 5356 atomic_long_add(dr, &cfs_rq->tg->runnable_avg); 5357 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg; 5358 cfs_rq->tg_runnable_avg_contrib = cfs_rq->avg.runnable_avg; 5359 cfs_rq->last_update_tg_load_avg = now; 5360 } 5361 } 5362 5363 static inline void clear_tg_load_avg(struct cfs_rq *cfs_rq) 5364 { 5365 long dl, dr; 5366 u64 now; 5367 5368 /* 5369 * No need to update load_avg for root_task_group, as it is not used. 5370 */ 5371 if (cfs_rq->tg == &root_task_group) 5372 return; 5373 5374 now = rq_clock(rq_of(cfs_rq)); 5375 dl = 0 - cfs_rq->tg_load_avg_contrib; 5376 dr = 0 - cfs_rq->tg_runnable_avg_contrib; 5377 atomic_long_add(dl, &cfs_rq->tg->load_avg); 5378 atomic_long_add(dr, &cfs_rq->tg->runnable_avg); 5379 cfs_rq->tg_load_avg_contrib = 0; 5380 cfs_rq->tg_runnable_avg_contrib = 0; 5381 cfs_rq->last_update_tg_load_avg = now; 5382 } 5383 5384 /* CPU offline callback: */ 5385 static void __maybe_unused clear_tg_offline_cfs_rqs(struct rq *rq) 5386 { 5387 struct task_group *tg; 5388 5389 lockdep_assert_rq_held(rq); 5390 5391 /* 5392 * The rq clock has already been updated in 5393 * set_rq_offline(), so we should skip updating 5394 * the rq clock again in unthrottle_cfs_rq(). 5395 */ 5396 rq_clock_start_loop_update(rq); 5397 5398 guard(rcu)(); 5399 5400 list_for_each_entry_rcu(tg, &task_groups, list) { 5401 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq)); 5402 5403 clear_tg_load_avg(cfs_rq); 5404 } 5405 5406 rq_clock_stop_loop_update(rq); 5407 } 5408 5409 /* 5410 * Called within set_task_rq() right before setting a task's CPU. The 5411 * caller only guarantees p->pi_lock is held; no other assumptions, 5412 * including the state of rq->lock, should be made. 5413 */ 5414 void set_task_rq_fair(struct sched_entity *se, 5415 struct cfs_rq *prev, struct cfs_rq *next) 5416 { 5417 u64 p_last_update_time; 5418 u64 n_last_update_time; 5419 5420 if (!sched_feat(ATTACH_AGE_LOAD)) 5421 return; 5422 5423 /* 5424 * We are supposed to update the task to "current" time, then its up to 5425 * date and ready to go to new CPU/cfs_rq. But we have difficulty in 5426 * getting what current time is, so simply throw away the out-of-date 5427 * time. This will result in the wakee task is less decayed, but giving 5428 * the wakee more load sounds not bad. 5429 */ 5430 if (!(se->avg.last_update_time && prev)) 5431 return; 5432 5433 p_last_update_time = cfs_rq_last_update_time(prev); 5434 n_last_update_time = cfs_rq_last_update_time(next); 5435 5436 __update_load_avg_blocked_se(p_last_update_time, se); 5437 se->avg.last_update_time = n_last_update_time; 5438 } 5439 5440 /* 5441 * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to 5442 * propagate its contribution. The key to this propagation is the invariant 5443 * that for each group: 5444 * 5445 * ge->avg == grq->avg (1) 5446 * 5447 * _IFF_ we look at the pure running and runnable sums. Because they 5448 * represent the very same entity, just at different points in the hierarchy. 5449 * 5450 * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial 5451 * and simply copies the running/runnable sum over (but still wrong, because 5452 * the group entity and group rq do not have their PELT windows aligned). 5453 * 5454 * However, update_tg_cfs_load() is more complex. So we have: 5455 * 5456 * ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg (2) 5457 * 5458 * And since, like util, the runnable part should be directly transferable, 5459 * the following would _appear_ to be the straight forward approach: 5460 * 5461 * grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg (3) 5462 * 5463 * And per (1) we have: 5464 * 5465 * ge->avg.runnable_avg == grq->avg.runnable_avg 5466 * 5467 * Which gives: 5468 * 5469 * ge->load.weight * grq->avg.load_avg 5470 * ge->avg.load_avg = ----------------------------------- (4) 5471 * grq->load.weight 5472 * 5473 * Except that is wrong! 5474 * 5475 * Because while for entities historical weight is not important and we 5476 * really only care about our future and therefore can consider a pure 5477 * runnable sum, runqueues can NOT do this. 5478 * 5479 * We specifically want runqueues to have a load_avg that includes 5480 * historical weights. Those represent the blocked load, the load we expect 5481 * to (shortly) return to us. This only works by keeping the weights as 5482 * integral part of the sum. We therefore cannot decompose as per (3). 5483 * 5484 * Another reason this doesn't work is that runnable isn't a 0-sum entity. 5485 * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the 5486 * rq itself is runnable anywhere between 2/3 and 1 depending on how the 5487 * runnable section of these tasks overlap (or not). If they were to perfectly 5488 * align the rq as a whole would be runnable 2/3 of the time. If however we 5489 * always have at least 1 runnable task, the rq as a whole is always runnable. 5490 * 5491 * So we'll have to approximate.. :/ 5492 * 5493 * Given the constraint: 5494 * 5495 * ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX 5496 * 5497 * We can construct a rule that adds runnable to a rq by assuming minimal 5498 * overlap. 5499 * 5500 * On removal, we'll assume each task is equally runnable; which yields: 5501 * 5502 * grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight 5503 * 5504 * XXX: only do this for the part of runnable > running ? 5505 * 5506 */ 5507 static inline void 5508 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq) 5509 { 5510 long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg; 5511 u32 new_sum, divider; 5512 5513 /* Nothing to update */ 5514 if (!delta_avg) 5515 return; 5516 5517 /* 5518 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se. 5519 * See ___update_load_avg() for details. 5520 */ 5521 divider = get_pelt_divider(&cfs_rq->avg); 5522 5523 /* Set new sched_entity's utilization */ 5524 se->avg.util_avg = gcfs_rq->avg.util_avg; 5525 new_sum = se->avg.util_avg * divider; 5526 delta_sum = (long)new_sum - (long)se->avg.util_sum; 5527 se->avg.util_sum = new_sum; 5528 5529 /* Update parent cfs_rq utilization */ 5530 __update_sa(&cfs_rq->avg, util, delta_avg, delta_sum); 5531 } 5532 5533 static inline void 5534 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq) 5535 { 5536 long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg; 5537 u64 new_sum; 5538 u32 divider; 5539 5540 /* Nothing to update */ 5541 if (!delta_avg) 5542 return; 5543 5544 /* 5545 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se. 5546 * See ___update_load_avg() for details. 5547 */ 5548 divider = get_pelt_divider(&cfs_rq->avg); 5549 5550 /* Set new sched_entity's runnable */ 5551 se->avg.runnable_avg = gcfs_rq->avg.runnable_avg; 5552 new_sum = (u64)se->avg.runnable_avg * divider; 5553 delta_sum = (long)new_sum - (long)se->avg.runnable_sum; 5554 se->avg.runnable_sum = new_sum; 5555 5556 /* Update parent cfs_rq runnable */ 5557 __update_sa(&cfs_rq->avg, runnable, delta_avg, delta_sum); 5558 } 5559 5560 static inline void 5561 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq) 5562 { 5563 long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum; 5564 unsigned long load_avg; 5565 u64 load_sum = 0; 5566 s64 delta_sum; 5567 u32 divider; 5568 5569 if (!runnable_sum) 5570 return; 5571 5572 gcfs_rq->prop_runnable_sum = 0; 5573 5574 /* 5575 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se. 5576 * See ___update_load_avg() for details. 5577 */ 5578 divider = get_pelt_divider(&cfs_rq->avg); 5579 5580 if (runnable_sum >= 0) { 5581 /* 5582 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until 5583 * the CPU is saturated running == runnable. 5584 */ 5585 runnable_sum += se->avg.load_sum; 5586 runnable_sum = min_t(long, runnable_sum, divider); 5587 } else { 5588 /* 5589 * Estimate the new unweighted runnable_sum of the gcfs_rq by 5590 * assuming all tasks are equally runnable. 5591 */ 5592 if (scale_load_down(gcfs_rq->load.weight)) { 5593 load_sum = div_u64(gcfs_rq->avg.load_sum, 5594 scale_load_down(gcfs_rq->load.weight)); 5595 } 5596 5597 /* But make sure to not inflate se's runnable */ 5598 runnable_sum = min(se->avg.load_sum, load_sum); 5599 } 5600 5601 /* 5602 * runnable_sum can't be lower than running_sum 5603 * Rescale running sum to be in the same range as runnable sum 5604 * running_sum is in [0 : LOAD_AVG_MAX << SCHED_CAPACITY_SHIFT] 5605 * runnable_sum is in [0 : LOAD_AVG_MAX] 5606 */ 5607 running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT; 5608 runnable_sum = max(runnable_sum, running_sum); 5609 5610 load_sum = se_weight(se) * runnable_sum; 5611 load_avg = div_u64(load_sum, divider); 5612 5613 delta_avg = load_avg - se->avg.load_avg; 5614 if (!delta_avg) 5615 return; 5616 5617 delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum; 5618 5619 se->avg.load_sum = runnable_sum; 5620 se->avg.load_avg = load_avg; 5621 __update_sa(&cfs_rq->avg, load, delta_avg, delta_sum); 5622 } 5623 5624 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) 5625 { 5626 cfs_rq->propagate = 1; 5627 cfs_rq->prop_runnable_sum += runnable_sum; 5628 } 5629 5630 /* Update task and its cfs_rq load average */ 5631 static inline int propagate_entity_load_avg(struct sched_entity *se) 5632 { 5633 struct cfs_rq *cfs_rq, *gcfs_rq; 5634 5635 if (entity_is_task(se)) 5636 return 0; 5637 5638 gcfs_rq = group_cfs_rq(se); 5639 if (!gcfs_rq->propagate) 5640 return 0; 5641 5642 gcfs_rq->propagate = 0; 5643 5644 cfs_rq = cfs_rq_of(se); 5645 5646 add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum); 5647 5648 update_tg_cfs_util(cfs_rq, se, gcfs_rq); 5649 update_tg_cfs_runnable(cfs_rq, se, gcfs_rq); 5650 update_tg_cfs_load(cfs_rq, se, gcfs_rq); 5651 5652 trace_pelt_cfs_tp(cfs_rq); 5653 trace_pelt_se_tp(se); 5654 5655 return 1; 5656 } 5657 5658 /* 5659 * Check if we need to update the load and the utilization of a blocked 5660 * group_entity: 5661 */ 5662 static inline bool skip_blocked_update(struct sched_entity *se) 5663 { 5664 struct cfs_rq *gcfs_rq = group_cfs_rq(se); 5665 5666 /* 5667 * If sched_entity still have not zero load or utilization, we have to 5668 * decay it: 5669 */ 5670 if (se->avg.load_avg || se->avg.util_avg) 5671 return false; 5672 5673 /* 5674 * If there is a pending propagation, we have to update the load and 5675 * the utilization of the sched_entity: 5676 */ 5677 if (gcfs_rq->propagate) 5678 return false; 5679 5680 /* 5681 * Otherwise, the load and the utilization of the sched_entity is 5682 * already zero and there is no pending propagation, so it will be a 5683 * waste of time to try to decay it: 5684 */ 5685 return true; 5686 } 5687 5688 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 5689 5690 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {} 5691 5692 static inline void clear_tg_offline_cfs_rqs(struct rq *rq) {} 5693 5694 static inline int propagate_entity_load_avg(struct sched_entity *se) 5695 { 5696 return 0; 5697 } 5698 5699 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {} 5700 5701 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 5702 5703 #ifdef CONFIG_NO_HZ_COMMON 5704 static inline void migrate_se_pelt_lag(struct sched_entity *se) 5705 { 5706 u64 throttled = 0, now, lut; 5707 struct cfs_rq *cfs_rq; 5708 struct rq *rq; 5709 bool is_idle; 5710 5711 if (load_avg_is_decayed(&se->avg)) 5712 return; 5713 5714 cfs_rq = cfs_rq_of(se); 5715 rq = rq_of(cfs_rq); 5716 5717 rcu_read_lock(); 5718 is_idle = is_idle_task(rcu_dereference_all(rq->curr)); 5719 rcu_read_unlock(); 5720 5721 /* 5722 * The lag estimation comes with a cost we don't want to pay all the 5723 * time. Hence, limiting to the case where the source CPU is idle and 5724 * we know we are at the greatest risk to have an outdated clock. 5725 */ 5726 if (!is_idle) 5727 return; 5728 5729 /* 5730 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where: 5731 * 5732 * last_update_time (the cfs_rq's last_update_time) 5733 * = cfs_rq_clock_pelt()@cfs_rq_idle 5734 * = rq_clock_pelt()@cfs_rq_idle 5735 * - cfs->throttled_clock_pelt_time@cfs_rq_idle 5736 * 5737 * cfs_idle_lag (delta between rq's update and cfs_rq's update) 5738 * = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle 5739 * 5740 * rq_idle_lag (delta between now and rq's update) 5741 * = sched_clock_cpu() - rq_clock()@rq_idle 5742 * 5743 * We can then write: 5744 * 5745 * now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time + 5746 * sched_clock_cpu() - rq_clock()@rq_idle 5747 * Where: 5748 * rq_clock_pelt()@rq_idle is rq->clock_pelt_idle 5749 * rq_clock()@rq_idle is rq->clock_idle 5750 * cfs->throttled_clock_pelt_time@cfs_rq_idle 5751 * is cfs_rq->throttled_pelt_idle 5752 */ 5753 5754 #ifdef CONFIG_CFS_BANDWIDTH 5755 throttled = u64_u32_load(cfs_rq->throttled_pelt_idle); 5756 /* The clock has been stopped for throttling */ 5757 if (throttled == U64_MAX) 5758 return; 5759 #endif 5760 now = u64_u32_load(rq->clock_pelt_idle); 5761 /* 5762 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case 5763 * is observed the old clock_pelt_idle value and the new clock_idle, 5764 * which lead to an underestimation. The opposite would lead to an 5765 * overestimation. 5766 */ 5767 smp_rmb(); 5768 lut = cfs_rq_last_update_time(cfs_rq); 5769 5770 now -= throttled; 5771 if (now < lut) 5772 /* 5773 * cfs_rq->avg.last_update_time is more recent than our 5774 * estimation, let's use it. 5775 */ 5776 now = lut; 5777 else 5778 now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle); 5779 5780 __update_load_avg_blocked_se(now, se); 5781 } 5782 #else /* !CONFIG_NO_HZ_COMMON: */ 5783 static void migrate_se_pelt_lag(struct sched_entity *se) {} 5784 #endif /* !CONFIG_NO_HZ_COMMON */ 5785 5786 /** 5787 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages 5788 * @now: current time, as per cfs_rq_clock_pelt() 5789 * @cfs_rq: cfs_rq to update 5790 * 5791 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable) 5792 * avg. The immediate corollary is that all (fair) tasks must be attached. 5793 * 5794 * cfs_rq->avg is used for task_h_load() and update_cfs_group() for example. 5795 * 5796 * Return: true if the load decayed or we removed load. 5797 * 5798 * Since both these conditions indicate a changed cfs_rq->avg.load we should 5799 * call update_tg_load_avg() when this function returns true. 5800 */ 5801 static inline int 5802 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq) 5803 { 5804 unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0; 5805 struct sched_avg *sa = &cfs_rq->avg; 5806 int decayed = 0; 5807 5808 if (cfs_rq->removed.nr) { 5809 unsigned long r; 5810 u32 divider = get_pelt_divider(&cfs_rq->avg); 5811 5812 raw_spin_lock(&cfs_rq->removed.lock); 5813 swap(cfs_rq->removed.util_avg, removed_util); 5814 swap(cfs_rq->removed.load_avg, removed_load); 5815 swap(cfs_rq->removed.runnable_avg, removed_runnable); 5816 cfs_rq->removed.nr = 0; 5817 raw_spin_unlock(&cfs_rq->removed.lock); 5818 5819 r = removed_load; 5820 __update_sa(sa, load, -r, -r*divider); 5821 5822 r = removed_util; 5823 __update_sa(sa, util, -r, -r*divider); 5824 5825 r = removed_runnable; 5826 __update_sa(sa, runnable, -r, -r*divider); 5827 5828 /* 5829 * removed_runnable is the unweighted version of removed_load so we 5830 * can use it to estimate removed_load_sum. 5831 */ 5832 add_tg_cfs_propagate(cfs_rq, 5833 -(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT); 5834 5835 decayed = 1; 5836 } 5837 5838 decayed |= __update_load_avg_cfs_rq(now, cfs_rq); 5839 u64_u32_store_copy(sa->last_update_time, 5840 cfs_rq->last_update_time_copy, 5841 sa->last_update_time); 5842 return decayed; 5843 } 5844 5845 /** 5846 * attach_entity_load_avg - attach this entity to its cfs_rq load avg 5847 * @cfs_rq: cfs_rq to attach to 5848 * @se: sched_entity to attach 5849 * 5850 * Must call update_cfs_rq_load_avg() before this, since we rely on 5851 * cfs_rq->avg.last_update_time being current. 5852 */ 5853 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) 5854 { 5855 /* 5856 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se. 5857 * See ___update_load_avg() for details. 5858 */ 5859 u32 divider = get_pelt_divider(&cfs_rq->avg); 5860 5861 /* 5862 * When we attach the @se to the @cfs_rq, we must align the decay 5863 * window because without that, really weird and wonderful things can 5864 * happen. 5865 * 5866 * XXX illustrate 5867 */ 5868 se->avg.last_update_time = cfs_rq->avg.last_update_time; 5869 se->avg.period_contrib = cfs_rq->avg.period_contrib; 5870 5871 /* 5872 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new 5873 * period_contrib. This isn't strictly correct, but since we're 5874 * entirely outside of the PELT hierarchy, nobody cares if we truncate 5875 * _sum a little. 5876 */ 5877 se->avg.util_sum = se->avg.util_avg * divider; 5878 5879 se->avg.runnable_sum = se->avg.runnable_avg * divider; 5880 5881 se->avg.load_sum = se->avg.load_avg * divider; 5882 if (se_weight(se) < se->avg.load_sum) 5883 se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se)); 5884 else 5885 se->avg.load_sum = 1; 5886 5887 enqueue_load_avg(cfs_rq, se); 5888 cfs_rq->avg.util_avg += se->avg.util_avg; 5889 cfs_rq->avg.util_sum += se->avg.util_sum; 5890 cfs_rq->avg.runnable_avg += se->avg.runnable_avg; 5891 cfs_rq->avg.runnable_sum += se->avg.runnable_sum; 5892 5893 add_tg_cfs_propagate(cfs_rq, se->avg.load_sum); 5894 5895 cfs_rq_util_change(cfs_rq, 0); 5896 5897 trace_pelt_cfs_tp(cfs_rq); 5898 } 5899 5900 /** 5901 * detach_entity_load_avg - detach this entity from its cfs_rq load avg 5902 * @cfs_rq: cfs_rq to detach from 5903 * @se: sched_entity to detach 5904 * 5905 * Must call update_cfs_rq_load_avg() before this, since we rely on 5906 * cfs_rq->avg.last_update_time being current. 5907 */ 5908 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) 5909 { 5910 dequeue_load_avg(cfs_rq, se); 5911 __update_sa(&cfs_rq->avg, util, -se->avg.util_avg, -se->avg.util_sum); 5912 __update_sa(&cfs_rq->avg, runnable, -se->avg.runnable_avg, -se->avg.runnable_sum); 5913 5914 add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum); 5915 5916 cfs_rq_util_change(cfs_rq, 0); 5917 5918 trace_pelt_cfs_tp(cfs_rq); 5919 } 5920 5921 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100) 5922 5923 static inline void util_est_update(struct sched_entity *se) 5924 { 5925 unsigned int ewma, dequeued, last_ewma_diff; 5926 5927 if (!sched_feat(UTIL_EST)) 5928 return; 5929 5930 /* Get current estimate of utilization */ 5931 ewma = READ_ONCE(se->avg.util_est); 5932 5933 /* 5934 * If the PELT values haven't changed since enqueue time, 5935 * skip the util_est update. 5936 */ 5937 if (ewma & UTIL_AVG_UNCHANGED) 5938 return; 5939 5940 /* Get utilization at dequeue */ 5941 dequeued = READ_ONCE(se->avg.util_avg); 5942 5943 /* 5944 * Reset EWMA on utilization increases, the moving average is used only 5945 * to smooth utilization decreases. 5946 */ 5947 if (ewma <= dequeued) { 5948 ewma = dequeued; 5949 goto done; 5950 } 5951 5952 /* 5953 * Skip update of task's estimated utilization when its members are 5954 * already ~1% close to its last activation value. 5955 */ 5956 last_ewma_diff = ewma - dequeued; 5957 if (last_ewma_diff < UTIL_EST_MARGIN) 5958 goto done; 5959 5960 /* 5961 * To avoid underestimate of task utilization, skip updates of EWMA if 5962 * we cannot grant that thread got all CPU time it wanted. 5963 */ 5964 if ((dequeued + UTIL_EST_MARGIN) < READ_ONCE(se->avg.runnable_avg)) 5965 goto done; 5966 5967 /* 5968 * Update Task's estimated utilization 5969 * 5970 * When *p completes an activation we can consolidate another sample 5971 * of the task size. This is done by using this value to update the 5972 * Exponential Weighted Moving Average (EWMA): 5973 * 5974 * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1) 5975 * = w * task_util(p) + ewma(t-1) - w * ewma(t-1) 5976 * = w * (task_util(p) - ewma(t-1)) + ewma(t-1) 5977 * = w * ( -last_ewma_diff ) + ewma(t-1) 5978 * = w * (-last_ewma_diff + ewma(t-1) / w) 5979 * 5980 * Where 'w' is the weight of new samples, which is configured to be 5981 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT) 5982 */ 5983 ewma <<= UTIL_EST_WEIGHT_SHIFT; 5984 ewma -= last_ewma_diff; 5985 ewma >>= UTIL_EST_WEIGHT_SHIFT; 5986 done: 5987 ewma |= UTIL_AVG_UNCHANGED; 5988 WRITE_ONCE(se->avg.util_est, ewma); 5989 5990 trace_sched_util_est_se_tp(se); 5991 } 5992 5993 /* 5994 * Optional action to be done while updating the load average 5995 */ 5996 #define UPDATE_TG 0x01 5997 #define SKIP_AGE_LOAD 0x02 5998 #define DO_ATTACH 0x04 5999 #define DO_DETACH 0x08 6000 #define UPDATE_UTIL_EST 0x10 6001 6002 /* Update task and its cfs_rq load average */ 6003 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 6004 { 6005 u64 now = cfs_rq_clock_pelt(cfs_rq); 6006 int decayed; 6007 6008 /* 6009 * Track task load average for carrying it to new CPU after migrated, and 6010 * track group sched_entity load average for task_h_load calculation in migration 6011 */ 6012 if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD)) 6013 __update_load_avg_se(now, cfs_rq, se); 6014 6015 decayed = update_cfs_rq_load_avg(now, cfs_rq); 6016 decayed |= propagate_entity_load_avg(se); 6017 6018 if (!se->avg.last_update_time && (flags & DO_ATTACH)) { 6019 6020 /* 6021 * DO_ATTACH means we're here from enqueue_entity(). 6022 * !last_update_time means we've passed through 6023 * migrate_task_rq_fair() indicating we migrated. 6024 * 6025 * IOW we're enqueueing a task on a new CPU. 6026 */ 6027 attach_entity_load_avg(cfs_rq, se); 6028 update_tg_load_avg(cfs_rq); 6029 6030 } else if (flags & DO_DETACH) { 6031 /* 6032 * DO_DETACH means we're here from dequeue_entity() 6033 * and we are migrating task out of the CPU. 6034 */ 6035 detach_entity_load_avg(cfs_rq, se); 6036 update_tg_load_avg(cfs_rq); 6037 } else if (decayed) { 6038 cfs_rq_util_change(cfs_rq, 0); 6039 6040 if (flags & UPDATE_TG) 6041 update_tg_load_avg(cfs_rq); 6042 } 6043 6044 if (flags & UPDATE_UTIL_EST) 6045 util_est_update(se); 6046 } 6047 6048 /* 6049 * Synchronize entity load avg of dequeued entity without locking 6050 * the previous rq. 6051 */ 6052 static void sync_entity_load_avg(struct sched_entity *se) 6053 { 6054 struct cfs_rq *cfs_rq = cfs_rq_of(se); 6055 u64 last_update_time; 6056 6057 last_update_time = cfs_rq_last_update_time(cfs_rq); 6058 __update_load_avg_blocked_se(last_update_time, se); 6059 } 6060 6061 /* 6062 * Task first catches up with cfs_rq, and then subtract 6063 * itself from the cfs_rq (task must be off the queue now). 6064 */ 6065 static void remove_entity_load_avg(struct sched_entity *se) 6066 { 6067 struct cfs_rq *cfs_rq = cfs_rq_of(se); 6068 unsigned long flags; 6069 6070 /* 6071 * tasks cannot exit without having gone through wake_up_new_task() -> 6072 * enqueue_task_fair() which will have added things to the cfs_rq, 6073 * so we can remove unconditionally. 6074 */ 6075 6076 sync_entity_load_avg(se); 6077 6078 raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags); 6079 ++cfs_rq->removed.nr; 6080 cfs_rq->removed.util_avg += se->avg.util_avg; 6081 cfs_rq->removed.load_avg += se->avg.load_avg; 6082 cfs_rq->removed.runnable_avg += se->avg.runnable_avg; 6083 raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags); 6084 } 6085 6086 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq) 6087 { 6088 return cfs_rq->avg.runnable_avg; 6089 } 6090 6091 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq) 6092 { 6093 return cfs_rq->avg.load_avg; 6094 } 6095 6096 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf) 6097 __must_hold(__rq_lockp(this_rq)); 6098 6099 static inline unsigned long task_util(struct task_struct *p) 6100 { 6101 return READ_ONCE(p->se.avg.util_avg); 6102 } 6103 6104 static inline unsigned long _task_util_est(struct task_struct *p) 6105 { 6106 return READ_ONCE(p->se.avg.util_est) & ~UTIL_AVG_UNCHANGED; 6107 } 6108 6109 static inline unsigned long task_util_est(struct task_struct *p) 6110 { 6111 return max(task_util(p), _task_util_est(p)); 6112 } 6113 6114 static inline void util_est_enqueue(struct cfs_rq *cfs_rq, 6115 struct task_struct *p) 6116 { 6117 unsigned int enqueued; 6118 6119 if (!sched_feat(UTIL_EST)) 6120 return; 6121 6122 /* Update root cfs_rq's estimated utilization */ 6123 enqueued = cfs_rq->avg.util_est; 6124 enqueued += _task_util_est(p); 6125 WRITE_ONCE(cfs_rq->avg.util_est, enqueued); 6126 6127 trace_sched_util_est_cfs_tp(cfs_rq); 6128 } 6129 6130 static inline void util_est_dequeue(struct cfs_rq *cfs_rq, 6131 struct task_struct *p) 6132 { 6133 unsigned int enqueued; 6134 6135 if (!sched_feat(UTIL_EST)) 6136 return; 6137 6138 /* Update root cfs_rq's estimated utilization */ 6139 enqueued = cfs_rq->avg.util_est; 6140 enqueued -= min_t(unsigned int, enqueued, _task_util_est(p)); 6141 WRITE_ONCE(cfs_rq->avg.util_est, enqueued); 6142 6143 trace_sched_util_est_cfs_tp(cfs_rq); 6144 } 6145 6146 static inline unsigned long get_actual_cpu_capacity(int cpu) 6147 { 6148 unsigned long capacity = arch_scale_cpu_capacity(cpu); 6149 6150 capacity -= max(hw_load_avg(cpu_rq(cpu)), cpufreq_get_pressure(cpu)); 6151 6152 return capacity; 6153 } 6154 6155 static inline int util_fits_cpu(unsigned long util, 6156 unsigned long uclamp_min, 6157 unsigned long uclamp_max, 6158 int cpu) 6159 { 6160 unsigned long capacity = capacity_of(cpu); 6161 unsigned long capacity_orig; 6162 bool fits, uclamp_max_fits; 6163 6164 /* 6165 * Check if the real util fits without any uclamp boost/cap applied. 6166 */ 6167 fits = fits_capacity(util, capacity); 6168 6169 if (!uclamp_is_used()) 6170 return fits; 6171 6172 /* 6173 * We must use arch_scale_cpu_capacity() for comparing against uclamp_min and 6174 * uclamp_max. We only care about capacity pressure (by using 6175 * capacity_of()) for comparing against the real util. 6176 * 6177 * If a task is boosted to 1024 for example, we don't want a tiny 6178 * pressure to skew the check whether it fits a CPU or not. 6179 * 6180 * Similarly if a task is capped to arch_scale_cpu_capacity(little_cpu), it 6181 * should fit a little cpu even if there's some pressure. 6182 * 6183 * Only exception is for HW or cpufreq pressure since it has a direct impact 6184 * on available OPP of the system. 6185 * 6186 * We honour it for uclamp_min only as a drop in performance level 6187 * could result in not getting the requested minimum performance level. 6188 * 6189 * For uclamp_max, we can tolerate a drop in performance level as the 6190 * goal is to cap the task. So it's okay if it's getting less. 6191 */ 6192 capacity_orig = arch_scale_cpu_capacity(cpu); 6193 6194 /* 6195 * We want to force a task to fit a cpu as implied by uclamp_max. 6196 * But we do have some corner cases to cater for.. 6197 * 6198 * 6199 * C=z 6200 * | ___ 6201 * | C=y | | 6202 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max 6203 * | C=x | | | | 6204 * | ___ | | | | 6205 * | | | | | | | (util somewhere in this region) 6206 * | | | | | | | 6207 * | | | | | | | 6208 * +---------------------------------------- 6209 * CPU0 CPU1 CPU2 6210 * 6211 * In the above example if a task is capped to a specific performance 6212 * point, y, then when: 6213 * 6214 * * util = 80% of x then it does not fit on CPU0 and should migrate 6215 * to CPU1 6216 * * util = 80% of y then it is forced to fit on CPU1 to honour 6217 * uclamp_max request. 6218 * 6219 * which is what we're enforcing here. A task always fits if 6220 * uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig, 6221 * the normal upmigration rules should withhold still. 6222 * 6223 * Only exception is when we are on max capacity, then we need to be 6224 * careful not to block overutilized state. This is so because: 6225 * 6226 * 1. There's no concept of capping at max_capacity! We can't go 6227 * beyond this performance level anyway. 6228 * 2. The system is being saturated when we're operating near 6229 * max capacity, it doesn't make sense to block overutilized. 6230 */ 6231 uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE); 6232 uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig); 6233 fits = fits || uclamp_max_fits; 6234 6235 /* 6236 * 6237 * C=z 6238 * | ___ (region a, capped, util >= uclamp_max) 6239 * | C=y | | 6240 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max 6241 * | C=x | | | | 6242 * | ___ | | | | (region b, uclamp_min <= util <= uclamp_max) 6243 * |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min 6244 * | | | | | | | 6245 * | | | | | | | (region c, boosted, util < uclamp_min) 6246 * +---------------------------------------- 6247 * CPU0 CPU1 CPU2 6248 * 6249 * a) If util > uclamp_max, then we're capped, we don't care about 6250 * actual fitness value here. We only care if uclamp_max fits 6251 * capacity without taking margin/pressure into account. 6252 * See comment above. 6253 * 6254 * b) If uclamp_min <= util <= uclamp_max, then the normal 6255 * fits_capacity() rules apply. Except we need to ensure that we 6256 * enforce we remain within uclamp_max, see comment above. 6257 * 6258 * c) If util < uclamp_min, then we are boosted. Same as (b) but we 6259 * need to take into account the boosted value fits the CPU without 6260 * taking margin/pressure into account. 6261 * 6262 * Cases (a) and (b) are handled in the 'fits' variable already. We 6263 * just need to consider an extra check for case (c) after ensuring we 6264 * handle the case uclamp_min > uclamp_max. 6265 */ 6266 uclamp_min = min(uclamp_min, uclamp_max); 6267 if (fits && (util < uclamp_min) && 6268 (uclamp_min > get_actual_cpu_capacity(cpu))) 6269 return -1; 6270 6271 return fits; 6272 } 6273 6274 static inline int task_fits_cpu(struct task_struct *p, int cpu) 6275 { 6276 unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN); 6277 unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX); 6278 unsigned long util = task_util_est(p); 6279 /* 6280 * Return true only if the cpu fully fits the task requirements, which 6281 * include the utilization but also the performance hints. 6282 */ 6283 return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0); 6284 } 6285 6286 static inline void update_misfit_status(struct task_struct *p, struct rq *rq) 6287 { 6288 int cpu = cpu_of(rq); 6289 6290 if (!sched_asym_cpucap_active()) 6291 return; 6292 6293 /* 6294 * Affinity allows us to go somewhere higher? Or are we on biggest 6295 * available CPU already? Or do we fit into this CPU ? 6296 */ 6297 if (!p || (p->nr_cpus_allowed == 1) || 6298 (arch_scale_cpu_capacity(cpu) == p->max_allowed_capacity) || 6299 task_fits_cpu(p, cpu)) { 6300 6301 rq->misfit_task_load = 0; 6302 return; 6303 } 6304 6305 /* 6306 * Make sure that misfit_task_load will not be null even if 6307 * task_h_load() returns 0. 6308 */ 6309 rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1); 6310 } 6311 6312 void __setparam_fair(struct task_struct *p, const struct sched_attr *attr) 6313 { 6314 struct sched_entity *se = &p->se; 6315 6316 p->static_prio = NICE_TO_PRIO(attr->sched_nice); 6317 if (attr->sched_runtime) { 6318 se->custom_slice = 1; 6319 se->slice = clamp_t(u64, attr->sched_runtime, 6320 NSEC_PER_MSEC/10, /* HZ=1000 * 10 */ 6321 NSEC_PER_MSEC*100); /* HZ=100 / 10 */ 6322 } else { 6323 se->custom_slice = 0; 6324 se->slice = sysctl_sched_base_slice; 6325 } 6326 } 6327 6328 static void 6329 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 6330 { 6331 u64 vslice, vruntime = avg_vruntime(cfs_rq); 6332 unsigned int nr_queued = cfs_rq->h_nr_queued; 6333 bool update_zero = false; 6334 s64 lag = 0; 6335 6336 if (!se->custom_slice) 6337 se->slice = sysctl_sched_base_slice; 6338 vslice = calc_delta_fair(se->slice, se); 6339 6340 if (flags & ENQUEUE_QUEUED) 6341 nr_queued -= 1; 6342 6343 /* 6344 * Due to how V is constructed as the weighted average of entities, 6345 * adding tasks with positive lag, or removing tasks with negative lag 6346 * will move 'time' backwards, this can screw around with the lag of 6347 * other tasks. 6348 * 6349 * EEVDF: placement strategy #1 / #2 6350 */ 6351 if (sched_feat(PLACE_LAG) && nr_queued && se->vlag) { 6352 struct sched_entity *curr = cfs_rq->curr; 6353 long load, weight; 6354 6355 lag = se->vlag; 6356 6357 /* 6358 * If we want to place a task and preserve lag, we have to 6359 * consider the effect of the new entity on the weighted 6360 * average and compensate for this, otherwise lag can quickly 6361 * evaporate. 6362 * 6363 * Lag is defined as: 6364 * 6365 * lag_i = S - s_i = w_i * (V - v_i) 6366 * 6367 * To avoid the 'w_i' term all over the place, we only track 6368 * the virtual lag: 6369 * 6370 * vl_i = V - v_i <=> v_i = V - vl_i 6371 * 6372 * And we take V to be the weighted average of all v: 6373 * 6374 * V = (\Sum w_j*v_j) / W 6375 * 6376 * Where W is: \Sum w_j 6377 * 6378 * Then, the weighted average after adding an entity with lag 6379 * vl_i is given by: 6380 * 6381 * V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i) 6382 * = (W*V + w_i*(V - vl_i)) / (W + w_i) 6383 * = (W*V + w_i*V - w_i*vl_i) / (W + w_i) 6384 * = (V*(W + w_i) - w_i*vl_i) / (W + w_i) 6385 * = V - w_i*vl_i / (W + w_i) 6386 * 6387 * And the actual lag after adding an entity with vl_i is: 6388 * 6389 * vl'_i = V' - v_i 6390 * = V - w_i*vl_i / (W + w_i) - (V - vl_i) 6391 * = vl_i - w_i*vl_i / (W + w_i) 6392 * 6393 * Which is strictly less than vl_i. So in order to preserve lag 6394 * we should inflate the lag before placement such that the 6395 * effective lag after placement comes out right. 6396 * 6397 * As such, invert the above relation for vl'_i to get the vl_i 6398 * we need to use such that the lag after placement is the lag 6399 * we computed before dequeue. 6400 * 6401 * vl'_i = vl_i - w_i*vl_i / (W + w_i) 6402 * = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i) 6403 * 6404 * (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i 6405 * = W*vl_i 6406 * 6407 * vl_i = (W + w_i)*vl'_i / W 6408 */ 6409 load = cfs_rq->sum_weight; 6410 if (curr && curr->on_rq) 6411 load += avg_vruntime_weight(cfs_rq, curr->h_load.weight); 6412 if (WARN_ON_ONCE(!load)) 6413 load = 1; 6414 6415 weight = avg_vruntime_weight(cfs_rq, se->h_load.weight); 6416 6417 /* 6418 * Rewrite, because the product (W + w_i)*vl'_i might 6419 * overflow s64: 6420 * 6421 * vl_i = (W + w_i)*vl'_i / W 6422 * = (W*vl'_i + w_i*vl'_i) / W 6423 * = vl'_i + w_i*vl'_i/W 6424 */ 6425 lag += div64_long(lag * weight, load); 6426 6427 /* 6428 * A heavy entity (relative to the tree) will pull the 6429 * avg_vruntime close to its vruntime position on enqueue. But 6430 * the zero_vruntime point is only updated at the next 6431 * update_deadline()/place_entity()/update_entity_lag(). 6432 * 6433 * Specifically (see the comment near avg_vruntime_weight()): 6434 * 6435 * sum_w_vruntime = \Sum (v_i - v0) * w_i 6436 * 6437 * Note that if v0 is near a light entity, both terms will be 6438 * small for the light entity, while in that case both terms 6439 * are large for the heavy entity, leading to risk of 6440 * overflow. 6441 * 6442 * OTOH if v0 is near the heavy entity, then the difference is 6443 * larger for the light entity, but the factor is small, while 6444 * for the heavy entity the difference is small but the factor 6445 * is large. Avoiding the multiplication overflow. 6446 */ 6447 if (weight > load) 6448 update_zero = true; 6449 } 6450 6451 se->vruntime = vruntime - lag; 6452 6453 if (update_zero) 6454 update_zero_vruntime(cfs_rq, -lag); 6455 6456 if (sched_feat(PLACE_REL_DEADLINE) && se->rel_deadline) { 6457 se->deadline += se->vruntime; 6458 se->rel_deadline = 0; 6459 return; 6460 } 6461 6462 /* 6463 * When joining the competition; the existing tasks will be, 6464 * on average, halfway through their slice, as such start tasks 6465 * off with half a slice to ease into the competition. 6466 */ 6467 if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL)) 6468 vslice /= 2; 6469 6470 /* 6471 * EEVDF: vd_i = ve_i + r_i/w_i 6472 */ 6473 se->deadline = se->vruntime + vslice; 6474 } 6475 6476 static void check_enqueue_throttle(struct cfs_rq *cfs_rq); 6477 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq); 6478 6479 static void 6480 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 6481 { 6482 /* 6483 * When enqueuing a sched_entity, we must: 6484 * - Update loads to have both entity and cfs_rq synced with now. 6485 * - For group_entity, update its runnable_weight to reflect the new 6486 * h_nr_runnable of its group cfs_rq. 6487 * - For group_entity, update its weight to reflect the new share of 6488 * its group cfs_rq 6489 * - Add its new weight to cfs_rq->load.weight 6490 */ 6491 update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH); 6492 se_update_runnable(se); 6493 /* 6494 * XXX update_load_avg() above will have attached us to the pelt sum; 6495 * but update_cfs_group() here will re-adjust the weight and have to 6496 * undo/redo all that. Seems wasteful. 6497 */ 6498 update_cfs_group(se); 6499 6500 account_entity_enqueue(cfs_rq, se); 6501 6502 /* Entity has migrated, no longer consider this task hot */ 6503 if (flags & ENQUEUE_MIGRATED) 6504 se->exec_start = 0; 6505 6506 check_schedstat_required(); 6507 update_stats_enqueue_fair(cfs_rq, se, flags); 6508 se->on_rq = 1; 6509 6510 if (cfs_rq->nr_queued == 1) { 6511 check_enqueue_throttle(cfs_rq); 6512 list_add_leaf_cfs_rq(cfs_rq); 6513 #ifdef CONFIG_CFS_BANDWIDTH 6514 if (cfs_rq->pelt_clock_throttled) { 6515 struct rq *rq = rq_of(cfs_rq); 6516 6517 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) - 6518 cfs_rq->throttled_clock_pelt; 6519 cfs_rq->pelt_clock_throttled = 0; 6520 } 6521 #endif 6522 } 6523 } 6524 6525 static void set_next_buddy(struct cfs_rq *cfs_rq, struct sched_entity *se) 6526 { 6527 if (WARN_ON_ONCE(!se->on_rq || se->sched_delayed)) 6528 return; 6529 if (se_is_idle(se)) 6530 return; 6531 cfs_rq->next = se; 6532 } 6533 6534 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se) 6535 { 6536 if (cfs_rq->next == se) 6537 cfs_rq->next = NULL; 6538 } 6539 6540 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq); 6541 6542 static void set_delayed(struct sched_entity *se) 6543 { 6544 /* 6545 * Delayed se of cfs_rq have no tasks queued on them. 6546 * Do not adjust h_nr_runnable since __dequeue_task() 6547 * will account it for blocked tasks. 6548 * 6549 * This check can be removed because when flat pick 6550 * patches get merged as only task can get delayed, 6551 * same for clear_delayed(). 6552 */ 6553 if (!entity_is_task(se)) { 6554 se->sched_delayed = 1; 6555 return; 6556 } 6557 6558 /* 6559 * Drop a task leaving the runnable set. 6560 * Needs to be called before sched_delayed is set. 6561 * clear_delayed() mirrors this after clearing the flag. 6562 */ 6563 pref_llc_running_dec(rq_of(cfs_rq_of(se)), task_of(se)); 6564 se->sched_delayed = 1; 6565 6566 for_each_sched_entity(se) { 6567 struct cfs_rq *cfs_rq = cfs_rq_of(se); 6568 6569 cfs_rq->h_nr_runnable--; 6570 } 6571 } 6572 6573 static void clear_delayed(struct sched_entity *se) 6574 { 6575 se->sched_delayed = 0; 6576 6577 /* 6578 * Delayed se of cfs_rq have no tasks queued on them. 6579 * Do not adjust h_nr_runnable since a dequeue has 6580 * already accounted for it or an enqueue of a task 6581 * below it will account for it in enqueue_task_fair(). 6582 */ 6583 if (!entity_is_task(se)) 6584 return; 6585 6586 /* 6587 * Re-add on wake, after sched_delayed is cleared. On a final delayed 6588 * dequeue account_llc_dequeue() already cleared pref_llc_queued, so 6589 * this does nothing. 6590 */ 6591 pref_llc_running_inc(rq_of(cfs_rq_of(se)), task_of(se)); 6592 6593 for_each_sched_entity(se) { 6594 struct cfs_rq *cfs_rq = cfs_rq_of(se); 6595 6596 cfs_rq->h_nr_runnable++; 6597 } 6598 } 6599 6600 static void 6601 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 6602 { 6603 int action = UPDATE_TG; 6604 6605 if (entity_is_task(se)) { 6606 if (task_on_rq_migrating(task_of(se))) 6607 action |= DO_DETACH; 6608 6609 if ((flags & DEQUEUE_SLEEP) && !(flags & DEQUEUE_DELAYED)) 6610 action |= UPDATE_UTIL_EST; 6611 } 6612 6613 /* 6614 * When dequeuing a sched_entity, we must: 6615 * - Update loads to have both entity and cfs_rq synced with now. 6616 * - For group_entity, update its runnable_weight to reflect the new 6617 * h_nr_runnable of its group cfs_rq. 6618 * - Subtract its previous weight from cfs_rq->load.weight. 6619 * - For group entity, update its weight to reflect the new share 6620 * of its group cfs_rq. 6621 */ 6622 update_load_avg(cfs_rq, se, action); 6623 se_update_runnable(se); 6624 6625 update_stats_dequeue_fair(cfs_rq, se, flags); 6626 6627 se->on_rq = 0; 6628 account_entity_dequeue(cfs_rq, se); 6629 6630 /* return excess runtime on last dequeue */ 6631 return_cfs_rq_runtime(cfs_rq); 6632 6633 update_cfs_group(se); 6634 6635 if (cfs_rq->nr_queued == 0) { 6636 update_idle_cfs_rq_clock_pelt(cfs_rq); 6637 #ifdef CONFIG_CFS_BANDWIDTH 6638 if (throttled_hierarchy(cfs_rq)) { 6639 struct rq *rq = rq_of(cfs_rq); 6640 6641 list_del_leaf_cfs_rq(cfs_rq); 6642 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq); 6643 cfs_rq->pelt_clock_throttled = 1; 6644 } 6645 #endif 6646 } 6647 } 6648 6649 static void 6650 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) 6651 { 6652 /* 'current' is not kept within the tree. */ 6653 if (se->on_rq) { 6654 /* 6655 * Any task has to be enqueued before it get to execute on 6656 * a CPU. So account for the time it spent waiting on the 6657 * runqueue. 6658 */ 6659 update_stats_wait_end_fair(cfs_rq, se); 6660 update_load_avg(cfs_rq, se, UPDATE_TG); 6661 } 6662 6663 update_stats_curr_start(cfs_rq, se); 6664 WARN_ON_ONCE(cfs_rq->h_curr); 6665 cfs_rq->h_curr = se; 6666 6667 /* 6668 * Track our maximum slice length, if the CPU's load is at 6669 * least twice that of our own weight (i.e. don't track it 6670 * when there are only lesser-weight tasks around): 6671 */ 6672 if (schedstat_enabled() && 6673 rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) { 6674 struct sched_statistics *stats; 6675 6676 stats = __schedstats_from_se(se); 6677 __schedstat_set(stats->slice_max, 6678 max((u64)stats->slice_max, 6679 se->sum_exec_runtime - se->prev_sum_exec_runtime)); 6680 } 6681 6682 se->prev_sum_exec_runtime = se->sum_exec_runtime; 6683 } 6684 6685 static bool __dequeue_task(struct rq *rq, struct task_struct *p, int flags); 6686 6687 static struct sched_entity * 6688 pick_next_entity(struct rq *rq, bool protect) 6689 { 6690 struct cfs_rq *cfs_rq = &rq->cfs; 6691 struct sched_entity *se; 6692 6693 se = pick_eevdf(cfs_rq, protect); 6694 if (se->sched_delayed) { 6695 __dequeue_task(rq, task_of(se), DEQUEUE_SLEEP | DEQUEUE_DELAYED); 6696 /* 6697 * Must not reference @se again, see __block_task(). 6698 */ 6699 return NULL; 6700 } 6701 return se; 6702 } 6703 6704 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev) 6705 { 6706 /* 6707 * If still on the runqueue then deactivate_task() 6708 * was not called and update_curr() has to be done: 6709 */ 6710 if (prev->on_rq) 6711 update_curr(cfs_rq); 6712 6713 if (prev->on_rq) { 6714 update_stats_wait_start_fair(cfs_rq, prev); 6715 /* in !on_rq case, update occurred at dequeue */ 6716 update_load_avg(cfs_rq, prev, 0); 6717 } 6718 WARN_ON_ONCE(cfs_rq->h_curr != prev); 6719 cfs_rq->h_curr = NULL; 6720 } 6721 6722 static void 6723 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued) 6724 { 6725 /* 6726 * Update run-time statistics of the 'current'. 6727 */ 6728 update_curr(cfs_rq); 6729 6730 /* 6731 * Ensure that runnable average is periodically updated. 6732 */ 6733 update_load_avg(cfs_rq, curr, UPDATE_TG); 6734 update_cfs_group(curr); 6735 6736 #ifdef CONFIG_SCHED_HRTICK 6737 /* 6738 * queued ticks are scheduled to match the slice, so don't bother 6739 * validating it and just reschedule. 6740 */ 6741 if (queued) { 6742 resched_curr(rq_of(cfs_rq)); 6743 return; 6744 } 6745 #endif 6746 } 6747 6748 6749 /************************************************** 6750 * CFS bandwidth control machinery 6751 */ 6752 6753 #ifdef CONFIG_CFS_BANDWIDTH 6754 6755 #ifdef CONFIG_JUMP_LABEL 6756 static struct static_key __cfs_bandwidth_used; 6757 6758 static inline bool cfs_bandwidth_used(void) 6759 { 6760 return static_key_false(&__cfs_bandwidth_used); 6761 } 6762 6763 void cfs_bandwidth_usage_inc(void) 6764 { 6765 static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used); 6766 } 6767 6768 void cfs_bandwidth_usage_dec(void) 6769 { 6770 static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used); 6771 } 6772 #else /* !CONFIG_JUMP_LABEL: */ 6773 static bool cfs_bandwidth_used(void) 6774 { 6775 return true; 6776 } 6777 6778 void cfs_bandwidth_usage_inc(void) {} 6779 void cfs_bandwidth_usage_dec(void) {} 6780 #endif /* !CONFIG_JUMP_LABEL */ 6781 6782 static inline u64 sched_cfs_bandwidth_slice(void) 6783 { 6784 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC; 6785 } 6786 6787 /* 6788 * Replenish runtime according to assigned quota. We use sched_clock_cpu 6789 * directly instead of rq->clock to avoid adding additional synchronization 6790 * around rq->lock. 6791 * 6792 * requires cfs_b->lock 6793 */ 6794 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b) 6795 { 6796 s64 runtime; 6797 6798 if (unlikely(cfs_b->quota == RUNTIME_INF)) 6799 return; 6800 6801 cfs_b->runtime += cfs_b->quota; 6802 runtime = cfs_b->runtime_snap - cfs_b->runtime; 6803 if (runtime > 0) { 6804 cfs_b->burst_time += runtime; 6805 cfs_b->nr_burst++; 6806 } 6807 6808 cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst); 6809 cfs_b->runtime_snap = cfs_b->runtime; 6810 } 6811 6812 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg) 6813 { 6814 return &tg->cfs_bandwidth; 6815 } 6816 6817 /* returns 0 on failure to allocate runtime */ 6818 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b, 6819 struct cfs_rq *cfs_rq, u64 target_runtime) 6820 { 6821 u64 min_amount, amount = 0; 6822 6823 lockdep_assert_held(&cfs_b->lock); 6824 6825 /* note: this is a positive sum as runtime_remaining <= 0 */ 6826 min_amount = target_runtime - cfs_rq->runtime_remaining; 6827 6828 if (cfs_b->quota == RUNTIME_INF) 6829 amount = min_amount; 6830 else { 6831 start_cfs_bandwidth(cfs_b); 6832 6833 if (cfs_b->runtime > 0) { 6834 amount = min(cfs_b->runtime, min_amount); 6835 cfs_b->runtime -= amount; 6836 cfs_b->idle = 0; 6837 } 6838 } 6839 6840 cfs_rq->runtime_remaining += amount; 6841 6842 return cfs_rq->runtime_remaining > 0; 6843 } 6844 6845 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq); 6846 6847 static bool __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) 6848 { 6849 /* dock delta_exec before expiring quota (as it could span periods) */ 6850 cfs_rq->runtime_remaining -= delta_exec; 6851 6852 if (likely(cfs_rq->runtime_remaining > 0)) 6853 return false; 6854 6855 if (cfs_rq->throttled) 6856 return true; 6857 /* 6858 * throttle_cfs_rq() will try to extend the runtime first 6859 * before throttling the hierarchy. 6860 */ 6861 return throttle_cfs_rq(cfs_rq); 6862 } 6863 6864 static __always_inline 6865 bool account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) 6866 { 6867 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled) 6868 return false; 6869 6870 return __account_cfs_rq_runtime(cfs_rq, delta_exec); 6871 } 6872 6873 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq) 6874 { 6875 return cfs_bandwidth_used() && cfs_rq->throttled; 6876 } 6877 6878 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq) 6879 { 6880 return cfs_bandwidth_used() && cfs_rq->pelt_clock_throttled; 6881 } 6882 6883 /* check whether cfs_rq, or any parent, is throttled */ 6884 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq) 6885 { 6886 return cfs_bandwidth_used() && cfs_rq->throttle_count; 6887 } 6888 6889 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu) 6890 { 6891 return throttled_hierarchy(tg_cfs_rq(task_group(p), dst_cpu)); 6892 } 6893 6894 static inline bool task_is_throttled(struct task_struct *p) 6895 { 6896 return cfs_bandwidth_used() && p->throttled; 6897 } 6898 6899 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags); 6900 static void throttle_cfs_rq_work(struct callback_head *work) 6901 { 6902 struct task_struct *p = container_of(work, struct task_struct, sched_throttle_work); 6903 struct sched_entity *se; 6904 struct cfs_rq *cfs_rq; 6905 struct rq *rq; 6906 6907 WARN_ON_ONCE(p != current); 6908 p->sched_throttle_work.next = &p->sched_throttle_work; 6909 6910 /* 6911 * If task is exiting, then there won't be a return to userspace, so we 6912 * don't have to bother with any of this. 6913 */ 6914 if ((p->flags & PF_EXITING)) 6915 return; 6916 6917 scoped_guard(task_rq_lock, p) { 6918 se = &p->se; 6919 cfs_rq = cfs_rq_of(se); 6920 6921 /* Raced, forget */ 6922 if (p->sched_class != &fair_sched_class) 6923 return; 6924 6925 /* 6926 * If not in limbo, then either replenish has happened or this 6927 * task got migrated out of the throttled cfs_rq, move along. 6928 */ 6929 if (!cfs_rq->throttle_count) 6930 return; 6931 rq = scope.rq; 6932 update_rq_clock(rq); 6933 WARN_ON_ONCE(p->throttled || !list_empty(&p->throttle_node)); 6934 dequeue_task_fair(rq, p, DEQUEUE_SLEEP | DEQUEUE_THROTTLE); 6935 list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list); 6936 /* 6937 * Must not set throttled before dequeue or dequeue will 6938 * mistakenly regard this task as an already throttled one. 6939 */ 6940 p->throttled = true; 6941 resched_curr(rq); 6942 } 6943 } 6944 6945 void init_cfs_throttle_work(struct task_struct *p) 6946 { 6947 init_task_work(&p->sched_throttle_work, throttle_cfs_rq_work); 6948 /* Protect against double add, see throttle_cfs_rq() and throttle_cfs_rq_work() */ 6949 p->sched_throttle_work.next = &p->sched_throttle_work; 6950 INIT_LIST_HEAD(&p->throttle_node); 6951 } 6952 6953 /* 6954 * Task is throttled and someone wants to dequeue it again: 6955 * it could be sched/core when core needs to do things like 6956 * task affinity change, task group change, task sched class 6957 * change etc. and in these cases, DEQUEUE_SLEEP is not set; 6958 * or the task is blocked after throttled due to freezer etc. 6959 * and in these cases, DEQUEUE_SLEEP is set. 6960 */ 6961 static void detach_task_cfs_rq(struct task_struct *p); 6962 static void dequeue_throttled_task(struct task_struct *p, int flags) 6963 { 6964 WARN_ON_ONCE(p->se.on_rq); 6965 list_del_init(&p->throttle_node); 6966 6967 /* Task blocked after throttling or is leaving the fair class: */ 6968 if (flags & (DEQUEUE_SLEEP | DEQUEUE_CLASS)) { 6969 p->throttled = false; 6970 return; 6971 } 6972 6973 /* 6974 * task is migrating off its old cfs_rq, detach 6975 * the task's load from its old cfs_rq. 6976 */ 6977 if (task_on_rq_migrating(p)) 6978 detach_task_cfs_rq(p); 6979 } 6980 6981 static bool enqueue_throttled_task(struct task_struct *p) 6982 { 6983 struct cfs_rq *cfs_rq = cfs_rq_of(&p->se); 6984 6985 /* @p should have gone through dequeue_throttled_task() first */ 6986 WARN_ON_ONCE(!list_empty(&p->throttle_node)); 6987 6988 /* 6989 * If the throttled task @p is enqueued to a throttled cfs_rq, 6990 * take the fast path by directly putting the task on the 6991 * target cfs_rq's limbo list. 6992 * 6993 * Do not do that when @p is current because the following race can 6994 * cause @p's group_node to be incorectly re-insterted in its rq's 6995 * cfs_tasks list, despite being throttled: 6996 * 6997 * cpuX cpuY 6998 * p ret2user 6999 * throttle_cfs_rq_work() sched_move_task(p) 7000 * LOCK task_rq_lock 7001 * dequeue_task_fair(p) 7002 * UNLOCK task_rq_lock 7003 * LOCK task_rq_lock 7004 * task_current_donor(p) == true 7005 * task_on_rq_queued(p) == true 7006 * dequeue_task(p) 7007 * put_prev_task(p) 7008 * sched_change_group() 7009 * enqueue_task(p) -> p's new cfs_rq 7010 * is throttled, go 7011 * fast path and skip 7012 * actual enqueue 7013 * set_next_task(p) 7014 * list_move(&se->group_node, &rq->cfs_tasks); // bug 7015 * schedule() 7016 * 7017 * In the above race case, @p current cfs_rq is in the same rq as 7018 * its previous cfs_rq because sched_move_task() only moves a task 7019 * to a different group from the same rq, so we can use its current 7020 * cfs_rq to derive rq and test if the task is current. 7021 */ 7022 if (throttled_hierarchy(cfs_rq) && 7023 !task_current_donor(rq_of(cfs_rq), p)) { 7024 list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list); 7025 return true; 7026 } 7027 7028 /* we can't take the fast path, do an actual enqueue*/ 7029 p->throttled = false; 7030 return false; 7031 } 7032 7033 static void enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags); 7034 static int tg_unthrottle_up(struct task_group *tg, void *data) 7035 { 7036 struct rq *rq = data; 7037 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq)); 7038 struct task_struct *p, *tmp; 7039 LIST_HEAD(throttled_tasks); 7040 7041 /* 7042 * If cfs_rq->curr is set, the cfs_rq might not have caught up 7043 * since the last clock update. Do it now before we begin 7044 * queueing task onto it to save the need for unnecessarily 7045 * unthrottle the hierarchy for this cfs_rq to be throttled 7046 * right back again. 7047 */ 7048 update_curr(cfs_rq); 7049 7050 if (--cfs_rq->throttle_count) 7051 return 0; 7052 7053 if (cfs_rq->pelt_clock_throttled) { 7054 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) - 7055 cfs_rq->throttled_clock_pelt; 7056 cfs_rq->pelt_clock_throttled = 0; 7057 } 7058 7059 if (cfs_rq->throttled_clock_self) { 7060 u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self; 7061 7062 cfs_rq->throttled_clock_self = 0; 7063 7064 if (WARN_ON_ONCE((s64)delta < 0)) 7065 delta = 0; 7066 7067 cfs_rq->throttled_clock_self_time += delta; 7068 } 7069 7070 /* 7071 * Move the tasks to a local list since an update_curr() during 7072 * enqueue_task_fair() can throttle a higher cfs_rq, and it can 7073 * see the "throttled_limbo_list" being non-empty in 7074 * tg_throttle_down() if throttle_count turned 0 above. 7075 */ 7076 list_splice_init(&cfs_rq->throttled_limbo_list, &throttled_tasks); 7077 7078 /* Re-enqueue the tasks that have been throttled at this level. */ 7079 list_for_each_entry_safe(p, tmp, &throttled_tasks, throttle_node) { 7080 /* 7081 * Back to being throttled! Break out and put the remaining 7082 * tasks back onto the limbo_list to prevent running them 7083 * unnecessarily. 7084 */ 7085 if (cfs_rq->throttle_count) 7086 break; 7087 7088 list_del_init(&p->throttle_node); 7089 p->throttled = false; 7090 enqueue_task_fair(rq, p, ENQUEUE_WAKEUP); 7091 } 7092 7093 list_splice(&throttled_tasks, &cfs_rq->throttled_limbo_list); 7094 7095 /* Add cfs_rq with load or one or more already running entities to the list */ 7096 if (!cfs_rq_is_decayed(cfs_rq)) 7097 list_add_leaf_cfs_rq(cfs_rq); 7098 7099 return 0; 7100 } 7101 7102 static inline bool task_has_throttle_work(struct task_struct *p) 7103 { 7104 return p->sched_throttle_work.next != &p->sched_throttle_work; 7105 } 7106 7107 static inline void task_throttle_setup_work(struct task_struct *p) 7108 { 7109 if (task_has_throttle_work(p)) 7110 return; 7111 7112 /* 7113 * Kthreads and exiting tasks don't return to userspace, so adding the 7114 * work is pointless 7115 */ 7116 if ((p->flags & (PF_EXITING | PF_KTHREAD))) 7117 return; 7118 7119 task_work_add(p, &p->sched_throttle_work, TWA_RESUME); 7120 } 7121 7122 static void record_throttle_clock(struct cfs_rq *cfs_rq) 7123 { 7124 struct rq *rq = rq_of(cfs_rq); 7125 7126 if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock) 7127 cfs_rq->throttled_clock = rq_clock(rq); 7128 7129 if (!cfs_rq->throttled_clock_self) 7130 cfs_rq->throttled_clock_self = rq_clock(rq); 7131 } 7132 7133 static int tg_throttle_down(struct task_group *tg, void *data) 7134 { 7135 struct rq *rq = data; 7136 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq)); 7137 7138 if (cfs_rq->throttle_count++) 7139 return 0; 7140 7141 /* 7142 * For cfs_rqs that still have entities enqueued, PELT clock 7143 * stop happens at dequeue time when all entities are dequeued. 7144 */ 7145 if (!cfs_rq->nr_queued) { 7146 list_del_leaf_cfs_rq(cfs_rq); 7147 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq); 7148 cfs_rq->pelt_clock_throttled = 1; 7149 } 7150 7151 WARN_ON_ONCE(cfs_rq->throttled_clock_self); 7152 WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_limbo_list)); 7153 return 0; 7154 } 7155 7156 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq) 7157 { 7158 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 7159 struct sched_entity *curr = cfs_rq->h_curr; 7160 struct rq *rq = rq_of(cfs_rq); 7161 7162 scoped_guard(raw_spinlock, &cfs_b->lock) { 7163 u64 target_runtime = 1; 7164 7165 /* 7166 * If cfs_rq->h_curr is still runnable, we are here from an 7167 * update_curr(). Request sysctl_sched_cfs_bandwidth_slice 7168 * worth of bandwidth to continue running. 7169 * 7170 * If the curr is not runnable, just request enough bandwidth 7171 * to be runnable next time the pick selects this cfs_rq. 7172 */ 7173 if (curr && curr->on_rq) 7174 target_runtime = sched_cfs_bandwidth_slice(); 7175 7176 /* 7177 * Check if We have raced with bandwidth becoming available. If 7178 * we actually throttled the timer might not unthrottle us for 7179 * an entire period. We additionally needed to make sure that 7180 * any subsequent check_cfs_rq_runtime calls agree not to 7181 * throttle us, as we may commit to do cfs put_prev+pick_next, 7182 * so we ask for 1ns of runtime rather than just check cfs_b. 7183 * 7184 * This will start the period timer if necessary. 7185 */ 7186 if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, target_runtime)) 7187 return false; 7188 7189 /* 7190 * No bandwidth available; Add ourselves on the list to be 7191 * unthrottled later. 7192 */ 7193 list_add_tail_rcu(&cfs_rq->throttled_list, 7194 &cfs_b->throttled_cfs_rq); 7195 } 7196 7197 /* freeze hierarchy runnable averages while throttled */ 7198 scoped_guard(rcu) 7199 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq); 7200 7201 /* 7202 * Note: distribution will already see us throttled via the 7203 * throttled-list. rq->lock protects completion. 7204 */ 7205 cfs_rq->throttled = 1; 7206 WARN_ON_ONCE(cfs_rq->throttled_clock); 7207 7208 /* 7209 * If current hierarchy was throttled, add throttle work to the 7210 * current donor. In case of proxy-execution, the execution 7211 * context cannot exit to the userspace while holding a mutex 7212 * and the rule of throttle deferral to only throttle the 7213 * throttled context at exit to userspace is still preserved. 7214 */ 7215 if (curr && curr->on_rq) 7216 task_throttle_setup_work(rq->donor); 7217 7218 return true; 7219 } 7220 7221 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq) 7222 { 7223 struct rq *rq = rq_of(cfs_rq); 7224 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 7225 struct sched_entity *se = cfs_rq_se(cfs_rq); 7226 7227 /* 7228 * It's possible we are called with runtime_remaining < 0 due to things 7229 * like async unthrottled us with a positive runtime_remaining but other 7230 * still running entities consumed those runtime before we reached here. 7231 * 7232 * We can't unthrottle this cfs_rq without any runtime remaining because 7233 * any enqueue in tg_unthrottle_up() will immediately trigger a throttle, 7234 * which is not supposed to happen on unthrottle path. 7235 * 7236 * Catch up on the remaining runtime since last clock update before 7237 * checking runtime remaining. 7238 */ 7239 update_curr(cfs_rq); 7240 if (cfs_rq->runtime_enabled && cfs_rq->runtime_remaining <= 0) 7241 return; 7242 7243 cfs_rq->throttled = 0; 7244 7245 scoped_guard(raw_spinlock, &cfs_b->lock) { 7246 list_del_rcu(&cfs_rq->throttled_list); 7247 7248 if (!cfs_rq->throttled_clock) 7249 break; 7250 7251 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock; 7252 cfs_rq->throttled_clock = 0; 7253 } 7254 7255 /* update hierarchical throttle state */ 7256 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq); 7257 7258 if (!cfs_rq->load.weight) { 7259 if (!cfs_rq->on_list) 7260 return; 7261 /* 7262 * Nothing to run but something to decay (on_list)? 7263 * Complete the branch. 7264 */ 7265 for_each_sched_entity(se) { 7266 if (list_add_leaf_cfs_rq(cfs_rq_of(se))) 7267 break; 7268 } 7269 } 7270 7271 assert_list_leaf_cfs_rq(rq); 7272 7273 /* Determine whether we need to wake up potentially idle CPU: */ 7274 if (rq->curr == rq->idle && rq->cfs.h_nr_queued) 7275 resched_curr(rq); 7276 } 7277 7278 static void __cfsb_csd_unthrottle(void *arg) 7279 { 7280 struct cfs_rq *cursor, *tmp; 7281 struct rq *rq = arg; 7282 7283 guard(rq_lock)(rq); 7284 7285 /* 7286 * Iterating over the list can trigger several call to 7287 * update_rq_clock() in unthrottle_cfs_rq(). 7288 * Do it once and skip the potential next ones. 7289 */ 7290 update_rq_clock(rq); 7291 rq_clock_start_loop_update(rq); 7292 7293 /* 7294 * Since we hold rq lock we're safe from concurrent manipulation of 7295 * the CSD list. However, this RCU critical section annotates the 7296 * fact that we pair with sched_free_group_rcu(), so that we cannot 7297 * race with group being freed in the window between removing it 7298 * from the list and advancing to the next entry in the list. 7299 */ 7300 guard(rcu)(); 7301 7302 list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list, 7303 throttled_csd_list) { 7304 list_del_init(&cursor->throttled_csd_list); 7305 7306 if (cfs_rq_throttled(cursor)) 7307 unthrottle_cfs_rq(cursor); 7308 } 7309 7310 rq_clock_stop_loop_update(rq); 7311 } 7312 7313 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq) 7314 { 7315 struct rq *rq = rq_of(cfs_rq); 7316 bool first; 7317 7318 if (rq == this_rq()) { 7319 update_rq_clock(rq); 7320 unthrottle_cfs_rq(cfs_rq); 7321 return; 7322 } 7323 7324 /* Already enqueued */ 7325 if (WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_csd_list))) 7326 return; 7327 7328 first = list_empty(&rq->cfsb_csd_list); 7329 list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list); 7330 if (first) 7331 smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd); 7332 } 7333 7334 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq) 7335 { 7336 lockdep_assert_rq_held(rq_of(cfs_rq)); 7337 7338 if (WARN_ON_ONCE(!cfs_rq_throttled(cfs_rq) || 7339 cfs_rq->runtime_remaining <= 0)) 7340 return; 7341 7342 __unthrottle_cfs_rq_async(cfs_rq); 7343 } 7344 7345 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b) 7346 { 7347 bool throttled = false, unthrottle_local = false; 7348 int this_cpu = smp_processor_id(); 7349 u64 runtime, remaining = 1; 7350 struct cfs_rq *cfs_rq; 7351 struct rq *rq; 7352 7353 guard(rcu)(); 7354 7355 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq, 7356 throttled_list) { 7357 rq = rq_of(cfs_rq); 7358 7359 if (!remaining) { 7360 throttled = true; 7361 break; 7362 } 7363 7364 guard(rq_lock_irqsave)(rq); 7365 7366 if (!cfs_rq_throttled(cfs_rq)) 7367 continue; 7368 7369 /* Already queued for async unthrottle */ 7370 if (!list_empty(&cfs_rq->throttled_csd_list)) 7371 continue; 7372 7373 if (cfs_rq->h_curr) { 7374 update_rq_clock(rq); 7375 update_curr(cfs_rq); 7376 } 7377 7378 /* By the above checks, this should never be true */ 7379 WARN_ON_ONCE(cfs_rq->runtime_remaining > 0); 7380 7381 scoped_guard(raw_spinlock, &cfs_b->lock) { 7382 runtime = -cfs_rq->runtime_remaining + 1; 7383 if (runtime > cfs_b->runtime) 7384 runtime = cfs_b->runtime; 7385 cfs_b->runtime -= runtime; 7386 remaining = cfs_b->runtime; 7387 } 7388 7389 cfs_rq->runtime_remaining += runtime; 7390 7391 /* 7392 * Ran out of bandwidth during distribution! 7393 * Indicate throttled entities and break early. 7394 */ 7395 if (cfs_rq->runtime_remaining <= 0) { 7396 throttled = true; 7397 break; 7398 } 7399 7400 /* we check whether we're throttled above */ 7401 if (cpu_of(rq) != this_cpu) { 7402 unthrottle_cfs_rq_async(cfs_rq); 7403 continue; 7404 } 7405 7406 /* 7407 * Allow a parallel async unthrottle to unthrottle 7408 * this cfs_rq too via __cfsb_csd_unthrottle(). 7409 * If we are first, do it ourselves at the end and 7410 * save on an IPI from remote CPUs. 7411 */ 7412 unthrottle_local = list_empty(&rq->cfsb_csd_list); 7413 list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list); 7414 } 7415 7416 if (unthrottle_local) { 7417 /* 7418 * Protect against an IPI that is also trying to flush 7419 * the unthrottled cfs_rq(s) from this CPU's csd_list. 7420 */ 7421 scoped_guard(irqsave) 7422 __cfsb_csd_unthrottle(cpu_rq(this_cpu)); 7423 } 7424 7425 return throttled; 7426 } 7427 7428 /* 7429 * Responsible for refilling a task_group's bandwidth and unthrottling its 7430 * cfs_rqs as appropriate. If there has been no activity within the last 7431 * period the timer is deactivated until scheduling resumes; cfs_b->idle is 7432 * used to track this state. 7433 */ 7434 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags) 7435 __must_hold(&cfs_b->lock) 7436 { 7437 int throttled; 7438 7439 /* no need to continue the timer with no bandwidth constraint */ 7440 if (cfs_b->quota == RUNTIME_INF) 7441 goto out_deactivate; 7442 7443 throttled = !list_empty(&cfs_b->throttled_cfs_rq); 7444 cfs_b->nr_periods += overrun; 7445 7446 /* Refill extra burst quota even if cfs_b->idle */ 7447 __refill_cfs_bandwidth_runtime(cfs_b); 7448 7449 /* 7450 * idle depends on !throttled (for the case of a large deficit), and if 7451 * we're going inactive then everything else can be deferred 7452 */ 7453 if (cfs_b->idle && !throttled) 7454 goto out_deactivate; 7455 7456 if (!throttled) { 7457 /* mark as potentially idle for the upcoming period */ 7458 cfs_b->idle = 1; 7459 return 0; 7460 } 7461 7462 /* account preceding periods in which throttling occurred */ 7463 cfs_b->nr_throttled += overrun; 7464 7465 /* 7466 * This check is repeated as we release cfs_b->lock while we unthrottle. 7467 */ 7468 while (throttled && cfs_b->runtime > 0) { 7469 raw_spin_unlock_irqrestore(&cfs_b->lock, flags); 7470 /* we can't nest cfs_b->lock while distributing bandwidth */ 7471 throttled = distribute_cfs_runtime(cfs_b); 7472 raw_spin_lock_irqsave(&cfs_b->lock, flags); 7473 } 7474 7475 /* 7476 * While we are ensured activity in the period following an 7477 * unthrottle, this also covers the case in which the new bandwidth is 7478 * insufficient to cover the existing bandwidth deficit. (Forcing the 7479 * timer to remain active while there are any throttled entities.) 7480 */ 7481 cfs_b->idle = 0; 7482 7483 return 0; 7484 7485 out_deactivate: 7486 return 1; 7487 } 7488 7489 /* a cfs_rq won't donate quota below this amount */ 7490 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC; 7491 /* minimum remaining period time to redistribute slack quota */ 7492 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC; 7493 /* how long we wait to gather additional slack before distributing */ 7494 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC; 7495 7496 /* 7497 * Are we near the end of the current quota period? 7498 * 7499 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the 7500 * hrtimer base being cleared by hrtimer_start. In the case of 7501 * migrate_hrtimers, base is never cleared, so we are fine. 7502 */ 7503 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire) 7504 { 7505 struct hrtimer *refresh_timer = &cfs_b->period_timer; 7506 s64 remaining; 7507 7508 /* if the call-back is running a quota refresh is already occurring */ 7509 if (hrtimer_callback_running(refresh_timer)) 7510 return 1; 7511 7512 /* is a quota refresh about to occur? */ 7513 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer)); 7514 if (remaining < (s64)min_expire) 7515 return 1; 7516 7517 return 0; 7518 } 7519 7520 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b) 7521 { 7522 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration; 7523 7524 /* if there's a quota refresh soon don't bother with slack */ 7525 if (runtime_refresh_within(cfs_b, min_left)) 7526 return; 7527 7528 /* don't push forwards an existing deferred unthrottle */ 7529 if (cfs_b->slack_started) 7530 return; 7531 cfs_b->slack_started = true; 7532 7533 hrtimer_start(&cfs_b->slack_timer, 7534 ns_to_ktime(cfs_bandwidth_slack_period), 7535 HRTIMER_MODE_REL); 7536 } 7537 7538 /* we know any runtime found here is valid as update_curr() precedes return */ 7539 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq) 7540 { 7541 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 7542 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime; 7543 7544 if (slack_runtime <= 0) 7545 return; 7546 7547 guard(raw_spinlock)(&cfs_b->lock); 7548 7549 if (cfs_b->quota != RUNTIME_INF) { 7550 cfs_b->runtime += slack_runtime; 7551 7552 /* we are under rq->lock, defer unthrottling using a timer */ 7553 if (cfs_b->runtime > sched_cfs_bandwidth_slice() && 7554 !list_empty(&cfs_b->throttled_cfs_rq)) 7555 start_cfs_slack_bandwidth(cfs_b); 7556 } 7557 7558 /* even if it's not valid for return we don't want to try again */ 7559 cfs_rq->runtime_remaining -= slack_runtime; 7560 } 7561 7562 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) 7563 { 7564 if (!cfs_bandwidth_used()) 7565 return; 7566 7567 if (!cfs_rq->runtime_enabled || cfs_rq->nr_queued) 7568 return; 7569 7570 __return_cfs_rq_runtime(cfs_rq); 7571 } 7572 7573 /* 7574 * This is done with a timer (instead of inline with bandwidth return) since 7575 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs. 7576 */ 7577 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b) 7578 { 7579 /* confirm we're still not at a refresh boundary */ 7580 scoped_guard(raw_spinlock_irqsave, &cfs_b->lock) { 7581 u64 runtime = 0, slice = sched_cfs_bandwidth_slice(); 7582 7583 cfs_b->slack_started = false; 7584 7585 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) 7586 return; 7587 7588 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice) 7589 runtime = cfs_b->runtime; 7590 7591 if (!runtime) 7592 return; 7593 } 7594 7595 distribute_cfs_runtime(cfs_b); 7596 } 7597 7598 /* 7599 * When a group wakes up we want to make sure that its quota is not already 7600 * expired/exceeded, otherwise it may be allowed to steal additional ticks of 7601 * runtime as update_curr() throttling can not trigger until it's on-rq. 7602 */ 7603 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) 7604 { 7605 if (!cfs_bandwidth_used()) 7606 return; 7607 7608 /* an active group must be handled by the update_curr() path */ 7609 if (!cfs_rq->runtime_enabled || cfs_rq->h_curr) 7610 return; 7611 7612 /* ensure the group is not already throttled */ 7613 if (cfs_rq_throttled(cfs_rq)) 7614 return; 7615 7616 /* update runtime allocation */ 7617 account_cfs_rq_runtime(cfs_rq, 0); 7618 } 7619 7620 static void sync_throttle(struct task_group *tg, int cpu) 7621 { 7622 struct cfs_rq *pcfs_rq, *cfs_rq; 7623 7624 if (!cfs_bandwidth_used()) 7625 return; 7626 7627 if (!tg->parent) 7628 return; 7629 7630 cfs_rq = tg_cfs_rq(tg, cpu); 7631 pcfs_rq = tg_cfs_rq(tg->parent, cpu); 7632 7633 cfs_rq->throttle_count = pcfs_rq->throttle_count; 7634 cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu)); 7635 7636 /* 7637 * It is not enough to sync the "pelt_clock_throttled" indicator 7638 * with the parent cfs_rq when the hierarchy is not queued. 7639 * Always join a throttled hierarchy with PELT clock throttled 7640 * and leaf it to the first enqueue, or distribution to 7641 * unthrottle the PELT clock. 7642 */ 7643 if (cfs_rq->throttle_count) 7644 cfs_rq->pelt_clock_throttled = 1; 7645 } 7646 7647 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer) 7648 { 7649 struct cfs_bandwidth *cfs_b = 7650 container_of(timer, struct cfs_bandwidth, slack_timer); 7651 7652 do_sched_cfs_slack_timer(cfs_b); 7653 7654 return HRTIMER_NORESTART; 7655 } 7656 7657 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer) 7658 { 7659 struct cfs_bandwidth *cfs_b = 7660 container_of(timer, struct cfs_bandwidth, period_timer); 7661 int overrun; 7662 int idle = 0; 7663 int count = 0; 7664 7665 CLASS(raw_spinlock_irqsave, cfsb_guard)(&cfs_b->lock); 7666 7667 for (;;) { 7668 overrun = hrtimer_forward_now(timer, cfs_b->period); 7669 if (!overrun) 7670 break; 7671 7672 idle = do_sched_cfs_period_timer(cfs_b, overrun, cfsb_guard.flags); 7673 7674 if (++count > 3) { 7675 u64 new, old = ktime_to_ns(cfs_b->period); 7676 7677 /* 7678 * Grow period by a factor of 2 to avoid losing precision. 7679 * Precision loss in the quota/period ratio can cause __cfs_schedulable 7680 * to fail. 7681 */ 7682 new = old * 2; 7683 if (new < max_bw_quota_period_us * NSEC_PER_USEC) { 7684 cfs_b->period = ns_to_ktime(new); 7685 cfs_b->quota *= 2; 7686 cfs_b->burst *= 2; 7687 7688 pr_warn_ratelimited( 7689 "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n", 7690 smp_processor_id(), 7691 div_u64(new, NSEC_PER_USEC), 7692 div_u64(cfs_b->quota, NSEC_PER_USEC)); 7693 } else { 7694 pr_warn_ratelimited( 7695 "cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n", 7696 smp_processor_id(), 7697 div_u64(old, NSEC_PER_USEC), 7698 div_u64(cfs_b->quota, NSEC_PER_USEC)); 7699 } 7700 7701 /* reset count so we don't come right back in here */ 7702 count = 0; 7703 } 7704 } 7705 7706 if (idle) { 7707 cfs_b->period_active = 0; 7708 return HRTIMER_NORESTART; 7709 } 7710 7711 return HRTIMER_RESTART; 7712 } 7713 7714 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) 7715 { 7716 raw_spin_lock_init(&cfs_b->lock); 7717 cfs_b->runtime = 0; 7718 cfs_b->quota = RUNTIME_INF; 7719 cfs_b->period = us_to_ktime(default_bw_period_us()); 7720 cfs_b->burst = 0; 7721 cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF; 7722 7723 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq); 7724 hrtimer_setup(&cfs_b->period_timer, sched_cfs_period_timer, CLOCK_MONOTONIC, 7725 HRTIMER_MODE_ABS_PINNED); 7726 7727 /* Add a random offset so that timers interleave */ 7728 hrtimer_set_expires(&cfs_b->period_timer, 7729 get_random_u32_below(cfs_b->period)); 7730 hrtimer_setup(&cfs_b->slack_timer, sched_cfs_slack_timer, CLOCK_MONOTONIC, 7731 HRTIMER_MODE_REL); 7732 cfs_b->slack_started = false; 7733 } 7734 7735 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) 7736 { 7737 cfs_rq->runtime_enabled = 0; 7738 INIT_LIST_HEAD(&cfs_rq->throttled_list); 7739 INIT_LIST_HEAD(&cfs_rq->throttled_csd_list); 7740 INIT_LIST_HEAD(&cfs_rq->throttled_limbo_list); 7741 } 7742 7743 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b) 7744 { 7745 lockdep_assert_held(&cfs_b->lock); 7746 7747 if (cfs_b->period_active) 7748 return; 7749 7750 cfs_b->period_active = 1; 7751 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period); 7752 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED); 7753 } 7754 7755 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) 7756 { 7757 int __maybe_unused i; 7758 7759 /* init_cfs_bandwidth() was not called */ 7760 if (!cfs_b->throttled_cfs_rq.next) 7761 return; 7762 7763 hrtimer_cancel(&cfs_b->period_timer); 7764 hrtimer_cancel(&cfs_b->slack_timer); 7765 7766 /* 7767 * It is possible that we still have some cfs_rq's pending on a CSD 7768 * list, though this race is very rare. In order for this to occur, we 7769 * must have raced with the last task leaving the group while there 7770 * exist throttled cfs_rq(s), and the period_timer must have queued the 7771 * CSD item but the remote cpu has not yet processed it. To handle this, 7772 * we can simply flush all pending CSD work inline here. We're 7773 * guaranteed at this point that no additional cfs_rq of this group can 7774 * join a CSD list. 7775 */ 7776 for_each_possible_cpu(i) { 7777 struct rq *rq = cpu_rq(i); 7778 7779 if (list_empty(&rq->cfsb_csd_list)) 7780 continue; 7781 7782 scoped_guard(irqsave) 7783 __cfsb_csd_unthrottle(rq); 7784 } 7785 } 7786 7787 /* 7788 * Both these CPU hotplug callbacks race against unregister_fair_sched_group() 7789 * 7790 * The race is harmless, since modifying bandwidth settings of unhooked group 7791 * bits doesn't do much. 7792 */ 7793 7794 /* cpu online callback */ 7795 static void __maybe_unused update_runtime_enabled(struct rq *rq) 7796 { 7797 struct task_group *tg; 7798 7799 lockdep_assert_rq_held(rq); 7800 7801 guard(rcu)(); 7802 7803 list_for_each_entry_rcu(tg, &task_groups, list) { 7804 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; 7805 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq)); 7806 7807 scoped_guard(raw_spinlock, &cfs_b->lock) 7808 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF; 7809 } 7810 } 7811 7812 /* cpu offline callback */ 7813 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq) 7814 { 7815 struct task_group *tg; 7816 7817 lockdep_assert_rq_held(rq); 7818 7819 // Do not unthrottle for an active CPU 7820 if (cpumask_test_cpu(cpu_of(rq), cpu_active_mask)) 7821 return; 7822 7823 /* 7824 * The rq clock has already been updated in the 7825 * set_rq_offline(), so we should skip updating 7826 * the rq clock again in unthrottle_cfs_rq(). 7827 */ 7828 rq_clock_start_loop_update(rq); 7829 7830 guard(rcu)(); 7831 7832 list_for_each_entry_rcu(tg, &task_groups, list) { 7833 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq)); 7834 7835 if (!cfs_rq->runtime_enabled) 7836 continue; 7837 7838 /* 7839 * Offline rq is schedulable till CPU is completely disabled 7840 * in take_cpu_down(), so we prevent new cfs throttling here. 7841 */ 7842 cfs_rq->runtime_enabled = 0; 7843 7844 if (!cfs_rq_throttled(cfs_rq)) 7845 continue; 7846 7847 /* 7848 * clock_task is not advancing so we just need to make sure 7849 * there's some valid quota amount 7850 */ 7851 cfs_rq->runtime_remaining = 1; 7852 unthrottle_cfs_rq(cfs_rq); 7853 } 7854 7855 rq_clock_stop_loop_update(rq); 7856 } 7857 7858 bool cfs_task_bw_constrained(struct task_struct *p) 7859 { 7860 struct cfs_rq *cfs_rq = task_cfs_rq(p); 7861 7862 if (!cfs_bandwidth_used()) 7863 return false; 7864 7865 if (cfs_rq->runtime_enabled || 7866 tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF) 7867 return true; 7868 7869 return false; 7870 } 7871 7872 #ifdef CONFIG_NO_HZ_FULL 7873 /* called from pick_next_task_fair() */ 7874 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) 7875 { 7876 int cpu = cpu_of(rq); 7877 7878 if (!cfs_bandwidth_used()) 7879 return; 7880 7881 if (!tick_nohz_full_cpu(cpu)) 7882 return; 7883 7884 if (rq->nr_running != 1) 7885 return; 7886 7887 /* 7888 * We know there is only one task runnable and we've just picked it. The 7889 * normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will 7890 * be otherwise able to stop the tick. Just need to check if we are using 7891 * bandwidth control. 7892 */ 7893 if (cfs_task_bw_constrained(p)) 7894 tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED); 7895 } 7896 #endif /* CONFIG_NO_HZ_FULL */ 7897 7898 #else /* !CONFIG_CFS_BANDWIDTH: */ 7899 7900 static bool account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) { return false; } 7901 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {} 7902 static inline void sync_throttle(struct task_group *tg, int cpu) {} 7903 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {} 7904 static void task_throttle_setup_work(struct task_struct *p) {} 7905 static bool task_is_throttled(struct task_struct *p) { return false; } 7906 static void dequeue_throttled_task(struct task_struct *p, int flags) {} 7907 static bool enqueue_throttled_task(struct task_struct *p) { return false; } 7908 static void record_throttle_clock(struct cfs_rq *cfs_rq) {} 7909 7910 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq) 7911 { 7912 return 0; 7913 } 7914 7915 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq) 7916 { 7917 return false; 7918 } 7919 7920 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq) 7921 { 7922 return 0; 7923 } 7924 7925 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu) 7926 { 7927 return 0; 7928 } 7929 7930 #ifdef CONFIG_FAIR_GROUP_SCHED 7931 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {} 7932 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {} 7933 #endif 7934 7935 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg) 7936 { 7937 return NULL; 7938 } 7939 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {} 7940 static inline void update_runtime_enabled(struct rq *rq) {} 7941 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {} 7942 #ifdef CONFIG_CGROUP_SCHED 7943 bool cfs_task_bw_constrained(struct task_struct *p) 7944 { 7945 return false; 7946 } 7947 #endif 7948 #endif /* !CONFIG_CFS_BANDWIDTH */ 7949 7950 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL) 7951 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {} 7952 #endif 7953 7954 /************************************************** 7955 * CFS operations on tasks: 7956 */ 7957 7958 #ifdef CONFIG_SCHED_HRTICK 7959 static void hrtick_start_fair(struct rq *rq, struct task_struct *p) 7960 { 7961 struct sched_entity *se = &p->se; 7962 unsigned long scale = 1024; 7963 unsigned long util = 0; 7964 u64 vdelta; 7965 u64 delta; 7966 7967 WARN_ON_ONCE(task_rq(p) != rq); 7968 7969 if (rq->cfs.h_nr_queued <= 1) 7970 return; 7971 7972 /* 7973 * Compute time until virtual deadline 7974 */ 7975 vdelta = se->deadline - se->vruntime; 7976 if ((s64)vdelta < 0) { 7977 if (task_current_donor(rq, p)) 7978 resched_curr(rq); 7979 return; 7980 } 7981 delta = (se->h_load.weight * vdelta) / NICE_0_LOAD; 7982 7983 /* 7984 * Correct for instantaneous load of other classes. 7985 */ 7986 util += cpu_util_irq(rq); 7987 if (util && util < 1024) { 7988 scale *= 1024; 7989 scale /= (1024 - util); 7990 } 7991 7992 hrtick_start(rq, (scale * delta) / 1024); 7993 } 7994 7995 /* 7996 * Called on enqueue to start the hrtick when h_nr_queued becomes more than 1. 7997 */ 7998 static void hrtick_update(struct rq *rq) 7999 { 8000 struct task_struct *donor = rq->donor; 8001 8002 if (!hrtick_enabled_fair(rq) || donor->sched_class != &fair_sched_class) 8003 return; 8004 8005 if (hrtick_active(rq)) 8006 return; 8007 8008 hrtick_start_fair(rq, donor); 8009 } 8010 #else /* !CONFIG_SCHED_HRTICK: */ 8011 static inline void 8012 hrtick_start_fair(struct rq *rq, struct task_struct *p) 8013 { 8014 } 8015 8016 static inline void hrtick_update(struct rq *rq) 8017 { 8018 } 8019 #endif /* !CONFIG_SCHED_HRTICK */ 8020 8021 static inline bool cpu_overutilized(int cpu) 8022 { 8023 unsigned long rq_util_max; 8024 8025 if (!sched_energy_enabled()) 8026 return false; 8027 8028 rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX); 8029 8030 /* Return true only if the utilization doesn't fit CPU's capacity */ 8031 return !util_fits_cpu(cpu_util_cfs(cpu), 0, rq_util_max, cpu); 8032 } 8033 8034 /* 8035 * overutilized value make sense only if EAS is enabled 8036 */ 8037 static inline bool is_rd_overutilized(struct root_domain *rd) 8038 { 8039 return !sched_energy_enabled() || READ_ONCE(rd->overutilized); 8040 } 8041 8042 static inline void set_rd_overutilized(struct root_domain *rd, bool flag) 8043 { 8044 if (!sched_energy_enabled()) 8045 return; 8046 8047 WRITE_ONCE(rd->overutilized, flag); 8048 trace_sched_overutilized_tp(rd, flag); 8049 } 8050 8051 static inline void check_update_overutilized_status(struct rq *rq) 8052 { 8053 /* 8054 * overutilized field is used for load balancing decisions only 8055 * if energy aware scheduler is being used 8056 */ 8057 8058 if (!is_rd_overutilized(rq->rd) && cpu_overutilized(rq->cpu)) 8059 set_rd_overutilized(rq->rd, 1); 8060 } 8061 8062 /* Runqueue only has SCHED_IDLE tasks enqueued */ 8063 static int sched_idle_rq(struct rq *rq) 8064 { 8065 return unlikely(rq->nr_running == rq->cfs.h_nr_idle && 8066 rq->nr_running); 8067 } 8068 8069 static int choose_sched_idle_rq(struct rq *rq, struct task_struct *p) 8070 { 8071 return sched_idle_rq(rq) && !task_has_idle_policy(p); 8072 } 8073 8074 static int choose_idle_cpu(int cpu, struct task_struct *p) 8075 { 8076 return available_idle_cpu(cpu) || 8077 choose_sched_idle_rq(cpu_rq(cpu), p); 8078 } 8079 8080 static void 8081 requeue_delayed_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) 8082 { 8083 /* 8084 * se->sched_delayed should imply: se->on_rq == 1. 8085 * Because a delayed entity is one that is still on 8086 * the runqueue competing until elegibility. 8087 */ 8088 WARN_ON_ONCE(!se->sched_delayed); 8089 WARN_ON_ONCE(!se->on_rq); 8090 8091 if (update_entity_lag(cfs_rq, se)) { 8092 cfs_rq->h_nr_queued--; 8093 if (se != cfs_rq->curr) 8094 __dequeue_entity(cfs_rq, se); 8095 place_entity(cfs_rq, se, 0); 8096 if (se != cfs_rq->curr) 8097 __enqueue_entity(cfs_rq, se); 8098 cfs_rq->h_nr_queued++; 8099 } 8100 8101 update_load_avg(cfs_rq, se, 0); 8102 clear_delayed(se); 8103 } 8104 8105 static unsigned long enqueue_hierarchy(struct task_struct *p, int flags) 8106 { 8107 unsigned long weight = NICE_0_LOAD; 8108 int task_new = !(flags & ENQUEUE_WAKEUP); 8109 struct sched_entity *se = &p->se; 8110 int h_nr_idle = task_has_idle_policy(p); 8111 int h_nr_runnable = 1; 8112 8113 if (task_new && se->sched_delayed) 8114 h_nr_runnable = 0; 8115 8116 for_each_sched_entity(se) { 8117 struct cfs_rq *cfs_rq = cfs_rq_of(se); 8118 8119 update_curr(cfs_rq); 8120 8121 if (!se->on_rq) { 8122 enqueue_entity(cfs_rq, se, flags); 8123 } else { 8124 update_load_avg(cfs_rq, se, UPDATE_TG); 8125 se_update_runnable(se); 8126 update_cfs_group(se); 8127 } 8128 8129 cfs_rq->h_nr_runnable += h_nr_runnable; 8130 cfs_rq->h_nr_queued++; 8131 cfs_rq->h_nr_idle += h_nr_idle; 8132 8133 if (cfs_rq_is_idle(cfs_rq)) 8134 h_nr_idle = 1; 8135 8136 weight = __calc_prop_weight(cfs_rq, se, weight); 8137 8138 flags = ENQUEUE_WAKEUP; 8139 } 8140 8141 return weight; 8142 } 8143 8144 /* Update curr's vruntime before placing entity or updating lag */ 8145 static inline void update_curr_eevdf(struct cfs_rq *cfs_rq) 8146 { 8147 if (!cfs_rq->curr) 8148 return; 8149 8150 update_curr(cfs_rq_of(cfs_rq->curr)); 8151 } 8152 8153 /* 8154 * The enqueue_task method is called before nr_running is 8155 * increased. Here we update the fair scheduling stats and 8156 * then put the task into the rbtree: 8157 */ 8158 static void 8159 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags) 8160 { 8161 int rq_h_nr_queued = rq->cfs.h_nr_queued; 8162 int task_new = !(flags & ENQUEUE_WAKEUP); 8163 struct sched_entity *se = &p->se; 8164 struct cfs_rq *cfs_rq = &rq->cfs; 8165 unsigned long weight; 8166 bool curr; 8167 8168 if (task_is_throttled(p) && enqueue_throttled_task(p)) 8169 return; 8170 8171 /* 8172 * The code below (indirectly) updates schedutil which looks at 8173 * the cfs_rq utilization to select a frequency. 8174 * Let's add the task's estimated utilization to the cfs_rq's 8175 * estimated utilization, before we update schedutil. 8176 */ 8177 if (!p->se.sched_delayed || (flags & ENQUEUE_DELAYED)) 8178 util_est_enqueue(cfs_rq, p); 8179 8180 update_curr_eevdf(cfs_rq); 8181 8182 if (flags & ENQUEUE_DELAYED) { 8183 requeue_delayed_entity(cfs_rq, se); 8184 return; 8185 } 8186 8187 /* 8188 * If in_iowait is set, the code below may not trigger any cpufreq 8189 * utilization updates, so do it here explicitly with the IOWAIT flag 8190 * passed. 8191 */ 8192 if (p->in_iowait) 8193 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT); 8194 8195 curr = (cfs_rq->curr == se); 8196 /* 8197 * This can actually happen with CFS_BANDWIDTH, a task can be throttled 8198 * and dequeued, unthrottled from another CPU and then enqueued again 8199 * before schedule(). 8200 */ 8201 if (curr) 8202 place_entity(cfs_rq, se, flags); 8203 8204 if (se->on_rq && se->sched_delayed) 8205 requeue_delayed_entity(cfs_rq, se); 8206 8207 weight = enqueue_hierarchy(p, flags); 8208 8209 if (!curr) { 8210 reweight_eevdf(cfs_rq, se, weight, false); 8211 place_entity(cfs_rq, se, flags | ENQUEUE_QUEUED); 8212 __enqueue_entity(cfs_rq, se); 8213 } 8214 8215 if (!rq_h_nr_queued && rq->cfs.h_nr_queued) 8216 dl_server_start(&rq->fair_server); 8217 8218 /* At this point se is NULL and we are at root level*/ 8219 add_nr_running(rq, 1); 8220 8221 /* 8222 * Since new tasks are assigned an initial util_avg equal to 8223 * half of the spare capacity of their CPU, tiny tasks have the 8224 * ability to cross the overutilized threshold, which will 8225 * result in the load balancer ruining all the task placement 8226 * done by EAS. As a way to mitigate that effect, do not account 8227 * for the first enqueue operation of new tasks during the 8228 * overutilized flag detection. 8229 * 8230 * A better way of solving this problem would be to wait for 8231 * the PELT signals of tasks to converge before taking them 8232 * into account, but that is not straightforward to implement, 8233 * and the following generally works well enough in practice. 8234 */ 8235 if (!task_new) 8236 check_update_overutilized_status(rq); 8237 8238 assert_list_leaf_cfs_rq(rq); 8239 8240 hrtick_update(rq); 8241 } 8242 8243 static void dequeue_hierarchy(struct task_struct *p, int flags) 8244 { 8245 struct sched_entity *se = &p->se; 8246 bool task_sleep = flags & DEQUEUE_SLEEP; 8247 bool task_delayed = flags & DEQUEUE_DELAYED; 8248 bool task_throttled = flags & DEQUEUE_THROTTLE; 8249 int h_nr_runnable = 0; 8250 int h_nr_idle = task_has_idle_policy(p); 8251 bool dequeue = true; 8252 8253 if (task_sleep || task_delayed || !se->sched_delayed) 8254 h_nr_runnable = 1; 8255 8256 for_each_sched_entity(se) { 8257 struct cfs_rq *cfs_rq = cfs_rq_of(se); 8258 8259 update_curr(cfs_rq); 8260 8261 if (dequeue) { 8262 dequeue_entity(cfs_rq, se, flags); 8263 /* Don't dequeue parent if it has other entities besides us */ 8264 if (cfs_rq->load.weight) 8265 dequeue = false; 8266 } else { 8267 update_load_avg(cfs_rq, se, UPDATE_TG); 8268 se_update_runnable(se); 8269 update_cfs_group(se); 8270 } 8271 8272 cfs_rq->h_nr_runnable -= h_nr_runnable; 8273 cfs_rq->h_nr_queued--; 8274 cfs_rq->h_nr_idle -= h_nr_idle; 8275 8276 if (cfs_rq_is_idle(cfs_rq)) 8277 h_nr_idle = 1; 8278 8279 if (throttled_hierarchy(cfs_rq) && task_throttled) 8280 record_throttle_clock(cfs_rq); 8281 8282 flags |= DEQUEUE_SLEEP; 8283 flags &= ~(DEQUEUE_DELAYED | DEQUEUE_SPECIAL); 8284 } 8285 } 8286 8287 /* 8288 * The part of dequeue_task_fair() that is needed to dequeue delayed tasks. 8289 * 8290 * Returns: 8291 * true - dequeued 8292 * false - delayed 8293 */ 8294 static bool __dequeue_task(struct rq *rq, struct task_struct *p, int flags) 8295 { 8296 struct sched_entity *se = &p->se; 8297 struct cfs_rq *cfs_rq = &rq->cfs; 8298 bool was_sched_idle = sched_idle_rq(rq); 8299 bool task_sleep = flags & DEQUEUE_SLEEP; 8300 bool task_delayed = flags & DEQUEUE_DELAYED; 8301 8302 clear_buddies(cfs_rq, se); 8303 8304 update_curr_eevdf(cfs_rq); 8305 update_entity_lag(cfs_rq, se); 8306 8307 if (flags & DEQUEUE_DELAYED) { 8308 WARN_ON_ONCE(!se->sched_delayed); 8309 } else { 8310 bool delay = task_sleep; 8311 /* 8312 * DELAY_DEQUEUE relies on spurious wakeups, special task 8313 * states must not suffer spurious wakeups, excempt them. 8314 */ 8315 if (flags & (DEQUEUE_SPECIAL | DEQUEUE_THROTTLE)) 8316 delay = false; 8317 8318 WARN_ON_ONCE(delay && se->sched_delayed); 8319 8320 if (sched_feat(DELAY_DEQUEUE) && delay && 8321 !entity_eligible(cfs_rq, se)) { 8322 update_load_avg(cfs_rq_of(se), se, UPDATE_UTIL_EST); 8323 set_delayed(se); 8324 return false; 8325 } 8326 } 8327 8328 dequeue_hierarchy(p, flags); 8329 8330 if (sched_feat(PLACE_REL_DEADLINE) && !task_sleep) { 8331 se->deadline -= se->vruntime; 8332 se->rel_deadline = 1; 8333 } 8334 if (se != cfs_rq->curr) 8335 __dequeue_entity(cfs_rq, se); 8336 8337 sub_nr_running(rq, 1); 8338 8339 /* balance early to pull high priority tasks */ 8340 if (unlikely(!was_sched_idle && sched_idle_rq(rq))) 8341 rq->next_balance = jiffies; 8342 8343 if (task_delayed) { 8344 clear_delayed(se); 8345 8346 WARN_ON_ONCE(!task_sleep); 8347 WARN_ON_ONCE(p->on_rq != 1); 8348 8349 /* 8350 * Fix-up what block_task() skipped. 8351 * 8352 * Must be last, @p might not be valid after this. 8353 */ 8354 __block_task(rq, p); 8355 } 8356 8357 return true; 8358 } 8359 8360 /* 8361 * The dequeue_task method is called before nr_running is 8362 * decreased. We remove the task from the rbtree and 8363 * update the fair scheduling stats: 8364 */ 8365 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags) 8366 { 8367 if (task_is_throttled(p)) { 8368 dequeue_throttled_task(p, flags); 8369 return true; 8370 } 8371 8372 if (!p->se.sched_delayed) 8373 util_est_dequeue(&rq->cfs, p); 8374 8375 if (!__dequeue_task(rq, p, flags)) 8376 return false; 8377 8378 /* 8379 * Must not reference @p after __dequeue_task(DEQUEUE_DELAYED). 8380 */ 8381 return true; 8382 } 8383 8384 static inline unsigned int cfs_h_nr_delayed(struct rq *rq) 8385 { 8386 return (rq->cfs.h_nr_queued - rq->cfs.h_nr_runnable); 8387 } 8388 8389 /* Working cpumask for: sched_balance_rq(), sched_balance_newidle(). */ 8390 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask); 8391 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask); 8392 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask); 8393 8394 #ifdef CONFIG_NO_HZ_COMMON 8395 8396 static struct { 8397 cpumask_var_t idle_cpus_mask; 8398 int has_blocked_load; /* Idle CPUS has blocked load */ 8399 int needs_update; /* Newly idle CPUs need their next_balance collated */ 8400 unsigned long next_balance; /* in jiffy units */ 8401 unsigned long next_blocked; /* Next update of blocked load in jiffies */ 8402 } nohz ____cacheline_aligned; 8403 8404 #endif /* CONFIG_NO_HZ_COMMON */ 8405 8406 static unsigned long cpu_load(struct rq *rq) 8407 { 8408 return cfs_rq_load_avg(&rq->cfs); 8409 } 8410 8411 /* 8412 * cpu_load_without - compute CPU load without any contributions from *p 8413 * @cpu: the CPU which load is requested 8414 * @p: the task which load should be discounted 8415 * 8416 * The load of a CPU is defined by the load of tasks currently enqueued on that 8417 * CPU as well as tasks which are currently sleeping after an execution on that 8418 * CPU. 8419 * 8420 * This method returns the load of the specified CPU by discounting the load of 8421 * the specified task, whenever the task is currently contributing to the CPU 8422 * load. 8423 */ 8424 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p) 8425 { 8426 struct cfs_rq *cfs_rq; 8427 unsigned int load; 8428 8429 /* Task has no contribution or is new */ 8430 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 8431 return cpu_load(rq); 8432 8433 cfs_rq = &rq->cfs; 8434 load = READ_ONCE(cfs_rq->avg.load_avg); 8435 8436 /* Discount task's util from CPU's util */ 8437 lsub_positive(&load, task_h_load(p)); 8438 8439 return load; 8440 } 8441 8442 static unsigned long cpu_runnable(struct rq *rq) 8443 { 8444 return cfs_rq_runnable_avg(&rq->cfs); 8445 } 8446 8447 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p) 8448 { 8449 struct cfs_rq *cfs_rq; 8450 unsigned int runnable; 8451 8452 /* Task has no contribution or is new */ 8453 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 8454 return cpu_runnable(rq); 8455 8456 cfs_rq = &rq->cfs; 8457 runnable = READ_ONCE(cfs_rq->avg.runnable_avg); 8458 8459 /* Discount task's runnable from CPU's runnable */ 8460 lsub_positive(&runnable, p->se.avg.runnable_avg); 8461 8462 return runnable; 8463 } 8464 8465 static unsigned long capacity_of(int cpu) 8466 { 8467 return cpu_rq(cpu)->cpu_capacity; 8468 } 8469 8470 static void record_wakee(struct task_struct *p) 8471 { 8472 /* 8473 * Only decay a single time; tasks that have less then 1 wakeup per 8474 * jiffy will not have built up many flips. 8475 */ 8476 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) { 8477 current->wakee_flips >>= 1; 8478 current->wakee_flip_decay_ts = jiffies; 8479 } 8480 8481 if (current->last_wakee != p) { 8482 current->last_wakee = p; 8483 current->wakee_flips++; 8484 } 8485 } 8486 8487 /* 8488 * Detect M:N waker/wakee relationships via a switching-frequency heuristic. 8489 * 8490 * A waker of many should wake a different task than the one last awakened 8491 * at a frequency roughly N times higher than one of its wakees. 8492 * 8493 * In order to determine whether we should let the load spread vs consolidating 8494 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one 8495 * partner, and a factor of lls_size higher frequency in the other. 8496 * 8497 * With both conditions met, we can be relatively sure that the relationship is 8498 * non-monogamous, with partner count exceeding socket size. 8499 * 8500 * Waker/wakee being client/server, worker/dispatcher, interrupt source or 8501 * whatever is irrelevant, spread criteria is apparent partner count exceeds 8502 * socket size. 8503 */ 8504 static int wake_wide(struct task_struct *p) 8505 { 8506 unsigned int master = current->wakee_flips; 8507 unsigned int slave = p->wakee_flips; 8508 int factor = __this_cpu_read(sd_llc_size); 8509 8510 if (master < slave) 8511 swap(master, slave); 8512 if (slave < factor || master < slave * factor) 8513 return 0; 8514 return 1; 8515 } 8516 8517 /* 8518 * The purpose of wake_affine() is to quickly determine on which CPU we can run 8519 * soonest. For the purpose of speed we only consider the waking and previous 8520 * CPU. 8521 * 8522 * wake_affine_idle() - only considers 'now', it check if the waking CPU is 8523 * cache-affine and is (or will be) idle. 8524 * 8525 * wake_affine_weight() - considers the weight to reflect the average 8526 * scheduling latency of the CPUs. This seems to work 8527 * for the overloaded case. 8528 */ 8529 static int 8530 wake_affine_idle(int this_cpu, int prev_cpu, int sync) 8531 { 8532 /* 8533 * If this_cpu is idle, it implies the wakeup is from interrupt 8534 * context. Only allow the move if cache is shared. Otherwise an 8535 * interrupt intensive workload could force all tasks onto one 8536 * node depending on the IO topology or IRQ affinity settings. 8537 * 8538 * If the prev_cpu is idle and cache affine then avoid a migration. 8539 * There is no guarantee that the cache hot data from an interrupt 8540 * is more important than cache hot data on the prev_cpu and from 8541 * a cpufreq perspective, it's better to have higher utilisation 8542 * on one CPU. 8543 */ 8544 if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu)) 8545 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu; 8546 8547 if (sync) { 8548 struct rq *rq = cpu_rq(this_cpu); 8549 8550 if ((rq->nr_running - cfs_h_nr_delayed(rq)) == 1) 8551 return this_cpu; 8552 } 8553 8554 if (available_idle_cpu(prev_cpu)) 8555 return prev_cpu; 8556 8557 return nr_cpumask_bits; 8558 } 8559 8560 static int 8561 wake_affine_weight(struct sched_domain *sd, struct task_struct *p, 8562 int this_cpu, int prev_cpu, int sync) 8563 { 8564 s64 this_eff_load, prev_eff_load; 8565 unsigned long task_load; 8566 8567 this_eff_load = cpu_load(cpu_rq(this_cpu)); 8568 8569 if (sync) { 8570 unsigned long current_load = task_h_load(current); 8571 8572 if (current_load > this_eff_load) 8573 return this_cpu; 8574 8575 this_eff_load -= current_load; 8576 } 8577 8578 task_load = task_h_load(p); 8579 8580 this_eff_load += task_load; 8581 if (sched_feat(WA_BIAS)) 8582 this_eff_load *= 100; 8583 this_eff_load *= capacity_of(prev_cpu); 8584 8585 prev_eff_load = cpu_load(cpu_rq(prev_cpu)); 8586 prev_eff_load -= task_load; 8587 if (sched_feat(WA_BIAS)) 8588 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2; 8589 prev_eff_load *= capacity_of(this_cpu); 8590 8591 /* 8592 * If sync, adjust the weight of prev_eff_load such that if 8593 * prev_eff == this_eff that select_idle_sibling() will consider 8594 * stacking the wakee on top of the waker if no other CPU is 8595 * idle. 8596 */ 8597 if (sync) 8598 prev_eff_load += 1; 8599 8600 return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits; 8601 } 8602 8603 static int wake_affine(struct sched_domain *sd, struct task_struct *p, 8604 int this_cpu, int prev_cpu, int sync) 8605 { 8606 int target = nr_cpumask_bits; 8607 8608 if (sched_feat(WA_IDLE)) 8609 target = wake_affine_idle(this_cpu, prev_cpu, sync); 8610 8611 if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits) 8612 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync); 8613 8614 schedstat_inc(p->stats.nr_wakeups_affine_attempts); 8615 if (target != this_cpu) 8616 return prev_cpu; 8617 8618 schedstat_inc(sd->ttwu_move_affine); 8619 schedstat_inc(p->stats.nr_wakeups_affine); 8620 return target; 8621 } 8622 8623 static struct sched_group * 8624 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu); 8625 8626 /* 8627 * sched_balance_find_dst_group_cpu - find the idlest CPU among the CPUs in the group. 8628 */ 8629 static int 8630 sched_balance_find_dst_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu) 8631 { 8632 unsigned long load, min_load = ULONG_MAX; 8633 u64 min_exit_latency = U64_MAX; 8634 unsigned int nr_candidates = 0; 8635 int least_loaded_cpu = this_cpu; 8636 int shallowest_idle_cpu = -1; 8637 int i; 8638 8639 /* Check if we have any choice: */ 8640 if (group->group_weight == 1) 8641 return cpumask_first(sched_group_span(group)); 8642 8643 /* Traverse only the allowed CPUs */ 8644 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) { 8645 struct rq *rq = cpu_rq(i); 8646 8647 if (!sched_core_cookie_match(rq, p)) 8648 continue; 8649 8650 if (choose_sched_idle_rq(rq, p)) 8651 return i; 8652 8653 if (available_idle_cpu(i)) { 8654 struct cpuidle_state *idle = idle_get_state(rq); 8655 u64 exit_latency = idle ? idle->exit_latency : U64_MAX; 8656 8657 if (shallowest_idle_cpu == -1 || exit_latency < min_exit_latency) { 8658 min_exit_latency = exit_latency; 8659 shallowest_idle_cpu = i; 8660 nr_candidates = 1; 8661 } else if (exit_latency == min_exit_latency) { 8662 nr_candidates++; 8663 if (!reciprocal_scale(sched_rng(), nr_candidates)) 8664 shallowest_idle_cpu = i; 8665 } 8666 } else if (shallowest_idle_cpu == -1) { 8667 load = cpu_load(cpu_rq(i)); 8668 if (load < min_load) { 8669 min_load = load; 8670 least_loaded_cpu = i; 8671 } 8672 } 8673 } 8674 8675 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu; 8676 } 8677 8678 static inline int sched_balance_find_dst_cpu(struct sched_domain *sd, struct task_struct *p, 8679 int cpu, int prev_cpu, int sd_flag) 8680 { 8681 int new_cpu = cpu; 8682 8683 if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr)) 8684 return prev_cpu; 8685 8686 /* 8687 * We need task's util for cpu_util_without, sync it up to 8688 * prev_cpu's last_update_time. 8689 */ 8690 if (!(sd_flag & SD_BALANCE_FORK)) 8691 sync_entity_load_avg(&p->se); 8692 8693 while (sd) { 8694 struct sched_group *group; 8695 struct sched_domain *tmp; 8696 int weight; 8697 8698 if (!(sd->flags & sd_flag)) { 8699 sd = sd->child; 8700 continue; 8701 } 8702 8703 group = sched_balance_find_dst_group(sd, p, cpu); 8704 if (!group) { 8705 sd = sd->child; 8706 continue; 8707 } 8708 8709 new_cpu = sched_balance_find_dst_group_cpu(group, p, cpu); 8710 if (new_cpu == cpu) { 8711 /* Now try balancing at a lower domain level of 'cpu': */ 8712 sd = sd->child; 8713 continue; 8714 } 8715 8716 /* Now try balancing at a lower domain level of 'new_cpu': */ 8717 cpu = new_cpu; 8718 weight = sd->span_weight; 8719 sd = NULL; 8720 for_each_domain(cpu, tmp) { 8721 if (weight <= tmp->span_weight) 8722 break; 8723 if (tmp->flags & sd_flag) 8724 sd = tmp; 8725 } 8726 } 8727 8728 return new_cpu; 8729 } 8730 8731 static inline int __select_idle_cpu(int cpu, struct task_struct *p) 8732 { 8733 if (choose_idle_cpu(cpu, p) && sched_cpu_cookie_match(cpu_rq(cpu), p)) 8734 return cpu; 8735 8736 return -1; 8737 } 8738 8739 DEFINE_STATIC_KEY_FALSE(sched_smt_present); 8740 EXPORT_SYMBOL_GPL(sched_smt_present); 8741 8742 static inline void set_idle_cores(int cpu, int val) 8743 { 8744 struct sched_domain_shared *sds; 8745 8746 sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu)); 8747 if (sds) 8748 WRITE_ONCE(sds->has_idle_cores, val); 8749 } 8750 8751 static inline bool test_idle_cores(int cpu) 8752 { 8753 struct sched_domain_shared *sds; 8754 8755 sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu)); 8756 if (sds) 8757 return READ_ONCE(sds->has_idle_cores); 8758 8759 return false; 8760 } 8761 8762 /* 8763 * Redirect a CPU to a higher-priority available sibling in its SMT domain, 8764 * subject to task affinity. 8765 */ 8766 static inline int select_idle_smt_cpu(struct task_struct *p, int cpu) 8767 { 8768 struct sched_domain *sd; 8769 int best = cpu; 8770 int sibling; 8771 8772 if (!sched_smt_active()) 8773 return cpu; 8774 8775 sd = rcu_dereference_all(cpu_rq(cpu)->sd); 8776 if (!sd || !(sd->flags & SD_SHARE_CPUCAPACITY) || 8777 !(sd->flags & SD_ASYM_PACKING)) 8778 return cpu; 8779 8780 for_each_cpu_and(sibling, sched_domain_span(sd), p->cpus_ptr) { 8781 if (sibling == best || !choose_idle_cpu(sibling, p)) 8782 continue; 8783 8784 if (sched_asym_prefer(sibling, best)) 8785 best = sibling; 8786 } 8787 8788 return best; 8789 } 8790 8791 /* 8792 * Scans the local SMT mask to see if the entire core is idle, and records this 8793 * information in sd_balance_shared->has_idle_cores. 8794 * 8795 * Since SMT siblings share all cache levels, inspecting this limited remote 8796 * state should be fairly cheap. 8797 */ 8798 void __update_idle_core(struct rq *rq) 8799 { 8800 int core = cpu_of(rq); 8801 int cpu; 8802 8803 rcu_read_lock(); 8804 if (test_idle_cores(core)) 8805 goto unlock; 8806 8807 for_each_cpu(cpu, cpu_smt_mask(core)) { 8808 if (cpu == core) 8809 continue; 8810 8811 if (!available_idle_cpu(cpu)) 8812 goto unlock; 8813 } 8814 8815 set_idle_cores(core, 1); 8816 unlock: 8817 rcu_read_unlock(); 8818 } 8819 8820 /* 8821 * Scan the entire LLC domain for idle cores; this dynamically switches off if 8822 * there are no idle cores left in the system; tracked through 8823 * sd_balance_shared->has_idle_cores and enabled through update_idle_core() 8824 * above. 8825 */ 8826 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu) 8827 { 8828 bool idle = true; 8829 int cpu; 8830 8831 for_each_cpu(cpu, cpu_smt_mask(core)) { 8832 if (!available_idle_cpu(cpu)) { 8833 idle = false; 8834 if (*idle_cpu == -1) { 8835 if (choose_sched_idle_rq(cpu_rq(cpu), p) && 8836 cpumask_test_cpu(cpu, cpus)) { 8837 *idle_cpu = cpu; 8838 break; 8839 } 8840 continue; 8841 } 8842 break; 8843 } 8844 if (*idle_cpu == -1 && cpumask_test_cpu(cpu, cpus)) 8845 *idle_cpu = cpu; 8846 } 8847 8848 if (idle) 8849 return core; 8850 8851 cpumask_andnot(cpus, cpus, cpu_smt_mask(core)); 8852 return -1; 8853 } 8854 8855 /* 8856 * Scan the local SMT mask for idle CPUs. 8857 */ 8858 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target) 8859 { 8860 int cpu; 8861 8862 for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) { 8863 if (cpu == target) 8864 continue; 8865 /* 8866 * Check if the CPU is in the LLC scheduling domain of @target. 8867 * Due to isolcpus, there is no guarantee that all the siblings are in the domain. 8868 */ 8869 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) 8870 continue; 8871 if (choose_idle_cpu(cpu, p)) 8872 return cpu; 8873 } 8874 8875 return -1; 8876 } 8877 8878 /* 8879 * Scan the LLC domain for idle CPUs; this is dynamically regulated by 8880 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the 8881 * average idle time for this rq (as found in rq->avg_idle). 8882 */ 8883 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target) 8884 { 8885 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask); 8886 int i, cpu, idle_cpu = -1, nr = INT_MAX; 8887 8888 if (sched_feat(SIS_UTIL) && sd->shared) { 8889 /* 8890 * Increment because !--nr is the condition to stop scan. 8891 * 8892 * Since "sd" is "sd_llc" for target CPU dereferenced in the 8893 * caller, it is safe to directly dereference "sd->shared". 8894 * Topology bits always ensure it assigned for "sd_llc" abd it 8895 * cannot disappear as long as we have a RCU protected 8896 * reference to one the associated "sd" here. 8897 */ 8898 nr = READ_ONCE(sd->shared->nr_idle_scan) + 1; 8899 /* overloaded LLC is unlikely to have idle cpu/core */ 8900 if (nr == 1) 8901 return -1; 8902 } 8903 8904 if (!cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr)) 8905 return -1; 8906 8907 if (static_branch_unlikely(&sched_cluster_active)) { 8908 struct sched_group *sg = sd->groups; 8909 8910 if (sg->flags & SD_CLUSTER) { 8911 for_each_cpu_wrap(cpu, sched_group_span(sg), target + 1) { 8912 if (!cpumask_test_cpu(cpu, cpus)) 8913 continue; 8914 8915 if (has_idle_core) { 8916 i = select_idle_core(p, cpu, cpus, &idle_cpu); 8917 if ((unsigned int)i < nr_cpumask_bits) 8918 return i; 8919 } else { 8920 if (--nr <= 0) 8921 return -1; 8922 idle_cpu = __select_idle_cpu(cpu, p); 8923 if ((unsigned int)idle_cpu < nr_cpumask_bits) 8924 return idle_cpu; 8925 } 8926 } 8927 cpumask_andnot(cpus, cpus, sched_group_span(sg)); 8928 } 8929 } 8930 8931 for_each_cpu_wrap(cpu, cpus, target + 1) { 8932 if (has_idle_core) { 8933 i = select_idle_core(p, cpu, cpus, &idle_cpu); 8934 if ((unsigned int)i < nr_cpumask_bits) 8935 return i; 8936 8937 } else { 8938 if (--nr <= 0) 8939 return -1; 8940 idle_cpu = __select_idle_cpu(cpu, p); 8941 if ((unsigned int)idle_cpu < nr_cpumask_bits) 8942 break; 8943 } 8944 } 8945 8946 if (has_idle_core) 8947 set_idle_cores(target, false); 8948 8949 return idle_cpu; 8950 } 8951 8952 /* 8953 * Idle-capacity scan converts util_fits_cpu() outcomes into preference ranks, 8954 * where lower values indicate a better fit - see select_idle_capacity(). 8955 * 8956 * A CPU that both fits the task and sits on a fully-idle SMT core is returned 8957 * immediately and is never assigned one of these ranks. On !SMT every CPU is 8958 * its own "core", so the early return covers all fits-and-idle cases and the 8959 * core-tier ranks below become unreachable. 8960 * 8961 * Rank Val Tier Meaning 8962 * ------------------------------ --- ------ --------------------------- 8963 * ASYM_IDLE_UCLAMP_MISFIT -4 core Idle core; capacity fits 8964 * util but uclamp_min misses. 8965 * ASYM_IDLE_COMPLETE_MISFIT -3 core Idle core; capacity does 8966 * not fit. Still beats every 8967 * thread-tier rank: a busy 8968 * sibling cuts effective 8969 * capacity more than a 8970 * misfit hurts a quiet core. 8971 * ASYM_IDLE_THREAD_FITS -2 thread Busy SMT sibling; capacity 8972 * fits util + uclamp. 8973 * ASYM_IDLE_THREAD_UCLAMP_MISFIT -1 thread Busy SMT sibling; capacity 8974 * fits but uclamp_min misses 8975 * (native util_fits_cpu() 8976 * return value). 8977 * ASYM_IDLE_THREAD_MISFIT 0 thread Busy SMT sibling; capacity 8978 * does not fit. 8979 * 8980 * ASYM_IDLE_CORE_BIAS (-3) is an offset, not a state. On an idle core, 8981 * fits += ASYM_IDLE_CORE_BIAS rebases thread-tier ranks into the core tier: 8982 * 8983 * ASYM_IDLE_THREAD_UCLAMP_MISFIT (-1) + BIAS -> ASYM_IDLE_UCLAMP_MISFIT (-4) 8984 * ASYM_IDLE_THREAD_MISFIT (0) + BIAS -> ASYM_IDLE_COMPLETE_MISFIT (-3) 8985 * 8986 * ASYM_IDLE_THREAD_FITS (-2) is never rebased because a fully-fitting idle-core 8987 * candidate early-returns from select_idle_capacity(). 8988 */ 8989 enum asym_fits_state { 8990 ASYM_IDLE_UCLAMP_MISFIT = -4, 8991 ASYM_IDLE_COMPLETE_MISFIT, 8992 ASYM_IDLE_THREAD_FITS, 8993 ASYM_IDLE_THREAD_UCLAMP_MISFIT, 8994 ASYM_IDLE_THREAD_MISFIT, 8995 8996 /* util_fits_cpu() bias for idle core */ 8997 ASYM_IDLE_CORE_BIAS = -3, 8998 }; 8999 9000 /* 9001 * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which 9002 * the task fits. If no CPU is big enough, but there are idle ones, try to 9003 * maximize capacity. 9004 */ 9005 static int 9006 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target) 9007 { 9008 /* 9009 * On !SMT systems, has_idle_core is always false and preferred_core 9010 * is always true (CPU == core), so the SMT preference logic below 9011 * collapses to the plain capacity scan. 9012 */ 9013 bool has_idle_core = sched_smt_active() && test_idle_cores(target); 9014 unsigned long task_util, util_min, util_max, best_cap = 0; 9015 int fits, best_fits = ASYM_IDLE_THREAD_MISFIT; 9016 int cpu, best_cpu = -1; 9017 struct cpumask *cpus; 9018 int nr = INT_MAX; 9019 9020 cpus = this_cpu_cpumask_var_ptr(select_rq_mask); 9021 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr); 9022 9023 task_util = task_util_est(p); 9024 util_min = uclamp_eff_value(p, UCLAMP_MIN); 9025 util_max = uclamp_eff_value(p, UCLAMP_MAX); 9026 9027 if (sched_feat(SIS_UTIL) && sd->shared) { 9028 /* 9029 * Same nr_idle_scan hint as select_idle_cpu(), nr only limits 9030 * the scan when not preferring an idle core. 9031 */ 9032 nr = READ_ONCE(sd->shared->nr_idle_scan) + 1; 9033 /* overloaded domain is unlikely to have idle cpu/core */ 9034 if (nr == 1) 9035 return -1; 9036 } 9037 9038 for_each_cpu_wrap(cpu, cpus, target) { 9039 bool preferred_core = !has_idle_core || is_core_idle(cpu); 9040 unsigned long cpu_cap = capacity_of(cpu); 9041 9042 /* 9043 * Stop when the nr_idle_scan is exhausted (mirrors 9044 * select_idle_cpu() logic). 9045 */ 9046 if (!has_idle_core && --nr <= 0) 9047 return best_cpu; 9048 9049 if (!choose_idle_cpu(cpu, p)) 9050 continue; 9051 9052 fits = util_fits_cpu(task_util, util_min, util_max, cpu); 9053 9054 /* 9055 * Perfect fit: capacity satisfies util + uclamp and the CPU 9056 * sits on a fully-idle SMT core, this is a !SMT system, or 9057 * there is no idle core to find. 9058 * Short-circuit the rank-based selection and return 9059 * immediately. 9060 */ 9061 if (fits > 0 && preferred_core) 9062 return cpu; 9063 /* 9064 * Only the min performance hint (i.e. uclamp_min) doesn't fit. 9065 * Look for the CPU with best capacity. 9066 */ 9067 else if (fits < 0) 9068 cpu_cap = get_actual_cpu_capacity(cpu); 9069 /* 9070 * fits > 0 implies we are not on a preferred core, but the util 9071 * fits CPU capacity. Set fits to ASYM_IDLE_THREAD_FITS 9072 * so the effective range becomes 9073 * [ASYM_IDLE_THREAD_FITS, ASYM_IDLE_THREAD_MISFIT], where: 9074 * ASYM_IDLE_THREAD_MISFIT - does not fit 9075 * ASYM_IDLE_THREAD_UCLAMP_MISFIT - fits with the exception of UCLAMP_MIN 9076 * ASYM_IDLE_THREAD_FITS - fits with the exception of preferred_core 9077 */ 9078 else if (fits > 0) 9079 fits = ASYM_IDLE_THREAD_FITS; 9080 9081 /* 9082 * If we are on a preferred core, translate the range of fits 9083 * of [ASYM_IDLE_THREAD_UCLAMP_MISFIT, ASYM_IDLE_THREAD_MISFIT] to 9084 * [ASYM_IDLE_UCLAMP_MISFIT, ASYM_IDLE_COMPLETE_MISFIT]. 9085 * This ensures that an idle core is always given priority over 9086 * (partially) busy core. 9087 * 9088 * A fully fitting idle core would have returned early and hence 9089 * fits > 0 for preferred_core need not be dealt with. 9090 */ 9091 if (preferred_core) 9092 fits += ASYM_IDLE_CORE_BIAS; 9093 9094 /* 9095 * First, select CPU which fits better (lower is more preferred). 9096 * Then, select the one with best capacity at same level. 9097 */ 9098 if ((fits < best_fits) || 9099 ((fits == best_fits) && (cpu_cap > best_cap))) { 9100 best_cap = cpu_cap; 9101 best_cpu = cpu; 9102 best_fits = fits; 9103 } 9104 } 9105 9106 /* 9107 * A value in the [ASYM_IDLE_UCLAMP_MISFIT, ASYM_IDLE_COMPLETE_MISFIT] 9108 * range means the chosen CPU is in a fully idle SMT core. Values above 9109 * ASYM_IDLE_COMPLETE_MISFIT mean we never ranked such a CPU best. 9110 * 9111 * The asym-capacity wakeup path returns from select_idle_sibling() 9112 * after this function and never runs select_idle_cpu(), so the usual 9113 * select_idle_cpu() tail that clears idle cores must live here when the 9114 * idle-core preference did not win. 9115 */ 9116 if (has_idle_core && best_fits > ASYM_IDLE_COMPLETE_MISFIT) 9117 set_idle_cores(target, false); 9118 9119 return best_cpu; 9120 } 9121 9122 static inline bool asym_fits_cpu(unsigned long util, 9123 unsigned long util_min, 9124 unsigned long util_max, 9125 int cpu) 9126 { 9127 if (sched_asym_cpucap_active()) { 9128 /* 9129 * Return true only if the cpu fully fits the task requirements 9130 * which include the utilization and the performance hints. 9131 * 9132 * When SMT is active, also require that the core has no busy 9133 * siblings. 9134 * 9135 * Note: gating on is_core_idle() also makes the early-bailout 9136 * candidates in select_idle_sibling() (target, prev, 9137 * recent_used_cpu) idle-core-aware on ASYM+SMT, which the 9138 * NO_ASYM path does not do. 9139 */ 9140 return (!sched_smt_active() || is_core_idle(cpu)) && 9141 (util_fits_cpu(util, util_min, util_max, cpu) > 0); 9142 } 9143 9144 return true; 9145 } 9146 9147 /* 9148 * Try and locate an idle core/thread in the LLC cache domain. 9149 */ 9150 static int select_idle_sibling(struct task_struct *p, int prev, int target) 9151 { 9152 bool has_idle_core = false; 9153 struct sched_domain *sd; 9154 unsigned long task_util, util_min, util_max; 9155 int i, recent_used_cpu, prev_aff = -1; 9156 9157 /* 9158 * On asymmetric system, update task utilization because we will check 9159 * that the task fits with CPU's capacity. 9160 */ 9161 if (sched_asym_cpucap_active()) { 9162 sync_entity_load_avg(&p->se); 9163 task_util = task_util_est(p); 9164 util_min = uclamp_eff_value(p, UCLAMP_MIN); 9165 util_max = uclamp_eff_value(p, UCLAMP_MAX); 9166 } 9167 9168 /* 9169 * per-cpu select_rq_mask usage 9170 */ 9171 lockdep_assert_irqs_disabled(); 9172 9173 if (choose_idle_cpu(target, p) && 9174 asym_fits_cpu(task_util, util_min, util_max, target)) 9175 goto select_smt_priority; 9176 9177 /* 9178 * If the previous CPU is cache affine and idle, don't be stupid: 9179 */ 9180 if (prev != target && cpus_share_cache(prev, target) && 9181 choose_idle_cpu(prev, p) && 9182 asym_fits_cpu(task_util, util_min, util_max, prev)) { 9183 9184 if (!static_branch_unlikely(&sched_cluster_active) || 9185 cpus_share_resources(prev, target)) { 9186 target = prev; 9187 goto select_smt_priority; 9188 } 9189 9190 prev_aff = prev; 9191 } 9192 9193 /* 9194 * Allow a per-cpu kthread to stack with the wakee if the 9195 * kworker thread and the tasks previous CPUs are the same. 9196 * The assumption is that the wakee queued work for the 9197 * per-cpu kthread that is now complete and the wakeup is 9198 * essentially a sync wakeup. An obvious example of this 9199 * pattern is IO completions. 9200 */ 9201 if (is_per_cpu_kthread(current) && 9202 in_task() && 9203 prev == smp_processor_id() && 9204 this_rq()->nr_running <= 1 && 9205 asym_fits_cpu(task_util, util_min, util_max, prev)) { 9206 target = prev; 9207 goto select_smt_priority; 9208 } 9209 9210 /* Check a recently used CPU as a potential idle candidate: */ 9211 recent_used_cpu = p->recent_used_cpu; 9212 p->recent_used_cpu = prev; 9213 if (recent_used_cpu != prev && 9214 recent_used_cpu != target && 9215 cpus_share_cache(recent_used_cpu, target) && 9216 choose_idle_cpu(recent_used_cpu, p) && 9217 cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) && 9218 asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) { 9219 9220 if (!static_branch_unlikely(&sched_cluster_active) || 9221 cpus_share_resources(recent_used_cpu, target)) { 9222 target = recent_used_cpu; 9223 goto select_smt_priority; 9224 } 9225 9226 } else { 9227 recent_used_cpu = -1; 9228 } 9229 9230 /* 9231 * For asymmetric CPU capacity systems, our domain of interest is 9232 * sd_asym_cpucapacity rather than sd_llc. 9233 */ 9234 if (sched_asym_cpucap_active()) { 9235 sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, target)); 9236 /* 9237 * On an asymmetric CPU capacity system where an exclusive 9238 * cpuset defines a symmetric island (i.e. one unique 9239 * capacity_orig value through the cpuset), the key will be set 9240 * but the CPUs within that cpuset will not have a domain with 9241 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric 9242 * capacity path. 9243 */ 9244 if (sd) { 9245 i = select_idle_capacity(p, sd, target); 9246 if ((unsigned int)i < nr_cpumask_bits) { 9247 target = i; 9248 goto select_smt_priority; 9249 } 9250 return target; 9251 } 9252 } 9253 9254 sd = rcu_dereference_all(per_cpu(sd_llc, target)); 9255 if (!sd) 9256 return target; 9257 9258 if (sched_smt_active()) { 9259 has_idle_core = test_idle_cores(target); 9260 9261 if (!has_idle_core && cpus_share_cache(prev, target)) { 9262 i = select_idle_smt(p, sd, prev); 9263 if ((unsigned int)i < nr_cpumask_bits) { 9264 target = i; 9265 goto select_smt_priority; 9266 } 9267 } 9268 } 9269 9270 i = select_idle_cpu(p, sd, has_idle_core, target); 9271 if ((unsigned int)i < nr_cpumask_bits) { 9272 target = i; 9273 goto select_smt_priority; 9274 } 9275 9276 /* 9277 * For cluster machines which have lower sharing cache like L2 or 9278 * LLC Tag, we tend to find an idle CPU in the target's cluster 9279 * first. But prev_cpu or recent_used_cpu may also be a good candidate, 9280 * use them if possible when no idle CPU found in select_idle_cpu(). 9281 */ 9282 if ((unsigned int)prev_aff < nr_cpumask_bits) { 9283 target = prev_aff; 9284 goto select_smt_priority; 9285 } 9286 if ((unsigned int)recent_used_cpu < nr_cpumask_bits) { 9287 target = recent_used_cpu; 9288 goto select_smt_priority; 9289 } 9290 9291 return target; 9292 9293 select_smt_priority: 9294 return select_idle_smt_cpu(p, target); 9295 } 9296 9297 /** 9298 * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks. 9299 * @cpu: the CPU to get the utilization for 9300 * @p: task for which the CPU utilization should be predicted or NULL 9301 * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL 9302 * @boost: 1 to enable boosting, otherwise 0 9303 * 9304 * The unit of the return value must be the same as the one of CPU capacity 9305 * so that CPU utilization can be compared with CPU capacity. 9306 * 9307 * CPU utilization is the sum of running time of runnable tasks plus the 9308 * recent utilization of currently non-runnable tasks on that CPU. 9309 * It represents the amount of CPU capacity currently used by CFS tasks in 9310 * the range [0..max CPU capacity] with max CPU capacity being the CPU 9311 * capacity at f_max. 9312 * 9313 * The estimated CPU utilization is defined as the maximum between CPU 9314 * utilization and sum of the estimated utilization of the currently 9315 * runnable tasks on that CPU. It preserves a utilization "snapshot" of 9316 * previously-executed tasks, which helps better deduce how busy a CPU will 9317 * be when a long-sleeping task wakes up. The contribution to CPU utilization 9318 * of such a task would be significantly decayed at this point of time. 9319 * 9320 * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization). 9321 * CPU contention for CFS tasks can be detected by CPU runnable > CPU 9322 * utilization. Boosting is implemented in cpu_util() so that internal 9323 * users (e.g. EAS) can use it next to external users (e.g. schedutil), 9324 * latter via cpu_util_cfs_boost(). 9325 * 9326 * CPU utilization can be higher than the current CPU capacity 9327 * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because 9328 * of rounding errors as well as task migrations or wakeups of new tasks. 9329 * CPU utilization has to be capped to fit into the [0..max CPU capacity] 9330 * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%) 9331 * could be seen as over-utilized even though CPU1 has 20% of spare CPU 9332 * capacity. CPU utilization is allowed to overshoot current CPU capacity 9333 * though since this is useful for predicting the CPU capacity required 9334 * after task migrations (scheduler-driven DVFS). 9335 * 9336 * Return: (Boosted) (estimated) utilization for the specified CPU. 9337 */ 9338 static unsigned long 9339 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost) 9340 { 9341 bool add_task = p && task_cpu(p) != cpu && dst_cpu == cpu; 9342 bool sub_task = p && task_cpu(p) == cpu && dst_cpu != cpu; 9343 struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs; 9344 unsigned long util = READ_ONCE(cfs_rq->avg.util_avg); 9345 unsigned long runnable; 9346 9347 /* 9348 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its 9349 * contribution. If @p migrates from another CPU to @cpu add its 9350 * contribution. In all the other cases @cpu is not impacted by the 9351 * migration so its util_avg is already correct. 9352 */ 9353 if (add_task) 9354 util += task_util(p); 9355 else if (sub_task) 9356 lsub_positive(&util, task_util(p)); 9357 9358 if (boost) { 9359 runnable = READ_ONCE(cfs_rq->avg.runnable_avg); 9360 if (add_task) 9361 runnable += READ_ONCE(p->se.avg.runnable_avg); 9362 else if (sub_task) 9363 lsub_positive(&runnable, 9364 READ_ONCE(p->se.avg.runnable_avg)); 9365 util = max(util, runnable); 9366 } 9367 9368 if (sched_feat(UTIL_EST)) { 9369 unsigned long util_est; 9370 9371 util_est = READ_ONCE(cfs_rq->avg.util_est); 9372 9373 /* 9374 * During wake-up @p isn't enqueued yet and doesn't contribute 9375 * to any cpu_rq(cpu)->cfs.avg.util_est. 9376 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p 9377 * has been enqueued. 9378 * 9379 * During exec (@dst_cpu = -1) @p is enqueued and does 9380 * contribute to cpu_rq(cpu)->cfs.util_est. 9381 * Remove it to "simulate" cpu_util without @p's contribution. 9382 * 9383 * Despite the task_on_rq_queued(@p) check there is still a 9384 * small window for a possible race when an exec 9385 * select_task_rq_fair() races with LB's detach_task(). 9386 * 9387 * detach_task() 9388 * deactivate_task() 9389 * p->on_rq = TASK_ON_RQ_MIGRATING; 9390 * -------------------------------- A 9391 * dequeue_task() \ 9392 * dequeue_task_fair() + Race Time 9393 * util_est_dequeue() / 9394 * -------------------------------- B 9395 * 9396 * The additional check "current == p" is required to further 9397 * reduce the race window. 9398 */ 9399 if (dst_cpu == cpu) 9400 util_est += _task_util_est(p); 9401 else if (p && unlikely(task_on_rq_queued(p) || current == p)) 9402 lsub_positive(&util_est, _task_util_est(p)); 9403 9404 util = max(util, util_est); 9405 } 9406 9407 return min(util, arch_scale_cpu_capacity(cpu)); 9408 } 9409 9410 unsigned long cpu_util_cfs(int cpu) 9411 { 9412 return cpu_util(cpu, NULL, -1, 0); 9413 } 9414 9415 unsigned long cpu_util_cfs_boost(int cpu) 9416 { 9417 return cpu_util(cpu, NULL, -1, 1); 9418 } 9419 9420 /* 9421 * cpu_util_without: compute cpu utilization without any contributions from *p 9422 * @cpu: the CPU which utilization is requested 9423 * @p: the task which utilization should be discounted 9424 * 9425 * The utilization of a CPU is defined by the utilization of tasks currently 9426 * enqueued on that CPU as well as tasks which are currently sleeping after an 9427 * execution on that CPU. 9428 * 9429 * This method returns the utilization of the specified CPU by discounting the 9430 * utilization of the specified task, whenever the task is currently 9431 * contributing to the CPU utilization. 9432 */ 9433 static unsigned long cpu_util_without(int cpu, struct task_struct *p) 9434 { 9435 /* Task has no contribution or is new */ 9436 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 9437 p = NULL; 9438 9439 return cpu_util(cpu, p, -1, 0); 9440 } 9441 9442 /* 9443 * This function computes an effective utilization for the given CPU, to be 9444 * used for frequency selection given the linear relation: f = u * f_max. 9445 * 9446 * The scheduler tracks the following metrics: 9447 * 9448 * cpu_util_{cfs,rt,dl,irq}() 9449 * cpu_bw_dl() 9450 * 9451 * Where the cfs,rt and dl util numbers are tracked with the same metric and 9452 * synchronized windows and are thus directly comparable. 9453 * 9454 * The cfs,rt,dl utilization are the running times measured with rq->clock_task 9455 * which excludes things like IRQ and steal-time. These latter are then accrued 9456 * in the IRQ utilization. 9457 * 9458 * The DL bandwidth number OTOH is not a measured metric but a value computed 9459 * based on the task model parameters and gives the minimal utilization 9460 * required to meet deadlines. 9461 */ 9462 unsigned long effective_cpu_util(int cpu, unsigned long util_cfs, 9463 unsigned long *min, 9464 unsigned long *max) 9465 { 9466 unsigned long util, irq, scale; 9467 struct rq *rq = cpu_rq(cpu); 9468 9469 scale = arch_scale_cpu_capacity(cpu); 9470 9471 /* 9472 * Early check to see if IRQ/steal time saturates the CPU, can be 9473 * because of inaccuracies in how we track these -- see 9474 * update_irq_load_avg(). 9475 */ 9476 irq = cpu_util_irq(rq); 9477 if (unlikely(irq >= scale)) { 9478 if (min) 9479 *min = scale; 9480 if (max) 9481 *max = scale; 9482 return scale; 9483 } 9484 9485 if (min) { 9486 /* 9487 * The minimum utilization returns the highest level between: 9488 * - the computed DL bandwidth needed with the IRQ pressure which 9489 * steals time to the deadline task. 9490 * - The minimum performance requirement for CFS and/or RT. 9491 */ 9492 *min = max(irq + cpu_bw_dl(rq), uclamp_rq_get(rq, UCLAMP_MIN)); 9493 9494 /* 9495 * When an RT task is runnable and uclamp is not used, we must 9496 * ensure that the task will run at maximum compute capacity. 9497 */ 9498 if (!uclamp_is_used() && rt_rq_is_runnable(&rq->rt)) 9499 *min = max(*min, scale); 9500 } 9501 9502 /* 9503 * Because the time spend on RT/DL tasks is visible as 'lost' time to 9504 * CFS tasks and we use the same metric to track the effective 9505 * utilization (PELT windows are synchronized) we can directly add them 9506 * to obtain the CPU's actual utilization. 9507 */ 9508 util = util_cfs + cpu_util_rt(rq); 9509 util += cpu_util_dl(rq); 9510 9511 /* 9512 * The maximum hint is a soft bandwidth requirement, which can be lower 9513 * than the actual utilization because of uclamp_max requirements. 9514 */ 9515 if (max) 9516 *max = min(scale, uclamp_rq_get(rq, UCLAMP_MAX)); 9517 9518 if (util >= scale) 9519 return scale; 9520 9521 /* 9522 * There is still idle time; further improve the number by using the 9523 * IRQ metric. Because IRQ/steal time is hidden from the task clock we 9524 * need to scale the task numbers: 9525 * 9526 * max - irq 9527 * U' = irq + --------- * U 9528 * max 9529 */ 9530 util = scale_irq_capacity(util, irq, scale); 9531 util += irq; 9532 9533 return min(scale, util); 9534 } 9535 9536 unsigned long sched_cpu_util(int cpu) 9537 { 9538 return effective_cpu_util(cpu, cpu_util_cfs(cpu), NULL, NULL); 9539 } 9540 9541 /* 9542 * energy_env - Utilization landscape for energy estimation. 9543 * @task_busy_time: Utilization contribution by the task for which we test the 9544 * placement. Given by eenv_task_busy_time(). 9545 * @pd_busy_time: Utilization of the whole perf domain without the task 9546 * contribution. Given by eenv_pd_busy_time(). 9547 * @cpu_cap: Maximum CPU capacity for the perf domain. 9548 * @pd_cap: Entire perf domain capacity. (pd->nr_cpus * cpu_cap). 9549 */ 9550 struct energy_env { 9551 unsigned long task_busy_time; 9552 unsigned long pd_busy_time; 9553 unsigned long cpu_cap; 9554 unsigned long pd_cap; 9555 }; 9556 9557 /* 9558 * Compute the task busy time for compute_energy(). This time cannot be 9559 * injected directly into effective_cpu_util() because of the IRQ scaling. 9560 * The latter only makes sense with the most recent CPUs where the task has 9561 * run. 9562 */ 9563 static inline void eenv_task_busy_time(struct energy_env *eenv, 9564 struct task_struct *p, int prev_cpu) 9565 { 9566 unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu); 9567 unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu)); 9568 9569 if (unlikely(irq >= max_cap)) 9570 busy_time = max_cap; 9571 else 9572 busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap); 9573 9574 eenv->task_busy_time = busy_time; 9575 } 9576 9577 /* 9578 * Compute the perf_domain (PD) busy time for compute_energy(). Based on the 9579 * utilization for each @pd_cpus, it however doesn't take into account 9580 * clamping since the ratio (utilization / cpu_capacity) is already enough to 9581 * scale the EM reported power consumption at the (eventually clamped) 9582 * cpu_capacity. 9583 * 9584 * The contribution of the task @p for which we want to estimate the 9585 * energy cost is removed (by cpu_util()) and must be calculated 9586 * separately (see eenv_task_busy_time). This ensures: 9587 * 9588 * - A stable PD utilization, no matter which CPU of that PD we want to place 9589 * the task on. 9590 * 9591 * - A fair comparison between CPUs as the task contribution (task_util()) 9592 * will always be the same no matter which CPU utilization we rely on 9593 * (util_avg or util_est). 9594 * 9595 * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't 9596 * exceed @eenv->pd_cap. 9597 */ 9598 static inline void eenv_pd_busy_time(struct energy_env *eenv, 9599 struct cpumask *pd_cpus, 9600 struct task_struct *p) 9601 { 9602 unsigned long busy_time = 0; 9603 int cpu; 9604 9605 for_each_cpu(cpu, pd_cpus) { 9606 unsigned long util = cpu_util(cpu, p, -1, 0); 9607 9608 busy_time += effective_cpu_util(cpu, util, NULL, NULL); 9609 } 9610 9611 eenv->pd_busy_time = min(eenv->pd_cap, busy_time); 9612 } 9613 9614 /* 9615 * Compute the maximum utilization for compute_energy() when the task @p 9616 * is placed on the cpu @dst_cpu. 9617 * 9618 * Returns the maximum utilization among @eenv->cpus. This utilization can't 9619 * exceed @eenv->cpu_cap. 9620 */ 9621 static inline unsigned long 9622 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus, 9623 struct task_struct *p, int dst_cpu) 9624 { 9625 unsigned long max_util = 0; 9626 int cpu; 9627 9628 for_each_cpu(cpu, pd_cpus) { 9629 struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL; 9630 unsigned long util = cpu_util(cpu, p, dst_cpu, 1); 9631 unsigned long eff_util, min, max; 9632 9633 /* 9634 * Performance domain frequency: utilization clamping 9635 * must be considered since it affects the selection 9636 * of the performance domain frequency. 9637 * NOTE: in case RT tasks are running, by default the min 9638 * utilization can be max OPP. 9639 */ 9640 eff_util = effective_cpu_util(cpu, util, &min, &max); 9641 9642 /* Task's uclamp can modify min and max value */ 9643 if (tsk && uclamp_is_used()) { 9644 min = max(min, uclamp_eff_value(p, UCLAMP_MIN)); 9645 9646 /* 9647 * If there is no active max uclamp constraint, 9648 * directly use task's one, otherwise keep max. 9649 */ 9650 if (uclamp_rq_is_idle(cpu_rq(cpu))) 9651 max = uclamp_eff_value(p, UCLAMP_MAX); 9652 else 9653 max = max(max, uclamp_eff_value(p, UCLAMP_MAX)); 9654 } 9655 9656 eff_util = sugov_effective_cpu_perf(cpu, eff_util, min, max); 9657 max_util = max(max_util, eff_util); 9658 } 9659 9660 return min(max_util, eenv->cpu_cap); 9661 } 9662 9663 /* 9664 * compute_energy(): Use the Energy Model to estimate the energy that @pd would 9665 * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task 9666 * contribution is ignored. 9667 */ 9668 static inline unsigned long 9669 compute_energy(struct energy_env *eenv, struct perf_domain *pd, 9670 struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu) 9671 { 9672 unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu); 9673 unsigned long busy_time = eenv->pd_busy_time; 9674 unsigned long energy; 9675 9676 if (dst_cpu >= 0) 9677 busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time); 9678 9679 energy = em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap); 9680 9681 trace_sched_compute_energy_tp(p, dst_cpu, energy, max_util, busy_time); 9682 9683 return energy; 9684 } 9685 9686 /* 9687 * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the 9688 * waking task. find_energy_efficient_cpu() looks for the CPU with maximum 9689 * spare capacity in each performance domain and uses it as a potential 9690 * candidate to execute the task. Then, it uses the Energy Model to figure 9691 * out which of the CPU candidates is the most energy-efficient. 9692 * 9693 * The rationale for this heuristic is as follows. In a performance domain, 9694 * all the most energy efficient CPU candidates (according to the Energy 9695 * Model) are those for which we'll request a low frequency. When there are 9696 * several CPUs for which the frequency request will be the same, we don't 9697 * have enough data to break the tie between them, because the Energy Model 9698 * only includes active power costs. With this model, if we assume that 9699 * frequency requests follow utilization (e.g. using schedutil), the CPU with 9700 * the maximum spare capacity in a performance domain is guaranteed to be among 9701 * the best candidates of the performance domain. 9702 * 9703 * In practice, it could be preferable from an energy standpoint to pack 9704 * small tasks on a CPU in order to let other CPUs go in deeper idle states, 9705 * but that could also hurt our chances to go cluster idle, and we have no 9706 * ways to tell with the current Energy Model if this is actually a good 9707 * idea or not. So, find_energy_efficient_cpu() basically favors 9708 * cluster-packing, and spreading inside a cluster. That should at least be 9709 * a good thing for latency, and this is consistent with the idea that most 9710 * of the energy savings of EAS come from the asymmetry of the system, and 9711 * not so much from breaking the tie between identical CPUs. That's also the 9712 * reason why EAS is enabled in the topology code only for systems where 9713 * SD_ASYM_CPUCAPACITY is set. 9714 * 9715 * NOTE: Forkees are not accepted in the energy-aware wake-up path because 9716 * they don't have any useful utilization data yet and it's not possible to 9717 * forecast their impact on energy consumption. Consequently, they will be 9718 * placed by sched_balance_find_dst_cpu() on the least loaded CPU, which might turn out 9719 * to be energy-inefficient in some use-cases. The alternative would be to 9720 * bias new tasks towards specific types of CPUs first, or to try to infer 9721 * their util_avg from the parent task, but those heuristics could hurt 9722 * other use-cases too. So, until someone finds a better way to solve this, 9723 * let's keep things simple by re-using the existing slow path. 9724 */ 9725 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu) 9726 { 9727 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask); 9728 unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX; 9729 unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0; 9730 unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024; 9731 struct root_domain *rd = this_rq()->rd; 9732 int cpu, best_energy_cpu, target = -1; 9733 int prev_fits = -1, best_fits = -1; 9734 unsigned long best_actual_cap = 0; 9735 unsigned long prev_actual_cap = 0; 9736 struct sched_domain *sd; 9737 struct perf_domain *pd; 9738 struct energy_env eenv; 9739 9740 pd = rcu_dereference_all(rd->pd); 9741 if (!pd) 9742 return target; 9743 9744 /* 9745 * Energy-aware wake-up happens on the lowest sched_domain starting 9746 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu. 9747 */ 9748 sd = rcu_dereference_all(*this_cpu_ptr(&sd_asym_cpucapacity)); 9749 while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd))) 9750 sd = sd->parent; 9751 if (!sd) 9752 return target; 9753 9754 target = prev_cpu; 9755 9756 sync_entity_load_avg(&p->se); 9757 if (!task_util_est(p) && p_util_min == 0) 9758 return target; 9759 9760 eenv_task_busy_time(&eenv, p, prev_cpu); 9761 9762 for (; pd; pd = pd->next) { 9763 unsigned long util_min = p_util_min, util_max = p_util_max; 9764 unsigned long cpu_cap, cpu_actual_cap, util; 9765 long prev_spare_cap = -1, max_spare_cap = -1; 9766 unsigned long rq_util_min, rq_util_max; 9767 unsigned long cur_delta, base_energy; 9768 int max_spare_cap_cpu = -1; 9769 int fits, max_fits = -1; 9770 9771 if (!cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask)) 9772 continue; 9773 9774 /* Account external pressure for the energy estimation */ 9775 cpu = cpumask_first(cpus); 9776 cpu_actual_cap = get_actual_cpu_capacity(cpu); 9777 9778 eenv.cpu_cap = cpu_actual_cap; 9779 eenv.pd_cap = 0; 9780 9781 for_each_cpu(cpu, cpus) { 9782 struct rq *rq = cpu_rq(cpu); 9783 9784 eenv.pd_cap += cpu_actual_cap; 9785 9786 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) 9787 continue; 9788 9789 if (!cpumask_test_cpu(cpu, p->cpus_ptr)) 9790 continue; 9791 9792 util = cpu_util(cpu, p, cpu, 0); 9793 cpu_cap = capacity_of(cpu); 9794 9795 /* 9796 * Skip CPUs that cannot satisfy the capacity request. 9797 * IOW, placing the task there would make the CPU 9798 * overutilized. Take uclamp into account to see how 9799 * much capacity we can get out of the CPU; this is 9800 * aligned with sched_cpu_util(). 9801 */ 9802 if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) { 9803 /* 9804 * Open code uclamp_rq_util_with() except for 9805 * the clamp() part. I.e.: apply max aggregation 9806 * only. util_fits_cpu() logic requires to 9807 * operate on non clamped util but must use the 9808 * max-aggregated uclamp_{min, max}. 9809 */ 9810 rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN); 9811 rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX); 9812 9813 util_min = max(rq_util_min, p_util_min); 9814 util_max = max(rq_util_max, p_util_max); 9815 } 9816 9817 fits = util_fits_cpu(util, util_min, util_max, cpu); 9818 if (!fits) 9819 continue; 9820 9821 lsub_positive(&cpu_cap, util); 9822 9823 if (cpu == prev_cpu) { 9824 /* Always use prev_cpu as a candidate. */ 9825 prev_spare_cap = cpu_cap; 9826 prev_fits = fits; 9827 } else if ((fits > max_fits) || 9828 ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) { 9829 /* 9830 * Find the CPU with the maximum spare capacity 9831 * among the remaining CPUs in the performance 9832 * domain. 9833 */ 9834 max_spare_cap = cpu_cap; 9835 max_spare_cap_cpu = cpu; 9836 max_fits = fits; 9837 } 9838 } 9839 9840 if (max_spare_cap_cpu < 0 && prev_spare_cap < 0) 9841 continue; 9842 9843 eenv_pd_busy_time(&eenv, cpus, p); 9844 /* Compute the 'base' energy of the pd, without @p */ 9845 base_energy = compute_energy(&eenv, pd, cpus, p, -1); 9846 9847 /* Evaluate the energy impact of using prev_cpu. */ 9848 if (prev_spare_cap > -1) { 9849 prev_delta = compute_energy(&eenv, pd, cpus, p, 9850 prev_cpu); 9851 /* CPU utilization has changed */ 9852 if (prev_delta < base_energy) 9853 return target; 9854 prev_delta -= base_energy; 9855 prev_actual_cap = cpu_actual_cap; 9856 best_delta = min(best_delta, prev_delta); 9857 } 9858 9859 /* Evaluate the energy impact of using max_spare_cap_cpu. */ 9860 if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) { 9861 /* Current best energy cpu fits better */ 9862 if (max_fits < best_fits) 9863 continue; 9864 9865 /* 9866 * Both don't fit performance hint (i.e. uclamp_min) 9867 * but best energy cpu has better capacity. 9868 */ 9869 if ((max_fits < 0) && 9870 (cpu_actual_cap <= best_actual_cap)) 9871 continue; 9872 9873 cur_delta = compute_energy(&eenv, pd, cpus, p, 9874 max_spare_cap_cpu); 9875 /* CPU utilization has changed */ 9876 if (cur_delta < base_energy) 9877 return target; 9878 cur_delta -= base_energy; 9879 9880 /* 9881 * Both fit for the task but best energy cpu has lower 9882 * energy impact. 9883 */ 9884 if ((max_fits > 0) && (best_fits > 0) && 9885 (cur_delta >= best_delta)) 9886 continue; 9887 9888 best_delta = cur_delta; 9889 best_energy_cpu = max_spare_cap_cpu; 9890 best_fits = max_fits; 9891 best_actual_cap = cpu_actual_cap; 9892 } 9893 } 9894 9895 if ((best_fits > prev_fits) || 9896 ((best_fits > 0) && (best_delta < prev_delta)) || 9897 ((best_fits < 0) && (best_actual_cap > prev_actual_cap))) 9898 target = best_energy_cpu; 9899 9900 return target; 9901 } 9902 9903 /* 9904 * select_task_rq_fair: Select target runqueue for the waking task in domains 9905 * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE, 9906 * SD_BALANCE_FORK, or SD_BALANCE_EXEC. 9907 * 9908 * Balances load by selecting the idlest CPU in the idlest group, or under 9909 * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set. 9910 * 9911 * Returns the target CPU number. 9912 */ 9913 static int 9914 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags) 9915 { 9916 int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING); 9917 struct sched_domain *tmp, *sd = NULL; 9918 int cpu = smp_processor_id(); 9919 int new_cpu = prev_cpu; 9920 int want_affine = 0; 9921 /* SD_flags and WF_flags share the first nibble */ 9922 int sd_flag = wake_flags & 0xF; 9923 9924 /* 9925 * required for stable ->cpus_allowed 9926 */ 9927 lockdep_assert_held(&p->pi_lock); 9928 if (wake_flags & WF_TTWU) { 9929 record_wakee(p); 9930 9931 if ((wake_flags & WF_CURRENT_CPU) && 9932 cpumask_test_cpu(cpu, p->cpus_ptr)) 9933 return cpu; 9934 9935 if (!is_rd_overutilized(this_rq()->rd)) { 9936 new_cpu = find_energy_efficient_cpu(p, prev_cpu); 9937 if (new_cpu >= 0) 9938 return new_cpu; 9939 new_cpu = prev_cpu; 9940 } 9941 9942 want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr); 9943 } 9944 9945 for_each_domain(cpu, tmp) { 9946 /* 9947 * If both 'cpu' and 'prev_cpu' are part of this domain, 9948 * cpu is a valid SD_WAKE_AFFINE target. 9949 */ 9950 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) && 9951 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) { 9952 if (cpu != prev_cpu) 9953 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync); 9954 9955 sd = NULL; /* Prefer wake_affine over balance flags */ 9956 break; 9957 } 9958 9959 /* 9960 * Usually only true for WF_EXEC and WF_FORK, as sched_domains 9961 * usually do not have SD_BALANCE_WAKE set. That means wakeup 9962 * will usually go to the fast path. 9963 */ 9964 if (tmp->flags & sd_flag) 9965 sd = tmp; 9966 else if (!want_affine) 9967 break; 9968 } 9969 9970 /* Slow path */ 9971 if (unlikely(sd)) { 9972 new_cpu = sched_balance_find_dst_cpu(sd, p, cpu, prev_cpu, sd_flag); 9973 return select_idle_smt_cpu(p, new_cpu); 9974 } 9975 9976 /* Fast path */ 9977 if (wake_flags & WF_TTWU) 9978 return select_idle_sibling(p, prev_cpu, new_cpu); 9979 9980 return new_cpu; 9981 } 9982 9983 /* 9984 * Called immediately before a task is migrated to a new CPU; task_cpu(p) and 9985 * cfs_rq_of(p) references at time of call are still valid and identify the 9986 * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held. 9987 */ 9988 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu) 9989 { 9990 struct sched_entity *se = &p->se; 9991 9992 if (!task_on_rq_migrating(p)) { 9993 remove_entity_load_avg(se); 9994 9995 /* 9996 * Here, the task's PELT values have been updated according to 9997 * the current rq's clock. But if that clock hasn't been 9998 * updated in a while, a substantial idle time will be missed, 9999 * leading to an inflation after wake-up on the new rq. 10000 * 10001 * Estimate the missing time from the cfs_rq last_update_time 10002 * and update sched_avg to improve the PELT continuity after 10003 * migration. 10004 */ 10005 migrate_se_pelt_lag(se); 10006 } 10007 10008 /* Tell new CPU we are migrated */ 10009 se->avg.last_update_time = 0; 10010 10011 update_scan_period(p, new_cpu); 10012 } 10013 10014 static void task_dead_fair(struct task_struct *p) 10015 { 10016 struct sched_entity *se = &p->se; 10017 remove_entity_load_avg(se); 10018 } 10019 10020 /* 10021 * Set the max capacity the task is allowed to run at for misfit detection. 10022 */ 10023 static void set_task_max_allowed_capacity(struct task_struct *p) 10024 { 10025 struct asym_cap_data *entry; 10026 10027 if (!sched_asym_cpucap_active()) 10028 return; 10029 10030 rcu_read_lock(); 10031 list_for_each_entry_rcu(entry, &asym_cap_list, link) { 10032 cpumask_t *cpumask; 10033 10034 cpumask = cpu_capacity_span(entry); 10035 if (!cpumask_intersects(p->cpus_ptr, cpumask)) 10036 continue; 10037 10038 p->max_allowed_capacity = entry->capacity; 10039 break; 10040 } 10041 rcu_read_unlock(); 10042 } 10043 10044 static void set_cpus_allowed_fair(struct task_struct *p, struct affinity_context *ctx) 10045 { 10046 set_cpus_allowed_common(p, ctx); 10047 set_task_max_allowed_capacity(p); 10048 } 10049 10050 enum preempt_wakeup_action { 10051 PREEMPT_WAKEUP_NONE, /* No preemption. */ 10052 PREEMPT_WAKEUP_SHORT, /* Ignore slice protection. */ 10053 PREEMPT_WAKEUP_PICK, /* Let pick_eevdf() decide. */ 10054 PREEMPT_WAKEUP_RESCHED, /* Force reschedule. */ 10055 }; 10056 10057 static inline bool set_preempt_buddy(struct cfs_rq *cfs_rq, struct sched_entity *pse) 10058 { 10059 /* 10060 * Keep existing buddy if the deadline is sooner than pse. 10061 * The older buddy may be cache cold and completely unrelated 10062 * to the current wakeup but that is unpredictable where as 10063 * obeying the deadline is more in line with EEVDF objectives. 10064 */ 10065 if (cfs_rq->next && entity_before(cfs_rq->next, pse)) 10066 return false; 10067 10068 set_next_buddy(cfs_rq, pse); 10069 return true; 10070 } 10071 10072 static inline bool set_short_buddy(struct cfs_rq *cfs_rq, struct sched_entity *pse) 10073 { 10074 if (cfs_rq->next) { 10075 if (cfs_rq->next->slice < pse->slice) 10076 return false; 10077 10078 if (cfs_rq->next->slice == pse->slice && 10079 entity_before(cfs_rq->next, pse)) 10080 return false; 10081 } 10082 10083 set_next_buddy(cfs_rq, pse); 10084 return true; 10085 } 10086 10087 /* 10088 * WF_SYNC|WF_TTWU indicates the waker expects to sleep but it is not 10089 * strictly enforced because the hint is either misunderstood or 10090 * multiple tasks must be woken up. 10091 */ 10092 static inline enum preempt_wakeup_action 10093 preempt_sync(struct rq *rq, int wake_flags, 10094 struct sched_entity *pse, struct sched_entity *se) 10095 { 10096 u64 threshold, delta; 10097 10098 /* 10099 * WF_SYNC without WF_TTWU is not expected so warn if it happens even 10100 * though it is likely harmless. 10101 */ 10102 WARN_ON_ONCE(!(wake_flags & WF_TTWU)); 10103 10104 threshold = sysctl_sched_migration_cost; 10105 delta = rq_clock_task(rq) - se->exec_start; 10106 if ((s64)delta < 0) 10107 delta = 0; 10108 10109 /* 10110 * WF_RQ_SELECTED implies the tasks are stacking on a CPU when they 10111 * could run on other CPUs. Reduce the threshold before preemption is 10112 * allowed to an arbitrary lower value as it is more likely (but not 10113 * guaranteed) the waker requires the wakee to finish. 10114 */ 10115 if (wake_flags & WF_RQ_SELECTED) 10116 threshold >>= 2; 10117 10118 /* 10119 * As WF_SYNC is not strictly obeyed, allow some runtime for batch 10120 * wakeups to be issued. 10121 */ 10122 if (entity_before(pse, se) && delta >= threshold) 10123 return PREEMPT_WAKEUP_RESCHED; 10124 10125 return PREEMPT_WAKEUP_NONE; 10126 } 10127 10128 /* 10129 * Preempt the current task with a newly woken task if needed: 10130 */ 10131 static void wakeup_preempt_fair(struct rq *rq, struct task_struct *p, int wake_flags) 10132 { 10133 enum preempt_wakeup_action preempt_action = PREEMPT_WAKEUP_PICK; 10134 struct task_struct *donor = rq->donor; 10135 struct sched_entity *nse, *se = &donor->se, *pse = &p->se; 10136 struct cfs_rq *cfs_rq = &rq->cfs; 10137 int cse_is_idle, pse_is_idle; 10138 10139 /* 10140 * XXX Getting preempted by higher class, try and find idle CPU? 10141 */ 10142 if (p->sched_class != &fair_sched_class || 10143 donor->sched_class != &fair_sched_class) 10144 return; 10145 10146 if (unlikely(se == pse)) 10147 return; 10148 10149 /* 10150 * This is possible from callers such as attach_tasks(), in which we 10151 * unconditionally wakeup_preempt() after an enqueue (which may have 10152 * lead to a throttle). This both saves work and prevents false 10153 * next-buddy nomination below. 10154 */ 10155 if (task_is_throttled(p)) 10156 return; 10157 10158 /* 10159 * We can come here with TIF_NEED_RESCHED already set from new task 10160 * wake up path. 10161 * 10162 * Note: this also catches the edge-case of curr being in a throttled 10163 * group (e.g. via set_curr_task), since update_curr() (in the 10164 * enqueue of curr) will have resulted in resched being set. This 10165 * prevents us from potentially nominating it as a false LAST_BUDDY 10166 * below. 10167 */ 10168 if (!sched_feat(PREEMPT_SHORT) && test_tsk_need_resched(rq->curr)) 10169 return; 10170 10171 if (!sched_feat(WAKEUP_PREEMPTION)) 10172 return; 10173 10174 WARN_ON_ONCE(!pse); 10175 10176 cse_is_idle = se_is_idle(se); 10177 pse_is_idle = se_is_idle(pse); 10178 10179 nse = se; 10180 /* 10181 * Preempt an idle entity in favor of a non-idle entity (and don't preempt 10182 * in the inverse case). 10183 */ 10184 if (cse_is_idle && !pse_is_idle) 10185 goto preempt; 10186 10187 update_curr_fair(rq); 10188 10189 if (cse_is_idle != pse_is_idle) 10190 goto update; 10191 10192 /* 10193 * BATCH and IDLE tasks do not preempt others. 10194 */ 10195 if (unlikely(!normal_policy(p->policy))) 10196 goto update; 10197 10198 /* 10199 * Do not preempt for tasks that are sched_delayed as it would violate 10200 * EEVDF to forcibly queue an ineligible task. 10201 */ 10202 if (pse->sched_delayed) 10203 goto update; 10204 10205 /* 10206 * If @p has a shorter slice than current and @p is eligible, override 10207 * current's slice protection in order to allow preemption. 10208 */ 10209 if (sched_feat(PREEMPT_SHORT) && (pse->slice < se->slice)) { 10210 preempt_action = PREEMPT_WAKEUP_SHORT; 10211 goto pick; 10212 } 10213 10214 /* 10215 * Ignore wakee preemption on WF_FORK as it is less likely that 10216 * there is shared data as exec often follow fork. 10217 */ 10218 if (wake_flags & WF_FORK) 10219 goto update; 10220 10221 /* Prefer picking wakee soon if appropriate. */ 10222 if (sched_feat(NEXT_BUDDY) && set_preempt_buddy(cfs_rq, pse)) { 10223 /* 10224 * Decide whether to obey WF_SYNC hint for a new buddy. Old 10225 * buddies are ignored as they may not be relevant to the 10226 * waker and less likely to be cache hot. 10227 */ 10228 if (wake_flags & WF_SYNC) 10229 preempt_action = preempt_sync(rq, wake_flags, pse, se); 10230 } 10231 10232 switch (preempt_action) { 10233 case PREEMPT_WAKEUP_NONE: 10234 return; 10235 case PREEMPT_WAKEUP_RESCHED: 10236 goto preempt; 10237 case PREEMPT_WAKEUP_SHORT: 10238 fallthrough; 10239 case PREEMPT_WAKEUP_PICK: 10240 break; 10241 } 10242 10243 pick: 10244 if (cfs_rq->h_nr_queued) { 10245 nse = pick_next_entity(rq, preempt_action != PREEMPT_WAKEUP_SHORT); 10246 if (unlikely(!nse)) 10247 goto pick; 10248 10249 /* If @p has become the most eligible task, force preemption */ 10250 if (nse == pse) 10251 goto preempt; 10252 } 10253 10254 /* 10255 * If @p is eligible but not the next task to run then cancel protection 10256 * to prevent large scheduling latency 10257 */ 10258 if (preempt_action == PREEMPT_WAKEUP_SHORT && entity_eligible(cfs_rq, pse)) 10259 goto preempt; 10260 update: 10261 if (sched_feat(RUN_TO_PARITY)) 10262 update_protect_slice(cfs_rq, se); 10263 10264 return; 10265 10266 preempt: 10267 cancel_protect_slice(se); 10268 10269 if (preempt_action == PREEMPT_WAKEUP_SHORT) 10270 set_short_buddy(cfs_rq, pse); 10271 10272 resched_curr_lazy(rq); 10273 } 10274 10275 struct task_struct *pick_task_fair(struct rq *rq, struct rq_flags *rf) 10276 __must_hold(__rq_lockp(rq)) 10277 { 10278 struct cfs_rq *cfs_rq = &rq->cfs; 10279 struct sched_entity *se; 10280 struct task_struct *p; 10281 int new_tasks; 10282 10283 again: 10284 if (!cfs_rq->h_nr_queued) 10285 goto idle; 10286 10287 /* Might not have done put_prev_entity() */ 10288 if (cfs_rq->curr && cfs_rq->curr->on_rq) 10289 update_curr_eevdf(cfs_rq); 10290 10291 se = pick_next_entity(rq, true); 10292 if (!se) 10293 goto again; 10294 10295 p = task_of(se); 10296 return p; 10297 10298 idle: 10299 if (sched_core_enabled(rq)) 10300 return NULL; 10301 10302 new_tasks = sched_balance_newidle(rq, rf); 10303 if (new_tasks < 0) 10304 return RETRY_TASK; 10305 if (new_tasks > 0) 10306 goto again; 10307 return NULL; 10308 } 10309 10310 static struct task_struct * 10311 fair_server_pick_task(struct sched_dl_entity *dl_se, struct rq_flags *rf) 10312 __must_hold(__rq_lockp(dl_se->rq)) 10313 { 10314 return pick_task_fair(dl_se->rq, rf); 10315 } 10316 10317 void fair_server_init(struct rq *rq) 10318 { 10319 struct sched_dl_entity *dl_se = &rq->fair_server; 10320 10321 init_dl_entity(dl_se); 10322 10323 dl_server_init(dl_se, rq, fair_server_pick_task); 10324 } 10325 10326 /* 10327 * Account for a descheduled task: 10328 */ 10329 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev, struct task_struct *next) 10330 { 10331 struct sched_entity *se = &prev->se; 10332 struct cfs_rq *cfs_rq = &rq->cfs; 10333 struct sched_entity *nse = NULL; 10334 10335 #ifdef CONFIG_FAIR_GROUP_SCHED 10336 if (next && next->sched_class == &fair_sched_class) 10337 nse = &next->se; 10338 #endif 10339 10340 while (se) { 10341 cfs_rq = cfs_rq_of(se); 10342 if (!nse || cfs_rq->h_curr) 10343 put_prev_entity(cfs_rq, se); 10344 #ifdef CONFIG_FAIR_GROUP_SCHED 10345 if (nse) { 10346 if (is_same_group(se, nse)) 10347 break; 10348 10349 int d = nse->depth - se->depth; 10350 if (d >= 0) { 10351 /* nse has equal or greater depth, ascend */ 10352 nse = parent_entity(nse); 10353 /* if nse is the deeper, do not ascend se */ 10354 if (d > 0) 10355 continue; 10356 } 10357 } 10358 #endif 10359 se = parent_entity(se); 10360 } 10361 10362 /* Put 'current' back into the tree. */ 10363 cfs_rq = &rq->cfs; 10364 se = &prev->se; 10365 WARN_ON_ONCE(cfs_rq->curr != se); 10366 cfs_rq->curr = NULL; 10367 if (se->on_rq) 10368 __enqueue_entity(cfs_rq, se); 10369 } 10370 10371 /* 10372 * sched_yield() is very simple 10373 */ 10374 static void yield_task_fair(struct rq *rq) 10375 { 10376 struct task_struct *curr = rq->donor; 10377 struct sched_entity *se = &curr->se; 10378 struct cfs_rq *cfs_rq = &rq->cfs; 10379 10380 /* 10381 * Are we the only task in the tree? 10382 */ 10383 if (unlikely(rq->nr_running == 1)) 10384 return; 10385 10386 clear_buddies(cfs_rq, se); 10387 10388 update_rq_clock(rq); 10389 /* 10390 * Update run-time statistics of the 'current'. 10391 */ 10392 update_curr_eevdf(cfs_rq); 10393 /* 10394 * Tell update_rq_clock() that we've just updated, 10395 * so we don't do microscopic update in schedule() 10396 * and double the fastpath cost. 10397 */ 10398 rq_clock_skip_update(rq); 10399 10400 /* 10401 * Forfeit the remaining vruntime, only if the entity is eligible. This 10402 * condition is necessary because in core scheduling we prefer to run 10403 * ineligible tasks rather than force idling. If this happens we may 10404 * end up in a loop where the core scheduler picks the yielding task, 10405 * which yields immediately again; without the condition the vruntime 10406 * ends up quickly running away. 10407 */ 10408 if (entity_eligible(cfs_rq, se)) { 10409 se->vruntime = se->deadline; 10410 update_deadline(cfs_rq, se); 10411 } 10412 } 10413 10414 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p) 10415 { 10416 struct sched_entity *se = &p->se; 10417 10418 /* !se->on_rq also covers throttled task */ 10419 if (!se->on_rq || se->sched_delayed) 10420 return false; 10421 10422 /* Tell the scheduler that we'd really like se to run next. */ 10423 set_next_buddy(&task_rq(p)->cfs, se); 10424 10425 yield_task_fair(rq); 10426 10427 return true; 10428 } 10429 10430 /************************************************** 10431 * Fair scheduling class load-balancing methods. 10432 * 10433 * BASICS 10434 * 10435 * The purpose of load-balancing is to achieve the same basic fairness the 10436 * per-CPU scheduler provides, namely provide a proportional amount of compute 10437 * time to each task. This is expressed in the following equation: 10438 * 10439 * W_i,n/P_i == W_j,n/P_j for all i,j (1) 10440 * 10441 * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight 10442 * W_i,0 is defined as: 10443 * 10444 * W_i,0 = \Sum_j w_i,j (2) 10445 * 10446 * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight 10447 * is derived from the nice value as per sched_prio_to_weight[]. 10448 * 10449 * The weight average is an exponential decay average of the instantaneous 10450 * weight: 10451 * 10452 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3) 10453 * 10454 * C_i is the compute capacity of CPU i, typically it is the 10455 * fraction of 'recent' time available for SCHED_OTHER task execution. But it 10456 * can also include other factors [XXX]. 10457 * 10458 * To achieve this balance we define a measure of imbalance which follows 10459 * directly from (1): 10460 * 10461 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4) 10462 * 10463 * We them move tasks around to minimize the imbalance. In the continuous 10464 * function space it is obvious this converges, in the discrete case we get 10465 * a few fun cases generally called infeasible weight scenarios. 10466 * 10467 * [XXX expand on: 10468 * - infeasible weights; 10469 * - local vs global optima in the discrete case. ] 10470 * 10471 * 10472 * SCHED DOMAINS 10473 * 10474 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2) 10475 * for all i,j solution, we create a tree of CPUs that follows the hardware 10476 * topology where each level pairs two lower groups (or better). This results 10477 * in O(log n) layers. Furthermore we reduce the number of CPUs going up the 10478 * tree to only the first of the previous level and we decrease the frequency 10479 * of load-balance at each level inversely proportional to the number of CPUs in 10480 * the groups. 10481 * 10482 * This yields: 10483 * 10484 * log_2 n 1 n 10485 * \Sum { --- * --- * 2^i } = O(n) (5) 10486 * i = 0 2^i 2^i 10487 * `- size of each group 10488 * | | `- number of CPUs doing load-balance 10489 * | `- freq 10490 * `- sum over all levels 10491 * 10492 * Coupled with a limit on how many tasks we can migrate every balance pass, 10493 * this makes (5) the runtime complexity of the balancer. 10494 * 10495 * An important property here is that each CPU is still (indirectly) connected 10496 * to every other CPU in at most O(log n) steps: 10497 * 10498 * The adjacency matrix of the resulting graph is given by: 10499 * 10500 * log_2 n 10501 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6) 10502 * k = 0 10503 * 10504 * And you'll find that: 10505 * 10506 * A^(log_2 n)_i,j != 0 for all i,j (7) 10507 * 10508 * Showing there's indeed a path between every CPU in at most O(log n) steps. 10509 * The task movement gives a factor of O(m), giving a convergence complexity 10510 * of: 10511 * 10512 * O(nm log n), n := nr_cpus, m := nr_tasks (8) 10513 * 10514 * 10515 * WORK CONSERVING 10516 * 10517 * In order to avoid CPUs going idle while there's still work to do, new idle 10518 * balancing is more aggressive and has the newly idle CPU iterate up the domain 10519 * tree itself instead of relying on other CPUs to bring it work. 10520 * 10521 * This adds some complexity to both (5) and (8) but it reduces the total idle 10522 * time. 10523 * 10524 * [XXX more?] 10525 * 10526 * 10527 * CGROUPS 10528 * 10529 * Cgroups make a horror show out of (2), instead of a simple sum we get: 10530 * 10531 * s_k,i 10532 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9) 10533 * S_k 10534 * 10535 * Where 10536 * 10537 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10) 10538 * 10539 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i. 10540 * 10541 * The big problem is S_k, its a global sum needed to compute a local (W_i) 10542 * property. 10543 * 10544 * [XXX write more on how we solve this.. _after_ merging pjt's patches that 10545 * rewrite all of this once again.] 10546 */ 10547 10548 static unsigned long __read_mostly max_load_balance_interval = HZ/10; 10549 10550 enum fbq_type { regular, remote, all }; 10551 10552 /* 10553 * 'group_type' describes the group of CPUs at the moment of load balancing. 10554 * 10555 * The enum is ordered by pulling priority, with the group with lowest priority 10556 * first so the group_type can simply be compared when selecting the busiest 10557 * group. See update_sd_pick_busiest(). 10558 */ 10559 enum group_type { 10560 /* The group has spare capacity that can be used to run more tasks. */ 10561 group_has_spare = 0, 10562 /* 10563 * The group is fully used and the tasks don't compete for more CPU 10564 * cycles. Nevertheless, some tasks might wait before running. 10565 */ 10566 group_fully_busy, 10567 /* 10568 * One task doesn't fit with CPU's capacity and must be migrated to a 10569 * more powerful CPU. 10570 */ 10571 group_misfit_task, 10572 /* 10573 * Balance SMT group that's fully busy. Can benefit from migration 10574 * a task on SMT with busy sibling to another CPU on idle core. 10575 */ 10576 group_smt_balance, 10577 /* 10578 * SD_ASYM_PACKING only: One local CPU with higher capacity is available, 10579 * and the task should be migrated to it instead of running on the 10580 * current CPU. 10581 */ 10582 group_asym_packing, 10583 /* 10584 * The tasks' affinity constraints previously prevented the scheduler 10585 * from balancing the load across the system. 10586 */ 10587 group_imbalanced, 10588 /* 10589 * There are tasks running on non-preferred LLC, possible to move 10590 * them to their preferred LLC without creating too much imbalance. 10591 * The priority of group_llc_balance is lower than that of 10592 * group_overloaded and higher than that of all other group types. 10593 * This is because group_llc_balance may exacerbate load imbalance. 10594 * If the LLC balancing attempt fails, the nr_balance_failed 10595 * mechanism will trigger other group types to rebalance the load. 10596 */ 10597 group_llc_balance, 10598 /* 10599 * The CPU is overloaded and can't provide expected CPU cycles to all 10600 * tasks. 10601 */ 10602 group_overloaded 10603 }; 10604 10605 enum migration_type { 10606 migrate_load = 0, 10607 migrate_util, 10608 migrate_task, 10609 migrate_misfit, 10610 migrate_llc_task 10611 }; 10612 10613 #define LBF_ALL_PINNED 0x01 10614 #define LBF_NEED_BREAK 0x02 10615 #define LBF_DST_PINNED 0x04 10616 #define LBF_SOME_PINNED 0x08 10617 #define LBF_ACTIVE_LB 0x10 10618 #define LBF_LLC_PINNED 0x20 10619 #define LBF_ACTIVE_LB_LLC 0x40 10620 10621 struct lb_env { 10622 struct sched_domain *sd; 10623 10624 struct rq *src_rq; 10625 int src_cpu; 10626 10627 int dst_cpu; 10628 struct rq *dst_rq; 10629 bool dst_core_idle; 10630 10631 struct cpumask *dst_grpmask; 10632 int new_dst_cpu; 10633 enum cpu_idle_type idle; 10634 long imbalance; 10635 /* The set of CPUs under consideration for load-balancing */ 10636 struct cpumask *cpus; 10637 10638 unsigned int flags; 10639 10640 unsigned int loop; 10641 unsigned int loop_break; 10642 unsigned int loop_max; 10643 10644 enum fbq_type fbq_type; 10645 enum migration_type migration_type; 10646 struct list_head tasks; 10647 }; 10648 10649 /* 10650 * Is this task likely cache-hot: 10651 */ 10652 static int task_hot(struct task_struct *p, struct lb_env *env) 10653 { 10654 s64 delta; 10655 10656 lockdep_assert_rq_held(env->src_rq); 10657 10658 if (p->sched_class != &fair_sched_class) 10659 return 0; 10660 10661 if (unlikely(task_has_idle_policy(p))) 10662 return 0; 10663 10664 /* SMT siblings share cache */ 10665 if (env->sd->flags & SD_SHARE_CPUCAPACITY) 10666 return 0; 10667 10668 /* 10669 * Buddy candidates are cache hot: 10670 */ 10671 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running && 10672 (&p->se == cfs_rq_of(&p->se)->next)) 10673 return 1; 10674 10675 if (sysctl_sched_migration_cost == -1) 10676 return 1; 10677 10678 /* 10679 * Don't migrate task if the task's cookie does not match 10680 * with the destination CPU's core cookie. 10681 */ 10682 if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p)) 10683 return 1; 10684 10685 if (sysctl_sched_migration_cost == 0) 10686 return 0; 10687 10688 delta = rq_clock_task(env->src_rq) - p->se.exec_start; 10689 10690 return delta < (s64)sysctl_sched_migration_cost; 10691 } 10692 10693 #ifdef CONFIG_NUMA_BALANCING 10694 /* 10695 * Returns a positive value, if task migration degrades locality. 10696 * Returns 0, if task migration is not affected by locality. 10697 * Returns a negative value, if task migration improves locality i.e migration preferred. 10698 */ 10699 static long migrate_degrades_locality(struct task_struct *p, struct lb_env *env) 10700 { 10701 struct numa_group *numa_group = rcu_dereference_all(p->numa_group); 10702 unsigned long src_weight, dst_weight; 10703 int src_nid, dst_nid, dist; 10704 10705 if (!static_branch_likely(&sched_numa_balancing)) 10706 return 0; 10707 10708 if (!p->numa_faults || !(env->sd->flags & SD_NUMA)) 10709 return 0; 10710 10711 src_nid = cpu_to_node(env->src_cpu); 10712 dst_nid = cpu_to_node(env->dst_cpu); 10713 10714 if (src_nid == dst_nid) 10715 return 0; 10716 10717 /* Migrating away from the preferred node is always bad. */ 10718 if (src_nid == p->numa_preferred_nid) { 10719 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running) 10720 return 1; 10721 else 10722 return 0; 10723 } 10724 10725 /* Encourage migration to the preferred node. */ 10726 if (dst_nid == p->numa_preferred_nid) 10727 return -1; 10728 10729 /* Leaving a core idle is often worse than degrading locality. */ 10730 if (env->idle == CPU_IDLE) 10731 return 0; 10732 10733 dist = node_distance(src_nid, dst_nid); 10734 if (numa_group) { 10735 src_weight = group_weight(p, src_nid, dist); 10736 dst_weight = group_weight(p, dst_nid, dist); 10737 } else { 10738 src_weight = task_weight(p, src_nid, dist); 10739 dst_weight = task_weight(p, dst_nid, dist); 10740 } 10741 10742 return src_weight - dst_weight; 10743 } 10744 10745 #else /* !CONFIG_NUMA_BALANCING: */ 10746 static inline long migrate_degrades_locality(struct task_struct *p, 10747 struct lb_env *env) 10748 { 10749 return 0; 10750 } 10751 #endif /* !CONFIG_NUMA_BALANCING */ 10752 10753 /* 10754 * Check whether the task is ineligible on the destination cpu 10755 * 10756 * When the PLACE_LAG scheduling feature is enabled and 10757 * dst_cfs_rq->nr_queued is greater than 1, if the task 10758 * is ineligible, it will also be ineligible when 10759 * it is migrated to the destination cpu. 10760 */ 10761 static inline int task_is_ineligible_on_dst_cpu(struct task_struct *p, int dest_cpu) 10762 { 10763 struct cfs_rq *dst_cfs_rq = &cpu_rq(dest_cpu)->cfs; 10764 10765 if (sched_feat(PLACE_LAG) && dst_cfs_rq->h_nr_queued && 10766 !entity_eligible(&task_rq(p)->cfs, &p->se)) 10767 return 1; 10768 10769 return 0; 10770 } 10771 10772 #ifdef CONFIG_SCHED_CACHE 10773 /* 10774 * The margin used when comparing LLC utilization with CPU capacity. 10775 * It determines the LLC load level where active LLC aggregation is 10776 * done. 10777 * Derived from fits_capacity(). 10778 * 10779 * (default: ~50%, tunable via debugfs) 10780 */ 10781 static bool fits_llc_capacity(unsigned long util, unsigned long max) 10782 { 10783 u32 aggr_pct = llc_overaggr_pct; 10784 10785 /* 10786 * For single core systems, raise the aggregation 10787 * threshold to accommodate more tasks. 10788 */ 10789 if (cpu_smt_num_threads == 1) 10790 aggr_pct = (aggr_pct * 3 / 2); 10791 10792 return util * 100 < max * aggr_pct; 10793 } 10794 10795 /* 10796 * The margin used when comparing utilization. 10797 * is 'util1' noticeably greater than 'util2' 10798 * Derived from capacity_greater(). 10799 * Bias is in perentage. 10800 */ 10801 /* Allows dst util to be bigger than src util by up to bias percent */ 10802 #define util_greater(util1, util2) \ 10803 ((util1) * 100 > (util2) * (100 + llc_imb_pct)) 10804 10805 static __maybe_unused bool get_llc_stats(int cpu, unsigned long *util, 10806 unsigned long *cap) 10807 { 10808 struct sched_domain_shared *sd_share; 10809 10810 sd_share = rcu_dereference_all(per_cpu(sd_llc_shared, cpu)); 10811 if (!sd_share) 10812 return false; 10813 10814 *util = READ_ONCE(sd_share->util_avg); 10815 *cap = READ_ONCE(sd_share->capacity); 10816 10817 return true; 10818 } 10819 10820 /* 10821 * Decision matrix according to the LLC utilization. To 10822 * decide whether we can do task aggregation across LLC. 10823 * 10824 * By default, 50% is the threshold for treating the LLC 10825 * as busy. The reason for choosing 50% is to avoid saturation 10826 * of SMT-2, and it is also a safe cutoff for other SMT-n 10827 * platforms. SMT-1 has higher threshold because it is 10828 * supposed to accommodate more tasks, see fits_llc_capacity(). 10829 * 10830 * 20% is the utilization imbalance percentage to decide 10831 * if the preferred LLC is busier than the non-preferred LLC. 10832 * 20 is a little higher than the LLC domain's imbalance_pct 10833 * 17. The hysteresis is used to avoid task bouncing between the 10834 * preferred LLC and the non-preferred LLC, and it will 10835 * be turned into tunable debugfs. 10836 * 10837 * 1. moving towards the preferred LLC, dst is the preferred 10838 * LLC, src is not. 10839 * 10840 * src \ dst 30% 40% 50% 60% 10841 * 30% Y Y Y N 10842 * 40% Y Y Y Y 10843 * 50% Y Y G G 10844 * 60% Y Y G G 10845 * 10846 * 2. moving out of the preferred LLC, src is the preferred 10847 * LLC, dst is not: 10848 * 10849 * src \ dst 30% 40% 50% 60% 10850 * 30% N N N N 10851 * 40% N N N N 10852 * 50% N N G G 10853 * 60% Y N G G 10854 * 10855 * src : src_util 10856 * dst : dst_util 10857 * Y : Yes, migrate 10858 * N : No, do not migrate 10859 * G : let the Generic load balance to even the load. 10860 * 10861 * The intention is that if both LLCs are quite busy, cache aware 10862 * load balance should not be performed, and generic load balance 10863 * should take effect. However, if one is busy and the other is not, 10864 * the preferred LLC capacity(50%) and imbalance criteria(20%) should 10865 * be considered to determine whether LLC aggregation should be 10866 * performed to bias the load towards the preferred LLC. 10867 */ 10868 10869 /* migration decision, 3 states are orthogonal. */ 10870 enum llc_mig { 10871 mig_forbid = 0, /* N: Don't migrate task, respect LLC preference */ 10872 mig_llc, /* Y: Do LLC preference based migration */ 10873 mig_unrestricted /* G: Don't restrict generic load balance migration */ 10874 }; 10875 10876 /* 10877 * Check if task can be moved from the source LLC to the 10878 * destination LLC without breaking cache aware preferrence. 10879 * src_cpu and dst_cpu are arbitrary CPUs within the source 10880 * and destination LLCs, respectively. 10881 */ 10882 static enum llc_mig can_migrate_llc(int src_cpu, int dst_cpu, 10883 unsigned long tsk_util, 10884 bool to_pref) 10885 { 10886 unsigned long src_util, dst_util, src_cap, dst_cap; 10887 10888 if (!get_llc_stats(src_cpu, &src_util, &src_cap) || 10889 !get_llc_stats(dst_cpu, &dst_util, &dst_cap)) 10890 return mig_unrestricted; 10891 10892 src_util = src_util < tsk_util ? 0 : src_util - tsk_util; 10893 dst_util = dst_util + tsk_util; 10894 10895 if (!fits_llc_capacity(dst_util, dst_cap) && 10896 !fits_llc_capacity(src_util, src_cap)) 10897 return mig_unrestricted; 10898 10899 if (to_pref) { 10900 /* 10901 * Don't migrate if we will get preferred LLC too 10902 * heavily loaded and if the dest is much busier 10903 * than the src, in which case migration will 10904 * increase the imbalance too much. 10905 */ 10906 if (!fits_llc_capacity(dst_util, dst_cap) && 10907 util_greater(dst_util, src_util)) 10908 return mig_forbid; 10909 } else { 10910 /* 10911 * Don't migrate if we will leave preferred LLC 10912 * too idle, or if this migration leads to the 10913 * non-preferred LLC falls within sysctl_aggr_imb percent 10914 * of preferred LLC, leading to migration again 10915 * back to preferred LLC. 10916 */ 10917 if (fits_llc_capacity(src_util, src_cap) || 10918 !util_greater(src_util, dst_util)) 10919 return mig_forbid; 10920 } 10921 return mig_llc; 10922 } 10923 10924 static inline bool task_misfits_asym_cpu(struct lb_env *env, struct task_struct *p) 10925 { 10926 /* 10927 * On asymmetric CPU capacity domains, do not let cache-aware 10928 * balancing pull the task onto a destination CPU that cannot 10929 * accommodate it. Doing so would turn the task into a misfit on 10930 * the destination, trading a cache-locality gain for a capacity 10931 * loss. If the task already does not fit its source CPU, the move 10932 * cannot make things worse, so let the LLC preference decide. 10933 */ 10934 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) && p && 10935 !task_fits_cpu(p, env->dst_cpu) && 10936 task_fits_cpu(p, env->src_cpu)) 10937 return true; 10938 10939 return false; 10940 } 10941 10942 static inline bool sched_asym(struct sched_domain *sd, int dst_cpu, int src_cpu); 10943 10944 /* 10945 * Check if task p can migrate from source LLC to 10946 * destination LLC in terms of cache aware load balance. 10947 */ 10948 static enum llc_mig can_migrate_llc_task(struct lb_env *env, 10949 struct task_struct *p) 10950 { 10951 struct sched_cache_group *grp; 10952 bool to_pref; 10953 int cpu, src_cpu, dst_cpu; 10954 10955 if (task_misfits_asym_cpu(env, p)) 10956 return mig_forbid; 10957 10958 src_cpu = env->src_cpu; 10959 dst_cpu = env->dst_cpu; 10960 grp = rcu_dereference_all(p->sched_cache_grp); 10961 if (!grp) 10962 return mig_unrestricted; 10963 10964 cpu = READ_ONCE(grp->cpu); 10965 if (cpu < 0 || cpus_share_cache(src_cpu, dst_cpu)) 10966 return mig_unrestricted; 10967 10968 /* Prioritize asym packing to idle core over cache awareness */ 10969 if (env->idle && sched_asym(env->sd, dst_cpu, src_cpu)) 10970 return mig_unrestricted; 10971 10972 /* skip cache aware load balance for too many threads */ 10973 if (invalid_llc_nr(grp, p, dst_cpu) || 10974 exceed_llc_capacity(grp, dst_cpu)) { 10975 if (READ_ONCE(grp->cpu) != -1) 10976 WRITE_ONCE(grp->cpu, -1); 10977 return mig_unrestricted; 10978 } 10979 10980 if (cpus_share_cache(dst_cpu, cpu)) 10981 to_pref = true; 10982 else if (cpus_share_cache(src_cpu, cpu)) 10983 to_pref = false; 10984 else 10985 return mig_unrestricted; 10986 10987 return can_migrate_llc(src_cpu, dst_cpu, 10988 task_util(p), to_pref); 10989 } 10990 10991 /* 10992 * Check if active load balance breaks LLC locality in 10993 * terms of cache aware load balance. The load level and 10994 * imbalance do not warrant breaking LLC preference per 10995 * the can_migrate_llc() policy. Here, the benefit of 10996 * LLC locality outweighs the power efficiency gained from 10997 * migrating the only runnable task away. 10998 */ 10999 static inline bool 11000 alb_break_llc(struct lb_env *env) 11001 { 11002 if (!sched_cache_enabled()) 11003 return false; 11004 11005 if (cpus_share_cache(env->src_cpu, env->dst_cpu)) 11006 return false; 11007 /* 11008 * All tasks prefer to stay on their current CPU. 11009 * Do not pull a task from its preferred CPU if: 11010 * 1. It is the only task running and does not exceed 11011 * imbalance allowance; OR 11012 * 2. Migrating it away from its preferred LLC would violate 11013 * the cache-aware scheduling policy. 11014 */ 11015 if (env->src_rq->nr_pref_llc_running && 11016 env->src_rq->nr_pref_llc_running == env->src_rq->cfs.h_nr_runnable) { 11017 unsigned long util = 0; 11018 struct task_struct *cur; 11019 11020 /* 11021 * Migrating misfit tasks from current CPU 11022 * to CPU with a better fit. 11023 * Prioritize that over LLC preference. 11024 */ 11025 if (env->migration_type == migrate_misfit) 11026 return false; 11027 11028 if (env->src_rq->nr_running <= 1) 11029 return true; 11030 11031 cur = rcu_dereference_all(env->src_rq->curr); 11032 /* 11033 * Active balance only detaches CFS tasks, so a non-fair 11034 * curr is never migrated. Ignore it and avoid using its 11035 * state util in the misfit and LLC checks. 11036 */ 11037 if (cur && cur->sched_class != &fair_sched_class) 11038 cur = NULL; 11039 if (cur) 11040 util = task_util(cur); 11041 11042 if (task_misfits_asym_cpu(env, cur) || 11043 can_migrate_llc(env->src_cpu, env->dst_cpu, 11044 util, false) == mig_forbid) 11045 return true; 11046 } 11047 11048 return false; 11049 } 11050 11051 /* 11052 * Returns true if p's preferred LLC does not match the destination CPU 11053 * under migrate_llc_task semantics. Passive LB passes migrate_llc_task 11054 * in env->migration_type, while active LB carries LBF_ACTIVE_LB_LLC in 11055 * env->flags to avoid overwriting env->migration_type. 11056 */ 11057 static inline bool 11058 migrate_llc_task_wrong_dst(struct task_struct *p, struct lb_env *env) 11059 { 11060 return sched_cache_enabled() && 11061 (env->migration_type == migrate_llc_task || 11062 env->flags & LBF_ACTIVE_LB_LLC) && 11063 READ_ONCE(p->preferred_llc) != llc_id(env->dst_cpu); 11064 } 11065 11066 /* 11067 * Check if migrating task p from env->src_cpu to 11068 * env->dst_cpu breaks LLC localiy. 11069 */ 11070 static bool migrate_degrades_llc(struct task_struct *p, struct lb_env *env) 11071 { 11072 if (!sched_cache_enabled()) 11073 return false; 11074 11075 if (task_has_sched_core(p)) 11076 return false; 11077 /* 11078 * Skip over tasks that would degrade LLC locality; 11079 * only when nr_balanced_failed is sufficiently high do we 11080 * ignore this constraint. 11081 * 11082 * Threshold of cache_nice_tries is set to 1 higher 11083 * than nr_balance_failed to avoid excessive task 11084 * migration at the same time. 11085 */ 11086 if (env->sd->nr_balance_failed >= env->sd->cache_nice_tries + 1) 11087 return false; 11088 11089 /* 11090 * We know the env->src_cpu has some tasks prefer to 11091 * run on env->dst_cpu, skip the tasks do not prefer 11092 * env->dst_cpu, and find the one that prefers. 11093 */ 11094 if (migrate_llc_task_wrong_dst(p, env)) 11095 return true; 11096 11097 if (can_migrate_llc_task(env, p) != mig_forbid) 11098 return false; 11099 11100 return true; 11101 } 11102 11103 #else 11104 static inline bool get_llc_stats(int cpu, unsigned long *util, 11105 unsigned long *cap) 11106 { 11107 return false; 11108 } 11109 11110 static inline bool 11111 alb_break_llc(struct lb_env *env) 11112 { 11113 return false; 11114 } 11115 11116 static inline bool 11117 migrate_llc_task_wrong_dst(struct task_struct *p, struct lb_env *env) 11118 { 11119 return false; 11120 } 11121 11122 static inline bool 11123 migrate_degrades_llc(struct task_struct *p, struct lb_env *env) 11124 { 11125 return false; 11126 } 11127 #endif 11128 /* 11129 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu? 11130 */ 11131 static 11132 int can_migrate_task(struct task_struct *p, struct lb_env *env) 11133 { 11134 long degrades, hot; 11135 11136 lockdep_assert_rq_held(env->src_rq); 11137 if (p->sched_task_hot) 11138 p->sched_task_hot = 0; 11139 11140 /* 11141 * We do not migrate tasks that are: 11142 * 1) delayed dequeued unless we migrate load, or 11143 * 2) target cfs_rq is in throttled hierarchy, or 11144 * 3) cannot be migrated to this CPU due to cpus_ptr, or 11145 * 4) running (obviously), or 11146 * 5) are cache-hot on their current CPU, or 11147 * 6) are blocked on mutexes (if SCHED_PROXY_EXEC is enabled) 11148 */ 11149 if ((p->se.sched_delayed) && (env->migration_type != migrate_load)) 11150 return 0; 11151 11152 if (lb_throttled_hierarchy(p, env->dst_cpu)) 11153 return 0; 11154 11155 /* 11156 * We want to prioritize the migration of eligible tasks. 11157 * For ineligible tasks we soft-limit them and only allow 11158 * them to migrate when nr_balance_failed is non-zero to 11159 * avoid load-balancing trying very hard to balance the load. 11160 */ 11161 if (!env->sd->nr_balance_failed && 11162 task_is_ineligible_on_dst_cpu(p, env->dst_cpu)) 11163 return 0; 11164 11165 /* Disregard percpu kthreads; they are where they need to be. */ 11166 if (kthread_is_per_cpu(p)) 11167 return 0; 11168 11169 if (task_is_blocked(p)) 11170 return 0; 11171 11172 if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) { 11173 int cpu; 11174 11175 schedstat_inc(p->stats.nr_failed_migrations_affine); 11176 11177 env->flags |= LBF_SOME_PINNED; 11178 11179 /* 11180 * Remember if this task can be migrated to any other CPU in 11181 * our sched_group. We may want to revisit it if we couldn't 11182 * meet load balance goals by pulling other tasks on src_cpu. 11183 * 11184 * Avoid computing new_dst_cpu 11185 * - for NEWLY_IDLE 11186 * - if we have already computed one in current iteration 11187 * - if it's an active balance 11188 */ 11189 if (env->idle == CPU_NEWLY_IDLE || 11190 env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB)) 11191 return 0; 11192 11193 /* Prevent to re-select dst_cpu via env's CPUs: */ 11194 cpu = cpumask_first_and_and(env->dst_grpmask, env->cpus, p->cpus_ptr); 11195 11196 if (cpu < nr_cpu_ids) { 11197 env->flags |= LBF_DST_PINNED; 11198 env->new_dst_cpu = cpu; 11199 } 11200 11201 return 0; 11202 } 11203 11204 /* Record that we found at least one task that could run on dst_cpu */ 11205 env->flags &= ~LBF_ALL_PINNED; 11206 11207 if (task_on_cpu(env->src_rq, p) || 11208 task_current_donor(env->src_rq, p)) { 11209 schedstat_inc(p->stats.nr_failed_migrations_running); 11210 return 0; 11211 } 11212 11213 /* 11214 * Aggressive migration if: 11215 * 1) active balance 11216 * 2) destination numa is preferred 11217 * 3) task is cache cold, or 11218 * 4) too many balance attempts have failed. 11219 */ 11220 if (env->flags & LBF_ACTIVE_LB) 11221 return !migrate_llc_task_wrong_dst(p, env); 11222 11223 degrades = migrate_degrades_locality(p, env); 11224 if (!degrades) { 11225 /* 11226 * If the NUMA locality is not broken, 11227 * further check if migration would hurt 11228 * LLC locality. 11229 */ 11230 if (migrate_degrades_llc(p, env)) { 11231 /* 11232 * If regular load balancing fails to pull a task 11233 * due to LLC locality, this is expected behavior 11234 * and we set LBF_LLC_PINNED so we don't increase 11235 * nr_balance_failed unecessarily. 11236 */ 11237 if (env->migration_type != migrate_llc_task) 11238 env->flags |= LBF_LLC_PINNED; 11239 11240 return 0; 11241 } 11242 11243 hot = task_hot(p, env); 11244 } else { 11245 hot = degrades > 0; 11246 } 11247 11248 if (!hot || env->sd->nr_balance_failed > env->sd->cache_nice_tries) { 11249 if (hot) 11250 p->sched_task_hot = 1; 11251 return 1; 11252 } 11253 11254 schedstat_inc(p->stats.nr_failed_migrations_hot); 11255 return 0; 11256 } 11257 11258 /* 11259 * detach_task() -- detach the task for the migration specified in env 11260 */ 11261 static void detach_task(struct task_struct *p, struct lb_env *env) 11262 { 11263 lockdep_assert_rq_held(env->src_rq); 11264 11265 if (p->sched_task_hot) { 11266 p->sched_task_hot = 0; 11267 schedstat_inc(env->sd->lb_hot_gained[env->idle]); 11268 schedstat_inc(p->stats.nr_forced_migrations); 11269 } 11270 11271 WARN_ON(task_current(env->src_rq, p)); 11272 WARN_ON(task_current_donor(env->src_rq, p)); 11273 11274 deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK); 11275 set_task_cpu(p, env->dst_cpu); 11276 } 11277 11278 /* 11279 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as 11280 * part of active balancing operations within "domain". 11281 * 11282 * Returns a task if successful and NULL otherwise. 11283 */ 11284 static struct task_struct *detach_one_task(struct lb_env *env) 11285 { 11286 struct task_struct *p; 11287 11288 lockdep_assert_rq_held(env->src_rq); 11289 11290 list_for_each_entry_reverse(p, 11291 &env->src_rq->cfs_tasks, se.group_node) { 11292 if (!can_migrate_task(p, env)) 11293 continue; 11294 11295 detach_task(p, env); 11296 11297 /* 11298 * Right now, this is only the second place where 11299 * lb_gained[env->idle] is updated (other is detach_tasks) 11300 * so we can safely collect stats here rather than 11301 * inside detach_tasks(). 11302 */ 11303 schedstat_inc(env->sd->lb_gained[env->idle]); 11304 return p; 11305 } 11306 return NULL; 11307 } 11308 11309 /* 11310 * detach_tasks() -- tries to detach up to imbalance load/util/tasks from 11311 * busiest_rq, as part of a balancing operation within domain "sd". 11312 * 11313 * Returns number of detached tasks if successful and 0 otherwise. 11314 */ 11315 static int detach_tasks(struct lb_env *env) 11316 { 11317 struct list_head *tasks = &env->src_rq->cfs_tasks; 11318 unsigned long util, load; 11319 struct task_struct *p; 11320 int detached = 0; 11321 11322 lockdep_assert_rq_held(env->src_rq); 11323 11324 /* 11325 * Source run queue has been emptied by another CPU, clear 11326 * LBF_ALL_PINNED flag as we will not test any task. 11327 */ 11328 if (env->src_rq->nr_running <= 1) { 11329 env->flags &= ~LBF_ALL_PINNED; 11330 return 0; 11331 } 11332 11333 if (env->imbalance <= 0) 11334 return 0; 11335 11336 while (!list_empty(tasks)) { 11337 /* 11338 * We don't want to steal all, otherwise we may be treated likewise, 11339 * which could at worst lead to a livelock crash. 11340 */ 11341 if (env->idle && env->src_rq->nr_running <= 1) 11342 break; 11343 11344 env->loop++; 11345 /* We've more or less seen every task there is, call it quits */ 11346 if (env->loop > env->loop_max) 11347 break; 11348 11349 /* take a breather every nr_migrate tasks */ 11350 if (env->loop > env->loop_break) { 11351 env->loop_break += SCHED_NR_MIGRATE_BREAK; 11352 env->flags |= LBF_NEED_BREAK; 11353 break; 11354 } 11355 11356 p = list_last_entry(tasks, struct task_struct, se.group_node); 11357 11358 if (!can_migrate_task(p, env)) 11359 goto next; 11360 11361 switch (env->migration_type) { 11362 case migrate_load: 11363 /* 11364 * Depending of the number of CPUs and tasks and the 11365 * cgroup hierarchy, task_h_load() can return a null 11366 * value. Make sure that env->imbalance decreases 11367 * otherwise detach_tasks() will stop only after 11368 * detaching up to loop_max tasks. 11369 */ 11370 load = max_t(unsigned long, task_h_load(p), 1); 11371 11372 if (sched_feat(LB_MIN) && 11373 load < 16 && !env->sd->nr_balance_failed) 11374 goto next; 11375 11376 /* 11377 * Make sure that we don't migrate too much load. 11378 * Nevertheless, let relax the constraint if 11379 * scheduler fails to find a good waiting task to 11380 * migrate. 11381 */ 11382 if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance) 11383 goto next; 11384 11385 env->imbalance -= load; 11386 break; 11387 11388 case migrate_util: 11389 util = task_util_est(p); 11390 11391 if (shr_bound(util, env->sd->nr_balance_failed) > env->imbalance) 11392 goto next; 11393 11394 env->imbalance -= util; 11395 break; 11396 11397 case migrate_task: 11398 env->imbalance--; 11399 break; 11400 11401 case migrate_misfit: 11402 /* This is not a misfit task */ 11403 if (task_fits_cpu(p, env->src_cpu)) 11404 goto next; 11405 11406 env->imbalance = 0; 11407 break; 11408 11409 case migrate_llc_task: 11410 env->imbalance--; 11411 break; 11412 } 11413 11414 detach_task(p, env); 11415 list_add(&p->se.group_node, &env->tasks); 11416 11417 detached++; 11418 11419 #ifdef CONFIG_PREEMPTION 11420 /* 11421 * NEWIDLE balancing is a source of latency, so preemptible 11422 * kernels will stop after the first task is detached to minimize 11423 * the critical section. 11424 */ 11425 if (env->idle == CPU_NEWLY_IDLE) 11426 break; 11427 #endif 11428 11429 /* 11430 * We only want to steal up to the prescribed amount of 11431 * load/util/tasks. 11432 */ 11433 if (env->imbalance <= 0) 11434 break; 11435 11436 continue; 11437 next: 11438 if (p->sched_task_hot) 11439 schedstat_inc(p->stats.nr_failed_migrations_hot); 11440 11441 list_move(&p->se.group_node, tasks); 11442 } 11443 11444 /* 11445 * Right now, this is one of only two places we collect this stat 11446 * so we can safely collect detach_one_task() stats here rather 11447 * than inside detach_one_task(). 11448 */ 11449 schedstat_add(env->sd->lb_gained[env->idle], detached); 11450 11451 return detached; 11452 } 11453 11454 /* 11455 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their 11456 * new rq. 11457 */ 11458 static void attach_tasks(struct lb_env *env) 11459 { 11460 __attach_tasks(env->dst_rq, &env->tasks); 11461 } 11462 11463 #ifdef CONFIG_NO_HZ_COMMON 11464 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq) 11465 { 11466 if (cfs_rq->avg.load_avg) 11467 return true; 11468 11469 if (cfs_rq->avg.util_avg) 11470 return true; 11471 11472 return false; 11473 } 11474 11475 static inline bool others_have_blocked(struct rq *rq) 11476 { 11477 if (cpu_util_rt(rq)) 11478 return true; 11479 11480 if (cpu_util_dl(rq)) 11481 return true; 11482 11483 if (hw_load_avg(rq)) 11484 return true; 11485 11486 if (cpu_util_irq(rq)) 11487 return true; 11488 11489 return false; 11490 } 11491 11492 static inline void update_blocked_load_tick(struct rq *rq) 11493 { 11494 WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies); 11495 } 11496 11497 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load) 11498 { 11499 if (!has_blocked_load) 11500 rq->has_blocked_load = 0; 11501 } 11502 #else /* !CONFIG_NO_HZ_COMMON: */ 11503 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq) { return false; } 11504 static inline bool others_have_blocked(struct rq *rq) { return false; } 11505 static inline void update_blocked_load_tick(struct rq *rq) {} 11506 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load) {} 11507 #endif /* !CONFIG_NO_HZ_COMMON */ 11508 11509 static bool __update_blocked_others(struct rq *rq, bool *done) 11510 { 11511 bool updated; 11512 11513 /* 11514 * update_load_avg() can call cpufreq_update_util(). Make sure that RT, 11515 * DL and IRQ signals have been updated before updating CFS. 11516 */ 11517 updated = update_other_load_avgs(rq); 11518 11519 if (others_have_blocked(rq)) 11520 *done = false; 11521 11522 return updated; 11523 } 11524 11525 #ifdef CONFIG_FAIR_GROUP_SCHED 11526 11527 static bool __update_blocked_fair(struct rq *rq, bool *done) 11528 { 11529 struct cfs_rq *cfs_rq, *pos; 11530 bool decayed = false; 11531 11532 /* 11533 * Iterates the task_group tree in a bottom up fashion, see 11534 * list_add_leaf_cfs_rq() for details. 11535 */ 11536 for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) { 11537 struct sched_entity *se; 11538 11539 if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) { 11540 update_tg_load_avg(cfs_rq); 11541 11542 if (cfs_rq->nr_queued == 0) 11543 update_idle_cfs_rq_clock_pelt(cfs_rq); 11544 11545 if (cfs_rq == &rq->cfs) 11546 decayed = true; 11547 } 11548 11549 /* Propagate pending load changes to the parent, if any: */ 11550 se = cfs_rq_se(cfs_rq); 11551 if (se && !skip_blocked_update(se)) 11552 update_load_avg(cfs_rq_of(se), se, UPDATE_TG); 11553 11554 /* 11555 * There can be a lot of idle CPU cgroups. Don't let fully 11556 * decayed cfs_rqs linger on the list. 11557 */ 11558 if (cfs_rq_is_decayed(cfs_rq)) 11559 list_del_leaf_cfs_rq(cfs_rq); 11560 11561 /* Don't need periodic decay once load/util_avg are null */ 11562 if (cfs_rq_has_blocked_load(cfs_rq)) 11563 *done = false; 11564 } 11565 11566 return decayed; 11567 } 11568 11569 /* 11570 * Compute the hierarchical load factor for cfs_rq and all its ascendants. 11571 * This needs to be done in a top-down fashion because the load of a child 11572 * group is a fraction of its parents load. 11573 */ 11574 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq) 11575 { 11576 struct sched_entity *se = cfs_rq_se(cfs_rq); 11577 unsigned long now = jiffies; 11578 unsigned long load; 11579 11580 if (cfs_rq->last_h_load_update == now) 11581 return; 11582 11583 WRITE_ONCE(cfs_rq->h_load_next, NULL); 11584 for_each_sched_entity(se) { 11585 cfs_rq = cfs_rq_of(se); 11586 WRITE_ONCE(cfs_rq->h_load_next, se); 11587 if (cfs_rq->last_h_load_update == now) 11588 break; 11589 } 11590 11591 if (!se) { 11592 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq); 11593 cfs_rq->last_h_load_update = now; 11594 } 11595 11596 while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) { 11597 load = cfs_rq->h_load; 11598 load = div64_ul(load * se->avg.load_avg, 11599 cfs_rq_load_avg(cfs_rq) + 1); 11600 cfs_rq = group_cfs_rq(se); 11601 cfs_rq->h_load = load; 11602 cfs_rq->last_h_load_update = now; 11603 } 11604 } 11605 11606 static unsigned long task_h_load(struct task_struct *p) 11607 { 11608 struct cfs_rq *cfs_rq = task_cfs_rq(p); 11609 11610 update_cfs_rq_h_load(cfs_rq); 11611 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load, 11612 cfs_rq_load_avg(cfs_rq) + 1); 11613 } 11614 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 11615 static bool __update_blocked_fair(struct rq *rq, bool *done) 11616 { 11617 struct cfs_rq *cfs_rq = &rq->cfs; 11618 bool decayed; 11619 11620 decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq); 11621 if (cfs_rq_has_blocked_load(cfs_rq)) 11622 *done = false; 11623 11624 return decayed; 11625 } 11626 11627 static unsigned long task_h_load(struct task_struct *p) 11628 { 11629 return p->se.avg.load_avg; 11630 } 11631 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 11632 11633 static void __sched_balance_update_blocked_averages(struct rq *rq) 11634 { 11635 bool decayed = false, done = true; 11636 11637 update_blocked_load_tick(rq); 11638 11639 decayed |= __update_blocked_others(rq, &done); 11640 decayed |= __update_blocked_fair(rq, &done); 11641 11642 update_has_blocked_load_status(rq, !done); 11643 if (decayed) 11644 cpufreq_update_util(rq, 0); 11645 } 11646 11647 static void sched_balance_update_blocked_averages(int cpu) 11648 { 11649 struct rq *rq = cpu_rq(cpu); 11650 11651 guard(rq_lock_irqsave)(rq); 11652 update_rq_clock(rq); 11653 __sched_balance_update_blocked_averages(rq); 11654 } 11655 11656 /********** Helpers for sched_balance_find_src_group ************************/ 11657 11658 /* 11659 * sg_lb_stats - stats of a sched_group required for load-balancing: 11660 */ 11661 struct sg_lb_stats { 11662 unsigned long avg_load; /* Avg load over the CPUs of the group */ 11663 unsigned long group_load; /* Total load over the CPUs of the group */ 11664 unsigned long group_capacity; /* Capacity over the CPUs of the group */ 11665 unsigned long group_util; /* Total utilization over the CPUs of the group */ 11666 unsigned long group_runnable; /* Total runnable time over the CPUs of the group */ 11667 unsigned int sum_nr_running; /* Nr of all tasks running in the group */ 11668 unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */ 11669 unsigned int idle_cpus; /* Nr of idle CPUs in the group */ 11670 unsigned int group_weight; 11671 enum group_type group_type; 11672 unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */ 11673 unsigned int group_smt_balance; /* Task on busy SMT be moved */ 11674 unsigned int group_llc_balance; /* Tasks should be moved to preferred LLC */ 11675 unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */ 11676 unsigned int group_overutilized; /* At least one CPU is overutilized in the group */ 11677 #ifdef CONFIG_NUMA_BALANCING 11678 unsigned int nr_numa_running; 11679 unsigned int nr_preferred_running; 11680 #endif 11681 #ifdef CONFIG_SCHED_CACHE 11682 unsigned int nr_pref_dst_llc; 11683 #endif 11684 }; 11685 11686 /* 11687 * sd_lb_stats - stats of a sched_domain required for load-balancing: 11688 */ 11689 struct sd_lb_stats { 11690 struct sched_group *busiest; /* Busiest group in this sd */ 11691 struct sched_group *local; /* Local group in this sd */ 11692 unsigned long total_load; /* Total load of all groups in sd */ 11693 unsigned long total_capacity; /* Total capacity of all groups in sd */ 11694 unsigned long avg_load; /* Average load across all groups in sd */ 11695 unsigned int prefer_sibling; /* Tasks should go to sibling first */ 11696 11697 struct sg_lb_stats busiest_stat; /* Statistics of the busiest group */ 11698 struct sg_lb_stats local_stat; /* Statistics of the local group */ 11699 }; 11700 11701 static inline void init_sd_lb_stats(struct sd_lb_stats *sds) 11702 { 11703 /* 11704 * Skimp on the clearing to avoid duplicate work. We can avoid clearing 11705 * local_stat because update_sg_lb_stats() does a full clear/assignment. 11706 * We must however set busiest_stat::group_type and 11707 * busiest_stat::idle_cpus to the worst busiest group because 11708 * update_sd_pick_busiest() reads these before assignment. 11709 */ 11710 *sds = (struct sd_lb_stats){ 11711 .busiest = NULL, 11712 .local = NULL, 11713 .total_load = 0UL, 11714 .total_capacity = 0UL, 11715 .busiest_stat = { 11716 .idle_cpus = UINT_MAX, 11717 .group_type = group_has_spare, 11718 }, 11719 }; 11720 } 11721 11722 static unsigned long scale_rt_capacity(int cpu) 11723 { 11724 unsigned long max = get_actual_cpu_capacity(cpu); 11725 struct rq *rq = cpu_rq(cpu); 11726 unsigned long used, free; 11727 unsigned long irq; 11728 11729 irq = cpu_util_irq(rq); 11730 11731 if (unlikely(irq >= max)) 11732 return 1; 11733 11734 /* 11735 * avg_rt.util_avg and avg_dl.util_avg track binary signals 11736 * (running and not running) with weights 0 and 1024 respectively. 11737 */ 11738 used = cpu_util_rt(rq); 11739 used += cpu_util_dl(rq); 11740 11741 if (unlikely(used >= max)) 11742 return 1; 11743 11744 free = max - used; 11745 11746 return scale_irq_capacity(free, irq, max); 11747 } 11748 11749 static void update_cpu_capacity(struct sched_domain *sd, int cpu) 11750 { 11751 unsigned long capacity = scale_rt_capacity(cpu); 11752 struct sched_group *sdg = sd->groups; 11753 11754 if (!capacity) 11755 capacity = 1; 11756 11757 cpu_rq(cpu)->cpu_capacity = capacity; 11758 trace_sched_cpu_capacity_tp(cpu_rq(cpu)); 11759 11760 sdg->sgc->capacity = capacity; 11761 sdg->sgc->min_capacity = capacity; 11762 sdg->sgc->max_capacity = capacity; 11763 } 11764 11765 void update_group_capacity(struct sched_domain *sd, int cpu) 11766 { 11767 struct sched_domain *child = sd->child; 11768 struct sched_group *group, *sdg = sd->groups; 11769 unsigned long capacity, min_capacity, max_capacity; 11770 unsigned long interval; 11771 11772 interval = msecs_to_jiffies(sd->balance_interval); 11773 interval = clamp(interval, 1UL, max_load_balance_interval); 11774 sdg->sgc->next_update = jiffies + interval; 11775 11776 if (!child) { 11777 update_cpu_capacity(sd, cpu); 11778 return; 11779 } 11780 11781 capacity = 0; 11782 min_capacity = ULONG_MAX; 11783 max_capacity = 0; 11784 11785 if (child->flags & SD_NUMA) { 11786 /* 11787 * SD_NUMA domains cannot assume that child groups 11788 * span the current group. 11789 */ 11790 11791 for_each_cpu(cpu, sched_group_span(sdg)) { 11792 unsigned long cpu_cap = capacity_of(cpu); 11793 11794 capacity += cpu_cap; 11795 min_capacity = min(cpu_cap, min_capacity); 11796 max_capacity = max(cpu_cap, max_capacity); 11797 } 11798 } else { 11799 /* 11800 * !SD_NUMA domains can assume that child groups 11801 * span the current group. 11802 */ 11803 11804 group = child->groups; 11805 do { 11806 struct sched_group_capacity *sgc = group->sgc; 11807 11808 capacity += sgc->capacity; 11809 min_capacity = min(sgc->min_capacity, min_capacity); 11810 max_capacity = max(sgc->max_capacity, max_capacity); 11811 group = group->next; 11812 } while (group != child->groups); 11813 } 11814 11815 sdg->sgc->capacity = capacity; 11816 sdg->sgc->min_capacity = min_capacity; 11817 sdg->sgc->max_capacity = max_capacity; 11818 } 11819 11820 /* 11821 * Check whether the capacity of the rq has been noticeably reduced by side 11822 * activity. The imbalance_pct is used for the threshold. 11823 * Return true is the capacity is reduced 11824 */ 11825 static inline int 11826 check_cpu_capacity(struct rq *rq, struct sched_domain *sd) 11827 { 11828 return ((rq->cpu_capacity * sd->imbalance_pct) < 11829 (arch_scale_cpu_capacity(cpu_of(rq)) * 100)); 11830 } 11831 11832 /* Check if the rq has a misfit task */ 11833 static inline bool check_misfit_status(struct rq *rq) 11834 { 11835 return rq->misfit_task_load; 11836 } 11837 11838 /* 11839 * Group imbalance indicates (and tries to solve) the problem where balancing 11840 * groups is inadequate due to ->cpus_ptr constraints. 11841 * 11842 * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a 11843 * cpumask covering 1 CPU of the first group and 3 CPUs of the second group. 11844 * Something like: 11845 * 11846 * { 0 1 2 3 } { 4 5 6 7 } 11847 * * * * * 11848 * 11849 * If we were to balance group-wise we'd place two tasks in the first group and 11850 * two tasks in the second group. Clearly this is undesired as it will overload 11851 * cpu 3 and leave one of the CPUs in the second group unused. 11852 * 11853 * The current solution to this issue is detecting the skew in the first group 11854 * by noticing the lower domain failed to reach balance and had difficulty 11855 * moving tasks due to affinity constraints. 11856 * 11857 * When this is so detected; this group becomes a candidate for busiest; see 11858 * update_sd_pick_busiest(). And calculate_imbalance() and 11859 * sched_balance_find_src_group() avoid some of the usual balance conditions to allow it 11860 * to create an effective group imbalance. 11861 * 11862 * This is a somewhat tricky proposition since the next run might not find the 11863 * group imbalance and decide the groups need to be balanced again. A most 11864 * subtle and fragile situation. 11865 */ 11866 11867 static inline int sg_imbalanced(struct sched_group *group) 11868 { 11869 return group->sgc->imbalance; 11870 } 11871 11872 /* 11873 * group_has_capacity returns true if the group has spare capacity that could 11874 * be used by some tasks. 11875 * We consider that a group has spare capacity if the number of task is 11876 * smaller than the number of CPUs or if the utilization is lower than the 11877 * available capacity for CFS tasks. 11878 * For the latter, we use a threshold to stabilize the state, to take into 11879 * account the variance of the tasks' load and to return true if the available 11880 * capacity in meaningful for the load balancer. 11881 * As an example, an available capacity of 1% can appear but it doesn't make 11882 * any benefit for the load balance. 11883 */ 11884 static inline bool 11885 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs) 11886 { 11887 if (sgs->sum_nr_running < sgs->group_weight) 11888 return true; 11889 11890 if ((sgs->group_capacity * imbalance_pct) < 11891 (sgs->group_runnable * 100)) 11892 return false; 11893 11894 if ((sgs->group_capacity * 100) > 11895 (sgs->group_util * imbalance_pct)) 11896 return true; 11897 11898 return false; 11899 } 11900 11901 /* 11902 * group_is_overloaded returns true if the group has more tasks than it can 11903 * handle. 11904 * group_is_overloaded is not equals to !group_has_capacity because a group 11905 * with the exact right number of tasks, has no more spare capacity but is not 11906 * overloaded so both group_has_capacity and group_is_overloaded return 11907 * false. 11908 */ 11909 static inline bool 11910 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs) 11911 { 11912 /* 11913 * With EAS and uclamp, 1 CPU in the group must be overutilized to 11914 * consider the group overloaded. 11915 */ 11916 if (sched_energy_enabled() && !sgs->group_overutilized) 11917 return false; 11918 11919 if (sgs->sum_nr_running <= sgs->group_weight) 11920 return false; 11921 11922 if ((sgs->group_capacity * 100) < 11923 (sgs->group_util * imbalance_pct)) 11924 return true; 11925 11926 if ((sgs->group_capacity * imbalance_pct) < 11927 (sgs->group_runnable * 100)) 11928 return true; 11929 11930 return false; 11931 } 11932 11933 static inline enum 11934 group_type group_classify(unsigned int imbalance_pct, 11935 struct sched_group *group, 11936 struct sg_lb_stats *sgs) 11937 { 11938 if (group_is_overloaded(imbalance_pct, sgs)) 11939 return group_overloaded; 11940 11941 if (sgs->group_llc_balance) 11942 return group_llc_balance; 11943 11944 if (sg_imbalanced(group)) 11945 return group_imbalanced; 11946 11947 if (sgs->group_asym_packing) 11948 return group_asym_packing; 11949 11950 if (sgs->group_smt_balance) 11951 return group_smt_balance; 11952 11953 if (sgs->group_misfit_task_load) 11954 return group_misfit_task; 11955 11956 if (!group_has_capacity(imbalance_pct, sgs)) 11957 return group_fully_busy; 11958 11959 return group_has_spare; 11960 } 11961 11962 /** 11963 * sched_use_asym_prio - Check whether asym_packing priority must be used 11964 * @sd: The scheduling domain of the load balancing 11965 * @cpu: A CPU 11966 * 11967 * Always use CPU priority when balancing load between SMT siblings. When 11968 * balancing load between cores, it is not sufficient that @cpu is idle. Only 11969 * use CPU priority if the whole core is idle. 11970 * 11971 * Returns: True if the priority of @cpu must be followed. False otherwise. 11972 */ 11973 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu) 11974 { 11975 if (!(sd->flags & SD_ASYM_PACKING)) 11976 return false; 11977 11978 if (!sched_smt_active()) 11979 return true; 11980 11981 return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu); 11982 } 11983 11984 static inline bool sched_asym(struct sched_domain *sd, int dst_cpu, int src_cpu) 11985 { 11986 /* 11987 * First check if @dst_cpu can do asym_packing load balance. Only do it 11988 * if it has higher priority than @src_cpu. 11989 */ 11990 return sched_use_asym_prio(sd, dst_cpu) && 11991 sched_asym_prefer(dst_cpu, src_cpu); 11992 } 11993 11994 /** 11995 * sched_group_asym - Check if the destination CPU can do asym_packing balance 11996 * @env: The load balancing environment 11997 * @sgs: Load-balancing statistics of the candidate busiest group 11998 * @group: The candidate busiest group 11999 * 12000 * @env::dst_cpu can do asym_packing if it has higher priority than the 12001 * preferred CPU of @group. 12002 * 12003 * Return: true if @env::dst_cpu can do with asym_packing load balance. False 12004 * otherwise. 12005 */ 12006 static inline bool 12007 sched_group_asym(struct lb_env *env, struct sg_lb_stats *sgs, struct sched_group *group) 12008 { 12009 /* 12010 * CPU priorities do not make sense for SMT cores with more than one 12011 * busy sibling. 12012 */ 12013 if ((group->flags & SD_SHARE_CPUCAPACITY) && 12014 (sgs->group_weight - sgs->idle_cpus != 1)) 12015 return false; 12016 12017 return sched_asym(env->sd, env->dst_cpu, READ_ONCE(group->asym_prefer_cpu)); 12018 } 12019 12020 /* One group has more than one SMT CPU while the other group does not */ 12021 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1, 12022 struct sched_group *sg2) 12023 { 12024 if (!sg1 || !sg2) 12025 return false; 12026 12027 return (sg1->flags & SD_SHARE_CPUCAPACITY) != 12028 (sg2->flags & SD_SHARE_CPUCAPACITY); 12029 } 12030 12031 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs, 12032 struct sched_group *group) 12033 { 12034 if (!env->idle) 12035 return false; 12036 12037 /* 12038 * For SMT source group, it is better to move a task 12039 * to a CPU that doesn't have multiple tasks sharing its CPU capacity. 12040 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY 12041 * will not be on. 12042 */ 12043 if (group->flags & SD_SHARE_CPUCAPACITY && 12044 sgs->sum_h_nr_running > 1) 12045 return true; 12046 12047 return false; 12048 } 12049 12050 static inline long sibling_imbalance(struct lb_env *env, 12051 struct sd_lb_stats *sds, 12052 struct sg_lb_stats *busiest, 12053 struct sg_lb_stats *local) 12054 { 12055 int ncores_busiest, ncores_local; 12056 long imbalance; 12057 12058 if (!env->idle || !busiest->sum_nr_running) 12059 return 0; 12060 12061 ncores_busiest = sds->busiest->cores; 12062 ncores_local = sds->local->cores; 12063 12064 if (ncores_busiest == ncores_local) { 12065 imbalance = busiest->sum_nr_running; 12066 lsub_positive(&imbalance, local->sum_nr_running); 12067 return imbalance; 12068 } 12069 12070 /* Balance such that nr_running/ncores ratio are same on both groups */ 12071 imbalance = ncores_local * busiest->sum_nr_running; 12072 lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running); 12073 /* Normalize imbalance and do rounding on normalization */ 12074 imbalance = 2 * imbalance + ncores_local + ncores_busiest; 12075 imbalance /= ncores_local + ncores_busiest; 12076 12077 /* Take advantage of resource in an empty sched group */ 12078 if (imbalance <= 1 && local->sum_nr_running == 0 && 12079 busiest->sum_nr_running > 1) 12080 imbalance = 2; 12081 12082 return imbalance; 12083 } 12084 12085 static inline bool 12086 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd) 12087 { 12088 /* 12089 * When there is more than 1 task, the group_overloaded case already 12090 * takes care of cpu with reduced capacity 12091 */ 12092 if (rq->cfs.h_nr_runnable != 1) 12093 return false; 12094 12095 return check_cpu_capacity(rq, sd); 12096 } 12097 12098 #ifdef CONFIG_SCHED_CACHE 12099 /* 12100 * Record the statistics for this scheduler group for later 12101 * use. These values guide load balancing on aggregating tasks 12102 * to a LLC. 12103 */ 12104 static void record_sg_llc_stats(struct lb_env *env, 12105 struct sg_lb_stats *sgs, 12106 struct sched_group *group) 12107 { 12108 struct sched_domain_shared *sd_share; 12109 int cpu; 12110 12111 if (!sched_cache_enabled() || env->idle == CPU_NEWLY_IDLE) 12112 return; 12113 12114 /* Only care about sched domain spanning multiple LLCs */ 12115 if (env->sd->child != rcu_dereference_all(per_cpu(sd_llc, env->dst_cpu))) 12116 return; 12117 12118 /* 12119 * A redo repeats stats published on the first pass. Hotplug can 12120 * still leave env->cpus partial, so util would not match capacity. 12121 */ 12122 if ((env->flags & LBF_ALL_PINNED) || 12123 !cpumask_subset(sched_group_span(group), env->cpus)) 12124 return; 12125 12126 /* 12127 * At this point we know this group spans a LLC domain. 12128 * Record the statistic of this group in its corresponding 12129 * shared LLC domain. 12130 * Note: sd_share cannot be obtained via sd->child->shared, 12131 * because the latter refers to the domain that covers the 12132 * local group. Instead, sd_share should be located using 12133 * the first CPU of the LLC group. 12134 */ 12135 cpu = cpumask_first(sched_group_span(group)); 12136 sd_share = rcu_dereference_all(per_cpu(sd_llc_shared, cpu)); 12137 if (!sd_share) 12138 return; 12139 12140 if (READ_ONCE(sd_share->util_avg) != sgs->group_util) 12141 WRITE_ONCE(sd_share->util_avg, sgs->group_util); 12142 12143 if (unlikely(READ_ONCE(sd_share->capacity) != sgs->group_capacity)) 12144 WRITE_ONCE(sd_share->capacity, sgs->group_capacity); 12145 } 12146 12147 /* 12148 * Do LLC balance on sched group that contains LLC, and have tasks preferring 12149 * to run on LLC in idle dst_cpu. 12150 */ 12151 static inline bool llc_balance(struct lb_env *env, struct sg_lb_stats *sgs, 12152 struct sched_group *group) 12153 { 12154 if (!sched_cache_enabled()) 12155 return false; 12156 12157 if (env->sd->flags & SD_SHARE_LLC) 12158 return false; 12159 12160 /* 12161 * On asymmetric domains, group_misfit_task_load 12162 * should be prioritized to move tasks to CPU that fit them 12163 * over aggregating tasks to their preferred LLC. 12164 */ 12165 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) && 12166 sgs->group_misfit_task_load) 12167 return false; 12168 12169 /* 12170 * On asym packing domains, if the destination CPU 12171 * has higher priority than all CPUs in the source group, 12172 * prioritize asym packing. 12173 */ 12174 if (sgs->group_asym_packing) 12175 return false; 12176 12177 /* 12178 * Skip cache aware tagging if nr_balanced_failed is sufficiently high. 12179 * Threshold of cache_nice_tries is set to 1 higher than nr_balance_failed 12180 * to avoid excessive task migration at the same time. 12181 */ 12182 if (env->sd->nr_balance_failed >= env->sd->cache_nice_tries + 1) 12183 return false; 12184 12185 if (sgs->nr_pref_dst_llc && 12186 can_migrate_llc(cpumask_first(sched_group_span(group)), 12187 env->dst_cpu, 0, true) == mig_llc) 12188 return true; 12189 12190 return false; 12191 } 12192 12193 static bool update_llc_busiest(struct lb_env *env, 12194 struct sg_lb_stats *busiest, 12195 struct sg_lb_stats *sgs) 12196 { 12197 /* 12198 * There are more tasks that want to run on dst_cpu's LLC. 12199 */ 12200 return sgs->nr_pref_dst_llc > busiest->nr_pref_dst_llc; 12201 } 12202 #else 12203 static inline void record_sg_llc_stats(struct lb_env *env, struct sg_lb_stats *sgs, 12204 struct sched_group *group) 12205 { 12206 } 12207 12208 static inline bool llc_balance(struct lb_env *env, struct sg_lb_stats *sgs, 12209 struct sched_group *group) 12210 { 12211 return false; 12212 } 12213 12214 static bool update_llc_busiest(struct lb_env *env, 12215 struct sg_lb_stats *busiest, 12216 struct sg_lb_stats *sgs) 12217 { 12218 return false; 12219 } 12220 #endif 12221 12222 /** 12223 * update_sg_lb_stats - Update sched_group's statistics for load balancing. 12224 * @env: The load balancing environment. 12225 * @sds: Load-balancing data with statistics of the local group. 12226 * @group: sched_group whose statistics are to be updated. 12227 * @sgs: variable to hold the statistics for this group. 12228 * @sg_overloaded: sched_group is overloaded 12229 */ 12230 static inline void update_sg_lb_stats(struct lb_env *env, 12231 struct sd_lb_stats *sds, 12232 struct sched_group *group, 12233 struct sg_lb_stats *sgs, 12234 bool *sg_overloaded) 12235 { 12236 int i, nr_running, local_group, sd_flags = env->sd->flags; 12237 bool balancing_at_rd = !env->sd->parent; 12238 12239 memset(sgs, 0, sizeof(*sgs)); 12240 12241 local_group = group == sds->local; 12242 12243 for_each_cpu_and(i, sched_group_span(group), env->cpus) { 12244 struct rq *rq = cpu_rq(i); 12245 unsigned long load = cpu_load(rq); 12246 12247 sgs->group_load += load; 12248 sgs->group_util += cpu_util_cfs(i); 12249 sgs->group_runnable += cpu_runnable(rq); 12250 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable; 12251 12252 nr_running = rq->nr_running; 12253 sgs->sum_nr_running += nr_running; 12254 12255 if (cpu_overutilized(i)) 12256 sgs->group_overutilized = 1; 12257 12258 #ifdef CONFIG_SCHED_CACHE 12259 if (sched_cache_enabled()) { 12260 struct sched_domain *sd_tmp; 12261 int dst_llc; 12262 12263 dst_llc = llc_id(env->dst_cpu); 12264 if (llc_id(i) != dst_llc) { 12265 sd_tmp = rcu_dereference_all(rq->sd); 12266 if (sd_tmp && (unsigned int)dst_llc < sd_tmp->llc_max) 12267 sgs->nr_pref_dst_llc += sd_tmp->llc_counts[dst_llc]; 12268 } 12269 } 12270 #endif 12271 12272 /* 12273 * No need to call idle_cpu() if nr_running is not 0 12274 */ 12275 if (!nr_running && idle_cpu(i)) { 12276 sgs->idle_cpus++; 12277 /* Idle cpu can't have misfit task */ 12278 continue; 12279 } 12280 12281 /* Overload indicator is only updated at root domain */ 12282 if (balancing_at_rd && nr_running > 1) 12283 *sg_overloaded = 1; 12284 12285 #ifdef CONFIG_NUMA_BALANCING 12286 /* Only fbq_classify_group() uses this to classify NUMA groups */ 12287 if (sd_flags & SD_NUMA) { 12288 sgs->nr_numa_running += rq->nr_numa_running; 12289 sgs->nr_preferred_running += rq->nr_preferred_running; 12290 } 12291 #endif 12292 if (local_group) 12293 continue; 12294 12295 if (sd_flags & SD_ASYM_CPUCAPACITY) { 12296 if (rq->misfit_task_load) { 12297 /* 12298 * Always mark the root domain overloaded so big 12299 * CPUs can pick up misfit tasks via newly idle 12300 * balance. 12301 */ 12302 if (balancing_at_rd) 12303 *sg_overloaded = 1; 12304 12305 /* 12306 * Only account misfit load if @dst_cpu can 12307 * help; otherwise, the group may be classified 12308 * as misfit_task and update_sd_pick_busiest() 12309 * will skip it. 12310 */ 12311 if (capacity_greater(capacity_of(env->dst_cpu), 12312 group->sgc->max_capacity) && 12313 (sgs->group_misfit_task_load < rq->misfit_task_load)) 12314 sgs->group_misfit_task_load = rq->misfit_task_load; 12315 } 12316 } else if (env->idle && sched_reduced_capacity(rq, env->sd)) { 12317 /* Check for a task running on a CPU with reduced capacity */ 12318 if (sgs->group_misfit_task_load < load) 12319 sgs->group_misfit_task_load = load; 12320 } 12321 } 12322 12323 sgs->group_capacity = group->sgc->capacity; 12324 12325 sgs->group_weight = group->group_weight; 12326 12327 if (!local_group) { 12328 /* Check if dst CPU is idle and preferred to this group */ 12329 if (env->idle && sgs->sum_h_nr_running && 12330 sched_group_asym(env, sgs, group)) 12331 sgs->group_asym_packing = 1; 12332 12333 /* Check for loaded SMT group to be balanced to dst CPU */ 12334 if (smt_balance(env, sgs, group)) 12335 sgs->group_smt_balance = 1; 12336 12337 /* Check for tasks in this group can be moved to their preferred LLC */ 12338 if (llc_balance(env, sgs, group)) 12339 sgs->group_llc_balance = 1; 12340 } 12341 12342 sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs); 12343 12344 record_sg_llc_stats(env, sgs, group); 12345 /* Computing avg_load makes sense only when group is overloaded */ 12346 if (sgs->group_type == group_overloaded) 12347 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) / 12348 sgs->group_capacity; 12349 } 12350 12351 /** 12352 * update_sd_pick_busiest - return 1 on busiest group 12353 * @env: The load balancing environment. 12354 * @sds: sched_domain statistics 12355 * @sg: sched_group candidate to be checked for being the busiest 12356 * @sgs: sched_group statistics 12357 * 12358 * Determine if @sg is a busier group than the previously selected 12359 * busiest group. 12360 * 12361 * Return: %true if @sg is a busier group than the previously selected 12362 * busiest group. %false otherwise. 12363 */ 12364 static bool update_sd_pick_busiest(struct lb_env *env, 12365 struct sd_lb_stats *sds, 12366 struct sched_group *sg, 12367 struct sg_lb_stats *sgs) 12368 { 12369 struct sg_lb_stats *busiest = &sds->busiest_stat; 12370 12371 /* Make sure that there is at least one task to pull */ 12372 if (!sgs->sum_h_nr_running) 12373 return false; 12374 12375 /* 12376 * Don't try to pull misfit tasks we can't help. 12377 * We can use max_capacity here as reduction in capacity on some 12378 * CPUs in the group should either be possible to resolve 12379 * internally or be covered by avg_load imbalance (eventually). 12380 * 12381 * When SMT is active, only pull a misfit to dst_cpu if it is on a 12382 * fully idle core; otherwise the effective capacity of the core is 12383 * reduced and we may not actually provide more capacity than the 12384 * source. 12385 */ 12386 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) && 12387 (sgs->group_type == group_misfit_task) && 12388 (!env->dst_core_idle || 12389 !capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) || 12390 sds->local_stat.group_type != group_has_spare)) 12391 return false; 12392 12393 /* 12394 * Candidate sg has no more than one task per CPU and has higher 12395 * per-CPU capacity. Migrating tasks to less capable CPUs may harm 12396 * throughput. Maximize throughput, power/energy consequences are not 12397 * considered. 12398 */ 12399 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) && 12400 (sgs->group_type <= group_fully_busy) && 12401 (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu)))) 12402 return false; 12403 12404 if (sgs->group_type > busiest->group_type) 12405 return true; 12406 12407 if (sgs->group_type < busiest->group_type) 12408 return false; 12409 12410 /* 12411 * The candidate and the current busiest group are the same type of 12412 * group. Let check which one is the busiest according to the type. 12413 */ 12414 12415 switch (sgs->group_type) { 12416 case group_overloaded: 12417 /* Select the overloaded group with highest avg_load. */ 12418 return sgs->avg_load > busiest->avg_load; 12419 12420 case group_llc_balance: 12421 /* Select the group with most tasks preferring dst LLC */ 12422 return update_llc_busiest(env, busiest, sgs); 12423 12424 case group_imbalanced: 12425 /* 12426 * Select the 1st imbalanced group as we don't have any way to 12427 * choose one more than another. 12428 */ 12429 return false; 12430 12431 case group_asym_packing: 12432 /* Prefer to move from lowest priority CPU's work */ 12433 return sched_asym_prefer(READ_ONCE(sds->busiest->asym_prefer_cpu), 12434 READ_ONCE(sg->asym_prefer_cpu)); 12435 12436 case group_misfit_task: 12437 /* 12438 * If we have more than one misfit sg go with the biggest 12439 * misfit. 12440 */ 12441 return sgs->group_misfit_task_load > busiest->group_misfit_task_load; 12442 12443 case group_smt_balance: 12444 /* 12445 * Check if we have spare CPUs on either SMT group to 12446 * choose has spare or fully busy handling. 12447 */ 12448 if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0) 12449 goto has_spare; 12450 12451 fallthrough; 12452 12453 case group_fully_busy: 12454 /* 12455 * Select the fully busy group with highest avg_load. In 12456 * theory, there is no need to pull task from such kind of 12457 * group because tasks have all compute capacity that they need 12458 * but we can still improve the overall throughput by reducing 12459 * contention when accessing shared HW resources. 12460 * 12461 * XXX for now avg_load is not computed and always 0 so we 12462 * select the 1st one, except if @sg is composed of SMT 12463 * siblings. 12464 */ 12465 12466 if (sgs->avg_load < busiest->avg_load) 12467 return false; 12468 12469 if (sgs->avg_load == busiest->avg_load) { 12470 /* 12471 * SMT sched groups need more help than non-SMT groups. 12472 * If @sg happens to also be SMT, either choice is good. 12473 */ 12474 if (sds->busiest->flags & SD_SHARE_CPUCAPACITY) 12475 return false; 12476 } 12477 12478 break; 12479 12480 case group_has_spare: 12481 /* 12482 * Do not pick sg with SMT CPUs over sg with pure CPUs, 12483 * as we do not want to pull task off SMT core with one task 12484 * and make the core idle. 12485 */ 12486 if (smt_vs_nonsmt_groups(sds->busiest, sg)) { 12487 if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1) 12488 return false; 12489 else 12490 return true; 12491 } 12492 has_spare: 12493 12494 /* 12495 * Select not overloaded group with lowest number of idle CPUs 12496 * and highest number of running tasks. We could also compare 12497 * the spare capacity which is more stable but it can end up 12498 * that the group has less spare capacity but finally more idle 12499 * CPUs which means less opportunity to pull tasks. 12500 */ 12501 if (sgs->idle_cpus > busiest->idle_cpus) 12502 return false; 12503 else if ((sgs->idle_cpus == busiest->idle_cpus) && 12504 (sgs->sum_nr_running <= busiest->sum_nr_running)) 12505 return false; 12506 12507 break; 12508 } 12509 12510 return true; 12511 } 12512 12513 #ifdef CONFIG_NUMA_BALANCING 12514 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs) 12515 { 12516 if (sgs->sum_h_nr_running > sgs->nr_numa_running) 12517 return regular; 12518 if (sgs->sum_h_nr_running > sgs->nr_preferred_running) 12519 return remote; 12520 return all; 12521 } 12522 12523 static inline enum fbq_type fbq_classify_rq(struct rq *rq) 12524 { 12525 if (rq->nr_running > rq->nr_numa_running) 12526 return regular; 12527 if (rq->nr_running > rq->nr_preferred_running) 12528 return remote; 12529 return all; 12530 } 12531 #else /* !CONFIG_NUMA_BALANCING: */ 12532 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs) 12533 { 12534 return all; 12535 } 12536 12537 static inline enum fbq_type fbq_classify_rq(struct rq *rq) 12538 { 12539 return regular; 12540 } 12541 #endif /* !CONFIG_NUMA_BALANCING */ 12542 12543 12544 struct sg_lb_stats; 12545 12546 /* 12547 * task_running_on_cpu - return 1 if @p is running on @cpu. 12548 */ 12549 12550 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p) 12551 { 12552 /* Task has no contribution or is new */ 12553 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 12554 return 0; 12555 12556 if (task_on_rq_queued(p)) 12557 return 1; 12558 12559 return 0; 12560 } 12561 12562 /** 12563 * idle_cpu_without - would a given CPU be idle without p ? 12564 * @cpu: the processor on which idleness is tested. 12565 * @p: task which should be ignored. 12566 * 12567 * Return: 1 if the CPU would be idle. 0 otherwise. 12568 */ 12569 static int idle_cpu_without(int cpu, struct task_struct *p) 12570 { 12571 struct rq *rq = cpu_rq(cpu); 12572 12573 if (rq->curr != rq->idle && rq->curr != p) 12574 return 0; 12575 12576 /* 12577 * rq->nr_running can't be used but an updated version without the 12578 * impact of p on cpu must be used instead. The updated nr_running 12579 * be computed and tested before calling idle_cpu_without(). 12580 */ 12581 12582 if (rq->ttwu_pending) 12583 return 0; 12584 12585 return 1; 12586 } 12587 12588 /* 12589 * update_sg_wakeup_stats - Update sched_group's statistics for wakeup. 12590 * @sd: The sched_domain level to look for idlest group. 12591 * @group: sched_group whose statistics are to be updated. 12592 * @sgs: variable to hold the statistics for this group. 12593 * @p: The task for which we look for the idlest group/CPU. 12594 */ 12595 static inline void update_sg_wakeup_stats(struct sched_domain *sd, 12596 struct sched_group *group, 12597 struct sg_lb_stats *sgs, 12598 struct task_struct *p) 12599 { 12600 int i, nr_running; 12601 12602 memset(sgs, 0, sizeof(*sgs)); 12603 12604 /* Assume that task can't fit any CPU of the group */ 12605 if (sd->flags & SD_ASYM_CPUCAPACITY) 12606 sgs->group_misfit_task_load = 1; 12607 12608 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) { 12609 struct rq *rq = cpu_rq(i); 12610 unsigned int local; 12611 12612 sgs->group_load += cpu_load_without(rq, p); 12613 sgs->group_util += cpu_util_without(i, p); 12614 sgs->group_runnable += cpu_runnable_without(rq, p); 12615 local = task_running_on_cpu(i, p); 12616 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable - local; 12617 12618 nr_running = rq->nr_running - local; 12619 sgs->sum_nr_running += nr_running; 12620 12621 /* 12622 * No need to call idle_cpu_without() if nr_running is not 0 12623 */ 12624 if (!nr_running && idle_cpu_without(i, p)) 12625 sgs->idle_cpus++; 12626 12627 /* Check if task fits in the CPU */ 12628 if (sd->flags & SD_ASYM_CPUCAPACITY && 12629 sgs->group_misfit_task_load && 12630 task_fits_cpu(p, i)) 12631 sgs->group_misfit_task_load = 0; 12632 12633 } 12634 12635 sgs->group_capacity = group->sgc->capacity; 12636 12637 sgs->group_weight = group->group_weight; 12638 12639 sgs->group_type = group_classify(sd->imbalance_pct, group, sgs); 12640 12641 /* 12642 * Computing avg_load makes sense only when group is fully busy or 12643 * overloaded 12644 */ 12645 if (sgs->group_type == group_fully_busy || 12646 sgs->group_type == group_overloaded) 12647 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) / 12648 sgs->group_capacity; 12649 } 12650 12651 static bool update_pick_idlest(struct sched_group *idlest, 12652 struct sg_lb_stats *idlest_sgs, 12653 struct sched_group *group, 12654 struct sg_lb_stats *sgs) 12655 { 12656 if (sgs->group_type < idlest_sgs->group_type) 12657 return true; 12658 12659 if (sgs->group_type > idlest_sgs->group_type) 12660 return false; 12661 12662 /* 12663 * The candidate and the current idlest group are the same type of 12664 * group. Let check which one is the idlest according to the type. 12665 */ 12666 12667 switch (sgs->group_type) { 12668 case group_overloaded: 12669 case group_fully_busy: 12670 /* Select the group with lowest avg_load. */ 12671 if (idlest_sgs->avg_load <= sgs->avg_load) 12672 return false; 12673 break; 12674 12675 case group_llc_balance: 12676 case group_imbalanced: 12677 case group_asym_packing: 12678 case group_smt_balance: 12679 /* Those types are not used in the slow wakeup path */ 12680 return false; 12681 12682 case group_misfit_task: 12683 /* Select group with the highest max capacity */ 12684 if (idlest->sgc->max_capacity >= group->sgc->max_capacity) 12685 return false; 12686 break; 12687 12688 case group_has_spare: 12689 /* Select group with most idle CPUs */ 12690 if (idlest_sgs->idle_cpus > sgs->idle_cpus) 12691 return false; 12692 12693 /* Select group with lowest group_util */ 12694 if (idlest_sgs->idle_cpus == sgs->idle_cpus && 12695 idlest_sgs->group_util <= sgs->group_util) 12696 return false; 12697 12698 break; 12699 } 12700 12701 return true; 12702 } 12703 12704 /* 12705 * sched_balance_find_dst_group() finds and returns the least busy CPU group within the 12706 * domain. 12707 * 12708 * Assumes p is allowed on at least one CPU in sd. 12709 */ 12710 static struct sched_group * 12711 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu) 12712 { 12713 struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups; 12714 struct sg_lb_stats local_sgs, tmp_sgs; 12715 struct sg_lb_stats *sgs; 12716 unsigned long imbalance; 12717 struct sg_lb_stats idlest_sgs = { 12718 .avg_load = UINT_MAX, 12719 .group_type = group_overloaded, 12720 }; 12721 12722 do { 12723 int local_group; 12724 12725 /* Skip over this group if it has no CPUs allowed */ 12726 if (!cpumask_intersects(sched_group_span(group), 12727 p->cpus_ptr)) 12728 continue; 12729 12730 /* Skip over this group if no cookie matched */ 12731 if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group)) 12732 continue; 12733 12734 local_group = cpumask_test_cpu(this_cpu, 12735 sched_group_span(group)); 12736 12737 if (local_group) { 12738 sgs = &local_sgs; 12739 local = group; 12740 } else { 12741 sgs = &tmp_sgs; 12742 } 12743 12744 update_sg_wakeup_stats(sd, group, sgs, p); 12745 12746 if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) { 12747 idlest = group; 12748 idlest_sgs = *sgs; 12749 } 12750 12751 } while (group = group->next, group != sd->groups); 12752 12753 12754 /* There is no idlest group to push tasks to */ 12755 if (!idlest) 12756 return NULL; 12757 12758 /* The local group has been skipped because of CPU affinity */ 12759 if (!local) 12760 return idlest; 12761 12762 /* 12763 * If the local group is idler than the selected idlest group 12764 * don't try and push the task. 12765 */ 12766 if (local_sgs.group_type < idlest_sgs.group_type) 12767 return NULL; 12768 12769 /* 12770 * If the local group is busier than the selected idlest group 12771 * try and push the task. 12772 */ 12773 if (local_sgs.group_type > idlest_sgs.group_type) 12774 return idlest; 12775 12776 switch (local_sgs.group_type) { 12777 case group_overloaded: 12778 case group_fully_busy: 12779 12780 /* Calculate allowed imbalance based on load */ 12781 imbalance = scale_load_down(NICE_0_LOAD) * 12782 (sd->imbalance_pct-100) / 100; 12783 12784 /* 12785 * When comparing groups across NUMA domains, it's possible for 12786 * the local domain to be very lightly loaded relative to the 12787 * remote domains but "imbalance" skews the comparison making 12788 * remote CPUs look much more favourable. When considering 12789 * cross-domain, add imbalance to the load on the remote node 12790 * and consider staying local. 12791 */ 12792 12793 if ((sd->flags & SD_NUMA) && 12794 ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load)) 12795 return NULL; 12796 12797 /* 12798 * If the local group is less loaded than the selected 12799 * idlest group don't try and push any tasks. 12800 */ 12801 if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance)) 12802 return NULL; 12803 12804 if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load) 12805 return NULL; 12806 break; 12807 12808 case group_llc_balance: 12809 case group_imbalanced: 12810 case group_asym_packing: 12811 case group_smt_balance: 12812 /* Those type are not used in the slow wakeup path */ 12813 return NULL; 12814 12815 case group_misfit_task: 12816 /* Select group with the highest max capacity */ 12817 if (local->sgc->max_capacity >= idlest->sgc->max_capacity) 12818 return NULL; 12819 break; 12820 12821 case group_has_spare: 12822 #ifdef CONFIG_NUMA 12823 if (sd->flags & SD_NUMA) { 12824 int imb_numa_nr = sd->imb_numa_nr; 12825 #ifdef CONFIG_NUMA_BALANCING 12826 int idlest_cpu; 12827 /* 12828 * If there is spare capacity at NUMA, try to select 12829 * the preferred node 12830 */ 12831 if (cpu_to_node(this_cpu) == p->numa_preferred_nid) 12832 return NULL; 12833 12834 idlest_cpu = cpumask_first(sched_group_span(idlest)); 12835 if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid) 12836 return idlest; 12837 #endif /* CONFIG_NUMA_BALANCING */ 12838 /* 12839 * Otherwise, keep the task close to the wakeup source 12840 * and improve locality if the number of running tasks 12841 * would remain below threshold where an imbalance is 12842 * allowed while accounting for the possibility the 12843 * task is pinned to a subset of CPUs. If there is a 12844 * real need of migration, periodic load balance will 12845 * take care of it. 12846 */ 12847 if (p->nr_cpus_allowed != NR_CPUS) { 12848 unsigned int w = cpumask_weight_and(p->cpus_ptr, 12849 sched_group_span(local)); 12850 imb_numa_nr = min(w, sd->imb_numa_nr); 12851 } 12852 12853 imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus); 12854 if (!adjust_numa_imbalance(imbalance, 12855 local_sgs.sum_nr_running + 1, 12856 imb_numa_nr)) { 12857 return NULL; 12858 } 12859 } 12860 #endif /* CONFIG_NUMA */ 12861 12862 /* 12863 * Select group with highest number of idle CPUs. We could also 12864 * compare the utilization which is more stable but it can end 12865 * up that the group has less spare capacity but finally more 12866 * idle CPUs which means more opportunity to run task. 12867 */ 12868 if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus) 12869 return NULL; 12870 break; 12871 } 12872 12873 return idlest; 12874 } 12875 12876 static void update_idle_cpu_scan(struct lb_env *env, 12877 unsigned long sum_util) 12878 { 12879 struct sched_domain_shared *sd_share; 12880 struct sched_domain *sd = env->sd; 12881 int llc_weight, pct; 12882 u64 x, y, tmp; 12883 /* 12884 * Update the number of CPUs to scan in LLC domain, which could 12885 * be used as a hint in select_idle_cpu(). The update of sd_share 12886 * could be expensive because it is within a shared cache line. 12887 * So the write of this hint only occurs during periodic load 12888 * balancing, rather than CPU_NEWLY_IDLE, because the latter 12889 * can fire way more frequently than the former. 12890 */ 12891 if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE) 12892 return; 12893 12894 sd_share = sd->shared; 12895 if (!sd_share) 12896 return; 12897 12898 /* 12899 * The number of CPUs to search drops as sum_util increases, when 12900 * sum_util hits 85% or above, the scan stops. 12901 * The reason to choose 85% as the threshold is because this is the 12902 * imbalance_pct(117) when a LLC sched group is overloaded. 12903 * 12904 * let y = SCHED_CAPACITY_SCALE - p * x^2 [1] 12905 * and y'= y / SCHED_CAPACITY_SCALE 12906 * 12907 * x is the ratio of sum_util compared to the CPU capacity: 12908 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE) 12909 * y' is the ratio of CPUs to be scanned in the LLC domain, 12910 * and the number of CPUs to scan is calculated by: 12911 * 12912 * nr_scan = llc_weight * y' [2] 12913 * 12914 * When x hits the threshold of overloaded, AKA, when 12915 * x = 100 / pct, y drops to 0. According to [1], 12916 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000 12917 * 12918 * Scale x by SCHED_CAPACITY_SCALE: 12919 * x' = sum_util / llc_weight; [3] 12920 * 12921 * and finally [1] becomes: 12922 * y = SCHED_CAPACITY_SCALE - 12923 * x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE) [4] 12924 * 12925 */ 12926 /* equation [3] */ 12927 x = sum_util; 12928 llc_weight = sd->span_weight; 12929 do_div(x, llc_weight); 12930 12931 /* equation [4] */ 12932 pct = sd->imbalance_pct; 12933 tmp = x * x * pct * pct; 12934 do_div(tmp, 10000 * SCHED_CAPACITY_SCALE); 12935 tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE); 12936 y = SCHED_CAPACITY_SCALE - tmp; 12937 12938 /* equation [2] */ 12939 y *= llc_weight; 12940 do_div(y, SCHED_CAPACITY_SCALE); 12941 if ((int)y != sd_share->nr_idle_scan) 12942 WRITE_ONCE(sd_share->nr_idle_scan, (int)y); 12943 } 12944 12945 /** 12946 * update_sd_lb_stats - Update sched_domain's statistics for load balancing. 12947 * @env: The load balancing environment. 12948 * @sds: variable to hold the statistics for this sched_domain. 12949 */ 12950 12951 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds) 12952 { 12953 struct sched_group *sg = env->sd->groups; 12954 struct sg_lb_stats *local = &sds->local_stat; 12955 struct sg_lb_stats tmp_sgs; 12956 unsigned long sum_util = 0; 12957 bool sg_overloaded = 0, sg_overutilized = 0; 12958 12959 env->dst_core_idle = !sched_smt_active() || is_core_idle(env->dst_cpu); 12960 12961 do { 12962 struct sg_lb_stats *sgs = &tmp_sgs; 12963 int local_group; 12964 12965 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg)); 12966 if (local_group) { 12967 sds->local = sg; 12968 sgs = local; 12969 12970 if (env->idle != CPU_NEWLY_IDLE || 12971 time_after_eq(jiffies, sg->sgc->next_update)) 12972 update_group_capacity(env->sd, env->dst_cpu); 12973 } 12974 12975 update_sg_lb_stats(env, sds, sg, sgs, &sg_overloaded); 12976 12977 if (!local_group && update_sd_pick_busiest(env, sds, sg, sgs)) { 12978 sds->busiest = sg; 12979 sds->busiest_stat = *sgs; 12980 } 12981 12982 sg_overutilized |= sgs->group_overutilized; 12983 12984 /* Now, start updating sd_lb_stats */ 12985 sds->total_load += sgs->group_load; 12986 sds->total_capacity += sgs->group_capacity; 12987 12988 sum_util += sgs->group_util; 12989 sg = sg->next; 12990 } while (sg != env->sd->groups); 12991 12992 /* 12993 * Indicate that the child domain of the busiest group prefers tasks 12994 * go to a child's sibling domains first. NB the flags of a sched group 12995 * are those of the child domain. 12996 */ 12997 if (sds->busiest) 12998 sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING); 12999 13000 13001 if (env->sd->flags & SD_NUMA) 13002 env->fbq_type = fbq_classify_group(&sds->busiest_stat); 13003 13004 if (!env->sd->parent) { 13005 /* update overload indicator if we are at root domain */ 13006 set_rd_overloaded(env->dst_rq->rd, sg_overloaded); 13007 13008 /* Update over-utilization (tipping point, U >= 0) indicator */ 13009 set_rd_overutilized(env->dst_rq->rd, sg_overutilized); 13010 } else if (sg_overutilized) { 13011 set_rd_overutilized(env->dst_rq->rd, sg_overutilized); 13012 } 13013 13014 update_idle_cpu_scan(env, sum_util); 13015 } 13016 13017 /** 13018 * calculate_imbalance - Calculate the amount of imbalance present within the 13019 * groups of a given sched_domain during load balance. 13020 * @env: load balance environment 13021 * @sds: statistics of the sched_domain whose imbalance is to be calculated. 13022 */ 13023 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds) 13024 { 13025 struct sg_lb_stats *local, *busiest; 13026 13027 local = &sds->local_stat; 13028 busiest = &sds->busiest_stat; 13029 13030 if (busiest->group_type == group_misfit_task) { 13031 if (env->sd->flags & SD_ASYM_CPUCAPACITY) { 13032 /* Set imbalance to allow misfit tasks to be balanced. */ 13033 env->migration_type = migrate_misfit; 13034 env->imbalance = 1; 13035 } else { 13036 /* 13037 * Set load imbalance to allow moving task from cpu 13038 * with reduced capacity. 13039 */ 13040 env->migration_type = migrate_load; 13041 env->imbalance = busiest->group_misfit_task_load; 13042 } 13043 return; 13044 } 13045 13046 if (busiest->group_type == group_asym_packing) { 13047 /* 13048 * In case of asym capacity, we will try to migrate all load to 13049 * the preferred CPU. 13050 */ 13051 env->migration_type = migrate_task; 13052 env->imbalance = busiest->sum_h_nr_running; 13053 return; 13054 } 13055 13056 if (busiest->group_type == group_smt_balance) { 13057 /* Reduce number of tasks sharing CPU capacity */ 13058 env->migration_type = migrate_task; 13059 env->imbalance = 1; 13060 return; 13061 } 13062 13063 #ifdef CONFIG_SCHED_CACHE 13064 if (busiest->group_type == group_llc_balance) { 13065 /* Move a task that prefer local LLC */ 13066 env->migration_type = migrate_llc_task; 13067 env->imbalance = 1; 13068 return; 13069 } 13070 #endif 13071 13072 if (busiest->group_type == group_imbalanced) { 13073 /* 13074 * In the group_imb case we cannot rely on group-wide averages 13075 * to ensure CPU-load equilibrium, try to move any task to fix 13076 * the imbalance. The next load balance will take care of 13077 * balancing back the system. 13078 */ 13079 env->migration_type = migrate_task; 13080 env->imbalance = 1; 13081 return; 13082 } 13083 13084 /* 13085 * Try to use spare capacity of local group without overloading it or 13086 * emptying busiest. 13087 */ 13088 if (local->group_type == group_has_spare) { 13089 if ((busiest->group_type > group_fully_busy) && 13090 !(env->sd->flags & SD_SHARE_LLC)) { 13091 /* 13092 * If busiest is overloaded, try to fill spare 13093 * capacity. This might end up creating spare capacity 13094 * in busiest or busiest still being overloaded but 13095 * there is no simple way to directly compute the 13096 * amount of load to migrate in order to balance the 13097 * system. 13098 */ 13099 env->migration_type = migrate_util; 13100 env->imbalance = max(local->group_capacity, local->group_util) - 13101 local->group_util; 13102 13103 /* 13104 * In some cases, the group's utilization is max or even 13105 * higher than capacity because of migrations but the 13106 * local CPU is (newly) idle. There is at least one 13107 * waiting task in this overloaded busiest group. Let's 13108 * try to pull it. 13109 */ 13110 if (env->idle && env->imbalance == 0) { 13111 env->migration_type = migrate_task; 13112 env->imbalance = 1; 13113 } 13114 13115 return; 13116 } 13117 13118 if (busiest->group_weight == 1 || sds->prefer_sibling) { 13119 /* 13120 * When prefer sibling, evenly spread running tasks on 13121 * groups. 13122 */ 13123 env->migration_type = migrate_task; 13124 env->imbalance = sibling_imbalance(env, sds, busiest, local); 13125 } else { 13126 13127 /* 13128 * If there is no overload, we just want to even the number of 13129 * idle CPUs. 13130 */ 13131 env->migration_type = migrate_task; 13132 env->imbalance = max_t(long, 0, 13133 (local->idle_cpus - busiest->idle_cpus)); 13134 } 13135 13136 #ifdef CONFIG_NUMA 13137 /* Consider allowing a small imbalance between NUMA groups */ 13138 if (env->sd->flags & SD_NUMA) { 13139 env->imbalance = adjust_numa_imbalance(env->imbalance, 13140 local->sum_nr_running + 1, 13141 env->sd->imb_numa_nr); 13142 } 13143 #endif 13144 13145 /* Number of tasks to move to restore balance */ 13146 env->imbalance >>= 1; 13147 13148 return; 13149 } 13150 13151 /* 13152 * Local is fully busy but has to take more load to relieve the 13153 * busiest group 13154 */ 13155 if (local->group_type < group_overloaded) { 13156 /* 13157 * Local will become overloaded so the avg_load metrics are 13158 * finally needed. 13159 */ 13160 13161 local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) / 13162 local->group_capacity; 13163 13164 /* 13165 * If the local group is more loaded than the selected 13166 * busiest group don't try to pull any tasks. 13167 */ 13168 if (local->avg_load >= busiest->avg_load) { 13169 env->imbalance = 0; 13170 return; 13171 } 13172 13173 sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) / 13174 sds->total_capacity; 13175 13176 /* 13177 * If the local group is more loaded than the average system 13178 * load, don't try to pull any tasks. 13179 */ 13180 if (local->avg_load >= sds->avg_load) { 13181 env->imbalance = 0; 13182 return; 13183 } 13184 13185 } 13186 13187 /* 13188 * Both group are or will become overloaded and we're trying to get all 13189 * the CPUs to the average_load, so we don't want to push ourselves 13190 * above the average load, nor do we wish to reduce the max loaded CPU 13191 * below the average load. At the same time, we also don't want to 13192 * reduce the group load below the group capacity. Thus we look for 13193 * the minimum possible imbalance. 13194 */ 13195 env->migration_type = migrate_load; 13196 env->imbalance = min( 13197 (busiest->avg_load - sds->avg_load) * busiest->group_capacity, 13198 (sds->avg_load - local->avg_load) * local->group_capacity 13199 ) / SCHED_CAPACITY_SCALE; 13200 } 13201 13202 /******* sched_balance_find_src_group() helpers end here *********************/ 13203 13204 /* 13205 * Decision matrix according to the local and busiest group type: 13206 * 13207 * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded 13208 * has_spare nr_idle balanced N/A N/A balanced balanced 13209 * fully_busy nr_idle nr_idle N/A N/A balanced balanced 13210 * misfit_task force N/A N/A N/A N/A N/A 13211 * asym_packing force force N/A N/A force force 13212 * imbalanced force force N/A N/A force force 13213 * overloaded force force N/A N/A force avg_load 13214 * 13215 * N/A : Not Applicable because already filtered while updating 13216 * statistics. 13217 * balanced : The system is balanced for these 2 groups. 13218 * force : Calculate the imbalance as load migration is probably needed. 13219 * avg_load : Only if imbalance is significant enough. 13220 * nr_idle : dst_cpu is not busy and the number of idle CPUs is quite 13221 * different in groups. 13222 */ 13223 13224 /** 13225 * sched_balance_find_src_group - Returns the busiest group within the sched_domain 13226 * if there is an imbalance. 13227 * @env: The load balancing environment. 13228 * 13229 * Also calculates the amount of runnable load which should be moved 13230 * to restore balance. 13231 * 13232 * Return: - The busiest group if imbalance exists. 13233 */ 13234 static struct sched_group *sched_balance_find_src_group(struct lb_env *env) 13235 { 13236 struct sg_lb_stats *local, *busiest; 13237 struct sd_lb_stats sds; 13238 13239 init_sd_lb_stats(&sds); 13240 13241 /* 13242 * Compute the various statistics relevant for load balancing at 13243 * this level. 13244 */ 13245 update_sd_lb_stats(env, &sds); 13246 13247 /* There is no busy sibling group to pull tasks from */ 13248 if (!sds.busiest) 13249 goto out_balanced; 13250 13251 busiest = &sds.busiest_stat; 13252 13253 /* Misfit tasks should be dealt with regardless of the avg load */ 13254 if (busiest->group_type == group_misfit_task) 13255 goto force_balance; 13256 13257 if (!is_rd_overutilized(env->dst_rq->rd) && 13258 rcu_dereference_all(env->dst_rq->rd->pd)) 13259 goto out_balanced; 13260 13261 /* ASYM feature bypasses nice load balance check */ 13262 if (busiest->group_type == group_asym_packing) 13263 goto force_balance; 13264 13265 /* 13266 * If the busiest group is imbalanced the below checks don't 13267 * work because they assume all things are equal, which typically 13268 * isn't true due to cpus_ptr constraints and the like. 13269 */ 13270 if (busiest->group_type == group_imbalanced) 13271 goto force_balance; 13272 13273 local = &sds.local_stat; 13274 /* 13275 * If the local group is busier than the selected busiest group 13276 * don't try and pull any tasks. 13277 */ 13278 if (local->group_type > busiest->group_type) 13279 goto out_balanced; 13280 13281 /* 13282 * When groups are overloaded, use the avg_load to ensure fairness 13283 * between tasks. 13284 */ 13285 if (local->group_type == group_overloaded) { 13286 /* 13287 * If the local group is more loaded than the selected 13288 * busiest group don't try to pull any tasks. 13289 */ 13290 if (local->avg_load >= busiest->avg_load) 13291 goto out_balanced; 13292 13293 /* XXX broken for overlapping NUMA groups */ 13294 sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) / 13295 sds.total_capacity; 13296 13297 /* 13298 * Don't pull any tasks if this group is already above the 13299 * domain average load. 13300 */ 13301 if (local->avg_load >= sds.avg_load) 13302 goto out_balanced; 13303 13304 /* 13305 * If the busiest group is more loaded, use imbalance_pct to be 13306 * conservative. 13307 */ 13308 if (100 * busiest->avg_load <= 13309 env->sd->imbalance_pct * local->avg_load) 13310 goto out_balanced; 13311 } 13312 13313 /* 13314 * Try to move all excess tasks to a sibling domain of the busiest 13315 * group's child domain. 13316 */ 13317 if (sds.prefer_sibling && local->group_type == group_has_spare && 13318 (busiest->group_type == group_llc_balance || 13319 sibling_imbalance(env, &sds, busiest, local) > 1)) 13320 goto force_balance; 13321 13322 if (busiest->group_type != group_overloaded) { 13323 if (!env->idle) { 13324 /* 13325 * If the busiest group is not overloaded (and as a 13326 * result the local one too) but this CPU is already 13327 * busy, let another idle CPU try to pull task. 13328 */ 13329 goto out_balanced; 13330 } 13331 13332 if (busiest->group_type == group_smt_balance && 13333 smt_vs_nonsmt_groups(sds.local, sds.busiest)) { 13334 /* Let non SMT CPU pull from SMT CPU sharing with sibling */ 13335 goto force_balance; 13336 } 13337 13338 if (busiest->group_weight > 1 && 13339 local->idle_cpus <= (busiest->idle_cpus + 1)) { 13340 /* 13341 * If the busiest group is not overloaded 13342 * and there is no imbalance between this and busiest 13343 * group wrt idle CPUs, it is balanced. The imbalance 13344 * becomes significant if the diff is greater than 1 13345 * otherwise we might end up to just move the imbalance 13346 * on another group. Of course this applies only if 13347 * there is more than 1 CPU per group. 13348 */ 13349 goto out_balanced; 13350 } 13351 13352 if (busiest->sum_h_nr_running == 1) { 13353 /* 13354 * busiest doesn't have any tasks waiting to run 13355 */ 13356 goto out_balanced; 13357 } 13358 } 13359 13360 force_balance: 13361 /* Looks like there is an imbalance. Compute it */ 13362 calculate_imbalance(env, &sds); 13363 return env->imbalance ? sds.busiest : NULL; 13364 13365 out_balanced: 13366 env->imbalance = 0; 13367 return NULL; 13368 } 13369 13370 /* 13371 * sched_balance_find_src_rq - find the busiest runqueue among the CPUs in the group. 13372 */ 13373 static struct rq *sched_balance_find_src_rq(struct lb_env *env, 13374 struct sched_group *group) 13375 { 13376 struct rq *busiest = NULL, *rq; 13377 unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1; 13378 unsigned int __maybe_unused busiest_pref_llc = 0; 13379 struct sched_domain __maybe_unused *sd_tmp; 13380 unsigned int busiest_nr = 0; 13381 int __maybe_unused dst_llc; 13382 int i; 13383 13384 for_each_cpu_and(i, sched_group_span(group), env->cpus) { 13385 unsigned long capacity, load, util; 13386 unsigned int nr_running; 13387 enum fbq_type rt; 13388 13389 rq = cpu_rq(i); 13390 rt = fbq_classify_rq(rq); 13391 13392 /* 13393 * We classify groups/runqueues into three groups: 13394 * - regular: there are !numa tasks 13395 * - remote: there are numa tasks that run on the 'wrong' node 13396 * - all: there is no distinction 13397 * 13398 * In order to avoid migrating ideally placed numa tasks, 13399 * ignore those when there's better options. 13400 * 13401 * If we ignore the actual busiest queue to migrate another 13402 * task, the next balance pass can still reduce the busiest 13403 * queue by moving tasks around inside the node. 13404 * 13405 * If we cannot move enough load due to this classification 13406 * the next pass will adjust the group classification and 13407 * allow migration of more tasks. 13408 * 13409 * Both cases only affect the total convergence complexity. 13410 */ 13411 if (rt > env->fbq_type) 13412 continue; 13413 13414 nr_running = rq->cfs.h_nr_runnable; 13415 if (!nr_running) 13416 continue; 13417 13418 capacity = capacity_of(i); 13419 13420 /* 13421 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could 13422 * eventually lead to active_balancing high->low capacity. 13423 * Higher per-CPU capacity is considered better than balancing 13424 * average load. 13425 */ 13426 if (env->sd->flags & SD_ASYM_CPUCAPACITY && 13427 nr_running == 1) { 13428 bool cluster_equal_cap = static_branch_unlikely(&sched_cluster_active) && 13429 (get_actual_cpu_capacity(env->dst_cpu) == 13430 get_actual_cpu_capacity(i)); 13431 bool smt_degraded_cap = sched_smt_active() && !is_core_idle(i); 13432 13433 /* 13434 * Busy SMT siblings reduce the capacity of CPU @i. Do 13435 * not skip it in this case. 13436 * 13437 * CONFIG_SCHED_CLUSTER requires balancing load across 13438 * clusters of identical capacity, accounting for 13439 * hardware and cpufreq pressure. 13440 */ 13441 if (!smt_degraded_cap && !cluster_equal_cap && 13442 !capacity_greater(capacity_of(env->dst_cpu), capacity)) 13443 continue; 13444 } 13445 13446 /* 13447 * Make sure we only pull tasks from a CPU of lower priority 13448 * when balancing between SMT siblings. 13449 * 13450 * If balancing between cores, let lower priority CPUs help 13451 * SMT cores with more than one busy sibling. 13452 */ 13453 if (sched_asym(env->sd, i, env->dst_cpu) && nr_running == 1) 13454 continue; 13455 13456 switch (env->migration_type) { 13457 case migrate_load: 13458 /* 13459 * When comparing with load imbalance, use cpu_load() 13460 * which is not scaled with the CPU capacity. 13461 */ 13462 load = cpu_load(rq); 13463 13464 if (nr_running == 1 && load > env->imbalance && 13465 !check_cpu_capacity(rq, env->sd)) 13466 break; 13467 13468 /* 13469 * For the load comparisons with the other CPUs, 13470 * consider the cpu_load() scaled with the CPU 13471 * capacity, so that the load can be moved away 13472 * from the CPU that is potentially running at a 13473 * lower capacity. 13474 * 13475 * Thus we're looking for max(load_i / capacity_i), 13476 * crosswise multiplication to rid ourselves of the 13477 * division works out to: 13478 * load_i * capacity_j > load_j * capacity_i; 13479 * where j is our previous maximum. 13480 */ 13481 if (load * busiest_capacity > busiest_load * capacity) { 13482 busiest_load = load; 13483 busiest_capacity = capacity; 13484 busiest = rq; 13485 } 13486 break; 13487 13488 case migrate_util: 13489 util = cpu_util_cfs_boost(i); 13490 13491 /* 13492 * Don't try to pull utilization from a CPU with one 13493 * running task. Whatever its utilization, we will fail 13494 * detach the task. 13495 */ 13496 if (nr_running <= 1) 13497 continue; 13498 13499 if (busiest_util < util) { 13500 busiest_util = util; 13501 busiest = rq; 13502 } 13503 break; 13504 13505 case migrate_task: 13506 if (busiest_nr < nr_running) { 13507 busiest_nr = nr_running; 13508 busiest = rq; 13509 } 13510 break; 13511 13512 case migrate_misfit: 13513 /* 13514 * For ASYM_CPUCAPACITY domains with misfit tasks we 13515 * simply seek the "biggest" misfit task. 13516 */ 13517 if (rq->misfit_task_load > busiest_load) { 13518 busiest_load = rq->misfit_task_load; 13519 busiest = rq; 13520 } 13521 13522 break; 13523 13524 case migrate_llc_task: 13525 #ifdef CONFIG_SCHED_CACHE 13526 sd_tmp = rcu_dereference_all(rq->sd); 13527 dst_llc = llc_id(env->dst_cpu); 13528 13529 if (sd_tmp && (unsigned)dst_llc < sd_tmp->llc_max) { 13530 unsigned int this_pref_llc = 13531 sd_tmp->llc_counts[dst_llc]; 13532 13533 if (busiest_pref_llc < this_pref_llc) { 13534 busiest_pref_llc = this_pref_llc; 13535 busiest = rq; 13536 } 13537 } 13538 #endif 13539 break; 13540 13541 } 13542 } 13543 13544 return busiest; 13545 } 13546 13547 /* 13548 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but 13549 * so long as it is large enough. 13550 */ 13551 #define MAX_PINNED_INTERVAL 512 13552 13553 static inline bool 13554 asym_active_balance(struct lb_env *env) 13555 { 13556 /* 13557 * ASYM_PACKING needs to force migrate tasks from busy but lower 13558 * priority CPUs in order to pack all tasks in the highest priority 13559 * CPUs. When done between cores, do it only if the whole core if the 13560 * whole core is idle. 13561 * 13562 * If @env::src_cpu is an SMT core with busy siblings, let 13563 * the lower priority @env::dst_cpu help it. Do not follow 13564 * CPU priority. 13565 */ 13566 return env->idle && sched_use_asym_prio(env->sd, env->dst_cpu) && 13567 (sched_asym_prefer(env->dst_cpu, env->src_cpu) || 13568 !sched_use_asym_prio(env->sd, env->src_cpu)); 13569 } 13570 13571 static inline bool 13572 imbalanced_active_balance(struct lb_env *env) 13573 { 13574 struct sched_domain *sd = env->sd; 13575 13576 /* 13577 * The imbalanced case includes the case of pinned tasks preventing a fair 13578 * distribution of the load on the system but also the even distribution of the 13579 * threads on a system with spare capacity 13580 */ 13581 if ((env->migration_type == migrate_task) && 13582 (sd->nr_balance_failed > sd->cache_nice_tries+2)) 13583 return 1; 13584 13585 return 0; 13586 } 13587 13588 static int need_active_balance(struct lb_env *env) 13589 { 13590 struct sched_domain *sd = env->sd; 13591 13592 if (asym_active_balance(env)) 13593 return 1; 13594 13595 if (alb_break_llc(env)) 13596 return 0; 13597 13598 if (imbalanced_active_balance(env)) 13599 return 1; 13600 13601 /* 13602 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task. 13603 * It's worth migrating the task if the src_cpu's capacity is reduced 13604 * because of other sched_class or IRQs if more capacity stays 13605 * available on dst_cpu. 13606 */ 13607 if (env->idle && 13608 (env->src_rq->cfs.h_nr_runnable == 1)) { 13609 if ((check_cpu_capacity(env->src_rq, sd)) && 13610 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100)) 13611 return 1; 13612 } 13613 13614 if (env->migration_type == migrate_misfit || 13615 env->migration_type == migrate_llc_task) 13616 return 1; 13617 13618 return 0; 13619 } 13620 13621 static int active_load_balance_cpu_stop(void *data); 13622 static int active_load_balance_llc_cpu_stop(void *data); 13623 13624 /* 13625 * migration_type is checked elsewhere to decide migration policy, so 13626 * it shouldn't be repurposed just to flag an LLC-directed active 13627 * balance across the stopper. Pick the callback here instead. 13628 */ 13629 static inline cpu_stop_fn_t alb_stop_fn(struct lb_env *env) 13630 { 13631 if (env->migration_type == migrate_llc_task) 13632 return active_load_balance_llc_cpu_stop; 13633 13634 return active_load_balance_cpu_stop; 13635 } 13636 13637 static int should_we_balance(struct lb_env *env) 13638 { 13639 struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask); 13640 struct sched_group *sg = env->sd->groups; 13641 int cpu, idle_smt = -1; 13642 13643 /* 13644 * Ensure the balancing environment is consistent; can happen 13645 * when the softirq triggers 'during' hotplug. 13646 */ 13647 if (!cpumask_test_cpu(env->dst_cpu, env->cpus)) 13648 return 0; 13649 13650 /* 13651 * In the newly idle case, we will allow all the CPUs 13652 * to do the newly idle load balance. 13653 * 13654 * However, we bail out if we already have tasks or a wakeup pending, 13655 * to optimize wakeup latency. 13656 */ 13657 if (env->idle == CPU_NEWLY_IDLE) { 13658 if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending) 13659 return 0; 13660 return 1; 13661 } 13662 13663 cpumask_copy(swb_cpus, group_balance_mask(sg)); 13664 /* Try to find first idle CPU */ 13665 for_each_cpu_and(cpu, swb_cpus, env->cpus) { 13666 if (!idle_cpu(cpu)) 13667 continue; 13668 13669 /* 13670 * Don't balance to idle SMT in busy core right away when 13671 * balancing cores, but remember the first idle SMT CPU for 13672 * later consideration. Find CPU on an idle core first. 13673 */ 13674 if (sched_smt_active() && 13675 !(env->sd->flags & SD_SHARE_CPUCAPACITY) && 13676 !is_core_idle(cpu)) { 13677 if (idle_smt == -1) 13678 idle_smt = cpu; 13679 /* 13680 * If the core is not idle, and first SMT sibling which is 13681 * idle has been found, then its not needed to check other 13682 * SMT siblings for idleness: 13683 */ 13684 cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu)); 13685 continue; 13686 } 13687 13688 /* 13689 * Are we the first idle core in a non-SMT domain or higher, 13690 * or the first idle CPU in a SMT domain? 13691 */ 13692 return cpu == env->dst_cpu; 13693 } 13694 13695 /* Are we the first idle CPU with busy siblings? */ 13696 if (idle_smt != -1) 13697 return idle_smt == env->dst_cpu; 13698 13699 /* Are we the first CPU of this group ? */ 13700 return group_balance_cpu(sg) == env->dst_cpu; 13701 } 13702 13703 static void update_lb_imbalance_stat(struct lb_env *env, struct sched_domain *sd, 13704 enum cpu_idle_type idle) 13705 { 13706 if (!schedstat_enabled()) 13707 return; 13708 13709 switch (env->migration_type) { 13710 case migrate_load: 13711 __schedstat_add(sd->lb_imbalance_load[idle], env->imbalance); 13712 break; 13713 case migrate_util: 13714 __schedstat_add(sd->lb_imbalance_util[idle], env->imbalance); 13715 break; 13716 case migrate_task: 13717 __schedstat_add(sd->lb_imbalance_task[idle], env->imbalance); 13718 break; 13719 case migrate_misfit: 13720 __schedstat_add(sd->lb_imbalance_misfit[idle], env->imbalance); 13721 break; 13722 case migrate_llc_task: 13723 break; 13724 } 13725 } 13726 13727 /* 13728 * This flag serializes load-balancing passes over large domains 13729 * (above the NODE topology level) - only one load-balancing instance 13730 * may run at a time, to reduce overhead on very large systems with 13731 * lots of CPUs and large NUMA distances. 13732 * 13733 * - Note that load-balancing passes triggered while another one 13734 * is executing are skipped and not re-tried. 13735 * 13736 * - Also note that this does not serialize rebalance_domains() 13737 * execution, as non-SD_SERIALIZE domains will still be 13738 * load-balanced in parallel. 13739 */ 13740 static atomic_t sched_balance_running = ATOMIC_INIT(0); 13741 13742 /* 13743 * Check this_cpu to ensure it is balanced within domain. Attempt to move 13744 * tasks if there is an imbalance. 13745 */ 13746 static int sched_balance_rq(int this_cpu, struct rq *this_rq, 13747 struct sched_domain *sd, enum cpu_idle_type idle, 13748 int *continue_balancing) 13749 { 13750 int ld_moved, cur_ld_moved, active_balance = 0; 13751 struct sched_domain *sd_parent = sd->parent; 13752 struct sched_group *group; 13753 struct rq *busiest; 13754 struct rq_flags rf; 13755 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask); 13756 struct lb_env env = { 13757 .sd = sd, 13758 .dst_cpu = this_cpu, 13759 .dst_rq = this_rq, 13760 .dst_grpmask = group_balance_mask(sd->groups), 13761 .idle = idle, 13762 .loop_break = SCHED_NR_MIGRATE_BREAK, 13763 .cpus = cpus, 13764 .fbq_type = all, 13765 .tasks = LIST_HEAD_INIT(env.tasks), 13766 }; 13767 bool need_unlock = false; 13768 13769 cpumask_and(cpus, sched_domain_span(sd), cpu_preferred_mask); 13770 13771 schedstat_inc(sd->lb_count[idle]); 13772 13773 redo: 13774 if (!should_we_balance(&env)) { 13775 *continue_balancing = 0; 13776 goto out_balanced; 13777 } 13778 13779 if (!need_unlock && (sd->flags & SD_SERIALIZE)) { 13780 int zero = 0; 13781 if (!atomic_try_cmpxchg_acquire(&sched_balance_running, &zero, 1)) 13782 goto out_balanced; 13783 13784 need_unlock = true; 13785 } 13786 13787 group = sched_balance_find_src_group(&env); 13788 if (!group) { 13789 schedstat_inc(sd->lb_nobusyg[idle]); 13790 goto out_balanced; 13791 } 13792 13793 busiest = sched_balance_find_src_rq(&env, group); 13794 if (!busiest) { 13795 schedstat_inc(sd->lb_nobusyq[idle]); 13796 goto out_balanced; 13797 } 13798 13799 WARN_ON_ONCE(busiest == env.dst_rq); 13800 13801 update_lb_imbalance_stat(&env, sd, idle); 13802 13803 env.src_cpu = busiest->cpu; 13804 env.src_rq = busiest; 13805 13806 ld_moved = 0; 13807 /* Clear this flag as soon as we find a pullable task */ 13808 env.flags |= LBF_ALL_PINNED; 13809 if (busiest->nr_running > 1) { 13810 /* 13811 * Attempt to move tasks. If sched_balance_find_src_group has found 13812 * an imbalance but busiest->nr_running <= 1, the group is 13813 * still unbalanced. ld_moved simply stays zero, so it is 13814 * correctly treated as an imbalance. 13815 */ 13816 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running); 13817 13818 more_balance: 13819 rq_lock_irqsave(busiest, &rf); 13820 update_rq_clock(busiest); 13821 13822 /* 13823 * cur_ld_moved - load moved in current iteration 13824 * ld_moved - cumulative load moved across iterations 13825 */ 13826 cur_ld_moved = detach_tasks(&env); 13827 13828 /* 13829 * We've detached some tasks from busiest_rq. Every 13830 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely 13831 * unlock busiest->lock, and we are able to be sure 13832 * that nobody can manipulate the tasks in parallel. 13833 * See task_rq_lock() family for the details. 13834 */ 13835 13836 rq_unlock(busiest, &rf); 13837 13838 if (cur_ld_moved) { 13839 attach_tasks(&env); 13840 ld_moved += cur_ld_moved; 13841 } 13842 13843 local_irq_restore(rf.flags); 13844 13845 if (env.flags & LBF_NEED_BREAK) { 13846 env.flags &= ~LBF_NEED_BREAK; 13847 goto more_balance; 13848 } 13849 13850 /* 13851 * Revisit (affine) tasks on src_cpu that couldn't be moved to 13852 * us and move them to an alternate dst_cpu in our sched_group 13853 * where they can run. The upper limit on how many times we 13854 * iterate on same src_cpu is dependent on number of CPUs in our 13855 * sched_group. 13856 * 13857 * This changes load balance semantics a bit on who can move 13858 * load to a given_cpu. In addition to the given_cpu itself 13859 * (or a ilb_cpu acting on its behalf where given_cpu is 13860 * nohz-idle), we now have balance_cpu in a position to move 13861 * load to given_cpu. In rare situations, this may cause 13862 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding 13863 * _independently_ and at _same_ time to move some load to 13864 * given_cpu) causing excess load to be moved to given_cpu. 13865 * This however should not happen so much in practice and 13866 * moreover subsequent load balance cycles should correct the 13867 * excess load moved. 13868 */ 13869 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) { 13870 13871 /* Prevent to re-select dst_cpu via env's CPUs */ 13872 __cpumask_clear_cpu(env.dst_cpu, env.cpus); 13873 13874 env.dst_rq = cpu_rq(env.new_dst_cpu); 13875 env.dst_cpu = env.new_dst_cpu; 13876 env.flags &= ~LBF_DST_PINNED; 13877 env.loop = 0; 13878 env.loop_break = SCHED_NR_MIGRATE_BREAK; 13879 13880 /* 13881 * Go back to "more_balance" rather than "redo" since we 13882 * need to continue with same src_cpu. 13883 */ 13884 goto more_balance; 13885 } 13886 13887 /* 13888 * We failed to reach balance because of affinity. 13889 */ 13890 if (sd_parent) { 13891 int *group_imbalance = &sd_parent->groups->sgc->imbalance; 13892 13893 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0) 13894 *group_imbalance = 1; 13895 } 13896 13897 /* All tasks on this runqueue were pinned by CPU affinity */ 13898 if (unlikely(env.flags & LBF_ALL_PINNED)) { 13899 __cpumask_clear_cpu(cpu_of(busiest), cpus); 13900 /* 13901 * Attempting to continue load balancing at the current 13902 * sched_domain level only makes sense if there are 13903 * active CPUs remaining as possible busiest CPUs to 13904 * pull load from which are not contained within the 13905 * destination group that is receiving any migrated 13906 * load. 13907 */ 13908 if (!cpumask_subset(cpus, env.dst_grpmask)) { 13909 env.loop = 0; 13910 env.loop_break = SCHED_NR_MIGRATE_BREAK; 13911 goto redo; 13912 } 13913 goto out_all_pinned; 13914 } 13915 } 13916 13917 if (ld_moved) { 13918 sd->nr_balance_failed = 0; 13919 goto out_unbalanced; 13920 } 13921 13922 schedstat_inc(sd->lb_failed[idle]); 13923 /* 13924 * Increment the failure counter only on periodic balance. 13925 * We do not want newidle balance, which can be very 13926 * frequent, pollute the failure counter causing 13927 * excessive cache_hot migrations and active balances. 13928 * 13929 * Similarly for migration_misfit which is not related to 13930 * load/util migration, don't pollute nr_balance_failed. 13931 * 13932 * The same for cache aware scheduling's allowance for 13933 * load imbalance. If regular load balance does not 13934 * migrate task due to LLC locality, it is a expected 13935 * behavior and don't pollute nr_balance_failed. 13936 * See can_migrate_task(). 13937 */ 13938 if (idle != CPU_NEWLY_IDLE && 13939 env.migration_type != migrate_misfit && 13940 !(env.flags & LBF_LLC_PINNED)) 13941 sd->nr_balance_failed++; 13942 13943 if (!need_active_balance(&env)) 13944 goto out_unbalanced; 13945 13946 scoped_guard (raw_spin_rq_lock_irqsave, busiest) { 13947 /* 13948 * Don't kick the active_load_balance_cpu_stop, 13949 * if the curr task on busiest CPU can't be 13950 * moved to this_cpu: 13951 */ 13952 if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) 13953 goto out_one_pinned; 13954 13955 /* Record that we found at least one task that could run on this_cpu */ 13956 env.flags &= ~LBF_ALL_PINNED; 13957 13958 /* 13959 * ->active_balance synchronizes accesses to 13960 * ->active_balance_work. Once set, it's cleared 13961 * only after active load balance is finished. 13962 */ 13963 if (busiest->active_balance) 13964 goto out_unbalanced; 13965 13966 /* 13967 * @busiest dropped its rq_lock in the middle of 13968 * scheduling out its ->curr task (->on_rq := 0), no 13969 * need to forcefully punt it away with active balance. 13970 */ 13971 if (!busiest->curr->on_rq) 13972 goto out_unbalanced; 13973 13974 busiest->active_balance = 1; 13975 busiest->push_cpu = this_cpu; 13976 active_balance = 1; 13977 preempt_disable(); 13978 } 13979 if (active_balance) { 13980 stop_one_cpu_nowait(cpu_of(busiest), 13981 alb_stop_fn(&env), busiest, 13982 &busiest->active_balance_work); 13983 } 13984 preempt_enable(); 13985 13986 out_unbalanced: 13987 /* We were unbalanced, so reset the balancing interval */ 13988 sd->balance_interval = sd->min_interval; 13989 goto out; 13990 13991 out_balanced: 13992 /* 13993 * We reach balance although we may have faced some affinity 13994 * constraints. Clear the imbalance flag only if other tasks got 13995 * a chance to move and fix the imbalance. 13996 */ 13997 if (sd_parent && !(env.flags & LBF_ALL_PINNED)) { 13998 int *group_imbalance = &sd_parent->groups->sgc->imbalance; 13999 14000 if (*group_imbalance) 14001 *group_imbalance = 0; 14002 } 14003 14004 out_all_pinned: 14005 /* 14006 * We reach balance because all tasks are pinned at this level so 14007 * we can't migrate them. Let the imbalance flag set so parent level 14008 * can try to migrate them. 14009 */ 14010 schedstat_inc(sd->lb_balanced[idle]); 14011 14012 sd->nr_balance_failed = 0; 14013 14014 out_one_pinned: 14015 ld_moved = 0; 14016 14017 /* 14018 * sched_balance_newidle() disregards balance intervals, so we could 14019 * repeatedly reach this code, which would lead to balance_interval 14020 * skyrocketing in a short amount of time. Skip the balance_interval 14021 * increase logic to avoid that. 14022 * 14023 * Similarly misfit migration which is not necessarily an indication of 14024 * the system being busy and requires lb to backoff to let it settle 14025 * down. 14026 */ 14027 if (env.idle == CPU_NEWLY_IDLE || 14028 env.migration_type == migrate_misfit) 14029 goto out; 14030 14031 /* tune up the balancing interval */ 14032 if ((env.flags & LBF_ALL_PINNED && 14033 sd->balance_interval < MAX_PINNED_INTERVAL) || 14034 sd->balance_interval < sd->max_interval) 14035 sd->balance_interval *= 2; 14036 out: 14037 if (need_unlock) 14038 atomic_set_release(&sched_balance_running, 0); 14039 14040 return ld_moved; 14041 } 14042 14043 static inline unsigned long 14044 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy) 14045 { 14046 unsigned long interval = sd->balance_interval; 14047 14048 if (cpu_busy) 14049 interval *= sd->busy_factor; 14050 14051 /* scale ms to jiffies */ 14052 interval = msecs_to_jiffies(interval); 14053 14054 /* 14055 * Reduce likelihood of busy balancing at higher domains racing with 14056 * balancing at lower domains by preventing their balancing periods 14057 * from being multiples of each other. 14058 */ 14059 if (cpu_busy) 14060 interval -= 1; 14061 14062 interval = clamp(interval, 1UL, max_load_balance_interval); 14063 14064 return interval; 14065 } 14066 14067 static inline void 14068 update_next_balance(struct sched_domain *sd, unsigned long *next_balance) 14069 { 14070 unsigned long interval, next; 14071 14072 /* used by idle balance, so cpu_busy = 0 */ 14073 interval = get_sd_balance_interval(sd, 0); 14074 next = sd->last_balance + interval; 14075 14076 if (time_after(*next_balance, next)) 14077 *next_balance = next; 14078 } 14079 14080 /* 14081 * active_load_balance_cpu_stop is run by the CPU stopper. It pushes 14082 * running tasks off the busiest CPU onto idle CPUs. It requires at 14083 * least 1 task to be running on each physical CPU where possible, and 14084 * avoids physical / logical imbalances. 14085 */ 14086 static int __active_load_balance_cpu_stop(void *data, unsigned int lb_flags) 14087 { 14088 struct rq *busiest_rq = data; 14089 int busiest_cpu = cpu_of(busiest_rq); 14090 int target_cpu = busiest_rq->push_cpu; 14091 struct rq *target_rq = cpu_rq(target_cpu); 14092 struct sched_domain *sd; 14093 struct task_struct *p = NULL; 14094 struct rq_flags rf; 14095 14096 rq_lock_irq(busiest_rq, &rf); 14097 /* 14098 * Between queueing the stop-work and running it is a hole in which 14099 * CPUs can become inactive. We should not move tasks from or to 14100 * inactive CPUs. 14101 */ 14102 if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu)) 14103 goto out_unlock; 14104 14105 /* Make sure the requested CPU hasn't gone down in the meantime: */ 14106 if (unlikely(busiest_cpu != smp_processor_id() || 14107 !busiest_rq->active_balance)) 14108 goto out_unlock; 14109 14110 /* Is there any task to move? */ 14111 if (busiest_rq->nr_running <= 1) 14112 goto out_unlock; 14113 14114 /* 14115 * This condition is "impossible", if it occurs 14116 * we need to fix it. Originally reported by 14117 * Bjorn Helgaas on a 128-CPU setup. 14118 */ 14119 WARN_ON_ONCE(busiest_rq == target_rq); 14120 14121 /* Search for an sd spanning us and the target CPU. */ 14122 rcu_read_lock(); 14123 for_each_domain(target_cpu, sd) { 14124 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd))) 14125 break; 14126 } 14127 14128 if (likely(sd)) { 14129 struct lb_env env = { 14130 .sd = sd, 14131 .dst_cpu = target_cpu, 14132 .dst_rq = target_rq, 14133 .src_cpu = busiest_rq->cpu, 14134 .src_rq = busiest_rq, 14135 .idle = CPU_IDLE, 14136 .flags = LBF_ACTIVE_LB | lb_flags, 14137 }; 14138 14139 schedstat_inc(sd->alb_count); 14140 update_rq_clock(busiest_rq); 14141 14142 p = detach_one_task(&env); 14143 if (p) { 14144 schedstat_inc(sd->alb_pushed); 14145 /* Active balancing done, reset the failure counter. */ 14146 sd->nr_balance_failed = 0; 14147 } else { 14148 schedstat_inc(sd->alb_failed); 14149 } 14150 } 14151 rcu_read_unlock(); 14152 out_unlock: 14153 busiest_rq->active_balance = 0; 14154 rq_unlock(busiest_rq, &rf); 14155 14156 if (p) 14157 attach_one_task(target_rq, p); 14158 14159 local_irq_enable(); 14160 14161 return 0; 14162 } 14163 14164 static int active_load_balance_cpu_stop(void *data) 14165 { 14166 return __active_load_balance_cpu_stop(data, 0); 14167 } 14168 14169 static int active_load_balance_llc_cpu_stop(void *data) 14170 { 14171 return __active_load_balance_cpu_stop(data, LBF_ACTIVE_LB_LLC); 14172 } 14173 14174 /* 14175 * Scale the max sched_balance_rq interval with the number of CPUs in the system. 14176 * This trades load-balance latency on larger machines for less cross talk. 14177 */ 14178 void update_max_interval(void) 14179 { 14180 max_load_balance_interval = HZ*num_online_cpus()/10; 14181 } 14182 14183 static inline void update_newidle_stats(struct sched_domain *sd, unsigned int success) 14184 { 14185 sd->newidle_call++; 14186 sd->newidle_success += success; 14187 14188 if (sd->newidle_call >= 1024) { 14189 u64 now = sched_clock(); 14190 s64 delta = now - sd->newidle_stamp; 14191 sd->newidle_stamp = now; 14192 int ratio = 0; 14193 14194 if (delta < 0) 14195 delta = 0; 14196 14197 if (sched_feat(NI_RATE)) { 14198 /* 14199 * ratio delta freq 14200 * 14201 * 1024 - 4 s - 128 Hz 14202 * 512 - 2 s - 256 Hz 14203 * 256 - 1 s - 512 Hz 14204 * 128 - .5 s - 1024 Hz 14205 * 64 - .25 s - 2048 Hz 14206 */ 14207 ratio = delta >> 22; 14208 } 14209 14210 ratio += sd->newidle_success; 14211 14212 sd->newidle_ratio = min(1024, ratio); 14213 sd->newidle_call /= 2; 14214 sd->newidle_success /= 2; 14215 } 14216 } 14217 14218 static inline bool 14219 update_newidle_cost(struct sched_domain *sd, u64 cost, unsigned int success) 14220 { 14221 unsigned long next_decay = sd->last_decay_max_lb_cost + HZ; 14222 unsigned long now = jiffies; 14223 14224 if (cost) 14225 update_newidle_stats(sd, success); 14226 14227 if (cost > sd->max_newidle_lb_cost) { 14228 /* 14229 * Track max cost of a domain to make sure to not delay the 14230 * next wakeup on the CPU. 14231 */ 14232 sd->max_newidle_lb_cost = cost; 14233 sd->last_decay_max_lb_cost = now; 14234 14235 } else if (time_after(now, next_decay)) { 14236 /* 14237 * Decay the newidle max times by ~1% per second to ensure that 14238 * it is not outdated and the current max cost is actually 14239 * shorter. 14240 */ 14241 sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256; 14242 sd->last_decay_max_lb_cost = now; 14243 return true; 14244 } 14245 14246 return false; 14247 } 14248 14249 /* 14250 * It checks each scheduling domain to see if it is due to be balanced, 14251 * and initiates a balancing operation if so. 14252 * 14253 * Balancing parameters are set up in init_sched_domains. 14254 */ 14255 static void sched_balance_domains(struct rq *rq, enum cpu_idle_type idle) 14256 { 14257 int continue_balancing = 1; 14258 int cpu = rq->cpu; 14259 int busy = idle != CPU_IDLE && !sched_idle_rq(rq); 14260 unsigned long interval; 14261 struct sched_domain *sd; 14262 /* Earliest time when we have to do rebalance again */ 14263 unsigned long next_balance = jiffies + 60*HZ; 14264 int update_next_balance = 0; 14265 int need_decay = 0; 14266 u64 max_cost = 0; 14267 14268 rcu_read_lock(); 14269 for_each_domain(cpu, sd) { 14270 /* 14271 * Decay the newidle max times here because this is a regular 14272 * visit to all the domains. 14273 */ 14274 need_decay = update_newidle_cost(sd, 0, 0); 14275 max_cost += sd->max_newidle_lb_cost; 14276 14277 /* 14278 * Stop the load balance at this level. There is another 14279 * CPU in our sched group which is doing load balancing more 14280 * actively. 14281 */ 14282 if (!continue_balancing) { 14283 if (need_decay) 14284 continue; 14285 break; 14286 } 14287 14288 interval = get_sd_balance_interval(sd, busy); 14289 if (time_after_eq(jiffies, sd->last_balance + interval)) { 14290 if (sched_balance_rq(cpu, rq, sd, idle, &continue_balancing)) { 14291 /* 14292 * The LBF_DST_PINNED logic could have changed 14293 * env->dst_cpu, so we can't know our idle 14294 * state even if we migrated tasks. Update it. 14295 */ 14296 idle = idle_cpu(cpu); 14297 busy = !idle && !sched_idle_rq(rq); 14298 } 14299 sd->last_balance = jiffies; 14300 interval = get_sd_balance_interval(sd, busy); 14301 } 14302 if (time_after(next_balance, sd->last_balance + interval)) { 14303 next_balance = sd->last_balance + interval; 14304 update_next_balance = 1; 14305 } 14306 } 14307 if (need_decay) { 14308 /* 14309 * Ensure the rq-wide value also decays but keep it at a 14310 * reasonable floor to avoid funnies with rq->avg_idle. 14311 */ 14312 rq->max_idle_balance_cost = 14313 max((u64)sysctl_sched_migration_cost, max_cost); 14314 } 14315 rcu_read_unlock(); 14316 14317 /* 14318 * next_balance will be updated only when there is a need. 14319 * When the cpu is attached to null domain for ex, it will not be 14320 * updated. 14321 */ 14322 if (likely(update_next_balance)) 14323 rq->next_balance = next_balance; 14324 14325 } 14326 14327 static inline int on_null_domain(struct rq *rq) 14328 { 14329 return unlikely(!rcu_dereference_sched(rq->sd)); 14330 } 14331 14332 #ifdef CONFIG_NO_HZ_COMMON 14333 /* 14334 * NOHZ idle load balancing (ILB) details: 14335 * 14336 * - When one of the busy CPUs notices that there may be an idle rebalancing 14337 * needed, they will kick the idle load balancer, which then does idle 14338 * load balancing for all the idle CPUs. 14339 */ 14340 static inline int find_new_ilb(void) 14341 { 14342 struct cpumask *ilb_cpus; 14343 int ilb_cpu, fallback = -1; 14344 14345 lockdep_assert_irqs_disabled(); 14346 14347 /* 14348 * Reuse the per-CPU select_rq_mask, which is protected from concurrent 14349 * use on this CPU by having interrupts disabled. 14350 */ 14351 ilb_cpus = this_cpu_cpumask_var_ptr(select_rq_mask); 14352 cpumask_and(ilb_cpus, nohz.idle_cpus_mask, 14353 housekeeping_cpumask(HK_TYPE_KERNEL_NOISE)); 14354 14355 for_each_cpu(ilb_cpu, ilb_cpus) { 14356 if (!idle_cpu(ilb_cpu)) { 14357 /* 14358 * Once an idle fallback exists, a busy CPU proves that 14359 * this core cannot be fully idle. Skip its siblings. 14360 */ 14361 if (sched_smt_active() && fallback >= 0) 14362 cpumask_andnot(ilb_cpus, ilb_cpus, cpu_smt_mask(ilb_cpu)); 14363 continue; 14364 } 14365 14366 /* 14367 * Running the idle load balancer on an idle sibling of a busy 14368 * SMT core can reduce the capacity available to its sibling. Prefer 14369 * a CPU whose entire core is idle, but retain the first idle CPU as 14370 * a fallback so idle balancing can still make progress when no fully 14371 * idle core exists. 14372 */ 14373 if (sched_smt_active() && !is_core_idle(ilb_cpu)) { 14374 if (fallback < 0) 14375 fallback = ilb_cpu; 14376 14377 /* 14378 * The core is not idle, so there is no need to check 14379 * any of its other SMT siblings. 14380 */ 14381 cpumask_andnot(ilb_cpus, ilb_cpus, 14382 cpu_smt_mask(ilb_cpu)); 14383 continue; 14384 } 14385 14386 return ilb_cpu; 14387 } 14388 14389 return fallback; 14390 } 14391 14392 /* 14393 * Kick a CPU to do the NOHZ balancing, if it is time for it, via a cross-CPU 14394 * SMP function call (IPI). 14395 * 14396 * Prefer a CPU on a fully idle core in the HK_TYPE_KERNEL_NOISE housekeeping 14397 * set. Fall back to the first idle CPU when no fully idle core exists. 14398 */ 14399 static void kick_ilb(unsigned int flags) 14400 { 14401 int ilb_cpu; 14402 14403 /* 14404 * Increase nohz.next_balance only when if full ilb is triggered but 14405 * not if we only update stats. 14406 */ 14407 if (flags & NOHZ_BALANCE_KICK) 14408 nohz.next_balance = jiffies+1; 14409 14410 ilb_cpu = find_new_ilb(); 14411 if (ilb_cpu < 0) 14412 return; 14413 14414 /* 14415 * Don't bother if no new NOHZ balance work items for ilb_cpu, 14416 * i.e. all bits in flags are already set in ilb_cpu. 14417 */ 14418 if ((atomic_read(nohz_flags(ilb_cpu)) & flags) == flags) 14419 return; 14420 14421 /* 14422 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets 14423 * the first flag owns it; cleared by nohz_csd_func(). 14424 */ 14425 flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu)); 14426 if (flags & NOHZ_KICK_MASK) 14427 return; 14428 14429 /* 14430 * This way we generate an IPI on the target CPU which 14431 * is idle, and the softirq performing NOHZ idle load balancing 14432 * will be run before returning from the IPI. 14433 */ 14434 smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd); 14435 } 14436 14437 /* 14438 * Current decision point for kicking the idle load balancer in the presence 14439 * of idle CPUs in the system. 14440 */ 14441 static void nohz_balancer_kick(struct rq *rq) 14442 { 14443 unsigned long now = jiffies; 14444 struct sched_domain_shared *sds; 14445 struct sched_domain *sd; 14446 int nr_busy, i, cpu = rq->cpu; 14447 unsigned int flags = 0; 14448 14449 if (unlikely(rq->idle_balance)) 14450 return; 14451 14452 /* 14453 * We may be recently in ticked or tickless idle mode. At the first 14454 * busy tick after returning from idle, we will update the busy stats. 14455 */ 14456 nohz_balance_exit_idle(rq); 14457 14458 if (READ_ONCE(nohz.has_blocked_load) && 14459 time_after(now, READ_ONCE(nohz.next_blocked))) 14460 flags = NOHZ_STATS_KICK; 14461 14462 /* 14463 * Most of the time system is not 100% busy. i.e nohz.nr_cpus > 0 14464 * Skip the read if time is not due. 14465 * 14466 * If none are in tickless mode, there maybe a narrow window 14467 * (28 jiffies, HZ=1000) where flags maybe set and kick_ilb called. 14468 * But idle load balancing is not done as find_new_ilb fails. 14469 * That's very rare. So read nohz.nr_cpus only if time is due. 14470 */ 14471 if (time_before(now, nohz.next_balance)) 14472 goto out; 14473 14474 /* 14475 * None are in tickless mode and hence no need for NOHZ idle load 14476 * balancing 14477 */ 14478 if (unlikely(cpumask_empty(nohz.idle_cpus_mask))) 14479 return; 14480 14481 if (rq->nr_running >= 2) { 14482 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 14483 goto out; 14484 } 14485 14486 sd = rcu_dereference_all(rq->sd); 14487 if (sd) { 14488 /* 14489 * If there's a runnable CFS task and the current CPU has reduced 14490 * capacity, kick the ILB to see if there's a better CPU to run on: 14491 */ 14492 if (rq->cfs.h_nr_runnable >= 1 && check_cpu_capacity(rq, sd)) { 14493 flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 14494 goto out; 14495 } 14496 } 14497 14498 sd = rcu_dereference_all(per_cpu(sd_asym_packing, cpu)); 14499 if (sd) { 14500 /* 14501 * When ASYM_PACKING; see if there's a more preferred CPU 14502 * currently idle; in which case, kick the ILB to move tasks 14503 * around. 14504 * 14505 * When balancing between cores, all the SMT siblings of the 14506 * preferred CPU must be idle. 14507 */ 14508 for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) { 14509 if (sched_asym(sd, i, cpu)) { 14510 flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 14511 goto out; 14512 } 14513 } 14514 } 14515 14516 sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, cpu)); 14517 if (sd) { 14518 /* 14519 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU 14520 * to run the misfit task on. 14521 */ 14522 if (check_misfit_status(rq)) 14523 flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 14524 14525 /* 14526 * For asymmetric systems, we do not want to nicely balance 14527 * cache use, instead we want to embrace asymmetry and only 14528 * ensure tasks have enough CPU capacity. 14529 * 14530 * Skip the LLC logic because it's not relevant in that case. 14531 */ 14532 goto out; 14533 } 14534 14535 sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu)); 14536 if (sds) { 14537 /* 14538 * If there is an imbalance between LLC domains (IOW we could 14539 * increase the overall cache utilization), we need a less-loaded LLC 14540 * domain to pull some load from. Likewise, we may need to spread 14541 * load within the current LLC domain (e.g. packed SMT cores but 14542 * other CPUs are idle). We can't really know from here how busy 14543 * the others are - so just get a NOHZ balance going if it looks 14544 * like this LLC domain has tasks we could move. 14545 */ 14546 nr_busy = atomic_read(&sds->nr_busy_cpus); 14547 if (nr_busy > 1) 14548 flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 14549 } 14550 out: 14551 if (READ_ONCE(nohz.needs_update)) 14552 flags |= NOHZ_NEXT_KICK; 14553 14554 if (flags) 14555 kick_ilb(flags); 14556 } 14557 14558 static void set_cpu_sd_state_busy(int cpu) 14559 { 14560 struct sched_domain *sd; 14561 sd = rcu_dereference_all(per_cpu(sd_llc, cpu)); 14562 14563 /* 14564 * sd->nohz_idle only pairs with nr_busy_cpus on sd->shared; if this 14565 * domain has no shared object there is nothing to clear or account. 14566 */ 14567 if (!sd || !sd->shared || !sd->nohz_idle) 14568 return; 14569 sd->nohz_idle = 0; 14570 14571 atomic_inc(&sd->shared->nr_busy_cpus); 14572 } 14573 14574 void nohz_balance_exit_idle(struct rq *rq) 14575 { 14576 WARN_ON_ONCE(rq != this_rq()); 14577 14578 if (likely(!rq->nohz_tick_stopped)) 14579 return; 14580 14581 rq->nohz_tick_stopped = 0; 14582 cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask); 14583 14584 set_cpu_sd_state_busy(rq->cpu); 14585 } 14586 14587 static void set_cpu_sd_state_idle(int cpu) 14588 { 14589 struct sched_domain *sd; 14590 sd = rcu_dereference_all(per_cpu(sd_llc, cpu)); 14591 14592 /* See set_cpu_sd_state_busy(): nohz_idle is only used with sd->shared. */ 14593 if (!sd || !sd->shared || sd->nohz_idle) 14594 return; 14595 sd->nohz_idle = 1; 14596 14597 atomic_dec(&sd->shared->nr_busy_cpus); 14598 } 14599 14600 /* 14601 * This routine will record that the CPU is going idle with tick stopped. 14602 * This info will be used in performing idle load balancing in the future. 14603 */ 14604 void nohz_balance_enter_idle(int cpu) 14605 { 14606 struct rq *rq = cpu_rq(cpu); 14607 14608 WARN_ON_ONCE(cpu != smp_processor_id()); 14609 14610 /* If this CPU is going down, then nothing needs to be done: */ 14611 if (!cpu_active(cpu)) 14612 return; 14613 14614 /* 14615 * Can be set safely without rq->lock held 14616 * If a clear happens, it will have evaluated last additions because 14617 * rq->lock is held during the check and the clear 14618 */ 14619 rq->has_blocked_load = 1; 14620 14621 /* 14622 * The tick is still stopped but load could have been added in the 14623 * meantime. We set the nohz.has_blocked_load flag to trig a check of the 14624 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear 14625 * of nohz.has_blocked_load can only happen after checking the new load 14626 */ 14627 if (rq->nohz_tick_stopped) 14628 goto out; 14629 14630 /* If we're a completely isolated CPU, we don't play: */ 14631 if (on_null_domain(rq)) 14632 return; 14633 14634 rq->nohz_tick_stopped = 1; 14635 14636 cpumask_set_cpu(cpu, nohz.idle_cpus_mask); 14637 14638 /* 14639 * Ensures that if nohz_idle_balance() fails to observe our 14640 * @idle_cpus_mask store, it must observe the @has_blocked_load 14641 * and @needs_update stores. 14642 */ 14643 smp_mb__after_atomic(); 14644 14645 set_cpu_sd_state_idle(cpu); 14646 14647 WRITE_ONCE(nohz.needs_update, 1); 14648 out: 14649 /* 14650 * Each time a cpu enter idle, we assume that it has blocked load and 14651 * enable the periodic update of the load of idle CPUs 14652 */ 14653 WRITE_ONCE(nohz.has_blocked_load, 1); 14654 } 14655 14656 static bool update_nohz_stats(struct rq *rq) 14657 { 14658 unsigned int cpu = rq->cpu; 14659 14660 if (!rq->has_blocked_load) 14661 return false; 14662 14663 if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask)) 14664 return false; 14665 14666 if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick))) 14667 return true; 14668 14669 sched_balance_update_blocked_averages(cpu); 14670 14671 return rq->has_blocked_load; 14672 } 14673 14674 /* 14675 * Internal function that runs load balance for all idle CPUs. The load balance 14676 * can be a simple update of blocked load or a complete load balance with 14677 * tasks movement depending of flags. 14678 */ 14679 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags) 14680 { 14681 /* Earliest time when we have to do rebalance again */ 14682 unsigned long now = jiffies; 14683 unsigned long next_balance = now + 60*HZ; 14684 bool has_blocked_load = false; 14685 int update_next_balance = 0; 14686 int this_cpu = this_rq->cpu; 14687 int balance_cpu; 14688 struct rq *rq; 14689 14690 WARN_ON_ONCE((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK); 14691 14692 /* 14693 * We assume there will be no idle load after this update and clear 14694 * the has_blocked_load flag. If a cpu enters idle in the mean time, it will 14695 * set the has_blocked_load flag and trigger another update of idle load. 14696 * Because a cpu that becomes idle, is added to idle_cpus_mask before 14697 * setting the flag, we are sure to not clear the state and not 14698 * check the load of an idle cpu. 14699 * 14700 * Same applies to idle_cpus_mask vs needs_update. 14701 */ 14702 if (flags & NOHZ_STATS_KICK) 14703 WRITE_ONCE(nohz.has_blocked_load, 0); 14704 if (flags & NOHZ_NEXT_KICK) 14705 WRITE_ONCE(nohz.needs_update, 0); 14706 14707 /* 14708 * Ensures that if we miss the CPU, we must see the has_blocked_load 14709 * store from nohz_balance_enter_idle(). 14710 */ 14711 smp_mb(); 14712 14713 /* 14714 * Start with the next CPU after this_cpu so we will end with this_cpu and let a 14715 * chance for other idle cpu to pull load. 14716 */ 14717 for_each_cpu_wrap(balance_cpu, nohz.idle_cpus_mask, this_cpu+1) { 14718 if (!idle_cpu(balance_cpu)) 14719 continue; 14720 14721 /* 14722 * If this CPU gets work to do, stop the load balancing 14723 * work being done for other CPUs. Next load 14724 * balancing owner will pick it up. 14725 */ 14726 if (!idle_cpu(this_cpu) && need_resched()) { 14727 if (flags & NOHZ_STATS_KICK) 14728 has_blocked_load = true; 14729 if (flags & NOHZ_NEXT_KICK) 14730 WRITE_ONCE(nohz.needs_update, 1); 14731 goto abort; 14732 } 14733 14734 rq = cpu_rq(balance_cpu); 14735 14736 if (flags & NOHZ_STATS_KICK) 14737 has_blocked_load |= update_nohz_stats(rq); 14738 14739 /* 14740 * If time for next balance is due, 14741 * do the balance. 14742 */ 14743 if (time_after_eq(jiffies, rq->next_balance)) { 14744 struct rq_flags rf; 14745 14746 rq_lock_irqsave(rq, &rf); 14747 update_rq_clock(rq); 14748 rq_unlock_irqrestore(rq, &rf); 14749 14750 if (flags & NOHZ_BALANCE_KICK) 14751 sched_balance_domains(rq, CPU_IDLE); 14752 } 14753 14754 if (time_after(next_balance, rq->next_balance)) { 14755 next_balance = rq->next_balance; 14756 update_next_balance = 1; 14757 } 14758 } 14759 14760 /* 14761 * next_balance will be updated only when there is a need. 14762 * When the CPU is attached to null domain for ex, it will not be 14763 * updated. 14764 */ 14765 if (likely(update_next_balance)) 14766 nohz.next_balance = next_balance; 14767 14768 if (flags & NOHZ_STATS_KICK) 14769 WRITE_ONCE(nohz.next_blocked, 14770 now + msecs_to_jiffies(LOAD_AVG_PERIOD)); 14771 14772 abort: 14773 /* There is still blocked load, enable periodic update */ 14774 if (has_blocked_load) 14775 WRITE_ONCE(nohz.has_blocked_load, 1); 14776 } 14777 14778 /* 14779 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the 14780 * rebalancing for all the CPUs for whom scheduler ticks are stopped. 14781 */ 14782 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) 14783 { 14784 unsigned int flags = this_rq->nohz_idle_balance; 14785 14786 if (!flags) 14787 return false; 14788 14789 this_rq->nohz_idle_balance = 0; 14790 14791 if (idle != CPU_IDLE) 14792 return false; 14793 14794 _nohz_idle_balance(this_rq, flags); 14795 14796 return true; 14797 } 14798 14799 /* 14800 * Check if we need to directly run the ILB for updating blocked load before 14801 * entering idle state. Here we run ILB directly without issuing IPIs. 14802 * 14803 * Note that when this function is called, the tick may not yet be stopped on 14804 * this CPU yet. nohz.idle_cpus_mask is updated only when tick is stopped and 14805 * cleared on the next busy tick. In other words, nohz.idle_cpus_mask updates 14806 * don't align with CPUs enter/exit idle to avoid bottlenecks due to high idle 14807 * entry/exit rate (usec). So it is possible that _nohz_idle_balance() is 14808 * called from this function on (this) CPU that's not yet in the mask. That's 14809 * OK because the goal of nohz_run_idle_balance() is to run ILB only for 14810 * updating the blocked load of already idle CPUs without waking up one of 14811 * those idle CPUs and outside the preempt disable / IRQ off phase of the local 14812 * cpu about to enter idle, because it can take a long time. 14813 */ 14814 void nohz_run_idle_balance(int cpu) 14815 { 14816 unsigned int flags; 14817 14818 flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu)); 14819 14820 /* 14821 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen 14822 * (i.e. NOHZ_STATS_KICK set) and will do the same. 14823 */ 14824 if ((flags == NOHZ_NEWILB_KICK) && !need_resched()) 14825 _nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK); 14826 } 14827 14828 static void nohz_newidle_balance(struct rq *this_rq) 14829 { 14830 int this_cpu = this_rq->cpu; 14831 14832 /* Will wake up very soon. No time for doing anything else*/ 14833 if (this_rq->avg_idle < sysctl_sched_migration_cost) 14834 return; 14835 14836 /* Don't need to update blocked load of idle CPUs*/ 14837 if (!READ_ONCE(nohz.has_blocked_load) || 14838 time_before(jiffies, READ_ONCE(nohz.next_blocked))) 14839 return; 14840 14841 /* 14842 * Set the need to trigger ILB in order to update blocked load 14843 * before entering idle state. 14844 */ 14845 atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu)); 14846 } 14847 14848 #else /* !CONFIG_NO_HZ_COMMON: */ 14849 static inline void nohz_balancer_kick(struct rq *rq) { } 14850 14851 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) 14852 { 14853 return false; 14854 } 14855 14856 static inline void nohz_newidle_balance(struct rq *this_rq) { } 14857 #endif /* !CONFIG_NO_HZ_COMMON */ 14858 14859 /* 14860 * sched_balance_newidle is called by schedule() if this_cpu is about to become 14861 * idle. Attempts to pull tasks from other CPUs. 14862 * 14863 * Returns: 14864 * < 0 - we released the lock and there are !fair tasks present 14865 * 0 - failed, no new tasks 14866 * > 0 - success, new (fair) tasks present 14867 */ 14868 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf) 14869 __must_hold(__rq_lockp(this_rq)) 14870 { 14871 unsigned long next_balance = jiffies + HZ; 14872 int this_cpu = this_rq->cpu; 14873 int continue_balancing = 1; 14874 u64 t0, t1, curr_cost = 0; 14875 struct sched_domain *sd; 14876 int pulled_task = 0; 14877 14878 update_misfit_status(NULL, this_rq); 14879 14880 /* 14881 * There is a task waiting to run. No need to search for one. 14882 * Return 0; the task will be enqueued when switching to idle. 14883 */ 14884 if (this_rq->ttwu_pending) 14885 return 0; 14886 14887 /* 14888 * We must set idle_stamp _before_ calling sched_balance_rq() 14889 * for CPU_NEWLY_IDLE, such that we measure the this duration 14890 * as idle time. 14891 */ 14892 this_rq->idle_stamp = rq_clock(this_rq); 14893 14894 /* Do not pull tasks towards !preferred CPUs */ 14895 if (!cpu_preferred(this_cpu)) 14896 return 0; 14897 14898 /* 14899 * This is OK, because current is on_cpu, which avoids it being picked 14900 * for load-balance and preemption/IRQs are still disabled avoiding 14901 * further scheduler activity on it and we're being very careful to 14902 * re-start the picking loop. 14903 */ 14904 rq_unpin_lock(this_rq, rf); 14905 14906 sd = rcu_dereference_sched_domain(this_rq->sd); 14907 if (!sd) 14908 goto out; 14909 14910 if (!get_rd_overloaded(this_rq->rd) || 14911 this_rq->avg_idle < sd->max_newidle_lb_cost) { 14912 14913 update_next_balance(sd, &next_balance); 14914 goto out; 14915 } 14916 14917 /* 14918 * Include sched_balance_update_blocked_averages() in the cost 14919 * calculation because it can be quite costly -- this ensures we skip 14920 * it when avg_idle gets to be very low. 14921 */ 14922 t0 = sched_clock_cpu(this_cpu); 14923 __sched_balance_update_blocked_averages(this_rq); 14924 14925 rq_modified_begin(this_rq, &fair_sched_class); 14926 raw_spin_rq_unlock(this_rq); 14927 14928 for_each_domain(this_cpu, sd) { 14929 u64 domain_cost; 14930 14931 update_next_balance(sd, &next_balance); 14932 14933 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) 14934 break; 14935 14936 if (sd->flags & SD_BALANCE_NEWIDLE) { 14937 unsigned int weight = 1; 14938 14939 if (sched_feat(NI_RANDOM) && sd->newidle_ratio < 1024) { 14940 /* 14941 * Throw a 1k sided dice; and only run 14942 * newidle_balance according to the success 14943 * rate. 14944 */ 14945 u32 d1k = sched_rng() % 1024; 14946 weight = 1 + sd->newidle_ratio; 14947 if (d1k > weight) { 14948 update_newidle_stats(sd, 0); 14949 continue; 14950 } 14951 weight = (1024 + weight/2) / weight; 14952 } 14953 14954 pulled_task = sched_balance_rq(this_cpu, this_rq, 14955 sd, CPU_NEWLY_IDLE, 14956 &continue_balancing); 14957 14958 t1 = sched_clock_cpu(this_cpu); 14959 domain_cost = t1 - t0; 14960 curr_cost += domain_cost; 14961 t0 = t1; 14962 14963 /* 14964 * Track max cost of a domain to make sure to not delay the 14965 * next wakeup on the CPU. 14966 */ 14967 update_newidle_cost(sd, domain_cost, weight * !!pulled_task); 14968 } 14969 14970 /* 14971 * Stop searching for tasks to pull if there are 14972 * now runnable tasks on this rq. 14973 */ 14974 if (pulled_task || !continue_balancing) 14975 break; 14976 } 14977 14978 raw_spin_rq_lock(this_rq); 14979 14980 if (curr_cost > this_rq->max_idle_balance_cost) 14981 this_rq->max_idle_balance_cost = curr_cost; 14982 14983 /* 14984 * While browsing the domains, we released the rq lock, a task could 14985 * have been enqueued in the meantime. Since we're not going idle, 14986 * pretend we pulled a task. 14987 */ 14988 if (this_rq->cfs.h_nr_queued && !pulled_task) 14989 pulled_task = 1; 14990 14991 /* If a higher prio class was modified, restart the pick */ 14992 if (rq_modified_above(this_rq, &fair_sched_class)) 14993 pulled_task = -1; 14994 14995 out: 14996 /* Move the next balance forward */ 14997 if (time_after(this_rq->next_balance, next_balance)) 14998 this_rq->next_balance = next_balance; 14999 15000 if (pulled_task) 15001 this_rq->idle_stamp = 0; 15002 else 15003 nohz_newidle_balance(this_rq); 15004 15005 rq_repin_lock(this_rq, rf); 15006 15007 return pulled_task; 15008 } 15009 15010 /* 15011 * This softirq handler is triggered via SCHED_SOFTIRQ from two places: 15012 * 15013 * - directly from the local sched_tick() for periodic load balancing 15014 * 15015 * - indirectly from a remote sched_tick() for NOHZ idle balancing 15016 * through the SMP cross-call nohz_csd_func() 15017 */ 15018 static __latent_entropy void sched_balance_softirq(void) 15019 { 15020 struct rq *this_rq = this_rq(); 15021 enum cpu_idle_type idle = this_rq->idle_balance; 15022 /* 15023 * If this CPU has a pending NOHZ_BALANCE_KICK, then do the 15024 * balancing on behalf of the other idle CPUs whose ticks are 15025 * stopped. Do nohz_idle_balance *before* sched_balance_domains to 15026 * give the idle CPUs a chance to load balance. Else we may 15027 * load balance only within the local sched_domain hierarchy 15028 * and abort nohz_idle_balance altogether if we pull some load. 15029 */ 15030 if (nohz_idle_balance(this_rq, idle)) 15031 return; 15032 15033 /* normal load balance */ 15034 sched_balance_update_blocked_averages(this_rq->cpu); 15035 sched_balance_domains(this_rq, idle); 15036 } 15037 15038 /* 15039 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing. 15040 */ 15041 void sched_balance_trigger(struct rq *rq) 15042 { 15043 /* 15044 * Don't need to rebalance while attached to NULL domain or 15045 * runqueue CPU is not active 15046 */ 15047 if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq)))) 15048 return; 15049 15050 if (time_after_eq(jiffies, rq->next_balance)) 15051 raise_softirq(SCHED_SOFTIRQ); 15052 15053 nohz_balancer_kick(rq); 15054 } 15055 15056 static void rq_online_fair(struct rq *rq) 15057 { 15058 update_sysctl(); 15059 15060 update_runtime_enabled(rq); 15061 } 15062 15063 static void rq_offline_fair(struct rq *rq) 15064 { 15065 update_sysctl(); 15066 15067 /* Ensure any throttled groups are reachable by pick_next_task */ 15068 unthrottle_offline_cfs_rqs(rq); 15069 15070 /* Ensure that we remove rq contribution to group share: */ 15071 clear_tg_offline_cfs_rqs(rq); 15072 } 15073 15074 #ifdef CONFIG_SCHED_CORE 15075 static inline bool 15076 __entity_slice_used(struct sched_entity *se, int min_nr_tasks) 15077 { 15078 u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime; 15079 u64 slice = se->slice; 15080 15081 return (rtime * min_nr_tasks > slice); 15082 } 15083 15084 #define MIN_NR_TASKS_DURING_FORCEIDLE 2 15085 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) 15086 { 15087 if (!sched_core_enabled(rq)) 15088 return; 15089 15090 /* 15091 * If runqueue has only one task which used up its slice and 15092 * if the sibling is forced idle, then trigger schedule to 15093 * give forced idle task a chance. 15094 * 15095 * __entity_slice_used() considers only this active rq and it gets the 15096 * whole slice. But during force idle, we have siblings acting 15097 * like a single runqueue and hence we need to consider runnable 15098 * tasks on this CPU and the forced idle CPU. Ideally, we should 15099 * go through the forced idle rq, but that would be a perf hit. 15100 * We can assume that the forced idle CPU has at least 15101 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check 15102 * if we need to give up the CPU. 15103 */ 15104 if (rq->core->core_forceidle_count && rq->cfs.h_nr_queued == 1 && 15105 __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE)) 15106 resched_curr(rq); 15107 } 15108 15109 /* 15110 * Consider any infeasible weight scenario. Take for instance two tasks, 15111 * each bound to their respective sibling, one with weight 1 and one with 15112 * weight 2. Then the lower weight task will run ahead of the higher weight 15113 * task without bound. 15114 * 15115 * This utterly destroys the concept of a shared time base. 15116 * 15117 * Remember; all this is about a proportionally fair scheduling, where each 15118 * tasks receives: 15119 * 15120 * w_i 15121 * dt_i = ---------- dt (1) 15122 * \Sum_j w_j 15123 * 15124 * which we do by tracking a virtual time, s_i: 15125 * 15126 * 1 15127 * s_i = --- d[t]_i (2) 15128 * w_i 15129 * 15130 * Where d[t] is a delta of discrete time, while dt is an infinitesimal. 15131 * The immediate corollary is that the ideal schedule S, where (2) to use 15132 * an infinitesimal delta, is: 15133 * 15134 * 1 15135 * S = ---------- dt (3) 15136 * \Sum_i w_i 15137 * 15138 * From which we can define the lag, or deviation from the ideal, as: 15139 * 15140 * lag(i) = S - s_i (4) 15141 * 15142 * And since the one and only purpose is to approximate S, we get that: 15143 * 15144 * \Sum_i w_i lag(i) := 0 (5) 15145 * 15146 * If this were not so, we no longer converge to S, and we can no longer 15147 * claim our scheduler has any of the properties we derive from S. This is 15148 * exactly what you did above, you broke it! 15149 * 15150 * 15151 * Let's continue for a while though; to see if there is anything useful to 15152 * be learned. We can combine (1)-(3) or (4)-(5) and express S in s_i: 15153 * 15154 * \Sum_i w_i s_i 15155 * S = -------------- (6) 15156 * \Sum_i w_i 15157 * 15158 * Which gives us a way to compute S, given our s_i. Now, if you've read 15159 * our code, you know that we do not in fact do this, the reason for this 15160 * is two-fold. Firstly, computing S in that way requires a 64bit division 15161 * for every time we'd use it (see 12), and secondly, this only describes 15162 * the steady-state, it doesn't handle dynamics. 15163 * 15164 * Anyway, in (6): s_i -> x + (s_i - x), to get: 15165 * 15166 * \Sum_i w_i (s_i - x) 15167 * S - x = -------------------- (7) 15168 * \Sum_i w_i 15169 * 15170 * Which shows that S and s_i transform alike (which makes perfect sense 15171 * given that S is basically the (weighted) average of s_i). 15172 * 15173 * So the thing to remember is that the above is strictly UP. It is 15174 * possible to generalize to multiple runqueues -- however it gets really 15175 * yuck when you have to add affinity support, as illustrated by our very 15176 * first counter-example. 15177 * 15178 * Luckily I think we can avoid needing a full multi-queue variant for 15179 * core-scheduling (or load-balancing). The crucial observation is that we 15180 * only actually need this comparison in the presence of forced-idle; only 15181 * then do we need to tell if the stalled rq has higher priority over the 15182 * other. 15183 * 15184 * [XXX assumes SMT2; better consider the more general case, I suspect 15185 * it'll work out because our comparison is always between 2 rqs and the 15186 * answer is only interesting if one of them is forced-idle] 15187 * 15188 * And (under assumption of SMT2) when there is forced-idle, there is only 15189 * a single queue, so everything works like normal. 15190 * 15191 * Let, for our runqueue 'k': 15192 * 15193 * T_k = \Sum_i w_i s_i 15194 * W_k = \Sum_i w_i ; for all i of k (8) 15195 * 15196 * Then we can write (6) like: 15197 * 15198 * T_k 15199 * S_k = --- (9) 15200 * W_k 15201 * 15202 * From which immediately follows that: 15203 * 15204 * T_k + T_l 15205 * S_k+l = --------- (10) 15206 * W_k + W_l 15207 * 15208 * On which we can define a combined lag: 15209 * 15210 * lag_k+l(i) := S_k+l - s_i (11) 15211 * 15212 * And that gives us the tools to compare tasks across a combined runqueue. 15213 * 15214 * 15215 * Combined this gives the following: 15216 * 15217 * a) when a runqueue enters force-idle, sync it against it's sibling rq(s) 15218 * using (7); this only requires storing single 'time'-stamps. 15219 * 15220 * b) when comparing tasks between 2 runqueues of which one is forced-idle, 15221 * compare the combined lag, per (11). 15222 * 15223 * Now, of course cgroups (I so hate them) make this more interesting in 15224 * that a) seems to suggest we need to iterate all cgroup on a CPU at such 15225 * boundaries, but I think we can avoid that. The force-idle is for the 15226 * whole CPU, all it's rqs. So we can mark it in the root and lazily 15227 * propagate downward on demand. 15228 */ 15229 15230 /* 15231 * So this sync is basically a relative reset of S to 0. 15232 * 15233 * So with 2 queues, when one goes idle, we drop them both to 0 and one 15234 * then increases due to not being idle, and the idle one builds up lag to 15235 * get re-elected. So far so simple, right? 15236 * 15237 * When there's 3, we can have the situation where 2 run and one is idle, 15238 * we sync to 0 and let the idle one build up lag to get re-election. Now 15239 * suppose another one also drops idle. At this point dropping all to 0 15240 * again would destroy the built-up lag from the queue that was already 15241 * idle, not good. 15242 * 15243 * So instead of syncing everything, we can: 15244 * 15245 * less := !((s64)(s_a - s_b) <= 0) 15246 * 15247 * (v_a - S_a) - (v_b - S_b) == v_a - v_b - S_a + S_b 15248 * == v_a - (v_b - S_a + S_b) 15249 * 15250 * IOW, we can recast the (lag) comparison to a one-sided difference. 15251 * So if then, instead of syncing the whole queue, sync the idle queue 15252 * against the active queue with S_a + S_b at the point where we sync. 15253 * 15254 * (XXX consider the implication of living in a cyclic group: N / 2^n N) 15255 * 15256 * This gives us means of syncing single queues against the active queue, 15257 * and for already idle queues to preserve their build-up lag. 15258 * 15259 * Of course, then we get the situation where there's 2 active and one 15260 * going idle, who do we pick to sync against? Theory would have us sync 15261 * against the combined S, but as we've already demonstrated, there is no 15262 * such thing in infeasible weight scenarios. 15263 * 15264 * One thing I've considered; and this is where that core_active rudiment 15265 * came from, is having active queues sync up between themselves after 15266 * every tick. This limits the observed divergence due to the work 15267 * conservancy. 15268 * 15269 * On top of that, we can improve upon things by employing (10) here. 15270 */ 15271 15272 /* 15273 * se_fi_update - Update the cfs_rq->zero_vruntime_fi in a CFS hierarchy if needed. 15274 */ 15275 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq, 15276 bool forceidle) 15277 { 15278 for_each_sched_entity(se) { 15279 struct cfs_rq *cfs_rq = cfs_rq_of(se); 15280 15281 if (forceidle) { 15282 if (cfs_rq->forceidle_seq == fi_seq) 15283 break; 15284 cfs_rq->forceidle_seq = fi_seq; 15285 } 15286 15287 cfs_rq->zero_vruntime_fi = cfs_rq->zero_vruntime; 15288 } 15289 } 15290 15291 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi) 15292 { 15293 struct sched_entity *se = &p->se; 15294 15295 if (p->sched_class != &fair_sched_class) 15296 return; 15297 15298 se_fi_update(se, rq->core->core_forceidle_seq, in_fi); 15299 } 15300 15301 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b, 15302 bool in_fi) 15303 { 15304 struct rq *rq = task_rq(a); 15305 const struct sched_entity *sea = &a->se; 15306 const struct sched_entity *seb = &b->se; 15307 struct cfs_rq *cfs_rqa; 15308 struct cfs_rq *cfs_rqb; 15309 s64 delta; 15310 15311 WARN_ON_ONCE(task_rq(b)->core != rq->core); 15312 15313 cfs_rqa = &task_rq(a)->cfs; 15314 cfs_rqb = &task_rq(b)->cfs; 15315 15316 /* 15317 * Find delta after normalizing se's vruntime with its cfs_rq's 15318 * zero_vruntime_fi, which would have been updated in prior calls 15319 * to se_fi_update(). 15320 */ 15321 delta = vruntime_op(sea->vruntime, "-", seb->vruntime) + 15322 vruntime_op(cfs_rqb->zero_vruntime_fi, "-", cfs_rqa->zero_vruntime_fi); 15323 15324 return delta > 0; 15325 } 15326 15327 static int task_is_throttled_fair(struct task_struct *p, int cpu) 15328 { 15329 struct cfs_rq *cfs_rq; 15330 15331 #ifdef CONFIG_FAIR_GROUP_SCHED 15332 cfs_rq = tg_cfs_rq(task_group(p), cpu); 15333 #else 15334 cfs_rq = &cpu_rq(cpu)->cfs; 15335 #endif 15336 return throttled_hierarchy(cfs_rq); 15337 } 15338 #else /* !CONFIG_SCHED_CORE: */ 15339 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {} 15340 #endif /* !CONFIG_SCHED_CORE */ 15341 15342 /* 15343 * scheduler tick hitting a task of our scheduling class. 15344 * 15345 * NOTE: This function can be called remotely by the tick offload that 15346 * goes along full dynticks. Therefore no local assumption can be made 15347 * and everything must be accessed through the @rq and @curr passed in 15348 * parameters. 15349 */ 15350 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued) 15351 { 15352 struct sched_entity *se = &curr->se; 15353 15354 if (se->on_rq) { 15355 unsigned long weight = NICE_0_LOAD; 15356 struct cfs_rq *cfs_rq; 15357 15358 for_each_sched_entity(se) { 15359 cfs_rq = cfs_rq_of(se); 15360 entity_tick(cfs_rq, se, queued); 15361 15362 weight = __calc_prop_weight(cfs_rq, se, weight); 15363 } 15364 15365 se = &curr->se; 15366 reweight_eevdf(cfs_rq, se, weight, se->on_rq); 15367 } 15368 15369 if (queued) 15370 return; 15371 15372 if (static_branch_unlikely(&sched_numa_balancing)) 15373 task_tick_numa(rq, curr); 15374 15375 task_tick_cache(rq, curr); 15376 15377 update_misfit_status(curr, rq); 15378 check_update_overutilized_status(task_rq(curr)); 15379 15380 task_tick_core(rq, curr); 15381 } 15382 15383 /* 15384 * called on fork with the child task as argument from the parent's context 15385 * - child not yet on the tasklist 15386 * - preemption disabled 15387 */ 15388 static void task_fork_fair(struct task_struct *p) 15389 { 15390 set_task_max_allowed_capacity(p); 15391 } 15392 15393 /* 15394 * Priority of the task has changed. Check to see if we preempt 15395 * the current task. 15396 */ 15397 static void 15398 prio_changed_fair(struct rq *rq, struct task_struct *p, u64 oldprio) 15399 { 15400 if (!task_on_rq_queued(p)) 15401 return; 15402 15403 if (p->prio == oldprio) 15404 return; 15405 15406 if (rq->cfs.h_nr_queued == 1) 15407 return; 15408 15409 /* 15410 * Reschedule if we are currently running on this runqueue and 15411 * our priority decreased, or if we are not currently running on 15412 * this runqueue and our priority is higher than the current's 15413 */ 15414 if (task_current_donor(rq, p)) { 15415 if (p->prio > oldprio) 15416 resched_curr(rq); 15417 } else { 15418 wakeup_preempt(rq, p, 0); 15419 } 15420 } 15421 15422 #ifdef CONFIG_FAIR_GROUP_SCHED 15423 /* 15424 * Propagate the changes of the sched_entity across the tg tree to make it 15425 * visible to the root 15426 */ 15427 static void propagate_entity_cfs_rq(struct sched_entity *se) 15428 { 15429 struct cfs_rq *cfs_rq = cfs_rq_of(se); 15430 15431 /* 15432 * If a task gets attached to this cfs_rq and before being queued, 15433 * it gets migrated to another CPU due to reasons like affinity 15434 * change, make sure this cfs_rq stays on leaf cfs_rq list to have 15435 * that removed load decayed or it can cause faireness problem. 15436 */ 15437 if (!cfs_rq_pelt_clock_throttled(cfs_rq)) 15438 list_add_leaf_cfs_rq(cfs_rq); 15439 15440 /* Start to propagate at parent */ 15441 se = se->parent; 15442 15443 for_each_sched_entity(se) { 15444 cfs_rq = cfs_rq_of(se); 15445 15446 update_load_avg(cfs_rq, se, UPDATE_TG); 15447 15448 if (!cfs_rq_pelt_clock_throttled(cfs_rq)) 15449 list_add_leaf_cfs_rq(cfs_rq); 15450 } 15451 15452 assert_list_leaf_cfs_rq(rq_of(cfs_rq)); 15453 } 15454 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 15455 static void propagate_entity_cfs_rq(struct sched_entity *se) { } 15456 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 15457 15458 static void detach_entity_cfs_rq(struct sched_entity *se) 15459 { 15460 struct cfs_rq *cfs_rq = cfs_rq_of(se); 15461 15462 /* 15463 * In case the task sched_avg hasn't been attached: 15464 * - A forked task which hasn't been woken up by wake_up_new_task(). 15465 * - A task which has been woken up by try_to_wake_up() but is 15466 * waiting for actually being woken up by sched_ttwu_pending(). 15467 */ 15468 if (!se->avg.last_update_time) 15469 return; 15470 15471 /* Catch up with the cfs_rq and remove our load when we leave */ 15472 update_load_avg(cfs_rq, se, 0); 15473 detach_entity_load_avg(cfs_rq, se); 15474 update_tg_load_avg(cfs_rq); 15475 propagate_entity_cfs_rq(se); 15476 } 15477 15478 static void attach_entity_cfs_rq(struct sched_entity *se) 15479 { 15480 struct cfs_rq *cfs_rq = cfs_rq_of(se); 15481 15482 /* Synchronize entity with its cfs_rq */ 15483 update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD); 15484 attach_entity_load_avg(cfs_rq, se); 15485 update_tg_load_avg(cfs_rq); 15486 propagate_entity_cfs_rq(se); 15487 } 15488 15489 static void detach_task_cfs_rq(struct task_struct *p) 15490 { 15491 struct sched_entity *se = &p->se; 15492 15493 detach_entity_cfs_rq(se); 15494 } 15495 15496 static void attach_task_cfs_rq(struct task_struct *p) 15497 { 15498 struct sched_entity *se = &p->se; 15499 15500 attach_entity_cfs_rq(se); 15501 } 15502 15503 static void switching_from_fair(struct rq *rq, struct task_struct *p) 15504 { 15505 if (p->se.sched_delayed) 15506 dequeue_task(rq, p, DEQUEUE_SLEEP | DEQUEUE_DELAYED | DEQUEUE_NOCLOCK); 15507 } 15508 15509 static void switched_from_fair(struct rq *rq, struct task_struct *p) 15510 { 15511 detach_task_cfs_rq(p); 15512 } 15513 15514 static void switched_to_fair(struct rq *rq, struct task_struct *p) 15515 { 15516 WARN_ON_ONCE(p->se.sched_delayed); 15517 15518 attach_task_cfs_rq(p); 15519 15520 set_task_max_allowed_capacity(p); 15521 15522 if (task_on_rq_queued(p)) { 15523 /* 15524 * We were most likely switched from sched_rt, so 15525 * kick off the schedule if running, otherwise just see 15526 * if we can still preempt the current task. 15527 */ 15528 if (task_current_donor(rq, p)) 15529 resched_curr(rq); 15530 else 15531 wakeup_preempt(rq, p, 0); 15532 } 15533 } 15534 15535 static void set_next_task_fair(struct rq *rq, struct task_struct *p, enum snt_e type) 15536 { 15537 struct sched_entity *se = &p->se; 15538 struct cfs_rq *cfs_rq = &rq->cfs; 15539 unsigned long weight = NICE_0_LOAD; 15540 bool first = type == SNT_PICK; 15541 bool throttled = false; 15542 bool on_rq = se->on_rq; 15543 15544 if (type == SNT_REPICK) 15545 goto repick; 15546 15547 clear_buddies(cfs_rq, se); 15548 15549 if (on_rq) 15550 __dequeue_entity(cfs_rq, se); 15551 15552 for_each_sched_entity(se) { 15553 cfs_rq = cfs_rq_of(se); 15554 15555 if (!IS_ENABLED(CONFIG_FAIR_GROUP_SCHED) || 15556 !first || !cfs_rq->h_curr) 15557 set_next_entity(cfs_rq, se); 15558 15559 /* ensure bandwidth has been allocated on our new cfs_rq */ 15560 throttled |= account_cfs_rq_runtime(cfs_rq, 0); 15561 15562 if (on_rq) 15563 weight = __calc_prop_weight(cfs_rq, se, weight); 15564 } 15565 15566 if (throttled) 15567 task_throttle_setup_work(p); 15568 15569 se = &p->se; 15570 cfs_rq->curr = se; 15571 15572 if (on_rq) { 15573 reweight_eevdf(cfs_rq, se, weight, se->on_rq); 15574 if (first) 15575 set_protect_slice(cfs_rq, se); 15576 } 15577 15578 if (task_on_rq_queued(p)) { 15579 /* 15580 * Move the next running task to the front of the list, so our 15581 * cfs_tasks list becomes MRU one. 15582 */ 15583 list_move(&se->group_node, &rq->cfs_tasks); 15584 } 15585 if (!first) 15586 return; 15587 15588 WARN_ON_ONCE(se->sched_delayed); 15589 15590 update_misfit_status(p, rq); 15591 sched_fair_update_stop_tick(rq, p); 15592 15593 repick: 15594 /* 15595 * A same-task repick skips put_prev_task_fair(), but 15596 * pick_task_fair() refreshed the entity hrtick_start_fair() reads 15597 * before selecting it again. rq->cfs.curr identifies that entity, 15598 * including with group scheduling. 15599 */ 15600 if (hrtick_enabled_fair(rq)) 15601 hrtick_start_fair(rq, p); 15602 } 15603 15604 void init_cfs_rq(struct cfs_rq *cfs_rq) 15605 { 15606 cfs_rq->tasks_timeline = RB_ROOT_CACHED; 15607 cfs_rq->zero_vruntime = (u64)(-(1LL << 20)); 15608 raw_spin_lock_init(&cfs_rq->removed.lock); 15609 } 15610 15611 #ifdef CONFIG_FAIR_GROUP_SCHED 15612 static void task_change_group_fair(struct task_struct *p) 15613 { 15614 /* 15615 * We couldn't detach or attach a forked task which 15616 * hasn't been woken up by wake_up_new_task(). 15617 */ 15618 if (READ_ONCE(p->__state) == TASK_NEW) 15619 return; 15620 15621 detach_task_cfs_rq(p); 15622 15623 /* Tell se's cfs_rq has been changed -- migrated */ 15624 p->se.avg.last_update_time = 0; 15625 set_task_rq(p, task_cpu(p)); 15626 attach_task_cfs_rq(p); 15627 } 15628 15629 void free_fair_sched_group(struct task_group *tg) 15630 { 15631 free_percpu(tg->cfs_rq); 15632 } 15633 15634 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent) 15635 { 15636 struct cfs_tg_state __percpu *state; 15637 struct sched_entity *se; 15638 struct cfs_rq *cfs_rq; 15639 int i; 15640 15641 state = alloc_percpu_gfp(struct cfs_tg_state, GFP_KERNEL); 15642 if (!state) 15643 goto err; 15644 15645 tg->cfs_rq = &state->cfs_rq; 15646 tg->shares = NICE_0_LOAD; 15647 15648 init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent)); 15649 15650 for_each_possible_cpu(i) { 15651 cfs_rq = tg_cfs_rq(tg, i); 15652 if (!cfs_rq) 15653 goto err; 15654 15655 se = tg_se(tg, i); 15656 init_cfs_rq(cfs_rq); 15657 init_tg_cfs_entry(tg, cfs_rq, se, i, tg_se(parent, i)); 15658 init_entity_runnable_average(se); 15659 } 15660 15661 return 1; 15662 15663 err: 15664 return 0; 15665 } 15666 15667 void online_fair_sched_group(struct task_group *tg) 15668 { 15669 struct sched_entity *se; 15670 struct rq_flags rf; 15671 struct rq *rq; 15672 int i; 15673 15674 for_each_possible_cpu(i) { 15675 rq = cpu_rq(i); 15676 se = tg_se(tg, i); 15677 rq_lock_irq(rq, &rf); 15678 update_rq_clock(rq); 15679 attach_entity_cfs_rq(se); 15680 sync_throttle(tg, i); 15681 rq_unlock_irq(rq, &rf); 15682 } 15683 } 15684 15685 void unregister_fair_sched_group(struct task_group *tg) 15686 { 15687 int cpu; 15688 15689 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg)); 15690 15691 for_each_possible_cpu(cpu) { 15692 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu); 15693 struct sched_entity *se = tg_se(tg, cpu); 15694 struct rq *rq = cpu_rq(cpu); 15695 15696 if (se) 15697 remove_entity_load_avg(se); 15698 15699 /* 15700 * Only empty task groups can be destroyed; so we can speculatively 15701 * check on_list without danger of it being re-added. 15702 */ 15703 if (cfs_rq->on_list) { 15704 guard(rq_lock_irqsave)(rq); 15705 list_del_leaf_cfs_rq(cfs_rq); 15706 } 15707 } 15708 } 15709 15710 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq, 15711 struct sched_entity *se, int cpu, 15712 struct sched_entity *parent) 15713 { 15714 struct rq *rq = cpu_rq(cpu); 15715 15716 cfs_rq->tg = tg; 15717 cfs_rq->rq = rq; 15718 init_cfs_rq_runtime(cfs_rq); 15719 15720 /* se could be NULL for root_task_group */ 15721 if (!se) 15722 return; 15723 15724 if (!parent) { 15725 se->cfs_rq = &rq->cfs; 15726 se->depth = 0; 15727 } else { 15728 se->cfs_rq = parent->my_q; 15729 se->depth = parent->depth + 1; 15730 } 15731 15732 se->my_q = cfs_rq; 15733 /* guarantee group entities always have weight */ 15734 update_load_set(&se->load, NICE_0_LOAD); 15735 se->parent = parent; 15736 } 15737 15738 static DEFINE_MUTEX(shares_mutex); 15739 15740 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares) 15741 { 15742 int i; 15743 15744 lockdep_assert_held(&shares_mutex); 15745 15746 /* 15747 * We can't change the weight of the root cgroup. 15748 */ 15749 if (is_root_task_group(tg)) 15750 return -EINVAL; 15751 15752 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES)); 15753 15754 if (tg->shares == shares) 15755 return 0; 15756 15757 tg->shares = shares; 15758 for_each_possible_cpu(i) { 15759 struct rq *rq = cpu_rq(i); 15760 struct sched_entity *se = tg_se(tg, i); 15761 struct rq_flags rf; 15762 15763 /* Propagate contribution to hierarchy */ 15764 rq_lock_irqsave(rq, &rf); 15765 update_rq_clock(rq); 15766 for_each_sched_entity(se) { 15767 update_load_avg(cfs_rq_of(se), se, UPDATE_TG); 15768 update_cfs_group(se); 15769 } 15770 rq_unlock_irqrestore(rq, &rf); 15771 } 15772 15773 return 0; 15774 } 15775 15776 int sched_group_set_shares(struct task_group *tg, unsigned long shares) 15777 { 15778 int ret; 15779 15780 mutex_lock(&shares_mutex); 15781 if (tg_is_idle(tg)) 15782 ret = -EINVAL; 15783 else 15784 ret = __sched_group_set_shares(tg, shares); 15785 mutex_unlock(&shares_mutex); 15786 15787 return ret; 15788 } 15789 15790 int sched_group_set_idle(struct task_group *tg, long idle) 15791 { 15792 int i; 15793 15794 if (tg == &root_task_group) 15795 return -EINVAL; 15796 15797 if (idle < 0 || idle > 1) 15798 return -EINVAL; 15799 15800 mutex_lock(&shares_mutex); 15801 15802 if (tg->idle == idle) { 15803 mutex_unlock(&shares_mutex); 15804 return 0; 15805 } 15806 15807 tg->idle = idle; 15808 15809 for_each_possible_cpu(i) { 15810 struct rq *rq = cpu_rq(i); 15811 struct sched_entity *se = tg_se(tg, i); 15812 struct cfs_rq *grp_cfs_rq = tg_cfs_rq(tg, i); 15813 bool was_idle = cfs_rq_is_idle(grp_cfs_rq); 15814 long idle_task_delta; 15815 struct rq_flags rf; 15816 15817 rq_lock_irqsave(rq, &rf); 15818 15819 grp_cfs_rq->idle = idle; 15820 if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq))) 15821 goto next_cpu; 15822 15823 idle_task_delta = grp_cfs_rq->h_nr_queued - 15824 grp_cfs_rq->h_nr_idle; 15825 if (!cfs_rq_is_idle(grp_cfs_rq)) 15826 idle_task_delta *= -1; 15827 15828 for_each_sched_entity(se) { 15829 struct cfs_rq *cfs_rq = cfs_rq_of(se); 15830 15831 if (!se->on_rq) 15832 break; 15833 15834 cfs_rq->h_nr_idle += idle_task_delta; 15835 15836 /* Already accounted at parent level and above. */ 15837 if (cfs_rq_is_idle(cfs_rq)) 15838 break; 15839 } 15840 15841 next_cpu: 15842 rq_unlock_irqrestore(rq, &rf); 15843 } 15844 15845 /* Idle groups have minimum weight. */ 15846 if (tg_is_idle(tg)) 15847 __sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO)); 15848 else 15849 __sched_group_set_shares(tg, NICE_0_LOAD); 15850 15851 mutex_unlock(&shares_mutex); 15852 return 0; 15853 } 15854 15855 #endif /* CONFIG_FAIR_GROUP_SCHED */ 15856 15857 15858 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task) 15859 { 15860 struct sched_entity *se = &task->se; 15861 unsigned int rr_interval = 0; 15862 15863 /* 15864 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise 15865 * idle runqueue: 15866 */ 15867 if (rq->cfs.load.weight) 15868 rr_interval = NS_TO_JIFFIES(se->slice); 15869 15870 return rr_interval; 15871 } 15872 15873 /* 15874 * All the scheduling class methods: 15875 */ 15876 DEFINE_SCHED_CLASS(fair) = { 15877 .enqueue_task = enqueue_task_fair, 15878 .dequeue_task = dequeue_task_fair, 15879 .yield_task = yield_task_fair, 15880 .yield_to_task = yield_to_task_fair, 15881 15882 .wakeup_preempt = wakeup_preempt_fair, 15883 15884 .pick_task = pick_task_fair, 15885 .put_prev_task = put_prev_task_fair, 15886 .set_next_task = set_next_task_fair, 15887 15888 .select_task_rq = select_task_rq_fair, 15889 .migrate_task_rq = migrate_task_rq_fair, 15890 15891 .rq_online = rq_online_fair, 15892 .rq_offline = rq_offline_fair, 15893 15894 .task_dead = task_dead_fair, 15895 .set_cpus_allowed = set_cpus_allowed_fair, 15896 15897 .task_tick = task_tick_fair, 15898 .task_fork = task_fork_fair, 15899 15900 .reweight_task = reweight_task_fair, 15901 .prio_changed = prio_changed_fair, 15902 .switching_from = switching_from_fair, 15903 .switched_from = switched_from_fair, 15904 .switched_to = switched_to_fair, 15905 15906 .get_rr_interval = get_rr_interval_fair, 15907 15908 .update_curr = update_curr_fair, 15909 15910 #ifdef CONFIG_FAIR_GROUP_SCHED 15911 .task_change_group = task_change_group_fair, 15912 #endif 15913 15914 #ifdef CONFIG_SCHED_CORE 15915 .task_is_throttled = task_is_throttled_fair, 15916 #endif 15917 15918 #ifdef CONFIG_UCLAMP_TASK 15919 .uclamp_enabled = 1, 15920 #endif 15921 }; 15922 15923 void print_cfs_stats(struct seq_file *m, int cpu) 15924 { 15925 struct cfs_rq *cfs_rq, *pos; 15926 15927 rcu_read_lock(); 15928 for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos) 15929 print_cfs_rq(m, cpu, cfs_rq); 15930 rcu_read_unlock(); 15931 } 15932 15933 #ifdef CONFIG_NUMA_BALANCING 15934 void show_numa_stats(struct task_struct *p, struct seq_file *m) 15935 { 15936 int node; 15937 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0; 15938 struct numa_group *ng; 15939 15940 rcu_read_lock(); 15941 ng = rcu_dereference_all(p->numa_group); 15942 for_each_online_node(node) { 15943 if (p->numa_faults) { 15944 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)]; 15945 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)]; 15946 } 15947 if (ng) { 15948 gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)]; 15949 gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)]; 15950 } 15951 print_numa_stats(m, node, tsf, tpf, gsf, gpf); 15952 } 15953 rcu_read_unlock(); 15954 } 15955 #endif /* CONFIG_NUMA_BALANCING */ 15956 15957 __init void init_sched_fair_class(void) 15958 { 15959 int i; 15960 15961 for_each_possible_cpu(i) { 15962 zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i)); 15963 zalloc_cpumask_var_node(&per_cpu(select_rq_mask, i), GFP_KERNEL, cpu_to_node(i)); 15964 zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i), 15965 GFP_KERNEL, cpu_to_node(i)); 15966 15967 #ifdef CONFIG_CFS_BANDWIDTH 15968 INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i)); 15969 INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list); 15970 #endif 15971 } 15972 15973 open_softirq(SCHED_SOFTIRQ, sched_balance_softirq); 15974 15975 #ifdef CONFIG_NO_HZ_COMMON 15976 nohz.next_balance = jiffies; 15977 nohz.next_blocked = jiffies; 15978 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT); 15979 #endif 15980 } 15981