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