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/spinlock_api.h> 30 #include <linux/cpumask_api.h> 31 #include <linux/lockdep_api.h> 32 #include <linux/softirq.h> 33 #include <linux/refcount_api.h> 34 #include <linux/topology.h> 35 #include <linux/sched/clock.h> 36 #include <linux/sched/cond_resched.h> 37 #include <linux/sched/cputime.h> 38 #include <linux/sched/isolation.h> 39 #include <linux/sched/nohz.h> 40 #include <linux/sched/prio.h> 41 42 #include <linux/cpuidle.h> 43 #include <linux/interrupt.h> 44 #include <linux/memory-tiers.h> 45 #include <linux/mempolicy.h> 46 #include <linux/mutex_api.h> 47 #include <linux/profile.h> 48 #include <linux/psi.h> 49 #include <linux/ratelimit.h> 50 #include <linux/task_work.h> 51 #include <linux/rbtree_augmented.h> 52 53 #include <asm/switch_to.h> 54 55 #include <uapi/linux/sched/types.h> 56 57 #include "sched.h" 58 #include "stats.h" 59 #include "autogroup.h" 60 61 /* 62 * The initial- and re-scaling of tunables is configurable 63 * 64 * Options are: 65 * 66 * SCHED_TUNABLESCALING_NONE - unscaled, always *1 67 * SCHED_TUNABLESCALING_LOG - scaled logarithmically, *1+ilog(ncpus) 68 * SCHED_TUNABLESCALING_LINEAR - scaled linear, *ncpus 69 * 70 * (default SCHED_TUNABLESCALING_LOG = *(1+ilog(ncpus)) 71 */ 72 unsigned int sysctl_sched_tunable_scaling = SCHED_TUNABLESCALING_LOG; 73 74 /* 75 * Minimal preemption granularity for CPU-bound tasks: 76 * 77 * (default: 0.70 msec * (1 + ilog(ncpus)), units: nanoseconds) 78 */ 79 unsigned int sysctl_sched_base_slice = 700000ULL; 80 static unsigned int normalized_sysctl_sched_base_slice = 700000ULL; 81 82 __read_mostly unsigned int sysctl_sched_migration_cost = 500000UL; 83 84 static int __init setup_sched_thermal_decay_shift(char *str) 85 { 86 pr_warn("Ignoring the deprecated sched_thermal_decay_shift= option\n"); 87 return 1; 88 } 89 __setup("sched_thermal_decay_shift=", setup_sched_thermal_decay_shift); 90 91 /* 92 * For asym packing, by default the lower numbered CPU has higher priority. 93 */ 94 int __weak arch_asym_cpu_priority(int cpu) 95 { 96 return -cpu; 97 } 98 99 /* 100 * The margin used when comparing utilization with CPU capacity. 101 * 102 * (default: ~20%) 103 */ 104 #define fits_capacity(cap, max) ((cap) * 1280 < (max) * 1024) 105 106 /* 107 * The margin used when comparing CPU capacities. 108 * is 'cap1' noticeably greater than 'cap2' 109 * 110 * (default: ~5%) 111 */ 112 #define capacity_greater(cap1, cap2) ((cap1) * 1024 > (cap2) * 1078) 113 114 #ifdef CONFIG_CFS_BANDWIDTH 115 /* 116 * Amount of runtime to allocate from global (tg) to local (per-cfs_rq) pool 117 * each time a cfs_rq requests quota. 118 * 119 * Note: in the case that the slice exceeds the runtime remaining (either due 120 * to consumption or the quota being specified to be smaller than the slice) 121 * we will always only issue the remaining available time. 122 * 123 * (default: 5 msec, units: microseconds) 124 */ 125 static unsigned int sysctl_sched_cfs_bandwidth_slice = 5000UL; 126 #endif 127 128 #ifdef CONFIG_NUMA_BALANCING 129 /* Restrict the NUMA promotion throughput (MB/s) for each target node. */ 130 static unsigned int sysctl_numa_balancing_promote_rate_limit = 65536; 131 #endif 132 133 #ifdef CONFIG_SYSCTL 134 static const struct ctl_table sched_fair_sysctls[] = { 135 #ifdef CONFIG_CFS_BANDWIDTH 136 { 137 .procname = "sched_cfs_bandwidth_slice_us", 138 .data = &sysctl_sched_cfs_bandwidth_slice, 139 .maxlen = sizeof(unsigned int), 140 .mode = 0644, 141 .proc_handler = proc_dointvec_minmax, 142 .extra1 = SYSCTL_ONE, 143 }, 144 #endif 145 #ifdef CONFIG_NUMA_BALANCING 146 { 147 .procname = "numa_balancing_promote_rate_limit_MBps", 148 .data = &sysctl_numa_balancing_promote_rate_limit, 149 .maxlen = sizeof(unsigned int), 150 .mode = 0644, 151 .proc_handler = proc_dointvec_minmax, 152 .extra1 = SYSCTL_ZERO, 153 }, 154 #endif /* CONFIG_NUMA_BALANCING */ 155 }; 156 157 static int __init sched_fair_sysctl_init(void) 158 { 159 register_sysctl_init("kernel", sched_fair_sysctls); 160 return 0; 161 } 162 late_initcall(sched_fair_sysctl_init); 163 #endif /* CONFIG_SYSCTL */ 164 165 static inline void update_load_add(struct load_weight *lw, unsigned long inc) 166 { 167 lw->weight += inc; 168 lw->inv_weight = 0; 169 } 170 171 static inline void update_load_sub(struct load_weight *lw, unsigned long dec) 172 { 173 lw->weight -= dec; 174 lw->inv_weight = 0; 175 } 176 177 static inline void update_load_set(struct load_weight *lw, unsigned long w) 178 { 179 lw->weight = w; 180 lw->inv_weight = 0; 181 } 182 183 /* 184 * Increase the granularity value when there are more CPUs, 185 * because with more CPUs the 'effective latency' as visible 186 * to users decreases. But the relationship is not linear, 187 * so pick a second-best guess by going with the log2 of the 188 * number of CPUs. 189 * 190 * This idea comes from the SD scheduler of Con Kolivas: 191 */ 192 static unsigned int get_update_sysctl_factor(void) 193 { 194 unsigned int cpus = min_t(unsigned int, num_online_cpus(), 8); 195 unsigned int factor; 196 197 switch (sysctl_sched_tunable_scaling) { 198 case SCHED_TUNABLESCALING_NONE: 199 factor = 1; 200 break; 201 case SCHED_TUNABLESCALING_LINEAR: 202 factor = cpus; 203 break; 204 case SCHED_TUNABLESCALING_LOG: 205 default: 206 factor = 1 + ilog2(cpus); 207 break; 208 } 209 210 return factor; 211 } 212 213 static void update_sysctl(void) 214 { 215 unsigned int factor = get_update_sysctl_factor(); 216 217 #define SET_SYSCTL(name) \ 218 (sysctl_##name = (factor) * normalized_sysctl_##name) 219 SET_SYSCTL(sched_base_slice); 220 #undef SET_SYSCTL 221 } 222 223 void __init sched_init_granularity(void) 224 { 225 update_sysctl(); 226 } 227 228 #ifndef CONFIG_64BIT 229 #define WMULT_CONST (~0U) 230 #define WMULT_SHIFT 32 231 232 static void __update_inv_weight(struct load_weight *lw) 233 { 234 unsigned long w; 235 236 if (likely(lw->inv_weight)) 237 return; 238 239 w = scale_load_down(lw->weight); 240 241 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST)) 242 lw->inv_weight = 1; 243 else if (unlikely(!w)) 244 lw->inv_weight = WMULT_CONST; 245 else 246 lw->inv_weight = WMULT_CONST / w; 247 } 248 249 /* 250 * delta_exec * weight / lw.weight 251 * OR 252 * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT 253 * 254 * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case 255 * we're guaranteed shift stays positive because inv_weight is guaranteed to 256 * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22. 257 * 258 * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus 259 * weight/lw.weight <= 1, and therefore our shift will also be positive. 260 */ 261 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw) 262 { 263 u64 fact = scale_load_down(weight); 264 u32 fact_hi = (u32)(fact >> 32); 265 int shift = WMULT_SHIFT; 266 int fs; 267 268 __update_inv_weight(lw); 269 270 if (unlikely(fact_hi)) { 271 fs = fls(fact_hi); 272 shift -= fs; 273 fact >>= fs; 274 } 275 276 fact = mul_u32_u32(fact, lw->inv_weight); 277 278 fact_hi = (u32)(fact >> 32); 279 if (fact_hi) { 280 fs = fls(fact_hi); 281 shift -= fs; 282 fact >>= fs; 283 } 284 285 return mul_u64_u32_shr(delta_exec, fact, shift); 286 } 287 #else 288 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw) 289 { 290 return (delta_exec * weight) / lw->weight; 291 } 292 #endif 293 294 /* 295 * delta /= w 296 */ 297 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se) 298 { 299 if (unlikely(se->load.weight != NICE_0_LOAD)) 300 delta = __calc_delta(delta, NICE_0_LOAD, &se->load); 301 302 return delta; 303 } 304 305 const struct sched_class fair_sched_class; 306 307 /************************************************************** 308 * CFS operations on generic schedulable entities: 309 */ 310 311 #ifdef CONFIG_FAIR_GROUP_SCHED 312 313 /* Walk up scheduling entities hierarchy */ 314 #define for_each_sched_entity(se) \ 315 for (; se; se = se->parent) 316 317 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq) 318 { 319 struct rq *rq = rq_of(cfs_rq); 320 int cpu = cpu_of(rq); 321 322 if (cfs_rq->on_list) 323 return rq->tmp_alone_branch == &rq->leaf_cfs_rq_list; 324 325 cfs_rq->on_list = 1; 326 327 /* 328 * Ensure we either appear before our parent (if already 329 * enqueued) or force our parent to appear after us when it is 330 * enqueued. The fact that we always enqueue bottom-up 331 * reduces this to two cases and a special case for the root 332 * cfs_rq. Furthermore, it also means that we will always reset 333 * tmp_alone_branch either when the branch is connected 334 * to a tree or when we reach the top of the tree 335 */ 336 if (cfs_rq->tg->parent && 337 tg_cfs_rq(cfs_rq->tg->parent, cpu)->on_list) { 338 /* 339 * If parent is already on the list, we add the child 340 * just before. Thanks to circular linked property of 341 * the list, this means to put the child at the tail 342 * of the list that starts by parent. 343 */ 344 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list, 345 &(tg_cfs_rq(cfs_rq->tg->parent, cpu)->leaf_cfs_rq_list)); 346 /* 347 * The branch is now connected to its tree so we can 348 * reset tmp_alone_branch to the beginning of the 349 * list. 350 */ 351 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list; 352 return true; 353 } 354 355 if (!cfs_rq->tg->parent) { 356 /* 357 * cfs rq without parent should be put 358 * at the tail of the list. 359 */ 360 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list, 361 &rq->leaf_cfs_rq_list); 362 /* 363 * We have reach the top of a tree so we can reset 364 * tmp_alone_branch to the beginning of the list. 365 */ 366 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list; 367 return true; 368 } 369 370 /* 371 * The parent has not already been added so we want to 372 * make sure that it will be put after us. 373 * tmp_alone_branch points to the begin of the branch 374 * where we will add parent. 375 */ 376 list_add_rcu(&cfs_rq->leaf_cfs_rq_list, rq->tmp_alone_branch); 377 /* 378 * update tmp_alone_branch to points to the new begin 379 * of the branch 380 */ 381 rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list; 382 return false; 383 } 384 385 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq) 386 { 387 if (cfs_rq->on_list) { 388 struct rq *rq = rq_of(cfs_rq); 389 390 /* 391 * With cfs_rq being unthrottled/throttled during an enqueue, 392 * it can happen the tmp_alone_branch points to the leaf that 393 * we finally want to delete. In this case, tmp_alone_branch moves 394 * to the prev element but it will point to rq->leaf_cfs_rq_list 395 * at the end of the enqueue. 396 */ 397 if (rq->tmp_alone_branch == &cfs_rq->leaf_cfs_rq_list) 398 rq->tmp_alone_branch = cfs_rq->leaf_cfs_rq_list.prev; 399 400 list_del_rcu(&cfs_rq->leaf_cfs_rq_list); 401 cfs_rq->on_list = 0; 402 } 403 } 404 405 static inline void assert_list_leaf_cfs_rq(struct rq *rq) 406 { 407 WARN_ON_ONCE(rq->tmp_alone_branch != &rq->leaf_cfs_rq_list); 408 } 409 410 /* Iterate through all leaf cfs_rq's on a runqueue */ 411 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \ 412 list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list, \ 413 leaf_cfs_rq_list) 414 415 /* Do the two (enqueued) entities belong to the same group ? */ 416 static inline struct cfs_rq * 417 is_same_group(struct sched_entity *se, struct sched_entity *pse) 418 { 419 if (se->cfs_rq == pse->cfs_rq) 420 return se->cfs_rq; 421 422 return NULL; 423 } 424 425 static inline struct sched_entity *parent_entity(const struct sched_entity *se) 426 { 427 return se->parent; 428 } 429 430 static void 431 find_matching_se(struct sched_entity **se, struct sched_entity **pse) 432 { 433 int se_depth, pse_depth; 434 435 /* 436 * preemption test can be made between sibling entities who are in the 437 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of 438 * both tasks until we find their ancestors who are siblings of common 439 * parent. 440 */ 441 442 /* First walk up until both entities are at same depth */ 443 se_depth = (*se)->depth; 444 pse_depth = (*pse)->depth; 445 446 while (se_depth > pse_depth) { 447 se_depth--; 448 *se = parent_entity(*se); 449 } 450 451 while (pse_depth > se_depth) { 452 pse_depth--; 453 *pse = parent_entity(*pse); 454 } 455 456 while (!is_same_group(*se, *pse)) { 457 *se = parent_entity(*se); 458 *pse = parent_entity(*pse); 459 } 460 } 461 462 static int tg_is_idle(struct task_group *tg) 463 { 464 return tg->idle > 0; 465 } 466 467 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq) 468 { 469 return cfs_rq->idle > 0; 470 } 471 472 static int se_is_idle(struct sched_entity *se) 473 { 474 if (entity_is_task(se)) 475 return task_has_idle_policy(task_of(se)); 476 return cfs_rq_is_idle(group_cfs_rq(se)); 477 } 478 479 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 480 481 #define for_each_sched_entity(se) \ 482 for (; se; se = NULL) 483 484 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq) 485 { 486 return true; 487 } 488 489 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq) 490 { 491 } 492 493 static inline void assert_list_leaf_cfs_rq(struct rq *rq) 494 { 495 } 496 497 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \ 498 for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos) 499 500 static inline struct sched_entity *parent_entity(struct sched_entity *se) 501 { 502 return NULL; 503 } 504 505 static inline void 506 find_matching_se(struct sched_entity **se, struct sched_entity **pse) 507 { 508 } 509 510 static inline int tg_is_idle(struct task_group *tg) 511 { 512 return 0; 513 } 514 515 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq) 516 { 517 return 0; 518 } 519 520 static int se_is_idle(struct sched_entity *se) 521 { 522 return task_has_idle_policy(task_of(se)); 523 } 524 525 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 526 527 static __always_inline 528 bool account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec); 529 530 /************************************************************** 531 * Scheduling class tree data structure manipulation methods: 532 */ 533 534 extern void __BUILD_BUG_vruntime_cmp(void); 535 536 /* Use __builtin_strcmp() because of __HAVE_ARCH_STRCMP: */ 537 538 #define vruntime_cmp(A, CMP_STR, B) ({ \ 539 int __res = 0; \ 540 \ 541 if (!__builtin_strcmp(CMP_STR, "<")) { \ 542 __res = ((s64)((A)-(B)) < 0); \ 543 } else if (!__builtin_strcmp(CMP_STR, "<=")) { \ 544 __res = ((s64)((A)-(B)) <= 0); \ 545 } else if (!__builtin_strcmp(CMP_STR, ">")) { \ 546 __res = ((s64)((A)-(B)) > 0); \ 547 } else if (!__builtin_strcmp(CMP_STR, ">=")) { \ 548 __res = ((s64)((A)-(B)) >= 0); \ 549 } else { \ 550 /* Unknown operator throws linker error: */ \ 551 __BUILD_BUG_vruntime_cmp(); \ 552 } \ 553 \ 554 __res; \ 555 }) 556 557 extern void __BUILD_BUG_vruntime_op(void); 558 559 #define vruntime_op(A, OP_STR, B) ({ \ 560 s64 __res = 0; \ 561 \ 562 if (!__builtin_strcmp(OP_STR, "-")) { \ 563 __res = (s64)((A)-(B)); \ 564 } else { \ 565 /* Unknown operator throws linker error: */ \ 566 __BUILD_BUG_vruntime_op(); \ 567 } \ 568 \ 569 __res; \ 570 }) 571 572 573 static inline __maybe_unused u64 max_vruntime(u64 max_vruntime, u64 vruntime) 574 { 575 if (vruntime_cmp(vruntime, ">", max_vruntime)) 576 max_vruntime = vruntime; 577 578 return max_vruntime; 579 } 580 581 static inline __maybe_unused u64 min_vruntime(u64 min_vruntime, u64 vruntime) 582 { 583 if (vruntime_cmp(vruntime, "<", min_vruntime)) 584 min_vruntime = vruntime; 585 586 return min_vruntime; 587 } 588 589 static inline bool entity_before(const struct sched_entity *a, 590 const struct sched_entity *b) 591 { 592 /* 593 * Tiebreak on vruntime seems unnecessary since it can 594 * hardly happen. 595 */ 596 return vruntime_cmp(a->deadline, "<", b->deadline); 597 } 598 599 /* 600 * Per avg_vruntime() below, cfs_rq::zero_vruntime is only slightly stale 601 * and this value should be no more than two lag bounds. Which puts it in the 602 * general order of: 603 * 604 * (slice + TICK_NSEC) << NICE_0_LOAD_SHIFT 605 * 606 * which is around 44 bits in size (on 64bit); that is 20 for 607 * NICE_0_LOAD_SHIFT, another 20 for NSEC_PER_MSEC and then a handful for 608 * however many msec the actual slice+tick ends up begin. 609 * 610 * (disregarding the actual divide-by-weight part makes for the worst case 611 * weight of 2, which nicely cancels vs the fuzz in zero_vruntime not actually 612 * being the zero-lag point). 613 */ 614 static inline s64 entity_key(struct cfs_rq *cfs_rq, struct sched_entity *se) 615 { 616 return vruntime_op(se->vruntime, "-", cfs_rq->zero_vruntime); 617 } 618 619 #define __node_2_se(node) \ 620 rb_entry((node), struct sched_entity, run_node) 621 622 /* 623 * Compute virtual time from the per-task service numbers: 624 * 625 * Fair schedulers conserve lag: 626 * 627 * \Sum lag_i = 0 628 * 629 * Where lag_i is given by: 630 * 631 * lag_i = S - s_i = w_i * (V - v_i) 632 * 633 * Where S is the ideal service time and V is it's virtual time counterpart. 634 * Therefore: 635 * 636 * \Sum lag_i = 0 637 * \Sum w_i * (V - v_i) = 0 638 * \Sum (w_i * V - w_i * v_i) = 0 639 * 640 * From which we can solve an expression for V in v_i (which we have in 641 * se->vruntime): 642 * 643 * \Sum v_i * w_i \Sum v_i * w_i 644 * V = -------------- = -------------- 645 * \Sum w_i W 646 * 647 * Specifically, this is the weighted average of all entity virtual runtimes. 648 * 649 * [[ NOTE: this is only equal to the ideal scheduler under the condition 650 * that join/leave operations happen at lag_i = 0, otherwise the 651 * virtual time has non-contiguous motion equivalent to: 652 * 653 * V +-= lag_i / W 654 * 655 * Also see the comment in place_entity() that deals with this. ]] 656 * 657 * However, since v_i is u64, and the multiplication could easily overflow 658 * transform it into a relative form that uses smaller quantities: 659 * 660 * Substitute: v_i == (v_i - v0) + v0 661 * 662 * \Sum ((v_i - v0) + v0) * w_i \Sum (v_i - v0) * w_i 663 * V = ---------------------------- = --------------------- + v0 664 * W W 665 * 666 * Which we track using: 667 * 668 * v0 := cfs_rq->zero_vruntime 669 * \Sum (v_i - v0) * w_i := cfs_rq->sum_w_vruntime 670 * \Sum w_i := cfs_rq->sum_weight 671 * 672 * Since zero_vruntime closely tracks the per-task service, these 673 * deltas: (v_i - v0), will be in the order of the maximal (virtual) lag 674 * induced in the system due to quantisation. 675 */ 676 static inline unsigned long avg_vruntime_weight(struct cfs_rq *cfs_rq, unsigned long w) 677 { 678 #ifdef CONFIG_64BIT 679 if (cfs_rq->sum_shift) 680 w = max(2UL, w >> cfs_rq->sum_shift); 681 #endif 682 return w; 683 } 684 685 static inline void 686 __sum_w_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se) 687 { 688 unsigned long weight = avg_vruntime_weight(cfs_rq, se->load.weight); 689 s64 w_vruntime, key = entity_key(cfs_rq, se); 690 691 w_vruntime = key * weight; 692 WARN_ON_ONCE((w_vruntime >> 63) != (w_vruntime >> 62)); 693 694 cfs_rq->sum_w_vruntime += w_vruntime; 695 cfs_rq->sum_weight += weight; 696 } 697 698 static void 699 sum_w_vruntime_add_paranoid(struct cfs_rq *cfs_rq, struct sched_entity *se) 700 { 701 unsigned long weight; 702 s64 key, tmp; 703 704 again: 705 weight = avg_vruntime_weight(cfs_rq, se->load.weight); 706 key = entity_key(cfs_rq, se); 707 708 if (check_mul_overflow(key, weight, &key)) 709 goto overflow; 710 711 if (check_add_overflow(cfs_rq->sum_w_vruntime, key, &tmp)) 712 goto overflow; 713 714 cfs_rq->sum_w_vruntime = tmp; 715 cfs_rq->sum_weight += weight; 716 return; 717 718 overflow: 719 /* 720 * There's gotta be a limit -- if we're still failing at this point 721 * there's really nothing much to be done about things. 722 */ 723 BUG_ON(cfs_rq->sum_shift >= 10); 724 cfs_rq->sum_shift++; 725 726 /* 727 * Note: \Sum (k_i * (w_i >> 1)) != (\Sum (k_i * w_i)) >> 1 728 */ 729 cfs_rq->sum_w_vruntime = 0; 730 cfs_rq->sum_weight = 0; 731 732 for (struct rb_node *node = cfs_rq->tasks_timeline.rb_leftmost; 733 node; node = rb_next(node)) 734 __sum_w_vruntime_add(cfs_rq, __node_2_se(node)); 735 736 goto again; 737 } 738 739 static void 740 sum_w_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se) 741 { 742 if (sched_feat(PARANOID_AVG)) 743 return sum_w_vruntime_add_paranoid(cfs_rq, se); 744 745 __sum_w_vruntime_add(cfs_rq, se); 746 } 747 748 static void 749 sum_w_vruntime_sub(struct cfs_rq *cfs_rq, struct sched_entity *se) 750 { 751 unsigned long weight = avg_vruntime_weight(cfs_rq, se->load.weight); 752 s64 key = entity_key(cfs_rq, se); 753 754 cfs_rq->sum_w_vruntime -= key * weight; 755 cfs_rq->sum_weight -= weight; 756 } 757 758 static inline 759 void update_zero_vruntime(struct cfs_rq *cfs_rq, s64 delta) 760 { 761 /* 762 * v' = v + d ==> sum_w_vruntime' = sum_w_vruntime - d*sum_weight 763 */ 764 cfs_rq->sum_w_vruntime -= cfs_rq->sum_weight * delta; 765 cfs_rq->zero_vruntime += delta; 766 } 767 768 /* 769 * Specifically: avg_vruntime() + 0 must result in entity_eligible() := true 770 * For this to be so, the result of this function must have a left bias. 771 * 772 * Called in: 773 * - place_entity() -- before enqueue 774 * - update_entity_lag() -- before dequeue 775 * - update_deadline() -- slice expiration 776 * 777 * This means it is one entry 'behind' but that puts it close enough to where 778 * the bound on entity_key() is at most two lag bounds. 779 */ 780 u64 avg_vruntime(struct cfs_rq *cfs_rq) 781 { 782 struct sched_entity *curr = cfs_rq->curr; 783 long weight = cfs_rq->sum_weight; 784 s64 delta = 0; 785 786 if (curr && !curr->on_rq) 787 curr = NULL; 788 789 if (weight) { 790 s64 runtime = cfs_rq->sum_w_vruntime; 791 792 if (curr) { 793 unsigned long w = avg_vruntime_weight(cfs_rq, curr->load.weight); 794 795 runtime += entity_key(cfs_rq, curr) * w; 796 weight += w; 797 } 798 799 /* sign flips effective floor / ceiling */ 800 if (runtime < 0) 801 runtime -= (weight - 1); 802 803 delta = div64_long(runtime, weight); 804 } else if (curr) { 805 /* 806 * When there is but one element, it is the average. 807 */ 808 delta = curr->vruntime - cfs_rq->zero_vruntime; 809 } 810 811 update_zero_vruntime(cfs_rq, delta); 812 813 return cfs_rq->zero_vruntime; 814 } 815 816 static inline u64 cfs_rq_max_slice(struct cfs_rq *cfs_rq); 817 818 /* 819 * lag_i = S - s_i = w_i * (V - v_i) 820 * 821 * However, since V is approximated by the weighted average of all entities it 822 * is possible -- by addition/removal/reweight to the tree -- to move V around 823 * and end up with a larger lag than we started with. 824 * 825 * Limit this to either double the slice length with a minimum of TICK_NSEC 826 * since that is the timing granularity. 827 * 828 * EEVDF gives the following limit for a steady state system: 829 * 830 * -r_max < lag < max(r_max, q) 831 */ 832 static s64 entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se, u64 avruntime) 833 { 834 u64 max_slice = cfs_rq_max_slice(cfs_rq) + TICK_NSEC; 835 s64 vlag, limit; 836 837 vlag = avruntime - se->vruntime; 838 limit = calc_delta_fair(max_slice, se); 839 840 return clamp(vlag, -limit, limit); 841 } 842 843 /* 844 * Delayed dequeue aims to reduce the negative lag of a dequeued task. While 845 * updating the lag of an entity, check that negative lag didn't increase 846 * during the delayed dequeue period which would be unfair. 847 * Similarly, check that the entity didn't gain positive lag when DELAY_ZERO 848 * is set. 849 * 850 * Return true if the vlag has been modified. Specifically: 851 * 852 * se->vlag != avg_vruntime() - se->vruntime 853 * 854 * This can be due to clamping in entity_lag() or clamping due to 855 * sched_delayed. Either way, when vlag is modified and the entity is 856 * retained, the tree needs to be adjusted. 857 */ 858 static __always_inline 859 bool update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se) 860 { 861 u64 avruntime = avg_vruntime(cfs_rq); 862 s64 vlag = entity_lag(cfs_rq, se, avruntime); 863 864 WARN_ON_ONCE(!se->on_rq); 865 866 if (se->sched_delayed) { 867 /* previous vlag < 0 otherwise se would not be delayed */ 868 vlag = max(vlag, se->vlag); 869 if (sched_feat(DELAY_ZERO)) 870 vlag = min(vlag, 0); 871 } 872 se->vlag = vlag; 873 874 return avruntime - vlag != se->vruntime; 875 } 876 877 /* 878 * Entity is eligible once it received less service than it ought to have, 879 * eg. lag >= 0. 880 * 881 * lag_i = S - s_i = w_i*(V - v_i) 882 * 883 * lag_i >= 0 -> V >= v_i 884 * 885 * \Sum (v_i - v0)*w_i 886 * V = ------------------- + v0 887 * \Sum w_i 888 * 889 * lag_i >= 0 -> \Sum (v_i - v0)*w_i >= (v_i - v0)*(\Sum w_i) 890 * 891 * Note: using 'avg_vruntime() > se->vruntime' is inaccurate due 892 * to the loss in precision caused by the division. 893 */ 894 static int vruntime_eligible(struct cfs_rq *cfs_rq, u64 vruntime) 895 { 896 struct sched_entity *curr = cfs_rq->curr; 897 s64 key, avg = cfs_rq->sum_w_vruntime; 898 long load = cfs_rq->sum_weight; 899 900 if (curr && curr->on_rq) { 901 unsigned long weight = avg_vruntime_weight(cfs_rq, curr->load.weight); 902 903 avg += entity_key(cfs_rq, curr) * weight; 904 load += weight; 905 } 906 907 key = vruntime_op(vruntime, "-", cfs_rq->zero_vruntime); 908 909 /* 910 * The worst case term for @key includes 'NSEC_TICK * NICE_0_LOAD' 911 * and @load obviously includes NICE_0_LOAD. NSEC_TICK is around 24 912 * bits, while NICE_0_LOAD is 20 on 64bit and 10 otherwise. 913 * 914 * This gives that on 64bit the product will be at least 64bit which 915 * overflows s64, while on 32bit it will only be 44bits and should fit 916 * comfortably. 917 */ 918 #ifdef CONFIG_64BIT 919 #ifdef CONFIG_ARCH_SUPPORTS_INT128 920 /* This often results in simpler code than __builtin_mul_overflow(). */ 921 return avg >= (__int128)key * load; 922 #else 923 s64 rhs; 924 /* 925 * On overflow, the sign of key tells us the correct answer: a large 926 * positive key means vruntime >> V, so not eligible; a large negative 927 * key means vruntime << V, so eligible. 928 */ 929 if (check_mul_overflow(key, load, &rhs)) 930 return key <= 0; 931 932 return avg >= rhs; 933 #endif 934 #else /* 32bit */ 935 return avg >= key * load; 936 #endif 937 } 938 939 int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se) 940 { 941 return vruntime_eligible(cfs_rq, se->vruntime); 942 } 943 944 static inline u64 cfs_rq_min_slice(struct cfs_rq *cfs_rq) 945 { 946 struct sched_entity *root = __pick_root_entity(cfs_rq); 947 struct sched_entity *curr = cfs_rq->curr; 948 u64 min_slice = ~0ULL; 949 950 if (curr && curr->on_rq) 951 min_slice = curr->slice; 952 953 if (root) 954 min_slice = min(min_slice, root->min_slice); 955 956 return min_slice; 957 } 958 959 static inline u64 cfs_rq_max_slice(struct cfs_rq *cfs_rq) 960 { 961 struct sched_entity *root = __pick_root_entity(cfs_rq); 962 struct sched_entity *curr = cfs_rq->curr; 963 u64 max_slice = 0ULL; 964 965 if (curr && curr->on_rq) 966 max_slice = curr->slice; 967 968 if (root) 969 max_slice = max(max_slice, root->max_slice); 970 971 return max_slice; 972 } 973 974 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b) 975 { 976 return entity_before(__node_2_se(a), __node_2_se(b)); 977 } 978 979 static inline void __min_vruntime_update(struct sched_entity *se, struct rb_node *node) 980 { 981 if (node) { 982 struct sched_entity *rse = __node_2_se(node); 983 984 if (vruntime_cmp(se->min_vruntime, ">", rse->min_vruntime)) 985 se->min_vruntime = rse->min_vruntime; 986 } 987 } 988 989 static inline void __min_slice_update(struct sched_entity *se, struct rb_node *node) 990 { 991 if (node) { 992 struct sched_entity *rse = __node_2_se(node); 993 if (rse->min_slice < se->min_slice) 994 se->min_slice = rse->min_slice; 995 } 996 } 997 998 static inline void __max_slice_update(struct sched_entity *se, struct rb_node *node) 999 { 1000 if (node) { 1001 struct sched_entity *rse = __node_2_se(node); 1002 if (rse->max_slice > se->max_slice) 1003 se->max_slice = rse->max_slice; 1004 } 1005 } 1006 1007 /* 1008 * se->min_vruntime = min(se->vruntime, {left,right}->min_vruntime) 1009 */ 1010 static inline bool min_vruntime_update(struct sched_entity *se, bool exit) 1011 { 1012 u64 old_min_vruntime = se->min_vruntime; 1013 u64 old_min_slice = se->min_slice; 1014 u64 old_max_slice = se->max_slice; 1015 struct rb_node *node = &se->run_node; 1016 1017 se->min_vruntime = se->vruntime; 1018 __min_vruntime_update(se, node->rb_right); 1019 __min_vruntime_update(se, node->rb_left); 1020 1021 se->min_slice = se->slice; 1022 __min_slice_update(se, node->rb_right); 1023 __min_slice_update(se, node->rb_left); 1024 1025 se->max_slice = se->slice; 1026 __max_slice_update(se, node->rb_right); 1027 __max_slice_update(se, node->rb_left); 1028 1029 return se->min_vruntime == old_min_vruntime && 1030 se->min_slice == old_min_slice && 1031 se->max_slice == old_max_slice; 1032 } 1033 1034 RB_DECLARE_CALLBACKS(static, min_vruntime_cb, struct sched_entity, 1035 run_node, min_vruntime, min_vruntime_update); 1036 1037 /* 1038 * Enqueue an entity into the rb-tree: 1039 */ 1040 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) 1041 { 1042 sum_w_vruntime_add(cfs_rq, se); 1043 se->min_vruntime = se->vruntime; 1044 se->min_slice = se->slice; 1045 rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline, 1046 __entity_less, &min_vruntime_cb); 1047 } 1048 1049 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) 1050 { 1051 rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline, 1052 &min_vruntime_cb); 1053 sum_w_vruntime_sub(cfs_rq, se); 1054 } 1055 1056 struct sched_entity *__pick_root_entity(struct cfs_rq *cfs_rq) 1057 { 1058 struct rb_node *root = cfs_rq->tasks_timeline.rb_root.rb_node; 1059 1060 if (!root) 1061 return NULL; 1062 1063 return __node_2_se(root); 1064 } 1065 1066 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq) 1067 { 1068 struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline); 1069 1070 if (!left) 1071 return NULL; 1072 1073 return __node_2_se(left); 1074 } 1075 1076 /* 1077 * Set the vruntime up to which an entity can run before looking 1078 * for another entity to pick. 1079 * In case of run to parity, we use the shortest slice of the enqueued 1080 * entities to set the protected period. 1081 * When run to parity is disabled, we give a minimum quantum to the running 1082 * entity to ensure progress. 1083 */ 1084 static inline void set_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se) 1085 { 1086 u64 slice = normalized_sysctl_sched_base_slice; 1087 u64 vprot = se->deadline; 1088 1089 if (sched_feat(RUN_TO_PARITY)) 1090 slice = cfs_rq_min_slice(cfs_rq); 1091 1092 slice = min(slice, se->slice); 1093 if (slice != se->slice) 1094 vprot = min_vruntime(vprot, se->vruntime + calc_delta_fair(slice, se)); 1095 1096 se->vprot = vprot; 1097 } 1098 1099 static inline void update_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se) 1100 { 1101 u64 slice = cfs_rq_min_slice(cfs_rq); 1102 1103 se->vprot = min_vruntime(se->vprot, se->vruntime + calc_delta_fair(slice, se)); 1104 } 1105 1106 static inline bool protect_slice(struct sched_entity *se) 1107 { 1108 return vruntime_cmp(se->vruntime, "<", se->vprot); 1109 } 1110 1111 static inline void cancel_protect_slice(struct sched_entity *se) 1112 { 1113 if (protect_slice(se)) 1114 se->vprot = se->vruntime; 1115 } 1116 1117 /* 1118 * Earliest Eligible Virtual Deadline First 1119 * 1120 * In order to provide latency guarantees for different request sizes 1121 * EEVDF selects the best runnable task from two criteria: 1122 * 1123 * 1) the task must be eligible (must be owed service) 1124 * 1125 * 2) from those tasks that meet 1), we select the one 1126 * with the earliest virtual deadline. 1127 * 1128 * We can do this in O(log n) time due to an augmented RB-tree. The 1129 * tree keeps the entries sorted on deadline, but also functions as a 1130 * heap based on the vruntime by keeping: 1131 * 1132 * se->min_vruntime = min(se->vruntime, se->{left,right}->min_vruntime) 1133 * 1134 * Which allows tree pruning through eligibility. 1135 */ 1136 static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq, bool protect) 1137 { 1138 struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node; 1139 struct sched_entity *se = __pick_first_entity(cfs_rq); 1140 struct sched_entity *curr = cfs_rq->curr; 1141 struct sched_entity *best = NULL; 1142 1143 /* 1144 * We can safely skip eligibility check if there is only one entity 1145 * in this cfs_rq, saving some cycles. 1146 */ 1147 if (cfs_rq->nr_queued == 1) 1148 return curr && curr->on_rq ? curr : se; 1149 1150 /* 1151 * Picking the ->next buddy will affect latency but not fairness. 1152 */ 1153 if (sched_feat(PICK_BUDDY) && protect && 1154 cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next)) { 1155 /* ->next will never be delayed */ 1156 WARN_ON_ONCE(cfs_rq->next->sched_delayed); 1157 return cfs_rq->next; 1158 } 1159 1160 if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr))) 1161 curr = NULL; 1162 1163 if (curr && protect && protect_slice(curr)) 1164 return curr; 1165 1166 /* Pick the leftmost entity if it's eligible */ 1167 if (se && entity_eligible(cfs_rq, se)) { 1168 best = se; 1169 goto found; 1170 } 1171 1172 /* Heap search for the EEVD entity */ 1173 while (node) { 1174 struct rb_node *left = node->rb_left; 1175 1176 /* 1177 * Eligible entities in left subtree are always better 1178 * choices, since they have earlier deadlines. 1179 */ 1180 if (left && vruntime_eligible(cfs_rq, 1181 __node_2_se(left)->min_vruntime)) { 1182 node = left; 1183 continue; 1184 } 1185 1186 se = __node_2_se(node); 1187 1188 /* 1189 * The left subtree either is empty or has no eligible 1190 * entity, so check the current node since it is the one 1191 * with earliest deadline that might be eligible. 1192 */ 1193 if (entity_eligible(cfs_rq, se)) { 1194 best = se; 1195 break; 1196 } 1197 1198 node = node->rb_right; 1199 } 1200 found: 1201 if (!best || (curr && entity_before(curr, best))) 1202 best = curr; 1203 1204 return best; 1205 } 1206 1207 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq) 1208 { 1209 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root); 1210 1211 if (!last) 1212 return NULL; 1213 1214 return __node_2_se(last); 1215 } 1216 1217 /************************************************************** 1218 * Scheduling class statistics methods: 1219 */ 1220 int sched_update_scaling(void) 1221 { 1222 unsigned int factor = get_update_sysctl_factor(); 1223 1224 #define WRT_SYSCTL(name) \ 1225 (normalized_sysctl_##name = sysctl_##name / (factor)) 1226 WRT_SYSCTL(sched_base_slice); 1227 #undef WRT_SYSCTL 1228 1229 return 0; 1230 } 1231 1232 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se); 1233 1234 /* 1235 * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i 1236 * this is probably good enough. 1237 */ 1238 static bool update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se) 1239 { 1240 if (vruntime_cmp(se->vruntime, "<", se->deadline)) 1241 return false; 1242 1243 /* 1244 * For EEVDF the virtual time slope is determined by w_i (iow. 1245 * nice) while the request time r_i is determined by 1246 * sysctl_sched_base_slice. 1247 */ 1248 if (!se->custom_slice) 1249 se->slice = sysctl_sched_base_slice; 1250 1251 /* 1252 * EEVDF: vd_i = ve_i + r_i / w_i 1253 */ 1254 se->deadline = se->vruntime + calc_delta_fair(se->slice, se); 1255 avg_vruntime(cfs_rq); 1256 1257 /* 1258 * The task has consumed its request, reschedule. 1259 */ 1260 return true; 1261 } 1262 1263 #include "pelt.h" 1264 1265 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu); 1266 static unsigned long task_h_load(struct task_struct *p); 1267 static unsigned long capacity_of(int cpu); 1268 1269 /* Give new sched_entity start runnable values to heavy its load in infant time */ 1270 void init_entity_runnable_average(struct sched_entity *se) 1271 { 1272 struct sched_avg *sa = &se->avg; 1273 1274 memset(sa, 0, sizeof(*sa)); 1275 1276 /* 1277 * Tasks are initialized with full load to be seen as heavy tasks until 1278 * they get a chance to stabilize to their real load level. 1279 * Group entities are initialized with zero load to reflect the fact that 1280 * nothing has been attached to the task group yet. 1281 */ 1282 if (entity_is_task(se)) 1283 sa->load_avg = scale_load_down(se->load.weight); 1284 1285 /* when this task is enqueued, it will contribute to its cfs_rq's load_avg */ 1286 } 1287 1288 /* 1289 * With new tasks being created, their initial util_avgs are extrapolated 1290 * based on the cfs_rq's current util_avg: 1291 * 1292 * util_avg = cfs_rq->avg.util_avg / (cfs_rq->avg.load_avg + 1) 1293 * * se_weight(se) 1294 * 1295 * However, in many cases, the above util_avg does not give a desired 1296 * value. Moreover, the sum of the util_avgs may be divergent, such 1297 * as when the series is a harmonic series. 1298 * 1299 * To solve this problem, we also cap the util_avg of successive tasks to 1300 * only 1/2 of the left utilization budget: 1301 * 1302 * util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n 1303 * 1304 * where n denotes the nth task and cpu_scale the CPU capacity. 1305 * 1306 * For example, for a CPU with 1024 of capacity, a simplest series from 1307 * the beginning would be like: 1308 * 1309 * task util_avg: 512, 256, 128, 64, 32, 16, 8, ... 1310 * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ... 1311 * 1312 * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap) 1313 * if util_avg > util_avg_cap. 1314 */ 1315 void post_init_entity_util_avg(struct task_struct *p) 1316 { 1317 struct sched_entity *se = &p->se; 1318 struct cfs_rq *cfs_rq = cfs_rq_of(se); 1319 struct sched_avg *sa = &se->avg; 1320 long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq))); 1321 long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2; 1322 1323 if (p->sched_class != &fair_sched_class) { 1324 /* 1325 * For !fair tasks do: 1326 * 1327 update_cfs_rq_load_avg(now, cfs_rq); 1328 attach_entity_load_avg(cfs_rq, se); 1329 switched_from_fair(rq, p); 1330 * 1331 * such that the next switched_to_fair() has the 1332 * expected state. 1333 */ 1334 se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq); 1335 return; 1336 } 1337 1338 if (cap > 0) { 1339 if (cfs_rq->avg.util_avg != 0) { 1340 sa->util_avg = cfs_rq->avg.util_avg * se_weight(se); 1341 sa->util_avg /= (cfs_rq->avg.load_avg + 1); 1342 1343 if (sa->util_avg > cap) 1344 sa->util_avg = cap; 1345 } else { 1346 sa->util_avg = cap; 1347 } 1348 } 1349 1350 sa->runnable_avg = sa->util_avg; 1351 } 1352 1353 static inline void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec); 1354 1355 static s64 update_se(struct rq *rq, struct sched_entity *se) 1356 { 1357 u64 now = rq_clock_task(rq); 1358 s64 delta_exec; 1359 1360 delta_exec = now - se->exec_start; 1361 if (unlikely(delta_exec <= 0)) 1362 return delta_exec; 1363 1364 se->exec_start = now; 1365 if (entity_is_task(se)) { 1366 struct task_struct *donor = task_of(se); 1367 struct task_struct *running = rq->curr; 1368 /* 1369 * If se is a task, we account the time against the running 1370 * task, as w/ proxy-exec they may not be the same. 1371 */ 1372 running->se.exec_start = now; 1373 running->se.sum_exec_runtime += delta_exec; 1374 1375 trace_sched_stat_runtime(running, delta_exec); 1376 account_group_exec_runtime(running, delta_exec); 1377 account_mm_sched(rq, running, delta_exec); 1378 1379 /* cgroup time is always accounted against the donor */ 1380 cgroup_account_cputime(donor, delta_exec); 1381 } else { 1382 /* If not task, account the time against donor se */ 1383 se->sum_exec_runtime += delta_exec; 1384 } 1385 1386 if (schedstat_enabled()) { 1387 struct sched_statistics *stats; 1388 1389 stats = __schedstats_from_se(se); 1390 __schedstat_set(stats->exec_max, 1391 max(delta_exec, stats->exec_max)); 1392 } 1393 1394 return delta_exec; 1395 } 1396 1397 static void set_next_buddy(struct sched_entity *se); 1398 1399 #ifdef CONFIG_SCHED_CACHE 1400 1401 /* 1402 * XXX numbers come from a place the sun don't shine -- probably wants to be SD 1403 * tunable or so. 1404 */ 1405 #define EPOCH_PERIOD (HZ / 100) /* 10 ms */ 1406 #define EPOCH_LLC_AFFINITY_TIMEOUT 5 /* 50 ms */ 1407 __read_mostly unsigned int llc_aggr_tolerance = 1; 1408 __read_mostly unsigned int llc_epoch_period = EPOCH_PERIOD; 1409 __read_mostly unsigned int llc_epoch_affinity_timeout = EPOCH_LLC_AFFINITY_TIMEOUT; 1410 __read_mostly unsigned int llc_imb_pct = 20; 1411 __read_mostly unsigned int llc_overaggr_pct = 50; 1412 1413 static int llc_id(int cpu) 1414 { 1415 if (cpu < 0) 1416 return -1; 1417 1418 return per_cpu(sd_llc_id, cpu); 1419 } 1420 1421 static inline int get_sched_cache_scale(int mul) 1422 { 1423 unsigned int tol = READ_ONCE(llc_aggr_tolerance); 1424 1425 if (!tol) 1426 return 0; 1427 1428 if (tol >= 100) 1429 return INT_MAX; 1430 1431 return (1 + (tol - 1) * mul); 1432 } 1433 1434 static bool exceed_llc_capacity(struct mm_struct *mm, int cpu) 1435 { 1436 #ifdef CONFIG_NUMA_BALANCING 1437 unsigned long llc, footprint; 1438 struct sched_domain *sd; 1439 int scale; 1440 1441 guard(rcu)(); 1442 1443 sd = rcu_dereference_sched_domain(cpu_rq(cpu)->sd); 1444 if (!sd) 1445 return true; 1446 1447 if (static_branch_likely(&sched_numa_balancing)) { 1448 /* 1449 * TBD: RDT exclusive LLC ways reserved should be 1450 * excluded. 1451 */ 1452 llc = sd->llc_bytes; 1453 footprint = READ_ONCE(mm->sc_stat.footprint); 1454 1455 /* 1456 * Scale the LLC size by 256*llc_aggr_tolerance 1457 * and compare it to the task's footprint. 1458 * 1459 * Suppose the L3 size is 32MB. If the 1460 * llc_aggr_tolerance is 1: 1461 * When the footprint is larger than 32MB, the 1462 * process is regarded as exceeding the LLC 1463 * capacity. If the llc_aggr_tolerance is 99: 1464 * When the footprint is larger than 784GB, the 1465 * process is regarded as exceeding the LLC 1466 * capacity: 1467 * 784GB = (1 + (99 - 1) * 256) * 32MB 1468 * If the llc_aggr_tolerance is 100: 1469 * ignore the footprint and do the aggregation 1470 * anyway. 1471 */ 1472 scale = get_sched_cache_scale(256); 1473 if (scale == INT_MAX) 1474 return false; 1475 1476 return ((llc * (u64)scale) < (footprint * PAGE_SIZE)); 1477 } 1478 #endif 1479 return false; 1480 } 1481 1482 static bool invalid_llc_nr(struct mm_struct *mm, struct task_struct *p, 1483 int cpu) 1484 { 1485 int scale; 1486 1487 if (get_nr_threads(p) <= 1) 1488 return true; 1489 1490 /* 1491 * Scale the number of 'cores' in a LLC by llc_aggr_tolerance 1492 * and compare it to the task's active threads. 1493 */ 1494 scale = get_sched_cache_scale(1); 1495 if (scale == INT_MAX) 1496 return false; 1497 1498 return !fits_capacity((mm->sc_stat.nr_running_avg * cpu_smt_num_threads), 1499 (scale * per_cpu(sd_llc_size, cpu))); 1500 } 1501 1502 static void account_llc_enqueue(struct rq *rq, struct task_struct *p) 1503 { 1504 int pref_llc, pref_llc_queued; 1505 struct sched_domain *sd; 1506 1507 pref_llc = p->preferred_llc; 1508 if (pref_llc < 0) 1509 return; 1510 1511 pref_llc_queued = (pref_llc == task_llc(p)); 1512 rq->nr_llc_running++; 1513 rq->nr_pref_llc_running += pref_llc_queued; 1514 1515 /* 1516 * Record whether p is enqueued on its preferred 1517 * LLC, in order to pair with account_llc_dequeue() 1518 * to maintain a consistent nr_pref_llc_running per 1519 * runqueue. 1520 * This is necessary because a race condition exists: 1521 * after a task is enqueued on a runqueue, task_llc(p) 1522 * may change due to CPU hotplug. Therefore, checking 1523 * task_llc(p) to determine whether the task is being 1524 * dequeued from its preferred LLC is unreliable and 1525 * can cause inconsistent values - checking the 1526 * p->pref_llc_queued in account_llc_dequeue() would 1527 * be reliable. 1528 */ 1529 p->pref_llc_queued = pref_llc_queued; 1530 1531 sd = rcu_dereference_all(rq->sd); 1532 if (sd && (unsigned int)pref_llc < sd->llc_max) 1533 sd->llc_counts[pref_llc]++; 1534 } 1535 1536 static void account_llc_dequeue(struct rq *rq, struct task_struct *p) 1537 { 1538 struct sched_domain *sd; 1539 int pref_llc; 1540 1541 pref_llc = p->preferred_llc; 1542 if (pref_llc < 0) 1543 return; 1544 1545 rq->nr_llc_running--; 1546 if (p->pref_llc_queued) { 1547 rq->nr_pref_llc_running--; 1548 /* 1549 * Update the status in case 1550 * other logic might query 1551 * this. 1552 */ 1553 p->pref_llc_queued = 0; 1554 } 1555 1556 sd = rcu_dereference_all(rq->sd); 1557 if (sd && (unsigned int)pref_llc < sd->llc_max) { 1558 /* 1559 * There is a race condition between dequeue 1560 * and CPU hotplug. After a task has been enqueued 1561 * on CPUx, a CPU hotplug event occurs, and all online 1562 * CPUs (including CPUx) rebuild their sched_domains 1563 * and reset statistics to zero(including sd->llc_counts). 1564 * This can cause temporary undercount and we have to 1565 * check for such underflow in sd->llc_counts. 1566 * 1567 * This undercount is temporary and accurate accounting 1568 * will resume once the rq has a chance to be idle. 1569 */ 1570 if (sd->llc_counts[pref_llc]) 1571 sd->llc_counts[pref_llc]--; 1572 } 1573 } 1574 1575 void mm_init_sched(struct mm_struct *mm, 1576 struct sched_cache_time __percpu *_pcpu_sched) 1577 { 1578 unsigned long epoch = 0; 1579 int i; 1580 1581 for_each_possible_cpu(i) { 1582 struct sched_cache_time *pcpu_sched = per_cpu_ptr(_pcpu_sched, i); 1583 struct rq *rq = cpu_rq(i); 1584 1585 pcpu_sched->runtime = 0; 1586 /* a slightly stale cpu epoch is acceptible */ 1587 pcpu_sched->epoch = rq->cpu_epoch; 1588 epoch = rq->cpu_epoch; 1589 } 1590 1591 raw_spin_lock_init(&mm->sc_stat.lock); 1592 mm->sc_stat.epoch = epoch; 1593 mm->sc_stat.cpu = -1; 1594 mm->sc_stat.next_scan = jiffies; 1595 mm->sc_stat.nr_running_avg = 0; 1596 mm->sc_stat.footprint = 0; 1597 /* 1598 * The update to mm->sc_stat should not be reordered 1599 * before initialization to mm's other fields, in case 1600 * the readers may get invalid mm_sched_epoch, etc. 1601 */ 1602 smp_store_release(&mm->sc_stat.pcpu_sched, _pcpu_sched); 1603 } 1604 1605 /* because why would C be fully specified */ 1606 static __always_inline void __shr_u64(u64 *val, unsigned int n) 1607 { 1608 if (n >= 64) { 1609 *val = 0; 1610 return; 1611 } 1612 *val >>= n; 1613 } 1614 1615 static inline void __update_mm_sched(struct rq *rq, 1616 struct sched_cache_time *pcpu_sched) 1617 { 1618 lockdep_assert_held(&rq->cpu_epoch_lock); 1619 1620 unsigned int period = max(READ_ONCE(llc_epoch_period), 1U); 1621 unsigned long n, now = jiffies; 1622 long delta = now - rq->cpu_epoch_next; 1623 1624 if (delta > 0) { 1625 n = (delta + period - 1) / period; 1626 rq->cpu_epoch += n; 1627 rq->cpu_epoch_next += n * period; 1628 __shr_u64(&rq->cpu_runtime, n); 1629 } 1630 1631 n = rq->cpu_epoch - pcpu_sched->epoch; 1632 if (n) { 1633 pcpu_sched->epoch += n; 1634 __shr_u64(&pcpu_sched->runtime, n); 1635 } 1636 } 1637 1638 static unsigned long fraction_mm_sched(struct rq *rq, 1639 struct sched_cache_time *pcpu_sched) 1640 { 1641 guard(raw_spinlock_irqsave)(&rq->cpu_epoch_lock); 1642 1643 __update_mm_sched(rq, pcpu_sched); 1644 1645 /* 1646 * Runtime is a geometric series (r=0.5) and as such will sum to twice 1647 * the accumulation period, this means the multiplcation here should 1648 * not overflow. 1649 */ 1650 return div64_u64(NICE_0_LOAD * pcpu_sched->runtime, rq->cpu_runtime + 1); 1651 } 1652 1653 static int get_pref_llc(struct task_struct *p, struct mm_struct *mm) 1654 { 1655 int mm_sched_llc = -1, mm_sched_cpu; 1656 1657 if (!mm) 1658 return -1; 1659 1660 mm_sched_cpu = READ_ONCE(mm->sc_stat.cpu); 1661 if (mm_sched_cpu != -1) { 1662 mm_sched_llc = llc_id(mm_sched_cpu); 1663 1664 #ifdef CONFIG_NUMA_BALANCING 1665 /* 1666 * Don't assign preferred LLC if it 1667 * conflicts with NUMA balancing. 1668 * This can happen when sched_setnuma() gets 1669 * called, however it is not much of an issue 1670 * because we expect account_mm_sched() to get 1671 * called fairly regularly -- at a higher rate 1672 * than sched_setnuma() at least -- and thus the 1673 * conflict only exists for a short period of time. 1674 */ 1675 if (static_branch_likely(&sched_numa_balancing) && 1676 p->numa_preferred_nid >= 0 && 1677 cpu_to_node(mm_sched_cpu) != p->numa_preferred_nid) 1678 mm_sched_llc = -1; 1679 #endif 1680 } 1681 1682 return mm_sched_llc; 1683 } 1684 1685 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p); 1686 1687 static inline 1688 void account_mm_sched(struct rq *rq, struct task_struct *p, s64 delta_exec) 1689 { 1690 struct sched_cache_time *pcpu_sched; 1691 struct mm_struct *mm = p->mm; 1692 int mm_sched_llc = -1; 1693 unsigned long epoch; 1694 1695 if (!sched_cache_enabled()) 1696 return; 1697 1698 if (p->sched_class != &fair_sched_class) 1699 return; 1700 /* 1701 * init_task, kthreads and user thread created 1702 * by user_mode_thread() don't have mm. 1703 */ 1704 if (!mm || !mm->sc_stat.pcpu_sched) 1705 return; 1706 1707 pcpu_sched = per_cpu_ptr(mm->sc_stat.pcpu_sched, cpu_of(rq)); 1708 1709 scoped_guard (raw_spinlock, &rq->cpu_epoch_lock) { 1710 __update_mm_sched(rq, pcpu_sched); 1711 pcpu_sched->runtime += delta_exec; 1712 rq->cpu_runtime += delta_exec; 1713 epoch = rq->cpu_epoch; 1714 } 1715 1716 /* 1717 * If this process hasn't hit task_cache_work() for a while invalidate 1718 * its preferred state. 1719 */ 1720 if ((long)(epoch - READ_ONCE(mm->sc_stat.epoch)) > llc_epoch_affinity_timeout || 1721 invalid_llc_nr(mm, p, cpu_of(rq)) || 1722 exceed_llc_capacity(mm, cpu_of(rq))) { 1723 if (READ_ONCE(mm->sc_stat.cpu) != -1) 1724 WRITE_ONCE(mm->sc_stat.cpu, -1); 1725 } 1726 1727 mm_sched_llc = get_pref_llc(p, mm); 1728 1729 /* task not on rq accounted later in account_entity_enqueue() */ 1730 if (task_running_on_cpu(rq->cpu, p) && 1731 READ_ONCE(p->preferred_llc) != mm_sched_llc) { 1732 account_llc_dequeue(rq, p); 1733 WRITE_ONCE(p->preferred_llc, mm_sched_llc); 1734 account_llc_enqueue(rq, p); 1735 } 1736 } 1737 1738 static void task_tick_cache(struct rq *rq, struct task_struct *p) 1739 { 1740 struct callback_head *work = &p->cache_work; 1741 struct mm_struct *mm = p->mm; 1742 unsigned long epoch; 1743 1744 if (!sched_cache_enabled()) 1745 return; 1746 1747 if (!mm || p->flags & PF_KTHREAD || 1748 !mm->sc_stat.pcpu_sched) 1749 return; 1750 1751 epoch = rq->cpu_epoch; 1752 /* avoid moving backwards */ 1753 if (time_after_eq(mm->sc_stat.epoch, epoch)) 1754 return; 1755 1756 guard(raw_spinlock)(&mm->sc_stat.lock); 1757 1758 if (work->next == work) { 1759 task_work_add(p, work, TWA_RESUME); 1760 WRITE_ONCE(mm->sc_stat.epoch, epoch); 1761 } 1762 } 1763 1764 static void get_scan_cpumasks(cpumask_var_t cpus, struct task_struct *p) 1765 { 1766 #ifdef CONFIG_NUMA_BALANCING 1767 int cpu, curr_cpu, nid, pref_nid; 1768 1769 if (!static_branch_likely(&sched_numa_balancing)) 1770 goto out; 1771 1772 cpu = READ_ONCE(p->mm->sc_stat.cpu); 1773 if (cpu != -1) 1774 nid = cpu_to_node(cpu); 1775 curr_cpu = task_cpu(p); 1776 1777 /* 1778 * Scanning in the preferred NUMA node is ideal. However, the NUMA 1779 * preferred node is per-task rather than per-process. It is possible 1780 * for different threads of the process to have distinct preferred 1781 * nodes; consequently, the process-wide preferred LLC may bounce 1782 * between different nodes. As a workaround, maintain the scan 1783 * CPU mask to also cover the process's current preferred LLC and the 1784 * current running node to mitigate the bouncing risk. 1785 * TBD: numa_group should be considered during task aggregation. 1786 */ 1787 pref_nid = p->numa_preferred_nid; 1788 /* honor the task's preferred node */ 1789 if (pref_nid == NUMA_NO_NODE) 1790 goto out; 1791 1792 cpumask_or(cpus, cpus, cpumask_of_node(pref_nid)); 1793 1794 /* honor the task's preferred LLC CPU */ 1795 if (cpu != -1 && !cpumask_test_cpu(cpu, cpus) && nid != NUMA_NO_NODE) 1796 cpumask_or(cpus, cpus, cpumask_of_node(nid)); 1797 1798 /* make sure the task's current running node is included */ 1799 if (!cpumask_test_cpu(curr_cpu, cpus)) 1800 cpumask_or(cpus, cpus, cpumask_of_node(cpu_to_node(curr_cpu))); 1801 1802 return; 1803 1804 out: 1805 #endif 1806 cpumask_copy(cpus, cpu_online_mask); 1807 } 1808 1809 static inline void update_avg_scale(u64 *avg, u64 sample) 1810 { 1811 int factor = per_cpu(sd_llc_size, raw_smp_processor_id()); 1812 s64 diff = sample - *avg; 1813 u32 divisor; 1814 1815 /* 1816 * Scale the divisor based on the number of CPUs contained 1817 * in the LLC. This scaling ensures smaller LLC domains use 1818 * a smaller divisor to achieve more precise sensitivity to 1819 * changes in nr_running, while larger LLC domains are capped 1820 * at a maximum divisor of 8 which is the default smoothing 1821 * factor of EWMA in update_avg(). 1822 */ 1823 divisor = clamp_t(u32, (factor >> 2), 2, 8); 1824 *avg += div64_s64(diff, divisor); 1825 } 1826 1827 static void task_cache_work(struct callback_head *work) 1828 { 1829 int cpu, m_a_cpu = -1, nr_running = 0, curr_cpu; 1830 unsigned long next_scan, now = jiffies; 1831 struct task_struct *p = current, *cur; 1832 unsigned long curr_m_a_occ = 0; 1833 struct mm_struct *mm = p->mm; 1834 unsigned long m_a_occ = 0; 1835 cpumask_var_t cpus; 1836 1837 WARN_ON_ONCE(work != &p->cache_work); 1838 1839 work->next = work; 1840 1841 if (p->flags & PF_EXITING) 1842 return; 1843 1844 next_scan = READ_ONCE(mm->sc_stat.next_scan); 1845 if (time_before(now, next_scan)) 1846 return; 1847 1848 /* only 1 thread is allowed to scan */ 1849 if (!try_cmpxchg(&mm->sc_stat.next_scan, &next_scan, 1850 now + max_t(unsigned long, 1851 READ_ONCE(llc_epoch_period), 1))) 1852 return; 1853 1854 curr_cpu = task_cpu(p); 1855 if (invalid_llc_nr(mm, p, curr_cpu) || 1856 exceed_llc_capacity(mm, curr_cpu)) { 1857 if (READ_ONCE(mm->sc_stat.cpu) != -1) 1858 WRITE_ONCE(mm->sc_stat.cpu, -1); 1859 1860 return; 1861 } 1862 1863 if (!zalloc_cpumask_var(&cpus, GFP_KERNEL)) 1864 return; 1865 1866 scoped_guard (cpus_read_lock) { 1867 guard(rcu)(); 1868 1869 get_scan_cpumasks(cpus, p); 1870 1871 for_each_cpu(cpu, cpus) { 1872 /* XXX sched_cluster_active */ 1873 struct sched_domain *sd = rcu_dereference_all(per_cpu(sd_llc, cpu)); 1874 unsigned long occ, m_occ = 0, a_occ = 0; 1875 int m_cpu = -1, i; 1876 1877 if (!sd) 1878 continue; 1879 1880 for_each_cpu(i, sched_domain_span(sd)) { 1881 occ = fraction_mm_sched(cpu_rq(i), 1882 per_cpu_ptr(mm->sc_stat.pcpu_sched, i)); 1883 a_occ += occ; 1884 if (occ > m_occ) { 1885 m_occ = occ; 1886 m_cpu = i; 1887 } 1888 1889 cur = rcu_dereference_all(cpu_rq(i)->curr); 1890 if (cur && !(cur->flags & (PF_EXITING | PF_KTHREAD)) && 1891 cur->mm == mm) 1892 nr_running++; 1893 } 1894 1895 /* 1896 * Compare the accumulated occupancy of each LLC. The 1897 * reason for using accumulated occupancy rather than average 1898 * per CPU occupancy is that it works better in asymmetric LLC 1899 * scenarios. 1900 * For example, if there are 2 threads in a 4CPU LLC and 3 1901 * threads in an 8CPU LLC, it might be better to choose the one 1902 * with 3 threads. However, this would not be the case if the 1903 * occupancy is divided by the number of CPUs in an LLC (i.e., 1904 * if average per CPU occupancy is used). 1905 * Besides, NUMA balancing fault statistics behave similarly: 1906 * the total number of faults per node is compared rather than 1907 * the average number of faults per CPU. This strategy is also 1908 * followed here. 1909 */ 1910 if (a_occ > m_a_occ) { 1911 m_a_occ = a_occ; 1912 m_a_cpu = m_cpu; 1913 } 1914 1915 if (llc_id(cpu) == llc_id(READ_ONCE(mm->sc_stat.cpu))) 1916 curr_m_a_occ = a_occ; 1917 1918 cpumask_andnot(cpus, cpus, sched_domain_span(sd)); 1919 } 1920 } 1921 1922 if (m_a_occ > (2 * curr_m_a_occ)) { 1923 /* 1924 * Avoid switching sc_stat.cpu too fast. 1925 * The reason to choose 2X is because: 1926 * 1. It is better to keep the preferred LLC stable, 1927 * rather than changing it frequently and cause migrations 1928 * 2. 2X means the new preferred LLC has at least 1 more 1929 * busy CPU than the old one(200% vs 100%, eg) 1930 * 3. 2X is chosen based on test results, as it delivers 1931 * the optimal performance gain so far. 1932 */ 1933 WRITE_ONCE(mm->sc_stat.cpu, m_a_cpu); 1934 } 1935 1936 update_avg_scale(&mm->sc_stat.nr_running_avg, nr_running); 1937 free_cpumask_var(cpus); 1938 } 1939 1940 void init_sched_mm(struct task_struct *p) 1941 { 1942 struct callback_head *work = &p->cache_work; 1943 1944 init_task_work(work, task_cache_work); 1945 work->next = work; 1946 /* 1947 * Reset new task's preference to avoid 1948 * polluting account_llc_enqueue(). 1949 */ 1950 p->preferred_llc = -1; 1951 } 1952 1953 #else /* CONFIG_SCHED_CACHE */ 1954 1955 static inline void account_mm_sched(struct rq *rq, struct task_struct *p, 1956 s64 delta_exec) { } 1957 1958 void init_sched_mm(struct task_struct *p) { } 1959 1960 static void task_tick_cache(struct rq *rq, struct task_struct *p) { } 1961 1962 static inline int get_pref_llc(struct task_struct *p, 1963 struct mm_struct *mm) 1964 { 1965 return -1; 1966 } 1967 1968 static void account_llc_enqueue(struct rq *rq, struct task_struct *p) {} 1969 1970 static void account_llc_dequeue(struct rq *rq, struct task_struct *p) {} 1971 1972 #endif /* CONFIG_SCHED_CACHE */ 1973 1974 /* 1975 * Used by other classes to account runtime. 1976 */ 1977 s64 update_curr_common(struct rq *rq) 1978 { 1979 return update_se(rq, &rq->donor->se); 1980 } 1981 1982 /* 1983 * Update the current task's runtime statistics. 1984 */ 1985 static void update_curr(struct cfs_rq *cfs_rq) 1986 { 1987 /* 1988 * Note: cfs_rq->curr corresponds to the task picked to 1989 * run (ie: rq->donor.se) which due to proxy-exec may 1990 * not necessarily be the actual task running 1991 * (rq->curr.se). This is easy to confuse! 1992 */ 1993 struct sched_entity *curr = cfs_rq->curr; 1994 struct rq *rq = rq_of(cfs_rq); 1995 s64 delta_exec; 1996 bool resched; 1997 1998 if (unlikely(!curr)) 1999 return; 2000 2001 delta_exec = update_se(rq, curr); 2002 if (unlikely(delta_exec <= 0)) 2003 return; 2004 2005 curr->vruntime += calc_delta_fair(delta_exec, curr); 2006 resched = update_deadline(cfs_rq, curr); 2007 2008 if (entity_is_task(curr)) { 2009 /* 2010 * If the fair_server is active, we need to account for the 2011 * fair_server time whether or not the task is running on 2012 * behalf of fair_server or not: 2013 * - If the task is running on behalf of fair_server, we need 2014 * to limit its time based on the assigned runtime. 2015 * - Fair task that runs outside of fair_server should account 2016 * against fair_server such that it can account for this time 2017 * and possibly avoid running this period. 2018 */ 2019 dl_server_update(&rq->fair_server, delta_exec); 2020 } 2021 2022 account_cfs_rq_runtime(cfs_rq, delta_exec); 2023 2024 if (cfs_rq->nr_queued == 1) 2025 return; 2026 2027 if (resched || !protect_slice(curr)) { 2028 resched_curr_lazy(rq); 2029 clear_buddies(cfs_rq, curr); 2030 } 2031 } 2032 2033 static void update_curr_fair(struct rq *rq) 2034 { 2035 update_curr(cfs_rq_of(&rq->donor->se)); 2036 } 2037 2038 static inline void 2039 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se) 2040 { 2041 struct sched_statistics *stats; 2042 struct task_struct *p = NULL; 2043 2044 if (!schedstat_enabled()) 2045 return; 2046 2047 stats = __schedstats_from_se(se); 2048 2049 if (entity_is_task(se)) 2050 p = task_of(se); 2051 2052 __update_stats_wait_start(rq_of(cfs_rq), p, stats); 2053 } 2054 2055 static inline void 2056 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se) 2057 { 2058 struct sched_statistics *stats; 2059 struct task_struct *p = NULL; 2060 2061 if (!schedstat_enabled()) 2062 return; 2063 2064 stats = __schedstats_from_se(se); 2065 2066 /* 2067 * When the sched_schedstat changes from 0 to 1, some sched se 2068 * maybe already in the runqueue, the se->statistics.wait_start 2069 * will be 0.So it will let the delta wrong. We need to avoid this 2070 * scenario. 2071 */ 2072 if (unlikely(!schedstat_val(stats->wait_start))) 2073 return; 2074 2075 if (entity_is_task(se)) 2076 p = task_of(se); 2077 2078 __update_stats_wait_end(rq_of(cfs_rq), p, stats); 2079 } 2080 2081 static inline void 2082 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se) 2083 { 2084 struct sched_statistics *stats; 2085 struct task_struct *tsk = NULL; 2086 2087 if (!schedstat_enabled()) 2088 return; 2089 2090 stats = __schedstats_from_se(se); 2091 2092 if (entity_is_task(se)) 2093 tsk = task_of(se); 2094 2095 __update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats); 2096 } 2097 2098 /* 2099 * Task is being enqueued - update stats: 2100 */ 2101 static inline void 2102 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 2103 { 2104 if (!schedstat_enabled()) 2105 return; 2106 2107 /* 2108 * Are we enqueueing a waiting task? (for current tasks 2109 * a dequeue/enqueue event is a NOP) 2110 */ 2111 if (se != cfs_rq->curr) 2112 update_stats_wait_start_fair(cfs_rq, se); 2113 2114 if (flags & ENQUEUE_WAKEUP) 2115 update_stats_enqueue_sleeper_fair(cfs_rq, se); 2116 } 2117 2118 static inline void 2119 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 2120 { 2121 2122 if (!schedstat_enabled()) 2123 return; 2124 2125 /* 2126 * Mark the end of the wait period if dequeueing a 2127 * waiting task: 2128 */ 2129 if (se != cfs_rq->curr) 2130 update_stats_wait_end_fair(cfs_rq, se); 2131 2132 if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) { 2133 struct task_struct *tsk = task_of(se); 2134 unsigned int state; 2135 2136 /* XXX racy against TTWU */ 2137 state = READ_ONCE(tsk->__state); 2138 if (state & TASK_INTERRUPTIBLE) 2139 __schedstat_set(tsk->stats.sleep_start, 2140 rq_clock(rq_of(cfs_rq))); 2141 if (state & TASK_UNINTERRUPTIBLE) 2142 __schedstat_set(tsk->stats.block_start, 2143 rq_clock(rq_of(cfs_rq))); 2144 } 2145 } 2146 2147 /* 2148 * We are picking a new current task - update its stats: 2149 */ 2150 static inline void 2151 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se) 2152 { 2153 /* 2154 * We are starting a new run period: 2155 */ 2156 se->exec_start = rq_clock_task(rq_of(cfs_rq)); 2157 } 2158 2159 /* Check sched_smt_active before calling this to avoid overheads in fastpaths */ 2160 static inline bool is_core_idle(int cpu) 2161 { 2162 int sibling; 2163 2164 for_each_cpu(sibling, cpu_smt_mask(cpu)) { 2165 if (cpu == sibling) 2166 continue; 2167 2168 if (!idle_cpu(sibling)) 2169 return false; 2170 } 2171 2172 return true; 2173 } 2174 2175 #ifdef CONFIG_NUMA 2176 #define NUMA_IMBALANCE_MIN 2 2177 2178 static inline long 2179 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr) 2180 { 2181 /* 2182 * Allow a NUMA imbalance if busy CPUs is less than the maximum 2183 * threshold. Above this threshold, individual tasks may be contending 2184 * for both memory bandwidth and any shared HT resources. This is an 2185 * approximation as the number of running tasks may not be related to 2186 * the number of busy CPUs due to sched_setaffinity. 2187 */ 2188 if (dst_running > imb_numa_nr) 2189 return imbalance; 2190 2191 /* 2192 * Allow a small imbalance based on a simple pair of communicating 2193 * tasks that remain local when the destination is lightly loaded. 2194 */ 2195 if (imbalance <= NUMA_IMBALANCE_MIN) 2196 return 0; 2197 2198 return imbalance; 2199 } 2200 #endif /* CONFIG_NUMA */ 2201 2202 #ifdef CONFIG_NUMA_BALANCING 2203 /* 2204 * Approximate time to scan a full NUMA task in ms. The task scan period is 2205 * calculated based on the tasks virtual memory size and 2206 * numa_balancing_scan_size. 2207 */ 2208 unsigned int sysctl_numa_balancing_scan_period_min = 1000; 2209 unsigned int sysctl_numa_balancing_scan_period_max = 60000; 2210 2211 /* Portion of address space to scan in MB */ 2212 unsigned int sysctl_numa_balancing_scan_size = 256; 2213 2214 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */ 2215 unsigned int sysctl_numa_balancing_scan_delay = 1000; 2216 2217 /* The page with hint page fault latency < threshold in ms is considered hot */ 2218 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC; 2219 2220 struct numa_group { 2221 refcount_t refcount; 2222 2223 spinlock_t lock; /* nr_tasks, tasks */ 2224 int nr_tasks; 2225 pid_t gid; 2226 int active_nodes; 2227 2228 struct rcu_head rcu; 2229 unsigned long total_faults; 2230 unsigned long max_faults_cpu; 2231 /* 2232 * faults[] array is split into two regions: faults_mem and faults_cpu. 2233 * 2234 * Faults_cpu is used to decide whether memory should move 2235 * towards the CPU. As a consequence, these stats are weighted 2236 * more by CPU use than by memory faults. 2237 */ 2238 unsigned long faults[]; 2239 }; 2240 2241 /* 2242 * For functions that can be called in multiple contexts that permit reading 2243 * ->numa_group (see struct task_struct for locking rules). 2244 */ 2245 static struct numa_group *deref_task_numa_group(struct task_struct *p) 2246 { 2247 return rcu_dereference_check(p->numa_group, p == current || 2248 (lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu))); 2249 } 2250 2251 static struct numa_group *deref_curr_numa_group(struct task_struct *p) 2252 { 2253 return rcu_dereference_protected(p->numa_group, p == current); 2254 } 2255 2256 static inline unsigned long group_faults_priv(struct numa_group *ng); 2257 static inline unsigned long group_faults_shared(struct numa_group *ng); 2258 2259 static unsigned int task_nr_scan_windows(struct task_struct *p) 2260 { 2261 unsigned long rss = 0; 2262 unsigned long nr_scan_pages; 2263 2264 /* 2265 * Calculations based on RSS as non-present and empty pages are skipped 2266 * by the PTE scanner and NUMA hinting faults should be trapped based 2267 * on resident pages 2268 */ 2269 nr_scan_pages = MB_TO_PAGES(sysctl_numa_balancing_scan_size); 2270 rss = get_mm_rss(p->mm); 2271 if (!rss) 2272 rss = nr_scan_pages; 2273 2274 rss = round_up(rss, nr_scan_pages); 2275 return rss / nr_scan_pages; 2276 } 2277 2278 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */ 2279 #define MAX_SCAN_WINDOW 2560 2280 2281 static unsigned int task_scan_min(struct task_struct *p) 2282 { 2283 unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size); 2284 unsigned int scan, floor; 2285 unsigned int windows = 1; 2286 2287 if (scan_size < MAX_SCAN_WINDOW) 2288 windows = MAX_SCAN_WINDOW / scan_size; 2289 floor = 1000 / windows; 2290 2291 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p); 2292 return max_t(unsigned int, floor, scan); 2293 } 2294 2295 static unsigned int task_scan_start(struct task_struct *p) 2296 { 2297 unsigned long smin = task_scan_min(p); 2298 unsigned long period = smin; 2299 struct numa_group *ng; 2300 2301 /* Scale the maximum scan period with the amount of shared memory. */ 2302 rcu_read_lock(); 2303 ng = rcu_dereference_all(p->numa_group); 2304 if (ng) { 2305 unsigned long shared = group_faults_shared(ng); 2306 unsigned long private = group_faults_priv(ng); 2307 2308 period *= refcount_read(&ng->refcount); 2309 period *= shared + 1; 2310 period /= private + shared + 1; 2311 } 2312 rcu_read_unlock(); 2313 2314 return max(smin, period); 2315 } 2316 2317 static unsigned int task_scan_max(struct task_struct *p) 2318 { 2319 unsigned long smin = task_scan_min(p); 2320 unsigned long smax; 2321 struct numa_group *ng; 2322 2323 /* Watch for min being lower than max due to floor calculations */ 2324 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p); 2325 2326 /* Scale the maximum scan period with the amount of shared memory. */ 2327 ng = deref_curr_numa_group(p); 2328 if (ng) { 2329 unsigned long shared = group_faults_shared(ng); 2330 unsigned long private = group_faults_priv(ng); 2331 unsigned long period = smax; 2332 2333 period *= refcount_read(&ng->refcount); 2334 period *= shared + 1; 2335 period /= private + shared + 1; 2336 2337 smax = max(smax, period); 2338 } 2339 2340 return max(smin, smax); 2341 } 2342 2343 static void account_numa_enqueue(struct rq *rq, struct task_struct *p) 2344 { 2345 rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE); 2346 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p)); 2347 } 2348 2349 static void account_numa_dequeue(struct rq *rq, struct task_struct *p) 2350 { 2351 rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE); 2352 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p)); 2353 } 2354 2355 /* Shared or private faults. */ 2356 #define NR_NUMA_HINT_FAULT_TYPES 2 2357 2358 /* Memory and CPU locality */ 2359 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2) 2360 2361 /* Averaged statistics, and temporary buffers. */ 2362 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2) 2363 2364 pid_t task_numa_group_id(struct task_struct *p) 2365 { 2366 struct numa_group *ng; 2367 pid_t gid = 0; 2368 2369 rcu_read_lock(); 2370 ng = rcu_dereference_all(p->numa_group); 2371 if (ng) 2372 gid = ng->gid; 2373 rcu_read_unlock(); 2374 2375 return gid; 2376 } 2377 2378 /* 2379 * The averaged statistics, shared & private, memory & CPU, 2380 * occupy the first half of the array. The second half of the 2381 * array is for current counters, which are averaged into the 2382 * first set by task_numa_placement. 2383 */ 2384 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv) 2385 { 2386 return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv; 2387 } 2388 2389 static inline unsigned long task_faults(struct task_struct *p, int nid) 2390 { 2391 if (!p->numa_faults) 2392 return 0; 2393 2394 return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] + 2395 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)]; 2396 } 2397 2398 static inline unsigned long group_faults(struct task_struct *p, int nid) 2399 { 2400 struct numa_group *ng = deref_task_numa_group(p); 2401 2402 if (!ng) 2403 return 0; 2404 2405 return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] + 2406 ng->faults[task_faults_idx(NUMA_MEM, nid, 1)]; 2407 } 2408 2409 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid) 2410 { 2411 return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] + 2412 group->faults[task_faults_idx(NUMA_CPU, nid, 1)]; 2413 } 2414 2415 static inline unsigned long group_faults_priv(struct numa_group *ng) 2416 { 2417 unsigned long faults = 0; 2418 int node; 2419 2420 for_each_online_node(node) { 2421 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)]; 2422 } 2423 2424 return faults; 2425 } 2426 2427 static inline unsigned long group_faults_shared(struct numa_group *ng) 2428 { 2429 unsigned long faults = 0; 2430 int node; 2431 2432 for_each_online_node(node) { 2433 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)]; 2434 } 2435 2436 return faults; 2437 } 2438 2439 /* 2440 * A node triggering more than 1/3 as many NUMA faults as the maximum is 2441 * considered part of a numa group's pseudo-interleaving set. Migrations 2442 * between these nodes are slowed down, to allow things to settle down. 2443 */ 2444 #define ACTIVE_NODE_FRACTION 3 2445 2446 static bool numa_is_active_node(int nid, struct numa_group *ng) 2447 { 2448 return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu; 2449 } 2450 2451 /* Handle placement on systems where not all nodes are directly connected. */ 2452 static unsigned long score_nearby_nodes(struct task_struct *p, int nid, 2453 int lim_dist, bool task) 2454 { 2455 unsigned long score = 0; 2456 int node, max_dist; 2457 2458 /* 2459 * All nodes are directly connected, and the same distance 2460 * from each other. No need for fancy placement algorithms. 2461 */ 2462 if (sched_numa_topology_type == NUMA_DIRECT) 2463 return 0; 2464 2465 /* sched_max_numa_distance may be changed in parallel. */ 2466 max_dist = READ_ONCE(sched_max_numa_distance); 2467 /* 2468 * This code is called for each node, introducing N^2 complexity, 2469 * which should be OK given the number of nodes rarely exceeds 8. 2470 */ 2471 for_each_online_node(node) { 2472 unsigned long faults; 2473 int dist = node_distance(nid, node); 2474 2475 /* 2476 * The furthest away nodes in the system are not interesting 2477 * for placement; nid was already counted. 2478 */ 2479 if (dist >= max_dist || node == nid) 2480 continue; 2481 2482 /* 2483 * On systems with a backplane NUMA topology, compare groups 2484 * of nodes, and move tasks towards the group with the most 2485 * memory accesses. When comparing two nodes at distance 2486 * "hoplimit", only nodes closer by than "hoplimit" are part 2487 * of each group. Skip other nodes. 2488 */ 2489 if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist) 2490 continue; 2491 2492 /* Add up the faults from nearby nodes. */ 2493 if (task) 2494 faults = task_faults(p, node); 2495 else 2496 faults = group_faults(p, node); 2497 2498 /* 2499 * On systems with a glueless mesh NUMA topology, there are 2500 * no fixed "groups of nodes". Instead, nodes that are not 2501 * directly connected bounce traffic through intermediate 2502 * nodes; a numa_group can occupy any set of nodes. 2503 * The further away a node is, the less the faults count. 2504 * This seems to result in good task placement. 2505 */ 2506 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) { 2507 faults *= (max_dist - dist); 2508 faults /= (max_dist - LOCAL_DISTANCE); 2509 } 2510 2511 score += faults; 2512 } 2513 2514 return score; 2515 } 2516 2517 /* 2518 * These return the fraction of accesses done by a particular task, or 2519 * task group, on a particular numa node. The group weight is given a 2520 * larger multiplier, in order to group tasks together that are almost 2521 * evenly spread out between numa nodes. 2522 */ 2523 static inline unsigned long task_weight(struct task_struct *p, int nid, 2524 int dist) 2525 { 2526 unsigned long faults, total_faults; 2527 2528 if (!p->numa_faults) 2529 return 0; 2530 2531 total_faults = p->total_numa_faults; 2532 2533 if (!total_faults) 2534 return 0; 2535 2536 faults = task_faults(p, nid); 2537 faults += score_nearby_nodes(p, nid, dist, true); 2538 2539 return 1000 * faults / total_faults; 2540 } 2541 2542 static inline unsigned long group_weight(struct task_struct *p, int nid, 2543 int dist) 2544 { 2545 struct numa_group *ng = deref_task_numa_group(p); 2546 unsigned long faults, total_faults; 2547 2548 if (!ng) 2549 return 0; 2550 2551 total_faults = ng->total_faults; 2552 2553 if (!total_faults) 2554 return 0; 2555 2556 faults = group_faults(p, nid); 2557 faults += score_nearby_nodes(p, nid, dist, false); 2558 2559 return 1000 * faults / total_faults; 2560 } 2561 2562 /* 2563 * If memory tiering mode is enabled, cpupid of slow memory page is 2564 * used to record scan time instead of CPU and PID. When tiering mode 2565 * is disabled at run time, the scan time (in cpupid) will be 2566 * interpreted as CPU and PID. So CPU needs to be checked to avoid to 2567 * access out of array bound. 2568 */ 2569 static inline bool cpupid_valid(int cpupid) 2570 { 2571 return cpupid_to_cpu(cpupid) < nr_cpu_ids; 2572 } 2573 2574 /* 2575 * For memory tiering mode, if there are enough free pages (more than 2576 * enough watermark defined here) in fast memory node, to take full 2577 * advantage of fast memory capacity, all recently accessed slow 2578 * memory pages will be migrated to fast memory node without 2579 * considering hot threshold. 2580 */ 2581 static bool pgdat_free_space_enough(struct pglist_data *pgdat) 2582 { 2583 int z; 2584 unsigned long enough_wmark; 2585 2586 enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT, 2587 pgdat->node_present_pages >> 4); 2588 for (z = pgdat->nr_zones - 1; z >= 0; z--) { 2589 struct zone *zone = pgdat->node_zones + z; 2590 2591 if (!populated_zone(zone)) 2592 continue; 2593 2594 if (zone_watermark_ok(zone, 0, 2595 promo_wmark_pages(zone) + enough_wmark, 2596 ZONE_MOVABLE, 0)) 2597 return true; 2598 } 2599 return false; 2600 } 2601 2602 /* 2603 * For memory tiering mode, when page tables are scanned, the scan 2604 * time will be recorded in struct page in addition to make page 2605 * PROT_NONE for slow memory page. So when the page is accessed, in 2606 * hint page fault handler, the hint page fault latency is calculated 2607 * via, 2608 * 2609 * hint page fault latency = hint page fault time - scan time 2610 * 2611 * The smaller the hint page fault latency, the higher the possibility 2612 * for the page to be hot. 2613 */ 2614 static int numa_hint_fault_latency(struct folio *folio) 2615 { 2616 int last_time, time; 2617 2618 time = jiffies_to_msecs(jiffies); 2619 last_time = folio_xchg_access_time(folio, time); 2620 2621 return (time - last_time) & PAGE_ACCESS_TIME_MASK; 2622 } 2623 2624 /* 2625 * For memory tiering mode, too high promotion/demotion throughput may 2626 * hurt application latency. So we provide a mechanism to rate limit 2627 * the number of pages that are tried to be promoted. 2628 */ 2629 static bool numa_promotion_rate_limit(struct pglist_data *pgdat, 2630 unsigned long rate_limit, int nr) 2631 { 2632 unsigned long nr_cand; 2633 unsigned int now, start; 2634 2635 now = jiffies_to_msecs(jiffies); 2636 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr); 2637 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE); 2638 start = pgdat->nbp_rl_start; 2639 if (now - start > MSEC_PER_SEC && 2640 cmpxchg(&pgdat->nbp_rl_start, start, now) == start) 2641 pgdat->nbp_rl_nr_cand = nr_cand; 2642 if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit) 2643 return true; 2644 return false; 2645 } 2646 2647 #define NUMA_MIGRATION_ADJUST_STEPS 16 2648 2649 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat, 2650 unsigned long rate_limit, 2651 unsigned int ref_th) 2652 { 2653 unsigned int now, start, th_period, unit_th, th; 2654 unsigned long nr_cand, ref_cand, diff_cand; 2655 2656 now = jiffies_to_msecs(jiffies); 2657 th_period = sysctl_numa_balancing_scan_period_max; 2658 start = pgdat->nbp_th_start; 2659 if (now - start > th_period && 2660 cmpxchg(&pgdat->nbp_th_start, start, now) == start) { 2661 ref_cand = rate_limit * 2662 sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC; 2663 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE); 2664 diff_cand = nr_cand - pgdat->nbp_th_nr_cand; 2665 unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS; 2666 th = pgdat->nbp_threshold ? : ref_th; 2667 if (diff_cand > ref_cand * 11 / 10) 2668 th = max(th - unit_th, unit_th); 2669 else if (diff_cand < ref_cand * 9 / 10) 2670 th = min(th + unit_th, ref_th * 2); 2671 pgdat->nbp_th_nr_cand = nr_cand; 2672 pgdat->nbp_threshold = th; 2673 } 2674 } 2675 2676 bool should_numa_migrate_memory(struct task_struct *p, struct folio *folio, 2677 int src_nid, int dst_cpu) 2678 { 2679 struct numa_group *ng = deref_curr_numa_group(p); 2680 int dst_nid = cpu_to_node(dst_cpu); 2681 int last_cpupid, this_cpupid; 2682 2683 /* 2684 * Cannot migrate to memoryless nodes. 2685 */ 2686 if (!node_state(dst_nid, N_MEMORY)) 2687 return false; 2688 2689 /* 2690 * The pages in slow memory node should be migrated according 2691 * to hot/cold instead of private/shared. 2692 */ 2693 if (folio_use_access_time(folio)) { 2694 struct pglist_data *pgdat; 2695 unsigned long rate_limit; 2696 unsigned int latency, th, def_th; 2697 long nr = folio_nr_pages(folio); 2698 2699 pgdat = NODE_DATA(dst_nid); 2700 if (pgdat_free_space_enough(pgdat)) { 2701 /* workload changed, reset hot threshold */ 2702 pgdat->nbp_threshold = 0; 2703 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE_NRL, nr); 2704 return true; 2705 } 2706 2707 def_th = sysctl_numa_balancing_hot_threshold; 2708 rate_limit = MB_TO_PAGES(sysctl_numa_balancing_promote_rate_limit); 2709 numa_promotion_adjust_threshold(pgdat, rate_limit, def_th); 2710 2711 th = pgdat->nbp_threshold ? : def_th; 2712 latency = numa_hint_fault_latency(folio); 2713 if (latency >= th) 2714 return false; 2715 2716 return !numa_promotion_rate_limit(pgdat, rate_limit, nr); 2717 } 2718 2719 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid); 2720 last_cpupid = folio_xchg_last_cpupid(folio, this_cpupid); 2721 2722 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) && 2723 !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid)) 2724 return false; 2725 2726 /* 2727 * Allow first faults or private faults to migrate immediately early in 2728 * the lifetime of a task. The magic number 4 is based on waiting for 2729 * two full passes of the "multi-stage node selection" test that is 2730 * executed below. 2731 */ 2732 if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) && 2733 (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid))) 2734 return true; 2735 2736 /* 2737 * Multi-stage node selection is used in conjunction with a periodic 2738 * migration fault to build a temporal task<->page relation. By using 2739 * a two-stage filter we remove short/unlikely relations. 2740 * 2741 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate 2742 * a task's usage of a particular page (n_p) per total usage of this 2743 * page (n_t) (in a given time-span) to a probability. 2744 * 2745 * Our periodic faults will sample this probability and getting the 2746 * same result twice in a row, given these samples are fully 2747 * independent, is then given by P(n)^2, provided our sample period 2748 * is sufficiently short compared to the usage pattern. 2749 * 2750 * This quadric squishes small probabilities, making it less likely we 2751 * act on an unlikely task<->page relation. 2752 */ 2753 if (!cpupid_pid_unset(last_cpupid) && 2754 cpupid_to_nid(last_cpupid) != dst_nid) 2755 return false; 2756 2757 /* Always allow migrate on private faults */ 2758 if (cpupid_match_pid(p, last_cpupid)) 2759 return true; 2760 2761 /* A shared fault, but p->numa_group has not been set up yet. */ 2762 if (!ng) 2763 return true; 2764 2765 /* 2766 * Destination node is much more heavily used than the source 2767 * node? Allow migration. 2768 */ 2769 if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) * 2770 ACTIVE_NODE_FRACTION) 2771 return true; 2772 2773 /* 2774 * Distribute memory according to CPU & memory use on each node, 2775 * with 3/4 hysteresis to avoid unnecessary memory migrations: 2776 * 2777 * faults_cpu(dst) 3 faults_cpu(src) 2778 * --------------- * - > --------------- 2779 * faults_mem(dst) 4 faults_mem(src) 2780 */ 2781 return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 > 2782 group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4; 2783 } 2784 2785 /* 2786 * 'numa_type' describes the node at the moment of load balancing. 2787 */ 2788 enum numa_type { 2789 /* The node has spare capacity that can be used to run more tasks. */ 2790 node_has_spare = 0, 2791 /* 2792 * The node is fully used and the tasks don't compete for more CPU 2793 * cycles. Nevertheless, some tasks might wait before running. 2794 */ 2795 node_fully_busy, 2796 /* 2797 * The node is overloaded and can't provide expected CPU cycles to all 2798 * tasks. 2799 */ 2800 node_overloaded 2801 }; 2802 2803 /* Cached statistics for all CPUs within a node */ 2804 struct numa_stats { 2805 unsigned long load; 2806 unsigned long runnable; 2807 unsigned long util; 2808 /* Total compute capacity of CPUs on a node */ 2809 unsigned long compute_capacity; 2810 unsigned int nr_running; 2811 unsigned int weight; 2812 enum numa_type node_type; 2813 int idle_cpu; 2814 }; 2815 2816 struct task_numa_env { 2817 struct task_struct *p; 2818 2819 int src_cpu, src_nid; 2820 int dst_cpu, dst_nid; 2821 int imb_numa_nr; 2822 2823 struct numa_stats src_stats, dst_stats; 2824 2825 int imbalance_pct; 2826 int dist; 2827 2828 struct task_struct *best_task; 2829 long best_imp; 2830 int best_cpu; 2831 }; 2832 2833 static unsigned long cpu_load(struct rq *rq); 2834 static unsigned long cpu_runnable(struct rq *rq); 2835 2836 static inline enum 2837 numa_type numa_classify(unsigned int imbalance_pct, 2838 struct numa_stats *ns) 2839 { 2840 if ((ns->nr_running > ns->weight) && 2841 (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) || 2842 ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100)))) 2843 return node_overloaded; 2844 2845 if ((ns->nr_running < ns->weight) || 2846 (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) && 2847 ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100)))) 2848 return node_has_spare; 2849 2850 return node_fully_busy; 2851 } 2852 2853 /* Forward declarations of select_idle_sibling helpers */ 2854 static inline bool test_idle_cores(int cpu); 2855 static inline int numa_idle_core(int idle_core, int cpu) 2856 { 2857 if (!sched_smt_active() || 2858 idle_core >= 0 || !test_idle_cores(cpu)) 2859 return idle_core; 2860 2861 /* 2862 * Prefer cores instead of packing HT siblings 2863 * and triggering future load balancing. 2864 */ 2865 if (is_core_idle(cpu)) 2866 idle_core = cpu; 2867 2868 return idle_core; 2869 } 2870 2871 /* 2872 * Gather all necessary information to make NUMA balancing placement 2873 * decisions that are compatible with standard load balancer. This 2874 * borrows code and logic from update_sg_lb_stats but sharing a 2875 * common implementation is impractical. 2876 */ 2877 static void update_numa_stats(struct task_numa_env *env, 2878 struct numa_stats *ns, int nid, 2879 bool find_idle) 2880 { 2881 int cpu, idle_core = -1; 2882 2883 memset(ns, 0, sizeof(*ns)); 2884 ns->idle_cpu = -1; 2885 2886 rcu_read_lock(); 2887 for_each_cpu(cpu, cpumask_of_node(nid)) { 2888 struct rq *rq = cpu_rq(cpu); 2889 2890 ns->load += cpu_load(rq); 2891 ns->runnable += cpu_runnable(rq); 2892 ns->util += cpu_util_cfs(cpu); 2893 ns->nr_running += rq->cfs.h_nr_runnable; 2894 ns->compute_capacity += capacity_of(cpu); 2895 2896 if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) { 2897 if (READ_ONCE(rq->numa_migrate_on) || 2898 !cpumask_test_cpu(cpu, env->p->cpus_ptr)) 2899 continue; 2900 2901 if (ns->idle_cpu == -1) 2902 ns->idle_cpu = cpu; 2903 2904 idle_core = numa_idle_core(idle_core, cpu); 2905 } 2906 } 2907 rcu_read_unlock(); 2908 2909 ns->weight = cpumask_weight(cpumask_of_node(nid)); 2910 2911 ns->node_type = numa_classify(env->imbalance_pct, ns); 2912 2913 if (idle_core >= 0) 2914 ns->idle_cpu = idle_core; 2915 } 2916 2917 static void task_numa_assign(struct task_numa_env *env, 2918 struct task_struct *p, long imp) 2919 { 2920 struct rq *rq = cpu_rq(env->dst_cpu); 2921 2922 /* Check if run-queue part of active NUMA balance. */ 2923 if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) { 2924 int cpu; 2925 int start = env->dst_cpu; 2926 2927 /* Find alternative idle CPU. */ 2928 for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) { 2929 if (cpu == env->best_cpu || !idle_cpu(cpu) || 2930 !cpumask_test_cpu(cpu, env->p->cpus_ptr)) { 2931 continue; 2932 } 2933 2934 env->dst_cpu = cpu; 2935 rq = cpu_rq(env->dst_cpu); 2936 if (!xchg(&rq->numa_migrate_on, 1)) 2937 goto assign; 2938 } 2939 2940 /* Failed to find an alternative idle CPU */ 2941 return; 2942 } 2943 2944 assign: 2945 /* 2946 * Clear previous best_cpu/rq numa-migrate flag, since task now 2947 * found a better CPU to move/swap. 2948 */ 2949 if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) { 2950 rq = cpu_rq(env->best_cpu); 2951 WRITE_ONCE(rq->numa_migrate_on, 0); 2952 } 2953 2954 if (env->best_task) 2955 put_task_struct(env->best_task); 2956 if (p) 2957 get_task_struct(p); 2958 2959 env->best_task = p; 2960 env->best_imp = imp; 2961 env->best_cpu = env->dst_cpu; 2962 } 2963 2964 static bool load_too_imbalanced(long src_load, long dst_load, 2965 struct task_numa_env *env) 2966 { 2967 long imb, old_imb; 2968 long orig_src_load, orig_dst_load; 2969 long src_capacity, dst_capacity; 2970 2971 /* 2972 * The load is corrected for the CPU capacity available on each node. 2973 * 2974 * src_load dst_load 2975 * ------------ vs --------- 2976 * src_capacity dst_capacity 2977 */ 2978 src_capacity = env->src_stats.compute_capacity; 2979 dst_capacity = env->dst_stats.compute_capacity; 2980 2981 imb = abs(dst_load * src_capacity - src_load * dst_capacity); 2982 2983 orig_src_load = env->src_stats.load; 2984 orig_dst_load = env->dst_stats.load; 2985 2986 old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity); 2987 2988 /* Would this change make things worse? */ 2989 return (imb > old_imb); 2990 } 2991 2992 /* 2993 * Maximum NUMA importance can be 1998 (2*999); 2994 * SMALLIMP @ 30 would be close to 1998/64. 2995 * Used to deter task migration. 2996 */ 2997 #define SMALLIMP 30 2998 2999 /* 3000 * This checks if the overall compute and NUMA accesses of the system would 3001 * be improved if the source tasks was migrated to the target dst_cpu taking 3002 * into account that it might be best if task running on the dst_cpu should 3003 * be exchanged with the source task 3004 */ 3005 static bool task_numa_compare(struct task_numa_env *env, 3006 long taskimp, long groupimp, bool maymove) 3007 { 3008 struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p); 3009 struct rq *dst_rq = cpu_rq(env->dst_cpu); 3010 long imp = p_ng ? groupimp : taskimp; 3011 struct task_struct *cur; 3012 long src_load, dst_load; 3013 int dist = env->dist; 3014 long moveimp = imp; 3015 long load; 3016 bool stopsearch = false; 3017 3018 if (READ_ONCE(dst_rq->numa_migrate_on)) 3019 return false; 3020 3021 rcu_read_lock(); 3022 cur = rcu_dereference_all(dst_rq->curr); 3023 if (cur && ((cur->flags & (PF_EXITING | PF_KTHREAD)) || 3024 !cur->mm)) 3025 cur = NULL; 3026 3027 /* 3028 * Because we have preemption enabled we can get migrated around and 3029 * end try selecting ourselves (current == env->p) as a swap candidate. 3030 */ 3031 if (cur == env->p) { 3032 stopsearch = true; 3033 goto unlock; 3034 } 3035 3036 if (!cur) { 3037 if (maymove && moveimp >= env->best_imp) 3038 goto assign; 3039 else 3040 goto unlock; 3041 } 3042 3043 /* Skip this swap candidate if cannot move to the source cpu. */ 3044 if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr)) 3045 goto unlock; 3046 3047 /* 3048 * Skip this swap candidate if it is not moving to its preferred 3049 * node and the best task is. 3050 */ 3051 if (env->best_task && 3052 env->best_task->numa_preferred_nid == env->src_nid && 3053 cur->numa_preferred_nid != env->src_nid) { 3054 goto unlock; 3055 } 3056 3057 /* 3058 * "imp" is the fault differential for the source task between the 3059 * source and destination node. Calculate the total differential for 3060 * the source task and potential destination task. The more negative 3061 * the value is, the more remote accesses that would be expected to 3062 * be incurred if the tasks were swapped. 3063 * 3064 * If dst and source tasks are in the same NUMA group, or not 3065 * in any group then look only at task weights. 3066 */ 3067 cur_ng = rcu_dereference_all(cur->numa_group); 3068 if (cur_ng == p_ng) { 3069 /* 3070 * Do not swap within a group or between tasks that have 3071 * no group if there is spare capacity. Swapping does 3072 * not address the load imbalance and helps one task at 3073 * the cost of punishing another. 3074 */ 3075 if (env->dst_stats.node_type == node_has_spare) 3076 goto unlock; 3077 3078 imp = taskimp + task_weight(cur, env->src_nid, dist) - 3079 task_weight(cur, env->dst_nid, dist); 3080 /* 3081 * Add some hysteresis to prevent swapping the 3082 * tasks within a group over tiny differences. 3083 */ 3084 if (cur_ng) 3085 imp -= imp / 16; 3086 } else { 3087 /* 3088 * Compare the group weights. If a task is all by itself 3089 * (not part of a group), use the task weight instead. 3090 */ 3091 if (cur_ng && p_ng) 3092 imp += group_weight(cur, env->src_nid, dist) - 3093 group_weight(cur, env->dst_nid, dist); 3094 else 3095 imp += task_weight(cur, env->src_nid, dist) - 3096 task_weight(cur, env->dst_nid, dist); 3097 } 3098 3099 /* Discourage picking a task already on its preferred node */ 3100 if (cur->numa_preferred_nid == env->dst_nid) 3101 imp -= imp / 16; 3102 3103 /* 3104 * Encourage picking a task that moves to its preferred node. 3105 * This potentially makes imp larger than it's maximum of 3106 * 1998 (see SMALLIMP and task_weight for why) but in this 3107 * case, it does not matter. 3108 */ 3109 if (cur->numa_preferred_nid == env->src_nid) 3110 imp += imp / 8; 3111 3112 if (maymove && moveimp > imp && moveimp > env->best_imp) { 3113 imp = moveimp; 3114 cur = NULL; 3115 goto assign; 3116 } 3117 3118 /* 3119 * Prefer swapping with a task moving to its preferred node over a 3120 * task that is not. 3121 */ 3122 if (env->best_task && cur->numa_preferred_nid == env->src_nid && 3123 env->best_task->numa_preferred_nid != env->src_nid) { 3124 goto assign; 3125 } 3126 3127 /* 3128 * If the NUMA importance is less than SMALLIMP, 3129 * task migration might only result in ping pong 3130 * of tasks and also hurt performance due to cache 3131 * misses. 3132 */ 3133 if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2) 3134 goto unlock; 3135 3136 /* 3137 * In the overloaded case, try and keep the load balanced. 3138 */ 3139 load = task_h_load(env->p) - task_h_load(cur); 3140 if (!load) 3141 goto assign; 3142 3143 dst_load = env->dst_stats.load + load; 3144 src_load = env->src_stats.load - load; 3145 3146 if (load_too_imbalanced(src_load, dst_load, env)) 3147 goto unlock; 3148 3149 assign: 3150 /* Evaluate an idle CPU for a task numa move. */ 3151 if (!cur) { 3152 int cpu = env->dst_stats.idle_cpu; 3153 3154 /* Nothing cached so current CPU went idle since the search. */ 3155 if (cpu < 0) 3156 cpu = env->dst_cpu; 3157 3158 /* 3159 * If the CPU is no longer truly idle and the previous best CPU 3160 * is, keep using it. 3161 */ 3162 if (!idle_cpu(cpu) && env->best_cpu >= 0 && 3163 idle_cpu(env->best_cpu)) { 3164 cpu = env->best_cpu; 3165 } 3166 3167 env->dst_cpu = cpu; 3168 } 3169 3170 task_numa_assign(env, cur, imp); 3171 3172 /* 3173 * If a move to idle is allowed because there is capacity or load 3174 * balance improves then stop the search. While a better swap 3175 * candidate may exist, a search is not free. 3176 */ 3177 if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu)) 3178 stopsearch = true; 3179 3180 /* 3181 * If a swap candidate must be identified and the current best task 3182 * moves its preferred node then stop the search. 3183 */ 3184 if (!maymove && env->best_task && 3185 env->best_task->numa_preferred_nid == env->src_nid) { 3186 stopsearch = true; 3187 } 3188 unlock: 3189 rcu_read_unlock(); 3190 3191 return stopsearch; 3192 } 3193 3194 static void task_numa_find_cpu(struct task_numa_env *env, 3195 long taskimp, long groupimp) 3196 { 3197 bool maymove = false; 3198 int cpu; 3199 3200 /* 3201 * If dst node has spare capacity, then check if there is an 3202 * imbalance that would be overruled by the load balancer. 3203 */ 3204 if (env->dst_stats.node_type == node_has_spare) { 3205 unsigned int imbalance; 3206 int src_running, dst_running; 3207 3208 /* 3209 * Would movement cause an imbalance? Note that if src has 3210 * more running tasks that the imbalance is ignored as the 3211 * move improves the imbalance from the perspective of the 3212 * CPU load balancer. 3213 * */ 3214 src_running = env->src_stats.nr_running - 1; 3215 dst_running = env->dst_stats.nr_running + 1; 3216 imbalance = max(0, dst_running - src_running); 3217 imbalance = adjust_numa_imbalance(imbalance, dst_running, 3218 env->imb_numa_nr); 3219 3220 /* Use idle CPU if there is no imbalance */ 3221 if (!imbalance) { 3222 maymove = true; 3223 if (env->dst_stats.idle_cpu >= 0) { 3224 env->dst_cpu = env->dst_stats.idle_cpu; 3225 task_numa_assign(env, NULL, 0); 3226 return; 3227 } 3228 } 3229 } else { 3230 long src_load, dst_load, load; 3231 /* 3232 * If the improvement from just moving env->p direction is better 3233 * than swapping tasks around, check if a move is possible. 3234 */ 3235 load = task_h_load(env->p); 3236 dst_load = env->dst_stats.load + load; 3237 src_load = env->src_stats.load - load; 3238 maymove = !load_too_imbalanced(src_load, dst_load, env); 3239 } 3240 3241 /* Skip CPUs if the source task cannot migrate */ 3242 for_each_cpu_and(cpu, cpumask_of_node(env->dst_nid), env->p->cpus_ptr) { 3243 env->dst_cpu = cpu; 3244 if (task_numa_compare(env, taskimp, groupimp, maymove)) 3245 break; 3246 } 3247 } 3248 3249 static int task_numa_migrate(struct task_struct *p) 3250 { 3251 struct task_numa_env env = { 3252 .p = p, 3253 3254 .src_cpu = task_cpu(p), 3255 .src_nid = task_node(p), 3256 3257 .imbalance_pct = 112, 3258 3259 .best_task = NULL, 3260 .best_imp = 0, 3261 .best_cpu = -1, 3262 }; 3263 unsigned long taskweight, groupweight; 3264 struct sched_domain *sd; 3265 long taskimp, groupimp; 3266 struct numa_group *ng; 3267 struct rq *best_rq; 3268 int nid, ret, dist; 3269 3270 /* 3271 * Pick the lowest SD_NUMA domain, as that would have the smallest 3272 * imbalance and would be the first to start moving tasks about. 3273 * 3274 * And we want to avoid any moving of tasks about, as that would create 3275 * random movement of tasks -- counter the numa conditions we're trying 3276 * to satisfy here. 3277 */ 3278 rcu_read_lock(); 3279 sd = rcu_dereference_all(per_cpu(sd_numa, env.src_cpu)); 3280 if (sd) { 3281 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2; 3282 env.imb_numa_nr = sd->imb_numa_nr; 3283 } 3284 rcu_read_unlock(); 3285 3286 /* 3287 * Cpusets can break the scheduler domain tree into smaller 3288 * balance domains, some of which do not cross NUMA boundaries. 3289 * Tasks that are "trapped" in such domains cannot be migrated 3290 * elsewhere, so there is no point in (re)trying. 3291 */ 3292 if (unlikely(!sd)) { 3293 sched_setnuma(p, task_node(p)); 3294 return -EINVAL; 3295 } 3296 3297 env.dst_nid = p->numa_preferred_nid; 3298 dist = env.dist = node_distance(env.src_nid, env.dst_nid); 3299 taskweight = task_weight(p, env.src_nid, dist); 3300 groupweight = group_weight(p, env.src_nid, dist); 3301 update_numa_stats(&env, &env.src_stats, env.src_nid, false); 3302 taskimp = task_weight(p, env.dst_nid, dist) - taskweight; 3303 groupimp = group_weight(p, env.dst_nid, dist) - groupweight; 3304 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true); 3305 3306 /* Try to find a spot on the preferred nid. */ 3307 task_numa_find_cpu(&env, taskimp, groupimp); 3308 3309 /* 3310 * Look at other nodes in these cases: 3311 * - there is no space available on the preferred_nid 3312 * - the task is part of a numa_group that is interleaved across 3313 * multiple NUMA nodes; in order to better consolidate the group, 3314 * we need to check other locations. 3315 */ 3316 ng = deref_curr_numa_group(p); 3317 if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) { 3318 for_each_node_state(nid, N_CPU) { 3319 if (nid == env.src_nid || nid == p->numa_preferred_nid) 3320 continue; 3321 3322 dist = node_distance(env.src_nid, env.dst_nid); 3323 if (sched_numa_topology_type == NUMA_BACKPLANE && 3324 dist != env.dist) { 3325 taskweight = task_weight(p, env.src_nid, dist); 3326 groupweight = group_weight(p, env.src_nid, dist); 3327 } 3328 3329 /* Only consider nodes where both task and groups benefit */ 3330 taskimp = task_weight(p, nid, dist) - taskweight; 3331 groupimp = group_weight(p, nid, dist) - groupweight; 3332 if (taskimp < 0 && groupimp < 0) 3333 continue; 3334 3335 env.dist = dist; 3336 env.dst_nid = nid; 3337 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true); 3338 task_numa_find_cpu(&env, taskimp, groupimp); 3339 } 3340 } 3341 3342 /* 3343 * If the task is part of a workload that spans multiple NUMA nodes, 3344 * and is migrating into one of the workload's active nodes, remember 3345 * this node as the task's preferred numa node, so the workload can 3346 * settle down. 3347 * A task that migrated to a second choice node will be better off 3348 * trying for a better one later. Do not set the preferred node here. 3349 */ 3350 if (ng) { 3351 if (env.best_cpu == -1) 3352 nid = env.src_nid; 3353 else 3354 nid = cpu_to_node(env.best_cpu); 3355 3356 if (nid != p->numa_preferred_nid) 3357 sched_setnuma(p, nid); 3358 } 3359 3360 /* No better CPU than the current one was found. */ 3361 if (env.best_cpu == -1) { 3362 trace_sched_stick_numa(p, env.src_cpu, NULL, -1); 3363 return -EAGAIN; 3364 } 3365 3366 best_rq = cpu_rq(env.best_cpu); 3367 if (env.best_task == NULL) { 3368 ret = migrate_task_to(p, env.best_cpu); 3369 WRITE_ONCE(best_rq->numa_migrate_on, 0); 3370 if (ret != 0) 3371 trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu); 3372 return ret; 3373 } 3374 3375 ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu); 3376 WRITE_ONCE(best_rq->numa_migrate_on, 0); 3377 3378 if (ret != 0) 3379 trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu); 3380 put_task_struct(env.best_task); 3381 return ret; 3382 } 3383 3384 /* Attempt to migrate a task to a CPU on the preferred node. */ 3385 static void numa_migrate_preferred(struct task_struct *p) 3386 { 3387 unsigned long interval = HZ; 3388 3389 /* This task has no NUMA fault statistics yet */ 3390 if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults)) 3391 return; 3392 3393 /* Periodically retry migrating the task to the preferred node */ 3394 interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16); 3395 p->numa_migrate_retry = jiffies + interval; 3396 3397 /* Success if task is already running on preferred CPU */ 3398 if (task_node(p) == p->numa_preferred_nid) 3399 return; 3400 3401 /* Otherwise, try migrate to a CPU on the preferred node */ 3402 task_numa_migrate(p); 3403 } 3404 3405 /* 3406 * Find out how many nodes the workload is actively running on. Do this by 3407 * tracking the nodes from which NUMA hinting faults are triggered. This can 3408 * be different from the set of nodes where the workload's memory is currently 3409 * located. 3410 */ 3411 static void numa_group_count_active_nodes(struct numa_group *numa_group) 3412 { 3413 unsigned long faults, max_faults = 0; 3414 int nid, active_nodes = 0; 3415 3416 for_each_node_state(nid, N_CPU) { 3417 faults = group_faults_cpu(numa_group, nid); 3418 if (faults > max_faults) 3419 max_faults = faults; 3420 } 3421 3422 for_each_node_state(nid, N_CPU) { 3423 faults = group_faults_cpu(numa_group, nid); 3424 if (faults * ACTIVE_NODE_FRACTION > max_faults) 3425 active_nodes++; 3426 } 3427 3428 numa_group->max_faults_cpu = max_faults; 3429 numa_group->active_nodes = active_nodes; 3430 } 3431 3432 /* 3433 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS 3434 * increments. The more local the fault statistics are, the higher the scan 3435 * period will be for the next scan window. If local/(local+remote) ratio is 3436 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS) 3437 * the scan period will decrease. Aim for 70% local accesses. 3438 */ 3439 #define NUMA_PERIOD_SLOTS 10 3440 #define NUMA_PERIOD_THRESHOLD 7 3441 3442 /* 3443 * Increase the scan period (slow down scanning) if the majority of 3444 * our memory is already on our local node, or if the majority of 3445 * the page accesses are shared with other processes. 3446 * Otherwise, decrease the scan period. 3447 */ 3448 static void update_task_scan_period(struct task_struct *p, 3449 unsigned long shared, unsigned long private) 3450 { 3451 unsigned int period_slot; 3452 int lr_ratio, ps_ratio; 3453 int diff; 3454 3455 unsigned long remote = p->numa_faults_locality[0]; 3456 unsigned long local = p->numa_faults_locality[1]; 3457 3458 /* 3459 * If there were no record hinting faults then either the task is 3460 * completely idle or all activity is in areas that are not of interest 3461 * to automatic numa balancing. Related to that, if there were failed 3462 * migration then it implies we are migrating too quickly or the local 3463 * node is overloaded. In either case, scan slower 3464 */ 3465 if (local + shared == 0 || p->numa_faults_locality[2]) { 3466 p->numa_scan_period = min(p->numa_scan_period_max, 3467 p->numa_scan_period << 1); 3468 3469 p->mm->numa_next_scan = jiffies + 3470 msecs_to_jiffies(p->numa_scan_period); 3471 3472 return; 3473 } 3474 3475 /* 3476 * Prepare to scale scan period relative to the current period. 3477 * == NUMA_PERIOD_THRESHOLD scan period stays the same 3478 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster) 3479 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower) 3480 */ 3481 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS); 3482 lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote); 3483 ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared); 3484 3485 if (ps_ratio >= NUMA_PERIOD_THRESHOLD) { 3486 /* 3487 * Most memory accesses are local. There is no need to 3488 * do fast NUMA scanning, since memory is already local. 3489 */ 3490 int slot = ps_ratio - NUMA_PERIOD_THRESHOLD; 3491 if (!slot) 3492 slot = 1; 3493 diff = slot * period_slot; 3494 } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) { 3495 /* 3496 * Most memory accesses are shared with other tasks. 3497 * There is no point in continuing fast NUMA scanning, 3498 * since other tasks may just move the memory elsewhere. 3499 */ 3500 int slot = lr_ratio - NUMA_PERIOD_THRESHOLD; 3501 if (!slot) 3502 slot = 1; 3503 diff = slot * period_slot; 3504 } else { 3505 /* 3506 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS, 3507 * yet they are not on the local NUMA node. Speed up 3508 * NUMA scanning to get the memory moved over. 3509 */ 3510 int ratio = max(lr_ratio, ps_ratio); 3511 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot; 3512 } 3513 3514 p->numa_scan_period = clamp(p->numa_scan_period + diff, 3515 task_scan_min(p), task_scan_max(p)); 3516 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality)); 3517 } 3518 3519 /* 3520 * Get the fraction of time the task has been running since the last 3521 * NUMA placement cycle. The scheduler keeps similar statistics, but 3522 * decays those on a 32ms period, which is orders of magnitude off 3523 * from the dozens-of-seconds NUMA balancing period. Use the scheduler 3524 * stats only if the task is so new there are no NUMA statistics yet. 3525 */ 3526 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period) 3527 { 3528 u64 runtime, delta, now; 3529 /* Use the start of this time slice to avoid calculations. */ 3530 now = p->se.exec_start; 3531 runtime = p->se.sum_exec_runtime; 3532 3533 if (p->last_task_numa_placement) { 3534 delta = runtime - p->last_sum_exec_runtime; 3535 *period = now - p->last_task_numa_placement; 3536 3537 /* Avoid time going backwards, prevent potential divide error: */ 3538 if (unlikely((s64)*period < 0)) 3539 *period = 0; 3540 } else { 3541 delta = p->se.avg.load_sum; 3542 *period = LOAD_AVG_MAX; 3543 } 3544 3545 p->last_sum_exec_runtime = runtime; 3546 p->last_task_numa_placement = now; 3547 3548 return delta; 3549 } 3550 3551 /* 3552 * Determine the preferred nid for a task in a numa_group. This needs to 3553 * be done in a way that produces consistent results with group_weight, 3554 * otherwise workloads might not converge. 3555 */ 3556 static int preferred_group_nid(struct task_struct *p, int nid) 3557 { 3558 nodemask_t nodes; 3559 int dist; 3560 3561 /* Direct connections between all NUMA nodes. */ 3562 if (sched_numa_topology_type == NUMA_DIRECT) 3563 return nid; 3564 3565 /* 3566 * On a system with glueless mesh NUMA topology, group_weight 3567 * scores nodes according to the number of NUMA hinting faults on 3568 * both the node itself, and on nearby nodes. 3569 */ 3570 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) { 3571 unsigned long score, max_score = 0; 3572 int node, max_node = nid; 3573 3574 dist = sched_max_numa_distance; 3575 3576 for_each_node_state(node, N_CPU) { 3577 score = group_weight(p, node, dist); 3578 if (score > max_score) { 3579 max_score = score; 3580 max_node = node; 3581 } 3582 } 3583 return max_node; 3584 } 3585 3586 /* 3587 * Finding the preferred nid in a system with NUMA backplane 3588 * interconnect topology is more involved. The goal is to locate 3589 * tasks from numa_groups near each other in the system, and 3590 * untangle workloads from different sides of the system. This requires 3591 * searching down the hierarchy of node groups, recursively searching 3592 * inside the highest scoring group of nodes. The nodemask tricks 3593 * keep the complexity of the search down. 3594 */ 3595 nodes = node_states[N_CPU]; 3596 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) { 3597 unsigned long max_faults = 0; 3598 nodemask_t max_group = NODE_MASK_NONE; 3599 int a, b; 3600 3601 /* Are there nodes at this distance from each other? */ 3602 if (!find_numa_distance(dist)) 3603 continue; 3604 3605 for_each_node_mask(a, nodes) { 3606 unsigned long faults = 0; 3607 nodemask_t this_group; 3608 nodes_clear(this_group); 3609 3610 /* Sum group's NUMA faults; includes a==b case. */ 3611 for_each_node_mask(b, nodes) { 3612 if (node_distance(a, b) < dist) { 3613 faults += group_faults(p, b); 3614 node_set(b, this_group); 3615 node_clear(b, nodes); 3616 } 3617 } 3618 3619 /* Remember the top group. */ 3620 if (faults > max_faults) { 3621 max_faults = faults; 3622 max_group = this_group; 3623 /* 3624 * subtle: at the smallest distance there is 3625 * just one node left in each "group", the 3626 * winner is the preferred nid. 3627 */ 3628 nid = a; 3629 } 3630 } 3631 /* Next round, evaluate the nodes within max_group. */ 3632 if (!max_faults) 3633 break; 3634 nodes = max_group; 3635 } 3636 return nid; 3637 } 3638 3639 static void task_numa_placement(struct task_struct *p) 3640 __context_unsafe(/* conditional locking */) 3641 { 3642 int seq, nid, max_nid = NUMA_NO_NODE; 3643 unsigned long max_faults = 0; 3644 unsigned long fault_types[2] = { 0, 0 }; 3645 unsigned long total_faults; 3646 u64 runtime, period; 3647 spinlock_t *group_lock = NULL; 3648 long __maybe_unused new_fp; 3649 struct numa_group *ng; 3650 3651 /* 3652 * The p->mm->numa_scan_seq field gets updated without 3653 * exclusive access. Use READ_ONCE() here to ensure 3654 * that the field is read in a single access: 3655 */ 3656 seq = READ_ONCE(p->mm->numa_scan_seq); 3657 if (p->numa_scan_seq == seq) 3658 return; 3659 p->numa_scan_seq = seq; 3660 p->numa_scan_period_max = task_scan_max(p); 3661 3662 total_faults = p->numa_faults_locality[0] + 3663 p->numa_faults_locality[1]; 3664 runtime = numa_get_avg_runtime(p, &period); 3665 3666 /* If the task is part of a group prevent parallel updates to group stats */ 3667 ng = deref_curr_numa_group(p); 3668 if (ng) { 3669 group_lock = &ng->lock; 3670 spin_lock_irq(group_lock); 3671 } 3672 3673 /* Find the node with the highest number of faults */ 3674 for_each_online_node(nid) { 3675 /* Keep track of the offsets in numa_faults array */ 3676 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx; 3677 unsigned long faults = 0, group_faults = 0; 3678 int priv; 3679 3680 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) { 3681 long diff, f_diff, f_weight; 3682 3683 mem_idx = task_faults_idx(NUMA_MEM, nid, priv); 3684 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv); 3685 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv); 3686 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv); 3687 3688 /* Decay existing window, copy faults since last scan */ 3689 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2; 3690 fault_types[priv] += p->numa_faults[membuf_idx]; 3691 p->numa_faults[membuf_idx] = 0; 3692 3693 /* 3694 * Normalize the faults_from, so all tasks in a group 3695 * count according to CPU use, instead of by the raw 3696 * number of faults. Tasks with little runtime have 3697 * little over-all impact on throughput, and thus their 3698 * faults are less important. 3699 */ 3700 f_weight = div64_u64(runtime << 16, period + 1); 3701 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) / 3702 (total_faults + 1); 3703 f_diff = f_weight - p->numa_faults[cpu_idx] / 2; 3704 p->numa_faults[cpubuf_idx] = 0; 3705 3706 p->numa_faults[mem_idx] += diff; 3707 p->numa_faults[cpu_idx] += f_diff; 3708 faults += p->numa_faults[mem_idx]; 3709 p->total_numa_faults += diff; 3710 if (ng) { 3711 /* 3712 * safe because we can only change our own group 3713 * 3714 * mem_idx represents the offset for a given 3715 * nid and priv in a specific region because it 3716 * is at the beginning of the numa_faults array. 3717 */ 3718 ng->faults[mem_idx] += diff; 3719 ng->faults[cpu_idx] += f_diff; 3720 ng->total_faults += diff; 3721 group_faults += ng->faults[mem_idx]; 3722 } 3723 #ifdef CONFIG_SCHED_CACHE 3724 /* 3725 * Per task p->numa_faults[mem_idx] converges, 3726 * so the accumulation of each task's faults 3727 * converges too - Given the number of threads, 3728 * it cannot overflow an unsigned long. 3729 * Racy with concurrent updates from other threads 3730 * sharing this mm. Acceptable since footprint is a 3731 * heuristic and occasional lost updates are tolerable. 3732 * 3733 * If a task exits, its corresponding footprint must 3734 * be subtracted from the mm->sc_stat.footprint, otherwise 3735 * the mm->sc_stat.footprint will not converge: 3736 * the exiting thread's footprint remains unchanged/undecayed 3737 * in mm->sc_stat.footprint. See exit_mm(). 3738 * 3739 * Lost updates and unsynchronized subtraction 3740 * in exit_mm() can cause footprint + diff to 3741 * go negative. Clamp to zero to prevent the 3742 * unsigned footprint from wrapping. 3743 */ 3744 new_fp = (long)READ_ONCE(p->mm->sc_stat.footprint) + diff; 3745 WRITE_ONCE(p->mm->sc_stat.footprint, 3746 max(new_fp, 0L)); 3747 #endif 3748 } 3749 3750 if (!ng) { 3751 if (faults > max_faults) { 3752 max_faults = faults; 3753 max_nid = nid; 3754 } 3755 } else if (group_faults > max_faults) { 3756 max_faults = group_faults; 3757 max_nid = nid; 3758 } 3759 } 3760 3761 /* Cannot migrate task to CPU-less node */ 3762 max_nid = numa_nearest_node(max_nid, N_CPU); 3763 3764 if (ng) { 3765 numa_group_count_active_nodes(ng); 3766 spin_unlock_irq(group_lock); 3767 max_nid = preferred_group_nid(p, max_nid); 3768 } 3769 3770 if (max_faults) { 3771 /* Set the new preferred node */ 3772 if (max_nid != p->numa_preferred_nid) 3773 sched_setnuma(p, max_nid); 3774 } 3775 3776 update_task_scan_period(p, fault_types[0], fault_types[1]); 3777 } 3778 3779 static inline int get_numa_group(struct numa_group *grp) 3780 { 3781 return refcount_inc_not_zero(&grp->refcount); 3782 } 3783 3784 static inline void put_numa_group(struct numa_group *grp) 3785 { 3786 if (refcount_dec_and_test(&grp->refcount)) 3787 kfree_rcu(grp, rcu); 3788 } 3789 3790 static void task_numa_group(struct task_struct *p, int cpupid, int flags, 3791 int *priv) 3792 { 3793 struct numa_group *grp, *my_grp; 3794 struct task_struct *tsk; 3795 bool join = false; 3796 int cpu = cpupid_to_cpu(cpupid); 3797 int i; 3798 3799 if (unlikely(!deref_curr_numa_group(p))) { 3800 unsigned int size = sizeof(struct numa_group) + 3801 NR_NUMA_HINT_FAULT_STATS * 3802 nr_node_ids * sizeof(unsigned long); 3803 3804 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN); 3805 if (!grp) 3806 return; 3807 3808 refcount_set(&grp->refcount, 1); 3809 grp->active_nodes = 1; 3810 grp->max_faults_cpu = 0; 3811 spin_lock_init(&grp->lock); 3812 grp->gid = p->pid; 3813 3814 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) 3815 grp->faults[i] = p->numa_faults[i]; 3816 3817 grp->total_faults = p->total_numa_faults; 3818 3819 grp->nr_tasks++; 3820 rcu_assign_pointer(p->numa_group, grp); 3821 } 3822 3823 rcu_read_lock(); 3824 tsk = READ_ONCE(cpu_rq(cpu)->curr); 3825 3826 if (!cpupid_match_pid(tsk, cpupid)) 3827 goto no_join; 3828 3829 grp = rcu_dereference_all(tsk->numa_group); 3830 if (!grp) 3831 goto no_join; 3832 3833 my_grp = deref_curr_numa_group(p); 3834 if (grp == my_grp) 3835 goto no_join; 3836 3837 /* 3838 * Only join the other group if its bigger; if we're the bigger group, 3839 * the other task will join us. 3840 */ 3841 if (my_grp->nr_tasks > grp->nr_tasks) 3842 goto no_join; 3843 3844 /* 3845 * Tie-break on the grp address. 3846 */ 3847 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp) 3848 goto no_join; 3849 3850 /* Always join threads in the same process. */ 3851 if (tsk->mm == current->mm) 3852 join = true; 3853 3854 /* Simple filter to avoid false positives due to PID collisions */ 3855 if (flags & TNF_SHARED) 3856 join = true; 3857 3858 /* Update priv based on whether false sharing was detected */ 3859 *priv = !join; 3860 3861 if (join && !get_numa_group(grp)) 3862 goto no_join; 3863 3864 rcu_read_unlock(); 3865 3866 if (!join) 3867 return; 3868 3869 WARN_ON_ONCE(irqs_disabled()); 3870 double_lock_irq(&my_grp->lock, &grp->lock); 3871 3872 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) { 3873 my_grp->faults[i] -= p->numa_faults[i]; 3874 grp->faults[i] += p->numa_faults[i]; 3875 } 3876 my_grp->total_faults -= p->total_numa_faults; 3877 grp->total_faults += p->total_numa_faults; 3878 3879 my_grp->nr_tasks--; 3880 grp->nr_tasks++; 3881 3882 spin_unlock(&my_grp->lock); 3883 spin_unlock_irq(&grp->lock); 3884 3885 rcu_assign_pointer(p->numa_group, grp); 3886 3887 put_numa_group(my_grp); 3888 return; 3889 3890 no_join: 3891 rcu_read_unlock(); 3892 return; 3893 } 3894 3895 /* 3896 * Get rid of NUMA statistics associated with a task (either current or dead). 3897 * If @final is set, the task is dead and has reached refcount zero, so we can 3898 * safely free all relevant data structures. Otherwise, there might be 3899 * concurrent reads from places like load balancing and procfs, and we should 3900 * reset the data back to default state without freeing ->numa_faults. 3901 */ 3902 void task_numa_free(struct task_struct *p, bool final) 3903 { 3904 /* safe: p either is current or is being freed by current */ 3905 struct numa_group *grp = rcu_dereference_raw(p->numa_group); 3906 unsigned long *numa_faults = p->numa_faults; 3907 unsigned long flags; 3908 int i; 3909 3910 if (!numa_faults) 3911 return; 3912 3913 if (grp) { 3914 spin_lock_irqsave(&grp->lock, flags); 3915 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) 3916 grp->faults[i] -= p->numa_faults[i]; 3917 grp->total_faults -= p->total_numa_faults; 3918 3919 grp->nr_tasks--; 3920 spin_unlock_irqrestore(&grp->lock, flags); 3921 RCU_INIT_POINTER(p->numa_group, NULL); 3922 put_numa_group(grp); 3923 } 3924 3925 if (final) { 3926 p->numa_faults = NULL; 3927 kfree(numa_faults); 3928 } else { 3929 p->total_numa_faults = 0; 3930 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) 3931 numa_faults[i] = 0; 3932 } 3933 } 3934 3935 /* 3936 * Got a PROT_NONE fault for a page on @node. 3937 */ 3938 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags) 3939 { 3940 struct task_struct *p = current; 3941 bool migrated = flags & TNF_MIGRATED; 3942 int cpu_node = task_node(current); 3943 int local = !!(flags & TNF_FAULT_LOCAL); 3944 struct numa_group *ng; 3945 int priv; 3946 3947 if (!static_branch_likely(&sched_numa_balancing)) 3948 return; 3949 3950 /* for example, ksmd faulting in a user's mm */ 3951 if (!p->mm) 3952 return; 3953 3954 /* 3955 * NUMA faults statistics are unnecessary for the slow memory 3956 * node for memory tiering mode. 3957 */ 3958 if (!node_is_toptier(mem_node) && 3959 (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING || 3960 !cpupid_valid(last_cpupid))) 3961 return; 3962 3963 /* Allocate buffer to track faults on a per-node basis */ 3964 if (unlikely(!p->numa_faults)) { 3965 int size = sizeof(*p->numa_faults) * 3966 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids; 3967 3968 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN); 3969 if (!p->numa_faults) 3970 return; 3971 3972 p->total_numa_faults = 0; 3973 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality)); 3974 } 3975 3976 /* 3977 * First accesses are treated as private, otherwise consider accesses 3978 * to be private if the accessing pid has not changed 3979 */ 3980 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) { 3981 priv = 1; 3982 } else { 3983 priv = cpupid_match_pid(p, last_cpupid); 3984 if (!priv && !(flags & TNF_NO_GROUP)) 3985 task_numa_group(p, last_cpupid, flags, &priv); 3986 } 3987 3988 /* 3989 * If a workload spans multiple NUMA nodes, a shared fault that 3990 * occurs wholly within the set of nodes that the workload is 3991 * actively using should be counted as local. This allows the 3992 * scan rate to slow down when a workload has settled down. 3993 */ 3994 ng = deref_curr_numa_group(p); 3995 if (!priv && !local && ng && ng->active_nodes > 1 && 3996 numa_is_active_node(cpu_node, ng) && 3997 numa_is_active_node(mem_node, ng)) 3998 local = 1; 3999 4000 /* 4001 * Retry to migrate task to preferred node periodically, in case it 4002 * previously failed, or the scheduler moved us. 4003 */ 4004 if (time_after(jiffies, p->numa_migrate_retry)) { 4005 task_numa_placement(p); 4006 numa_migrate_preferred(p); 4007 } 4008 4009 if (migrated) 4010 p->numa_pages_migrated += pages; 4011 if (flags & TNF_MIGRATE_FAIL) 4012 p->numa_faults_locality[2] += pages; 4013 4014 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages; 4015 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages; 4016 p->numa_faults_locality[local] += pages; 4017 } 4018 4019 static void reset_ptenuma_scan(struct task_struct *p) 4020 { 4021 /* 4022 * We only did a read acquisition of the mmap sem, so 4023 * p->mm->numa_scan_seq is written to without exclusive access 4024 * and the update is not guaranteed to be atomic. That's not 4025 * much of an issue though, since this is just used for 4026 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not 4027 * expensive, to avoid any form of compiler optimizations: 4028 */ 4029 WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1); 4030 p->mm->numa_scan_offset = 0; 4031 } 4032 4033 static bool vma_is_accessed(struct mm_struct *mm, struct vm_area_struct *vma) 4034 { 4035 unsigned long pids; 4036 /* 4037 * Allow unconditional access first two times, so that all the (pages) 4038 * of VMAs get prot_none fault introduced irrespective of accesses. 4039 * This is also done to avoid any side effect of task scanning 4040 * amplifying the unfairness of disjoint set of VMAs' access. 4041 */ 4042 if ((READ_ONCE(current->mm->numa_scan_seq) - vma->numab_state->start_scan_seq) < 2) 4043 return true; 4044 4045 pids = vma->numab_state->pids_active[0] | vma->numab_state->pids_active[1]; 4046 if (test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids)) 4047 return true; 4048 4049 /* 4050 * Complete a scan that has already started regardless of PID access, or 4051 * some VMAs may never be scanned in multi-threaded applications: 4052 */ 4053 if (mm->numa_scan_offset > vma->vm_start) { 4054 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_IGNORE_PID); 4055 return true; 4056 } 4057 4058 /* 4059 * This vma has not been accessed for a while, and if the number 4060 * the threads in the same process is low, which means no other 4061 * threads can help scan this vma, force a vma scan. 4062 */ 4063 if (READ_ONCE(mm->numa_scan_seq) > 4064 (vma->numab_state->prev_scan_seq + get_nr_threads(current))) 4065 return true; 4066 4067 return false; 4068 } 4069 4070 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay) 4071 4072 /* 4073 * The expensive part of numa migration is done from task_work context. 4074 * Triggered from task_tick_numa(). 4075 */ 4076 static void task_numa_work(struct callback_head *work) 4077 { 4078 unsigned long migrate, next_scan, now = jiffies; 4079 struct task_struct *p = current; 4080 struct mm_struct *mm = p->mm; 4081 u64 runtime = p->se.sum_exec_runtime; 4082 struct vm_area_struct *vma; 4083 unsigned long start, end; 4084 unsigned long nr_pte_updates = 0; 4085 long pages, virtpages; 4086 struct vma_iterator vmi; 4087 bool vma_pids_skipped; 4088 bool vma_pids_forced = false; 4089 4090 WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work)); 4091 4092 work->next = work; 4093 /* 4094 * Who cares about NUMA placement when they're dying. 4095 * 4096 * NOTE: make sure not to dereference p->mm before this check, 4097 * exit_task_work() happens _after_ exit_mm() so we could be called 4098 * without p->mm even though we still had it when we enqueued this 4099 * work. 4100 */ 4101 if (p->flags & PF_EXITING) 4102 return; 4103 4104 /* 4105 * Memory is pinned to only one NUMA node via cpuset.mems, naturally 4106 * no page can be migrated. 4107 */ 4108 if (cpusets_enabled() && nodes_weight(cpuset_current_mems_allowed) == 1) { 4109 trace_sched_skip_cpuset_numa(current, &cpuset_current_mems_allowed); 4110 return; 4111 } 4112 4113 if (!mm->numa_next_scan) { 4114 mm->numa_next_scan = now + 4115 msecs_to_jiffies(sysctl_numa_balancing_scan_delay); 4116 } 4117 4118 /* 4119 * Enforce maximal scan/migration frequency.. 4120 */ 4121 migrate = mm->numa_next_scan; 4122 if (time_before(now, migrate)) 4123 return; 4124 4125 if (p->numa_scan_period == 0) { 4126 p->numa_scan_period_max = task_scan_max(p); 4127 p->numa_scan_period = task_scan_start(p); 4128 } 4129 4130 next_scan = now + msecs_to_jiffies(p->numa_scan_period); 4131 if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan)) 4132 return; 4133 4134 /* 4135 * Delay this task enough that another task of this mm will likely win 4136 * the next time around. 4137 */ 4138 p->node_stamp += 2 * TICK_NSEC; 4139 4140 pages = sysctl_numa_balancing_scan_size; 4141 pages <<= 20 - PAGE_SHIFT; /* MB in pages */ 4142 virtpages = pages * 8; /* Scan up to this much virtual space */ 4143 if (!pages) 4144 return; 4145 4146 4147 if (!mmap_read_trylock(mm)) 4148 return; 4149 4150 /* 4151 * VMAs are skipped if the current PID has not trapped a fault within 4152 * the VMA recently. Allow scanning to be forced if there is no 4153 * suitable VMA remaining. 4154 */ 4155 vma_pids_skipped = false; 4156 4157 retry_pids: 4158 start = mm->numa_scan_offset; 4159 vma_iter_init(&vmi, mm, start); 4160 vma = vma_next(&vmi); 4161 if (!vma) { 4162 reset_ptenuma_scan(p); 4163 start = 0; 4164 vma_iter_set(&vmi, start); 4165 vma = vma_next(&vmi); 4166 } 4167 4168 for (; vma; vma = vma_next(&vmi)) { 4169 if (!vma_migratable(vma) || !vma_policy_mof(vma) || 4170 is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) { 4171 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_UNSUITABLE); 4172 continue; 4173 } 4174 4175 /* 4176 * Shared library pages mapped by multiple processes are not 4177 * migrated as it is expected they are cache replicated. Avoid 4178 * hinting faults in read-only file-backed mappings or the vDSO 4179 * as migrating the pages will be of marginal benefit. 4180 */ 4181 if (!vma->vm_mm || 4182 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ))) { 4183 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SHARED_RO); 4184 continue; 4185 } 4186 4187 /* 4188 * Skip inaccessible VMAs to avoid any confusion between 4189 * PROT_NONE and NUMA hinting PTEs 4190 */ 4191 if (!vma_is_accessible(vma)) { 4192 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_INACCESSIBLE); 4193 continue; 4194 } 4195 4196 /* Initialise new per-VMA NUMAB state. */ 4197 if (!vma->numab_state) { 4198 struct vma_numab_state *ptr; 4199 4200 ptr = kzalloc_obj(*ptr); 4201 if (!ptr) 4202 continue; 4203 4204 if (cmpxchg(&vma->numab_state, NULL, ptr)) { 4205 kfree(ptr); 4206 continue; 4207 } 4208 4209 vma->numab_state->start_scan_seq = mm->numa_scan_seq; 4210 4211 vma->numab_state->next_scan = now + 4212 msecs_to_jiffies(sysctl_numa_balancing_scan_delay); 4213 4214 /* Reset happens after 4 times scan delay of scan start */ 4215 vma->numab_state->pids_active_reset = vma->numab_state->next_scan + 4216 msecs_to_jiffies(VMA_PID_RESET_PERIOD); 4217 4218 /* 4219 * Ensure prev_scan_seq does not match numa_scan_seq, 4220 * to prevent VMAs being skipped prematurely on the 4221 * first scan: 4222 */ 4223 vma->numab_state->prev_scan_seq = mm->numa_scan_seq - 1; 4224 } 4225 4226 /* 4227 * Scanning the VMAs of short lived tasks add more overhead. So 4228 * delay the scan for new VMAs. 4229 */ 4230 if (mm->numa_scan_seq && time_before(jiffies, 4231 vma->numab_state->next_scan)) { 4232 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SCAN_DELAY); 4233 continue; 4234 } 4235 4236 /* RESET access PIDs regularly for old VMAs. */ 4237 if (mm->numa_scan_seq && 4238 time_after(jiffies, vma->numab_state->pids_active_reset)) { 4239 vma->numab_state->pids_active_reset = vma->numab_state->pids_active_reset + 4240 msecs_to_jiffies(VMA_PID_RESET_PERIOD); 4241 vma->numab_state->pids_active[0] = READ_ONCE(vma->numab_state->pids_active[1]); 4242 vma->numab_state->pids_active[1] = 0; 4243 } 4244 4245 /* Do not rescan VMAs twice within the same sequence. */ 4246 if (vma->numab_state->prev_scan_seq == mm->numa_scan_seq) { 4247 mm->numa_scan_offset = vma->vm_end; 4248 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SEQ_COMPLETED); 4249 continue; 4250 } 4251 4252 /* 4253 * Do not scan the VMA if task has not accessed it, unless no other 4254 * VMA candidate exists. 4255 */ 4256 if (!vma_pids_forced && !vma_is_accessed(mm, vma)) { 4257 vma_pids_skipped = true; 4258 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_PID_INACTIVE); 4259 continue; 4260 } 4261 4262 do { 4263 start = max(start, vma->vm_start); 4264 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE); 4265 end = min(end, vma->vm_end); 4266 nr_pte_updates = change_prot_numa(vma, start, end); 4267 4268 /* 4269 * Try to scan sysctl_numa_balancing_size worth of 4270 * hpages that have at least one present PTE that 4271 * is not already PTE-numa. If the VMA contains 4272 * areas that are unused or already full of prot_numa 4273 * PTEs, scan up to virtpages, to skip through those 4274 * areas faster. 4275 */ 4276 if (nr_pte_updates) 4277 pages -= (end - start) >> PAGE_SHIFT; 4278 virtpages -= (end - start) >> PAGE_SHIFT; 4279 4280 start = end; 4281 if (pages <= 0 || virtpages <= 0) 4282 goto out; 4283 4284 cond_resched(); 4285 } while (end != vma->vm_end); 4286 4287 /* VMA scan is complete, do not scan until next sequence. */ 4288 vma->numab_state->prev_scan_seq = mm->numa_scan_seq; 4289 4290 /* 4291 * Only force scan within one VMA at a time, to limit the 4292 * cost of scanning a potentially uninteresting VMA. 4293 */ 4294 if (vma_pids_forced) 4295 break; 4296 } 4297 4298 /* 4299 * If no VMAs are remaining and VMAs were skipped due to the PID 4300 * not accessing the VMA previously, then force a scan to ensure 4301 * forward progress: 4302 */ 4303 if (!vma && !vma_pids_forced && vma_pids_skipped) { 4304 vma_pids_forced = true; 4305 goto retry_pids; 4306 } 4307 4308 out: 4309 /* 4310 * It is possible to reach the end of the VMA list but the last few 4311 * VMAs are not guaranteed to the vma_migratable. If they are not, we 4312 * would find the !migratable VMA on the next scan but not reset the 4313 * scanner to the start so check it now. 4314 */ 4315 if (vma) 4316 mm->numa_scan_offset = start; 4317 else 4318 reset_ptenuma_scan(p); 4319 mmap_read_unlock(mm); 4320 4321 /* 4322 * Make sure tasks use at least 32x as much time to run other code 4323 * than they used here, to limit NUMA PTE scanning overhead to 3% max. 4324 * Usually update_task_scan_period slows down scanning enough; on an 4325 * overloaded system we need to limit overhead on a per task basis. 4326 */ 4327 if (unlikely(p->se.sum_exec_runtime != runtime)) { 4328 u64 diff = p->se.sum_exec_runtime - runtime; 4329 p->node_stamp += 32 * diff; 4330 } 4331 } 4332 4333 void init_numa_balancing(u64 clone_flags, struct task_struct *p) 4334 { 4335 int mm_users = 0; 4336 struct mm_struct *mm = p->mm; 4337 4338 if (mm) { 4339 mm_users = atomic_read(&mm->mm_users); 4340 if (mm_users == 1) { 4341 mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay); 4342 mm->numa_scan_seq = 0; 4343 } 4344 } 4345 p->node_stamp = 0; 4346 p->numa_scan_seq = mm ? mm->numa_scan_seq : 0; 4347 p->numa_scan_period = sysctl_numa_balancing_scan_delay; 4348 p->numa_migrate_retry = 0; 4349 /* Protect against double add, see task_tick_numa and task_numa_work */ 4350 p->numa_work.next = &p->numa_work; 4351 p->numa_faults = NULL; 4352 p->numa_pages_migrated = 0; 4353 p->total_numa_faults = 0; 4354 RCU_INIT_POINTER(p->numa_group, NULL); 4355 p->last_task_numa_placement = 0; 4356 p->last_sum_exec_runtime = 0; 4357 4358 init_task_work(&p->numa_work, task_numa_work); 4359 4360 /* New address space, reset the preferred nid */ 4361 if (!(clone_flags & CLONE_VM)) { 4362 p->numa_preferred_nid = NUMA_NO_NODE; 4363 return; 4364 } 4365 4366 /* 4367 * New thread, keep existing numa_preferred_nid which should be copied 4368 * already by arch_dup_task_struct but stagger when scans start. 4369 */ 4370 if (mm) { 4371 unsigned int delay; 4372 4373 delay = min_t(unsigned int, task_scan_max(current), 4374 current->numa_scan_period * mm_users * NSEC_PER_MSEC); 4375 delay += 2 * TICK_NSEC; 4376 p->node_stamp = delay; 4377 } 4378 } 4379 4380 /* 4381 * Drive the periodic memory faults.. 4382 */ 4383 static void task_tick_numa(struct rq *rq, struct task_struct *curr) 4384 { 4385 struct callback_head *work = &curr->numa_work; 4386 u64 period, now; 4387 4388 /* 4389 * We don't care about NUMA placement if we don't have memory. 4390 */ 4391 if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work) 4392 return; 4393 4394 /* 4395 * Using runtime rather than walltime has the dual advantage that 4396 * we (mostly) drive the selection from busy threads and that the 4397 * task needs to have done some actual work before we bother with 4398 * NUMA placement. 4399 */ 4400 now = curr->se.sum_exec_runtime; 4401 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC; 4402 4403 if (now > curr->node_stamp + period) { 4404 if (!curr->node_stamp) 4405 curr->numa_scan_period = task_scan_start(curr); 4406 curr->node_stamp += period; 4407 4408 if (!time_before(jiffies, curr->mm->numa_next_scan)) 4409 task_work_add(curr, work, TWA_RESUME); 4410 } 4411 } 4412 4413 static void update_scan_period(struct task_struct *p, int new_cpu) 4414 { 4415 int src_nid = cpu_to_node(task_cpu(p)); 4416 int dst_nid = cpu_to_node(new_cpu); 4417 4418 if (!static_branch_likely(&sched_numa_balancing)) 4419 return; 4420 4421 if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING)) 4422 return; 4423 4424 if (src_nid == dst_nid) 4425 return; 4426 4427 /* 4428 * Allow resets if faults have been trapped before one scan 4429 * has completed. This is most likely due to a new task that 4430 * is pulled cross-node due to wakeups or load balancing. 4431 */ 4432 if (p->numa_scan_seq) { 4433 /* 4434 * Avoid scan adjustments if moving to the preferred 4435 * node or if the task was not previously running on 4436 * the preferred node. 4437 */ 4438 if (dst_nid == p->numa_preferred_nid || 4439 (p->numa_preferred_nid != NUMA_NO_NODE && 4440 src_nid != p->numa_preferred_nid)) 4441 return; 4442 } 4443 4444 p->numa_scan_period = task_scan_start(p); 4445 } 4446 4447 #else /* !CONFIG_NUMA_BALANCING: */ 4448 4449 static void task_tick_numa(struct rq *rq, struct task_struct *curr) 4450 { 4451 } 4452 4453 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p) 4454 { 4455 } 4456 4457 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p) 4458 { 4459 } 4460 4461 static inline void update_scan_period(struct task_struct *p, int new_cpu) 4462 { 4463 } 4464 4465 #endif /* !CONFIG_NUMA_BALANCING */ 4466 4467 static void 4468 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se) 4469 { 4470 update_load_add(&cfs_rq->load, se->load.weight); 4471 if (entity_is_task(se)) { 4472 struct task_struct *p = task_of(se); 4473 struct rq *rq = rq_of(cfs_rq); 4474 4475 account_numa_enqueue(rq, p); 4476 account_llc_enqueue(rq, p); 4477 list_add(&se->group_node, &rq->cfs_tasks); 4478 } 4479 cfs_rq->nr_queued++; 4480 } 4481 4482 static void 4483 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se) 4484 { 4485 update_load_sub(&cfs_rq->load, se->load.weight); 4486 if (entity_is_task(se)) { 4487 struct task_struct *p = task_of(se); 4488 struct rq *rq = rq_of(cfs_rq); 4489 4490 account_numa_dequeue(rq, p); 4491 account_llc_dequeue(rq, p); 4492 list_del_init(&se->group_node); 4493 } 4494 cfs_rq->nr_queued--; 4495 } 4496 4497 /* 4498 * Signed add and clamp on underflow. 4499 * 4500 * Explicitly do a load-store to ensure the intermediate value never hits 4501 * memory. This allows lockless observations without ever seeing the negative 4502 * values. 4503 */ 4504 #define add_positive(_ptr, _val) do { \ 4505 typeof(_ptr) ptr = (_ptr); \ 4506 __signed_scalar_typeof(*ptr) val = (_val); \ 4507 typeof(*ptr) res, var = READ_ONCE(*ptr); \ 4508 \ 4509 res = var + val; \ 4510 \ 4511 if (val < 0 && res > var) \ 4512 res = 0; \ 4513 \ 4514 WRITE_ONCE(*ptr, res); \ 4515 } while (0) 4516 4517 /* 4518 * Remove and clamp on negative, from a local variable. 4519 * 4520 * A variant of sub_positive(), which does not use explicit load-store 4521 * and is thus optimized for local variable updates. 4522 */ 4523 #define lsub_positive(_ptr, _val) do { \ 4524 typeof(_ptr) ptr = (_ptr); \ 4525 *ptr -= min_t(typeof(*ptr), *ptr, _val); \ 4526 } while (0) 4527 4528 4529 /* 4530 * Because of rounding, se->util_sum might ends up being +1 more than 4531 * cfs->util_sum. Although this is not a problem by itself, detaching 4532 * a lot of tasks with the rounding problem between 2 updates of 4533 * util_avg (~1ms) can make cfs->util_sum becoming null whereas 4534 * cfs_util_avg is not. 4535 * 4536 * Check that util_sum is still above its lower bound for the new 4537 * util_avg. Given that period_contrib might have moved since the last 4538 * sync, we are only sure that util_sum must be above or equal to 4539 * util_avg * minimum possible divider 4540 */ 4541 #define __update_sa(sa, name, delta_avg, delta_sum) do { \ 4542 add_positive(&(sa)->name##_avg, delta_avg); \ 4543 add_positive(&(sa)->name##_sum, delta_sum); \ 4544 (sa)->name##_sum = max_t(typeof((sa)->name##_sum), \ 4545 (sa)->name##_sum, \ 4546 (sa)->name##_avg * PELT_MIN_DIVIDER); \ 4547 } while (0) 4548 4549 static inline void 4550 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) 4551 { 4552 __update_sa(&cfs_rq->avg, load, se->avg.load_avg, 4553 se_weight(se) * se->avg.load_sum); 4554 } 4555 4556 static inline void 4557 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) 4558 { 4559 __update_sa(&cfs_rq->avg, load, -se->avg.load_avg, 4560 se_weight(se) * -se->avg.load_sum); 4561 } 4562 4563 static void 4564 rescale_entity(struct sched_entity *se, unsigned long weight, bool rel_vprot) 4565 { 4566 unsigned long old_weight = se->load.weight; 4567 4568 /* 4569 * VRUNTIME 4570 * -------- 4571 * 4572 * COROLLARY #1: The virtual runtime of the entity needs to be 4573 * adjusted if re-weight at !0-lag point. 4574 * 4575 * Proof: For contradiction assume this is not true, so we can 4576 * re-weight without changing vruntime at !0-lag point. 4577 * 4578 * Weight VRuntime Avg-VRuntime 4579 * before w v V 4580 * after w' v' V' 4581 * 4582 * Since lag needs to be preserved through re-weight: 4583 * 4584 * lag = (V - v)*w = (V'- v')*w', where v = v' 4585 * ==> V' = (V - v)*w/w' + v (1) 4586 * 4587 * Let W be the total weight of the entities before reweight, 4588 * since V' is the new weighted average of entities: 4589 * 4590 * V' = (WV + w'v - wv) / (W + w' - w) (2) 4591 * 4592 * by using (1) & (2) we obtain: 4593 * 4594 * (WV + w'v - wv) / (W + w' - w) = (V - v)*w/w' + v 4595 * ==> (WV-Wv+Wv+w'v-wv)/(W+w'-w) = (V - v)*w/w' + v 4596 * ==> (WV - Wv)/(W + w' - w) + v = (V - v)*w/w' + v 4597 * ==> (V - v)*W/(W + w' - w) = (V - v)*w/w' (3) 4598 * 4599 * Since we are doing at !0-lag point which means V != v, we 4600 * can simplify (3): 4601 * 4602 * ==> W / (W + w' - w) = w / w' 4603 * ==> Ww' = Ww + ww' - ww 4604 * ==> W * (w' - w) = w * (w' - w) 4605 * ==> W = w (re-weight indicates w' != w) 4606 * 4607 * So the cfs_rq contains only one entity, hence vruntime of 4608 * the entity @v should always equal to the cfs_rq's weighted 4609 * average vruntime @V, which means we will always re-weight 4610 * at 0-lag point, thus breach assumption. Proof completed. 4611 * 4612 * 4613 * COROLLARY #2: Re-weight does NOT affect weighted average 4614 * vruntime of all the entities. 4615 * 4616 * Proof: According to corollary #1, Eq. (1) should be: 4617 * 4618 * (V - v)*w = (V' - v')*w' 4619 * ==> v' = V' - (V - v)*w/w' (4) 4620 * 4621 * According to the weighted average formula, we have: 4622 * 4623 * V' = (WV - wv + w'v') / (W - w + w') 4624 * = (WV - wv + w'(V' - (V - v)w/w')) / (W - w + w') 4625 * = (WV - wv + w'V' - Vw + wv) / (W - w + w') 4626 * = (WV + w'V' - Vw) / (W - w + w') 4627 * 4628 * ==> V'*(W - w + w') = WV + w'V' - Vw 4629 * ==> V' * (W - w) = (W - w) * V (5) 4630 * 4631 * If the entity is the only one in the cfs_rq, then reweight 4632 * always occurs at 0-lag point, so V won't change. Or else 4633 * there are other entities, hence W != w, then Eq. (5) turns 4634 * into V' = V. So V won't change in either case, proof done. 4635 * 4636 * 4637 * So according to corollary #1 & #2, the effect of re-weight 4638 * on vruntime should be: 4639 * 4640 * v' = V' - (V - v) * w / w' (4) 4641 * = V - (V - v) * w / w' 4642 * = V - vl * w / w' 4643 * = V - vl' 4644 */ 4645 se->vlag = div64_long(se->vlag * old_weight, weight); 4646 4647 /* 4648 * DEADLINE 4649 * -------- 4650 * 4651 * When the weight changes, the virtual time slope changes and 4652 * we should adjust the relative virtual deadline accordingly. 4653 * 4654 * d' = v' + (d - v)*w/w' 4655 * = V' - (V - v)*w/w' + (d - v)*w/w' 4656 * = V - (V - v)*w/w' + (d - v)*w/w' 4657 * = V + (d - V)*w/w' 4658 */ 4659 if (se->rel_deadline) 4660 se->deadline = div64_long(se->deadline * old_weight, weight); 4661 4662 if (rel_vprot) 4663 se->vprot = div64_long(se->vprot * old_weight, weight); 4664 } 4665 4666 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, 4667 unsigned long weight) 4668 { 4669 bool curr = cfs_rq->curr == se; 4670 bool rel_vprot = false; 4671 u64 avruntime = 0; 4672 4673 if (se->on_rq) { 4674 /* commit outstanding execution time */ 4675 update_curr(cfs_rq); 4676 avruntime = avg_vruntime(cfs_rq); 4677 se->vlag = entity_lag(cfs_rq, se, avruntime); 4678 se->deadline -= avruntime; 4679 se->rel_deadline = 1; 4680 if (curr && protect_slice(se)) { 4681 se->vprot -= avruntime; 4682 rel_vprot = true; 4683 } 4684 4685 cfs_rq->nr_queued--; 4686 if (!curr) 4687 __dequeue_entity(cfs_rq, se); 4688 update_load_sub(&cfs_rq->load, se->load.weight); 4689 } 4690 dequeue_load_avg(cfs_rq, se); 4691 4692 rescale_entity(se, weight, rel_vprot); 4693 4694 update_load_set(&se->load, weight); 4695 4696 do { 4697 u32 divider = get_pelt_divider(&se->avg); 4698 se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider); 4699 } while (0); 4700 4701 enqueue_load_avg(cfs_rq, se); 4702 if (se->on_rq) { 4703 if (rel_vprot) 4704 se->vprot += avruntime; 4705 se->deadline += avruntime; 4706 se->rel_deadline = 0; 4707 se->vruntime = avruntime - se->vlag; 4708 4709 update_load_add(&cfs_rq->load, se->load.weight); 4710 if (!curr) 4711 __enqueue_entity(cfs_rq, se); 4712 cfs_rq->nr_queued++; 4713 } 4714 } 4715 4716 static void reweight_task_fair(struct rq *rq, struct task_struct *p, 4717 const struct load_weight *lw) 4718 { 4719 struct sched_entity *se = &p->se; 4720 struct cfs_rq *cfs_rq = cfs_rq_of(se); 4721 struct load_weight *load = &se->load; 4722 4723 reweight_entity(cfs_rq, se, lw->weight); 4724 load->inv_weight = lw->inv_weight; 4725 } 4726 4727 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq); 4728 4729 #ifdef CONFIG_FAIR_GROUP_SCHED 4730 /* 4731 * All this does is approximate the hierarchical proportion which includes that 4732 * global sum we all love to hate. 4733 * 4734 * That is, the weight of a group entity, is the proportional share of the 4735 * group weight based on the group runqueue weights. That is: 4736 * 4737 * tg->weight * grq->load.weight 4738 * ge->load.weight = ----------------------------- (1) 4739 * \Sum grq->load.weight 4740 * 4741 * Now, because computing that sum is prohibitively expensive to compute (been 4742 * there, done that) we approximate it with this average stuff. The average 4743 * moves slower and therefore the approximation is cheaper and more stable. 4744 * 4745 * So instead of the above, we substitute: 4746 * 4747 * grq->load.weight -> grq->avg.load_avg (2) 4748 * 4749 * which yields the following: 4750 * 4751 * tg->weight * grq->avg.load_avg 4752 * ge->load.weight = ------------------------------ (3) 4753 * tg->load_avg 4754 * 4755 * Where: tg->load_avg ~= \Sum grq->avg.load_avg 4756 * 4757 * That is shares_avg, and it is right (given the approximation (2)). 4758 * 4759 * The problem with it is that because the average is slow -- it was designed 4760 * to be exactly that of course -- this leads to transients in boundary 4761 * conditions. In specific, the case where the group was idle and we start the 4762 * one task. It takes time for our CPU's grq->avg.load_avg to build up, 4763 * yielding bad latency etc.. 4764 * 4765 * Now, in that special case (1) reduces to: 4766 * 4767 * tg->weight * grq->load.weight 4768 * ge->load.weight = ----------------------------- = tg->weight (4) 4769 * grp->load.weight 4770 * 4771 * That is, the sum collapses because all other CPUs are idle; the UP scenario. 4772 * 4773 * So what we do is modify our approximation (3) to approach (4) in the (near) 4774 * UP case, like: 4775 * 4776 * ge->load.weight = 4777 * 4778 * tg->weight * grq->load.weight 4779 * --------------------------------------------------- (5) 4780 * tg->load_avg - grq->avg.load_avg + grq->load.weight 4781 * 4782 * But because grq->load.weight can drop to 0, resulting in a divide by zero, 4783 * we need to use grq->avg.load_avg as its lower bound, which then gives: 4784 * 4785 * 4786 * tg->weight * grq->load.weight 4787 * ge->load.weight = ----------------------------- (6) 4788 * tg_load_avg' 4789 * 4790 * Where: 4791 * 4792 * tg_load_avg' = tg->load_avg - grq->avg.load_avg + 4793 * max(grq->load.weight, grq->avg.load_avg) 4794 * 4795 * And that is shares_weight and is icky. In the (near) UP case it approaches 4796 * (4) while in the normal case it approaches (3). It consistently 4797 * overestimates the ge->load.weight and therefore: 4798 * 4799 * \Sum ge->load.weight >= tg->weight 4800 * 4801 * hence icky! 4802 */ 4803 static long calc_group_shares(struct cfs_rq *cfs_rq) 4804 { 4805 long tg_weight, tg_shares, load, shares; 4806 struct task_group *tg = cfs_rq->tg; 4807 4808 tg_shares = READ_ONCE(tg->shares); 4809 4810 load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg); 4811 4812 tg_weight = atomic_long_read(&tg->load_avg); 4813 4814 /* Ensure tg_weight >= load */ 4815 tg_weight -= cfs_rq->tg_load_avg_contrib; 4816 tg_weight += load; 4817 4818 shares = (tg_shares * load); 4819 if (tg_weight) 4820 shares /= tg_weight; 4821 4822 /* 4823 * MIN_SHARES has to be unscaled here to support per-CPU partitioning 4824 * of a group with small tg->shares value. It is a floor value which is 4825 * assigned as a minimum load.weight to the sched_entity representing 4826 * the group on a CPU. 4827 * 4828 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024 4829 * on an 8-core system with 8 tasks each runnable on one CPU shares has 4830 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In 4831 * case no task is runnable on a CPU MIN_SHARES=2 should be returned 4832 * instead of 0. 4833 */ 4834 return clamp_t(long, shares, MIN_SHARES, tg_shares); 4835 } 4836 4837 /* 4838 * Recomputes the group entity based on the current state of its group 4839 * runqueue. 4840 */ 4841 static void update_cfs_group(struct sched_entity *se) 4842 { 4843 struct cfs_rq *gcfs_rq = group_cfs_rq(se); 4844 long shares; 4845 4846 /* 4847 * When a group becomes empty, preserve its weight. This matters for 4848 * DELAY_DEQUEUE. 4849 */ 4850 if (!gcfs_rq || !gcfs_rq->load.weight) 4851 return; 4852 4853 shares = calc_group_shares(gcfs_rq); 4854 if (unlikely(se->load.weight != shares)) 4855 reweight_entity(cfs_rq_of(se), se, shares); 4856 } 4857 4858 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 4859 static inline void update_cfs_group(struct sched_entity *se) 4860 { 4861 } 4862 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 4863 4864 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags) 4865 { 4866 struct rq *rq = rq_of(cfs_rq); 4867 4868 if (&rq->cfs == cfs_rq) { 4869 /* 4870 * There are a few boundary cases this might miss but it should 4871 * get called often enough that that should (hopefully) not be 4872 * a real problem. 4873 * 4874 * It will not get called when we go idle, because the idle 4875 * thread is a different class (!fair), nor will the utilization 4876 * number include things like RT tasks. 4877 * 4878 * As is, the util number is not freq-invariant (we'd have to 4879 * implement arch_scale_freq_capacity() for that). 4880 * 4881 * See cpu_util_cfs(). 4882 */ 4883 cpufreq_update_util(rq, flags); 4884 } 4885 } 4886 4887 static inline bool load_avg_is_decayed(struct sched_avg *sa) 4888 { 4889 if (sa->load_sum) 4890 return false; 4891 4892 if (sa->util_sum) 4893 return false; 4894 4895 if (sa->runnable_sum) 4896 return false; 4897 4898 /* 4899 * _avg must be null when _sum are null because _avg = _sum / divider 4900 * Make sure that rounding and/or propagation of PELT values never 4901 * break this. 4902 */ 4903 WARN_ON_ONCE(sa->load_avg || 4904 sa->util_avg || 4905 sa->runnable_avg); 4906 4907 return true; 4908 } 4909 4910 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq) 4911 { 4912 return u64_u32_load_copy(cfs_rq->avg.last_update_time, 4913 cfs_rq->last_update_time_copy); 4914 } 4915 #ifdef CONFIG_FAIR_GROUP_SCHED 4916 /* 4917 * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list 4918 * immediately before a parent cfs_rq, and cfs_rqs are removed from the list 4919 * bottom-up, we only have to test whether the cfs_rq before us on the list 4920 * is our child. 4921 * If cfs_rq is not on the list, test whether a child needs its to be added to 4922 * connect a branch to the tree * (see list_add_leaf_cfs_rq() for details). 4923 */ 4924 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq) 4925 { 4926 struct cfs_rq *prev_cfs_rq; 4927 struct list_head *prev; 4928 struct rq *rq = rq_of(cfs_rq); 4929 4930 if (cfs_rq->on_list) { 4931 prev = cfs_rq->leaf_cfs_rq_list.prev; 4932 } else { 4933 prev = rq->tmp_alone_branch; 4934 } 4935 4936 if (prev == &rq->leaf_cfs_rq_list) 4937 return false; 4938 4939 prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list); 4940 4941 return (prev_cfs_rq->tg->parent == cfs_rq->tg); 4942 } 4943 4944 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq) 4945 { 4946 if (cfs_rq->load.weight) 4947 return false; 4948 4949 if (!load_avg_is_decayed(&cfs_rq->avg)) 4950 return false; 4951 4952 if (child_cfs_rq_on_list(cfs_rq)) 4953 return false; 4954 4955 if (cfs_rq->tg_load_avg_contrib) 4956 return false; 4957 4958 return true; 4959 } 4960 4961 /** 4962 * update_tg_load_avg - update the tg's load avg 4963 * @cfs_rq: the cfs_rq whose avg changed 4964 * 4965 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load. 4966 * However, because tg->load_avg is a global value there are performance 4967 * considerations. 4968 * 4969 * In order to avoid having to look at the other cfs_rq's, we use a 4970 * differential update where we store the last value we propagated. This in 4971 * turn allows skipping updates if the differential is 'small'. 4972 * 4973 * Updating tg's load_avg is necessary before update_cfs_share(). 4974 */ 4975 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) 4976 { 4977 long delta; 4978 u64 now; 4979 4980 /* 4981 * No need to update load_avg for root_task_group as it is not used. 4982 */ 4983 if (cfs_rq->tg == &root_task_group) 4984 return; 4985 4986 /* rq has been offline and doesn't contribute to the share anymore: */ 4987 if (!cpu_active(cpu_of(rq_of(cfs_rq)))) 4988 return; 4989 4990 /* 4991 * For migration heavy workloads, access to tg->load_avg can be 4992 * unbound. Limit the update rate to at most once per ms. 4993 */ 4994 now = rq_clock(rq_of(cfs_rq)); 4995 if (now - cfs_rq->last_update_tg_load_avg < NSEC_PER_MSEC) 4996 return; 4997 4998 delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib; 4999 if (abs(delta) > cfs_rq->tg_load_avg_contrib / 64) { 5000 atomic_long_add(delta, &cfs_rq->tg->load_avg); 5001 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg; 5002 cfs_rq->last_update_tg_load_avg = now; 5003 } 5004 } 5005 5006 static inline void clear_tg_load_avg(struct cfs_rq *cfs_rq) 5007 { 5008 long delta; 5009 u64 now; 5010 5011 /* 5012 * No need to update load_avg for root_task_group, as it is not used. 5013 */ 5014 if (cfs_rq->tg == &root_task_group) 5015 return; 5016 5017 now = rq_clock(rq_of(cfs_rq)); 5018 delta = 0 - cfs_rq->tg_load_avg_contrib; 5019 atomic_long_add(delta, &cfs_rq->tg->load_avg); 5020 cfs_rq->tg_load_avg_contrib = 0; 5021 cfs_rq->last_update_tg_load_avg = now; 5022 } 5023 5024 /* CPU offline callback: */ 5025 static void __maybe_unused clear_tg_offline_cfs_rqs(struct rq *rq) 5026 { 5027 struct task_group *tg; 5028 5029 lockdep_assert_rq_held(rq); 5030 5031 /* 5032 * The rq clock has already been updated in 5033 * set_rq_offline(), so we should skip updating 5034 * the rq clock again in unthrottle_cfs_rq(). 5035 */ 5036 rq_clock_start_loop_update(rq); 5037 5038 guard(rcu)(); 5039 5040 list_for_each_entry_rcu(tg, &task_groups, list) { 5041 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq)); 5042 5043 clear_tg_load_avg(cfs_rq); 5044 } 5045 5046 rq_clock_stop_loop_update(rq); 5047 } 5048 5049 /* 5050 * Called within set_task_rq() right before setting a task's CPU. The 5051 * caller only guarantees p->pi_lock is held; no other assumptions, 5052 * including the state of rq->lock, should be made. 5053 */ 5054 void set_task_rq_fair(struct sched_entity *se, 5055 struct cfs_rq *prev, struct cfs_rq *next) 5056 { 5057 u64 p_last_update_time; 5058 u64 n_last_update_time; 5059 5060 if (!sched_feat(ATTACH_AGE_LOAD)) 5061 return; 5062 5063 /* 5064 * We are supposed to update the task to "current" time, then its up to 5065 * date and ready to go to new CPU/cfs_rq. But we have difficulty in 5066 * getting what current time is, so simply throw away the out-of-date 5067 * time. This will result in the wakee task is less decayed, but giving 5068 * the wakee more load sounds not bad. 5069 */ 5070 if (!(se->avg.last_update_time && prev)) 5071 return; 5072 5073 p_last_update_time = cfs_rq_last_update_time(prev); 5074 n_last_update_time = cfs_rq_last_update_time(next); 5075 5076 __update_load_avg_blocked_se(p_last_update_time, se); 5077 se->avg.last_update_time = n_last_update_time; 5078 } 5079 5080 /* 5081 * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to 5082 * propagate its contribution. The key to this propagation is the invariant 5083 * that for each group: 5084 * 5085 * ge->avg == grq->avg (1) 5086 * 5087 * _IFF_ we look at the pure running and runnable sums. Because they 5088 * represent the very same entity, just at different points in the hierarchy. 5089 * 5090 * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial 5091 * and simply copies the running/runnable sum over (but still wrong, because 5092 * the group entity and group rq do not have their PELT windows aligned). 5093 * 5094 * However, update_tg_cfs_load() is more complex. So we have: 5095 * 5096 * ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg (2) 5097 * 5098 * And since, like util, the runnable part should be directly transferable, 5099 * the following would _appear_ to be the straight forward approach: 5100 * 5101 * grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg (3) 5102 * 5103 * And per (1) we have: 5104 * 5105 * ge->avg.runnable_avg == grq->avg.runnable_avg 5106 * 5107 * Which gives: 5108 * 5109 * ge->load.weight * grq->avg.load_avg 5110 * ge->avg.load_avg = ----------------------------------- (4) 5111 * grq->load.weight 5112 * 5113 * Except that is wrong! 5114 * 5115 * Because while for entities historical weight is not important and we 5116 * really only care about our future and therefore can consider a pure 5117 * runnable sum, runqueues can NOT do this. 5118 * 5119 * We specifically want runqueues to have a load_avg that includes 5120 * historical weights. Those represent the blocked load, the load we expect 5121 * to (shortly) return to us. This only works by keeping the weights as 5122 * integral part of the sum. We therefore cannot decompose as per (3). 5123 * 5124 * Another reason this doesn't work is that runnable isn't a 0-sum entity. 5125 * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the 5126 * rq itself is runnable anywhere between 2/3 and 1 depending on how the 5127 * runnable section of these tasks overlap (or not). If they were to perfectly 5128 * align the rq as a whole would be runnable 2/3 of the time. If however we 5129 * always have at least 1 runnable task, the rq as a whole is always runnable. 5130 * 5131 * So we'll have to approximate.. :/ 5132 * 5133 * Given the constraint: 5134 * 5135 * ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX 5136 * 5137 * We can construct a rule that adds runnable to a rq by assuming minimal 5138 * overlap. 5139 * 5140 * On removal, we'll assume each task is equally runnable; which yields: 5141 * 5142 * grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight 5143 * 5144 * XXX: only do this for the part of runnable > running ? 5145 * 5146 */ 5147 static inline void 5148 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq) 5149 { 5150 long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg; 5151 u32 new_sum, divider; 5152 5153 /* Nothing to update */ 5154 if (!delta_avg) 5155 return; 5156 5157 /* 5158 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se. 5159 * See ___update_load_avg() for details. 5160 */ 5161 divider = get_pelt_divider(&cfs_rq->avg); 5162 5163 /* Set new sched_entity's utilization */ 5164 se->avg.util_avg = gcfs_rq->avg.util_avg; 5165 new_sum = se->avg.util_avg * divider; 5166 delta_sum = (long)new_sum - (long)se->avg.util_sum; 5167 se->avg.util_sum = new_sum; 5168 5169 /* Update parent cfs_rq utilization */ 5170 __update_sa(&cfs_rq->avg, util, delta_avg, delta_sum); 5171 } 5172 5173 static inline void 5174 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq) 5175 { 5176 long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg; 5177 u32 new_sum, divider; 5178 5179 /* Nothing to update */ 5180 if (!delta_avg) 5181 return; 5182 5183 /* 5184 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se. 5185 * See ___update_load_avg() for details. 5186 */ 5187 divider = get_pelt_divider(&cfs_rq->avg); 5188 5189 /* Set new sched_entity's runnable */ 5190 se->avg.runnable_avg = gcfs_rq->avg.runnable_avg; 5191 new_sum = se->avg.runnable_avg * divider; 5192 delta_sum = (long)new_sum - (long)se->avg.runnable_sum; 5193 se->avg.runnable_sum = new_sum; 5194 5195 /* Update parent cfs_rq runnable */ 5196 __update_sa(&cfs_rq->avg, runnable, delta_avg, delta_sum); 5197 } 5198 5199 static inline void 5200 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq) 5201 { 5202 long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum; 5203 unsigned long load_avg; 5204 u64 load_sum = 0; 5205 s64 delta_sum; 5206 u32 divider; 5207 5208 if (!runnable_sum) 5209 return; 5210 5211 gcfs_rq->prop_runnable_sum = 0; 5212 5213 /* 5214 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se. 5215 * See ___update_load_avg() for details. 5216 */ 5217 divider = get_pelt_divider(&cfs_rq->avg); 5218 5219 if (runnable_sum >= 0) { 5220 /* 5221 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until 5222 * the CPU is saturated running == runnable. 5223 */ 5224 runnable_sum += se->avg.load_sum; 5225 runnable_sum = min_t(long, runnable_sum, divider); 5226 } else { 5227 /* 5228 * Estimate the new unweighted runnable_sum of the gcfs_rq by 5229 * assuming all tasks are equally runnable. 5230 */ 5231 if (scale_load_down(gcfs_rq->load.weight)) { 5232 load_sum = div_u64(gcfs_rq->avg.load_sum, 5233 scale_load_down(gcfs_rq->load.weight)); 5234 } 5235 5236 /* But make sure to not inflate se's runnable */ 5237 runnable_sum = min(se->avg.load_sum, load_sum); 5238 } 5239 5240 /* 5241 * runnable_sum can't be lower than running_sum 5242 * Rescale running sum to be in the same range as runnable sum 5243 * running_sum is in [0 : LOAD_AVG_MAX << SCHED_CAPACITY_SHIFT] 5244 * runnable_sum is in [0 : LOAD_AVG_MAX] 5245 */ 5246 running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT; 5247 runnable_sum = max(runnable_sum, running_sum); 5248 5249 load_sum = se_weight(se) * runnable_sum; 5250 load_avg = div_u64(load_sum, divider); 5251 5252 delta_avg = load_avg - se->avg.load_avg; 5253 if (!delta_avg) 5254 return; 5255 5256 delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum; 5257 5258 se->avg.load_sum = runnable_sum; 5259 se->avg.load_avg = load_avg; 5260 __update_sa(&cfs_rq->avg, load, delta_avg, delta_sum); 5261 } 5262 5263 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) 5264 { 5265 cfs_rq->propagate = 1; 5266 cfs_rq->prop_runnable_sum += runnable_sum; 5267 } 5268 5269 /* Update task and its cfs_rq load average */ 5270 static inline int propagate_entity_load_avg(struct sched_entity *se) 5271 { 5272 struct cfs_rq *cfs_rq, *gcfs_rq; 5273 5274 if (entity_is_task(se)) 5275 return 0; 5276 5277 gcfs_rq = group_cfs_rq(se); 5278 if (!gcfs_rq->propagate) 5279 return 0; 5280 5281 gcfs_rq->propagate = 0; 5282 5283 cfs_rq = cfs_rq_of(se); 5284 5285 add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum); 5286 5287 update_tg_cfs_util(cfs_rq, se, gcfs_rq); 5288 update_tg_cfs_runnable(cfs_rq, se, gcfs_rq); 5289 update_tg_cfs_load(cfs_rq, se, gcfs_rq); 5290 5291 trace_pelt_cfs_tp(cfs_rq); 5292 trace_pelt_se_tp(se); 5293 5294 return 1; 5295 } 5296 5297 /* 5298 * Check if we need to update the load and the utilization of a blocked 5299 * group_entity: 5300 */ 5301 static inline bool skip_blocked_update(struct sched_entity *se) 5302 { 5303 struct cfs_rq *gcfs_rq = group_cfs_rq(se); 5304 5305 /* 5306 * If sched_entity still have not zero load or utilization, we have to 5307 * decay it: 5308 */ 5309 if (se->avg.load_avg || se->avg.util_avg) 5310 return false; 5311 5312 /* 5313 * If there is a pending propagation, we have to update the load and 5314 * the utilization of the sched_entity: 5315 */ 5316 if (gcfs_rq->propagate) 5317 return false; 5318 5319 /* 5320 * Otherwise, the load and the utilization of the sched_entity is 5321 * already zero and there is no pending propagation, so it will be a 5322 * waste of time to try to decay it: 5323 */ 5324 return true; 5325 } 5326 5327 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 5328 5329 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {} 5330 5331 static inline void clear_tg_offline_cfs_rqs(struct rq *rq) {} 5332 5333 static inline int propagate_entity_load_avg(struct sched_entity *se) 5334 { 5335 return 0; 5336 } 5337 5338 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {} 5339 5340 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 5341 5342 #ifdef CONFIG_NO_HZ_COMMON 5343 static inline void migrate_se_pelt_lag(struct sched_entity *se) 5344 { 5345 u64 throttled = 0, now, lut; 5346 struct cfs_rq *cfs_rq; 5347 struct rq *rq; 5348 bool is_idle; 5349 5350 if (load_avg_is_decayed(&se->avg)) 5351 return; 5352 5353 cfs_rq = cfs_rq_of(se); 5354 rq = rq_of(cfs_rq); 5355 5356 rcu_read_lock(); 5357 is_idle = is_idle_task(rcu_dereference_all(rq->curr)); 5358 rcu_read_unlock(); 5359 5360 /* 5361 * The lag estimation comes with a cost we don't want to pay all the 5362 * time. Hence, limiting to the case where the source CPU is idle and 5363 * we know we are at the greatest risk to have an outdated clock. 5364 */ 5365 if (!is_idle) 5366 return; 5367 5368 /* 5369 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where: 5370 * 5371 * last_update_time (the cfs_rq's last_update_time) 5372 * = cfs_rq_clock_pelt()@cfs_rq_idle 5373 * = rq_clock_pelt()@cfs_rq_idle 5374 * - cfs->throttled_clock_pelt_time@cfs_rq_idle 5375 * 5376 * cfs_idle_lag (delta between rq's update and cfs_rq's update) 5377 * = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle 5378 * 5379 * rq_idle_lag (delta between now and rq's update) 5380 * = sched_clock_cpu() - rq_clock()@rq_idle 5381 * 5382 * We can then write: 5383 * 5384 * now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time + 5385 * sched_clock_cpu() - rq_clock()@rq_idle 5386 * Where: 5387 * rq_clock_pelt()@rq_idle is rq->clock_pelt_idle 5388 * rq_clock()@rq_idle is rq->clock_idle 5389 * cfs->throttled_clock_pelt_time@cfs_rq_idle 5390 * is cfs_rq->throttled_pelt_idle 5391 */ 5392 5393 #ifdef CONFIG_CFS_BANDWIDTH 5394 throttled = u64_u32_load(cfs_rq->throttled_pelt_idle); 5395 /* The clock has been stopped for throttling */ 5396 if (throttled == U64_MAX) 5397 return; 5398 #endif 5399 now = u64_u32_load(rq->clock_pelt_idle); 5400 /* 5401 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case 5402 * is observed the old clock_pelt_idle value and the new clock_idle, 5403 * which lead to an underestimation. The opposite would lead to an 5404 * overestimation. 5405 */ 5406 smp_rmb(); 5407 lut = cfs_rq_last_update_time(cfs_rq); 5408 5409 now -= throttled; 5410 if (now < lut) 5411 /* 5412 * cfs_rq->avg.last_update_time is more recent than our 5413 * estimation, let's use it. 5414 */ 5415 now = lut; 5416 else 5417 now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle); 5418 5419 __update_load_avg_blocked_se(now, se); 5420 } 5421 #else /* !CONFIG_NO_HZ_COMMON: */ 5422 static void migrate_se_pelt_lag(struct sched_entity *se) {} 5423 #endif /* !CONFIG_NO_HZ_COMMON */ 5424 5425 /** 5426 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages 5427 * @now: current time, as per cfs_rq_clock_pelt() 5428 * @cfs_rq: cfs_rq to update 5429 * 5430 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable) 5431 * avg. The immediate corollary is that all (fair) tasks must be attached. 5432 * 5433 * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example. 5434 * 5435 * Return: true if the load decayed or we removed load. 5436 * 5437 * Since both these conditions indicate a changed cfs_rq->avg.load we should 5438 * call update_tg_load_avg() when this function returns true. 5439 */ 5440 static inline int 5441 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq) 5442 { 5443 unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0; 5444 struct sched_avg *sa = &cfs_rq->avg; 5445 int decayed = 0; 5446 5447 if (cfs_rq->removed.nr) { 5448 unsigned long r; 5449 u32 divider = get_pelt_divider(&cfs_rq->avg); 5450 5451 raw_spin_lock(&cfs_rq->removed.lock); 5452 swap(cfs_rq->removed.util_avg, removed_util); 5453 swap(cfs_rq->removed.load_avg, removed_load); 5454 swap(cfs_rq->removed.runnable_avg, removed_runnable); 5455 cfs_rq->removed.nr = 0; 5456 raw_spin_unlock(&cfs_rq->removed.lock); 5457 5458 r = removed_load; 5459 __update_sa(sa, load, -r, -r*divider); 5460 5461 r = removed_util; 5462 __update_sa(sa, util, -r, -r*divider); 5463 5464 r = removed_runnable; 5465 __update_sa(sa, runnable, -r, -r*divider); 5466 5467 /* 5468 * removed_runnable is the unweighted version of removed_load so we 5469 * can use it to estimate removed_load_sum. 5470 */ 5471 add_tg_cfs_propagate(cfs_rq, 5472 -(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT); 5473 5474 decayed = 1; 5475 } 5476 5477 decayed |= __update_load_avg_cfs_rq(now, cfs_rq); 5478 u64_u32_store_copy(sa->last_update_time, 5479 cfs_rq->last_update_time_copy, 5480 sa->last_update_time); 5481 return decayed; 5482 } 5483 5484 /** 5485 * attach_entity_load_avg - attach this entity to its cfs_rq load avg 5486 * @cfs_rq: cfs_rq to attach to 5487 * @se: sched_entity to attach 5488 * 5489 * Must call update_cfs_rq_load_avg() before this, since we rely on 5490 * cfs_rq->avg.last_update_time being current. 5491 */ 5492 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) 5493 { 5494 /* 5495 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se. 5496 * See ___update_load_avg() for details. 5497 */ 5498 u32 divider = get_pelt_divider(&cfs_rq->avg); 5499 5500 /* 5501 * When we attach the @se to the @cfs_rq, we must align the decay 5502 * window because without that, really weird and wonderful things can 5503 * happen. 5504 * 5505 * XXX illustrate 5506 */ 5507 se->avg.last_update_time = cfs_rq->avg.last_update_time; 5508 se->avg.period_contrib = cfs_rq->avg.period_contrib; 5509 5510 /* 5511 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new 5512 * period_contrib. This isn't strictly correct, but since we're 5513 * entirely outside of the PELT hierarchy, nobody cares if we truncate 5514 * _sum a little. 5515 */ 5516 se->avg.util_sum = se->avg.util_avg * divider; 5517 5518 se->avg.runnable_sum = se->avg.runnable_avg * divider; 5519 5520 se->avg.load_sum = se->avg.load_avg * divider; 5521 if (se_weight(se) < se->avg.load_sum) 5522 se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se)); 5523 else 5524 se->avg.load_sum = 1; 5525 5526 enqueue_load_avg(cfs_rq, se); 5527 cfs_rq->avg.util_avg += se->avg.util_avg; 5528 cfs_rq->avg.util_sum += se->avg.util_sum; 5529 cfs_rq->avg.runnable_avg += se->avg.runnable_avg; 5530 cfs_rq->avg.runnable_sum += se->avg.runnable_sum; 5531 5532 add_tg_cfs_propagate(cfs_rq, se->avg.load_sum); 5533 5534 cfs_rq_util_change(cfs_rq, 0); 5535 5536 trace_pelt_cfs_tp(cfs_rq); 5537 } 5538 5539 /** 5540 * detach_entity_load_avg - detach this entity from its cfs_rq load avg 5541 * @cfs_rq: cfs_rq to detach from 5542 * @se: sched_entity to detach 5543 * 5544 * Must call update_cfs_rq_load_avg() before this, since we rely on 5545 * cfs_rq->avg.last_update_time being current. 5546 */ 5547 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) 5548 { 5549 dequeue_load_avg(cfs_rq, se); 5550 __update_sa(&cfs_rq->avg, util, -se->avg.util_avg, -se->avg.util_sum); 5551 __update_sa(&cfs_rq->avg, runnable, -se->avg.runnable_avg, -se->avg.runnable_sum); 5552 5553 add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum); 5554 5555 cfs_rq_util_change(cfs_rq, 0); 5556 5557 trace_pelt_cfs_tp(cfs_rq); 5558 } 5559 5560 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100) 5561 5562 static inline void util_est_update(struct sched_entity *se) 5563 { 5564 unsigned int ewma, dequeued, last_ewma_diff; 5565 5566 if (!sched_feat(UTIL_EST)) 5567 return; 5568 5569 /* Get current estimate of utilization */ 5570 ewma = READ_ONCE(se->avg.util_est); 5571 5572 /* 5573 * If the PELT values haven't changed since enqueue time, 5574 * skip the util_est update. 5575 */ 5576 if (ewma & UTIL_AVG_UNCHANGED) 5577 return; 5578 5579 /* Get utilization at dequeue */ 5580 dequeued = READ_ONCE(se->avg.util_avg); 5581 5582 /* 5583 * Reset EWMA on utilization increases, the moving average is used only 5584 * to smooth utilization decreases. 5585 */ 5586 if (ewma <= dequeued) { 5587 ewma = dequeued; 5588 goto done; 5589 } 5590 5591 /* 5592 * Skip update of task's estimated utilization when its members are 5593 * already ~1% close to its last activation value. 5594 */ 5595 last_ewma_diff = ewma - dequeued; 5596 if (last_ewma_diff < UTIL_EST_MARGIN) 5597 goto done; 5598 5599 /* 5600 * To avoid underestimate of task utilization, skip updates of EWMA if 5601 * we cannot grant that thread got all CPU time it wanted. 5602 */ 5603 if ((dequeued + UTIL_EST_MARGIN) < READ_ONCE(se->avg.runnable_avg)) 5604 goto done; 5605 5606 /* 5607 * Update Task's estimated utilization 5608 * 5609 * When *p completes an activation we can consolidate another sample 5610 * of the task size. This is done by using this value to update the 5611 * Exponential Weighted Moving Average (EWMA): 5612 * 5613 * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1) 5614 * = w * task_util(p) + ewma(t-1) - w * ewma(t-1) 5615 * = w * (task_util(p) - ewma(t-1)) + ewma(t-1) 5616 * = w * ( -last_ewma_diff ) + ewma(t-1) 5617 * = w * (-last_ewma_diff + ewma(t-1) / w) 5618 * 5619 * Where 'w' is the weight of new samples, which is configured to be 5620 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT) 5621 */ 5622 ewma <<= UTIL_EST_WEIGHT_SHIFT; 5623 ewma -= last_ewma_diff; 5624 ewma >>= UTIL_EST_WEIGHT_SHIFT; 5625 done: 5626 ewma |= UTIL_AVG_UNCHANGED; 5627 WRITE_ONCE(se->avg.util_est, ewma); 5628 5629 trace_sched_util_est_se_tp(se); 5630 } 5631 5632 /* 5633 * Optional action to be done while updating the load average 5634 */ 5635 #define UPDATE_TG 0x01 5636 #define SKIP_AGE_LOAD 0x02 5637 #define DO_ATTACH 0x04 5638 #define DO_DETACH 0x08 5639 #define UPDATE_UTIL_EST 0x10 5640 5641 /* Update task and its cfs_rq load average */ 5642 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 5643 { 5644 u64 now = cfs_rq_clock_pelt(cfs_rq); 5645 int decayed; 5646 5647 /* 5648 * Track task load average for carrying it to new CPU after migrated, and 5649 * track group sched_entity load average for task_h_load calculation in migration 5650 */ 5651 if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD)) 5652 __update_load_avg_se(now, cfs_rq, se); 5653 5654 decayed = update_cfs_rq_load_avg(now, cfs_rq); 5655 decayed |= propagate_entity_load_avg(se); 5656 5657 if (!se->avg.last_update_time && (flags & DO_ATTACH)) { 5658 5659 /* 5660 * DO_ATTACH means we're here from enqueue_entity(). 5661 * !last_update_time means we've passed through 5662 * migrate_task_rq_fair() indicating we migrated. 5663 * 5664 * IOW we're enqueueing a task on a new CPU. 5665 */ 5666 attach_entity_load_avg(cfs_rq, se); 5667 update_tg_load_avg(cfs_rq); 5668 5669 } else if (flags & DO_DETACH) { 5670 /* 5671 * DO_DETACH means we're here from dequeue_entity() 5672 * and we are migrating task out of the CPU. 5673 */ 5674 detach_entity_load_avg(cfs_rq, se); 5675 update_tg_load_avg(cfs_rq); 5676 } else if (decayed) { 5677 cfs_rq_util_change(cfs_rq, 0); 5678 5679 if (flags & UPDATE_TG) 5680 update_tg_load_avg(cfs_rq); 5681 } 5682 5683 if (flags & UPDATE_UTIL_EST) 5684 util_est_update(se); 5685 } 5686 5687 /* 5688 * Synchronize entity load avg of dequeued entity without locking 5689 * the previous rq. 5690 */ 5691 static void sync_entity_load_avg(struct sched_entity *se) 5692 { 5693 struct cfs_rq *cfs_rq = cfs_rq_of(se); 5694 u64 last_update_time; 5695 5696 last_update_time = cfs_rq_last_update_time(cfs_rq); 5697 __update_load_avg_blocked_se(last_update_time, se); 5698 } 5699 5700 /* 5701 * Task first catches up with cfs_rq, and then subtract 5702 * itself from the cfs_rq (task must be off the queue now). 5703 */ 5704 static void remove_entity_load_avg(struct sched_entity *se) 5705 { 5706 struct cfs_rq *cfs_rq = cfs_rq_of(se); 5707 unsigned long flags; 5708 5709 /* 5710 * tasks cannot exit without having gone through wake_up_new_task() -> 5711 * enqueue_task_fair() which will have added things to the cfs_rq, 5712 * so we can remove unconditionally. 5713 */ 5714 5715 sync_entity_load_avg(se); 5716 5717 raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags); 5718 ++cfs_rq->removed.nr; 5719 cfs_rq->removed.util_avg += se->avg.util_avg; 5720 cfs_rq->removed.load_avg += se->avg.load_avg; 5721 cfs_rq->removed.runnable_avg += se->avg.runnable_avg; 5722 raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags); 5723 } 5724 5725 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq) 5726 { 5727 return cfs_rq->avg.runnable_avg; 5728 } 5729 5730 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq) 5731 { 5732 return cfs_rq->avg.load_avg; 5733 } 5734 5735 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf) 5736 __must_hold(__rq_lockp(this_rq)); 5737 5738 static inline unsigned long task_util(struct task_struct *p) 5739 { 5740 return READ_ONCE(p->se.avg.util_avg); 5741 } 5742 5743 static inline unsigned long _task_util_est(struct task_struct *p) 5744 { 5745 return READ_ONCE(p->se.avg.util_est) & ~UTIL_AVG_UNCHANGED; 5746 } 5747 5748 static inline unsigned long task_util_est(struct task_struct *p) 5749 { 5750 return max(task_util(p), _task_util_est(p)); 5751 } 5752 5753 static inline void util_est_enqueue(struct cfs_rq *cfs_rq, 5754 struct task_struct *p) 5755 { 5756 unsigned int enqueued; 5757 5758 if (!sched_feat(UTIL_EST)) 5759 return; 5760 5761 /* Update root cfs_rq's estimated utilization */ 5762 enqueued = cfs_rq->avg.util_est; 5763 enqueued += _task_util_est(p); 5764 WRITE_ONCE(cfs_rq->avg.util_est, enqueued); 5765 5766 trace_sched_util_est_cfs_tp(cfs_rq); 5767 } 5768 5769 static inline void util_est_dequeue(struct cfs_rq *cfs_rq, 5770 struct task_struct *p) 5771 { 5772 unsigned int enqueued; 5773 5774 if (!sched_feat(UTIL_EST)) 5775 return; 5776 5777 /* Update root cfs_rq's estimated utilization */ 5778 enqueued = cfs_rq->avg.util_est; 5779 enqueued -= min_t(unsigned int, enqueued, _task_util_est(p)); 5780 WRITE_ONCE(cfs_rq->avg.util_est, enqueued); 5781 5782 trace_sched_util_est_cfs_tp(cfs_rq); 5783 } 5784 5785 static inline unsigned long get_actual_cpu_capacity(int cpu) 5786 { 5787 unsigned long capacity = arch_scale_cpu_capacity(cpu); 5788 5789 capacity -= max(hw_load_avg(cpu_rq(cpu)), cpufreq_get_pressure(cpu)); 5790 5791 return capacity; 5792 } 5793 5794 static inline int util_fits_cpu(unsigned long util, 5795 unsigned long uclamp_min, 5796 unsigned long uclamp_max, 5797 int cpu) 5798 { 5799 unsigned long capacity = capacity_of(cpu); 5800 unsigned long capacity_orig; 5801 bool fits, uclamp_max_fits; 5802 5803 /* 5804 * Check if the real util fits without any uclamp boost/cap applied. 5805 */ 5806 fits = fits_capacity(util, capacity); 5807 5808 if (!uclamp_is_used()) 5809 return fits; 5810 5811 /* 5812 * We must use arch_scale_cpu_capacity() for comparing against uclamp_min and 5813 * uclamp_max. We only care about capacity pressure (by using 5814 * capacity_of()) for comparing against the real util. 5815 * 5816 * If a task is boosted to 1024 for example, we don't want a tiny 5817 * pressure to skew the check whether it fits a CPU or not. 5818 * 5819 * Similarly if a task is capped to arch_scale_cpu_capacity(little_cpu), it 5820 * should fit a little cpu even if there's some pressure. 5821 * 5822 * Only exception is for HW or cpufreq pressure since it has a direct impact 5823 * on available OPP of the system. 5824 * 5825 * We honour it for uclamp_min only as a drop in performance level 5826 * could result in not getting the requested minimum performance level. 5827 * 5828 * For uclamp_max, we can tolerate a drop in performance level as the 5829 * goal is to cap the task. So it's okay if it's getting less. 5830 */ 5831 capacity_orig = arch_scale_cpu_capacity(cpu); 5832 5833 /* 5834 * We want to force a task to fit a cpu as implied by uclamp_max. 5835 * But we do have some corner cases to cater for.. 5836 * 5837 * 5838 * C=z 5839 * | ___ 5840 * | C=y | | 5841 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max 5842 * | C=x | | | | 5843 * | ___ | | | | 5844 * | | | | | | | (util somewhere in this region) 5845 * | | | | | | | 5846 * | | | | | | | 5847 * +---------------------------------------- 5848 * CPU0 CPU1 CPU2 5849 * 5850 * In the above example if a task is capped to a specific performance 5851 * point, y, then when: 5852 * 5853 * * util = 80% of x then it does not fit on CPU0 and should migrate 5854 * to CPU1 5855 * * util = 80% of y then it is forced to fit on CPU1 to honour 5856 * uclamp_max request. 5857 * 5858 * which is what we're enforcing here. A task always fits if 5859 * uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig, 5860 * the normal upmigration rules should withhold still. 5861 * 5862 * Only exception is when we are on max capacity, then we need to be 5863 * careful not to block overutilized state. This is so because: 5864 * 5865 * 1. There's no concept of capping at max_capacity! We can't go 5866 * beyond this performance level anyway. 5867 * 2. The system is being saturated when we're operating near 5868 * max capacity, it doesn't make sense to block overutilized. 5869 */ 5870 uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE); 5871 uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig); 5872 fits = fits || uclamp_max_fits; 5873 5874 /* 5875 * 5876 * C=z 5877 * | ___ (region a, capped, util >= uclamp_max) 5878 * | C=y | | 5879 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max 5880 * | C=x | | | | 5881 * | ___ | | | | (region b, uclamp_min <= util <= uclamp_max) 5882 * |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min 5883 * | | | | | | | 5884 * | | | | | | | (region c, boosted, util < uclamp_min) 5885 * +---------------------------------------- 5886 * CPU0 CPU1 CPU2 5887 * 5888 * a) If util > uclamp_max, then we're capped, we don't care about 5889 * actual fitness value here. We only care if uclamp_max fits 5890 * capacity without taking margin/pressure into account. 5891 * See comment above. 5892 * 5893 * b) If uclamp_min <= util <= uclamp_max, then the normal 5894 * fits_capacity() rules apply. Except we need to ensure that we 5895 * enforce we remain within uclamp_max, see comment above. 5896 * 5897 * c) If util < uclamp_min, then we are boosted. Same as (b) but we 5898 * need to take into account the boosted value fits the CPU without 5899 * taking margin/pressure into account. 5900 * 5901 * Cases (a) and (b) are handled in the 'fits' variable already. We 5902 * just need to consider an extra check for case (c) after ensuring we 5903 * handle the case uclamp_min > uclamp_max. 5904 */ 5905 uclamp_min = min(uclamp_min, uclamp_max); 5906 if (fits && (util < uclamp_min) && 5907 (uclamp_min > get_actual_cpu_capacity(cpu))) 5908 return -1; 5909 5910 return fits; 5911 } 5912 5913 static inline int task_fits_cpu(struct task_struct *p, int cpu) 5914 { 5915 unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN); 5916 unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX); 5917 unsigned long util = task_util_est(p); 5918 /* 5919 * Return true only if the cpu fully fits the task requirements, which 5920 * include the utilization but also the performance hints. 5921 */ 5922 return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0); 5923 } 5924 5925 static inline void update_misfit_status(struct task_struct *p, struct rq *rq) 5926 { 5927 int cpu = cpu_of(rq); 5928 5929 if (!sched_asym_cpucap_active()) 5930 return; 5931 5932 /* 5933 * Affinity allows us to go somewhere higher? Or are we on biggest 5934 * available CPU already? Or do we fit into this CPU ? 5935 */ 5936 if (!p || (p->nr_cpus_allowed == 1) || 5937 (arch_scale_cpu_capacity(cpu) == p->max_allowed_capacity) || 5938 task_fits_cpu(p, cpu)) { 5939 5940 rq->misfit_task_load = 0; 5941 return; 5942 } 5943 5944 /* 5945 * Make sure that misfit_task_load will not be null even if 5946 * task_h_load() returns 0. 5947 */ 5948 rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1); 5949 } 5950 5951 void __setparam_fair(struct task_struct *p, const struct sched_attr *attr) 5952 { 5953 struct sched_entity *se = &p->se; 5954 5955 p->static_prio = NICE_TO_PRIO(attr->sched_nice); 5956 if (attr->sched_runtime) { 5957 se->custom_slice = 1; 5958 se->slice = clamp_t(u64, attr->sched_runtime, 5959 NSEC_PER_MSEC/10, /* HZ=1000 * 10 */ 5960 NSEC_PER_MSEC*100); /* HZ=100 / 10 */ 5961 } else { 5962 se->custom_slice = 0; 5963 se->slice = sysctl_sched_base_slice; 5964 } 5965 } 5966 5967 static void 5968 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 5969 { 5970 u64 vslice, vruntime = avg_vruntime(cfs_rq); 5971 bool update_zero = false; 5972 s64 lag = 0; 5973 5974 if (!se->custom_slice) 5975 se->slice = sysctl_sched_base_slice; 5976 vslice = calc_delta_fair(se->slice, se); 5977 5978 /* 5979 * Due to how V is constructed as the weighted average of entities, 5980 * adding tasks with positive lag, or removing tasks with negative lag 5981 * will move 'time' backwards, this can screw around with the lag of 5982 * other tasks. 5983 * 5984 * EEVDF: placement strategy #1 / #2 5985 */ 5986 if (sched_feat(PLACE_LAG) && cfs_rq->nr_queued && se->vlag) { 5987 struct sched_entity *curr = cfs_rq->curr; 5988 long load, weight; 5989 5990 lag = se->vlag; 5991 5992 /* 5993 * If we want to place a task and preserve lag, we have to 5994 * consider the effect of the new entity on the weighted 5995 * average and compensate for this, otherwise lag can quickly 5996 * evaporate. 5997 * 5998 * Lag is defined as: 5999 * 6000 * lag_i = S - s_i = w_i * (V - v_i) 6001 * 6002 * To avoid the 'w_i' term all over the place, we only track 6003 * the virtual lag: 6004 * 6005 * vl_i = V - v_i <=> v_i = V - vl_i 6006 * 6007 * And we take V to be the weighted average of all v: 6008 * 6009 * V = (\Sum w_j*v_j) / W 6010 * 6011 * Where W is: \Sum w_j 6012 * 6013 * Then, the weighted average after adding an entity with lag 6014 * vl_i is given by: 6015 * 6016 * V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i) 6017 * = (W*V + w_i*(V - vl_i)) / (W + w_i) 6018 * = (W*V + w_i*V - w_i*vl_i) / (W + w_i) 6019 * = (V*(W + w_i) - w_i*vl_i) / (W + w_i) 6020 * = V - w_i*vl_i / (W + w_i) 6021 * 6022 * And the actual lag after adding an entity with vl_i is: 6023 * 6024 * vl'_i = V' - v_i 6025 * = V - w_i*vl_i / (W + w_i) - (V - vl_i) 6026 * = vl_i - w_i*vl_i / (W + w_i) 6027 * 6028 * Which is strictly less than vl_i. So in order to preserve lag 6029 * we should inflate the lag before placement such that the 6030 * effective lag after placement comes out right. 6031 * 6032 * As such, invert the above relation for vl'_i to get the vl_i 6033 * we need to use such that the lag after placement is the lag 6034 * we computed before dequeue. 6035 * 6036 * vl'_i = vl_i - w_i*vl_i / (W + w_i) 6037 * = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i) 6038 * 6039 * (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i 6040 * = W*vl_i 6041 * 6042 * vl_i = (W + w_i)*vl'_i / W 6043 */ 6044 load = cfs_rq->sum_weight; 6045 if (curr && curr->on_rq) 6046 load += avg_vruntime_weight(cfs_rq, curr->load.weight); 6047 6048 weight = avg_vruntime_weight(cfs_rq, se->load.weight); 6049 lag *= load + weight; 6050 if (WARN_ON_ONCE(!load)) 6051 load = 1; 6052 lag = div64_long(lag, load); 6053 6054 /* 6055 * A heavy entity (relative to the tree) will pull the 6056 * avg_vruntime close to its vruntime position on enqueue. But 6057 * the zero_vruntime point is only updated at the next 6058 * update_deadline()/place_entity()/update_entity_lag(). 6059 * 6060 * Specifically (see the comment near avg_vruntime_weight()): 6061 * 6062 * sum_w_vruntime = \Sum (v_i - v0) * w_i 6063 * 6064 * Note that if v0 is near a light entity, both terms will be 6065 * small for the light entity, while in that case both terms 6066 * are large for the heavy entity, leading to risk of 6067 * overflow. 6068 * 6069 * OTOH if v0 is near the heavy entity, then the difference is 6070 * larger for the light entity, but the factor is small, while 6071 * for the heavy entity the difference is small but the factor 6072 * is large. Avoiding the multiplication overflow. 6073 */ 6074 if (weight > load) 6075 update_zero = true; 6076 } 6077 6078 se->vruntime = vruntime - lag; 6079 6080 if (update_zero) 6081 update_zero_vruntime(cfs_rq, -lag); 6082 6083 if (sched_feat(PLACE_REL_DEADLINE) && se->rel_deadline) { 6084 se->deadline += se->vruntime; 6085 se->rel_deadline = 0; 6086 return; 6087 } 6088 6089 /* 6090 * When joining the competition; the existing tasks will be, 6091 * on average, halfway through their slice, as such start tasks 6092 * off with half a slice to ease into the competition. 6093 */ 6094 if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL)) 6095 vslice /= 2; 6096 6097 /* 6098 * EEVDF: vd_i = ve_i + r_i/w_i 6099 */ 6100 se->deadline = se->vruntime + vslice; 6101 } 6102 6103 static void check_enqueue_throttle(struct cfs_rq *cfs_rq); 6104 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq); 6105 6106 static void 6107 requeue_delayed_entity(struct sched_entity *se); 6108 6109 static void 6110 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 6111 { 6112 bool curr = cfs_rq->curr == se; 6113 6114 /* 6115 * If we're the current task, we must renormalise before calling 6116 * update_curr(). 6117 */ 6118 if (curr) 6119 place_entity(cfs_rq, se, flags); 6120 6121 update_curr(cfs_rq); 6122 6123 /* 6124 * When enqueuing a sched_entity, we must: 6125 * - Update loads to have both entity and cfs_rq synced with now. 6126 * - For group_entity, update its runnable_weight to reflect the new 6127 * h_nr_runnable of its group cfs_rq. 6128 * - For group_entity, update its weight to reflect the new share of 6129 * its group cfs_rq 6130 * - Add its new weight to cfs_rq->load.weight 6131 */ 6132 update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH); 6133 se_update_runnable(se); 6134 /* 6135 * XXX update_load_avg() above will have attached us to the pelt sum; 6136 * but update_cfs_group() here will re-adjust the weight and have to 6137 * undo/redo all that. Seems wasteful. 6138 */ 6139 update_cfs_group(se); 6140 6141 /* 6142 * XXX now that the entity has been re-weighted, and it's lag adjusted, 6143 * we can place the entity. 6144 */ 6145 if (!curr) 6146 place_entity(cfs_rq, se, flags); 6147 6148 account_entity_enqueue(cfs_rq, se); 6149 6150 /* Entity has migrated, no longer consider this task hot */ 6151 if (flags & ENQUEUE_MIGRATED) 6152 se->exec_start = 0; 6153 6154 check_schedstat_required(); 6155 update_stats_enqueue_fair(cfs_rq, se, flags); 6156 if (!curr) 6157 __enqueue_entity(cfs_rq, se); 6158 se->on_rq = 1; 6159 6160 if (cfs_rq->nr_queued == 1) { 6161 check_enqueue_throttle(cfs_rq); 6162 list_add_leaf_cfs_rq(cfs_rq); 6163 #ifdef CONFIG_CFS_BANDWIDTH 6164 if (cfs_rq->pelt_clock_throttled) { 6165 struct rq *rq = rq_of(cfs_rq); 6166 6167 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) - 6168 cfs_rq->throttled_clock_pelt; 6169 cfs_rq->pelt_clock_throttled = 0; 6170 } 6171 #endif 6172 } 6173 } 6174 6175 static void __clear_buddies_next(struct sched_entity *se) 6176 { 6177 for_each_sched_entity(se) { 6178 struct cfs_rq *cfs_rq = cfs_rq_of(se); 6179 if (cfs_rq->next != se) 6180 break; 6181 6182 cfs_rq->next = NULL; 6183 } 6184 } 6185 6186 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se) 6187 { 6188 if (cfs_rq->next == se) 6189 __clear_buddies_next(se); 6190 } 6191 6192 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq); 6193 6194 static void set_delayed(struct sched_entity *se) 6195 { 6196 se->sched_delayed = 1; 6197 6198 /* 6199 * Delayed se of cfs_rq have no tasks queued on them. 6200 * Do not adjust h_nr_runnable since dequeue_entities() 6201 * will account it for blocked tasks. 6202 */ 6203 if (!entity_is_task(se)) 6204 return; 6205 6206 for_each_sched_entity(se) { 6207 struct cfs_rq *cfs_rq = cfs_rq_of(se); 6208 6209 cfs_rq->h_nr_runnable--; 6210 } 6211 } 6212 6213 static void clear_delayed(struct sched_entity *se) 6214 { 6215 se->sched_delayed = 0; 6216 6217 /* 6218 * Delayed se of cfs_rq have no tasks queued on them. 6219 * Do not adjust h_nr_runnable since a dequeue has 6220 * already accounted for it or an enqueue of a task 6221 * below it will account for it in enqueue_task_fair(). 6222 */ 6223 if (!entity_is_task(se)) 6224 return; 6225 6226 for_each_sched_entity(se) { 6227 struct cfs_rq *cfs_rq = cfs_rq_of(se); 6228 6229 cfs_rq->h_nr_runnable++; 6230 } 6231 } 6232 6233 static bool 6234 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 6235 { 6236 bool sleep = flags & DEQUEUE_SLEEP; 6237 int action = 0; 6238 6239 update_curr(cfs_rq); 6240 clear_buddies(cfs_rq, se); 6241 6242 if (flags & DEQUEUE_DELAYED) { 6243 WARN_ON_ONCE(!se->sched_delayed); 6244 } else { 6245 bool delay = sleep; 6246 /* 6247 * DELAY_DEQUEUE relies on spurious wakeups, special task 6248 * states must not suffer spurious wakeups, excempt them. 6249 */ 6250 if (flags & (DEQUEUE_SPECIAL | DEQUEUE_THROTTLE)) 6251 delay = false; 6252 6253 WARN_ON_ONCE(delay && se->sched_delayed); 6254 6255 if (sched_feat(DELAY_DEQUEUE) && delay && 6256 !entity_eligible(cfs_rq, se)) { 6257 if (entity_is_task(se)) 6258 action |= UPDATE_UTIL_EST; 6259 update_load_avg(cfs_rq, se, action); 6260 update_entity_lag(cfs_rq, se); 6261 set_delayed(se); 6262 return false; 6263 } 6264 } 6265 6266 action = UPDATE_TG; 6267 if (entity_is_task(se)) { 6268 if (task_on_rq_migrating(task_of(se))) 6269 action |= DO_DETACH; 6270 6271 if (sleep && !(flags & DEQUEUE_DELAYED)) 6272 action |= UPDATE_UTIL_EST; 6273 } 6274 6275 /* 6276 * When dequeuing a sched_entity, we must: 6277 * - Update loads to have both entity and cfs_rq synced with now. 6278 * - For group_entity, update its runnable_weight to reflect the new 6279 * h_nr_runnable of its group cfs_rq. 6280 * - Subtract its previous weight from cfs_rq->load.weight. 6281 * - For group entity, update its weight to reflect the new share 6282 * of its group cfs_rq. 6283 */ 6284 update_load_avg(cfs_rq, se, action); 6285 se_update_runnable(se); 6286 6287 update_stats_dequeue_fair(cfs_rq, se, flags); 6288 6289 update_entity_lag(cfs_rq, se); 6290 if (sched_feat(PLACE_REL_DEADLINE) && !sleep) { 6291 se->deadline -= se->vruntime; 6292 se->rel_deadline = 1; 6293 } 6294 6295 if (se != cfs_rq->curr) 6296 __dequeue_entity(cfs_rq, se); 6297 se->on_rq = 0; 6298 account_entity_dequeue(cfs_rq, se); 6299 6300 /* return excess runtime on last dequeue */ 6301 return_cfs_rq_runtime(cfs_rq); 6302 6303 update_cfs_group(se); 6304 6305 if (flags & DEQUEUE_DELAYED) 6306 clear_delayed(se); 6307 6308 if (cfs_rq->nr_queued == 0) { 6309 update_idle_cfs_rq_clock_pelt(cfs_rq); 6310 #ifdef CONFIG_CFS_BANDWIDTH 6311 if (throttled_hierarchy(cfs_rq)) { 6312 struct rq *rq = rq_of(cfs_rq); 6313 6314 list_del_leaf_cfs_rq(cfs_rq); 6315 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq); 6316 cfs_rq->pelt_clock_throttled = 1; 6317 } 6318 #endif 6319 } 6320 6321 return true; 6322 } 6323 6324 static void 6325 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, bool first) 6326 { 6327 clear_buddies(cfs_rq, se); 6328 6329 /* 'current' is not kept within the tree. */ 6330 if (se->on_rq) { 6331 /* 6332 * Any task has to be enqueued before it get to execute on 6333 * a CPU. So account for the time it spent waiting on the 6334 * runqueue. 6335 */ 6336 update_stats_wait_end_fair(cfs_rq, se); 6337 __dequeue_entity(cfs_rq, se); 6338 update_load_avg(cfs_rq, se, UPDATE_TG); 6339 6340 if (first) 6341 set_protect_slice(cfs_rq, se); 6342 } 6343 6344 update_stats_curr_start(cfs_rq, se); 6345 WARN_ON_ONCE(cfs_rq->curr); 6346 cfs_rq->curr = se; 6347 6348 /* 6349 * Track our maximum slice length, if the CPU's load is at 6350 * least twice that of our own weight (i.e. don't track it 6351 * when there are only lesser-weight tasks around): 6352 */ 6353 if (schedstat_enabled() && 6354 rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) { 6355 struct sched_statistics *stats; 6356 6357 stats = __schedstats_from_se(se); 6358 __schedstat_set(stats->slice_max, 6359 max((u64)stats->slice_max, 6360 se->sum_exec_runtime - se->prev_sum_exec_runtime)); 6361 } 6362 6363 se->prev_sum_exec_runtime = se->sum_exec_runtime; 6364 } 6365 6366 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags); 6367 6368 /* 6369 * Pick the next process, keeping these things in mind, in this order: 6370 * 1) keep things fair between processes/task groups 6371 * 2) pick the "next" process, since someone really wants that to run 6372 * 3) pick the "last" process, for cache locality 6373 * 4) do not run the "skip" process, if something else is available 6374 */ 6375 static struct sched_entity * 6376 pick_next_entity(struct rq *rq, struct cfs_rq *cfs_rq, bool protect) 6377 { 6378 struct sched_entity *se; 6379 6380 se = pick_eevdf(cfs_rq, protect); 6381 if (se->sched_delayed) { 6382 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED); 6383 /* 6384 * Must not reference @se again, see __block_task(). 6385 */ 6386 return NULL; 6387 } 6388 return se; 6389 } 6390 6391 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev) 6392 { 6393 /* 6394 * If still on the runqueue then deactivate_task() 6395 * was not called and update_curr() has to be done: 6396 */ 6397 if (prev->on_rq) 6398 update_curr(cfs_rq); 6399 6400 if (prev->on_rq) { 6401 update_stats_wait_start_fair(cfs_rq, prev); 6402 /* Put 'current' back into the tree. */ 6403 __enqueue_entity(cfs_rq, prev); 6404 /* in !on_rq case, update occurred at dequeue */ 6405 update_load_avg(cfs_rq, prev, 0); 6406 } 6407 WARN_ON_ONCE(cfs_rq->curr != prev); 6408 cfs_rq->curr = NULL; 6409 } 6410 6411 static void 6412 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued) 6413 { 6414 /* 6415 * Update run-time statistics of the 'current'. 6416 */ 6417 update_curr(cfs_rq); 6418 6419 /* 6420 * Ensure that runnable average is periodically updated. 6421 */ 6422 update_load_avg(cfs_rq, curr, UPDATE_TG); 6423 update_cfs_group(curr); 6424 6425 #ifdef CONFIG_SCHED_HRTICK 6426 /* 6427 * queued ticks are scheduled to match the slice, so don't bother 6428 * validating it and just reschedule. 6429 */ 6430 if (queued) { 6431 resched_curr(rq_of(cfs_rq)); 6432 return; 6433 } 6434 #endif 6435 } 6436 6437 6438 /************************************************** 6439 * CFS bandwidth control machinery 6440 */ 6441 6442 #ifdef CONFIG_CFS_BANDWIDTH 6443 6444 #ifdef CONFIG_JUMP_LABEL 6445 static struct static_key __cfs_bandwidth_used; 6446 6447 static inline bool cfs_bandwidth_used(void) 6448 { 6449 return static_key_false(&__cfs_bandwidth_used); 6450 } 6451 6452 void cfs_bandwidth_usage_inc(void) 6453 { 6454 static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used); 6455 } 6456 6457 void cfs_bandwidth_usage_dec(void) 6458 { 6459 static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used); 6460 } 6461 #else /* !CONFIG_JUMP_LABEL: */ 6462 static bool cfs_bandwidth_used(void) 6463 { 6464 return true; 6465 } 6466 6467 void cfs_bandwidth_usage_inc(void) {} 6468 void cfs_bandwidth_usage_dec(void) {} 6469 #endif /* !CONFIG_JUMP_LABEL */ 6470 6471 static inline u64 sched_cfs_bandwidth_slice(void) 6472 { 6473 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC; 6474 } 6475 6476 /* 6477 * Replenish runtime according to assigned quota. We use sched_clock_cpu 6478 * directly instead of rq->clock to avoid adding additional synchronization 6479 * around rq->lock. 6480 * 6481 * requires cfs_b->lock 6482 */ 6483 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b) 6484 { 6485 s64 runtime; 6486 6487 if (unlikely(cfs_b->quota == RUNTIME_INF)) 6488 return; 6489 6490 cfs_b->runtime += cfs_b->quota; 6491 runtime = cfs_b->runtime_snap - cfs_b->runtime; 6492 if (runtime > 0) { 6493 cfs_b->burst_time += runtime; 6494 cfs_b->nr_burst++; 6495 } 6496 6497 cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst); 6498 cfs_b->runtime_snap = cfs_b->runtime; 6499 } 6500 6501 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg) 6502 { 6503 return &tg->cfs_bandwidth; 6504 } 6505 6506 /* returns 0 on failure to allocate runtime */ 6507 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b, 6508 struct cfs_rq *cfs_rq, u64 target_runtime) 6509 { 6510 u64 min_amount, amount = 0; 6511 6512 lockdep_assert_held(&cfs_b->lock); 6513 6514 /* note: this is a positive sum as runtime_remaining <= 0 */ 6515 min_amount = target_runtime - cfs_rq->runtime_remaining; 6516 6517 if (cfs_b->quota == RUNTIME_INF) 6518 amount = min_amount; 6519 else { 6520 start_cfs_bandwidth(cfs_b); 6521 6522 if (cfs_b->runtime > 0) { 6523 amount = min(cfs_b->runtime, min_amount); 6524 cfs_b->runtime -= amount; 6525 cfs_b->idle = 0; 6526 } 6527 } 6528 6529 cfs_rq->runtime_remaining += amount; 6530 6531 return cfs_rq->runtime_remaining > 0; 6532 } 6533 6534 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq); 6535 6536 static bool __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) 6537 { 6538 /* dock delta_exec before expiring quota (as it could span periods) */ 6539 cfs_rq->runtime_remaining -= delta_exec; 6540 6541 if (likely(cfs_rq->runtime_remaining > 0)) 6542 return false; 6543 6544 if (cfs_rq->throttled) 6545 return true; 6546 /* 6547 * throttle_cfs_rq() will try to extend the runtime first 6548 * before throttling the hierarchy. 6549 */ 6550 return throttle_cfs_rq(cfs_rq); 6551 } 6552 6553 static __always_inline 6554 bool account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) 6555 { 6556 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled) 6557 return false; 6558 6559 return __account_cfs_rq_runtime(cfs_rq, delta_exec); 6560 } 6561 6562 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq) 6563 { 6564 return cfs_bandwidth_used() && cfs_rq->throttled; 6565 } 6566 6567 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq) 6568 { 6569 return cfs_bandwidth_used() && cfs_rq->pelt_clock_throttled; 6570 } 6571 6572 /* check whether cfs_rq, or any parent, is throttled */ 6573 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq) 6574 { 6575 return cfs_bandwidth_used() && cfs_rq->throttle_count; 6576 } 6577 6578 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu) 6579 { 6580 return throttled_hierarchy(tg_cfs_rq(task_group(p), dst_cpu)); 6581 } 6582 6583 static inline bool task_is_throttled(struct task_struct *p) 6584 { 6585 return cfs_bandwidth_used() && p->throttled; 6586 } 6587 6588 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags); 6589 static void throttle_cfs_rq_work(struct callback_head *work) 6590 { 6591 struct task_struct *p = container_of(work, struct task_struct, sched_throttle_work); 6592 struct sched_entity *se; 6593 struct cfs_rq *cfs_rq; 6594 struct rq *rq; 6595 6596 WARN_ON_ONCE(p != current); 6597 p->sched_throttle_work.next = &p->sched_throttle_work; 6598 6599 /* 6600 * If task is exiting, then there won't be a return to userspace, so we 6601 * don't have to bother with any of this. 6602 */ 6603 if ((p->flags & PF_EXITING)) 6604 return; 6605 6606 scoped_guard(task_rq_lock, p) { 6607 se = &p->se; 6608 cfs_rq = cfs_rq_of(se); 6609 6610 /* Raced, forget */ 6611 if (p->sched_class != &fair_sched_class) 6612 return; 6613 6614 /* 6615 * If not in limbo, then either replenish has happened or this 6616 * task got migrated out of the throttled cfs_rq, move along. 6617 */ 6618 if (!cfs_rq->throttle_count) 6619 return; 6620 rq = scope.rq; 6621 update_rq_clock(rq); 6622 WARN_ON_ONCE(p->throttled || !list_empty(&p->throttle_node)); 6623 dequeue_task_fair(rq, p, DEQUEUE_SLEEP | DEQUEUE_THROTTLE); 6624 list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list); 6625 /* 6626 * Must not set throttled before dequeue or dequeue will 6627 * mistakenly regard this task as an already throttled one. 6628 */ 6629 p->throttled = true; 6630 resched_curr(rq); 6631 } 6632 } 6633 6634 void init_cfs_throttle_work(struct task_struct *p) 6635 { 6636 init_task_work(&p->sched_throttle_work, throttle_cfs_rq_work); 6637 /* Protect against double add, see throttle_cfs_rq() and throttle_cfs_rq_work() */ 6638 p->sched_throttle_work.next = &p->sched_throttle_work; 6639 INIT_LIST_HEAD(&p->throttle_node); 6640 } 6641 6642 /* 6643 * Task is throttled and someone wants to dequeue it again: 6644 * it could be sched/core when core needs to do things like 6645 * task affinity change, task group change, task sched class 6646 * change etc. and in these cases, DEQUEUE_SLEEP is not set; 6647 * or the task is blocked after throttled due to freezer etc. 6648 * and in these cases, DEQUEUE_SLEEP is set. 6649 */ 6650 static void detach_task_cfs_rq(struct task_struct *p); 6651 static void dequeue_throttled_task(struct task_struct *p, int flags) 6652 { 6653 WARN_ON_ONCE(p->se.on_rq); 6654 list_del_init(&p->throttle_node); 6655 6656 /* task blocked after throttled */ 6657 if (flags & DEQUEUE_SLEEP) { 6658 p->throttled = false; 6659 return; 6660 } 6661 6662 /* 6663 * task is migrating off its old cfs_rq, detach 6664 * the task's load from its old cfs_rq. 6665 */ 6666 if (task_on_rq_migrating(p)) 6667 detach_task_cfs_rq(p); 6668 } 6669 6670 static bool enqueue_throttled_task(struct task_struct *p) 6671 { 6672 struct cfs_rq *cfs_rq = cfs_rq_of(&p->se); 6673 6674 /* @p should have gone through dequeue_throttled_task() first */ 6675 WARN_ON_ONCE(!list_empty(&p->throttle_node)); 6676 6677 /* 6678 * If the throttled task @p is enqueued to a throttled cfs_rq, 6679 * take the fast path by directly putting the task on the 6680 * target cfs_rq's limbo list. 6681 * 6682 * Do not do that when @p is current because the following race can 6683 * cause @p's group_node to be incorectly re-insterted in its rq's 6684 * cfs_tasks list, despite being throttled: 6685 * 6686 * cpuX cpuY 6687 * p ret2user 6688 * throttle_cfs_rq_work() sched_move_task(p) 6689 * LOCK task_rq_lock 6690 * dequeue_task_fair(p) 6691 * UNLOCK task_rq_lock 6692 * LOCK task_rq_lock 6693 * task_current_donor(p) == true 6694 * task_on_rq_queued(p) == true 6695 * dequeue_task(p) 6696 * put_prev_task(p) 6697 * sched_change_group() 6698 * enqueue_task(p) -> p's new cfs_rq 6699 * is throttled, go 6700 * fast path and skip 6701 * actual enqueue 6702 * set_next_task(p) 6703 * list_move(&se->group_node, &rq->cfs_tasks); // bug 6704 * schedule() 6705 * 6706 * In the above race case, @p current cfs_rq is in the same rq as 6707 * its previous cfs_rq because sched_move_task() only moves a task 6708 * to a different group from the same rq, so we can use its current 6709 * cfs_rq to derive rq and test if the task is current. 6710 */ 6711 if (throttled_hierarchy(cfs_rq) && 6712 !task_current_donor(rq_of(cfs_rq), p)) { 6713 list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list); 6714 return true; 6715 } 6716 6717 /* we can't take the fast path, do an actual enqueue*/ 6718 p->throttled = false; 6719 return false; 6720 } 6721 6722 static void enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags); 6723 static int tg_unthrottle_up(struct task_group *tg, void *data) 6724 { 6725 struct rq *rq = data; 6726 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq)); 6727 struct task_struct *p, *tmp; 6728 LIST_HEAD(throttled_tasks); 6729 6730 /* 6731 * If cfs_rq->curr is set, the cfs_rq might not have caught up 6732 * since the last clock update. Do it now before we begin 6733 * queueing task onto it to save the need for unnecessarily 6734 * unthrottle the hierarchy for this cfs_rq to be throttled 6735 * right back again. 6736 */ 6737 update_curr(cfs_rq); 6738 6739 if (--cfs_rq->throttle_count) 6740 return 0; 6741 6742 if (cfs_rq->pelt_clock_throttled) { 6743 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) - 6744 cfs_rq->throttled_clock_pelt; 6745 cfs_rq->pelt_clock_throttled = 0; 6746 } 6747 6748 if (cfs_rq->throttled_clock_self) { 6749 u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self; 6750 6751 cfs_rq->throttled_clock_self = 0; 6752 6753 if (WARN_ON_ONCE((s64)delta < 0)) 6754 delta = 0; 6755 6756 cfs_rq->throttled_clock_self_time += delta; 6757 } 6758 6759 /* 6760 * Move the tasks to a local list since an update_curr() during 6761 * enqueue_task_fair() can throttle a higher cfs_rq, and it can 6762 * see the "throttled_limbo_list" being non-empty in 6763 * tg_throttle_down() if throttle_count turned 0 above. 6764 */ 6765 list_splice_init(&cfs_rq->throttled_limbo_list, &throttled_tasks); 6766 6767 /* Re-enqueue the tasks that have been throttled at this level. */ 6768 list_for_each_entry_safe(p, tmp, &throttled_tasks, throttle_node) { 6769 /* 6770 * Back to being throttled! Break out and put the remaining 6771 * tasks back onto the limbo_list to prevent running them 6772 * unnecessarily. 6773 */ 6774 if (cfs_rq->throttle_count) 6775 break; 6776 6777 list_del_init(&p->throttle_node); 6778 p->throttled = false; 6779 enqueue_task_fair(rq, p, ENQUEUE_WAKEUP); 6780 } 6781 6782 list_splice(&throttled_tasks, &cfs_rq->throttled_limbo_list); 6783 6784 /* Add cfs_rq with load or one or more already running entities to the list */ 6785 if (!cfs_rq_is_decayed(cfs_rq)) 6786 list_add_leaf_cfs_rq(cfs_rq); 6787 6788 return 0; 6789 } 6790 6791 static inline bool task_has_throttle_work(struct task_struct *p) 6792 { 6793 return p->sched_throttle_work.next != &p->sched_throttle_work; 6794 } 6795 6796 static inline void task_throttle_setup_work(struct task_struct *p) 6797 { 6798 if (task_has_throttle_work(p)) 6799 return; 6800 6801 /* 6802 * Kthreads and exiting tasks don't return to userspace, so adding the 6803 * work is pointless 6804 */ 6805 if ((p->flags & (PF_EXITING | PF_KTHREAD))) 6806 return; 6807 6808 task_work_add(p, &p->sched_throttle_work, TWA_RESUME); 6809 } 6810 6811 static void record_throttle_clock(struct cfs_rq *cfs_rq) 6812 { 6813 struct rq *rq = rq_of(cfs_rq); 6814 6815 if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock) 6816 cfs_rq->throttled_clock = rq_clock(rq); 6817 6818 if (!cfs_rq->throttled_clock_self) 6819 cfs_rq->throttled_clock_self = rq_clock(rq); 6820 } 6821 6822 static int tg_throttle_down(struct task_group *tg, void *data) 6823 { 6824 struct rq *rq = data; 6825 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq)); 6826 6827 if (cfs_rq->throttle_count++) 6828 return 0; 6829 6830 /* 6831 * For cfs_rqs that still have entities enqueued, PELT clock 6832 * stop happens at dequeue time when all entities are dequeued. 6833 */ 6834 if (!cfs_rq->nr_queued) { 6835 list_del_leaf_cfs_rq(cfs_rq); 6836 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq); 6837 cfs_rq->pelt_clock_throttled = 1; 6838 } 6839 6840 WARN_ON_ONCE(cfs_rq->throttled_clock_self); 6841 WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_limbo_list)); 6842 return 0; 6843 } 6844 6845 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq) 6846 { 6847 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 6848 struct sched_entity *curr = cfs_rq->curr; 6849 struct rq *rq = rq_of(cfs_rq); 6850 6851 scoped_guard(raw_spinlock, &cfs_b->lock) { 6852 u64 target_runtime = 1; 6853 6854 /* 6855 * If cfs_rq->curr is still runnable, we are here from an 6856 * update_curr(). Request sysctl_sched_cfs_bandwidth_slice 6857 * worth of bandwidth to continue running. 6858 * 6859 * If the curr is not runnable, just request enough bandwidth 6860 * to be runnable next time the pick selects this cfs_rq. 6861 */ 6862 if (curr && curr->on_rq) 6863 target_runtime = sched_cfs_bandwidth_slice(); 6864 6865 /* 6866 * Check if We have raced with bandwidth becoming available. If 6867 * we actually throttled the timer might not unthrottle us for 6868 * an entire period. We additionally needed to make sure that 6869 * any subsequent check_cfs_rq_runtime calls agree not to 6870 * throttle us, as we may commit to do cfs put_prev+pick_next, 6871 * so we ask for 1ns of runtime rather than just check cfs_b. 6872 * 6873 * This will start the period timer if necessary. 6874 */ 6875 if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, target_runtime)) 6876 return false; 6877 6878 /* 6879 * No bandwidth available; Add ourselves on the list to be 6880 * unthrottled later. 6881 */ 6882 list_add_tail_rcu(&cfs_rq->throttled_list, 6883 &cfs_b->throttled_cfs_rq); 6884 } 6885 6886 /* freeze hierarchy runnable averages while throttled */ 6887 scoped_guard(rcu) 6888 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq); 6889 6890 /* 6891 * Note: distribution will already see us throttled via the 6892 * throttled-list. rq->lock protects completion. 6893 */ 6894 cfs_rq->throttled = 1; 6895 WARN_ON_ONCE(cfs_rq->throttled_clock); 6896 6897 /* 6898 * If current hierarchy was throttled, add throttle work to the 6899 * current donor. In case of proxy-execution, the execution 6900 * context cannot exit to the userspace while holding a mutex 6901 * and the rule of throttle deferral to only throttle the 6902 * throttled context at exit to userspace is still preserved. 6903 */ 6904 if (curr && curr->on_rq) 6905 task_throttle_setup_work(rq->donor); 6906 6907 return true; 6908 } 6909 6910 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq) 6911 { 6912 struct rq *rq = rq_of(cfs_rq); 6913 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 6914 struct sched_entity *se = cfs_rq_se(cfs_rq); 6915 6916 /* 6917 * It's possible we are called with runtime_remaining < 0 due to things 6918 * like async unthrottled us with a positive runtime_remaining but other 6919 * still running entities consumed those runtime before we reached here. 6920 * 6921 * We can't unthrottle this cfs_rq without any runtime remaining because 6922 * any enqueue in tg_unthrottle_up() will immediately trigger a throttle, 6923 * which is not supposed to happen on unthrottle path. 6924 * 6925 * Catch up on the remaining runtime since last clock update before 6926 * checking runtime remaining. 6927 */ 6928 update_curr(cfs_rq); 6929 if (cfs_rq->runtime_enabled && cfs_rq->runtime_remaining <= 0) 6930 return; 6931 6932 cfs_rq->throttled = 0; 6933 6934 scoped_guard(raw_spinlock, &cfs_b->lock) { 6935 list_del_rcu(&cfs_rq->throttled_list); 6936 6937 if (!cfs_rq->throttled_clock) 6938 break; 6939 6940 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock; 6941 cfs_rq->throttled_clock = 0; 6942 } 6943 6944 /* update hierarchical throttle state */ 6945 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq); 6946 6947 if (!cfs_rq->load.weight) { 6948 if (!cfs_rq->on_list) 6949 return; 6950 /* 6951 * Nothing to run but something to decay (on_list)? 6952 * Complete the branch. 6953 */ 6954 for_each_sched_entity(se) { 6955 if (list_add_leaf_cfs_rq(cfs_rq_of(se))) 6956 break; 6957 } 6958 } 6959 6960 assert_list_leaf_cfs_rq(rq); 6961 6962 /* Determine whether we need to wake up potentially idle CPU: */ 6963 if (rq->curr == rq->idle && rq->cfs.nr_queued) 6964 resched_curr(rq); 6965 } 6966 6967 static void __cfsb_csd_unthrottle(void *arg) 6968 { 6969 struct cfs_rq *cursor, *tmp; 6970 struct rq *rq = arg; 6971 6972 guard(rq_lock)(rq); 6973 6974 /* 6975 * Iterating over the list can trigger several call to 6976 * update_rq_clock() in unthrottle_cfs_rq(). 6977 * Do it once and skip the potential next ones. 6978 */ 6979 update_rq_clock(rq); 6980 rq_clock_start_loop_update(rq); 6981 6982 /* 6983 * Since we hold rq lock we're safe from concurrent manipulation of 6984 * the CSD list. However, this RCU critical section annotates the 6985 * fact that we pair with sched_free_group_rcu(), so that we cannot 6986 * race with group being freed in the window between removing it 6987 * from the list and advancing to the next entry in the list. 6988 */ 6989 guard(rcu)(); 6990 6991 list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list, 6992 throttled_csd_list) { 6993 list_del_init(&cursor->throttled_csd_list); 6994 6995 if (cfs_rq_throttled(cursor)) 6996 unthrottle_cfs_rq(cursor); 6997 } 6998 6999 rq_clock_stop_loop_update(rq); 7000 } 7001 7002 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq) 7003 { 7004 struct rq *rq = rq_of(cfs_rq); 7005 bool first; 7006 7007 if (rq == this_rq()) { 7008 update_rq_clock(rq); 7009 unthrottle_cfs_rq(cfs_rq); 7010 return; 7011 } 7012 7013 /* Already enqueued */ 7014 if (WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_csd_list))) 7015 return; 7016 7017 first = list_empty(&rq->cfsb_csd_list); 7018 list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list); 7019 if (first) 7020 smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd); 7021 } 7022 7023 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq) 7024 { 7025 lockdep_assert_rq_held(rq_of(cfs_rq)); 7026 7027 if (WARN_ON_ONCE(!cfs_rq_throttled(cfs_rq) || 7028 cfs_rq->runtime_remaining <= 0)) 7029 return; 7030 7031 __unthrottle_cfs_rq_async(cfs_rq); 7032 } 7033 7034 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b) 7035 { 7036 bool throttled = false, unthrottle_local = false; 7037 int this_cpu = smp_processor_id(); 7038 u64 runtime, remaining = 1; 7039 struct cfs_rq *cfs_rq; 7040 struct rq *rq; 7041 7042 guard(rcu)(); 7043 7044 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq, 7045 throttled_list) { 7046 rq = rq_of(cfs_rq); 7047 7048 if (!remaining) { 7049 throttled = true; 7050 break; 7051 } 7052 7053 guard(rq_lock_irqsave)(rq); 7054 7055 if (!cfs_rq_throttled(cfs_rq)) 7056 continue; 7057 7058 /* Already queued for async unthrottle */ 7059 if (!list_empty(&cfs_rq->throttled_csd_list)) 7060 continue; 7061 7062 if (cfs_rq->curr) { 7063 update_rq_clock(rq); 7064 update_curr(cfs_rq); 7065 } 7066 7067 /* By the above checks, this should never be true */ 7068 WARN_ON_ONCE(cfs_rq->runtime_remaining > 0); 7069 7070 scoped_guard(raw_spinlock, &cfs_b->lock) { 7071 runtime = -cfs_rq->runtime_remaining + 1; 7072 if (runtime > cfs_b->runtime) 7073 runtime = cfs_b->runtime; 7074 cfs_b->runtime -= runtime; 7075 remaining = cfs_b->runtime; 7076 } 7077 7078 cfs_rq->runtime_remaining += runtime; 7079 7080 /* 7081 * Ran out of bandwidth during distribution! 7082 * Indicate throttled entities and break early. 7083 */ 7084 if (cfs_rq->runtime_remaining <= 0) { 7085 throttled = true; 7086 break; 7087 } 7088 7089 /* we check whether we're throttled above */ 7090 if (cpu_of(rq) != this_cpu) { 7091 unthrottle_cfs_rq_async(cfs_rq); 7092 continue; 7093 } 7094 7095 /* 7096 * Allow a parallel async unthrottle to unthrottle 7097 * this cfs_rq too via __cfsb_csd_unthrottle(). 7098 * If we are first, do it ourselves at the end and 7099 * save on an IPI from remote CPUs. 7100 */ 7101 unthrottle_local = list_empty(&rq->cfsb_csd_list); 7102 list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list); 7103 } 7104 7105 if (unthrottle_local) { 7106 /* 7107 * Protect against an IPI that is also trying to flush 7108 * the unthrottled cfs_rq(s) from this CPU's csd_list. 7109 */ 7110 scoped_guard(irqsave) 7111 __cfsb_csd_unthrottle(cpu_rq(this_cpu)); 7112 } 7113 7114 return throttled; 7115 } 7116 7117 /* 7118 * Responsible for refilling a task_group's bandwidth and unthrottling its 7119 * cfs_rqs as appropriate. If there has been no activity within the last 7120 * period the timer is deactivated until scheduling resumes; cfs_b->idle is 7121 * used to track this state. 7122 */ 7123 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags) 7124 __must_hold(&cfs_b->lock) 7125 { 7126 int throttled; 7127 7128 /* no need to continue the timer with no bandwidth constraint */ 7129 if (cfs_b->quota == RUNTIME_INF) 7130 goto out_deactivate; 7131 7132 throttled = !list_empty(&cfs_b->throttled_cfs_rq); 7133 cfs_b->nr_periods += overrun; 7134 7135 /* Refill extra burst quota even if cfs_b->idle */ 7136 __refill_cfs_bandwidth_runtime(cfs_b); 7137 7138 /* 7139 * idle depends on !throttled (for the case of a large deficit), and if 7140 * we're going inactive then everything else can be deferred 7141 */ 7142 if (cfs_b->idle && !throttled) 7143 goto out_deactivate; 7144 7145 if (!throttled) { 7146 /* mark as potentially idle for the upcoming period */ 7147 cfs_b->idle = 1; 7148 return 0; 7149 } 7150 7151 /* account preceding periods in which throttling occurred */ 7152 cfs_b->nr_throttled += overrun; 7153 7154 /* 7155 * This check is repeated as we release cfs_b->lock while we unthrottle. 7156 */ 7157 while (throttled && cfs_b->runtime > 0) { 7158 raw_spin_unlock_irqrestore(&cfs_b->lock, flags); 7159 /* we can't nest cfs_b->lock while distributing bandwidth */ 7160 throttled = distribute_cfs_runtime(cfs_b); 7161 raw_spin_lock_irqsave(&cfs_b->lock, flags); 7162 } 7163 7164 /* 7165 * While we are ensured activity in the period following an 7166 * unthrottle, this also covers the case in which the new bandwidth is 7167 * insufficient to cover the existing bandwidth deficit. (Forcing the 7168 * timer to remain active while there are any throttled entities.) 7169 */ 7170 cfs_b->idle = 0; 7171 7172 return 0; 7173 7174 out_deactivate: 7175 return 1; 7176 } 7177 7178 /* a cfs_rq won't donate quota below this amount */ 7179 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC; 7180 /* minimum remaining period time to redistribute slack quota */ 7181 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC; 7182 /* how long we wait to gather additional slack before distributing */ 7183 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC; 7184 7185 /* 7186 * Are we near the end of the current quota period? 7187 * 7188 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the 7189 * hrtimer base being cleared by hrtimer_start. In the case of 7190 * migrate_hrtimers, base is never cleared, so we are fine. 7191 */ 7192 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire) 7193 { 7194 struct hrtimer *refresh_timer = &cfs_b->period_timer; 7195 s64 remaining; 7196 7197 /* if the call-back is running a quota refresh is already occurring */ 7198 if (hrtimer_callback_running(refresh_timer)) 7199 return 1; 7200 7201 /* is a quota refresh about to occur? */ 7202 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer)); 7203 if (remaining < (s64)min_expire) 7204 return 1; 7205 7206 return 0; 7207 } 7208 7209 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b) 7210 { 7211 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration; 7212 7213 /* if there's a quota refresh soon don't bother with slack */ 7214 if (runtime_refresh_within(cfs_b, min_left)) 7215 return; 7216 7217 /* don't push forwards an existing deferred unthrottle */ 7218 if (cfs_b->slack_started) 7219 return; 7220 cfs_b->slack_started = true; 7221 7222 hrtimer_start(&cfs_b->slack_timer, 7223 ns_to_ktime(cfs_bandwidth_slack_period), 7224 HRTIMER_MODE_REL); 7225 } 7226 7227 /* we know any runtime found here is valid as update_curr() precedes return */ 7228 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq) 7229 { 7230 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 7231 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime; 7232 7233 if (slack_runtime <= 0) 7234 return; 7235 7236 guard(raw_spinlock)(&cfs_b->lock); 7237 7238 if (cfs_b->quota != RUNTIME_INF) { 7239 cfs_b->runtime += slack_runtime; 7240 7241 /* we are under rq->lock, defer unthrottling using a timer */ 7242 if (cfs_b->runtime > sched_cfs_bandwidth_slice() && 7243 !list_empty(&cfs_b->throttled_cfs_rq)) 7244 start_cfs_slack_bandwidth(cfs_b); 7245 } 7246 7247 /* even if it's not valid for return we don't want to try again */ 7248 cfs_rq->runtime_remaining -= slack_runtime; 7249 } 7250 7251 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) 7252 { 7253 if (!cfs_bandwidth_used()) 7254 return; 7255 7256 if (!cfs_rq->runtime_enabled || cfs_rq->nr_queued) 7257 return; 7258 7259 __return_cfs_rq_runtime(cfs_rq); 7260 } 7261 7262 /* 7263 * This is done with a timer (instead of inline with bandwidth return) since 7264 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs. 7265 */ 7266 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b) 7267 { 7268 /* confirm we're still not at a refresh boundary */ 7269 scoped_guard(raw_spinlock_irqsave, &cfs_b->lock) { 7270 u64 runtime = 0, slice = sched_cfs_bandwidth_slice(); 7271 7272 cfs_b->slack_started = false; 7273 7274 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) 7275 return; 7276 7277 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice) 7278 runtime = cfs_b->runtime; 7279 7280 if (!runtime) 7281 return; 7282 } 7283 7284 distribute_cfs_runtime(cfs_b); 7285 } 7286 7287 /* 7288 * When a group wakes up we want to make sure that its quota is not already 7289 * expired/exceeded, otherwise it may be allowed to steal additional ticks of 7290 * runtime as update_curr() throttling can not trigger until it's on-rq. 7291 */ 7292 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) 7293 { 7294 if (!cfs_bandwidth_used()) 7295 return; 7296 7297 /* an active group must be handled by the update_curr() path */ 7298 if (!cfs_rq->runtime_enabled || cfs_rq->curr) 7299 return; 7300 7301 /* ensure the group is not already throttled */ 7302 if (cfs_rq_throttled(cfs_rq)) 7303 return; 7304 7305 /* update runtime allocation */ 7306 account_cfs_rq_runtime(cfs_rq, 0); 7307 } 7308 7309 static void sync_throttle(struct task_group *tg, int cpu) 7310 { 7311 struct cfs_rq *pcfs_rq, *cfs_rq; 7312 7313 if (!cfs_bandwidth_used()) 7314 return; 7315 7316 if (!tg->parent) 7317 return; 7318 7319 cfs_rq = tg_cfs_rq(tg, cpu); 7320 pcfs_rq = tg_cfs_rq(tg->parent, cpu); 7321 7322 cfs_rq->throttle_count = pcfs_rq->throttle_count; 7323 cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu)); 7324 7325 /* 7326 * It is not enough to sync the "pelt_clock_throttled" indicator 7327 * with the parent cfs_rq when the hierarchy is not queued. 7328 * Always join a throttled hierarchy with PELT clock throttled 7329 * and leaf it to the first enqueue, or distribution to 7330 * unthrottle the PELT clock. 7331 */ 7332 if (cfs_rq->throttle_count) 7333 cfs_rq->pelt_clock_throttled = 1; 7334 } 7335 7336 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer) 7337 { 7338 struct cfs_bandwidth *cfs_b = 7339 container_of(timer, struct cfs_bandwidth, slack_timer); 7340 7341 do_sched_cfs_slack_timer(cfs_b); 7342 7343 return HRTIMER_NORESTART; 7344 } 7345 7346 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer) 7347 { 7348 struct cfs_bandwidth *cfs_b = 7349 container_of(timer, struct cfs_bandwidth, period_timer); 7350 int overrun; 7351 int idle = 0; 7352 int count = 0; 7353 7354 CLASS(raw_spinlock_irqsave, cfsb_guard)(&cfs_b->lock); 7355 7356 for (;;) { 7357 overrun = hrtimer_forward_now(timer, cfs_b->period); 7358 if (!overrun) 7359 break; 7360 7361 idle = do_sched_cfs_period_timer(cfs_b, overrun, cfsb_guard.flags); 7362 7363 if (++count > 3) { 7364 u64 new, old = ktime_to_ns(cfs_b->period); 7365 7366 /* 7367 * Grow period by a factor of 2 to avoid losing precision. 7368 * Precision loss in the quota/period ratio can cause __cfs_schedulable 7369 * to fail. 7370 */ 7371 new = old * 2; 7372 if (new < max_bw_quota_period_us * NSEC_PER_USEC) { 7373 cfs_b->period = ns_to_ktime(new); 7374 cfs_b->quota *= 2; 7375 cfs_b->burst *= 2; 7376 7377 pr_warn_ratelimited( 7378 "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n", 7379 smp_processor_id(), 7380 div_u64(new, NSEC_PER_USEC), 7381 div_u64(cfs_b->quota, NSEC_PER_USEC)); 7382 } else { 7383 pr_warn_ratelimited( 7384 "cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n", 7385 smp_processor_id(), 7386 div_u64(old, NSEC_PER_USEC), 7387 div_u64(cfs_b->quota, NSEC_PER_USEC)); 7388 } 7389 7390 /* reset count so we don't come right back in here */ 7391 count = 0; 7392 } 7393 } 7394 7395 if (idle) { 7396 cfs_b->period_active = 0; 7397 return HRTIMER_NORESTART; 7398 } 7399 7400 return HRTIMER_RESTART; 7401 } 7402 7403 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) 7404 { 7405 raw_spin_lock_init(&cfs_b->lock); 7406 cfs_b->runtime = 0; 7407 cfs_b->quota = RUNTIME_INF; 7408 cfs_b->period = us_to_ktime(default_bw_period_us()); 7409 cfs_b->burst = 0; 7410 cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF; 7411 7412 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq); 7413 hrtimer_setup(&cfs_b->period_timer, sched_cfs_period_timer, CLOCK_MONOTONIC, 7414 HRTIMER_MODE_ABS_PINNED); 7415 7416 /* Add a random offset so that timers interleave */ 7417 hrtimer_set_expires(&cfs_b->period_timer, 7418 get_random_u32_below(cfs_b->period)); 7419 hrtimer_setup(&cfs_b->slack_timer, sched_cfs_slack_timer, CLOCK_MONOTONIC, 7420 HRTIMER_MODE_REL); 7421 cfs_b->slack_started = false; 7422 } 7423 7424 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) 7425 { 7426 cfs_rq->runtime_enabled = 0; 7427 INIT_LIST_HEAD(&cfs_rq->throttled_list); 7428 INIT_LIST_HEAD(&cfs_rq->throttled_csd_list); 7429 INIT_LIST_HEAD(&cfs_rq->throttled_limbo_list); 7430 } 7431 7432 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b) 7433 { 7434 lockdep_assert_held(&cfs_b->lock); 7435 7436 if (cfs_b->period_active) 7437 return; 7438 7439 cfs_b->period_active = 1; 7440 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period); 7441 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED); 7442 } 7443 7444 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) 7445 { 7446 int __maybe_unused i; 7447 7448 /* init_cfs_bandwidth() was not called */ 7449 if (!cfs_b->throttled_cfs_rq.next) 7450 return; 7451 7452 hrtimer_cancel(&cfs_b->period_timer); 7453 hrtimer_cancel(&cfs_b->slack_timer); 7454 7455 /* 7456 * It is possible that we still have some cfs_rq's pending on a CSD 7457 * list, though this race is very rare. In order for this to occur, we 7458 * must have raced with the last task leaving the group while there 7459 * exist throttled cfs_rq(s), and the period_timer must have queued the 7460 * CSD item but the remote cpu has not yet processed it. To handle this, 7461 * we can simply flush all pending CSD work inline here. We're 7462 * guaranteed at this point that no additional cfs_rq of this group can 7463 * join a CSD list. 7464 */ 7465 for_each_possible_cpu(i) { 7466 struct rq *rq = cpu_rq(i); 7467 7468 if (list_empty(&rq->cfsb_csd_list)) 7469 continue; 7470 7471 scoped_guard(irqsave) 7472 __cfsb_csd_unthrottle(rq); 7473 } 7474 } 7475 7476 /* 7477 * Both these CPU hotplug callbacks race against unregister_fair_sched_group() 7478 * 7479 * The race is harmless, since modifying bandwidth settings of unhooked group 7480 * bits doesn't do much. 7481 */ 7482 7483 /* cpu online callback */ 7484 static void __maybe_unused update_runtime_enabled(struct rq *rq) 7485 { 7486 struct task_group *tg; 7487 7488 lockdep_assert_rq_held(rq); 7489 7490 guard(rcu)(); 7491 7492 list_for_each_entry_rcu(tg, &task_groups, list) { 7493 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; 7494 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq)); 7495 7496 scoped_guard(raw_spinlock, &cfs_b->lock) 7497 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF; 7498 } 7499 } 7500 7501 /* cpu offline callback */ 7502 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq) 7503 { 7504 struct task_group *tg; 7505 7506 lockdep_assert_rq_held(rq); 7507 7508 // Do not unthrottle for an active CPU 7509 if (cpumask_test_cpu(cpu_of(rq), cpu_active_mask)) 7510 return; 7511 7512 /* 7513 * The rq clock has already been updated in the 7514 * set_rq_offline(), so we should skip updating 7515 * the rq clock again in unthrottle_cfs_rq(). 7516 */ 7517 rq_clock_start_loop_update(rq); 7518 7519 guard(rcu)(); 7520 7521 list_for_each_entry_rcu(tg, &task_groups, list) { 7522 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu_of(rq)); 7523 7524 if (!cfs_rq->runtime_enabled) 7525 continue; 7526 7527 /* 7528 * Offline rq is schedulable till CPU is completely disabled 7529 * in take_cpu_down(), so we prevent new cfs throttling here. 7530 */ 7531 cfs_rq->runtime_enabled = 0; 7532 7533 if (!cfs_rq_throttled(cfs_rq)) 7534 continue; 7535 7536 /* 7537 * clock_task is not advancing so we just need to make sure 7538 * there's some valid quota amount 7539 */ 7540 cfs_rq->runtime_remaining = 1; 7541 unthrottle_cfs_rq(cfs_rq); 7542 } 7543 7544 rq_clock_stop_loop_update(rq); 7545 } 7546 7547 bool cfs_task_bw_constrained(struct task_struct *p) 7548 { 7549 struct cfs_rq *cfs_rq = task_cfs_rq(p); 7550 7551 if (!cfs_bandwidth_used()) 7552 return false; 7553 7554 if (cfs_rq->runtime_enabled || 7555 tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF) 7556 return true; 7557 7558 return false; 7559 } 7560 7561 #ifdef CONFIG_NO_HZ_FULL 7562 /* called from pick_next_task_fair() */ 7563 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) 7564 { 7565 int cpu = cpu_of(rq); 7566 7567 if (!cfs_bandwidth_used()) 7568 return; 7569 7570 if (!tick_nohz_full_cpu(cpu)) 7571 return; 7572 7573 if (rq->nr_running != 1) 7574 return; 7575 7576 /* 7577 * We know there is only one task runnable and we've just picked it. The 7578 * normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will 7579 * be otherwise able to stop the tick. Just need to check if we are using 7580 * bandwidth control. 7581 */ 7582 if (cfs_task_bw_constrained(p)) 7583 tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED); 7584 } 7585 #endif /* CONFIG_NO_HZ_FULL */ 7586 7587 #else /* !CONFIG_CFS_BANDWIDTH: */ 7588 7589 static bool account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) { return false; } 7590 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {} 7591 static inline void sync_throttle(struct task_group *tg, int cpu) {} 7592 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {} 7593 static void task_throttle_setup_work(struct task_struct *p) {} 7594 static bool task_is_throttled(struct task_struct *p) { return false; } 7595 static void dequeue_throttled_task(struct task_struct *p, int flags) {} 7596 static bool enqueue_throttled_task(struct task_struct *p) { return false; } 7597 static void record_throttle_clock(struct cfs_rq *cfs_rq) {} 7598 7599 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq) 7600 { 7601 return 0; 7602 } 7603 7604 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq) 7605 { 7606 return false; 7607 } 7608 7609 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq) 7610 { 7611 return 0; 7612 } 7613 7614 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu) 7615 { 7616 return 0; 7617 } 7618 7619 #ifdef CONFIG_FAIR_GROUP_SCHED 7620 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {} 7621 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {} 7622 #endif 7623 7624 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg) 7625 { 7626 return NULL; 7627 } 7628 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {} 7629 static inline void update_runtime_enabled(struct rq *rq) {} 7630 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {} 7631 #ifdef CONFIG_CGROUP_SCHED 7632 bool cfs_task_bw_constrained(struct task_struct *p) 7633 { 7634 return false; 7635 } 7636 #endif 7637 #endif /* !CONFIG_CFS_BANDWIDTH */ 7638 7639 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL) 7640 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {} 7641 #endif 7642 7643 /************************************************** 7644 * CFS operations on tasks: 7645 */ 7646 7647 #ifdef CONFIG_SCHED_HRTICK 7648 static void hrtick_start_fair(struct rq *rq, struct task_struct *p) 7649 { 7650 struct sched_entity *se = &p->se; 7651 unsigned long scale = 1024; 7652 unsigned long util = 0; 7653 u64 vdelta; 7654 u64 delta; 7655 7656 WARN_ON_ONCE(task_rq(p) != rq); 7657 7658 if (rq->cfs.h_nr_queued <= 1) 7659 return; 7660 7661 /* 7662 * Compute time until virtual deadline 7663 */ 7664 vdelta = se->deadline - se->vruntime; 7665 if ((s64)vdelta < 0) { 7666 if (task_current_donor(rq, p)) 7667 resched_curr(rq); 7668 return; 7669 } 7670 delta = (se->load.weight * vdelta) / NICE_0_LOAD; 7671 7672 /* 7673 * Correct for instantaneous load of other classes. 7674 */ 7675 util += cpu_util_irq(rq); 7676 if (util && util < 1024) { 7677 scale *= 1024; 7678 scale /= (1024 - util); 7679 } 7680 7681 hrtick_start(rq, (scale * delta) / 1024); 7682 } 7683 7684 /* 7685 * Called on enqueue to start the hrtick when h_nr_queued becomes more than 1. 7686 */ 7687 static void hrtick_update(struct rq *rq) 7688 { 7689 struct task_struct *donor = rq->donor; 7690 7691 if (!hrtick_enabled_fair(rq) || donor->sched_class != &fair_sched_class) 7692 return; 7693 7694 if (hrtick_active(rq)) 7695 return; 7696 7697 hrtick_start_fair(rq, donor); 7698 } 7699 #else /* !CONFIG_SCHED_HRTICK: */ 7700 static inline void 7701 hrtick_start_fair(struct rq *rq, struct task_struct *p) 7702 { 7703 } 7704 7705 static inline void hrtick_update(struct rq *rq) 7706 { 7707 } 7708 #endif /* !CONFIG_SCHED_HRTICK */ 7709 7710 static inline bool cpu_overutilized(int cpu) 7711 { 7712 unsigned long rq_util_max; 7713 7714 if (!sched_energy_enabled()) 7715 return false; 7716 7717 rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX); 7718 7719 /* Return true only if the utilization doesn't fit CPU's capacity */ 7720 return !util_fits_cpu(cpu_util_cfs(cpu), 0, rq_util_max, cpu); 7721 } 7722 7723 /* 7724 * overutilized value make sense only if EAS is enabled 7725 */ 7726 static inline bool is_rd_overutilized(struct root_domain *rd) 7727 { 7728 return !sched_energy_enabled() || READ_ONCE(rd->overutilized); 7729 } 7730 7731 static inline void set_rd_overutilized(struct root_domain *rd, bool flag) 7732 { 7733 if (!sched_energy_enabled()) 7734 return; 7735 7736 WRITE_ONCE(rd->overutilized, flag); 7737 trace_sched_overutilized_tp(rd, flag); 7738 } 7739 7740 static inline void check_update_overutilized_status(struct rq *rq) 7741 { 7742 /* 7743 * overutilized field is used for load balancing decisions only 7744 * if energy aware scheduler is being used 7745 */ 7746 7747 if (!is_rd_overutilized(rq->rd) && cpu_overutilized(rq->cpu)) 7748 set_rd_overutilized(rq->rd, 1); 7749 } 7750 7751 /* Runqueue only has SCHED_IDLE tasks enqueued */ 7752 static int sched_idle_rq(struct rq *rq) 7753 { 7754 return unlikely(rq->nr_running == rq->cfs.h_nr_idle && 7755 rq->nr_running); 7756 } 7757 7758 static int choose_sched_idle_rq(struct rq *rq, struct task_struct *p) 7759 { 7760 return sched_idle_rq(rq) && !task_has_idle_policy(p); 7761 } 7762 7763 static int choose_idle_cpu(int cpu, struct task_struct *p) 7764 { 7765 return available_idle_cpu(cpu) || 7766 choose_sched_idle_rq(cpu_rq(cpu), p); 7767 } 7768 7769 static void 7770 requeue_delayed_entity(struct sched_entity *se) 7771 { 7772 struct cfs_rq *cfs_rq = cfs_rq_of(se); 7773 7774 /* 7775 * se->sched_delayed should imply: se->on_rq == 1. 7776 * Because a delayed entity is one that is still on 7777 * the runqueue competing until elegibility. 7778 */ 7779 WARN_ON_ONCE(!se->sched_delayed); 7780 WARN_ON_ONCE(!se->on_rq); 7781 7782 if (update_entity_lag(cfs_rq, se)) { 7783 cfs_rq->nr_queued--; 7784 if (se != cfs_rq->curr) 7785 __dequeue_entity(cfs_rq, se); 7786 place_entity(cfs_rq, se, 0); 7787 if (se != cfs_rq->curr) 7788 __enqueue_entity(cfs_rq, se); 7789 cfs_rq->nr_queued++; 7790 } 7791 7792 update_load_avg(cfs_rq, se, 0); 7793 clear_delayed(se); 7794 } 7795 7796 /* 7797 * The enqueue_task method is called before nr_running is 7798 * increased. Here we update the fair scheduling stats and 7799 * then put the task into the rbtree: 7800 */ 7801 static void 7802 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags) 7803 { 7804 struct cfs_rq *cfs_rq; 7805 struct sched_entity *se = &p->se; 7806 int h_nr_idle = task_has_idle_policy(p); 7807 int h_nr_runnable = 1; 7808 int task_new = !(flags & ENQUEUE_WAKEUP); 7809 int rq_h_nr_queued = rq->cfs.h_nr_queued; 7810 u64 slice = 0; 7811 7812 if (task_is_throttled(p) && enqueue_throttled_task(p)) 7813 return; 7814 7815 /* 7816 * The code below (indirectly) updates schedutil which looks at 7817 * the cfs_rq utilization to select a frequency. 7818 * Let's add the task's estimated utilization to the cfs_rq's 7819 * estimated utilization, before we update schedutil. 7820 */ 7821 if (!p->se.sched_delayed || (flags & ENQUEUE_DELAYED)) 7822 util_est_enqueue(&rq->cfs, p); 7823 7824 if (flags & ENQUEUE_DELAYED) { 7825 requeue_delayed_entity(se); 7826 return; 7827 } 7828 7829 /* 7830 * If in_iowait is set, the code below may not trigger any cpufreq 7831 * utilization updates, so do it here explicitly with the IOWAIT flag 7832 * passed. 7833 */ 7834 if (p->in_iowait) 7835 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT); 7836 7837 if (task_new && se->sched_delayed) 7838 h_nr_runnable = 0; 7839 7840 for_each_sched_entity(se) { 7841 if (se->on_rq) { 7842 if (se->sched_delayed) 7843 requeue_delayed_entity(se); 7844 break; 7845 } 7846 cfs_rq = cfs_rq_of(se); 7847 7848 /* 7849 * Basically set the slice of group entries to the min_slice of 7850 * their respective cfs_rq. This ensures the group can service 7851 * its entities in the desired time-frame. 7852 */ 7853 if (slice) { 7854 se->slice = slice; 7855 se->custom_slice = 1; 7856 } 7857 enqueue_entity(cfs_rq, se, flags); 7858 slice = cfs_rq_min_slice(cfs_rq); 7859 7860 cfs_rq->h_nr_runnable += h_nr_runnable; 7861 cfs_rq->h_nr_queued++; 7862 cfs_rq->h_nr_idle += h_nr_idle; 7863 7864 if (cfs_rq_is_idle(cfs_rq)) 7865 h_nr_idle = 1; 7866 7867 flags = ENQUEUE_WAKEUP; 7868 } 7869 7870 for_each_sched_entity(se) { 7871 cfs_rq = cfs_rq_of(se); 7872 7873 update_load_avg(cfs_rq, se, UPDATE_TG); 7874 se_update_runnable(se); 7875 update_cfs_group(se); 7876 7877 se->slice = slice; 7878 if (se != cfs_rq->curr) 7879 min_vruntime_cb_propagate(&se->run_node, NULL); 7880 slice = cfs_rq_min_slice(cfs_rq); 7881 7882 cfs_rq->h_nr_runnable += h_nr_runnable; 7883 cfs_rq->h_nr_queued++; 7884 cfs_rq->h_nr_idle += h_nr_idle; 7885 7886 if (cfs_rq_is_idle(cfs_rq)) 7887 h_nr_idle = 1; 7888 } 7889 7890 if (!rq_h_nr_queued && rq->cfs.h_nr_queued) 7891 dl_server_start(&rq->fair_server); 7892 7893 /* At this point se is NULL and we are at root level*/ 7894 add_nr_running(rq, 1); 7895 7896 /* 7897 * Since new tasks are assigned an initial util_avg equal to 7898 * half of the spare capacity of their CPU, tiny tasks have the 7899 * ability to cross the overutilized threshold, which will 7900 * result in the load balancer ruining all the task placement 7901 * done by EAS. As a way to mitigate that effect, do not account 7902 * for the first enqueue operation of new tasks during the 7903 * overutilized flag detection. 7904 * 7905 * A better way of solving this problem would be to wait for 7906 * the PELT signals of tasks to converge before taking them 7907 * into account, but that is not straightforward to implement, 7908 * and the following generally works well enough in practice. 7909 */ 7910 if (!task_new) 7911 check_update_overutilized_status(rq); 7912 7913 assert_list_leaf_cfs_rq(rq); 7914 7915 hrtick_update(rq); 7916 } 7917 7918 /* 7919 * Basically dequeue_task_fair(), except it can deal with dequeue_entity() 7920 * failing half-way through and resume the dequeue later. 7921 * 7922 * Returns: 7923 * -1 - dequeue delayed 7924 * 0 - dequeue throttled 7925 * 1 - dequeue complete 7926 */ 7927 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags) 7928 { 7929 bool was_sched_idle = sched_idle_rq(rq); 7930 bool task_sleep = flags & DEQUEUE_SLEEP; 7931 bool task_delayed = flags & DEQUEUE_DELAYED; 7932 bool task_throttled = flags & DEQUEUE_THROTTLE; 7933 struct task_struct *p = NULL; 7934 int h_nr_idle = 0; 7935 int h_nr_queued = 0; 7936 int h_nr_runnable = 0; 7937 struct cfs_rq *cfs_rq; 7938 u64 slice = 0; 7939 7940 if (entity_is_task(se)) { 7941 p = task_of(se); 7942 h_nr_queued = 1; 7943 h_nr_idle = task_has_idle_policy(p); 7944 if (task_sleep || task_delayed || !se->sched_delayed) 7945 h_nr_runnable = 1; 7946 } 7947 7948 for_each_sched_entity(se) { 7949 cfs_rq = cfs_rq_of(se); 7950 7951 if (!dequeue_entity(cfs_rq, se, flags)) { 7952 if (p && &p->se == se) 7953 return -1; 7954 7955 slice = cfs_rq_min_slice(cfs_rq); 7956 break; 7957 } 7958 7959 cfs_rq->h_nr_runnable -= h_nr_runnable; 7960 cfs_rq->h_nr_queued -= h_nr_queued; 7961 cfs_rq->h_nr_idle -= h_nr_idle; 7962 7963 if (cfs_rq_is_idle(cfs_rq)) 7964 h_nr_idle = h_nr_queued; 7965 7966 if (throttled_hierarchy(cfs_rq) && task_throttled) 7967 record_throttle_clock(cfs_rq); 7968 7969 /* Don't dequeue parent if it has other entities besides us */ 7970 if (cfs_rq->load.weight) { 7971 slice = cfs_rq_min_slice(cfs_rq); 7972 7973 /* Avoid re-evaluating load for this entity: */ 7974 se = parent_entity(se); 7975 /* 7976 * Bias pick_next to pick a task from this cfs_rq, as 7977 * p is sleeping when it is within its sched_slice. 7978 */ 7979 if (task_sleep && se) 7980 set_next_buddy(se); 7981 break; 7982 } 7983 flags |= DEQUEUE_SLEEP; 7984 flags &= ~(DEQUEUE_DELAYED | DEQUEUE_SPECIAL); 7985 } 7986 7987 for_each_sched_entity(se) { 7988 cfs_rq = cfs_rq_of(se); 7989 7990 update_load_avg(cfs_rq, se, UPDATE_TG); 7991 se_update_runnable(se); 7992 update_cfs_group(se); 7993 7994 se->slice = slice; 7995 if (se != cfs_rq->curr) 7996 min_vruntime_cb_propagate(&se->run_node, NULL); 7997 slice = cfs_rq_min_slice(cfs_rq); 7998 7999 cfs_rq->h_nr_runnable -= h_nr_runnable; 8000 cfs_rq->h_nr_queued -= h_nr_queued; 8001 cfs_rq->h_nr_idle -= h_nr_idle; 8002 8003 if (cfs_rq_is_idle(cfs_rq)) 8004 h_nr_idle = h_nr_queued; 8005 8006 if (throttled_hierarchy(cfs_rq) && task_throttled) 8007 record_throttle_clock(cfs_rq); 8008 } 8009 8010 sub_nr_running(rq, h_nr_queued); 8011 8012 /* balance early to pull high priority tasks */ 8013 if (unlikely(!was_sched_idle && sched_idle_rq(rq))) 8014 rq->next_balance = jiffies; 8015 8016 if (p && task_delayed) { 8017 WARN_ON_ONCE(!task_sleep); 8018 WARN_ON_ONCE(p->on_rq != 1); 8019 8020 /* 8021 * Fix-up what block_task() skipped. 8022 * 8023 * Must be last, @p might not be valid after this. 8024 */ 8025 __block_task(rq, p); 8026 } 8027 8028 return 1; 8029 } 8030 8031 /* 8032 * The dequeue_task method is called before nr_running is 8033 * decreased. We remove the task from the rbtree and 8034 * update the fair scheduling stats: 8035 */ 8036 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags) 8037 { 8038 if (task_is_throttled(p)) { 8039 dequeue_throttled_task(p, flags); 8040 return true; 8041 } 8042 8043 if (!p->se.sched_delayed) 8044 util_est_dequeue(&rq->cfs, p); 8045 8046 if (dequeue_entities(rq, &p->se, flags) < 0) 8047 return false; 8048 8049 /* 8050 * Must not reference @p after dequeue_entities(DEQUEUE_DELAYED). 8051 */ 8052 return true; 8053 } 8054 8055 static inline unsigned int cfs_h_nr_delayed(struct rq *rq) 8056 { 8057 return (rq->cfs.h_nr_queued - rq->cfs.h_nr_runnable); 8058 } 8059 8060 /* Working cpumask for: sched_balance_rq(), sched_balance_newidle(). */ 8061 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask); 8062 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask); 8063 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask); 8064 8065 #ifdef CONFIG_NO_HZ_COMMON 8066 8067 static struct { 8068 cpumask_var_t idle_cpus_mask; 8069 int has_blocked_load; /* Idle CPUS has blocked load */ 8070 int needs_update; /* Newly idle CPUs need their next_balance collated */ 8071 unsigned long next_balance; /* in jiffy units */ 8072 unsigned long next_blocked; /* Next update of blocked load in jiffies */ 8073 } nohz ____cacheline_aligned; 8074 8075 #endif /* CONFIG_NO_HZ_COMMON */ 8076 8077 static unsigned long cpu_load(struct rq *rq) 8078 { 8079 return cfs_rq_load_avg(&rq->cfs); 8080 } 8081 8082 /* 8083 * cpu_load_without - compute CPU load without any contributions from *p 8084 * @cpu: the CPU which load is requested 8085 * @p: the task which load should be discounted 8086 * 8087 * The load of a CPU is defined by the load of tasks currently enqueued on that 8088 * CPU as well as tasks which are currently sleeping after an execution on that 8089 * CPU. 8090 * 8091 * This method returns the load of the specified CPU by discounting the load of 8092 * the specified task, whenever the task is currently contributing to the CPU 8093 * load. 8094 */ 8095 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p) 8096 { 8097 struct cfs_rq *cfs_rq; 8098 unsigned int load; 8099 8100 /* Task has no contribution or is new */ 8101 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 8102 return cpu_load(rq); 8103 8104 cfs_rq = &rq->cfs; 8105 load = READ_ONCE(cfs_rq->avg.load_avg); 8106 8107 /* Discount task's util from CPU's util */ 8108 lsub_positive(&load, task_h_load(p)); 8109 8110 return load; 8111 } 8112 8113 static unsigned long cpu_runnable(struct rq *rq) 8114 { 8115 return cfs_rq_runnable_avg(&rq->cfs); 8116 } 8117 8118 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p) 8119 { 8120 struct cfs_rq *cfs_rq; 8121 unsigned int runnable; 8122 8123 /* Task has no contribution or is new */ 8124 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 8125 return cpu_runnable(rq); 8126 8127 cfs_rq = &rq->cfs; 8128 runnable = READ_ONCE(cfs_rq->avg.runnable_avg); 8129 8130 /* Discount task's runnable from CPU's runnable */ 8131 lsub_positive(&runnable, p->se.avg.runnable_avg); 8132 8133 return runnable; 8134 } 8135 8136 static unsigned long capacity_of(int cpu) 8137 { 8138 return cpu_rq(cpu)->cpu_capacity; 8139 } 8140 8141 static void record_wakee(struct task_struct *p) 8142 { 8143 /* 8144 * Only decay a single time; tasks that have less then 1 wakeup per 8145 * jiffy will not have built up many flips. 8146 */ 8147 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) { 8148 current->wakee_flips >>= 1; 8149 current->wakee_flip_decay_ts = jiffies; 8150 } 8151 8152 if (current->last_wakee != p) { 8153 current->last_wakee = p; 8154 current->wakee_flips++; 8155 } 8156 } 8157 8158 /* 8159 * Detect M:N waker/wakee relationships via a switching-frequency heuristic. 8160 * 8161 * A waker of many should wake a different task than the one last awakened 8162 * at a frequency roughly N times higher than one of its wakees. 8163 * 8164 * In order to determine whether we should let the load spread vs consolidating 8165 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one 8166 * partner, and a factor of lls_size higher frequency in the other. 8167 * 8168 * With both conditions met, we can be relatively sure that the relationship is 8169 * non-monogamous, with partner count exceeding socket size. 8170 * 8171 * Waker/wakee being client/server, worker/dispatcher, interrupt source or 8172 * whatever is irrelevant, spread criteria is apparent partner count exceeds 8173 * socket size. 8174 */ 8175 static int wake_wide(struct task_struct *p) 8176 { 8177 unsigned int master = current->wakee_flips; 8178 unsigned int slave = p->wakee_flips; 8179 int factor = __this_cpu_read(sd_llc_size); 8180 8181 if (master < slave) 8182 swap(master, slave); 8183 if (slave < factor || master < slave * factor) 8184 return 0; 8185 return 1; 8186 } 8187 8188 /* 8189 * The purpose of wake_affine() is to quickly determine on which CPU we can run 8190 * soonest. For the purpose of speed we only consider the waking and previous 8191 * CPU. 8192 * 8193 * wake_affine_idle() - only considers 'now', it check if the waking CPU is 8194 * cache-affine and is (or will be) idle. 8195 * 8196 * wake_affine_weight() - considers the weight to reflect the average 8197 * scheduling latency of the CPUs. This seems to work 8198 * for the overloaded case. 8199 */ 8200 static int 8201 wake_affine_idle(int this_cpu, int prev_cpu, int sync) 8202 { 8203 /* 8204 * If this_cpu is idle, it implies the wakeup is from interrupt 8205 * context. Only allow the move if cache is shared. Otherwise an 8206 * interrupt intensive workload could force all tasks onto one 8207 * node depending on the IO topology or IRQ affinity settings. 8208 * 8209 * If the prev_cpu is idle and cache affine then avoid a migration. 8210 * There is no guarantee that the cache hot data from an interrupt 8211 * is more important than cache hot data on the prev_cpu and from 8212 * a cpufreq perspective, it's better to have higher utilisation 8213 * on one CPU. 8214 */ 8215 if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu)) 8216 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu; 8217 8218 if (sync) { 8219 struct rq *rq = cpu_rq(this_cpu); 8220 8221 if ((rq->nr_running - cfs_h_nr_delayed(rq)) == 1) 8222 return this_cpu; 8223 } 8224 8225 if (available_idle_cpu(prev_cpu)) 8226 return prev_cpu; 8227 8228 return nr_cpumask_bits; 8229 } 8230 8231 static int 8232 wake_affine_weight(struct sched_domain *sd, struct task_struct *p, 8233 int this_cpu, int prev_cpu, int sync) 8234 { 8235 s64 this_eff_load, prev_eff_load; 8236 unsigned long task_load; 8237 8238 this_eff_load = cpu_load(cpu_rq(this_cpu)); 8239 8240 if (sync) { 8241 unsigned long current_load = task_h_load(current); 8242 8243 if (current_load > this_eff_load) 8244 return this_cpu; 8245 8246 this_eff_load -= current_load; 8247 } 8248 8249 task_load = task_h_load(p); 8250 8251 this_eff_load += task_load; 8252 if (sched_feat(WA_BIAS)) 8253 this_eff_load *= 100; 8254 this_eff_load *= capacity_of(prev_cpu); 8255 8256 prev_eff_load = cpu_load(cpu_rq(prev_cpu)); 8257 prev_eff_load -= task_load; 8258 if (sched_feat(WA_BIAS)) 8259 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2; 8260 prev_eff_load *= capacity_of(this_cpu); 8261 8262 /* 8263 * If sync, adjust the weight of prev_eff_load such that if 8264 * prev_eff == this_eff that select_idle_sibling() will consider 8265 * stacking the wakee on top of the waker if no other CPU is 8266 * idle. 8267 */ 8268 if (sync) 8269 prev_eff_load += 1; 8270 8271 return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits; 8272 } 8273 8274 static int wake_affine(struct sched_domain *sd, struct task_struct *p, 8275 int this_cpu, int prev_cpu, int sync) 8276 { 8277 int target = nr_cpumask_bits; 8278 8279 if (sched_feat(WA_IDLE)) 8280 target = wake_affine_idle(this_cpu, prev_cpu, sync); 8281 8282 if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits) 8283 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync); 8284 8285 schedstat_inc(p->stats.nr_wakeups_affine_attempts); 8286 if (target != this_cpu) 8287 return prev_cpu; 8288 8289 schedstat_inc(sd->ttwu_move_affine); 8290 schedstat_inc(p->stats.nr_wakeups_affine); 8291 return target; 8292 } 8293 8294 static struct sched_group * 8295 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu); 8296 8297 /* 8298 * sched_balance_find_dst_group_cpu - find the idlest CPU among the CPUs in the group. 8299 */ 8300 static int 8301 sched_balance_find_dst_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu) 8302 { 8303 unsigned long load, min_load = ULONG_MAX; 8304 unsigned int min_exit_latency = UINT_MAX; 8305 u64 latest_idle_timestamp = 0; 8306 int least_loaded_cpu = this_cpu; 8307 int shallowest_idle_cpu = -1; 8308 int i; 8309 8310 /* Check if we have any choice: */ 8311 if (group->group_weight == 1) 8312 return cpumask_first(sched_group_span(group)); 8313 8314 /* Traverse only the allowed CPUs */ 8315 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) { 8316 struct rq *rq = cpu_rq(i); 8317 8318 if (!sched_core_cookie_match(rq, p)) 8319 continue; 8320 8321 if (choose_sched_idle_rq(rq, p)) 8322 return i; 8323 8324 if (available_idle_cpu(i)) { 8325 struct cpuidle_state *idle = idle_get_state(rq); 8326 if (idle && idle->exit_latency < min_exit_latency) { 8327 /* 8328 * We give priority to a CPU whose idle state 8329 * has the smallest exit latency irrespective 8330 * of any idle timestamp. 8331 */ 8332 min_exit_latency = idle->exit_latency; 8333 latest_idle_timestamp = rq->idle_stamp; 8334 shallowest_idle_cpu = i; 8335 } else if ((!idle || idle->exit_latency == min_exit_latency) && 8336 rq->idle_stamp > latest_idle_timestamp) { 8337 /* 8338 * If equal or no active idle state, then 8339 * the most recently idled CPU might have 8340 * a warmer cache. 8341 */ 8342 latest_idle_timestamp = rq->idle_stamp; 8343 shallowest_idle_cpu = i; 8344 } 8345 } else if (shallowest_idle_cpu == -1) { 8346 load = cpu_load(cpu_rq(i)); 8347 if (load < min_load) { 8348 min_load = load; 8349 least_loaded_cpu = i; 8350 } 8351 } 8352 } 8353 8354 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu; 8355 } 8356 8357 static inline int sched_balance_find_dst_cpu(struct sched_domain *sd, struct task_struct *p, 8358 int cpu, int prev_cpu, int sd_flag) 8359 { 8360 int new_cpu = cpu; 8361 8362 if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr)) 8363 return prev_cpu; 8364 8365 /* 8366 * We need task's util for cpu_util_without, sync it up to 8367 * prev_cpu's last_update_time. 8368 */ 8369 if (!(sd_flag & SD_BALANCE_FORK)) 8370 sync_entity_load_avg(&p->se); 8371 8372 while (sd) { 8373 struct sched_group *group; 8374 struct sched_domain *tmp; 8375 int weight; 8376 8377 if (!(sd->flags & sd_flag)) { 8378 sd = sd->child; 8379 continue; 8380 } 8381 8382 group = sched_balance_find_dst_group(sd, p, cpu); 8383 if (!group) { 8384 sd = sd->child; 8385 continue; 8386 } 8387 8388 new_cpu = sched_balance_find_dst_group_cpu(group, p, cpu); 8389 if (new_cpu == cpu) { 8390 /* Now try balancing at a lower domain level of 'cpu': */ 8391 sd = sd->child; 8392 continue; 8393 } 8394 8395 /* Now try balancing at a lower domain level of 'new_cpu': */ 8396 cpu = new_cpu; 8397 weight = sd->span_weight; 8398 sd = NULL; 8399 for_each_domain(cpu, tmp) { 8400 if (weight <= tmp->span_weight) 8401 break; 8402 if (tmp->flags & sd_flag) 8403 sd = tmp; 8404 } 8405 } 8406 8407 return new_cpu; 8408 } 8409 8410 static inline int __select_idle_cpu(int cpu, struct task_struct *p) 8411 { 8412 if (choose_idle_cpu(cpu, p) && sched_cpu_cookie_match(cpu_rq(cpu), p)) 8413 return cpu; 8414 8415 return -1; 8416 } 8417 8418 DEFINE_STATIC_KEY_FALSE(sched_smt_present); 8419 EXPORT_SYMBOL_GPL(sched_smt_present); 8420 8421 static inline void set_idle_cores(int cpu, int val) 8422 { 8423 struct sched_domain_shared *sds; 8424 8425 sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu)); 8426 if (sds) 8427 WRITE_ONCE(sds->has_idle_cores, val); 8428 } 8429 8430 static inline bool test_idle_cores(int cpu) 8431 { 8432 struct sched_domain_shared *sds; 8433 8434 sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu)); 8435 if (sds) 8436 return READ_ONCE(sds->has_idle_cores); 8437 8438 return false; 8439 } 8440 8441 /* 8442 * Scans the local SMT mask to see if the entire core is idle, and records this 8443 * information in sd_balance_shared->has_idle_cores. 8444 * 8445 * Since SMT siblings share all cache levels, inspecting this limited remote 8446 * state should be fairly cheap. 8447 */ 8448 void __update_idle_core(struct rq *rq) 8449 { 8450 int core = cpu_of(rq); 8451 int cpu; 8452 8453 rcu_read_lock(); 8454 if (test_idle_cores(core)) 8455 goto unlock; 8456 8457 for_each_cpu(cpu, cpu_smt_mask(core)) { 8458 if (cpu == core) 8459 continue; 8460 8461 if (!available_idle_cpu(cpu)) 8462 goto unlock; 8463 } 8464 8465 set_idle_cores(core, 1); 8466 unlock: 8467 rcu_read_unlock(); 8468 } 8469 8470 /* 8471 * Scan the entire LLC domain for idle cores; this dynamically switches off if 8472 * there are no idle cores left in the system; tracked through 8473 * sd_balance_shared->has_idle_cores and enabled through update_idle_core() 8474 * above. 8475 */ 8476 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu) 8477 { 8478 bool idle = true; 8479 int cpu; 8480 8481 for_each_cpu(cpu, cpu_smt_mask(core)) { 8482 if (!available_idle_cpu(cpu)) { 8483 idle = false; 8484 if (*idle_cpu == -1) { 8485 if (choose_sched_idle_rq(cpu_rq(cpu), p) && 8486 cpumask_test_cpu(cpu, cpus)) { 8487 *idle_cpu = cpu; 8488 break; 8489 } 8490 continue; 8491 } 8492 break; 8493 } 8494 if (*idle_cpu == -1 && cpumask_test_cpu(cpu, cpus)) 8495 *idle_cpu = cpu; 8496 } 8497 8498 if (idle) 8499 return core; 8500 8501 cpumask_andnot(cpus, cpus, cpu_smt_mask(core)); 8502 return -1; 8503 } 8504 8505 /* 8506 * Scan the local SMT mask for idle CPUs. 8507 */ 8508 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target) 8509 { 8510 int cpu; 8511 8512 for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) { 8513 if (cpu == target) 8514 continue; 8515 /* 8516 * Check if the CPU is in the LLC scheduling domain of @target. 8517 * Due to isolcpus, there is no guarantee that all the siblings are in the domain. 8518 */ 8519 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) 8520 continue; 8521 if (choose_idle_cpu(cpu, p)) 8522 return cpu; 8523 } 8524 8525 return -1; 8526 } 8527 8528 /* 8529 * Scan the LLC domain for idle CPUs; this is dynamically regulated by 8530 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the 8531 * average idle time for this rq (as found in rq->avg_idle). 8532 */ 8533 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target) 8534 { 8535 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask); 8536 int i, cpu, idle_cpu = -1, nr = INT_MAX; 8537 8538 if (sched_feat(SIS_UTIL) && sd->shared) { 8539 /* 8540 * Increment because !--nr is the condition to stop scan. 8541 * 8542 * Since "sd" is "sd_llc" for target CPU dereferenced in the 8543 * caller, it is safe to directly dereference "sd->shared". 8544 * Topology bits always ensure it assigned for "sd_llc" abd it 8545 * cannot disappear as long as we have a RCU protected 8546 * reference to one the associated "sd" here. 8547 */ 8548 nr = READ_ONCE(sd->shared->nr_idle_scan) + 1; 8549 /* overloaded LLC is unlikely to have idle cpu/core */ 8550 if (nr == 1) 8551 return -1; 8552 } 8553 8554 if (!cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr)) 8555 return -1; 8556 8557 if (static_branch_unlikely(&sched_cluster_active)) { 8558 struct sched_group *sg = sd->groups; 8559 8560 if (sg->flags & SD_CLUSTER) { 8561 for_each_cpu_wrap(cpu, sched_group_span(sg), target + 1) { 8562 if (!cpumask_test_cpu(cpu, cpus)) 8563 continue; 8564 8565 if (has_idle_core) { 8566 i = select_idle_core(p, cpu, cpus, &idle_cpu); 8567 if ((unsigned int)i < nr_cpumask_bits) 8568 return i; 8569 } else { 8570 if (--nr <= 0) 8571 return -1; 8572 idle_cpu = __select_idle_cpu(cpu, p); 8573 if ((unsigned int)idle_cpu < nr_cpumask_bits) 8574 return idle_cpu; 8575 } 8576 } 8577 cpumask_andnot(cpus, cpus, sched_group_span(sg)); 8578 } 8579 } 8580 8581 for_each_cpu_wrap(cpu, cpus, target + 1) { 8582 if (has_idle_core) { 8583 i = select_idle_core(p, cpu, cpus, &idle_cpu); 8584 if ((unsigned int)i < nr_cpumask_bits) 8585 return i; 8586 8587 } else { 8588 if (--nr <= 0) 8589 return -1; 8590 idle_cpu = __select_idle_cpu(cpu, p); 8591 if ((unsigned int)idle_cpu < nr_cpumask_bits) 8592 break; 8593 } 8594 } 8595 8596 if (has_idle_core) 8597 set_idle_cores(target, false); 8598 8599 return idle_cpu; 8600 } 8601 8602 /* 8603 * Idle-capacity scan converts util_fits_cpu() outcomes into preference ranks, 8604 * where lower values indicate a better fit - see select_idle_capacity(). 8605 * 8606 * A CPU that both fits the task and sits on a fully-idle SMT core is returned 8607 * immediately and is never assigned one of these ranks. On !SMT every CPU is 8608 * its own "core", so the early return covers all fits-and-idle cases and the 8609 * core-tier ranks below become unreachable. 8610 * 8611 * Rank Val Tier Meaning 8612 * ------------------------------ --- ------ --------------------------- 8613 * ASYM_IDLE_UCLAMP_MISFIT -4 core Idle core; capacity fits 8614 * util but uclamp_min misses. 8615 * ASYM_IDLE_COMPLETE_MISFIT -3 core Idle core; capacity does 8616 * not fit. Still beats every 8617 * thread-tier rank: a busy 8618 * sibling cuts effective 8619 * capacity more than a 8620 * misfit hurts a quiet core. 8621 * ASYM_IDLE_THREAD_FITS -2 thread Busy SMT sibling; capacity 8622 * fits util + uclamp. 8623 * ASYM_IDLE_THREAD_UCLAMP_MISFIT -1 thread Busy SMT sibling; capacity 8624 * fits but uclamp_min misses 8625 * (native util_fits_cpu() 8626 * return value). 8627 * ASYM_IDLE_THREAD_MISFIT 0 thread Busy SMT sibling; capacity 8628 * does not fit. 8629 * 8630 * ASYM_IDLE_CORE_BIAS (-3) is an offset, not a state. On an idle core, 8631 * fits += ASYM_IDLE_CORE_BIAS rebases thread-tier ranks into the core tier: 8632 * 8633 * ASYM_IDLE_THREAD_UCLAMP_MISFIT (-1) + BIAS -> ASYM_IDLE_UCLAMP_MISFIT (-4) 8634 * ASYM_IDLE_THREAD_MISFIT (0) + BIAS -> ASYM_IDLE_COMPLETE_MISFIT (-3) 8635 * 8636 * ASYM_IDLE_THREAD_FITS (-2) is never rebased because a fully-fitting idle-core 8637 * candidate early-returns from select_idle_capacity(). 8638 */ 8639 enum asym_fits_state { 8640 ASYM_IDLE_UCLAMP_MISFIT = -4, 8641 ASYM_IDLE_COMPLETE_MISFIT, 8642 ASYM_IDLE_THREAD_FITS, 8643 ASYM_IDLE_THREAD_UCLAMP_MISFIT, 8644 ASYM_IDLE_THREAD_MISFIT, 8645 8646 /* util_fits_cpu() bias for idle core */ 8647 ASYM_IDLE_CORE_BIAS = -3, 8648 }; 8649 8650 /* 8651 * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which 8652 * the task fits. If no CPU is big enough, but there are idle ones, try to 8653 * maximize capacity. 8654 */ 8655 static int 8656 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target) 8657 { 8658 /* 8659 * On !SMT systems, has_idle_core is always false and preferred_core 8660 * is always true (CPU == core), so the SMT preference logic below 8661 * collapses to the plain capacity scan. 8662 */ 8663 bool has_idle_core = sched_smt_active() && test_idle_cores(target); 8664 unsigned long task_util, util_min, util_max, best_cap = 0; 8665 int fits, best_fits = ASYM_IDLE_THREAD_MISFIT; 8666 int cpu, best_cpu = -1; 8667 struct cpumask *cpus; 8668 int nr = INT_MAX; 8669 8670 cpus = this_cpu_cpumask_var_ptr(select_rq_mask); 8671 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr); 8672 8673 task_util = task_util_est(p); 8674 util_min = uclamp_eff_value(p, UCLAMP_MIN); 8675 util_max = uclamp_eff_value(p, UCLAMP_MAX); 8676 8677 if (sched_feat(SIS_UTIL) && sd->shared) { 8678 /* 8679 * Same nr_idle_scan hint as select_idle_cpu(), nr only limits 8680 * the scan when not preferring an idle core. 8681 */ 8682 nr = READ_ONCE(sd->shared->nr_idle_scan) + 1; 8683 /* overloaded domain is unlikely to have idle cpu/core */ 8684 if (nr == 1) 8685 return -1; 8686 } 8687 8688 for_each_cpu_wrap(cpu, cpus, target) { 8689 bool preferred_core = !has_idle_core || is_core_idle(cpu); 8690 unsigned long cpu_cap = capacity_of(cpu); 8691 8692 /* 8693 * Stop when the nr_idle_scan is exhausted (mirrors 8694 * select_idle_cpu() logic). 8695 */ 8696 if (!has_idle_core && --nr <= 0) 8697 return best_cpu; 8698 8699 if (!choose_idle_cpu(cpu, p)) 8700 continue; 8701 8702 fits = util_fits_cpu(task_util, util_min, util_max, cpu); 8703 8704 /* 8705 * Perfect fit: capacity satisfies util + uclamp and the CPU 8706 * sits on a fully-idle SMT core, this is a !SMT system, or 8707 * there is no idle core to find. 8708 * Short-circuit the rank-based selection and return 8709 * immediately. 8710 */ 8711 if (fits > 0 && preferred_core) 8712 return cpu; 8713 /* 8714 * Only the min performance hint (i.e. uclamp_min) doesn't fit. 8715 * Look for the CPU with best capacity. 8716 */ 8717 else if (fits < 0) 8718 cpu_cap = get_actual_cpu_capacity(cpu); 8719 /* 8720 * fits > 0 implies we are not on a preferred core, but the util 8721 * fits CPU capacity. Set fits to ASYM_IDLE_THREAD_FITS 8722 * so the effective range becomes 8723 * [ASYM_IDLE_THREAD_FITS, ASYM_IDLE_THREAD_MISFIT], where: 8724 * ASYM_IDLE_THREAD_MISFIT - does not fit 8725 * ASYM_IDLE_THREAD_UCLAMP_MISFIT - fits with the exception of UCLAMP_MIN 8726 * ASYM_IDLE_THREAD_FITS - fits with the exception of preferred_core 8727 */ 8728 else if (fits > 0) 8729 fits = ASYM_IDLE_THREAD_FITS; 8730 8731 /* 8732 * If we are on a preferred core, translate the range of fits 8733 * of [ASYM_IDLE_THREAD_UCLAMP_MISFIT, ASYM_IDLE_THREAD_MISFIT] to 8734 * [ASYM_IDLE_UCLAMP_MISFIT, ASYM_IDLE_COMPLETE_MISFIT]. 8735 * This ensures that an idle core is always given priority over 8736 * (partially) busy core. 8737 * 8738 * A fully fitting idle core would have returned early and hence 8739 * fits > 0 for preferred_core need not be dealt with. 8740 */ 8741 if (preferred_core) 8742 fits += ASYM_IDLE_CORE_BIAS; 8743 8744 /* 8745 * First, select CPU which fits better (lower is more preferred). 8746 * Then, select the one with best capacity at same level. 8747 */ 8748 if ((fits < best_fits) || 8749 ((fits == best_fits) && (cpu_cap > best_cap))) { 8750 best_cap = cpu_cap; 8751 best_cpu = cpu; 8752 best_fits = fits; 8753 } 8754 } 8755 8756 /* 8757 * A value in the [ASYM_IDLE_UCLAMP_MISFIT, ASYM_IDLE_COMPLETE_MISFIT] 8758 * range means the chosen CPU is in a fully idle SMT core. Values above 8759 * ASYM_IDLE_COMPLETE_MISFIT mean we never ranked such a CPU best. 8760 * 8761 * The asym-capacity wakeup path returns from select_idle_sibling() 8762 * after this function and never runs select_idle_cpu(), so the usual 8763 * select_idle_cpu() tail that clears idle cores must live here when the 8764 * idle-core preference did not win. 8765 */ 8766 if (has_idle_core && best_fits > ASYM_IDLE_COMPLETE_MISFIT) 8767 set_idle_cores(target, false); 8768 8769 return best_cpu; 8770 } 8771 8772 static inline bool asym_fits_cpu(unsigned long util, 8773 unsigned long util_min, 8774 unsigned long util_max, 8775 int cpu) 8776 { 8777 if (sched_asym_cpucap_active()) { 8778 /* 8779 * Return true only if the cpu fully fits the task requirements 8780 * which include the utilization and the performance hints. 8781 * 8782 * When SMT is active, also require that the core has no busy 8783 * siblings. 8784 * 8785 * Note: gating on is_core_idle() also makes the early-bailout 8786 * candidates in select_idle_sibling() (target, prev, 8787 * recent_used_cpu) idle-core-aware on ASYM+SMT, which the 8788 * NO_ASYM path does not do. 8789 */ 8790 return (!sched_smt_active() || is_core_idle(cpu)) && 8791 (util_fits_cpu(util, util_min, util_max, cpu) > 0); 8792 } 8793 8794 return true; 8795 } 8796 8797 /* 8798 * Try and locate an idle core/thread in the LLC cache domain. 8799 */ 8800 static int select_idle_sibling(struct task_struct *p, int prev, int target) 8801 { 8802 bool has_idle_core = false; 8803 struct sched_domain *sd; 8804 unsigned long task_util, util_min, util_max; 8805 int i, recent_used_cpu, prev_aff = -1; 8806 8807 /* 8808 * On asymmetric system, update task utilization because we will check 8809 * that the task fits with CPU's capacity. 8810 */ 8811 if (sched_asym_cpucap_active()) { 8812 sync_entity_load_avg(&p->se); 8813 task_util = task_util_est(p); 8814 util_min = uclamp_eff_value(p, UCLAMP_MIN); 8815 util_max = uclamp_eff_value(p, UCLAMP_MAX); 8816 } 8817 8818 /* 8819 * per-cpu select_rq_mask usage 8820 */ 8821 lockdep_assert_irqs_disabled(); 8822 8823 if (choose_idle_cpu(target, p) && 8824 asym_fits_cpu(task_util, util_min, util_max, target)) 8825 return target; 8826 8827 /* 8828 * If the previous CPU is cache affine and idle, don't be stupid: 8829 */ 8830 if (prev != target && cpus_share_cache(prev, target) && 8831 choose_idle_cpu(prev, p) && 8832 asym_fits_cpu(task_util, util_min, util_max, prev)) { 8833 8834 if (!static_branch_unlikely(&sched_cluster_active) || 8835 cpus_share_resources(prev, target)) 8836 return prev; 8837 8838 prev_aff = prev; 8839 } 8840 8841 /* 8842 * Allow a per-cpu kthread to stack with the wakee if the 8843 * kworker thread and the tasks previous CPUs are the same. 8844 * The assumption is that the wakee queued work for the 8845 * per-cpu kthread that is now complete and the wakeup is 8846 * essentially a sync wakeup. An obvious example of this 8847 * pattern is IO completions. 8848 */ 8849 if (is_per_cpu_kthread(current) && 8850 in_task() && 8851 prev == smp_processor_id() && 8852 this_rq()->nr_running <= 1 && 8853 asym_fits_cpu(task_util, util_min, util_max, prev)) { 8854 return prev; 8855 } 8856 8857 /* Check a recently used CPU as a potential idle candidate: */ 8858 recent_used_cpu = p->recent_used_cpu; 8859 p->recent_used_cpu = prev; 8860 if (recent_used_cpu != prev && 8861 recent_used_cpu != target && 8862 cpus_share_cache(recent_used_cpu, target) && 8863 choose_idle_cpu(recent_used_cpu, p) && 8864 cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) && 8865 asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) { 8866 8867 if (!static_branch_unlikely(&sched_cluster_active) || 8868 cpus_share_resources(recent_used_cpu, target)) 8869 return recent_used_cpu; 8870 8871 } else { 8872 recent_used_cpu = -1; 8873 } 8874 8875 /* 8876 * For asymmetric CPU capacity systems, our domain of interest is 8877 * sd_asym_cpucapacity rather than sd_llc. 8878 */ 8879 if (sched_asym_cpucap_active()) { 8880 sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, target)); 8881 /* 8882 * On an asymmetric CPU capacity system where an exclusive 8883 * cpuset defines a symmetric island (i.e. one unique 8884 * capacity_orig value through the cpuset), the key will be set 8885 * but the CPUs within that cpuset will not have a domain with 8886 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric 8887 * capacity path. 8888 */ 8889 if (sd) { 8890 i = select_idle_capacity(p, sd, target); 8891 return ((unsigned)i < nr_cpumask_bits) ? i : target; 8892 } 8893 } 8894 8895 sd = rcu_dereference_all(per_cpu(sd_llc, target)); 8896 if (!sd) 8897 return target; 8898 8899 if (sched_smt_active()) { 8900 has_idle_core = test_idle_cores(target); 8901 8902 if (!has_idle_core && cpus_share_cache(prev, target)) { 8903 i = select_idle_smt(p, sd, prev); 8904 if ((unsigned int)i < nr_cpumask_bits) 8905 return i; 8906 } 8907 } 8908 8909 i = select_idle_cpu(p, sd, has_idle_core, target); 8910 if ((unsigned)i < nr_cpumask_bits) 8911 return i; 8912 8913 /* 8914 * For cluster machines which have lower sharing cache like L2 or 8915 * LLC Tag, we tend to find an idle CPU in the target's cluster 8916 * first. But prev_cpu or recent_used_cpu may also be a good candidate, 8917 * use them if possible when no idle CPU found in select_idle_cpu(). 8918 */ 8919 if ((unsigned int)prev_aff < nr_cpumask_bits) 8920 return prev_aff; 8921 if ((unsigned int)recent_used_cpu < nr_cpumask_bits) 8922 return recent_used_cpu; 8923 8924 return target; 8925 } 8926 8927 /** 8928 * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks. 8929 * @cpu: the CPU to get the utilization for 8930 * @p: task for which the CPU utilization should be predicted or NULL 8931 * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL 8932 * @boost: 1 to enable boosting, otherwise 0 8933 * 8934 * The unit of the return value must be the same as the one of CPU capacity 8935 * so that CPU utilization can be compared with CPU capacity. 8936 * 8937 * CPU utilization is the sum of running time of runnable tasks plus the 8938 * recent utilization of currently non-runnable tasks on that CPU. 8939 * It represents the amount of CPU capacity currently used by CFS tasks in 8940 * the range [0..max CPU capacity] with max CPU capacity being the CPU 8941 * capacity at f_max. 8942 * 8943 * The estimated CPU utilization is defined as the maximum between CPU 8944 * utilization and sum of the estimated utilization of the currently 8945 * runnable tasks on that CPU. It preserves a utilization "snapshot" of 8946 * previously-executed tasks, which helps better deduce how busy a CPU will 8947 * be when a long-sleeping task wakes up. The contribution to CPU utilization 8948 * of such a task would be significantly decayed at this point of time. 8949 * 8950 * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization). 8951 * CPU contention for CFS tasks can be detected by CPU runnable > CPU 8952 * utilization. Boosting is implemented in cpu_util() so that internal 8953 * users (e.g. EAS) can use it next to external users (e.g. schedutil), 8954 * latter via cpu_util_cfs_boost(). 8955 * 8956 * CPU utilization can be higher than the current CPU capacity 8957 * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because 8958 * of rounding errors as well as task migrations or wakeups of new tasks. 8959 * CPU utilization has to be capped to fit into the [0..max CPU capacity] 8960 * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%) 8961 * could be seen as over-utilized even though CPU1 has 20% of spare CPU 8962 * capacity. CPU utilization is allowed to overshoot current CPU capacity 8963 * though since this is useful for predicting the CPU capacity required 8964 * after task migrations (scheduler-driven DVFS). 8965 * 8966 * Return: (Boosted) (estimated) utilization for the specified CPU. 8967 */ 8968 static unsigned long 8969 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost) 8970 { 8971 bool add_task = p && task_cpu(p) != cpu && dst_cpu == cpu; 8972 bool sub_task = p && task_cpu(p) == cpu && dst_cpu != cpu; 8973 struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs; 8974 unsigned long util = READ_ONCE(cfs_rq->avg.util_avg); 8975 unsigned long runnable; 8976 8977 /* 8978 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its 8979 * contribution. If @p migrates from another CPU to @cpu add its 8980 * contribution. In all the other cases @cpu is not impacted by the 8981 * migration so its util_avg is already correct. 8982 */ 8983 if (add_task) 8984 util += task_util(p); 8985 else if (sub_task) 8986 lsub_positive(&util, task_util(p)); 8987 8988 if (boost) { 8989 runnable = READ_ONCE(cfs_rq->avg.runnable_avg); 8990 if (add_task) 8991 runnable += READ_ONCE(p->se.avg.runnable_avg); 8992 else if (sub_task) 8993 lsub_positive(&runnable, 8994 READ_ONCE(p->se.avg.runnable_avg)); 8995 util = max(util, runnable); 8996 } 8997 8998 if (sched_feat(UTIL_EST)) { 8999 unsigned long util_est; 9000 9001 util_est = READ_ONCE(cfs_rq->avg.util_est); 9002 9003 /* 9004 * During wake-up @p isn't enqueued yet and doesn't contribute 9005 * to any cpu_rq(cpu)->cfs.avg.util_est. 9006 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p 9007 * has been enqueued. 9008 * 9009 * During exec (@dst_cpu = -1) @p is enqueued and does 9010 * contribute to cpu_rq(cpu)->cfs.util_est. 9011 * Remove it to "simulate" cpu_util without @p's contribution. 9012 * 9013 * Despite the task_on_rq_queued(@p) check there is still a 9014 * small window for a possible race when an exec 9015 * select_task_rq_fair() races with LB's detach_task(). 9016 * 9017 * detach_task() 9018 * deactivate_task() 9019 * p->on_rq = TASK_ON_RQ_MIGRATING; 9020 * -------------------------------- A 9021 * dequeue_task() \ 9022 * dequeue_task_fair() + Race Time 9023 * util_est_dequeue() / 9024 * -------------------------------- B 9025 * 9026 * The additional check "current == p" is required to further 9027 * reduce the race window. 9028 */ 9029 if (dst_cpu == cpu) 9030 util_est += _task_util_est(p); 9031 else if (p && unlikely(task_on_rq_queued(p) || current == p)) 9032 lsub_positive(&util_est, _task_util_est(p)); 9033 9034 util = max(util, util_est); 9035 } 9036 9037 return min(util, arch_scale_cpu_capacity(cpu)); 9038 } 9039 9040 unsigned long cpu_util_cfs(int cpu) 9041 { 9042 return cpu_util(cpu, NULL, -1, 0); 9043 } 9044 9045 unsigned long cpu_util_cfs_boost(int cpu) 9046 { 9047 return cpu_util(cpu, NULL, -1, 1); 9048 } 9049 9050 /* 9051 * cpu_util_without: compute cpu utilization without any contributions from *p 9052 * @cpu: the CPU which utilization is requested 9053 * @p: the task which utilization should be discounted 9054 * 9055 * The utilization of a CPU is defined by the utilization of tasks currently 9056 * enqueued on that CPU as well as tasks which are currently sleeping after an 9057 * execution on that CPU. 9058 * 9059 * This method returns the utilization of the specified CPU by discounting the 9060 * utilization of the specified task, whenever the task is currently 9061 * contributing to the CPU utilization. 9062 */ 9063 static unsigned long cpu_util_without(int cpu, struct task_struct *p) 9064 { 9065 /* Task has no contribution or is new */ 9066 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 9067 p = NULL; 9068 9069 return cpu_util(cpu, p, -1, 0); 9070 } 9071 9072 /* 9073 * This function computes an effective utilization for the given CPU, to be 9074 * used for frequency selection given the linear relation: f = u * f_max. 9075 * 9076 * The scheduler tracks the following metrics: 9077 * 9078 * cpu_util_{cfs,rt,dl,irq}() 9079 * cpu_bw_dl() 9080 * 9081 * Where the cfs,rt and dl util numbers are tracked with the same metric and 9082 * synchronized windows and are thus directly comparable. 9083 * 9084 * The cfs,rt,dl utilization are the running times measured with rq->clock_task 9085 * which excludes things like IRQ and steal-time. These latter are then accrued 9086 * in the IRQ utilization. 9087 * 9088 * The DL bandwidth number OTOH is not a measured metric but a value computed 9089 * based on the task model parameters and gives the minimal utilization 9090 * required to meet deadlines. 9091 */ 9092 unsigned long effective_cpu_util(int cpu, unsigned long util_cfs, 9093 unsigned long *min, 9094 unsigned long *max) 9095 { 9096 unsigned long util, irq, scale; 9097 struct rq *rq = cpu_rq(cpu); 9098 9099 scale = arch_scale_cpu_capacity(cpu); 9100 9101 /* 9102 * Early check to see if IRQ/steal time saturates the CPU, can be 9103 * because of inaccuracies in how we track these -- see 9104 * update_irq_load_avg(). 9105 */ 9106 irq = cpu_util_irq(rq); 9107 if (unlikely(irq >= scale)) { 9108 if (min) 9109 *min = scale; 9110 if (max) 9111 *max = scale; 9112 return scale; 9113 } 9114 9115 if (min) { 9116 /* 9117 * The minimum utilization returns the highest level between: 9118 * - the computed DL bandwidth needed with the IRQ pressure which 9119 * steals time to the deadline task. 9120 * - The minimum performance requirement for CFS and/or RT. 9121 */ 9122 *min = max(irq + cpu_bw_dl(rq), uclamp_rq_get(rq, UCLAMP_MIN)); 9123 9124 /* 9125 * When an RT task is runnable and uclamp is not used, we must 9126 * ensure that the task will run at maximum compute capacity. 9127 */ 9128 if (!uclamp_is_used() && rt_rq_is_runnable(&rq->rt)) 9129 *min = max(*min, scale); 9130 } 9131 9132 /* 9133 * Because the time spend on RT/DL tasks is visible as 'lost' time to 9134 * CFS tasks and we use the same metric to track the effective 9135 * utilization (PELT windows are synchronized) we can directly add them 9136 * to obtain the CPU's actual utilization. 9137 */ 9138 util = util_cfs + cpu_util_rt(rq); 9139 util += cpu_util_dl(rq); 9140 9141 /* 9142 * The maximum hint is a soft bandwidth requirement, which can be lower 9143 * than the actual utilization because of uclamp_max requirements. 9144 */ 9145 if (max) 9146 *max = min(scale, uclamp_rq_get(rq, UCLAMP_MAX)); 9147 9148 if (util >= scale) 9149 return scale; 9150 9151 /* 9152 * There is still idle time; further improve the number by using the 9153 * IRQ metric. Because IRQ/steal time is hidden from the task clock we 9154 * need to scale the task numbers: 9155 * 9156 * max - irq 9157 * U' = irq + --------- * U 9158 * max 9159 */ 9160 util = scale_irq_capacity(util, irq, scale); 9161 util += irq; 9162 9163 return min(scale, util); 9164 } 9165 9166 unsigned long sched_cpu_util(int cpu) 9167 { 9168 return effective_cpu_util(cpu, cpu_util_cfs(cpu), NULL, NULL); 9169 } 9170 9171 /* 9172 * energy_env - Utilization landscape for energy estimation. 9173 * @task_busy_time: Utilization contribution by the task for which we test the 9174 * placement. Given by eenv_task_busy_time(). 9175 * @pd_busy_time: Utilization of the whole perf domain without the task 9176 * contribution. Given by eenv_pd_busy_time(). 9177 * @cpu_cap: Maximum CPU capacity for the perf domain. 9178 * @pd_cap: Entire perf domain capacity. (pd->nr_cpus * cpu_cap). 9179 */ 9180 struct energy_env { 9181 unsigned long task_busy_time; 9182 unsigned long pd_busy_time; 9183 unsigned long cpu_cap; 9184 unsigned long pd_cap; 9185 }; 9186 9187 /* 9188 * Compute the task busy time for compute_energy(). This time cannot be 9189 * injected directly into effective_cpu_util() because of the IRQ scaling. 9190 * The latter only makes sense with the most recent CPUs where the task has 9191 * run. 9192 */ 9193 static inline void eenv_task_busy_time(struct energy_env *eenv, 9194 struct task_struct *p, int prev_cpu) 9195 { 9196 unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu); 9197 unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu)); 9198 9199 if (unlikely(irq >= max_cap)) 9200 busy_time = max_cap; 9201 else 9202 busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap); 9203 9204 eenv->task_busy_time = busy_time; 9205 } 9206 9207 /* 9208 * Compute the perf_domain (PD) busy time for compute_energy(). Based on the 9209 * utilization for each @pd_cpus, it however doesn't take into account 9210 * clamping since the ratio (utilization / cpu_capacity) is already enough to 9211 * scale the EM reported power consumption at the (eventually clamped) 9212 * cpu_capacity. 9213 * 9214 * The contribution of the task @p for which we want to estimate the 9215 * energy cost is removed (by cpu_util()) and must be calculated 9216 * separately (see eenv_task_busy_time). This ensures: 9217 * 9218 * - A stable PD utilization, no matter which CPU of that PD we want to place 9219 * the task on. 9220 * 9221 * - A fair comparison between CPUs as the task contribution (task_util()) 9222 * will always be the same no matter which CPU utilization we rely on 9223 * (util_avg or util_est). 9224 * 9225 * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't 9226 * exceed @eenv->pd_cap. 9227 */ 9228 static inline void eenv_pd_busy_time(struct energy_env *eenv, 9229 struct cpumask *pd_cpus, 9230 struct task_struct *p) 9231 { 9232 unsigned long busy_time = 0; 9233 int cpu; 9234 9235 for_each_cpu(cpu, pd_cpus) { 9236 unsigned long util = cpu_util(cpu, p, -1, 0); 9237 9238 busy_time += effective_cpu_util(cpu, util, NULL, NULL); 9239 } 9240 9241 eenv->pd_busy_time = min(eenv->pd_cap, busy_time); 9242 } 9243 9244 /* 9245 * Compute the maximum utilization for compute_energy() when the task @p 9246 * is placed on the cpu @dst_cpu. 9247 * 9248 * Returns the maximum utilization among @eenv->cpus. This utilization can't 9249 * exceed @eenv->cpu_cap. 9250 */ 9251 static inline unsigned long 9252 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus, 9253 struct task_struct *p, int dst_cpu) 9254 { 9255 unsigned long max_util = 0; 9256 int cpu; 9257 9258 for_each_cpu(cpu, pd_cpus) { 9259 struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL; 9260 unsigned long util = cpu_util(cpu, p, dst_cpu, 1); 9261 unsigned long eff_util, min, max; 9262 9263 /* 9264 * Performance domain frequency: utilization clamping 9265 * must be considered since it affects the selection 9266 * of the performance domain frequency. 9267 * NOTE: in case RT tasks are running, by default the min 9268 * utilization can be max OPP. 9269 */ 9270 eff_util = effective_cpu_util(cpu, util, &min, &max); 9271 9272 /* Task's uclamp can modify min and max value */ 9273 if (tsk && uclamp_is_used()) { 9274 min = max(min, uclamp_eff_value(p, UCLAMP_MIN)); 9275 9276 /* 9277 * If there is no active max uclamp constraint, 9278 * directly use task's one, otherwise keep max. 9279 */ 9280 if (uclamp_rq_is_idle(cpu_rq(cpu))) 9281 max = uclamp_eff_value(p, UCLAMP_MAX); 9282 else 9283 max = max(max, uclamp_eff_value(p, UCLAMP_MAX)); 9284 } 9285 9286 eff_util = sugov_effective_cpu_perf(cpu, eff_util, min, max); 9287 max_util = max(max_util, eff_util); 9288 } 9289 9290 return min(max_util, eenv->cpu_cap); 9291 } 9292 9293 /* 9294 * compute_energy(): Use the Energy Model to estimate the energy that @pd would 9295 * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task 9296 * contribution is ignored. 9297 */ 9298 static inline unsigned long 9299 compute_energy(struct energy_env *eenv, struct perf_domain *pd, 9300 struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu) 9301 { 9302 unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu); 9303 unsigned long busy_time = eenv->pd_busy_time; 9304 unsigned long energy; 9305 9306 if (dst_cpu >= 0) 9307 busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time); 9308 9309 energy = em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap); 9310 9311 trace_sched_compute_energy_tp(p, dst_cpu, energy, max_util, busy_time); 9312 9313 return energy; 9314 } 9315 9316 /* 9317 * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the 9318 * waking task. find_energy_efficient_cpu() looks for the CPU with maximum 9319 * spare capacity in each performance domain and uses it as a potential 9320 * candidate to execute the task. Then, it uses the Energy Model to figure 9321 * out which of the CPU candidates is the most energy-efficient. 9322 * 9323 * The rationale for this heuristic is as follows. In a performance domain, 9324 * all the most energy efficient CPU candidates (according to the Energy 9325 * Model) are those for which we'll request a low frequency. When there are 9326 * several CPUs for which the frequency request will be the same, we don't 9327 * have enough data to break the tie between them, because the Energy Model 9328 * only includes active power costs. With this model, if we assume that 9329 * frequency requests follow utilization (e.g. using schedutil), the CPU with 9330 * the maximum spare capacity in a performance domain is guaranteed to be among 9331 * the best candidates of the performance domain. 9332 * 9333 * In practice, it could be preferable from an energy standpoint to pack 9334 * small tasks on a CPU in order to let other CPUs go in deeper idle states, 9335 * but that could also hurt our chances to go cluster idle, and we have no 9336 * ways to tell with the current Energy Model if this is actually a good 9337 * idea or not. So, find_energy_efficient_cpu() basically favors 9338 * cluster-packing, and spreading inside a cluster. That should at least be 9339 * a good thing for latency, and this is consistent with the idea that most 9340 * of the energy savings of EAS come from the asymmetry of the system, and 9341 * not so much from breaking the tie between identical CPUs. That's also the 9342 * reason why EAS is enabled in the topology code only for systems where 9343 * SD_ASYM_CPUCAPACITY is set. 9344 * 9345 * NOTE: Forkees are not accepted in the energy-aware wake-up path because 9346 * they don't have any useful utilization data yet and it's not possible to 9347 * forecast their impact on energy consumption. Consequently, they will be 9348 * placed by sched_balance_find_dst_cpu() on the least loaded CPU, which might turn out 9349 * to be energy-inefficient in some use-cases. The alternative would be to 9350 * bias new tasks towards specific types of CPUs first, or to try to infer 9351 * their util_avg from the parent task, but those heuristics could hurt 9352 * other use-cases too. So, until someone finds a better way to solve this, 9353 * let's keep things simple by re-using the existing slow path. 9354 */ 9355 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu) 9356 { 9357 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask); 9358 unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX; 9359 unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0; 9360 unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024; 9361 struct root_domain *rd = this_rq()->rd; 9362 int cpu, best_energy_cpu, target = -1; 9363 int prev_fits = -1, best_fits = -1; 9364 unsigned long best_actual_cap = 0; 9365 unsigned long prev_actual_cap = 0; 9366 struct sched_domain *sd; 9367 struct perf_domain *pd; 9368 struct energy_env eenv; 9369 9370 pd = rcu_dereference_all(rd->pd); 9371 if (!pd) 9372 return target; 9373 9374 /* 9375 * Energy-aware wake-up happens on the lowest sched_domain starting 9376 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu. 9377 */ 9378 sd = rcu_dereference_all(*this_cpu_ptr(&sd_asym_cpucapacity)); 9379 while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd))) 9380 sd = sd->parent; 9381 if (!sd) 9382 return target; 9383 9384 target = prev_cpu; 9385 9386 sync_entity_load_avg(&p->se); 9387 if (!task_util_est(p) && p_util_min == 0) 9388 return target; 9389 9390 eenv_task_busy_time(&eenv, p, prev_cpu); 9391 9392 for (; pd; pd = pd->next) { 9393 unsigned long util_min = p_util_min, util_max = p_util_max; 9394 unsigned long cpu_cap, cpu_actual_cap, util; 9395 long prev_spare_cap = -1, max_spare_cap = -1; 9396 unsigned long rq_util_min, rq_util_max; 9397 unsigned long cur_delta, base_energy; 9398 int max_spare_cap_cpu = -1; 9399 int fits, max_fits = -1; 9400 9401 if (!cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask)) 9402 continue; 9403 9404 /* Account external pressure for the energy estimation */ 9405 cpu = cpumask_first(cpus); 9406 cpu_actual_cap = get_actual_cpu_capacity(cpu); 9407 9408 eenv.cpu_cap = cpu_actual_cap; 9409 eenv.pd_cap = 0; 9410 9411 for_each_cpu(cpu, cpus) { 9412 struct rq *rq = cpu_rq(cpu); 9413 9414 eenv.pd_cap += cpu_actual_cap; 9415 9416 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) 9417 continue; 9418 9419 if (!cpumask_test_cpu(cpu, p->cpus_ptr)) 9420 continue; 9421 9422 util = cpu_util(cpu, p, cpu, 0); 9423 cpu_cap = capacity_of(cpu); 9424 9425 /* 9426 * Skip CPUs that cannot satisfy the capacity request. 9427 * IOW, placing the task there would make the CPU 9428 * overutilized. Take uclamp into account to see how 9429 * much capacity we can get out of the CPU; this is 9430 * aligned with sched_cpu_util(). 9431 */ 9432 if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) { 9433 /* 9434 * Open code uclamp_rq_util_with() except for 9435 * the clamp() part. I.e.: apply max aggregation 9436 * only. util_fits_cpu() logic requires to 9437 * operate on non clamped util but must use the 9438 * max-aggregated uclamp_{min, max}. 9439 */ 9440 rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN); 9441 rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX); 9442 9443 util_min = max(rq_util_min, p_util_min); 9444 util_max = max(rq_util_max, p_util_max); 9445 } 9446 9447 fits = util_fits_cpu(util, util_min, util_max, cpu); 9448 if (!fits) 9449 continue; 9450 9451 lsub_positive(&cpu_cap, util); 9452 9453 if (cpu == prev_cpu) { 9454 /* Always use prev_cpu as a candidate. */ 9455 prev_spare_cap = cpu_cap; 9456 prev_fits = fits; 9457 } else if ((fits > max_fits) || 9458 ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) { 9459 /* 9460 * Find the CPU with the maximum spare capacity 9461 * among the remaining CPUs in the performance 9462 * domain. 9463 */ 9464 max_spare_cap = cpu_cap; 9465 max_spare_cap_cpu = cpu; 9466 max_fits = fits; 9467 } 9468 } 9469 9470 if (max_spare_cap_cpu < 0 && prev_spare_cap < 0) 9471 continue; 9472 9473 eenv_pd_busy_time(&eenv, cpus, p); 9474 /* Compute the 'base' energy of the pd, without @p */ 9475 base_energy = compute_energy(&eenv, pd, cpus, p, -1); 9476 9477 /* Evaluate the energy impact of using prev_cpu. */ 9478 if (prev_spare_cap > -1) { 9479 prev_delta = compute_energy(&eenv, pd, cpus, p, 9480 prev_cpu); 9481 /* CPU utilization has changed */ 9482 if (prev_delta < base_energy) 9483 return target; 9484 prev_delta -= base_energy; 9485 prev_actual_cap = cpu_actual_cap; 9486 best_delta = min(best_delta, prev_delta); 9487 } 9488 9489 /* Evaluate the energy impact of using max_spare_cap_cpu. */ 9490 if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) { 9491 /* Current best energy cpu fits better */ 9492 if (max_fits < best_fits) 9493 continue; 9494 9495 /* 9496 * Both don't fit performance hint (i.e. uclamp_min) 9497 * but best energy cpu has better capacity. 9498 */ 9499 if ((max_fits < 0) && 9500 (cpu_actual_cap <= best_actual_cap)) 9501 continue; 9502 9503 cur_delta = compute_energy(&eenv, pd, cpus, p, 9504 max_spare_cap_cpu); 9505 /* CPU utilization has changed */ 9506 if (cur_delta < base_energy) 9507 return target; 9508 cur_delta -= base_energy; 9509 9510 /* 9511 * Both fit for the task but best energy cpu has lower 9512 * energy impact. 9513 */ 9514 if ((max_fits > 0) && (best_fits > 0) && 9515 (cur_delta >= best_delta)) 9516 continue; 9517 9518 best_delta = cur_delta; 9519 best_energy_cpu = max_spare_cap_cpu; 9520 best_fits = max_fits; 9521 best_actual_cap = cpu_actual_cap; 9522 } 9523 } 9524 9525 if ((best_fits > prev_fits) || 9526 ((best_fits > 0) && (best_delta < prev_delta)) || 9527 ((best_fits < 0) && (best_actual_cap > prev_actual_cap))) 9528 target = best_energy_cpu; 9529 9530 return target; 9531 } 9532 9533 /* 9534 * select_task_rq_fair: Select target runqueue for the waking task in domains 9535 * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE, 9536 * SD_BALANCE_FORK, or SD_BALANCE_EXEC. 9537 * 9538 * Balances load by selecting the idlest CPU in the idlest group, or under 9539 * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set. 9540 * 9541 * Returns the target CPU number. 9542 */ 9543 static int 9544 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags) 9545 { 9546 int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING); 9547 struct sched_domain *tmp, *sd = NULL; 9548 int cpu = smp_processor_id(); 9549 int new_cpu = prev_cpu; 9550 int want_affine = 0; 9551 /* SD_flags and WF_flags share the first nibble */ 9552 int sd_flag = wake_flags & 0xF; 9553 9554 /* 9555 * required for stable ->cpus_allowed 9556 */ 9557 lockdep_assert_held(&p->pi_lock); 9558 if (wake_flags & WF_TTWU) { 9559 record_wakee(p); 9560 9561 if ((wake_flags & WF_CURRENT_CPU) && 9562 cpumask_test_cpu(cpu, p->cpus_ptr)) 9563 return cpu; 9564 9565 if (!is_rd_overutilized(this_rq()->rd)) { 9566 new_cpu = find_energy_efficient_cpu(p, prev_cpu); 9567 if (new_cpu >= 0) 9568 return new_cpu; 9569 new_cpu = prev_cpu; 9570 } 9571 9572 want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr); 9573 } 9574 9575 for_each_domain(cpu, tmp) { 9576 /* 9577 * If both 'cpu' and 'prev_cpu' are part of this domain, 9578 * cpu is a valid SD_WAKE_AFFINE target. 9579 */ 9580 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) && 9581 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) { 9582 if (cpu != prev_cpu) 9583 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync); 9584 9585 sd = NULL; /* Prefer wake_affine over balance flags */ 9586 break; 9587 } 9588 9589 /* 9590 * Usually only true for WF_EXEC and WF_FORK, as sched_domains 9591 * usually do not have SD_BALANCE_WAKE set. That means wakeup 9592 * will usually go to the fast path. 9593 */ 9594 if (tmp->flags & sd_flag) 9595 sd = tmp; 9596 else if (!want_affine) 9597 break; 9598 } 9599 9600 /* Slow path */ 9601 if (unlikely(sd)) 9602 return sched_balance_find_dst_cpu(sd, p, cpu, prev_cpu, sd_flag); 9603 9604 /* Fast path */ 9605 if (wake_flags & WF_TTWU) 9606 return select_idle_sibling(p, prev_cpu, new_cpu); 9607 9608 return new_cpu; 9609 } 9610 9611 /* 9612 * Called immediately before a task is migrated to a new CPU; task_cpu(p) and 9613 * cfs_rq_of(p) references at time of call are still valid and identify the 9614 * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held. 9615 */ 9616 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu) 9617 { 9618 struct sched_entity *se = &p->se; 9619 9620 if (!task_on_rq_migrating(p)) { 9621 remove_entity_load_avg(se); 9622 9623 /* 9624 * Here, the task's PELT values have been updated according to 9625 * the current rq's clock. But if that clock hasn't been 9626 * updated in a while, a substantial idle time will be missed, 9627 * leading to an inflation after wake-up on the new rq. 9628 * 9629 * Estimate the missing time from the cfs_rq last_update_time 9630 * and update sched_avg to improve the PELT continuity after 9631 * migration. 9632 */ 9633 migrate_se_pelt_lag(se); 9634 } 9635 9636 /* Tell new CPU we are migrated */ 9637 se->avg.last_update_time = 0; 9638 9639 update_scan_period(p, new_cpu); 9640 } 9641 9642 static void task_dead_fair(struct task_struct *p) 9643 { 9644 struct sched_entity *se = &p->se; 9645 9646 if (se->sched_delayed) { 9647 struct rq_flags rf; 9648 struct rq *rq; 9649 9650 rq = task_rq_lock(p, &rf); 9651 if (se->sched_delayed) { 9652 update_rq_clock(rq); 9653 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED); 9654 } 9655 task_rq_unlock(rq, p, &rf); 9656 } 9657 9658 remove_entity_load_avg(se); 9659 } 9660 9661 /* 9662 * Set the max capacity the task is allowed to run at for misfit detection. 9663 */ 9664 static void set_task_max_allowed_capacity(struct task_struct *p) 9665 { 9666 struct asym_cap_data *entry; 9667 9668 if (!sched_asym_cpucap_active()) 9669 return; 9670 9671 rcu_read_lock(); 9672 list_for_each_entry_rcu(entry, &asym_cap_list, link) { 9673 cpumask_t *cpumask; 9674 9675 cpumask = cpu_capacity_span(entry); 9676 if (!cpumask_intersects(p->cpus_ptr, cpumask)) 9677 continue; 9678 9679 p->max_allowed_capacity = entry->capacity; 9680 break; 9681 } 9682 rcu_read_unlock(); 9683 } 9684 9685 static void set_cpus_allowed_fair(struct task_struct *p, struct affinity_context *ctx) 9686 { 9687 set_cpus_allowed_common(p, ctx); 9688 set_task_max_allowed_capacity(p); 9689 } 9690 9691 static void set_next_buddy(struct sched_entity *se) 9692 { 9693 for_each_sched_entity(se) { 9694 if (WARN_ON_ONCE(!se->on_rq)) 9695 return; 9696 if (se_is_idle(se)) 9697 return; 9698 cfs_rq_of(se)->next = se; 9699 } 9700 } 9701 9702 enum preempt_wakeup_action { 9703 PREEMPT_WAKEUP_NONE, /* No preemption. */ 9704 PREEMPT_WAKEUP_SHORT, /* Ignore slice protection. */ 9705 PREEMPT_WAKEUP_PICK, /* Let __pick_eevdf() decide. */ 9706 PREEMPT_WAKEUP_RESCHED, /* Force reschedule. */ 9707 }; 9708 9709 static inline bool 9710 set_preempt_buddy(struct cfs_rq *cfs_rq, int wake_flags, 9711 struct sched_entity *pse, struct sched_entity *se) 9712 { 9713 /* 9714 * Keep existing buddy if the deadline is sooner than pse. 9715 * The older buddy may be cache cold and completely unrelated 9716 * to the current wakeup but that is unpredictable where as 9717 * obeying the deadline is more in line with EEVDF objectives. 9718 */ 9719 if (cfs_rq->next && entity_before(cfs_rq->next, pse)) 9720 return false; 9721 9722 set_next_buddy(pse); 9723 return true; 9724 } 9725 9726 /* 9727 * WF_SYNC|WF_TTWU indicates the waker expects to sleep but it is not 9728 * strictly enforced because the hint is either misunderstood or 9729 * multiple tasks must be woken up. 9730 */ 9731 static inline enum preempt_wakeup_action 9732 preempt_sync(struct rq *rq, int wake_flags, 9733 struct sched_entity *pse, struct sched_entity *se) 9734 { 9735 u64 threshold, delta; 9736 9737 /* 9738 * WF_SYNC without WF_TTWU is not expected so warn if it happens even 9739 * though it is likely harmless. 9740 */ 9741 WARN_ON_ONCE(!(wake_flags & WF_TTWU)); 9742 9743 threshold = sysctl_sched_migration_cost; 9744 delta = rq_clock_task(rq) - se->exec_start; 9745 if ((s64)delta < 0) 9746 delta = 0; 9747 9748 /* 9749 * WF_RQ_SELECTED implies the tasks are stacking on a CPU when they 9750 * could run on other CPUs. Reduce the threshold before preemption is 9751 * allowed to an arbitrary lower value as it is more likely (but not 9752 * guaranteed) the waker requires the wakee to finish. 9753 */ 9754 if (wake_flags & WF_RQ_SELECTED) 9755 threshold >>= 2; 9756 9757 /* 9758 * As WF_SYNC is not strictly obeyed, allow some runtime for batch 9759 * wakeups to be issued. 9760 */ 9761 if (entity_before(pse, se) && delta >= threshold) 9762 return PREEMPT_WAKEUP_RESCHED; 9763 9764 return PREEMPT_WAKEUP_NONE; 9765 } 9766 9767 /* 9768 * Preempt the current task with a newly woken task if needed: 9769 */ 9770 static void wakeup_preempt_fair(struct rq *rq, struct task_struct *p, int wake_flags) 9771 { 9772 enum preempt_wakeup_action preempt_action = PREEMPT_WAKEUP_PICK; 9773 struct task_struct *donor = rq->donor; 9774 struct sched_entity *nse, *se = &donor->se, *pse = &p->se; 9775 struct cfs_rq *cfs_rq = task_cfs_rq(donor); 9776 int cse_is_idle, pse_is_idle; 9777 9778 /* 9779 * XXX Getting preempted by higher class, try and find idle CPU? 9780 */ 9781 if (p->sched_class != &fair_sched_class) 9782 return; 9783 9784 if (unlikely(se == pse)) 9785 return; 9786 9787 /* 9788 * This is possible from callers such as attach_tasks(), in which we 9789 * unconditionally wakeup_preempt() after an enqueue (which may have 9790 * lead to a throttle). This both saves work and prevents false 9791 * next-buddy nomination below. 9792 */ 9793 if (task_is_throttled(p)) 9794 return; 9795 9796 /* 9797 * We can come here with TIF_NEED_RESCHED already set from new task 9798 * wake up path. 9799 * 9800 * Note: this also catches the edge-case of curr being in a throttled 9801 * group (e.g. via set_curr_task), since update_curr() (in the 9802 * enqueue of curr) will have resulted in resched being set. This 9803 * prevents us from potentially nominating it as a false LAST_BUDDY 9804 * below. 9805 */ 9806 if (test_tsk_need_resched(rq->curr)) 9807 return; 9808 9809 if (!sched_feat(WAKEUP_PREEMPTION)) 9810 return; 9811 9812 find_matching_se(&se, &pse); 9813 WARN_ON_ONCE(!pse); 9814 9815 cse_is_idle = se_is_idle(se); 9816 pse_is_idle = se_is_idle(pse); 9817 9818 /* 9819 * Preempt an idle entity in favor of a non-idle entity (and don't preempt 9820 * in the inverse case). 9821 */ 9822 if (cse_is_idle && !pse_is_idle) { 9823 /* 9824 * When non-idle entity preempt an idle entity, 9825 * don't give idle entity slice protection. 9826 */ 9827 preempt_action = PREEMPT_WAKEUP_SHORT; 9828 goto preempt; 9829 } 9830 9831 if (cse_is_idle != pse_is_idle) 9832 return; 9833 9834 /* 9835 * BATCH and IDLE tasks do not preempt others. 9836 */ 9837 if (unlikely(!normal_policy(p->policy))) 9838 return; 9839 9840 cfs_rq = cfs_rq_of(se); 9841 update_curr(cfs_rq); 9842 /* 9843 * If @p has a shorter slice than current and @p is eligible, override 9844 * current's slice protection in order to allow preemption. 9845 */ 9846 if (sched_feat(PREEMPT_SHORT) && (pse->slice < se->slice)) { 9847 preempt_action = PREEMPT_WAKEUP_SHORT; 9848 goto pick; 9849 } 9850 9851 /* 9852 * Ignore wakee preemption on WF_FORK as it is less likely that 9853 * there is shared data as exec often follow fork. Do not 9854 * preempt for tasks that are sched_delayed as it would violate 9855 * EEVDF to forcibly queue an ineligible task. 9856 */ 9857 if ((wake_flags & WF_FORK) || pse->sched_delayed) 9858 return; 9859 9860 /* Prefer picking wakee soon if appropriate. */ 9861 if (sched_feat(NEXT_BUDDY) && 9862 set_preempt_buddy(cfs_rq, wake_flags, pse, se)) { 9863 9864 /* 9865 * Decide whether to obey WF_SYNC hint for a new buddy. Old 9866 * buddies are ignored as they may not be relevant to the 9867 * waker and less likely to be cache hot. 9868 */ 9869 if (wake_flags & WF_SYNC) 9870 preempt_action = preempt_sync(rq, wake_flags, pse, se); 9871 } 9872 9873 switch (preempt_action) { 9874 case PREEMPT_WAKEUP_NONE: 9875 return; 9876 case PREEMPT_WAKEUP_RESCHED: 9877 goto preempt; 9878 case PREEMPT_WAKEUP_SHORT: 9879 fallthrough; 9880 case PREEMPT_WAKEUP_PICK: 9881 break; 9882 } 9883 9884 pick: 9885 nse = pick_next_entity(rq, cfs_rq, preempt_action != PREEMPT_WAKEUP_SHORT); 9886 /* If @p has become the most eligible task, force preemption */ 9887 if (nse == pse) 9888 goto preempt; 9889 9890 /* 9891 * Because p is enqueued, nse being null can only mean that we 9892 * dequeued a delayed task. If there are still entities queued in 9893 * cfs, check if the next one will be p. 9894 */ 9895 if (!nse && cfs_rq->nr_queued) 9896 goto pick; 9897 9898 if (sched_feat(RUN_TO_PARITY)) 9899 update_protect_slice(cfs_rq, se); 9900 9901 return; 9902 9903 preempt: 9904 if (preempt_action == PREEMPT_WAKEUP_SHORT) { 9905 cancel_protect_slice(se); 9906 clear_buddies(cfs_rq, se); 9907 } 9908 9909 resched_curr_lazy(rq); 9910 } 9911 9912 struct task_struct *pick_task_fair(struct rq *rq, struct rq_flags *rf) 9913 __must_hold(__rq_lockp(rq)) 9914 { 9915 struct sched_entity *se; 9916 struct cfs_rq *cfs_rq; 9917 struct task_struct *p; 9918 bool throttled; 9919 int new_tasks; 9920 9921 again: 9922 cfs_rq = &rq->cfs; 9923 if (!cfs_rq->nr_queued) 9924 goto idle; 9925 9926 throttled = false; 9927 9928 do { 9929 /* Might not have done put_prev_entity() */ 9930 if (cfs_rq->curr && cfs_rq->curr->on_rq) 9931 update_curr(cfs_rq); 9932 9933 se = pick_next_entity(rq, cfs_rq, true); 9934 if (!se) 9935 goto again; 9936 cfs_rq = group_cfs_rq(se); 9937 } while (cfs_rq); 9938 9939 p = task_of(se); 9940 if (unlikely(throttled)) 9941 task_throttle_setup_work(p); 9942 return p; 9943 9944 idle: 9945 if (sched_core_enabled(rq)) 9946 return NULL; 9947 9948 new_tasks = sched_balance_newidle(rq, rf); 9949 if (new_tasks < 0) 9950 return RETRY_TASK; 9951 if (new_tasks > 0) 9952 goto again; 9953 return NULL; 9954 } 9955 9956 static struct task_struct * 9957 fair_server_pick_task(struct sched_dl_entity *dl_se, struct rq_flags *rf) 9958 __must_hold(__rq_lockp(dl_se->rq)) 9959 { 9960 return pick_task_fair(dl_se->rq, rf); 9961 } 9962 9963 void fair_server_init(struct rq *rq) 9964 { 9965 struct sched_dl_entity *dl_se = &rq->fair_server; 9966 9967 init_dl_entity(dl_se); 9968 9969 dl_server_init(dl_se, rq, fair_server_pick_task); 9970 } 9971 9972 /* 9973 * Account for a descheduled task: 9974 */ 9975 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev, struct task_struct *next) 9976 { 9977 struct sched_entity *se = &prev->se; 9978 struct cfs_rq *cfs_rq; 9979 struct sched_entity *nse = NULL; 9980 9981 #ifdef CONFIG_FAIR_GROUP_SCHED 9982 if (next && next->sched_class == &fair_sched_class) 9983 nse = &next->se; 9984 #endif 9985 9986 while (se) { 9987 cfs_rq = cfs_rq_of(se); 9988 if (!nse || cfs_rq->curr) 9989 put_prev_entity(cfs_rq, se); 9990 #ifdef CONFIG_FAIR_GROUP_SCHED 9991 if (nse) { 9992 if (is_same_group(se, nse)) 9993 break; 9994 9995 int d = nse->depth - se->depth; 9996 if (d >= 0) { 9997 /* nse has equal or greater depth, ascend */ 9998 nse = parent_entity(nse); 9999 /* if nse is the deeper, do not ascend se */ 10000 if (d > 0) 10001 continue; 10002 } 10003 } 10004 #endif 10005 se = parent_entity(se); 10006 } 10007 } 10008 10009 /* 10010 * sched_yield() is very simple 10011 */ 10012 static void yield_task_fair(struct rq *rq) 10013 { 10014 struct task_struct *curr = rq->donor; 10015 struct cfs_rq *cfs_rq = task_cfs_rq(curr); 10016 struct sched_entity *se = &curr->se; 10017 10018 /* 10019 * Are we the only task in the tree? 10020 */ 10021 if (unlikely(rq->nr_running == 1)) 10022 return; 10023 10024 clear_buddies(cfs_rq, se); 10025 10026 update_rq_clock(rq); 10027 /* 10028 * Update run-time statistics of the 'current'. 10029 */ 10030 update_curr(cfs_rq); 10031 /* 10032 * Tell update_rq_clock() that we've just updated, 10033 * so we don't do microscopic update in schedule() 10034 * and double the fastpath cost. 10035 */ 10036 rq_clock_skip_update(rq); 10037 10038 /* 10039 * Forfeit the remaining vruntime, only if the entity is eligible. This 10040 * condition is necessary because in core scheduling we prefer to run 10041 * ineligible tasks rather than force idling. If this happens we may 10042 * end up in a loop where the core scheduler picks the yielding task, 10043 * which yields immediately again; without the condition the vruntime 10044 * ends up quickly running away. 10045 */ 10046 if (entity_eligible(cfs_rq, se)) { 10047 se->vruntime = se->deadline; 10048 update_deadline(cfs_rq, se); 10049 } 10050 } 10051 10052 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p) 10053 { 10054 struct sched_entity *se = &p->se; 10055 10056 /* !se->on_rq also covers throttled task */ 10057 if (!se->on_rq) 10058 return false; 10059 10060 /* Tell the scheduler that we'd really like se to run next. */ 10061 set_next_buddy(se); 10062 10063 yield_task_fair(rq); 10064 10065 return true; 10066 } 10067 10068 /************************************************** 10069 * Fair scheduling class load-balancing methods. 10070 * 10071 * BASICS 10072 * 10073 * The purpose of load-balancing is to achieve the same basic fairness the 10074 * per-CPU scheduler provides, namely provide a proportional amount of compute 10075 * time to each task. This is expressed in the following equation: 10076 * 10077 * W_i,n/P_i == W_j,n/P_j for all i,j (1) 10078 * 10079 * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight 10080 * W_i,0 is defined as: 10081 * 10082 * W_i,0 = \Sum_j w_i,j (2) 10083 * 10084 * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight 10085 * is derived from the nice value as per sched_prio_to_weight[]. 10086 * 10087 * The weight average is an exponential decay average of the instantaneous 10088 * weight: 10089 * 10090 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3) 10091 * 10092 * C_i is the compute capacity of CPU i, typically it is the 10093 * fraction of 'recent' time available for SCHED_OTHER task execution. But it 10094 * can also include other factors [XXX]. 10095 * 10096 * To achieve this balance we define a measure of imbalance which follows 10097 * directly from (1): 10098 * 10099 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4) 10100 * 10101 * We them move tasks around to minimize the imbalance. In the continuous 10102 * function space it is obvious this converges, in the discrete case we get 10103 * a few fun cases generally called infeasible weight scenarios. 10104 * 10105 * [XXX expand on: 10106 * - infeasible weights; 10107 * - local vs global optima in the discrete case. ] 10108 * 10109 * 10110 * SCHED DOMAINS 10111 * 10112 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2) 10113 * for all i,j solution, we create a tree of CPUs that follows the hardware 10114 * topology where each level pairs two lower groups (or better). This results 10115 * in O(log n) layers. Furthermore we reduce the number of CPUs going up the 10116 * tree to only the first of the previous level and we decrease the frequency 10117 * of load-balance at each level inversely proportional to the number of CPUs in 10118 * the groups. 10119 * 10120 * This yields: 10121 * 10122 * log_2 n 1 n 10123 * \Sum { --- * --- * 2^i } = O(n) (5) 10124 * i = 0 2^i 2^i 10125 * `- size of each group 10126 * | | `- number of CPUs doing load-balance 10127 * | `- freq 10128 * `- sum over all levels 10129 * 10130 * Coupled with a limit on how many tasks we can migrate every balance pass, 10131 * this makes (5) the runtime complexity of the balancer. 10132 * 10133 * An important property here is that each CPU is still (indirectly) connected 10134 * to every other CPU in at most O(log n) steps: 10135 * 10136 * The adjacency matrix of the resulting graph is given by: 10137 * 10138 * log_2 n 10139 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6) 10140 * k = 0 10141 * 10142 * And you'll find that: 10143 * 10144 * A^(log_2 n)_i,j != 0 for all i,j (7) 10145 * 10146 * Showing there's indeed a path between every CPU in at most O(log n) steps. 10147 * The task movement gives a factor of O(m), giving a convergence complexity 10148 * of: 10149 * 10150 * O(nm log n), n := nr_cpus, m := nr_tasks (8) 10151 * 10152 * 10153 * WORK CONSERVING 10154 * 10155 * In order to avoid CPUs going idle while there's still work to do, new idle 10156 * balancing is more aggressive and has the newly idle CPU iterate up the domain 10157 * tree itself instead of relying on other CPUs to bring it work. 10158 * 10159 * This adds some complexity to both (5) and (8) but it reduces the total idle 10160 * time. 10161 * 10162 * [XXX more?] 10163 * 10164 * 10165 * CGROUPS 10166 * 10167 * Cgroups make a horror show out of (2), instead of a simple sum we get: 10168 * 10169 * s_k,i 10170 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9) 10171 * S_k 10172 * 10173 * Where 10174 * 10175 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10) 10176 * 10177 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i. 10178 * 10179 * The big problem is S_k, its a global sum needed to compute a local (W_i) 10180 * property. 10181 * 10182 * [XXX write more on how we solve this.. _after_ merging pjt's patches that 10183 * rewrite all of this once again.] 10184 */ 10185 10186 static unsigned long __read_mostly max_load_balance_interval = HZ/10; 10187 10188 enum fbq_type { regular, remote, all }; 10189 10190 /* 10191 * 'group_type' describes the group of CPUs at the moment of load balancing. 10192 * 10193 * The enum is ordered by pulling priority, with the group with lowest priority 10194 * first so the group_type can simply be compared when selecting the busiest 10195 * group. See update_sd_pick_busiest(). 10196 */ 10197 enum group_type { 10198 /* The group has spare capacity that can be used to run more tasks. */ 10199 group_has_spare = 0, 10200 /* 10201 * The group is fully used and the tasks don't compete for more CPU 10202 * cycles. Nevertheless, some tasks might wait before running. 10203 */ 10204 group_fully_busy, 10205 /* 10206 * One task doesn't fit with CPU's capacity and must be migrated to a 10207 * more powerful CPU. 10208 */ 10209 group_misfit_task, 10210 /* 10211 * Balance SMT group that's fully busy. Can benefit from migration 10212 * a task on SMT with busy sibling to another CPU on idle core. 10213 */ 10214 group_smt_balance, 10215 /* 10216 * SD_ASYM_PACKING only: One local CPU with higher capacity is available, 10217 * and the task should be migrated to it instead of running on the 10218 * current CPU. 10219 */ 10220 group_asym_packing, 10221 /* 10222 * The tasks' affinity constraints previously prevented the scheduler 10223 * from balancing the load across the system. 10224 */ 10225 group_imbalanced, 10226 /* 10227 * There are tasks running on non-preferred LLC, possible to move 10228 * them to their preferred LLC without creating too much imbalance. 10229 * The priority of group_llc_balance is lower than that of 10230 * group_overloaded and higher than that of all other group types. 10231 * This is because group_llc_balance may exacerbate load imbalance. 10232 * If the LLC balancing attempt fails, the nr_balance_failed 10233 * mechanism will trigger other group types to rebalance the load. 10234 */ 10235 group_llc_balance, 10236 /* 10237 * The CPU is overloaded and can't provide expected CPU cycles to all 10238 * tasks. 10239 */ 10240 group_overloaded 10241 }; 10242 10243 enum migration_type { 10244 migrate_load = 0, 10245 migrate_util, 10246 migrate_task, 10247 migrate_misfit, 10248 migrate_llc_task 10249 }; 10250 10251 #define LBF_ALL_PINNED 0x01 10252 #define LBF_NEED_BREAK 0x02 10253 #define LBF_DST_PINNED 0x04 10254 #define LBF_SOME_PINNED 0x08 10255 #define LBF_ACTIVE_LB 0x10 10256 #define LBF_LLC_PINNED 0x20 10257 10258 struct lb_env { 10259 struct sched_domain *sd; 10260 10261 struct rq *src_rq; 10262 int src_cpu; 10263 10264 int dst_cpu; 10265 struct rq *dst_rq; 10266 bool dst_core_idle; 10267 10268 struct cpumask *dst_grpmask; 10269 int new_dst_cpu; 10270 enum cpu_idle_type idle; 10271 long imbalance; 10272 /* The set of CPUs under consideration for load-balancing */ 10273 struct cpumask *cpus; 10274 10275 unsigned int flags; 10276 10277 unsigned int loop; 10278 unsigned int loop_break; 10279 unsigned int loop_max; 10280 10281 enum fbq_type fbq_type; 10282 enum migration_type migration_type; 10283 struct list_head tasks; 10284 }; 10285 10286 /* 10287 * Is this task likely cache-hot: 10288 */ 10289 static int task_hot(struct task_struct *p, struct lb_env *env) 10290 { 10291 s64 delta; 10292 10293 lockdep_assert_rq_held(env->src_rq); 10294 10295 if (p->sched_class != &fair_sched_class) 10296 return 0; 10297 10298 if (unlikely(task_has_idle_policy(p))) 10299 return 0; 10300 10301 /* SMT siblings share cache */ 10302 if (env->sd->flags & SD_SHARE_CPUCAPACITY) 10303 return 0; 10304 10305 /* 10306 * Buddy candidates are cache hot: 10307 */ 10308 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running && 10309 (&p->se == cfs_rq_of(&p->se)->next)) 10310 return 1; 10311 10312 if (sysctl_sched_migration_cost == -1) 10313 return 1; 10314 10315 /* 10316 * Don't migrate task if the task's cookie does not match 10317 * with the destination CPU's core cookie. 10318 */ 10319 if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p)) 10320 return 1; 10321 10322 if (sysctl_sched_migration_cost == 0) 10323 return 0; 10324 10325 delta = rq_clock_task(env->src_rq) - p->se.exec_start; 10326 10327 return delta < (s64)sysctl_sched_migration_cost; 10328 } 10329 10330 #ifdef CONFIG_NUMA_BALANCING 10331 /* 10332 * Returns a positive value, if task migration degrades locality. 10333 * Returns 0, if task migration is not affected by locality. 10334 * Returns a negative value, if task migration improves locality i.e migration preferred. 10335 */ 10336 static long migrate_degrades_locality(struct task_struct *p, struct lb_env *env) 10337 { 10338 struct numa_group *numa_group = rcu_dereference_all(p->numa_group); 10339 unsigned long src_weight, dst_weight; 10340 int src_nid, dst_nid, dist; 10341 10342 if (!static_branch_likely(&sched_numa_balancing)) 10343 return 0; 10344 10345 if (!p->numa_faults || !(env->sd->flags & SD_NUMA)) 10346 return 0; 10347 10348 src_nid = cpu_to_node(env->src_cpu); 10349 dst_nid = cpu_to_node(env->dst_cpu); 10350 10351 if (src_nid == dst_nid) 10352 return 0; 10353 10354 /* Migrating away from the preferred node is always bad. */ 10355 if (src_nid == p->numa_preferred_nid) { 10356 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running) 10357 return 1; 10358 else 10359 return 0; 10360 } 10361 10362 /* Encourage migration to the preferred node. */ 10363 if (dst_nid == p->numa_preferred_nid) 10364 return -1; 10365 10366 /* Leaving a core idle is often worse than degrading locality. */ 10367 if (env->idle == CPU_IDLE) 10368 return 0; 10369 10370 dist = node_distance(src_nid, dst_nid); 10371 if (numa_group) { 10372 src_weight = group_weight(p, src_nid, dist); 10373 dst_weight = group_weight(p, dst_nid, dist); 10374 } else { 10375 src_weight = task_weight(p, src_nid, dist); 10376 dst_weight = task_weight(p, dst_nid, dist); 10377 } 10378 10379 return src_weight - dst_weight; 10380 } 10381 10382 #else /* !CONFIG_NUMA_BALANCING: */ 10383 static inline long migrate_degrades_locality(struct task_struct *p, 10384 struct lb_env *env) 10385 { 10386 return 0; 10387 } 10388 #endif /* !CONFIG_NUMA_BALANCING */ 10389 10390 /* 10391 * Check whether the task is ineligible on the destination cpu 10392 * 10393 * When the PLACE_LAG scheduling feature is enabled and 10394 * dst_cfs_rq->nr_queued is greater than 1, if the task 10395 * is ineligible, it will also be ineligible when 10396 * it is migrated to the destination cpu. 10397 */ 10398 static inline int task_is_ineligible_on_dst_cpu(struct task_struct *p, int dest_cpu) 10399 { 10400 struct cfs_rq *dst_cfs_rq; 10401 10402 #ifdef CONFIG_FAIR_GROUP_SCHED 10403 dst_cfs_rq = tg_cfs_rq(task_group(p), dest_cpu); 10404 #else 10405 dst_cfs_rq = &cpu_rq(dest_cpu)->cfs; 10406 #endif 10407 if (sched_feat(PLACE_LAG) && dst_cfs_rq->nr_queued && 10408 !entity_eligible(task_cfs_rq(p), &p->se)) 10409 return 1; 10410 10411 return 0; 10412 } 10413 10414 #ifdef CONFIG_SCHED_CACHE 10415 /* 10416 * The margin used when comparing LLC utilization with CPU capacity. 10417 * It determines the LLC load level where active LLC aggregation is 10418 * done. 10419 * Derived from fits_capacity(). 10420 * 10421 * (default: ~50%, tunable via debugfs) 10422 */ 10423 static bool fits_llc_capacity(unsigned long util, unsigned long max) 10424 { 10425 u32 aggr_pct = llc_overaggr_pct; 10426 10427 /* 10428 * For single core systems, raise the aggregation 10429 * threshold to accommodate more tasks. 10430 */ 10431 if (cpu_smt_num_threads == 1) 10432 aggr_pct = (aggr_pct * 3 / 2); 10433 10434 return util * 100 < max * aggr_pct; 10435 } 10436 10437 /* 10438 * The margin used when comparing utilization. 10439 * is 'util1' noticeably greater than 'util2' 10440 * Derived from capacity_greater(). 10441 * Bias is in perentage. 10442 */ 10443 /* Allows dst util to be bigger than src util by up to bias percent */ 10444 #define util_greater(util1, util2) \ 10445 ((util1) * 100 > (util2) * (100 + llc_imb_pct)) 10446 10447 static __maybe_unused bool get_llc_stats(int cpu, unsigned long *util, 10448 unsigned long *cap) 10449 { 10450 struct sched_domain_shared *sd_share; 10451 10452 sd_share = rcu_dereference_all(per_cpu(sd_llc_shared, cpu)); 10453 if (!sd_share) 10454 return false; 10455 10456 *util = READ_ONCE(sd_share->util_avg); 10457 *cap = READ_ONCE(sd_share->capacity); 10458 10459 return true; 10460 } 10461 10462 /* 10463 * Decision matrix according to the LLC utilization. To 10464 * decide whether we can do task aggregation across LLC. 10465 * 10466 * By default, 50% is the threshold for treating the LLC 10467 * as busy. The reason for choosing 50% is to avoid saturation 10468 * of SMT-2, and it is also a safe cutoff for other SMT-n 10469 * platforms. SMT-1 has higher threshold because it is 10470 * supposed to accommodate more tasks, see fits_llc_capacity(). 10471 * 10472 * 20% is the utilization imbalance percentage to decide 10473 * if the preferred LLC is busier than the non-preferred LLC. 10474 * 20 is a little higher than the LLC domain's imbalance_pct 10475 * 17. The hysteresis is used to avoid task bouncing between the 10476 * preferred LLC and the non-preferred LLC, and it will 10477 * be turned into tunable debugfs. 10478 * 10479 * 1. moving towards the preferred LLC, dst is the preferred 10480 * LLC, src is not. 10481 * 10482 * src \ dst 30% 40% 50% 60% 10483 * 30% Y Y Y N 10484 * 40% Y Y Y Y 10485 * 50% Y Y G G 10486 * 60% Y Y G G 10487 * 10488 * 2. moving out of the preferred LLC, src is the preferred 10489 * LLC, dst is not: 10490 * 10491 * src \ dst 30% 40% 50% 60% 10492 * 30% N N N N 10493 * 40% N N N N 10494 * 50% N N G G 10495 * 60% Y N G G 10496 * 10497 * src : src_util 10498 * dst : dst_util 10499 * Y : Yes, migrate 10500 * N : No, do not migrate 10501 * G : let the Generic load balance to even the load. 10502 * 10503 * The intention is that if both LLCs are quite busy, cache aware 10504 * load balance should not be performed, and generic load balance 10505 * should take effect. However, if one is busy and the other is not, 10506 * the preferred LLC capacity(50%) and imbalance criteria(20%) should 10507 * be considered to determine whether LLC aggregation should be 10508 * performed to bias the load towards the preferred LLC. 10509 */ 10510 10511 /* migration decision, 3 states are orthogonal. */ 10512 enum llc_mig { 10513 mig_forbid = 0, /* N: Don't migrate task, respect LLC preference */ 10514 mig_llc, /* Y: Do LLC preference based migration */ 10515 mig_unrestricted /* G: Don't restrict generic load balance migration */ 10516 }; 10517 10518 /* 10519 * Check if task can be moved from the source LLC to the 10520 * destination LLC without breaking cache aware preferrence. 10521 * src_cpu and dst_cpu are arbitrary CPUs within the source 10522 * and destination LLCs, respectively. 10523 */ 10524 static enum llc_mig can_migrate_llc(int src_cpu, int dst_cpu, 10525 unsigned long tsk_util, 10526 bool to_pref) 10527 { 10528 unsigned long src_util, dst_util, src_cap, dst_cap; 10529 10530 if (!get_llc_stats(src_cpu, &src_util, &src_cap) || 10531 !get_llc_stats(dst_cpu, &dst_util, &dst_cap)) 10532 return mig_unrestricted; 10533 10534 src_util = src_util < tsk_util ? 0 : src_util - tsk_util; 10535 dst_util = dst_util + tsk_util; 10536 10537 if (!fits_llc_capacity(dst_util, dst_cap) && 10538 !fits_llc_capacity(src_util, src_cap)) 10539 return mig_unrestricted; 10540 10541 if (to_pref) { 10542 /* 10543 * Don't migrate if we will get preferred LLC too 10544 * heavily loaded and if the dest is much busier 10545 * than the src, in which case migration will 10546 * increase the imbalance too much. 10547 */ 10548 if (!fits_llc_capacity(dst_util, dst_cap) && 10549 util_greater(dst_util, src_util)) 10550 return mig_forbid; 10551 } else { 10552 /* 10553 * Don't migrate if we will leave preferred LLC 10554 * too idle, or if this migration leads to the 10555 * non-preferred LLC falls within sysctl_aggr_imb percent 10556 * of preferred LLC, leading to migration again 10557 * back to preferred LLC. 10558 */ 10559 if (fits_llc_capacity(src_util, src_cap) || 10560 !util_greater(src_util, dst_util)) 10561 return mig_forbid; 10562 } 10563 return mig_llc; 10564 } 10565 10566 /* 10567 * Check if task p can migrate from source LLC to 10568 * destination LLC in terms of cache aware load balance. 10569 */ 10570 static enum llc_mig can_migrate_llc_task(int src_cpu, int dst_cpu, 10571 struct task_struct *p) 10572 { 10573 struct mm_struct *mm; 10574 bool to_pref; 10575 int cpu; 10576 10577 mm = p->mm; 10578 if (!mm) 10579 return mig_unrestricted; 10580 10581 cpu = READ_ONCE(mm->sc_stat.cpu); 10582 if (cpu < 0 || cpus_share_cache(src_cpu, dst_cpu)) 10583 return mig_unrestricted; 10584 10585 /* skip cache aware load balance for too many threads */ 10586 if (invalid_llc_nr(mm, p, dst_cpu) || 10587 exceed_llc_capacity(mm, dst_cpu)) { 10588 if (READ_ONCE(mm->sc_stat.cpu) != -1) 10589 WRITE_ONCE(mm->sc_stat.cpu, -1); 10590 return mig_unrestricted; 10591 } 10592 10593 if (cpus_share_cache(dst_cpu, cpu)) 10594 to_pref = true; 10595 else if (cpus_share_cache(src_cpu, cpu)) 10596 to_pref = false; 10597 else 10598 return mig_unrestricted; 10599 10600 return can_migrate_llc(src_cpu, dst_cpu, 10601 task_util(p), to_pref); 10602 } 10603 10604 /* 10605 * Check if active load balance breaks LLC locality in 10606 * terms of cache aware load balance. The load level and 10607 * imbalance do not warrant breaking LLC preference per 10608 * the can_migrate_llc() policy. Here, the benefit of 10609 * LLC locality outweighs the power efficiency gained from 10610 * migrating the only runnable task away. 10611 */ 10612 static inline bool 10613 alb_break_llc(struct lb_env *env) 10614 { 10615 if (!sched_cache_enabled()) 10616 return false; 10617 10618 if (cpus_share_cache(env->src_cpu, env->dst_cpu)) 10619 return false; 10620 /* 10621 * All tasks prefer to stay on their current CPU. 10622 * Do not pull a task from its preferred CPU if: 10623 * 1. It is the only task running and does not exceed 10624 * imbalance allowance; OR 10625 * 2. Migrating it away from its preferred LLC would violate 10626 * the cache-aware scheduling policy. 10627 */ 10628 if (env->src_rq->nr_pref_llc_running && 10629 env->src_rq->nr_pref_llc_running == env->src_rq->cfs.h_nr_runnable) { 10630 unsigned long util = 0; 10631 struct task_struct *cur; 10632 10633 if (env->src_rq->nr_running <= 1) 10634 return true; 10635 10636 cur = rcu_dereference_all(env->src_rq->curr); 10637 if (cur && cur->sched_class == &fair_sched_class) 10638 util = task_util(cur); 10639 10640 if (can_migrate_llc(env->src_cpu, env->dst_cpu, 10641 util, false) == mig_forbid) 10642 return true; 10643 } 10644 10645 return false; 10646 } 10647 10648 /* 10649 * Check if migrating task p from env->src_cpu to 10650 * env->dst_cpu breaks LLC localiy. 10651 */ 10652 static bool migrate_degrades_llc(struct task_struct *p, struct lb_env *env) 10653 { 10654 if (!sched_cache_enabled()) 10655 return false; 10656 10657 if (task_has_sched_core(p)) 10658 return false; 10659 /* 10660 * Skip over tasks that would degrade LLC locality; 10661 * only when nr_balanced_failed is sufficiently high do we 10662 * ignore this constraint. 10663 * 10664 * Threshold of cache_nice_tries is set to 1 higher 10665 * than nr_balance_failed to avoid excessive task 10666 * migration at the same time. 10667 */ 10668 if (env->sd->nr_balance_failed >= env->sd->cache_nice_tries + 1) 10669 return false; 10670 10671 /* 10672 * We know the env->src_cpu has some tasks prefer to 10673 * run on env->dst_cpu, skip the tasks do not prefer 10674 * env->dst_cpu, and find the one that prefers. 10675 */ 10676 if (env->migration_type == migrate_llc_task && 10677 READ_ONCE(p->preferred_llc) != llc_id(env->dst_cpu)) 10678 return true; 10679 10680 if (can_migrate_llc_task(env->src_cpu, 10681 env->dst_cpu, p) != mig_forbid) 10682 return false; 10683 10684 return true; 10685 } 10686 10687 #else 10688 static inline bool get_llc_stats(int cpu, unsigned long *util, 10689 unsigned long *cap) 10690 { 10691 return false; 10692 } 10693 10694 static inline bool 10695 alb_break_llc(struct lb_env *env) 10696 { 10697 return false; 10698 } 10699 10700 static inline bool 10701 migrate_degrades_llc(struct task_struct *p, struct lb_env *env) 10702 { 10703 return false; 10704 } 10705 #endif 10706 /* 10707 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu? 10708 */ 10709 static 10710 int can_migrate_task(struct task_struct *p, struct lb_env *env) 10711 { 10712 long degrades, hot; 10713 10714 lockdep_assert_rq_held(env->src_rq); 10715 if (p->sched_task_hot) 10716 p->sched_task_hot = 0; 10717 10718 /* 10719 * We do not migrate tasks that are: 10720 * 1) delayed dequeued unless we migrate load, or 10721 * 2) target cfs_rq is in throttled hierarchy, or 10722 * 3) cannot be migrated to this CPU due to cpus_ptr, or 10723 * 4) running (obviously), or 10724 * 5) are cache-hot on their current CPU, or 10725 * 6) are blocked on mutexes (if SCHED_PROXY_EXEC is enabled) 10726 */ 10727 if ((p->se.sched_delayed) && (env->migration_type != migrate_load)) 10728 return 0; 10729 10730 if (lb_throttled_hierarchy(p, env->dst_cpu)) 10731 return 0; 10732 10733 /* 10734 * We want to prioritize the migration of eligible tasks. 10735 * For ineligible tasks we soft-limit them and only allow 10736 * them to migrate when nr_balance_failed is non-zero to 10737 * avoid load-balancing trying very hard to balance the load. 10738 */ 10739 if (!env->sd->nr_balance_failed && 10740 task_is_ineligible_on_dst_cpu(p, env->dst_cpu)) 10741 return 0; 10742 10743 /* Disregard percpu kthreads; they are where they need to be. */ 10744 if (kthread_is_per_cpu(p)) 10745 return 0; 10746 10747 if (task_is_blocked(p)) 10748 return 0; 10749 10750 if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) { 10751 int cpu; 10752 10753 schedstat_inc(p->stats.nr_failed_migrations_affine); 10754 10755 env->flags |= LBF_SOME_PINNED; 10756 10757 /* 10758 * Remember if this task can be migrated to any other CPU in 10759 * our sched_group. We may want to revisit it if we couldn't 10760 * meet load balance goals by pulling other tasks on src_cpu. 10761 * 10762 * Avoid computing new_dst_cpu 10763 * - for NEWLY_IDLE 10764 * - if we have already computed one in current iteration 10765 * - if it's an active balance 10766 */ 10767 if (env->idle == CPU_NEWLY_IDLE || 10768 env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB)) 10769 return 0; 10770 10771 /* Prevent to re-select dst_cpu via env's CPUs: */ 10772 cpu = cpumask_first_and_and(env->dst_grpmask, env->cpus, p->cpus_ptr); 10773 10774 if (cpu < nr_cpu_ids) { 10775 env->flags |= LBF_DST_PINNED; 10776 env->new_dst_cpu = cpu; 10777 } 10778 10779 return 0; 10780 } 10781 10782 /* Record that we found at least one task that could run on dst_cpu */ 10783 env->flags &= ~LBF_ALL_PINNED; 10784 10785 if (task_on_cpu(env->src_rq, p) || 10786 task_current_donor(env->src_rq, p)) { 10787 schedstat_inc(p->stats.nr_failed_migrations_running); 10788 return 0; 10789 } 10790 10791 /* 10792 * Aggressive migration if: 10793 * 1) active balance 10794 * 2) destination numa is preferred 10795 * 3) task is cache cold, or 10796 * 4) too many balance attempts have failed. 10797 */ 10798 if (env->flags & LBF_ACTIVE_LB) 10799 return 1; 10800 10801 degrades = migrate_degrades_locality(p, env); 10802 if (!degrades) { 10803 /* 10804 * If the NUMA locality is not broken, 10805 * further check if migration would hurt 10806 * LLC locality. 10807 */ 10808 if (migrate_degrades_llc(p, env)) { 10809 /* 10810 * If regular load balancing fails to pull a task 10811 * due to LLC locality, this is expected behavior 10812 * and we set LBF_LLC_PINNED so we don't increase 10813 * nr_balance_failed unecessarily. 10814 */ 10815 if (env->migration_type != migrate_llc_task) 10816 env->flags |= LBF_LLC_PINNED; 10817 10818 return 0; 10819 } 10820 10821 hot = task_hot(p, env); 10822 } else { 10823 hot = degrades > 0; 10824 } 10825 10826 if (!hot || env->sd->nr_balance_failed > env->sd->cache_nice_tries) { 10827 if (hot) 10828 p->sched_task_hot = 1; 10829 return 1; 10830 } 10831 10832 schedstat_inc(p->stats.nr_failed_migrations_hot); 10833 return 0; 10834 } 10835 10836 /* 10837 * detach_task() -- detach the task for the migration specified in env 10838 */ 10839 static void detach_task(struct task_struct *p, struct lb_env *env) 10840 { 10841 lockdep_assert_rq_held(env->src_rq); 10842 10843 if (p->sched_task_hot) { 10844 p->sched_task_hot = 0; 10845 schedstat_inc(env->sd->lb_hot_gained[env->idle]); 10846 schedstat_inc(p->stats.nr_forced_migrations); 10847 } 10848 10849 WARN_ON(task_current(env->src_rq, p)); 10850 WARN_ON(task_current_donor(env->src_rq, p)); 10851 10852 deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK); 10853 set_task_cpu(p, env->dst_cpu); 10854 } 10855 10856 /* 10857 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as 10858 * part of active balancing operations within "domain". 10859 * 10860 * Returns a task if successful and NULL otherwise. 10861 */ 10862 static struct task_struct *detach_one_task(struct lb_env *env) 10863 { 10864 struct task_struct *p; 10865 10866 lockdep_assert_rq_held(env->src_rq); 10867 10868 list_for_each_entry_reverse(p, 10869 &env->src_rq->cfs_tasks, se.group_node) { 10870 if (!can_migrate_task(p, env)) 10871 continue; 10872 10873 detach_task(p, env); 10874 10875 /* 10876 * Right now, this is only the second place where 10877 * lb_gained[env->idle] is updated (other is detach_tasks) 10878 * so we can safely collect stats here rather than 10879 * inside detach_tasks(). 10880 */ 10881 schedstat_inc(env->sd->lb_gained[env->idle]); 10882 return p; 10883 } 10884 return NULL; 10885 } 10886 10887 /* 10888 * detach_tasks() -- tries to detach up to imbalance load/util/tasks from 10889 * busiest_rq, as part of a balancing operation within domain "sd". 10890 * 10891 * Returns number of detached tasks if successful and 0 otherwise. 10892 */ 10893 static int detach_tasks(struct lb_env *env) 10894 { 10895 struct list_head *tasks = &env->src_rq->cfs_tasks; 10896 unsigned long util, load; 10897 struct task_struct *p; 10898 int detached = 0; 10899 10900 lockdep_assert_rq_held(env->src_rq); 10901 10902 /* 10903 * Source run queue has been emptied by another CPU, clear 10904 * LBF_ALL_PINNED flag as we will not test any task. 10905 */ 10906 if (env->src_rq->nr_running <= 1) { 10907 env->flags &= ~LBF_ALL_PINNED; 10908 return 0; 10909 } 10910 10911 if (env->imbalance <= 0) 10912 return 0; 10913 10914 while (!list_empty(tasks)) { 10915 /* 10916 * We don't want to steal all, otherwise we may be treated likewise, 10917 * which could at worst lead to a livelock crash. 10918 */ 10919 if (env->idle && env->src_rq->nr_running <= 1) 10920 break; 10921 10922 env->loop++; 10923 /* We've more or less seen every task there is, call it quits */ 10924 if (env->loop > env->loop_max) 10925 break; 10926 10927 /* take a breather every nr_migrate tasks */ 10928 if (env->loop > env->loop_break) { 10929 env->loop_break += SCHED_NR_MIGRATE_BREAK; 10930 env->flags |= LBF_NEED_BREAK; 10931 break; 10932 } 10933 10934 p = list_last_entry(tasks, struct task_struct, se.group_node); 10935 10936 if (!can_migrate_task(p, env)) 10937 goto next; 10938 10939 switch (env->migration_type) { 10940 case migrate_load: 10941 /* 10942 * Depending of the number of CPUs and tasks and the 10943 * cgroup hierarchy, task_h_load() can return a null 10944 * value. Make sure that env->imbalance decreases 10945 * otherwise detach_tasks() will stop only after 10946 * detaching up to loop_max tasks. 10947 */ 10948 load = max_t(unsigned long, task_h_load(p), 1); 10949 10950 if (sched_feat(LB_MIN) && 10951 load < 16 && !env->sd->nr_balance_failed) 10952 goto next; 10953 10954 /* 10955 * Make sure that we don't migrate too much load. 10956 * Nevertheless, let relax the constraint if 10957 * scheduler fails to find a good waiting task to 10958 * migrate. 10959 */ 10960 if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance) 10961 goto next; 10962 10963 env->imbalance -= load; 10964 break; 10965 10966 case migrate_util: 10967 util = task_util_est(p); 10968 10969 if (shr_bound(util, env->sd->nr_balance_failed) > env->imbalance) 10970 goto next; 10971 10972 env->imbalance -= util; 10973 break; 10974 10975 case migrate_task: 10976 env->imbalance--; 10977 break; 10978 10979 case migrate_misfit: 10980 /* This is not a misfit task */ 10981 if (task_fits_cpu(p, env->src_cpu)) 10982 goto next; 10983 10984 env->imbalance = 0; 10985 break; 10986 10987 case migrate_llc_task: 10988 env->imbalance--; 10989 break; 10990 } 10991 10992 detach_task(p, env); 10993 list_add(&p->se.group_node, &env->tasks); 10994 10995 detached++; 10996 10997 #ifdef CONFIG_PREEMPTION 10998 /* 10999 * NEWIDLE balancing is a source of latency, so preemptible 11000 * kernels will stop after the first task is detached to minimize 11001 * the critical section. 11002 */ 11003 if (env->idle == CPU_NEWLY_IDLE) 11004 break; 11005 #endif 11006 11007 /* 11008 * We only want to steal up to the prescribed amount of 11009 * load/util/tasks. 11010 */ 11011 if (env->imbalance <= 0) 11012 break; 11013 11014 continue; 11015 next: 11016 if (p->sched_task_hot) 11017 schedstat_inc(p->stats.nr_failed_migrations_hot); 11018 11019 list_move(&p->se.group_node, tasks); 11020 } 11021 11022 /* 11023 * Right now, this is one of only two places we collect this stat 11024 * so we can safely collect detach_one_task() stats here rather 11025 * than inside detach_one_task(). 11026 */ 11027 schedstat_add(env->sd->lb_gained[env->idle], detached); 11028 11029 return detached; 11030 } 11031 11032 /* 11033 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their 11034 * new rq. 11035 */ 11036 static void attach_tasks(struct lb_env *env) 11037 { 11038 struct list_head *tasks = &env->tasks; 11039 struct task_struct *p; 11040 struct rq_flags rf; 11041 11042 rq_lock(env->dst_rq, &rf); 11043 update_rq_clock(env->dst_rq); 11044 11045 while (!list_empty(tasks)) { 11046 p = list_first_entry(tasks, struct task_struct, se.group_node); 11047 list_del_init(&p->se.group_node); 11048 11049 attach_task(env->dst_rq, p); 11050 } 11051 11052 rq_unlock(env->dst_rq, &rf); 11053 } 11054 11055 #ifdef CONFIG_NO_HZ_COMMON 11056 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq) 11057 { 11058 if (cfs_rq->avg.load_avg) 11059 return true; 11060 11061 if (cfs_rq->avg.util_avg) 11062 return true; 11063 11064 return false; 11065 } 11066 11067 static inline bool others_have_blocked(struct rq *rq) 11068 { 11069 if (cpu_util_rt(rq)) 11070 return true; 11071 11072 if (cpu_util_dl(rq)) 11073 return true; 11074 11075 if (hw_load_avg(rq)) 11076 return true; 11077 11078 if (cpu_util_irq(rq)) 11079 return true; 11080 11081 return false; 11082 } 11083 11084 static inline void update_blocked_load_tick(struct rq *rq) 11085 { 11086 WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies); 11087 } 11088 11089 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load) 11090 { 11091 if (!has_blocked_load) 11092 rq->has_blocked_load = 0; 11093 } 11094 #else /* !CONFIG_NO_HZ_COMMON: */ 11095 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq) { return false; } 11096 static inline bool others_have_blocked(struct rq *rq) { return false; } 11097 static inline void update_blocked_load_tick(struct rq *rq) {} 11098 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load) {} 11099 #endif /* !CONFIG_NO_HZ_COMMON */ 11100 11101 static bool __update_blocked_others(struct rq *rq, bool *done) 11102 { 11103 bool updated; 11104 11105 /* 11106 * update_load_avg() can call cpufreq_update_util(). Make sure that RT, 11107 * DL and IRQ signals have been updated before updating CFS. 11108 */ 11109 updated = update_other_load_avgs(rq); 11110 11111 if (others_have_blocked(rq)) 11112 *done = false; 11113 11114 return updated; 11115 } 11116 11117 #ifdef CONFIG_FAIR_GROUP_SCHED 11118 11119 static bool __update_blocked_fair(struct rq *rq, bool *done) 11120 { 11121 struct cfs_rq *cfs_rq, *pos; 11122 bool decayed = false; 11123 11124 /* 11125 * Iterates the task_group tree in a bottom up fashion, see 11126 * list_add_leaf_cfs_rq() for details. 11127 */ 11128 for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) { 11129 struct sched_entity *se; 11130 11131 if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) { 11132 update_tg_load_avg(cfs_rq); 11133 11134 if (cfs_rq->nr_queued == 0) 11135 update_idle_cfs_rq_clock_pelt(cfs_rq); 11136 11137 if (cfs_rq == &rq->cfs) 11138 decayed = true; 11139 } 11140 11141 /* Propagate pending load changes to the parent, if any: */ 11142 se = cfs_rq_se(cfs_rq); 11143 if (se && !skip_blocked_update(se)) 11144 update_load_avg(cfs_rq_of(se), se, UPDATE_TG); 11145 11146 /* 11147 * There can be a lot of idle CPU cgroups. Don't let fully 11148 * decayed cfs_rqs linger on the list. 11149 */ 11150 if (cfs_rq_is_decayed(cfs_rq)) 11151 list_del_leaf_cfs_rq(cfs_rq); 11152 11153 /* Don't need periodic decay once load/util_avg are null */ 11154 if (cfs_rq_has_blocked_load(cfs_rq)) 11155 *done = false; 11156 } 11157 11158 return decayed; 11159 } 11160 11161 /* 11162 * Compute the hierarchical load factor for cfs_rq and all its ascendants. 11163 * This needs to be done in a top-down fashion because the load of a child 11164 * group is a fraction of its parents load. 11165 */ 11166 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq) 11167 { 11168 struct sched_entity *se = cfs_rq_se(cfs_rq); 11169 unsigned long now = jiffies; 11170 unsigned long load; 11171 11172 if (cfs_rq->last_h_load_update == now) 11173 return; 11174 11175 WRITE_ONCE(cfs_rq->h_load_next, NULL); 11176 for_each_sched_entity(se) { 11177 cfs_rq = cfs_rq_of(se); 11178 WRITE_ONCE(cfs_rq->h_load_next, se); 11179 if (cfs_rq->last_h_load_update == now) 11180 break; 11181 } 11182 11183 if (!se) { 11184 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq); 11185 cfs_rq->last_h_load_update = now; 11186 } 11187 11188 while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) { 11189 load = cfs_rq->h_load; 11190 load = div64_ul(load * se->avg.load_avg, 11191 cfs_rq_load_avg(cfs_rq) + 1); 11192 cfs_rq = group_cfs_rq(se); 11193 cfs_rq->h_load = load; 11194 cfs_rq->last_h_load_update = now; 11195 } 11196 } 11197 11198 static unsigned long task_h_load(struct task_struct *p) 11199 { 11200 struct cfs_rq *cfs_rq = task_cfs_rq(p); 11201 11202 update_cfs_rq_h_load(cfs_rq); 11203 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load, 11204 cfs_rq_load_avg(cfs_rq) + 1); 11205 } 11206 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 11207 static bool __update_blocked_fair(struct rq *rq, bool *done) 11208 { 11209 struct cfs_rq *cfs_rq = &rq->cfs; 11210 bool decayed; 11211 11212 decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq); 11213 if (cfs_rq_has_blocked_load(cfs_rq)) 11214 *done = false; 11215 11216 return decayed; 11217 } 11218 11219 static unsigned long task_h_load(struct task_struct *p) 11220 { 11221 return p->se.avg.load_avg; 11222 } 11223 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 11224 11225 static void __sched_balance_update_blocked_averages(struct rq *rq) 11226 { 11227 bool decayed = false, done = true; 11228 11229 update_blocked_load_tick(rq); 11230 11231 decayed |= __update_blocked_others(rq, &done); 11232 decayed |= __update_blocked_fair(rq, &done); 11233 11234 update_has_blocked_load_status(rq, !done); 11235 if (decayed) 11236 cpufreq_update_util(rq, 0); 11237 } 11238 11239 static void sched_balance_update_blocked_averages(int cpu) 11240 { 11241 struct rq *rq = cpu_rq(cpu); 11242 11243 guard(rq_lock_irqsave)(rq); 11244 update_rq_clock(rq); 11245 __sched_balance_update_blocked_averages(rq); 11246 } 11247 11248 /********** Helpers for sched_balance_find_src_group ************************/ 11249 11250 /* 11251 * sg_lb_stats - stats of a sched_group required for load-balancing: 11252 */ 11253 struct sg_lb_stats { 11254 unsigned long avg_load; /* Avg load over the CPUs of the group */ 11255 unsigned long group_load; /* Total load over the CPUs of the group */ 11256 unsigned long group_capacity; /* Capacity over the CPUs of the group */ 11257 unsigned long group_util; /* Total utilization over the CPUs of the group */ 11258 unsigned long group_runnable; /* Total runnable time over the CPUs of the group */ 11259 unsigned int sum_nr_running; /* Nr of all tasks running in the group */ 11260 unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */ 11261 unsigned int idle_cpus; /* Nr of idle CPUs in the group */ 11262 unsigned int group_weight; 11263 enum group_type group_type; 11264 unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */ 11265 unsigned int group_smt_balance; /* Task on busy SMT be moved */ 11266 unsigned int group_llc_balance; /* Tasks should be moved to preferred LLC */ 11267 unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */ 11268 unsigned int group_overutilized; /* At least one CPU is overutilized in the group */ 11269 #ifdef CONFIG_NUMA_BALANCING 11270 unsigned int nr_numa_running; 11271 unsigned int nr_preferred_running; 11272 #endif 11273 #ifdef CONFIG_SCHED_CACHE 11274 unsigned int nr_pref_dst_llc; 11275 #endif 11276 }; 11277 11278 /* 11279 * sd_lb_stats - stats of a sched_domain required for load-balancing: 11280 */ 11281 struct sd_lb_stats { 11282 struct sched_group *busiest; /* Busiest group in this sd */ 11283 struct sched_group *local; /* Local group in this sd */ 11284 unsigned long total_load; /* Total load of all groups in sd */ 11285 unsigned long total_capacity; /* Total capacity of all groups in sd */ 11286 unsigned long avg_load; /* Average load across all groups in sd */ 11287 unsigned int prefer_sibling; /* Tasks should go to sibling first */ 11288 11289 struct sg_lb_stats busiest_stat; /* Statistics of the busiest group */ 11290 struct sg_lb_stats local_stat; /* Statistics of the local group */ 11291 }; 11292 11293 static inline void init_sd_lb_stats(struct sd_lb_stats *sds) 11294 { 11295 /* 11296 * Skimp on the clearing to avoid duplicate work. We can avoid clearing 11297 * local_stat because update_sg_lb_stats() does a full clear/assignment. 11298 * We must however set busiest_stat::group_type and 11299 * busiest_stat::idle_cpus to the worst busiest group because 11300 * update_sd_pick_busiest() reads these before assignment. 11301 */ 11302 *sds = (struct sd_lb_stats){ 11303 .busiest = NULL, 11304 .local = NULL, 11305 .total_load = 0UL, 11306 .total_capacity = 0UL, 11307 .busiest_stat = { 11308 .idle_cpus = UINT_MAX, 11309 .group_type = group_has_spare, 11310 }, 11311 }; 11312 } 11313 11314 static unsigned long scale_rt_capacity(int cpu) 11315 { 11316 unsigned long max = get_actual_cpu_capacity(cpu); 11317 struct rq *rq = cpu_rq(cpu); 11318 unsigned long used, free; 11319 unsigned long irq; 11320 11321 irq = cpu_util_irq(rq); 11322 11323 if (unlikely(irq >= max)) 11324 return 1; 11325 11326 /* 11327 * avg_rt.util_avg and avg_dl.util_avg track binary signals 11328 * (running and not running) with weights 0 and 1024 respectively. 11329 */ 11330 used = cpu_util_rt(rq); 11331 used += cpu_util_dl(rq); 11332 11333 if (unlikely(used >= max)) 11334 return 1; 11335 11336 free = max - used; 11337 11338 return scale_irq_capacity(free, irq, max); 11339 } 11340 11341 static void update_cpu_capacity(struct sched_domain *sd, int cpu) 11342 { 11343 unsigned long capacity = scale_rt_capacity(cpu); 11344 struct sched_group *sdg = sd->groups; 11345 11346 if (!capacity) 11347 capacity = 1; 11348 11349 cpu_rq(cpu)->cpu_capacity = capacity; 11350 trace_sched_cpu_capacity_tp(cpu_rq(cpu)); 11351 11352 sdg->sgc->capacity = capacity; 11353 sdg->sgc->min_capacity = capacity; 11354 sdg->sgc->max_capacity = capacity; 11355 } 11356 11357 void update_group_capacity(struct sched_domain *sd, int cpu) 11358 { 11359 struct sched_domain *child = sd->child; 11360 struct sched_group *group, *sdg = sd->groups; 11361 unsigned long capacity, min_capacity, max_capacity; 11362 unsigned long interval; 11363 11364 interval = msecs_to_jiffies(sd->balance_interval); 11365 interval = clamp(interval, 1UL, max_load_balance_interval); 11366 sdg->sgc->next_update = jiffies + interval; 11367 11368 if (!child) { 11369 update_cpu_capacity(sd, cpu); 11370 return; 11371 } 11372 11373 capacity = 0; 11374 min_capacity = ULONG_MAX; 11375 max_capacity = 0; 11376 11377 if (child->flags & SD_NUMA) { 11378 /* 11379 * SD_NUMA domains cannot assume that child groups 11380 * span the current group. 11381 */ 11382 11383 for_each_cpu(cpu, sched_group_span(sdg)) { 11384 unsigned long cpu_cap = capacity_of(cpu); 11385 11386 capacity += cpu_cap; 11387 min_capacity = min(cpu_cap, min_capacity); 11388 max_capacity = max(cpu_cap, max_capacity); 11389 } 11390 } else { 11391 /* 11392 * !SD_NUMA domains can assume that child groups 11393 * span the current group. 11394 */ 11395 11396 group = child->groups; 11397 do { 11398 struct sched_group_capacity *sgc = group->sgc; 11399 11400 capacity += sgc->capacity; 11401 min_capacity = min(sgc->min_capacity, min_capacity); 11402 max_capacity = max(sgc->max_capacity, max_capacity); 11403 group = group->next; 11404 } while (group != child->groups); 11405 } 11406 11407 sdg->sgc->capacity = capacity; 11408 sdg->sgc->min_capacity = min_capacity; 11409 sdg->sgc->max_capacity = max_capacity; 11410 } 11411 11412 /* 11413 * Check whether the capacity of the rq has been noticeably reduced by side 11414 * activity. The imbalance_pct is used for the threshold. 11415 * Return true is the capacity is reduced 11416 */ 11417 static inline int 11418 check_cpu_capacity(struct rq *rq, struct sched_domain *sd) 11419 { 11420 return ((rq->cpu_capacity * sd->imbalance_pct) < 11421 (arch_scale_cpu_capacity(cpu_of(rq)) * 100)); 11422 } 11423 11424 /* Check if the rq has a misfit task */ 11425 static inline bool check_misfit_status(struct rq *rq) 11426 { 11427 return rq->misfit_task_load; 11428 } 11429 11430 /* 11431 * Group imbalance indicates (and tries to solve) the problem where balancing 11432 * groups is inadequate due to ->cpus_ptr constraints. 11433 * 11434 * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a 11435 * cpumask covering 1 CPU of the first group and 3 CPUs of the second group. 11436 * Something like: 11437 * 11438 * { 0 1 2 3 } { 4 5 6 7 } 11439 * * * * * 11440 * 11441 * If we were to balance group-wise we'd place two tasks in the first group and 11442 * two tasks in the second group. Clearly this is undesired as it will overload 11443 * cpu 3 and leave one of the CPUs in the second group unused. 11444 * 11445 * The current solution to this issue is detecting the skew in the first group 11446 * by noticing the lower domain failed to reach balance and had difficulty 11447 * moving tasks due to affinity constraints. 11448 * 11449 * When this is so detected; this group becomes a candidate for busiest; see 11450 * update_sd_pick_busiest(). And calculate_imbalance() and 11451 * sched_balance_find_src_group() avoid some of the usual balance conditions to allow it 11452 * to create an effective group imbalance. 11453 * 11454 * This is a somewhat tricky proposition since the next run might not find the 11455 * group imbalance and decide the groups need to be balanced again. A most 11456 * subtle and fragile situation. 11457 */ 11458 11459 static inline int sg_imbalanced(struct sched_group *group) 11460 { 11461 return group->sgc->imbalance; 11462 } 11463 11464 /* 11465 * group_has_capacity returns true if the group has spare capacity that could 11466 * be used by some tasks. 11467 * We consider that a group has spare capacity if the number of task is 11468 * smaller than the number of CPUs or if the utilization is lower than the 11469 * available capacity for CFS tasks. 11470 * For the latter, we use a threshold to stabilize the state, to take into 11471 * account the variance of the tasks' load and to return true if the available 11472 * capacity in meaningful for the load balancer. 11473 * As an example, an available capacity of 1% can appear but it doesn't make 11474 * any benefit for the load balance. 11475 */ 11476 static inline bool 11477 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs) 11478 { 11479 if (sgs->sum_nr_running < sgs->group_weight) 11480 return true; 11481 11482 if ((sgs->group_capacity * imbalance_pct) < 11483 (sgs->group_runnable * 100)) 11484 return false; 11485 11486 if ((sgs->group_capacity * 100) > 11487 (sgs->group_util * imbalance_pct)) 11488 return true; 11489 11490 return false; 11491 } 11492 11493 /* 11494 * group_is_overloaded returns true if the group has more tasks than it can 11495 * handle. 11496 * group_is_overloaded is not equals to !group_has_capacity because a group 11497 * with the exact right number of tasks, has no more spare capacity but is not 11498 * overloaded so both group_has_capacity and group_is_overloaded return 11499 * false. 11500 */ 11501 static inline bool 11502 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs) 11503 { 11504 /* 11505 * With EAS and uclamp, 1 CPU in the group must be overutilized to 11506 * consider the group overloaded. 11507 */ 11508 if (sched_energy_enabled() && !sgs->group_overutilized) 11509 return false; 11510 11511 if (sgs->sum_nr_running <= sgs->group_weight) 11512 return false; 11513 11514 if ((sgs->group_capacity * 100) < 11515 (sgs->group_util * imbalance_pct)) 11516 return true; 11517 11518 if ((sgs->group_capacity * imbalance_pct) < 11519 (sgs->group_runnable * 100)) 11520 return true; 11521 11522 return false; 11523 } 11524 11525 static inline enum 11526 group_type group_classify(unsigned int imbalance_pct, 11527 struct sched_group *group, 11528 struct sg_lb_stats *sgs) 11529 { 11530 if (group_is_overloaded(imbalance_pct, sgs)) 11531 return group_overloaded; 11532 11533 if (sgs->group_llc_balance) 11534 return group_llc_balance; 11535 11536 if (sg_imbalanced(group)) 11537 return group_imbalanced; 11538 11539 if (sgs->group_asym_packing) 11540 return group_asym_packing; 11541 11542 if (sgs->group_smt_balance) 11543 return group_smt_balance; 11544 11545 if (sgs->group_misfit_task_load) 11546 return group_misfit_task; 11547 11548 if (!group_has_capacity(imbalance_pct, sgs)) 11549 return group_fully_busy; 11550 11551 return group_has_spare; 11552 } 11553 11554 /** 11555 * sched_use_asym_prio - Check whether asym_packing priority must be used 11556 * @sd: The scheduling domain of the load balancing 11557 * @cpu: A CPU 11558 * 11559 * Always use CPU priority when balancing load between SMT siblings. When 11560 * balancing load between cores, it is not sufficient that @cpu is idle. Only 11561 * use CPU priority if the whole core is idle. 11562 * 11563 * Returns: True if the priority of @cpu must be followed. False otherwise. 11564 */ 11565 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu) 11566 { 11567 if (!(sd->flags & SD_ASYM_PACKING)) 11568 return false; 11569 11570 if (!sched_smt_active()) 11571 return true; 11572 11573 return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu); 11574 } 11575 11576 static inline bool sched_asym(struct sched_domain *sd, int dst_cpu, int src_cpu) 11577 { 11578 /* 11579 * First check if @dst_cpu can do asym_packing load balance. Only do it 11580 * if it has higher priority than @src_cpu. 11581 */ 11582 return sched_use_asym_prio(sd, dst_cpu) && 11583 sched_asym_prefer(dst_cpu, src_cpu); 11584 } 11585 11586 /** 11587 * sched_group_asym - Check if the destination CPU can do asym_packing balance 11588 * @env: The load balancing environment 11589 * @sgs: Load-balancing statistics of the candidate busiest group 11590 * @group: The candidate busiest group 11591 * 11592 * @env::dst_cpu can do asym_packing if it has higher priority than the 11593 * preferred CPU of @group. 11594 * 11595 * Return: true if @env::dst_cpu can do with asym_packing load balance. False 11596 * otherwise. 11597 */ 11598 static inline bool 11599 sched_group_asym(struct lb_env *env, struct sg_lb_stats *sgs, struct sched_group *group) 11600 { 11601 /* 11602 * CPU priorities do not make sense for SMT cores with more than one 11603 * busy sibling. 11604 */ 11605 if ((group->flags & SD_SHARE_CPUCAPACITY) && 11606 (sgs->group_weight - sgs->idle_cpus != 1)) 11607 return false; 11608 11609 return sched_asym(env->sd, env->dst_cpu, READ_ONCE(group->asym_prefer_cpu)); 11610 } 11611 11612 /* One group has more than one SMT CPU while the other group does not */ 11613 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1, 11614 struct sched_group *sg2) 11615 { 11616 if (!sg1 || !sg2) 11617 return false; 11618 11619 return (sg1->flags & SD_SHARE_CPUCAPACITY) != 11620 (sg2->flags & SD_SHARE_CPUCAPACITY); 11621 } 11622 11623 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs, 11624 struct sched_group *group) 11625 { 11626 if (!env->idle) 11627 return false; 11628 11629 /* 11630 * For SMT source group, it is better to move a task 11631 * to a CPU that doesn't have multiple tasks sharing its CPU capacity. 11632 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY 11633 * will not be on. 11634 */ 11635 if (group->flags & SD_SHARE_CPUCAPACITY && 11636 sgs->sum_h_nr_running > 1) 11637 return true; 11638 11639 return false; 11640 } 11641 11642 static inline long sibling_imbalance(struct lb_env *env, 11643 struct sd_lb_stats *sds, 11644 struct sg_lb_stats *busiest, 11645 struct sg_lb_stats *local) 11646 { 11647 int ncores_busiest, ncores_local; 11648 long imbalance; 11649 11650 if (!env->idle || !busiest->sum_nr_running) 11651 return 0; 11652 11653 ncores_busiest = sds->busiest->cores; 11654 ncores_local = sds->local->cores; 11655 11656 if (ncores_busiest == ncores_local) { 11657 imbalance = busiest->sum_nr_running; 11658 lsub_positive(&imbalance, local->sum_nr_running); 11659 return imbalance; 11660 } 11661 11662 /* Balance such that nr_running/ncores ratio are same on both groups */ 11663 imbalance = ncores_local * busiest->sum_nr_running; 11664 lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running); 11665 /* Normalize imbalance and do rounding on normalization */ 11666 imbalance = 2 * imbalance + ncores_local + ncores_busiest; 11667 imbalance /= ncores_local + ncores_busiest; 11668 11669 /* Take advantage of resource in an empty sched group */ 11670 if (imbalance <= 1 && local->sum_nr_running == 0 && 11671 busiest->sum_nr_running > 1) 11672 imbalance = 2; 11673 11674 return imbalance; 11675 } 11676 11677 static inline bool 11678 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd) 11679 { 11680 /* 11681 * When there is more than 1 task, the group_overloaded case already 11682 * takes care of cpu with reduced capacity 11683 */ 11684 if (rq->cfs.h_nr_runnable != 1) 11685 return false; 11686 11687 return check_cpu_capacity(rq, sd); 11688 } 11689 11690 #ifdef CONFIG_SCHED_CACHE 11691 /* 11692 * Record the statistics for this scheduler group for later 11693 * use. These values guide load balancing on aggregating tasks 11694 * to a LLC. 11695 */ 11696 static void record_sg_llc_stats(struct lb_env *env, 11697 struct sg_lb_stats *sgs, 11698 struct sched_group *group) 11699 { 11700 struct sched_domain_shared *sd_share; 11701 int cpu; 11702 11703 if (!sched_cache_enabled() || env->idle == CPU_NEWLY_IDLE) 11704 return; 11705 11706 /* Only care about sched domain spanning multiple LLCs */ 11707 if (env->sd->child != rcu_dereference_all(per_cpu(sd_llc, env->dst_cpu))) 11708 return; 11709 11710 /* 11711 * At this point we know this group spans a LLC domain. 11712 * Record the statistic of this group in its corresponding 11713 * shared LLC domain. 11714 * Note: sd_share cannot be obtained via sd->child->shared, 11715 * because the latter refers to the domain that covers the 11716 * local group. Instead, sd_share should be located using 11717 * the first CPU of the LLC group. 11718 */ 11719 cpu = cpumask_first(sched_group_span(group)); 11720 sd_share = rcu_dereference_all(per_cpu(sd_llc_shared, cpu)); 11721 if (!sd_share) 11722 return; 11723 11724 if (READ_ONCE(sd_share->util_avg) != sgs->group_util) 11725 WRITE_ONCE(sd_share->util_avg, sgs->group_util); 11726 11727 if (unlikely(READ_ONCE(sd_share->capacity) != sgs->group_capacity)) 11728 WRITE_ONCE(sd_share->capacity, sgs->group_capacity); 11729 } 11730 11731 /* 11732 * Do LLC balance on sched group that contains LLC, and have tasks preferring 11733 * to run on LLC in idle dst_cpu. 11734 */ 11735 static inline bool llc_balance(struct lb_env *env, struct sg_lb_stats *sgs, 11736 struct sched_group *group) 11737 { 11738 if (!sched_cache_enabled()) 11739 return false; 11740 11741 if (env->sd->flags & SD_SHARE_LLC) 11742 return false; 11743 11744 /* 11745 * Skip cache aware tagging if nr_balanced_failed is sufficiently high. 11746 * Threshold of cache_nice_tries is set to 1 higher than nr_balance_failed 11747 * to avoid excessive task migration at the same time. 11748 */ 11749 if (env->sd->nr_balance_failed >= env->sd->cache_nice_tries + 1) 11750 return false; 11751 11752 if (sgs->nr_pref_dst_llc && 11753 can_migrate_llc(cpumask_first(sched_group_span(group)), 11754 env->dst_cpu, 0, true) == mig_llc) 11755 return true; 11756 11757 return false; 11758 } 11759 11760 static bool update_llc_busiest(struct lb_env *env, 11761 struct sg_lb_stats *busiest, 11762 struct sg_lb_stats *sgs) 11763 { 11764 /* 11765 * There are more tasks that want to run on dst_cpu's LLC. 11766 */ 11767 return sgs->nr_pref_dst_llc > busiest->nr_pref_dst_llc; 11768 } 11769 #else 11770 static inline void record_sg_llc_stats(struct lb_env *env, struct sg_lb_stats *sgs, 11771 struct sched_group *group) 11772 { 11773 } 11774 11775 static inline bool llc_balance(struct lb_env *env, struct sg_lb_stats *sgs, 11776 struct sched_group *group) 11777 { 11778 return false; 11779 } 11780 11781 static bool update_llc_busiest(struct lb_env *env, 11782 struct sg_lb_stats *busiest, 11783 struct sg_lb_stats *sgs) 11784 { 11785 return false; 11786 } 11787 #endif 11788 11789 /** 11790 * update_sg_lb_stats - Update sched_group's statistics for load balancing. 11791 * @env: The load balancing environment. 11792 * @sds: Load-balancing data with statistics of the local group. 11793 * @group: sched_group whose statistics are to be updated. 11794 * @sgs: variable to hold the statistics for this group. 11795 * @sg_overloaded: sched_group is overloaded 11796 */ 11797 static inline void update_sg_lb_stats(struct lb_env *env, 11798 struct sd_lb_stats *sds, 11799 struct sched_group *group, 11800 struct sg_lb_stats *sgs, 11801 bool *sg_overloaded) 11802 { 11803 int i, nr_running, local_group, sd_flags = env->sd->flags; 11804 bool balancing_at_rd = !env->sd->parent; 11805 11806 memset(sgs, 0, sizeof(*sgs)); 11807 11808 local_group = group == sds->local; 11809 11810 for_each_cpu_and(i, sched_group_span(group), env->cpus) { 11811 struct rq *rq = cpu_rq(i); 11812 unsigned long load = cpu_load(rq); 11813 11814 sgs->group_load += load; 11815 sgs->group_util += cpu_util_cfs(i); 11816 sgs->group_runnable += cpu_runnable(rq); 11817 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable; 11818 11819 nr_running = rq->nr_running; 11820 sgs->sum_nr_running += nr_running; 11821 11822 if (cpu_overutilized(i)) 11823 sgs->group_overutilized = 1; 11824 11825 #ifdef CONFIG_SCHED_CACHE 11826 if (sched_cache_enabled()) { 11827 struct sched_domain *sd_tmp; 11828 int dst_llc; 11829 11830 dst_llc = llc_id(env->dst_cpu); 11831 if (llc_id(i) != dst_llc) { 11832 sd_tmp = rcu_dereference_all(rq->sd); 11833 if (sd_tmp && (unsigned int)dst_llc < sd_tmp->llc_max) 11834 sgs->nr_pref_dst_llc += sd_tmp->llc_counts[dst_llc]; 11835 } 11836 } 11837 #endif 11838 11839 /* 11840 * No need to call idle_cpu() if nr_running is not 0 11841 */ 11842 if (!nr_running && idle_cpu(i)) { 11843 sgs->idle_cpus++; 11844 /* Idle cpu can't have misfit task */ 11845 continue; 11846 } 11847 11848 /* Overload indicator is only updated at root domain */ 11849 if (balancing_at_rd && nr_running > 1) 11850 *sg_overloaded = 1; 11851 11852 #ifdef CONFIG_NUMA_BALANCING 11853 /* Only fbq_classify_group() uses this to classify NUMA groups */ 11854 if (sd_flags & SD_NUMA) { 11855 sgs->nr_numa_running += rq->nr_numa_running; 11856 sgs->nr_preferred_running += rq->nr_preferred_running; 11857 } 11858 #endif 11859 if (local_group) 11860 continue; 11861 11862 if (sd_flags & SD_ASYM_CPUCAPACITY) { 11863 /* Check for a misfit task on the cpu */ 11864 if (sgs->group_misfit_task_load < rq->misfit_task_load) { 11865 sgs->group_misfit_task_load = rq->misfit_task_load; 11866 *sg_overloaded = 1; 11867 } 11868 } else if (env->idle && sched_reduced_capacity(rq, env->sd)) { 11869 /* Check for a task running on a CPU with reduced capacity */ 11870 if (sgs->group_misfit_task_load < load) 11871 sgs->group_misfit_task_load = load; 11872 } 11873 } 11874 11875 sgs->group_capacity = group->sgc->capacity; 11876 11877 sgs->group_weight = group->group_weight; 11878 11879 if (!local_group) { 11880 /* Check if dst CPU is idle and preferred to this group */ 11881 if (env->idle && sgs->sum_h_nr_running && 11882 sched_group_asym(env, sgs, group)) 11883 sgs->group_asym_packing = 1; 11884 11885 /* Check for loaded SMT group to be balanced to dst CPU */ 11886 if (smt_balance(env, sgs, group)) 11887 sgs->group_smt_balance = 1; 11888 11889 /* Check for tasks in this group can be moved to their preferred LLC */ 11890 if (llc_balance(env, sgs, group)) 11891 sgs->group_llc_balance = 1; 11892 } 11893 11894 sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs); 11895 11896 record_sg_llc_stats(env, sgs, group); 11897 /* Computing avg_load makes sense only when group is overloaded */ 11898 if (sgs->group_type == group_overloaded) 11899 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) / 11900 sgs->group_capacity; 11901 } 11902 11903 /** 11904 * update_sd_pick_busiest - return 1 on busiest group 11905 * @env: The load balancing environment. 11906 * @sds: sched_domain statistics 11907 * @sg: sched_group candidate to be checked for being the busiest 11908 * @sgs: sched_group statistics 11909 * 11910 * Determine if @sg is a busier group than the previously selected 11911 * busiest group. 11912 * 11913 * Return: %true if @sg is a busier group than the previously selected 11914 * busiest group. %false otherwise. 11915 */ 11916 static bool update_sd_pick_busiest(struct lb_env *env, 11917 struct sd_lb_stats *sds, 11918 struct sched_group *sg, 11919 struct sg_lb_stats *sgs) 11920 { 11921 struct sg_lb_stats *busiest = &sds->busiest_stat; 11922 11923 /* Make sure that there is at least one task to pull */ 11924 if (!sgs->sum_h_nr_running) 11925 return false; 11926 11927 /* 11928 * Don't try to pull misfit tasks we can't help. 11929 * We can use max_capacity here as reduction in capacity on some 11930 * CPUs in the group should either be possible to resolve 11931 * internally or be covered by avg_load imbalance (eventually). 11932 * 11933 * When SMT is active, only pull a misfit to dst_cpu if it is on a 11934 * fully idle core; otherwise the effective capacity of the core is 11935 * reduced and we may not actually provide more capacity than the 11936 * source. 11937 */ 11938 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) && 11939 (sgs->group_type == group_misfit_task) && 11940 (!env->dst_core_idle || 11941 !capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) || 11942 sds->local_stat.group_type != group_has_spare)) 11943 return false; 11944 11945 if (sgs->group_type > busiest->group_type) 11946 return true; 11947 11948 if (sgs->group_type < busiest->group_type) 11949 return false; 11950 11951 /* 11952 * The candidate and the current busiest group are the same type of 11953 * group. Let check which one is the busiest according to the type. 11954 */ 11955 11956 switch (sgs->group_type) { 11957 case group_overloaded: 11958 /* Select the overloaded group with highest avg_load. */ 11959 return sgs->avg_load > busiest->avg_load; 11960 11961 case group_llc_balance: 11962 /* Select the group with most tasks preferring dst LLC */ 11963 return update_llc_busiest(env, busiest, sgs); 11964 11965 case group_imbalanced: 11966 /* 11967 * Select the 1st imbalanced group as we don't have any way to 11968 * choose one more than another. 11969 */ 11970 return false; 11971 11972 case group_asym_packing: 11973 /* Prefer to move from lowest priority CPU's work */ 11974 return sched_asym_prefer(READ_ONCE(sds->busiest->asym_prefer_cpu), 11975 READ_ONCE(sg->asym_prefer_cpu)); 11976 11977 case group_misfit_task: 11978 /* 11979 * If we have more than one misfit sg go with the biggest 11980 * misfit. 11981 */ 11982 return sgs->group_misfit_task_load > busiest->group_misfit_task_load; 11983 11984 case group_smt_balance: 11985 /* 11986 * Check if we have spare CPUs on either SMT group to 11987 * choose has spare or fully busy handling. 11988 */ 11989 if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0) 11990 goto has_spare; 11991 11992 fallthrough; 11993 11994 case group_fully_busy: 11995 /* 11996 * Select the fully busy group with highest avg_load. In 11997 * theory, there is no need to pull task from such kind of 11998 * group because tasks have all compute capacity that they need 11999 * but we can still improve the overall throughput by reducing 12000 * contention when accessing shared HW resources. 12001 * 12002 * XXX for now avg_load is not computed and always 0 so we 12003 * select the 1st one, except if @sg is composed of SMT 12004 * siblings. 12005 */ 12006 12007 if (sgs->avg_load < busiest->avg_load) 12008 return false; 12009 12010 if (sgs->avg_load == busiest->avg_load) { 12011 /* 12012 * SMT sched groups need more help than non-SMT groups. 12013 * If @sg happens to also be SMT, either choice is good. 12014 */ 12015 if (sds->busiest->flags & SD_SHARE_CPUCAPACITY) 12016 return false; 12017 } 12018 12019 break; 12020 12021 case group_has_spare: 12022 /* 12023 * Do not pick sg with SMT CPUs over sg with pure CPUs, 12024 * as we do not want to pull task off SMT core with one task 12025 * and make the core idle. 12026 */ 12027 if (smt_vs_nonsmt_groups(sds->busiest, sg)) { 12028 if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1) 12029 return false; 12030 else 12031 return true; 12032 } 12033 has_spare: 12034 12035 /* 12036 * Select not overloaded group with lowest number of idle CPUs 12037 * and highest number of running tasks. We could also compare 12038 * the spare capacity which is more stable but it can end up 12039 * that the group has less spare capacity but finally more idle 12040 * CPUs which means less opportunity to pull tasks. 12041 */ 12042 if (sgs->idle_cpus > busiest->idle_cpus) 12043 return false; 12044 else if ((sgs->idle_cpus == busiest->idle_cpus) && 12045 (sgs->sum_nr_running <= busiest->sum_nr_running)) 12046 return false; 12047 12048 break; 12049 } 12050 12051 /* 12052 * Candidate sg has no more than one task per CPU and has higher 12053 * per-CPU capacity. Migrating tasks to less capable CPUs may harm 12054 * throughput. Maximize throughput, power/energy consequences are not 12055 * considered. 12056 */ 12057 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) && 12058 (sgs->group_type <= group_fully_busy) && 12059 (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu)))) 12060 return false; 12061 12062 return true; 12063 } 12064 12065 #ifdef CONFIG_NUMA_BALANCING 12066 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs) 12067 { 12068 if (sgs->sum_h_nr_running > sgs->nr_numa_running) 12069 return regular; 12070 if (sgs->sum_h_nr_running > sgs->nr_preferred_running) 12071 return remote; 12072 return all; 12073 } 12074 12075 static inline enum fbq_type fbq_classify_rq(struct rq *rq) 12076 { 12077 if (rq->nr_running > rq->nr_numa_running) 12078 return regular; 12079 if (rq->nr_running > rq->nr_preferred_running) 12080 return remote; 12081 return all; 12082 } 12083 #else /* !CONFIG_NUMA_BALANCING: */ 12084 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs) 12085 { 12086 return all; 12087 } 12088 12089 static inline enum fbq_type fbq_classify_rq(struct rq *rq) 12090 { 12091 return regular; 12092 } 12093 #endif /* !CONFIG_NUMA_BALANCING */ 12094 12095 12096 struct sg_lb_stats; 12097 12098 /* 12099 * task_running_on_cpu - return 1 if @p is running on @cpu. 12100 */ 12101 12102 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p) 12103 { 12104 /* Task has no contribution or is new */ 12105 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 12106 return 0; 12107 12108 if (task_on_rq_queued(p)) 12109 return 1; 12110 12111 return 0; 12112 } 12113 12114 /** 12115 * idle_cpu_without - would a given CPU be idle without p ? 12116 * @cpu: the processor on which idleness is tested. 12117 * @p: task which should be ignored. 12118 * 12119 * Return: 1 if the CPU would be idle. 0 otherwise. 12120 */ 12121 static int idle_cpu_without(int cpu, struct task_struct *p) 12122 { 12123 struct rq *rq = cpu_rq(cpu); 12124 12125 if (rq->curr != rq->idle && rq->curr != p) 12126 return 0; 12127 12128 /* 12129 * rq->nr_running can't be used but an updated version without the 12130 * impact of p on cpu must be used instead. The updated nr_running 12131 * be computed and tested before calling idle_cpu_without(). 12132 */ 12133 12134 if (rq->ttwu_pending) 12135 return 0; 12136 12137 return 1; 12138 } 12139 12140 /* 12141 * update_sg_wakeup_stats - Update sched_group's statistics for wakeup. 12142 * @sd: The sched_domain level to look for idlest group. 12143 * @group: sched_group whose statistics are to be updated. 12144 * @sgs: variable to hold the statistics for this group. 12145 * @p: The task for which we look for the idlest group/CPU. 12146 */ 12147 static inline void update_sg_wakeup_stats(struct sched_domain *sd, 12148 struct sched_group *group, 12149 struct sg_lb_stats *sgs, 12150 struct task_struct *p) 12151 { 12152 int i, nr_running; 12153 12154 memset(sgs, 0, sizeof(*sgs)); 12155 12156 /* Assume that task can't fit any CPU of the group */ 12157 if (sd->flags & SD_ASYM_CPUCAPACITY) 12158 sgs->group_misfit_task_load = 1; 12159 12160 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) { 12161 struct rq *rq = cpu_rq(i); 12162 unsigned int local; 12163 12164 sgs->group_load += cpu_load_without(rq, p); 12165 sgs->group_util += cpu_util_without(i, p); 12166 sgs->group_runnable += cpu_runnable_without(rq, p); 12167 local = task_running_on_cpu(i, p); 12168 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable - local; 12169 12170 nr_running = rq->nr_running - local; 12171 sgs->sum_nr_running += nr_running; 12172 12173 /* 12174 * No need to call idle_cpu_without() if nr_running is not 0 12175 */ 12176 if (!nr_running && idle_cpu_without(i, p)) 12177 sgs->idle_cpus++; 12178 12179 /* Check if task fits in the CPU */ 12180 if (sd->flags & SD_ASYM_CPUCAPACITY && 12181 sgs->group_misfit_task_load && 12182 task_fits_cpu(p, i)) 12183 sgs->group_misfit_task_load = 0; 12184 12185 } 12186 12187 sgs->group_capacity = group->sgc->capacity; 12188 12189 sgs->group_weight = group->group_weight; 12190 12191 sgs->group_type = group_classify(sd->imbalance_pct, group, sgs); 12192 12193 /* 12194 * Computing avg_load makes sense only when group is fully busy or 12195 * overloaded 12196 */ 12197 if (sgs->group_type == group_fully_busy || 12198 sgs->group_type == group_overloaded) 12199 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) / 12200 sgs->group_capacity; 12201 } 12202 12203 static bool update_pick_idlest(struct sched_group *idlest, 12204 struct sg_lb_stats *idlest_sgs, 12205 struct sched_group *group, 12206 struct sg_lb_stats *sgs) 12207 { 12208 if (sgs->group_type < idlest_sgs->group_type) 12209 return true; 12210 12211 if (sgs->group_type > idlest_sgs->group_type) 12212 return false; 12213 12214 /* 12215 * The candidate and the current idlest group are the same type of 12216 * group. Let check which one is the idlest according to the type. 12217 */ 12218 12219 switch (sgs->group_type) { 12220 case group_overloaded: 12221 case group_fully_busy: 12222 /* Select the group with lowest avg_load. */ 12223 if (idlest_sgs->avg_load <= sgs->avg_load) 12224 return false; 12225 break; 12226 12227 case group_llc_balance: 12228 case group_imbalanced: 12229 case group_asym_packing: 12230 case group_smt_balance: 12231 /* Those types are not used in the slow wakeup path */ 12232 return false; 12233 12234 case group_misfit_task: 12235 /* Select group with the highest max capacity */ 12236 if (idlest->sgc->max_capacity >= group->sgc->max_capacity) 12237 return false; 12238 break; 12239 12240 case group_has_spare: 12241 /* Select group with most idle CPUs */ 12242 if (idlest_sgs->idle_cpus > sgs->idle_cpus) 12243 return false; 12244 12245 /* Select group with lowest group_util */ 12246 if (idlest_sgs->idle_cpus == sgs->idle_cpus && 12247 idlest_sgs->group_util <= sgs->group_util) 12248 return false; 12249 12250 break; 12251 } 12252 12253 return true; 12254 } 12255 12256 /* 12257 * sched_balance_find_dst_group() finds and returns the least busy CPU group within the 12258 * domain. 12259 * 12260 * Assumes p is allowed on at least one CPU in sd. 12261 */ 12262 static struct sched_group * 12263 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu) 12264 { 12265 struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups; 12266 struct sg_lb_stats local_sgs, tmp_sgs; 12267 struct sg_lb_stats *sgs; 12268 unsigned long imbalance; 12269 struct sg_lb_stats idlest_sgs = { 12270 .avg_load = UINT_MAX, 12271 .group_type = group_overloaded, 12272 }; 12273 12274 do { 12275 int local_group; 12276 12277 /* Skip over this group if it has no CPUs allowed */ 12278 if (!cpumask_intersects(sched_group_span(group), 12279 p->cpus_ptr)) 12280 continue; 12281 12282 /* Skip over this group if no cookie matched */ 12283 if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group)) 12284 continue; 12285 12286 local_group = cpumask_test_cpu(this_cpu, 12287 sched_group_span(group)); 12288 12289 if (local_group) { 12290 sgs = &local_sgs; 12291 local = group; 12292 } else { 12293 sgs = &tmp_sgs; 12294 } 12295 12296 update_sg_wakeup_stats(sd, group, sgs, p); 12297 12298 if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) { 12299 idlest = group; 12300 idlest_sgs = *sgs; 12301 } 12302 12303 } while (group = group->next, group != sd->groups); 12304 12305 12306 /* There is no idlest group to push tasks to */ 12307 if (!idlest) 12308 return NULL; 12309 12310 /* The local group has been skipped because of CPU affinity */ 12311 if (!local) 12312 return idlest; 12313 12314 /* 12315 * If the local group is idler than the selected idlest group 12316 * don't try and push the task. 12317 */ 12318 if (local_sgs.group_type < idlest_sgs.group_type) 12319 return NULL; 12320 12321 /* 12322 * If the local group is busier than the selected idlest group 12323 * try and push the task. 12324 */ 12325 if (local_sgs.group_type > idlest_sgs.group_type) 12326 return idlest; 12327 12328 switch (local_sgs.group_type) { 12329 case group_overloaded: 12330 case group_fully_busy: 12331 12332 /* Calculate allowed imbalance based on load */ 12333 imbalance = scale_load_down(NICE_0_LOAD) * 12334 (sd->imbalance_pct-100) / 100; 12335 12336 /* 12337 * When comparing groups across NUMA domains, it's possible for 12338 * the local domain to be very lightly loaded relative to the 12339 * remote domains but "imbalance" skews the comparison making 12340 * remote CPUs look much more favourable. When considering 12341 * cross-domain, add imbalance to the load on the remote node 12342 * and consider staying local. 12343 */ 12344 12345 if ((sd->flags & SD_NUMA) && 12346 ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load)) 12347 return NULL; 12348 12349 /* 12350 * If the local group is less loaded than the selected 12351 * idlest group don't try and push any tasks. 12352 */ 12353 if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance)) 12354 return NULL; 12355 12356 if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load) 12357 return NULL; 12358 break; 12359 12360 case group_llc_balance: 12361 case group_imbalanced: 12362 case group_asym_packing: 12363 case group_smt_balance: 12364 /* Those type are not used in the slow wakeup path */ 12365 return NULL; 12366 12367 case group_misfit_task: 12368 /* Select group with the highest max capacity */ 12369 if (local->sgc->max_capacity >= idlest->sgc->max_capacity) 12370 return NULL; 12371 break; 12372 12373 case group_has_spare: 12374 #ifdef CONFIG_NUMA 12375 if (sd->flags & SD_NUMA) { 12376 int imb_numa_nr = sd->imb_numa_nr; 12377 #ifdef CONFIG_NUMA_BALANCING 12378 int idlest_cpu; 12379 /* 12380 * If there is spare capacity at NUMA, try to select 12381 * the preferred node 12382 */ 12383 if (cpu_to_node(this_cpu) == p->numa_preferred_nid) 12384 return NULL; 12385 12386 idlest_cpu = cpumask_first(sched_group_span(idlest)); 12387 if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid) 12388 return idlest; 12389 #endif /* CONFIG_NUMA_BALANCING */ 12390 /* 12391 * Otherwise, keep the task close to the wakeup source 12392 * and improve locality if the number of running tasks 12393 * would remain below threshold where an imbalance is 12394 * allowed while accounting for the possibility the 12395 * task is pinned to a subset of CPUs. If there is a 12396 * real need of migration, periodic load balance will 12397 * take care of it. 12398 */ 12399 if (p->nr_cpus_allowed != NR_CPUS) { 12400 unsigned int w = cpumask_weight_and(p->cpus_ptr, 12401 sched_group_span(local)); 12402 imb_numa_nr = min(w, sd->imb_numa_nr); 12403 } 12404 12405 imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus); 12406 if (!adjust_numa_imbalance(imbalance, 12407 local_sgs.sum_nr_running + 1, 12408 imb_numa_nr)) { 12409 return NULL; 12410 } 12411 } 12412 #endif /* CONFIG_NUMA */ 12413 12414 /* 12415 * Select group with highest number of idle CPUs. We could also 12416 * compare the utilization which is more stable but it can end 12417 * up that the group has less spare capacity but finally more 12418 * idle CPUs which means more opportunity to run task. 12419 */ 12420 if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus) 12421 return NULL; 12422 break; 12423 } 12424 12425 return idlest; 12426 } 12427 12428 static void update_idle_cpu_scan(struct lb_env *env, 12429 unsigned long sum_util) 12430 { 12431 struct sched_domain_shared *sd_share; 12432 struct sched_domain *sd = env->sd; 12433 int llc_weight, pct; 12434 u64 x, y, tmp; 12435 /* 12436 * Update the number of CPUs to scan in LLC domain, which could 12437 * be used as a hint in select_idle_cpu(). The update of sd_share 12438 * could be expensive because it is within a shared cache line. 12439 * So the write of this hint only occurs during periodic load 12440 * balancing, rather than CPU_NEWLY_IDLE, because the latter 12441 * can fire way more frequently than the former. 12442 */ 12443 if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE) 12444 return; 12445 12446 sd_share = sd->shared; 12447 if (!sd_share) 12448 return; 12449 12450 /* 12451 * The number of CPUs to search drops as sum_util increases, when 12452 * sum_util hits 85% or above, the scan stops. 12453 * The reason to choose 85% as the threshold is because this is the 12454 * imbalance_pct(117) when a LLC sched group is overloaded. 12455 * 12456 * let y = SCHED_CAPACITY_SCALE - p * x^2 [1] 12457 * and y'= y / SCHED_CAPACITY_SCALE 12458 * 12459 * x is the ratio of sum_util compared to the CPU capacity: 12460 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE) 12461 * y' is the ratio of CPUs to be scanned in the LLC domain, 12462 * and the number of CPUs to scan is calculated by: 12463 * 12464 * nr_scan = llc_weight * y' [2] 12465 * 12466 * When x hits the threshold of overloaded, AKA, when 12467 * x = 100 / pct, y drops to 0. According to [1], 12468 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000 12469 * 12470 * Scale x by SCHED_CAPACITY_SCALE: 12471 * x' = sum_util / llc_weight; [3] 12472 * 12473 * and finally [1] becomes: 12474 * y = SCHED_CAPACITY_SCALE - 12475 * x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE) [4] 12476 * 12477 */ 12478 /* equation [3] */ 12479 x = sum_util; 12480 llc_weight = sd->span_weight; 12481 do_div(x, llc_weight); 12482 12483 /* equation [4] */ 12484 pct = sd->imbalance_pct; 12485 tmp = x * x * pct * pct; 12486 do_div(tmp, 10000 * SCHED_CAPACITY_SCALE); 12487 tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE); 12488 y = SCHED_CAPACITY_SCALE - tmp; 12489 12490 /* equation [2] */ 12491 y *= llc_weight; 12492 do_div(y, SCHED_CAPACITY_SCALE); 12493 if ((int)y != sd_share->nr_idle_scan) 12494 WRITE_ONCE(sd_share->nr_idle_scan, (int)y); 12495 } 12496 12497 /** 12498 * update_sd_lb_stats - Update sched_domain's statistics for load balancing. 12499 * @env: The load balancing environment. 12500 * @sds: variable to hold the statistics for this sched_domain. 12501 */ 12502 12503 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds) 12504 { 12505 struct sched_group *sg = env->sd->groups; 12506 struct sg_lb_stats *local = &sds->local_stat; 12507 struct sg_lb_stats tmp_sgs; 12508 unsigned long sum_util = 0; 12509 bool sg_overloaded = 0, sg_overutilized = 0; 12510 12511 env->dst_core_idle = !sched_smt_active() || is_core_idle(env->dst_cpu); 12512 12513 do { 12514 struct sg_lb_stats *sgs = &tmp_sgs; 12515 int local_group; 12516 12517 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg)); 12518 if (local_group) { 12519 sds->local = sg; 12520 sgs = local; 12521 12522 if (env->idle != CPU_NEWLY_IDLE || 12523 time_after_eq(jiffies, sg->sgc->next_update)) 12524 update_group_capacity(env->sd, env->dst_cpu); 12525 } 12526 12527 update_sg_lb_stats(env, sds, sg, sgs, &sg_overloaded); 12528 12529 if (!local_group && update_sd_pick_busiest(env, sds, sg, sgs)) { 12530 sds->busiest = sg; 12531 sds->busiest_stat = *sgs; 12532 } 12533 12534 sg_overutilized |= sgs->group_overutilized; 12535 12536 /* Now, start updating sd_lb_stats */ 12537 sds->total_load += sgs->group_load; 12538 sds->total_capacity += sgs->group_capacity; 12539 12540 sum_util += sgs->group_util; 12541 sg = sg->next; 12542 } while (sg != env->sd->groups); 12543 12544 /* 12545 * Indicate that the child domain of the busiest group prefers tasks 12546 * go to a child's sibling domains first. NB the flags of a sched group 12547 * are those of the child domain. 12548 */ 12549 if (sds->busiest) 12550 sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING); 12551 12552 12553 if (env->sd->flags & SD_NUMA) 12554 env->fbq_type = fbq_classify_group(&sds->busiest_stat); 12555 12556 if (!env->sd->parent) { 12557 /* update overload indicator if we are at root domain */ 12558 set_rd_overloaded(env->dst_rq->rd, sg_overloaded); 12559 12560 /* Update over-utilization (tipping point, U >= 0) indicator */ 12561 set_rd_overutilized(env->dst_rq->rd, sg_overutilized); 12562 } else if (sg_overutilized) { 12563 set_rd_overutilized(env->dst_rq->rd, sg_overutilized); 12564 } 12565 12566 update_idle_cpu_scan(env, sum_util); 12567 } 12568 12569 /** 12570 * calculate_imbalance - Calculate the amount of imbalance present within the 12571 * groups of a given sched_domain during load balance. 12572 * @env: load balance environment 12573 * @sds: statistics of the sched_domain whose imbalance is to be calculated. 12574 */ 12575 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds) 12576 { 12577 struct sg_lb_stats *local, *busiest; 12578 12579 local = &sds->local_stat; 12580 busiest = &sds->busiest_stat; 12581 12582 if (busiest->group_type == group_misfit_task) { 12583 if (env->sd->flags & SD_ASYM_CPUCAPACITY) { 12584 /* Set imbalance to allow misfit tasks to be balanced. */ 12585 env->migration_type = migrate_misfit; 12586 env->imbalance = 1; 12587 } else { 12588 /* 12589 * Set load imbalance to allow moving task from cpu 12590 * with reduced capacity. 12591 */ 12592 env->migration_type = migrate_load; 12593 env->imbalance = busiest->group_misfit_task_load; 12594 } 12595 return; 12596 } 12597 12598 if (busiest->group_type == group_asym_packing) { 12599 /* 12600 * In case of asym capacity, we will try to migrate all load to 12601 * the preferred CPU. 12602 */ 12603 env->migration_type = migrate_task; 12604 env->imbalance = busiest->sum_h_nr_running; 12605 return; 12606 } 12607 12608 if (busiest->group_type == group_smt_balance) { 12609 /* Reduce number of tasks sharing CPU capacity */ 12610 env->migration_type = migrate_task; 12611 env->imbalance = 1; 12612 return; 12613 } 12614 12615 #ifdef CONFIG_SCHED_CACHE 12616 if (busiest->group_type == group_llc_balance) { 12617 /* Move a task that prefer local LLC */ 12618 env->migration_type = migrate_llc_task; 12619 env->imbalance = 1; 12620 return; 12621 } 12622 #endif 12623 12624 if (busiest->group_type == group_imbalanced) { 12625 /* 12626 * In the group_imb case we cannot rely on group-wide averages 12627 * to ensure CPU-load equilibrium, try to move any task to fix 12628 * the imbalance. The next load balance will take care of 12629 * balancing back the system. 12630 */ 12631 env->migration_type = migrate_task; 12632 env->imbalance = 1; 12633 return; 12634 } 12635 12636 /* 12637 * Try to use spare capacity of local group without overloading it or 12638 * emptying busiest. 12639 */ 12640 if (local->group_type == group_has_spare) { 12641 if ((busiest->group_type > group_fully_busy) && 12642 !(env->sd->flags & SD_SHARE_LLC)) { 12643 /* 12644 * If busiest is overloaded, try to fill spare 12645 * capacity. This might end up creating spare capacity 12646 * in busiest or busiest still being overloaded but 12647 * there is no simple way to directly compute the 12648 * amount of load to migrate in order to balance the 12649 * system. 12650 */ 12651 env->migration_type = migrate_util; 12652 env->imbalance = max(local->group_capacity, local->group_util) - 12653 local->group_util; 12654 12655 /* 12656 * In some cases, the group's utilization is max or even 12657 * higher than capacity because of migrations but the 12658 * local CPU is (newly) idle. There is at least one 12659 * waiting task in this overloaded busiest group. Let's 12660 * try to pull it. 12661 */ 12662 if (env->idle && env->imbalance == 0) { 12663 env->migration_type = migrate_task; 12664 env->imbalance = 1; 12665 } 12666 12667 return; 12668 } 12669 12670 if (busiest->group_weight == 1 || sds->prefer_sibling) { 12671 /* 12672 * When prefer sibling, evenly spread running tasks on 12673 * groups. 12674 */ 12675 env->migration_type = migrate_task; 12676 env->imbalance = sibling_imbalance(env, sds, busiest, local); 12677 } else { 12678 12679 /* 12680 * If there is no overload, we just want to even the number of 12681 * idle CPUs. 12682 */ 12683 env->migration_type = migrate_task; 12684 env->imbalance = max_t(long, 0, 12685 (local->idle_cpus - busiest->idle_cpus)); 12686 } 12687 12688 #ifdef CONFIG_NUMA 12689 /* Consider allowing a small imbalance between NUMA groups */ 12690 if (env->sd->flags & SD_NUMA) { 12691 env->imbalance = adjust_numa_imbalance(env->imbalance, 12692 local->sum_nr_running + 1, 12693 env->sd->imb_numa_nr); 12694 } 12695 #endif 12696 12697 /* Number of tasks to move to restore balance */ 12698 env->imbalance >>= 1; 12699 12700 return; 12701 } 12702 12703 /* 12704 * Local is fully busy but has to take more load to relieve the 12705 * busiest group 12706 */ 12707 if (local->group_type < group_overloaded) { 12708 /* 12709 * Local will become overloaded so the avg_load metrics are 12710 * finally needed. 12711 */ 12712 12713 local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) / 12714 local->group_capacity; 12715 12716 /* 12717 * If the local group is more loaded than the selected 12718 * busiest group don't try to pull any tasks. 12719 */ 12720 if (local->avg_load >= busiest->avg_load) { 12721 env->imbalance = 0; 12722 return; 12723 } 12724 12725 sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) / 12726 sds->total_capacity; 12727 12728 /* 12729 * If the local group is more loaded than the average system 12730 * load, don't try to pull any tasks. 12731 */ 12732 if (local->avg_load >= sds->avg_load) { 12733 env->imbalance = 0; 12734 return; 12735 } 12736 12737 } 12738 12739 /* 12740 * Both group are or will become overloaded and we're trying to get all 12741 * the CPUs to the average_load, so we don't want to push ourselves 12742 * above the average load, nor do we wish to reduce the max loaded CPU 12743 * below the average load. At the same time, we also don't want to 12744 * reduce the group load below the group capacity. Thus we look for 12745 * the minimum possible imbalance. 12746 */ 12747 env->migration_type = migrate_load; 12748 env->imbalance = min( 12749 (busiest->avg_load - sds->avg_load) * busiest->group_capacity, 12750 (sds->avg_load - local->avg_load) * local->group_capacity 12751 ) / SCHED_CAPACITY_SCALE; 12752 } 12753 12754 /******* sched_balance_find_src_group() helpers end here *********************/ 12755 12756 /* 12757 * Decision matrix according to the local and busiest group type: 12758 * 12759 * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded 12760 * has_spare nr_idle balanced N/A N/A balanced balanced 12761 * fully_busy nr_idle nr_idle N/A N/A balanced balanced 12762 * misfit_task force N/A N/A N/A N/A N/A 12763 * asym_packing force force N/A N/A force force 12764 * imbalanced force force N/A N/A force force 12765 * overloaded force force N/A N/A force avg_load 12766 * 12767 * N/A : Not Applicable because already filtered while updating 12768 * statistics. 12769 * balanced : The system is balanced for these 2 groups. 12770 * force : Calculate the imbalance as load migration is probably needed. 12771 * avg_load : Only if imbalance is significant enough. 12772 * nr_idle : dst_cpu is not busy and the number of idle CPUs is quite 12773 * different in groups. 12774 */ 12775 12776 /** 12777 * sched_balance_find_src_group - Returns the busiest group within the sched_domain 12778 * if there is an imbalance. 12779 * @env: The load balancing environment. 12780 * 12781 * Also calculates the amount of runnable load which should be moved 12782 * to restore balance. 12783 * 12784 * Return: - The busiest group if imbalance exists. 12785 */ 12786 static struct sched_group *sched_balance_find_src_group(struct lb_env *env) 12787 { 12788 struct sg_lb_stats *local, *busiest; 12789 struct sd_lb_stats sds; 12790 12791 init_sd_lb_stats(&sds); 12792 12793 /* 12794 * Compute the various statistics relevant for load balancing at 12795 * this level. 12796 */ 12797 update_sd_lb_stats(env, &sds); 12798 12799 /* There is no busy sibling group to pull tasks from */ 12800 if (!sds.busiest) 12801 goto out_balanced; 12802 12803 busiest = &sds.busiest_stat; 12804 12805 /* Misfit tasks should be dealt with regardless of the avg load */ 12806 if (busiest->group_type == group_misfit_task) 12807 goto force_balance; 12808 12809 if (!is_rd_overutilized(env->dst_rq->rd) && 12810 rcu_dereference_all(env->dst_rq->rd->pd)) 12811 goto out_balanced; 12812 12813 /* ASYM feature bypasses nice load balance check */ 12814 if (busiest->group_type == group_asym_packing) 12815 goto force_balance; 12816 12817 /* 12818 * If the busiest group is imbalanced the below checks don't 12819 * work because they assume all things are equal, which typically 12820 * isn't true due to cpus_ptr constraints and the like. 12821 */ 12822 if (busiest->group_type == group_imbalanced) 12823 goto force_balance; 12824 12825 local = &sds.local_stat; 12826 /* 12827 * If the local group is busier than the selected busiest group 12828 * don't try and pull any tasks. 12829 */ 12830 if (local->group_type > busiest->group_type) 12831 goto out_balanced; 12832 12833 /* 12834 * When groups are overloaded, use the avg_load to ensure fairness 12835 * between tasks. 12836 */ 12837 if (local->group_type == group_overloaded) { 12838 /* 12839 * If the local group is more loaded than the selected 12840 * busiest group don't try to pull any tasks. 12841 */ 12842 if (local->avg_load >= busiest->avg_load) 12843 goto out_balanced; 12844 12845 /* XXX broken for overlapping NUMA groups */ 12846 sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) / 12847 sds.total_capacity; 12848 12849 /* 12850 * Don't pull any tasks if this group is already above the 12851 * domain average load. 12852 */ 12853 if (local->avg_load >= sds.avg_load) 12854 goto out_balanced; 12855 12856 /* 12857 * If the busiest group is more loaded, use imbalance_pct to be 12858 * conservative. 12859 */ 12860 if (100 * busiest->avg_load <= 12861 env->sd->imbalance_pct * local->avg_load) 12862 goto out_balanced; 12863 } 12864 12865 /* 12866 * Try to move all excess tasks to a sibling domain of the busiest 12867 * group's child domain. 12868 */ 12869 if (sds.prefer_sibling && local->group_type == group_has_spare && 12870 (busiest->group_type == group_llc_balance || 12871 sibling_imbalance(env, &sds, busiest, local) > 1)) 12872 goto force_balance; 12873 12874 if (busiest->group_type != group_overloaded) { 12875 if (!env->idle) { 12876 /* 12877 * If the busiest group is not overloaded (and as a 12878 * result the local one too) but this CPU is already 12879 * busy, let another idle CPU try to pull task. 12880 */ 12881 goto out_balanced; 12882 } 12883 12884 if (busiest->group_type == group_smt_balance && 12885 smt_vs_nonsmt_groups(sds.local, sds.busiest)) { 12886 /* Let non SMT CPU pull from SMT CPU sharing with sibling */ 12887 goto force_balance; 12888 } 12889 12890 if (busiest->group_weight > 1 && 12891 local->idle_cpus <= (busiest->idle_cpus + 1)) { 12892 /* 12893 * If the busiest group is not overloaded 12894 * and there is no imbalance between this and busiest 12895 * group wrt idle CPUs, it is balanced. The imbalance 12896 * becomes significant if the diff is greater than 1 12897 * otherwise we might end up to just move the imbalance 12898 * on another group. Of course this applies only if 12899 * there is more than 1 CPU per group. 12900 */ 12901 goto out_balanced; 12902 } 12903 12904 if (busiest->sum_h_nr_running == 1) { 12905 /* 12906 * busiest doesn't have any tasks waiting to run 12907 */ 12908 goto out_balanced; 12909 } 12910 } 12911 12912 force_balance: 12913 /* Looks like there is an imbalance. Compute it */ 12914 calculate_imbalance(env, &sds); 12915 return env->imbalance ? sds.busiest : NULL; 12916 12917 out_balanced: 12918 env->imbalance = 0; 12919 return NULL; 12920 } 12921 12922 /* 12923 * sched_balance_find_src_rq - find the busiest runqueue among the CPUs in the group. 12924 */ 12925 static struct rq *sched_balance_find_src_rq(struct lb_env *env, 12926 struct sched_group *group) 12927 { 12928 struct rq *busiest = NULL, *rq; 12929 unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1; 12930 unsigned int __maybe_unused busiest_pref_llc = 0; 12931 struct sched_domain __maybe_unused *sd_tmp; 12932 unsigned int busiest_nr = 0; 12933 int __maybe_unused dst_llc; 12934 int i; 12935 12936 for_each_cpu_and(i, sched_group_span(group), env->cpus) { 12937 unsigned long capacity, load, util; 12938 unsigned int nr_running; 12939 enum fbq_type rt; 12940 12941 rq = cpu_rq(i); 12942 rt = fbq_classify_rq(rq); 12943 12944 /* 12945 * We classify groups/runqueues into three groups: 12946 * - regular: there are !numa tasks 12947 * - remote: there are numa tasks that run on the 'wrong' node 12948 * - all: there is no distinction 12949 * 12950 * In order to avoid migrating ideally placed numa tasks, 12951 * ignore those when there's better options. 12952 * 12953 * If we ignore the actual busiest queue to migrate another 12954 * task, the next balance pass can still reduce the busiest 12955 * queue by moving tasks around inside the node. 12956 * 12957 * If we cannot move enough load due to this classification 12958 * the next pass will adjust the group classification and 12959 * allow migration of more tasks. 12960 * 12961 * Both cases only affect the total convergence complexity. 12962 */ 12963 if (rt > env->fbq_type) 12964 continue; 12965 12966 nr_running = rq->cfs.h_nr_runnable; 12967 if (!nr_running) 12968 continue; 12969 12970 capacity = capacity_of(i); 12971 12972 /* 12973 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could 12974 * eventually lead to active_balancing high->low capacity. 12975 * Higher per-CPU capacity is considered better than balancing 12976 * average load. 12977 */ 12978 if (env->sd->flags & SD_ASYM_CPUCAPACITY && 12979 !capacity_greater(capacity_of(env->dst_cpu), capacity) && 12980 nr_running == 1) 12981 continue; 12982 12983 /* 12984 * Make sure we only pull tasks from a CPU of lower priority 12985 * when balancing between SMT siblings. 12986 * 12987 * If balancing between cores, let lower priority CPUs help 12988 * SMT cores with more than one busy sibling. 12989 */ 12990 if (sched_asym(env->sd, i, env->dst_cpu) && nr_running == 1) 12991 continue; 12992 12993 switch (env->migration_type) { 12994 case migrate_load: 12995 /* 12996 * When comparing with load imbalance, use cpu_load() 12997 * which is not scaled with the CPU capacity. 12998 */ 12999 load = cpu_load(rq); 13000 13001 if (nr_running == 1 && load > env->imbalance && 13002 !check_cpu_capacity(rq, env->sd)) 13003 break; 13004 13005 /* 13006 * For the load comparisons with the other CPUs, 13007 * consider the cpu_load() scaled with the CPU 13008 * capacity, so that the load can be moved away 13009 * from the CPU that is potentially running at a 13010 * lower capacity. 13011 * 13012 * Thus we're looking for max(load_i / capacity_i), 13013 * crosswise multiplication to rid ourselves of the 13014 * division works out to: 13015 * load_i * capacity_j > load_j * capacity_i; 13016 * where j is our previous maximum. 13017 */ 13018 if (load * busiest_capacity > busiest_load * capacity) { 13019 busiest_load = load; 13020 busiest_capacity = capacity; 13021 busiest = rq; 13022 } 13023 break; 13024 13025 case migrate_util: 13026 util = cpu_util_cfs_boost(i); 13027 13028 /* 13029 * Don't try to pull utilization from a CPU with one 13030 * running task. Whatever its utilization, we will fail 13031 * detach the task. 13032 */ 13033 if (nr_running <= 1) 13034 continue; 13035 13036 if (busiest_util < util) { 13037 busiest_util = util; 13038 busiest = rq; 13039 } 13040 break; 13041 13042 case migrate_task: 13043 if (busiest_nr < nr_running) { 13044 busiest_nr = nr_running; 13045 busiest = rq; 13046 } 13047 break; 13048 13049 case migrate_misfit: 13050 /* 13051 * For ASYM_CPUCAPACITY domains with misfit tasks we 13052 * simply seek the "biggest" misfit task. 13053 */ 13054 if (rq->misfit_task_load > busiest_load) { 13055 busiest_load = rq->misfit_task_load; 13056 busiest = rq; 13057 } 13058 13059 break; 13060 13061 case migrate_llc_task: 13062 #ifdef CONFIG_SCHED_CACHE 13063 sd_tmp = rcu_dereference_all(rq->sd); 13064 dst_llc = llc_id(env->dst_cpu); 13065 13066 if (sd_tmp && (unsigned)dst_llc < sd_tmp->llc_max) { 13067 unsigned int this_pref_llc = 13068 sd_tmp->llc_counts[dst_llc]; 13069 13070 if (busiest_pref_llc < this_pref_llc) { 13071 busiest_pref_llc = this_pref_llc; 13072 busiest = rq; 13073 } 13074 } 13075 #endif 13076 break; 13077 13078 } 13079 } 13080 13081 return busiest; 13082 } 13083 13084 /* 13085 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but 13086 * so long as it is large enough. 13087 */ 13088 #define MAX_PINNED_INTERVAL 512 13089 13090 static inline bool 13091 asym_active_balance(struct lb_env *env) 13092 { 13093 /* 13094 * ASYM_PACKING needs to force migrate tasks from busy but lower 13095 * priority CPUs in order to pack all tasks in the highest priority 13096 * CPUs. When done between cores, do it only if the whole core if the 13097 * whole core is idle. 13098 * 13099 * If @env::src_cpu is an SMT core with busy siblings, let 13100 * the lower priority @env::dst_cpu help it. Do not follow 13101 * CPU priority. 13102 */ 13103 return env->idle && sched_use_asym_prio(env->sd, env->dst_cpu) && 13104 (sched_asym_prefer(env->dst_cpu, env->src_cpu) || 13105 !sched_use_asym_prio(env->sd, env->src_cpu)); 13106 } 13107 13108 static inline bool 13109 imbalanced_active_balance(struct lb_env *env) 13110 { 13111 struct sched_domain *sd = env->sd; 13112 13113 /* 13114 * The imbalanced case includes the case of pinned tasks preventing a fair 13115 * distribution of the load on the system but also the even distribution of the 13116 * threads on a system with spare capacity 13117 */ 13118 if ((env->migration_type == migrate_task) && 13119 (sd->nr_balance_failed > sd->cache_nice_tries+2)) 13120 return 1; 13121 13122 return 0; 13123 } 13124 13125 static int need_active_balance(struct lb_env *env) 13126 { 13127 struct sched_domain *sd = env->sd; 13128 13129 if (alb_break_llc(env)) 13130 return 0; 13131 13132 if (asym_active_balance(env)) 13133 return 1; 13134 13135 if (imbalanced_active_balance(env)) 13136 return 1; 13137 13138 /* 13139 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task. 13140 * It's worth migrating the task if the src_cpu's capacity is reduced 13141 * because of other sched_class or IRQs if more capacity stays 13142 * available on dst_cpu. 13143 */ 13144 if (env->idle && 13145 (env->src_rq->cfs.h_nr_runnable == 1)) { 13146 if ((check_cpu_capacity(env->src_rq, sd)) && 13147 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100)) 13148 return 1; 13149 } 13150 13151 if (env->migration_type == migrate_misfit || 13152 env->migration_type == migrate_llc_task) 13153 return 1; 13154 13155 return 0; 13156 } 13157 13158 static int active_load_balance_cpu_stop(void *data); 13159 13160 static int should_we_balance(struct lb_env *env) 13161 { 13162 struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask); 13163 struct sched_group *sg = env->sd->groups; 13164 int cpu, idle_smt = -1; 13165 13166 /* 13167 * Ensure the balancing environment is consistent; can happen 13168 * when the softirq triggers 'during' hotplug. 13169 */ 13170 if (!cpumask_test_cpu(env->dst_cpu, env->cpus)) 13171 return 0; 13172 13173 /* 13174 * In the newly idle case, we will allow all the CPUs 13175 * to do the newly idle load balance. 13176 * 13177 * However, we bail out if we already have tasks or a wakeup pending, 13178 * to optimize wakeup latency. 13179 */ 13180 if (env->idle == CPU_NEWLY_IDLE) { 13181 if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending) 13182 return 0; 13183 return 1; 13184 } 13185 13186 cpumask_copy(swb_cpus, group_balance_mask(sg)); 13187 /* Try to find first idle CPU */ 13188 for_each_cpu_and(cpu, swb_cpus, env->cpus) { 13189 if (!idle_cpu(cpu)) 13190 continue; 13191 13192 /* 13193 * Don't balance to idle SMT in busy core right away when 13194 * balancing cores, but remember the first idle SMT CPU for 13195 * later consideration. Find CPU on an idle core first. 13196 */ 13197 if (sched_smt_active() && 13198 !(env->sd->flags & SD_SHARE_CPUCAPACITY) && 13199 !is_core_idle(cpu)) { 13200 if (idle_smt == -1) 13201 idle_smt = cpu; 13202 /* 13203 * If the core is not idle, and first SMT sibling which is 13204 * idle has been found, then its not needed to check other 13205 * SMT siblings for idleness: 13206 */ 13207 cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu)); 13208 continue; 13209 } 13210 13211 /* 13212 * Are we the first idle core in a non-SMT domain or higher, 13213 * or the first idle CPU in a SMT domain? 13214 */ 13215 return cpu == env->dst_cpu; 13216 } 13217 13218 /* Are we the first idle CPU with busy siblings? */ 13219 if (idle_smt != -1) 13220 return idle_smt == env->dst_cpu; 13221 13222 /* Are we the first CPU of this group ? */ 13223 return group_balance_cpu(sg) == env->dst_cpu; 13224 } 13225 13226 static void update_lb_imbalance_stat(struct lb_env *env, struct sched_domain *sd, 13227 enum cpu_idle_type idle) 13228 { 13229 if (!schedstat_enabled()) 13230 return; 13231 13232 switch (env->migration_type) { 13233 case migrate_load: 13234 __schedstat_add(sd->lb_imbalance_load[idle], env->imbalance); 13235 break; 13236 case migrate_util: 13237 __schedstat_add(sd->lb_imbalance_util[idle], env->imbalance); 13238 break; 13239 case migrate_task: 13240 __schedstat_add(sd->lb_imbalance_task[idle], env->imbalance); 13241 break; 13242 case migrate_misfit: 13243 __schedstat_add(sd->lb_imbalance_misfit[idle], env->imbalance); 13244 break; 13245 case migrate_llc_task: 13246 break; 13247 } 13248 } 13249 13250 /* 13251 * This flag serializes load-balancing passes over large domains 13252 * (above the NODE topology level) - only one load-balancing instance 13253 * may run at a time, to reduce overhead on very large systems with 13254 * lots of CPUs and large NUMA distances. 13255 * 13256 * - Note that load-balancing passes triggered while another one 13257 * is executing are skipped and not re-tried. 13258 * 13259 * - Also note that this does not serialize rebalance_domains() 13260 * execution, as non-SD_SERIALIZE domains will still be 13261 * load-balanced in parallel. 13262 */ 13263 static atomic_t sched_balance_running = ATOMIC_INIT(0); 13264 13265 /* 13266 * Check this_cpu to ensure it is balanced within domain. Attempt to move 13267 * tasks if there is an imbalance. 13268 */ 13269 static int sched_balance_rq(int this_cpu, struct rq *this_rq, 13270 struct sched_domain *sd, enum cpu_idle_type idle, 13271 int *continue_balancing) 13272 { 13273 int ld_moved, cur_ld_moved, active_balance = 0; 13274 struct sched_domain *sd_parent = sd->parent; 13275 struct sched_group *group; 13276 struct rq *busiest; 13277 struct rq_flags rf; 13278 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask); 13279 struct lb_env env = { 13280 .sd = sd, 13281 .dst_cpu = this_cpu, 13282 .dst_rq = this_rq, 13283 .dst_grpmask = group_balance_mask(sd->groups), 13284 .idle = idle, 13285 .loop_break = SCHED_NR_MIGRATE_BREAK, 13286 .cpus = cpus, 13287 .fbq_type = all, 13288 .tasks = LIST_HEAD_INIT(env.tasks), 13289 }; 13290 bool need_unlock = false; 13291 13292 cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask); 13293 13294 schedstat_inc(sd->lb_count[idle]); 13295 13296 redo: 13297 if (!should_we_balance(&env)) { 13298 *continue_balancing = 0; 13299 goto out_balanced; 13300 } 13301 13302 if (!need_unlock && (sd->flags & SD_SERIALIZE)) { 13303 int zero = 0; 13304 if (!atomic_try_cmpxchg_acquire(&sched_balance_running, &zero, 1)) 13305 goto out_balanced; 13306 13307 need_unlock = true; 13308 } 13309 13310 group = sched_balance_find_src_group(&env); 13311 if (!group) { 13312 schedstat_inc(sd->lb_nobusyg[idle]); 13313 goto out_balanced; 13314 } 13315 13316 busiest = sched_balance_find_src_rq(&env, group); 13317 if (!busiest) { 13318 schedstat_inc(sd->lb_nobusyq[idle]); 13319 goto out_balanced; 13320 } 13321 13322 WARN_ON_ONCE(busiest == env.dst_rq); 13323 13324 update_lb_imbalance_stat(&env, sd, idle); 13325 13326 env.src_cpu = busiest->cpu; 13327 env.src_rq = busiest; 13328 13329 ld_moved = 0; 13330 /* Clear this flag as soon as we find a pullable task */ 13331 env.flags |= LBF_ALL_PINNED; 13332 if (busiest->nr_running > 1) { 13333 /* 13334 * Attempt to move tasks. If sched_balance_find_src_group has found 13335 * an imbalance but busiest->nr_running <= 1, the group is 13336 * still unbalanced. ld_moved simply stays zero, so it is 13337 * correctly treated as an imbalance. 13338 */ 13339 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running); 13340 13341 more_balance: 13342 rq_lock_irqsave(busiest, &rf); 13343 update_rq_clock(busiest); 13344 13345 /* 13346 * cur_ld_moved - load moved in current iteration 13347 * ld_moved - cumulative load moved across iterations 13348 */ 13349 cur_ld_moved = detach_tasks(&env); 13350 13351 /* 13352 * We've detached some tasks from busiest_rq. Every 13353 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely 13354 * unlock busiest->lock, and we are able to be sure 13355 * that nobody can manipulate the tasks in parallel. 13356 * See task_rq_lock() family for the details. 13357 */ 13358 13359 rq_unlock(busiest, &rf); 13360 13361 if (cur_ld_moved) { 13362 attach_tasks(&env); 13363 ld_moved += cur_ld_moved; 13364 } 13365 13366 local_irq_restore(rf.flags); 13367 13368 if (env.flags & LBF_NEED_BREAK) { 13369 env.flags &= ~LBF_NEED_BREAK; 13370 goto more_balance; 13371 } 13372 13373 /* 13374 * Revisit (affine) tasks on src_cpu that couldn't be moved to 13375 * us and move them to an alternate dst_cpu in our sched_group 13376 * where they can run. The upper limit on how many times we 13377 * iterate on same src_cpu is dependent on number of CPUs in our 13378 * sched_group. 13379 * 13380 * This changes load balance semantics a bit on who can move 13381 * load to a given_cpu. In addition to the given_cpu itself 13382 * (or a ilb_cpu acting on its behalf where given_cpu is 13383 * nohz-idle), we now have balance_cpu in a position to move 13384 * load to given_cpu. In rare situations, this may cause 13385 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding 13386 * _independently_ and at _same_ time to move some load to 13387 * given_cpu) causing excess load to be moved to given_cpu. 13388 * This however should not happen so much in practice and 13389 * moreover subsequent load balance cycles should correct the 13390 * excess load moved. 13391 */ 13392 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) { 13393 13394 /* Prevent to re-select dst_cpu via env's CPUs */ 13395 __cpumask_clear_cpu(env.dst_cpu, env.cpus); 13396 13397 env.dst_rq = cpu_rq(env.new_dst_cpu); 13398 env.dst_cpu = env.new_dst_cpu; 13399 env.flags &= ~LBF_DST_PINNED; 13400 env.loop = 0; 13401 env.loop_break = SCHED_NR_MIGRATE_BREAK; 13402 13403 /* 13404 * Go back to "more_balance" rather than "redo" since we 13405 * need to continue with same src_cpu. 13406 */ 13407 goto more_balance; 13408 } 13409 13410 /* 13411 * We failed to reach balance because of affinity. 13412 */ 13413 if (sd_parent) { 13414 int *group_imbalance = &sd_parent->groups->sgc->imbalance; 13415 13416 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0) 13417 *group_imbalance = 1; 13418 } 13419 13420 /* All tasks on this runqueue were pinned by CPU affinity */ 13421 if (unlikely(env.flags & LBF_ALL_PINNED)) { 13422 __cpumask_clear_cpu(cpu_of(busiest), cpus); 13423 /* 13424 * Attempting to continue load balancing at the current 13425 * sched_domain level only makes sense if there are 13426 * active CPUs remaining as possible busiest CPUs to 13427 * pull load from which are not contained within the 13428 * destination group that is receiving any migrated 13429 * load. 13430 */ 13431 if (!cpumask_subset(cpus, env.dst_grpmask)) { 13432 env.loop = 0; 13433 env.loop_break = SCHED_NR_MIGRATE_BREAK; 13434 goto redo; 13435 } 13436 goto out_all_pinned; 13437 } 13438 } 13439 13440 if (!ld_moved) { 13441 schedstat_inc(sd->lb_failed[idle]); 13442 /* 13443 * Increment the failure counter only on periodic balance. 13444 * We do not want newidle balance, which can be very 13445 * frequent, pollute the failure counter causing 13446 * excessive cache_hot migrations and active balances. 13447 * 13448 * Similarly for migration_misfit which is not related to 13449 * load/util migration, don't pollute nr_balance_failed. 13450 * 13451 * The same for cache aware scheduling's allowance for 13452 * load imbalance. If regular load balance does not 13453 * migrate task due to LLC locality, it is a expected 13454 * behavior and don't pollute nr_balance_failed. 13455 * See can_migrate_task(). 13456 */ 13457 if (idle != CPU_NEWLY_IDLE && 13458 env.migration_type != migrate_misfit && 13459 !(env.flags & LBF_LLC_PINNED)) 13460 sd->nr_balance_failed++; 13461 13462 if (need_active_balance(&env)) { 13463 unsigned long flags; 13464 13465 raw_spin_rq_lock_irqsave(busiest, flags); 13466 13467 /* 13468 * Don't kick the active_load_balance_cpu_stop, 13469 * if the curr task on busiest CPU can't be 13470 * moved to this_cpu: 13471 */ 13472 if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) { 13473 raw_spin_rq_unlock_irqrestore(busiest, flags); 13474 goto out_one_pinned; 13475 } 13476 13477 /* Record that we found at least one task that could run on this_cpu */ 13478 env.flags &= ~LBF_ALL_PINNED; 13479 13480 /* 13481 * ->active_balance synchronizes accesses to 13482 * ->active_balance_work. Once set, it's cleared 13483 * only after active load balance is finished. 13484 */ 13485 if (!busiest->active_balance) { 13486 busiest->active_balance = 1; 13487 busiest->push_cpu = this_cpu; 13488 active_balance = 1; 13489 } 13490 13491 preempt_disable(); 13492 raw_spin_rq_unlock_irqrestore(busiest, flags); 13493 if (active_balance) { 13494 stop_one_cpu_nowait(cpu_of(busiest), 13495 active_load_balance_cpu_stop, busiest, 13496 &busiest->active_balance_work); 13497 } 13498 preempt_enable(); 13499 } 13500 } else { 13501 sd->nr_balance_failed = 0; 13502 } 13503 13504 if (likely(!active_balance) || need_active_balance(&env)) { 13505 /* We were unbalanced, so reset the balancing interval */ 13506 sd->balance_interval = sd->min_interval; 13507 } 13508 13509 goto out; 13510 13511 out_balanced: 13512 /* 13513 * We reach balance although we may have faced some affinity 13514 * constraints. Clear the imbalance flag only if other tasks got 13515 * a chance to move and fix the imbalance. 13516 */ 13517 if (sd_parent && !(env.flags & LBF_ALL_PINNED)) { 13518 int *group_imbalance = &sd_parent->groups->sgc->imbalance; 13519 13520 if (*group_imbalance) 13521 *group_imbalance = 0; 13522 } 13523 13524 out_all_pinned: 13525 /* 13526 * We reach balance because all tasks are pinned at this level so 13527 * we can't migrate them. Let the imbalance flag set so parent level 13528 * can try to migrate them. 13529 */ 13530 schedstat_inc(sd->lb_balanced[idle]); 13531 13532 sd->nr_balance_failed = 0; 13533 13534 out_one_pinned: 13535 ld_moved = 0; 13536 13537 /* 13538 * sched_balance_newidle() disregards balance intervals, so we could 13539 * repeatedly reach this code, which would lead to balance_interval 13540 * skyrocketing in a short amount of time. Skip the balance_interval 13541 * increase logic to avoid that. 13542 * 13543 * Similarly misfit migration which is not necessarily an indication of 13544 * the system being busy and requires lb to backoff to let it settle 13545 * down. 13546 */ 13547 if (env.idle == CPU_NEWLY_IDLE || 13548 env.migration_type == migrate_misfit) 13549 goto out; 13550 13551 /* tune up the balancing interval */ 13552 if ((env.flags & LBF_ALL_PINNED && 13553 sd->balance_interval < MAX_PINNED_INTERVAL) || 13554 sd->balance_interval < sd->max_interval) 13555 sd->balance_interval *= 2; 13556 out: 13557 if (need_unlock) 13558 atomic_set_release(&sched_balance_running, 0); 13559 13560 return ld_moved; 13561 } 13562 13563 static inline unsigned long 13564 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy) 13565 { 13566 unsigned long interval = sd->balance_interval; 13567 13568 if (cpu_busy) 13569 interval *= sd->busy_factor; 13570 13571 /* scale ms to jiffies */ 13572 interval = msecs_to_jiffies(interval); 13573 13574 /* 13575 * Reduce likelihood of busy balancing at higher domains racing with 13576 * balancing at lower domains by preventing their balancing periods 13577 * from being multiples of each other. 13578 */ 13579 if (cpu_busy) 13580 interval -= 1; 13581 13582 interval = clamp(interval, 1UL, max_load_balance_interval); 13583 13584 return interval; 13585 } 13586 13587 static inline void 13588 update_next_balance(struct sched_domain *sd, unsigned long *next_balance) 13589 { 13590 unsigned long interval, next; 13591 13592 /* used by idle balance, so cpu_busy = 0 */ 13593 interval = get_sd_balance_interval(sd, 0); 13594 next = sd->last_balance + interval; 13595 13596 if (time_after(*next_balance, next)) 13597 *next_balance = next; 13598 } 13599 13600 /* 13601 * active_load_balance_cpu_stop is run by the CPU stopper. It pushes 13602 * running tasks off the busiest CPU onto idle CPUs. It requires at 13603 * least 1 task to be running on each physical CPU where possible, and 13604 * avoids physical / logical imbalances. 13605 */ 13606 static int active_load_balance_cpu_stop(void *data) 13607 { 13608 struct rq *busiest_rq = data; 13609 int busiest_cpu = cpu_of(busiest_rq); 13610 int target_cpu = busiest_rq->push_cpu; 13611 struct rq *target_rq = cpu_rq(target_cpu); 13612 struct sched_domain *sd; 13613 struct task_struct *p = NULL; 13614 struct rq_flags rf; 13615 13616 rq_lock_irq(busiest_rq, &rf); 13617 /* 13618 * Between queueing the stop-work and running it is a hole in which 13619 * CPUs can become inactive. We should not move tasks from or to 13620 * inactive CPUs. 13621 */ 13622 if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu)) 13623 goto out_unlock; 13624 13625 /* Make sure the requested CPU hasn't gone down in the meantime: */ 13626 if (unlikely(busiest_cpu != smp_processor_id() || 13627 !busiest_rq->active_balance)) 13628 goto out_unlock; 13629 13630 /* Is there any task to move? */ 13631 if (busiest_rq->nr_running <= 1) 13632 goto out_unlock; 13633 13634 /* 13635 * This condition is "impossible", if it occurs 13636 * we need to fix it. Originally reported by 13637 * Bjorn Helgaas on a 128-CPU setup. 13638 */ 13639 WARN_ON_ONCE(busiest_rq == target_rq); 13640 13641 /* Search for an sd spanning us and the target CPU. */ 13642 rcu_read_lock(); 13643 for_each_domain(target_cpu, sd) { 13644 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd))) 13645 break; 13646 } 13647 13648 if (likely(sd)) { 13649 struct lb_env env = { 13650 .sd = sd, 13651 .dst_cpu = target_cpu, 13652 .dst_rq = target_rq, 13653 .src_cpu = busiest_rq->cpu, 13654 .src_rq = busiest_rq, 13655 .idle = CPU_IDLE, 13656 .flags = LBF_ACTIVE_LB, 13657 }; 13658 13659 schedstat_inc(sd->alb_count); 13660 update_rq_clock(busiest_rq); 13661 13662 p = detach_one_task(&env); 13663 if (p) { 13664 schedstat_inc(sd->alb_pushed); 13665 /* Active balancing done, reset the failure counter. */ 13666 sd->nr_balance_failed = 0; 13667 } else { 13668 schedstat_inc(sd->alb_failed); 13669 } 13670 } 13671 rcu_read_unlock(); 13672 out_unlock: 13673 busiest_rq->active_balance = 0; 13674 rq_unlock(busiest_rq, &rf); 13675 13676 if (p) 13677 attach_one_task(target_rq, p); 13678 13679 local_irq_enable(); 13680 13681 return 0; 13682 } 13683 13684 /* 13685 * Scale the max sched_balance_rq interval with the number of CPUs in the system. 13686 * This trades load-balance latency on larger machines for less cross talk. 13687 */ 13688 void update_max_interval(void) 13689 { 13690 max_load_balance_interval = HZ*num_online_cpus()/10; 13691 } 13692 13693 static inline void update_newidle_stats(struct sched_domain *sd, unsigned int success) 13694 { 13695 sd->newidle_call++; 13696 sd->newidle_success += success; 13697 13698 if (sd->newidle_call >= 1024) { 13699 u64 now = sched_clock(); 13700 s64 delta = now - sd->newidle_stamp; 13701 sd->newidle_stamp = now; 13702 int ratio = 0; 13703 13704 if (delta < 0) 13705 delta = 0; 13706 13707 if (sched_feat(NI_RATE)) { 13708 /* 13709 * ratio delta freq 13710 * 13711 * 1024 - 4 s - 128 Hz 13712 * 512 - 2 s - 256 Hz 13713 * 256 - 1 s - 512 Hz 13714 * 128 - .5 s - 1024 Hz 13715 * 64 - .25 s - 2048 Hz 13716 */ 13717 ratio = delta >> 22; 13718 } 13719 13720 ratio += sd->newidle_success; 13721 13722 sd->newidle_ratio = min(1024, ratio); 13723 sd->newidle_call /= 2; 13724 sd->newidle_success /= 2; 13725 } 13726 } 13727 13728 static inline bool 13729 update_newidle_cost(struct sched_domain *sd, u64 cost, unsigned int success) 13730 { 13731 unsigned long next_decay = sd->last_decay_max_lb_cost + HZ; 13732 unsigned long now = jiffies; 13733 13734 if (cost) 13735 update_newidle_stats(sd, success); 13736 13737 if (cost > sd->max_newidle_lb_cost) { 13738 /* 13739 * Track max cost of a domain to make sure to not delay the 13740 * next wakeup on the CPU. 13741 */ 13742 sd->max_newidle_lb_cost = cost; 13743 sd->last_decay_max_lb_cost = now; 13744 13745 } else if (time_after(now, next_decay)) { 13746 /* 13747 * Decay the newidle max times by ~1% per second to ensure that 13748 * it is not outdated and the current max cost is actually 13749 * shorter. 13750 */ 13751 sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256; 13752 sd->last_decay_max_lb_cost = now; 13753 return true; 13754 } 13755 13756 return false; 13757 } 13758 13759 /* 13760 * It checks each scheduling domain to see if it is due to be balanced, 13761 * and initiates a balancing operation if so. 13762 * 13763 * Balancing parameters are set up in init_sched_domains. 13764 */ 13765 static void sched_balance_domains(struct rq *rq, enum cpu_idle_type idle) 13766 { 13767 int continue_balancing = 1; 13768 int cpu = rq->cpu; 13769 int busy = idle != CPU_IDLE && !sched_idle_rq(rq); 13770 unsigned long interval; 13771 struct sched_domain *sd; 13772 /* Earliest time when we have to do rebalance again */ 13773 unsigned long next_balance = jiffies + 60*HZ; 13774 int update_next_balance = 0; 13775 int need_decay = 0; 13776 u64 max_cost = 0; 13777 13778 rcu_read_lock(); 13779 for_each_domain(cpu, sd) { 13780 /* 13781 * Decay the newidle max times here because this is a regular 13782 * visit to all the domains. 13783 */ 13784 need_decay = update_newidle_cost(sd, 0, 0); 13785 max_cost += sd->max_newidle_lb_cost; 13786 13787 /* 13788 * Stop the load balance at this level. There is another 13789 * CPU in our sched group which is doing load balancing more 13790 * actively. 13791 */ 13792 if (!continue_balancing) { 13793 if (need_decay) 13794 continue; 13795 break; 13796 } 13797 13798 interval = get_sd_balance_interval(sd, busy); 13799 if (time_after_eq(jiffies, sd->last_balance + interval)) { 13800 if (sched_balance_rq(cpu, rq, sd, idle, &continue_balancing)) { 13801 /* 13802 * The LBF_DST_PINNED logic could have changed 13803 * env->dst_cpu, so we can't know our idle 13804 * state even if we migrated tasks. Update it. 13805 */ 13806 idle = idle_cpu(cpu); 13807 busy = !idle && !sched_idle_rq(rq); 13808 } 13809 sd->last_balance = jiffies; 13810 interval = get_sd_balance_interval(sd, busy); 13811 } 13812 if (time_after(next_balance, sd->last_balance + interval)) { 13813 next_balance = sd->last_balance + interval; 13814 update_next_balance = 1; 13815 } 13816 } 13817 if (need_decay) { 13818 /* 13819 * Ensure the rq-wide value also decays but keep it at a 13820 * reasonable floor to avoid funnies with rq->avg_idle. 13821 */ 13822 rq->max_idle_balance_cost = 13823 max((u64)sysctl_sched_migration_cost, max_cost); 13824 } 13825 rcu_read_unlock(); 13826 13827 /* 13828 * next_balance will be updated only when there is a need. 13829 * When the cpu is attached to null domain for ex, it will not be 13830 * updated. 13831 */ 13832 if (likely(update_next_balance)) 13833 rq->next_balance = next_balance; 13834 13835 } 13836 13837 static inline int on_null_domain(struct rq *rq) 13838 { 13839 return unlikely(!rcu_dereference_sched(rq->sd)); 13840 } 13841 13842 #ifdef CONFIG_NO_HZ_COMMON 13843 /* 13844 * NOHZ idle load balancing (ILB) details: 13845 * 13846 * - When one of the busy CPUs notices that there may be an idle rebalancing 13847 * needed, they will kick the idle load balancer, which then does idle 13848 * load balancing for all the idle CPUs. 13849 */ 13850 static inline int find_new_ilb(void) 13851 { 13852 int this_cpu = smp_processor_id(); 13853 const struct cpumask *hk_mask; 13854 int ilb_cpu; 13855 13856 hk_mask = housekeeping_cpumask(HK_TYPE_KERNEL_NOISE); 13857 13858 for_each_cpu_and(ilb_cpu, nohz.idle_cpus_mask, hk_mask) { 13859 if (ilb_cpu == this_cpu) 13860 continue; 13861 13862 if (idle_cpu(ilb_cpu)) 13863 return ilb_cpu; 13864 } 13865 13866 return -1; 13867 } 13868 13869 /* 13870 * Kick a CPU to do the NOHZ balancing, if it is time for it, via a cross-CPU 13871 * SMP function call (IPI). 13872 * 13873 * We pick the first idle CPU in the HK_TYPE_KERNEL_NOISE housekeeping set 13874 * (if there is one). 13875 */ 13876 static void kick_ilb(unsigned int flags) 13877 { 13878 int ilb_cpu; 13879 13880 /* 13881 * Increase nohz.next_balance only when if full ilb is triggered but 13882 * not if we only update stats. 13883 */ 13884 if (flags & NOHZ_BALANCE_KICK) 13885 nohz.next_balance = jiffies+1; 13886 13887 ilb_cpu = find_new_ilb(); 13888 if (ilb_cpu < 0) 13889 return; 13890 13891 /* 13892 * Don't bother if no new NOHZ balance work items for ilb_cpu, 13893 * i.e. all bits in flags are already set in ilb_cpu. 13894 */ 13895 if ((atomic_read(nohz_flags(ilb_cpu)) & flags) == flags) 13896 return; 13897 13898 /* 13899 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets 13900 * the first flag owns it; cleared by nohz_csd_func(). 13901 */ 13902 flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu)); 13903 if (flags & NOHZ_KICK_MASK) 13904 return; 13905 13906 /* 13907 * This way we generate an IPI on the target CPU which 13908 * is idle, and the softirq performing NOHZ idle load balancing 13909 * will be run before returning from the IPI. 13910 */ 13911 smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd); 13912 } 13913 13914 /* 13915 * Current decision point for kicking the idle load balancer in the presence 13916 * of idle CPUs in the system. 13917 */ 13918 static void nohz_balancer_kick(struct rq *rq) 13919 { 13920 unsigned long now = jiffies; 13921 struct sched_domain_shared *sds; 13922 struct sched_domain *sd; 13923 int nr_busy, i, cpu = rq->cpu; 13924 unsigned int flags = 0; 13925 13926 if (unlikely(rq->idle_balance)) 13927 return; 13928 13929 /* 13930 * We may be recently in ticked or tickless idle mode. At the first 13931 * busy tick after returning from idle, we will update the busy stats. 13932 */ 13933 nohz_balance_exit_idle(rq); 13934 13935 if (READ_ONCE(nohz.has_blocked_load) && 13936 time_after(now, READ_ONCE(nohz.next_blocked))) 13937 flags = NOHZ_STATS_KICK; 13938 13939 /* 13940 * Most of the time system is not 100% busy. i.e nohz.nr_cpus > 0 13941 * Skip the read if time is not due. 13942 * 13943 * If none are in tickless mode, there maybe a narrow window 13944 * (28 jiffies, HZ=1000) where flags maybe set and kick_ilb called. 13945 * But idle load balancing is not done as find_new_ilb fails. 13946 * That's very rare. So read nohz.nr_cpus only if time is due. 13947 */ 13948 if (time_before(now, nohz.next_balance)) 13949 goto out; 13950 13951 /* 13952 * None are in tickless mode and hence no need for NOHZ idle load 13953 * balancing 13954 */ 13955 if (unlikely(cpumask_empty(nohz.idle_cpus_mask))) 13956 return; 13957 13958 if (rq->nr_running >= 2) { 13959 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 13960 goto out; 13961 } 13962 13963 sd = rcu_dereference_all(rq->sd); 13964 if (sd) { 13965 /* 13966 * If there's a runnable CFS task and the current CPU has reduced 13967 * capacity, kick the ILB to see if there's a better CPU to run on: 13968 */ 13969 if (rq->cfs.h_nr_runnable >= 1 && check_cpu_capacity(rq, sd)) { 13970 flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 13971 goto out; 13972 } 13973 } 13974 13975 sd = rcu_dereference_all(per_cpu(sd_asym_packing, cpu)); 13976 if (sd) { 13977 /* 13978 * When ASYM_PACKING; see if there's a more preferred CPU 13979 * currently idle; in which case, kick the ILB to move tasks 13980 * around. 13981 * 13982 * When balancing between cores, all the SMT siblings of the 13983 * preferred CPU must be idle. 13984 */ 13985 for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) { 13986 if (sched_asym(sd, i, cpu)) { 13987 flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 13988 goto out; 13989 } 13990 } 13991 } 13992 13993 sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, cpu)); 13994 if (sd) { 13995 /* 13996 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU 13997 * to run the misfit task on. 13998 */ 13999 if (check_misfit_status(rq)) 14000 flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 14001 14002 /* 14003 * For asymmetric systems, we do not want to nicely balance 14004 * cache use, instead we want to embrace asymmetry and only 14005 * ensure tasks have enough CPU capacity. 14006 * 14007 * Skip the LLC logic because it's not relevant in that case. 14008 */ 14009 goto out; 14010 } 14011 14012 sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu)); 14013 if (sds) { 14014 /* 14015 * If there is an imbalance between LLC domains (IOW we could 14016 * increase the overall cache utilization), we need a less-loaded LLC 14017 * domain to pull some load from. Likewise, we may need to spread 14018 * load within the current LLC domain (e.g. packed SMT cores but 14019 * other CPUs are idle). We can't really know from here how busy 14020 * the others are - so just get a NOHZ balance going if it looks 14021 * like this LLC domain has tasks we could move. 14022 */ 14023 nr_busy = atomic_read(&sds->nr_busy_cpus); 14024 if (nr_busy > 1) 14025 flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 14026 } 14027 out: 14028 if (READ_ONCE(nohz.needs_update)) 14029 flags |= NOHZ_NEXT_KICK; 14030 14031 if (flags) 14032 kick_ilb(flags); 14033 } 14034 14035 static void set_cpu_sd_state_busy(int cpu) 14036 { 14037 struct sched_domain *sd; 14038 sd = rcu_dereference_all(per_cpu(sd_llc, cpu)); 14039 14040 /* 14041 * sd->nohz_idle only pairs with nr_busy_cpus on sd->shared; if this 14042 * domain has no shared object there is nothing to clear or account. 14043 */ 14044 if (!sd || !sd->shared || !sd->nohz_idle) 14045 return; 14046 sd->nohz_idle = 0; 14047 14048 atomic_inc(&sd->shared->nr_busy_cpus); 14049 } 14050 14051 void nohz_balance_exit_idle(struct rq *rq) 14052 { 14053 WARN_ON_ONCE(rq != this_rq()); 14054 14055 if (likely(!rq->nohz_tick_stopped)) 14056 return; 14057 14058 rq->nohz_tick_stopped = 0; 14059 cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask); 14060 14061 set_cpu_sd_state_busy(rq->cpu); 14062 } 14063 14064 static void set_cpu_sd_state_idle(int cpu) 14065 { 14066 struct sched_domain *sd; 14067 sd = rcu_dereference_all(per_cpu(sd_llc, cpu)); 14068 14069 /* See set_cpu_sd_state_busy(): nohz_idle is only used with sd->shared. */ 14070 if (!sd || !sd->shared || sd->nohz_idle) 14071 return; 14072 sd->nohz_idle = 1; 14073 14074 atomic_dec(&sd->shared->nr_busy_cpus); 14075 } 14076 14077 /* 14078 * This routine will record that the CPU is going idle with tick stopped. 14079 * This info will be used in performing idle load balancing in the future. 14080 */ 14081 void nohz_balance_enter_idle(int cpu) 14082 { 14083 struct rq *rq = cpu_rq(cpu); 14084 14085 WARN_ON_ONCE(cpu != smp_processor_id()); 14086 14087 /* If this CPU is going down, then nothing needs to be done: */ 14088 if (!cpu_active(cpu)) 14089 return; 14090 14091 /* 14092 * Can be set safely without rq->lock held 14093 * If a clear happens, it will have evaluated last additions because 14094 * rq->lock is held during the check and the clear 14095 */ 14096 rq->has_blocked_load = 1; 14097 14098 /* 14099 * The tick is still stopped but load could have been added in the 14100 * meantime. We set the nohz.has_blocked_load flag to trig a check of the 14101 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear 14102 * of nohz.has_blocked_load can only happen after checking the new load 14103 */ 14104 if (rq->nohz_tick_stopped) 14105 goto out; 14106 14107 /* If we're a completely isolated CPU, we don't play: */ 14108 if (on_null_domain(rq)) 14109 return; 14110 14111 rq->nohz_tick_stopped = 1; 14112 14113 cpumask_set_cpu(cpu, nohz.idle_cpus_mask); 14114 14115 /* 14116 * Ensures that if nohz_idle_balance() fails to observe our 14117 * @idle_cpus_mask store, it must observe the @has_blocked_load 14118 * and @needs_update stores. 14119 */ 14120 smp_mb__after_atomic(); 14121 14122 set_cpu_sd_state_idle(cpu); 14123 14124 WRITE_ONCE(nohz.needs_update, 1); 14125 out: 14126 /* 14127 * Each time a cpu enter idle, we assume that it has blocked load and 14128 * enable the periodic update of the load of idle CPUs 14129 */ 14130 WRITE_ONCE(nohz.has_blocked_load, 1); 14131 } 14132 14133 static bool update_nohz_stats(struct rq *rq) 14134 { 14135 unsigned int cpu = rq->cpu; 14136 14137 if (!rq->has_blocked_load) 14138 return false; 14139 14140 if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask)) 14141 return false; 14142 14143 if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick))) 14144 return true; 14145 14146 sched_balance_update_blocked_averages(cpu); 14147 14148 return rq->has_blocked_load; 14149 } 14150 14151 /* 14152 * Internal function that runs load balance for all idle CPUs. The load balance 14153 * can be a simple update of blocked load or a complete load balance with 14154 * tasks movement depending of flags. 14155 */ 14156 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags) 14157 { 14158 /* Earliest time when we have to do rebalance again */ 14159 unsigned long now = jiffies; 14160 unsigned long next_balance = now + 60*HZ; 14161 bool has_blocked_load = false; 14162 int update_next_balance = 0; 14163 int this_cpu = this_rq->cpu; 14164 int balance_cpu; 14165 struct rq *rq; 14166 14167 WARN_ON_ONCE((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK); 14168 14169 /* 14170 * We assume there will be no idle load after this update and clear 14171 * the has_blocked_load flag. If a cpu enters idle in the mean time, it will 14172 * set the has_blocked_load flag and trigger another update of idle load. 14173 * Because a cpu that becomes idle, is added to idle_cpus_mask before 14174 * setting the flag, we are sure to not clear the state and not 14175 * check the load of an idle cpu. 14176 * 14177 * Same applies to idle_cpus_mask vs needs_update. 14178 */ 14179 if (flags & NOHZ_STATS_KICK) 14180 WRITE_ONCE(nohz.has_blocked_load, 0); 14181 if (flags & NOHZ_NEXT_KICK) 14182 WRITE_ONCE(nohz.needs_update, 0); 14183 14184 /* 14185 * Ensures that if we miss the CPU, we must see the has_blocked_load 14186 * store from nohz_balance_enter_idle(). 14187 */ 14188 smp_mb(); 14189 14190 /* 14191 * Start with the next CPU after this_cpu so we will end with this_cpu and let a 14192 * chance for other idle cpu to pull load. 14193 */ 14194 for_each_cpu_wrap(balance_cpu, nohz.idle_cpus_mask, this_cpu+1) { 14195 if (!idle_cpu(balance_cpu)) 14196 continue; 14197 14198 /* 14199 * If this CPU gets work to do, stop the load balancing 14200 * work being done for other CPUs. Next load 14201 * balancing owner will pick it up. 14202 */ 14203 if (!idle_cpu(this_cpu) && need_resched()) { 14204 if (flags & NOHZ_STATS_KICK) 14205 has_blocked_load = true; 14206 if (flags & NOHZ_NEXT_KICK) 14207 WRITE_ONCE(nohz.needs_update, 1); 14208 goto abort; 14209 } 14210 14211 rq = cpu_rq(balance_cpu); 14212 14213 if (flags & NOHZ_STATS_KICK) 14214 has_blocked_load |= update_nohz_stats(rq); 14215 14216 /* 14217 * If time for next balance is due, 14218 * do the balance. 14219 */ 14220 if (time_after_eq(jiffies, rq->next_balance)) { 14221 struct rq_flags rf; 14222 14223 rq_lock_irqsave(rq, &rf); 14224 update_rq_clock(rq); 14225 rq_unlock_irqrestore(rq, &rf); 14226 14227 if (flags & NOHZ_BALANCE_KICK) 14228 sched_balance_domains(rq, CPU_IDLE); 14229 } 14230 14231 if (time_after(next_balance, rq->next_balance)) { 14232 next_balance = rq->next_balance; 14233 update_next_balance = 1; 14234 } 14235 } 14236 14237 /* 14238 * next_balance will be updated only when there is a need. 14239 * When the CPU is attached to null domain for ex, it will not be 14240 * updated. 14241 */ 14242 if (likely(update_next_balance)) 14243 nohz.next_balance = next_balance; 14244 14245 if (flags & NOHZ_STATS_KICK) 14246 WRITE_ONCE(nohz.next_blocked, 14247 now + msecs_to_jiffies(LOAD_AVG_PERIOD)); 14248 14249 abort: 14250 /* There is still blocked load, enable periodic update */ 14251 if (has_blocked_load) 14252 WRITE_ONCE(nohz.has_blocked_load, 1); 14253 } 14254 14255 /* 14256 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the 14257 * rebalancing for all the CPUs for whom scheduler ticks are stopped. 14258 */ 14259 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) 14260 { 14261 unsigned int flags = this_rq->nohz_idle_balance; 14262 14263 if (!flags) 14264 return false; 14265 14266 this_rq->nohz_idle_balance = 0; 14267 14268 if (idle != CPU_IDLE) 14269 return false; 14270 14271 _nohz_idle_balance(this_rq, flags); 14272 14273 return true; 14274 } 14275 14276 /* 14277 * Check if we need to directly run the ILB for updating blocked load before 14278 * entering idle state. Here we run ILB directly without issuing IPIs. 14279 * 14280 * Note that when this function is called, the tick may not yet be stopped on 14281 * this CPU yet. nohz.idle_cpus_mask is updated only when tick is stopped and 14282 * cleared on the next busy tick. In other words, nohz.idle_cpus_mask updates 14283 * don't align with CPUs enter/exit idle to avoid bottlenecks due to high idle 14284 * entry/exit rate (usec). So it is possible that _nohz_idle_balance() is 14285 * called from this function on (this) CPU that's not yet in the mask. That's 14286 * OK because the goal of nohz_run_idle_balance() is to run ILB only for 14287 * updating the blocked load of already idle CPUs without waking up one of 14288 * those idle CPUs and outside the preempt disable / IRQ off phase of the local 14289 * cpu about to enter idle, because it can take a long time. 14290 */ 14291 void nohz_run_idle_balance(int cpu) 14292 { 14293 unsigned int flags; 14294 14295 flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu)); 14296 14297 /* 14298 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen 14299 * (i.e. NOHZ_STATS_KICK set) and will do the same. 14300 */ 14301 if ((flags == NOHZ_NEWILB_KICK) && !need_resched()) 14302 _nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK); 14303 } 14304 14305 static void nohz_newidle_balance(struct rq *this_rq) 14306 { 14307 int this_cpu = this_rq->cpu; 14308 14309 /* Will wake up very soon. No time for doing anything else*/ 14310 if (this_rq->avg_idle < sysctl_sched_migration_cost) 14311 return; 14312 14313 /* Don't need to update blocked load of idle CPUs*/ 14314 if (!READ_ONCE(nohz.has_blocked_load) || 14315 time_before(jiffies, READ_ONCE(nohz.next_blocked))) 14316 return; 14317 14318 /* 14319 * Set the need to trigger ILB in order to update blocked load 14320 * before entering idle state. 14321 */ 14322 atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu)); 14323 } 14324 14325 #else /* !CONFIG_NO_HZ_COMMON: */ 14326 static inline void nohz_balancer_kick(struct rq *rq) { } 14327 14328 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) 14329 { 14330 return false; 14331 } 14332 14333 static inline void nohz_newidle_balance(struct rq *this_rq) { } 14334 #endif /* !CONFIG_NO_HZ_COMMON */ 14335 14336 /* 14337 * sched_balance_newidle is called by schedule() if this_cpu is about to become 14338 * idle. Attempts to pull tasks from other CPUs. 14339 * 14340 * Returns: 14341 * < 0 - we released the lock and there are !fair tasks present 14342 * 0 - failed, no new tasks 14343 * > 0 - success, new (fair) tasks present 14344 */ 14345 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf) 14346 __must_hold(__rq_lockp(this_rq)) 14347 { 14348 unsigned long next_balance = jiffies + HZ; 14349 int this_cpu = this_rq->cpu; 14350 int continue_balancing = 1; 14351 u64 t0, t1, curr_cost = 0; 14352 struct sched_domain *sd; 14353 int pulled_task = 0; 14354 14355 update_misfit_status(NULL, this_rq); 14356 14357 /* 14358 * There is a task waiting to run. No need to search for one. 14359 * Return 0; the task will be enqueued when switching to idle. 14360 */ 14361 if (this_rq->ttwu_pending) 14362 return 0; 14363 14364 /* 14365 * We must set idle_stamp _before_ calling sched_balance_rq() 14366 * for CPU_NEWLY_IDLE, such that we measure the this duration 14367 * as idle time. 14368 */ 14369 this_rq->idle_stamp = rq_clock(this_rq); 14370 14371 /* 14372 * Do not pull tasks towards !active CPUs... 14373 */ 14374 if (!cpu_active(this_cpu)) 14375 return 0; 14376 14377 /* 14378 * This is OK, because current is on_cpu, which avoids it being picked 14379 * for load-balance and preemption/IRQs are still disabled avoiding 14380 * further scheduler activity on it and we're being very careful to 14381 * re-start the picking loop. 14382 */ 14383 rq_unpin_lock(this_rq, rf); 14384 14385 sd = rcu_dereference_sched_domain(this_rq->sd); 14386 if (!sd) 14387 goto out; 14388 14389 if (!get_rd_overloaded(this_rq->rd) || 14390 this_rq->avg_idle < sd->max_newidle_lb_cost) { 14391 14392 update_next_balance(sd, &next_balance); 14393 goto out; 14394 } 14395 14396 /* 14397 * Include sched_balance_update_blocked_averages() in the cost 14398 * calculation because it can be quite costly -- this ensures we skip 14399 * it when avg_idle gets to be very low. 14400 */ 14401 t0 = sched_clock_cpu(this_cpu); 14402 __sched_balance_update_blocked_averages(this_rq); 14403 14404 rq_modified_begin(this_rq, &fair_sched_class); 14405 raw_spin_rq_unlock(this_rq); 14406 14407 for_each_domain(this_cpu, sd) { 14408 u64 domain_cost; 14409 14410 update_next_balance(sd, &next_balance); 14411 14412 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) 14413 break; 14414 14415 if (sd->flags & SD_BALANCE_NEWIDLE) { 14416 unsigned int weight = 1; 14417 14418 if (sched_feat(NI_RANDOM) && sd->newidle_ratio < 1024) { 14419 /* 14420 * Throw a 1k sided dice; and only run 14421 * newidle_balance according to the success 14422 * rate. 14423 */ 14424 u32 d1k = sched_rng() % 1024; 14425 weight = 1 + sd->newidle_ratio; 14426 if (d1k > weight) { 14427 update_newidle_stats(sd, 0); 14428 continue; 14429 } 14430 weight = (1024 + weight/2) / weight; 14431 } 14432 14433 pulled_task = sched_balance_rq(this_cpu, this_rq, 14434 sd, CPU_NEWLY_IDLE, 14435 &continue_balancing); 14436 14437 t1 = sched_clock_cpu(this_cpu); 14438 domain_cost = t1 - t0; 14439 curr_cost += domain_cost; 14440 t0 = t1; 14441 14442 /* 14443 * Track max cost of a domain to make sure to not delay the 14444 * next wakeup on the CPU. 14445 */ 14446 update_newidle_cost(sd, domain_cost, weight * !!pulled_task); 14447 } 14448 14449 /* 14450 * Stop searching for tasks to pull if there are 14451 * now runnable tasks on this rq. 14452 */ 14453 if (pulled_task || !continue_balancing) 14454 break; 14455 } 14456 14457 raw_spin_rq_lock(this_rq); 14458 14459 if (curr_cost > this_rq->max_idle_balance_cost) 14460 this_rq->max_idle_balance_cost = curr_cost; 14461 14462 /* 14463 * While browsing the domains, we released the rq lock, a task could 14464 * have been enqueued in the meantime. Since we're not going idle, 14465 * pretend we pulled a task. 14466 */ 14467 if (this_rq->cfs.h_nr_queued && !pulled_task) 14468 pulled_task = 1; 14469 14470 /* If a higher prio class was modified, restart the pick */ 14471 if (rq_modified_above(this_rq, &fair_sched_class)) 14472 pulled_task = -1; 14473 14474 out: 14475 /* Move the next balance forward */ 14476 if (time_after(this_rq->next_balance, next_balance)) 14477 this_rq->next_balance = next_balance; 14478 14479 if (pulled_task) 14480 this_rq->idle_stamp = 0; 14481 else 14482 nohz_newidle_balance(this_rq); 14483 14484 rq_repin_lock(this_rq, rf); 14485 14486 return pulled_task; 14487 } 14488 14489 /* 14490 * This softirq handler is triggered via SCHED_SOFTIRQ from two places: 14491 * 14492 * - directly from the local sched_tick() for periodic load balancing 14493 * 14494 * - indirectly from a remote sched_tick() for NOHZ idle balancing 14495 * through the SMP cross-call nohz_csd_func() 14496 */ 14497 static __latent_entropy void sched_balance_softirq(void) 14498 { 14499 struct rq *this_rq = this_rq(); 14500 enum cpu_idle_type idle = this_rq->idle_balance; 14501 /* 14502 * If this CPU has a pending NOHZ_BALANCE_KICK, then do the 14503 * balancing on behalf of the other idle CPUs whose ticks are 14504 * stopped. Do nohz_idle_balance *before* sched_balance_domains to 14505 * give the idle CPUs a chance to load balance. Else we may 14506 * load balance only within the local sched_domain hierarchy 14507 * and abort nohz_idle_balance altogether if we pull some load. 14508 */ 14509 if (nohz_idle_balance(this_rq, idle)) 14510 return; 14511 14512 /* normal load balance */ 14513 sched_balance_update_blocked_averages(this_rq->cpu); 14514 sched_balance_domains(this_rq, idle); 14515 } 14516 14517 /* 14518 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing. 14519 */ 14520 void sched_balance_trigger(struct rq *rq) 14521 { 14522 /* 14523 * Don't need to rebalance while attached to NULL domain or 14524 * runqueue CPU is not active 14525 */ 14526 if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq)))) 14527 return; 14528 14529 if (time_after_eq(jiffies, rq->next_balance)) 14530 raise_softirq(SCHED_SOFTIRQ); 14531 14532 nohz_balancer_kick(rq); 14533 } 14534 14535 static void rq_online_fair(struct rq *rq) 14536 { 14537 update_sysctl(); 14538 14539 update_runtime_enabled(rq); 14540 } 14541 14542 static void rq_offline_fair(struct rq *rq) 14543 { 14544 update_sysctl(); 14545 14546 /* Ensure any throttled groups are reachable by pick_next_task */ 14547 unthrottle_offline_cfs_rqs(rq); 14548 14549 /* Ensure that we remove rq contribution to group share: */ 14550 clear_tg_offline_cfs_rqs(rq); 14551 } 14552 14553 #ifdef CONFIG_SCHED_CORE 14554 static inline bool 14555 __entity_slice_used(struct sched_entity *se, int min_nr_tasks) 14556 { 14557 u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime; 14558 u64 slice = se->slice; 14559 14560 return (rtime * min_nr_tasks > slice); 14561 } 14562 14563 #define MIN_NR_TASKS_DURING_FORCEIDLE 2 14564 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) 14565 { 14566 if (!sched_core_enabled(rq)) 14567 return; 14568 14569 /* 14570 * If runqueue has only one task which used up its slice and 14571 * if the sibling is forced idle, then trigger schedule to 14572 * give forced idle task a chance. 14573 * 14574 * sched_slice() considers only this active rq and it gets the 14575 * whole slice. But during force idle, we have siblings acting 14576 * like a single runqueue and hence we need to consider runnable 14577 * tasks on this CPU and the forced idle CPU. Ideally, we should 14578 * go through the forced idle rq, but that would be a perf hit. 14579 * We can assume that the forced idle CPU has at least 14580 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check 14581 * if we need to give up the CPU. 14582 */ 14583 if (rq->core->core_forceidle_count && rq->cfs.nr_queued == 1 && 14584 __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE)) 14585 resched_curr(rq); 14586 } 14587 14588 /* 14589 * Consider any infeasible weight scenario. Take for instance two tasks, 14590 * each bound to their respective sibling, one with weight 1 and one with 14591 * weight 2. Then the lower weight task will run ahead of the higher weight 14592 * task without bound. 14593 * 14594 * This utterly destroys the concept of a shared time base. 14595 * 14596 * Remember; all this is about a proportionally fair scheduling, where each 14597 * tasks receives: 14598 * 14599 * w_i 14600 * dt_i = ---------- dt (1) 14601 * \Sum_j w_j 14602 * 14603 * which we do by tracking a virtual time, s_i: 14604 * 14605 * 1 14606 * s_i = --- d[t]_i (2) 14607 * w_i 14608 * 14609 * Where d[t] is a delta of discrete time, while dt is an infinitesimal. 14610 * The immediate corollary is that the ideal schedule S, where (2) to use 14611 * an infinitesimal delta, is: 14612 * 14613 * 1 14614 * S = ---------- dt (3) 14615 * \Sum_i w_i 14616 * 14617 * From which we can define the lag, or deviation from the ideal, as: 14618 * 14619 * lag(i) = S - s_i (4) 14620 * 14621 * And since the one and only purpose is to approximate S, we get that: 14622 * 14623 * \Sum_i w_i lag(i) := 0 (5) 14624 * 14625 * If this were not so, we no longer converge to S, and we can no longer 14626 * claim our scheduler has any of the properties we derive from S. This is 14627 * exactly what you did above, you broke it! 14628 * 14629 * 14630 * Let's continue for a while though; to see if there is anything useful to 14631 * be learned. We can combine (1)-(3) or (4)-(5) and express S in s_i: 14632 * 14633 * \Sum_i w_i s_i 14634 * S = -------------- (6) 14635 * \Sum_i w_i 14636 * 14637 * Which gives us a way to compute S, given our s_i. Now, if you've read 14638 * our code, you know that we do not in fact do this, the reason for this 14639 * is two-fold. Firstly, computing S in that way requires a 64bit division 14640 * for every time we'd use it (see 12), and secondly, this only describes 14641 * the steady-state, it doesn't handle dynamics. 14642 * 14643 * Anyway, in (6): s_i -> x + (s_i - x), to get: 14644 * 14645 * \Sum_i w_i (s_i - x) 14646 * S - x = -------------------- (7) 14647 * \Sum_i w_i 14648 * 14649 * Which shows that S and s_i transform alike (which makes perfect sense 14650 * given that S is basically the (weighted) average of s_i). 14651 * 14652 * So the thing to remember is that the above is strictly UP. It is 14653 * possible to generalize to multiple runqueues -- however it gets really 14654 * yuck when you have to add affinity support, as illustrated by our very 14655 * first counter-example. 14656 * 14657 * Luckily I think we can avoid needing a full multi-queue variant for 14658 * core-scheduling (or load-balancing). The crucial observation is that we 14659 * only actually need this comparison in the presence of forced-idle; only 14660 * then do we need to tell if the stalled rq has higher priority over the 14661 * other. 14662 * 14663 * [XXX assumes SMT2; better consider the more general case, I suspect 14664 * it'll work out because our comparison is always between 2 rqs and the 14665 * answer is only interesting if one of them is forced-idle] 14666 * 14667 * And (under assumption of SMT2) when there is forced-idle, there is only 14668 * a single queue, so everything works like normal. 14669 * 14670 * Let, for our runqueue 'k': 14671 * 14672 * T_k = \Sum_i w_i s_i 14673 * W_k = \Sum_i w_i ; for all i of k (8) 14674 * 14675 * Then we can write (6) like: 14676 * 14677 * T_k 14678 * S_k = --- (9) 14679 * W_k 14680 * 14681 * From which immediately follows that: 14682 * 14683 * T_k + T_l 14684 * S_k+l = --------- (10) 14685 * W_k + W_l 14686 * 14687 * On which we can define a combined lag: 14688 * 14689 * lag_k+l(i) := S_k+l - s_i (11) 14690 * 14691 * And that gives us the tools to compare tasks across a combined runqueue. 14692 * 14693 * 14694 * Combined this gives the following: 14695 * 14696 * a) when a runqueue enters force-idle, sync it against it's sibling rq(s) 14697 * using (7); this only requires storing single 'time'-stamps. 14698 * 14699 * b) when comparing tasks between 2 runqueues of which one is forced-idle, 14700 * compare the combined lag, per (11). 14701 * 14702 * Now, of course cgroups (I so hate them) make this more interesting in 14703 * that a) seems to suggest we need to iterate all cgroup on a CPU at such 14704 * boundaries, but I think we can avoid that. The force-idle is for the 14705 * whole CPU, all it's rqs. So we can mark it in the root and lazily 14706 * propagate downward on demand. 14707 */ 14708 14709 /* 14710 * So this sync is basically a relative reset of S to 0. 14711 * 14712 * So with 2 queues, when one goes idle, we drop them both to 0 and one 14713 * then increases due to not being idle, and the idle one builds up lag to 14714 * get re-elected. So far so simple, right? 14715 * 14716 * When there's 3, we can have the situation where 2 run and one is idle, 14717 * we sync to 0 and let the idle one build up lag to get re-election. Now 14718 * suppose another one also drops idle. At this point dropping all to 0 14719 * again would destroy the built-up lag from the queue that was already 14720 * idle, not good. 14721 * 14722 * So instead of syncing everything, we can: 14723 * 14724 * less := !((s64)(s_a - s_b) <= 0) 14725 * 14726 * (v_a - S_a) - (v_b - S_b) == v_a - v_b - S_a + S_b 14727 * == v_a - (v_b - S_a + S_b) 14728 * 14729 * IOW, we can recast the (lag) comparison to a one-sided difference. 14730 * So if then, instead of syncing the whole queue, sync the idle queue 14731 * against the active queue with S_a + S_b at the point where we sync. 14732 * 14733 * (XXX consider the implication of living in a cyclic group: N / 2^n N) 14734 * 14735 * This gives us means of syncing single queues against the active queue, 14736 * and for already idle queues to preserve their build-up lag. 14737 * 14738 * Of course, then we get the situation where there's 2 active and one 14739 * going idle, who do we pick to sync against? Theory would have us sync 14740 * against the combined S, but as we've already demonstrated, there is no 14741 * such thing in infeasible weight scenarios. 14742 * 14743 * One thing I've considered; and this is where that core_active rudiment 14744 * came from, is having active queues sync up between themselves after 14745 * every tick. This limits the observed divergence due to the work 14746 * conservancy. 14747 * 14748 * On top of that, we can improve upon things by employing (10) here. 14749 */ 14750 14751 /* 14752 * se_fi_update - Update the cfs_rq->zero_vruntime_fi in a CFS hierarchy if needed. 14753 */ 14754 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq, 14755 bool forceidle) 14756 { 14757 for_each_sched_entity(se) { 14758 struct cfs_rq *cfs_rq = cfs_rq_of(se); 14759 14760 if (forceidle) { 14761 if (cfs_rq->forceidle_seq == fi_seq) 14762 break; 14763 cfs_rq->forceidle_seq = fi_seq; 14764 } 14765 14766 cfs_rq->zero_vruntime_fi = cfs_rq->zero_vruntime; 14767 } 14768 } 14769 14770 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi) 14771 { 14772 struct sched_entity *se = &p->se; 14773 14774 if (p->sched_class != &fair_sched_class) 14775 return; 14776 14777 se_fi_update(se, rq->core->core_forceidle_seq, in_fi); 14778 } 14779 14780 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b, 14781 bool in_fi) 14782 { 14783 struct rq *rq = task_rq(a); 14784 const struct sched_entity *sea = &a->se; 14785 const struct sched_entity *seb = &b->se; 14786 struct cfs_rq *cfs_rqa; 14787 struct cfs_rq *cfs_rqb; 14788 s64 delta; 14789 14790 WARN_ON_ONCE(task_rq(b)->core != rq->core); 14791 14792 #ifdef CONFIG_FAIR_GROUP_SCHED 14793 /* 14794 * Find an se in the hierarchy for tasks a and b, such that the se's 14795 * are immediate siblings. 14796 */ 14797 while (sea->cfs_rq->tg != seb->cfs_rq->tg) { 14798 int sea_depth = sea->depth; 14799 int seb_depth = seb->depth; 14800 14801 if (sea_depth >= seb_depth) 14802 sea = parent_entity(sea); 14803 if (sea_depth <= seb_depth) 14804 seb = parent_entity(seb); 14805 } 14806 14807 se_fi_update(sea, rq->core->core_forceidle_seq, in_fi); 14808 se_fi_update(seb, rq->core->core_forceidle_seq, in_fi); 14809 14810 cfs_rqa = sea->cfs_rq; 14811 cfs_rqb = seb->cfs_rq; 14812 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 14813 cfs_rqa = &task_rq(a)->cfs; 14814 cfs_rqb = &task_rq(b)->cfs; 14815 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 14816 14817 /* 14818 * Find delta after normalizing se's vruntime with its cfs_rq's 14819 * zero_vruntime_fi, which would have been updated in prior calls 14820 * to se_fi_update(). 14821 */ 14822 delta = vruntime_op(sea->vruntime, "-", seb->vruntime) + 14823 vruntime_op(cfs_rqb->zero_vruntime_fi, "-", cfs_rqa->zero_vruntime_fi); 14824 14825 return delta > 0; 14826 } 14827 14828 static int task_is_throttled_fair(struct task_struct *p, int cpu) 14829 { 14830 struct cfs_rq *cfs_rq; 14831 14832 #ifdef CONFIG_FAIR_GROUP_SCHED 14833 cfs_rq = tg_cfs_rq(task_group(p), cpu); 14834 #else 14835 cfs_rq = &cpu_rq(cpu)->cfs; 14836 #endif 14837 return throttled_hierarchy(cfs_rq); 14838 } 14839 #else /* !CONFIG_SCHED_CORE: */ 14840 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {} 14841 #endif /* !CONFIG_SCHED_CORE */ 14842 14843 /* 14844 * scheduler tick hitting a task of our scheduling class. 14845 * 14846 * NOTE: This function can be called remotely by the tick offload that 14847 * goes along full dynticks. Therefore no local assumption can be made 14848 * and everything must be accessed through the @rq and @curr passed in 14849 * parameters. 14850 */ 14851 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued) 14852 { 14853 struct sched_entity *se = &curr->se; 14854 struct cfs_rq *cfs_rq; 14855 14856 for_each_sched_entity(se) { 14857 cfs_rq = cfs_rq_of(se); 14858 entity_tick(cfs_rq, se, queued); 14859 } 14860 14861 if (queued) 14862 return; 14863 14864 if (static_branch_unlikely(&sched_numa_balancing)) 14865 task_tick_numa(rq, curr); 14866 14867 task_tick_cache(rq, curr); 14868 14869 update_misfit_status(curr, rq); 14870 check_update_overutilized_status(task_rq(curr)); 14871 14872 task_tick_core(rq, curr); 14873 } 14874 14875 /* 14876 * called on fork with the child task as argument from the parent's context 14877 * - child not yet on the tasklist 14878 * - preemption disabled 14879 */ 14880 static void task_fork_fair(struct task_struct *p) 14881 { 14882 set_task_max_allowed_capacity(p); 14883 } 14884 14885 /* 14886 * Priority of the task has changed. Check to see if we preempt 14887 * the current task. 14888 */ 14889 static void 14890 prio_changed_fair(struct rq *rq, struct task_struct *p, u64 oldprio) 14891 { 14892 if (!task_on_rq_queued(p)) 14893 return; 14894 14895 if (p->prio == oldprio) 14896 return; 14897 14898 if (rq->cfs.nr_queued == 1) 14899 return; 14900 14901 /* 14902 * Reschedule if we are currently running on this runqueue and 14903 * our priority decreased, or if we are not currently running on 14904 * this runqueue and our priority is higher than the current's 14905 */ 14906 if (task_current_donor(rq, p)) { 14907 if (p->prio > oldprio) 14908 resched_curr(rq); 14909 } else { 14910 wakeup_preempt(rq, p, 0); 14911 } 14912 } 14913 14914 #ifdef CONFIG_FAIR_GROUP_SCHED 14915 /* 14916 * Propagate the changes of the sched_entity across the tg tree to make it 14917 * visible to the root 14918 */ 14919 static void propagate_entity_cfs_rq(struct sched_entity *se) 14920 { 14921 struct cfs_rq *cfs_rq = cfs_rq_of(se); 14922 14923 /* 14924 * If a task gets attached to this cfs_rq and before being queued, 14925 * it gets migrated to another CPU due to reasons like affinity 14926 * change, make sure this cfs_rq stays on leaf cfs_rq list to have 14927 * that removed load decayed or it can cause faireness problem. 14928 */ 14929 if (!cfs_rq_pelt_clock_throttled(cfs_rq)) 14930 list_add_leaf_cfs_rq(cfs_rq); 14931 14932 /* Start to propagate at parent */ 14933 se = se->parent; 14934 14935 for_each_sched_entity(se) { 14936 cfs_rq = cfs_rq_of(se); 14937 14938 update_load_avg(cfs_rq, se, UPDATE_TG); 14939 14940 if (!cfs_rq_pelt_clock_throttled(cfs_rq)) 14941 list_add_leaf_cfs_rq(cfs_rq); 14942 } 14943 14944 assert_list_leaf_cfs_rq(rq_of(cfs_rq)); 14945 } 14946 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 14947 static void propagate_entity_cfs_rq(struct sched_entity *se) { } 14948 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 14949 14950 static void detach_entity_cfs_rq(struct sched_entity *se) 14951 { 14952 struct cfs_rq *cfs_rq = cfs_rq_of(se); 14953 14954 /* 14955 * In case the task sched_avg hasn't been attached: 14956 * - A forked task which hasn't been woken up by wake_up_new_task(). 14957 * - A task which has been woken up by try_to_wake_up() but is 14958 * waiting for actually being woken up by sched_ttwu_pending(). 14959 */ 14960 if (!se->avg.last_update_time) 14961 return; 14962 14963 /* Catch up with the cfs_rq and remove our load when we leave */ 14964 update_load_avg(cfs_rq, se, 0); 14965 detach_entity_load_avg(cfs_rq, se); 14966 update_tg_load_avg(cfs_rq); 14967 propagate_entity_cfs_rq(se); 14968 } 14969 14970 static void attach_entity_cfs_rq(struct sched_entity *se) 14971 { 14972 struct cfs_rq *cfs_rq = cfs_rq_of(se); 14973 14974 /* Synchronize entity with its cfs_rq */ 14975 update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD); 14976 attach_entity_load_avg(cfs_rq, se); 14977 update_tg_load_avg(cfs_rq); 14978 propagate_entity_cfs_rq(se); 14979 } 14980 14981 static void detach_task_cfs_rq(struct task_struct *p) 14982 { 14983 struct sched_entity *se = &p->se; 14984 14985 detach_entity_cfs_rq(se); 14986 } 14987 14988 static void attach_task_cfs_rq(struct task_struct *p) 14989 { 14990 struct sched_entity *se = &p->se; 14991 14992 attach_entity_cfs_rq(se); 14993 } 14994 14995 static void switching_from_fair(struct rq *rq, struct task_struct *p) 14996 { 14997 if (p->se.sched_delayed) 14998 dequeue_task(rq, p, DEQUEUE_SLEEP | DEQUEUE_DELAYED | DEQUEUE_NOCLOCK); 14999 } 15000 15001 static void switched_from_fair(struct rq *rq, struct task_struct *p) 15002 { 15003 detach_task_cfs_rq(p); 15004 } 15005 15006 static void switched_to_fair(struct rq *rq, struct task_struct *p) 15007 { 15008 WARN_ON_ONCE(p->se.sched_delayed); 15009 15010 attach_task_cfs_rq(p); 15011 15012 set_task_max_allowed_capacity(p); 15013 15014 if (task_on_rq_queued(p)) { 15015 /* 15016 * We were most likely switched from sched_rt, so 15017 * kick off the schedule if running, otherwise just see 15018 * if we can still preempt the current task. 15019 */ 15020 if (task_current_donor(rq, p)) 15021 resched_curr(rq); 15022 else 15023 wakeup_preempt(rq, p, 0); 15024 } 15025 } 15026 15027 /* 15028 * Account for a task changing its policy or group. 15029 * 15030 * This routine is mostly called to set cfs_rq->curr field when a task 15031 * migrates between groups/classes. 15032 */ 15033 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first) 15034 { 15035 struct sched_entity *se = &p->se; 15036 bool throttled = false; 15037 15038 for_each_sched_entity(se) { 15039 struct cfs_rq *cfs_rq = cfs_rq_of(se); 15040 15041 if (IS_ENABLED(CONFIG_FAIR_GROUP_SCHED) && 15042 first && cfs_rq->curr) 15043 break; 15044 15045 set_next_entity(cfs_rq, se, first); 15046 /* ensure bandwidth has been allocated on our new cfs_rq */ 15047 throttled |= account_cfs_rq_runtime(cfs_rq, 0); 15048 } 15049 15050 if (throttled) 15051 task_throttle_setup_work(p); 15052 15053 se = &p->se; 15054 15055 if (task_on_rq_queued(p)) { 15056 /* 15057 * Move the next running task to the front of the list, so our 15058 * cfs_tasks list becomes MRU one. 15059 */ 15060 list_move(&se->group_node, &rq->cfs_tasks); 15061 } 15062 if (!first) 15063 return; 15064 15065 WARN_ON_ONCE(se->sched_delayed); 15066 15067 if (hrtick_enabled_fair(rq)) 15068 hrtick_start_fair(rq, p); 15069 15070 update_misfit_status(p, rq); 15071 sched_fair_update_stop_tick(rq, p); 15072 } 15073 15074 void init_cfs_rq(struct cfs_rq *cfs_rq) 15075 { 15076 cfs_rq->tasks_timeline = RB_ROOT_CACHED; 15077 cfs_rq->zero_vruntime = (u64)(-(1LL << 20)); 15078 raw_spin_lock_init(&cfs_rq->removed.lock); 15079 } 15080 15081 #ifdef CONFIG_FAIR_GROUP_SCHED 15082 static void task_change_group_fair(struct task_struct *p) 15083 { 15084 /* 15085 * We couldn't detach or attach a forked task which 15086 * hasn't been woken up by wake_up_new_task(). 15087 */ 15088 if (READ_ONCE(p->__state) == TASK_NEW) 15089 return; 15090 15091 detach_task_cfs_rq(p); 15092 15093 /* Tell se's cfs_rq has been changed -- migrated */ 15094 p->se.avg.last_update_time = 0; 15095 set_task_rq(p, task_cpu(p)); 15096 attach_task_cfs_rq(p); 15097 } 15098 15099 void free_fair_sched_group(struct task_group *tg) 15100 { 15101 free_percpu(tg->cfs_rq); 15102 } 15103 15104 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent) 15105 { 15106 struct cfs_tg_state __percpu *state; 15107 struct sched_entity *se; 15108 struct cfs_rq *cfs_rq; 15109 int i; 15110 15111 state = alloc_percpu_gfp(struct cfs_tg_state, GFP_KERNEL); 15112 if (!state) 15113 goto err; 15114 15115 tg->cfs_rq = &state->cfs_rq; 15116 tg->shares = NICE_0_LOAD; 15117 15118 init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent)); 15119 15120 for_each_possible_cpu(i) { 15121 cfs_rq = tg_cfs_rq(tg, i); 15122 if (!cfs_rq) 15123 goto err; 15124 15125 se = tg_se(tg, i); 15126 init_cfs_rq(cfs_rq); 15127 init_tg_cfs_entry(tg, cfs_rq, se, i, tg_se(parent, i)); 15128 init_entity_runnable_average(se); 15129 } 15130 15131 return 1; 15132 15133 err: 15134 return 0; 15135 } 15136 15137 void online_fair_sched_group(struct task_group *tg) 15138 { 15139 struct sched_entity *se; 15140 struct rq_flags rf; 15141 struct rq *rq; 15142 int i; 15143 15144 for_each_possible_cpu(i) { 15145 rq = cpu_rq(i); 15146 se = tg_se(tg, i); 15147 rq_lock_irq(rq, &rf); 15148 update_rq_clock(rq); 15149 attach_entity_cfs_rq(se); 15150 sync_throttle(tg, i); 15151 rq_unlock_irq(rq, &rf); 15152 } 15153 } 15154 15155 void unregister_fair_sched_group(struct task_group *tg) 15156 { 15157 int cpu; 15158 15159 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg)); 15160 15161 for_each_possible_cpu(cpu) { 15162 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu); 15163 struct sched_entity *se = tg_se(tg, cpu); 15164 struct rq *rq = cpu_rq(cpu); 15165 15166 if (se) { 15167 if (se->sched_delayed) { 15168 guard(rq_lock_irqsave)(rq); 15169 if (se->sched_delayed) { 15170 update_rq_clock(rq); 15171 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED); 15172 } 15173 list_del_leaf_cfs_rq(cfs_rq); 15174 } 15175 remove_entity_load_avg(se); 15176 } 15177 15178 /* 15179 * Only empty task groups can be destroyed; so we can speculatively 15180 * check on_list without danger of it being re-added. 15181 */ 15182 if (cfs_rq->on_list) { 15183 guard(rq_lock_irqsave)(rq); 15184 list_del_leaf_cfs_rq(cfs_rq); 15185 } 15186 } 15187 } 15188 15189 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq, 15190 struct sched_entity *se, int cpu, 15191 struct sched_entity *parent) 15192 { 15193 struct rq *rq = cpu_rq(cpu); 15194 15195 cfs_rq->tg = tg; 15196 cfs_rq->rq = rq; 15197 init_cfs_rq_runtime(cfs_rq); 15198 15199 /* se could be NULL for root_task_group */ 15200 if (!se) 15201 return; 15202 15203 if (!parent) { 15204 se->cfs_rq = &rq->cfs; 15205 se->depth = 0; 15206 } else { 15207 se->cfs_rq = parent->my_q; 15208 se->depth = parent->depth + 1; 15209 } 15210 15211 se->my_q = cfs_rq; 15212 /* guarantee group entities always have weight */ 15213 update_load_set(&se->load, NICE_0_LOAD); 15214 se->parent = parent; 15215 } 15216 15217 static DEFINE_MUTEX(shares_mutex); 15218 15219 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares) 15220 { 15221 int i; 15222 15223 lockdep_assert_held(&shares_mutex); 15224 15225 /* 15226 * We can't change the weight of the root cgroup. 15227 */ 15228 if (is_root_task_group(tg)) 15229 return -EINVAL; 15230 15231 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES)); 15232 15233 if (tg->shares == shares) 15234 return 0; 15235 15236 tg->shares = shares; 15237 for_each_possible_cpu(i) { 15238 struct rq *rq = cpu_rq(i); 15239 struct sched_entity *se = tg_se(tg, i); 15240 struct rq_flags rf; 15241 15242 /* Propagate contribution to hierarchy */ 15243 rq_lock_irqsave(rq, &rf); 15244 update_rq_clock(rq); 15245 for_each_sched_entity(se) { 15246 update_load_avg(cfs_rq_of(se), se, UPDATE_TG); 15247 update_cfs_group(se); 15248 } 15249 rq_unlock_irqrestore(rq, &rf); 15250 } 15251 15252 return 0; 15253 } 15254 15255 int sched_group_set_shares(struct task_group *tg, unsigned long shares) 15256 { 15257 int ret; 15258 15259 mutex_lock(&shares_mutex); 15260 if (tg_is_idle(tg)) 15261 ret = -EINVAL; 15262 else 15263 ret = __sched_group_set_shares(tg, shares); 15264 mutex_unlock(&shares_mutex); 15265 15266 return ret; 15267 } 15268 15269 int sched_group_set_idle(struct task_group *tg, long idle) 15270 { 15271 int i; 15272 15273 if (tg == &root_task_group) 15274 return -EINVAL; 15275 15276 if (idle < 0 || idle > 1) 15277 return -EINVAL; 15278 15279 mutex_lock(&shares_mutex); 15280 15281 if (tg->idle == idle) { 15282 mutex_unlock(&shares_mutex); 15283 return 0; 15284 } 15285 15286 tg->idle = idle; 15287 15288 for_each_possible_cpu(i) { 15289 struct rq *rq = cpu_rq(i); 15290 struct sched_entity *se = tg_se(tg, i); 15291 struct cfs_rq *grp_cfs_rq = tg_cfs_rq(tg, i); 15292 bool was_idle = cfs_rq_is_idle(grp_cfs_rq); 15293 long idle_task_delta; 15294 struct rq_flags rf; 15295 15296 rq_lock_irqsave(rq, &rf); 15297 15298 grp_cfs_rq->idle = idle; 15299 if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq))) 15300 goto next_cpu; 15301 15302 idle_task_delta = grp_cfs_rq->h_nr_queued - 15303 grp_cfs_rq->h_nr_idle; 15304 if (!cfs_rq_is_idle(grp_cfs_rq)) 15305 idle_task_delta *= -1; 15306 15307 for_each_sched_entity(se) { 15308 struct cfs_rq *cfs_rq = cfs_rq_of(se); 15309 15310 if (!se->on_rq) 15311 break; 15312 15313 cfs_rq->h_nr_idle += idle_task_delta; 15314 15315 /* Already accounted at parent level and above. */ 15316 if (cfs_rq_is_idle(cfs_rq)) 15317 break; 15318 } 15319 15320 next_cpu: 15321 rq_unlock_irqrestore(rq, &rf); 15322 } 15323 15324 /* Idle groups have minimum weight. */ 15325 if (tg_is_idle(tg)) 15326 __sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO)); 15327 else 15328 __sched_group_set_shares(tg, NICE_0_LOAD); 15329 15330 mutex_unlock(&shares_mutex); 15331 return 0; 15332 } 15333 15334 #endif /* CONFIG_FAIR_GROUP_SCHED */ 15335 15336 15337 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task) 15338 { 15339 struct sched_entity *se = &task->se; 15340 unsigned int rr_interval = 0; 15341 15342 /* 15343 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise 15344 * idle runqueue: 15345 */ 15346 if (rq->cfs.load.weight) 15347 rr_interval = NS_TO_JIFFIES(se->slice); 15348 15349 return rr_interval; 15350 } 15351 15352 /* 15353 * All the scheduling class methods: 15354 */ 15355 DEFINE_SCHED_CLASS(fair) = { 15356 .enqueue_task = enqueue_task_fair, 15357 .dequeue_task = dequeue_task_fair, 15358 .yield_task = yield_task_fair, 15359 .yield_to_task = yield_to_task_fair, 15360 15361 .wakeup_preempt = wakeup_preempt_fair, 15362 15363 .pick_task = pick_task_fair, 15364 .put_prev_task = put_prev_task_fair, 15365 .set_next_task = set_next_task_fair, 15366 15367 .select_task_rq = select_task_rq_fair, 15368 .migrate_task_rq = migrate_task_rq_fair, 15369 15370 .rq_online = rq_online_fair, 15371 .rq_offline = rq_offline_fair, 15372 15373 .task_dead = task_dead_fair, 15374 .set_cpus_allowed = set_cpus_allowed_fair, 15375 15376 .task_tick = task_tick_fair, 15377 .task_fork = task_fork_fair, 15378 15379 .reweight_task = reweight_task_fair, 15380 .prio_changed = prio_changed_fair, 15381 .switching_from = switching_from_fair, 15382 .switched_from = switched_from_fair, 15383 .switched_to = switched_to_fair, 15384 15385 .get_rr_interval = get_rr_interval_fair, 15386 15387 .update_curr = update_curr_fair, 15388 15389 #ifdef CONFIG_FAIR_GROUP_SCHED 15390 .task_change_group = task_change_group_fair, 15391 #endif 15392 15393 #ifdef CONFIG_SCHED_CORE 15394 .task_is_throttled = task_is_throttled_fair, 15395 #endif 15396 15397 #ifdef CONFIG_UCLAMP_TASK 15398 .uclamp_enabled = 1, 15399 #endif 15400 }; 15401 15402 void print_cfs_stats(struct seq_file *m, int cpu) 15403 { 15404 struct cfs_rq *cfs_rq, *pos; 15405 15406 rcu_read_lock(); 15407 for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos) 15408 print_cfs_rq(m, cpu, cfs_rq); 15409 rcu_read_unlock(); 15410 } 15411 15412 #ifdef CONFIG_NUMA_BALANCING 15413 void show_numa_stats(struct task_struct *p, struct seq_file *m) 15414 { 15415 int node; 15416 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0; 15417 struct numa_group *ng; 15418 15419 rcu_read_lock(); 15420 ng = rcu_dereference_all(p->numa_group); 15421 for_each_online_node(node) { 15422 if (p->numa_faults) { 15423 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)]; 15424 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)]; 15425 } 15426 if (ng) { 15427 gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)]; 15428 gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)]; 15429 } 15430 print_numa_stats(m, node, tsf, tpf, gsf, gpf); 15431 } 15432 rcu_read_unlock(); 15433 } 15434 #endif /* CONFIG_NUMA_BALANCING */ 15435 15436 __init void init_sched_fair_class(void) 15437 { 15438 int i; 15439 15440 for_each_possible_cpu(i) { 15441 zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i)); 15442 zalloc_cpumask_var_node(&per_cpu(select_rq_mask, i), GFP_KERNEL, cpu_to_node(i)); 15443 zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i), 15444 GFP_KERNEL, cpu_to_node(i)); 15445 15446 #ifdef CONFIG_CFS_BANDWIDTH 15447 INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i)); 15448 INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list); 15449 #endif 15450 } 15451 15452 open_softirq(SCHED_SOFTIRQ, sched_balance_softirq); 15453 15454 #ifdef CONFIG_NO_HZ_COMMON 15455 nohz.next_balance = jiffies; 15456 nohz.next_blocked = jiffies; 15457 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT); 15458 #endif 15459 } 15460