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 cfs_rq->tg->parent->cfs_rq[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 &(cfs_rq->tg->parent->cfs_rq[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 void 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 s64 update_se(struct rq *rq, struct sched_entity *se) 1354 { 1355 u64 now = rq_clock_task(rq); 1356 s64 delta_exec; 1357 1358 delta_exec = now - se->exec_start; 1359 if (unlikely(delta_exec <= 0)) 1360 return delta_exec; 1361 1362 se->exec_start = now; 1363 if (entity_is_task(se)) { 1364 struct task_struct *donor = task_of(se); 1365 struct task_struct *running = rq->curr; 1366 /* 1367 * If se is a task, we account the time against the running 1368 * task, as w/ proxy-exec they may not be the same. 1369 */ 1370 running->se.exec_start = now; 1371 running->se.sum_exec_runtime += delta_exec; 1372 1373 trace_sched_stat_runtime(running, delta_exec); 1374 account_group_exec_runtime(running, delta_exec); 1375 1376 /* cgroup time is always accounted against the donor */ 1377 cgroup_account_cputime(donor, delta_exec); 1378 } else { 1379 /* If not task, account the time against donor se */ 1380 se->sum_exec_runtime += delta_exec; 1381 } 1382 1383 if (schedstat_enabled()) { 1384 struct sched_statistics *stats; 1385 1386 stats = __schedstats_from_se(se); 1387 __schedstat_set(stats->exec_max, 1388 max(delta_exec, stats->exec_max)); 1389 } 1390 1391 return delta_exec; 1392 } 1393 1394 static void set_next_buddy(struct sched_entity *se); 1395 1396 /* 1397 * Used by other classes to account runtime. 1398 */ 1399 s64 update_curr_common(struct rq *rq) 1400 { 1401 return update_se(rq, &rq->donor->se); 1402 } 1403 1404 /* 1405 * Update the current task's runtime statistics. 1406 */ 1407 static void update_curr(struct cfs_rq *cfs_rq) 1408 { 1409 /* 1410 * Note: cfs_rq->curr corresponds to the task picked to 1411 * run (ie: rq->donor.se) which due to proxy-exec may 1412 * not necessarily be the actual task running 1413 * (rq->curr.se). This is easy to confuse! 1414 */ 1415 struct sched_entity *curr = cfs_rq->curr; 1416 struct rq *rq = rq_of(cfs_rq); 1417 s64 delta_exec; 1418 bool resched; 1419 1420 if (unlikely(!curr)) 1421 return; 1422 1423 delta_exec = update_se(rq, curr); 1424 if (unlikely(delta_exec <= 0)) 1425 return; 1426 1427 curr->vruntime += calc_delta_fair(delta_exec, curr); 1428 resched = update_deadline(cfs_rq, curr); 1429 1430 if (entity_is_task(curr)) { 1431 /* 1432 * If the fair_server is active, we need to account for the 1433 * fair_server time whether or not the task is running on 1434 * behalf of fair_server or not: 1435 * - If the task is running on behalf of fair_server, we need 1436 * to limit its time based on the assigned runtime. 1437 * - Fair task that runs outside of fair_server should account 1438 * against fair_server such that it can account for this time 1439 * and possibly avoid running this period. 1440 */ 1441 dl_server_update(&rq->fair_server, delta_exec); 1442 } 1443 1444 account_cfs_rq_runtime(cfs_rq, delta_exec); 1445 1446 if (cfs_rq->nr_queued == 1) 1447 return; 1448 1449 if (resched || !protect_slice(curr)) { 1450 resched_curr_lazy(rq); 1451 clear_buddies(cfs_rq, curr); 1452 } 1453 } 1454 1455 static void update_curr_fair(struct rq *rq) 1456 { 1457 update_curr(cfs_rq_of(&rq->donor->se)); 1458 } 1459 1460 static inline void 1461 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se) 1462 { 1463 struct sched_statistics *stats; 1464 struct task_struct *p = NULL; 1465 1466 if (!schedstat_enabled()) 1467 return; 1468 1469 stats = __schedstats_from_se(se); 1470 1471 if (entity_is_task(se)) 1472 p = task_of(se); 1473 1474 __update_stats_wait_start(rq_of(cfs_rq), p, stats); 1475 } 1476 1477 static inline void 1478 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se) 1479 { 1480 struct sched_statistics *stats; 1481 struct task_struct *p = NULL; 1482 1483 if (!schedstat_enabled()) 1484 return; 1485 1486 stats = __schedstats_from_se(se); 1487 1488 /* 1489 * When the sched_schedstat changes from 0 to 1, some sched se 1490 * maybe already in the runqueue, the se->statistics.wait_start 1491 * will be 0.So it will let the delta wrong. We need to avoid this 1492 * scenario. 1493 */ 1494 if (unlikely(!schedstat_val(stats->wait_start))) 1495 return; 1496 1497 if (entity_is_task(se)) 1498 p = task_of(se); 1499 1500 __update_stats_wait_end(rq_of(cfs_rq), p, stats); 1501 } 1502 1503 static inline void 1504 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se) 1505 { 1506 struct sched_statistics *stats; 1507 struct task_struct *tsk = NULL; 1508 1509 if (!schedstat_enabled()) 1510 return; 1511 1512 stats = __schedstats_from_se(se); 1513 1514 if (entity_is_task(se)) 1515 tsk = task_of(se); 1516 1517 __update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats); 1518 } 1519 1520 /* 1521 * Task is being enqueued - update stats: 1522 */ 1523 static inline void 1524 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 1525 { 1526 if (!schedstat_enabled()) 1527 return; 1528 1529 /* 1530 * Are we enqueueing a waiting task? (for current tasks 1531 * a dequeue/enqueue event is a NOP) 1532 */ 1533 if (se != cfs_rq->curr) 1534 update_stats_wait_start_fair(cfs_rq, se); 1535 1536 if (flags & ENQUEUE_WAKEUP) 1537 update_stats_enqueue_sleeper_fair(cfs_rq, se); 1538 } 1539 1540 static inline void 1541 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 1542 { 1543 1544 if (!schedstat_enabled()) 1545 return; 1546 1547 /* 1548 * Mark the end of the wait period if dequeueing a 1549 * waiting task: 1550 */ 1551 if (se != cfs_rq->curr) 1552 update_stats_wait_end_fair(cfs_rq, se); 1553 1554 if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) { 1555 struct task_struct *tsk = task_of(se); 1556 unsigned int state; 1557 1558 /* XXX racy against TTWU */ 1559 state = READ_ONCE(tsk->__state); 1560 if (state & TASK_INTERRUPTIBLE) 1561 __schedstat_set(tsk->stats.sleep_start, 1562 rq_clock(rq_of(cfs_rq))); 1563 if (state & TASK_UNINTERRUPTIBLE) 1564 __schedstat_set(tsk->stats.block_start, 1565 rq_clock(rq_of(cfs_rq))); 1566 } 1567 } 1568 1569 /* 1570 * We are picking a new current task - update its stats: 1571 */ 1572 static inline void 1573 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se) 1574 { 1575 /* 1576 * We are starting a new run period: 1577 */ 1578 se->exec_start = rq_clock_task(rq_of(cfs_rq)); 1579 } 1580 1581 /************************************************** 1582 * Scheduling class queueing methods: 1583 */ 1584 1585 static inline bool is_core_idle(int cpu) 1586 { 1587 #ifdef CONFIG_SCHED_SMT 1588 int sibling; 1589 1590 for_each_cpu(sibling, cpu_smt_mask(cpu)) { 1591 if (cpu == sibling) 1592 continue; 1593 1594 if (!idle_cpu(sibling)) 1595 return false; 1596 } 1597 #endif 1598 1599 return true; 1600 } 1601 1602 #ifdef CONFIG_NUMA 1603 #define NUMA_IMBALANCE_MIN 2 1604 1605 static inline long 1606 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr) 1607 { 1608 /* 1609 * Allow a NUMA imbalance if busy CPUs is less than the maximum 1610 * threshold. Above this threshold, individual tasks may be contending 1611 * for both memory bandwidth and any shared HT resources. This is an 1612 * approximation as the number of running tasks may not be related to 1613 * the number of busy CPUs due to sched_setaffinity. 1614 */ 1615 if (dst_running > imb_numa_nr) 1616 return imbalance; 1617 1618 /* 1619 * Allow a small imbalance based on a simple pair of communicating 1620 * tasks that remain local when the destination is lightly loaded. 1621 */ 1622 if (imbalance <= NUMA_IMBALANCE_MIN) 1623 return 0; 1624 1625 return imbalance; 1626 } 1627 #endif /* CONFIG_NUMA */ 1628 1629 #ifdef CONFIG_NUMA_BALANCING 1630 /* 1631 * Approximate time to scan a full NUMA task in ms. The task scan period is 1632 * calculated based on the tasks virtual memory size and 1633 * numa_balancing_scan_size. 1634 */ 1635 unsigned int sysctl_numa_balancing_scan_period_min = 1000; 1636 unsigned int sysctl_numa_balancing_scan_period_max = 60000; 1637 1638 /* Portion of address space to scan in MB */ 1639 unsigned int sysctl_numa_balancing_scan_size = 256; 1640 1641 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */ 1642 unsigned int sysctl_numa_balancing_scan_delay = 1000; 1643 1644 /* The page with hint page fault latency < threshold in ms is considered hot */ 1645 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC; 1646 1647 struct numa_group { 1648 refcount_t refcount; 1649 1650 spinlock_t lock; /* nr_tasks, tasks */ 1651 int nr_tasks; 1652 pid_t gid; 1653 int active_nodes; 1654 1655 struct rcu_head rcu; 1656 unsigned long total_faults; 1657 unsigned long max_faults_cpu; 1658 /* 1659 * faults[] array is split into two regions: faults_mem and faults_cpu. 1660 * 1661 * Faults_cpu is used to decide whether memory should move 1662 * towards the CPU. As a consequence, these stats are weighted 1663 * more by CPU use than by memory faults. 1664 */ 1665 unsigned long faults[]; 1666 }; 1667 1668 /* 1669 * For functions that can be called in multiple contexts that permit reading 1670 * ->numa_group (see struct task_struct for locking rules). 1671 */ 1672 static struct numa_group *deref_task_numa_group(struct task_struct *p) 1673 { 1674 return rcu_dereference_check(p->numa_group, p == current || 1675 (lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu))); 1676 } 1677 1678 static struct numa_group *deref_curr_numa_group(struct task_struct *p) 1679 { 1680 return rcu_dereference_protected(p->numa_group, p == current); 1681 } 1682 1683 static inline unsigned long group_faults_priv(struct numa_group *ng); 1684 static inline unsigned long group_faults_shared(struct numa_group *ng); 1685 1686 static unsigned int task_nr_scan_windows(struct task_struct *p) 1687 { 1688 unsigned long rss = 0; 1689 unsigned long nr_scan_pages; 1690 1691 /* 1692 * Calculations based on RSS as non-present and empty pages are skipped 1693 * by the PTE scanner and NUMA hinting faults should be trapped based 1694 * on resident pages 1695 */ 1696 nr_scan_pages = MB_TO_PAGES(sysctl_numa_balancing_scan_size); 1697 rss = get_mm_rss(p->mm); 1698 if (!rss) 1699 rss = nr_scan_pages; 1700 1701 rss = round_up(rss, nr_scan_pages); 1702 return rss / nr_scan_pages; 1703 } 1704 1705 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */ 1706 #define MAX_SCAN_WINDOW 2560 1707 1708 static unsigned int task_scan_min(struct task_struct *p) 1709 { 1710 unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size); 1711 unsigned int scan, floor; 1712 unsigned int windows = 1; 1713 1714 if (scan_size < MAX_SCAN_WINDOW) 1715 windows = MAX_SCAN_WINDOW / scan_size; 1716 floor = 1000 / windows; 1717 1718 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p); 1719 return max_t(unsigned int, floor, scan); 1720 } 1721 1722 static unsigned int task_scan_start(struct task_struct *p) 1723 { 1724 unsigned long smin = task_scan_min(p); 1725 unsigned long period = smin; 1726 struct numa_group *ng; 1727 1728 /* Scale the maximum scan period with the amount of shared memory. */ 1729 rcu_read_lock(); 1730 ng = rcu_dereference_all(p->numa_group); 1731 if (ng) { 1732 unsigned long shared = group_faults_shared(ng); 1733 unsigned long private = group_faults_priv(ng); 1734 1735 period *= refcount_read(&ng->refcount); 1736 period *= shared + 1; 1737 period /= private + shared + 1; 1738 } 1739 rcu_read_unlock(); 1740 1741 return max(smin, period); 1742 } 1743 1744 static unsigned int task_scan_max(struct task_struct *p) 1745 { 1746 unsigned long smin = task_scan_min(p); 1747 unsigned long smax; 1748 struct numa_group *ng; 1749 1750 /* Watch for min being lower than max due to floor calculations */ 1751 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p); 1752 1753 /* Scale the maximum scan period with the amount of shared memory. */ 1754 ng = deref_curr_numa_group(p); 1755 if (ng) { 1756 unsigned long shared = group_faults_shared(ng); 1757 unsigned long private = group_faults_priv(ng); 1758 unsigned long period = smax; 1759 1760 period *= refcount_read(&ng->refcount); 1761 period *= shared + 1; 1762 period /= private + shared + 1; 1763 1764 smax = max(smax, period); 1765 } 1766 1767 return max(smin, smax); 1768 } 1769 1770 static void account_numa_enqueue(struct rq *rq, struct task_struct *p) 1771 { 1772 rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE); 1773 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p)); 1774 } 1775 1776 static void account_numa_dequeue(struct rq *rq, struct task_struct *p) 1777 { 1778 rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE); 1779 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p)); 1780 } 1781 1782 /* Shared or private faults. */ 1783 #define NR_NUMA_HINT_FAULT_TYPES 2 1784 1785 /* Memory and CPU locality */ 1786 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2) 1787 1788 /* Averaged statistics, and temporary buffers. */ 1789 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2) 1790 1791 pid_t task_numa_group_id(struct task_struct *p) 1792 { 1793 struct numa_group *ng; 1794 pid_t gid = 0; 1795 1796 rcu_read_lock(); 1797 ng = rcu_dereference_all(p->numa_group); 1798 if (ng) 1799 gid = ng->gid; 1800 rcu_read_unlock(); 1801 1802 return gid; 1803 } 1804 1805 /* 1806 * The averaged statistics, shared & private, memory & CPU, 1807 * occupy the first half of the array. The second half of the 1808 * array is for current counters, which are averaged into the 1809 * first set by task_numa_placement. 1810 */ 1811 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv) 1812 { 1813 return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv; 1814 } 1815 1816 static inline unsigned long task_faults(struct task_struct *p, int nid) 1817 { 1818 if (!p->numa_faults) 1819 return 0; 1820 1821 return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] + 1822 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)]; 1823 } 1824 1825 static inline unsigned long group_faults(struct task_struct *p, int nid) 1826 { 1827 struct numa_group *ng = deref_task_numa_group(p); 1828 1829 if (!ng) 1830 return 0; 1831 1832 return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] + 1833 ng->faults[task_faults_idx(NUMA_MEM, nid, 1)]; 1834 } 1835 1836 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid) 1837 { 1838 return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] + 1839 group->faults[task_faults_idx(NUMA_CPU, nid, 1)]; 1840 } 1841 1842 static inline unsigned long group_faults_priv(struct numa_group *ng) 1843 { 1844 unsigned long faults = 0; 1845 int node; 1846 1847 for_each_online_node(node) { 1848 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)]; 1849 } 1850 1851 return faults; 1852 } 1853 1854 static inline unsigned long group_faults_shared(struct numa_group *ng) 1855 { 1856 unsigned long faults = 0; 1857 int node; 1858 1859 for_each_online_node(node) { 1860 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)]; 1861 } 1862 1863 return faults; 1864 } 1865 1866 /* 1867 * A node triggering more than 1/3 as many NUMA faults as the maximum is 1868 * considered part of a numa group's pseudo-interleaving set. Migrations 1869 * between these nodes are slowed down, to allow things to settle down. 1870 */ 1871 #define ACTIVE_NODE_FRACTION 3 1872 1873 static bool numa_is_active_node(int nid, struct numa_group *ng) 1874 { 1875 return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu; 1876 } 1877 1878 /* Handle placement on systems where not all nodes are directly connected. */ 1879 static unsigned long score_nearby_nodes(struct task_struct *p, int nid, 1880 int lim_dist, bool task) 1881 { 1882 unsigned long score = 0; 1883 int node, max_dist; 1884 1885 /* 1886 * All nodes are directly connected, and the same distance 1887 * from each other. No need for fancy placement algorithms. 1888 */ 1889 if (sched_numa_topology_type == NUMA_DIRECT) 1890 return 0; 1891 1892 /* sched_max_numa_distance may be changed in parallel. */ 1893 max_dist = READ_ONCE(sched_max_numa_distance); 1894 /* 1895 * This code is called for each node, introducing N^2 complexity, 1896 * which should be OK given the number of nodes rarely exceeds 8. 1897 */ 1898 for_each_online_node(node) { 1899 unsigned long faults; 1900 int dist = node_distance(nid, node); 1901 1902 /* 1903 * The furthest away nodes in the system are not interesting 1904 * for placement; nid was already counted. 1905 */ 1906 if (dist >= max_dist || node == nid) 1907 continue; 1908 1909 /* 1910 * On systems with a backplane NUMA topology, compare groups 1911 * of nodes, and move tasks towards the group with the most 1912 * memory accesses. When comparing two nodes at distance 1913 * "hoplimit", only nodes closer by than "hoplimit" are part 1914 * of each group. Skip other nodes. 1915 */ 1916 if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist) 1917 continue; 1918 1919 /* Add up the faults from nearby nodes. */ 1920 if (task) 1921 faults = task_faults(p, node); 1922 else 1923 faults = group_faults(p, node); 1924 1925 /* 1926 * On systems with a glueless mesh NUMA topology, there are 1927 * no fixed "groups of nodes". Instead, nodes that are not 1928 * directly connected bounce traffic through intermediate 1929 * nodes; a numa_group can occupy any set of nodes. 1930 * The further away a node is, the less the faults count. 1931 * This seems to result in good task placement. 1932 */ 1933 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) { 1934 faults *= (max_dist - dist); 1935 faults /= (max_dist - LOCAL_DISTANCE); 1936 } 1937 1938 score += faults; 1939 } 1940 1941 return score; 1942 } 1943 1944 /* 1945 * These return the fraction of accesses done by a particular task, or 1946 * task group, on a particular numa node. The group weight is given a 1947 * larger multiplier, in order to group tasks together that are almost 1948 * evenly spread out between numa nodes. 1949 */ 1950 static inline unsigned long task_weight(struct task_struct *p, int nid, 1951 int dist) 1952 { 1953 unsigned long faults, total_faults; 1954 1955 if (!p->numa_faults) 1956 return 0; 1957 1958 total_faults = p->total_numa_faults; 1959 1960 if (!total_faults) 1961 return 0; 1962 1963 faults = task_faults(p, nid); 1964 faults += score_nearby_nodes(p, nid, dist, true); 1965 1966 return 1000 * faults / total_faults; 1967 } 1968 1969 static inline unsigned long group_weight(struct task_struct *p, int nid, 1970 int dist) 1971 { 1972 struct numa_group *ng = deref_task_numa_group(p); 1973 unsigned long faults, total_faults; 1974 1975 if (!ng) 1976 return 0; 1977 1978 total_faults = ng->total_faults; 1979 1980 if (!total_faults) 1981 return 0; 1982 1983 faults = group_faults(p, nid); 1984 faults += score_nearby_nodes(p, nid, dist, false); 1985 1986 return 1000 * faults / total_faults; 1987 } 1988 1989 /* 1990 * If memory tiering mode is enabled, cpupid of slow memory page is 1991 * used to record scan time instead of CPU and PID. When tiering mode 1992 * is disabled at run time, the scan time (in cpupid) will be 1993 * interpreted as CPU and PID. So CPU needs to be checked to avoid to 1994 * access out of array bound. 1995 */ 1996 static inline bool cpupid_valid(int cpupid) 1997 { 1998 return cpupid_to_cpu(cpupid) < nr_cpu_ids; 1999 } 2000 2001 /* 2002 * For memory tiering mode, if there are enough free pages (more than 2003 * enough watermark defined here) in fast memory node, to take full 2004 * advantage of fast memory capacity, all recently accessed slow 2005 * memory pages will be migrated to fast memory node without 2006 * considering hot threshold. 2007 */ 2008 static bool pgdat_free_space_enough(struct pglist_data *pgdat) 2009 { 2010 int z; 2011 unsigned long enough_wmark; 2012 2013 enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT, 2014 pgdat->node_present_pages >> 4); 2015 for (z = pgdat->nr_zones - 1; z >= 0; z--) { 2016 struct zone *zone = pgdat->node_zones + z; 2017 2018 if (!populated_zone(zone)) 2019 continue; 2020 2021 if (zone_watermark_ok(zone, 0, 2022 promo_wmark_pages(zone) + enough_wmark, 2023 ZONE_MOVABLE, 0)) 2024 return true; 2025 } 2026 return false; 2027 } 2028 2029 /* 2030 * For memory tiering mode, when page tables are scanned, the scan 2031 * time will be recorded in struct page in addition to make page 2032 * PROT_NONE for slow memory page. So when the page is accessed, in 2033 * hint page fault handler, the hint page fault latency is calculated 2034 * via, 2035 * 2036 * hint page fault latency = hint page fault time - scan time 2037 * 2038 * The smaller the hint page fault latency, the higher the possibility 2039 * for the page to be hot. 2040 */ 2041 static int numa_hint_fault_latency(struct folio *folio) 2042 { 2043 int last_time, time; 2044 2045 time = jiffies_to_msecs(jiffies); 2046 last_time = folio_xchg_access_time(folio, time); 2047 2048 return (time - last_time) & PAGE_ACCESS_TIME_MASK; 2049 } 2050 2051 /* 2052 * For memory tiering mode, too high promotion/demotion throughput may 2053 * hurt application latency. So we provide a mechanism to rate limit 2054 * the number of pages that are tried to be promoted. 2055 */ 2056 static bool numa_promotion_rate_limit(struct pglist_data *pgdat, 2057 unsigned long rate_limit, int nr) 2058 { 2059 unsigned long nr_cand; 2060 unsigned int now, start; 2061 2062 now = jiffies_to_msecs(jiffies); 2063 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr); 2064 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE); 2065 start = pgdat->nbp_rl_start; 2066 if (now - start > MSEC_PER_SEC && 2067 cmpxchg(&pgdat->nbp_rl_start, start, now) == start) 2068 pgdat->nbp_rl_nr_cand = nr_cand; 2069 if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit) 2070 return true; 2071 return false; 2072 } 2073 2074 #define NUMA_MIGRATION_ADJUST_STEPS 16 2075 2076 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat, 2077 unsigned long rate_limit, 2078 unsigned int ref_th) 2079 { 2080 unsigned int now, start, th_period, unit_th, th; 2081 unsigned long nr_cand, ref_cand, diff_cand; 2082 2083 now = jiffies_to_msecs(jiffies); 2084 th_period = sysctl_numa_balancing_scan_period_max; 2085 start = pgdat->nbp_th_start; 2086 if (now - start > th_period && 2087 cmpxchg(&pgdat->nbp_th_start, start, now) == start) { 2088 ref_cand = rate_limit * 2089 sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC; 2090 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE); 2091 diff_cand = nr_cand - pgdat->nbp_th_nr_cand; 2092 unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS; 2093 th = pgdat->nbp_threshold ? : ref_th; 2094 if (diff_cand > ref_cand * 11 / 10) 2095 th = max(th - unit_th, unit_th); 2096 else if (diff_cand < ref_cand * 9 / 10) 2097 th = min(th + unit_th, ref_th * 2); 2098 pgdat->nbp_th_nr_cand = nr_cand; 2099 pgdat->nbp_threshold = th; 2100 } 2101 } 2102 2103 bool should_numa_migrate_memory(struct task_struct *p, struct folio *folio, 2104 int src_nid, int dst_cpu) 2105 { 2106 struct numa_group *ng = deref_curr_numa_group(p); 2107 int dst_nid = cpu_to_node(dst_cpu); 2108 int last_cpupid, this_cpupid; 2109 2110 /* 2111 * Cannot migrate to memoryless nodes. 2112 */ 2113 if (!node_state(dst_nid, N_MEMORY)) 2114 return false; 2115 2116 /* 2117 * The pages in slow memory node should be migrated according 2118 * to hot/cold instead of private/shared. 2119 */ 2120 if (folio_use_access_time(folio)) { 2121 struct pglist_data *pgdat; 2122 unsigned long rate_limit; 2123 unsigned int latency, th, def_th; 2124 long nr = folio_nr_pages(folio); 2125 2126 pgdat = NODE_DATA(dst_nid); 2127 if (pgdat_free_space_enough(pgdat)) { 2128 /* workload changed, reset hot threshold */ 2129 pgdat->nbp_threshold = 0; 2130 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE_NRL, nr); 2131 return true; 2132 } 2133 2134 def_th = sysctl_numa_balancing_hot_threshold; 2135 rate_limit = MB_TO_PAGES(sysctl_numa_balancing_promote_rate_limit); 2136 numa_promotion_adjust_threshold(pgdat, rate_limit, def_th); 2137 2138 th = pgdat->nbp_threshold ? : def_th; 2139 latency = numa_hint_fault_latency(folio); 2140 if (latency >= th) 2141 return false; 2142 2143 return !numa_promotion_rate_limit(pgdat, rate_limit, nr); 2144 } 2145 2146 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid); 2147 last_cpupid = folio_xchg_last_cpupid(folio, this_cpupid); 2148 2149 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) && 2150 !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid)) 2151 return false; 2152 2153 /* 2154 * Allow first faults or private faults to migrate immediately early in 2155 * the lifetime of a task. The magic number 4 is based on waiting for 2156 * two full passes of the "multi-stage node selection" test that is 2157 * executed below. 2158 */ 2159 if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) && 2160 (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid))) 2161 return true; 2162 2163 /* 2164 * Multi-stage node selection is used in conjunction with a periodic 2165 * migration fault to build a temporal task<->page relation. By using 2166 * a two-stage filter we remove short/unlikely relations. 2167 * 2168 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate 2169 * a task's usage of a particular page (n_p) per total usage of this 2170 * page (n_t) (in a given time-span) to a probability. 2171 * 2172 * Our periodic faults will sample this probability and getting the 2173 * same result twice in a row, given these samples are fully 2174 * independent, is then given by P(n)^2, provided our sample period 2175 * is sufficiently short compared to the usage pattern. 2176 * 2177 * This quadric squishes small probabilities, making it less likely we 2178 * act on an unlikely task<->page relation. 2179 */ 2180 if (!cpupid_pid_unset(last_cpupid) && 2181 cpupid_to_nid(last_cpupid) != dst_nid) 2182 return false; 2183 2184 /* Always allow migrate on private faults */ 2185 if (cpupid_match_pid(p, last_cpupid)) 2186 return true; 2187 2188 /* A shared fault, but p->numa_group has not been set up yet. */ 2189 if (!ng) 2190 return true; 2191 2192 /* 2193 * Destination node is much more heavily used than the source 2194 * node? Allow migration. 2195 */ 2196 if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) * 2197 ACTIVE_NODE_FRACTION) 2198 return true; 2199 2200 /* 2201 * Distribute memory according to CPU & memory use on each node, 2202 * with 3/4 hysteresis to avoid unnecessary memory migrations: 2203 * 2204 * faults_cpu(dst) 3 faults_cpu(src) 2205 * --------------- * - > --------------- 2206 * faults_mem(dst) 4 faults_mem(src) 2207 */ 2208 return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 > 2209 group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4; 2210 } 2211 2212 /* 2213 * 'numa_type' describes the node at the moment of load balancing. 2214 */ 2215 enum numa_type { 2216 /* The node has spare capacity that can be used to run more tasks. */ 2217 node_has_spare = 0, 2218 /* 2219 * The node is fully used and the tasks don't compete for more CPU 2220 * cycles. Nevertheless, some tasks might wait before running. 2221 */ 2222 node_fully_busy, 2223 /* 2224 * The node is overloaded and can't provide expected CPU cycles to all 2225 * tasks. 2226 */ 2227 node_overloaded 2228 }; 2229 2230 /* Cached statistics for all CPUs within a node */ 2231 struct numa_stats { 2232 unsigned long load; 2233 unsigned long runnable; 2234 unsigned long util; 2235 /* Total compute capacity of CPUs on a node */ 2236 unsigned long compute_capacity; 2237 unsigned int nr_running; 2238 unsigned int weight; 2239 enum numa_type node_type; 2240 int idle_cpu; 2241 }; 2242 2243 struct task_numa_env { 2244 struct task_struct *p; 2245 2246 int src_cpu, src_nid; 2247 int dst_cpu, dst_nid; 2248 int imb_numa_nr; 2249 2250 struct numa_stats src_stats, dst_stats; 2251 2252 int imbalance_pct; 2253 int dist; 2254 2255 struct task_struct *best_task; 2256 long best_imp; 2257 int best_cpu; 2258 }; 2259 2260 static unsigned long cpu_load(struct rq *rq); 2261 static unsigned long cpu_runnable(struct rq *rq); 2262 2263 static inline enum 2264 numa_type numa_classify(unsigned int imbalance_pct, 2265 struct numa_stats *ns) 2266 { 2267 if ((ns->nr_running > ns->weight) && 2268 (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) || 2269 ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100)))) 2270 return node_overloaded; 2271 2272 if ((ns->nr_running < ns->weight) || 2273 (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) && 2274 ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100)))) 2275 return node_has_spare; 2276 2277 return node_fully_busy; 2278 } 2279 2280 #ifdef CONFIG_SCHED_SMT 2281 /* Forward declarations of select_idle_sibling helpers */ 2282 static inline bool test_idle_cores(int cpu); 2283 static inline int numa_idle_core(int idle_core, int cpu) 2284 { 2285 if (!static_branch_likely(&sched_smt_present) || 2286 idle_core >= 0 || !test_idle_cores(cpu)) 2287 return idle_core; 2288 2289 /* 2290 * Prefer cores instead of packing HT siblings 2291 * and triggering future load balancing. 2292 */ 2293 if (is_core_idle(cpu)) 2294 idle_core = cpu; 2295 2296 return idle_core; 2297 } 2298 #else /* !CONFIG_SCHED_SMT: */ 2299 static inline int numa_idle_core(int idle_core, int cpu) 2300 { 2301 return idle_core; 2302 } 2303 #endif /* !CONFIG_SCHED_SMT */ 2304 2305 /* 2306 * Gather all necessary information to make NUMA balancing placement 2307 * decisions that are compatible with standard load balancer. This 2308 * borrows code and logic from update_sg_lb_stats but sharing a 2309 * common implementation is impractical. 2310 */ 2311 static void update_numa_stats(struct task_numa_env *env, 2312 struct numa_stats *ns, int nid, 2313 bool find_idle) 2314 { 2315 int cpu, idle_core = -1; 2316 2317 memset(ns, 0, sizeof(*ns)); 2318 ns->idle_cpu = -1; 2319 2320 rcu_read_lock(); 2321 for_each_cpu(cpu, cpumask_of_node(nid)) { 2322 struct rq *rq = cpu_rq(cpu); 2323 2324 ns->load += cpu_load(rq); 2325 ns->runnable += cpu_runnable(rq); 2326 ns->util += cpu_util_cfs(cpu); 2327 ns->nr_running += rq->cfs.h_nr_runnable; 2328 ns->compute_capacity += capacity_of(cpu); 2329 2330 if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) { 2331 if (READ_ONCE(rq->numa_migrate_on) || 2332 !cpumask_test_cpu(cpu, env->p->cpus_ptr)) 2333 continue; 2334 2335 if (ns->idle_cpu == -1) 2336 ns->idle_cpu = cpu; 2337 2338 idle_core = numa_idle_core(idle_core, cpu); 2339 } 2340 } 2341 rcu_read_unlock(); 2342 2343 ns->weight = cpumask_weight(cpumask_of_node(nid)); 2344 2345 ns->node_type = numa_classify(env->imbalance_pct, ns); 2346 2347 if (idle_core >= 0) 2348 ns->idle_cpu = idle_core; 2349 } 2350 2351 static void task_numa_assign(struct task_numa_env *env, 2352 struct task_struct *p, long imp) 2353 { 2354 struct rq *rq = cpu_rq(env->dst_cpu); 2355 2356 /* Check if run-queue part of active NUMA balance. */ 2357 if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) { 2358 int cpu; 2359 int start = env->dst_cpu; 2360 2361 /* Find alternative idle CPU. */ 2362 for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) { 2363 if (cpu == env->best_cpu || !idle_cpu(cpu) || 2364 !cpumask_test_cpu(cpu, env->p->cpus_ptr)) { 2365 continue; 2366 } 2367 2368 env->dst_cpu = cpu; 2369 rq = cpu_rq(env->dst_cpu); 2370 if (!xchg(&rq->numa_migrate_on, 1)) 2371 goto assign; 2372 } 2373 2374 /* Failed to find an alternative idle CPU */ 2375 return; 2376 } 2377 2378 assign: 2379 /* 2380 * Clear previous best_cpu/rq numa-migrate flag, since task now 2381 * found a better CPU to move/swap. 2382 */ 2383 if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) { 2384 rq = cpu_rq(env->best_cpu); 2385 WRITE_ONCE(rq->numa_migrate_on, 0); 2386 } 2387 2388 if (env->best_task) 2389 put_task_struct(env->best_task); 2390 if (p) 2391 get_task_struct(p); 2392 2393 env->best_task = p; 2394 env->best_imp = imp; 2395 env->best_cpu = env->dst_cpu; 2396 } 2397 2398 static bool load_too_imbalanced(long src_load, long dst_load, 2399 struct task_numa_env *env) 2400 { 2401 long imb, old_imb; 2402 long orig_src_load, orig_dst_load; 2403 long src_capacity, dst_capacity; 2404 2405 /* 2406 * The load is corrected for the CPU capacity available on each node. 2407 * 2408 * src_load dst_load 2409 * ------------ vs --------- 2410 * src_capacity dst_capacity 2411 */ 2412 src_capacity = env->src_stats.compute_capacity; 2413 dst_capacity = env->dst_stats.compute_capacity; 2414 2415 imb = abs(dst_load * src_capacity - src_load * dst_capacity); 2416 2417 orig_src_load = env->src_stats.load; 2418 orig_dst_load = env->dst_stats.load; 2419 2420 old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity); 2421 2422 /* Would this change make things worse? */ 2423 return (imb > old_imb); 2424 } 2425 2426 /* 2427 * Maximum NUMA importance can be 1998 (2*999); 2428 * SMALLIMP @ 30 would be close to 1998/64. 2429 * Used to deter task migration. 2430 */ 2431 #define SMALLIMP 30 2432 2433 /* 2434 * This checks if the overall compute and NUMA accesses of the system would 2435 * be improved if the source tasks was migrated to the target dst_cpu taking 2436 * into account that it might be best if task running on the dst_cpu should 2437 * be exchanged with the source task 2438 */ 2439 static bool task_numa_compare(struct task_numa_env *env, 2440 long taskimp, long groupimp, bool maymove) 2441 { 2442 struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p); 2443 struct rq *dst_rq = cpu_rq(env->dst_cpu); 2444 long imp = p_ng ? groupimp : taskimp; 2445 struct task_struct *cur; 2446 long src_load, dst_load; 2447 int dist = env->dist; 2448 long moveimp = imp; 2449 long load; 2450 bool stopsearch = false; 2451 2452 if (READ_ONCE(dst_rq->numa_migrate_on)) 2453 return false; 2454 2455 rcu_read_lock(); 2456 cur = rcu_dereference_all(dst_rq->curr); 2457 if (cur && ((cur->flags & (PF_EXITING | PF_KTHREAD)) || 2458 !cur->mm)) 2459 cur = NULL; 2460 2461 /* 2462 * Because we have preemption enabled we can get migrated around and 2463 * end try selecting ourselves (current == env->p) as a swap candidate. 2464 */ 2465 if (cur == env->p) { 2466 stopsearch = true; 2467 goto unlock; 2468 } 2469 2470 if (!cur) { 2471 if (maymove && moveimp >= env->best_imp) 2472 goto assign; 2473 else 2474 goto unlock; 2475 } 2476 2477 /* Skip this swap candidate if cannot move to the source cpu. */ 2478 if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr)) 2479 goto unlock; 2480 2481 /* 2482 * Skip this swap candidate if it is not moving to its preferred 2483 * node and the best task is. 2484 */ 2485 if (env->best_task && 2486 env->best_task->numa_preferred_nid == env->src_nid && 2487 cur->numa_preferred_nid != env->src_nid) { 2488 goto unlock; 2489 } 2490 2491 /* 2492 * "imp" is the fault differential for the source task between the 2493 * source and destination node. Calculate the total differential for 2494 * the source task and potential destination task. The more negative 2495 * the value is, the more remote accesses that would be expected to 2496 * be incurred if the tasks were swapped. 2497 * 2498 * If dst and source tasks are in the same NUMA group, or not 2499 * in any group then look only at task weights. 2500 */ 2501 cur_ng = rcu_dereference_all(cur->numa_group); 2502 if (cur_ng == p_ng) { 2503 /* 2504 * Do not swap within a group or between tasks that have 2505 * no group if there is spare capacity. Swapping does 2506 * not address the load imbalance and helps one task at 2507 * the cost of punishing another. 2508 */ 2509 if (env->dst_stats.node_type == node_has_spare) 2510 goto unlock; 2511 2512 imp = taskimp + task_weight(cur, env->src_nid, dist) - 2513 task_weight(cur, env->dst_nid, dist); 2514 /* 2515 * Add some hysteresis to prevent swapping the 2516 * tasks within a group over tiny differences. 2517 */ 2518 if (cur_ng) 2519 imp -= imp / 16; 2520 } else { 2521 /* 2522 * Compare the group weights. If a task is all by itself 2523 * (not part of a group), use the task weight instead. 2524 */ 2525 if (cur_ng && p_ng) 2526 imp += group_weight(cur, env->src_nid, dist) - 2527 group_weight(cur, env->dst_nid, dist); 2528 else 2529 imp += task_weight(cur, env->src_nid, dist) - 2530 task_weight(cur, env->dst_nid, dist); 2531 } 2532 2533 /* Discourage picking a task already on its preferred node */ 2534 if (cur->numa_preferred_nid == env->dst_nid) 2535 imp -= imp / 16; 2536 2537 /* 2538 * Encourage picking a task that moves to its preferred node. 2539 * This potentially makes imp larger than it's maximum of 2540 * 1998 (see SMALLIMP and task_weight for why) but in this 2541 * case, it does not matter. 2542 */ 2543 if (cur->numa_preferred_nid == env->src_nid) 2544 imp += imp / 8; 2545 2546 if (maymove && moveimp > imp && moveimp > env->best_imp) { 2547 imp = moveimp; 2548 cur = NULL; 2549 goto assign; 2550 } 2551 2552 /* 2553 * Prefer swapping with a task moving to its preferred node over a 2554 * task that is not. 2555 */ 2556 if (env->best_task && cur->numa_preferred_nid == env->src_nid && 2557 env->best_task->numa_preferred_nid != env->src_nid) { 2558 goto assign; 2559 } 2560 2561 /* 2562 * If the NUMA importance is less than SMALLIMP, 2563 * task migration might only result in ping pong 2564 * of tasks and also hurt performance due to cache 2565 * misses. 2566 */ 2567 if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2) 2568 goto unlock; 2569 2570 /* 2571 * In the overloaded case, try and keep the load balanced. 2572 */ 2573 load = task_h_load(env->p) - task_h_load(cur); 2574 if (!load) 2575 goto assign; 2576 2577 dst_load = env->dst_stats.load + load; 2578 src_load = env->src_stats.load - load; 2579 2580 if (load_too_imbalanced(src_load, dst_load, env)) 2581 goto unlock; 2582 2583 assign: 2584 /* Evaluate an idle CPU for a task numa move. */ 2585 if (!cur) { 2586 int cpu = env->dst_stats.idle_cpu; 2587 2588 /* Nothing cached so current CPU went idle since the search. */ 2589 if (cpu < 0) 2590 cpu = env->dst_cpu; 2591 2592 /* 2593 * If the CPU is no longer truly idle and the previous best CPU 2594 * is, keep using it. 2595 */ 2596 if (!idle_cpu(cpu) && env->best_cpu >= 0 && 2597 idle_cpu(env->best_cpu)) { 2598 cpu = env->best_cpu; 2599 } 2600 2601 env->dst_cpu = cpu; 2602 } 2603 2604 task_numa_assign(env, cur, imp); 2605 2606 /* 2607 * If a move to idle is allowed because there is capacity or load 2608 * balance improves then stop the search. While a better swap 2609 * candidate may exist, a search is not free. 2610 */ 2611 if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu)) 2612 stopsearch = true; 2613 2614 /* 2615 * If a swap candidate must be identified and the current best task 2616 * moves its preferred node then stop the search. 2617 */ 2618 if (!maymove && env->best_task && 2619 env->best_task->numa_preferred_nid == env->src_nid) { 2620 stopsearch = true; 2621 } 2622 unlock: 2623 rcu_read_unlock(); 2624 2625 return stopsearch; 2626 } 2627 2628 static void task_numa_find_cpu(struct task_numa_env *env, 2629 long taskimp, long groupimp) 2630 { 2631 bool maymove = false; 2632 int cpu; 2633 2634 /* 2635 * If dst node has spare capacity, then check if there is an 2636 * imbalance that would be overruled by the load balancer. 2637 */ 2638 if (env->dst_stats.node_type == node_has_spare) { 2639 unsigned int imbalance; 2640 int src_running, dst_running; 2641 2642 /* 2643 * Would movement cause an imbalance? Note that if src has 2644 * more running tasks that the imbalance is ignored as the 2645 * move improves the imbalance from the perspective of the 2646 * CPU load balancer. 2647 * */ 2648 src_running = env->src_stats.nr_running - 1; 2649 dst_running = env->dst_stats.nr_running + 1; 2650 imbalance = max(0, dst_running - src_running); 2651 imbalance = adjust_numa_imbalance(imbalance, dst_running, 2652 env->imb_numa_nr); 2653 2654 /* Use idle CPU if there is no imbalance */ 2655 if (!imbalance) { 2656 maymove = true; 2657 if (env->dst_stats.idle_cpu >= 0) { 2658 env->dst_cpu = env->dst_stats.idle_cpu; 2659 task_numa_assign(env, NULL, 0); 2660 return; 2661 } 2662 } 2663 } else { 2664 long src_load, dst_load, load; 2665 /* 2666 * If the improvement from just moving env->p direction is better 2667 * than swapping tasks around, check if a move is possible. 2668 */ 2669 load = task_h_load(env->p); 2670 dst_load = env->dst_stats.load + load; 2671 src_load = env->src_stats.load - load; 2672 maymove = !load_too_imbalanced(src_load, dst_load, env); 2673 } 2674 2675 /* Skip CPUs if the source task cannot migrate */ 2676 for_each_cpu_and(cpu, cpumask_of_node(env->dst_nid), env->p->cpus_ptr) { 2677 env->dst_cpu = cpu; 2678 if (task_numa_compare(env, taskimp, groupimp, maymove)) 2679 break; 2680 } 2681 } 2682 2683 static int task_numa_migrate(struct task_struct *p) 2684 { 2685 struct task_numa_env env = { 2686 .p = p, 2687 2688 .src_cpu = task_cpu(p), 2689 .src_nid = task_node(p), 2690 2691 .imbalance_pct = 112, 2692 2693 .best_task = NULL, 2694 .best_imp = 0, 2695 .best_cpu = -1, 2696 }; 2697 unsigned long taskweight, groupweight; 2698 struct sched_domain *sd; 2699 long taskimp, groupimp; 2700 struct numa_group *ng; 2701 struct rq *best_rq; 2702 int nid, ret, dist; 2703 2704 /* 2705 * Pick the lowest SD_NUMA domain, as that would have the smallest 2706 * imbalance and would be the first to start moving tasks about. 2707 * 2708 * And we want to avoid any moving of tasks about, as that would create 2709 * random movement of tasks -- counter the numa conditions we're trying 2710 * to satisfy here. 2711 */ 2712 rcu_read_lock(); 2713 sd = rcu_dereference_all(per_cpu(sd_numa, env.src_cpu)); 2714 if (sd) { 2715 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2; 2716 env.imb_numa_nr = sd->imb_numa_nr; 2717 } 2718 rcu_read_unlock(); 2719 2720 /* 2721 * Cpusets can break the scheduler domain tree into smaller 2722 * balance domains, some of which do not cross NUMA boundaries. 2723 * Tasks that are "trapped" in such domains cannot be migrated 2724 * elsewhere, so there is no point in (re)trying. 2725 */ 2726 if (unlikely(!sd)) { 2727 sched_setnuma(p, task_node(p)); 2728 return -EINVAL; 2729 } 2730 2731 env.dst_nid = p->numa_preferred_nid; 2732 dist = env.dist = node_distance(env.src_nid, env.dst_nid); 2733 taskweight = task_weight(p, env.src_nid, dist); 2734 groupweight = group_weight(p, env.src_nid, dist); 2735 update_numa_stats(&env, &env.src_stats, env.src_nid, false); 2736 taskimp = task_weight(p, env.dst_nid, dist) - taskweight; 2737 groupimp = group_weight(p, env.dst_nid, dist) - groupweight; 2738 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true); 2739 2740 /* Try to find a spot on the preferred nid. */ 2741 task_numa_find_cpu(&env, taskimp, groupimp); 2742 2743 /* 2744 * Look at other nodes in these cases: 2745 * - there is no space available on the preferred_nid 2746 * - the task is part of a numa_group that is interleaved across 2747 * multiple NUMA nodes; in order to better consolidate the group, 2748 * we need to check other locations. 2749 */ 2750 ng = deref_curr_numa_group(p); 2751 if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) { 2752 for_each_node_state(nid, N_CPU) { 2753 if (nid == env.src_nid || nid == p->numa_preferred_nid) 2754 continue; 2755 2756 dist = node_distance(env.src_nid, env.dst_nid); 2757 if (sched_numa_topology_type == NUMA_BACKPLANE && 2758 dist != env.dist) { 2759 taskweight = task_weight(p, env.src_nid, dist); 2760 groupweight = group_weight(p, env.src_nid, dist); 2761 } 2762 2763 /* Only consider nodes where both task and groups benefit */ 2764 taskimp = task_weight(p, nid, dist) - taskweight; 2765 groupimp = group_weight(p, nid, dist) - groupweight; 2766 if (taskimp < 0 && groupimp < 0) 2767 continue; 2768 2769 env.dist = dist; 2770 env.dst_nid = nid; 2771 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true); 2772 task_numa_find_cpu(&env, taskimp, groupimp); 2773 } 2774 } 2775 2776 /* 2777 * If the task is part of a workload that spans multiple NUMA nodes, 2778 * and is migrating into one of the workload's active nodes, remember 2779 * this node as the task's preferred numa node, so the workload can 2780 * settle down. 2781 * A task that migrated to a second choice node will be better off 2782 * trying for a better one later. Do not set the preferred node here. 2783 */ 2784 if (ng) { 2785 if (env.best_cpu == -1) 2786 nid = env.src_nid; 2787 else 2788 nid = cpu_to_node(env.best_cpu); 2789 2790 if (nid != p->numa_preferred_nid) 2791 sched_setnuma(p, nid); 2792 } 2793 2794 /* No better CPU than the current one was found. */ 2795 if (env.best_cpu == -1) { 2796 trace_sched_stick_numa(p, env.src_cpu, NULL, -1); 2797 return -EAGAIN; 2798 } 2799 2800 best_rq = cpu_rq(env.best_cpu); 2801 if (env.best_task == NULL) { 2802 ret = migrate_task_to(p, env.best_cpu); 2803 WRITE_ONCE(best_rq->numa_migrate_on, 0); 2804 if (ret != 0) 2805 trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu); 2806 return ret; 2807 } 2808 2809 ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu); 2810 WRITE_ONCE(best_rq->numa_migrate_on, 0); 2811 2812 if (ret != 0) 2813 trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu); 2814 put_task_struct(env.best_task); 2815 return ret; 2816 } 2817 2818 /* Attempt to migrate a task to a CPU on the preferred node. */ 2819 static void numa_migrate_preferred(struct task_struct *p) 2820 { 2821 unsigned long interval = HZ; 2822 2823 /* This task has no NUMA fault statistics yet */ 2824 if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults)) 2825 return; 2826 2827 /* Periodically retry migrating the task to the preferred node */ 2828 interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16); 2829 p->numa_migrate_retry = jiffies + interval; 2830 2831 /* Success if task is already running on preferred CPU */ 2832 if (task_node(p) == p->numa_preferred_nid) 2833 return; 2834 2835 /* Otherwise, try migrate to a CPU on the preferred node */ 2836 task_numa_migrate(p); 2837 } 2838 2839 /* 2840 * Find out how many nodes the workload is actively running on. Do this by 2841 * tracking the nodes from which NUMA hinting faults are triggered. This can 2842 * be different from the set of nodes where the workload's memory is currently 2843 * located. 2844 */ 2845 static void numa_group_count_active_nodes(struct numa_group *numa_group) 2846 { 2847 unsigned long faults, max_faults = 0; 2848 int nid, active_nodes = 0; 2849 2850 for_each_node_state(nid, N_CPU) { 2851 faults = group_faults_cpu(numa_group, nid); 2852 if (faults > max_faults) 2853 max_faults = faults; 2854 } 2855 2856 for_each_node_state(nid, N_CPU) { 2857 faults = group_faults_cpu(numa_group, nid); 2858 if (faults * ACTIVE_NODE_FRACTION > max_faults) 2859 active_nodes++; 2860 } 2861 2862 numa_group->max_faults_cpu = max_faults; 2863 numa_group->active_nodes = active_nodes; 2864 } 2865 2866 /* 2867 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS 2868 * increments. The more local the fault statistics are, the higher the scan 2869 * period will be for the next scan window. If local/(local+remote) ratio is 2870 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS) 2871 * the scan period will decrease. Aim for 70% local accesses. 2872 */ 2873 #define NUMA_PERIOD_SLOTS 10 2874 #define NUMA_PERIOD_THRESHOLD 7 2875 2876 /* 2877 * Increase the scan period (slow down scanning) if the majority of 2878 * our memory is already on our local node, or if the majority of 2879 * the page accesses are shared with other processes. 2880 * Otherwise, decrease the scan period. 2881 */ 2882 static void update_task_scan_period(struct task_struct *p, 2883 unsigned long shared, unsigned long private) 2884 { 2885 unsigned int period_slot; 2886 int lr_ratio, ps_ratio; 2887 int diff; 2888 2889 unsigned long remote = p->numa_faults_locality[0]; 2890 unsigned long local = p->numa_faults_locality[1]; 2891 2892 /* 2893 * If there were no record hinting faults then either the task is 2894 * completely idle or all activity is in areas that are not of interest 2895 * to automatic numa balancing. Related to that, if there were failed 2896 * migration then it implies we are migrating too quickly or the local 2897 * node is overloaded. In either case, scan slower 2898 */ 2899 if (local + shared == 0 || p->numa_faults_locality[2]) { 2900 p->numa_scan_period = min(p->numa_scan_period_max, 2901 p->numa_scan_period << 1); 2902 2903 p->mm->numa_next_scan = jiffies + 2904 msecs_to_jiffies(p->numa_scan_period); 2905 2906 return; 2907 } 2908 2909 /* 2910 * Prepare to scale scan period relative to the current period. 2911 * == NUMA_PERIOD_THRESHOLD scan period stays the same 2912 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster) 2913 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower) 2914 */ 2915 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS); 2916 lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote); 2917 ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared); 2918 2919 if (ps_ratio >= NUMA_PERIOD_THRESHOLD) { 2920 /* 2921 * Most memory accesses are local. There is no need to 2922 * do fast NUMA scanning, since memory is already local. 2923 */ 2924 int slot = ps_ratio - NUMA_PERIOD_THRESHOLD; 2925 if (!slot) 2926 slot = 1; 2927 diff = slot * period_slot; 2928 } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) { 2929 /* 2930 * Most memory accesses are shared with other tasks. 2931 * There is no point in continuing fast NUMA scanning, 2932 * since other tasks may just move the memory elsewhere. 2933 */ 2934 int slot = lr_ratio - NUMA_PERIOD_THRESHOLD; 2935 if (!slot) 2936 slot = 1; 2937 diff = slot * period_slot; 2938 } else { 2939 /* 2940 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS, 2941 * yet they are not on the local NUMA node. Speed up 2942 * NUMA scanning to get the memory moved over. 2943 */ 2944 int ratio = max(lr_ratio, ps_ratio); 2945 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot; 2946 } 2947 2948 p->numa_scan_period = clamp(p->numa_scan_period + diff, 2949 task_scan_min(p), task_scan_max(p)); 2950 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality)); 2951 } 2952 2953 /* 2954 * Get the fraction of time the task has been running since the last 2955 * NUMA placement cycle. The scheduler keeps similar statistics, but 2956 * decays those on a 32ms period, which is orders of magnitude off 2957 * from the dozens-of-seconds NUMA balancing period. Use the scheduler 2958 * stats only if the task is so new there are no NUMA statistics yet. 2959 */ 2960 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period) 2961 { 2962 u64 runtime, delta, now; 2963 /* Use the start of this time slice to avoid calculations. */ 2964 now = p->se.exec_start; 2965 runtime = p->se.sum_exec_runtime; 2966 2967 if (p->last_task_numa_placement) { 2968 delta = runtime - p->last_sum_exec_runtime; 2969 *period = now - p->last_task_numa_placement; 2970 2971 /* Avoid time going backwards, prevent potential divide error: */ 2972 if (unlikely((s64)*period < 0)) 2973 *period = 0; 2974 } else { 2975 delta = p->se.avg.load_sum; 2976 *period = LOAD_AVG_MAX; 2977 } 2978 2979 p->last_sum_exec_runtime = runtime; 2980 p->last_task_numa_placement = now; 2981 2982 return delta; 2983 } 2984 2985 /* 2986 * Determine the preferred nid for a task in a numa_group. This needs to 2987 * be done in a way that produces consistent results with group_weight, 2988 * otherwise workloads might not converge. 2989 */ 2990 static int preferred_group_nid(struct task_struct *p, int nid) 2991 { 2992 nodemask_t nodes; 2993 int dist; 2994 2995 /* Direct connections between all NUMA nodes. */ 2996 if (sched_numa_topology_type == NUMA_DIRECT) 2997 return nid; 2998 2999 /* 3000 * On a system with glueless mesh NUMA topology, group_weight 3001 * scores nodes according to the number of NUMA hinting faults on 3002 * both the node itself, and on nearby nodes. 3003 */ 3004 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) { 3005 unsigned long score, max_score = 0; 3006 int node, max_node = nid; 3007 3008 dist = sched_max_numa_distance; 3009 3010 for_each_node_state(node, N_CPU) { 3011 score = group_weight(p, node, dist); 3012 if (score > max_score) { 3013 max_score = score; 3014 max_node = node; 3015 } 3016 } 3017 return max_node; 3018 } 3019 3020 /* 3021 * Finding the preferred nid in a system with NUMA backplane 3022 * interconnect topology is more involved. The goal is to locate 3023 * tasks from numa_groups near each other in the system, and 3024 * untangle workloads from different sides of the system. This requires 3025 * searching down the hierarchy of node groups, recursively searching 3026 * inside the highest scoring group of nodes. The nodemask tricks 3027 * keep the complexity of the search down. 3028 */ 3029 nodes = node_states[N_CPU]; 3030 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) { 3031 unsigned long max_faults = 0; 3032 nodemask_t max_group = NODE_MASK_NONE; 3033 int a, b; 3034 3035 /* Are there nodes at this distance from each other? */ 3036 if (!find_numa_distance(dist)) 3037 continue; 3038 3039 for_each_node_mask(a, nodes) { 3040 unsigned long faults = 0; 3041 nodemask_t this_group; 3042 nodes_clear(this_group); 3043 3044 /* Sum group's NUMA faults; includes a==b case. */ 3045 for_each_node_mask(b, nodes) { 3046 if (node_distance(a, b) < dist) { 3047 faults += group_faults(p, b); 3048 node_set(b, this_group); 3049 node_clear(b, nodes); 3050 } 3051 } 3052 3053 /* Remember the top group. */ 3054 if (faults > max_faults) { 3055 max_faults = faults; 3056 max_group = this_group; 3057 /* 3058 * subtle: at the smallest distance there is 3059 * just one node left in each "group", the 3060 * winner is the preferred nid. 3061 */ 3062 nid = a; 3063 } 3064 } 3065 /* Next round, evaluate the nodes within max_group. */ 3066 if (!max_faults) 3067 break; 3068 nodes = max_group; 3069 } 3070 return nid; 3071 } 3072 3073 static void task_numa_placement(struct task_struct *p) 3074 __context_unsafe(/* conditional locking */) 3075 { 3076 int seq, nid, max_nid = NUMA_NO_NODE; 3077 unsigned long max_faults = 0; 3078 unsigned long fault_types[2] = { 0, 0 }; 3079 unsigned long total_faults; 3080 u64 runtime, period; 3081 spinlock_t *group_lock = NULL; 3082 struct numa_group *ng; 3083 3084 /* 3085 * The p->mm->numa_scan_seq field gets updated without 3086 * exclusive access. Use READ_ONCE() here to ensure 3087 * that the field is read in a single access: 3088 */ 3089 seq = READ_ONCE(p->mm->numa_scan_seq); 3090 if (p->numa_scan_seq == seq) 3091 return; 3092 p->numa_scan_seq = seq; 3093 p->numa_scan_period_max = task_scan_max(p); 3094 3095 total_faults = p->numa_faults_locality[0] + 3096 p->numa_faults_locality[1]; 3097 runtime = numa_get_avg_runtime(p, &period); 3098 3099 /* If the task is part of a group prevent parallel updates to group stats */ 3100 ng = deref_curr_numa_group(p); 3101 if (ng) { 3102 group_lock = &ng->lock; 3103 spin_lock_irq(group_lock); 3104 } 3105 3106 /* Find the node with the highest number of faults */ 3107 for_each_online_node(nid) { 3108 /* Keep track of the offsets in numa_faults array */ 3109 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx; 3110 unsigned long faults = 0, group_faults = 0; 3111 int priv; 3112 3113 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) { 3114 long diff, f_diff, f_weight; 3115 3116 mem_idx = task_faults_idx(NUMA_MEM, nid, priv); 3117 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv); 3118 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv); 3119 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv); 3120 3121 /* Decay existing window, copy faults since last scan */ 3122 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2; 3123 fault_types[priv] += p->numa_faults[membuf_idx]; 3124 p->numa_faults[membuf_idx] = 0; 3125 3126 /* 3127 * Normalize the faults_from, so all tasks in a group 3128 * count according to CPU use, instead of by the raw 3129 * number of faults. Tasks with little runtime have 3130 * little over-all impact on throughput, and thus their 3131 * faults are less important. 3132 */ 3133 f_weight = div64_u64(runtime << 16, period + 1); 3134 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) / 3135 (total_faults + 1); 3136 f_diff = f_weight - p->numa_faults[cpu_idx] / 2; 3137 p->numa_faults[cpubuf_idx] = 0; 3138 3139 p->numa_faults[mem_idx] += diff; 3140 p->numa_faults[cpu_idx] += f_diff; 3141 faults += p->numa_faults[mem_idx]; 3142 p->total_numa_faults += diff; 3143 if (ng) { 3144 /* 3145 * safe because we can only change our own group 3146 * 3147 * mem_idx represents the offset for a given 3148 * nid and priv in a specific region because it 3149 * is at the beginning of the numa_faults array. 3150 */ 3151 ng->faults[mem_idx] += diff; 3152 ng->faults[cpu_idx] += f_diff; 3153 ng->total_faults += diff; 3154 group_faults += ng->faults[mem_idx]; 3155 } 3156 } 3157 3158 if (!ng) { 3159 if (faults > max_faults) { 3160 max_faults = faults; 3161 max_nid = nid; 3162 } 3163 } else if (group_faults > max_faults) { 3164 max_faults = group_faults; 3165 max_nid = nid; 3166 } 3167 } 3168 3169 /* Cannot migrate task to CPU-less node */ 3170 max_nid = numa_nearest_node(max_nid, N_CPU); 3171 3172 if (ng) { 3173 numa_group_count_active_nodes(ng); 3174 spin_unlock_irq(group_lock); 3175 max_nid = preferred_group_nid(p, max_nid); 3176 } 3177 3178 if (max_faults) { 3179 /* Set the new preferred node */ 3180 if (max_nid != p->numa_preferred_nid) 3181 sched_setnuma(p, max_nid); 3182 } 3183 3184 update_task_scan_period(p, fault_types[0], fault_types[1]); 3185 } 3186 3187 static inline int get_numa_group(struct numa_group *grp) 3188 { 3189 return refcount_inc_not_zero(&grp->refcount); 3190 } 3191 3192 static inline void put_numa_group(struct numa_group *grp) 3193 { 3194 if (refcount_dec_and_test(&grp->refcount)) 3195 kfree_rcu(grp, rcu); 3196 } 3197 3198 static void task_numa_group(struct task_struct *p, int cpupid, int flags, 3199 int *priv) 3200 { 3201 struct numa_group *grp, *my_grp; 3202 struct task_struct *tsk; 3203 bool join = false; 3204 int cpu = cpupid_to_cpu(cpupid); 3205 int i; 3206 3207 if (unlikely(!deref_curr_numa_group(p))) { 3208 unsigned int size = sizeof(struct numa_group) + 3209 NR_NUMA_HINT_FAULT_STATS * 3210 nr_node_ids * sizeof(unsigned long); 3211 3212 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN); 3213 if (!grp) 3214 return; 3215 3216 refcount_set(&grp->refcount, 1); 3217 grp->active_nodes = 1; 3218 grp->max_faults_cpu = 0; 3219 spin_lock_init(&grp->lock); 3220 grp->gid = p->pid; 3221 3222 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) 3223 grp->faults[i] = p->numa_faults[i]; 3224 3225 grp->total_faults = p->total_numa_faults; 3226 3227 grp->nr_tasks++; 3228 rcu_assign_pointer(p->numa_group, grp); 3229 } 3230 3231 rcu_read_lock(); 3232 tsk = READ_ONCE(cpu_rq(cpu)->curr); 3233 3234 if (!cpupid_match_pid(tsk, cpupid)) 3235 goto no_join; 3236 3237 grp = rcu_dereference_all(tsk->numa_group); 3238 if (!grp) 3239 goto no_join; 3240 3241 my_grp = deref_curr_numa_group(p); 3242 if (grp == my_grp) 3243 goto no_join; 3244 3245 /* 3246 * Only join the other group if its bigger; if we're the bigger group, 3247 * the other task will join us. 3248 */ 3249 if (my_grp->nr_tasks > grp->nr_tasks) 3250 goto no_join; 3251 3252 /* 3253 * Tie-break on the grp address. 3254 */ 3255 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp) 3256 goto no_join; 3257 3258 /* Always join threads in the same process. */ 3259 if (tsk->mm == current->mm) 3260 join = true; 3261 3262 /* Simple filter to avoid false positives due to PID collisions */ 3263 if (flags & TNF_SHARED) 3264 join = true; 3265 3266 /* Update priv based on whether false sharing was detected */ 3267 *priv = !join; 3268 3269 if (join && !get_numa_group(grp)) 3270 goto no_join; 3271 3272 rcu_read_unlock(); 3273 3274 if (!join) 3275 return; 3276 3277 WARN_ON_ONCE(irqs_disabled()); 3278 double_lock_irq(&my_grp->lock, &grp->lock); 3279 3280 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) { 3281 my_grp->faults[i] -= p->numa_faults[i]; 3282 grp->faults[i] += p->numa_faults[i]; 3283 } 3284 my_grp->total_faults -= p->total_numa_faults; 3285 grp->total_faults += p->total_numa_faults; 3286 3287 my_grp->nr_tasks--; 3288 grp->nr_tasks++; 3289 3290 spin_unlock(&my_grp->lock); 3291 spin_unlock_irq(&grp->lock); 3292 3293 rcu_assign_pointer(p->numa_group, grp); 3294 3295 put_numa_group(my_grp); 3296 return; 3297 3298 no_join: 3299 rcu_read_unlock(); 3300 return; 3301 } 3302 3303 /* 3304 * Get rid of NUMA statistics associated with a task (either current or dead). 3305 * If @final is set, the task is dead and has reached refcount zero, so we can 3306 * safely free all relevant data structures. Otherwise, there might be 3307 * concurrent reads from places like load balancing and procfs, and we should 3308 * reset the data back to default state without freeing ->numa_faults. 3309 */ 3310 void task_numa_free(struct task_struct *p, bool final) 3311 { 3312 /* safe: p either is current or is being freed by current */ 3313 struct numa_group *grp = rcu_dereference_raw(p->numa_group); 3314 unsigned long *numa_faults = p->numa_faults; 3315 unsigned long flags; 3316 int i; 3317 3318 if (!numa_faults) 3319 return; 3320 3321 if (grp) { 3322 spin_lock_irqsave(&grp->lock, flags); 3323 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) 3324 grp->faults[i] -= p->numa_faults[i]; 3325 grp->total_faults -= p->total_numa_faults; 3326 3327 grp->nr_tasks--; 3328 spin_unlock_irqrestore(&grp->lock, flags); 3329 RCU_INIT_POINTER(p->numa_group, NULL); 3330 put_numa_group(grp); 3331 } 3332 3333 if (final) { 3334 p->numa_faults = NULL; 3335 kfree(numa_faults); 3336 } else { 3337 p->total_numa_faults = 0; 3338 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) 3339 numa_faults[i] = 0; 3340 } 3341 } 3342 3343 /* 3344 * Got a PROT_NONE fault for a page on @node. 3345 */ 3346 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags) 3347 { 3348 struct task_struct *p = current; 3349 bool migrated = flags & TNF_MIGRATED; 3350 int cpu_node = task_node(current); 3351 int local = !!(flags & TNF_FAULT_LOCAL); 3352 struct numa_group *ng; 3353 int priv; 3354 3355 if (!static_branch_likely(&sched_numa_balancing)) 3356 return; 3357 3358 /* for example, ksmd faulting in a user's mm */ 3359 if (!p->mm) 3360 return; 3361 3362 /* 3363 * NUMA faults statistics are unnecessary for the slow memory 3364 * node for memory tiering mode. 3365 */ 3366 if (!node_is_toptier(mem_node) && 3367 (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING || 3368 !cpupid_valid(last_cpupid))) 3369 return; 3370 3371 /* Allocate buffer to track faults on a per-node basis */ 3372 if (unlikely(!p->numa_faults)) { 3373 int size = sizeof(*p->numa_faults) * 3374 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids; 3375 3376 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN); 3377 if (!p->numa_faults) 3378 return; 3379 3380 p->total_numa_faults = 0; 3381 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality)); 3382 } 3383 3384 /* 3385 * First accesses are treated as private, otherwise consider accesses 3386 * to be private if the accessing pid has not changed 3387 */ 3388 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) { 3389 priv = 1; 3390 } else { 3391 priv = cpupid_match_pid(p, last_cpupid); 3392 if (!priv && !(flags & TNF_NO_GROUP)) 3393 task_numa_group(p, last_cpupid, flags, &priv); 3394 } 3395 3396 /* 3397 * If a workload spans multiple NUMA nodes, a shared fault that 3398 * occurs wholly within the set of nodes that the workload is 3399 * actively using should be counted as local. This allows the 3400 * scan rate to slow down when a workload has settled down. 3401 */ 3402 ng = deref_curr_numa_group(p); 3403 if (!priv && !local && ng && ng->active_nodes > 1 && 3404 numa_is_active_node(cpu_node, ng) && 3405 numa_is_active_node(mem_node, ng)) 3406 local = 1; 3407 3408 /* 3409 * Retry to migrate task to preferred node periodically, in case it 3410 * previously failed, or the scheduler moved us. 3411 */ 3412 if (time_after(jiffies, p->numa_migrate_retry)) { 3413 task_numa_placement(p); 3414 numa_migrate_preferred(p); 3415 } 3416 3417 if (migrated) 3418 p->numa_pages_migrated += pages; 3419 if (flags & TNF_MIGRATE_FAIL) 3420 p->numa_faults_locality[2] += pages; 3421 3422 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages; 3423 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages; 3424 p->numa_faults_locality[local] += pages; 3425 } 3426 3427 static void reset_ptenuma_scan(struct task_struct *p) 3428 { 3429 /* 3430 * We only did a read acquisition of the mmap sem, so 3431 * p->mm->numa_scan_seq is written to without exclusive access 3432 * and the update is not guaranteed to be atomic. That's not 3433 * much of an issue though, since this is just used for 3434 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not 3435 * expensive, to avoid any form of compiler optimizations: 3436 */ 3437 WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1); 3438 p->mm->numa_scan_offset = 0; 3439 } 3440 3441 static bool vma_is_accessed(struct mm_struct *mm, struct vm_area_struct *vma) 3442 { 3443 unsigned long pids; 3444 /* 3445 * Allow unconditional access first two times, so that all the (pages) 3446 * of VMAs get prot_none fault introduced irrespective of accesses. 3447 * This is also done to avoid any side effect of task scanning 3448 * amplifying the unfairness of disjoint set of VMAs' access. 3449 */ 3450 if ((READ_ONCE(current->mm->numa_scan_seq) - vma->numab_state->start_scan_seq) < 2) 3451 return true; 3452 3453 pids = vma->numab_state->pids_active[0] | vma->numab_state->pids_active[1]; 3454 if (test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids)) 3455 return true; 3456 3457 /* 3458 * Complete a scan that has already started regardless of PID access, or 3459 * some VMAs may never be scanned in multi-threaded applications: 3460 */ 3461 if (mm->numa_scan_offset > vma->vm_start) { 3462 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_IGNORE_PID); 3463 return true; 3464 } 3465 3466 /* 3467 * This vma has not been accessed for a while, and if the number 3468 * the threads in the same process is low, which means no other 3469 * threads can help scan this vma, force a vma scan. 3470 */ 3471 if (READ_ONCE(mm->numa_scan_seq) > 3472 (vma->numab_state->prev_scan_seq + get_nr_threads(current))) 3473 return true; 3474 3475 return false; 3476 } 3477 3478 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay) 3479 3480 /* 3481 * The expensive part of numa migration is done from task_work context. 3482 * Triggered from task_tick_numa(). 3483 */ 3484 static void task_numa_work(struct callback_head *work) 3485 { 3486 unsigned long migrate, next_scan, now = jiffies; 3487 struct task_struct *p = current; 3488 struct mm_struct *mm = p->mm; 3489 u64 runtime = p->se.sum_exec_runtime; 3490 struct vm_area_struct *vma; 3491 unsigned long start, end; 3492 unsigned long nr_pte_updates = 0; 3493 long pages, virtpages; 3494 struct vma_iterator vmi; 3495 bool vma_pids_skipped; 3496 bool vma_pids_forced = false; 3497 3498 WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work)); 3499 3500 work->next = work; 3501 /* 3502 * Who cares about NUMA placement when they're dying. 3503 * 3504 * NOTE: make sure not to dereference p->mm before this check, 3505 * exit_task_work() happens _after_ exit_mm() so we could be called 3506 * without p->mm even though we still had it when we enqueued this 3507 * work. 3508 */ 3509 if (p->flags & PF_EXITING) 3510 return; 3511 3512 /* 3513 * Memory is pinned to only one NUMA node via cpuset.mems, naturally 3514 * no page can be migrated. 3515 */ 3516 if (cpusets_enabled() && nodes_weight(cpuset_current_mems_allowed) == 1) { 3517 trace_sched_skip_cpuset_numa(current, &cpuset_current_mems_allowed); 3518 return; 3519 } 3520 3521 if (!mm->numa_next_scan) { 3522 mm->numa_next_scan = now + 3523 msecs_to_jiffies(sysctl_numa_balancing_scan_delay); 3524 } 3525 3526 /* 3527 * Enforce maximal scan/migration frequency.. 3528 */ 3529 migrate = mm->numa_next_scan; 3530 if (time_before(now, migrate)) 3531 return; 3532 3533 if (p->numa_scan_period == 0) { 3534 p->numa_scan_period_max = task_scan_max(p); 3535 p->numa_scan_period = task_scan_start(p); 3536 } 3537 3538 next_scan = now + msecs_to_jiffies(p->numa_scan_period); 3539 if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan)) 3540 return; 3541 3542 /* 3543 * Delay this task enough that another task of this mm will likely win 3544 * the next time around. 3545 */ 3546 p->node_stamp += 2 * TICK_NSEC; 3547 3548 pages = sysctl_numa_balancing_scan_size; 3549 pages <<= 20 - PAGE_SHIFT; /* MB in pages */ 3550 virtpages = pages * 8; /* Scan up to this much virtual space */ 3551 if (!pages) 3552 return; 3553 3554 3555 if (!mmap_read_trylock(mm)) 3556 return; 3557 3558 /* 3559 * VMAs are skipped if the current PID has not trapped a fault within 3560 * the VMA recently. Allow scanning to be forced if there is no 3561 * suitable VMA remaining. 3562 */ 3563 vma_pids_skipped = false; 3564 3565 retry_pids: 3566 start = mm->numa_scan_offset; 3567 vma_iter_init(&vmi, mm, start); 3568 vma = vma_next(&vmi); 3569 if (!vma) { 3570 reset_ptenuma_scan(p); 3571 start = 0; 3572 vma_iter_set(&vmi, start); 3573 vma = vma_next(&vmi); 3574 } 3575 3576 for (; vma; vma = vma_next(&vmi)) { 3577 if (!vma_migratable(vma) || !vma_policy_mof(vma) || 3578 is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) { 3579 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_UNSUITABLE); 3580 continue; 3581 } 3582 3583 /* 3584 * Shared library pages mapped by multiple processes are not 3585 * migrated as it is expected they are cache replicated. Avoid 3586 * hinting faults in read-only file-backed mappings or the vDSO 3587 * as migrating the pages will be of marginal benefit. 3588 */ 3589 if (!vma->vm_mm || 3590 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ))) { 3591 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SHARED_RO); 3592 continue; 3593 } 3594 3595 /* 3596 * Skip inaccessible VMAs to avoid any confusion between 3597 * PROT_NONE and NUMA hinting PTEs 3598 */ 3599 if (!vma_is_accessible(vma)) { 3600 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_INACCESSIBLE); 3601 continue; 3602 } 3603 3604 /* Initialise new per-VMA NUMAB state. */ 3605 if (!vma->numab_state) { 3606 struct vma_numab_state *ptr; 3607 3608 ptr = kzalloc_obj(*ptr); 3609 if (!ptr) 3610 continue; 3611 3612 if (cmpxchg(&vma->numab_state, NULL, ptr)) { 3613 kfree(ptr); 3614 continue; 3615 } 3616 3617 vma->numab_state->start_scan_seq = mm->numa_scan_seq; 3618 3619 vma->numab_state->next_scan = now + 3620 msecs_to_jiffies(sysctl_numa_balancing_scan_delay); 3621 3622 /* Reset happens after 4 times scan delay of scan start */ 3623 vma->numab_state->pids_active_reset = vma->numab_state->next_scan + 3624 msecs_to_jiffies(VMA_PID_RESET_PERIOD); 3625 3626 /* 3627 * Ensure prev_scan_seq does not match numa_scan_seq, 3628 * to prevent VMAs being skipped prematurely on the 3629 * first scan: 3630 */ 3631 vma->numab_state->prev_scan_seq = mm->numa_scan_seq - 1; 3632 } 3633 3634 /* 3635 * Scanning the VMAs of short lived tasks add more overhead. So 3636 * delay the scan for new VMAs. 3637 */ 3638 if (mm->numa_scan_seq && time_before(jiffies, 3639 vma->numab_state->next_scan)) { 3640 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SCAN_DELAY); 3641 continue; 3642 } 3643 3644 /* RESET access PIDs regularly for old VMAs. */ 3645 if (mm->numa_scan_seq && 3646 time_after(jiffies, vma->numab_state->pids_active_reset)) { 3647 vma->numab_state->pids_active_reset = vma->numab_state->pids_active_reset + 3648 msecs_to_jiffies(VMA_PID_RESET_PERIOD); 3649 vma->numab_state->pids_active[0] = READ_ONCE(vma->numab_state->pids_active[1]); 3650 vma->numab_state->pids_active[1] = 0; 3651 } 3652 3653 /* Do not rescan VMAs twice within the same sequence. */ 3654 if (vma->numab_state->prev_scan_seq == mm->numa_scan_seq) { 3655 mm->numa_scan_offset = vma->vm_end; 3656 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SEQ_COMPLETED); 3657 continue; 3658 } 3659 3660 /* 3661 * Do not scan the VMA if task has not accessed it, unless no other 3662 * VMA candidate exists. 3663 */ 3664 if (!vma_pids_forced && !vma_is_accessed(mm, vma)) { 3665 vma_pids_skipped = true; 3666 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_PID_INACTIVE); 3667 continue; 3668 } 3669 3670 do { 3671 start = max(start, vma->vm_start); 3672 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE); 3673 end = min(end, vma->vm_end); 3674 nr_pte_updates = change_prot_numa(vma, start, end); 3675 3676 /* 3677 * Try to scan sysctl_numa_balancing_size worth of 3678 * hpages that have at least one present PTE that 3679 * is not already PTE-numa. If the VMA contains 3680 * areas that are unused or already full of prot_numa 3681 * PTEs, scan up to virtpages, to skip through those 3682 * areas faster. 3683 */ 3684 if (nr_pte_updates) 3685 pages -= (end - start) >> PAGE_SHIFT; 3686 virtpages -= (end - start) >> PAGE_SHIFT; 3687 3688 start = end; 3689 if (pages <= 0 || virtpages <= 0) 3690 goto out; 3691 3692 cond_resched(); 3693 } while (end != vma->vm_end); 3694 3695 /* VMA scan is complete, do not scan until next sequence. */ 3696 vma->numab_state->prev_scan_seq = mm->numa_scan_seq; 3697 3698 /* 3699 * Only force scan within one VMA at a time, to limit the 3700 * cost of scanning a potentially uninteresting VMA. 3701 */ 3702 if (vma_pids_forced) 3703 break; 3704 } 3705 3706 /* 3707 * If no VMAs are remaining and VMAs were skipped due to the PID 3708 * not accessing the VMA previously, then force a scan to ensure 3709 * forward progress: 3710 */ 3711 if (!vma && !vma_pids_forced && vma_pids_skipped) { 3712 vma_pids_forced = true; 3713 goto retry_pids; 3714 } 3715 3716 out: 3717 /* 3718 * It is possible to reach the end of the VMA list but the last few 3719 * VMAs are not guaranteed to the vma_migratable. If they are not, we 3720 * would find the !migratable VMA on the next scan but not reset the 3721 * scanner to the start so check it now. 3722 */ 3723 if (vma) 3724 mm->numa_scan_offset = start; 3725 else 3726 reset_ptenuma_scan(p); 3727 mmap_read_unlock(mm); 3728 3729 /* 3730 * Make sure tasks use at least 32x as much time to run other code 3731 * than they used here, to limit NUMA PTE scanning overhead to 3% max. 3732 * Usually update_task_scan_period slows down scanning enough; on an 3733 * overloaded system we need to limit overhead on a per task basis. 3734 */ 3735 if (unlikely(p->se.sum_exec_runtime != runtime)) { 3736 u64 diff = p->se.sum_exec_runtime - runtime; 3737 p->node_stamp += 32 * diff; 3738 } 3739 } 3740 3741 void init_numa_balancing(u64 clone_flags, struct task_struct *p) 3742 { 3743 int mm_users = 0; 3744 struct mm_struct *mm = p->mm; 3745 3746 if (mm) { 3747 mm_users = atomic_read(&mm->mm_users); 3748 if (mm_users == 1) { 3749 mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay); 3750 mm->numa_scan_seq = 0; 3751 } 3752 } 3753 p->node_stamp = 0; 3754 p->numa_scan_seq = mm ? mm->numa_scan_seq : 0; 3755 p->numa_scan_period = sysctl_numa_balancing_scan_delay; 3756 p->numa_migrate_retry = 0; 3757 /* Protect against double add, see task_tick_numa and task_numa_work */ 3758 p->numa_work.next = &p->numa_work; 3759 p->numa_faults = NULL; 3760 p->numa_pages_migrated = 0; 3761 p->total_numa_faults = 0; 3762 RCU_INIT_POINTER(p->numa_group, NULL); 3763 p->last_task_numa_placement = 0; 3764 p->last_sum_exec_runtime = 0; 3765 3766 init_task_work(&p->numa_work, task_numa_work); 3767 3768 /* New address space, reset the preferred nid */ 3769 if (!(clone_flags & CLONE_VM)) { 3770 p->numa_preferred_nid = NUMA_NO_NODE; 3771 return; 3772 } 3773 3774 /* 3775 * New thread, keep existing numa_preferred_nid which should be copied 3776 * already by arch_dup_task_struct but stagger when scans start. 3777 */ 3778 if (mm) { 3779 unsigned int delay; 3780 3781 delay = min_t(unsigned int, task_scan_max(current), 3782 current->numa_scan_period * mm_users * NSEC_PER_MSEC); 3783 delay += 2 * TICK_NSEC; 3784 p->node_stamp = delay; 3785 } 3786 } 3787 3788 /* 3789 * Drive the periodic memory faults.. 3790 */ 3791 static void task_tick_numa(struct rq *rq, struct task_struct *curr) 3792 { 3793 struct callback_head *work = &curr->numa_work; 3794 u64 period, now; 3795 3796 /* 3797 * We don't care about NUMA placement if we don't have memory. 3798 */ 3799 if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work) 3800 return; 3801 3802 /* 3803 * Using runtime rather than walltime has the dual advantage that 3804 * we (mostly) drive the selection from busy threads and that the 3805 * task needs to have done some actual work before we bother with 3806 * NUMA placement. 3807 */ 3808 now = curr->se.sum_exec_runtime; 3809 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC; 3810 3811 if (now > curr->node_stamp + period) { 3812 if (!curr->node_stamp) 3813 curr->numa_scan_period = task_scan_start(curr); 3814 curr->node_stamp += period; 3815 3816 if (!time_before(jiffies, curr->mm->numa_next_scan)) 3817 task_work_add(curr, work, TWA_RESUME); 3818 } 3819 } 3820 3821 static void update_scan_period(struct task_struct *p, int new_cpu) 3822 { 3823 int src_nid = cpu_to_node(task_cpu(p)); 3824 int dst_nid = cpu_to_node(new_cpu); 3825 3826 if (!static_branch_likely(&sched_numa_balancing)) 3827 return; 3828 3829 if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING)) 3830 return; 3831 3832 if (src_nid == dst_nid) 3833 return; 3834 3835 /* 3836 * Allow resets if faults have been trapped before one scan 3837 * has completed. This is most likely due to a new task that 3838 * is pulled cross-node due to wakeups or load balancing. 3839 */ 3840 if (p->numa_scan_seq) { 3841 /* 3842 * Avoid scan adjustments if moving to the preferred 3843 * node or if the task was not previously running on 3844 * the preferred node. 3845 */ 3846 if (dst_nid == p->numa_preferred_nid || 3847 (p->numa_preferred_nid != NUMA_NO_NODE && 3848 src_nid != p->numa_preferred_nid)) 3849 return; 3850 } 3851 3852 p->numa_scan_period = task_scan_start(p); 3853 } 3854 3855 #else /* !CONFIG_NUMA_BALANCING: */ 3856 3857 static void task_tick_numa(struct rq *rq, struct task_struct *curr) 3858 { 3859 } 3860 3861 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p) 3862 { 3863 } 3864 3865 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p) 3866 { 3867 } 3868 3869 static inline void update_scan_period(struct task_struct *p, int new_cpu) 3870 { 3871 } 3872 3873 #endif /* !CONFIG_NUMA_BALANCING */ 3874 3875 static void 3876 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se) 3877 { 3878 update_load_add(&cfs_rq->load, se->load.weight); 3879 if (entity_is_task(se)) { 3880 struct rq *rq = rq_of(cfs_rq); 3881 3882 account_numa_enqueue(rq, task_of(se)); 3883 list_add(&se->group_node, &rq->cfs_tasks); 3884 } 3885 cfs_rq->nr_queued++; 3886 } 3887 3888 static void 3889 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se) 3890 { 3891 update_load_sub(&cfs_rq->load, se->load.weight); 3892 if (entity_is_task(se)) { 3893 account_numa_dequeue(rq_of(cfs_rq), task_of(se)); 3894 list_del_init(&se->group_node); 3895 } 3896 cfs_rq->nr_queued--; 3897 } 3898 3899 /* 3900 * Signed add and clamp on underflow. 3901 * 3902 * Explicitly do a load-store to ensure the intermediate value never hits 3903 * memory. This allows lockless observations without ever seeing the negative 3904 * values. 3905 */ 3906 #define add_positive(_ptr, _val) do { \ 3907 typeof(_ptr) ptr = (_ptr); \ 3908 __signed_scalar_typeof(*ptr) val = (_val); \ 3909 typeof(*ptr) res, var = READ_ONCE(*ptr); \ 3910 \ 3911 res = var + val; \ 3912 \ 3913 if (val < 0 && res > var) \ 3914 res = 0; \ 3915 \ 3916 WRITE_ONCE(*ptr, res); \ 3917 } while (0) 3918 3919 /* 3920 * Remove and clamp on negative, from a local variable. 3921 * 3922 * A variant of sub_positive(), which does not use explicit load-store 3923 * and is thus optimized for local variable updates. 3924 */ 3925 #define lsub_positive(_ptr, _val) do { \ 3926 typeof(_ptr) ptr = (_ptr); \ 3927 *ptr -= min_t(typeof(*ptr), *ptr, _val); \ 3928 } while (0) 3929 3930 3931 /* 3932 * Because of rounding, se->util_sum might ends up being +1 more than 3933 * cfs->util_sum. Although this is not a problem by itself, detaching 3934 * a lot of tasks with the rounding problem between 2 updates of 3935 * util_avg (~1ms) can make cfs->util_sum becoming null whereas 3936 * cfs_util_avg is not. 3937 * 3938 * Check that util_sum is still above its lower bound for the new 3939 * util_avg. Given that period_contrib might have moved since the last 3940 * sync, we are only sure that util_sum must be above or equal to 3941 * util_avg * minimum possible divider 3942 */ 3943 #define __update_sa(sa, name, delta_avg, delta_sum) do { \ 3944 add_positive(&(sa)->name##_avg, delta_avg); \ 3945 add_positive(&(sa)->name##_sum, delta_sum); \ 3946 (sa)->name##_sum = max_t(typeof((sa)->name##_sum), \ 3947 (sa)->name##_sum, \ 3948 (sa)->name##_avg * PELT_MIN_DIVIDER); \ 3949 } while (0) 3950 3951 static inline void 3952 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) 3953 { 3954 __update_sa(&cfs_rq->avg, load, se->avg.load_avg, 3955 se_weight(se) * se->avg.load_sum); 3956 } 3957 3958 static inline void 3959 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) 3960 { 3961 __update_sa(&cfs_rq->avg, load, -se->avg.load_avg, 3962 se_weight(se) * -se->avg.load_sum); 3963 } 3964 3965 static void 3966 rescale_entity(struct sched_entity *se, unsigned long weight, bool rel_vprot) 3967 { 3968 unsigned long old_weight = se->load.weight; 3969 3970 /* 3971 * VRUNTIME 3972 * -------- 3973 * 3974 * COROLLARY #1: The virtual runtime of the entity needs to be 3975 * adjusted if re-weight at !0-lag point. 3976 * 3977 * Proof: For contradiction assume this is not true, so we can 3978 * re-weight without changing vruntime at !0-lag point. 3979 * 3980 * Weight VRuntime Avg-VRuntime 3981 * before w v V 3982 * after w' v' V' 3983 * 3984 * Since lag needs to be preserved through re-weight: 3985 * 3986 * lag = (V - v)*w = (V'- v')*w', where v = v' 3987 * ==> V' = (V - v)*w/w' + v (1) 3988 * 3989 * Let W be the total weight of the entities before reweight, 3990 * since V' is the new weighted average of entities: 3991 * 3992 * V' = (WV + w'v - wv) / (W + w' - w) (2) 3993 * 3994 * by using (1) & (2) we obtain: 3995 * 3996 * (WV + w'v - wv) / (W + w' - w) = (V - v)*w/w' + v 3997 * ==> (WV-Wv+Wv+w'v-wv)/(W+w'-w) = (V - v)*w/w' + v 3998 * ==> (WV - Wv)/(W + w' - w) + v = (V - v)*w/w' + v 3999 * ==> (V - v)*W/(W + w' - w) = (V - v)*w/w' (3) 4000 * 4001 * Since we are doing at !0-lag point which means V != v, we 4002 * can simplify (3): 4003 * 4004 * ==> W / (W + w' - w) = w / w' 4005 * ==> Ww' = Ww + ww' - ww 4006 * ==> W * (w' - w) = w * (w' - w) 4007 * ==> W = w (re-weight indicates w' != w) 4008 * 4009 * So the cfs_rq contains only one entity, hence vruntime of 4010 * the entity @v should always equal to the cfs_rq's weighted 4011 * average vruntime @V, which means we will always re-weight 4012 * at 0-lag point, thus breach assumption. Proof completed. 4013 * 4014 * 4015 * COROLLARY #2: Re-weight does NOT affect weighted average 4016 * vruntime of all the entities. 4017 * 4018 * Proof: According to corollary #1, Eq. (1) should be: 4019 * 4020 * (V - v)*w = (V' - v')*w' 4021 * ==> v' = V' - (V - v)*w/w' (4) 4022 * 4023 * According to the weighted average formula, we have: 4024 * 4025 * V' = (WV - wv + w'v') / (W - w + w') 4026 * = (WV - wv + w'(V' - (V - v)w/w')) / (W - w + w') 4027 * = (WV - wv + w'V' - Vw + wv) / (W - w + w') 4028 * = (WV + w'V' - Vw) / (W - w + w') 4029 * 4030 * ==> V'*(W - w + w') = WV + w'V' - Vw 4031 * ==> V' * (W - w) = (W - w) * V (5) 4032 * 4033 * If the entity is the only one in the cfs_rq, then reweight 4034 * always occurs at 0-lag point, so V won't change. Or else 4035 * there are other entities, hence W != w, then Eq. (5) turns 4036 * into V' = V. So V won't change in either case, proof done. 4037 * 4038 * 4039 * So according to corollary #1 & #2, the effect of re-weight 4040 * on vruntime should be: 4041 * 4042 * v' = V' - (V - v) * w / w' (4) 4043 * = V - (V - v) * w / w' 4044 * = V - vl * w / w' 4045 * = V - vl' 4046 */ 4047 se->vlag = div64_long(se->vlag * old_weight, weight); 4048 4049 /* 4050 * DEADLINE 4051 * -------- 4052 * 4053 * When the weight changes, the virtual time slope changes and 4054 * we should adjust the relative virtual deadline accordingly. 4055 * 4056 * d' = v' + (d - v)*w/w' 4057 * = V' - (V - v)*w/w' + (d - v)*w/w' 4058 * = V - (V - v)*w/w' + (d - v)*w/w' 4059 * = V + (d - V)*w/w' 4060 */ 4061 if (se->rel_deadline) 4062 se->deadline = div64_long(se->deadline * old_weight, weight); 4063 4064 if (rel_vprot) 4065 se->vprot = div64_long(se->vprot * old_weight, weight); 4066 } 4067 4068 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, 4069 unsigned long weight) 4070 { 4071 bool curr = cfs_rq->curr == se; 4072 bool rel_vprot = false; 4073 u64 avruntime = 0; 4074 4075 if (se->on_rq) { 4076 /* commit outstanding execution time */ 4077 update_curr(cfs_rq); 4078 avruntime = avg_vruntime(cfs_rq); 4079 se->vlag = entity_lag(cfs_rq, se, avruntime); 4080 se->deadline -= avruntime; 4081 se->rel_deadline = 1; 4082 if (curr && protect_slice(se)) { 4083 se->vprot -= avruntime; 4084 rel_vprot = true; 4085 } 4086 4087 cfs_rq->nr_queued--; 4088 if (!curr) 4089 __dequeue_entity(cfs_rq, se); 4090 update_load_sub(&cfs_rq->load, se->load.weight); 4091 } 4092 dequeue_load_avg(cfs_rq, se); 4093 4094 rescale_entity(se, weight, rel_vprot); 4095 4096 update_load_set(&se->load, weight); 4097 4098 do { 4099 u32 divider = get_pelt_divider(&se->avg); 4100 se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider); 4101 } while (0); 4102 4103 enqueue_load_avg(cfs_rq, se); 4104 if (se->on_rq) { 4105 if (rel_vprot) 4106 se->vprot += avruntime; 4107 se->deadline += avruntime; 4108 se->rel_deadline = 0; 4109 se->vruntime = avruntime - se->vlag; 4110 4111 update_load_add(&cfs_rq->load, se->load.weight); 4112 if (!curr) 4113 __enqueue_entity(cfs_rq, se); 4114 cfs_rq->nr_queued++; 4115 } 4116 } 4117 4118 static void reweight_task_fair(struct rq *rq, struct task_struct *p, 4119 const struct load_weight *lw) 4120 { 4121 struct sched_entity *se = &p->se; 4122 struct cfs_rq *cfs_rq = cfs_rq_of(se); 4123 struct load_weight *load = &se->load; 4124 4125 reweight_entity(cfs_rq, se, lw->weight); 4126 load->inv_weight = lw->inv_weight; 4127 } 4128 4129 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq); 4130 4131 #ifdef CONFIG_FAIR_GROUP_SCHED 4132 /* 4133 * All this does is approximate the hierarchical proportion which includes that 4134 * global sum we all love to hate. 4135 * 4136 * That is, the weight of a group entity, is the proportional share of the 4137 * group weight based on the group runqueue weights. That is: 4138 * 4139 * tg->weight * grq->load.weight 4140 * ge->load.weight = ----------------------------- (1) 4141 * \Sum grq->load.weight 4142 * 4143 * Now, because computing that sum is prohibitively expensive to compute (been 4144 * there, done that) we approximate it with this average stuff. The average 4145 * moves slower and therefore the approximation is cheaper and more stable. 4146 * 4147 * So instead of the above, we substitute: 4148 * 4149 * grq->load.weight -> grq->avg.load_avg (2) 4150 * 4151 * which yields the following: 4152 * 4153 * tg->weight * grq->avg.load_avg 4154 * ge->load.weight = ------------------------------ (3) 4155 * tg->load_avg 4156 * 4157 * Where: tg->load_avg ~= \Sum grq->avg.load_avg 4158 * 4159 * That is shares_avg, and it is right (given the approximation (2)). 4160 * 4161 * The problem with it is that because the average is slow -- it was designed 4162 * to be exactly that of course -- this leads to transients in boundary 4163 * conditions. In specific, the case where the group was idle and we start the 4164 * one task. It takes time for our CPU's grq->avg.load_avg to build up, 4165 * yielding bad latency etc.. 4166 * 4167 * Now, in that special case (1) reduces to: 4168 * 4169 * tg->weight * grq->load.weight 4170 * ge->load.weight = ----------------------------- = tg->weight (4) 4171 * grp->load.weight 4172 * 4173 * That is, the sum collapses because all other CPUs are idle; the UP scenario. 4174 * 4175 * So what we do is modify our approximation (3) to approach (4) in the (near) 4176 * UP case, like: 4177 * 4178 * ge->load.weight = 4179 * 4180 * tg->weight * grq->load.weight 4181 * --------------------------------------------------- (5) 4182 * tg->load_avg - grq->avg.load_avg + grq->load.weight 4183 * 4184 * But because grq->load.weight can drop to 0, resulting in a divide by zero, 4185 * we need to use grq->avg.load_avg as its lower bound, which then gives: 4186 * 4187 * 4188 * tg->weight * grq->load.weight 4189 * ge->load.weight = ----------------------------- (6) 4190 * tg_load_avg' 4191 * 4192 * Where: 4193 * 4194 * tg_load_avg' = tg->load_avg - grq->avg.load_avg + 4195 * max(grq->load.weight, grq->avg.load_avg) 4196 * 4197 * And that is shares_weight and is icky. In the (near) UP case it approaches 4198 * (4) while in the normal case it approaches (3). It consistently 4199 * overestimates the ge->load.weight and therefore: 4200 * 4201 * \Sum ge->load.weight >= tg->weight 4202 * 4203 * hence icky! 4204 */ 4205 static long calc_group_shares(struct cfs_rq *cfs_rq) 4206 { 4207 long tg_weight, tg_shares, load, shares; 4208 struct task_group *tg = cfs_rq->tg; 4209 4210 tg_shares = READ_ONCE(tg->shares); 4211 4212 load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg); 4213 4214 tg_weight = atomic_long_read(&tg->load_avg); 4215 4216 /* Ensure tg_weight >= load */ 4217 tg_weight -= cfs_rq->tg_load_avg_contrib; 4218 tg_weight += load; 4219 4220 shares = (tg_shares * load); 4221 if (tg_weight) 4222 shares /= tg_weight; 4223 4224 /* 4225 * MIN_SHARES has to be unscaled here to support per-CPU partitioning 4226 * of a group with small tg->shares value. It is a floor value which is 4227 * assigned as a minimum load.weight to the sched_entity representing 4228 * the group on a CPU. 4229 * 4230 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024 4231 * on an 8-core system with 8 tasks each runnable on one CPU shares has 4232 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In 4233 * case no task is runnable on a CPU MIN_SHARES=2 should be returned 4234 * instead of 0. 4235 */ 4236 return clamp_t(long, shares, MIN_SHARES, tg_shares); 4237 } 4238 4239 /* 4240 * Recomputes the group entity based on the current state of its group 4241 * runqueue. 4242 */ 4243 static void update_cfs_group(struct sched_entity *se) 4244 { 4245 struct cfs_rq *gcfs_rq = group_cfs_rq(se); 4246 long shares; 4247 4248 /* 4249 * When a group becomes empty, preserve its weight. This matters for 4250 * DELAY_DEQUEUE. 4251 */ 4252 if (!gcfs_rq || !gcfs_rq->load.weight) 4253 return; 4254 4255 shares = calc_group_shares(gcfs_rq); 4256 if (unlikely(se->load.weight != shares)) 4257 reweight_entity(cfs_rq_of(se), se, shares); 4258 } 4259 4260 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 4261 static inline void update_cfs_group(struct sched_entity *se) 4262 { 4263 } 4264 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 4265 4266 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags) 4267 { 4268 struct rq *rq = rq_of(cfs_rq); 4269 4270 if (&rq->cfs == cfs_rq) { 4271 /* 4272 * There are a few boundary cases this might miss but it should 4273 * get called often enough that that should (hopefully) not be 4274 * a real problem. 4275 * 4276 * It will not get called when we go idle, because the idle 4277 * thread is a different class (!fair), nor will the utilization 4278 * number include things like RT tasks. 4279 * 4280 * As is, the util number is not freq-invariant (we'd have to 4281 * implement arch_scale_freq_capacity() for that). 4282 * 4283 * See cpu_util_cfs(). 4284 */ 4285 cpufreq_update_util(rq, flags); 4286 } 4287 } 4288 4289 static inline bool load_avg_is_decayed(struct sched_avg *sa) 4290 { 4291 if (sa->load_sum) 4292 return false; 4293 4294 if (sa->util_sum) 4295 return false; 4296 4297 if (sa->runnable_sum) 4298 return false; 4299 4300 /* 4301 * _avg must be null when _sum are null because _avg = _sum / divider 4302 * Make sure that rounding and/or propagation of PELT values never 4303 * break this. 4304 */ 4305 WARN_ON_ONCE(sa->load_avg || 4306 sa->util_avg || 4307 sa->runnable_avg); 4308 4309 return true; 4310 } 4311 4312 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq) 4313 { 4314 return u64_u32_load_copy(cfs_rq->avg.last_update_time, 4315 cfs_rq->last_update_time_copy); 4316 } 4317 #ifdef CONFIG_FAIR_GROUP_SCHED 4318 /* 4319 * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list 4320 * immediately before a parent cfs_rq, and cfs_rqs are removed from the list 4321 * bottom-up, we only have to test whether the cfs_rq before us on the list 4322 * is our child. 4323 * If cfs_rq is not on the list, test whether a child needs its to be added to 4324 * connect a branch to the tree * (see list_add_leaf_cfs_rq() for details). 4325 */ 4326 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq) 4327 { 4328 struct cfs_rq *prev_cfs_rq; 4329 struct list_head *prev; 4330 struct rq *rq = rq_of(cfs_rq); 4331 4332 if (cfs_rq->on_list) { 4333 prev = cfs_rq->leaf_cfs_rq_list.prev; 4334 } else { 4335 prev = rq->tmp_alone_branch; 4336 } 4337 4338 if (prev == &rq->leaf_cfs_rq_list) 4339 return false; 4340 4341 prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list); 4342 4343 return (prev_cfs_rq->tg->parent == cfs_rq->tg); 4344 } 4345 4346 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq) 4347 { 4348 if (cfs_rq->load.weight) 4349 return false; 4350 4351 if (!load_avg_is_decayed(&cfs_rq->avg)) 4352 return false; 4353 4354 if (child_cfs_rq_on_list(cfs_rq)) 4355 return false; 4356 4357 if (cfs_rq->tg_load_avg_contrib) 4358 return false; 4359 4360 return true; 4361 } 4362 4363 /** 4364 * update_tg_load_avg - update the tg's load avg 4365 * @cfs_rq: the cfs_rq whose avg changed 4366 * 4367 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load. 4368 * However, because tg->load_avg is a global value there are performance 4369 * considerations. 4370 * 4371 * In order to avoid having to look at the other cfs_rq's, we use a 4372 * differential update where we store the last value we propagated. This in 4373 * turn allows skipping updates if the differential is 'small'. 4374 * 4375 * Updating tg's load_avg is necessary before update_cfs_share(). 4376 */ 4377 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) 4378 { 4379 long delta; 4380 u64 now; 4381 4382 /* 4383 * No need to update load_avg for root_task_group as it is not used. 4384 */ 4385 if (cfs_rq->tg == &root_task_group) 4386 return; 4387 4388 /* rq has been offline and doesn't contribute to the share anymore: */ 4389 if (!cpu_active(cpu_of(rq_of(cfs_rq)))) 4390 return; 4391 4392 /* 4393 * For migration heavy workloads, access to tg->load_avg can be 4394 * unbound. Limit the update rate to at most once per ms. 4395 */ 4396 now = sched_clock_cpu(cpu_of(rq_of(cfs_rq))); 4397 if (now - cfs_rq->last_update_tg_load_avg < NSEC_PER_MSEC) 4398 return; 4399 4400 delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib; 4401 if (abs(delta) > cfs_rq->tg_load_avg_contrib / 64) { 4402 atomic_long_add(delta, &cfs_rq->tg->load_avg); 4403 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg; 4404 cfs_rq->last_update_tg_load_avg = now; 4405 } 4406 } 4407 4408 static inline void clear_tg_load_avg(struct cfs_rq *cfs_rq) 4409 { 4410 long delta; 4411 u64 now; 4412 4413 /* 4414 * No need to update load_avg for root_task_group, as it is not used. 4415 */ 4416 if (cfs_rq->tg == &root_task_group) 4417 return; 4418 4419 now = sched_clock_cpu(cpu_of(rq_of(cfs_rq))); 4420 delta = 0 - cfs_rq->tg_load_avg_contrib; 4421 atomic_long_add(delta, &cfs_rq->tg->load_avg); 4422 cfs_rq->tg_load_avg_contrib = 0; 4423 cfs_rq->last_update_tg_load_avg = now; 4424 } 4425 4426 /* CPU offline callback: */ 4427 static void __maybe_unused clear_tg_offline_cfs_rqs(struct rq *rq) 4428 { 4429 struct task_group *tg; 4430 4431 lockdep_assert_rq_held(rq); 4432 4433 /* 4434 * The rq clock has already been updated in 4435 * set_rq_offline(), so we should skip updating 4436 * the rq clock again in unthrottle_cfs_rq(). 4437 */ 4438 rq_clock_start_loop_update(rq); 4439 4440 rcu_read_lock(); 4441 list_for_each_entry_rcu(tg, &task_groups, list) { 4442 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)]; 4443 4444 clear_tg_load_avg(cfs_rq); 4445 } 4446 rcu_read_unlock(); 4447 4448 rq_clock_stop_loop_update(rq); 4449 } 4450 4451 /* 4452 * Called within set_task_rq() right before setting a task's CPU. The 4453 * caller only guarantees p->pi_lock is held; no other assumptions, 4454 * including the state of rq->lock, should be made. 4455 */ 4456 void set_task_rq_fair(struct sched_entity *se, 4457 struct cfs_rq *prev, struct cfs_rq *next) 4458 { 4459 u64 p_last_update_time; 4460 u64 n_last_update_time; 4461 4462 if (!sched_feat(ATTACH_AGE_LOAD)) 4463 return; 4464 4465 /* 4466 * We are supposed to update the task to "current" time, then its up to 4467 * date and ready to go to new CPU/cfs_rq. But we have difficulty in 4468 * getting what current time is, so simply throw away the out-of-date 4469 * time. This will result in the wakee task is less decayed, but giving 4470 * the wakee more load sounds not bad. 4471 */ 4472 if (!(se->avg.last_update_time && prev)) 4473 return; 4474 4475 p_last_update_time = cfs_rq_last_update_time(prev); 4476 n_last_update_time = cfs_rq_last_update_time(next); 4477 4478 __update_load_avg_blocked_se(p_last_update_time, se); 4479 se->avg.last_update_time = n_last_update_time; 4480 } 4481 4482 /* 4483 * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to 4484 * propagate its contribution. The key to this propagation is the invariant 4485 * that for each group: 4486 * 4487 * ge->avg == grq->avg (1) 4488 * 4489 * _IFF_ we look at the pure running and runnable sums. Because they 4490 * represent the very same entity, just at different points in the hierarchy. 4491 * 4492 * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial 4493 * and simply copies the running/runnable sum over (but still wrong, because 4494 * the group entity and group rq do not have their PELT windows aligned). 4495 * 4496 * However, update_tg_cfs_load() is more complex. So we have: 4497 * 4498 * ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg (2) 4499 * 4500 * And since, like util, the runnable part should be directly transferable, 4501 * the following would _appear_ to be the straight forward approach: 4502 * 4503 * grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg (3) 4504 * 4505 * And per (1) we have: 4506 * 4507 * ge->avg.runnable_avg == grq->avg.runnable_avg 4508 * 4509 * Which gives: 4510 * 4511 * ge->load.weight * grq->avg.load_avg 4512 * ge->avg.load_avg = ----------------------------------- (4) 4513 * grq->load.weight 4514 * 4515 * Except that is wrong! 4516 * 4517 * Because while for entities historical weight is not important and we 4518 * really only care about our future and therefore can consider a pure 4519 * runnable sum, runqueues can NOT do this. 4520 * 4521 * We specifically want runqueues to have a load_avg that includes 4522 * historical weights. Those represent the blocked load, the load we expect 4523 * to (shortly) return to us. This only works by keeping the weights as 4524 * integral part of the sum. We therefore cannot decompose as per (3). 4525 * 4526 * Another reason this doesn't work is that runnable isn't a 0-sum entity. 4527 * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the 4528 * rq itself is runnable anywhere between 2/3 and 1 depending on how the 4529 * runnable section of these tasks overlap (or not). If they were to perfectly 4530 * align the rq as a whole would be runnable 2/3 of the time. If however we 4531 * always have at least 1 runnable task, the rq as a whole is always runnable. 4532 * 4533 * So we'll have to approximate.. :/ 4534 * 4535 * Given the constraint: 4536 * 4537 * ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX 4538 * 4539 * We can construct a rule that adds runnable to a rq by assuming minimal 4540 * overlap. 4541 * 4542 * On removal, we'll assume each task is equally runnable; which yields: 4543 * 4544 * grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight 4545 * 4546 * XXX: only do this for the part of runnable > running ? 4547 * 4548 */ 4549 static inline void 4550 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq) 4551 { 4552 long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg; 4553 u32 new_sum, divider; 4554 4555 /* Nothing to update */ 4556 if (!delta_avg) 4557 return; 4558 4559 /* 4560 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se. 4561 * See ___update_load_avg() for details. 4562 */ 4563 divider = get_pelt_divider(&cfs_rq->avg); 4564 4565 /* Set new sched_entity's utilization */ 4566 se->avg.util_avg = gcfs_rq->avg.util_avg; 4567 new_sum = se->avg.util_avg * divider; 4568 delta_sum = (long)new_sum - (long)se->avg.util_sum; 4569 se->avg.util_sum = new_sum; 4570 4571 /* Update parent cfs_rq utilization */ 4572 __update_sa(&cfs_rq->avg, util, delta_avg, delta_sum); 4573 } 4574 4575 static inline void 4576 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq) 4577 { 4578 long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg; 4579 u32 new_sum, divider; 4580 4581 /* Nothing to update */ 4582 if (!delta_avg) 4583 return; 4584 4585 /* 4586 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se. 4587 * See ___update_load_avg() for details. 4588 */ 4589 divider = get_pelt_divider(&cfs_rq->avg); 4590 4591 /* Set new sched_entity's runnable */ 4592 se->avg.runnable_avg = gcfs_rq->avg.runnable_avg; 4593 new_sum = se->avg.runnable_avg * divider; 4594 delta_sum = (long)new_sum - (long)se->avg.runnable_sum; 4595 se->avg.runnable_sum = new_sum; 4596 4597 /* Update parent cfs_rq runnable */ 4598 __update_sa(&cfs_rq->avg, runnable, delta_avg, delta_sum); 4599 } 4600 4601 static inline void 4602 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq) 4603 { 4604 long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum; 4605 unsigned long load_avg; 4606 u64 load_sum = 0; 4607 s64 delta_sum; 4608 u32 divider; 4609 4610 if (!runnable_sum) 4611 return; 4612 4613 gcfs_rq->prop_runnable_sum = 0; 4614 4615 /* 4616 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se. 4617 * See ___update_load_avg() for details. 4618 */ 4619 divider = get_pelt_divider(&cfs_rq->avg); 4620 4621 if (runnable_sum >= 0) { 4622 /* 4623 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until 4624 * the CPU is saturated running == runnable. 4625 */ 4626 runnable_sum += se->avg.load_sum; 4627 runnable_sum = min_t(long, runnable_sum, divider); 4628 } else { 4629 /* 4630 * Estimate the new unweighted runnable_sum of the gcfs_rq by 4631 * assuming all tasks are equally runnable. 4632 */ 4633 if (scale_load_down(gcfs_rq->load.weight)) { 4634 load_sum = div_u64(gcfs_rq->avg.load_sum, 4635 scale_load_down(gcfs_rq->load.weight)); 4636 } 4637 4638 /* But make sure to not inflate se's runnable */ 4639 runnable_sum = min(se->avg.load_sum, load_sum); 4640 } 4641 4642 /* 4643 * runnable_sum can't be lower than running_sum 4644 * Rescale running sum to be in the same range as runnable sum 4645 * running_sum is in [0 : LOAD_AVG_MAX << SCHED_CAPACITY_SHIFT] 4646 * runnable_sum is in [0 : LOAD_AVG_MAX] 4647 */ 4648 running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT; 4649 runnable_sum = max(runnable_sum, running_sum); 4650 4651 load_sum = se_weight(se) * runnable_sum; 4652 load_avg = div_u64(load_sum, divider); 4653 4654 delta_avg = load_avg - se->avg.load_avg; 4655 if (!delta_avg) 4656 return; 4657 4658 delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum; 4659 4660 se->avg.load_sum = runnable_sum; 4661 se->avg.load_avg = load_avg; 4662 __update_sa(&cfs_rq->avg, load, delta_avg, delta_sum); 4663 } 4664 4665 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) 4666 { 4667 cfs_rq->propagate = 1; 4668 cfs_rq->prop_runnable_sum += runnable_sum; 4669 } 4670 4671 /* Update task and its cfs_rq load average */ 4672 static inline int propagate_entity_load_avg(struct sched_entity *se) 4673 { 4674 struct cfs_rq *cfs_rq, *gcfs_rq; 4675 4676 if (entity_is_task(se)) 4677 return 0; 4678 4679 gcfs_rq = group_cfs_rq(se); 4680 if (!gcfs_rq->propagate) 4681 return 0; 4682 4683 gcfs_rq->propagate = 0; 4684 4685 cfs_rq = cfs_rq_of(se); 4686 4687 add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum); 4688 4689 update_tg_cfs_util(cfs_rq, se, gcfs_rq); 4690 update_tg_cfs_runnable(cfs_rq, se, gcfs_rq); 4691 update_tg_cfs_load(cfs_rq, se, gcfs_rq); 4692 4693 trace_pelt_cfs_tp(cfs_rq); 4694 trace_pelt_se_tp(se); 4695 4696 return 1; 4697 } 4698 4699 /* 4700 * Check if we need to update the load and the utilization of a blocked 4701 * group_entity: 4702 */ 4703 static inline bool skip_blocked_update(struct sched_entity *se) 4704 { 4705 struct cfs_rq *gcfs_rq = group_cfs_rq(se); 4706 4707 /* 4708 * If sched_entity still have not zero load or utilization, we have to 4709 * decay it: 4710 */ 4711 if (se->avg.load_avg || se->avg.util_avg) 4712 return false; 4713 4714 /* 4715 * If there is a pending propagation, we have to update the load and 4716 * the utilization of the sched_entity: 4717 */ 4718 if (gcfs_rq->propagate) 4719 return false; 4720 4721 /* 4722 * Otherwise, the load and the utilization of the sched_entity is 4723 * already zero and there is no pending propagation, so it will be a 4724 * waste of time to try to decay it: 4725 */ 4726 return true; 4727 } 4728 4729 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 4730 4731 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {} 4732 4733 static inline void clear_tg_offline_cfs_rqs(struct rq *rq) {} 4734 4735 static inline int propagate_entity_load_avg(struct sched_entity *se) 4736 { 4737 return 0; 4738 } 4739 4740 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {} 4741 4742 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 4743 4744 #ifdef CONFIG_NO_HZ_COMMON 4745 static inline void migrate_se_pelt_lag(struct sched_entity *se) 4746 { 4747 u64 throttled = 0, now, lut; 4748 struct cfs_rq *cfs_rq; 4749 struct rq *rq; 4750 bool is_idle; 4751 4752 if (load_avg_is_decayed(&se->avg)) 4753 return; 4754 4755 cfs_rq = cfs_rq_of(se); 4756 rq = rq_of(cfs_rq); 4757 4758 rcu_read_lock(); 4759 is_idle = is_idle_task(rcu_dereference_all(rq->curr)); 4760 rcu_read_unlock(); 4761 4762 /* 4763 * The lag estimation comes with a cost we don't want to pay all the 4764 * time. Hence, limiting to the case where the source CPU is idle and 4765 * we know we are at the greatest risk to have an outdated clock. 4766 */ 4767 if (!is_idle) 4768 return; 4769 4770 /* 4771 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where: 4772 * 4773 * last_update_time (the cfs_rq's last_update_time) 4774 * = cfs_rq_clock_pelt()@cfs_rq_idle 4775 * = rq_clock_pelt()@cfs_rq_idle 4776 * - cfs->throttled_clock_pelt_time@cfs_rq_idle 4777 * 4778 * cfs_idle_lag (delta between rq's update and cfs_rq's update) 4779 * = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle 4780 * 4781 * rq_idle_lag (delta between now and rq's update) 4782 * = sched_clock_cpu() - rq_clock()@rq_idle 4783 * 4784 * We can then write: 4785 * 4786 * now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time + 4787 * sched_clock_cpu() - rq_clock()@rq_idle 4788 * Where: 4789 * rq_clock_pelt()@rq_idle is rq->clock_pelt_idle 4790 * rq_clock()@rq_idle is rq->clock_idle 4791 * cfs->throttled_clock_pelt_time@cfs_rq_idle 4792 * is cfs_rq->throttled_pelt_idle 4793 */ 4794 4795 #ifdef CONFIG_CFS_BANDWIDTH 4796 throttled = u64_u32_load(cfs_rq->throttled_pelt_idle); 4797 /* The clock has been stopped for throttling */ 4798 if (throttled == U64_MAX) 4799 return; 4800 #endif 4801 now = u64_u32_load(rq->clock_pelt_idle); 4802 /* 4803 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case 4804 * is observed the old clock_pelt_idle value and the new clock_idle, 4805 * which lead to an underestimation. The opposite would lead to an 4806 * overestimation. 4807 */ 4808 smp_rmb(); 4809 lut = cfs_rq_last_update_time(cfs_rq); 4810 4811 now -= throttled; 4812 if (now < lut) 4813 /* 4814 * cfs_rq->avg.last_update_time is more recent than our 4815 * estimation, let's use it. 4816 */ 4817 now = lut; 4818 else 4819 now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle); 4820 4821 __update_load_avg_blocked_se(now, se); 4822 } 4823 #else /* !CONFIG_NO_HZ_COMMON: */ 4824 static void migrate_se_pelt_lag(struct sched_entity *se) {} 4825 #endif /* !CONFIG_NO_HZ_COMMON */ 4826 4827 /** 4828 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages 4829 * @now: current time, as per cfs_rq_clock_pelt() 4830 * @cfs_rq: cfs_rq to update 4831 * 4832 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable) 4833 * avg. The immediate corollary is that all (fair) tasks must be attached. 4834 * 4835 * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example. 4836 * 4837 * Return: true if the load decayed or we removed load. 4838 * 4839 * Since both these conditions indicate a changed cfs_rq->avg.load we should 4840 * call update_tg_load_avg() when this function returns true. 4841 */ 4842 static inline int 4843 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq) 4844 { 4845 unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0; 4846 struct sched_avg *sa = &cfs_rq->avg; 4847 int decayed = 0; 4848 4849 if (cfs_rq->removed.nr) { 4850 unsigned long r; 4851 u32 divider = get_pelt_divider(&cfs_rq->avg); 4852 4853 raw_spin_lock(&cfs_rq->removed.lock); 4854 swap(cfs_rq->removed.util_avg, removed_util); 4855 swap(cfs_rq->removed.load_avg, removed_load); 4856 swap(cfs_rq->removed.runnable_avg, removed_runnable); 4857 cfs_rq->removed.nr = 0; 4858 raw_spin_unlock(&cfs_rq->removed.lock); 4859 4860 r = removed_load; 4861 __update_sa(sa, load, -r, -r*divider); 4862 4863 r = removed_util; 4864 __update_sa(sa, util, -r, -r*divider); 4865 4866 r = removed_runnable; 4867 __update_sa(sa, runnable, -r, -r*divider); 4868 4869 /* 4870 * removed_runnable is the unweighted version of removed_load so we 4871 * can use it to estimate removed_load_sum. 4872 */ 4873 add_tg_cfs_propagate(cfs_rq, 4874 -(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT); 4875 4876 decayed = 1; 4877 } 4878 4879 decayed |= __update_load_avg_cfs_rq(now, cfs_rq); 4880 u64_u32_store_copy(sa->last_update_time, 4881 cfs_rq->last_update_time_copy, 4882 sa->last_update_time); 4883 return decayed; 4884 } 4885 4886 /** 4887 * attach_entity_load_avg - attach this entity to its cfs_rq load avg 4888 * @cfs_rq: cfs_rq to attach to 4889 * @se: sched_entity to attach 4890 * 4891 * Must call update_cfs_rq_load_avg() before this, since we rely on 4892 * cfs_rq->avg.last_update_time being current. 4893 */ 4894 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) 4895 { 4896 /* 4897 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se. 4898 * See ___update_load_avg() for details. 4899 */ 4900 u32 divider = get_pelt_divider(&cfs_rq->avg); 4901 4902 /* 4903 * When we attach the @se to the @cfs_rq, we must align the decay 4904 * window because without that, really weird and wonderful things can 4905 * happen. 4906 * 4907 * XXX illustrate 4908 */ 4909 se->avg.last_update_time = cfs_rq->avg.last_update_time; 4910 se->avg.period_contrib = cfs_rq->avg.period_contrib; 4911 4912 /* 4913 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new 4914 * period_contrib. This isn't strictly correct, but since we're 4915 * entirely outside of the PELT hierarchy, nobody cares if we truncate 4916 * _sum a little. 4917 */ 4918 se->avg.util_sum = se->avg.util_avg * divider; 4919 4920 se->avg.runnable_sum = se->avg.runnable_avg * divider; 4921 4922 se->avg.load_sum = se->avg.load_avg * divider; 4923 if (se_weight(se) < se->avg.load_sum) 4924 se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se)); 4925 else 4926 se->avg.load_sum = 1; 4927 4928 enqueue_load_avg(cfs_rq, se); 4929 cfs_rq->avg.util_avg += se->avg.util_avg; 4930 cfs_rq->avg.util_sum += se->avg.util_sum; 4931 cfs_rq->avg.runnable_avg += se->avg.runnable_avg; 4932 cfs_rq->avg.runnable_sum += se->avg.runnable_sum; 4933 4934 add_tg_cfs_propagate(cfs_rq, se->avg.load_sum); 4935 4936 cfs_rq_util_change(cfs_rq, 0); 4937 4938 trace_pelt_cfs_tp(cfs_rq); 4939 } 4940 4941 /** 4942 * detach_entity_load_avg - detach this entity from its cfs_rq load avg 4943 * @cfs_rq: cfs_rq to detach from 4944 * @se: sched_entity to detach 4945 * 4946 * Must call update_cfs_rq_load_avg() before this, since we rely on 4947 * cfs_rq->avg.last_update_time being current. 4948 */ 4949 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) 4950 { 4951 dequeue_load_avg(cfs_rq, se); 4952 __update_sa(&cfs_rq->avg, util, -se->avg.util_avg, -se->avg.util_sum); 4953 __update_sa(&cfs_rq->avg, runnable, -se->avg.runnable_avg, -se->avg.runnable_sum); 4954 4955 add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum); 4956 4957 cfs_rq_util_change(cfs_rq, 0); 4958 4959 trace_pelt_cfs_tp(cfs_rq); 4960 } 4961 4962 /* 4963 * Optional action to be done while updating the load average 4964 */ 4965 #define UPDATE_TG 0x1 4966 #define SKIP_AGE_LOAD 0x2 4967 #define DO_ATTACH 0x4 4968 #define DO_DETACH 0x8 4969 4970 /* Update task and its cfs_rq load average */ 4971 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 4972 { 4973 u64 now = cfs_rq_clock_pelt(cfs_rq); 4974 int decayed; 4975 4976 /* 4977 * Track task load average for carrying it to new CPU after migrated, and 4978 * track group sched_entity load average for task_h_load calculation in migration 4979 */ 4980 if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD)) 4981 __update_load_avg_se(now, cfs_rq, se); 4982 4983 decayed = update_cfs_rq_load_avg(now, cfs_rq); 4984 decayed |= propagate_entity_load_avg(se); 4985 4986 if (!se->avg.last_update_time && (flags & DO_ATTACH)) { 4987 4988 /* 4989 * DO_ATTACH means we're here from enqueue_entity(). 4990 * !last_update_time means we've passed through 4991 * migrate_task_rq_fair() indicating we migrated. 4992 * 4993 * IOW we're enqueueing a task on a new CPU. 4994 */ 4995 attach_entity_load_avg(cfs_rq, se); 4996 update_tg_load_avg(cfs_rq); 4997 4998 } else if (flags & DO_DETACH) { 4999 /* 5000 * DO_DETACH means we're here from dequeue_entity() 5001 * and we are migrating task out of the CPU. 5002 */ 5003 detach_entity_load_avg(cfs_rq, se); 5004 update_tg_load_avg(cfs_rq); 5005 } else if (decayed) { 5006 cfs_rq_util_change(cfs_rq, 0); 5007 5008 if (flags & UPDATE_TG) 5009 update_tg_load_avg(cfs_rq); 5010 } 5011 } 5012 5013 /* 5014 * Synchronize entity load avg of dequeued entity without locking 5015 * the previous rq. 5016 */ 5017 static void sync_entity_load_avg(struct sched_entity *se) 5018 { 5019 struct cfs_rq *cfs_rq = cfs_rq_of(se); 5020 u64 last_update_time; 5021 5022 last_update_time = cfs_rq_last_update_time(cfs_rq); 5023 __update_load_avg_blocked_se(last_update_time, se); 5024 } 5025 5026 /* 5027 * Task first catches up with cfs_rq, and then subtract 5028 * itself from the cfs_rq (task must be off the queue now). 5029 */ 5030 static void remove_entity_load_avg(struct sched_entity *se) 5031 { 5032 struct cfs_rq *cfs_rq = cfs_rq_of(se); 5033 unsigned long flags; 5034 5035 /* 5036 * tasks cannot exit without having gone through wake_up_new_task() -> 5037 * enqueue_task_fair() which will have added things to the cfs_rq, 5038 * so we can remove unconditionally. 5039 */ 5040 5041 sync_entity_load_avg(se); 5042 5043 raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags); 5044 ++cfs_rq->removed.nr; 5045 cfs_rq->removed.util_avg += se->avg.util_avg; 5046 cfs_rq->removed.load_avg += se->avg.load_avg; 5047 cfs_rq->removed.runnable_avg += se->avg.runnable_avg; 5048 raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags); 5049 } 5050 5051 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq) 5052 { 5053 return cfs_rq->avg.runnable_avg; 5054 } 5055 5056 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq) 5057 { 5058 return cfs_rq->avg.load_avg; 5059 } 5060 5061 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf) 5062 __must_hold(__rq_lockp(this_rq)); 5063 5064 static inline unsigned long task_util(struct task_struct *p) 5065 { 5066 return READ_ONCE(p->se.avg.util_avg); 5067 } 5068 5069 static inline unsigned long task_runnable(struct task_struct *p) 5070 { 5071 return READ_ONCE(p->se.avg.runnable_avg); 5072 } 5073 5074 static inline unsigned long _task_util_est(struct task_struct *p) 5075 { 5076 return READ_ONCE(p->se.avg.util_est) & ~UTIL_AVG_UNCHANGED; 5077 } 5078 5079 static inline unsigned long task_util_est(struct task_struct *p) 5080 { 5081 return max(task_util(p), _task_util_est(p)); 5082 } 5083 5084 static inline void util_est_enqueue(struct cfs_rq *cfs_rq, 5085 struct task_struct *p) 5086 { 5087 unsigned int enqueued; 5088 5089 if (!sched_feat(UTIL_EST)) 5090 return; 5091 5092 /* Update root cfs_rq's estimated utilization */ 5093 enqueued = cfs_rq->avg.util_est; 5094 enqueued += _task_util_est(p); 5095 WRITE_ONCE(cfs_rq->avg.util_est, enqueued); 5096 5097 trace_sched_util_est_cfs_tp(cfs_rq); 5098 } 5099 5100 static inline void util_est_dequeue(struct cfs_rq *cfs_rq, 5101 struct task_struct *p) 5102 { 5103 unsigned int enqueued; 5104 5105 if (!sched_feat(UTIL_EST)) 5106 return; 5107 5108 /* Update root cfs_rq's estimated utilization */ 5109 enqueued = cfs_rq->avg.util_est; 5110 enqueued -= min_t(unsigned int, enqueued, _task_util_est(p)); 5111 WRITE_ONCE(cfs_rq->avg.util_est, enqueued); 5112 5113 trace_sched_util_est_cfs_tp(cfs_rq); 5114 } 5115 5116 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100) 5117 5118 static inline void util_est_update(struct cfs_rq *cfs_rq, 5119 struct task_struct *p, 5120 bool task_sleep) 5121 { 5122 unsigned int ewma, dequeued, last_ewma_diff; 5123 5124 if (!sched_feat(UTIL_EST)) 5125 return; 5126 5127 /* 5128 * Skip update of task's estimated utilization when the task has not 5129 * yet completed an activation, e.g. being migrated. 5130 */ 5131 if (!task_sleep) 5132 return; 5133 5134 /* Get current estimate of utilization */ 5135 ewma = READ_ONCE(p->se.avg.util_est); 5136 5137 /* 5138 * If the PELT values haven't changed since enqueue time, 5139 * skip the util_est update. 5140 */ 5141 if (ewma & UTIL_AVG_UNCHANGED) 5142 return; 5143 5144 /* Get utilization at dequeue */ 5145 dequeued = task_util(p); 5146 5147 /* 5148 * Reset EWMA on utilization increases, the moving average is used only 5149 * to smooth utilization decreases. 5150 */ 5151 if (ewma <= dequeued) { 5152 ewma = dequeued; 5153 goto done; 5154 } 5155 5156 /* 5157 * Skip update of task's estimated utilization when its members are 5158 * already ~1% close to its last activation value. 5159 */ 5160 last_ewma_diff = ewma - dequeued; 5161 if (last_ewma_diff < UTIL_EST_MARGIN) 5162 goto done; 5163 5164 /* 5165 * To avoid underestimate of task utilization, skip updates of EWMA if 5166 * we cannot grant that thread got all CPU time it wanted. 5167 */ 5168 if ((dequeued + UTIL_EST_MARGIN) < task_runnable(p)) 5169 goto done; 5170 5171 5172 /* 5173 * Update Task's estimated utilization 5174 * 5175 * When *p completes an activation we can consolidate another sample 5176 * of the task size. This is done by using this value to update the 5177 * Exponential Weighted Moving Average (EWMA): 5178 * 5179 * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1) 5180 * = w * task_util(p) + ewma(t-1) - w * ewma(t-1) 5181 * = w * (task_util(p) - ewma(t-1)) + ewma(t-1) 5182 * = w * ( -last_ewma_diff ) + ewma(t-1) 5183 * = w * (-last_ewma_diff + ewma(t-1) / w) 5184 * 5185 * Where 'w' is the weight of new samples, which is configured to be 5186 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT) 5187 */ 5188 ewma <<= UTIL_EST_WEIGHT_SHIFT; 5189 ewma -= last_ewma_diff; 5190 ewma >>= UTIL_EST_WEIGHT_SHIFT; 5191 done: 5192 ewma |= UTIL_AVG_UNCHANGED; 5193 WRITE_ONCE(p->se.avg.util_est, ewma); 5194 5195 trace_sched_util_est_se_tp(&p->se); 5196 } 5197 5198 static inline unsigned long get_actual_cpu_capacity(int cpu) 5199 { 5200 unsigned long capacity = arch_scale_cpu_capacity(cpu); 5201 5202 capacity -= max(hw_load_avg(cpu_rq(cpu)), cpufreq_get_pressure(cpu)); 5203 5204 return capacity; 5205 } 5206 5207 static inline int util_fits_cpu(unsigned long util, 5208 unsigned long uclamp_min, 5209 unsigned long uclamp_max, 5210 int cpu) 5211 { 5212 unsigned long capacity = capacity_of(cpu); 5213 unsigned long capacity_orig; 5214 bool fits, uclamp_max_fits; 5215 5216 /* 5217 * Check if the real util fits without any uclamp boost/cap applied. 5218 */ 5219 fits = fits_capacity(util, capacity); 5220 5221 if (!uclamp_is_used()) 5222 return fits; 5223 5224 /* 5225 * We must use arch_scale_cpu_capacity() for comparing against uclamp_min and 5226 * uclamp_max. We only care about capacity pressure (by using 5227 * capacity_of()) for comparing against the real util. 5228 * 5229 * If a task is boosted to 1024 for example, we don't want a tiny 5230 * pressure to skew the check whether it fits a CPU or not. 5231 * 5232 * Similarly if a task is capped to arch_scale_cpu_capacity(little_cpu), it 5233 * should fit a little cpu even if there's some pressure. 5234 * 5235 * Only exception is for HW or cpufreq pressure since it has a direct impact 5236 * on available OPP of the system. 5237 * 5238 * We honour it for uclamp_min only as a drop in performance level 5239 * could result in not getting the requested minimum performance level. 5240 * 5241 * For uclamp_max, we can tolerate a drop in performance level as the 5242 * goal is to cap the task. So it's okay if it's getting less. 5243 */ 5244 capacity_orig = arch_scale_cpu_capacity(cpu); 5245 5246 /* 5247 * We want to force a task to fit a cpu as implied by uclamp_max. 5248 * But we do have some corner cases to cater for.. 5249 * 5250 * 5251 * C=z 5252 * | ___ 5253 * | C=y | | 5254 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max 5255 * | C=x | | | | 5256 * | ___ | | | | 5257 * | | | | | | | (util somewhere in this region) 5258 * | | | | | | | 5259 * | | | | | | | 5260 * +---------------------------------------- 5261 * CPU0 CPU1 CPU2 5262 * 5263 * In the above example if a task is capped to a specific performance 5264 * point, y, then when: 5265 * 5266 * * util = 80% of x then it does not fit on CPU0 and should migrate 5267 * to CPU1 5268 * * util = 80% of y then it is forced to fit on CPU1 to honour 5269 * uclamp_max request. 5270 * 5271 * which is what we're enforcing here. A task always fits if 5272 * uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig, 5273 * the normal upmigration rules should withhold still. 5274 * 5275 * Only exception is when we are on max capacity, then we need to be 5276 * careful not to block overutilized state. This is so because: 5277 * 5278 * 1. There's no concept of capping at max_capacity! We can't go 5279 * beyond this performance level anyway. 5280 * 2. The system is being saturated when we're operating near 5281 * max capacity, it doesn't make sense to block overutilized. 5282 */ 5283 uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE); 5284 uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig); 5285 fits = fits || uclamp_max_fits; 5286 5287 /* 5288 * 5289 * C=z 5290 * | ___ (region a, capped, util >= uclamp_max) 5291 * | C=y | | 5292 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max 5293 * | C=x | | | | 5294 * | ___ | | | | (region b, uclamp_min <= util <= uclamp_max) 5295 * |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min 5296 * | | | | | | | 5297 * | | | | | | | (region c, boosted, util < uclamp_min) 5298 * +---------------------------------------- 5299 * CPU0 CPU1 CPU2 5300 * 5301 * a) If util > uclamp_max, then we're capped, we don't care about 5302 * actual fitness value here. We only care if uclamp_max fits 5303 * capacity without taking margin/pressure into account. 5304 * See comment above. 5305 * 5306 * b) If uclamp_min <= util <= uclamp_max, then the normal 5307 * fits_capacity() rules apply. Except we need to ensure that we 5308 * enforce we remain within uclamp_max, see comment above. 5309 * 5310 * c) If util < uclamp_min, then we are boosted. Same as (b) but we 5311 * need to take into account the boosted value fits the CPU without 5312 * taking margin/pressure into account. 5313 * 5314 * Cases (a) and (b) are handled in the 'fits' variable already. We 5315 * just need to consider an extra check for case (c) after ensuring we 5316 * handle the case uclamp_min > uclamp_max. 5317 */ 5318 uclamp_min = min(uclamp_min, uclamp_max); 5319 if (fits && (util < uclamp_min) && 5320 (uclamp_min > get_actual_cpu_capacity(cpu))) 5321 return -1; 5322 5323 return fits; 5324 } 5325 5326 static inline int task_fits_cpu(struct task_struct *p, int cpu) 5327 { 5328 unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN); 5329 unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX); 5330 unsigned long util = task_util_est(p); 5331 /* 5332 * Return true only if the cpu fully fits the task requirements, which 5333 * include the utilization but also the performance hints. 5334 */ 5335 return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0); 5336 } 5337 5338 static inline void update_misfit_status(struct task_struct *p, struct rq *rq) 5339 { 5340 int cpu = cpu_of(rq); 5341 5342 if (!sched_asym_cpucap_active()) 5343 return; 5344 5345 /* 5346 * Affinity allows us to go somewhere higher? Or are we on biggest 5347 * available CPU already? Or do we fit into this CPU ? 5348 */ 5349 if (!p || (p->nr_cpus_allowed == 1) || 5350 (arch_scale_cpu_capacity(cpu) == p->max_allowed_capacity) || 5351 task_fits_cpu(p, cpu)) { 5352 5353 rq->misfit_task_load = 0; 5354 return; 5355 } 5356 5357 /* 5358 * Make sure that misfit_task_load will not be null even if 5359 * task_h_load() returns 0. 5360 */ 5361 rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1); 5362 } 5363 5364 void __setparam_fair(struct task_struct *p, const struct sched_attr *attr) 5365 { 5366 struct sched_entity *se = &p->se; 5367 5368 p->static_prio = NICE_TO_PRIO(attr->sched_nice); 5369 if (attr->sched_runtime) { 5370 se->custom_slice = 1; 5371 se->slice = clamp_t(u64, attr->sched_runtime, 5372 NSEC_PER_MSEC/10, /* HZ=1000 * 10 */ 5373 NSEC_PER_MSEC*100); /* HZ=100 / 10 */ 5374 } else { 5375 se->custom_slice = 0; 5376 se->slice = sysctl_sched_base_slice; 5377 } 5378 } 5379 5380 static void 5381 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 5382 { 5383 u64 vslice, vruntime = avg_vruntime(cfs_rq); 5384 bool update_zero = false; 5385 s64 lag = 0; 5386 5387 if (!se->custom_slice) 5388 se->slice = sysctl_sched_base_slice; 5389 vslice = calc_delta_fair(se->slice, se); 5390 5391 /* 5392 * Due to how V is constructed as the weighted average of entities, 5393 * adding tasks with positive lag, or removing tasks with negative lag 5394 * will move 'time' backwards, this can screw around with the lag of 5395 * other tasks. 5396 * 5397 * EEVDF: placement strategy #1 / #2 5398 */ 5399 if (sched_feat(PLACE_LAG) && cfs_rq->nr_queued && se->vlag) { 5400 struct sched_entity *curr = cfs_rq->curr; 5401 long load, weight; 5402 5403 lag = se->vlag; 5404 5405 /* 5406 * If we want to place a task and preserve lag, we have to 5407 * consider the effect of the new entity on the weighted 5408 * average and compensate for this, otherwise lag can quickly 5409 * evaporate. 5410 * 5411 * Lag is defined as: 5412 * 5413 * lag_i = S - s_i = w_i * (V - v_i) 5414 * 5415 * To avoid the 'w_i' term all over the place, we only track 5416 * the virtual lag: 5417 * 5418 * vl_i = V - v_i <=> v_i = V - vl_i 5419 * 5420 * And we take V to be the weighted average of all v: 5421 * 5422 * V = (\Sum w_j*v_j) / W 5423 * 5424 * Where W is: \Sum w_j 5425 * 5426 * Then, the weighted average after adding an entity with lag 5427 * vl_i is given by: 5428 * 5429 * V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i) 5430 * = (W*V + w_i*(V - vl_i)) / (W + w_i) 5431 * = (W*V + w_i*V - w_i*vl_i) / (W + w_i) 5432 * = (V*(W + w_i) - w_i*vl_i) / (W + w_i) 5433 * = V - w_i*vl_i / (W + w_i) 5434 * 5435 * And the actual lag after adding an entity with vl_i is: 5436 * 5437 * vl'_i = V' - v_i 5438 * = V - w_i*vl_i / (W + w_i) - (V - vl_i) 5439 * = vl_i - w_i*vl_i / (W + w_i) 5440 * 5441 * Which is strictly less than vl_i. So in order to preserve lag 5442 * we should inflate the lag before placement such that the 5443 * effective lag after placement comes out right. 5444 * 5445 * As such, invert the above relation for vl'_i to get the vl_i 5446 * we need to use such that the lag after placement is the lag 5447 * we computed before dequeue. 5448 * 5449 * vl'_i = vl_i - w_i*vl_i / (W + w_i) 5450 * = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i) 5451 * 5452 * (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i 5453 * = W*vl_i 5454 * 5455 * vl_i = (W + w_i)*vl'_i / W 5456 */ 5457 load = cfs_rq->sum_weight; 5458 if (curr && curr->on_rq) 5459 load += avg_vruntime_weight(cfs_rq, curr->load.weight); 5460 5461 weight = avg_vruntime_weight(cfs_rq, se->load.weight); 5462 lag *= load + weight; 5463 if (WARN_ON_ONCE(!load)) 5464 load = 1; 5465 lag = div64_long(lag, load); 5466 5467 /* 5468 * A heavy entity (relative to the tree) will pull the 5469 * avg_vruntime close to its vruntime position on enqueue. But 5470 * the zero_vruntime point is only updated at the next 5471 * update_deadline()/place_entity()/update_entity_lag(). 5472 * 5473 * Specifically (see the comment near avg_vruntime_weight()): 5474 * 5475 * sum_w_vruntime = \Sum (v_i - v0) * w_i 5476 * 5477 * Note that if v0 is near a light entity, both terms will be 5478 * small for the light entity, while in that case both terms 5479 * are large for the heavy entity, leading to risk of 5480 * overflow. 5481 * 5482 * OTOH if v0 is near the heavy entity, then the difference is 5483 * larger for the light entity, but the factor is small, while 5484 * for the heavy entity the difference is small but the factor 5485 * is large. Avoiding the multiplication overflow. 5486 */ 5487 if (weight > load) 5488 update_zero = true; 5489 } 5490 5491 se->vruntime = vruntime - lag; 5492 5493 if (update_zero) 5494 update_zero_vruntime(cfs_rq, -lag); 5495 5496 if (sched_feat(PLACE_REL_DEADLINE) && se->rel_deadline) { 5497 se->deadline += se->vruntime; 5498 se->rel_deadline = 0; 5499 return; 5500 } 5501 5502 /* 5503 * When joining the competition; the existing tasks will be, 5504 * on average, halfway through their slice, as such start tasks 5505 * off with half a slice to ease into the competition. 5506 */ 5507 if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL)) 5508 vslice /= 2; 5509 5510 /* 5511 * EEVDF: vd_i = ve_i + r_i/w_i 5512 */ 5513 se->deadline = se->vruntime + vslice; 5514 } 5515 5516 static void check_enqueue_throttle(struct cfs_rq *cfs_rq); 5517 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq); 5518 5519 static void 5520 requeue_delayed_entity(struct sched_entity *se); 5521 5522 static void 5523 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 5524 { 5525 bool curr = cfs_rq->curr == se; 5526 5527 /* 5528 * If we're the current task, we must renormalise before calling 5529 * update_curr(). 5530 */ 5531 if (curr) 5532 place_entity(cfs_rq, se, flags); 5533 5534 update_curr(cfs_rq); 5535 5536 /* 5537 * When enqueuing a sched_entity, we must: 5538 * - Update loads to have both entity and cfs_rq synced with now. 5539 * - For group_entity, update its runnable_weight to reflect the new 5540 * h_nr_runnable of its group cfs_rq. 5541 * - For group_entity, update its weight to reflect the new share of 5542 * its group cfs_rq 5543 * - Add its new weight to cfs_rq->load.weight 5544 */ 5545 update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH); 5546 se_update_runnable(se); 5547 /* 5548 * XXX update_load_avg() above will have attached us to the pelt sum; 5549 * but update_cfs_group() here will re-adjust the weight and have to 5550 * undo/redo all that. Seems wasteful. 5551 */ 5552 update_cfs_group(se); 5553 5554 /* 5555 * XXX now that the entity has been re-weighted, and it's lag adjusted, 5556 * we can place the entity. 5557 */ 5558 if (!curr) 5559 place_entity(cfs_rq, se, flags); 5560 5561 account_entity_enqueue(cfs_rq, se); 5562 5563 /* Entity has migrated, no longer consider this task hot */ 5564 if (flags & ENQUEUE_MIGRATED) 5565 se->exec_start = 0; 5566 5567 check_schedstat_required(); 5568 update_stats_enqueue_fair(cfs_rq, se, flags); 5569 if (!curr) 5570 __enqueue_entity(cfs_rq, se); 5571 se->on_rq = 1; 5572 5573 if (cfs_rq->nr_queued == 1) { 5574 check_enqueue_throttle(cfs_rq); 5575 list_add_leaf_cfs_rq(cfs_rq); 5576 #ifdef CONFIG_CFS_BANDWIDTH 5577 if (cfs_rq->pelt_clock_throttled) { 5578 struct rq *rq = rq_of(cfs_rq); 5579 5580 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) - 5581 cfs_rq->throttled_clock_pelt; 5582 cfs_rq->pelt_clock_throttled = 0; 5583 } 5584 #endif 5585 } 5586 } 5587 5588 static void __clear_buddies_next(struct sched_entity *se) 5589 { 5590 for_each_sched_entity(se) { 5591 struct cfs_rq *cfs_rq = cfs_rq_of(se); 5592 if (cfs_rq->next != se) 5593 break; 5594 5595 cfs_rq->next = NULL; 5596 } 5597 } 5598 5599 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se) 5600 { 5601 if (cfs_rq->next == se) 5602 __clear_buddies_next(se); 5603 } 5604 5605 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq); 5606 5607 static void set_delayed(struct sched_entity *se) 5608 { 5609 se->sched_delayed = 1; 5610 5611 /* 5612 * Delayed se of cfs_rq have no tasks queued on them. 5613 * Do not adjust h_nr_runnable since dequeue_entities() 5614 * will account it for blocked tasks. 5615 */ 5616 if (!entity_is_task(se)) 5617 return; 5618 5619 for_each_sched_entity(se) { 5620 struct cfs_rq *cfs_rq = cfs_rq_of(se); 5621 5622 cfs_rq->h_nr_runnable--; 5623 } 5624 } 5625 5626 static void clear_delayed(struct sched_entity *se) 5627 { 5628 se->sched_delayed = 0; 5629 5630 /* 5631 * Delayed se of cfs_rq have no tasks queued on them. 5632 * Do not adjust h_nr_runnable since a dequeue has 5633 * already accounted for it or an enqueue of a task 5634 * below it will account for it in enqueue_task_fair(). 5635 */ 5636 if (!entity_is_task(se)) 5637 return; 5638 5639 for_each_sched_entity(se) { 5640 struct cfs_rq *cfs_rq = cfs_rq_of(se); 5641 5642 cfs_rq->h_nr_runnable++; 5643 } 5644 } 5645 5646 static bool 5647 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 5648 { 5649 bool sleep = flags & DEQUEUE_SLEEP; 5650 int action = UPDATE_TG; 5651 5652 update_curr(cfs_rq); 5653 clear_buddies(cfs_rq, se); 5654 5655 if (flags & DEQUEUE_DELAYED) { 5656 WARN_ON_ONCE(!se->sched_delayed); 5657 } else { 5658 bool delay = sleep; 5659 /* 5660 * DELAY_DEQUEUE relies on spurious wakeups, special task 5661 * states must not suffer spurious wakeups, excempt them. 5662 */ 5663 if (flags & (DEQUEUE_SPECIAL | DEQUEUE_THROTTLE)) 5664 delay = false; 5665 5666 WARN_ON_ONCE(delay && se->sched_delayed); 5667 5668 if (sched_feat(DELAY_DEQUEUE) && delay && 5669 !entity_eligible(cfs_rq, se)) { 5670 update_load_avg(cfs_rq, se, 0); 5671 update_entity_lag(cfs_rq, se); 5672 set_delayed(se); 5673 return false; 5674 } 5675 } 5676 5677 if (entity_is_task(se) && task_on_rq_migrating(task_of(se))) 5678 action |= DO_DETACH; 5679 5680 /* 5681 * When dequeuing a sched_entity, we must: 5682 * - Update loads to have both entity and cfs_rq synced with now. 5683 * - For group_entity, update its runnable_weight to reflect the new 5684 * h_nr_runnable of its group cfs_rq. 5685 * - Subtract its previous weight from cfs_rq->load.weight. 5686 * - For group entity, update its weight to reflect the new share 5687 * of its group cfs_rq. 5688 */ 5689 update_load_avg(cfs_rq, se, action); 5690 se_update_runnable(se); 5691 5692 update_stats_dequeue_fair(cfs_rq, se, flags); 5693 5694 update_entity_lag(cfs_rq, se); 5695 if (sched_feat(PLACE_REL_DEADLINE) && !sleep) { 5696 se->deadline -= se->vruntime; 5697 se->rel_deadline = 1; 5698 } 5699 5700 if (se != cfs_rq->curr) 5701 __dequeue_entity(cfs_rq, se); 5702 se->on_rq = 0; 5703 account_entity_dequeue(cfs_rq, se); 5704 5705 /* return excess runtime on last dequeue */ 5706 return_cfs_rq_runtime(cfs_rq); 5707 5708 update_cfs_group(se); 5709 5710 if (flags & DEQUEUE_DELAYED) 5711 clear_delayed(se); 5712 5713 if (cfs_rq->nr_queued == 0) { 5714 update_idle_cfs_rq_clock_pelt(cfs_rq); 5715 #ifdef CONFIG_CFS_BANDWIDTH 5716 if (throttled_hierarchy(cfs_rq)) { 5717 struct rq *rq = rq_of(cfs_rq); 5718 5719 list_del_leaf_cfs_rq(cfs_rq); 5720 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq); 5721 cfs_rq->pelt_clock_throttled = 1; 5722 } 5723 #endif 5724 } 5725 5726 return true; 5727 } 5728 5729 static void 5730 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, bool first) 5731 { 5732 clear_buddies(cfs_rq, se); 5733 5734 /* 'current' is not kept within the tree. */ 5735 if (se->on_rq) { 5736 /* 5737 * Any task has to be enqueued before it get to execute on 5738 * a CPU. So account for the time it spent waiting on the 5739 * runqueue. 5740 */ 5741 update_stats_wait_end_fair(cfs_rq, se); 5742 __dequeue_entity(cfs_rq, se); 5743 update_load_avg(cfs_rq, se, UPDATE_TG); 5744 5745 if (first) 5746 set_protect_slice(cfs_rq, se); 5747 } 5748 5749 update_stats_curr_start(cfs_rq, se); 5750 WARN_ON_ONCE(cfs_rq->curr); 5751 cfs_rq->curr = se; 5752 5753 /* 5754 * Track our maximum slice length, if the CPU's load is at 5755 * least twice that of our own weight (i.e. don't track it 5756 * when there are only lesser-weight tasks around): 5757 */ 5758 if (schedstat_enabled() && 5759 rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) { 5760 struct sched_statistics *stats; 5761 5762 stats = __schedstats_from_se(se); 5763 __schedstat_set(stats->slice_max, 5764 max((u64)stats->slice_max, 5765 se->sum_exec_runtime - se->prev_sum_exec_runtime)); 5766 } 5767 5768 se->prev_sum_exec_runtime = se->sum_exec_runtime; 5769 } 5770 5771 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags); 5772 5773 /* 5774 * Pick the next process, keeping these things in mind, in this order: 5775 * 1) keep things fair between processes/task groups 5776 * 2) pick the "next" process, since someone really wants that to run 5777 * 3) pick the "last" process, for cache locality 5778 * 4) do not run the "skip" process, if something else is available 5779 */ 5780 static struct sched_entity * 5781 pick_next_entity(struct rq *rq, struct cfs_rq *cfs_rq, bool protect) 5782 { 5783 struct sched_entity *se; 5784 5785 se = pick_eevdf(cfs_rq, protect); 5786 if (se->sched_delayed) { 5787 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED); 5788 /* 5789 * Must not reference @se again, see __block_task(). 5790 */ 5791 return NULL; 5792 } 5793 return se; 5794 } 5795 5796 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq); 5797 5798 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev) 5799 { 5800 /* 5801 * If still on the runqueue then deactivate_task() 5802 * was not called and update_curr() has to be done: 5803 */ 5804 if (prev->on_rq) 5805 update_curr(cfs_rq); 5806 5807 /* throttle cfs_rqs exceeding runtime */ 5808 check_cfs_rq_runtime(cfs_rq); 5809 5810 if (prev->on_rq) { 5811 update_stats_wait_start_fair(cfs_rq, prev); 5812 /* Put 'current' back into the tree. */ 5813 __enqueue_entity(cfs_rq, prev); 5814 /* in !on_rq case, update occurred at dequeue */ 5815 update_load_avg(cfs_rq, prev, 0); 5816 } 5817 WARN_ON_ONCE(cfs_rq->curr != prev); 5818 cfs_rq->curr = NULL; 5819 } 5820 5821 static void 5822 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued) 5823 { 5824 /* 5825 * Update run-time statistics of the 'current'. 5826 */ 5827 update_curr(cfs_rq); 5828 5829 /* 5830 * Ensure that runnable average is periodically updated. 5831 */ 5832 update_load_avg(cfs_rq, curr, UPDATE_TG); 5833 update_cfs_group(curr); 5834 5835 #ifdef CONFIG_SCHED_HRTICK 5836 /* 5837 * queued ticks are scheduled to match the slice, so don't bother 5838 * validating it and just reschedule. 5839 */ 5840 if (queued) { 5841 resched_curr(rq_of(cfs_rq)); 5842 return; 5843 } 5844 #endif 5845 } 5846 5847 5848 /************************************************** 5849 * CFS bandwidth control machinery 5850 */ 5851 5852 #ifdef CONFIG_CFS_BANDWIDTH 5853 5854 #ifdef CONFIG_JUMP_LABEL 5855 static struct static_key __cfs_bandwidth_used; 5856 5857 static inline bool cfs_bandwidth_used(void) 5858 { 5859 return static_key_false(&__cfs_bandwidth_used); 5860 } 5861 5862 void cfs_bandwidth_usage_inc(void) 5863 { 5864 static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used); 5865 } 5866 5867 void cfs_bandwidth_usage_dec(void) 5868 { 5869 static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used); 5870 } 5871 #else /* !CONFIG_JUMP_LABEL: */ 5872 static bool cfs_bandwidth_used(void) 5873 { 5874 return true; 5875 } 5876 5877 void cfs_bandwidth_usage_inc(void) {} 5878 void cfs_bandwidth_usage_dec(void) {} 5879 #endif /* !CONFIG_JUMP_LABEL */ 5880 5881 static inline u64 sched_cfs_bandwidth_slice(void) 5882 { 5883 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC; 5884 } 5885 5886 /* 5887 * Replenish runtime according to assigned quota. We use sched_clock_cpu 5888 * directly instead of rq->clock to avoid adding additional synchronization 5889 * around rq->lock. 5890 * 5891 * requires cfs_b->lock 5892 */ 5893 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b) 5894 { 5895 s64 runtime; 5896 5897 if (unlikely(cfs_b->quota == RUNTIME_INF)) 5898 return; 5899 5900 cfs_b->runtime += cfs_b->quota; 5901 runtime = cfs_b->runtime_snap - cfs_b->runtime; 5902 if (runtime > 0) { 5903 cfs_b->burst_time += runtime; 5904 cfs_b->nr_burst++; 5905 } 5906 5907 cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst); 5908 cfs_b->runtime_snap = cfs_b->runtime; 5909 } 5910 5911 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg) 5912 { 5913 return &tg->cfs_bandwidth; 5914 } 5915 5916 /* returns 0 on failure to allocate runtime */ 5917 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b, 5918 struct cfs_rq *cfs_rq, u64 target_runtime) 5919 { 5920 u64 min_amount, amount = 0; 5921 5922 lockdep_assert_held(&cfs_b->lock); 5923 5924 /* note: this is a positive sum as runtime_remaining <= 0 */ 5925 min_amount = target_runtime - cfs_rq->runtime_remaining; 5926 5927 if (cfs_b->quota == RUNTIME_INF) 5928 amount = min_amount; 5929 else { 5930 start_cfs_bandwidth(cfs_b); 5931 5932 if (cfs_b->runtime > 0) { 5933 amount = min(cfs_b->runtime, min_amount); 5934 cfs_b->runtime -= amount; 5935 cfs_b->idle = 0; 5936 } 5937 } 5938 5939 cfs_rq->runtime_remaining += amount; 5940 5941 return cfs_rq->runtime_remaining > 0; 5942 } 5943 5944 /* returns 0 on failure to allocate runtime */ 5945 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq) 5946 { 5947 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 5948 int ret; 5949 5950 raw_spin_lock(&cfs_b->lock); 5951 ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice()); 5952 raw_spin_unlock(&cfs_b->lock); 5953 5954 return ret; 5955 } 5956 5957 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) 5958 { 5959 /* dock delta_exec before expiring quota (as it could span periods) */ 5960 cfs_rq->runtime_remaining -= delta_exec; 5961 5962 if (likely(cfs_rq->runtime_remaining > 0)) 5963 return; 5964 5965 if (cfs_rq->throttled) 5966 return; 5967 /* 5968 * if we're unable to extend our runtime we resched so that the active 5969 * hierarchy can be throttled 5970 */ 5971 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr)) 5972 resched_curr(rq_of(cfs_rq)); 5973 } 5974 5975 static __always_inline 5976 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) 5977 { 5978 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled) 5979 return; 5980 5981 __account_cfs_rq_runtime(cfs_rq, delta_exec); 5982 } 5983 5984 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq) 5985 { 5986 return cfs_bandwidth_used() && cfs_rq->throttled; 5987 } 5988 5989 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq) 5990 { 5991 return cfs_bandwidth_used() && cfs_rq->pelt_clock_throttled; 5992 } 5993 5994 /* check whether cfs_rq, or any parent, is throttled */ 5995 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq) 5996 { 5997 return cfs_bandwidth_used() && cfs_rq->throttle_count; 5998 } 5999 6000 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu) 6001 { 6002 return throttled_hierarchy(task_group(p)->cfs_rq[dst_cpu]); 6003 } 6004 6005 static inline bool task_is_throttled(struct task_struct *p) 6006 { 6007 return cfs_bandwidth_used() && p->throttled; 6008 } 6009 6010 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags); 6011 static void throttle_cfs_rq_work(struct callback_head *work) 6012 { 6013 struct task_struct *p = container_of(work, struct task_struct, sched_throttle_work); 6014 struct sched_entity *se; 6015 struct cfs_rq *cfs_rq; 6016 struct rq *rq; 6017 6018 WARN_ON_ONCE(p != current); 6019 p->sched_throttle_work.next = &p->sched_throttle_work; 6020 6021 /* 6022 * If task is exiting, then there won't be a return to userspace, so we 6023 * don't have to bother with any of this. 6024 */ 6025 if ((p->flags & PF_EXITING)) 6026 return; 6027 6028 scoped_guard(task_rq_lock, p) { 6029 se = &p->se; 6030 cfs_rq = cfs_rq_of(se); 6031 6032 /* Raced, forget */ 6033 if (p->sched_class != &fair_sched_class) 6034 return; 6035 6036 /* 6037 * If not in limbo, then either replenish has happened or this 6038 * task got migrated out of the throttled cfs_rq, move along. 6039 */ 6040 if (!cfs_rq->throttle_count) 6041 return; 6042 rq = scope.rq; 6043 update_rq_clock(rq); 6044 WARN_ON_ONCE(p->throttled || !list_empty(&p->throttle_node)); 6045 dequeue_task_fair(rq, p, DEQUEUE_SLEEP | DEQUEUE_THROTTLE); 6046 list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list); 6047 /* 6048 * Must not set throttled before dequeue or dequeue will 6049 * mistakenly regard this task as an already throttled one. 6050 */ 6051 p->throttled = true; 6052 resched_curr(rq); 6053 } 6054 } 6055 6056 void init_cfs_throttle_work(struct task_struct *p) 6057 { 6058 init_task_work(&p->sched_throttle_work, throttle_cfs_rq_work); 6059 /* Protect against double add, see throttle_cfs_rq() and throttle_cfs_rq_work() */ 6060 p->sched_throttle_work.next = &p->sched_throttle_work; 6061 INIT_LIST_HEAD(&p->throttle_node); 6062 } 6063 6064 /* 6065 * Task is throttled and someone wants to dequeue it again: 6066 * it could be sched/core when core needs to do things like 6067 * task affinity change, task group change, task sched class 6068 * change etc. and in these cases, DEQUEUE_SLEEP is not set; 6069 * or the task is blocked after throttled due to freezer etc. 6070 * and in these cases, DEQUEUE_SLEEP is set. 6071 */ 6072 static void detach_task_cfs_rq(struct task_struct *p); 6073 static void dequeue_throttled_task(struct task_struct *p, int flags) 6074 { 6075 WARN_ON_ONCE(p->se.on_rq); 6076 list_del_init(&p->throttle_node); 6077 6078 /* task blocked after throttled */ 6079 if (flags & DEQUEUE_SLEEP) { 6080 p->throttled = false; 6081 return; 6082 } 6083 6084 /* 6085 * task is migrating off its old cfs_rq, detach 6086 * the task's load from its old cfs_rq. 6087 */ 6088 if (task_on_rq_migrating(p)) 6089 detach_task_cfs_rq(p); 6090 } 6091 6092 static bool enqueue_throttled_task(struct task_struct *p) 6093 { 6094 struct cfs_rq *cfs_rq = cfs_rq_of(&p->se); 6095 6096 /* @p should have gone through dequeue_throttled_task() first */ 6097 WARN_ON_ONCE(!list_empty(&p->throttle_node)); 6098 6099 /* 6100 * If the throttled task @p is enqueued to a throttled cfs_rq, 6101 * take the fast path by directly putting the task on the 6102 * target cfs_rq's limbo list. 6103 * 6104 * Do not do that when @p is current because the following race can 6105 * cause @p's group_node to be incorectly re-insterted in its rq's 6106 * cfs_tasks list, despite being throttled: 6107 * 6108 * cpuX cpuY 6109 * p ret2user 6110 * throttle_cfs_rq_work() sched_move_task(p) 6111 * LOCK task_rq_lock 6112 * dequeue_task_fair(p) 6113 * UNLOCK task_rq_lock 6114 * LOCK task_rq_lock 6115 * task_current_donor(p) == true 6116 * task_on_rq_queued(p) == true 6117 * dequeue_task(p) 6118 * put_prev_task(p) 6119 * sched_change_group() 6120 * enqueue_task(p) -> p's new cfs_rq 6121 * is throttled, go 6122 * fast path and skip 6123 * actual enqueue 6124 * set_next_task(p) 6125 * list_move(&se->group_node, &rq->cfs_tasks); // bug 6126 * schedule() 6127 * 6128 * In the above race case, @p current cfs_rq is in the same rq as 6129 * its previous cfs_rq because sched_move_task() only moves a task 6130 * to a different group from the same rq, so we can use its current 6131 * cfs_rq to derive rq and test if the task is current. 6132 */ 6133 if (throttled_hierarchy(cfs_rq) && 6134 !task_current_donor(rq_of(cfs_rq), p)) { 6135 list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list); 6136 return true; 6137 } 6138 6139 /* we can't take the fast path, do an actual enqueue*/ 6140 p->throttled = false; 6141 return false; 6142 } 6143 6144 static void enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags); 6145 static int tg_unthrottle_up(struct task_group *tg, void *data) 6146 { 6147 struct rq *rq = data; 6148 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)]; 6149 struct task_struct *p, *tmp; 6150 6151 if (--cfs_rq->throttle_count) 6152 return 0; 6153 6154 if (cfs_rq->pelt_clock_throttled) { 6155 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) - 6156 cfs_rq->throttled_clock_pelt; 6157 cfs_rq->pelt_clock_throttled = 0; 6158 } 6159 6160 if (cfs_rq->throttled_clock_self) { 6161 u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self; 6162 6163 cfs_rq->throttled_clock_self = 0; 6164 6165 if (WARN_ON_ONCE((s64)delta < 0)) 6166 delta = 0; 6167 6168 cfs_rq->throttled_clock_self_time += delta; 6169 } 6170 6171 /* Re-enqueue the tasks that have been throttled at this level. */ 6172 list_for_each_entry_safe(p, tmp, &cfs_rq->throttled_limbo_list, throttle_node) { 6173 list_del_init(&p->throttle_node); 6174 p->throttled = false; 6175 enqueue_task_fair(rq_of(cfs_rq), p, ENQUEUE_WAKEUP); 6176 } 6177 6178 /* Add cfs_rq with load or one or more already running entities to the list */ 6179 if (!cfs_rq_is_decayed(cfs_rq)) 6180 list_add_leaf_cfs_rq(cfs_rq); 6181 6182 return 0; 6183 } 6184 6185 static inline bool task_has_throttle_work(struct task_struct *p) 6186 { 6187 return p->sched_throttle_work.next != &p->sched_throttle_work; 6188 } 6189 6190 static inline void task_throttle_setup_work(struct task_struct *p) 6191 { 6192 if (task_has_throttle_work(p)) 6193 return; 6194 6195 /* 6196 * Kthreads and exiting tasks don't return to userspace, so adding the 6197 * work is pointless 6198 */ 6199 if ((p->flags & (PF_EXITING | PF_KTHREAD))) 6200 return; 6201 6202 task_work_add(p, &p->sched_throttle_work, TWA_RESUME); 6203 } 6204 6205 static void record_throttle_clock(struct cfs_rq *cfs_rq) 6206 { 6207 struct rq *rq = rq_of(cfs_rq); 6208 6209 if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock) 6210 cfs_rq->throttled_clock = rq_clock(rq); 6211 6212 if (!cfs_rq->throttled_clock_self) 6213 cfs_rq->throttled_clock_self = rq_clock(rq); 6214 } 6215 6216 static int tg_throttle_down(struct task_group *tg, void *data) 6217 { 6218 struct rq *rq = data; 6219 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)]; 6220 6221 if (cfs_rq->throttle_count++) 6222 return 0; 6223 6224 /* 6225 * For cfs_rqs that still have entities enqueued, PELT clock 6226 * stop happens at dequeue time when all entities are dequeued. 6227 */ 6228 if (!cfs_rq->nr_queued) { 6229 list_del_leaf_cfs_rq(cfs_rq); 6230 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq); 6231 cfs_rq->pelt_clock_throttled = 1; 6232 } 6233 6234 WARN_ON_ONCE(cfs_rq->throttled_clock_self); 6235 WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_limbo_list)); 6236 return 0; 6237 } 6238 6239 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq) 6240 { 6241 struct rq *rq = rq_of(cfs_rq); 6242 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 6243 int dequeue = 1; 6244 6245 raw_spin_lock(&cfs_b->lock); 6246 /* This will start the period timer if necessary */ 6247 if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) { 6248 /* 6249 * We have raced with bandwidth becoming available, and if we 6250 * actually throttled the timer might not unthrottle us for an 6251 * entire period. We additionally needed to make sure that any 6252 * subsequent check_cfs_rq_runtime calls agree not to throttle 6253 * us, as we may commit to do cfs put_prev+pick_next, so we ask 6254 * for 1ns of runtime rather than just check cfs_b. 6255 */ 6256 dequeue = 0; 6257 } else { 6258 list_add_tail_rcu(&cfs_rq->throttled_list, 6259 &cfs_b->throttled_cfs_rq); 6260 } 6261 raw_spin_unlock(&cfs_b->lock); 6262 6263 if (!dequeue) 6264 return false; /* Throttle no longer required. */ 6265 6266 /* freeze hierarchy runnable averages while throttled */ 6267 rcu_read_lock(); 6268 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq); 6269 rcu_read_unlock(); 6270 6271 /* 6272 * Note: distribution will already see us throttled via the 6273 * throttled-list. rq->lock protects completion. 6274 */ 6275 cfs_rq->throttled = 1; 6276 WARN_ON_ONCE(cfs_rq->throttled_clock); 6277 return true; 6278 } 6279 6280 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq) 6281 { 6282 struct rq *rq = rq_of(cfs_rq); 6283 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 6284 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)]; 6285 6286 /* 6287 * It's possible we are called with runtime_remaining < 0 due to things 6288 * like async unthrottled us with a positive runtime_remaining but other 6289 * still running entities consumed those runtime before we reached here. 6290 * 6291 * We can't unthrottle this cfs_rq without any runtime remaining because 6292 * any enqueue in tg_unthrottle_up() will immediately trigger a throttle, 6293 * which is not supposed to happen on unthrottle path. 6294 */ 6295 if (cfs_rq->runtime_enabled && cfs_rq->runtime_remaining <= 0) 6296 return; 6297 6298 cfs_rq->throttled = 0; 6299 6300 update_rq_clock(rq); 6301 6302 raw_spin_lock(&cfs_b->lock); 6303 if (cfs_rq->throttled_clock) { 6304 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock; 6305 cfs_rq->throttled_clock = 0; 6306 } 6307 list_del_rcu(&cfs_rq->throttled_list); 6308 raw_spin_unlock(&cfs_b->lock); 6309 6310 /* update hierarchical throttle state */ 6311 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq); 6312 6313 if (!cfs_rq->load.weight) { 6314 if (!cfs_rq->on_list) 6315 return; 6316 /* 6317 * Nothing to run but something to decay (on_list)? 6318 * Complete the branch. 6319 */ 6320 for_each_sched_entity(se) { 6321 if (list_add_leaf_cfs_rq(cfs_rq_of(se))) 6322 break; 6323 } 6324 } 6325 6326 assert_list_leaf_cfs_rq(rq); 6327 6328 /* Determine whether we need to wake up potentially idle CPU: */ 6329 if (rq->curr == rq->idle && rq->cfs.nr_queued) 6330 resched_curr(rq); 6331 } 6332 6333 static void __cfsb_csd_unthrottle(void *arg) 6334 { 6335 struct cfs_rq *cursor, *tmp; 6336 struct rq *rq = arg; 6337 struct rq_flags rf; 6338 6339 rq_lock(rq, &rf); 6340 6341 /* 6342 * Iterating over the list can trigger several call to 6343 * update_rq_clock() in unthrottle_cfs_rq(). 6344 * Do it once and skip the potential next ones. 6345 */ 6346 update_rq_clock(rq); 6347 rq_clock_start_loop_update(rq); 6348 6349 /* 6350 * Since we hold rq lock we're safe from concurrent manipulation of 6351 * the CSD list. However, this RCU critical section annotates the 6352 * fact that we pair with sched_free_group_rcu(), so that we cannot 6353 * race with group being freed in the window between removing it 6354 * from the list and advancing to the next entry in the list. 6355 */ 6356 rcu_read_lock(); 6357 6358 list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list, 6359 throttled_csd_list) { 6360 list_del_init(&cursor->throttled_csd_list); 6361 6362 if (cfs_rq_throttled(cursor)) 6363 unthrottle_cfs_rq(cursor); 6364 } 6365 6366 rcu_read_unlock(); 6367 6368 rq_clock_stop_loop_update(rq); 6369 rq_unlock(rq, &rf); 6370 } 6371 6372 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq) 6373 { 6374 struct rq *rq = rq_of(cfs_rq); 6375 bool first; 6376 6377 if (rq == this_rq()) { 6378 unthrottle_cfs_rq(cfs_rq); 6379 return; 6380 } 6381 6382 /* Already enqueued */ 6383 if (WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_csd_list))) 6384 return; 6385 6386 first = list_empty(&rq->cfsb_csd_list); 6387 list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list); 6388 if (first) 6389 smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd); 6390 } 6391 6392 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq) 6393 { 6394 lockdep_assert_rq_held(rq_of(cfs_rq)); 6395 6396 if (WARN_ON_ONCE(!cfs_rq_throttled(cfs_rq) || 6397 cfs_rq->runtime_remaining <= 0)) 6398 return; 6399 6400 __unthrottle_cfs_rq_async(cfs_rq); 6401 } 6402 6403 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b) 6404 { 6405 int this_cpu = smp_processor_id(); 6406 u64 runtime, remaining = 1; 6407 bool throttled = false; 6408 struct cfs_rq *cfs_rq, *tmp; 6409 struct rq_flags rf; 6410 struct rq *rq; 6411 LIST_HEAD(local_unthrottle); 6412 6413 rcu_read_lock(); 6414 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq, 6415 throttled_list) { 6416 rq = rq_of(cfs_rq); 6417 6418 if (!remaining) { 6419 throttled = true; 6420 break; 6421 } 6422 6423 rq_lock_irqsave(rq, &rf); 6424 if (!cfs_rq_throttled(cfs_rq)) 6425 goto next; 6426 6427 /* Already queued for async unthrottle */ 6428 if (!list_empty(&cfs_rq->throttled_csd_list)) 6429 goto next; 6430 6431 /* By the above checks, this should never be true */ 6432 WARN_ON_ONCE(cfs_rq->runtime_remaining > 0); 6433 6434 raw_spin_lock(&cfs_b->lock); 6435 runtime = -cfs_rq->runtime_remaining + 1; 6436 if (runtime > cfs_b->runtime) 6437 runtime = cfs_b->runtime; 6438 cfs_b->runtime -= runtime; 6439 remaining = cfs_b->runtime; 6440 raw_spin_unlock(&cfs_b->lock); 6441 6442 cfs_rq->runtime_remaining += runtime; 6443 6444 /* we check whether we're throttled above */ 6445 if (cfs_rq->runtime_remaining > 0) { 6446 if (cpu_of(rq) != this_cpu) { 6447 unthrottle_cfs_rq_async(cfs_rq); 6448 } else { 6449 /* 6450 * We currently only expect to be unthrottling 6451 * a single cfs_rq locally. 6452 */ 6453 WARN_ON_ONCE(!list_empty(&local_unthrottle)); 6454 list_add_tail(&cfs_rq->throttled_csd_list, 6455 &local_unthrottle); 6456 } 6457 } else { 6458 throttled = true; 6459 } 6460 6461 next: 6462 rq_unlock_irqrestore(rq, &rf); 6463 } 6464 6465 list_for_each_entry_safe(cfs_rq, tmp, &local_unthrottle, 6466 throttled_csd_list) { 6467 struct rq *rq = rq_of(cfs_rq); 6468 6469 rq_lock_irqsave(rq, &rf); 6470 6471 list_del_init(&cfs_rq->throttled_csd_list); 6472 6473 if (cfs_rq_throttled(cfs_rq)) 6474 unthrottle_cfs_rq(cfs_rq); 6475 6476 rq_unlock_irqrestore(rq, &rf); 6477 } 6478 WARN_ON_ONCE(!list_empty(&local_unthrottle)); 6479 6480 rcu_read_unlock(); 6481 6482 return throttled; 6483 } 6484 6485 /* 6486 * Responsible for refilling a task_group's bandwidth and unthrottling its 6487 * cfs_rqs as appropriate. If there has been no activity within the last 6488 * period the timer is deactivated until scheduling resumes; cfs_b->idle is 6489 * used to track this state. 6490 */ 6491 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags) 6492 __must_hold(&cfs_b->lock) 6493 { 6494 int throttled; 6495 6496 /* no need to continue the timer with no bandwidth constraint */ 6497 if (cfs_b->quota == RUNTIME_INF) 6498 goto out_deactivate; 6499 6500 throttled = !list_empty(&cfs_b->throttled_cfs_rq); 6501 cfs_b->nr_periods += overrun; 6502 6503 /* Refill extra burst quota even if cfs_b->idle */ 6504 __refill_cfs_bandwidth_runtime(cfs_b); 6505 6506 /* 6507 * idle depends on !throttled (for the case of a large deficit), and if 6508 * we're going inactive then everything else can be deferred 6509 */ 6510 if (cfs_b->idle && !throttled) 6511 goto out_deactivate; 6512 6513 if (!throttled) { 6514 /* mark as potentially idle for the upcoming period */ 6515 cfs_b->idle = 1; 6516 return 0; 6517 } 6518 6519 /* account preceding periods in which throttling occurred */ 6520 cfs_b->nr_throttled += overrun; 6521 6522 /* 6523 * This check is repeated as we release cfs_b->lock while we unthrottle. 6524 */ 6525 while (throttled && cfs_b->runtime > 0) { 6526 raw_spin_unlock_irqrestore(&cfs_b->lock, flags); 6527 /* we can't nest cfs_b->lock while distributing bandwidth */ 6528 throttled = distribute_cfs_runtime(cfs_b); 6529 raw_spin_lock_irqsave(&cfs_b->lock, flags); 6530 } 6531 6532 /* 6533 * While we are ensured activity in the period following an 6534 * unthrottle, this also covers the case in which the new bandwidth is 6535 * insufficient to cover the existing bandwidth deficit. (Forcing the 6536 * timer to remain active while there are any throttled entities.) 6537 */ 6538 cfs_b->idle = 0; 6539 6540 return 0; 6541 6542 out_deactivate: 6543 return 1; 6544 } 6545 6546 /* a cfs_rq won't donate quota below this amount */ 6547 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC; 6548 /* minimum remaining period time to redistribute slack quota */ 6549 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC; 6550 /* how long we wait to gather additional slack before distributing */ 6551 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC; 6552 6553 /* 6554 * Are we near the end of the current quota period? 6555 * 6556 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the 6557 * hrtimer base being cleared by hrtimer_start. In the case of 6558 * migrate_hrtimers, base is never cleared, so we are fine. 6559 */ 6560 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire) 6561 { 6562 struct hrtimer *refresh_timer = &cfs_b->period_timer; 6563 s64 remaining; 6564 6565 /* if the call-back is running a quota refresh is already occurring */ 6566 if (hrtimer_callback_running(refresh_timer)) 6567 return 1; 6568 6569 /* is a quota refresh about to occur? */ 6570 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer)); 6571 if (remaining < (s64)min_expire) 6572 return 1; 6573 6574 return 0; 6575 } 6576 6577 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b) 6578 { 6579 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration; 6580 6581 /* if there's a quota refresh soon don't bother with slack */ 6582 if (runtime_refresh_within(cfs_b, min_left)) 6583 return; 6584 6585 /* don't push forwards an existing deferred unthrottle */ 6586 if (cfs_b->slack_started) 6587 return; 6588 cfs_b->slack_started = true; 6589 6590 hrtimer_start(&cfs_b->slack_timer, 6591 ns_to_ktime(cfs_bandwidth_slack_period), 6592 HRTIMER_MODE_REL); 6593 } 6594 6595 /* we know any runtime found here is valid as update_curr() precedes return */ 6596 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq) 6597 { 6598 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 6599 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime; 6600 6601 if (slack_runtime <= 0) 6602 return; 6603 6604 raw_spin_lock(&cfs_b->lock); 6605 if (cfs_b->quota != RUNTIME_INF) { 6606 cfs_b->runtime += slack_runtime; 6607 6608 /* we are under rq->lock, defer unthrottling using a timer */ 6609 if (cfs_b->runtime > sched_cfs_bandwidth_slice() && 6610 !list_empty(&cfs_b->throttled_cfs_rq)) 6611 start_cfs_slack_bandwidth(cfs_b); 6612 } 6613 raw_spin_unlock(&cfs_b->lock); 6614 6615 /* even if it's not valid for return we don't want to try again */ 6616 cfs_rq->runtime_remaining -= slack_runtime; 6617 } 6618 6619 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) 6620 { 6621 if (!cfs_bandwidth_used()) 6622 return; 6623 6624 if (!cfs_rq->runtime_enabled || cfs_rq->nr_queued) 6625 return; 6626 6627 __return_cfs_rq_runtime(cfs_rq); 6628 } 6629 6630 /* 6631 * This is done with a timer (instead of inline with bandwidth return) since 6632 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs. 6633 */ 6634 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b) 6635 { 6636 u64 runtime = 0, slice = sched_cfs_bandwidth_slice(); 6637 unsigned long flags; 6638 6639 /* confirm we're still not at a refresh boundary */ 6640 raw_spin_lock_irqsave(&cfs_b->lock, flags); 6641 cfs_b->slack_started = false; 6642 6643 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) { 6644 raw_spin_unlock_irqrestore(&cfs_b->lock, flags); 6645 return; 6646 } 6647 6648 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice) 6649 runtime = cfs_b->runtime; 6650 6651 raw_spin_unlock_irqrestore(&cfs_b->lock, flags); 6652 6653 if (!runtime) 6654 return; 6655 6656 distribute_cfs_runtime(cfs_b); 6657 } 6658 6659 /* 6660 * When a group wakes up we want to make sure that its quota is not already 6661 * expired/exceeded, otherwise it may be allowed to steal additional ticks of 6662 * runtime as update_curr() throttling can not trigger until it's on-rq. 6663 */ 6664 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) 6665 { 6666 if (!cfs_bandwidth_used()) 6667 return; 6668 6669 /* an active group must be handled by the update_curr()->put() path */ 6670 if (!cfs_rq->runtime_enabled || cfs_rq->curr) 6671 return; 6672 6673 /* ensure the group is not already throttled */ 6674 if (cfs_rq_throttled(cfs_rq)) 6675 return; 6676 6677 /* update runtime allocation */ 6678 account_cfs_rq_runtime(cfs_rq, 0); 6679 if (cfs_rq->runtime_remaining <= 0) 6680 throttle_cfs_rq(cfs_rq); 6681 } 6682 6683 static void sync_throttle(struct task_group *tg, int cpu) 6684 { 6685 struct cfs_rq *pcfs_rq, *cfs_rq; 6686 6687 if (!cfs_bandwidth_used()) 6688 return; 6689 6690 if (!tg->parent) 6691 return; 6692 6693 cfs_rq = tg->cfs_rq[cpu]; 6694 pcfs_rq = tg->parent->cfs_rq[cpu]; 6695 6696 cfs_rq->throttle_count = pcfs_rq->throttle_count; 6697 cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu)); 6698 6699 /* 6700 * It is not enough to sync the "pelt_clock_throttled" indicator 6701 * with the parent cfs_rq when the hierarchy is not queued. 6702 * Always join a throttled hierarchy with PELT clock throttled 6703 * and leaf it to the first enqueue, or distribution to 6704 * unthrottle the PELT clock. 6705 */ 6706 if (cfs_rq->throttle_count) 6707 cfs_rq->pelt_clock_throttled = 1; 6708 } 6709 6710 /* conditionally throttle active cfs_rq's from put_prev_entity() */ 6711 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) 6712 { 6713 if (!cfs_bandwidth_used()) 6714 return false; 6715 6716 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0)) 6717 return false; 6718 6719 /* 6720 * it's possible for a throttled entity to be forced into a running 6721 * state (e.g. set_curr_task), in this case we're finished. 6722 */ 6723 if (cfs_rq_throttled(cfs_rq)) 6724 return true; 6725 6726 return throttle_cfs_rq(cfs_rq); 6727 } 6728 6729 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer) 6730 { 6731 struct cfs_bandwidth *cfs_b = 6732 container_of(timer, struct cfs_bandwidth, slack_timer); 6733 6734 do_sched_cfs_slack_timer(cfs_b); 6735 6736 return HRTIMER_NORESTART; 6737 } 6738 6739 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer) 6740 { 6741 struct cfs_bandwidth *cfs_b = 6742 container_of(timer, struct cfs_bandwidth, period_timer); 6743 unsigned long flags; 6744 int overrun; 6745 int idle = 0; 6746 int count = 0; 6747 6748 raw_spin_lock_irqsave(&cfs_b->lock, flags); 6749 for (;;) { 6750 overrun = hrtimer_forward_now(timer, cfs_b->period); 6751 if (!overrun) 6752 break; 6753 6754 idle = do_sched_cfs_period_timer(cfs_b, overrun, flags); 6755 6756 if (++count > 3) { 6757 u64 new, old = ktime_to_ns(cfs_b->period); 6758 6759 /* 6760 * Grow period by a factor of 2 to avoid losing precision. 6761 * Precision loss in the quota/period ratio can cause __cfs_schedulable 6762 * to fail. 6763 */ 6764 new = old * 2; 6765 if (new < max_bw_quota_period_us * NSEC_PER_USEC) { 6766 cfs_b->period = ns_to_ktime(new); 6767 cfs_b->quota *= 2; 6768 cfs_b->burst *= 2; 6769 6770 pr_warn_ratelimited( 6771 "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n", 6772 smp_processor_id(), 6773 div_u64(new, NSEC_PER_USEC), 6774 div_u64(cfs_b->quota, NSEC_PER_USEC)); 6775 } else { 6776 pr_warn_ratelimited( 6777 "cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n", 6778 smp_processor_id(), 6779 div_u64(old, NSEC_PER_USEC), 6780 div_u64(cfs_b->quota, NSEC_PER_USEC)); 6781 } 6782 6783 /* reset count so we don't come right back in here */ 6784 count = 0; 6785 } 6786 } 6787 if (idle) 6788 cfs_b->period_active = 0; 6789 raw_spin_unlock_irqrestore(&cfs_b->lock, flags); 6790 6791 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART; 6792 } 6793 6794 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) 6795 { 6796 raw_spin_lock_init(&cfs_b->lock); 6797 cfs_b->runtime = 0; 6798 cfs_b->quota = RUNTIME_INF; 6799 cfs_b->period = us_to_ktime(default_bw_period_us()); 6800 cfs_b->burst = 0; 6801 cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF; 6802 6803 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq); 6804 hrtimer_setup(&cfs_b->period_timer, sched_cfs_period_timer, CLOCK_MONOTONIC, 6805 HRTIMER_MODE_ABS_PINNED); 6806 6807 /* Add a random offset so that timers interleave */ 6808 hrtimer_set_expires(&cfs_b->period_timer, 6809 get_random_u32_below(cfs_b->period)); 6810 hrtimer_setup(&cfs_b->slack_timer, sched_cfs_slack_timer, CLOCK_MONOTONIC, 6811 HRTIMER_MODE_REL); 6812 cfs_b->slack_started = false; 6813 } 6814 6815 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) 6816 { 6817 cfs_rq->runtime_enabled = 0; 6818 INIT_LIST_HEAD(&cfs_rq->throttled_list); 6819 INIT_LIST_HEAD(&cfs_rq->throttled_csd_list); 6820 INIT_LIST_HEAD(&cfs_rq->throttled_limbo_list); 6821 } 6822 6823 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b) 6824 { 6825 lockdep_assert_held(&cfs_b->lock); 6826 6827 if (cfs_b->period_active) 6828 return; 6829 6830 cfs_b->period_active = 1; 6831 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period); 6832 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED); 6833 } 6834 6835 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) 6836 { 6837 int __maybe_unused i; 6838 6839 /* init_cfs_bandwidth() was not called */ 6840 if (!cfs_b->throttled_cfs_rq.next) 6841 return; 6842 6843 hrtimer_cancel(&cfs_b->period_timer); 6844 hrtimer_cancel(&cfs_b->slack_timer); 6845 6846 /* 6847 * It is possible that we still have some cfs_rq's pending on a CSD 6848 * list, though this race is very rare. In order for this to occur, we 6849 * must have raced with the last task leaving the group while there 6850 * exist throttled cfs_rq(s), and the period_timer must have queued the 6851 * CSD item but the remote cpu has not yet processed it. To handle this, 6852 * we can simply flush all pending CSD work inline here. We're 6853 * guaranteed at this point that no additional cfs_rq of this group can 6854 * join a CSD list. 6855 */ 6856 for_each_possible_cpu(i) { 6857 struct rq *rq = cpu_rq(i); 6858 unsigned long flags; 6859 6860 if (list_empty(&rq->cfsb_csd_list)) 6861 continue; 6862 6863 local_irq_save(flags); 6864 __cfsb_csd_unthrottle(rq); 6865 local_irq_restore(flags); 6866 } 6867 } 6868 6869 /* 6870 * Both these CPU hotplug callbacks race against unregister_fair_sched_group() 6871 * 6872 * The race is harmless, since modifying bandwidth settings of unhooked group 6873 * bits doesn't do much. 6874 */ 6875 6876 /* cpu online callback */ 6877 static void __maybe_unused update_runtime_enabled(struct rq *rq) 6878 { 6879 struct task_group *tg; 6880 6881 lockdep_assert_rq_held(rq); 6882 6883 rcu_read_lock(); 6884 list_for_each_entry_rcu(tg, &task_groups, list) { 6885 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; 6886 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)]; 6887 6888 raw_spin_lock(&cfs_b->lock); 6889 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF; 6890 raw_spin_unlock(&cfs_b->lock); 6891 } 6892 rcu_read_unlock(); 6893 } 6894 6895 /* cpu offline callback */ 6896 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq) 6897 { 6898 struct task_group *tg; 6899 6900 lockdep_assert_rq_held(rq); 6901 6902 // Do not unthrottle for an active CPU 6903 if (cpumask_test_cpu(cpu_of(rq), cpu_active_mask)) 6904 return; 6905 6906 /* 6907 * The rq clock has already been updated in the 6908 * set_rq_offline(), so we should skip updating 6909 * the rq clock again in unthrottle_cfs_rq(). 6910 */ 6911 rq_clock_start_loop_update(rq); 6912 6913 rcu_read_lock(); 6914 list_for_each_entry_rcu(tg, &task_groups, list) { 6915 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)]; 6916 6917 if (!cfs_rq->runtime_enabled) 6918 continue; 6919 6920 /* 6921 * Offline rq is schedulable till CPU is completely disabled 6922 * in take_cpu_down(), so we prevent new cfs throttling here. 6923 */ 6924 cfs_rq->runtime_enabled = 0; 6925 6926 if (!cfs_rq_throttled(cfs_rq)) 6927 continue; 6928 6929 /* 6930 * clock_task is not advancing so we just need to make sure 6931 * there's some valid quota amount 6932 */ 6933 cfs_rq->runtime_remaining = 1; 6934 unthrottle_cfs_rq(cfs_rq); 6935 } 6936 rcu_read_unlock(); 6937 6938 rq_clock_stop_loop_update(rq); 6939 } 6940 6941 bool cfs_task_bw_constrained(struct task_struct *p) 6942 { 6943 struct cfs_rq *cfs_rq = task_cfs_rq(p); 6944 6945 if (!cfs_bandwidth_used()) 6946 return false; 6947 6948 if (cfs_rq->runtime_enabled || 6949 tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF) 6950 return true; 6951 6952 return false; 6953 } 6954 6955 #ifdef CONFIG_NO_HZ_FULL 6956 /* called from pick_next_task_fair() */ 6957 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) 6958 { 6959 int cpu = cpu_of(rq); 6960 6961 if (!cfs_bandwidth_used()) 6962 return; 6963 6964 if (!tick_nohz_full_cpu(cpu)) 6965 return; 6966 6967 if (rq->nr_running != 1) 6968 return; 6969 6970 /* 6971 * We know there is only one task runnable and we've just picked it. The 6972 * normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will 6973 * be otherwise able to stop the tick. Just need to check if we are using 6974 * bandwidth control. 6975 */ 6976 if (cfs_task_bw_constrained(p)) 6977 tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED); 6978 } 6979 #endif /* CONFIG_NO_HZ_FULL */ 6980 6981 #else /* !CONFIG_CFS_BANDWIDTH: */ 6982 6983 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {} 6984 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; } 6985 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {} 6986 static inline void sync_throttle(struct task_group *tg, int cpu) {} 6987 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {} 6988 static void task_throttle_setup_work(struct task_struct *p) {} 6989 static bool task_is_throttled(struct task_struct *p) { return false; } 6990 static void dequeue_throttled_task(struct task_struct *p, int flags) {} 6991 static bool enqueue_throttled_task(struct task_struct *p) { return false; } 6992 static void record_throttle_clock(struct cfs_rq *cfs_rq) {} 6993 6994 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq) 6995 { 6996 return 0; 6997 } 6998 6999 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq) 7000 { 7001 return false; 7002 } 7003 7004 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq) 7005 { 7006 return 0; 7007 } 7008 7009 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu) 7010 { 7011 return 0; 7012 } 7013 7014 #ifdef CONFIG_FAIR_GROUP_SCHED 7015 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {} 7016 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {} 7017 #endif 7018 7019 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg) 7020 { 7021 return NULL; 7022 } 7023 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {} 7024 static inline void update_runtime_enabled(struct rq *rq) {} 7025 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {} 7026 #ifdef CONFIG_CGROUP_SCHED 7027 bool cfs_task_bw_constrained(struct task_struct *p) 7028 { 7029 return false; 7030 } 7031 #endif 7032 #endif /* !CONFIG_CFS_BANDWIDTH */ 7033 7034 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL) 7035 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {} 7036 #endif 7037 7038 /************************************************** 7039 * CFS operations on tasks: 7040 */ 7041 7042 #ifdef CONFIG_SCHED_HRTICK 7043 static void hrtick_start_fair(struct rq *rq, struct task_struct *p) 7044 { 7045 struct sched_entity *se = &p->se; 7046 unsigned long scale = 1024; 7047 unsigned long util = 0; 7048 u64 vdelta; 7049 u64 delta; 7050 7051 WARN_ON_ONCE(task_rq(p) != rq); 7052 7053 if (rq->cfs.h_nr_queued <= 1) 7054 return; 7055 7056 /* 7057 * Compute time until virtual deadline 7058 */ 7059 vdelta = se->deadline - se->vruntime; 7060 if ((s64)vdelta < 0) { 7061 if (task_current_donor(rq, p)) 7062 resched_curr(rq); 7063 return; 7064 } 7065 delta = (se->load.weight * vdelta) / NICE_0_LOAD; 7066 7067 /* 7068 * Correct for instantaneous load of other classes. 7069 */ 7070 util += cpu_util_irq(rq); 7071 if (util && util < 1024) { 7072 scale *= 1024; 7073 scale /= (1024 - util); 7074 } 7075 7076 hrtick_start(rq, (scale * delta) / 1024); 7077 } 7078 7079 /* 7080 * Called on enqueue to start the hrtick when h_nr_queued becomes more than 1. 7081 */ 7082 static void hrtick_update(struct rq *rq) 7083 { 7084 struct task_struct *donor = rq->donor; 7085 7086 if (!hrtick_enabled_fair(rq) || donor->sched_class != &fair_sched_class) 7087 return; 7088 7089 if (hrtick_active(rq)) 7090 return; 7091 7092 hrtick_start_fair(rq, donor); 7093 } 7094 #else /* !CONFIG_SCHED_HRTICK: */ 7095 static inline void 7096 hrtick_start_fair(struct rq *rq, struct task_struct *p) 7097 { 7098 } 7099 7100 static inline void hrtick_update(struct rq *rq) 7101 { 7102 } 7103 #endif /* !CONFIG_SCHED_HRTICK */ 7104 7105 static inline bool cpu_overutilized(int cpu) 7106 { 7107 unsigned long rq_util_max; 7108 7109 if (!sched_energy_enabled()) 7110 return false; 7111 7112 rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX); 7113 7114 /* Return true only if the utilization doesn't fit CPU's capacity */ 7115 return !util_fits_cpu(cpu_util_cfs(cpu), 0, rq_util_max, cpu); 7116 } 7117 7118 /* 7119 * overutilized value make sense only if EAS is enabled 7120 */ 7121 static inline bool is_rd_overutilized(struct root_domain *rd) 7122 { 7123 return !sched_energy_enabled() || READ_ONCE(rd->overutilized); 7124 } 7125 7126 static inline void set_rd_overutilized(struct root_domain *rd, bool flag) 7127 { 7128 if (!sched_energy_enabled()) 7129 return; 7130 7131 WRITE_ONCE(rd->overutilized, flag); 7132 trace_sched_overutilized_tp(rd, flag); 7133 } 7134 7135 static inline void check_update_overutilized_status(struct rq *rq) 7136 { 7137 /* 7138 * overutilized field is used for load balancing decisions only 7139 * if energy aware scheduler is being used 7140 */ 7141 7142 if (!is_rd_overutilized(rq->rd) && cpu_overutilized(rq->cpu)) 7143 set_rd_overutilized(rq->rd, 1); 7144 } 7145 7146 /* Runqueue only has SCHED_IDLE tasks enqueued */ 7147 static int sched_idle_rq(struct rq *rq) 7148 { 7149 return unlikely(rq->nr_running == rq->cfs.h_nr_idle && 7150 rq->nr_running); 7151 } 7152 7153 static int choose_sched_idle_rq(struct rq *rq, struct task_struct *p) 7154 { 7155 return sched_idle_rq(rq) && !task_has_idle_policy(p); 7156 } 7157 7158 static int choose_idle_cpu(int cpu, struct task_struct *p) 7159 { 7160 return available_idle_cpu(cpu) || 7161 choose_sched_idle_rq(cpu_rq(cpu), p); 7162 } 7163 7164 static void 7165 requeue_delayed_entity(struct sched_entity *se) 7166 { 7167 struct cfs_rq *cfs_rq = cfs_rq_of(se); 7168 7169 /* 7170 * se->sched_delayed should imply: se->on_rq == 1. 7171 * Because a delayed entity is one that is still on 7172 * the runqueue competing until elegibility. 7173 */ 7174 WARN_ON_ONCE(!se->sched_delayed); 7175 WARN_ON_ONCE(!se->on_rq); 7176 7177 if (update_entity_lag(cfs_rq, se)) { 7178 cfs_rq->nr_queued--; 7179 if (se != cfs_rq->curr) 7180 __dequeue_entity(cfs_rq, se); 7181 place_entity(cfs_rq, se, 0); 7182 if (se != cfs_rq->curr) 7183 __enqueue_entity(cfs_rq, se); 7184 cfs_rq->nr_queued++; 7185 } 7186 7187 update_load_avg(cfs_rq, se, 0); 7188 clear_delayed(se); 7189 } 7190 7191 /* 7192 * The enqueue_task method is called before nr_running is 7193 * increased. Here we update the fair scheduling stats and 7194 * then put the task into the rbtree: 7195 */ 7196 static void 7197 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags) 7198 { 7199 struct cfs_rq *cfs_rq; 7200 struct sched_entity *se = &p->se; 7201 int h_nr_idle = task_has_idle_policy(p); 7202 int h_nr_runnable = 1; 7203 int task_new = !(flags & ENQUEUE_WAKEUP); 7204 int rq_h_nr_queued = rq->cfs.h_nr_queued; 7205 u64 slice = 0; 7206 7207 if (task_is_throttled(p) && enqueue_throttled_task(p)) 7208 return; 7209 7210 /* 7211 * The code below (indirectly) updates schedutil which looks at 7212 * the cfs_rq utilization to select a frequency. 7213 * Let's add the task's estimated utilization to the cfs_rq's 7214 * estimated utilization, before we update schedutil. 7215 */ 7216 if (!p->se.sched_delayed || (flags & ENQUEUE_DELAYED)) 7217 util_est_enqueue(&rq->cfs, p); 7218 7219 if (flags & ENQUEUE_DELAYED) { 7220 requeue_delayed_entity(se); 7221 return; 7222 } 7223 7224 /* 7225 * If in_iowait is set, the code below may not trigger any cpufreq 7226 * utilization updates, so do it here explicitly with the IOWAIT flag 7227 * passed. 7228 */ 7229 if (p->in_iowait) 7230 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT); 7231 7232 if (task_new && se->sched_delayed) 7233 h_nr_runnable = 0; 7234 7235 for_each_sched_entity(se) { 7236 if (se->on_rq) { 7237 if (se->sched_delayed) 7238 requeue_delayed_entity(se); 7239 break; 7240 } 7241 cfs_rq = cfs_rq_of(se); 7242 7243 /* 7244 * Basically set the slice of group entries to the min_slice of 7245 * their respective cfs_rq. This ensures the group can service 7246 * its entities in the desired time-frame. 7247 */ 7248 if (slice) { 7249 se->slice = slice; 7250 se->custom_slice = 1; 7251 } 7252 enqueue_entity(cfs_rq, se, flags); 7253 slice = cfs_rq_min_slice(cfs_rq); 7254 7255 cfs_rq->h_nr_runnable += h_nr_runnable; 7256 cfs_rq->h_nr_queued++; 7257 cfs_rq->h_nr_idle += h_nr_idle; 7258 7259 if (cfs_rq_is_idle(cfs_rq)) 7260 h_nr_idle = 1; 7261 7262 flags = ENQUEUE_WAKEUP; 7263 } 7264 7265 for_each_sched_entity(se) { 7266 cfs_rq = cfs_rq_of(se); 7267 7268 update_load_avg(cfs_rq, se, UPDATE_TG); 7269 se_update_runnable(se); 7270 update_cfs_group(se); 7271 7272 se->slice = slice; 7273 if (se != cfs_rq->curr) 7274 min_vruntime_cb_propagate(&se->run_node, NULL); 7275 slice = cfs_rq_min_slice(cfs_rq); 7276 7277 cfs_rq->h_nr_runnable += h_nr_runnable; 7278 cfs_rq->h_nr_queued++; 7279 cfs_rq->h_nr_idle += h_nr_idle; 7280 7281 if (cfs_rq_is_idle(cfs_rq)) 7282 h_nr_idle = 1; 7283 } 7284 7285 if (!rq_h_nr_queued && rq->cfs.h_nr_queued) 7286 dl_server_start(&rq->fair_server); 7287 7288 /* At this point se is NULL and we are at root level*/ 7289 add_nr_running(rq, 1); 7290 7291 /* 7292 * Since new tasks are assigned an initial util_avg equal to 7293 * half of the spare capacity of their CPU, tiny tasks have the 7294 * ability to cross the overutilized threshold, which will 7295 * result in the load balancer ruining all the task placement 7296 * done by EAS. As a way to mitigate that effect, do not account 7297 * for the first enqueue operation of new tasks during the 7298 * overutilized flag detection. 7299 * 7300 * A better way of solving this problem would be to wait for 7301 * the PELT signals of tasks to converge before taking them 7302 * into account, but that is not straightforward to implement, 7303 * and the following generally works well enough in practice. 7304 */ 7305 if (!task_new) 7306 check_update_overutilized_status(rq); 7307 7308 assert_list_leaf_cfs_rq(rq); 7309 7310 hrtick_update(rq); 7311 } 7312 7313 /* 7314 * Basically dequeue_task_fair(), except it can deal with dequeue_entity() 7315 * failing half-way through and resume the dequeue later. 7316 * 7317 * Returns: 7318 * -1 - dequeue delayed 7319 * 0 - dequeue throttled 7320 * 1 - dequeue complete 7321 */ 7322 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags) 7323 { 7324 bool was_sched_idle = sched_idle_rq(rq); 7325 bool task_sleep = flags & DEQUEUE_SLEEP; 7326 bool task_delayed = flags & DEQUEUE_DELAYED; 7327 bool task_throttled = flags & DEQUEUE_THROTTLE; 7328 struct task_struct *p = NULL; 7329 int h_nr_idle = 0; 7330 int h_nr_queued = 0; 7331 int h_nr_runnable = 0; 7332 struct cfs_rq *cfs_rq; 7333 u64 slice = 0; 7334 7335 if (entity_is_task(se)) { 7336 p = task_of(se); 7337 h_nr_queued = 1; 7338 h_nr_idle = task_has_idle_policy(p); 7339 if (task_sleep || task_delayed || !se->sched_delayed) 7340 h_nr_runnable = 1; 7341 } 7342 7343 for_each_sched_entity(se) { 7344 cfs_rq = cfs_rq_of(se); 7345 7346 if (!dequeue_entity(cfs_rq, se, flags)) { 7347 if (p && &p->se == se) 7348 return -1; 7349 7350 slice = cfs_rq_min_slice(cfs_rq); 7351 break; 7352 } 7353 7354 cfs_rq->h_nr_runnable -= h_nr_runnable; 7355 cfs_rq->h_nr_queued -= h_nr_queued; 7356 cfs_rq->h_nr_idle -= h_nr_idle; 7357 7358 if (cfs_rq_is_idle(cfs_rq)) 7359 h_nr_idle = h_nr_queued; 7360 7361 if (throttled_hierarchy(cfs_rq) && task_throttled) 7362 record_throttle_clock(cfs_rq); 7363 7364 /* Don't dequeue parent if it has other entities besides us */ 7365 if (cfs_rq->load.weight) { 7366 slice = cfs_rq_min_slice(cfs_rq); 7367 7368 /* Avoid re-evaluating load for this entity: */ 7369 se = parent_entity(se); 7370 /* 7371 * Bias pick_next to pick a task from this cfs_rq, as 7372 * p is sleeping when it is within its sched_slice. 7373 */ 7374 if (task_sleep && se) 7375 set_next_buddy(se); 7376 break; 7377 } 7378 flags |= DEQUEUE_SLEEP; 7379 flags &= ~(DEQUEUE_DELAYED | DEQUEUE_SPECIAL); 7380 } 7381 7382 for_each_sched_entity(se) { 7383 cfs_rq = cfs_rq_of(se); 7384 7385 update_load_avg(cfs_rq, se, UPDATE_TG); 7386 se_update_runnable(se); 7387 update_cfs_group(se); 7388 7389 se->slice = slice; 7390 if (se != cfs_rq->curr) 7391 min_vruntime_cb_propagate(&se->run_node, NULL); 7392 slice = cfs_rq_min_slice(cfs_rq); 7393 7394 cfs_rq->h_nr_runnable -= h_nr_runnable; 7395 cfs_rq->h_nr_queued -= h_nr_queued; 7396 cfs_rq->h_nr_idle -= h_nr_idle; 7397 7398 if (cfs_rq_is_idle(cfs_rq)) 7399 h_nr_idle = h_nr_queued; 7400 7401 if (throttled_hierarchy(cfs_rq) && task_throttled) 7402 record_throttle_clock(cfs_rq); 7403 } 7404 7405 sub_nr_running(rq, h_nr_queued); 7406 7407 /* balance early to pull high priority tasks */ 7408 if (unlikely(!was_sched_idle && sched_idle_rq(rq))) 7409 rq->next_balance = jiffies; 7410 7411 if (p && task_delayed) { 7412 WARN_ON_ONCE(!task_sleep); 7413 WARN_ON_ONCE(p->on_rq != 1); 7414 7415 /* 7416 * Fix-up what block_task() skipped. 7417 * 7418 * Must be last, @p might not be valid after this. 7419 */ 7420 __block_task(rq, p); 7421 } 7422 7423 return 1; 7424 } 7425 7426 /* 7427 * The dequeue_task method is called before nr_running is 7428 * decreased. We remove the task from the rbtree and 7429 * update the fair scheduling stats: 7430 */ 7431 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags) 7432 { 7433 if (task_is_throttled(p)) { 7434 dequeue_throttled_task(p, flags); 7435 return true; 7436 } 7437 7438 if (!p->se.sched_delayed) 7439 util_est_dequeue(&rq->cfs, p); 7440 7441 util_est_update(&rq->cfs, p, flags & DEQUEUE_SLEEP); 7442 if (dequeue_entities(rq, &p->se, flags) < 0) 7443 return false; 7444 7445 /* 7446 * Must not reference @p after dequeue_entities(DEQUEUE_DELAYED). 7447 */ 7448 return true; 7449 } 7450 7451 static inline unsigned int cfs_h_nr_delayed(struct rq *rq) 7452 { 7453 return (rq->cfs.h_nr_queued - rq->cfs.h_nr_runnable); 7454 } 7455 7456 /* Working cpumask for: sched_balance_rq(), sched_balance_newidle(). */ 7457 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask); 7458 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask); 7459 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask); 7460 7461 #ifdef CONFIG_NO_HZ_COMMON 7462 7463 static struct { 7464 cpumask_var_t idle_cpus_mask; 7465 int has_blocked_load; /* Idle CPUS has blocked load */ 7466 int needs_update; /* Newly idle CPUs need their next_balance collated */ 7467 unsigned long next_balance; /* in jiffy units */ 7468 unsigned long next_blocked; /* Next update of blocked load in jiffies */ 7469 } nohz ____cacheline_aligned; 7470 7471 #endif /* CONFIG_NO_HZ_COMMON */ 7472 7473 static unsigned long cpu_load(struct rq *rq) 7474 { 7475 return cfs_rq_load_avg(&rq->cfs); 7476 } 7477 7478 /* 7479 * cpu_load_without - compute CPU load without any contributions from *p 7480 * @cpu: the CPU which load is requested 7481 * @p: the task which load should be discounted 7482 * 7483 * The load of a CPU is defined by the load of tasks currently enqueued on that 7484 * CPU as well as tasks which are currently sleeping after an execution on that 7485 * CPU. 7486 * 7487 * This method returns the load of the specified CPU by discounting the load of 7488 * the specified task, whenever the task is currently contributing to the CPU 7489 * load. 7490 */ 7491 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p) 7492 { 7493 struct cfs_rq *cfs_rq; 7494 unsigned int load; 7495 7496 /* Task has no contribution or is new */ 7497 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 7498 return cpu_load(rq); 7499 7500 cfs_rq = &rq->cfs; 7501 load = READ_ONCE(cfs_rq->avg.load_avg); 7502 7503 /* Discount task's util from CPU's util */ 7504 lsub_positive(&load, task_h_load(p)); 7505 7506 return load; 7507 } 7508 7509 static unsigned long cpu_runnable(struct rq *rq) 7510 { 7511 return cfs_rq_runnable_avg(&rq->cfs); 7512 } 7513 7514 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p) 7515 { 7516 struct cfs_rq *cfs_rq; 7517 unsigned int runnable; 7518 7519 /* Task has no contribution or is new */ 7520 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 7521 return cpu_runnable(rq); 7522 7523 cfs_rq = &rq->cfs; 7524 runnable = READ_ONCE(cfs_rq->avg.runnable_avg); 7525 7526 /* Discount task's runnable from CPU's runnable */ 7527 lsub_positive(&runnable, p->se.avg.runnable_avg); 7528 7529 return runnable; 7530 } 7531 7532 static unsigned long capacity_of(int cpu) 7533 { 7534 return cpu_rq(cpu)->cpu_capacity; 7535 } 7536 7537 static void record_wakee(struct task_struct *p) 7538 { 7539 /* 7540 * Only decay a single time; tasks that have less then 1 wakeup per 7541 * jiffy will not have built up many flips. 7542 */ 7543 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) { 7544 current->wakee_flips >>= 1; 7545 current->wakee_flip_decay_ts = jiffies; 7546 } 7547 7548 if (current->last_wakee != p) { 7549 current->last_wakee = p; 7550 current->wakee_flips++; 7551 } 7552 } 7553 7554 /* 7555 * Detect M:N waker/wakee relationships via a switching-frequency heuristic. 7556 * 7557 * A waker of many should wake a different task than the one last awakened 7558 * at a frequency roughly N times higher than one of its wakees. 7559 * 7560 * In order to determine whether we should let the load spread vs consolidating 7561 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one 7562 * partner, and a factor of lls_size higher frequency in the other. 7563 * 7564 * With both conditions met, we can be relatively sure that the relationship is 7565 * non-monogamous, with partner count exceeding socket size. 7566 * 7567 * Waker/wakee being client/server, worker/dispatcher, interrupt source or 7568 * whatever is irrelevant, spread criteria is apparent partner count exceeds 7569 * socket size. 7570 */ 7571 static int wake_wide(struct task_struct *p) 7572 { 7573 unsigned int master = current->wakee_flips; 7574 unsigned int slave = p->wakee_flips; 7575 int factor = __this_cpu_read(sd_llc_size); 7576 7577 if (master < slave) 7578 swap(master, slave); 7579 if (slave < factor || master < slave * factor) 7580 return 0; 7581 return 1; 7582 } 7583 7584 /* 7585 * The purpose of wake_affine() is to quickly determine on which CPU we can run 7586 * soonest. For the purpose of speed we only consider the waking and previous 7587 * CPU. 7588 * 7589 * wake_affine_idle() - only considers 'now', it check if the waking CPU is 7590 * cache-affine and is (or will be) idle. 7591 * 7592 * wake_affine_weight() - considers the weight to reflect the average 7593 * scheduling latency of the CPUs. This seems to work 7594 * for the overloaded case. 7595 */ 7596 static int 7597 wake_affine_idle(int this_cpu, int prev_cpu, int sync) 7598 { 7599 /* 7600 * If this_cpu is idle, it implies the wakeup is from interrupt 7601 * context. Only allow the move if cache is shared. Otherwise an 7602 * interrupt intensive workload could force all tasks onto one 7603 * node depending on the IO topology or IRQ affinity settings. 7604 * 7605 * If the prev_cpu is idle and cache affine then avoid a migration. 7606 * There is no guarantee that the cache hot data from an interrupt 7607 * is more important than cache hot data on the prev_cpu and from 7608 * a cpufreq perspective, it's better to have higher utilisation 7609 * on one CPU. 7610 */ 7611 if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu)) 7612 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu; 7613 7614 if (sync) { 7615 struct rq *rq = cpu_rq(this_cpu); 7616 7617 if ((rq->nr_running - cfs_h_nr_delayed(rq)) == 1) 7618 return this_cpu; 7619 } 7620 7621 if (available_idle_cpu(prev_cpu)) 7622 return prev_cpu; 7623 7624 return nr_cpumask_bits; 7625 } 7626 7627 static int 7628 wake_affine_weight(struct sched_domain *sd, struct task_struct *p, 7629 int this_cpu, int prev_cpu, int sync) 7630 { 7631 s64 this_eff_load, prev_eff_load; 7632 unsigned long task_load; 7633 7634 this_eff_load = cpu_load(cpu_rq(this_cpu)); 7635 7636 if (sync) { 7637 unsigned long current_load = task_h_load(current); 7638 7639 if (current_load > this_eff_load) 7640 return this_cpu; 7641 7642 this_eff_load -= current_load; 7643 } 7644 7645 task_load = task_h_load(p); 7646 7647 this_eff_load += task_load; 7648 if (sched_feat(WA_BIAS)) 7649 this_eff_load *= 100; 7650 this_eff_load *= capacity_of(prev_cpu); 7651 7652 prev_eff_load = cpu_load(cpu_rq(prev_cpu)); 7653 prev_eff_load -= task_load; 7654 if (sched_feat(WA_BIAS)) 7655 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2; 7656 prev_eff_load *= capacity_of(this_cpu); 7657 7658 /* 7659 * If sync, adjust the weight of prev_eff_load such that if 7660 * prev_eff == this_eff that select_idle_sibling() will consider 7661 * stacking the wakee on top of the waker if no other CPU is 7662 * idle. 7663 */ 7664 if (sync) 7665 prev_eff_load += 1; 7666 7667 return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits; 7668 } 7669 7670 static int wake_affine(struct sched_domain *sd, struct task_struct *p, 7671 int this_cpu, int prev_cpu, int sync) 7672 { 7673 int target = nr_cpumask_bits; 7674 7675 if (sched_feat(WA_IDLE)) 7676 target = wake_affine_idle(this_cpu, prev_cpu, sync); 7677 7678 if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits) 7679 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync); 7680 7681 schedstat_inc(p->stats.nr_wakeups_affine_attempts); 7682 if (target != this_cpu) 7683 return prev_cpu; 7684 7685 schedstat_inc(sd->ttwu_move_affine); 7686 schedstat_inc(p->stats.nr_wakeups_affine); 7687 return target; 7688 } 7689 7690 static struct sched_group * 7691 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu); 7692 7693 /* 7694 * sched_balance_find_dst_group_cpu - find the idlest CPU among the CPUs in the group. 7695 */ 7696 static int 7697 sched_balance_find_dst_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu) 7698 { 7699 unsigned long load, min_load = ULONG_MAX; 7700 unsigned int min_exit_latency = UINT_MAX; 7701 u64 latest_idle_timestamp = 0; 7702 int least_loaded_cpu = this_cpu; 7703 int shallowest_idle_cpu = -1; 7704 int i; 7705 7706 /* Check if we have any choice: */ 7707 if (group->group_weight == 1) 7708 return cpumask_first(sched_group_span(group)); 7709 7710 /* Traverse only the allowed CPUs */ 7711 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) { 7712 struct rq *rq = cpu_rq(i); 7713 7714 if (!sched_core_cookie_match(rq, p)) 7715 continue; 7716 7717 if (choose_sched_idle_rq(rq, p)) 7718 return i; 7719 7720 if (available_idle_cpu(i)) { 7721 struct cpuidle_state *idle = idle_get_state(rq); 7722 if (idle && idle->exit_latency < min_exit_latency) { 7723 /* 7724 * We give priority to a CPU whose idle state 7725 * has the smallest exit latency irrespective 7726 * of any idle timestamp. 7727 */ 7728 min_exit_latency = idle->exit_latency; 7729 latest_idle_timestamp = rq->idle_stamp; 7730 shallowest_idle_cpu = i; 7731 } else if ((!idle || idle->exit_latency == min_exit_latency) && 7732 rq->idle_stamp > latest_idle_timestamp) { 7733 /* 7734 * If equal or no active idle state, then 7735 * the most recently idled CPU might have 7736 * a warmer cache. 7737 */ 7738 latest_idle_timestamp = rq->idle_stamp; 7739 shallowest_idle_cpu = i; 7740 } 7741 } else if (shallowest_idle_cpu == -1) { 7742 load = cpu_load(cpu_rq(i)); 7743 if (load < min_load) { 7744 min_load = load; 7745 least_loaded_cpu = i; 7746 } 7747 } 7748 } 7749 7750 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu; 7751 } 7752 7753 static inline int sched_balance_find_dst_cpu(struct sched_domain *sd, struct task_struct *p, 7754 int cpu, int prev_cpu, int sd_flag) 7755 { 7756 int new_cpu = cpu; 7757 7758 if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr)) 7759 return prev_cpu; 7760 7761 /* 7762 * We need task's util for cpu_util_without, sync it up to 7763 * prev_cpu's last_update_time. 7764 */ 7765 if (!(sd_flag & SD_BALANCE_FORK)) 7766 sync_entity_load_avg(&p->se); 7767 7768 while (sd) { 7769 struct sched_group *group; 7770 struct sched_domain *tmp; 7771 int weight; 7772 7773 if (!(sd->flags & sd_flag)) { 7774 sd = sd->child; 7775 continue; 7776 } 7777 7778 group = sched_balance_find_dst_group(sd, p, cpu); 7779 if (!group) { 7780 sd = sd->child; 7781 continue; 7782 } 7783 7784 new_cpu = sched_balance_find_dst_group_cpu(group, p, cpu); 7785 if (new_cpu == cpu) { 7786 /* Now try balancing at a lower domain level of 'cpu': */ 7787 sd = sd->child; 7788 continue; 7789 } 7790 7791 /* Now try balancing at a lower domain level of 'new_cpu': */ 7792 cpu = new_cpu; 7793 weight = sd->span_weight; 7794 sd = NULL; 7795 for_each_domain(cpu, tmp) { 7796 if (weight <= tmp->span_weight) 7797 break; 7798 if (tmp->flags & sd_flag) 7799 sd = tmp; 7800 } 7801 } 7802 7803 return new_cpu; 7804 } 7805 7806 static inline int __select_idle_cpu(int cpu, struct task_struct *p) 7807 { 7808 if (choose_idle_cpu(cpu, p) && sched_cpu_cookie_match(cpu_rq(cpu), p)) 7809 return cpu; 7810 7811 return -1; 7812 } 7813 7814 #ifdef CONFIG_SCHED_SMT 7815 DEFINE_STATIC_KEY_FALSE(sched_smt_present); 7816 EXPORT_SYMBOL_GPL(sched_smt_present); 7817 7818 static inline void set_idle_cores(int cpu, int val) 7819 { 7820 struct sched_domain_shared *sds; 7821 7822 sds = rcu_dereference_all(per_cpu(sd_llc_shared, cpu)); 7823 if (sds) 7824 WRITE_ONCE(sds->has_idle_cores, val); 7825 } 7826 7827 static inline bool test_idle_cores(int cpu) 7828 { 7829 struct sched_domain_shared *sds; 7830 7831 sds = rcu_dereference_all(per_cpu(sd_llc_shared, cpu)); 7832 if (sds) 7833 return READ_ONCE(sds->has_idle_cores); 7834 7835 return false; 7836 } 7837 7838 /* 7839 * Scans the local SMT mask to see if the entire core is idle, and records this 7840 * information in sd_llc_shared->has_idle_cores. 7841 * 7842 * Since SMT siblings share all cache levels, inspecting this limited remote 7843 * state should be fairly cheap. 7844 */ 7845 void __update_idle_core(struct rq *rq) 7846 { 7847 int core = cpu_of(rq); 7848 int cpu; 7849 7850 rcu_read_lock(); 7851 if (test_idle_cores(core)) 7852 goto unlock; 7853 7854 for_each_cpu(cpu, cpu_smt_mask(core)) { 7855 if (cpu == core) 7856 continue; 7857 7858 if (!available_idle_cpu(cpu)) 7859 goto unlock; 7860 } 7861 7862 set_idle_cores(core, 1); 7863 unlock: 7864 rcu_read_unlock(); 7865 } 7866 7867 /* 7868 * Scan the entire LLC domain for idle cores; this dynamically switches off if 7869 * there are no idle cores left in the system; tracked through 7870 * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above. 7871 */ 7872 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu) 7873 { 7874 bool idle = true; 7875 int cpu; 7876 7877 for_each_cpu(cpu, cpu_smt_mask(core)) { 7878 if (!available_idle_cpu(cpu)) { 7879 idle = false; 7880 if (*idle_cpu == -1) { 7881 if (choose_sched_idle_rq(cpu_rq(cpu), p) && 7882 cpumask_test_cpu(cpu, cpus)) { 7883 *idle_cpu = cpu; 7884 break; 7885 } 7886 continue; 7887 } 7888 break; 7889 } 7890 if (*idle_cpu == -1 && cpumask_test_cpu(cpu, cpus)) 7891 *idle_cpu = cpu; 7892 } 7893 7894 if (idle) 7895 return core; 7896 7897 cpumask_andnot(cpus, cpus, cpu_smt_mask(core)); 7898 return -1; 7899 } 7900 7901 /* 7902 * Scan the local SMT mask for idle CPUs. 7903 */ 7904 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target) 7905 { 7906 int cpu; 7907 7908 for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) { 7909 if (cpu == target) 7910 continue; 7911 /* 7912 * Check if the CPU is in the LLC scheduling domain of @target. 7913 * Due to isolcpus, there is no guarantee that all the siblings are in the domain. 7914 */ 7915 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) 7916 continue; 7917 if (choose_idle_cpu(cpu, p)) 7918 return cpu; 7919 } 7920 7921 return -1; 7922 } 7923 7924 #else /* !CONFIG_SCHED_SMT: */ 7925 7926 static inline void set_idle_cores(int cpu, int val) 7927 { 7928 } 7929 7930 static inline bool test_idle_cores(int cpu) 7931 { 7932 return false; 7933 } 7934 7935 static inline int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu) 7936 { 7937 return __select_idle_cpu(core, p); 7938 } 7939 7940 static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target) 7941 { 7942 return -1; 7943 } 7944 7945 #endif /* !CONFIG_SCHED_SMT */ 7946 7947 /* 7948 * Scan the LLC domain for idle CPUs; this is dynamically regulated by 7949 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the 7950 * average idle time for this rq (as found in rq->avg_idle). 7951 */ 7952 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target) 7953 { 7954 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask); 7955 int i, cpu, idle_cpu = -1, nr = INT_MAX; 7956 7957 if (sched_feat(SIS_UTIL)) { 7958 /* 7959 * Increment because !--nr is the condition to stop scan. 7960 * 7961 * Since "sd" is "sd_llc" for target CPU dereferenced in the 7962 * caller, it is safe to directly dereference "sd->shared". 7963 * Topology bits always ensure it assigned for "sd_llc" abd it 7964 * cannot disappear as long as we have a RCU protected 7965 * reference to one the associated "sd" here. 7966 */ 7967 nr = READ_ONCE(sd->shared->nr_idle_scan) + 1; 7968 /* overloaded LLC is unlikely to have idle cpu/core */ 7969 if (nr == 1) 7970 return -1; 7971 } 7972 7973 if (!cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr)) 7974 return -1; 7975 7976 if (static_branch_unlikely(&sched_cluster_active)) { 7977 struct sched_group *sg = sd->groups; 7978 7979 if (sg->flags & SD_CLUSTER) { 7980 for_each_cpu_wrap(cpu, sched_group_span(sg), target + 1) { 7981 if (!cpumask_test_cpu(cpu, cpus)) 7982 continue; 7983 7984 if (has_idle_core) { 7985 i = select_idle_core(p, cpu, cpus, &idle_cpu); 7986 if ((unsigned int)i < nr_cpumask_bits) 7987 return i; 7988 } else { 7989 if (--nr <= 0) 7990 return -1; 7991 idle_cpu = __select_idle_cpu(cpu, p); 7992 if ((unsigned int)idle_cpu < nr_cpumask_bits) 7993 return idle_cpu; 7994 } 7995 } 7996 cpumask_andnot(cpus, cpus, sched_group_span(sg)); 7997 } 7998 } 7999 8000 for_each_cpu_wrap(cpu, cpus, target + 1) { 8001 if (has_idle_core) { 8002 i = select_idle_core(p, cpu, cpus, &idle_cpu); 8003 if ((unsigned int)i < nr_cpumask_bits) 8004 return i; 8005 8006 } else { 8007 if (--nr <= 0) 8008 return -1; 8009 idle_cpu = __select_idle_cpu(cpu, p); 8010 if ((unsigned int)idle_cpu < nr_cpumask_bits) 8011 break; 8012 } 8013 } 8014 8015 if (has_idle_core) 8016 set_idle_cores(target, false); 8017 8018 return idle_cpu; 8019 } 8020 8021 /* 8022 * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which 8023 * the task fits. If no CPU is big enough, but there are idle ones, try to 8024 * maximize capacity. 8025 */ 8026 static int 8027 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target) 8028 { 8029 unsigned long task_util, util_min, util_max, best_cap = 0; 8030 int fits, best_fits = 0; 8031 int cpu, best_cpu = -1; 8032 struct cpumask *cpus; 8033 8034 cpus = this_cpu_cpumask_var_ptr(select_rq_mask); 8035 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr); 8036 8037 task_util = task_util_est(p); 8038 util_min = uclamp_eff_value(p, UCLAMP_MIN); 8039 util_max = uclamp_eff_value(p, UCLAMP_MAX); 8040 8041 for_each_cpu_wrap(cpu, cpus, target) { 8042 unsigned long cpu_cap = capacity_of(cpu); 8043 8044 if (!choose_idle_cpu(cpu, p)) 8045 continue; 8046 8047 fits = util_fits_cpu(task_util, util_min, util_max, cpu); 8048 8049 /* This CPU fits with all requirements */ 8050 if (fits > 0) 8051 return cpu; 8052 /* 8053 * Only the min performance hint (i.e. uclamp_min) doesn't fit. 8054 * Look for the CPU with best capacity. 8055 */ 8056 else if (fits < 0) 8057 cpu_cap = get_actual_cpu_capacity(cpu); 8058 8059 /* 8060 * First, select CPU which fits better (-1 being better than 0). 8061 * Then, select the one with best capacity at same level. 8062 */ 8063 if ((fits < best_fits) || 8064 ((fits == best_fits) && (cpu_cap > best_cap))) { 8065 best_cap = cpu_cap; 8066 best_cpu = cpu; 8067 best_fits = fits; 8068 } 8069 } 8070 8071 return best_cpu; 8072 } 8073 8074 static inline bool asym_fits_cpu(unsigned long util, 8075 unsigned long util_min, 8076 unsigned long util_max, 8077 int cpu) 8078 { 8079 if (sched_asym_cpucap_active()) 8080 /* 8081 * Return true only if the cpu fully fits the task requirements 8082 * which include the utilization and the performance hints. 8083 */ 8084 return (util_fits_cpu(util, util_min, util_max, cpu) > 0); 8085 8086 return true; 8087 } 8088 8089 /* 8090 * Try and locate an idle core/thread in the LLC cache domain. 8091 */ 8092 static int select_idle_sibling(struct task_struct *p, int prev, int target) 8093 { 8094 bool has_idle_core = false; 8095 struct sched_domain *sd; 8096 unsigned long task_util, util_min, util_max; 8097 int i, recent_used_cpu, prev_aff = -1; 8098 8099 /* 8100 * On asymmetric system, update task utilization because we will check 8101 * that the task fits with CPU's capacity. 8102 */ 8103 if (sched_asym_cpucap_active()) { 8104 sync_entity_load_avg(&p->se); 8105 task_util = task_util_est(p); 8106 util_min = uclamp_eff_value(p, UCLAMP_MIN); 8107 util_max = uclamp_eff_value(p, UCLAMP_MAX); 8108 } 8109 8110 /* 8111 * per-cpu select_rq_mask usage 8112 */ 8113 lockdep_assert_irqs_disabled(); 8114 8115 if (choose_idle_cpu(target, p) && 8116 asym_fits_cpu(task_util, util_min, util_max, target)) 8117 return target; 8118 8119 /* 8120 * If the previous CPU is cache affine and idle, don't be stupid: 8121 */ 8122 if (prev != target && cpus_share_cache(prev, target) && 8123 choose_idle_cpu(prev, p) && 8124 asym_fits_cpu(task_util, util_min, util_max, prev)) { 8125 8126 if (!static_branch_unlikely(&sched_cluster_active) || 8127 cpus_share_resources(prev, target)) 8128 return prev; 8129 8130 prev_aff = prev; 8131 } 8132 8133 /* 8134 * Allow a per-cpu kthread to stack with the wakee if the 8135 * kworker thread and the tasks previous CPUs are the same. 8136 * The assumption is that the wakee queued work for the 8137 * per-cpu kthread that is now complete and the wakeup is 8138 * essentially a sync wakeup. An obvious example of this 8139 * pattern is IO completions. 8140 */ 8141 if (is_per_cpu_kthread(current) && 8142 in_task() && 8143 prev == smp_processor_id() && 8144 this_rq()->nr_running <= 1 && 8145 asym_fits_cpu(task_util, util_min, util_max, prev)) { 8146 return prev; 8147 } 8148 8149 /* Check a recently used CPU as a potential idle candidate: */ 8150 recent_used_cpu = p->recent_used_cpu; 8151 p->recent_used_cpu = prev; 8152 if (recent_used_cpu != prev && 8153 recent_used_cpu != target && 8154 cpus_share_cache(recent_used_cpu, target) && 8155 choose_idle_cpu(recent_used_cpu, p) && 8156 cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) && 8157 asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) { 8158 8159 if (!static_branch_unlikely(&sched_cluster_active) || 8160 cpus_share_resources(recent_used_cpu, target)) 8161 return recent_used_cpu; 8162 8163 } else { 8164 recent_used_cpu = -1; 8165 } 8166 8167 /* 8168 * For asymmetric CPU capacity systems, our domain of interest is 8169 * sd_asym_cpucapacity rather than sd_llc. 8170 */ 8171 if (sched_asym_cpucap_active()) { 8172 sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, target)); 8173 /* 8174 * On an asymmetric CPU capacity system where an exclusive 8175 * cpuset defines a symmetric island (i.e. one unique 8176 * capacity_orig value through the cpuset), the key will be set 8177 * but the CPUs within that cpuset will not have a domain with 8178 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric 8179 * capacity path. 8180 */ 8181 if (sd) { 8182 i = select_idle_capacity(p, sd, target); 8183 return ((unsigned)i < nr_cpumask_bits) ? i : target; 8184 } 8185 } 8186 8187 sd = rcu_dereference_all(per_cpu(sd_llc, target)); 8188 if (!sd) 8189 return target; 8190 8191 if (sched_smt_active()) { 8192 has_idle_core = test_idle_cores(target); 8193 8194 if (!has_idle_core && cpus_share_cache(prev, target)) { 8195 i = select_idle_smt(p, sd, prev); 8196 if ((unsigned int)i < nr_cpumask_bits) 8197 return i; 8198 } 8199 } 8200 8201 i = select_idle_cpu(p, sd, has_idle_core, target); 8202 if ((unsigned)i < nr_cpumask_bits) 8203 return i; 8204 8205 /* 8206 * For cluster machines which have lower sharing cache like L2 or 8207 * LLC Tag, we tend to find an idle CPU in the target's cluster 8208 * first. But prev_cpu or recent_used_cpu may also be a good candidate, 8209 * use them if possible when no idle CPU found in select_idle_cpu(). 8210 */ 8211 if ((unsigned int)prev_aff < nr_cpumask_bits) 8212 return prev_aff; 8213 if ((unsigned int)recent_used_cpu < nr_cpumask_bits) 8214 return recent_used_cpu; 8215 8216 return target; 8217 } 8218 8219 /** 8220 * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks. 8221 * @cpu: the CPU to get the utilization for 8222 * @p: task for which the CPU utilization should be predicted or NULL 8223 * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL 8224 * @boost: 1 to enable boosting, otherwise 0 8225 * 8226 * The unit of the return value must be the same as the one of CPU capacity 8227 * so that CPU utilization can be compared with CPU capacity. 8228 * 8229 * CPU utilization is the sum of running time of runnable tasks plus the 8230 * recent utilization of currently non-runnable tasks on that CPU. 8231 * It represents the amount of CPU capacity currently used by CFS tasks in 8232 * the range [0..max CPU capacity] with max CPU capacity being the CPU 8233 * capacity at f_max. 8234 * 8235 * The estimated CPU utilization is defined as the maximum between CPU 8236 * utilization and sum of the estimated utilization of the currently 8237 * runnable tasks on that CPU. It preserves a utilization "snapshot" of 8238 * previously-executed tasks, which helps better deduce how busy a CPU will 8239 * be when a long-sleeping task wakes up. The contribution to CPU utilization 8240 * of such a task would be significantly decayed at this point of time. 8241 * 8242 * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization). 8243 * CPU contention for CFS tasks can be detected by CPU runnable > CPU 8244 * utilization. Boosting is implemented in cpu_util() so that internal 8245 * users (e.g. EAS) can use it next to external users (e.g. schedutil), 8246 * latter via cpu_util_cfs_boost(). 8247 * 8248 * CPU utilization can be higher than the current CPU capacity 8249 * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because 8250 * of rounding errors as well as task migrations or wakeups of new tasks. 8251 * CPU utilization has to be capped to fit into the [0..max CPU capacity] 8252 * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%) 8253 * could be seen as over-utilized even though CPU1 has 20% of spare CPU 8254 * capacity. CPU utilization is allowed to overshoot current CPU capacity 8255 * though since this is useful for predicting the CPU capacity required 8256 * after task migrations (scheduler-driven DVFS). 8257 * 8258 * Return: (Boosted) (estimated) utilization for the specified CPU. 8259 */ 8260 static unsigned long 8261 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost) 8262 { 8263 struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs; 8264 unsigned long util = READ_ONCE(cfs_rq->avg.util_avg); 8265 unsigned long runnable; 8266 8267 if (boost) { 8268 runnable = READ_ONCE(cfs_rq->avg.runnable_avg); 8269 util = max(util, runnable); 8270 } 8271 8272 /* 8273 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its 8274 * contribution. If @p migrates from another CPU to @cpu add its 8275 * contribution. In all the other cases @cpu is not impacted by the 8276 * migration so its util_avg is already correct. 8277 */ 8278 if (p && task_cpu(p) == cpu && dst_cpu != cpu) 8279 lsub_positive(&util, task_util(p)); 8280 else if (p && task_cpu(p) != cpu && dst_cpu == cpu) 8281 util += task_util(p); 8282 8283 if (sched_feat(UTIL_EST)) { 8284 unsigned long util_est; 8285 8286 util_est = READ_ONCE(cfs_rq->avg.util_est); 8287 8288 /* 8289 * During wake-up @p isn't enqueued yet and doesn't contribute 8290 * to any cpu_rq(cpu)->cfs.avg.util_est. 8291 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p 8292 * has been enqueued. 8293 * 8294 * During exec (@dst_cpu = -1) @p is enqueued and does 8295 * contribute to cpu_rq(cpu)->cfs.util_est. 8296 * Remove it to "simulate" cpu_util without @p's contribution. 8297 * 8298 * Despite the task_on_rq_queued(@p) check there is still a 8299 * small window for a possible race when an exec 8300 * select_task_rq_fair() races with LB's detach_task(). 8301 * 8302 * detach_task() 8303 * deactivate_task() 8304 * p->on_rq = TASK_ON_RQ_MIGRATING; 8305 * -------------------------------- A 8306 * dequeue_task() \ 8307 * dequeue_task_fair() + Race Time 8308 * util_est_dequeue() / 8309 * -------------------------------- B 8310 * 8311 * The additional check "current == p" is required to further 8312 * reduce the race window. 8313 */ 8314 if (dst_cpu == cpu) 8315 util_est += _task_util_est(p); 8316 else if (p && unlikely(task_on_rq_queued(p) || current == p)) 8317 lsub_positive(&util_est, _task_util_est(p)); 8318 8319 util = max(util, util_est); 8320 } 8321 8322 return min(util, arch_scale_cpu_capacity(cpu)); 8323 } 8324 8325 unsigned long cpu_util_cfs(int cpu) 8326 { 8327 return cpu_util(cpu, NULL, -1, 0); 8328 } 8329 8330 unsigned long cpu_util_cfs_boost(int cpu) 8331 { 8332 return cpu_util(cpu, NULL, -1, 1); 8333 } 8334 8335 /* 8336 * cpu_util_without: compute cpu utilization without any contributions from *p 8337 * @cpu: the CPU which utilization is requested 8338 * @p: the task which utilization should be discounted 8339 * 8340 * The utilization of a CPU is defined by the utilization of tasks currently 8341 * enqueued on that CPU as well as tasks which are currently sleeping after an 8342 * execution on that CPU. 8343 * 8344 * This method returns the utilization of the specified CPU by discounting the 8345 * utilization of the specified task, whenever the task is currently 8346 * contributing to the CPU utilization. 8347 */ 8348 static unsigned long cpu_util_without(int cpu, struct task_struct *p) 8349 { 8350 /* Task has no contribution or is new */ 8351 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 8352 p = NULL; 8353 8354 return cpu_util(cpu, p, -1, 0); 8355 } 8356 8357 /* 8358 * This function computes an effective utilization for the given CPU, to be 8359 * used for frequency selection given the linear relation: f = u * f_max. 8360 * 8361 * The scheduler tracks the following metrics: 8362 * 8363 * cpu_util_{cfs,rt,dl,irq}() 8364 * cpu_bw_dl() 8365 * 8366 * Where the cfs,rt and dl util numbers are tracked with the same metric and 8367 * synchronized windows and are thus directly comparable. 8368 * 8369 * The cfs,rt,dl utilization are the running times measured with rq->clock_task 8370 * which excludes things like IRQ and steal-time. These latter are then accrued 8371 * in the IRQ utilization. 8372 * 8373 * The DL bandwidth number OTOH is not a measured metric but a value computed 8374 * based on the task model parameters and gives the minimal utilization 8375 * required to meet deadlines. 8376 */ 8377 unsigned long effective_cpu_util(int cpu, unsigned long util_cfs, 8378 unsigned long *min, 8379 unsigned long *max) 8380 { 8381 unsigned long util, irq, scale; 8382 struct rq *rq = cpu_rq(cpu); 8383 8384 scale = arch_scale_cpu_capacity(cpu); 8385 8386 /* 8387 * Early check to see if IRQ/steal time saturates the CPU, can be 8388 * because of inaccuracies in how we track these -- see 8389 * update_irq_load_avg(). 8390 */ 8391 irq = cpu_util_irq(rq); 8392 if (unlikely(irq >= scale)) { 8393 if (min) 8394 *min = scale; 8395 if (max) 8396 *max = scale; 8397 return scale; 8398 } 8399 8400 if (min) { 8401 /* 8402 * The minimum utilization returns the highest level between: 8403 * - the computed DL bandwidth needed with the IRQ pressure which 8404 * steals time to the deadline task. 8405 * - The minimum performance requirement for CFS and/or RT. 8406 */ 8407 *min = max(irq + cpu_bw_dl(rq), uclamp_rq_get(rq, UCLAMP_MIN)); 8408 8409 /* 8410 * When an RT task is runnable and uclamp is not used, we must 8411 * ensure that the task will run at maximum compute capacity. 8412 */ 8413 if (!uclamp_is_used() && rt_rq_is_runnable(&rq->rt)) 8414 *min = max(*min, scale); 8415 } 8416 8417 /* 8418 * Because the time spend on RT/DL tasks is visible as 'lost' time to 8419 * CFS tasks and we use the same metric to track the effective 8420 * utilization (PELT windows are synchronized) we can directly add them 8421 * to obtain the CPU's actual utilization. 8422 */ 8423 util = util_cfs + cpu_util_rt(rq); 8424 util += cpu_util_dl(rq); 8425 8426 /* 8427 * The maximum hint is a soft bandwidth requirement, which can be lower 8428 * than the actual utilization because of uclamp_max requirements. 8429 */ 8430 if (max) 8431 *max = min(scale, uclamp_rq_get(rq, UCLAMP_MAX)); 8432 8433 if (util >= scale) 8434 return scale; 8435 8436 /* 8437 * There is still idle time; further improve the number by using the 8438 * IRQ metric. Because IRQ/steal time is hidden from the task clock we 8439 * need to scale the task numbers: 8440 * 8441 * max - irq 8442 * U' = irq + --------- * U 8443 * max 8444 */ 8445 util = scale_irq_capacity(util, irq, scale); 8446 util += irq; 8447 8448 return min(scale, util); 8449 } 8450 8451 unsigned long sched_cpu_util(int cpu) 8452 { 8453 return effective_cpu_util(cpu, cpu_util_cfs(cpu), NULL, NULL); 8454 } 8455 8456 /* 8457 * energy_env - Utilization landscape for energy estimation. 8458 * @task_busy_time: Utilization contribution by the task for which we test the 8459 * placement. Given by eenv_task_busy_time(). 8460 * @pd_busy_time: Utilization of the whole perf domain without the task 8461 * contribution. Given by eenv_pd_busy_time(). 8462 * @cpu_cap: Maximum CPU capacity for the perf domain. 8463 * @pd_cap: Entire perf domain capacity. (pd->nr_cpus * cpu_cap). 8464 */ 8465 struct energy_env { 8466 unsigned long task_busy_time; 8467 unsigned long pd_busy_time; 8468 unsigned long cpu_cap; 8469 unsigned long pd_cap; 8470 }; 8471 8472 /* 8473 * Compute the task busy time for compute_energy(). This time cannot be 8474 * injected directly into effective_cpu_util() because of the IRQ scaling. 8475 * The latter only makes sense with the most recent CPUs where the task has 8476 * run. 8477 */ 8478 static inline void eenv_task_busy_time(struct energy_env *eenv, 8479 struct task_struct *p, int prev_cpu) 8480 { 8481 unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu); 8482 unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu)); 8483 8484 if (unlikely(irq >= max_cap)) 8485 busy_time = max_cap; 8486 else 8487 busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap); 8488 8489 eenv->task_busy_time = busy_time; 8490 } 8491 8492 /* 8493 * Compute the perf_domain (PD) busy time for compute_energy(). Based on the 8494 * utilization for each @pd_cpus, it however doesn't take into account 8495 * clamping since the ratio (utilization / cpu_capacity) is already enough to 8496 * scale the EM reported power consumption at the (eventually clamped) 8497 * cpu_capacity. 8498 * 8499 * The contribution of the task @p for which we want to estimate the 8500 * energy cost is removed (by cpu_util()) and must be calculated 8501 * separately (see eenv_task_busy_time). This ensures: 8502 * 8503 * - A stable PD utilization, no matter which CPU of that PD we want to place 8504 * the task on. 8505 * 8506 * - A fair comparison between CPUs as the task contribution (task_util()) 8507 * will always be the same no matter which CPU utilization we rely on 8508 * (util_avg or util_est). 8509 * 8510 * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't 8511 * exceed @eenv->pd_cap. 8512 */ 8513 static inline void eenv_pd_busy_time(struct energy_env *eenv, 8514 struct cpumask *pd_cpus, 8515 struct task_struct *p) 8516 { 8517 unsigned long busy_time = 0; 8518 int cpu; 8519 8520 for_each_cpu(cpu, pd_cpus) { 8521 unsigned long util = cpu_util(cpu, p, -1, 0); 8522 8523 busy_time += effective_cpu_util(cpu, util, NULL, NULL); 8524 } 8525 8526 eenv->pd_busy_time = min(eenv->pd_cap, busy_time); 8527 } 8528 8529 /* 8530 * Compute the maximum utilization for compute_energy() when the task @p 8531 * is placed on the cpu @dst_cpu. 8532 * 8533 * Returns the maximum utilization among @eenv->cpus. This utilization can't 8534 * exceed @eenv->cpu_cap. 8535 */ 8536 static inline unsigned long 8537 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus, 8538 struct task_struct *p, int dst_cpu) 8539 { 8540 unsigned long max_util = 0; 8541 int cpu; 8542 8543 for_each_cpu(cpu, pd_cpus) { 8544 struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL; 8545 unsigned long util = cpu_util(cpu, p, dst_cpu, 1); 8546 unsigned long eff_util, min, max; 8547 8548 /* 8549 * Performance domain frequency: utilization clamping 8550 * must be considered since it affects the selection 8551 * of the performance domain frequency. 8552 * NOTE: in case RT tasks are running, by default the min 8553 * utilization can be max OPP. 8554 */ 8555 eff_util = effective_cpu_util(cpu, util, &min, &max); 8556 8557 /* Task's uclamp can modify min and max value */ 8558 if (tsk && uclamp_is_used()) { 8559 min = max(min, uclamp_eff_value(p, UCLAMP_MIN)); 8560 8561 /* 8562 * If there is no active max uclamp constraint, 8563 * directly use task's one, otherwise keep max. 8564 */ 8565 if (uclamp_rq_is_idle(cpu_rq(cpu))) 8566 max = uclamp_eff_value(p, UCLAMP_MAX); 8567 else 8568 max = max(max, uclamp_eff_value(p, UCLAMP_MAX)); 8569 } 8570 8571 eff_util = sugov_effective_cpu_perf(cpu, eff_util, min, max); 8572 max_util = max(max_util, eff_util); 8573 } 8574 8575 return min(max_util, eenv->cpu_cap); 8576 } 8577 8578 /* 8579 * compute_energy(): Use the Energy Model to estimate the energy that @pd would 8580 * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task 8581 * contribution is ignored. 8582 */ 8583 static inline unsigned long 8584 compute_energy(struct energy_env *eenv, struct perf_domain *pd, 8585 struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu) 8586 { 8587 unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu); 8588 unsigned long busy_time = eenv->pd_busy_time; 8589 unsigned long energy; 8590 8591 if (dst_cpu >= 0) 8592 busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time); 8593 8594 energy = em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap); 8595 8596 trace_sched_compute_energy_tp(p, dst_cpu, energy, max_util, busy_time); 8597 8598 return energy; 8599 } 8600 8601 /* 8602 * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the 8603 * waking task. find_energy_efficient_cpu() looks for the CPU with maximum 8604 * spare capacity in each performance domain and uses it as a potential 8605 * candidate to execute the task. Then, it uses the Energy Model to figure 8606 * out which of the CPU candidates is the most energy-efficient. 8607 * 8608 * The rationale for this heuristic is as follows. In a performance domain, 8609 * all the most energy efficient CPU candidates (according to the Energy 8610 * Model) are those for which we'll request a low frequency. When there are 8611 * several CPUs for which the frequency request will be the same, we don't 8612 * have enough data to break the tie between them, because the Energy Model 8613 * only includes active power costs. With this model, if we assume that 8614 * frequency requests follow utilization (e.g. using schedutil), the CPU with 8615 * the maximum spare capacity in a performance domain is guaranteed to be among 8616 * the best candidates of the performance domain. 8617 * 8618 * In practice, it could be preferable from an energy standpoint to pack 8619 * small tasks on a CPU in order to let other CPUs go in deeper idle states, 8620 * but that could also hurt our chances to go cluster idle, and we have no 8621 * ways to tell with the current Energy Model if this is actually a good 8622 * idea or not. So, find_energy_efficient_cpu() basically favors 8623 * cluster-packing, and spreading inside a cluster. That should at least be 8624 * a good thing for latency, and this is consistent with the idea that most 8625 * of the energy savings of EAS come from the asymmetry of the system, and 8626 * not so much from breaking the tie between identical CPUs. That's also the 8627 * reason why EAS is enabled in the topology code only for systems where 8628 * SD_ASYM_CPUCAPACITY is set. 8629 * 8630 * NOTE: Forkees are not accepted in the energy-aware wake-up path because 8631 * they don't have any useful utilization data yet and it's not possible to 8632 * forecast their impact on energy consumption. Consequently, they will be 8633 * placed by sched_balance_find_dst_cpu() on the least loaded CPU, which might turn out 8634 * to be energy-inefficient in some use-cases. The alternative would be to 8635 * bias new tasks towards specific types of CPUs first, or to try to infer 8636 * their util_avg from the parent task, but those heuristics could hurt 8637 * other use-cases too. So, until someone finds a better way to solve this, 8638 * let's keep things simple by re-using the existing slow path. 8639 */ 8640 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu) 8641 { 8642 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask); 8643 unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX; 8644 unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0; 8645 unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024; 8646 struct root_domain *rd = this_rq()->rd; 8647 int cpu, best_energy_cpu, target = -1; 8648 int prev_fits = -1, best_fits = -1; 8649 unsigned long best_actual_cap = 0; 8650 unsigned long prev_actual_cap = 0; 8651 struct sched_domain *sd; 8652 struct perf_domain *pd; 8653 struct energy_env eenv; 8654 8655 pd = rcu_dereference_all(rd->pd); 8656 if (!pd) 8657 return target; 8658 8659 /* 8660 * Energy-aware wake-up happens on the lowest sched_domain starting 8661 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu. 8662 */ 8663 sd = rcu_dereference_all(*this_cpu_ptr(&sd_asym_cpucapacity)); 8664 while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd))) 8665 sd = sd->parent; 8666 if (!sd) 8667 return target; 8668 8669 target = prev_cpu; 8670 8671 sync_entity_load_avg(&p->se); 8672 if (!task_util_est(p) && p_util_min == 0) 8673 return target; 8674 8675 eenv_task_busy_time(&eenv, p, prev_cpu); 8676 8677 for (; pd; pd = pd->next) { 8678 unsigned long util_min = p_util_min, util_max = p_util_max; 8679 unsigned long cpu_cap, cpu_actual_cap, util; 8680 long prev_spare_cap = -1, max_spare_cap = -1; 8681 unsigned long rq_util_min, rq_util_max; 8682 unsigned long cur_delta, base_energy; 8683 int max_spare_cap_cpu = -1; 8684 int fits, max_fits = -1; 8685 8686 if (!cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask)) 8687 continue; 8688 8689 /* Account external pressure for the energy estimation */ 8690 cpu = cpumask_first(cpus); 8691 cpu_actual_cap = get_actual_cpu_capacity(cpu); 8692 8693 eenv.cpu_cap = cpu_actual_cap; 8694 eenv.pd_cap = 0; 8695 8696 for_each_cpu(cpu, cpus) { 8697 struct rq *rq = cpu_rq(cpu); 8698 8699 eenv.pd_cap += cpu_actual_cap; 8700 8701 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) 8702 continue; 8703 8704 if (!cpumask_test_cpu(cpu, p->cpus_ptr)) 8705 continue; 8706 8707 util = cpu_util(cpu, p, cpu, 0); 8708 cpu_cap = capacity_of(cpu); 8709 8710 /* 8711 * Skip CPUs that cannot satisfy the capacity request. 8712 * IOW, placing the task there would make the CPU 8713 * overutilized. Take uclamp into account to see how 8714 * much capacity we can get out of the CPU; this is 8715 * aligned with sched_cpu_util(). 8716 */ 8717 if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) { 8718 /* 8719 * Open code uclamp_rq_util_with() except for 8720 * the clamp() part. I.e.: apply max aggregation 8721 * only. util_fits_cpu() logic requires to 8722 * operate on non clamped util but must use the 8723 * max-aggregated uclamp_{min, max}. 8724 */ 8725 rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN); 8726 rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX); 8727 8728 util_min = max(rq_util_min, p_util_min); 8729 util_max = max(rq_util_max, p_util_max); 8730 } 8731 8732 fits = util_fits_cpu(util, util_min, util_max, cpu); 8733 if (!fits) 8734 continue; 8735 8736 lsub_positive(&cpu_cap, util); 8737 8738 if (cpu == prev_cpu) { 8739 /* Always use prev_cpu as a candidate. */ 8740 prev_spare_cap = cpu_cap; 8741 prev_fits = fits; 8742 } else if ((fits > max_fits) || 8743 ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) { 8744 /* 8745 * Find the CPU with the maximum spare capacity 8746 * among the remaining CPUs in the performance 8747 * domain. 8748 */ 8749 max_spare_cap = cpu_cap; 8750 max_spare_cap_cpu = cpu; 8751 max_fits = fits; 8752 } 8753 } 8754 8755 if (max_spare_cap_cpu < 0 && prev_spare_cap < 0) 8756 continue; 8757 8758 eenv_pd_busy_time(&eenv, cpus, p); 8759 /* Compute the 'base' energy of the pd, without @p */ 8760 base_energy = compute_energy(&eenv, pd, cpus, p, -1); 8761 8762 /* Evaluate the energy impact of using prev_cpu. */ 8763 if (prev_spare_cap > -1) { 8764 prev_delta = compute_energy(&eenv, pd, cpus, p, 8765 prev_cpu); 8766 /* CPU utilization has changed */ 8767 if (prev_delta < base_energy) 8768 return target; 8769 prev_delta -= base_energy; 8770 prev_actual_cap = cpu_actual_cap; 8771 best_delta = min(best_delta, prev_delta); 8772 } 8773 8774 /* Evaluate the energy impact of using max_spare_cap_cpu. */ 8775 if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) { 8776 /* Current best energy cpu fits better */ 8777 if (max_fits < best_fits) 8778 continue; 8779 8780 /* 8781 * Both don't fit performance hint (i.e. uclamp_min) 8782 * but best energy cpu has better capacity. 8783 */ 8784 if ((max_fits < 0) && 8785 (cpu_actual_cap <= best_actual_cap)) 8786 continue; 8787 8788 cur_delta = compute_energy(&eenv, pd, cpus, p, 8789 max_spare_cap_cpu); 8790 /* CPU utilization has changed */ 8791 if (cur_delta < base_energy) 8792 return target; 8793 cur_delta -= base_energy; 8794 8795 /* 8796 * Both fit for the task but best energy cpu has lower 8797 * energy impact. 8798 */ 8799 if ((max_fits > 0) && (best_fits > 0) && 8800 (cur_delta >= best_delta)) 8801 continue; 8802 8803 best_delta = cur_delta; 8804 best_energy_cpu = max_spare_cap_cpu; 8805 best_fits = max_fits; 8806 best_actual_cap = cpu_actual_cap; 8807 } 8808 } 8809 8810 if ((best_fits > prev_fits) || 8811 ((best_fits > 0) && (best_delta < prev_delta)) || 8812 ((best_fits < 0) && (best_actual_cap > prev_actual_cap))) 8813 target = best_energy_cpu; 8814 8815 return target; 8816 } 8817 8818 /* 8819 * select_task_rq_fair: Select target runqueue for the waking task in domains 8820 * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE, 8821 * SD_BALANCE_FORK, or SD_BALANCE_EXEC. 8822 * 8823 * Balances load by selecting the idlest CPU in the idlest group, or under 8824 * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set. 8825 * 8826 * Returns the target CPU number. 8827 */ 8828 static int 8829 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags) 8830 { 8831 int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING); 8832 struct sched_domain *tmp, *sd = NULL; 8833 int cpu = smp_processor_id(); 8834 int new_cpu = prev_cpu; 8835 int want_affine = 0; 8836 /* SD_flags and WF_flags share the first nibble */ 8837 int sd_flag = wake_flags & 0xF; 8838 8839 /* 8840 * required for stable ->cpus_allowed 8841 */ 8842 lockdep_assert_held(&p->pi_lock); 8843 if (wake_flags & WF_TTWU) { 8844 record_wakee(p); 8845 8846 if ((wake_flags & WF_CURRENT_CPU) && 8847 cpumask_test_cpu(cpu, p->cpus_ptr)) 8848 return cpu; 8849 8850 if (!is_rd_overutilized(this_rq()->rd)) { 8851 new_cpu = find_energy_efficient_cpu(p, prev_cpu); 8852 if (new_cpu >= 0) 8853 return new_cpu; 8854 new_cpu = prev_cpu; 8855 } 8856 8857 want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr); 8858 } 8859 8860 for_each_domain(cpu, tmp) { 8861 /* 8862 * If both 'cpu' and 'prev_cpu' are part of this domain, 8863 * cpu is a valid SD_WAKE_AFFINE target. 8864 */ 8865 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) && 8866 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) { 8867 if (cpu != prev_cpu) 8868 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync); 8869 8870 sd = NULL; /* Prefer wake_affine over balance flags */ 8871 break; 8872 } 8873 8874 /* 8875 * Usually only true for WF_EXEC and WF_FORK, as sched_domains 8876 * usually do not have SD_BALANCE_WAKE set. That means wakeup 8877 * will usually go to the fast path. 8878 */ 8879 if (tmp->flags & sd_flag) 8880 sd = tmp; 8881 else if (!want_affine) 8882 break; 8883 } 8884 8885 /* Slow path */ 8886 if (unlikely(sd)) 8887 return sched_balance_find_dst_cpu(sd, p, cpu, prev_cpu, sd_flag); 8888 8889 /* Fast path */ 8890 if (wake_flags & WF_TTWU) 8891 return select_idle_sibling(p, prev_cpu, new_cpu); 8892 8893 return new_cpu; 8894 } 8895 8896 /* 8897 * Called immediately before a task is migrated to a new CPU; task_cpu(p) and 8898 * cfs_rq_of(p) references at time of call are still valid and identify the 8899 * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held. 8900 */ 8901 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu) 8902 { 8903 struct sched_entity *se = &p->se; 8904 8905 if (!task_on_rq_migrating(p)) { 8906 remove_entity_load_avg(se); 8907 8908 /* 8909 * Here, the task's PELT values have been updated according to 8910 * the current rq's clock. But if that clock hasn't been 8911 * updated in a while, a substantial idle time will be missed, 8912 * leading to an inflation after wake-up on the new rq. 8913 * 8914 * Estimate the missing time from the cfs_rq last_update_time 8915 * and update sched_avg to improve the PELT continuity after 8916 * migration. 8917 */ 8918 migrate_se_pelt_lag(se); 8919 } 8920 8921 /* Tell new CPU we are migrated */ 8922 se->avg.last_update_time = 0; 8923 8924 update_scan_period(p, new_cpu); 8925 } 8926 8927 static void task_dead_fair(struct task_struct *p) 8928 { 8929 struct sched_entity *se = &p->se; 8930 8931 if (se->sched_delayed) { 8932 struct rq_flags rf; 8933 struct rq *rq; 8934 8935 rq = task_rq_lock(p, &rf); 8936 if (se->sched_delayed) { 8937 update_rq_clock(rq); 8938 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED); 8939 } 8940 task_rq_unlock(rq, p, &rf); 8941 } 8942 8943 remove_entity_load_avg(se); 8944 } 8945 8946 /* 8947 * Set the max capacity the task is allowed to run at for misfit detection. 8948 */ 8949 static void set_task_max_allowed_capacity(struct task_struct *p) 8950 { 8951 struct asym_cap_data *entry; 8952 8953 if (!sched_asym_cpucap_active()) 8954 return; 8955 8956 rcu_read_lock(); 8957 list_for_each_entry_rcu(entry, &asym_cap_list, link) { 8958 cpumask_t *cpumask; 8959 8960 cpumask = cpu_capacity_span(entry); 8961 if (!cpumask_intersects(p->cpus_ptr, cpumask)) 8962 continue; 8963 8964 p->max_allowed_capacity = entry->capacity; 8965 break; 8966 } 8967 rcu_read_unlock(); 8968 } 8969 8970 static void set_cpus_allowed_fair(struct task_struct *p, struct affinity_context *ctx) 8971 { 8972 set_cpus_allowed_common(p, ctx); 8973 set_task_max_allowed_capacity(p); 8974 } 8975 8976 static void set_next_buddy(struct sched_entity *se) 8977 { 8978 for_each_sched_entity(se) { 8979 if (WARN_ON_ONCE(!se->on_rq)) 8980 return; 8981 if (se_is_idle(se)) 8982 return; 8983 cfs_rq_of(se)->next = se; 8984 } 8985 } 8986 8987 enum preempt_wakeup_action { 8988 PREEMPT_WAKEUP_NONE, /* No preemption. */ 8989 PREEMPT_WAKEUP_SHORT, /* Ignore slice protection. */ 8990 PREEMPT_WAKEUP_PICK, /* Let __pick_eevdf() decide. */ 8991 PREEMPT_WAKEUP_RESCHED, /* Force reschedule. */ 8992 }; 8993 8994 static inline bool 8995 set_preempt_buddy(struct cfs_rq *cfs_rq, int wake_flags, 8996 struct sched_entity *pse, struct sched_entity *se) 8997 { 8998 /* 8999 * Keep existing buddy if the deadline is sooner than pse. 9000 * The older buddy may be cache cold and completely unrelated 9001 * to the current wakeup but that is unpredictable where as 9002 * obeying the deadline is more in line with EEVDF objectives. 9003 */ 9004 if (cfs_rq->next && entity_before(cfs_rq->next, pse)) 9005 return false; 9006 9007 set_next_buddy(pse); 9008 return true; 9009 } 9010 9011 /* 9012 * WF_SYNC|WF_TTWU indicates the waker expects to sleep but it is not 9013 * strictly enforced because the hint is either misunderstood or 9014 * multiple tasks must be woken up. 9015 */ 9016 static inline enum preempt_wakeup_action 9017 preempt_sync(struct rq *rq, int wake_flags, 9018 struct sched_entity *pse, struct sched_entity *se) 9019 { 9020 u64 threshold, delta; 9021 9022 /* 9023 * WF_SYNC without WF_TTWU is not expected so warn if it happens even 9024 * though it is likely harmless. 9025 */ 9026 WARN_ON_ONCE(!(wake_flags & WF_TTWU)); 9027 9028 threshold = sysctl_sched_migration_cost; 9029 delta = rq_clock_task(rq) - se->exec_start; 9030 if ((s64)delta < 0) 9031 delta = 0; 9032 9033 /* 9034 * WF_RQ_SELECTED implies the tasks are stacking on a CPU when they 9035 * could run on other CPUs. Reduce the threshold before preemption is 9036 * allowed to an arbitrary lower value as it is more likely (but not 9037 * guaranteed) the waker requires the wakee to finish. 9038 */ 9039 if (wake_flags & WF_RQ_SELECTED) 9040 threshold >>= 2; 9041 9042 /* 9043 * As WF_SYNC is not strictly obeyed, allow some runtime for batch 9044 * wakeups to be issued. 9045 */ 9046 if (entity_before(pse, se) && delta >= threshold) 9047 return PREEMPT_WAKEUP_RESCHED; 9048 9049 return PREEMPT_WAKEUP_NONE; 9050 } 9051 9052 /* 9053 * Preempt the current task with a newly woken task if needed: 9054 */ 9055 static void wakeup_preempt_fair(struct rq *rq, struct task_struct *p, int wake_flags) 9056 { 9057 enum preempt_wakeup_action preempt_action = PREEMPT_WAKEUP_PICK; 9058 struct task_struct *donor = rq->donor; 9059 struct sched_entity *nse, *se = &donor->se, *pse = &p->se; 9060 struct cfs_rq *cfs_rq = task_cfs_rq(donor); 9061 int cse_is_idle, pse_is_idle; 9062 9063 /* 9064 * XXX Getting preempted by higher class, try and find idle CPU? 9065 */ 9066 if (p->sched_class != &fair_sched_class) 9067 return; 9068 9069 if (unlikely(se == pse)) 9070 return; 9071 9072 /* 9073 * This is possible from callers such as attach_tasks(), in which we 9074 * unconditionally wakeup_preempt() after an enqueue (which may have 9075 * lead to a throttle). This both saves work and prevents false 9076 * next-buddy nomination below. 9077 */ 9078 if (task_is_throttled(p)) 9079 return; 9080 9081 /* 9082 * We can come here with TIF_NEED_RESCHED already set from new task 9083 * wake up path. 9084 * 9085 * Note: this also catches the edge-case of curr being in a throttled 9086 * group (e.g. via set_curr_task), since update_curr() (in the 9087 * enqueue of curr) will have resulted in resched being set. This 9088 * prevents us from potentially nominating it as a false LAST_BUDDY 9089 * below. 9090 */ 9091 if (test_tsk_need_resched(rq->curr)) 9092 return; 9093 9094 if (!sched_feat(WAKEUP_PREEMPTION)) 9095 return; 9096 9097 find_matching_se(&se, &pse); 9098 WARN_ON_ONCE(!pse); 9099 9100 cse_is_idle = se_is_idle(se); 9101 pse_is_idle = se_is_idle(pse); 9102 9103 /* 9104 * Preempt an idle entity in favor of a non-idle entity (and don't preempt 9105 * in the inverse case). 9106 */ 9107 if (cse_is_idle && !pse_is_idle) { 9108 /* 9109 * When non-idle entity preempt an idle entity, 9110 * don't give idle entity slice protection. 9111 */ 9112 preempt_action = PREEMPT_WAKEUP_SHORT; 9113 goto preempt; 9114 } 9115 9116 if (cse_is_idle != pse_is_idle) 9117 return; 9118 9119 /* 9120 * BATCH and IDLE tasks do not preempt others. 9121 */ 9122 if (unlikely(!normal_policy(p->policy))) 9123 return; 9124 9125 cfs_rq = cfs_rq_of(se); 9126 update_curr(cfs_rq); 9127 /* 9128 * If @p has a shorter slice than current and @p is eligible, override 9129 * current's slice protection in order to allow preemption. 9130 */ 9131 if (sched_feat(PREEMPT_SHORT) && (pse->slice < se->slice)) { 9132 preempt_action = PREEMPT_WAKEUP_SHORT; 9133 goto pick; 9134 } 9135 9136 /* 9137 * Ignore wakee preemption on WF_FORK as it is less likely that 9138 * there is shared data as exec often follow fork. Do not 9139 * preempt for tasks that are sched_delayed as it would violate 9140 * EEVDF to forcibly queue an ineligible task. 9141 */ 9142 if ((wake_flags & WF_FORK) || pse->sched_delayed) 9143 return; 9144 9145 /* Prefer picking wakee soon if appropriate. */ 9146 if (sched_feat(NEXT_BUDDY) && 9147 set_preempt_buddy(cfs_rq, wake_flags, pse, se)) { 9148 9149 /* 9150 * Decide whether to obey WF_SYNC hint for a new buddy. Old 9151 * buddies are ignored as they may not be relevant to the 9152 * waker and less likely to be cache hot. 9153 */ 9154 if (wake_flags & WF_SYNC) 9155 preempt_action = preempt_sync(rq, wake_flags, pse, se); 9156 } 9157 9158 switch (preempt_action) { 9159 case PREEMPT_WAKEUP_NONE: 9160 return; 9161 case PREEMPT_WAKEUP_RESCHED: 9162 goto preempt; 9163 case PREEMPT_WAKEUP_SHORT: 9164 fallthrough; 9165 case PREEMPT_WAKEUP_PICK: 9166 break; 9167 } 9168 9169 pick: 9170 nse = pick_next_entity(rq, cfs_rq, preempt_action != PREEMPT_WAKEUP_SHORT); 9171 /* If @p has become the most eligible task, force preemption */ 9172 if (nse == pse) 9173 goto preempt; 9174 9175 /* 9176 * Because p is enqueued, nse being null can only mean that we 9177 * dequeued a delayed task. If there are still entities queued in 9178 * cfs, check if the next one will be p. 9179 */ 9180 if (!nse && cfs_rq->nr_queued) 9181 goto pick; 9182 9183 if (sched_feat(RUN_TO_PARITY)) 9184 update_protect_slice(cfs_rq, se); 9185 9186 return; 9187 9188 preempt: 9189 if (preempt_action == PREEMPT_WAKEUP_SHORT) { 9190 cancel_protect_slice(se); 9191 clear_buddies(cfs_rq, se); 9192 } 9193 9194 resched_curr_lazy(rq); 9195 } 9196 9197 static struct task_struct *pick_task_fair(struct rq *rq, struct rq_flags *rf) 9198 { 9199 struct sched_entity *se; 9200 struct cfs_rq *cfs_rq; 9201 struct task_struct *p; 9202 bool throttled; 9203 9204 again: 9205 cfs_rq = &rq->cfs; 9206 if (!cfs_rq->nr_queued) 9207 return NULL; 9208 9209 throttled = false; 9210 9211 do { 9212 /* Might not have done put_prev_entity() */ 9213 if (cfs_rq->curr && cfs_rq->curr->on_rq) 9214 update_curr(cfs_rq); 9215 9216 throttled |= check_cfs_rq_runtime(cfs_rq); 9217 9218 se = pick_next_entity(rq, cfs_rq, true); 9219 if (!se) 9220 goto again; 9221 cfs_rq = group_cfs_rq(se); 9222 } while (cfs_rq); 9223 9224 p = task_of(se); 9225 if (unlikely(throttled)) 9226 task_throttle_setup_work(p); 9227 return p; 9228 } 9229 9230 static void __set_next_task_fair(struct rq *rq, struct task_struct *p, bool first); 9231 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first); 9232 9233 struct task_struct * 9234 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf) 9235 __must_hold(__rq_lockp(rq)) 9236 { 9237 struct sched_entity *se; 9238 struct task_struct *p; 9239 int new_tasks; 9240 9241 again: 9242 p = pick_task_fair(rq, rf); 9243 if (!p) 9244 goto idle; 9245 se = &p->se; 9246 9247 #ifdef CONFIG_FAIR_GROUP_SCHED 9248 if (prev->sched_class != &fair_sched_class) 9249 goto simple; 9250 9251 __put_prev_set_next_dl_server(rq, prev, p); 9252 9253 /* 9254 * Because of the set_next_buddy() in dequeue_task_fair() it is rather 9255 * likely that a next task is from the same cgroup as the current. 9256 * 9257 * Therefore attempt to avoid putting and setting the entire cgroup 9258 * hierarchy, only change the part that actually changes. 9259 * 9260 * Since we haven't yet done put_prev_entity and if the selected task 9261 * is a different task than we started out with, try and touch the 9262 * least amount of cfs_rqs. 9263 */ 9264 if (prev != p) { 9265 struct sched_entity *pse = &prev->se; 9266 struct cfs_rq *cfs_rq; 9267 9268 while (!(cfs_rq = is_same_group(se, pse))) { 9269 int se_depth = se->depth; 9270 int pse_depth = pse->depth; 9271 9272 if (se_depth <= pse_depth) { 9273 put_prev_entity(cfs_rq_of(pse), pse); 9274 pse = parent_entity(pse); 9275 } 9276 if (se_depth >= pse_depth) { 9277 set_next_entity(cfs_rq_of(se), se, true); 9278 se = parent_entity(se); 9279 } 9280 } 9281 9282 put_prev_entity(cfs_rq, pse); 9283 set_next_entity(cfs_rq, se, true); 9284 9285 __set_next_task_fair(rq, p, true); 9286 } 9287 9288 return p; 9289 9290 simple: 9291 #endif /* CONFIG_FAIR_GROUP_SCHED */ 9292 put_prev_set_next_task(rq, prev, p); 9293 return p; 9294 9295 idle: 9296 if (rf) { 9297 new_tasks = sched_balance_newidle(rq, rf); 9298 9299 /* 9300 * Because sched_balance_newidle() releases (and re-acquires) 9301 * rq->lock, it is possible for any higher priority task to 9302 * appear. In that case we must re-start the pick_next_entity() 9303 * loop. 9304 */ 9305 if (new_tasks < 0) 9306 return RETRY_TASK; 9307 9308 if (new_tasks > 0) 9309 goto again; 9310 } 9311 9312 return NULL; 9313 } 9314 9315 static struct task_struct * 9316 fair_server_pick_task(struct sched_dl_entity *dl_se, struct rq_flags *rf) 9317 { 9318 return pick_task_fair(dl_se->rq, rf); 9319 } 9320 9321 void fair_server_init(struct rq *rq) 9322 { 9323 struct sched_dl_entity *dl_se = &rq->fair_server; 9324 9325 init_dl_entity(dl_se); 9326 9327 dl_server_init(dl_se, rq, fair_server_pick_task); 9328 } 9329 9330 /* 9331 * Account for a descheduled task: 9332 */ 9333 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev, struct task_struct *next) 9334 { 9335 struct sched_entity *se = &prev->se; 9336 struct cfs_rq *cfs_rq; 9337 9338 for_each_sched_entity(se) { 9339 cfs_rq = cfs_rq_of(se); 9340 put_prev_entity(cfs_rq, se); 9341 } 9342 } 9343 9344 /* 9345 * sched_yield() is very simple 9346 */ 9347 static void yield_task_fair(struct rq *rq) 9348 { 9349 struct task_struct *curr = rq->donor; 9350 struct cfs_rq *cfs_rq = task_cfs_rq(curr); 9351 struct sched_entity *se = &curr->se; 9352 9353 /* 9354 * Are we the only task in the tree? 9355 */ 9356 if (unlikely(rq->nr_running == 1)) 9357 return; 9358 9359 clear_buddies(cfs_rq, se); 9360 9361 update_rq_clock(rq); 9362 /* 9363 * Update run-time statistics of the 'current'. 9364 */ 9365 update_curr(cfs_rq); 9366 /* 9367 * Tell update_rq_clock() that we've just updated, 9368 * so we don't do microscopic update in schedule() 9369 * and double the fastpath cost. 9370 */ 9371 rq_clock_skip_update(rq); 9372 9373 /* 9374 * Forfeit the remaining vruntime, only if the entity is eligible. This 9375 * condition is necessary because in core scheduling we prefer to run 9376 * ineligible tasks rather than force idling. If this happens we may 9377 * end up in a loop where the core scheduler picks the yielding task, 9378 * which yields immediately again; without the condition the vruntime 9379 * ends up quickly running away. 9380 */ 9381 if (entity_eligible(cfs_rq, se)) { 9382 se->vruntime = se->deadline; 9383 update_deadline(cfs_rq, se); 9384 } 9385 } 9386 9387 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p) 9388 { 9389 struct sched_entity *se = &p->se; 9390 9391 /* !se->on_rq also covers throttled task */ 9392 if (!se->on_rq) 9393 return false; 9394 9395 /* Tell the scheduler that we'd really like se to run next. */ 9396 set_next_buddy(se); 9397 9398 yield_task_fair(rq); 9399 9400 return true; 9401 } 9402 9403 /************************************************** 9404 * Fair scheduling class load-balancing methods. 9405 * 9406 * BASICS 9407 * 9408 * The purpose of load-balancing is to achieve the same basic fairness the 9409 * per-CPU scheduler provides, namely provide a proportional amount of compute 9410 * time to each task. This is expressed in the following equation: 9411 * 9412 * W_i,n/P_i == W_j,n/P_j for all i,j (1) 9413 * 9414 * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight 9415 * W_i,0 is defined as: 9416 * 9417 * W_i,0 = \Sum_j w_i,j (2) 9418 * 9419 * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight 9420 * is derived from the nice value as per sched_prio_to_weight[]. 9421 * 9422 * The weight average is an exponential decay average of the instantaneous 9423 * weight: 9424 * 9425 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3) 9426 * 9427 * C_i is the compute capacity of CPU i, typically it is the 9428 * fraction of 'recent' time available for SCHED_OTHER task execution. But it 9429 * can also include other factors [XXX]. 9430 * 9431 * To achieve this balance we define a measure of imbalance which follows 9432 * directly from (1): 9433 * 9434 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4) 9435 * 9436 * We them move tasks around to minimize the imbalance. In the continuous 9437 * function space it is obvious this converges, in the discrete case we get 9438 * a few fun cases generally called infeasible weight scenarios. 9439 * 9440 * [XXX expand on: 9441 * - infeasible weights; 9442 * - local vs global optima in the discrete case. ] 9443 * 9444 * 9445 * SCHED DOMAINS 9446 * 9447 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2) 9448 * for all i,j solution, we create a tree of CPUs that follows the hardware 9449 * topology where each level pairs two lower groups (or better). This results 9450 * in O(log n) layers. Furthermore we reduce the number of CPUs going up the 9451 * tree to only the first of the previous level and we decrease the frequency 9452 * of load-balance at each level inversely proportional to the number of CPUs in 9453 * the groups. 9454 * 9455 * This yields: 9456 * 9457 * log_2 n 1 n 9458 * \Sum { --- * --- * 2^i } = O(n) (5) 9459 * i = 0 2^i 2^i 9460 * `- size of each group 9461 * | | `- number of CPUs doing load-balance 9462 * | `- freq 9463 * `- sum over all levels 9464 * 9465 * Coupled with a limit on how many tasks we can migrate every balance pass, 9466 * this makes (5) the runtime complexity of the balancer. 9467 * 9468 * An important property here is that each CPU is still (indirectly) connected 9469 * to every other CPU in at most O(log n) steps: 9470 * 9471 * The adjacency matrix of the resulting graph is given by: 9472 * 9473 * log_2 n 9474 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6) 9475 * k = 0 9476 * 9477 * And you'll find that: 9478 * 9479 * A^(log_2 n)_i,j != 0 for all i,j (7) 9480 * 9481 * Showing there's indeed a path between every CPU in at most O(log n) steps. 9482 * The task movement gives a factor of O(m), giving a convergence complexity 9483 * of: 9484 * 9485 * O(nm log n), n := nr_cpus, m := nr_tasks (8) 9486 * 9487 * 9488 * WORK CONSERVING 9489 * 9490 * In order to avoid CPUs going idle while there's still work to do, new idle 9491 * balancing is more aggressive and has the newly idle CPU iterate up the domain 9492 * tree itself instead of relying on other CPUs to bring it work. 9493 * 9494 * This adds some complexity to both (5) and (8) but it reduces the total idle 9495 * time. 9496 * 9497 * [XXX more?] 9498 * 9499 * 9500 * CGROUPS 9501 * 9502 * Cgroups make a horror show out of (2), instead of a simple sum we get: 9503 * 9504 * s_k,i 9505 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9) 9506 * S_k 9507 * 9508 * Where 9509 * 9510 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10) 9511 * 9512 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i. 9513 * 9514 * The big problem is S_k, its a global sum needed to compute a local (W_i) 9515 * property. 9516 * 9517 * [XXX write more on how we solve this.. _after_ merging pjt's patches that 9518 * rewrite all of this once again.] 9519 */ 9520 9521 static unsigned long __read_mostly max_load_balance_interval = HZ/10; 9522 9523 enum fbq_type { regular, remote, all }; 9524 9525 /* 9526 * 'group_type' describes the group of CPUs at the moment of load balancing. 9527 * 9528 * The enum is ordered by pulling priority, with the group with lowest priority 9529 * first so the group_type can simply be compared when selecting the busiest 9530 * group. See update_sd_pick_busiest(). 9531 */ 9532 enum group_type { 9533 /* The group has spare capacity that can be used to run more tasks. */ 9534 group_has_spare = 0, 9535 /* 9536 * The group is fully used and the tasks don't compete for more CPU 9537 * cycles. Nevertheless, some tasks might wait before running. 9538 */ 9539 group_fully_busy, 9540 /* 9541 * One task doesn't fit with CPU's capacity and must be migrated to a 9542 * more powerful CPU. 9543 */ 9544 group_misfit_task, 9545 /* 9546 * Balance SMT group that's fully busy. Can benefit from migration 9547 * a task on SMT with busy sibling to another CPU on idle core. 9548 */ 9549 group_smt_balance, 9550 /* 9551 * SD_ASYM_PACKING only: One local CPU with higher capacity is available, 9552 * and the task should be migrated to it instead of running on the 9553 * current CPU. 9554 */ 9555 group_asym_packing, 9556 /* 9557 * The tasks' affinity constraints previously prevented the scheduler 9558 * from balancing the load across the system. 9559 */ 9560 group_imbalanced, 9561 /* 9562 * The CPU is overloaded and can't provide expected CPU cycles to all 9563 * tasks. 9564 */ 9565 group_overloaded 9566 }; 9567 9568 enum migration_type { 9569 migrate_load = 0, 9570 migrate_util, 9571 migrate_task, 9572 migrate_misfit 9573 }; 9574 9575 #define LBF_ALL_PINNED 0x01 9576 #define LBF_NEED_BREAK 0x02 9577 #define LBF_DST_PINNED 0x04 9578 #define LBF_SOME_PINNED 0x08 9579 #define LBF_ACTIVE_LB 0x10 9580 9581 struct lb_env { 9582 struct sched_domain *sd; 9583 9584 struct rq *src_rq; 9585 int src_cpu; 9586 9587 int dst_cpu; 9588 struct rq *dst_rq; 9589 9590 struct cpumask *dst_grpmask; 9591 int new_dst_cpu; 9592 enum cpu_idle_type idle; 9593 long imbalance; 9594 /* The set of CPUs under consideration for load-balancing */ 9595 struct cpumask *cpus; 9596 9597 unsigned int flags; 9598 9599 unsigned int loop; 9600 unsigned int loop_break; 9601 unsigned int loop_max; 9602 9603 enum fbq_type fbq_type; 9604 enum migration_type migration_type; 9605 struct list_head tasks; 9606 }; 9607 9608 /* 9609 * Is this task likely cache-hot: 9610 */ 9611 static int task_hot(struct task_struct *p, struct lb_env *env) 9612 { 9613 s64 delta; 9614 9615 lockdep_assert_rq_held(env->src_rq); 9616 9617 if (p->sched_class != &fair_sched_class) 9618 return 0; 9619 9620 if (unlikely(task_has_idle_policy(p))) 9621 return 0; 9622 9623 /* SMT siblings share cache */ 9624 if (env->sd->flags & SD_SHARE_CPUCAPACITY) 9625 return 0; 9626 9627 /* 9628 * Buddy candidates are cache hot: 9629 */ 9630 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running && 9631 (&p->se == cfs_rq_of(&p->se)->next)) 9632 return 1; 9633 9634 if (sysctl_sched_migration_cost == -1) 9635 return 1; 9636 9637 /* 9638 * Don't migrate task if the task's cookie does not match 9639 * with the destination CPU's core cookie. 9640 */ 9641 if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p)) 9642 return 1; 9643 9644 if (sysctl_sched_migration_cost == 0) 9645 return 0; 9646 9647 delta = rq_clock_task(env->src_rq) - p->se.exec_start; 9648 9649 return delta < (s64)sysctl_sched_migration_cost; 9650 } 9651 9652 #ifdef CONFIG_NUMA_BALANCING 9653 /* 9654 * Returns a positive value, if task migration degrades locality. 9655 * Returns 0, if task migration is not affected by locality. 9656 * Returns a negative value, if task migration improves locality i.e migration preferred. 9657 */ 9658 static long migrate_degrades_locality(struct task_struct *p, struct lb_env *env) 9659 { 9660 struct numa_group *numa_group = rcu_dereference_all(p->numa_group); 9661 unsigned long src_weight, dst_weight; 9662 int src_nid, dst_nid, dist; 9663 9664 if (!static_branch_likely(&sched_numa_balancing)) 9665 return 0; 9666 9667 if (!p->numa_faults || !(env->sd->flags & SD_NUMA)) 9668 return 0; 9669 9670 src_nid = cpu_to_node(env->src_cpu); 9671 dst_nid = cpu_to_node(env->dst_cpu); 9672 9673 if (src_nid == dst_nid) 9674 return 0; 9675 9676 /* Migrating away from the preferred node is always bad. */ 9677 if (src_nid == p->numa_preferred_nid) { 9678 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running) 9679 return 1; 9680 else 9681 return 0; 9682 } 9683 9684 /* Encourage migration to the preferred node. */ 9685 if (dst_nid == p->numa_preferred_nid) 9686 return -1; 9687 9688 /* Leaving a core idle is often worse than degrading locality. */ 9689 if (env->idle == CPU_IDLE) 9690 return 0; 9691 9692 dist = node_distance(src_nid, dst_nid); 9693 if (numa_group) { 9694 src_weight = group_weight(p, src_nid, dist); 9695 dst_weight = group_weight(p, dst_nid, dist); 9696 } else { 9697 src_weight = task_weight(p, src_nid, dist); 9698 dst_weight = task_weight(p, dst_nid, dist); 9699 } 9700 9701 return src_weight - dst_weight; 9702 } 9703 9704 #else /* !CONFIG_NUMA_BALANCING: */ 9705 static inline long migrate_degrades_locality(struct task_struct *p, 9706 struct lb_env *env) 9707 { 9708 return 0; 9709 } 9710 #endif /* !CONFIG_NUMA_BALANCING */ 9711 9712 /* 9713 * Check whether the task is ineligible on the destination cpu 9714 * 9715 * When the PLACE_LAG scheduling feature is enabled and 9716 * dst_cfs_rq->nr_queued is greater than 1, if the task 9717 * is ineligible, it will also be ineligible when 9718 * it is migrated to the destination cpu. 9719 */ 9720 static inline int task_is_ineligible_on_dst_cpu(struct task_struct *p, int dest_cpu) 9721 { 9722 struct cfs_rq *dst_cfs_rq; 9723 9724 #ifdef CONFIG_FAIR_GROUP_SCHED 9725 dst_cfs_rq = task_group(p)->cfs_rq[dest_cpu]; 9726 #else 9727 dst_cfs_rq = &cpu_rq(dest_cpu)->cfs; 9728 #endif 9729 if (sched_feat(PLACE_LAG) && dst_cfs_rq->nr_queued && 9730 !entity_eligible(task_cfs_rq(p), &p->se)) 9731 return 1; 9732 9733 return 0; 9734 } 9735 9736 /* 9737 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu? 9738 */ 9739 static 9740 int can_migrate_task(struct task_struct *p, struct lb_env *env) 9741 { 9742 long degrades, hot; 9743 9744 lockdep_assert_rq_held(env->src_rq); 9745 if (p->sched_task_hot) 9746 p->sched_task_hot = 0; 9747 9748 /* 9749 * We do not migrate tasks that are: 9750 * 1) delayed dequeued unless we migrate load, or 9751 * 2) target cfs_rq is in throttled hierarchy, or 9752 * 3) cannot be migrated to this CPU due to cpus_ptr, or 9753 * 4) running (obviously), or 9754 * 5) are cache-hot on their current CPU, or 9755 * 6) are blocked on mutexes (if SCHED_PROXY_EXEC is enabled) 9756 */ 9757 if ((p->se.sched_delayed) && (env->migration_type != migrate_load)) 9758 return 0; 9759 9760 if (lb_throttled_hierarchy(p, env->dst_cpu)) 9761 return 0; 9762 9763 /* 9764 * We want to prioritize the migration of eligible tasks. 9765 * For ineligible tasks we soft-limit them and only allow 9766 * them to migrate when nr_balance_failed is non-zero to 9767 * avoid load-balancing trying very hard to balance the load. 9768 */ 9769 if (!env->sd->nr_balance_failed && 9770 task_is_ineligible_on_dst_cpu(p, env->dst_cpu)) 9771 return 0; 9772 9773 /* Disregard percpu kthreads; they are where they need to be. */ 9774 if (kthread_is_per_cpu(p)) 9775 return 0; 9776 9777 if (task_is_blocked(p)) 9778 return 0; 9779 9780 if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) { 9781 int cpu; 9782 9783 schedstat_inc(p->stats.nr_failed_migrations_affine); 9784 9785 env->flags |= LBF_SOME_PINNED; 9786 9787 /* 9788 * Remember if this task can be migrated to any other CPU in 9789 * our sched_group. We may want to revisit it if we couldn't 9790 * meet load balance goals by pulling other tasks on src_cpu. 9791 * 9792 * Avoid computing new_dst_cpu 9793 * - for NEWLY_IDLE 9794 * - if we have already computed one in current iteration 9795 * - if it's an active balance 9796 */ 9797 if (env->idle == CPU_NEWLY_IDLE || 9798 env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB)) 9799 return 0; 9800 9801 /* Prevent to re-select dst_cpu via env's CPUs: */ 9802 cpu = cpumask_first_and_and(env->dst_grpmask, env->cpus, p->cpus_ptr); 9803 9804 if (cpu < nr_cpu_ids) { 9805 env->flags |= LBF_DST_PINNED; 9806 env->new_dst_cpu = cpu; 9807 } 9808 9809 return 0; 9810 } 9811 9812 /* Record that we found at least one task that could run on dst_cpu */ 9813 env->flags &= ~LBF_ALL_PINNED; 9814 9815 if (task_on_cpu(env->src_rq, p) || 9816 task_current_donor(env->src_rq, p)) { 9817 schedstat_inc(p->stats.nr_failed_migrations_running); 9818 return 0; 9819 } 9820 9821 /* 9822 * Aggressive migration if: 9823 * 1) active balance 9824 * 2) destination numa is preferred 9825 * 3) task is cache cold, or 9826 * 4) too many balance attempts have failed. 9827 */ 9828 if (env->flags & LBF_ACTIVE_LB) 9829 return 1; 9830 9831 degrades = migrate_degrades_locality(p, env); 9832 if (!degrades) 9833 hot = task_hot(p, env); 9834 else 9835 hot = degrades > 0; 9836 9837 if (!hot || env->sd->nr_balance_failed > env->sd->cache_nice_tries) { 9838 if (hot) 9839 p->sched_task_hot = 1; 9840 return 1; 9841 } 9842 9843 schedstat_inc(p->stats.nr_failed_migrations_hot); 9844 return 0; 9845 } 9846 9847 /* 9848 * detach_task() -- detach the task for the migration specified in env 9849 */ 9850 static void detach_task(struct task_struct *p, struct lb_env *env) 9851 { 9852 lockdep_assert_rq_held(env->src_rq); 9853 9854 if (p->sched_task_hot) { 9855 p->sched_task_hot = 0; 9856 schedstat_inc(env->sd->lb_hot_gained[env->idle]); 9857 schedstat_inc(p->stats.nr_forced_migrations); 9858 } 9859 9860 WARN_ON(task_current(env->src_rq, p)); 9861 WARN_ON(task_current_donor(env->src_rq, p)); 9862 9863 deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK); 9864 set_task_cpu(p, env->dst_cpu); 9865 } 9866 9867 /* 9868 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as 9869 * part of active balancing operations within "domain". 9870 * 9871 * Returns a task if successful and NULL otherwise. 9872 */ 9873 static struct task_struct *detach_one_task(struct lb_env *env) 9874 { 9875 struct task_struct *p; 9876 9877 lockdep_assert_rq_held(env->src_rq); 9878 9879 list_for_each_entry_reverse(p, 9880 &env->src_rq->cfs_tasks, se.group_node) { 9881 if (!can_migrate_task(p, env)) 9882 continue; 9883 9884 detach_task(p, env); 9885 9886 /* 9887 * Right now, this is only the second place where 9888 * lb_gained[env->idle] is updated (other is detach_tasks) 9889 * so we can safely collect stats here rather than 9890 * inside detach_tasks(). 9891 */ 9892 schedstat_inc(env->sd->lb_gained[env->idle]); 9893 return p; 9894 } 9895 return NULL; 9896 } 9897 9898 /* 9899 * detach_tasks() -- tries to detach up to imbalance load/util/tasks from 9900 * busiest_rq, as part of a balancing operation within domain "sd". 9901 * 9902 * Returns number of detached tasks if successful and 0 otherwise. 9903 */ 9904 static int detach_tasks(struct lb_env *env) 9905 { 9906 struct list_head *tasks = &env->src_rq->cfs_tasks; 9907 unsigned long util, load; 9908 struct task_struct *p; 9909 int detached = 0; 9910 9911 lockdep_assert_rq_held(env->src_rq); 9912 9913 /* 9914 * Source run queue has been emptied by another CPU, clear 9915 * LBF_ALL_PINNED flag as we will not test any task. 9916 */ 9917 if (env->src_rq->nr_running <= 1) { 9918 env->flags &= ~LBF_ALL_PINNED; 9919 return 0; 9920 } 9921 9922 if (env->imbalance <= 0) 9923 return 0; 9924 9925 while (!list_empty(tasks)) { 9926 /* 9927 * We don't want to steal all, otherwise we may be treated likewise, 9928 * which could at worst lead to a livelock crash. 9929 */ 9930 if (env->idle && env->src_rq->nr_running <= 1) 9931 break; 9932 9933 env->loop++; 9934 /* We've more or less seen every task there is, call it quits */ 9935 if (env->loop > env->loop_max) 9936 break; 9937 9938 /* take a breather every nr_migrate tasks */ 9939 if (env->loop > env->loop_break) { 9940 env->loop_break += SCHED_NR_MIGRATE_BREAK; 9941 env->flags |= LBF_NEED_BREAK; 9942 break; 9943 } 9944 9945 p = list_last_entry(tasks, struct task_struct, se.group_node); 9946 9947 if (!can_migrate_task(p, env)) 9948 goto next; 9949 9950 switch (env->migration_type) { 9951 case migrate_load: 9952 /* 9953 * Depending of the number of CPUs and tasks and the 9954 * cgroup hierarchy, task_h_load() can return a null 9955 * value. Make sure that env->imbalance decreases 9956 * otherwise detach_tasks() will stop only after 9957 * detaching up to loop_max tasks. 9958 */ 9959 load = max_t(unsigned long, task_h_load(p), 1); 9960 9961 if (sched_feat(LB_MIN) && 9962 load < 16 && !env->sd->nr_balance_failed) 9963 goto next; 9964 9965 /* 9966 * Make sure that we don't migrate too much load. 9967 * Nevertheless, let relax the constraint if 9968 * scheduler fails to find a good waiting task to 9969 * migrate. 9970 */ 9971 if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance) 9972 goto next; 9973 9974 env->imbalance -= load; 9975 break; 9976 9977 case migrate_util: 9978 util = task_util_est(p); 9979 9980 if (shr_bound(util, env->sd->nr_balance_failed) > env->imbalance) 9981 goto next; 9982 9983 env->imbalance -= util; 9984 break; 9985 9986 case migrate_task: 9987 env->imbalance--; 9988 break; 9989 9990 case migrate_misfit: 9991 /* This is not a misfit task */ 9992 if (task_fits_cpu(p, env->src_cpu)) 9993 goto next; 9994 9995 env->imbalance = 0; 9996 break; 9997 } 9998 9999 detach_task(p, env); 10000 list_add(&p->se.group_node, &env->tasks); 10001 10002 detached++; 10003 10004 #ifdef CONFIG_PREEMPTION 10005 /* 10006 * NEWIDLE balancing is a source of latency, so preemptible 10007 * kernels will stop after the first task is detached to minimize 10008 * the critical section. 10009 */ 10010 if (env->idle == CPU_NEWLY_IDLE) 10011 break; 10012 #endif 10013 10014 /* 10015 * We only want to steal up to the prescribed amount of 10016 * load/util/tasks. 10017 */ 10018 if (env->imbalance <= 0) 10019 break; 10020 10021 continue; 10022 next: 10023 if (p->sched_task_hot) 10024 schedstat_inc(p->stats.nr_failed_migrations_hot); 10025 10026 list_move(&p->se.group_node, tasks); 10027 } 10028 10029 /* 10030 * Right now, this is one of only two places we collect this stat 10031 * so we can safely collect detach_one_task() stats here rather 10032 * than inside detach_one_task(). 10033 */ 10034 schedstat_add(env->sd->lb_gained[env->idle], detached); 10035 10036 return detached; 10037 } 10038 10039 /* 10040 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their 10041 * new rq. 10042 */ 10043 static void attach_tasks(struct lb_env *env) 10044 { 10045 struct list_head *tasks = &env->tasks; 10046 struct task_struct *p; 10047 struct rq_flags rf; 10048 10049 rq_lock(env->dst_rq, &rf); 10050 update_rq_clock(env->dst_rq); 10051 10052 while (!list_empty(tasks)) { 10053 p = list_first_entry(tasks, struct task_struct, se.group_node); 10054 list_del_init(&p->se.group_node); 10055 10056 attach_task(env->dst_rq, p); 10057 } 10058 10059 rq_unlock(env->dst_rq, &rf); 10060 } 10061 10062 #ifdef CONFIG_NO_HZ_COMMON 10063 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq) 10064 { 10065 if (cfs_rq->avg.load_avg) 10066 return true; 10067 10068 if (cfs_rq->avg.util_avg) 10069 return true; 10070 10071 return false; 10072 } 10073 10074 static inline bool others_have_blocked(struct rq *rq) 10075 { 10076 if (cpu_util_rt(rq)) 10077 return true; 10078 10079 if (cpu_util_dl(rq)) 10080 return true; 10081 10082 if (hw_load_avg(rq)) 10083 return true; 10084 10085 if (cpu_util_irq(rq)) 10086 return true; 10087 10088 return false; 10089 } 10090 10091 static inline void update_blocked_load_tick(struct rq *rq) 10092 { 10093 WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies); 10094 } 10095 10096 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load) 10097 { 10098 if (!has_blocked_load) 10099 rq->has_blocked_load = 0; 10100 } 10101 #else /* !CONFIG_NO_HZ_COMMON: */ 10102 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq) { return false; } 10103 static inline bool others_have_blocked(struct rq *rq) { return false; } 10104 static inline void update_blocked_load_tick(struct rq *rq) {} 10105 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load) {} 10106 #endif /* !CONFIG_NO_HZ_COMMON */ 10107 10108 static bool __update_blocked_others(struct rq *rq, bool *done) 10109 { 10110 bool updated; 10111 10112 /* 10113 * update_load_avg() can call cpufreq_update_util(). Make sure that RT, 10114 * DL and IRQ signals have been updated before updating CFS. 10115 */ 10116 updated = update_other_load_avgs(rq); 10117 10118 if (others_have_blocked(rq)) 10119 *done = false; 10120 10121 return updated; 10122 } 10123 10124 #ifdef CONFIG_FAIR_GROUP_SCHED 10125 10126 static bool __update_blocked_fair(struct rq *rq, bool *done) 10127 { 10128 struct cfs_rq *cfs_rq, *pos; 10129 bool decayed = false; 10130 int cpu = cpu_of(rq); 10131 10132 /* 10133 * Iterates the task_group tree in a bottom up fashion, see 10134 * list_add_leaf_cfs_rq() for details. 10135 */ 10136 for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) { 10137 struct sched_entity *se; 10138 10139 if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) { 10140 update_tg_load_avg(cfs_rq); 10141 10142 if (cfs_rq->nr_queued == 0) 10143 update_idle_cfs_rq_clock_pelt(cfs_rq); 10144 10145 if (cfs_rq == &rq->cfs) 10146 decayed = true; 10147 } 10148 10149 /* Propagate pending load changes to the parent, if any: */ 10150 se = cfs_rq->tg->se[cpu]; 10151 if (se && !skip_blocked_update(se)) 10152 update_load_avg(cfs_rq_of(se), se, UPDATE_TG); 10153 10154 /* 10155 * There can be a lot of idle CPU cgroups. Don't let fully 10156 * decayed cfs_rqs linger on the list. 10157 */ 10158 if (cfs_rq_is_decayed(cfs_rq)) 10159 list_del_leaf_cfs_rq(cfs_rq); 10160 10161 /* Don't need periodic decay once load/util_avg are null */ 10162 if (cfs_rq_has_blocked_load(cfs_rq)) 10163 *done = false; 10164 } 10165 10166 return decayed; 10167 } 10168 10169 /* 10170 * Compute the hierarchical load factor for cfs_rq and all its ascendants. 10171 * This needs to be done in a top-down fashion because the load of a child 10172 * group is a fraction of its parents load. 10173 */ 10174 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq) 10175 { 10176 struct rq *rq = rq_of(cfs_rq); 10177 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)]; 10178 unsigned long now = jiffies; 10179 unsigned long load; 10180 10181 if (cfs_rq->last_h_load_update == now) 10182 return; 10183 10184 WRITE_ONCE(cfs_rq->h_load_next, NULL); 10185 for_each_sched_entity(se) { 10186 cfs_rq = cfs_rq_of(se); 10187 WRITE_ONCE(cfs_rq->h_load_next, se); 10188 if (cfs_rq->last_h_load_update == now) 10189 break; 10190 } 10191 10192 if (!se) { 10193 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq); 10194 cfs_rq->last_h_load_update = now; 10195 } 10196 10197 while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) { 10198 load = cfs_rq->h_load; 10199 load = div64_ul(load * se->avg.load_avg, 10200 cfs_rq_load_avg(cfs_rq) + 1); 10201 cfs_rq = group_cfs_rq(se); 10202 cfs_rq->h_load = load; 10203 cfs_rq->last_h_load_update = now; 10204 } 10205 } 10206 10207 static unsigned long task_h_load(struct task_struct *p) 10208 { 10209 struct cfs_rq *cfs_rq = task_cfs_rq(p); 10210 10211 update_cfs_rq_h_load(cfs_rq); 10212 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load, 10213 cfs_rq_load_avg(cfs_rq) + 1); 10214 } 10215 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 10216 static bool __update_blocked_fair(struct rq *rq, bool *done) 10217 { 10218 struct cfs_rq *cfs_rq = &rq->cfs; 10219 bool decayed; 10220 10221 decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq); 10222 if (cfs_rq_has_blocked_load(cfs_rq)) 10223 *done = false; 10224 10225 return decayed; 10226 } 10227 10228 static unsigned long task_h_load(struct task_struct *p) 10229 { 10230 return p->se.avg.load_avg; 10231 } 10232 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 10233 10234 static void __sched_balance_update_blocked_averages(struct rq *rq) 10235 { 10236 bool decayed = false, done = true; 10237 10238 update_blocked_load_tick(rq); 10239 10240 decayed |= __update_blocked_others(rq, &done); 10241 decayed |= __update_blocked_fair(rq, &done); 10242 10243 update_has_blocked_load_status(rq, !done); 10244 if (decayed) 10245 cpufreq_update_util(rq, 0); 10246 } 10247 10248 static void sched_balance_update_blocked_averages(int cpu) 10249 { 10250 struct rq *rq = cpu_rq(cpu); 10251 10252 guard(rq_lock_irqsave)(rq); 10253 update_rq_clock(rq); 10254 __sched_balance_update_blocked_averages(rq); 10255 } 10256 10257 /********** Helpers for sched_balance_find_src_group ************************/ 10258 10259 /* 10260 * sg_lb_stats - stats of a sched_group required for load-balancing: 10261 */ 10262 struct sg_lb_stats { 10263 unsigned long avg_load; /* Avg load over the CPUs of the group */ 10264 unsigned long group_load; /* Total load over the CPUs of the group */ 10265 unsigned long group_capacity; /* Capacity over the CPUs of the group */ 10266 unsigned long group_util; /* Total utilization over the CPUs of the group */ 10267 unsigned long group_runnable; /* Total runnable time over the CPUs of the group */ 10268 unsigned int sum_nr_running; /* Nr of all tasks running in the group */ 10269 unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */ 10270 unsigned int idle_cpus; /* Nr of idle CPUs in the group */ 10271 unsigned int group_weight; 10272 enum group_type group_type; 10273 unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */ 10274 unsigned int group_smt_balance; /* Task on busy SMT be moved */ 10275 unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */ 10276 unsigned int group_overutilized; /* At least one CPU is overutilized in the group */ 10277 #ifdef CONFIG_NUMA_BALANCING 10278 unsigned int nr_numa_running; 10279 unsigned int nr_preferred_running; 10280 #endif 10281 }; 10282 10283 /* 10284 * sd_lb_stats - stats of a sched_domain required for load-balancing: 10285 */ 10286 struct sd_lb_stats { 10287 struct sched_group *busiest; /* Busiest group in this sd */ 10288 struct sched_group *local; /* Local group in this sd */ 10289 unsigned long total_load; /* Total load of all groups in sd */ 10290 unsigned long total_capacity; /* Total capacity of all groups in sd */ 10291 unsigned long avg_load; /* Average load across all groups in sd */ 10292 unsigned int prefer_sibling; /* Tasks should go to sibling first */ 10293 10294 struct sg_lb_stats busiest_stat; /* Statistics of the busiest group */ 10295 struct sg_lb_stats local_stat; /* Statistics of the local group */ 10296 }; 10297 10298 static inline void init_sd_lb_stats(struct sd_lb_stats *sds) 10299 { 10300 /* 10301 * Skimp on the clearing to avoid duplicate work. We can avoid clearing 10302 * local_stat because update_sg_lb_stats() does a full clear/assignment. 10303 * We must however set busiest_stat::group_type and 10304 * busiest_stat::idle_cpus to the worst busiest group because 10305 * update_sd_pick_busiest() reads these before assignment. 10306 */ 10307 *sds = (struct sd_lb_stats){ 10308 .busiest = NULL, 10309 .local = NULL, 10310 .total_load = 0UL, 10311 .total_capacity = 0UL, 10312 .busiest_stat = { 10313 .idle_cpus = UINT_MAX, 10314 .group_type = group_has_spare, 10315 }, 10316 }; 10317 } 10318 10319 static unsigned long scale_rt_capacity(int cpu) 10320 { 10321 unsigned long max = get_actual_cpu_capacity(cpu); 10322 struct rq *rq = cpu_rq(cpu); 10323 unsigned long used, free; 10324 unsigned long irq; 10325 10326 irq = cpu_util_irq(rq); 10327 10328 if (unlikely(irq >= max)) 10329 return 1; 10330 10331 /* 10332 * avg_rt.util_avg and avg_dl.util_avg track binary signals 10333 * (running and not running) with weights 0 and 1024 respectively. 10334 */ 10335 used = cpu_util_rt(rq); 10336 used += cpu_util_dl(rq); 10337 10338 if (unlikely(used >= max)) 10339 return 1; 10340 10341 free = max - used; 10342 10343 return scale_irq_capacity(free, irq, max); 10344 } 10345 10346 static void update_cpu_capacity(struct sched_domain *sd, int cpu) 10347 { 10348 unsigned long capacity = scale_rt_capacity(cpu); 10349 struct sched_group *sdg = sd->groups; 10350 10351 if (!capacity) 10352 capacity = 1; 10353 10354 cpu_rq(cpu)->cpu_capacity = capacity; 10355 trace_sched_cpu_capacity_tp(cpu_rq(cpu)); 10356 10357 sdg->sgc->capacity = capacity; 10358 sdg->sgc->min_capacity = capacity; 10359 sdg->sgc->max_capacity = capacity; 10360 } 10361 10362 void update_group_capacity(struct sched_domain *sd, int cpu) 10363 { 10364 struct sched_domain *child = sd->child; 10365 struct sched_group *group, *sdg = sd->groups; 10366 unsigned long capacity, min_capacity, max_capacity; 10367 unsigned long interval; 10368 10369 interval = msecs_to_jiffies(sd->balance_interval); 10370 interval = clamp(interval, 1UL, max_load_balance_interval); 10371 sdg->sgc->next_update = jiffies + interval; 10372 10373 if (!child) { 10374 update_cpu_capacity(sd, cpu); 10375 return; 10376 } 10377 10378 capacity = 0; 10379 min_capacity = ULONG_MAX; 10380 max_capacity = 0; 10381 10382 if (child->flags & SD_NUMA) { 10383 /* 10384 * SD_NUMA domains cannot assume that child groups 10385 * span the current group. 10386 */ 10387 10388 for_each_cpu(cpu, sched_group_span(sdg)) { 10389 unsigned long cpu_cap = capacity_of(cpu); 10390 10391 capacity += cpu_cap; 10392 min_capacity = min(cpu_cap, min_capacity); 10393 max_capacity = max(cpu_cap, max_capacity); 10394 } 10395 } else { 10396 /* 10397 * !SD_NUMA domains can assume that child groups 10398 * span the current group. 10399 */ 10400 10401 group = child->groups; 10402 do { 10403 struct sched_group_capacity *sgc = group->sgc; 10404 10405 capacity += sgc->capacity; 10406 min_capacity = min(sgc->min_capacity, min_capacity); 10407 max_capacity = max(sgc->max_capacity, max_capacity); 10408 group = group->next; 10409 } while (group != child->groups); 10410 } 10411 10412 sdg->sgc->capacity = capacity; 10413 sdg->sgc->min_capacity = min_capacity; 10414 sdg->sgc->max_capacity = max_capacity; 10415 } 10416 10417 /* 10418 * Check whether the capacity of the rq has been noticeably reduced by side 10419 * activity. The imbalance_pct is used for the threshold. 10420 * Return true is the capacity is reduced 10421 */ 10422 static inline int 10423 check_cpu_capacity(struct rq *rq, struct sched_domain *sd) 10424 { 10425 return ((rq->cpu_capacity * sd->imbalance_pct) < 10426 (arch_scale_cpu_capacity(cpu_of(rq)) * 100)); 10427 } 10428 10429 /* Check if the rq has a misfit task */ 10430 static inline bool check_misfit_status(struct rq *rq) 10431 { 10432 return rq->misfit_task_load; 10433 } 10434 10435 /* 10436 * Group imbalance indicates (and tries to solve) the problem where balancing 10437 * groups is inadequate due to ->cpus_ptr constraints. 10438 * 10439 * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a 10440 * cpumask covering 1 CPU of the first group and 3 CPUs of the second group. 10441 * Something like: 10442 * 10443 * { 0 1 2 3 } { 4 5 6 7 } 10444 * * * * * 10445 * 10446 * If we were to balance group-wise we'd place two tasks in the first group and 10447 * two tasks in the second group. Clearly this is undesired as it will overload 10448 * cpu 3 and leave one of the CPUs in the second group unused. 10449 * 10450 * The current solution to this issue is detecting the skew in the first group 10451 * by noticing the lower domain failed to reach balance and had difficulty 10452 * moving tasks due to affinity constraints. 10453 * 10454 * When this is so detected; this group becomes a candidate for busiest; see 10455 * update_sd_pick_busiest(). And calculate_imbalance() and 10456 * sched_balance_find_src_group() avoid some of the usual balance conditions to allow it 10457 * to create an effective group imbalance. 10458 * 10459 * This is a somewhat tricky proposition since the next run might not find the 10460 * group imbalance and decide the groups need to be balanced again. A most 10461 * subtle and fragile situation. 10462 */ 10463 10464 static inline int sg_imbalanced(struct sched_group *group) 10465 { 10466 return group->sgc->imbalance; 10467 } 10468 10469 /* 10470 * group_has_capacity returns true if the group has spare capacity that could 10471 * be used by some tasks. 10472 * We consider that a group has spare capacity if the number of task is 10473 * smaller than the number of CPUs or if the utilization is lower than the 10474 * available capacity for CFS tasks. 10475 * For the latter, we use a threshold to stabilize the state, to take into 10476 * account the variance of the tasks' load and to return true if the available 10477 * capacity in meaningful for the load balancer. 10478 * As an example, an available capacity of 1% can appear but it doesn't make 10479 * any benefit for the load balance. 10480 */ 10481 static inline bool 10482 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs) 10483 { 10484 if (sgs->sum_nr_running < sgs->group_weight) 10485 return true; 10486 10487 if ((sgs->group_capacity * imbalance_pct) < 10488 (sgs->group_runnable * 100)) 10489 return false; 10490 10491 if ((sgs->group_capacity * 100) > 10492 (sgs->group_util * imbalance_pct)) 10493 return true; 10494 10495 return false; 10496 } 10497 10498 /* 10499 * group_is_overloaded returns true if the group has more tasks than it can 10500 * handle. 10501 * group_is_overloaded is not equals to !group_has_capacity because a group 10502 * with the exact right number of tasks, has no more spare capacity but is not 10503 * overloaded so both group_has_capacity and group_is_overloaded return 10504 * false. 10505 */ 10506 static inline bool 10507 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs) 10508 { 10509 /* 10510 * With EAS and uclamp, 1 CPU in the group must be overutilized to 10511 * consider the group overloaded. 10512 */ 10513 if (sched_energy_enabled() && !sgs->group_overutilized) 10514 return false; 10515 10516 if (sgs->sum_nr_running <= sgs->group_weight) 10517 return false; 10518 10519 if ((sgs->group_capacity * 100) < 10520 (sgs->group_util * imbalance_pct)) 10521 return true; 10522 10523 if ((sgs->group_capacity * imbalance_pct) < 10524 (sgs->group_runnable * 100)) 10525 return true; 10526 10527 return false; 10528 } 10529 10530 static inline enum 10531 group_type group_classify(unsigned int imbalance_pct, 10532 struct sched_group *group, 10533 struct sg_lb_stats *sgs) 10534 { 10535 if (group_is_overloaded(imbalance_pct, sgs)) 10536 return group_overloaded; 10537 10538 if (sg_imbalanced(group)) 10539 return group_imbalanced; 10540 10541 if (sgs->group_asym_packing) 10542 return group_asym_packing; 10543 10544 if (sgs->group_smt_balance) 10545 return group_smt_balance; 10546 10547 if (sgs->group_misfit_task_load) 10548 return group_misfit_task; 10549 10550 if (!group_has_capacity(imbalance_pct, sgs)) 10551 return group_fully_busy; 10552 10553 return group_has_spare; 10554 } 10555 10556 /** 10557 * sched_use_asym_prio - Check whether asym_packing priority must be used 10558 * @sd: The scheduling domain of the load balancing 10559 * @cpu: A CPU 10560 * 10561 * Always use CPU priority when balancing load between SMT siblings. When 10562 * balancing load between cores, it is not sufficient that @cpu is idle. Only 10563 * use CPU priority if the whole core is idle. 10564 * 10565 * Returns: True if the priority of @cpu must be followed. False otherwise. 10566 */ 10567 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu) 10568 { 10569 if (!(sd->flags & SD_ASYM_PACKING)) 10570 return false; 10571 10572 if (!sched_smt_active()) 10573 return true; 10574 10575 return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu); 10576 } 10577 10578 static inline bool sched_asym(struct sched_domain *sd, int dst_cpu, int src_cpu) 10579 { 10580 /* 10581 * First check if @dst_cpu can do asym_packing load balance. Only do it 10582 * if it has higher priority than @src_cpu. 10583 */ 10584 return sched_use_asym_prio(sd, dst_cpu) && 10585 sched_asym_prefer(dst_cpu, src_cpu); 10586 } 10587 10588 /** 10589 * sched_group_asym - Check if the destination CPU can do asym_packing balance 10590 * @env: The load balancing environment 10591 * @sgs: Load-balancing statistics of the candidate busiest group 10592 * @group: The candidate busiest group 10593 * 10594 * @env::dst_cpu can do asym_packing if it has higher priority than the 10595 * preferred CPU of @group. 10596 * 10597 * Return: true if @env::dst_cpu can do with asym_packing load balance. False 10598 * otherwise. 10599 */ 10600 static inline bool 10601 sched_group_asym(struct lb_env *env, struct sg_lb_stats *sgs, struct sched_group *group) 10602 { 10603 /* 10604 * CPU priorities do not make sense for SMT cores with more than one 10605 * busy sibling. 10606 */ 10607 if ((group->flags & SD_SHARE_CPUCAPACITY) && 10608 (sgs->group_weight - sgs->idle_cpus != 1)) 10609 return false; 10610 10611 return sched_asym(env->sd, env->dst_cpu, READ_ONCE(group->asym_prefer_cpu)); 10612 } 10613 10614 /* One group has more than one SMT CPU while the other group does not */ 10615 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1, 10616 struct sched_group *sg2) 10617 { 10618 if (!sg1 || !sg2) 10619 return false; 10620 10621 return (sg1->flags & SD_SHARE_CPUCAPACITY) != 10622 (sg2->flags & SD_SHARE_CPUCAPACITY); 10623 } 10624 10625 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs, 10626 struct sched_group *group) 10627 { 10628 if (!env->idle) 10629 return false; 10630 10631 /* 10632 * For SMT source group, it is better to move a task 10633 * to a CPU that doesn't have multiple tasks sharing its CPU capacity. 10634 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY 10635 * will not be on. 10636 */ 10637 if (group->flags & SD_SHARE_CPUCAPACITY && 10638 sgs->sum_h_nr_running > 1) 10639 return true; 10640 10641 return false; 10642 } 10643 10644 static inline long sibling_imbalance(struct lb_env *env, 10645 struct sd_lb_stats *sds, 10646 struct sg_lb_stats *busiest, 10647 struct sg_lb_stats *local) 10648 { 10649 int ncores_busiest, ncores_local; 10650 long imbalance; 10651 10652 if (!env->idle || !busiest->sum_nr_running) 10653 return 0; 10654 10655 ncores_busiest = sds->busiest->cores; 10656 ncores_local = sds->local->cores; 10657 10658 if (ncores_busiest == ncores_local) { 10659 imbalance = busiest->sum_nr_running; 10660 lsub_positive(&imbalance, local->sum_nr_running); 10661 return imbalance; 10662 } 10663 10664 /* Balance such that nr_running/ncores ratio are same on both groups */ 10665 imbalance = ncores_local * busiest->sum_nr_running; 10666 lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running); 10667 /* Normalize imbalance and do rounding on normalization */ 10668 imbalance = 2 * imbalance + ncores_local + ncores_busiest; 10669 imbalance /= ncores_local + ncores_busiest; 10670 10671 /* Take advantage of resource in an empty sched group */ 10672 if (imbalance <= 1 && local->sum_nr_running == 0 && 10673 busiest->sum_nr_running > 1) 10674 imbalance = 2; 10675 10676 return imbalance; 10677 } 10678 10679 static inline bool 10680 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd) 10681 { 10682 /* 10683 * When there is more than 1 task, the group_overloaded case already 10684 * takes care of cpu with reduced capacity 10685 */ 10686 if (rq->cfs.h_nr_runnable != 1) 10687 return false; 10688 10689 return check_cpu_capacity(rq, sd); 10690 } 10691 10692 /** 10693 * update_sg_lb_stats - Update sched_group's statistics for load balancing. 10694 * @env: The load balancing environment. 10695 * @sds: Load-balancing data with statistics of the local group. 10696 * @group: sched_group whose statistics are to be updated. 10697 * @sgs: variable to hold the statistics for this group. 10698 * @sg_overloaded: sched_group is overloaded 10699 */ 10700 static inline void update_sg_lb_stats(struct lb_env *env, 10701 struct sd_lb_stats *sds, 10702 struct sched_group *group, 10703 struct sg_lb_stats *sgs, 10704 bool *sg_overloaded) 10705 { 10706 int i, nr_running, local_group, sd_flags = env->sd->flags; 10707 bool balancing_at_rd = !env->sd->parent; 10708 10709 memset(sgs, 0, sizeof(*sgs)); 10710 10711 local_group = group == sds->local; 10712 10713 for_each_cpu_and(i, sched_group_span(group), env->cpus) { 10714 struct rq *rq = cpu_rq(i); 10715 unsigned long load = cpu_load(rq); 10716 10717 sgs->group_load += load; 10718 sgs->group_util += cpu_util_cfs(i); 10719 sgs->group_runnable += cpu_runnable(rq); 10720 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable; 10721 10722 nr_running = rq->nr_running; 10723 sgs->sum_nr_running += nr_running; 10724 10725 if (cpu_overutilized(i)) 10726 sgs->group_overutilized = 1; 10727 10728 /* 10729 * No need to call idle_cpu() if nr_running is not 0 10730 */ 10731 if (!nr_running && idle_cpu(i)) { 10732 sgs->idle_cpus++; 10733 /* Idle cpu can't have misfit task */ 10734 continue; 10735 } 10736 10737 /* Overload indicator is only updated at root domain */ 10738 if (balancing_at_rd && nr_running > 1) 10739 *sg_overloaded = 1; 10740 10741 #ifdef CONFIG_NUMA_BALANCING 10742 /* Only fbq_classify_group() uses this to classify NUMA groups */ 10743 if (sd_flags & SD_NUMA) { 10744 sgs->nr_numa_running += rq->nr_numa_running; 10745 sgs->nr_preferred_running += rq->nr_preferred_running; 10746 } 10747 #endif 10748 if (local_group) 10749 continue; 10750 10751 if (sd_flags & SD_ASYM_CPUCAPACITY) { 10752 /* Check for a misfit task on the cpu */ 10753 if (sgs->group_misfit_task_load < rq->misfit_task_load) { 10754 sgs->group_misfit_task_load = rq->misfit_task_load; 10755 *sg_overloaded = 1; 10756 } 10757 } else if (env->idle && sched_reduced_capacity(rq, env->sd)) { 10758 /* Check for a task running on a CPU with reduced capacity */ 10759 if (sgs->group_misfit_task_load < load) 10760 sgs->group_misfit_task_load = load; 10761 } 10762 } 10763 10764 sgs->group_capacity = group->sgc->capacity; 10765 10766 sgs->group_weight = group->group_weight; 10767 10768 /* Check if dst CPU is idle and preferred to this group */ 10769 if (!local_group && env->idle && sgs->sum_h_nr_running && 10770 sched_group_asym(env, sgs, group)) 10771 sgs->group_asym_packing = 1; 10772 10773 /* Check for loaded SMT group to be balanced to dst CPU */ 10774 if (!local_group && smt_balance(env, sgs, group)) 10775 sgs->group_smt_balance = 1; 10776 10777 sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs); 10778 10779 /* Computing avg_load makes sense only when group is overloaded */ 10780 if (sgs->group_type == group_overloaded) 10781 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) / 10782 sgs->group_capacity; 10783 } 10784 10785 /** 10786 * update_sd_pick_busiest - return 1 on busiest group 10787 * @env: The load balancing environment. 10788 * @sds: sched_domain statistics 10789 * @sg: sched_group candidate to be checked for being the busiest 10790 * @sgs: sched_group statistics 10791 * 10792 * Determine if @sg is a busier group than the previously selected 10793 * busiest group. 10794 * 10795 * Return: %true if @sg is a busier group than the previously selected 10796 * busiest group. %false otherwise. 10797 */ 10798 static bool update_sd_pick_busiest(struct lb_env *env, 10799 struct sd_lb_stats *sds, 10800 struct sched_group *sg, 10801 struct sg_lb_stats *sgs) 10802 { 10803 struct sg_lb_stats *busiest = &sds->busiest_stat; 10804 10805 /* Make sure that there is at least one task to pull */ 10806 if (!sgs->sum_h_nr_running) 10807 return false; 10808 10809 /* 10810 * Don't try to pull misfit tasks we can't help. 10811 * We can use max_capacity here as reduction in capacity on some 10812 * CPUs in the group should either be possible to resolve 10813 * internally or be covered by avg_load imbalance (eventually). 10814 */ 10815 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) && 10816 (sgs->group_type == group_misfit_task) && 10817 (!capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) || 10818 sds->local_stat.group_type != group_has_spare)) 10819 return false; 10820 10821 if (sgs->group_type > busiest->group_type) 10822 return true; 10823 10824 if (sgs->group_type < busiest->group_type) 10825 return false; 10826 10827 /* 10828 * The candidate and the current busiest group are the same type of 10829 * group. Let check which one is the busiest according to the type. 10830 */ 10831 10832 switch (sgs->group_type) { 10833 case group_overloaded: 10834 /* Select the overloaded group with highest avg_load. */ 10835 return sgs->avg_load > busiest->avg_load; 10836 10837 case group_imbalanced: 10838 /* 10839 * Select the 1st imbalanced group as we don't have any way to 10840 * choose one more than another. 10841 */ 10842 return false; 10843 10844 case group_asym_packing: 10845 /* Prefer to move from lowest priority CPU's work */ 10846 return sched_asym_prefer(READ_ONCE(sds->busiest->asym_prefer_cpu), 10847 READ_ONCE(sg->asym_prefer_cpu)); 10848 10849 case group_misfit_task: 10850 /* 10851 * If we have more than one misfit sg go with the biggest 10852 * misfit. 10853 */ 10854 return sgs->group_misfit_task_load > busiest->group_misfit_task_load; 10855 10856 case group_smt_balance: 10857 /* 10858 * Check if we have spare CPUs on either SMT group to 10859 * choose has spare or fully busy handling. 10860 */ 10861 if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0) 10862 goto has_spare; 10863 10864 fallthrough; 10865 10866 case group_fully_busy: 10867 /* 10868 * Select the fully busy group with highest avg_load. In 10869 * theory, there is no need to pull task from such kind of 10870 * group because tasks have all compute capacity that they need 10871 * but we can still improve the overall throughput by reducing 10872 * contention when accessing shared HW resources. 10873 * 10874 * XXX for now avg_load is not computed and always 0 so we 10875 * select the 1st one, except if @sg is composed of SMT 10876 * siblings. 10877 */ 10878 10879 if (sgs->avg_load < busiest->avg_load) 10880 return false; 10881 10882 if (sgs->avg_load == busiest->avg_load) { 10883 /* 10884 * SMT sched groups need more help than non-SMT groups. 10885 * If @sg happens to also be SMT, either choice is good. 10886 */ 10887 if (sds->busiest->flags & SD_SHARE_CPUCAPACITY) 10888 return false; 10889 } 10890 10891 break; 10892 10893 case group_has_spare: 10894 /* 10895 * Do not pick sg with SMT CPUs over sg with pure CPUs, 10896 * as we do not want to pull task off SMT core with one task 10897 * and make the core idle. 10898 */ 10899 if (smt_vs_nonsmt_groups(sds->busiest, sg)) { 10900 if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1) 10901 return false; 10902 else 10903 return true; 10904 } 10905 has_spare: 10906 10907 /* 10908 * Select not overloaded group with lowest number of idle CPUs 10909 * and highest number of running tasks. We could also compare 10910 * the spare capacity which is more stable but it can end up 10911 * that the group has less spare capacity but finally more idle 10912 * CPUs which means less opportunity to pull tasks. 10913 */ 10914 if (sgs->idle_cpus > busiest->idle_cpus) 10915 return false; 10916 else if ((sgs->idle_cpus == busiest->idle_cpus) && 10917 (sgs->sum_nr_running <= busiest->sum_nr_running)) 10918 return false; 10919 10920 break; 10921 } 10922 10923 /* 10924 * Candidate sg has no more than one task per CPU and has higher 10925 * per-CPU capacity. Migrating tasks to less capable CPUs may harm 10926 * throughput. Maximize throughput, power/energy consequences are not 10927 * considered. 10928 */ 10929 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) && 10930 (sgs->group_type <= group_fully_busy) && 10931 (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu)))) 10932 return false; 10933 10934 return true; 10935 } 10936 10937 #ifdef CONFIG_NUMA_BALANCING 10938 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs) 10939 { 10940 if (sgs->sum_h_nr_running > sgs->nr_numa_running) 10941 return regular; 10942 if (sgs->sum_h_nr_running > sgs->nr_preferred_running) 10943 return remote; 10944 return all; 10945 } 10946 10947 static inline enum fbq_type fbq_classify_rq(struct rq *rq) 10948 { 10949 if (rq->nr_running > rq->nr_numa_running) 10950 return regular; 10951 if (rq->nr_running > rq->nr_preferred_running) 10952 return remote; 10953 return all; 10954 } 10955 #else /* !CONFIG_NUMA_BALANCING: */ 10956 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs) 10957 { 10958 return all; 10959 } 10960 10961 static inline enum fbq_type fbq_classify_rq(struct rq *rq) 10962 { 10963 return regular; 10964 } 10965 #endif /* !CONFIG_NUMA_BALANCING */ 10966 10967 10968 struct sg_lb_stats; 10969 10970 /* 10971 * task_running_on_cpu - return 1 if @p is running on @cpu. 10972 */ 10973 10974 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p) 10975 { 10976 /* Task has no contribution or is new */ 10977 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 10978 return 0; 10979 10980 if (task_on_rq_queued(p)) 10981 return 1; 10982 10983 return 0; 10984 } 10985 10986 /** 10987 * idle_cpu_without - would a given CPU be idle without p ? 10988 * @cpu: the processor on which idleness is tested. 10989 * @p: task which should be ignored. 10990 * 10991 * Return: 1 if the CPU would be idle. 0 otherwise. 10992 */ 10993 static int idle_cpu_without(int cpu, struct task_struct *p) 10994 { 10995 struct rq *rq = cpu_rq(cpu); 10996 10997 if (rq->curr != rq->idle && rq->curr != p) 10998 return 0; 10999 11000 /* 11001 * rq->nr_running can't be used but an updated version without the 11002 * impact of p on cpu must be used instead. The updated nr_running 11003 * be computed and tested before calling idle_cpu_without(). 11004 */ 11005 11006 if (rq->ttwu_pending) 11007 return 0; 11008 11009 return 1; 11010 } 11011 11012 /* 11013 * update_sg_wakeup_stats - Update sched_group's statistics for wakeup. 11014 * @sd: The sched_domain level to look for idlest group. 11015 * @group: sched_group whose statistics are to be updated. 11016 * @sgs: variable to hold the statistics for this group. 11017 * @p: The task for which we look for the idlest group/CPU. 11018 */ 11019 static inline void update_sg_wakeup_stats(struct sched_domain *sd, 11020 struct sched_group *group, 11021 struct sg_lb_stats *sgs, 11022 struct task_struct *p) 11023 { 11024 int i, nr_running; 11025 11026 memset(sgs, 0, sizeof(*sgs)); 11027 11028 /* Assume that task can't fit any CPU of the group */ 11029 if (sd->flags & SD_ASYM_CPUCAPACITY) 11030 sgs->group_misfit_task_load = 1; 11031 11032 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) { 11033 struct rq *rq = cpu_rq(i); 11034 unsigned int local; 11035 11036 sgs->group_load += cpu_load_without(rq, p); 11037 sgs->group_util += cpu_util_without(i, p); 11038 sgs->group_runnable += cpu_runnable_without(rq, p); 11039 local = task_running_on_cpu(i, p); 11040 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable - local; 11041 11042 nr_running = rq->nr_running - local; 11043 sgs->sum_nr_running += nr_running; 11044 11045 /* 11046 * No need to call idle_cpu_without() if nr_running is not 0 11047 */ 11048 if (!nr_running && idle_cpu_without(i, p)) 11049 sgs->idle_cpus++; 11050 11051 /* Check if task fits in the CPU */ 11052 if (sd->flags & SD_ASYM_CPUCAPACITY && 11053 sgs->group_misfit_task_load && 11054 task_fits_cpu(p, i)) 11055 sgs->group_misfit_task_load = 0; 11056 11057 } 11058 11059 sgs->group_capacity = group->sgc->capacity; 11060 11061 sgs->group_weight = group->group_weight; 11062 11063 sgs->group_type = group_classify(sd->imbalance_pct, group, sgs); 11064 11065 /* 11066 * Computing avg_load makes sense only when group is fully busy or 11067 * overloaded 11068 */ 11069 if (sgs->group_type == group_fully_busy || 11070 sgs->group_type == group_overloaded) 11071 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) / 11072 sgs->group_capacity; 11073 } 11074 11075 static bool update_pick_idlest(struct sched_group *idlest, 11076 struct sg_lb_stats *idlest_sgs, 11077 struct sched_group *group, 11078 struct sg_lb_stats *sgs) 11079 { 11080 if (sgs->group_type < idlest_sgs->group_type) 11081 return true; 11082 11083 if (sgs->group_type > idlest_sgs->group_type) 11084 return false; 11085 11086 /* 11087 * The candidate and the current idlest group are the same type of 11088 * group. Let check which one is the idlest according to the type. 11089 */ 11090 11091 switch (sgs->group_type) { 11092 case group_overloaded: 11093 case group_fully_busy: 11094 /* Select the group with lowest avg_load. */ 11095 if (idlest_sgs->avg_load <= sgs->avg_load) 11096 return false; 11097 break; 11098 11099 case group_imbalanced: 11100 case group_asym_packing: 11101 case group_smt_balance: 11102 /* Those types are not used in the slow wakeup path */ 11103 return false; 11104 11105 case group_misfit_task: 11106 /* Select group with the highest max capacity */ 11107 if (idlest->sgc->max_capacity >= group->sgc->max_capacity) 11108 return false; 11109 break; 11110 11111 case group_has_spare: 11112 /* Select group with most idle CPUs */ 11113 if (idlest_sgs->idle_cpus > sgs->idle_cpus) 11114 return false; 11115 11116 /* Select group with lowest group_util */ 11117 if (idlest_sgs->idle_cpus == sgs->idle_cpus && 11118 idlest_sgs->group_util <= sgs->group_util) 11119 return false; 11120 11121 break; 11122 } 11123 11124 return true; 11125 } 11126 11127 /* 11128 * sched_balance_find_dst_group() finds and returns the least busy CPU group within the 11129 * domain. 11130 * 11131 * Assumes p is allowed on at least one CPU in sd. 11132 */ 11133 static struct sched_group * 11134 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu) 11135 { 11136 struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups; 11137 struct sg_lb_stats local_sgs, tmp_sgs; 11138 struct sg_lb_stats *sgs; 11139 unsigned long imbalance; 11140 struct sg_lb_stats idlest_sgs = { 11141 .avg_load = UINT_MAX, 11142 .group_type = group_overloaded, 11143 }; 11144 11145 do { 11146 int local_group; 11147 11148 /* Skip over this group if it has no CPUs allowed */ 11149 if (!cpumask_intersects(sched_group_span(group), 11150 p->cpus_ptr)) 11151 continue; 11152 11153 /* Skip over this group if no cookie matched */ 11154 if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group)) 11155 continue; 11156 11157 local_group = cpumask_test_cpu(this_cpu, 11158 sched_group_span(group)); 11159 11160 if (local_group) { 11161 sgs = &local_sgs; 11162 local = group; 11163 } else { 11164 sgs = &tmp_sgs; 11165 } 11166 11167 update_sg_wakeup_stats(sd, group, sgs, p); 11168 11169 if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) { 11170 idlest = group; 11171 idlest_sgs = *sgs; 11172 } 11173 11174 } while (group = group->next, group != sd->groups); 11175 11176 11177 /* There is no idlest group to push tasks to */ 11178 if (!idlest) 11179 return NULL; 11180 11181 /* The local group has been skipped because of CPU affinity */ 11182 if (!local) 11183 return idlest; 11184 11185 /* 11186 * If the local group is idler than the selected idlest group 11187 * don't try and push the task. 11188 */ 11189 if (local_sgs.group_type < idlest_sgs.group_type) 11190 return NULL; 11191 11192 /* 11193 * If the local group is busier than the selected idlest group 11194 * try and push the task. 11195 */ 11196 if (local_sgs.group_type > idlest_sgs.group_type) 11197 return idlest; 11198 11199 switch (local_sgs.group_type) { 11200 case group_overloaded: 11201 case group_fully_busy: 11202 11203 /* Calculate allowed imbalance based on load */ 11204 imbalance = scale_load_down(NICE_0_LOAD) * 11205 (sd->imbalance_pct-100) / 100; 11206 11207 /* 11208 * When comparing groups across NUMA domains, it's possible for 11209 * the local domain to be very lightly loaded relative to the 11210 * remote domains but "imbalance" skews the comparison making 11211 * remote CPUs look much more favourable. When considering 11212 * cross-domain, add imbalance to the load on the remote node 11213 * and consider staying local. 11214 */ 11215 11216 if ((sd->flags & SD_NUMA) && 11217 ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load)) 11218 return NULL; 11219 11220 /* 11221 * If the local group is less loaded than the selected 11222 * idlest group don't try and push any tasks. 11223 */ 11224 if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance)) 11225 return NULL; 11226 11227 if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load) 11228 return NULL; 11229 break; 11230 11231 case group_imbalanced: 11232 case group_asym_packing: 11233 case group_smt_balance: 11234 /* Those type are not used in the slow wakeup path */ 11235 return NULL; 11236 11237 case group_misfit_task: 11238 /* Select group with the highest max capacity */ 11239 if (local->sgc->max_capacity >= idlest->sgc->max_capacity) 11240 return NULL; 11241 break; 11242 11243 case group_has_spare: 11244 #ifdef CONFIG_NUMA 11245 if (sd->flags & SD_NUMA) { 11246 int imb_numa_nr = sd->imb_numa_nr; 11247 #ifdef CONFIG_NUMA_BALANCING 11248 int idlest_cpu; 11249 /* 11250 * If there is spare capacity at NUMA, try to select 11251 * the preferred node 11252 */ 11253 if (cpu_to_node(this_cpu) == p->numa_preferred_nid) 11254 return NULL; 11255 11256 idlest_cpu = cpumask_first(sched_group_span(idlest)); 11257 if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid) 11258 return idlest; 11259 #endif /* CONFIG_NUMA_BALANCING */ 11260 /* 11261 * Otherwise, keep the task close to the wakeup source 11262 * and improve locality if the number of running tasks 11263 * would remain below threshold where an imbalance is 11264 * allowed while accounting for the possibility the 11265 * task is pinned to a subset of CPUs. If there is a 11266 * real need of migration, periodic load balance will 11267 * take care of it. 11268 */ 11269 if (p->nr_cpus_allowed != NR_CPUS) { 11270 unsigned int w = cpumask_weight_and(p->cpus_ptr, 11271 sched_group_span(local)); 11272 imb_numa_nr = min(w, sd->imb_numa_nr); 11273 } 11274 11275 imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus); 11276 if (!adjust_numa_imbalance(imbalance, 11277 local_sgs.sum_nr_running + 1, 11278 imb_numa_nr)) { 11279 return NULL; 11280 } 11281 } 11282 #endif /* CONFIG_NUMA */ 11283 11284 /* 11285 * Select group with highest number of idle CPUs. We could also 11286 * compare the utilization which is more stable but it can end 11287 * up that the group has less spare capacity but finally more 11288 * idle CPUs which means more opportunity to run task. 11289 */ 11290 if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus) 11291 return NULL; 11292 break; 11293 } 11294 11295 return idlest; 11296 } 11297 11298 static void update_idle_cpu_scan(struct lb_env *env, 11299 unsigned long sum_util) 11300 { 11301 struct sched_domain_shared *sd_share; 11302 struct sched_domain *sd = env->sd; 11303 int llc_weight, pct; 11304 u64 x, y, tmp; 11305 /* 11306 * Update the number of CPUs to scan in LLC domain, which could 11307 * be used as a hint in select_idle_cpu(). The update of sd_share 11308 * could be expensive because it is within a shared cache line. 11309 * So the write of this hint only occurs during periodic load 11310 * balancing, rather than CPU_NEWLY_IDLE, because the latter 11311 * can fire way more frequently than the former. 11312 */ 11313 if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE) 11314 return; 11315 11316 sd_share = sd->shared; 11317 if (!sd_share) 11318 return; 11319 11320 /* 11321 * The number of CPUs to search drops as sum_util increases, when 11322 * sum_util hits 85% or above, the scan stops. 11323 * The reason to choose 85% as the threshold is because this is the 11324 * imbalance_pct(117) when a LLC sched group is overloaded. 11325 * 11326 * let y = SCHED_CAPACITY_SCALE - p * x^2 [1] 11327 * and y'= y / SCHED_CAPACITY_SCALE 11328 * 11329 * x is the ratio of sum_util compared to the CPU capacity: 11330 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE) 11331 * y' is the ratio of CPUs to be scanned in the LLC domain, 11332 * and the number of CPUs to scan is calculated by: 11333 * 11334 * nr_scan = llc_weight * y' [2] 11335 * 11336 * When x hits the threshold of overloaded, AKA, when 11337 * x = 100 / pct, y drops to 0. According to [1], 11338 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000 11339 * 11340 * Scale x by SCHED_CAPACITY_SCALE: 11341 * x' = sum_util / llc_weight; [3] 11342 * 11343 * and finally [1] becomes: 11344 * y = SCHED_CAPACITY_SCALE - 11345 * x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE) [4] 11346 * 11347 */ 11348 /* equation [3] */ 11349 x = sum_util; 11350 llc_weight = sd->span_weight; 11351 do_div(x, llc_weight); 11352 11353 /* equation [4] */ 11354 pct = sd->imbalance_pct; 11355 tmp = x * x * pct * pct; 11356 do_div(tmp, 10000 * SCHED_CAPACITY_SCALE); 11357 tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE); 11358 y = SCHED_CAPACITY_SCALE - tmp; 11359 11360 /* equation [2] */ 11361 y *= llc_weight; 11362 do_div(y, SCHED_CAPACITY_SCALE); 11363 if ((int)y != sd_share->nr_idle_scan) 11364 WRITE_ONCE(sd_share->nr_idle_scan, (int)y); 11365 } 11366 11367 /** 11368 * update_sd_lb_stats - Update sched_domain's statistics for load balancing. 11369 * @env: The load balancing environment. 11370 * @sds: variable to hold the statistics for this sched_domain. 11371 */ 11372 11373 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds) 11374 { 11375 struct sched_group *sg = env->sd->groups; 11376 struct sg_lb_stats *local = &sds->local_stat; 11377 struct sg_lb_stats tmp_sgs; 11378 unsigned long sum_util = 0; 11379 bool sg_overloaded = 0, sg_overutilized = 0; 11380 11381 do { 11382 struct sg_lb_stats *sgs = &tmp_sgs; 11383 int local_group; 11384 11385 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg)); 11386 if (local_group) { 11387 sds->local = sg; 11388 sgs = local; 11389 11390 if (env->idle != CPU_NEWLY_IDLE || 11391 time_after_eq(jiffies, sg->sgc->next_update)) 11392 update_group_capacity(env->sd, env->dst_cpu); 11393 } 11394 11395 update_sg_lb_stats(env, sds, sg, sgs, &sg_overloaded); 11396 11397 if (!local_group && update_sd_pick_busiest(env, sds, sg, sgs)) { 11398 sds->busiest = sg; 11399 sds->busiest_stat = *sgs; 11400 } 11401 11402 sg_overutilized |= sgs->group_overutilized; 11403 11404 /* Now, start updating sd_lb_stats */ 11405 sds->total_load += sgs->group_load; 11406 sds->total_capacity += sgs->group_capacity; 11407 11408 sum_util += sgs->group_util; 11409 sg = sg->next; 11410 } while (sg != env->sd->groups); 11411 11412 /* 11413 * Indicate that the child domain of the busiest group prefers tasks 11414 * go to a child's sibling domains first. NB the flags of a sched group 11415 * are those of the child domain. 11416 */ 11417 if (sds->busiest) 11418 sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING); 11419 11420 11421 if (env->sd->flags & SD_NUMA) 11422 env->fbq_type = fbq_classify_group(&sds->busiest_stat); 11423 11424 if (!env->sd->parent) { 11425 /* update overload indicator if we are at root domain */ 11426 set_rd_overloaded(env->dst_rq->rd, sg_overloaded); 11427 11428 /* Update over-utilization (tipping point, U >= 0) indicator */ 11429 set_rd_overutilized(env->dst_rq->rd, sg_overutilized); 11430 } else if (sg_overutilized) { 11431 set_rd_overutilized(env->dst_rq->rd, sg_overutilized); 11432 } 11433 11434 update_idle_cpu_scan(env, sum_util); 11435 } 11436 11437 /** 11438 * calculate_imbalance - Calculate the amount of imbalance present within the 11439 * groups of a given sched_domain during load balance. 11440 * @env: load balance environment 11441 * @sds: statistics of the sched_domain whose imbalance is to be calculated. 11442 */ 11443 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds) 11444 { 11445 struct sg_lb_stats *local, *busiest; 11446 11447 local = &sds->local_stat; 11448 busiest = &sds->busiest_stat; 11449 11450 if (busiest->group_type == group_misfit_task) { 11451 if (env->sd->flags & SD_ASYM_CPUCAPACITY) { 11452 /* Set imbalance to allow misfit tasks to be balanced. */ 11453 env->migration_type = migrate_misfit; 11454 env->imbalance = 1; 11455 } else { 11456 /* 11457 * Set load imbalance to allow moving task from cpu 11458 * with reduced capacity. 11459 */ 11460 env->migration_type = migrate_load; 11461 env->imbalance = busiest->group_misfit_task_load; 11462 } 11463 return; 11464 } 11465 11466 if (busiest->group_type == group_asym_packing) { 11467 /* 11468 * In case of asym capacity, we will try to migrate all load to 11469 * the preferred CPU. 11470 */ 11471 env->migration_type = migrate_task; 11472 env->imbalance = busiest->sum_h_nr_running; 11473 return; 11474 } 11475 11476 if (busiest->group_type == group_smt_balance) { 11477 /* Reduce number of tasks sharing CPU capacity */ 11478 env->migration_type = migrate_task; 11479 env->imbalance = 1; 11480 return; 11481 } 11482 11483 if (busiest->group_type == group_imbalanced) { 11484 /* 11485 * In the group_imb case we cannot rely on group-wide averages 11486 * to ensure CPU-load equilibrium, try to move any task to fix 11487 * the imbalance. The next load balance will take care of 11488 * balancing back the system. 11489 */ 11490 env->migration_type = migrate_task; 11491 env->imbalance = 1; 11492 return; 11493 } 11494 11495 /* 11496 * Try to use spare capacity of local group without overloading it or 11497 * emptying busiest. 11498 */ 11499 if (local->group_type == group_has_spare) { 11500 if ((busiest->group_type > group_fully_busy) && 11501 !(env->sd->flags & SD_SHARE_LLC)) { 11502 /* 11503 * If busiest is overloaded, try to fill spare 11504 * capacity. This might end up creating spare capacity 11505 * in busiest or busiest still being overloaded but 11506 * there is no simple way to directly compute the 11507 * amount of load to migrate in order to balance the 11508 * system. 11509 */ 11510 env->migration_type = migrate_util; 11511 env->imbalance = max(local->group_capacity, local->group_util) - 11512 local->group_util; 11513 11514 /* 11515 * In some cases, the group's utilization is max or even 11516 * higher than capacity because of migrations but the 11517 * local CPU is (newly) idle. There is at least one 11518 * waiting task in this overloaded busiest group. Let's 11519 * try to pull it. 11520 */ 11521 if (env->idle && env->imbalance == 0) { 11522 env->migration_type = migrate_task; 11523 env->imbalance = 1; 11524 } 11525 11526 return; 11527 } 11528 11529 if (busiest->group_weight == 1 || sds->prefer_sibling) { 11530 /* 11531 * When prefer sibling, evenly spread running tasks on 11532 * groups. 11533 */ 11534 env->migration_type = migrate_task; 11535 env->imbalance = sibling_imbalance(env, sds, busiest, local); 11536 } else { 11537 11538 /* 11539 * If there is no overload, we just want to even the number of 11540 * idle CPUs. 11541 */ 11542 env->migration_type = migrate_task; 11543 env->imbalance = max_t(long, 0, 11544 (local->idle_cpus - busiest->idle_cpus)); 11545 } 11546 11547 #ifdef CONFIG_NUMA 11548 /* Consider allowing a small imbalance between NUMA groups */ 11549 if (env->sd->flags & SD_NUMA) { 11550 env->imbalance = adjust_numa_imbalance(env->imbalance, 11551 local->sum_nr_running + 1, 11552 env->sd->imb_numa_nr); 11553 } 11554 #endif 11555 11556 /* Number of tasks to move to restore balance */ 11557 env->imbalance >>= 1; 11558 11559 return; 11560 } 11561 11562 /* 11563 * Local is fully busy but has to take more load to relieve the 11564 * busiest group 11565 */ 11566 if (local->group_type < group_overloaded) { 11567 /* 11568 * Local will become overloaded so the avg_load metrics are 11569 * finally needed. 11570 */ 11571 11572 local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) / 11573 local->group_capacity; 11574 11575 /* 11576 * If the local group is more loaded than the selected 11577 * busiest group don't try to pull any tasks. 11578 */ 11579 if (local->avg_load >= busiest->avg_load) { 11580 env->imbalance = 0; 11581 return; 11582 } 11583 11584 sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) / 11585 sds->total_capacity; 11586 11587 /* 11588 * If the local group is more loaded than the average system 11589 * load, don't try to pull any tasks. 11590 */ 11591 if (local->avg_load >= sds->avg_load) { 11592 env->imbalance = 0; 11593 return; 11594 } 11595 11596 } 11597 11598 /* 11599 * Both group are or will become overloaded and we're trying to get all 11600 * the CPUs to the average_load, so we don't want to push ourselves 11601 * above the average load, nor do we wish to reduce the max loaded CPU 11602 * below the average load. At the same time, we also don't want to 11603 * reduce the group load below the group capacity. Thus we look for 11604 * the minimum possible imbalance. 11605 */ 11606 env->migration_type = migrate_load; 11607 env->imbalance = min( 11608 (busiest->avg_load - sds->avg_load) * busiest->group_capacity, 11609 (sds->avg_load - local->avg_load) * local->group_capacity 11610 ) / SCHED_CAPACITY_SCALE; 11611 } 11612 11613 /******* sched_balance_find_src_group() helpers end here *********************/ 11614 11615 /* 11616 * Decision matrix according to the local and busiest group type: 11617 * 11618 * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded 11619 * has_spare nr_idle balanced N/A N/A balanced balanced 11620 * fully_busy nr_idle nr_idle N/A N/A balanced balanced 11621 * misfit_task force N/A N/A N/A N/A N/A 11622 * asym_packing force force N/A N/A force force 11623 * imbalanced force force N/A N/A force force 11624 * overloaded force force N/A N/A force avg_load 11625 * 11626 * N/A : Not Applicable because already filtered while updating 11627 * statistics. 11628 * balanced : The system is balanced for these 2 groups. 11629 * force : Calculate the imbalance as load migration is probably needed. 11630 * avg_load : Only if imbalance is significant enough. 11631 * nr_idle : dst_cpu is not busy and the number of idle CPUs is quite 11632 * different in groups. 11633 */ 11634 11635 /** 11636 * sched_balance_find_src_group - Returns the busiest group within the sched_domain 11637 * if there is an imbalance. 11638 * @env: The load balancing environment. 11639 * 11640 * Also calculates the amount of runnable load which should be moved 11641 * to restore balance. 11642 * 11643 * Return: - The busiest group if imbalance exists. 11644 */ 11645 static struct sched_group *sched_balance_find_src_group(struct lb_env *env) 11646 { 11647 struct sg_lb_stats *local, *busiest; 11648 struct sd_lb_stats sds; 11649 11650 init_sd_lb_stats(&sds); 11651 11652 /* 11653 * Compute the various statistics relevant for load balancing at 11654 * this level. 11655 */ 11656 update_sd_lb_stats(env, &sds); 11657 11658 /* There is no busy sibling group to pull tasks from */ 11659 if (!sds.busiest) 11660 goto out_balanced; 11661 11662 busiest = &sds.busiest_stat; 11663 11664 /* Misfit tasks should be dealt with regardless of the avg load */ 11665 if (busiest->group_type == group_misfit_task) 11666 goto force_balance; 11667 11668 if (!is_rd_overutilized(env->dst_rq->rd) && 11669 rcu_dereference_all(env->dst_rq->rd->pd)) 11670 goto out_balanced; 11671 11672 /* ASYM feature bypasses nice load balance check */ 11673 if (busiest->group_type == group_asym_packing) 11674 goto force_balance; 11675 11676 /* 11677 * If the busiest group is imbalanced the below checks don't 11678 * work because they assume all things are equal, which typically 11679 * isn't true due to cpus_ptr constraints and the like. 11680 */ 11681 if (busiest->group_type == group_imbalanced) 11682 goto force_balance; 11683 11684 local = &sds.local_stat; 11685 /* 11686 * If the local group is busier than the selected busiest group 11687 * don't try and pull any tasks. 11688 */ 11689 if (local->group_type > busiest->group_type) 11690 goto out_balanced; 11691 11692 /* 11693 * When groups are overloaded, use the avg_load to ensure fairness 11694 * between tasks. 11695 */ 11696 if (local->group_type == group_overloaded) { 11697 /* 11698 * If the local group is more loaded than the selected 11699 * busiest group don't try to pull any tasks. 11700 */ 11701 if (local->avg_load >= busiest->avg_load) 11702 goto out_balanced; 11703 11704 /* XXX broken for overlapping NUMA groups */ 11705 sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) / 11706 sds.total_capacity; 11707 11708 /* 11709 * Don't pull any tasks if this group is already above the 11710 * domain average load. 11711 */ 11712 if (local->avg_load >= sds.avg_load) 11713 goto out_balanced; 11714 11715 /* 11716 * If the busiest group is more loaded, use imbalance_pct to be 11717 * conservative. 11718 */ 11719 if (100 * busiest->avg_load <= 11720 env->sd->imbalance_pct * local->avg_load) 11721 goto out_balanced; 11722 } 11723 11724 /* 11725 * Try to move all excess tasks to a sibling domain of the busiest 11726 * group's child domain. 11727 */ 11728 if (sds.prefer_sibling && local->group_type == group_has_spare && 11729 sibling_imbalance(env, &sds, busiest, local) > 1) 11730 goto force_balance; 11731 11732 if (busiest->group_type != group_overloaded) { 11733 if (!env->idle) { 11734 /* 11735 * If the busiest group is not overloaded (and as a 11736 * result the local one too) but this CPU is already 11737 * busy, let another idle CPU try to pull task. 11738 */ 11739 goto out_balanced; 11740 } 11741 11742 if (busiest->group_type == group_smt_balance && 11743 smt_vs_nonsmt_groups(sds.local, sds.busiest)) { 11744 /* Let non SMT CPU pull from SMT CPU sharing with sibling */ 11745 goto force_balance; 11746 } 11747 11748 if (busiest->group_weight > 1 && 11749 local->idle_cpus <= (busiest->idle_cpus + 1)) { 11750 /* 11751 * If the busiest group is not overloaded 11752 * and there is no imbalance between this and busiest 11753 * group wrt idle CPUs, it is balanced. The imbalance 11754 * becomes significant if the diff is greater than 1 11755 * otherwise we might end up to just move the imbalance 11756 * on another group. Of course this applies only if 11757 * there is more than 1 CPU per group. 11758 */ 11759 goto out_balanced; 11760 } 11761 11762 if (busiest->sum_h_nr_running == 1) { 11763 /* 11764 * busiest doesn't have any tasks waiting to run 11765 */ 11766 goto out_balanced; 11767 } 11768 } 11769 11770 force_balance: 11771 /* Looks like there is an imbalance. Compute it */ 11772 calculate_imbalance(env, &sds); 11773 return env->imbalance ? sds.busiest : NULL; 11774 11775 out_balanced: 11776 env->imbalance = 0; 11777 return NULL; 11778 } 11779 11780 /* 11781 * sched_balance_find_src_rq - find the busiest runqueue among the CPUs in the group. 11782 */ 11783 static struct rq *sched_balance_find_src_rq(struct lb_env *env, 11784 struct sched_group *group) 11785 { 11786 struct rq *busiest = NULL, *rq; 11787 unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1; 11788 unsigned int busiest_nr = 0; 11789 int i; 11790 11791 for_each_cpu_and(i, sched_group_span(group), env->cpus) { 11792 unsigned long capacity, load, util; 11793 unsigned int nr_running; 11794 enum fbq_type rt; 11795 11796 rq = cpu_rq(i); 11797 rt = fbq_classify_rq(rq); 11798 11799 /* 11800 * We classify groups/runqueues into three groups: 11801 * - regular: there are !numa tasks 11802 * - remote: there are numa tasks that run on the 'wrong' node 11803 * - all: there is no distinction 11804 * 11805 * In order to avoid migrating ideally placed numa tasks, 11806 * ignore those when there's better options. 11807 * 11808 * If we ignore the actual busiest queue to migrate another 11809 * task, the next balance pass can still reduce the busiest 11810 * queue by moving tasks around inside the node. 11811 * 11812 * If we cannot move enough load due to this classification 11813 * the next pass will adjust the group classification and 11814 * allow migration of more tasks. 11815 * 11816 * Both cases only affect the total convergence complexity. 11817 */ 11818 if (rt > env->fbq_type) 11819 continue; 11820 11821 nr_running = rq->cfs.h_nr_runnable; 11822 if (!nr_running) 11823 continue; 11824 11825 capacity = capacity_of(i); 11826 11827 /* 11828 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could 11829 * eventually lead to active_balancing high->low capacity. 11830 * Higher per-CPU capacity is considered better than balancing 11831 * average load. 11832 */ 11833 if (env->sd->flags & SD_ASYM_CPUCAPACITY && 11834 !capacity_greater(capacity_of(env->dst_cpu), capacity) && 11835 nr_running == 1) 11836 continue; 11837 11838 /* 11839 * Make sure we only pull tasks from a CPU of lower priority 11840 * when balancing between SMT siblings. 11841 * 11842 * If balancing between cores, let lower priority CPUs help 11843 * SMT cores with more than one busy sibling. 11844 */ 11845 if (sched_asym(env->sd, i, env->dst_cpu) && nr_running == 1) 11846 continue; 11847 11848 switch (env->migration_type) { 11849 case migrate_load: 11850 /* 11851 * When comparing with load imbalance, use cpu_load() 11852 * which is not scaled with the CPU capacity. 11853 */ 11854 load = cpu_load(rq); 11855 11856 if (nr_running == 1 && load > env->imbalance && 11857 !check_cpu_capacity(rq, env->sd)) 11858 break; 11859 11860 /* 11861 * For the load comparisons with the other CPUs, 11862 * consider the cpu_load() scaled with the CPU 11863 * capacity, so that the load can be moved away 11864 * from the CPU that is potentially running at a 11865 * lower capacity. 11866 * 11867 * Thus we're looking for max(load_i / capacity_i), 11868 * crosswise multiplication to rid ourselves of the 11869 * division works out to: 11870 * load_i * capacity_j > load_j * capacity_i; 11871 * where j is our previous maximum. 11872 */ 11873 if (load * busiest_capacity > busiest_load * capacity) { 11874 busiest_load = load; 11875 busiest_capacity = capacity; 11876 busiest = rq; 11877 } 11878 break; 11879 11880 case migrate_util: 11881 util = cpu_util_cfs_boost(i); 11882 11883 /* 11884 * Don't try to pull utilization from a CPU with one 11885 * running task. Whatever its utilization, we will fail 11886 * detach the task. 11887 */ 11888 if (nr_running <= 1) 11889 continue; 11890 11891 if (busiest_util < util) { 11892 busiest_util = util; 11893 busiest = rq; 11894 } 11895 break; 11896 11897 case migrate_task: 11898 if (busiest_nr < nr_running) { 11899 busiest_nr = nr_running; 11900 busiest = rq; 11901 } 11902 break; 11903 11904 case migrate_misfit: 11905 /* 11906 * For ASYM_CPUCAPACITY domains with misfit tasks we 11907 * simply seek the "biggest" misfit task. 11908 */ 11909 if (rq->misfit_task_load > busiest_load) { 11910 busiest_load = rq->misfit_task_load; 11911 busiest = rq; 11912 } 11913 11914 break; 11915 11916 } 11917 } 11918 11919 return busiest; 11920 } 11921 11922 /* 11923 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but 11924 * so long as it is large enough. 11925 */ 11926 #define MAX_PINNED_INTERVAL 512 11927 11928 static inline bool 11929 asym_active_balance(struct lb_env *env) 11930 { 11931 /* 11932 * ASYM_PACKING needs to force migrate tasks from busy but lower 11933 * priority CPUs in order to pack all tasks in the highest priority 11934 * CPUs. When done between cores, do it only if the whole core if the 11935 * whole core is idle. 11936 * 11937 * If @env::src_cpu is an SMT core with busy siblings, let 11938 * the lower priority @env::dst_cpu help it. Do not follow 11939 * CPU priority. 11940 */ 11941 return env->idle && sched_use_asym_prio(env->sd, env->dst_cpu) && 11942 (sched_asym_prefer(env->dst_cpu, env->src_cpu) || 11943 !sched_use_asym_prio(env->sd, env->src_cpu)); 11944 } 11945 11946 static inline bool 11947 imbalanced_active_balance(struct lb_env *env) 11948 { 11949 struct sched_domain *sd = env->sd; 11950 11951 /* 11952 * The imbalanced case includes the case of pinned tasks preventing a fair 11953 * distribution of the load on the system but also the even distribution of the 11954 * threads on a system with spare capacity 11955 */ 11956 if ((env->migration_type == migrate_task) && 11957 (sd->nr_balance_failed > sd->cache_nice_tries+2)) 11958 return 1; 11959 11960 return 0; 11961 } 11962 11963 static int need_active_balance(struct lb_env *env) 11964 { 11965 struct sched_domain *sd = env->sd; 11966 11967 if (asym_active_balance(env)) 11968 return 1; 11969 11970 if (imbalanced_active_balance(env)) 11971 return 1; 11972 11973 /* 11974 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task. 11975 * It's worth migrating the task if the src_cpu's capacity is reduced 11976 * because of other sched_class or IRQs if more capacity stays 11977 * available on dst_cpu. 11978 */ 11979 if (env->idle && 11980 (env->src_rq->cfs.h_nr_runnable == 1)) { 11981 if ((check_cpu_capacity(env->src_rq, sd)) && 11982 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100)) 11983 return 1; 11984 } 11985 11986 if (env->migration_type == migrate_misfit) 11987 return 1; 11988 11989 return 0; 11990 } 11991 11992 static int active_load_balance_cpu_stop(void *data); 11993 11994 static int should_we_balance(struct lb_env *env) 11995 { 11996 struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask); 11997 struct sched_group *sg = env->sd->groups; 11998 int cpu, idle_smt = -1; 11999 12000 /* 12001 * Ensure the balancing environment is consistent; can happen 12002 * when the softirq triggers 'during' hotplug. 12003 */ 12004 if (!cpumask_test_cpu(env->dst_cpu, env->cpus)) 12005 return 0; 12006 12007 /* 12008 * In the newly idle case, we will allow all the CPUs 12009 * to do the newly idle load balance. 12010 * 12011 * However, we bail out if we already have tasks or a wakeup pending, 12012 * to optimize wakeup latency. 12013 */ 12014 if (env->idle == CPU_NEWLY_IDLE) { 12015 if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending) 12016 return 0; 12017 return 1; 12018 } 12019 12020 cpumask_copy(swb_cpus, group_balance_mask(sg)); 12021 /* Try to find first idle CPU */ 12022 for_each_cpu_and(cpu, swb_cpus, env->cpus) { 12023 if (!idle_cpu(cpu)) 12024 continue; 12025 12026 /* 12027 * Don't balance to idle SMT in busy core right away when 12028 * balancing cores, but remember the first idle SMT CPU for 12029 * later consideration. Find CPU on an idle core first. 12030 */ 12031 if (!(env->sd->flags & SD_SHARE_CPUCAPACITY) && !is_core_idle(cpu)) { 12032 if (idle_smt == -1) 12033 idle_smt = cpu; 12034 /* 12035 * If the core is not idle, and first SMT sibling which is 12036 * idle has been found, then its not needed to check other 12037 * SMT siblings for idleness: 12038 */ 12039 #ifdef CONFIG_SCHED_SMT 12040 cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu)); 12041 #endif 12042 continue; 12043 } 12044 12045 /* 12046 * Are we the first idle core in a non-SMT domain or higher, 12047 * or the first idle CPU in a SMT domain? 12048 */ 12049 return cpu == env->dst_cpu; 12050 } 12051 12052 /* Are we the first idle CPU with busy siblings? */ 12053 if (idle_smt != -1) 12054 return idle_smt == env->dst_cpu; 12055 12056 /* Are we the first CPU of this group ? */ 12057 return group_balance_cpu(sg) == env->dst_cpu; 12058 } 12059 12060 static void update_lb_imbalance_stat(struct lb_env *env, struct sched_domain *sd, 12061 enum cpu_idle_type idle) 12062 { 12063 if (!schedstat_enabled()) 12064 return; 12065 12066 switch (env->migration_type) { 12067 case migrate_load: 12068 __schedstat_add(sd->lb_imbalance_load[idle], env->imbalance); 12069 break; 12070 case migrate_util: 12071 __schedstat_add(sd->lb_imbalance_util[idle], env->imbalance); 12072 break; 12073 case migrate_task: 12074 __schedstat_add(sd->lb_imbalance_task[idle], env->imbalance); 12075 break; 12076 case migrate_misfit: 12077 __schedstat_add(sd->lb_imbalance_misfit[idle], env->imbalance); 12078 break; 12079 } 12080 } 12081 12082 /* 12083 * This flag serializes load-balancing passes over large domains 12084 * (above the NODE topology level) - only one load-balancing instance 12085 * may run at a time, to reduce overhead on very large systems with 12086 * lots of CPUs and large NUMA distances. 12087 * 12088 * - Note that load-balancing passes triggered while another one 12089 * is executing are skipped and not re-tried. 12090 * 12091 * - Also note that this does not serialize rebalance_domains() 12092 * execution, as non-SD_SERIALIZE domains will still be 12093 * load-balanced in parallel. 12094 */ 12095 static atomic_t sched_balance_running = ATOMIC_INIT(0); 12096 12097 /* 12098 * Check this_cpu to ensure it is balanced within domain. Attempt to move 12099 * tasks if there is an imbalance. 12100 */ 12101 static int sched_balance_rq(int this_cpu, struct rq *this_rq, 12102 struct sched_domain *sd, enum cpu_idle_type idle, 12103 int *continue_balancing) 12104 { 12105 int ld_moved, cur_ld_moved, active_balance = 0; 12106 struct sched_domain *sd_parent = sd->parent; 12107 struct sched_group *group; 12108 struct rq *busiest; 12109 struct rq_flags rf; 12110 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask); 12111 struct lb_env env = { 12112 .sd = sd, 12113 .dst_cpu = this_cpu, 12114 .dst_rq = this_rq, 12115 .dst_grpmask = group_balance_mask(sd->groups), 12116 .idle = idle, 12117 .loop_break = SCHED_NR_MIGRATE_BREAK, 12118 .cpus = cpus, 12119 .fbq_type = all, 12120 .tasks = LIST_HEAD_INIT(env.tasks), 12121 }; 12122 bool need_unlock = false; 12123 12124 cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask); 12125 12126 schedstat_inc(sd->lb_count[idle]); 12127 12128 redo: 12129 if (!should_we_balance(&env)) { 12130 *continue_balancing = 0; 12131 goto out_balanced; 12132 } 12133 12134 if (!need_unlock && (sd->flags & SD_SERIALIZE)) { 12135 int zero = 0; 12136 if (!atomic_try_cmpxchg_acquire(&sched_balance_running, &zero, 1)) 12137 goto out_balanced; 12138 12139 need_unlock = true; 12140 } 12141 12142 group = sched_balance_find_src_group(&env); 12143 if (!group) { 12144 schedstat_inc(sd->lb_nobusyg[idle]); 12145 goto out_balanced; 12146 } 12147 12148 busiest = sched_balance_find_src_rq(&env, group); 12149 if (!busiest) { 12150 schedstat_inc(sd->lb_nobusyq[idle]); 12151 goto out_balanced; 12152 } 12153 12154 WARN_ON_ONCE(busiest == env.dst_rq); 12155 12156 update_lb_imbalance_stat(&env, sd, idle); 12157 12158 env.src_cpu = busiest->cpu; 12159 env.src_rq = busiest; 12160 12161 ld_moved = 0; 12162 /* Clear this flag as soon as we find a pullable task */ 12163 env.flags |= LBF_ALL_PINNED; 12164 if (busiest->nr_running > 1) { 12165 /* 12166 * Attempt to move tasks. If sched_balance_find_src_group has found 12167 * an imbalance but busiest->nr_running <= 1, the group is 12168 * still unbalanced. ld_moved simply stays zero, so it is 12169 * correctly treated as an imbalance. 12170 */ 12171 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running); 12172 12173 more_balance: 12174 rq_lock_irqsave(busiest, &rf); 12175 update_rq_clock(busiest); 12176 12177 /* 12178 * cur_ld_moved - load moved in current iteration 12179 * ld_moved - cumulative load moved across iterations 12180 */ 12181 cur_ld_moved = detach_tasks(&env); 12182 12183 /* 12184 * We've detached some tasks from busiest_rq. Every 12185 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely 12186 * unlock busiest->lock, and we are able to be sure 12187 * that nobody can manipulate the tasks in parallel. 12188 * See task_rq_lock() family for the details. 12189 */ 12190 12191 rq_unlock(busiest, &rf); 12192 12193 if (cur_ld_moved) { 12194 attach_tasks(&env); 12195 ld_moved += cur_ld_moved; 12196 } 12197 12198 local_irq_restore(rf.flags); 12199 12200 if (env.flags & LBF_NEED_BREAK) { 12201 env.flags &= ~LBF_NEED_BREAK; 12202 goto more_balance; 12203 } 12204 12205 /* 12206 * Revisit (affine) tasks on src_cpu that couldn't be moved to 12207 * us and move them to an alternate dst_cpu in our sched_group 12208 * where they can run. The upper limit on how many times we 12209 * iterate on same src_cpu is dependent on number of CPUs in our 12210 * sched_group. 12211 * 12212 * This changes load balance semantics a bit on who can move 12213 * load to a given_cpu. In addition to the given_cpu itself 12214 * (or a ilb_cpu acting on its behalf where given_cpu is 12215 * nohz-idle), we now have balance_cpu in a position to move 12216 * load to given_cpu. In rare situations, this may cause 12217 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding 12218 * _independently_ and at _same_ time to move some load to 12219 * given_cpu) causing excess load to be moved to given_cpu. 12220 * This however should not happen so much in practice and 12221 * moreover subsequent load balance cycles should correct the 12222 * excess load moved. 12223 */ 12224 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) { 12225 12226 /* Prevent to re-select dst_cpu via env's CPUs */ 12227 __cpumask_clear_cpu(env.dst_cpu, env.cpus); 12228 12229 env.dst_rq = cpu_rq(env.new_dst_cpu); 12230 env.dst_cpu = env.new_dst_cpu; 12231 env.flags &= ~LBF_DST_PINNED; 12232 env.loop = 0; 12233 env.loop_break = SCHED_NR_MIGRATE_BREAK; 12234 12235 /* 12236 * Go back to "more_balance" rather than "redo" since we 12237 * need to continue with same src_cpu. 12238 */ 12239 goto more_balance; 12240 } 12241 12242 /* 12243 * We failed to reach balance because of affinity. 12244 */ 12245 if (sd_parent) { 12246 int *group_imbalance = &sd_parent->groups->sgc->imbalance; 12247 12248 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0) 12249 *group_imbalance = 1; 12250 } 12251 12252 /* All tasks on this runqueue were pinned by CPU affinity */ 12253 if (unlikely(env.flags & LBF_ALL_PINNED)) { 12254 __cpumask_clear_cpu(cpu_of(busiest), cpus); 12255 /* 12256 * Attempting to continue load balancing at the current 12257 * sched_domain level only makes sense if there are 12258 * active CPUs remaining as possible busiest CPUs to 12259 * pull load from which are not contained within the 12260 * destination group that is receiving any migrated 12261 * load. 12262 */ 12263 if (!cpumask_subset(cpus, env.dst_grpmask)) { 12264 env.loop = 0; 12265 env.loop_break = SCHED_NR_MIGRATE_BREAK; 12266 goto redo; 12267 } 12268 goto out_all_pinned; 12269 } 12270 } 12271 12272 if (!ld_moved) { 12273 schedstat_inc(sd->lb_failed[idle]); 12274 /* 12275 * Increment the failure counter only on periodic balance. 12276 * We do not want newidle balance, which can be very 12277 * frequent, pollute the failure counter causing 12278 * excessive cache_hot migrations and active balances. 12279 * 12280 * Similarly for migration_misfit which is not related to 12281 * load/util migration, don't pollute nr_balance_failed. 12282 */ 12283 if (idle != CPU_NEWLY_IDLE && 12284 env.migration_type != migrate_misfit) 12285 sd->nr_balance_failed++; 12286 12287 if (need_active_balance(&env)) { 12288 unsigned long flags; 12289 12290 raw_spin_rq_lock_irqsave(busiest, flags); 12291 12292 /* 12293 * Don't kick the active_load_balance_cpu_stop, 12294 * if the curr task on busiest CPU can't be 12295 * moved to this_cpu: 12296 */ 12297 if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) { 12298 raw_spin_rq_unlock_irqrestore(busiest, flags); 12299 goto out_one_pinned; 12300 } 12301 12302 /* Record that we found at least one task that could run on this_cpu */ 12303 env.flags &= ~LBF_ALL_PINNED; 12304 12305 /* 12306 * ->active_balance synchronizes accesses to 12307 * ->active_balance_work. Once set, it's cleared 12308 * only after active load balance is finished. 12309 */ 12310 if (!busiest->active_balance) { 12311 busiest->active_balance = 1; 12312 busiest->push_cpu = this_cpu; 12313 active_balance = 1; 12314 } 12315 12316 preempt_disable(); 12317 raw_spin_rq_unlock_irqrestore(busiest, flags); 12318 if (active_balance) { 12319 stop_one_cpu_nowait(cpu_of(busiest), 12320 active_load_balance_cpu_stop, busiest, 12321 &busiest->active_balance_work); 12322 } 12323 preempt_enable(); 12324 } 12325 } else { 12326 sd->nr_balance_failed = 0; 12327 } 12328 12329 if (likely(!active_balance) || need_active_balance(&env)) { 12330 /* We were unbalanced, so reset the balancing interval */ 12331 sd->balance_interval = sd->min_interval; 12332 } 12333 12334 goto out; 12335 12336 out_balanced: 12337 /* 12338 * We reach balance although we may have faced some affinity 12339 * constraints. Clear the imbalance flag only if other tasks got 12340 * a chance to move and fix the imbalance. 12341 */ 12342 if (sd_parent && !(env.flags & LBF_ALL_PINNED)) { 12343 int *group_imbalance = &sd_parent->groups->sgc->imbalance; 12344 12345 if (*group_imbalance) 12346 *group_imbalance = 0; 12347 } 12348 12349 out_all_pinned: 12350 /* 12351 * We reach balance because all tasks are pinned at this level so 12352 * we can't migrate them. Let the imbalance flag set so parent level 12353 * can try to migrate them. 12354 */ 12355 schedstat_inc(sd->lb_balanced[idle]); 12356 12357 sd->nr_balance_failed = 0; 12358 12359 out_one_pinned: 12360 ld_moved = 0; 12361 12362 /* 12363 * sched_balance_newidle() disregards balance intervals, so we could 12364 * repeatedly reach this code, which would lead to balance_interval 12365 * skyrocketing in a short amount of time. Skip the balance_interval 12366 * increase logic to avoid that. 12367 * 12368 * Similarly misfit migration which is not necessarily an indication of 12369 * the system being busy and requires lb to backoff to let it settle 12370 * down. 12371 */ 12372 if (env.idle == CPU_NEWLY_IDLE || 12373 env.migration_type == migrate_misfit) 12374 goto out; 12375 12376 /* tune up the balancing interval */ 12377 if ((env.flags & LBF_ALL_PINNED && 12378 sd->balance_interval < MAX_PINNED_INTERVAL) || 12379 sd->balance_interval < sd->max_interval) 12380 sd->balance_interval *= 2; 12381 out: 12382 if (need_unlock) 12383 atomic_set_release(&sched_balance_running, 0); 12384 12385 return ld_moved; 12386 } 12387 12388 static inline unsigned long 12389 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy) 12390 { 12391 unsigned long interval = sd->balance_interval; 12392 12393 if (cpu_busy) 12394 interval *= sd->busy_factor; 12395 12396 /* scale ms to jiffies */ 12397 interval = msecs_to_jiffies(interval); 12398 12399 /* 12400 * Reduce likelihood of busy balancing at higher domains racing with 12401 * balancing at lower domains by preventing their balancing periods 12402 * from being multiples of each other. 12403 */ 12404 if (cpu_busy) 12405 interval -= 1; 12406 12407 interval = clamp(interval, 1UL, max_load_balance_interval); 12408 12409 return interval; 12410 } 12411 12412 static inline void 12413 update_next_balance(struct sched_domain *sd, unsigned long *next_balance) 12414 { 12415 unsigned long interval, next; 12416 12417 /* used by idle balance, so cpu_busy = 0 */ 12418 interval = get_sd_balance_interval(sd, 0); 12419 next = sd->last_balance + interval; 12420 12421 if (time_after(*next_balance, next)) 12422 *next_balance = next; 12423 } 12424 12425 /* 12426 * active_load_balance_cpu_stop is run by the CPU stopper. It pushes 12427 * running tasks off the busiest CPU onto idle CPUs. It requires at 12428 * least 1 task to be running on each physical CPU where possible, and 12429 * avoids physical / logical imbalances. 12430 */ 12431 static int active_load_balance_cpu_stop(void *data) 12432 { 12433 struct rq *busiest_rq = data; 12434 int busiest_cpu = cpu_of(busiest_rq); 12435 int target_cpu = busiest_rq->push_cpu; 12436 struct rq *target_rq = cpu_rq(target_cpu); 12437 struct sched_domain *sd; 12438 struct task_struct *p = NULL; 12439 struct rq_flags rf; 12440 12441 rq_lock_irq(busiest_rq, &rf); 12442 /* 12443 * Between queueing the stop-work and running it is a hole in which 12444 * CPUs can become inactive. We should not move tasks from or to 12445 * inactive CPUs. 12446 */ 12447 if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu)) 12448 goto out_unlock; 12449 12450 /* Make sure the requested CPU hasn't gone down in the meantime: */ 12451 if (unlikely(busiest_cpu != smp_processor_id() || 12452 !busiest_rq->active_balance)) 12453 goto out_unlock; 12454 12455 /* Is there any task to move? */ 12456 if (busiest_rq->nr_running <= 1) 12457 goto out_unlock; 12458 12459 /* 12460 * This condition is "impossible", if it occurs 12461 * we need to fix it. Originally reported by 12462 * Bjorn Helgaas on a 128-CPU setup. 12463 */ 12464 WARN_ON_ONCE(busiest_rq == target_rq); 12465 12466 /* Search for an sd spanning us and the target CPU. */ 12467 rcu_read_lock(); 12468 for_each_domain(target_cpu, sd) { 12469 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd))) 12470 break; 12471 } 12472 12473 if (likely(sd)) { 12474 struct lb_env env = { 12475 .sd = sd, 12476 .dst_cpu = target_cpu, 12477 .dst_rq = target_rq, 12478 .src_cpu = busiest_rq->cpu, 12479 .src_rq = busiest_rq, 12480 .idle = CPU_IDLE, 12481 .flags = LBF_ACTIVE_LB, 12482 }; 12483 12484 schedstat_inc(sd->alb_count); 12485 update_rq_clock(busiest_rq); 12486 12487 p = detach_one_task(&env); 12488 if (p) { 12489 schedstat_inc(sd->alb_pushed); 12490 /* Active balancing done, reset the failure counter. */ 12491 sd->nr_balance_failed = 0; 12492 } else { 12493 schedstat_inc(sd->alb_failed); 12494 } 12495 } 12496 rcu_read_unlock(); 12497 out_unlock: 12498 busiest_rq->active_balance = 0; 12499 rq_unlock(busiest_rq, &rf); 12500 12501 if (p) 12502 attach_one_task(target_rq, p); 12503 12504 local_irq_enable(); 12505 12506 return 0; 12507 } 12508 12509 /* 12510 * Scale the max sched_balance_rq interval with the number of CPUs in the system. 12511 * This trades load-balance latency on larger machines for less cross talk. 12512 */ 12513 void update_max_interval(void) 12514 { 12515 max_load_balance_interval = HZ*num_online_cpus()/10; 12516 } 12517 12518 static inline void update_newidle_stats(struct sched_domain *sd, unsigned int success) 12519 { 12520 sd->newidle_call++; 12521 sd->newidle_success += success; 12522 12523 if (sd->newidle_call >= 1024) { 12524 u64 now = sched_clock(); 12525 s64 delta = now - sd->newidle_stamp; 12526 sd->newidle_stamp = now; 12527 int ratio = 0; 12528 12529 if (delta < 0) 12530 delta = 0; 12531 12532 if (sched_feat(NI_RATE)) { 12533 /* 12534 * ratio delta freq 12535 * 12536 * 1024 - 4 s - 128 Hz 12537 * 512 - 2 s - 256 Hz 12538 * 256 - 1 s - 512 Hz 12539 * 128 - .5 s - 1024 Hz 12540 * 64 - .25 s - 2048 Hz 12541 */ 12542 ratio = delta >> 22; 12543 } 12544 12545 ratio += sd->newidle_success; 12546 12547 sd->newidle_ratio = min(1024, ratio); 12548 sd->newidle_call /= 2; 12549 sd->newidle_success /= 2; 12550 } 12551 } 12552 12553 static inline bool 12554 update_newidle_cost(struct sched_domain *sd, u64 cost, unsigned int success) 12555 { 12556 unsigned long next_decay = sd->last_decay_max_lb_cost + HZ; 12557 unsigned long now = jiffies; 12558 12559 if (cost) 12560 update_newidle_stats(sd, success); 12561 12562 if (cost > sd->max_newidle_lb_cost) { 12563 /* 12564 * Track max cost of a domain to make sure to not delay the 12565 * next wakeup on the CPU. 12566 */ 12567 sd->max_newidle_lb_cost = cost; 12568 sd->last_decay_max_lb_cost = now; 12569 12570 } else if (time_after(now, next_decay)) { 12571 /* 12572 * Decay the newidle max times by ~1% per second to ensure that 12573 * it is not outdated and the current max cost is actually 12574 * shorter. 12575 */ 12576 sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256; 12577 sd->last_decay_max_lb_cost = now; 12578 return true; 12579 } 12580 12581 return false; 12582 } 12583 12584 /* 12585 * It checks each scheduling domain to see if it is due to be balanced, 12586 * and initiates a balancing operation if so. 12587 * 12588 * Balancing parameters are set up in init_sched_domains. 12589 */ 12590 static void sched_balance_domains(struct rq *rq, enum cpu_idle_type idle) 12591 { 12592 int continue_balancing = 1; 12593 int cpu = rq->cpu; 12594 int busy = idle != CPU_IDLE && !sched_idle_rq(rq); 12595 unsigned long interval; 12596 struct sched_domain *sd; 12597 /* Earliest time when we have to do rebalance again */ 12598 unsigned long next_balance = jiffies + 60*HZ; 12599 int update_next_balance = 0; 12600 int need_decay = 0; 12601 u64 max_cost = 0; 12602 12603 rcu_read_lock(); 12604 for_each_domain(cpu, sd) { 12605 /* 12606 * Decay the newidle max times here because this is a regular 12607 * visit to all the domains. 12608 */ 12609 need_decay = update_newidle_cost(sd, 0, 0); 12610 max_cost += sd->max_newidle_lb_cost; 12611 12612 /* 12613 * Stop the load balance at this level. There is another 12614 * CPU in our sched group which is doing load balancing more 12615 * actively. 12616 */ 12617 if (!continue_balancing) { 12618 if (need_decay) 12619 continue; 12620 break; 12621 } 12622 12623 interval = get_sd_balance_interval(sd, busy); 12624 if (time_after_eq(jiffies, sd->last_balance + interval)) { 12625 if (sched_balance_rq(cpu, rq, sd, idle, &continue_balancing)) { 12626 /* 12627 * The LBF_DST_PINNED logic could have changed 12628 * env->dst_cpu, so we can't know our idle 12629 * state even if we migrated tasks. Update it. 12630 */ 12631 idle = idle_cpu(cpu); 12632 busy = !idle && !sched_idle_rq(rq); 12633 } 12634 sd->last_balance = jiffies; 12635 interval = get_sd_balance_interval(sd, busy); 12636 } 12637 if (time_after(next_balance, sd->last_balance + interval)) { 12638 next_balance = sd->last_balance + interval; 12639 update_next_balance = 1; 12640 } 12641 } 12642 if (need_decay) { 12643 /* 12644 * Ensure the rq-wide value also decays but keep it at a 12645 * reasonable floor to avoid funnies with rq->avg_idle. 12646 */ 12647 rq->max_idle_balance_cost = 12648 max((u64)sysctl_sched_migration_cost, max_cost); 12649 } 12650 rcu_read_unlock(); 12651 12652 /* 12653 * next_balance will be updated only when there is a need. 12654 * When the cpu is attached to null domain for ex, it will not be 12655 * updated. 12656 */ 12657 if (likely(update_next_balance)) 12658 rq->next_balance = next_balance; 12659 12660 } 12661 12662 static inline int on_null_domain(struct rq *rq) 12663 { 12664 return unlikely(!rcu_dereference_sched(rq->sd)); 12665 } 12666 12667 #ifdef CONFIG_NO_HZ_COMMON 12668 /* 12669 * NOHZ idle load balancing (ILB) details: 12670 * 12671 * - When one of the busy CPUs notices that there may be an idle rebalancing 12672 * needed, they will kick the idle load balancer, which then does idle 12673 * load balancing for all the idle CPUs. 12674 */ 12675 static inline int find_new_ilb(void) 12676 { 12677 int this_cpu = smp_processor_id(); 12678 const struct cpumask *hk_mask; 12679 int ilb_cpu; 12680 12681 hk_mask = housekeeping_cpumask(HK_TYPE_KERNEL_NOISE); 12682 12683 for_each_cpu_and(ilb_cpu, nohz.idle_cpus_mask, hk_mask) { 12684 if (ilb_cpu == this_cpu) 12685 continue; 12686 12687 if (idle_cpu(ilb_cpu)) 12688 return ilb_cpu; 12689 } 12690 12691 return -1; 12692 } 12693 12694 /* 12695 * Kick a CPU to do the NOHZ balancing, if it is time for it, via a cross-CPU 12696 * SMP function call (IPI). 12697 * 12698 * We pick the first idle CPU in the HK_TYPE_KERNEL_NOISE housekeeping set 12699 * (if there is one). 12700 */ 12701 static void kick_ilb(unsigned int flags) 12702 { 12703 int ilb_cpu; 12704 12705 /* 12706 * Increase nohz.next_balance only when if full ilb is triggered but 12707 * not if we only update stats. 12708 */ 12709 if (flags & NOHZ_BALANCE_KICK) 12710 nohz.next_balance = jiffies+1; 12711 12712 ilb_cpu = find_new_ilb(); 12713 if (ilb_cpu < 0) 12714 return; 12715 12716 /* 12717 * Don't bother if no new NOHZ balance work items for ilb_cpu, 12718 * i.e. all bits in flags are already set in ilb_cpu. 12719 */ 12720 if ((atomic_read(nohz_flags(ilb_cpu)) & flags) == flags) 12721 return; 12722 12723 /* 12724 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets 12725 * the first flag owns it; cleared by nohz_csd_func(). 12726 */ 12727 flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu)); 12728 if (flags & NOHZ_KICK_MASK) 12729 return; 12730 12731 /* 12732 * This way we generate an IPI on the target CPU which 12733 * is idle, and the softirq performing NOHZ idle load balancing 12734 * will be run before returning from the IPI. 12735 */ 12736 smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd); 12737 } 12738 12739 /* 12740 * Current decision point for kicking the idle load balancer in the presence 12741 * of idle CPUs in the system. 12742 */ 12743 static void nohz_balancer_kick(struct rq *rq) 12744 { 12745 unsigned long now = jiffies; 12746 struct sched_domain_shared *sds; 12747 struct sched_domain *sd; 12748 int nr_busy, i, cpu = rq->cpu; 12749 unsigned int flags = 0; 12750 12751 if (unlikely(rq->idle_balance)) 12752 return; 12753 12754 /* 12755 * We may be recently in ticked or tickless idle mode. At the first 12756 * busy tick after returning from idle, we will update the busy stats. 12757 */ 12758 nohz_balance_exit_idle(rq); 12759 12760 if (READ_ONCE(nohz.has_blocked_load) && 12761 time_after(now, READ_ONCE(nohz.next_blocked))) 12762 flags = NOHZ_STATS_KICK; 12763 12764 /* 12765 * Most of the time system is not 100% busy. i.e nohz.nr_cpus > 0 12766 * Skip the read if time is not due. 12767 * 12768 * If none are in tickless mode, there maybe a narrow window 12769 * (28 jiffies, HZ=1000) where flags maybe set and kick_ilb called. 12770 * But idle load balancing is not done as find_new_ilb fails. 12771 * That's very rare. So read nohz.nr_cpus only if time is due. 12772 */ 12773 if (time_before(now, nohz.next_balance)) 12774 goto out; 12775 12776 /* 12777 * None are in tickless mode and hence no need for NOHZ idle load 12778 * balancing 12779 */ 12780 if (unlikely(cpumask_empty(nohz.idle_cpus_mask))) 12781 return; 12782 12783 if (rq->nr_running >= 2) { 12784 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 12785 goto out; 12786 } 12787 12788 rcu_read_lock(); 12789 12790 sd = rcu_dereference_all(rq->sd); 12791 if (sd) { 12792 /* 12793 * If there's a runnable CFS task and the current CPU has reduced 12794 * capacity, kick the ILB to see if there's a better CPU to run on: 12795 */ 12796 if (rq->cfs.h_nr_runnable >= 1 && check_cpu_capacity(rq, sd)) { 12797 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 12798 goto unlock; 12799 } 12800 } 12801 12802 sd = rcu_dereference_all(per_cpu(sd_asym_packing, cpu)); 12803 if (sd) { 12804 /* 12805 * When ASYM_PACKING; see if there's a more preferred CPU 12806 * currently idle; in which case, kick the ILB to move tasks 12807 * around. 12808 * 12809 * When balancing between cores, all the SMT siblings of the 12810 * preferred CPU must be idle. 12811 */ 12812 for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) { 12813 if (sched_asym(sd, i, cpu)) { 12814 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 12815 goto unlock; 12816 } 12817 } 12818 } 12819 12820 sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, cpu)); 12821 if (sd) { 12822 /* 12823 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU 12824 * to run the misfit task on. 12825 */ 12826 if (check_misfit_status(rq)) { 12827 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 12828 goto unlock; 12829 } 12830 12831 /* 12832 * For asymmetric systems, we do not want to nicely balance 12833 * cache use, instead we want to embrace asymmetry and only 12834 * ensure tasks have enough CPU capacity. 12835 * 12836 * Skip the LLC logic because it's not relevant in that case. 12837 */ 12838 goto unlock; 12839 } 12840 12841 sds = rcu_dereference_all(per_cpu(sd_llc_shared, cpu)); 12842 if (sds) { 12843 /* 12844 * If there is an imbalance between LLC domains (IOW we could 12845 * increase the overall cache utilization), we need a less-loaded LLC 12846 * domain to pull some load from. Likewise, we may need to spread 12847 * load within the current LLC domain (e.g. packed SMT cores but 12848 * other CPUs are idle). We can't really know from here how busy 12849 * the others are - so just get a NOHZ balance going if it looks 12850 * like this LLC domain has tasks we could move. 12851 */ 12852 nr_busy = atomic_read(&sds->nr_busy_cpus); 12853 if (nr_busy > 1) { 12854 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 12855 goto unlock; 12856 } 12857 } 12858 unlock: 12859 rcu_read_unlock(); 12860 out: 12861 if (READ_ONCE(nohz.needs_update)) 12862 flags |= NOHZ_NEXT_KICK; 12863 12864 if (flags) 12865 kick_ilb(flags); 12866 } 12867 12868 static void set_cpu_sd_state_busy(int cpu) 12869 { 12870 struct sched_domain *sd; 12871 12872 rcu_read_lock(); 12873 sd = rcu_dereference_all(per_cpu(sd_llc, cpu)); 12874 12875 if (!sd || !sd->nohz_idle) 12876 goto unlock; 12877 sd->nohz_idle = 0; 12878 12879 atomic_inc(&sd->shared->nr_busy_cpus); 12880 unlock: 12881 rcu_read_unlock(); 12882 } 12883 12884 void nohz_balance_exit_idle(struct rq *rq) 12885 { 12886 WARN_ON_ONCE(rq != this_rq()); 12887 12888 if (likely(!rq->nohz_tick_stopped)) 12889 return; 12890 12891 rq->nohz_tick_stopped = 0; 12892 cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask); 12893 12894 set_cpu_sd_state_busy(rq->cpu); 12895 } 12896 12897 static void set_cpu_sd_state_idle(int cpu) 12898 { 12899 struct sched_domain *sd; 12900 12901 rcu_read_lock(); 12902 sd = rcu_dereference_all(per_cpu(sd_llc, cpu)); 12903 12904 if (!sd || sd->nohz_idle) 12905 goto unlock; 12906 sd->nohz_idle = 1; 12907 12908 atomic_dec(&sd->shared->nr_busy_cpus); 12909 unlock: 12910 rcu_read_unlock(); 12911 } 12912 12913 /* 12914 * This routine will record that the CPU is going idle with tick stopped. 12915 * This info will be used in performing idle load balancing in the future. 12916 */ 12917 void nohz_balance_enter_idle(int cpu) 12918 { 12919 struct rq *rq = cpu_rq(cpu); 12920 12921 WARN_ON_ONCE(cpu != smp_processor_id()); 12922 12923 /* If this CPU is going down, then nothing needs to be done: */ 12924 if (!cpu_active(cpu)) 12925 return; 12926 12927 /* 12928 * Can be set safely without rq->lock held 12929 * If a clear happens, it will have evaluated last additions because 12930 * rq->lock is held during the check and the clear 12931 */ 12932 rq->has_blocked_load = 1; 12933 12934 /* 12935 * The tick is still stopped but load could have been added in the 12936 * meantime. We set the nohz.has_blocked_load flag to trig a check of the 12937 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear 12938 * of nohz.has_blocked_load can only happen after checking the new load 12939 */ 12940 if (rq->nohz_tick_stopped) 12941 goto out; 12942 12943 /* If we're a completely isolated CPU, we don't play: */ 12944 if (on_null_domain(rq)) 12945 return; 12946 12947 rq->nohz_tick_stopped = 1; 12948 12949 cpumask_set_cpu(cpu, nohz.idle_cpus_mask); 12950 12951 /* 12952 * Ensures that if nohz_idle_balance() fails to observe our 12953 * @idle_cpus_mask store, it must observe the @has_blocked_load 12954 * and @needs_update stores. 12955 */ 12956 smp_mb__after_atomic(); 12957 12958 set_cpu_sd_state_idle(cpu); 12959 12960 WRITE_ONCE(nohz.needs_update, 1); 12961 out: 12962 /* 12963 * Each time a cpu enter idle, we assume that it has blocked load and 12964 * enable the periodic update of the load of idle CPUs 12965 */ 12966 WRITE_ONCE(nohz.has_blocked_load, 1); 12967 } 12968 12969 static bool update_nohz_stats(struct rq *rq) 12970 { 12971 unsigned int cpu = rq->cpu; 12972 12973 if (!rq->has_blocked_load) 12974 return false; 12975 12976 if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask)) 12977 return false; 12978 12979 if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick))) 12980 return true; 12981 12982 sched_balance_update_blocked_averages(cpu); 12983 12984 return rq->has_blocked_load; 12985 } 12986 12987 /* 12988 * Internal function that runs load balance for all idle CPUs. The load balance 12989 * can be a simple update of blocked load or a complete load balance with 12990 * tasks movement depending of flags. 12991 */ 12992 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags) 12993 { 12994 /* Earliest time when we have to do rebalance again */ 12995 unsigned long now = jiffies; 12996 unsigned long next_balance = now + 60*HZ; 12997 bool has_blocked_load = false; 12998 int update_next_balance = 0; 12999 int this_cpu = this_rq->cpu; 13000 int balance_cpu; 13001 struct rq *rq; 13002 13003 WARN_ON_ONCE((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK); 13004 13005 /* 13006 * We assume there will be no idle load after this update and clear 13007 * the has_blocked_load flag. If a cpu enters idle in the mean time, it will 13008 * set the has_blocked_load flag and trigger another update of idle load. 13009 * Because a cpu that becomes idle, is added to idle_cpus_mask before 13010 * setting the flag, we are sure to not clear the state and not 13011 * check the load of an idle cpu. 13012 * 13013 * Same applies to idle_cpus_mask vs needs_update. 13014 */ 13015 if (flags & NOHZ_STATS_KICK) 13016 WRITE_ONCE(nohz.has_blocked_load, 0); 13017 if (flags & NOHZ_NEXT_KICK) 13018 WRITE_ONCE(nohz.needs_update, 0); 13019 13020 /* 13021 * Ensures that if we miss the CPU, we must see the has_blocked_load 13022 * store from nohz_balance_enter_idle(). 13023 */ 13024 smp_mb(); 13025 13026 /* 13027 * Start with the next CPU after this_cpu so we will end with this_cpu and let a 13028 * chance for other idle cpu to pull load. 13029 */ 13030 for_each_cpu_wrap(balance_cpu, nohz.idle_cpus_mask, this_cpu+1) { 13031 if (!idle_cpu(balance_cpu)) 13032 continue; 13033 13034 /* 13035 * If this CPU gets work to do, stop the load balancing 13036 * work being done for other CPUs. Next load 13037 * balancing owner will pick it up. 13038 */ 13039 if (!idle_cpu(this_cpu) && need_resched()) { 13040 if (flags & NOHZ_STATS_KICK) 13041 has_blocked_load = true; 13042 if (flags & NOHZ_NEXT_KICK) 13043 WRITE_ONCE(nohz.needs_update, 1); 13044 goto abort; 13045 } 13046 13047 rq = cpu_rq(balance_cpu); 13048 13049 if (flags & NOHZ_STATS_KICK) 13050 has_blocked_load |= update_nohz_stats(rq); 13051 13052 /* 13053 * If time for next balance is due, 13054 * do the balance. 13055 */ 13056 if (time_after_eq(jiffies, rq->next_balance)) { 13057 struct rq_flags rf; 13058 13059 rq_lock_irqsave(rq, &rf); 13060 update_rq_clock(rq); 13061 rq_unlock_irqrestore(rq, &rf); 13062 13063 if (flags & NOHZ_BALANCE_KICK) 13064 sched_balance_domains(rq, CPU_IDLE); 13065 } 13066 13067 if (time_after(next_balance, rq->next_balance)) { 13068 next_balance = rq->next_balance; 13069 update_next_balance = 1; 13070 } 13071 } 13072 13073 /* 13074 * next_balance will be updated only when there is a need. 13075 * When the CPU is attached to null domain for ex, it will not be 13076 * updated. 13077 */ 13078 if (likely(update_next_balance)) 13079 nohz.next_balance = next_balance; 13080 13081 if (flags & NOHZ_STATS_KICK) 13082 WRITE_ONCE(nohz.next_blocked, 13083 now + msecs_to_jiffies(LOAD_AVG_PERIOD)); 13084 13085 abort: 13086 /* There is still blocked load, enable periodic update */ 13087 if (has_blocked_load) 13088 WRITE_ONCE(nohz.has_blocked_load, 1); 13089 } 13090 13091 /* 13092 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the 13093 * rebalancing for all the CPUs for whom scheduler ticks are stopped. 13094 */ 13095 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) 13096 { 13097 unsigned int flags = this_rq->nohz_idle_balance; 13098 13099 if (!flags) 13100 return false; 13101 13102 this_rq->nohz_idle_balance = 0; 13103 13104 if (idle != CPU_IDLE) 13105 return false; 13106 13107 _nohz_idle_balance(this_rq, flags); 13108 13109 return true; 13110 } 13111 13112 /* 13113 * Check if we need to directly run the ILB for updating blocked load before 13114 * entering idle state. Here we run ILB directly without issuing IPIs. 13115 * 13116 * Note that when this function is called, the tick may not yet be stopped on 13117 * this CPU yet. nohz.idle_cpus_mask is updated only when tick is stopped and 13118 * cleared on the next busy tick. In other words, nohz.idle_cpus_mask updates 13119 * don't align with CPUs enter/exit idle to avoid bottlenecks due to high idle 13120 * entry/exit rate (usec). So it is possible that _nohz_idle_balance() is 13121 * called from this function on (this) CPU that's not yet in the mask. That's 13122 * OK because the goal of nohz_run_idle_balance() is to run ILB only for 13123 * updating the blocked load of already idle CPUs without waking up one of 13124 * those idle CPUs and outside the preempt disable / IRQ off phase of the local 13125 * cpu about to enter idle, because it can take a long time. 13126 */ 13127 void nohz_run_idle_balance(int cpu) 13128 { 13129 unsigned int flags; 13130 13131 flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu)); 13132 13133 /* 13134 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen 13135 * (i.e. NOHZ_STATS_KICK set) and will do the same. 13136 */ 13137 if ((flags == NOHZ_NEWILB_KICK) && !need_resched()) 13138 _nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK); 13139 } 13140 13141 static void nohz_newidle_balance(struct rq *this_rq) 13142 { 13143 int this_cpu = this_rq->cpu; 13144 13145 /* Will wake up very soon. No time for doing anything else*/ 13146 if (this_rq->avg_idle < sysctl_sched_migration_cost) 13147 return; 13148 13149 /* Don't need to update blocked load of idle CPUs*/ 13150 if (!READ_ONCE(nohz.has_blocked_load) || 13151 time_before(jiffies, READ_ONCE(nohz.next_blocked))) 13152 return; 13153 13154 /* 13155 * Set the need to trigger ILB in order to update blocked load 13156 * before entering idle state. 13157 */ 13158 atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu)); 13159 } 13160 13161 #else /* !CONFIG_NO_HZ_COMMON: */ 13162 static inline void nohz_balancer_kick(struct rq *rq) { } 13163 13164 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) 13165 { 13166 return false; 13167 } 13168 13169 static inline void nohz_newidle_balance(struct rq *this_rq) { } 13170 #endif /* !CONFIG_NO_HZ_COMMON */ 13171 13172 /* 13173 * sched_balance_newidle is called by schedule() if this_cpu is about to become 13174 * idle. Attempts to pull tasks from other CPUs. 13175 * 13176 * Returns: 13177 * < 0 - we released the lock and there are !fair tasks present 13178 * 0 - failed, no new tasks 13179 * > 0 - success, new (fair) tasks present 13180 */ 13181 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf) 13182 __must_hold(__rq_lockp(this_rq)) 13183 { 13184 unsigned long next_balance = jiffies + HZ; 13185 int this_cpu = this_rq->cpu; 13186 int continue_balancing = 1; 13187 u64 t0, t1, curr_cost = 0; 13188 struct sched_domain *sd; 13189 int pulled_task = 0; 13190 13191 update_misfit_status(NULL, this_rq); 13192 13193 /* 13194 * There is a task waiting to run. No need to search for one. 13195 * Return 0; the task will be enqueued when switching to idle. 13196 */ 13197 if (this_rq->ttwu_pending) 13198 return 0; 13199 13200 /* 13201 * We must set idle_stamp _before_ calling sched_balance_rq() 13202 * for CPU_NEWLY_IDLE, such that we measure the this duration 13203 * as idle time. 13204 */ 13205 this_rq->idle_stamp = rq_clock(this_rq); 13206 13207 /* 13208 * Do not pull tasks towards !active CPUs... 13209 */ 13210 if (!cpu_active(this_cpu)) 13211 return 0; 13212 13213 /* 13214 * This is OK, because current is on_cpu, which avoids it being picked 13215 * for load-balance and preemption/IRQs are still disabled avoiding 13216 * further scheduler activity on it and we're being very careful to 13217 * re-start the picking loop. 13218 */ 13219 rq_unpin_lock(this_rq, rf); 13220 13221 sd = rcu_dereference_sched_domain(this_rq->sd); 13222 if (!sd) 13223 goto out; 13224 13225 if (!get_rd_overloaded(this_rq->rd) || 13226 this_rq->avg_idle < sd->max_newidle_lb_cost) { 13227 13228 update_next_balance(sd, &next_balance); 13229 goto out; 13230 } 13231 13232 /* 13233 * Include sched_balance_update_blocked_averages() in the cost 13234 * calculation because it can be quite costly -- this ensures we skip 13235 * it when avg_idle gets to be very low. 13236 */ 13237 t0 = sched_clock_cpu(this_cpu); 13238 __sched_balance_update_blocked_averages(this_rq); 13239 13240 rq_modified_begin(this_rq, &fair_sched_class); 13241 raw_spin_rq_unlock(this_rq); 13242 13243 for_each_domain(this_cpu, sd) { 13244 u64 domain_cost; 13245 13246 update_next_balance(sd, &next_balance); 13247 13248 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) 13249 break; 13250 13251 if (sd->flags & SD_BALANCE_NEWIDLE) { 13252 unsigned int weight = 1; 13253 13254 if (sched_feat(NI_RANDOM) && sd->newidle_ratio < 1024) { 13255 /* 13256 * Throw a 1k sided dice; and only run 13257 * newidle_balance according to the success 13258 * rate. 13259 */ 13260 u32 d1k = sched_rng() % 1024; 13261 weight = 1 + sd->newidle_ratio; 13262 if (d1k > weight) { 13263 update_newidle_stats(sd, 0); 13264 continue; 13265 } 13266 weight = (1024 + weight/2) / weight; 13267 } 13268 13269 pulled_task = sched_balance_rq(this_cpu, this_rq, 13270 sd, CPU_NEWLY_IDLE, 13271 &continue_balancing); 13272 13273 t1 = sched_clock_cpu(this_cpu); 13274 domain_cost = t1 - t0; 13275 curr_cost += domain_cost; 13276 t0 = t1; 13277 13278 /* 13279 * Track max cost of a domain to make sure to not delay the 13280 * next wakeup on the CPU. 13281 */ 13282 update_newidle_cost(sd, domain_cost, weight * !!pulled_task); 13283 } 13284 13285 /* 13286 * Stop searching for tasks to pull if there are 13287 * now runnable tasks on this rq. 13288 */ 13289 if (pulled_task || !continue_balancing) 13290 break; 13291 } 13292 13293 raw_spin_rq_lock(this_rq); 13294 13295 if (curr_cost > this_rq->max_idle_balance_cost) 13296 this_rq->max_idle_balance_cost = curr_cost; 13297 13298 /* 13299 * While browsing the domains, we released the rq lock, a task could 13300 * have been enqueued in the meantime. Since we're not going idle, 13301 * pretend we pulled a task. 13302 */ 13303 if (this_rq->cfs.h_nr_queued && !pulled_task) 13304 pulled_task = 1; 13305 13306 /* If a higher prio class was modified, restart the pick */ 13307 if (rq_modified_above(this_rq, &fair_sched_class)) 13308 pulled_task = -1; 13309 13310 out: 13311 /* Move the next balance forward */ 13312 if (time_after(this_rq->next_balance, next_balance)) 13313 this_rq->next_balance = next_balance; 13314 13315 if (pulled_task) 13316 this_rq->idle_stamp = 0; 13317 else 13318 nohz_newidle_balance(this_rq); 13319 13320 rq_repin_lock(this_rq, rf); 13321 13322 return pulled_task; 13323 } 13324 13325 /* 13326 * This softirq handler is triggered via SCHED_SOFTIRQ from two places: 13327 * 13328 * - directly from the local sched_tick() for periodic load balancing 13329 * 13330 * - indirectly from a remote sched_tick() for NOHZ idle balancing 13331 * through the SMP cross-call nohz_csd_func() 13332 */ 13333 static __latent_entropy void sched_balance_softirq(void) 13334 { 13335 struct rq *this_rq = this_rq(); 13336 enum cpu_idle_type idle = this_rq->idle_balance; 13337 /* 13338 * If this CPU has a pending NOHZ_BALANCE_KICK, then do the 13339 * balancing on behalf of the other idle CPUs whose ticks are 13340 * stopped. Do nohz_idle_balance *before* sched_balance_domains to 13341 * give the idle CPUs a chance to load balance. Else we may 13342 * load balance only within the local sched_domain hierarchy 13343 * and abort nohz_idle_balance altogether if we pull some load. 13344 */ 13345 if (nohz_idle_balance(this_rq, idle)) 13346 return; 13347 13348 /* normal load balance */ 13349 sched_balance_update_blocked_averages(this_rq->cpu); 13350 sched_balance_domains(this_rq, idle); 13351 } 13352 13353 /* 13354 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing. 13355 */ 13356 void sched_balance_trigger(struct rq *rq) 13357 { 13358 /* 13359 * Don't need to rebalance while attached to NULL domain or 13360 * runqueue CPU is not active 13361 */ 13362 if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq)))) 13363 return; 13364 13365 if (time_after_eq(jiffies, rq->next_balance)) 13366 raise_softirq(SCHED_SOFTIRQ); 13367 13368 nohz_balancer_kick(rq); 13369 } 13370 13371 static void rq_online_fair(struct rq *rq) 13372 { 13373 update_sysctl(); 13374 13375 update_runtime_enabled(rq); 13376 } 13377 13378 static void rq_offline_fair(struct rq *rq) 13379 { 13380 update_sysctl(); 13381 13382 /* Ensure any throttled groups are reachable by pick_next_task */ 13383 unthrottle_offline_cfs_rqs(rq); 13384 13385 /* Ensure that we remove rq contribution to group share: */ 13386 clear_tg_offline_cfs_rqs(rq); 13387 } 13388 13389 #ifdef CONFIG_SCHED_CORE 13390 static inline bool 13391 __entity_slice_used(struct sched_entity *se, int min_nr_tasks) 13392 { 13393 u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime; 13394 u64 slice = se->slice; 13395 13396 return (rtime * min_nr_tasks > slice); 13397 } 13398 13399 #define MIN_NR_TASKS_DURING_FORCEIDLE 2 13400 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) 13401 { 13402 if (!sched_core_enabled(rq)) 13403 return; 13404 13405 /* 13406 * If runqueue has only one task which used up its slice and 13407 * if the sibling is forced idle, then trigger schedule to 13408 * give forced idle task a chance. 13409 * 13410 * sched_slice() considers only this active rq and it gets the 13411 * whole slice. But during force idle, we have siblings acting 13412 * like a single runqueue and hence we need to consider runnable 13413 * tasks on this CPU and the forced idle CPU. Ideally, we should 13414 * go through the forced idle rq, but that would be a perf hit. 13415 * We can assume that the forced idle CPU has at least 13416 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check 13417 * if we need to give up the CPU. 13418 */ 13419 if (rq->core->core_forceidle_count && rq->cfs.nr_queued == 1 && 13420 __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE)) 13421 resched_curr(rq); 13422 } 13423 13424 /* 13425 * Consider any infeasible weight scenario. Take for instance two tasks, 13426 * each bound to their respective sibling, one with weight 1 and one with 13427 * weight 2. Then the lower weight task will run ahead of the higher weight 13428 * task without bound. 13429 * 13430 * This utterly destroys the concept of a shared time base. 13431 * 13432 * Remember; all this is about a proportionally fair scheduling, where each 13433 * tasks receives: 13434 * 13435 * w_i 13436 * dt_i = ---------- dt (1) 13437 * \Sum_j w_j 13438 * 13439 * which we do by tracking a virtual time, s_i: 13440 * 13441 * 1 13442 * s_i = --- d[t]_i (2) 13443 * w_i 13444 * 13445 * Where d[t] is a delta of discrete time, while dt is an infinitesimal. 13446 * The immediate corollary is that the ideal schedule S, where (2) to use 13447 * an infinitesimal delta, is: 13448 * 13449 * 1 13450 * S = ---------- dt (3) 13451 * \Sum_i w_i 13452 * 13453 * From which we can define the lag, or deviation from the ideal, as: 13454 * 13455 * lag(i) = S - s_i (4) 13456 * 13457 * And since the one and only purpose is to approximate S, we get that: 13458 * 13459 * \Sum_i w_i lag(i) := 0 (5) 13460 * 13461 * If this were not so, we no longer converge to S, and we can no longer 13462 * claim our scheduler has any of the properties we derive from S. This is 13463 * exactly what you did above, you broke it! 13464 * 13465 * 13466 * Let's continue for a while though; to see if there is anything useful to 13467 * be learned. We can combine (1)-(3) or (4)-(5) and express S in s_i: 13468 * 13469 * \Sum_i w_i s_i 13470 * S = -------------- (6) 13471 * \Sum_i w_i 13472 * 13473 * Which gives us a way to compute S, given our s_i. Now, if you've read 13474 * our code, you know that we do not in fact do this, the reason for this 13475 * is two-fold. Firstly, computing S in that way requires a 64bit division 13476 * for every time we'd use it (see 12), and secondly, this only describes 13477 * the steady-state, it doesn't handle dynamics. 13478 * 13479 * Anyway, in (6): s_i -> x + (s_i - x), to get: 13480 * 13481 * \Sum_i w_i (s_i - x) 13482 * S - x = -------------------- (7) 13483 * \Sum_i w_i 13484 * 13485 * Which shows that S and s_i transform alike (which makes perfect sense 13486 * given that S is basically the (weighted) average of s_i). 13487 * 13488 * So the thing to remember is that the above is strictly UP. It is 13489 * possible to generalize to multiple runqueues -- however it gets really 13490 * yuck when you have to add affinity support, as illustrated by our very 13491 * first counter-example. 13492 * 13493 * Luckily I think we can avoid needing a full multi-queue variant for 13494 * core-scheduling (or load-balancing). The crucial observation is that we 13495 * only actually need this comparison in the presence of forced-idle; only 13496 * then do we need to tell if the stalled rq has higher priority over the 13497 * other. 13498 * 13499 * [XXX assumes SMT2; better consider the more general case, I suspect 13500 * it'll work out because our comparison is always between 2 rqs and the 13501 * answer is only interesting if one of them is forced-idle] 13502 * 13503 * And (under assumption of SMT2) when there is forced-idle, there is only 13504 * a single queue, so everything works like normal. 13505 * 13506 * Let, for our runqueue 'k': 13507 * 13508 * T_k = \Sum_i w_i s_i 13509 * W_k = \Sum_i w_i ; for all i of k (8) 13510 * 13511 * Then we can write (6) like: 13512 * 13513 * T_k 13514 * S_k = --- (9) 13515 * W_k 13516 * 13517 * From which immediately follows that: 13518 * 13519 * T_k + T_l 13520 * S_k+l = --------- (10) 13521 * W_k + W_l 13522 * 13523 * On which we can define a combined lag: 13524 * 13525 * lag_k+l(i) := S_k+l - s_i (11) 13526 * 13527 * And that gives us the tools to compare tasks across a combined runqueue. 13528 * 13529 * 13530 * Combined this gives the following: 13531 * 13532 * a) when a runqueue enters force-idle, sync it against it's sibling rq(s) 13533 * using (7); this only requires storing single 'time'-stamps. 13534 * 13535 * b) when comparing tasks between 2 runqueues of which one is forced-idle, 13536 * compare the combined lag, per (11). 13537 * 13538 * Now, of course cgroups (I so hate them) make this more interesting in 13539 * that a) seems to suggest we need to iterate all cgroup on a CPU at such 13540 * boundaries, but I think we can avoid that. The force-idle is for the 13541 * whole CPU, all it's rqs. So we can mark it in the root and lazily 13542 * propagate downward on demand. 13543 */ 13544 13545 /* 13546 * So this sync is basically a relative reset of S to 0. 13547 * 13548 * So with 2 queues, when one goes idle, we drop them both to 0 and one 13549 * then increases due to not being idle, and the idle one builds up lag to 13550 * get re-elected. So far so simple, right? 13551 * 13552 * When there's 3, we can have the situation where 2 run and one is idle, 13553 * we sync to 0 and let the idle one build up lag to get re-election. Now 13554 * suppose another one also drops idle. At this point dropping all to 0 13555 * again would destroy the built-up lag from the queue that was already 13556 * idle, not good. 13557 * 13558 * So instead of syncing everything, we can: 13559 * 13560 * less := !((s64)(s_a - s_b) <= 0) 13561 * 13562 * (v_a - S_a) - (v_b - S_b) == v_a - v_b - S_a + S_b 13563 * == v_a - (v_b - S_a + S_b) 13564 * 13565 * IOW, we can recast the (lag) comparison to a one-sided difference. 13566 * So if then, instead of syncing the whole queue, sync the idle queue 13567 * against the active queue with S_a + S_b at the point where we sync. 13568 * 13569 * (XXX consider the implication of living in a cyclic group: N / 2^n N) 13570 * 13571 * This gives us means of syncing single queues against the active queue, 13572 * and for already idle queues to preserve their build-up lag. 13573 * 13574 * Of course, then we get the situation where there's 2 active and one 13575 * going idle, who do we pick to sync against? Theory would have us sync 13576 * against the combined S, but as we've already demonstrated, there is no 13577 * such thing in infeasible weight scenarios. 13578 * 13579 * One thing I've considered; and this is where that core_active rudiment 13580 * came from, is having active queues sync up between themselves after 13581 * every tick. This limits the observed divergence due to the work 13582 * conservancy. 13583 * 13584 * On top of that, we can improve upon things by employing (10) here. 13585 */ 13586 13587 /* 13588 * se_fi_update - Update the cfs_rq->zero_vruntime_fi in a CFS hierarchy if needed. 13589 */ 13590 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq, 13591 bool forceidle) 13592 { 13593 for_each_sched_entity(se) { 13594 struct cfs_rq *cfs_rq = cfs_rq_of(se); 13595 13596 if (forceidle) { 13597 if (cfs_rq->forceidle_seq == fi_seq) 13598 break; 13599 cfs_rq->forceidle_seq = fi_seq; 13600 } 13601 13602 cfs_rq->zero_vruntime_fi = cfs_rq->zero_vruntime; 13603 } 13604 } 13605 13606 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi) 13607 { 13608 struct sched_entity *se = &p->se; 13609 13610 if (p->sched_class != &fair_sched_class) 13611 return; 13612 13613 se_fi_update(se, rq->core->core_forceidle_seq, in_fi); 13614 } 13615 13616 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b, 13617 bool in_fi) 13618 { 13619 struct rq *rq = task_rq(a); 13620 const struct sched_entity *sea = &a->se; 13621 const struct sched_entity *seb = &b->se; 13622 struct cfs_rq *cfs_rqa; 13623 struct cfs_rq *cfs_rqb; 13624 s64 delta; 13625 13626 WARN_ON_ONCE(task_rq(b)->core != rq->core); 13627 13628 #ifdef CONFIG_FAIR_GROUP_SCHED 13629 /* 13630 * Find an se in the hierarchy for tasks a and b, such that the se's 13631 * are immediate siblings. 13632 */ 13633 while (sea->cfs_rq->tg != seb->cfs_rq->tg) { 13634 int sea_depth = sea->depth; 13635 int seb_depth = seb->depth; 13636 13637 if (sea_depth >= seb_depth) 13638 sea = parent_entity(sea); 13639 if (sea_depth <= seb_depth) 13640 seb = parent_entity(seb); 13641 } 13642 13643 se_fi_update(sea, rq->core->core_forceidle_seq, in_fi); 13644 se_fi_update(seb, rq->core->core_forceidle_seq, in_fi); 13645 13646 cfs_rqa = sea->cfs_rq; 13647 cfs_rqb = seb->cfs_rq; 13648 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 13649 cfs_rqa = &task_rq(a)->cfs; 13650 cfs_rqb = &task_rq(b)->cfs; 13651 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 13652 13653 /* 13654 * Find delta after normalizing se's vruntime with its cfs_rq's 13655 * zero_vruntime_fi, which would have been updated in prior calls 13656 * to se_fi_update(). 13657 */ 13658 delta = vruntime_op(sea->vruntime, "-", seb->vruntime) + 13659 vruntime_op(cfs_rqb->zero_vruntime_fi, "-", cfs_rqa->zero_vruntime_fi); 13660 13661 return delta > 0; 13662 } 13663 13664 static int task_is_throttled_fair(struct task_struct *p, int cpu) 13665 { 13666 struct cfs_rq *cfs_rq; 13667 13668 #ifdef CONFIG_FAIR_GROUP_SCHED 13669 cfs_rq = task_group(p)->cfs_rq[cpu]; 13670 #else 13671 cfs_rq = &cpu_rq(cpu)->cfs; 13672 #endif 13673 return throttled_hierarchy(cfs_rq); 13674 } 13675 #else /* !CONFIG_SCHED_CORE: */ 13676 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {} 13677 #endif /* !CONFIG_SCHED_CORE */ 13678 13679 /* 13680 * scheduler tick hitting a task of our scheduling class. 13681 * 13682 * NOTE: This function can be called remotely by the tick offload that 13683 * goes along full dynticks. Therefore no local assumption can be made 13684 * and everything must be accessed through the @rq and @curr passed in 13685 * parameters. 13686 */ 13687 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued) 13688 { 13689 struct cfs_rq *cfs_rq; 13690 struct sched_entity *se = &curr->se; 13691 13692 for_each_sched_entity(se) { 13693 cfs_rq = cfs_rq_of(se); 13694 entity_tick(cfs_rq, se, queued); 13695 } 13696 13697 if (queued) 13698 return; 13699 13700 if (static_branch_unlikely(&sched_numa_balancing)) 13701 task_tick_numa(rq, curr); 13702 13703 update_misfit_status(curr, rq); 13704 check_update_overutilized_status(task_rq(curr)); 13705 13706 task_tick_core(rq, curr); 13707 } 13708 13709 /* 13710 * called on fork with the child task as argument from the parent's context 13711 * - child not yet on the tasklist 13712 * - preemption disabled 13713 */ 13714 static void task_fork_fair(struct task_struct *p) 13715 { 13716 set_task_max_allowed_capacity(p); 13717 } 13718 13719 /* 13720 * Priority of the task has changed. Check to see if we preempt 13721 * the current task. 13722 */ 13723 static void 13724 prio_changed_fair(struct rq *rq, struct task_struct *p, u64 oldprio) 13725 { 13726 if (!task_on_rq_queued(p)) 13727 return; 13728 13729 if (p->prio == oldprio) 13730 return; 13731 13732 if (rq->cfs.nr_queued == 1) 13733 return; 13734 13735 /* 13736 * Reschedule if we are currently running on this runqueue and 13737 * our priority decreased, or if we are not currently running on 13738 * this runqueue and our priority is higher than the current's 13739 */ 13740 if (task_current_donor(rq, p)) { 13741 if (p->prio > oldprio) 13742 resched_curr(rq); 13743 } else { 13744 wakeup_preempt(rq, p, 0); 13745 } 13746 } 13747 13748 #ifdef CONFIG_FAIR_GROUP_SCHED 13749 /* 13750 * Propagate the changes of the sched_entity across the tg tree to make it 13751 * visible to the root 13752 */ 13753 static void propagate_entity_cfs_rq(struct sched_entity *se) 13754 { 13755 struct cfs_rq *cfs_rq = cfs_rq_of(se); 13756 13757 /* 13758 * If a task gets attached to this cfs_rq and before being queued, 13759 * it gets migrated to another CPU due to reasons like affinity 13760 * change, make sure this cfs_rq stays on leaf cfs_rq list to have 13761 * that removed load decayed or it can cause faireness problem. 13762 */ 13763 if (!cfs_rq_pelt_clock_throttled(cfs_rq)) 13764 list_add_leaf_cfs_rq(cfs_rq); 13765 13766 /* Start to propagate at parent */ 13767 se = se->parent; 13768 13769 for_each_sched_entity(se) { 13770 cfs_rq = cfs_rq_of(se); 13771 13772 update_load_avg(cfs_rq, se, UPDATE_TG); 13773 13774 if (!cfs_rq_pelt_clock_throttled(cfs_rq)) 13775 list_add_leaf_cfs_rq(cfs_rq); 13776 } 13777 13778 assert_list_leaf_cfs_rq(rq_of(cfs_rq)); 13779 } 13780 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 13781 static void propagate_entity_cfs_rq(struct sched_entity *se) { } 13782 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 13783 13784 static void detach_entity_cfs_rq(struct sched_entity *se) 13785 { 13786 struct cfs_rq *cfs_rq = cfs_rq_of(se); 13787 13788 /* 13789 * In case the task sched_avg hasn't been attached: 13790 * - A forked task which hasn't been woken up by wake_up_new_task(). 13791 * - A task which has been woken up by try_to_wake_up() but is 13792 * waiting for actually being woken up by sched_ttwu_pending(). 13793 */ 13794 if (!se->avg.last_update_time) 13795 return; 13796 13797 /* Catch up with the cfs_rq and remove our load when we leave */ 13798 update_load_avg(cfs_rq, se, 0); 13799 detach_entity_load_avg(cfs_rq, se); 13800 update_tg_load_avg(cfs_rq); 13801 propagate_entity_cfs_rq(se); 13802 } 13803 13804 static void attach_entity_cfs_rq(struct sched_entity *se) 13805 { 13806 struct cfs_rq *cfs_rq = cfs_rq_of(se); 13807 13808 /* Synchronize entity with its cfs_rq */ 13809 update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD); 13810 attach_entity_load_avg(cfs_rq, se); 13811 update_tg_load_avg(cfs_rq); 13812 propagate_entity_cfs_rq(se); 13813 } 13814 13815 static void detach_task_cfs_rq(struct task_struct *p) 13816 { 13817 struct sched_entity *se = &p->se; 13818 13819 detach_entity_cfs_rq(se); 13820 } 13821 13822 static void attach_task_cfs_rq(struct task_struct *p) 13823 { 13824 struct sched_entity *se = &p->se; 13825 13826 attach_entity_cfs_rq(se); 13827 } 13828 13829 static void switching_from_fair(struct rq *rq, struct task_struct *p) 13830 { 13831 if (p->se.sched_delayed) 13832 dequeue_task(rq, p, DEQUEUE_SLEEP | DEQUEUE_DELAYED | DEQUEUE_NOCLOCK); 13833 } 13834 13835 static void switched_from_fair(struct rq *rq, struct task_struct *p) 13836 { 13837 detach_task_cfs_rq(p); 13838 } 13839 13840 static void switched_to_fair(struct rq *rq, struct task_struct *p) 13841 { 13842 WARN_ON_ONCE(p->se.sched_delayed); 13843 13844 attach_task_cfs_rq(p); 13845 13846 set_task_max_allowed_capacity(p); 13847 13848 if (task_on_rq_queued(p)) { 13849 /* 13850 * We were most likely switched from sched_rt, so 13851 * kick off the schedule if running, otherwise just see 13852 * if we can still preempt the current task. 13853 */ 13854 if (task_current_donor(rq, p)) 13855 resched_curr(rq); 13856 else 13857 wakeup_preempt(rq, p, 0); 13858 } 13859 } 13860 13861 static void __set_next_task_fair(struct rq *rq, struct task_struct *p, bool first) 13862 { 13863 struct sched_entity *se = &p->se; 13864 13865 if (task_on_rq_queued(p)) { 13866 /* 13867 * Move the next running task to the front of the list, so our 13868 * cfs_tasks list becomes MRU one. 13869 */ 13870 list_move(&se->group_node, &rq->cfs_tasks); 13871 } 13872 if (!first) 13873 return; 13874 13875 WARN_ON_ONCE(se->sched_delayed); 13876 13877 if (hrtick_enabled_fair(rq)) 13878 hrtick_start_fair(rq, p); 13879 13880 update_misfit_status(p, rq); 13881 sched_fair_update_stop_tick(rq, p); 13882 } 13883 13884 /* 13885 * Account for a task changing its policy or group. 13886 * 13887 * This routine is mostly called to set cfs_rq->curr field when a task 13888 * migrates between groups/classes. 13889 */ 13890 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first) 13891 { 13892 struct sched_entity *se = &p->se; 13893 13894 for_each_sched_entity(se) { 13895 struct cfs_rq *cfs_rq = cfs_rq_of(se); 13896 13897 set_next_entity(cfs_rq, se, first); 13898 /* ensure bandwidth has been allocated on our new cfs_rq */ 13899 account_cfs_rq_runtime(cfs_rq, 0); 13900 } 13901 13902 __set_next_task_fair(rq, p, first); 13903 } 13904 13905 void init_cfs_rq(struct cfs_rq *cfs_rq) 13906 { 13907 cfs_rq->tasks_timeline = RB_ROOT_CACHED; 13908 cfs_rq->zero_vruntime = (u64)(-(1LL << 20)); 13909 raw_spin_lock_init(&cfs_rq->removed.lock); 13910 } 13911 13912 #ifdef CONFIG_FAIR_GROUP_SCHED 13913 static void task_change_group_fair(struct task_struct *p) 13914 { 13915 /* 13916 * We couldn't detach or attach a forked task which 13917 * hasn't been woken up by wake_up_new_task(). 13918 */ 13919 if (READ_ONCE(p->__state) == TASK_NEW) 13920 return; 13921 13922 detach_task_cfs_rq(p); 13923 13924 /* Tell se's cfs_rq has been changed -- migrated */ 13925 p->se.avg.last_update_time = 0; 13926 set_task_rq(p, task_cpu(p)); 13927 attach_task_cfs_rq(p); 13928 } 13929 13930 void free_fair_sched_group(struct task_group *tg) 13931 { 13932 int i; 13933 13934 for_each_possible_cpu(i) { 13935 if (tg->cfs_rq) 13936 kfree(tg->cfs_rq[i]); 13937 if (tg->se) 13938 kfree(tg->se[i]); 13939 } 13940 13941 kfree(tg->cfs_rq); 13942 kfree(tg->se); 13943 } 13944 13945 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent) 13946 { 13947 struct sched_entity *se; 13948 struct cfs_rq *cfs_rq; 13949 int i; 13950 13951 tg->cfs_rq = kzalloc_objs(cfs_rq, nr_cpu_ids); 13952 if (!tg->cfs_rq) 13953 goto err; 13954 tg->se = kzalloc_objs(se, nr_cpu_ids); 13955 if (!tg->se) 13956 goto err; 13957 13958 tg->shares = NICE_0_LOAD; 13959 13960 init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent)); 13961 13962 for_each_possible_cpu(i) { 13963 cfs_rq = kzalloc_node(sizeof(struct cfs_rq), 13964 GFP_KERNEL, cpu_to_node(i)); 13965 if (!cfs_rq) 13966 goto err; 13967 13968 se = kzalloc_node(sizeof(struct sched_entity_stats), 13969 GFP_KERNEL, cpu_to_node(i)); 13970 if (!se) 13971 goto err_free_rq; 13972 13973 init_cfs_rq(cfs_rq); 13974 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]); 13975 init_entity_runnable_average(se); 13976 } 13977 13978 return 1; 13979 13980 err_free_rq: 13981 kfree(cfs_rq); 13982 err: 13983 return 0; 13984 } 13985 13986 void online_fair_sched_group(struct task_group *tg) 13987 { 13988 struct sched_entity *se; 13989 struct rq_flags rf; 13990 struct rq *rq; 13991 int i; 13992 13993 for_each_possible_cpu(i) { 13994 rq = cpu_rq(i); 13995 se = tg->se[i]; 13996 rq_lock_irq(rq, &rf); 13997 update_rq_clock(rq); 13998 attach_entity_cfs_rq(se); 13999 sync_throttle(tg, i); 14000 rq_unlock_irq(rq, &rf); 14001 } 14002 } 14003 14004 void unregister_fair_sched_group(struct task_group *tg) 14005 { 14006 int cpu; 14007 14008 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg)); 14009 14010 for_each_possible_cpu(cpu) { 14011 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu]; 14012 struct sched_entity *se = tg->se[cpu]; 14013 struct rq *rq = cpu_rq(cpu); 14014 14015 if (se) { 14016 if (se->sched_delayed) { 14017 guard(rq_lock_irqsave)(rq); 14018 if (se->sched_delayed) { 14019 update_rq_clock(rq); 14020 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED); 14021 } 14022 list_del_leaf_cfs_rq(cfs_rq); 14023 } 14024 remove_entity_load_avg(se); 14025 } 14026 14027 /* 14028 * Only empty task groups can be destroyed; so we can speculatively 14029 * check on_list without danger of it being re-added. 14030 */ 14031 if (cfs_rq->on_list) { 14032 guard(rq_lock_irqsave)(rq); 14033 list_del_leaf_cfs_rq(cfs_rq); 14034 } 14035 } 14036 } 14037 14038 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq, 14039 struct sched_entity *se, int cpu, 14040 struct sched_entity *parent) 14041 { 14042 struct rq *rq = cpu_rq(cpu); 14043 14044 cfs_rq->tg = tg; 14045 cfs_rq->rq = rq; 14046 init_cfs_rq_runtime(cfs_rq); 14047 14048 tg->cfs_rq[cpu] = cfs_rq; 14049 tg->se[cpu] = se; 14050 14051 /* se could be NULL for root_task_group */ 14052 if (!se) 14053 return; 14054 14055 if (!parent) { 14056 se->cfs_rq = &rq->cfs; 14057 se->depth = 0; 14058 } else { 14059 se->cfs_rq = parent->my_q; 14060 se->depth = parent->depth + 1; 14061 } 14062 14063 se->my_q = cfs_rq; 14064 /* guarantee group entities always have weight */ 14065 update_load_set(&se->load, NICE_0_LOAD); 14066 se->parent = parent; 14067 } 14068 14069 static DEFINE_MUTEX(shares_mutex); 14070 14071 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares) 14072 { 14073 int i; 14074 14075 lockdep_assert_held(&shares_mutex); 14076 14077 /* 14078 * We can't change the weight of the root cgroup. 14079 */ 14080 if (!tg->se[0]) 14081 return -EINVAL; 14082 14083 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES)); 14084 14085 if (tg->shares == shares) 14086 return 0; 14087 14088 tg->shares = shares; 14089 for_each_possible_cpu(i) { 14090 struct rq *rq = cpu_rq(i); 14091 struct sched_entity *se = tg->se[i]; 14092 struct rq_flags rf; 14093 14094 /* Propagate contribution to hierarchy */ 14095 rq_lock_irqsave(rq, &rf); 14096 update_rq_clock(rq); 14097 for_each_sched_entity(se) { 14098 update_load_avg(cfs_rq_of(se), se, UPDATE_TG); 14099 update_cfs_group(se); 14100 } 14101 rq_unlock_irqrestore(rq, &rf); 14102 } 14103 14104 return 0; 14105 } 14106 14107 int sched_group_set_shares(struct task_group *tg, unsigned long shares) 14108 { 14109 int ret; 14110 14111 mutex_lock(&shares_mutex); 14112 if (tg_is_idle(tg)) 14113 ret = -EINVAL; 14114 else 14115 ret = __sched_group_set_shares(tg, shares); 14116 mutex_unlock(&shares_mutex); 14117 14118 return ret; 14119 } 14120 14121 int sched_group_set_idle(struct task_group *tg, long idle) 14122 { 14123 int i; 14124 14125 if (tg == &root_task_group) 14126 return -EINVAL; 14127 14128 if (idle < 0 || idle > 1) 14129 return -EINVAL; 14130 14131 mutex_lock(&shares_mutex); 14132 14133 if (tg->idle == idle) { 14134 mutex_unlock(&shares_mutex); 14135 return 0; 14136 } 14137 14138 tg->idle = idle; 14139 14140 for_each_possible_cpu(i) { 14141 struct rq *rq = cpu_rq(i); 14142 struct sched_entity *se = tg->se[i]; 14143 struct cfs_rq *grp_cfs_rq = tg->cfs_rq[i]; 14144 bool was_idle = cfs_rq_is_idle(grp_cfs_rq); 14145 long idle_task_delta; 14146 struct rq_flags rf; 14147 14148 rq_lock_irqsave(rq, &rf); 14149 14150 grp_cfs_rq->idle = idle; 14151 if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq))) 14152 goto next_cpu; 14153 14154 idle_task_delta = grp_cfs_rq->h_nr_queued - 14155 grp_cfs_rq->h_nr_idle; 14156 if (!cfs_rq_is_idle(grp_cfs_rq)) 14157 idle_task_delta *= -1; 14158 14159 for_each_sched_entity(se) { 14160 struct cfs_rq *cfs_rq = cfs_rq_of(se); 14161 14162 if (!se->on_rq) 14163 break; 14164 14165 cfs_rq->h_nr_idle += idle_task_delta; 14166 14167 /* Already accounted at parent level and above. */ 14168 if (cfs_rq_is_idle(cfs_rq)) 14169 break; 14170 } 14171 14172 next_cpu: 14173 rq_unlock_irqrestore(rq, &rf); 14174 } 14175 14176 /* Idle groups have minimum weight. */ 14177 if (tg_is_idle(tg)) 14178 __sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO)); 14179 else 14180 __sched_group_set_shares(tg, NICE_0_LOAD); 14181 14182 mutex_unlock(&shares_mutex); 14183 return 0; 14184 } 14185 14186 #endif /* CONFIG_FAIR_GROUP_SCHED */ 14187 14188 14189 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task) 14190 { 14191 struct sched_entity *se = &task->se; 14192 unsigned int rr_interval = 0; 14193 14194 /* 14195 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise 14196 * idle runqueue: 14197 */ 14198 if (rq->cfs.load.weight) 14199 rr_interval = NS_TO_JIFFIES(se->slice); 14200 14201 return rr_interval; 14202 } 14203 14204 /* 14205 * All the scheduling class methods: 14206 */ 14207 DEFINE_SCHED_CLASS(fair) = { 14208 .enqueue_task = enqueue_task_fair, 14209 .dequeue_task = dequeue_task_fair, 14210 .yield_task = yield_task_fair, 14211 .yield_to_task = yield_to_task_fair, 14212 14213 .wakeup_preempt = wakeup_preempt_fair, 14214 14215 .pick_task = pick_task_fair, 14216 .pick_next_task = pick_next_task_fair, 14217 .put_prev_task = put_prev_task_fair, 14218 .set_next_task = set_next_task_fair, 14219 14220 .select_task_rq = select_task_rq_fair, 14221 .migrate_task_rq = migrate_task_rq_fair, 14222 14223 .rq_online = rq_online_fair, 14224 .rq_offline = rq_offline_fair, 14225 14226 .task_dead = task_dead_fair, 14227 .set_cpus_allowed = set_cpus_allowed_fair, 14228 14229 .task_tick = task_tick_fair, 14230 .task_fork = task_fork_fair, 14231 14232 .reweight_task = reweight_task_fair, 14233 .prio_changed = prio_changed_fair, 14234 .switching_from = switching_from_fair, 14235 .switched_from = switched_from_fair, 14236 .switched_to = switched_to_fair, 14237 14238 .get_rr_interval = get_rr_interval_fair, 14239 14240 .update_curr = update_curr_fair, 14241 14242 #ifdef CONFIG_FAIR_GROUP_SCHED 14243 .task_change_group = task_change_group_fair, 14244 #endif 14245 14246 #ifdef CONFIG_SCHED_CORE 14247 .task_is_throttled = task_is_throttled_fair, 14248 #endif 14249 14250 #ifdef CONFIG_UCLAMP_TASK 14251 .uclamp_enabled = 1, 14252 #endif 14253 }; 14254 14255 void print_cfs_stats(struct seq_file *m, int cpu) 14256 { 14257 struct cfs_rq *cfs_rq, *pos; 14258 14259 rcu_read_lock(); 14260 for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos) 14261 print_cfs_rq(m, cpu, cfs_rq); 14262 rcu_read_unlock(); 14263 } 14264 14265 #ifdef CONFIG_NUMA_BALANCING 14266 void show_numa_stats(struct task_struct *p, struct seq_file *m) 14267 { 14268 int node; 14269 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0; 14270 struct numa_group *ng; 14271 14272 rcu_read_lock(); 14273 ng = rcu_dereference_all(p->numa_group); 14274 for_each_online_node(node) { 14275 if (p->numa_faults) { 14276 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)]; 14277 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)]; 14278 } 14279 if (ng) { 14280 gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)]; 14281 gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)]; 14282 } 14283 print_numa_stats(m, node, tsf, tpf, gsf, gpf); 14284 } 14285 rcu_read_unlock(); 14286 } 14287 #endif /* CONFIG_NUMA_BALANCING */ 14288 14289 __init void init_sched_fair_class(void) 14290 { 14291 int i; 14292 14293 for_each_possible_cpu(i) { 14294 zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i)); 14295 zalloc_cpumask_var_node(&per_cpu(select_rq_mask, i), GFP_KERNEL, cpu_to_node(i)); 14296 zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i), 14297 GFP_KERNEL, cpu_to_node(i)); 14298 14299 #ifdef CONFIG_CFS_BANDWIDTH 14300 INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i)); 14301 INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list); 14302 #endif 14303 } 14304 14305 open_softirq(SCHED_SOFTIRQ, sched_balance_softirq); 14306 14307 #ifdef CONFIG_NO_HZ_COMMON 14308 nohz.next_balance = jiffies; 14309 nohz.next_blocked = jiffies; 14310 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT); 14311 #endif 14312 } 14313