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/hugetlb_inline.h> 26 #include <linux/jiffies.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 /* 824 * This is called from set_next_task_fair(.first=true) / 825 * set_protect_slice() so curr had better be set and on_rq. 826 */ 827 WARN_ON_ONCE(!curr); 828 829 if (weight) { 830 s64 runtime = cfs_rq->sum_w_vruntime; 831 832 /* 833 * Do not add @curr to obtain the effective '- w_j' terms. 834 */ 835 836 /* sign flips effective floor / ceiling */ 837 if (runtime < 0) 838 runtime -= (weight - 1); 839 840 delta = div64_long(runtime, weight); 841 } 842 843 return cfs_rq->zero_vruntime + delta + 1; 844 } 845 846 static inline u64 cfs_rq_max_slice(struct cfs_rq *cfs_rq); 847 848 /* 849 * lag_i = S - s_i = w_i * (V - v_i) 850 * 851 * However, since V is approximated by the weighted average of all entities it 852 * is possible -- by addition/removal/reweight to the tree -- to move V around 853 * and end up with a larger lag than we started with. 854 * 855 * Limit this to either double the slice length with a minimum of TICK_NSEC 856 * since that is the timing granularity. 857 * 858 * EEVDF gives the following limit for a steady state system: 859 * 860 * -r_max < lag < max(r_max, q) 861 */ 862 static s64 entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se, u64 avruntime) 863 { 864 u64 max_slice = cfs_rq_max_slice(cfs_rq) + TICK_NSEC; 865 s64 vlag, limit; 866 867 vlag = avruntime - se->vruntime; 868 limit = calc_delta_fair(max_slice, se); 869 870 return clamp(vlag, -limit, limit); 871 } 872 873 /* 874 * Delayed dequeue aims to reduce the negative lag of a dequeued task. While 875 * updating the lag of an entity, check that negative lag didn't increase 876 * during the delayed dequeue period which would be unfair. 877 * Similarly, check that the entity didn't gain positive lag when DELAY_ZERO 878 * is set. 879 * 880 * Return true if the vlag has been modified. Specifically: 881 * 882 * se->vlag != avg_vruntime() - se->vruntime 883 * 884 * This can be due to clamping in entity_lag() or clamping due to 885 * sched_delayed. Either way, when vlag is modified and the entity is 886 * retained, the tree needs to be adjusted. 887 */ 888 static __always_inline 889 bool update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se) 890 { 891 u64 avruntime = avg_vruntime(cfs_rq); 892 s64 vlag = entity_lag(cfs_rq, se, avruntime); 893 894 if (se->sched_delayed) { 895 /* previous vlag < 0 otherwise se would not be delayed */ 896 vlag = max(vlag, se->vlag); 897 if (sched_feat(DELAY_ZERO)) 898 vlag = min(vlag, 0); 899 } 900 se->vlag = vlag; 901 902 return avruntime - vlag != se->vruntime; 903 } 904 905 /* 906 * Entity is eligible once it received less service than it ought to have, 907 * eg. lag >= 0. 908 * 909 * lag_i = S - s_i = w_i*(V - v_i) 910 * 911 * lag_i >= 0 -> V >= v_i 912 * 913 * \Sum (v_i - v0)*w_i 914 * V = ------------------- + v0 915 * \Sum w_i 916 * 917 * lag_i >= 0 -> \Sum (v_i - v0)*w_i >= (v_i - v0)*(\Sum w_i) 918 * 919 * Note: using 'avg_vruntime() > se->vruntime' is inaccurate due 920 * to the loss in precision caused by the division. 921 */ 922 static int vruntime_eligible(struct cfs_rq *cfs_rq, u64 vruntime) 923 { 924 struct sched_entity *curr = cfs_rq->curr; 925 s64 key, avg = cfs_rq->sum_w_vruntime; 926 long load = cfs_rq->sum_weight; 927 928 if (curr && curr->on_rq) { 929 unsigned long weight = avg_vruntime_weight(cfs_rq, curr->h_load.weight); 930 931 avg += entity_key(cfs_rq, curr) * weight; 932 load += weight; 933 } 934 935 key = vruntime_op(vruntime, "-", cfs_rq->zero_vruntime); 936 937 /* 938 * The worst case term for @key includes 'NSEC_TICK * NICE_0_LOAD' 939 * and @load obviously includes NICE_0_LOAD. NSEC_TICK is around 24 940 * bits, while NICE_0_LOAD is 20 on 64bit and 10 otherwise. 941 * 942 * This gives that on 64bit the product will be at least 64bit which 943 * overflows s64, while on 32bit it will only be 44bits and should fit 944 * comfortably. 945 */ 946 #ifdef CONFIG_64BIT 947 #ifdef CONFIG_ARCH_SUPPORTS_INT128 948 /* This often results in simpler code than __builtin_mul_overflow(). */ 949 return avg >= (__int128)key * load; 950 #else 951 s64 rhs; 952 /* 953 * On overflow, the sign of key tells us the correct answer: a large 954 * positive key means vruntime >> V, so not eligible; a large negative 955 * key means vruntime << V, so eligible. 956 */ 957 if (check_mul_overflow(key, load, &rhs)) 958 return key <= 0; 959 960 return avg >= rhs; 961 #endif 962 #else /* 32bit */ 963 return avg >= key * load; 964 #endif 965 } 966 967 int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se) 968 { 969 return vruntime_eligible(cfs_rq, se->vruntime); 970 } 971 972 static inline u64 cfs_rq_min_slice(struct cfs_rq *cfs_rq) 973 { 974 struct sched_entity *root = __pick_root_entity(cfs_rq); 975 struct sched_entity *curr = cfs_rq->curr; 976 u64 min_slice = ~0ULL; 977 978 if (curr && curr->on_rq) 979 min_slice = curr->slice; 980 981 if (root) 982 min_slice = min(min_slice, root->min_slice); 983 984 return min_slice; 985 } 986 987 static inline u64 cfs_rq_max_slice(struct cfs_rq *cfs_rq) 988 { 989 struct sched_entity *root = __pick_root_entity(cfs_rq); 990 struct sched_entity *curr = cfs_rq->curr; 991 u64 max_slice = 0ULL; 992 993 if (curr && curr->on_rq) 994 max_slice = curr->slice; 995 996 if (root) 997 max_slice = max(max_slice, root->max_slice); 998 999 return max_slice; 1000 } 1001 1002 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b) 1003 { 1004 return entity_before(__node_2_se(a), __node_2_se(b)); 1005 } 1006 1007 static inline void __min_vruntime_update(struct sched_entity *se, struct rb_node *node) 1008 { 1009 if (node) { 1010 struct sched_entity *rse = __node_2_se(node); 1011 1012 if (vruntime_cmp(se->min_vruntime, ">", rse->min_vruntime)) 1013 se->min_vruntime = rse->min_vruntime; 1014 } 1015 } 1016 1017 static inline void __min_slice_update(struct sched_entity *se, struct rb_node *node) 1018 { 1019 if (node) { 1020 struct sched_entity *rse = __node_2_se(node); 1021 if (rse->min_slice < se->min_slice) 1022 se->min_slice = rse->min_slice; 1023 } 1024 } 1025 1026 static inline void __max_slice_update(struct sched_entity *se, struct rb_node *node) 1027 { 1028 if (node) { 1029 struct sched_entity *rse = __node_2_se(node); 1030 if (rse->max_slice > se->max_slice) 1031 se->max_slice = rse->max_slice; 1032 } 1033 } 1034 1035 /* 1036 * se->min_vruntime = min(se->vruntime, {left,right}->min_vruntime) 1037 */ 1038 static inline bool min_vruntime_update(struct sched_entity *se, bool exit) 1039 { 1040 u64 old_min_vruntime = se->min_vruntime; 1041 u64 old_min_slice = se->min_slice; 1042 u64 old_max_slice = se->max_slice; 1043 struct rb_node *node = &se->run_node; 1044 1045 se->min_vruntime = se->vruntime; 1046 __min_vruntime_update(se, node->rb_right); 1047 __min_vruntime_update(se, node->rb_left); 1048 1049 se->min_slice = se->slice; 1050 __min_slice_update(se, node->rb_right); 1051 __min_slice_update(se, node->rb_left); 1052 1053 se->max_slice = se->slice; 1054 __max_slice_update(se, node->rb_right); 1055 __max_slice_update(se, node->rb_left); 1056 1057 return se->min_vruntime == old_min_vruntime && 1058 se->min_slice == old_min_slice && 1059 se->max_slice == old_max_slice; 1060 } 1061 1062 RB_DECLARE_CALLBACKS(static, min_vruntime_cb, struct sched_entity, 1063 run_node, min_vruntime, min_vruntime_update); 1064 1065 /* 1066 * Enqueue an entity into the rb-tree: 1067 */ 1068 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) 1069 { 1070 WARN_ON_ONCE(&rq_of(cfs_rq)->cfs != cfs_rq); 1071 WARN_ON_ONCE(!entity_is_task(se)); 1072 1073 sum_w_vruntime_add(cfs_rq, se); 1074 se->min_vruntime = se->vruntime; 1075 se->min_slice = se->slice; 1076 rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline, 1077 __entity_less, &min_vruntime_cb); 1078 } 1079 1080 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) 1081 { 1082 WARN_ON_ONCE(&rq_of(cfs_rq)->cfs != cfs_rq); 1083 WARN_ON_ONCE(!entity_is_task(se)); 1084 1085 rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline, 1086 &min_vruntime_cb); 1087 sum_w_vruntime_sub(cfs_rq, se); 1088 } 1089 1090 struct sched_entity *__pick_root_entity(struct cfs_rq *cfs_rq) 1091 { 1092 struct rb_node *root = cfs_rq->tasks_timeline.rb_root.rb_node; 1093 1094 if (!root) 1095 return NULL; 1096 1097 return __node_2_se(root); 1098 } 1099 1100 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq) 1101 { 1102 struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline); 1103 1104 if (!left) 1105 return NULL; 1106 1107 return __node_2_se(left); 1108 } 1109 1110 /* 1111 * Set the vruntime up to which an entity can run before looking 1112 * for another entity to pick. 1113 * In case of run to parity, we use the shortest slice of the enqueued 1114 * entities to set the protected period. 1115 * When run to parity is disabled, we give a minimum quantum to the running 1116 * entity to ensure progress. 1117 */ 1118 static inline void set_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se) 1119 { 1120 u64 slice = normalized_sysctl_sched_base_slice; 1121 u64 vprot = se->deadline; 1122 1123 if (sched_feat(RUN_TO_PARITY)) 1124 slice = cfs_rq_min_slice(cfs_rq); 1125 1126 slice = min(slice, se->slice); 1127 1128 /* If there are shorter slices than se's one */ 1129 if (slice != se->slice) { 1130 if (sched_feat(PREEMPT_SHORT)) 1131 vprot = min_vruntime(vprot, ineligible_vruntime(cfs_rq)); 1132 else 1133 vprot = min_vruntime(vprot, se->vruntime + calc_delta_fair(slice, se)); 1134 } 1135 1136 se->vprot = vprot; 1137 } 1138 1139 static inline void update_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se) 1140 { 1141 u64 slice = cfs_rq_min_slice(cfs_rq); 1142 u64 vruntime = min_vruntime(se->vruntime, avg_vruntime(cfs_rq)); 1143 1144 se->vprot = min_vruntime(se->vprot, vruntime + calc_delta_fair(slice, se)); 1145 } 1146 1147 static inline bool protect_slice(struct sched_entity *se) 1148 { 1149 return vruntime_cmp(se->vruntime, "<", se->vprot); 1150 } 1151 1152 static inline void cancel_protect_slice(struct sched_entity *se) 1153 { 1154 if (protect_slice(se)) 1155 se->vprot = se->vruntime; 1156 } 1157 1158 /* 1159 * Earliest Eligible Virtual Deadline First 1160 * 1161 * In order to provide latency guarantees for different request sizes 1162 * EEVDF selects the best runnable task from two criteria: 1163 * 1164 * 1) the task must be eligible (must be owed service) 1165 * 1166 * 2) from those tasks that meet 1), we select the one 1167 * with the earliest virtual deadline. 1168 * 1169 * We can do this in O(log n) time due to an augmented RB-tree. The 1170 * tree keeps the entries sorted on deadline, but also functions as a 1171 * heap based on the vruntime by keeping: 1172 * 1173 * se->min_vruntime = min(se->vruntime, se->{left,right}->min_vruntime) 1174 * 1175 * Which allows tree pruning through eligibility. 1176 */ 1177 static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq, bool protect) 1178 { 1179 struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node; 1180 struct sched_entity *se = __pick_first_entity(cfs_rq); 1181 struct sched_entity *curr = cfs_rq->curr; 1182 struct sched_entity *best = NULL; 1183 1184 /* 1185 * We can safely skip eligibility check if there is only one entity 1186 * in this cfs_rq, saving some cycles. 1187 */ 1188 if (cfs_rq->h_nr_queued == 1) 1189 return curr && curr->on_rq ? curr : se; 1190 1191 /* 1192 * Picking the ->next buddy will affect latency but not fairness. 1193 */ 1194 if (sched_feat(PICK_BUDDY) && protect && 1195 cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next)) { 1196 /* ->next will never be delayed */ 1197 WARN_ON_ONCE(cfs_rq->next->sched_delayed); 1198 return cfs_rq->next; 1199 } 1200 1201 if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr))) 1202 curr = NULL; 1203 1204 if (curr && protect && protect_slice(curr)) 1205 return curr; 1206 1207 /* Pick the leftmost entity if it's eligible */ 1208 if (se && entity_eligible(cfs_rq, se)) { 1209 best = se; 1210 goto found; 1211 } 1212 1213 /* Heap search for the EEVD entity */ 1214 while (node) { 1215 struct rb_node *left = node->rb_left; 1216 1217 /* 1218 * Eligible entities in left subtree are always better 1219 * choices, since they have earlier deadlines. 1220 */ 1221 if (left && vruntime_eligible(cfs_rq, 1222 __node_2_se(left)->min_vruntime)) { 1223 node = left; 1224 continue; 1225 } 1226 1227 se = __node_2_se(node); 1228 1229 /* 1230 * The left subtree either is empty or has no eligible 1231 * entity, so check the current node since it is the one 1232 * with earliest deadline that might be eligible. 1233 */ 1234 if (entity_eligible(cfs_rq, se)) { 1235 best = se; 1236 break; 1237 } 1238 1239 node = node->rb_right; 1240 } 1241 found: 1242 if (!best || (curr && entity_before(curr, best))) 1243 best = curr; 1244 1245 return best; 1246 } 1247 1248 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq) 1249 { 1250 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root); 1251 1252 if (!last) 1253 return NULL; 1254 1255 return __node_2_se(last); 1256 } 1257 1258 /************************************************************** 1259 * Scheduling class statistics methods: 1260 */ 1261 int sched_update_scaling(void) 1262 { 1263 unsigned int factor = get_update_sysctl_factor(); 1264 1265 #define WRT_SYSCTL(name) \ 1266 (normalized_sysctl_##name = sysctl_##name / (factor)) 1267 WRT_SYSCTL(sched_base_slice); 1268 #undef WRT_SYSCTL 1269 1270 return 0; 1271 } 1272 1273 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se); 1274 1275 /* 1276 * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i 1277 * this is probably good enough. 1278 */ 1279 static bool update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se) 1280 { 1281 if (vruntime_cmp(se->vruntime, "<", se->deadline)) 1282 return false; 1283 1284 /* 1285 * For EEVDF the virtual time slope is determined by w_i (iow. 1286 * nice) while the request time r_i is determined by 1287 * sysctl_sched_base_slice. 1288 */ 1289 if (!se->custom_slice) 1290 se->slice = sysctl_sched_base_slice; 1291 1292 /* 1293 * EEVDF: vd_i = ve_i + r_i / w_i 1294 */ 1295 se->deadline = se->vruntime + calc_delta_fair(se->slice, se); 1296 avg_vruntime(cfs_rq); 1297 1298 /* 1299 * The task has consumed its request, reschedule. 1300 */ 1301 return true; 1302 } 1303 1304 #include "pelt.h" 1305 1306 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu); 1307 static unsigned long task_h_load(struct task_struct *p); 1308 static unsigned long capacity_of(int cpu); 1309 1310 /* Give new sched_entity start runnable values to heavy its load in infant time */ 1311 void init_entity_runnable_average(struct sched_entity *se) 1312 { 1313 struct sched_avg *sa = &se->avg; 1314 1315 memset(sa, 0, sizeof(*sa)); 1316 1317 /* 1318 * Tasks are initialized with full load to be seen as heavy tasks until 1319 * they get a chance to stabilize to their real load level. 1320 * Group entities are initialized with zero load to reflect the fact that 1321 * nothing has been attached to the task group yet. 1322 */ 1323 if (entity_is_task(se)) 1324 sa->load_avg = scale_load_down(se->load.weight); 1325 1326 /* when this task is enqueued, it will contribute to its cfs_rq's load_avg */ 1327 } 1328 1329 /* 1330 * With new tasks being created, their initial util_avgs are extrapolated 1331 * based on the cfs_rq's current util_avg: 1332 * 1333 * util_avg = cfs_rq->avg.util_avg / (cfs_rq->avg.load_avg + 1) 1334 * * se_weight(se) 1335 * 1336 * However, in many cases, the above util_avg does not give a desired 1337 * value. Moreover, the sum of the util_avgs may be divergent, such 1338 * as when the series is a harmonic series. 1339 * 1340 * To solve this problem, we also cap the util_avg of successive tasks to 1341 * only 1/2 of the left utilization budget: 1342 * 1343 * util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n 1344 * 1345 * where n denotes the nth task and cpu_scale the CPU capacity. 1346 * 1347 * For example, for a CPU with 1024 of capacity, a simplest series from 1348 * the beginning would be like: 1349 * 1350 * task util_avg: 512, 256, 128, 64, 32, 16, 8, ... 1351 * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ... 1352 * 1353 * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap) 1354 * if util_avg > util_avg_cap. 1355 */ 1356 void post_init_entity_util_avg(struct task_struct *p) 1357 { 1358 struct sched_entity *se = &p->se; 1359 struct cfs_rq *cfs_rq = cfs_rq_of(se); 1360 struct sched_avg *sa = &se->avg; 1361 long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq))); 1362 long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2; 1363 1364 if (p->sched_class != &fair_sched_class) { 1365 /* 1366 * For !fair tasks do: 1367 * 1368 update_cfs_rq_load_avg(now, cfs_rq); 1369 attach_entity_load_avg(cfs_rq, se); 1370 switched_from_fair(rq, p); 1371 * 1372 * such that the next switched_to_fair() has the 1373 * expected state. 1374 */ 1375 se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq); 1376 return; 1377 } 1378 1379 if (cap > 0) { 1380 if (cfs_rq->avg.util_avg != 0) { 1381 sa->util_avg = cfs_rq->avg.util_avg * se_weight(se); 1382 sa->util_avg /= (cfs_rq->avg.load_avg + 1); 1383 1384 if (sa->util_avg > cap) 1385 sa->util_avg = cap; 1386 } else { 1387 sa->util_avg = cap; 1388 } 1389 } 1390 1391 sa->runnable_avg = sa->util_avg; 1392 } 1393 1394 static inline void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec); 1395 1396 static s64 update_se(struct rq *rq, struct sched_entity *se) 1397 { 1398 u64 now = rq_clock_task(rq); 1399 s64 delta_exec; 1400 1401 delta_exec = now - se->exec_start; 1402 if (unlikely(delta_exec <= 0)) 1403 return delta_exec; 1404 1405 se->exec_start = now; 1406 if (entity_is_task(se)) { 1407 struct task_struct *donor = task_of(se); 1408 struct task_struct *running = rq->curr; 1409 /* 1410 * If se is a task, we account the time against the running 1411 * task, as w/ proxy-exec they may not be the same. 1412 */ 1413 running->se.exec_start = now; 1414 running->se.sum_exec_runtime += delta_exec; 1415 1416 trace_sched_stat_runtime(running, delta_exec); 1417 account_group_exec_runtime(running, delta_exec); 1418 account_mm_sched(rq, running, delta_exec); 1419 1420 /* cgroup time is always accounted against the donor */ 1421 cgroup_account_cputime(donor, delta_exec); 1422 } else { 1423 /* If not task, account the time against donor se */ 1424 se->sum_exec_runtime += delta_exec; 1425 } 1426 1427 if (schedstat_enabled()) { 1428 struct sched_statistics *stats; 1429 1430 stats = __schedstats_from_se(se); 1431 __schedstat_set(stats->exec_max, 1432 max(delta_exec, stats->exec_max)); 1433 } 1434 1435 return delta_exec; 1436 } 1437 1438 #ifdef CONFIG_SCHED_CACHE 1439 1440 /* 1441 * XXX numbers come from a place the sun don't shine -- probably wants to be SD 1442 * tunable or so. 1443 */ 1444 #define EPOCH_PERIOD (HZ / 100) /* 10 ms */ 1445 #define EPOCH_LLC_AFFINITY_TIMEOUT 5 /* 50 ms */ 1446 __read_mostly unsigned int llc_aggr_tolerance = 1; 1447 __read_mostly unsigned int llc_epoch_period = EPOCH_PERIOD; 1448 __read_mostly unsigned int llc_epoch_affinity_timeout = EPOCH_LLC_AFFINITY_TIMEOUT; 1449 __read_mostly unsigned int llc_imb_pct = 20; 1450 __read_mostly unsigned int llc_overaggr_pct = 50; 1451 1452 static int llc_id(int cpu) 1453 { 1454 if (cpu < 0) 1455 return -1; 1456 1457 return per_cpu(sd_llc_id, cpu); 1458 } 1459 1460 static inline int get_sched_cache_scale(int mul) 1461 { 1462 unsigned int tol = READ_ONCE(llc_aggr_tolerance); 1463 1464 if (!tol) 1465 return 0; 1466 1467 if (tol >= 100) 1468 return INT_MAX; 1469 1470 return (1 + (tol - 1) * mul); 1471 } 1472 1473 static bool exceed_llc_capacity(struct mm_struct *mm, int cpu) 1474 { 1475 #ifdef CONFIG_NUMA_BALANCING 1476 unsigned long llc, footprint; 1477 struct sched_domain *sd; 1478 int scale; 1479 1480 guard(rcu)(); 1481 1482 sd = rcu_dereference_sched_domain(cpu_rq(cpu)->sd); 1483 if (!sd) 1484 return true; 1485 1486 if (static_branch_likely(&sched_numa_balancing)) { 1487 /* 1488 * TBD: RDT exclusive LLC ways reserved should be 1489 * excluded. 1490 */ 1491 llc = sd->llc_bytes; 1492 footprint = READ_ONCE(mm->sc_stat.footprint); 1493 1494 /* 1495 * Scale the LLC size by 256*llc_aggr_tolerance 1496 * and compare it to the task's footprint. 1497 * 1498 * Suppose the L3 size is 32MB. If the 1499 * llc_aggr_tolerance is 1: 1500 * When the footprint is larger than 32MB, the 1501 * process is regarded as exceeding the LLC 1502 * capacity. If the llc_aggr_tolerance is 99: 1503 * When the footprint is larger than 784GB, the 1504 * process is regarded as exceeding the LLC 1505 * capacity: 1506 * 784GB = (1 + (99 - 1) * 256) * 32MB 1507 * If the llc_aggr_tolerance is 100: 1508 * ignore the footprint and do the aggregation 1509 * anyway. 1510 */ 1511 scale = get_sched_cache_scale(256); 1512 if (scale == INT_MAX) 1513 return false; 1514 1515 return ((llc * (u64)scale) < (footprint * PAGE_SIZE)); 1516 } 1517 #endif 1518 return false; 1519 } 1520 1521 static bool invalid_llc_nr(struct mm_struct *mm, struct task_struct *p, 1522 int cpu) 1523 { 1524 int scale; 1525 1526 if (get_nr_threads(p) <= 1) 1527 return true; 1528 1529 /* 1530 * Scale the number of 'cores' in a LLC by llc_aggr_tolerance 1531 * and compare it to the task's active threads. 1532 */ 1533 scale = get_sched_cache_scale(1); 1534 if (scale == INT_MAX) 1535 return false; 1536 1537 return !fits_capacity((mm->sc_stat.nr_running_avg * cpu_smt_num_threads), 1538 (scale * per_cpu(sd_llc_size, cpu))); 1539 } 1540 1541 static void account_llc_enqueue(struct rq *rq, struct task_struct *p) 1542 { 1543 int pref_llc, pref_llc_queued; 1544 struct sched_domain *sd; 1545 1546 pref_llc = p->preferred_llc; 1547 if (pref_llc < 0) 1548 return; 1549 1550 pref_llc_queued = (pref_llc == task_llc(p)); 1551 rq->nr_llc_running++; 1552 rq->nr_pref_llc_running += pref_llc_queued; 1553 1554 /* 1555 * Record whether p is enqueued on its preferred 1556 * LLC, in order to pair with account_llc_dequeue() 1557 * to maintain a consistent nr_pref_llc_running per 1558 * runqueue. 1559 * This is necessary because a race condition exists: 1560 * after a task is enqueued on a runqueue, task_llc(p) 1561 * may change due to CPU hotplug. Therefore, checking 1562 * task_llc(p) to determine whether the task is being 1563 * dequeued from its preferred LLC is unreliable and 1564 * can cause inconsistent values - checking the 1565 * p->pref_llc_queued in account_llc_dequeue() would 1566 * be reliable. 1567 */ 1568 p->pref_llc_queued = pref_llc_queued; 1569 1570 sd = rcu_dereference_all(rq->sd); 1571 if (sd && (unsigned int)pref_llc < sd->llc_max) 1572 sd->llc_counts[pref_llc]++; 1573 } 1574 1575 static void account_llc_dequeue(struct rq *rq, struct task_struct *p) 1576 { 1577 struct sched_domain *sd; 1578 int pref_llc; 1579 1580 pref_llc = p->preferred_llc; 1581 if (pref_llc < 0) 1582 return; 1583 1584 rq->nr_llc_running--; 1585 if (p->pref_llc_queued) { 1586 rq->nr_pref_llc_running--; 1587 /* 1588 * Update the status in case 1589 * other logic might query 1590 * this. 1591 */ 1592 p->pref_llc_queued = 0; 1593 } 1594 1595 sd = rcu_dereference_all(rq->sd); 1596 if (sd && (unsigned int)pref_llc < sd->llc_max) { 1597 /* 1598 * There is a race condition between dequeue 1599 * and CPU hotplug. After a task has been enqueued 1600 * on CPUx, a CPU hotplug event occurs, and all online 1601 * CPUs (including CPUx) rebuild their sched_domains 1602 * and reset statistics to zero(including sd->llc_counts). 1603 * This can cause temporary undercount and we have to 1604 * check for such underflow in sd->llc_counts. 1605 * 1606 * This undercount is temporary and accurate accounting 1607 * will resume once the rq has a chance to be idle. 1608 */ 1609 if (sd->llc_counts[pref_llc]) 1610 sd->llc_counts[pref_llc]--; 1611 } 1612 } 1613 1614 void mm_init_sched(struct mm_struct *mm, 1615 struct sched_cache_time __percpu *_pcpu_sched) 1616 { 1617 unsigned long epoch = 0; 1618 int i; 1619 1620 for_each_possible_cpu(i) { 1621 struct sched_cache_time *pcpu_sched = per_cpu_ptr(_pcpu_sched, i); 1622 struct rq *rq = cpu_rq(i); 1623 1624 pcpu_sched->runtime = 0; 1625 /* a slightly stale cpu epoch is acceptible */ 1626 pcpu_sched->epoch = rq->cpu_epoch; 1627 epoch = rq->cpu_epoch; 1628 } 1629 1630 raw_spin_lock_init(&mm->sc_stat.lock); 1631 mm->sc_stat.epoch = epoch; 1632 mm->sc_stat.cpu = -1; 1633 mm->sc_stat.next_scan = jiffies; 1634 mm->sc_stat.nr_running_avg = 0; 1635 mm->sc_stat.footprint = 0; 1636 /* 1637 * The update to mm->sc_stat should not be reordered 1638 * before initialization to mm's other fields, in case 1639 * the readers may get invalid mm_sched_epoch, etc. 1640 */ 1641 smp_store_release(&mm->sc_stat.pcpu_sched, _pcpu_sched); 1642 } 1643 1644 /* because why would C be fully specified */ 1645 static __always_inline void __shr_u64(u64 *val, unsigned int n) 1646 { 1647 if (n >= 64) { 1648 *val = 0; 1649 return; 1650 } 1651 *val >>= n; 1652 } 1653 1654 static inline void __update_mm_sched(struct rq *rq, 1655 struct sched_cache_time *pcpu_sched) 1656 { 1657 lockdep_assert_held(&rq->cpu_epoch_lock); 1658 1659 unsigned int period = max(READ_ONCE(llc_epoch_period), 1U); 1660 unsigned long n, now = jiffies; 1661 long delta = now - rq->cpu_epoch_next; 1662 1663 if (delta > 0) { 1664 n = (delta + period - 1) / period; 1665 rq->cpu_epoch += n; 1666 rq->cpu_epoch_next += n * period; 1667 __shr_u64(&rq->cpu_runtime, n); 1668 } 1669 1670 n = rq->cpu_epoch - pcpu_sched->epoch; 1671 if (n) { 1672 pcpu_sched->epoch += n; 1673 __shr_u64(&pcpu_sched->runtime, n); 1674 } 1675 } 1676 1677 static unsigned long fraction_mm_sched(struct rq *rq, 1678 struct sched_cache_time *pcpu_sched) 1679 { 1680 guard(raw_spinlock_irqsave)(&rq->cpu_epoch_lock); 1681 1682 __update_mm_sched(rq, pcpu_sched); 1683 1684 /* 1685 * Runtime is a geometric series (r=0.5) and as such will sum to twice 1686 * the accumulation period, this means the multiplcation here should 1687 * not overflow. 1688 */ 1689 return div64_u64(NICE_0_LOAD * pcpu_sched->runtime, rq->cpu_runtime + 1); 1690 } 1691 1692 static int get_pref_llc(struct task_struct *p, struct mm_struct *mm) 1693 { 1694 int mm_sched_llc = -1, mm_sched_cpu; 1695 1696 if (!mm) 1697 return -1; 1698 1699 mm_sched_cpu = READ_ONCE(mm->sc_stat.cpu); 1700 if (mm_sched_cpu != -1) { 1701 mm_sched_llc = llc_id(mm_sched_cpu); 1702 1703 #ifdef CONFIG_NUMA_BALANCING 1704 /* 1705 * Don't assign preferred LLC if it 1706 * conflicts with NUMA balancing. 1707 * This can happen when sched_setnuma() gets 1708 * called, however it is not much of an issue 1709 * because we expect account_mm_sched() to get 1710 * called fairly regularly -- at a higher rate 1711 * than sched_setnuma() at least -- and thus the 1712 * conflict only exists for a short period of time. 1713 */ 1714 if (static_branch_likely(&sched_numa_balancing) && 1715 p->numa_preferred_nid >= 0 && 1716 cpu_to_node(mm_sched_cpu) != p->numa_preferred_nid) 1717 mm_sched_llc = -1; 1718 #endif 1719 } 1720 1721 return mm_sched_llc; 1722 } 1723 1724 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p); 1725 1726 static inline 1727 void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec) 1728 { 1729 struct sched_cache_time *pcpu_sched; 1730 struct mm_struct *mm = p->mm; 1731 int mm_sched_llc = -1; 1732 unsigned long epoch; 1733 1734 if (!sched_cache_enabled()) 1735 return; 1736 1737 if (p->sched_class != &fair_sched_class) 1738 return; 1739 /* 1740 * init_task, kthreads and user thread created 1741 * by user_mode_thread() don't have mm. 1742 */ 1743 if (!mm || !mm->sc_stat.pcpu_sched) 1744 return; 1745 1746 pcpu_sched = per_cpu_ptr(mm->sc_stat.pcpu_sched, cpu_of(rq)); 1747 1748 scoped_guard (raw_spinlock, &rq->cpu_epoch_lock) { 1749 __update_mm_sched(rq, pcpu_sched); 1750 pcpu_sched->runtime += delta_exec; 1751 rq->cpu_runtime += delta_exec; 1752 epoch = rq->cpu_epoch; 1753 } 1754 1755 /* 1756 * If this process hasn't hit task_cache_work() for a while invalidate 1757 * its preferred state. 1758 */ 1759 if ((long)(epoch - READ_ONCE(mm->sc_stat.epoch)) > llc_epoch_affinity_timeout || 1760 invalid_llc_nr(mm, p, cpu_of(rq)) || 1761 exceed_llc_capacity(mm, cpu_of(rq))) { 1762 if (READ_ONCE(mm->sc_stat.cpu) != -1) 1763 WRITE_ONCE(mm->sc_stat.cpu, -1); 1764 } 1765 1766 mm_sched_llc = get_pref_llc(p, mm); 1767 1768 /* task not on rq accounted later in account_entity_enqueue() */ 1769 if (task_running_on_cpu(rq->cpu, p) && 1770 READ_ONCE(p->preferred_llc) != mm_sched_llc) { 1771 account_llc_dequeue(rq, p); 1772 WRITE_ONCE(p->preferred_llc, mm_sched_llc); 1773 account_llc_enqueue(rq, p); 1774 } 1775 } 1776 1777 static void task_tick_cache(struct rq *rq, struct task_struct *p) 1778 { 1779 struct callback_head *work = &p->cache_work; 1780 struct mm_struct *mm = p->mm; 1781 unsigned long epoch; 1782 1783 if (!sched_cache_enabled()) 1784 return; 1785 1786 if (!mm || p->flags & PF_KTHREAD || 1787 !mm->sc_stat.pcpu_sched) 1788 return; 1789 1790 epoch = rq->cpu_epoch; 1791 /* avoid moving backwards */ 1792 if (time_after_eq(mm->sc_stat.epoch, epoch)) 1793 return; 1794 1795 guard(raw_spinlock)(&mm->sc_stat.lock); 1796 1797 if (work->next == work) { 1798 task_work_add(p, work, TWA_RESUME); 1799 WRITE_ONCE(mm->sc_stat.epoch, epoch); 1800 } 1801 } 1802 1803 static void get_scan_cpumasks(cpumask_var_t cpus, struct task_struct *p) 1804 { 1805 #ifdef CONFIG_NUMA_BALANCING 1806 int cpu, curr_cpu, nid, pref_nid; 1807 1808 if (!static_branch_likely(&sched_numa_balancing)) 1809 goto out; 1810 1811 cpu = READ_ONCE(p->mm->sc_stat.cpu); 1812 if (cpu != -1) 1813 nid = cpu_to_node(cpu); 1814 curr_cpu = task_cpu(p); 1815 1816 /* 1817 * Scanning in the preferred NUMA node is ideal. However, the NUMA 1818 * preferred node is per-task rather than per-process. It is possible 1819 * for different threads of the process to have distinct preferred 1820 * nodes; consequently, the process-wide preferred LLC may bounce 1821 * between different nodes. As a workaround, maintain the scan 1822 * CPU mask to also cover the process's current preferred LLC and the 1823 * current running node to mitigate the bouncing risk. 1824 * TBD: numa_group should be considered during task aggregation. 1825 */ 1826 pref_nid = p->numa_preferred_nid; 1827 /* honor the task's preferred node */ 1828 if (pref_nid == NUMA_NO_NODE) 1829 goto out; 1830 1831 cpumask_or(cpus, cpus, cpumask_of_node(pref_nid)); 1832 1833 /* honor the task's preferred LLC CPU */ 1834 if (cpu != -1 && !cpumask_test_cpu(cpu, cpus) && nid != NUMA_NO_NODE) 1835 cpumask_or(cpus, cpus, cpumask_of_node(nid)); 1836 1837 /* make sure the task's current running node is included */ 1838 if (!cpumask_test_cpu(curr_cpu, cpus)) 1839 cpumask_or(cpus, cpus, cpumask_of_node(cpu_to_node(curr_cpu))); 1840 1841 return; 1842 1843 out: 1844 #endif 1845 cpumask_copy(cpus, cpu_online_mask); 1846 } 1847 1848 static inline void update_avg_scale(u64 *avg, u64 sample) 1849 { 1850 int factor = per_cpu(sd_llc_size, raw_smp_processor_id()); 1851 s64 diff = sample - *avg; 1852 u32 divisor; 1853 1854 /* 1855 * Scale the divisor based on the number of CPUs contained 1856 * in the LLC. This scaling ensures smaller LLC domains use 1857 * a smaller divisor to achieve more precise sensitivity to 1858 * changes in nr_running, while larger LLC domains are capped 1859 * at a maximum divisor of 8 which is the default smoothing 1860 * factor of EWMA in update_avg(). 1861 */ 1862 divisor = clamp_t(u32, (factor >> 2), 2, 8); 1863 *avg += div64_s64(diff, divisor); 1864 } 1865 1866 static void task_cache_work(struct callback_head *work) 1867 { 1868 int cpu, m_a_cpu = -1, nr_running = 0, curr_cpu; 1869 unsigned long next_scan, now = jiffies; 1870 struct task_struct *p = current, *cur; 1871 unsigned long curr_m_a_occ = 0; 1872 struct mm_struct *mm = p->mm; 1873 unsigned long m_a_occ = 0; 1874 cpumask_var_t cpus; 1875 1876 WARN_ON_ONCE(work != &p->cache_work); 1877 1878 work->next = work; 1879 1880 if (p->flags & PF_EXITING) 1881 return; 1882 1883 next_scan = READ_ONCE(mm->sc_stat.next_scan); 1884 if (time_before(now, next_scan)) 1885 return; 1886 1887 /* only 1 thread is allowed to scan */ 1888 if (!try_cmpxchg(&mm->sc_stat.next_scan, &next_scan, 1889 now + max_t(unsigned long, 1890 READ_ONCE(llc_epoch_period), 1))) 1891 return; 1892 1893 curr_cpu = task_cpu(p); 1894 if (invalid_llc_nr(mm, p, curr_cpu) || 1895 exceed_llc_capacity(mm, curr_cpu)) { 1896 if (READ_ONCE(mm->sc_stat.cpu) != -1) 1897 WRITE_ONCE(mm->sc_stat.cpu, -1); 1898 1899 return; 1900 } 1901 1902 if (!zalloc_cpumask_var(&cpus, GFP_KERNEL)) 1903 return; 1904 1905 scoped_guard (cpus_read_lock) { 1906 guard(rcu)(); 1907 1908 get_scan_cpumasks(cpus, p); 1909 1910 for_each_cpu(cpu, cpus) { 1911 /* XXX sched_cluster_active */ 1912 struct sched_domain *sd = rcu_dereference_all(per_cpu(sd_llc, cpu)); 1913 unsigned long occ, m_occ = 0, a_occ = 0; 1914 int m_cpu = -1, i; 1915 1916 if (!sd) 1917 continue; 1918 1919 for_each_cpu(i, sched_domain_span(sd)) { 1920 occ = fraction_mm_sched(cpu_rq(i), 1921 per_cpu_ptr(mm->sc_stat.pcpu_sched, i)); 1922 a_occ += occ; 1923 if (occ > m_occ) { 1924 m_occ = occ; 1925 m_cpu = i; 1926 } 1927 1928 cur = rcu_dereference_all(cpu_rq(i)->curr); 1929 if (cur && !(cur->flags & (PF_EXITING | PF_KTHREAD)) && 1930 cur->mm == mm) 1931 nr_running++; 1932 } 1933 1934 /* 1935 * Compare the accumulated occupancy of each LLC. The 1936 * reason for using accumulated occupancy rather than average 1937 * per CPU occupancy is that it works better in asymmetric LLC 1938 * scenarios. 1939 * For example, if there are 2 threads in a 4CPU LLC and 3 1940 * threads in an 8CPU LLC, it might be better to choose the one 1941 * with 3 threads. However, this would not be the case if the 1942 * occupancy is divided by the number of CPUs in an LLC (i.e., 1943 * if average per CPU occupancy is used). 1944 * Besides, NUMA balancing fault statistics behave similarly: 1945 * the total number of faults per node is compared rather than 1946 * the average number of faults per CPU. This strategy is also 1947 * followed here. 1948 */ 1949 if (a_occ > m_a_occ) { 1950 m_a_occ = a_occ; 1951 m_a_cpu = m_cpu; 1952 } 1953 1954 if (llc_id(cpu) == llc_id(READ_ONCE(mm->sc_stat.cpu))) 1955 curr_m_a_occ = a_occ; 1956 1957 cpumask_andnot(cpus, cpus, sched_domain_span(sd)); 1958 } 1959 } 1960 1961 if (m_a_occ > (2 * curr_m_a_occ)) { 1962 /* 1963 * Avoid switching sc_stat.cpu too fast. 1964 * The reason to choose 2X is because: 1965 * 1. It is better to keep the preferred LLC stable, 1966 * rather than changing it frequently and cause migrations 1967 * 2. 2X means the new preferred LLC has at least 1 more 1968 * busy CPU than the old one(200% vs 100%, eg) 1969 * 3. 2X is chosen based on test results, as it delivers 1970 * the optimal performance gain so far. 1971 */ 1972 WRITE_ONCE(mm->sc_stat.cpu, m_a_cpu); 1973 } 1974 1975 update_avg_scale(&mm->sc_stat.nr_running_avg, nr_running); 1976 free_cpumask_var(cpus); 1977 } 1978 1979 void init_sched_mm(struct task_struct *p) 1980 { 1981 struct callback_head *work = &p->cache_work; 1982 1983 init_task_work(work, task_cache_work); 1984 work->next = work; 1985 /* 1986 * Reset new task's preference to avoid 1987 * polluting account_llc_enqueue(). 1988 */ 1989 p->preferred_llc = -1; 1990 } 1991 1992 #else /* CONFIG_SCHED_CACHE */ 1993 1994 static inline void account_mm_sched(struct rq *rq, struct task_struct *p, 1995 s64 delta_exec) { } 1996 1997 void init_sched_mm(struct task_struct *p) { } 1998 1999 static void task_tick_cache(struct rq *rq, struct task_struct *p) { } 2000 2001 static inline int get_pref_llc(struct task_struct *p, 2002 struct mm_struct *mm) 2003 { 2004 return -1; 2005 } 2006 2007 static void account_llc_enqueue(struct rq *rq, struct task_struct *p) {} 2008 2009 static void account_llc_dequeue(struct rq *rq, struct task_struct *p) {} 2010 2011 #endif /* CONFIG_SCHED_CACHE */ 2012 2013 /* 2014 * Used by other classes to account runtime. 2015 */ 2016 s64 update_curr_common(struct rq *rq) 2017 { 2018 return update_se(rq, &rq->donor->se); 2019 } 2020 2021 /* 2022 * Update the current task's runtime statistics. 2023 */ 2024 static void update_curr(struct cfs_rq *cfs_rq) 2025 { 2026 /* 2027 * Note: cfs_rq->curr corresponds to the task picked to 2028 * run (ie: rq->donor.se) which due to proxy-exec may 2029 * not necessarily be the actual task running 2030 * (rq->curr.se). This is easy to confuse! 2031 */ 2032 struct sched_entity *curr = cfs_rq->h_curr; 2033 struct rq *rq = rq_of(cfs_rq); 2034 s64 delta_exec; 2035 bool resched; 2036 2037 if (unlikely(!curr)) 2038 return; 2039 2040 delta_exec = update_se(rq, curr); 2041 if (unlikely(delta_exec <= 0)) 2042 return; 2043 2044 account_cfs_rq_runtime(cfs_rq, delta_exec); 2045 2046 if (!entity_is_task(curr)) 2047 return; 2048 2049 cfs_rq = &rq->cfs; 2050 2051 curr->vruntime += calc_delta_fair(delta_exec, curr); 2052 resched = update_deadline(cfs_rq, curr); 2053 2054 /* 2055 * If the fair_server is active, we need to account for the 2056 * fair_server time whether or not the task is running on 2057 * behalf of fair_server or not: 2058 * - If the task is running on behalf of fair_server, we need 2059 * to limit its time based on the assigned runtime. 2060 * - Fair task that runs outside of fair_server should account 2061 * against fair_server such that it can account for this time 2062 * and possibly avoid running this period. 2063 */ 2064 dl_server_update(&rq->fair_server, delta_exec); 2065 2066 if (cfs_rq->h_nr_queued == 1) 2067 return; 2068 2069 if (resched || !protect_slice(curr)) { 2070 resched_curr_lazy(rq); 2071 clear_buddies(cfs_rq, curr); 2072 } 2073 } 2074 2075 static void update_curr_fair(struct rq *rq) 2076 { 2077 struct sched_entity *se = &rq->donor->se; 2078 2079 for_each_sched_entity(se) 2080 update_curr(cfs_rq_of(se)); 2081 } 2082 2083 static inline void 2084 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se) 2085 { 2086 struct sched_statistics *stats; 2087 struct task_struct *p = NULL; 2088 2089 if (!schedstat_enabled()) 2090 return; 2091 2092 stats = __schedstats_from_se(se); 2093 2094 if (entity_is_task(se)) 2095 p = task_of(se); 2096 2097 __update_stats_wait_start(rq_of(cfs_rq), p, stats); 2098 } 2099 2100 static inline void 2101 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se) 2102 { 2103 struct sched_statistics *stats; 2104 struct task_struct *p = NULL; 2105 2106 if (!schedstat_enabled()) 2107 return; 2108 2109 stats = __schedstats_from_se(se); 2110 2111 /* 2112 * When the sched_schedstat changes from 0 to 1, some sched se 2113 * maybe already in the runqueue, the se->statistics.wait_start 2114 * will be 0.So it will let the delta wrong. We need to avoid this 2115 * scenario. 2116 */ 2117 if (unlikely(!schedstat_val(stats->wait_start))) 2118 return; 2119 2120 if (entity_is_task(se)) 2121 p = task_of(se); 2122 2123 __update_stats_wait_end(rq_of(cfs_rq), p, stats); 2124 } 2125 2126 static inline void 2127 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se) 2128 { 2129 struct sched_statistics *stats; 2130 struct task_struct *tsk = NULL; 2131 2132 if (!schedstat_enabled()) 2133 return; 2134 2135 stats = __schedstats_from_se(se); 2136 2137 if (entity_is_task(se)) 2138 tsk = task_of(se); 2139 2140 __update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats); 2141 } 2142 2143 /* 2144 * Task is being enqueued - update stats: 2145 */ 2146 static inline void 2147 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 2148 { 2149 if (!schedstat_enabled()) 2150 return; 2151 2152 /* 2153 * Are we enqueueing a waiting task? (for current tasks 2154 * a dequeue/enqueue event is a NOP) 2155 */ 2156 if (se != cfs_rq->h_curr) 2157 update_stats_wait_start_fair(cfs_rq, se); 2158 2159 if (flags & ENQUEUE_WAKEUP) 2160 update_stats_enqueue_sleeper_fair(cfs_rq, se); 2161 } 2162 2163 static inline void 2164 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 2165 { 2166 2167 if (!schedstat_enabled()) 2168 return; 2169 2170 /* 2171 * Mark the end of the wait period if dequeueing a 2172 * waiting task: 2173 */ 2174 if (se != cfs_rq->h_curr) 2175 update_stats_wait_end_fair(cfs_rq, se); 2176 2177 if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) { 2178 struct task_struct *tsk = task_of(se); 2179 unsigned int state; 2180 2181 /* XXX racy against TTWU */ 2182 state = READ_ONCE(tsk->__state); 2183 if (state & TASK_INTERRUPTIBLE) 2184 __schedstat_set(tsk->stats.sleep_start, 2185 rq_clock(rq_of(cfs_rq))); 2186 if (state & TASK_UNINTERRUPTIBLE) 2187 __schedstat_set(tsk->stats.block_start, 2188 rq_clock(rq_of(cfs_rq))); 2189 } 2190 } 2191 2192 /* 2193 * We are picking a new current task - update its stats: 2194 */ 2195 static inline void 2196 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se) 2197 { 2198 /* 2199 * We are starting a new run period: 2200 */ 2201 se->exec_start = rq_clock_task(rq_of(cfs_rq)); 2202 } 2203 2204 /* Check sched_smt_active before calling this to avoid overheads in fastpaths */ 2205 static inline bool is_core_idle(int cpu) 2206 { 2207 int sibling; 2208 2209 for_each_cpu(sibling, cpu_smt_mask(cpu)) { 2210 if (cpu == sibling) 2211 continue; 2212 2213 if (!idle_cpu(sibling)) 2214 return false; 2215 } 2216 2217 return true; 2218 } 2219 2220 #ifdef CONFIG_NUMA 2221 #define NUMA_IMBALANCE_MIN 2 2222 2223 static inline long 2224 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr) 2225 { 2226 /* 2227 * Allow a NUMA imbalance if busy CPUs is less than the maximum 2228 * threshold. Above this threshold, individual tasks may be contending 2229 * for both memory bandwidth and any shared HT resources. This is an 2230 * approximation as the number of running tasks may not be related to 2231 * the number of busy CPUs due to sched_setaffinity. 2232 */ 2233 if (dst_running > imb_numa_nr) 2234 return imbalance; 2235 2236 /* 2237 * Allow a small imbalance based on a simple pair of communicating 2238 * tasks that remain local when the destination is lightly loaded. 2239 */ 2240 if (imbalance <= NUMA_IMBALANCE_MIN) 2241 return 0; 2242 2243 return imbalance; 2244 } 2245 #endif /* CONFIG_NUMA */ 2246 2247 #ifdef CONFIG_NUMA_BALANCING 2248 /* 2249 * Approximate time to scan a full NUMA task in ms. The task scan period is 2250 * calculated based on the tasks virtual memory size and 2251 * numa_balancing_scan_size. 2252 */ 2253 unsigned int sysctl_numa_balancing_scan_period_min = 1000; 2254 unsigned int sysctl_numa_balancing_scan_period_max = 60000; 2255 2256 /* Portion of address space to scan in MB */ 2257 unsigned int sysctl_numa_balancing_scan_size = 256; 2258 2259 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */ 2260 unsigned int sysctl_numa_balancing_scan_delay = 1000; 2261 2262 /* The page with hint page fault latency < threshold in ms is considered hot */ 2263 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC; 2264 2265 struct numa_group { 2266 refcount_t refcount; 2267 2268 spinlock_t lock; /* nr_tasks, tasks */ 2269 int nr_tasks; 2270 pid_t gid; 2271 int active_nodes; 2272 2273 struct rcu_head rcu; 2274 unsigned long total_faults; 2275 unsigned long max_faults_cpu; 2276 /* 2277 * faults[] array is split into two regions: faults_mem and faults_cpu. 2278 * 2279 * Faults_cpu is used to decide whether memory should move 2280 * towards the CPU. As a consequence, these stats are weighted 2281 * more by CPU use than by memory faults. 2282 */ 2283 unsigned long faults[]; 2284 }; 2285 2286 /* 2287 * For functions that can be called in multiple contexts that permit reading 2288 * ->numa_group (see struct task_struct for locking rules). 2289 */ 2290 static struct numa_group *deref_task_numa_group(struct task_struct *p) 2291 { 2292 return rcu_dereference_check(p->numa_group, p == current || 2293 (lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu))); 2294 } 2295 2296 static struct numa_group *deref_curr_numa_group(struct task_struct *p) 2297 { 2298 return rcu_dereference_protected(p->numa_group, p == current); 2299 } 2300 2301 static inline unsigned long group_faults_priv(struct numa_group *ng); 2302 static inline unsigned long group_faults_shared(struct numa_group *ng); 2303 2304 static unsigned int task_nr_scan_windows(struct task_struct *p) 2305 { 2306 unsigned long rss = 0; 2307 unsigned long nr_scan_pages; 2308 2309 /* 2310 * Calculations based on RSS as non-present and empty pages are skipped 2311 * by the PTE scanner and NUMA hinting faults should be trapped based 2312 * on resident pages 2313 */ 2314 nr_scan_pages = MB_TO_PAGES(sysctl_numa_balancing_scan_size); 2315 rss = get_mm_rss(p->mm); 2316 if (!rss) 2317 rss = nr_scan_pages; 2318 2319 rss = round_up(rss, nr_scan_pages); 2320 return rss / nr_scan_pages; 2321 } 2322 2323 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */ 2324 #define MAX_SCAN_WINDOW 2560 2325 2326 static unsigned int task_scan_min(struct task_struct *p) 2327 { 2328 unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size); 2329 unsigned int scan, floor; 2330 unsigned int windows = 1; 2331 2332 if (scan_size < MAX_SCAN_WINDOW) 2333 windows = MAX_SCAN_WINDOW / scan_size; 2334 floor = 1000 / windows; 2335 2336 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p); 2337 return max_t(unsigned int, floor, scan); 2338 } 2339 2340 static unsigned int task_scan_start(struct task_struct *p) 2341 { 2342 unsigned long smin = task_scan_min(p); 2343 unsigned long period = smin; 2344 struct numa_group *ng; 2345 2346 /* Scale the maximum scan period with the amount of shared memory. */ 2347 rcu_read_lock(); 2348 ng = rcu_dereference_all(p->numa_group); 2349 if (ng) { 2350 unsigned long shared = group_faults_shared(ng); 2351 unsigned long private = group_faults_priv(ng); 2352 2353 period *= refcount_read(&ng->refcount); 2354 period *= shared + 1; 2355 period /= private + shared + 1; 2356 } 2357 rcu_read_unlock(); 2358 2359 return max(smin, period); 2360 } 2361 2362 static unsigned int task_scan_max(struct task_struct *p) 2363 { 2364 unsigned long smin = task_scan_min(p); 2365 unsigned long smax; 2366 struct numa_group *ng; 2367 2368 /* Watch for min being lower than max due to floor calculations */ 2369 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p); 2370 2371 /* Scale the maximum scan period with the amount of shared memory. */ 2372 ng = deref_curr_numa_group(p); 2373 if (ng) { 2374 unsigned long shared = group_faults_shared(ng); 2375 unsigned long private = group_faults_priv(ng); 2376 unsigned long period = smax; 2377 2378 period *= refcount_read(&ng->refcount); 2379 period *= shared + 1; 2380 period /= private + shared + 1; 2381 2382 smax = max(smax, period); 2383 } 2384 2385 return max(smin, smax); 2386 } 2387 2388 static void account_numa_enqueue(struct rq *rq, struct task_struct *p) 2389 { 2390 rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE); 2391 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p)); 2392 } 2393 2394 static void account_numa_dequeue(struct rq *rq, struct task_struct *p) 2395 { 2396 rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE); 2397 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p)); 2398 } 2399 2400 /* Shared or private faults. */ 2401 #define NR_NUMA_HINT_FAULT_TYPES 2 2402 2403 /* Memory and CPU locality */ 2404 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2) 2405 2406 /* Averaged statistics, and temporary buffers. */ 2407 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2) 2408 2409 pid_t task_numa_group_id(struct task_struct *p) 2410 { 2411 struct numa_group *ng; 2412 pid_t gid = 0; 2413 2414 rcu_read_lock(); 2415 ng = rcu_dereference_all(p->numa_group); 2416 if (ng) 2417 gid = ng->gid; 2418 rcu_read_unlock(); 2419 2420 return gid; 2421 } 2422 2423 /* 2424 * The averaged statistics, shared & private, memory & CPU, 2425 * occupy the first half of the array. The second half of the 2426 * array is for current counters, which are averaged into the 2427 * first set by task_numa_placement. 2428 */ 2429 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv) 2430 { 2431 return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv; 2432 } 2433 2434 static inline unsigned long task_faults(struct task_struct *p, int nid) 2435 { 2436 if (!p->numa_faults) 2437 return 0; 2438 2439 return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] + 2440 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)]; 2441 } 2442 2443 static inline unsigned long group_faults(struct task_struct *p, int nid) 2444 { 2445 struct numa_group *ng = deref_task_numa_group(p); 2446 2447 if (!ng) 2448 return 0; 2449 2450 return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] + 2451 ng->faults[task_faults_idx(NUMA_MEM, nid, 1)]; 2452 } 2453 2454 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid) 2455 { 2456 return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] + 2457 group->faults[task_faults_idx(NUMA_CPU, nid, 1)]; 2458 } 2459 2460 static inline unsigned long group_faults_priv(struct numa_group *ng) 2461 { 2462 unsigned long faults = 0; 2463 int node; 2464 2465 for_each_online_node(node) { 2466 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)]; 2467 } 2468 2469 return faults; 2470 } 2471 2472 static inline unsigned long group_faults_shared(struct numa_group *ng) 2473 { 2474 unsigned long faults = 0; 2475 int node; 2476 2477 for_each_online_node(node) { 2478 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)]; 2479 } 2480 2481 return faults; 2482 } 2483 2484 /* 2485 * A node triggering more than 1/3 as many NUMA faults as the maximum is 2486 * considered part of a numa group's pseudo-interleaving set. Migrations 2487 * between these nodes are slowed down, to allow things to settle down. 2488 */ 2489 #define ACTIVE_NODE_FRACTION 3 2490 2491 static bool numa_is_active_node(int nid, struct numa_group *ng) 2492 { 2493 return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu; 2494 } 2495 2496 /* Handle placement on systems where not all nodes are directly connected. */ 2497 static unsigned long score_nearby_nodes(struct task_struct *p, int nid, 2498 int lim_dist, bool task) 2499 { 2500 unsigned long score = 0; 2501 int node, max_dist; 2502 2503 /* 2504 * All nodes are directly connected, and the same distance 2505 * from each other. No need for fancy placement algorithms. 2506 */ 2507 if (sched_numa_topology_type == NUMA_DIRECT) 2508 return 0; 2509 2510 /* sched_max_numa_distance may be changed in parallel. */ 2511 max_dist = READ_ONCE(sched_max_numa_distance); 2512 /* 2513 * This code is called for each node, introducing N^2 complexity, 2514 * which should be OK given the number of nodes rarely exceeds 8. 2515 */ 2516 for_each_online_node(node) { 2517 unsigned long faults; 2518 int dist = node_distance(nid, node); 2519 2520 /* 2521 * The furthest away nodes in the system are not interesting 2522 * for placement; nid was already counted. 2523 */ 2524 if (dist >= max_dist || node == nid) 2525 continue; 2526 2527 /* 2528 * On systems with a backplane NUMA topology, compare groups 2529 * of nodes, and move tasks towards the group with the most 2530 * memory accesses. When comparing two nodes at distance 2531 * "hoplimit", only nodes closer by than "hoplimit" are part 2532 * of each group. Skip other nodes. 2533 */ 2534 if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist) 2535 continue; 2536 2537 /* Add up the faults from nearby nodes. */ 2538 if (task) 2539 faults = task_faults(p, node); 2540 else 2541 faults = group_faults(p, node); 2542 2543 /* 2544 * On systems with a glueless mesh NUMA topology, there are 2545 * no fixed "groups of nodes". Instead, nodes that are not 2546 * directly connected bounce traffic through intermediate 2547 * nodes; a numa_group can occupy any set of nodes. 2548 * The further away a node is, the less the faults count. 2549 * This seems to result in good task placement. 2550 */ 2551 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) { 2552 faults *= (max_dist - dist); 2553 faults /= (max_dist - LOCAL_DISTANCE); 2554 } 2555 2556 score += faults; 2557 } 2558 2559 return score; 2560 } 2561 2562 /* 2563 * These return the fraction of accesses done by a particular task, or 2564 * task group, on a particular numa node. The group weight is given a 2565 * larger multiplier, in order to group tasks together that are almost 2566 * evenly spread out between numa nodes. 2567 */ 2568 static inline unsigned long task_weight(struct task_struct *p, int nid, 2569 int dist) 2570 { 2571 unsigned long faults, total_faults; 2572 2573 if (!p->numa_faults) 2574 return 0; 2575 2576 total_faults = p->total_numa_faults; 2577 2578 if (!total_faults) 2579 return 0; 2580 2581 faults = task_faults(p, nid); 2582 faults += score_nearby_nodes(p, nid, dist, true); 2583 2584 return 1000 * faults / total_faults; 2585 } 2586 2587 static inline unsigned long group_weight(struct task_struct *p, int nid, 2588 int dist) 2589 { 2590 struct numa_group *ng = deref_task_numa_group(p); 2591 unsigned long faults, total_faults; 2592 2593 if (!ng) 2594 return 0; 2595 2596 total_faults = ng->total_faults; 2597 2598 if (!total_faults) 2599 return 0; 2600 2601 faults = group_faults(p, nid); 2602 faults += score_nearby_nodes(p, nid, dist, false); 2603 2604 return 1000 * faults / total_faults; 2605 } 2606 2607 /* 2608 * If memory tiering mode is enabled, cpupid of slow memory page is 2609 * used to record scan time instead of CPU and PID. When tiering mode 2610 * is disabled at run time, the scan time (in cpupid) will be 2611 * interpreted as CPU and PID. So CPU needs to be checked to avoid to 2612 * access out of array bound. 2613 */ 2614 static inline bool cpupid_valid(int cpupid) 2615 { 2616 return cpupid_to_cpu(cpupid) < nr_cpu_ids; 2617 } 2618 2619 /* 2620 * For memory tiering mode, if there are enough free pages (more than 2621 * enough watermark defined here) in fast memory node, to take full 2622 * advantage of fast memory capacity, all recently accessed slow 2623 * memory pages will be migrated to fast memory node without 2624 * considering hot threshold. 2625 */ 2626 static bool pgdat_free_space_enough(struct pglist_data *pgdat) 2627 { 2628 int z; 2629 unsigned long enough_wmark; 2630 2631 enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT, 2632 pgdat->node_present_pages >> 4); 2633 for (z = pgdat->nr_zones - 1; z >= 0; z--) { 2634 struct zone *zone = pgdat->node_zones + z; 2635 2636 if (!populated_zone(zone)) 2637 continue; 2638 2639 if (zone_watermark_ok(zone, 0, 2640 promo_wmark_pages(zone) + enough_wmark, 2641 ZONE_MOVABLE, 0)) 2642 return true; 2643 } 2644 return false; 2645 } 2646 2647 /* 2648 * For memory tiering mode, when page tables are scanned, the scan 2649 * time will be recorded in struct page in addition to make page 2650 * PROT_NONE for slow memory page. So when the page is accessed, in 2651 * hint page fault handler, the hint page fault latency is calculated 2652 * via, 2653 * 2654 * hint page fault latency = hint page fault time - scan time 2655 * 2656 * The smaller the hint page fault latency, the higher the possibility 2657 * for the page to be hot. 2658 */ 2659 static int numa_hint_fault_latency(struct folio *folio) 2660 { 2661 int last_time, time; 2662 2663 time = jiffies_to_msecs(jiffies); 2664 last_time = folio_xchg_access_time(folio, time); 2665 2666 return (time - last_time) & PAGE_ACCESS_TIME_MASK; 2667 } 2668 2669 /* 2670 * For memory tiering mode, too high promotion/demotion throughput may 2671 * hurt application latency. So we provide a mechanism to rate limit 2672 * the number of pages that are tried to be promoted. 2673 */ 2674 static bool numa_promotion_rate_limit(struct pglist_data *pgdat, 2675 unsigned long rate_limit, int nr) 2676 { 2677 unsigned long nr_cand; 2678 unsigned int now, start; 2679 2680 now = jiffies_to_msecs(jiffies); 2681 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr); 2682 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE); 2683 start = pgdat->nbp_rl_start; 2684 if (now - start > MSEC_PER_SEC && 2685 cmpxchg(&pgdat->nbp_rl_start, start, now) == start) 2686 pgdat->nbp_rl_nr_cand = nr_cand; 2687 if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit) 2688 return true; 2689 return false; 2690 } 2691 2692 #define NUMA_MIGRATION_ADJUST_STEPS 16 2693 2694 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat, 2695 unsigned long rate_limit, 2696 unsigned int ref_th) 2697 { 2698 unsigned int now, start, th_period, unit_th, th; 2699 unsigned long nr_cand, ref_cand, diff_cand; 2700 2701 now = jiffies_to_msecs(jiffies); 2702 th_period = sysctl_numa_balancing_scan_period_max; 2703 start = pgdat->nbp_th_start; 2704 if (now - start > th_period && 2705 cmpxchg(&pgdat->nbp_th_start, start, now) == start) { 2706 ref_cand = rate_limit * 2707 sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC; 2708 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE); 2709 diff_cand = nr_cand - pgdat->nbp_th_nr_cand; 2710 unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS; 2711 th = pgdat->nbp_threshold ? : ref_th; 2712 if (diff_cand > ref_cand * 11 / 10) 2713 th = max(th - unit_th, unit_th); 2714 else if (diff_cand < ref_cand * 9 / 10) 2715 th = min(th + unit_th, ref_th * 2); 2716 pgdat->nbp_th_nr_cand = nr_cand; 2717 pgdat->nbp_threshold = th; 2718 } 2719 } 2720 2721 bool should_numa_migrate_memory(struct task_struct *p, struct folio *folio, 2722 int src_nid, int dst_cpu) 2723 { 2724 struct numa_group *ng = deref_curr_numa_group(p); 2725 int dst_nid = cpu_to_node(dst_cpu); 2726 int last_cpupid, this_cpupid; 2727 2728 /* 2729 * Cannot migrate to memoryless nodes. 2730 */ 2731 if (!node_state(dst_nid, N_MEMORY)) 2732 return false; 2733 2734 /* 2735 * The pages in slow memory node should be migrated according 2736 * to hot/cold instead of private/shared. 2737 */ 2738 if (folio_use_access_time(folio)) { 2739 struct pglist_data *pgdat; 2740 unsigned long rate_limit; 2741 unsigned int latency, th, def_th; 2742 long nr = folio_nr_pages(folio); 2743 2744 pgdat = NODE_DATA(dst_nid); 2745 if (pgdat_free_space_enough(pgdat)) { 2746 /* workload changed, reset hot threshold */ 2747 pgdat->nbp_threshold = 0; 2748 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE_NRL, nr); 2749 return true; 2750 } 2751 2752 def_th = sysctl_numa_balancing_hot_threshold; 2753 rate_limit = MB_TO_PAGES(sysctl_numa_balancing_promote_rate_limit); 2754 numa_promotion_adjust_threshold(pgdat, rate_limit, def_th); 2755 2756 th = pgdat->nbp_threshold ? : def_th; 2757 latency = numa_hint_fault_latency(folio); 2758 if (latency >= th) 2759 return false; 2760 2761 return !numa_promotion_rate_limit(pgdat, rate_limit, nr); 2762 } 2763 2764 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid); 2765 last_cpupid = folio_xchg_last_cpupid(folio, this_cpupid); 2766 2767 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) && 2768 !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid)) 2769 return false; 2770 2771 /* 2772 * Allow first faults or private faults to migrate immediately early in 2773 * the lifetime of a task. The magic number 4 is based on waiting for 2774 * two full passes of the "multi-stage node selection" test that is 2775 * executed below. 2776 */ 2777 if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) && 2778 (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid))) 2779 return true; 2780 2781 /* 2782 * Multi-stage node selection is used in conjunction with a periodic 2783 * migration fault to build a temporal task<->page relation. By using 2784 * a two-stage filter we remove short/unlikely relations. 2785 * 2786 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate 2787 * a task's usage of a particular page (n_p) per total usage of this 2788 * page (n_t) (in a given time-span) to a probability. 2789 * 2790 * Our periodic faults will sample this probability and getting the 2791 * same result twice in a row, given these samples are fully 2792 * independent, is then given by P(n)^2, provided our sample period 2793 * is sufficiently short compared to the usage pattern. 2794 * 2795 * This quadric squishes small probabilities, making it less likely we 2796 * act on an unlikely task<->page relation. 2797 */ 2798 if (!cpupid_pid_unset(last_cpupid) && 2799 cpupid_to_nid(last_cpupid) != dst_nid) 2800 return false; 2801 2802 /* Always allow migrate on private faults */ 2803 if (cpupid_match_pid(p, last_cpupid)) 2804 return true; 2805 2806 /* A shared fault, but p->numa_group has not been set up yet. */ 2807 if (!ng) 2808 return true; 2809 2810 /* 2811 * Destination node is much more heavily used than the source 2812 * node? Allow migration. 2813 */ 2814 if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) * 2815 ACTIVE_NODE_FRACTION) 2816 return true; 2817 2818 /* 2819 * Distribute memory according to CPU & memory use on each node, 2820 * with 3/4 hysteresis to avoid unnecessary memory migrations: 2821 * 2822 * faults_cpu(dst) 3 faults_cpu(src) 2823 * --------------- * - > --------------- 2824 * faults_mem(dst) 4 faults_mem(src) 2825 */ 2826 return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 > 2827 group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4; 2828 } 2829 2830 /* 2831 * 'numa_type' describes the node at the moment of load balancing. 2832 */ 2833 enum numa_type { 2834 /* The node has spare capacity that can be used to run more tasks. */ 2835 node_has_spare = 0, 2836 /* 2837 * The node is fully used and the tasks don't compete for more CPU 2838 * cycles. Nevertheless, some tasks might wait before running. 2839 */ 2840 node_fully_busy, 2841 /* 2842 * The node is overloaded and can't provide expected CPU cycles to all 2843 * tasks. 2844 */ 2845 node_overloaded 2846 }; 2847 2848 /* Cached statistics for all CPUs within a node */ 2849 struct numa_stats { 2850 unsigned long load; 2851 unsigned long runnable; 2852 unsigned long util; 2853 /* Total compute capacity of CPUs on a node */ 2854 unsigned long compute_capacity; 2855 unsigned int nr_running; 2856 unsigned int weight; 2857 enum numa_type node_type; 2858 int idle_cpu; 2859 }; 2860 2861 struct task_numa_env { 2862 struct task_struct *p; 2863 2864 int src_cpu, src_nid; 2865 int dst_cpu, dst_nid; 2866 int imb_numa_nr; 2867 2868 struct numa_stats src_stats, dst_stats; 2869 2870 int imbalance_pct; 2871 int dist; 2872 2873 struct task_struct *best_task; 2874 long best_imp; 2875 int best_cpu; 2876 }; 2877 2878 static unsigned long cpu_load(struct rq *rq); 2879 static unsigned long cpu_runnable(struct rq *rq); 2880 2881 static inline enum 2882 numa_type numa_classify(unsigned int imbalance_pct, 2883 struct numa_stats *ns) 2884 { 2885 if ((ns->nr_running > ns->weight) && 2886 (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) || 2887 ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100)))) 2888 return node_overloaded; 2889 2890 if ((ns->nr_running < ns->weight) || 2891 (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) && 2892 ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100)))) 2893 return node_has_spare; 2894 2895 return node_fully_busy; 2896 } 2897 2898 /* Forward declarations of select_idle_sibling helpers */ 2899 static inline bool test_idle_cores(int cpu); 2900 static inline int numa_idle_core(int idle_core, int cpu) 2901 { 2902 if (!sched_smt_active() || 2903 idle_core >= 0 || !test_idle_cores(cpu)) 2904 return idle_core; 2905 2906 /* 2907 * Prefer cores instead of packing HT siblings 2908 * and triggering future load balancing. 2909 */ 2910 if (is_core_idle(cpu)) 2911 idle_core = cpu; 2912 2913 return idle_core; 2914 } 2915 2916 /* 2917 * Gather all necessary information to make NUMA balancing placement 2918 * decisions that are compatible with standard load balancer. This 2919 * borrows code and logic from update_sg_lb_stats but sharing a 2920 * common implementation is impractical. 2921 */ 2922 static void update_numa_stats(struct task_numa_env *env, 2923 struct numa_stats *ns, int nid, 2924 bool find_idle) 2925 { 2926 int cpu, idle_core = -1; 2927 2928 memset(ns, 0, sizeof(*ns)); 2929 ns->idle_cpu = -1; 2930 2931 rcu_read_lock(); 2932 for_each_cpu(cpu, cpumask_of_node(nid)) { 2933 struct rq *rq = cpu_rq(cpu); 2934 2935 ns->load += cpu_load(rq); 2936 ns->runnable += cpu_runnable(rq); 2937 ns->util += cpu_util_cfs(cpu); 2938 ns->nr_running += rq->cfs.h_nr_runnable; 2939 ns->compute_capacity += capacity_of(cpu); 2940 2941 if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) { 2942 if (READ_ONCE(rq->numa_migrate_on) || 2943 !cpumask_test_cpu(cpu, env->p->cpus_ptr)) 2944 continue; 2945 2946 if (ns->idle_cpu == -1) 2947 ns->idle_cpu = cpu; 2948 2949 idle_core = numa_idle_core(idle_core, cpu); 2950 } 2951 } 2952 rcu_read_unlock(); 2953 2954 ns->weight = cpumask_weight(cpumask_of_node(nid)); 2955 2956 ns->node_type = numa_classify(env->imbalance_pct, ns); 2957 2958 if (idle_core >= 0) 2959 ns->idle_cpu = idle_core; 2960 } 2961 2962 static void task_numa_assign(struct task_numa_env *env, 2963 struct task_struct *p, long imp) 2964 { 2965 struct rq *rq = cpu_rq(env->dst_cpu); 2966 2967 /* Check if run-queue part of active NUMA balance. */ 2968 if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) { 2969 int cpu; 2970 int start = env->dst_cpu; 2971 2972 /* Find alternative idle CPU. */ 2973 for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) { 2974 if (cpu == env->best_cpu || !idle_cpu(cpu) || 2975 !cpumask_test_cpu(cpu, env->p->cpus_ptr)) { 2976 continue; 2977 } 2978 2979 env->dst_cpu = cpu; 2980 rq = cpu_rq(env->dst_cpu); 2981 if (!xchg(&rq->numa_migrate_on, 1)) 2982 goto assign; 2983 } 2984 2985 /* Failed to find an alternative idle CPU */ 2986 return; 2987 } 2988 2989 assign: 2990 /* 2991 * Clear previous best_cpu/rq numa-migrate flag, since task now 2992 * found a better CPU to move/swap. 2993 */ 2994 if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) { 2995 rq = cpu_rq(env->best_cpu); 2996 WRITE_ONCE(rq->numa_migrate_on, 0); 2997 } 2998 2999 if (env->best_task) 3000 put_task_struct(env->best_task); 3001 if (p) 3002 get_task_struct(p); 3003 3004 env->best_task = p; 3005 env->best_imp = imp; 3006 env->best_cpu = env->dst_cpu; 3007 } 3008 3009 static bool load_too_imbalanced(long src_load, long dst_load, 3010 struct task_numa_env *env) 3011 { 3012 long imb, old_imb; 3013 long orig_src_load, orig_dst_load; 3014 long src_capacity, dst_capacity; 3015 3016 /* 3017 * The load is corrected for the CPU capacity available on each node. 3018 * 3019 * src_load dst_load 3020 * ------------ vs --------- 3021 * src_capacity dst_capacity 3022 */ 3023 src_capacity = env->src_stats.compute_capacity; 3024 dst_capacity = env->dst_stats.compute_capacity; 3025 3026 imb = abs(dst_load * src_capacity - src_load * dst_capacity); 3027 3028 orig_src_load = env->src_stats.load; 3029 orig_dst_load = env->dst_stats.load; 3030 3031 old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity); 3032 3033 /* Would this change make things worse? */ 3034 return (imb > old_imb); 3035 } 3036 3037 /* 3038 * Maximum NUMA importance can be 1998 (2*999); 3039 * SMALLIMP @ 30 would be close to 1998/64. 3040 * Used to deter task migration. 3041 */ 3042 #define SMALLIMP 30 3043 3044 /* 3045 * This checks if the overall compute and NUMA accesses of the system would 3046 * be improved if the source tasks was migrated to the target dst_cpu taking 3047 * into account that it might be best if task running on the dst_cpu should 3048 * be exchanged with the source task 3049 */ 3050 static bool task_numa_compare(struct task_numa_env *env, 3051 long taskimp, long groupimp, bool maymove) 3052 { 3053 struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p); 3054 struct rq *dst_rq = cpu_rq(env->dst_cpu); 3055 long imp = p_ng ? groupimp : taskimp; 3056 struct task_struct *cur; 3057 long src_load, dst_load; 3058 int dist = env->dist; 3059 long moveimp = imp; 3060 long load; 3061 bool stopsearch = false; 3062 3063 if (READ_ONCE(dst_rq->numa_migrate_on)) 3064 return false; 3065 3066 rcu_read_lock(); 3067 cur = rcu_dereference_all(dst_rq->curr); 3068 if (cur && ((cur->flags & (PF_EXITING | PF_KTHREAD)) || 3069 !cur->mm)) 3070 cur = NULL; 3071 3072 /* 3073 * Because we have preemption enabled we can get migrated around and 3074 * end try selecting ourselves (current == env->p) as a swap candidate. 3075 */ 3076 if (cur == env->p) { 3077 stopsearch = true; 3078 goto unlock; 3079 } 3080 3081 if (!cur) { 3082 if (maymove && moveimp >= env->best_imp) 3083 goto assign; 3084 else 3085 goto unlock; 3086 } 3087 3088 /* Skip this swap candidate if cannot move to the source cpu. */ 3089 if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr)) 3090 goto unlock; 3091 3092 /* 3093 * Skip this swap candidate if it is not moving to its preferred 3094 * node and the best task is. 3095 */ 3096 if (env->best_task && 3097 env->best_task->numa_preferred_nid == env->src_nid && 3098 cur->numa_preferred_nid != env->src_nid) { 3099 goto unlock; 3100 } 3101 3102 /* 3103 * "imp" is the fault differential for the source task between the 3104 * source and destination node. Calculate the total differential for 3105 * the source task and potential destination task. The more negative 3106 * the value is, the more remote accesses that would be expected to 3107 * be incurred if the tasks were swapped. 3108 * 3109 * If dst and source tasks are in the same NUMA group, or not 3110 * in any group then look only at task weights. 3111 */ 3112 cur_ng = rcu_dereference_all(cur->numa_group); 3113 if (cur_ng == p_ng) { 3114 /* 3115 * Do not swap within a group or between tasks that have 3116 * no group if there is spare capacity. Swapping does 3117 * not address the load imbalance and helps one task at 3118 * the cost of punishing another. 3119 */ 3120 if (env->dst_stats.node_type == node_has_spare) 3121 goto unlock; 3122 3123 imp = taskimp + task_weight(cur, env->src_nid, dist) - 3124 task_weight(cur, env->dst_nid, dist); 3125 /* 3126 * Add some hysteresis to prevent swapping the 3127 * tasks within a group over tiny differences. 3128 */ 3129 if (cur_ng) 3130 imp -= imp / 16; 3131 } else { 3132 /* 3133 * Compare the group weights. If a task is all by itself 3134 * (not part of a group), use the task weight instead. 3135 */ 3136 if (cur_ng && p_ng) 3137 imp += group_weight(cur, env->src_nid, dist) - 3138 group_weight(cur, env->dst_nid, dist); 3139 else 3140 imp += task_weight(cur, env->src_nid, dist) - 3141 task_weight(cur, env->dst_nid, dist); 3142 } 3143 3144 /* Discourage picking a task already on its preferred node */ 3145 if (cur->numa_preferred_nid == env->dst_nid) 3146 imp -= imp / 16; 3147 3148 /* 3149 * Encourage picking a task that moves to its preferred node. 3150 * This potentially makes imp larger than it's maximum of 3151 * 1998 (see SMALLIMP and task_weight for why) but in this 3152 * case, it does not matter. 3153 */ 3154 if (cur->numa_preferred_nid == env->src_nid) 3155 imp += imp / 8; 3156 3157 if (maymove && moveimp > imp && moveimp > env->best_imp) { 3158 imp = moveimp; 3159 cur = NULL; 3160 goto assign; 3161 } 3162 3163 /* 3164 * Prefer swapping with a task moving to its preferred node over a 3165 * task that is not. 3166 */ 3167 if (env->best_task && cur->numa_preferred_nid == env->src_nid && 3168 env->best_task->numa_preferred_nid != env->src_nid) { 3169 goto assign; 3170 } 3171 3172 /* 3173 * If the NUMA importance is less than SMALLIMP, 3174 * task migration might only result in ping pong 3175 * of tasks and also hurt performance due to cache 3176 * misses. 3177 */ 3178 if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2) 3179 goto unlock; 3180 3181 /* 3182 * In the overloaded case, try and keep the load balanced. 3183 */ 3184 load = task_h_load(env->p) - task_h_load(cur); 3185 if (!load) 3186 goto assign; 3187 3188 dst_load = env->dst_stats.load + load; 3189 src_load = env->src_stats.load - load; 3190 3191 if (load_too_imbalanced(src_load, dst_load, env)) 3192 goto unlock; 3193 3194 assign: 3195 /* Evaluate an idle CPU for a task numa move. */ 3196 if (!cur) { 3197 int cpu = env->dst_stats.idle_cpu; 3198 3199 /* Nothing cached so current CPU went idle since the search. */ 3200 if (cpu < 0) 3201 cpu = env->dst_cpu; 3202 3203 /* 3204 * If the CPU is no longer truly idle and the previous best CPU 3205 * is, keep using it. 3206 */ 3207 if (!idle_cpu(cpu) && env->best_cpu >= 0 && 3208 idle_cpu(env->best_cpu)) { 3209 cpu = env->best_cpu; 3210 } 3211 3212 env->dst_cpu = cpu; 3213 } 3214 3215 task_numa_assign(env, cur, imp); 3216 3217 /* 3218 * If a move to idle is allowed because there is capacity or load 3219 * balance improves then stop the search. While a better swap 3220 * candidate may exist, a search is not free. 3221 */ 3222 if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu)) 3223 stopsearch = true; 3224 3225 /* 3226 * If a swap candidate must be identified and the current best task 3227 * moves its preferred node then stop the search. 3228 */ 3229 if (!maymove && env->best_task && 3230 env->best_task->numa_preferred_nid == env->src_nid) { 3231 stopsearch = true; 3232 } 3233 unlock: 3234 rcu_read_unlock(); 3235 3236 return stopsearch; 3237 } 3238 3239 static void task_numa_find_cpu(struct task_numa_env *env, 3240 long taskimp, long groupimp) 3241 { 3242 bool maymove = false; 3243 int cpu; 3244 3245 /* 3246 * If dst node has spare capacity, then check if there is an 3247 * imbalance that would be overruled by the load balancer. 3248 */ 3249 if (env->dst_stats.node_type == node_has_spare) { 3250 unsigned int imbalance; 3251 int src_running, dst_running; 3252 3253 /* 3254 * Would movement cause an imbalance? Note that if src has 3255 * more running tasks that the imbalance is ignored as the 3256 * move improves the imbalance from the perspective of the 3257 * CPU load balancer. 3258 * */ 3259 src_running = env->src_stats.nr_running - 1; 3260 dst_running = env->dst_stats.nr_running + 1; 3261 imbalance = max(0, dst_running - src_running); 3262 imbalance = adjust_numa_imbalance(imbalance, dst_running, 3263 env->imb_numa_nr); 3264 3265 /* Use idle CPU if there is no imbalance */ 3266 if (!imbalance) { 3267 maymove = true; 3268 if (env->dst_stats.idle_cpu >= 0) { 3269 env->dst_cpu = env->dst_stats.idle_cpu; 3270 task_numa_assign(env, NULL, 0); 3271 return; 3272 } 3273 } 3274 } else { 3275 long src_load, dst_load, load; 3276 /* 3277 * If the improvement from just moving env->p direction is better 3278 * than swapping tasks around, check if a move is possible. 3279 */ 3280 load = task_h_load(env->p); 3281 dst_load = env->dst_stats.load + load; 3282 src_load = env->src_stats.load - load; 3283 maymove = !load_too_imbalanced(src_load, dst_load, env); 3284 } 3285 3286 /* Skip CPUs if the source task cannot migrate */ 3287 for_each_cpu_and(cpu, cpumask_of_node(env->dst_nid), env->p->cpus_ptr) { 3288 env->dst_cpu = cpu; 3289 if (task_numa_compare(env, taskimp, groupimp, maymove)) 3290 break; 3291 } 3292 } 3293 3294 static int task_numa_migrate(struct task_struct *p) 3295 { 3296 struct task_numa_env env = { 3297 .p = p, 3298 3299 .src_cpu = task_cpu(p), 3300 .src_nid = task_node(p), 3301 3302 .imbalance_pct = 112, 3303 3304 .best_task = NULL, 3305 .best_imp = 0, 3306 .best_cpu = -1, 3307 }; 3308 unsigned long taskweight, groupweight; 3309 struct sched_domain *sd; 3310 long taskimp, groupimp; 3311 struct numa_group *ng; 3312 struct rq *best_rq; 3313 int nid, ret, dist; 3314 3315 /* 3316 * Pick the lowest SD_NUMA domain, as that would have the smallest 3317 * imbalance and would be the first to start moving tasks about. 3318 * 3319 * And we want to avoid any moving of tasks about, as that would create 3320 * random movement of tasks -- counter the numa conditions we're trying 3321 * to satisfy here. 3322 */ 3323 rcu_read_lock(); 3324 sd = rcu_dereference_all(per_cpu(sd_numa, env.src_cpu)); 3325 if (sd) { 3326 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2; 3327 env.imb_numa_nr = sd->imb_numa_nr; 3328 } 3329 rcu_read_unlock(); 3330 3331 /* 3332 * Cpusets can break the scheduler domain tree into smaller 3333 * balance domains, some of which do not cross NUMA boundaries. 3334 * Tasks that are "trapped" in such domains cannot be migrated 3335 * elsewhere, so there is no point in (re)trying. 3336 */ 3337 if (unlikely(!sd)) { 3338 sched_setnuma(p, task_node(p)); 3339 return -EINVAL; 3340 } 3341 3342 env.dst_nid = p->numa_preferred_nid; 3343 dist = env.dist = node_distance(env.src_nid, env.dst_nid); 3344 taskweight = task_weight(p, env.src_nid, dist); 3345 groupweight = group_weight(p, env.src_nid, dist); 3346 update_numa_stats(&env, &env.src_stats, env.src_nid, false); 3347 taskimp = task_weight(p, env.dst_nid, dist) - taskweight; 3348 groupimp = group_weight(p, env.dst_nid, dist) - groupweight; 3349 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true); 3350 3351 /* Try to find a spot on the preferred nid. */ 3352 task_numa_find_cpu(&env, taskimp, groupimp); 3353 3354 /* 3355 * Look at other nodes in these cases: 3356 * - there is no space available on the preferred_nid 3357 * - the task is part of a numa_group that is interleaved across 3358 * multiple NUMA nodes; in order to better consolidate the group, 3359 * we need to check other locations. 3360 */ 3361 ng = deref_curr_numa_group(p); 3362 if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) { 3363 for_each_node_state(nid, N_CPU) { 3364 if (nid == env.src_nid || nid == p->numa_preferred_nid) 3365 continue; 3366 3367 dist = node_distance(env.src_nid, env.dst_nid); 3368 if (sched_numa_topology_type == NUMA_BACKPLANE && 3369 dist != env.dist) { 3370 taskweight = task_weight(p, env.src_nid, dist); 3371 groupweight = group_weight(p, env.src_nid, dist); 3372 } 3373 3374 /* Only consider nodes where both task and groups benefit */ 3375 taskimp = task_weight(p, nid, dist) - taskweight; 3376 groupimp = group_weight(p, nid, dist) - groupweight; 3377 if (taskimp < 0 && groupimp < 0) 3378 continue; 3379 3380 env.dist = dist; 3381 env.dst_nid = nid; 3382 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true); 3383 task_numa_find_cpu(&env, taskimp, groupimp); 3384 } 3385 } 3386 3387 /* 3388 * If the task is part of a workload that spans multiple NUMA nodes, 3389 * and is migrating into one of the workload's active nodes, remember 3390 * this node as the task's preferred numa node, so the workload can 3391 * settle down. 3392 * A task that migrated to a second choice node will be better off 3393 * trying for a better one later. Do not set the preferred node here. 3394 */ 3395 if (ng) { 3396 if (env.best_cpu == -1) 3397 nid = env.src_nid; 3398 else 3399 nid = cpu_to_node(env.best_cpu); 3400 3401 if (nid != p->numa_preferred_nid) 3402 sched_setnuma(p, nid); 3403 } 3404 3405 /* No better CPU than the current one was found. */ 3406 if (env.best_cpu == -1) { 3407 trace_sched_stick_numa(p, env.src_cpu, NULL, -1); 3408 return -EAGAIN; 3409 } 3410 3411 best_rq = cpu_rq(env.best_cpu); 3412 if (env.best_task == NULL) { 3413 ret = migrate_task_to(p, env.best_cpu); 3414 WRITE_ONCE(best_rq->numa_migrate_on, 0); 3415 if (ret != 0) 3416 trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu); 3417 return ret; 3418 } 3419 3420 ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu); 3421 WRITE_ONCE(best_rq->numa_migrate_on, 0); 3422 3423 if (ret != 0) 3424 trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu); 3425 put_task_struct(env.best_task); 3426 return ret; 3427 } 3428 3429 /* Attempt to migrate a task to a CPU on the preferred node. */ 3430 static void numa_migrate_preferred(struct task_struct *p) 3431 { 3432 unsigned long interval = HZ; 3433 3434 /* This task has no NUMA fault statistics yet */ 3435 if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults)) 3436 return; 3437 3438 /* Periodically retry migrating the task to the preferred node */ 3439 interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16); 3440 p->numa_migrate_retry = jiffies + interval; 3441 3442 /* Success if task is already running on preferred CPU */ 3443 if (task_node(p) == p->numa_preferred_nid) 3444 return; 3445 3446 /* Otherwise, try migrate to a CPU on the preferred node */ 3447 task_numa_migrate(p); 3448 } 3449 3450 /* 3451 * Find out how many nodes the workload is actively running on. Do this by 3452 * tracking the nodes from which NUMA hinting faults are triggered. This can 3453 * be different from the set of nodes where the workload's memory is currently 3454 * located. 3455 */ 3456 static void numa_group_count_active_nodes(struct numa_group *numa_group) 3457 { 3458 unsigned long faults, max_faults = 0; 3459 int nid, active_nodes = 0; 3460 3461 for_each_node_state(nid, N_CPU) { 3462 faults = group_faults_cpu(numa_group, nid); 3463 if (faults > max_faults) 3464 max_faults = faults; 3465 } 3466 3467 for_each_node_state(nid, N_CPU) { 3468 faults = group_faults_cpu(numa_group, nid); 3469 if (faults * ACTIVE_NODE_FRACTION > max_faults) 3470 active_nodes++; 3471 } 3472 3473 numa_group->max_faults_cpu = max_faults; 3474 numa_group->active_nodes = active_nodes; 3475 } 3476 3477 /* 3478 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS 3479 * increments. The more local the fault statistics are, the higher the scan 3480 * period will be for the next scan window. If local/(local+remote) ratio is 3481 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS) 3482 * the scan period will decrease. Aim for 70% local accesses. 3483 */ 3484 #define NUMA_PERIOD_SLOTS 10 3485 #define NUMA_PERIOD_THRESHOLD 7 3486 3487 /* 3488 * Increase the scan period (slow down scanning) if the majority of 3489 * our memory is already on our local node, or if the majority of 3490 * the page accesses are shared with other processes. 3491 * Otherwise, decrease the scan period. 3492 */ 3493 static void update_task_scan_period(struct task_struct *p, 3494 unsigned long shared, unsigned long private) 3495 { 3496 unsigned int period_slot; 3497 int lr_ratio, ps_ratio; 3498 int diff; 3499 3500 unsigned long remote = p->numa_faults_locality[0]; 3501 unsigned long local = p->numa_faults_locality[1]; 3502 3503 /* 3504 * If there were no record hinting faults then either the task is 3505 * completely idle or all activity is in areas that are not of interest 3506 * to automatic numa balancing. Related to that, if there were failed 3507 * migration then it implies we are migrating too quickly or the local 3508 * node is overloaded. In either case, scan slower 3509 */ 3510 if (local + shared == 0 || p->numa_faults_locality[2]) { 3511 p->numa_scan_period = min(p->numa_scan_period_max, 3512 p->numa_scan_period << 1); 3513 3514 p->mm->numa_next_scan = jiffies + 3515 msecs_to_jiffies(p->numa_scan_period); 3516 3517 return; 3518 } 3519 3520 /* 3521 * Prepare to scale scan period relative to the current period. 3522 * == NUMA_PERIOD_THRESHOLD scan period stays the same 3523 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster) 3524 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower) 3525 */ 3526 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS); 3527 lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote); 3528 ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared); 3529 3530 if (ps_ratio >= NUMA_PERIOD_THRESHOLD) { 3531 /* 3532 * Most memory accesses are local. There is no need to 3533 * do fast NUMA scanning, since memory is already local. 3534 */ 3535 int slot = ps_ratio - NUMA_PERIOD_THRESHOLD; 3536 if (!slot) 3537 slot = 1; 3538 diff = slot * period_slot; 3539 } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) { 3540 /* 3541 * Most memory accesses are shared with other tasks. 3542 * There is no point in continuing fast NUMA scanning, 3543 * since other tasks may just move the memory elsewhere. 3544 */ 3545 int slot = lr_ratio - NUMA_PERIOD_THRESHOLD; 3546 if (!slot) 3547 slot = 1; 3548 diff = slot * period_slot; 3549 } else { 3550 /* 3551 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS, 3552 * yet they are not on the local NUMA node. Speed up 3553 * NUMA scanning to get the memory moved over. 3554 */ 3555 int ratio = max(lr_ratio, ps_ratio); 3556 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot; 3557 } 3558 3559 p->numa_scan_period = clamp(p->numa_scan_period + diff, 3560 task_scan_min(p), task_scan_max(p)); 3561 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality)); 3562 } 3563 3564 /* 3565 * Get the fraction of time the task has been running since the last 3566 * NUMA placement cycle. The scheduler keeps similar statistics, but 3567 * decays those on a 32ms period, which is orders of magnitude off 3568 * from the dozens-of-seconds NUMA balancing period. Use the scheduler 3569 * stats only if the task is so new there are no NUMA statistics yet. 3570 */ 3571 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period) 3572 { 3573 u64 runtime, delta, now; 3574 /* Use the start of this time slice to avoid calculations. */ 3575 now = p->se.exec_start; 3576 runtime = p->se.sum_exec_runtime; 3577 3578 if (p->last_task_numa_placement) { 3579 delta = runtime - p->last_sum_exec_runtime; 3580 *period = now - p->last_task_numa_placement; 3581 3582 /* Avoid time going backwards, prevent potential divide error: */ 3583 if (unlikely((s64)*period < 0)) 3584 *period = 0; 3585 } else { 3586 delta = p->se.avg.load_sum; 3587 *period = LOAD_AVG_MAX; 3588 } 3589 3590 p->last_sum_exec_runtime = runtime; 3591 p->last_task_numa_placement = now; 3592 3593 return delta; 3594 } 3595 3596 /* 3597 * Determine the preferred nid for a task in a numa_group. This needs to 3598 * be done in a way that produces consistent results with group_weight, 3599 * otherwise workloads might not converge. 3600 */ 3601 static int preferred_group_nid(struct task_struct *p, int nid) 3602 { 3603 nodemask_t nodes; 3604 int dist; 3605 3606 /* Direct connections between all NUMA nodes. */ 3607 if (sched_numa_topology_type == NUMA_DIRECT) 3608 return nid; 3609 3610 /* 3611 * On a system with glueless mesh NUMA topology, group_weight 3612 * scores nodes according to the number of NUMA hinting faults on 3613 * both the node itself, and on nearby nodes. 3614 */ 3615 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) { 3616 unsigned long score, max_score = 0; 3617 int node, max_node = nid; 3618 3619 dist = sched_max_numa_distance; 3620 3621 for_each_node_state(node, N_CPU) { 3622 score = group_weight(p, node, dist); 3623 if (score > max_score) { 3624 max_score = score; 3625 max_node = node; 3626 } 3627 } 3628 return max_node; 3629 } 3630 3631 /* 3632 * Finding the preferred nid in a system with NUMA backplane 3633 * interconnect topology is more involved. The goal is to locate 3634 * tasks from numa_groups near each other in the system, and 3635 * untangle workloads from different sides of the system. This requires 3636 * searching down the hierarchy of node groups, recursively searching 3637 * inside the highest scoring group of nodes. The nodemask tricks 3638 * keep the complexity of the search down. 3639 */ 3640 nodes = node_states[N_CPU]; 3641 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) { 3642 unsigned long max_faults = 0; 3643 nodemask_t max_group = NODE_MASK_NONE; 3644 int a, b; 3645 3646 /* Are there nodes at this distance from each other? */ 3647 if (!find_numa_distance(dist)) 3648 continue; 3649 3650 for_each_node_mask(a, nodes) { 3651 unsigned long faults = 0; 3652 nodemask_t this_group; 3653 nodes_clear(this_group); 3654 3655 /* Sum group's NUMA faults; includes a==b case. */ 3656 for_each_node_mask(b, nodes) { 3657 if (node_distance(a, b) < dist) { 3658 faults += group_faults(p, b); 3659 node_set(b, this_group); 3660 node_clear(b, nodes); 3661 } 3662 } 3663 3664 /* Remember the top group. */ 3665 if (faults > max_faults) { 3666 max_faults = faults; 3667 max_group = this_group; 3668 /* 3669 * subtle: at the smallest distance there is 3670 * just one node left in each "group", the 3671 * winner is the preferred nid. 3672 */ 3673 nid = a; 3674 } 3675 } 3676 /* Next round, evaluate the nodes within max_group. */ 3677 if (!max_faults) 3678 break; 3679 nodes = max_group; 3680 } 3681 return nid; 3682 } 3683 3684 static void task_numa_placement(struct task_struct *p) 3685 __context_unsafe(/* conditional locking */) 3686 { 3687 int seq, nid, max_nid = NUMA_NO_NODE; 3688 unsigned long max_faults = 0; 3689 unsigned long fault_types[2] = { 0, 0 }; 3690 unsigned long total_faults; 3691 u64 runtime, period; 3692 spinlock_t *group_lock = NULL; 3693 long __maybe_unused new_fp; 3694 struct numa_group *ng; 3695 3696 /* 3697 * The p->mm->numa_scan_seq field gets updated without 3698 * exclusive access. Use READ_ONCE() here to ensure 3699 * that the field is read in a single access: 3700 */ 3701 seq = READ_ONCE(p->mm->numa_scan_seq); 3702 if (p->numa_scan_seq == seq) 3703 return; 3704 p->numa_scan_seq = seq; 3705 p->numa_scan_period_max = task_scan_max(p); 3706 3707 total_faults = p->numa_faults_locality[0] + 3708 p->numa_faults_locality[1]; 3709 runtime = numa_get_avg_runtime(p, &period); 3710 3711 /* If the task is part of a group prevent parallel updates to group stats */ 3712 ng = deref_curr_numa_group(p); 3713 if (ng) { 3714 group_lock = &ng->lock; 3715 spin_lock_irq(group_lock); 3716 } 3717 3718 /* Find the node with the highest number of faults */ 3719 for_each_online_node(nid) { 3720 /* Keep track of the offsets in numa_faults array */ 3721 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx; 3722 unsigned long faults = 0, group_faults = 0; 3723 int priv; 3724 3725 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) { 3726 long diff, f_diff, f_weight; 3727 3728 mem_idx = task_faults_idx(NUMA_MEM, nid, priv); 3729 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv); 3730 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv); 3731 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv); 3732 3733 /* Decay existing window, copy faults since last scan */ 3734 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2; 3735 fault_types[priv] += p->numa_faults[membuf_idx]; 3736 p->numa_faults[membuf_idx] = 0; 3737 3738 /* 3739 * Normalize the faults_from, so all tasks in a group 3740 * count according to CPU use, instead of by the raw 3741 * number of faults. Tasks with little runtime have 3742 * little over-all impact on throughput, and thus their 3743 * faults are less important. 3744 */ 3745 f_weight = div64_u64(runtime << 16, period + 1); 3746 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) / 3747 (total_faults + 1); 3748 f_diff = f_weight - p->numa_faults[cpu_idx] / 2; 3749 p->numa_faults[cpubuf_idx] = 0; 3750 3751 p->numa_faults[mem_idx] += diff; 3752 p->numa_faults[cpu_idx] += f_diff; 3753 faults += p->numa_faults[mem_idx]; 3754 p->total_numa_faults += diff; 3755 if (ng) { 3756 /* 3757 * safe because we can only change our own group 3758 * 3759 * mem_idx represents the offset for a given 3760 * nid and priv in a specific region because it 3761 * is at the beginning of the numa_faults array. 3762 */ 3763 ng->faults[mem_idx] += diff; 3764 ng->faults[cpu_idx] += f_diff; 3765 ng->total_faults += diff; 3766 group_faults += ng->faults[mem_idx]; 3767 } 3768 #ifdef CONFIG_SCHED_CACHE 3769 /* 3770 * Per task p->numa_faults[mem_idx] converges, 3771 * so the accumulation of each task's faults 3772 * converges too - Given the number of threads, 3773 * it cannot overflow an unsigned long. 3774 * Racy with concurrent updates from other threads 3775 * sharing this mm. Acceptable since footprint is a 3776 * heuristic and occasional lost updates are tolerable. 3777 * 3778 * If a task exits, its corresponding footprint must 3779 * be subtracted from the mm->sc_stat.footprint, otherwise 3780 * the mm->sc_stat.footprint will not converge: 3781 * the exiting thread's footprint remains unchanged/undecayed 3782 * in mm->sc_stat.footprint. See exit_mm(). 3783 * 3784 * Lost updates and unsynchronized subtraction 3785 * in exit_mm() can cause footprint + diff to 3786 * go negative. Clamp to zero to prevent the 3787 * unsigned footprint from wrapping. 3788 */ 3789 new_fp = (long)READ_ONCE(p->mm->sc_stat.footprint) + diff; 3790 WRITE_ONCE(p->mm->sc_stat.footprint, 3791 max(new_fp, 0L)); 3792 #endif 3793 } 3794 3795 if (!ng) { 3796 if (faults > max_faults) { 3797 max_faults = faults; 3798 max_nid = nid; 3799 } 3800 } else if (group_faults > max_faults) { 3801 max_faults = group_faults; 3802 max_nid = nid; 3803 } 3804 } 3805 3806 /* Cannot migrate task to CPU-less node */ 3807 max_nid = numa_nearest_node(max_nid, N_CPU); 3808 3809 if (ng) { 3810 numa_group_count_active_nodes(ng); 3811 spin_unlock_irq(group_lock); 3812 max_nid = preferred_group_nid(p, max_nid); 3813 } 3814 3815 if (max_faults) { 3816 /* Set the new preferred node */ 3817 if (max_nid != p->numa_preferred_nid) 3818 sched_setnuma(p, max_nid); 3819 } 3820 3821 update_task_scan_period(p, fault_types[0], fault_types[1]); 3822 } 3823 3824 static inline int get_numa_group(struct numa_group *grp) 3825 { 3826 return refcount_inc_not_zero(&grp->refcount); 3827 } 3828 3829 static inline void put_numa_group(struct numa_group *grp) 3830 { 3831 if (refcount_dec_and_test(&grp->refcount)) 3832 kfree_rcu(grp, rcu); 3833 } 3834 3835 static void task_numa_group(struct task_struct *p, int cpupid, int flags, 3836 int *priv) 3837 { 3838 struct numa_group *grp, *my_grp; 3839 struct task_struct *tsk; 3840 bool join = false; 3841 int cpu = cpupid_to_cpu(cpupid); 3842 int i; 3843 3844 if (unlikely(!deref_curr_numa_group(p))) { 3845 unsigned int size = sizeof(struct numa_group) + 3846 NR_NUMA_HINT_FAULT_STATS * 3847 nr_node_ids * sizeof(unsigned long); 3848 3849 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN); 3850 if (!grp) 3851 return; 3852 3853 refcount_set(&grp->refcount, 1); 3854 grp->active_nodes = 1; 3855 grp->max_faults_cpu = 0; 3856 spin_lock_init(&grp->lock); 3857 grp->gid = p->pid; 3858 3859 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) 3860 grp->faults[i] = p->numa_faults[i]; 3861 3862 grp->total_faults = p->total_numa_faults; 3863 3864 grp->nr_tasks++; 3865 rcu_assign_pointer(p->numa_group, grp); 3866 } 3867 3868 rcu_read_lock(); 3869 tsk = READ_ONCE(cpu_rq(cpu)->curr); 3870 3871 if (!cpupid_match_pid(tsk, cpupid)) 3872 goto no_join; 3873 3874 grp = rcu_dereference_all(tsk->numa_group); 3875 if (!grp) 3876 goto no_join; 3877 3878 my_grp = deref_curr_numa_group(p); 3879 if (grp == my_grp) 3880 goto no_join; 3881 3882 /* 3883 * Only join the other group if its bigger; if we're the bigger group, 3884 * the other task will join us. 3885 */ 3886 if (my_grp->nr_tasks > grp->nr_tasks) 3887 goto no_join; 3888 3889 /* 3890 * Tie-break on the grp address. 3891 */ 3892 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp) 3893 goto no_join; 3894 3895 /* Always join threads in the same process. */ 3896 if (tsk->mm == current->mm) 3897 join = true; 3898 3899 /* Simple filter to avoid false positives due to PID collisions */ 3900 if (flags & TNF_SHARED) 3901 join = true; 3902 3903 /* Update priv based on whether false sharing was detected */ 3904 *priv = !join; 3905 3906 if (join && !get_numa_group(grp)) 3907 goto no_join; 3908 3909 rcu_read_unlock(); 3910 3911 if (!join) 3912 return; 3913 3914 WARN_ON_ONCE(irqs_disabled()); 3915 double_lock_irq(&my_grp->lock, &grp->lock); 3916 3917 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) { 3918 my_grp->faults[i] -= p->numa_faults[i]; 3919 grp->faults[i] += p->numa_faults[i]; 3920 } 3921 my_grp->total_faults -= p->total_numa_faults; 3922 grp->total_faults += p->total_numa_faults; 3923 3924 my_grp->nr_tasks--; 3925 grp->nr_tasks++; 3926 3927 spin_unlock(&my_grp->lock); 3928 spin_unlock_irq(&grp->lock); 3929 3930 rcu_assign_pointer(p->numa_group, grp); 3931 3932 put_numa_group(my_grp); 3933 return; 3934 3935 no_join: 3936 rcu_read_unlock(); 3937 return; 3938 } 3939 3940 /* 3941 * Get rid of NUMA statistics associated with a task (either current or dead). 3942 * If @final is set, the task is dead and has reached refcount zero, so we can 3943 * safely free all relevant data structures. Otherwise, there might be 3944 * concurrent reads from places like load balancing and procfs, and we should 3945 * reset the data back to default state without freeing ->numa_faults. 3946 */ 3947 void task_numa_free(struct task_struct *p, bool final) 3948 { 3949 /* safe: p either is current or is being freed by current */ 3950 struct numa_group *grp = rcu_dereference_raw(p->numa_group); 3951 unsigned long *numa_faults = p->numa_faults; 3952 unsigned long flags; 3953 int i; 3954 3955 if (!numa_faults) 3956 return; 3957 3958 if (grp) { 3959 spin_lock_irqsave(&grp->lock, flags); 3960 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) 3961 grp->faults[i] -= p->numa_faults[i]; 3962 grp->total_faults -= p->total_numa_faults; 3963 3964 grp->nr_tasks--; 3965 spin_unlock_irqrestore(&grp->lock, flags); 3966 RCU_INIT_POINTER(p->numa_group, NULL); 3967 put_numa_group(grp); 3968 } 3969 3970 if (final) { 3971 p->numa_faults = NULL; 3972 kfree(numa_faults); 3973 } else { 3974 p->total_numa_faults = 0; 3975 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) 3976 numa_faults[i] = 0; 3977 } 3978 } 3979 3980 /* 3981 * Got a PROT_NONE fault for a page on @node. 3982 */ 3983 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags) 3984 { 3985 struct task_struct *p = current; 3986 bool migrated = flags & TNF_MIGRATED; 3987 int cpu_node = task_node(current); 3988 int local = !!(flags & TNF_FAULT_LOCAL); 3989 struct numa_group *ng; 3990 int priv; 3991 3992 if (!static_branch_likely(&sched_numa_balancing)) 3993 return; 3994 3995 /* for example, ksmd faulting in a user's mm */ 3996 if (!p->mm) 3997 return; 3998 3999 /* 4000 * NUMA faults statistics are unnecessary for the slow memory 4001 * node for memory tiering mode. 4002 */ 4003 if (!node_is_toptier(mem_node) && 4004 (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING || 4005 !cpupid_valid(last_cpupid))) 4006 return; 4007 4008 /* Allocate buffer to track faults on a per-node basis */ 4009 if (unlikely(!p->numa_faults)) { 4010 int size = sizeof(*p->numa_faults) * 4011 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids; 4012 4013 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN); 4014 if (!p->numa_faults) 4015 return; 4016 4017 p->total_numa_faults = 0; 4018 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality)); 4019 } 4020 4021 /* 4022 * First accesses are treated as private, otherwise consider accesses 4023 * to be private if the accessing pid has not changed 4024 */ 4025 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) { 4026 priv = 1; 4027 } else { 4028 priv = cpupid_match_pid(p, last_cpupid); 4029 if (!priv && !(flags & TNF_NO_GROUP)) 4030 task_numa_group(p, last_cpupid, flags, &priv); 4031 } 4032 4033 /* 4034 * If a workload spans multiple NUMA nodes, a shared fault that 4035 * occurs wholly within the set of nodes that the workload is 4036 * actively using should be counted as local. This allows the 4037 * scan rate to slow down when a workload has settled down. 4038 */ 4039 ng = deref_curr_numa_group(p); 4040 if (!priv && !local && ng && ng->active_nodes > 1 && 4041 numa_is_active_node(cpu_node, ng) && 4042 numa_is_active_node(mem_node, ng)) 4043 local = 1; 4044 4045 /* 4046 * Retry to migrate task to preferred node periodically, in case it 4047 * previously failed, or the scheduler moved us. 4048 */ 4049 if (time_after(jiffies, p->numa_migrate_retry)) { 4050 task_numa_placement(p); 4051 numa_migrate_preferred(p); 4052 } 4053 4054 if (migrated) 4055 p->numa_pages_migrated += pages; 4056 if (flags & TNF_MIGRATE_FAIL) 4057 p->numa_faults_locality[2] += pages; 4058 4059 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages; 4060 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages; 4061 p->numa_faults_locality[local] += pages; 4062 } 4063 4064 static void reset_ptenuma_scan(struct task_struct *p) 4065 { 4066 /* 4067 * We only did a read acquisition of the mmap sem, so 4068 * p->mm->numa_scan_seq is written to without exclusive access 4069 * and the update is not guaranteed to be atomic. That's not 4070 * much of an issue though, since this is just used for 4071 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not 4072 * expensive, to avoid any form of compiler optimizations: 4073 */ 4074 WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1); 4075 p->mm->numa_scan_offset = 0; 4076 } 4077 4078 static bool vma_is_accessed(struct mm_struct *mm, struct vm_area_struct *vma) 4079 { 4080 unsigned long pids; 4081 /* 4082 * Allow unconditional access first two times, so that all the (pages) 4083 * of VMAs get prot_none fault introduced irrespective of accesses. 4084 * This is also done to avoid any side effect of task scanning 4085 * amplifying the unfairness of disjoint set of VMAs' access. 4086 */ 4087 if ((READ_ONCE(current->mm->numa_scan_seq) - vma->numab_state->start_scan_seq) < 2) 4088 return true; 4089 4090 pids = vma->numab_state->pids_active[0] | vma->numab_state->pids_active[1]; 4091 if (test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids)) 4092 return true; 4093 4094 /* 4095 * Complete a scan that has already started regardless of PID access, or 4096 * some VMAs may never be scanned in multi-threaded applications: 4097 */ 4098 if (mm->numa_scan_offset > vma->vm_start) { 4099 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_IGNORE_PID); 4100 return true; 4101 } 4102 4103 /* 4104 * This vma has not been accessed for a while, and if the number 4105 * the threads in the same process is low, which means no other 4106 * threads can help scan this vma, force a vma scan. 4107 */ 4108 if (READ_ONCE(mm->numa_scan_seq) > 4109 (vma->numab_state->prev_scan_seq + get_nr_threads(current))) 4110 return true; 4111 4112 return false; 4113 } 4114 4115 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay) 4116 4117 /* 4118 * The expensive part of numa migration is done from task_work context. 4119 * Triggered from task_tick_numa(). 4120 */ 4121 static void task_numa_work(struct callback_head *work) 4122 { 4123 unsigned long migrate, next_scan, now = jiffies; 4124 struct task_struct *p = current; 4125 struct mm_struct *mm = p->mm; 4126 u64 runtime = p->se.sum_exec_runtime; 4127 struct vm_area_struct *vma; 4128 unsigned long start, end; 4129 unsigned long nr_pte_updates = 0; 4130 long pages, virtpages; 4131 struct vma_iterator vmi; 4132 bool vma_pids_skipped; 4133 bool vma_pids_forced = false; 4134 4135 WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work)); 4136 4137 work->next = work; 4138 /* 4139 * Who cares about NUMA placement when they're dying. 4140 * 4141 * NOTE: make sure not to dereference p->mm before this check, 4142 * exit_task_work() happens _after_ exit_mm() so we could be called 4143 * without p->mm even though we still had it when we enqueued this 4144 * work. 4145 */ 4146 if (p->flags & PF_EXITING) 4147 return; 4148 4149 /* 4150 * Memory is pinned to only one NUMA node via cpuset.mems, naturally 4151 * no page can be migrated. 4152 */ 4153 if (cpusets_enabled() && nodes_weight(cpuset_current_mems_allowed) == 1) { 4154 trace_sched_skip_cpuset_numa(current, &cpuset_current_mems_allowed); 4155 return; 4156 } 4157 4158 if (!mm->numa_next_scan) { 4159 mm->numa_next_scan = now + 4160 msecs_to_jiffies(sysctl_numa_balancing_scan_delay); 4161 } 4162 4163 /* 4164 * Enforce maximal scan/migration frequency.. 4165 */ 4166 migrate = mm->numa_next_scan; 4167 if (time_before(now, migrate)) 4168 return; 4169 4170 if (p->numa_scan_period == 0) { 4171 p->numa_scan_period_max = task_scan_max(p); 4172 p->numa_scan_period = task_scan_start(p); 4173 } 4174 4175 next_scan = now + msecs_to_jiffies(p->numa_scan_period); 4176 if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan)) 4177 return; 4178 4179 /* 4180 * Delay this task enough that another task of this mm will likely win 4181 * the next time around. 4182 */ 4183 p->node_stamp += 2 * TICK_NSEC; 4184 4185 pages = sysctl_numa_balancing_scan_size; 4186 pages <<= 20 - PAGE_SHIFT; /* MB in pages */ 4187 virtpages = pages * 8; /* Scan up to this much virtual space */ 4188 if (!pages) 4189 return; 4190 4191 4192 if (!mmap_read_trylock(mm)) 4193 return; 4194 4195 /* 4196 * VMAs are skipped if the current PID has not trapped a fault within 4197 * the VMA recently. Allow scanning to be forced if there is no 4198 * suitable VMA remaining. 4199 */ 4200 vma_pids_skipped = false; 4201 4202 retry_pids: 4203 start = mm->numa_scan_offset; 4204 vma_iter_init(&vmi, mm, start); 4205 vma = vma_next(&vmi); 4206 if (!vma) { 4207 reset_ptenuma_scan(p); 4208 start = 0; 4209 vma_iter_set(&vmi, start); 4210 vma = vma_next(&vmi); 4211 } 4212 4213 for (; vma; vma = vma_next(&vmi)) { 4214 if (!vma_migratable(vma) || !vma_policy_mof(vma) || 4215 is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) { 4216 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_UNSUITABLE); 4217 continue; 4218 } 4219 4220 /* 4221 * Shared library pages mapped by multiple processes are not 4222 * migrated as it is expected they are cache replicated. Avoid 4223 * hinting faults in read-only file-backed mappings or the vDSO 4224 * as migrating the pages will be of marginal benefit. 4225 */ 4226 if (!vma->vm_mm || 4227 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ))) { 4228 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SHARED_RO); 4229 continue; 4230 } 4231 4232 /* 4233 * Skip inaccessible VMAs to avoid any confusion between 4234 * PROT_NONE and NUMA hinting PTEs 4235 */ 4236 if (!vma_is_accessible(vma)) { 4237 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_INACCESSIBLE); 4238 continue; 4239 } 4240 4241 /* Initialise new per-VMA NUMAB state. */ 4242 if (!vma->numab_state) { 4243 struct vma_numab_state *ptr; 4244 4245 ptr = kzalloc_obj(*ptr); 4246 if (!ptr) 4247 continue; 4248 4249 if (cmpxchg(&vma->numab_state, NULL, ptr)) { 4250 kfree(ptr); 4251 continue; 4252 } 4253 4254 vma->numab_state->start_scan_seq = mm->numa_scan_seq; 4255 4256 vma->numab_state->next_scan = now + 4257 msecs_to_jiffies(sysctl_numa_balancing_scan_delay); 4258 4259 /* Reset happens after 4 times scan delay of scan start */ 4260 vma->numab_state->pids_active_reset = vma->numab_state->next_scan + 4261 msecs_to_jiffies(VMA_PID_RESET_PERIOD); 4262 4263 /* 4264 * Ensure prev_scan_seq does not match numa_scan_seq, 4265 * to prevent VMAs being skipped prematurely on the 4266 * first scan: 4267 */ 4268 vma->numab_state->prev_scan_seq = mm->numa_scan_seq - 1; 4269 } 4270 4271 /* 4272 * Scanning the VMAs of short lived tasks add more overhead. So 4273 * delay the scan for new VMAs. 4274 */ 4275 if (mm->numa_scan_seq && time_before(jiffies, 4276 vma->numab_state->next_scan)) { 4277 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SCAN_DELAY); 4278 continue; 4279 } 4280 4281 /* RESET access PIDs regularly for old VMAs. */ 4282 if (mm->numa_scan_seq && 4283 time_after(jiffies, vma->numab_state->pids_active_reset)) { 4284 vma->numab_state->pids_active_reset = vma->numab_state->pids_active_reset + 4285 msecs_to_jiffies(VMA_PID_RESET_PERIOD); 4286 vma->numab_state->pids_active[0] = READ_ONCE(vma->numab_state->pids_active[1]); 4287 vma->numab_state->pids_active[1] = 0; 4288 } 4289 4290 /* Do not rescan VMAs twice within the same sequence. */ 4291 if (vma->numab_state->prev_scan_seq == mm->numa_scan_seq) { 4292 mm->numa_scan_offset = vma->vm_end; 4293 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SEQ_COMPLETED); 4294 continue; 4295 } 4296 4297 /* 4298 * Do not scan the VMA if task has not accessed it, unless no other 4299 * VMA candidate exists. 4300 */ 4301 if (!vma_pids_forced && !vma_is_accessed(mm, vma)) { 4302 vma_pids_skipped = true; 4303 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_PID_INACTIVE); 4304 continue; 4305 } 4306 4307 do { 4308 start = max(start, vma->vm_start); 4309 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE); 4310 end = min(end, vma->vm_end); 4311 nr_pte_updates = change_prot_numa(vma, start, end); 4312 4313 /* 4314 * Try to scan sysctl_numa_balancing_size worth of 4315 * hpages that have at least one present PTE that 4316 * is not already PTE-numa. If the VMA contains 4317 * areas that are unused or already full of prot_numa 4318 * PTEs, scan up to virtpages, to skip through those 4319 * areas faster. 4320 */ 4321 if (nr_pte_updates) 4322 pages -= (end - start) >> PAGE_SHIFT; 4323 virtpages -= (end - start) >> PAGE_SHIFT; 4324 4325 start = end; 4326 if (pages <= 0 || virtpages <= 0) 4327 goto out; 4328 4329 cond_resched(); 4330 } while (end != vma->vm_end); 4331 4332 /* VMA scan is complete, do not scan until next sequence. */ 4333 vma->numab_state->prev_scan_seq = mm->numa_scan_seq; 4334 4335 /* 4336 * Only force scan within one VMA at a time, to limit the 4337 * cost of scanning a potentially uninteresting VMA. 4338 */ 4339 if (vma_pids_forced) 4340 break; 4341 } 4342 4343 /* 4344 * If no VMAs are remaining and VMAs were skipped due to the PID 4345 * not accessing the VMA previously, then force a scan to ensure 4346 * forward progress: 4347 */ 4348 if (!vma && !vma_pids_forced && vma_pids_skipped) { 4349 vma_pids_forced = true; 4350 goto retry_pids; 4351 } 4352 4353 out: 4354 /* 4355 * It is possible to reach the end of the VMA list but the last few 4356 * VMAs are not guaranteed to the vma_migratable. If they are not, we 4357 * would find the !migratable VMA on the next scan but not reset the 4358 * scanner to the start so check it now. 4359 */ 4360 if (vma) 4361 mm->numa_scan_offset = start; 4362 else 4363 reset_ptenuma_scan(p); 4364 mmap_read_unlock(mm); 4365 4366 /* 4367 * Make sure tasks use at least 32x as much time to run other code 4368 * than they used here, to limit NUMA PTE scanning overhead to 3% max. 4369 * Usually update_task_scan_period slows down scanning enough; on an 4370 * overloaded system we need to limit overhead on a per task basis. 4371 */ 4372 if (unlikely(p->se.sum_exec_runtime != runtime)) { 4373 u64 diff = p->se.sum_exec_runtime - runtime; 4374 p->node_stamp += 32 * diff; 4375 } 4376 } 4377 4378 void init_numa_balancing(u64 clone_flags, struct task_struct *p) 4379 { 4380 int mm_users = 0; 4381 struct mm_struct *mm = p->mm; 4382 4383 if (mm) { 4384 mm_users = atomic_read(&mm->mm_users); 4385 if (mm_users == 1) { 4386 mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay); 4387 mm->numa_scan_seq = 0; 4388 } 4389 } 4390 p->node_stamp = 0; 4391 p->numa_scan_seq = mm ? mm->numa_scan_seq : 0; 4392 p->numa_scan_period = sysctl_numa_balancing_scan_delay; 4393 p->numa_migrate_retry = 0; 4394 /* Protect against double add, see task_tick_numa and task_numa_work */ 4395 p->numa_work.next = &p->numa_work; 4396 p->numa_faults = NULL; 4397 p->numa_pages_migrated = 0; 4398 p->total_numa_faults = 0; 4399 RCU_INIT_POINTER(p->numa_group, NULL); 4400 p->last_task_numa_placement = 0; 4401 p->last_sum_exec_runtime = 0; 4402 4403 init_task_work(&p->numa_work, task_numa_work); 4404 4405 /* New address space, reset the preferred nid */ 4406 if (!(clone_flags & CLONE_VM)) { 4407 p->numa_preferred_nid = NUMA_NO_NODE; 4408 return; 4409 } 4410 4411 /* 4412 * New thread, keep existing numa_preferred_nid which should be copied 4413 * already by arch_dup_task_struct but stagger when scans start. 4414 */ 4415 if (mm) { 4416 unsigned int delay; 4417 4418 delay = min_t(unsigned int, task_scan_max(current), 4419 current->numa_scan_period * mm_users * NSEC_PER_MSEC); 4420 delay += 2 * TICK_NSEC; 4421 p->node_stamp = delay; 4422 } 4423 } 4424 4425 /* 4426 * Drive the periodic memory faults.. 4427 */ 4428 static void task_tick_numa(struct rq *rq, struct task_struct *curr) 4429 { 4430 struct callback_head *work = &curr->numa_work; 4431 u64 period, now; 4432 4433 /* 4434 * We don't care about NUMA placement if we don't have memory. 4435 */ 4436 if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work) 4437 return; 4438 4439 /* 4440 * Using runtime rather than walltime has the dual advantage that 4441 * we (mostly) drive the selection from busy threads and that the 4442 * task needs to have done some actual work before we bother with 4443 * NUMA placement. 4444 */ 4445 now = curr->se.sum_exec_runtime; 4446 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC; 4447 4448 if (now > curr->node_stamp + period) { 4449 if (!curr->node_stamp) 4450 curr->numa_scan_period = task_scan_start(curr); 4451 curr->node_stamp += period; 4452 4453 if (!time_before(jiffies, curr->mm->numa_next_scan)) 4454 task_work_add(curr, work, TWA_RESUME); 4455 } 4456 } 4457 4458 static void update_scan_period(struct task_struct *p, int new_cpu) 4459 { 4460 int src_nid = cpu_to_node(task_cpu(p)); 4461 int dst_nid = cpu_to_node(new_cpu); 4462 4463 if (!static_branch_likely(&sched_numa_balancing)) 4464 return; 4465 4466 if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING)) 4467 return; 4468 4469 if (src_nid == dst_nid) 4470 return; 4471 4472 /* 4473 * Allow resets if faults have been trapped before one scan 4474 * has completed. This is most likely due to a new task that 4475 * is pulled cross-node due to wakeups or load balancing. 4476 */ 4477 if (p->numa_scan_seq) { 4478 /* 4479 * Avoid scan adjustments if moving to the preferred 4480 * node or if the task was not previously running on 4481 * the preferred node. 4482 */ 4483 if (dst_nid == p->numa_preferred_nid || 4484 (p->numa_preferred_nid != NUMA_NO_NODE && 4485 src_nid != p->numa_preferred_nid)) 4486 return; 4487 } 4488 4489 p->numa_scan_period = task_scan_start(p); 4490 } 4491 4492 #else /* !CONFIG_NUMA_BALANCING: */ 4493 4494 static void task_tick_numa(struct rq *rq, struct task_struct *curr) 4495 { 4496 } 4497 4498 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p) 4499 { 4500 } 4501 4502 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p) 4503 { 4504 } 4505 4506 static inline void update_scan_period(struct task_struct *p, int new_cpu) 4507 { 4508 } 4509 4510 #endif /* !CONFIG_NUMA_BALANCING */ 4511 4512 static void 4513 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se) 4514 { 4515 WARN_ON_ONCE(cfs_rq != cfs_rq_of(se)); 4516 update_load_add(&cfs_rq->load, se->load.weight); 4517 if (entity_is_task(se)) { 4518 struct task_struct *p = task_of(se); 4519 struct rq *rq = rq_of(cfs_rq); 4520 4521 account_numa_enqueue(rq, p); 4522 account_llc_enqueue(rq, p); 4523 list_add(&se->group_node, &rq->cfs_tasks); 4524 } 4525 cfs_rq->nr_queued++; 4526 } 4527 4528 static void 4529 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se) 4530 { 4531 WARN_ON_ONCE(cfs_rq != cfs_rq_of(se)); 4532 update_load_sub(&cfs_rq->load, se->load.weight); 4533 if (entity_is_task(se)) { 4534 struct task_struct *p = task_of(se); 4535 struct rq *rq = rq_of(cfs_rq); 4536 4537 account_numa_dequeue(rq, p); 4538 account_llc_dequeue(rq, p); 4539 list_del_init(&se->group_node); 4540 } 4541 cfs_rq->nr_queued--; 4542 } 4543 4544 /* 4545 * Signed add and clamp on underflow. 4546 * 4547 * Explicitly do a load-store to ensure the intermediate value never hits 4548 * memory. This allows lockless observations without ever seeing the negative 4549 * values. 4550 */ 4551 #define add_positive(_ptr, _val) do { \ 4552 typeof(_ptr) ptr = (_ptr); \ 4553 __signed_scalar_typeof(*ptr) val = (_val); \ 4554 typeof(*ptr) res, var = READ_ONCE(*ptr); \ 4555 \ 4556 res = var + val; \ 4557 \ 4558 if (val < 0 && res > var) \ 4559 res = 0; \ 4560 \ 4561 WRITE_ONCE(*ptr, res); \ 4562 } while (0) 4563 4564 /* 4565 * Remove and clamp on negative, from a local variable. 4566 * 4567 * A variant of sub_positive(), which does not use explicit load-store 4568 * and is thus optimized for local variable updates. 4569 */ 4570 #define lsub_positive(_ptr, _val) do { \ 4571 typeof(_ptr) ptr = (_ptr); \ 4572 *ptr -= min_t(typeof(*ptr), *ptr, _val); \ 4573 } while (0) 4574 4575 4576 /* 4577 * Because of rounding, se->util_sum might ends up being +1 more than 4578 * cfs->util_sum. Although this is not a problem by itself, detaching 4579 * a lot of tasks with the rounding problem between 2 updates of 4580 * util_avg (~1ms) can make cfs->util_sum becoming null whereas 4581 * cfs_util_avg is not. 4582 * 4583 * Check that util_sum is still above its lower bound for the new 4584 * util_avg. Given that period_contrib might have moved since the last 4585 * sync, we are only sure that util_sum must be above or equal to 4586 * util_avg * minimum possible divider 4587 */ 4588 #define __update_sa(sa, name, delta_avg, delta_sum) do { \ 4589 add_positive(&(sa)->name##_avg, delta_avg); \ 4590 add_positive(&(sa)->name##_sum, delta_sum); \ 4591 (sa)->name##_sum = max_t(typeof((sa)->name##_sum), \ 4592 (sa)->name##_sum, \ 4593 (sa)->name##_avg * PELT_MIN_DIVIDER); \ 4594 } while (0) 4595 4596 static inline void 4597 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) 4598 { 4599 __update_sa(&cfs_rq->avg, load, se->avg.load_avg, 4600 se_weight(se) * se->avg.load_sum); 4601 } 4602 4603 static inline void 4604 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) 4605 { 4606 __update_sa(&cfs_rq->avg, load, -se->avg.load_avg, 4607 se_weight(se) * -se->avg.load_sum); 4608 } 4609 4610 static void 4611 rescale_entity(struct sched_entity *se, unsigned long weight, bool rel_vprot) 4612 { 4613 long old_weight = se->h_load.weight; 4614 4615 /* 4616 * VRUNTIME 4617 * -------- 4618 * 4619 * COROLLARY #1: The virtual runtime of the entity needs to be 4620 * adjusted if re-weight at !0-lag point. 4621 * 4622 * Proof: For contradiction assume this is not true, so we can 4623 * re-weight without changing vruntime at !0-lag point. 4624 * 4625 * Weight VRuntime Avg-VRuntime 4626 * before w v V 4627 * after w' v' V' 4628 * 4629 * Since lag needs to be preserved through re-weight: 4630 * 4631 * lag = (V - v)*w = (V'- v')*w', where v = v' 4632 * ==> V' = (V - v)*w/w' + v (1) 4633 * 4634 * Let W be the total weight of the entities before reweight, 4635 * since V' is the new weighted average of entities: 4636 * 4637 * V' = (WV + w'v - wv) / (W + w' - w) (2) 4638 * 4639 * by using (1) & (2) we obtain: 4640 * 4641 * (WV + w'v - wv) / (W + w' - w) = (V - v)*w/w' + v 4642 * ==> (WV-Wv+Wv+w'v-wv)/(W+w'-w) = (V - v)*w/w' + v 4643 * ==> (WV - Wv)/(W + w' - w) + v = (V - v)*w/w' + v 4644 * ==> (V - v)*W/(W + w' - w) = (V - v)*w/w' (3) 4645 * 4646 * Since we are doing at !0-lag point which means V != v, we 4647 * can simplify (3): 4648 * 4649 * ==> W / (W + w' - w) = w / w' 4650 * ==> Ww' = Ww + ww' - ww 4651 * ==> W * (w' - w) = w * (w' - w) 4652 * ==> W = w (re-weight indicates w' != w) 4653 * 4654 * So the cfs_rq contains only one entity, hence vruntime of 4655 * the entity @v should always equal to the cfs_rq's weighted 4656 * average vruntime @V, which means we will always re-weight 4657 * at 0-lag point, thus breach assumption. Proof completed. 4658 * 4659 * 4660 * COROLLARY #2: Re-weight does NOT affect weighted average 4661 * vruntime of all the entities. 4662 * 4663 * Proof: According to corollary #1, Eq. (1) should be: 4664 * 4665 * (V - v)*w = (V' - v')*w' 4666 * ==> v' = V' - (V - v)*w/w' (4) 4667 * 4668 * According to the weighted average formula, we have: 4669 * 4670 * V' = (WV - wv + w'v') / (W - w + w') 4671 * = (WV - wv + w'(V' - (V - v)w/w')) / (W - w + w') 4672 * = (WV - wv + w'V' - Vw + wv) / (W - w + w') 4673 * = (WV + w'V' - Vw) / (W - w + w') 4674 * 4675 * ==> V'*(W - w + w') = WV + w'V' - Vw 4676 * ==> V' * (W - w) = (W - w) * V (5) 4677 * 4678 * If the entity is the only one in the cfs_rq, then reweight 4679 * always occurs at 0-lag point, so V won't change. Or else 4680 * there are other entities, hence W != w, then Eq. (5) turns 4681 * into V' = V. So V won't change in either case, proof done. 4682 * 4683 * 4684 * So according to corollary #1 & #2, the effect of re-weight 4685 * on vruntime should be: 4686 * 4687 * v' = V' - (V - v) * w / w' (4) 4688 * = V - (V - v) * w / w' 4689 * = V - vl * w / w' 4690 * = V - vl' 4691 */ 4692 se->vlag = div64_long(se->vlag * old_weight, weight); 4693 4694 /* 4695 * DEADLINE 4696 * -------- 4697 * 4698 * When the weight changes, the virtual time slope changes and 4699 * we should adjust the relative virtual deadline accordingly. 4700 * 4701 * d' = v' + (d - v)*w/w' 4702 * = V' - (V - v)*w/w' + (d - v)*w/w' 4703 * = V - (V - v)*w/w' + (d - v)*w/w' 4704 * = V + (d - V)*w/w' 4705 */ 4706 if (se->rel_deadline) 4707 se->deadline = div64_long(se->deadline * old_weight, weight); 4708 4709 if (rel_vprot) 4710 se->vprot = div64_long(se->vprot * old_weight, weight); 4711 } 4712 4713 static void reweight_eevdf(struct cfs_rq *cfs_rq, struct sched_entity *se, 4714 unsigned long weight, bool on_rq) 4715 { 4716 bool curr = cfs_rq->curr == se; 4717 bool rel_vprot = false; 4718 u64 avruntime = 0; 4719 4720 if (se->h_load.weight == weight) 4721 return; 4722 4723 if (on_rq) { 4724 avruntime = avg_vruntime(cfs_rq); 4725 se->vlag = entity_lag(cfs_rq, se, avruntime); 4726 se->deadline -= avruntime; 4727 se->rel_deadline = 1; 4728 if (curr && protect_slice(se)) { 4729 se->vprot -= avruntime; 4730 rel_vprot = true; 4731 } 4732 4733 cfs_rq->h_nr_queued--; 4734 if (!curr) 4735 __dequeue_entity(cfs_rq, se); 4736 } 4737 4738 rescale_entity(se, weight, rel_vprot); 4739 4740 update_load_set(&se->h_load, weight); 4741 4742 if (on_rq) { 4743 if (rel_vprot) 4744 se->vprot += avruntime; 4745 se->deadline += avruntime; 4746 se->rel_deadline = 0; 4747 se->vruntime = avruntime - se->vlag; 4748 4749 if (!curr) 4750 __enqueue_entity(cfs_rq, se); 4751 cfs_rq->h_nr_queued++; 4752 } 4753 } 4754 4755 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, 4756 unsigned long weight) 4757 { 4758 if (se->load.weight == weight) 4759 return; 4760 4761 if (se->on_rq) { 4762 WARN_ON_ONCE(cfs_rq != cfs_rq_of(se)); 4763 update_load_sub(&cfs_rq->load, se->load.weight); 4764 } 4765 dequeue_load_avg(cfs_rq, se); 4766 4767 update_load_set(&se->load, weight); 4768 4769 do { 4770 u32 divider = get_pelt_divider(&se->avg); 4771 se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider); 4772 } while (0); 4773 4774 enqueue_load_avg(cfs_rq, se); 4775 4776 if (se->on_rq) 4777 update_load_add(&cfs_rq->load, se->load.weight); 4778 } 4779 4780 /* 4781 * weight = NICE_0_LOAD; 4782 * for_each_entity_se(se) 4783 * weight = __calc_prop_weight(cfs_rq_of(se), se, weight); 4784 */ 4785 static __always_inline 4786 unsigned long __calc_prop_weight(struct cfs_rq *cfs_rq, struct sched_entity *se, 4787 unsigned long weight) 4788 { 4789 weight *= se->load.weight; 4790 if (parent_entity(se)) 4791 weight /= cfs_rq->load.weight; 4792 else 4793 weight /= NICE_0_LOAD; 4794 4795 return max(weight, MIN_SHARES); 4796 } 4797 4798 static void reweight_task_fair(struct rq *rq, struct task_struct *p, 4799 const struct load_weight *lw) 4800 { 4801 struct sched_entity *se = &p->se; 4802 unsigned long weight = NICE_0_LOAD; 4803 4804 if (se->on_rq) 4805 update_curr_fair(rq); 4806 4807 reweight_entity(cfs_rq_of(se), se, lw->weight); 4808 se->load.inv_weight = lw->inv_weight; 4809 4810 if (!se->on_rq) 4811 return; 4812 4813 for_each_sched_entity(se) 4814 weight = __calc_prop_weight(cfs_rq_of(se), se, weight); 4815 4816 reweight_eevdf(&rq->cfs, &p->se, weight, p->se.on_rq); 4817 } 4818 4819 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq); 4820 4821 #ifdef CONFIG_FAIR_GROUP_SCHED 4822 /* 4823 * All this does is approximate the hierarchical proportion which includes that 4824 * global sum we all love to hate. 4825 * 4826 * That is, the weight of a group entity, is the proportional share of the 4827 * group weight based on the group runqueue weights. That is: 4828 * 4829 * tg->weight * grq->load.weight 4830 * ge->load.weight = ----------------------------- (1) 4831 * \Sum grq->load.weight 4832 * 4833 * Now, because computing that sum is prohibitively expensive to compute (been 4834 * there, done that) we approximate it with this average stuff. The average 4835 * moves slower and therefore the approximation is cheaper and more stable. 4836 * 4837 * So instead of the above, we substitute: 4838 * 4839 * grq->load.weight -> grq->avg.load_avg (2) 4840 * 4841 * which yields the following: 4842 * 4843 * tg->weight * grq->avg.load_avg 4844 * ge->load.weight = ------------------------------ (3) 4845 * tg->load_avg 4846 * 4847 * Where: tg->load_avg ~= \Sum grq->avg.load_avg 4848 * 4849 * That is shares_avg, and it is right (given the approximation (2)). 4850 * 4851 * The problem with it is that because the average is slow -- it was designed 4852 * to be exactly that of course -- this leads to transients in boundary 4853 * conditions. In specific, the case where the group was idle and we start the 4854 * one task. It takes time for our CPU's grq->avg.load_avg to build up, 4855 * yielding bad latency etc.. 4856 * 4857 * Now, in that special case (1) reduces to: 4858 * 4859 * tg->weight * grq->load.weight 4860 * ge->load.weight = ----------------------------- = tg->weight (4) 4861 * grp->load.weight 4862 * 4863 * That is, the sum collapses because all other CPUs are idle; the UP scenario. 4864 * 4865 * So what we do is modify our approximation (3) to approach (4) in the (near) 4866 * UP case, like: 4867 * 4868 * ge->load.weight = 4869 * 4870 * tg->weight * grq->load.weight 4871 * --------------------------------------------------- (5) 4872 * tg->load_avg - grq->avg.load_avg + grq->load.weight 4873 * 4874 * But because grq->load.weight can drop to 0, resulting in a divide by zero, 4875 * we need to use grq->avg.load_avg as its lower bound, which then gives: 4876 * 4877 * 4878 * tg->weight * grq->load.weight 4879 * ge->load.weight = ----------------------------- (6) 4880 * tg_load_avg' 4881 * 4882 * Where: 4883 * 4884 * tg_load_avg' = tg->load_avg - grq->avg.load_avg + 4885 * max(grq->load.weight, grq->avg.load_avg) 4886 * 4887 * And that is shares_weight and is icky. In the (near) UP case it approaches 4888 * (4) while in the normal case it approaches (3). It consistently 4889 * overestimates the ge->load.weight and therefore: 4890 * 4891 * \Sum ge->load.weight >= tg->weight 4892 * 4893 * hence icky! 4894 */ 4895 static long __calc_smp_shares(struct cfs_rq *cfs_rq, long tg_shares, long shares_max) 4896 { 4897 struct task_group *tg = cfs_rq->tg; 4898 long tg_weight, load, shares; 4899 4900 load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg); 4901 4902 tg_weight = atomic_long_read(&tg->load_avg); 4903 4904 /* Ensure tg_weight >= load */ 4905 tg_weight -= cfs_rq->tg_load_avg_contrib; 4906 tg_weight += load; 4907 4908 shares = (tg_shares * load); 4909 if (tg_weight) 4910 shares /= tg_weight; 4911 4912 /* 4913 * MIN_SHARES has to be unscaled here to support per-CPU partitioning 4914 * of a group with small tg->shares value. It is a floor value which is 4915 * assigned as a minimum load.weight to the sched_entity representing 4916 * the group on a CPU. 4917 * 4918 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024 4919 * on an 8-core system with 8 tasks each runnable on one CPU shares has 4920 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In 4921 * case no task is runnable on a CPU MIN_SHARES=2 should be returned 4922 * instead of 0. 4923 */ 4924 return clamp_t(long, shares, MIN_SHARES, shares_max); 4925 } 4926 4927 static int tg_cpus(struct task_group *tg) 4928 { 4929 int nr = num_online_cpus(); 4930 4931 if (cpusets_enabled()) { 4932 struct cgroup *cgrp = tg->css.cgroup; 4933 if (cgrp) 4934 nr = cpuset_num_cpus(cgrp); 4935 } 4936 4937 /* 4938 * An empty cpuset would propagate a 0 shares_max into 4939 * __calc_smp_shares(), where clamp() yields hi when hi < lo and so 4940 * defeats the MIN_SHARES floor. Match tg_tasks(), which floors at 1. 4941 */ 4942 return max(nr, 1); 4943 } 4944 4945 static inline int tg_tasks(struct task_group *tg) 4946 { 4947 return max(1, atomic_long_read(&tg->runnable_avg) >> SCHED_CAPACITY_SHIFT); 4948 } 4949 4950 /* 4951 * Func: fraction(nr_tasks * tg->shares) 4952 * 4953 * Scale tg->shares by the number of tasks. 4954 */ 4955 static long calc_tasks_shares(struct cfs_rq *cfs_rq) 4956 { 4957 struct task_group *tg = cfs_rq->tg; 4958 int nr = tg_tasks(tg); 4959 long tg_shares = READ_ONCE(tg->shares); 4960 return __calc_smp_shares(cfs_rq, nr * tg_shares, nr * tg_shares); 4961 } 4962 4963 /* 4964 * Func: min(fraction(nr_cpus * tg->shares), nice -20) 4965 * 4966 * Scale tg->shares by the maximal number of CPUs; but clip the max shares at 4967 * nice -20, otherwise a single spinner on a 512 CPU machine would result in 4968 * 512*NICE_0_LOAD, which is also crazy. 4969 */ 4970 static long calc_max_shares(struct cfs_rq *cfs_rq) 4971 { 4972 struct task_group *tg = cfs_rq->tg; 4973 int nr = tg_cpus(tg); 4974 long tg_shares = READ_ONCE(tg->shares); 4975 long max_shares = scale_load(sched_prio_to_weight[0]); 4976 return __calc_smp_shares(cfs_rq, tg_shares * nr, max_shares); 4977 } 4978 4979 /* 4980 * Func: fraction(nr * tg->shares); nr = min(nr_tasks, nr_cpus) 4981 * 4982 * Scales between "smp" and "max" in a natural way. No longer needs clipping 4983 * since there are no unnatural inflations like with "max". 4984 */ 4985 static long calc_concur_shares(struct cfs_rq *cfs_rq) 4986 { 4987 struct task_group *tg = cfs_rq->tg; 4988 int nr = min(tg_tasks(tg), tg_cpus(tg)); 4989 long tg_shares = READ_ONCE(tg->shares); 4990 return __calc_smp_shares(cfs_rq, nr * tg_shares, nr * tg_shares); 4991 } 4992 4993 /* 4994 * Func: fraction(tg->shares) 4995 * 4996 * This infamously results in tiny shares when you have many CPUs. 4997 */ 4998 static long calc_smp_shares(struct cfs_rq *cfs_rq) 4999 { 5000 struct task_group *tg = cfs_rq->tg; 5001 long tg_shares = READ_ONCE(tg->shares); 5002 return __calc_smp_shares(cfs_rq, tg_shares, tg_shares); 5003 } 5004 5005 /* 5006 * Ignore this pesky SMP stuff, use (4). 5007 */ 5008 static long calc_up_shares(struct cfs_rq *cfs_rq) 5009 { 5010 struct task_group *tg = cfs_rq->tg; 5011 return READ_ONCE(tg->shares); 5012 } 5013 5014 DEFINE_STATIC_CALL(calc_group_shares, calc_concur_shares); 5015 5016 void __sched_cgroup_mode_update(int mode) 5017 { 5018 long (*func)(struct cfs_rq *); 5019 switch (mode) { 5020 case 0: 5021 func = &calc_up_shares; 5022 break; 5023 case 1: 5024 func = &calc_smp_shares; 5025 break; 5026 case 2: 5027 default: 5028 func = &calc_concur_shares; 5029 break; 5030 case 3: 5031 func = &calc_max_shares; 5032 break; 5033 case 4: 5034 func = &calc_tasks_shares; 5035 break; 5036 } 5037 static_call_update(calc_group_shares, func); 5038 } 5039 5040 /* 5041 * Recomputes the group entity based on the current state of its group 5042 * runqueue. 5043 */ 5044 static void update_cfs_group(struct sched_entity *se) 5045 { 5046 struct cfs_rq *gcfs_rq = group_cfs_rq(se); 5047 long shares; 5048 5049 /* 5050 * When a group becomes empty, preserve its weight. This matters for 5051 * DELAY_DEQUEUE. 5052 */ 5053 if (!gcfs_rq || !gcfs_rq->load.weight) 5054 return; 5055 5056 shares = static_call(calc_group_shares)(gcfs_rq); 5057 reweight_entity(cfs_rq_of(se), se, shares); 5058 } 5059 5060 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 5061 static inline void update_cfs_group(struct sched_entity *se) 5062 { 5063 } 5064 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 5065 5066 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags) 5067 { 5068 struct rq *rq = rq_of(cfs_rq); 5069 5070 if (&rq->cfs == cfs_rq) { 5071 /* 5072 * There are a few boundary cases this might miss but it should 5073 * get called often enough that that should (hopefully) not be 5074 * a real problem. 5075 * 5076 * It will not get called when we go idle, because the idle 5077 * thread is a different class (!fair), nor will the utilization 5078 * number include things like RT tasks. 5079 * 5080 * As is, the util number is not freq-invariant (we'd have to 5081 * implement arch_scale_freq_capacity() for that). 5082 * 5083 * See cpu_util_cfs(). 5084 */ 5085 cpufreq_update_util(rq, flags); 5086 } 5087 } 5088 5089 static inline bool load_avg_is_decayed(struct sched_avg *sa) 5090 { 5091 if (sa->load_sum) 5092 return false; 5093 5094 if (sa->util_sum) 5095 return false; 5096 5097 if (sa->runnable_sum) 5098 return false; 5099 5100 /* 5101 * _avg must be null when _sum are null because _avg = _sum / divider 5102 * Make sure that rounding and/or propagation of PELT values never 5103 * break this. 5104 */ 5105 WARN_ON_ONCE(sa->load_avg || 5106 sa->util_avg || 5107 sa->runnable_avg); 5108 5109 return true; 5110 } 5111 5112 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq) 5113 { 5114 return u64_u32_load_copy(cfs_rq->avg.last_update_time, 5115 cfs_rq->last_update_time_copy); 5116 } 5117 #ifdef CONFIG_FAIR_GROUP_SCHED 5118 /* 5119 * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list 5120 * immediately before a parent cfs_rq, and cfs_rqs are removed from the list 5121 * bottom-up, we only have to test whether the cfs_rq before us on the list 5122 * is our child. 5123 * If cfs_rq is not on the list, test whether a child needs its to be added to 5124 * connect a branch to the tree * (see list_add_leaf_cfs_rq() for details). 5125 */ 5126 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq) 5127 { 5128 struct cfs_rq *prev_cfs_rq; 5129 struct list_head *prev; 5130 struct rq *rq = rq_of(cfs_rq); 5131 5132 if (cfs_rq->on_list) { 5133 prev = cfs_rq->leaf_cfs_rq_list.prev; 5134 } else { 5135 prev = rq->tmp_alone_branch; 5136 } 5137 5138 if (prev == &rq->leaf_cfs_rq_list) 5139 return false; 5140 5141 prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list); 5142 5143 return (prev_cfs_rq->tg->parent == cfs_rq->tg); 5144 } 5145 5146 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq) 5147 { 5148 if (cfs_rq->load.weight) 5149 return false; 5150 5151 if (!load_avg_is_decayed(&cfs_rq->avg)) 5152 return false; 5153 5154 if (child_cfs_rq_on_list(cfs_rq)) 5155 return false; 5156 5157 if (cfs_rq->tg_load_avg_contrib) 5158 return false; 5159 5160 return true; 5161 } 5162 5163 /** 5164 * update_tg_load_avg - update the tg's load avg 5165 * @cfs_rq: the cfs_rq whose avg changed 5166 * 5167 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load. 5168 * However, because tg->load_avg is a global value there are performance 5169 * considerations. 5170 * 5171 * In order to avoid having to look at the other cfs_rq's, we use a 5172 * differential update where we store the last value we propagated. This in 5173 * turn allows skipping updates if the differential is 'small'. 5174 * 5175 * Updating tg's load_avg is necessary before update_cfs_group(). 5176 */ 5177 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) 5178 { 5179 long dl, dr; 5180 u64 now; 5181 5182 /* 5183 * No need to update load_avg for root_task_group as it is not used. 5184 */ 5185 if (cfs_rq->tg == &root_task_group) 5186 return; 5187 5188 /* rq has been offline and doesn't contribute to the share anymore: */ 5189 if (!cpu_active(cpu_of(rq_of(cfs_rq)))) 5190 return; 5191 5192 /* 5193 * For migration heavy workloads, access to tg->load_avg can be 5194 * unbound. Limit the update rate to at most once per ms. 5195 */ 5196 now = rq_clock(rq_of(cfs_rq)); 5197 if (now - cfs_rq->last_update_tg_load_avg < NSEC_PER_MSEC) 5198 return; 5199 5200 dl = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib; 5201 dr = cfs_rq->avg.runnable_avg - cfs_rq->tg_runnable_avg_contrib; 5202 if (abs(dl) > cfs_rq->tg_load_avg_contrib / 64 || 5203 abs(dr) > cfs_rq->tg_runnable_avg_contrib / 64) { 5204 atomic_long_add(dl, &cfs_rq->tg->load_avg); 5205 atomic_long_add(dr, &cfs_rq->tg->runnable_avg); 5206 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg; 5207 cfs_rq->tg_runnable_avg_contrib = cfs_rq->avg.runnable_avg; 5208 cfs_rq->last_update_tg_load_avg = now; 5209 } 5210 } 5211 5212 static inline void clear_tg_load_avg(struct cfs_rq *cfs_rq) 5213 { 5214 long dl, dr; 5215 u64 now; 5216 5217 /* 5218 * No need to update load_avg for root_task_group, as it is not used. 5219 */ 5220 if (cfs_rq->tg == &root_task_group) 5221 return; 5222 5223 now = rq_clock(rq_of(cfs_rq)); 5224 dl = 0 - cfs_rq->tg_load_avg_contrib; 5225 dr = 0 - cfs_rq->tg_runnable_avg_contrib; 5226 atomic_long_add(dl, &cfs_rq->tg->load_avg); 5227 atomic_long_add(dr, &cfs_rq->tg->runnable_avg); 5228 cfs_rq->tg_load_avg_contrib = 0; 5229 cfs_rq->tg_runnable_avg_contrib = 0; 5230 cfs_rq->last_update_tg_load_avg = now; 5231 } 5232 5233 /* CPU offline callback: */ 5234 static void __maybe_unused clear_tg_offline_cfs_rqs(struct rq *rq) 5235 { 5236 struct task_group *tg; 5237 5238 lockdep_assert_rq_held(rq); 5239 5240 /* 5241 * The rq clock has already been updated in 5242 * set_rq_offline(), so we should skip updating 5243 * the rq clock again in unthrottle_cfs_rq(). 5244 */ 5245 rq_clock_start_loop_update(rq); 5246 5247 guard(rcu)(); 5248 5249 list_for_each_entry_rcu(tg, &task_groups, list) { 5250 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq)); 5251 5252 clear_tg_load_avg(cfs_rq); 5253 } 5254 5255 rq_clock_stop_loop_update(rq); 5256 } 5257 5258 /* 5259 * Called within set_task_rq() right before setting a task's CPU. The 5260 * caller only guarantees p->pi_lock is held; no other assumptions, 5261 * including the state of rq->lock, should be made. 5262 */ 5263 void set_task_rq_fair(struct sched_entity *se, 5264 struct cfs_rq *prev, struct cfs_rq *next) 5265 { 5266 u64 p_last_update_time; 5267 u64 n_last_update_time; 5268 5269 if (!sched_feat(ATTACH_AGE_LOAD)) 5270 return; 5271 5272 /* 5273 * We are supposed to update the task to "current" time, then its up to 5274 * date and ready to go to new CPU/cfs_rq. But we have difficulty in 5275 * getting what current time is, so simply throw away the out-of-date 5276 * time. This will result in the wakee task is less decayed, but giving 5277 * the wakee more load sounds not bad. 5278 */ 5279 if (!(se->avg.last_update_time && prev)) 5280 return; 5281 5282 p_last_update_time = cfs_rq_last_update_time(prev); 5283 n_last_update_time = cfs_rq_last_update_time(next); 5284 5285 __update_load_avg_blocked_se(p_last_update_time, se); 5286 se->avg.last_update_time = n_last_update_time; 5287 } 5288 5289 /* 5290 * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to 5291 * propagate its contribution. The key to this propagation is the invariant 5292 * that for each group: 5293 * 5294 * ge->avg == grq->avg (1) 5295 * 5296 * _IFF_ we look at the pure running and runnable sums. Because they 5297 * represent the very same entity, just at different points in the hierarchy. 5298 * 5299 * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial 5300 * and simply copies the running/runnable sum over (but still wrong, because 5301 * the group entity and group rq do not have their PELT windows aligned). 5302 * 5303 * However, update_tg_cfs_load() is more complex. So we have: 5304 * 5305 * ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg (2) 5306 * 5307 * And since, like util, the runnable part should be directly transferable, 5308 * the following would _appear_ to be the straight forward approach: 5309 * 5310 * grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg (3) 5311 * 5312 * And per (1) we have: 5313 * 5314 * ge->avg.runnable_avg == grq->avg.runnable_avg 5315 * 5316 * Which gives: 5317 * 5318 * ge->load.weight * grq->avg.load_avg 5319 * ge->avg.load_avg = ----------------------------------- (4) 5320 * grq->load.weight 5321 * 5322 * Except that is wrong! 5323 * 5324 * Because while for entities historical weight is not important and we 5325 * really only care about our future and therefore can consider a pure 5326 * runnable sum, runqueues can NOT do this. 5327 * 5328 * We specifically want runqueues to have a load_avg that includes 5329 * historical weights. Those represent the blocked load, the load we expect 5330 * to (shortly) return to us. This only works by keeping the weights as 5331 * integral part of the sum. We therefore cannot decompose as per (3). 5332 * 5333 * Another reason this doesn't work is that runnable isn't a 0-sum entity. 5334 * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the 5335 * rq itself is runnable anywhere between 2/3 and 1 depending on how the 5336 * runnable section of these tasks overlap (or not). If they were to perfectly 5337 * align the rq as a whole would be runnable 2/3 of the time. If however we 5338 * always have at least 1 runnable task, the rq as a whole is always runnable. 5339 * 5340 * So we'll have to approximate.. :/ 5341 * 5342 * Given the constraint: 5343 * 5344 * ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX 5345 * 5346 * We can construct a rule that adds runnable to a rq by assuming minimal 5347 * overlap. 5348 * 5349 * On removal, we'll assume each task is equally runnable; which yields: 5350 * 5351 * grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight 5352 * 5353 * XXX: only do this for the part of runnable > running ? 5354 * 5355 */ 5356 static inline void 5357 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq) 5358 { 5359 long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg; 5360 u32 new_sum, divider; 5361 5362 /* Nothing to update */ 5363 if (!delta_avg) 5364 return; 5365 5366 /* 5367 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se. 5368 * See ___update_load_avg() for details. 5369 */ 5370 divider = get_pelt_divider(&cfs_rq->avg); 5371 5372 /* Set new sched_entity's utilization */ 5373 se->avg.util_avg = gcfs_rq->avg.util_avg; 5374 new_sum = se->avg.util_avg * divider; 5375 delta_sum = (long)new_sum - (long)se->avg.util_sum; 5376 se->avg.util_sum = new_sum; 5377 5378 /* Update parent cfs_rq utilization */ 5379 __update_sa(&cfs_rq->avg, util, delta_avg, delta_sum); 5380 } 5381 5382 static inline void 5383 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq) 5384 { 5385 long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg; 5386 u64 new_sum; 5387 u32 divider; 5388 5389 /* Nothing to update */ 5390 if (!delta_avg) 5391 return; 5392 5393 /* 5394 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se. 5395 * See ___update_load_avg() for details. 5396 */ 5397 divider = get_pelt_divider(&cfs_rq->avg); 5398 5399 /* Set new sched_entity's runnable */ 5400 se->avg.runnable_avg = gcfs_rq->avg.runnable_avg; 5401 new_sum = (u64)se->avg.runnable_avg * divider; 5402 delta_sum = (long)new_sum - (long)se->avg.runnable_sum; 5403 se->avg.runnable_sum = new_sum; 5404 5405 /* Update parent cfs_rq runnable */ 5406 __update_sa(&cfs_rq->avg, runnable, delta_avg, delta_sum); 5407 } 5408 5409 static inline void 5410 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq) 5411 { 5412 long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum; 5413 unsigned long load_avg; 5414 u64 load_sum = 0; 5415 s64 delta_sum; 5416 u32 divider; 5417 5418 if (!runnable_sum) 5419 return; 5420 5421 gcfs_rq->prop_runnable_sum = 0; 5422 5423 /* 5424 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se. 5425 * See ___update_load_avg() for details. 5426 */ 5427 divider = get_pelt_divider(&cfs_rq->avg); 5428 5429 if (runnable_sum >= 0) { 5430 /* 5431 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until 5432 * the CPU is saturated running == runnable. 5433 */ 5434 runnable_sum += se->avg.load_sum; 5435 runnable_sum = min_t(long, runnable_sum, divider); 5436 } else { 5437 /* 5438 * Estimate the new unweighted runnable_sum of the gcfs_rq by 5439 * assuming all tasks are equally runnable. 5440 */ 5441 if (scale_load_down(gcfs_rq->load.weight)) { 5442 load_sum = div_u64(gcfs_rq->avg.load_sum, 5443 scale_load_down(gcfs_rq->load.weight)); 5444 } 5445 5446 /* But make sure to not inflate se's runnable */ 5447 runnable_sum = min(se->avg.load_sum, load_sum); 5448 } 5449 5450 /* 5451 * runnable_sum can't be lower than running_sum 5452 * Rescale running sum to be in the same range as runnable sum 5453 * running_sum is in [0 : LOAD_AVG_MAX << SCHED_CAPACITY_SHIFT] 5454 * runnable_sum is in [0 : LOAD_AVG_MAX] 5455 */ 5456 running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT; 5457 runnable_sum = max(runnable_sum, running_sum); 5458 5459 load_sum = se_weight(se) * runnable_sum; 5460 load_avg = div_u64(load_sum, divider); 5461 5462 delta_avg = load_avg - se->avg.load_avg; 5463 if (!delta_avg) 5464 return; 5465 5466 delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum; 5467 5468 se->avg.load_sum = runnable_sum; 5469 se->avg.load_avg = load_avg; 5470 __update_sa(&cfs_rq->avg, load, delta_avg, delta_sum); 5471 } 5472 5473 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) 5474 { 5475 cfs_rq->propagate = 1; 5476 cfs_rq->prop_runnable_sum += runnable_sum; 5477 } 5478 5479 /* Update task and its cfs_rq load average */ 5480 static inline int propagate_entity_load_avg(struct sched_entity *se) 5481 { 5482 struct cfs_rq *cfs_rq, *gcfs_rq; 5483 5484 if (entity_is_task(se)) 5485 return 0; 5486 5487 gcfs_rq = group_cfs_rq(se); 5488 if (!gcfs_rq->propagate) 5489 return 0; 5490 5491 gcfs_rq->propagate = 0; 5492 5493 cfs_rq = cfs_rq_of(se); 5494 5495 add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum); 5496 5497 update_tg_cfs_util(cfs_rq, se, gcfs_rq); 5498 update_tg_cfs_runnable(cfs_rq, se, gcfs_rq); 5499 update_tg_cfs_load(cfs_rq, se, gcfs_rq); 5500 5501 trace_pelt_cfs_tp(cfs_rq); 5502 trace_pelt_se_tp(se); 5503 5504 return 1; 5505 } 5506 5507 /* 5508 * Check if we need to update the load and the utilization of a blocked 5509 * group_entity: 5510 */ 5511 static inline bool skip_blocked_update(struct sched_entity *se) 5512 { 5513 struct cfs_rq *gcfs_rq = group_cfs_rq(se); 5514 5515 /* 5516 * If sched_entity still have not zero load or utilization, we have to 5517 * decay it: 5518 */ 5519 if (se->avg.load_avg || se->avg.util_avg) 5520 return false; 5521 5522 /* 5523 * If there is a pending propagation, we have to update the load and 5524 * the utilization of the sched_entity: 5525 */ 5526 if (gcfs_rq->propagate) 5527 return false; 5528 5529 /* 5530 * Otherwise, the load and the utilization of the sched_entity is 5531 * already zero and there is no pending propagation, so it will be a 5532 * waste of time to try to decay it: 5533 */ 5534 return true; 5535 } 5536 5537 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 5538 5539 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {} 5540 5541 static inline void clear_tg_offline_cfs_rqs(struct rq *rq) {} 5542 5543 static inline int propagate_entity_load_avg(struct sched_entity *se) 5544 { 5545 return 0; 5546 } 5547 5548 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {} 5549 5550 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 5551 5552 #ifdef CONFIG_NO_HZ_COMMON 5553 static inline void migrate_se_pelt_lag(struct sched_entity *se) 5554 { 5555 u64 throttled = 0, now, lut; 5556 struct cfs_rq *cfs_rq; 5557 struct rq *rq; 5558 bool is_idle; 5559 5560 if (load_avg_is_decayed(&se->avg)) 5561 return; 5562 5563 cfs_rq = cfs_rq_of(se); 5564 rq = rq_of(cfs_rq); 5565 5566 rcu_read_lock(); 5567 is_idle = is_idle_task(rcu_dereference_all(rq->curr)); 5568 rcu_read_unlock(); 5569 5570 /* 5571 * The lag estimation comes with a cost we don't want to pay all the 5572 * time. Hence, limiting to the case where the source CPU is idle and 5573 * we know we are at the greatest risk to have an outdated clock. 5574 */ 5575 if (!is_idle) 5576 return; 5577 5578 /* 5579 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where: 5580 * 5581 * last_update_time (the cfs_rq's last_update_time) 5582 * = cfs_rq_clock_pelt()@cfs_rq_idle 5583 * = rq_clock_pelt()@cfs_rq_idle 5584 * - cfs->throttled_clock_pelt_time@cfs_rq_idle 5585 * 5586 * cfs_idle_lag (delta between rq's update and cfs_rq's update) 5587 * = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle 5588 * 5589 * rq_idle_lag (delta between now and rq's update) 5590 * = sched_clock_cpu() - rq_clock()@rq_idle 5591 * 5592 * We can then write: 5593 * 5594 * now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time + 5595 * sched_clock_cpu() - rq_clock()@rq_idle 5596 * Where: 5597 * rq_clock_pelt()@rq_idle is rq->clock_pelt_idle 5598 * rq_clock()@rq_idle is rq->clock_idle 5599 * cfs->throttled_clock_pelt_time@cfs_rq_idle 5600 * is cfs_rq->throttled_pelt_idle 5601 */ 5602 5603 #ifdef CONFIG_CFS_BANDWIDTH 5604 throttled = u64_u32_load(cfs_rq->throttled_pelt_idle); 5605 /* The clock has been stopped for throttling */ 5606 if (throttled == U64_MAX) 5607 return; 5608 #endif 5609 now = u64_u32_load(rq->clock_pelt_idle); 5610 /* 5611 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case 5612 * is observed the old clock_pelt_idle value and the new clock_idle, 5613 * which lead to an underestimation. The opposite would lead to an 5614 * overestimation. 5615 */ 5616 smp_rmb(); 5617 lut = cfs_rq_last_update_time(cfs_rq); 5618 5619 now -= throttled; 5620 if (now < lut) 5621 /* 5622 * cfs_rq->avg.last_update_time is more recent than our 5623 * estimation, let's use it. 5624 */ 5625 now = lut; 5626 else 5627 now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle); 5628 5629 __update_load_avg_blocked_se(now, se); 5630 } 5631 #else /* !CONFIG_NO_HZ_COMMON: */ 5632 static void migrate_se_pelt_lag(struct sched_entity *se) {} 5633 #endif /* !CONFIG_NO_HZ_COMMON */ 5634 5635 /** 5636 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages 5637 * @now: current time, as per cfs_rq_clock_pelt() 5638 * @cfs_rq: cfs_rq to update 5639 * 5640 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable) 5641 * avg. The immediate corollary is that all (fair) tasks must be attached. 5642 * 5643 * cfs_rq->avg is used for task_h_load() and update_cfs_group() for example. 5644 * 5645 * Return: true if the load decayed or we removed load. 5646 * 5647 * Since both these conditions indicate a changed cfs_rq->avg.load we should 5648 * call update_tg_load_avg() when this function returns true. 5649 */ 5650 static inline int 5651 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq) 5652 { 5653 unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0; 5654 struct sched_avg *sa = &cfs_rq->avg; 5655 int decayed = 0; 5656 5657 if (cfs_rq->removed.nr) { 5658 unsigned long r; 5659 u32 divider = get_pelt_divider(&cfs_rq->avg); 5660 5661 raw_spin_lock(&cfs_rq->removed.lock); 5662 swap(cfs_rq->removed.util_avg, removed_util); 5663 swap(cfs_rq->removed.load_avg, removed_load); 5664 swap(cfs_rq->removed.runnable_avg, removed_runnable); 5665 cfs_rq->removed.nr = 0; 5666 raw_spin_unlock(&cfs_rq->removed.lock); 5667 5668 r = removed_load; 5669 __update_sa(sa, load, -r, -r*divider); 5670 5671 r = removed_util; 5672 __update_sa(sa, util, -r, -r*divider); 5673 5674 r = removed_runnable; 5675 __update_sa(sa, runnable, -r, -r*divider); 5676 5677 /* 5678 * removed_runnable is the unweighted version of removed_load so we 5679 * can use it to estimate removed_load_sum. 5680 */ 5681 add_tg_cfs_propagate(cfs_rq, 5682 -(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT); 5683 5684 decayed = 1; 5685 } 5686 5687 decayed |= __update_load_avg_cfs_rq(now, cfs_rq); 5688 u64_u32_store_copy(sa->last_update_time, 5689 cfs_rq->last_update_time_copy, 5690 sa->last_update_time); 5691 return decayed; 5692 } 5693 5694 /** 5695 * attach_entity_load_avg - attach this entity to its cfs_rq load avg 5696 * @cfs_rq: cfs_rq to attach to 5697 * @se: sched_entity to attach 5698 * 5699 * Must call update_cfs_rq_load_avg() before this, since we rely on 5700 * cfs_rq->avg.last_update_time being current. 5701 */ 5702 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) 5703 { 5704 /* 5705 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se. 5706 * See ___update_load_avg() for details. 5707 */ 5708 u32 divider = get_pelt_divider(&cfs_rq->avg); 5709 5710 /* 5711 * When we attach the @se to the @cfs_rq, we must align the decay 5712 * window because without that, really weird and wonderful things can 5713 * happen. 5714 * 5715 * XXX illustrate 5716 */ 5717 se->avg.last_update_time = cfs_rq->avg.last_update_time; 5718 se->avg.period_contrib = cfs_rq->avg.period_contrib; 5719 5720 /* 5721 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new 5722 * period_contrib. This isn't strictly correct, but since we're 5723 * entirely outside of the PELT hierarchy, nobody cares if we truncate 5724 * _sum a little. 5725 */ 5726 se->avg.util_sum = se->avg.util_avg * divider; 5727 5728 se->avg.runnable_sum = se->avg.runnable_avg * divider; 5729 5730 se->avg.load_sum = se->avg.load_avg * divider; 5731 if (se_weight(se) < se->avg.load_sum) 5732 se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se)); 5733 else 5734 se->avg.load_sum = 1; 5735 5736 enqueue_load_avg(cfs_rq, se); 5737 cfs_rq->avg.util_avg += se->avg.util_avg; 5738 cfs_rq->avg.util_sum += se->avg.util_sum; 5739 cfs_rq->avg.runnable_avg += se->avg.runnable_avg; 5740 cfs_rq->avg.runnable_sum += se->avg.runnable_sum; 5741 5742 add_tg_cfs_propagate(cfs_rq, se->avg.load_sum); 5743 5744 cfs_rq_util_change(cfs_rq, 0); 5745 5746 trace_pelt_cfs_tp(cfs_rq); 5747 } 5748 5749 /** 5750 * detach_entity_load_avg - detach this entity from its cfs_rq load avg 5751 * @cfs_rq: cfs_rq to detach from 5752 * @se: sched_entity to detach 5753 * 5754 * Must call update_cfs_rq_load_avg() before this, since we rely on 5755 * cfs_rq->avg.last_update_time being current. 5756 */ 5757 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) 5758 { 5759 dequeue_load_avg(cfs_rq, se); 5760 __update_sa(&cfs_rq->avg, util, -se->avg.util_avg, -se->avg.util_sum); 5761 __update_sa(&cfs_rq->avg, runnable, -se->avg.runnable_avg, -se->avg.runnable_sum); 5762 5763 add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum); 5764 5765 cfs_rq_util_change(cfs_rq, 0); 5766 5767 trace_pelt_cfs_tp(cfs_rq); 5768 } 5769 5770 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100) 5771 5772 static inline void util_est_update(struct sched_entity *se) 5773 { 5774 unsigned int ewma, dequeued, last_ewma_diff; 5775 5776 if (!sched_feat(UTIL_EST)) 5777 return; 5778 5779 /* Get current estimate of utilization */ 5780 ewma = READ_ONCE(se->avg.util_est); 5781 5782 /* 5783 * If the PELT values haven't changed since enqueue time, 5784 * skip the util_est update. 5785 */ 5786 if (ewma & UTIL_AVG_UNCHANGED) 5787 return; 5788 5789 /* Get utilization at dequeue */ 5790 dequeued = READ_ONCE(se->avg.util_avg); 5791 5792 /* 5793 * Reset EWMA on utilization increases, the moving average is used only 5794 * to smooth utilization decreases. 5795 */ 5796 if (ewma <= dequeued) { 5797 ewma = dequeued; 5798 goto done; 5799 } 5800 5801 /* 5802 * Skip update of task's estimated utilization when its members are 5803 * already ~1% close to its last activation value. 5804 */ 5805 last_ewma_diff = ewma - dequeued; 5806 if (last_ewma_diff < UTIL_EST_MARGIN) 5807 goto done; 5808 5809 /* 5810 * To avoid underestimate of task utilization, skip updates of EWMA if 5811 * we cannot grant that thread got all CPU time it wanted. 5812 */ 5813 if ((dequeued + UTIL_EST_MARGIN) < READ_ONCE(se->avg.runnable_avg)) 5814 goto done; 5815 5816 /* 5817 * Update Task's estimated utilization 5818 * 5819 * When *p completes an activation we can consolidate another sample 5820 * of the task size. This is done by using this value to update the 5821 * Exponential Weighted Moving Average (EWMA): 5822 * 5823 * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1) 5824 * = w * task_util(p) + ewma(t-1) - w * ewma(t-1) 5825 * = w * (task_util(p) - ewma(t-1)) + ewma(t-1) 5826 * = w * ( -last_ewma_diff ) + ewma(t-1) 5827 * = w * (-last_ewma_diff + ewma(t-1) / w) 5828 * 5829 * Where 'w' is the weight of new samples, which is configured to be 5830 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT) 5831 */ 5832 ewma <<= UTIL_EST_WEIGHT_SHIFT; 5833 ewma -= last_ewma_diff; 5834 ewma >>= UTIL_EST_WEIGHT_SHIFT; 5835 done: 5836 ewma |= UTIL_AVG_UNCHANGED; 5837 WRITE_ONCE(se->avg.util_est, ewma); 5838 5839 trace_sched_util_est_se_tp(se); 5840 } 5841 5842 /* 5843 * Optional action to be done while updating the load average 5844 */ 5845 #define UPDATE_TG 0x01 5846 #define SKIP_AGE_LOAD 0x02 5847 #define DO_ATTACH 0x04 5848 #define DO_DETACH 0x08 5849 #define UPDATE_UTIL_EST 0x10 5850 5851 /* Update task and its cfs_rq load average */ 5852 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 5853 { 5854 u64 now = cfs_rq_clock_pelt(cfs_rq); 5855 int decayed; 5856 5857 /* 5858 * Track task load average for carrying it to new CPU after migrated, and 5859 * track group sched_entity load average for task_h_load calculation in migration 5860 */ 5861 if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD)) 5862 __update_load_avg_se(now, cfs_rq, se); 5863 5864 decayed = update_cfs_rq_load_avg(now, cfs_rq); 5865 decayed |= propagate_entity_load_avg(se); 5866 5867 if (!se->avg.last_update_time && (flags & DO_ATTACH)) { 5868 5869 /* 5870 * DO_ATTACH means we're here from enqueue_entity(). 5871 * !last_update_time means we've passed through 5872 * migrate_task_rq_fair() indicating we migrated. 5873 * 5874 * IOW we're enqueueing a task on a new CPU. 5875 */ 5876 attach_entity_load_avg(cfs_rq, se); 5877 update_tg_load_avg(cfs_rq); 5878 5879 } else if (flags & DO_DETACH) { 5880 /* 5881 * DO_DETACH means we're here from dequeue_entity() 5882 * and we are migrating task out of the CPU. 5883 */ 5884 detach_entity_load_avg(cfs_rq, se); 5885 update_tg_load_avg(cfs_rq); 5886 } else if (decayed) { 5887 cfs_rq_util_change(cfs_rq, 0); 5888 5889 if (flags & UPDATE_TG) 5890 update_tg_load_avg(cfs_rq); 5891 } 5892 5893 if (flags & UPDATE_UTIL_EST) 5894 util_est_update(se); 5895 } 5896 5897 /* 5898 * Synchronize entity load avg of dequeued entity without locking 5899 * the previous rq. 5900 */ 5901 static void sync_entity_load_avg(struct sched_entity *se) 5902 { 5903 struct cfs_rq *cfs_rq = cfs_rq_of(se); 5904 u64 last_update_time; 5905 5906 last_update_time = cfs_rq_last_update_time(cfs_rq); 5907 __update_load_avg_blocked_se(last_update_time, se); 5908 } 5909 5910 /* 5911 * Task first catches up with cfs_rq, and then subtract 5912 * itself from the cfs_rq (task must be off the queue now). 5913 */ 5914 static void remove_entity_load_avg(struct sched_entity *se) 5915 { 5916 struct cfs_rq *cfs_rq = cfs_rq_of(se); 5917 unsigned long flags; 5918 5919 /* 5920 * tasks cannot exit without having gone through wake_up_new_task() -> 5921 * enqueue_task_fair() which will have added things to the cfs_rq, 5922 * so we can remove unconditionally. 5923 */ 5924 5925 sync_entity_load_avg(se); 5926 5927 raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags); 5928 ++cfs_rq->removed.nr; 5929 cfs_rq->removed.util_avg += se->avg.util_avg; 5930 cfs_rq->removed.load_avg += se->avg.load_avg; 5931 cfs_rq->removed.runnable_avg += se->avg.runnable_avg; 5932 raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags); 5933 } 5934 5935 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq) 5936 { 5937 return cfs_rq->avg.runnable_avg; 5938 } 5939 5940 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq) 5941 { 5942 return cfs_rq->avg.load_avg; 5943 } 5944 5945 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf) 5946 __must_hold(__rq_lockp(this_rq)); 5947 5948 static inline unsigned long task_util(struct task_struct *p) 5949 { 5950 return READ_ONCE(p->se.avg.util_avg); 5951 } 5952 5953 static inline unsigned long _task_util_est(struct task_struct *p) 5954 { 5955 return READ_ONCE(p->se.avg.util_est) & ~UTIL_AVG_UNCHANGED; 5956 } 5957 5958 static inline unsigned long task_util_est(struct task_struct *p) 5959 { 5960 return max(task_util(p), _task_util_est(p)); 5961 } 5962 5963 static inline void util_est_enqueue(struct cfs_rq *cfs_rq, 5964 struct task_struct *p) 5965 { 5966 unsigned int enqueued; 5967 5968 if (!sched_feat(UTIL_EST)) 5969 return; 5970 5971 /* Update root cfs_rq's estimated utilization */ 5972 enqueued = cfs_rq->avg.util_est; 5973 enqueued += _task_util_est(p); 5974 WRITE_ONCE(cfs_rq->avg.util_est, enqueued); 5975 5976 trace_sched_util_est_cfs_tp(cfs_rq); 5977 } 5978 5979 static inline void util_est_dequeue(struct cfs_rq *cfs_rq, 5980 struct task_struct *p) 5981 { 5982 unsigned int enqueued; 5983 5984 if (!sched_feat(UTIL_EST)) 5985 return; 5986 5987 /* Update root cfs_rq's estimated utilization */ 5988 enqueued = cfs_rq->avg.util_est; 5989 enqueued -= min_t(unsigned int, enqueued, _task_util_est(p)); 5990 WRITE_ONCE(cfs_rq->avg.util_est, enqueued); 5991 5992 trace_sched_util_est_cfs_tp(cfs_rq); 5993 } 5994 5995 static inline unsigned long get_actual_cpu_capacity(int cpu) 5996 { 5997 unsigned long capacity = arch_scale_cpu_capacity(cpu); 5998 5999 capacity -= max(hw_load_avg(cpu_rq(cpu)), cpufreq_get_pressure(cpu)); 6000 6001 return capacity; 6002 } 6003 6004 static inline int util_fits_cpu(unsigned long util, 6005 unsigned long uclamp_min, 6006 unsigned long uclamp_max, 6007 int cpu) 6008 { 6009 unsigned long capacity = capacity_of(cpu); 6010 unsigned long capacity_orig; 6011 bool fits, uclamp_max_fits; 6012 6013 /* 6014 * Check if the real util fits without any uclamp boost/cap applied. 6015 */ 6016 fits = fits_capacity(util, capacity); 6017 6018 if (!uclamp_is_used()) 6019 return fits; 6020 6021 /* 6022 * We must use arch_scale_cpu_capacity() for comparing against uclamp_min and 6023 * uclamp_max. We only care about capacity pressure (by using 6024 * capacity_of()) for comparing against the real util. 6025 * 6026 * If a task is boosted to 1024 for example, we don't want a tiny 6027 * pressure to skew the check whether it fits a CPU or not. 6028 * 6029 * Similarly if a task is capped to arch_scale_cpu_capacity(little_cpu), it 6030 * should fit a little cpu even if there's some pressure. 6031 * 6032 * Only exception is for HW or cpufreq pressure since it has a direct impact 6033 * on available OPP of the system. 6034 * 6035 * We honour it for uclamp_min only as a drop in performance level 6036 * could result in not getting the requested minimum performance level. 6037 * 6038 * For uclamp_max, we can tolerate a drop in performance level as the 6039 * goal is to cap the task. So it's okay if it's getting less. 6040 */ 6041 capacity_orig = arch_scale_cpu_capacity(cpu); 6042 6043 /* 6044 * We want to force a task to fit a cpu as implied by uclamp_max. 6045 * But we do have some corner cases to cater for.. 6046 * 6047 * 6048 * C=z 6049 * | ___ 6050 * | C=y | | 6051 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max 6052 * | C=x | | | | 6053 * | ___ | | | | 6054 * | | | | | | | (util somewhere in this region) 6055 * | | | | | | | 6056 * | | | | | | | 6057 * +---------------------------------------- 6058 * CPU0 CPU1 CPU2 6059 * 6060 * In the above example if a task is capped to a specific performance 6061 * point, y, then when: 6062 * 6063 * * util = 80% of x then it does not fit on CPU0 and should migrate 6064 * to CPU1 6065 * * util = 80% of y then it is forced to fit on CPU1 to honour 6066 * uclamp_max request. 6067 * 6068 * which is what we're enforcing here. A task always fits if 6069 * uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig, 6070 * the normal upmigration rules should withhold still. 6071 * 6072 * Only exception is when we are on max capacity, then we need to be 6073 * careful not to block overutilized state. This is so because: 6074 * 6075 * 1. There's no concept of capping at max_capacity! We can't go 6076 * beyond this performance level anyway. 6077 * 2. The system is being saturated when we're operating near 6078 * max capacity, it doesn't make sense to block overutilized. 6079 */ 6080 uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE); 6081 uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig); 6082 fits = fits || uclamp_max_fits; 6083 6084 /* 6085 * 6086 * C=z 6087 * | ___ (region a, capped, util >= uclamp_max) 6088 * | C=y | | 6089 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max 6090 * | C=x | | | | 6091 * | ___ | | | | (region b, uclamp_min <= util <= uclamp_max) 6092 * |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min 6093 * | | | | | | | 6094 * | | | | | | | (region c, boosted, util < uclamp_min) 6095 * +---------------------------------------- 6096 * CPU0 CPU1 CPU2 6097 * 6098 * a) If util > uclamp_max, then we're capped, we don't care about 6099 * actual fitness value here. We only care if uclamp_max fits 6100 * capacity without taking margin/pressure into account. 6101 * See comment above. 6102 * 6103 * b) If uclamp_min <= util <= uclamp_max, then the normal 6104 * fits_capacity() rules apply. Except we need to ensure that we 6105 * enforce we remain within uclamp_max, see comment above. 6106 * 6107 * c) If util < uclamp_min, then we are boosted. Same as (b) but we 6108 * need to take into account the boosted value fits the CPU without 6109 * taking margin/pressure into account. 6110 * 6111 * Cases (a) and (b) are handled in the 'fits' variable already. We 6112 * just need to consider an extra check for case (c) after ensuring we 6113 * handle the case uclamp_min > uclamp_max. 6114 */ 6115 uclamp_min = min(uclamp_min, uclamp_max); 6116 if (fits && (util < uclamp_min) && 6117 (uclamp_min > get_actual_cpu_capacity(cpu))) 6118 return -1; 6119 6120 return fits; 6121 } 6122 6123 static inline int task_fits_cpu(struct task_struct *p, int cpu) 6124 { 6125 unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN); 6126 unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX); 6127 unsigned long util = task_util_est(p); 6128 /* 6129 * Return true only if the cpu fully fits the task requirements, which 6130 * include the utilization but also the performance hints. 6131 */ 6132 return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0); 6133 } 6134 6135 static inline void update_misfit_status(struct task_struct *p, struct rq *rq) 6136 { 6137 int cpu = cpu_of(rq); 6138 6139 if (!sched_asym_cpucap_active()) 6140 return; 6141 6142 /* 6143 * Affinity allows us to go somewhere higher? Or are we on biggest 6144 * available CPU already? Or do we fit into this CPU ? 6145 */ 6146 if (!p || (p->nr_cpus_allowed == 1) || 6147 (arch_scale_cpu_capacity(cpu) == p->max_allowed_capacity) || 6148 task_fits_cpu(p, cpu)) { 6149 6150 rq->misfit_task_load = 0; 6151 return; 6152 } 6153 6154 /* 6155 * Make sure that misfit_task_load will not be null even if 6156 * task_h_load() returns 0. 6157 */ 6158 rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1); 6159 } 6160 6161 void __setparam_fair(struct task_struct *p, const struct sched_attr *attr) 6162 { 6163 struct sched_entity *se = &p->se; 6164 6165 p->static_prio = NICE_TO_PRIO(attr->sched_nice); 6166 if (attr->sched_runtime) { 6167 se->custom_slice = 1; 6168 se->slice = clamp_t(u64, attr->sched_runtime, 6169 NSEC_PER_MSEC/10, /* HZ=1000 * 10 */ 6170 NSEC_PER_MSEC*100); /* HZ=100 / 10 */ 6171 } else { 6172 se->custom_slice = 0; 6173 se->slice = sysctl_sched_base_slice; 6174 } 6175 } 6176 6177 static void 6178 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 6179 { 6180 u64 vslice, vruntime = avg_vruntime(cfs_rq); 6181 unsigned int nr_queued = cfs_rq->h_nr_queued; 6182 bool update_zero = false; 6183 s64 lag = 0; 6184 6185 if (!se->custom_slice) 6186 se->slice = sysctl_sched_base_slice; 6187 vslice = calc_delta_fair(se->slice, se); 6188 6189 if (flags & ENQUEUE_QUEUED) 6190 nr_queued -= 1; 6191 6192 /* 6193 * Due to how V is constructed as the weighted average of entities, 6194 * adding tasks with positive lag, or removing tasks with negative lag 6195 * will move 'time' backwards, this can screw around with the lag of 6196 * other tasks. 6197 * 6198 * EEVDF: placement strategy #1 / #2 6199 */ 6200 if (sched_feat(PLACE_LAG) && nr_queued && se->vlag) { 6201 struct sched_entity *curr = cfs_rq->curr; 6202 long load, weight; 6203 6204 lag = se->vlag; 6205 6206 /* 6207 * If we want to place a task and preserve lag, we have to 6208 * consider the effect of the new entity on the weighted 6209 * average and compensate for this, otherwise lag can quickly 6210 * evaporate. 6211 * 6212 * Lag is defined as: 6213 * 6214 * lag_i = S - s_i = w_i * (V - v_i) 6215 * 6216 * To avoid the 'w_i' term all over the place, we only track 6217 * the virtual lag: 6218 * 6219 * vl_i = V - v_i <=> v_i = V - vl_i 6220 * 6221 * And we take V to be the weighted average of all v: 6222 * 6223 * V = (\Sum w_j*v_j) / W 6224 * 6225 * Where W is: \Sum w_j 6226 * 6227 * Then, the weighted average after adding an entity with lag 6228 * vl_i is given by: 6229 * 6230 * V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i) 6231 * = (W*V + w_i*(V - vl_i)) / (W + w_i) 6232 * = (W*V + w_i*V - w_i*vl_i) / (W + w_i) 6233 * = (V*(W + w_i) - w_i*vl_i) / (W + w_i) 6234 * = V - w_i*vl_i / (W + w_i) 6235 * 6236 * And the actual lag after adding an entity with vl_i is: 6237 * 6238 * vl'_i = V' - v_i 6239 * = V - w_i*vl_i / (W + w_i) - (V - vl_i) 6240 * = vl_i - w_i*vl_i / (W + w_i) 6241 * 6242 * Which is strictly less than vl_i. So in order to preserve lag 6243 * we should inflate the lag before placement such that the 6244 * effective lag after placement comes out right. 6245 * 6246 * As such, invert the above relation for vl'_i to get the vl_i 6247 * we need to use such that the lag after placement is the lag 6248 * we computed before dequeue. 6249 * 6250 * vl'_i = vl_i - w_i*vl_i / (W + w_i) 6251 * = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i) 6252 * 6253 * (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i 6254 * = W*vl_i 6255 * 6256 * vl_i = (W + w_i)*vl'_i / W 6257 */ 6258 load = cfs_rq->sum_weight; 6259 if (curr && curr->on_rq) 6260 load += avg_vruntime_weight(cfs_rq, curr->h_load.weight); 6261 6262 weight = avg_vruntime_weight(cfs_rq, se->h_load.weight); 6263 lag *= load + weight; 6264 if (WARN_ON_ONCE(!load)) 6265 load = 1; 6266 lag = div64_long(lag, load); 6267 6268 /* 6269 * A heavy entity (relative to the tree) will pull the 6270 * avg_vruntime close to its vruntime position on enqueue. But 6271 * the zero_vruntime point is only updated at the next 6272 * update_deadline()/place_entity()/update_entity_lag(). 6273 * 6274 * Specifically (see the comment near avg_vruntime_weight()): 6275 * 6276 * sum_w_vruntime = \Sum (v_i - v0) * w_i 6277 * 6278 * Note that if v0 is near a light entity, both terms will be 6279 * small for the light entity, while in that case both terms 6280 * are large for the heavy entity, leading to risk of 6281 * overflow. 6282 * 6283 * OTOH if v0 is near the heavy entity, then the difference is 6284 * larger for the light entity, but the factor is small, while 6285 * for the heavy entity the difference is small but the factor 6286 * is large. Avoiding the multiplication overflow. 6287 */ 6288 if (weight > load) 6289 update_zero = true; 6290 } 6291 6292 se->vruntime = vruntime - lag; 6293 6294 if (update_zero) 6295 update_zero_vruntime(cfs_rq, -lag); 6296 6297 if (sched_feat(PLACE_REL_DEADLINE) && se->rel_deadline) { 6298 se->deadline += se->vruntime; 6299 se->rel_deadline = 0; 6300 return; 6301 } 6302 6303 /* 6304 * When joining the competition; the existing tasks will be, 6305 * on average, halfway through their slice, as such start tasks 6306 * off with half a slice to ease into the competition. 6307 */ 6308 if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL)) 6309 vslice /= 2; 6310 6311 /* 6312 * EEVDF: vd_i = ve_i + r_i/w_i 6313 */ 6314 se->deadline = se->vruntime + vslice; 6315 } 6316 6317 static void check_enqueue_throttle(struct cfs_rq *cfs_rq); 6318 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq); 6319 6320 static void 6321 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 6322 { 6323 /* 6324 * When enqueuing a sched_entity, we must: 6325 * - Update loads to have both entity and cfs_rq synced with now. 6326 * - For group_entity, update its runnable_weight to reflect the new 6327 * h_nr_runnable of its group cfs_rq. 6328 * - For group_entity, update its weight to reflect the new share of 6329 * its group cfs_rq 6330 * - Add its new weight to cfs_rq->load.weight 6331 */ 6332 update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH); 6333 se_update_runnable(se); 6334 /* 6335 * XXX update_load_avg() above will have attached us to the pelt sum; 6336 * but update_cfs_group() here will re-adjust the weight and have to 6337 * undo/redo all that. Seems wasteful. 6338 */ 6339 update_cfs_group(se); 6340 6341 account_entity_enqueue(cfs_rq, se); 6342 6343 /* Entity has migrated, no longer consider this task hot */ 6344 if (flags & ENQUEUE_MIGRATED) 6345 se->exec_start = 0; 6346 6347 check_schedstat_required(); 6348 update_stats_enqueue_fair(cfs_rq, se, flags); 6349 se->on_rq = 1; 6350 6351 if (cfs_rq->nr_queued == 1) { 6352 check_enqueue_throttle(cfs_rq); 6353 list_add_leaf_cfs_rq(cfs_rq); 6354 #ifdef CONFIG_CFS_BANDWIDTH 6355 if (cfs_rq->pelt_clock_throttled) { 6356 struct rq *rq = rq_of(cfs_rq); 6357 6358 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) - 6359 cfs_rq->throttled_clock_pelt; 6360 cfs_rq->pelt_clock_throttled = 0; 6361 } 6362 #endif 6363 } 6364 } 6365 6366 static void set_next_buddy(struct cfs_rq *cfs_rq, struct sched_entity *se) 6367 { 6368 if (WARN_ON_ONCE(!se->on_rq || se->sched_delayed)) 6369 return; 6370 if (se_is_idle(se)) 6371 return; 6372 cfs_rq->next = se; 6373 } 6374 6375 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se) 6376 { 6377 if (cfs_rq->next == se) 6378 cfs_rq->next = NULL; 6379 } 6380 6381 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq); 6382 6383 static void set_delayed(struct sched_entity *se) 6384 { 6385 se->sched_delayed = 1; 6386 6387 /* 6388 * Delayed se of cfs_rq have no tasks queued on them. 6389 * Do not adjust h_nr_runnable since __dequeue_task() 6390 * will account it for blocked tasks. 6391 */ 6392 if (!entity_is_task(se)) 6393 return; 6394 6395 for_each_sched_entity(se) { 6396 struct cfs_rq *cfs_rq = cfs_rq_of(se); 6397 6398 cfs_rq->h_nr_runnable--; 6399 } 6400 } 6401 6402 static void clear_delayed(struct sched_entity *se) 6403 { 6404 se->sched_delayed = 0; 6405 6406 /* 6407 * Delayed se of cfs_rq have no tasks queued on them. 6408 * Do not adjust h_nr_runnable since a dequeue has 6409 * already accounted for it or an enqueue of a task 6410 * below it will account for it in enqueue_task_fair(). 6411 */ 6412 if (!entity_is_task(se)) 6413 return; 6414 6415 for_each_sched_entity(se) { 6416 struct cfs_rq *cfs_rq = cfs_rq_of(se); 6417 6418 cfs_rq->h_nr_runnable++; 6419 } 6420 } 6421 6422 static void 6423 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 6424 { 6425 int action = UPDATE_TG; 6426 6427 if (entity_is_task(se)) { 6428 if (task_on_rq_migrating(task_of(se))) 6429 action |= DO_DETACH; 6430 6431 if ((flags & DEQUEUE_SLEEP) && !(flags & DEQUEUE_DELAYED)) 6432 action |= UPDATE_UTIL_EST; 6433 } 6434 6435 /* 6436 * When dequeuing a sched_entity, we must: 6437 * - Update loads to have both entity and cfs_rq synced with now. 6438 * - For group_entity, update its runnable_weight to reflect the new 6439 * h_nr_runnable of its group cfs_rq. 6440 * - Subtract its previous weight from cfs_rq->load.weight. 6441 * - For group entity, update its weight to reflect the new share 6442 * of its group cfs_rq. 6443 */ 6444 update_load_avg(cfs_rq, se, action); 6445 se_update_runnable(se); 6446 6447 update_stats_dequeue_fair(cfs_rq, se, flags); 6448 6449 se->on_rq = 0; 6450 account_entity_dequeue(cfs_rq, se); 6451 6452 /* return excess runtime on last dequeue */ 6453 return_cfs_rq_runtime(cfs_rq); 6454 6455 update_cfs_group(se); 6456 6457 if (cfs_rq->nr_queued == 0) { 6458 update_idle_cfs_rq_clock_pelt(cfs_rq); 6459 #ifdef CONFIG_CFS_BANDWIDTH 6460 if (throttled_hierarchy(cfs_rq)) { 6461 struct rq *rq = rq_of(cfs_rq); 6462 6463 list_del_leaf_cfs_rq(cfs_rq); 6464 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq); 6465 cfs_rq->pelt_clock_throttled = 1; 6466 } 6467 #endif 6468 } 6469 } 6470 6471 static void 6472 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) 6473 { 6474 /* 'current' is not kept within the tree. */ 6475 if (se->on_rq) { 6476 /* 6477 * Any task has to be enqueued before it get to execute on 6478 * a CPU. So account for the time it spent waiting on the 6479 * runqueue. 6480 */ 6481 update_stats_wait_end_fair(cfs_rq, se); 6482 update_load_avg(cfs_rq, se, UPDATE_TG); 6483 } 6484 6485 update_stats_curr_start(cfs_rq, se); 6486 WARN_ON_ONCE(cfs_rq->h_curr); 6487 cfs_rq->h_curr = se; 6488 6489 /* 6490 * Track our maximum slice length, if the CPU's load is at 6491 * least twice that of our own weight (i.e. don't track it 6492 * when there are only lesser-weight tasks around): 6493 */ 6494 if (schedstat_enabled() && 6495 rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) { 6496 struct sched_statistics *stats; 6497 6498 stats = __schedstats_from_se(se); 6499 __schedstat_set(stats->slice_max, 6500 max((u64)stats->slice_max, 6501 se->sum_exec_runtime - se->prev_sum_exec_runtime)); 6502 } 6503 6504 se->prev_sum_exec_runtime = se->sum_exec_runtime; 6505 } 6506 6507 static bool __dequeue_task(struct rq *rq, struct task_struct *p, int flags); 6508 6509 static struct sched_entity * 6510 pick_next_entity(struct rq *rq, bool protect) 6511 { 6512 struct cfs_rq *cfs_rq = &rq->cfs; 6513 struct sched_entity *se; 6514 6515 se = pick_eevdf(cfs_rq, protect); 6516 if (se->sched_delayed) { 6517 __dequeue_task(rq, task_of(se), DEQUEUE_SLEEP | DEQUEUE_DELAYED); 6518 /* 6519 * Must not reference @se again, see __block_task(). 6520 */ 6521 return NULL; 6522 } 6523 return se; 6524 } 6525 6526 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev) 6527 { 6528 /* 6529 * If still on the runqueue then deactivate_task() 6530 * was not called and update_curr() has to be done: 6531 */ 6532 if (prev->on_rq) 6533 update_curr(cfs_rq); 6534 6535 if (prev->on_rq) { 6536 update_stats_wait_start_fair(cfs_rq, prev); 6537 /* in !on_rq case, update occurred at dequeue */ 6538 update_load_avg(cfs_rq, prev, 0); 6539 } 6540 WARN_ON_ONCE(cfs_rq->h_curr != prev); 6541 cfs_rq->h_curr = NULL; 6542 } 6543 6544 static void 6545 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued) 6546 { 6547 /* 6548 * Update run-time statistics of the 'current'. 6549 */ 6550 update_curr(cfs_rq); 6551 6552 /* 6553 * Ensure that runnable average is periodically updated. 6554 */ 6555 update_load_avg(cfs_rq, curr, UPDATE_TG); 6556 update_cfs_group(curr); 6557 6558 #ifdef CONFIG_SCHED_HRTICK 6559 /* 6560 * queued ticks are scheduled to match the slice, so don't bother 6561 * validating it and just reschedule. 6562 */ 6563 if (queued) { 6564 resched_curr(rq_of(cfs_rq)); 6565 return; 6566 } 6567 #endif 6568 } 6569 6570 6571 /************************************************** 6572 * CFS bandwidth control machinery 6573 */ 6574 6575 #ifdef CONFIG_CFS_BANDWIDTH 6576 6577 #ifdef CONFIG_JUMP_LABEL 6578 static struct static_key __cfs_bandwidth_used; 6579 6580 static inline bool cfs_bandwidth_used(void) 6581 { 6582 return static_key_false(&__cfs_bandwidth_used); 6583 } 6584 6585 void cfs_bandwidth_usage_inc(void) 6586 { 6587 static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used); 6588 } 6589 6590 void cfs_bandwidth_usage_dec(void) 6591 { 6592 static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used); 6593 } 6594 #else /* !CONFIG_JUMP_LABEL: */ 6595 static bool cfs_bandwidth_used(void) 6596 { 6597 return true; 6598 } 6599 6600 void cfs_bandwidth_usage_inc(void) {} 6601 void cfs_bandwidth_usage_dec(void) {} 6602 #endif /* !CONFIG_JUMP_LABEL */ 6603 6604 static inline u64 sched_cfs_bandwidth_slice(void) 6605 { 6606 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC; 6607 } 6608 6609 /* 6610 * Replenish runtime according to assigned quota. We use sched_clock_cpu 6611 * directly instead of rq->clock to avoid adding additional synchronization 6612 * around rq->lock. 6613 * 6614 * requires cfs_b->lock 6615 */ 6616 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b) 6617 { 6618 s64 runtime; 6619 6620 if (unlikely(cfs_b->quota == RUNTIME_INF)) 6621 return; 6622 6623 cfs_b->runtime += cfs_b->quota; 6624 runtime = cfs_b->runtime_snap - cfs_b->runtime; 6625 if (runtime > 0) { 6626 cfs_b->burst_time += runtime; 6627 cfs_b->nr_burst++; 6628 } 6629 6630 cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst); 6631 cfs_b->runtime_snap = cfs_b->runtime; 6632 } 6633 6634 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg) 6635 { 6636 return &tg->cfs_bandwidth; 6637 } 6638 6639 /* returns 0 on failure to allocate runtime */ 6640 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b, 6641 struct cfs_rq *cfs_rq, u64 target_runtime) 6642 { 6643 u64 min_amount, amount = 0; 6644 6645 lockdep_assert_held(&cfs_b->lock); 6646 6647 /* note: this is a positive sum as runtime_remaining <= 0 */ 6648 min_amount = target_runtime - cfs_rq->runtime_remaining; 6649 6650 if (cfs_b->quota == RUNTIME_INF) 6651 amount = min_amount; 6652 else { 6653 start_cfs_bandwidth(cfs_b); 6654 6655 if (cfs_b->runtime > 0) { 6656 amount = min(cfs_b->runtime, min_amount); 6657 cfs_b->runtime -= amount; 6658 cfs_b->idle = 0; 6659 } 6660 } 6661 6662 cfs_rq->runtime_remaining += amount; 6663 6664 return cfs_rq->runtime_remaining > 0; 6665 } 6666 6667 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq); 6668 6669 static bool __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) 6670 { 6671 /* dock delta_exec before expiring quota (as it could span periods) */ 6672 cfs_rq->runtime_remaining -= delta_exec; 6673 6674 if (likely(cfs_rq->runtime_remaining > 0)) 6675 return false; 6676 6677 if (cfs_rq->throttled) 6678 return true; 6679 /* 6680 * throttle_cfs_rq() will try to extend the runtime first 6681 * before throttling the hierarchy. 6682 */ 6683 return throttle_cfs_rq(cfs_rq); 6684 } 6685 6686 static __always_inline 6687 bool account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) 6688 { 6689 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled) 6690 return false; 6691 6692 return __account_cfs_rq_runtime(cfs_rq, delta_exec); 6693 } 6694 6695 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq) 6696 { 6697 return cfs_bandwidth_used() && cfs_rq->throttled; 6698 } 6699 6700 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq) 6701 { 6702 return cfs_bandwidth_used() && cfs_rq->pelt_clock_throttled; 6703 } 6704 6705 /* check whether cfs_rq, or any parent, is throttled */ 6706 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq) 6707 { 6708 return cfs_bandwidth_used() && cfs_rq->throttle_count; 6709 } 6710 6711 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu) 6712 { 6713 return throttled_hierarchy(tg_cfs_rq(task_group(p), dst_cpu)); 6714 } 6715 6716 static inline bool task_is_throttled(struct task_struct *p) 6717 { 6718 return cfs_bandwidth_used() && p->throttled; 6719 } 6720 6721 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags); 6722 static void throttle_cfs_rq_work(struct callback_head *work) 6723 { 6724 struct task_struct *p = container_of(work, struct task_struct, sched_throttle_work); 6725 struct sched_entity *se; 6726 struct cfs_rq *cfs_rq; 6727 struct rq *rq; 6728 6729 WARN_ON_ONCE(p != current); 6730 p->sched_throttle_work.next = &p->sched_throttle_work; 6731 6732 /* 6733 * If task is exiting, then there won't be a return to userspace, so we 6734 * don't have to bother with any of this. 6735 */ 6736 if ((p->flags & PF_EXITING)) 6737 return; 6738 6739 scoped_guard(task_rq_lock, p) { 6740 se = &p->se; 6741 cfs_rq = cfs_rq_of(se); 6742 6743 /* Raced, forget */ 6744 if (p->sched_class != &fair_sched_class) 6745 return; 6746 6747 /* 6748 * If not in limbo, then either replenish has happened or this 6749 * task got migrated out of the throttled cfs_rq, move along. 6750 */ 6751 if (!cfs_rq->throttle_count) 6752 return; 6753 rq = scope.rq; 6754 update_rq_clock(rq); 6755 WARN_ON_ONCE(p->throttled || !list_empty(&p->throttle_node)); 6756 dequeue_task_fair(rq, p, DEQUEUE_SLEEP | DEQUEUE_THROTTLE); 6757 list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list); 6758 /* 6759 * Must not set throttled before dequeue or dequeue will 6760 * mistakenly regard this task as an already throttled one. 6761 */ 6762 p->throttled = true; 6763 resched_curr(rq); 6764 } 6765 } 6766 6767 void init_cfs_throttle_work(struct task_struct *p) 6768 { 6769 init_task_work(&p->sched_throttle_work, throttle_cfs_rq_work); 6770 /* Protect against double add, see throttle_cfs_rq() and throttle_cfs_rq_work() */ 6771 p->sched_throttle_work.next = &p->sched_throttle_work; 6772 INIT_LIST_HEAD(&p->throttle_node); 6773 } 6774 6775 /* 6776 * Task is throttled and someone wants to dequeue it again: 6777 * it could be sched/core when core needs to do things like 6778 * task affinity change, task group change, task sched class 6779 * change etc. and in these cases, DEQUEUE_SLEEP is not set; 6780 * or the task is blocked after throttled due to freezer etc. 6781 * and in these cases, DEQUEUE_SLEEP is set. 6782 */ 6783 static void detach_task_cfs_rq(struct task_struct *p); 6784 static void dequeue_throttled_task(struct task_struct *p, int flags) 6785 { 6786 WARN_ON_ONCE(p->se.on_rq); 6787 list_del_init(&p->throttle_node); 6788 6789 /* task blocked after throttled */ 6790 if (flags & DEQUEUE_SLEEP) { 6791 p->throttled = false; 6792 return; 6793 } 6794 6795 /* 6796 * task is migrating off its old cfs_rq, detach 6797 * the task's load from its old cfs_rq. 6798 */ 6799 if (task_on_rq_migrating(p)) 6800 detach_task_cfs_rq(p); 6801 } 6802 6803 static bool enqueue_throttled_task(struct task_struct *p) 6804 { 6805 struct cfs_rq *cfs_rq = cfs_rq_of(&p->se); 6806 6807 /* @p should have gone through dequeue_throttled_task() first */ 6808 WARN_ON_ONCE(!list_empty(&p->throttle_node)); 6809 6810 /* 6811 * If the throttled task @p is enqueued to a throttled cfs_rq, 6812 * take the fast path by directly putting the task on the 6813 * target cfs_rq's limbo list. 6814 * 6815 * Do not do that when @p is current because the following race can 6816 * cause @p's group_node to be incorectly re-insterted in its rq's 6817 * cfs_tasks list, despite being throttled: 6818 * 6819 * cpuX cpuY 6820 * p ret2user 6821 * throttle_cfs_rq_work() sched_move_task(p) 6822 * LOCK task_rq_lock 6823 * dequeue_task_fair(p) 6824 * UNLOCK task_rq_lock 6825 * LOCK task_rq_lock 6826 * task_current_donor(p) == true 6827 * task_on_rq_queued(p) == true 6828 * dequeue_task(p) 6829 * put_prev_task(p) 6830 * sched_change_group() 6831 * enqueue_task(p) -> p's new cfs_rq 6832 * is throttled, go 6833 * fast path and skip 6834 * actual enqueue 6835 * set_next_task(p) 6836 * list_move(&se->group_node, &rq->cfs_tasks); // bug 6837 * schedule() 6838 * 6839 * In the above race case, @p current cfs_rq is in the same rq as 6840 * its previous cfs_rq because sched_move_task() only moves a task 6841 * to a different group from the same rq, so we can use its current 6842 * cfs_rq to derive rq and test if the task is current. 6843 */ 6844 if (throttled_hierarchy(cfs_rq) && 6845 !task_current_donor(rq_of(cfs_rq), p)) { 6846 list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list); 6847 return true; 6848 } 6849 6850 /* we can't take the fast path, do an actual enqueue*/ 6851 p->throttled = false; 6852 return false; 6853 } 6854 6855 static void enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags); 6856 static int tg_unthrottle_up(struct task_group *tg, void *data) 6857 { 6858 struct rq *rq = data; 6859 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq)); 6860 struct task_struct *p, *tmp; 6861 LIST_HEAD(throttled_tasks); 6862 6863 /* 6864 * If cfs_rq->curr is set, the cfs_rq might not have caught up 6865 * since the last clock update. Do it now before we begin 6866 * queueing task onto it to save the need for unnecessarily 6867 * unthrottle the hierarchy for this cfs_rq to be throttled 6868 * right back again. 6869 */ 6870 update_curr(cfs_rq); 6871 6872 if (--cfs_rq->throttle_count) 6873 return 0; 6874 6875 if (cfs_rq->pelt_clock_throttled) { 6876 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) - 6877 cfs_rq->throttled_clock_pelt; 6878 cfs_rq->pelt_clock_throttled = 0; 6879 } 6880 6881 if (cfs_rq->throttled_clock_self) { 6882 u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self; 6883 6884 cfs_rq->throttled_clock_self = 0; 6885 6886 if (WARN_ON_ONCE((s64)delta < 0)) 6887 delta = 0; 6888 6889 cfs_rq->throttled_clock_self_time += delta; 6890 } 6891 6892 /* 6893 * Move the tasks to a local list since an update_curr() during 6894 * enqueue_task_fair() can throttle a higher cfs_rq, and it can 6895 * see the "throttled_limbo_list" being non-empty in 6896 * tg_throttle_down() if throttle_count turned 0 above. 6897 */ 6898 list_splice_init(&cfs_rq->throttled_limbo_list, &throttled_tasks); 6899 6900 /* Re-enqueue the tasks that have been throttled at this level. */ 6901 list_for_each_entry_safe(p, tmp, &throttled_tasks, throttle_node) { 6902 /* 6903 * Back to being throttled! Break out and put the remaining 6904 * tasks back onto the limbo_list to prevent running them 6905 * unnecessarily. 6906 */ 6907 if (cfs_rq->throttle_count) 6908 break; 6909 6910 list_del_init(&p->throttle_node); 6911 p->throttled = false; 6912 enqueue_task_fair(rq, p, ENQUEUE_WAKEUP); 6913 } 6914 6915 list_splice(&throttled_tasks, &cfs_rq->throttled_limbo_list); 6916 6917 /* Add cfs_rq with load or one or more already running entities to the list */ 6918 if (!cfs_rq_is_decayed(cfs_rq)) 6919 list_add_leaf_cfs_rq(cfs_rq); 6920 6921 return 0; 6922 } 6923 6924 static inline bool task_has_throttle_work(struct task_struct *p) 6925 { 6926 return p->sched_throttle_work.next != &p->sched_throttle_work; 6927 } 6928 6929 static inline void task_throttle_setup_work(struct task_struct *p) 6930 { 6931 if (task_has_throttle_work(p)) 6932 return; 6933 6934 /* 6935 * Kthreads and exiting tasks don't return to userspace, so adding the 6936 * work is pointless 6937 */ 6938 if ((p->flags & (PF_EXITING | PF_KTHREAD))) 6939 return; 6940 6941 task_work_add(p, &p->sched_throttle_work, TWA_RESUME); 6942 } 6943 6944 static void record_throttle_clock(struct cfs_rq *cfs_rq) 6945 { 6946 struct rq *rq = rq_of(cfs_rq); 6947 6948 if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock) 6949 cfs_rq->throttled_clock = rq_clock(rq); 6950 6951 if (!cfs_rq->throttled_clock_self) 6952 cfs_rq->throttled_clock_self = rq_clock(rq); 6953 } 6954 6955 static int tg_throttle_down(struct task_group *tg, void *data) 6956 { 6957 struct rq *rq = data; 6958 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq)); 6959 6960 if (cfs_rq->throttle_count++) 6961 return 0; 6962 6963 /* 6964 * For cfs_rqs that still have entities enqueued, PELT clock 6965 * stop happens at dequeue time when all entities are dequeued. 6966 */ 6967 if (!cfs_rq->nr_queued) { 6968 list_del_leaf_cfs_rq(cfs_rq); 6969 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq); 6970 cfs_rq->pelt_clock_throttled = 1; 6971 } 6972 6973 WARN_ON_ONCE(cfs_rq->throttled_clock_self); 6974 WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_limbo_list)); 6975 return 0; 6976 } 6977 6978 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq) 6979 { 6980 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 6981 struct sched_entity *curr = cfs_rq->curr; 6982 struct rq *rq = rq_of(cfs_rq); 6983 6984 scoped_guard(raw_spinlock, &cfs_b->lock) { 6985 u64 target_runtime = 1; 6986 6987 /* 6988 * If cfs_rq->curr is still runnable, we are here from an 6989 * update_curr(). Request sysctl_sched_cfs_bandwidth_slice 6990 * worth of bandwidth to continue running. 6991 * 6992 * If the curr is not runnable, just request enough bandwidth 6993 * to be runnable next time the pick selects this cfs_rq. 6994 */ 6995 if (curr && curr->on_rq) 6996 target_runtime = sched_cfs_bandwidth_slice(); 6997 6998 /* 6999 * Check if We have raced with bandwidth becoming available. If 7000 * we actually throttled the timer might not unthrottle us for 7001 * an entire period. We additionally needed to make sure that 7002 * any subsequent check_cfs_rq_runtime calls agree not to 7003 * throttle us, as we may commit to do cfs put_prev+pick_next, 7004 * so we ask for 1ns of runtime rather than just check cfs_b. 7005 * 7006 * This will start the period timer if necessary. 7007 */ 7008 if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, target_runtime)) 7009 return false; 7010 7011 /* 7012 * No bandwidth available; Add ourselves on the list to be 7013 * unthrottled later. 7014 */ 7015 list_add_tail_rcu(&cfs_rq->throttled_list, 7016 &cfs_b->throttled_cfs_rq); 7017 } 7018 7019 /* freeze hierarchy runnable averages while throttled */ 7020 scoped_guard(rcu) 7021 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq); 7022 7023 /* 7024 * Note: distribution will already see us throttled via the 7025 * throttled-list. rq->lock protects completion. 7026 */ 7027 cfs_rq->throttled = 1; 7028 WARN_ON_ONCE(cfs_rq->throttled_clock); 7029 7030 /* 7031 * If current hierarchy was throttled, add throttle work to the 7032 * current donor. In case of proxy-execution, the execution 7033 * context cannot exit to the userspace while holding a mutex 7034 * and the rule of throttle deferral to only throttle the 7035 * throttled context at exit to userspace is still preserved. 7036 */ 7037 if (curr && curr->on_rq) 7038 task_throttle_setup_work(rq->donor); 7039 7040 return true; 7041 } 7042 7043 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq) 7044 { 7045 struct rq *rq = rq_of(cfs_rq); 7046 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 7047 struct sched_entity *se = cfs_rq_se(cfs_rq); 7048 7049 /* 7050 * It's possible we are called with runtime_remaining < 0 due to things 7051 * like async unthrottled us with a positive runtime_remaining but other 7052 * still running entities consumed those runtime before we reached here. 7053 * 7054 * We can't unthrottle this cfs_rq without any runtime remaining because 7055 * any enqueue in tg_unthrottle_up() will immediately trigger a throttle, 7056 * which is not supposed to happen on unthrottle path. 7057 * 7058 * Catch up on the remaining runtime since last clock update before 7059 * checking runtime remaining. 7060 */ 7061 update_curr(cfs_rq); 7062 if (cfs_rq->runtime_enabled && cfs_rq->runtime_remaining <= 0) 7063 return; 7064 7065 cfs_rq->throttled = 0; 7066 7067 scoped_guard(raw_spinlock, &cfs_b->lock) { 7068 list_del_rcu(&cfs_rq->throttled_list); 7069 7070 if (!cfs_rq->throttled_clock) 7071 break; 7072 7073 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock; 7074 cfs_rq->throttled_clock = 0; 7075 } 7076 7077 /* update hierarchical throttle state */ 7078 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq); 7079 7080 if (!cfs_rq->load.weight) { 7081 if (!cfs_rq->on_list) 7082 return; 7083 /* 7084 * Nothing to run but something to decay (on_list)? 7085 * Complete the branch. 7086 */ 7087 for_each_sched_entity(se) { 7088 if (list_add_leaf_cfs_rq(cfs_rq_of(se))) 7089 break; 7090 } 7091 } 7092 7093 assert_list_leaf_cfs_rq(rq); 7094 7095 /* Determine whether we need to wake up potentially idle CPU: */ 7096 if (rq->curr == rq->idle && rq->cfs.h_nr_queued) 7097 resched_curr(rq); 7098 } 7099 7100 static void __cfsb_csd_unthrottle(void *arg) 7101 { 7102 struct cfs_rq *cursor, *tmp; 7103 struct rq *rq = arg; 7104 7105 guard(rq_lock)(rq); 7106 7107 /* 7108 * Iterating over the list can trigger several call to 7109 * update_rq_clock() in unthrottle_cfs_rq(). 7110 * Do it once and skip the potential next ones. 7111 */ 7112 update_rq_clock(rq); 7113 rq_clock_start_loop_update(rq); 7114 7115 /* 7116 * Since we hold rq lock we're safe from concurrent manipulation of 7117 * the CSD list. However, this RCU critical section annotates the 7118 * fact that we pair with sched_free_group_rcu(), so that we cannot 7119 * race with group being freed in the window between removing it 7120 * from the list and advancing to the next entry in the list. 7121 */ 7122 guard(rcu)(); 7123 7124 list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list, 7125 throttled_csd_list) { 7126 list_del_init(&cursor->throttled_csd_list); 7127 7128 if (cfs_rq_throttled(cursor)) 7129 unthrottle_cfs_rq(cursor); 7130 } 7131 7132 rq_clock_stop_loop_update(rq); 7133 } 7134 7135 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq) 7136 { 7137 struct rq *rq = rq_of(cfs_rq); 7138 bool first; 7139 7140 if (rq == this_rq()) { 7141 update_rq_clock(rq); 7142 unthrottle_cfs_rq(cfs_rq); 7143 return; 7144 } 7145 7146 /* Already enqueued */ 7147 if (WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_csd_list))) 7148 return; 7149 7150 first = list_empty(&rq->cfsb_csd_list); 7151 list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list); 7152 if (first) 7153 smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd); 7154 } 7155 7156 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq) 7157 { 7158 lockdep_assert_rq_held(rq_of(cfs_rq)); 7159 7160 if (WARN_ON_ONCE(!cfs_rq_throttled(cfs_rq) || 7161 cfs_rq->runtime_remaining <= 0)) 7162 return; 7163 7164 __unthrottle_cfs_rq_async(cfs_rq); 7165 } 7166 7167 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b) 7168 { 7169 bool throttled = false, unthrottle_local = false; 7170 int this_cpu = smp_processor_id(); 7171 u64 runtime, remaining = 1; 7172 struct cfs_rq *cfs_rq; 7173 struct rq *rq; 7174 7175 guard(rcu)(); 7176 7177 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq, 7178 throttled_list) { 7179 rq = rq_of(cfs_rq); 7180 7181 if (!remaining) { 7182 throttled = true; 7183 break; 7184 } 7185 7186 guard(rq_lock_irqsave)(rq); 7187 7188 if (!cfs_rq_throttled(cfs_rq)) 7189 continue; 7190 7191 /* Already queued for async unthrottle */ 7192 if (!list_empty(&cfs_rq->throttled_csd_list)) 7193 continue; 7194 7195 if (cfs_rq->curr) { 7196 update_rq_clock(rq); 7197 update_curr(cfs_rq); 7198 } 7199 7200 /* By the above checks, this should never be true */ 7201 WARN_ON_ONCE(cfs_rq->runtime_remaining > 0); 7202 7203 scoped_guard(raw_spinlock, &cfs_b->lock) { 7204 runtime = -cfs_rq->runtime_remaining + 1; 7205 if (runtime > cfs_b->runtime) 7206 runtime = cfs_b->runtime; 7207 cfs_b->runtime -= runtime; 7208 remaining = cfs_b->runtime; 7209 } 7210 7211 cfs_rq->runtime_remaining += runtime; 7212 7213 /* 7214 * Ran out of bandwidth during distribution! 7215 * Indicate throttled entities and break early. 7216 */ 7217 if (cfs_rq->runtime_remaining <= 0) { 7218 throttled = true; 7219 break; 7220 } 7221 7222 /* we check whether we're throttled above */ 7223 if (cpu_of(rq) != this_cpu) { 7224 unthrottle_cfs_rq_async(cfs_rq); 7225 continue; 7226 } 7227 7228 /* 7229 * Allow a parallel async unthrottle to unthrottle 7230 * this cfs_rq too via __cfsb_csd_unthrottle(). 7231 * If we are first, do it ourselves at the end and 7232 * save on an IPI from remote CPUs. 7233 */ 7234 unthrottle_local = list_empty(&rq->cfsb_csd_list); 7235 list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list); 7236 } 7237 7238 if (unthrottle_local) { 7239 /* 7240 * Protect against an IPI that is also trying to flush 7241 * the unthrottled cfs_rq(s) from this CPU's csd_list. 7242 */ 7243 scoped_guard(irqsave) 7244 __cfsb_csd_unthrottle(cpu_rq(this_cpu)); 7245 } 7246 7247 return throttled; 7248 } 7249 7250 /* 7251 * Responsible for refilling a task_group's bandwidth and unthrottling its 7252 * cfs_rqs as appropriate. If there has been no activity within the last 7253 * period the timer is deactivated until scheduling resumes; cfs_b->idle is 7254 * used to track this state. 7255 */ 7256 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun) 7257 __must_hold(&cfs_b->lock) 7258 { 7259 int throttled; 7260 7261 /* no need to continue the timer with no bandwidth constraint */ 7262 if (cfs_b->quota == RUNTIME_INF) 7263 goto out_deactivate; 7264 7265 throttled = !list_empty(&cfs_b->throttled_cfs_rq); 7266 cfs_b->nr_periods += overrun; 7267 7268 /* Refill extra burst quota even if cfs_b->idle */ 7269 __refill_cfs_bandwidth_runtime(cfs_b); 7270 7271 /* 7272 * idle depends on !throttled (for the case of a large deficit), and if 7273 * we're going inactive then everything else can be deferred 7274 */ 7275 if (cfs_b->idle && !throttled) 7276 goto out_deactivate; 7277 7278 if (!throttled) { 7279 /* mark as potentially idle for the upcoming period */ 7280 cfs_b->idle = 1; 7281 return 0; 7282 } 7283 7284 /* account preceding periods in which throttling occurred */ 7285 cfs_b->nr_throttled += overrun; 7286 7287 /* 7288 * This check is repeated as we release cfs_b->lock while we unthrottle. 7289 */ 7290 while (throttled && cfs_b->runtime > 0) { 7291 raw_spin_unlock_irq_enable(&cfs_b->lock); 7292 /* we can't nest cfs_b->lock while distributing bandwidth */ 7293 throttled = distribute_cfs_runtime(cfs_b); 7294 raw_spin_lock_irq_disable(&cfs_b->lock); 7295 } 7296 7297 /* 7298 * While we are ensured activity in the period following an 7299 * unthrottle, this also covers the case in which the new bandwidth is 7300 * insufficient to cover the existing bandwidth deficit. (Forcing the 7301 * timer to remain active while there are any throttled entities.) 7302 */ 7303 cfs_b->idle = 0; 7304 7305 return 0; 7306 7307 out_deactivate: 7308 return 1; 7309 } 7310 7311 /* a cfs_rq won't donate quota below this amount */ 7312 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC; 7313 /* minimum remaining period time to redistribute slack quota */ 7314 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC; 7315 /* how long we wait to gather additional slack before distributing */ 7316 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC; 7317 7318 /* 7319 * Are we near the end of the current quota period? 7320 * 7321 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the 7322 * hrtimer base being cleared by hrtimer_start. In the case of 7323 * migrate_hrtimers, base is never cleared, so we are fine. 7324 */ 7325 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire) 7326 { 7327 struct hrtimer *refresh_timer = &cfs_b->period_timer; 7328 s64 remaining; 7329 7330 /* if the call-back is running a quota refresh is already occurring */ 7331 if (hrtimer_callback_running(refresh_timer)) 7332 return 1; 7333 7334 /* is a quota refresh about to occur? */ 7335 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer)); 7336 if (remaining < (s64)min_expire) 7337 return 1; 7338 7339 return 0; 7340 } 7341 7342 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b) 7343 { 7344 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration; 7345 7346 /* if there's a quota refresh soon don't bother with slack */ 7347 if (runtime_refresh_within(cfs_b, min_left)) 7348 return; 7349 7350 /* don't push forwards an existing deferred unthrottle */ 7351 if (cfs_b->slack_started) 7352 return; 7353 cfs_b->slack_started = true; 7354 7355 hrtimer_start(&cfs_b->slack_timer, 7356 ns_to_ktime(cfs_bandwidth_slack_period), 7357 HRTIMER_MODE_REL); 7358 } 7359 7360 /* we know any runtime found here is valid as update_curr() precedes return */ 7361 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq) 7362 { 7363 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 7364 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime; 7365 7366 if (slack_runtime <= 0) 7367 return; 7368 7369 guard(raw_spinlock)(&cfs_b->lock); 7370 7371 if (cfs_b->quota != RUNTIME_INF) { 7372 cfs_b->runtime += slack_runtime; 7373 7374 /* we are under rq->lock, defer unthrottling using a timer */ 7375 if (cfs_b->runtime > sched_cfs_bandwidth_slice() && 7376 !list_empty(&cfs_b->throttled_cfs_rq)) 7377 start_cfs_slack_bandwidth(cfs_b); 7378 } 7379 7380 /* even if it's not valid for return we don't want to try again */ 7381 cfs_rq->runtime_remaining -= slack_runtime; 7382 } 7383 7384 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) 7385 { 7386 if (!cfs_bandwidth_used()) 7387 return; 7388 7389 if (!cfs_rq->runtime_enabled || cfs_rq->nr_queued) 7390 return; 7391 7392 __return_cfs_rq_runtime(cfs_rq); 7393 } 7394 7395 /* 7396 * This is done with a timer (instead of inline with bandwidth return) since 7397 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs. 7398 */ 7399 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b) 7400 { 7401 /* confirm we're still not at a refresh boundary */ 7402 scoped_guard(raw_spinlock_irq, &cfs_b->lock) { 7403 u64 runtime = 0, slice = sched_cfs_bandwidth_slice(); 7404 7405 cfs_b->slack_started = false; 7406 7407 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) 7408 return; 7409 7410 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice) 7411 runtime = cfs_b->runtime; 7412 7413 if (!runtime) 7414 return; 7415 } 7416 7417 distribute_cfs_runtime(cfs_b); 7418 } 7419 7420 /* 7421 * When a group wakes up we want to make sure that its quota is not already 7422 * expired/exceeded, otherwise it may be allowed to steal additional ticks of 7423 * runtime as update_curr() throttling can not trigger until it's on-rq. 7424 */ 7425 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) 7426 { 7427 if (!cfs_bandwidth_used()) 7428 return; 7429 7430 /* an active group must be handled by the update_curr() path */ 7431 if (!cfs_rq->runtime_enabled || cfs_rq->h_curr) 7432 return; 7433 7434 /* ensure the group is not already throttled */ 7435 if (cfs_rq_throttled(cfs_rq)) 7436 return; 7437 7438 /* update runtime allocation */ 7439 account_cfs_rq_runtime(cfs_rq, 0); 7440 } 7441 7442 static void sync_throttle(struct task_group *tg, int cpu) 7443 { 7444 struct cfs_rq *pcfs_rq, *cfs_rq; 7445 7446 if (!cfs_bandwidth_used()) 7447 return; 7448 7449 if (!tg->parent) 7450 return; 7451 7452 cfs_rq = tg_cfs_rq(tg, cpu); 7453 pcfs_rq = tg_cfs_rq(tg->parent, cpu); 7454 7455 cfs_rq->throttle_count = pcfs_rq->throttle_count; 7456 cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu)); 7457 7458 /* 7459 * It is not enough to sync the "pelt_clock_throttled" indicator 7460 * with the parent cfs_rq when the hierarchy is not queued. 7461 * Always join a throttled hierarchy with PELT clock throttled 7462 * and leaf it to the first enqueue, or distribution to 7463 * unthrottle the PELT clock. 7464 */ 7465 if (cfs_rq->throttle_count) 7466 cfs_rq->pelt_clock_throttled = 1; 7467 } 7468 7469 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer) 7470 { 7471 struct cfs_bandwidth *cfs_b = 7472 container_of(timer, struct cfs_bandwidth, slack_timer); 7473 7474 do_sched_cfs_slack_timer(cfs_b); 7475 7476 return HRTIMER_NORESTART; 7477 } 7478 7479 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer) 7480 { 7481 struct cfs_bandwidth *cfs_b = 7482 container_of(timer, struct cfs_bandwidth, period_timer); 7483 int overrun; 7484 int idle = 0; 7485 int count = 0; 7486 7487 guard(raw_spinlock_irq)(&cfs_b->lock); 7488 7489 for (;;) { 7490 overrun = hrtimer_forward_now(timer, cfs_b->period); 7491 if (!overrun) 7492 break; 7493 7494 idle = do_sched_cfs_period_timer(cfs_b, overrun); 7495 7496 if (++count > 3) { 7497 u64 new, old = ktime_to_ns(cfs_b->period); 7498 7499 /* 7500 * Grow period by a factor of 2 to avoid losing precision. 7501 * Precision loss in the quota/period ratio can cause __cfs_schedulable 7502 * to fail. 7503 */ 7504 new = old * 2; 7505 if (new < max_bw_quota_period_us * NSEC_PER_USEC) { 7506 cfs_b->period = ns_to_ktime(new); 7507 cfs_b->quota *= 2; 7508 cfs_b->burst *= 2; 7509 7510 pr_warn_ratelimited( 7511 "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n", 7512 smp_processor_id(), 7513 div_u64(new, NSEC_PER_USEC), 7514 div_u64(cfs_b->quota, NSEC_PER_USEC)); 7515 } else { 7516 pr_warn_ratelimited( 7517 "cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n", 7518 smp_processor_id(), 7519 div_u64(old, NSEC_PER_USEC), 7520 div_u64(cfs_b->quota, NSEC_PER_USEC)); 7521 } 7522 7523 /* reset count so we don't come right back in here */ 7524 count = 0; 7525 } 7526 } 7527 7528 if (idle) { 7529 cfs_b->period_active = 0; 7530 return HRTIMER_NORESTART; 7531 } 7532 7533 return HRTIMER_RESTART; 7534 } 7535 7536 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) 7537 { 7538 raw_spin_lock_init(&cfs_b->lock); 7539 cfs_b->runtime = 0; 7540 cfs_b->quota = RUNTIME_INF; 7541 cfs_b->period = us_to_ktime(default_bw_period_us()); 7542 cfs_b->burst = 0; 7543 cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF; 7544 7545 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq); 7546 hrtimer_setup(&cfs_b->period_timer, sched_cfs_period_timer, CLOCK_MONOTONIC, 7547 HRTIMER_MODE_ABS_PINNED); 7548 7549 /* Add a random offset so that timers interleave */ 7550 hrtimer_set_expires(&cfs_b->period_timer, 7551 get_random_u32_below(cfs_b->period)); 7552 hrtimer_setup(&cfs_b->slack_timer, sched_cfs_slack_timer, CLOCK_MONOTONIC, 7553 HRTIMER_MODE_REL); 7554 cfs_b->slack_started = false; 7555 } 7556 7557 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) 7558 { 7559 cfs_rq->runtime_enabled = 0; 7560 INIT_LIST_HEAD(&cfs_rq->throttled_list); 7561 INIT_LIST_HEAD(&cfs_rq->throttled_csd_list); 7562 INIT_LIST_HEAD(&cfs_rq->throttled_limbo_list); 7563 } 7564 7565 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b) 7566 { 7567 lockdep_assert_held(&cfs_b->lock); 7568 7569 if (cfs_b->period_active) 7570 return; 7571 7572 cfs_b->period_active = 1; 7573 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period); 7574 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED); 7575 } 7576 7577 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) 7578 { 7579 int __maybe_unused i; 7580 7581 /* init_cfs_bandwidth() was not called */ 7582 if (!cfs_b->throttled_cfs_rq.next) 7583 return; 7584 7585 hrtimer_cancel(&cfs_b->period_timer); 7586 hrtimer_cancel(&cfs_b->slack_timer); 7587 7588 /* 7589 * It is possible that we still have some cfs_rq's pending on a CSD 7590 * list, though this race is very rare. In order for this to occur, we 7591 * must have raced with the last task leaving the group while there 7592 * exist throttled cfs_rq(s), and the period_timer must have queued the 7593 * CSD item but the remote cpu has not yet processed it. To handle this, 7594 * we can simply flush all pending CSD work inline here. We're 7595 * guaranteed at this point that no additional cfs_rq of this group can 7596 * join a CSD list. 7597 */ 7598 for_each_possible_cpu(i) { 7599 struct rq *rq = cpu_rq(i); 7600 7601 if (list_empty(&rq->cfsb_csd_list)) 7602 continue; 7603 7604 scoped_guard(irqsave) 7605 __cfsb_csd_unthrottle(rq); 7606 } 7607 } 7608 7609 /* 7610 * Both these CPU hotplug callbacks race against unregister_fair_sched_group() 7611 * 7612 * The race is harmless, since modifying bandwidth settings of unhooked group 7613 * bits doesn't do much. 7614 */ 7615 7616 /* cpu online callback */ 7617 static void __maybe_unused update_runtime_enabled(struct rq *rq) 7618 { 7619 struct task_group *tg; 7620 7621 lockdep_assert_rq_held(rq); 7622 7623 guard(rcu)(); 7624 7625 list_for_each_entry_rcu(tg, &task_groups, list) { 7626 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; 7627 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq)); 7628 7629 scoped_guard(raw_spinlock, &cfs_b->lock) 7630 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF; 7631 } 7632 } 7633 7634 /* cpu offline callback */ 7635 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq) 7636 { 7637 struct task_group *tg; 7638 7639 lockdep_assert_rq_held(rq); 7640 7641 // Do not unthrottle for an active CPU 7642 if (cpumask_test_cpu(cpu_of(rq), cpu_active_mask)) 7643 return; 7644 7645 /* 7646 * The rq clock has already been updated in the 7647 * set_rq_offline(), so we should skip updating 7648 * the rq clock again in unthrottle_cfs_rq(). 7649 */ 7650 rq_clock_start_loop_update(rq); 7651 7652 guard(rcu)(); 7653 7654 list_for_each_entry_rcu(tg, &task_groups, list) { 7655 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq)); 7656 7657 if (!cfs_rq->runtime_enabled) 7658 continue; 7659 7660 /* 7661 * Offline rq is schedulable till CPU is completely disabled 7662 * in take_cpu_down(), so we prevent new cfs throttling here. 7663 */ 7664 cfs_rq->runtime_enabled = 0; 7665 7666 if (!cfs_rq_throttled(cfs_rq)) 7667 continue; 7668 7669 /* 7670 * clock_task is not advancing so we just need to make sure 7671 * there's some valid quota amount 7672 */ 7673 cfs_rq->runtime_remaining = 1; 7674 unthrottle_cfs_rq(cfs_rq); 7675 } 7676 7677 rq_clock_stop_loop_update(rq); 7678 } 7679 7680 bool cfs_task_bw_constrained(struct task_struct *p) 7681 { 7682 struct cfs_rq *cfs_rq = task_cfs_rq(p); 7683 7684 if (!cfs_bandwidth_used()) 7685 return false; 7686 7687 if (cfs_rq->runtime_enabled || 7688 tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF) 7689 return true; 7690 7691 return false; 7692 } 7693 7694 #ifdef CONFIG_NO_HZ_FULL 7695 /* called from pick_next_task_fair() */ 7696 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) 7697 { 7698 int cpu = cpu_of(rq); 7699 7700 if (!cfs_bandwidth_used()) 7701 return; 7702 7703 if (!tick_nohz_full_cpu(cpu)) 7704 return; 7705 7706 if (rq->nr_running != 1) 7707 return; 7708 7709 /* 7710 * We know there is only one task runnable and we've just picked it. The 7711 * normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will 7712 * be otherwise able to stop the tick. Just need to check if we are using 7713 * bandwidth control. 7714 */ 7715 if (cfs_task_bw_constrained(p)) 7716 tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED); 7717 } 7718 #endif /* CONFIG_NO_HZ_FULL */ 7719 7720 #else /* !CONFIG_CFS_BANDWIDTH: */ 7721 7722 static bool account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) { return false; } 7723 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {} 7724 static inline void sync_throttle(struct task_group *tg, int cpu) {} 7725 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {} 7726 static void task_throttle_setup_work(struct task_struct *p) {} 7727 static bool task_is_throttled(struct task_struct *p) { return false; } 7728 static void dequeue_throttled_task(struct task_struct *p, int flags) {} 7729 static bool enqueue_throttled_task(struct task_struct *p) { return false; } 7730 static void record_throttle_clock(struct cfs_rq *cfs_rq) {} 7731 7732 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq) 7733 { 7734 return 0; 7735 } 7736 7737 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq) 7738 { 7739 return false; 7740 } 7741 7742 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq) 7743 { 7744 return 0; 7745 } 7746 7747 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu) 7748 { 7749 return 0; 7750 } 7751 7752 #ifdef CONFIG_FAIR_GROUP_SCHED 7753 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {} 7754 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {} 7755 #endif 7756 7757 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg) 7758 { 7759 return NULL; 7760 } 7761 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {} 7762 static inline void update_runtime_enabled(struct rq *rq) {} 7763 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {} 7764 #ifdef CONFIG_CGROUP_SCHED 7765 bool cfs_task_bw_constrained(struct task_struct *p) 7766 { 7767 return false; 7768 } 7769 #endif 7770 #endif /* !CONFIG_CFS_BANDWIDTH */ 7771 7772 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL) 7773 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {} 7774 #endif 7775 7776 /************************************************** 7777 * CFS operations on tasks: 7778 */ 7779 7780 #ifdef CONFIG_SCHED_HRTICK 7781 static void hrtick_start_fair(struct rq *rq, struct task_struct *p) 7782 { 7783 struct sched_entity *se = &p->se; 7784 unsigned long scale = 1024; 7785 unsigned long util = 0; 7786 u64 vdelta; 7787 u64 delta; 7788 7789 WARN_ON_ONCE(task_rq(p) != rq); 7790 7791 if (rq->cfs.h_nr_queued <= 1) 7792 return; 7793 7794 /* 7795 * Compute time until virtual deadline 7796 */ 7797 vdelta = se->deadline - se->vruntime; 7798 if ((s64)vdelta < 0) { 7799 if (task_current_donor(rq, p)) 7800 resched_curr(rq); 7801 return; 7802 } 7803 delta = (se->h_load.weight * vdelta) / NICE_0_LOAD; 7804 7805 /* 7806 * Correct for instantaneous load of other classes. 7807 */ 7808 util += cpu_util_irq(rq); 7809 if (util && util < 1024) { 7810 scale *= 1024; 7811 scale /= (1024 - util); 7812 } 7813 7814 hrtick_start(rq, (scale * delta) / 1024); 7815 } 7816 7817 /* 7818 * Called on enqueue to start the hrtick when h_nr_queued becomes more than 1. 7819 */ 7820 static void hrtick_update(struct rq *rq) 7821 { 7822 struct task_struct *donor = rq->donor; 7823 7824 if (!hrtick_enabled_fair(rq) || donor->sched_class != &fair_sched_class) 7825 return; 7826 7827 if (hrtick_active(rq)) 7828 return; 7829 7830 hrtick_start_fair(rq, donor); 7831 } 7832 #else /* !CONFIG_SCHED_HRTICK: */ 7833 static inline void 7834 hrtick_start_fair(struct rq *rq, struct task_struct *p) 7835 { 7836 } 7837 7838 static inline void hrtick_update(struct rq *rq) 7839 { 7840 } 7841 #endif /* !CONFIG_SCHED_HRTICK */ 7842 7843 static inline bool cpu_overutilized(int cpu) 7844 { 7845 unsigned long rq_util_max; 7846 7847 if (!sched_energy_enabled()) 7848 return false; 7849 7850 rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX); 7851 7852 /* Return true only if the utilization doesn't fit CPU's capacity */ 7853 return !util_fits_cpu(cpu_util_cfs(cpu), 0, rq_util_max, cpu); 7854 } 7855 7856 /* 7857 * overutilized value make sense only if EAS is enabled 7858 */ 7859 static inline bool is_rd_overutilized(struct root_domain *rd) 7860 { 7861 return !sched_energy_enabled() || READ_ONCE(rd->overutilized); 7862 } 7863 7864 static inline void set_rd_overutilized(struct root_domain *rd, bool flag) 7865 { 7866 if (!sched_energy_enabled()) 7867 return; 7868 7869 WRITE_ONCE(rd->overutilized, flag); 7870 trace_sched_overutilized_tp(rd, flag); 7871 } 7872 7873 static inline void check_update_overutilized_status(struct rq *rq) 7874 { 7875 /* 7876 * overutilized field is used for load balancing decisions only 7877 * if energy aware scheduler is being used 7878 */ 7879 7880 if (!is_rd_overutilized(rq->rd) && cpu_overutilized(rq->cpu)) 7881 set_rd_overutilized(rq->rd, 1); 7882 } 7883 7884 /* Runqueue only has SCHED_IDLE tasks enqueued */ 7885 static int sched_idle_rq(struct rq *rq) 7886 { 7887 return unlikely(rq->nr_running == rq->cfs.h_nr_idle && 7888 rq->nr_running); 7889 } 7890 7891 static int choose_sched_idle_rq(struct rq *rq, struct task_struct *p) 7892 { 7893 return sched_idle_rq(rq) && !task_has_idle_policy(p); 7894 } 7895 7896 static int choose_idle_cpu(int cpu, struct task_struct *p) 7897 { 7898 return available_idle_cpu(cpu) || 7899 choose_sched_idle_rq(cpu_rq(cpu), p); 7900 } 7901 7902 static void 7903 requeue_delayed_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) 7904 { 7905 /* 7906 * se->sched_delayed should imply: se->on_rq == 1. 7907 * Because a delayed entity is one that is still on 7908 * the runqueue competing until elegibility. 7909 */ 7910 WARN_ON_ONCE(!se->sched_delayed); 7911 WARN_ON_ONCE(!se->on_rq); 7912 7913 if (update_entity_lag(cfs_rq, se)) { 7914 cfs_rq->h_nr_queued--; 7915 if (se != cfs_rq->curr) 7916 __dequeue_entity(cfs_rq, se); 7917 place_entity(cfs_rq, se, 0); 7918 if (se != cfs_rq->curr) 7919 __enqueue_entity(cfs_rq, se); 7920 cfs_rq->h_nr_queued++; 7921 } 7922 7923 update_load_avg(cfs_rq, se, 0); 7924 clear_delayed(se); 7925 } 7926 7927 static unsigned long enqueue_hierarchy(struct task_struct *p, int flags) 7928 { 7929 unsigned long weight = NICE_0_LOAD; 7930 int task_new = !(flags & ENQUEUE_WAKEUP); 7931 struct sched_entity *se = &p->se; 7932 int h_nr_idle = task_has_idle_policy(p); 7933 int h_nr_runnable = 1; 7934 7935 if (task_new && se->sched_delayed) 7936 h_nr_runnable = 0; 7937 7938 for_each_sched_entity(se) { 7939 struct cfs_rq *cfs_rq = cfs_rq_of(se); 7940 7941 update_curr(cfs_rq); 7942 7943 if (!se->on_rq) { 7944 enqueue_entity(cfs_rq, se, flags); 7945 } else { 7946 update_load_avg(cfs_rq, se, UPDATE_TG); 7947 se_update_runnable(se); 7948 update_cfs_group(se); 7949 } 7950 7951 cfs_rq->h_nr_runnable += h_nr_runnable; 7952 cfs_rq->h_nr_queued++; 7953 cfs_rq->h_nr_idle += h_nr_idle; 7954 7955 if (cfs_rq_is_idle(cfs_rq)) 7956 h_nr_idle = 1; 7957 7958 weight = __calc_prop_weight(cfs_rq, se, weight); 7959 7960 flags = ENQUEUE_WAKEUP; 7961 } 7962 7963 return weight; 7964 } 7965 7966 /* Update curr's vruntime before placing entity or updating lag */ 7967 static inline void update_curr_eevdf(struct cfs_rq *cfs_rq) 7968 { 7969 if (!cfs_rq->curr) 7970 return; 7971 7972 update_curr(cfs_rq_of(cfs_rq->curr)); 7973 } 7974 7975 /* 7976 * The enqueue_task method is called before nr_running is 7977 * increased. Here we update the fair scheduling stats and 7978 * then put the task into the rbtree: 7979 */ 7980 static void 7981 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags) 7982 { 7983 int rq_h_nr_queued = rq->cfs.h_nr_queued; 7984 int task_new = !(flags & ENQUEUE_WAKEUP); 7985 struct sched_entity *se = &p->se; 7986 struct cfs_rq *cfs_rq = &rq->cfs; 7987 unsigned long weight; 7988 bool curr; 7989 7990 if (task_is_throttled(p) && enqueue_throttled_task(p)) 7991 return; 7992 7993 /* 7994 * The code below (indirectly) updates schedutil which looks at 7995 * the cfs_rq utilization to select a frequency. 7996 * Let's add the task's estimated utilization to the cfs_rq's 7997 * estimated utilization, before we update schedutil. 7998 */ 7999 if (!p->se.sched_delayed || (flags & ENQUEUE_DELAYED)) 8000 util_est_enqueue(cfs_rq, p); 8001 8002 update_curr_eevdf(cfs_rq); 8003 8004 if (flags & ENQUEUE_DELAYED) { 8005 requeue_delayed_entity(cfs_rq, se); 8006 return; 8007 } 8008 8009 /* 8010 * If in_iowait is set, the code below may not trigger any cpufreq 8011 * utilization updates, so do it here explicitly with the IOWAIT flag 8012 * passed. 8013 */ 8014 if (p->in_iowait) 8015 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT); 8016 8017 /* 8018 * XXX comment on the curr thing 8019 */ 8020 curr = (cfs_rq->curr == se); 8021 if (curr) 8022 place_entity(cfs_rq, se, flags); 8023 8024 if (se->on_rq && se->sched_delayed) 8025 requeue_delayed_entity(cfs_rq, se); 8026 8027 weight = enqueue_hierarchy(p, flags); 8028 8029 if (!curr) { 8030 reweight_eevdf(cfs_rq, se, weight, false); 8031 place_entity(cfs_rq, se, flags | ENQUEUE_QUEUED); 8032 __enqueue_entity(cfs_rq, se); 8033 } 8034 8035 if (!rq_h_nr_queued && rq->cfs.h_nr_queued) 8036 dl_server_start(&rq->fair_server); 8037 8038 /* At this point se is NULL and we are at root level*/ 8039 add_nr_running(rq, 1); 8040 8041 /* 8042 * Since new tasks are assigned an initial util_avg equal to 8043 * half of the spare capacity of their CPU, tiny tasks have the 8044 * ability to cross the overutilized threshold, which will 8045 * result in the load balancer ruining all the task placement 8046 * done by EAS. As a way to mitigate that effect, do not account 8047 * for the first enqueue operation of new tasks during the 8048 * overutilized flag detection. 8049 * 8050 * A better way of solving this problem would be to wait for 8051 * the PELT signals of tasks to converge before taking them 8052 * into account, but that is not straightforward to implement, 8053 * and the following generally works well enough in practice. 8054 */ 8055 if (!task_new) 8056 check_update_overutilized_status(rq); 8057 8058 assert_list_leaf_cfs_rq(rq); 8059 8060 hrtick_update(rq); 8061 } 8062 8063 static void dequeue_hierarchy(struct task_struct *p, int flags) 8064 { 8065 struct sched_entity *se = &p->se; 8066 bool task_sleep = flags & DEQUEUE_SLEEP; 8067 bool task_delayed = flags & DEQUEUE_DELAYED; 8068 bool task_throttled = flags & DEQUEUE_THROTTLE; 8069 int h_nr_runnable = 0; 8070 int h_nr_idle = task_has_idle_policy(p); 8071 bool dequeue = true; 8072 8073 if (task_sleep || task_delayed || !se->sched_delayed) 8074 h_nr_runnable = 1; 8075 8076 for_each_sched_entity(se) { 8077 struct cfs_rq *cfs_rq = cfs_rq_of(se); 8078 8079 update_curr(cfs_rq); 8080 8081 if (dequeue) { 8082 dequeue_entity(cfs_rq, se, flags); 8083 /* Don't dequeue parent if it has other entities besides us */ 8084 if (cfs_rq->load.weight) 8085 dequeue = false; 8086 } else { 8087 update_load_avg(cfs_rq, se, UPDATE_TG); 8088 se_update_runnable(se); 8089 update_cfs_group(se); 8090 } 8091 8092 cfs_rq->h_nr_runnable -= h_nr_runnable; 8093 cfs_rq->h_nr_queued--; 8094 cfs_rq->h_nr_idle -= h_nr_idle; 8095 8096 if (cfs_rq_is_idle(cfs_rq)) 8097 h_nr_idle = 1; 8098 8099 if (throttled_hierarchy(cfs_rq) && task_throttled) 8100 record_throttle_clock(cfs_rq); 8101 8102 flags |= DEQUEUE_SLEEP; 8103 flags &= ~(DEQUEUE_DELAYED | DEQUEUE_SPECIAL); 8104 } 8105 } 8106 8107 /* 8108 * The part of dequeue_task_fair() that is needed to dequeue delayed tasks. 8109 * 8110 * Returns: 8111 * true - dequeued 8112 * false - delayed 8113 */ 8114 static bool __dequeue_task(struct rq *rq, struct task_struct *p, int flags) 8115 { 8116 struct sched_entity *se = &p->se; 8117 struct cfs_rq *cfs_rq = &rq->cfs; 8118 bool was_sched_idle = sched_idle_rq(rq); 8119 bool task_sleep = flags & DEQUEUE_SLEEP; 8120 bool task_delayed = flags & DEQUEUE_DELAYED; 8121 8122 clear_buddies(cfs_rq, se); 8123 8124 update_curr_eevdf(cfs_rq); 8125 update_entity_lag(cfs_rq, se); 8126 8127 if (flags & DEQUEUE_DELAYED) { 8128 WARN_ON_ONCE(!se->sched_delayed); 8129 } else { 8130 bool delay = task_sleep; 8131 /* 8132 * DELAY_DEQUEUE relies on spurious wakeups, special task 8133 * states must not suffer spurious wakeups, excempt them. 8134 */ 8135 if (flags & (DEQUEUE_SPECIAL | DEQUEUE_THROTTLE)) 8136 delay = false; 8137 8138 WARN_ON_ONCE(delay && se->sched_delayed); 8139 8140 if (sched_feat(DELAY_DEQUEUE) && delay && 8141 !entity_eligible(cfs_rq, se)) { 8142 update_load_avg(cfs_rq_of(se), se, UPDATE_UTIL_EST); 8143 set_delayed(se); 8144 return false; 8145 } 8146 } 8147 8148 dequeue_hierarchy(p, flags); 8149 8150 if (sched_feat(PLACE_REL_DEADLINE) && !task_sleep) { 8151 se->deadline -= se->vruntime; 8152 se->rel_deadline = 1; 8153 } 8154 if (se != cfs_rq->curr) 8155 __dequeue_entity(cfs_rq, se); 8156 8157 sub_nr_running(rq, 1); 8158 8159 /* balance early to pull high priority tasks */ 8160 if (unlikely(!was_sched_idle && sched_idle_rq(rq))) 8161 rq->next_balance = jiffies; 8162 8163 if (task_delayed) { 8164 clear_delayed(se); 8165 8166 WARN_ON_ONCE(!task_sleep); 8167 WARN_ON_ONCE(p->on_rq != 1); 8168 8169 /* 8170 * Fix-up what block_task() skipped. 8171 * 8172 * Must be last, @p might not be valid after this. 8173 */ 8174 __block_task(rq, p); 8175 } 8176 8177 return true; 8178 } 8179 8180 /* 8181 * The dequeue_task method is called before nr_running is 8182 * decreased. We remove the task from the rbtree and 8183 * update the fair scheduling stats: 8184 */ 8185 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags) 8186 { 8187 if (task_is_throttled(p)) { 8188 dequeue_throttled_task(p, flags); 8189 return true; 8190 } 8191 8192 if (!p->se.sched_delayed) 8193 util_est_dequeue(&rq->cfs, p); 8194 8195 if (!__dequeue_task(rq, p, flags)) 8196 return false; 8197 8198 /* 8199 * Must not reference @p after __dequeue_task(DEQUEUE_DELAYED). 8200 */ 8201 return true; 8202 } 8203 8204 static inline unsigned int cfs_h_nr_delayed(struct rq *rq) 8205 { 8206 return (rq->cfs.h_nr_queued - rq->cfs.h_nr_runnable); 8207 } 8208 8209 /* Working cpumask for: sched_balance_rq(), sched_balance_newidle(). */ 8210 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask); 8211 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask); 8212 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask); 8213 8214 #ifdef CONFIG_NO_HZ_COMMON 8215 8216 static struct { 8217 cpumask_var_t idle_cpus_mask; 8218 int has_blocked_load; /* Idle CPUS has blocked load */ 8219 int needs_update; /* Newly idle CPUs need their next_balance collated */ 8220 unsigned long next_balance; /* in jiffy units */ 8221 unsigned long next_blocked; /* Next update of blocked load in jiffies */ 8222 } nohz ____cacheline_aligned; 8223 8224 #endif /* CONFIG_NO_HZ_COMMON */ 8225 8226 static unsigned long cpu_load(struct rq *rq) 8227 { 8228 return cfs_rq_load_avg(&rq->cfs); 8229 } 8230 8231 /* 8232 * cpu_load_without - compute CPU load without any contributions from *p 8233 * @cpu: the CPU which load is requested 8234 * @p: the task which load should be discounted 8235 * 8236 * The load of a CPU is defined by the load of tasks currently enqueued on that 8237 * CPU as well as tasks which are currently sleeping after an execution on that 8238 * CPU. 8239 * 8240 * This method returns the load of the specified CPU by discounting the load of 8241 * the specified task, whenever the task is currently contributing to the CPU 8242 * load. 8243 */ 8244 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p) 8245 { 8246 struct cfs_rq *cfs_rq; 8247 unsigned int load; 8248 8249 /* Task has no contribution or is new */ 8250 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 8251 return cpu_load(rq); 8252 8253 cfs_rq = &rq->cfs; 8254 load = READ_ONCE(cfs_rq->avg.load_avg); 8255 8256 /* Discount task's util from CPU's util */ 8257 lsub_positive(&load, task_h_load(p)); 8258 8259 return load; 8260 } 8261 8262 static unsigned long cpu_runnable(struct rq *rq) 8263 { 8264 return cfs_rq_runnable_avg(&rq->cfs); 8265 } 8266 8267 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p) 8268 { 8269 struct cfs_rq *cfs_rq; 8270 unsigned int runnable; 8271 8272 /* Task has no contribution or is new */ 8273 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 8274 return cpu_runnable(rq); 8275 8276 cfs_rq = &rq->cfs; 8277 runnable = READ_ONCE(cfs_rq->avg.runnable_avg); 8278 8279 /* Discount task's runnable from CPU's runnable */ 8280 lsub_positive(&runnable, p->se.avg.runnable_avg); 8281 8282 return runnable; 8283 } 8284 8285 static unsigned long capacity_of(int cpu) 8286 { 8287 return cpu_rq(cpu)->cpu_capacity; 8288 } 8289 8290 static void record_wakee(struct task_struct *p) 8291 { 8292 /* 8293 * Only decay a single time; tasks that have less then 1 wakeup per 8294 * jiffy will not have built up many flips. 8295 */ 8296 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) { 8297 current->wakee_flips >>= 1; 8298 current->wakee_flip_decay_ts = jiffies; 8299 } 8300 8301 if (current->last_wakee != p) { 8302 current->last_wakee = p; 8303 current->wakee_flips++; 8304 } 8305 } 8306 8307 /* 8308 * Detect M:N waker/wakee relationships via a switching-frequency heuristic. 8309 * 8310 * A waker of many should wake a different task than the one last awakened 8311 * at a frequency roughly N times higher than one of its wakees. 8312 * 8313 * In order to determine whether we should let the load spread vs consolidating 8314 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one 8315 * partner, and a factor of lls_size higher frequency in the other. 8316 * 8317 * With both conditions met, we can be relatively sure that the relationship is 8318 * non-monogamous, with partner count exceeding socket size. 8319 * 8320 * Waker/wakee being client/server, worker/dispatcher, interrupt source or 8321 * whatever is irrelevant, spread criteria is apparent partner count exceeds 8322 * socket size. 8323 */ 8324 static int wake_wide(struct task_struct *p) 8325 { 8326 unsigned int master = current->wakee_flips; 8327 unsigned int slave = p->wakee_flips; 8328 int factor = __this_cpu_read(sd_llc_size); 8329 8330 if (master < slave) 8331 swap(master, slave); 8332 if (slave < factor || master < slave * factor) 8333 return 0; 8334 return 1; 8335 } 8336 8337 /* 8338 * The purpose of wake_affine() is to quickly determine on which CPU we can run 8339 * soonest. For the purpose of speed we only consider the waking and previous 8340 * CPU. 8341 * 8342 * wake_affine_idle() - only considers 'now', it check if the waking CPU is 8343 * cache-affine and is (or will be) idle. 8344 * 8345 * wake_affine_weight() - considers the weight to reflect the average 8346 * scheduling latency of the CPUs. This seems to work 8347 * for the overloaded case. 8348 */ 8349 static int 8350 wake_affine_idle(int this_cpu, int prev_cpu, int sync) 8351 { 8352 /* 8353 * If this_cpu is idle, it implies the wakeup is from interrupt 8354 * context. Only allow the move if cache is shared. Otherwise an 8355 * interrupt intensive workload could force all tasks onto one 8356 * node depending on the IO topology or IRQ affinity settings. 8357 * 8358 * If the prev_cpu is idle and cache affine then avoid a migration. 8359 * There is no guarantee that the cache hot data from an interrupt 8360 * is more important than cache hot data on the prev_cpu and from 8361 * a cpufreq perspective, it's better to have higher utilisation 8362 * on one CPU. 8363 */ 8364 if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu)) 8365 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu; 8366 8367 if (sync) { 8368 struct rq *rq = cpu_rq(this_cpu); 8369 8370 if ((rq->nr_running - cfs_h_nr_delayed(rq)) == 1) 8371 return this_cpu; 8372 } 8373 8374 if (available_idle_cpu(prev_cpu)) 8375 return prev_cpu; 8376 8377 return nr_cpumask_bits; 8378 } 8379 8380 static int 8381 wake_affine_weight(struct sched_domain *sd, struct task_struct *p, 8382 int this_cpu, int prev_cpu, int sync) 8383 { 8384 s64 this_eff_load, prev_eff_load; 8385 unsigned long task_load; 8386 8387 this_eff_load = cpu_load(cpu_rq(this_cpu)); 8388 8389 if (sync) { 8390 unsigned long current_load = task_h_load(current); 8391 8392 if (current_load > this_eff_load) 8393 return this_cpu; 8394 8395 this_eff_load -= current_load; 8396 } 8397 8398 task_load = task_h_load(p); 8399 8400 this_eff_load += task_load; 8401 if (sched_feat(WA_BIAS)) 8402 this_eff_load *= 100; 8403 this_eff_load *= capacity_of(prev_cpu); 8404 8405 prev_eff_load = cpu_load(cpu_rq(prev_cpu)); 8406 prev_eff_load -= task_load; 8407 if (sched_feat(WA_BIAS)) 8408 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2; 8409 prev_eff_load *= capacity_of(this_cpu); 8410 8411 /* 8412 * If sync, adjust the weight of prev_eff_load such that if 8413 * prev_eff == this_eff that select_idle_sibling() will consider 8414 * stacking the wakee on top of the waker if no other CPU is 8415 * idle. 8416 */ 8417 if (sync) 8418 prev_eff_load += 1; 8419 8420 return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits; 8421 } 8422 8423 static int wake_affine(struct sched_domain *sd, struct task_struct *p, 8424 int this_cpu, int prev_cpu, int sync) 8425 { 8426 int target = nr_cpumask_bits; 8427 8428 if (sched_feat(WA_IDLE)) 8429 target = wake_affine_idle(this_cpu, prev_cpu, sync); 8430 8431 if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits) 8432 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync); 8433 8434 schedstat_inc(p->stats.nr_wakeups_affine_attempts); 8435 if (target != this_cpu) 8436 return prev_cpu; 8437 8438 schedstat_inc(sd->ttwu_move_affine); 8439 schedstat_inc(p->stats.nr_wakeups_affine); 8440 return target; 8441 } 8442 8443 static struct sched_group * 8444 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu); 8445 8446 /* 8447 * sched_balance_find_dst_group_cpu - find the idlest CPU among the CPUs in the group. 8448 */ 8449 static int 8450 sched_balance_find_dst_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu) 8451 { 8452 unsigned long load, min_load = ULONG_MAX; 8453 unsigned int min_exit_latency = UINT_MAX; 8454 u64 latest_idle_timestamp = 0; 8455 int least_loaded_cpu = this_cpu; 8456 int shallowest_idle_cpu = -1; 8457 int i; 8458 8459 /* Check if we have any choice: */ 8460 if (group->group_weight == 1) 8461 return cpumask_first(sched_group_span(group)); 8462 8463 /* Traverse only the allowed CPUs */ 8464 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) { 8465 struct rq *rq = cpu_rq(i); 8466 8467 if (!sched_core_cookie_match(rq, p)) 8468 continue; 8469 8470 if (choose_sched_idle_rq(rq, p)) 8471 return i; 8472 8473 if (available_idle_cpu(i)) { 8474 struct cpuidle_state *idle = idle_get_state(rq); 8475 if (idle && idle->exit_latency < min_exit_latency) { 8476 /* 8477 * We give priority to a CPU whose idle state 8478 * has the smallest exit latency irrespective 8479 * of any idle timestamp. 8480 */ 8481 min_exit_latency = idle->exit_latency; 8482 latest_idle_timestamp = rq->idle_stamp; 8483 shallowest_idle_cpu = i; 8484 } else if ((!idle || idle->exit_latency == min_exit_latency) && 8485 rq->idle_stamp > latest_idle_timestamp) { 8486 /* 8487 * If equal or no active idle state, then 8488 * the most recently idled CPU might have 8489 * a warmer cache. 8490 */ 8491 latest_idle_timestamp = rq->idle_stamp; 8492 shallowest_idle_cpu = i; 8493 } 8494 } else if (shallowest_idle_cpu == -1) { 8495 load = cpu_load(cpu_rq(i)); 8496 if (load < min_load) { 8497 min_load = load; 8498 least_loaded_cpu = i; 8499 } 8500 } 8501 } 8502 8503 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu; 8504 } 8505 8506 static inline int sched_balance_find_dst_cpu(struct sched_domain *sd, struct task_struct *p, 8507 int cpu, int prev_cpu, int sd_flag) 8508 { 8509 int new_cpu = cpu; 8510 8511 if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr)) 8512 return prev_cpu; 8513 8514 /* 8515 * We need task's util for cpu_util_without, sync it up to 8516 * prev_cpu's last_update_time. 8517 */ 8518 if (!(sd_flag & SD_BALANCE_FORK)) 8519 sync_entity_load_avg(&p->se); 8520 8521 while (sd) { 8522 struct sched_group *group; 8523 struct sched_domain *tmp; 8524 int weight; 8525 8526 if (!(sd->flags & sd_flag)) { 8527 sd = sd->child; 8528 continue; 8529 } 8530 8531 group = sched_balance_find_dst_group(sd, p, cpu); 8532 if (!group) { 8533 sd = sd->child; 8534 continue; 8535 } 8536 8537 new_cpu = sched_balance_find_dst_group_cpu(group, p, cpu); 8538 if (new_cpu == cpu) { 8539 /* Now try balancing at a lower domain level of 'cpu': */ 8540 sd = sd->child; 8541 continue; 8542 } 8543 8544 /* Now try balancing at a lower domain level of 'new_cpu': */ 8545 cpu = new_cpu; 8546 weight = sd->span_weight; 8547 sd = NULL; 8548 for_each_domain(cpu, tmp) { 8549 if (weight <= tmp->span_weight) 8550 break; 8551 if (tmp->flags & sd_flag) 8552 sd = tmp; 8553 } 8554 } 8555 8556 return new_cpu; 8557 } 8558 8559 static inline int __select_idle_cpu(int cpu, struct task_struct *p) 8560 { 8561 if (choose_idle_cpu(cpu, p) && sched_cpu_cookie_match(cpu_rq(cpu), p)) 8562 return cpu; 8563 8564 return -1; 8565 } 8566 8567 DEFINE_STATIC_KEY_FALSE(sched_smt_present); 8568 EXPORT_SYMBOL_GPL(sched_smt_present); 8569 8570 static inline void set_idle_cores(int cpu, int val) 8571 { 8572 struct sched_domain_shared *sds; 8573 8574 sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu)); 8575 if (sds) 8576 WRITE_ONCE(sds->has_idle_cores, val); 8577 } 8578 8579 static inline bool test_idle_cores(int cpu) 8580 { 8581 struct sched_domain_shared *sds; 8582 8583 sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu)); 8584 if (sds) 8585 return READ_ONCE(sds->has_idle_cores); 8586 8587 return false; 8588 } 8589 8590 /* 8591 * Scans the local SMT mask to see if the entire core is idle, and records this 8592 * information in sd_balance_shared->has_idle_cores. 8593 * 8594 * Since SMT siblings share all cache levels, inspecting this limited remote 8595 * state should be fairly cheap. 8596 */ 8597 void __update_idle_core(struct rq *rq) 8598 { 8599 int core = cpu_of(rq); 8600 int cpu; 8601 8602 rcu_read_lock(); 8603 if (test_idle_cores(core)) 8604 goto unlock; 8605 8606 for_each_cpu(cpu, cpu_smt_mask(core)) { 8607 if (cpu == core) 8608 continue; 8609 8610 if (!available_idle_cpu(cpu)) 8611 goto unlock; 8612 } 8613 8614 set_idle_cores(core, 1); 8615 unlock: 8616 rcu_read_unlock(); 8617 } 8618 8619 /* 8620 * Scan the entire LLC domain for idle cores; this dynamically switches off if 8621 * there are no idle cores left in the system; tracked through 8622 * sd_balance_shared->has_idle_cores and enabled through update_idle_core() 8623 * above. 8624 */ 8625 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu) 8626 { 8627 bool idle = true; 8628 int cpu; 8629 8630 for_each_cpu(cpu, cpu_smt_mask(core)) { 8631 if (!available_idle_cpu(cpu)) { 8632 idle = false; 8633 if (*idle_cpu == -1) { 8634 if (choose_sched_idle_rq(cpu_rq(cpu), p) && 8635 cpumask_test_cpu(cpu, cpus)) { 8636 *idle_cpu = cpu; 8637 break; 8638 } 8639 continue; 8640 } 8641 break; 8642 } 8643 if (*idle_cpu == -1 && cpumask_test_cpu(cpu, cpus)) 8644 *idle_cpu = cpu; 8645 } 8646 8647 if (idle) 8648 return core; 8649 8650 cpumask_andnot(cpus, cpus, cpu_smt_mask(core)); 8651 return -1; 8652 } 8653 8654 /* 8655 * Scan the local SMT mask for idle CPUs. 8656 */ 8657 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target) 8658 { 8659 int cpu; 8660 8661 for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) { 8662 if (cpu == target) 8663 continue; 8664 /* 8665 * Check if the CPU is in the LLC scheduling domain of @target. 8666 * Due to isolcpus, there is no guarantee that all the siblings are in the domain. 8667 */ 8668 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) 8669 continue; 8670 if (choose_idle_cpu(cpu, p)) 8671 return cpu; 8672 } 8673 8674 return -1; 8675 } 8676 8677 /* 8678 * Scan the LLC domain for idle CPUs; this is dynamically regulated by 8679 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the 8680 * average idle time for this rq (as found in rq->avg_idle). 8681 */ 8682 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target) 8683 { 8684 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask); 8685 int i, cpu, idle_cpu = -1, nr = INT_MAX; 8686 8687 if (sched_feat(SIS_UTIL) && sd->shared) { 8688 /* 8689 * Increment because !--nr is the condition to stop scan. 8690 * 8691 * Since "sd" is "sd_llc" for target CPU dereferenced in the 8692 * caller, it is safe to directly dereference "sd->shared". 8693 * Topology bits always ensure it assigned for "sd_llc" abd it 8694 * cannot disappear as long as we have a RCU protected 8695 * reference to one the associated "sd" here. 8696 */ 8697 nr = READ_ONCE(sd->shared->nr_idle_scan) + 1; 8698 /* overloaded LLC is unlikely to have idle cpu/core */ 8699 if (nr == 1) 8700 return -1; 8701 } 8702 8703 if (!cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr)) 8704 return -1; 8705 8706 if (static_branch_unlikely(&sched_cluster_active)) { 8707 struct sched_group *sg = sd->groups; 8708 8709 if (sg->flags & SD_CLUSTER) { 8710 for_each_cpu_wrap(cpu, sched_group_span(sg), target + 1) { 8711 if (!cpumask_test_cpu(cpu, cpus)) 8712 continue; 8713 8714 if (has_idle_core) { 8715 i = select_idle_core(p, cpu, cpus, &idle_cpu); 8716 if ((unsigned int)i < nr_cpumask_bits) 8717 return i; 8718 } else { 8719 if (--nr <= 0) 8720 return -1; 8721 idle_cpu = __select_idle_cpu(cpu, p); 8722 if ((unsigned int)idle_cpu < nr_cpumask_bits) 8723 return idle_cpu; 8724 } 8725 } 8726 cpumask_andnot(cpus, cpus, sched_group_span(sg)); 8727 } 8728 } 8729 8730 for_each_cpu_wrap(cpu, cpus, target + 1) { 8731 if (has_idle_core) { 8732 i = select_idle_core(p, cpu, cpus, &idle_cpu); 8733 if ((unsigned int)i < nr_cpumask_bits) 8734 return i; 8735 8736 } else { 8737 if (--nr <= 0) 8738 return -1; 8739 idle_cpu = __select_idle_cpu(cpu, p); 8740 if ((unsigned int)idle_cpu < nr_cpumask_bits) 8741 break; 8742 } 8743 } 8744 8745 if (has_idle_core) 8746 set_idle_cores(target, false); 8747 8748 return idle_cpu; 8749 } 8750 8751 /* 8752 * Idle-capacity scan converts util_fits_cpu() outcomes into preference ranks, 8753 * where lower values indicate a better fit - see select_idle_capacity(). 8754 * 8755 * A CPU that both fits the task and sits on a fully-idle SMT core is returned 8756 * immediately and is never assigned one of these ranks. On !SMT every CPU is 8757 * its own "core", so the early return covers all fits-and-idle cases and the 8758 * core-tier ranks below become unreachable. 8759 * 8760 * Rank Val Tier Meaning 8761 * ------------------------------ --- ------ --------------------------- 8762 * ASYM_IDLE_UCLAMP_MISFIT -4 core Idle core; capacity fits 8763 * util but uclamp_min misses. 8764 * ASYM_IDLE_COMPLETE_MISFIT -3 core Idle core; capacity does 8765 * not fit. Still beats every 8766 * thread-tier rank: a busy 8767 * sibling cuts effective 8768 * capacity more than a 8769 * misfit hurts a quiet core. 8770 * ASYM_IDLE_THREAD_FITS -2 thread Busy SMT sibling; capacity 8771 * fits util + uclamp. 8772 * ASYM_IDLE_THREAD_UCLAMP_MISFIT -1 thread Busy SMT sibling; capacity 8773 * fits but uclamp_min misses 8774 * (native util_fits_cpu() 8775 * return value). 8776 * ASYM_IDLE_THREAD_MISFIT 0 thread Busy SMT sibling; capacity 8777 * does not fit. 8778 * 8779 * ASYM_IDLE_CORE_BIAS (-3) is an offset, not a state. On an idle core, 8780 * fits += ASYM_IDLE_CORE_BIAS rebases thread-tier ranks into the core tier: 8781 * 8782 * ASYM_IDLE_THREAD_UCLAMP_MISFIT (-1) + BIAS -> ASYM_IDLE_UCLAMP_MISFIT (-4) 8783 * ASYM_IDLE_THREAD_MISFIT (0) + BIAS -> ASYM_IDLE_COMPLETE_MISFIT (-3) 8784 * 8785 * ASYM_IDLE_THREAD_FITS (-2) is never rebased because a fully-fitting idle-core 8786 * candidate early-returns from select_idle_capacity(). 8787 */ 8788 enum asym_fits_state { 8789 ASYM_IDLE_UCLAMP_MISFIT = -4, 8790 ASYM_IDLE_COMPLETE_MISFIT, 8791 ASYM_IDLE_THREAD_FITS, 8792 ASYM_IDLE_THREAD_UCLAMP_MISFIT, 8793 ASYM_IDLE_THREAD_MISFIT, 8794 8795 /* util_fits_cpu() bias for idle core */ 8796 ASYM_IDLE_CORE_BIAS = -3, 8797 }; 8798 8799 /* 8800 * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which 8801 * the task fits. If no CPU is big enough, but there are idle ones, try to 8802 * maximize capacity. 8803 */ 8804 static int 8805 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target) 8806 { 8807 /* 8808 * On !SMT systems, has_idle_core is always false and preferred_core 8809 * is always true (CPU == core), so the SMT preference logic below 8810 * collapses to the plain capacity scan. 8811 */ 8812 bool has_idle_core = sched_smt_active() && test_idle_cores(target); 8813 unsigned long task_util, util_min, util_max, best_cap = 0; 8814 int fits, best_fits = ASYM_IDLE_THREAD_MISFIT; 8815 int cpu, best_cpu = -1; 8816 struct cpumask *cpus; 8817 int nr = INT_MAX; 8818 8819 cpus = this_cpu_cpumask_var_ptr(select_rq_mask); 8820 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr); 8821 8822 task_util = task_util_est(p); 8823 util_min = uclamp_eff_value(p, UCLAMP_MIN); 8824 util_max = uclamp_eff_value(p, UCLAMP_MAX); 8825 8826 if (sched_feat(SIS_UTIL) && sd->shared) { 8827 /* 8828 * Same nr_idle_scan hint as select_idle_cpu(), nr only limits 8829 * the scan when not preferring an idle core. 8830 */ 8831 nr = READ_ONCE(sd->shared->nr_idle_scan) + 1; 8832 /* overloaded domain is unlikely to have idle cpu/core */ 8833 if (nr == 1) 8834 return -1; 8835 } 8836 8837 for_each_cpu_wrap(cpu, cpus, target) { 8838 bool preferred_core = !has_idle_core || is_core_idle(cpu); 8839 unsigned long cpu_cap = capacity_of(cpu); 8840 8841 /* 8842 * Stop when the nr_idle_scan is exhausted (mirrors 8843 * select_idle_cpu() logic). 8844 */ 8845 if (!has_idle_core && --nr <= 0) 8846 return best_cpu; 8847 8848 if (!choose_idle_cpu(cpu, p)) 8849 continue; 8850 8851 fits = util_fits_cpu(task_util, util_min, util_max, cpu); 8852 8853 /* 8854 * Perfect fit: capacity satisfies util + uclamp and the CPU 8855 * sits on a fully-idle SMT core, this is a !SMT system, or 8856 * there is no idle core to find. 8857 * Short-circuit the rank-based selection and return 8858 * immediately. 8859 */ 8860 if (fits > 0 && preferred_core) 8861 return cpu; 8862 /* 8863 * Only the min performance hint (i.e. uclamp_min) doesn't fit. 8864 * Look for the CPU with best capacity. 8865 */ 8866 else if (fits < 0) 8867 cpu_cap = get_actual_cpu_capacity(cpu); 8868 /* 8869 * fits > 0 implies we are not on a preferred core, but the util 8870 * fits CPU capacity. Set fits to ASYM_IDLE_THREAD_FITS 8871 * so the effective range becomes 8872 * [ASYM_IDLE_THREAD_FITS, ASYM_IDLE_THREAD_MISFIT], where: 8873 * ASYM_IDLE_THREAD_MISFIT - does not fit 8874 * ASYM_IDLE_THREAD_UCLAMP_MISFIT - fits with the exception of UCLAMP_MIN 8875 * ASYM_IDLE_THREAD_FITS - fits with the exception of preferred_core 8876 */ 8877 else if (fits > 0) 8878 fits = ASYM_IDLE_THREAD_FITS; 8879 8880 /* 8881 * If we are on a preferred core, translate the range of fits 8882 * of [ASYM_IDLE_THREAD_UCLAMP_MISFIT, ASYM_IDLE_THREAD_MISFIT] to 8883 * [ASYM_IDLE_UCLAMP_MISFIT, ASYM_IDLE_COMPLETE_MISFIT]. 8884 * This ensures that an idle core is always given priority over 8885 * (partially) busy core. 8886 * 8887 * A fully fitting idle core would have returned early and hence 8888 * fits > 0 for preferred_core need not be dealt with. 8889 */ 8890 if (preferred_core) 8891 fits += ASYM_IDLE_CORE_BIAS; 8892 8893 /* 8894 * First, select CPU which fits better (lower is more preferred). 8895 * Then, select the one with best capacity at same level. 8896 */ 8897 if ((fits < best_fits) || 8898 ((fits == best_fits) && (cpu_cap > best_cap))) { 8899 best_cap = cpu_cap; 8900 best_cpu = cpu; 8901 best_fits = fits; 8902 } 8903 } 8904 8905 /* 8906 * A value in the [ASYM_IDLE_UCLAMP_MISFIT, ASYM_IDLE_COMPLETE_MISFIT] 8907 * range means the chosen CPU is in a fully idle SMT core. Values above 8908 * ASYM_IDLE_COMPLETE_MISFIT mean we never ranked such a CPU best. 8909 * 8910 * The asym-capacity wakeup path returns from select_idle_sibling() 8911 * after this function and never runs select_idle_cpu(), so the usual 8912 * select_idle_cpu() tail that clears idle cores must live here when the 8913 * idle-core preference did not win. 8914 */ 8915 if (has_idle_core && best_fits > ASYM_IDLE_COMPLETE_MISFIT) 8916 set_idle_cores(target, false); 8917 8918 return best_cpu; 8919 } 8920 8921 static inline bool asym_fits_cpu(unsigned long util, 8922 unsigned long util_min, 8923 unsigned long util_max, 8924 int cpu) 8925 { 8926 if (sched_asym_cpucap_active()) { 8927 /* 8928 * Return true only if the cpu fully fits the task requirements 8929 * which include the utilization and the performance hints. 8930 * 8931 * When SMT is active, also require that the core has no busy 8932 * siblings. 8933 * 8934 * Note: gating on is_core_idle() also makes the early-bailout 8935 * candidates in select_idle_sibling() (target, prev, 8936 * recent_used_cpu) idle-core-aware on ASYM+SMT, which the 8937 * NO_ASYM path does not do. 8938 */ 8939 return (!sched_smt_active() || is_core_idle(cpu)) && 8940 (util_fits_cpu(util, util_min, util_max, cpu) > 0); 8941 } 8942 8943 return true; 8944 } 8945 8946 /* 8947 * Try and locate an idle core/thread in the LLC cache domain. 8948 */ 8949 static int select_idle_sibling(struct task_struct *p, int prev, int target) 8950 { 8951 bool has_idle_core = false; 8952 struct sched_domain *sd; 8953 unsigned long task_util, util_min, util_max; 8954 int i, recent_used_cpu, prev_aff = -1; 8955 8956 /* 8957 * On asymmetric system, update task utilization because we will check 8958 * that the task fits with CPU's capacity. 8959 */ 8960 if (sched_asym_cpucap_active()) { 8961 sync_entity_load_avg(&p->se); 8962 task_util = task_util_est(p); 8963 util_min = uclamp_eff_value(p, UCLAMP_MIN); 8964 util_max = uclamp_eff_value(p, UCLAMP_MAX); 8965 } 8966 8967 /* 8968 * per-cpu select_rq_mask usage 8969 */ 8970 lockdep_assert_irqs_disabled(); 8971 8972 if (choose_idle_cpu(target, p) && 8973 asym_fits_cpu(task_util, util_min, util_max, target)) 8974 return target; 8975 8976 /* 8977 * If the previous CPU is cache affine and idle, don't be stupid: 8978 */ 8979 if (prev != target && cpus_share_cache(prev, target) && 8980 choose_idle_cpu(prev, p) && 8981 asym_fits_cpu(task_util, util_min, util_max, prev)) { 8982 8983 if (!static_branch_unlikely(&sched_cluster_active) || 8984 cpus_share_resources(prev, target)) 8985 return prev; 8986 8987 prev_aff = prev; 8988 } 8989 8990 /* 8991 * Allow a per-cpu kthread to stack with the wakee if the 8992 * kworker thread and the tasks previous CPUs are the same. 8993 * The assumption is that the wakee queued work for the 8994 * per-cpu kthread that is now complete and the wakeup is 8995 * essentially a sync wakeup. An obvious example of this 8996 * pattern is IO completions. 8997 */ 8998 if (is_per_cpu_kthread(current) && 8999 in_task() && 9000 prev == smp_processor_id() && 9001 this_rq()->nr_running <= 1 && 9002 asym_fits_cpu(task_util, util_min, util_max, prev)) { 9003 return prev; 9004 } 9005 9006 /* Check a recently used CPU as a potential idle candidate: */ 9007 recent_used_cpu = p->recent_used_cpu; 9008 p->recent_used_cpu = prev; 9009 if (recent_used_cpu != prev && 9010 recent_used_cpu != target && 9011 cpus_share_cache(recent_used_cpu, target) && 9012 choose_idle_cpu(recent_used_cpu, p) && 9013 cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) && 9014 asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) { 9015 9016 if (!static_branch_unlikely(&sched_cluster_active) || 9017 cpus_share_resources(recent_used_cpu, target)) 9018 return recent_used_cpu; 9019 9020 } else { 9021 recent_used_cpu = -1; 9022 } 9023 9024 /* 9025 * For asymmetric CPU capacity systems, our domain of interest is 9026 * sd_asym_cpucapacity rather than sd_llc. 9027 */ 9028 if (sched_asym_cpucap_active()) { 9029 sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, target)); 9030 /* 9031 * On an asymmetric CPU capacity system where an exclusive 9032 * cpuset defines a symmetric island (i.e. one unique 9033 * capacity_orig value through the cpuset), the key will be set 9034 * but the CPUs within that cpuset will not have a domain with 9035 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric 9036 * capacity path. 9037 */ 9038 if (sd) { 9039 i = select_idle_capacity(p, sd, target); 9040 return ((unsigned)i < nr_cpumask_bits) ? i : target; 9041 } 9042 } 9043 9044 sd = rcu_dereference_all(per_cpu(sd_llc, target)); 9045 if (!sd) 9046 return target; 9047 9048 if (sched_smt_active()) { 9049 has_idle_core = test_idle_cores(target); 9050 9051 if (!has_idle_core && cpus_share_cache(prev, target)) { 9052 i = select_idle_smt(p, sd, prev); 9053 if ((unsigned int)i < nr_cpumask_bits) 9054 return i; 9055 } 9056 } 9057 9058 i = select_idle_cpu(p, sd, has_idle_core, target); 9059 if ((unsigned)i < nr_cpumask_bits) 9060 return i; 9061 9062 /* 9063 * For cluster machines which have lower sharing cache like L2 or 9064 * LLC Tag, we tend to find an idle CPU in the target's cluster 9065 * first. But prev_cpu or recent_used_cpu may also be a good candidate, 9066 * use them if possible when no idle CPU found in select_idle_cpu(). 9067 */ 9068 if ((unsigned int)prev_aff < nr_cpumask_bits) 9069 return prev_aff; 9070 if ((unsigned int)recent_used_cpu < nr_cpumask_bits) 9071 return recent_used_cpu; 9072 9073 return target; 9074 } 9075 9076 /** 9077 * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks. 9078 * @cpu: the CPU to get the utilization for 9079 * @p: task for which the CPU utilization should be predicted or NULL 9080 * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL 9081 * @boost: 1 to enable boosting, otherwise 0 9082 * 9083 * The unit of the return value must be the same as the one of CPU capacity 9084 * so that CPU utilization can be compared with CPU capacity. 9085 * 9086 * CPU utilization is the sum of running time of runnable tasks plus the 9087 * recent utilization of currently non-runnable tasks on that CPU. 9088 * It represents the amount of CPU capacity currently used by CFS tasks in 9089 * the range [0..max CPU capacity] with max CPU capacity being the CPU 9090 * capacity at f_max. 9091 * 9092 * The estimated CPU utilization is defined as the maximum between CPU 9093 * utilization and sum of the estimated utilization of the currently 9094 * runnable tasks on that CPU. It preserves a utilization "snapshot" of 9095 * previously-executed tasks, which helps better deduce how busy a CPU will 9096 * be when a long-sleeping task wakes up. The contribution to CPU utilization 9097 * of such a task would be significantly decayed at this point of time. 9098 * 9099 * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization). 9100 * CPU contention for CFS tasks can be detected by CPU runnable > CPU 9101 * utilization. Boosting is implemented in cpu_util() so that internal 9102 * users (e.g. EAS) can use it next to external users (e.g. schedutil), 9103 * latter via cpu_util_cfs_boost(). 9104 * 9105 * CPU utilization can be higher than the current CPU capacity 9106 * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because 9107 * of rounding errors as well as task migrations or wakeups of new tasks. 9108 * CPU utilization has to be capped to fit into the [0..max CPU capacity] 9109 * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%) 9110 * could be seen as over-utilized even though CPU1 has 20% of spare CPU 9111 * capacity. CPU utilization is allowed to overshoot current CPU capacity 9112 * though since this is useful for predicting the CPU capacity required 9113 * after task migrations (scheduler-driven DVFS). 9114 * 9115 * Return: (Boosted) (estimated) utilization for the specified CPU. 9116 */ 9117 static unsigned long 9118 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost) 9119 { 9120 bool add_task = p && task_cpu(p) != cpu && dst_cpu == cpu; 9121 bool sub_task = p && task_cpu(p) == cpu && dst_cpu != cpu; 9122 struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs; 9123 unsigned long util = READ_ONCE(cfs_rq->avg.util_avg); 9124 unsigned long runnable; 9125 9126 /* 9127 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its 9128 * contribution. If @p migrates from another CPU to @cpu add its 9129 * contribution. In all the other cases @cpu is not impacted by the 9130 * migration so its util_avg is already correct. 9131 */ 9132 if (add_task) 9133 util += task_util(p); 9134 else if (sub_task) 9135 lsub_positive(&util, task_util(p)); 9136 9137 if (boost) { 9138 runnable = READ_ONCE(cfs_rq->avg.runnable_avg); 9139 if (add_task) 9140 runnable += READ_ONCE(p->se.avg.runnable_avg); 9141 else if (sub_task) 9142 lsub_positive(&runnable, 9143 READ_ONCE(p->se.avg.runnable_avg)); 9144 util = max(util, runnable); 9145 } 9146 9147 if (sched_feat(UTIL_EST)) { 9148 unsigned long util_est; 9149 9150 util_est = READ_ONCE(cfs_rq->avg.util_est); 9151 9152 /* 9153 * During wake-up @p isn't enqueued yet and doesn't contribute 9154 * to any cpu_rq(cpu)->cfs.avg.util_est. 9155 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p 9156 * has been enqueued. 9157 * 9158 * During exec (@dst_cpu = -1) @p is enqueued and does 9159 * contribute to cpu_rq(cpu)->cfs.util_est. 9160 * Remove it to "simulate" cpu_util without @p's contribution. 9161 * 9162 * Despite the task_on_rq_queued(@p) check there is still a 9163 * small window for a possible race when an exec 9164 * select_task_rq_fair() races with LB's detach_task(). 9165 * 9166 * detach_task() 9167 * deactivate_task() 9168 * p->on_rq = TASK_ON_RQ_MIGRATING; 9169 * -------------------------------- A 9170 * dequeue_task() \ 9171 * dequeue_task_fair() + Race Time 9172 * util_est_dequeue() / 9173 * -------------------------------- B 9174 * 9175 * The additional check "current == p" is required to further 9176 * reduce the race window. 9177 */ 9178 if (dst_cpu == cpu) 9179 util_est += _task_util_est(p); 9180 else if (p && unlikely(task_on_rq_queued(p) || current == p)) 9181 lsub_positive(&util_est, _task_util_est(p)); 9182 9183 util = max(util, util_est); 9184 } 9185 9186 return min(util, arch_scale_cpu_capacity(cpu)); 9187 } 9188 9189 unsigned long cpu_util_cfs(int cpu) 9190 { 9191 return cpu_util(cpu, NULL, -1, 0); 9192 } 9193 9194 unsigned long cpu_util_cfs_boost(int cpu) 9195 { 9196 return cpu_util(cpu, NULL, -1, 1); 9197 } 9198 9199 /* 9200 * cpu_util_without: compute cpu utilization without any contributions from *p 9201 * @cpu: the CPU which utilization is requested 9202 * @p: the task which utilization should be discounted 9203 * 9204 * The utilization of a CPU is defined by the utilization of tasks currently 9205 * enqueued on that CPU as well as tasks which are currently sleeping after an 9206 * execution on that CPU. 9207 * 9208 * This method returns the utilization of the specified CPU by discounting the 9209 * utilization of the specified task, whenever the task is currently 9210 * contributing to the CPU utilization. 9211 */ 9212 static unsigned long cpu_util_without(int cpu, struct task_struct *p) 9213 { 9214 /* Task has no contribution or is new */ 9215 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 9216 p = NULL; 9217 9218 return cpu_util(cpu, p, -1, 0); 9219 } 9220 9221 /* 9222 * This function computes an effective utilization for the given CPU, to be 9223 * used for frequency selection given the linear relation: f = u * f_max. 9224 * 9225 * The scheduler tracks the following metrics: 9226 * 9227 * cpu_util_{cfs,rt,dl,irq}() 9228 * cpu_bw_dl() 9229 * 9230 * Where the cfs,rt and dl util numbers are tracked with the same metric and 9231 * synchronized windows and are thus directly comparable. 9232 * 9233 * The cfs,rt,dl utilization are the running times measured with rq->clock_task 9234 * which excludes things like IRQ and steal-time. These latter are then accrued 9235 * in the IRQ utilization. 9236 * 9237 * The DL bandwidth number OTOH is not a measured metric but a value computed 9238 * based on the task model parameters and gives the minimal utilization 9239 * required to meet deadlines. 9240 */ 9241 unsigned long effective_cpu_util(int cpu, unsigned long util_cfs, 9242 unsigned long *min, 9243 unsigned long *max) 9244 { 9245 unsigned long util, irq, scale; 9246 struct rq *rq = cpu_rq(cpu); 9247 9248 scale = arch_scale_cpu_capacity(cpu); 9249 9250 /* 9251 * Early check to see if IRQ/steal time saturates the CPU, can be 9252 * because of inaccuracies in how we track these -- see 9253 * update_irq_load_avg(). 9254 */ 9255 irq = cpu_util_irq(rq); 9256 if (unlikely(irq >= scale)) { 9257 if (min) 9258 *min = scale; 9259 if (max) 9260 *max = scale; 9261 return scale; 9262 } 9263 9264 if (min) { 9265 /* 9266 * The minimum utilization returns the highest level between: 9267 * - the computed DL bandwidth needed with the IRQ pressure which 9268 * steals time to the deadline task. 9269 * - The minimum performance requirement for CFS and/or RT. 9270 */ 9271 *min = max(irq + cpu_bw_dl(rq), uclamp_rq_get(rq, UCLAMP_MIN)); 9272 9273 /* 9274 * When an RT task is runnable and uclamp is not used, we must 9275 * ensure that the task will run at maximum compute capacity. 9276 */ 9277 if (!uclamp_is_used() && rt_rq_is_runnable(&rq->rt)) 9278 *min = max(*min, scale); 9279 } 9280 9281 /* 9282 * Because the time spend on RT/DL tasks is visible as 'lost' time to 9283 * CFS tasks and we use the same metric to track the effective 9284 * utilization (PELT windows are synchronized) we can directly add them 9285 * to obtain the CPU's actual utilization. 9286 */ 9287 util = util_cfs + cpu_util_rt(rq); 9288 util += cpu_util_dl(rq); 9289 9290 /* 9291 * The maximum hint is a soft bandwidth requirement, which can be lower 9292 * than the actual utilization because of uclamp_max requirements. 9293 */ 9294 if (max) 9295 *max = min(scale, uclamp_rq_get(rq, UCLAMP_MAX)); 9296 9297 if (util >= scale) 9298 return scale; 9299 9300 /* 9301 * There is still idle time; further improve the number by using the 9302 * IRQ metric. Because IRQ/steal time is hidden from the task clock we 9303 * need to scale the task numbers: 9304 * 9305 * max - irq 9306 * U' = irq + --------- * U 9307 * max 9308 */ 9309 util = scale_irq_capacity(util, irq, scale); 9310 util += irq; 9311 9312 return min(scale, util); 9313 } 9314 9315 unsigned long sched_cpu_util(int cpu) 9316 { 9317 return effective_cpu_util(cpu, cpu_util_cfs(cpu), NULL, NULL); 9318 } 9319 9320 /* 9321 * energy_env - Utilization landscape for energy estimation. 9322 * @task_busy_time: Utilization contribution by the task for which we test the 9323 * placement. Given by eenv_task_busy_time(). 9324 * @pd_busy_time: Utilization of the whole perf domain without the task 9325 * contribution. Given by eenv_pd_busy_time(). 9326 * @cpu_cap: Maximum CPU capacity for the perf domain. 9327 * @pd_cap: Entire perf domain capacity. (pd->nr_cpus * cpu_cap). 9328 */ 9329 struct energy_env { 9330 unsigned long task_busy_time; 9331 unsigned long pd_busy_time; 9332 unsigned long cpu_cap; 9333 unsigned long pd_cap; 9334 }; 9335 9336 /* 9337 * Compute the task busy time for compute_energy(). This time cannot be 9338 * injected directly into effective_cpu_util() because of the IRQ scaling. 9339 * The latter only makes sense with the most recent CPUs where the task has 9340 * run. 9341 */ 9342 static inline void eenv_task_busy_time(struct energy_env *eenv, 9343 struct task_struct *p, int prev_cpu) 9344 { 9345 unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu); 9346 unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu)); 9347 9348 if (unlikely(irq >= max_cap)) 9349 busy_time = max_cap; 9350 else 9351 busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap); 9352 9353 eenv->task_busy_time = busy_time; 9354 } 9355 9356 /* 9357 * Compute the perf_domain (PD) busy time for compute_energy(). Based on the 9358 * utilization for each @pd_cpus, it however doesn't take into account 9359 * clamping since the ratio (utilization / cpu_capacity) is already enough to 9360 * scale the EM reported power consumption at the (eventually clamped) 9361 * cpu_capacity. 9362 * 9363 * The contribution of the task @p for which we want to estimate the 9364 * energy cost is removed (by cpu_util()) and must be calculated 9365 * separately (see eenv_task_busy_time). This ensures: 9366 * 9367 * - A stable PD utilization, no matter which CPU of that PD we want to place 9368 * the task on. 9369 * 9370 * - A fair comparison between CPUs as the task contribution (task_util()) 9371 * will always be the same no matter which CPU utilization we rely on 9372 * (util_avg or util_est). 9373 * 9374 * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't 9375 * exceed @eenv->pd_cap. 9376 */ 9377 static inline void eenv_pd_busy_time(struct energy_env *eenv, 9378 struct cpumask *pd_cpus, 9379 struct task_struct *p) 9380 { 9381 unsigned long busy_time = 0; 9382 int cpu; 9383 9384 for_each_cpu(cpu, pd_cpus) { 9385 unsigned long util = cpu_util(cpu, p, -1, 0); 9386 9387 busy_time += effective_cpu_util(cpu, util, NULL, NULL); 9388 } 9389 9390 eenv->pd_busy_time = min(eenv->pd_cap, busy_time); 9391 } 9392 9393 /* 9394 * Compute the maximum utilization for compute_energy() when the task @p 9395 * is placed on the cpu @dst_cpu. 9396 * 9397 * Returns the maximum utilization among @eenv->cpus. This utilization can't 9398 * exceed @eenv->cpu_cap. 9399 */ 9400 static inline unsigned long 9401 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus, 9402 struct task_struct *p, int dst_cpu) 9403 { 9404 unsigned long max_util = 0; 9405 int cpu; 9406 9407 for_each_cpu(cpu, pd_cpus) { 9408 struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL; 9409 unsigned long util = cpu_util(cpu, p, dst_cpu, 1); 9410 unsigned long eff_util, min, max; 9411 9412 /* 9413 * Performance domain frequency: utilization clamping 9414 * must be considered since it affects the selection 9415 * of the performance domain frequency. 9416 * NOTE: in case RT tasks are running, by default the min 9417 * utilization can be max OPP. 9418 */ 9419 eff_util = effective_cpu_util(cpu, util, &min, &max); 9420 9421 /* Task's uclamp can modify min and max value */ 9422 if (tsk && uclamp_is_used()) { 9423 min = max(min, uclamp_eff_value(p, UCLAMP_MIN)); 9424 9425 /* 9426 * If there is no active max uclamp constraint, 9427 * directly use task's one, otherwise keep max. 9428 */ 9429 if (uclamp_rq_is_idle(cpu_rq(cpu))) 9430 max = uclamp_eff_value(p, UCLAMP_MAX); 9431 else 9432 max = max(max, uclamp_eff_value(p, UCLAMP_MAX)); 9433 } 9434 9435 eff_util = sugov_effective_cpu_perf(cpu, eff_util, min, max); 9436 max_util = max(max_util, eff_util); 9437 } 9438 9439 return min(max_util, eenv->cpu_cap); 9440 } 9441 9442 /* 9443 * compute_energy(): Use the Energy Model to estimate the energy that @pd would 9444 * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task 9445 * contribution is ignored. 9446 */ 9447 static inline unsigned long 9448 compute_energy(struct energy_env *eenv, struct perf_domain *pd, 9449 struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu) 9450 { 9451 unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu); 9452 unsigned long busy_time = eenv->pd_busy_time; 9453 unsigned long energy; 9454 9455 if (dst_cpu >= 0) 9456 busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time); 9457 9458 energy = em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap); 9459 9460 trace_sched_compute_energy_tp(p, dst_cpu, energy, max_util, busy_time); 9461 9462 return energy; 9463 } 9464 9465 /* 9466 * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the 9467 * waking task. find_energy_efficient_cpu() looks for the CPU with maximum 9468 * spare capacity in each performance domain and uses it as a potential 9469 * candidate to execute the task. Then, it uses the Energy Model to figure 9470 * out which of the CPU candidates is the most energy-efficient. 9471 * 9472 * The rationale for this heuristic is as follows. In a performance domain, 9473 * all the most energy efficient CPU candidates (according to the Energy 9474 * Model) are those for which we'll request a low frequency. When there are 9475 * several CPUs for which the frequency request will be the same, we don't 9476 * have enough data to break the tie between them, because the Energy Model 9477 * only includes active power costs. With this model, if we assume that 9478 * frequency requests follow utilization (e.g. using schedutil), the CPU with 9479 * the maximum spare capacity in a performance domain is guaranteed to be among 9480 * the best candidates of the performance domain. 9481 * 9482 * In practice, it could be preferable from an energy standpoint to pack 9483 * small tasks on a CPU in order to let other CPUs go in deeper idle states, 9484 * but that could also hurt our chances to go cluster idle, and we have no 9485 * ways to tell with the current Energy Model if this is actually a good 9486 * idea or not. So, find_energy_efficient_cpu() basically favors 9487 * cluster-packing, and spreading inside a cluster. That should at least be 9488 * a good thing for latency, and this is consistent with the idea that most 9489 * of the energy savings of EAS come from the asymmetry of the system, and 9490 * not so much from breaking the tie between identical CPUs. That's also the 9491 * reason why EAS is enabled in the topology code only for systems where 9492 * SD_ASYM_CPUCAPACITY is set. 9493 * 9494 * NOTE: Forkees are not accepted in the energy-aware wake-up path because 9495 * they don't have any useful utilization data yet and it's not possible to 9496 * forecast their impact on energy consumption. Consequently, they will be 9497 * placed by sched_balance_find_dst_cpu() on the least loaded CPU, which might turn out 9498 * to be energy-inefficient in some use-cases. The alternative would be to 9499 * bias new tasks towards specific types of CPUs first, or to try to infer 9500 * their util_avg from the parent task, but those heuristics could hurt 9501 * other use-cases too. So, until someone finds a better way to solve this, 9502 * let's keep things simple by re-using the existing slow path. 9503 */ 9504 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu) 9505 { 9506 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask); 9507 unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX; 9508 unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0; 9509 unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024; 9510 struct root_domain *rd = this_rq()->rd; 9511 int cpu, best_energy_cpu, target = -1; 9512 int prev_fits = -1, best_fits = -1; 9513 unsigned long best_actual_cap = 0; 9514 unsigned long prev_actual_cap = 0; 9515 struct sched_domain *sd; 9516 struct perf_domain *pd; 9517 struct energy_env eenv; 9518 9519 pd = rcu_dereference_all(rd->pd); 9520 if (!pd) 9521 return target; 9522 9523 /* 9524 * Energy-aware wake-up happens on the lowest sched_domain starting 9525 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu. 9526 */ 9527 sd = rcu_dereference_all(*this_cpu_ptr(&sd_asym_cpucapacity)); 9528 while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd))) 9529 sd = sd->parent; 9530 if (!sd) 9531 return target; 9532 9533 target = prev_cpu; 9534 9535 sync_entity_load_avg(&p->se); 9536 if (!task_util_est(p) && p_util_min == 0) 9537 return target; 9538 9539 eenv_task_busy_time(&eenv, p, prev_cpu); 9540 9541 for (; pd; pd = pd->next) { 9542 unsigned long util_min = p_util_min, util_max = p_util_max; 9543 unsigned long cpu_cap, cpu_actual_cap, util; 9544 long prev_spare_cap = -1, max_spare_cap = -1; 9545 unsigned long rq_util_min, rq_util_max; 9546 unsigned long cur_delta, base_energy; 9547 int max_spare_cap_cpu = -1; 9548 int fits, max_fits = -1; 9549 9550 if (!cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask)) 9551 continue; 9552 9553 /* Account external pressure for the energy estimation */ 9554 cpu = cpumask_first(cpus); 9555 cpu_actual_cap = get_actual_cpu_capacity(cpu); 9556 9557 eenv.cpu_cap = cpu_actual_cap; 9558 eenv.pd_cap = 0; 9559 9560 for_each_cpu(cpu, cpus) { 9561 struct rq *rq = cpu_rq(cpu); 9562 9563 eenv.pd_cap += cpu_actual_cap; 9564 9565 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) 9566 continue; 9567 9568 if (!cpumask_test_cpu(cpu, p->cpus_ptr)) 9569 continue; 9570 9571 util = cpu_util(cpu, p, cpu, 0); 9572 cpu_cap = capacity_of(cpu); 9573 9574 /* 9575 * Skip CPUs that cannot satisfy the capacity request. 9576 * IOW, placing the task there would make the CPU 9577 * overutilized. Take uclamp into account to see how 9578 * much capacity we can get out of the CPU; this is 9579 * aligned with sched_cpu_util(). 9580 */ 9581 if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) { 9582 /* 9583 * Open code uclamp_rq_util_with() except for 9584 * the clamp() part. I.e.: apply max aggregation 9585 * only. util_fits_cpu() logic requires to 9586 * operate on non clamped util but must use the 9587 * max-aggregated uclamp_{min, max}. 9588 */ 9589 rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN); 9590 rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX); 9591 9592 util_min = max(rq_util_min, p_util_min); 9593 util_max = max(rq_util_max, p_util_max); 9594 } 9595 9596 fits = util_fits_cpu(util, util_min, util_max, cpu); 9597 if (!fits) 9598 continue; 9599 9600 lsub_positive(&cpu_cap, util); 9601 9602 if (cpu == prev_cpu) { 9603 /* Always use prev_cpu as a candidate. */ 9604 prev_spare_cap = cpu_cap; 9605 prev_fits = fits; 9606 } else if ((fits > max_fits) || 9607 ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) { 9608 /* 9609 * Find the CPU with the maximum spare capacity 9610 * among the remaining CPUs in the performance 9611 * domain. 9612 */ 9613 max_spare_cap = cpu_cap; 9614 max_spare_cap_cpu = cpu; 9615 max_fits = fits; 9616 } 9617 } 9618 9619 if (max_spare_cap_cpu < 0 && prev_spare_cap < 0) 9620 continue; 9621 9622 eenv_pd_busy_time(&eenv, cpus, p); 9623 /* Compute the 'base' energy of the pd, without @p */ 9624 base_energy = compute_energy(&eenv, pd, cpus, p, -1); 9625 9626 /* Evaluate the energy impact of using prev_cpu. */ 9627 if (prev_spare_cap > -1) { 9628 prev_delta = compute_energy(&eenv, pd, cpus, p, 9629 prev_cpu); 9630 /* CPU utilization has changed */ 9631 if (prev_delta < base_energy) 9632 return target; 9633 prev_delta -= base_energy; 9634 prev_actual_cap = cpu_actual_cap; 9635 best_delta = min(best_delta, prev_delta); 9636 } 9637 9638 /* Evaluate the energy impact of using max_spare_cap_cpu. */ 9639 if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) { 9640 /* Current best energy cpu fits better */ 9641 if (max_fits < best_fits) 9642 continue; 9643 9644 /* 9645 * Both don't fit performance hint (i.e. uclamp_min) 9646 * but best energy cpu has better capacity. 9647 */ 9648 if ((max_fits < 0) && 9649 (cpu_actual_cap <= best_actual_cap)) 9650 continue; 9651 9652 cur_delta = compute_energy(&eenv, pd, cpus, p, 9653 max_spare_cap_cpu); 9654 /* CPU utilization has changed */ 9655 if (cur_delta < base_energy) 9656 return target; 9657 cur_delta -= base_energy; 9658 9659 /* 9660 * Both fit for the task but best energy cpu has lower 9661 * energy impact. 9662 */ 9663 if ((max_fits > 0) && (best_fits > 0) && 9664 (cur_delta >= best_delta)) 9665 continue; 9666 9667 best_delta = cur_delta; 9668 best_energy_cpu = max_spare_cap_cpu; 9669 best_fits = max_fits; 9670 best_actual_cap = cpu_actual_cap; 9671 } 9672 } 9673 9674 if ((best_fits > prev_fits) || 9675 ((best_fits > 0) && (best_delta < prev_delta)) || 9676 ((best_fits < 0) && (best_actual_cap > prev_actual_cap))) 9677 target = best_energy_cpu; 9678 9679 return target; 9680 } 9681 9682 /* 9683 * select_task_rq_fair: Select target runqueue for the waking task in domains 9684 * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE, 9685 * SD_BALANCE_FORK, or SD_BALANCE_EXEC. 9686 * 9687 * Balances load by selecting the idlest CPU in the idlest group, or under 9688 * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set. 9689 * 9690 * Returns the target CPU number. 9691 */ 9692 static int 9693 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags) 9694 { 9695 int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING); 9696 struct sched_domain *tmp, *sd = NULL; 9697 int cpu = smp_processor_id(); 9698 int new_cpu = prev_cpu; 9699 int want_affine = 0; 9700 /* SD_flags and WF_flags share the first nibble */ 9701 int sd_flag = wake_flags & 0xF; 9702 9703 /* 9704 * required for stable ->cpus_allowed 9705 */ 9706 lockdep_assert_held(&p->pi_lock); 9707 if (wake_flags & WF_TTWU) { 9708 record_wakee(p); 9709 9710 if ((wake_flags & WF_CURRENT_CPU) && 9711 cpumask_test_cpu(cpu, p->cpus_ptr)) 9712 return cpu; 9713 9714 if (!is_rd_overutilized(this_rq()->rd)) { 9715 new_cpu = find_energy_efficient_cpu(p, prev_cpu); 9716 if (new_cpu >= 0) 9717 return new_cpu; 9718 new_cpu = prev_cpu; 9719 } 9720 9721 want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr); 9722 } 9723 9724 for_each_domain(cpu, tmp) { 9725 /* 9726 * If both 'cpu' and 'prev_cpu' are part of this domain, 9727 * cpu is a valid SD_WAKE_AFFINE target. 9728 */ 9729 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) && 9730 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) { 9731 if (cpu != prev_cpu) 9732 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync); 9733 9734 sd = NULL; /* Prefer wake_affine over balance flags */ 9735 break; 9736 } 9737 9738 /* 9739 * Usually only true for WF_EXEC and WF_FORK, as sched_domains 9740 * usually do not have SD_BALANCE_WAKE set. That means wakeup 9741 * will usually go to the fast path. 9742 */ 9743 if (tmp->flags & sd_flag) 9744 sd = tmp; 9745 else if (!want_affine) 9746 break; 9747 } 9748 9749 /* Slow path */ 9750 if (unlikely(sd)) 9751 return sched_balance_find_dst_cpu(sd, p, cpu, prev_cpu, sd_flag); 9752 9753 /* Fast path */ 9754 if (wake_flags & WF_TTWU) 9755 return select_idle_sibling(p, prev_cpu, new_cpu); 9756 9757 return new_cpu; 9758 } 9759 9760 /* 9761 * Called immediately before a task is migrated to a new CPU; task_cpu(p) and 9762 * cfs_rq_of(p) references at time of call are still valid and identify the 9763 * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held. 9764 */ 9765 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu) 9766 { 9767 struct sched_entity *se = &p->se; 9768 9769 if (!task_on_rq_migrating(p)) { 9770 remove_entity_load_avg(se); 9771 9772 /* 9773 * Here, the task's PELT values have been updated according to 9774 * the current rq's clock. But if that clock hasn't been 9775 * updated in a while, a substantial idle time will be missed, 9776 * leading to an inflation after wake-up on the new rq. 9777 * 9778 * Estimate the missing time from the cfs_rq last_update_time 9779 * and update sched_avg to improve the PELT continuity after 9780 * migration. 9781 */ 9782 migrate_se_pelt_lag(se); 9783 } 9784 9785 /* Tell new CPU we are migrated */ 9786 se->avg.last_update_time = 0; 9787 9788 update_scan_period(p, new_cpu); 9789 } 9790 9791 static void task_dead_fair(struct task_struct *p) 9792 { 9793 struct sched_entity *se = &p->se; 9794 remove_entity_load_avg(se); 9795 } 9796 9797 /* 9798 * Set the max capacity the task is allowed to run at for misfit detection. 9799 */ 9800 static void set_task_max_allowed_capacity(struct task_struct *p) 9801 { 9802 struct asym_cap_data *entry; 9803 9804 if (!sched_asym_cpucap_active()) 9805 return; 9806 9807 rcu_read_lock(); 9808 list_for_each_entry_rcu(entry, &asym_cap_list, link) { 9809 cpumask_t *cpumask; 9810 9811 cpumask = cpu_capacity_span(entry); 9812 if (!cpumask_intersects(p->cpus_ptr, cpumask)) 9813 continue; 9814 9815 p->max_allowed_capacity = entry->capacity; 9816 break; 9817 } 9818 rcu_read_unlock(); 9819 } 9820 9821 static void set_cpus_allowed_fair(struct task_struct *p, struct affinity_context *ctx) 9822 { 9823 set_cpus_allowed_common(p, ctx); 9824 set_task_max_allowed_capacity(p); 9825 } 9826 9827 enum preempt_wakeup_action { 9828 PREEMPT_WAKEUP_NONE, /* No preemption. */ 9829 PREEMPT_WAKEUP_SHORT, /* Ignore slice protection. */ 9830 PREEMPT_WAKEUP_PICK, /* Let pick_eevdf() decide. */ 9831 PREEMPT_WAKEUP_RESCHED, /* Force reschedule. */ 9832 }; 9833 9834 static inline bool set_preempt_buddy(struct cfs_rq *cfs_rq, struct sched_entity *pse) 9835 { 9836 /* 9837 * Keep existing buddy if the deadline is sooner than pse. 9838 * The older buddy may be cache cold and completely unrelated 9839 * to the current wakeup but that is unpredictable where as 9840 * obeying the deadline is more in line with EEVDF objectives. 9841 */ 9842 if (cfs_rq->next && entity_before(cfs_rq->next, pse)) 9843 return false; 9844 9845 set_next_buddy(cfs_rq, pse); 9846 return true; 9847 } 9848 9849 static inline bool set_short_buddy(struct cfs_rq *cfs_rq, struct sched_entity *pse) 9850 { 9851 if (cfs_rq->next && cfs_rq->next->slice < pse->slice) 9852 return false; 9853 9854 set_next_buddy(cfs_rq, pse); 9855 return true; 9856 } 9857 9858 /* 9859 * WF_SYNC|WF_TTWU indicates the waker expects to sleep but it is not 9860 * strictly enforced because the hint is either misunderstood or 9861 * multiple tasks must be woken up. 9862 */ 9863 static inline enum preempt_wakeup_action 9864 preempt_sync(struct rq *rq, int wake_flags, 9865 struct sched_entity *pse, struct sched_entity *se) 9866 { 9867 u64 threshold, delta; 9868 9869 /* 9870 * WF_SYNC without WF_TTWU is not expected so warn if it happens even 9871 * though it is likely harmless. 9872 */ 9873 WARN_ON_ONCE(!(wake_flags & WF_TTWU)); 9874 9875 threshold = sysctl_sched_migration_cost; 9876 delta = rq_clock_task(rq) - se->exec_start; 9877 if ((s64)delta < 0) 9878 delta = 0; 9879 9880 /* 9881 * WF_RQ_SELECTED implies the tasks are stacking on a CPU when they 9882 * could run on other CPUs. Reduce the threshold before preemption is 9883 * allowed to an arbitrary lower value as it is more likely (but not 9884 * guaranteed) the waker requires the wakee to finish. 9885 */ 9886 if (wake_flags & WF_RQ_SELECTED) 9887 threshold >>= 2; 9888 9889 /* 9890 * As WF_SYNC is not strictly obeyed, allow some runtime for batch 9891 * wakeups to be issued. 9892 */ 9893 if (entity_before(pse, se) && delta >= threshold) 9894 return PREEMPT_WAKEUP_RESCHED; 9895 9896 return PREEMPT_WAKEUP_NONE; 9897 } 9898 9899 /* 9900 * Preempt the current task with a newly woken task if needed: 9901 */ 9902 static void wakeup_preempt_fair(struct rq *rq, struct task_struct *p, int wake_flags) 9903 { 9904 enum preempt_wakeup_action preempt_action = PREEMPT_WAKEUP_PICK; 9905 struct task_struct *donor = rq->donor; 9906 struct sched_entity *nse, *se = &donor->se, *pse = &p->se; 9907 struct cfs_rq *cfs_rq = &rq->cfs; 9908 int cse_is_idle, pse_is_idle; 9909 9910 /* 9911 * XXX Getting preempted by higher class, try and find idle CPU? 9912 */ 9913 if (p->sched_class != &fair_sched_class || 9914 donor->sched_class != &fair_sched_class) 9915 return; 9916 9917 if (unlikely(se == pse)) 9918 return; 9919 9920 /* 9921 * This is possible from callers such as attach_tasks(), in which we 9922 * unconditionally wakeup_preempt() after an enqueue (which may have 9923 * lead to a throttle). This both saves work and prevents false 9924 * next-buddy nomination below. 9925 */ 9926 if (task_is_throttled(p)) 9927 return; 9928 9929 /* 9930 * We can come here with TIF_NEED_RESCHED already set from new task 9931 * wake up path. 9932 * 9933 * Note: this also catches the edge-case of curr being in a throttled 9934 * group (e.g. via set_curr_task), since update_curr() (in the 9935 * enqueue of curr) will have resulted in resched being set. This 9936 * prevents us from potentially nominating it as a false LAST_BUDDY 9937 * below. 9938 */ 9939 if (!sched_feat(PREEMPT_SHORT) && test_tsk_need_resched(rq->curr)) 9940 return; 9941 9942 if (!sched_feat(WAKEUP_PREEMPTION)) 9943 return; 9944 9945 WARN_ON_ONCE(!pse); 9946 9947 cse_is_idle = se_is_idle(se); 9948 pse_is_idle = se_is_idle(pse); 9949 9950 nse = se; 9951 /* 9952 * Preempt an idle entity in favor of a non-idle entity (and don't preempt 9953 * in the inverse case). 9954 */ 9955 if (cse_is_idle && !pse_is_idle) 9956 goto preempt; 9957 9958 update_curr_fair(rq); 9959 9960 if (cse_is_idle != pse_is_idle) 9961 goto update; 9962 9963 /* 9964 * BATCH and IDLE tasks do not preempt others. 9965 */ 9966 if (unlikely(!normal_policy(p->policy))) 9967 goto update; 9968 9969 /* 9970 * Do not preempt for tasks that are sched_delayed as it would violate 9971 * EEVDF to forcibly queue an ineligible task. 9972 */ 9973 if (pse->sched_delayed) 9974 goto update; 9975 9976 /* 9977 * If @p has a shorter slice than current and @p is eligible, override 9978 * current's slice protection in order to allow preemption. 9979 */ 9980 if (sched_feat(PREEMPT_SHORT) && (pse->slice < se->slice)) { 9981 preempt_action = PREEMPT_WAKEUP_SHORT; 9982 goto pick; 9983 } 9984 9985 /* 9986 * Ignore wakee preemption on WF_FORK as it is less likely that 9987 * there is shared data as exec often follow fork. 9988 */ 9989 if (wake_flags & WF_FORK) 9990 goto update; 9991 9992 /* Prefer picking wakee soon if appropriate. */ 9993 if (sched_feat(NEXT_BUDDY) && set_preempt_buddy(cfs_rq, pse)) { 9994 /* 9995 * Decide whether to obey WF_SYNC hint for a new buddy. Old 9996 * buddies are ignored as they may not be relevant to the 9997 * waker and less likely to be cache hot. 9998 */ 9999 if (wake_flags & WF_SYNC) 10000 preempt_action = preempt_sync(rq, wake_flags, pse, se); 10001 } 10002 10003 switch (preempt_action) { 10004 case PREEMPT_WAKEUP_NONE: 10005 return; 10006 case PREEMPT_WAKEUP_RESCHED: 10007 goto preempt; 10008 case PREEMPT_WAKEUP_SHORT: 10009 fallthrough; 10010 case PREEMPT_WAKEUP_PICK: 10011 break; 10012 } 10013 10014 pick: 10015 if (cfs_rq->h_nr_queued) { 10016 nse = pick_next_entity(rq, preempt_action != PREEMPT_WAKEUP_SHORT); 10017 if (unlikely(!nse)) 10018 goto pick; 10019 10020 /* If @p has become the most eligible task, force preemption */ 10021 if (nse == pse) 10022 goto preempt; 10023 } 10024 10025 /* 10026 * If @p is eligible but not the next task to run then cancel protection 10027 * to prevent large scheduling latency 10028 */ 10029 if (preempt_action == PREEMPT_WAKEUP_SHORT && entity_eligible(cfs_rq, pse)) 10030 goto preempt; 10031 update: 10032 if (sched_feat(RUN_TO_PARITY)) 10033 update_protect_slice(cfs_rq, se); 10034 10035 return; 10036 10037 preempt: 10038 cancel_protect_slice(se); 10039 10040 if (preempt_action == PREEMPT_WAKEUP_SHORT) 10041 set_short_buddy(cfs_rq, pse); 10042 10043 resched_curr_lazy(rq); 10044 } 10045 10046 struct task_struct *pick_task_fair(struct rq *rq, struct rq_flags *rf) 10047 __must_hold(__rq_lockp(rq)) 10048 { 10049 struct cfs_rq *cfs_rq = &rq->cfs; 10050 struct sched_entity *se; 10051 struct task_struct *p; 10052 int new_tasks; 10053 10054 again: 10055 if (!cfs_rq->h_nr_queued) 10056 goto idle; 10057 10058 /* Might not have done put_prev_entity() */ 10059 if (cfs_rq->curr && cfs_rq->curr->on_rq) 10060 update_curr(cfs_rq); 10061 10062 se = pick_next_entity(rq, true); 10063 if (!se) 10064 goto again; 10065 10066 p = task_of(se); 10067 return p; 10068 10069 idle: 10070 if (sched_core_enabled(rq)) 10071 return NULL; 10072 10073 new_tasks = sched_balance_newidle(rq, rf); 10074 if (new_tasks < 0) 10075 return RETRY_TASK; 10076 if (new_tasks > 0) 10077 goto again; 10078 return NULL; 10079 } 10080 10081 static struct task_struct * 10082 fair_server_pick_task(struct sched_dl_entity *dl_se, struct rq_flags *rf) 10083 __must_hold(__rq_lockp(dl_se->rq)) 10084 { 10085 return pick_task_fair(dl_se->rq, rf); 10086 } 10087 10088 void fair_server_init(struct rq *rq) 10089 { 10090 struct sched_dl_entity *dl_se = &rq->fair_server; 10091 10092 init_dl_entity(dl_se); 10093 10094 dl_server_init(dl_se, rq, fair_server_pick_task); 10095 } 10096 10097 /* 10098 * Account for a descheduled task: 10099 */ 10100 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev, struct task_struct *next) 10101 { 10102 struct sched_entity *se = &prev->se; 10103 struct cfs_rq *cfs_rq = &rq->cfs; 10104 struct sched_entity *nse = NULL; 10105 10106 #ifdef CONFIG_FAIR_GROUP_SCHED 10107 if (next && next->sched_class == &fair_sched_class) 10108 nse = &next->se; 10109 #endif 10110 10111 while (se) { 10112 cfs_rq = cfs_rq_of(se); 10113 if (!nse || cfs_rq->h_curr) 10114 put_prev_entity(cfs_rq, se); 10115 #ifdef CONFIG_FAIR_GROUP_SCHED 10116 if (nse) { 10117 if (is_same_group(se, nse)) 10118 break; 10119 10120 int d = nse->depth - se->depth; 10121 if (d >= 0) { 10122 /* nse has equal or greater depth, ascend */ 10123 nse = parent_entity(nse); 10124 /* if nse is the deeper, do not ascend se */ 10125 if (d > 0) 10126 continue; 10127 } 10128 } 10129 #endif 10130 se = parent_entity(se); 10131 } 10132 10133 /* Put 'current' back into the tree. */ 10134 cfs_rq = &rq->cfs; 10135 se = &prev->se; 10136 WARN_ON_ONCE(cfs_rq->curr != se); 10137 cfs_rq->curr = NULL; 10138 if (se->on_rq) 10139 __enqueue_entity(cfs_rq, se); 10140 } 10141 10142 /* 10143 * sched_yield() is very simple 10144 */ 10145 static void yield_task_fair(struct rq *rq) 10146 { 10147 struct task_struct *curr = rq->donor; 10148 struct sched_entity *se = &curr->se; 10149 struct cfs_rq *cfs_rq = &rq->cfs; 10150 10151 /* 10152 * Are we the only task in the tree? 10153 */ 10154 if (unlikely(rq->nr_running == 1)) 10155 return; 10156 10157 clear_buddies(cfs_rq, se); 10158 10159 update_rq_clock(rq); 10160 /* 10161 * Update run-time statistics of the 'current'. 10162 */ 10163 update_curr(cfs_rq); 10164 /* 10165 * Tell update_rq_clock() that we've just updated, 10166 * so we don't do microscopic update in schedule() 10167 * and double the fastpath cost. 10168 */ 10169 rq_clock_skip_update(rq); 10170 10171 /* 10172 * Forfeit the remaining vruntime, only if the entity is eligible. This 10173 * condition is necessary because in core scheduling we prefer to run 10174 * ineligible tasks rather than force idling. If this happens we may 10175 * end up in a loop where the core scheduler picks the yielding task, 10176 * which yields immediately again; without the condition the vruntime 10177 * ends up quickly running away. 10178 */ 10179 if (entity_eligible(cfs_rq, se)) { 10180 se->vruntime = se->deadline; 10181 update_deadline(cfs_rq, se); 10182 } 10183 } 10184 10185 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p) 10186 { 10187 struct sched_entity *se = &p->se; 10188 10189 /* !se->on_rq also covers throttled task */ 10190 if (!se->on_rq || se->sched_delayed) 10191 return false; 10192 10193 /* Tell the scheduler that we'd really like se to run next. */ 10194 set_next_buddy(&task_rq(p)->cfs, se); 10195 10196 yield_task_fair(rq); 10197 10198 return true; 10199 } 10200 10201 /************************************************** 10202 * Fair scheduling class load-balancing methods. 10203 * 10204 * BASICS 10205 * 10206 * The purpose of load-balancing is to achieve the same basic fairness the 10207 * per-CPU scheduler provides, namely provide a proportional amount of compute 10208 * time to each task. This is expressed in the following equation: 10209 * 10210 * W_i,n/P_i == W_j,n/P_j for all i,j (1) 10211 * 10212 * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight 10213 * W_i,0 is defined as: 10214 * 10215 * W_i,0 = \Sum_j w_i,j (2) 10216 * 10217 * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight 10218 * is derived from the nice value as per sched_prio_to_weight[]. 10219 * 10220 * The weight average is an exponential decay average of the instantaneous 10221 * weight: 10222 * 10223 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3) 10224 * 10225 * C_i is the compute capacity of CPU i, typically it is the 10226 * fraction of 'recent' time available for SCHED_OTHER task execution. But it 10227 * can also include other factors [XXX]. 10228 * 10229 * To achieve this balance we define a measure of imbalance which follows 10230 * directly from (1): 10231 * 10232 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4) 10233 * 10234 * We them move tasks around to minimize the imbalance. In the continuous 10235 * function space it is obvious this converges, in the discrete case we get 10236 * a few fun cases generally called infeasible weight scenarios. 10237 * 10238 * [XXX expand on: 10239 * - infeasible weights; 10240 * - local vs global optima in the discrete case. ] 10241 * 10242 * 10243 * SCHED DOMAINS 10244 * 10245 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2) 10246 * for all i,j solution, we create a tree of CPUs that follows the hardware 10247 * topology where each level pairs two lower groups (or better). This results 10248 * in O(log n) layers. Furthermore we reduce the number of CPUs going up the 10249 * tree to only the first of the previous level and we decrease the frequency 10250 * of load-balance at each level inversely proportional to the number of CPUs in 10251 * the groups. 10252 * 10253 * This yields: 10254 * 10255 * log_2 n 1 n 10256 * \Sum { --- * --- * 2^i } = O(n) (5) 10257 * i = 0 2^i 2^i 10258 * `- size of each group 10259 * | | `- number of CPUs doing load-balance 10260 * | `- freq 10261 * `- sum over all levels 10262 * 10263 * Coupled with a limit on how many tasks we can migrate every balance pass, 10264 * this makes (5) the runtime complexity of the balancer. 10265 * 10266 * An important property here is that each CPU is still (indirectly) connected 10267 * to every other CPU in at most O(log n) steps: 10268 * 10269 * The adjacency matrix of the resulting graph is given by: 10270 * 10271 * log_2 n 10272 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6) 10273 * k = 0 10274 * 10275 * And you'll find that: 10276 * 10277 * A^(log_2 n)_i,j != 0 for all i,j (7) 10278 * 10279 * Showing there's indeed a path between every CPU in at most O(log n) steps. 10280 * The task movement gives a factor of O(m), giving a convergence complexity 10281 * of: 10282 * 10283 * O(nm log n), n := nr_cpus, m := nr_tasks (8) 10284 * 10285 * 10286 * WORK CONSERVING 10287 * 10288 * In order to avoid CPUs going idle while there's still work to do, new idle 10289 * balancing is more aggressive and has the newly idle CPU iterate up the domain 10290 * tree itself instead of relying on other CPUs to bring it work. 10291 * 10292 * This adds some complexity to both (5) and (8) but it reduces the total idle 10293 * time. 10294 * 10295 * [XXX more?] 10296 * 10297 * 10298 * CGROUPS 10299 * 10300 * Cgroups make a horror show out of (2), instead of a simple sum we get: 10301 * 10302 * s_k,i 10303 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9) 10304 * S_k 10305 * 10306 * Where 10307 * 10308 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10) 10309 * 10310 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i. 10311 * 10312 * The big problem is S_k, its a global sum needed to compute a local (W_i) 10313 * property. 10314 * 10315 * [XXX write more on how we solve this.. _after_ merging pjt's patches that 10316 * rewrite all of this once again.] 10317 */ 10318 10319 static unsigned long __read_mostly max_load_balance_interval = HZ/10; 10320 10321 enum fbq_type { regular, remote, all }; 10322 10323 /* 10324 * 'group_type' describes the group of CPUs at the moment of load balancing. 10325 * 10326 * The enum is ordered by pulling priority, with the group with lowest priority 10327 * first so the group_type can simply be compared when selecting the busiest 10328 * group. See update_sd_pick_busiest(). 10329 */ 10330 enum group_type { 10331 /* The group has spare capacity that can be used to run more tasks. */ 10332 group_has_spare = 0, 10333 /* 10334 * The group is fully used and the tasks don't compete for more CPU 10335 * cycles. Nevertheless, some tasks might wait before running. 10336 */ 10337 group_fully_busy, 10338 /* 10339 * One task doesn't fit with CPU's capacity and must be migrated to a 10340 * more powerful CPU. 10341 */ 10342 group_misfit_task, 10343 /* 10344 * Balance SMT group that's fully busy. Can benefit from migration 10345 * a task on SMT with busy sibling to another CPU on idle core. 10346 */ 10347 group_smt_balance, 10348 /* 10349 * SD_ASYM_PACKING only: One local CPU with higher capacity is available, 10350 * and the task should be migrated to it instead of running on the 10351 * current CPU. 10352 */ 10353 group_asym_packing, 10354 /* 10355 * The tasks' affinity constraints previously prevented the scheduler 10356 * from balancing the load across the system. 10357 */ 10358 group_imbalanced, 10359 /* 10360 * There are tasks running on non-preferred LLC, possible to move 10361 * them to their preferred LLC without creating too much imbalance. 10362 * The priority of group_llc_balance is lower than that of 10363 * group_overloaded and higher than that of all other group types. 10364 * This is because group_llc_balance may exacerbate load imbalance. 10365 * If the LLC balancing attempt fails, the nr_balance_failed 10366 * mechanism will trigger other group types to rebalance the load. 10367 */ 10368 group_llc_balance, 10369 /* 10370 * The CPU is overloaded and can't provide expected CPU cycles to all 10371 * tasks. 10372 */ 10373 group_overloaded 10374 }; 10375 10376 enum migration_type { 10377 migrate_load = 0, 10378 migrate_util, 10379 migrate_task, 10380 migrate_misfit, 10381 migrate_llc_task 10382 }; 10383 10384 #define LBF_ALL_PINNED 0x01 10385 #define LBF_NEED_BREAK 0x02 10386 #define LBF_DST_PINNED 0x04 10387 #define LBF_SOME_PINNED 0x08 10388 #define LBF_ACTIVE_LB 0x10 10389 #define LBF_LLC_PINNED 0x20 10390 10391 struct lb_env { 10392 struct sched_domain *sd; 10393 10394 struct rq *src_rq; 10395 int src_cpu; 10396 10397 int dst_cpu; 10398 struct rq *dst_rq; 10399 bool dst_core_idle; 10400 10401 struct cpumask *dst_grpmask; 10402 int new_dst_cpu; 10403 enum cpu_idle_type idle; 10404 long imbalance; 10405 /* The set of CPUs under consideration for load-balancing */ 10406 struct cpumask *cpus; 10407 10408 unsigned int flags; 10409 10410 unsigned int loop; 10411 unsigned int loop_break; 10412 unsigned int loop_max; 10413 10414 enum fbq_type fbq_type; 10415 enum migration_type migration_type; 10416 struct list_head tasks; 10417 }; 10418 10419 /* 10420 * Is this task likely cache-hot: 10421 */ 10422 static int task_hot(struct task_struct *p, struct lb_env *env) 10423 { 10424 s64 delta; 10425 10426 lockdep_assert_rq_held(env->src_rq); 10427 10428 if (p->sched_class != &fair_sched_class) 10429 return 0; 10430 10431 if (unlikely(task_has_idle_policy(p))) 10432 return 0; 10433 10434 /* SMT siblings share cache */ 10435 if (env->sd->flags & SD_SHARE_CPUCAPACITY) 10436 return 0; 10437 10438 /* 10439 * Buddy candidates are cache hot: 10440 */ 10441 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running && 10442 (&p->se == cfs_rq_of(&p->se)->next)) 10443 return 1; 10444 10445 if (sysctl_sched_migration_cost == -1) 10446 return 1; 10447 10448 /* 10449 * Don't migrate task if the task's cookie does not match 10450 * with the destination CPU's core cookie. 10451 */ 10452 if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p)) 10453 return 1; 10454 10455 if (sysctl_sched_migration_cost == 0) 10456 return 0; 10457 10458 delta = rq_clock_task(env->src_rq) - p->se.exec_start; 10459 10460 return delta < (s64)sysctl_sched_migration_cost; 10461 } 10462 10463 #ifdef CONFIG_NUMA_BALANCING 10464 /* 10465 * Returns a positive value, if task migration degrades locality. 10466 * Returns 0, if task migration is not affected by locality. 10467 * Returns a negative value, if task migration improves locality i.e migration preferred. 10468 */ 10469 static long migrate_degrades_locality(struct task_struct *p, struct lb_env *env) 10470 { 10471 struct numa_group *numa_group = rcu_dereference_all(p->numa_group); 10472 unsigned long src_weight, dst_weight; 10473 int src_nid, dst_nid, dist; 10474 10475 if (!static_branch_likely(&sched_numa_balancing)) 10476 return 0; 10477 10478 if (!p->numa_faults || !(env->sd->flags & SD_NUMA)) 10479 return 0; 10480 10481 src_nid = cpu_to_node(env->src_cpu); 10482 dst_nid = cpu_to_node(env->dst_cpu); 10483 10484 if (src_nid == dst_nid) 10485 return 0; 10486 10487 /* Migrating away from the preferred node is always bad. */ 10488 if (src_nid == p->numa_preferred_nid) { 10489 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running) 10490 return 1; 10491 else 10492 return 0; 10493 } 10494 10495 /* Encourage migration to the preferred node. */ 10496 if (dst_nid == p->numa_preferred_nid) 10497 return -1; 10498 10499 /* Leaving a core idle is often worse than degrading locality. */ 10500 if (env->idle == CPU_IDLE) 10501 return 0; 10502 10503 dist = node_distance(src_nid, dst_nid); 10504 if (numa_group) { 10505 src_weight = group_weight(p, src_nid, dist); 10506 dst_weight = group_weight(p, dst_nid, dist); 10507 } else { 10508 src_weight = task_weight(p, src_nid, dist); 10509 dst_weight = task_weight(p, dst_nid, dist); 10510 } 10511 10512 return src_weight - dst_weight; 10513 } 10514 10515 #else /* !CONFIG_NUMA_BALANCING: */ 10516 static inline long migrate_degrades_locality(struct task_struct *p, 10517 struct lb_env *env) 10518 { 10519 return 0; 10520 } 10521 #endif /* !CONFIG_NUMA_BALANCING */ 10522 10523 /* 10524 * Check whether the task is ineligible on the destination cpu 10525 * 10526 * When the PLACE_LAG scheduling feature is enabled and 10527 * dst_cfs_rq->nr_queued is greater than 1, if the task 10528 * is ineligible, it will also be ineligible when 10529 * it is migrated to the destination cpu. 10530 */ 10531 static inline int task_is_ineligible_on_dst_cpu(struct task_struct *p, int dest_cpu) 10532 { 10533 struct cfs_rq *dst_cfs_rq = &cpu_rq(dest_cpu)->cfs; 10534 10535 if (sched_feat(PLACE_LAG) && dst_cfs_rq->h_nr_queued && 10536 !entity_eligible(&task_rq(p)->cfs, &p->se)) 10537 return 1; 10538 10539 return 0; 10540 } 10541 10542 #ifdef CONFIG_SCHED_CACHE 10543 /* 10544 * The margin used when comparing LLC utilization with CPU capacity. 10545 * It determines the LLC load level where active LLC aggregation is 10546 * done. 10547 * Derived from fits_capacity(). 10548 * 10549 * (default: ~50%, tunable via debugfs) 10550 */ 10551 static bool fits_llc_capacity(unsigned long util, unsigned long max) 10552 { 10553 u32 aggr_pct = llc_overaggr_pct; 10554 10555 /* 10556 * For single core systems, raise the aggregation 10557 * threshold to accommodate more tasks. 10558 */ 10559 if (cpu_smt_num_threads == 1) 10560 aggr_pct = (aggr_pct * 3 / 2); 10561 10562 return util * 100 < max * aggr_pct; 10563 } 10564 10565 /* 10566 * The margin used when comparing utilization. 10567 * is 'util1' noticeably greater than 'util2' 10568 * Derived from capacity_greater(). 10569 * Bias is in perentage. 10570 */ 10571 /* Allows dst util to be bigger than src util by up to bias percent */ 10572 #define util_greater(util1, util2) \ 10573 ((util1) * 100 > (util2) * (100 + llc_imb_pct)) 10574 10575 static __maybe_unused bool get_llc_stats(int cpu, unsigned long *util, 10576 unsigned long *cap) 10577 { 10578 struct sched_domain_shared *sd_share; 10579 10580 sd_share = rcu_dereference_all(per_cpu(sd_llc_shared, cpu)); 10581 if (!sd_share) 10582 return false; 10583 10584 *util = READ_ONCE(sd_share->util_avg); 10585 *cap = READ_ONCE(sd_share->capacity); 10586 10587 return true; 10588 } 10589 10590 /* 10591 * Decision matrix according to the LLC utilization. To 10592 * decide whether we can do task aggregation across LLC. 10593 * 10594 * By default, 50% is the threshold for treating the LLC 10595 * as busy. The reason for choosing 50% is to avoid saturation 10596 * of SMT-2, and it is also a safe cutoff for other SMT-n 10597 * platforms. SMT-1 has higher threshold because it is 10598 * supposed to accommodate more tasks, see fits_llc_capacity(). 10599 * 10600 * 20% is the utilization imbalance percentage to decide 10601 * if the preferred LLC is busier than the non-preferred LLC. 10602 * 20 is a little higher than the LLC domain's imbalance_pct 10603 * 17. The hysteresis is used to avoid task bouncing between the 10604 * preferred LLC and the non-preferred LLC, and it will 10605 * be turned into tunable debugfs. 10606 * 10607 * 1. moving towards the preferred LLC, dst is the preferred 10608 * LLC, src is not. 10609 * 10610 * src \ dst 30% 40% 50% 60% 10611 * 30% Y Y Y N 10612 * 40% Y Y Y Y 10613 * 50% Y Y G G 10614 * 60% Y Y G G 10615 * 10616 * 2. moving out of the preferred LLC, src is the preferred 10617 * LLC, dst is not: 10618 * 10619 * src \ dst 30% 40% 50% 60% 10620 * 30% N N N N 10621 * 40% N N N N 10622 * 50% N N G G 10623 * 60% Y N G G 10624 * 10625 * src : src_util 10626 * dst : dst_util 10627 * Y : Yes, migrate 10628 * N : No, do not migrate 10629 * G : let the Generic load balance to even the load. 10630 * 10631 * The intention is that if both LLCs are quite busy, cache aware 10632 * load balance should not be performed, and generic load balance 10633 * should take effect. However, if one is busy and the other is not, 10634 * the preferred LLC capacity(50%) and imbalance criteria(20%) should 10635 * be considered to determine whether LLC aggregation should be 10636 * performed to bias the load towards the preferred LLC. 10637 */ 10638 10639 /* migration decision, 3 states are orthogonal. */ 10640 enum llc_mig { 10641 mig_forbid = 0, /* N: Don't migrate task, respect LLC preference */ 10642 mig_llc, /* Y: Do LLC preference based migration */ 10643 mig_unrestricted /* G: Don't restrict generic load balance migration */ 10644 }; 10645 10646 /* 10647 * Check if task can be moved from the source LLC to the 10648 * destination LLC without breaking cache aware preferrence. 10649 * src_cpu and dst_cpu are arbitrary CPUs within the source 10650 * and destination LLCs, respectively. 10651 */ 10652 static enum llc_mig can_migrate_llc(int src_cpu, int dst_cpu, 10653 unsigned long tsk_util, 10654 bool to_pref) 10655 { 10656 unsigned long src_util, dst_util, src_cap, dst_cap; 10657 10658 if (!get_llc_stats(src_cpu, &src_util, &src_cap) || 10659 !get_llc_stats(dst_cpu, &dst_util, &dst_cap)) 10660 return mig_unrestricted; 10661 10662 src_util = src_util < tsk_util ? 0 : src_util - tsk_util; 10663 dst_util = dst_util + tsk_util; 10664 10665 if (!fits_llc_capacity(dst_util, dst_cap) && 10666 !fits_llc_capacity(src_util, src_cap)) 10667 return mig_unrestricted; 10668 10669 if (to_pref) { 10670 /* 10671 * Don't migrate if we will get preferred LLC too 10672 * heavily loaded and if the dest is much busier 10673 * than the src, in which case migration will 10674 * increase the imbalance too much. 10675 */ 10676 if (!fits_llc_capacity(dst_util, dst_cap) && 10677 util_greater(dst_util, src_util)) 10678 return mig_forbid; 10679 } else { 10680 /* 10681 * Don't migrate if we will leave preferred LLC 10682 * too idle, or if this migration leads to the 10683 * non-preferred LLC falls within sysctl_aggr_imb percent 10684 * of preferred LLC, leading to migration again 10685 * back to preferred LLC. 10686 */ 10687 if (fits_llc_capacity(src_util, src_cap) || 10688 !util_greater(src_util, dst_util)) 10689 return mig_forbid; 10690 } 10691 return mig_llc; 10692 } 10693 10694 /* 10695 * Check if task p can migrate from source LLC to 10696 * destination LLC in terms of cache aware load balance. 10697 */ 10698 static enum llc_mig can_migrate_llc_task(int src_cpu, int dst_cpu, 10699 struct task_struct *p) 10700 { 10701 struct mm_struct *mm; 10702 bool to_pref; 10703 int cpu; 10704 10705 mm = p->mm; 10706 if (!mm) 10707 return mig_unrestricted; 10708 10709 cpu = READ_ONCE(mm->sc_stat.cpu); 10710 if (cpu < 0 || cpus_share_cache(src_cpu, dst_cpu)) 10711 return mig_unrestricted; 10712 10713 /* skip cache aware load balance for too many threads */ 10714 if (invalid_llc_nr(mm, p, dst_cpu) || 10715 exceed_llc_capacity(mm, dst_cpu)) { 10716 if (READ_ONCE(mm->sc_stat.cpu) != -1) 10717 WRITE_ONCE(mm->sc_stat.cpu, -1); 10718 return mig_unrestricted; 10719 } 10720 10721 if (cpus_share_cache(dst_cpu, cpu)) 10722 to_pref = true; 10723 else if (cpus_share_cache(src_cpu, cpu)) 10724 to_pref = false; 10725 else 10726 return mig_unrestricted; 10727 10728 return can_migrate_llc(src_cpu, dst_cpu, 10729 task_util(p), to_pref); 10730 } 10731 10732 /* 10733 * Check if active load balance breaks LLC locality in 10734 * terms of cache aware load balance. The load level and 10735 * imbalance do not warrant breaking LLC preference per 10736 * the can_migrate_llc() policy. Here, the benefit of 10737 * LLC locality outweighs the power efficiency gained from 10738 * migrating the only runnable task away. 10739 */ 10740 static inline bool 10741 alb_break_llc(struct lb_env *env) 10742 { 10743 if (!sched_cache_enabled()) 10744 return false; 10745 10746 if (cpus_share_cache(env->src_cpu, env->dst_cpu)) 10747 return false; 10748 /* 10749 * All tasks prefer to stay on their current CPU. 10750 * Do not pull a task from its preferred CPU if: 10751 * 1. It is the only task running and does not exceed 10752 * imbalance allowance; OR 10753 * 2. Migrating it away from its preferred LLC would violate 10754 * the cache-aware scheduling policy. 10755 */ 10756 if (env->src_rq->nr_pref_llc_running && 10757 env->src_rq->nr_pref_llc_running == env->src_rq->cfs.h_nr_runnable) { 10758 unsigned long util = 0; 10759 struct task_struct *cur; 10760 10761 if (env->src_rq->nr_running <= 1) 10762 return true; 10763 10764 cur = rcu_dereference_all(env->src_rq->curr); 10765 if (cur && cur->sched_class == &fair_sched_class) 10766 util = task_util(cur); 10767 10768 if (can_migrate_llc(env->src_cpu, env->dst_cpu, 10769 util, false) == mig_forbid) 10770 return true; 10771 } 10772 10773 return false; 10774 } 10775 10776 /* 10777 * Check if migrating task p from env->src_cpu to 10778 * env->dst_cpu breaks LLC localiy. 10779 */ 10780 static bool migrate_degrades_llc(struct task_struct *p, struct lb_env *env) 10781 { 10782 if (!sched_cache_enabled()) 10783 return false; 10784 10785 if (task_has_sched_core(p)) 10786 return false; 10787 /* 10788 * Skip over tasks that would degrade LLC locality; 10789 * only when nr_balanced_failed is sufficiently high do we 10790 * ignore this constraint. 10791 * 10792 * Threshold of cache_nice_tries is set to 1 higher 10793 * than nr_balance_failed to avoid excessive task 10794 * migration at the same time. 10795 */ 10796 if (env->sd->nr_balance_failed >= env->sd->cache_nice_tries + 1) 10797 return false; 10798 10799 /* 10800 * We know the env->src_cpu has some tasks prefer to 10801 * run on env->dst_cpu, skip the tasks do not prefer 10802 * env->dst_cpu, and find the one that prefers. 10803 */ 10804 if (env->migration_type == migrate_llc_task && 10805 READ_ONCE(p->preferred_llc) != llc_id(env->dst_cpu)) 10806 return true; 10807 10808 if (can_migrate_llc_task(env->src_cpu, 10809 env->dst_cpu, p) != mig_forbid) 10810 return false; 10811 10812 return true; 10813 } 10814 10815 #else 10816 static inline bool get_llc_stats(int cpu, unsigned long *util, 10817 unsigned long *cap) 10818 { 10819 return false; 10820 } 10821 10822 static inline bool 10823 alb_break_llc(struct lb_env *env) 10824 { 10825 return false; 10826 } 10827 10828 static inline bool 10829 migrate_degrades_llc(struct task_struct *p, struct lb_env *env) 10830 { 10831 return false; 10832 } 10833 #endif 10834 /* 10835 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu? 10836 */ 10837 static 10838 int can_migrate_task(struct task_struct *p, struct lb_env *env) 10839 { 10840 long degrades, hot; 10841 10842 lockdep_assert_rq_held(env->src_rq); 10843 if (p->sched_task_hot) 10844 p->sched_task_hot = 0; 10845 10846 /* 10847 * We do not migrate tasks that are: 10848 * 1) delayed dequeued unless we migrate load, or 10849 * 2) target cfs_rq is in throttled hierarchy, or 10850 * 3) cannot be migrated to this CPU due to cpus_ptr, or 10851 * 4) running (obviously), or 10852 * 5) are cache-hot on their current CPU, or 10853 * 6) are blocked on mutexes (if SCHED_PROXY_EXEC is enabled) 10854 */ 10855 if ((p->se.sched_delayed) && (env->migration_type != migrate_load)) 10856 return 0; 10857 10858 if (lb_throttled_hierarchy(p, env->dst_cpu)) 10859 return 0; 10860 10861 /* 10862 * We want to prioritize the migration of eligible tasks. 10863 * For ineligible tasks we soft-limit them and only allow 10864 * them to migrate when nr_balance_failed is non-zero to 10865 * avoid load-balancing trying very hard to balance the load. 10866 */ 10867 if (!env->sd->nr_balance_failed && 10868 task_is_ineligible_on_dst_cpu(p, env->dst_cpu)) 10869 return 0; 10870 10871 /* Disregard percpu kthreads; they are where they need to be. */ 10872 if (kthread_is_per_cpu(p)) 10873 return 0; 10874 10875 if (task_is_blocked(p)) 10876 return 0; 10877 10878 if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) { 10879 int cpu; 10880 10881 schedstat_inc(p->stats.nr_failed_migrations_affine); 10882 10883 env->flags |= LBF_SOME_PINNED; 10884 10885 /* 10886 * Remember if this task can be migrated to any other CPU in 10887 * our sched_group. We may want to revisit it if we couldn't 10888 * meet load balance goals by pulling other tasks on src_cpu. 10889 * 10890 * Avoid computing new_dst_cpu 10891 * - for NEWLY_IDLE 10892 * - if we have already computed one in current iteration 10893 * - if it's an active balance 10894 */ 10895 if (env->idle == CPU_NEWLY_IDLE || 10896 env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB)) 10897 return 0; 10898 10899 /* Prevent to re-select dst_cpu via env's CPUs: */ 10900 cpu = cpumask_first_and_and(env->dst_grpmask, env->cpus, p->cpus_ptr); 10901 10902 if (cpu < nr_cpu_ids) { 10903 env->flags |= LBF_DST_PINNED; 10904 env->new_dst_cpu = cpu; 10905 } 10906 10907 return 0; 10908 } 10909 10910 /* Record that we found at least one task that could run on dst_cpu */ 10911 env->flags &= ~LBF_ALL_PINNED; 10912 10913 if (task_on_cpu(env->src_rq, p) || 10914 task_current_donor(env->src_rq, p)) { 10915 schedstat_inc(p->stats.nr_failed_migrations_running); 10916 return 0; 10917 } 10918 10919 /* 10920 * Aggressive migration if: 10921 * 1) active balance 10922 * 2) destination numa is preferred 10923 * 3) task is cache cold, or 10924 * 4) too many balance attempts have failed. 10925 */ 10926 if (env->flags & LBF_ACTIVE_LB) 10927 return 1; 10928 10929 degrades = migrate_degrades_locality(p, env); 10930 if (!degrades) { 10931 /* 10932 * If the NUMA locality is not broken, 10933 * further check if migration would hurt 10934 * LLC locality. 10935 */ 10936 if (migrate_degrades_llc(p, env)) { 10937 /* 10938 * If regular load balancing fails to pull a task 10939 * due to LLC locality, this is expected behavior 10940 * and we set LBF_LLC_PINNED so we don't increase 10941 * nr_balance_failed unecessarily. 10942 */ 10943 if (env->migration_type != migrate_llc_task) 10944 env->flags |= LBF_LLC_PINNED; 10945 10946 return 0; 10947 } 10948 10949 hot = task_hot(p, env); 10950 } else { 10951 hot = degrades > 0; 10952 } 10953 10954 if (!hot || env->sd->nr_balance_failed > env->sd->cache_nice_tries) { 10955 if (hot) 10956 p->sched_task_hot = 1; 10957 return 1; 10958 } 10959 10960 schedstat_inc(p->stats.nr_failed_migrations_hot); 10961 return 0; 10962 } 10963 10964 /* 10965 * detach_task() -- detach the task for the migration specified in env 10966 */ 10967 static void detach_task(struct task_struct *p, struct lb_env *env) 10968 { 10969 lockdep_assert_rq_held(env->src_rq); 10970 10971 if (p->sched_task_hot) { 10972 p->sched_task_hot = 0; 10973 schedstat_inc(env->sd->lb_hot_gained[env->idle]); 10974 schedstat_inc(p->stats.nr_forced_migrations); 10975 } 10976 10977 WARN_ON(task_current(env->src_rq, p)); 10978 WARN_ON(task_current_donor(env->src_rq, p)); 10979 10980 deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK); 10981 set_task_cpu(p, env->dst_cpu); 10982 } 10983 10984 /* 10985 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as 10986 * part of active balancing operations within "domain". 10987 * 10988 * Returns a task if successful and NULL otherwise. 10989 */ 10990 static struct task_struct *detach_one_task(struct lb_env *env) 10991 { 10992 struct task_struct *p; 10993 10994 lockdep_assert_rq_held(env->src_rq); 10995 10996 list_for_each_entry_reverse(p, 10997 &env->src_rq->cfs_tasks, se.group_node) { 10998 if (!can_migrate_task(p, env)) 10999 continue; 11000 11001 detach_task(p, env); 11002 11003 /* 11004 * Right now, this is only the second place where 11005 * lb_gained[env->idle] is updated (other is detach_tasks) 11006 * so we can safely collect stats here rather than 11007 * inside detach_tasks(). 11008 */ 11009 schedstat_inc(env->sd->lb_gained[env->idle]); 11010 return p; 11011 } 11012 return NULL; 11013 } 11014 11015 /* 11016 * detach_tasks() -- tries to detach up to imbalance load/util/tasks from 11017 * busiest_rq, as part of a balancing operation within domain "sd". 11018 * 11019 * Returns number of detached tasks if successful and 0 otherwise. 11020 */ 11021 static int detach_tasks(struct lb_env *env) 11022 { 11023 struct list_head *tasks = &env->src_rq->cfs_tasks; 11024 unsigned long util, load; 11025 struct task_struct *p; 11026 int detached = 0; 11027 11028 lockdep_assert_rq_held(env->src_rq); 11029 11030 /* 11031 * Source run queue has been emptied by another CPU, clear 11032 * LBF_ALL_PINNED flag as we will not test any task. 11033 */ 11034 if (env->src_rq->nr_running <= 1) { 11035 env->flags &= ~LBF_ALL_PINNED; 11036 return 0; 11037 } 11038 11039 if (env->imbalance <= 0) 11040 return 0; 11041 11042 while (!list_empty(tasks)) { 11043 /* 11044 * We don't want to steal all, otherwise we may be treated likewise, 11045 * which could at worst lead to a livelock crash. 11046 */ 11047 if (env->idle && env->src_rq->nr_running <= 1) 11048 break; 11049 11050 env->loop++; 11051 /* We've more or less seen every task there is, call it quits */ 11052 if (env->loop > env->loop_max) 11053 break; 11054 11055 /* take a breather every nr_migrate tasks */ 11056 if (env->loop > env->loop_break) { 11057 env->loop_break += SCHED_NR_MIGRATE_BREAK; 11058 env->flags |= LBF_NEED_BREAK; 11059 break; 11060 } 11061 11062 p = list_last_entry(tasks, struct task_struct, se.group_node); 11063 11064 if (!can_migrate_task(p, env)) 11065 goto next; 11066 11067 switch (env->migration_type) { 11068 case migrate_load: 11069 /* 11070 * Depending of the number of CPUs and tasks and the 11071 * cgroup hierarchy, task_h_load() can return a null 11072 * value. Make sure that env->imbalance decreases 11073 * otherwise detach_tasks() will stop only after 11074 * detaching up to loop_max tasks. 11075 */ 11076 load = max_t(unsigned long, task_h_load(p), 1); 11077 11078 if (sched_feat(LB_MIN) && 11079 load < 16 && !env->sd->nr_balance_failed) 11080 goto next; 11081 11082 /* 11083 * Make sure that we don't migrate too much load. 11084 * Nevertheless, let relax the constraint if 11085 * scheduler fails to find a good waiting task to 11086 * migrate. 11087 */ 11088 if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance) 11089 goto next; 11090 11091 env->imbalance -= load; 11092 break; 11093 11094 case migrate_util: 11095 util = task_util_est(p); 11096 11097 if (shr_bound(util, env->sd->nr_balance_failed) > env->imbalance) 11098 goto next; 11099 11100 env->imbalance -= util; 11101 break; 11102 11103 case migrate_task: 11104 env->imbalance--; 11105 break; 11106 11107 case migrate_misfit: 11108 /* This is not a misfit task */ 11109 if (task_fits_cpu(p, env->src_cpu)) 11110 goto next; 11111 11112 env->imbalance = 0; 11113 break; 11114 11115 case migrate_llc_task: 11116 env->imbalance--; 11117 break; 11118 } 11119 11120 detach_task(p, env); 11121 list_add(&p->se.group_node, &env->tasks); 11122 11123 detached++; 11124 11125 #ifdef CONFIG_PREEMPTION 11126 /* 11127 * NEWIDLE balancing is a source of latency, so preemptible 11128 * kernels will stop after the first task is detached to minimize 11129 * the critical section. 11130 */ 11131 if (env->idle == CPU_NEWLY_IDLE) 11132 break; 11133 #endif 11134 11135 /* 11136 * We only want to steal up to the prescribed amount of 11137 * load/util/tasks. 11138 */ 11139 if (env->imbalance <= 0) 11140 break; 11141 11142 continue; 11143 next: 11144 if (p->sched_task_hot) 11145 schedstat_inc(p->stats.nr_failed_migrations_hot); 11146 11147 list_move(&p->se.group_node, tasks); 11148 } 11149 11150 /* 11151 * Right now, this is one of only two places we collect this stat 11152 * so we can safely collect detach_one_task() stats here rather 11153 * than inside detach_one_task(). 11154 */ 11155 schedstat_add(env->sd->lb_gained[env->idle], detached); 11156 11157 return detached; 11158 } 11159 11160 /* 11161 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their 11162 * new rq. 11163 */ 11164 static void attach_tasks(struct lb_env *env) 11165 { 11166 struct list_head *tasks = &env->tasks; 11167 struct task_struct *p; 11168 struct rq_flags rf; 11169 11170 rq_lock(env->dst_rq, &rf); 11171 update_rq_clock(env->dst_rq); 11172 11173 while (!list_empty(tasks)) { 11174 p = list_first_entry(tasks, struct task_struct, se.group_node); 11175 list_del_init(&p->se.group_node); 11176 11177 attach_task(env->dst_rq, p); 11178 } 11179 11180 rq_unlock(env->dst_rq, &rf); 11181 } 11182 11183 #ifdef CONFIG_NO_HZ_COMMON 11184 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq) 11185 { 11186 if (cfs_rq->avg.load_avg) 11187 return true; 11188 11189 if (cfs_rq->avg.util_avg) 11190 return true; 11191 11192 return false; 11193 } 11194 11195 static inline bool others_have_blocked(struct rq *rq) 11196 { 11197 if (cpu_util_rt(rq)) 11198 return true; 11199 11200 if (cpu_util_dl(rq)) 11201 return true; 11202 11203 if (hw_load_avg(rq)) 11204 return true; 11205 11206 if (cpu_util_irq(rq)) 11207 return true; 11208 11209 return false; 11210 } 11211 11212 static inline void update_blocked_load_tick(struct rq *rq) 11213 { 11214 WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies); 11215 } 11216 11217 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load) 11218 { 11219 if (!has_blocked_load) 11220 rq->has_blocked_load = 0; 11221 } 11222 #else /* !CONFIG_NO_HZ_COMMON: */ 11223 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq) { return false; } 11224 static inline bool others_have_blocked(struct rq *rq) { return false; } 11225 static inline void update_blocked_load_tick(struct rq *rq) {} 11226 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load) {} 11227 #endif /* !CONFIG_NO_HZ_COMMON */ 11228 11229 static bool __update_blocked_others(struct rq *rq, bool *done) 11230 { 11231 bool updated; 11232 11233 /* 11234 * update_load_avg() can call cpufreq_update_util(). Make sure that RT, 11235 * DL and IRQ signals have been updated before updating CFS. 11236 */ 11237 updated = update_other_load_avgs(rq); 11238 11239 if (others_have_blocked(rq)) 11240 *done = false; 11241 11242 return updated; 11243 } 11244 11245 #ifdef CONFIG_FAIR_GROUP_SCHED 11246 11247 static bool __update_blocked_fair(struct rq *rq, bool *done) 11248 { 11249 struct cfs_rq *cfs_rq, *pos; 11250 bool decayed = false; 11251 11252 /* 11253 * Iterates the task_group tree in a bottom up fashion, see 11254 * list_add_leaf_cfs_rq() for details. 11255 */ 11256 for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) { 11257 struct sched_entity *se; 11258 11259 if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) { 11260 update_tg_load_avg(cfs_rq); 11261 11262 if (cfs_rq->nr_queued == 0) 11263 update_idle_cfs_rq_clock_pelt(cfs_rq); 11264 11265 if (cfs_rq == &rq->cfs) 11266 decayed = true; 11267 } 11268 11269 /* Propagate pending load changes to the parent, if any: */ 11270 se = cfs_rq_se(cfs_rq); 11271 if (se && !skip_blocked_update(se)) 11272 update_load_avg(cfs_rq_of(se), se, UPDATE_TG); 11273 11274 /* 11275 * There can be a lot of idle CPU cgroups. Don't let fully 11276 * decayed cfs_rqs linger on the list. 11277 */ 11278 if (cfs_rq_is_decayed(cfs_rq)) 11279 list_del_leaf_cfs_rq(cfs_rq); 11280 11281 /* Don't need periodic decay once load/util_avg are null */ 11282 if (cfs_rq_has_blocked_load(cfs_rq)) 11283 *done = false; 11284 } 11285 11286 return decayed; 11287 } 11288 11289 /* 11290 * Compute the hierarchical load factor for cfs_rq and all its ascendants. 11291 * This needs to be done in a top-down fashion because the load of a child 11292 * group is a fraction of its parents load. 11293 */ 11294 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq) 11295 { 11296 struct sched_entity *se = cfs_rq_se(cfs_rq); 11297 unsigned long now = jiffies; 11298 unsigned long load; 11299 11300 if (cfs_rq->last_h_load_update == now) 11301 return; 11302 11303 WRITE_ONCE(cfs_rq->h_load_next, NULL); 11304 for_each_sched_entity(se) { 11305 cfs_rq = cfs_rq_of(se); 11306 WRITE_ONCE(cfs_rq->h_load_next, se); 11307 if (cfs_rq->last_h_load_update == now) 11308 break; 11309 } 11310 11311 if (!se) { 11312 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq); 11313 cfs_rq->last_h_load_update = now; 11314 } 11315 11316 while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) { 11317 load = cfs_rq->h_load; 11318 load = div64_ul(load * se->avg.load_avg, 11319 cfs_rq_load_avg(cfs_rq) + 1); 11320 cfs_rq = group_cfs_rq(se); 11321 cfs_rq->h_load = load; 11322 cfs_rq->last_h_load_update = now; 11323 } 11324 } 11325 11326 static unsigned long task_h_load(struct task_struct *p) 11327 { 11328 struct cfs_rq *cfs_rq = task_cfs_rq(p); 11329 11330 update_cfs_rq_h_load(cfs_rq); 11331 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load, 11332 cfs_rq_load_avg(cfs_rq) + 1); 11333 } 11334 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 11335 static bool __update_blocked_fair(struct rq *rq, bool *done) 11336 { 11337 struct cfs_rq *cfs_rq = &rq->cfs; 11338 bool decayed; 11339 11340 decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq); 11341 if (cfs_rq_has_blocked_load(cfs_rq)) 11342 *done = false; 11343 11344 return decayed; 11345 } 11346 11347 static unsigned long task_h_load(struct task_struct *p) 11348 { 11349 return p->se.avg.load_avg; 11350 } 11351 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 11352 11353 static void __sched_balance_update_blocked_averages(struct rq *rq) 11354 { 11355 bool decayed = false, done = true; 11356 11357 update_blocked_load_tick(rq); 11358 11359 decayed |= __update_blocked_others(rq, &done); 11360 decayed |= __update_blocked_fair(rq, &done); 11361 11362 update_has_blocked_load_status(rq, !done); 11363 if (decayed) 11364 cpufreq_update_util(rq, 0); 11365 } 11366 11367 static void sched_balance_update_blocked_averages(int cpu) 11368 { 11369 struct rq *rq = cpu_rq(cpu); 11370 11371 guard(rq_lock_irqsave)(rq); 11372 update_rq_clock(rq); 11373 __sched_balance_update_blocked_averages(rq); 11374 } 11375 11376 /********** Helpers for sched_balance_find_src_group ************************/ 11377 11378 /* 11379 * sg_lb_stats - stats of a sched_group required for load-balancing: 11380 */ 11381 struct sg_lb_stats { 11382 unsigned long avg_load; /* Avg load over the CPUs of the group */ 11383 unsigned long group_load; /* Total load over the CPUs of the group */ 11384 unsigned long group_capacity; /* Capacity over the CPUs of the group */ 11385 unsigned long group_util; /* Total utilization over the CPUs of the group */ 11386 unsigned long group_runnable; /* Total runnable time over the CPUs of the group */ 11387 unsigned int sum_nr_running; /* Nr of all tasks running in the group */ 11388 unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */ 11389 unsigned int idle_cpus; /* Nr of idle CPUs in the group */ 11390 unsigned int group_weight; 11391 enum group_type group_type; 11392 unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */ 11393 unsigned int group_smt_balance; /* Task on busy SMT be moved */ 11394 unsigned int group_llc_balance; /* Tasks should be moved to preferred LLC */ 11395 unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */ 11396 unsigned int group_overutilized; /* At least one CPU is overutilized in the group */ 11397 #ifdef CONFIG_NUMA_BALANCING 11398 unsigned int nr_numa_running; 11399 unsigned int nr_preferred_running; 11400 #endif 11401 #ifdef CONFIG_SCHED_CACHE 11402 unsigned int nr_pref_dst_llc; 11403 #endif 11404 }; 11405 11406 /* 11407 * sd_lb_stats - stats of a sched_domain required for load-balancing: 11408 */ 11409 struct sd_lb_stats { 11410 struct sched_group *busiest; /* Busiest group in this sd */ 11411 struct sched_group *local; /* Local group in this sd */ 11412 unsigned long total_load; /* Total load of all groups in sd */ 11413 unsigned long total_capacity; /* Total capacity of all groups in sd */ 11414 unsigned long avg_load; /* Average load across all groups in sd */ 11415 unsigned int prefer_sibling; /* Tasks should go to sibling first */ 11416 11417 struct sg_lb_stats busiest_stat; /* Statistics of the busiest group */ 11418 struct sg_lb_stats local_stat; /* Statistics of the local group */ 11419 }; 11420 11421 static inline void init_sd_lb_stats(struct sd_lb_stats *sds) 11422 { 11423 /* 11424 * Skimp on the clearing to avoid duplicate work. We can avoid clearing 11425 * local_stat because update_sg_lb_stats() does a full clear/assignment. 11426 * We must however set busiest_stat::group_type and 11427 * busiest_stat::idle_cpus to the worst busiest group because 11428 * update_sd_pick_busiest() reads these before assignment. 11429 */ 11430 *sds = (struct sd_lb_stats){ 11431 .busiest = NULL, 11432 .local = NULL, 11433 .total_load = 0UL, 11434 .total_capacity = 0UL, 11435 .busiest_stat = { 11436 .idle_cpus = UINT_MAX, 11437 .group_type = group_has_spare, 11438 }, 11439 }; 11440 } 11441 11442 static unsigned long scale_rt_capacity(int cpu) 11443 { 11444 unsigned long max = get_actual_cpu_capacity(cpu); 11445 struct rq *rq = cpu_rq(cpu); 11446 unsigned long used, free; 11447 unsigned long irq; 11448 11449 irq = cpu_util_irq(rq); 11450 11451 if (unlikely(irq >= max)) 11452 return 1; 11453 11454 /* 11455 * avg_rt.util_avg and avg_dl.util_avg track binary signals 11456 * (running and not running) with weights 0 and 1024 respectively. 11457 */ 11458 used = cpu_util_rt(rq); 11459 used += cpu_util_dl(rq); 11460 11461 if (unlikely(used >= max)) 11462 return 1; 11463 11464 free = max - used; 11465 11466 return scale_irq_capacity(free, irq, max); 11467 } 11468 11469 static void update_cpu_capacity(struct sched_domain *sd, int cpu) 11470 { 11471 unsigned long capacity = scale_rt_capacity(cpu); 11472 struct sched_group *sdg = sd->groups; 11473 11474 if (!capacity) 11475 capacity = 1; 11476 11477 cpu_rq(cpu)->cpu_capacity = capacity; 11478 trace_sched_cpu_capacity_tp(cpu_rq(cpu)); 11479 11480 sdg->sgc->capacity = capacity; 11481 sdg->sgc->min_capacity = capacity; 11482 sdg->sgc->max_capacity = capacity; 11483 } 11484 11485 void update_group_capacity(struct sched_domain *sd, int cpu) 11486 { 11487 struct sched_domain *child = sd->child; 11488 struct sched_group *group, *sdg = sd->groups; 11489 unsigned long capacity, min_capacity, max_capacity; 11490 unsigned long interval; 11491 11492 interval = msecs_to_jiffies(sd->balance_interval); 11493 interval = clamp(interval, 1UL, max_load_balance_interval); 11494 sdg->sgc->next_update = jiffies + interval; 11495 11496 if (!child) { 11497 update_cpu_capacity(sd, cpu); 11498 return; 11499 } 11500 11501 capacity = 0; 11502 min_capacity = ULONG_MAX; 11503 max_capacity = 0; 11504 11505 if (child->flags & SD_NUMA) { 11506 /* 11507 * SD_NUMA domains cannot assume that child groups 11508 * span the current group. 11509 */ 11510 11511 for_each_cpu(cpu, sched_group_span(sdg)) { 11512 unsigned long cpu_cap = capacity_of(cpu); 11513 11514 capacity += cpu_cap; 11515 min_capacity = min(cpu_cap, min_capacity); 11516 max_capacity = max(cpu_cap, max_capacity); 11517 } 11518 } else { 11519 /* 11520 * !SD_NUMA domains can assume that child groups 11521 * span the current group. 11522 */ 11523 11524 group = child->groups; 11525 do { 11526 struct sched_group_capacity *sgc = group->sgc; 11527 11528 capacity += sgc->capacity; 11529 min_capacity = min(sgc->min_capacity, min_capacity); 11530 max_capacity = max(sgc->max_capacity, max_capacity); 11531 group = group->next; 11532 } while (group != child->groups); 11533 } 11534 11535 sdg->sgc->capacity = capacity; 11536 sdg->sgc->min_capacity = min_capacity; 11537 sdg->sgc->max_capacity = max_capacity; 11538 } 11539 11540 /* 11541 * Check whether the capacity of the rq has been noticeably reduced by side 11542 * activity. The imbalance_pct is used for the threshold. 11543 * Return true is the capacity is reduced 11544 */ 11545 static inline int 11546 check_cpu_capacity(struct rq *rq, struct sched_domain *sd) 11547 { 11548 return ((rq->cpu_capacity * sd->imbalance_pct) < 11549 (arch_scale_cpu_capacity(cpu_of(rq)) * 100)); 11550 } 11551 11552 /* Check if the rq has a misfit task */ 11553 static inline bool check_misfit_status(struct rq *rq) 11554 { 11555 return rq->misfit_task_load; 11556 } 11557 11558 /* 11559 * Group imbalance indicates (and tries to solve) the problem where balancing 11560 * groups is inadequate due to ->cpus_ptr constraints. 11561 * 11562 * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a 11563 * cpumask covering 1 CPU of the first group and 3 CPUs of the second group. 11564 * Something like: 11565 * 11566 * { 0 1 2 3 } { 4 5 6 7 } 11567 * * * * * 11568 * 11569 * If we were to balance group-wise we'd place two tasks in the first group and 11570 * two tasks in the second group. Clearly this is undesired as it will overload 11571 * cpu 3 and leave one of the CPUs in the second group unused. 11572 * 11573 * The current solution to this issue is detecting the skew in the first group 11574 * by noticing the lower domain failed to reach balance and had difficulty 11575 * moving tasks due to affinity constraints. 11576 * 11577 * When this is so detected; this group becomes a candidate for busiest; see 11578 * update_sd_pick_busiest(). And calculate_imbalance() and 11579 * sched_balance_find_src_group() avoid some of the usual balance conditions to allow it 11580 * to create an effective group imbalance. 11581 * 11582 * This is a somewhat tricky proposition since the next run might not find the 11583 * group imbalance and decide the groups need to be balanced again. A most 11584 * subtle and fragile situation. 11585 */ 11586 11587 static inline int sg_imbalanced(struct sched_group *group) 11588 { 11589 return group->sgc->imbalance; 11590 } 11591 11592 /* 11593 * group_has_capacity returns true if the group has spare capacity that could 11594 * be used by some tasks. 11595 * We consider that a group has spare capacity if the number of task is 11596 * smaller than the number of CPUs or if the utilization is lower than the 11597 * available capacity for CFS tasks. 11598 * For the latter, we use a threshold to stabilize the state, to take into 11599 * account the variance of the tasks' load and to return true if the available 11600 * capacity in meaningful for the load balancer. 11601 * As an example, an available capacity of 1% can appear but it doesn't make 11602 * any benefit for the load balance. 11603 */ 11604 static inline bool 11605 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs) 11606 { 11607 if (sgs->sum_nr_running < sgs->group_weight) 11608 return true; 11609 11610 if ((sgs->group_capacity * imbalance_pct) < 11611 (sgs->group_runnable * 100)) 11612 return false; 11613 11614 if ((sgs->group_capacity * 100) > 11615 (sgs->group_util * imbalance_pct)) 11616 return true; 11617 11618 return false; 11619 } 11620 11621 /* 11622 * group_is_overloaded returns true if the group has more tasks than it can 11623 * handle. 11624 * group_is_overloaded is not equals to !group_has_capacity because a group 11625 * with the exact right number of tasks, has no more spare capacity but is not 11626 * overloaded so both group_has_capacity and group_is_overloaded return 11627 * false. 11628 */ 11629 static inline bool 11630 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs) 11631 { 11632 /* 11633 * With EAS and uclamp, 1 CPU in the group must be overutilized to 11634 * consider the group overloaded. 11635 */ 11636 if (sched_energy_enabled() && !sgs->group_overutilized) 11637 return false; 11638 11639 if (sgs->sum_nr_running <= sgs->group_weight) 11640 return false; 11641 11642 if ((sgs->group_capacity * 100) < 11643 (sgs->group_util * imbalance_pct)) 11644 return true; 11645 11646 if ((sgs->group_capacity * imbalance_pct) < 11647 (sgs->group_runnable * 100)) 11648 return true; 11649 11650 return false; 11651 } 11652 11653 static inline enum 11654 group_type group_classify(unsigned int imbalance_pct, 11655 struct sched_group *group, 11656 struct sg_lb_stats *sgs) 11657 { 11658 if (group_is_overloaded(imbalance_pct, sgs)) 11659 return group_overloaded; 11660 11661 if (sgs->group_llc_balance) 11662 return group_llc_balance; 11663 11664 if (sg_imbalanced(group)) 11665 return group_imbalanced; 11666 11667 if (sgs->group_asym_packing) 11668 return group_asym_packing; 11669 11670 if (sgs->group_smt_balance) 11671 return group_smt_balance; 11672 11673 if (sgs->group_misfit_task_load) 11674 return group_misfit_task; 11675 11676 if (!group_has_capacity(imbalance_pct, sgs)) 11677 return group_fully_busy; 11678 11679 return group_has_spare; 11680 } 11681 11682 /** 11683 * sched_use_asym_prio - Check whether asym_packing priority must be used 11684 * @sd: The scheduling domain of the load balancing 11685 * @cpu: A CPU 11686 * 11687 * Always use CPU priority when balancing load between SMT siblings. When 11688 * balancing load between cores, it is not sufficient that @cpu is idle. Only 11689 * use CPU priority if the whole core is idle. 11690 * 11691 * Returns: True if the priority of @cpu must be followed. False otherwise. 11692 */ 11693 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu) 11694 { 11695 if (!(sd->flags & SD_ASYM_PACKING)) 11696 return false; 11697 11698 if (!sched_smt_active()) 11699 return true; 11700 11701 return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu); 11702 } 11703 11704 static inline bool sched_asym(struct sched_domain *sd, int dst_cpu, int src_cpu) 11705 { 11706 /* 11707 * First check if @dst_cpu can do asym_packing load balance. Only do it 11708 * if it has higher priority than @src_cpu. 11709 */ 11710 return sched_use_asym_prio(sd, dst_cpu) && 11711 sched_asym_prefer(dst_cpu, src_cpu); 11712 } 11713 11714 /** 11715 * sched_group_asym - Check if the destination CPU can do asym_packing balance 11716 * @env: The load balancing environment 11717 * @sgs: Load-balancing statistics of the candidate busiest group 11718 * @group: The candidate busiest group 11719 * 11720 * @env::dst_cpu can do asym_packing if it has higher priority than the 11721 * preferred CPU of @group. 11722 * 11723 * Return: true if @env::dst_cpu can do with asym_packing load balance. False 11724 * otherwise. 11725 */ 11726 static inline bool 11727 sched_group_asym(struct lb_env *env, struct sg_lb_stats *sgs, struct sched_group *group) 11728 { 11729 /* 11730 * CPU priorities do not make sense for SMT cores with more than one 11731 * busy sibling. 11732 */ 11733 if ((group->flags & SD_SHARE_CPUCAPACITY) && 11734 (sgs->group_weight - sgs->idle_cpus != 1)) 11735 return false; 11736 11737 return sched_asym(env->sd, env->dst_cpu, READ_ONCE(group->asym_prefer_cpu)); 11738 } 11739 11740 /* One group has more than one SMT CPU while the other group does not */ 11741 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1, 11742 struct sched_group *sg2) 11743 { 11744 if (!sg1 || !sg2) 11745 return false; 11746 11747 return (sg1->flags & SD_SHARE_CPUCAPACITY) != 11748 (sg2->flags & SD_SHARE_CPUCAPACITY); 11749 } 11750 11751 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs, 11752 struct sched_group *group) 11753 { 11754 if (!env->idle) 11755 return false; 11756 11757 /* 11758 * For SMT source group, it is better to move a task 11759 * to a CPU that doesn't have multiple tasks sharing its CPU capacity. 11760 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY 11761 * will not be on. 11762 */ 11763 if (group->flags & SD_SHARE_CPUCAPACITY && 11764 sgs->sum_h_nr_running > 1) 11765 return true; 11766 11767 return false; 11768 } 11769 11770 static inline long sibling_imbalance(struct lb_env *env, 11771 struct sd_lb_stats *sds, 11772 struct sg_lb_stats *busiest, 11773 struct sg_lb_stats *local) 11774 { 11775 int ncores_busiest, ncores_local; 11776 long imbalance; 11777 11778 if (!env->idle || !busiest->sum_nr_running) 11779 return 0; 11780 11781 ncores_busiest = sds->busiest->cores; 11782 ncores_local = sds->local->cores; 11783 11784 if (ncores_busiest == ncores_local) { 11785 imbalance = busiest->sum_nr_running; 11786 lsub_positive(&imbalance, local->sum_nr_running); 11787 return imbalance; 11788 } 11789 11790 /* Balance such that nr_running/ncores ratio are same on both groups */ 11791 imbalance = ncores_local * busiest->sum_nr_running; 11792 lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running); 11793 /* Normalize imbalance and do rounding on normalization */ 11794 imbalance = 2 * imbalance + ncores_local + ncores_busiest; 11795 imbalance /= ncores_local + ncores_busiest; 11796 11797 /* Take advantage of resource in an empty sched group */ 11798 if (imbalance <= 1 && local->sum_nr_running == 0 && 11799 busiest->sum_nr_running > 1) 11800 imbalance = 2; 11801 11802 return imbalance; 11803 } 11804 11805 static inline bool 11806 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd) 11807 { 11808 /* 11809 * When there is more than 1 task, the group_overloaded case already 11810 * takes care of cpu with reduced capacity 11811 */ 11812 if (rq->cfs.h_nr_runnable != 1) 11813 return false; 11814 11815 return check_cpu_capacity(rq, sd); 11816 } 11817 11818 #ifdef CONFIG_SCHED_CACHE 11819 /* 11820 * Record the statistics for this scheduler group for later 11821 * use. These values guide load balancing on aggregating tasks 11822 * to a LLC. 11823 */ 11824 static void record_sg_llc_stats(struct lb_env *env, 11825 struct sg_lb_stats *sgs, 11826 struct sched_group *group) 11827 { 11828 struct sched_domain_shared *sd_share; 11829 int cpu; 11830 11831 if (!sched_cache_enabled() || env->idle == CPU_NEWLY_IDLE) 11832 return; 11833 11834 /* Only care about sched domain spanning multiple LLCs */ 11835 if (env->sd->child != rcu_dereference_all(per_cpu(sd_llc, env->dst_cpu))) 11836 return; 11837 11838 /* 11839 * At this point we know this group spans a LLC domain. 11840 * Record the statistic of this group in its corresponding 11841 * shared LLC domain. 11842 * Note: sd_share cannot be obtained via sd->child->shared, 11843 * because the latter refers to the domain that covers the 11844 * local group. Instead, sd_share should be located using 11845 * the first CPU of the LLC group. 11846 */ 11847 cpu = cpumask_first(sched_group_span(group)); 11848 sd_share = rcu_dereference_all(per_cpu(sd_llc_shared, cpu)); 11849 if (!sd_share) 11850 return; 11851 11852 if (READ_ONCE(sd_share->util_avg) != sgs->group_util) 11853 WRITE_ONCE(sd_share->util_avg, sgs->group_util); 11854 11855 if (unlikely(READ_ONCE(sd_share->capacity) != sgs->group_capacity)) 11856 WRITE_ONCE(sd_share->capacity, sgs->group_capacity); 11857 } 11858 11859 /* 11860 * Do LLC balance on sched group that contains LLC, and have tasks preferring 11861 * to run on LLC in idle dst_cpu. 11862 */ 11863 static inline bool llc_balance(struct lb_env *env, struct sg_lb_stats *sgs, 11864 struct sched_group *group) 11865 { 11866 if (!sched_cache_enabled()) 11867 return false; 11868 11869 if (env->sd->flags & SD_SHARE_LLC) 11870 return false; 11871 11872 /* 11873 * Skip cache aware tagging if nr_balanced_failed is sufficiently high. 11874 * Threshold of cache_nice_tries is set to 1 higher than nr_balance_failed 11875 * to avoid excessive task migration at the same time. 11876 */ 11877 if (env->sd->nr_balance_failed >= env->sd->cache_nice_tries + 1) 11878 return false; 11879 11880 if (sgs->nr_pref_dst_llc && 11881 can_migrate_llc(cpumask_first(sched_group_span(group)), 11882 env->dst_cpu, 0, true) == mig_llc) 11883 return true; 11884 11885 return false; 11886 } 11887 11888 static bool update_llc_busiest(struct lb_env *env, 11889 struct sg_lb_stats *busiest, 11890 struct sg_lb_stats *sgs) 11891 { 11892 /* 11893 * There are more tasks that want to run on dst_cpu's LLC. 11894 */ 11895 return sgs->nr_pref_dst_llc > busiest->nr_pref_dst_llc; 11896 } 11897 #else 11898 static inline void record_sg_llc_stats(struct lb_env *env, struct sg_lb_stats *sgs, 11899 struct sched_group *group) 11900 { 11901 } 11902 11903 static inline bool llc_balance(struct lb_env *env, struct sg_lb_stats *sgs, 11904 struct sched_group *group) 11905 { 11906 return false; 11907 } 11908 11909 static bool update_llc_busiest(struct lb_env *env, 11910 struct sg_lb_stats *busiest, 11911 struct sg_lb_stats *sgs) 11912 { 11913 return false; 11914 } 11915 #endif 11916 11917 /** 11918 * update_sg_lb_stats - Update sched_group's statistics for load balancing. 11919 * @env: The load balancing environment. 11920 * @sds: Load-balancing data with statistics of the local group. 11921 * @group: sched_group whose statistics are to be updated. 11922 * @sgs: variable to hold the statistics for this group. 11923 * @sg_overloaded: sched_group is overloaded 11924 */ 11925 static inline void update_sg_lb_stats(struct lb_env *env, 11926 struct sd_lb_stats *sds, 11927 struct sched_group *group, 11928 struct sg_lb_stats *sgs, 11929 bool *sg_overloaded) 11930 { 11931 int i, nr_running, local_group, sd_flags = env->sd->flags; 11932 bool balancing_at_rd = !env->sd->parent; 11933 11934 memset(sgs, 0, sizeof(*sgs)); 11935 11936 local_group = group == sds->local; 11937 11938 for_each_cpu_and(i, sched_group_span(group), env->cpus) { 11939 struct rq *rq = cpu_rq(i); 11940 unsigned long load = cpu_load(rq); 11941 11942 sgs->group_load += load; 11943 sgs->group_util += cpu_util_cfs(i); 11944 sgs->group_runnable += cpu_runnable(rq); 11945 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable; 11946 11947 nr_running = rq->nr_running; 11948 sgs->sum_nr_running += nr_running; 11949 11950 if (cpu_overutilized(i)) 11951 sgs->group_overutilized = 1; 11952 11953 #ifdef CONFIG_SCHED_CACHE 11954 if (sched_cache_enabled()) { 11955 struct sched_domain *sd_tmp; 11956 int dst_llc; 11957 11958 dst_llc = llc_id(env->dst_cpu); 11959 if (llc_id(i) != dst_llc) { 11960 sd_tmp = rcu_dereference_all(rq->sd); 11961 if (sd_tmp && (unsigned int)dst_llc < sd_tmp->llc_max) 11962 sgs->nr_pref_dst_llc += sd_tmp->llc_counts[dst_llc]; 11963 } 11964 } 11965 #endif 11966 11967 /* 11968 * No need to call idle_cpu() if nr_running is not 0 11969 */ 11970 if (!nr_running && idle_cpu(i)) { 11971 sgs->idle_cpus++; 11972 /* Idle cpu can't have misfit task */ 11973 continue; 11974 } 11975 11976 /* Overload indicator is only updated at root domain */ 11977 if (balancing_at_rd && nr_running > 1) 11978 *sg_overloaded = 1; 11979 11980 #ifdef CONFIG_NUMA_BALANCING 11981 /* Only fbq_classify_group() uses this to classify NUMA groups */ 11982 if (sd_flags & SD_NUMA) { 11983 sgs->nr_numa_running += rq->nr_numa_running; 11984 sgs->nr_preferred_running += rq->nr_preferred_running; 11985 } 11986 #endif 11987 if (local_group) 11988 continue; 11989 11990 if (sd_flags & SD_ASYM_CPUCAPACITY) { 11991 if (rq->misfit_task_load) { 11992 /* 11993 * Always mark the root domain overloaded so big 11994 * CPUs can pick up misfit tasks via newly idle 11995 * balance. 11996 */ 11997 if (balancing_at_rd) 11998 *sg_overloaded = 1; 11999 12000 /* 12001 * Only account misfit load if @dst_cpu can 12002 * help; otherwise, the group may be classified 12003 * as misfit_task and update_sd_pick_busiest() 12004 * will skip it. 12005 */ 12006 if (capacity_greater(capacity_of(env->dst_cpu), 12007 group->sgc->max_capacity) && 12008 (sgs->group_misfit_task_load < rq->misfit_task_load)) 12009 sgs->group_misfit_task_load = rq->misfit_task_load; 12010 } 12011 } else if (env->idle && sched_reduced_capacity(rq, env->sd)) { 12012 /* Check for a task running on a CPU with reduced capacity */ 12013 if (sgs->group_misfit_task_load < load) 12014 sgs->group_misfit_task_load = load; 12015 } 12016 } 12017 12018 sgs->group_capacity = group->sgc->capacity; 12019 12020 sgs->group_weight = group->group_weight; 12021 12022 if (!local_group) { 12023 /* Check if dst CPU is idle and preferred to this group */ 12024 if (env->idle && sgs->sum_h_nr_running && 12025 sched_group_asym(env, sgs, group)) 12026 sgs->group_asym_packing = 1; 12027 12028 /* Check for loaded SMT group to be balanced to dst CPU */ 12029 if (smt_balance(env, sgs, group)) 12030 sgs->group_smt_balance = 1; 12031 12032 /* Check for tasks in this group can be moved to their preferred LLC */ 12033 if (llc_balance(env, sgs, group)) 12034 sgs->group_llc_balance = 1; 12035 } 12036 12037 sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs); 12038 12039 record_sg_llc_stats(env, sgs, group); 12040 /* Computing avg_load makes sense only when group is overloaded */ 12041 if (sgs->group_type == group_overloaded) 12042 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) / 12043 sgs->group_capacity; 12044 } 12045 12046 /** 12047 * update_sd_pick_busiest - return 1 on busiest group 12048 * @env: The load balancing environment. 12049 * @sds: sched_domain statistics 12050 * @sg: sched_group candidate to be checked for being the busiest 12051 * @sgs: sched_group statistics 12052 * 12053 * Determine if @sg is a busier group than the previously selected 12054 * busiest group. 12055 * 12056 * Return: %true if @sg is a busier group than the previously selected 12057 * busiest group. %false otherwise. 12058 */ 12059 static bool update_sd_pick_busiest(struct lb_env *env, 12060 struct sd_lb_stats *sds, 12061 struct sched_group *sg, 12062 struct sg_lb_stats *sgs) 12063 { 12064 struct sg_lb_stats *busiest = &sds->busiest_stat; 12065 12066 /* Make sure that there is at least one task to pull */ 12067 if (!sgs->sum_h_nr_running) 12068 return false; 12069 12070 /* 12071 * Don't try to pull misfit tasks we can't help. 12072 * We can use max_capacity here as reduction in capacity on some 12073 * CPUs in the group should either be possible to resolve 12074 * internally or be covered by avg_load imbalance (eventually). 12075 * 12076 * When SMT is active, only pull a misfit to dst_cpu if it is on a 12077 * fully idle core; otherwise the effective capacity of the core is 12078 * reduced and we may not actually provide more capacity than the 12079 * source. 12080 */ 12081 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) && 12082 (sgs->group_type == group_misfit_task) && 12083 (!env->dst_core_idle || 12084 !capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) || 12085 sds->local_stat.group_type != group_has_spare)) 12086 return false; 12087 12088 /* 12089 * Candidate sg has no more than one task per CPU and has higher 12090 * per-CPU capacity. Migrating tasks to less capable CPUs may harm 12091 * throughput. Maximize throughput, power/energy consequences are not 12092 * considered. 12093 */ 12094 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) && 12095 (sgs->group_type <= group_fully_busy) && 12096 (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu)))) 12097 return false; 12098 12099 if (sgs->group_type > busiest->group_type) 12100 return true; 12101 12102 if (sgs->group_type < busiest->group_type) 12103 return false; 12104 12105 /* 12106 * The candidate and the current busiest group are the same type of 12107 * group. Let check which one is the busiest according to the type. 12108 */ 12109 12110 switch (sgs->group_type) { 12111 case group_overloaded: 12112 /* Select the overloaded group with highest avg_load. */ 12113 return sgs->avg_load > busiest->avg_load; 12114 12115 case group_llc_balance: 12116 /* Select the group with most tasks preferring dst LLC */ 12117 return update_llc_busiest(env, busiest, sgs); 12118 12119 case group_imbalanced: 12120 /* 12121 * Select the 1st imbalanced group as we don't have any way to 12122 * choose one more than another. 12123 */ 12124 return false; 12125 12126 case group_asym_packing: 12127 /* Prefer to move from lowest priority CPU's work */ 12128 return sched_asym_prefer(READ_ONCE(sds->busiest->asym_prefer_cpu), 12129 READ_ONCE(sg->asym_prefer_cpu)); 12130 12131 case group_misfit_task: 12132 /* 12133 * If we have more than one misfit sg go with the biggest 12134 * misfit. 12135 */ 12136 return sgs->group_misfit_task_load > busiest->group_misfit_task_load; 12137 12138 case group_smt_balance: 12139 /* 12140 * Check if we have spare CPUs on either SMT group to 12141 * choose has spare or fully busy handling. 12142 */ 12143 if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0) 12144 goto has_spare; 12145 12146 fallthrough; 12147 12148 case group_fully_busy: 12149 /* 12150 * Select the fully busy group with highest avg_load. In 12151 * theory, there is no need to pull task from such kind of 12152 * group because tasks have all compute capacity that they need 12153 * but we can still improve the overall throughput by reducing 12154 * contention when accessing shared HW resources. 12155 * 12156 * XXX for now avg_load is not computed and always 0 so we 12157 * select the 1st one, except if @sg is composed of SMT 12158 * siblings. 12159 */ 12160 12161 if (sgs->avg_load < busiest->avg_load) 12162 return false; 12163 12164 if (sgs->avg_load == busiest->avg_load) { 12165 /* 12166 * SMT sched groups need more help than non-SMT groups. 12167 * If @sg happens to also be SMT, either choice is good. 12168 */ 12169 if (sds->busiest->flags & SD_SHARE_CPUCAPACITY) 12170 return false; 12171 } 12172 12173 break; 12174 12175 case group_has_spare: 12176 /* 12177 * Do not pick sg with SMT CPUs over sg with pure CPUs, 12178 * as we do not want to pull task off SMT core with one task 12179 * and make the core idle. 12180 */ 12181 if (smt_vs_nonsmt_groups(sds->busiest, sg)) { 12182 if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1) 12183 return false; 12184 else 12185 return true; 12186 } 12187 has_spare: 12188 12189 /* 12190 * Select not overloaded group with lowest number of idle CPUs 12191 * and highest number of running tasks. We could also compare 12192 * the spare capacity which is more stable but it can end up 12193 * that the group has less spare capacity but finally more idle 12194 * CPUs which means less opportunity to pull tasks. 12195 */ 12196 if (sgs->idle_cpus > busiest->idle_cpus) 12197 return false; 12198 else if ((sgs->idle_cpus == busiest->idle_cpus) && 12199 (sgs->sum_nr_running <= busiest->sum_nr_running)) 12200 return false; 12201 12202 break; 12203 } 12204 12205 return true; 12206 } 12207 12208 #ifdef CONFIG_NUMA_BALANCING 12209 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs) 12210 { 12211 if (sgs->sum_h_nr_running > sgs->nr_numa_running) 12212 return regular; 12213 if (sgs->sum_h_nr_running > sgs->nr_preferred_running) 12214 return remote; 12215 return all; 12216 } 12217 12218 static inline enum fbq_type fbq_classify_rq(struct rq *rq) 12219 { 12220 if (rq->nr_running > rq->nr_numa_running) 12221 return regular; 12222 if (rq->nr_running > rq->nr_preferred_running) 12223 return remote; 12224 return all; 12225 } 12226 #else /* !CONFIG_NUMA_BALANCING: */ 12227 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs) 12228 { 12229 return all; 12230 } 12231 12232 static inline enum fbq_type fbq_classify_rq(struct rq *rq) 12233 { 12234 return regular; 12235 } 12236 #endif /* !CONFIG_NUMA_BALANCING */ 12237 12238 12239 struct sg_lb_stats; 12240 12241 /* 12242 * task_running_on_cpu - return 1 if @p is running on @cpu. 12243 */ 12244 12245 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p) 12246 { 12247 /* Task has no contribution or is new */ 12248 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 12249 return 0; 12250 12251 if (task_on_rq_queued(p)) 12252 return 1; 12253 12254 return 0; 12255 } 12256 12257 /** 12258 * idle_cpu_without - would a given CPU be idle without p ? 12259 * @cpu: the processor on which idleness is tested. 12260 * @p: task which should be ignored. 12261 * 12262 * Return: 1 if the CPU would be idle. 0 otherwise. 12263 */ 12264 static int idle_cpu_without(int cpu, struct task_struct *p) 12265 { 12266 struct rq *rq = cpu_rq(cpu); 12267 12268 if (rq->curr != rq->idle && rq->curr != p) 12269 return 0; 12270 12271 /* 12272 * rq->nr_running can't be used but an updated version without the 12273 * impact of p on cpu must be used instead. The updated nr_running 12274 * be computed and tested before calling idle_cpu_without(). 12275 */ 12276 12277 if (rq->ttwu_pending) 12278 return 0; 12279 12280 return 1; 12281 } 12282 12283 /* 12284 * update_sg_wakeup_stats - Update sched_group's statistics for wakeup. 12285 * @sd: The sched_domain level to look for idlest group. 12286 * @group: sched_group whose statistics are to be updated. 12287 * @sgs: variable to hold the statistics for this group. 12288 * @p: The task for which we look for the idlest group/CPU. 12289 */ 12290 static inline void update_sg_wakeup_stats(struct sched_domain *sd, 12291 struct sched_group *group, 12292 struct sg_lb_stats *sgs, 12293 struct task_struct *p) 12294 { 12295 int i, nr_running; 12296 12297 memset(sgs, 0, sizeof(*sgs)); 12298 12299 /* Assume that task can't fit any CPU of the group */ 12300 if (sd->flags & SD_ASYM_CPUCAPACITY) 12301 sgs->group_misfit_task_load = 1; 12302 12303 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) { 12304 struct rq *rq = cpu_rq(i); 12305 unsigned int local; 12306 12307 sgs->group_load += cpu_load_without(rq, p); 12308 sgs->group_util += cpu_util_without(i, p); 12309 sgs->group_runnable += cpu_runnable_without(rq, p); 12310 local = task_running_on_cpu(i, p); 12311 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable - local; 12312 12313 nr_running = rq->nr_running - local; 12314 sgs->sum_nr_running += nr_running; 12315 12316 /* 12317 * No need to call idle_cpu_without() if nr_running is not 0 12318 */ 12319 if (!nr_running && idle_cpu_without(i, p)) 12320 sgs->idle_cpus++; 12321 12322 /* Check if task fits in the CPU */ 12323 if (sd->flags & SD_ASYM_CPUCAPACITY && 12324 sgs->group_misfit_task_load && 12325 task_fits_cpu(p, i)) 12326 sgs->group_misfit_task_load = 0; 12327 12328 } 12329 12330 sgs->group_capacity = group->sgc->capacity; 12331 12332 sgs->group_weight = group->group_weight; 12333 12334 sgs->group_type = group_classify(sd->imbalance_pct, group, sgs); 12335 12336 /* 12337 * Computing avg_load makes sense only when group is fully busy or 12338 * overloaded 12339 */ 12340 if (sgs->group_type == group_fully_busy || 12341 sgs->group_type == group_overloaded) 12342 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) / 12343 sgs->group_capacity; 12344 } 12345 12346 static bool update_pick_idlest(struct sched_group *idlest, 12347 struct sg_lb_stats *idlest_sgs, 12348 struct sched_group *group, 12349 struct sg_lb_stats *sgs) 12350 { 12351 if (sgs->group_type < idlest_sgs->group_type) 12352 return true; 12353 12354 if (sgs->group_type > idlest_sgs->group_type) 12355 return false; 12356 12357 /* 12358 * The candidate and the current idlest group are the same type of 12359 * group. Let check which one is the idlest according to the type. 12360 */ 12361 12362 switch (sgs->group_type) { 12363 case group_overloaded: 12364 case group_fully_busy: 12365 /* Select the group with lowest avg_load. */ 12366 if (idlest_sgs->avg_load <= sgs->avg_load) 12367 return false; 12368 break; 12369 12370 case group_llc_balance: 12371 case group_imbalanced: 12372 case group_asym_packing: 12373 case group_smt_balance: 12374 /* Those types are not used in the slow wakeup path */ 12375 return false; 12376 12377 case group_misfit_task: 12378 /* Select group with the highest max capacity */ 12379 if (idlest->sgc->max_capacity >= group->sgc->max_capacity) 12380 return false; 12381 break; 12382 12383 case group_has_spare: 12384 /* Select group with most idle CPUs */ 12385 if (idlest_sgs->idle_cpus > sgs->idle_cpus) 12386 return false; 12387 12388 /* Select group with lowest group_util */ 12389 if (idlest_sgs->idle_cpus == sgs->idle_cpus && 12390 idlest_sgs->group_util <= sgs->group_util) 12391 return false; 12392 12393 break; 12394 } 12395 12396 return true; 12397 } 12398 12399 /* 12400 * sched_balance_find_dst_group() finds and returns the least busy CPU group within the 12401 * domain. 12402 * 12403 * Assumes p is allowed on at least one CPU in sd. 12404 */ 12405 static struct sched_group * 12406 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu) 12407 { 12408 struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups; 12409 struct sg_lb_stats local_sgs, tmp_sgs; 12410 struct sg_lb_stats *sgs; 12411 unsigned long imbalance; 12412 struct sg_lb_stats idlest_sgs = { 12413 .avg_load = UINT_MAX, 12414 .group_type = group_overloaded, 12415 }; 12416 12417 do { 12418 int local_group; 12419 12420 /* Skip over this group if it has no CPUs allowed */ 12421 if (!cpumask_intersects(sched_group_span(group), 12422 p->cpus_ptr)) 12423 continue; 12424 12425 /* Skip over this group if no cookie matched */ 12426 if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group)) 12427 continue; 12428 12429 local_group = cpumask_test_cpu(this_cpu, 12430 sched_group_span(group)); 12431 12432 if (local_group) { 12433 sgs = &local_sgs; 12434 local = group; 12435 } else { 12436 sgs = &tmp_sgs; 12437 } 12438 12439 update_sg_wakeup_stats(sd, group, sgs, p); 12440 12441 if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) { 12442 idlest = group; 12443 idlest_sgs = *sgs; 12444 } 12445 12446 } while (group = group->next, group != sd->groups); 12447 12448 12449 /* There is no idlest group to push tasks to */ 12450 if (!idlest) 12451 return NULL; 12452 12453 /* The local group has been skipped because of CPU affinity */ 12454 if (!local) 12455 return idlest; 12456 12457 /* 12458 * If the local group is idler than the selected idlest group 12459 * don't try and push the task. 12460 */ 12461 if (local_sgs.group_type < idlest_sgs.group_type) 12462 return NULL; 12463 12464 /* 12465 * If the local group is busier than the selected idlest group 12466 * try and push the task. 12467 */ 12468 if (local_sgs.group_type > idlest_sgs.group_type) 12469 return idlest; 12470 12471 switch (local_sgs.group_type) { 12472 case group_overloaded: 12473 case group_fully_busy: 12474 12475 /* Calculate allowed imbalance based on load */ 12476 imbalance = scale_load_down(NICE_0_LOAD) * 12477 (sd->imbalance_pct-100) / 100; 12478 12479 /* 12480 * When comparing groups across NUMA domains, it's possible for 12481 * the local domain to be very lightly loaded relative to the 12482 * remote domains but "imbalance" skews the comparison making 12483 * remote CPUs look much more favourable. When considering 12484 * cross-domain, add imbalance to the load on the remote node 12485 * and consider staying local. 12486 */ 12487 12488 if ((sd->flags & SD_NUMA) && 12489 ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load)) 12490 return NULL; 12491 12492 /* 12493 * If the local group is less loaded than the selected 12494 * idlest group don't try and push any tasks. 12495 */ 12496 if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance)) 12497 return NULL; 12498 12499 if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load) 12500 return NULL; 12501 break; 12502 12503 case group_llc_balance: 12504 case group_imbalanced: 12505 case group_asym_packing: 12506 case group_smt_balance: 12507 /* Those type are not used in the slow wakeup path */ 12508 return NULL; 12509 12510 case group_misfit_task: 12511 /* Select group with the highest max capacity */ 12512 if (local->sgc->max_capacity >= idlest->sgc->max_capacity) 12513 return NULL; 12514 break; 12515 12516 case group_has_spare: 12517 #ifdef CONFIG_NUMA 12518 if (sd->flags & SD_NUMA) { 12519 int imb_numa_nr = sd->imb_numa_nr; 12520 #ifdef CONFIG_NUMA_BALANCING 12521 int idlest_cpu; 12522 /* 12523 * If there is spare capacity at NUMA, try to select 12524 * the preferred node 12525 */ 12526 if (cpu_to_node(this_cpu) == p->numa_preferred_nid) 12527 return NULL; 12528 12529 idlest_cpu = cpumask_first(sched_group_span(idlest)); 12530 if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid) 12531 return idlest; 12532 #endif /* CONFIG_NUMA_BALANCING */ 12533 /* 12534 * Otherwise, keep the task close to the wakeup source 12535 * and improve locality if the number of running tasks 12536 * would remain below threshold where an imbalance is 12537 * allowed while accounting for the possibility the 12538 * task is pinned to a subset of CPUs. If there is a 12539 * real need of migration, periodic load balance will 12540 * take care of it. 12541 */ 12542 if (p->nr_cpus_allowed != NR_CPUS) { 12543 unsigned int w = cpumask_weight_and(p->cpus_ptr, 12544 sched_group_span(local)); 12545 imb_numa_nr = min(w, sd->imb_numa_nr); 12546 } 12547 12548 imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus); 12549 if (!adjust_numa_imbalance(imbalance, 12550 local_sgs.sum_nr_running + 1, 12551 imb_numa_nr)) { 12552 return NULL; 12553 } 12554 } 12555 #endif /* CONFIG_NUMA */ 12556 12557 /* 12558 * Select group with highest number of idle CPUs. We could also 12559 * compare the utilization which is more stable but it can end 12560 * up that the group has less spare capacity but finally more 12561 * idle CPUs which means more opportunity to run task. 12562 */ 12563 if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus) 12564 return NULL; 12565 break; 12566 } 12567 12568 return idlest; 12569 } 12570 12571 static void update_idle_cpu_scan(struct lb_env *env, 12572 unsigned long sum_util) 12573 { 12574 struct sched_domain_shared *sd_share; 12575 struct sched_domain *sd = env->sd; 12576 int llc_weight, pct; 12577 u64 x, y, tmp; 12578 /* 12579 * Update the number of CPUs to scan in LLC domain, which could 12580 * be used as a hint in select_idle_cpu(). The update of sd_share 12581 * could be expensive because it is within a shared cache line. 12582 * So the write of this hint only occurs during periodic load 12583 * balancing, rather than CPU_NEWLY_IDLE, because the latter 12584 * can fire way more frequently than the former. 12585 */ 12586 if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE) 12587 return; 12588 12589 sd_share = sd->shared; 12590 if (!sd_share) 12591 return; 12592 12593 /* 12594 * The number of CPUs to search drops as sum_util increases, when 12595 * sum_util hits 85% or above, the scan stops. 12596 * The reason to choose 85% as the threshold is because this is the 12597 * imbalance_pct(117) when a LLC sched group is overloaded. 12598 * 12599 * let y = SCHED_CAPACITY_SCALE - p * x^2 [1] 12600 * and y'= y / SCHED_CAPACITY_SCALE 12601 * 12602 * x is the ratio of sum_util compared to the CPU capacity: 12603 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE) 12604 * y' is the ratio of CPUs to be scanned in the LLC domain, 12605 * and the number of CPUs to scan is calculated by: 12606 * 12607 * nr_scan = llc_weight * y' [2] 12608 * 12609 * When x hits the threshold of overloaded, AKA, when 12610 * x = 100 / pct, y drops to 0. According to [1], 12611 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000 12612 * 12613 * Scale x by SCHED_CAPACITY_SCALE: 12614 * x' = sum_util / llc_weight; [3] 12615 * 12616 * and finally [1] becomes: 12617 * y = SCHED_CAPACITY_SCALE - 12618 * x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE) [4] 12619 * 12620 */ 12621 /* equation [3] */ 12622 x = sum_util; 12623 llc_weight = sd->span_weight; 12624 do_div(x, llc_weight); 12625 12626 /* equation [4] */ 12627 pct = sd->imbalance_pct; 12628 tmp = x * x * pct * pct; 12629 do_div(tmp, 10000 * SCHED_CAPACITY_SCALE); 12630 tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE); 12631 y = SCHED_CAPACITY_SCALE - tmp; 12632 12633 /* equation [2] */ 12634 y *= llc_weight; 12635 do_div(y, SCHED_CAPACITY_SCALE); 12636 if ((int)y != sd_share->nr_idle_scan) 12637 WRITE_ONCE(sd_share->nr_idle_scan, (int)y); 12638 } 12639 12640 /** 12641 * update_sd_lb_stats - Update sched_domain's statistics for load balancing. 12642 * @env: The load balancing environment. 12643 * @sds: variable to hold the statistics for this sched_domain. 12644 */ 12645 12646 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds) 12647 { 12648 struct sched_group *sg = env->sd->groups; 12649 struct sg_lb_stats *local = &sds->local_stat; 12650 struct sg_lb_stats tmp_sgs; 12651 unsigned long sum_util = 0; 12652 bool sg_overloaded = 0, sg_overutilized = 0; 12653 12654 env->dst_core_idle = !sched_smt_active() || is_core_idle(env->dst_cpu); 12655 12656 do { 12657 struct sg_lb_stats *sgs = &tmp_sgs; 12658 int local_group; 12659 12660 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg)); 12661 if (local_group) { 12662 sds->local = sg; 12663 sgs = local; 12664 12665 if (env->idle != CPU_NEWLY_IDLE || 12666 time_after_eq(jiffies, sg->sgc->next_update)) 12667 update_group_capacity(env->sd, env->dst_cpu); 12668 } 12669 12670 update_sg_lb_stats(env, sds, sg, sgs, &sg_overloaded); 12671 12672 if (!local_group && update_sd_pick_busiest(env, sds, sg, sgs)) { 12673 sds->busiest = sg; 12674 sds->busiest_stat = *sgs; 12675 } 12676 12677 sg_overutilized |= sgs->group_overutilized; 12678 12679 /* Now, start updating sd_lb_stats */ 12680 sds->total_load += sgs->group_load; 12681 sds->total_capacity += sgs->group_capacity; 12682 12683 sum_util += sgs->group_util; 12684 sg = sg->next; 12685 } while (sg != env->sd->groups); 12686 12687 /* 12688 * Indicate that the child domain of the busiest group prefers tasks 12689 * go to a child's sibling domains first. NB the flags of a sched group 12690 * are those of the child domain. 12691 */ 12692 if (sds->busiest) 12693 sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING); 12694 12695 12696 if (env->sd->flags & SD_NUMA) 12697 env->fbq_type = fbq_classify_group(&sds->busiest_stat); 12698 12699 if (!env->sd->parent) { 12700 /* update overload indicator if we are at root domain */ 12701 set_rd_overloaded(env->dst_rq->rd, sg_overloaded); 12702 12703 /* Update over-utilization (tipping point, U >= 0) indicator */ 12704 set_rd_overutilized(env->dst_rq->rd, sg_overutilized); 12705 } else if (sg_overutilized) { 12706 set_rd_overutilized(env->dst_rq->rd, sg_overutilized); 12707 } 12708 12709 update_idle_cpu_scan(env, sum_util); 12710 } 12711 12712 /** 12713 * calculate_imbalance - Calculate the amount of imbalance present within the 12714 * groups of a given sched_domain during load balance. 12715 * @env: load balance environment 12716 * @sds: statistics of the sched_domain whose imbalance is to be calculated. 12717 */ 12718 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds) 12719 { 12720 struct sg_lb_stats *local, *busiest; 12721 12722 local = &sds->local_stat; 12723 busiest = &sds->busiest_stat; 12724 12725 if (busiest->group_type == group_misfit_task) { 12726 if (env->sd->flags & SD_ASYM_CPUCAPACITY) { 12727 /* Set imbalance to allow misfit tasks to be balanced. */ 12728 env->migration_type = migrate_misfit; 12729 env->imbalance = 1; 12730 } else { 12731 /* 12732 * Set load imbalance to allow moving task from cpu 12733 * with reduced capacity. 12734 */ 12735 env->migration_type = migrate_load; 12736 env->imbalance = busiest->group_misfit_task_load; 12737 } 12738 return; 12739 } 12740 12741 if (busiest->group_type == group_asym_packing) { 12742 /* 12743 * In case of asym capacity, we will try to migrate all load to 12744 * the preferred CPU. 12745 */ 12746 env->migration_type = migrate_task; 12747 env->imbalance = busiest->sum_h_nr_running; 12748 return; 12749 } 12750 12751 if (busiest->group_type == group_smt_balance) { 12752 /* Reduce number of tasks sharing CPU capacity */ 12753 env->migration_type = migrate_task; 12754 env->imbalance = 1; 12755 return; 12756 } 12757 12758 #ifdef CONFIG_SCHED_CACHE 12759 if (busiest->group_type == group_llc_balance) { 12760 /* Move a task that prefer local LLC */ 12761 env->migration_type = migrate_llc_task; 12762 env->imbalance = 1; 12763 return; 12764 } 12765 #endif 12766 12767 if (busiest->group_type == group_imbalanced) { 12768 /* 12769 * In the group_imb case we cannot rely on group-wide averages 12770 * to ensure CPU-load equilibrium, try to move any task to fix 12771 * the imbalance. The next load balance will take care of 12772 * balancing back the system. 12773 */ 12774 env->migration_type = migrate_task; 12775 env->imbalance = 1; 12776 return; 12777 } 12778 12779 /* 12780 * Try to use spare capacity of local group without overloading it or 12781 * emptying busiest. 12782 */ 12783 if (local->group_type == group_has_spare) { 12784 if ((busiest->group_type > group_fully_busy) && 12785 !(env->sd->flags & SD_SHARE_LLC)) { 12786 /* 12787 * If busiest is overloaded, try to fill spare 12788 * capacity. This might end up creating spare capacity 12789 * in busiest or busiest still being overloaded but 12790 * there is no simple way to directly compute the 12791 * amount of load to migrate in order to balance the 12792 * system. 12793 */ 12794 env->migration_type = migrate_util; 12795 env->imbalance = max(local->group_capacity, local->group_util) - 12796 local->group_util; 12797 12798 /* 12799 * In some cases, the group's utilization is max or even 12800 * higher than capacity because of migrations but the 12801 * local CPU is (newly) idle. There is at least one 12802 * waiting task in this overloaded busiest group. Let's 12803 * try to pull it. 12804 */ 12805 if (env->idle && env->imbalance == 0) { 12806 env->migration_type = migrate_task; 12807 env->imbalance = 1; 12808 } 12809 12810 return; 12811 } 12812 12813 if (busiest->group_weight == 1 || sds->prefer_sibling) { 12814 /* 12815 * When prefer sibling, evenly spread running tasks on 12816 * groups. 12817 */ 12818 env->migration_type = migrate_task; 12819 env->imbalance = sibling_imbalance(env, sds, busiest, local); 12820 } else { 12821 12822 /* 12823 * If there is no overload, we just want to even the number of 12824 * idle CPUs. 12825 */ 12826 env->migration_type = migrate_task; 12827 env->imbalance = max_t(long, 0, 12828 (local->idle_cpus - busiest->idle_cpus)); 12829 } 12830 12831 #ifdef CONFIG_NUMA 12832 /* Consider allowing a small imbalance between NUMA groups */ 12833 if (env->sd->flags & SD_NUMA) { 12834 env->imbalance = adjust_numa_imbalance(env->imbalance, 12835 local->sum_nr_running + 1, 12836 env->sd->imb_numa_nr); 12837 } 12838 #endif 12839 12840 /* Number of tasks to move to restore balance */ 12841 env->imbalance >>= 1; 12842 12843 return; 12844 } 12845 12846 /* 12847 * Local is fully busy but has to take more load to relieve the 12848 * busiest group 12849 */ 12850 if (local->group_type < group_overloaded) { 12851 /* 12852 * Local will become overloaded so the avg_load metrics are 12853 * finally needed. 12854 */ 12855 12856 local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) / 12857 local->group_capacity; 12858 12859 /* 12860 * If the local group is more loaded than the selected 12861 * busiest group don't try to pull any tasks. 12862 */ 12863 if (local->avg_load >= busiest->avg_load) { 12864 env->imbalance = 0; 12865 return; 12866 } 12867 12868 sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) / 12869 sds->total_capacity; 12870 12871 /* 12872 * If the local group is more loaded than the average system 12873 * load, don't try to pull any tasks. 12874 */ 12875 if (local->avg_load >= sds->avg_load) { 12876 env->imbalance = 0; 12877 return; 12878 } 12879 12880 } 12881 12882 /* 12883 * Both group are or will become overloaded and we're trying to get all 12884 * the CPUs to the average_load, so we don't want to push ourselves 12885 * above the average load, nor do we wish to reduce the max loaded CPU 12886 * below the average load. At the same time, we also don't want to 12887 * reduce the group load below the group capacity. Thus we look for 12888 * the minimum possible imbalance. 12889 */ 12890 env->migration_type = migrate_load; 12891 env->imbalance = min( 12892 (busiest->avg_load - sds->avg_load) * busiest->group_capacity, 12893 (sds->avg_load - local->avg_load) * local->group_capacity 12894 ) / SCHED_CAPACITY_SCALE; 12895 } 12896 12897 /******* sched_balance_find_src_group() helpers end here *********************/ 12898 12899 /* 12900 * Decision matrix according to the local and busiest group type: 12901 * 12902 * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded 12903 * has_spare nr_idle balanced N/A N/A balanced balanced 12904 * fully_busy nr_idle nr_idle N/A N/A balanced balanced 12905 * misfit_task force N/A N/A N/A N/A N/A 12906 * asym_packing force force N/A N/A force force 12907 * imbalanced force force N/A N/A force force 12908 * overloaded force force N/A N/A force avg_load 12909 * 12910 * N/A : Not Applicable because already filtered while updating 12911 * statistics. 12912 * balanced : The system is balanced for these 2 groups. 12913 * force : Calculate the imbalance as load migration is probably needed. 12914 * avg_load : Only if imbalance is significant enough. 12915 * nr_idle : dst_cpu is not busy and the number of idle CPUs is quite 12916 * different in groups. 12917 */ 12918 12919 /** 12920 * sched_balance_find_src_group - Returns the busiest group within the sched_domain 12921 * if there is an imbalance. 12922 * @env: The load balancing environment. 12923 * 12924 * Also calculates the amount of runnable load which should be moved 12925 * to restore balance. 12926 * 12927 * Return: - The busiest group if imbalance exists. 12928 */ 12929 static struct sched_group *sched_balance_find_src_group(struct lb_env *env) 12930 { 12931 struct sg_lb_stats *local, *busiest; 12932 struct sd_lb_stats sds; 12933 12934 init_sd_lb_stats(&sds); 12935 12936 /* 12937 * Compute the various statistics relevant for load balancing at 12938 * this level. 12939 */ 12940 update_sd_lb_stats(env, &sds); 12941 12942 /* There is no busy sibling group to pull tasks from */ 12943 if (!sds.busiest) 12944 goto out_balanced; 12945 12946 busiest = &sds.busiest_stat; 12947 12948 /* Misfit tasks should be dealt with regardless of the avg load */ 12949 if (busiest->group_type == group_misfit_task) 12950 goto force_balance; 12951 12952 if (!is_rd_overutilized(env->dst_rq->rd) && 12953 rcu_dereference_all(env->dst_rq->rd->pd)) 12954 goto out_balanced; 12955 12956 /* ASYM feature bypasses nice load balance check */ 12957 if (busiest->group_type == group_asym_packing) 12958 goto force_balance; 12959 12960 /* 12961 * If the busiest group is imbalanced the below checks don't 12962 * work because they assume all things are equal, which typically 12963 * isn't true due to cpus_ptr constraints and the like. 12964 */ 12965 if (busiest->group_type == group_imbalanced) 12966 goto force_balance; 12967 12968 local = &sds.local_stat; 12969 /* 12970 * If the local group is busier than the selected busiest group 12971 * don't try and pull any tasks. 12972 */ 12973 if (local->group_type > busiest->group_type) 12974 goto out_balanced; 12975 12976 /* 12977 * When groups are overloaded, use the avg_load to ensure fairness 12978 * between tasks. 12979 */ 12980 if (local->group_type == group_overloaded) { 12981 /* 12982 * If the local group is more loaded than the selected 12983 * busiest group don't try to pull any tasks. 12984 */ 12985 if (local->avg_load >= busiest->avg_load) 12986 goto out_balanced; 12987 12988 /* XXX broken for overlapping NUMA groups */ 12989 sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) / 12990 sds.total_capacity; 12991 12992 /* 12993 * Don't pull any tasks if this group is already above the 12994 * domain average load. 12995 */ 12996 if (local->avg_load >= sds.avg_load) 12997 goto out_balanced; 12998 12999 /* 13000 * If the busiest group is more loaded, use imbalance_pct to be 13001 * conservative. 13002 */ 13003 if (100 * busiest->avg_load <= 13004 env->sd->imbalance_pct * local->avg_load) 13005 goto out_balanced; 13006 } 13007 13008 /* 13009 * Try to move all excess tasks to a sibling domain of the busiest 13010 * group's child domain. 13011 */ 13012 if (sds.prefer_sibling && local->group_type == group_has_spare && 13013 (busiest->group_type == group_llc_balance || 13014 sibling_imbalance(env, &sds, busiest, local) > 1)) 13015 goto force_balance; 13016 13017 if (busiest->group_type != group_overloaded) { 13018 if (!env->idle) { 13019 /* 13020 * If the busiest group is not overloaded (and as a 13021 * result the local one too) but this CPU is already 13022 * busy, let another idle CPU try to pull task. 13023 */ 13024 goto out_balanced; 13025 } 13026 13027 if (busiest->group_type == group_smt_balance && 13028 smt_vs_nonsmt_groups(sds.local, sds.busiest)) { 13029 /* Let non SMT CPU pull from SMT CPU sharing with sibling */ 13030 goto force_balance; 13031 } 13032 13033 if (busiest->group_weight > 1 && 13034 local->idle_cpus <= (busiest->idle_cpus + 1)) { 13035 /* 13036 * If the busiest group is not overloaded 13037 * and there is no imbalance between this and busiest 13038 * group wrt idle CPUs, it is balanced. The imbalance 13039 * becomes significant if the diff is greater than 1 13040 * otherwise we might end up to just move the imbalance 13041 * on another group. Of course this applies only if 13042 * there is more than 1 CPU per group. 13043 */ 13044 goto out_balanced; 13045 } 13046 13047 if (busiest->sum_h_nr_running == 1) { 13048 /* 13049 * busiest doesn't have any tasks waiting to run 13050 */ 13051 goto out_balanced; 13052 } 13053 } 13054 13055 force_balance: 13056 /* Looks like there is an imbalance. Compute it */ 13057 calculate_imbalance(env, &sds); 13058 return env->imbalance ? sds.busiest : NULL; 13059 13060 out_balanced: 13061 env->imbalance = 0; 13062 return NULL; 13063 } 13064 13065 /* 13066 * sched_balance_find_src_rq - find the busiest runqueue among the CPUs in the group. 13067 */ 13068 static struct rq *sched_balance_find_src_rq(struct lb_env *env, 13069 struct sched_group *group) 13070 { 13071 struct rq *busiest = NULL, *rq; 13072 unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1; 13073 unsigned int __maybe_unused busiest_pref_llc = 0; 13074 struct sched_domain __maybe_unused *sd_tmp; 13075 unsigned int busiest_nr = 0; 13076 int __maybe_unused dst_llc; 13077 int i; 13078 13079 for_each_cpu_and(i, sched_group_span(group), env->cpus) { 13080 unsigned long capacity, load, util; 13081 unsigned int nr_running; 13082 enum fbq_type rt; 13083 13084 rq = cpu_rq(i); 13085 rt = fbq_classify_rq(rq); 13086 13087 /* 13088 * We classify groups/runqueues into three groups: 13089 * - regular: there are !numa tasks 13090 * - remote: there are numa tasks that run on the 'wrong' node 13091 * - all: there is no distinction 13092 * 13093 * In order to avoid migrating ideally placed numa tasks, 13094 * ignore those when there's better options. 13095 * 13096 * If we ignore the actual busiest queue to migrate another 13097 * task, the next balance pass can still reduce the busiest 13098 * queue by moving tasks around inside the node. 13099 * 13100 * If we cannot move enough load due to this classification 13101 * the next pass will adjust the group classification and 13102 * allow migration of more tasks. 13103 * 13104 * Both cases only affect the total convergence complexity. 13105 */ 13106 if (rt > env->fbq_type) 13107 continue; 13108 13109 nr_running = rq->cfs.h_nr_runnable; 13110 if (!nr_running) 13111 continue; 13112 13113 capacity = capacity_of(i); 13114 13115 /* 13116 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could 13117 * eventually lead to active_balancing high->low capacity. 13118 * Higher per-CPU capacity is considered better than balancing 13119 * average load. 13120 */ 13121 if (env->sd->flags & SD_ASYM_CPUCAPACITY && 13122 nr_running == 1) { 13123 bool cluster_equal_cap = static_branch_unlikely(&sched_cluster_active) && 13124 (get_actual_cpu_capacity(env->dst_cpu) == 13125 get_actual_cpu_capacity(i)); 13126 bool smt_degraded_cap = sched_smt_active() && !is_core_idle(i); 13127 13128 /* 13129 * Busy SMT siblings reduce the capacity of CPU @i. Do 13130 * not skip it in this case. 13131 * 13132 * CONFIG_SCHED_CLUSTER requires balancing load across 13133 * clusters of identical capacity, accounting for 13134 * hardware and cpufreq pressure. 13135 */ 13136 if (!smt_degraded_cap && !cluster_equal_cap && 13137 !capacity_greater(capacity_of(env->dst_cpu), capacity)) 13138 continue; 13139 } 13140 13141 /* 13142 * Make sure we only pull tasks from a CPU of lower priority 13143 * when balancing between SMT siblings. 13144 * 13145 * If balancing between cores, let lower priority CPUs help 13146 * SMT cores with more than one busy sibling. 13147 */ 13148 if (sched_asym(env->sd, i, env->dst_cpu) && nr_running == 1) 13149 continue; 13150 13151 switch (env->migration_type) { 13152 case migrate_load: 13153 /* 13154 * When comparing with load imbalance, use cpu_load() 13155 * which is not scaled with the CPU capacity. 13156 */ 13157 load = cpu_load(rq); 13158 13159 if (nr_running == 1 && load > env->imbalance && 13160 !check_cpu_capacity(rq, env->sd)) 13161 break; 13162 13163 /* 13164 * For the load comparisons with the other CPUs, 13165 * consider the cpu_load() scaled with the CPU 13166 * capacity, so that the load can be moved away 13167 * from the CPU that is potentially running at a 13168 * lower capacity. 13169 * 13170 * Thus we're looking for max(load_i / capacity_i), 13171 * crosswise multiplication to rid ourselves of the 13172 * division works out to: 13173 * load_i * capacity_j > load_j * capacity_i; 13174 * where j is our previous maximum. 13175 */ 13176 if (load * busiest_capacity > busiest_load * capacity) { 13177 busiest_load = load; 13178 busiest_capacity = capacity; 13179 busiest = rq; 13180 } 13181 break; 13182 13183 case migrate_util: 13184 util = cpu_util_cfs_boost(i); 13185 13186 /* 13187 * Don't try to pull utilization from a CPU with one 13188 * running task. Whatever its utilization, we will fail 13189 * detach the task. 13190 */ 13191 if (nr_running <= 1) 13192 continue; 13193 13194 if (busiest_util < util) { 13195 busiest_util = util; 13196 busiest = rq; 13197 } 13198 break; 13199 13200 case migrate_task: 13201 if (busiest_nr < nr_running) { 13202 busiest_nr = nr_running; 13203 busiest = rq; 13204 } 13205 break; 13206 13207 case migrate_misfit: 13208 /* 13209 * For ASYM_CPUCAPACITY domains with misfit tasks we 13210 * simply seek the "biggest" misfit task. 13211 */ 13212 if (rq->misfit_task_load > busiest_load) { 13213 busiest_load = rq->misfit_task_load; 13214 busiest = rq; 13215 } 13216 13217 break; 13218 13219 case migrate_llc_task: 13220 #ifdef CONFIG_SCHED_CACHE 13221 sd_tmp = rcu_dereference_all(rq->sd); 13222 dst_llc = llc_id(env->dst_cpu); 13223 13224 if (sd_tmp && (unsigned)dst_llc < sd_tmp->llc_max) { 13225 unsigned int this_pref_llc = 13226 sd_tmp->llc_counts[dst_llc]; 13227 13228 if (busiest_pref_llc < this_pref_llc) { 13229 busiest_pref_llc = this_pref_llc; 13230 busiest = rq; 13231 } 13232 } 13233 #endif 13234 break; 13235 13236 } 13237 } 13238 13239 return busiest; 13240 } 13241 13242 /* 13243 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but 13244 * so long as it is large enough. 13245 */ 13246 #define MAX_PINNED_INTERVAL 512 13247 13248 static inline bool 13249 asym_active_balance(struct lb_env *env) 13250 { 13251 /* 13252 * ASYM_PACKING needs to force migrate tasks from busy but lower 13253 * priority CPUs in order to pack all tasks in the highest priority 13254 * CPUs. When done between cores, do it only if the whole core if the 13255 * whole core is idle. 13256 * 13257 * If @env::src_cpu is an SMT core with busy siblings, let 13258 * the lower priority @env::dst_cpu help it. Do not follow 13259 * CPU priority. 13260 */ 13261 return env->idle && sched_use_asym_prio(env->sd, env->dst_cpu) && 13262 (sched_asym_prefer(env->dst_cpu, env->src_cpu) || 13263 !sched_use_asym_prio(env->sd, env->src_cpu)); 13264 } 13265 13266 static inline bool 13267 imbalanced_active_balance(struct lb_env *env) 13268 { 13269 struct sched_domain *sd = env->sd; 13270 13271 /* 13272 * The imbalanced case includes the case of pinned tasks preventing a fair 13273 * distribution of the load on the system but also the even distribution of the 13274 * threads on a system with spare capacity 13275 */ 13276 if ((env->migration_type == migrate_task) && 13277 (sd->nr_balance_failed > sd->cache_nice_tries+2)) 13278 return 1; 13279 13280 return 0; 13281 } 13282 13283 static int need_active_balance(struct lb_env *env) 13284 { 13285 struct sched_domain *sd = env->sd; 13286 13287 if (alb_break_llc(env)) 13288 return 0; 13289 13290 if (asym_active_balance(env)) 13291 return 1; 13292 13293 if (imbalanced_active_balance(env)) 13294 return 1; 13295 13296 /* 13297 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task. 13298 * It's worth migrating the task if the src_cpu's capacity is reduced 13299 * because of other sched_class or IRQs if more capacity stays 13300 * available on dst_cpu. 13301 */ 13302 if (env->idle && 13303 (env->src_rq->cfs.h_nr_runnable == 1)) { 13304 if ((check_cpu_capacity(env->src_rq, sd)) && 13305 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100)) 13306 return 1; 13307 } 13308 13309 if (env->migration_type == migrate_misfit || 13310 env->migration_type == migrate_llc_task) 13311 return 1; 13312 13313 return 0; 13314 } 13315 13316 static int active_load_balance_cpu_stop(void *data); 13317 13318 static int should_we_balance(struct lb_env *env) 13319 { 13320 struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask); 13321 struct sched_group *sg = env->sd->groups; 13322 int cpu, idle_smt = -1; 13323 13324 /* 13325 * Ensure the balancing environment is consistent; can happen 13326 * when the softirq triggers 'during' hotplug. 13327 */ 13328 if (!cpumask_test_cpu(env->dst_cpu, env->cpus)) 13329 return 0; 13330 13331 /* 13332 * In the newly idle case, we will allow all the CPUs 13333 * to do the newly idle load balance. 13334 * 13335 * However, we bail out if we already have tasks or a wakeup pending, 13336 * to optimize wakeup latency. 13337 */ 13338 if (env->idle == CPU_NEWLY_IDLE) { 13339 if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending) 13340 return 0; 13341 return 1; 13342 } 13343 13344 cpumask_copy(swb_cpus, group_balance_mask(sg)); 13345 /* Try to find first idle CPU */ 13346 for_each_cpu_and(cpu, swb_cpus, env->cpus) { 13347 if (!idle_cpu(cpu)) 13348 continue; 13349 13350 /* 13351 * Don't balance to idle SMT in busy core right away when 13352 * balancing cores, but remember the first idle SMT CPU for 13353 * later consideration. Find CPU on an idle core first. 13354 */ 13355 if (sched_smt_active() && 13356 !(env->sd->flags & SD_SHARE_CPUCAPACITY) && 13357 !is_core_idle(cpu)) { 13358 if (idle_smt == -1) 13359 idle_smt = cpu; 13360 /* 13361 * If the core is not idle, and first SMT sibling which is 13362 * idle has been found, then its not needed to check other 13363 * SMT siblings for idleness: 13364 */ 13365 cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu)); 13366 continue; 13367 } 13368 13369 /* 13370 * Are we the first idle core in a non-SMT domain or higher, 13371 * or the first idle CPU in a SMT domain? 13372 */ 13373 return cpu == env->dst_cpu; 13374 } 13375 13376 /* Are we the first idle CPU with busy siblings? */ 13377 if (idle_smt != -1) 13378 return idle_smt == env->dst_cpu; 13379 13380 /* Are we the first CPU of this group ? */ 13381 return group_balance_cpu(sg) == env->dst_cpu; 13382 } 13383 13384 static void update_lb_imbalance_stat(struct lb_env *env, struct sched_domain *sd, 13385 enum cpu_idle_type idle) 13386 { 13387 if (!schedstat_enabled()) 13388 return; 13389 13390 switch (env->migration_type) { 13391 case migrate_load: 13392 __schedstat_add(sd->lb_imbalance_load[idle], env->imbalance); 13393 break; 13394 case migrate_util: 13395 __schedstat_add(sd->lb_imbalance_util[idle], env->imbalance); 13396 break; 13397 case migrate_task: 13398 __schedstat_add(sd->lb_imbalance_task[idle], env->imbalance); 13399 break; 13400 case migrate_misfit: 13401 __schedstat_add(sd->lb_imbalance_misfit[idle], env->imbalance); 13402 break; 13403 case migrate_llc_task: 13404 break; 13405 } 13406 } 13407 13408 /* 13409 * This flag serializes load-balancing passes over large domains 13410 * (above the NODE topology level) - only one load-balancing instance 13411 * may run at a time, to reduce overhead on very large systems with 13412 * lots of CPUs and large NUMA distances. 13413 * 13414 * - Note that load-balancing passes triggered while another one 13415 * is executing are skipped and not re-tried. 13416 * 13417 * - Also note that this does not serialize rebalance_domains() 13418 * execution, as non-SD_SERIALIZE domains will still be 13419 * load-balanced in parallel. 13420 */ 13421 static atomic_t sched_balance_running = ATOMIC_INIT(0); 13422 13423 /* 13424 * Check this_cpu to ensure it is balanced within domain. Attempt to move 13425 * tasks if there is an imbalance. 13426 */ 13427 static int sched_balance_rq(int this_cpu, struct rq *this_rq, 13428 struct sched_domain *sd, enum cpu_idle_type idle, 13429 int *continue_balancing) 13430 { 13431 int ld_moved, cur_ld_moved, active_balance = 0; 13432 struct sched_domain *sd_parent = sd->parent; 13433 struct sched_group *group; 13434 struct rq *busiest; 13435 struct rq_flags rf; 13436 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask); 13437 struct lb_env env = { 13438 .sd = sd, 13439 .dst_cpu = this_cpu, 13440 .dst_rq = this_rq, 13441 .dst_grpmask = group_balance_mask(sd->groups), 13442 .idle = idle, 13443 .loop_break = SCHED_NR_MIGRATE_BREAK, 13444 .cpus = cpus, 13445 .fbq_type = all, 13446 .tasks = LIST_HEAD_INIT(env.tasks), 13447 }; 13448 bool need_unlock = false; 13449 13450 cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask); 13451 13452 schedstat_inc(sd->lb_count[idle]); 13453 13454 redo: 13455 if (!should_we_balance(&env)) { 13456 *continue_balancing = 0; 13457 goto out_balanced; 13458 } 13459 13460 if (!need_unlock && (sd->flags & SD_SERIALIZE)) { 13461 int zero = 0; 13462 if (!atomic_try_cmpxchg_acquire(&sched_balance_running, &zero, 1)) 13463 goto out_balanced; 13464 13465 need_unlock = true; 13466 } 13467 13468 group = sched_balance_find_src_group(&env); 13469 if (!group) { 13470 schedstat_inc(sd->lb_nobusyg[idle]); 13471 goto out_balanced; 13472 } 13473 13474 busiest = sched_balance_find_src_rq(&env, group); 13475 if (!busiest) { 13476 schedstat_inc(sd->lb_nobusyq[idle]); 13477 goto out_balanced; 13478 } 13479 13480 WARN_ON_ONCE(busiest == env.dst_rq); 13481 13482 update_lb_imbalance_stat(&env, sd, idle); 13483 13484 env.src_cpu = busiest->cpu; 13485 env.src_rq = busiest; 13486 13487 ld_moved = 0; 13488 /* Clear this flag as soon as we find a pullable task */ 13489 env.flags |= LBF_ALL_PINNED; 13490 if (busiest->nr_running > 1) { 13491 /* 13492 * Attempt to move tasks. If sched_balance_find_src_group has found 13493 * an imbalance but busiest->nr_running <= 1, the group is 13494 * still unbalanced. ld_moved simply stays zero, so it is 13495 * correctly treated as an imbalance. 13496 */ 13497 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running); 13498 13499 more_balance: 13500 rq_lock_irqsave(busiest, &rf); 13501 update_rq_clock(busiest); 13502 13503 /* 13504 * cur_ld_moved - load moved in current iteration 13505 * ld_moved - cumulative load moved across iterations 13506 */ 13507 cur_ld_moved = detach_tasks(&env); 13508 13509 /* 13510 * We've detached some tasks from busiest_rq. Every 13511 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely 13512 * unlock busiest->lock, and we are able to be sure 13513 * that nobody can manipulate the tasks in parallel. 13514 * See task_rq_lock() family for the details. 13515 */ 13516 13517 rq_unlock(busiest, &rf); 13518 13519 if (cur_ld_moved) { 13520 attach_tasks(&env); 13521 ld_moved += cur_ld_moved; 13522 } 13523 13524 local_irq_restore(rf.flags); 13525 13526 if (env.flags & LBF_NEED_BREAK) { 13527 env.flags &= ~LBF_NEED_BREAK; 13528 goto more_balance; 13529 } 13530 13531 /* 13532 * Revisit (affine) tasks on src_cpu that couldn't be moved to 13533 * us and move them to an alternate dst_cpu in our sched_group 13534 * where they can run. The upper limit on how many times we 13535 * iterate on same src_cpu is dependent on number of CPUs in our 13536 * sched_group. 13537 * 13538 * This changes load balance semantics a bit on who can move 13539 * load to a given_cpu. In addition to the given_cpu itself 13540 * (or a ilb_cpu acting on its behalf where given_cpu is 13541 * nohz-idle), we now have balance_cpu in a position to move 13542 * load to given_cpu. In rare situations, this may cause 13543 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding 13544 * _independently_ and at _same_ time to move some load to 13545 * given_cpu) causing excess load to be moved to given_cpu. 13546 * This however should not happen so much in practice and 13547 * moreover subsequent load balance cycles should correct the 13548 * excess load moved. 13549 */ 13550 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) { 13551 13552 /* Prevent to re-select dst_cpu via env's CPUs */ 13553 __cpumask_clear_cpu(env.dst_cpu, env.cpus); 13554 13555 env.dst_rq = cpu_rq(env.new_dst_cpu); 13556 env.dst_cpu = env.new_dst_cpu; 13557 env.flags &= ~LBF_DST_PINNED; 13558 env.loop = 0; 13559 env.loop_break = SCHED_NR_MIGRATE_BREAK; 13560 13561 /* 13562 * Go back to "more_balance" rather than "redo" since we 13563 * need to continue with same src_cpu. 13564 */ 13565 goto more_balance; 13566 } 13567 13568 /* 13569 * We failed to reach balance because of affinity. 13570 */ 13571 if (sd_parent) { 13572 int *group_imbalance = &sd_parent->groups->sgc->imbalance; 13573 13574 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0) 13575 *group_imbalance = 1; 13576 } 13577 13578 /* All tasks on this runqueue were pinned by CPU affinity */ 13579 if (unlikely(env.flags & LBF_ALL_PINNED)) { 13580 __cpumask_clear_cpu(cpu_of(busiest), cpus); 13581 /* 13582 * Attempting to continue load balancing at the current 13583 * sched_domain level only makes sense if there are 13584 * active CPUs remaining as possible busiest CPUs to 13585 * pull load from which are not contained within the 13586 * destination group that is receiving any migrated 13587 * load. 13588 */ 13589 if (!cpumask_subset(cpus, env.dst_grpmask)) { 13590 env.loop = 0; 13591 env.loop_break = SCHED_NR_MIGRATE_BREAK; 13592 goto redo; 13593 } 13594 goto out_all_pinned; 13595 } 13596 } 13597 13598 if (ld_moved) { 13599 sd->nr_balance_failed = 0; 13600 goto out_unbalanced; 13601 } 13602 13603 schedstat_inc(sd->lb_failed[idle]); 13604 /* 13605 * Increment the failure counter only on periodic balance. 13606 * We do not want newidle balance, which can be very 13607 * frequent, pollute the failure counter causing 13608 * excessive cache_hot migrations and active balances. 13609 * 13610 * Similarly for migration_misfit which is not related to 13611 * load/util migration, don't pollute nr_balance_failed. 13612 * 13613 * The same for cache aware scheduling's allowance for 13614 * load imbalance. If regular load balance does not 13615 * migrate task due to LLC locality, it is a expected 13616 * behavior and don't pollute nr_balance_failed. 13617 * See can_migrate_task(). 13618 */ 13619 if (idle != CPU_NEWLY_IDLE && 13620 env.migration_type != migrate_misfit && 13621 !(env.flags & LBF_LLC_PINNED)) 13622 sd->nr_balance_failed++; 13623 13624 if (!need_active_balance(&env)) 13625 goto out_unbalanced; 13626 13627 scoped_guard (raw_spin_rq_lock_irqsave, busiest) { 13628 /* 13629 * Don't kick the active_load_balance_cpu_stop, 13630 * if the curr task on busiest CPU can't be 13631 * moved to this_cpu: 13632 */ 13633 if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) 13634 goto out_one_pinned; 13635 13636 /* Record that we found at least one task that could run on this_cpu */ 13637 env.flags &= ~LBF_ALL_PINNED; 13638 13639 /* 13640 * ->active_balance synchronizes accesses to 13641 * ->active_balance_work. Once set, it's cleared 13642 * only after active load balance is finished. 13643 */ 13644 if (busiest->active_balance) 13645 goto out_unbalanced; 13646 13647 /* 13648 * @busiest dropped its rq_lock in the middle of 13649 * scheduling out its ->curr task (->on_rq := 0), no 13650 * need to forcefully punt it away with active balance. 13651 */ 13652 if (!busiest->curr->on_rq) 13653 goto out_unbalanced; 13654 13655 busiest->active_balance = 1; 13656 busiest->push_cpu = this_cpu; 13657 active_balance = 1; 13658 preempt_disable(); 13659 } 13660 if (active_balance) { 13661 stop_one_cpu_nowait(cpu_of(busiest), 13662 active_load_balance_cpu_stop, busiest, 13663 &busiest->active_balance_work); 13664 } 13665 preempt_enable(); 13666 13667 out_unbalanced: 13668 /* We were unbalanced, so reset the balancing interval */ 13669 sd->balance_interval = sd->min_interval; 13670 goto out; 13671 13672 out_balanced: 13673 /* 13674 * We reach balance although we may have faced some affinity 13675 * constraints. Clear the imbalance flag only if other tasks got 13676 * a chance to move and fix the imbalance. 13677 */ 13678 if (sd_parent && !(env.flags & LBF_ALL_PINNED)) { 13679 int *group_imbalance = &sd_parent->groups->sgc->imbalance; 13680 13681 if (*group_imbalance) 13682 *group_imbalance = 0; 13683 } 13684 13685 out_all_pinned: 13686 /* 13687 * We reach balance because all tasks are pinned at this level so 13688 * we can't migrate them. Let the imbalance flag set so parent level 13689 * can try to migrate them. 13690 */ 13691 schedstat_inc(sd->lb_balanced[idle]); 13692 13693 sd->nr_balance_failed = 0; 13694 13695 out_one_pinned: 13696 ld_moved = 0; 13697 13698 /* 13699 * sched_balance_newidle() disregards balance intervals, so we could 13700 * repeatedly reach this code, which would lead to balance_interval 13701 * skyrocketing in a short amount of time. Skip the balance_interval 13702 * increase logic to avoid that. 13703 * 13704 * Similarly misfit migration which is not necessarily an indication of 13705 * the system being busy and requires lb to backoff to let it settle 13706 * down. 13707 */ 13708 if (env.idle == CPU_NEWLY_IDLE || 13709 env.migration_type == migrate_misfit) 13710 goto out; 13711 13712 /* tune up the balancing interval */ 13713 if ((env.flags & LBF_ALL_PINNED && 13714 sd->balance_interval < MAX_PINNED_INTERVAL) || 13715 sd->balance_interval < sd->max_interval) 13716 sd->balance_interval *= 2; 13717 out: 13718 if (need_unlock) 13719 atomic_set_release(&sched_balance_running, 0); 13720 13721 return ld_moved; 13722 } 13723 13724 static inline unsigned long 13725 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy) 13726 { 13727 unsigned long interval = sd->balance_interval; 13728 13729 if (cpu_busy) 13730 interval *= sd->busy_factor; 13731 13732 /* scale ms to jiffies */ 13733 interval = msecs_to_jiffies(interval); 13734 13735 /* 13736 * Reduce likelihood of busy balancing at higher domains racing with 13737 * balancing at lower domains by preventing their balancing periods 13738 * from being multiples of each other. 13739 */ 13740 if (cpu_busy) 13741 interval -= 1; 13742 13743 interval = clamp(interval, 1UL, max_load_balance_interval); 13744 13745 return interval; 13746 } 13747 13748 static inline void 13749 update_next_balance(struct sched_domain *sd, unsigned long *next_balance) 13750 { 13751 unsigned long interval, next; 13752 13753 /* used by idle balance, so cpu_busy = 0 */ 13754 interval = get_sd_balance_interval(sd, 0); 13755 next = sd->last_balance + interval; 13756 13757 if (time_after(*next_balance, next)) 13758 *next_balance = next; 13759 } 13760 13761 /* 13762 * active_load_balance_cpu_stop is run by the CPU stopper. It pushes 13763 * running tasks off the busiest CPU onto idle CPUs. It requires at 13764 * least 1 task to be running on each physical CPU where possible, and 13765 * avoids physical / logical imbalances. 13766 */ 13767 static int active_load_balance_cpu_stop(void *data) 13768 { 13769 struct rq *busiest_rq = data; 13770 int busiest_cpu = cpu_of(busiest_rq); 13771 int target_cpu = busiest_rq->push_cpu; 13772 struct rq *target_rq = cpu_rq(target_cpu); 13773 struct sched_domain *sd; 13774 struct task_struct *p = NULL; 13775 struct rq_flags rf; 13776 13777 rq_lock_irq(busiest_rq, &rf); 13778 /* 13779 * Between queueing the stop-work and running it is a hole in which 13780 * CPUs can become inactive. We should not move tasks from or to 13781 * inactive CPUs. 13782 */ 13783 if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu)) 13784 goto out_unlock; 13785 13786 /* Make sure the requested CPU hasn't gone down in the meantime: */ 13787 if (unlikely(busiest_cpu != smp_processor_id() || 13788 !busiest_rq->active_balance)) 13789 goto out_unlock; 13790 13791 /* Is there any task to move? */ 13792 if (busiest_rq->nr_running <= 1) 13793 goto out_unlock; 13794 13795 /* 13796 * This condition is "impossible", if it occurs 13797 * we need to fix it. Originally reported by 13798 * Bjorn Helgaas on a 128-CPU setup. 13799 */ 13800 WARN_ON_ONCE(busiest_rq == target_rq); 13801 13802 /* Search for an sd spanning us and the target CPU. */ 13803 rcu_read_lock(); 13804 for_each_domain(target_cpu, sd) { 13805 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd))) 13806 break; 13807 } 13808 13809 if (likely(sd)) { 13810 struct lb_env env = { 13811 .sd = sd, 13812 .dst_cpu = target_cpu, 13813 .dst_rq = target_rq, 13814 .src_cpu = busiest_rq->cpu, 13815 .src_rq = busiest_rq, 13816 .idle = CPU_IDLE, 13817 .flags = LBF_ACTIVE_LB, 13818 }; 13819 13820 schedstat_inc(sd->alb_count); 13821 update_rq_clock(busiest_rq); 13822 13823 p = detach_one_task(&env); 13824 if (p) { 13825 schedstat_inc(sd->alb_pushed); 13826 /* Active balancing done, reset the failure counter. */ 13827 sd->nr_balance_failed = 0; 13828 } else { 13829 schedstat_inc(sd->alb_failed); 13830 } 13831 } 13832 rcu_read_unlock(); 13833 out_unlock: 13834 busiest_rq->active_balance = 0; 13835 rq_unlock(busiest_rq, &rf); 13836 13837 if (p) 13838 attach_one_task(target_rq, p); 13839 13840 local_irq_enable(); 13841 13842 return 0; 13843 } 13844 13845 /* 13846 * Scale the max sched_balance_rq interval with the number of CPUs in the system. 13847 * This trades load-balance latency on larger machines for less cross talk. 13848 */ 13849 void update_max_interval(void) 13850 { 13851 max_load_balance_interval = HZ*num_online_cpus()/10; 13852 } 13853 13854 static inline void update_newidle_stats(struct sched_domain *sd, unsigned int success) 13855 { 13856 sd->newidle_call++; 13857 sd->newidle_success += success; 13858 13859 if (sd->newidle_call >= 1024) { 13860 u64 now = sched_clock(); 13861 s64 delta = now - sd->newidle_stamp; 13862 sd->newidle_stamp = now; 13863 int ratio = 0; 13864 13865 if (delta < 0) 13866 delta = 0; 13867 13868 if (sched_feat(NI_RATE)) { 13869 /* 13870 * ratio delta freq 13871 * 13872 * 1024 - 4 s - 128 Hz 13873 * 512 - 2 s - 256 Hz 13874 * 256 - 1 s - 512 Hz 13875 * 128 - .5 s - 1024 Hz 13876 * 64 - .25 s - 2048 Hz 13877 */ 13878 ratio = delta >> 22; 13879 } 13880 13881 ratio += sd->newidle_success; 13882 13883 sd->newidle_ratio = min(1024, ratio); 13884 sd->newidle_call /= 2; 13885 sd->newidle_success /= 2; 13886 } 13887 } 13888 13889 static inline bool 13890 update_newidle_cost(struct sched_domain *sd, u64 cost, unsigned int success) 13891 { 13892 unsigned long next_decay = sd->last_decay_max_lb_cost + HZ; 13893 unsigned long now = jiffies; 13894 13895 if (cost) 13896 update_newidle_stats(sd, success); 13897 13898 if (cost > sd->max_newidle_lb_cost) { 13899 /* 13900 * Track max cost of a domain to make sure to not delay the 13901 * next wakeup on the CPU. 13902 */ 13903 sd->max_newidle_lb_cost = cost; 13904 sd->last_decay_max_lb_cost = now; 13905 13906 } else if (time_after(now, next_decay)) { 13907 /* 13908 * Decay the newidle max times by ~1% per second to ensure that 13909 * it is not outdated and the current max cost is actually 13910 * shorter. 13911 */ 13912 sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256; 13913 sd->last_decay_max_lb_cost = now; 13914 return true; 13915 } 13916 13917 return false; 13918 } 13919 13920 /* 13921 * It checks each scheduling domain to see if it is due to be balanced, 13922 * and initiates a balancing operation if so. 13923 * 13924 * Balancing parameters are set up in init_sched_domains. 13925 */ 13926 static void sched_balance_domains(struct rq *rq, enum cpu_idle_type idle) 13927 { 13928 int continue_balancing = 1; 13929 int cpu = rq->cpu; 13930 int busy = idle != CPU_IDLE && !sched_idle_rq(rq); 13931 unsigned long interval; 13932 struct sched_domain *sd; 13933 /* Earliest time when we have to do rebalance again */ 13934 unsigned long next_balance = jiffies + 60*HZ; 13935 int update_next_balance = 0; 13936 int need_decay = 0; 13937 u64 max_cost = 0; 13938 13939 rcu_read_lock(); 13940 for_each_domain(cpu, sd) { 13941 /* 13942 * Decay the newidle max times here because this is a regular 13943 * visit to all the domains. 13944 */ 13945 need_decay = update_newidle_cost(sd, 0, 0); 13946 max_cost += sd->max_newidle_lb_cost; 13947 13948 /* 13949 * Stop the load balance at this level. There is another 13950 * CPU in our sched group which is doing load balancing more 13951 * actively. 13952 */ 13953 if (!continue_balancing) { 13954 if (need_decay) 13955 continue; 13956 break; 13957 } 13958 13959 interval = get_sd_balance_interval(sd, busy); 13960 if (time_after_eq(jiffies, sd->last_balance + interval)) { 13961 if (sched_balance_rq(cpu, rq, sd, idle, &continue_balancing)) { 13962 /* 13963 * The LBF_DST_PINNED logic could have changed 13964 * env->dst_cpu, so we can't know our idle 13965 * state even if we migrated tasks. Update it. 13966 */ 13967 idle = idle_cpu(cpu); 13968 busy = !idle && !sched_idle_rq(rq); 13969 } 13970 sd->last_balance = jiffies; 13971 interval = get_sd_balance_interval(sd, busy); 13972 } 13973 if (time_after(next_balance, sd->last_balance + interval)) { 13974 next_balance = sd->last_balance + interval; 13975 update_next_balance = 1; 13976 } 13977 } 13978 if (need_decay) { 13979 /* 13980 * Ensure the rq-wide value also decays but keep it at a 13981 * reasonable floor to avoid funnies with rq->avg_idle. 13982 */ 13983 rq->max_idle_balance_cost = 13984 max((u64)sysctl_sched_migration_cost, max_cost); 13985 } 13986 rcu_read_unlock(); 13987 13988 /* 13989 * next_balance will be updated only when there is a need. 13990 * When the cpu is attached to null domain for ex, it will not be 13991 * updated. 13992 */ 13993 if (likely(update_next_balance)) 13994 rq->next_balance = next_balance; 13995 13996 } 13997 13998 static inline int on_null_domain(struct rq *rq) 13999 { 14000 return unlikely(!rcu_dereference_sched(rq->sd)); 14001 } 14002 14003 #ifdef CONFIG_NO_HZ_COMMON 14004 /* 14005 * NOHZ idle load balancing (ILB) details: 14006 * 14007 * - When one of the busy CPUs notices that there may be an idle rebalancing 14008 * needed, they will kick the idle load balancer, which then does idle 14009 * load balancing for all the idle CPUs. 14010 */ 14011 static inline int find_new_ilb(void) 14012 { 14013 struct cpumask *ilb_cpus; 14014 int ilb_cpu, fallback = -1; 14015 14016 lockdep_assert_irqs_disabled(); 14017 14018 /* 14019 * Reuse the per-CPU select_rq_mask, which is protected from concurrent 14020 * use on this CPU by having interrupts disabled. 14021 */ 14022 ilb_cpus = this_cpu_cpumask_var_ptr(select_rq_mask); 14023 cpumask_and(ilb_cpus, nohz.idle_cpus_mask, 14024 housekeeping_cpumask(HK_TYPE_KERNEL_NOISE)); 14025 14026 for_each_cpu(ilb_cpu, ilb_cpus) { 14027 if (!idle_cpu(ilb_cpu)) { 14028 /* 14029 * Once an idle fallback exists, a busy CPU proves that 14030 * this core cannot be fully idle. Skip its siblings. 14031 */ 14032 if (sched_smt_active() && fallback >= 0) 14033 cpumask_andnot(ilb_cpus, ilb_cpus, cpu_smt_mask(ilb_cpu)); 14034 continue; 14035 } 14036 14037 /* 14038 * Running the idle load balancer on an idle sibling of a busy 14039 * SMT core can reduce the capacity available to its sibling. Prefer 14040 * a CPU whose entire core is idle, but retain the first idle CPU as 14041 * a fallback so idle balancing can still make progress when no fully 14042 * idle core exists. 14043 */ 14044 if (sched_smt_active() && !is_core_idle(ilb_cpu)) { 14045 if (fallback < 0) 14046 fallback = ilb_cpu; 14047 14048 /* 14049 * The core is not idle, so there is no need to check 14050 * any of its other SMT siblings. 14051 */ 14052 cpumask_andnot(ilb_cpus, ilb_cpus, 14053 cpu_smt_mask(ilb_cpu)); 14054 continue; 14055 } 14056 14057 return ilb_cpu; 14058 } 14059 14060 return fallback; 14061 } 14062 14063 /* 14064 * Kick a CPU to do the NOHZ balancing, if it is time for it, via a cross-CPU 14065 * SMP function call (IPI). 14066 * 14067 * Prefer a CPU on a fully idle core in the HK_TYPE_KERNEL_NOISE housekeeping 14068 * set. Fall back to the first idle CPU when no fully idle core exists. 14069 */ 14070 static void kick_ilb(unsigned int flags) 14071 { 14072 int ilb_cpu; 14073 14074 /* 14075 * Increase nohz.next_balance only when if full ilb is triggered but 14076 * not if we only update stats. 14077 */ 14078 if (flags & NOHZ_BALANCE_KICK) 14079 nohz.next_balance = jiffies+1; 14080 14081 ilb_cpu = find_new_ilb(); 14082 if (ilb_cpu < 0) 14083 return; 14084 14085 /* 14086 * Don't bother if no new NOHZ balance work items for ilb_cpu, 14087 * i.e. all bits in flags are already set in ilb_cpu. 14088 */ 14089 if ((atomic_read(nohz_flags(ilb_cpu)) & flags) == flags) 14090 return; 14091 14092 /* 14093 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets 14094 * the first flag owns it; cleared by nohz_csd_func(). 14095 */ 14096 flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu)); 14097 if (flags & NOHZ_KICK_MASK) 14098 return; 14099 14100 /* 14101 * This way we generate an IPI on the target CPU which 14102 * is idle, and the softirq performing NOHZ idle load balancing 14103 * will be run before returning from the IPI. 14104 */ 14105 smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd); 14106 } 14107 14108 /* 14109 * Current decision point for kicking the idle load balancer in the presence 14110 * of idle CPUs in the system. 14111 */ 14112 static void nohz_balancer_kick(struct rq *rq) 14113 { 14114 unsigned long now = jiffies; 14115 struct sched_domain_shared *sds; 14116 struct sched_domain *sd; 14117 int nr_busy, i, cpu = rq->cpu; 14118 unsigned int flags = 0; 14119 14120 if (unlikely(rq->idle_balance)) 14121 return; 14122 14123 /* 14124 * We may be recently in ticked or tickless idle mode. At the first 14125 * busy tick after returning from idle, we will update the busy stats. 14126 */ 14127 nohz_balance_exit_idle(rq); 14128 14129 if (READ_ONCE(nohz.has_blocked_load) && 14130 time_after(now, READ_ONCE(nohz.next_blocked))) 14131 flags = NOHZ_STATS_KICK; 14132 14133 /* 14134 * Most of the time system is not 100% busy. i.e nohz.nr_cpus > 0 14135 * Skip the read if time is not due. 14136 * 14137 * If none are in tickless mode, there maybe a narrow window 14138 * (28 jiffies, HZ=1000) where flags maybe set and kick_ilb called. 14139 * But idle load balancing is not done as find_new_ilb fails. 14140 * That's very rare. So read nohz.nr_cpus only if time is due. 14141 */ 14142 if (time_before(now, nohz.next_balance)) 14143 goto out; 14144 14145 /* 14146 * None are in tickless mode and hence no need for NOHZ idle load 14147 * balancing 14148 */ 14149 if (unlikely(cpumask_empty(nohz.idle_cpus_mask))) 14150 return; 14151 14152 if (rq->nr_running >= 2) { 14153 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 14154 goto out; 14155 } 14156 14157 sd = rcu_dereference_all(rq->sd); 14158 if (sd) { 14159 /* 14160 * If there's a runnable CFS task and the current CPU has reduced 14161 * capacity, kick the ILB to see if there's a better CPU to run on: 14162 */ 14163 if (rq->cfs.h_nr_runnable >= 1 && check_cpu_capacity(rq, sd)) { 14164 flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 14165 goto out; 14166 } 14167 } 14168 14169 sd = rcu_dereference_all(per_cpu(sd_asym_packing, cpu)); 14170 if (sd) { 14171 /* 14172 * When ASYM_PACKING; see if there's a more preferred CPU 14173 * currently idle; in which case, kick the ILB to move tasks 14174 * around. 14175 * 14176 * When balancing between cores, all the SMT siblings of the 14177 * preferred CPU must be idle. 14178 */ 14179 for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) { 14180 if (sched_asym(sd, i, cpu)) { 14181 flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 14182 goto out; 14183 } 14184 } 14185 } 14186 14187 sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, cpu)); 14188 if (sd) { 14189 /* 14190 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU 14191 * to run the misfit task on. 14192 */ 14193 if (check_misfit_status(rq)) 14194 flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 14195 14196 /* 14197 * For asymmetric systems, we do not want to nicely balance 14198 * cache use, instead we want to embrace asymmetry and only 14199 * ensure tasks have enough CPU capacity. 14200 * 14201 * Skip the LLC logic because it's not relevant in that case. 14202 */ 14203 goto out; 14204 } 14205 14206 sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu)); 14207 if (sds) { 14208 /* 14209 * If there is an imbalance between LLC domains (IOW we could 14210 * increase the overall cache utilization), we need a less-loaded LLC 14211 * domain to pull some load from. Likewise, we may need to spread 14212 * load within the current LLC domain (e.g. packed SMT cores but 14213 * other CPUs are idle). We can't really know from here how busy 14214 * the others are - so just get a NOHZ balance going if it looks 14215 * like this LLC domain has tasks we could move. 14216 */ 14217 nr_busy = atomic_read(&sds->nr_busy_cpus); 14218 if (nr_busy > 1) 14219 flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 14220 } 14221 out: 14222 if (READ_ONCE(nohz.needs_update)) 14223 flags |= NOHZ_NEXT_KICK; 14224 14225 if (flags) 14226 kick_ilb(flags); 14227 } 14228 14229 static void set_cpu_sd_state_busy(int cpu) 14230 { 14231 struct sched_domain *sd; 14232 sd = rcu_dereference_all(per_cpu(sd_llc, cpu)); 14233 14234 /* 14235 * sd->nohz_idle only pairs with nr_busy_cpus on sd->shared; if this 14236 * domain has no shared object there is nothing to clear or account. 14237 */ 14238 if (!sd || !sd->shared || !sd->nohz_idle) 14239 return; 14240 sd->nohz_idle = 0; 14241 14242 atomic_inc(&sd->shared->nr_busy_cpus); 14243 } 14244 14245 void nohz_balance_exit_idle(struct rq *rq) 14246 { 14247 WARN_ON_ONCE(rq != this_rq()); 14248 14249 if (likely(!rq->nohz_tick_stopped)) 14250 return; 14251 14252 rq->nohz_tick_stopped = 0; 14253 cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask); 14254 14255 set_cpu_sd_state_busy(rq->cpu); 14256 } 14257 14258 static void set_cpu_sd_state_idle(int cpu) 14259 { 14260 struct sched_domain *sd; 14261 sd = rcu_dereference_all(per_cpu(sd_llc, cpu)); 14262 14263 /* See set_cpu_sd_state_busy(): nohz_idle is only used with sd->shared. */ 14264 if (!sd || !sd->shared || sd->nohz_idle) 14265 return; 14266 sd->nohz_idle = 1; 14267 14268 atomic_dec(&sd->shared->nr_busy_cpus); 14269 } 14270 14271 /* 14272 * This routine will record that the CPU is going idle with tick stopped. 14273 * This info will be used in performing idle load balancing in the future. 14274 */ 14275 void nohz_balance_enter_idle(int cpu) 14276 { 14277 struct rq *rq = cpu_rq(cpu); 14278 14279 WARN_ON_ONCE(cpu != smp_processor_id()); 14280 14281 /* If this CPU is going down, then nothing needs to be done: */ 14282 if (!cpu_active(cpu)) 14283 return; 14284 14285 /* 14286 * Can be set safely without rq->lock held 14287 * If a clear happens, it will have evaluated last additions because 14288 * rq->lock is held during the check and the clear 14289 */ 14290 rq->has_blocked_load = 1; 14291 14292 /* 14293 * The tick is still stopped but load could have been added in the 14294 * meantime. We set the nohz.has_blocked_load flag to trig a check of the 14295 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear 14296 * of nohz.has_blocked_load can only happen after checking the new load 14297 */ 14298 if (rq->nohz_tick_stopped) 14299 goto out; 14300 14301 /* If we're a completely isolated CPU, we don't play: */ 14302 if (on_null_domain(rq)) 14303 return; 14304 14305 rq->nohz_tick_stopped = 1; 14306 14307 cpumask_set_cpu(cpu, nohz.idle_cpus_mask); 14308 14309 /* 14310 * Ensures that if nohz_idle_balance() fails to observe our 14311 * @idle_cpus_mask store, it must observe the @has_blocked_load 14312 * and @needs_update stores. 14313 */ 14314 smp_mb__after_atomic(); 14315 14316 set_cpu_sd_state_idle(cpu); 14317 14318 WRITE_ONCE(nohz.needs_update, 1); 14319 out: 14320 /* 14321 * Each time a cpu enter idle, we assume that it has blocked load and 14322 * enable the periodic update of the load of idle CPUs 14323 */ 14324 WRITE_ONCE(nohz.has_blocked_load, 1); 14325 } 14326 14327 static bool update_nohz_stats(struct rq *rq) 14328 { 14329 unsigned int cpu = rq->cpu; 14330 14331 if (!rq->has_blocked_load) 14332 return false; 14333 14334 if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask)) 14335 return false; 14336 14337 if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick))) 14338 return true; 14339 14340 sched_balance_update_blocked_averages(cpu); 14341 14342 return rq->has_blocked_load; 14343 } 14344 14345 /* 14346 * Internal function that runs load balance for all idle CPUs. The load balance 14347 * can be a simple update of blocked load or a complete load balance with 14348 * tasks movement depending of flags. 14349 */ 14350 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags) 14351 { 14352 /* Earliest time when we have to do rebalance again */ 14353 unsigned long now = jiffies; 14354 unsigned long next_balance = now + 60*HZ; 14355 bool has_blocked_load = false; 14356 int update_next_balance = 0; 14357 int this_cpu = this_rq->cpu; 14358 int balance_cpu; 14359 struct rq *rq; 14360 14361 WARN_ON_ONCE((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK); 14362 14363 /* 14364 * We assume there will be no idle load after this update and clear 14365 * the has_blocked_load flag. If a cpu enters idle in the mean time, it will 14366 * set the has_blocked_load flag and trigger another update of idle load. 14367 * Because a cpu that becomes idle, is added to idle_cpus_mask before 14368 * setting the flag, we are sure to not clear the state and not 14369 * check the load of an idle cpu. 14370 * 14371 * Same applies to idle_cpus_mask vs needs_update. 14372 */ 14373 if (flags & NOHZ_STATS_KICK) 14374 WRITE_ONCE(nohz.has_blocked_load, 0); 14375 if (flags & NOHZ_NEXT_KICK) 14376 WRITE_ONCE(nohz.needs_update, 0); 14377 14378 /* 14379 * Ensures that if we miss the CPU, we must see the has_blocked_load 14380 * store from nohz_balance_enter_idle(). 14381 */ 14382 smp_mb(); 14383 14384 /* 14385 * Start with the next CPU after this_cpu so we will end with this_cpu and let a 14386 * chance for other idle cpu to pull load. 14387 */ 14388 for_each_cpu_wrap(balance_cpu, nohz.idle_cpus_mask, this_cpu+1) { 14389 if (!idle_cpu(balance_cpu)) 14390 continue; 14391 14392 /* 14393 * If this CPU gets work to do, stop the load balancing 14394 * work being done for other CPUs. Next load 14395 * balancing owner will pick it up. 14396 */ 14397 if (!idle_cpu(this_cpu) && need_resched()) { 14398 if (flags & NOHZ_STATS_KICK) 14399 has_blocked_load = true; 14400 if (flags & NOHZ_NEXT_KICK) 14401 WRITE_ONCE(nohz.needs_update, 1); 14402 goto abort; 14403 } 14404 14405 rq = cpu_rq(balance_cpu); 14406 14407 if (flags & NOHZ_STATS_KICK) 14408 has_blocked_load |= update_nohz_stats(rq); 14409 14410 /* 14411 * If time for next balance is due, 14412 * do the balance. 14413 */ 14414 if (time_after_eq(jiffies, rq->next_balance)) { 14415 struct rq_flags rf; 14416 14417 rq_lock_irqsave(rq, &rf); 14418 update_rq_clock(rq); 14419 rq_unlock_irqrestore(rq, &rf); 14420 14421 if (flags & NOHZ_BALANCE_KICK) 14422 sched_balance_domains(rq, CPU_IDLE); 14423 } 14424 14425 if (time_after(next_balance, rq->next_balance)) { 14426 next_balance = rq->next_balance; 14427 update_next_balance = 1; 14428 } 14429 } 14430 14431 /* 14432 * next_balance will be updated only when there is a need. 14433 * When the CPU is attached to null domain for ex, it will not be 14434 * updated. 14435 */ 14436 if (likely(update_next_balance)) 14437 nohz.next_balance = next_balance; 14438 14439 if (flags & NOHZ_STATS_KICK) 14440 WRITE_ONCE(nohz.next_blocked, 14441 now + msecs_to_jiffies(LOAD_AVG_PERIOD)); 14442 14443 abort: 14444 /* There is still blocked load, enable periodic update */ 14445 if (has_blocked_load) 14446 WRITE_ONCE(nohz.has_blocked_load, 1); 14447 } 14448 14449 /* 14450 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the 14451 * rebalancing for all the CPUs for whom scheduler ticks are stopped. 14452 */ 14453 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) 14454 { 14455 unsigned int flags = this_rq->nohz_idle_balance; 14456 14457 if (!flags) 14458 return false; 14459 14460 this_rq->nohz_idle_balance = 0; 14461 14462 if (idle != CPU_IDLE) 14463 return false; 14464 14465 _nohz_idle_balance(this_rq, flags); 14466 14467 return true; 14468 } 14469 14470 /* 14471 * Check if we need to directly run the ILB for updating blocked load before 14472 * entering idle state. Here we run ILB directly without issuing IPIs. 14473 * 14474 * Note that when this function is called, the tick may not yet be stopped on 14475 * this CPU yet. nohz.idle_cpus_mask is updated only when tick is stopped and 14476 * cleared on the next busy tick. In other words, nohz.idle_cpus_mask updates 14477 * don't align with CPUs enter/exit idle to avoid bottlenecks due to high idle 14478 * entry/exit rate (usec). So it is possible that _nohz_idle_balance() is 14479 * called from this function on (this) CPU that's not yet in the mask. That's 14480 * OK because the goal of nohz_run_idle_balance() is to run ILB only for 14481 * updating the blocked load of already idle CPUs without waking up one of 14482 * those idle CPUs and outside the preempt disable / IRQ off phase of the local 14483 * cpu about to enter idle, because it can take a long time. 14484 */ 14485 void nohz_run_idle_balance(int cpu) 14486 { 14487 unsigned int flags; 14488 14489 flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu)); 14490 14491 /* 14492 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen 14493 * (i.e. NOHZ_STATS_KICK set) and will do the same. 14494 */ 14495 if ((flags == NOHZ_NEWILB_KICK) && !need_resched()) 14496 _nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK); 14497 } 14498 14499 static void nohz_newidle_balance(struct rq *this_rq) 14500 { 14501 int this_cpu = this_rq->cpu; 14502 14503 /* Will wake up very soon. No time for doing anything else*/ 14504 if (this_rq->avg_idle < sysctl_sched_migration_cost) 14505 return; 14506 14507 /* Don't need to update blocked load of idle CPUs*/ 14508 if (!READ_ONCE(nohz.has_blocked_load) || 14509 time_before(jiffies, READ_ONCE(nohz.next_blocked))) 14510 return; 14511 14512 /* 14513 * Set the need to trigger ILB in order to update blocked load 14514 * before entering idle state. 14515 */ 14516 atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu)); 14517 } 14518 14519 #else /* !CONFIG_NO_HZ_COMMON: */ 14520 static inline void nohz_balancer_kick(struct rq *rq) { } 14521 14522 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) 14523 { 14524 return false; 14525 } 14526 14527 static inline void nohz_newidle_balance(struct rq *this_rq) { } 14528 #endif /* !CONFIG_NO_HZ_COMMON */ 14529 14530 /* 14531 * sched_balance_newidle is called by schedule() if this_cpu is about to become 14532 * idle. Attempts to pull tasks from other CPUs. 14533 * 14534 * Returns: 14535 * < 0 - we released the lock and there are !fair tasks present 14536 * 0 - failed, no new tasks 14537 * > 0 - success, new (fair) tasks present 14538 */ 14539 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf) 14540 __must_hold(__rq_lockp(this_rq)) 14541 { 14542 unsigned long next_balance = jiffies + HZ; 14543 int this_cpu = this_rq->cpu; 14544 int continue_balancing = 1; 14545 u64 t0, t1, curr_cost = 0; 14546 struct sched_domain *sd; 14547 int pulled_task = 0; 14548 14549 update_misfit_status(NULL, this_rq); 14550 14551 /* 14552 * There is a task waiting to run. No need to search for one. 14553 * Return 0; the task will be enqueued when switching to idle. 14554 */ 14555 if (this_rq->ttwu_pending) 14556 return 0; 14557 14558 /* 14559 * We must set idle_stamp _before_ calling sched_balance_rq() 14560 * for CPU_NEWLY_IDLE, such that we measure the this duration 14561 * as idle time. 14562 */ 14563 this_rq->idle_stamp = rq_clock(this_rq); 14564 14565 /* 14566 * Do not pull tasks towards !active CPUs... 14567 */ 14568 if (!cpu_active(this_cpu)) 14569 return 0; 14570 14571 /* 14572 * This is OK, because current is on_cpu, which avoids it being picked 14573 * for load-balance and preemption/IRQs are still disabled avoiding 14574 * further scheduler activity on it and we're being very careful to 14575 * re-start the picking loop. 14576 */ 14577 rq_unpin_lock(this_rq, rf); 14578 14579 sd = rcu_dereference_sched_domain(this_rq->sd); 14580 if (!sd) 14581 goto out; 14582 14583 if (!get_rd_overloaded(this_rq->rd) || 14584 this_rq->avg_idle < sd->max_newidle_lb_cost) { 14585 14586 update_next_balance(sd, &next_balance); 14587 goto out; 14588 } 14589 14590 /* 14591 * Include sched_balance_update_blocked_averages() in the cost 14592 * calculation because it can be quite costly -- this ensures we skip 14593 * it when avg_idle gets to be very low. 14594 */ 14595 t0 = sched_clock_cpu(this_cpu); 14596 __sched_balance_update_blocked_averages(this_rq); 14597 14598 rq_modified_begin(this_rq, &fair_sched_class); 14599 raw_spin_rq_unlock(this_rq); 14600 14601 for_each_domain(this_cpu, sd) { 14602 u64 domain_cost; 14603 14604 update_next_balance(sd, &next_balance); 14605 14606 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) 14607 break; 14608 14609 if (sd->flags & SD_BALANCE_NEWIDLE) { 14610 unsigned int weight = 1; 14611 14612 if (sched_feat(NI_RANDOM) && sd->newidle_ratio < 1024) { 14613 /* 14614 * Throw a 1k sided dice; and only run 14615 * newidle_balance according to the success 14616 * rate. 14617 */ 14618 u32 d1k = sched_rng() % 1024; 14619 weight = 1 + sd->newidle_ratio; 14620 if (d1k > weight) { 14621 update_newidle_stats(sd, 0); 14622 continue; 14623 } 14624 weight = (1024 + weight/2) / weight; 14625 } 14626 14627 pulled_task = sched_balance_rq(this_cpu, this_rq, 14628 sd, CPU_NEWLY_IDLE, 14629 &continue_balancing); 14630 14631 t1 = sched_clock_cpu(this_cpu); 14632 domain_cost = t1 - t0; 14633 curr_cost += domain_cost; 14634 t0 = t1; 14635 14636 /* 14637 * Track max cost of a domain to make sure to not delay the 14638 * next wakeup on the CPU. 14639 */ 14640 update_newidle_cost(sd, domain_cost, weight * !!pulled_task); 14641 } 14642 14643 /* 14644 * Stop searching for tasks to pull if there are 14645 * now runnable tasks on this rq. 14646 */ 14647 if (pulled_task || !continue_balancing) 14648 break; 14649 } 14650 14651 raw_spin_rq_lock(this_rq); 14652 14653 if (curr_cost > this_rq->max_idle_balance_cost) 14654 this_rq->max_idle_balance_cost = curr_cost; 14655 14656 /* 14657 * While browsing the domains, we released the rq lock, a task could 14658 * have been enqueued in the meantime. Since we're not going idle, 14659 * pretend we pulled a task. 14660 */ 14661 if (this_rq->cfs.h_nr_queued && !pulled_task) 14662 pulled_task = 1; 14663 14664 /* If a higher prio class was modified, restart the pick */ 14665 if (rq_modified_above(this_rq, &fair_sched_class)) 14666 pulled_task = -1; 14667 14668 out: 14669 /* Move the next balance forward */ 14670 if (time_after(this_rq->next_balance, next_balance)) 14671 this_rq->next_balance = next_balance; 14672 14673 if (pulled_task) 14674 this_rq->idle_stamp = 0; 14675 else 14676 nohz_newidle_balance(this_rq); 14677 14678 rq_repin_lock(this_rq, rf); 14679 14680 return pulled_task; 14681 } 14682 14683 /* 14684 * This softirq handler is triggered via SCHED_SOFTIRQ from two places: 14685 * 14686 * - directly from the local sched_tick() for periodic load balancing 14687 * 14688 * - indirectly from a remote sched_tick() for NOHZ idle balancing 14689 * through the SMP cross-call nohz_csd_func() 14690 */ 14691 static __latent_entropy void sched_balance_softirq(void) 14692 { 14693 struct rq *this_rq = this_rq(); 14694 enum cpu_idle_type idle = this_rq->idle_balance; 14695 /* 14696 * If this CPU has a pending NOHZ_BALANCE_KICK, then do the 14697 * balancing on behalf of the other idle CPUs whose ticks are 14698 * stopped. Do nohz_idle_balance *before* sched_balance_domains to 14699 * give the idle CPUs a chance to load balance. Else we may 14700 * load balance only within the local sched_domain hierarchy 14701 * and abort nohz_idle_balance altogether if we pull some load. 14702 */ 14703 if (nohz_idle_balance(this_rq, idle)) 14704 return; 14705 14706 /* normal load balance */ 14707 sched_balance_update_blocked_averages(this_rq->cpu); 14708 sched_balance_domains(this_rq, idle); 14709 } 14710 14711 /* 14712 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing. 14713 */ 14714 void sched_balance_trigger(struct rq *rq) 14715 { 14716 /* 14717 * Don't need to rebalance while attached to NULL domain or 14718 * runqueue CPU is not active 14719 */ 14720 if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq)))) 14721 return; 14722 14723 if (time_after_eq(jiffies, rq->next_balance)) 14724 raise_softirq(SCHED_SOFTIRQ); 14725 14726 nohz_balancer_kick(rq); 14727 } 14728 14729 static void rq_online_fair(struct rq *rq) 14730 { 14731 update_sysctl(); 14732 14733 update_runtime_enabled(rq); 14734 } 14735 14736 static void rq_offline_fair(struct rq *rq) 14737 { 14738 update_sysctl(); 14739 14740 /* Ensure any throttled groups are reachable by pick_next_task */ 14741 unthrottle_offline_cfs_rqs(rq); 14742 14743 /* Ensure that we remove rq contribution to group share: */ 14744 clear_tg_offline_cfs_rqs(rq); 14745 } 14746 14747 #ifdef CONFIG_SCHED_CORE 14748 static inline bool 14749 __entity_slice_used(struct sched_entity *se, int min_nr_tasks) 14750 { 14751 u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime; 14752 u64 slice = se->slice; 14753 14754 return (rtime * min_nr_tasks > slice); 14755 } 14756 14757 #define MIN_NR_TASKS_DURING_FORCEIDLE 2 14758 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) 14759 { 14760 if (!sched_core_enabled(rq)) 14761 return; 14762 14763 /* 14764 * If runqueue has only one task which used up its slice and 14765 * if the sibling is forced idle, then trigger schedule to 14766 * give forced idle task a chance. 14767 * 14768 * __entity_slice_used() considers only this active rq and it gets the 14769 * whole slice. But during force idle, we have siblings acting 14770 * like a single runqueue and hence we need to consider runnable 14771 * tasks on this CPU and the forced idle CPU. Ideally, we should 14772 * go through the forced idle rq, but that would be a perf hit. 14773 * We can assume that the forced idle CPU has at least 14774 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check 14775 * if we need to give up the CPU. 14776 */ 14777 if (rq->core->core_forceidle_count && rq->cfs.h_nr_queued == 1 && 14778 __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE)) 14779 resched_curr(rq); 14780 } 14781 14782 /* 14783 * Consider any infeasible weight scenario. Take for instance two tasks, 14784 * each bound to their respective sibling, one with weight 1 and one with 14785 * weight 2. Then the lower weight task will run ahead of the higher weight 14786 * task without bound. 14787 * 14788 * This utterly destroys the concept of a shared time base. 14789 * 14790 * Remember; all this is about a proportionally fair scheduling, where each 14791 * tasks receives: 14792 * 14793 * w_i 14794 * dt_i = ---------- dt (1) 14795 * \Sum_j w_j 14796 * 14797 * which we do by tracking a virtual time, s_i: 14798 * 14799 * 1 14800 * s_i = --- d[t]_i (2) 14801 * w_i 14802 * 14803 * Where d[t] is a delta of discrete time, while dt is an infinitesimal. 14804 * The immediate corollary is that the ideal schedule S, where (2) to use 14805 * an infinitesimal delta, is: 14806 * 14807 * 1 14808 * S = ---------- dt (3) 14809 * \Sum_i w_i 14810 * 14811 * From which we can define the lag, or deviation from the ideal, as: 14812 * 14813 * lag(i) = S - s_i (4) 14814 * 14815 * And since the one and only purpose is to approximate S, we get that: 14816 * 14817 * \Sum_i w_i lag(i) := 0 (5) 14818 * 14819 * If this were not so, we no longer converge to S, and we can no longer 14820 * claim our scheduler has any of the properties we derive from S. This is 14821 * exactly what you did above, you broke it! 14822 * 14823 * 14824 * Let's continue for a while though; to see if there is anything useful to 14825 * be learned. We can combine (1)-(3) or (4)-(5) and express S in s_i: 14826 * 14827 * \Sum_i w_i s_i 14828 * S = -------------- (6) 14829 * \Sum_i w_i 14830 * 14831 * Which gives us a way to compute S, given our s_i. Now, if you've read 14832 * our code, you know that we do not in fact do this, the reason for this 14833 * is two-fold. Firstly, computing S in that way requires a 64bit division 14834 * for every time we'd use it (see 12), and secondly, this only describes 14835 * the steady-state, it doesn't handle dynamics. 14836 * 14837 * Anyway, in (6): s_i -> x + (s_i - x), to get: 14838 * 14839 * \Sum_i w_i (s_i - x) 14840 * S - x = -------------------- (7) 14841 * \Sum_i w_i 14842 * 14843 * Which shows that S and s_i transform alike (which makes perfect sense 14844 * given that S is basically the (weighted) average of s_i). 14845 * 14846 * So the thing to remember is that the above is strictly UP. It is 14847 * possible to generalize to multiple runqueues -- however it gets really 14848 * yuck when you have to add affinity support, as illustrated by our very 14849 * first counter-example. 14850 * 14851 * Luckily I think we can avoid needing a full multi-queue variant for 14852 * core-scheduling (or load-balancing). The crucial observation is that we 14853 * only actually need this comparison in the presence of forced-idle; only 14854 * then do we need to tell if the stalled rq has higher priority over the 14855 * other. 14856 * 14857 * [XXX assumes SMT2; better consider the more general case, I suspect 14858 * it'll work out because our comparison is always between 2 rqs and the 14859 * answer is only interesting if one of them is forced-idle] 14860 * 14861 * And (under assumption of SMT2) when there is forced-idle, there is only 14862 * a single queue, so everything works like normal. 14863 * 14864 * Let, for our runqueue 'k': 14865 * 14866 * T_k = \Sum_i w_i s_i 14867 * W_k = \Sum_i w_i ; for all i of k (8) 14868 * 14869 * Then we can write (6) like: 14870 * 14871 * T_k 14872 * S_k = --- (9) 14873 * W_k 14874 * 14875 * From which immediately follows that: 14876 * 14877 * T_k + T_l 14878 * S_k+l = --------- (10) 14879 * W_k + W_l 14880 * 14881 * On which we can define a combined lag: 14882 * 14883 * lag_k+l(i) := S_k+l - s_i (11) 14884 * 14885 * And that gives us the tools to compare tasks across a combined runqueue. 14886 * 14887 * 14888 * Combined this gives the following: 14889 * 14890 * a) when a runqueue enters force-idle, sync it against it's sibling rq(s) 14891 * using (7); this only requires storing single 'time'-stamps. 14892 * 14893 * b) when comparing tasks between 2 runqueues of which one is forced-idle, 14894 * compare the combined lag, per (11). 14895 * 14896 * Now, of course cgroups (I so hate them) make this more interesting in 14897 * that a) seems to suggest we need to iterate all cgroup on a CPU at such 14898 * boundaries, but I think we can avoid that. The force-idle is for the 14899 * whole CPU, all it's rqs. So we can mark it in the root and lazily 14900 * propagate downward on demand. 14901 */ 14902 14903 /* 14904 * So this sync is basically a relative reset of S to 0. 14905 * 14906 * So with 2 queues, when one goes idle, we drop them both to 0 and one 14907 * then increases due to not being idle, and the idle one builds up lag to 14908 * get re-elected. So far so simple, right? 14909 * 14910 * When there's 3, we can have the situation where 2 run and one is idle, 14911 * we sync to 0 and let the idle one build up lag to get re-election. Now 14912 * suppose another one also drops idle. At this point dropping all to 0 14913 * again would destroy the built-up lag from the queue that was already 14914 * idle, not good. 14915 * 14916 * So instead of syncing everything, we can: 14917 * 14918 * less := !((s64)(s_a - s_b) <= 0) 14919 * 14920 * (v_a - S_a) - (v_b - S_b) == v_a - v_b - S_a + S_b 14921 * == v_a - (v_b - S_a + S_b) 14922 * 14923 * IOW, we can recast the (lag) comparison to a one-sided difference. 14924 * So if then, instead of syncing the whole queue, sync the idle queue 14925 * against the active queue with S_a + S_b at the point where we sync. 14926 * 14927 * (XXX consider the implication of living in a cyclic group: N / 2^n N) 14928 * 14929 * This gives us means of syncing single queues against the active queue, 14930 * and for already idle queues to preserve their build-up lag. 14931 * 14932 * Of course, then we get the situation where there's 2 active and one 14933 * going idle, who do we pick to sync against? Theory would have us sync 14934 * against the combined S, but as we've already demonstrated, there is no 14935 * such thing in infeasible weight scenarios. 14936 * 14937 * One thing I've considered; and this is where that core_active rudiment 14938 * came from, is having active queues sync up between themselves after 14939 * every tick. This limits the observed divergence due to the work 14940 * conservancy. 14941 * 14942 * On top of that, we can improve upon things by employing (10) here. 14943 */ 14944 14945 /* 14946 * se_fi_update - Update the cfs_rq->zero_vruntime_fi in a CFS hierarchy if needed. 14947 */ 14948 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq, 14949 bool forceidle) 14950 { 14951 for_each_sched_entity(se) { 14952 struct cfs_rq *cfs_rq = cfs_rq_of(se); 14953 14954 if (forceidle) { 14955 if (cfs_rq->forceidle_seq == fi_seq) 14956 break; 14957 cfs_rq->forceidle_seq = fi_seq; 14958 } 14959 14960 cfs_rq->zero_vruntime_fi = cfs_rq->zero_vruntime; 14961 } 14962 } 14963 14964 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi) 14965 { 14966 struct sched_entity *se = &p->se; 14967 14968 if (p->sched_class != &fair_sched_class) 14969 return; 14970 14971 se_fi_update(se, rq->core->core_forceidle_seq, in_fi); 14972 } 14973 14974 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b, 14975 bool in_fi) 14976 { 14977 struct rq *rq = task_rq(a); 14978 const struct sched_entity *sea = &a->se; 14979 const struct sched_entity *seb = &b->se; 14980 struct cfs_rq *cfs_rqa; 14981 struct cfs_rq *cfs_rqb; 14982 s64 delta; 14983 14984 WARN_ON_ONCE(task_rq(b)->core != rq->core); 14985 14986 cfs_rqa = &task_rq(a)->cfs; 14987 cfs_rqb = &task_rq(b)->cfs; 14988 14989 /* 14990 * Find delta after normalizing se's vruntime with its cfs_rq's 14991 * zero_vruntime_fi, which would have been updated in prior calls 14992 * to se_fi_update(). 14993 */ 14994 delta = vruntime_op(sea->vruntime, "-", seb->vruntime) + 14995 vruntime_op(cfs_rqb->zero_vruntime_fi, "-", cfs_rqa->zero_vruntime_fi); 14996 14997 return delta > 0; 14998 } 14999 15000 static int task_is_throttled_fair(struct task_struct *p, int cpu) 15001 { 15002 struct cfs_rq *cfs_rq; 15003 15004 #ifdef CONFIG_FAIR_GROUP_SCHED 15005 cfs_rq = tg_cfs_rq(task_group(p), cpu); 15006 #else 15007 cfs_rq = &cpu_rq(cpu)->cfs; 15008 #endif 15009 return throttled_hierarchy(cfs_rq); 15010 } 15011 #else /* !CONFIG_SCHED_CORE: */ 15012 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {} 15013 #endif /* !CONFIG_SCHED_CORE */ 15014 15015 /* 15016 * scheduler tick hitting a task of our scheduling class. 15017 * 15018 * NOTE: This function can be called remotely by the tick offload that 15019 * goes along full dynticks. Therefore no local assumption can be made 15020 * and everything must be accessed through the @rq and @curr passed in 15021 * parameters. 15022 */ 15023 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued) 15024 { 15025 struct sched_entity *se = &curr->se; 15026 15027 if (se->on_rq) { 15028 unsigned long weight = NICE_0_LOAD; 15029 struct cfs_rq *cfs_rq; 15030 15031 for_each_sched_entity(se) { 15032 cfs_rq = cfs_rq_of(se); 15033 entity_tick(cfs_rq, se, queued); 15034 15035 weight = __calc_prop_weight(cfs_rq, se, weight); 15036 } 15037 15038 se = &curr->se; 15039 reweight_eevdf(cfs_rq, se, weight, se->on_rq); 15040 } 15041 15042 if (queued) 15043 return; 15044 15045 if (static_branch_unlikely(&sched_numa_balancing)) 15046 task_tick_numa(rq, curr); 15047 15048 task_tick_cache(rq, curr); 15049 15050 update_misfit_status(curr, rq); 15051 check_update_overutilized_status(task_rq(curr)); 15052 15053 task_tick_core(rq, curr); 15054 } 15055 15056 /* 15057 * called on fork with the child task as argument from the parent's context 15058 * - child not yet on the tasklist 15059 * - preemption disabled 15060 */ 15061 static void task_fork_fair(struct task_struct *p) 15062 { 15063 set_task_max_allowed_capacity(p); 15064 } 15065 15066 /* 15067 * Priority of the task has changed. Check to see if we preempt 15068 * the current task. 15069 */ 15070 static void 15071 prio_changed_fair(struct rq *rq, struct task_struct *p, u64 oldprio) 15072 { 15073 if (!task_on_rq_queued(p)) 15074 return; 15075 15076 if (p->prio == oldprio) 15077 return; 15078 15079 if (rq->cfs.h_nr_queued == 1) 15080 return; 15081 15082 /* 15083 * Reschedule if we are currently running on this runqueue and 15084 * our priority decreased, or if we are not currently running on 15085 * this runqueue and our priority is higher than the current's 15086 */ 15087 if (task_current_donor(rq, p)) { 15088 if (p->prio > oldprio) 15089 resched_curr(rq); 15090 } else { 15091 wakeup_preempt(rq, p, 0); 15092 } 15093 } 15094 15095 #ifdef CONFIG_FAIR_GROUP_SCHED 15096 /* 15097 * Propagate the changes of the sched_entity across the tg tree to make it 15098 * visible to the root 15099 */ 15100 static void propagate_entity_cfs_rq(struct sched_entity *se) 15101 { 15102 struct cfs_rq *cfs_rq = cfs_rq_of(se); 15103 15104 /* 15105 * If a task gets attached to this cfs_rq and before being queued, 15106 * it gets migrated to another CPU due to reasons like affinity 15107 * change, make sure this cfs_rq stays on leaf cfs_rq list to have 15108 * that removed load decayed or it can cause faireness problem. 15109 */ 15110 if (!cfs_rq_pelt_clock_throttled(cfs_rq)) 15111 list_add_leaf_cfs_rq(cfs_rq); 15112 15113 /* Start to propagate at parent */ 15114 se = se->parent; 15115 15116 for_each_sched_entity(se) { 15117 cfs_rq = cfs_rq_of(se); 15118 15119 update_load_avg(cfs_rq, se, UPDATE_TG); 15120 15121 if (!cfs_rq_pelt_clock_throttled(cfs_rq)) 15122 list_add_leaf_cfs_rq(cfs_rq); 15123 } 15124 15125 assert_list_leaf_cfs_rq(rq_of(cfs_rq)); 15126 } 15127 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 15128 static void propagate_entity_cfs_rq(struct sched_entity *se) { } 15129 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 15130 15131 static void detach_entity_cfs_rq(struct sched_entity *se) 15132 { 15133 struct cfs_rq *cfs_rq = cfs_rq_of(se); 15134 15135 /* 15136 * In case the task sched_avg hasn't been attached: 15137 * - A forked task which hasn't been woken up by wake_up_new_task(). 15138 * - A task which has been woken up by try_to_wake_up() but is 15139 * waiting for actually being woken up by sched_ttwu_pending(). 15140 */ 15141 if (!se->avg.last_update_time) 15142 return; 15143 15144 /* Catch up with the cfs_rq and remove our load when we leave */ 15145 update_load_avg(cfs_rq, se, 0); 15146 detach_entity_load_avg(cfs_rq, se); 15147 update_tg_load_avg(cfs_rq); 15148 propagate_entity_cfs_rq(se); 15149 } 15150 15151 static void attach_entity_cfs_rq(struct sched_entity *se) 15152 { 15153 struct cfs_rq *cfs_rq = cfs_rq_of(se); 15154 15155 /* Synchronize entity with its cfs_rq */ 15156 update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD); 15157 attach_entity_load_avg(cfs_rq, se); 15158 update_tg_load_avg(cfs_rq); 15159 propagate_entity_cfs_rq(se); 15160 } 15161 15162 static void detach_task_cfs_rq(struct task_struct *p) 15163 { 15164 struct sched_entity *se = &p->se; 15165 15166 detach_entity_cfs_rq(se); 15167 } 15168 15169 static void attach_task_cfs_rq(struct task_struct *p) 15170 { 15171 struct sched_entity *se = &p->se; 15172 15173 attach_entity_cfs_rq(se); 15174 } 15175 15176 static void switching_from_fair(struct rq *rq, struct task_struct *p) 15177 { 15178 if (p->se.sched_delayed) 15179 dequeue_task(rq, p, DEQUEUE_SLEEP | DEQUEUE_DELAYED | DEQUEUE_NOCLOCK); 15180 } 15181 15182 static void switched_from_fair(struct rq *rq, struct task_struct *p) 15183 { 15184 detach_task_cfs_rq(p); 15185 } 15186 15187 static void switched_to_fair(struct rq *rq, struct task_struct *p) 15188 { 15189 WARN_ON_ONCE(p->se.sched_delayed); 15190 15191 attach_task_cfs_rq(p); 15192 15193 set_task_max_allowed_capacity(p); 15194 15195 if (task_on_rq_queued(p)) { 15196 /* 15197 * We were most likely switched from sched_rt, so 15198 * kick off the schedule if running, otherwise just see 15199 * if we can still preempt the current task. 15200 */ 15201 if (task_current_donor(rq, p)) 15202 resched_curr(rq); 15203 else 15204 wakeup_preempt(rq, p, 0); 15205 } 15206 } 15207 15208 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first) 15209 { 15210 struct sched_entity *se = &p->se; 15211 bool throttled = false; 15212 struct cfs_rq *cfs_rq = &rq->cfs; 15213 unsigned long weight = NICE_0_LOAD; 15214 bool on_rq = se->on_rq; 15215 15216 clear_buddies(cfs_rq, se); 15217 15218 if (on_rq) 15219 __dequeue_entity(cfs_rq, se); 15220 15221 for_each_sched_entity(se) { 15222 cfs_rq = cfs_rq_of(se); 15223 15224 if (!IS_ENABLED(CONFIG_FAIR_GROUP_SCHED) || 15225 !first || !cfs_rq->h_curr) 15226 set_next_entity(cfs_rq, se); 15227 15228 /* ensure bandwidth has been allocated on our new cfs_rq */ 15229 throttled |= account_cfs_rq_runtime(cfs_rq, 0); 15230 15231 if (on_rq) 15232 weight = __calc_prop_weight(cfs_rq, se, weight); 15233 } 15234 15235 if (throttled) 15236 task_throttle_setup_work(p); 15237 15238 se = &p->se; 15239 cfs_rq->curr = se; 15240 15241 if (on_rq) { 15242 reweight_eevdf(cfs_rq, se, weight, se->on_rq); 15243 if (first) 15244 set_protect_slice(cfs_rq, se); 15245 } 15246 15247 if (task_on_rq_queued(p)) { 15248 /* 15249 * Move the next running task to the front of the list, so our 15250 * cfs_tasks list becomes MRU one. 15251 */ 15252 list_move(&se->group_node, &rq->cfs_tasks); 15253 } 15254 if (!first) 15255 return; 15256 15257 WARN_ON_ONCE(se->sched_delayed); 15258 15259 if (hrtick_enabled_fair(rq)) 15260 hrtick_start_fair(rq, p); 15261 15262 update_misfit_status(p, rq); 15263 sched_fair_update_stop_tick(rq, p); 15264 } 15265 15266 void init_cfs_rq(struct cfs_rq *cfs_rq) 15267 { 15268 cfs_rq->tasks_timeline = RB_ROOT_CACHED; 15269 cfs_rq->zero_vruntime = (u64)(-(1LL << 20)); 15270 raw_spin_lock_init(&cfs_rq->removed.lock); 15271 } 15272 15273 #ifdef CONFIG_FAIR_GROUP_SCHED 15274 static void task_change_group_fair(struct task_struct *p) 15275 { 15276 /* 15277 * We couldn't detach or attach a forked task which 15278 * hasn't been woken up by wake_up_new_task(). 15279 */ 15280 if (READ_ONCE(p->__state) == TASK_NEW) 15281 return; 15282 15283 detach_task_cfs_rq(p); 15284 15285 /* Tell se's cfs_rq has been changed -- migrated */ 15286 p->se.avg.last_update_time = 0; 15287 set_task_rq(p, task_cpu(p)); 15288 attach_task_cfs_rq(p); 15289 } 15290 15291 void free_fair_sched_group(struct task_group *tg) 15292 { 15293 free_percpu(tg->cfs_rq); 15294 } 15295 15296 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent) 15297 { 15298 struct cfs_tg_state __percpu *state; 15299 struct sched_entity *se; 15300 struct cfs_rq *cfs_rq; 15301 int i; 15302 15303 state = alloc_percpu_gfp(struct cfs_tg_state, GFP_KERNEL); 15304 if (!state) 15305 goto err; 15306 15307 tg->cfs_rq = &state->cfs_rq; 15308 tg->shares = NICE_0_LOAD; 15309 15310 init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent)); 15311 15312 for_each_possible_cpu(i) { 15313 cfs_rq = tg_cfs_rq(tg, i); 15314 if (!cfs_rq) 15315 goto err; 15316 15317 se = tg_se(tg, i); 15318 init_cfs_rq(cfs_rq); 15319 init_tg_cfs_entry(tg, cfs_rq, se, i, tg_se(parent, i)); 15320 init_entity_runnable_average(se); 15321 } 15322 15323 return 1; 15324 15325 err: 15326 return 0; 15327 } 15328 15329 void online_fair_sched_group(struct task_group *tg) 15330 { 15331 struct sched_entity *se; 15332 struct rq_flags rf; 15333 struct rq *rq; 15334 int i; 15335 15336 for_each_possible_cpu(i) { 15337 rq = cpu_rq(i); 15338 se = tg_se(tg, i); 15339 rq_lock_irq(rq, &rf); 15340 update_rq_clock(rq); 15341 attach_entity_cfs_rq(se); 15342 sync_throttle(tg, i); 15343 rq_unlock_irq(rq, &rf); 15344 } 15345 } 15346 15347 void unregister_fair_sched_group(struct task_group *tg) 15348 { 15349 int cpu; 15350 15351 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg)); 15352 15353 for_each_possible_cpu(cpu) { 15354 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu); 15355 struct sched_entity *se = tg_se(tg, cpu); 15356 struct rq *rq = cpu_rq(cpu); 15357 15358 if (se) 15359 remove_entity_load_avg(se); 15360 15361 /* 15362 * Only empty task groups can be destroyed; so we can speculatively 15363 * check on_list without danger of it being re-added. 15364 */ 15365 if (cfs_rq->on_list) { 15366 guard(rq_lock_irqsave)(rq); 15367 list_del_leaf_cfs_rq(cfs_rq); 15368 } 15369 } 15370 } 15371 15372 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq, 15373 struct sched_entity *se, int cpu, 15374 struct sched_entity *parent) 15375 { 15376 struct rq *rq = cpu_rq(cpu); 15377 15378 cfs_rq->tg = tg; 15379 cfs_rq->rq = rq; 15380 init_cfs_rq_runtime(cfs_rq); 15381 15382 /* se could be NULL for root_task_group */ 15383 if (!se) 15384 return; 15385 15386 if (!parent) { 15387 se->cfs_rq = &rq->cfs; 15388 se->depth = 0; 15389 } else { 15390 se->cfs_rq = parent->my_q; 15391 se->depth = parent->depth + 1; 15392 } 15393 15394 se->my_q = cfs_rq; 15395 /* guarantee group entities always have weight */ 15396 update_load_set(&se->load, NICE_0_LOAD); 15397 se->parent = parent; 15398 } 15399 15400 static DEFINE_MUTEX(shares_mutex); 15401 15402 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares) 15403 { 15404 int i; 15405 15406 lockdep_assert_held(&shares_mutex); 15407 15408 /* 15409 * We can't change the weight of the root cgroup. 15410 */ 15411 if (is_root_task_group(tg)) 15412 return -EINVAL; 15413 15414 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES)); 15415 15416 if (tg->shares == shares) 15417 return 0; 15418 15419 tg->shares = shares; 15420 for_each_possible_cpu(i) { 15421 struct rq *rq = cpu_rq(i); 15422 struct sched_entity *se = tg_se(tg, i); 15423 struct rq_flags rf; 15424 15425 /* Propagate contribution to hierarchy */ 15426 rq_lock_irqsave(rq, &rf); 15427 update_rq_clock(rq); 15428 for_each_sched_entity(se) { 15429 update_load_avg(cfs_rq_of(se), se, UPDATE_TG); 15430 update_cfs_group(se); 15431 } 15432 rq_unlock_irqrestore(rq, &rf); 15433 } 15434 15435 return 0; 15436 } 15437 15438 int sched_group_set_shares(struct task_group *tg, unsigned long shares) 15439 { 15440 int ret; 15441 15442 mutex_lock(&shares_mutex); 15443 if (tg_is_idle(tg)) 15444 ret = -EINVAL; 15445 else 15446 ret = __sched_group_set_shares(tg, shares); 15447 mutex_unlock(&shares_mutex); 15448 15449 return ret; 15450 } 15451 15452 int sched_group_set_idle(struct task_group *tg, long idle) 15453 { 15454 int i; 15455 15456 if (tg == &root_task_group) 15457 return -EINVAL; 15458 15459 if (idle < 0 || idle > 1) 15460 return -EINVAL; 15461 15462 mutex_lock(&shares_mutex); 15463 15464 if (tg->idle == idle) { 15465 mutex_unlock(&shares_mutex); 15466 return 0; 15467 } 15468 15469 tg->idle = idle; 15470 15471 for_each_possible_cpu(i) { 15472 struct rq *rq = cpu_rq(i); 15473 struct sched_entity *se = tg_se(tg, i); 15474 struct cfs_rq *grp_cfs_rq = tg_cfs_rq(tg, i); 15475 bool was_idle = cfs_rq_is_idle(grp_cfs_rq); 15476 long idle_task_delta; 15477 struct rq_flags rf; 15478 15479 rq_lock_irqsave(rq, &rf); 15480 15481 grp_cfs_rq->idle = idle; 15482 if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq))) 15483 goto next_cpu; 15484 15485 idle_task_delta = grp_cfs_rq->h_nr_queued - 15486 grp_cfs_rq->h_nr_idle; 15487 if (!cfs_rq_is_idle(grp_cfs_rq)) 15488 idle_task_delta *= -1; 15489 15490 for_each_sched_entity(se) { 15491 struct cfs_rq *cfs_rq = cfs_rq_of(se); 15492 15493 if (!se->on_rq) 15494 break; 15495 15496 cfs_rq->h_nr_idle += idle_task_delta; 15497 15498 /* Already accounted at parent level and above. */ 15499 if (cfs_rq_is_idle(cfs_rq)) 15500 break; 15501 } 15502 15503 next_cpu: 15504 rq_unlock_irqrestore(rq, &rf); 15505 } 15506 15507 /* Idle groups have minimum weight. */ 15508 if (tg_is_idle(tg)) 15509 __sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO)); 15510 else 15511 __sched_group_set_shares(tg, NICE_0_LOAD); 15512 15513 mutex_unlock(&shares_mutex); 15514 return 0; 15515 } 15516 15517 #endif /* CONFIG_FAIR_GROUP_SCHED */ 15518 15519 15520 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task) 15521 { 15522 struct sched_entity *se = &task->se; 15523 unsigned int rr_interval = 0; 15524 15525 /* 15526 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise 15527 * idle runqueue: 15528 */ 15529 if (rq->cfs.load.weight) 15530 rr_interval = NS_TO_JIFFIES(se->slice); 15531 15532 return rr_interval; 15533 } 15534 15535 /* 15536 * All the scheduling class methods: 15537 */ 15538 DEFINE_SCHED_CLASS(fair) = { 15539 .enqueue_task = enqueue_task_fair, 15540 .dequeue_task = dequeue_task_fair, 15541 .yield_task = yield_task_fair, 15542 .yield_to_task = yield_to_task_fair, 15543 15544 .wakeup_preempt = wakeup_preempt_fair, 15545 15546 .pick_task = pick_task_fair, 15547 .put_prev_task = put_prev_task_fair, 15548 .set_next_task = set_next_task_fair, 15549 15550 .select_task_rq = select_task_rq_fair, 15551 .migrate_task_rq = migrate_task_rq_fair, 15552 15553 .rq_online = rq_online_fair, 15554 .rq_offline = rq_offline_fair, 15555 15556 .task_dead = task_dead_fair, 15557 .set_cpus_allowed = set_cpus_allowed_fair, 15558 15559 .task_tick = task_tick_fair, 15560 .task_fork = task_fork_fair, 15561 15562 .reweight_task = reweight_task_fair, 15563 .prio_changed = prio_changed_fair, 15564 .switching_from = switching_from_fair, 15565 .switched_from = switched_from_fair, 15566 .switched_to = switched_to_fair, 15567 15568 .get_rr_interval = get_rr_interval_fair, 15569 15570 .update_curr = update_curr_fair, 15571 15572 #ifdef CONFIG_FAIR_GROUP_SCHED 15573 .task_change_group = task_change_group_fair, 15574 #endif 15575 15576 #ifdef CONFIG_SCHED_CORE 15577 .task_is_throttled = task_is_throttled_fair, 15578 #endif 15579 15580 #ifdef CONFIG_UCLAMP_TASK 15581 .uclamp_enabled = 1, 15582 #endif 15583 }; 15584 15585 void print_cfs_stats(struct seq_file *m, int cpu) 15586 { 15587 struct cfs_rq *cfs_rq, *pos; 15588 15589 rcu_read_lock(); 15590 for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos) 15591 print_cfs_rq(m, cpu, cfs_rq); 15592 rcu_read_unlock(); 15593 } 15594 15595 #ifdef CONFIG_NUMA_BALANCING 15596 void show_numa_stats(struct task_struct *p, struct seq_file *m) 15597 { 15598 int node; 15599 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0; 15600 struct numa_group *ng; 15601 15602 rcu_read_lock(); 15603 ng = rcu_dereference_all(p->numa_group); 15604 for_each_online_node(node) { 15605 if (p->numa_faults) { 15606 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)]; 15607 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)]; 15608 } 15609 if (ng) { 15610 gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)]; 15611 gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)]; 15612 } 15613 print_numa_stats(m, node, tsf, tpf, gsf, gpf); 15614 } 15615 rcu_read_unlock(); 15616 } 15617 #endif /* CONFIG_NUMA_BALANCING */ 15618 15619 __init void init_sched_fair_class(void) 15620 { 15621 int i; 15622 15623 for_each_possible_cpu(i) { 15624 zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i)); 15625 zalloc_cpumask_var_node(&per_cpu(select_rq_mask, i), GFP_KERNEL, cpu_to_node(i)); 15626 zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i), 15627 GFP_KERNEL, cpu_to_node(i)); 15628 15629 #ifdef CONFIG_CFS_BANDWIDTH 15630 INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i)); 15631 INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list); 15632 #endif 15633 } 15634 15635 open_softirq(SCHED_SOFTIRQ, sched_balance_softirq); 15636 15637 #ifdef CONFIG_NO_HZ_COMMON 15638 nohz.next_balance = jiffies; 15639 nohz.next_blocked = jiffies; 15640 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT); 15641 #endif 15642 } 15643