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 #define WMULT_CONST (~0U) 229 #define WMULT_SHIFT 32 230 231 static void __update_inv_weight(struct load_weight *lw) 232 { 233 unsigned long w; 234 235 if (likely(lw->inv_weight)) 236 return; 237 238 w = scale_load_down(lw->weight); 239 240 if (BITS_PER_LONG > 32 && unlikely(w >= WMULT_CONST)) 241 lw->inv_weight = 1; 242 else if (unlikely(!w)) 243 lw->inv_weight = WMULT_CONST; 244 else 245 lw->inv_weight = WMULT_CONST / w; 246 } 247 248 /* 249 * delta_exec * weight / lw.weight 250 * OR 251 * (delta_exec * (weight * lw->inv_weight)) >> WMULT_SHIFT 252 * 253 * Either weight := NICE_0_LOAD and lw \e sched_prio_to_wmult[], in which case 254 * we're guaranteed shift stays positive because inv_weight is guaranteed to 255 * fit 32 bits, and NICE_0_LOAD gives another 10 bits; therefore shift >= 22. 256 * 257 * Or, weight =< lw.weight (because lw.weight is the runqueue weight), thus 258 * weight/lw.weight <= 1, and therefore our shift will also be positive. 259 */ 260 static u64 __calc_delta(u64 delta_exec, unsigned long weight, struct load_weight *lw) 261 { 262 u64 fact = scale_load_down(weight); 263 u32 fact_hi = (u32)(fact >> 32); 264 int shift = WMULT_SHIFT; 265 int fs; 266 267 __update_inv_weight(lw); 268 269 if (unlikely(fact_hi)) { 270 fs = fls(fact_hi); 271 shift -= fs; 272 fact >>= fs; 273 } 274 275 fact = mul_u32_u32(fact, lw->inv_weight); 276 277 fact_hi = (u32)(fact >> 32); 278 if (fact_hi) { 279 fs = fls(fact_hi); 280 shift -= fs; 281 fact >>= fs; 282 } 283 284 return mul_u64_u32_shr(delta_exec, fact, shift); 285 } 286 287 /* 288 * delta /= w 289 */ 290 static inline u64 calc_delta_fair(u64 delta, struct sched_entity *se) 291 { 292 if (unlikely(se->load.weight != NICE_0_LOAD)) 293 delta = __calc_delta(delta, NICE_0_LOAD, &se->load); 294 295 return delta; 296 } 297 298 const struct sched_class fair_sched_class; 299 300 /************************************************************** 301 * CFS operations on generic schedulable entities: 302 */ 303 304 #ifdef CONFIG_FAIR_GROUP_SCHED 305 306 /* Walk up scheduling entities hierarchy */ 307 #define for_each_sched_entity(se) \ 308 for (; se; se = se->parent) 309 310 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq) 311 { 312 struct rq *rq = rq_of(cfs_rq); 313 int cpu = cpu_of(rq); 314 315 if (cfs_rq->on_list) 316 return rq->tmp_alone_branch == &rq->leaf_cfs_rq_list; 317 318 cfs_rq->on_list = 1; 319 320 /* 321 * Ensure we either appear before our parent (if already 322 * enqueued) or force our parent to appear after us when it is 323 * enqueued. The fact that we always enqueue bottom-up 324 * reduces this to two cases and a special case for the root 325 * cfs_rq. Furthermore, it also means that we will always reset 326 * tmp_alone_branch either when the branch is connected 327 * to a tree or when we reach the top of the tree 328 */ 329 if (cfs_rq->tg->parent && 330 cfs_rq->tg->parent->cfs_rq[cpu]->on_list) { 331 /* 332 * If parent is already on the list, we add the child 333 * just before. Thanks to circular linked property of 334 * the list, this means to put the child at the tail 335 * of the list that starts by parent. 336 */ 337 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list, 338 &(cfs_rq->tg->parent->cfs_rq[cpu]->leaf_cfs_rq_list)); 339 /* 340 * The branch is now connected to its tree so we can 341 * reset tmp_alone_branch to the beginning of the 342 * list. 343 */ 344 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list; 345 return true; 346 } 347 348 if (!cfs_rq->tg->parent) { 349 /* 350 * cfs rq without parent should be put 351 * at the tail of the list. 352 */ 353 list_add_tail_rcu(&cfs_rq->leaf_cfs_rq_list, 354 &rq->leaf_cfs_rq_list); 355 /* 356 * We have reach the top of a tree so we can reset 357 * tmp_alone_branch to the beginning of the list. 358 */ 359 rq->tmp_alone_branch = &rq->leaf_cfs_rq_list; 360 return true; 361 } 362 363 /* 364 * The parent has not already been added so we want to 365 * make sure that it will be put after us. 366 * tmp_alone_branch points to the begin of the branch 367 * where we will add parent. 368 */ 369 list_add_rcu(&cfs_rq->leaf_cfs_rq_list, rq->tmp_alone_branch); 370 /* 371 * update tmp_alone_branch to points to the new begin 372 * of the branch 373 */ 374 rq->tmp_alone_branch = &cfs_rq->leaf_cfs_rq_list; 375 return false; 376 } 377 378 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq) 379 { 380 if (cfs_rq->on_list) { 381 struct rq *rq = rq_of(cfs_rq); 382 383 /* 384 * With cfs_rq being unthrottled/throttled during an enqueue, 385 * it can happen the tmp_alone_branch points to the leaf that 386 * we finally want to delete. In this case, tmp_alone_branch moves 387 * to the prev element but it will point to rq->leaf_cfs_rq_list 388 * at the end of the enqueue. 389 */ 390 if (rq->tmp_alone_branch == &cfs_rq->leaf_cfs_rq_list) 391 rq->tmp_alone_branch = cfs_rq->leaf_cfs_rq_list.prev; 392 393 list_del_rcu(&cfs_rq->leaf_cfs_rq_list); 394 cfs_rq->on_list = 0; 395 } 396 } 397 398 static inline void assert_list_leaf_cfs_rq(struct rq *rq) 399 { 400 WARN_ON_ONCE(rq->tmp_alone_branch != &rq->leaf_cfs_rq_list); 401 } 402 403 /* Iterate through all leaf cfs_rq's on a runqueue */ 404 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \ 405 list_for_each_entry_safe(cfs_rq, pos, &rq->leaf_cfs_rq_list, \ 406 leaf_cfs_rq_list) 407 408 /* Do the two (enqueued) entities belong to the same group ? */ 409 static inline struct cfs_rq * 410 is_same_group(struct sched_entity *se, struct sched_entity *pse) 411 { 412 if (se->cfs_rq == pse->cfs_rq) 413 return se->cfs_rq; 414 415 return NULL; 416 } 417 418 static inline struct sched_entity *parent_entity(const struct sched_entity *se) 419 { 420 return se->parent; 421 } 422 423 static void 424 find_matching_se(struct sched_entity **se, struct sched_entity **pse) 425 { 426 int se_depth, pse_depth; 427 428 /* 429 * preemption test can be made between sibling entities who are in the 430 * same cfs_rq i.e who have a common parent. Walk up the hierarchy of 431 * both tasks until we find their ancestors who are siblings of common 432 * parent. 433 */ 434 435 /* First walk up until both entities are at same depth */ 436 se_depth = (*se)->depth; 437 pse_depth = (*pse)->depth; 438 439 while (se_depth > pse_depth) { 440 se_depth--; 441 *se = parent_entity(*se); 442 } 443 444 while (pse_depth > se_depth) { 445 pse_depth--; 446 *pse = parent_entity(*pse); 447 } 448 449 while (!is_same_group(*se, *pse)) { 450 *se = parent_entity(*se); 451 *pse = parent_entity(*pse); 452 } 453 } 454 455 static int tg_is_idle(struct task_group *tg) 456 { 457 return tg->idle > 0; 458 } 459 460 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq) 461 { 462 return cfs_rq->idle > 0; 463 } 464 465 static int se_is_idle(struct sched_entity *se) 466 { 467 if (entity_is_task(se)) 468 return task_has_idle_policy(task_of(se)); 469 return cfs_rq_is_idle(group_cfs_rq(se)); 470 } 471 472 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 473 474 #define for_each_sched_entity(se) \ 475 for (; se; se = NULL) 476 477 static inline bool list_add_leaf_cfs_rq(struct cfs_rq *cfs_rq) 478 { 479 return true; 480 } 481 482 static inline void list_del_leaf_cfs_rq(struct cfs_rq *cfs_rq) 483 { 484 } 485 486 static inline void assert_list_leaf_cfs_rq(struct rq *rq) 487 { 488 } 489 490 #define for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) \ 491 for (cfs_rq = &rq->cfs, pos = NULL; cfs_rq; cfs_rq = pos) 492 493 static inline struct sched_entity *parent_entity(struct sched_entity *se) 494 { 495 return NULL; 496 } 497 498 static inline void 499 find_matching_se(struct sched_entity **se, struct sched_entity **pse) 500 { 501 } 502 503 static inline int tg_is_idle(struct task_group *tg) 504 { 505 return 0; 506 } 507 508 static int cfs_rq_is_idle(struct cfs_rq *cfs_rq) 509 { 510 return 0; 511 } 512 513 static int se_is_idle(struct sched_entity *se) 514 { 515 return task_has_idle_policy(task_of(se)); 516 } 517 518 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 519 520 static __always_inline 521 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec); 522 523 /************************************************************** 524 * Scheduling class tree data structure manipulation methods: 525 */ 526 527 extern void __BUILD_BUG_vruntime_cmp(void); 528 529 /* Use __builtin_strcmp() because of __HAVE_ARCH_STRCMP: */ 530 531 #define vruntime_cmp(A, CMP_STR, B) ({ \ 532 int __res = 0; \ 533 \ 534 if (!__builtin_strcmp(CMP_STR, "<")) { \ 535 __res = ((s64)((A)-(B)) < 0); \ 536 } else if (!__builtin_strcmp(CMP_STR, "<=")) { \ 537 __res = ((s64)((A)-(B)) <= 0); \ 538 } else if (!__builtin_strcmp(CMP_STR, ">")) { \ 539 __res = ((s64)((A)-(B)) > 0); \ 540 } else if (!__builtin_strcmp(CMP_STR, ">=")) { \ 541 __res = ((s64)((A)-(B)) >= 0); \ 542 } else { \ 543 /* Unknown operator throws linker error: */ \ 544 __BUILD_BUG_vruntime_cmp(); \ 545 } \ 546 \ 547 __res; \ 548 }) 549 550 extern void __BUILD_BUG_vruntime_op(void); 551 552 #define vruntime_op(A, OP_STR, B) ({ \ 553 s64 __res = 0; \ 554 \ 555 if (!__builtin_strcmp(OP_STR, "-")) { \ 556 __res = (s64)((A)-(B)); \ 557 } else { \ 558 /* Unknown operator throws linker error: */ \ 559 __BUILD_BUG_vruntime_op(); \ 560 } \ 561 \ 562 __res; \ 563 }) 564 565 566 static inline __maybe_unused u64 max_vruntime(u64 max_vruntime, u64 vruntime) 567 { 568 if (vruntime_cmp(vruntime, ">", max_vruntime)) 569 max_vruntime = vruntime; 570 571 return max_vruntime; 572 } 573 574 static inline __maybe_unused u64 min_vruntime(u64 min_vruntime, u64 vruntime) 575 { 576 if (vruntime_cmp(vruntime, "<", min_vruntime)) 577 min_vruntime = vruntime; 578 579 return min_vruntime; 580 } 581 582 static inline bool entity_before(const struct sched_entity *a, 583 const struct sched_entity *b) 584 { 585 /* 586 * Tiebreak on vruntime seems unnecessary since it can 587 * hardly happen. 588 */ 589 return vruntime_cmp(a->deadline, "<", b->deadline); 590 } 591 592 /* 593 * Per avg_vruntime() below, cfs_rq::zero_vruntime is only slightly stale 594 * and this value should be no more than two lag bounds. Which puts it in the 595 * general order of: 596 * 597 * (slice + TICK_NSEC) << NICE_0_LOAD_SHIFT 598 * 599 * which is around 44 bits in size (on 64bit); that is 20 for 600 * NICE_0_LOAD_SHIFT, another 20 for NSEC_PER_MSEC and then a handful for 601 * however many msec the actual slice+tick ends up begin. 602 * 603 * (disregarding the actual divide-by-weight part makes for the worst case 604 * weight of 2, which nicely cancels vs the fuzz in zero_vruntime not actually 605 * being the zero-lag point). 606 */ 607 static inline s64 entity_key(struct cfs_rq *cfs_rq, struct sched_entity *se) 608 { 609 return vruntime_op(se->vruntime, "-", cfs_rq->zero_vruntime); 610 } 611 612 #define __node_2_se(node) \ 613 rb_entry((node), struct sched_entity, run_node) 614 615 /* 616 * Compute virtual time from the per-task service numbers: 617 * 618 * Fair schedulers conserve lag: 619 * 620 * \Sum lag_i = 0 621 * 622 * Where lag_i is given by: 623 * 624 * lag_i = S - s_i = w_i * (V - v_i) 625 * 626 * Where S is the ideal service time and V is it's virtual time counterpart. 627 * Therefore: 628 * 629 * \Sum lag_i = 0 630 * \Sum w_i * (V - v_i) = 0 631 * \Sum (w_i * V - w_i * v_i) = 0 632 * 633 * From which we can solve an expression for V in v_i (which we have in 634 * se->vruntime): 635 * 636 * \Sum v_i * w_i \Sum v_i * w_i 637 * V = -------------- = -------------- 638 * \Sum w_i W 639 * 640 * Specifically, this is the weighted average of all entity virtual runtimes. 641 * 642 * [[ NOTE: this is only equal to the ideal scheduler under the condition 643 * that join/leave operations happen at lag_i = 0, otherwise the 644 * virtual time has non-contiguous motion equivalent to: 645 * 646 * V +-= lag_i / W 647 * 648 * Also see the comment in place_entity() that deals with this. ]] 649 * 650 * However, since v_i is u64, and the multiplication could easily overflow 651 * transform it into a relative form that uses smaller quantities: 652 * 653 * Substitute: v_i == (v_i - v0) + v0 654 * 655 * \Sum ((v_i - v0) + v0) * w_i \Sum (v_i - v0) * w_i 656 * V = ---------------------------- = --------------------- + v0 657 * W W 658 * 659 * Which we track using: 660 * 661 * v0 := cfs_rq->zero_vruntime 662 * \Sum (v_i - v0) * w_i := cfs_rq->sum_w_vruntime 663 * \Sum w_i := cfs_rq->sum_weight 664 * 665 * Since zero_vruntime closely tracks the per-task service, these 666 * deltas: (v_i - v0), will be in the order of the maximal (virtual) lag 667 * induced in the system due to quantisation. 668 * 669 * Also, we use scale_load_down() to reduce the size. 670 * 671 * As measured, the max (key * weight) value was ~44 bits for a kernel build. 672 */ 673 static void 674 sum_w_vruntime_add(struct cfs_rq *cfs_rq, struct sched_entity *se) 675 { 676 unsigned long weight = scale_load_down(se->load.weight); 677 s64 key = entity_key(cfs_rq, se); 678 679 cfs_rq->sum_w_vruntime += key * weight; 680 cfs_rq->sum_weight += weight; 681 } 682 683 static void 684 sum_w_vruntime_sub(struct cfs_rq *cfs_rq, struct sched_entity *se) 685 { 686 unsigned long weight = scale_load_down(se->load.weight); 687 s64 key = entity_key(cfs_rq, se); 688 689 cfs_rq->sum_w_vruntime -= key * weight; 690 cfs_rq->sum_weight -= weight; 691 } 692 693 static inline 694 void update_zero_vruntime(struct cfs_rq *cfs_rq, s64 delta) 695 { 696 /* 697 * v' = v + d ==> sum_w_vruntime' = sum_w_vruntime - d*sum_weight 698 */ 699 cfs_rq->sum_w_vruntime -= cfs_rq->sum_weight * delta; 700 cfs_rq->zero_vruntime += delta; 701 } 702 703 /* 704 * Specifically: avg_vruntime() + 0 must result in entity_eligible() := true 705 * For this to be so, the result of this function must have a left bias. 706 * 707 * Called in: 708 * - place_entity() -- before enqueue 709 * - update_entity_lag() -- before dequeue 710 * - entity_tick() 711 * 712 * This means it is one entry 'behind' but that puts it close enough to where 713 * the bound on entity_key() is at most two lag bounds. 714 */ 715 u64 avg_vruntime(struct cfs_rq *cfs_rq) 716 { 717 struct sched_entity *curr = cfs_rq->curr; 718 long weight = cfs_rq->sum_weight; 719 s64 delta = 0; 720 721 if (curr && !curr->on_rq) 722 curr = NULL; 723 724 if (weight) { 725 s64 runtime = cfs_rq->sum_w_vruntime; 726 727 if (curr) { 728 unsigned long w = scale_load_down(curr->load.weight); 729 730 runtime += entity_key(cfs_rq, curr) * w; 731 weight += w; 732 } 733 734 /* sign flips effective floor / ceiling */ 735 if (runtime < 0) 736 runtime -= (weight - 1); 737 738 delta = div_s64(runtime, weight); 739 } else if (curr) { 740 /* 741 * When there is but one element, it is the average. 742 */ 743 delta = curr->vruntime - cfs_rq->zero_vruntime; 744 } 745 746 update_zero_vruntime(cfs_rq, delta); 747 748 return cfs_rq->zero_vruntime; 749 } 750 751 static inline u64 cfs_rq_max_slice(struct cfs_rq *cfs_rq); 752 753 /* 754 * lag_i = S - s_i = w_i * (V - v_i) 755 * 756 * However, since V is approximated by the weighted average of all entities it 757 * is possible -- by addition/removal/reweight to the tree -- to move V around 758 * and end up with a larger lag than we started with. 759 * 760 * Limit this to either double the slice length with a minimum of TICK_NSEC 761 * since that is the timing granularity. 762 * 763 * EEVDF gives the following limit for a steady state system: 764 * 765 * -r_max < lag < max(r_max, q) 766 */ 767 static void update_entity_lag(struct cfs_rq *cfs_rq, struct sched_entity *se) 768 { 769 u64 max_slice = cfs_rq_max_slice(cfs_rq) + TICK_NSEC; 770 s64 vlag, limit; 771 772 WARN_ON_ONCE(!se->on_rq); 773 774 vlag = avg_vruntime(cfs_rq) - se->vruntime; 775 limit = calc_delta_fair(max_slice, se); 776 777 se->vlag = clamp(vlag, -limit, limit); 778 } 779 780 /* 781 * Entity is eligible once it received less service than it ought to have, 782 * eg. lag >= 0. 783 * 784 * lag_i = S - s_i = w_i*(V - v_i) 785 * 786 * lag_i >= 0 -> V >= v_i 787 * 788 * \Sum (v_i - v)*w_i 789 * V = ------------------ + v 790 * \Sum w_i 791 * 792 * lag_i >= 0 -> \Sum (v_i - v)*w_i >= (v_i - v)*(\Sum w_i) 793 * 794 * Note: using 'avg_vruntime() > se->vruntime' is inaccurate due 795 * to the loss in precision caused by the division. 796 */ 797 static int vruntime_eligible(struct cfs_rq *cfs_rq, u64 vruntime) 798 { 799 struct sched_entity *curr = cfs_rq->curr; 800 s64 avg = cfs_rq->sum_w_vruntime; 801 long load = cfs_rq->sum_weight; 802 803 if (curr && curr->on_rq) { 804 unsigned long weight = scale_load_down(curr->load.weight); 805 806 avg += entity_key(cfs_rq, curr) * weight; 807 load += weight; 808 } 809 810 return avg >= vruntime_op(vruntime, "-", cfs_rq->zero_vruntime) * load; 811 } 812 813 int entity_eligible(struct cfs_rq *cfs_rq, struct sched_entity *se) 814 { 815 return vruntime_eligible(cfs_rq, se->vruntime); 816 } 817 818 static inline u64 cfs_rq_min_slice(struct cfs_rq *cfs_rq) 819 { 820 struct sched_entity *root = __pick_root_entity(cfs_rq); 821 struct sched_entity *curr = cfs_rq->curr; 822 u64 min_slice = ~0ULL; 823 824 if (curr && curr->on_rq) 825 min_slice = curr->slice; 826 827 if (root) 828 min_slice = min(min_slice, root->min_slice); 829 830 return min_slice; 831 } 832 833 static inline u64 cfs_rq_max_slice(struct cfs_rq *cfs_rq) 834 { 835 struct sched_entity *root = __pick_root_entity(cfs_rq); 836 struct sched_entity *curr = cfs_rq->curr; 837 u64 max_slice = 0ULL; 838 839 if (curr && curr->on_rq) 840 max_slice = curr->slice; 841 842 if (root) 843 max_slice = max(max_slice, root->max_slice); 844 845 return max_slice; 846 } 847 848 static inline bool __entity_less(struct rb_node *a, const struct rb_node *b) 849 { 850 return entity_before(__node_2_se(a), __node_2_se(b)); 851 } 852 853 static inline void __min_vruntime_update(struct sched_entity *se, struct rb_node *node) 854 { 855 if (node) { 856 struct sched_entity *rse = __node_2_se(node); 857 858 if (vruntime_cmp(se->min_vruntime, ">", rse->min_vruntime)) 859 se->min_vruntime = rse->min_vruntime; 860 } 861 } 862 863 static inline void __min_slice_update(struct sched_entity *se, struct rb_node *node) 864 { 865 if (node) { 866 struct sched_entity *rse = __node_2_se(node); 867 if (rse->min_slice < se->min_slice) 868 se->min_slice = rse->min_slice; 869 } 870 } 871 872 static inline void __max_slice_update(struct sched_entity *se, struct rb_node *node) 873 { 874 if (node) { 875 struct sched_entity *rse = __node_2_se(node); 876 if (rse->max_slice > se->max_slice) 877 se->max_slice = rse->max_slice; 878 } 879 } 880 881 /* 882 * se->min_vruntime = min(se->vruntime, {left,right}->min_vruntime) 883 */ 884 static inline bool min_vruntime_update(struct sched_entity *se, bool exit) 885 { 886 u64 old_min_vruntime = se->min_vruntime; 887 u64 old_min_slice = se->min_slice; 888 u64 old_max_slice = se->max_slice; 889 struct rb_node *node = &se->run_node; 890 891 se->min_vruntime = se->vruntime; 892 __min_vruntime_update(se, node->rb_right); 893 __min_vruntime_update(se, node->rb_left); 894 895 se->min_slice = se->slice; 896 __min_slice_update(se, node->rb_right); 897 __min_slice_update(se, node->rb_left); 898 899 se->max_slice = se->slice; 900 __max_slice_update(se, node->rb_right); 901 __max_slice_update(se, node->rb_left); 902 903 return se->min_vruntime == old_min_vruntime && 904 se->min_slice == old_min_slice && 905 se->max_slice == old_max_slice; 906 } 907 908 RB_DECLARE_CALLBACKS(static, min_vruntime_cb, struct sched_entity, 909 run_node, min_vruntime, min_vruntime_update); 910 911 /* 912 * Enqueue an entity into the rb-tree: 913 */ 914 static void __enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) 915 { 916 sum_w_vruntime_add(cfs_rq, se); 917 se->min_vruntime = se->vruntime; 918 se->min_slice = se->slice; 919 rb_add_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline, 920 __entity_less, &min_vruntime_cb); 921 } 922 923 static void __dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se) 924 { 925 rb_erase_augmented_cached(&se->run_node, &cfs_rq->tasks_timeline, 926 &min_vruntime_cb); 927 sum_w_vruntime_sub(cfs_rq, se); 928 } 929 930 struct sched_entity *__pick_root_entity(struct cfs_rq *cfs_rq) 931 { 932 struct rb_node *root = cfs_rq->tasks_timeline.rb_root.rb_node; 933 934 if (!root) 935 return NULL; 936 937 return __node_2_se(root); 938 } 939 940 struct sched_entity *__pick_first_entity(struct cfs_rq *cfs_rq) 941 { 942 struct rb_node *left = rb_first_cached(&cfs_rq->tasks_timeline); 943 944 if (!left) 945 return NULL; 946 947 return __node_2_se(left); 948 } 949 950 /* 951 * Set the vruntime up to which an entity can run before looking 952 * for another entity to pick. 953 * In case of run to parity, we use the shortest slice of the enqueued 954 * entities to set the protected period. 955 * When run to parity is disabled, we give a minimum quantum to the running 956 * entity to ensure progress. 957 */ 958 static inline void set_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se) 959 { 960 u64 slice = normalized_sysctl_sched_base_slice; 961 u64 vprot = se->deadline; 962 963 if (sched_feat(RUN_TO_PARITY)) 964 slice = cfs_rq_min_slice(cfs_rq); 965 966 slice = min(slice, se->slice); 967 if (slice != se->slice) 968 vprot = min_vruntime(vprot, se->vruntime + calc_delta_fair(slice, se)); 969 970 se->vprot = vprot; 971 } 972 973 static inline void update_protect_slice(struct cfs_rq *cfs_rq, struct sched_entity *se) 974 { 975 u64 slice = cfs_rq_min_slice(cfs_rq); 976 977 se->vprot = min_vruntime(se->vprot, se->vruntime + calc_delta_fair(slice, se)); 978 } 979 980 static inline bool protect_slice(struct sched_entity *se) 981 { 982 return vruntime_cmp(se->vruntime, "<", se->vprot); 983 } 984 985 static inline void cancel_protect_slice(struct sched_entity *se) 986 { 987 if (protect_slice(se)) 988 se->vprot = se->vruntime; 989 } 990 991 /* 992 * Earliest Eligible Virtual Deadline First 993 * 994 * In order to provide latency guarantees for different request sizes 995 * EEVDF selects the best runnable task from two criteria: 996 * 997 * 1) the task must be eligible (must be owed service) 998 * 999 * 2) from those tasks that meet 1), we select the one 1000 * with the earliest virtual deadline. 1001 * 1002 * We can do this in O(log n) time due to an augmented RB-tree. The 1003 * tree keeps the entries sorted on deadline, but also functions as a 1004 * heap based on the vruntime by keeping: 1005 * 1006 * se->min_vruntime = min(se->vruntime, se->{left,right}->min_vruntime) 1007 * 1008 * Which allows tree pruning through eligibility. 1009 */ 1010 static struct sched_entity *__pick_eevdf(struct cfs_rq *cfs_rq, bool protect) 1011 { 1012 struct rb_node *node = cfs_rq->tasks_timeline.rb_root.rb_node; 1013 struct sched_entity *se = __pick_first_entity(cfs_rq); 1014 struct sched_entity *curr = cfs_rq->curr; 1015 struct sched_entity *best = NULL; 1016 1017 /* 1018 * We can safely skip eligibility check if there is only one entity 1019 * in this cfs_rq, saving some cycles. 1020 */ 1021 if (cfs_rq->nr_queued == 1) 1022 return curr && curr->on_rq ? curr : se; 1023 1024 /* 1025 * Picking the ->next buddy will affect latency but not fairness. 1026 */ 1027 if (sched_feat(PICK_BUDDY) && 1028 cfs_rq->next && entity_eligible(cfs_rq, cfs_rq->next)) { 1029 /* ->next will never be delayed */ 1030 WARN_ON_ONCE(cfs_rq->next->sched_delayed); 1031 return cfs_rq->next; 1032 } 1033 1034 if (curr && (!curr->on_rq || !entity_eligible(cfs_rq, curr))) 1035 curr = NULL; 1036 1037 if (curr && protect && protect_slice(curr)) 1038 return curr; 1039 1040 /* Pick the leftmost entity if it's eligible */ 1041 if (se && entity_eligible(cfs_rq, se)) { 1042 best = se; 1043 goto found; 1044 } 1045 1046 /* Heap search for the EEVD entity */ 1047 while (node) { 1048 struct rb_node *left = node->rb_left; 1049 1050 /* 1051 * Eligible entities in left subtree are always better 1052 * choices, since they have earlier deadlines. 1053 */ 1054 if (left && vruntime_eligible(cfs_rq, 1055 __node_2_se(left)->min_vruntime)) { 1056 node = left; 1057 continue; 1058 } 1059 1060 se = __node_2_se(node); 1061 1062 /* 1063 * The left subtree either is empty or has no eligible 1064 * entity, so check the current node since it is the one 1065 * with earliest deadline that might be eligible. 1066 */ 1067 if (entity_eligible(cfs_rq, se)) { 1068 best = se; 1069 break; 1070 } 1071 1072 node = node->rb_right; 1073 } 1074 found: 1075 if (!best || (curr && entity_before(curr, best))) 1076 best = curr; 1077 1078 return best; 1079 } 1080 1081 static struct sched_entity *pick_eevdf(struct cfs_rq *cfs_rq) 1082 { 1083 return __pick_eevdf(cfs_rq, true); 1084 } 1085 1086 struct sched_entity *__pick_last_entity(struct cfs_rq *cfs_rq) 1087 { 1088 struct rb_node *last = rb_last(&cfs_rq->tasks_timeline.rb_root); 1089 1090 if (!last) 1091 return NULL; 1092 1093 return __node_2_se(last); 1094 } 1095 1096 /************************************************************** 1097 * Scheduling class statistics methods: 1098 */ 1099 int sched_update_scaling(void) 1100 { 1101 unsigned int factor = get_update_sysctl_factor(); 1102 1103 #define WRT_SYSCTL(name) \ 1104 (normalized_sysctl_##name = sysctl_##name / (factor)) 1105 WRT_SYSCTL(sched_base_slice); 1106 #undef WRT_SYSCTL 1107 1108 return 0; 1109 } 1110 1111 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se); 1112 1113 /* 1114 * XXX: strictly: vd_i += N*r_i/w_i such that: vd_i > ve_i 1115 * this is probably good enough. 1116 */ 1117 static bool update_deadline(struct cfs_rq *cfs_rq, struct sched_entity *se) 1118 { 1119 if (vruntime_cmp(se->vruntime, "<", se->deadline)) 1120 return false; 1121 1122 /* 1123 * For EEVDF the virtual time slope is determined by w_i (iow. 1124 * nice) while the request time r_i is determined by 1125 * sysctl_sched_base_slice. 1126 */ 1127 if (!se->custom_slice) 1128 se->slice = sysctl_sched_base_slice; 1129 1130 /* 1131 * EEVDF: vd_i = ve_i + r_i / w_i 1132 */ 1133 se->deadline = se->vruntime + calc_delta_fair(se->slice, se); 1134 1135 /* 1136 * The task has consumed its request, reschedule. 1137 */ 1138 return true; 1139 } 1140 1141 #include "pelt.h" 1142 1143 static int select_idle_sibling(struct task_struct *p, int prev_cpu, int cpu); 1144 static unsigned long task_h_load(struct task_struct *p); 1145 static unsigned long capacity_of(int cpu); 1146 1147 /* Give new sched_entity start runnable values to heavy its load in infant time */ 1148 void init_entity_runnable_average(struct sched_entity *se) 1149 { 1150 struct sched_avg *sa = &se->avg; 1151 1152 memset(sa, 0, sizeof(*sa)); 1153 1154 /* 1155 * Tasks are initialized with full load to be seen as heavy tasks until 1156 * they get a chance to stabilize to their real load level. 1157 * Group entities are initialized with zero load to reflect the fact that 1158 * nothing has been attached to the task group yet. 1159 */ 1160 if (entity_is_task(se)) 1161 sa->load_avg = scale_load_down(se->load.weight); 1162 1163 /* when this task is enqueued, it will contribute to its cfs_rq's load_avg */ 1164 } 1165 1166 /* 1167 * With new tasks being created, their initial util_avgs are extrapolated 1168 * based on the cfs_rq's current util_avg: 1169 * 1170 * util_avg = cfs_rq->avg.util_avg / (cfs_rq->avg.load_avg + 1) 1171 * * se_weight(se) 1172 * 1173 * However, in many cases, the above util_avg does not give a desired 1174 * value. Moreover, the sum of the util_avgs may be divergent, such 1175 * as when the series is a harmonic series. 1176 * 1177 * To solve this problem, we also cap the util_avg of successive tasks to 1178 * only 1/2 of the left utilization budget: 1179 * 1180 * util_avg_cap = (cpu_scale - cfs_rq->avg.util_avg) / 2^n 1181 * 1182 * where n denotes the nth task and cpu_scale the CPU capacity. 1183 * 1184 * For example, for a CPU with 1024 of capacity, a simplest series from 1185 * the beginning would be like: 1186 * 1187 * task util_avg: 512, 256, 128, 64, 32, 16, 8, ... 1188 * cfs_rq util_avg: 512, 768, 896, 960, 992, 1008, 1016, ... 1189 * 1190 * Finally, that extrapolated util_avg is clamped to the cap (util_avg_cap) 1191 * if util_avg > util_avg_cap. 1192 */ 1193 void post_init_entity_util_avg(struct task_struct *p) 1194 { 1195 struct sched_entity *se = &p->se; 1196 struct cfs_rq *cfs_rq = cfs_rq_of(se); 1197 struct sched_avg *sa = &se->avg; 1198 long cpu_scale = arch_scale_cpu_capacity(cpu_of(rq_of(cfs_rq))); 1199 long cap = (long)(cpu_scale - cfs_rq->avg.util_avg) / 2; 1200 1201 if (p->sched_class != &fair_sched_class) { 1202 /* 1203 * For !fair tasks do: 1204 * 1205 update_cfs_rq_load_avg(now, cfs_rq); 1206 attach_entity_load_avg(cfs_rq, se); 1207 switched_from_fair(rq, p); 1208 * 1209 * such that the next switched_to_fair() has the 1210 * expected state. 1211 */ 1212 se->avg.last_update_time = cfs_rq_clock_pelt(cfs_rq); 1213 return; 1214 } 1215 1216 if (cap > 0) { 1217 if (cfs_rq->avg.util_avg != 0) { 1218 sa->util_avg = cfs_rq->avg.util_avg * se_weight(se); 1219 sa->util_avg /= (cfs_rq->avg.load_avg + 1); 1220 1221 if (sa->util_avg > cap) 1222 sa->util_avg = cap; 1223 } else { 1224 sa->util_avg = cap; 1225 } 1226 } 1227 1228 sa->runnable_avg = sa->util_avg; 1229 } 1230 1231 static s64 update_se(struct rq *rq, struct sched_entity *se) 1232 { 1233 u64 now = rq_clock_task(rq); 1234 s64 delta_exec; 1235 1236 delta_exec = now - se->exec_start; 1237 if (unlikely(delta_exec <= 0)) 1238 return delta_exec; 1239 1240 se->exec_start = now; 1241 if (entity_is_task(se)) { 1242 struct task_struct *donor = task_of(se); 1243 struct task_struct *running = rq->curr; 1244 /* 1245 * If se is a task, we account the time against the running 1246 * task, as w/ proxy-exec they may not be the same. 1247 */ 1248 running->se.exec_start = now; 1249 running->se.sum_exec_runtime += delta_exec; 1250 1251 trace_sched_stat_runtime(running, delta_exec); 1252 account_group_exec_runtime(running, delta_exec); 1253 1254 /* cgroup time is always accounted against the donor */ 1255 cgroup_account_cputime(donor, delta_exec); 1256 } else { 1257 /* If not task, account the time against donor se */ 1258 se->sum_exec_runtime += delta_exec; 1259 } 1260 1261 if (schedstat_enabled()) { 1262 struct sched_statistics *stats; 1263 1264 stats = __schedstats_from_se(se); 1265 __schedstat_set(stats->exec_max, 1266 max(delta_exec, stats->exec_max)); 1267 } 1268 1269 return delta_exec; 1270 } 1271 1272 static void set_next_buddy(struct sched_entity *se); 1273 1274 /* 1275 * Used by other classes to account runtime. 1276 */ 1277 s64 update_curr_common(struct rq *rq) 1278 { 1279 return update_se(rq, &rq->donor->se); 1280 } 1281 1282 /* 1283 * Update the current task's runtime statistics. 1284 */ 1285 static void update_curr(struct cfs_rq *cfs_rq) 1286 { 1287 /* 1288 * Note: cfs_rq->curr corresponds to the task picked to 1289 * run (ie: rq->donor.se) which due to proxy-exec may 1290 * not necessarily be the actual task running 1291 * (rq->curr.se). This is easy to confuse! 1292 */ 1293 struct sched_entity *curr = cfs_rq->curr; 1294 struct rq *rq = rq_of(cfs_rq); 1295 s64 delta_exec; 1296 bool resched; 1297 1298 if (unlikely(!curr)) 1299 return; 1300 1301 delta_exec = update_se(rq, curr); 1302 if (unlikely(delta_exec <= 0)) 1303 return; 1304 1305 curr->vruntime += calc_delta_fair(delta_exec, curr); 1306 resched = update_deadline(cfs_rq, curr); 1307 1308 if (entity_is_task(curr)) { 1309 /* 1310 * If the fair_server is active, we need to account for the 1311 * fair_server time whether or not the task is running on 1312 * behalf of fair_server or not: 1313 * - If the task is running on behalf of fair_server, we need 1314 * to limit its time based on the assigned runtime. 1315 * - Fair task that runs outside of fair_server should account 1316 * against fair_server such that it can account for this time 1317 * and possibly avoid running this period. 1318 */ 1319 dl_server_update(&rq->fair_server, delta_exec); 1320 } 1321 1322 account_cfs_rq_runtime(cfs_rq, delta_exec); 1323 1324 if (cfs_rq->nr_queued == 1) 1325 return; 1326 1327 if (resched || !protect_slice(curr)) { 1328 resched_curr_lazy(rq); 1329 clear_buddies(cfs_rq, curr); 1330 } 1331 } 1332 1333 static void update_curr_fair(struct rq *rq) 1334 { 1335 update_curr(cfs_rq_of(&rq->donor->se)); 1336 } 1337 1338 static inline void 1339 update_stats_wait_start_fair(struct cfs_rq *cfs_rq, struct sched_entity *se) 1340 { 1341 struct sched_statistics *stats; 1342 struct task_struct *p = NULL; 1343 1344 if (!schedstat_enabled()) 1345 return; 1346 1347 stats = __schedstats_from_se(se); 1348 1349 if (entity_is_task(se)) 1350 p = task_of(se); 1351 1352 __update_stats_wait_start(rq_of(cfs_rq), p, stats); 1353 } 1354 1355 static inline void 1356 update_stats_wait_end_fair(struct cfs_rq *cfs_rq, struct sched_entity *se) 1357 { 1358 struct sched_statistics *stats; 1359 struct task_struct *p = NULL; 1360 1361 if (!schedstat_enabled()) 1362 return; 1363 1364 stats = __schedstats_from_se(se); 1365 1366 /* 1367 * When the sched_schedstat changes from 0 to 1, some sched se 1368 * maybe already in the runqueue, the se->statistics.wait_start 1369 * will be 0.So it will let the delta wrong. We need to avoid this 1370 * scenario. 1371 */ 1372 if (unlikely(!schedstat_val(stats->wait_start))) 1373 return; 1374 1375 if (entity_is_task(se)) 1376 p = task_of(se); 1377 1378 __update_stats_wait_end(rq_of(cfs_rq), p, stats); 1379 } 1380 1381 static inline void 1382 update_stats_enqueue_sleeper_fair(struct cfs_rq *cfs_rq, struct sched_entity *se) 1383 { 1384 struct sched_statistics *stats; 1385 struct task_struct *tsk = NULL; 1386 1387 if (!schedstat_enabled()) 1388 return; 1389 1390 stats = __schedstats_from_se(se); 1391 1392 if (entity_is_task(se)) 1393 tsk = task_of(se); 1394 1395 __update_stats_enqueue_sleeper(rq_of(cfs_rq), tsk, stats); 1396 } 1397 1398 /* 1399 * Task is being enqueued - update stats: 1400 */ 1401 static inline void 1402 update_stats_enqueue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 1403 { 1404 if (!schedstat_enabled()) 1405 return; 1406 1407 /* 1408 * Are we enqueueing a waiting task? (for current tasks 1409 * a dequeue/enqueue event is a NOP) 1410 */ 1411 if (se != cfs_rq->curr) 1412 update_stats_wait_start_fair(cfs_rq, se); 1413 1414 if (flags & ENQUEUE_WAKEUP) 1415 update_stats_enqueue_sleeper_fair(cfs_rq, se); 1416 } 1417 1418 static inline void 1419 update_stats_dequeue_fair(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 1420 { 1421 1422 if (!schedstat_enabled()) 1423 return; 1424 1425 /* 1426 * Mark the end of the wait period if dequeueing a 1427 * waiting task: 1428 */ 1429 if (se != cfs_rq->curr) 1430 update_stats_wait_end_fair(cfs_rq, se); 1431 1432 if ((flags & DEQUEUE_SLEEP) && entity_is_task(se)) { 1433 struct task_struct *tsk = task_of(se); 1434 unsigned int state; 1435 1436 /* XXX racy against TTWU */ 1437 state = READ_ONCE(tsk->__state); 1438 if (state & TASK_INTERRUPTIBLE) 1439 __schedstat_set(tsk->stats.sleep_start, 1440 rq_clock(rq_of(cfs_rq))); 1441 if (state & TASK_UNINTERRUPTIBLE) 1442 __schedstat_set(tsk->stats.block_start, 1443 rq_clock(rq_of(cfs_rq))); 1444 } 1445 } 1446 1447 /* 1448 * We are picking a new current task - update its stats: 1449 */ 1450 static inline void 1451 update_stats_curr_start(struct cfs_rq *cfs_rq, struct sched_entity *se) 1452 { 1453 /* 1454 * We are starting a new run period: 1455 */ 1456 se->exec_start = rq_clock_task(rq_of(cfs_rq)); 1457 } 1458 1459 /************************************************** 1460 * Scheduling class queueing methods: 1461 */ 1462 1463 static inline bool is_core_idle(int cpu) 1464 { 1465 #ifdef CONFIG_SCHED_SMT 1466 int sibling; 1467 1468 for_each_cpu(sibling, cpu_smt_mask(cpu)) { 1469 if (cpu == sibling) 1470 continue; 1471 1472 if (!idle_cpu(sibling)) 1473 return false; 1474 } 1475 #endif 1476 1477 return true; 1478 } 1479 1480 #ifdef CONFIG_NUMA 1481 #define NUMA_IMBALANCE_MIN 2 1482 1483 static inline long 1484 adjust_numa_imbalance(int imbalance, int dst_running, int imb_numa_nr) 1485 { 1486 /* 1487 * Allow a NUMA imbalance if busy CPUs is less than the maximum 1488 * threshold. Above this threshold, individual tasks may be contending 1489 * for both memory bandwidth and any shared HT resources. This is an 1490 * approximation as the number of running tasks may not be related to 1491 * the number of busy CPUs due to sched_setaffinity. 1492 */ 1493 if (dst_running > imb_numa_nr) 1494 return imbalance; 1495 1496 /* 1497 * Allow a small imbalance based on a simple pair of communicating 1498 * tasks that remain local when the destination is lightly loaded. 1499 */ 1500 if (imbalance <= NUMA_IMBALANCE_MIN) 1501 return 0; 1502 1503 return imbalance; 1504 } 1505 #endif /* CONFIG_NUMA */ 1506 1507 #ifdef CONFIG_NUMA_BALANCING 1508 /* 1509 * Approximate time to scan a full NUMA task in ms. The task scan period is 1510 * calculated based on the tasks virtual memory size and 1511 * numa_balancing_scan_size. 1512 */ 1513 unsigned int sysctl_numa_balancing_scan_period_min = 1000; 1514 unsigned int sysctl_numa_balancing_scan_period_max = 60000; 1515 1516 /* Portion of address space to scan in MB */ 1517 unsigned int sysctl_numa_balancing_scan_size = 256; 1518 1519 /* Scan @scan_size MB every @scan_period after an initial @scan_delay in ms */ 1520 unsigned int sysctl_numa_balancing_scan_delay = 1000; 1521 1522 /* The page with hint page fault latency < threshold in ms is considered hot */ 1523 unsigned int sysctl_numa_balancing_hot_threshold = MSEC_PER_SEC; 1524 1525 struct numa_group { 1526 refcount_t refcount; 1527 1528 spinlock_t lock; /* nr_tasks, tasks */ 1529 int nr_tasks; 1530 pid_t gid; 1531 int active_nodes; 1532 1533 struct rcu_head rcu; 1534 unsigned long total_faults; 1535 unsigned long max_faults_cpu; 1536 /* 1537 * faults[] array is split into two regions: faults_mem and faults_cpu. 1538 * 1539 * Faults_cpu is used to decide whether memory should move 1540 * towards the CPU. As a consequence, these stats are weighted 1541 * more by CPU use than by memory faults. 1542 */ 1543 unsigned long faults[]; 1544 }; 1545 1546 /* 1547 * For functions that can be called in multiple contexts that permit reading 1548 * ->numa_group (see struct task_struct for locking rules). 1549 */ 1550 static struct numa_group *deref_task_numa_group(struct task_struct *p) 1551 { 1552 return rcu_dereference_check(p->numa_group, p == current || 1553 (lockdep_is_held(__rq_lockp(task_rq(p))) && !READ_ONCE(p->on_cpu))); 1554 } 1555 1556 static struct numa_group *deref_curr_numa_group(struct task_struct *p) 1557 { 1558 return rcu_dereference_protected(p->numa_group, p == current); 1559 } 1560 1561 static inline unsigned long group_faults_priv(struct numa_group *ng); 1562 static inline unsigned long group_faults_shared(struct numa_group *ng); 1563 1564 static unsigned int task_nr_scan_windows(struct task_struct *p) 1565 { 1566 unsigned long rss = 0; 1567 unsigned long nr_scan_pages; 1568 1569 /* 1570 * Calculations based on RSS as non-present and empty pages are skipped 1571 * by the PTE scanner and NUMA hinting faults should be trapped based 1572 * on resident pages 1573 */ 1574 nr_scan_pages = MB_TO_PAGES(sysctl_numa_balancing_scan_size); 1575 rss = get_mm_rss(p->mm); 1576 if (!rss) 1577 rss = nr_scan_pages; 1578 1579 rss = round_up(rss, nr_scan_pages); 1580 return rss / nr_scan_pages; 1581 } 1582 1583 /* For sanity's sake, never scan more PTEs than MAX_SCAN_WINDOW MB/sec. */ 1584 #define MAX_SCAN_WINDOW 2560 1585 1586 static unsigned int task_scan_min(struct task_struct *p) 1587 { 1588 unsigned int scan_size = READ_ONCE(sysctl_numa_balancing_scan_size); 1589 unsigned int scan, floor; 1590 unsigned int windows = 1; 1591 1592 if (scan_size < MAX_SCAN_WINDOW) 1593 windows = MAX_SCAN_WINDOW / scan_size; 1594 floor = 1000 / windows; 1595 1596 scan = sysctl_numa_balancing_scan_period_min / task_nr_scan_windows(p); 1597 return max_t(unsigned int, floor, scan); 1598 } 1599 1600 static unsigned int task_scan_start(struct task_struct *p) 1601 { 1602 unsigned long smin = task_scan_min(p); 1603 unsigned long period = smin; 1604 struct numa_group *ng; 1605 1606 /* Scale the maximum scan period with the amount of shared memory. */ 1607 rcu_read_lock(); 1608 ng = rcu_dereference_all(p->numa_group); 1609 if (ng) { 1610 unsigned long shared = group_faults_shared(ng); 1611 unsigned long private = group_faults_priv(ng); 1612 1613 period *= refcount_read(&ng->refcount); 1614 period *= shared + 1; 1615 period /= private + shared + 1; 1616 } 1617 rcu_read_unlock(); 1618 1619 return max(smin, period); 1620 } 1621 1622 static unsigned int task_scan_max(struct task_struct *p) 1623 { 1624 unsigned long smin = task_scan_min(p); 1625 unsigned long smax; 1626 struct numa_group *ng; 1627 1628 /* Watch for min being lower than max due to floor calculations */ 1629 smax = sysctl_numa_balancing_scan_period_max / task_nr_scan_windows(p); 1630 1631 /* Scale the maximum scan period with the amount of shared memory. */ 1632 ng = deref_curr_numa_group(p); 1633 if (ng) { 1634 unsigned long shared = group_faults_shared(ng); 1635 unsigned long private = group_faults_priv(ng); 1636 unsigned long period = smax; 1637 1638 period *= refcount_read(&ng->refcount); 1639 period *= shared + 1; 1640 period /= private + shared + 1; 1641 1642 smax = max(smax, period); 1643 } 1644 1645 return max(smin, smax); 1646 } 1647 1648 static void account_numa_enqueue(struct rq *rq, struct task_struct *p) 1649 { 1650 rq->nr_numa_running += (p->numa_preferred_nid != NUMA_NO_NODE); 1651 rq->nr_preferred_running += (p->numa_preferred_nid == task_node(p)); 1652 } 1653 1654 static void account_numa_dequeue(struct rq *rq, struct task_struct *p) 1655 { 1656 rq->nr_numa_running -= (p->numa_preferred_nid != NUMA_NO_NODE); 1657 rq->nr_preferred_running -= (p->numa_preferred_nid == task_node(p)); 1658 } 1659 1660 /* Shared or private faults. */ 1661 #define NR_NUMA_HINT_FAULT_TYPES 2 1662 1663 /* Memory and CPU locality */ 1664 #define NR_NUMA_HINT_FAULT_STATS (NR_NUMA_HINT_FAULT_TYPES * 2) 1665 1666 /* Averaged statistics, and temporary buffers. */ 1667 #define NR_NUMA_HINT_FAULT_BUCKETS (NR_NUMA_HINT_FAULT_STATS * 2) 1668 1669 pid_t task_numa_group_id(struct task_struct *p) 1670 { 1671 struct numa_group *ng; 1672 pid_t gid = 0; 1673 1674 rcu_read_lock(); 1675 ng = rcu_dereference_all(p->numa_group); 1676 if (ng) 1677 gid = ng->gid; 1678 rcu_read_unlock(); 1679 1680 return gid; 1681 } 1682 1683 /* 1684 * The averaged statistics, shared & private, memory & CPU, 1685 * occupy the first half of the array. The second half of the 1686 * array is for current counters, which are averaged into the 1687 * first set by task_numa_placement. 1688 */ 1689 static inline int task_faults_idx(enum numa_faults_stats s, int nid, int priv) 1690 { 1691 return NR_NUMA_HINT_FAULT_TYPES * (s * nr_node_ids + nid) + priv; 1692 } 1693 1694 static inline unsigned long task_faults(struct task_struct *p, int nid) 1695 { 1696 if (!p->numa_faults) 1697 return 0; 1698 1699 return p->numa_faults[task_faults_idx(NUMA_MEM, nid, 0)] + 1700 p->numa_faults[task_faults_idx(NUMA_MEM, nid, 1)]; 1701 } 1702 1703 static inline unsigned long group_faults(struct task_struct *p, int nid) 1704 { 1705 struct numa_group *ng = deref_task_numa_group(p); 1706 1707 if (!ng) 1708 return 0; 1709 1710 return ng->faults[task_faults_idx(NUMA_MEM, nid, 0)] + 1711 ng->faults[task_faults_idx(NUMA_MEM, nid, 1)]; 1712 } 1713 1714 static inline unsigned long group_faults_cpu(struct numa_group *group, int nid) 1715 { 1716 return group->faults[task_faults_idx(NUMA_CPU, nid, 0)] + 1717 group->faults[task_faults_idx(NUMA_CPU, nid, 1)]; 1718 } 1719 1720 static inline unsigned long group_faults_priv(struct numa_group *ng) 1721 { 1722 unsigned long faults = 0; 1723 int node; 1724 1725 for_each_online_node(node) { 1726 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 1)]; 1727 } 1728 1729 return faults; 1730 } 1731 1732 static inline unsigned long group_faults_shared(struct numa_group *ng) 1733 { 1734 unsigned long faults = 0; 1735 int node; 1736 1737 for_each_online_node(node) { 1738 faults += ng->faults[task_faults_idx(NUMA_MEM, node, 0)]; 1739 } 1740 1741 return faults; 1742 } 1743 1744 /* 1745 * A node triggering more than 1/3 as many NUMA faults as the maximum is 1746 * considered part of a numa group's pseudo-interleaving set. Migrations 1747 * between these nodes are slowed down, to allow things to settle down. 1748 */ 1749 #define ACTIVE_NODE_FRACTION 3 1750 1751 static bool numa_is_active_node(int nid, struct numa_group *ng) 1752 { 1753 return group_faults_cpu(ng, nid) * ACTIVE_NODE_FRACTION > ng->max_faults_cpu; 1754 } 1755 1756 /* Handle placement on systems where not all nodes are directly connected. */ 1757 static unsigned long score_nearby_nodes(struct task_struct *p, int nid, 1758 int lim_dist, bool task) 1759 { 1760 unsigned long score = 0; 1761 int node, max_dist; 1762 1763 /* 1764 * All nodes are directly connected, and the same distance 1765 * from each other. No need for fancy placement algorithms. 1766 */ 1767 if (sched_numa_topology_type == NUMA_DIRECT) 1768 return 0; 1769 1770 /* sched_max_numa_distance may be changed in parallel. */ 1771 max_dist = READ_ONCE(sched_max_numa_distance); 1772 /* 1773 * This code is called for each node, introducing N^2 complexity, 1774 * which should be OK given the number of nodes rarely exceeds 8. 1775 */ 1776 for_each_online_node(node) { 1777 unsigned long faults; 1778 int dist = node_distance(nid, node); 1779 1780 /* 1781 * The furthest away nodes in the system are not interesting 1782 * for placement; nid was already counted. 1783 */ 1784 if (dist >= max_dist || node == nid) 1785 continue; 1786 1787 /* 1788 * On systems with a backplane NUMA topology, compare groups 1789 * of nodes, and move tasks towards the group with the most 1790 * memory accesses. When comparing two nodes at distance 1791 * "hoplimit", only nodes closer by than "hoplimit" are part 1792 * of each group. Skip other nodes. 1793 */ 1794 if (sched_numa_topology_type == NUMA_BACKPLANE && dist >= lim_dist) 1795 continue; 1796 1797 /* Add up the faults from nearby nodes. */ 1798 if (task) 1799 faults = task_faults(p, node); 1800 else 1801 faults = group_faults(p, node); 1802 1803 /* 1804 * On systems with a glueless mesh NUMA topology, there are 1805 * no fixed "groups of nodes". Instead, nodes that are not 1806 * directly connected bounce traffic through intermediate 1807 * nodes; a numa_group can occupy any set of nodes. 1808 * The further away a node is, the less the faults count. 1809 * This seems to result in good task placement. 1810 */ 1811 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) { 1812 faults *= (max_dist - dist); 1813 faults /= (max_dist - LOCAL_DISTANCE); 1814 } 1815 1816 score += faults; 1817 } 1818 1819 return score; 1820 } 1821 1822 /* 1823 * These return the fraction of accesses done by a particular task, or 1824 * task group, on a particular numa node. The group weight is given a 1825 * larger multiplier, in order to group tasks together that are almost 1826 * evenly spread out between numa nodes. 1827 */ 1828 static inline unsigned long task_weight(struct task_struct *p, int nid, 1829 int dist) 1830 { 1831 unsigned long faults, total_faults; 1832 1833 if (!p->numa_faults) 1834 return 0; 1835 1836 total_faults = p->total_numa_faults; 1837 1838 if (!total_faults) 1839 return 0; 1840 1841 faults = task_faults(p, nid); 1842 faults += score_nearby_nodes(p, nid, dist, true); 1843 1844 return 1000 * faults / total_faults; 1845 } 1846 1847 static inline unsigned long group_weight(struct task_struct *p, int nid, 1848 int dist) 1849 { 1850 struct numa_group *ng = deref_task_numa_group(p); 1851 unsigned long faults, total_faults; 1852 1853 if (!ng) 1854 return 0; 1855 1856 total_faults = ng->total_faults; 1857 1858 if (!total_faults) 1859 return 0; 1860 1861 faults = group_faults(p, nid); 1862 faults += score_nearby_nodes(p, nid, dist, false); 1863 1864 return 1000 * faults / total_faults; 1865 } 1866 1867 /* 1868 * If memory tiering mode is enabled, cpupid of slow memory page is 1869 * used to record scan time instead of CPU and PID. When tiering mode 1870 * is disabled at run time, the scan time (in cpupid) will be 1871 * interpreted as CPU and PID. So CPU needs to be checked to avoid to 1872 * access out of array bound. 1873 */ 1874 static inline bool cpupid_valid(int cpupid) 1875 { 1876 return cpupid_to_cpu(cpupid) < nr_cpu_ids; 1877 } 1878 1879 /* 1880 * For memory tiering mode, if there are enough free pages (more than 1881 * enough watermark defined here) in fast memory node, to take full 1882 * advantage of fast memory capacity, all recently accessed slow 1883 * memory pages will be migrated to fast memory node without 1884 * considering hot threshold. 1885 */ 1886 static bool pgdat_free_space_enough(struct pglist_data *pgdat) 1887 { 1888 int z; 1889 unsigned long enough_wmark; 1890 1891 enough_wmark = max(1UL * 1024 * 1024 * 1024 >> PAGE_SHIFT, 1892 pgdat->node_present_pages >> 4); 1893 for (z = pgdat->nr_zones - 1; z >= 0; z--) { 1894 struct zone *zone = pgdat->node_zones + z; 1895 1896 if (!populated_zone(zone)) 1897 continue; 1898 1899 if (zone_watermark_ok(zone, 0, 1900 promo_wmark_pages(zone) + enough_wmark, 1901 ZONE_MOVABLE, 0)) 1902 return true; 1903 } 1904 return false; 1905 } 1906 1907 /* 1908 * For memory tiering mode, when page tables are scanned, the scan 1909 * time will be recorded in struct page in addition to make page 1910 * PROT_NONE for slow memory page. So when the page is accessed, in 1911 * hint page fault handler, the hint page fault latency is calculated 1912 * via, 1913 * 1914 * hint page fault latency = hint page fault time - scan time 1915 * 1916 * The smaller the hint page fault latency, the higher the possibility 1917 * for the page to be hot. 1918 */ 1919 static int numa_hint_fault_latency(struct folio *folio) 1920 { 1921 int last_time, time; 1922 1923 time = jiffies_to_msecs(jiffies); 1924 last_time = folio_xchg_access_time(folio, time); 1925 1926 return (time - last_time) & PAGE_ACCESS_TIME_MASK; 1927 } 1928 1929 /* 1930 * For memory tiering mode, too high promotion/demotion throughput may 1931 * hurt application latency. So we provide a mechanism to rate limit 1932 * the number of pages that are tried to be promoted. 1933 */ 1934 static bool numa_promotion_rate_limit(struct pglist_data *pgdat, 1935 unsigned long rate_limit, int nr) 1936 { 1937 unsigned long nr_cand; 1938 unsigned int now, start; 1939 1940 now = jiffies_to_msecs(jiffies); 1941 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE, nr); 1942 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE); 1943 start = pgdat->nbp_rl_start; 1944 if (now - start > MSEC_PER_SEC && 1945 cmpxchg(&pgdat->nbp_rl_start, start, now) == start) 1946 pgdat->nbp_rl_nr_cand = nr_cand; 1947 if (nr_cand - pgdat->nbp_rl_nr_cand >= rate_limit) 1948 return true; 1949 return false; 1950 } 1951 1952 #define NUMA_MIGRATION_ADJUST_STEPS 16 1953 1954 static void numa_promotion_adjust_threshold(struct pglist_data *pgdat, 1955 unsigned long rate_limit, 1956 unsigned int ref_th) 1957 { 1958 unsigned int now, start, th_period, unit_th, th; 1959 unsigned long nr_cand, ref_cand, diff_cand; 1960 1961 now = jiffies_to_msecs(jiffies); 1962 th_period = sysctl_numa_balancing_scan_period_max; 1963 start = pgdat->nbp_th_start; 1964 if (now - start > th_period && 1965 cmpxchg(&pgdat->nbp_th_start, start, now) == start) { 1966 ref_cand = rate_limit * 1967 sysctl_numa_balancing_scan_period_max / MSEC_PER_SEC; 1968 nr_cand = node_page_state(pgdat, PGPROMOTE_CANDIDATE); 1969 diff_cand = nr_cand - pgdat->nbp_th_nr_cand; 1970 unit_th = ref_th * 2 / NUMA_MIGRATION_ADJUST_STEPS; 1971 th = pgdat->nbp_threshold ? : ref_th; 1972 if (diff_cand > ref_cand * 11 / 10) 1973 th = max(th - unit_th, unit_th); 1974 else if (diff_cand < ref_cand * 9 / 10) 1975 th = min(th + unit_th, ref_th * 2); 1976 pgdat->nbp_th_nr_cand = nr_cand; 1977 pgdat->nbp_threshold = th; 1978 } 1979 } 1980 1981 bool should_numa_migrate_memory(struct task_struct *p, struct folio *folio, 1982 int src_nid, int dst_cpu) 1983 { 1984 struct numa_group *ng = deref_curr_numa_group(p); 1985 int dst_nid = cpu_to_node(dst_cpu); 1986 int last_cpupid, this_cpupid; 1987 1988 /* 1989 * Cannot migrate to memoryless nodes. 1990 */ 1991 if (!node_state(dst_nid, N_MEMORY)) 1992 return false; 1993 1994 /* 1995 * The pages in slow memory node should be migrated according 1996 * to hot/cold instead of private/shared. 1997 */ 1998 if (folio_use_access_time(folio)) { 1999 struct pglist_data *pgdat; 2000 unsigned long rate_limit; 2001 unsigned int latency, th, def_th; 2002 long nr = folio_nr_pages(folio); 2003 2004 pgdat = NODE_DATA(dst_nid); 2005 if (pgdat_free_space_enough(pgdat)) { 2006 /* workload changed, reset hot threshold */ 2007 pgdat->nbp_threshold = 0; 2008 mod_node_page_state(pgdat, PGPROMOTE_CANDIDATE_NRL, nr); 2009 return true; 2010 } 2011 2012 def_th = sysctl_numa_balancing_hot_threshold; 2013 rate_limit = MB_TO_PAGES(sysctl_numa_balancing_promote_rate_limit); 2014 numa_promotion_adjust_threshold(pgdat, rate_limit, def_th); 2015 2016 th = pgdat->nbp_threshold ? : def_th; 2017 latency = numa_hint_fault_latency(folio); 2018 if (latency >= th) 2019 return false; 2020 2021 return !numa_promotion_rate_limit(pgdat, rate_limit, nr); 2022 } 2023 2024 this_cpupid = cpu_pid_to_cpupid(dst_cpu, current->pid); 2025 last_cpupid = folio_xchg_last_cpupid(folio, this_cpupid); 2026 2027 if (!(sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING) && 2028 !node_is_toptier(src_nid) && !cpupid_valid(last_cpupid)) 2029 return false; 2030 2031 /* 2032 * Allow first faults or private faults to migrate immediately early in 2033 * the lifetime of a task. The magic number 4 is based on waiting for 2034 * two full passes of the "multi-stage node selection" test that is 2035 * executed below. 2036 */ 2037 if ((p->numa_preferred_nid == NUMA_NO_NODE || p->numa_scan_seq <= 4) && 2038 (cpupid_pid_unset(last_cpupid) || cpupid_match_pid(p, last_cpupid))) 2039 return true; 2040 2041 /* 2042 * Multi-stage node selection is used in conjunction with a periodic 2043 * migration fault to build a temporal task<->page relation. By using 2044 * a two-stage filter we remove short/unlikely relations. 2045 * 2046 * Using P(p) ~ n_p / n_t as per frequentist probability, we can equate 2047 * a task's usage of a particular page (n_p) per total usage of this 2048 * page (n_t) (in a given time-span) to a probability. 2049 * 2050 * Our periodic faults will sample this probability and getting the 2051 * same result twice in a row, given these samples are fully 2052 * independent, is then given by P(n)^2, provided our sample period 2053 * is sufficiently short compared to the usage pattern. 2054 * 2055 * This quadric squishes small probabilities, making it less likely we 2056 * act on an unlikely task<->page relation. 2057 */ 2058 if (!cpupid_pid_unset(last_cpupid) && 2059 cpupid_to_nid(last_cpupid) != dst_nid) 2060 return false; 2061 2062 /* Always allow migrate on private faults */ 2063 if (cpupid_match_pid(p, last_cpupid)) 2064 return true; 2065 2066 /* A shared fault, but p->numa_group has not been set up yet. */ 2067 if (!ng) 2068 return true; 2069 2070 /* 2071 * Destination node is much more heavily used than the source 2072 * node? Allow migration. 2073 */ 2074 if (group_faults_cpu(ng, dst_nid) > group_faults_cpu(ng, src_nid) * 2075 ACTIVE_NODE_FRACTION) 2076 return true; 2077 2078 /* 2079 * Distribute memory according to CPU & memory use on each node, 2080 * with 3/4 hysteresis to avoid unnecessary memory migrations: 2081 * 2082 * faults_cpu(dst) 3 faults_cpu(src) 2083 * --------------- * - > --------------- 2084 * faults_mem(dst) 4 faults_mem(src) 2085 */ 2086 return group_faults_cpu(ng, dst_nid) * group_faults(p, src_nid) * 3 > 2087 group_faults_cpu(ng, src_nid) * group_faults(p, dst_nid) * 4; 2088 } 2089 2090 /* 2091 * 'numa_type' describes the node at the moment of load balancing. 2092 */ 2093 enum numa_type { 2094 /* The node has spare capacity that can be used to run more tasks. */ 2095 node_has_spare = 0, 2096 /* 2097 * The node is fully used and the tasks don't compete for more CPU 2098 * cycles. Nevertheless, some tasks might wait before running. 2099 */ 2100 node_fully_busy, 2101 /* 2102 * The node is overloaded and can't provide expected CPU cycles to all 2103 * tasks. 2104 */ 2105 node_overloaded 2106 }; 2107 2108 /* Cached statistics for all CPUs within a node */ 2109 struct numa_stats { 2110 unsigned long load; 2111 unsigned long runnable; 2112 unsigned long util; 2113 /* Total compute capacity of CPUs on a node */ 2114 unsigned long compute_capacity; 2115 unsigned int nr_running; 2116 unsigned int weight; 2117 enum numa_type node_type; 2118 int idle_cpu; 2119 }; 2120 2121 struct task_numa_env { 2122 struct task_struct *p; 2123 2124 int src_cpu, src_nid; 2125 int dst_cpu, dst_nid; 2126 int imb_numa_nr; 2127 2128 struct numa_stats src_stats, dst_stats; 2129 2130 int imbalance_pct; 2131 int dist; 2132 2133 struct task_struct *best_task; 2134 long best_imp; 2135 int best_cpu; 2136 }; 2137 2138 static unsigned long cpu_load(struct rq *rq); 2139 static unsigned long cpu_runnable(struct rq *rq); 2140 2141 static inline enum 2142 numa_type numa_classify(unsigned int imbalance_pct, 2143 struct numa_stats *ns) 2144 { 2145 if ((ns->nr_running > ns->weight) && 2146 (((ns->compute_capacity * 100) < (ns->util * imbalance_pct)) || 2147 ((ns->compute_capacity * imbalance_pct) < (ns->runnable * 100)))) 2148 return node_overloaded; 2149 2150 if ((ns->nr_running < ns->weight) || 2151 (((ns->compute_capacity * 100) > (ns->util * imbalance_pct)) && 2152 ((ns->compute_capacity * imbalance_pct) > (ns->runnable * 100)))) 2153 return node_has_spare; 2154 2155 return node_fully_busy; 2156 } 2157 2158 #ifdef CONFIG_SCHED_SMT 2159 /* Forward declarations of select_idle_sibling helpers */ 2160 static inline bool test_idle_cores(int cpu); 2161 static inline int numa_idle_core(int idle_core, int cpu) 2162 { 2163 if (!static_branch_likely(&sched_smt_present) || 2164 idle_core >= 0 || !test_idle_cores(cpu)) 2165 return idle_core; 2166 2167 /* 2168 * Prefer cores instead of packing HT siblings 2169 * and triggering future load balancing. 2170 */ 2171 if (is_core_idle(cpu)) 2172 idle_core = cpu; 2173 2174 return idle_core; 2175 } 2176 #else /* !CONFIG_SCHED_SMT: */ 2177 static inline int numa_idle_core(int idle_core, int cpu) 2178 { 2179 return idle_core; 2180 } 2181 #endif /* !CONFIG_SCHED_SMT */ 2182 2183 /* 2184 * Gather all necessary information to make NUMA balancing placement 2185 * decisions that are compatible with standard load balancer. This 2186 * borrows code and logic from update_sg_lb_stats but sharing a 2187 * common implementation is impractical. 2188 */ 2189 static void update_numa_stats(struct task_numa_env *env, 2190 struct numa_stats *ns, int nid, 2191 bool find_idle) 2192 { 2193 int cpu, idle_core = -1; 2194 2195 memset(ns, 0, sizeof(*ns)); 2196 ns->idle_cpu = -1; 2197 2198 rcu_read_lock(); 2199 for_each_cpu(cpu, cpumask_of_node(nid)) { 2200 struct rq *rq = cpu_rq(cpu); 2201 2202 ns->load += cpu_load(rq); 2203 ns->runnable += cpu_runnable(rq); 2204 ns->util += cpu_util_cfs(cpu); 2205 ns->nr_running += rq->cfs.h_nr_runnable; 2206 ns->compute_capacity += capacity_of(cpu); 2207 2208 if (find_idle && idle_core < 0 && !rq->nr_running && idle_cpu(cpu)) { 2209 if (READ_ONCE(rq->numa_migrate_on) || 2210 !cpumask_test_cpu(cpu, env->p->cpus_ptr)) 2211 continue; 2212 2213 if (ns->idle_cpu == -1) 2214 ns->idle_cpu = cpu; 2215 2216 idle_core = numa_idle_core(idle_core, cpu); 2217 } 2218 } 2219 rcu_read_unlock(); 2220 2221 ns->weight = cpumask_weight(cpumask_of_node(nid)); 2222 2223 ns->node_type = numa_classify(env->imbalance_pct, ns); 2224 2225 if (idle_core >= 0) 2226 ns->idle_cpu = idle_core; 2227 } 2228 2229 static void task_numa_assign(struct task_numa_env *env, 2230 struct task_struct *p, long imp) 2231 { 2232 struct rq *rq = cpu_rq(env->dst_cpu); 2233 2234 /* Check if run-queue part of active NUMA balance. */ 2235 if (env->best_cpu != env->dst_cpu && xchg(&rq->numa_migrate_on, 1)) { 2236 int cpu; 2237 int start = env->dst_cpu; 2238 2239 /* Find alternative idle CPU. */ 2240 for_each_cpu_wrap(cpu, cpumask_of_node(env->dst_nid), start + 1) { 2241 if (cpu == env->best_cpu || !idle_cpu(cpu) || 2242 !cpumask_test_cpu(cpu, env->p->cpus_ptr)) { 2243 continue; 2244 } 2245 2246 env->dst_cpu = cpu; 2247 rq = cpu_rq(env->dst_cpu); 2248 if (!xchg(&rq->numa_migrate_on, 1)) 2249 goto assign; 2250 } 2251 2252 /* Failed to find an alternative idle CPU */ 2253 return; 2254 } 2255 2256 assign: 2257 /* 2258 * Clear previous best_cpu/rq numa-migrate flag, since task now 2259 * found a better CPU to move/swap. 2260 */ 2261 if (env->best_cpu != -1 && env->best_cpu != env->dst_cpu) { 2262 rq = cpu_rq(env->best_cpu); 2263 WRITE_ONCE(rq->numa_migrate_on, 0); 2264 } 2265 2266 if (env->best_task) 2267 put_task_struct(env->best_task); 2268 if (p) 2269 get_task_struct(p); 2270 2271 env->best_task = p; 2272 env->best_imp = imp; 2273 env->best_cpu = env->dst_cpu; 2274 } 2275 2276 static bool load_too_imbalanced(long src_load, long dst_load, 2277 struct task_numa_env *env) 2278 { 2279 long imb, old_imb; 2280 long orig_src_load, orig_dst_load; 2281 long src_capacity, dst_capacity; 2282 2283 /* 2284 * The load is corrected for the CPU capacity available on each node. 2285 * 2286 * src_load dst_load 2287 * ------------ vs --------- 2288 * src_capacity dst_capacity 2289 */ 2290 src_capacity = env->src_stats.compute_capacity; 2291 dst_capacity = env->dst_stats.compute_capacity; 2292 2293 imb = abs(dst_load * src_capacity - src_load * dst_capacity); 2294 2295 orig_src_load = env->src_stats.load; 2296 orig_dst_load = env->dst_stats.load; 2297 2298 old_imb = abs(orig_dst_load * src_capacity - orig_src_load * dst_capacity); 2299 2300 /* Would this change make things worse? */ 2301 return (imb > old_imb); 2302 } 2303 2304 /* 2305 * Maximum NUMA importance can be 1998 (2*999); 2306 * SMALLIMP @ 30 would be close to 1998/64. 2307 * Used to deter task migration. 2308 */ 2309 #define SMALLIMP 30 2310 2311 /* 2312 * This checks if the overall compute and NUMA accesses of the system would 2313 * be improved if the source tasks was migrated to the target dst_cpu taking 2314 * into account that it might be best if task running on the dst_cpu should 2315 * be exchanged with the source task 2316 */ 2317 static bool task_numa_compare(struct task_numa_env *env, 2318 long taskimp, long groupimp, bool maymove) 2319 { 2320 struct numa_group *cur_ng, *p_ng = deref_curr_numa_group(env->p); 2321 struct rq *dst_rq = cpu_rq(env->dst_cpu); 2322 long imp = p_ng ? groupimp : taskimp; 2323 struct task_struct *cur; 2324 long src_load, dst_load; 2325 int dist = env->dist; 2326 long moveimp = imp; 2327 long load; 2328 bool stopsearch = false; 2329 2330 if (READ_ONCE(dst_rq->numa_migrate_on)) 2331 return false; 2332 2333 rcu_read_lock(); 2334 cur = rcu_dereference_all(dst_rq->curr); 2335 if (cur && ((cur->flags & (PF_EXITING | PF_KTHREAD)) || 2336 !cur->mm)) 2337 cur = NULL; 2338 2339 /* 2340 * Because we have preemption enabled we can get migrated around and 2341 * end try selecting ourselves (current == env->p) as a swap candidate. 2342 */ 2343 if (cur == env->p) { 2344 stopsearch = true; 2345 goto unlock; 2346 } 2347 2348 if (!cur) { 2349 if (maymove && moveimp >= env->best_imp) 2350 goto assign; 2351 else 2352 goto unlock; 2353 } 2354 2355 /* Skip this swap candidate if cannot move to the source cpu. */ 2356 if (!cpumask_test_cpu(env->src_cpu, cur->cpus_ptr)) 2357 goto unlock; 2358 2359 /* 2360 * Skip this swap candidate if it is not moving to its preferred 2361 * node and the best task is. 2362 */ 2363 if (env->best_task && 2364 env->best_task->numa_preferred_nid == env->src_nid && 2365 cur->numa_preferred_nid != env->src_nid) { 2366 goto unlock; 2367 } 2368 2369 /* 2370 * "imp" is the fault differential for the source task between the 2371 * source and destination node. Calculate the total differential for 2372 * the source task and potential destination task. The more negative 2373 * the value is, the more remote accesses that would be expected to 2374 * be incurred if the tasks were swapped. 2375 * 2376 * If dst and source tasks are in the same NUMA group, or not 2377 * in any group then look only at task weights. 2378 */ 2379 cur_ng = rcu_dereference_all(cur->numa_group); 2380 if (cur_ng == p_ng) { 2381 /* 2382 * Do not swap within a group or between tasks that have 2383 * no group if there is spare capacity. Swapping does 2384 * not address the load imbalance and helps one task at 2385 * the cost of punishing another. 2386 */ 2387 if (env->dst_stats.node_type == node_has_spare) 2388 goto unlock; 2389 2390 imp = taskimp + task_weight(cur, env->src_nid, dist) - 2391 task_weight(cur, env->dst_nid, dist); 2392 /* 2393 * Add some hysteresis to prevent swapping the 2394 * tasks within a group over tiny differences. 2395 */ 2396 if (cur_ng) 2397 imp -= imp / 16; 2398 } else { 2399 /* 2400 * Compare the group weights. If a task is all by itself 2401 * (not part of a group), use the task weight instead. 2402 */ 2403 if (cur_ng && p_ng) 2404 imp += group_weight(cur, env->src_nid, dist) - 2405 group_weight(cur, env->dst_nid, dist); 2406 else 2407 imp += task_weight(cur, env->src_nid, dist) - 2408 task_weight(cur, env->dst_nid, dist); 2409 } 2410 2411 /* Discourage picking a task already on its preferred node */ 2412 if (cur->numa_preferred_nid == env->dst_nid) 2413 imp -= imp / 16; 2414 2415 /* 2416 * Encourage picking a task that moves to its preferred node. 2417 * This potentially makes imp larger than it's maximum of 2418 * 1998 (see SMALLIMP and task_weight for why) but in this 2419 * case, it does not matter. 2420 */ 2421 if (cur->numa_preferred_nid == env->src_nid) 2422 imp += imp / 8; 2423 2424 if (maymove && moveimp > imp && moveimp > env->best_imp) { 2425 imp = moveimp; 2426 cur = NULL; 2427 goto assign; 2428 } 2429 2430 /* 2431 * Prefer swapping with a task moving to its preferred node over a 2432 * task that is not. 2433 */ 2434 if (env->best_task && cur->numa_preferred_nid == env->src_nid && 2435 env->best_task->numa_preferred_nid != env->src_nid) { 2436 goto assign; 2437 } 2438 2439 /* 2440 * If the NUMA importance is less than SMALLIMP, 2441 * task migration might only result in ping pong 2442 * of tasks and also hurt performance due to cache 2443 * misses. 2444 */ 2445 if (imp < SMALLIMP || imp <= env->best_imp + SMALLIMP / 2) 2446 goto unlock; 2447 2448 /* 2449 * In the overloaded case, try and keep the load balanced. 2450 */ 2451 load = task_h_load(env->p) - task_h_load(cur); 2452 if (!load) 2453 goto assign; 2454 2455 dst_load = env->dst_stats.load + load; 2456 src_load = env->src_stats.load - load; 2457 2458 if (load_too_imbalanced(src_load, dst_load, env)) 2459 goto unlock; 2460 2461 assign: 2462 /* Evaluate an idle CPU for a task numa move. */ 2463 if (!cur) { 2464 int cpu = env->dst_stats.idle_cpu; 2465 2466 /* Nothing cached so current CPU went idle since the search. */ 2467 if (cpu < 0) 2468 cpu = env->dst_cpu; 2469 2470 /* 2471 * If the CPU is no longer truly idle and the previous best CPU 2472 * is, keep using it. 2473 */ 2474 if (!idle_cpu(cpu) && env->best_cpu >= 0 && 2475 idle_cpu(env->best_cpu)) { 2476 cpu = env->best_cpu; 2477 } 2478 2479 env->dst_cpu = cpu; 2480 } 2481 2482 task_numa_assign(env, cur, imp); 2483 2484 /* 2485 * If a move to idle is allowed because there is capacity or load 2486 * balance improves then stop the search. While a better swap 2487 * candidate may exist, a search is not free. 2488 */ 2489 if (maymove && !cur && env->best_cpu >= 0 && idle_cpu(env->best_cpu)) 2490 stopsearch = true; 2491 2492 /* 2493 * If a swap candidate must be identified and the current best task 2494 * moves its preferred node then stop the search. 2495 */ 2496 if (!maymove && env->best_task && 2497 env->best_task->numa_preferred_nid == env->src_nid) { 2498 stopsearch = true; 2499 } 2500 unlock: 2501 rcu_read_unlock(); 2502 2503 return stopsearch; 2504 } 2505 2506 static void task_numa_find_cpu(struct task_numa_env *env, 2507 long taskimp, long groupimp) 2508 { 2509 bool maymove = false; 2510 int cpu; 2511 2512 /* 2513 * If dst node has spare capacity, then check if there is an 2514 * imbalance that would be overruled by the load balancer. 2515 */ 2516 if (env->dst_stats.node_type == node_has_spare) { 2517 unsigned int imbalance; 2518 int src_running, dst_running; 2519 2520 /* 2521 * Would movement cause an imbalance? Note that if src has 2522 * more running tasks that the imbalance is ignored as the 2523 * move improves the imbalance from the perspective of the 2524 * CPU load balancer. 2525 * */ 2526 src_running = env->src_stats.nr_running - 1; 2527 dst_running = env->dst_stats.nr_running + 1; 2528 imbalance = max(0, dst_running - src_running); 2529 imbalance = adjust_numa_imbalance(imbalance, dst_running, 2530 env->imb_numa_nr); 2531 2532 /* Use idle CPU if there is no imbalance */ 2533 if (!imbalance) { 2534 maymove = true; 2535 if (env->dst_stats.idle_cpu >= 0) { 2536 env->dst_cpu = env->dst_stats.idle_cpu; 2537 task_numa_assign(env, NULL, 0); 2538 return; 2539 } 2540 } 2541 } else { 2542 long src_load, dst_load, load; 2543 /* 2544 * If the improvement from just moving env->p direction is better 2545 * than swapping tasks around, check if a move is possible. 2546 */ 2547 load = task_h_load(env->p); 2548 dst_load = env->dst_stats.load + load; 2549 src_load = env->src_stats.load - load; 2550 maymove = !load_too_imbalanced(src_load, dst_load, env); 2551 } 2552 2553 /* Skip CPUs if the source task cannot migrate */ 2554 for_each_cpu_and(cpu, cpumask_of_node(env->dst_nid), env->p->cpus_ptr) { 2555 env->dst_cpu = cpu; 2556 if (task_numa_compare(env, taskimp, groupimp, maymove)) 2557 break; 2558 } 2559 } 2560 2561 static int task_numa_migrate(struct task_struct *p) 2562 { 2563 struct task_numa_env env = { 2564 .p = p, 2565 2566 .src_cpu = task_cpu(p), 2567 .src_nid = task_node(p), 2568 2569 .imbalance_pct = 112, 2570 2571 .best_task = NULL, 2572 .best_imp = 0, 2573 .best_cpu = -1, 2574 }; 2575 unsigned long taskweight, groupweight; 2576 struct sched_domain *sd; 2577 long taskimp, groupimp; 2578 struct numa_group *ng; 2579 struct rq *best_rq; 2580 int nid, ret, dist; 2581 2582 /* 2583 * Pick the lowest SD_NUMA domain, as that would have the smallest 2584 * imbalance and would be the first to start moving tasks about. 2585 * 2586 * And we want to avoid any moving of tasks about, as that would create 2587 * random movement of tasks -- counter the numa conditions we're trying 2588 * to satisfy here. 2589 */ 2590 rcu_read_lock(); 2591 sd = rcu_dereference_all(per_cpu(sd_numa, env.src_cpu)); 2592 if (sd) { 2593 env.imbalance_pct = 100 + (sd->imbalance_pct - 100) / 2; 2594 env.imb_numa_nr = sd->imb_numa_nr; 2595 } 2596 rcu_read_unlock(); 2597 2598 /* 2599 * Cpusets can break the scheduler domain tree into smaller 2600 * balance domains, some of which do not cross NUMA boundaries. 2601 * Tasks that are "trapped" in such domains cannot be migrated 2602 * elsewhere, so there is no point in (re)trying. 2603 */ 2604 if (unlikely(!sd)) { 2605 sched_setnuma(p, task_node(p)); 2606 return -EINVAL; 2607 } 2608 2609 env.dst_nid = p->numa_preferred_nid; 2610 dist = env.dist = node_distance(env.src_nid, env.dst_nid); 2611 taskweight = task_weight(p, env.src_nid, dist); 2612 groupweight = group_weight(p, env.src_nid, dist); 2613 update_numa_stats(&env, &env.src_stats, env.src_nid, false); 2614 taskimp = task_weight(p, env.dst_nid, dist) - taskweight; 2615 groupimp = group_weight(p, env.dst_nid, dist) - groupweight; 2616 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true); 2617 2618 /* Try to find a spot on the preferred nid. */ 2619 task_numa_find_cpu(&env, taskimp, groupimp); 2620 2621 /* 2622 * Look at other nodes in these cases: 2623 * - there is no space available on the preferred_nid 2624 * - the task is part of a numa_group that is interleaved across 2625 * multiple NUMA nodes; in order to better consolidate the group, 2626 * we need to check other locations. 2627 */ 2628 ng = deref_curr_numa_group(p); 2629 if (env.best_cpu == -1 || (ng && ng->active_nodes > 1)) { 2630 for_each_node_state(nid, N_CPU) { 2631 if (nid == env.src_nid || nid == p->numa_preferred_nid) 2632 continue; 2633 2634 dist = node_distance(env.src_nid, env.dst_nid); 2635 if (sched_numa_topology_type == NUMA_BACKPLANE && 2636 dist != env.dist) { 2637 taskweight = task_weight(p, env.src_nid, dist); 2638 groupweight = group_weight(p, env.src_nid, dist); 2639 } 2640 2641 /* Only consider nodes where both task and groups benefit */ 2642 taskimp = task_weight(p, nid, dist) - taskweight; 2643 groupimp = group_weight(p, nid, dist) - groupweight; 2644 if (taskimp < 0 && groupimp < 0) 2645 continue; 2646 2647 env.dist = dist; 2648 env.dst_nid = nid; 2649 update_numa_stats(&env, &env.dst_stats, env.dst_nid, true); 2650 task_numa_find_cpu(&env, taskimp, groupimp); 2651 } 2652 } 2653 2654 /* 2655 * If the task is part of a workload that spans multiple NUMA nodes, 2656 * and is migrating into one of the workload's active nodes, remember 2657 * this node as the task's preferred numa node, so the workload can 2658 * settle down. 2659 * A task that migrated to a second choice node will be better off 2660 * trying for a better one later. Do not set the preferred node here. 2661 */ 2662 if (ng) { 2663 if (env.best_cpu == -1) 2664 nid = env.src_nid; 2665 else 2666 nid = cpu_to_node(env.best_cpu); 2667 2668 if (nid != p->numa_preferred_nid) 2669 sched_setnuma(p, nid); 2670 } 2671 2672 /* No better CPU than the current one was found. */ 2673 if (env.best_cpu == -1) { 2674 trace_sched_stick_numa(p, env.src_cpu, NULL, -1); 2675 return -EAGAIN; 2676 } 2677 2678 best_rq = cpu_rq(env.best_cpu); 2679 if (env.best_task == NULL) { 2680 ret = migrate_task_to(p, env.best_cpu); 2681 WRITE_ONCE(best_rq->numa_migrate_on, 0); 2682 if (ret != 0) 2683 trace_sched_stick_numa(p, env.src_cpu, NULL, env.best_cpu); 2684 return ret; 2685 } 2686 2687 ret = migrate_swap(p, env.best_task, env.best_cpu, env.src_cpu); 2688 WRITE_ONCE(best_rq->numa_migrate_on, 0); 2689 2690 if (ret != 0) 2691 trace_sched_stick_numa(p, env.src_cpu, env.best_task, env.best_cpu); 2692 put_task_struct(env.best_task); 2693 return ret; 2694 } 2695 2696 /* Attempt to migrate a task to a CPU on the preferred node. */ 2697 static void numa_migrate_preferred(struct task_struct *p) 2698 { 2699 unsigned long interval = HZ; 2700 2701 /* This task has no NUMA fault statistics yet */ 2702 if (unlikely(p->numa_preferred_nid == NUMA_NO_NODE || !p->numa_faults)) 2703 return; 2704 2705 /* Periodically retry migrating the task to the preferred node */ 2706 interval = min(interval, msecs_to_jiffies(p->numa_scan_period) / 16); 2707 p->numa_migrate_retry = jiffies + interval; 2708 2709 /* Success if task is already running on preferred CPU */ 2710 if (task_node(p) == p->numa_preferred_nid) 2711 return; 2712 2713 /* Otherwise, try migrate to a CPU on the preferred node */ 2714 task_numa_migrate(p); 2715 } 2716 2717 /* 2718 * Find out how many nodes the workload is actively running on. Do this by 2719 * tracking the nodes from which NUMA hinting faults are triggered. This can 2720 * be different from the set of nodes where the workload's memory is currently 2721 * located. 2722 */ 2723 static void numa_group_count_active_nodes(struct numa_group *numa_group) 2724 { 2725 unsigned long faults, max_faults = 0; 2726 int nid, active_nodes = 0; 2727 2728 for_each_node_state(nid, N_CPU) { 2729 faults = group_faults_cpu(numa_group, nid); 2730 if (faults > max_faults) 2731 max_faults = faults; 2732 } 2733 2734 for_each_node_state(nid, N_CPU) { 2735 faults = group_faults_cpu(numa_group, nid); 2736 if (faults * ACTIVE_NODE_FRACTION > max_faults) 2737 active_nodes++; 2738 } 2739 2740 numa_group->max_faults_cpu = max_faults; 2741 numa_group->active_nodes = active_nodes; 2742 } 2743 2744 /* 2745 * When adapting the scan rate, the period is divided into NUMA_PERIOD_SLOTS 2746 * increments. The more local the fault statistics are, the higher the scan 2747 * period will be for the next scan window. If local/(local+remote) ratio is 2748 * below NUMA_PERIOD_THRESHOLD (where range of ratio is 1..NUMA_PERIOD_SLOTS) 2749 * the scan period will decrease. Aim for 70% local accesses. 2750 */ 2751 #define NUMA_PERIOD_SLOTS 10 2752 #define NUMA_PERIOD_THRESHOLD 7 2753 2754 /* 2755 * Increase the scan period (slow down scanning) if the majority of 2756 * our memory is already on our local node, or if the majority of 2757 * the page accesses are shared with other processes. 2758 * Otherwise, decrease the scan period. 2759 */ 2760 static void update_task_scan_period(struct task_struct *p, 2761 unsigned long shared, unsigned long private) 2762 { 2763 unsigned int period_slot; 2764 int lr_ratio, ps_ratio; 2765 int diff; 2766 2767 unsigned long remote = p->numa_faults_locality[0]; 2768 unsigned long local = p->numa_faults_locality[1]; 2769 2770 /* 2771 * If there were no record hinting faults then either the task is 2772 * completely idle or all activity is in areas that are not of interest 2773 * to automatic numa balancing. Related to that, if there were failed 2774 * migration then it implies we are migrating too quickly or the local 2775 * node is overloaded. In either case, scan slower 2776 */ 2777 if (local + shared == 0 || p->numa_faults_locality[2]) { 2778 p->numa_scan_period = min(p->numa_scan_period_max, 2779 p->numa_scan_period << 1); 2780 2781 p->mm->numa_next_scan = jiffies + 2782 msecs_to_jiffies(p->numa_scan_period); 2783 2784 return; 2785 } 2786 2787 /* 2788 * Prepare to scale scan period relative to the current period. 2789 * == NUMA_PERIOD_THRESHOLD scan period stays the same 2790 * < NUMA_PERIOD_THRESHOLD scan period decreases (scan faster) 2791 * >= NUMA_PERIOD_THRESHOLD scan period increases (scan slower) 2792 */ 2793 period_slot = DIV_ROUND_UP(p->numa_scan_period, NUMA_PERIOD_SLOTS); 2794 lr_ratio = (local * NUMA_PERIOD_SLOTS) / (local + remote); 2795 ps_ratio = (private * NUMA_PERIOD_SLOTS) / (private + shared); 2796 2797 if (ps_ratio >= NUMA_PERIOD_THRESHOLD) { 2798 /* 2799 * Most memory accesses are local. There is no need to 2800 * do fast NUMA scanning, since memory is already local. 2801 */ 2802 int slot = ps_ratio - NUMA_PERIOD_THRESHOLD; 2803 if (!slot) 2804 slot = 1; 2805 diff = slot * period_slot; 2806 } else if (lr_ratio >= NUMA_PERIOD_THRESHOLD) { 2807 /* 2808 * Most memory accesses are shared with other tasks. 2809 * There is no point in continuing fast NUMA scanning, 2810 * since other tasks may just move the memory elsewhere. 2811 */ 2812 int slot = lr_ratio - NUMA_PERIOD_THRESHOLD; 2813 if (!slot) 2814 slot = 1; 2815 diff = slot * period_slot; 2816 } else { 2817 /* 2818 * Private memory faults exceed (SLOTS-THRESHOLD)/SLOTS, 2819 * yet they are not on the local NUMA node. Speed up 2820 * NUMA scanning to get the memory moved over. 2821 */ 2822 int ratio = max(lr_ratio, ps_ratio); 2823 diff = -(NUMA_PERIOD_THRESHOLD - ratio) * period_slot; 2824 } 2825 2826 p->numa_scan_period = clamp(p->numa_scan_period + diff, 2827 task_scan_min(p), task_scan_max(p)); 2828 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality)); 2829 } 2830 2831 /* 2832 * Get the fraction of time the task has been running since the last 2833 * NUMA placement cycle. The scheduler keeps similar statistics, but 2834 * decays those on a 32ms period, which is orders of magnitude off 2835 * from the dozens-of-seconds NUMA balancing period. Use the scheduler 2836 * stats only if the task is so new there are no NUMA statistics yet. 2837 */ 2838 static u64 numa_get_avg_runtime(struct task_struct *p, u64 *period) 2839 { 2840 u64 runtime, delta, now; 2841 /* Use the start of this time slice to avoid calculations. */ 2842 now = p->se.exec_start; 2843 runtime = p->se.sum_exec_runtime; 2844 2845 if (p->last_task_numa_placement) { 2846 delta = runtime - p->last_sum_exec_runtime; 2847 *period = now - p->last_task_numa_placement; 2848 2849 /* Avoid time going backwards, prevent potential divide error: */ 2850 if (unlikely((s64)*period < 0)) 2851 *period = 0; 2852 } else { 2853 delta = p->se.avg.load_sum; 2854 *period = LOAD_AVG_MAX; 2855 } 2856 2857 p->last_sum_exec_runtime = runtime; 2858 p->last_task_numa_placement = now; 2859 2860 return delta; 2861 } 2862 2863 /* 2864 * Determine the preferred nid for a task in a numa_group. This needs to 2865 * be done in a way that produces consistent results with group_weight, 2866 * otherwise workloads might not converge. 2867 */ 2868 static int preferred_group_nid(struct task_struct *p, int nid) 2869 { 2870 nodemask_t nodes; 2871 int dist; 2872 2873 /* Direct connections between all NUMA nodes. */ 2874 if (sched_numa_topology_type == NUMA_DIRECT) 2875 return nid; 2876 2877 /* 2878 * On a system with glueless mesh NUMA topology, group_weight 2879 * scores nodes according to the number of NUMA hinting faults on 2880 * both the node itself, and on nearby nodes. 2881 */ 2882 if (sched_numa_topology_type == NUMA_GLUELESS_MESH) { 2883 unsigned long score, max_score = 0; 2884 int node, max_node = nid; 2885 2886 dist = sched_max_numa_distance; 2887 2888 for_each_node_state(node, N_CPU) { 2889 score = group_weight(p, node, dist); 2890 if (score > max_score) { 2891 max_score = score; 2892 max_node = node; 2893 } 2894 } 2895 return max_node; 2896 } 2897 2898 /* 2899 * Finding the preferred nid in a system with NUMA backplane 2900 * interconnect topology is more involved. The goal is to locate 2901 * tasks from numa_groups near each other in the system, and 2902 * untangle workloads from different sides of the system. This requires 2903 * searching down the hierarchy of node groups, recursively searching 2904 * inside the highest scoring group of nodes. The nodemask tricks 2905 * keep the complexity of the search down. 2906 */ 2907 nodes = node_states[N_CPU]; 2908 for (dist = sched_max_numa_distance; dist > LOCAL_DISTANCE; dist--) { 2909 unsigned long max_faults = 0; 2910 nodemask_t max_group = NODE_MASK_NONE; 2911 int a, b; 2912 2913 /* Are there nodes at this distance from each other? */ 2914 if (!find_numa_distance(dist)) 2915 continue; 2916 2917 for_each_node_mask(a, nodes) { 2918 unsigned long faults = 0; 2919 nodemask_t this_group; 2920 nodes_clear(this_group); 2921 2922 /* Sum group's NUMA faults; includes a==b case. */ 2923 for_each_node_mask(b, nodes) { 2924 if (node_distance(a, b) < dist) { 2925 faults += group_faults(p, b); 2926 node_set(b, this_group); 2927 node_clear(b, nodes); 2928 } 2929 } 2930 2931 /* Remember the top group. */ 2932 if (faults > max_faults) { 2933 max_faults = faults; 2934 max_group = this_group; 2935 /* 2936 * subtle: at the smallest distance there is 2937 * just one node left in each "group", the 2938 * winner is the preferred nid. 2939 */ 2940 nid = a; 2941 } 2942 } 2943 /* Next round, evaluate the nodes within max_group. */ 2944 if (!max_faults) 2945 break; 2946 nodes = max_group; 2947 } 2948 return nid; 2949 } 2950 2951 static void task_numa_placement(struct task_struct *p) 2952 __context_unsafe(/* conditional locking */) 2953 { 2954 int seq, nid, max_nid = NUMA_NO_NODE; 2955 unsigned long max_faults = 0; 2956 unsigned long fault_types[2] = { 0, 0 }; 2957 unsigned long total_faults; 2958 u64 runtime, period; 2959 spinlock_t *group_lock = NULL; 2960 struct numa_group *ng; 2961 2962 /* 2963 * The p->mm->numa_scan_seq field gets updated without 2964 * exclusive access. Use READ_ONCE() here to ensure 2965 * that the field is read in a single access: 2966 */ 2967 seq = READ_ONCE(p->mm->numa_scan_seq); 2968 if (p->numa_scan_seq == seq) 2969 return; 2970 p->numa_scan_seq = seq; 2971 p->numa_scan_period_max = task_scan_max(p); 2972 2973 total_faults = p->numa_faults_locality[0] + 2974 p->numa_faults_locality[1]; 2975 runtime = numa_get_avg_runtime(p, &period); 2976 2977 /* If the task is part of a group prevent parallel updates to group stats */ 2978 ng = deref_curr_numa_group(p); 2979 if (ng) { 2980 group_lock = &ng->lock; 2981 spin_lock_irq(group_lock); 2982 } 2983 2984 /* Find the node with the highest number of faults */ 2985 for_each_online_node(nid) { 2986 /* Keep track of the offsets in numa_faults array */ 2987 int mem_idx, membuf_idx, cpu_idx, cpubuf_idx; 2988 unsigned long faults = 0, group_faults = 0; 2989 int priv; 2990 2991 for (priv = 0; priv < NR_NUMA_HINT_FAULT_TYPES; priv++) { 2992 long diff, f_diff, f_weight; 2993 2994 mem_idx = task_faults_idx(NUMA_MEM, nid, priv); 2995 membuf_idx = task_faults_idx(NUMA_MEMBUF, nid, priv); 2996 cpu_idx = task_faults_idx(NUMA_CPU, nid, priv); 2997 cpubuf_idx = task_faults_idx(NUMA_CPUBUF, nid, priv); 2998 2999 /* Decay existing window, copy faults since last scan */ 3000 diff = p->numa_faults[membuf_idx] - p->numa_faults[mem_idx] / 2; 3001 fault_types[priv] += p->numa_faults[membuf_idx]; 3002 p->numa_faults[membuf_idx] = 0; 3003 3004 /* 3005 * Normalize the faults_from, so all tasks in a group 3006 * count according to CPU use, instead of by the raw 3007 * number of faults. Tasks with little runtime have 3008 * little over-all impact on throughput, and thus their 3009 * faults are less important. 3010 */ 3011 f_weight = div64_u64(runtime << 16, period + 1); 3012 f_weight = (f_weight * p->numa_faults[cpubuf_idx]) / 3013 (total_faults + 1); 3014 f_diff = f_weight - p->numa_faults[cpu_idx] / 2; 3015 p->numa_faults[cpubuf_idx] = 0; 3016 3017 p->numa_faults[mem_idx] += diff; 3018 p->numa_faults[cpu_idx] += f_diff; 3019 faults += p->numa_faults[mem_idx]; 3020 p->total_numa_faults += diff; 3021 if (ng) { 3022 /* 3023 * safe because we can only change our own group 3024 * 3025 * mem_idx represents the offset for a given 3026 * nid and priv in a specific region because it 3027 * is at the beginning of the numa_faults array. 3028 */ 3029 ng->faults[mem_idx] += diff; 3030 ng->faults[cpu_idx] += f_diff; 3031 ng->total_faults += diff; 3032 group_faults += ng->faults[mem_idx]; 3033 } 3034 } 3035 3036 if (!ng) { 3037 if (faults > max_faults) { 3038 max_faults = faults; 3039 max_nid = nid; 3040 } 3041 } else if (group_faults > max_faults) { 3042 max_faults = group_faults; 3043 max_nid = nid; 3044 } 3045 } 3046 3047 /* Cannot migrate task to CPU-less node */ 3048 max_nid = numa_nearest_node(max_nid, N_CPU); 3049 3050 if (ng) { 3051 numa_group_count_active_nodes(ng); 3052 spin_unlock_irq(group_lock); 3053 max_nid = preferred_group_nid(p, max_nid); 3054 } 3055 3056 if (max_faults) { 3057 /* Set the new preferred node */ 3058 if (max_nid != p->numa_preferred_nid) 3059 sched_setnuma(p, max_nid); 3060 } 3061 3062 update_task_scan_period(p, fault_types[0], fault_types[1]); 3063 } 3064 3065 static inline int get_numa_group(struct numa_group *grp) 3066 { 3067 return refcount_inc_not_zero(&grp->refcount); 3068 } 3069 3070 static inline void put_numa_group(struct numa_group *grp) 3071 { 3072 if (refcount_dec_and_test(&grp->refcount)) 3073 kfree_rcu(grp, rcu); 3074 } 3075 3076 static void task_numa_group(struct task_struct *p, int cpupid, int flags, 3077 int *priv) 3078 { 3079 struct numa_group *grp, *my_grp; 3080 struct task_struct *tsk; 3081 bool join = false; 3082 int cpu = cpupid_to_cpu(cpupid); 3083 int i; 3084 3085 if (unlikely(!deref_curr_numa_group(p))) { 3086 unsigned int size = sizeof(struct numa_group) + 3087 NR_NUMA_HINT_FAULT_STATS * 3088 nr_node_ids * sizeof(unsigned long); 3089 3090 grp = kzalloc(size, GFP_KERNEL | __GFP_NOWARN); 3091 if (!grp) 3092 return; 3093 3094 refcount_set(&grp->refcount, 1); 3095 grp->active_nodes = 1; 3096 grp->max_faults_cpu = 0; 3097 spin_lock_init(&grp->lock); 3098 grp->gid = p->pid; 3099 3100 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) 3101 grp->faults[i] = p->numa_faults[i]; 3102 3103 grp->total_faults = p->total_numa_faults; 3104 3105 grp->nr_tasks++; 3106 rcu_assign_pointer(p->numa_group, grp); 3107 } 3108 3109 rcu_read_lock(); 3110 tsk = READ_ONCE(cpu_rq(cpu)->curr); 3111 3112 if (!cpupid_match_pid(tsk, cpupid)) 3113 goto no_join; 3114 3115 grp = rcu_dereference_all(tsk->numa_group); 3116 if (!grp) 3117 goto no_join; 3118 3119 my_grp = deref_curr_numa_group(p); 3120 if (grp == my_grp) 3121 goto no_join; 3122 3123 /* 3124 * Only join the other group if its bigger; if we're the bigger group, 3125 * the other task will join us. 3126 */ 3127 if (my_grp->nr_tasks > grp->nr_tasks) 3128 goto no_join; 3129 3130 /* 3131 * Tie-break on the grp address. 3132 */ 3133 if (my_grp->nr_tasks == grp->nr_tasks && my_grp > grp) 3134 goto no_join; 3135 3136 /* Always join threads in the same process. */ 3137 if (tsk->mm == current->mm) 3138 join = true; 3139 3140 /* Simple filter to avoid false positives due to PID collisions */ 3141 if (flags & TNF_SHARED) 3142 join = true; 3143 3144 /* Update priv based on whether false sharing was detected */ 3145 *priv = !join; 3146 3147 if (join && !get_numa_group(grp)) 3148 goto no_join; 3149 3150 rcu_read_unlock(); 3151 3152 if (!join) 3153 return; 3154 3155 WARN_ON_ONCE(irqs_disabled()); 3156 double_lock_irq(&my_grp->lock, &grp->lock); 3157 3158 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) { 3159 my_grp->faults[i] -= p->numa_faults[i]; 3160 grp->faults[i] += p->numa_faults[i]; 3161 } 3162 my_grp->total_faults -= p->total_numa_faults; 3163 grp->total_faults += p->total_numa_faults; 3164 3165 my_grp->nr_tasks--; 3166 grp->nr_tasks++; 3167 3168 spin_unlock(&my_grp->lock); 3169 spin_unlock_irq(&grp->lock); 3170 3171 rcu_assign_pointer(p->numa_group, grp); 3172 3173 put_numa_group(my_grp); 3174 return; 3175 3176 no_join: 3177 rcu_read_unlock(); 3178 return; 3179 } 3180 3181 /* 3182 * Get rid of NUMA statistics associated with a task (either current or dead). 3183 * If @final is set, the task is dead and has reached refcount zero, so we can 3184 * safely free all relevant data structures. Otherwise, there might be 3185 * concurrent reads from places like load balancing and procfs, and we should 3186 * reset the data back to default state without freeing ->numa_faults. 3187 */ 3188 void task_numa_free(struct task_struct *p, bool final) 3189 { 3190 /* safe: p either is current or is being freed by current */ 3191 struct numa_group *grp = rcu_dereference_raw(p->numa_group); 3192 unsigned long *numa_faults = p->numa_faults; 3193 unsigned long flags; 3194 int i; 3195 3196 if (!numa_faults) 3197 return; 3198 3199 if (grp) { 3200 spin_lock_irqsave(&grp->lock, flags); 3201 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) 3202 grp->faults[i] -= p->numa_faults[i]; 3203 grp->total_faults -= p->total_numa_faults; 3204 3205 grp->nr_tasks--; 3206 spin_unlock_irqrestore(&grp->lock, flags); 3207 RCU_INIT_POINTER(p->numa_group, NULL); 3208 put_numa_group(grp); 3209 } 3210 3211 if (final) { 3212 p->numa_faults = NULL; 3213 kfree(numa_faults); 3214 } else { 3215 p->total_numa_faults = 0; 3216 for (i = 0; i < NR_NUMA_HINT_FAULT_STATS * nr_node_ids; i++) 3217 numa_faults[i] = 0; 3218 } 3219 } 3220 3221 /* 3222 * Got a PROT_NONE fault for a page on @node. 3223 */ 3224 void task_numa_fault(int last_cpupid, int mem_node, int pages, int flags) 3225 { 3226 struct task_struct *p = current; 3227 bool migrated = flags & TNF_MIGRATED; 3228 int cpu_node = task_node(current); 3229 int local = !!(flags & TNF_FAULT_LOCAL); 3230 struct numa_group *ng; 3231 int priv; 3232 3233 if (!static_branch_likely(&sched_numa_balancing)) 3234 return; 3235 3236 /* for example, ksmd faulting in a user's mm */ 3237 if (!p->mm) 3238 return; 3239 3240 /* 3241 * NUMA faults statistics are unnecessary for the slow memory 3242 * node for memory tiering mode. 3243 */ 3244 if (!node_is_toptier(mem_node) && 3245 (sysctl_numa_balancing_mode & NUMA_BALANCING_MEMORY_TIERING || 3246 !cpupid_valid(last_cpupid))) 3247 return; 3248 3249 /* Allocate buffer to track faults on a per-node basis */ 3250 if (unlikely(!p->numa_faults)) { 3251 int size = sizeof(*p->numa_faults) * 3252 NR_NUMA_HINT_FAULT_BUCKETS * nr_node_ids; 3253 3254 p->numa_faults = kzalloc(size, GFP_KERNEL|__GFP_NOWARN); 3255 if (!p->numa_faults) 3256 return; 3257 3258 p->total_numa_faults = 0; 3259 memset(p->numa_faults_locality, 0, sizeof(p->numa_faults_locality)); 3260 } 3261 3262 /* 3263 * First accesses are treated as private, otherwise consider accesses 3264 * to be private if the accessing pid has not changed 3265 */ 3266 if (unlikely(last_cpupid == (-1 & LAST_CPUPID_MASK))) { 3267 priv = 1; 3268 } else { 3269 priv = cpupid_match_pid(p, last_cpupid); 3270 if (!priv && !(flags & TNF_NO_GROUP)) 3271 task_numa_group(p, last_cpupid, flags, &priv); 3272 } 3273 3274 /* 3275 * If a workload spans multiple NUMA nodes, a shared fault that 3276 * occurs wholly within the set of nodes that the workload is 3277 * actively using should be counted as local. This allows the 3278 * scan rate to slow down when a workload has settled down. 3279 */ 3280 ng = deref_curr_numa_group(p); 3281 if (!priv && !local && ng && ng->active_nodes > 1 && 3282 numa_is_active_node(cpu_node, ng) && 3283 numa_is_active_node(mem_node, ng)) 3284 local = 1; 3285 3286 /* 3287 * Retry to migrate task to preferred node periodically, in case it 3288 * previously failed, or the scheduler moved us. 3289 */ 3290 if (time_after(jiffies, p->numa_migrate_retry)) { 3291 task_numa_placement(p); 3292 numa_migrate_preferred(p); 3293 } 3294 3295 if (migrated) 3296 p->numa_pages_migrated += pages; 3297 if (flags & TNF_MIGRATE_FAIL) 3298 p->numa_faults_locality[2] += pages; 3299 3300 p->numa_faults[task_faults_idx(NUMA_MEMBUF, mem_node, priv)] += pages; 3301 p->numa_faults[task_faults_idx(NUMA_CPUBUF, cpu_node, priv)] += pages; 3302 p->numa_faults_locality[local] += pages; 3303 } 3304 3305 static void reset_ptenuma_scan(struct task_struct *p) 3306 { 3307 /* 3308 * We only did a read acquisition of the mmap sem, so 3309 * p->mm->numa_scan_seq is written to without exclusive access 3310 * and the update is not guaranteed to be atomic. That's not 3311 * much of an issue though, since this is just used for 3312 * statistical sampling. Use READ_ONCE/WRITE_ONCE, which are not 3313 * expensive, to avoid any form of compiler optimizations: 3314 */ 3315 WRITE_ONCE(p->mm->numa_scan_seq, READ_ONCE(p->mm->numa_scan_seq) + 1); 3316 p->mm->numa_scan_offset = 0; 3317 } 3318 3319 static bool vma_is_accessed(struct mm_struct *mm, struct vm_area_struct *vma) 3320 { 3321 unsigned long pids; 3322 /* 3323 * Allow unconditional access first two times, so that all the (pages) 3324 * of VMAs get prot_none fault introduced irrespective of accesses. 3325 * This is also done to avoid any side effect of task scanning 3326 * amplifying the unfairness of disjoint set of VMAs' access. 3327 */ 3328 if ((READ_ONCE(current->mm->numa_scan_seq) - vma->numab_state->start_scan_seq) < 2) 3329 return true; 3330 3331 pids = vma->numab_state->pids_active[0] | vma->numab_state->pids_active[1]; 3332 if (test_bit(hash_32(current->pid, ilog2(BITS_PER_LONG)), &pids)) 3333 return true; 3334 3335 /* 3336 * Complete a scan that has already started regardless of PID access, or 3337 * some VMAs may never be scanned in multi-threaded applications: 3338 */ 3339 if (mm->numa_scan_offset > vma->vm_start) { 3340 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_IGNORE_PID); 3341 return true; 3342 } 3343 3344 /* 3345 * This vma has not been accessed for a while, and if the number 3346 * the threads in the same process is low, which means no other 3347 * threads can help scan this vma, force a vma scan. 3348 */ 3349 if (READ_ONCE(mm->numa_scan_seq) > 3350 (vma->numab_state->prev_scan_seq + get_nr_threads(current))) 3351 return true; 3352 3353 return false; 3354 } 3355 3356 #define VMA_PID_RESET_PERIOD (4 * sysctl_numa_balancing_scan_delay) 3357 3358 /* 3359 * The expensive part of numa migration is done from task_work context. 3360 * Triggered from task_tick_numa(). 3361 */ 3362 static void task_numa_work(struct callback_head *work) 3363 { 3364 unsigned long migrate, next_scan, now = jiffies; 3365 struct task_struct *p = current; 3366 struct mm_struct *mm = p->mm; 3367 u64 runtime = p->se.sum_exec_runtime; 3368 struct vm_area_struct *vma; 3369 unsigned long start, end; 3370 unsigned long nr_pte_updates = 0; 3371 long pages, virtpages; 3372 struct vma_iterator vmi; 3373 bool vma_pids_skipped; 3374 bool vma_pids_forced = false; 3375 3376 WARN_ON_ONCE(p != container_of(work, struct task_struct, numa_work)); 3377 3378 work->next = work; 3379 /* 3380 * Who cares about NUMA placement when they're dying. 3381 * 3382 * NOTE: make sure not to dereference p->mm before this check, 3383 * exit_task_work() happens _after_ exit_mm() so we could be called 3384 * without p->mm even though we still had it when we enqueued this 3385 * work. 3386 */ 3387 if (p->flags & PF_EXITING) 3388 return; 3389 3390 /* 3391 * Memory is pinned to only one NUMA node via cpuset.mems, naturally 3392 * no page can be migrated. 3393 */ 3394 if (cpusets_enabled() && nodes_weight(cpuset_current_mems_allowed) == 1) { 3395 trace_sched_skip_cpuset_numa(current, &cpuset_current_mems_allowed); 3396 return; 3397 } 3398 3399 if (!mm->numa_next_scan) { 3400 mm->numa_next_scan = now + 3401 msecs_to_jiffies(sysctl_numa_balancing_scan_delay); 3402 } 3403 3404 /* 3405 * Enforce maximal scan/migration frequency.. 3406 */ 3407 migrate = mm->numa_next_scan; 3408 if (time_before(now, migrate)) 3409 return; 3410 3411 if (p->numa_scan_period == 0) { 3412 p->numa_scan_period_max = task_scan_max(p); 3413 p->numa_scan_period = task_scan_start(p); 3414 } 3415 3416 next_scan = now + msecs_to_jiffies(p->numa_scan_period); 3417 if (!try_cmpxchg(&mm->numa_next_scan, &migrate, next_scan)) 3418 return; 3419 3420 /* 3421 * Delay this task enough that another task of this mm will likely win 3422 * the next time around. 3423 */ 3424 p->node_stamp += 2 * TICK_NSEC; 3425 3426 pages = sysctl_numa_balancing_scan_size; 3427 pages <<= 20 - PAGE_SHIFT; /* MB in pages */ 3428 virtpages = pages * 8; /* Scan up to this much virtual space */ 3429 if (!pages) 3430 return; 3431 3432 3433 if (!mmap_read_trylock(mm)) 3434 return; 3435 3436 /* 3437 * VMAs are skipped if the current PID has not trapped a fault within 3438 * the VMA recently. Allow scanning to be forced if there is no 3439 * suitable VMA remaining. 3440 */ 3441 vma_pids_skipped = false; 3442 3443 retry_pids: 3444 start = mm->numa_scan_offset; 3445 vma_iter_init(&vmi, mm, start); 3446 vma = vma_next(&vmi); 3447 if (!vma) { 3448 reset_ptenuma_scan(p); 3449 start = 0; 3450 vma_iter_set(&vmi, start); 3451 vma = vma_next(&vmi); 3452 } 3453 3454 for (; vma; vma = vma_next(&vmi)) { 3455 if (!vma_migratable(vma) || !vma_policy_mof(vma) || 3456 is_vm_hugetlb_page(vma) || (vma->vm_flags & VM_MIXEDMAP)) { 3457 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_UNSUITABLE); 3458 continue; 3459 } 3460 3461 /* 3462 * Shared library pages mapped by multiple processes are not 3463 * migrated as it is expected they are cache replicated. Avoid 3464 * hinting faults in read-only file-backed mappings or the vDSO 3465 * as migrating the pages will be of marginal benefit. 3466 */ 3467 if (!vma->vm_mm || 3468 (vma->vm_file && (vma->vm_flags & (VM_READ|VM_WRITE)) == (VM_READ))) { 3469 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SHARED_RO); 3470 continue; 3471 } 3472 3473 /* 3474 * Skip inaccessible VMAs to avoid any confusion between 3475 * PROT_NONE and NUMA hinting PTEs 3476 */ 3477 if (!vma_is_accessible(vma)) { 3478 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_INACCESSIBLE); 3479 continue; 3480 } 3481 3482 /* Initialise new per-VMA NUMAB state. */ 3483 if (!vma->numab_state) { 3484 struct vma_numab_state *ptr; 3485 3486 ptr = kzalloc_obj(*ptr); 3487 if (!ptr) 3488 continue; 3489 3490 if (cmpxchg(&vma->numab_state, NULL, ptr)) { 3491 kfree(ptr); 3492 continue; 3493 } 3494 3495 vma->numab_state->start_scan_seq = mm->numa_scan_seq; 3496 3497 vma->numab_state->next_scan = now + 3498 msecs_to_jiffies(sysctl_numa_balancing_scan_delay); 3499 3500 /* Reset happens after 4 times scan delay of scan start */ 3501 vma->numab_state->pids_active_reset = vma->numab_state->next_scan + 3502 msecs_to_jiffies(VMA_PID_RESET_PERIOD); 3503 3504 /* 3505 * Ensure prev_scan_seq does not match numa_scan_seq, 3506 * to prevent VMAs being skipped prematurely on the 3507 * first scan: 3508 */ 3509 vma->numab_state->prev_scan_seq = mm->numa_scan_seq - 1; 3510 } 3511 3512 /* 3513 * Scanning the VMAs of short lived tasks add more overhead. So 3514 * delay the scan for new VMAs. 3515 */ 3516 if (mm->numa_scan_seq && time_before(jiffies, 3517 vma->numab_state->next_scan)) { 3518 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SCAN_DELAY); 3519 continue; 3520 } 3521 3522 /* RESET access PIDs regularly for old VMAs. */ 3523 if (mm->numa_scan_seq && 3524 time_after(jiffies, vma->numab_state->pids_active_reset)) { 3525 vma->numab_state->pids_active_reset = vma->numab_state->pids_active_reset + 3526 msecs_to_jiffies(VMA_PID_RESET_PERIOD); 3527 vma->numab_state->pids_active[0] = READ_ONCE(vma->numab_state->pids_active[1]); 3528 vma->numab_state->pids_active[1] = 0; 3529 } 3530 3531 /* Do not rescan VMAs twice within the same sequence. */ 3532 if (vma->numab_state->prev_scan_seq == mm->numa_scan_seq) { 3533 mm->numa_scan_offset = vma->vm_end; 3534 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_SEQ_COMPLETED); 3535 continue; 3536 } 3537 3538 /* 3539 * Do not scan the VMA if task has not accessed it, unless no other 3540 * VMA candidate exists. 3541 */ 3542 if (!vma_pids_forced && !vma_is_accessed(mm, vma)) { 3543 vma_pids_skipped = true; 3544 trace_sched_skip_vma_numa(mm, vma, NUMAB_SKIP_PID_INACTIVE); 3545 continue; 3546 } 3547 3548 do { 3549 start = max(start, vma->vm_start); 3550 end = ALIGN(start + (pages << PAGE_SHIFT), HPAGE_SIZE); 3551 end = min(end, vma->vm_end); 3552 nr_pte_updates = change_prot_numa(vma, start, end); 3553 3554 /* 3555 * Try to scan sysctl_numa_balancing_size worth of 3556 * hpages that have at least one present PTE that 3557 * is not already PTE-numa. If the VMA contains 3558 * areas that are unused or already full of prot_numa 3559 * PTEs, scan up to virtpages, to skip through those 3560 * areas faster. 3561 */ 3562 if (nr_pte_updates) 3563 pages -= (end - start) >> PAGE_SHIFT; 3564 virtpages -= (end - start) >> PAGE_SHIFT; 3565 3566 start = end; 3567 if (pages <= 0 || virtpages <= 0) 3568 goto out; 3569 3570 cond_resched(); 3571 } while (end != vma->vm_end); 3572 3573 /* VMA scan is complete, do not scan until next sequence. */ 3574 vma->numab_state->prev_scan_seq = mm->numa_scan_seq; 3575 3576 /* 3577 * Only force scan within one VMA at a time, to limit the 3578 * cost of scanning a potentially uninteresting VMA. 3579 */ 3580 if (vma_pids_forced) 3581 break; 3582 } 3583 3584 /* 3585 * If no VMAs are remaining and VMAs were skipped due to the PID 3586 * not accessing the VMA previously, then force a scan to ensure 3587 * forward progress: 3588 */ 3589 if (!vma && !vma_pids_forced && vma_pids_skipped) { 3590 vma_pids_forced = true; 3591 goto retry_pids; 3592 } 3593 3594 out: 3595 /* 3596 * It is possible to reach the end of the VMA list but the last few 3597 * VMAs are not guaranteed to the vma_migratable. If they are not, we 3598 * would find the !migratable VMA on the next scan but not reset the 3599 * scanner to the start so check it now. 3600 */ 3601 if (vma) 3602 mm->numa_scan_offset = start; 3603 else 3604 reset_ptenuma_scan(p); 3605 mmap_read_unlock(mm); 3606 3607 /* 3608 * Make sure tasks use at least 32x as much time to run other code 3609 * than they used here, to limit NUMA PTE scanning overhead to 3% max. 3610 * Usually update_task_scan_period slows down scanning enough; on an 3611 * overloaded system we need to limit overhead on a per task basis. 3612 */ 3613 if (unlikely(p->se.sum_exec_runtime != runtime)) { 3614 u64 diff = p->se.sum_exec_runtime - runtime; 3615 p->node_stamp += 32 * diff; 3616 } 3617 } 3618 3619 void init_numa_balancing(u64 clone_flags, struct task_struct *p) 3620 { 3621 int mm_users = 0; 3622 struct mm_struct *mm = p->mm; 3623 3624 if (mm) { 3625 mm_users = atomic_read(&mm->mm_users); 3626 if (mm_users == 1) { 3627 mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay); 3628 mm->numa_scan_seq = 0; 3629 } 3630 } 3631 p->node_stamp = 0; 3632 p->numa_scan_seq = mm ? mm->numa_scan_seq : 0; 3633 p->numa_scan_period = sysctl_numa_balancing_scan_delay; 3634 p->numa_migrate_retry = 0; 3635 /* Protect against double add, see task_tick_numa and task_numa_work */ 3636 p->numa_work.next = &p->numa_work; 3637 p->numa_faults = NULL; 3638 p->numa_pages_migrated = 0; 3639 p->total_numa_faults = 0; 3640 RCU_INIT_POINTER(p->numa_group, NULL); 3641 p->last_task_numa_placement = 0; 3642 p->last_sum_exec_runtime = 0; 3643 3644 init_task_work(&p->numa_work, task_numa_work); 3645 3646 /* New address space, reset the preferred nid */ 3647 if (!(clone_flags & CLONE_VM)) { 3648 p->numa_preferred_nid = NUMA_NO_NODE; 3649 return; 3650 } 3651 3652 /* 3653 * New thread, keep existing numa_preferred_nid which should be copied 3654 * already by arch_dup_task_struct but stagger when scans start. 3655 */ 3656 if (mm) { 3657 unsigned int delay; 3658 3659 delay = min_t(unsigned int, task_scan_max(current), 3660 current->numa_scan_period * mm_users * NSEC_PER_MSEC); 3661 delay += 2 * TICK_NSEC; 3662 p->node_stamp = delay; 3663 } 3664 } 3665 3666 /* 3667 * Drive the periodic memory faults.. 3668 */ 3669 static void task_tick_numa(struct rq *rq, struct task_struct *curr) 3670 { 3671 struct callback_head *work = &curr->numa_work; 3672 u64 period, now; 3673 3674 /* 3675 * We don't care about NUMA placement if we don't have memory. 3676 */ 3677 if (!curr->mm || (curr->flags & (PF_EXITING | PF_KTHREAD)) || work->next != work) 3678 return; 3679 3680 /* 3681 * Using runtime rather than walltime has the dual advantage that 3682 * we (mostly) drive the selection from busy threads and that the 3683 * task needs to have done some actual work before we bother with 3684 * NUMA placement. 3685 */ 3686 now = curr->se.sum_exec_runtime; 3687 period = (u64)curr->numa_scan_period * NSEC_PER_MSEC; 3688 3689 if (now > curr->node_stamp + period) { 3690 if (!curr->node_stamp) 3691 curr->numa_scan_period = task_scan_start(curr); 3692 curr->node_stamp += period; 3693 3694 if (!time_before(jiffies, curr->mm->numa_next_scan)) 3695 task_work_add(curr, work, TWA_RESUME); 3696 } 3697 } 3698 3699 static void update_scan_period(struct task_struct *p, int new_cpu) 3700 { 3701 int src_nid = cpu_to_node(task_cpu(p)); 3702 int dst_nid = cpu_to_node(new_cpu); 3703 3704 if (!static_branch_likely(&sched_numa_balancing)) 3705 return; 3706 3707 if (!p->mm || !p->numa_faults || (p->flags & PF_EXITING)) 3708 return; 3709 3710 if (src_nid == dst_nid) 3711 return; 3712 3713 /* 3714 * Allow resets if faults have been trapped before one scan 3715 * has completed. This is most likely due to a new task that 3716 * is pulled cross-node due to wakeups or load balancing. 3717 */ 3718 if (p->numa_scan_seq) { 3719 /* 3720 * Avoid scan adjustments if moving to the preferred 3721 * node or if the task was not previously running on 3722 * the preferred node. 3723 */ 3724 if (dst_nid == p->numa_preferred_nid || 3725 (p->numa_preferred_nid != NUMA_NO_NODE && 3726 src_nid != p->numa_preferred_nid)) 3727 return; 3728 } 3729 3730 p->numa_scan_period = task_scan_start(p); 3731 } 3732 3733 #else /* !CONFIG_NUMA_BALANCING: */ 3734 3735 static void task_tick_numa(struct rq *rq, struct task_struct *curr) 3736 { 3737 } 3738 3739 static inline void account_numa_enqueue(struct rq *rq, struct task_struct *p) 3740 { 3741 } 3742 3743 static inline void account_numa_dequeue(struct rq *rq, struct task_struct *p) 3744 { 3745 } 3746 3747 static inline void update_scan_period(struct task_struct *p, int new_cpu) 3748 { 3749 } 3750 3751 #endif /* !CONFIG_NUMA_BALANCING */ 3752 3753 static void 3754 account_entity_enqueue(struct cfs_rq *cfs_rq, struct sched_entity *se) 3755 { 3756 update_load_add(&cfs_rq->load, se->load.weight); 3757 if (entity_is_task(se)) { 3758 struct rq *rq = rq_of(cfs_rq); 3759 3760 account_numa_enqueue(rq, task_of(se)); 3761 list_add(&se->group_node, &rq->cfs_tasks); 3762 } 3763 cfs_rq->nr_queued++; 3764 } 3765 3766 static void 3767 account_entity_dequeue(struct cfs_rq *cfs_rq, struct sched_entity *se) 3768 { 3769 update_load_sub(&cfs_rq->load, se->load.weight); 3770 if (entity_is_task(se)) { 3771 account_numa_dequeue(rq_of(cfs_rq), task_of(se)); 3772 list_del_init(&se->group_node); 3773 } 3774 cfs_rq->nr_queued--; 3775 } 3776 3777 /* 3778 * Signed add and clamp on underflow. 3779 * 3780 * Explicitly do a load-store to ensure the intermediate value never hits 3781 * memory. This allows lockless observations without ever seeing the negative 3782 * values. 3783 */ 3784 #define add_positive(_ptr, _val) do { \ 3785 typeof(_ptr) ptr = (_ptr); \ 3786 __signed_scalar_typeof(*ptr) val = (_val); \ 3787 typeof(*ptr) res, var = READ_ONCE(*ptr); \ 3788 \ 3789 res = var + val; \ 3790 \ 3791 if (val < 0 && res > var) \ 3792 res = 0; \ 3793 \ 3794 WRITE_ONCE(*ptr, res); \ 3795 } while (0) 3796 3797 /* 3798 * Remove and clamp on negative, from a local variable. 3799 * 3800 * A variant of sub_positive(), which does not use explicit load-store 3801 * and is thus optimized for local variable updates. 3802 */ 3803 #define lsub_positive(_ptr, _val) do { \ 3804 typeof(_ptr) ptr = (_ptr); \ 3805 *ptr -= min_t(typeof(*ptr), *ptr, _val); \ 3806 } while (0) 3807 3808 3809 /* 3810 * Because of rounding, se->util_sum might ends up being +1 more than 3811 * cfs->util_sum. Although this is not a problem by itself, detaching 3812 * a lot of tasks with the rounding problem between 2 updates of 3813 * util_avg (~1ms) can make cfs->util_sum becoming null whereas 3814 * cfs_util_avg is not. 3815 * 3816 * Check that util_sum is still above its lower bound for the new 3817 * util_avg. Given that period_contrib might have moved since the last 3818 * sync, we are only sure that util_sum must be above or equal to 3819 * util_avg * minimum possible divider 3820 */ 3821 #define __update_sa(sa, name, delta_avg, delta_sum) do { \ 3822 add_positive(&(sa)->name##_avg, delta_avg); \ 3823 add_positive(&(sa)->name##_sum, delta_sum); \ 3824 (sa)->name##_sum = max_t(typeof((sa)->name##_sum), \ 3825 (sa)->name##_sum, \ 3826 (sa)->name##_avg * PELT_MIN_DIVIDER); \ 3827 } while (0) 3828 3829 static inline void 3830 enqueue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) 3831 { 3832 __update_sa(&cfs_rq->avg, load, se->avg.load_avg, 3833 se_weight(se) * se->avg.load_sum); 3834 } 3835 3836 static inline void 3837 dequeue_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) 3838 { 3839 __update_sa(&cfs_rq->avg, load, -se->avg.load_avg, 3840 se_weight(se) * -se->avg.load_sum); 3841 } 3842 3843 static void place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags); 3844 3845 static void reweight_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, 3846 unsigned long weight) 3847 { 3848 bool curr = cfs_rq->curr == se; 3849 bool rel_vprot = false; 3850 u64 vprot; 3851 3852 if (se->on_rq) { 3853 /* commit outstanding execution time */ 3854 update_curr(cfs_rq); 3855 update_entity_lag(cfs_rq, se); 3856 se->deadline -= se->vruntime; 3857 se->rel_deadline = 1; 3858 if (curr && protect_slice(se)) { 3859 vprot = se->vprot - se->vruntime; 3860 rel_vprot = true; 3861 } 3862 3863 cfs_rq->nr_queued--; 3864 if (!curr) 3865 __dequeue_entity(cfs_rq, se); 3866 update_load_sub(&cfs_rq->load, se->load.weight); 3867 } 3868 dequeue_load_avg(cfs_rq, se); 3869 3870 /* 3871 * Because we keep se->vlag = V - v_i, while: lag_i = w_i*(V - v_i), 3872 * we need to scale se->vlag when w_i changes. 3873 */ 3874 se->vlag = div_s64(se->vlag * se->load.weight, weight); 3875 if (se->rel_deadline) 3876 se->deadline = div_s64(se->deadline * se->load.weight, weight); 3877 3878 if (rel_vprot) 3879 vprot = div_s64(vprot * se->load.weight, weight); 3880 3881 update_load_set(&se->load, weight); 3882 3883 do { 3884 u32 divider = get_pelt_divider(&se->avg); 3885 3886 se->avg.load_avg = div_u64(se_weight(se) * se->avg.load_sum, divider); 3887 } while (0); 3888 3889 enqueue_load_avg(cfs_rq, se); 3890 if (se->on_rq) { 3891 place_entity(cfs_rq, se, 0); 3892 if (rel_vprot) 3893 se->vprot = se->vruntime + vprot; 3894 update_load_add(&cfs_rq->load, se->load.weight); 3895 if (!curr) 3896 __enqueue_entity(cfs_rq, se); 3897 cfs_rq->nr_queued++; 3898 } 3899 } 3900 3901 static void reweight_task_fair(struct rq *rq, struct task_struct *p, 3902 const struct load_weight *lw) 3903 { 3904 struct sched_entity *se = &p->se; 3905 struct cfs_rq *cfs_rq = cfs_rq_of(se); 3906 struct load_weight *load = &se->load; 3907 3908 reweight_entity(cfs_rq, se, lw->weight); 3909 load->inv_weight = lw->inv_weight; 3910 } 3911 3912 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq); 3913 3914 #ifdef CONFIG_FAIR_GROUP_SCHED 3915 /* 3916 * All this does is approximate the hierarchical proportion which includes that 3917 * global sum we all love to hate. 3918 * 3919 * That is, the weight of a group entity, is the proportional share of the 3920 * group weight based on the group runqueue weights. That is: 3921 * 3922 * tg->weight * grq->load.weight 3923 * ge->load.weight = ----------------------------- (1) 3924 * \Sum grq->load.weight 3925 * 3926 * Now, because computing that sum is prohibitively expensive to compute (been 3927 * there, done that) we approximate it with this average stuff. The average 3928 * moves slower and therefore the approximation is cheaper and more stable. 3929 * 3930 * So instead of the above, we substitute: 3931 * 3932 * grq->load.weight -> grq->avg.load_avg (2) 3933 * 3934 * which yields the following: 3935 * 3936 * tg->weight * grq->avg.load_avg 3937 * ge->load.weight = ------------------------------ (3) 3938 * tg->load_avg 3939 * 3940 * Where: tg->load_avg ~= \Sum grq->avg.load_avg 3941 * 3942 * That is shares_avg, and it is right (given the approximation (2)). 3943 * 3944 * The problem with it is that because the average is slow -- it was designed 3945 * to be exactly that of course -- this leads to transients in boundary 3946 * conditions. In specific, the case where the group was idle and we start the 3947 * one task. It takes time for our CPU's grq->avg.load_avg to build up, 3948 * yielding bad latency etc.. 3949 * 3950 * Now, in that special case (1) reduces to: 3951 * 3952 * tg->weight * grq->load.weight 3953 * ge->load.weight = ----------------------------- = tg->weight (4) 3954 * grp->load.weight 3955 * 3956 * That is, the sum collapses because all other CPUs are idle; the UP scenario. 3957 * 3958 * So what we do is modify our approximation (3) to approach (4) in the (near) 3959 * UP case, like: 3960 * 3961 * ge->load.weight = 3962 * 3963 * tg->weight * grq->load.weight 3964 * --------------------------------------------------- (5) 3965 * tg->load_avg - grq->avg.load_avg + grq->load.weight 3966 * 3967 * But because grq->load.weight can drop to 0, resulting in a divide by zero, 3968 * we need to use grq->avg.load_avg as its lower bound, which then gives: 3969 * 3970 * 3971 * tg->weight * grq->load.weight 3972 * ge->load.weight = ----------------------------- (6) 3973 * tg_load_avg' 3974 * 3975 * Where: 3976 * 3977 * tg_load_avg' = tg->load_avg - grq->avg.load_avg + 3978 * max(grq->load.weight, grq->avg.load_avg) 3979 * 3980 * And that is shares_weight and is icky. In the (near) UP case it approaches 3981 * (4) while in the normal case it approaches (3). It consistently 3982 * overestimates the ge->load.weight and therefore: 3983 * 3984 * \Sum ge->load.weight >= tg->weight 3985 * 3986 * hence icky! 3987 */ 3988 static long calc_group_shares(struct cfs_rq *cfs_rq) 3989 { 3990 long tg_weight, tg_shares, load, shares; 3991 struct task_group *tg = cfs_rq->tg; 3992 3993 tg_shares = READ_ONCE(tg->shares); 3994 3995 load = max(scale_load_down(cfs_rq->load.weight), cfs_rq->avg.load_avg); 3996 3997 tg_weight = atomic_long_read(&tg->load_avg); 3998 3999 /* Ensure tg_weight >= load */ 4000 tg_weight -= cfs_rq->tg_load_avg_contrib; 4001 tg_weight += load; 4002 4003 shares = (tg_shares * load); 4004 if (tg_weight) 4005 shares /= tg_weight; 4006 4007 /* 4008 * MIN_SHARES has to be unscaled here to support per-CPU partitioning 4009 * of a group with small tg->shares value. It is a floor value which is 4010 * assigned as a minimum load.weight to the sched_entity representing 4011 * the group on a CPU. 4012 * 4013 * E.g. on 64-bit for a group with tg->shares of scale_load(15)=15*1024 4014 * on an 8-core system with 8 tasks each runnable on one CPU shares has 4015 * to be 15*1024*1/8=1920 instead of scale_load(MIN_SHARES)=2*1024. In 4016 * case no task is runnable on a CPU MIN_SHARES=2 should be returned 4017 * instead of 0. 4018 */ 4019 return clamp_t(long, shares, MIN_SHARES, tg_shares); 4020 } 4021 4022 /* 4023 * Recomputes the group entity based on the current state of its group 4024 * runqueue. 4025 */ 4026 static void update_cfs_group(struct sched_entity *se) 4027 { 4028 struct cfs_rq *gcfs_rq = group_cfs_rq(se); 4029 long shares; 4030 4031 /* 4032 * When a group becomes empty, preserve its weight. This matters for 4033 * DELAY_DEQUEUE. 4034 */ 4035 if (!gcfs_rq || !gcfs_rq->load.weight) 4036 return; 4037 4038 shares = calc_group_shares(gcfs_rq); 4039 if (unlikely(se->load.weight != shares)) 4040 reweight_entity(cfs_rq_of(se), se, shares); 4041 } 4042 4043 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 4044 static inline void update_cfs_group(struct sched_entity *se) 4045 { 4046 } 4047 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 4048 4049 static inline void cfs_rq_util_change(struct cfs_rq *cfs_rq, int flags) 4050 { 4051 struct rq *rq = rq_of(cfs_rq); 4052 4053 if (&rq->cfs == cfs_rq) { 4054 /* 4055 * There are a few boundary cases this might miss but it should 4056 * get called often enough that that should (hopefully) not be 4057 * a real problem. 4058 * 4059 * It will not get called when we go idle, because the idle 4060 * thread is a different class (!fair), nor will the utilization 4061 * number include things like RT tasks. 4062 * 4063 * As is, the util number is not freq-invariant (we'd have to 4064 * implement arch_scale_freq_capacity() for that). 4065 * 4066 * See cpu_util_cfs(). 4067 */ 4068 cpufreq_update_util(rq, flags); 4069 } 4070 } 4071 4072 static inline bool load_avg_is_decayed(struct sched_avg *sa) 4073 { 4074 if (sa->load_sum) 4075 return false; 4076 4077 if (sa->util_sum) 4078 return false; 4079 4080 if (sa->runnable_sum) 4081 return false; 4082 4083 /* 4084 * _avg must be null when _sum are null because _avg = _sum / divider 4085 * Make sure that rounding and/or propagation of PELT values never 4086 * break this. 4087 */ 4088 WARN_ON_ONCE(sa->load_avg || 4089 sa->util_avg || 4090 sa->runnable_avg); 4091 4092 return true; 4093 } 4094 4095 static inline u64 cfs_rq_last_update_time(struct cfs_rq *cfs_rq) 4096 { 4097 return u64_u32_load_copy(cfs_rq->avg.last_update_time, 4098 cfs_rq->last_update_time_copy); 4099 } 4100 #ifdef CONFIG_FAIR_GROUP_SCHED 4101 /* 4102 * Because list_add_leaf_cfs_rq always places a child cfs_rq on the list 4103 * immediately before a parent cfs_rq, and cfs_rqs are removed from the list 4104 * bottom-up, we only have to test whether the cfs_rq before us on the list 4105 * is our child. 4106 * If cfs_rq is not on the list, test whether a child needs its to be added to 4107 * connect a branch to the tree * (see list_add_leaf_cfs_rq() for details). 4108 */ 4109 static inline bool child_cfs_rq_on_list(struct cfs_rq *cfs_rq) 4110 { 4111 struct cfs_rq *prev_cfs_rq; 4112 struct list_head *prev; 4113 struct rq *rq = rq_of(cfs_rq); 4114 4115 if (cfs_rq->on_list) { 4116 prev = cfs_rq->leaf_cfs_rq_list.prev; 4117 } else { 4118 prev = rq->tmp_alone_branch; 4119 } 4120 4121 if (prev == &rq->leaf_cfs_rq_list) 4122 return false; 4123 4124 prev_cfs_rq = container_of(prev, struct cfs_rq, leaf_cfs_rq_list); 4125 4126 return (prev_cfs_rq->tg->parent == cfs_rq->tg); 4127 } 4128 4129 static inline bool cfs_rq_is_decayed(struct cfs_rq *cfs_rq) 4130 { 4131 if (cfs_rq->load.weight) 4132 return false; 4133 4134 if (!load_avg_is_decayed(&cfs_rq->avg)) 4135 return false; 4136 4137 if (child_cfs_rq_on_list(cfs_rq)) 4138 return false; 4139 4140 if (cfs_rq->tg_load_avg_contrib) 4141 return false; 4142 4143 return true; 4144 } 4145 4146 /** 4147 * update_tg_load_avg - update the tg's load avg 4148 * @cfs_rq: the cfs_rq whose avg changed 4149 * 4150 * This function 'ensures': tg->load_avg := \Sum tg->cfs_rq[]->avg.load. 4151 * However, because tg->load_avg is a global value there are performance 4152 * considerations. 4153 * 4154 * In order to avoid having to look at the other cfs_rq's, we use a 4155 * differential update where we store the last value we propagated. This in 4156 * turn allows skipping updates if the differential is 'small'. 4157 * 4158 * Updating tg's load_avg is necessary before update_cfs_share(). 4159 */ 4160 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) 4161 { 4162 long delta; 4163 u64 now; 4164 4165 /* 4166 * No need to update load_avg for root_task_group as it is not used. 4167 */ 4168 if (cfs_rq->tg == &root_task_group) 4169 return; 4170 4171 /* rq has been offline and doesn't contribute to the share anymore: */ 4172 if (!cpu_active(cpu_of(rq_of(cfs_rq)))) 4173 return; 4174 4175 /* 4176 * For migration heavy workloads, access to tg->load_avg can be 4177 * unbound. Limit the update rate to at most once per ms. 4178 */ 4179 now = sched_clock_cpu(cpu_of(rq_of(cfs_rq))); 4180 if (now - cfs_rq->last_update_tg_load_avg < NSEC_PER_MSEC) 4181 return; 4182 4183 delta = cfs_rq->avg.load_avg - cfs_rq->tg_load_avg_contrib; 4184 if (abs(delta) > cfs_rq->tg_load_avg_contrib / 64) { 4185 atomic_long_add(delta, &cfs_rq->tg->load_avg); 4186 cfs_rq->tg_load_avg_contrib = cfs_rq->avg.load_avg; 4187 cfs_rq->last_update_tg_load_avg = now; 4188 } 4189 } 4190 4191 static inline void clear_tg_load_avg(struct cfs_rq *cfs_rq) 4192 { 4193 long delta; 4194 u64 now; 4195 4196 /* 4197 * No need to update load_avg for root_task_group, as it is not used. 4198 */ 4199 if (cfs_rq->tg == &root_task_group) 4200 return; 4201 4202 now = sched_clock_cpu(cpu_of(rq_of(cfs_rq))); 4203 delta = 0 - cfs_rq->tg_load_avg_contrib; 4204 atomic_long_add(delta, &cfs_rq->tg->load_avg); 4205 cfs_rq->tg_load_avg_contrib = 0; 4206 cfs_rq->last_update_tg_load_avg = now; 4207 } 4208 4209 /* CPU offline callback: */ 4210 static void __maybe_unused clear_tg_offline_cfs_rqs(struct rq *rq) 4211 { 4212 struct task_group *tg; 4213 4214 lockdep_assert_rq_held(rq); 4215 4216 /* 4217 * The rq clock has already been updated in 4218 * set_rq_offline(), so we should skip updating 4219 * the rq clock again in unthrottle_cfs_rq(). 4220 */ 4221 rq_clock_start_loop_update(rq); 4222 4223 rcu_read_lock(); 4224 list_for_each_entry_rcu(tg, &task_groups, list) { 4225 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)]; 4226 4227 clear_tg_load_avg(cfs_rq); 4228 } 4229 rcu_read_unlock(); 4230 4231 rq_clock_stop_loop_update(rq); 4232 } 4233 4234 /* 4235 * Called within set_task_rq() right before setting a task's CPU. The 4236 * caller only guarantees p->pi_lock is held; no other assumptions, 4237 * including the state of rq->lock, should be made. 4238 */ 4239 void set_task_rq_fair(struct sched_entity *se, 4240 struct cfs_rq *prev, struct cfs_rq *next) 4241 { 4242 u64 p_last_update_time; 4243 u64 n_last_update_time; 4244 4245 if (!sched_feat(ATTACH_AGE_LOAD)) 4246 return; 4247 4248 /* 4249 * We are supposed to update the task to "current" time, then its up to 4250 * date and ready to go to new CPU/cfs_rq. But we have difficulty in 4251 * getting what current time is, so simply throw away the out-of-date 4252 * time. This will result in the wakee task is less decayed, but giving 4253 * the wakee more load sounds not bad. 4254 */ 4255 if (!(se->avg.last_update_time && prev)) 4256 return; 4257 4258 p_last_update_time = cfs_rq_last_update_time(prev); 4259 n_last_update_time = cfs_rq_last_update_time(next); 4260 4261 __update_load_avg_blocked_se(p_last_update_time, se); 4262 se->avg.last_update_time = n_last_update_time; 4263 } 4264 4265 /* 4266 * When on migration a sched_entity joins/leaves the PELT hierarchy, we need to 4267 * propagate its contribution. The key to this propagation is the invariant 4268 * that for each group: 4269 * 4270 * ge->avg == grq->avg (1) 4271 * 4272 * _IFF_ we look at the pure running and runnable sums. Because they 4273 * represent the very same entity, just at different points in the hierarchy. 4274 * 4275 * Per the above update_tg_cfs_util() and update_tg_cfs_runnable() are trivial 4276 * and simply copies the running/runnable sum over (but still wrong, because 4277 * the group entity and group rq do not have their PELT windows aligned). 4278 * 4279 * However, update_tg_cfs_load() is more complex. So we have: 4280 * 4281 * ge->avg.load_avg = ge->load.weight * ge->avg.runnable_avg (2) 4282 * 4283 * And since, like util, the runnable part should be directly transferable, 4284 * the following would _appear_ to be the straight forward approach: 4285 * 4286 * grq->avg.load_avg = grq->load.weight * grq->avg.runnable_avg (3) 4287 * 4288 * And per (1) we have: 4289 * 4290 * ge->avg.runnable_avg == grq->avg.runnable_avg 4291 * 4292 * Which gives: 4293 * 4294 * ge->load.weight * grq->avg.load_avg 4295 * ge->avg.load_avg = ----------------------------------- (4) 4296 * grq->load.weight 4297 * 4298 * Except that is wrong! 4299 * 4300 * Because while for entities historical weight is not important and we 4301 * really only care about our future and therefore can consider a pure 4302 * runnable sum, runqueues can NOT do this. 4303 * 4304 * We specifically want runqueues to have a load_avg that includes 4305 * historical weights. Those represent the blocked load, the load we expect 4306 * to (shortly) return to us. This only works by keeping the weights as 4307 * integral part of the sum. We therefore cannot decompose as per (3). 4308 * 4309 * Another reason this doesn't work is that runnable isn't a 0-sum entity. 4310 * Imagine a rq with 2 tasks that each are runnable 2/3 of the time. Then the 4311 * rq itself is runnable anywhere between 2/3 and 1 depending on how the 4312 * runnable section of these tasks overlap (or not). If they were to perfectly 4313 * align the rq as a whole would be runnable 2/3 of the time. If however we 4314 * always have at least 1 runnable task, the rq as a whole is always runnable. 4315 * 4316 * So we'll have to approximate.. :/ 4317 * 4318 * Given the constraint: 4319 * 4320 * ge->avg.running_sum <= ge->avg.runnable_sum <= LOAD_AVG_MAX 4321 * 4322 * We can construct a rule that adds runnable to a rq by assuming minimal 4323 * overlap. 4324 * 4325 * On removal, we'll assume each task is equally runnable; which yields: 4326 * 4327 * grq->avg.runnable_sum = grq->avg.load_sum / grq->load.weight 4328 * 4329 * XXX: only do this for the part of runnable > running ? 4330 * 4331 */ 4332 static inline void 4333 update_tg_cfs_util(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq) 4334 { 4335 long delta_sum, delta_avg = gcfs_rq->avg.util_avg - se->avg.util_avg; 4336 u32 new_sum, divider; 4337 4338 /* Nothing to update */ 4339 if (!delta_avg) 4340 return; 4341 4342 /* 4343 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se. 4344 * See ___update_load_avg() for details. 4345 */ 4346 divider = get_pelt_divider(&cfs_rq->avg); 4347 4348 /* Set new sched_entity's utilization */ 4349 se->avg.util_avg = gcfs_rq->avg.util_avg; 4350 new_sum = se->avg.util_avg * divider; 4351 delta_sum = (long)new_sum - (long)se->avg.util_sum; 4352 se->avg.util_sum = new_sum; 4353 4354 /* Update parent cfs_rq utilization */ 4355 __update_sa(&cfs_rq->avg, util, delta_avg, delta_sum); 4356 } 4357 4358 static inline void 4359 update_tg_cfs_runnable(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq) 4360 { 4361 long delta_sum, delta_avg = gcfs_rq->avg.runnable_avg - se->avg.runnable_avg; 4362 u32 new_sum, divider; 4363 4364 /* Nothing to update */ 4365 if (!delta_avg) 4366 return; 4367 4368 /* 4369 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se. 4370 * See ___update_load_avg() for details. 4371 */ 4372 divider = get_pelt_divider(&cfs_rq->avg); 4373 4374 /* Set new sched_entity's runnable */ 4375 se->avg.runnable_avg = gcfs_rq->avg.runnable_avg; 4376 new_sum = se->avg.runnable_avg * divider; 4377 delta_sum = (long)new_sum - (long)se->avg.runnable_sum; 4378 se->avg.runnable_sum = new_sum; 4379 4380 /* Update parent cfs_rq runnable */ 4381 __update_sa(&cfs_rq->avg, runnable, delta_avg, delta_sum); 4382 } 4383 4384 static inline void 4385 update_tg_cfs_load(struct cfs_rq *cfs_rq, struct sched_entity *se, struct cfs_rq *gcfs_rq) 4386 { 4387 long delta_avg, running_sum, runnable_sum = gcfs_rq->prop_runnable_sum; 4388 unsigned long load_avg; 4389 u64 load_sum = 0; 4390 s64 delta_sum; 4391 u32 divider; 4392 4393 if (!runnable_sum) 4394 return; 4395 4396 gcfs_rq->prop_runnable_sum = 0; 4397 4398 /* 4399 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se. 4400 * See ___update_load_avg() for details. 4401 */ 4402 divider = get_pelt_divider(&cfs_rq->avg); 4403 4404 if (runnable_sum >= 0) { 4405 /* 4406 * Add runnable; clip at LOAD_AVG_MAX. Reflects that until 4407 * the CPU is saturated running == runnable. 4408 */ 4409 runnable_sum += se->avg.load_sum; 4410 runnable_sum = min_t(long, runnable_sum, divider); 4411 } else { 4412 /* 4413 * Estimate the new unweighted runnable_sum of the gcfs_rq by 4414 * assuming all tasks are equally runnable. 4415 */ 4416 if (scale_load_down(gcfs_rq->load.weight)) { 4417 load_sum = div_u64(gcfs_rq->avg.load_sum, 4418 scale_load_down(gcfs_rq->load.weight)); 4419 } 4420 4421 /* But make sure to not inflate se's runnable */ 4422 runnable_sum = min(se->avg.load_sum, load_sum); 4423 } 4424 4425 /* 4426 * runnable_sum can't be lower than running_sum 4427 * Rescale running sum to be in the same range as runnable sum 4428 * running_sum is in [0 : LOAD_AVG_MAX << SCHED_CAPACITY_SHIFT] 4429 * runnable_sum is in [0 : LOAD_AVG_MAX] 4430 */ 4431 running_sum = se->avg.util_sum >> SCHED_CAPACITY_SHIFT; 4432 runnable_sum = max(runnable_sum, running_sum); 4433 4434 load_sum = se_weight(se) * runnable_sum; 4435 load_avg = div_u64(load_sum, divider); 4436 4437 delta_avg = load_avg - se->avg.load_avg; 4438 if (!delta_avg) 4439 return; 4440 4441 delta_sum = load_sum - (s64)se_weight(se) * se->avg.load_sum; 4442 4443 se->avg.load_sum = runnable_sum; 4444 se->avg.load_avg = load_avg; 4445 __update_sa(&cfs_rq->avg, load, delta_avg, delta_sum); 4446 } 4447 4448 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) 4449 { 4450 cfs_rq->propagate = 1; 4451 cfs_rq->prop_runnable_sum += runnable_sum; 4452 } 4453 4454 /* Update task and its cfs_rq load average */ 4455 static inline int propagate_entity_load_avg(struct sched_entity *se) 4456 { 4457 struct cfs_rq *cfs_rq, *gcfs_rq; 4458 4459 if (entity_is_task(se)) 4460 return 0; 4461 4462 gcfs_rq = group_cfs_rq(se); 4463 if (!gcfs_rq->propagate) 4464 return 0; 4465 4466 gcfs_rq->propagate = 0; 4467 4468 cfs_rq = cfs_rq_of(se); 4469 4470 add_tg_cfs_propagate(cfs_rq, gcfs_rq->prop_runnable_sum); 4471 4472 update_tg_cfs_util(cfs_rq, se, gcfs_rq); 4473 update_tg_cfs_runnable(cfs_rq, se, gcfs_rq); 4474 update_tg_cfs_load(cfs_rq, se, gcfs_rq); 4475 4476 trace_pelt_cfs_tp(cfs_rq); 4477 trace_pelt_se_tp(se); 4478 4479 return 1; 4480 } 4481 4482 /* 4483 * Check if we need to update the load and the utilization of a blocked 4484 * group_entity: 4485 */ 4486 static inline bool skip_blocked_update(struct sched_entity *se) 4487 { 4488 struct cfs_rq *gcfs_rq = group_cfs_rq(se); 4489 4490 /* 4491 * If sched_entity still have not zero load or utilization, we have to 4492 * decay it: 4493 */ 4494 if (se->avg.load_avg || se->avg.util_avg) 4495 return false; 4496 4497 /* 4498 * If there is a pending propagation, we have to update the load and 4499 * the utilization of the sched_entity: 4500 */ 4501 if (gcfs_rq->propagate) 4502 return false; 4503 4504 /* 4505 * Otherwise, the load and the utilization of the sched_entity is 4506 * already zero and there is no pending propagation, so it will be a 4507 * waste of time to try to decay it: 4508 */ 4509 return true; 4510 } 4511 4512 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 4513 4514 static inline void update_tg_load_avg(struct cfs_rq *cfs_rq) {} 4515 4516 static inline void clear_tg_offline_cfs_rqs(struct rq *rq) {} 4517 4518 static inline int propagate_entity_load_avg(struct sched_entity *se) 4519 { 4520 return 0; 4521 } 4522 4523 static inline void add_tg_cfs_propagate(struct cfs_rq *cfs_rq, long runnable_sum) {} 4524 4525 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 4526 4527 #ifdef CONFIG_NO_HZ_COMMON 4528 static inline void migrate_se_pelt_lag(struct sched_entity *se) 4529 { 4530 u64 throttled = 0, now, lut; 4531 struct cfs_rq *cfs_rq; 4532 struct rq *rq; 4533 bool is_idle; 4534 4535 if (load_avg_is_decayed(&se->avg)) 4536 return; 4537 4538 cfs_rq = cfs_rq_of(se); 4539 rq = rq_of(cfs_rq); 4540 4541 rcu_read_lock(); 4542 is_idle = is_idle_task(rcu_dereference_all(rq->curr)); 4543 rcu_read_unlock(); 4544 4545 /* 4546 * The lag estimation comes with a cost we don't want to pay all the 4547 * time. Hence, limiting to the case where the source CPU is idle and 4548 * we know we are at the greatest risk to have an outdated clock. 4549 */ 4550 if (!is_idle) 4551 return; 4552 4553 /* 4554 * Estimated "now" is: last_update_time + cfs_idle_lag + rq_idle_lag, where: 4555 * 4556 * last_update_time (the cfs_rq's last_update_time) 4557 * = cfs_rq_clock_pelt()@cfs_rq_idle 4558 * = rq_clock_pelt()@cfs_rq_idle 4559 * - cfs->throttled_clock_pelt_time@cfs_rq_idle 4560 * 4561 * cfs_idle_lag (delta between rq's update and cfs_rq's update) 4562 * = rq_clock_pelt()@rq_idle - rq_clock_pelt()@cfs_rq_idle 4563 * 4564 * rq_idle_lag (delta between now and rq's update) 4565 * = sched_clock_cpu() - rq_clock()@rq_idle 4566 * 4567 * We can then write: 4568 * 4569 * now = rq_clock_pelt()@rq_idle - cfs->throttled_clock_pelt_time + 4570 * sched_clock_cpu() - rq_clock()@rq_idle 4571 * Where: 4572 * rq_clock_pelt()@rq_idle is rq->clock_pelt_idle 4573 * rq_clock()@rq_idle is rq->clock_idle 4574 * cfs->throttled_clock_pelt_time@cfs_rq_idle 4575 * is cfs_rq->throttled_pelt_idle 4576 */ 4577 4578 #ifdef CONFIG_CFS_BANDWIDTH 4579 throttled = u64_u32_load(cfs_rq->throttled_pelt_idle); 4580 /* The clock has been stopped for throttling */ 4581 if (throttled == U64_MAX) 4582 return; 4583 #endif 4584 now = u64_u32_load(rq->clock_pelt_idle); 4585 /* 4586 * Paired with _update_idle_rq_clock_pelt(). It ensures at the worst case 4587 * is observed the old clock_pelt_idle value and the new clock_idle, 4588 * which lead to an underestimation. The opposite would lead to an 4589 * overestimation. 4590 */ 4591 smp_rmb(); 4592 lut = cfs_rq_last_update_time(cfs_rq); 4593 4594 now -= throttled; 4595 if (now < lut) 4596 /* 4597 * cfs_rq->avg.last_update_time is more recent than our 4598 * estimation, let's use it. 4599 */ 4600 now = lut; 4601 else 4602 now += sched_clock_cpu(cpu_of(rq)) - u64_u32_load(rq->clock_idle); 4603 4604 __update_load_avg_blocked_se(now, se); 4605 } 4606 #else /* !CONFIG_NO_HZ_COMMON: */ 4607 static void migrate_se_pelt_lag(struct sched_entity *se) {} 4608 #endif /* !CONFIG_NO_HZ_COMMON */ 4609 4610 /** 4611 * update_cfs_rq_load_avg - update the cfs_rq's load/util averages 4612 * @now: current time, as per cfs_rq_clock_pelt() 4613 * @cfs_rq: cfs_rq to update 4614 * 4615 * The cfs_rq avg is the direct sum of all its entities (blocked and runnable) 4616 * avg. The immediate corollary is that all (fair) tasks must be attached. 4617 * 4618 * cfs_rq->avg is used for task_h_load() and update_cfs_share() for example. 4619 * 4620 * Return: true if the load decayed or we removed load. 4621 * 4622 * Since both these conditions indicate a changed cfs_rq->avg.load we should 4623 * call update_tg_load_avg() when this function returns true. 4624 */ 4625 static inline int 4626 update_cfs_rq_load_avg(u64 now, struct cfs_rq *cfs_rq) 4627 { 4628 unsigned long removed_load = 0, removed_util = 0, removed_runnable = 0; 4629 struct sched_avg *sa = &cfs_rq->avg; 4630 int decayed = 0; 4631 4632 if (cfs_rq->removed.nr) { 4633 unsigned long r; 4634 u32 divider = get_pelt_divider(&cfs_rq->avg); 4635 4636 raw_spin_lock(&cfs_rq->removed.lock); 4637 swap(cfs_rq->removed.util_avg, removed_util); 4638 swap(cfs_rq->removed.load_avg, removed_load); 4639 swap(cfs_rq->removed.runnable_avg, removed_runnable); 4640 cfs_rq->removed.nr = 0; 4641 raw_spin_unlock(&cfs_rq->removed.lock); 4642 4643 r = removed_load; 4644 __update_sa(sa, load, -r, -r*divider); 4645 4646 r = removed_util; 4647 __update_sa(sa, util, -r, -r*divider); 4648 4649 r = removed_runnable; 4650 __update_sa(sa, runnable, -r, -r*divider); 4651 4652 /* 4653 * removed_runnable is the unweighted version of removed_load so we 4654 * can use it to estimate removed_load_sum. 4655 */ 4656 add_tg_cfs_propagate(cfs_rq, 4657 -(long)(removed_runnable * divider) >> SCHED_CAPACITY_SHIFT); 4658 4659 decayed = 1; 4660 } 4661 4662 decayed |= __update_load_avg_cfs_rq(now, cfs_rq); 4663 u64_u32_store_copy(sa->last_update_time, 4664 cfs_rq->last_update_time_copy, 4665 sa->last_update_time); 4666 return decayed; 4667 } 4668 4669 /** 4670 * attach_entity_load_avg - attach this entity to its cfs_rq load avg 4671 * @cfs_rq: cfs_rq to attach to 4672 * @se: sched_entity to attach 4673 * 4674 * Must call update_cfs_rq_load_avg() before this, since we rely on 4675 * cfs_rq->avg.last_update_time being current. 4676 */ 4677 static void attach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) 4678 { 4679 /* 4680 * cfs_rq->avg.period_contrib can be used for both cfs_rq and se. 4681 * See ___update_load_avg() for details. 4682 */ 4683 u32 divider = get_pelt_divider(&cfs_rq->avg); 4684 4685 /* 4686 * When we attach the @se to the @cfs_rq, we must align the decay 4687 * window because without that, really weird and wonderful things can 4688 * happen. 4689 * 4690 * XXX illustrate 4691 */ 4692 se->avg.last_update_time = cfs_rq->avg.last_update_time; 4693 se->avg.period_contrib = cfs_rq->avg.period_contrib; 4694 4695 /* 4696 * Hell(o) Nasty stuff.. we need to recompute _sum based on the new 4697 * period_contrib. This isn't strictly correct, but since we're 4698 * entirely outside of the PELT hierarchy, nobody cares if we truncate 4699 * _sum a little. 4700 */ 4701 se->avg.util_sum = se->avg.util_avg * divider; 4702 4703 se->avg.runnable_sum = se->avg.runnable_avg * divider; 4704 4705 se->avg.load_sum = se->avg.load_avg * divider; 4706 if (se_weight(se) < se->avg.load_sum) 4707 se->avg.load_sum = div_u64(se->avg.load_sum, se_weight(se)); 4708 else 4709 se->avg.load_sum = 1; 4710 4711 enqueue_load_avg(cfs_rq, se); 4712 cfs_rq->avg.util_avg += se->avg.util_avg; 4713 cfs_rq->avg.util_sum += se->avg.util_sum; 4714 cfs_rq->avg.runnable_avg += se->avg.runnable_avg; 4715 cfs_rq->avg.runnable_sum += se->avg.runnable_sum; 4716 4717 add_tg_cfs_propagate(cfs_rq, se->avg.load_sum); 4718 4719 cfs_rq_util_change(cfs_rq, 0); 4720 4721 trace_pelt_cfs_tp(cfs_rq); 4722 } 4723 4724 /** 4725 * detach_entity_load_avg - detach this entity from its cfs_rq load avg 4726 * @cfs_rq: cfs_rq to detach from 4727 * @se: sched_entity to detach 4728 * 4729 * Must call update_cfs_rq_load_avg() before this, since we rely on 4730 * cfs_rq->avg.last_update_time being current. 4731 */ 4732 static void detach_entity_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se) 4733 { 4734 dequeue_load_avg(cfs_rq, se); 4735 __update_sa(&cfs_rq->avg, util, -se->avg.util_avg, -se->avg.util_sum); 4736 __update_sa(&cfs_rq->avg, runnable, -se->avg.runnable_avg, -se->avg.runnable_sum); 4737 4738 add_tg_cfs_propagate(cfs_rq, -se->avg.load_sum); 4739 4740 cfs_rq_util_change(cfs_rq, 0); 4741 4742 trace_pelt_cfs_tp(cfs_rq); 4743 } 4744 4745 /* 4746 * Optional action to be done while updating the load average 4747 */ 4748 #define UPDATE_TG 0x1 4749 #define SKIP_AGE_LOAD 0x2 4750 #define DO_ATTACH 0x4 4751 #define DO_DETACH 0x8 4752 4753 /* Update task and its cfs_rq load average */ 4754 static inline void update_load_avg(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 4755 { 4756 u64 now = cfs_rq_clock_pelt(cfs_rq); 4757 int decayed; 4758 4759 /* 4760 * Track task load average for carrying it to new CPU after migrated, and 4761 * track group sched_entity load average for task_h_load calculation in migration 4762 */ 4763 if (se->avg.last_update_time && !(flags & SKIP_AGE_LOAD)) 4764 __update_load_avg_se(now, cfs_rq, se); 4765 4766 decayed = update_cfs_rq_load_avg(now, cfs_rq); 4767 decayed |= propagate_entity_load_avg(se); 4768 4769 if (!se->avg.last_update_time && (flags & DO_ATTACH)) { 4770 4771 /* 4772 * DO_ATTACH means we're here from enqueue_entity(). 4773 * !last_update_time means we've passed through 4774 * migrate_task_rq_fair() indicating we migrated. 4775 * 4776 * IOW we're enqueueing a task on a new CPU. 4777 */ 4778 attach_entity_load_avg(cfs_rq, se); 4779 update_tg_load_avg(cfs_rq); 4780 4781 } else if (flags & DO_DETACH) { 4782 /* 4783 * DO_DETACH means we're here from dequeue_entity() 4784 * and we are migrating task out of the CPU. 4785 */ 4786 detach_entity_load_avg(cfs_rq, se); 4787 update_tg_load_avg(cfs_rq); 4788 } else if (decayed) { 4789 cfs_rq_util_change(cfs_rq, 0); 4790 4791 if (flags & UPDATE_TG) 4792 update_tg_load_avg(cfs_rq); 4793 } 4794 } 4795 4796 /* 4797 * Synchronize entity load avg of dequeued entity without locking 4798 * the previous rq. 4799 */ 4800 static void sync_entity_load_avg(struct sched_entity *se) 4801 { 4802 struct cfs_rq *cfs_rq = cfs_rq_of(se); 4803 u64 last_update_time; 4804 4805 last_update_time = cfs_rq_last_update_time(cfs_rq); 4806 __update_load_avg_blocked_se(last_update_time, se); 4807 } 4808 4809 /* 4810 * Task first catches up with cfs_rq, and then subtract 4811 * itself from the cfs_rq (task must be off the queue now). 4812 */ 4813 static void remove_entity_load_avg(struct sched_entity *se) 4814 { 4815 struct cfs_rq *cfs_rq = cfs_rq_of(se); 4816 unsigned long flags; 4817 4818 /* 4819 * tasks cannot exit without having gone through wake_up_new_task() -> 4820 * enqueue_task_fair() which will have added things to the cfs_rq, 4821 * so we can remove unconditionally. 4822 */ 4823 4824 sync_entity_load_avg(se); 4825 4826 raw_spin_lock_irqsave(&cfs_rq->removed.lock, flags); 4827 ++cfs_rq->removed.nr; 4828 cfs_rq->removed.util_avg += se->avg.util_avg; 4829 cfs_rq->removed.load_avg += se->avg.load_avg; 4830 cfs_rq->removed.runnable_avg += se->avg.runnable_avg; 4831 raw_spin_unlock_irqrestore(&cfs_rq->removed.lock, flags); 4832 } 4833 4834 static inline unsigned long cfs_rq_runnable_avg(struct cfs_rq *cfs_rq) 4835 { 4836 return cfs_rq->avg.runnable_avg; 4837 } 4838 4839 static inline unsigned long cfs_rq_load_avg(struct cfs_rq *cfs_rq) 4840 { 4841 return cfs_rq->avg.load_avg; 4842 } 4843 4844 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf) 4845 __must_hold(__rq_lockp(this_rq)); 4846 4847 static inline unsigned long task_util(struct task_struct *p) 4848 { 4849 return READ_ONCE(p->se.avg.util_avg); 4850 } 4851 4852 static inline unsigned long task_runnable(struct task_struct *p) 4853 { 4854 return READ_ONCE(p->se.avg.runnable_avg); 4855 } 4856 4857 static inline unsigned long _task_util_est(struct task_struct *p) 4858 { 4859 return READ_ONCE(p->se.avg.util_est) & ~UTIL_AVG_UNCHANGED; 4860 } 4861 4862 static inline unsigned long task_util_est(struct task_struct *p) 4863 { 4864 return max(task_util(p), _task_util_est(p)); 4865 } 4866 4867 static inline void util_est_enqueue(struct cfs_rq *cfs_rq, 4868 struct task_struct *p) 4869 { 4870 unsigned int enqueued; 4871 4872 if (!sched_feat(UTIL_EST)) 4873 return; 4874 4875 /* Update root cfs_rq's estimated utilization */ 4876 enqueued = cfs_rq->avg.util_est; 4877 enqueued += _task_util_est(p); 4878 WRITE_ONCE(cfs_rq->avg.util_est, enqueued); 4879 4880 trace_sched_util_est_cfs_tp(cfs_rq); 4881 } 4882 4883 static inline void util_est_dequeue(struct cfs_rq *cfs_rq, 4884 struct task_struct *p) 4885 { 4886 unsigned int enqueued; 4887 4888 if (!sched_feat(UTIL_EST)) 4889 return; 4890 4891 /* Update root cfs_rq's estimated utilization */ 4892 enqueued = cfs_rq->avg.util_est; 4893 enqueued -= min_t(unsigned int, enqueued, _task_util_est(p)); 4894 WRITE_ONCE(cfs_rq->avg.util_est, enqueued); 4895 4896 trace_sched_util_est_cfs_tp(cfs_rq); 4897 } 4898 4899 #define UTIL_EST_MARGIN (SCHED_CAPACITY_SCALE / 100) 4900 4901 static inline void util_est_update(struct cfs_rq *cfs_rq, 4902 struct task_struct *p, 4903 bool task_sleep) 4904 { 4905 unsigned int ewma, dequeued, last_ewma_diff; 4906 4907 if (!sched_feat(UTIL_EST)) 4908 return; 4909 4910 /* 4911 * Skip update of task's estimated utilization when the task has not 4912 * yet completed an activation, e.g. being migrated. 4913 */ 4914 if (!task_sleep) 4915 return; 4916 4917 /* Get current estimate of utilization */ 4918 ewma = READ_ONCE(p->se.avg.util_est); 4919 4920 /* 4921 * If the PELT values haven't changed since enqueue time, 4922 * skip the util_est update. 4923 */ 4924 if (ewma & UTIL_AVG_UNCHANGED) 4925 return; 4926 4927 /* Get utilization at dequeue */ 4928 dequeued = task_util(p); 4929 4930 /* 4931 * Reset EWMA on utilization increases, the moving average is used only 4932 * to smooth utilization decreases. 4933 */ 4934 if (ewma <= dequeued) { 4935 ewma = dequeued; 4936 goto done; 4937 } 4938 4939 /* 4940 * Skip update of task's estimated utilization when its members are 4941 * already ~1% close to its last activation value. 4942 */ 4943 last_ewma_diff = ewma - dequeued; 4944 if (last_ewma_diff < UTIL_EST_MARGIN) 4945 goto done; 4946 4947 /* 4948 * To avoid underestimate of task utilization, skip updates of EWMA if 4949 * we cannot grant that thread got all CPU time it wanted. 4950 */ 4951 if ((dequeued + UTIL_EST_MARGIN) < task_runnable(p)) 4952 goto done; 4953 4954 4955 /* 4956 * Update Task's estimated utilization 4957 * 4958 * When *p completes an activation we can consolidate another sample 4959 * of the task size. This is done by using this value to update the 4960 * Exponential Weighted Moving Average (EWMA): 4961 * 4962 * ewma(t) = w * task_util(p) + (1-w) * ewma(t-1) 4963 * = w * task_util(p) + ewma(t-1) - w * ewma(t-1) 4964 * = w * (task_util(p) - ewma(t-1)) + ewma(t-1) 4965 * = w * ( -last_ewma_diff ) + ewma(t-1) 4966 * = w * (-last_ewma_diff + ewma(t-1) / w) 4967 * 4968 * Where 'w' is the weight of new samples, which is configured to be 4969 * 0.25, thus making w=1/4 ( >>= UTIL_EST_WEIGHT_SHIFT) 4970 */ 4971 ewma <<= UTIL_EST_WEIGHT_SHIFT; 4972 ewma -= last_ewma_diff; 4973 ewma >>= UTIL_EST_WEIGHT_SHIFT; 4974 done: 4975 ewma |= UTIL_AVG_UNCHANGED; 4976 WRITE_ONCE(p->se.avg.util_est, ewma); 4977 4978 trace_sched_util_est_se_tp(&p->se); 4979 } 4980 4981 static inline unsigned long get_actual_cpu_capacity(int cpu) 4982 { 4983 unsigned long capacity = arch_scale_cpu_capacity(cpu); 4984 4985 capacity -= max(hw_load_avg(cpu_rq(cpu)), cpufreq_get_pressure(cpu)); 4986 4987 return capacity; 4988 } 4989 4990 static inline int util_fits_cpu(unsigned long util, 4991 unsigned long uclamp_min, 4992 unsigned long uclamp_max, 4993 int cpu) 4994 { 4995 unsigned long capacity = capacity_of(cpu); 4996 unsigned long capacity_orig; 4997 bool fits, uclamp_max_fits; 4998 4999 /* 5000 * Check if the real util fits without any uclamp boost/cap applied. 5001 */ 5002 fits = fits_capacity(util, capacity); 5003 5004 if (!uclamp_is_used()) 5005 return fits; 5006 5007 /* 5008 * We must use arch_scale_cpu_capacity() for comparing against uclamp_min and 5009 * uclamp_max. We only care about capacity pressure (by using 5010 * capacity_of()) for comparing against the real util. 5011 * 5012 * If a task is boosted to 1024 for example, we don't want a tiny 5013 * pressure to skew the check whether it fits a CPU or not. 5014 * 5015 * Similarly if a task is capped to arch_scale_cpu_capacity(little_cpu), it 5016 * should fit a little cpu even if there's some pressure. 5017 * 5018 * Only exception is for HW or cpufreq pressure since it has a direct impact 5019 * on available OPP of the system. 5020 * 5021 * We honour it for uclamp_min only as a drop in performance level 5022 * could result in not getting the requested minimum performance level. 5023 * 5024 * For uclamp_max, we can tolerate a drop in performance level as the 5025 * goal is to cap the task. So it's okay if it's getting less. 5026 */ 5027 capacity_orig = arch_scale_cpu_capacity(cpu); 5028 5029 /* 5030 * We want to force a task to fit a cpu as implied by uclamp_max. 5031 * But we do have some corner cases to cater for.. 5032 * 5033 * 5034 * C=z 5035 * | ___ 5036 * | C=y | | 5037 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max 5038 * | C=x | | | | 5039 * | ___ | | | | 5040 * | | | | | | | (util somewhere in this region) 5041 * | | | | | | | 5042 * | | | | | | | 5043 * +---------------------------------------- 5044 * CPU0 CPU1 CPU2 5045 * 5046 * In the above example if a task is capped to a specific performance 5047 * point, y, then when: 5048 * 5049 * * util = 80% of x then it does not fit on CPU0 and should migrate 5050 * to CPU1 5051 * * util = 80% of y then it is forced to fit on CPU1 to honour 5052 * uclamp_max request. 5053 * 5054 * which is what we're enforcing here. A task always fits if 5055 * uclamp_max <= capacity_orig. But when uclamp_max > capacity_orig, 5056 * the normal upmigration rules should withhold still. 5057 * 5058 * Only exception is when we are on max capacity, then we need to be 5059 * careful not to block overutilized state. This is so because: 5060 * 5061 * 1. There's no concept of capping at max_capacity! We can't go 5062 * beyond this performance level anyway. 5063 * 2. The system is being saturated when we're operating near 5064 * max capacity, it doesn't make sense to block overutilized. 5065 */ 5066 uclamp_max_fits = (capacity_orig == SCHED_CAPACITY_SCALE) && (uclamp_max == SCHED_CAPACITY_SCALE); 5067 uclamp_max_fits = !uclamp_max_fits && (uclamp_max <= capacity_orig); 5068 fits = fits || uclamp_max_fits; 5069 5070 /* 5071 * 5072 * C=z 5073 * | ___ (region a, capped, util >= uclamp_max) 5074 * | C=y | | 5075 * |_ _ _ _ _ _ _ _ _ ___ _ _ _ | _ | _ _ _ _ _ uclamp_max 5076 * | C=x | | | | 5077 * | ___ | | | | (region b, uclamp_min <= util <= uclamp_max) 5078 * |_ _ _|_ _|_ _ _ _| _ | _ _ _| _ | _ _ _ _ _ uclamp_min 5079 * | | | | | | | 5080 * | | | | | | | (region c, boosted, util < uclamp_min) 5081 * +---------------------------------------- 5082 * CPU0 CPU1 CPU2 5083 * 5084 * a) If util > uclamp_max, then we're capped, we don't care about 5085 * actual fitness value here. We only care if uclamp_max fits 5086 * capacity without taking margin/pressure into account. 5087 * See comment above. 5088 * 5089 * b) If uclamp_min <= util <= uclamp_max, then the normal 5090 * fits_capacity() rules apply. Except we need to ensure that we 5091 * enforce we remain within uclamp_max, see comment above. 5092 * 5093 * c) If util < uclamp_min, then we are boosted. Same as (b) but we 5094 * need to take into account the boosted value fits the CPU without 5095 * taking margin/pressure into account. 5096 * 5097 * Cases (a) and (b) are handled in the 'fits' variable already. We 5098 * just need to consider an extra check for case (c) after ensuring we 5099 * handle the case uclamp_min > uclamp_max. 5100 */ 5101 uclamp_min = min(uclamp_min, uclamp_max); 5102 if (fits && (util < uclamp_min) && 5103 (uclamp_min > get_actual_cpu_capacity(cpu))) 5104 return -1; 5105 5106 return fits; 5107 } 5108 5109 static inline int task_fits_cpu(struct task_struct *p, int cpu) 5110 { 5111 unsigned long uclamp_min = uclamp_eff_value(p, UCLAMP_MIN); 5112 unsigned long uclamp_max = uclamp_eff_value(p, UCLAMP_MAX); 5113 unsigned long util = task_util_est(p); 5114 /* 5115 * Return true only if the cpu fully fits the task requirements, which 5116 * include the utilization but also the performance hints. 5117 */ 5118 return (util_fits_cpu(util, uclamp_min, uclamp_max, cpu) > 0); 5119 } 5120 5121 static inline void update_misfit_status(struct task_struct *p, struct rq *rq) 5122 { 5123 int cpu = cpu_of(rq); 5124 5125 if (!sched_asym_cpucap_active()) 5126 return; 5127 5128 /* 5129 * Affinity allows us to go somewhere higher? Or are we on biggest 5130 * available CPU already? Or do we fit into this CPU ? 5131 */ 5132 if (!p || (p->nr_cpus_allowed == 1) || 5133 (arch_scale_cpu_capacity(cpu) == p->max_allowed_capacity) || 5134 task_fits_cpu(p, cpu)) { 5135 5136 rq->misfit_task_load = 0; 5137 return; 5138 } 5139 5140 /* 5141 * Make sure that misfit_task_load will not be null even if 5142 * task_h_load() returns 0. 5143 */ 5144 rq->misfit_task_load = max_t(unsigned long, task_h_load(p), 1); 5145 } 5146 5147 void __setparam_fair(struct task_struct *p, const struct sched_attr *attr) 5148 { 5149 struct sched_entity *se = &p->se; 5150 5151 p->static_prio = NICE_TO_PRIO(attr->sched_nice); 5152 if (attr->sched_runtime) { 5153 se->custom_slice = 1; 5154 se->slice = clamp_t(u64, attr->sched_runtime, 5155 NSEC_PER_MSEC/10, /* HZ=1000 * 10 */ 5156 NSEC_PER_MSEC*100); /* HZ=100 / 10 */ 5157 } else { 5158 se->custom_slice = 0; 5159 se->slice = sysctl_sched_base_slice; 5160 } 5161 } 5162 5163 static void 5164 place_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 5165 { 5166 u64 vslice, vruntime = avg_vruntime(cfs_rq); 5167 s64 lag = 0; 5168 5169 if (!se->custom_slice) 5170 se->slice = sysctl_sched_base_slice; 5171 vslice = calc_delta_fair(se->slice, se); 5172 5173 /* 5174 * Due to how V is constructed as the weighted average of entities, 5175 * adding tasks with positive lag, or removing tasks with negative lag 5176 * will move 'time' backwards, this can screw around with the lag of 5177 * other tasks. 5178 * 5179 * EEVDF: placement strategy #1 / #2 5180 */ 5181 if (sched_feat(PLACE_LAG) && cfs_rq->nr_queued && se->vlag) { 5182 struct sched_entity *curr = cfs_rq->curr; 5183 unsigned long load; 5184 5185 lag = se->vlag; 5186 5187 /* 5188 * If we want to place a task and preserve lag, we have to 5189 * consider the effect of the new entity on the weighted 5190 * average and compensate for this, otherwise lag can quickly 5191 * evaporate. 5192 * 5193 * Lag is defined as: 5194 * 5195 * lag_i = S - s_i = w_i * (V - v_i) 5196 * 5197 * To avoid the 'w_i' term all over the place, we only track 5198 * the virtual lag: 5199 * 5200 * vl_i = V - v_i <=> v_i = V - vl_i 5201 * 5202 * And we take V to be the weighted average of all v: 5203 * 5204 * V = (\Sum w_j*v_j) / W 5205 * 5206 * Where W is: \Sum w_j 5207 * 5208 * Then, the weighted average after adding an entity with lag 5209 * vl_i is given by: 5210 * 5211 * V' = (\Sum w_j*v_j + w_i*v_i) / (W + w_i) 5212 * = (W*V + w_i*(V - vl_i)) / (W + w_i) 5213 * = (W*V + w_i*V - w_i*vl_i) / (W + w_i) 5214 * = (V*(W + w_i) - w_i*vl_i) / (W + w_i) 5215 * = V - w_i*vl_i / (W + w_i) 5216 * 5217 * And the actual lag after adding an entity with vl_i is: 5218 * 5219 * vl'_i = V' - v_i 5220 * = V - w_i*vl_i / (W + w_i) - (V - vl_i) 5221 * = vl_i - w_i*vl_i / (W + w_i) 5222 * 5223 * Which is strictly less than vl_i. So in order to preserve lag 5224 * we should inflate the lag before placement such that the 5225 * effective lag after placement comes out right. 5226 * 5227 * As such, invert the above relation for vl'_i to get the vl_i 5228 * we need to use such that the lag after placement is the lag 5229 * we computed before dequeue. 5230 * 5231 * vl'_i = vl_i - w_i*vl_i / (W + w_i) 5232 * = ((W + w_i)*vl_i - w_i*vl_i) / (W + w_i) 5233 * 5234 * (W + w_i)*vl'_i = (W + w_i)*vl_i - w_i*vl_i 5235 * = W*vl_i 5236 * 5237 * vl_i = (W + w_i)*vl'_i / W 5238 */ 5239 load = cfs_rq->sum_weight; 5240 if (curr && curr->on_rq) 5241 load += scale_load_down(curr->load.weight); 5242 5243 lag *= load + scale_load_down(se->load.weight); 5244 if (WARN_ON_ONCE(!load)) 5245 load = 1; 5246 lag = div_s64(lag, load); 5247 } 5248 5249 se->vruntime = vruntime - lag; 5250 5251 if (se->rel_deadline) { 5252 se->deadline += se->vruntime; 5253 se->rel_deadline = 0; 5254 return; 5255 } 5256 5257 /* 5258 * When joining the competition; the existing tasks will be, 5259 * on average, halfway through their slice, as such start tasks 5260 * off with half a slice to ease into the competition. 5261 */ 5262 if (sched_feat(PLACE_DEADLINE_INITIAL) && (flags & ENQUEUE_INITIAL)) 5263 vslice /= 2; 5264 5265 /* 5266 * EEVDF: vd_i = ve_i + r_i/w_i 5267 */ 5268 se->deadline = se->vruntime + vslice; 5269 } 5270 5271 static void check_enqueue_throttle(struct cfs_rq *cfs_rq); 5272 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq); 5273 5274 static void 5275 requeue_delayed_entity(struct sched_entity *se); 5276 5277 static void 5278 enqueue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 5279 { 5280 bool curr = cfs_rq->curr == se; 5281 5282 /* 5283 * If we're the current task, we must renormalise before calling 5284 * update_curr(). 5285 */ 5286 if (curr) 5287 place_entity(cfs_rq, se, flags); 5288 5289 update_curr(cfs_rq); 5290 5291 /* 5292 * When enqueuing a sched_entity, we must: 5293 * - Update loads to have both entity and cfs_rq synced with now. 5294 * - For group_entity, update its runnable_weight to reflect the new 5295 * h_nr_runnable of its group cfs_rq. 5296 * - For group_entity, update its weight to reflect the new share of 5297 * its group cfs_rq 5298 * - Add its new weight to cfs_rq->load.weight 5299 */ 5300 update_load_avg(cfs_rq, se, UPDATE_TG | DO_ATTACH); 5301 se_update_runnable(se); 5302 /* 5303 * XXX update_load_avg() above will have attached us to the pelt sum; 5304 * but update_cfs_group() here will re-adjust the weight and have to 5305 * undo/redo all that. Seems wasteful. 5306 */ 5307 update_cfs_group(se); 5308 5309 /* 5310 * XXX now that the entity has been re-weighted, and it's lag adjusted, 5311 * we can place the entity. 5312 */ 5313 if (!curr) 5314 place_entity(cfs_rq, se, flags); 5315 5316 account_entity_enqueue(cfs_rq, se); 5317 5318 /* Entity has migrated, no longer consider this task hot */ 5319 if (flags & ENQUEUE_MIGRATED) 5320 se->exec_start = 0; 5321 5322 check_schedstat_required(); 5323 update_stats_enqueue_fair(cfs_rq, se, flags); 5324 if (!curr) 5325 __enqueue_entity(cfs_rq, se); 5326 se->on_rq = 1; 5327 5328 if (cfs_rq->nr_queued == 1) { 5329 check_enqueue_throttle(cfs_rq); 5330 list_add_leaf_cfs_rq(cfs_rq); 5331 #ifdef CONFIG_CFS_BANDWIDTH 5332 if (cfs_rq->pelt_clock_throttled) { 5333 struct rq *rq = rq_of(cfs_rq); 5334 5335 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) - 5336 cfs_rq->throttled_clock_pelt; 5337 cfs_rq->pelt_clock_throttled = 0; 5338 } 5339 #endif 5340 } 5341 } 5342 5343 static void __clear_buddies_next(struct sched_entity *se) 5344 { 5345 for_each_sched_entity(se) { 5346 struct cfs_rq *cfs_rq = cfs_rq_of(se); 5347 if (cfs_rq->next != se) 5348 break; 5349 5350 cfs_rq->next = NULL; 5351 } 5352 } 5353 5354 static void clear_buddies(struct cfs_rq *cfs_rq, struct sched_entity *se) 5355 { 5356 if (cfs_rq->next == se) 5357 __clear_buddies_next(se); 5358 } 5359 5360 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq); 5361 5362 static void set_delayed(struct sched_entity *se) 5363 { 5364 se->sched_delayed = 1; 5365 5366 /* 5367 * Delayed se of cfs_rq have no tasks queued on them. 5368 * Do not adjust h_nr_runnable since dequeue_entities() 5369 * will account it for blocked tasks. 5370 */ 5371 if (!entity_is_task(se)) 5372 return; 5373 5374 for_each_sched_entity(se) { 5375 struct cfs_rq *cfs_rq = cfs_rq_of(se); 5376 5377 cfs_rq->h_nr_runnable--; 5378 } 5379 } 5380 5381 static void clear_delayed(struct sched_entity *se) 5382 { 5383 se->sched_delayed = 0; 5384 5385 /* 5386 * Delayed se of cfs_rq have no tasks queued on them. 5387 * Do not adjust h_nr_runnable since a dequeue has 5388 * already accounted for it or an enqueue of a task 5389 * below it will account for it in enqueue_task_fair(). 5390 */ 5391 if (!entity_is_task(se)) 5392 return; 5393 5394 for_each_sched_entity(se) { 5395 struct cfs_rq *cfs_rq = cfs_rq_of(se); 5396 5397 cfs_rq->h_nr_runnable++; 5398 } 5399 } 5400 5401 static inline void finish_delayed_dequeue_entity(struct sched_entity *se) 5402 { 5403 clear_delayed(se); 5404 if (sched_feat(DELAY_ZERO) && se->vlag > 0) 5405 se->vlag = 0; 5406 } 5407 5408 static bool 5409 dequeue_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, int flags) 5410 { 5411 bool sleep = flags & DEQUEUE_SLEEP; 5412 int action = UPDATE_TG; 5413 5414 update_curr(cfs_rq); 5415 clear_buddies(cfs_rq, se); 5416 5417 if (flags & DEQUEUE_DELAYED) { 5418 WARN_ON_ONCE(!se->sched_delayed); 5419 } else { 5420 bool delay = sleep; 5421 /* 5422 * DELAY_DEQUEUE relies on spurious wakeups, special task 5423 * states must not suffer spurious wakeups, excempt them. 5424 */ 5425 if (flags & (DEQUEUE_SPECIAL | DEQUEUE_THROTTLE)) 5426 delay = false; 5427 5428 WARN_ON_ONCE(delay && se->sched_delayed); 5429 5430 if (sched_feat(DELAY_DEQUEUE) && delay && 5431 !entity_eligible(cfs_rq, se)) { 5432 update_load_avg(cfs_rq, se, 0); 5433 set_delayed(se); 5434 return false; 5435 } 5436 } 5437 5438 if (entity_is_task(se) && task_on_rq_migrating(task_of(se))) 5439 action |= DO_DETACH; 5440 5441 /* 5442 * When dequeuing a sched_entity, we must: 5443 * - Update loads to have both entity and cfs_rq synced with now. 5444 * - For group_entity, update its runnable_weight to reflect the new 5445 * h_nr_runnable of its group cfs_rq. 5446 * - Subtract its previous weight from cfs_rq->load.weight. 5447 * - For group entity, update its weight to reflect the new share 5448 * of its group cfs_rq. 5449 */ 5450 update_load_avg(cfs_rq, se, action); 5451 se_update_runnable(se); 5452 5453 update_stats_dequeue_fair(cfs_rq, se, flags); 5454 5455 update_entity_lag(cfs_rq, se); 5456 if (sched_feat(PLACE_REL_DEADLINE) && !sleep) { 5457 se->deadline -= se->vruntime; 5458 se->rel_deadline = 1; 5459 } 5460 5461 if (se != cfs_rq->curr) 5462 __dequeue_entity(cfs_rq, se); 5463 se->on_rq = 0; 5464 account_entity_dequeue(cfs_rq, se); 5465 5466 /* return excess runtime on last dequeue */ 5467 return_cfs_rq_runtime(cfs_rq); 5468 5469 update_cfs_group(se); 5470 5471 if (flags & DEQUEUE_DELAYED) 5472 finish_delayed_dequeue_entity(se); 5473 5474 if (cfs_rq->nr_queued == 0) { 5475 update_idle_cfs_rq_clock_pelt(cfs_rq); 5476 #ifdef CONFIG_CFS_BANDWIDTH 5477 if (throttled_hierarchy(cfs_rq)) { 5478 struct rq *rq = rq_of(cfs_rq); 5479 5480 list_del_leaf_cfs_rq(cfs_rq); 5481 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq); 5482 cfs_rq->pelt_clock_throttled = 1; 5483 } 5484 #endif 5485 } 5486 5487 return true; 5488 } 5489 5490 static void 5491 set_next_entity(struct cfs_rq *cfs_rq, struct sched_entity *se, bool first) 5492 { 5493 clear_buddies(cfs_rq, se); 5494 5495 /* 'current' is not kept within the tree. */ 5496 if (se->on_rq) { 5497 /* 5498 * Any task has to be enqueued before it get to execute on 5499 * a CPU. So account for the time it spent waiting on the 5500 * runqueue. 5501 */ 5502 update_stats_wait_end_fair(cfs_rq, se); 5503 __dequeue_entity(cfs_rq, se); 5504 update_load_avg(cfs_rq, se, UPDATE_TG); 5505 5506 if (first) 5507 set_protect_slice(cfs_rq, se); 5508 } 5509 5510 update_stats_curr_start(cfs_rq, se); 5511 WARN_ON_ONCE(cfs_rq->curr); 5512 cfs_rq->curr = se; 5513 5514 /* 5515 * Track our maximum slice length, if the CPU's load is at 5516 * least twice that of our own weight (i.e. don't track it 5517 * when there are only lesser-weight tasks around): 5518 */ 5519 if (schedstat_enabled() && 5520 rq_of(cfs_rq)->cfs.load.weight >= 2*se->load.weight) { 5521 struct sched_statistics *stats; 5522 5523 stats = __schedstats_from_se(se); 5524 __schedstat_set(stats->slice_max, 5525 max((u64)stats->slice_max, 5526 se->sum_exec_runtime - se->prev_sum_exec_runtime)); 5527 } 5528 5529 se->prev_sum_exec_runtime = se->sum_exec_runtime; 5530 } 5531 5532 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags); 5533 5534 /* 5535 * Pick the next process, keeping these things in mind, in this order: 5536 * 1) keep things fair between processes/task groups 5537 * 2) pick the "next" process, since someone really wants that to run 5538 * 3) pick the "last" process, for cache locality 5539 * 4) do not run the "skip" process, if something else is available 5540 */ 5541 static struct sched_entity * 5542 pick_next_entity(struct rq *rq, struct cfs_rq *cfs_rq) 5543 { 5544 struct sched_entity *se; 5545 5546 se = pick_eevdf(cfs_rq); 5547 if (se->sched_delayed) { 5548 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED); 5549 /* 5550 * Must not reference @se again, see __block_task(). 5551 */ 5552 return NULL; 5553 } 5554 return se; 5555 } 5556 5557 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq); 5558 5559 static void put_prev_entity(struct cfs_rq *cfs_rq, struct sched_entity *prev) 5560 { 5561 /* 5562 * If still on the runqueue then deactivate_task() 5563 * was not called and update_curr() has to be done: 5564 */ 5565 if (prev->on_rq) 5566 update_curr(cfs_rq); 5567 5568 /* throttle cfs_rqs exceeding runtime */ 5569 check_cfs_rq_runtime(cfs_rq); 5570 5571 if (prev->on_rq) { 5572 update_stats_wait_start_fair(cfs_rq, prev); 5573 /* Put 'current' back into the tree. */ 5574 __enqueue_entity(cfs_rq, prev); 5575 /* in !on_rq case, update occurred at dequeue */ 5576 update_load_avg(cfs_rq, prev, 0); 5577 } 5578 WARN_ON_ONCE(cfs_rq->curr != prev); 5579 cfs_rq->curr = NULL; 5580 } 5581 5582 static void 5583 entity_tick(struct cfs_rq *cfs_rq, struct sched_entity *curr, int queued) 5584 { 5585 /* 5586 * Update run-time statistics of the 'current'. 5587 */ 5588 update_curr(cfs_rq); 5589 5590 /* 5591 * Ensure that runnable average is periodically updated. 5592 */ 5593 update_load_avg(cfs_rq, curr, UPDATE_TG); 5594 update_cfs_group(curr); 5595 5596 /* 5597 * Pulls along cfs_rq::zero_vruntime. 5598 */ 5599 avg_vruntime(cfs_rq); 5600 5601 #ifdef CONFIG_SCHED_HRTICK 5602 /* 5603 * queued ticks are scheduled to match the slice, so don't bother 5604 * validating it and just reschedule. 5605 */ 5606 if (queued) { 5607 resched_curr_lazy(rq_of(cfs_rq)); 5608 return; 5609 } 5610 #endif 5611 } 5612 5613 5614 /************************************************** 5615 * CFS bandwidth control machinery 5616 */ 5617 5618 #ifdef CONFIG_CFS_BANDWIDTH 5619 5620 #ifdef CONFIG_JUMP_LABEL 5621 static struct static_key __cfs_bandwidth_used; 5622 5623 static inline bool cfs_bandwidth_used(void) 5624 { 5625 return static_key_false(&__cfs_bandwidth_used); 5626 } 5627 5628 void cfs_bandwidth_usage_inc(void) 5629 { 5630 static_key_slow_inc_cpuslocked(&__cfs_bandwidth_used); 5631 } 5632 5633 void cfs_bandwidth_usage_dec(void) 5634 { 5635 static_key_slow_dec_cpuslocked(&__cfs_bandwidth_used); 5636 } 5637 #else /* !CONFIG_JUMP_LABEL: */ 5638 static bool cfs_bandwidth_used(void) 5639 { 5640 return true; 5641 } 5642 5643 void cfs_bandwidth_usage_inc(void) {} 5644 void cfs_bandwidth_usage_dec(void) {} 5645 #endif /* !CONFIG_JUMP_LABEL */ 5646 5647 static inline u64 sched_cfs_bandwidth_slice(void) 5648 { 5649 return (u64)sysctl_sched_cfs_bandwidth_slice * NSEC_PER_USEC; 5650 } 5651 5652 /* 5653 * Replenish runtime according to assigned quota. We use sched_clock_cpu 5654 * directly instead of rq->clock to avoid adding additional synchronization 5655 * around rq->lock. 5656 * 5657 * requires cfs_b->lock 5658 */ 5659 void __refill_cfs_bandwidth_runtime(struct cfs_bandwidth *cfs_b) 5660 { 5661 s64 runtime; 5662 5663 if (unlikely(cfs_b->quota == RUNTIME_INF)) 5664 return; 5665 5666 cfs_b->runtime += cfs_b->quota; 5667 runtime = cfs_b->runtime_snap - cfs_b->runtime; 5668 if (runtime > 0) { 5669 cfs_b->burst_time += runtime; 5670 cfs_b->nr_burst++; 5671 } 5672 5673 cfs_b->runtime = min(cfs_b->runtime, cfs_b->quota + cfs_b->burst); 5674 cfs_b->runtime_snap = cfs_b->runtime; 5675 } 5676 5677 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg) 5678 { 5679 return &tg->cfs_bandwidth; 5680 } 5681 5682 /* returns 0 on failure to allocate runtime */ 5683 static int __assign_cfs_rq_runtime(struct cfs_bandwidth *cfs_b, 5684 struct cfs_rq *cfs_rq, u64 target_runtime) 5685 { 5686 u64 min_amount, amount = 0; 5687 5688 lockdep_assert_held(&cfs_b->lock); 5689 5690 /* note: this is a positive sum as runtime_remaining <= 0 */ 5691 min_amount = target_runtime - cfs_rq->runtime_remaining; 5692 5693 if (cfs_b->quota == RUNTIME_INF) 5694 amount = min_amount; 5695 else { 5696 start_cfs_bandwidth(cfs_b); 5697 5698 if (cfs_b->runtime > 0) { 5699 amount = min(cfs_b->runtime, min_amount); 5700 cfs_b->runtime -= amount; 5701 cfs_b->idle = 0; 5702 } 5703 } 5704 5705 cfs_rq->runtime_remaining += amount; 5706 5707 return cfs_rq->runtime_remaining > 0; 5708 } 5709 5710 /* returns 0 on failure to allocate runtime */ 5711 static int assign_cfs_rq_runtime(struct cfs_rq *cfs_rq) 5712 { 5713 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 5714 int ret; 5715 5716 raw_spin_lock(&cfs_b->lock); 5717 ret = __assign_cfs_rq_runtime(cfs_b, cfs_rq, sched_cfs_bandwidth_slice()); 5718 raw_spin_unlock(&cfs_b->lock); 5719 5720 return ret; 5721 } 5722 5723 static void __account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) 5724 { 5725 /* dock delta_exec before expiring quota (as it could span periods) */ 5726 cfs_rq->runtime_remaining -= delta_exec; 5727 5728 if (likely(cfs_rq->runtime_remaining > 0)) 5729 return; 5730 5731 if (cfs_rq->throttled) 5732 return; 5733 /* 5734 * if we're unable to extend our runtime we resched so that the active 5735 * hierarchy can be throttled 5736 */ 5737 if (!assign_cfs_rq_runtime(cfs_rq) && likely(cfs_rq->curr)) 5738 resched_curr(rq_of(cfs_rq)); 5739 } 5740 5741 static __always_inline 5742 void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) 5743 { 5744 if (!cfs_bandwidth_used() || !cfs_rq->runtime_enabled) 5745 return; 5746 5747 __account_cfs_rq_runtime(cfs_rq, delta_exec); 5748 } 5749 5750 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq) 5751 { 5752 return cfs_bandwidth_used() && cfs_rq->throttled; 5753 } 5754 5755 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq) 5756 { 5757 return cfs_bandwidth_used() && cfs_rq->pelt_clock_throttled; 5758 } 5759 5760 /* check whether cfs_rq, or any parent, is throttled */ 5761 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq) 5762 { 5763 return cfs_bandwidth_used() && cfs_rq->throttle_count; 5764 } 5765 5766 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu) 5767 { 5768 return throttled_hierarchy(task_group(p)->cfs_rq[dst_cpu]); 5769 } 5770 5771 static inline bool task_is_throttled(struct task_struct *p) 5772 { 5773 return cfs_bandwidth_used() && p->throttled; 5774 } 5775 5776 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags); 5777 static void throttle_cfs_rq_work(struct callback_head *work) 5778 { 5779 struct task_struct *p = container_of(work, struct task_struct, sched_throttle_work); 5780 struct sched_entity *se; 5781 struct cfs_rq *cfs_rq; 5782 struct rq *rq; 5783 5784 WARN_ON_ONCE(p != current); 5785 p->sched_throttle_work.next = &p->sched_throttle_work; 5786 5787 /* 5788 * If task is exiting, then there won't be a return to userspace, so we 5789 * don't have to bother with any of this. 5790 */ 5791 if ((p->flags & PF_EXITING)) 5792 return; 5793 5794 scoped_guard(task_rq_lock, p) { 5795 se = &p->se; 5796 cfs_rq = cfs_rq_of(se); 5797 5798 /* Raced, forget */ 5799 if (p->sched_class != &fair_sched_class) 5800 return; 5801 5802 /* 5803 * If not in limbo, then either replenish has happened or this 5804 * task got migrated out of the throttled cfs_rq, move along. 5805 */ 5806 if (!cfs_rq->throttle_count) 5807 return; 5808 rq = scope.rq; 5809 update_rq_clock(rq); 5810 WARN_ON_ONCE(p->throttled || !list_empty(&p->throttle_node)); 5811 dequeue_task_fair(rq, p, DEQUEUE_SLEEP | DEQUEUE_THROTTLE); 5812 list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list); 5813 /* 5814 * Must not set throttled before dequeue or dequeue will 5815 * mistakenly regard this task as an already throttled one. 5816 */ 5817 p->throttled = true; 5818 resched_curr(rq); 5819 } 5820 } 5821 5822 void init_cfs_throttle_work(struct task_struct *p) 5823 { 5824 init_task_work(&p->sched_throttle_work, throttle_cfs_rq_work); 5825 /* Protect against double add, see throttle_cfs_rq() and throttle_cfs_rq_work() */ 5826 p->sched_throttle_work.next = &p->sched_throttle_work; 5827 INIT_LIST_HEAD(&p->throttle_node); 5828 } 5829 5830 /* 5831 * Task is throttled and someone wants to dequeue it again: 5832 * it could be sched/core when core needs to do things like 5833 * task affinity change, task group change, task sched class 5834 * change etc. and in these cases, DEQUEUE_SLEEP is not set; 5835 * or the task is blocked after throttled due to freezer etc. 5836 * and in these cases, DEQUEUE_SLEEP is set. 5837 */ 5838 static void detach_task_cfs_rq(struct task_struct *p); 5839 static void dequeue_throttled_task(struct task_struct *p, int flags) 5840 { 5841 WARN_ON_ONCE(p->se.on_rq); 5842 list_del_init(&p->throttle_node); 5843 5844 /* task blocked after throttled */ 5845 if (flags & DEQUEUE_SLEEP) { 5846 p->throttled = false; 5847 return; 5848 } 5849 5850 /* 5851 * task is migrating off its old cfs_rq, detach 5852 * the task's load from its old cfs_rq. 5853 */ 5854 if (task_on_rq_migrating(p)) 5855 detach_task_cfs_rq(p); 5856 } 5857 5858 static bool enqueue_throttled_task(struct task_struct *p) 5859 { 5860 struct cfs_rq *cfs_rq = cfs_rq_of(&p->se); 5861 5862 /* @p should have gone through dequeue_throttled_task() first */ 5863 WARN_ON_ONCE(!list_empty(&p->throttle_node)); 5864 5865 /* 5866 * If the throttled task @p is enqueued to a throttled cfs_rq, 5867 * take the fast path by directly putting the task on the 5868 * target cfs_rq's limbo list. 5869 * 5870 * Do not do that when @p is current because the following race can 5871 * cause @p's group_node to be incorectly re-insterted in its rq's 5872 * cfs_tasks list, despite being throttled: 5873 * 5874 * cpuX cpuY 5875 * p ret2user 5876 * throttle_cfs_rq_work() sched_move_task(p) 5877 * LOCK task_rq_lock 5878 * dequeue_task_fair(p) 5879 * UNLOCK task_rq_lock 5880 * LOCK task_rq_lock 5881 * task_current_donor(p) == true 5882 * task_on_rq_queued(p) == true 5883 * dequeue_task(p) 5884 * put_prev_task(p) 5885 * sched_change_group() 5886 * enqueue_task(p) -> p's new cfs_rq 5887 * is throttled, go 5888 * fast path and skip 5889 * actual enqueue 5890 * set_next_task(p) 5891 * list_move(&se->group_node, &rq->cfs_tasks); // bug 5892 * schedule() 5893 * 5894 * In the above race case, @p current cfs_rq is in the same rq as 5895 * its previous cfs_rq because sched_move_task() only moves a task 5896 * to a different group from the same rq, so we can use its current 5897 * cfs_rq to derive rq and test if the task is current. 5898 */ 5899 if (throttled_hierarchy(cfs_rq) && 5900 !task_current_donor(rq_of(cfs_rq), p)) { 5901 list_add(&p->throttle_node, &cfs_rq->throttled_limbo_list); 5902 return true; 5903 } 5904 5905 /* we can't take the fast path, do an actual enqueue*/ 5906 p->throttled = false; 5907 return false; 5908 } 5909 5910 static void enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags); 5911 static int tg_unthrottle_up(struct task_group *tg, void *data) 5912 { 5913 struct rq *rq = data; 5914 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)]; 5915 struct task_struct *p, *tmp; 5916 5917 if (--cfs_rq->throttle_count) 5918 return 0; 5919 5920 if (cfs_rq->pelt_clock_throttled) { 5921 cfs_rq->throttled_clock_pelt_time += rq_clock_pelt(rq) - 5922 cfs_rq->throttled_clock_pelt; 5923 cfs_rq->pelt_clock_throttled = 0; 5924 } 5925 5926 if (cfs_rq->throttled_clock_self) { 5927 u64 delta = rq_clock(rq) - cfs_rq->throttled_clock_self; 5928 5929 cfs_rq->throttled_clock_self = 0; 5930 5931 if (WARN_ON_ONCE((s64)delta < 0)) 5932 delta = 0; 5933 5934 cfs_rq->throttled_clock_self_time += delta; 5935 } 5936 5937 /* Re-enqueue the tasks that have been throttled at this level. */ 5938 list_for_each_entry_safe(p, tmp, &cfs_rq->throttled_limbo_list, throttle_node) { 5939 list_del_init(&p->throttle_node); 5940 p->throttled = false; 5941 enqueue_task_fair(rq_of(cfs_rq), p, ENQUEUE_WAKEUP); 5942 } 5943 5944 /* Add cfs_rq with load or one or more already running entities to the list */ 5945 if (!cfs_rq_is_decayed(cfs_rq)) 5946 list_add_leaf_cfs_rq(cfs_rq); 5947 5948 return 0; 5949 } 5950 5951 static inline bool task_has_throttle_work(struct task_struct *p) 5952 { 5953 return p->sched_throttle_work.next != &p->sched_throttle_work; 5954 } 5955 5956 static inline void task_throttle_setup_work(struct task_struct *p) 5957 { 5958 if (task_has_throttle_work(p)) 5959 return; 5960 5961 /* 5962 * Kthreads and exiting tasks don't return to userspace, so adding the 5963 * work is pointless 5964 */ 5965 if ((p->flags & (PF_EXITING | PF_KTHREAD))) 5966 return; 5967 5968 task_work_add(p, &p->sched_throttle_work, TWA_RESUME); 5969 } 5970 5971 static void record_throttle_clock(struct cfs_rq *cfs_rq) 5972 { 5973 struct rq *rq = rq_of(cfs_rq); 5974 5975 if (cfs_rq_throttled(cfs_rq) && !cfs_rq->throttled_clock) 5976 cfs_rq->throttled_clock = rq_clock(rq); 5977 5978 if (!cfs_rq->throttled_clock_self) 5979 cfs_rq->throttled_clock_self = rq_clock(rq); 5980 } 5981 5982 static int tg_throttle_down(struct task_group *tg, void *data) 5983 { 5984 struct rq *rq = data; 5985 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)]; 5986 5987 if (cfs_rq->throttle_count++) 5988 return 0; 5989 5990 /* 5991 * For cfs_rqs that still have entities enqueued, PELT clock 5992 * stop happens at dequeue time when all entities are dequeued. 5993 */ 5994 if (!cfs_rq->nr_queued) { 5995 list_del_leaf_cfs_rq(cfs_rq); 5996 cfs_rq->throttled_clock_pelt = rq_clock_pelt(rq); 5997 cfs_rq->pelt_clock_throttled = 1; 5998 } 5999 6000 WARN_ON_ONCE(cfs_rq->throttled_clock_self); 6001 WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_limbo_list)); 6002 return 0; 6003 } 6004 6005 static bool throttle_cfs_rq(struct cfs_rq *cfs_rq) 6006 { 6007 struct rq *rq = rq_of(cfs_rq); 6008 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 6009 int dequeue = 1; 6010 6011 raw_spin_lock(&cfs_b->lock); 6012 /* This will start the period timer if necessary */ 6013 if (__assign_cfs_rq_runtime(cfs_b, cfs_rq, 1)) { 6014 /* 6015 * We have raced with bandwidth becoming available, and if we 6016 * actually throttled the timer might not unthrottle us for an 6017 * entire period. We additionally needed to make sure that any 6018 * subsequent check_cfs_rq_runtime calls agree not to throttle 6019 * us, as we may commit to do cfs put_prev+pick_next, so we ask 6020 * for 1ns of runtime rather than just check cfs_b. 6021 */ 6022 dequeue = 0; 6023 } else { 6024 list_add_tail_rcu(&cfs_rq->throttled_list, 6025 &cfs_b->throttled_cfs_rq); 6026 } 6027 raw_spin_unlock(&cfs_b->lock); 6028 6029 if (!dequeue) 6030 return false; /* Throttle no longer required. */ 6031 6032 /* freeze hierarchy runnable averages while throttled */ 6033 rcu_read_lock(); 6034 walk_tg_tree_from(cfs_rq->tg, tg_throttle_down, tg_nop, (void *)rq); 6035 rcu_read_unlock(); 6036 6037 /* 6038 * Note: distribution will already see us throttled via the 6039 * throttled-list. rq->lock protects completion. 6040 */ 6041 cfs_rq->throttled = 1; 6042 WARN_ON_ONCE(cfs_rq->throttled_clock); 6043 return true; 6044 } 6045 6046 void unthrottle_cfs_rq(struct cfs_rq *cfs_rq) 6047 { 6048 struct rq *rq = rq_of(cfs_rq); 6049 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 6050 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)]; 6051 6052 /* 6053 * It's possible we are called with runtime_remaining < 0 due to things 6054 * like async unthrottled us with a positive runtime_remaining but other 6055 * still running entities consumed those runtime before we reached here. 6056 * 6057 * We can't unthrottle this cfs_rq without any runtime remaining because 6058 * any enqueue in tg_unthrottle_up() will immediately trigger a throttle, 6059 * which is not supposed to happen on unthrottle path. 6060 */ 6061 if (cfs_rq->runtime_enabled && cfs_rq->runtime_remaining <= 0) 6062 return; 6063 6064 cfs_rq->throttled = 0; 6065 6066 update_rq_clock(rq); 6067 6068 raw_spin_lock(&cfs_b->lock); 6069 if (cfs_rq->throttled_clock) { 6070 cfs_b->throttled_time += rq_clock(rq) - cfs_rq->throttled_clock; 6071 cfs_rq->throttled_clock = 0; 6072 } 6073 list_del_rcu(&cfs_rq->throttled_list); 6074 raw_spin_unlock(&cfs_b->lock); 6075 6076 /* update hierarchical throttle state */ 6077 walk_tg_tree_from(cfs_rq->tg, tg_nop, tg_unthrottle_up, (void *)rq); 6078 6079 if (!cfs_rq->load.weight) { 6080 if (!cfs_rq->on_list) 6081 return; 6082 /* 6083 * Nothing to run but something to decay (on_list)? 6084 * Complete the branch. 6085 */ 6086 for_each_sched_entity(se) { 6087 if (list_add_leaf_cfs_rq(cfs_rq_of(se))) 6088 break; 6089 } 6090 } 6091 6092 assert_list_leaf_cfs_rq(rq); 6093 6094 /* Determine whether we need to wake up potentially idle CPU: */ 6095 if (rq->curr == rq->idle && rq->cfs.nr_queued) 6096 resched_curr(rq); 6097 } 6098 6099 static void __cfsb_csd_unthrottle(void *arg) 6100 { 6101 struct cfs_rq *cursor, *tmp; 6102 struct rq *rq = arg; 6103 struct rq_flags rf; 6104 6105 rq_lock(rq, &rf); 6106 6107 /* 6108 * Iterating over the list can trigger several call to 6109 * update_rq_clock() in unthrottle_cfs_rq(). 6110 * Do it once and skip the potential next ones. 6111 */ 6112 update_rq_clock(rq); 6113 rq_clock_start_loop_update(rq); 6114 6115 /* 6116 * Since we hold rq lock we're safe from concurrent manipulation of 6117 * the CSD list. However, this RCU critical section annotates the 6118 * fact that we pair with sched_free_group_rcu(), so that we cannot 6119 * race with group being freed in the window between removing it 6120 * from the list and advancing to the next entry in the list. 6121 */ 6122 rcu_read_lock(); 6123 6124 list_for_each_entry_safe(cursor, tmp, &rq->cfsb_csd_list, 6125 throttled_csd_list) { 6126 list_del_init(&cursor->throttled_csd_list); 6127 6128 if (cfs_rq_throttled(cursor)) 6129 unthrottle_cfs_rq(cursor); 6130 } 6131 6132 rcu_read_unlock(); 6133 6134 rq_clock_stop_loop_update(rq); 6135 rq_unlock(rq, &rf); 6136 } 6137 6138 static inline void __unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq) 6139 { 6140 struct rq *rq = rq_of(cfs_rq); 6141 bool first; 6142 6143 if (rq == this_rq()) { 6144 unthrottle_cfs_rq(cfs_rq); 6145 return; 6146 } 6147 6148 /* Already enqueued */ 6149 if (WARN_ON_ONCE(!list_empty(&cfs_rq->throttled_csd_list))) 6150 return; 6151 6152 first = list_empty(&rq->cfsb_csd_list); 6153 list_add_tail(&cfs_rq->throttled_csd_list, &rq->cfsb_csd_list); 6154 if (first) 6155 smp_call_function_single_async(cpu_of(rq), &rq->cfsb_csd); 6156 } 6157 6158 static void unthrottle_cfs_rq_async(struct cfs_rq *cfs_rq) 6159 { 6160 lockdep_assert_rq_held(rq_of(cfs_rq)); 6161 6162 if (WARN_ON_ONCE(!cfs_rq_throttled(cfs_rq) || 6163 cfs_rq->runtime_remaining <= 0)) 6164 return; 6165 6166 __unthrottle_cfs_rq_async(cfs_rq); 6167 } 6168 6169 static bool distribute_cfs_runtime(struct cfs_bandwidth *cfs_b) 6170 { 6171 int this_cpu = smp_processor_id(); 6172 u64 runtime, remaining = 1; 6173 bool throttled = false; 6174 struct cfs_rq *cfs_rq, *tmp; 6175 struct rq_flags rf; 6176 struct rq *rq; 6177 LIST_HEAD(local_unthrottle); 6178 6179 rcu_read_lock(); 6180 list_for_each_entry_rcu(cfs_rq, &cfs_b->throttled_cfs_rq, 6181 throttled_list) { 6182 rq = rq_of(cfs_rq); 6183 6184 if (!remaining) { 6185 throttled = true; 6186 break; 6187 } 6188 6189 rq_lock_irqsave(rq, &rf); 6190 if (!cfs_rq_throttled(cfs_rq)) 6191 goto next; 6192 6193 /* Already queued for async unthrottle */ 6194 if (!list_empty(&cfs_rq->throttled_csd_list)) 6195 goto next; 6196 6197 /* By the above checks, this should never be true */ 6198 WARN_ON_ONCE(cfs_rq->runtime_remaining > 0); 6199 6200 raw_spin_lock(&cfs_b->lock); 6201 runtime = -cfs_rq->runtime_remaining + 1; 6202 if (runtime > cfs_b->runtime) 6203 runtime = cfs_b->runtime; 6204 cfs_b->runtime -= runtime; 6205 remaining = cfs_b->runtime; 6206 raw_spin_unlock(&cfs_b->lock); 6207 6208 cfs_rq->runtime_remaining += runtime; 6209 6210 /* we check whether we're throttled above */ 6211 if (cfs_rq->runtime_remaining > 0) { 6212 if (cpu_of(rq) != this_cpu) { 6213 unthrottle_cfs_rq_async(cfs_rq); 6214 } else { 6215 /* 6216 * We currently only expect to be unthrottling 6217 * a single cfs_rq locally. 6218 */ 6219 WARN_ON_ONCE(!list_empty(&local_unthrottle)); 6220 list_add_tail(&cfs_rq->throttled_csd_list, 6221 &local_unthrottle); 6222 } 6223 } else { 6224 throttled = true; 6225 } 6226 6227 next: 6228 rq_unlock_irqrestore(rq, &rf); 6229 } 6230 6231 list_for_each_entry_safe(cfs_rq, tmp, &local_unthrottle, 6232 throttled_csd_list) { 6233 struct rq *rq = rq_of(cfs_rq); 6234 6235 rq_lock_irqsave(rq, &rf); 6236 6237 list_del_init(&cfs_rq->throttled_csd_list); 6238 6239 if (cfs_rq_throttled(cfs_rq)) 6240 unthrottle_cfs_rq(cfs_rq); 6241 6242 rq_unlock_irqrestore(rq, &rf); 6243 } 6244 WARN_ON_ONCE(!list_empty(&local_unthrottle)); 6245 6246 rcu_read_unlock(); 6247 6248 return throttled; 6249 } 6250 6251 /* 6252 * Responsible for refilling a task_group's bandwidth and unthrottling its 6253 * cfs_rqs as appropriate. If there has been no activity within the last 6254 * period the timer is deactivated until scheduling resumes; cfs_b->idle is 6255 * used to track this state. 6256 */ 6257 static int do_sched_cfs_period_timer(struct cfs_bandwidth *cfs_b, int overrun, unsigned long flags) 6258 __must_hold(&cfs_b->lock) 6259 { 6260 int throttled; 6261 6262 /* no need to continue the timer with no bandwidth constraint */ 6263 if (cfs_b->quota == RUNTIME_INF) 6264 goto out_deactivate; 6265 6266 throttled = !list_empty(&cfs_b->throttled_cfs_rq); 6267 cfs_b->nr_periods += overrun; 6268 6269 /* Refill extra burst quota even if cfs_b->idle */ 6270 __refill_cfs_bandwidth_runtime(cfs_b); 6271 6272 /* 6273 * idle depends on !throttled (for the case of a large deficit), and if 6274 * we're going inactive then everything else can be deferred 6275 */ 6276 if (cfs_b->idle && !throttled) 6277 goto out_deactivate; 6278 6279 if (!throttled) { 6280 /* mark as potentially idle for the upcoming period */ 6281 cfs_b->idle = 1; 6282 return 0; 6283 } 6284 6285 /* account preceding periods in which throttling occurred */ 6286 cfs_b->nr_throttled += overrun; 6287 6288 /* 6289 * This check is repeated as we release cfs_b->lock while we unthrottle. 6290 */ 6291 while (throttled && cfs_b->runtime > 0) { 6292 raw_spin_unlock_irqrestore(&cfs_b->lock, flags); 6293 /* we can't nest cfs_b->lock while distributing bandwidth */ 6294 throttled = distribute_cfs_runtime(cfs_b); 6295 raw_spin_lock_irqsave(&cfs_b->lock, flags); 6296 } 6297 6298 /* 6299 * While we are ensured activity in the period following an 6300 * unthrottle, this also covers the case in which the new bandwidth is 6301 * insufficient to cover the existing bandwidth deficit. (Forcing the 6302 * timer to remain active while there are any throttled entities.) 6303 */ 6304 cfs_b->idle = 0; 6305 6306 return 0; 6307 6308 out_deactivate: 6309 return 1; 6310 } 6311 6312 /* a cfs_rq won't donate quota below this amount */ 6313 static const u64 min_cfs_rq_runtime = 1 * NSEC_PER_MSEC; 6314 /* minimum remaining period time to redistribute slack quota */ 6315 static const u64 min_bandwidth_expiration = 2 * NSEC_PER_MSEC; 6316 /* how long we wait to gather additional slack before distributing */ 6317 static const u64 cfs_bandwidth_slack_period = 5 * NSEC_PER_MSEC; 6318 6319 /* 6320 * Are we near the end of the current quota period? 6321 * 6322 * Requires cfs_b->lock for hrtimer_expires_remaining to be safe against the 6323 * hrtimer base being cleared by hrtimer_start. In the case of 6324 * migrate_hrtimers, base is never cleared, so we are fine. 6325 */ 6326 static int runtime_refresh_within(struct cfs_bandwidth *cfs_b, u64 min_expire) 6327 { 6328 struct hrtimer *refresh_timer = &cfs_b->period_timer; 6329 s64 remaining; 6330 6331 /* if the call-back is running a quota refresh is already occurring */ 6332 if (hrtimer_callback_running(refresh_timer)) 6333 return 1; 6334 6335 /* is a quota refresh about to occur? */ 6336 remaining = ktime_to_ns(hrtimer_expires_remaining(refresh_timer)); 6337 if (remaining < (s64)min_expire) 6338 return 1; 6339 6340 return 0; 6341 } 6342 6343 static void start_cfs_slack_bandwidth(struct cfs_bandwidth *cfs_b) 6344 { 6345 u64 min_left = cfs_bandwidth_slack_period + min_bandwidth_expiration; 6346 6347 /* if there's a quota refresh soon don't bother with slack */ 6348 if (runtime_refresh_within(cfs_b, min_left)) 6349 return; 6350 6351 /* don't push forwards an existing deferred unthrottle */ 6352 if (cfs_b->slack_started) 6353 return; 6354 cfs_b->slack_started = true; 6355 6356 hrtimer_start(&cfs_b->slack_timer, 6357 ns_to_ktime(cfs_bandwidth_slack_period), 6358 HRTIMER_MODE_REL); 6359 } 6360 6361 /* we know any runtime found here is valid as update_curr() precedes return */ 6362 static void __return_cfs_rq_runtime(struct cfs_rq *cfs_rq) 6363 { 6364 struct cfs_bandwidth *cfs_b = tg_cfs_bandwidth(cfs_rq->tg); 6365 s64 slack_runtime = cfs_rq->runtime_remaining - min_cfs_rq_runtime; 6366 6367 if (slack_runtime <= 0) 6368 return; 6369 6370 raw_spin_lock(&cfs_b->lock); 6371 if (cfs_b->quota != RUNTIME_INF) { 6372 cfs_b->runtime += slack_runtime; 6373 6374 /* we are under rq->lock, defer unthrottling using a timer */ 6375 if (cfs_b->runtime > sched_cfs_bandwidth_slice() && 6376 !list_empty(&cfs_b->throttled_cfs_rq)) 6377 start_cfs_slack_bandwidth(cfs_b); 6378 } 6379 raw_spin_unlock(&cfs_b->lock); 6380 6381 /* even if it's not valid for return we don't want to try again */ 6382 cfs_rq->runtime_remaining -= slack_runtime; 6383 } 6384 6385 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) 6386 { 6387 if (!cfs_bandwidth_used()) 6388 return; 6389 6390 if (!cfs_rq->runtime_enabled || cfs_rq->nr_queued) 6391 return; 6392 6393 __return_cfs_rq_runtime(cfs_rq); 6394 } 6395 6396 /* 6397 * This is done with a timer (instead of inline with bandwidth return) since 6398 * it's necessary to juggle rq->locks to unthrottle their respective cfs_rqs. 6399 */ 6400 static void do_sched_cfs_slack_timer(struct cfs_bandwidth *cfs_b) 6401 { 6402 u64 runtime = 0, slice = sched_cfs_bandwidth_slice(); 6403 unsigned long flags; 6404 6405 /* confirm we're still not at a refresh boundary */ 6406 raw_spin_lock_irqsave(&cfs_b->lock, flags); 6407 cfs_b->slack_started = false; 6408 6409 if (runtime_refresh_within(cfs_b, min_bandwidth_expiration)) { 6410 raw_spin_unlock_irqrestore(&cfs_b->lock, flags); 6411 return; 6412 } 6413 6414 if (cfs_b->quota != RUNTIME_INF && cfs_b->runtime > slice) 6415 runtime = cfs_b->runtime; 6416 6417 raw_spin_unlock_irqrestore(&cfs_b->lock, flags); 6418 6419 if (!runtime) 6420 return; 6421 6422 distribute_cfs_runtime(cfs_b); 6423 } 6424 6425 /* 6426 * When a group wakes up we want to make sure that its quota is not already 6427 * expired/exceeded, otherwise it may be allowed to steal additional ticks of 6428 * runtime as update_curr() throttling can not trigger until it's on-rq. 6429 */ 6430 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) 6431 { 6432 if (!cfs_bandwidth_used()) 6433 return; 6434 6435 /* an active group must be handled by the update_curr()->put() path */ 6436 if (!cfs_rq->runtime_enabled || cfs_rq->curr) 6437 return; 6438 6439 /* ensure the group is not already throttled */ 6440 if (cfs_rq_throttled(cfs_rq)) 6441 return; 6442 6443 /* update runtime allocation */ 6444 account_cfs_rq_runtime(cfs_rq, 0); 6445 if (cfs_rq->runtime_remaining <= 0) 6446 throttle_cfs_rq(cfs_rq); 6447 } 6448 6449 static void sync_throttle(struct task_group *tg, int cpu) 6450 { 6451 struct cfs_rq *pcfs_rq, *cfs_rq; 6452 6453 if (!cfs_bandwidth_used()) 6454 return; 6455 6456 if (!tg->parent) 6457 return; 6458 6459 cfs_rq = tg->cfs_rq[cpu]; 6460 pcfs_rq = tg->parent->cfs_rq[cpu]; 6461 6462 cfs_rq->throttle_count = pcfs_rq->throttle_count; 6463 cfs_rq->throttled_clock_pelt = rq_clock_pelt(cpu_rq(cpu)); 6464 6465 /* 6466 * It is not enough to sync the "pelt_clock_throttled" indicator 6467 * with the parent cfs_rq when the hierarchy is not queued. 6468 * Always join a throttled hierarchy with PELT clock throttled 6469 * and leaf it to the first enqueue, or distribution to 6470 * unthrottle the PELT clock. 6471 */ 6472 if (cfs_rq->throttle_count) 6473 cfs_rq->pelt_clock_throttled = 1; 6474 } 6475 6476 /* conditionally throttle active cfs_rq's from put_prev_entity() */ 6477 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) 6478 { 6479 if (!cfs_bandwidth_used()) 6480 return false; 6481 6482 if (likely(!cfs_rq->runtime_enabled || cfs_rq->runtime_remaining > 0)) 6483 return false; 6484 6485 /* 6486 * it's possible for a throttled entity to be forced into a running 6487 * state (e.g. set_curr_task), in this case we're finished. 6488 */ 6489 if (cfs_rq_throttled(cfs_rq)) 6490 return true; 6491 6492 return throttle_cfs_rq(cfs_rq); 6493 } 6494 6495 static enum hrtimer_restart sched_cfs_slack_timer(struct hrtimer *timer) 6496 { 6497 struct cfs_bandwidth *cfs_b = 6498 container_of(timer, struct cfs_bandwidth, slack_timer); 6499 6500 do_sched_cfs_slack_timer(cfs_b); 6501 6502 return HRTIMER_NORESTART; 6503 } 6504 6505 static enum hrtimer_restart sched_cfs_period_timer(struct hrtimer *timer) 6506 { 6507 struct cfs_bandwidth *cfs_b = 6508 container_of(timer, struct cfs_bandwidth, period_timer); 6509 unsigned long flags; 6510 int overrun; 6511 int idle = 0; 6512 int count = 0; 6513 6514 raw_spin_lock_irqsave(&cfs_b->lock, flags); 6515 for (;;) { 6516 overrun = hrtimer_forward_now(timer, cfs_b->period); 6517 if (!overrun) 6518 break; 6519 6520 idle = do_sched_cfs_period_timer(cfs_b, overrun, flags); 6521 6522 if (++count > 3) { 6523 u64 new, old = ktime_to_ns(cfs_b->period); 6524 6525 /* 6526 * Grow period by a factor of 2 to avoid losing precision. 6527 * Precision loss in the quota/period ratio can cause __cfs_schedulable 6528 * to fail. 6529 */ 6530 new = old * 2; 6531 if (new < max_bw_quota_period_us * NSEC_PER_USEC) { 6532 cfs_b->period = ns_to_ktime(new); 6533 cfs_b->quota *= 2; 6534 cfs_b->burst *= 2; 6535 6536 pr_warn_ratelimited( 6537 "cfs_period_timer[cpu%d]: period too short, scaling up (new cfs_period_us = %lld, cfs_quota_us = %lld)\n", 6538 smp_processor_id(), 6539 div_u64(new, NSEC_PER_USEC), 6540 div_u64(cfs_b->quota, NSEC_PER_USEC)); 6541 } else { 6542 pr_warn_ratelimited( 6543 "cfs_period_timer[cpu%d]: period too short, but cannot scale up without losing precision (cfs_period_us = %lld, cfs_quota_us = %lld)\n", 6544 smp_processor_id(), 6545 div_u64(old, NSEC_PER_USEC), 6546 div_u64(cfs_b->quota, NSEC_PER_USEC)); 6547 } 6548 6549 /* reset count so we don't come right back in here */ 6550 count = 0; 6551 } 6552 } 6553 if (idle) 6554 cfs_b->period_active = 0; 6555 raw_spin_unlock_irqrestore(&cfs_b->lock, flags); 6556 6557 return idle ? HRTIMER_NORESTART : HRTIMER_RESTART; 6558 } 6559 6560 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) 6561 { 6562 raw_spin_lock_init(&cfs_b->lock); 6563 cfs_b->runtime = 0; 6564 cfs_b->quota = RUNTIME_INF; 6565 cfs_b->period = us_to_ktime(default_bw_period_us()); 6566 cfs_b->burst = 0; 6567 cfs_b->hierarchical_quota = parent ? parent->hierarchical_quota : RUNTIME_INF; 6568 6569 INIT_LIST_HEAD(&cfs_b->throttled_cfs_rq); 6570 hrtimer_setup(&cfs_b->period_timer, sched_cfs_period_timer, CLOCK_MONOTONIC, 6571 HRTIMER_MODE_ABS_PINNED); 6572 6573 /* Add a random offset so that timers interleave */ 6574 hrtimer_set_expires(&cfs_b->period_timer, 6575 get_random_u32_below(cfs_b->period)); 6576 hrtimer_setup(&cfs_b->slack_timer, sched_cfs_slack_timer, CLOCK_MONOTONIC, 6577 HRTIMER_MODE_REL); 6578 cfs_b->slack_started = false; 6579 } 6580 6581 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) 6582 { 6583 cfs_rq->runtime_enabled = 0; 6584 INIT_LIST_HEAD(&cfs_rq->throttled_list); 6585 INIT_LIST_HEAD(&cfs_rq->throttled_csd_list); 6586 INIT_LIST_HEAD(&cfs_rq->throttled_limbo_list); 6587 } 6588 6589 void start_cfs_bandwidth(struct cfs_bandwidth *cfs_b) 6590 { 6591 lockdep_assert_held(&cfs_b->lock); 6592 6593 if (cfs_b->period_active) 6594 return; 6595 6596 cfs_b->period_active = 1; 6597 hrtimer_forward_now(&cfs_b->period_timer, cfs_b->period); 6598 hrtimer_start_expires(&cfs_b->period_timer, HRTIMER_MODE_ABS_PINNED); 6599 } 6600 6601 static void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) 6602 { 6603 int __maybe_unused i; 6604 6605 /* init_cfs_bandwidth() was not called */ 6606 if (!cfs_b->throttled_cfs_rq.next) 6607 return; 6608 6609 hrtimer_cancel(&cfs_b->period_timer); 6610 hrtimer_cancel(&cfs_b->slack_timer); 6611 6612 /* 6613 * It is possible that we still have some cfs_rq's pending on a CSD 6614 * list, though this race is very rare. In order for this to occur, we 6615 * must have raced with the last task leaving the group while there 6616 * exist throttled cfs_rq(s), and the period_timer must have queued the 6617 * CSD item but the remote cpu has not yet processed it. To handle this, 6618 * we can simply flush all pending CSD work inline here. We're 6619 * guaranteed at this point that no additional cfs_rq of this group can 6620 * join a CSD list. 6621 */ 6622 for_each_possible_cpu(i) { 6623 struct rq *rq = cpu_rq(i); 6624 unsigned long flags; 6625 6626 if (list_empty(&rq->cfsb_csd_list)) 6627 continue; 6628 6629 local_irq_save(flags); 6630 __cfsb_csd_unthrottle(rq); 6631 local_irq_restore(flags); 6632 } 6633 } 6634 6635 /* 6636 * Both these CPU hotplug callbacks race against unregister_fair_sched_group() 6637 * 6638 * The race is harmless, since modifying bandwidth settings of unhooked group 6639 * bits doesn't do much. 6640 */ 6641 6642 /* cpu online callback */ 6643 static void __maybe_unused update_runtime_enabled(struct rq *rq) 6644 { 6645 struct task_group *tg; 6646 6647 lockdep_assert_rq_held(rq); 6648 6649 rcu_read_lock(); 6650 list_for_each_entry_rcu(tg, &task_groups, list) { 6651 struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; 6652 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)]; 6653 6654 raw_spin_lock(&cfs_b->lock); 6655 cfs_rq->runtime_enabled = cfs_b->quota != RUNTIME_INF; 6656 raw_spin_unlock(&cfs_b->lock); 6657 } 6658 rcu_read_unlock(); 6659 } 6660 6661 /* cpu offline callback */ 6662 static void __maybe_unused unthrottle_offline_cfs_rqs(struct rq *rq) 6663 { 6664 struct task_group *tg; 6665 6666 lockdep_assert_rq_held(rq); 6667 6668 // Do not unthrottle for an active CPU 6669 if (cpumask_test_cpu(cpu_of(rq), cpu_active_mask)) 6670 return; 6671 6672 /* 6673 * The rq clock has already been updated in the 6674 * set_rq_offline(), so we should skip updating 6675 * the rq clock again in unthrottle_cfs_rq(). 6676 */ 6677 rq_clock_start_loop_update(rq); 6678 6679 rcu_read_lock(); 6680 list_for_each_entry_rcu(tg, &task_groups, list) { 6681 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu_of(rq)]; 6682 6683 if (!cfs_rq->runtime_enabled) 6684 continue; 6685 6686 /* 6687 * Offline rq is schedulable till CPU is completely disabled 6688 * in take_cpu_down(), so we prevent new cfs throttling here. 6689 */ 6690 cfs_rq->runtime_enabled = 0; 6691 6692 if (!cfs_rq_throttled(cfs_rq)) 6693 continue; 6694 6695 /* 6696 * clock_task is not advancing so we just need to make sure 6697 * there's some valid quota amount 6698 */ 6699 cfs_rq->runtime_remaining = 1; 6700 unthrottle_cfs_rq(cfs_rq); 6701 } 6702 rcu_read_unlock(); 6703 6704 rq_clock_stop_loop_update(rq); 6705 } 6706 6707 bool cfs_task_bw_constrained(struct task_struct *p) 6708 { 6709 struct cfs_rq *cfs_rq = task_cfs_rq(p); 6710 6711 if (!cfs_bandwidth_used()) 6712 return false; 6713 6714 if (cfs_rq->runtime_enabled || 6715 tg_cfs_bandwidth(cfs_rq->tg)->hierarchical_quota != RUNTIME_INF) 6716 return true; 6717 6718 return false; 6719 } 6720 6721 #ifdef CONFIG_NO_HZ_FULL 6722 /* called from pick_next_task_fair() */ 6723 static void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) 6724 { 6725 int cpu = cpu_of(rq); 6726 6727 if (!cfs_bandwidth_used()) 6728 return; 6729 6730 if (!tick_nohz_full_cpu(cpu)) 6731 return; 6732 6733 if (rq->nr_running != 1) 6734 return; 6735 6736 /* 6737 * We know there is only one task runnable and we've just picked it. The 6738 * normal enqueue path will have cleared TICK_DEP_BIT_SCHED if we will 6739 * be otherwise able to stop the tick. Just need to check if we are using 6740 * bandwidth control. 6741 */ 6742 if (cfs_task_bw_constrained(p)) 6743 tick_nohz_dep_set_cpu(cpu, TICK_DEP_BIT_SCHED); 6744 } 6745 #endif /* CONFIG_NO_HZ_FULL */ 6746 6747 #else /* !CONFIG_CFS_BANDWIDTH: */ 6748 6749 static void account_cfs_rq_runtime(struct cfs_rq *cfs_rq, u64 delta_exec) {} 6750 static bool check_cfs_rq_runtime(struct cfs_rq *cfs_rq) { return false; } 6751 static void check_enqueue_throttle(struct cfs_rq *cfs_rq) {} 6752 static inline void sync_throttle(struct task_group *tg, int cpu) {} 6753 static __always_inline void return_cfs_rq_runtime(struct cfs_rq *cfs_rq) {} 6754 static void task_throttle_setup_work(struct task_struct *p) {} 6755 static bool task_is_throttled(struct task_struct *p) { return false; } 6756 static void dequeue_throttled_task(struct task_struct *p, int flags) {} 6757 static bool enqueue_throttled_task(struct task_struct *p) { return false; } 6758 static void record_throttle_clock(struct cfs_rq *cfs_rq) {} 6759 6760 static inline int cfs_rq_throttled(struct cfs_rq *cfs_rq) 6761 { 6762 return 0; 6763 } 6764 6765 static inline bool cfs_rq_pelt_clock_throttled(struct cfs_rq *cfs_rq) 6766 { 6767 return false; 6768 } 6769 6770 static inline int throttled_hierarchy(struct cfs_rq *cfs_rq) 6771 { 6772 return 0; 6773 } 6774 6775 static inline int lb_throttled_hierarchy(struct task_struct *p, int dst_cpu) 6776 { 6777 return 0; 6778 } 6779 6780 #ifdef CONFIG_FAIR_GROUP_SCHED 6781 void init_cfs_bandwidth(struct cfs_bandwidth *cfs_b, struct cfs_bandwidth *parent) {} 6782 static void init_cfs_rq_runtime(struct cfs_rq *cfs_rq) {} 6783 #endif 6784 6785 static inline struct cfs_bandwidth *tg_cfs_bandwidth(struct task_group *tg) 6786 { 6787 return NULL; 6788 } 6789 static inline void destroy_cfs_bandwidth(struct cfs_bandwidth *cfs_b) {} 6790 static inline void update_runtime_enabled(struct rq *rq) {} 6791 static inline void unthrottle_offline_cfs_rqs(struct rq *rq) {} 6792 #ifdef CONFIG_CGROUP_SCHED 6793 bool cfs_task_bw_constrained(struct task_struct *p) 6794 { 6795 return false; 6796 } 6797 #endif 6798 #endif /* !CONFIG_CFS_BANDWIDTH */ 6799 6800 #if !defined(CONFIG_CFS_BANDWIDTH) || !defined(CONFIG_NO_HZ_FULL) 6801 static inline void sched_fair_update_stop_tick(struct rq *rq, struct task_struct *p) {} 6802 #endif 6803 6804 /************************************************** 6805 * CFS operations on tasks: 6806 */ 6807 6808 #ifdef CONFIG_SCHED_HRTICK 6809 static void hrtick_start_fair(struct rq *rq, struct task_struct *p) 6810 { 6811 struct sched_entity *se = &p->se; 6812 6813 WARN_ON_ONCE(task_rq(p) != rq); 6814 6815 if (rq->cfs.h_nr_queued > 1) { 6816 u64 ran = se->sum_exec_runtime - se->prev_sum_exec_runtime; 6817 u64 slice = se->slice; 6818 s64 delta = slice - ran; 6819 6820 if (delta < 0) { 6821 if (task_current_donor(rq, p)) 6822 resched_curr(rq); 6823 return; 6824 } 6825 hrtick_start(rq, delta); 6826 } 6827 } 6828 6829 /* 6830 * called from enqueue/dequeue and updates the hrtick when the 6831 * current task is from our class and nr_running is low enough 6832 * to matter. 6833 */ 6834 static void hrtick_update(struct rq *rq) 6835 { 6836 struct task_struct *donor = rq->donor; 6837 6838 if (!hrtick_enabled_fair(rq) || donor->sched_class != &fair_sched_class) 6839 return; 6840 6841 hrtick_start_fair(rq, donor); 6842 } 6843 #else /* !CONFIG_SCHED_HRTICK: */ 6844 static inline void 6845 hrtick_start_fair(struct rq *rq, struct task_struct *p) 6846 { 6847 } 6848 6849 static inline void hrtick_update(struct rq *rq) 6850 { 6851 } 6852 #endif /* !CONFIG_SCHED_HRTICK */ 6853 6854 static inline bool cpu_overutilized(int cpu) 6855 { 6856 unsigned long rq_util_min, rq_util_max; 6857 6858 if (!sched_energy_enabled()) 6859 return false; 6860 6861 rq_util_min = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MIN); 6862 rq_util_max = uclamp_rq_get(cpu_rq(cpu), UCLAMP_MAX); 6863 6864 /* Return true only if the utilization doesn't fit CPU's capacity */ 6865 return !util_fits_cpu(cpu_util_cfs(cpu), rq_util_min, rq_util_max, cpu); 6866 } 6867 6868 /* 6869 * overutilized value make sense only if EAS is enabled 6870 */ 6871 static inline bool is_rd_overutilized(struct root_domain *rd) 6872 { 6873 return !sched_energy_enabled() || READ_ONCE(rd->overutilized); 6874 } 6875 6876 static inline void set_rd_overutilized(struct root_domain *rd, bool flag) 6877 { 6878 if (!sched_energy_enabled()) 6879 return; 6880 6881 WRITE_ONCE(rd->overutilized, flag); 6882 trace_sched_overutilized_tp(rd, flag); 6883 } 6884 6885 static inline void check_update_overutilized_status(struct rq *rq) 6886 { 6887 /* 6888 * overutilized field is used for load balancing decisions only 6889 * if energy aware scheduler is being used 6890 */ 6891 6892 if (!is_rd_overutilized(rq->rd) && cpu_overutilized(rq->cpu)) 6893 set_rd_overutilized(rq->rd, 1); 6894 } 6895 6896 /* Runqueue only has SCHED_IDLE tasks enqueued */ 6897 static int sched_idle_rq(struct rq *rq) 6898 { 6899 return unlikely(rq->nr_running == rq->cfs.h_nr_idle && 6900 rq->nr_running); 6901 } 6902 6903 static int sched_idle_cpu(int cpu) 6904 { 6905 return sched_idle_rq(cpu_rq(cpu)); 6906 } 6907 6908 static void 6909 requeue_delayed_entity(struct sched_entity *se) 6910 { 6911 struct cfs_rq *cfs_rq = cfs_rq_of(se); 6912 6913 /* 6914 * se->sched_delayed should imply: se->on_rq == 1. 6915 * Because a delayed entity is one that is still on 6916 * the runqueue competing until elegibility. 6917 */ 6918 WARN_ON_ONCE(!se->sched_delayed); 6919 WARN_ON_ONCE(!se->on_rq); 6920 6921 if (sched_feat(DELAY_ZERO)) { 6922 update_entity_lag(cfs_rq, se); 6923 if (se->vlag > 0) { 6924 cfs_rq->nr_queued--; 6925 if (se != cfs_rq->curr) 6926 __dequeue_entity(cfs_rq, se); 6927 se->vlag = 0; 6928 place_entity(cfs_rq, se, 0); 6929 if (se != cfs_rq->curr) 6930 __enqueue_entity(cfs_rq, se); 6931 cfs_rq->nr_queued++; 6932 } 6933 } 6934 6935 update_load_avg(cfs_rq, se, 0); 6936 clear_delayed(se); 6937 } 6938 6939 /* 6940 * The enqueue_task method is called before nr_running is 6941 * increased. Here we update the fair scheduling stats and 6942 * then put the task into the rbtree: 6943 */ 6944 static void 6945 enqueue_task_fair(struct rq *rq, struct task_struct *p, int flags) 6946 { 6947 struct cfs_rq *cfs_rq; 6948 struct sched_entity *se = &p->se; 6949 int h_nr_idle = task_has_idle_policy(p); 6950 int h_nr_runnable = 1; 6951 int task_new = !(flags & ENQUEUE_WAKEUP); 6952 int rq_h_nr_queued = rq->cfs.h_nr_queued; 6953 u64 slice = 0; 6954 6955 if (task_is_throttled(p) && enqueue_throttled_task(p)) 6956 return; 6957 6958 /* 6959 * The code below (indirectly) updates schedutil which looks at 6960 * the cfs_rq utilization to select a frequency. 6961 * Let's add the task's estimated utilization to the cfs_rq's 6962 * estimated utilization, before we update schedutil. 6963 */ 6964 if (!p->se.sched_delayed || (flags & ENQUEUE_DELAYED)) 6965 util_est_enqueue(&rq->cfs, p); 6966 6967 if (flags & ENQUEUE_DELAYED) { 6968 requeue_delayed_entity(se); 6969 return; 6970 } 6971 6972 /* 6973 * If in_iowait is set, the code below may not trigger any cpufreq 6974 * utilization updates, so do it here explicitly with the IOWAIT flag 6975 * passed. 6976 */ 6977 if (p->in_iowait) 6978 cpufreq_update_util(rq, SCHED_CPUFREQ_IOWAIT); 6979 6980 if (task_new && se->sched_delayed) 6981 h_nr_runnable = 0; 6982 6983 for_each_sched_entity(se) { 6984 if (se->on_rq) { 6985 if (se->sched_delayed) 6986 requeue_delayed_entity(se); 6987 break; 6988 } 6989 cfs_rq = cfs_rq_of(se); 6990 6991 /* 6992 * Basically set the slice of group entries to the min_slice of 6993 * their respective cfs_rq. This ensures the group can service 6994 * its entities in the desired time-frame. 6995 */ 6996 if (slice) { 6997 se->slice = slice; 6998 se->custom_slice = 1; 6999 } 7000 enqueue_entity(cfs_rq, se, flags); 7001 slice = cfs_rq_min_slice(cfs_rq); 7002 7003 cfs_rq->h_nr_runnable += h_nr_runnable; 7004 cfs_rq->h_nr_queued++; 7005 cfs_rq->h_nr_idle += h_nr_idle; 7006 7007 if (cfs_rq_is_idle(cfs_rq)) 7008 h_nr_idle = 1; 7009 7010 flags = ENQUEUE_WAKEUP; 7011 } 7012 7013 for_each_sched_entity(se) { 7014 cfs_rq = cfs_rq_of(se); 7015 7016 update_load_avg(cfs_rq, se, UPDATE_TG); 7017 se_update_runnable(se); 7018 update_cfs_group(se); 7019 7020 se->slice = slice; 7021 if (se != cfs_rq->curr) 7022 min_vruntime_cb_propagate(&se->run_node, NULL); 7023 slice = cfs_rq_min_slice(cfs_rq); 7024 7025 cfs_rq->h_nr_runnable += h_nr_runnable; 7026 cfs_rq->h_nr_queued++; 7027 cfs_rq->h_nr_idle += h_nr_idle; 7028 7029 if (cfs_rq_is_idle(cfs_rq)) 7030 h_nr_idle = 1; 7031 } 7032 7033 if (!rq_h_nr_queued && rq->cfs.h_nr_queued) 7034 dl_server_start(&rq->fair_server); 7035 7036 /* At this point se is NULL and we are at root level*/ 7037 add_nr_running(rq, 1); 7038 7039 /* 7040 * Since new tasks are assigned an initial util_avg equal to 7041 * half of the spare capacity of their CPU, tiny tasks have the 7042 * ability to cross the overutilized threshold, which will 7043 * result in the load balancer ruining all the task placement 7044 * done by EAS. As a way to mitigate that effect, do not account 7045 * for the first enqueue operation of new tasks during the 7046 * overutilized flag detection. 7047 * 7048 * A better way of solving this problem would be to wait for 7049 * the PELT signals of tasks to converge before taking them 7050 * into account, but that is not straightforward to implement, 7051 * and the following generally works well enough in practice. 7052 */ 7053 if (!task_new) 7054 check_update_overutilized_status(rq); 7055 7056 assert_list_leaf_cfs_rq(rq); 7057 7058 hrtick_update(rq); 7059 } 7060 7061 /* 7062 * Basically dequeue_task_fair(), except it can deal with dequeue_entity() 7063 * failing half-way through and resume the dequeue later. 7064 * 7065 * Returns: 7066 * -1 - dequeue delayed 7067 * 0 - dequeue throttled 7068 * 1 - dequeue complete 7069 */ 7070 static int dequeue_entities(struct rq *rq, struct sched_entity *se, int flags) 7071 { 7072 bool was_sched_idle = sched_idle_rq(rq); 7073 bool task_sleep = flags & DEQUEUE_SLEEP; 7074 bool task_delayed = flags & DEQUEUE_DELAYED; 7075 bool task_throttled = flags & DEQUEUE_THROTTLE; 7076 struct task_struct *p = NULL; 7077 int h_nr_idle = 0; 7078 int h_nr_queued = 0; 7079 int h_nr_runnable = 0; 7080 struct cfs_rq *cfs_rq; 7081 u64 slice = 0; 7082 7083 if (entity_is_task(se)) { 7084 p = task_of(se); 7085 h_nr_queued = 1; 7086 h_nr_idle = task_has_idle_policy(p); 7087 if (task_sleep || task_delayed || !se->sched_delayed) 7088 h_nr_runnable = 1; 7089 } 7090 7091 for_each_sched_entity(se) { 7092 cfs_rq = cfs_rq_of(se); 7093 7094 if (!dequeue_entity(cfs_rq, se, flags)) { 7095 if (p && &p->se == se) 7096 return -1; 7097 7098 slice = cfs_rq_min_slice(cfs_rq); 7099 break; 7100 } 7101 7102 cfs_rq->h_nr_runnable -= h_nr_runnable; 7103 cfs_rq->h_nr_queued -= h_nr_queued; 7104 cfs_rq->h_nr_idle -= h_nr_idle; 7105 7106 if (cfs_rq_is_idle(cfs_rq)) 7107 h_nr_idle = h_nr_queued; 7108 7109 if (throttled_hierarchy(cfs_rq) && task_throttled) 7110 record_throttle_clock(cfs_rq); 7111 7112 /* Don't dequeue parent if it has other entities besides us */ 7113 if (cfs_rq->load.weight) { 7114 slice = cfs_rq_min_slice(cfs_rq); 7115 7116 /* Avoid re-evaluating load for this entity: */ 7117 se = parent_entity(se); 7118 /* 7119 * Bias pick_next to pick a task from this cfs_rq, as 7120 * p is sleeping when it is within its sched_slice. 7121 */ 7122 if (task_sleep && se) 7123 set_next_buddy(se); 7124 break; 7125 } 7126 flags |= DEQUEUE_SLEEP; 7127 flags &= ~(DEQUEUE_DELAYED | DEQUEUE_SPECIAL); 7128 } 7129 7130 for_each_sched_entity(se) { 7131 cfs_rq = cfs_rq_of(se); 7132 7133 update_load_avg(cfs_rq, se, UPDATE_TG); 7134 se_update_runnable(se); 7135 update_cfs_group(se); 7136 7137 se->slice = slice; 7138 if (se != cfs_rq->curr) 7139 min_vruntime_cb_propagate(&se->run_node, NULL); 7140 slice = cfs_rq_min_slice(cfs_rq); 7141 7142 cfs_rq->h_nr_runnable -= h_nr_runnable; 7143 cfs_rq->h_nr_queued -= h_nr_queued; 7144 cfs_rq->h_nr_idle -= h_nr_idle; 7145 7146 if (cfs_rq_is_idle(cfs_rq)) 7147 h_nr_idle = h_nr_queued; 7148 7149 if (throttled_hierarchy(cfs_rq) && task_throttled) 7150 record_throttle_clock(cfs_rq); 7151 } 7152 7153 sub_nr_running(rq, h_nr_queued); 7154 7155 /* balance early to pull high priority tasks */ 7156 if (unlikely(!was_sched_idle && sched_idle_rq(rq))) 7157 rq->next_balance = jiffies; 7158 7159 if (p && task_delayed) { 7160 WARN_ON_ONCE(!task_sleep); 7161 WARN_ON_ONCE(p->on_rq != 1); 7162 7163 /* Fix-up what dequeue_task_fair() skipped */ 7164 hrtick_update(rq); 7165 7166 /* 7167 * Fix-up what block_task() skipped. 7168 * 7169 * Must be last, @p might not be valid after this. 7170 */ 7171 __block_task(rq, p); 7172 } 7173 7174 return 1; 7175 } 7176 7177 /* 7178 * The dequeue_task method is called before nr_running is 7179 * decreased. We remove the task from the rbtree and 7180 * update the fair scheduling stats: 7181 */ 7182 static bool dequeue_task_fair(struct rq *rq, struct task_struct *p, int flags) 7183 { 7184 if (task_is_throttled(p)) { 7185 dequeue_throttled_task(p, flags); 7186 return true; 7187 } 7188 7189 if (!p->se.sched_delayed) 7190 util_est_dequeue(&rq->cfs, p); 7191 7192 util_est_update(&rq->cfs, p, flags & DEQUEUE_SLEEP); 7193 if (dequeue_entities(rq, &p->se, flags) < 0) 7194 return false; 7195 7196 /* 7197 * Must not reference @p after dequeue_entities(DEQUEUE_DELAYED). 7198 */ 7199 7200 hrtick_update(rq); 7201 return true; 7202 } 7203 7204 static inline unsigned int cfs_h_nr_delayed(struct rq *rq) 7205 { 7206 return (rq->cfs.h_nr_queued - rq->cfs.h_nr_runnable); 7207 } 7208 7209 /* Working cpumask for: sched_balance_rq(), sched_balance_newidle(). */ 7210 static DEFINE_PER_CPU(cpumask_var_t, load_balance_mask); 7211 static DEFINE_PER_CPU(cpumask_var_t, select_rq_mask); 7212 static DEFINE_PER_CPU(cpumask_var_t, should_we_balance_tmpmask); 7213 7214 #ifdef CONFIG_NO_HZ_COMMON 7215 7216 static struct { 7217 cpumask_var_t idle_cpus_mask; 7218 int has_blocked_load; /* Idle CPUS has blocked load */ 7219 int needs_update; /* Newly idle CPUs need their next_balance collated */ 7220 unsigned long next_balance; /* in jiffy units */ 7221 unsigned long next_blocked; /* Next update of blocked load in jiffies */ 7222 } nohz ____cacheline_aligned; 7223 7224 #endif /* CONFIG_NO_HZ_COMMON */ 7225 7226 static unsigned long cpu_load(struct rq *rq) 7227 { 7228 return cfs_rq_load_avg(&rq->cfs); 7229 } 7230 7231 /* 7232 * cpu_load_without - compute CPU load without any contributions from *p 7233 * @cpu: the CPU which load is requested 7234 * @p: the task which load should be discounted 7235 * 7236 * The load of a CPU is defined by the load of tasks currently enqueued on that 7237 * CPU as well as tasks which are currently sleeping after an execution on that 7238 * CPU. 7239 * 7240 * This method returns the load of the specified CPU by discounting the load of 7241 * the specified task, whenever the task is currently contributing to the CPU 7242 * load. 7243 */ 7244 static unsigned long cpu_load_without(struct rq *rq, struct task_struct *p) 7245 { 7246 struct cfs_rq *cfs_rq; 7247 unsigned int load; 7248 7249 /* Task has no contribution or is new */ 7250 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 7251 return cpu_load(rq); 7252 7253 cfs_rq = &rq->cfs; 7254 load = READ_ONCE(cfs_rq->avg.load_avg); 7255 7256 /* Discount task's util from CPU's util */ 7257 lsub_positive(&load, task_h_load(p)); 7258 7259 return load; 7260 } 7261 7262 static unsigned long cpu_runnable(struct rq *rq) 7263 { 7264 return cfs_rq_runnable_avg(&rq->cfs); 7265 } 7266 7267 static unsigned long cpu_runnable_without(struct rq *rq, struct task_struct *p) 7268 { 7269 struct cfs_rq *cfs_rq; 7270 unsigned int runnable; 7271 7272 /* Task has no contribution or is new */ 7273 if (cpu_of(rq) != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 7274 return cpu_runnable(rq); 7275 7276 cfs_rq = &rq->cfs; 7277 runnable = READ_ONCE(cfs_rq->avg.runnable_avg); 7278 7279 /* Discount task's runnable from CPU's runnable */ 7280 lsub_positive(&runnable, p->se.avg.runnable_avg); 7281 7282 return runnable; 7283 } 7284 7285 static unsigned long capacity_of(int cpu) 7286 { 7287 return cpu_rq(cpu)->cpu_capacity; 7288 } 7289 7290 static void record_wakee(struct task_struct *p) 7291 { 7292 /* 7293 * Only decay a single time; tasks that have less then 1 wakeup per 7294 * jiffy will not have built up many flips. 7295 */ 7296 if (time_after(jiffies, current->wakee_flip_decay_ts + HZ)) { 7297 current->wakee_flips >>= 1; 7298 current->wakee_flip_decay_ts = jiffies; 7299 } 7300 7301 if (current->last_wakee != p) { 7302 current->last_wakee = p; 7303 current->wakee_flips++; 7304 } 7305 } 7306 7307 /* 7308 * Detect M:N waker/wakee relationships via a switching-frequency heuristic. 7309 * 7310 * A waker of many should wake a different task than the one last awakened 7311 * at a frequency roughly N times higher than one of its wakees. 7312 * 7313 * In order to determine whether we should let the load spread vs consolidating 7314 * to shared cache, we look for a minimum 'flip' frequency of llc_size in one 7315 * partner, and a factor of lls_size higher frequency in the other. 7316 * 7317 * With both conditions met, we can be relatively sure that the relationship is 7318 * non-monogamous, with partner count exceeding socket size. 7319 * 7320 * Waker/wakee being client/server, worker/dispatcher, interrupt source or 7321 * whatever is irrelevant, spread criteria is apparent partner count exceeds 7322 * socket size. 7323 */ 7324 static int wake_wide(struct task_struct *p) 7325 { 7326 unsigned int master = current->wakee_flips; 7327 unsigned int slave = p->wakee_flips; 7328 int factor = __this_cpu_read(sd_llc_size); 7329 7330 if (master < slave) 7331 swap(master, slave); 7332 if (slave < factor || master < slave * factor) 7333 return 0; 7334 return 1; 7335 } 7336 7337 /* 7338 * The purpose of wake_affine() is to quickly determine on which CPU we can run 7339 * soonest. For the purpose of speed we only consider the waking and previous 7340 * CPU. 7341 * 7342 * wake_affine_idle() - only considers 'now', it check if the waking CPU is 7343 * cache-affine and is (or will be) idle. 7344 * 7345 * wake_affine_weight() - considers the weight to reflect the average 7346 * scheduling latency of the CPUs. This seems to work 7347 * for the overloaded case. 7348 */ 7349 static int 7350 wake_affine_idle(int this_cpu, int prev_cpu, int sync) 7351 { 7352 /* 7353 * If this_cpu is idle, it implies the wakeup is from interrupt 7354 * context. Only allow the move if cache is shared. Otherwise an 7355 * interrupt intensive workload could force all tasks onto one 7356 * node depending on the IO topology or IRQ affinity settings. 7357 * 7358 * If the prev_cpu is idle and cache affine then avoid a migration. 7359 * There is no guarantee that the cache hot data from an interrupt 7360 * is more important than cache hot data on the prev_cpu and from 7361 * a cpufreq perspective, it's better to have higher utilisation 7362 * on one CPU. 7363 */ 7364 if (available_idle_cpu(this_cpu) && cpus_share_cache(this_cpu, prev_cpu)) 7365 return available_idle_cpu(prev_cpu) ? prev_cpu : this_cpu; 7366 7367 if (sync) { 7368 struct rq *rq = cpu_rq(this_cpu); 7369 7370 if ((rq->nr_running - cfs_h_nr_delayed(rq)) == 1) 7371 return this_cpu; 7372 } 7373 7374 if (available_idle_cpu(prev_cpu)) 7375 return prev_cpu; 7376 7377 return nr_cpumask_bits; 7378 } 7379 7380 static int 7381 wake_affine_weight(struct sched_domain *sd, struct task_struct *p, 7382 int this_cpu, int prev_cpu, int sync) 7383 { 7384 s64 this_eff_load, prev_eff_load; 7385 unsigned long task_load; 7386 7387 this_eff_load = cpu_load(cpu_rq(this_cpu)); 7388 7389 if (sync) { 7390 unsigned long current_load = task_h_load(current); 7391 7392 if (current_load > this_eff_load) 7393 return this_cpu; 7394 7395 this_eff_load -= current_load; 7396 } 7397 7398 task_load = task_h_load(p); 7399 7400 this_eff_load += task_load; 7401 if (sched_feat(WA_BIAS)) 7402 this_eff_load *= 100; 7403 this_eff_load *= capacity_of(prev_cpu); 7404 7405 prev_eff_load = cpu_load(cpu_rq(prev_cpu)); 7406 prev_eff_load -= task_load; 7407 if (sched_feat(WA_BIAS)) 7408 prev_eff_load *= 100 + (sd->imbalance_pct - 100) / 2; 7409 prev_eff_load *= capacity_of(this_cpu); 7410 7411 /* 7412 * If sync, adjust the weight of prev_eff_load such that if 7413 * prev_eff == this_eff that select_idle_sibling() will consider 7414 * stacking the wakee on top of the waker if no other CPU is 7415 * idle. 7416 */ 7417 if (sync) 7418 prev_eff_load += 1; 7419 7420 return this_eff_load < prev_eff_load ? this_cpu : nr_cpumask_bits; 7421 } 7422 7423 static int wake_affine(struct sched_domain *sd, struct task_struct *p, 7424 int this_cpu, int prev_cpu, int sync) 7425 { 7426 int target = nr_cpumask_bits; 7427 7428 if (sched_feat(WA_IDLE)) 7429 target = wake_affine_idle(this_cpu, prev_cpu, sync); 7430 7431 if (sched_feat(WA_WEIGHT) && target == nr_cpumask_bits) 7432 target = wake_affine_weight(sd, p, this_cpu, prev_cpu, sync); 7433 7434 schedstat_inc(p->stats.nr_wakeups_affine_attempts); 7435 if (target != this_cpu) 7436 return prev_cpu; 7437 7438 schedstat_inc(sd->ttwu_move_affine); 7439 schedstat_inc(p->stats.nr_wakeups_affine); 7440 return target; 7441 } 7442 7443 static struct sched_group * 7444 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu); 7445 7446 /* 7447 * sched_balance_find_dst_group_cpu - find the idlest CPU among the CPUs in the group. 7448 */ 7449 static int 7450 sched_balance_find_dst_group_cpu(struct sched_group *group, struct task_struct *p, int this_cpu) 7451 { 7452 unsigned long load, min_load = ULONG_MAX; 7453 unsigned int min_exit_latency = UINT_MAX; 7454 u64 latest_idle_timestamp = 0; 7455 int least_loaded_cpu = this_cpu; 7456 int shallowest_idle_cpu = -1; 7457 int i; 7458 7459 /* Check if we have any choice: */ 7460 if (group->group_weight == 1) 7461 return cpumask_first(sched_group_span(group)); 7462 7463 /* Traverse only the allowed CPUs */ 7464 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) { 7465 struct rq *rq = cpu_rq(i); 7466 7467 if (!sched_core_cookie_match(rq, p)) 7468 continue; 7469 7470 if (sched_idle_cpu(i)) 7471 return i; 7472 7473 if (available_idle_cpu(i)) { 7474 struct cpuidle_state *idle = idle_get_state(rq); 7475 if (idle && idle->exit_latency < min_exit_latency) { 7476 /* 7477 * We give priority to a CPU whose idle state 7478 * has the smallest exit latency irrespective 7479 * of any idle timestamp. 7480 */ 7481 min_exit_latency = idle->exit_latency; 7482 latest_idle_timestamp = rq->idle_stamp; 7483 shallowest_idle_cpu = i; 7484 } else if ((!idle || idle->exit_latency == min_exit_latency) && 7485 rq->idle_stamp > latest_idle_timestamp) { 7486 /* 7487 * If equal or no active idle state, then 7488 * the most recently idled CPU might have 7489 * a warmer cache. 7490 */ 7491 latest_idle_timestamp = rq->idle_stamp; 7492 shallowest_idle_cpu = i; 7493 } 7494 } else if (shallowest_idle_cpu == -1) { 7495 load = cpu_load(cpu_rq(i)); 7496 if (load < min_load) { 7497 min_load = load; 7498 least_loaded_cpu = i; 7499 } 7500 } 7501 } 7502 7503 return shallowest_idle_cpu != -1 ? shallowest_idle_cpu : least_loaded_cpu; 7504 } 7505 7506 static inline int sched_balance_find_dst_cpu(struct sched_domain *sd, struct task_struct *p, 7507 int cpu, int prev_cpu, int sd_flag) 7508 { 7509 int new_cpu = cpu; 7510 7511 if (!cpumask_intersects(sched_domain_span(sd), p->cpus_ptr)) 7512 return prev_cpu; 7513 7514 /* 7515 * We need task's util for cpu_util_without, sync it up to 7516 * prev_cpu's last_update_time. 7517 */ 7518 if (!(sd_flag & SD_BALANCE_FORK)) 7519 sync_entity_load_avg(&p->se); 7520 7521 while (sd) { 7522 struct sched_group *group; 7523 struct sched_domain *tmp; 7524 int weight; 7525 7526 if (!(sd->flags & sd_flag)) { 7527 sd = sd->child; 7528 continue; 7529 } 7530 7531 group = sched_balance_find_dst_group(sd, p, cpu); 7532 if (!group) { 7533 sd = sd->child; 7534 continue; 7535 } 7536 7537 new_cpu = sched_balance_find_dst_group_cpu(group, p, cpu); 7538 if (new_cpu == cpu) { 7539 /* Now try balancing at a lower domain level of 'cpu': */ 7540 sd = sd->child; 7541 continue; 7542 } 7543 7544 /* Now try balancing at a lower domain level of 'new_cpu': */ 7545 cpu = new_cpu; 7546 weight = sd->span_weight; 7547 sd = NULL; 7548 for_each_domain(cpu, tmp) { 7549 if (weight <= tmp->span_weight) 7550 break; 7551 if (tmp->flags & sd_flag) 7552 sd = tmp; 7553 } 7554 } 7555 7556 return new_cpu; 7557 } 7558 7559 static inline int __select_idle_cpu(int cpu, struct task_struct *p) 7560 { 7561 if ((available_idle_cpu(cpu) || sched_idle_cpu(cpu)) && 7562 sched_cpu_cookie_match(cpu_rq(cpu), p)) 7563 return cpu; 7564 7565 return -1; 7566 } 7567 7568 #ifdef CONFIG_SCHED_SMT 7569 DEFINE_STATIC_KEY_FALSE(sched_smt_present); 7570 EXPORT_SYMBOL_GPL(sched_smt_present); 7571 7572 static inline void set_idle_cores(int cpu, int val) 7573 { 7574 struct sched_domain_shared *sds; 7575 7576 sds = rcu_dereference_all(per_cpu(sd_llc_shared, cpu)); 7577 if (sds) 7578 WRITE_ONCE(sds->has_idle_cores, val); 7579 } 7580 7581 static inline bool test_idle_cores(int cpu) 7582 { 7583 struct sched_domain_shared *sds; 7584 7585 sds = rcu_dereference_all(per_cpu(sd_llc_shared, cpu)); 7586 if (sds) 7587 return READ_ONCE(sds->has_idle_cores); 7588 7589 return false; 7590 } 7591 7592 /* 7593 * Scans the local SMT mask to see if the entire core is idle, and records this 7594 * information in sd_llc_shared->has_idle_cores. 7595 * 7596 * Since SMT siblings share all cache levels, inspecting this limited remote 7597 * state should be fairly cheap. 7598 */ 7599 void __update_idle_core(struct rq *rq) 7600 { 7601 int core = cpu_of(rq); 7602 int cpu; 7603 7604 rcu_read_lock(); 7605 if (test_idle_cores(core)) 7606 goto unlock; 7607 7608 for_each_cpu(cpu, cpu_smt_mask(core)) { 7609 if (cpu == core) 7610 continue; 7611 7612 if (!available_idle_cpu(cpu)) 7613 goto unlock; 7614 } 7615 7616 set_idle_cores(core, 1); 7617 unlock: 7618 rcu_read_unlock(); 7619 } 7620 7621 /* 7622 * Scan the entire LLC domain for idle cores; this dynamically switches off if 7623 * there are no idle cores left in the system; tracked through 7624 * sd_llc->shared->has_idle_cores and enabled through update_idle_core() above. 7625 */ 7626 static int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu) 7627 { 7628 bool idle = true; 7629 int cpu; 7630 7631 for_each_cpu(cpu, cpu_smt_mask(core)) { 7632 if (!available_idle_cpu(cpu)) { 7633 idle = false; 7634 if (*idle_cpu == -1) { 7635 if (sched_idle_cpu(cpu) && cpumask_test_cpu(cpu, cpus)) { 7636 *idle_cpu = cpu; 7637 break; 7638 } 7639 continue; 7640 } 7641 break; 7642 } 7643 if (*idle_cpu == -1 && cpumask_test_cpu(cpu, cpus)) 7644 *idle_cpu = cpu; 7645 } 7646 7647 if (idle) 7648 return core; 7649 7650 cpumask_andnot(cpus, cpus, cpu_smt_mask(core)); 7651 return -1; 7652 } 7653 7654 /* 7655 * Scan the local SMT mask for idle CPUs. 7656 */ 7657 static int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target) 7658 { 7659 int cpu; 7660 7661 for_each_cpu_and(cpu, cpu_smt_mask(target), p->cpus_ptr) { 7662 if (cpu == target) 7663 continue; 7664 /* 7665 * Check if the CPU is in the LLC scheduling domain of @target. 7666 * Due to isolcpus, there is no guarantee that all the siblings are in the domain. 7667 */ 7668 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) 7669 continue; 7670 if (available_idle_cpu(cpu) || sched_idle_cpu(cpu)) 7671 return cpu; 7672 } 7673 7674 return -1; 7675 } 7676 7677 #else /* !CONFIG_SCHED_SMT: */ 7678 7679 static inline void set_idle_cores(int cpu, int val) 7680 { 7681 } 7682 7683 static inline bool test_idle_cores(int cpu) 7684 { 7685 return false; 7686 } 7687 7688 static inline int select_idle_core(struct task_struct *p, int core, struct cpumask *cpus, int *idle_cpu) 7689 { 7690 return __select_idle_cpu(core, p); 7691 } 7692 7693 static inline int select_idle_smt(struct task_struct *p, struct sched_domain *sd, int target) 7694 { 7695 return -1; 7696 } 7697 7698 #endif /* !CONFIG_SCHED_SMT */ 7699 7700 /* 7701 * Scan the LLC domain for idle CPUs; this is dynamically regulated by 7702 * comparing the average scan cost (tracked in sd->avg_scan_cost) against the 7703 * average idle time for this rq (as found in rq->avg_idle). 7704 */ 7705 static int select_idle_cpu(struct task_struct *p, struct sched_domain *sd, bool has_idle_core, int target) 7706 { 7707 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask); 7708 int i, cpu, idle_cpu = -1, nr = INT_MAX; 7709 struct sched_domain_shared *sd_share; 7710 7711 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr); 7712 7713 if (sched_feat(SIS_UTIL)) { 7714 sd_share = rcu_dereference_all(per_cpu(sd_llc_shared, target)); 7715 if (sd_share) { 7716 /* because !--nr is the condition to stop scan */ 7717 nr = READ_ONCE(sd_share->nr_idle_scan) + 1; 7718 /* overloaded LLC is unlikely to have idle cpu/core */ 7719 if (nr == 1) 7720 return -1; 7721 } 7722 } 7723 7724 if (static_branch_unlikely(&sched_cluster_active)) { 7725 struct sched_group *sg = sd->groups; 7726 7727 if (sg->flags & SD_CLUSTER) { 7728 for_each_cpu_wrap(cpu, sched_group_span(sg), target + 1) { 7729 if (!cpumask_test_cpu(cpu, cpus)) 7730 continue; 7731 7732 if (has_idle_core) { 7733 i = select_idle_core(p, cpu, cpus, &idle_cpu); 7734 if ((unsigned int)i < nr_cpumask_bits) 7735 return i; 7736 } else { 7737 if (--nr <= 0) 7738 return -1; 7739 idle_cpu = __select_idle_cpu(cpu, p); 7740 if ((unsigned int)idle_cpu < nr_cpumask_bits) 7741 return idle_cpu; 7742 } 7743 } 7744 cpumask_andnot(cpus, cpus, sched_group_span(sg)); 7745 } 7746 } 7747 7748 for_each_cpu_wrap(cpu, cpus, target + 1) { 7749 if (has_idle_core) { 7750 i = select_idle_core(p, cpu, cpus, &idle_cpu); 7751 if ((unsigned int)i < nr_cpumask_bits) 7752 return i; 7753 7754 } else { 7755 if (--nr <= 0) 7756 return -1; 7757 idle_cpu = __select_idle_cpu(cpu, p); 7758 if ((unsigned int)idle_cpu < nr_cpumask_bits) 7759 break; 7760 } 7761 } 7762 7763 if (has_idle_core) 7764 set_idle_cores(target, false); 7765 7766 return idle_cpu; 7767 } 7768 7769 /* 7770 * Scan the asym_capacity domain for idle CPUs; pick the first idle one on which 7771 * the task fits. If no CPU is big enough, but there are idle ones, try to 7772 * maximize capacity. 7773 */ 7774 static int 7775 select_idle_capacity(struct task_struct *p, struct sched_domain *sd, int target) 7776 { 7777 unsigned long task_util, util_min, util_max, best_cap = 0; 7778 int fits, best_fits = 0; 7779 int cpu, best_cpu = -1; 7780 struct cpumask *cpus; 7781 7782 cpus = this_cpu_cpumask_var_ptr(select_rq_mask); 7783 cpumask_and(cpus, sched_domain_span(sd), p->cpus_ptr); 7784 7785 task_util = task_util_est(p); 7786 util_min = uclamp_eff_value(p, UCLAMP_MIN); 7787 util_max = uclamp_eff_value(p, UCLAMP_MAX); 7788 7789 for_each_cpu_wrap(cpu, cpus, target) { 7790 unsigned long cpu_cap = capacity_of(cpu); 7791 7792 if (!available_idle_cpu(cpu) && !sched_idle_cpu(cpu)) 7793 continue; 7794 7795 fits = util_fits_cpu(task_util, util_min, util_max, cpu); 7796 7797 /* This CPU fits with all requirements */ 7798 if (fits > 0) 7799 return cpu; 7800 /* 7801 * Only the min performance hint (i.e. uclamp_min) doesn't fit. 7802 * Look for the CPU with best capacity. 7803 */ 7804 else if (fits < 0) 7805 cpu_cap = get_actual_cpu_capacity(cpu); 7806 7807 /* 7808 * First, select CPU which fits better (-1 being better than 0). 7809 * Then, select the one with best capacity at same level. 7810 */ 7811 if ((fits < best_fits) || 7812 ((fits == best_fits) && (cpu_cap > best_cap))) { 7813 best_cap = cpu_cap; 7814 best_cpu = cpu; 7815 best_fits = fits; 7816 } 7817 } 7818 7819 return best_cpu; 7820 } 7821 7822 static inline bool asym_fits_cpu(unsigned long util, 7823 unsigned long util_min, 7824 unsigned long util_max, 7825 int cpu) 7826 { 7827 if (sched_asym_cpucap_active()) 7828 /* 7829 * Return true only if the cpu fully fits the task requirements 7830 * which include the utilization and the performance hints. 7831 */ 7832 return (util_fits_cpu(util, util_min, util_max, cpu) > 0); 7833 7834 return true; 7835 } 7836 7837 /* 7838 * Try and locate an idle core/thread in the LLC cache domain. 7839 */ 7840 static int select_idle_sibling(struct task_struct *p, int prev, int target) 7841 { 7842 bool has_idle_core = false; 7843 struct sched_domain *sd; 7844 unsigned long task_util, util_min, util_max; 7845 int i, recent_used_cpu, prev_aff = -1; 7846 7847 /* 7848 * On asymmetric system, update task utilization because we will check 7849 * that the task fits with CPU's capacity. 7850 */ 7851 if (sched_asym_cpucap_active()) { 7852 sync_entity_load_avg(&p->se); 7853 task_util = task_util_est(p); 7854 util_min = uclamp_eff_value(p, UCLAMP_MIN); 7855 util_max = uclamp_eff_value(p, UCLAMP_MAX); 7856 } 7857 7858 /* 7859 * per-cpu select_rq_mask usage 7860 */ 7861 lockdep_assert_irqs_disabled(); 7862 7863 if ((available_idle_cpu(target) || sched_idle_cpu(target)) && 7864 asym_fits_cpu(task_util, util_min, util_max, target)) 7865 return target; 7866 7867 /* 7868 * If the previous CPU is cache affine and idle, don't be stupid: 7869 */ 7870 if (prev != target && cpus_share_cache(prev, target) && 7871 (available_idle_cpu(prev) || sched_idle_cpu(prev)) && 7872 asym_fits_cpu(task_util, util_min, util_max, prev)) { 7873 7874 if (!static_branch_unlikely(&sched_cluster_active) || 7875 cpus_share_resources(prev, target)) 7876 return prev; 7877 7878 prev_aff = prev; 7879 } 7880 7881 /* 7882 * Allow a per-cpu kthread to stack with the wakee if the 7883 * kworker thread and the tasks previous CPUs are the same. 7884 * The assumption is that the wakee queued work for the 7885 * per-cpu kthread that is now complete and the wakeup is 7886 * essentially a sync wakeup. An obvious example of this 7887 * pattern is IO completions. 7888 */ 7889 if (is_per_cpu_kthread(current) && 7890 in_task() && 7891 prev == smp_processor_id() && 7892 this_rq()->nr_running <= 1 && 7893 asym_fits_cpu(task_util, util_min, util_max, prev)) { 7894 return prev; 7895 } 7896 7897 /* Check a recently used CPU as a potential idle candidate: */ 7898 recent_used_cpu = p->recent_used_cpu; 7899 p->recent_used_cpu = prev; 7900 if (recent_used_cpu != prev && 7901 recent_used_cpu != target && 7902 cpus_share_cache(recent_used_cpu, target) && 7903 (available_idle_cpu(recent_used_cpu) || sched_idle_cpu(recent_used_cpu)) && 7904 cpumask_test_cpu(recent_used_cpu, p->cpus_ptr) && 7905 asym_fits_cpu(task_util, util_min, util_max, recent_used_cpu)) { 7906 7907 if (!static_branch_unlikely(&sched_cluster_active) || 7908 cpus_share_resources(recent_used_cpu, target)) 7909 return recent_used_cpu; 7910 7911 } else { 7912 recent_used_cpu = -1; 7913 } 7914 7915 /* 7916 * For asymmetric CPU capacity systems, our domain of interest is 7917 * sd_asym_cpucapacity rather than sd_llc. 7918 */ 7919 if (sched_asym_cpucap_active()) { 7920 sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, target)); 7921 /* 7922 * On an asymmetric CPU capacity system where an exclusive 7923 * cpuset defines a symmetric island (i.e. one unique 7924 * capacity_orig value through the cpuset), the key will be set 7925 * but the CPUs within that cpuset will not have a domain with 7926 * SD_ASYM_CPUCAPACITY. These should follow the usual symmetric 7927 * capacity path. 7928 */ 7929 if (sd) { 7930 i = select_idle_capacity(p, sd, target); 7931 return ((unsigned)i < nr_cpumask_bits) ? i : target; 7932 } 7933 } 7934 7935 sd = rcu_dereference_all(per_cpu(sd_llc, target)); 7936 if (!sd) 7937 return target; 7938 7939 if (sched_smt_active()) { 7940 has_idle_core = test_idle_cores(target); 7941 7942 if (!has_idle_core && cpus_share_cache(prev, target)) { 7943 i = select_idle_smt(p, sd, prev); 7944 if ((unsigned int)i < nr_cpumask_bits) 7945 return i; 7946 } 7947 } 7948 7949 i = select_idle_cpu(p, sd, has_idle_core, target); 7950 if ((unsigned)i < nr_cpumask_bits) 7951 return i; 7952 7953 /* 7954 * For cluster machines which have lower sharing cache like L2 or 7955 * LLC Tag, we tend to find an idle CPU in the target's cluster 7956 * first. But prev_cpu or recent_used_cpu may also be a good candidate, 7957 * use them if possible when no idle CPU found in select_idle_cpu(). 7958 */ 7959 if ((unsigned int)prev_aff < nr_cpumask_bits) 7960 return prev_aff; 7961 if ((unsigned int)recent_used_cpu < nr_cpumask_bits) 7962 return recent_used_cpu; 7963 7964 return target; 7965 } 7966 7967 /** 7968 * cpu_util() - Estimates the amount of CPU capacity used by CFS tasks. 7969 * @cpu: the CPU to get the utilization for 7970 * @p: task for which the CPU utilization should be predicted or NULL 7971 * @dst_cpu: CPU @p migrates to, -1 if @p moves from @cpu or @p == NULL 7972 * @boost: 1 to enable boosting, otherwise 0 7973 * 7974 * The unit of the return value must be the same as the one of CPU capacity 7975 * so that CPU utilization can be compared with CPU capacity. 7976 * 7977 * CPU utilization is the sum of running time of runnable tasks plus the 7978 * recent utilization of currently non-runnable tasks on that CPU. 7979 * It represents the amount of CPU capacity currently used by CFS tasks in 7980 * the range [0..max CPU capacity] with max CPU capacity being the CPU 7981 * capacity at f_max. 7982 * 7983 * The estimated CPU utilization is defined as the maximum between CPU 7984 * utilization and sum of the estimated utilization of the currently 7985 * runnable tasks on that CPU. It preserves a utilization "snapshot" of 7986 * previously-executed tasks, which helps better deduce how busy a CPU will 7987 * be when a long-sleeping task wakes up. The contribution to CPU utilization 7988 * of such a task would be significantly decayed at this point of time. 7989 * 7990 * Boosted CPU utilization is defined as max(CPU runnable, CPU utilization). 7991 * CPU contention for CFS tasks can be detected by CPU runnable > CPU 7992 * utilization. Boosting is implemented in cpu_util() so that internal 7993 * users (e.g. EAS) can use it next to external users (e.g. schedutil), 7994 * latter via cpu_util_cfs_boost(). 7995 * 7996 * CPU utilization can be higher than the current CPU capacity 7997 * (f_curr/f_max * max CPU capacity) or even the max CPU capacity because 7998 * of rounding errors as well as task migrations or wakeups of new tasks. 7999 * CPU utilization has to be capped to fit into the [0..max CPU capacity] 8000 * range. Otherwise a group of CPUs (CPU0 util = 121% + CPU1 util = 80%) 8001 * could be seen as over-utilized even though CPU1 has 20% of spare CPU 8002 * capacity. CPU utilization is allowed to overshoot current CPU capacity 8003 * though since this is useful for predicting the CPU capacity required 8004 * after task migrations (scheduler-driven DVFS). 8005 * 8006 * Return: (Boosted) (estimated) utilization for the specified CPU. 8007 */ 8008 static unsigned long 8009 cpu_util(int cpu, struct task_struct *p, int dst_cpu, int boost) 8010 { 8011 struct cfs_rq *cfs_rq = &cpu_rq(cpu)->cfs; 8012 unsigned long util = READ_ONCE(cfs_rq->avg.util_avg); 8013 unsigned long runnable; 8014 8015 if (boost) { 8016 runnable = READ_ONCE(cfs_rq->avg.runnable_avg); 8017 util = max(util, runnable); 8018 } 8019 8020 /* 8021 * If @dst_cpu is -1 or @p migrates from @cpu to @dst_cpu remove its 8022 * contribution. If @p migrates from another CPU to @cpu add its 8023 * contribution. In all the other cases @cpu is not impacted by the 8024 * migration so its util_avg is already correct. 8025 */ 8026 if (p && task_cpu(p) == cpu && dst_cpu != cpu) 8027 lsub_positive(&util, task_util(p)); 8028 else if (p && task_cpu(p) != cpu && dst_cpu == cpu) 8029 util += task_util(p); 8030 8031 if (sched_feat(UTIL_EST)) { 8032 unsigned long util_est; 8033 8034 util_est = READ_ONCE(cfs_rq->avg.util_est); 8035 8036 /* 8037 * During wake-up @p isn't enqueued yet and doesn't contribute 8038 * to any cpu_rq(cpu)->cfs.avg.util_est. 8039 * If @dst_cpu == @cpu add it to "simulate" cpu_util after @p 8040 * has been enqueued. 8041 * 8042 * During exec (@dst_cpu = -1) @p is enqueued and does 8043 * contribute to cpu_rq(cpu)->cfs.util_est. 8044 * Remove it to "simulate" cpu_util without @p's contribution. 8045 * 8046 * Despite the task_on_rq_queued(@p) check there is still a 8047 * small window for a possible race when an exec 8048 * select_task_rq_fair() races with LB's detach_task(). 8049 * 8050 * detach_task() 8051 * deactivate_task() 8052 * p->on_rq = TASK_ON_RQ_MIGRATING; 8053 * -------------------------------- A 8054 * dequeue_task() \ 8055 * dequeue_task_fair() + Race Time 8056 * util_est_dequeue() / 8057 * -------------------------------- B 8058 * 8059 * The additional check "current == p" is required to further 8060 * reduce the race window. 8061 */ 8062 if (dst_cpu == cpu) 8063 util_est += _task_util_est(p); 8064 else if (p && unlikely(task_on_rq_queued(p) || current == p)) 8065 lsub_positive(&util_est, _task_util_est(p)); 8066 8067 util = max(util, util_est); 8068 } 8069 8070 return min(util, arch_scale_cpu_capacity(cpu)); 8071 } 8072 8073 unsigned long cpu_util_cfs(int cpu) 8074 { 8075 return cpu_util(cpu, NULL, -1, 0); 8076 } 8077 8078 unsigned long cpu_util_cfs_boost(int cpu) 8079 { 8080 return cpu_util(cpu, NULL, -1, 1); 8081 } 8082 8083 /* 8084 * cpu_util_without: compute cpu utilization without any contributions from *p 8085 * @cpu: the CPU which utilization is requested 8086 * @p: the task which utilization should be discounted 8087 * 8088 * The utilization of a CPU is defined by the utilization of tasks currently 8089 * enqueued on that CPU as well as tasks which are currently sleeping after an 8090 * execution on that CPU. 8091 * 8092 * This method returns the utilization of the specified CPU by discounting the 8093 * utilization of the specified task, whenever the task is currently 8094 * contributing to the CPU utilization. 8095 */ 8096 static unsigned long cpu_util_without(int cpu, struct task_struct *p) 8097 { 8098 /* Task has no contribution or is new */ 8099 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 8100 p = NULL; 8101 8102 return cpu_util(cpu, p, -1, 0); 8103 } 8104 8105 /* 8106 * This function computes an effective utilization for the given CPU, to be 8107 * used for frequency selection given the linear relation: f = u * f_max. 8108 * 8109 * The scheduler tracks the following metrics: 8110 * 8111 * cpu_util_{cfs,rt,dl,irq}() 8112 * cpu_bw_dl() 8113 * 8114 * Where the cfs,rt and dl util numbers are tracked with the same metric and 8115 * synchronized windows and are thus directly comparable. 8116 * 8117 * The cfs,rt,dl utilization are the running times measured with rq->clock_task 8118 * which excludes things like IRQ and steal-time. These latter are then accrued 8119 * in the IRQ utilization. 8120 * 8121 * The DL bandwidth number OTOH is not a measured metric but a value computed 8122 * based on the task model parameters and gives the minimal utilization 8123 * required to meet deadlines. 8124 */ 8125 unsigned long effective_cpu_util(int cpu, unsigned long util_cfs, 8126 unsigned long *min, 8127 unsigned long *max) 8128 { 8129 unsigned long util, irq, scale; 8130 struct rq *rq = cpu_rq(cpu); 8131 8132 scale = arch_scale_cpu_capacity(cpu); 8133 8134 /* 8135 * Early check to see if IRQ/steal time saturates the CPU, can be 8136 * because of inaccuracies in how we track these -- see 8137 * update_irq_load_avg(). 8138 */ 8139 irq = cpu_util_irq(rq); 8140 if (unlikely(irq >= scale)) { 8141 if (min) 8142 *min = scale; 8143 if (max) 8144 *max = scale; 8145 return scale; 8146 } 8147 8148 if (min) { 8149 /* 8150 * The minimum utilization returns the highest level between: 8151 * - the computed DL bandwidth needed with the IRQ pressure which 8152 * steals time to the deadline task. 8153 * - The minimum performance requirement for CFS and/or RT. 8154 */ 8155 *min = max(irq + cpu_bw_dl(rq), uclamp_rq_get(rq, UCLAMP_MIN)); 8156 8157 /* 8158 * When an RT task is runnable and uclamp is not used, we must 8159 * ensure that the task will run at maximum compute capacity. 8160 */ 8161 if (!uclamp_is_used() && rt_rq_is_runnable(&rq->rt)) 8162 *min = max(*min, scale); 8163 } 8164 8165 /* 8166 * Because the time spend on RT/DL tasks is visible as 'lost' time to 8167 * CFS tasks and we use the same metric to track the effective 8168 * utilization (PELT windows are synchronized) we can directly add them 8169 * to obtain the CPU's actual utilization. 8170 */ 8171 util = util_cfs + cpu_util_rt(rq); 8172 util += cpu_util_dl(rq); 8173 8174 /* 8175 * The maximum hint is a soft bandwidth requirement, which can be lower 8176 * than the actual utilization because of uclamp_max requirements. 8177 */ 8178 if (max) 8179 *max = min(scale, uclamp_rq_get(rq, UCLAMP_MAX)); 8180 8181 if (util >= scale) 8182 return scale; 8183 8184 /* 8185 * There is still idle time; further improve the number by using the 8186 * IRQ metric. Because IRQ/steal time is hidden from the task clock we 8187 * need to scale the task numbers: 8188 * 8189 * max - irq 8190 * U' = irq + --------- * U 8191 * max 8192 */ 8193 util = scale_irq_capacity(util, irq, scale); 8194 util += irq; 8195 8196 return min(scale, util); 8197 } 8198 8199 unsigned long sched_cpu_util(int cpu) 8200 { 8201 return effective_cpu_util(cpu, cpu_util_cfs(cpu), NULL, NULL); 8202 } 8203 8204 /* 8205 * energy_env - Utilization landscape for energy estimation. 8206 * @task_busy_time: Utilization contribution by the task for which we test the 8207 * placement. Given by eenv_task_busy_time(). 8208 * @pd_busy_time: Utilization of the whole perf domain without the task 8209 * contribution. Given by eenv_pd_busy_time(). 8210 * @cpu_cap: Maximum CPU capacity for the perf domain. 8211 * @pd_cap: Entire perf domain capacity. (pd->nr_cpus * cpu_cap). 8212 */ 8213 struct energy_env { 8214 unsigned long task_busy_time; 8215 unsigned long pd_busy_time; 8216 unsigned long cpu_cap; 8217 unsigned long pd_cap; 8218 }; 8219 8220 /* 8221 * Compute the task busy time for compute_energy(). This time cannot be 8222 * injected directly into effective_cpu_util() because of the IRQ scaling. 8223 * The latter only makes sense with the most recent CPUs where the task has 8224 * run. 8225 */ 8226 static inline void eenv_task_busy_time(struct energy_env *eenv, 8227 struct task_struct *p, int prev_cpu) 8228 { 8229 unsigned long busy_time, max_cap = arch_scale_cpu_capacity(prev_cpu); 8230 unsigned long irq = cpu_util_irq(cpu_rq(prev_cpu)); 8231 8232 if (unlikely(irq >= max_cap)) 8233 busy_time = max_cap; 8234 else 8235 busy_time = scale_irq_capacity(task_util_est(p), irq, max_cap); 8236 8237 eenv->task_busy_time = busy_time; 8238 } 8239 8240 /* 8241 * Compute the perf_domain (PD) busy time for compute_energy(). Based on the 8242 * utilization for each @pd_cpus, it however doesn't take into account 8243 * clamping since the ratio (utilization / cpu_capacity) is already enough to 8244 * scale the EM reported power consumption at the (eventually clamped) 8245 * cpu_capacity. 8246 * 8247 * The contribution of the task @p for which we want to estimate the 8248 * energy cost is removed (by cpu_util()) and must be calculated 8249 * separately (see eenv_task_busy_time). This ensures: 8250 * 8251 * - A stable PD utilization, no matter which CPU of that PD we want to place 8252 * the task on. 8253 * 8254 * - A fair comparison between CPUs as the task contribution (task_util()) 8255 * will always be the same no matter which CPU utilization we rely on 8256 * (util_avg or util_est). 8257 * 8258 * Set @eenv busy time for the PD that spans @pd_cpus. This busy time can't 8259 * exceed @eenv->pd_cap. 8260 */ 8261 static inline void eenv_pd_busy_time(struct energy_env *eenv, 8262 struct cpumask *pd_cpus, 8263 struct task_struct *p) 8264 { 8265 unsigned long busy_time = 0; 8266 int cpu; 8267 8268 for_each_cpu(cpu, pd_cpus) { 8269 unsigned long util = cpu_util(cpu, p, -1, 0); 8270 8271 busy_time += effective_cpu_util(cpu, util, NULL, NULL); 8272 } 8273 8274 eenv->pd_busy_time = min(eenv->pd_cap, busy_time); 8275 } 8276 8277 /* 8278 * Compute the maximum utilization for compute_energy() when the task @p 8279 * is placed on the cpu @dst_cpu. 8280 * 8281 * Returns the maximum utilization among @eenv->cpus. This utilization can't 8282 * exceed @eenv->cpu_cap. 8283 */ 8284 static inline unsigned long 8285 eenv_pd_max_util(struct energy_env *eenv, struct cpumask *pd_cpus, 8286 struct task_struct *p, int dst_cpu) 8287 { 8288 unsigned long max_util = 0; 8289 int cpu; 8290 8291 for_each_cpu(cpu, pd_cpus) { 8292 struct task_struct *tsk = (cpu == dst_cpu) ? p : NULL; 8293 unsigned long util = cpu_util(cpu, p, dst_cpu, 1); 8294 unsigned long eff_util, min, max; 8295 8296 /* 8297 * Performance domain frequency: utilization clamping 8298 * must be considered since it affects the selection 8299 * of the performance domain frequency. 8300 * NOTE: in case RT tasks are running, by default the min 8301 * utilization can be max OPP. 8302 */ 8303 eff_util = effective_cpu_util(cpu, util, &min, &max); 8304 8305 /* Task's uclamp can modify min and max value */ 8306 if (tsk && uclamp_is_used()) { 8307 min = max(min, uclamp_eff_value(p, UCLAMP_MIN)); 8308 8309 /* 8310 * If there is no active max uclamp constraint, 8311 * directly use task's one, otherwise keep max. 8312 */ 8313 if (uclamp_rq_is_idle(cpu_rq(cpu))) 8314 max = uclamp_eff_value(p, UCLAMP_MAX); 8315 else 8316 max = max(max, uclamp_eff_value(p, UCLAMP_MAX)); 8317 } 8318 8319 eff_util = sugov_effective_cpu_perf(cpu, eff_util, min, max); 8320 max_util = max(max_util, eff_util); 8321 } 8322 8323 return min(max_util, eenv->cpu_cap); 8324 } 8325 8326 /* 8327 * compute_energy(): Use the Energy Model to estimate the energy that @pd would 8328 * consume for a given utilization landscape @eenv. When @dst_cpu < 0, the task 8329 * contribution is ignored. 8330 */ 8331 static inline unsigned long 8332 compute_energy(struct energy_env *eenv, struct perf_domain *pd, 8333 struct cpumask *pd_cpus, struct task_struct *p, int dst_cpu) 8334 { 8335 unsigned long max_util = eenv_pd_max_util(eenv, pd_cpus, p, dst_cpu); 8336 unsigned long busy_time = eenv->pd_busy_time; 8337 unsigned long energy; 8338 8339 if (dst_cpu >= 0) 8340 busy_time = min(eenv->pd_cap, busy_time + eenv->task_busy_time); 8341 8342 energy = em_cpu_energy(pd->em_pd, max_util, busy_time, eenv->cpu_cap); 8343 8344 trace_sched_compute_energy_tp(p, dst_cpu, energy, max_util, busy_time); 8345 8346 return energy; 8347 } 8348 8349 /* 8350 * find_energy_efficient_cpu(): Find most energy-efficient target CPU for the 8351 * waking task. find_energy_efficient_cpu() looks for the CPU with maximum 8352 * spare capacity in each performance domain and uses it as a potential 8353 * candidate to execute the task. Then, it uses the Energy Model to figure 8354 * out which of the CPU candidates is the most energy-efficient. 8355 * 8356 * The rationale for this heuristic is as follows. In a performance domain, 8357 * all the most energy efficient CPU candidates (according to the Energy 8358 * Model) are those for which we'll request a low frequency. When there are 8359 * several CPUs for which the frequency request will be the same, we don't 8360 * have enough data to break the tie between them, because the Energy Model 8361 * only includes active power costs. With this model, if we assume that 8362 * frequency requests follow utilization (e.g. using schedutil), the CPU with 8363 * the maximum spare capacity in a performance domain is guaranteed to be among 8364 * the best candidates of the performance domain. 8365 * 8366 * In practice, it could be preferable from an energy standpoint to pack 8367 * small tasks on a CPU in order to let other CPUs go in deeper idle states, 8368 * but that could also hurt our chances to go cluster idle, and we have no 8369 * ways to tell with the current Energy Model if this is actually a good 8370 * idea or not. So, find_energy_efficient_cpu() basically favors 8371 * cluster-packing, and spreading inside a cluster. That should at least be 8372 * a good thing for latency, and this is consistent with the idea that most 8373 * of the energy savings of EAS come from the asymmetry of the system, and 8374 * not so much from breaking the tie between identical CPUs. That's also the 8375 * reason why EAS is enabled in the topology code only for systems where 8376 * SD_ASYM_CPUCAPACITY is set. 8377 * 8378 * NOTE: Forkees are not accepted in the energy-aware wake-up path because 8379 * they don't have any useful utilization data yet and it's not possible to 8380 * forecast their impact on energy consumption. Consequently, they will be 8381 * placed by sched_balance_find_dst_cpu() on the least loaded CPU, which might turn out 8382 * to be energy-inefficient in some use-cases. The alternative would be to 8383 * bias new tasks towards specific types of CPUs first, or to try to infer 8384 * their util_avg from the parent task, but those heuristics could hurt 8385 * other use-cases too. So, until someone finds a better way to solve this, 8386 * let's keep things simple by re-using the existing slow path. 8387 */ 8388 static int find_energy_efficient_cpu(struct task_struct *p, int prev_cpu) 8389 { 8390 struct cpumask *cpus = this_cpu_cpumask_var_ptr(select_rq_mask); 8391 unsigned long prev_delta = ULONG_MAX, best_delta = ULONG_MAX; 8392 unsigned long p_util_min = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MIN) : 0; 8393 unsigned long p_util_max = uclamp_is_used() ? uclamp_eff_value(p, UCLAMP_MAX) : 1024; 8394 struct root_domain *rd = this_rq()->rd; 8395 int cpu, best_energy_cpu, target = -1; 8396 int prev_fits = -1, best_fits = -1; 8397 unsigned long best_actual_cap = 0; 8398 unsigned long prev_actual_cap = 0; 8399 struct sched_domain *sd; 8400 struct perf_domain *pd; 8401 struct energy_env eenv; 8402 8403 rcu_read_lock(); 8404 pd = rcu_dereference_all(rd->pd); 8405 if (!pd) 8406 goto unlock; 8407 8408 /* 8409 * Energy-aware wake-up happens on the lowest sched_domain starting 8410 * from sd_asym_cpucapacity spanning over this_cpu and prev_cpu. 8411 */ 8412 sd = rcu_dereference_all(*this_cpu_ptr(&sd_asym_cpucapacity)); 8413 while (sd && !cpumask_test_cpu(prev_cpu, sched_domain_span(sd))) 8414 sd = sd->parent; 8415 if (!sd) 8416 goto unlock; 8417 8418 target = prev_cpu; 8419 8420 sync_entity_load_avg(&p->se); 8421 if (!task_util_est(p) && p_util_min == 0) 8422 goto unlock; 8423 8424 eenv_task_busy_time(&eenv, p, prev_cpu); 8425 8426 for (; pd; pd = pd->next) { 8427 unsigned long util_min = p_util_min, util_max = p_util_max; 8428 unsigned long cpu_cap, cpu_actual_cap, util; 8429 long prev_spare_cap = -1, max_spare_cap = -1; 8430 unsigned long rq_util_min, rq_util_max; 8431 unsigned long cur_delta, base_energy; 8432 int max_spare_cap_cpu = -1; 8433 int fits, max_fits = -1; 8434 8435 if (!cpumask_and(cpus, perf_domain_span(pd), cpu_online_mask)) 8436 continue; 8437 8438 /* Account external pressure for the energy estimation */ 8439 cpu = cpumask_first(cpus); 8440 cpu_actual_cap = get_actual_cpu_capacity(cpu); 8441 8442 eenv.cpu_cap = cpu_actual_cap; 8443 eenv.pd_cap = 0; 8444 8445 for_each_cpu(cpu, cpus) { 8446 struct rq *rq = cpu_rq(cpu); 8447 8448 eenv.pd_cap += cpu_actual_cap; 8449 8450 if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) 8451 continue; 8452 8453 if (!cpumask_test_cpu(cpu, p->cpus_ptr)) 8454 continue; 8455 8456 util = cpu_util(cpu, p, cpu, 0); 8457 cpu_cap = capacity_of(cpu); 8458 8459 /* 8460 * Skip CPUs that cannot satisfy the capacity request. 8461 * IOW, placing the task there would make the CPU 8462 * overutilized. Take uclamp into account to see how 8463 * much capacity we can get out of the CPU; this is 8464 * aligned with sched_cpu_util(). 8465 */ 8466 if (uclamp_is_used() && !uclamp_rq_is_idle(rq)) { 8467 /* 8468 * Open code uclamp_rq_util_with() except for 8469 * the clamp() part. I.e.: apply max aggregation 8470 * only. util_fits_cpu() logic requires to 8471 * operate on non clamped util but must use the 8472 * max-aggregated uclamp_{min, max}. 8473 */ 8474 rq_util_min = uclamp_rq_get(rq, UCLAMP_MIN); 8475 rq_util_max = uclamp_rq_get(rq, UCLAMP_MAX); 8476 8477 util_min = max(rq_util_min, p_util_min); 8478 util_max = max(rq_util_max, p_util_max); 8479 } 8480 8481 fits = util_fits_cpu(util, util_min, util_max, cpu); 8482 if (!fits) 8483 continue; 8484 8485 lsub_positive(&cpu_cap, util); 8486 8487 if (cpu == prev_cpu) { 8488 /* Always use prev_cpu as a candidate. */ 8489 prev_spare_cap = cpu_cap; 8490 prev_fits = fits; 8491 } else if ((fits > max_fits) || 8492 ((fits == max_fits) && ((long)cpu_cap > max_spare_cap))) { 8493 /* 8494 * Find the CPU with the maximum spare capacity 8495 * among the remaining CPUs in the performance 8496 * domain. 8497 */ 8498 max_spare_cap = cpu_cap; 8499 max_spare_cap_cpu = cpu; 8500 max_fits = fits; 8501 } 8502 } 8503 8504 if (max_spare_cap_cpu < 0 && prev_spare_cap < 0) 8505 continue; 8506 8507 eenv_pd_busy_time(&eenv, cpus, p); 8508 /* Compute the 'base' energy of the pd, without @p */ 8509 base_energy = compute_energy(&eenv, pd, cpus, p, -1); 8510 8511 /* Evaluate the energy impact of using prev_cpu. */ 8512 if (prev_spare_cap > -1) { 8513 prev_delta = compute_energy(&eenv, pd, cpus, p, 8514 prev_cpu); 8515 /* CPU utilization has changed */ 8516 if (prev_delta < base_energy) 8517 goto unlock; 8518 prev_delta -= base_energy; 8519 prev_actual_cap = cpu_actual_cap; 8520 best_delta = min(best_delta, prev_delta); 8521 } 8522 8523 /* Evaluate the energy impact of using max_spare_cap_cpu. */ 8524 if (max_spare_cap_cpu >= 0 && max_spare_cap > prev_spare_cap) { 8525 /* Current best energy cpu fits better */ 8526 if (max_fits < best_fits) 8527 continue; 8528 8529 /* 8530 * Both don't fit performance hint (i.e. uclamp_min) 8531 * but best energy cpu has better capacity. 8532 */ 8533 if ((max_fits < 0) && 8534 (cpu_actual_cap <= best_actual_cap)) 8535 continue; 8536 8537 cur_delta = compute_energy(&eenv, pd, cpus, p, 8538 max_spare_cap_cpu); 8539 /* CPU utilization has changed */ 8540 if (cur_delta < base_energy) 8541 goto unlock; 8542 cur_delta -= base_energy; 8543 8544 /* 8545 * Both fit for the task but best energy cpu has lower 8546 * energy impact. 8547 */ 8548 if ((max_fits > 0) && (best_fits > 0) && 8549 (cur_delta >= best_delta)) 8550 continue; 8551 8552 best_delta = cur_delta; 8553 best_energy_cpu = max_spare_cap_cpu; 8554 best_fits = max_fits; 8555 best_actual_cap = cpu_actual_cap; 8556 } 8557 } 8558 rcu_read_unlock(); 8559 8560 if ((best_fits > prev_fits) || 8561 ((best_fits > 0) && (best_delta < prev_delta)) || 8562 ((best_fits < 0) && (best_actual_cap > prev_actual_cap))) 8563 target = best_energy_cpu; 8564 8565 return target; 8566 8567 unlock: 8568 rcu_read_unlock(); 8569 8570 return target; 8571 } 8572 8573 /* 8574 * select_task_rq_fair: Select target runqueue for the waking task in domains 8575 * that have the relevant SD flag set. In practice, this is SD_BALANCE_WAKE, 8576 * SD_BALANCE_FORK, or SD_BALANCE_EXEC. 8577 * 8578 * Balances load by selecting the idlest CPU in the idlest group, or under 8579 * certain conditions an idle sibling CPU if the domain has SD_WAKE_AFFINE set. 8580 * 8581 * Returns the target CPU number. 8582 */ 8583 static int 8584 select_task_rq_fair(struct task_struct *p, int prev_cpu, int wake_flags) 8585 { 8586 int sync = (wake_flags & WF_SYNC) && !(current->flags & PF_EXITING); 8587 struct sched_domain *tmp, *sd = NULL; 8588 int cpu = smp_processor_id(); 8589 int new_cpu = prev_cpu; 8590 int want_affine = 0; 8591 /* SD_flags and WF_flags share the first nibble */ 8592 int sd_flag = wake_flags & 0xF; 8593 8594 /* 8595 * required for stable ->cpus_allowed 8596 */ 8597 lockdep_assert_held(&p->pi_lock); 8598 if (wake_flags & WF_TTWU) { 8599 record_wakee(p); 8600 8601 if ((wake_flags & WF_CURRENT_CPU) && 8602 cpumask_test_cpu(cpu, p->cpus_ptr)) 8603 return cpu; 8604 8605 if (!is_rd_overutilized(this_rq()->rd)) { 8606 new_cpu = find_energy_efficient_cpu(p, prev_cpu); 8607 if (new_cpu >= 0) 8608 return new_cpu; 8609 new_cpu = prev_cpu; 8610 } 8611 8612 want_affine = !wake_wide(p) && cpumask_test_cpu(cpu, p->cpus_ptr); 8613 } 8614 8615 rcu_read_lock(); 8616 for_each_domain(cpu, tmp) { 8617 /* 8618 * If both 'cpu' and 'prev_cpu' are part of this domain, 8619 * cpu is a valid SD_WAKE_AFFINE target. 8620 */ 8621 if (want_affine && (tmp->flags & SD_WAKE_AFFINE) && 8622 cpumask_test_cpu(prev_cpu, sched_domain_span(tmp))) { 8623 if (cpu != prev_cpu) 8624 new_cpu = wake_affine(tmp, p, cpu, prev_cpu, sync); 8625 8626 sd = NULL; /* Prefer wake_affine over balance flags */ 8627 break; 8628 } 8629 8630 /* 8631 * Usually only true for WF_EXEC and WF_FORK, as sched_domains 8632 * usually do not have SD_BALANCE_WAKE set. That means wakeup 8633 * will usually go to the fast path. 8634 */ 8635 if (tmp->flags & sd_flag) 8636 sd = tmp; 8637 else if (!want_affine) 8638 break; 8639 } 8640 8641 if (unlikely(sd)) { 8642 /* Slow path */ 8643 new_cpu = sched_balance_find_dst_cpu(sd, p, cpu, prev_cpu, sd_flag); 8644 } else if (wake_flags & WF_TTWU) { /* XXX always ? */ 8645 /* Fast path */ 8646 new_cpu = select_idle_sibling(p, prev_cpu, new_cpu); 8647 } 8648 rcu_read_unlock(); 8649 8650 return new_cpu; 8651 } 8652 8653 /* 8654 * Called immediately before a task is migrated to a new CPU; task_cpu(p) and 8655 * cfs_rq_of(p) references at time of call are still valid and identify the 8656 * previous CPU. The caller guarantees p->pi_lock or task_rq(p)->lock is held. 8657 */ 8658 static void migrate_task_rq_fair(struct task_struct *p, int new_cpu) 8659 { 8660 struct sched_entity *se = &p->se; 8661 8662 if (!task_on_rq_migrating(p)) { 8663 remove_entity_load_avg(se); 8664 8665 /* 8666 * Here, the task's PELT values have been updated according to 8667 * the current rq's clock. But if that clock hasn't been 8668 * updated in a while, a substantial idle time will be missed, 8669 * leading to an inflation after wake-up on the new rq. 8670 * 8671 * Estimate the missing time from the cfs_rq last_update_time 8672 * and update sched_avg to improve the PELT continuity after 8673 * migration. 8674 */ 8675 migrate_se_pelt_lag(se); 8676 } 8677 8678 /* Tell new CPU we are migrated */ 8679 se->avg.last_update_time = 0; 8680 8681 update_scan_period(p, new_cpu); 8682 } 8683 8684 static void task_dead_fair(struct task_struct *p) 8685 { 8686 struct sched_entity *se = &p->se; 8687 8688 if (se->sched_delayed) { 8689 struct rq_flags rf; 8690 struct rq *rq; 8691 8692 rq = task_rq_lock(p, &rf); 8693 if (se->sched_delayed) { 8694 update_rq_clock(rq); 8695 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED); 8696 } 8697 task_rq_unlock(rq, p, &rf); 8698 } 8699 8700 remove_entity_load_avg(se); 8701 } 8702 8703 /* 8704 * Set the max capacity the task is allowed to run at for misfit detection. 8705 */ 8706 static void set_task_max_allowed_capacity(struct task_struct *p) 8707 { 8708 struct asym_cap_data *entry; 8709 8710 if (!sched_asym_cpucap_active()) 8711 return; 8712 8713 rcu_read_lock(); 8714 list_for_each_entry_rcu(entry, &asym_cap_list, link) { 8715 cpumask_t *cpumask; 8716 8717 cpumask = cpu_capacity_span(entry); 8718 if (!cpumask_intersects(p->cpus_ptr, cpumask)) 8719 continue; 8720 8721 p->max_allowed_capacity = entry->capacity; 8722 break; 8723 } 8724 rcu_read_unlock(); 8725 } 8726 8727 static void set_cpus_allowed_fair(struct task_struct *p, struct affinity_context *ctx) 8728 { 8729 set_cpus_allowed_common(p, ctx); 8730 set_task_max_allowed_capacity(p); 8731 } 8732 8733 static void set_next_buddy(struct sched_entity *se) 8734 { 8735 for_each_sched_entity(se) { 8736 if (WARN_ON_ONCE(!se->on_rq)) 8737 return; 8738 if (se_is_idle(se)) 8739 return; 8740 cfs_rq_of(se)->next = se; 8741 } 8742 } 8743 8744 enum preempt_wakeup_action { 8745 PREEMPT_WAKEUP_NONE, /* No preemption. */ 8746 PREEMPT_WAKEUP_SHORT, /* Ignore slice protection. */ 8747 PREEMPT_WAKEUP_PICK, /* Let __pick_eevdf() decide. */ 8748 PREEMPT_WAKEUP_RESCHED, /* Force reschedule. */ 8749 }; 8750 8751 static inline bool 8752 set_preempt_buddy(struct cfs_rq *cfs_rq, int wake_flags, 8753 struct sched_entity *pse, struct sched_entity *se) 8754 { 8755 /* 8756 * Keep existing buddy if the deadline is sooner than pse. 8757 * The older buddy may be cache cold and completely unrelated 8758 * to the current wakeup but that is unpredictable where as 8759 * obeying the deadline is more in line with EEVDF objectives. 8760 */ 8761 if (cfs_rq->next && entity_before(cfs_rq->next, pse)) 8762 return false; 8763 8764 set_next_buddy(pse); 8765 return true; 8766 } 8767 8768 /* 8769 * WF_SYNC|WF_TTWU indicates the waker expects to sleep but it is not 8770 * strictly enforced because the hint is either misunderstood or 8771 * multiple tasks must be woken up. 8772 */ 8773 static inline enum preempt_wakeup_action 8774 preempt_sync(struct rq *rq, int wake_flags, 8775 struct sched_entity *pse, struct sched_entity *se) 8776 { 8777 u64 threshold, delta; 8778 8779 /* 8780 * WF_SYNC without WF_TTWU is not expected so warn if it happens even 8781 * though it is likely harmless. 8782 */ 8783 WARN_ON_ONCE(!(wake_flags & WF_TTWU)); 8784 8785 threshold = sysctl_sched_migration_cost; 8786 delta = rq_clock_task(rq) - se->exec_start; 8787 if ((s64)delta < 0) 8788 delta = 0; 8789 8790 /* 8791 * WF_RQ_SELECTED implies the tasks are stacking on a CPU when they 8792 * could run on other CPUs. Reduce the threshold before preemption is 8793 * allowed to an arbitrary lower value as it is more likely (but not 8794 * guaranteed) the waker requires the wakee to finish. 8795 */ 8796 if (wake_flags & WF_RQ_SELECTED) 8797 threshold >>= 2; 8798 8799 /* 8800 * As WF_SYNC is not strictly obeyed, allow some runtime for batch 8801 * wakeups to be issued. 8802 */ 8803 if (entity_before(pse, se) && delta >= threshold) 8804 return PREEMPT_WAKEUP_RESCHED; 8805 8806 return PREEMPT_WAKEUP_NONE; 8807 } 8808 8809 /* 8810 * Preempt the current task with a newly woken task if needed: 8811 */ 8812 static void wakeup_preempt_fair(struct rq *rq, struct task_struct *p, int wake_flags) 8813 { 8814 enum preempt_wakeup_action preempt_action = PREEMPT_WAKEUP_PICK; 8815 struct task_struct *donor = rq->donor; 8816 struct sched_entity *se = &donor->se, *pse = &p->se; 8817 struct cfs_rq *cfs_rq = task_cfs_rq(donor); 8818 int cse_is_idle, pse_is_idle; 8819 8820 /* 8821 * XXX Getting preempted by higher class, try and find idle CPU? 8822 */ 8823 if (p->sched_class != &fair_sched_class) 8824 return; 8825 8826 if (unlikely(se == pse)) 8827 return; 8828 8829 /* 8830 * This is possible from callers such as attach_tasks(), in which we 8831 * unconditionally wakeup_preempt() after an enqueue (which may have 8832 * lead to a throttle). This both saves work and prevents false 8833 * next-buddy nomination below. 8834 */ 8835 if (task_is_throttled(p)) 8836 return; 8837 8838 /* 8839 * We can come here with TIF_NEED_RESCHED already set from new task 8840 * wake up path. 8841 * 8842 * Note: this also catches the edge-case of curr being in a throttled 8843 * group (e.g. via set_curr_task), since update_curr() (in the 8844 * enqueue of curr) will have resulted in resched being set. This 8845 * prevents us from potentially nominating it as a false LAST_BUDDY 8846 * below. 8847 */ 8848 if (test_tsk_need_resched(rq->curr)) 8849 return; 8850 8851 if (!sched_feat(WAKEUP_PREEMPTION)) 8852 return; 8853 8854 find_matching_se(&se, &pse); 8855 WARN_ON_ONCE(!pse); 8856 8857 cse_is_idle = se_is_idle(se); 8858 pse_is_idle = se_is_idle(pse); 8859 8860 /* 8861 * Preempt an idle entity in favor of a non-idle entity (and don't preempt 8862 * in the inverse case). 8863 */ 8864 if (cse_is_idle && !pse_is_idle) { 8865 /* 8866 * When non-idle entity preempt an idle entity, 8867 * don't give idle entity slice protection. 8868 */ 8869 preempt_action = PREEMPT_WAKEUP_SHORT; 8870 goto preempt; 8871 } 8872 8873 if (cse_is_idle != pse_is_idle) 8874 return; 8875 8876 /* 8877 * BATCH and IDLE tasks do not preempt others. 8878 */ 8879 if (unlikely(!normal_policy(p->policy))) 8880 return; 8881 8882 cfs_rq = cfs_rq_of(se); 8883 update_curr(cfs_rq); 8884 /* 8885 * If @p has a shorter slice than current and @p is eligible, override 8886 * current's slice protection in order to allow preemption. 8887 */ 8888 if (sched_feat(PREEMPT_SHORT) && (pse->slice < se->slice)) { 8889 preempt_action = PREEMPT_WAKEUP_SHORT; 8890 goto pick; 8891 } 8892 8893 /* 8894 * Ignore wakee preemption on WF_FORK as it is less likely that 8895 * there is shared data as exec often follow fork. Do not 8896 * preempt for tasks that are sched_delayed as it would violate 8897 * EEVDF to forcibly queue an ineligible task. 8898 */ 8899 if ((wake_flags & WF_FORK) || pse->sched_delayed) 8900 return; 8901 8902 /* Prefer picking wakee soon if appropriate. */ 8903 if (sched_feat(NEXT_BUDDY) && 8904 set_preempt_buddy(cfs_rq, wake_flags, pse, se)) { 8905 8906 /* 8907 * Decide whether to obey WF_SYNC hint for a new buddy. Old 8908 * buddies are ignored as they may not be relevant to the 8909 * waker and less likely to be cache hot. 8910 */ 8911 if (wake_flags & WF_SYNC) 8912 preempt_action = preempt_sync(rq, wake_flags, pse, se); 8913 } 8914 8915 switch (preempt_action) { 8916 case PREEMPT_WAKEUP_NONE: 8917 return; 8918 case PREEMPT_WAKEUP_RESCHED: 8919 goto preempt; 8920 case PREEMPT_WAKEUP_SHORT: 8921 fallthrough; 8922 case PREEMPT_WAKEUP_PICK: 8923 break; 8924 } 8925 8926 pick: 8927 /* 8928 * If @p has become the most eligible task, force preemption. 8929 */ 8930 if (__pick_eevdf(cfs_rq, preempt_action != PREEMPT_WAKEUP_SHORT) == pse) 8931 goto preempt; 8932 8933 if (sched_feat(RUN_TO_PARITY)) 8934 update_protect_slice(cfs_rq, se); 8935 8936 return; 8937 8938 preempt: 8939 if (preempt_action == PREEMPT_WAKEUP_SHORT) 8940 cancel_protect_slice(se); 8941 8942 resched_curr_lazy(rq); 8943 } 8944 8945 static struct task_struct *pick_task_fair(struct rq *rq, struct rq_flags *rf) 8946 { 8947 struct sched_entity *se; 8948 struct cfs_rq *cfs_rq; 8949 struct task_struct *p; 8950 bool throttled; 8951 8952 again: 8953 cfs_rq = &rq->cfs; 8954 if (!cfs_rq->nr_queued) 8955 return NULL; 8956 8957 throttled = false; 8958 8959 do { 8960 /* Might not have done put_prev_entity() */ 8961 if (cfs_rq->curr && cfs_rq->curr->on_rq) 8962 update_curr(cfs_rq); 8963 8964 throttled |= check_cfs_rq_runtime(cfs_rq); 8965 8966 se = pick_next_entity(rq, cfs_rq); 8967 if (!se) 8968 goto again; 8969 cfs_rq = group_cfs_rq(se); 8970 } while (cfs_rq); 8971 8972 p = task_of(se); 8973 if (unlikely(throttled)) 8974 task_throttle_setup_work(p); 8975 return p; 8976 } 8977 8978 static void __set_next_task_fair(struct rq *rq, struct task_struct *p, bool first); 8979 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first); 8980 8981 struct task_struct * 8982 pick_next_task_fair(struct rq *rq, struct task_struct *prev, struct rq_flags *rf) 8983 __must_hold(__rq_lockp(rq)) 8984 { 8985 struct sched_entity *se; 8986 struct task_struct *p; 8987 int new_tasks; 8988 8989 again: 8990 p = pick_task_fair(rq, rf); 8991 if (!p) 8992 goto idle; 8993 se = &p->se; 8994 8995 #ifdef CONFIG_FAIR_GROUP_SCHED 8996 if (prev->sched_class != &fair_sched_class) 8997 goto simple; 8998 8999 __put_prev_set_next_dl_server(rq, prev, p); 9000 9001 /* 9002 * Because of the set_next_buddy() in dequeue_task_fair() it is rather 9003 * likely that a next task is from the same cgroup as the current. 9004 * 9005 * Therefore attempt to avoid putting and setting the entire cgroup 9006 * hierarchy, only change the part that actually changes. 9007 * 9008 * Since we haven't yet done put_prev_entity and if the selected task 9009 * is a different task than we started out with, try and touch the 9010 * least amount of cfs_rqs. 9011 */ 9012 if (prev != p) { 9013 struct sched_entity *pse = &prev->se; 9014 struct cfs_rq *cfs_rq; 9015 9016 while (!(cfs_rq = is_same_group(se, pse))) { 9017 int se_depth = se->depth; 9018 int pse_depth = pse->depth; 9019 9020 if (se_depth <= pse_depth) { 9021 put_prev_entity(cfs_rq_of(pse), pse); 9022 pse = parent_entity(pse); 9023 } 9024 if (se_depth >= pse_depth) { 9025 set_next_entity(cfs_rq_of(se), se, true); 9026 se = parent_entity(se); 9027 } 9028 } 9029 9030 put_prev_entity(cfs_rq, pse); 9031 set_next_entity(cfs_rq, se, true); 9032 9033 __set_next_task_fair(rq, p, true); 9034 } 9035 9036 return p; 9037 9038 simple: 9039 #endif /* CONFIG_FAIR_GROUP_SCHED */ 9040 put_prev_set_next_task(rq, prev, p); 9041 return p; 9042 9043 idle: 9044 if (rf) { 9045 new_tasks = sched_balance_newidle(rq, rf); 9046 9047 /* 9048 * Because sched_balance_newidle() releases (and re-acquires) 9049 * rq->lock, it is possible for any higher priority task to 9050 * appear. In that case we must re-start the pick_next_entity() 9051 * loop. 9052 */ 9053 if (new_tasks < 0) 9054 return RETRY_TASK; 9055 9056 if (new_tasks > 0) 9057 goto again; 9058 } 9059 9060 return NULL; 9061 } 9062 9063 static struct task_struct * 9064 fair_server_pick_task(struct sched_dl_entity *dl_se, struct rq_flags *rf) 9065 { 9066 return pick_task_fair(dl_se->rq, rf); 9067 } 9068 9069 void fair_server_init(struct rq *rq) 9070 { 9071 struct sched_dl_entity *dl_se = &rq->fair_server; 9072 9073 init_dl_entity(dl_se); 9074 9075 dl_server_init(dl_se, rq, fair_server_pick_task); 9076 } 9077 9078 /* 9079 * Account for a descheduled task: 9080 */ 9081 static void put_prev_task_fair(struct rq *rq, struct task_struct *prev, struct task_struct *next) 9082 { 9083 struct sched_entity *se = &prev->se; 9084 struct cfs_rq *cfs_rq; 9085 9086 for_each_sched_entity(se) { 9087 cfs_rq = cfs_rq_of(se); 9088 put_prev_entity(cfs_rq, se); 9089 } 9090 } 9091 9092 /* 9093 * sched_yield() is very simple 9094 */ 9095 static void yield_task_fair(struct rq *rq) 9096 { 9097 struct task_struct *curr = rq->donor; 9098 struct cfs_rq *cfs_rq = task_cfs_rq(curr); 9099 struct sched_entity *se = &curr->se; 9100 9101 /* 9102 * Are we the only task in the tree? 9103 */ 9104 if (unlikely(rq->nr_running == 1)) 9105 return; 9106 9107 clear_buddies(cfs_rq, se); 9108 9109 update_rq_clock(rq); 9110 /* 9111 * Update run-time statistics of the 'current'. 9112 */ 9113 update_curr(cfs_rq); 9114 /* 9115 * Tell update_rq_clock() that we've just updated, 9116 * so we don't do microscopic update in schedule() 9117 * and double the fastpath cost. 9118 */ 9119 rq_clock_skip_update(rq); 9120 9121 /* 9122 * Forfeit the remaining vruntime, only if the entity is eligible. This 9123 * condition is necessary because in core scheduling we prefer to run 9124 * ineligible tasks rather than force idling. If this happens we may 9125 * end up in a loop where the core scheduler picks the yielding task, 9126 * which yields immediately again; without the condition the vruntime 9127 * ends up quickly running away. 9128 */ 9129 if (entity_eligible(cfs_rq, se)) { 9130 se->vruntime = se->deadline; 9131 se->deadline += calc_delta_fair(se->slice, se); 9132 } 9133 } 9134 9135 static bool yield_to_task_fair(struct rq *rq, struct task_struct *p) 9136 { 9137 struct sched_entity *se = &p->se; 9138 9139 /* !se->on_rq also covers throttled task */ 9140 if (!se->on_rq) 9141 return false; 9142 9143 /* Tell the scheduler that we'd really like se to run next. */ 9144 set_next_buddy(se); 9145 9146 yield_task_fair(rq); 9147 9148 return true; 9149 } 9150 9151 /************************************************** 9152 * Fair scheduling class load-balancing methods. 9153 * 9154 * BASICS 9155 * 9156 * The purpose of load-balancing is to achieve the same basic fairness the 9157 * per-CPU scheduler provides, namely provide a proportional amount of compute 9158 * time to each task. This is expressed in the following equation: 9159 * 9160 * W_i,n/P_i == W_j,n/P_j for all i,j (1) 9161 * 9162 * Where W_i,n is the n-th weight average for CPU i. The instantaneous weight 9163 * W_i,0 is defined as: 9164 * 9165 * W_i,0 = \Sum_j w_i,j (2) 9166 * 9167 * Where w_i,j is the weight of the j-th runnable task on CPU i. This weight 9168 * is derived from the nice value as per sched_prio_to_weight[]. 9169 * 9170 * The weight average is an exponential decay average of the instantaneous 9171 * weight: 9172 * 9173 * W'_i,n = (2^n - 1) / 2^n * W_i,n + 1 / 2^n * W_i,0 (3) 9174 * 9175 * C_i is the compute capacity of CPU i, typically it is the 9176 * fraction of 'recent' time available for SCHED_OTHER task execution. But it 9177 * can also include other factors [XXX]. 9178 * 9179 * To achieve this balance we define a measure of imbalance which follows 9180 * directly from (1): 9181 * 9182 * imb_i,j = max{ avg(W/C), W_i/C_i } - min{ avg(W/C), W_j/C_j } (4) 9183 * 9184 * We them move tasks around to minimize the imbalance. In the continuous 9185 * function space it is obvious this converges, in the discrete case we get 9186 * a few fun cases generally called infeasible weight scenarios. 9187 * 9188 * [XXX expand on: 9189 * - infeasible weights; 9190 * - local vs global optima in the discrete case. ] 9191 * 9192 * 9193 * SCHED DOMAINS 9194 * 9195 * In order to solve the imbalance equation (4), and avoid the obvious O(n^2) 9196 * for all i,j solution, we create a tree of CPUs that follows the hardware 9197 * topology where each level pairs two lower groups (or better). This results 9198 * in O(log n) layers. Furthermore we reduce the number of CPUs going up the 9199 * tree to only the first of the previous level and we decrease the frequency 9200 * of load-balance at each level inversely proportional to the number of CPUs in 9201 * the groups. 9202 * 9203 * This yields: 9204 * 9205 * log_2 n 1 n 9206 * \Sum { --- * --- * 2^i } = O(n) (5) 9207 * i = 0 2^i 2^i 9208 * `- size of each group 9209 * | | `- number of CPUs doing load-balance 9210 * | `- freq 9211 * `- sum over all levels 9212 * 9213 * Coupled with a limit on how many tasks we can migrate every balance pass, 9214 * this makes (5) the runtime complexity of the balancer. 9215 * 9216 * An important property here is that each CPU is still (indirectly) connected 9217 * to every other CPU in at most O(log n) steps: 9218 * 9219 * The adjacency matrix of the resulting graph is given by: 9220 * 9221 * log_2 n 9222 * A_i,j = \Union (i % 2^k == 0) && i / 2^(k+1) == j / 2^(k+1) (6) 9223 * k = 0 9224 * 9225 * And you'll find that: 9226 * 9227 * A^(log_2 n)_i,j != 0 for all i,j (7) 9228 * 9229 * Showing there's indeed a path between every CPU in at most O(log n) steps. 9230 * The task movement gives a factor of O(m), giving a convergence complexity 9231 * of: 9232 * 9233 * O(nm log n), n := nr_cpus, m := nr_tasks (8) 9234 * 9235 * 9236 * WORK CONSERVING 9237 * 9238 * In order to avoid CPUs going idle while there's still work to do, new idle 9239 * balancing is more aggressive and has the newly idle CPU iterate up the domain 9240 * tree itself instead of relying on other CPUs to bring it work. 9241 * 9242 * This adds some complexity to both (5) and (8) but it reduces the total idle 9243 * time. 9244 * 9245 * [XXX more?] 9246 * 9247 * 9248 * CGROUPS 9249 * 9250 * Cgroups make a horror show out of (2), instead of a simple sum we get: 9251 * 9252 * s_k,i 9253 * W_i,0 = \Sum_j \Prod_k w_k * ----- (9) 9254 * S_k 9255 * 9256 * Where 9257 * 9258 * s_k,i = \Sum_j w_i,j,k and S_k = \Sum_i s_k,i (10) 9259 * 9260 * w_i,j,k is the weight of the j-th runnable task in the k-th cgroup on CPU i. 9261 * 9262 * The big problem is S_k, its a global sum needed to compute a local (W_i) 9263 * property. 9264 * 9265 * [XXX write more on how we solve this.. _after_ merging pjt's patches that 9266 * rewrite all of this once again.] 9267 */ 9268 9269 static unsigned long __read_mostly max_load_balance_interval = HZ/10; 9270 9271 enum fbq_type { regular, remote, all }; 9272 9273 /* 9274 * 'group_type' describes the group of CPUs at the moment of load balancing. 9275 * 9276 * The enum is ordered by pulling priority, with the group with lowest priority 9277 * first so the group_type can simply be compared when selecting the busiest 9278 * group. See update_sd_pick_busiest(). 9279 */ 9280 enum group_type { 9281 /* The group has spare capacity that can be used to run more tasks. */ 9282 group_has_spare = 0, 9283 /* 9284 * The group is fully used and the tasks don't compete for more CPU 9285 * cycles. Nevertheless, some tasks might wait before running. 9286 */ 9287 group_fully_busy, 9288 /* 9289 * One task doesn't fit with CPU's capacity and must be migrated to a 9290 * more powerful CPU. 9291 */ 9292 group_misfit_task, 9293 /* 9294 * Balance SMT group that's fully busy. Can benefit from migration 9295 * a task on SMT with busy sibling to another CPU on idle core. 9296 */ 9297 group_smt_balance, 9298 /* 9299 * SD_ASYM_PACKING only: One local CPU with higher capacity is available, 9300 * and the task should be migrated to it instead of running on the 9301 * current CPU. 9302 */ 9303 group_asym_packing, 9304 /* 9305 * The tasks' affinity constraints previously prevented the scheduler 9306 * from balancing the load across the system. 9307 */ 9308 group_imbalanced, 9309 /* 9310 * The CPU is overloaded and can't provide expected CPU cycles to all 9311 * tasks. 9312 */ 9313 group_overloaded 9314 }; 9315 9316 enum migration_type { 9317 migrate_load = 0, 9318 migrate_util, 9319 migrate_task, 9320 migrate_misfit 9321 }; 9322 9323 #define LBF_ALL_PINNED 0x01 9324 #define LBF_NEED_BREAK 0x02 9325 #define LBF_DST_PINNED 0x04 9326 #define LBF_SOME_PINNED 0x08 9327 #define LBF_ACTIVE_LB 0x10 9328 9329 struct lb_env { 9330 struct sched_domain *sd; 9331 9332 struct rq *src_rq; 9333 int src_cpu; 9334 9335 int dst_cpu; 9336 struct rq *dst_rq; 9337 9338 struct cpumask *dst_grpmask; 9339 int new_dst_cpu; 9340 enum cpu_idle_type idle; 9341 long imbalance; 9342 /* The set of CPUs under consideration for load-balancing */ 9343 struct cpumask *cpus; 9344 9345 unsigned int flags; 9346 9347 unsigned int loop; 9348 unsigned int loop_break; 9349 unsigned int loop_max; 9350 9351 enum fbq_type fbq_type; 9352 enum migration_type migration_type; 9353 struct list_head tasks; 9354 }; 9355 9356 /* 9357 * Is this task likely cache-hot: 9358 */ 9359 static int task_hot(struct task_struct *p, struct lb_env *env) 9360 { 9361 s64 delta; 9362 9363 lockdep_assert_rq_held(env->src_rq); 9364 9365 if (p->sched_class != &fair_sched_class) 9366 return 0; 9367 9368 if (unlikely(task_has_idle_policy(p))) 9369 return 0; 9370 9371 /* SMT siblings share cache */ 9372 if (env->sd->flags & SD_SHARE_CPUCAPACITY) 9373 return 0; 9374 9375 /* 9376 * Buddy candidates are cache hot: 9377 */ 9378 if (sched_feat(CACHE_HOT_BUDDY) && env->dst_rq->nr_running && 9379 (&p->se == cfs_rq_of(&p->se)->next)) 9380 return 1; 9381 9382 if (sysctl_sched_migration_cost == -1) 9383 return 1; 9384 9385 /* 9386 * Don't migrate task if the task's cookie does not match 9387 * with the destination CPU's core cookie. 9388 */ 9389 if (!sched_core_cookie_match(cpu_rq(env->dst_cpu), p)) 9390 return 1; 9391 9392 if (sysctl_sched_migration_cost == 0) 9393 return 0; 9394 9395 delta = rq_clock_task(env->src_rq) - p->se.exec_start; 9396 9397 return delta < (s64)sysctl_sched_migration_cost; 9398 } 9399 9400 #ifdef CONFIG_NUMA_BALANCING 9401 /* 9402 * Returns a positive value, if task migration degrades locality. 9403 * Returns 0, if task migration is not affected by locality. 9404 * Returns a negative value, if task migration improves locality i.e migration preferred. 9405 */ 9406 static long migrate_degrades_locality(struct task_struct *p, struct lb_env *env) 9407 { 9408 struct numa_group *numa_group = rcu_dereference_all(p->numa_group); 9409 unsigned long src_weight, dst_weight; 9410 int src_nid, dst_nid, dist; 9411 9412 if (!static_branch_likely(&sched_numa_balancing)) 9413 return 0; 9414 9415 if (!p->numa_faults || !(env->sd->flags & SD_NUMA)) 9416 return 0; 9417 9418 src_nid = cpu_to_node(env->src_cpu); 9419 dst_nid = cpu_to_node(env->dst_cpu); 9420 9421 if (src_nid == dst_nid) 9422 return 0; 9423 9424 /* Migrating away from the preferred node is always bad. */ 9425 if (src_nid == p->numa_preferred_nid) { 9426 if (env->src_rq->nr_running > env->src_rq->nr_preferred_running) 9427 return 1; 9428 else 9429 return 0; 9430 } 9431 9432 /* Encourage migration to the preferred node. */ 9433 if (dst_nid == p->numa_preferred_nid) 9434 return -1; 9435 9436 /* Leaving a core idle is often worse than degrading locality. */ 9437 if (env->idle == CPU_IDLE) 9438 return 0; 9439 9440 dist = node_distance(src_nid, dst_nid); 9441 if (numa_group) { 9442 src_weight = group_weight(p, src_nid, dist); 9443 dst_weight = group_weight(p, dst_nid, dist); 9444 } else { 9445 src_weight = task_weight(p, src_nid, dist); 9446 dst_weight = task_weight(p, dst_nid, dist); 9447 } 9448 9449 return src_weight - dst_weight; 9450 } 9451 9452 #else /* !CONFIG_NUMA_BALANCING: */ 9453 static inline long migrate_degrades_locality(struct task_struct *p, 9454 struct lb_env *env) 9455 { 9456 return 0; 9457 } 9458 #endif /* !CONFIG_NUMA_BALANCING */ 9459 9460 /* 9461 * Check whether the task is ineligible on the destination cpu 9462 * 9463 * When the PLACE_LAG scheduling feature is enabled and 9464 * dst_cfs_rq->nr_queued is greater than 1, if the task 9465 * is ineligible, it will also be ineligible when 9466 * it is migrated to the destination cpu. 9467 */ 9468 static inline int task_is_ineligible_on_dst_cpu(struct task_struct *p, int dest_cpu) 9469 { 9470 struct cfs_rq *dst_cfs_rq; 9471 9472 #ifdef CONFIG_FAIR_GROUP_SCHED 9473 dst_cfs_rq = task_group(p)->cfs_rq[dest_cpu]; 9474 #else 9475 dst_cfs_rq = &cpu_rq(dest_cpu)->cfs; 9476 #endif 9477 if (sched_feat(PLACE_LAG) && dst_cfs_rq->nr_queued && 9478 !entity_eligible(task_cfs_rq(p), &p->se)) 9479 return 1; 9480 9481 return 0; 9482 } 9483 9484 /* 9485 * can_migrate_task - may task p from runqueue rq be migrated to this_cpu? 9486 */ 9487 static 9488 int can_migrate_task(struct task_struct *p, struct lb_env *env) 9489 { 9490 long degrades, hot; 9491 9492 lockdep_assert_rq_held(env->src_rq); 9493 if (p->sched_task_hot) 9494 p->sched_task_hot = 0; 9495 9496 /* 9497 * We do not migrate tasks that are: 9498 * 1) delayed dequeued unless we migrate load, or 9499 * 2) target cfs_rq is in throttled hierarchy, or 9500 * 3) cannot be migrated to this CPU due to cpus_ptr, or 9501 * 4) running (obviously), or 9502 * 5) are cache-hot on their current CPU, or 9503 * 6) are blocked on mutexes (if SCHED_PROXY_EXEC is enabled) 9504 */ 9505 if ((p->se.sched_delayed) && (env->migration_type != migrate_load)) 9506 return 0; 9507 9508 if (lb_throttled_hierarchy(p, env->dst_cpu)) 9509 return 0; 9510 9511 /* 9512 * We want to prioritize the migration of eligible tasks. 9513 * For ineligible tasks we soft-limit them and only allow 9514 * them to migrate when nr_balance_failed is non-zero to 9515 * avoid load-balancing trying very hard to balance the load. 9516 */ 9517 if (!env->sd->nr_balance_failed && 9518 task_is_ineligible_on_dst_cpu(p, env->dst_cpu)) 9519 return 0; 9520 9521 /* Disregard percpu kthreads; they are where they need to be. */ 9522 if (kthread_is_per_cpu(p)) 9523 return 0; 9524 9525 if (task_is_blocked(p)) 9526 return 0; 9527 9528 if (!cpumask_test_cpu(env->dst_cpu, p->cpus_ptr)) { 9529 int cpu; 9530 9531 schedstat_inc(p->stats.nr_failed_migrations_affine); 9532 9533 env->flags |= LBF_SOME_PINNED; 9534 9535 /* 9536 * Remember if this task can be migrated to any other CPU in 9537 * our sched_group. We may want to revisit it if we couldn't 9538 * meet load balance goals by pulling other tasks on src_cpu. 9539 * 9540 * Avoid computing new_dst_cpu 9541 * - for NEWLY_IDLE 9542 * - if we have already computed one in current iteration 9543 * - if it's an active balance 9544 */ 9545 if (env->idle == CPU_NEWLY_IDLE || 9546 env->flags & (LBF_DST_PINNED | LBF_ACTIVE_LB)) 9547 return 0; 9548 9549 /* Prevent to re-select dst_cpu via env's CPUs: */ 9550 cpu = cpumask_first_and_and(env->dst_grpmask, env->cpus, p->cpus_ptr); 9551 9552 if (cpu < nr_cpu_ids) { 9553 env->flags |= LBF_DST_PINNED; 9554 env->new_dst_cpu = cpu; 9555 } 9556 9557 return 0; 9558 } 9559 9560 /* Record that we found at least one task that could run on dst_cpu */ 9561 env->flags &= ~LBF_ALL_PINNED; 9562 9563 if (task_on_cpu(env->src_rq, p) || 9564 task_current_donor(env->src_rq, p)) { 9565 schedstat_inc(p->stats.nr_failed_migrations_running); 9566 return 0; 9567 } 9568 9569 /* 9570 * Aggressive migration if: 9571 * 1) active balance 9572 * 2) destination numa is preferred 9573 * 3) task is cache cold, or 9574 * 4) too many balance attempts have failed. 9575 */ 9576 if (env->flags & LBF_ACTIVE_LB) 9577 return 1; 9578 9579 degrades = migrate_degrades_locality(p, env); 9580 if (!degrades) 9581 hot = task_hot(p, env); 9582 else 9583 hot = degrades > 0; 9584 9585 if (!hot || env->sd->nr_balance_failed > env->sd->cache_nice_tries) { 9586 if (hot) 9587 p->sched_task_hot = 1; 9588 return 1; 9589 } 9590 9591 schedstat_inc(p->stats.nr_failed_migrations_hot); 9592 return 0; 9593 } 9594 9595 /* 9596 * detach_task() -- detach the task for the migration specified in env 9597 */ 9598 static void detach_task(struct task_struct *p, struct lb_env *env) 9599 { 9600 lockdep_assert_rq_held(env->src_rq); 9601 9602 if (p->sched_task_hot) { 9603 p->sched_task_hot = 0; 9604 schedstat_inc(env->sd->lb_hot_gained[env->idle]); 9605 schedstat_inc(p->stats.nr_forced_migrations); 9606 } 9607 9608 WARN_ON(task_current(env->src_rq, p)); 9609 WARN_ON(task_current_donor(env->src_rq, p)); 9610 9611 deactivate_task(env->src_rq, p, DEQUEUE_NOCLOCK); 9612 set_task_cpu(p, env->dst_cpu); 9613 } 9614 9615 /* 9616 * detach_one_task() -- tries to dequeue exactly one task from env->src_rq, as 9617 * part of active balancing operations within "domain". 9618 * 9619 * Returns a task if successful and NULL otherwise. 9620 */ 9621 static struct task_struct *detach_one_task(struct lb_env *env) 9622 { 9623 struct task_struct *p; 9624 9625 lockdep_assert_rq_held(env->src_rq); 9626 9627 list_for_each_entry_reverse(p, 9628 &env->src_rq->cfs_tasks, se.group_node) { 9629 if (!can_migrate_task(p, env)) 9630 continue; 9631 9632 detach_task(p, env); 9633 9634 /* 9635 * Right now, this is only the second place where 9636 * lb_gained[env->idle] is updated (other is detach_tasks) 9637 * so we can safely collect stats here rather than 9638 * inside detach_tasks(). 9639 */ 9640 schedstat_inc(env->sd->lb_gained[env->idle]); 9641 return p; 9642 } 9643 return NULL; 9644 } 9645 9646 /* 9647 * detach_tasks() -- tries to detach up to imbalance load/util/tasks from 9648 * busiest_rq, as part of a balancing operation within domain "sd". 9649 * 9650 * Returns number of detached tasks if successful and 0 otherwise. 9651 */ 9652 static int detach_tasks(struct lb_env *env) 9653 { 9654 struct list_head *tasks = &env->src_rq->cfs_tasks; 9655 unsigned long util, load; 9656 struct task_struct *p; 9657 int detached = 0; 9658 9659 lockdep_assert_rq_held(env->src_rq); 9660 9661 /* 9662 * Source run queue has been emptied by another CPU, clear 9663 * LBF_ALL_PINNED flag as we will not test any task. 9664 */ 9665 if (env->src_rq->nr_running <= 1) { 9666 env->flags &= ~LBF_ALL_PINNED; 9667 return 0; 9668 } 9669 9670 if (env->imbalance <= 0) 9671 return 0; 9672 9673 while (!list_empty(tasks)) { 9674 /* 9675 * We don't want to steal all, otherwise we may be treated likewise, 9676 * which could at worst lead to a livelock crash. 9677 */ 9678 if (env->idle && env->src_rq->nr_running <= 1) 9679 break; 9680 9681 env->loop++; 9682 /* We've more or less seen every task there is, call it quits */ 9683 if (env->loop > env->loop_max) 9684 break; 9685 9686 /* take a breather every nr_migrate tasks */ 9687 if (env->loop > env->loop_break) { 9688 env->loop_break += SCHED_NR_MIGRATE_BREAK; 9689 env->flags |= LBF_NEED_BREAK; 9690 break; 9691 } 9692 9693 p = list_last_entry(tasks, struct task_struct, se.group_node); 9694 9695 if (!can_migrate_task(p, env)) 9696 goto next; 9697 9698 switch (env->migration_type) { 9699 case migrate_load: 9700 /* 9701 * Depending of the number of CPUs and tasks and the 9702 * cgroup hierarchy, task_h_load() can return a null 9703 * value. Make sure that env->imbalance decreases 9704 * otherwise detach_tasks() will stop only after 9705 * detaching up to loop_max tasks. 9706 */ 9707 load = max_t(unsigned long, task_h_load(p), 1); 9708 9709 if (sched_feat(LB_MIN) && 9710 load < 16 && !env->sd->nr_balance_failed) 9711 goto next; 9712 9713 /* 9714 * Make sure that we don't migrate too much load. 9715 * Nevertheless, let relax the constraint if 9716 * scheduler fails to find a good waiting task to 9717 * migrate. 9718 */ 9719 if (shr_bound(load, env->sd->nr_balance_failed) > env->imbalance) 9720 goto next; 9721 9722 env->imbalance -= load; 9723 break; 9724 9725 case migrate_util: 9726 util = task_util_est(p); 9727 9728 if (shr_bound(util, env->sd->nr_balance_failed) > env->imbalance) 9729 goto next; 9730 9731 env->imbalance -= util; 9732 break; 9733 9734 case migrate_task: 9735 env->imbalance--; 9736 break; 9737 9738 case migrate_misfit: 9739 /* This is not a misfit task */ 9740 if (task_fits_cpu(p, env->src_cpu)) 9741 goto next; 9742 9743 env->imbalance = 0; 9744 break; 9745 } 9746 9747 detach_task(p, env); 9748 list_add(&p->se.group_node, &env->tasks); 9749 9750 detached++; 9751 9752 #ifdef CONFIG_PREEMPTION 9753 /* 9754 * NEWIDLE balancing is a source of latency, so preemptible 9755 * kernels will stop after the first task is detached to minimize 9756 * the critical section. 9757 */ 9758 if (env->idle == CPU_NEWLY_IDLE) 9759 break; 9760 #endif 9761 9762 /* 9763 * We only want to steal up to the prescribed amount of 9764 * load/util/tasks. 9765 */ 9766 if (env->imbalance <= 0) 9767 break; 9768 9769 continue; 9770 next: 9771 if (p->sched_task_hot) 9772 schedstat_inc(p->stats.nr_failed_migrations_hot); 9773 9774 list_move(&p->se.group_node, tasks); 9775 } 9776 9777 /* 9778 * Right now, this is one of only two places we collect this stat 9779 * so we can safely collect detach_one_task() stats here rather 9780 * than inside detach_one_task(). 9781 */ 9782 schedstat_add(env->sd->lb_gained[env->idle], detached); 9783 9784 return detached; 9785 } 9786 9787 /* 9788 * attach_task() -- attach the task detached by detach_task() to its new rq. 9789 */ 9790 static void attach_task(struct rq *rq, struct task_struct *p) 9791 { 9792 lockdep_assert_rq_held(rq); 9793 9794 WARN_ON_ONCE(task_rq(p) != rq); 9795 activate_task(rq, p, ENQUEUE_NOCLOCK); 9796 wakeup_preempt(rq, p, 0); 9797 } 9798 9799 /* 9800 * attach_one_task() -- attaches the task returned from detach_one_task() to 9801 * its new rq. 9802 */ 9803 static void attach_one_task(struct rq *rq, struct task_struct *p) 9804 { 9805 struct rq_flags rf; 9806 9807 rq_lock(rq, &rf); 9808 update_rq_clock(rq); 9809 attach_task(rq, p); 9810 rq_unlock(rq, &rf); 9811 } 9812 9813 /* 9814 * attach_tasks() -- attaches all tasks detached by detach_tasks() to their 9815 * new rq. 9816 */ 9817 static void attach_tasks(struct lb_env *env) 9818 { 9819 struct list_head *tasks = &env->tasks; 9820 struct task_struct *p; 9821 struct rq_flags rf; 9822 9823 rq_lock(env->dst_rq, &rf); 9824 update_rq_clock(env->dst_rq); 9825 9826 while (!list_empty(tasks)) { 9827 p = list_first_entry(tasks, struct task_struct, se.group_node); 9828 list_del_init(&p->se.group_node); 9829 9830 attach_task(env->dst_rq, p); 9831 } 9832 9833 rq_unlock(env->dst_rq, &rf); 9834 } 9835 9836 #ifdef CONFIG_NO_HZ_COMMON 9837 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq) 9838 { 9839 if (cfs_rq->avg.load_avg) 9840 return true; 9841 9842 if (cfs_rq->avg.util_avg) 9843 return true; 9844 9845 return false; 9846 } 9847 9848 static inline bool others_have_blocked(struct rq *rq) 9849 { 9850 if (cpu_util_rt(rq)) 9851 return true; 9852 9853 if (cpu_util_dl(rq)) 9854 return true; 9855 9856 if (hw_load_avg(rq)) 9857 return true; 9858 9859 if (cpu_util_irq(rq)) 9860 return true; 9861 9862 return false; 9863 } 9864 9865 static inline void update_blocked_load_tick(struct rq *rq) 9866 { 9867 WRITE_ONCE(rq->last_blocked_load_update_tick, jiffies); 9868 } 9869 9870 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load) 9871 { 9872 if (!has_blocked_load) 9873 rq->has_blocked_load = 0; 9874 } 9875 #else /* !CONFIG_NO_HZ_COMMON: */ 9876 static inline bool cfs_rq_has_blocked_load(struct cfs_rq *cfs_rq) { return false; } 9877 static inline bool others_have_blocked(struct rq *rq) { return false; } 9878 static inline void update_blocked_load_tick(struct rq *rq) {} 9879 static inline void update_has_blocked_load_status(struct rq *rq, bool has_blocked_load) {} 9880 #endif /* !CONFIG_NO_HZ_COMMON */ 9881 9882 static bool __update_blocked_others(struct rq *rq, bool *done) 9883 { 9884 bool updated; 9885 9886 /* 9887 * update_load_avg() can call cpufreq_update_util(). Make sure that RT, 9888 * DL and IRQ signals have been updated before updating CFS. 9889 */ 9890 updated = update_other_load_avgs(rq); 9891 9892 if (others_have_blocked(rq)) 9893 *done = false; 9894 9895 return updated; 9896 } 9897 9898 #ifdef CONFIG_FAIR_GROUP_SCHED 9899 9900 static bool __update_blocked_fair(struct rq *rq, bool *done) 9901 { 9902 struct cfs_rq *cfs_rq, *pos; 9903 bool decayed = false; 9904 int cpu = cpu_of(rq); 9905 9906 /* 9907 * Iterates the task_group tree in a bottom up fashion, see 9908 * list_add_leaf_cfs_rq() for details. 9909 */ 9910 for_each_leaf_cfs_rq_safe(rq, cfs_rq, pos) { 9911 struct sched_entity *se; 9912 9913 if (update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq)) { 9914 update_tg_load_avg(cfs_rq); 9915 9916 if (cfs_rq->nr_queued == 0) 9917 update_idle_cfs_rq_clock_pelt(cfs_rq); 9918 9919 if (cfs_rq == &rq->cfs) 9920 decayed = true; 9921 } 9922 9923 /* Propagate pending load changes to the parent, if any: */ 9924 se = cfs_rq->tg->se[cpu]; 9925 if (se && !skip_blocked_update(se)) 9926 update_load_avg(cfs_rq_of(se), se, UPDATE_TG); 9927 9928 /* 9929 * There can be a lot of idle CPU cgroups. Don't let fully 9930 * decayed cfs_rqs linger on the list. 9931 */ 9932 if (cfs_rq_is_decayed(cfs_rq)) 9933 list_del_leaf_cfs_rq(cfs_rq); 9934 9935 /* Don't need periodic decay once load/util_avg are null */ 9936 if (cfs_rq_has_blocked_load(cfs_rq)) 9937 *done = false; 9938 } 9939 9940 return decayed; 9941 } 9942 9943 /* 9944 * Compute the hierarchical load factor for cfs_rq and all its ascendants. 9945 * This needs to be done in a top-down fashion because the load of a child 9946 * group is a fraction of its parents load. 9947 */ 9948 static void update_cfs_rq_h_load(struct cfs_rq *cfs_rq) 9949 { 9950 struct rq *rq = rq_of(cfs_rq); 9951 struct sched_entity *se = cfs_rq->tg->se[cpu_of(rq)]; 9952 unsigned long now = jiffies; 9953 unsigned long load; 9954 9955 if (cfs_rq->last_h_load_update == now) 9956 return; 9957 9958 WRITE_ONCE(cfs_rq->h_load_next, NULL); 9959 for_each_sched_entity(se) { 9960 cfs_rq = cfs_rq_of(se); 9961 WRITE_ONCE(cfs_rq->h_load_next, se); 9962 if (cfs_rq->last_h_load_update == now) 9963 break; 9964 } 9965 9966 if (!se) { 9967 cfs_rq->h_load = cfs_rq_load_avg(cfs_rq); 9968 cfs_rq->last_h_load_update = now; 9969 } 9970 9971 while ((se = READ_ONCE(cfs_rq->h_load_next)) != NULL) { 9972 load = cfs_rq->h_load; 9973 load = div64_ul(load * se->avg.load_avg, 9974 cfs_rq_load_avg(cfs_rq) + 1); 9975 cfs_rq = group_cfs_rq(se); 9976 cfs_rq->h_load = load; 9977 cfs_rq->last_h_load_update = now; 9978 } 9979 } 9980 9981 static unsigned long task_h_load(struct task_struct *p) 9982 { 9983 struct cfs_rq *cfs_rq = task_cfs_rq(p); 9984 9985 update_cfs_rq_h_load(cfs_rq); 9986 return div64_ul(p->se.avg.load_avg * cfs_rq->h_load, 9987 cfs_rq_load_avg(cfs_rq) + 1); 9988 } 9989 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 9990 static bool __update_blocked_fair(struct rq *rq, bool *done) 9991 { 9992 struct cfs_rq *cfs_rq = &rq->cfs; 9993 bool decayed; 9994 9995 decayed = update_cfs_rq_load_avg(cfs_rq_clock_pelt(cfs_rq), cfs_rq); 9996 if (cfs_rq_has_blocked_load(cfs_rq)) 9997 *done = false; 9998 9999 return decayed; 10000 } 10001 10002 static unsigned long task_h_load(struct task_struct *p) 10003 { 10004 return p->se.avg.load_avg; 10005 } 10006 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 10007 10008 static void __sched_balance_update_blocked_averages(struct rq *rq) 10009 { 10010 bool decayed = false, done = true; 10011 10012 update_blocked_load_tick(rq); 10013 10014 decayed |= __update_blocked_others(rq, &done); 10015 decayed |= __update_blocked_fair(rq, &done); 10016 10017 update_has_blocked_load_status(rq, !done); 10018 if (decayed) 10019 cpufreq_update_util(rq, 0); 10020 } 10021 10022 static void sched_balance_update_blocked_averages(int cpu) 10023 { 10024 struct rq *rq = cpu_rq(cpu); 10025 10026 guard(rq_lock_irqsave)(rq); 10027 update_rq_clock(rq); 10028 __sched_balance_update_blocked_averages(rq); 10029 } 10030 10031 /********** Helpers for sched_balance_find_src_group ************************/ 10032 10033 /* 10034 * sg_lb_stats - stats of a sched_group required for load-balancing: 10035 */ 10036 struct sg_lb_stats { 10037 unsigned long avg_load; /* Avg load over the CPUs of the group */ 10038 unsigned long group_load; /* Total load over the CPUs of the group */ 10039 unsigned long group_capacity; /* Capacity over the CPUs of the group */ 10040 unsigned long group_util; /* Total utilization over the CPUs of the group */ 10041 unsigned long group_runnable; /* Total runnable time over the CPUs of the group */ 10042 unsigned int sum_nr_running; /* Nr of all tasks running in the group */ 10043 unsigned int sum_h_nr_running; /* Nr of CFS tasks running in the group */ 10044 unsigned int idle_cpus; /* Nr of idle CPUs in the group */ 10045 unsigned int group_weight; 10046 enum group_type group_type; 10047 unsigned int group_asym_packing; /* Tasks should be moved to preferred CPU */ 10048 unsigned int group_smt_balance; /* Task on busy SMT be moved */ 10049 unsigned long group_misfit_task_load; /* A CPU has a task too big for its capacity */ 10050 #ifdef CONFIG_NUMA_BALANCING 10051 unsigned int nr_numa_running; 10052 unsigned int nr_preferred_running; 10053 #endif 10054 }; 10055 10056 /* 10057 * sd_lb_stats - stats of a sched_domain required for load-balancing: 10058 */ 10059 struct sd_lb_stats { 10060 struct sched_group *busiest; /* Busiest group in this sd */ 10061 struct sched_group *local; /* Local group in this sd */ 10062 unsigned long total_load; /* Total load of all groups in sd */ 10063 unsigned long total_capacity; /* Total capacity of all groups in sd */ 10064 unsigned long avg_load; /* Average load across all groups in sd */ 10065 unsigned int prefer_sibling; /* Tasks should go to sibling first */ 10066 10067 struct sg_lb_stats busiest_stat; /* Statistics of the busiest group */ 10068 struct sg_lb_stats local_stat; /* Statistics of the local group */ 10069 }; 10070 10071 static inline void init_sd_lb_stats(struct sd_lb_stats *sds) 10072 { 10073 /* 10074 * Skimp on the clearing to avoid duplicate work. We can avoid clearing 10075 * local_stat because update_sg_lb_stats() does a full clear/assignment. 10076 * We must however set busiest_stat::group_type and 10077 * busiest_stat::idle_cpus to the worst busiest group because 10078 * update_sd_pick_busiest() reads these before assignment. 10079 */ 10080 *sds = (struct sd_lb_stats){ 10081 .busiest = NULL, 10082 .local = NULL, 10083 .total_load = 0UL, 10084 .total_capacity = 0UL, 10085 .busiest_stat = { 10086 .idle_cpus = UINT_MAX, 10087 .group_type = group_has_spare, 10088 }, 10089 }; 10090 } 10091 10092 static unsigned long scale_rt_capacity(int cpu) 10093 { 10094 unsigned long max = get_actual_cpu_capacity(cpu); 10095 struct rq *rq = cpu_rq(cpu); 10096 unsigned long used, free; 10097 unsigned long irq; 10098 10099 irq = cpu_util_irq(rq); 10100 10101 if (unlikely(irq >= max)) 10102 return 1; 10103 10104 /* 10105 * avg_rt.util_avg and avg_dl.util_avg track binary signals 10106 * (running and not running) with weights 0 and 1024 respectively. 10107 */ 10108 used = cpu_util_rt(rq); 10109 used += cpu_util_dl(rq); 10110 10111 if (unlikely(used >= max)) 10112 return 1; 10113 10114 free = max - used; 10115 10116 return scale_irq_capacity(free, irq, max); 10117 } 10118 10119 static void update_cpu_capacity(struct sched_domain *sd, int cpu) 10120 { 10121 unsigned long capacity = scale_rt_capacity(cpu); 10122 struct sched_group *sdg = sd->groups; 10123 10124 if (!capacity) 10125 capacity = 1; 10126 10127 cpu_rq(cpu)->cpu_capacity = capacity; 10128 trace_sched_cpu_capacity_tp(cpu_rq(cpu)); 10129 10130 sdg->sgc->capacity = capacity; 10131 sdg->sgc->min_capacity = capacity; 10132 sdg->sgc->max_capacity = capacity; 10133 } 10134 10135 void update_group_capacity(struct sched_domain *sd, int cpu) 10136 { 10137 struct sched_domain *child = sd->child; 10138 struct sched_group *group, *sdg = sd->groups; 10139 unsigned long capacity, min_capacity, max_capacity; 10140 unsigned long interval; 10141 10142 interval = msecs_to_jiffies(sd->balance_interval); 10143 interval = clamp(interval, 1UL, max_load_balance_interval); 10144 sdg->sgc->next_update = jiffies + interval; 10145 10146 if (!child) { 10147 update_cpu_capacity(sd, cpu); 10148 return; 10149 } 10150 10151 capacity = 0; 10152 min_capacity = ULONG_MAX; 10153 max_capacity = 0; 10154 10155 if (child->flags & SD_NUMA) { 10156 /* 10157 * SD_NUMA domains cannot assume that child groups 10158 * span the current group. 10159 */ 10160 10161 for_each_cpu(cpu, sched_group_span(sdg)) { 10162 unsigned long cpu_cap = capacity_of(cpu); 10163 10164 capacity += cpu_cap; 10165 min_capacity = min(cpu_cap, min_capacity); 10166 max_capacity = max(cpu_cap, max_capacity); 10167 } 10168 } else { 10169 /* 10170 * !SD_NUMA domains can assume that child groups 10171 * span the current group. 10172 */ 10173 10174 group = child->groups; 10175 do { 10176 struct sched_group_capacity *sgc = group->sgc; 10177 10178 capacity += sgc->capacity; 10179 min_capacity = min(sgc->min_capacity, min_capacity); 10180 max_capacity = max(sgc->max_capacity, max_capacity); 10181 group = group->next; 10182 } while (group != child->groups); 10183 } 10184 10185 sdg->sgc->capacity = capacity; 10186 sdg->sgc->min_capacity = min_capacity; 10187 sdg->sgc->max_capacity = max_capacity; 10188 } 10189 10190 /* 10191 * Check whether the capacity of the rq has been noticeably reduced by side 10192 * activity. The imbalance_pct is used for the threshold. 10193 * Return true is the capacity is reduced 10194 */ 10195 static inline int 10196 check_cpu_capacity(struct rq *rq, struct sched_domain *sd) 10197 { 10198 return ((rq->cpu_capacity * sd->imbalance_pct) < 10199 (arch_scale_cpu_capacity(cpu_of(rq)) * 100)); 10200 } 10201 10202 /* Check if the rq has a misfit task */ 10203 static inline bool check_misfit_status(struct rq *rq) 10204 { 10205 return rq->misfit_task_load; 10206 } 10207 10208 /* 10209 * Group imbalance indicates (and tries to solve) the problem where balancing 10210 * groups is inadequate due to ->cpus_ptr constraints. 10211 * 10212 * Imagine a situation of two groups of 4 CPUs each and 4 tasks each with a 10213 * cpumask covering 1 CPU of the first group and 3 CPUs of the second group. 10214 * Something like: 10215 * 10216 * { 0 1 2 3 } { 4 5 6 7 } 10217 * * * * * 10218 * 10219 * If we were to balance group-wise we'd place two tasks in the first group and 10220 * two tasks in the second group. Clearly this is undesired as it will overload 10221 * cpu 3 and leave one of the CPUs in the second group unused. 10222 * 10223 * The current solution to this issue is detecting the skew in the first group 10224 * by noticing the lower domain failed to reach balance and had difficulty 10225 * moving tasks due to affinity constraints. 10226 * 10227 * When this is so detected; this group becomes a candidate for busiest; see 10228 * update_sd_pick_busiest(). And calculate_imbalance() and 10229 * sched_balance_find_src_group() avoid some of the usual balance conditions to allow it 10230 * to create an effective group imbalance. 10231 * 10232 * This is a somewhat tricky proposition since the next run might not find the 10233 * group imbalance and decide the groups need to be balanced again. A most 10234 * subtle and fragile situation. 10235 */ 10236 10237 static inline int sg_imbalanced(struct sched_group *group) 10238 { 10239 return group->sgc->imbalance; 10240 } 10241 10242 /* 10243 * group_has_capacity returns true if the group has spare capacity that could 10244 * be used by some tasks. 10245 * We consider that a group has spare capacity if the number of task is 10246 * smaller than the number of CPUs or if the utilization is lower than the 10247 * available capacity for CFS tasks. 10248 * For the latter, we use a threshold to stabilize the state, to take into 10249 * account the variance of the tasks' load and to return true if the available 10250 * capacity in meaningful for the load balancer. 10251 * As an example, an available capacity of 1% can appear but it doesn't make 10252 * any benefit for the load balance. 10253 */ 10254 static inline bool 10255 group_has_capacity(unsigned int imbalance_pct, struct sg_lb_stats *sgs) 10256 { 10257 if (sgs->sum_nr_running < sgs->group_weight) 10258 return true; 10259 10260 if ((sgs->group_capacity * imbalance_pct) < 10261 (sgs->group_runnable * 100)) 10262 return false; 10263 10264 if ((sgs->group_capacity * 100) > 10265 (sgs->group_util * imbalance_pct)) 10266 return true; 10267 10268 return false; 10269 } 10270 10271 /* 10272 * group_is_overloaded returns true if the group has more tasks than it can 10273 * handle. 10274 * group_is_overloaded is not equals to !group_has_capacity because a group 10275 * with the exact right number of tasks, has no more spare capacity but is not 10276 * overloaded so both group_has_capacity and group_is_overloaded return 10277 * false. 10278 */ 10279 static inline bool 10280 group_is_overloaded(unsigned int imbalance_pct, struct sg_lb_stats *sgs) 10281 { 10282 if (sgs->sum_nr_running <= sgs->group_weight) 10283 return false; 10284 10285 if ((sgs->group_capacity * 100) < 10286 (sgs->group_util * imbalance_pct)) 10287 return true; 10288 10289 if ((sgs->group_capacity * imbalance_pct) < 10290 (sgs->group_runnable * 100)) 10291 return true; 10292 10293 return false; 10294 } 10295 10296 static inline enum 10297 group_type group_classify(unsigned int imbalance_pct, 10298 struct sched_group *group, 10299 struct sg_lb_stats *sgs) 10300 { 10301 if (group_is_overloaded(imbalance_pct, sgs)) 10302 return group_overloaded; 10303 10304 if (sg_imbalanced(group)) 10305 return group_imbalanced; 10306 10307 if (sgs->group_asym_packing) 10308 return group_asym_packing; 10309 10310 if (sgs->group_smt_balance) 10311 return group_smt_balance; 10312 10313 if (sgs->group_misfit_task_load) 10314 return group_misfit_task; 10315 10316 if (!group_has_capacity(imbalance_pct, sgs)) 10317 return group_fully_busy; 10318 10319 return group_has_spare; 10320 } 10321 10322 /** 10323 * sched_use_asym_prio - Check whether asym_packing priority must be used 10324 * @sd: The scheduling domain of the load balancing 10325 * @cpu: A CPU 10326 * 10327 * Always use CPU priority when balancing load between SMT siblings. When 10328 * balancing load between cores, it is not sufficient that @cpu is idle. Only 10329 * use CPU priority if the whole core is idle. 10330 * 10331 * Returns: True if the priority of @cpu must be followed. False otherwise. 10332 */ 10333 static bool sched_use_asym_prio(struct sched_domain *sd, int cpu) 10334 { 10335 if (!(sd->flags & SD_ASYM_PACKING)) 10336 return false; 10337 10338 if (!sched_smt_active()) 10339 return true; 10340 10341 return sd->flags & SD_SHARE_CPUCAPACITY || is_core_idle(cpu); 10342 } 10343 10344 static inline bool sched_asym(struct sched_domain *sd, int dst_cpu, int src_cpu) 10345 { 10346 /* 10347 * First check if @dst_cpu can do asym_packing load balance. Only do it 10348 * if it has higher priority than @src_cpu. 10349 */ 10350 return sched_use_asym_prio(sd, dst_cpu) && 10351 sched_asym_prefer(dst_cpu, src_cpu); 10352 } 10353 10354 /** 10355 * sched_group_asym - Check if the destination CPU can do asym_packing balance 10356 * @env: The load balancing environment 10357 * @sgs: Load-balancing statistics of the candidate busiest group 10358 * @group: The candidate busiest group 10359 * 10360 * @env::dst_cpu can do asym_packing if it has higher priority than the 10361 * preferred CPU of @group. 10362 * 10363 * Return: true if @env::dst_cpu can do with asym_packing load balance. False 10364 * otherwise. 10365 */ 10366 static inline bool 10367 sched_group_asym(struct lb_env *env, struct sg_lb_stats *sgs, struct sched_group *group) 10368 { 10369 /* 10370 * CPU priorities do not make sense for SMT cores with more than one 10371 * busy sibling. 10372 */ 10373 if ((group->flags & SD_SHARE_CPUCAPACITY) && 10374 (sgs->group_weight - sgs->idle_cpus != 1)) 10375 return false; 10376 10377 return sched_asym(env->sd, env->dst_cpu, READ_ONCE(group->asym_prefer_cpu)); 10378 } 10379 10380 /* One group has more than one SMT CPU while the other group does not */ 10381 static inline bool smt_vs_nonsmt_groups(struct sched_group *sg1, 10382 struct sched_group *sg2) 10383 { 10384 if (!sg1 || !sg2) 10385 return false; 10386 10387 return (sg1->flags & SD_SHARE_CPUCAPACITY) != 10388 (sg2->flags & SD_SHARE_CPUCAPACITY); 10389 } 10390 10391 static inline bool smt_balance(struct lb_env *env, struct sg_lb_stats *sgs, 10392 struct sched_group *group) 10393 { 10394 if (!env->idle) 10395 return false; 10396 10397 /* 10398 * For SMT source group, it is better to move a task 10399 * to a CPU that doesn't have multiple tasks sharing its CPU capacity. 10400 * Note that if a group has a single SMT, SD_SHARE_CPUCAPACITY 10401 * will not be on. 10402 */ 10403 if (group->flags & SD_SHARE_CPUCAPACITY && 10404 sgs->sum_h_nr_running > 1) 10405 return true; 10406 10407 return false; 10408 } 10409 10410 static inline long sibling_imbalance(struct lb_env *env, 10411 struct sd_lb_stats *sds, 10412 struct sg_lb_stats *busiest, 10413 struct sg_lb_stats *local) 10414 { 10415 int ncores_busiest, ncores_local; 10416 long imbalance; 10417 10418 if (!env->idle || !busiest->sum_nr_running) 10419 return 0; 10420 10421 ncores_busiest = sds->busiest->cores; 10422 ncores_local = sds->local->cores; 10423 10424 if (ncores_busiest == ncores_local) { 10425 imbalance = busiest->sum_nr_running; 10426 lsub_positive(&imbalance, local->sum_nr_running); 10427 return imbalance; 10428 } 10429 10430 /* Balance such that nr_running/ncores ratio are same on both groups */ 10431 imbalance = ncores_local * busiest->sum_nr_running; 10432 lsub_positive(&imbalance, ncores_busiest * local->sum_nr_running); 10433 /* Normalize imbalance and do rounding on normalization */ 10434 imbalance = 2 * imbalance + ncores_local + ncores_busiest; 10435 imbalance /= ncores_local + ncores_busiest; 10436 10437 /* Take advantage of resource in an empty sched group */ 10438 if (imbalance <= 1 && local->sum_nr_running == 0 && 10439 busiest->sum_nr_running > 1) 10440 imbalance = 2; 10441 10442 return imbalance; 10443 } 10444 10445 static inline bool 10446 sched_reduced_capacity(struct rq *rq, struct sched_domain *sd) 10447 { 10448 /* 10449 * When there is more than 1 task, the group_overloaded case already 10450 * takes care of cpu with reduced capacity 10451 */ 10452 if (rq->cfs.h_nr_runnable != 1) 10453 return false; 10454 10455 return check_cpu_capacity(rq, sd); 10456 } 10457 10458 /** 10459 * update_sg_lb_stats - Update sched_group's statistics for load balancing. 10460 * @env: The load balancing environment. 10461 * @sds: Load-balancing data with statistics of the local group. 10462 * @group: sched_group whose statistics are to be updated. 10463 * @sgs: variable to hold the statistics for this group. 10464 * @sg_overloaded: sched_group is overloaded 10465 * @sg_overutilized: sched_group is overutilized 10466 */ 10467 static inline void update_sg_lb_stats(struct lb_env *env, 10468 struct sd_lb_stats *sds, 10469 struct sched_group *group, 10470 struct sg_lb_stats *sgs, 10471 bool *sg_overloaded, 10472 bool *sg_overutilized) 10473 { 10474 int i, nr_running, local_group, sd_flags = env->sd->flags; 10475 bool balancing_at_rd = !env->sd->parent; 10476 10477 memset(sgs, 0, sizeof(*sgs)); 10478 10479 local_group = group == sds->local; 10480 10481 for_each_cpu_and(i, sched_group_span(group), env->cpus) { 10482 struct rq *rq = cpu_rq(i); 10483 unsigned long load = cpu_load(rq); 10484 10485 sgs->group_load += load; 10486 sgs->group_util += cpu_util_cfs(i); 10487 sgs->group_runnable += cpu_runnable(rq); 10488 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable; 10489 10490 nr_running = rq->nr_running; 10491 sgs->sum_nr_running += nr_running; 10492 10493 if (cpu_overutilized(i)) 10494 *sg_overutilized = 1; 10495 10496 /* 10497 * No need to call idle_cpu() if nr_running is not 0 10498 */ 10499 if (!nr_running && idle_cpu(i)) { 10500 sgs->idle_cpus++; 10501 /* Idle cpu can't have misfit task */ 10502 continue; 10503 } 10504 10505 /* Overload indicator is only updated at root domain */ 10506 if (balancing_at_rd && nr_running > 1) 10507 *sg_overloaded = 1; 10508 10509 #ifdef CONFIG_NUMA_BALANCING 10510 /* Only fbq_classify_group() uses this to classify NUMA groups */ 10511 if (sd_flags & SD_NUMA) { 10512 sgs->nr_numa_running += rq->nr_numa_running; 10513 sgs->nr_preferred_running += rq->nr_preferred_running; 10514 } 10515 #endif 10516 if (local_group) 10517 continue; 10518 10519 if (sd_flags & SD_ASYM_CPUCAPACITY) { 10520 /* Check for a misfit task on the cpu */ 10521 if (sgs->group_misfit_task_load < rq->misfit_task_load) { 10522 sgs->group_misfit_task_load = rq->misfit_task_load; 10523 *sg_overloaded = 1; 10524 } 10525 } else if (env->idle && sched_reduced_capacity(rq, env->sd)) { 10526 /* Check for a task running on a CPU with reduced capacity */ 10527 if (sgs->group_misfit_task_load < load) 10528 sgs->group_misfit_task_load = load; 10529 } 10530 } 10531 10532 sgs->group_capacity = group->sgc->capacity; 10533 10534 sgs->group_weight = group->group_weight; 10535 10536 /* Check if dst CPU is idle and preferred to this group */ 10537 if (!local_group && env->idle && sgs->sum_h_nr_running && 10538 sched_group_asym(env, sgs, group)) 10539 sgs->group_asym_packing = 1; 10540 10541 /* Check for loaded SMT group to be balanced to dst CPU */ 10542 if (!local_group && smt_balance(env, sgs, group)) 10543 sgs->group_smt_balance = 1; 10544 10545 sgs->group_type = group_classify(env->sd->imbalance_pct, group, sgs); 10546 10547 /* Computing avg_load makes sense only when group is overloaded */ 10548 if (sgs->group_type == group_overloaded) 10549 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) / 10550 sgs->group_capacity; 10551 } 10552 10553 /** 10554 * update_sd_pick_busiest - return 1 on busiest group 10555 * @env: The load balancing environment. 10556 * @sds: sched_domain statistics 10557 * @sg: sched_group candidate to be checked for being the busiest 10558 * @sgs: sched_group statistics 10559 * 10560 * Determine if @sg is a busier group than the previously selected 10561 * busiest group. 10562 * 10563 * Return: %true if @sg is a busier group than the previously selected 10564 * busiest group. %false otherwise. 10565 */ 10566 static bool update_sd_pick_busiest(struct lb_env *env, 10567 struct sd_lb_stats *sds, 10568 struct sched_group *sg, 10569 struct sg_lb_stats *sgs) 10570 { 10571 struct sg_lb_stats *busiest = &sds->busiest_stat; 10572 10573 /* Make sure that there is at least one task to pull */ 10574 if (!sgs->sum_h_nr_running) 10575 return false; 10576 10577 /* 10578 * Don't try to pull misfit tasks we can't help. 10579 * We can use max_capacity here as reduction in capacity on some 10580 * CPUs in the group should either be possible to resolve 10581 * internally or be covered by avg_load imbalance (eventually). 10582 */ 10583 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) && 10584 (sgs->group_type == group_misfit_task) && 10585 (!capacity_greater(capacity_of(env->dst_cpu), sg->sgc->max_capacity) || 10586 sds->local_stat.group_type != group_has_spare)) 10587 return false; 10588 10589 if (sgs->group_type > busiest->group_type) 10590 return true; 10591 10592 if (sgs->group_type < busiest->group_type) 10593 return false; 10594 10595 /* 10596 * The candidate and the current busiest group are the same type of 10597 * group. Let check which one is the busiest according to the type. 10598 */ 10599 10600 switch (sgs->group_type) { 10601 case group_overloaded: 10602 /* Select the overloaded group with highest avg_load. */ 10603 return sgs->avg_load > busiest->avg_load; 10604 10605 case group_imbalanced: 10606 /* 10607 * Select the 1st imbalanced group as we don't have any way to 10608 * choose one more than another. 10609 */ 10610 return false; 10611 10612 case group_asym_packing: 10613 /* Prefer to move from lowest priority CPU's work */ 10614 return sched_asym_prefer(READ_ONCE(sds->busiest->asym_prefer_cpu), 10615 READ_ONCE(sg->asym_prefer_cpu)); 10616 10617 case group_misfit_task: 10618 /* 10619 * If we have more than one misfit sg go with the biggest 10620 * misfit. 10621 */ 10622 return sgs->group_misfit_task_load > busiest->group_misfit_task_load; 10623 10624 case group_smt_balance: 10625 /* 10626 * Check if we have spare CPUs on either SMT group to 10627 * choose has spare or fully busy handling. 10628 */ 10629 if (sgs->idle_cpus != 0 || busiest->idle_cpus != 0) 10630 goto has_spare; 10631 10632 fallthrough; 10633 10634 case group_fully_busy: 10635 /* 10636 * Select the fully busy group with highest avg_load. In 10637 * theory, there is no need to pull task from such kind of 10638 * group because tasks have all compute capacity that they need 10639 * but we can still improve the overall throughput by reducing 10640 * contention when accessing shared HW resources. 10641 * 10642 * XXX for now avg_load is not computed and always 0 so we 10643 * select the 1st one, except if @sg is composed of SMT 10644 * siblings. 10645 */ 10646 10647 if (sgs->avg_load < busiest->avg_load) 10648 return false; 10649 10650 if (sgs->avg_load == busiest->avg_load) { 10651 /* 10652 * SMT sched groups need more help than non-SMT groups. 10653 * If @sg happens to also be SMT, either choice is good. 10654 */ 10655 if (sds->busiest->flags & SD_SHARE_CPUCAPACITY) 10656 return false; 10657 } 10658 10659 break; 10660 10661 case group_has_spare: 10662 /* 10663 * Do not pick sg with SMT CPUs over sg with pure CPUs, 10664 * as we do not want to pull task off SMT core with one task 10665 * and make the core idle. 10666 */ 10667 if (smt_vs_nonsmt_groups(sds->busiest, sg)) { 10668 if (sg->flags & SD_SHARE_CPUCAPACITY && sgs->sum_h_nr_running <= 1) 10669 return false; 10670 else 10671 return true; 10672 } 10673 has_spare: 10674 10675 /* 10676 * Select not overloaded group with lowest number of idle CPUs 10677 * and highest number of running tasks. We could also compare 10678 * the spare capacity which is more stable but it can end up 10679 * that the group has less spare capacity but finally more idle 10680 * CPUs which means less opportunity to pull tasks. 10681 */ 10682 if (sgs->idle_cpus > busiest->idle_cpus) 10683 return false; 10684 else if ((sgs->idle_cpus == busiest->idle_cpus) && 10685 (sgs->sum_nr_running <= busiest->sum_nr_running)) 10686 return false; 10687 10688 break; 10689 } 10690 10691 /* 10692 * Candidate sg has no more than one task per CPU and has higher 10693 * per-CPU capacity. Migrating tasks to less capable CPUs may harm 10694 * throughput. Maximize throughput, power/energy consequences are not 10695 * considered. 10696 */ 10697 if ((env->sd->flags & SD_ASYM_CPUCAPACITY) && 10698 (sgs->group_type <= group_fully_busy) && 10699 (capacity_greater(sg->sgc->min_capacity, capacity_of(env->dst_cpu)))) 10700 return false; 10701 10702 return true; 10703 } 10704 10705 #ifdef CONFIG_NUMA_BALANCING 10706 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs) 10707 { 10708 if (sgs->sum_h_nr_running > sgs->nr_numa_running) 10709 return regular; 10710 if (sgs->sum_h_nr_running > sgs->nr_preferred_running) 10711 return remote; 10712 return all; 10713 } 10714 10715 static inline enum fbq_type fbq_classify_rq(struct rq *rq) 10716 { 10717 if (rq->nr_running > rq->nr_numa_running) 10718 return regular; 10719 if (rq->nr_running > rq->nr_preferred_running) 10720 return remote; 10721 return all; 10722 } 10723 #else /* !CONFIG_NUMA_BALANCING: */ 10724 static inline enum fbq_type fbq_classify_group(struct sg_lb_stats *sgs) 10725 { 10726 return all; 10727 } 10728 10729 static inline enum fbq_type fbq_classify_rq(struct rq *rq) 10730 { 10731 return regular; 10732 } 10733 #endif /* !CONFIG_NUMA_BALANCING */ 10734 10735 10736 struct sg_lb_stats; 10737 10738 /* 10739 * task_running_on_cpu - return 1 if @p is running on @cpu. 10740 */ 10741 10742 static unsigned int task_running_on_cpu(int cpu, struct task_struct *p) 10743 { 10744 /* Task has no contribution or is new */ 10745 if (cpu != task_cpu(p) || !READ_ONCE(p->se.avg.last_update_time)) 10746 return 0; 10747 10748 if (task_on_rq_queued(p)) 10749 return 1; 10750 10751 return 0; 10752 } 10753 10754 /** 10755 * idle_cpu_without - would a given CPU be idle without p ? 10756 * @cpu: the processor on which idleness is tested. 10757 * @p: task which should be ignored. 10758 * 10759 * Return: 1 if the CPU would be idle. 0 otherwise. 10760 */ 10761 static int idle_cpu_without(int cpu, struct task_struct *p) 10762 { 10763 struct rq *rq = cpu_rq(cpu); 10764 10765 if (rq->curr != rq->idle && rq->curr != p) 10766 return 0; 10767 10768 /* 10769 * rq->nr_running can't be used but an updated version without the 10770 * impact of p on cpu must be used instead. The updated nr_running 10771 * be computed and tested before calling idle_cpu_without(). 10772 */ 10773 10774 if (rq->ttwu_pending) 10775 return 0; 10776 10777 return 1; 10778 } 10779 10780 /* 10781 * update_sg_wakeup_stats - Update sched_group's statistics for wakeup. 10782 * @sd: The sched_domain level to look for idlest group. 10783 * @group: sched_group whose statistics are to be updated. 10784 * @sgs: variable to hold the statistics for this group. 10785 * @p: The task for which we look for the idlest group/CPU. 10786 */ 10787 static inline void update_sg_wakeup_stats(struct sched_domain *sd, 10788 struct sched_group *group, 10789 struct sg_lb_stats *sgs, 10790 struct task_struct *p) 10791 { 10792 int i, nr_running; 10793 10794 memset(sgs, 0, sizeof(*sgs)); 10795 10796 /* Assume that task can't fit any CPU of the group */ 10797 if (sd->flags & SD_ASYM_CPUCAPACITY) 10798 sgs->group_misfit_task_load = 1; 10799 10800 for_each_cpu_and(i, sched_group_span(group), p->cpus_ptr) { 10801 struct rq *rq = cpu_rq(i); 10802 unsigned int local; 10803 10804 sgs->group_load += cpu_load_without(rq, p); 10805 sgs->group_util += cpu_util_without(i, p); 10806 sgs->group_runnable += cpu_runnable_without(rq, p); 10807 local = task_running_on_cpu(i, p); 10808 sgs->sum_h_nr_running += rq->cfs.h_nr_runnable - local; 10809 10810 nr_running = rq->nr_running - local; 10811 sgs->sum_nr_running += nr_running; 10812 10813 /* 10814 * No need to call idle_cpu_without() if nr_running is not 0 10815 */ 10816 if (!nr_running && idle_cpu_without(i, p)) 10817 sgs->idle_cpus++; 10818 10819 /* Check if task fits in the CPU */ 10820 if (sd->flags & SD_ASYM_CPUCAPACITY && 10821 sgs->group_misfit_task_load && 10822 task_fits_cpu(p, i)) 10823 sgs->group_misfit_task_load = 0; 10824 10825 } 10826 10827 sgs->group_capacity = group->sgc->capacity; 10828 10829 sgs->group_weight = group->group_weight; 10830 10831 sgs->group_type = group_classify(sd->imbalance_pct, group, sgs); 10832 10833 /* 10834 * Computing avg_load makes sense only when group is fully busy or 10835 * overloaded 10836 */ 10837 if (sgs->group_type == group_fully_busy || 10838 sgs->group_type == group_overloaded) 10839 sgs->avg_load = (sgs->group_load * SCHED_CAPACITY_SCALE) / 10840 sgs->group_capacity; 10841 } 10842 10843 static bool update_pick_idlest(struct sched_group *idlest, 10844 struct sg_lb_stats *idlest_sgs, 10845 struct sched_group *group, 10846 struct sg_lb_stats *sgs) 10847 { 10848 if (sgs->group_type < idlest_sgs->group_type) 10849 return true; 10850 10851 if (sgs->group_type > idlest_sgs->group_type) 10852 return false; 10853 10854 /* 10855 * The candidate and the current idlest group are the same type of 10856 * group. Let check which one is the idlest according to the type. 10857 */ 10858 10859 switch (sgs->group_type) { 10860 case group_overloaded: 10861 case group_fully_busy: 10862 /* Select the group with lowest avg_load. */ 10863 if (idlest_sgs->avg_load <= sgs->avg_load) 10864 return false; 10865 break; 10866 10867 case group_imbalanced: 10868 case group_asym_packing: 10869 case group_smt_balance: 10870 /* Those types are not used in the slow wakeup path */ 10871 return false; 10872 10873 case group_misfit_task: 10874 /* Select group with the highest max capacity */ 10875 if (idlest->sgc->max_capacity >= group->sgc->max_capacity) 10876 return false; 10877 break; 10878 10879 case group_has_spare: 10880 /* Select group with most idle CPUs */ 10881 if (idlest_sgs->idle_cpus > sgs->idle_cpus) 10882 return false; 10883 10884 /* Select group with lowest group_util */ 10885 if (idlest_sgs->idle_cpus == sgs->idle_cpus && 10886 idlest_sgs->group_util <= sgs->group_util) 10887 return false; 10888 10889 break; 10890 } 10891 10892 return true; 10893 } 10894 10895 /* 10896 * sched_balance_find_dst_group() finds and returns the least busy CPU group within the 10897 * domain. 10898 * 10899 * Assumes p is allowed on at least one CPU in sd. 10900 */ 10901 static struct sched_group * 10902 sched_balance_find_dst_group(struct sched_domain *sd, struct task_struct *p, int this_cpu) 10903 { 10904 struct sched_group *idlest = NULL, *local = NULL, *group = sd->groups; 10905 struct sg_lb_stats local_sgs, tmp_sgs; 10906 struct sg_lb_stats *sgs; 10907 unsigned long imbalance; 10908 struct sg_lb_stats idlest_sgs = { 10909 .avg_load = UINT_MAX, 10910 .group_type = group_overloaded, 10911 }; 10912 10913 do { 10914 int local_group; 10915 10916 /* Skip over this group if it has no CPUs allowed */ 10917 if (!cpumask_intersects(sched_group_span(group), 10918 p->cpus_ptr)) 10919 continue; 10920 10921 /* Skip over this group if no cookie matched */ 10922 if (!sched_group_cookie_match(cpu_rq(this_cpu), p, group)) 10923 continue; 10924 10925 local_group = cpumask_test_cpu(this_cpu, 10926 sched_group_span(group)); 10927 10928 if (local_group) { 10929 sgs = &local_sgs; 10930 local = group; 10931 } else { 10932 sgs = &tmp_sgs; 10933 } 10934 10935 update_sg_wakeup_stats(sd, group, sgs, p); 10936 10937 if (!local_group && update_pick_idlest(idlest, &idlest_sgs, group, sgs)) { 10938 idlest = group; 10939 idlest_sgs = *sgs; 10940 } 10941 10942 } while (group = group->next, group != sd->groups); 10943 10944 10945 /* There is no idlest group to push tasks to */ 10946 if (!idlest) 10947 return NULL; 10948 10949 /* The local group has been skipped because of CPU affinity */ 10950 if (!local) 10951 return idlest; 10952 10953 /* 10954 * If the local group is idler than the selected idlest group 10955 * don't try and push the task. 10956 */ 10957 if (local_sgs.group_type < idlest_sgs.group_type) 10958 return NULL; 10959 10960 /* 10961 * If the local group is busier than the selected idlest group 10962 * try and push the task. 10963 */ 10964 if (local_sgs.group_type > idlest_sgs.group_type) 10965 return idlest; 10966 10967 switch (local_sgs.group_type) { 10968 case group_overloaded: 10969 case group_fully_busy: 10970 10971 /* Calculate allowed imbalance based on load */ 10972 imbalance = scale_load_down(NICE_0_LOAD) * 10973 (sd->imbalance_pct-100) / 100; 10974 10975 /* 10976 * When comparing groups across NUMA domains, it's possible for 10977 * the local domain to be very lightly loaded relative to the 10978 * remote domains but "imbalance" skews the comparison making 10979 * remote CPUs look much more favourable. When considering 10980 * cross-domain, add imbalance to the load on the remote node 10981 * and consider staying local. 10982 */ 10983 10984 if ((sd->flags & SD_NUMA) && 10985 ((idlest_sgs.avg_load + imbalance) >= local_sgs.avg_load)) 10986 return NULL; 10987 10988 /* 10989 * If the local group is less loaded than the selected 10990 * idlest group don't try and push any tasks. 10991 */ 10992 if (idlest_sgs.avg_load >= (local_sgs.avg_load + imbalance)) 10993 return NULL; 10994 10995 if (100 * local_sgs.avg_load <= sd->imbalance_pct * idlest_sgs.avg_load) 10996 return NULL; 10997 break; 10998 10999 case group_imbalanced: 11000 case group_asym_packing: 11001 case group_smt_balance: 11002 /* Those type are not used in the slow wakeup path */ 11003 return NULL; 11004 11005 case group_misfit_task: 11006 /* Select group with the highest max capacity */ 11007 if (local->sgc->max_capacity >= idlest->sgc->max_capacity) 11008 return NULL; 11009 break; 11010 11011 case group_has_spare: 11012 #ifdef CONFIG_NUMA 11013 if (sd->flags & SD_NUMA) { 11014 int imb_numa_nr = sd->imb_numa_nr; 11015 #ifdef CONFIG_NUMA_BALANCING 11016 int idlest_cpu; 11017 /* 11018 * If there is spare capacity at NUMA, try to select 11019 * the preferred node 11020 */ 11021 if (cpu_to_node(this_cpu) == p->numa_preferred_nid) 11022 return NULL; 11023 11024 idlest_cpu = cpumask_first(sched_group_span(idlest)); 11025 if (cpu_to_node(idlest_cpu) == p->numa_preferred_nid) 11026 return idlest; 11027 #endif /* CONFIG_NUMA_BALANCING */ 11028 /* 11029 * Otherwise, keep the task close to the wakeup source 11030 * and improve locality if the number of running tasks 11031 * would remain below threshold where an imbalance is 11032 * allowed while accounting for the possibility the 11033 * task is pinned to a subset of CPUs. If there is a 11034 * real need of migration, periodic load balance will 11035 * take care of it. 11036 */ 11037 if (p->nr_cpus_allowed != NR_CPUS) { 11038 unsigned int w = cpumask_weight_and(p->cpus_ptr, 11039 sched_group_span(local)); 11040 imb_numa_nr = min(w, sd->imb_numa_nr); 11041 } 11042 11043 imbalance = abs(local_sgs.idle_cpus - idlest_sgs.idle_cpus); 11044 if (!adjust_numa_imbalance(imbalance, 11045 local_sgs.sum_nr_running + 1, 11046 imb_numa_nr)) { 11047 return NULL; 11048 } 11049 } 11050 #endif /* CONFIG_NUMA */ 11051 11052 /* 11053 * Select group with highest number of idle CPUs. We could also 11054 * compare the utilization which is more stable but it can end 11055 * up that the group has less spare capacity but finally more 11056 * idle CPUs which means more opportunity to run task. 11057 */ 11058 if (local_sgs.idle_cpus >= idlest_sgs.idle_cpus) 11059 return NULL; 11060 break; 11061 } 11062 11063 return idlest; 11064 } 11065 11066 static void update_idle_cpu_scan(struct lb_env *env, 11067 unsigned long sum_util) 11068 { 11069 struct sched_domain_shared *sd_share; 11070 int llc_weight, pct; 11071 u64 x, y, tmp; 11072 /* 11073 * Update the number of CPUs to scan in LLC domain, which could 11074 * be used as a hint in select_idle_cpu(). The update of sd_share 11075 * could be expensive because it is within a shared cache line. 11076 * So the write of this hint only occurs during periodic load 11077 * balancing, rather than CPU_NEWLY_IDLE, because the latter 11078 * can fire way more frequently than the former. 11079 */ 11080 if (!sched_feat(SIS_UTIL) || env->idle == CPU_NEWLY_IDLE) 11081 return; 11082 11083 llc_weight = per_cpu(sd_llc_size, env->dst_cpu); 11084 if (env->sd->span_weight != llc_weight) 11085 return; 11086 11087 sd_share = rcu_dereference_all(per_cpu(sd_llc_shared, env->dst_cpu)); 11088 if (!sd_share) 11089 return; 11090 11091 /* 11092 * The number of CPUs to search drops as sum_util increases, when 11093 * sum_util hits 85% or above, the scan stops. 11094 * The reason to choose 85% as the threshold is because this is the 11095 * imbalance_pct(117) when a LLC sched group is overloaded. 11096 * 11097 * let y = SCHED_CAPACITY_SCALE - p * x^2 [1] 11098 * and y'= y / SCHED_CAPACITY_SCALE 11099 * 11100 * x is the ratio of sum_util compared to the CPU capacity: 11101 * x = sum_util / (llc_weight * SCHED_CAPACITY_SCALE) 11102 * y' is the ratio of CPUs to be scanned in the LLC domain, 11103 * and the number of CPUs to scan is calculated by: 11104 * 11105 * nr_scan = llc_weight * y' [2] 11106 * 11107 * When x hits the threshold of overloaded, AKA, when 11108 * x = 100 / pct, y drops to 0. According to [1], 11109 * p should be SCHED_CAPACITY_SCALE * pct^2 / 10000 11110 * 11111 * Scale x by SCHED_CAPACITY_SCALE: 11112 * x' = sum_util / llc_weight; [3] 11113 * 11114 * and finally [1] becomes: 11115 * y = SCHED_CAPACITY_SCALE - 11116 * x'^2 * pct^2 / (10000 * SCHED_CAPACITY_SCALE) [4] 11117 * 11118 */ 11119 /* equation [3] */ 11120 x = sum_util; 11121 do_div(x, llc_weight); 11122 11123 /* equation [4] */ 11124 pct = env->sd->imbalance_pct; 11125 tmp = x * x * pct * pct; 11126 do_div(tmp, 10000 * SCHED_CAPACITY_SCALE); 11127 tmp = min_t(long, tmp, SCHED_CAPACITY_SCALE); 11128 y = SCHED_CAPACITY_SCALE - tmp; 11129 11130 /* equation [2] */ 11131 y *= llc_weight; 11132 do_div(y, SCHED_CAPACITY_SCALE); 11133 if ((int)y != sd_share->nr_idle_scan) 11134 WRITE_ONCE(sd_share->nr_idle_scan, (int)y); 11135 } 11136 11137 /** 11138 * update_sd_lb_stats - Update sched_domain's statistics for load balancing. 11139 * @env: The load balancing environment. 11140 * @sds: variable to hold the statistics for this sched_domain. 11141 */ 11142 11143 static inline void update_sd_lb_stats(struct lb_env *env, struct sd_lb_stats *sds) 11144 { 11145 struct sched_group *sg = env->sd->groups; 11146 struct sg_lb_stats *local = &sds->local_stat; 11147 struct sg_lb_stats tmp_sgs; 11148 unsigned long sum_util = 0; 11149 bool sg_overloaded = 0, sg_overutilized = 0; 11150 11151 do { 11152 struct sg_lb_stats *sgs = &tmp_sgs; 11153 int local_group; 11154 11155 local_group = cpumask_test_cpu(env->dst_cpu, sched_group_span(sg)); 11156 if (local_group) { 11157 sds->local = sg; 11158 sgs = local; 11159 11160 if (env->idle != CPU_NEWLY_IDLE || 11161 time_after_eq(jiffies, sg->sgc->next_update)) 11162 update_group_capacity(env->sd, env->dst_cpu); 11163 } 11164 11165 update_sg_lb_stats(env, sds, sg, sgs, &sg_overloaded, &sg_overutilized); 11166 11167 if (!local_group && update_sd_pick_busiest(env, sds, sg, sgs)) { 11168 sds->busiest = sg; 11169 sds->busiest_stat = *sgs; 11170 } 11171 11172 /* Now, start updating sd_lb_stats */ 11173 sds->total_load += sgs->group_load; 11174 sds->total_capacity += sgs->group_capacity; 11175 11176 sum_util += sgs->group_util; 11177 sg = sg->next; 11178 } while (sg != env->sd->groups); 11179 11180 /* 11181 * Indicate that the child domain of the busiest group prefers tasks 11182 * go to a child's sibling domains first. NB the flags of a sched group 11183 * are those of the child domain. 11184 */ 11185 if (sds->busiest) 11186 sds->prefer_sibling = !!(sds->busiest->flags & SD_PREFER_SIBLING); 11187 11188 11189 if (env->sd->flags & SD_NUMA) 11190 env->fbq_type = fbq_classify_group(&sds->busiest_stat); 11191 11192 if (!env->sd->parent) { 11193 /* update overload indicator if we are at root domain */ 11194 set_rd_overloaded(env->dst_rq->rd, sg_overloaded); 11195 11196 /* Update over-utilization (tipping point, U >= 0) indicator */ 11197 set_rd_overutilized(env->dst_rq->rd, sg_overutilized); 11198 } else if (sg_overutilized) { 11199 set_rd_overutilized(env->dst_rq->rd, sg_overutilized); 11200 } 11201 11202 update_idle_cpu_scan(env, sum_util); 11203 } 11204 11205 /** 11206 * calculate_imbalance - Calculate the amount of imbalance present within the 11207 * groups of a given sched_domain during load balance. 11208 * @env: load balance environment 11209 * @sds: statistics of the sched_domain whose imbalance is to be calculated. 11210 */ 11211 static inline void calculate_imbalance(struct lb_env *env, struct sd_lb_stats *sds) 11212 { 11213 struct sg_lb_stats *local, *busiest; 11214 11215 local = &sds->local_stat; 11216 busiest = &sds->busiest_stat; 11217 11218 if (busiest->group_type == group_misfit_task) { 11219 if (env->sd->flags & SD_ASYM_CPUCAPACITY) { 11220 /* Set imbalance to allow misfit tasks to be balanced. */ 11221 env->migration_type = migrate_misfit; 11222 env->imbalance = 1; 11223 } else { 11224 /* 11225 * Set load imbalance to allow moving task from cpu 11226 * with reduced capacity. 11227 */ 11228 env->migration_type = migrate_load; 11229 env->imbalance = busiest->group_misfit_task_load; 11230 } 11231 return; 11232 } 11233 11234 if (busiest->group_type == group_asym_packing) { 11235 /* 11236 * In case of asym capacity, we will try to migrate all load to 11237 * the preferred CPU. 11238 */ 11239 env->migration_type = migrate_task; 11240 env->imbalance = busiest->sum_h_nr_running; 11241 return; 11242 } 11243 11244 if (busiest->group_type == group_smt_balance) { 11245 /* Reduce number of tasks sharing CPU capacity */ 11246 env->migration_type = migrate_task; 11247 env->imbalance = 1; 11248 return; 11249 } 11250 11251 if (busiest->group_type == group_imbalanced) { 11252 /* 11253 * In the group_imb case we cannot rely on group-wide averages 11254 * to ensure CPU-load equilibrium, try to move any task to fix 11255 * the imbalance. The next load balance will take care of 11256 * balancing back the system. 11257 */ 11258 env->migration_type = migrate_task; 11259 env->imbalance = 1; 11260 return; 11261 } 11262 11263 /* 11264 * Try to use spare capacity of local group without overloading it or 11265 * emptying busiest. 11266 */ 11267 if (local->group_type == group_has_spare) { 11268 if ((busiest->group_type > group_fully_busy) && 11269 !(env->sd->flags & SD_SHARE_LLC)) { 11270 /* 11271 * If busiest is overloaded, try to fill spare 11272 * capacity. This might end up creating spare capacity 11273 * in busiest or busiest still being overloaded but 11274 * there is no simple way to directly compute the 11275 * amount of load to migrate in order to balance the 11276 * system. 11277 */ 11278 env->migration_type = migrate_util; 11279 env->imbalance = max(local->group_capacity, local->group_util) - 11280 local->group_util; 11281 11282 /* 11283 * In some cases, the group's utilization is max or even 11284 * higher than capacity because of migrations but the 11285 * local CPU is (newly) idle. There is at least one 11286 * waiting task in this overloaded busiest group. Let's 11287 * try to pull it. 11288 */ 11289 if (env->idle && env->imbalance == 0) { 11290 env->migration_type = migrate_task; 11291 env->imbalance = 1; 11292 } 11293 11294 return; 11295 } 11296 11297 if (busiest->group_weight == 1 || sds->prefer_sibling) { 11298 /* 11299 * When prefer sibling, evenly spread running tasks on 11300 * groups. 11301 */ 11302 env->migration_type = migrate_task; 11303 env->imbalance = sibling_imbalance(env, sds, busiest, local); 11304 } else { 11305 11306 /* 11307 * If there is no overload, we just want to even the number of 11308 * idle CPUs. 11309 */ 11310 env->migration_type = migrate_task; 11311 env->imbalance = max_t(long, 0, 11312 (local->idle_cpus - busiest->idle_cpus)); 11313 } 11314 11315 #ifdef CONFIG_NUMA 11316 /* Consider allowing a small imbalance between NUMA groups */ 11317 if (env->sd->flags & SD_NUMA) { 11318 env->imbalance = adjust_numa_imbalance(env->imbalance, 11319 local->sum_nr_running + 1, 11320 env->sd->imb_numa_nr); 11321 } 11322 #endif 11323 11324 /* Number of tasks to move to restore balance */ 11325 env->imbalance >>= 1; 11326 11327 return; 11328 } 11329 11330 /* 11331 * Local is fully busy but has to take more load to relieve the 11332 * busiest group 11333 */ 11334 if (local->group_type < group_overloaded) { 11335 /* 11336 * Local will become overloaded so the avg_load metrics are 11337 * finally needed. 11338 */ 11339 11340 local->avg_load = (local->group_load * SCHED_CAPACITY_SCALE) / 11341 local->group_capacity; 11342 11343 /* 11344 * If the local group is more loaded than the selected 11345 * busiest group don't try to pull any tasks. 11346 */ 11347 if (local->avg_load >= busiest->avg_load) { 11348 env->imbalance = 0; 11349 return; 11350 } 11351 11352 sds->avg_load = (sds->total_load * SCHED_CAPACITY_SCALE) / 11353 sds->total_capacity; 11354 11355 /* 11356 * If the local group is more loaded than the average system 11357 * load, don't try to pull any tasks. 11358 */ 11359 if (local->avg_load >= sds->avg_load) { 11360 env->imbalance = 0; 11361 return; 11362 } 11363 11364 } 11365 11366 /* 11367 * Both group are or will become overloaded and we're trying to get all 11368 * the CPUs to the average_load, so we don't want to push ourselves 11369 * above the average load, nor do we wish to reduce the max loaded CPU 11370 * below the average load. At the same time, we also don't want to 11371 * reduce the group load below the group capacity. Thus we look for 11372 * the minimum possible imbalance. 11373 */ 11374 env->migration_type = migrate_load; 11375 env->imbalance = min( 11376 (busiest->avg_load - sds->avg_load) * busiest->group_capacity, 11377 (sds->avg_load - local->avg_load) * local->group_capacity 11378 ) / SCHED_CAPACITY_SCALE; 11379 } 11380 11381 /******* sched_balance_find_src_group() helpers end here *********************/ 11382 11383 /* 11384 * Decision matrix according to the local and busiest group type: 11385 * 11386 * busiest \ local has_spare fully_busy misfit asym imbalanced overloaded 11387 * has_spare nr_idle balanced N/A N/A balanced balanced 11388 * fully_busy nr_idle nr_idle N/A N/A balanced balanced 11389 * misfit_task force N/A N/A N/A N/A N/A 11390 * asym_packing force force N/A N/A force force 11391 * imbalanced force force N/A N/A force force 11392 * overloaded force force N/A N/A force avg_load 11393 * 11394 * N/A : Not Applicable because already filtered while updating 11395 * statistics. 11396 * balanced : The system is balanced for these 2 groups. 11397 * force : Calculate the imbalance as load migration is probably needed. 11398 * avg_load : Only if imbalance is significant enough. 11399 * nr_idle : dst_cpu is not busy and the number of idle CPUs is quite 11400 * different in groups. 11401 */ 11402 11403 /** 11404 * sched_balance_find_src_group - Returns the busiest group within the sched_domain 11405 * if there is an imbalance. 11406 * @env: The load balancing environment. 11407 * 11408 * Also calculates the amount of runnable load which should be moved 11409 * to restore balance. 11410 * 11411 * Return: - The busiest group if imbalance exists. 11412 */ 11413 static struct sched_group *sched_balance_find_src_group(struct lb_env *env) 11414 { 11415 struct sg_lb_stats *local, *busiest; 11416 struct sd_lb_stats sds; 11417 11418 init_sd_lb_stats(&sds); 11419 11420 /* 11421 * Compute the various statistics relevant for load balancing at 11422 * this level. 11423 */ 11424 update_sd_lb_stats(env, &sds); 11425 11426 /* There is no busy sibling group to pull tasks from */ 11427 if (!sds.busiest) 11428 goto out_balanced; 11429 11430 busiest = &sds.busiest_stat; 11431 11432 /* Misfit tasks should be dealt with regardless of the avg load */ 11433 if (busiest->group_type == group_misfit_task) 11434 goto force_balance; 11435 11436 if (!is_rd_overutilized(env->dst_rq->rd) && 11437 rcu_dereference_all(env->dst_rq->rd->pd)) 11438 goto out_balanced; 11439 11440 /* ASYM feature bypasses nice load balance check */ 11441 if (busiest->group_type == group_asym_packing) 11442 goto force_balance; 11443 11444 /* 11445 * If the busiest group is imbalanced the below checks don't 11446 * work because they assume all things are equal, which typically 11447 * isn't true due to cpus_ptr constraints and the like. 11448 */ 11449 if (busiest->group_type == group_imbalanced) 11450 goto force_balance; 11451 11452 local = &sds.local_stat; 11453 /* 11454 * If the local group is busier than the selected busiest group 11455 * don't try and pull any tasks. 11456 */ 11457 if (local->group_type > busiest->group_type) 11458 goto out_balanced; 11459 11460 /* 11461 * When groups are overloaded, use the avg_load to ensure fairness 11462 * between tasks. 11463 */ 11464 if (local->group_type == group_overloaded) { 11465 /* 11466 * If the local group is more loaded than the selected 11467 * busiest group don't try to pull any tasks. 11468 */ 11469 if (local->avg_load >= busiest->avg_load) 11470 goto out_balanced; 11471 11472 /* XXX broken for overlapping NUMA groups */ 11473 sds.avg_load = (sds.total_load * SCHED_CAPACITY_SCALE) / 11474 sds.total_capacity; 11475 11476 /* 11477 * Don't pull any tasks if this group is already above the 11478 * domain average load. 11479 */ 11480 if (local->avg_load >= sds.avg_load) 11481 goto out_balanced; 11482 11483 /* 11484 * If the busiest group is more loaded, use imbalance_pct to be 11485 * conservative. 11486 */ 11487 if (100 * busiest->avg_load <= 11488 env->sd->imbalance_pct * local->avg_load) 11489 goto out_balanced; 11490 } 11491 11492 /* 11493 * Try to move all excess tasks to a sibling domain of the busiest 11494 * group's child domain. 11495 */ 11496 if (sds.prefer_sibling && local->group_type == group_has_spare && 11497 sibling_imbalance(env, &sds, busiest, local) > 1) 11498 goto force_balance; 11499 11500 if (busiest->group_type != group_overloaded) { 11501 if (!env->idle) { 11502 /* 11503 * If the busiest group is not overloaded (and as a 11504 * result the local one too) but this CPU is already 11505 * busy, let another idle CPU try to pull task. 11506 */ 11507 goto out_balanced; 11508 } 11509 11510 if (busiest->group_type == group_smt_balance && 11511 smt_vs_nonsmt_groups(sds.local, sds.busiest)) { 11512 /* Let non SMT CPU pull from SMT CPU sharing with sibling */ 11513 goto force_balance; 11514 } 11515 11516 if (busiest->group_weight > 1 && 11517 local->idle_cpus <= (busiest->idle_cpus + 1)) { 11518 /* 11519 * If the busiest group is not overloaded 11520 * and there is no imbalance between this and busiest 11521 * group wrt idle CPUs, it is balanced. The imbalance 11522 * becomes significant if the diff is greater than 1 11523 * otherwise we might end up to just move the imbalance 11524 * on another group. Of course this applies only if 11525 * there is more than 1 CPU per group. 11526 */ 11527 goto out_balanced; 11528 } 11529 11530 if (busiest->sum_h_nr_running == 1) { 11531 /* 11532 * busiest doesn't have any tasks waiting to run 11533 */ 11534 goto out_balanced; 11535 } 11536 } 11537 11538 force_balance: 11539 /* Looks like there is an imbalance. Compute it */ 11540 calculate_imbalance(env, &sds); 11541 return env->imbalance ? sds.busiest : NULL; 11542 11543 out_balanced: 11544 env->imbalance = 0; 11545 return NULL; 11546 } 11547 11548 /* 11549 * sched_balance_find_src_rq - find the busiest runqueue among the CPUs in the group. 11550 */ 11551 static struct rq *sched_balance_find_src_rq(struct lb_env *env, 11552 struct sched_group *group) 11553 { 11554 struct rq *busiest = NULL, *rq; 11555 unsigned long busiest_util = 0, busiest_load = 0, busiest_capacity = 1; 11556 unsigned int busiest_nr = 0; 11557 int i; 11558 11559 for_each_cpu_and(i, sched_group_span(group), env->cpus) { 11560 unsigned long capacity, load, util; 11561 unsigned int nr_running; 11562 enum fbq_type rt; 11563 11564 rq = cpu_rq(i); 11565 rt = fbq_classify_rq(rq); 11566 11567 /* 11568 * We classify groups/runqueues into three groups: 11569 * - regular: there are !numa tasks 11570 * - remote: there are numa tasks that run on the 'wrong' node 11571 * - all: there is no distinction 11572 * 11573 * In order to avoid migrating ideally placed numa tasks, 11574 * ignore those when there's better options. 11575 * 11576 * If we ignore the actual busiest queue to migrate another 11577 * task, the next balance pass can still reduce the busiest 11578 * queue by moving tasks around inside the node. 11579 * 11580 * If we cannot move enough load due to this classification 11581 * the next pass will adjust the group classification and 11582 * allow migration of more tasks. 11583 * 11584 * Both cases only affect the total convergence complexity. 11585 */ 11586 if (rt > env->fbq_type) 11587 continue; 11588 11589 nr_running = rq->cfs.h_nr_runnable; 11590 if (!nr_running) 11591 continue; 11592 11593 capacity = capacity_of(i); 11594 11595 /* 11596 * For ASYM_CPUCAPACITY domains, don't pick a CPU that could 11597 * eventually lead to active_balancing high->low capacity. 11598 * Higher per-CPU capacity is considered better than balancing 11599 * average load. 11600 */ 11601 if (env->sd->flags & SD_ASYM_CPUCAPACITY && 11602 !capacity_greater(capacity_of(env->dst_cpu), capacity) && 11603 nr_running == 1) 11604 continue; 11605 11606 /* 11607 * Make sure we only pull tasks from a CPU of lower priority 11608 * when balancing between SMT siblings. 11609 * 11610 * If balancing between cores, let lower priority CPUs help 11611 * SMT cores with more than one busy sibling. 11612 */ 11613 if (sched_asym(env->sd, i, env->dst_cpu) && nr_running == 1) 11614 continue; 11615 11616 switch (env->migration_type) { 11617 case migrate_load: 11618 /* 11619 * When comparing with load imbalance, use cpu_load() 11620 * which is not scaled with the CPU capacity. 11621 */ 11622 load = cpu_load(rq); 11623 11624 if (nr_running == 1 && load > env->imbalance && 11625 !check_cpu_capacity(rq, env->sd)) 11626 break; 11627 11628 /* 11629 * For the load comparisons with the other CPUs, 11630 * consider the cpu_load() scaled with the CPU 11631 * capacity, so that the load can be moved away 11632 * from the CPU that is potentially running at a 11633 * lower capacity. 11634 * 11635 * Thus we're looking for max(load_i / capacity_i), 11636 * crosswise multiplication to rid ourselves of the 11637 * division works out to: 11638 * load_i * capacity_j > load_j * capacity_i; 11639 * where j is our previous maximum. 11640 */ 11641 if (load * busiest_capacity > busiest_load * capacity) { 11642 busiest_load = load; 11643 busiest_capacity = capacity; 11644 busiest = rq; 11645 } 11646 break; 11647 11648 case migrate_util: 11649 util = cpu_util_cfs_boost(i); 11650 11651 /* 11652 * Don't try to pull utilization from a CPU with one 11653 * running task. Whatever its utilization, we will fail 11654 * detach the task. 11655 */ 11656 if (nr_running <= 1) 11657 continue; 11658 11659 if (busiest_util < util) { 11660 busiest_util = util; 11661 busiest = rq; 11662 } 11663 break; 11664 11665 case migrate_task: 11666 if (busiest_nr < nr_running) { 11667 busiest_nr = nr_running; 11668 busiest = rq; 11669 } 11670 break; 11671 11672 case migrate_misfit: 11673 /* 11674 * For ASYM_CPUCAPACITY domains with misfit tasks we 11675 * simply seek the "biggest" misfit task. 11676 */ 11677 if (rq->misfit_task_load > busiest_load) { 11678 busiest_load = rq->misfit_task_load; 11679 busiest = rq; 11680 } 11681 11682 break; 11683 11684 } 11685 } 11686 11687 return busiest; 11688 } 11689 11690 /* 11691 * Max backoff if we encounter pinned tasks. Pretty arbitrary value, but 11692 * so long as it is large enough. 11693 */ 11694 #define MAX_PINNED_INTERVAL 512 11695 11696 static inline bool 11697 asym_active_balance(struct lb_env *env) 11698 { 11699 /* 11700 * ASYM_PACKING needs to force migrate tasks from busy but lower 11701 * priority CPUs in order to pack all tasks in the highest priority 11702 * CPUs. When done between cores, do it only if the whole core if the 11703 * whole core is idle. 11704 * 11705 * If @env::src_cpu is an SMT core with busy siblings, let 11706 * the lower priority @env::dst_cpu help it. Do not follow 11707 * CPU priority. 11708 */ 11709 return env->idle && sched_use_asym_prio(env->sd, env->dst_cpu) && 11710 (sched_asym_prefer(env->dst_cpu, env->src_cpu) || 11711 !sched_use_asym_prio(env->sd, env->src_cpu)); 11712 } 11713 11714 static inline bool 11715 imbalanced_active_balance(struct lb_env *env) 11716 { 11717 struct sched_domain *sd = env->sd; 11718 11719 /* 11720 * The imbalanced case includes the case of pinned tasks preventing a fair 11721 * distribution of the load on the system but also the even distribution of the 11722 * threads on a system with spare capacity 11723 */ 11724 if ((env->migration_type == migrate_task) && 11725 (sd->nr_balance_failed > sd->cache_nice_tries+2)) 11726 return 1; 11727 11728 return 0; 11729 } 11730 11731 static int need_active_balance(struct lb_env *env) 11732 { 11733 struct sched_domain *sd = env->sd; 11734 11735 if (asym_active_balance(env)) 11736 return 1; 11737 11738 if (imbalanced_active_balance(env)) 11739 return 1; 11740 11741 /* 11742 * The dst_cpu is idle and the src_cpu CPU has only 1 CFS task. 11743 * It's worth migrating the task if the src_cpu's capacity is reduced 11744 * because of other sched_class or IRQs if more capacity stays 11745 * available on dst_cpu. 11746 */ 11747 if (env->idle && 11748 (env->src_rq->cfs.h_nr_runnable == 1)) { 11749 if ((check_cpu_capacity(env->src_rq, sd)) && 11750 (capacity_of(env->src_cpu)*sd->imbalance_pct < capacity_of(env->dst_cpu)*100)) 11751 return 1; 11752 } 11753 11754 if (env->migration_type == migrate_misfit) 11755 return 1; 11756 11757 return 0; 11758 } 11759 11760 static int active_load_balance_cpu_stop(void *data); 11761 11762 static int should_we_balance(struct lb_env *env) 11763 { 11764 struct cpumask *swb_cpus = this_cpu_cpumask_var_ptr(should_we_balance_tmpmask); 11765 struct sched_group *sg = env->sd->groups; 11766 int cpu, idle_smt = -1; 11767 11768 /* 11769 * Ensure the balancing environment is consistent; can happen 11770 * when the softirq triggers 'during' hotplug. 11771 */ 11772 if (!cpumask_test_cpu(env->dst_cpu, env->cpus)) 11773 return 0; 11774 11775 /* 11776 * In the newly idle case, we will allow all the CPUs 11777 * to do the newly idle load balance. 11778 * 11779 * However, we bail out if we already have tasks or a wakeup pending, 11780 * to optimize wakeup latency. 11781 */ 11782 if (env->idle == CPU_NEWLY_IDLE) { 11783 if (env->dst_rq->nr_running > 0 || env->dst_rq->ttwu_pending) 11784 return 0; 11785 return 1; 11786 } 11787 11788 cpumask_copy(swb_cpus, group_balance_mask(sg)); 11789 /* Try to find first idle CPU */ 11790 for_each_cpu_and(cpu, swb_cpus, env->cpus) { 11791 if (!idle_cpu(cpu)) 11792 continue; 11793 11794 /* 11795 * Don't balance to idle SMT in busy core right away when 11796 * balancing cores, but remember the first idle SMT CPU for 11797 * later consideration. Find CPU on an idle core first. 11798 */ 11799 if (!(env->sd->flags & SD_SHARE_CPUCAPACITY) && !is_core_idle(cpu)) { 11800 if (idle_smt == -1) 11801 idle_smt = cpu; 11802 /* 11803 * If the core is not idle, and first SMT sibling which is 11804 * idle has been found, then its not needed to check other 11805 * SMT siblings for idleness: 11806 */ 11807 #ifdef CONFIG_SCHED_SMT 11808 cpumask_andnot(swb_cpus, swb_cpus, cpu_smt_mask(cpu)); 11809 #endif 11810 continue; 11811 } 11812 11813 /* 11814 * Are we the first idle core in a non-SMT domain or higher, 11815 * or the first idle CPU in a SMT domain? 11816 */ 11817 return cpu == env->dst_cpu; 11818 } 11819 11820 /* Are we the first idle CPU with busy siblings? */ 11821 if (idle_smt != -1) 11822 return idle_smt == env->dst_cpu; 11823 11824 /* Are we the first CPU of this group ? */ 11825 return group_balance_cpu(sg) == env->dst_cpu; 11826 } 11827 11828 static void update_lb_imbalance_stat(struct lb_env *env, struct sched_domain *sd, 11829 enum cpu_idle_type idle) 11830 { 11831 if (!schedstat_enabled()) 11832 return; 11833 11834 switch (env->migration_type) { 11835 case migrate_load: 11836 __schedstat_add(sd->lb_imbalance_load[idle], env->imbalance); 11837 break; 11838 case migrate_util: 11839 __schedstat_add(sd->lb_imbalance_util[idle], env->imbalance); 11840 break; 11841 case migrate_task: 11842 __schedstat_add(sd->lb_imbalance_task[idle], env->imbalance); 11843 break; 11844 case migrate_misfit: 11845 __schedstat_add(sd->lb_imbalance_misfit[idle], env->imbalance); 11846 break; 11847 } 11848 } 11849 11850 /* 11851 * This flag serializes load-balancing passes over large domains 11852 * (above the NODE topology level) - only one load-balancing instance 11853 * may run at a time, to reduce overhead on very large systems with 11854 * lots of CPUs and large NUMA distances. 11855 * 11856 * - Note that load-balancing passes triggered while another one 11857 * is executing are skipped and not re-tried. 11858 * 11859 * - Also note that this does not serialize rebalance_domains() 11860 * execution, as non-SD_SERIALIZE domains will still be 11861 * load-balanced in parallel. 11862 */ 11863 static atomic_t sched_balance_running = ATOMIC_INIT(0); 11864 11865 /* 11866 * Check this_cpu to ensure it is balanced within domain. Attempt to move 11867 * tasks if there is an imbalance. 11868 */ 11869 static int sched_balance_rq(int this_cpu, struct rq *this_rq, 11870 struct sched_domain *sd, enum cpu_idle_type idle, 11871 int *continue_balancing) 11872 { 11873 int ld_moved, cur_ld_moved, active_balance = 0; 11874 struct sched_domain *sd_parent = sd->parent; 11875 struct sched_group *group; 11876 struct rq *busiest; 11877 struct rq_flags rf; 11878 struct cpumask *cpus = this_cpu_cpumask_var_ptr(load_balance_mask); 11879 struct lb_env env = { 11880 .sd = sd, 11881 .dst_cpu = this_cpu, 11882 .dst_rq = this_rq, 11883 .dst_grpmask = group_balance_mask(sd->groups), 11884 .idle = idle, 11885 .loop_break = SCHED_NR_MIGRATE_BREAK, 11886 .cpus = cpus, 11887 .fbq_type = all, 11888 .tasks = LIST_HEAD_INIT(env.tasks), 11889 }; 11890 bool need_unlock = false; 11891 11892 cpumask_and(cpus, sched_domain_span(sd), cpu_active_mask); 11893 11894 schedstat_inc(sd->lb_count[idle]); 11895 11896 redo: 11897 if (!should_we_balance(&env)) { 11898 *continue_balancing = 0; 11899 goto out_balanced; 11900 } 11901 11902 if (!need_unlock && (sd->flags & SD_SERIALIZE)) { 11903 int zero = 0; 11904 if (!atomic_try_cmpxchg_acquire(&sched_balance_running, &zero, 1)) 11905 goto out_balanced; 11906 11907 need_unlock = true; 11908 } 11909 11910 group = sched_balance_find_src_group(&env); 11911 if (!group) { 11912 schedstat_inc(sd->lb_nobusyg[idle]); 11913 goto out_balanced; 11914 } 11915 11916 busiest = sched_balance_find_src_rq(&env, group); 11917 if (!busiest) { 11918 schedstat_inc(sd->lb_nobusyq[idle]); 11919 goto out_balanced; 11920 } 11921 11922 WARN_ON_ONCE(busiest == env.dst_rq); 11923 11924 update_lb_imbalance_stat(&env, sd, idle); 11925 11926 env.src_cpu = busiest->cpu; 11927 env.src_rq = busiest; 11928 11929 ld_moved = 0; 11930 /* Clear this flag as soon as we find a pullable task */ 11931 env.flags |= LBF_ALL_PINNED; 11932 if (busiest->nr_running > 1) { 11933 /* 11934 * Attempt to move tasks. If sched_balance_find_src_group has found 11935 * an imbalance but busiest->nr_running <= 1, the group is 11936 * still unbalanced. ld_moved simply stays zero, so it is 11937 * correctly treated as an imbalance. 11938 */ 11939 env.loop_max = min(sysctl_sched_nr_migrate, busiest->nr_running); 11940 11941 more_balance: 11942 rq_lock_irqsave(busiest, &rf); 11943 update_rq_clock(busiest); 11944 11945 /* 11946 * cur_ld_moved - load moved in current iteration 11947 * ld_moved - cumulative load moved across iterations 11948 */ 11949 cur_ld_moved = detach_tasks(&env); 11950 11951 /* 11952 * We've detached some tasks from busiest_rq. Every 11953 * task is masked "TASK_ON_RQ_MIGRATING", so we can safely 11954 * unlock busiest->lock, and we are able to be sure 11955 * that nobody can manipulate the tasks in parallel. 11956 * See task_rq_lock() family for the details. 11957 */ 11958 11959 rq_unlock(busiest, &rf); 11960 11961 if (cur_ld_moved) { 11962 attach_tasks(&env); 11963 ld_moved += cur_ld_moved; 11964 } 11965 11966 local_irq_restore(rf.flags); 11967 11968 if (env.flags & LBF_NEED_BREAK) { 11969 env.flags &= ~LBF_NEED_BREAK; 11970 goto more_balance; 11971 } 11972 11973 /* 11974 * Revisit (affine) tasks on src_cpu that couldn't be moved to 11975 * us and move them to an alternate dst_cpu in our sched_group 11976 * where they can run. The upper limit on how many times we 11977 * iterate on same src_cpu is dependent on number of CPUs in our 11978 * sched_group. 11979 * 11980 * This changes load balance semantics a bit on who can move 11981 * load to a given_cpu. In addition to the given_cpu itself 11982 * (or a ilb_cpu acting on its behalf where given_cpu is 11983 * nohz-idle), we now have balance_cpu in a position to move 11984 * load to given_cpu. In rare situations, this may cause 11985 * conflicts (balance_cpu and given_cpu/ilb_cpu deciding 11986 * _independently_ and at _same_ time to move some load to 11987 * given_cpu) causing excess load to be moved to given_cpu. 11988 * This however should not happen so much in practice and 11989 * moreover subsequent load balance cycles should correct the 11990 * excess load moved. 11991 */ 11992 if ((env.flags & LBF_DST_PINNED) && env.imbalance > 0) { 11993 11994 /* Prevent to re-select dst_cpu via env's CPUs */ 11995 __cpumask_clear_cpu(env.dst_cpu, env.cpus); 11996 11997 env.dst_rq = cpu_rq(env.new_dst_cpu); 11998 env.dst_cpu = env.new_dst_cpu; 11999 env.flags &= ~LBF_DST_PINNED; 12000 env.loop = 0; 12001 env.loop_break = SCHED_NR_MIGRATE_BREAK; 12002 12003 /* 12004 * Go back to "more_balance" rather than "redo" since we 12005 * need to continue with same src_cpu. 12006 */ 12007 goto more_balance; 12008 } 12009 12010 /* 12011 * We failed to reach balance because of affinity. 12012 */ 12013 if (sd_parent) { 12014 int *group_imbalance = &sd_parent->groups->sgc->imbalance; 12015 12016 if ((env.flags & LBF_SOME_PINNED) && env.imbalance > 0) 12017 *group_imbalance = 1; 12018 } 12019 12020 /* All tasks on this runqueue were pinned by CPU affinity */ 12021 if (unlikely(env.flags & LBF_ALL_PINNED)) { 12022 __cpumask_clear_cpu(cpu_of(busiest), cpus); 12023 /* 12024 * Attempting to continue load balancing at the current 12025 * sched_domain level only makes sense if there are 12026 * active CPUs remaining as possible busiest CPUs to 12027 * pull load from which are not contained within the 12028 * destination group that is receiving any migrated 12029 * load. 12030 */ 12031 if (!cpumask_subset(cpus, env.dst_grpmask)) { 12032 env.loop = 0; 12033 env.loop_break = SCHED_NR_MIGRATE_BREAK; 12034 goto redo; 12035 } 12036 goto out_all_pinned; 12037 } 12038 } 12039 12040 if (!ld_moved) { 12041 schedstat_inc(sd->lb_failed[idle]); 12042 /* 12043 * Increment the failure counter only on periodic balance. 12044 * We do not want newidle balance, which can be very 12045 * frequent, pollute the failure counter causing 12046 * excessive cache_hot migrations and active balances. 12047 * 12048 * Similarly for migration_misfit which is not related to 12049 * load/util migration, don't pollute nr_balance_failed. 12050 */ 12051 if (idle != CPU_NEWLY_IDLE && 12052 env.migration_type != migrate_misfit) 12053 sd->nr_balance_failed++; 12054 12055 if (need_active_balance(&env)) { 12056 unsigned long flags; 12057 12058 raw_spin_rq_lock_irqsave(busiest, flags); 12059 12060 /* 12061 * Don't kick the active_load_balance_cpu_stop, 12062 * if the curr task on busiest CPU can't be 12063 * moved to this_cpu: 12064 */ 12065 if (!cpumask_test_cpu(this_cpu, busiest->curr->cpus_ptr)) { 12066 raw_spin_rq_unlock_irqrestore(busiest, flags); 12067 goto out_one_pinned; 12068 } 12069 12070 /* Record that we found at least one task that could run on this_cpu */ 12071 env.flags &= ~LBF_ALL_PINNED; 12072 12073 /* 12074 * ->active_balance synchronizes accesses to 12075 * ->active_balance_work. Once set, it's cleared 12076 * only after active load balance is finished. 12077 */ 12078 if (!busiest->active_balance) { 12079 busiest->active_balance = 1; 12080 busiest->push_cpu = this_cpu; 12081 active_balance = 1; 12082 } 12083 12084 preempt_disable(); 12085 raw_spin_rq_unlock_irqrestore(busiest, flags); 12086 if (active_balance) { 12087 stop_one_cpu_nowait(cpu_of(busiest), 12088 active_load_balance_cpu_stop, busiest, 12089 &busiest->active_balance_work); 12090 } 12091 preempt_enable(); 12092 } 12093 } else { 12094 sd->nr_balance_failed = 0; 12095 } 12096 12097 if (likely(!active_balance) || need_active_balance(&env)) { 12098 /* We were unbalanced, so reset the balancing interval */ 12099 sd->balance_interval = sd->min_interval; 12100 } 12101 12102 goto out; 12103 12104 out_balanced: 12105 /* 12106 * We reach balance although we may have faced some affinity 12107 * constraints. Clear the imbalance flag only if other tasks got 12108 * a chance to move and fix the imbalance. 12109 */ 12110 if (sd_parent && !(env.flags & LBF_ALL_PINNED)) { 12111 int *group_imbalance = &sd_parent->groups->sgc->imbalance; 12112 12113 if (*group_imbalance) 12114 *group_imbalance = 0; 12115 } 12116 12117 out_all_pinned: 12118 /* 12119 * We reach balance because all tasks are pinned at this level so 12120 * we can't migrate them. Let the imbalance flag set so parent level 12121 * can try to migrate them. 12122 */ 12123 schedstat_inc(sd->lb_balanced[idle]); 12124 12125 sd->nr_balance_failed = 0; 12126 12127 out_one_pinned: 12128 ld_moved = 0; 12129 12130 /* 12131 * sched_balance_newidle() disregards balance intervals, so we could 12132 * repeatedly reach this code, which would lead to balance_interval 12133 * skyrocketing in a short amount of time. Skip the balance_interval 12134 * increase logic to avoid that. 12135 * 12136 * Similarly misfit migration which is not necessarily an indication of 12137 * the system being busy and requires lb to backoff to let it settle 12138 * down. 12139 */ 12140 if (env.idle == CPU_NEWLY_IDLE || 12141 env.migration_type == migrate_misfit) 12142 goto out; 12143 12144 /* tune up the balancing interval */ 12145 if ((env.flags & LBF_ALL_PINNED && 12146 sd->balance_interval < MAX_PINNED_INTERVAL) || 12147 sd->balance_interval < sd->max_interval) 12148 sd->balance_interval *= 2; 12149 out: 12150 if (need_unlock) 12151 atomic_set_release(&sched_balance_running, 0); 12152 12153 return ld_moved; 12154 } 12155 12156 static inline unsigned long 12157 get_sd_balance_interval(struct sched_domain *sd, int cpu_busy) 12158 { 12159 unsigned long interval = sd->balance_interval; 12160 12161 if (cpu_busy) 12162 interval *= sd->busy_factor; 12163 12164 /* scale ms to jiffies */ 12165 interval = msecs_to_jiffies(interval); 12166 12167 /* 12168 * Reduce likelihood of busy balancing at higher domains racing with 12169 * balancing at lower domains by preventing their balancing periods 12170 * from being multiples of each other. 12171 */ 12172 if (cpu_busy) 12173 interval -= 1; 12174 12175 interval = clamp(interval, 1UL, max_load_balance_interval); 12176 12177 return interval; 12178 } 12179 12180 static inline void 12181 update_next_balance(struct sched_domain *sd, unsigned long *next_balance) 12182 { 12183 unsigned long interval, next; 12184 12185 /* used by idle balance, so cpu_busy = 0 */ 12186 interval = get_sd_balance_interval(sd, 0); 12187 next = sd->last_balance + interval; 12188 12189 if (time_after(*next_balance, next)) 12190 *next_balance = next; 12191 } 12192 12193 /* 12194 * active_load_balance_cpu_stop is run by the CPU stopper. It pushes 12195 * running tasks off the busiest CPU onto idle CPUs. It requires at 12196 * least 1 task to be running on each physical CPU where possible, and 12197 * avoids physical / logical imbalances. 12198 */ 12199 static int active_load_balance_cpu_stop(void *data) 12200 { 12201 struct rq *busiest_rq = data; 12202 int busiest_cpu = cpu_of(busiest_rq); 12203 int target_cpu = busiest_rq->push_cpu; 12204 struct rq *target_rq = cpu_rq(target_cpu); 12205 struct sched_domain *sd; 12206 struct task_struct *p = NULL; 12207 struct rq_flags rf; 12208 12209 rq_lock_irq(busiest_rq, &rf); 12210 /* 12211 * Between queueing the stop-work and running it is a hole in which 12212 * CPUs can become inactive. We should not move tasks from or to 12213 * inactive CPUs. 12214 */ 12215 if (!cpu_active(busiest_cpu) || !cpu_active(target_cpu)) 12216 goto out_unlock; 12217 12218 /* Make sure the requested CPU hasn't gone down in the meantime: */ 12219 if (unlikely(busiest_cpu != smp_processor_id() || 12220 !busiest_rq->active_balance)) 12221 goto out_unlock; 12222 12223 /* Is there any task to move? */ 12224 if (busiest_rq->nr_running <= 1) 12225 goto out_unlock; 12226 12227 /* 12228 * This condition is "impossible", if it occurs 12229 * we need to fix it. Originally reported by 12230 * Bjorn Helgaas on a 128-CPU setup. 12231 */ 12232 WARN_ON_ONCE(busiest_rq == target_rq); 12233 12234 /* Search for an sd spanning us and the target CPU. */ 12235 rcu_read_lock(); 12236 for_each_domain(target_cpu, sd) { 12237 if (cpumask_test_cpu(busiest_cpu, sched_domain_span(sd))) 12238 break; 12239 } 12240 12241 if (likely(sd)) { 12242 struct lb_env env = { 12243 .sd = sd, 12244 .dst_cpu = target_cpu, 12245 .dst_rq = target_rq, 12246 .src_cpu = busiest_rq->cpu, 12247 .src_rq = busiest_rq, 12248 .idle = CPU_IDLE, 12249 .flags = LBF_ACTIVE_LB, 12250 }; 12251 12252 schedstat_inc(sd->alb_count); 12253 update_rq_clock(busiest_rq); 12254 12255 p = detach_one_task(&env); 12256 if (p) { 12257 schedstat_inc(sd->alb_pushed); 12258 /* Active balancing done, reset the failure counter. */ 12259 sd->nr_balance_failed = 0; 12260 } else { 12261 schedstat_inc(sd->alb_failed); 12262 } 12263 } 12264 rcu_read_unlock(); 12265 out_unlock: 12266 busiest_rq->active_balance = 0; 12267 rq_unlock(busiest_rq, &rf); 12268 12269 if (p) 12270 attach_one_task(target_rq, p); 12271 12272 local_irq_enable(); 12273 12274 return 0; 12275 } 12276 12277 /* 12278 * Scale the max sched_balance_rq interval with the number of CPUs in the system. 12279 * This trades load-balance latency on larger machines for less cross talk. 12280 */ 12281 void update_max_interval(void) 12282 { 12283 max_load_balance_interval = HZ*num_online_cpus()/10; 12284 } 12285 12286 static inline void update_newidle_stats(struct sched_domain *sd, unsigned int success) 12287 { 12288 sd->newidle_call++; 12289 sd->newidle_success += success; 12290 12291 if (sd->newidle_call >= 1024) { 12292 sd->newidle_ratio = sd->newidle_success; 12293 sd->newidle_call /= 2; 12294 sd->newidle_success /= 2; 12295 } 12296 } 12297 12298 static inline bool 12299 update_newidle_cost(struct sched_domain *sd, u64 cost, unsigned int success) 12300 { 12301 unsigned long next_decay = sd->last_decay_max_lb_cost + HZ; 12302 unsigned long now = jiffies; 12303 12304 if (cost) 12305 update_newidle_stats(sd, success); 12306 12307 if (cost > sd->max_newidle_lb_cost) { 12308 /* 12309 * Track max cost of a domain to make sure to not delay the 12310 * next wakeup on the CPU. 12311 */ 12312 sd->max_newidle_lb_cost = cost; 12313 sd->last_decay_max_lb_cost = now; 12314 12315 } else if (time_after(now, next_decay)) { 12316 /* 12317 * Decay the newidle max times by ~1% per second to ensure that 12318 * it is not outdated and the current max cost is actually 12319 * shorter. 12320 */ 12321 sd->max_newidle_lb_cost = (sd->max_newidle_lb_cost * 253) / 256; 12322 sd->last_decay_max_lb_cost = now; 12323 return true; 12324 } 12325 12326 return false; 12327 } 12328 12329 /* 12330 * It checks each scheduling domain to see if it is due to be balanced, 12331 * and initiates a balancing operation if so. 12332 * 12333 * Balancing parameters are set up in init_sched_domains. 12334 */ 12335 static void sched_balance_domains(struct rq *rq, enum cpu_idle_type idle) 12336 { 12337 int continue_balancing = 1; 12338 int cpu = rq->cpu; 12339 int busy = idle != CPU_IDLE && !sched_idle_cpu(cpu); 12340 unsigned long interval; 12341 struct sched_domain *sd; 12342 /* Earliest time when we have to do rebalance again */ 12343 unsigned long next_balance = jiffies + 60*HZ; 12344 int update_next_balance = 0; 12345 int need_decay = 0; 12346 u64 max_cost = 0; 12347 12348 rcu_read_lock(); 12349 for_each_domain(cpu, sd) { 12350 /* 12351 * Decay the newidle max times here because this is a regular 12352 * visit to all the domains. 12353 */ 12354 need_decay = update_newidle_cost(sd, 0, 0); 12355 max_cost += sd->max_newidle_lb_cost; 12356 12357 /* 12358 * Stop the load balance at this level. There is another 12359 * CPU in our sched group which is doing load balancing more 12360 * actively. 12361 */ 12362 if (!continue_balancing) { 12363 if (need_decay) 12364 continue; 12365 break; 12366 } 12367 12368 interval = get_sd_balance_interval(sd, busy); 12369 if (time_after_eq(jiffies, sd->last_balance + interval)) { 12370 if (sched_balance_rq(cpu, rq, sd, idle, &continue_balancing)) { 12371 /* 12372 * The LBF_DST_PINNED logic could have changed 12373 * env->dst_cpu, so we can't know our idle 12374 * state even if we migrated tasks. Update it. 12375 */ 12376 idle = idle_cpu(cpu); 12377 busy = !idle && !sched_idle_cpu(cpu); 12378 } 12379 sd->last_balance = jiffies; 12380 interval = get_sd_balance_interval(sd, busy); 12381 } 12382 if (time_after(next_balance, sd->last_balance + interval)) { 12383 next_balance = sd->last_balance + interval; 12384 update_next_balance = 1; 12385 } 12386 } 12387 if (need_decay) { 12388 /* 12389 * Ensure the rq-wide value also decays but keep it at a 12390 * reasonable floor to avoid funnies with rq->avg_idle. 12391 */ 12392 rq->max_idle_balance_cost = 12393 max((u64)sysctl_sched_migration_cost, max_cost); 12394 } 12395 rcu_read_unlock(); 12396 12397 /* 12398 * next_balance will be updated only when there is a need. 12399 * When the cpu is attached to null domain for ex, it will not be 12400 * updated. 12401 */ 12402 if (likely(update_next_balance)) 12403 rq->next_balance = next_balance; 12404 12405 } 12406 12407 static inline int on_null_domain(struct rq *rq) 12408 { 12409 return unlikely(!rcu_dereference_sched(rq->sd)); 12410 } 12411 12412 #ifdef CONFIG_NO_HZ_COMMON 12413 /* 12414 * NOHZ idle load balancing (ILB) details: 12415 * 12416 * - When one of the busy CPUs notices that there may be an idle rebalancing 12417 * needed, they will kick the idle load balancer, which then does idle 12418 * load balancing for all the idle CPUs. 12419 */ 12420 static inline int find_new_ilb(void) 12421 { 12422 const struct cpumask *hk_mask; 12423 int ilb_cpu; 12424 12425 hk_mask = housekeeping_cpumask(HK_TYPE_KERNEL_NOISE); 12426 12427 for_each_cpu_and(ilb_cpu, nohz.idle_cpus_mask, hk_mask) { 12428 12429 if (ilb_cpu == smp_processor_id()) 12430 continue; 12431 12432 if (idle_cpu(ilb_cpu)) 12433 return ilb_cpu; 12434 } 12435 12436 return -1; 12437 } 12438 12439 /* 12440 * Kick a CPU to do the NOHZ balancing, if it is time for it, via a cross-CPU 12441 * SMP function call (IPI). 12442 * 12443 * We pick the first idle CPU in the HK_TYPE_KERNEL_NOISE housekeeping set 12444 * (if there is one). 12445 */ 12446 static void kick_ilb(unsigned int flags) 12447 { 12448 int ilb_cpu; 12449 12450 /* 12451 * Increase nohz.next_balance only when if full ilb is triggered but 12452 * not if we only update stats. 12453 */ 12454 if (flags & NOHZ_BALANCE_KICK) 12455 nohz.next_balance = jiffies+1; 12456 12457 ilb_cpu = find_new_ilb(); 12458 if (ilb_cpu < 0) 12459 return; 12460 12461 /* 12462 * Don't bother if no new NOHZ balance work items for ilb_cpu, 12463 * i.e. all bits in flags are already set in ilb_cpu. 12464 */ 12465 if ((atomic_read(nohz_flags(ilb_cpu)) & flags) == flags) 12466 return; 12467 12468 /* 12469 * Access to rq::nohz_csd is serialized by NOHZ_KICK_MASK; he who sets 12470 * the first flag owns it; cleared by nohz_csd_func(). 12471 */ 12472 flags = atomic_fetch_or(flags, nohz_flags(ilb_cpu)); 12473 if (flags & NOHZ_KICK_MASK) 12474 return; 12475 12476 /* 12477 * This way we generate an IPI on the target CPU which 12478 * is idle, and the softirq performing NOHZ idle load balancing 12479 * will be run before returning from the IPI. 12480 */ 12481 smp_call_function_single_async(ilb_cpu, &cpu_rq(ilb_cpu)->nohz_csd); 12482 } 12483 12484 /* 12485 * Current decision point for kicking the idle load balancer in the presence 12486 * of idle CPUs in the system. 12487 */ 12488 static void nohz_balancer_kick(struct rq *rq) 12489 { 12490 unsigned long now = jiffies; 12491 struct sched_domain_shared *sds; 12492 struct sched_domain *sd; 12493 int nr_busy, i, cpu = rq->cpu; 12494 unsigned int flags = 0; 12495 12496 if (unlikely(rq->idle_balance)) 12497 return; 12498 12499 /* 12500 * We may be recently in ticked or tickless idle mode. At the first 12501 * busy tick after returning from idle, we will update the busy stats. 12502 */ 12503 nohz_balance_exit_idle(rq); 12504 12505 if (READ_ONCE(nohz.has_blocked_load) && 12506 time_after(now, READ_ONCE(nohz.next_blocked))) 12507 flags = NOHZ_STATS_KICK; 12508 12509 /* 12510 * Most of the time system is not 100% busy. i.e nohz.nr_cpus > 0 12511 * Skip the read if time is not due. 12512 * 12513 * If none are in tickless mode, there maybe a narrow window 12514 * (28 jiffies, HZ=1000) where flags maybe set and kick_ilb called. 12515 * But idle load balancing is not done as find_new_ilb fails. 12516 * That's very rare. So read nohz.nr_cpus only if time is due. 12517 */ 12518 if (time_before(now, nohz.next_balance)) 12519 goto out; 12520 12521 /* 12522 * None are in tickless mode and hence no need for NOHZ idle load 12523 * balancing 12524 */ 12525 if (unlikely(cpumask_empty(nohz.idle_cpus_mask))) 12526 return; 12527 12528 if (rq->nr_running >= 2) { 12529 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 12530 goto out; 12531 } 12532 12533 rcu_read_lock(); 12534 12535 sd = rcu_dereference_all(rq->sd); 12536 if (sd) { 12537 /* 12538 * If there's a runnable CFS task and the current CPU has reduced 12539 * capacity, kick the ILB to see if there's a better CPU to run on: 12540 */ 12541 if (rq->cfs.h_nr_runnable >= 1 && check_cpu_capacity(rq, sd)) { 12542 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 12543 goto unlock; 12544 } 12545 } 12546 12547 sd = rcu_dereference_all(per_cpu(sd_asym_packing, cpu)); 12548 if (sd) { 12549 /* 12550 * When ASYM_PACKING; see if there's a more preferred CPU 12551 * currently idle; in which case, kick the ILB to move tasks 12552 * around. 12553 * 12554 * When balancing between cores, all the SMT siblings of the 12555 * preferred CPU must be idle. 12556 */ 12557 for_each_cpu_and(i, sched_domain_span(sd), nohz.idle_cpus_mask) { 12558 if (sched_asym(sd, i, cpu)) { 12559 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 12560 goto unlock; 12561 } 12562 } 12563 } 12564 12565 sd = rcu_dereference_all(per_cpu(sd_asym_cpucapacity, cpu)); 12566 if (sd) { 12567 /* 12568 * When ASYM_CPUCAPACITY; see if there's a higher capacity CPU 12569 * to run the misfit task on. 12570 */ 12571 if (check_misfit_status(rq)) { 12572 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 12573 goto unlock; 12574 } 12575 12576 /* 12577 * For asymmetric systems, we do not want to nicely balance 12578 * cache use, instead we want to embrace asymmetry and only 12579 * ensure tasks have enough CPU capacity. 12580 * 12581 * Skip the LLC logic because it's not relevant in that case. 12582 */ 12583 goto unlock; 12584 } 12585 12586 sds = rcu_dereference_all(per_cpu(sd_llc_shared, cpu)); 12587 if (sds) { 12588 /* 12589 * If there is an imbalance between LLC domains (IOW we could 12590 * increase the overall cache utilization), we need a less-loaded LLC 12591 * domain to pull some load from. Likewise, we may need to spread 12592 * load within the current LLC domain (e.g. packed SMT cores but 12593 * other CPUs are idle). We can't really know from here how busy 12594 * the others are - so just get a NOHZ balance going if it looks 12595 * like this LLC domain has tasks we could move. 12596 */ 12597 nr_busy = atomic_read(&sds->nr_busy_cpus); 12598 if (nr_busy > 1) { 12599 flags = NOHZ_STATS_KICK | NOHZ_BALANCE_KICK; 12600 goto unlock; 12601 } 12602 } 12603 unlock: 12604 rcu_read_unlock(); 12605 out: 12606 if (READ_ONCE(nohz.needs_update)) 12607 flags |= NOHZ_NEXT_KICK; 12608 12609 if (flags) 12610 kick_ilb(flags); 12611 } 12612 12613 static void set_cpu_sd_state_busy(int cpu) 12614 { 12615 struct sched_domain *sd; 12616 12617 rcu_read_lock(); 12618 sd = rcu_dereference_all(per_cpu(sd_llc, cpu)); 12619 12620 if (!sd || !sd->nohz_idle) 12621 goto unlock; 12622 sd->nohz_idle = 0; 12623 12624 atomic_inc(&sd->shared->nr_busy_cpus); 12625 unlock: 12626 rcu_read_unlock(); 12627 } 12628 12629 void nohz_balance_exit_idle(struct rq *rq) 12630 { 12631 WARN_ON_ONCE(rq != this_rq()); 12632 12633 if (likely(!rq->nohz_tick_stopped)) 12634 return; 12635 12636 rq->nohz_tick_stopped = 0; 12637 cpumask_clear_cpu(rq->cpu, nohz.idle_cpus_mask); 12638 12639 set_cpu_sd_state_busy(rq->cpu); 12640 } 12641 12642 static void set_cpu_sd_state_idle(int cpu) 12643 { 12644 struct sched_domain *sd; 12645 12646 rcu_read_lock(); 12647 sd = rcu_dereference_all(per_cpu(sd_llc, cpu)); 12648 12649 if (!sd || sd->nohz_idle) 12650 goto unlock; 12651 sd->nohz_idle = 1; 12652 12653 atomic_dec(&sd->shared->nr_busy_cpus); 12654 unlock: 12655 rcu_read_unlock(); 12656 } 12657 12658 /* 12659 * This routine will record that the CPU is going idle with tick stopped. 12660 * This info will be used in performing idle load balancing in the future. 12661 */ 12662 void nohz_balance_enter_idle(int cpu) 12663 { 12664 struct rq *rq = cpu_rq(cpu); 12665 12666 WARN_ON_ONCE(cpu != smp_processor_id()); 12667 12668 /* If this CPU is going down, then nothing needs to be done: */ 12669 if (!cpu_active(cpu)) 12670 return; 12671 12672 /* 12673 * Can be set safely without rq->lock held 12674 * If a clear happens, it will have evaluated last additions because 12675 * rq->lock is held during the check and the clear 12676 */ 12677 rq->has_blocked_load = 1; 12678 12679 /* 12680 * The tick is still stopped but load could have been added in the 12681 * meantime. We set the nohz.has_blocked_load flag to trig a check of the 12682 * *_avg. The CPU is already part of nohz.idle_cpus_mask so the clear 12683 * of nohz.has_blocked_load can only happen after checking the new load 12684 */ 12685 if (rq->nohz_tick_stopped) 12686 goto out; 12687 12688 /* If we're a completely isolated CPU, we don't play: */ 12689 if (on_null_domain(rq)) 12690 return; 12691 12692 rq->nohz_tick_stopped = 1; 12693 12694 cpumask_set_cpu(cpu, nohz.idle_cpus_mask); 12695 12696 /* 12697 * Ensures that if nohz_idle_balance() fails to observe our 12698 * @idle_cpus_mask store, it must observe the @has_blocked_load 12699 * and @needs_update stores. 12700 */ 12701 smp_mb__after_atomic(); 12702 12703 set_cpu_sd_state_idle(cpu); 12704 12705 WRITE_ONCE(nohz.needs_update, 1); 12706 out: 12707 /* 12708 * Each time a cpu enter idle, we assume that it has blocked load and 12709 * enable the periodic update of the load of idle CPUs 12710 */ 12711 WRITE_ONCE(nohz.has_blocked_load, 1); 12712 } 12713 12714 static bool update_nohz_stats(struct rq *rq) 12715 { 12716 unsigned int cpu = rq->cpu; 12717 12718 if (!rq->has_blocked_load) 12719 return false; 12720 12721 if (!cpumask_test_cpu(cpu, nohz.idle_cpus_mask)) 12722 return false; 12723 12724 if (!time_after(jiffies, READ_ONCE(rq->last_blocked_load_update_tick))) 12725 return true; 12726 12727 sched_balance_update_blocked_averages(cpu); 12728 12729 return rq->has_blocked_load; 12730 } 12731 12732 /* 12733 * Internal function that runs load balance for all idle CPUs. The load balance 12734 * can be a simple update of blocked load or a complete load balance with 12735 * tasks movement depending of flags. 12736 */ 12737 static void _nohz_idle_balance(struct rq *this_rq, unsigned int flags) 12738 { 12739 /* Earliest time when we have to do rebalance again */ 12740 unsigned long now = jiffies; 12741 unsigned long next_balance = now + 60*HZ; 12742 bool has_blocked_load = false; 12743 int update_next_balance = 0; 12744 int this_cpu = this_rq->cpu; 12745 int balance_cpu; 12746 struct rq *rq; 12747 12748 WARN_ON_ONCE((flags & NOHZ_KICK_MASK) == NOHZ_BALANCE_KICK); 12749 12750 /* 12751 * We assume there will be no idle load after this update and clear 12752 * the has_blocked_load flag. If a cpu enters idle in the mean time, it will 12753 * set the has_blocked_load flag and trigger another update of idle load. 12754 * Because a cpu that becomes idle, is added to idle_cpus_mask before 12755 * setting the flag, we are sure to not clear the state and not 12756 * check the load of an idle cpu. 12757 * 12758 * Same applies to idle_cpus_mask vs needs_update. 12759 */ 12760 if (flags & NOHZ_STATS_KICK) 12761 WRITE_ONCE(nohz.has_blocked_load, 0); 12762 if (flags & NOHZ_NEXT_KICK) 12763 WRITE_ONCE(nohz.needs_update, 0); 12764 12765 /* 12766 * Ensures that if we miss the CPU, we must see the has_blocked_load 12767 * store from nohz_balance_enter_idle(). 12768 */ 12769 smp_mb(); 12770 12771 /* 12772 * Start with the next CPU after this_cpu so we will end with this_cpu and let a 12773 * chance for other idle cpu to pull load. 12774 */ 12775 for_each_cpu_wrap(balance_cpu, nohz.idle_cpus_mask, this_cpu+1) { 12776 if (!idle_cpu(balance_cpu)) 12777 continue; 12778 12779 /* 12780 * If this CPU gets work to do, stop the load balancing 12781 * work being done for other CPUs. Next load 12782 * balancing owner will pick it up. 12783 */ 12784 if (!idle_cpu(this_cpu) && need_resched()) { 12785 if (flags & NOHZ_STATS_KICK) 12786 has_blocked_load = true; 12787 if (flags & NOHZ_NEXT_KICK) 12788 WRITE_ONCE(nohz.needs_update, 1); 12789 goto abort; 12790 } 12791 12792 rq = cpu_rq(balance_cpu); 12793 12794 if (flags & NOHZ_STATS_KICK) 12795 has_blocked_load |= update_nohz_stats(rq); 12796 12797 /* 12798 * If time for next balance is due, 12799 * do the balance. 12800 */ 12801 if (time_after_eq(jiffies, rq->next_balance)) { 12802 struct rq_flags rf; 12803 12804 rq_lock_irqsave(rq, &rf); 12805 update_rq_clock(rq); 12806 rq_unlock_irqrestore(rq, &rf); 12807 12808 if (flags & NOHZ_BALANCE_KICK) 12809 sched_balance_domains(rq, CPU_IDLE); 12810 } 12811 12812 if (time_after(next_balance, rq->next_balance)) { 12813 next_balance = rq->next_balance; 12814 update_next_balance = 1; 12815 } 12816 } 12817 12818 /* 12819 * next_balance will be updated only when there is a need. 12820 * When the CPU is attached to null domain for ex, it will not be 12821 * updated. 12822 */ 12823 if (likely(update_next_balance)) 12824 nohz.next_balance = next_balance; 12825 12826 if (flags & NOHZ_STATS_KICK) 12827 WRITE_ONCE(nohz.next_blocked, 12828 now + msecs_to_jiffies(LOAD_AVG_PERIOD)); 12829 12830 abort: 12831 /* There is still blocked load, enable periodic update */ 12832 if (has_blocked_load) 12833 WRITE_ONCE(nohz.has_blocked_load, 1); 12834 } 12835 12836 /* 12837 * In CONFIG_NO_HZ_COMMON case, the idle balance kickee will do the 12838 * rebalancing for all the CPUs for whom scheduler ticks are stopped. 12839 */ 12840 static bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) 12841 { 12842 unsigned int flags = this_rq->nohz_idle_balance; 12843 12844 if (!flags) 12845 return false; 12846 12847 this_rq->nohz_idle_balance = 0; 12848 12849 if (idle != CPU_IDLE) 12850 return false; 12851 12852 _nohz_idle_balance(this_rq, flags); 12853 12854 return true; 12855 } 12856 12857 /* 12858 * Check if we need to directly run the ILB for updating blocked load before 12859 * entering idle state. Here we run ILB directly without issuing IPIs. 12860 * 12861 * Note that when this function is called, the tick may not yet be stopped on 12862 * this CPU yet. nohz.idle_cpus_mask is updated only when tick is stopped and 12863 * cleared on the next busy tick. In other words, nohz.idle_cpus_mask updates 12864 * don't align with CPUs enter/exit idle to avoid bottlenecks due to high idle 12865 * entry/exit rate (usec). So it is possible that _nohz_idle_balance() is 12866 * called from this function on (this) CPU that's not yet in the mask. That's 12867 * OK because the goal of nohz_run_idle_balance() is to run ILB only for 12868 * updating the blocked load of already idle CPUs without waking up one of 12869 * those idle CPUs and outside the preempt disable / IRQ off phase of the local 12870 * cpu about to enter idle, because it can take a long time. 12871 */ 12872 void nohz_run_idle_balance(int cpu) 12873 { 12874 unsigned int flags; 12875 12876 flags = atomic_fetch_andnot(NOHZ_NEWILB_KICK, nohz_flags(cpu)); 12877 12878 /* 12879 * Update the blocked load only if no SCHED_SOFTIRQ is about to happen 12880 * (i.e. NOHZ_STATS_KICK set) and will do the same. 12881 */ 12882 if ((flags == NOHZ_NEWILB_KICK) && !need_resched()) 12883 _nohz_idle_balance(cpu_rq(cpu), NOHZ_STATS_KICK); 12884 } 12885 12886 static void nohz_newidle_balance(struct rq *this_rq) 12887 { 12888 int this_cpu = this_rq->cpu; 12889 12890 /* Will wake up very soon. No time for doing anything else*/ 12891 if (this_rq->avg_idle < sysctl_sched_migration_cost) 12892 return; 12893 12894 /* Don't need to update blocked load of idle CPUs*/ 12895 if (!READ_ONCE(nohz.has_blocked_load) || 12896 time_before(jiffies, READ_ONCE(nohz.next_blocked))) 12897 return; 12898 12899 /* 12900 * Set the need to trigger ILB in order to update blocked load 12901 * before entering idle state. 12902 */ 12903 atomic_or(NOHZ_NEWILB_KICK, nohz_flags(this_cpu)); 12904 } 12905 12906 #else /* !CONFIG_NO_HZ_COMMON: */ 12907 static inline void nohz_balancer_kick(struct rq *rq) { } 12908 12909 static inline bool nohz_idle_balance(struct rq *this_rq, enum cpu_idle_type idle) 12910 { 12911 return false; 12912 } 12913 12914 static inline void nohz_newidle_balance(struct rq *this_rq) { } 12915 #endif /* !CONFIG_NO_HZ_COMMON */ 12916 12917 /* 12918 * sched_balance_newidle is called by schedule() if this_cpu is about to become 12919 * idle. Attempts to pull tasks from other CPUs. 12920 * 12921 * Returns: 12922 * < 0 - we released the lock and there are !fair tasks present 12923 * 0 - failed, no new tasks 12924 * > 0 - success, new (fair) tasks present 12925 */ 12926 static int sched_balance_newidle(struct rq *this_rq, struct rq_flags *rf) 12927 __must_hold(__rq_lockp(this_rq)) 12928 { 12929 unsigned long next_balance = jiffies + HZ; 12930 int this_cpu = this_rq->cpu; 12931 int continue_balancing = 1; 12932 u64 t0, t1, curr_cost = 0; 12933 struct sched_domain *sd; 12934 int pulled_task = 0; 12935 12936 update_misfit_status(NULL, this_rq); 12937 12938 /* 12939 * There is a task waiting to run. No need to search for one. 12940 * Return 0; the task will be enqueued when switching to idle. 12941 */ 12942 if (this_rq->ttwu_pending) 12943 return 0; 12944 12945 /* 12946 * We must set idle_stamp _before_ calling sched_balance_rq() 12947 * for CPU_NEWLY_IDLE, such that we measure the this duration 12948 * as idle time. 12949 */ 12950 this_rq->idle_stamp = rq_clock(this_rq); 12951 12952 /* 12953 * Do not pull tasks towards !active CPUs... 12954 */ 12955 if (!cpu_active(this_cpu)) 12956 return 0; 12957 12958 /* 12959 * This is OK, because current is on_cpu, which avoids it being picked 12960 * for load-balance and preemption/IRQs are still disabled avoiding 12961 * further scheduler activity on it and we're being very careful to 12962 * re-start the picking loop. 12963 */ 12964 rq_unpin_lock(this_rq, rf); 12965 12966 sd = rcu_dereference_sched_domain(this_rq->sd); 12967 if (!sd) 12968 goto out; 12969 12970 if (!get_rd_overloaded(this_rq->rd) || 12971 this_rq->avg_idle < sd->max_newidle_lb_cost) { 12972 12973 update_next_balance(sd, &next_balance); 12974 goto out; 12975 } 12976 12977 /* 12978 * Include sched_balance_update_blocked_averages() in the cost 12979 * calculation because it can be quite costly -- this ensures we skip 12980 * it when avg_idle gets to be very low. 12981 */ 12982 t0 = sched_clock_cpu(this_cpu); 12983 __sched_balance_update_blocked_averages(this_rq); 12984 12985 rq_modified_begin(this_rq, &fair_sched_class); 12986 raw_spin_rq_unlock(this_rq); 12987 12988 for_each_domain(this_cpu, sd) { 12989 u64 domain_cost; 12990 12991 update_next_balance(sd, &next_balance); 12992 12993 if (this_rq->avg_idle < curr_cost + sd->max_newidle_lb_cost) 12994 break; 12995 12996 if (sd->flags & SD_BALANCE_NEWIDLE) { 12997 unsigned int weight = 1; 12998 12999 if (sched_feat(NI_RANDOM)) { 13000 /* 13001 * Throw a 1k sided dice; and only run 13002 * newidle_balance according to the success 13003 * rate. 13004 */ 13005 u32 d1k = sched_rng() % 1024; 13006 weight = 1 + sd->newidle_ratio; 13007 if (d1k > weight) { 13008 update_newidle_stats(sd, 0); 13009 continue; 13010 } 13011 weight = (1024 + weight/2) / weight; 13012 } 13013 13014 pulled_task = sched_balance_rq(this_cpu, this_rq, 13015 sd, CPU_NEWLY_IDLE, 13016 &continue_balancing); 13017 13018 t1 = sched_clock_cpu(this_cpu); 13019 domain_cost = t1 - t0; 13020 curr_cost += domain_cost; 13021 t0 = t1; 13022 13023 /* 13024 * Track max cost of a domain to make sure to not delay the 13025 * next wakeup on the CPU. 13026 */ 13027 update_newidle_cost(sd, domain_cost, weight * !!pulled_task); 13028 } 13029 13030 /* 13031 * Stop searching for tasks to pull if there are 13032 * now runnable tasks on this rq. 13033 */ 13034 if (pulled_task || !continue_balancing) 13035 break; 13036 } 13037 13038 raw_spin_rq_lock(this_rq); 13039 13040 if (curr_cost > this_rq->max_idle_balance_cost) 13041 this_rq->max_idle_balance_cost = curr_cost; 13042 13043 /* 13044 * While browsing the domains, we released the rq lock, a task could 13045 * have been enqueued in the meantime. Since we're not going idle, 13046 * pretend we pulled a task. 13047 */ 13048 if (this_rq->cfs.h_nr_queued && !pulled_task) 13049 pulled_task = 1; 13050 13051 /* If a higher prio class was modified, restart the pick */ 13052 if (rq_modified_above(this_rq, &fair_sched_class)) 13053 pulled_task = -1; 13054 13055 out: 13056 /* Move the next balance forward */ 13057 if (time_after(this_rq->next_balance, next_balance)) 13058 this_rq->next_balance = next_balance; 13059 13060 if (pulled_task) 13061 this_rq->idle_stamp = 0; 13062 else 13063 nohz_newidle_balance(this_rq); 13064 13065 rq_repin_lock(this_rq, rf); 13066 13067 return pulled_task; 13068 } 13069 13070 /* 13071 * This softirq handler is triggered via SCHED_SOFTIRQ from two places: 13072 * 13073 * - directly from the local sched_tick() for periodic load balancing 13074 * 13075 * - indirectly from a remote sched_tick() for NOHZ idle balancing 13076 * through the SMP cross-call nohz_csd_func() 13077 */ 13078 static __latent_entropy void sched_balance_softirq(void) 13079 { 13080 struct rq *this_rq = this_rq(); 13081 enum cpu_idle_type idle = this_rq->idle_balance; 13082 /* 13083 * If this CPU has a pending NOHZ_BALANCE_KICK, then do the 13084 * balancing on behalf of the other idle CPUs whose ticks are 13085 * stopped. Do nohz_idle_balance *before* sched_balance_domains to 13086 * give the idle CPUs a chance to load balance. Else we may 13087 * load balance only within the local sched_domain hierarchy 13088 * and abort nohz_idle_balance altogether if we pull some load. 13089 */ 13090 if (nohz_idle_balance(this_rq, idle)) 13091 return; 13092 13093 /* normal load balance */ 13094 sched_balance_update_blocked_averages(this_rq->cpu); 13095 sched_balance_domains(this_rq, idle); 13096 } 13097 13098 /* 13099 * Trigger the SCHED_SOFTIRQ if it is time to do periodic load balancing. 13100 */ 13101 void sched_balance_trigger(struct rq *rq) 13102 { 13103 /* 13104 * Don't need to rebalance while attached to NULL domain or 13105 * runqueue CPU is not active 13106 */ 13107 if (unlikely(on_null_domain(rq) || !cpu_active(cpu_of(rq)))) 13108 return; 13109 13110 if (time_after_eq(jiffies, rq->next_balance)) 13111 raise_softirq(SCHED_SOFTIRQ); 13112 13113 nohz_balancer_kick(rq); 13114 } 13115 13116 static void rq_online_fair(struct rq *rq) 13117 { 13118 update_sysctl(); 13119 13120 update_runtime_enabled(rq); 13121 } 13122 13123 static void rq_offline_fair(struct rq *rq) 13124 { 13125 update_sysctl(); 13126 13127 /* Ensure any throttled groups are reachable by pick_next_task */ 13128 unthrottle_offline_cfs_rqs(rq); 13129 13130 /* Ensure that we remove rq contribution to group share: */ 13131 clear_tg_offline_cfs_rqs(rq); 13132 } 13133 13134 #ifdef CONFIG_SCHED_CORE 13135 static inline bool 13136 __entity_slice_used(struct sched_entity *se, int min_nr_tasks) 13137 { 13138 u64 rtime = se->sum_exec_runtime - se->prev_sum_exec_runtime; 13139 u64 slice = se->slice; 13140 13141 return (rtime * min_nr_tasks > slice); 13142 } 13143 13144 #define MIN_NR_TASKS_DURING_FORCEIDLE 2 13145 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) 13146 { 13147 if (!sched_core_enabled(rq)) 13148 return; 13149 13150 /* 13151 * If runqueue has only one task which used up its slice and 13152 * if the sibling is forced idle, then trigger schedule to 13153 * give forced idle task a chance. 13154 * 13155 * sched_slice() considers only this active rq and it gets the 13156 * whole slice. But during force idle, we have siblings acting 13157 * like a single runqueue and hence we need to consider runnable 13158 * tasks on this CPU and the forced idle CPU. Ideally, we should 13159 * go through the forced idle rq, but that would be a perf hit. 13160 * We can assume that the forced idle CPU has at least 13161 * MIN_NR_TASKS_DURING_FORCEIDLE - 1 tasks and use that to check 13162 * if we need to give up the CPU. 13163 */ 13164 if (rq->core->core_forceidle_count && rq->cfs.nr_queued == 1 && 13165 __entity_slice_used(&curr->se, MIN_NR_TASKS_DURING_FORCEIDLE)) 13166 resched_curr(rq); 13167 } 13168 13169 /* 13170 * Consider any infeasible weight scenario. Take for instance two tasks, 13171 * each bound to their respective sibling, one with weight 1 and one with 13172 * weight 2. Then the lower weight task will run ahead of the higher weight 13173 * task without bound. 13174 * 13175 * This utterly destroys the concept of a shared time base. 13176 * 13177 * Remember; all this is about a proportionally fair scheduling, where each 13178 * tasks receives: 13179 * 13180 * w_i 13181 * dt_i = ---------- dt (1) 13182 * \Sum_j w_j 13183 * 13184 * which we do by tracking a virtual time, s_i: 13185 * 13186 * 1 13187 * s_i = --- d[t]_i (2) 13188 * w_i 13189 * 13190 * Where d[t] is a delta of discrete time, while dt is an infinitesimal. 13191 * The immediate corollary is that the ideal schedule S, where (2) to use 13192 * an infinitesimal delta, is: 13193 * 13194 * 1 13195 * S = ---------- dt (3) 13196 * \Sum_i w_i 13197 * 13198 * From which we can define the lag, or deviation from the ideal, as: 13199 * 13200 * lag(i) = S - s_i (4) 13201 * 13202 * And since the one and only purpose is to approximate S, we get that: 13203 * 13204 * \Sum_i w_i lag(i) := 0 (5) 13205 * 13206 * If this were not so, we no longer converge to S, and we can no longer 13207 * claim our scheduler has any of the properties we derive from S. This is 13208 * exactly what you did above, you broke it! 13209 * 13210 * 13211 * Let's continue for a while though; to see if there is anything useful to 13212 * be learned. We can combine (1)-(3) or (4)-(5) and express S in s_i: 13213 * 13214 * \Sum_i w_i s_i 13215 * S = -------------- (6) 13216 * \Sum_i w_i 13217 * 13218 * Which gives us a way to compute S, given our s_i. Now, if you've read 13219 * our code, you know that we do not in fact do this, the reason for this 13220 * is two-fold. Firstly, computing S in that way requires a 64bit division 13221 * for every time we'd use it (see 12), and secondly, this only describes 13222 * the steady-state, it doesn't handle dynamics. 13223 * 13224 * Anyway, in (6): s_i -> x + (s_i - x), to get: 13225 * 13226 * \Sum_i w_i (s_i - x) 13227 * S - x = -------------------- (7) 13228 * \Sum_i w_i 13229 * 13230 * Which shows that S and s_i transform alike (which makes perfect sense 13231 * given that S is basically the (weighted) average of s_i). 13232 * 13233 * So the thing to remember is that the above is strictly UP. It is 13234 * possible to generalize to multiple runqueues -- however it gets really 13235 * yuck when you have to add affinity support, as illustrated by our very 13236 * first counter-example. 13237 * 13238 * Luckily I think we can avoid needing a full multi-queue variant for 13239 * core-scheduling (or load-balancing). The crucial observation is that we 13240 * only actually need this comparison in the presence of forced-idle; only 13241 * then do we need to tell if the stalled rq has higher priority over the 13242 * other. 13243 * 13244 * [XXX assumes SMT2; better consider the more general case, I suspect 13245 * it'll work out because our comparison is always between 2 rqs and the 13246 * answer is only interesting if one of them is forced-idle] 13247 * 13248 * And (under assumption of SMT2) when there is forced-idle, there is only 13249 * a single queue, so everything works like normal. 13250 * 13251 * Let, for our runqueue 'k': 13252 * 13253 * T_k = \Sum_i w_i s_i 13254 * W_k = \Sum_i w_i ; for all i of k (8) 13255 * 13256 * Then we can write (6) like: 13257 * 13258 * T_k 13259 * S_k = --- (9) 13260 * W_k 13261 * 13262 * From which immediately follows that: 13263 * 13264 * T_k + T_l 13265 * S_k+l = --------- (10) 13266 * W_k + W_l 13267 * 13268 * On which we can define a combined lag: 13269 * 13270 * lag_k+l(i) := S_k+l - s_i (11) 13271 * 13272 * And that gives us the tools to compare tasks across a combined runqueue. 13273 * 13274 * 13275 * Combined this gives the following: 13276 * 13277 * a) when a runqueue enters force-idle, sync it against it's sibling rq(s) 13278 * using (7); this only requires storing single 'time'-stamps. 13279 * 13280 * b) when comparing tasks between 2 runqueues of which one is forced-idle, 13281 * compare the combined lag, per (11). 13282 * 13283 * Now, of course cgroups (I so hate them) make this more interesting in 13284 * that a) seems to suggest we need to iterate all cgroup on a CPU at such 13285 * boundaries, but I think we can avoid that. The force-idle is for the 13286 * whole CPU, all it's rqs. So we can mark it in the root and lazily 13287 * propagate downward on demand. 13288 */ 13289 13290 /* 13291 * So this sync is basically a relative reset of S to 0. 13292 * 13293 * So with 2 queues, when one goes idle, we drop them both to 0 and one 13294 * then increases due to not being idle, and the idle one builds up lag to 13295 * get re-elected. So far so simple, right? 13296 * 13297 * When there's 3, we can have the situation where 2 run and one is idle, 13298 * we sync to 0 and let the idle one build up lag to get re-election. Now 13299 * suppose another one also drops idle. At this point dropping all to 0 13300 * again would destroy the built-up lag from the queue that was already 13301 * idle, not good. 13302 * 13303 * So instead of syncing everything, we can: 13304 * 13305 * less := !((s64)(s_a - s_b) <= 0) 13306 * 13307 * (v_a - S_a) - (v_b - S_b) == v_a - v_b - S_a + S_b 13308 * == v_a - (v_b - S_a + S_b) 13309 * 13310 * IOW, we can recast the (lag) comparison to a one-sided difference. 13311 * So if then, instead of syncing the whole queue, sync the idle queue 13312 * against the active queue with S_a + S_b at the point where we sync. 13313 * 13314 * (XXX consider the implication of living in a cyclic group: N / 2^n N) 13315 * 13316 * This gives us means of syncing single queues against the active queue, 13317 * and for already idle queues to preserve their build-up lag. 13318 * 13319 * Of course, then we get the situation where there's 2 active and one 13320 * going idle, who do we pick to sync against? Theory would have us sync 13321 * against the combined S, but as we've already demonstrated, there is no 13322 * such thing in infeasible weight scenarios. 13323 * 13324 * One thing I've considered; and this is where that core_active rudiment 13325 * came from, is having active queues sync up between themselves after 13326 * every tick. This limits the observed divergence due to the work 13327 * conservancy. 13328 * 13329 * On top of that, we can improve upon things by employing (10) here. 13330 */ 13331 13332 /* 13333 * se_fi_update - Update the cfs_rq->zero_vruntime_fi in a CFS hierarchy if needed. 13334 */ 13335 static void se_fi_update(const struct sched_entity *se, unsigned int fi_seq, 13336 bool forceidle) 13337 { 13338 for_each_sched_entity(se) { 13339 struct cfs_rq *cfs_rq = cfs_rq_of(se); 13340 13341 if (forceidle) { 13342 if (cfs_rq->forceidle_seq == fi_seq) 13343 break; 13344 cfs_rq->forceidle_seq = fi_seq; 13345 } 13346 13347 cfs_rq->zero_vruntime_fi = cfs_rq->zero_vruntime; 13348 } 13349 } 13350 13351 void task_vruntime_update(struct rq *rq, struct task_struct *p, bool in_fi) 13352 { 13353 struct sched_entity *se = &p->se; 13354 13355 if (p->sched_class != &fair_sched_class) 13356 return; 13357 13358 se_fi_update(se, rq->core->core_forceidle_seq, in_fi); 13359 } 13360 13361 bool cfs_prio_less(const struct task_struct *a, const struct task_struct *b, 13362 bool in_fi) 13363 { 13364 struct rq *rq = task_rq(a); 13365 const struct sched_entity *sea = &a->se; 13366 const struct sched_entity *seb = &b->se; 13367 struct cfs_rq *cfs_rqa; 13368 struct cfs_rq *cfs_rqb; 13369 s64 delta; 13370 13371 WARN_ON_ONCE(task_rq(b)->core != rq->core); 13372 13373 #ifdef CONFIG_FAIR_GROUP_SCHED 13374 /* 13375 * Find an se in the hierarchy for tasks a and b, such that the se's 13376 * are immediate siblings. 13377 */ 13378 while (sea->cfs_rq->tg != seb->cfs_rq->tg) { 13379 int sea_depth = sea->depth; 13380 int seb_depth = seb->depth; 13381 13382 if (sea_depth >= seb_depth) 13383 sea = parent_entity(sea); 13384 if (sea_depth <= seb_depth) 13385 seb = parent_entity(seb); 13386 } 13387 13388 se_fi_update(sea, rq->core->core_forceidle_seq, in_fi); 13389 se_fi_update(seb, rq->core->core_forceidle_seq, in_fi); 13390 13391 cfs_rqa = sea->cfs_rq; 13392 cfs_rqb = seb->cfs_rq; 13393 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 13394 cfs_rqa = &task_rq(a)->cfs; 13395 cfs_rqb = &task_rq(b)->cfs; 13396 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 13397 13398 /* 13399 * Find delta after normalizing se's vruntime with its cfs_rq's 13400 * zero_vruntime_fi, which would have been updated in prior calls 13401 * to se_fi_update(). 13402 */ 13403 delta = vruntime_op(sea->vruntime, "-", seb->vruntime) + 13404 vruntime_op(cfs_rqb->zero_vruntime_fi, "-", cfs_rqa->zero_vruntime_fi); 13405 13406 return delta > 0; 13407 } 13408 13409 static int task_is_throttled_fair(struct task_struct *p, int cpu) 13410 { 13411 struct cfs_rq *cfs_rq; 13412 13413 #ifdef CONFIG_FAIR_GROUP_SCHED 13414 cfs_rq = task_group(p)->cfs_rq[cpu]; 13415 #else 13416 cfs_rq = &cpu_rq(cpu)->cfs; 13417 #endif 13418 return throttled_hierarchy(cfs_rq); 13419 } 13420 #else /* !CONFIG_SCHED_CORE: */ 13421 static inline void task_tick_core(struct rq *rq, struct task_struct *curr) {} 13422 #endif /* !CONFIG_SCHED_CORE */ 13423 13424 /* 13425 * scheduler tick hitting a task of our scheduling class. 13426 * 13427 * NOTE: This function can be called remotely by the tick offload that 13428 * goes along full dynticks. Therefore no local assumption can be made 13429 * and everything must be accessed through the @rq and @curr passed in 13430 * parameters. 13431 */ 13432 static void task_tick_fair(struct rq *rq, struct task_struct *curr, int queued) 13433 { 13434 struct cfs_rq *cfs_rq; 13435 struct sched_entity *se = &curr->se; 13436 13437 for_each_sched_entity(se) { 13438 cfs_rq = cfs_rq_of(se); 13439 entity_tick(cfs_rq, se, queued); 13440 } 13441 13442 if (queued) { 13443 if (!need_resched()) 13444 hrtick_start_fair(rq, curr); 13445 return; 13446 } 13447 13448 if (static_branch_unlikely(&sched_numa_balancing)) 13449 task_tick_numa(rq, curr); 13450 13451 update_misfit_status(curr, rq); 13452 check_update_overutilized_status(task_rq(curr)); 13453 13454 task_tick_core(rq, curr); 13455 } 13456 13457 /* 13458 * called on fork with the child task as argument from the parent's context 13459 * - child not yet on the tasklist 13460 * - preemption disabled 13461 */ 13462 static void task_fork_fair(struct task_struct *p) 13463 { 13464 set_task_max_allowed_capacity(p); 13465 } 13466 13467 /* 13468 * Priority of the task has changed. Check to see if we preempt 13469 * the current task. 13470 */ 13471 static void 13472 prio_changed_fair(struct rq *rq, struct task_struct *p, u64 oldprio) 13473 { 13474 if (!task_on_rq_queued(p)) 13475 return; 13476 13477 if (p->prio == oldprio) 13478 return; 13479 13480 if (rq->cfs.nr_queued == 1) 13481 return; 13482 13483 /* 13484 * Reschedule if we are currently running on this runqueue and 13485 * our priority decreased, or if we are not currently running on 13486 * this runqueue and our priority is higher than the current's 13487 */ 13488 if (task_current_donor(rq, p)) { 13489 if (p->prio > oldprio) 13490 resched_curr(rq); 13491 } else { 13492 wakeup_preempt(rq, p, 0); 13493 } 13494 } 13495 13496 #ifdef CONFIG_FAIR_GROUP_SCHED 13497 /* 13498 * Propagate the changes of the sched_entity across the tg tree to make it 13499 * visible to the root 13500 */ 13501 static void propagate_entity_cfs_rq(struct sched_entity *se) 13502 { 13503 struct cfs_rq *cfs_rq = cfs_rq_of(se); 13504 13505 /* 13506 * If a task gets attached to this cfs_rq and before being queued, 13507 * it gets migrated to another CPU due to reasons like affinity 13508 * change, make sure this cfs_rq stays on leaf cfs_rq list to have 13509 * that removed load decayed or it can cause faireness problem. 13510 */ 13511 if (!cfs_rq_pelt_clock_throttled(cfs_rq)) 13512 list_add_leaf_cfs_rq(cfs_rq); 13513 13514 /* Start to propagate at parent */ 13515 se = se->parent; 13516 13517 for_each_sched_entity(se) { 13518 cfs_rq = cfs_rq_of(se); 13519 13520 update_load_avg(cfs_rq, se, UPDATE_TG); 13521 13522 if (!cfs_rq_pelt_clock_throttled(cfs_rq)) 13523 list_add_leaf_cfs_rq(cfs_rq); 13524 } 13525 13526 assert_list_leaf_cfs_rq(rq_of(cfs_rq)); 13527 } 13528 #else /* !CONFIG_FAIR_GROUP_SCHED: */ 13529 static void propagate_entity_cfs_rq(struct sched_entity *se) { } 13530 #endif /* !CONFIG_FAIR_GROUP_SCHED */ 13531 13532 static void detach_entity_cfs_rq(struct sched_entity *se) 13533 { 13534 struct cfs_rq *cfs_rq = cfs_rq_of(se); 13535 13536 /* 13537 * In case the task sched_avg hasn't been attached: 13538 * - A forked task which hasn't been woken up by wake_up_new_task(). 13539 * - A task which has been woken up by try_to_wake_up() but is 13540 * waiting for actually being woken up by sched_ttwu_pending(). 13541 */ 13542 if (!se->avg.last_update_time) 13543 return; 13544 13545 /* Catch up with the cfs_rq and remove our load when we leave */ 13546 update_load_avg(cfs_rq, se, 0); 13547 detach_entity_load_avg(cfs_rq, se); 13548 update_tg_load_avg(cfs_rq); 13549 propagate_entity_cfs_rq(se); 13550 } 13551 13552 static void attach_entity_cfs_rq(struct sched_entity *se) 13553 { 13554 struct cfs_rq *cfs_rq = cfs_rq_of(se); 13555 13556 /* Synchronize entity with its cfs_rq */ 13557 update_load_avg(cfs_rq, se, sched_feat(ATTACH_AGE_LOAD) ? 0 : SKIP_AGE_LOAD); 13558 attach_entity_load_avg(cfs_rq, se); 13559 update_tg_load_avg(cfs_rq); 13560 propagate_entity_cfs_rq(se); 13561 } 13562 13563 static void detach_task_cfs_rq(struct task_struct *p) 13564 { 13565 struct sched_entity *se = &p->se; 13566 13567 detach_entity_cfs_rq(se); 13568 } 13569 13570 static void attach_task_cfs_rq(struct task_struct *p) 13571 { 13572 struct sched_entity *se = &p->se; 13573 13574 attach_entity_cfs_rq(se); 13575 } 13576 13577 static void switching_from_fair(struct rq *rq, struct task_struct *p) 13578 { 13579 if (p->se.sched_delayed) 13580 dequeue_task(rq, p, DEQUEUE_SLEEP | DEQUEUE_DELAYED | DEQUEUE_NOCLOCK); 13581 } 13582 13583 static void switched_from_fair(struct rq *rq, struct task_struct *p) 13584 { 13585 detach_task_cfs_rq(p); 13586 } 13587 13588 static void switched_to_fair(struct rq *rq, struct task_struct *p) 13589 { 13590 WARN_ON_ONCE(p->se.sched_delayed); 13591 13592 attach_task_cfs_rq(p); 13593 13594 set_task_max_allowed_capacity(p); 13595 13596 if (task_on_rq_queued(p)) { 13597 /* 13598 * We were most likely switched from sched_rt, so 13599 * kick off the schedule if running, otherwise just see 13600 * if we can still preempt the current task. 13601 */ 13602 if (task_current_donor(rq, p)) 13603 resched_curr(rq); 13604 else 13605 wakeup_preempt(rq, p, 0); 13606 } 13607 } 13608 13609 static void __set_next_task_fair(struct rq *rq, struct task_struct *p, bool first) 13610 { 13611 struct sched_entity *se = &p->se; 13612 13613 if (task_on_rq_queued(p)) { 13614 /* 13615 * Move the next running task to the front of the list, so our 13616 * cfs_tasks list becomes MRU one. 13617 */ 13618 list_move(&se->group_node, &rq->cfs_tasks); 13619 } 13620 if (!first) 13621 return; 13622 13623 WARN_ON_ONCE(se->sched_delayed); 13624 13625 if (hrtick_enabled_fair(rq)) 13626 hrtick_start_fair(rq, p); 13627 13628 update_misfit_status(p, rq); 13629 sched_fair_update_stop_tick(rq, p); 13630 } 13631 13632 /* 13633 * Account for a task changing its policy or group. 13634 * 13635 * This routine is mostly called to set cfs_rq->curr field when a task 13636 * migrates between groups/classes. 13637 */ 13638 static void set_next_task_fair(struct rq *rq, struct task_struct *p, bool first) 13639 { 13640 struct sched_entity *se = &p->se; 13641 13642 for_each_sched_entity(se) { 13643 struct cfs_rq *cfs_rq = cfs_rq_of(se); 13644 13645 set_next_entity(cfs_rq, se, first); 13646 /* ensure bandwidth has been allocated on our new cfs_rq */ 13647 account_cfs_rq_runtime(cfs_rq, 0); 13648 } 13649 13650 __set_next_task_fair(rq, p, first); 13651 } 13652 13653 void init_cfs_rq(struct cfs_rq *cfs_rq) 13654 { 13655 cfs_rq->tasks_timeline = RB_ROOT_CACHED; 13656 cfs_rq->zero_vruntime = (u64)(-(1LL << 20)); 13657 raw_spin_lock_init(&cfs_rq->removed.lock); 13658 } 13659 13660 #ifdef CONFIG_FAIR_GROUP_SCHED 13661 static void task_change_group_fair(struct task_struct *p) 13662 { 13663 /* 13664 * We couldn't detach or attach a forked task which 13665 * hasn't been woken up by wake_up_new_task(). 13666 */ 13667 if (READ_ONCE(p->__state) == TASK_NEW) 13668 return; 13669 13670 detach_task_cfs_rq(p); 13671 13672 /* Tell se's cfs_rq has been changed -- migrated */ 13673 p->se.avg.last_update_time = 0; 13674 set_task_rq(p, task_cpu(p)); 13675 attach_task_cfs_rq(p); 13676 } 13677 13678 void free_fair_sched_group(struct task_group *tg) 13679 { 13680 int i; 13681 13682 for_each_possible_cpu(i) { 13683 if (tg->cfs_rq) 13684 kfree(tg->cfs_rq[i]); 13685 if (tg->se) 13686 kfree(tg->se[i]); 13687 } 13688 13689 kfree(tg->cfs_rq); 13690 kfree(tg->se); 13691 } 13692 13693 int alloc_fair_sched_group(struct task_group *tg, struct task_group *parent) 13694 { 13695 struct sched_entity *se; 13696 struct cfs_rq *cfs_rq; 13697 int i; 13698 13699 tg->cfs_rq = kzalloc_objs(cfs_rq, nr_cpu_ids); 13700 if (!tg->cfs_rq) 13701 goto err; 13702 tg->se = kzalloc_objs(se, nr_cpu_ids); 13703 if (!tg->se) 13704 goto err; 13705 13706 tg->shares = NICE_0_LOAD; 13707 13708 init_cfs_bandwidth(tg_cfs_bandwidth(tg), tg_cfs_bandwidth(parent)); 13709 13710 for_each_possible_cpu(i) { 13711 cfs_rq = kzalloc_node(sizeof(struct cfs_rq), 13712 GFP_KERNEL, cpu_to_node(i)); 13713 if (!cfs_rq) 13714 goto err; 13715 13716 se = kzalloc_node(sizeof(struct sched_entity_stats), 13717 GFP_KERNEL, cpu_to_node(i)); 13718 if (!se) 13719 goto err_free_rq; 13720 13721 init_cfs_rq(cfs_rq); 13722 init_tg_cfs_entry(tg, cfs_rq, se, i, parent->se[i]); 13723 init_entity_runnable_average(se); 13724 } 13725 13726 return 1; 13727 13728 err_free_rq: 13729 kfree(cfs_rq); 13730 err: 13731 return 0; 13732 } 13733 13734 void online_fair_sched_group(struct task_group *tg) 13735 { 13736 struct sched_entity *se; 13737 struct rq_flags rf; 13738 struct rq *rq; 13739 int i; 13740 13741 for_each_possible_cpu(i) { 13742 rq = cpu_rq(i); 13743 se = tg->se[i]; 13744 rq_lock_irq(rq, &rf); 13745 update_rq_clock(rq); 13746 attach_entity_cfs_rq(se); 13747 sync_throttle(tg, i); 13748 rq_unlock_irq(rq, &rf); 13749 } 13750 } 13751 13752 void unregister_fair_sched_group(struct task_group *tg) 13753 { 13754 int cpu; 13755 13756 destroy_cfs_bandwidth(tg_cfs_bandwidth(tg)); 13757 13758 for_each_possible_cpu(cpu) { 13759 struct cfs_rq *cfs_rq = tg->cfs_rq[cpu]; 13760 struct sched_entity *se = tg->se[cpu]; 13761 struct rq *rq = cpu_rq(cpu); 13762 13763 if (se) { 13764 if (se->sched_delayed) { 13765 guard(rq_lock_irqsave)(rq); 13766 if (se->sched_delayed) { 13767 update_rq_clock(rq); 13768 dequeue_entities(rq, se, DEQUEUE_SLEEP | DEQUEUE_DELAYED); 13769 } 13770 list_del_leaf_cfs_rq(cfs_rq); 13771 } 13772 remove_entity_load_avg(se); 13773 } 13774 13775 /* 13776 * Only empty task groups can be destroyed; so we can speculatively 13777 * check on_list without danger of it being re-added. 13778 */ 13779 if (cfs_rq->on_list) { 13780 guard(rq_lock_irqsave)(rq); 13781 list_del_leaf_cfs_rq(cfs_rq); 13782 } 13783 } 13784 } 13785 13786 void init_tg_cfs_entry(struct task_group *tg, struct cfs_rq *cfs_rq, 13787 struct sched_entity *se, int cpu, 13788 struct sched_entity *parent) 13789 { 13790 struct rq *rq = cpu_rq(cpu); 13791 13792 cfs_rq->tg = tg; 13793 cfs_rq->rq = rq; 13794 init_cfs_rq_runtime(cfs_rq); 13795 13796 tg->cfs_rq[cpu] = cfs_rq; 13797 tg->se[cpu] = se; 13798 13799 /* se could be NULL for root_task_group */ 13800 if (!se) 13801 return; 13802 13803 if (!parent) { 13804 se->cfs_rq = &rq->cfs; 13805 se->depth = 0; 13806 } else { 13807 se->cfs_rq = parent->my_q; 13808 se->depth = parent->depth + 1; 13809 } 13810 13811 se->my_q = cfs_rq; 13812 /* guarantee group entities always have weight */ 13813 update_load_set(&se->load, NICE_0_LOAD); 13814 se->parent = parent; 13815 } 13816 13817 static DEFINE_MUTEX(shares_mutex); 13818 13819 static int __sched_group_set_shares(struct task_group *tg, unsigned long shares) 13820 { 13821 int i; 13822 13823 lockdep_assert_held(&shares_mutex); 13824 13825 /* 13826 * We can't change the weight of the root cgroup. 13827 */ 13828 if (!tg->se[0]) 13829 return -EINVAL; 13830 13831 shares = clamp(shares, scale_load(MIN_SHARES), scale_load(MAX_SHARES)); 13832 13833 if (tg->shares == shares) 13834 return 0; 13835 13836 tg->shares = shares; 13837 for_each_possible_cpu(i) { 13838 struct rq *rq = cpu_rq(i); 13839 struct sched_entity *se = tg->se[i]; 13840 struct rq_flags rf; 13841 13842 /* Propagate contribution to hierarchy */ 13843 rq_lock_irqsave(rq, &rf); 13844 update_rq_clock(rq); 13845 for_each_sched_entity(se) { 13846 update_load_avg(cfs_rq_of(se), se, UPDATE_TG); 13847 update_cfs_group(se); 13848 } 13849 rq_unlock_irqrestore(rq, &rf); 13850 } 13851 13852 return 0; 13853 } 13854 13855 int sched_group_set_shares(struct task_group *tg, unsigned long shares) 13856 { 13857 int ret; 13858 13859 mutex_lock(&shares_mutex); 13860 if (tg_is_idle(tg)) 13861 ret = -EINVAL; 13862 else 13863 ret = __sched_group_set_shares(tg, shares); 13864 mutex_unlock(&shares_mutex); 13865 13866 return ret; 13867 } 13868 13869 int sched_group_set_idle(struct task_group *tg, long idle) 13870 { 13871 int i; 13872 13873 if (tg == &root_task_group) 13874 return -EINVAL; 13875 13876 if (idle < 0 || idle > 1) 13877 return -EINVAL; 13878 13879 mutex_lock(&shares_mutex); 13880 13881 if (tg->idle == idle) { 13882 mutex_unlock(&shares_mutex); 13883 return 0; 13884 } 13885 13886 tg->idle = idle; 13887 13888 for_each_possible_cpu(i) { 13889 struct rq *rq = cpu_rq(i); 13890 struct sched_entity *se = tg->se[i]; 13891 struct cfs_rq *grp_cfs_rq = tg->cfs_rq[i]; 13892 bool was_idle = cfs_rq_is_idle(grp_cfs_rq); 13893 long idle_task_delta; 13894 struct rq_flags rf; 13895 13896 rq_lock_irqsave(rq, &rf); 13897 13898 grp_cfs_rq->idle = idle; 13899 if (WARN_ON_ONCE(was_idle == cfs_rq_is_idle(grp_cfs_rq))) 13900 goto next_cpu; 13901 13902 idle_task_delta = grp_cfs_rq->h_nr_queued - 13903 grp_cfs_rq->h_nr_idle; 13904 if (!cfs_rq_is_idle(grp_cfs_rq)) 13905 idle_task_delta *= -1; 13906 13907 for_each_sched_entity(se) { 13908 struct cfs_rq *cfs_rq = cfs_rq_of(se); 13909 13910 if (!se->on_rq) 13911 break; 13912 13913 cfs_rq->h_nr_idle += idle_task_delta; 13914 13915 /* Already accounted at parent level and above. */ 13916 if (cfs_rq_is_idle(cfs_rq)) 13917 break; 13918 } 13919 13920 next_cpu: 13921 rq_unlock_irqrestore(rq, &rf); 13922 } 13923 13924 /* Idle groups have minimum weight. */ 13925 if (tg_is_idle(tg)) 13926 __sched_group_set_shares(tg, scale_load(WEIGHT_IDLEPRIO)); 13927 else 13928 __sched_group_set_shares(tg, NICE_0_LOAD); 13929 13930 mutex_unlock(&shares_mutex); 13931 return 0; 13932 } 13933 13934 #endif /* CONFIG_FAIR_GROUP_SCHED */ 13935 13936 13937 static unsigned int get_rr_interval_fair(struct rq *rq, struct task_struct *task) 13938 { 13939 struct sched_entity *se = &task->se; 13940 unsigned int rr_interval = 0; 13941 13942 /* 13943 * Time slice is 0 for SCHED_OTHER tasks that are on an otherwise 13944 * idle runqueue: 13945 */ 13946 if (rq->cfs.load.weight) 13947 rr_interval = NS_TO_JIFFIES(se->slice); 13948 13949 return rr_interval; 13950 } 13951 13952 /* 13953 * All the scheduling class methods: 13954 */ 13955 DEFINE_SCHED_CLASS(fair) = { 13956 .enqueue_task = enqueue_task_fair, 13957 .dequeue_task = dequeue_task_fair, 13958 .yield_task = yield_task_fair, 13959 .yield_to_task = yield_to_task_fair, 13960 13961 .wakeup_preempt = wakeup_preempt_fair, 13962 13963 .pick_task = pick_task_fair, 13964 .pick_next_task = pick_next_task_fair, 13965 .put_prev_task = put_prev_task_fair, 13966 .set_next_task = set_next_task_fair, 13967 13968 .select_task_rq = select_task_rq_fair, 13969 .migrate_task_rq = migrate_task_rq_fair, 13970 13971 .rq_online = rq_online_fair, 13972 .rq_offline = rq_offline_fair, 13973 13974 .task_dead = task_dead_fair, 13975 .set_cpus_allowed = set_cpus_allowed_fair, 13976 13977 .task_tick = task_tick_fair, 13978 .task_fork = task_fork_fair, 13979 13980 .reweight_task = reweight_task_fair, 13981 .prio_changed = prio_changed_fair, 13982 .switching_from = switching_from_fair, 13983 .switched_from = switched_from_fair, 13984 .switched_to = switched_to_fair, 13985 13986 .get_rr_interval = get_rr_interval_fair, 13987 13988 .update_curr = update_curr_fair, 13989 13990 #ifdef CONFIG_FAIR_GROUP_SCHED 13991 .task_change_group = task_change_group_fair, 13992 #endif 13993 13994 #ifdef CONFIG_SCHED_CORE 13995 .task_is_throttled = task_is_throttled_fair, 13996 #endif 13997 13998 #ifdef CONFIG_UCLAMP_TASK 13999 .uclamp_enabled = 1, 14000 #endif 14001 }; 14002 14003 void print_cfs_stats(struct seq_file *m, int cpu) 14004 { 14005 struct cfs_rq *cfs_rq, *pos; 14006 14007 rcu_read_lock(); 14008 for_each_leaf_cfs_rq_safe(cpu_rq(cpu), cfs_rq, pos) 14009 print_cfs_rq(m, cpu, cfs_rq); 14010 rcu_read_unlock(); 14011 } 14012 14013 #ifdef CONFIG_NUMA_BALANCING 14014 void show_numa_stats(struct task_struct *p, struct seq_file *m) 14015 { 14016 int node; 14017 unsigned long tsf = 0, tpf = 0, gsf = 0, gpf = 0; 14018 struct numa_group *ng; 14019 14020 rcu_read_lock(); 14021 ng = rcu_dereference_all(p->numa_group); 14022 for_each_online_node(node) { 14023 if (p->numa_faults) { 14024 tsf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 0)]; 14025 tpf = p->numa_faults[task_faults_idx(NUMA_MEM, node, 1)]; 14026 } 14027 if (ng) { 14028 gsf = ng->faults[task_faults_idx(NUMA_MEM, node, 0)], 14029 gpf = ng->faults[task_faults_idx(NUMA_MEM, node, 1)]; 14030 } 14031 print_numa_stats(m, node, tsf, tpf, gsf, gpf); 14032 } 14033 rcu_read_unlock(); 14034 } 14035 #endif /* CONFIG_NUMA_BALANCING */ 14036 14037 __init void init_sched_fair_class(void) 14038 { 14039 int i; 14040 14041 for_each_possible_cpu(i) { 14042 zalloc_cpumask_var_node(&per_cpu(load_balance_mask, i), GFP_KERNEL, cpu_to_node(i)); 14043 zalloc_cpumask_var_node(&per_cpu(select_rq_mask, i), GFP_KERNEL, cpu_to_node(i)); 14044 zalloc_cpumask_var_node(&per_cpu(should_we_balance_tmpmask, i), 14045 GFP_KERNEL, cpu_to_node(i)); 14046 14047 #ifdef CONFIG_CFS_BANDWIDTH 14048 INIT_CSD(&cpu_rq(i)->cfsb_csd, __cfsb_csd_unthrottle, cpu_rq(i)); 14049 INIT_LIST_HEAD(&cpu_rq(i)->cfsb_csd_list); 14050 #endif 14051 } 14052 14053 open_softirq(SCHED_SOFTIRQ, sched_balance_softirq); 14054 14055 #ifdef CONFIG_NO_HZ_COMMON 14056 nohz.next_balance = jiffies; 14057 nohz.next_blocked = jiffies; 14058 zalloc_cpumask_var(&nohz.idle_cpus_mask, GFP_NOWAIT); 14059 #endif 14060 } 14061