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