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) 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_irq_enable(&cfs_b->lock); 7159 /* we can't nest cfs_b->lock while distributing bandwidth */ 7160 throttled = distribute_cfs_runtime(cfs_b); 7161 raw_spin_lock_irq_disable(&cfs_b->lock); 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_irq, &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 guard(raw_spinlock_irq)(&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); 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 update_curr(cfs_rq); 7783 7784 if (update_entity_lag(cfs_rq, se)) { 7785 cfs_rq->nr_queued--; 7786 if (se != cfs_rq->curr) 7787 __dequeue_entity(cfs_rq, se); 7788 place_entity(cfs_rq, se, 0); 7789 if (se != cfs_rq->curr) 7790 __enqueue_entity(cfs_rq, se); 7791 cfs_rq->nr_queued++; 7792 } 7793 7794 update_load_avg(cfs_rq, se, 0); 7795 clear_delayed(se); 7796 } 7797 7798 /* 7799 * The enqueue_task method is called before nr_running is 7800 * increased. Here we update the fair scheduling stats and 7801 * then put the task into the rbtree: 7802 */ 7803 static void 7804 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags) 7805 { 7806 struct cfs_rq *cfs_rq; 7807 struct sched_entity *se = &p->se; 7808 int h_nr_idle = task_has_idle_policy(p); 7809 int h_nr_runnable = 1; 7810 int task_new = !(flags & ENQUEUE_WAKEUP); 7811 int rq_h_nr_queued = rq->cfs.h_nr_queued; 7812 u64 slice = 0; 7813 7814 if (task_is_throttled(p) && enqueue_throttled_task(p)) 7815 return; 7816 7817 /* 7818 * The code below (indirectly) updates schedutil which looks at 7819 * the cfs_rq utilization to select a frequency. 7820 * Let's add the task's estimated utilization to the cfs_rq's 7821 * estimated utilization, before we update schedutil. 7822 */ 7823 if (!p->se.sched_delayed || (flags & ENQUEUE_DELAYED)) 7824 util_est_enqueue(&rq->cfs, p); 7825 7826 if (flags & ENQUEUE_DELAYED) { 7827 requeue_delayed_entity(se); 7828 return; 7829 } 7830 7831 /* 7832 * If in_iowait is set, the code below may not trigger any cpufreq 7833 * utilization updates, so do it here explicitly with the IOWAIT flag 7834 * passed. 7835 */ 7836 if (p->in_iowait) 7837 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT); 7838 7839 if (task_new && se->sched_delayed) 7840 h_nr_runnable = 0; 7841 7842 for_each_sched_entity(se) { 7843 if (se->on_rq) { 7844 if (se->sched_delayed) 7845 requeue_delayed_entity(se); 7846 break; 7847 } 7848 cfs_rq = cfs_rq_of(se); 7849 7850 /* 7851 * Basically set the slice of group entries to the min_slice of 7852 * their respective cfs_rq. This ensures the group can service 7853 * its entities in the desired time-frame. 7854 */ 7855 if (slice) { 7856 se->slice = slice; 7857 se->custom_slice = 1; 7858 } 7859 enqueue_entity(cfs_rq, se, flags); 7860 slice = cfs_rq_min_slice(cfs_rq); 7861 7862 cfs_rq->h_nr_runnable += h_nr_runnable; 7863 cfs_rq->h_nr_queued++; 7864 cfs_rq->h_nr_idle += h_nr_idle; 7865 7866 if (cfs_rq_is_idle(cfs_rq)) 7867 h_nr_idle = 1; 7868 7869 flags = ENQUEUE_WAKEUP; 7870 } 7871 7872 for_each_sched_entity(se) { 7873 cfs_rq = cfs_rq_of(se); 7874 7875 update_load_avg(cfs_rq, se, UPDATE_TG); 7876 se_update_runnable(se); 7877 update_cfs_group(se); 7878 7879 se->slice = slice; 7880 if (se != cfs_rq->curr) 7881 min_vruntime_cb_propagate(&se->run_node, NULL); 7882 slice = cfs_rq_min_slice(cfs_rq); 7883 7884 cfs_rq->h_nr_runnable += h_nr_runnable; 7885 cfs_rq->h_nr_queued++; 7886 cfs_rq->h_nr_idle += h_nr_idle; 7887 7888 if (cfs_rq_is_idle(cfs_rq)) 7889 h_nr_idle = 1; 7890 } 7891 7892 if (!rq_h_nr_queued && rq->cfs.h_nr_queued) 7893 dl_server_start(&rq->fair_server); 7894 7895 /* At this point se is NULL and we are at root level*/ 7896 add_nr_running(rq, 1); 7897 7898 /* 7899 * Since new tasks are assigned an initial util_avg equal to 7900 * half of the spare capacity of their CPU, tiny tasks have the 7901 * ability to cross the overutilized threshold, which will 7902 * result in the load balancer ruining all the task placement 7903 * done by EAS. As a way to mitigate that effect, do not account 7904 * for the first enqueue operation of new tasks during the 7905 * overutilized flag detection. 7906 * 7907 * A better way of solving this problem would be to wait for 7908 * the PELT signals of tasks to converge before taking them 7909 * into account, but that is not straightforward to implement, 7910 * and the following generally works well enough in practice. 7911 */ 7912 if (!task_new) 7913 check_update_overutilized_status(rq); 7914 7915 assert_list_leaf_cfs_rq(rq); 7916 7917 hrtick_update(rq); 7918 } 7919 7920 /* 7921 * Basically dequeue_task_fair(), except it can deal with dequeue_entity() 7922 * failing half-way through and resume the dequeue later. 7923 * 7924 * Returns: 7925 * -1 - dequeue delayed 7926 * 0 - dequeue throttled 7927 * 1 - dequeue complete 7928 */ 7929 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags) 7930 { 7931 bool was_sched_idle = sched_idle_rq(rq); 7932 bool task_sleep = flags & DEQUEUE_SLEEP; 7933 bool task_delayed = flags & DEQUEUE_DELAYED; 7934 bool task_throttled = flags & DEQUEUE_THROTTLE; 7935 struct task_struct *p = NULL; 7936 int h_nr_idle = 0; 7937 int h_nr_queued = 0; 7938 int h_nr_runnable = 0; 7939 struct cfs_rq *cfs_rq; 7940 u64 slice = 0; 7941 7942 if (entity_is_task(se)) { 7943 p = task_of(se); 7944 h_nr_queued = 1; 7945 h_nr_idle = task_has_idle_policy(p); 7946 if (task_sleep || task_delayed || !se->sched_delayed) 7947 h_nr_runnable = 1; 7948 } 7949 7950 for_each_sched_entity(se) { 7951 cfs_rq = cfs_rq_of(se); 7952 7953 if (!dequeue_entity(cfs_rq, se, flags)) { 7954 if (p && &p->se == se) 7955 return -1; 7956 7957 slice = cfs_rq_min_slice(cfs_rq); 7958 break; 7959 } 7960 7961 cfs_rq->h_nr_runnable -= h_nr_runnable; 7962 cfs_rq->h_nr_queued -= h_nr_queued; 7963 cfs_rq->h_nr_idle -= h_nr_idle; 7964 7965 if (cfs_rq_is_idle(cfs_rq)) 7966 h_nr_idle = h_nr_queued; 7967 7968 if (throttled_hierarchy(cfs_rq) && task_throttled) 7969 record_throttle_clock(cfs_rq); 7970 7971 /* Don't dequeue parent if it has other entities besides us */ 7972 if (cfs_rq->load.weight) { 7973 slice = cfs_rq_min_slice(cfs_rq); 7974 7975 /* Avoid re-evaluating load for this entity: */ 7976 se = parent_entity(se); 7977 /* 7978 * Bias pick_next to pick a task from this cfs_rq, as 7979 * p is sleeping when it is within its sched_slice. 7980 */ 7981 if (task_sleep && se) 7982 set_next_buddy(se); 7983 break; 7984 } 7985 flags |= DEQUEUE_SLEEP; 7986 flags &= ~(DEQUEUE_DELAYED | DEQUEUE_SPECIAL); 7987 } 7988 7989 for_each_sched_entity(se) { 7990 cfs_rq = cfs_rq_of(se); 7991 7992 update_load_avg(cfs_rq, se, UPDATE_TG); 7993 se_update_runnable(se); 7994 update_cfs_group(se); 7995 7996 se->slice = slice; 7997 if (se != cfs_rq->curr) 7998 min_vruntime_cb_propagate(&se->run_node, NULL); 7999 slice = cfs_rq_min_slice(cfs_rq); 8000 8001 cfs_rq->h_nr_runnable -= h_nr_runnable; 8002 cfs_rq->h_nr_queued -= h_nr_queued; 8003 cfs_rq->h_nr_idle -= h_nr_idle; 8004 8005 if (cfs_rq_is_idle(cfs_rq)) 8006 h_nr_idle = h_nr_queued; 8007 8008 if (throttled_hierarchy(cfs_rq) && task_throttled) 8009 record_throttle_clock(cfs_rq); 8010 } 8011 8012 sub_nr_running(rq, h_nr_queued); 8013 8014 /* balance early to pull high priority tasks */ 8015 if (unlikely(!was_sched_idle && sched_idle_rq(rq))) 8016 rq->next_balance = jiffies; 8017 8018 if (p && task_delayed) { 8019 WARN_ON_ONCE(!task_sleep); 8020 WARN_ON_ONCE(p->on_rq != 1); 8021 8022 /* 8023 * Fix-up what block_task() skipped. 8024 * 8025 * Must be last, @p might not be valid after this. 8026 */ 8027 __block_task(rq, p); 8028 } 8029 8030 return 1; 8031 } 8032 8033 /* 8034 * The dequeue_task method is called before nr_running is 8035 * decreased. We remove the task from the rbtree and 8036 * update the fair scheduling stats: 8037 */ 8038 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags) 8039 { 8040 if (task_is_throttled(p)) { 8041 dequeue_throttled_task(p, flags); 8042 return true; 8043 } 8044 8045 if (!p->se.sched_delayed) 8046 util_est_dequeue(&rq->cfs, p); 8047 8048 if (dequeue_entities(rq, &p->se, flags) < 0) 8049 return false; 8050 8051 /* 8052 * Must not reference @p after dequeue_entities(DEQUEUE_DELAYED). 8053 */ 8054 return true; 8055 } 8056 8057 static inline unsigned int cfs_h_nr_delayed(struct rq *rq) 8058 { 8059 return (rq->cfs.h_nr_queued - rq->cfs.h_nr_runnable); 8060 } 8061 8062 /* Working cpumask for: sched_balance_rq(), sched_balance_newidle(). */ 8063 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask); 8064 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask); 8065 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask); 8066 8067 #ifdef CONFIG_NO_HZ_COMMON 8068 8069 static struct { 8070 cpumask_var_t idle_cpus_mask; 8071 int has_blocked_load; /* Idle CPUS has blocked load */ 8072 int needs_update; /* Newly idle CPUs need their next_balance collated */ 8073 unsigned long next_balance; /* in jiffy units */ 8074 unsigned long next_blocked; /* Next update of blocked load in jiffies */ 8075 } nohz ____cacheline_aligned; 8076 8077 #endif /* CONFIG_NO_HZ_COMMON */ 8078 8079 static unsigned long cpu_load(struct rq *rq) 8080 { 8081 return cfs_rq_load_avg(&rq->cfs); 8082 } 8083 8084 /* 8085 * cpu_load_without - compute CPU load without any contributions from *p 8086 * @cpu: the CPU which load is requested 8087 * @p: the task which load should be discounted 8088 * 8089 * The load of a CPU is defined by the load of tasks currently enqueued on that 8090 * CPU as well as tasks which are currently sleeping after an execution on that 8091 * CPU. 8092 * 8093 * This method returns the load of the specified CPU by discounting the load of 8094 * the specified task, whenever the task is currently contributing to the CPU 8095 * load. 8096 */ 8097 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p) 8098 { 8099 struct cfs_rq *cfs_rq; 8100 unsigned int load; 8101 8102 /* Task has no contribution or is new */ 8103 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 8104 return cpu_load(rq); 8105 8106 cfs_rq = &rq->cfs; 8107 load = READ_ONCE(cfs_rq->avg.load_avg); 8108 8109 /* Discount task's util from CPU's util */ 8110 lsub_positive(&load, task_h_load(p)); 8111 8112 return load; 8113 } 8114 8115 static unsigned long cpu_runnable(struct rq *rq) 8116 { 8117 return cfs_rq_runnable_avg(&rq->cfs); 8118 } 8119 8120 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p) 8121 { 8122 struct cfs_rq *cfs_rq; 8123 unsigned int runnable; 8124 8125 /* Task has no contribution or is new */ 8126 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 8127 return cpu_runnable(rq); 8128 8129 cfs_rq = &rq->cfs; 8130 runnable = READ_ONCE(cfs_rq->avg.runnable_avg); 8131 8132 /* Discount task's runnable from CPU's runnable */ 8133 lsub_positive(&runnable, p->se.avg.runnable_avg); 8134 8135 return runnable; 8136 } 8137 8138 static unsigned long capacity_of(int cpu) 8139 { 8140 return cpu_rq(cpu)->cpu_capacity; 8141 } 8142 8143 static void record_wakee(struct task_struct *p) 8144 { 8145 /* 8146 * Only decay a single time; tasks that have less then 1 wakeup per 8147 * jiffy will not have built up many flips. 8148 */ 8149 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) { 8150 current->wakee_flips >>= 1; 8151 current->wakee_flip_decay_ts = jiffies; 8152 } 8153 8154 if (current->last_wakee != p) { 8155 current->last_wakee = p; 8156 current->wakee_flips++; 8157 } 8158 } 8159 8160 /* 8161 * Detect M:N waker/wakee relationships via a switching-frequency heuristic. 8162 * 8163 * A waker of many should wake a different task than the one last awakened 8164 * at a frequency roughly N times higher than one of its wakees. 8165 * 8166 * In order to determine whether we should let the load spread vs consolidating 8167 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one 8168 * partner, and a factor of lls_size higher frequency in the other. 8169 * 8170 * With both conditions met, we can be relatively sure that the relationship is 8171 * non-monogamous, with partner count exceeding socket size. 8172 * 8173 * Waker/wakee being client/server, worker/dispatcher, interrupt source or 8174 * whatever is irrelevant, spread criteria is apparent partner count exceeds 8175 * socket size. 8176 */ 8177 static int wake_wide(struct task_struct *p) 8178 { 8179 unsigned int master = current->wakee_flips; 8180 unsigned int slave = p->wakee_flips; 8181 int factor = __this_cpu_read(sd_llc_size); 8182 8183 if (master < slave) 8184 swap(master, slave); 8185 if (slave < factor || master < slave * factor) 8186 return 0; 8187 return 1; 8188 } 8189 8190 /* 8191 * The purpose of wake_affine() is to quickly determine on which CPU we can run 8192 * soonest. For the purpose of speed we only consider the waking and previous 8193 * CPU. 8194 * 8195 * wake_affine_idle() - only considers 'now', it check if the waking CPU is 8196 * cache-affine and is (or will be) idle. 8197 * 8198 * wake_affine_weight() - considers the weight to reflect the average 8199 * scheduling latency of the CPUs. This seems to work 8200 * for the overloaded case. 8201 */ 8202 static int 8203 wake_affine_idle(int this_cpu, int prev_cpu, int sync) 8204 { 8205 /* 8206 * If this_cpu is idle, it implies the wakeup is from interrupt 8207 * context. Only allow the move if cache is shared. Otherwise an 8208 * interrupt intensive workload could force all tasks onto one 8209 * node depending on the IO topology or IRQ affinity settings. 8210 * 8211 * If the prev_cpu is idle and cache affine then avoid a migration. 8212 * There is no guarantee that the cache hot data from an interrupt 8213 * is more important than cache hot data on the prev_cpu and from 8214 * a cpufreq perspective, it's better to have higher utilisation 8215 * on one CPU. 8216 */ 8217 if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu)) 8218 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu; 8219 8220 if (sync) { 8221 struct rq *rq = cpu_rq(this_cpu); 8222 8223 if ((rq->nr_running - cfs_h_nr_delayed(rq)) == 1) 8224 return this_cpu; 8225 } 8226 8227 if (available_idle_cpu(prev_cpu)) 8228 return prev_cpu; 8229 8230 return nr_cpumask_bits; 8231 } 8232 8233 static int 8234 wake_affine_weight(struct sched_domain *sd, struct task_struct *p, 8235 int this_cpu, int prev_cpu, int sync) 8236 { 8237 s64 this_eff_load, prev_eff_load; 8238 unsigned long task_load; 8239 8240 this_eff_load = cpu_load(cpu_rq(this_cpu)); 8241 8242 if (sync) { 8243 unsigned long current_load = task_h_load(current); 8244 8245 if (current_load > this_eff_load) 8246 return this_cpu; 8247 8248 this_eff_load -= current_load; 8249 } 8250 8251 task_load = task_h_load(p); 8252 8253 this_eff_load += task_load; 8254 if (sched_feat(WA_BIAS)) 8255 this_eff_load *= 100; 8256 this_eff_load *= capacity_of(prev_cpu); 8257 8258 prev_eff_load = cpu_load(cpu_rq(prev_cpu)); 8259 prev_eff_load -= task_load; 8260 if (sched_feat(WA_BIAS)) 8261 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2; 8262 prev_eff_load *= capacity_of(this_cpu); 8263 8264 /* 8265 * If sync, adjust the weight of prev_eff_load such that if 8266 * prev_eff == this_eff that select_idle_sibling() will consider 8267 * stacking the wakee on top of the waker if no other CPU is 8268 * idle. 8269 */ 8270 if (sync) 8271 prev_eff_load += 1; 8272 8273 return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits; 8274 } 8275 8276 static int wake_affine(struct sched_domain *sd, struct task_struct *p, 8277 int this_cpu, int prev_cpu, int sync) 8278 { 8279 int target = nr_cpumask_bits; 8280 8281 if (sched_feat(WA_IDLE)) 8282 target = wake_affine_idle(this_cpu, prev_cpu, sync); 8283 8284 if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits) 8285 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync); 8286 8287 schedstat_inc(p->stats.nr_wakeups_affine_attempts); 8288 if (target != this_cpu) 8289 return prev_cpu; 8290 8291 schedstat_inc(sd->ttwu_move_affine); 8292 schedstat_inc(p->stats.nr_wakeups_affine); 8293 return target; 8294 } 8295 8296 static struct sched_group * 8297 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu); 8298 8299 /* 8300 * sched_balance_find_dst_group_cpu - find the idlest CPU among the CPUs in the group. 8301 */ 8302 static int 8303 sched_balance_find_dst_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu) 8304 { 8305 unsigned long load, min_load = ULONG_MAX; 8306 unsigned int min_exit_latency = UINT_MAX; 8307 u64 latest_idle_timestamp = 0; 8308 int least_loaded_cpu = this_cpu; 8309 int shallowest_idle_cpu = -1; 8310 int i; 8311 8312 /* Check if we have any choice: */ 8313 if (group->group_weight == 1) 8314 return cpumask_first(sched_group_span(group)); 8315 8316 /* Traverse only the allowed CPUs */ 8317 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) { 8318 struct rq *rq = cpu_rq(i); 8319 8320 if (!sched_core_cookie_match(rq, p)) 8321 continue; 8322 8323 if (choose_sched_idle_rq(rq, p)) 8324 return i; 8325 8326 if (available_idle_cpu(i)) { 8327 struct cpuidle_state *idle = idle_get_state(rq); 8328 if (idle && idle->exit_latency < min_exit_latency) { 8329 /* 8330 * We give priority to a CPU whose idle state 8331 * has the smallest exit latency irrespective 8332 * of any idle timestamp. 8333 */ 8334 min_exit_latency = idle->exit_latency; 8335 latest_idle_timestamp = rq->idle_stamp; 8336 shallowest_idle_cpu = i; 8337 } else if ((!idle || idle->exit_latency == min_exit_latency) && 8338 rq->idle_stamp > latest_idle_timestamp) { 8339 /* 8340 * If equal or no active idle state, then 8341 * the most recently idled CPU might have 8342 * a warmer cache. 8343 */ 8344 latest_idle_timestamp = rq->idle_stamp; 8345 shallowest_idle_cpu = i; 8346 } 8347 } else if (shallowest_idle_cpu == -1) { 8348 load = cpu_load(cpu_rq(i)); 8349 if (load < min_load) { 8350 min_load = load; 8351 least_loaded_cpu = i; 8352 } 8353 } 8354 } 8355 8356 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu; 8357 } 8358 8359 static inline int sched_balance_find_dst_cpu(struct sched_domain *sd, struct task_struct *p, 8360 int cpu, int prev_cpu, int sd_flag) 8361 { 8362 int new_cpu = cpu; 8363 8364 if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr)) 8365 return prev_cpu; 8366 8367 /* 8368 * We need task's util for cpu_util_without, sync it up to 8369 * prev_cpu's last_update_time. 8370 */ 8371 if (!(sd_flag & SD_BALANCE_FORK)) 8372 sync_entity_load_avg(&p->se); 8373 8374 while (sd) { 8375 struct sched_group *group; 8376 struct sched_domain *tmp; 8377 int weight; 8378 8379 if (!(sd->flags & sd_flag)) { 8380 sd = sd->child; 8381 continue; 8382 } 8383 8384 group = sched_balance_find_dst_group(sd, p, cpu); 8385 if (!group) { 8386 sd = sd->child; 8387 continue; 8388 } 8389 8390 new_cpu = sched_balance_find_dst_group_cpu(group, p, cpu); 8391 if (new_cpu == cpu) { 8392 /* Now try balancing at a lower domain level of 'cpu': */ 8393 sd = sd->child; 8394 continue; 8395 } 8396 8397 /* Now try balancing at a lower domain level of 'new_cpu': */ 8398 cpu = new_cpu; 8399 weight = sd->span_weight; 8400 sd = NULL; 8401 for_each_domain(cpu, tmp) { 8402 if (weight <= tmp->span_weight) 8403 break; 8404 if (tmp->flags & sd_flag) 8405 sd = tmp; 8406 } 8407 } 8408 8409 return new_cpu; 8410 } 8411 8412 static inline int __select_idle_cpu(int cpu, struct task_struct *p) 8413 { 8414 if (choose_idle_cpu(cpu, p) && sched_cpu_cookie_match(cpu_rq(cpu), p)) 8415 return cpu; 8416 8417 return -1; 8418 } 8419 8420 DEFINE_STATIC_KEY_FALSE(sched_smt_present); 8421 EXPORT_SYMBOL_GPL(sched_smt_present); 8422 8423 static inline void set_idle_cores(int cpu, int val) 8424 { 8425 struct sched_domain_shared *sds; 8426 8427 sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu)); 8428 if (sds) 8429 WRITE_ONCE(sds->has_idle_cores, val); 8430 } 8431 8432 static inline bool test_idle_cores(int cpu) 8433 { 8434 struct sched_domain_shared *sds; 8435 8436 sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu)); 8437 if (sds) 8438 return READ_ONCE(sds->has_idle_cores); 8439 8440 return false; 8441 } 8442 8443 /* 8444 * Scans the local SMT mask to see if the entire core is idle, and records this 8445 * information in sd_balance_shared->has_idle_cores. 8446 * 8447 * Since SMT siblings share all cache levels, inspecting this limited remote 8448 * state should be fairly cheap. 8449 */ 8450 void __update_idle_core(struct rq *rq) 8451 { 8452 int core = cpu_of(rq); 8453 int cpu; 8454 8455 rcu_read_lock(); 8456 if (test_idle_cores(core)) 8457 goto unlock; 8458 8459 for_each_cpu(cpu, cpu_smt_mask(core)) { 8460 if (cpu == core) 8461 continue; 8462 8463 if (!available_idle_cpu(cpu)) 8464 goto unlock; 8465 } 8466 8467 set_idle_cores(core, 1); 8468 unlock: 8469 rcu_read_unlock(); 8470 } 8471 8472 /* 8473 * Scan the entire LLC domain for idle cores; this dynamically switches off if 8474 * there are no idle cores left in the system; tracked through 8475 * sd_balance_shared->has_idle_cores and enabled through update_idle_core() 8476 * above. 8477 */ 8478 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu) 8479 { 8480 bool idle = true; 8481 int cpu; 8482 8483 for_each_cpu(cpu, cpu_smt_mask(core)) { 8484 if (!available_idle_cpu(cpu)) { 8485 idle = false; 8486 if (*idle_cpu == -1) { 8487 if (choose_sched_idle_rq(cpu_rq(cpu), p) && 8488 cpumask_test_cpu(cpu, cpus)) { 8489 *idle_cpu = cpu; 8490 break; 8491 } 8492 continue; 8493 } 8494 break; 8495 } 8496 if (*idle_cpu == -1 && cpumask_test_cpu(cpu, cpus)) 8497 *idle_cpu = cpu; 8498 } 8499 8500 if (idle) 8501 return core; 8502 8503 cpumask_andnot(cpus, cpus, cpu_smt_mask(core)); 8504 return -1; 8505 } 8506 8507 /* 8508 * Scan the local SMT mask for idle CPUs. 8509 */ 8510 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target) 8511 { 8512 int cpu; 8513 8514 for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) { 8515 if (cpu == target) 8516 continue; 8517 /* 8518 * Check if the CPU is in the LLC scheduling domain of @target. 8519 * Due to isolcpus, there is no guarantee that all the siblings are in the domain. 8520 */ 8521 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) 8522 continue; 8523 if (choose_idle_cpu(cpu, p)) 8524 return cpu; 8525 } 8526 8527 return -1; 8528 } 8529 8530 /* 8531 * Scan the LLC domain for idle CPUs; this is dynamically regulated by 8532 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the 8533 * average idle time for this rq (as found in rq->avg_idle). 8534 */ 8535 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target) 8536 { 8537 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask); 8538 int i, cpu, idle_cpu = -1, nr = INT_MAX; 8539 8540 if (sched_feat(SIS_UTIL) && sd->shared) { 8541 /* 8542 * Increment because !--nr is the condition to stop scan. 8543 * 8544 * Since "sd" is "sd_llc" for target CPU dereferenced in the 8545 * caller, it is safe to directly dereference "sd->shared". 8546 * Topology bits always ensure it assigned for "sd_llc" abd it 8547 * cannot disappear as long as we have a RCU protected 8548 * reference to one the associated "sd" here. 8549 */ 8550 nr = READ_ONCE(sd->shared->nr_idle_scan) + 1; 8551 /* overloaded LLC is unlikely to have idle cpu/core */ 8552 if (nr == 1) 8553 return -1; 8554 } 8555 8556 if (!cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr)) 8557 return -1; 8558 8559 if (static_branch_unlikely(&sched_cluster_active)) { 8560 struct sched_group *sg = sd->groups; 8561 8562 if (sg->flags & SD_CLUSTER) { 8563 for_each_cpu_wrap(cpu, sched_group_span(sg), target + 1) { 8564 if (!cpumask_test_cpu(cpu, cpus)) 8565 continue; 8566 8567 if (has_idle_core) { 8568 i = select_idle_core(p, cpu, cpus, &idle_cpu); 8569 if ((unsigned int)i < nr_cpumask_bits) 8570 return i; 8571 } else { 8572 if (--nr <= 0) 8573 return -1; 8574 idle_cpu = __select_idle_cpu(cpu, p); 8575 if ((unsigned int)idle_cpu < nr_cpumask_bits) 8576 return idle_cpu; 8577 } 8578 } 8579 cpumask_andnot(cpus, cpus, sched_group_span(sg)); 8580 } 8581 } 8582 8583 for_each_cpu_wrap(cpu, cpus, target + 1) { 8584 if (has_idle_core) { 8585 i = select_idle_core(p, cpu, cpus, &idle_cpu); 8586 if ((unsigned int)i < nr_cpumask_bits) 8587 return i; 8588 8589 } else { 8590 if (--nr <= 0) 8591 return -1; 8592 idle_cpu = __select_idle_cpu(cpu, p); 8593 if ((unsigned int)idle_cpu < nr_cpumask_bits) 8594 break; 8595 } 8596 } 8597 8598 if (has_idle_core) 8599 set_idle_cores(target, false); 8600 8601 return idle_cpu; 8602 } 8603 8604 /* 8605 * Idle-capacity scan converts util_fits_cpu() outcomes into preference ranks, 8606 * where lower values indicate a better fit - see select_idle_capacity(). 8607 * 8608 * A CPU that both fits the task and sits on a fully-idle SMT core is returned 8609 * immediately and is never assigned one of these ranks. On !SMT every CPU is 8610 * its own "core", so the early return covers all fits-and-idle cases and the 8611 * core-tier ranks below become unreachable. 8612 * 8613 * Rank Val Tier Meaning 8614 * ------------------------------ --- ------ --------------------------- 8615 * ASYM_IDLE_UCLAMP_MISFIT -4 core Idle core; capacity fits 8616 * util but uclamp_min misses. 8617 * ASYM_IDLE_COMPLETE_MISFIT -3 core Idle core; capacity does 8618 * not fit. Still beats every 8619 * thread-tier rank: a busy 8620 * sibling cuts effective 8621 * capacity more than a 8622 * misfit hurts a quiet core. 8623 * ASYM_IDLE_THREAD_FITS -2 thread Busy SMT sibling; capacity 8624 * fits util + uclamp. 8625 * ASYM_IDLE_THREAD_UCLAMP_MISFIT -1 thread Busy SMT sibling; capacity 8626 * fits but uclamp_min misses 8627 * (native util_fits_cpu() 8628 * return value). 8629 * ASYM_IDLE_THREAD_MISFIT 0 thread Busy SMT sibling; capacity 8630 * does not fit. 8631 * 8632 * ASYM_IDLE_CORE_BIAS (-3) is an offset, not a state. On an idle core, 8633 * fits += ASYM_IDLE_CORE_BIAS rebases thread-tier ranks into the core tier: 8634 * 8635 * ASYM_IDLE_THREAD_UCLAMP_MISFIT (-1) + BIAS -> ASYM_IDLE_UCLAMP_MISFIT (-4) 8636 * ASYM_IDLE_THREAD_MISFIT (0) + BIAS -> ASYM_IDLE_COMPLETE_MISFIT (-3) 8637 * 8638 * ASYM_IDLE_THREAD_FITS (-2) is never rebased because a fully-fitting idle-core 8639 * candidate early-returns from select_idle_capacity(). 8640 */ 8641 enum asym_fits_state { 8642 ASYM_IDLE_UCLAMP_MISFIT = -4, 8643 ASYM_IDLE_COMPLETE_MISFIT, 8644 ASYM_IDLE_THREAD_FITS, 8645 ASYM_IDLE_THREAD_UCLAMP_MISFIT, 8646 ASYM_IDLE_THREAD_MISFIT, 8647 8648 /* util_fits_cpu() bias for idle core */ 8649 ASYM_IDLE_CORE_BIAS = -3, 8650 }; 8651 8652 /* 8653 * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which 8654 * the task fits. If no CPU is big enough, but there are idle ones, try to 8655 * maximize capacity. 8656 */ 8657 static int 8658 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target) 8659 { 8660 /* 8661 * On !SMT systems, has_idle_core is always false and preferred_core 8662 * is always true (CPU == core), so the SMT preference logic below 8663 * collapses to the plain capacity scan. 8664 */ 8665 bool has_idle_core = sched_smt_active() && test_idle_cores(target); 8666 unsigned long task_util, util_min, util_max, best_cap = 0; 8667 int fits, best_fits = ASYM_IDLE_THREAD_MISFIT; 8668 int cpu, best_cpu = -1; 8669 struct cpumask *cpus; 8670 int nr = INT_MAX; 8671 8672 cpus = this_cpu_cpumask_var_ptr(select_rq_mask); 8673 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr); 8674 8675 task_util = task_util_est(p); 8676 util_min = uclamp_eff_value(p, UCLAMP_MIN); 8677 util_max = uclamp_eff_value(p, UCLAMP_MAX); 8678 8679 if (sched_feat(SIS_UTIL) && sd->shared) { 8680 /* 8681 * Same nr_idle_scan hint as select_idle_cpu(), nr only limits 8682 * the scan when not preferring an idle core. 8683 */ 8684 nr = READ_ONCE(sd->shared->nr_idle_scan) + 1; 8685 /* overloaded domain is unlikely to have idle cpu/core */ 8686 if (nr == 1) 8687 return -1; 8688 } 8689 8690 for_each_cpu_wrap(cpu, cpus, target) { 8691 bool preferred_core = !has_idle_core || is_core_idle(cpu); 8692 unsigned long cpu_cap = capacity_of(cpu); 8693 8694 /* 8695 * Stop when the nr_idle_scan is exhausted (mirrors 8696 * select_idle_cpu() logic). 8697 */ 8698 if (!has_idle_core && --nr <= 0) 8699 return best_cpu; 8700 8701 if (!choose_idle_cpu(cpu, p)) 8702 continue; 8703 8704 fits = util_fits_cpu(task_util, util_min, util_max, cpu); 8705 8706 /* 8707 * Perfect fit: capacity satisfies util + uclamp and the CPU 8708 * sits on a fully-idle SMT core, this is a !SMT system, or 8709 * there is no idle core to find. 8710 * Short-circuit the rank-based selection and return 8711 * immediately. 8712 */ 8713 if (fits > 0 && preferred_core) 8714 return cpu; 8715 /* 8716 * Only the min performance hint (i.e. uclamp_min) doesn't fit. 8717 * Look for the CPU with best capacity. 8718 */ 8719 else if (fits < 0) 8720 cpu_cap = get_actual_cpu_capacity(cpu); 8721 /* 8722 * fits > 0 implies we are not on a preferred core, but the util 8723 * fits CPU capacity. Set fits to ASYM_IDLE_THREAD_FITS 8724 * so the effective range becomes 8725 * [ASYM_IDLE_THREAD_FITS, ASYM_IDLE_THREAD_MISFIT], where: 8726 * ASYM_IDLE_THREAD_MISFIT - does not fit 8727 * ASYM_IDLE_THREAD_UCLAMP_MISFIT - fits with the exception of UCLAMP_MIN 8728 * ASYM_IDLE_THREAD_FITS - fits with the exception of preferred_core 8729 */ 8730 else if (fits > 0) 8731 fits = ASYM_IDLE_THREAD_FITS; 8732 8733 /* 8734 * If we are on a preferred core, translate the range of fits 8735 * of [ASYM_IDLE_THREAD_UCLAMP_MISFIT, ASYM_IDLE_THREAD_MISFIT] to 8736 * [ASYM_IDLE_UCLAMP_MISFIT, ASYM_IDLE_COMPLETE_MISFIT]. 8737 * This ensures that an idle core is always given priority over 8738 * (partially) busy core. 8739 * 8740 * A fully fitting idle core would have returned early and hence 8741 * fits > 0 for preferred_core need not be dealt with. 8742 */ 8743 if (preferred_core) 8744 fits += ASYM_IDLE_CORE_BIAS; 8745 8746 /* 8747 * First, select CPU which fits better (lower is more preferred). 8748 * Then, select the one with best capacity at same level. 8749 */ 8750 if ((fits < best_fits) || 8751 ((fits == best_fits) && (cpu_cap > best_cap))) { 8752 best_cap = cpu_cap; 8753 best_cpu = cpu; 8754 best_fits = fits; 8755 } 8756 } 8757 8758 /* 8759 * A value in the [ASYM_IDLE_UCLAMP_MISFIT, ASYM_IDLE_COMPLETE_MISFIT] 8760 * range means the chosen CPU is in a fully idle SMT core. Values above 8761 * ASYM_IDLE_COMPLETE_MISFIT mean we never ranked such a CPU best. 8762 * 8763 * The asym-capacity wakeup path returns from select_idle_sibling() 8764 * after this function and never runs select_idle_cpu(), so the usual 8765 * select_idle_cpu() tail that clears idle cores must live here when the 8766 * idle-core preference did not win. 8767 */ 8768 if (has_idle_core && best_fits > ASYM_IDLE_COMPLETE_MISFIT) 8769 set_idle_cores(target, false); 8770 8771 return best_cpu; 8772 } 8773 8774 static inline bool asym_fits_cpu(unsigned long util, 8775 unsigned long util_min, 8776 unsigned long util_max, 8777 int cpu) 8778 { 8779 if (sched_asym_cpucap_active()) { 8780 /* 8781 * Return true only if the cpu fully fits the task requirements 8782 * which include the utilization and the performance hints. 8783 * 8784 * When SMT is active, also require that the core has no busy 8785 * siblings. 8786 * 8787 * Note: gating on is_core_idle() also makes the early-bailout 8788 * candidates in select_idle_sibling() (target, prev, 8789 * recent_used_cpu) idle-core-aware on ASYM+SMT, which the 8790 * NO_ASYM path does not do. 8791 */ 8792 return (!sched_smt_active() || is_core_idle(cpu)) && 8793 (util_fits_cpu(util, util_min, util_max, cpu) > 0); 8794 } 8795 8796 return true; 8797 } 8798 8799 /* 8800 * Try and locate an idle core/thread in the LLC cache domain. 8801 */ 8802 static int select_idle_sibling(struct task_struct *p, int prev, int target) 8803 { 8804 bool has_idle_core = false; 8805 struct sched_domain *sd; 8806 unsigned long task_util, util_min, util_max; 8807 int i, recent_used_cpu, prev_aff = -1; 8808 8809 /* 8810 * On asymmetric system, update task utilization because we will check 8811 * that the task fits with CPU's capacity. 8812 */ 8813 if (sched_asym_cpucap_active()) { 8814 sync_entity_load_avg(&p->se); 8815 task_util = task_util_est(p); 8816 util_min = uclamp_eff_value(p, UCLAMP_MIN); 8817 util_max = uclamp_eff_value(p, UCLAMP_MAX); 8818 } 8819 8820 /* 8821 * per-cpu select_rq_mask usage 8822 */ 8823 lockdep_assert_irqs_disabled(); 8824 8825 if (choose_idle_cpu(target, p) && 8826 asym_fits_cpu(task_util, util_min, util_max, target)) 8827 return target; 8828 8829 /* 8830 * If the previous CPU is cache affine and idle, don't be stupid: 8831 */ 8832 if (prev != target && cpus_share_cache(prev, target) && 8833 choose_idle_cpu(prev, p) && 8834 asym_fits_cpu(task_util, util_min, util_max, prev)) { 8835 8836 if (!static_branch_unlikely(&sched_cluster_active) || 8837 cpus_share_resources(prev, target)) 8838 return prev; 8839 8840 prev_aff = prev; 8841 } 8842 8843 /* 8844 * Allow a per-cpu kthread to stack with the wakee if the 8845 * kworker thread and the tasks previous CPUs are the same. 8846 * The assumption is that the wakee queued work for the 8847 * per-cpu kthread that is now complete and the wakeup is 8848 * essentially a sync wakeup. An obvious example of this 8849 * pattern is IO completions. 8850 */ 8851 if (is_per_cpu_kthread(current) && 8852 in_task() && 8853 prev == smp_processor_id() && 8854 this_rq()->nr_running <= 1 && 8855 asym_fits_cpu(task_util, util_min, util_max, prev)) { 8856 return prev; 8857 } 8858 8859 /* Check a recently used CPU as a potential idle candidate: */ 8860 recent_used_cpu = p->recent_used_cpu; 8861 p->recent_used_cpu = prev; 8862 if (recent_used_cpu != prev && 8863 recent_used_cpu != target && 8864 cpus_share_cache(recent_used_cpu, target) && 8865 choose_idle_cpu(recent_used_cpu, p) && 8866 cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) && 8867 asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) { 8868 8869 if (!static_branch_unlikely(&sched_cluster_active) || 8870 cpus_share_resources(recent_used_cpu, target)) 8871 return recent_used_cpu; 8872 8873 } else { 8874 recent_used_cpu = -1; 8875 } 8876 8877 /* 8878 * For asymmetric CPU capacity systems, our domain of interest is 8879 * sd_asym_cpucapacity rather than sd_llc. 8880 */ 8881 if (sched_asym_cpucap_active()) { 8882 sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, target)); 8883 /* 8884 * On an asymmetric CPU capacity system where an exclusive 8885 * cpuset defines a symmetric island (i.e. one unique 8886 * capacity_orig value through the cpuset), the key will be set 8887 * but the CPUs within that cpuset will not have a domain with 8888 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric 8889 * capacity path. 8890 */ 8891 if (sd) { 8892 i = select_idle_capacity(p, sd, target); 8893 return ((unsigned)i < nr_cpumask_bits) ? i : target; 8894 } 8895 } 8896 8897 sd = rcu_dereference_all(per_cpu(sd_llc, target)); 8898 if (!sd) 8899 return target; 8900 8901 if (sched_smt_active()) { 8902 has_idle_core = test_idle_cores(target); 8903 8904 if (!has_idle_core && cpus_share_cache(prev, target)) { 8905 i = select_idle_smt(p, sd, prev); 8906 if ((unsigned int)i < nr_cpumask_bits) 8907 return i; 8908 } 8909 } 8910 8911 i = select_idle_cpu(p, sd, has_idle_core, target); 8912 if ((unsigned)i < nr_cpumask_bits) 8913 return i; 8914 8915 /* 8916 * For cluster machines which have lower sharing cache like L2 or 8917 * LLC Tag, we tend to find an idle CPU in the target's cluster 8918 * first. But prev_cpu or recent_used_cpu may also be a good candidate, 8919 * use them if possible when no idle CPU found in select_idle_cpu(). 8920 */ 8921 if ((unsigned int)prev_aff < nr_cpumask_bits) 8922 return prev_aff; 8923 if ((unsigned int)recent_used_cpu < nr_cpumask_bits) 8924 return recent_used_cpu; 8925 8926 return target; 8927 } 8928 8929 /** 8930 * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks. 8931 * @cpu: the CPU to get the utilization for 8932 * @p: task for which the CPU utilization should be predicted or NULL 8933 * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL 8934 * @boost: 1 to enable boosting, otherwise 0 8935 * 8936 * The unit of the return value must be the same as the one of CPU capacity 8937 * so that CPU utilization can be compared with CPU capacity. 8938 * 8939 * CPU utilization is the sum of running time of runnable tasks plus the 8940 * recent utilization of currently non-runnable tasks on that CPU. 8941 * It represents the amount of CPU capacity currently used by CFS tasks in 8942 * the range [0..max CPU capacity] with max CPU capacity being the CPU 8943 * capacity at f_max. 8944 * 8945 * The estimated CPU utilization is defined as the maximum between CPU 8946 * utilization and sum of the estimated utilization of the currently 8947 * runnable tasks on that CPU. It preserves a utilization "snapshot" of 8948 * previously-executed tasks, which helps better deduce how busy a CPU will 8949 * be when a long-sleeping task wakes up. The contribution to CPU utilization 8950 * of such a task would be significantly decayed at this point of time. 8951 * 8952 * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization). 8953 * CPU contention for CFS tasks can be detected by CPU runnable > CPU 8954 * utilization. Boosting is implemented in cpu_util() so that internal 8955 * users (e.g. EAS) can use it next to external users (e.g. schedutil), 8956 * latter via cpu_util_cfs_boost(). 8957 * 8958 * CPU utilization can be higher than the current CPU capacity 8959 * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because 8960 * of rounding errors as well as task migrations or wakeups of new tasks. 8961 * CPU utilization has to be capped to fit into the [0..max CPU capacity] 8962 * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%) 8963 * could be seen as over-utilized even though CPU1 has 20% of spare CPU 8964 * capacity. CPU utilization is allowed to overshoot current CPU capacity 8965 * though since this is useful for predicting the CPU capacity required 8966 * after task migrations (scheduler-driven DVFS). 8967 * 8968 * Return: (Boosted) (estimated) utilization for the specified CPU. 8969 */ 8970 static unsigned long 8971 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost) 8972 { 8973 bool add_task = p && task_cpu(p) != cpu && dst_cpu == cpu; 8974 bool sub_task = p && task_cpu(p) == cpu && dst_cpu != cpu; 8975 struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs; 8976 unsigned long util = READ_ONCE(cfs_rq->avg.util_avg); 8977 unsigned long runnable; 8978 8979 /* 8980 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its 8981 * contribution. If @p migrates from another CPU to @cpu add its 8982 * contribution. In all the other cases @cpu is not impacted by the 8983 * migration so its util_avg is already correct. 8984 */ 8985 if (add_task) 8986 util += task_util(p); 8987 else if (sub_task) 8988 lsub_positive(&util, task_util(p)); 8989 8990 if (boost) { 8991 runnable = READ_ONCE(cfs_rq->avg.runnable_avg); 8992 if (add_task) 8993 runnable += READ_ONCE(p->se.avg.runnable_avg); 8994 else if (sub_task) 8995 lsub_positive(&runnable, 8996 READ_ONCE(p->se.avg.runnable_avg)); 8997 util = max(util, runnable); 8998 } 8999 9000 if (sched_feat(UTIL_EST)) { 9001 unsigned long util_est; 9002 9003 util_est = READ_ONCE(cfs_rq->avg.util_est); 9004 9005 /* 9006 * During wake-up @p isn't enqueued yet and doesn't contribute 9007 * to any cpu_rq(cpu)->cfs.avg.util_est. 9008 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p 9009 * has been enqueued. 9010 * 9011 * During exec (@dst_cpu = -1) @p is enqueued and does 9012 * contribute to cpu_rq(cpu)->cfs.util_est. 9013 * Remove it to "simulate" cpu_util without @p's contribution. 9014 * 9015 * Despite the task_on_rq_queued(@p) check there is still a 9016 * small window for a possible race when an exec 9017 * select_task_rq_fair() races with LB's detach_task(). 9018 * 9019 * detach_task() 9020 * deactivate_task() 9021 * p->on_rq = TASK_ON_RQ_MIGRATING; 9022 * -------------------------------- A 9023 * dequeue_task() \ 9024 * dequeue_task_fair() + Race Time 9025 * util_est_dequeue() / 9026 * -------------------------------- B 9027 * 9028 * The additional check "current == p" is required to further 9029 * reduce the race window. 9030 */ 9031 if (dst_cpu == cpu) 9032 util_est += _task_util_est(p); 9033 else if (p && unlikely(task_on_rq_queued(p) || current == p)) 9034 lsub_positive(&util_est, _task_util_est(p)); 9035 9036 util = max(util, util_est); 9037 } 9038 9039 return min(util, arch_scale_cpu_capacity(cpu)); 9040 } 9041 9042 unsigned long cpu_util_cfs(int cpu) 9043 { 9044 return cpu_util(cpu, NULL, -1, 0); 9045 } 9046 9047 unsigned long cpu_util_cfs_boost(int cpu) 9048 { 9049 return cpu_util(cpu, NULL, -1, 1); 9050 } 9051 9052 /* 9053 * cpu_util_without: compute cpu utilization without any contributions from *p 9054 * @cpu: the CPU which utilization is requested 9055 * @p: the task which utilization should be discounted 9056 * 9057 * The utilization of a CPU is defined by the utilization of tasks currently 9058 * enqueued on that CPU as well as tasks which are currently sleeping after an 9059 * execution on that CPU. 9060 * 9061 * This method returns the utilization of the specified CPU by discounting the 9062 * utilization of the specified task, whenever the task is currently 9063 * contributing to the CPU utilization. 9064 */ 9065 static unsigned long cpu_util_without(int cpu, struct task_struct *p) 9066 { 9067 /* Task has no contribution or is new */ 9068 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 9069 p = NULL; 9070 9071 return cpu_util(cpu, p, -1, 0); 9072 } 9073 9074 /* 9075 * This function computes an effective utilization for the given CPU, to be 9076 * used for frequency selection given the linear relation: f = u * f_max. 9077 * 9078 * The scheduler tracks the following metrics: 9079 * 9080 * cpu_util_{cfs,rt,dl,irq}() 9081 * cpu_bw_dl() 9082 * 9083 * Where the cfs,rt and dl util numbers are tracked with the same metric and 9084 * synchronized windows and are thus directly comparable. 9085 * 9086 * The cfs,rt,dl utilization are the running times measured with rq->clock_task 9087 * which excludes things like IRQ and steal-time. These latter are then accrued 9088 * in the IRQ utilization. 9089 * 9090 * The DL bandwidth number OTOH is not a measured metric but a value computed 9091 * based on the task model parameters and gives the minimal utilization 9092 * required to meet deadlines. 9093 */ 9094 unsigned long effective_cpu_util(int cpu, unsigned long util_cfs, 9095 unsigned long *min, 9096 unsigned long *max) 9097 { 9098 unsigned long util, irq, scale; 9099 struct rq *rq = cpu_rq(cpu); 9100 9101 scale = arch_scale_cpu_capacity(cpu); 9102 9103 /* 9104 * Early check to see if IRQ/steal time saturates the CPU, can be 9105 * because of inaccuracies in how we track these -- see 9106 * update_irq_load_avg(). 9107 */ 9108 irq = cpu_util_irq(rq); 9109 if (unlikely(irq >= scale)) { 9110 if (min) 9111 *min = scale; 9112 if (max) 9113 *max = scale; 9114 return scale; 9115 } 9116 9117 if (min) { 9118 /* 9119 * The minimum utilization returns the highest level between: 9120 * - the computed DL bandwidth needed with the IRQ pressure which 9121 * steals time to the deadline task. 9122 * - The minimum performance requirement for CFS and/or RT. 9123 */ 9124 *min = max(irq + cpu_bw_dl(rq), uclamp_rq_get(rq, UCLAMP_MIN)); 9125 9126 /* 9127 * When an RT task is runnable and uclamp is not used, we must 9128 * ensure that the task will run at maximum compute capacity. 9129 */ 9130 if (!uclamp_is_used() && rt_rq_is_runnable(&rq->rt)) 9131 *min = max(*min, scale); 9132 } 9133 9134 /* 9135 * Because the time spend on RT/DL tasks is visible as 'lost' time to 9136 * CFS tasks and we use the same metric to track the effective 9137 * utilization (PELT windows are synchronized) we can directly add them 9138 * to obtain the CPU's actual utilization. 9139 */ 9140 util = util_cfs + cpu_util_rt(rq); 9141 util += cpu_util_dl(rq); 9142 9143 /* 9144 * The maximum hint is a soft bandwidth requirement, which can be lower 9145 * than the actual utilization because of uclamp_max requirements. 9146 */ 9147 if (max) 9148 *max = min(scale, uclamp_rq_get(rq, UCLAMP_MAX)); 9149 9150 if (util >= scale) 9151 return scale; 9152 9153 /* 9154 * There is still idle time; further improve the number by using the 9155 * IRQ metric. Because IRQ/steal time is hidden from the task clock we 9156 * need to scale the task numbers: 9157 * 9158 * max - irq 9159 * U' = irq + --------- * U 9160 * max 9161 */ 9162 util = scale_irq_capacity(util, irq, scale); 9163 util += irq; 9164 9165 return min(scale, util); 9166 } 9167 9168 unsigned long sched_cpu_util(int cpu) 9169 { 9170 return effective_cpu_util(cpu, cpu_util_cfs(cpu), NULL, NULL); 9171 } 9172 9173 /* 9174 * energy_env - Utilization landscape for energy estimation. 9175 * @task_busy_time: Utilization contribution by the task for which we test the 9176 * placement. Given by eenv_task_busy_time(). 9177 * @pd_busy_time: Utilization of the whole perf domain without the task 9178 * contribution. Given by eenv_pd_busy_time(). 9179 * @cpu_cap: Maximum CPU capacity for the perf domain. 9180 * @pd_cap: Entire perf domain capacity. (pd->nr_cpus * cpu_cap). 9181 */ 9182 struct energy_env { 9183 unsigned long task_busy_time; 9184 unsigned long pd_busy_time; 9185 unsigned long cpu_cap; 9186 unsigned long pd_cap; 9187 }; 9188 9189 /* 9190 * Compute the task busy time for compute_energy(). This time cannot be 9191 * injected directly into effective_cpu_util() because of the IRQ scaling. 9192 * The latter only makes sense with the most recent CPUs where the task has 9193 * run. 9194 */ 9195 static inline void eenv_task_busy_time(struct energy_env *eenv, 9196 struct task_struct *p, int prev_cpu) 9197 { 9198 unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu); 9199 unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu)); 9200 9201 if (unlikely(irq >= max_cap)) 9202 busy_time = max_cap; 9203 else 9204 busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap); 9205 9206 eenv->task_busy_time = busy_time; 9207 } 9208 9209 /* 9210 * Compute the perf_domain (PD) busy time for compute_energy(). Based on the 9211 * utilization for each @pd_cpus, it however doesn't take into account 9212 * clamping since the ratio (utilization / cpu_capacity) is already enough to 9213 * scale the EM reported power consumption at the (eventually clamped) 9214 * cpu_capacity. 9215 * 9216 * The contribution of the task @p for which we want to estimate the 9217 * energy cost is removed (by cpu_util()) and must be calculated 9218 * separately (see eenv_task_busy_time). This ensures: 9219 * 9220 * - A stable PD utilization, no matter which CPU of that PD we want to place 9221 * the task on. 9222 * 9223 * - A fair comparison between CPUs as the task contribution (task_util()) 9224 * will always be the same no matter which CPU utilization we rely on 9225 * (util_avg or util_est). 9226 * 9227 * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't 9228 * exceed @eenv->pd_cap. 9229 */ 9230 static inline void eenv_pd_busy_time(struct energy_env *eenv, 9231 struct cpumask *pd_cpus, 9232 struct task_struct *p) 9233 { 9234 unsigned long busy_time = 0; 9235 int cpu; 9236 9237 for_each_cpu(cpu, pd_cpus) { 9238 unsigned long util = cpu_util(cpu, p, -1, 0); 9239 9240 busy_time += effective_cpu_util(cpu, util, NULL, NULL); 9241 } 9242 9243 eenv->pd_busy_time = min(eenv->pd_cap, busy_time); 9244 } 9245 9246 /* 9247 * Compute the maximum utilization for compute_energy() when the task @p 9248 * is placed on the cpu @dst_cpu. 9249 * 9250 * Returns the maximum utilization among @eenv->cpus. This utilization can't 9251 * exceed @eenv->cpu_cap. 9252 */ 9253 static inline unsigned long 9254 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus, 9255 struct task_struct *p, int dst_cpu) 9256 { 9257 unsigned long max_util = 0; 9258 int cpu; 9259 9260 for_each_cpu(cpu, pd_cpus) { 9261 struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL; 9262 unsigned long util = cpu_util(cpu, p, dst_cpu, 1); 9263 unsigned long eff_util, min, max; 9264 9265 /* 9266 * Performance domain frequency: utilization clamping 9267 * must be considered since it affects the selection 9268 * of the performance domain frequency. 9269 * NOTE: in case RT tasks are running, by default the min 9270 * utilization can be max OPP. 9271 */ 9272 eff_util = effective_cpu_util(cpu, util, &min, &max); 9273 9274 /* Task's uclamp can modify min and max value */ 9275 if (tsk && uclamp_is_used()) { 9276 min = max(min, uclamp_eff_value(p, UCLAMP_MIN)); 9277 9278 /* 9279 * If there is no active max uclamp constraint, 9280 * directly use task's one, otherwise keep max. 9281 */ 9282 if (uclamp_rq_is_idle(cpu_rq(cpu))) 9283 max = uclamp_eff_value(p, UCLAMP_MAX); 9284 else 9285 max = max(max, uclamp_eff_value(p, UCLAMP_MAX)); 9286 } 9287 9288 eff_util = sugov_effective_cpu_perf(cpu, eff_util, min, max); 9289 max_util = max(max_util, eff_util); 9290 } 9291 9292 return min(max_util, eenv->cpu_cap); 9293 } 9294 9295 /* 9296 * compute_energy(): Use the Energy Model to estimate the energy that @pd would 9297 * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task 9298 * contribution is ignored. 9299 */ 9300 static inline unsigned long 9301 compute_energy(struct energy_env *eenv, struct perf_domain *pd, 9302 struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu) 9303 { 9304 unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu); 9305 unsigned long busy_time = eenv->pd_busy_time; 9306 unsigned long energy; 9307 9308 if (dst_cpu >= 0) 9309 busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time); 9310 9311 energy = em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap); 9312 9313 trace_sched_compute_energy_tp(p, dst_cpu, energy, max_util, busy_time); 9314 9315 return energy; 9316 } 9317 9318 /* 9319 * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the 9320 * waking task. find_energy_efficient_cpu() looks for the CPU with maximum 9321 * spare capacity in each performance domain and uses it as a potential 9322 * candidate to execute the task. Then, it uses the Energy Model to figure 9323 * out which of the CPU candidates is the most energy-efficient. 9324 * 9325 * The rationale for this heuristic is as follows. In a performance domain, 9326 * all the most energy efficient CPU candidates (according to the Energy 9327 * Model) are those for which we'll request a low frequency. When there are 9328 * several CPUs for which the frequency request will be the same, we don't 9329 * have enough data to break the tie between them, because the Energy Model 9330 * only includes active power costs. With this model, if we assume that 9331 * frequency requests follow utilization (e.g. using schedutil), the CPU with 9332 * the maximum spare capacity in a performance domain is guaranteed to be among 9333 * the best candidates of the performance domain. 9334 * 9335 * In practice, it could be preferable from an energy standpoint to pack 9336 * small tasks on a CPU in order to let other CPUs go in deeper idle states, 9337 * but that could also hurt our chances to go cluster idle, and we have no 9338 * ways to tell with the current Energy Model if this is actually a good 9339 * idea or not. So, find_energy_efficient_cpu() basically favors 9340 * cluster-packing, and spreading inside a cluster. That should at least be 9341 * a good thing for latency, and this is consistent with the idea that most 9342 * of the energy savings of EAS come from the asymmetry of the system, and 9343 * not so much from breaking the tie between identical CPUs. That's also the 9344 * reason why EAS is enabled in the topology code only for systems where 9345 * SD_ASYM_CPUCAPACITY is set. 9346 * 9347 * NOTE: Forkees are not accepted in the energy-aware wake-up path because 9348 * they don't have any useful utilization data yet and it's not possible to 9349 * forecast their impact on energy consumption. Consequently, they will be 9350 * placed by sched_balance_find_dst_cpu() on the least loaded CPU, which might turn out 9351 * to be energy-inefficient in some use-cases. The alternative would be to 9352 * bias new tasks towards specific types of CPUs first, or to try to infer 9353 * their util_avg from the parent task, but those heuristics could hurt 9354 * other use-cases too. So, until someone finds a better way to solve this, 9355 * let's keep things simple by re-using the existing slow path. 9356 */ 9357 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu) 9358 { 9359 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask); 9360 unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX; 9361 unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0; 9362 unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024; 9363 struct root_domain *rd = this_rq()->rd; 9364 int cpu, best_energy_cpu, target = -1; 9365 int prev_fits = -1, best_fits = -1; 9366 unsigned long best_actual_cap = 0; 9367 unsigned long prev_actual_cap = 0; 9368 struct sched_domain *sd; 9369 struct perf_domain *pd; 9370 struct energy_env eenv; 9371 9372 pd = rcu_dereference_all(rd->pd); 9373 if (!pd) 9374 return target; 9375 9376 /* 9377 * Energy-aware wake-up happens on the lowest sched_domain starting 9378 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu. 9379 */ 9380 sd = rcu_dereference_all(*this_cpu_ptr(&sd_asym_cpucapacity)); 9381 while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd))) 9382 sd = sd->parent; 9383 if (!sd) 9384 return target; 9385 9386 target = prev_cpu; 9387 9388 sync_entity_load_avg(&p->se); 9389 if (!task_util_est(p) && p_util_min == 0) 9390 return target; 9391 9392 eenv_task_busy_time(&eenv, p, prev_cpu); 9393 9394 for (; pd; pd = pd->next) { 9395 unsigned long util_min = p_util_min, util_max = p_util_max; 9396 unsigned long cpu_cap, cpu_actual_cap, util; 9397 long prev_spare_cap = -1, max_spare_cap = -1; 9398 unsigned long rq_util_min, rq_util_max; 9399 unsigned long cur_delta, base_energy; 9400 int max_spare_cap_cpu = -1; 9401 int fits, max_fits = -1; 9402 9403 if (!cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask)) 9404 continue; 9405 9406 /* Account external pressure for the energy estimation */ 9407 cpu = cpumask_first(cpus); 9408 cpu_actual_cap = get_actual_cpu_capacity(cpu); 9409 9410 eenv.cpu_cap = cpu_actual_cap; 9411 eenv.pd_cap = 0; 9412 9413 for_each_cpu(cpu, cpus) { 9414 struct rq *rq = cpu_rq(cpu); 9415 9416 eenv.pd_cap += cpu_actual_cap; 9417 9418 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) 9419 continue; 9420 9421 if (!cpumask_test_cpu(cpu, p->cpus_ptr)) 9422 continue; 9423 9424 util = cpu_util(cpu, p, cpu, 0); 9425 cpu_cap = capacity_of(cpu); 9426 9427 /* 9428 * Skip CPUs that cannot satisfy the capacity request. 9429 * IOW, placing the task there would make the CPU 9430 * overutilized. Take uclamp into account to see how 9431 * much capacity we can get out of the CPU; this is 9432 * aligned with sched_cpu_util(). 9433 */ 9434 if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) { 9435 /* 9436 * Open code uclamp_rq_util_with() except for 9437 * the clamp() part. I.e.: apply max aggregation 9438 * only. util_fits_cpu() logic requires to 9439 * operate on non clamped util but must use the 9440 * max-aggregated uclamp_{min, max}. 9441 */ 9442 rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN); 9443 rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX); 9444 9445 util_min = max(rq_util_min, p_util_min); 9446 util_max = max(rq_util_max, p_util_max); 9447 } 9448 9449 fits = util_fits_cpu(util, util_min, util_max, cpu); 9450 if (!fits) 9451 continue; 9452 9453 lsub_positive(&cpu_cap, util); 9454 9455 if (cpu == prev_cpu) { 9456 /* Always use prev_cpu as a candidate. */ 9457 prev_spare_cap = cpu_cap; 9458 prev_fits = fits; 9459 } else if ((fits > max_fits) || 9460 ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) { 9461 /* 9462 * Find the CPU with the maximum spare capacity 9463 * among the remaining CPUs in the performance 9464 * domain. 9465 */ 9466 max_spare_cap = cpu_cap; 9467 max_spare_cap_cpu = cpu; 9468 max_fits = fits; 9469 } 9470 } 9471 9472 if (max_spare_cap_cpu < 0 && prev_spare_cap < 0) 9473 continue; 9474 9475 eenv_pd_busy_time(&eenv, cpus, p); 9476 /* Compute the 'base' energy of the pd, without @p */ 9477 base_energy = compute_energy(&eenv, pd, cpus, p, -1); 9478 9479 /* Evaluate the energy impact of using prev_cpu. */ 9480 if (prev_spare_cap > -1) { 9481 prev_delta = compute_energy(&eenv, pd, cpus, p, 9482 prev_cpu); 9483 /* CPU utilization has changed */ 9484 if (prev_delta < base_energy) 9485 return target; 9486 prev_delta -= base_energy; 9487 prev_actual_cap = cpu_actual_cap; 9488 best_delta = min(best_delta, prev_delta); 9489 } 9490 9491 /* Evaluate the energy impact of using max_spare_cap_cpu. */ 9492 if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) { 9493 /* Current best energy cpu fits better */ 9494 if (max_fits < best_fits) 9495 continue; 9496 9497 /* 9498 * Both don't fit performance hint (i.e. uclamp_min) 9499 * but best energy cpu has better capacity. 9500 */ 9501 if ((max_fits < 0) && 9502 (cpu_actual_cap <= best_actual_cap)) 9503 continue; 9504 9505 cur_delta = compute_energy(&eenv, pd, cpus, p, 9506 max_spare_cap_cpu); 9507 /* CPU utilization has changed */ 9508 if (cur_delta < base_energy) 9509 return target; 9510 cur_delta -= base_energy; 9511 9512 /* 9513 * Both fit for the task but best energy cpu has lower 9514 * energy impact. 9515 */ 9516 if ((max_fits > 0) && (best_fits > 0) && 9517 (cur_delta >= best_delta)) 9518 continue; 9519 9520 best_delta = cur_delta; 9521 best_energy_cpu = max_spare_cap_cpu; 9522 best_fits = max_fits; 9523 best_actual_cap = cpu_actual_cap; 9524 } 9525 } 9526 9527 if ((best_fits > prev_fits) || 9528 ((best_fits > 0) && (best_delta < prev_delta)) || 9529 ((best_fits < 0) && (best_actual_cap > prev_actual_cap))) 9530 target = best_energy_cpu; 9531 9532 return target; 9533 } 9534 9535 /* 9536 * select_task_rq_fair: Select target runqueue for the waking task in domains 9537 * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE, 9538 * SD_BALANCE_FORK, or SD_BALANCE_EXEC. 9539 * 9540 * Balances load by selecting the idlest CPU in the idlest group, or under 9541 * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set. 9542 * 9543 * Returns the target CPU number. 9544 */ 9545 static int 9546 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags) 9547 { 9548 int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING); 9549 struct sched_domain *tmp, *sd = NULL; 9550 int cpu = smp_processor_id(); 9551 int new_cpu = prev_cpu; 9552 int want_affine = 0; 9553 /* SD_flags and WF_flags share the first nibble */ 9554 int sd_flag = wake_flags & 0xF; 9555 9556 /* 9557 * required for stable ->cpus_allowed 9558 */ 9559 lockdep_assert_held(&p->pi_lock); 9560 if (wake_flags & WF_TTWU) { 9561 record_wakee(p); 9562 9563 if ((wake_flags & WF_CURRENT_CPU) && 9564 cpumask_test_cpu(cpu, p->cpus_ptr)) 9565 return cpu; 9566 9567 if (!is_rd_overutilized(this_rq()->rd)) { 9568 new_cpu = find_energy_efficient_cpu(p, prev_cpu); 9569 if (new_cpu >= 0) 9570 return new_cpu; 9571 new_cpu = prev_cpu; 9572 } 9573 9574 want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr); 9575 } 9576 9577 for_each_domain(cpu, tmp) { 9578 /* 9579 * If both 'cpu' and 'prev_cpu' are part of this domain, 9580 * cpu is a valid SD_WAKE_AFFINE target. 9581 */ 9582 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) && 9583 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) { 9584 if (cpu != prev_cpu) 9585 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync); 9586 9587 sd = NULL; /* Prefer wake_affine over balance flags */ 9588 break; 9589 } 9590 9591 /* 9592 * Usually only true for WF_EXEC and WF_FORK, as sched_domains 9593 * usually do not have SD_BALANCE_WAKE set. That means wakeup 9594 * will usually go to the fast path. 9595 */ 9596 if (tmp->flags & sd_flag) 9597 sd = tmp; 9598 else if (!want_affine) 9599 break; 9600 } 9601 9602 /* Slow path */ 9603 if (unlikely(sd)) 9604 return sched_balance_find_dst_cpu(sd, p, cpu, prev_cpu, sd_flag); 9605 9606 /* Fast path */ 9607 if (wake_flags & WF_TTWU) 9608 return select_idle_sibling(p, prev_cpu, new_cpu); 9609 9610 return new_cpu; 9611 } 9612 9613 /* 9614 * Called immediately before a task is migrated to a new CPU; task_cpu(p) and 9615 * cfs_rq_of(p) references at time of call are still valid and identify the 9616 * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held. 9617 */ 9618 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu) 9619 { 9620 struct sched_entity *se = &p->se; 9621 9622 if (!task_on_rq_migrating(p)) { 9623 remove_entity_load_avg(se); 9624 9625 /* 9626 * Here, the task's PELT values have been updated according to 9627 * the current rq's clock. But if that clock hasn't been 9628 * updated in a while, a substantial idle time will be missed, 9629 * leading to an inflation after wake-up on the new rq. 9630 * 9631 * Estimate the missing time from the cfs_rq last_update_time 9632 * and update sched_avg to improve the PELT continuity after 9633 * migration. 9634 */ 9635 migrate_se_pelt_lag(se); 9636 } 9637 9638 /* Tell new CPU we are migrated */ 9639 se->avg.last_update_time = 0; 9640 9641 update_scan_period(p, new_cpu); 9642 } 9643 9644 static void task_dead_fair(struct task_struct *p) 9645 { 9646 struct sched_entity *se = &p->se; 9647 9648 if (se->sched_delayed) { 9649 struct rq_flags rf; 9650 struct rq *rq; 9651 9652 rq = task_rq_lock(p, &rf); 9653 if (se->sched_delayed) { 9654 update_rq_clock(rq); 9655 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED); 9656 } 9657 task_rq_unlock(rq, p, &rf); 9658 } 9659 9660 remove_entity_load_avg(se); 9661 } 9662 9663 /* 9664 * Set the max capacity the task is allowed to run at for misfit detection. 9665 */ 9666 static void set_task_max_allowed_capacity(struct task_struct *p) 9667 { 9668 struct asym_cap_data *entry; 9669 9670 if (!sched_asym_cpucap_active()) 9671 return; 9672 9673 rcu_read_lock(); 9674 list_for_each_entry_rcu(entry, &asym_cap_list, link) { 9675 cpumask_t *cpumask; 9676 9677 cpumask = cpu_capacity_span(entry); 9678 if (!cpumask_intersects(p->cpus_ptr, cpumask)) 9679 continue; 9680 9681 p->max_allowed_capacity = entry->capacity; 9682 break; 9683 } 9684 rcu_read_unlock(); 9685 } 9686 9687 static void set_cpus_allowed_fair(struct task_struct *p, struct affinity_context *ctx) 9688 { 9689 set_cpus_allowed_common(p, ctx); 9690 set_task_max_allowed_capacity(p); 9691 } 9692 9693 static void set_next_buddy(struct sched_entity *se) 9694 { 9695 for_each_sched_entity(se) { 9696 if (WARN_ON_ONCE(!se->on_rq)) 9697 return; 9698 if (se_is_idle(se)) 9699 return; 9700 cfs_rq_of(se)->next = se; 9701 } 9702 } 9703 9704 enum preempt_wakeup_action { 9705 PREEMPT_WAKEUP_NONE, /* No preemption. */ 9706 PREEMPT_WAKEUP_SHORT, /* Ignore slice protection. */ 9707 PREEMPT_WAKEUP_PICK, /* Let __pick_eevdf() decide. */ 9708 PREEMPT_WAKEUP_RESCHED, /* Force reschedule. */ 9709 }; 9710 9711 static inline bool 9712 set_preempt_buddy(struct cfs_rq *cfs_rq, int wake_flags, 9713 struct sched_entity *pse, struct sched_entity *se) 9714 { 9715 /* 9716 * Keep existing buddy if the deadline is sooner than pse. 9717 * The older buddy may be cache cold and completely unrelated 9718 * to the current wakeup but that is unpredictable where as 9719 * obeying the deadline is more in line with EEVDF objectives. 9720 */ 9721 if (cfs_rq->next && entity_before(cfs_rq->next, pse)) 9722 return false; 9723 9724 set_next_buddy(pse); 9725 return true; 9726 } 9727 9728 /* 9729 * WF_SYNC|WF_TTWU indicates the waker expects to sleep but it is not 9730 * strictly enforced because the hint is either misunderstood or 9731 * multiple tasks must be woken up. 9732 */ 9733 static inline enum preempt_wakeup_action 9734 preempt_sync(struct rq *rq, int wake_flags, 9735 struct sched_entity *pse, struct sched_entity *se) 9736 { 9737 u64 threshold, delta; 9738 9739 /* 9740 * WF_SYNC without WF_TTWU is not expected so warn if it happens even 9741 * though it is likely harmless. 9742 */ 9743 WARN_ON_ONCE(!(wake_flags & WF_TTWU)); 9744 9745 threshold = sysctl_sched_migration_cost; 9746 delta = rq_clock_task(rq) - se->exec_start; 9747 if ((s64)delta < 0) 9748 delta = 0; 9749 9750 /* 9751 * WF_RQ_SELECTED implies the tasks are stacking on a CPU when they 9752 * could run on other CPUs. Reduce the threshold before preemption is 9753 * allowed to an arbitrary lower value as it is more likely (but not 9754 * guaranteed) the waker requires the wakee to finish. 9755 */ 9756 if (wake_flags & WF_RQ_SELECTED) 9757 threshold >>= 2; 9758 9759 /* 9760 * As WF_SYNC is not strictly obeyed, allow some runtime for batch 9761 * wakeups to be issued. 9762 */ 9763 if (entity_before(pse, se) && delta >= threshold) 9764 return PREEMPT_WAKEUP_RESCHED; 9765 9766 return PREEMPT_WAKEUP_NONE; 9767 } 9768 9769 /* 9770 * Preempt the current task with a newly woken task if needed: 9771 */ 9772 static void wakeup_preempt_fair(struct rq *rq, struct task_struct *p, int wake_flags) 9773 { 9774 enum preempt_wakeup_action preempt_action = PREEMPT_WAKEUP_PICK; 9775 struct task_struct *donor = rq->donor; 9776 struct sched_entity *nse, *se = &donor->se, *pse = &p->se; 9777 struct cfs_rq *cfs_rq = task_cfs_rq(donor); 9778 int cse_is_idle, pse_is_idle; 9779 9780 /* 9781 * XXX Getting preempted by higher class, try and find idle CPU? 9782 */ 9783 if (p->sched_class != &fair_sched_class) 9784 return; 9785 9786 if (unlikely(se == pse)) 9787 return; 9788 9789 /* 9790 * This is possible from callers such as attach_tasks(), in which we 9791 * unconditionally wakeup_preempt() after an enqueue (which may have 9792 * lead to a throttle). This both saves work and prevents false 9793 * next-buddy nomination below. 9794 */ 9795 if (task_is_throttled(p)) 9796 return; 9797 9798 /* 9799 * We can come here with TIF_NEED_RESCHED already set from new task 9800 * wake up path. 9801 * 9802 * Note: this also catches the edge-case of curr being in a throttled 9803 * group (e.g. via set_curr_task), since update_curr() (in the 9804 * enqueue of curr) will have resulted in resched being set. This 9805 * prevents us from potentially nominating it as a false LAST_BUDDY 9806 * below. 9807 */ 9808 if (test_tsk_need_resched(rq->curr)) 9809 return; 9810 9811 if (!sched_feat(WAKEUP_PREEMPTION)) 9812 return; 9813 9814 find_matching_se(&se, &pse); 9815 WARN_ON_ONCE(!pse); 9816 9817 cse_is_idle = se_is_idle(se); 9818 pse_is_idle = se_is_idle(pse); 9819 9820 /* 9821 * Preempt an idle entity in favor of a non-idle entity (and don't preempt 9822 * in the inverse case). 9823 */ 9824 if (cse_is_idle && !pse_is_idle) { 9825 /* 9826 * When non-idle entity preempt an idle entity, 9827 * don't give idle entity slice protection. 9828 */ 9829 preempt_action = PREEMPT_WAKEUP_SHORT; 9830 goto preempt; 9831 } 9832 9833 if (cse_is_idle != pse_is_idle) 9834 return; 9835 9836 /* 9837 * BATCH and IDLE tasks do not preempt others. 9838 */ 9839 if (unlikely(!normal_policy(p->policy))) 9840 return; 9841 9842 cfs_rq = cfs_rq_of(se); 9843 update_curr(cfs_rq); 9844 /* 9845 * If @p has a shorter slice than current and @p is eligible, override 9846 * current's slice protection in order to allow preemption. 9847 */ 9848 if (sched_feat(PREEMPT_SHORT) && (pse->slice < se->slice)) { 9849 preempt_action = PREEMPT_WAKEUP_SHORT; 9850 goto pick; 9851 } 9852 9853 /* 9854 * Ignore wakee preemption on WF_FORK as it is less likely that 9855 * there is shared data as exec often follow fork. Do not 9856 * preempt for tasks that are sched_delayed as it would violate 9857 * EEVDF to forcibly queue an ineligible task. 9858 */ 9859 if ((wake_flags & WF_FORK) || pse->sched_delayed) 9860 return; 9861 9862 /* Prefer picking wakee soon if appropriate. */ 9863 if (sched_feat(NEXT_BUDDY) && 9864 set_preempt_buddy(cfs_rq, wake_flags, pse, se)) { 9865 9866 /* 9867 * Decide whether to obey WF_SYNC hint for a new buddy. Old 9868 * buddies are ignored as they may not be relevant to the 9869 * waker and less likely to be cache hot. 9870 */ 9871 if (wake_flags & WF_SYNC) 9872 preempt_action = preempt_sync(rq, wake_flags, pse, se); 9873 } 9874 9875 switch (preempt_action) { 9876 case PREEMPT_WAKEUP_NONE: 9877 return; 9878 case PREEMPT_WAKEUP_RESCHED: 9879 goto preempt; 9880 case PREEMPT_WAKEUP_SHORT: 9881 fallthrough; 9882 case PREEMPT_WAKEUP_PICK: 9883 break; 9884 } 9885 9886 pick: 9887 nse = pick_next_entity(rq, cfs_rq, preempt_action != PREEMPT_WAKEUP_SHORT); 9888 /* If @p has become the most eligible task, force preemption */ 9889 if (nse == pse) 9890 goto preempt; 9891 9892 /* 9893 * Because p is enqueued, nse being null can only mean that we 9894 * dequeued a delayed task. If there are still entities queued in 9895 * cfs, check if the next one will be p. 9896 */ 9897 if (!nse && cfs_rq->nr_queued) 9898 goto pick; 9899 9900 if (sched_feat(RUN_TO_PARITY)) 9901 update_protect_slice(cfs_rq, se); 9902 9903 return; 9904 9905 preempt: 9906 if (preempt_action == PREEMPT_WAKEUP_SHORT) { 9907 cancel_protect_slice(se); 9908 clear_buddies(cfs_rq, se); 9909 } 9910 9911 resched_curr_lazy(rq); 9912 } 9913 9914 struct task_struct *pick_task_fair(struct rq *rq, struct rq_flags *rf) 9915 __must_hold(__rq_lockp(rq)) 9916 { 9917 struct sched_entity *se; 9918 struct cfs_rq *cfs_rq; 9919 struct task_struct *p; 9920 bool throttled; 9921 int new_tasks; 9922 9923 again: 9924 cfs_rq = &rq->cfs; 9925 if (!cfs_rq->nr_queued) 9926 goto idle; 9927 9928 throttled = false; 9929 9930 do { 9931 /* Might not have done put_prev_entity() */ 9932 if (cfs_rq->curr && cfs_rq->curr->on_rq) 9933 update_curr(cfs_rq); 9934 9935 se = pick_next_entity(rq, cfs_rq, true); 9936 if (!se) 9937 goto again; 9938 cfs_rq = group_cfs_rq(se); 9939 } while (cfs_rq); 9940 9941 p = task_of(se); 9942 if (unlikely(throttled)) 9943 task_throttle_setup_work(p); 9944 return p; 9945 9946 idle: 9947 if (sched_core_enabled(rq)) 9948 return NULL; 9949 9950 new_tasks = sched_balance_newidle(rq, rf); 9951 if (new_tasks < 0) 9952 return RETRY_TASK; 9953 if (new_tasks > 0) 9954 goto again; 9955 return NULL; 9956 } 9957 9958 static struct task_struct * 9959 fair_server_pick_task(struct sched_dl_entity *dl_se, struct rq_flags *rf) 9960 __must_hold(__rq_lockp(dl_se->rq)) 9961 { 9962 return pick_task_fair(dl_se->rq, rf); 9963 } 9964 9965 void fair_server_init(struct rq *rq) 9966 { 9967 struct sched_dl_entity *dl_se = &rq->fair_server; 9968 9969 init_dl_entity(dl_se); 9970 9971 dl_server_init(dl_se, rq, fair_server_pick_task); 9972 } 9973 9974 /* 9975 * Account for a descheduled task: 9976 */ 9977 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev, struct task_struct *next) 9978 { 9979 struct sched_entity *se = &prev->se; 9980 struct cfs_rq *cfs_rq; 9981 struct sched_entity *nse = NULL; 9982 9983 #ifdef CONFIG_FAIR_GROUP_SCHED 9984 if (next && next->sched_class == &fair_sched_class) 9985 nse = &next->se; 9986 #endif 9987 9988 while (se) { 9989 cfs_rq = cfs_rq_of(se); 9990 if (!nse || cfs_rq->curr) 9991 put_prev_entity(cfs_rq, se); 9992 #ifdef CONFIG_FAIR_GROUP_SCHED 9993 if (nse) { 9994 if (is_same_group(se, nse)) 9995 break; 9996 9997 int d = nse->depth - se->depth; 9998 if (d >= 0) { 9999 /* nse has equal or greater depth, ascend */ 10000 nse = parent_entity(nse); 10001 /* if nse is the deeper, do not ascend se */ 10002 if (d > 0) 10003 continue; 10004 } 10005 } 10006 #endif 10007 se = parent_entity(se); 10008 } 10009 } 10010 10011 /* 10012 * sched_yield() is very simple 10013 */ 10014 static void yield_task_fair(struct rq *rq) 10015 { 10016 struct task_struct *curr = rq->donor; 10017 struct cfs_rq *cfs_rq = task_cfs_rq(curr); 10018 struct sched_entity *se = &curr->se; 10019 10020 /* 10021 * Are we the only task in the tree? 10022 */ 10023 if (unlikely(rq->nr_running == 1)) 10024 return; 10025 10026 clear_buddies(cfs_rq, se); 10027 10028 update_rq_clock(rq); 10029 /* 10030 * Update run-time statistics of the 'current'. 10031 */ 10032 update_curr(cfs_rq); 10033 /* 10034 * Tell update_rq_clock() that we've just updated, 10035 * so we don't do microscopic update in schedule() 10036 * and double the fastpath cost. 10037 */ 10038 rq_clock_skip_update(rq); 10039 10040 /* 10041 * Forfeit the remaining vruntime, only if the entity is eligible. This 10042 * condition is necessary because in core scheduling we prefer to run 10043 * ineligible tasks rather than force idling. If this happens we may 10044 * end up in a loop where the core scheduler picks the yielding task, 10045 * which yields immediately again; without the condition the vruntime 10046 * ends up quickly running away. 10047 */ 10048 if (entity_eligible(cfs_rq, se)) { 10049 se->vruntime = se->deadline; 10050 update_deadline(cfs_rq, se); 10051 } 10052 } 10053 10054 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p) 10055 { 10056 struct sched_entity *se = &p->se; 10057 10058 /* !se->on_rq also covers throttled task */ 10059 if (!se->on_rq) 10060 return false; 10061 10062 /* Tell the scheduler that we'd really like se to run next. */ 10063 set_next_buddy(se); 10064 10065 yield_task_fair(rq); 10066 10067 return true; 10068 } 10069 10070 /************************************************** 10071 * Fair scheduling class load-balancing methods. 10072 * 10073 * BASICS 10074 * 10075 * The purpose of load-balancing is to achieve the same basic fairness the 10076 * per-CPU scheduler provides, namely provide a proportional amount of compute 10077 * time to each task. This is expressed in the following equation: 10078 * 10079 * W_i,n/P_i == W_j,n/P_j for all i,j (1) 10080 * 10081 * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight 10082 * W_i,0 is defined as: 10083 * 10084 * W_i,0 = \Sum_j w_i,j (2) 10085 * 10086 * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight 10087 * is derived from the nice value as per sched_prio_to_weight[]. 10088 * 10089 * The weight average is an exponential decay average of the instantaneous 10090 * weight: 10091 * 10092 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3) 10093 * 10094 * C_i is the compute capacity of CPU i, typically it is the 10095 * fraction of 'recent' time available for SCHED_OTHER task execution. But it 10096 * can also include other factors [XXX]. 10097 * 10098 * To achieve this balance we define a measure of imbalance which follows 10099 * directly from (1): 10100 * 10101 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4) 10102 * 10103 * We them move tasks around to minimize the imbalance. In the continuous 10104 * function space it is obvious this converges, in the discrete case we get 10105 * a few fun cases generally called infeasible weight scenarios. 10106 * 10107 * [XXX expand on: 10108 * - infeasible weights; 10109 * - local vs global optima in the discrete case. ] 10110 * 10111 * 10112 * SCHED DOMAINS 10113 * 10114 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2) 10115 * for all i,j solution, we create a tree of CPUs that follows the hardware 10116 * topology where each level pairs two lower groups (or better). This results 10117 * in O(log n) layers. Furthermore we reduce the number of CPUs going up the 10118 * tree to only the first of the previous level and we decrease the frequency 10119 * of load-balance at each level inversely proportional to the number of CPUs in 10120 * the groups. 10121 * 10122 * This yields: 10123 * 10124 * log_2 n 1 n 10125 * \Sum { --- * --- * 2^i } = O(n) (5) 10126 * i = 0 2^i 2^i 10127 * `- size of each group 10128 * | | `- number of CPUs doing load-balance 10129 * | `- freq 10130 * `- sum over all levels 10131 * 10132 * Coupled with a limit on how many tasks we can migrate every balance pass, 10133 * this makes (5) the runtime complexity of the balancer. 10134 * 10135 * An important property here is that each CPU is still (indirectly) connected 10136 * to every other CPU in at most O(log n) steps: 10137 * 10138 * The adjacency matrix of the resulting graph is given by: 10139 * 10140 * log_2 n 10141 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6) 10142 * k = 0 10143 * 10144 * And you'll find that: 10145 * 10146 * A^(log_2 n)_i,j != 0 for all i,j (7) 10147 * 10148 * Showing there's indeed a path between every CPU in at most O(log n) steps. 10149 * The task movement gives a factor of O(m), giving a convergence complexity 10150 * of: 10151 * 10152 * O(nm log n), n := nr_cpus, m := nr_tasks (8) 10153 * 10154 * 10155 * WORK CONSERVING 10156 * 10157 * In order to avoid CPUs going idle while there's still work to do, new idle 10158 * balancing is more aggressive and has the newly idle CPU iterate up the domain 10159 * tree itself instead of relying on other CPUs to bring it work. 10160 * 10161 * This adds some complexity to both (5) and (8) but it reduces the total idle 10162 * time. 10163 * 10164 * [XXX more?] 10165 * 10166 * 10167 * CGROUPS 10168 * 10169 * Cgroups make a horror show out of (2), instead of a simple sum we get: 10170 * 10171 * s_k,i 10172 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9) 10173 * S_k 10174 * 10175 * Where 10176 * 10177 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10) 10178 * 10179 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i. 10180 * 10181 * The big problem is S_k, its a global sum needed to compute a local (W_i) 10182 * property. 10183 * 10184 * [XXX write more on how we solve this.. _after_ merging pjt's patches that 10185 * rewrite all of this once again.] 10186 */ 10187 10188 static unsigned long __read_mostly max_load_balance_interval = HZ/10; 10189 10190 enum fbq_type { regular, remote, all }; 10191 10192 /* 10193 * 'group_type' describes the group of CPUs at the moment of load balancing. 10194 * 10195 * The enum is ordered by pulling priority, with the group with lowest priority 10196 * first so the group_type can simply be compared when selecting the busiest 10197 * group. See update_sd_pick_busiest(). 10198 */ 10199 enum group_type { 10200 /* The group has spare capacity that can be used to run more tasks. */ 10201 group_has_spare = 0, 10202 /* 10203 * The group is fully used and the tasks don't compete for more CPU 10204 * cycles. Nevertheless, some tasks might wait before running. 10205 */ 10206 group_fully_busy, 10207 /* 10208 * One task doesn't fit with CPU's capacity and must be migrated to a 10209 * more powerful CPU. 10210 */ 10211 group_misfit_task, 10212 /* 10213 * Balance SMT group that's fully busy. Can benefit from migration 10214 * a task on SMT with busy sibling to another CPU on idle core. 10215 */ 10216 group_smt_balance, 10217 /* 10218 * SD_ASYM_PACKING only: One local CPU with higher capacity is available, 10219 * and the task should be migrated to it instead of running on the 10220 * current CPU. 10221 */ 10222 group_asym_packing, 10223 /* 10224 * The tasks' affinity constraints previously prevented the scheduler 10225 * from balancing the load across the system. 10226 */ 10227 group_imbalanced, 10228 /* 10229 * There are tasks running on non-preferred LLC, possible to move 10230 * them to their preferred LLC without creating too much imbalance. 10231 * The priority of group_llc_balance is lower than that of 10232 * group_overloaded and higher than that of all other group types. 10233 * This is because group_llc_balance may exacerbate load imbalance. 10234 * If the LLC balancing attempt fails, the nr_balance_failed 10235 * mechanism will trigger other group types to rebalance the load. 10236 */ 10237 group_llc_balance, 10238 /* 10239 * The CPU is overloaded and can't provide expected CPU cycles to all 10240 * tasks. 10241 */ 10242 group_overloaded 10243 }; 10244 10245 enum migration_type { 10246 migrate_load = 0, 10247 migrate_util, 10248 migrate_task, 10249 migrate_misfit, 10250 migrate_llc_task 10251 }; 10252 10253 #define LBF_ALL_PINNED 0x01 10254 #define LBF_NEED_BREAK 0x02 10255 #define LBF_DST_PINNED 0x04 10256 #define LBF_SOME_PINNED 0x08 10257 #define LBF_ACTIVE_LB 0x10 10258 #define LBF_LLC_PINNED 0x20 10259 10260 struct lb_env { 10261 struct sched_domain *sd; 10262 10263 struct rq *src_rq; 10264 int src_cpu; 10265 10266 int dst_cpu; 10267 struct rq *dst_rq; 10268 bool dst_core_idle; 10269 10270 struct cpumask *dst_grpmask; 10271 int new_dst_cpu; 10272 enum cpu_idle_type idle; 10273 long imbalance; 10274 /* The set of CPUs under consideration for load-balancing */ 10275 struct cpumask *cpus; 10276 10277 unsigned int flags; 10278 10279 unsigned int loop; 10280 unsigned int loop_break; 10281 unsigned int loop_max; 10282 10283 enum fbq_type fbq_type; 10284 enum migration_type migration_type; 10285 struct list_head tasks; 10286 }; 10287 10288 /* 10289 * Is this task likely cache-hot: 10290 */ 10291 static int task_hot(struct task_struct *p, struct lb_env *env) 10292 { 10293 s64 delta; 10294 10295 lockdep_assert_rq_held(env->src_rq); 10296 10297 if (p->sched_class != &fair_sched_class) 10298 return 0; 10299 10300 if (unlikely(task_has_idle_policy(p))) 10301 return 0; 10302 10303 /* SMT siblings share cache */ 10304 if (env->sd->flags & SD_SHARE_CPUCAPACITY) 10305 return 0; 10306 10307 /* 10308 * Buddy candidates are cache hot: 10309 */ 10310 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running && 10311 (&p->se == cfs_rq_of(&p->se)->next)) 10312 return 1; 10313 10314 if (sysctl_sched_migration_cost == -1) 10315 return 1; 10316 10317 /* 10318 * Don't migrate task if the task's cookie does not match 10319 * with the destination CPU's core cookie. 10320 */ 10321 if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p)) 10322 return 1; 10323 10324 if (sysctl_sched_migration_cost == 0) 10325 return 0; 10326 10327 delta = rq_clock_task(env->src_rq) - p->se.exec_start; 10328 10329 return delta < (s64)sysctl_sched_migration_cost; 10330 } 10331 10332 #ifdef CONFIG_NUMA_BALANCING 10333 /* 10334 * Returns a positive value, if task migration degrades locality. 10335 * Returns 0, if task migration is not affected by locality. 10336 * Returns a negative value, if task migration improves locality i.e migration preferred. 10337 */ 10338 static long migrate_degrades_locality(struct task_struct *p, struct lb_env *env) 10339 { 10340 struct numa_group *numa_group = rcu_dereference_all(p->numa_group); 10341 unsigned long src_weight, dst_weight; 10342 int src_nid, dst_nid, dist; 10343 10344 if (!static_branch_likely(&sched_numa_balancing)) 10345 return 0; 10346 10347 if (!p->numa_faults || !(env->sd->flags & SD_NUMA)) 10348 return 0; 10349 10350 src_nid = cpu_to_node(env->src_cpu); 10351 dst_nid = cpu_to_node(env->dst_cpu); 10352 10353 if (src_nid == dst_nid) 10354 return 0; 10355 10356 /* Migrating away from the preferred node is always bad. */ 10357 if (src_nid == p->numa_preferred_nid) { 10358 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running) 10359 return 1; 10360 else 10361 return 0; 10362 } 10363 10364 /* Encourage migration to the preferred node. */ 10365 if (dst_nid == p->numa_preferred_nid) 10366 return -1; 10367 10368 /* Leaving a core idle is often worse than degrading locality. */ 10369 if (env->idle == CPU_IDLE) 10370 return 0; 10371 10372 dist = node_distance(src_nid, dst_nid); 10373 if (numa_group) { 10374 src_weight = group_weight(p, src_nid, dist); 10375 dst_weight = group_weight(p, dst_nid, dist); 10376 } else { 10377 src_weight = task_weight(p, src_nid, dist); 10378 dst_weight = task_weight(p, dst_nid, dist); 10379 } 10380 10381 return src_weight - dst_weight; 10382 } 10383 10384 #else /* !CONFIG_NUMA_BALANCING: */ 10385 static inline long migrate_degrades_locality(struct task_struct *p, 10386 struct lb_env *env) 10387 { 10388 return 0; 10389 } 10390 #endif /* !CONFIG_NUMA_BALANCING */ 10391 10392 /* 10393 * Check whether the task is ineligible on the destination cpu 10394 * 10395 * When the PLACE_LAG scheduling feature is enabled and 10396 * dst_cfs_rq->nr_queued is greater than 1, if the task 10397 * is ineligible, it will also be ineligible when 10398 * it is migrated to the destination cpu. 10399 */ 10400 static inline int task_is_ineligible_on_dst_cpu(struct task_struct *p, int dest_cpu) 10401 { 10402 struct cfs_rq *dst_cfs_rq; 10403 10404 #ifdef CONFIG_FAIR_GROUP_SCHED 10405 dst_cfs_rq = tg_cfs_rq(task_group(p), dest_cpu); 10406 #else 10407 dst_cfs_rq = &cpu_rq(dest_cpu)->cfs; 10408 #endif 10409 if (sched_feat(PLACE_LAG) && dst_cfs_rq->nr_queued && 10410 !entity_eligible(task_cfs_rq(p), &p->se)) 10411 return 1; 10412 10413 return 0; 10414 } 10415 10416 #ifdef CONFIG_SCHED_CACHE 10417 /* 10418 * The margin used when comparing LLC utilization with CPU capacity. 10419 * It determines the LLC load level where active LLC aggregation is 10420 * done. 10421 * Derived from fits_capacity(). 10422 * 10423 * (default: ~50%, tunable via debugfs) 10424 */ 10425 static bool fits_llc_capacity(unsigned long util, unsigned long max) 10426 { 10427 u32 aggr_pct = llc_overaggr_pct; 10428 10429 /* 10430 * For single core systems, raise the aggregation 10431 * threshold to accommodate more tasks. 10432 */ 10433 if (cpu_smt_num_threads == 1) 10434 aggr_pct = (aggr_pct * 3 / 2); 10435 10436 return util * 100 < max * aggr_pct; 10437 } 10438 10439 /* 10440 * The margin used when comparing utilization. 10441 * is 'util1' noticeably greater than 'util2' 10442 * Derived from capacity_greater(). 10443 * Bias is in perentage. 10444 */ 10445 /* Allows dst util to be bigger than src util by up to bias percent */ 10446 #define util_greater(util1, util2) \ 10447 ((util1) * 100 > (util2) * (100 + llc_imb_pct)) 10448 10449 static __maybe_unused bool get_llc_stats(int cpu, unsigned long *util, 10450 unsigned long *cap) 10451 { 10452 struct sched_domain_shared *sd_share; 10453 10454 sd_share = rcu_dereference_all(per_cpu(sd_llc_shared, cpu)); 10455 if (!sd_share) 10456 return false; 10457 10458 *util = READ_ONCE(sd_share->util_avg); 10459 *cap = READ_ONCE(sd_share->capacity); 10460 10461 return true; 10462 } 10463 10464 /* 10465 * Decision matrix according to the LLC utilization. To 10466 * decide whether we can do task aggregation across LLC. 10467 * 10468 * By default, 50% is the threshold for treating the LLC 10469 * as busy. The reason for choosing 50% is to avoid saturation 10470 * of SMT-2, and it is also a safe cutoff for other SMT-n 10471 * platforms. SMT-1 has higher threshold because it is 10472 * supposed to accommodate more tasks, see fits_llc_capacity(). 10473 * 10474 * 20% is the utilization imbalance percentage to decide 10475 * if the preferred LLC is busier than the non-preferred LLC. 10476 * 20 is a little higher than the LLC domain's imbalance_pct 10477 * 17. The hysteresis is used to avoid task bouncing between the 10478 * preferred LLC and the non-preferred LLC, and it will 10479 * be turned into tunable debugfs. 10480 * 10481 * 1. moving towards the preferred LLC, dst is the preferred 10482 * LLC, src is not. 10483 * 10484 * src \ dst 30% 40% 50% 60% 10485 * 30% Y Y Y N 10486 * 40% Y Y Y Y 10487 * 50% Y Y G G 10488 * 60% Y Y G G 10489 * 10490 * 2. moving out of the preferred LLC, src is the preferred 10491 * LLC, dst is not: 10492 * 10493 * src \ dst 30% 40% 50% 60% 10494 * 30% N N N N 10495 * 40% N N N N 10496 * 50% N N G G 10497 * 60% Y N G G 10498 * 10499 * src : src_util 10500 * dst : dst_util 10501 * Y : Yes, migrate 10502 * N : No, do not migrate 10503 * G : let the Generic load balance to even the load. 10504 * 10505 * The intention is that if both LLCs are quite busy, cache aware 10506 * load balance should not be performed, and generic load balance 10507 * should take effect. However, if one is busy and the other is not, 10508 * the preferred LLC capacity(50%) and imbalance criteria(20%) should 10509 * be considered to determine whether LLC aggregation should be 10510 * performed to bias the load towards the preferred LLC. 10511 */ 10512 10513 /* migration decision, 3 states are orthogonal. */ 10514 enum llc_mig { 10515 mig_forbid = 0, /* N: Don't migrate task, respect LLC preference */ 10516 mig_llc, /* Y: Do LLC preference based migration */ 10517 mig_unrestricted /* G: Don't restrict generic load balance migration */ 10518 }; 10519 10520 /* 10521 * Check if task can be moved from the source LLC to the 10522 * destination LLC without breaking cache aware preferrence. 10523 * src_cpu and dst_cpu are arbitrary CPUs within the source 10524 * and destination LLCs, respectively. 10525 */ 10526 static enum llc_mig can_migrate_llc(int src_cpu, int dst_cpu, 10527 unsigned long tsk_util, 10528 bool to_pref) 10529 { 10530 unsigned long src_util, dst_util, src_cap, dst_cap; 10531 10532 if (!get_llc_stats(src_cpu, &src_util, &src_cap) || 10533 !get_llc_stats(dst_cpu, &dst_util, &dst_cap)) 10534 return mig_unrestricted; 10535 10536 src_util = src_util < tsk_util ? 0 : src_util - tsk_util; 10537 dst_util = dst_util + tsk_util; 10538 10539 if (!fits_llc_capacity(dst_util, dst_cap) && 10540 !fits_llc_capacity(src_util, src_cap)) 10541 return mig_unrestricted; 10542 10543 if (to_pref) { 10544 /* 10545 * Don't migrate if we will get preferred LLC too 10546 * heavily loaded and if the dest is much busier 10547 * than the src, in which case migration will 10548 * increase the imbalance too much. 10549 */ 10550 if (!fits_llc_capacity(dst_util, dst_cap) && 10551 util_greater(dst_util, src_util)) 10552 return mig_forbid; 10553 } else { 10554 /* 10555 * Don't migrate if we will leave preferred LLC 10556 * too idle, or if this migration leads to the 10557 * non-preferred LLC falls within sysctl_aggr_imb percent 10558 * of preferred LLC, leading to migration again 10559 * back to preferred LLC. 10560 */ 10561 if (fits_llc_capacity(src_util, src_cap) || 10562 !util_greater(src_util, dst_util)) 10563 return mig_forbid; 10564 } 10565 return mig_llc; 10566 } 10567 10568 /* 10569 * Check if task p can migrate from source LLC to 10570 * destination LLC in terms of cache aware load balance. 10571 */ 10572 static enum llc_mig can_migrate_llc_task(int src_cpu, int dst_cpu, 10573 struct task_struct *p) 10574 { 10575 struct mm_struct *mm; 10576 bool to_pref; 10577 int cpu; 10578 10579 mm = p->mm; 10580 if (!mm) 10581 return mig_unrestricted; 10582 10583 cpu = READ_ONCE(mm->sc_stat.cpu); 10584 if (cpu < 0 || cpus_share_cache(src_cpu, dst_cpu)) 10585 return mig_unrestricted; 10586 10587 /* skip cache aware load balance for too many threads */ 10588 if (invalid_llc_nr(mm, p, dst_cpu) || 10589 exceed_llc_capacity(mm, dst_cpu)) { 10590 if (READ_ONCE(mm->sc_stat.cpu) != -1) 10591 WRITE_ONCE(mm->sc_stat.cpu, -1); 10592 return mig_unrestricted; 10593 } 10594 10595 if (cpus_share_cache(dst_cpu, cpu)) 10596 to_pref = true; 10597 else if (cpus_share_cache(src_cpu, cpu)) 10598 to_pref = false; 10599 else 10600 return mig_unrestricted; 10601 10602 return can_migrate_llc(src_cpu, dst_cpu, 10603 task_util(p), to_pref); 10604 } 10605 10606 /* 10607 * Check if active load balance breaks LLC locality in 10608 * terms of cache aware load balance. The load level and 10609 * imbalance do not warrant breaking LLC preference per 10610 * the can_migrate_llc() policy. Here, the benefit of 10611 * LLC locality outweighs the power efficiency gained from 10612 * migrating the only runnable task away. 10613 */ 10614 static inline bool 10615 alb_break_llc(struct lb_env *env) 10616 { 10617 if (!sched_cache_enabled()) 10618 return false; 10619 10620 if (cpus_share_cache(env->src_cpu, env->dst_cpu)) 10621 return false; 10622 /* 10623 * All tasks prefer to stay on their current CPU. 10624 * Do not pull a task from its preferred CPU if: 10625 * 1. It is the only task running and does not exceed 10626 * imbalance allowance; OR 10627 * 2. Migrating it away from its preferred LLC would violate 10628 * the cache-aware scheduling policy. 10629 */ 10630 if (env->src_rq->nr_pref_llc_running && 10631 env->src_rq->nr_pref_llc_running == env->src_rq->cfs.h_nr_runnable) { 10632 unsigned long util = 0; 10633 struct task_struct *cur; 10634 10635 if (env->src_rq->nr_running <= 1) 10636 return true; 10637 10638 cur = rcu_dereference_all(env->src_rq->curr); 10639 if (cur && cur->sched_class == &fair_sched_class) 10640 util = task_util(cur); 10641 10642 if (can_migrate_llc(env->src_cpu, env->dst_cpu, 10643 util, false) == mig_forbid) 10644 return true; 10645 } 10646 10647 return false; 10648 } 10649 10650 /* 10651 * Check if migrating task p from env->src_cpu to 10652 * env->dst_cpu breaks LLC localiy. 10653 */ 10654 static bool migrate_degrades_llc(struct task_struct *p, struct lb_env *env) 10655 { 10656 if (!sched_cache_enabled()) 10657 return false; 10658 10659 if (task_has_sched_core(p)) 10660 return false; 10661 /* 10662 * Skip over tasks that would degrade LLC locality; 10663 * only when nr_balanced_failed is sufficiently high do we 10664 * ignore this constraint. 10665 * 10666 * Threshold of cache_nice_tries is set to 1 higher 10667 * than nr_balance_failed to avoid excessive task 10668 * migration at the same time. 10669 */ 10670 if (env->sd->nr_balance_failed >= env->sd->cache_nice_tries + 1) 10671 return false; 10672 10673 /* 10674 * We know the env->src_cpu has some tasks prefer to 10675 * run on env->dst_cpu, skip the tasks do not prefer 10676 * env->dst_cpu, and find the one that prefers. 10677 */ 10678 if (env->migration_type == migrate_llc_task && 10679 READ_ONCE(p->preferred_llc) != llc_id(env->dst_cpu)) 10680 return true; 10681 10682 if (can_migrate_llc_task(env->src_cpu, 10683 env->dst_cpu, p) != mig_forbid) 10684 return false; 10685 10686 return true; 10687 } 10688 10689 #else 10690 static inline bool get_llc_stats(int cpu, unsigned long *util, 10691 unsigned long *cap) 10692 { 10693 return false; 10694 } 10695 10696 static inline bool 10697 alb_break_llc(struct lb_env *env) 10698 { 10699 return false; 10700 } 10701 10702 static inline bool 10703 migrate_degrades_llc(struct task_struct *p, struct lb_env *env) 10704 { 10705 return false; 10706 } 10707 #endif 10708 /* 10709 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu? 10710 */ 10711 static 10712 int can_migrate_task(struct task_struct *p, struct lb_env *env) 10713 { 10714 long degrades, hot; 10715 10716 lockdep_assert_rq_held(env->src_rq); 10717 if (p->sched_task_hot) 10718 p->sched_task_hot = 0; 10719 10720 /* 10721 * We do not migrate tasks that are: 10722 * 1) delayed dequeued unless we migrate load, or 10723 * 2) target cfs_rq is in throttled hierarchy, or 10724 * 3) cannot be migrated to this CPU due to cpus_ptr, or 10725 * 4) running (obviously), or 10726 * 5) are cache-hot on their current CPU, or 10727 * 6) are blocked on mutexes (if SCHED_PROXY_EXEC is enabled) 10728 */ 10729 if ((p->se.sched_delayed) && (env->migration_type != migrate_load)) 10730 return 0; 10731 10732 if (lb_throttled_hierarchy(p, env->dst_cpu)) 10733 return 0; 10734 10735 /* 10736 * We want to prioritize the migration of eligible tasks. 10737 * For ineligible tasks we soft-limit them and only allow 10738 * them to migrate when nr_balance_failed is non-zero to 10739 * avoid load-balancing trying very hard to balance the load. 10740 */ 10741 if (!env->sd->nr_balance_failed && 10742 task_is_ineligible_on_dst_cpu(p, env->dst_cpu)) 10743 return 0; 10744 10745 /* Disregard percpu kthreads; they are where they need to be. */ 10746 if (kthread_is_per_cpu(p)) 10747 return 0; 10748 10749 if (task_is_blocked(p)) 10750 return 0; 10751 10752 if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) { 10753 int cpu; 10754 10755 schedstat_inc(p->stats.nr_failed_migrations_affine); 10756 10757 env->flags |= LBF_SOME_PINNED; 10758 10759 /* 10760 * Remember if this task can be migrated to any other CPU in 10761 * our sched_group. We may want to revisit it if we couldn't 10762 * meet load balance goals by pulling other tasks on src_cpu. 10763 * 10764 * Avoid computing new_dst_cpu 10765 * - for NEWLY_IDLE 10766 * - if we have already computed one in current iteration 10767 * - if it's an active balance 10768 */ 10769 if (env->idle == CPU_NEWLY_IDLE || 10770 env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB)) 10771 return 0; 10772 10773 /* Prevent to re-select dst_cpu via env's CPUs: */ 10774 cpu = cpumask_first_and_and(env->dst_grpmask, env->cpus, p->cpus_ptr); 10775 10776 if (cpu < nr_cpu_ids) { 10777 env->flags |= LBF_DST_PINNED; 10778 env->new_dst_cpu = cpu; 10779 } 10780 10781 return 0; 10782 } 10783 10784 /* Record that we found at least one task that could run on dst_cpu */ 10785 env->flags &= ~LBF_ALL_PINNED; 10786 10787 if (task_on_cpu(env->src_rq, p) || 10788 task_current_donor(env->src_rq, p)) { 10789 schedstat_inc(p->stats.nr_failed_migrations_running); 10790 return 0; 10791 } 10792 10793 /* 10794 * Aggressive migration if: 10795 * 1) active balance 10796 * 2) destination numa is preferred 10797 * 3) task is cache cold, or 10798 * 4) too many balance attempts have failed. 10799 */ 10800 if (env->flags & LBF_ACTIVE_LB) 10801 return 1; 10802 10803 degrades = migrate_degrades_locality(p, env); 10804 if (!degrades) { 10805 /* 10806 * If the NUMA locality is not broken, 10807 * further check if migration would hurt 10808 * LLC locality. 10809 */ 10810 if (migrate_degrades_llc(p, env)) { 10811 /* 10812 * If regular load balancing fails to pull a task 10813 * due to LLC locality, this is expected behavior 10814 * and we set LBF_LLC_PINNED so we don't increase 10815 * nr_balance_failed unecessarily. 10816 */ 10817 if (env->migration_type != migrate_llc_task) 10818 env->flags |= LBF_LLC_PINNED; 10819 10820 return 0; 10821 } 10822 10823 hot = task_hot(p, env); 10824 } else { 10825 hot = degrades > 0; 10826 } 10827 10828 if (!hot || env->sd->nr_balance_failed > env->sd->cache_nice_tries) { 10829 if (hot) 10830 p->sched_task_hot = 1; 10831 return 1; 10832 } 10833 10834 schedstat_inc(p->stats.nr_failed_migrations_hot); 10835 return 0; 10836 } 10837 10838 /* 10839 * detach_task() -- detach the task for the migration specified in env 10840 */ 10841 static void detach_task(struct task_struct *p, struct lb_env *env) 10842 { 10843 lockdep_assert_rq_held(env->src_rq); 10844 10845 if (p->sched_task_hot) { 10846 p->sched_task_hot = 0; 10847 schedstat_inc(env->sd->lb_hot_gained[env->idle]); 10848 schedstat_inc(p->stats.nr_forced_migrations); 10849 } 10850 10851 WARN_ON(task_current(env->src_rq, p)); 10852 WARN_ON(task_current_donor(env->src_rq, p)); 10853 10854 deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK); 10855 set_task_cpu(p, env->dst_cpu); 10856 } 10857 10858 /* 10859 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as 10860 * part of active balancing operations within "domain". 10861 * 10862 * Returns a task if successful and NULL otherwise. 10863 */ 10864 static struct task_struct *detach_one_task(struct lb_env *env) 10865 { 10866 struct task_struct *p; 10867 10868 lockdep_assert_rq_held(env->src_rq); 10869 10870 list_for_each_entry_reverse(p, 10871 &env->src_rq->cfs_tasks, se.group_node) { 10872 if (!can_migrate_task(p, env)) 10873 continue; 10874 10875 detach_task(p, env); 10876 10877 /* 10878 * Right now, this is only the second place where 10879 * lb_gained[env->idle] is updated (other is detach_tasks) 10880 * so we can safely collect stats here rather than 10881 * inside detach_tasks(). 10882 */ 10883 schedstat_inc(env->sd->lb_gained[env->idle]); 10884 return p; 10885 } 10886 return NULL; 10887 } 10888 10889 /* 10890 * detach_tasks() -- tries to detach up to imbalance load/util/tasks from 10891 * busiest_rq, as part of a balancing operation within domain "sd". 10892 * 10893 * Returns number of detached tasks if successful and 0 otherwise. 10894 */ 10895 static int detach_tasks(struct lb_env *env) 10896 { 10897 struct list_head *tasks = &env->src_rq->cfs_tasks; 10898 unsigned long util, load; 10899 struct task_struct *p; 10900 int detached = 0; 10901 10902 lockdep_assert_rq_held(env->src_rq); 10903 10904 /* 10905 * Source run queue has been emptied by another CPU, clear 10906 * LBF_ALL_PINNED flag as we will not test any task. 10907 */ 10908 if (env->src_rq->nr_running <= 1) { 10909 env->flags &= ~LBF_ALL_PINNED; 10910 return 0; 10911 } 10912 10913 if (env->imbalance <= 0) 10914 return 0; 10915 10916 while (!list_empty(tasks)) { 10917 /* 10918 * We don't want to steal all, otherwise we may be treated likewise, 10919 * which could at worst lead to a livelock crash. 10920 */ 10921 if (env->idle && env->src_rq->nr_running <= 1) 10922 break; 10923 10924 env->loop++; 10925 /* We've more or less seen every task there is, call it quits */ 10926 if (env->loop > env->loop_max) 10927 break; 10928 10929 /* take a breather every nr_migrate tasks */ 10930 if (env->loop > env->loop_break) { 10931 env->loop_break += SCHED_NR_MIGRATE_BREAK; 10932 env->flags |= LBF_NEED_BREAK; 10933 break; 10934 } 10935 10936 p = list_last_entry(tasks, struct task_struct, se.group_node); 10937 10938 if (!can_migrate_task(p, env)) 10939 goto next; 10940 10941 switch (env->migration_type) { 10942 case migrate_load: 10943 /* 10944 * Depending of the number of CPUs and tasks and the 10945 * cgroup hierarchy, task_h_load() can return a null 10946 * value. Make sure that env->imbalance decreases 10947 * otherwise detach_tasks() will stop only after 10948 * detaching up to loop_max tasks. 10949 */ 10950 load = max_t(unsigned long, task_h_load(p), 1); 10951 10952 if (sched_feat(LB_MIN) && 10953 load < 16 && !env->sd->nr_balance_failed) 10954 goto next; 10955 10956 /* 10957 * Make sure that we don't migrate too much load. 10958 * Nevertheless, let relax the constraint if 10959 * scheduler fails to find a good waiting task to 10960 * migrate. 10961 */ 10962 if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance) 10963 goto next; 10964 10965 env->imbalance -= load; 10966 break; 10967 10968 case migrate_util: 10969 util = task_util_est(p); 10970 10971 if (shr_bound(util, env->sd->nr_balance_failed) > env->imbalance) 10972 goto next; 10973 10974 env->imbalance -= util; 10975 break; 10976 10977 case migrate_task: 10978 env->imbalance--; 10979 break; 10980 10981 case migrate_misfit: 10982 /* This is not a misfit task */ 10983 if (task_fits_cpu(p, env->src_cpu)) 10984 goto next; 10985 10986 env->imbalance = 0; 10987 break; 10988 10989 case migrate_llc_task: 10990 env->imbalance--; 10991 break; 10992 } 10993 10994 detach_task(p, env); 10995 list_add(&p->se.group_node, &env->tasks); 10996 10997 detached++; 10998 10999 #ifdef CONFIG_PREEMPTION 11000 /* 11001 * NEWIDLE balancing is a source of latency, so preemptible 11002 * kernels will stop after the first task is detached to minimize 11003 * the critical section. 11004 */ 11005 if (env->idle == CPU_NEWLY_IDLE) 11006 break; 11007 #endif 11008 11009 /* 11010 * We only want to steal up to the prescribed amount of 11011 * load/util/tasks. 11012 */ 11013 if (env->imbalance <= 0) 11014 break; 11015 11016 continue; 11017 next: 11018 if (p->sched_task_hot) 11019 schedstat_inc(p->stats.nr_failed_migrations_hot); 11020 11021 list_move(&p->se.group_node, tasks); 11022 } 11023 11024 /* 11025 * Right now, this is one of only two places we collect this stat 11026 * so we can safely collect detach_one_task() stats here rather 11027 * than inside detach_one_task(). 11028 */ 11029 schedstat_add(env->sd->lb_gained[env->idle], detached); 11030 11031 return detached; 11032 } 11033 11034 /* 11035 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their 11036 * new rq. 11037 */ 11038 static void attach_tasks(struct lb_env *env) 11039 { 11040 struct list_head *tasks = &env->tasks; 11041 struct task_struct *p; 11042 struct rq_flags rf; 11043 11044 rq_lock(env->dst_rq, &rf); 11045 update_rq_clock(env->dst_rq); 11046 11047 while (!list_empty(tasks)) { 11048 p = list_first_entry(tasks, struct task_struct, se.group_node); 11049 list_del_init(&p->se.group_node); 11050 11051 attach_task(env->dst_rq, p); 11052 } 11053 11054 rq_unlock(env->dst_rq, &rf); 11055 } 11056 11057 #ifdef CONFIG_NO_HZ_COMMON 11058 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq) 11059 { 11060 if (cfs_rq->avg.load_avg) 11061 return true; 11062 11063 if (cfs_rq->avg.util_avg) 11064 return true; 11065 11066 return false; 11067 } 11068 11069 static inline bool others_have_blocked(struct rq *rq) 11070 { 11071 if (cpu_util_rt(rq)) 11072 return true; 11073 11074 if (cpu_util_dl(rq)) 11075 return true; 11076 11077 if (hw_load_avg(rq)) 11078 return true; 11079 11080 if (cpu_util_irq(rq)) 11081 return true; 11082 11083 return false; 11084 } 11085 11086 static inline void update_blocked_load_tick(struct rq *rq) 11087 { 11088 WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies); 11089 } 11090 11091 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load) 11092 { 11093 if (!has_blocked_load) 11094 rq->has_blocked_load = 0; 11095 } 11096 #else /* !CONFIG_NO_HZ_COMMON: */ 11097 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq) { return false; } 11098 static inline bool others_have_blocked(struct rq *rq) { return false; } 11099 static inline void update_blocked_load_tick(struct rq *rq) {} 11100 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load) {} 11101 #endif /* !CONFIG_NO_HZ_COMMON */ 11102 11103 static bool __update_blocked_others(struct rq *rq, bool *done) 11104 { 11105 bool updated; 11106 11107 /* 11108 * update_load_avg() can call cpufreq_update_util(). Make sure that RT, 11109 * DL and IRQ signals have been updated before updating CFS. 11110 */ 11111 updated = update_other_load_avgs(rq); 11112 11113 if (others_have_blocked(rq)) 11114 *done = false; 11115 11116 return updated; 11117 } 11118 11119 #ifdef CONFIG_FAIR_GROUP_SCHED 11120 11121 static bool __update_blocked_fair(struct rq *rq, bool *done) 11122 { 11123 struct cfs_rq *cfs_rq, *pos; 11124 bool decayed = false; 11125 11126 /* 11127 * Iterates the task_group tree in a bottom up fashion, see 11128 * list_add_leaf_cfs_rq() for details. 11129 */ 11130 for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) { 11131 struct sched_entity *se; 11132 11133 if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) { 11134 update_tg_load_avg(cfs_rq); 11135 11136 if (cfs_rq->nr_queued == 0) 11137 update_idle_cfs_rq_clock_pelt(cfs_rq); 11138 11139 if (cfs_rq == &rq->cfs) 11140 decayed = true; 11141 } 11142 11143 /* Propagate pending load changes to the parent, if any: */ 11144 se = cfs_rq_se(cfs_rq); 11145 if (se && !skip_blocked_update(se)) 11146 update_load_avg(cfs_rq_of(se), se, UPDATE_TG); 11147 11148 /* 11149 * There can be a lot of idle CPU cgroups. Don't let fully 11150 * decayed cfs_rqs linger on the list. 11151 */ 11152 if (cfs_rq_is_decayed(cfs_rq)) 11153 list_del_leaf_cfs_rq(cfs_rq); 11154 11155 /* Don't need periodic decay once load/util_avg are null */ 11156 if (cfs_rq_has_blocked_load(cfs_rq)) 11157 *done = false; 11158 } 11159 11160 return decayed; 11161 } 11162 11163 /* 11164 * Compute the hierarchical load factor for cfs_rq and all its ascendants. 11165 * This needs to be done in a top-down fashion because the load of a child 11166 * group is a fraction of its parents load. 11167 */ 11168 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq) 11169 { 11170 struct sched_entity *se = cfs_rq_se(cfs_rq); 11171 unsigned long now = jiffies; 11172 unsigned long load; 11173 11174 if (cfs_rq->last_h_load_update == now) 11175 return; 11176 11177 WRITE_ONCE(cfs_rq->h_load_next, NULL); 11178 for_each_sched_entity(se) { 11179 cfs_rq = cfs_rq_of(se); 11180 WRITE_ONCE(cfs_rq->h_load_next, se); 11181 if (cfs_rq->last_h_load_update == now) 11182 break; 11183 } 11184 11185 if (!se) { 11186 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq); 11187 cfs_rq->last_h_load_update = now; 11188 } 11189 11190 while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) { 11191 load = cfs_rq->h_load; 11192 load = div64_ul(load * se->avg.load_avg, 11193 cfs_rq_load_avg(cfs_rq) + 1); 11194 cfs_rq = group_cfs_rq(se); 11195 cfs_rq->h_load = load; 11196 cfs_rq->last_h_load_update = now; 11197 } 11198 } 11199 11200 static unsigned long task_h_load(struct task_struct *p) 11201 { 11202 struct cfs_rq *cfs_rq = task_cfs_rq(p); 11203 11204 update_cfs_rq_h_load(cfs_rq); 11205 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load, 11206 cfs_rq_load_avg(cfs_rq) + 1); 11207 } 11208 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 11209 static bool __update_blocked_fair(struct rq *rq, bool *done) 11210 { 11211 struct cfs_rq *cfs_rq = &rq->cfs; 11212 bool decayed; 11213 11214 decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq); 11215 if (cfs_rq_has_blocked_load(cfs_rq)) 11216 *done = false; 11217 11218 return decayed; 11219 } 11220 11221 static unsigned long task_h_load(struct task_struct *p) 11222 { 11223 return p->se.avg.load_avg; 11224 } 11225 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 11226 11227 static void __sched_balance_update_blocked_averages(struct rq *rq) 11228 { 11229 bool decayed = false, done = true; 11230 11231 update_blocked_load_tick(rq); 11232 11233 decayed |= __update_blocked_others(rq, &done); 11234 decayed |= __update_blocked_fair(rq, &done); 11235 11236 update_has_blocked_load_status(rq, !done); 11237 if (decayed) 11238 cpufreq_update_util(rq, 0); 11239 } 11240 11241 static void sched_balance_update_blocked_averages(int cpu) 11242 { 11243 struct rq *rq = cpu_rq(cpu); 11244 11245 guard(rq_lock_irqsave)(rq); 11246 update_rq_clock(rq); 11247 __sched_balance_update_blocked_averages(rq); 11248 } 11249 11250 /********** Helpers for sched_balance_find_src_group ************************/ 11251 11252 /* 11253 * sg_lb_stats - stats of a sched_group required for load-balancing: 11254 */ 11255 struct sg_lb_stats { 11256 unsigned long avg_load; /* Avg load over the CPUs of the group */ 11257 unsigned long group_load; /* Total load over the CPUs of the group */ 11258 unsigned long group_capacity; /* Capacity over the CPUs of the group */ 11259 unsigned long group_util; /* Total utilization over the CPUs of the group */ 11260 unsigned long group_runnable; /* Total runnable time over the CPUs of the group */ 11261 unsigned int sum_nr_running; /* Nr of all tasks running in the group */ 11262 unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */ 11263 unsigned int idle_cpus; /* Nr of idle CPUs in the group */ 11264 unsigned int group_weight; 11265 enum group_type group_type; 11266 unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */ 11267 unsigned int group_smt_balance; /* Task on busy SMT be moved */ 11268 unsigned int group_llc_balance; /* Tasks should be moved to preferred LLC */ 11269 unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */ 11270 unsigned int group_overutilized; /* At least one CPU is overutilized in the group */ 11271 #ifdef CONFIG_NUMA_BALANCING 11272 unsigned int nr_numa_running; 11273 unsigned int nr_preferred_running; 11274 #endif 11275 #ifdef CONFIG_SCHED_CACHE 11276 unsigned int nr_pref_dst_llc; 11277 #endif 11278 }; 11279 11280 /* 11281 * sd_lb_stats - stats of a sched_domain required for load-balancing: 11282 */ 11283 struct sd_lb_stats { 11284 struct sched_group *busiest; /* Busiest group in this sd */ 11285 struct sched_group *local; /* Local group in this sd */ 11286 unsigned long total_load; /* Total load of all groups in sd */ 11287 unsigned long total_capacity; /* Total capacity of all groups in sd */ 11288 unsigned long avg_load; /* Average load across all groups in sd */ 11289 unsigned int prefer_sibling; /* Tasks should go to sibling first */ 11290 11291 struct sg_lb_stats busiest_stat; /* Statistics of the busiest group */ 11292 struct sg_lb_stats local_stat; /* Statistics of the local group */ 11293 }; 11294 11295 static inline void init_sd_lb_stats(struct sd_lb_stats *sds) 11296 { 11297 /* 11298 * Skimp on the clearing to avoid duplicate work. We can avoid clearing 11299 * local_stat because update_sg_lb_stats() does a full clear/assignment. 11300 * We must however set busiest_stat::group_type and 11301 * busiest_stat::idle_cpus to the worst busiest group because 11302 * update_sd_pick_busiest() reads these before assignment. 11303 */ 11304 *sds = (struct sd_lb_stats){ 11305 .busiest = NULL, 11306 .local = NULL, 11307 .total_load = 0UL, 11308 .total_capacity = 0UL, 11309 .busiest_stat = { 11310 .idle_cpus = UINT_MAX, 11311 .group_type = group_has_spare, 11312 }, 11313 }; 11314 } 11315 11316 static unsigned long scale_rt_capacity(int cpu) 11317 { 11318 unsigned long max = get_actual_cpu_capacity(cpu); 11319 struct rq *rq = cpu_rq(cpu); 11320 unsigned long used, free; 11321 unsigned long irq; 11322 11323 irq = cpu_util_irq(rq); 11324 11325 if (unlikely(irq >= max)) 11326 return 1; 11327 11328 /* 11329 * avg_rt.util_avg and avg_dl.util_avg track binary signals 11330 * (running and not running) with weights 0 and 1024 respectively. 11331 */ 11332 used = cpu_util_rt(rq); 11333 used += cpu_util_dl(rq); 11334 11335 if (unlikely(used >= max)) 11336 return 1; 11337 11338 free = max - used; 11339 11340 return scale_irq_capacity(free, irq, max); 11341 } 11342 11343 static void update_cpu_capacity(struct sched_domain *sd, int cpu) 11344 { 11345 unsigned long capacity = scale_rt_capacity(cpu); 11346 struct sched_group *sdg = sd->groups; 11347 11348 if (!capacity) 11349 capacity = 1; 11350 11351 cpu_rq(cpu)->cpu_capacity = capacity; 11352 trace_sched_cpu_capacity_tp(cpu_rq(cpu)); 11353 11354 sdg->sgc->capacity = capacity; 11355 sdg->sgc->min_capacity = capacity; 11356 sdg->sgc->max_capacity = capacity; 11357 } 11358 11359 void update_group_capacity(struct sched_domain *sd, int cpu) 11360 { 11361 struct sched_domain *child = sd->child; 11362 struct sched_group *group, *sdg = sd->groups; 11363 unsigned long capacity, min_capacity, max_capacity; 11364 unsigned long interval; 11365 11366 interval = msecs_to_jiffies(sd->balance_interval); 11367 interval = clamp(interval, 1UL, max_load_balance_interval); 11368 sdg->sgc->next_update = jiffies + interval; 11369 11370 if (!child) { 11371 update_cpu_capacity(sd, cpu); 11372 return; 11373 } 11374 11375 capacity = 0; 11376 min_capacity = ULONG_MAX; 11377 max_capacity = 0; 11378 11379 if (child->flags & SD_NUMA) { 11380 /* 11381 * SD_NUMA domains cannot assume that child groups 11382 * span the current group. 11383 */ 11384 11385 for_each_cpu(cpu, sched_group_span(sdg)) { 11386 unsigned long cpu_cap = capacity_of(cpu); 11387 11388 capacity += cpu_cap; 11389 min_capacity = min(cpu_cap, min_capacity); 11390 max_capacity = max(cpu_cap, max_capacity); 11391 } 11392 } else { 11393 /* 11394 * !SD_NUMA domains can assume that child groups 11395 * span the current group. 11396 */ 11397 11398 group = child->groups; 11399 do { 11400 struct sched_group_capacity *sgc = group->sgc; 11401 11402 capacity += sgc->capacity; 11403 min_capacity = min(sgc->min_capacity, min_capacity); 11404 max_capacity = max(sgc->max_capacity, max_capacity); 11405 group = group->next; 11406 } while (group != child->groups); 11407 } 11408 11409 sdg->sgc->capacity = capacity; 11410 sdg->sgc->min_capacity = min_capacity; 11411 sdg->sgc->max_capacity = max_capacity; 11412 } 11413 11414 /* 11415 * Check whether the capacity of the rq has been noticeably reduced by side 11416 * activity. The imbalance_pct is used for the threshold. 11417 * Return true is the capacity is reduced 11418 */ 11419 static inline int 11420 check_cpu_capacity(struct rq *rq, struct sched_domain *sd) 11421 { 11422 return ((rq->cpu_capacity * sd->imbalance_pct) < 11423 (arch_scale_cpu_capacity(cpu_of(rq)) * 100)); 11424 } 11425 11426 /* Check if the rq has a misfit task */ 11427 static inline bool check_misfit_status(struct rq *rq) 11428 { 11429 return rq->misfit_task_load; 11430 } 11431 11432 /* 11433 * Group imbalance indicates (and tries to solve) the problem where balancing 11434 * groups is inadequate due to ->cpus_ptr constraints. 11435 * 11436 * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a 11437 * cpumask covering 1 CPU of the first group and 3 CPUs of the second group. 11438 * Something like: 11439 * 11440 * { 0 1 2 3 } { 4 5 6 7 } 11441 * * * * * 11442 * 11443 * If we were to balance group-wise we'd place two tasks in the first group and 11444 * two tasks in the second group. Clearly this is undesired as it will overload 11445 * cpu 3 and leave one of the CPUs in the second group unused. 11446 * 11447 * The current solution to this issue is detecting the skew in the first group 11448 * by noticing the lower domain failed to reach balance and had difficulty 11449 * moving tasks due to affinity constraints. 11450 * 11451 * When this is so detected; this group becomes a candidate for busiest; see 11452 * update_sd_pick_busiest(). And calculate_imbalance() and 11453 * sched_balance_find_src_group() avoid some of the usual balance conditions to allow it 11454 * to create an effective group imbalance. 11455 * 11456 * This is a somewhat tricky proposition since the next run might not find the 11457 * group imbalance and decide the groups need to be balanced again. A most 11458 * subtle and fragile situation. 11459 */ 11460 11461 static inline int sg_imbalanced(struct sched_group *group) 11462 { 11463 return group->sgc->imbalance; 11464 } 11465 11466 /* 11467 * group_has_capacity returns true if the group has spare capacity that could 11468 * be used by some tasks. 11469 * We consider that a group has spare capacity if the number of task is 11470 * smaller than the number of CPUs or if the utilization is lower than the 11471 * available capacity for CFS tasks. 11472 * For the latter, we use a threshold to stabilize the state, to take into 11473 * account the variance of the tasks' load and to return true if the available 11474 * capacity in meaningful for the load balancer. 11475 * As an example, an available capacity of 1% can appear but it doesn't make 11476 * any benefit for the load balance. 11477 */ 11478 static inline bool 11479 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs) 11480 { 11481 if (sgs->sum_nr_running < sgs->group_weight) 11482 return true; 11483 11484 if ((sgs->group_capacity * imbalance_pct) < 11485 (sgs->group_runnable * 100)) 11486 return false; 11487 11488 if ((sgs->group_capacity * 100) > 11489 (sgs->group_util * imbalance_pct)) 11490 return true; 11491 11492 return false; 11493 } 11494 11495 /* 11496 * group_is_overloaded returns true if the group has more tasks than it can 11497 * handle. 11498 * group_is_overloaded is not equals to !group_has_capacity because a group 11499 * with the exact right number of tasks, has no more spare capacity but is not 11500 * overloaded so both group_has_capacity and group_is_overloaded return 11501 * false. 11502 */ 11503 static inline bool 11504 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs) 11505 { 11506 /* 11507 * With EAS and uclamp, 1 CPU in the group must be overutilized to 11508 * consider the group overloaded. 11509 */ 11510 if (sched_energy_enabled() && !sgs->group_overutilized) 11511 return false; 11512 11513 if (sgs->sum_nr_running <= sgs->group_weight) 11514 return false; 11515 11516 if ((sgs->group_capacity * 100) < 11517 (sgs->group_util * imbalance_pct)) 11518 return true; 11519 11520 if ((sgs->group_capacity * imbalance_pct) < 11521 (sgs->group_runnable * 100)) 11522 return true; 11523 11524 return false; 11525 } 11526 11527 static inline enum 11528 group_type group_classify(unsigned int imbalance_pct, 11529 struct sched_group *group, 11530 struct sg_lb_stats *sgs) 11531 { 11532 if (group_is_overloaded(imbalance_pct, sgs)) 11533 return group_overloaded; 11534 11535 if (sgs->group_llc_balance) 11536 return group_llc_balance; 11537 11538 if (sg_imbalanced(group)) 11539 return group_imbalanced; 11540 11541 if (sgs->group_asym_packing) 11542 return group_asym_packing; 11543 11544 if (sgs->group_smt_balance) 11545 return group_smt_balance; 11546 11547 if (sgs->group_misfit_task_load) 11548 return group_misfit_task; 11549 11550 if (!group_has_capacity(imbalance_pct, sgs)) 11551 return group_fully_busy; 11552 11553 return group_has_spare; 11554 } 11555 11556 /** 11557 * sched_use_asym_prio - Check whether asym_packing priority must be used 11558 * @sd: The scheduling domain of the load balancing 11559 * @cpu: A CPU 11560 * 11561 * Always use CPU priority when balancing load between SMT siblings. When 11562 * balancing load between cores, it is not sufficient that @cpu is idle. Only 11563 * use CPU priority if the whole core is idle. 11564 * 11565 * Returns: True if the priority of @cpu must be followed. False otherwise. 11566 */ 11567 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu) 11568 { 11569 if (!(sd->flags & SD_ASYM_PACKING)) 11570 return false; 11571 11572 if (!sched_smt_active()) 11573 return true; 11574 11575 return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu); 11576 } 11577 11578 static inline bool sched_asym(struct sched_domain *sd, int dst_cpu, int src_cpu) 11579 { 11580 /* 11581 * First check if @dst_cpu can do asym_packing load balance. Only do it 11582 * if it has higher priority than @src_cpu. 11583 */ 11584 return sched_use_asym_prio(sd, dst_cpu) && 11585 sched_asym_prefer(dst_cpu, src_cpu); 11586 } 11587 11588 /** 11589 * sched_group_asym - Check if the destination CPU can do asym_packing balance 11590 * @env: The load balancing environment 11591 * @sgs: Load-balancing statistics of the candidate busiest group 11592 * @group: The candidate busiest group 11593 * 11594 * @env::dst_cpu can do asym_packing if it has higher priority than the 11595 * preferred CPU of @group. 11596 * 11597 * Return: true if @env::dst_cpu can do with asym_packing load balance. False 11598 * otherwise. 11599 */ 11600 static inline bool 11601 sched_group_asym(struct lb_env *env, struct sg_lb_stats *sgs, struct sched_group *group) 11602 { 11603 /* 11604 * CPU priorities do not make sense for SMT cores with more than one 11605 * busy sibling. 11606 */ 11607 if ((group->flags & SD_SHARE_CPUCAPACITY) && 11608 (sgs->group_weight - sgs->idle_cpus != 1)) 11609 return false; 11610 11611 return sched_asym(env->sd, env->dst_cpu, READ_ONCE(group->asym_prefer_cpu)); 11612 } 11613 11614 /* One group has more than one SMT CPU while the other group does not */ 11615 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1, 11616 struct sched_group *sg2) 11617 { 11618 if (!sg1 || !sg2) 11619 return false; 11620 11621 return (sg1->flags & SD_SHARE_CPUCAPACITY) != 11622 (sg2->flags & SD_SHARE_CPUCAPACITY); 11623 } 11624 11625 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs, 11626 struct sched_group *group) 11627 { 11628 if (!env->idle) 11629 return false; 11630 11631 /* 11632 * For SMT source group, it is better to move a task 11633 * to a CPU that doesn't have multiple tasks sharing its CPU capacity. 11634 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY 11635 * will not be on. 11636 */ 11637 if (group->flags & SD_SHARE_CPUCAPACITY && 11638 sgs->sum_h_nr_running > 1) 11639 return true; 11640 11641 return false; 11642 } 11643 11644 static inline long sibling_imbalance(struct lb_env *env, 11645 struct sd_lb_stats *sds, 11646 struct sg_lb_stats *busiest, 11647 struct sg_lb_stats *local) 11648 { 11649 int ncores_busiest, ncores_local; 11650 long imbalance; 11651 11652 if (!env->idle || !busiest->sum_nr_running) 11653 return 0; 11654 11655 ncores_busiest = sds->busiest->cores; 11656 ncores_local = sds->local->cores; 11657 11658 if (ncores_busiest == ncores_local) { 11659 imbalance = busiest->sum_nr_running; 11660 lsub_positive(&imbalance, local->sum_nr_running); 11661 return imbalance; 11662 } 11663 11664 /* Balance such that nr_running/ncores ratio are same on both groups */ 11665 imbalance = ncores_local * busiest->sum_nr_running; 11666 lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running); 11667 /* Normalize imbalance and do rounding on normalization */ 11668 imbalance = 2 * imbalance + ncores_local + ncores_busiest; 11669 imbalance /= ncores_local + ncores_busiest; 11670 11671 /* Take advantage of resource in an empty sched group */ 11672 if (imbalance <= 1 && local->sum_nr_running == 0 && 11673 busiest->sum_nr_running > 1) 11674 imbalance = 2; 11675 11676 return imbalance; 11677 } 11678 11679 static inline bool 11680 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd) 11681 { 11682 /* 11683 * When there is more than 1 task, the group_overloaded case already 11684 * takes care of cpu with reduced capacity 11685 */ 11686 if (rq->cfs.h_nr_runnable != 1) 11687 return false; 11688 11689 return check_cpu_capacity(rq, sd); 11690 } 11691 11692 #ifdef CONFIG_SCHED_CACHE 11693 /* 11694 * Record the statistics for this scheduler group for later 11695 * use. These values guide load balancing on aggregating tasks 11696 * to a LLC. 11697 */ 11698 static void record_sg_llc_stats(struct lb_env *env, 11699 struct sg_lb_stats *sgs, 11700 struct sched_group *group) 11701 { 11702 struct sched_domain_shared *sd_share; 11703 int cpu; 11704 11705 if (!sched_cache_enabled() || env->idle == CPU_NEWLY_IDLE) 11706 return; 11707 11708 /* Only care about sched domain spanning multiple LLCs */ 11709 if (env->sd->child != rcu_dereference_all(per_cpu(sd_llc, env->dst_cpu))) 11710 return; 11711 11712 /* 11713 * At this point we know this group spans a LLC domain. 11714 * Record the statistic of this group in its corresponding 11715 * shared LLC domain. 11716 * Note: sd_share cannot be obtained via sd->child->shared, 11717 * because the latter refers to the domain that covers the 11718 * local group. Instead, sd_share should be located using 11719 * the first CPU of the LLC group. 11720 */ 11721 cpu = cpumask_first(sched_group_span(group)); 11722 sd_share = rcu_dereference_all(per_cpu(sd_llc_shared, cpu)); 11723 if (!sd_share) 11724 return; 11725 11726 if (READ_ONCE(sd_share->util_avg) != sgs->group_util) 11727 WRITE_ONCE(sd_share->util_avg, sgs->group_util); 11728 11729 if (unlikely(READ_ONCE(sd_share->capacity) != sgs->group_capacity)) 11730 WRITE_ONCE(sd_share->capacity, sgs->group_capacity); 11731 } 11732 11733 /* 11734 * Do LLC balance on sched group that contains LLC, and have tasks preferring 11735 * to run on LLC in idle dst_cpu. 11736 */ 11737 static inline bool llc_balance(struct lb_env *env, struct sg_lb_stats *sgs, 11738 struct sched_group *group) 11739 { 11740 if (!sched_cache_enabled()) 11741 return false; 11742 11743 if (env->sd->flags & SD_SHARE_LLC) 11744 return false; 11745 11746 /* 11747 * Skip cache aware tagging if nr_balanced_failed is sufficiently high. 11748 * Threshold of cache_nice_tries is set to 1 higher than nr_balance_failed 11749 * to avoid excessive task migration at the same time. 11750 */ 11751 if (env->sd->nr_balance_failed >= env->sd->cache_nice_tries + 1) 11752 return false; 11753 11754 if (sgs->nr_pref_dst_llc && 11755 can_migrate_llc(cpumask_first(sched_group_span(group)), 11756 env->dst_cpu, 0, true) == mig_llc) 11757 return true; 11758 11759 return false; 11760 } 11761 11762 static bool update_llc_busiest(struct lb_env *env, 11763 struct sg_lb_stats *busiest, 11764 struct sg_lb_stats *sgs) 11765 { 11766 /* 11767 * There are more tasks that want to run on dst_cpu's LLC. 11768 */ 11769 return sgs->nr_pref_dst_llc > busiest->nr_pref_dst_llc; 11770 } 11771 #else 11772 static inline void record_sg_llc_stats(struct lb_env *env, struct sg_lb_stats *sgs, 11773 struct sched_group *group) 11774 { 11775 } 11776 11777 static inline bool llc_balance(struct lb_env *env, struct sg_lb_stats *sgs, 11778 struct sched_group *group) 11779 { 11780 return false; 11781 } 11782 11783 static bool update_llc_busiest(struct lb_env *env, 11784 struct sg_lb_stats *busiest, 11785 struct sg_lb_stats *sgs) 11786 { 11787 return false; 11788 } 11789 #endif 11790 11791 /** 11792 * update_sg_lb_stats - Update sched_group's statistics for load balancing. 11793 * @env: The load balancing environment. 11794 * @sds: Load-balancing data with statistics of the local group. 11795 * @group: sched_group whose statistics are to be updated. 11796 * @sgs: variable to hold the statistics for this group. 11797 * @sg_overloaded: sched_group is overloaded 11798 */ 11799 static inline void update_sg_lb_stats(struct lb_env *env, 11800 struct sd_lb_stats *sds, 11801 struct sched_group *group, 11802 struct sg_lb_stats *sgs, 11803 bool *sg_overloaded) 11804 { 11805 int i, nr_running, local_group, sd_flags = env->sd->flags; 11806 bool balancing_at_rd = !env->sd->parent; 11807 11808 memset(sgs, 0, sizeof(*sgs)); 11809 11810 local_group = group == sds->local; 11811 11812 for_each_cpu_and(i, sched_group_span(group), env->cpus) { 11813 struct rq *rq = cpu_rq(i); 11814 unsigned long load = cpu_load(rq); 11815 11816 sgs->group_load += load; 11817 sgs->group_util += cpu_util_cfs(i); 11818 sgs->group_runnable += cpu_runnable(rq); 11819 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable; 11820 11821 nr_running = rq->nr_running; 11822 sgs->sum_nr_running += nr_running; 11823 11824 if (cpu_overutilized(i)) 11825 sgs->group_overutilized = 1; 11826 11827 #ifdef CONFIG_SCHED_CACHE 11828 if (sched_cache_enabled()) { 11829 struct sched_domain *sd_tmp; 11830 int dst_llc; 11831 11832 dst_llc = llc_id(env->dst_cpu); 11833 if (llc_id(i) != dst_llc) { 11834 sd_tmp = rcu_dereference_all(rq->sd); 11835 if (sd_tmp && (unsigned int)dst_llc < sd_tmp->llc_max) 11836 sgs->nr_pref_dst_llc += sd_tmp->llc_counts[dst_llc]; 11837 } 11838 } 11839 #endif 11840 11841 /* 11842 * No need to call idle_cpu() if nr_running is not 0 11843 */ 11844 if (!nr_running && idle_cpu(i)) { 11845 sgs->idle_cpus++; 11846 /* Idle cpu can't have misfit task */ 11847 continue; 11848 } 11849 11850 /* Overload indicator is only updated at root domain */ 11851 if (balancing_at_rd && nr_running > 1) 11852 *sg_overloaded = 1; 11853 11854 #ifdef CONFIG_NUMA_BALANCING 11855 /* Only fbq_classify_group() uses this to classify NUMA groups */ 11856 if (sd_flags & SD_NUMA) { 11857 sgs->nr_numa_running += rq->nr_numa_running; 11858 sgs->nr_preferred_running += rq->nr_preferred_running; 11859 } 11860 #endif 11861 if (local_group) 11862 continue; 11863 11864 if (sd_flags & SD_ASYM_CPUCAPACITY) { 11865 /* Check for a misfit task on the cpu */ 11866 if (sgs->group_misfit_task_load < rq->misfit_task_load) { 11867 sgs->group_misfit_task_load = rq->misfit_task_load; 11868 *sg_overloaded = 1; 11869 } 11870 } else if (env->idle && sched_reduced_capacity(rq, env->sd)) { 11871 /* Check for a task running on a CPU with reduced capacity */ 11872 if (sgs->group_misfit_task_load < load) 11873 sgs->group_misfit_task_load = load; 11874 } 11875 } 11876 11877 sgs->group_capacity = group->sgc->capacity; 11878 11879 sgs->group_weight = group->group_weight; 11880 11881 if (!local_group) { 11882 /* Check if dst CPU is idle and preferred to this group */ 11883 if (env->idle && sgs->sum_h_nr_running && 11884 sched_group_asym(env, sgs, group)) 11885 sgs->group_asym_packing = 1; 11886 11887 /* Check for loaded SMT group to be balanced to dst CPU */ 11888 if (smt_balance(env, sgs, group)) 11889 sgs->group_smt_balance = 1; 11890 11891 /* Check for tasks in this group can be moved to their preferred LLC */ 11892 if (llc_balance(env, sgs, group)) 11893 sgs->group_llc_balance = 1; 11894 } 11895 11896 sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs); 11897 11898 record_sg_llc_stats(env, sgs, group); 11899 /* Computing avg_load makes sense only when group is overloaded */ 11900 if (sgs->group_type == group_overloaded) 11901 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) / 11902 sgs->group_capacity; 11903 } 11904 11905 /** 11906 * update_sd_pick_busiest - return 1 on busiest group 11907 * @env: The load balancing environment. 11908 * @sds: sched_domain statistics 11909 * @sg: sched_group candidate to be checked for being the busiest 11910 * @sgs: sched_group statistics 11911 * 11912 * Determine if @sg is a busier group than the previously selected 11913 * busiest group. 11914 * 11915 * Return: %true if @sg is a busier group than the previously selected 11916 * busiest group. %false otherwise. 11917 */ 11918 static bool update_sd_pick_busiest(struct lb_env *env, 11919 struct sd_lb_stats *sds, 11920 struct sched_group *sg, 11921 struct sg_lb_stats *sgs) 11922 { 11923 struct sg_lb_stats *busiest = &sds->busiest_stat; 11924 11925 /* Make sure that there is at least one task to pull */ 11926 if (!sgs->sum_h_nr_running) 11927 return false; 11928 11929 /* 11930 * Don't try to pull misfit tasks we can't help. 11931 * We can use max_capacity here as reduction in capacity on some 11932 * CPUs in the group should either be possible to resolve 11933 * internally or be covered by avg_load imbalance (eventually). 11934 * 11935 * When SMT is active, only pull a misfit to dst_cpu if it is on a 11936 * fully idle core; otherwise the effective capacity of the core is 11937 * reduced and we may not actually provide more capacity than the 11938 * source. 11939 */ 11940 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) && 11941 (sgs->group_type == group_misfit_task) && 11942 (!env->dst_core_idle || 11943 !capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) || 11944 sds->local_stat.group_type != group_has_spare)) 11945 return false; 11946 11947 if (sgs->group_type > busiest->group_type) 11948 return true; 11949 11950 if (sgs->group_type < busiest->group_type) 11951 return false; 11952 11953 /* 11954 * The candidate and the current busiest group are the same type of 11955 * group. Let check which one is the busiest according to the type. 11956 */ 11957 11958 switch (sgs->group_type) { 11959 case group_overloaded: 11960 /* Select the overloaded group with highest avg_load. */ 11961 return sgs->avg_load > busiest->avg_load; 11962 11963 case group_llc_balance: 11964 /* Select the group with most tasks preferring dst LLC */ 11965 return update_llc_busiest(env, busiest, sgs); 11966 11967 case group_imbalanced: 11968 /* 11969 * Select the 1st imbalanced group as we don't have any way to 11970 * choose one more than another. 11971 */ 11972 return false; 11973 11974 case group_asym_packing: 11975 /* Prefer to move from lowest priority CPU's work */ 11976 return sched_asym_prefer(READ_ONCE(sds->busiest->asym_prefer_cpu), 11977 READ_ONCE(sg->asym_prefer_cpu)); 11978 11979 case group_misfit_task: 11980 /* 11981 * If we have more than one misfit sg go with the biggest 11982 * misfit. 11983 */ 11984 return sgs->group_misfit_task_load > busiest->group_misfit_task_load; 11985 11986 case group_smt_balance: 11987 /* 11988 * Check if we have spare CPUs on either SMT group to 11989 * choose has spare or fully busy handling. 11990 */ 11991 if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0) 11992 goto has_spare; 11993 11994 fallthrough; 11995 11996 case group_fully_busy: 11997 /* 11998 * Select the fully busy group with highest avg_load. In 11999 * theory, there is no need to pull task from such kind of 12000 * group because tasks have all compute capacity that they need 12001 * but we can still improve the overall throughput by reducing 12002 * contention when accessing shared HW resources. 12003 * 12004 * XXX for now avg_load is not computed and always 0 so we 12005 * select the 1st one, except if @sg is composed of SMT 12006 * siblings. 12007 */ 12008 12009 if (sgs->avg_load < busiest->avg_load) 12010 return false; 12011 12012 if (sgs->avg_load == busiest->avg_load) { 12013 /* 12014 * SMT sched groups need more help than non-SMT groups. 12015 * If @sg happens to also be SMT, either choice is good. 12016 */ 12017 if (sds->busiest->flags & SD_SHARE_CPUCAPACITY) 12018 return false; 12019 } 12020 12021 break; 12022 12023 case group_has_spare: 12024 /* 12025 * Do not pick sg with SMT CPUs over sg with pure CPUs, 12026 * as we do not want to pull task off SMT core with one task 12027 * and make the core idle. 12028 */ 12029 if (smt_vs_nonsmt_groups(sds->busiest, sg)) { 12030 if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1) 12031 return false; 12032 else 12033 return true; 12034 } 12035 has_spare: 12036 12037 /* 12038 * Select not overloaded group with lowest number of idle CPUs 12039 * and highest number of running tasks. We could also compare 12040 * the spare capacity which is more stable but it can end up 12041 * that the group has less spare capacity but finally more idle 12042 * CPUs which means less opportunity to pull tasks. 12043 */ 12044 if (sgs->idle_cpus > busiest->idle_cpus) 12045 return false; 12046 else if ((sgs->idle_cpus == busiest->idle_cpus) && 12047 (sgs->sum_nr_running <= busiest->sum_nr_running)) 12048 return false; 12049 12050 break; 12051 } 12052 12053 /* 12054 * Candidate sg has no more than one task per CPU and has higher 12055 * per-CPU capacity. Migrating tasks to less capable CPUs may harm 12056 * throughput. Maximize throughput, power/energy consequences are not 12057 * considered. 12058 */ 12059 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) && 12060 (sgs->group_type <= group_fully_busy) && 12061 (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu)))) 12062 return false; 12063 12064 return true; 12065 } 12066 12067 #ifdef CONFIG_NUMA_BALANCING 12068 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs) 12069 { 12070 if (sgs->sum_h_nr_running > sgs->nr_numa_running) 12071 return regular; 12072 if (sgs->sum_h_nr_running > sgs->nr_preferred_running) 12073 return remote; 12074 return all; 12075 } 12076 12077 static inline enum fbq_type fbq_classify_rq(struct rq *rq) 12078 { 12079 if (rq->nr_running > rq->nr_numa_running) 12080 return regular; 12081 if (rq->nr_running > rq->nr_preferred_running) 12082 return remote; 12083 return all; 12084 } 12085 #else /* !CONFIG_NUMA_BALANCING: */ 12086 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs) 12087 { 12088 return all; 12089 } 12090 12091 static inline enum fbq_type fbq_classify_rq(struct rq *rq) 12092 { 12093 return regular; 12094 } 12095 #endif /* !CONFIG_NUMA_BALANCING */ 12096 12097 12098 struct sg_lb_stats; 12099 12100 /* 12101 * task_running_on_cpu - return 1 if @p is running on @cpu. 12102 */ 12103 12104 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p) 12105 { 12106 /* Task has no contribution or is new */ 12107 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 12108 return 0; 12109 12110 if (task_on_rq_queued(p)) 12111 return 1; 12112 12113 return 0; 12114 } 12115 12116 /** 12117 * idle_cpu_without - would a given CPU be idle without p ? 12118 * @cpu: the processor on which idleness is tested. 12119 * @p: task which should be ignored. 12120 * 12121 * Return: 1 if the CPU would be idle. 0 otherwise. 12122 */ 12123 static int idle_cpu_without(int cpu, struct task_struct *p) 12124 { 12125 struct rq *rq = cpu_rq(cpu); 12126 12127 if (rq->curr != rq->idle && rq->curr != p) 12128 return 0; 12129 12130 /* 12131 * rq->nr_running can't be used but an updated version without the 12132 * impact of p on cpu must be used instead. The updated nr_running 12133 * be computed and tested before calling idle_cpu_without(). 12134 */ 12135 12136 if (rq->ttwu_pending) 12137 return 0; 12138 12139 return 1; 12140 } 12141 12142 /* 12143 * update_sg_wakeup_stats - Update sched_group's statistics for wakeup. 12144 * @sd: The sched_domain level to look for idlest group. 12145 * @group: sched_group whose statistics are to be updated. 12146 * @sgs: variable to hold the statistics for this group. 12147 * @p: The task for which we look for the idlest group/CPU. 12148 */ 12149 static inline void update_sg_wakeup_stats(struct sched_domain *sd, 12150 struct sched_group *group, 12151 struct sg_lb_stats *sgs, 12152 struct task_struct *p) 12153 { 12154 int i, nr_running; 12155 12156 memset(sgs, 0, sizeof(*sgs)); 12157 12158 /* Assume that task can't fit any CPU of the group */ 12159 if (sd->flags & SD_ASYM_CPUCAPACITY) 12160 sgs->group_misfit_task_load = 1; 12161 12162 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) { 12163 struct rq *rq = cpu_rq(i); 12164 unsigned int local; 12165 12166 sgs->group_load += cpu_load_without(rq, p); 12167 sgs->group_util += cpu_util_without(i, p); 12168 sgs->group_runnable += cpu_runnable_without(rq, p); 12169 local = task_running_on_cpu(i, p); 12170 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable - local; 12171 12172 nr_running = rq->nr_running - local; 12173 sgs->sum_nr_running += nr_running; 12174 12175 /* 12176 * No need to call idle_cpu_without() if nr_running is not 0 12177 */ 12178 if (!nr_running && idle_cpu_without(i, p)) 12179 sgs->idle_cpus++; 12180 12181 /* Check if task fits in the CPU */ 12182 if (sd->flags & SD_ASYM_CPUCAPACITY && 12183 sgs->group_misfit_task_load && 12184 task_fits_cpu(p, i)) 12185 sgs->group_misfit_task_load = 0; 12186 12187 } 12188 12189 sgs->group_capacity = group->sgc->capacity; 12190 12191 sgs->group_weight = group->group_weight; 12192 12193 sgs->group_type = group_classify(sd->imbalance_pct, group, sgs); 12194 12195 /* 12196 * Computing avg_load makes sense only when group is fully busy or 12197 * overloaded 12198 */ 12199 if (sgs->group_type == group_fully_busy || 12200 sgs->group_type == group_overloaded) 12201 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) / 12202 sgs->group_capacity; 12203 } 12204 12205 static bool update_pick_idlest(struct sched_group *idlest, 12206 struct sg_lb_stats *idlest_sgs, 12207 struct sched_group *group, 12208 struct sg_lb_stats *sgs) 12209 { 12210 if (sgs->group_type < idlest_sgs->group_type) 12211 return true; 12212 12213 if (sgs->group_type > idlest_sgs->group_type) 12214 return false; 12215 12216 /* 12217 * The candidate and the current idlest group are the same type of 12218 * group. Let check which one is the idlest according to the type. 12219 */ 12220 12221 switch (sgs->group_type) { 12222 case group_overloaded: 12223 case group_fully_busy: 12224 /* Select the group with lowest avg_load. */ 12225 if (idlest_sgs->avg_load <= sgs->avg_load) 12226 return false; 12227 break; 12228 12229 case group_llc_balance: 12230 case group_imbalanced: 12231 case group_asym_packing: 12232 case group_smt_balance: 12233 /* Those types are not used in the slow wakeup path */ 12234 return false; 12235 12236 case group_misfit_task: 12237 /* Select group with the highest max capacity */ 12238 if (idlest->sgc->max_capacity >= group->sgc->max_capacity) 12239 return false; 12240 break; 12241 12242 case group_has_spare: 12243 /* Select group with most idle CPUs */ 12244 if (idlest_sgs->idle_cpus > sgs->idle_cpus) 12245 return false; 12246 12247 /* Select group with lowest group_util */ 12248 if (idlest_sgs->idle_cpus == sgs->idle_cpus && 12249 idlest_sgs->group_util <= sgs->group_util) 12250 return false; 12251 12252 break; 12253 } 12254 12255 return true; 12256 } 12257 12258 /* 12259 * sched_balance_find_dst_group() finds and returns the least busy CPU group within the 12260 * domain. 12261 * 12262 * Assumes p is allowed on at least one CPU in sd. 12263 */ 12264 static struct sched_group * 12265 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu) 12266 { 12267 struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups; 12268 struct sg_lb_stats local_sgs, tmp_sgs; 12269 struct sg_lb_stats *sgs; 12270 unsigned long imbalance; 12271 struct sg_lb_stats idlest_sgs = { 12272 .avg_load = UINT_MAX, 12273 .group_type = group_overloaded, 12274 }; 12275 12276 do { 12277 int local_group; 12278 12279 /* Skip over this group if it has no CPUs allowed */ 12280 if (!cpumask_intersects(sched_group_span(group), 12281 p->cpus_ptr)) 12282 continue; 12283 12284 /* Skip over this group if no cookie matched */ 12285 if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group)) 12286 continue; 12287 12288 local_group = cpumask_test_cpu(this_cpu, 12289 sched_group_span(group)); 12290 12291 if (local_group) { 12292 sgs = &local_sgs; 12293 local = group; 12294 } else { 12295 sgs = &tmp_sgs; 12296 } 12297 12298 update_sg_wakeup_stats(sd, group, sgs, p); 12299 12300 if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) { 12301 idlest = group; 12302 idlest_sgs = *sgs; 12303 } 12304 12305 } while (group = group->next, group != sd->groups); 12306 12307 12308 /* There is no idlest group to push tasks to */ 12309 if (!idlest) 12310 return NULL; 12311 12312 /* The local group has been skipped because of CPU affinity */ 12313 if (!local) 12314 return idlest; 12315 12316 /* 12317 * If the local group is idler than the selected idlest group 12318 * don't try and push the task. 12319 */ 12320 if (local_sgs.group_type < idlest_sgs.group_type) 12321 return NULL; 12322 12323 /* 12324 * If the local group is busier than the selected idlest group 12325 * try and push the task. 12326 */ 12327 if (local_sgs.group_type > idlest_sgs.group_type) 12328 return idlest; 12329 12330 switch (local_sgs.group_type) { 12331 case group_overloaded: 12332 case group_fully_busy: 12333 12334 /* Calculate allowed imbalance based on load */ 12335 imbalance = scale_load_down(NICE_0_LOAD) * 12336 (sd->imbalance_pct-100) / 100; 12337 12338 /* 12339 * When comparing groups across NUMA domains, it's possible for 12340 * the local domain to be very lightly loaded relative to the 12341 * remote domains but "imbalance" skews the comparison making 12342 * remote CPUs look much more favourable. When considering 12343 * cross-domain, add imbalance to the load on the remote node 12344 * and consider staying local. 12345 */ 12346 12347 if ((sd->flags & SD_NUMA) && 12348 ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load)) 12349 return NULL; 12350 12351 /* 12352 * If the local group is less loaded than the selected 12353 * idlest group don't try and push any tasks. 12354 */ 12355 if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance)) 12356 return NULL; 12357 12358 if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load) 12359 return NULL; 12360 break; 12361 12362 case group_llc_balance: 12363 case group_imbalanced: 12364 case group_asym_packing: 12365 case group_smt_balance: 12366 /* Those type are not used in the slow wakeup path */ 12367 return NULL; 12368 12369 case group_misfit_task: 12370 /* Select group with the highest max capacity */ 12371 if (local->sgc->max_capacity >= idlest->sgc->max_capacity) 12372 return NULL; 12373 break; 12374 12375 case group_has_spare: 12376 #ifdef CONFIG_NUMA 12377 if (sd->flags & SD_NUMA) { 12378 int imb_numa_nr = sd->imb_numa_nr; 12379 #ifdef CONFIG_NUMA_BALANCING 12380 int idlest_cpu; 12381 /* 12382 * If there is spare capacity at NUMA, try to select 12383 * the preferred node 12384 */ 12385 if (cpu_to_node(this_cpu) == p->numa_preferred_nid) 12386 return NULL; 12387 12388 idlest_cpu = cpumask_first(sched_group_span(idlest)); 12389 if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid) 12390 return idlest; 12391 #endif /* CONFIG_NUMA_BALANCING */ 12392 /* 12393 * Otherwise, keep the task close to the wakeup source 12394 * and improve locality if the number of running tasks 12395 * would remain below threshold where an imbalance is 12396 * allowed while accounting for the possibility the 12397 * task is pinned to a subset of CPUs. If there is a 12398 * real need of migration, periodic load balance will 12399 * take care of it. 12400 */ 12401 if (p->nr_cpus_allowed != NR_CPUS) { 12402 unsigned int w = cpumask_weight_and(p->cpus_ptr, 12403 sched_group_span(local)); 12404 imb_numa_nr = min(w, sd->imb_numa_nr); 12405 } 12406 12407 imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus); 12408 if (!adjust_numa_imbalance(imbalance, 12409 local_sgs.sum_nr_running + 1, 12410 imb_numa_nr)) { 12411 return NULL; 12412 } 12413 } 12414 #endif /* CONFIG_NUMA */ 12415 12416 /* 12417 * Select group with highest number of idle CPUs. We could also 12418 * compare the utilization which is more stable but it can end 12419 * up that the group has less spare capacity but finally more 12420 * idle CPUs which means more opportunity to run task. 12421 */ 12422 if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus) 12423 return NULL; 12424 break; 12425 } 12426 12427 return idlest; 12428 } 12429 12430 static void update_idle_cpu_scan(struct lb_env *env, 12431 unsigned long sum_util) 12432 { 12433 struct sched_domain_shared *sd_share; 12434 struct sched_domain *sd = env->sd; 12435 int llc_weight, pct; 12436 u64 x, y, tmp; 12437 /* 12438 * Update the number of CPUs to scan in LLC domain, which could 12439 * be used as a hint in select_idle_cpu(). The update of sd_share 12440 * could be expensive because it is within a shared cache line. 12441 * So the write of this hint only occurs during periodic load 12442 * balancing, rather than CPU_NEWLY_IDLE, because the latter 12443 * can fire way more frequently than the former. 12444 */ 12445 if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE) 12446 return; 12447 12448 sd_share = sd->shared; 12449 if (!sd_share) 12450 return; 12451 12452 /* 12453 * The number of CPUs to search drops as sum_util increases, when 12454 * sum_util hits 85% or above, the scan stops. 12455 * The reason to choose 85% as the threshold is because this is the 12456 * imbalance_pct(117) when a LLC sched group is overloaded. 12457 * 12458 * let y = SCHED_CAPACITY_SCALE - p * x^2 [1] 12459 * and y'= y / SCHED_CAPACITY_SCALE 12460 * 12461 * x is the ratio of sum_util compared to the CPU capacity: 12462 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE) 12463 * y' is the ratio of CPUs to be scanned in the LLC domain, 12464 * and the number of CPUs to scan is calculated by: 12465 * 12466 * nr_scan = llc_weight * y' [2] 12467 * 12468 * When x hits the threshold of overloaded, AKA, when 12469 * x = 100 / pct, y drops to 0. According to [1], 12470 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000 12471 * 12472 * Scale x by SCHED_CAPACITY_SCALE: 12473 * x' = sum_util / llc_weight; [3] 12474 * 12475 * and finally [1] becomes: 12476 * y = SCHED_CAPACITY_SCALE - 12477 * x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE) [4] 12478 * 12479 */ 12480 /* equation [3] */ 12481 x = sum_util; 12482 llc_weight = sd->span_weight; 12483 do_div(x, llc_weight); 12484 12485 /* equation [4] */ 12486 pct = sd->imbalance_pct; 12487 tmp = x * x * pct * pct; 12488 do_div(tmp, 10000 * SCHED_CAPACITY_SCALE); 12489 tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE); 12490 y = SCHED_CAPACITY_SCALE - tmp; 12491 12492 /* equation [2] */ 12493 y *= llc_weight; 12494 do_div(y, SCHED_CAPACITY_SCALE); 12495 if ((int)y != sd_share->nr_idle_scan) 12496 WRITE_ONCE(sd_share->nr_idle_scan, (int)y); 12497 } 12498 12499 /** 12500 * update_sd_lb_stats - Update sched_domain's statistics for load balancing. 12501 * @env: The load balancing environment. 12502 * @sds: variable to hold the statistics for this sched_domain. 12503 */ 12504 12505 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds) 12506 { 12507 struct sched_group *sg = env->sd->groups; 12508 struct sg_lb_stats *local = &sds->local_stat; 12509 struct sg_lb_stats tmp_sgs; 12510 unsigned long sum_util = 0; 12511 bool sg_overloaded = 0, sg_overutilized = 0; 12512 12513 env->dst_core_idle = !sched_smt_active() || is_core_idle(env->dst_cpu); 12514 12515 do { 12516 struct sg_lb_stats *sgs = &tmp_sgs; 12517 int local_group; 12518 12519 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg)); 12520 if (local_group) { 12521 sds->local = sg; 12522 sgs = local; 12523 12524 if (env->idle != CPU_NEWLY_IDLE || 12525 time_after_eq(jiffies, sg->sgc->next_update)) 12526 update_group_capacity(env->sd, env->dst_cpu); 12527 } 12528 12529 update_sg_lb_stats(env, sds, sg, sgs, &sg_overloaded); 12530 12531 if (!local_group && update_sd_pick_busiest(env, sds, sg, sgs)) { 12532 sds->busiest = sg; 12533 sds->busiest_stat = *sgs; 12534 } 12535 12536 sg_overutilized |= sgs->group_overutilized; 12537 12538 /* Now, start updating sd_lb_stats */ 12539 sds->total_load += sgs->group_load; 12540 sds->total_capacity += sgs->group_capacity; 12541 12542 sum_util += sgs->group_util; 12543 sg = sg->next; 12544 } while (sg != env->sd->groups); 12545 12546 /* 12547 * Indicate that the child domain of the busiest group prefers tasks 12548 * go to a child's sibling domains first. NB the flags of a sched group 12549 * are those of the child domain. 12550 */ 12551 if (sds->busiest) 12552 sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING); 12553 12554 12555 if (env->sd->flags & SD_NUMA) 12556 env->fbq_type = fbq_classify_group(&sds->busiest_stat); 12557 12558 if (!env->sd->parent) { 12559 /* update overload indicator if we are at root domain */ 12560 set_rd_overloaded(env->dst_rq->rd, sg_overloaded); 12561 12562 /* Update over-utilization (tipping point, U >= 0) indicator */ 12563 set_rd_overutilized(env->dst_rq->rd, sg_overutilized); 12564 } else if (sg_overutilized) { 12565 set_rd_overutilized(env->dst_rq->rd, sg_overutilized); 12566 } 12567 12568 update_idle_cpu_scan(env, sum_util); 12569 } 12570 12571 /** 12572 * calculate_imbalance - Calculate the amount of imbalance present within the 12573 * groups of a given sched_domain during load balance. 12574 * @env: load balance environment 12575 * @sds: statistics of the sched_domain whose imbalance is to be calculated. 12576 */ 12577 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds) 12578 { 12579 struct sg_lb_stats *local, *busiest; 12580 12581 local = &sds->local_stat; 12582 busiest = &sds->busiest_stat; 12583 12584 if (busiest->group_type == group_misfit_task) { 12585 if (env->sd->flags & SD_ASYM_CPUCAPACITY) { 12586 /* Set imbalance to allow misfit tasks to be balanced. */ 12587 env->migration_type = migrate_misfit; 12588 env->imbalance = 1; 12589 } else { 12590 /* 12591 * Set load imbalance to allow moving task from cpu 12592 * with reduced capacity. 12593 */ 12594 env->migration_type = migrate_load; 12595 env->imbalance = busiest->group_misfit_task_load; 12596 } 12597 return; 12598 } 12599 12600 if (busiest->group_type == group_asym_packing) { 12601 /* 12602 * In case of asym capacity, we will try to migrate all load to 12603 * the preferred CPU. 12604 */ 12605 env->migration_type = migrate_task; 12606 env->imbalance = busiest->sum_h_nr_running; 12607 return; 12608 } 12609 12610 if (busiest->group_type == group_smt_balance) { 12611 /* Reduce number of tasks sharing CPU capacity */ 12612 env->migration_type = migrate_task; 12613 env->imbalance = 1; 12614 return; 12615 } 12616 12617 #ifdef CONFIG_SCHED_CACHE 12618 if (busiest->group_type == group_llc_balance) { 12619 /* Move a task that prefer local LLC */ 12620 env->migration_type = migrate_llc_task; 12621 env->imbalance = 1; 12622 return; 12623 } 12624 #endif 12625 12626 if (busiest->group_type == group_imbalanced) { 12627 /* 12628 * In the group_imb case we cannot rely on group-wide averages 12629 * to ensure CPU-load equilibrium, try to move any task to fix 12630 * the imbalance. The next load balance will take care of 12631 * balancing back the system. 12632 */ 12633 env->migration_type = migrate_task; 12634 env->imbalance = 1; 12635 return; 12636 } 12637 12638 /* 12639 * Try to use spare capacity of local group without overloading it or 12640 * emptying busiest. 12641 */ 12642 if (local->group_type == group_has_spare) { 12643 if ((busiest->group_type > group_fully_busy) && 12644 !(env->sd->flags & SD_SHARE_LLC)) { 12645 /* 12646 * If busiest is overloaded, try to fill spare 12647 * capacity. This might end up creating spare capacity 12648 * in busiest or busiest still being overloaded but 12649 * there is no simple way to directly compute the 12650 * amount of load to migrate in order to balance the 12651 * system. 12652 */ 12653 env->migration_type = migrate_util; 12654 env->imbalance = max(local->group_capacity, local->group_util) - 12655 local->group_util; 12656 12657 /* 12658 * In some cases, the group's utilization is max or even 12659 * higher than capacity because of migrations but the 12660 * local CPU is (newly) idle. There is at least one 12661 * waiting task in this overloaded busiest group. Let's 12662 * try to pull it. 12663 */ 12664 if (env->idle && env->imbalance == 0) { 12665 env->migration_type = migrate_task; 12666 env->imbalance = 1; 12667 } 12668 12669 return; 12670 } 12671 12672 if (busiest->group_weight == 1 || sds->prefer_sibling) { 12673 /* 12674 * When prefer sibling, evenly spread running tasks on 12675 * groups. 12676 */ 12677 env->migration_type = migrate_task; 12678 env->imbalance = sibling_imbalance(env, sds, busiest, local); 12679 } else { 12680 12681 /* 12682 * If there is no overload, we just want to even the number of 12683 * idle CPUs. 12684 */ 12685 env->migration_type = migrate_task; 12686 env->imbalance = max_t(long, 0, 12687 (local->idle_cpus - busiest->idle_cpus)); 12688 } 12689 12690 #ifdef CONFIG_NUMA 12691 /* Consider allowing a small imbalance between NUMA groups */ 12692 if (env->sd->flags & SD_NUMA) { 12693 env->imbalance = adjust_numa_imbalance(env->imbalance, 12694 local->sum_nr_running + 1, 12695 env->sd->imb_numa_nr); 12696 } 12697 #endif 12698 12699 /* Number of tasks to move to restore balance */ 12700 env->imbalance >>= 1; 12701 12702 return; 12703 } 12704 12705 /* 12706 * Local is fully busy but has to take more load to relieve the 12707 * busiest group 12708 */ 12709 if (local->group_type < group_overloaded) { 12710 /* 12711 * Local will become overloaded so the avg_load metrics are 12712 * finally needed. 12713 */ 12714 12715 local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) / 12716 local->group_capacity; 12717 12718 /* 12719 * If the local group is more loaded than the selected 12720 * busiest group don't try to pull any tasks. 12721 */ 12722 if (local->avg_load >= busiest->avg_load) { 12723 env->imbalance = 0; 12724 return; 12725 } 12726 12727 sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) / 12728 sds->total_capacity; 12729 12730 /* 12731 * If the local group is more loaded than the average system 12732 * load, don't try to pull any tasks. 12733 */ 12734 if (local->avg_load >= sds->avg_load) { 12735 env->imbalance = 0; 12736 return; 12737 } 12738 12739 } 12740 12741 /* 12742 * Both group are or will become overloaded and we're trying to get all 12743 * the CPUs to the average_load, so we don't want to push ourselves 12744 * above the average load, nor do we wish to reduce the max loaded CPU 12745 * below the average load. At the same time, we also don't want to 12746 * reduce the group load below the group capacity. Thus we look for 12747 * the minimum possible imbalance. 12748 */ 12749 env->migration_type = migrate_load; 12750 env->imbalance = min( 12751 (busiest->avg_load - sds->avg_load) * busiest->group_capacity, 12752 (sds->avg_load - local->avg_load) * local->group_capacity 12753 ) / SCHED_CAPACITY_SCALE; 12754 } 12755 12756 /******* sched_balance_find_src_group() helpers end here *********************/ 12757 12758 /* 12759 * Decision matrix according to the local and busiest group type: 12760 * 12761 * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded 12762 * has_spare nr_idle balanced N/A N/A balanced balanced 12763 * fully_busy nr_idle nr_idle N/A N/A balanced balanced 12764 * misfit_task force N/A N/A N/A N/A N/A 12765 * asym_packing force force N/A N/A force force 12766 * imbalanced force force N/A N/A force force 12767 * overloaded force force N/A N/A force avg_load 12768 * 12769 * N/A : Not Applicable because already filtered while updating 12770 * statistics. 12771 * balanced : The system is balanced for these 2 groups. 12772 * force : Calculate the imbalance as load migration is probably needed. 12773 * avg_load : Only if imbalance is significant enough. 12774 * nr_idle : dst_cpu is not busy and the number of idle CPUs is quite 12775 * different in groups. 12776 */ 12777 12778 /** 12779 * sched_balance_find_src_group - Returns the busiest group within the sched_domain 12780 * if there is an imbalance. 12781 * @env: The load balancing environment. 12782 * 12783 * Also calculates the amount of runnable load which should be moved 12784 * to restore balance. 12785 * 12786 * Return: - The busiest group if imbalance exists. 12787 */ 12788 static struct sched_group *sched_balance_find_src_group(struct lb_env *env) 12789 { 12790 struct sg_lb_stats *local, *busiest; 12791 struct sd_lb_stats sds; 12792 12793 init_sd_lb_stats(&sds); 12794 12795 /* 12796 * Compute the various statistics relevant for load balancing at 12797 * this level. 12798 */ 12799 update_sd_lb_stats(env, &sds); 12800 12801 /* There is no busy sibling group to pull tasks from */ 12802 if (!sds.busiest) 12803 goto out_balanced; 12804 12805 busiest = &sds.busiest_stat; 12806 12807 /* Misfit tasks should be dealt with regardless of the avg load */ 12808 if (busiest->group_type == group_misfit_task) 12809 goto force_balance; 12810 12811 if (!is_rd_overutilized(env->dst_rq->rd) && 12812 rcu_dereference_all(env->dst_rq->rd->pd)) 12813 goto out_balanced; 12814 12815 /* ASYM feature bypasses nice load balance check */ 12816 if (busiest->group_type == group_asym_packing) 12817 goto force_balance; 12818 12819 /* 12820 * If the busiest group is imbalanced the below checks don't 12821 * work because they assume all things are equal, which typically 12822 * isn't true due to cpus_ptr constraints and the like. 12823 */ 12824 if (busiest->group_type == group_imbalanced) 12825 goto force_balance; 12826 12827 local = &sds.local_stat; 12828 /* 12829 * If the local group is busier than the selected busiest group 12830 * don't try and pull any tasks. 12831 */ 12832 if (local->group_type > busiest->group_type) 12833 goto out_balanced; 12834 12835 /* 12836 * When groups are overloaded, use the avg_load to ensure fairness 12837 * between tasks. 12838 */ 12839 if (local->group_type == group_overloaded) { 12840 /* 12841 * If the local group is more loaded than the selected 12842 * busiest group don't try to pull any tasks. 12843 */ 12844 if (local->avg_load >= busiest->avg_load) 12845 goto out_balanced; 12846 12847 /* XXX broken for overlapping NUMA groups */ 12848 sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) / 12849 sds.total_capacity; 12850 12851 /* 12852 * Don't pull any tasks if this group is already above the 12853 * domain average load. 12854 */ 12855 if (local->avg_load >= sds.avg_load) 12856 goto out_balanced; 12857 12858 /* 12859 * If the busiest group is more loaded, use imbalance_pct to be 12860 * conservative. 12861 */ 12862 if (100 * busiest->avg_load <= 12863 env->sd->imbalance_pct * local->avg_load) 12864 goto out_balanced; 12865 } 12866 12867 /* 12868 * Try to move all excess tasks to a sibling domain of the busiest 12869 * group's child domain. 12870 */ 12871 if (sds.prefer_sibling && local->group_type == group_has_spare && 12872 (busiest->group_type == group_llc_balance || 12873 sibling_imbalance(env, &sds, busiest, local) > 1)) 12874 goto force_balance; 12875 12876 if (busiest->group_type != group_overloaded) { 12877 if (!env->idle) { 12878 /* 12879 * If the busiest group is not overloaded (and as a 12880 * result the local one too) but this CPU is already 12881 * busy, let another idle CPU try to pull task. 12882 */ 12883 goto out_balanced; 12884 } 12885 12886 if (busiest->group_type == group_smt_balance && 12887 smt_vs_nonsmt_groups(sds.local, sds.busiest)) { 12888 /* Let non SMT CPU pull from SMT CPU sharing with sibling */ 12889 goto force_balance; 12890 } 12891 12892 if (busiest->group_weight > 1 && 12893 local->idle_cpus <= (busiest->idle_cpus + 1)) { 12894 /* 12895 * If the busiest group is not overloaded 12896 * and there is no imbalance between this and busiest 12897 * group wrt idle CPUs, it is balanced. The imbalance 12898 * becomes significant if the diff is greater than 1 12899 * otherwise we might end up to just move the imbalance 12900 * on another group. Of course this applies only if 12901 * there is more than 1 CPU per group. 12902 */ 12903 goto out_balanced; 12904 } 12905 12906 if (busiest->sum_h_nr_running == 1) { 12907 /* 12908 * busiest doesn't have any tasks waiting to run 12909 */ 12910 goto out_balanced; 12911 } 12912 } 12913 12914 force_balance: 12915 /* Looks like there is an imbalance. Compute it */ 12916 calculate_imbalance(env, &sds); 12917 return env->imbalance ? sds.busiest : NULL; 12918 12919 out_balanced: 12920 env->imbalance = 0; 12921 return NULL; 12922 } 12923 12924 /* 12925 * sched_balance_find_src_rq - find the busiest runqueue among the CPUs in the group. 12926 */ 12927 static struct rq *sched_balance_find_src_rq(struct lb_env *env, 12928 struct sched_group *group) 12929 { 12930 struct rq *busiest = NULL, *rq; 12931 unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1; 12932 unsigned int __maybe_unused busiest_pref_llc = 0; 12933 struct sched_domain __maybe_unused *sd_tmp; 12934 unsigned int busiest_nr = 0; 12935 int __maybe_unused dst_llc; 12936 int i; 12937 12938 for_each_cpu_and(i, sched_group_span(group), env->cpus) { 12939 unsigned long capacity, load, util; 12940 unsigned int nr_running; 12941 enum fbq_type rt; 12942 12943 rq = cpu_rq(i); 12944 rt = fbq_classify_rq(rq); 12945 12946 /* 12947 * We classify groups/runqueues into three groups: 12948 * - regular: there are !numa tasks 12949 * - remote: there are numa tasks that run on the 'wrong' node 12950 * - all: there is no distinction 12951 * 12952 * In order to avoid migrating ideally placed numa tasks, 12953 * ignore those when there's better options. 12954 * 12955 * If we ignore the actual busiest queue to migrate another 12956 * task, the next balance pass can still reduce the busiest 12957 * queue by moving tasks around inside the node. 12958 * 12959 * If we cannot move enough load due to this classification 12960 * the next pass will adjust the group classification and 12961 * allow migration of more tasks. 12962 * 12963 * Both cases only affect the total convergence complexity. 12964 */ 12965 if (rt > env->fbq_type) 12966 continue; 12967 12968 nr_running = rq->cfs.h_nr_runnable; 12969 if (!nr_running) 12970 continue; 12971 12972 capacity = capacity_of(i); 12973 12974 /* 12975 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could 12976 * eventually lead to active_balancing high->low capacity. 12977 * Higher per-CPU capacity is considered better than balancing 12978 * average load. 12979 */ 12980 if (env->sd->flags & SD_ASYM_CPUCAPACITY && 12981 !capacity_greater(capacity_of(env->dst_cpu), capacity) && 12982 nr_running == 1) 12983 continue; 12984 12985 /* 12986 * Make sure we only pull tasks from a CPU of lower priority 12987 * when balancing between SMT siblings. 12988 * 12989 * If balancing between cores, let lower priority CPUs help 12990 * SMT cores with more than one busy sibling. 12991 */ 12992 if (sched_asym(env->sd, i, env->dst_cpu) && nr_running == 1) 12993 continue; 12994 12995 switch (env->migration_type) { 12996 case migrate_load: 12997 /* 12998 * When comparing with load imbalance, use cpu_load() 12999 * which is not scaled with the CPU capacity. 13000 */ 13001 load = cpu_load(rq); 13002 13003 if (nr_running == 1 && load > env->imbalance && 13004 !check_cpu_capacity(rq, env->sd)) 13005 break; 13006 13007 /* 13008 * For the load comparisons with the other CPUs, 13009 * consider the cpu_load() scaled with the CPU 13010 * capacity, so that the load can be moved away 13011 * from the CPU that is potentially running at a 13012 * lower capacity. 13013 * 13014 * Thus we're looking for max(load_i / capacity_i), 13015 * crosswise multiplication to rid ourselves of the 13016 * division works out to: 13017 * load_i * capacity_j > load_j * capacity_i; 13018 * where j is our previous maximum. 13019 */ 13020 if (load * busiest_capacity > busiest_load * capacity) { 13021 busiest_load = load; 13022 busiest_capacity = capacity; 13023 busiest = rq; 13024 } 13025 break; 13026 13027 case migrate_util: 13028 util = cpu_util_cfs_boost(i); 13029 13030 /* 13031 * Don't try to pull utilization from a CPU with one 13032 * running task. Whatever its utilization, we will fail 13033 * detach the task. 13034 */ 13035 if (nr_running <= 1) 13036 continue; 13037 13038 if (busiest_util < util) { 13039 busiest_util = util; 13040 busiest = rq; 13041 } 13042 break; 13043 13044 case migrate_task: 13045 if (busiest_nr < nr_running) { 13046 busiest_nr = nr_running; 13047 busiest = rq; 13048 } 13049 break; 13050 13051 case migrate_misfit: 13052 /* 13053 * For ASYM_CPUCAPACITY domains with misfit tasks we 13054 * simply seek the "biggest" misfit task. 13055 */ 13056 if (rq->misfit_task_load > busiest_load) { 13057 busiest_load = rq->misfit_task_load; 13058 busiest = rq; 13059 } 13060 13061 break; 13062 13063 case migrate_llc_task: 13064 #ifdef CONFIG_SCHED_CACHE 13065 sd_tmp = rcu_dereference_all(rq->sd); 13066 dst_llc = llc_id(env->dst_cpu); 13067 13068 if (sd_tmp && (unsigned)dst_llc < sd_tmp->llc_max) { 13069 unsigned int this_pref_llc = 13070 sd_tmp->llc_counts[dst_llc]; 13071 13072 if (busiest_pref_llc < this_pref_llc) { 13073 busiest_pref_llc = this_pref_llc; 13074 busiest = rq; 13075 } 13076 } 13077 #endif 13078 break; 13079 13080 } 13081 } 13082 13083 return busiest; 13084 } 13085 13086 /* 13087 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but 13088 * so long as it is large enough. 13089 */ 13090 #define MAX_PINNED_INTERVAL 512 13091 13092 static inline bool 13093 asym_active_balance(struct lb_env *env) 13094 { 13095 /* 13096 * ASYM_PACKING needs to force migrate tasks from busy but lower 13097 * priority CPUs in order to pack all tasks in the highest priority 13098 * CPUs. When done between cores, do it only if the whole core if the 13099 * whole core is idle. 13100 * 13101 * If @env::src_cpu is an SMT core with busy siblings, let 13102 * the lower priority @env::dst_cpu help it. Do not follow 13103 * CPU priority. 13104 */ 13105 return env->idle && sched_use_asym_prio(env->sd, env->dst_cpu) && 13106 (sched_asym_prefer(env->dst_cpu, env->src_cpu) || 13107 !sched_use_asym_prio(env->sd, env->src_cpu)); 13108 } 13109 13110 static inline bool 13111 imbalanced_active_balance(struct lb_env *env) 13112 { 13113 struct sched_domain *sd = env->sd; 13114 13115 /* 13116 * The imbalanced case includes the case of pinned tasks preventing a fair 13117 * distribution of the load on the system but also the even distribution of the 13118 * threads on a system with spare capacity 13119 */ 13120 if ((env->migration_type == migrate_task) && 13121 (sd->nr_balance_failed > sd->cache_nice_tries+2)) 13122 return 1; 13123 13124 return 0; 13125 } 13126 13127 static int need_active_balance(struct lb_env *env) 13128 { 13129 struct sched_domain *sd = env->sd; 13130 13131 if (alb_break_llc(env)) 13132 return 0; 13133 13134 if (asym_active_balance(env)) 13135 return 1; 13136 13137 if (imbalanced_active_balance(env)) 13138 return 1; 13139 13140 /* 13141 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task. 13142 * It's worth migrating the task if the src_cpu's capacity is reduced 13143 * because of other sched_class or IRQs if more capacity stays 13144 * available on dst_cpu. 13145 */ 13146 if (env->idle && 13147 (env->src_rq->cfs.h_nr_runnable == 1)) { 13148 if ((check_cpu_capacity(env->src_rq, sd)) && 13149 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100)) 13150 return 1; 13151 } 13152 13153 if (env->migration_type == migrate_misfit || 13154 env->migration_type == migrate_llc_task) 13155 return 1; 13156 13157 return 0; 13158 } 13159 13160 static int active_load_balance_cpu_stop(void *data); 13161 13162 static int should_we_balance(struct lb_env *env) 13163 { 13164 struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask); 13165 struct sched_group *sg = env->sd->groups; 13166 int cpu, idle_smt = -1; 13167 13168 /* 13169 * Ensure the balancing environment is consistent; can happen 13170 * when the softirq triggers 'during' hotplug. 13171 */ 13172 if (!cpumask_test_cpu(env->dst_cpu, env->cpus)) 13173 return 0; 13174 13175 /* 13176 * In the newly idle case, we will allow all the CPUs 13177 * to do the newly idle load balance. 13178 * 13179 * However, we bail out if we already have tasks or a wakeup pending, 13180 * to optimize wakeup latency. 13181 */ 13182 if (env->idle == CPU_NEWLY_IDLE) { 13183 if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending) 13184 return 0; 13185 return 1; 13186 } 13187 13188 cpumask_copy(swb_cpus, group_balance_mask(sg)); 13189 /* Try to find first idle CPU */ 13190 for_each_cpu_and(cpu, swb_cpus, env->cpus) { 13191 if (!idle_cpu(cpu)) 13192 continue; 13193 13194 /* 13195 * Don't balance to idle SMT in busy core right away when 13196 * balancing cores, but remember the first idle SMT CPU for 13197 * later consideration. Find CPU on an idle core first. 13198 */ 13199 if (sched_smt_active() && 13200 !(env->sd->flags & SD_SHARE_CPUCAPACITY) && 13201 !is_core_idle(cpu)) { 13202 if (idle_smt == -1) 13203 idle_smt = cpu; 13204 /* 13205 * If the core is not idle, and first SMT sibling which is 13206 * idle has been found, then its not needed to check other 13207 * SMT siblings for idleness: 13208 */ 13209 cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu)); 13210 continue; 13211 } 13212 13213 /* 13214 * Are we the first idle core in a non-SMT domain or higher, 13215 * or the first idle CPU in a SMT domain? 13216 */ 13217 return cpu == env->dst_cpu; 13218 } 13219 13220 /* Are we the first idle CPU with busy siblings? */ 13221 if (idle_smt != -1) 13222 return idle_smt == env->dst_cpu; 13223 13224 /* Are we the first CPU of this group ? */ 13225 return group_balance_cpu(sg) == env->dst_cpu; 13226 } 13227 13228 static void update_lb_imbalance_stat(struct lb_env *env, struct sched_domain *sd, 13229 enum cpu_idle_type idle) 13230 { 13231 if (!schedstat_enabled()) 13232 return; 13233 13234 switch (env->migration_type) { 13235 case migrate_load: 13236 __schedstat_add(sd->lb_imbalance_load[idle], env->imbalance); 13237 break; 13238 case migrate_util: 13239 __schedstat_add(sd->lb_imbalance_util[idle], env->imbalance); 13240 break; 13241 case migrate_task: 13242 __schedstat_add(sd->lb_imbalance_task[idle], env->imbalance); 13243 break; 13244 case migrate_misfit: 13245 __schedstat_add(sd->lb_imbalance_misfit[idle], env->imbalance); 13246 break; 13247 case migrate_llc_task: 13248 break; 13249 } 13250 } 13251 13252 /* 13253 * This flag serializes load-balancing passes over large domains 13254 * (above the NODE topology level) - only one load-balancing instance 13255 * may run at a time, to reduce overhead on very large systems with 13256 * lots of CPUs and large NUMA distances. 13257 * 13258 * - Note that load-balancing passes triggered while another one 13259 * is executing are skipped and not re-tried. 13260 * 13261 * - Also note that this does not serialize rebalance_domains() 13262 * execution, as non-SD_SERIALIZE domains will still be 13263 * load-balanced in parallel. 13264 */ 13265 static atomic_t sched_balance_running = ATOMIC_INIT(0); 13266 13267 /* 13268 * Check this_cpu to ensure it is balanced within domain. Attempt to move 13269 * tasks if there is an imbalance. 13270 */ 13271 static int sched_balance_rq(int this_cpu, struct rq *this_rq, 13272 struct sched_domain *sd, enum cpu_idle_type idle, 13273 int *continue_balancing) 13274 { 13275 int ld_moved, cur_ld_moved, active_balance = 0; 13276 struct sched_domain *sd_parent = sd->parent; 13277 struct sched_group *group; 13278 struct rq *busiest; 13279 struct rq_flags rf; 13280 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask); 13281 struct lb_env env = { 13282 .sd = sd, 13283 .dst_cpu = this_cpu, 13284 .dst_rq = this_rq, 13285 .dst_grpmask = group_balance_mask(sd->groups), 13286 .idle = idle, 13287 .loop_break = SCHED_NR_MIGRATE_BREAK, 13288 .cpus = cpus, 13289 .fbq_type = all, 13290 .tasks = LIST_HEAD_INIT(env.tasks), 13291 }; 13292 bool need_unlock = false; 13293 13294 cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask); 13295 13296 schedstat_inc(sd->lb_count[idle]); 13297 13298 redo: 13299 if (!should_we_balance(&env)) { 13300 *continue_balancing = 0; 13301 goto out_balanced; 13302 } 13303 13304 if (!need_unlock && (sd->flags & SD_SERIALIZE)) { 13305 int zero = 0; 13306 if (!atomic_try_cmpxchg_acquire(&sched_balance_running, &zero, 1)) 13307 goto out_balanced; 13308 13309 need_unlock = true; 13310 } 13311 13312 group = sched_balance_find_src_group(&env); 13313 if (!group) { 13314 schedstat_inc(sd->lb_nobusyg[idle]); 13315 goto out_balanced; 13316 } 13317 13318 busiest = sched_balance_find_src_rq(&env, group); 13319 if (!busiest) { 13320 schedstat_inc(sd->lb_nobusyq[idle]); 13321 goto out_balanced; 13322 } 13323 13324 WARN_ON_ONCE(busiest == env.dst_rq); 13325 13326 update_lb_imbalance_stat(&env, sd, idle); 13327 13328 env.src_cpu = busiest->cpu; 13329 env.src_rq = busiest; 13330 13331 ld_moved = 0; 13332 /* Clear this flag as soon as we find a pullable task */ 13333 env.flags |= LBF_ALL_PINNED; 13334 if (busiest->nr_running > 1) { 13335 /* 13336 * Attempt to move tasks. If sched_balance_find_src_group has found 13337 * an imbalance but busiest->nr_running <= 1, the group is 13338 * still unbalanced. ld_moved simply stays zero, so it is 13339 * correctly treated as an imbalance. 13340 */ 13341 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running); 13342 13343 more_balance: 13344 rq_lock_irqsave(busiest, &rf); 13345 update_rq_clock(busiest); 13346 13347 /* 13348 * cur_ld_moved - load moved in current iteration 13349 * ld_moved - cumulative load moved across iterations 13350 */ 13351 cur_ld_moved = detach_tasks(&env); 13352 13353 /* 13354 * We've detached some tasks from busiest_rq. Every 13355 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely 13356 * unlock busiest->lock, and we are able to be sure 13357 * that nobody can manipulate the tasks in parallel. 13358 * See task_rq_lock() family for the details. 13359 */ 13360 13361 rq_unlock(busiest, &rf); 13362 13363 if (cur_ld_moved) { 13364 attach_tasks(&env); 13365 ld_moved += cur_ld_moved; 13366 } 13367 13368 local_irq_restore(rf.flags); 13369 13370 if (env.flags & LBF_NEED_BREAK) { 13371 env.flags &= ~LBF_NEED_BREAK; 13372 goto more_balance; 13373 } 13374 13375 /* 13376 * Revisit (affine) tasks on src_cpu that couldn't be moved to 13377 * us and move them to an alternate dst_cpu in our sched_group 13378 * where they can run. The upper limit on how many times we 13379 * iterate on same src_cpu is dependent on number of CPUs in our 13380 * sched_group. 13381 * 13382 * This changes load balance semantics a bit on who can move 13383 * load to a given_cpu. In addition to the given_cpu itself 13384 * (or a ilb_cpu acting on its behalf where given_cpu is 13385 * nohz-idle), we now have balance_cpu in a position to move 13386 * load to given_cpu. In rare situations, this may cause 13387 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding 13388 * _independently_ and at _same_ time to move some load to 13389 * given_cpu) causing excess load to be moved to given_cpu. 13390 * This however should not happen so much in practice and 13391 * moreover subsequent load balance cycles should correct the 13392 * excess load moved. 13393 */ 13394 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) { 13395 13396 /* Prevent to re-select dst_cpu via env's CPUs */ 13397 __cpumask_clear_cpu(env.dst_cpu, env.cpus); 13398 13399 env.dst_rq = cpu_rq(env.new_dst_cpu); 13400 env.dst_cpu = env.new_dst_cpu; 13401 env.flags &= ~LBF_DST_PINNED; 13402 env.loop = 0; 13403 env.loop_break = SCHED_NR_MIGRATE_BREAK; 13404 13405 /* 13406 * Go back to "more_balance" rather than "redo" since we 13407 * need to continue with same src_cpu. 13408 */ 13409 goto more_balance; 13410 } 13411 13412 /* 13413 * We failed to reach balance because of affinity. 13414 */ 13415 if (sd_parent) { 13416 int *group_imbalance = &sd_parent->groups->sgc->imbalance; 13417 13418 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0) 13419 *group_imbalance = 1; 13420 } 13421 13422 /* All tasks on this runqueue were pinned by CPU affinity */ 13423 if (unlikely(env.flags & LBF_ALL_PINNED)) { 13424 __cpumask_clear_cpu(cpu_of(busiest), cpus); 13425 /* 13426 * Attempting to continue load balancing at the current 13427 * sched_domain level only makes sense if there are 13428 * active CPUs remaining as possible busiest CPUs to 13429 * pull load from which are not contained within the 13430 * destination group that is receiving any migrated 13431 * load. 13432 */ 13433 if (!cpumask_subset(cpus, env.dst_grpmask)) { 13434 env.loop = 0; 13435 env.loop_break = SCHED_NR_MIGRATE_BREAK; 13436 goto redo; 13437 } 13438 goto out_all_pinned; 13439 } 13440 } 13441 13442 if (!ld_moved) { 13443 schedstat_inc(sd->lb_failed[idle]); 13444 /* 13445 * Increment the failure counter only on periodic balance. 13446 * We do not want newidle balance, which can be very 13447 * frequent, pollute the failure counter causing 13448 * excessive cache_hot migrations and active balances. 13449 * 13450 * Similarly for migration_misfit which is not related to 13451 * load/util migration, don't pollute nr_balance_failed. 13452 * 13453 * The same for cache aware scheduling's allowance for 13454 * load imbalance. If regular load balance does not 13455 * migrate task due to LLC locality, it is a expected 13456 * behavior and don't pollute nr_balance_failed. 13457 * See can_migrate_task(). 13458 */ 13459 if (idle != CPU_NEWLY_IDLE && 13460 env.migration_type != migrate_misfit && 13461 !(env.flags & LBF_LLC_PINNED)) 13462 sd->nr_balance_failed++; 13463 13464 if (need_active_balance(&env)) { 13465 unsigned long flags; 13466 13467 raw_spin_rq_lock_irqsave(busiest, flags); 13468 13469 /* 13470 * Don't kick the active_load_balance_cpu_stop, 13471 * if the curr task on busiest CPU can't be 13472 * moved to this_cpu: 13473 */ 13474 if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) { 13475 raw_spin_rq_unlock_irqrestore(busiest, flags); 13476 goto out_one_pinned; 13477 } 13478 13479 /* Record that we found at least one task that could run on this_cpu */ 13480 env.flags &= ~LBF_ALL_PINNED; 13481 13482 /* 13483 * ->active_balance synchronizes accesses to 13484 * ->active_balance_work. Once set, it's cleared 13485 * only after active load balance is finished. 13486 */ 13487 if (!busiest->active_balance) { 13488 busiest->active_balance = 1; 13489 busiest->push_cpu = this_cpu; 13490 active_balance = 1; 13491 } 13492 13493 preempt_disable(); 13494 raw_spin_rq_unlock_irqrestore(busiest, flags); 13495 if (active_balance) { 13496 stop_one_cpu_nowait(cpu_of(busiest), 13497 active_load_balance_cpu_stop, busiest, 13498 &busiest->active_balance_work); 13499 } 13500 preempt_enable(); 13501 } 13502 } else { 13503 sd->nr_balance_failed = 0; 13504 } 13505 13506 if (likely(!active_balance) || need_active_balance(&env)) { 13507 /* We were unbalanced, so reset the balancing interval */ 13508 sd->balance_interval = sd->min_interval; 13509 } 13510 13511 goto out; 13512 13513 out_balanced: 13514 /* 13515 * We reach balance although we may have faced some affinity 13516 * constraints. Clear the imbalance flag only if other tasks got 13517 * a chance to move and fix the imbalance. 13518 */ 13519 if (sd_parent && !(env.flags & LBF_ALL_PINNED)) { 13520 int *group_imbalance = &sd_parent->groups->sgc->imbalance; 13521 13522 if (*group_imbalance) 13523 *group_imbalance = 0; 13524 } 13525 13526 out_all_pinned: 13527 /* 13528 * We reach balance because all tasks are pinned at this level so 13529 * we can't migrate them. Let the imbalance flag set so parent level 13530 * can try to migrate them. 13531 */ 13532 schedstat_inc(sd->lb_balanced[idle]); 13533 13534 sd->nr_balance_failed = 0; 13535 13536 out_one_pinned: 13537 ld_moved = 0; 13538 13539 /* 13540 * sched_balance_newidle() disregards balance intervals, so we could 13541 * repeatedly reach this code, which would lead to balance_interval 13542 * skyrocketing in a short amount of time. Skip the balance_interval 13543 * increase logic to avoid that. 13544 * 13545 * Similarly misfit migration which is not necessarily an indication of 13546 * the system being busy and requires lb to backoff to let it settle 13547 * down. 13548 */ 13549 if (env.idle == CPU_NEWLY_IDLE || 13550 env.migration_type == migrate_misfit) 13551 goto out; 13552 13553 /* tune up the balancing interval */ 13554 if ((env.flags & LBF_ALL_PINNED && 13555 sd->balance_interval < MAX_PINNED_INTERVAL) || 13556 sd->balance_interval < sd->max_interval) 13557 sd->balance_interval *= 2; 13558 out: 13559 if (need_unlock) 13560 atomic_set_release(&sched_balance_running, 0); 13561 13562 return ld_moved; 13563 } 13564 13565 static inline unsigned long 13566 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy) 13567 { 13568 unsigned long interval = sd->balance_interval; 13569 13570 if (cpu_busy) 13571 interval *= sd->busy_factor; 13572 13573 /* scale ms to jiffies */ 13574 interval = msecs_to_jiffies(interval); 13575 13576 /* 13577 * Reduce likelihood of busy balancing at higher domains racing with 13578 * balancing at lower domains by preventing their balancing periods 13579 * from being multiples of each other. 13580 */ 13581 if (cpu_busy) 13582 interval -= 1; 13583 13584 interval = clamp(interval, 1UL, max_load_balance_interval); 13585 13586 return interval; 13587 } 13588 13589 static inline void 13590 update_next_balance(struct sched_domain *sd, unsigned long *next_balance) 13591 { 13592 unsigned long interval, next; 13593 13594 /* used by idle balance, so cpu_busy = 0 */ 13595 interval = get_sd_balance_interval(sd, 0); 13596 next = sd->last_balance + interval; 13597 13598 if (time_after(*next_balance, next)) 13599 *next_balance = next; 13600 } 13601 13602 /* 13603 * active_load_balance_cpu_stop is run by the CPU stopper. It pushes 13604 * running tasks off the busiest CPU onto idle CPUs. It requires at 13605 * least 1 task to be running on each physical CPU where possible, and 13606 * avoids physical / logical imbalances. 13607 */ 13608 static int active_load_balance_cpu_stop(void *data) 13609 { 13610 struct rq *busiest_rq = data; 13611 int busiest_cpu = cpu_of(busiest_rq); 13612 int target_cpu = busiest_rq->push_cpu; 13613 struct rq *target_rq = cpu_rq(target_cpu); 13614 struct sched_domain *sd; 13615 struct task_struct *p = NULL; 13616 struct rq_flags rf; 13617 13618 rq_lock_irq(busiest_rq, &rf); 13619 /* 13620 * Between queueing the stop-work and running it is a hole in which 13621 * CPUs can become inactive. We should not move tasks from or to 13622 * inactive CPUs. 13623 */ 13624 if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu)) 13625 goto out_unlock; 13626 13627 /* Make sure the requested CPU hasn't gone down in the meantime: */ 13628 if (unlikely(busiest_cpu != smp_processor_id() || 13629 !busiest_rq->active_balance)) 13630 goto out_unlock; 13631 13632 /* Is there any task to move? */ 13633 if (busiest_rq->nr_running <= 1) 13634 goto out_unlock; 13635 13636 /* 13637 * This condition is "impossible", if it occurs 13638 * we need to fix it. Originally reported by 13639 * Bjorn Helgaas on a 128-CPU setup. 13640 */ 13641 WARN_ON_ONCE(busiest_rq == target_rq); 13642 13643 /* Search for an sd spanning us and the target CPU. */ 13644 rcu_read_lock(); 13645 for_each_domain(target_cpu, sd) { 13646 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd))) 13647 break; 13648 } 13649 13650 if (likely(sd)) { 13651 struct lb_env env = { 13652 .sd = sd, 13653 .dst_cpu = target_cpu, 13654 .dst_rq = target_rq, 13655 .src_cpu = busiest_rq->cpu, 13656 .src_rq = busiest_rq, 13657 .idle = CPU_IDLE, 13658 .flags = LBF_ACTIVE_LB, 13659 }; 13660 13661 schedstat_inc(sd->alb_count); 13662 update_rq_clock(busiest_rq); 13663 13664 p = detach_one_task(&env); 13665 if (p) { 13666 schedstat_inc(sd->alb_pushed); 13667 /* Active balancing done, reset the failure counter. */ 13668 sd->nr_balance_failed = 0; 13669 } else { 13670 schedstat_inc(sd->alb_failed); 13671 } 13672 } 13673 rcu_read_unlock(); 13674 out_unlock: 13675 busiest_rq->active_balance = 0; 13676 rq_unlock(busiest_rq, &rf); 13677 13678 if (p) 13679 attach_one_task(target_rq, p); 13680 13681 local_irq_enable(); 13682 13683 return 0; 13684 } 13685 13686 /* 13687 * Scale the max sched_balance_rq interval with the number of CPUs in the system. 13688 * This trades load-balance latency on larger machines for less cross talk. 13689 */ 13690 void update_max_interval(void) 13691 { 13692 max_load_balance_interval = HZ*num_online_cpus()/10; 13693 } 13694 13695 static inline void update_newidle_stats(struct sched_domain *sd, unsigned int success) 13696 { 13697 sd->newidle_call++; 13698 sd->newidle_success += success; 13699 13700 if (sd->newidle_call >= 1024) { 13701 u64 now = sched_clock(); 13702 s64 delta = now - sd->newidle_stamp; 13703 sd->newidle_stamp = now; 13704 int ratio = 0; 13705 13706 if (delta < 0) 13707 delta = 0; 13708 13709 if (sched_feat(NI_RATE)) { 13710 /* 13711 * ratio delta freq 13712 * 13713 * 1024 - 4 s - 128 Hz 13714 * 512 - 2 s - 256 Hz 13715 * 256 - 1 s - 512 Hz 13716 * 128 - .5 s - 1024 Hz 13717 * 64 - .25 s - 2048 Hz 13718 */ 13719 ratio = delta >> 22; 13720 } 13721 13722 ratio += sd->newidle_success; 13723 13724 sd->newidle_ratio = min(1024, ratio); 13725 sd->newidle_call /= 2; 13726 sd->newidle_success /= 2; 13727 } 13728 } 13729 13730 static inline bool 13731 update_newidle_cost(struct sched_domain *sd, u64 cost, unsigned int success) 13732 { 13733 unsigned long next_decay = sd->last_decay_max_lb_cost + HZ; 13734 unsigned long now = jiffies; 13735 13736 if (cost) 13737 update_newidle_stats(sd, success); 13738 13739 if (cost > sd->max_newidle_lb_cost) { 13740 /* 13741 * Track max cost of a domain to make sure to not delay the 13742 * next wakeup on the CPU. 13743 */ 13744 sd->max_newidle_lb_cost = cost; 13745 sd->last_decay_max_lb_cost = now; 13746 13747 } else if (time_after(now, next_decay)) { 13748 /* 13749 * Decay the newidle max times by ~1% per second to ensure that 13750 * it is not outdated and the current max cost is actually 13751 * shorter. 13752 */ 13753 sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256; 13754 sd->last_decay_max_lb_cost = now; 13755 return true; 13756 } 13757 13758 return false; 13759 } 13760 13761 /* 13762 * It checks each scheduling domain to see if it is due to be balanced, 13763 * and initiates a balancing operation if so. 13764 * 13765 * Balancing parameters are set up in init_sched_domains. 13766 */ 13767 static void sched_balance_domains(struct rq *rq, enum cpu_idle_type idle) 13768 { 13769 int continue_balancing = 1; 13770 int cpu = rq->cpu; 13771 int busy = idle != CPU_IDLE && !sched_idle_rq(rq); 13772 unsigned long interval; 13773 struct sched_domain *sd; 13774 /* Earliest time when we have to do rebalance again */ 13775 unsigned long next_balance = jiffies + 60*HZ; 13776 int update_next_balance = 0; 13777 int need_decay = 0; 13778 u64 max_cost = 0; 13779 13780 rcu_read_lock(); 13781 for_each_domain(cpu, sd) { 13782 /* 13783 * Decay the newidle max times here because this is a regular 13784 * visit to all the domains. 13785 */ 13786 need_decay = update_newidle_cost(sd, 0, 0); 13787 max_cost += sd->max_newidle_lb_cost; 13788 13789 /* 13790 * Stop the load balance at this level. There is another 13791 * CPU in our sched group which is doing load balancing more 13792 * actively. 13793 */ 13794 if (!continue_balancing) { 13795 if (need_decay) 13796 continue; 13797 break; 13798 } 13799 13800 interval = get_sd_balance_interval(sd, busy); 13801 if (time_after_eq(jiffies, sd->last_balance + interval)) { 13802 if (sched_balance_rq(cpu, rq, sd, idle, &continue_balancing)) { 13803 /* 13804 * The LBF_DST_PINNED logic could have changed 13805 * env->dst_cpu, so we can't know our idle 13806 * state even if we migrated tasks. Update it. 13807 */ 13808 idle = idle_cpu(cpu); 13809 busy = !idle && !sched_idle_rq(rq); 13810 } 13811 sd->last_balance = jiffies; 13812 interval = get_sd_balance_interval(sd, busy); 13813 } 13814 if (time_after(next_balance, sd->last_balance + interval)) { 13815 next_balance = sd->last_balance + interval; 13816 update_next_balance = 1; 13817 } 13818 } 13819 if (need_decay) { 13820 /* 13821 * Ensure the rq-wide value also decays but keep it at a 13822 * reasonable floor to avoid funnies with rq->avg_idle. 13823 */ 13824 rq->max_idle_balance_cost = 13825 max((u64)sysctl_sched_migration_cost, max_cost); 13826 } 13827 rcu_read_unlock(); 13828 13829 /* 13830 * next_balance will be updated only when there is a need. 13831 * When the cpu is attached to null domain for ex, it will not be 13832 * updated. 13833 */ 13834 if (likely(update_next_balance)) 13835 rq->next_balance = next_balance; 13836 13837 } 13838 13839 static inline int on_null_domain(struct rq *rq) 13840 { 13841 return unlikely(!rcu_dereference_sched(rq->sd)); 13842 } 13843 13844 #ifdef CONFIG_NO_HZ_COMMON 13845 /* 13846 * NOHZ idle load balancing (ILB) details: 13847 * 13848 * - When one of the busy CPUs notices that there may be an idle rebalancing 13849 * needed, they will kick the idle load balancer, which then does idle 13850 * load balancing for all the idle CPUs. 13851 */ 13852 static inline int find_new_ilb(void) 13853 { 13854 int this_cpu = smp_processor_id(); 13855 const struct cpumask *hk_mask; 13856 int ilb_cpu; 13857 13858 hk_mask = housekeeping_cpumask(HK_TYPE_KERNEL_NOISE); 13859 13860 for_each_cpu_and(ilb_cpu, nohz.idle_cpus_mask, hk_mask) { 13861 if (ilb_cpu == this_cpu) 13862 continue; 13863 13864 if (idle_cpu(ilb_cpu)) 13865 return ilb_cpu; 13866 } 13867 13868 return -1; 13869 } 13870 13871 /* 13872 * Kick a CPU to do the NOHZ balancing, if it is time for it, via a cross-CPU 13873 * SMP function call (IPI). 13874 * 13875 * We pick the first idle CPU in the HK_TYPE_KERNEL_NOISE housekeeping set 13876 * (if there is one). 13877 */ 13878 static void kick_ilb(unsigned int flags) 13879 { 13880 int ilb_cpu; 13881 13882 /* 13883 * Increase nohz.next_balance only when if full ilb is triggered but 13884 * not if we only update stats. 13885 */ 13886 if (flags & NOHZ_BALANCE_KICK) 13887 nohz.next_balance = jiffies+1; 13888 13889 ilb_cpu = find_new_ilb(); 13890 if (ilb_cpu < 0) 13891 return; 13892 13893 /* 13894 * Don't bother if no new NOHZ balance work items for ilb_cpu, 13895 * i.e. all bits in flags are already set in ilb_cpu. 13896 */ 13897 if ((atomic_read(nohz_flags(ilb_cpu)) & flags) == flags) 13898 return; 13899 13900 /* 13901 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets 13902 * the first flag owns it; cleared by nohz_csd_func(). 13903 */ 13904 flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu)); 13905 if (flags & NOHZ_KICK_MASK) 13906 return; 13907 13908 /* 13909 * This way we generate an IPI on the target CPU which 13910 * is idle, and the softirq performing NOHZ idle load balancing 13911 * will be run before returning from the IPI. 13912 */ 13913 smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd); 13914 } 13915 13916 /* 13917 * Current decision point for kicking the idle load balancer in the presence 13918 * of idle CPUs in the system. 13919 */ 13920 static void nohz_balancer_kick(struct rq *rq) 13921 { 13922 unsigned long now = jiffies; 13923 struct sched_domain_shared *sds; 13924 struct sched_domain *sd; 13925 int nr_busy, i, cpu = rq->cpu; 13926 unsigned int flags = 0; 13927 13928 if (unlikely(rq->idle_balance)) 13929 return; 13930 13931 /* 13932 * We may be recently in ticked or tickless idle mode. At the first 13933 * busy tick after returning from idle, we will update the busy stats. 13934 */ 13935 nohz_balance_exit_idle(rq); 13936 13937 if (READ_ONCE(nohz.has_blocked_load) && 13938 time_after(now, READ_ONCE(nohz.next_blocked))) 13939 flags = NOHZ_STATS_KICK; 13940 13941 /* 13942 * Most of the time system is not 100% busy. i.e nohz.nr_cpus > 0 13943 * Skip the read if time is not due. 13944 * 13945 * If none are in tickless mode, there maybe a narrow window 13946 * (28 jiffies, HZ=1000) where flags maybe set and kick_ilb called. 13947 * But idle load balancing is not done as find_new_ilb fails. 13948 * That's very rare. So read nohz.nr_cpus only if time is due. 13949 */ 13950 if (time_before(now, nohz.next_balance)) 13951 goto out; 13952 13953 /* 13954 * None are in tickless mode and hence no need for NOHZ idle load 13955 * balancing 13956 */ 13957 if (unlikely(cpumask_empty(nohz.idle_cpus_mask))) 13958 return; 13959 13960 if (rq->nr_running >= 2) { 13961 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 13962 goto out; 13963 } 13964 13965 sd = rcu_dereference_all(rq->sd); 13966 if (sd) { 13967 /* 13968 * If there's a runnable CFS task and the current CPU has reduced 13969 * capacity, kick the ILB to see if there's a better CPU to run on: 13970 */ 13971 if (rq->cfs.h_nr_runnable >= 1 && check_cpu_capacity(rq, sd)) { 13972 flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 13973 goto out; 13974 } 13975 } 13976 13977 sd = rcu_dereference_all(per_cpu(sd_asym_packing, cpu)); 13978 if (sd) { 13979 /* 13980 * When ASYM_PACKING; see if there's a more preferred CPU 13981 * currently idle; in which case, kick the ILB to move tasks 13982 * around. 13983 * 13984 * When balancing between cores, all the SMT siblings of the 13985 * preferred CPU must be idle. 13986 */ 13987 for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) { 13988 if (sched_asym(sd, i, cpu)) { 13989 flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 13990 goto out; 13991 } 13992 } 13993 } 13994 13995 sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, cpu)); 13996 if (sd) { 13997 /* 13998 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU 13999 * to run the misfit task on. 14000 */ 14001 if (check_misfit_status(rq)) 14002 flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 14003 14004 /* 14005 * For asymmetric systems, we do not want to nicely balance 14006 * cache use, instead we want to embrace asymmetry and only 14007 * ensure tasks have enough CPU capacity. 14008 * 14009 * Skip the LLC logic because it's not relevant in that case. 14010 */ 14011 goto out; 14012 } 14013 14014 sds = rcu_dereference_all(per_cpu(sd_balance_shared, cpu)); 14015 if (sds) { 14016 /* 14017 * If there is an imbalance between LLC domains (IOW we could 14018 * increase the overall cache utilization), we need a less-loaded LLC 14019 * domain to pull some load from. Likewise, we may need to spread 14020 * load within the current LLC domain (e.g. packed SMT cores but 14021 * other CPUs are idle). We can't really know from here how busy 14022 * the others are - so just get a NOHZ balance going if it looks 14023 * like this LLC domain has tasks we could move. 14024 */ 14025 nr_busy = atomic_read(&sds->nr_busy_cpus); 14026 if (nr_busy > 1) 14027 flags |= NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 14028 } 14029 out: 14030 if (READ_ONCE(nohz.needs_update)) 14031 flags |= NOHZ_NEXT_KICK; 14032 14033 if (flags) 14034 kick_ilb(flags); 14035 } 14036 14037 static void set_cpu_sd_state_busy(int cpu) 14038 { 14039 struct sched_domain *sd; 14040 sd = rcu_dereference_all(per_cpu(sd_llc, cpu)); 14041 14042 /* 14043 * sd->nohz_idle only pairs with nr_busy_cpus on sd->shared; if this 14044 * domain has no shared object there is nothing to clear or account. 14045 */ 14046 if (!sd || !sd->shared || !sd->nohz_idle) 14047 return; 14048 sd->nohz_idle = 0; 14049 14050 atomic_inc(&sd->shared->nr_busy_cpus); 14051 } 14052 14053 void nohz_balance_exit_idle(struct rq *rq) 14054 { 14055 WARN_ON_ONCE(rq != this_rq()); 14056 14057 if (likely(!rq->nohz_tick_stopped)) 14058 return; 14059 14060 rq->nohz_tick_stopped = 0; 14061 cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask); 14062 14063 set_cpu_sd_state_busy(rq->cpu); 14064 } 14065 14066 static void set_cpu_sd_state_idle(int cpu) 14067 { 14068 struct sched_domain *sd; 14069 sd = rcu_dereference_all(per_cpu(sd_llc, cpu)); 14070 14071 /* See set_cpu_sd_state_busy(): nohz_idle is only used with sd->shared. */ 14072 if (!sd || !sd->shared || sd->nohz_idle) 14073 return; 14074 sd->nohz_idle = 1; 14075 14076 atomic_dec(&sd->shared->nr_busy_cpus); 14077 } 14078 14079 /* 14080 * This routine will record that the CPU is going idle with tick stopped. 14081 * This info will be used in performing idle load balancing in the future. 14082 */ 14083 void nohz_balance_enter_idle(int cpu) 14084 { 14085 struct rq *rq = cpu_rq(cpu); 14086 14087 WARN_ON_ONCE(cpu != smp_processor_id()); 14088 14089 /* If this CPU is going down, then nothing needs to be done: */ 14090 if (!cpu_active(cpu)) 14091 return; 14092 14093 /* 14094 * Can be set safely without rq->lock held 14095 * If a clear happens, it will have evaluated last additions because 14096 * rq->lock is held during the check and the clear 14097 */ 14098 rq->has_blocked_load = 1; 14099 14100 /* 14101 * The tick is still stopped but load could have been added in the 14102 * meantime. We set the nohz.has_blocked_load flag to trig a check of the 14103 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear 14104 * of nohz.has_blocked_load can only happen after checking the new load 14105 */ 14106 if (rq->nohz_tick_stopped) 14107 goto out; 14108 14109 /* If we're a completely isolated CPU, we don't play: */ 14110 if (on_null_domain(rq)) 14111 return; 14112 14113 rq->nohz_tick_stopped = 1; 14114 14115 cpumask_set_cpu(cpu, nohz.idle_cpus_mask); 14116 14117 /* 14118 * Ensures that if nohz_idle_balance() fails to observe our 14119 * @idle_cpus_mask store, it must observe the @has_blocked_load 14120 * and @needs_update stores. 14121 */ 14122 smp_mb__after_atomic(); 14123 14124 set_cpu_sd_state_idle(cpu); 14125 14126 WRITE_ONCE(nohz.needs_update, 1); 14127 out: 14128 /* 14129 * Each time a cpu enter idle, we assume that it has blocked load and 14130 * enable the periodic update of the load of idle CPUs 14131 */ 14132 WRITE_ONCE(nohz.has_blocked_load, 1); 14133 } 14134 14135 static bool update_nohz_stats(struct rq *rq) 14136 { 14137 unsigned int cpu = rq->cpu; 14138 14139 if (!rq->has_blocked_load) 14140 return false; 14141 14142 if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask)) 14143 return false; 14144 14145 if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick))) 14146 return true; 14147 14148 sched_balance_update_blocked_averages(cpu); 14149 14150 return rq->has_blocked_load; 14151 } 14152 14153 /* 14154 * Internal function that runs load balance for all idle CPUs. The load balance 14155 * can be a simple update of blocked load or a complete load balance with 14156 * tasks movement depending of flags. 14157 */ 14158 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags) 14159 { 14160 /* Earliest time when we have to do rebalance again */ 14161 unsigned long now = jiffies; 14162 unsigned long next_balance = now + 60*HZ; 14163 bool has_blocked_load = false; 14164 int update_next_balance = 0; 14165 int this_cpu = this_rq->cpu; 14166 int balance_cpu; 14167 struct rq *rq; 14168 14169 WARN_ON_ONCE((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK); 14170 14171 /* 14172 * We assume there will be no idle load after this update and clear 14173 * the has_blocked_load flag. If a cpu enters idle in the mean time, it will 14174 * set the has_blocked_load flag and trigger another update of idle load. 14175 * Because a cpu that becomes idle, is added to idle_cpus_mask before 14176 * setting the flag, we are sure to not clear the state and not 14177 * check the load of an idle cpu. 14178 * 14179 * Same applies to idle_cpus_mask vs needs_update. 14180 */ 14181 if (flags & NOHZ_STATS_KICK) 14182 WRITE_ONCE(nohz.has_blocked_load, 0); 14183 if (flags & NOHZ_NEXT_KICK) 14184 WRITE_ONCE(nohz.needs_update, 0); 14185 14186 /* 14187 * Ensures that if we miss the CPU, we must see the has_blocked_load 14188 * store from nohz_balance_enter_idle(). 14189 */ 14190 smp_mb(); 14191 14192 /* 14193 * Start with the next CPU after this_cpu so we will end with this_cpu and let a 14194 * chance for other idle cpu to pull load. 14195 */ 14196 for_each_cpu_wrap(balance_cpu, nohz.idle_cpus_mask, this_cpu+1) { 14197 if (!idle_cpu(balance_cpu)) 14198 continue; 14199 14200 /* 14201 * If this CPU gets work to do, stop the load balancing 14202 * work being done for other CPUs. Next load 14203 * balancing owner will pick it up. 14204 */ 14205 if (!idle_cpu(this_cpu) && need_resched()) { 14206 if (flags & NOHZ_STATS_KICK) 14207 has_blocked_load = true; 14208 if (flags & NOHZ_NEXT_KICK) 14209 WRITE_ONCE(nohz.needs_update, 1); 14210 goto abort; 14211 } 14212 14213 rq = cpu_rq(balance_cpu); 14214 14215 if (flags & NOHZ_STATS_KICK) 14216 has_blocked_load |= update_nohz_stats(rq); 14217 14218 /* 14219 * If time for next balance is due, 14220 * do the balance. 14221 */ 14222 if (time_after_eq(jiffies, rq->next_balance)) { 14223 struct rq_flags rf; 14224 14225 rq_lock_irqsave(rq, &rf); 14226 update_rq_clock(rq); 14227 rq_unlock_irqrestore(rq, &rf); 14228 14229 if (flags & NOHZ_BALANCE_KICK) 14230 sched_balance_domains(rq, CPU_IDLE); 14231 } 14232 14233 if (time_after(next_balance, rq->next_balance)) { 14234 next_balance = rq->next_balance; 14235 update_next_balance = 1; 14236 } 14237 } 14238 14239 /* 14240 * next_balance will be updated only when there is a need. 14241 * When the CPU is attached to null domain for ex, it will not be 14242 * updated. 14243 */ 14244 if (likely(update_next_balance)) 14245 nohz.next_balance = next_balance; 14246 14247 if (flags & NOHZ_STATS_KICK) 14248 WRITE_ONCE(nohz.next_blocked, 14249 now + msecs_to_jiffies(LOAD_AVG_PERIOD)); 14250 14251 abort: 14252 /* There is still blocked load, enable periodic update */ 14253 if (has_blocked_load) 14254 WRITE_ONCE(nohz.has_blocked_load, 1); 14255 } 14256 14257 /* 14258 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the 14259 * rebalancing for all the CPUs for whom scheduler ticks are stopped. 14260 */ 14261 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) 14262 { 14263 unsigned int flags = this_rq->nohz_idle_balance; 14264 14265 if (!flags) 14266 return false; 14267 14268 this_rq->nohz_idle_balance = 0; 14269 14270 if (idle != CPU_IDLE) 14271 return false; 14272 14273 _nohz_idle_balance(this_rq, flags); 14274 14275 return true; 14276 } 14277 14278 /* 14279 * Check if we need to directly run the ILB for updating blocked load before 14280 * entering idle state. Here we run ILB directly without issuing IPIs. 14281 * 14282 * Note that when this function is called, the tick may not yet be stopped on 14283 * this CPU yet. nohz.idle_cpus_mask is updated only when tick is stopped and 14284 * cleared on the next busy tick. In other words, nohz.idle_cpus_mask updates 14285 * don't align with CPUs enter/exit idle to avoid bottlenecks due to high idle 14286 * entry/exit rate (usec). So it is possible that _nohz_idle_balance() is 14287 * called from this function on (this) CPU that's not yet in the mask. That's 14288 * OK because the goal of nohz_run_idle_balance() is to run ILB only for 14289 * updating the blocked load of already idle CPUs without waking up one of 14290 * those idle CPUs and outside the preempt disable / IRQ off phase of the local 14291 * cpu about to enter idle, because it can take a long time. 14292 */ 14293 void nohz_run_idle_balance(int cpu) 14294 { 14295 unsigned int flags; 14296 14297 flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu)); 14298 14299 /* 14300 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen 14301 * (i.e. NOHZ_STATS_KICK set) and will do the same. 14302 */ 14303 if ((flags == NOHZ_NEWILB_KICK) && !need_resched()) 14304 _nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK); 14305 } 14306 14307 static void nohz_newidle_balance(struct rq *this_rq) 14308 { 14309 int this_cpu = this_rq->cpu; 14310 14311 /* Will wake up very soon. No time for doing anything else*/ 14312 if (this_rq->avg_idle < sysctl_sched_migration_cost) 14313 return; 14314 14315 /* Don't need to update blocked load of idle CPUs*/ 14316 if (!READ_ONCE(nohz.has_blocked_load) || 14317 time_before(jiffies, READ_ONCE(nohz.next_blocked))) 14318 return; 14319 14320 /* 14321 * Set the need to trigger ILB in order to update blocked load 14322 * before entering idle state. 14323 */ 14324 atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu)); 14325 } 14326 14327 #else /* !CONFIG_NO_HZ_COMMON: */ 14328 static inline void nohz_balancer_kick(struct rq *rq) { } 14329 14330 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) 14331 { 14332 return false; 14333 } 14334 14335 static inline void nohz_newidle_balance(struct rq *this_rq) { } 14336 #endif /* !CONFIG_NO_HZ_COMMON */ 14337 14338 /* 14339 * sched_balance_newidle is called by schedule() if this_cpu is about to become 14340 * idle. Attempts to pull tasks from other CPUs. 14341 * 14342 * Returns: 14343 * < 0 - we released the lock and there are !fair tasks present 14344 * 0 - failed, no new tasks 14345 * > 0 - success, new (fair) tasks present 14346 */ 14347 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf) 14348 __must_hold(__rq_lockp(this_rq)) 14349 { 14350 unsigned long next_balance = jiffies + HZ; 14351 int this_cpu = this_rq->cpu; 14352 int continue_balancing = 1; 14353 u64 t0, t1, curr_cost = 0; 14354 struct sched_domain *sd; 14355 int pulled_task = 0; 14356 14357 update_misfit_status(NULL, this_rq); 14358 14359 /* 14360 * There is a task waiting to run. No need to search for one. 14361 * Return 0; the task will be enqueued when switching to idle. 14362 */ 14363 if (this_rq->ttwu_pending) 14364 return 0; 14365 14366 /* 14367 * We must set idle_stamp _before_ calling sched_balance_rq() 14368 * for CPU_NEWLY_IDLE, such that we measure the this duration 14369 * as idle time. 14370 */ 14371 this_rq->idle_stamp = rq_clock(this_rq); 14372 14373 /* 14374 * Do not pull tasks towards !active CPUs... 14375 */ 14376 if (!cpu_active(this_cpu)) 14377 return 0; 14378 14379 /* 14380 * This is OK, because current is on_cpu, which avoids it being picked 14381 * for load-balance and preemption/IRQs are still disabled avoiding 14382 * further scheduler activity on it and we're being very careful to 14383 * re-start the picking loop. 14384 */ 14385 rq_unpin_lock(this_rq, rf); 14386 14387 sd = rcu_dereference_sched_domain(this_rq->sd); 14388 if (!sd) 14389 goto out; 14390 14391 if (!get_rd_overloaded(this_rq->rd) || 14392 this_rq->avg_idle < sd->max_newidle_lb_cost) { 14393 14394 update_next_balance(sd, &next_balance); 14395 goto out; 14396 } 14397 14398 /* 14399 * Include sched_balance_update_blocked_averages() in the cost 14400 * calculation because it can be quite costly -- this ensures we skip 14401 * it when avg_idle gets to be very low. 14402 */ 14403 t0 = sched_clock_cpu(this_cpu); 14404 __sched_balance_update_blocked_averages(this_rq); 14405 14406 rq_modified_begin(this_rq, &fair_sched_class); 14407 raw_spin_rq_unlock(this_rq); 14408 14409 for_each_domain(this_cpu, sd) { 14410 u64 domain_cost; 14411 14412 update_next_balance(sd, &next_balance); 14413 14414 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) 14415 break; 14416 14417 if (sd->flags & SD_BALANCE_NEWIDLE) { 14418 unsigned int weight = 1; 14419 14420 if (sched_feat(NI_RANDOM) && sd->newidle_ratio < 1024) { 14421 /* 14422 * Throw a 1k sided dice; and only run 14423 * newidle_balance according to the success 14424 * rate. 14425 */ 14426 u32 d1k = sched_rng() % 1024; 14427 weight = 1 + sd->newidle_ratio; 14428 if (d1k > weight) { 14429 update_newidle_stats(sd, 0); 14430 continue; 14431 } 14432 weight = (1024 + weight/2) / weight; 14433 } 14434 14435 pulled_task = sched_balance_rq(this_cpu, this_rq, 14436 sd, CPU_NEWLY_IDLE, 14437 &continue_balancing); 14438 14439 t1 = sched_clock_cpu(this_cpu); 14440 domain_cost = t1 - t0; 14441 curr_cost += domain_cost; 14442 t0 = t1; 14443 14444 /* 14445 * Track max cost of a domain to make sure to not delay the 14446 * next wakeup on the CPU. 14447 */ 14448 update_newidle_cost(sd, domain_cost, weight * !!pulled_task); 14449 } 14450 14451 /* 14452 * Stop searching for tasks to pull if there are 14453 * now runnable tasks on this rq. 14454 */ 14455 if (pulled_task || !continue_balancing) 14456 break; 14457 } 14458 14459 raw_spin_rq_lock(this_rq); 14460 14461 if (curr_cost > this_rq->max_idle_balance_cost) 14462 this_rq->max_idle_balance_cost = curr_cost; 14463 14464 /* 14465 * While browsing the domains, we released the rq lock, a task could 14466 * have been enqueued in the meantime. Since we're not going idle, 14467 * pretend we pulled a task. 14468 */ 14469 if (this_rq->cfs.h_nr_queued && !pulled_task) 14470 pulled_task = 1; 14471 14472 /* If a higher prio class was modified, restart the pick */ 14473 if (rq_modified_above(this_rq, &fair_sched_class)) 14474 pulled_task = -1; 14475 14476 out: 14477 /* Move the next balance forward */ 14478 if (time_after(this_rq->next_balance, next_balance)) 14479 this_rq->next_balance = next_balance; 14480 14481 if (pulled_task) 14482 this_rq->idle_stamp = 0; 14483 else 14484 nohz_newidle_balance(this_rq); 14485 14486 rq_repin_lock(this_rq, rf); 14487 14488 return pulled_task; 14489 } 14490 14491 /* 14492 * This softirq handler is triggered via SCHED_SOFTIRQ from two places: 14493 * 14494 * - directly from the local sched_tick() for periodic load balancing 14495 * 14496 * - indirectly from a remote sched_tick() for NOHZ idle balancing 14497 * through the SMP cross-call nohz_csd_func() 14498 */ 14499 static __latent_entropy void sched_balance_softirq(void) 14500 { 14501 struct rq *this_rq = this_rq(); 14502 enum cpu_idle_type idle = this_rq->idle_balance; 14503 /* 14504 * If this CPU has a pending NOHZ_BALANCE_KICK, then do the 14505 * balancing on behalf of the other idle CPUs whose ticks are 14506 * stopped. Do nohz_idle_balance *before* sched_balance_domains to 14507 * give the idle CPUs a chance to load balance. Else we may 14508 * load balance only within the local sched_domain hierarchy 14509 * and abort nohz_idle_balance altogether if we pull some load. 14510 */ 14511 if (nohz_idle_balance(this_rq, idle)) 14512 return; 14513 14514 /* normal load balance */ 14515 sched_balance_update_blocked_averages(this_rq->cpu); 14516 sched_balance_domains(this_rq, idle); 14517 } 14518 14519 /* 14520 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing. 14521 */ 14522 void sched_balance_trigger(struct rq *rq) 14523 { 14524 /* 14525 * Don't need to rebalance while attached to NULL domain or 14526 * runqueue CPU is not active 14527 */ 14528 if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq)))) 14529 return; 14530 14531 if (time_after_eq(jiffies, rq->next_balance)) 14532 raise_softirq(SCHED_SOFTIRQ); 14533 14534 nohz_balancer_kick(rq); 14535 } 14536 14537 static void rq_online_fair(struct rq *rq) 14538 { 14539 update_sysctl(); 14540 14541 update_runtime_enabled(rq); 14542 } 14543 14544 static void rq_offline_fair(struct rq *rq) 14545 { 14546 update_sysctl(); 14547 14548 /* Ensure any throttled groups are reachable by pick_next_task */ 14549 unthrottle_offline_cfs_rqs(rq); 14550 14551 /* Ensure that we remove rq contribution to group share: */ 14552 clear_tg_offline_cfs_rqs(rq); 14553 } 14554 14555 #ifdef CONFIG_SCHED_CORE 14556 static inline bool 14557 __entity_slice_used(struct sched_entity *se, int min_nr_tasks) 14558 { 14559 u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime; 14560 u64 slice = se->slice; 14561 14562 return (rtime * min_nr_tasks > slice); 14563 } 14564 14565 #define MIN_NR_TASKS_DURING_FORCEIDLE 2 14566 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) 14567 { 14568 if (!sched_core_enabled(rq)) 14569 return; 14570 14571 /* 14572 * If runqueue has only one task which used up its slice and 14573 * if the sibling is forced idle, then trigger schedule to 14574 * give forced idle task a chance. 14575 * 14576 * sched_slice() considers only this active rq and it gets the 14577 * whole slice. But during force idle, we have siblings acting 14578 * like a single runqueue and hence we need to consider runnable 14579 * tasks on this CPU and the forced idle CPU. Ideally, we should 14580 * go through the forced idle rq, but that would be a perf hit. 14581 * We can assume that the forced idle CPU has at least 14582 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check 14583 * if we need to give up the CPU. 14584 */ 14585 if (rq->core->core_forceidle_count && rq->cfs.nr_queued == 1 && 14586 __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE)) 14587 resched_curr(rq); 14588 } 14589 14590 /* 14591 * Consider any infeasible weight scenario. Take for instance two tasks, 14592 * each bound to their respective sibling, one with weight 1 and one with 14593 * weight 2. Then the lower weight task will run ahead of the higher weight 14594 * task without bound. 14595 * 14596 * This utterly destroys the concept of a shared time base. 14597 * 14598 * Remember; all this is about a proportionally fair scheduling, where each 14599 * tasks receives: 14600 * 14601 * w_i 14602 * dt_i = ---------- dt (1) 14603 * \Sum_j w_j 14604 * 14605 * which we do by tracking a virtual time, s_i: 14606 * 14607 * 1 14608 * s_i = --- d[t]_i (2) 14609 * w_i 14610 * 14611 * Where d[t] is a delta of discrete time, while dt is an infinitesimal. 14612 * The immediate corollary is that the ideal schedule S, where (2) to use 14613 * an infinitesimal delta, is: 14614 * 14615 * 1 14616 * S = ---------- dt (3) 14617 * \Sum_i w_i 14618 * 14619 * From which we can define the lag, or deviation from the ideal, as: 14620 * 14621 * lag(i) = S - s_i (4) 14622 * 14623 * And since the one and only purpose is to approximate S, we get that: 14624 * 14625 * \Sum_i w_i lag(i) := 0 (5) 14626 * 14627 * If this were not so, we no longer converge to S, and we can no longer 14628 * claim our scheduler has any of the properties we derive from S. This is 14629 * exactly what you did above, you broke it! 14630 * 14631 * 14632 * Let's continue for a while though; to see if there is anything useful to 14633 * be learned. We can combine (1)-(3) or (4)-(5) and express S in s_i: 14634 * 14635 * \Sum_i w_i s_i 14636 * S = -------------- (6) 14637 * \Sum_i w_i 14638 * 14639 * Which gives us a way to compute S, given our s_i. Now, if you've read 14640 * our code, you know that we do not in fact do this, the reason for this 14641 * is two-fold. Firstly, computing S in that way requires a 64bit division 14642 * for every time we'd use it (see 12), and secondly, this only describes 14643 * the steady-state, it doesn't handle dynamics. 14644 * 14645 * Anyway, in (6): s_i -> x + (s_i - x), to get: 14646 * 14647 * \Sum_i w_i (s_i - x) 14648 * S - x = -------------------- (7) 14649 * \Sum_i w_i 14650 * 14651 * Which shows that S and s_i transform alike (which makes perfect sense 14652 * given that S is basically the (weighted) average of s_i). 14653 * 14654 * So the thing to remember is that the above is strictly UP. It is 14655 * possible to generalize to multiple runqueues -- however it gets really 14656 * yuck when you have to add affinity support, as illustrated by our very 14657 * first counter-example. 14658 * 14659 * Luckily I think we can avoid needing a full multi-queue variant for 14660 * core-scheduling (or load-balancing). The crucial observation is that we 14661 * only actually need this comparison in the presence of forced-idle; only 14662 * then do we need to tell if the stalled rq has higher priority over the 14663 * other. 14664 * 14665 * [XXX assumes SMT2; better consider the more general case, I suspect 14666 * it'll work out because our comparison is always between 2 rqs and the 14667 * answer is only interesting if one of them is forced-idle] 14668 * 14669 * And (under assumption of SMT2) when there is forced-idle, there is only 14670 * a single queue, so everything works like normal. 14671 * 14672 * Let, for our runqueue 'k': 14673 * 14674 * T_k = \Sum_i w_i s_i 14675 * W_k = \Sum_i w_i ; for all i of k (8) 14676 * 14677 * Then we can write (6) like: 14678 * 14679 * T_k 14680 * S_k = --- (9) 14681 * W_k 14682 * 14683 * From which immediately follows that: 14684 * 14685 * T_k + T_l 14686 * S_k+l = --------- (10) 14687 * W_k + W_l 14688 * 14689 * On which we can define a combined lag: 14690 * 14691 * lag_k+l(i) := S_k+l - s_i (11) 14692 * 14693 * And that gives us the tools to compare tasks across a combined runqueue. 14694 * 14695 * 14696 * Combined this gives the following: 14697 * 14698 * a) when a runqueue enters force-idle, sync it against it's sibling rq(s) 14699 * using (7); this only requires storing single 'time'-stamps. 14700 * 14701 * b) when comparing tasks between 2 runqueues of which one is forced-idle, 14702 * compare the combined lag, per (11). 14703 * 14704 * Now, of course cgroups (I so hate them) make this more interesting in 14705 * that a) seems to suggest we need to iterate all cgroup on a CPU at such 14706 * boundaries, but I think we can avoid that. The force-idle is for the 14707 * whole CPU, all it's rqs. So we can mark it in the root and lazily 14708 * propagate downward on demand. 14709 */ 14710 14711 /* 14712 * So this sync is basically a relative reset of S to 0. 14713 * 14714 * So with 2 queues, when one goes idle, we drop them both to 0 and one 14715 * then increases due to not being idle, and the idle one builds up lag to 14716 * get re-elected. So far so simple, right? 14717 * 14718 * When there's 3, we can have the situation where 2 run and one is idle, 14719 * we sync to 0 and let the idle one build up lag to get re-election. Now 14720 * suppose another one also drops idle. At this point dropping all to 0 14721 * again would destroy the built-up lag from the queue that was already 14722 * idle, not good. 14723 * 14724 * So instead of syncing everything, we can: 14725 * 14726 * less := !((s64)(s_a - s_b) <= 0) 14727 * 14728 * (v_a - S_a) - (v_b - S_b) == v_a - v_b - S_a + S_b 14729 * == v_a - (v_b - S_a + S_b) 14730 * 14731 * IOW, we can recast the (lag) comparison to a one-sided difference. 14732 * So if then, instead of syncing the whole queue, sync the idle queue 14733 * against the active queue with S_a + S_b at the point where we sync. 14734 * 14735 * (XXX consider the implication of living in a cyclic group: N / 2^n N) 14736 * 14737 * This gives us means of syncing single queues against the active queue, 14738 * and for already idle queues to preserve their build-up lag. 14739 * 14740 * Of course, then we get the situation where there's 2 active and one 14741 * going idle, who do we pick to sync against? Theory would have us sync 14742 * against the combined S, but as we've already demonstrated, there is no 14743 * such thing in infeasible weight scenarios. 14744 * 14745 * One thing I've considered; and this is where that core_active rudiment 14746 * came from, is having active queues sync up between themselves after 14747 * every tick. This limits the observed divergence due to the work 14748 * conservancy. 14749 * 14750 * On top of that, we can improve upon things by employing (10) here. 14751 */ 14752 14753 /* 14754 * se_fi_update - Update the cfs_rq->zero_vruntime_fi in a CFS hierarchy if needed. 14755 */ 14756 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq, 14757 bool forceidle) 14758 { 14759 for_each_sched_entity(se) { 14760 struct cfs_rq *cfs_rq = cfs_rq_of(se); 14761 14762 if (forceidle) { 14763 if (cfs_rq->forceidle_seq == fi_seq) 14764 break; 14765 cfs_rq->forceidle_seq = fi_seq; 14766 } 14767 14768 cfs_rq->zero_vruntime_fi = cfs_rq->zero_vruntime; 14769 } 14770 } 14771 14772 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi) 14773 { 14774 struct sched_entity *se = &p->se; 14775 14776 if (p->sched_class != &fair_sched_class) 14777 return; 14778 14779 se_fi_update(se, rq->core->core_forceidle_seq, in_fi); 14780 } 14781 14782 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b, 14783 bool in_fi) 14784 { 14785 struct rq *rq = task_rq(a); 14786 const struct sched_entity *sea = &a->se; 14787 const struct sched_entity *seb = &b->se; 14788 struct cfs_rq *cfs_rqa; 14789 struct cfs_rq *cfs_rqb; 14790 s64 delta; 14791 14792 WARN_ON_ONCE(task_rq(b)->core != rq->core); 14793 14794 #ifdef CONFIG_FAIR_GROUP_SCHED 14795 /* 14796 * Find an se in the hierarchy for tasks a and b, such that the se's 14797 * are immediate siblings. 14798 */ 14799 while (sea->cfs_rq->tg != seb->cfs_rq->tg) { 14800 int sea_depth = sea->depth; 14801 int seb_depth = seb->depth; 14802 14803 if (sea_depth >= seb_depth) 14804 sea = parent_entity(sea); 14805 if (sea_depth <= seb_depth) 14806 seb = parent_entity(seb); 14807 } 14808 14809 se_fi_update(sea, rq->core->core_forceidle_seq, in_fi); 14810 se_fi_update(seb, rq->core->core_forceidle_seq, in_fi); 14811 14812 cfs_rqa = sea->cfs_rq; 14813 cfs_rqb = seb->cfs_rq; 14814 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 14815 cfs_rqa = &task_rq(a)->cfs; 14816 cfs_rqb = &task_rq(b)->cfs; 14817 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 14818 14819 /* 14820 * Find delta after normalizing se's vruntime with its cfs_rq's 14821 * zero_vruntime_fi, which would have been updated in prior calls 14822 * to se_fi_update(). 14823 */ 14824 delta = vruntime_op(sea->vruntime, "-", seb->vruntime) + 14825 vruntime_op(cfs_rqb->zero_vruntime_fi, "-", cfs_rqa->zero_vruntime_fi); 14826 14827 return delta > 0; 14828 } 14829 14830 static int task_is_throttled_fair(struct task_struct *p, int cpu) 14831 { 14832 struct cfs_rq *cfs_rq; 14833 14834 #ifdef CONFIG_FAIR_GROUP_SCHED 14835 cfs_rq = tg_cfs_rq(task_group(p), cpu); 14836 #else 14837 cfs_rq = &cpu_rq(cpu)->cfs; 14838 #endif 14839 return throttled_hierarchy(cfs_rq); 14840 } 14841 #else /* !CONFIG_SCHED_CORE: */ 14842 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {} 14843 #endif /* !CONFIG_SCHED_CORE */ 14844 14845 /* 14846 * scheduler tick hitting a task of our scheduling class. 14847 * 14848 * NOTE: This function can be called remotely by the tick offload that 14849 * goes along full dynticks. Therefore no local assumption can be made 14850 * and everything must be accessed through the @rq and @curr passed in 14851 * parameters. 14852 */ 14853 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued) 14854 { 14855 struct sched_entity *se = &curr->se; 14856 struct cfs_rq *cfs_rq; 14857 14858 for_each_sched_entity(se) { 14859 cfs_rq = cfs_rq_of(se); 14860 entity_tick(cfs_rq, se, queued); 14861 } 14862 14863 if (queued) 14864 return; 14865 14866 if (static_branch_unlikely(&sched_numa_balancing)) 14867 task_tick_numa(rq, curr); 14868 14869 task_tick_cache(rq, curr); 14870 14871 update_misfit_status(curr, rq); 14872 check_update_overutilized_status(task_rq(curr)); 14873 14874 task_tick_core(rq, curr); 14875 } 14876 14877 /* 14878 * called on fork with the child task as argument from the parent's context 14879 * - child not yet on the tasklist 14880 * - preemption disabled 14881 */ 14882 static void task_fork_fair(struct task_struct *p) 14883 { 14884 set_task_max_allowed_capacity(p); 14885 } 14886 14887 /* 14888 * Priority of the task has changed. Check to see if we preempt 14889 * the current task. 14890 */ 14891 static void 14892 prio_changed_fair(struct rq *rq, struct task_struct *p, u64 oldprio) 14893 { 14894 if (!task_on_rq_queued(p)) 14895 return; 14896 14897 if (p->prio == oldprio) 14898 return; 14899 14900 if (rq->cfs.nr_queued == 1) 14901 return; 14902 14903 /* 14904 * Reschedule if we are currently running on this runqueue and 14905 * our priority decreased, or if we are not currently running on 14906 * this runqueue and our priority is higher than the current's 14907 */ 14908 if (task_current_donor(rq, p)) { 14909 if (p->prio > oldprio) 14910 resched_curr(rq); 14911 } else { 14912 wakeup_preempt(rq, p, 0); 14913 } 14914 } 14915 14916 #ifdef CONFIG_FAIR_GROUP_SCHED 14917 /* 14918 * Propagate the changes of the sched_entity across the tg tree to make it 14919 * visible to the root 14920 */ 14921 static void propagate_entity_cfs_rq(struct sched_entity *se) 14922 { 14923 struct cfs_rq *cfs_rq = cfs_rq_of(se); 14924 14925 /* 14926 * If a task gets attached to this cfs_rq and before being queued, 14927 * it gets migrated to another CPU due to reasons like affinity 14928 * change, make sure this cfs_rq stays on leaf cfs_rq list to have 14929 * that removed load decayed or it can cause faireness problem. 14930 */ 14931 if (!cfs_rq_pelt_clock_throttled(cfs_rq)) 14932 list_add_leaf_cfs_rq(cfs_rq); 14933 14934 /* Start to propagate at parent */ 14935 se = se->parent; 14936 14937 for_each_sched_entity(se) { 14938 cfs_rq = cfs_rq_of(se); 14939 14940 update_load_avg(cfs_rq, se, UPDATE_TG); 14941 14942 if (!cfs_rq_pelt_clock_throttled(cfs_rq)) 14943 list_add_leaf_cfs_rq(cfs_rq); 14944 } 14945 14946 assert_list_leaf_cfs_rq(rq_of(cfs_rq)); 14947 } 14948 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 14949 static void propagate_entity_cfs_rq(struct sched_entity *se) { } 14950 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 14951 14952 static void detach_entity_cfs_rq(struct sched_entity *se) 14953 { 14954 struct cfs_rq *cfs_rq = cfs_rq_of(se); 14955 14956 /* 14957 * In case the task sched_avg hasn't been attached: 14958 * - A forked task which hasn't been woken up by wake_up_new_task(). 14959 * - A task which has been woken up by try_to_wake_up() but is 14960 * waiting for actually being woken up by sched_ttwu_pending(). 14961 */ 14962 if (!se->avg.last_update_time) 14963 return; 14964 14965 /* Catch up with the cfs_rq and remove our load when we leave */ 14966 update_load_avg(cfs_rq, se, 0); 14967 detach_entity_load_avg(cfs_rq, se); 14968 update_tg_load_avg(cfs_rq); 14969 propagate_entity_cfs_rq(se); 14970 } 14971 14972 static void attach_entity_cfs_rq(struct sched_entity *se) 14973 { 14974 struct cfs_rq *cfs_rq = cfs_rq_of(se); 14975 14976 /* Synchronize entity with its cfs_rq */ 14977 update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD); 14978 attach_entity_load_avg(cfs_rq, se); 14979 update_tg_load_avg(cfs_rq); 14980 propagate_entity_cfs_rq(se); 14981 } 14982 14983 static void detach_task_cfs_rq(struct task_struct *p) 14984 { 14985 struct sched_entity *se = &p->se; 14986 14987 detach_entity_cfs_rq(se); 14988 } 14989 14990 static void attach_task_cfs_rq(struct task_struct *p) 14991 { 14992 struct sched_entity *se = &p->se; 14993 14994 attach_entity_cfs_rq(se); 14995 } 14996 14997 static void switching_from_fair(struct rq *rq, struct task_struct *p) 14998 { 14999 if (p->se.sched_delayed) 15000 dequeue_task(rq, p, DEQUEUE_SLEEP | DEQUEUE_DELAYED | DEQUEUE_NOCLOCK); 15001 } 15002 15003 static void switched_from_fair(struct rq *rq, struct task_struct *p) 15004 { 15005 detach_task_cfs_rq(p); 15006 } 15007 15008 static void switched_to_fair(struct rq *rq, struct task_struct *p) 15009 { 15010 WARN_ON_ONCE(p->se.sched_delayed); 15011 15012 attach_task_cfs_rq(p); 15013 15014 set_task_max_allowed_capacity(p); 15015 15016 if (task_on_rq_queued(p)) { 15017 /* 15018 * We were most likely switched from sched_rt, so 15019 * kick off the schedule if running, otherwise just see 15020 * if we can still preempt the current task. 15021 */ 15022 if (task_current_donor(rq, p)) 15023 resched_curr(rq); 15024 else 15025 wakeup_preempt(rq, p, 0); 15026 } 15027 } 15028 15029 /* 15030 * Account for a task changing its policy or group. 15031 * 15032 * This routine is mostly called to set cfs_rq->curr field when a task 15033 * migrates between groups/classes. 15034 */ 15035 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first) 15036 { 15037 struct sched_entity *se = &p->se; 15038 bool throttled = false; 15039 15040 for_each_sched_entity(se) { 15041 struct cfs_rq *cfs_rq = cfs_rq_of(se); 15042 15043 if (IS_ENABLED(CONFIG_FAIR_GROUP_SCHED) && 15044 first && cfs_rq->curr) 15045 break; 15046 15047 set_next_entity(cfs_rq, se, first); 15048 /* ensure bandwidth has been allocated on our new cfs_rq */ 15049 throttled |= account_cfs_rq_runtime(cfs_rq, 0); 15050 } 15051 15052 if (throttled) 15053 task_throttle_setup_work(p); 15054 15055 se = &p->se; 15056 15057 if (task_on_rq_queued(p)) { 15058 /* 15059 * Move the next running task to the front of the list, so our 15060 * cfs_tasks list becomes MRU one. 15061 */ 15062 list_move(&se->group_node, &rq->cfs_tasks); 15063 } 15064 if (!first) 15065 return; 15066 15067 WARN_ON_ONCE(se->sched_delayed); 15068 15069 if (hrtick_enabled_fair(rq)) 15070 hrtick_start_fair(rq, p); 15071 15072 update_misfit_status(p, rq); 15073 sched_fair_update_stop_tick(rq, p); 15074 } 15075 15076 void init_cfs_rq(struct cfs_rq *cfs_rq) 15077 { 15078 cfs_rq->tasks_timeline = RB_ROOT_CACHED; 15079 cfs_rq->zero_vruntime = (u64)(-(1LL << 20)); 15080 raw_spin_lock_init(&cfs_rq->removed.lock); 15081 } 15082 15083 #ifdef CONFIG_FAIR_GROUP_SCHED 15084 static void task_change_group_fair(struct task_struct *p) 15085 { 15086 /* 15087 * We couldn't detach or attach a forked task which 15088 * hasn't been woken up by wake_up_new_task(). 15089 */ 15090 if (READ_ONCE(p->__state) == TASK_NEW) 15091 return; 15092 15093 detach_task_cfs_rq(p); 15094 15095 /* Tell se's cfs_rq has been changed -- migrated */ 15096 p->se.avg.last_update_time = 0; 15097 set_task_rq(p, task_cpu(p)); 15098 attach_task_cfs_rq(p); 15099 } 15100 15101 void free_fair_sched_group(struct task_group *tg) 15102 { 15103 free_percpu(tg->cfs_rq); 15104 } 15105 15106 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent) 15107 { 15108 struct cfs_tg_state __percpu *state; 15109 struct sched_entity *se; 15110 struct cfs_rq *cfs_rq; 15111 int i; 15112 15113 state = alloc_percpu_gfp(struct cfs_tg_state, GFP_KERNEL); 15114 if (!state) 15115 goto err; 15116 15117 tg->cfs_rq = &state->cfs_rq; 15118 tg->shares = NICE_0_LOAD; 15119 15120 init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent)); 15121 15122 for_each_possible_cpu(i) { 15123 cfs_rq = tg_cfs_rq(tg, i); 15124 if (!cfs_rq) 15125 goto err; 15126 15127 se = tg_se(tg, i); 15128 init_cfs_rq(cfs_rq); 15129 init_tg_cfs_entry(tg, cfs_rq, se, i, tg_se(parent, i)); 15130 init_entity_runnable_average(se); 15131 } 15132 15133 return 1; 15134 15135 err: 15136 return 0; 15137 } 15138 15139 void online_fair_sched_group(struct task_group *tg) 15140 { 15141 struct sched_entity *se; 15142 struct rq_flags rf; 15143 struct rq *rq; 15144 int i; 15145 15146 for_each_possible_cpu(i) { 15147 rq = cpu_rq(i); 15148 se = tg_se(tg, i); 15149 rq_lock_irq(rq, &rf); 15150 update_rq_clock(rq); 15151 attach_entity_cfs_rq(se); 15152 sync_throttle(tg, i); 15153 rq_unlock_irq(rq, &rf); 15154 } 15155 } 15156 15157 void unregister_fair_sched_group(struct task_group *tg) 15158 { 15159 int cpu; 15160 15161 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg)); 15162 15163 for_each_possible_cpu(cpu) { 15164 struct cfs_rq *cfs_rq = tg_cfs_rq(tg, cpu); 15165 struct sched_entity *se = tg_se(tg, cpu); 15166 struct rq *rq = cpu_rq(cpu); 15167 15168 if (se) { 15169 if (se->sched_delayed) { 15170 guard(rq_lock_irqsave)(rq); 15171 if (se->sched_delayed) { 15172 update_rq_clock(rq); 15173 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED); 15174 } 15175 list_del_leaf_cfs_rq(cfs_rq); 15176 } 15177 remove_entity_load_avg(se); 15178 } 15179 15180 /* 15181 * Only empty task groups can be destroyed; so we can speculatively 15182 * check on_list without danger of it being re-added. 15183 */ 15184 if (cfs_rq->on_list) { 15185 guard(rq_lock_irqsave)(rq); 15186 list_del_leaf_cfs_rq(cfs_rq); 15187 } 15188 } 15189 } 15190 15191 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq, 15192 struct sched_entity *se, int cpu, 15193 struct sched_entity *parent) 15194 { 15195 struct rq *rq = cpu_rq(cpu); 15196 15197 cfs_rq->tg = tg; 15198 cfs_rq->rq = rq; 15199 init_cfs_rq_runtime(cfs_rq); 15200 15201 /* se could be NULL for root_task_group */ 15202 if (!se) 15203 return; 15204 15205 if (!parent) { 15206 se->cfs_rq = &rq->cfs; 15207 se->depth = 0; 15208 } else { 15209 se->cfs_rq = parent->my_q; 15210 se->depth = parent->depth + 1; 15211 } 15212 15213 se->my_q = cfs_rq; 15214 /* guarantee group entities always have weight */ 15215 update_load_set(&se->load, NICE_0_LOAD); 15216 se->parent = parent; 15217 } 15218 15219 static DEFINE_MUTEX(shares_mutex); 15220 15221 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares) 15222 { 15223 int i; 15224 15225 lockdep_assert_held(&shares_mutex); 15226 15227 /* 15228 * We can't change the weight of the root cgroup. 15229 */ 15230 if (is_root_task_group(tg)) 15231 return -EINVAL; 15232 15233 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES)); 15234 15235 if (tg->shares == shares) 15236 return 0; 15237 15238 tg->shares = shares; 15239 for_each_possible_cpu(i) { 15240 struct rq *rq = cpu_rq(i); 15241 struct sched_entity *se = tg_se(tg, i); 15242 struct rq_flags rf; 15243 15244 /* Propagate contribution to hierarchy */ 15245 rq_lock_irqsave(rq, &rf); 15246 update_rq_clock(rq); 15247 for_each_sched_entity(se) { 15248 update_load_avg(cfs_rq_of(se), se, UPDATE_TG); 15249 update_cfs_group(se); 15250 } 15251 rq_unlock_irqrestore(rq, &rf); 15252 } 15253 15254 return 0; 15255 } 15256 15257 int sched_group_set_shares(struct task_group *tg, unsigned long shares) 15258 { 15259 int ret; 15260 15261 mutex_lock(&shares_mutex); 15262 if (tg_is_idle(tg)) 15263 ret = -EINVAL; 15264 else 15265 ret = __sched_group_set_shares(tg, shares); 15266 mutex_unlock(&shares_mutex); 15267 15268 return ret; 15269 } 15270 15271 int sched_group_set_idle(struct task_group *tg, long idle) 15272 { 15273 int i; 15274 15275 if (tg == &root_task_group) 15276 return -EINVAL; 15277 15278 if (idle < 0 || idle > 1) 15279 return -EINVAL; 15280 15281 mutex_lock(&shares_mutex); 15282 15283 if (tg->idle == idle) { 15284 mutex_unlock(&shares_mutex); 15285 return 0; 15286 } 15287 15288 tg->idle = idle; 15289 15290 for_each_possible_cpu(i) { 15291 struct rq *rq = cpu_rq(i); 15292 struct sched_entity *se = tg_se(tg, i); 15293 struct cfs_rq *grp_cfs_rq = tg_cfs_rq(tg, i); 15294 bool was_idle = cfs_rq_is_idle(grp_cfs_rq); 15295 long idle_task_delta; 15296 struct rq_flags rf; 15297 15298 rq_lock_irqsave(rq, &rf); 15299 15300 grp_cfs_rq->idle = idle; 15301 if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq))) 15302 goto next_cpu; 15303 15304 idle_task_delta = grp_cfs_rq->h_nr_queued - 15305 grp_cfs_rq->h_nr_idle; 15306 if (!cfs_rq_is_idle(grp_cfs_rq)) 15307 idle_task_delta *= -1; 15308 15309 for_each_sched_entity(se) { 15310 struct cfs_rq *cfs_rq = cfs_rq_of(se); 15311 15312 if (!se->on_rq) 15313 break; 15314 15315 cfs_rq->h_nr_idle += idle_task_delta; 15316 15317 /* Already accounted at parent level and above. */ 15318 if (cfs_rq_is_idle(cfs_rq)) 15319 break; 15320 } 15321 15322 next_cpu: 15323 rq_unlock_irqrestore(rq, &rf); 15324 } 15325 15326 /* Idle groups have minimum weight. */ 15327 if (tg_is_idle(tg)) 15328 __sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO)); 15329 else 15330 __sched_group_set_shares(tg, NICE_0_LOAD); 15331 15332 mutex_unlock(&shares_mutex); 15333 return 0; 15334 } 15335 15336 #endif /* CONFIG_FAIR_GROUP_SCHED */ 15337 15338 15339 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task) 15340 { 15341 struct sched_entity *se = &task->se; 15342 unsigned int rr_interval = 0; 15343 15344 /* 15345 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise 15346 * idle runqueue: 15347 */ 15348 if (rq->cfs.load.weight) 15349 rr_interval = NS_TO_JIFFIES(se->slice); 15350 15351 return rr_interval; 15352 } 15353 15354 /* 15355 * All the scheduling class methods: 15356 */ 15357 DEFINE_SCHED_CLASS(fair) = { 15358 .enqueue_task = enqueue_task_fair, 15359 .dequeue_task = dequeue_task_fair, 15360 .yield_task = yield_task_fair, 15361 .yield_to_task = yield_to_task_fair, 15362 15363 .wakeup_preempt = wakeup_preempt_fair, 15364 15365 .pick_task = pick_task_fair, 15366 .put_prev_task = put_prev_task_fair, 15367 .set_next_task = set_next_task_fair, 15368 15369 .select_task_rq = select_task_rq_fair, 15370 .migrate_task_rq = migrate_task_rq_fair, 15371 15372 .rq_online = rq_online_fair, 15373 .rq_offline = rq_offline_fair, 15374 15375 .task_dead = task_dead_fair, 15376 .set_cpus_allowed = set_cpus_allowed_fair, 15377 15378 .task_tick = task_tick_fair, 15379 .task_fork = task_fork_fair, 15380 15381 .reweight_task = reweight_task_fair, 15382 .prio_changed = prio_changed_fair, 15383 .switching_from = switching_from_fair, 15384 .switched_from = switched_from_fair, 15385 .switched_to = switched_to_fair, 15386 15387 .get_rr_interval = get_rr_interval_fair, 15388 15389 .update_curr = update_curr_fair, 15390 15391 #ifdef CONFIG_FAIR_GROUP_SCHED 15392 .task_change_group = task_change_group_fair, 15393 #endif 15394 15395 #ifdef CONFIG_SCHED_CORE 15396 .task_is_throttled = task_is_throttled_fair, 15397 #endif 15398 15399 #ifdef CONFIG_UCLAMP_TASK 15400 .uclamp_enabled = 1, 15401 #endif 15402 }; 15403 15404 void print_cfs_stats(struct seq_file *m, int cpu) 15405 { 15406 struct cfs_rq *cfs_rq, *pos; 15407 15408 rcu_read_lock(); 15409 for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos) 15410 print_cfs_rq(m, cpu, cfs_rq); 15411 rcu_read_unlock(); 15412 } 15413 15414 #ifdef CONFIG_NUMA_BALANCING 15415 void show_numa_stats(struct task_struct *p, struct seq_file *m) 15416 { 15417 int node; 15418 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0; 15419 struct numa_group *ng; 15420 15421 rcu_read_lock(); 15422 ng = rcu_dereference_all(p->numa_group); 15423 for_each_online_node(node) { 15424 if (p->numa_faults) { 15425 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)]; 15426 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)]; 15427 } 15428 if (ng) { 15429 gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)]; 15430 gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)]; 15431 } 15432 print_numa_stats(m, node, tsf, tpf, gsf, gpf); 15433 } 15434 rcu_read_unlock(); 15435 } 15436 #endif /* CONFIG_NUMA_BALANCING */ 15437 15438 __init void init_sched_fair_class(void) 15439 { 15440 int i; 15441 15442 for_each_possible_cpu(i) { 15443 zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i)); 15444 zalloc_cpumask_var_node(&per_cpu(select_rq_mask, i), GFP_KERNEL, cpu_to_node(i)); 15445 zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i), 15446 GFP_KERNEL, cpu_to_node(i)); 15447 15448 #ifdef CONFIG_CFS_BANDWIDTH 15449 INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i)); 15450 INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list); 15451 #endif 15452 } 15453 15454 open_softirq(SCHED_SOFTIRQ, sched_balance_softirq); 15455 15456 #ifdef CONFIG_NO_HZ_COMMON 15457 nohz.next_balance = jiffies; 15458 nohz.next_blocked = jiffies; 15459 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT); 15460 #endif 15461 } 15462