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